XRWS          œ½C  .Ç œŽ|ext_01.cat ext_01.dat aiscripts/interrupt.changedsector.xml 3218 1783040755 47a1eb797ca46eb0c5cc96df90cd016b
aiscripts/lib.gt.attention.autojump_distance_toggle.xml 1396 1781807250 78e2a0d4d8f541c89fff008dfddcdbdc
aiscripts/lib.gt.attention.emit_gt_state_changed.xml 2446 1776447298 51164633901f98c0df85f768816720ab
aiscripts/lib.gt.attention.is_gt_commander.xml 1822 1776447298 ca87c5ff3a9363ccbabe51f5b5f2d280
aiscripts/lib.gt.attention.min_player_money.xml 1575 1776447298 f46b2dce2cdbecbea477d8a85c5c55be
aiscripts/lib.gt.attention.refresh_ship_name.xml 1060 1781796047 557eb08a841c7951c33935c9b0352ecb
aiscripts/lib.gt.attention.restore_original_name.xml 3701 1776447298 579ffcf6be4e3d7fb3ced53231b600d5
aiscripts/lib.gt.blacklist.validate_lane.xml 13018 1782667004 d927fcafff9996920c60f296e0df6478
aiscripts/lib.gt.cache.score_for_ship.xml 9556 1782979742 b34587942af790e3798b35329871c225
aiscripts/lib.gt.cache.search.xml 87953 1783045730 f82756da3b748a67e8c57763e34e0c7b
aiscripts/lib.gt.cache.write.xml 29652 1782984064 1d55e042000e2ca12b702cfeb790d61f
aiscripts/lib.gt.dockcheck.xml 9950 1782452538 f573658b902e5e30200f430f45ff243a
aiscripts/lib.gt.failed_sector_pairs.xml 4141 1782667907 32cdc6d6264d7b119d858ddc8bd493d2
aiscripts/lib.gt.fallback.search.xml 13336 1782920837 6a2f1f26b0d991ab516507a3387d963a
aiscripts/lib.gt.idlepark.xml 11893 1782451572 a81db4721d6753b351b165de7f7210dd
aiscripts/lib.gt.live.search.xml 143859 1782989108 dcb6cc3c53907a16eb268f408a43ea52
aiscripts/lib.gt.miner_find_target.xml 12453 1782750779 e06ebb200b92cef036da7dcc41c9f1b3
aiscripts/lib.gt.miner_physical_storage_gate.xml 16838 1782353858 0dfa2e8657355b5b745e6ab75a19b83b
aiscripts/lib.gt.miner_same_fleet.xml 2762 1782353451 d6c344e49f64e14590774c27572e2f62
aiscripts/lib.gt.mk42.cache.search.xml 85018 1783028283 54ad8bbb6b4d8327cb150447de7cad75
aiscripts/lib.gt.mk42.cache.write.xml 17547 1782977071 5e8ad48316102fbd0c63bec70e1ddd81
aiscripts/lib.gt.mk42.classify.xml 3166 1782588086 d62740b6b2e48bd958d53f090354d73d
aiscripts/lib.gt.mk42.live.search.xml 169680 1783040119 a60897ccb9f0f510eca2d60a31a24f04
aiscripts/lib.gt.mk42.offer.filters.xml 3143 1782581787 c31e7b2a213dc963e8b4056f045b43dc
aiscripts/lib.gt.mk42.player.stations.xml 5229 1783039905 ddee25d4b3f9b19816b0efaf578149ce
aiscripts/lib.gt.mk42.policy.resolve.xml 5545 1782626504 ed92efac690f3c7920436ae10d7f393d
aiscripts/lib.gt.mk42.score.trades.xml 14388 1783038837 e92aa0e4da7c72c90cc23cdc32178133
aiscripts/lib.gt.mk42.tradematch.xml 109400 1783036081 e09a49a03163f4095dcaff71ae344132
aiscripts/lib.gt.offer.filters.xml 3569 1782334519 6411a52530be20882af0781e1a7a6b5e
aiscripts/lib.gt.pathfinding.xml 40214 1782329294 db6c365115ed053b810061472b75fc23
aiscripts/lib.gt.priority_wares.resolve.xml 2782 1776447298 076d08e7e39dbb41e1eac7fd400ce8e8
aiscripts/lib.gt.score.selection_sort.xml 4349 1782984127 0552a07aec096c274c53ff87ed255b37
aiscripts/lib.gt.score.trades.xml 9769 1782984050 7815a5fb52a480add55727b681fdcb69
aiscripts/lib.gt.tradematch.xml 78998 1782976993 1d441bc4a4ee1c1fc617fa35a9e9903f
aiscripts/lib.request.orders.xml 3306 1771087358 f89d84ef6e56714238c90774ce13dbc9
aiscripts/move.generic.xml 54388 1782749684 2cf5f2f182b10a4b5c58100f75cbf53b
aiscripts/order.assist.xml 188610 1782830719 78118a18176fd3924e435a16848903ad
aiscripts/order.build.equip.xml 8940 1782660988 12ed4358427866193eab53421de0c8c4
aiscripts/order.dock.pilotexchange.xml 7232 1775504225 8cd2f202c2b6ea5326e2745a13d2f51e
aiscripts/order.dock.train.xml 24439 1782785954 1e722e24c34fdb8a13edf220e4cf8979
aiscripts/order.dock.xml 2673 1767563959 c65a428f9b27d6647086cb17f6d3cada
aiscripts/order.gt.idlepark.xml 11252 1782411713 93bbf2ed2c239945945dafca2f44e78d
aiscripts/order.gt.returnhome.xml 5606 1782451573 f230e525fea1cb7d5e4e28ddbca159dd
aiscripts/order.mining.routine.gt.xml 121726 1783046680 439fc895062a5902977ef46dc45c4b39
aiscripts/order.repair.xml 1551 1767563959 1b164d8267aa697334bba17b25990067
aiscripts/order.restock.xml 10817 1782660986 fbd032c721fa07f61d4d21e56e00554f
aiscripts/order.trade.galaxyminer.xml 222037 1782820761 6d5ca2ee14722389938040d9a7d5af2a
aiscripts/order.trade.galaxytrader.xml 633208 1782990314 5bf65ab8abdbb6f86403430a067e4b8a
aiscripts/order.trade.galaxytradermk1.xml 176506 1782937197 e125c1c55104f3fbf9a3cce52dddd83d
aiscripts/order.trade.galaxytradermk2.xml 204025 1782847333 42b6222034849a38b21921ba6ab85e0a
aiscripts/order.trade.galaxytradermk4.xml 874130 1782921393 62cafe0a2ab4354dc34ac2d9ae61f920
aiscripts/order.trade.galaxytradermk42.xml 889408 1783039245 5701c5873e6e09a228e10505ecf85db8
aiscripts/order.trade.perform.xml 42376 1782903195 c74c56250f67c02291a1f3e7091cc0e2
aiscripts/order.wait.xml 15186 1782661000 96a2fc35712b155314d7576d3758011c
aiscripts/orders.base.xml 3599 1782769516 ae6a5f51dfb9238a7004d3acbf6f6e86
assets/fx/gui/textures/button_ordericons/order_galaxytradermk3.dds 418 1760972561 2dfaeaaeae25c4a608c0abc252636818
CHANGELOG.txt 129692 1783046968 bac670cb779ff30b12cb27dc49a954f3
content.xml 1291 1783097577 9b10b4370fe2497908e53adcc296eb89
libraries/equipmentmods.xml 4653 1767563959 30a7fa536664046bc8cc0012cac6e6dd
libraries/icons.xml 1513 1782586580 bb519a78e6f635c0523ecc7bf72c9ddc
libraries/wares.xml 6796 1775320667 b3680a54594f3951c699a7da891eea27
LICENSE.md 1639 1760972561 014defcbadaf8b1bac7b063c1dbaf10b
md/glx_lib_cache.xml 31209 1782394441 1e1b2ece4d1217af6dc11d4ac7fb209c
md/glx_lib_orders.xml 1374 1775504225 4e788ea7cabfeb26cce2bec7a8854d67
md/glx_lib_reservations.xml 39820 1775504225 9c5941375fe573949169536f146ffa14
md/glx_lib_settings_menu.xml 254217 1782930773 a13fe5c2c7b5425585234346bae7fac5
md/glx_lib_trading_log.xml 5927 1775504225 53da428024a3f083bb66448c697cb0f3
md/gt_blacklist_loader.xml 465 1781809401 538ff60bedc30bb728678991e4ecea9c
md/gt_buy_tracking.xml 12003 1782990290 09eb3ddce9796a27e74c117bcfcfdf99
md/gt_cheats.xml 13694 1782842051 492ffa9231f85e8bbdaf2823c501dd10
md/gt_configuration.xml 83832 1783097577 b6a57a91ccc763bc14c325a4f9efc0d9
md/gt_context_academy.xml 16695 1782022898 f388a8f1b6ba24d96a81b54efcc4a502
md/gt_context_diagnose.xml 634115 1783037503 9ae625685755dcad37fc0db2d671c462
md/gt_context_redistribute.xml 58504 1782451713 1034af2d5b03d07c45b31ff65fa3d738
md/gt_context_rename.xml 19429 1775504225 c5a914977f83a8a280c97d778084a3d1
md/gt_core_system.xml 313420 1782768540 c579493c34214ad08caa0648731021ca
md/gt_debug.xml 13545 1775504225 4b2d850a043776e4f9c32c85fabd9079
md/gt_fleet_coordination.xml 10738 1782394420 616464bfb065d7ab449e75032b8c5e64
md/gt_fleet_replacement.xml 4141 1776719010 70fe0b91f4c92971162552bc533289eb
md/gt_global_settings.xml 85523 1782903195 a803813cff69a10c61a4fad8b708d696
md/gt_home_fleet_profile.xml 10105 1782971873 7554b9a9d513f6a4d1ffb8fb57397a0f
md/gt_info_menu_loader.xml 31272 1776092910 06a19c0fd1b68a6dfeffdf5f4c0bc1ac
md/gt_libraries_blacklist.xml 73402 1781809401 311bc74af7831bfdbbdc946c2b32f144
md/gt_libraries_distribution.xml 4641 1775504225 0bc063e453e612078dbcb0050f6673ee
md/gt_libraries_general.xml 284601 1782976965 f9f3edb986e4e34255e7234d56278492
md/gt_libraries_pathfinding.xml 99222 1781907862 5e34cdee06a13b52b8e8750d1625f64c
md/gt_libraries_station_trader.xml 14227 1775504225 a961bd98fc512362ba03382d6d38dced
md/gt_maintenance.xml 200500 1782621995 d8983580babc63d8add651a229556cb4
md/gt_market_intelligence.xml 32954 1775504225 5c8acb2f659c7383d3df0b3006a780be
md/gt_mk1_global_settings.xml 9625 1775504225 255880e156fda30506bedce5fee91d13
md/gt_mk2_global_settings.xml 8413 1775504225 98bb2d8a0682e1397ac14fc093d4de58
md/gt_mk3_faction_blacklist.xml 12127 1775504225 9d1f0bd6577b0f89767b70010d6fe0f2
md/gt_order_monitor_bridge.xml 34180 1782667216 7b148b974518220063f7c5f87714f7a1
md/gt_pilot_field_migration.xml 8930 1782329295 807d618a6f77d7204639a36d9c4f0f72
md/gt_pilot_promotion.xml 26080 1775504225 851adedaf88d215ce4bb1ae05d3a190a
md/gt_profit_migration.xml 6486 1775504225 23e96f3a376110bc3d80f58752de8745
md/gt_reporting.xml 33135 1775504225 d41c8e858d130758872d5ab0523f00ce
md/gt_ship_management.xml 200371 1782768542 d634ede73cb2546ee527ce5d540356e0
md/gt_ship_modifications.xml 101567 1776169874 96462dc48b6786581b71260c64b17fbf
md/gt_ship_naming_pattern.xml 37383 1781796047 953caa9d37eee938c5abf4e1faef43b0
md/gt_ship_performance_system.xml 14269 1775504225 c37ccfa75d35996cd931beb9f969c39f
md/gt_ship_state_manager.xml 66776 1782329295 9961b8d04026a22c8e3ff8776204f871
md/gt_ship_state_utilities.xml 28175 1776085179 f64310b5a5da0b3a401fe293d9703d60
md/gt_territory_management.xml 15879 1775504225 dc50053054d9adce95c1484711a15101
md/gt_threat_intelligence.xml 112821 1782750152 d7d0206023fa3adf892c60e57c0c4a5c
md/gt_trade_logging.xml 78421 1782938087 7b123997508159a7a8378d322af1564d
md/gt_tradesearch_scheduler.xml 230125 1783031817 f653a14ed9bfde89393c6a046c285158
md/gt_tradesearch_scheduler_mk42.xml 33826 1783031819 f38c2313c0db0badc0f63c970d0ed8ba
md/gt_trading_ai.xml 58783 1782667885 df4fad8474ec394b2bd7a50359d862c9
md/gt_trading_execution.xml 31154 1782903195 b25e8cc8a42afd1e538df668d43e8e55
md/gt_trading_signals.xml 32755 1782903195 0136bf1084c93120bc0af6bcf8964c8b
md/gt_ware_filter.xml 33183 1775504225 8d6d8888c4afdeb2e8046d36704deab1
md/gt_xp_training.xml 165577 1782784985 a3212cb25bdc2cd4a4efbc6300110a30
README.txt 473 1777271882 b386ce15cb38a3d3b0f4c6aed5e962cf
reports/summary.json 4357 1775690386 453d4d0e6582fe37dd8f997a1be33d33
reports/validation_report.txt 344 1775690386 b9e25c9b98cfefd53b04b2ef0d67b972
t/0001-l007.xml 141687 1782931438 7fff680e9de847c98ac2a54a6c122fb6
t/0001-l033.xml 97695 1782931438 de33f23be2237f821d8984676f64a2c3
t/0001-l034.xml 93736 1782931438 0cf80bc7ba7ec12582104fa696fe6437
t/0001-l039.xml 92808 1782931438 e3f58ac8b6c218c2a57b469c5a94c29b
t/0001-l042.xml 89006 1782931438 aa079ac8d8e4996ae78297cb67304e0a
t/0001-l044.xml 82601 1782930775 2a1d60371618f54ca645e9969bd1a542
t/0001-l048.xml 93270 1782931438 6be46dc194428c77d01a3d42a7157743
t/0001-l049.xml 90231 1782931438 796ae1a4aabc870d747f87c680bd325a
t/0001-l055.xml 92300 1782931438 7c87ed502d40b5083a056299b141b1e3
t/0001-l081.xml 103903 1782931438 0ae872eeddaa09e5772da076bbc099b2
t/0001-l082.xml 89205 1782931438 82883a795521ea008fb6d231f118d04c
t/0001-l086.xml 74565 1782931438 d8b7b62577ebb90fbbb83e435ee3d645
t/0001-l088.xml 75110 1782931438 164bc65417672cdb5bb08f87dfe8cdea
t/0001-l090.xml 89989 1782931438 20c7bf7ce9561723aae30d74107afc6e
t/0001-l359.xml 144450 1782931438 3390903e094212db80eb12f5b93c6a8b
t/0001-l380.xml 140608 1782931438 665c5f1c4f76ef23f996a5a3b493e97f
ui.xml 1440 1782819091 48f033f79c38c66d8e32d5ddfea0ec0d
ui/gt_blacklist_manager.lua 36461 1782749875 d6079a6fb92d413a71731e4f69b3a53d
ui/gt_context_academy.lua 19164 1776779556 f19ae82abee54ee64e1fdf925492ed61
ui/gt_context_diagnose.lua 25248 1782329295 e29d10a92e063ced6d206bbb2854a3ea
ui/gt_context_promote.lua 42713 1776082412 6cb0275527e29e3842bbaec7a724d7fd
ui/gt_context_redistribute.lua 48142 1776218926 71f84d73f6857d5bbcc86079b8f9ef0f
ui/gt_context_rename.lua 15240 1774267347 2dd1ef6acde91b4095fb27280bec1e0d
ui/gt_credits_due_override.lua 8648 1773950481 bdda94ab9136cf46c079ec110955af17
ui/gt_crew_name_highlight.lua 12585 1776218926 91c23ed26bb4ac6c364411e79b40b479
ui/gt_info_menu.lua 43265 1773950481 fda2ad03e54b251ccd7f2b562300b71b
ui/gt_mk2_ware_exchange.lua 11853 1782329295 12701df92cd09ac75553c212dca348ce
ui/gt_mk3_faction_blacklist.lua 5776 1772810993 38a6bb35bed7a1bd80853e1eccf40d8d
ui/gt_mod_removal.lua 16104 1776161810 583ce002f4fad9f00fec642c1f73a73c
ui/gt_order_monitor.lua 12111 1774189945 c1b57386135621a98b6824e8c785c2ca
ui/gt_personnel_name_override.lua 4349 1776092920 296dcf67c1e72b19a2f0df671b1110da
ui/gt_pilot_control_bridge.lua 5166 1771491795 5bf8261cac8e6deba03d44ec115865bd
ui/gt_pilot_data_bridge.lua 24287 1776092899 bc4b97cbabaacde78a204b9e26ef6c1f
ui/gt_subordinate_access.lua 3877 1782573036 70c1f5edee662d00fb2d2be99402ed79
ui/gt_ui_library.lua 27266 1776742467 cc15dcd12892f5d67b22f971727c961a
<?xml version="1.0" encoding="utf-8"?>
<!-- GT override: vanilla set $changedsector_previoussector with chance=@$debugchance but debug_text
     rolls chance again â€” with GT debuglevel=1 (debugchance=50) Property lookup failed is common. -->
<aiscript name="interrupt.changedsector" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" priority="11">
  <interrupts>
    <library>
      <handler name="SectorChangeHandler">
        <conditions>
          <check_any>
            <!-- remember that event_object_changed_sector happens AFTER changing sectors while these two happen upon entering either an anomaly or a gate. -->
            <event_object_entered_anomaly object="this.ship"/>
            <event_object_entered_gate object="this.ship"/>
          </check_any>
        </conditions>
        <actions>
          <!-- NB: $nextsector is set in move.generic right before calling move.gate and is cleared immediately after. -->
          <!-- NB: $pathsectors set in move.autopilot -->
          <do_if value="(not @$nextsector or ($nextsector != event.param2.sector)) and (not @$pathsectors.count or not $pathsectors.indexof.{event.param2.sector})">
            <set_value name="$changedsector_newsector" exact="event.param2.sector"/>
            <set_value name="$changedsector_previoussector" exact="event.param.sector"/>
            <set_value name="$changedsector_reset"/>

            <do_if value="this.ship.isplayerowned">
              <set_known object="event.param" known="true"/>
              <set_known object="event.param2" known="true"/>
              <set_known object="$changedsector_newsector" known="true"/>
              <set_known object="$changedsector_newsector.cluster" known="true"/>
            </do_if>

            <do_if value="@$debugchance">
              <do_if value="event.name == 'event_object_entered_anomaly'">
                <set_value name="$changedsector_eventstring" exact="'entered an anomaly'"/>
              </do_if>
              <do_elseif value="event.name == 'event_object_entered_gate'">
                <set_value name="$changedsector_eventstring" exact="'entered a gate'"/>
              </do_elseif>
              <do_elseif value="event.name == 'event_object_changed_sector'">
                <set_value name="$changedsector_eventstring" exact="'changed sectors'"/>
              </do_elseif>

              <debug_text text="'%s %s %s %s from %s to %s.'.[this.ship.idcode, this.ship.knownname, this.ship, @$changedsector_eventstring, @$changedsector_previoussector.knownname, @$changedsector_newsector.knownname]"/>
              <remove_value name="$changedsector_eventstring"/>
            </do_if>
            <remove_value name="$changedsector_previoussector"/>
            <remove_value name="$changedsector_newsector"/>

            <do_if value="$changedsector_reset?">
              <remove_value name="$changedsector_reset"/>
              <abort_called_scripts resume="start"/>
            </do_if>
          </do_if>
        </actions>
      </handler>
    </library>
  </interrupts>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.attention.autojump_distance_toggle" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Detects false -> true transition on autoJumpDistanceByLevel and signals MD for one-shot tier-max sync.
    Save-load baseline is set via per-order script patch (this.$prevAutoJumpDistance) so existing
    enabled orders do not sync on first main-loop tick after load.
  -->
  <params>
    <param name="autoJumpDistanceByLevel" default="false"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="not $autoJumpDistanceByLevel?">
        <set_value name="$autoJumpDistanceByLevel" exact="false"/>
      </do_if>

      <do_if value="not this.$prevAutoJumpDistance?">
        <set_value name="this.$prevAutoJumpDistance" exact="$autoJumpDistanceByLevel"/>
      </do_if>
      <do_elseif value="$autoJumpDistanceByLevel and not this.$prevAutoJumpDistance">
        <signal_objects object="player.galaxy" param="'GT_AutoJumpDistance_Apply'" param2="table[
          $Ship = this.ship,
          $Reason = 'checkbox_enabled'
        ]"/>
      </do_elseif>
      <set_value name="this.$prevAutoJumpDistance" exact="$autoJumpDistanceByLevel"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.attention.emit_gt_state_changed" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Fires the matched pair of state-change signals that every GT order
    assignment / cancellation site emits:
      1) `GT_Ship_State_Update`         (UI / fleet-roster MD listener)
      2) `GT_Commander_GT_State_Changed`(commander-graph MD listener)

    Both signals carry the ship as the affected entity, the boolean
    `IsGTActive` flag, the current subordinate count snapshot, and a free-form
    `source` tag so MD-side traces can attribute each emission to the AI
    site that produced it.

    Replaces 4 inline emit pairs in MK3 init / main_loop (`AI_INIT_ASSIGN`,
    `AI_INIT_REASSIGN`, `AI_LOOP_REASSIGN`, `AI_LOOP_CANCEL`) and 4 more in
    MK4. The payloads are byte-identical aside from the `source` string,
    making this the highest-payoff dedup of the attention-lifecycle group.
    See DOCS/MK3_PIPELINE_REFACTOR.md Â§3.11.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="isGTActive" default="true"/>
    <param name="source" default="'AI_UNSPECIFIED'"/>
    <param name="updateType" default="if $isGTActive then 'GT_Order_Assigned' else 'GT_Order_Cancelled'"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="not $ship? or not @$ship.exists">
        <return/>
      </do_if>

      <set_value name="$subordinateCount" exact="if $ship.allsubordinates? then @$ship.allsubordinates.count else 0"/>

      <do_if value="$isGTActive">
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = $ship,
          $UpdateType = $updateType,
          $MacroShipName = @$ship.macro.name
        ]"/>
      </do_if>
      <do_else>
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = $ship,
          $UpdateType = $updateType
        ]"/>
      </do_else>

      <signal_objects object="player.galaxy" param="'GT_Commander_GT_State_Changed'" param2="table[
        $Commander = $ship,
        $IsGTActive = $isGTActive,
        $SubordinateCount = $subordinateCount,
        $Source = $source
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.attention.is_gt_commander" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Returns `true` if `commander` is a GalaxyTrader-controlled commander, i.e.
    its `defaultorder.id` matches one of `validOrderIds`, OR it is running the
    vanilla `Assist` order over a GalaxyTrader baseorder (whose id matches
    `validOrderIds`). Returns `false` for `null`, deleted, or non-GT commanders.

    The (`order == X` OR (`order == 'Assist'` AND `baseorder == X`)) check was
    copy-pasted ~9 times across `init`, `main_loop`, the Phase 6 commander-delta
    branches, the subordinate orphan check, and Phase 7 name-restoration logic
    in MK3 (and again in MK4 with `'GalaxyTraderMK4Supply'` added). Centralizing
    here also guarantees that future GalaxyTrader order variants only need to
    extend `validOrderIds` in one place. See DOCS/MK3_PIPELINE_REFACTOR.md Â§3.11.
  -->
  <params>
    <param name="commander" default="null"/>
    <param name="validOrderIds" default="['GalaxyTraderMK3']"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="$commander? and @$commander.exists and $commander.defaultorder?">
        <do_if value="$validOrderIds? and $validOrderIds.indexof.{@$commander.defaultorder.id}">
          <return value="true"/>
        </do_if>
        <do_if value="@$commander.defaultorder.id == 'Assist' and $commander.defaultorder.$baseorder? and $validOrderIds? and $validOrderIds.indexof.{@$commander.defaultorder.$baseorder.id}">
          <return value="true"/>
        </do_if>
      </do_if>
      <return value="false"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.attention.min_player_money" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Resolves the effective `MinPlayerMoney` setting (in credits) used by every
    money-gate and the authoritative budget guard.

    Read order:
      1) `global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney` (when present and > 0)
      2) Fallback to 1000 (the historical default if settings are not yet populated)

    Replaces ~10 inline `do_if value="not this.$minPlayerMoney?"` resolve blocks
    that were copy-pasted across `init`, `main_loop`, the early-money-gate region,
    `trade_found` fast-money short-circuit, the budget clamp, and the logbook â€”
    each of which redid the same `?-and-!=null-and-gt 0` triple guard against the
    same global. See DOCS/MK3_PIPELINE_REFACTOR.md Â§3.11.
  -->
  <attention min="unknown">
    <actions>
      <set_value name="$resolved" exact="1000"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney?">
        <set_value name="$tmpMinMoney" exact="@global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney"/>
        <do_if value="$tmpMinMoney? and $tmpMinMoney != null and $tmpMinMoney gt 0">
          <set_value name="$resolved" exact="$tmpMinMoney"/>
        </do_if>
      </do_if>
      <return value="$resolved"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.attention.refresh_ship_name" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Requests an MD-side ship name refresh via GT_Refresh_Ship_Name.
    Main-loop call site for all GT service orders (MK1/MK2/MK3/MK4/Miner).
    MD applies content dedupe ($LastResolvedShipName) before set_object_name.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="nameType" default="'trader'"/>
    <param name="force" default="false"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="not $ship? or not @$ship.exists">
        <return value="false"/>
      </do_if>

      <signal_objects object="player.galaxy" param="'GT_Refresh_Ship_Name'" param2="table[
        $Ship = $ship,
        $nameType = $nameType,
        $force = $force
      ]"/>
      <return value="true"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.attention.restore_original_name" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Emits `GT_Ship_Order_Aborted` with the pilot's `$OriginalShipName` payload
    so the MD-side name-restoration handler can revert the ship's GT-flavored
    name back to the player's original.

    No-ops (returns `false`) when:
      - ship has no pilot
      - pilot is not tracked in `global.$GT_Pilots`
      - pilot has no `$OriginalShipName` recorded
      - ship is still GT-controlled directly OR via a GT commander (caller
        decides via `skipIfStillGT`; when true, the GT-controlled check is
        applied here using lib.gt.attention.is_gt_commander)

    Returns `true` if the signal was emitted, `false` otherwise.

    Replaces 3 near-identical inline blocks in MK3 init / main_loop / Phase 7,
    and 3 more in MK4. Each duplicated the GT_Pilots lookup, OriginalShipName
    extraction, and signal_objects payload. See DOCS/MK3_PIPELINE_REFACTOR.md Â§3.11.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="reason" default="'GT order cancelled - restoring original name'"/>
    <param name="skipIfStillGT" default="true"/>
    <param name="validOrderIds" default="['GalaxyTraderMK3']"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="not $ship? or not @$ship.exists or not $ship.pilot?">
        <return value="false"/>
      </do_if>

      <!-- Optional safety: don't restore the name if the ship is still GT-controlled
           (either via direct order or via a GT commander). The caller pre-decides
           this in some sites, but doing it here too keeps every call site honest. -->
      <do_if value="$skipIfStillGT">
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <do_if value="$ship.defaultorder? and $validOrderIds? and $validOrderIds.indexof.{@$ship.defaultorder.id}">
          <set_value name="$hasDirectGTOrder" exact="true"/>
        </do_if>
        <do_if value="$hasDirectGTOrder">
          <return value="false"/>
        </do_if>
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <run_script name="'lib.gt.attention.is_gt_commander'" result="$cmdrIsGT">
            <param name="commander" value="$ship.commander"/>
            <param name="validOrderIds" value="$validOrderIds"/>
          </run_script>
          <do_if value="$cmdrIsGT">
            <return value="false"/>
          </do_if>
        </do_if>
      </do_if>

      <do_if value="not global.$GT_Pilots? or not global.$GT_Pilots.{$ship.pilot}? or not global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
        <return value="false"/>
      </do_if>
      <set_value name="$originalName" exact="global.$GT_Pilots.{$ship.pilot}.$OriginalShipName"/>
      <do_if value="not $originalName? or $originalName == null">
        <return value="false"/>
      </do_if>

      <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
        $Ship = $ship,
        $Pilot = $ship.pilot,
        $Reason = $reason,
        $OriginalName = $originalName
      ]"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] Name restoration signal sent for ' + $ship.idcode + ' (reason: ' + $reason + ', original name: ' + $originalName + ')'" chance="100"/>
      </do_if>
      <return value="true"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.blacklist.validate_lane" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    MK2/MK1 lane blacklist preflight (parity with MK3 trade_found partner checks).
    buyStation = pickup source; sellStation = delivery destination.
    Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted).
    Escape: selling from a blacklisted sector the ship is already in is allowed unless the station is object-blacklisted.
    sellOnly: cargo clearance / sell-only leg - skips buy partner checks; path is ship -> sellStation only.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="buyStation" default="null"/>
    <param name="sellStation" default="null"/>
    <param name="blacklistGroup" default="null"/>
    <param name="sectorWhitelist" default="[]"/>
    <param name="checkThreat" default="true"/>
    <param name="checkPath" default="false"/>
    <param name="sellOnly" default="false"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="$yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <set_value name="$result" exact="table[$Blocked = false, $Reason = '', $Leg = '']"/>
      <set_value name="$resolvedBlacklistGroup" exact="$blacklistGroup"/>
      <do_if value="not $resolvedBlacklistGroup? or $resolvedBlacklistGroup == null">
        <set_value name="$resolvedBlacklistGroup" exact="blacklistgroup.civilian"/>
        <do_if value="(@$ship.primarypurpose == purpose.fight) or (@$ship.primarypurpose == purpose.auxiliary)">
          <set_value name="$resolvedBlacklistGroup" exact="blacklistgroup.military"/>
        </do_if>
      </do_if>

      <set_value name="$validationWhitelist" exact="[]"/>
      <do_if value="$sectorWhitelist? and $sectorWhitelist != null and $sectorWhitelist.count gt 0">
        <set_value name="$validationWhitelist" exact="$sectorWhitelist"/>
      </do_if>

      <do_if value="$sellOnly">
        <do_if value="not $sellStation? or not $sellStation.exists">
          <set_value name="$result.$Blocked" exact="true"/>
          <set_value name="$result.$Reason" exact="'invalid_station'"/>
          <set_value name="$result.$Leg" exact="'station'"/>
          <wait exact="$yieldMs * 1ms"/>
          <return value="$result"/>
        </do_if>
      </do_if>
      <do_else>
        <do_if value="not $buyStation? or not $buyStation.exists or not $sellStation? or not $sellStation.exists">
          <set_value name="$result.$Blocked" exact="true"/>
          <set_value name="$result.$Reason" exact="'invalid_station'"/>
          <set_value name="$result.$Leg" exact="'station'"/>
          <wait exact="$yieldMs * 1ms"/>
          <return value="$result"/>
        </do_if>
      </do_else>

      <set_value name="$currentSector" exact="$ship.sector"/>
      <set_value name="$buySector" exact="if $sellOnly then null else $buyStation.sector"/>
      <set_value name="$sellSector" exact="$sellStation.sector"/>

      <!-- GT dynamic threat sectors (both legs) -->
      <do_if value="$checkThreat and global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.$BlacklistedSectors? and global.$GT_ThreatIntelligence.$BlacklistedSectors.count gt 0">
        <do_all exact="global.$GT_ThreatIntelligence.$BlacklistedSectors.count" counter="$bli">
          <set_value name="$threatSector" exact="global.$GT_ThreatIntelligence.$BlacklistedSectors.{$bli}"/>
          <do_if value="($sellOnly and $threatSector == $sellSector) or (not $sellOnly and ($threatSector == $buySector or $threatSector == $sellSector))">
            <set_value name="$sectorWhitelisted" exact="false"/>
            <do_if value="$validationWhitelist.count gt 0">
              <do_all exact="$validationWhitelist.count" counter="$swi">
                <do_if value="$validationWhitelist.{$swi} == $threatSector">
                  <set_value name="$sectorWhitelisted" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $sectorWhitelisted">
              <set_value name="$result.$Blocked" exact="true"/>
              <set_value name="$result.$Reason" exact="'threat_sector'"/>
              <set_value name="$result.$Leg" exact="if $sellOnly or $threatSector == $sellSector then 'sell_threat' else 'buy_threat'"/>
              <wait exact="$yieldMs * 1ms"/>
              <return value="$result"/>
            </do_if>
          </do_if>
        </do_all>
      </do_if>

      <!-- BUY partner blacklist (distribution legs only) -->
      <do_if value="not $sellOnly">
        <set_value name="$buyBlacklisted" exact="false"/>
        <set_value name="$buyStationBlacklisted" exact="@$buyStation.isblacklisted.{blacklisttype.objectactivity}.{$resolvedBlacklistGroup}.{$ship}"/>
        <set_value name="$buySectorWhitelisted" exact="false"/>
        <do_if value="$validationWhitelist.count gt 0">
          <do_all exact="$validationWhitelist.count" counter="$swIdx">
            <do_if value="$validationWhitelist.{$swIdx} == $buySector">
              <set_value name="$buySectorWhitelisted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <set_value name="$buySectorActivityBlacklisted" exact="false"/>
        <set_value name="$buySectorTravelBlacklisted" exact="false"/>
        <do_if value="not $buySectorWhitelisted">
          <set_value name="$buySectorActivityBlacklisted" exact="@$buySector.isblacklisted.{blacklisttype.sectoractivity}.{$resolvedBlacklistGroup}.{$ship}"/>
          <set_value name="$buySectorTravelBlacklisted" exact="@$buySector.isblacklisted.{blacklisttype.sectortravel}.{$resolvedBlacklistGroup}.{$ship}"/>
        </do_if>
        <do_if value="$buySectorActivityBlacklisted or $buySectorTravelBlacklisted">
          <set_value name="$buyBlacklisted" exact="true"/>
        </do_if>
        <do_else>
          <set_value name="$buyBlacklisted" exact="$buyStationBlacklisted"/>
        </do_else>
        <do_if value="$buyBlacklisted">
          <set_value name="$result.$Blocked" exact="true"/>
          <set_value name="$result.$Reason" exact="'buy_blacklisted'"/>
          <set_value name="$result.$Leg" exact="'buy'"/>
          <wait exact="$yieldMs * 1ms"/>
          <return value="$result"/>
        </do_if>
      </do_if>

      <!-- SELL partner blacklist (escape-aware) -->
      <set_value name="$sellBlacklisted" exact="false"/>
      <set_value name="$sellStationBlacklisted" exact="@$sellStation.isblacklisted.{blacklisttype.objectactivity}.{$resolvedBlacklistGroup}.{$ship}"/>
      <set_value name="$sellSectorWhitelisted" exact="false"/>
      <do_if value="$validationWhitelist.count gt 0">
        <do_all exact="$validationWhitelist.count" counter="$swIdx">
          <do_if value="$validationWhitelist.{$swIdx} == $sellSector">
            <set_value name="$sellSectorWhitelisted" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      <set_value name="$sellSectorActivityBlacklisted" exact="false"/>
      <set_value name="$sellSectorTravelBlacklisted" exact="false"/>
      <do_if value="not $sellSectorWhitelisted">
        <set_value name="$sellSectorActivityBlacklisted" exact="@$sellSector.isblacklisted.{blacklisttype.sectoractivity}.{$resolvedBlacklistGroup}.{$ship}"/>
        <set_value name="$sellSectorTravelBlacklisted" exact="@$sellSector.isblacklisted.{blacklisttype.sectortravel}.{$resolvedBlacklistGroup}.{$ship}"/>
      </do_if>
      <do_if value="$sellSectorActivityBlacklisted or $sellSectorTravelBlacklisted">
        <do_if value="$sellSector == $currentSector">
          <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
        </do_if>
        <do_else>
          <set_value name="$sellBlacklisted" exact="true"/>
        </do_else>
      </do_if>
      <do_else>
        <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
      </do_else>
      <do_if value="$sellBlacklisted">
        <set_value name="$result.$Blocked" exact="true"/>
        <set_value name="$result.$Reason" exact="'sell_blacklisted'"/>
        <set_value name="$result.$Leg" exact="'sell'"/>
        <wait exact="$yieldMs * 1ms"/>
        <return value="$result"/>
      </do_if>

      <!-- Optional blacklist-aware path reachability -->
      <do_if value="$checkPath">
        <set_value name="$currentSectorIsBlacklisted" exact="false"/>
        <set_value name="$currentSectorWhitelisted" exact="false"/>
        <do_if value="$validationWhitelist.count gt 0">
          <do_all exact="$validationWhitelist.count" counter="$swIdx">
            <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
              <set_value name="$currentSectorWhitelisted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $currentSectorWhitelisted">
          <set_value name="$curActBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$resolvedBlacklistGroup}.{$ship}"/>
          <set_value name="$curTrvBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$resolvedBlacklistGroup}.{$ship}"/>
          <set_value name="$currentSectorIsBlacklisted" exact="$curActBL or $curTrvBL"/>
        </do_if>

        <do_if value="$sellOnly">
          <set_value name="$sellDistance" exact="-1"/>
          <do_if value="$sellSector == $currentSector">
            <set_value name="$sellDistance" exact="0"/>
          </do_if>
          <do_elseif value="$currentSectorIsBlacklisted">
            <set_value name="$sellDistance" exact="$ship.gatedistance.{$sellSector}"/>
          </do_elseif>
          <do_else>
            <set_value name="$sellDistance" exact="$ship.gatedistance.{$sellSector}.{$resolvedBlacklistGroup}.{$ship}"/>
          </do_else>
          <do_if value="$sellDistance lt 0">
            <set_value name="$result.$Blocked" exact="true"/>
            <set_value name="$result.$Reason" exact="'path_sell'"/>
            <set_value name="$result.$Leg" exact="'path'"/>
            <wait exact="$yieldMs * 1ms"/>
            <return value="$result"/>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$buyDistance" exact="-1"/>
          <do_if value="$buySector == $currentSector">
            <set_value name="$buyDistance" exact="0"/>
          </do_if>
          <do_elseif value="$currentSectorIsBlacklisted">
            <set_value name="$buyDistance" exact="$ship.gatedistance.{$buySector}"/>
          </do_elseif>
          <do_else>
            <set_value name="$buyDistance" exact="$ship.gatedistance.{$buySector}.{$resolvedBlacklistGroup}.{$ship}"/>
          </do_else>
          <do_if value="$buyDistance lt 0">
            <set_value name="$result.$Blocked" exact="true"/>
            <set_value name="$result.$Reason" exact="'path_buy'"/>
            <set_value name="$result.$Leg" exact="'path'"/>
            <wait exact="$yieldMs * 1ms"/>
            <return value="$result"/>
          </do_if>

          <set_value name="$sellDistance" exact="-1"/>
          <do_if value="$sellSector == $buySector">
            <set_value name="$sellDistance" exact="0"/>
          </do_if>
          <do_elseif value="$buySector == $currentSector">
            <do_if value="$currentSectorIsBlacklisted">
              <set_value name="$sellDistance" exact="$ship.gatedistance.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="$ship.gatedistance.{$sellSector}.{$resolvedBlacklistGroup}.{$ship}"/>
            </do_else>
          </do_elseif>
          <do_else>
            <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$resolvedBlacklistGroup}.{$ship}"/>
          </do_else>
          <do_if value="$sellDistance lt 0">
            <set_value name="$result.$Blocked" exact="true"/>
            <set_value name="$result.$Reason" exact="'path_sell'"/>
            <set_value name="$result.$Leg" exact="'path'"/>
            <wait exact="$yieldMs * 1ms"/>
            <return value="$result"/>
          </do_if>
        </do_else>
      </do_if>

      <wait exact="$yieldMs * 1ms"/>
      <return value="$result"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- Per-ship cache read scoring: shipScore = profitCr / (1 + (shipâ†’buy + buyâ†’sell) Ã— distancePenalty).
     Does not mutate global cache rows â€” sets $ShipScore / $SelectionScore on list entries only. -->
<aiscript name="lib.gt.cache.score_for_ship" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="tradeList" default="[]"/>
    <param name="ship"/>
    <param name="distancePenalty" default="0.1"/>
    <param name="blacklistGroup" default="blacklistgroup.civilian"/>
    <param name="maxEntries" default="50"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="not $tradeList? or $tradeList.count == 0">
        <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $SortedTrades = if $tradeList? then $tradeList else [],
          $BestTrade = null,
          $BestScore = 0
        ]"/>
      </do_if>

      <set_value name="$penalty" exact="if $distancePenalty? and $distancePenalty ge 0 then $distancePenalty else 0.1"/>
      <set_value name="$shipSector" exact="null"/>
      <do_if value="$ship? and $ship.sector? and $ship.sector.exists">
        <set_value name="$shipSector" exact="$ship.sector"/>
      </do_if>
      <set_value name="$gdShipToBuy" exact="table[]"/>
      <set_value name="$gdBuyToSell" exact="table[]"/>

      <do_all exact="$tradeList.count" counter="$si">
        <set_value name="$trade" exact="$tradeList.{$si}"/>
        <set_value name="$shipScore" exact="if $trade.$Score? then $trade.$Score else 0"/>
        <set_value name="$shipToBuyDist" exact="-1"/>
        <set_value name="$routeLegDist" exact="0"/>
        <set_value name="$shipRouteDist" exact="0"/>

        <do_if value="$trade.$IsSellOnly? and $trade.$IsSellOnly">
          <set_value name="$trade.$ShipToBuyDistance" exact="0"/>
          <set_value name="$trade.$ShipRouteDistance" exact="0"/>
          <set_value name="$trade.$ShipScore" exact="$shipScore"/>
          <set_value name="$trade.$SelectionScore" exact="$shipScore"/>
          <set_value name="$trade.$ShipRouteScored" exact="true"/>
        </do_if>
        <do_else>
          <set_value name="$buySector" exact="null"/>
          <do_if value="$trade.$BuySector? and $trade.$BuySector.exists">
            <set_value name="$buySector" exact="$trade.$BuySector"/>
          </do_if>
          <do_elseif value="$trade.$BuyStation? and $trade.$BuyStation.sector? and $trade.$BuyStation.sector.exists">
            <set_value name="$buySector" exact="$trade.$BuyStation.sector"/>
          </do_elseif>
          <do_elseif value="$trade.$BuyOffer? and $trade.$BuyOffer.owner? and $trade.$BuyOffer.owner.sector? and $trade.$BuyOffer.owner.sector.exists">
            <set_value name="$buySector" exact="$trade.$BuyOffer.owner.sector"/>
          </do_elseif>

          <set_value name="$sellSector" exact="null"/>
          <do_if value="$trade.$SellSector? and $trade.$SellSector.exists">
            <set_value name="$sellSector" exact="$trade.$SellSector"/>
          </do_if>
          <do_elseif value="$trade.$SellStation? and $trade.$SellStation.sector? and $trade.$SellStation.sector.exists">
            <set_value name="$sellSector" exact="$trade.$SellStation.sector"/>
          </do_elseif>
          <do_elseif value="$trade.$SellOffer? and $trade.$SellOffer.owner? and $trade.$SellOffer.owner.sector? and $trade.$SellOffer.owner.sector.exists">
            <set_value name="$sellSector" exact="$trade.$SellOffer.owner.sector"/>
          </do_elseif>

          <do_if value="$buySector? and $shipSector?">
            <do_if value="$buySector == $shipSector">
              <set_value name="$shipToBuyDist" exact="0"/>
            </do_if>
            <do_elseif value="$blacklistGroup? and $blacklistGroup != null and $ship?">
              <do_if value="$gdShipToBuy.{$shipSector}? and $gdShipToBuy.{$shipSector}.{$buySector}?">
                <set_value name="$shipToBuyDist" exact="$gdShipToBuy.{$shipSector}.{$buySector}"/>
              </do_if>
              <do_else>
                <set_value name="$shipToBuyDist" exact="$ship.gatedistance.{$buySector}.{$blacklistGroup}.{$ship}"/>
                <do_if value="not $gdShipToBuy.{$shipSector}?">
                  <set_value name="$gdShipToBuy.{$shipSector}" exact="table[]"/>
                </do_if>
                <set_value name="$gdShipToBuy.{$shipSector}.{$buySector}" exact="$shipToBuyDist"/>
              </do_else>
            </do_elseif>
            <do_else>
              <set_value name="$shipToBuyDist" exact="$ship.gatedistance.{$buySector}"/>
            </do_else>
          </do_if>

          <do_if value="$shipToBuyDist lt 0">
            <set_value name="$shipScore" exact="0"/>
          </do_if>
          <do_else>
            <set_value name="$reuseRouteLeg" exact="false"/>
            <do_if value="$trade.$RouteDistance? and $buySector? and $sellSector? and $trade.$BuySector? and $trade.$BuySector.exists and $trade.$SellSector? and $trade.$SellSector.exists and $trade.$BuySector == $buySector and $trade.$SellSector == $sellSector">
              <set_value name="$routeLegDist" exact="$trade.$RouteDistance"/>
              <set_value name="$reuseRouteLeg" exact="true"/>
            </do_if>
            <do_if value="not $reuseRouteLeg and $buySector? and $sellSector?">
              <do_if value="$buySector == $sellSector">
                <set_value name="$routeLegDist" exact="0"/>
              </do_if>
              <do_elseif value="$blacklistGroup? and $blacklistGroup != null and $ship?">
                <do_if value="$gdBuyToSell.{$buySector}? and $gdBuyToSell.{$buySector}.{$sellSector}?">
                  <set_value name="$routeLegDist" exact="$gdBuyToSell.{$buySector}.{$sellSector}"/>
                </do_if>
                <do_else>
                  <set_value name="$routeLegDist" exact="$buySector.gatedistance.{$sellSector}.{$blacklistGroup}.{$ship}"/>
                  <do_if value="not $gdBuyToSell.{$buySector}?">
                    <set_value name="$gdBuyToSell.{$buySector}" exact="table[]"/>
                  </do_if>
                  <set_value name="$gdBuyToSell.{$buySector}.{$sellSector}" exact="$routeLegDist"/>
                </do_else>
              </do_elseif>
              <do_else>
                <set_value name="$routeLegDist" exact="$buySector.gatedistance.{$sellSector}"/>
              </do_else>
            </do_if>

            <do_if value="$routeLegDist lt 0">
              <set_value name="$shipScore" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$shipRouteDist" exact="$shipToBuyDist + $routeLegDist"/>
              <set_value name="$profitCr" exact="0"/>
              <do_if value="$trade.$Profit?">
                <set_value name="$profitCr" exact="($trade.$Profit / 1Cr)i"/>
              </do_if>
              <do_elseif value="$trade.$UnitProfit? and $trade.$Amount?">
                <set_value name="$profitCr" exact="(($trade.$UnitProfit * $trade.$Amount) / 1Cr)i"/>
              </do_elseif>
              <do_if value="$profitCr le 0 and $trade.$Score?">
                <set_value name="$shipScore" exact="$trade.$Score"/>
              </do_if>
              <do_else>
                <set_value name="$distanceFactor" exact="1.0 + ($shipRouteDist * $penalty)"/>
                <do_if value="$distanceFactor gt 0">
                  <set_value name="$shipScore" exact="$profitCr / $distanceFactor"/>
                </do_if>
              </do_else>
            </do_else>
          </do_else>

          <set_value name="$trade.$ShipToBuyDistance" exact="[$shipToBuyDist, 0].max"/>
          <set_value name="$trade.$ShipRouteDistance" exact="$shipRouteDist"/>
          <set_value name="$trade.$ShipScore" exact="$shipScore"/>
          <set_value name="$trade.$SelectionScore" exact="$shipScore"/>
          <set_value name="$trade.$ShipRouteScored" exact="true"/>
        </do_else>

        <do_if value="($si % 20) == 0">
          <wait exact="1ms" comment="Yield ship-route score loop"/>
        </do_if>
      </do_all>

      <sort_list list="$tradeList" sortbyvalue="loop.element.$ShipScore" sortdescending="true"/>

      <set_value name="$truncatedList" exact="[]"/>
      <set_value name="$outCount" exact="[$maxEntries, $tradeList.count].min"/>
      <do_all exact="$outCount" counter="$ti">
        <append_to_list name="$truncatedList" exact="$tradeList.{$ti}"/>
      </do_all>

      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScoreOut" exact="0"/>
      <do_if value="$truncatedList.count gt 0">
        <set_value name="$bestTrade" exact="$truncatedList.{1}"/>
        <do_if value="$bestTrade.$ShipScore?">
          <set_value name="$bestScoreOut" exact="$bestTrade.$ShipScore"/>
        </do_if>
      </do_if>

      <wait exact="1ms" comment="Cooperative yield before return (wake-loop guard)"/>
      <return value="table[
        $SortedTrades = $truncatedList,
        $BestTrade = $bestTrade,
        $BestScore = $bestScoreOut
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.cache.search" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="4">
  <params>
    <param name="cachePool" default="'mk3'" comment="Trade cache pool: mk3 (traders) or mk4 (supply)"/>
    <param name="ship" default="this.ship"/>
    <param name="searchMode" default="'buy_and_sell'"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="wareBasket" default="[]"/>
    <param name="minROI" default="0"/>
    <param name="minAbsoluteProfit" default="0"/>
    <param name="ignoreBuildStorage" default="false"/>
    <param name="ignoreCarrierAux" default="false"/>
    <param name="maxEntries" default="100"/>
    <param name="cacheReadOffset" default="0" comment="Rotates cache scan start so concurrent fleet ships pick different entries first"/>
    <param name="cacheMaxAge" default="300s"/> <!-- Matches $Fleet.$CacheTTL default -->
    <param name="cacheDropoffTolerance" default="15"/> <!-- Max % profit drop from cached value before rejection; also % slack on average-price band width at read (0 = strict band) -->
    <param name="sellPriceMax" default="1.0" comment="Max vs ware average for supplier sell offers (ship buys). Normalized -1..+1 offset; 1.0 = no filter (isolated). Matches live search SellPriceMax."/>
    <param name="buyPriceMin" default="-1.0" comment="Min vs ware average for customer buy offers (ship sells). Normalized -1..+1 offset; -1.0 = no filter (isolated). Matches live search BuyPriceMin."/>
    <param name="bypassPlayerSellerPricing" default="false" comment="When true, skip supplier price-band purge for player-owned suppliers (MK3 Ignore Player Pricing)."/>
    <param name="minCargoUtilPercent" default="10"/> <!-- Hard minimum cargo utilization threshold (10-100) -->
    <param name="enableMinCargoUtil" default="true"/>
    <!-- MK4 compatibility params (accepted for call-site compatibility; current cache filter logic is generic) -->
    <param name="mk4AllowResources" default="true"/>
    <param name="mk4AllowIntermediates" default="true"/>
    <param name="mk4AllowTradewares" default="true"/>
    <param name="mk4DedicatedServe" default="false"/>
    <param name="mk4AnchorHome" default="null"/>
    <param name="mk4BuildStorageOnlyMode" default="false"/>
    <param name="maxDistanceBuy" default="0"/>
    <param name="maxDistanceSell" default="0"/>
    <param name="requirePlayerDeliveryStation" default="false"/>
    <param name="requirePlayerSupplierStation" default="false"/>
    <param name="requireNonPlayerSupplierStation" default="false"/>
    <!-- MK3 'Ignore Player Pricing' companion filter: when true, drop cache entries whose delivery (customer) station is player-owned. -->
    <param name="requireNonPlayerDeliveryStation" default="false"/>
    <param name="ignoreTradeRules" default="false" comment="When false, drop entries where a player-owned station's trade rules block the pair (NPCÃ—NPC ignores cantradewith)."/>
    <param name="distancePenalty" default="0.1" comment="MK3 ship-route score divisor (matches lib.gt.tradematch / order distancepenalty)."/>
    <param name="blacklistGroup" default="blacklistgroup.civilian" comment="Blacklist-aware shipâ†’buy and buyâ†’sell for lib.gt.cache.score_for_ship."/>
    <param name="debugchance" default="0"/>
  </params>
  <patch sinceversion="3">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
  </patch>
  <patch sinceversion="4">
    <do_if value="not $cachePool?">
      <set_value name="$cachePool" exact="'mk3'"/>
    </do_if>
  </patch>
  <attention min="unknown">
    <actions>
      <create_list name="$tradeList"/>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <set_value name="this.$gt_cachePoolIsMk4" exact="$cachePool == 'mk4'"/>
      <set_value name="$cacheHomeKey" exact="$homeSector"/>
      <set_value name="$homeCache" exact="null"/>
      <do_if value="this.$gt_cachePoolIsMk4">
        <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK4.{$homeSector}"/>
      </do_if>
      <do_else>
        <set_value name="$homeCache" exact="@global.$GT_TradeCache.{$homeSector}"/>
      </do_else>
      <set_value name="$homeCacheCount" exact="0"/>
      <do_if value="$homeCache?">
        <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
      </do_if>
      <!-- Sector table-key reconciliation: lookup can miss when homeSector ref differs from writer key. -->
      <do_if value="$homeCacheCount == 0 and this.$gt_cachePoolIsMk4 and global.$GT_TradeCacheMK4? and $homeSector? and $homeSector.exists">
        <set_value name="$mk4CacheKeys" exact="@global.$GT_TradeCacheMK4.keys"/>
        <set_value name="$mk4CacheKeyCount" exact="0"/>
        <do_if value="$mk4CacheKeys?">
          <set_value name="$mk4CacheKeyCount" exact="@$mk4CacheKeys.count"/>
        </do_if>
        <do_if value="$mk4CacheKeyCount gt 0">
          <do_all exact="$mk4CacheKeyCount" counter="$cki">
            <set_value name="$ckiSector" exact="@$mk4CacheKeys.{$cki}"/>
            <do_if value="$ckiSector? and $ckiSector.exists and $ckiSector == $homeSector">
              <set_value name="$cacheHomeKey" exact="$ckiSector"/>
              <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK4.{$ckiSector}"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$homeCache?">
          <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
        </do_if>
      </do_if>
      <set_value name="$purgedStaleCount" exact="0"/>
      <do_if value="$homeCacheCount == 0">
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = $tradeList,
          $PurgedStale = 0,
          $PoolSizeAfter = 0
        ]"/>
      </do_if>

      <set_value name="this.$cleanupBatchSize" exact="50"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize?">
        <set_value name="this.$cleanupBatchSize" exact="[10, @global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize].max"/>
      </do_if>
      <set_value name="this.$cleanupBatchSize" exact="(this.$cleanupBatchSize)i"/>
      <set_value name="$now" exact="player.age"/>
      <!-- Average-price band thresholds (quantityfactor = unitprice / ware.averageprice).
           Matches slider intent (-20% buy / +20% sell vs galaxy average), not station-local relativeprice. -->
      <set_value name="$bandSellMax" exact="if $sellPriceMax? then $sellPriceMax else 1.0"/>
      <set_value name="$bandBuyMin" exact="if $buyPriceMin? then $buyPriceMin else -1.0"/>
      <set_value name="$bandPriceCheckActive" exact="false"/>
      <set_value name="$bandSellMaxRelaxed" exact="$bandSellMax"/>
      <set_value name="$bandBuyMinRelaxed" exact="$bandBuyMin"/>
      <set_value name="$bandSupplierQtyMax" exact="2.0"/>
      <set_value name="$bandCustomerQtyMin" exact="0.0"/>
      <set_value name="$bandMinQtySpread" exact="0.0"/>
      <do_if value="not ($bandSellMax ge 1.0 and $bandBuyMin le -1.0)">
        <set_value name="$bandPriceCheckActive" exact="true"/>
        <set_value name="$bandDropoffPct" exact="if $cacheDropoffTolerance? and $cacheDropoffTolerance gt 0 then $cacheDropoffTolerance else 0"/>
        <set_value name="$bandSellSlack" exact="[$bandSellMax, -$bandSellMax].max * ($bandDropoffPct / 100.0)"/>
        <set_value name="$bandBuySlack" exact="[$bandBuyMin, -$bandBuyMin].max * ($bandDropoffPct / 100.0)"/>
        <set_value name="$bandSellMaxRelaxed" exact="$bandSellMax + $bandSellSlack"/>
        <set_value name="$bandBuyMinRelaxed" exact="$bandBuyMin - $bandBuySlack"/>
        <set_value name="$bandSupplierQtyMax" exact="1.0 + $bandSellMaxRelaxed"/>
        <set_value name="$bandCustomerQtyMin" exact="1.0 + $bandBuyMinRelaxed"/>
        <set_value name="$bandMinQtySpread" exact="$bandBuyMinRelaxed - $bandSellMaxRelaxed"/>
      </do_if>
      <!-- Read-time purge: TTL + dead refs only. Average-price band is per-ship at read (lib.gt.cache.search). -->
      <do_all exact="$homeCacheCount" counter="$pci" reverse="true">
        <set_value name="$livePurgeCount" exact="0"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$livePurgeCount" exact="if @global.$GT_TradeCacheMK4.{$cacheHomeKey}.count != null then @global.$GT_TradeCacheMK4.{$cacheHomeKey}.count else 0"/>
        </do_if>
        <do_else>
          <set_value name="$livePurgeCount" exact="if @global.$GT_TradeCache.{$cacheHomeKey}.count != null then @global.$GT_TradeCache.{$cacheHomeKey}.count else 0"/>
        </do_else>
        <do_if value="$pci gt $livePurgeCount">
          <continue/>
        </do_if>
        <set_value name="$purgeEntry" exact="null"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$purgeEntry" exact="@global.$GT_TradeCacheMK4.{$cacheHomeKey}.{$pci}"/>
        </do_if>
        <do_else>
          <set_value name="$purgeEntry" exact="@global.$GT_TradeCache.{$cacheHomeKey}.{$pci}"/>
        </do_else>
        <set_value name="$purgeRemove" exact="false"/>
        <do_if value="not $purgeEntry?">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <do_if value="not $purgeRemove and (not $purgeEntry.$Score? or $purgeEntry.$Score le 0)">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <set_value name="$purgeTs" exact="null"/>
        <do_if value="not $purgeRemove">
          <set_value name="$purgeTs" exact="@$purgeEntry.$CachedAt"/>
          <do_if value="$purgeTs == null">
            <set_value name="$purgeTs" exact="@$purgeEntry.$Timestamp"/>
          </do_if>
          <do_if value="$purgeTs != null and ($now - $purgeTs) gt $cacheMaxAge">
            <set_value name="$purgeRemove" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $purgeRemove and @$purgeEntry.$BuyOffer != null and not @$purgeEntry.$BuyOffer.exists">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <!-- Customer buy-offer refs refresh continuously; rows with permanent keys are re-discovered at read. -->
        <set_value name="$purgeReResolvable" exact="(@$purgeEntry.$Ware != null or @$purgeEntry.$DeliveryStationName != null) and (@$purgeEntry.$DeliveryStationId != null or @$purgeEntry.$DeliveryStationName != null) and ((@$purgeEntry.$SellSector != null and @$purgeEntry.$SellSector.exists) or @$purgeEntry.$SellSectorId != null or @$purgeEntry.$DeliveryStationId != null)"/>
        <do_if value="not $purgeRemove and not $purgeReResolvable and @$purgeEntry.$SellOffer != null and not @$purgeEntry.$SellOffer.exists">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <do_if value="not $purgeRemove and not $purgeReResolvable and @$purgeEntry.$SellStation != null and not @$purgeEntry.$SellStation.exists">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <!-- Universal station resolution: drop rows no ship can use (dead delivery/supplier refs). -->
        <do_if value="not $purgeRemove and not $purgeReResolvable">
          <set_value name="$purgeSellStation" exact="null"/>
          <do_if value="$purgeEntry.$SellOffer? and @$purgeEntry.$SellOffer.exists and $purgeEntry.$SellOffer.buyer? and @$purgeEntry.$SellOffer.buyer.exists">
            <set_value name="$purgeSellStation" exact="@$purgeEntry.$SellOffer.buyer"/>
          </do_if>
          <do_if value="not $purgeSellStation? and $purgeEntry.$SellStation? and @$purgeEntry.$SellStation.exists">
            <set_value name="$purgeSellStation" exact="$purgeEntry.$SellStation"/>
          </do_if>
          <do_if value="not $purgeSellStation? and $purgeEntry.$SellOffer? and @$purgeEntry.$SellOffer.exists and $purgeEntry.$SellOffer.owner? and @$purgeEntry.$SellOffer.owner.exists">
            <set_value name="$purgeSellStation" exact="@$purgeEntry.$SellOffer.owner"/>
          </do_if>
          <do_if value="not $purgeSellStation? or not @$purgeSellStation.exists">
            <set_value name="$purgeRemove" exact="true"/>
          </do_if>
          <do_if value="not $purgeRemove and not ($purgeEntry.$IsSellOnly? and $purgeEntry.$IsSellOnly)">
            <set_value name="$purgeBuyStation" exact="null"/>
            <do_if value="$purgeEntry.$BuyStation? and @$purgeEntry.$BuyStation.exists">
              <set_value name="$purgeBuyStation" exact="$purgeEntry.$BuyStation"/>
            </do_if>
            <do_if value="not $purgeBuyStation? and $purgeEntry.$BuyOffer? and @$purgeEntry.$BuyOffer.exists">
              <do_if value="$purgeEntry.$BuyOffer.seller? and @$purgeEntry.$BuyOffer.seller.exists">
                <set_value name="$purgeBuyStation" exact="@$purgeEntry.$BuyOffer.seller"/>
              </do_if>
              <do_elseif value="$purgeEntry.$BuyOffer.owner? and @$purgeEntry.$BuyOffer.owner.exists">
                <set_value name="$purgeBuyStation" exact="@$purgeEntry.$BuyOffer.owner"/>
              </do_elseif>
            </do_if>
            <do_if value="not $purgeBuyStation? or not @$purgeBuyStation.exists">
              <set_value name="$purgeRemove" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$purgeRemove">
          <set_value name="$liveBeforeRemove" exact="0"/>
          <do_if value="this.$gt_cachePoolIsMk4">
            <set_value name="$liveBeforeRemove" exact="if @global.$GT_TradeCacheMK4.{$cacheHomeKey}.count != null then @global.$GT_TradeCacheMK4.{$cacheHomeKey}.count else 0"/>
          </do_if>
          <do_else>
            <set_value name="$liveBeforeRemove" exact="if @global.$GT_TradeCache.{$cacheHomeKey}.count != null then @global.$GT_TradeCache.{$cacheHomeKey}.count else 0"/>
          </do_else>
          <do_if value="$pci le $liveBeforeRemove">
            <do_if value="this.$gt_cachePoolIsMk4">
              <remove_value name="global.$GT_TradeCacheMK4.{$cacheHomeKey}.{$pci}"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_TradeCache.{$cacheHomeKey}.{$pci}"/>
            </do_else>
            <set_value name="$purgedStaleCount" operation="add"/>
          </do_if>
        </do_if>
        <set_value name="$pciInt" exact="($pci)i"/>
        <do_if value="($pciInt % this.$cleanupBatchSize) == 0">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield read-time purge loop"/>
        </do_if>
      </do_all>
      <do_if value="$purgedStaleCount gt 0">
        <set_value name="$homeCache" exact="null"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK4.{$cacheHomeKey}"/>
        </do_if>
        <do_else>
          <set_value name="$homeCache" exact="@global.$GT_TradeCache.{$cacheHomeKey}"/>
        </do_else>
        <set_value name="$homeCacheCount" exact="0"/>
        <do_if value="$homeCache?">
          <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
        </do_if>
        <set_value name="$poolLabel" exact="if this.$gt_cachePoolIsMk4 then 'MK4' else 'MK3'"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-CacheSearch] ' + $ship.idcode + ': (' + $poolLabel + ') Read-time purge removed ' + $purgedStaleCount + ' stale entries from ' + $cacheHomeKey.knownname + ' (remaining: ' + $homeCacheCount + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_if value="$homeCacheCount == 0">
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = $tradeList,
          $PurgedStale = $purgedStaleCount,
          $PoolSizeAfter = 0
        ]"/>
      </do_if>

      <set_value name="$maxDistanceBuyLeg" exact="if $maxDistanceBuy? and $maxDistanceBuy gt 0 then $maxDistanceBuy else $maxDistance"/>
      <set_value name="$maxDistanceSellLeg" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
      <!-- If cache was populated with a smaller search radius than this ship needs, treat as miss
           so live search (with completion pass) can find trades outside the cached radius. -->
      <set_value name="$foundCount" exact="0"/>
      <set_value name="$isSellOnlySearch" exact="$searchMode == 'sell_only'"/>
      <set_value name="$wareBasketCount" exact="if $wareBasket? and typeof $wareBasket == datatype.list then $wareBasket.count else 0"/>
      <set_value name="$isIsolatedMode" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?"/>
      <set_value name="$cargoUtilThresholdPct" exact="[10,[$minCargoUtilPercent,100].min].max"/>
      <!-- Per-ware diversification: each ware gets a slice of the result window so low-score
           wares (e.g. small remainder deliveries) are not crowded out by a few dominant wares. -->
      <set_value name="$foundPerWare" exact="table[]"/>
      <!-- Memoize delivery re-discovery within this cache read (same station+ware appears in many entries). -->
      <set_value name="$deliveryResolveMemo" exact="table[]"/>
      <set_value name="$stationIdResolveMemo" exact="table[]"/>
      <set_value name="$stationIdResolveMiss" exact="table[]"/>
      <set_value name="$sectorResolveMemo" exact="table[]"/>
      <set_value name="$sectorResolveMiss" exact="table[]"/>
      <set_value name="$reScanMaxDist" exact="[$maxDistance, $maxDistanceBuyLeg, $maxDistanceSellLeg, 1].max + 2"/>
      <set_value name="$maxTradesPerWareSetting" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
        <set_value name="$maxTradesPerWareSetting" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
      </do_if>
      <do_if value="$maxTradesPerWareSetting lt 1">
        <set_value name="$maxTradesPerWareSetting" exact="1"/>
      </do_if>
      <set_value name="$perWareCap" exact="$maxTradesPerWareSetting"/>
      <do_if value="$wareBasketCount gt 0">
        <set_value name="$perWareCapFromBudget" exact="[1, ($maxEntries / $wareBasketCount)i].max"/>
        <set_value name="$perWareCap" exact="[$perWareCapFromBudget, $maxTradesPerWareSetting].min"/>
      </do_if>
      <do_else>
        <set_value name="$perWareCap" exact="[2, [$maxTradesPerWareSetting, 5].min].max"/>
      </do_else>
      <!-- MK3: scan full pool (filter all), then lib.gt.cache.score_for_ship ranks by shipâ†’buy + buyâ†’sell.
           MK4: legacy rotated scan with early cap at $maxEntries (unchanged). -->
      <!-- NOTE: $homeCacheCount is a snapshot; the list can shrink mid-loop (MD purge/cleanup
           runs while this AI script yields). Guard with bounds check before access. -->
      <set_value name="$loopSpan" exact="[$homeCacheCount, 1].max"/>
      <set_value name="$startOffset" exact="0"/>
      <do_if value="this.$gt_cachePoolIsMk4 and $cacheReadOffset? and $loopSpan gt 0">
        <set_value name="$startOffset" exact="(($cacheReadOffset) % $loopSpan)"/>
      </do_if>
      <do_all exact="$loopSpan" counter="$visitIdx">
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$i" exact="(($startOffset + $visitIdx - 1) % $loopSpan) + 1"/>
        </do_if>
        <do_else>
          <set_value name="$i" exact="$visitIdx"/>
        </do_else>
        <!-- Bounds guard: list may have shrunk since $homeCacheCount was captured -->
        <do_if value="$i gt $homeCache.count">
          <continue/>
        </do_if>
        <set_value name="$entry" exact="@$homeCache.{$i}"/>
        <!-- Initialize per-entry offer capacities to avoid undefined-variable lookups -->
        <set_value name="$preCheckBuyAmt" exact="0"/>
        <set_value name="$preCheckSellAmt" exact="0"/>
        <!-- Resolve supplier/delivery stations: cached component refs go stale (0x0L) when
             stations are destroyed; prefer live offer seller/buyer when the stored ref is dead. -->
        <set_value name="$entryBuyStation" exact="null"/>
        <do_if value="$entry.$BuyStation? and @$entry.$BuyStation.exists">
          <set_value name="$entryBuyStation" exact="$entry.$BuyStation"/>
        </do_if>
        <do_if value="not $entryBuyStation? and $entry.$BuyOffer? and @$entry.$BuyOffer.exists">
          <do_if value="$entry.$BuyOffer.seller? and @$entry.$BuyOffer.seller.exists">
            <set_value name="$entryBuyStation" exact="@$entry.$BuyOffer.seller"/>
          </do_if>
          <do_elseif value="$entry.$BuyOffer.owner? and @$entry.$BuyOffer.owner.exists">
            <set_value name="$entryBuyStation" exact="@$entry.$BuyOffer.owner"/>
          </do_elseif>
        </do_if>
        <do_if value="($entryBuyStation == null or not @$entryBuyStation.exists) and $entry.$SupplierStationId? and $homeSector? and @$homeSector.exists">
          <set_value name="$buyIdMemoHit" exact="$stationIdResolveMemo.{$entry.$SupplierStationId}? or $stationIdResolveMiss.{$entry.$SupplierStationId}?"/>
          <do_if value="$stationIdResolveMemo.{$entry.$SupplierStationId}?">
            <set_value name="$buyIdMemoStation" exact="$stationIdResolveMemo.{$entry.$SupplierStationId}"/>
            <do_if value="$buyIdMemoStation? and @$buyIdMemoStation.exists">
              <set_value name="$entryBuyStation" exact="$buyIdMemoStation"/>
            </do_if>
          </do_if>
          <do_if value="not $buyIdMemoHit">
            <set_value name="$buyIdTargetStation" exact="null"/>
            <find_sector_in_range name="$buyIdScanSectors" object="$homeSector" maxdistance="$reScanMaxDist" multiple="true"/>
            <do_if value="$buyIdScanSectors? and $buyIdScanSectors.count gt 0">
              <do_for_each name="$buyIdScanSec" in="$buyIdScanSectors">
                <do_if value="not $buyIdTargetStation? and $buyIdScanSec? and @$buyIdScanSec.exists">
                  <find_station name="$buyIdScanStations" space="$buyIdScanSec" multiple="true"/>
                  <do_if value="$buyIdScanStations? and $buyIdScanStations.count gt 0">
                    <do_for_each name="$buyIdScanSt" in="$buyIdScanStations">
                      <do_if value="not $buyIdTargetStation? and $buyIdScanSt? and @$buyIdScanSt.exists and $buyIdScanSt.idcode? and @$buyIdScanSt.idcode == $entry.$SupplierStationId">
                        <set_value name="$buyIdTargetStation" exact="$buyIdScanSt"/>
                      </do_if>
                    </do_for_each>
                  </do_if>
                </do_if>
              </do_for_each>
            </do_if>
            <do_if value="$buyIdTargetStation? and @$buyIdTargetStation.exists">
              <set_value name="$stationIdResolveMemo.{$entry.$SupplierStationId}" exact="$buyIdTargetStation"/>
              <set_value name="$entryBuyStation" exact="$buyIdTargetStation"/>
            </do_if>
            <do_else>
              <set_value name="$stationIdResolveMiss.{$entry.$SupplierStationId}" exact="true"/>
            </do_else>
          </do_if>
        </do_if>
        <set_value name="$entrySellStationFromBuyer" exact="null"/>
        <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.buyer? and @$entry.$SellOffer.buyer.exists">
          <set_value name="$entrySellStationFromBuyer" exact="@$entry.$SellOffer.buyer"/>
        </do_if>
        <set_value name="$entrySellStation" exact="null"/>
        <!-- Primary: stored delivery station, UNGUARDED (mirrors buy-station resolution above).
             CRITICAL: use '$x == null' value-tests below, NOT 'not $x?'. After
             <set_value exact="null"/> the variable is DEFINED, so '$x?' returns true and
             'not $x?' is always false - which previously skipped every resolver and left
             $entrySellStation a defined-null, rejecting 100% of cache entries (f68ba09 regression). -->
        <do_if value="$entry.$SellStation? and @$entry.$SellStation.exists">
          <set_value name="$entrySellStation" exact="$entry.$SellStation"/>
        </do_if>
        <do_if value="$entrySellStation == null and $entrySellStationFromBuyer? and @$entrySellStationFromBuyer.exists">
          <set_value name="$entrySellStation" exact="$entrySellStationFromBuyer"/>
        </do_if>
        <do_if value="$entrySellStation == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.owner? and @$entry.$SellOffer.owner.exists">
          <set_value name="$entrySellStation" exact="@$entry.$SellOffer.owner"/>
        </do_if>
        <!-- Prefer buildstorage buyer when the stored SellStation is the parent station (not the BS). -->
        <do_if value="$entrySellStation != null and @$entrySellStation.exists and not @$entrySellStation.isclass.buildstorage and $entrySellStationFromBuyer? and @$entrySellStationFromBuyer.exists and @$entrySellStationFromBuyer.isclass.buildstorage">
          <set_value name="$entrySellStation" exact="$entrySellStationFromBuyer"/>
        </do_if>
        <!-- MK4 build-storage-only mode: delivery buy-offer buyer is authoritative (overrides parent-HQ SellStation). -->
        <do_if value="$mk4BuildStorageOnlyMode and $entrySellStationFromBuyer? and @$entrySellStationFromBuyer.exists">
          <set_value name="$entrySellStation" exact="$entrySellStationFromBuyer"/>
        </do_if>
        <!-- Customer buy-offer / delivery-station refs die when offers refresh; re-discover from permanent keys (memoized, targeted queries). -->
        <do_if value="$entrySellStation == null or not @$entrySellStation.exists">
          <do_if value="$entry.$SellStationBase? and @$entry.$SellStationBase.exists">
            <set_value name="$entryBaseBuildStorage" exact="@$entry.$SellStationBase.buildstorage"/>
            <do_if value="$entryBaseBuildStorage? and @$entryBaseBuildStorage.exists">
              <set_value name="$entrySellStation" exact="$entryBaseBuildStorage"/>
              <set_value name="$entry.$SellStation" exact="$entryBaseBuildStorage"/>
            </do_if>
          </do_if>
          <set_value name="$reResolveWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$reResolveWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$reResolveWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$reResolveWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$reResolveWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <do_if value="($entrySellStation == null or not @$entrySellStation.exists) and $entry.$DeliveryStationId? and $reResolveWare? and $homeSector? and @$homeSector.exists">
            <set_value name="$delIdMemoHit" exact="$stationIdResolveMemo.{$entry.$DeliveryStationId}? or $stationIdResolveMiss.{$entry.$DeliveryStationId}?"/>
            <do_if value="$stationIdResolveMemo.{$entry.$DeliveryStationId}?">
              <set_value name="$delIdMemoStation" exact="$stationIdResolveMemo.{$entry.$DeliveryStationId}"/>
              <do_if value="$delIdMemoStation? and @$delIdMemoStation.exists">
                <set_value name="$entrySellStation" exact="$delIdMemoStation"/>
                <set_value name="$entry.$SellStation" exact="$delIdMemoStation"/>
              </do_if>
            </do_if>
            <do_if value="not $delIdMemoHit">
              <set_value name="$delIdTargetStation" exact="null"/>
              <set_value name="$delIdTargetOffer" exact="null"/>
              <find_sector_in_range name="$delIdScanSectors" object="$homeSector" maxdistance="$reScanMaxDist" multiple="true"/>
              <do_if value="$delIdScanSectors? and $delIdScanSectors.count gt 0">
                <do_for_each name="$delIdScanSec" in="$delIdScanSectors">
                  <do_if value="not $delIdTargetStation? and $delIdScanSec? and @$delIdScanSec.exists">
                    <find_station name="$delIdScanStations" space="$delIdScanSec" multiple="true"/>
                    <do_if value="$delIdScanStations? and $delIdScanStations.count gt 0">
                      <do_for_each name="$delIdScanSt" in="$delIdScanStations">
                        <do_if value="not $delIdTargetStation? and $delIdScanSt? and @$delIdScanSt.exists and $delIdScanSt.idcode? and @$delIdScanSt.idcode == $entry.$DeliveryStationId">
                          <set_value name="$delIdTargetStation" exact="$delIdScanSt"/>
                        </do_if>
                      </do_for_each>
                    </do_if>
                    <do_if value="not $delIdTargetStation?">
                      <find_object name="$delIdScanBsObjs" class="class.buildstorage" space="$delIdScanSec" owner="faction.player" multiple="true"/>
                      <do_if value="$delIdScanBsObjs? and $delIdScanBsObjs.count gt 0">
                        <do_for_each name="$delIdScanBsCand" in="$delIdScanBsObjs">
                          <do_if value="not $delIdTargetStation? and $delIdScanBsCand? and @$delIdScanBsCand.exists and $delIdScanBsCand.base? and @$delIdScanBsCand.base.exists and @$delIdScanBsCand.base.idcode == $entry.$DeliveryStationId">
                            <set_value name="$delIdTargetStation" exact="$delIdScanBsCand"/>
                          </do_if>
                        </do_for_each>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_for_each>
              </do_if>
              <do_if value="$delIdTargetStation? and @$delIdTargetStation.exists">
                <set_value name="$stationIdResolveMemo.{$entry.$DeliveryStationId}" exact="$delIdTargetStation"/>
                <set_value name="$entrySellStation" exact="$delIdTargetStation"/>
                <set_value name="$entry.$SellStation" exact="$delIdTargetStation"/>
                <find_buy_offer buyer="$delIdTargetStation" tradepartner="$ship" wares="$reResolveWare" result="$delIdTargetOffers" multiple="true">
                  <offeramount min="1" tradepartner="$ship"/>
                </find_buy_offer>
                <do_if value="not ($delIdTargetOffers? and $delIdTargetOffers.count gt 0) and @$delIdTargetStation.isclass.buildstorage">
                  <find_buy_offer buyer="$delIdTargetStation" tradepartner="$ship" wares="$reResolveWare" result="$delIdTargetOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_if value="$delIdTargetOffers? and $delIdTargetOffers.count gt 0">
                  <set_value name="$delIdTargetOffer" exact="$delIdTargetOffers.{1}"/>
                  <set_value name="$entry.$SellOffer" exact="$delIdTargetOffer"/>
                </do_if>
                <do_if value="not $entry.$SellSectorId? and $delIdTargetStation.sector? and @$delIdTargetStation.sector.exists and $delIdTargetStation.sector.idcode?">
                  <set_value name="$entry.$SellSectorId" exact="@$delIdTargetStation.sector.idcode"/>
                </do_if>
              </do_if>
              <do_else>
                <set_value name="$stationIdResolveMiss.{$entry.$DeliveryStationId}" exact="true"/>
              </do_else>
            </do_if>
          </do_if>
          <set_value name="$reSellSector" exact="null"/>
          <do_if value="$entry.$SellSector? and @$entry.$SellSector.exists">
            <set_value name="$reSellSector" exact="$entry.$SellSector"/>
          </do_if>
          <do_elseif value="$entry.$SellSectorId? and $homeSector? and @$homeSector.exists">
            <set_value name="$secIdMemoHit" exact="$sectorResolveMemo.{$entry.$SellSectorId}? or $sectorResolveMiss.{$entry.$SellSectorId}?"/>
            <do_if value="$sectorResolveMemo.{$entry.$SellSectorId}?">
              <set_value name="$secIdMemoSector" exact="$sectorResolveMemo.{$entry.$SellSectorId}"/>
              <do_if value="$secIdMemoSector? and @$secIdMemoSector.exists">
                <set_value name="$reSellSector" exact="$secIdMemoSector"/>
              </do_if>
            </do_if>
            <do_if value="not $secIdMemoHit">
              <find_sector_in_range name="$secIdScanSectors" object="$homeSector" maxdistance="$reScanMaxDist" multiple="true"/>
              <do_if value="$secIdScanSectors? and $secIdScanSectors.count gt 0">
                <do_for_each name="$secIdScanSec" in="$secIdScanSectors">
                  <do_if value="not $reSellSector? and $secIdScanSec? and @$secIdScanSec.exists and $secIdScanSec.idcode? and @$secIdScanSec.idcode == $entry.$SellSectorId">
                    <set_value name="$reSellSector" exact="$secIdScanSec"/>
                  </do_if>
                </do_for_each>
              </do_if>
              <do_if value="$reSellSector? and @$reSellSector.exists">
                <set_value name="$sectorResolveMemo.{$entry.$SellSectorId}" exact="$reSellSector"/>
              </do_if>
              <do_else>
                <set_value name="$sectorResolveMiss.{$entry.$SellSectorId}" exact="true"/>
              </do_else>
            </do_if>
          </do_elseif>
          <do_if value="($entrySellStation == null or not @$entrySellStation.exists) and $reSellSector? and @$reSellSector.exists and $reResolveWare?">
            <set_value name="$reMemoAnchor" exact="if $entry.$DeliveryStationId? then $entry.$DeliveryStationId else (if $entry.$DeliveryStationName? then $entry.$DeliveryStationName else null)"/>
            <set_value name="$reMemoKey" exact="null"/>
            <do_if value="$reMemoAnchor? and $reResolveWare? and $reResolveWare.name?">
              <set_value name="$reMemoKey" exact="$reMemoAnchor + '|' + @$reResolveWare.name"/>
            </do_if>
            <set_value name="$reMemoHit" exact="false"/>
            <do_if value="$reMemoKey? and $deliveryResolveMemo.{$reMemoKey}?">
              <set_value name="$reMemoHit" exact="true"/>
              <set_value name="$reMemoEntry" exact="$deliveryResolveMemo.{$reMemoKey}"/>
              <do_if value="$reMemoEntry.$Resolved? and $reMemoEntry.$Resolved and $reMemoEntry.$Station? and @$reMemoEntry.$Station.exists">
                <set_value name="$entrySellStation" exact="$reMemoEntry.$Station"/>
                <set_value name="$entry.$SellStation" exact="$reMemoEntry.$Station"/>
                <do_if value="$reMemoEntry.$Offer? and @$reMemoEntry.$Offer.exists">
                  <set_value name="$entry.$SellOffer" exact="$reMemoEntry.$Offer"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="not $reMemoHit">
              <set_value name="$reTargetStation" exact="null"/>
              <set_value name="$reTargetOffer" exact="null"/>
              <do_if value="$entry.$DeliveryStationId?">
                <find_station name="$reStations" space="$reSellSector" multiple="true"/>
                <do_if value="$reStations? and $reStations.count gt 0">
                  <do_for_each name="$reSt" in="$reStations">
                    <do_if value="not $reTargetStation? and $reSt? and @$reSt.exists and @$reSt.idcode == $entry.$DeliveryStationId">
                      <set_value name="$reTargetStation" exact="$reSt"/>
                    </do_if>
                  </do_for_each>
                </do_if>
                <do_if value="not $reTargetStation?">
                  <find_object name="$reBsObjs" class="class.buildstorage" space="$reSellSector" owner="faction.player" multiple="true"/>
                  <do_if value="$reBsObjs? and $reBsObjs.count gt 0">
                    <do_for_each name="$reBsCand" in="$reBsObjs">
                      <do_if value="not $reTargetStation? and $reBsCand? and @$reBsCand.exists and $reBsCand.base? and @$reBsCand.base.exists and @$reBsCand.base.idcode == $entry.$DeliveryStationId">
                        <set_value name="$reTargetStation" exact="$reBsCand"/>
                      </do_if>
                    </do_for_each>
                  </do_if>
                </do_if>
              </do_if>
              <do_elseif value="$entry.$DeliveryStationName?">
                <find_station name="$reNameStations" space="$reSellSector" multiple="true"/>
                <do_if value="$reNameStations? and $reNameStations.count gt 0">
                  <do_for_each name="$reNameSt" in="$reNameStations">
                    <do_if value="not $reTargetStation? and $reNameSt? and @$reNameSt.exists and $reNameSt.knownname? and @$reNameSt.knownname == $entry.$DeliveryStationName">
                      <set_value name="$reTargetStation" exact="$reNameSt"/>
                    </do_if>
                  </do_for_each>
                </do_if>
              </do_elseif>
              <do_if value="$reTargetStation? and @$reTargetStation.exists">
                <find_buy_offer buyer="$reTargetStation" tradepartner="$ship" wares="$reResolveWare" result="$reTargetOffers" multiple="true">
                  <offeramount min="1" tradepartner="$ship"/>
                </find_buy_offer>
                <do_if value="not ($reTargetOffers? and $reTargetOffers.count gt 0) and @$reTargetStation.isclass.buildstorage">
                  <find_buy_offer buyer="$reTargetStation" tradepartner="$ship" wares="$reResolveWare" result="$reTargetOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_if value="$reTargetOffers? and $reTargetOffers.count gt 0">
                  <set_value name="$reTargetOffer" exact="$reTargetOffers.{1}"/>
                </do_if>
              </do_if>
              <do_if value="$reMemoKey?">
                <do_if value="$reTargetStation? and @$reTargetStation.exists">
                  <set_value name="$deliveryResolveMemo.{$reMemoKey}" exact="table[$Resolved = true, $Station = $reTargetStation]"/>
                  <do_if value="$reTargetOffer? and @$reTargetOffer.exists">
                    <set_value name="$deliveryResolveMemo.{$reMemoKey}.$Offer" exact="$reTargetOffer"/>
                  </do_if>
                </do_if>
                <do_else>
                  <set_value name="$deliveryResolveMemo.{$reMemoKey}" exact="table[$Resolved = false]"/>
                </do_else>
              </do_if>
              <do_if value="$reTargetStation? and @$reTargetStation.exists">
                <set_value name="$entrySellStation" exact="$reTargetStation"/>
                <set_value name="$entry.$SellStation" exact="$reTargetStation"/>
                <do_if value="$reTargetOffer? and @$reTargetOffer.exists">
                  <set_value name="$entry.$SellOffer" exact="$reTargetOffer"/>
                </do_if>
                <do_if value="not $entry.$DeliveryStationId?">
                  <do_if value="@$reTargetStation.isclass.buildstorage and $reTargetStation.base? and @$reTargetStation.base.exists">
                    <set_value name="$entry.$DeliveryStationId" exact="@$reTargetStation.base.idcode"/>
                    <set_value name="$entry.$SellStationBase" exact="@$reTargetStation.base"/>
                  </do_if>
                  <do_else>
                    <set_value name="$entry.$DeliveryStationId" exact="@$reTargetStation.idcode"/>
                  </do_else>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_if>

        <!-- Basic validity -->
        <do_if value="not $entry? or not $entry.$Score? or $entry.$Score le 0">
          <continue/>
        </do_if>

        <!-- Ship-scoped cache failure: skip entries this ship already rejected (S1b). -->
        <do_if value="$entry.$FailedShips? and $entry.$FailedShips.count gt 0">
          <set_value name="$shipFailedOnEntry" exact="false"/>
          <do_all exact="$entry.$FailedShips.count" counter="$fsi">
            <do_if value="$entry.$FailedShips.{$fsi} == $ship">
              <set_value name="$shipFailedOnEntry" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="$shipFailedOnEntry">
            <continue/>
          </do_if>
        </do_if>

        <!-- Search-mode guard:
             - sell_only: only sell-only entries for wares this ship is currently carrying
             - buy_and_sell: never pick sell-only disposal entries -->
        <do_if value="$isSellOnlySearch">
          <do_if value="not $entry.$IsSellOnly? or not $entry.$IsSellOnly">
            <continue/>
          </do_if>
          <do_if value="not $entry.$Ware? or $ship.cargo.{$entry.$Ware}.count le 0">
            <continue/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="$entry.$IsSellOnly? and $entry.$IsSellOnly">
            <continue/>
          </do_if>
        </do_else>

        <!-- Cargo bay compatibility: shared MK4 pool may contain trades from solid/liquid ships;
             skip wares this ship cannot carry (mirrors trade_found + GT_FilterTrade).
             $CargoWareTransport on MK4 entries survives stale ware refs. -->
        <do_if value="not $isSellOnlySearch">
          <set_value name="$cargoCompatWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$cargoCompatWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$cargoCompatWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$cargoCompatWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$cargoCompatWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <set_value name="$entryCargoTransport" exact="null"/>
          <do_if value="$entry.$CargoWareTransport?">
            <set_value name="$entryCargoTransport" exact="@$entry.$CargoWareTransport"/>
          </do_if>
          <do_elseif value="$cargoCompatWare?">
            <set_value name="$entryCargoTransport" exact="@$cargoCompatWare.waretransport"/>
          </do_elseif>
          <set_value name="$cargoHoldOk" exact="false"/>
          <do_if value="$cargoCompatWare? and @$ship.cargo.{$cargoCompatWare}.max gt 0">
            <set_value name="$cargoHoldOk" exact="true"/>
          </do_if>
          <do_elseif value="$entryCargoTransport? and $ship.waretransport.indexof.{$entryCargoTransport}">
            <set_value name="$cargoHoldOk" exact="true"/>
          </do_elseif>
          <do_if value="not $cargoHoldOk">
            <continue/>
          </do_if>
        </do_if>

        <!-- Ware basket filter (applies to all cache search modes when basket is non-empty). -->
        <do_if value="$wareBasketCount gt 0">
          <set_value name="$entryWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$entryWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$entryWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$entryWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$entryWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <set_value name="$wareAllowed" exact="false"/>
          <do_all exact="$wareBasketCount" counter="$wbIdx">
            <do_if value="$wareBasket.{$wbIdx} == $entryWare">
              <set_value name="$wareAllowed" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $wareAllowed">
            <continue/>
          </do_if>
        </do_if>

        <!-- TTL / age check -->
        <do_if value="$entry.$CachedAt? and ($now - $entry.$CachedAt) gt $cacheMaxAge">
          <continue/>
        </do_if>

        <!-- Station existence (before distance / MK4 ware-type property access on station). -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="not $entryBuyStation? or not @$entryBuyStation.exists">
            <continue/>
          </do_if>
        </do_if>
        <do_if value="not $entrySellStation? or not @$entrySellStation.exists">
          <continue/>
        </do_if>
        <do_if value="not $entry.$IsSellOnly? and $entryBuyStation? and $entrySellStation? and @$entryBuyStation.exists and @$entrySellStation.exists and $entryBuyStation == $entrySellStation">
          <continue/>
        </do_if>

        <!-- MK4 policy filters (no-op for callers that don't pass these flags). -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$requirePlayerDeliveryStation">
            <set_value name="$mk4DeliveryPlayerOk" exact="false"/>
            <do_if value="$entrySellStation? and @$entrySellStation.exists and @$entrySellStation.isplayerowned">
              <set_value name="$mk4DeliveryPlayerOk" exact="true"/>
            </do_if>
            <do_elseif value="$entrySellStation? and $entrySellStation.isclass.buildstorage and $entrySellStation.base? and @$entrySellStation.base.isplayerowned">
              <set_value name="$mk4DeliveryPlayerOk" exact="true"/>
            </do_elseif>
            <do_if value="not $mk4DeliveryPlayerOk">
              <continue/>
            </do_if>
          </do_if>
          <do_if value="$requirePlayerSupplierStation and (not $entryBuyStation? or not @$entryBuyStation.isplayerowned)">
            <continue/>
          </do_if>
          <do_if value="$requireNonPlayerSupplierStation and (not $entryBuyStation? or @$entryBuyStation.isplayerowned)">
            <continue/>
          </do_if>
        </do_if>
        <!-- 'Ignore Player Pricing' companion filter: drop any entry (including sell-only disposal)
             whose delivery destination is a player-owned station. -->
        <do_if value="$requireNonPlayerDeliveryStation and $entrySellStation? and @$entrySellStation.isplayerowned">
          <continue/>
        </do_if>
        <!-- MK4 serveHomeOnly: delivery must match home anchor (station + build storage, or sector). -->
        <do_if value="$mk4DedicatedServe and not $mk4BuildStorageOnlyMode">
          <set_value name="$serveHomeAnchor" exact="if $mk4AnchorHome? and $mk4AnchorHome.exists then $mk4AnchorHome else $homeSector"/>
          <set_value name="$serveHomeSector" exact="if $serveHomeAnchor? and $serveHomeAnchor.isclass.sector then $serveHomeAnchor else (if $serveHomeAnchor? and $serveHomeAnchor.sector? then @$serveHomeAnchor.sector else $homeSector)"/>
          <set_value name="$serveHomeMatch" exact="false"/>
          <do_if value="$serveHomeAnchor? and $serveHomeAnchor.isclass.station">
            <do_if value="$entrySellStation? and $entrySellStation.exists and $serveHomeAnchor.exists">
              <do_if value="$entrySellStation == $serveHomeAnchor">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_if>
              <do_elseif value="$serveHomeAnchor.buildstorage? and $serveHomeAnchor.buildstorage.exists and $entrySellStation == $serveHomeAnchor.buildstorage">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
              <do_elseif value="$entrySellStation.isclass.buildstorage and $entrySellStation.base? and $entrySellStation.base.exists and $entrySellStation.base == $serveHomeAnchor">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
              <do_elseif value="$entrySellStation.hascontext.{$serveHomeAnchor}">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
              <do_elseif value="$serveHomeAnchor.hascontext.{$entrySellStation}">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
            </do_if>
            <do_if value="not $serveHomeMatch">
              <continue/>
            </do_if>
          </do_if>
          <do_elseif value="$serveHomeSector? and $serveHomeSector.exists">
            <do_if value="not $entrySellStation? or not $entrySellStation.sector? or @$entrySellStation.sector != $serveHomeSector">
              <continue/>
            </do_if>
          </do_elseif>
        </do_if>
        <!-- MK4 build-storage-only mode: BS buyers within jumpDistanceCoverage; no BS supplier legs. -->
        <do_if value="$mk4BuildStorageOnlyMode and not $entry.$IsSellOnly?">
          <do_if value="$entryBuyStation? and @$entryBuyStation.isclass.buildstorage">
            <continue/>
          </do_if>
          <do_if value="not $entrySellStation? or not @$entrySellStation.isclass.buildstorage">
            <continue/>
          </do_if>
          <!-- BS-only delivery scope: player build storage within jumpDistanceCoverage from home. -->
          <set_value name="$mk4BsoCoverageMax" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
          <set_value name="$mk4BsoInScope" exact="false"/>
          <set_value name="$mk4BsoDist" exact="if $homeSector? and $entrySellStation? and $entrySellStation.sector? then $homeSector.gatedistance.{$entrySellStation.sector} else -1"/>
          <do_if value="$mk4BsoDist ge 0 and ($mk4BsoCoverageMax le 0 or $mk4BsoDist le $mk4BsoCoverageMax)">
            <set_value name="$mk4BsoInScope" exact="true"/>
          </do_if>
          <do_if value="not $mk4BsoInScope">
            <continue/>
          </do_if>
        </do_if>
        <!-- MK4 ware-type policy filter (cache-phase parity with match-phase). -->
        <do_if value="not $entry.$IsSellOnly? and $entrySellStation? and (not $entrySellStation.isclass.buildstorage or $ignoreBuildStorage)">
          <set_value name="$entryTypeWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$entryTypeWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$entryTypeWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$entryTypeWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$entryTypeWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <do_if value="$entryTypeWare?">
            <set_value name="$mk4IsTradeWare" exact="$entrySellStation.tradewares.{$entryTypeWare}.exists"/>
            <set_value name="$mk4IsResource" exact="$entrySellStation.resources.{$entryTypeWare}.exists"/>
            <set_value name="$mk4IsProduct" exact="$entrySellStation.products.{$entryTypeWare}.exists"/>
            <set_value name="$mk4IsIntermediate" exact="false"/>
            <do_if value="$entrySellStation.resources.{$entryTypeWare}.exists and @$entrySellStation.resources.{$entryTypeWare}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <do_if value="$entrySellStation.products.{$entryTypeWare}.exists and @$entrySellStation.products.{$entryTypeWare}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <set_value name="$mk4IsPureResource" exact="$mk4IsResource and not $mk4IsIntermediate"/>
            <set_value name="$mk4IsIntermediateOrProduct" exact="$mk4IsIntermediate or $mk4IsProduct"/>
            <set_value name="$mk4HasKnownType" exact="$mk4IsTradeWare or $mk4IsResource or $mk4IsProduct"/>
            <set_value name="$mk4AllowedByType" exact="false"/>
            <do_if value="$mk4IsTradeWare and $mk4AllowTradewares">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsPureResource and $mk4AllowResources">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsIntermediateOrProduct and $mk4AllowIntermediates">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="$mk4HasKnownType and not $mk4AllowedByType">
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Distance check with per-leg limits (sector-to-sector; station refs break gatedistance). -->
        <do_if value="$maxDistanceBuyLeg gt 0 and $entryBuyStation?">
          <set_value name="$distBuy" exact="-1"/>
          <do_if value="$entryBuyStation.sector? and $entryBuyStation.sector == $homeSector">
            <set_value name="$distBuy" exact="0"/>
          </do_if>
          <do_elseif value="$entryBuyStation.sector?">
            <set_value name="$distBuy" exact="$homeSector.gatedistance.{$entryBuyStation.sector}"/>
          </do_elseif>
          <do_if value="$distBuy lt 0 or $distBuy gt $maxDistanceBuyLeg">
            <continue/>
          </do_if>
        </do_if>
        <do_if value="$maxDistanceSellLeg gt 0 and $entrySellStation?">
          <set_value name="$distSell" exact="-1"/>
          <do_if value="$entrySellStation.sector? and $entrySellStation.sector == $homeSector">
            <set_value name="$distSell" exact="0"/>
          </do_if>
          <do_elseif value="$entrySellStation.sector?">
            <set_value name="$distSell" exact="$homeSector.gatedistance.{$entrySellStation.sector}"/>
          </do_elseif>
          <do_if value="$distSell lt 0 or $distSell gt $maxDistanceSellLeg">
            <continue/>
          </do_if>
        </do_if>

        <!-- ROI / absolute profit check (sell-mode trades only) -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$minAbsoluteProfit gt 0 and $entry.$Profit? and $entry.$Profit lt $minAbsoluteProfit">
            <continue/>
          </do_if>
          <do_if value="$minROI gt 0 and $entry.$BuyPrice? and $entry.$BuyPrice gt 0">
            <set_value name="$entryROI" exact="($entry.$UnitProfit * 100) / $entry.$BuyPrice"/>
            <do_if value="$entryROI lt $minROI">
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Cache Dropoff Tolerance: reject if profit dropped too much since caching -->
        <do_if value="$cacheDropoffTolerance gt 0 and not $entry.$IsSellOnly? and $entry.$UnitProfit? and $entry.$UnitProfit gt 0 and $entry.$BuyOffer? and $entry.$SellOffer?">
          <!-- Only check if both offers still exist (otherwise station-existence check will catch it) -->
          <do_if value="@$entry.$BuyOffer.exists and @$entry.$SellOffer.exists">
            <set_value name="$currentBuyPrice" exact="@$entry.$BuyOffer.unitprice"/>
            <set_value name="$currentSellPrice" exact="@$entry.$SellOffer.unitprice"/>
            <do_if value="$currentBuyPrice? and $currentSellPrice? and $currentBuyPrice gt 0">
              <set_value name="$currentUnitProfit" exact="$currentSellPrice - $currentBuyPrice"/>
              <!-- Calculate how much profit has dropped as % of original -->
              <do_if value="$currentUnitProfit le 0">
                <!-- Profit went negative â€” always reject -->
                <continue/>
              </do_if>
              <set_value name="$profitDropPct" exact="(($entry.$UnitProfit - $currentUnitProfit) * 100) / $entry.$UnitProfit"/>
              <do_if value="$profitDropPct gt $cacheDropoffTolerance">
                <continue/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>

        <!-- Average-price band filter: quantityfactor vs ware.averageprice (per-ship; drift since cache write). -->
        <do_if value="$bandPriceCheckActive? and $bandPriceCheckActive">
          <set_value name="$isSellOnlyFilter" exact="$entry.$IsSellOnly? and $entry.$IsSellOnly"/>
          <set_value name="$skipSupplierBandFilter" exact="false"/>
          <do_if value="$entry.$PlayerFreeSupplier? and $entry.$PlayerFreeSupplier">
            <set_value name="$skipSupplierBandFilter" exact="true"/>
          </do_if>
          <do_if value="not $skipSupplierBandFilter and $bypassPlayerSellerPricing? and $bypassPlayerSellerPricing and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.owner.isplayerowned">
            <set_value name="$skipSupplierBandFilter" exact="true"/>
          </do_if>
          <set_value name="$filterCustomerQty" exact="null"/>
          <set_value name="$filterSupplierQty" exact="null"/>
          <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists">
            <do_if value="$entry.$SellOffer.quantityfactor?">
              <set_value name="$filterCustomerQty" exact="@$entry.$SellOffer.quantityfactor"/>
            </do_if>
            <do_elseif value="$entry.$SellOffer.unitprice? and $entry.$SellOffer.ware? and @$entry.$SellOffer.ware.averageprice gt 0">
              <set_value name="$filterCustomerQty" exact="@$entry.$SellOffer.unitprice / (@$entry.$SellOffer.ware.averageprice * 100)"/>
            </do_elseif>
            <do_else>
              <continue/>
            </do_else>
            <do_if value="$filterCustomerQty? and $filterCustomerQty lt $bandCustomerQtyMin">
              <continue/>
            </do_if>
          </do_if>
          <do_else>
            <continue/>
          </do_else>
          <do_if value="not $isSellOnlyFilter and not $skipSupplierBandFilter">
            <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists">
              <do_if value="$entry.$BuyOffer.quantityfactor?">
                <set_value name="$filterSupplierQty" exact="@$entry.$BuyOffer.quantityfactor"/>
              </do_if>
              <do_elseif value="$entry.$BuyOffer.unitprice? and $entry.$BuyOffer.ware? and @$entry.$BuyOffer.ware.averageprice gt 0">
                <set_value name="$filterSupplierQty" exact="@$entry.$BuyOffer.unitprice / (@$entry.$BuyOffer.ware.averageprice * 100)"/>
              </do_elseif>
              <do_else>
                <continue/>
              </do_else>
              <do_if value="$filterSupplierQty? and $filterSupplierQty gt $bandSupplierQtyMax">
                <continue/>
              </do_if>
            </do_if>
            <do_else>
              <continue/>
            </do_else>
            <do_if value="$filterCustomerQty? and $filterSupplierQty?">
              <do_if value="($filterCustomerQty - $filterSupplierQty) lt $bandMinQtySpread">
                <continue/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>

        <!-- Build storage exclusion -->
        <do_if value="$ignoreBuildStorage">
          <do_if value="($entryBuyStation? and @$entryBuyStation.isclass.buildstorage) or ($entrySellStation? and @$entrySellStation.isclass.buildstorage)">
            <continue/>
          </do_if>
        </do_if>

        <!-- Carrier / auxiliary exclusion (stations are never carriers/auxiliaries, only ships can be) -->
        <do_if value="$ignoreCarrierAux">
          <do_if value="($entryBuyStation? and @$entryBuyStation.isclass.ship and (@$entryBuyStation.type == shiptype.carrier or @$entryBuyStation.type == shiptype.resupplier)) or ($entrySellStation? and @$entrySellStation.isclass.ship and (@$entrySellStation.type == shiptype.carrier or @$entrySellStation.type == shiptype.resupplier))">
            <continue/>
          </do_if>
        </do_if>

        <!-- Offer amount pre-filter (CHEAP: universal amount check; do NOT gate on .available alone).
             Build-storage delivery buy-offers often keep .available=false while cargo deficit exists. -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists">
            <set_value name="$preBuyAmtQuick" exact="@$entry.$BuyOffer.amount"/>
            <do_if value="not $preBuyAmtQuick? or $preBuyAmtQuick le 0">
              <set_value name="$preBuyAmtQuick" exact="0"/>
              <do_if value="$entryBuyStation? and @$entryBuyStation.exists">
                <set_value name="$preBuyWareQuick" exact="if $entry.$Ware? then $entry.$Ware else null"/>
                <do_if value="not $preBuyWareQuick? and @$entry.$BuyOffer.ware != null">
                  <set_value name="$preBuyWareQuick" exact="@$entry.$BuyOffer.ware"/>
                </do_if>
                <do_if value="$preBuyWareQuick?">
                  <get_ware_reservation object="$entryBuyStation" ware="$preBuyWareQuick" type="buy" virtual="false" result="$preBuyResQuick"/>
                  <set_value name="$preBuyAmtQuick" exact="[$entryBuyStation.cargo.{$preBuyWareQuick}.count - $preBuyResQuick, 0].max"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="not $preBuyAmtQuick? or $preBuyAmtQuick le 0">
              <continue/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists">
          <do_if value="@$entry.$SellOffer.amount le 0">
            <set_value name="$sellOfferDemandFallback" exact="0"/>
            <do_if value="$entrySellStation? and @$entrySellStation.exists">
              <set_value name="$sellOfferDemandWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
              <do_if value="not $sellOfferDemandWare? and @$entry.$SellOffer.ware != null">
                <set_value name="$sellOfferDemandWare" exact="@$entry.$SellOffer.ware"/>
              </do_if>
              <do_if value="$sellOfferDemandWare?">
                <set_value name="$sellOfferDemandFallback" exact="[0, $entrySellStation.cargo.{$sellOfferDemandWare}.target - $entrySellStation.cargo.{$sellOfferDemandWare}.count].max"/>
              </do_if>
            </do_if>
            <do_if value="$sellOfferDemandFallback le 0">
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Offer capacity check (EXPENSIVE: per-ship, considers pending trade reservations).
             Skip entries where offeramount.{ship} is 0 â€” station capacity is fully reserved
             by other ships' pending trades. Without this check, the scanner would return 50
             entries all pointing to saturated stations while valid entries deeper in the cache
             go unseen. Per-ware quota below restores diversification without skipping saturated entries entirely. -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists">
            <set_value name="$preCheckBuyAmt" exact="@$entry.$BuyOffer.offeramount.{$ship}"/>
            <do_if value="(not $preCheckBuyAmt? or $preCheckBuyAmt le 0) and @$entry.$BuyOffer.amount gt 0">
              <set_value name="$preCheckBuyAmt" exact="@$entry.$BuyOffer.amount"/>
            </do_if>
            <!-- Target-count demand fallback (mirrors lib.gt.tradematch + gt_context_diagnose). -->
            <do_if value="(not $preCheckBuyAmt? or $preCheckBuyAmt le 0) and $entrySellStation? and $entrySellStation.exists">
              <set_value name="$preCheckBuyWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
              <do_if value="not $preCheckBuyWare? and @$entry.$BuyOffer.ware != null">
                <set_value name="$preCheckBuyWare" exact="@$entry.$BuyOffer.ware"/>
              </do_if>
              <do_if value="$preCheckBuyWare?">
                <set_value name="$preCheckBuyAmt" exact="[0, $entrySellStation.cargo.{$preCheckBuyWare}.target - $entrySellStation.cargo.{$preCheckBuyWare}.count].max"/>
              </do_if>
            </do_if>
            <do_if value="not $preCheckBuyAmt? or $preCheckBuyAmt le 0">
              <continue/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists">
          <set_value name="$preCheckSellAmt" exact="@$entry.$SellOffer.offeramount.{$ship}"/>
          <do_if value="(not $preCheckSellAmt? or $preCheckSellAmt le 0) and @$entry.$SellOffer.amount gt 0">
            <set_value name="$preCheckSellAmt" exact="@$entry.$SellOffer.amount"/>
          </do_if>
          <!-- Target-count demand fallback (mirrors lib.gt.tradematch + gt_context_diagnose). -->
          <do_if value="(not $preCheckSellAmt? or $preCheckSellAmt le 0) and $entrySellStation? and $entrySellStation.exists">
            <set_value name="$preCheckSellWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
            <do_if value="not $preCheckSellWare? and @$entry.$SellOffer.ware != null">
              <set_value name="$preCheckSellWare" exact="@$entry.$SellOffer.ware"/>
            </do_if>
            <do_if value="$preCheckSellWare?">
              <set_value name="$preCheckSellAmt" exact="[0, $entrySellStation.cargo.{$preCheckSellWare}.target - $entrySellStation.cargo.{$preCheckSellWare}.count].max"/>
            </do_if>
          </do_if>
          <do_if value="not $preCheckSellAmt? or $preCheckSellAmt le 0">
            <continue/>
          </do_if>
        </do_if>

        <!-- Hard minimum cargo utilization pre-filter (cache path only, excluded in isolated mode).
             Uses available reserved-aware offer amounts to estimate max feasible load. -->
        <do_if value="$enableMinCargoUtil and not $isIsolatedMode and not $entry.$IsSellOnly?">
          <set_value name="$minUtilVolumePerUnit" exact="1"/>
          <do_if value="$entry.$Ware? and $entry.$Ware.volume?">
            <set_value name="$minUtilVolumePerUnit" exact="$entry.$Ware.volume"/>
          </do_if>
          <set_value name="$minUtilAmountLimit" exact="$preCheckSellAmt"/>
          <do_if value="$preCheckBuyAmt? and $preCheckBuyAmt lt $minUtilAmountLimit">
            <set_value name="$minUtilAmountLimit" exact="$preCheckBuyAmt"/>
          </do_if>
          <do_if value="$entry.$Amount? and $entry.$Amount gt 0 and $entry.$Amount lt $minUtilAmountLimit">
            <set_value name="$minUtilAmountLimit" exact="$entry.$Amount"/>
          </do_if>
          <set_value name="$minUtilTradeVolume" exact="$minUtilAmountLimit * $minUtilVolumePerUnit"/>
          <set_value name="$minUtilCapBucket" exact="$ship.cargo.capacity.all"/>
          <set_value name="$minUtilRequiredVolume" exact="($minUtilCapBucket * $cargoUtilThresholdPct) / 100.0"/>
          <do_if value="$minUtilTradeVolume lt $minUtilRequiredVolume">
            <continue/>
          </do_if>
        </do_if>

        <!-- Reservation check: skip trades reserved by other ships (same rule as MD reservations).
             Uses SellOffer object as key (Method B from GT_GenerateTradeKey â€” most reliable, offer.id often unavailable). -->
        <do_if value="global.$GT_Reservations? and $entry.$SellOffer?">
          <set_value name="$resKey" exact="$entry.$SellOffer"/>
          <do_if value="global.$GT_Reservations.{$resKey}?">
            <set_value name="$resData" exact="global.$GT_Reservations.{$resKey}"/>
            <!-- Only skip if reservation is unexpired AND belongs to a different ship -->
            <do_if value="$resData.$Until? and player.age lt @$resData.$Until and $resData.$Ship? and @$resData.$Ship != $ship">
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Per-ware quota gate (after all filters â€” only count shippable candidates). -->
        <set_value name="$quotaWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
        <do_if value="not $quotaWare? and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
          <set_value name="$quotaWare" exact="@$entry.$BuyOffer.ware"/>
        </do_if>
        <do_if value="not $quotaWare? and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
          <set_value name="$quotaWare" exact="@$entry.$SellOffer.ware"/>
        </do_if>
        <do_if value="$quotaWare?">
          <set_value name="$quotaWareFoundCount" exact="if $foundPerWare.{$quotaWare}? then $foundPerWare.{$quotaWare} else 0"/>
          <do_if value="$quotaWareFoundCount ge $perWareCap">
            <continue/>
          </do_if>
        </do_if>

        <!-- Trade rules + live profit gate (validation parity): run after offer-amount checks on live refs. -->
        <do_if value="not $entry.$IsSellOnly?">
          <set_value name="$trRuleBuyStation" exact="null"/>
          <do_if value="$entry.$BuyStation? and @$entry.$BuyStation.exists">
            <set_value name="$trRuleBuyStation" exact="$entry.$BuyStation"/>
          </do_if>
          <do_elseif value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists and $entry.$BuyOffer.owner? and @$entry.$BuyOffer.owner.exists">
            <set_value name="$trRuleBuyStation" exact="@$entry.$BuyOffer.owner"/>
          </do_elseif>
          <set_value name="$trRuleSellStation" exact="null"/>
          <do_if value="$entry.$SellStation? and @$entry.$SellStation.exists">
            <set_value name="$trRuleSellStation" exact="$entry.$SellStation"/>
          </do_if>
          <do_elseif value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.owner? and @$entry.$SellOffer.owner.exists">
            <set_value name="$trRuleSellStation" exact="@$entry.$SellOffer.owner"/>
          </do_elseif>
          <do_if value="not $ignoreTradeRules">
            <!-- Trade rules are a player-station feature only; NPCÃ—NPC cantradewith is not enforced. -->
            <set_value name="$trPlayerStationInvolved" exact="false"/>
            <do_if value="$trRuleBuyStation? and @$trRuleBuyStation.exists">
              <do_if value="@$trRuleBuyStation.isplayerowned">
                <set_value name="$trPlayerStationInvolved" exact="true"/>
              </do_if>
              <do_elseif value="@$trRuleBuyStation.isclass.buildstorage and $trRuleBuyStation.base? and @$trRuleBuyStation.base.exists and @$trRuleBuyStation.base.isplayerowned">
                <set_value name="$trPlayerStationInvolved" exact="true"/>
              </do_elseif>
            </do_if>
            <do_if value="not $trPlayerStationInvolved and $trRuleSellStation? and @$trRuleSellStation.exists">
              <do_if value="@$trRuleSellStation.isplayerowned">
                <set_value name="$trPlayerStationInvolved" exact="true"/>
              </do_if>
              <do_elseif value="@$trRuleSellStation.isclass.buildstorage and $trRuleSellStation.base? and @$trRuleSellStation.base.exists and @$trRuleSellStation.base.isplayerowned">
                <set_value name="$trPlayerStationInvolved" exact="true"/>
              </do_elseif>
            </do_if>
            <do_if value="$trPlayerStationInvolved">
              <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $trRuleBuyStation? and @$trRuleBuyStation.exists and not $entry.$SellOffer.cantradewith.{$trRuleBuyStation}">
                <continue/>
              </do_if>
              <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists and $trRuleSellStation? and @$trRuleSellStation.exists and not $entry.$BuyOffer.cantradewith.{$trRuleSellStation}">
                <continue/>
              </do_if>
            </do_if>
          </do_if>
          <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists and $entry.$SellOffer? and @$entry.$SellOffer.exists">
            <do_if value="$entry.$BuyOffer.unitprice? and $entry.$SellOffer.unitprice? and ($entry.$SellOffer.unitprice - $entry.$BuyOffer.unitprice) le 0">
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Entry passed all filters -->
        <append_to_list name="$tradeList" exact="$entry"/>
        <set_value name="$foundCount" operation="add"/>
        <do_if value="$quotaWare?">
          <set_value name="$foundPerWare.{$quotaWare}" exact="if $foundPerWare.{$quotaWare}? then ($foundPerWare.{$quotaWare} + 1) else 1"/>
        </do_if>
        <do_if value="this.$gt_cachePoolIsMk4">
          <do_if value="$entry.$Score gt $bestScore">
            <set_value name="$bestScore" exact="$entry.$Score"/>
            <set_value name="$bestTrade" exact="$entry"/>
          </do_if>
          <!-- MK4: stop once enough valid trades collected (home-sorted scan order). -->
          <do_if value="$foundCount ge $maxEntries">
            <break/>
          </do_if>
        </do_if>
        <do_if value="($visitIdx % 10) == 0">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield cache scan loop"/>
        </do_if>
      </do_all>

      <!-- When no trades matched, purge entries whose offers are globally exhausted (not transient per-ship reservation).
           Keeps pool count honest so scheduler escalates to live instead of parking on zombie rows. -->
      <set_value name="$purgedDeadCount" exact="0"/>
      <do_if value="$foundCount == 0 and $homeCache? and $homeCache.count gt 0">
        <set_value name="$deadScanCount" exact="@$homeCache.count"/>
        <do_all exact="$deadScanCount" counter="$ddi" reverse="true">
          <do_if value="$ddi gt $homeCache.count">
            <continue/>
          </do_if>
          <set_value name="$deadEntry" exact="@$homeCache.{$ddi}"/>
          <do_if value="not $deadEntry?">
            <continue/>
          </do_if>
          <set_value name="$deadRemove" exact="false"/>
          <set_value name="$deadSellStation" exact="null"/>
          <do_if value="$deadEntry.$SellStation? and @$deadEntry.$SellStation.exists">
            <set_value name="$deadSellStation" exact="$deadEntry.$SellStation"/>
          </do_if>
          <do_elseif value="$deadEntry.$SellOffer? and @$deadEntry.$SellOffer.exists and $deadEntry.$SellOffer.buyer? and @$deadEntry.$SellOffer.buyer.exists">
            <set_value name="$deadSellStation" exact="@$deadEntry.$SellOffer.buyer"/>
          </do_elseif>
          <do_if value="$deadEntry.$SellOffer? and @$deadEntry.$SellOffer.exists">
            <set_value name="$deadSellAmt" exact="@$deadEntry.$SellOffer.amount"/>
            <do_if value="not $deadSellAmt? or $deadSellAmt le 0">
              <set_value name="$deadSellDemand" exact="0"/>
              <do_if value="$deadSellStation? and @$deadSellStation.exists">
                <set_value name="$deadSellWare" exact="if $deadEntry.$Ware? then $deadEntry.$Ware else null"/>
                <do_if value="not $deadSellWare? and @$deadEntry.$SellOffer.ware != null">
                  <set_value name="$deadSellWare" exact="@$deadEntry.$SellOffer.ware"/>
                </do_if>
                <do_if value="$deadSellWare?">
                  <set_value name="$deadSellDemand" exact="[0, $deadSellStation.cargo.{$deadSellWare}.target - $deadSellStation.cargo.{$deadSellWare}.count].max"/>
                </do_if>
              </do_if>
              <do_if value="$deadSellDemand le 0">
                <set_value name="$deadRemove" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
          <do_if value="not $deadRemove and not $deadEntry.$IsSellOnly? and $deadEntry.$BuyOffer? and @$deadEntry.$BuyOffer.exists">
            <set_value name="$deadBuyAmt" exact="@$deadEntry.$BuyOffer.amount"/>
            <do_if value="not $deadBuyAmt? or $deadBuyAmt le 0">
              <set_value name="$deadBuySupply" exact="0"/>
              <set_value name="$deadBuyStation" exact="null"/>
              <do_if value="$deadEntry.$BuyStation? and @$deadEntry.$BuyStation.exists">
                <set_value name="$deadBuyStation" exact="$deadEntry.$BuyStation"/>
              </do_if>
              <do_elseif value="$deadEntry.$BuyOffer.seller? and @$deadEntry.$BuyOffer.seller.exists">
                <set_value name="$deadBuyStation" exact="@$deadEntry.$BuyOffer.seller"/>
              </do_elseif>
              <do_if value="$deadBuyStation? and @$deadBuyStation.exists">
                <set_value name="$deadBuyWare" exact="if $deadEntry.$Ware? then $deadEntry.$Ware else null"/>
                <do_if value="not $deadBuyWare? and @$deadEntry.$BuyOffer.ware != null">
                  <set_value name="$deadBuyWare" exact="@$deadEntry.$BuyOffer.ware"/>
                </do_if>
                <do_if value="$deadBuyWare?">
                  <get_ware_reservation object="$deadBuyStation" ware="$deadBuyWare" type="buy" virtual="false" result="$deadBuyRes"/>
                  <set_value name="$deadBuySupply" exact="[$deadBuyStation.cargo.{$deadBuyWare}.count - $deadBuyRes, 0].max"/>
                </do_if>
              </do_if>
              <do_if value="$deadBuySupply le 0">
                <set_value name="$deadRemove" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
          <!-- Unreadable for any ship with this fleet config: price band drift or cargo-util floor (diag omits these). -->
          <do_if value="not $deadRemove and $bandPriceCheckActive? and $bandPriceCheckActive and not ($deadEntry.$IsSellOnly? and $deadEntry.$IsSellOnly)">
            <set_value name="$deadSkipSupplierBand" exact="false"/>
            <do_if value="$deadEntry.$PlayerFreeSupplier? and $deadEntry.$PlayerFreeSupplier">
              <set_value name="$deadSkipSupplierBand" exact="true"/>
            </do_if>
            <do_if value="not $deadSkipSupplierBand and $bypassPlayerSellerPricing? and $bypassPlayerSellerPricing and $deadEntry.$BuyOffer? and @$deadEntry.$BuyOffer.exists and @$deadEntry.$BuyOffer.owner.isplayerowned">
              <set_value name="$deadSkipSupplierBand" exact="true"/>
            </do_if>
            <do_if value="$deadEntry.$SellOffer? and @$deadEntry.$SellOffer.exists">
              <set_value name="$deadCustQty" exact="null"/>
              <do_if value="$deadEntry.$SellOffer.quantityfactor?">
                <set_value name="$deadCustQty" exact="@$deadEntry.$SellOffer.quantityfactor"/>
              </do_if>
              <do_elseif value="$deadEntry.$SellOffer.unitprice? and $deadEntry.$SellOffer.ware? and @$deadEntry.$SellOffer.ware.averageprice gt 0">
                <set_value name="$deadCustQty" exact="@$deadEntry.$SellOffer.unitprice / (@$deadEntry.$SellOffer.ware.averageprice * 100)"/>
              </do_elseif>
              <do_else>
                <set_value name="$deadRemove" exact="true"/>
              </do_else>
              <do_if value="not $deadRemove and $deadCustQty? and $deadCustQty lt $bandCustomerQtyMin">
                <set_value name="$deadRemove" exact="true"/>
              </do_if>
              <do_if value="not $deadRemove and not $deadSkipSupplierBand and $deadEntry.$BuyOffer? and @$deadEntry.$BuyOffer.exists">
                <set_value name="$deadSupQty" exact="null"/>
                <do_if value="$deadEntry.$BuyOffer.quantityfactor?">
                  <set_value name="$deadSupQty" exact="@$deadEntry.$BuyOffer.quantityfactor"/>
                </do_if>
                <do_elseif value="$deadEntry.$BuyOffer.unitprice? and $deadEntry.$BuyOffer.ware? and @$deadEntry.$BuyOffer.ware.averageprice gt 0">
                  <set_value name="$deadSupQty" exact="@$deadEntry.$BuyOffer.unitprice / (@$deadEntry.$BuyOffer.ware.averageprice * 100)"/>
                </do_elseif>
                <do_else>
                  <set_value name="$deadRemove" exact="true"/>
                </do_else>
                <do_if value="not $deadRemove and $deadSupQty? and $deadSupQty gt $bandSupplierQtyMax">
                  <set_value name="$deadRemove" exact="true"/>
                </do_if>
                <do_if value="not $deadRemove and $deadCustQty? and $deadSupQty? and ($deadCustQty - $deadSupQty) lt $bandMinQtySpread">
                  <set_value name="$deadRemove" exact="true"/>
                </do_if>
              </do_if>
            </do_if>
            <do_elseif value="not ($deadEntry.$IsSellOnly? and $deadEntry.$IsSellOnly)">
              <set_value name="$deadRemove" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="not $deadRemove and $enableMinCargoUtil and not $isIsolatedMode and not ($deadEntry.$IsSellOnly? and $deadEntry.$IsSellOnly)">
            <set_value name="$deadMinSellAmt" exact="0"/>
            <set_value name="$deadMinBuyAmt" exact="0"/>
            <do_if value="$deadEntry.$SellOffer? and @$deadEntry.$SellOffer.exists">
              <set_value name="$deadMinSellAmt" exact="@$deadEntry.$SellOffer.offeramount.{$ship}"/>
              <do_if value="(not $deadMinSellAmt? or $deadMinSellAmt le 0) and @$deadEntry.$SellOffer.amount gt 0">
                <set_value name="$deadMinSellAmt" exact="@$deadEntry.$SellOffer.amount"/>
              </do_if>
            </do_if>
            <do_if value="$deadEntry.$BuyOffer? and @$deadEntry.$BuyOffer.exists">
              <set_value name="$deadMinBuyAmt" exact="@$deadEntry.$BuyOffer.offeramount.{$ship}"/>
              <do_if value="(not $deadMinBuyAmt? or $deadMinBuyAmt le 0) and @$deadEntry.$BuyOffer.amount gt 0">
                <set_value name="$deadMinBuyAmt" exact="@$deadEntry.$BuyOffer.amount"/>
              </do_if>
            </do_if>
            <set_value name="$deadMinVolPerUnit" exact="1"/>
            <do_if value="$deadEntry.$Ware? and $deadEntry.$Ware.volume?">
              <set_value name="$deadMinVolPerUnit" exact="$deadEntry.$Ware.volume"/>
            </do_if>
            <set_value name="$deadMinAmtLimit" exact="$deadMinSellAmt"/>
            <do_if value="$deadMinBuyAmt? and $deadMinBuyAmt lt $deadMinAmtLimit">
              <set_value name="$deadMinAmtLimit" exact="$deadMinBuyAmt"/>
            </do_if>
            <set_value name="$deadMinTradeVol" exact="$deadMinAmtLimit * $deadMinVolPerUnit"/>
            <set_value name="$deadMinCapBucket" exact="$ship.cargo.capacity.all"/>
            <set_value name="$deadMinRequiredVol" exact="($deadMinCapBucket * $cargoUtilThresholdPct) / 100.0"/>
            <do_if value="$deadMinTradeVol lt $deadMinRequiredVol">
              <set_value name="$deadRemove" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="$deadRemove">
            <do_if value="this.$gt_cachePoolIsMk4">
              <remove_value name="global.$GT_TradeCacheMK4.{$cacheHomeKey}.{$ddi}"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_TradeCache.{$cacheHomeKey}.{$ddi}"/>
            </do_else>
            <set_value name="$purgedDeadCount" operation="add"/>
          </do_if>
        </do_all>
        <do_if value="$purgedDeadCount gt 0">
          <set_value name="$homeCache" exact="null"/>
          <do_if value="this.$gt_cachePoolIsMk4">
            <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK4.{$cacheHomeKey}"/>
          </do_if>
          <do_else>
            <set_value name="$homeCache" exact="@global.$GT_TradeCache.{$cacheHomeKey}"/>
          </do_else>
          <set_value name="$homeCacheCount" exact="0"/>
          <do_if value="$homeCache?">
            <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-CacheSearch] ' + $ship.idcode + ': Read-time purge removed ' + $purgedDeadCount + ' unreadable entries from ' + $cacheHomeKey.knownname + ' (remaining: ' + $homeCacheCount + ')'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- MK3: per-ship route score, sort, truncate (fleet spread rotation happens in order validation). -->
      <do_if value="not this.$gt_cachePoolIsMk4 and $tradeList.count gt 0">
        <run_script name="'lib.gt.cache.score_for_ship'" result="$shipRouteScoreResult">
          <param name="tradeList" value="$tradeList"/>
          <param name="ship" value="$ship"/>
          <param name="distancePenalty" value="if $distancePenalty? then $distancePenalty else 0.1"/>
          <param name="blacklistGroup" value="if $blacklistGroup? then $blacklistGroup else blacklistgroup.civilian"/>
          <param name="maxEntries" value="$maxEntries"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
        <do_if value="$shipRouteScoreResult? and $shipRouteScoreResult.$SortedTrades?">
          <set_value name="$tradeList" exact="$shipRouteScoreResult.$SortedTrades"/>
        </do_if>
        <do_if value="$shipRouteScoreResult? and $shipRouteScoreResult.$BestTrade?">
          <set_value name="$bestTrade" exact="$shipRouteScoreResult.$BestTrade"/>
        </do_if>
        <do_if value="$shipRouteScoreResult? and $shipRouteScoreResult.$BestScore?">
          <set_value name="$bestScore" exact="$shipRouteScoreResult.$BestScore"/>
        </do_if>
        <do_if value="$tradeList.count == 0">
          <set_value name="$bestTrade" exact="null"/>
          <set_value name="$bestScore" exact="0"/>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList.count gt 0">
          <debug_text text="'[GT-CacheSearch] ' + $ship.idcode + ': Ship-route scored ' + $tradeList.count + ' cache trades (top ShipScore=' + $bestScore + ')'" chance="100"/>
        </do_if>
      </do_if>

      <return value="table[
        $Found = ($bestTrade != null),
        $BestTrade = $bestTrade,
        $BestScore = $bestScore,
        $TradeList = $tradeList,
        $PurgedStale = $purgedStaleCount,
        $PoolSizeAfter = $homeCacheCount
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.cache.write" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="2">
  <!-- Writes trade results into the global trade cache with sorted insertion (by Score descending).
       Runs in AI script context so <wait> can be used to yield between insertions,
       preventing frame drops while maintaining sort order atomically per entry.

       cachePool selects the storage bucket: mk3 (GalaxyTraderMK3) or mk4 (GalaxyTraderMK4Supply).

       Each insertion (linear search + insert) runs without yielding = atomic.
       Yields happen only BETWEEN entries, so concurrent writers to the same
       home sector cache see consistent state at each insertion boundary.

       Also performs write-time cleanup of expired/dead entries before insertion. -->
  <params>
    <param name="cachePool" default="'mk3'" comment="Trade cache pool: mk3 (traders) or mk4 (supply)"/>
    <param name="tradeList" default="[]"/>
    <param name="homeSector"/>
    <param name="cacheTTL" default="300s"/>
    <param name="maxSearchDistance" default="0"/> <!-- For per-pool max-distance metadata tracking -->
    <param name="cacheDropoffTolerance" default="15"/> <!-- Accepted at call site for API compat; band filter is read-time only (lib.gt.cache.search). -->
    <param name="sellPriceMax" default="1.0" comment="Unused at write; per-ship band filter runs at cache read."/>
    <param name="buyPriceMin" default="-1.0" comment="Unused at write; per-ship band filter runs at cache read."/>
    <param name="debugchance" default="0"/>
  </params>
  <patch sinceversion="2">
    <do_if value="not $cachePool?">
      <set_value name="$cachePool" exact="'mk3'"/>
    </do_if>
  </patch>
  <attention min="unknown">
    <actions>
      <set_value name="this.$gt_cachePoolIsMk4" exact="$cachePool == 'mk4'"/>

      <!-- Read performance settings from global settings -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>
      <set_value name="this.$writeBatchSize" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize?">
        <set_value name="this.$writeBatchSize" exact="[1, @global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize].max"/>
      </do_if>
      <set_value name="this.$writeBatchSize" exact="(this.$writeBatchSize)i"/>
      <set_value name="this.$cleanupBatchSize" exact="50"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize?">
        <set_value name="this.$cleanupBatchSize" exact="[10, @global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize].max"/>
      </do_if>
      <set_value name="this.$cleanupBatchSize" exact="(this.$cleanupBatchSize)i"/>

      <!-- Early exit if nothing to write -->
      <do_if value="$tradeList.count == 0 or not $homeSector?">
        <return value="table[$Written = 0, $Cleaned = 0, $CacheSize = 0]"/>
      </do_if>

      <!-- Ensure cache structure exists for the selected pool -->
      <do_if value="this.$gt_cachePoolIsMk4">
        <do_if value="not global.$GT_TradeCacheMK4?">
          <set_value name="global.$GT_TradeCacheMK4" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_TradeCacheMK4.{$homeSector}?">
          <set_value name="global.$GT_TradeCacheMK4.{$homeSector}" exact="[]"/>
        </do_if>
      </do_if>
      <do_else>
        <do_if value="not global.$GT_TradeCache?">
          <set_value name="global.$GT_TradeCache" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_TradeCache.{$homeSector}?">
          <set_value name="global.$GT_TradeCache.{$homeSector}" exact="[]"/>
        </do_if>
      </do_else>

      <set_value name="$cacheNow" exact="player.age"/>

      <!-- Phase 1: Write-time cleanup -->
      <set_value name="$expiredCount" exact="0"/>
      <set_value name="$cleanupSize" exact="0"/>
      <do_if value="this.$gt_cachePoolIsMk4">
        <set_value name="$cleanupSize" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.count != null then @global.$GT_TradeCacheMK4.{$homeSector}.count else 0"/>
      </do_if>
      <do_else>
        <set_value name="$cleanupSize" exact="if @global.$GT_TradeCache.{$homeSector}.count != null then @global.$GT_TradeCache.{$homeSector}.count else 0"/>
      </do_else>
      <do_all exact="$cleanupSize" counter="$ci" reverse="true">
        <set_value name="$liveCleanupCount" exact="0"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$liveCleanupCount" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.count != null then @global.$GT_TradeCacheMK4.{$homeSector}.count else 0"/>
        </do_if>
        <do_else>
          <set_value name="$liveCleanupCount" exact="if @global.$GT_TradeCache.{$homeSector}.count != null then @global.$GT_TradeCache.{$homeSector}.count else 0"/>
        </do_else>
        <do_if value="$ci gt $liveCleanupCount">
          <continue/>
        </do_if>
        <set_value name="$oldEntry" exact="null"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$oldEntry" exact="@global.$GT_TradeCacheMK4.{$homeSector}.{$ci}"/>
        </do_if>
        <do_else>
          <set_value name="$oldEntry" exact="@global.$GT_TradeCache.{$homeSector}.{$ci}"/>
        </do_else>
        <do_if value="not $oldEntry?">
          <do_if value="$ci le $liveCleanupCount">
            <do_if value="this.$gt_cachePoolIsMk4">
              <remove_value name="global.$GT_TradeCacheMK4.{$homeSector}.{$ci}"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_TradeCache.{$homeSector}.{$ci}"/>
            </do_else>
            <set_value name="$expiredCount" operation="add"/>
          </do_if>
          <continue/>
        </do_if>

        <set_value name="$oldTs" exact="@$oldEntry.$CachedAt"/>
        <do_if value="$oldTs == null">
          <set_value name="$oldTs" exact="@$oldEntry.$Timestamp"/>
        </do_if>

        <set_value name="$isStale" exact="false"/>
        <do_if value="$oldTs != null and ($cacheNow - $oldTs) gt $cacheTTL">
          <set_value name="$isStale" exact="true"/>
        </do_if>
        <set_value name="$oldReResolvable" exact="(@$oldEntry.$Ware != null or @$oldEntry.$DeliveryStationName != null) and (@$oldEntry.$DeliveryStationId != null or @$oldEntry.$DeliveryStationName != null) and ((@$oldEntry.$SellSector != null and @$oldEntry.$SellSector.exists) or @$oldEntry.$SellSectorId != null or @$oldEntry.$DeliveryStationId != null)"/>
        <do_if value="not $isStale and @$oldEntry.$BuyOffer != null and not @$oldEntry.$BuyOffer.exists">
          <set_value name="$isStale" exact="true"/>
        </do_if>
        <!-- Dead delivery offer/station refs are normal when buy offers refresh; permanent keys allow re-discovery at read. -->
        <do_if value="not $isStale and not $oldReResolvable and @$oldEntry.$SellOffer != null and not @$oldEntry.$SellOffer.exists">
          <set_value name="$isStale" exact="true"/>
        </do_if>
        <do_if value="not $isStale and not $oldReResolvable and @$oldEntry.$SellStation != null and not @$oldEntry.$SellStation.exists">
          <set_value name="$isStale" exact="true"/>
        </do_if>

        <do_if value="$isStale">
          <set_value name="$liveBeforeRemove" exact="0"/>
          <do_if value="this.$gt_cachePoolIsMk4">
            <set_value name="$liveBeforeRemove" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.count != null then @global.$GT_TradeCacheMK4.{$homeSector}.count else 0"/>
          </do_if>
          <do_else>
            <set_value name="$liveBeforeRemove" exact="if @global.$GT_TradeCache.{$homeSector}.count != null then @global.$GT_TradeCache.{$homeSector}.count else 0"/>
          </do_else>
          <do_if value="$ci le $liveBeforeRemove">
            <do_if value="this.$gt_cachePoolIsMk4">
              <remove_value name="global.$GT_TradeCacheMK4.{$homeSector}.{$ci}"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_TradeCache.{$homeSector}.{$ci}"/>
            </do_else>
            <set_value name="$expiredCount" operation="add"/>
          </do_if>
        </do_if>

        <set_value name="$ciInt" exact="($ci)i"/>
        <do_if value="($ciInt % this.$cleanupBatchSize) == 0">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield cleanup loop"/>
        </do_if>
      </do_all>

      <set_value name="$poolLabel" exact="if this.$gt_cachePoolIsMk4 then 'MK4' else 'MK3'"/>
      <do_if value="$expiredCount gt 0 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$remainingAfterCleanup" exact="0"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$remainingAfterCleanup" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.count != null then @global.$GT_TradeCacheMK4.{$homeSector}.count else 0"/>
        </do_if>
        <do_else>
          <set_value name="$remainingAfterCleanup" exact="if @global.$GT_TradeCache.{$homeSector}.count != null then @global.$GT_TradeCache.{$homeSector}.count else 0"/>
        </do_else>
        <debug_text text="'[GT-CacheWrite] ' + this.ship.idcode + ': (' + $poolLabel + ') Write-time cleanup removed ' + $expiredCount + ' expired/stale entries from ' + $homeSector.knownname + ' (remaining: ' + $remainingAfterCleanup + ')'" chance="100"/>
      </do_if>

      <!-- Phase 2: Sorted insertion by $Score descending -->
      <do_all exact="$tradeList.count" counter="$ti">
        <set_value name="$newTrade" exact="$tradeList.{$ti}"/>
        <set_value name="$newTrade.$CachedAt" exact="$cacheNow"/>
        <set_value name="$newTrade.$Timestamp" exact="$cacheNow"/>
        <!-- Snapshot delivery station name so diagnose can show stale cache rows after offer refs die. -->
        <do_if value="not $newTrade.$DeliveryStationName? and $newTrade.$SellStation? and @$newTrade.$SellStation.exists and @$newTrade.$SellStation.knownname">
          <set_value name="$newTrade.$DeliveryStationName" exact="@$newTrade.$SellStation.knownname"/>
        </do_if>
        <do_if value="not $newTrade.$DeliveryStationName? and $newTrade.$SellOffer? and @$newTrade.$SellOffer.exists">
          <do_if value="$newTrade.$SellOffer.buyer? and @$newTrade.$SellOffer.buyer.exists and @$newTrade.$SellOffer.buyer.knownname">
            <set_value name="$newTrade.$DeliveryStationName" exact="@$newTrade.$SellOffer.buyer.knownname"/>
          </do_if>
          <do_elseif value="$newTrade.$SellOffer.owner? and @$newTrade.$SellOffer.owner.exists and @$newTrade.$SellOffer.owner.knownname">
            <set_value name="$newTrade.$DeliveryStationName" exact="@$newTrade.$SellOffer.owner.knownname"/>
          </do_elseif>
        </do_if>
        <!-- Stable delivery keys: customer buy-offer refs die on refresh; idcode + sector + ware re-discover the live offer. -->
        <do_if value="not $newTrade.$SellStationBase?">
          <set_value name="$wAnchorSell" exact="null"/>
          <do_if value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists">
            <set_value name="$wAnchorSell" exact="@$newTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $newTrade.$SellOffer.buyer? and @$newTrade.$SellOffer.buyer.exists">
            <set_value name="$wAnchorSell" exact="@$newTrade.$SellOffer.buyer"/>
          </do_elseif>
          <do_if value="$wAnchorSell? and @$wAnchorSell.isclass.buildstorage and $wAnchorSell.base? and @$wAnchorSell.base.exists">
            <set_value name="$newTrade.$SellStationBase" exact="@$wAnchorSell.base"/>
          </do_if>
        </do_if>
        <do_if value="not $newTrade.$DeliveryStationId?">
          <set_value name="$wIdSell" exact="null"/>
          <do_if value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists">
            <set_value name="$wIdSell" exact="@$newTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $newTrade.$SellOffer.buyer? and @$newTrade.$SellOffer.buyer.exists">
            <set_value name="$wIdSell" exact="@$newTrade.$SellOffer.buyer"/>
          </do_elseif>
          <do_if value="$wIdSell? and @$wIdSell.exists">
            <do_if value="@$wIdSell.isclass.buildstorage and $wIdSell.base? and @$wIdSell.base.exists">
              <set_value name="$newTrade.$DeliveryStationId" exact="@$wIdSell.base.idcode"/>
            </do_if>
            <do_else>
              <set_value name="$newTrade.$DeliveryStationId" exact="@$wIdSell.idcode"/>
            </do_else>
          </do_if>
        </do_if>
        <do_if value="not $newTrade.$SellSectorId?">
          <set_value name="$wSecSell" exact="null"/>
          <do_if value="$newTrade.$SellSector? and @$newTrade.$SellSector.exists and $newTrade.$SellSector.idcode?">
            <set_value name="$wSecSell" exact="@$newTrade.$SellSector.idcode"/>
          </do_if>
          <do_elseif value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists and $newTrade.$SellStation.sector? and @$newTrade.$SellStation.sector.exists and $newTrade.$SellStation.sector.idcode?">
            <set_value name="$wSecSell" exact="@$newTrade.$SellStation.sector.idcode"/>
          </do_elseif>
          <do_if value="$wSecSell?">
            <set_value name="$newTrade.$SellSectorId" exact="$wSecSell"/>
          </do_if>
        </do_if>
        <do_if value="not $newTrade.$SupplierStationId?">
          <set_value name="$wIdBuy" exact="null"/>
          <do_if value="$newTrade.$BuyStation? and @$newTrade.$BuyStation.exists and $newTrade.$BuyStation.idcode?">
            <set_value name="$wIdBuy" exact="@$newTrade.$BuyStation.idcode"/>
          </do_if>
          <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $newTrade.$BuyOffer.seller? and @$newTrade.$BuyOffer.seller.exists and $newTrade.$BuyOffer.seller.idcode?">
            <set_value name="$wIdBuy" exact="@$newTrade.$BuyOffer.seller.idcode"/>
          </do_elseif>
          <do_if value="$wIdBuy?">
            <set_value name="$newTrade.$SupplierStationId" exact="$wIdBuy"/>
          </do_if>
        </do_if>
        <do_if value="not $newTrade.$BuySectorId?">
          <set_value name="$wSecBuy" exact="null"/>
          <do_if value="$newTrade.$BuySector? and @$newTrade.$BuySector.exists and $newTrade.$BuySector.idcode?">
            <set_value name="$wSecBuy" exact="@$newTrade.$BuySector.idcode"/>
          </do_if>
          <do_elseif value="$newTrade.$BuyStation? and @$newTrade.$BuyStation.exists and $newTrade.$BuyStation.sector? and @$newTrade.$BuyStation.sector.exists and $newTrade.$BuyStation.sector.idcode?">
            <set_value name="$wSecBuy" exact="@$newTrade.$BuyStation.sector.idcode"/>
          </do_elseif>
          <do_if value="$wSecBuy?">
            <set_value name="$newTrade.$BuySectorId" exact="$wSecBuy"/>
          </do_if>
        </do_if>
        <!-- Stamp trade-rule verdict for player-owned legs only (fresh offer refs).
             NPCÃ—NPC cantradewith is not a player trade rule â€” do not stamp or skip those rows. -->
        <do_if value="not $newTrade.$IsSellOnly?">
          <set_value name="$trbBuyStation" exact="null"/>
          <do_if value="$newTrade.$BuyStation? and @$newTrade.$BuyStation.exists">
            <set_value name="$trbBuyStation" exact="@$newTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $newTrade.$BuyOffer.seller? and @$newTrade.$BuyOffer.seller.exists">
            <set_value name="$trbBuyStation" exact="@$newTrade.$BuyOffer.seller"/>
          </do_elseif>
          <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $newTrade.$BuyOffer.owner? and @$newTrade.$BuyOffer.owner.exists">
            <set_value name="$trbBuyStation" exact="@$newTrade.$BuyOffer.owner"/>
          </do_elseif>
          <set_value name="$trbSellStation" exact="null"/>
          <do_if value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $newTrade.$SellOffer.buyer? and @$newTrade.$SellOffer.buyer.exists">
            <set_value name="$trbSellStation" exact="@$newTrade.$SellOffer.buyer"/>
          </do_if>
          <do_elseif value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists">
            <set_value name="$trbSellStation" exact="@$newTrade.$SellStation"/>
          </do_elseif>
          <do_elseif value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $newTrade.$SellOffer.owner? and @$newTrade.$SellOffer.owner.exists">
            <set_value name="$trbSellStation" exact="@$newTrade.$SellOffer.owner"/>
          </do_elseif>
          <set_value name="$trbPlayerStationInvolved" exact="false"/>
          <do_if value="$trbBuyStation? and @$trbBuyStation.exists">
            <do_if value="@$trbBuyStation.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_if>
            <do_elseif value="@$trbBuyStation.isclass.buildstorage and $trbBuyStation.base? and @$trbBuyStation.base.exists and @$trbBuyStation.base.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="not $trbPlayerStationInvolved and $trbSellStation? and @$trbSellStation.exists">
            <do_if value="@$trbSellStation.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_if>
            <do_elseif value="@$trbSellStation.isclass.buildstorage and $trbSellStation.base? and @$trbSellStation.base.exists and @$trbSellStation.base.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_elseif>
          </do_if>
          <set_value name="$newTrade.$TradeRuleBlocked" exact="false"/>
          <do_if value="$trbPlayerStationInvolved">
            <do_if value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $trbBuyStation? and @$trbBuyStation.exists and not $newTrade.$SellOffer.cantradewith.{$trbBuyStation}">
              <set_value name="$newTrade.$TradeRuleBlocked" exact="true"/>
            </do_if>
            <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $trbSellStation? and @$trbSellStation.exists and not $newTrade.$BuyOffer.cantradewith.{$trbSellStation}">
              <set_value name="$newTrade.$TradeRuleBlocked" exact="true"/>
            </do_elseif>
            <do_if value="$newTrade.$TradeRuleBlocked? and $newTrade.$TradeRuleBlocked">
              <continue/>
            </do_if>
          </do_if>
        </do_if>
        <!-- MK4 shared pool: persist ware transport (container/solid/liquid) so readers skip incompatible holds without validation poisoning. -->
        <do_if value="this.$gt_cachePoolIsMk4 and not $newTrade.$CargoWareTransport?">
          <set_value name="$cacheTagWare" exact="if $newTrade.$Ware? then $newTrade.$Ware else null"/>
          <do_if value="not $cacheTagWare? and $newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and @$newTrade.$BuyOffer.ware != null">
            <set_value name="$cacheTagWare" exact="@$newTrade.$BuyOffer.ware"/>
          </do_if>
          <do_if value="not $cacheTagWare? and $newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and @$newTrade.$SellOffer.ware != null">
            <set_value name="$cacheTagWare" exact="@$newTrade.$SellOffer.ware"/>
          </do_if>
          <do_if value="$cacheTagWare?">
            <set_value name="$newTrade.$CargoWareTransport" exact="@$cacheTagWare.waretransport"/>
          </do_if>
        </do_if>
        <set_value name="$newScore" exact="if $newTrade.$Score? then @$newTrade.$Score else 0"/>

        <!-- MK3: strip ephemeral per-ship route fields â€” shared cache stays ship-agnostic (LC4). -->
        <do_if value="not this.$gt_cachePoolIsMk4">
          <do_if value="$newTrade.$ShipRouteScored?">
            <remove_value name="$newTrade.$ShipRouteScored"/>
          </do_if>
          <do_if value="$newTrade.$ShipScore?">
            <remove_value name="$newTrade.$ShipScore"/>
          </do_if>
          <do_if value="$newTrade.$ShipToBuyDistance?">
            <remove_value name="$newTrade.$ShipToBuyDistance"/>
          </do_if>
          <do_if value="$newTrade.$ShipRouteDistance?">
            <remove_value name="$newTrade.$ShipRouteDistance"/>
          </do_if>
          <do_if value="$newTrade.$SelectionScore?">
            <remove_value name="$newTrade.$SelectionScore"/>
          </do_if>
        </do_if>

        <do_if value="this.$gt_cachePoolIsMk4">
          <do_if value="not global.$GT_TradeCacheMK4?">
            <set_value name="global.$GT_TradeCacheMK4" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_TradeCacheMK4.{$homeSector}?">
            <set_value name="global.$GT_TradeCacheMK4.{$homeSector}" exact="[]"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="not global.$GT_TradeCache?">
            <set_value name="global.$GT_TradeCache" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_TradeCache.{$homeSector}?">
            <set_value name="global.$GT_TradeCache.{$homeSector}" exact="[]"/>
          </do_if>
        </do_else>

        <set_value name="$insertIdx" exact="0"/>
        <set_value name="$insertFound" exact="false"/>
        <set_value name="$cacheSize" exact="0"/>
        <do_if value="this.$gt_cachePoolIsMk4">
          <set_value name="$cacheSize" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.count != null then @global.$GT_TradeCacheMK4.{$homeSector}.count else 0"/>
        </do_if>
        <do_else>
          <set_value name="$cacheSize" exact="if @global.$GT_TradeCache.{$homeSector}.count != null then @global.$GT_TradeCache.{$homeSector}.count else 0"/>
        </do_else>
        <do_if value="$cacheSize gt 0">
          <do_all exact="$cacheSize" counter="$si">
            <set_value name="$existingScore" exact="0"/>
            <do_if value="this.$gt_cachePoolIsMk4">
              <set_value name="$existingScore" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.{$si}.$Score != null then @global.$GT_TradeCacheMK4.{$homeSector}.{$si}.$Score else 0"/>
            </do_if>
            <do_else>
              <set_value name="$existingScore" exact="if @global.$GT_TradeCache.{$homeSector}.{$si}.$Score != null then @global.$GT_TradeCache.{$homeSector}.{$si}.$Score else 0"/>
            </do_else>
            <do_if value="$newScore gt $existingScore">
              <set_value name="$insertIdx" exact="$si"/>
              <set_value name="$insertFound" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="$insertFound">
          <do_if value="this.$gt_cachePoolIsMk4">
            <set_value name="global.$GT_TradeCacheMK4.{$homeSector}.{$insertIdx}" exact="$newTrade" operation="insert"/>
          </do_if>
          <do_else>
            <set_value name="global.$GT_TradeCache.{$homeSector}.{$insertIdx}" exact="$newTrade" operation="insert"/>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="this.$gt_cachePoolIsMk4">
            <append_to_list name="global.$GT_TradeCacheMK4.{$homeSector}" exact="$newTrade"/>
          </do_if>
          <do_else>
            <append_to_list name="global.$GT_TradeCache.{$homeSector}" exact="$newTrade"/>
          </do_else>
        </do_else>

        <set_value name="$tiInt" exact="($ti)i"/>
        <do_if value="($tiInt % this.$writeBatchSize) == 0">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield between sorted insertions"/>
        </do_if>
      </do_all>

      <set_value name="$finalCacheSize" exact="0"/>
      <do_if value="this.$gt_cachePoolIsMk4">
        <set_value name="$finalCacheSize" exact="if @global.$GT_TradeCacheMK4.{$homeSector}.count != null then @global.$GT_TradeCacheMK4.{$homeSector}.count else 0"/>
      </do_if>
      <do_else>
        <set_value name="$finalCacheSize" exact="if @global.$GT_TradeCache.{$homeSector}.count != null then @global.$GT_TradeCache.{$homeSector}.count else 0"/>
      </do_else>
      <!-- MK3 pool: when over cap, evict oldest entries by $CachedAt (not lowest home $Score tail).
           MK3 cache read scans the full pool and re-ranks per ship; age trim keeps fresh home-valid rows. -->
      <do_if value="not this.$gt_cachePoolIsMk4 and $finalCacheSize gt 0">
        <set_value name="$cacheMaxEntries" exact="50"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries?">
          <set_value name="$cacheMaxEntries" exact="@global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries"/>
        </do_if>
        <do_while value="$finalCacheSize gt $cacheMaxEntries">
          <set_value name="$oldestIdx" exact="1"/>
          <set_value name="$oldestTs" exact="null"/>
          <do_all exact="$finalCacheSize" counter="$trimIdx">
            <set_value name="$trimEntry" exact="@global.$GT_TradeCache.{$homeSector}.{$trimIdx}"/>
            <set_value name="$trimTs" exact="null"/>
            <do_if value="$trimEntry?">
              <set_value name="$trimTs" exact="@$trimEntry.$CachedAt"/>
              <do_if value="$trimTs == null">
                <set_value name="$trimTs" exact="@$trimEntry.$Timestamp"/>
              </do_if>
            </do_if>
            <do_if value="$trimTs == null">
              <set_value name="$trimTs" exact="0"/>
            </do_if>
            <do_if value="$oldestTs == null or $trimTs le $oldestTs">
              <set_value name="$oldestTs" exact="$trimTs"/>
              <set_value name="$oldestIdx" exact="$trimIdx"/>
            </do_if>
          </do_all>
          <remove_value name="global.$GT_TradeCache.{$homeSector}.{$oldestIdx}"/>
          <set_value name="$finalCacheSize" operation="subtract"/>
        </do_while>
      </do_if>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-CacheWrite] ' + this.ship.idcode + ': (' + $poolLabel + ') Wrote ' + $tradeList.count + ' trades (sorted) into ' + $homeSector.knownname + ' cache (total: ' + $finalCacheSize + ', cleaned: ' + $expiredCount + ')'" chance="100"/>
      </do_if>

      <!-- Phase 3: Update per-pool max-distance metadata -->
      <set_value name="$metadataUpdated" exact="false"/>
      <do_if value="$maxSearchDistance gt 0">
        <do_if value="this.$gt_cachePoolIsMk4">
          <do_if value="not global.$GT_TradeCacheMK4MaxDistance?">
            <set_value name="global.$GT_TradeCacheMK4MaxDistance" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_TradeCacheMK4MaxDistance.{$homeSector}? or $maxSearchDistance gt global.$GT_TradeCacheMK4MaxDistance.{$homeSector}">
            <set_value name="global.$GT_TradeCacheMK4MaxDistance.{$homeSector}" exact="$maxSearchDistance"/>
            <set_value name="$metadataUpdated" exact="true"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="not global.$GT_TradeCacheMaxDistance?">
            <set_value name="global.$GT_TradeCacheMaxDistance" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_TradeCacheMaxDistance.{$homeSector}? or $maxSearchDistance gt global.$GT_TradeCacheMaxDistance.{$homeSector}">
            <set_value name="global.$GT_TradeCacheMaxDistance.{$homeSector}" exact="$maxSearchDistance"/>
            <set_value name="$metadataUpdated" exact="true"/>
          </do_if>
        </do_else>
      </do_if>
      <!-- Wake same-home waiters on any pool write (MK3 traders + MK4 supply). -->
      <set_value name="$cacheWakeNeeded" exact="$homeSector? and $homeSector.exists and ($tradeList.count gt 0 or $metadataUpdated)"/>
      <do_if value="$cacheWakeNeeded">
        <signal_objects object="player.galaxy" param="'GT_MK4_Cache_Updated'" param2="table[
          $HomeSector = $homeSector,
          $MaxDistance = $maxSearchDistance,
          $Written = $tradeList.count,
          $CacheSize = $finalCacheSize,
          $CachePool = if this.$gt_cachePoolIsMk4 then 'mk4' else 'mk3'
        ]"/>
      </do_if>

      <return value="table[
        $Written = $tradeList.count,
        $Cleaned = $expiredCount,
        $CacheSize = $finalCacheSize
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.dockcheck" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Unified dock preflight (DOCS/Spec/improvements/FEATURE_UNIFY_DOCKING_CHECKS.md).
    Read-only probe â€” returns $CanDock + $Reason; never writes globals.
    Paired MD implementation: GT_CanDock in gt_libraries_general.xml.
    Cooperative yield before return prevents AIDirector infinite-wake loops in hot paths.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="station" default="null"/>
    <param name="purpose" default="'trade'"/>
    <param name="allowStorageDock" default="false"/>
    <param name="allowPlayerOnly" default="false"/>
    <param name="checkOperational" default="true"/>
    <param name="useMemo" default="false" comment="Cache on this.$gt_dockMemo per search pass (caller clears memo)"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="$yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <set_value name="$canDock" exact="false"/>
      <set_value name="$reason" exact="'invalid_station'"/>
      <set_value name="$usedStorageFallback" exact="false"/>
      <set_value name="$bay" exact="null"/>
      <set_value name="$memoHit" exact="false"/>

      <!-- Per-search memo (D8): skip redundant find_dockingbay when same station revisited -->
      <do_if value="$useMemo and $station? and $station.exists">
        <do_if value="this.$gt_dockMemo? and this.$gt_dockMemo.{$station}?">
          <set_value name="$memoEntry" exact="this.$gt_dockMemo.{$station}"/>
          <do_if value="$memoEntry.$Purpose == $purpose and $memoEntry.$AllowStorageDock == $allowStorageDock and $memoEntry.$AllowPlayerOnly == $allowPlayerOnly">
            <set_value name="$canDock" exact="$memoEntry.$CanDock"/>
            <set_value name="$reason" exact="$memoEntry.$Reason"/>
            <set_value name="$usedStorageFallback" exact="$memoEntry.$UsedStorageFallback"/>
            <set_value name="$bay" exact="$memoEntry.$Bay"/>
            <set_value name="$memoHit" exact="true"/>
          </do_if>
        </do_if>
      </do_if>

      <do_if value="not $memoHit">
        <do_if value="$station? and $station.exists">
          <set_value name="$reason" exact="'no_bay'"/>

          <!-- ================================================================= -->
          <!-- purpose=trade â€” Trading dock probe + storage fallback + capital park -->
          <!-- ================================================================= -->
          <do_if value="$purpose == 'trade'">
            <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
              <match_dock size="$ship.docksize" trading="true" storage="false" allowplayeronly="$allowPlayerOnly"/>
              <match_relation_to object="$ship" comparison="not" relation="enemy"/>
            </find_dockingbay>
            <do_if value="$bay">
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'ok'"/>
            </do_if>
            <do_elseif value="$allowStorageDock and $station.isplayerowned and not $station.isclass.buildstorage">
              <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
                <match_dock size="$ship.docksize" storage="true"/>
                <match_relation_to object="$ship" comparison="not" relation="enemy"/>
              </find_dockingbay>
              <do_if value="$bay">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
                <set_value name="$usedStorageFallback" exact="true"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'no_trading_bay'"/>
              </do_else>
            </do_elseif>
            <do_else>
              <do_if value="((@$station.type == shiptype.resupplier) or (@$station.type == shiptype.carrier)) and not $ship.hasrelation.enemy.{$station} and $ship.iscapitalship and not $station.zone.isclass.highway">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'capital_park'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'no_trading_bay'"/>
              </do_else>
            </do_else>
          </do_if>

          <!-- ================================================================= -->
          <!-- purpose=service | service_ai â€” Service dock probe -->
          <!-- ================================================================= -->
          <do_elseif value="$purpose == 'service' or $purpose == 'service_ai'">
            <do_if value="not $ship.iscapitalship or $station.isclass.station">
              <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
                <match_dock size="$ship.docksize" storage="false"/>
              </find_dockingbay>
              <do_if value="$bay">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'no_service_bay'"/>
              </do_else>
            </do_if>
            <do_else>
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'capital_skip'"/>
            </do_else>
          </do_elseif>

          <!-- ================================================================= -->
          <!-- purpose=permission_only â€” Docking permission gate -->
          <!-- ================================================================= -->
          <do_elseif value="$purpose == 'permission_only'">
            <do_if value="@$station.type == shiptype.resupplier">
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'ok'"/>
            </do_if>
            <do_else>
              <set_value name="$checkPolicy" exact="not $ship.iscapitalship or $station.isclass.station"/>
              <do_if value="not $checkPolicy or $station.dockingallowed.{$ship}">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'docking_denied'"/>
              </do_else>
            </do_else>
          </do_elseif>

          <!-- ================================================================= -->
          <!-- purpose=dual â€” Service dual probe (bay + permission + resupplier) -->
          <!-- ================================================================= -->
          <do_elseif value="$purpose == 'dual'">
            <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
              <match_dock size="$ship.docksize" storage="false"/>
            </find_dockingbay>
            <do_if value="not $bay">
              <set_value name="$reason" exact="'no_service_bay'"/>
            </do_if>
            <do_elseif value="@$station.type == shiptype.resupplier">
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'ok'"/>
            </do_elseif>
            <do_else>
              <set_value name="$checkPolicy" exact="not $ship.iscapitalship or $station.isclass.station"/>
              <do_if value="not $checkPolicy or $station.dockingallowed.{$ship}">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'docking_denied'"/>
              </do_else>
            </do_else>
          </do_elseif>

          <do_else>
            <set_value name="$reason" exact="'unknown_purpose'"/>
          </do_else>
        </do_if>

        <do_if value="$useMemo and $station? and $station.exists">
          <do_if value="not this.$gt_dockMemo?">
            <set_value name="this.$gt_dockMemo" exact="table[]"/>
          </do_if>
          <set_value name="this.$gt_dockMemo.{$station}" exact="table[
            $Purpose = $purpose,
            $AllowStorageDock = $allowStorageDock,
            $AllowPlayerOnly = $allowPlayerOnly,
            $CanDock = $canDock,
            $Reason = $reason,
            $UsedStorageFallback = $usedStorageFallback,
            $Bay = $bay
          ]"/>
        </do_if>
      </do_if>

      <do_if value="$debugchance gt 0">
        <debug_text text="'[GT-DockCheck] ' + $ship.idcode + ' @ ' + (if $station? and $station.exists then $station.knownname else 'null') + ' purpose=' + $purpose + ' canDock=' + $canDock + ' reason=' + $reason + (if $memoHit then ' (memo)' else '')" chance="$debugchance"/>
      </do_if>

      <!-- Required in hot loops: run_script without yield triggers AIDirector infinite-wake errors -->
      <wait exact="$yieldMs * 1ms"/>

      <return value="table[
        $CanDock = $canDock,
        $Reason = $reason,
        $UsedStorageFallback = $usedStorageFallback,
        $Bay = $bay
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.failed_sector_pairs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!-- Normalize per-sector GT_FailedSectorPairs entry to nested table {buySector}->{sellSector}->record.
       Mirrors md.GT_Libraries_General.GT_NormalizeFailedSectorPairsSectorEntry for AI cache prefilter. -->
  <params>
    <param name="rawEntry" default="null"/>
    <param name="expirationTime" default="1800s"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="$yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <set_value name="$normalized" exact="table[]"/>
      <do_if value="not $rawEntry?">
        <wait exact="$yieldMs * 1ms"/>
        <return value="$normalized"/>
      </do_if>
      <do_if value="typeof $rawEntry == datatype.table">
        <set_value name="$buyKeys" exact="$rawEntry.keys"/>
        <do_all exact="$buyKeys.count" counter="$bki">
          <set_value name="$buyKey" exact="$buyKeys.{$bki}"/>
          <do_if value="$rawEntry.{$buyKey}? and typeof $rawEntry.{$buyKey} == datatype.table">
            <set_value name="$innerTable" exact="$rawEntry.{$buyKey}"/>
            <set_value name="$sellKeys" exact="$innerTable.keys"/>
            <do_all exact="$sellKeys.count" counter="$ski">
              <set_value name="$sellKey" exact="$sellKeys.{$ski}"/>
              <set_value name="$record" exact="@$innerTable.{$sellKey}"/>
              <set_value name="$keep" exact="true"/>
              <do_if value="$expirationTime gt 0s and $record? and $record.$Timestamp?">
                <do_if value="(player.age - $record.$Timestamp) gt $expirationTime">
                  <set_value name="$keep" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="$keep and $record?">
                <set_value name="$buyMap" exact="if $normalized.{$buyKey}? then $normalized.{$buyKey} else table[]"/>
                <set_value name="$buyMap.{$sellKey}" exact="$record"/>
                <set_value name="$normalized.{$buyKey}" exact="$buyMap"/>
              </do_if>
            </do_all>
          </do_if>
        </do_all>
      </do_if>
      <do_elseif value="typeof $rawEntry == datatype.list">
        <do_all exact="$rawEntry.count" counter="$li">
          <set_value name="$legacyRec" exact="$rawEntry.{$li}"/>
          <do_if value="$legacyRec? and $legacyRec.$BuySector? and $legacyRec.$BuySector.exists and $legacyRec.$SellSector? and $legacyRec.$SellSector.exists">
            <set_value name="$keepLegacy" exact="true"/>
            <do_if value="$expirationTime gt 0s and $legacyRec.$Timestamp?">
              <do_if value="(player.age - $legacyRec.$Timestamp) gt $expirationTime">
                <set_value name="$keepLegacy" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$keepLegacy">
              <set_value name="$legacyBuy" exact="$legacyRec.$BuySector"/>
              <set_value name="$legacySell" exact="$legacyRec.$SellSector"/>
              <set_value name="$legacyBuyMap" exact="if $normalized.{$legacyBuy}? then $normalized.{$legacyBuy} else table[]"/>
              <set_value name="$legacyBuyMap.{$legacySell}" exact="table[
                $Reason = if $legacyRec.$Reason? then $legacyRec.$Reason else '',
                $Timestamp = if $legacyRec.$Timestamp? then $legacyRec.$Timestamp else player.age
              ]"/>
              <set_value name="$normalized.{$legacyBuy}" exact="$legacyBuyMap"/>
            </do_if>
          </do_if>
        </do_all>
      </do_elseif>

      <wait exact="$yieldMs * 1ms"/>
      <return value="$normalized"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- lib.gt.fallback.search â€” Fallback trade search with relaxed parameters.
     Ported from 0.7.6 gt_trading_search.xml / SearchFallbackTrades cue.

     Called when the normal pipeline (cache / live / tradematch / scoring) yields
    no results. Searches with reduced distance and relaxed profit/price-range
    thresholds. Fallback center is dynamic:
      - ship sector if ship is still within home maxDistance
      - home sector if ship drifted outside home maxDistance
    Resulting trades are still validated against original home sector + maxDistance
    to prevent ships from leaving their authorized trading range.

     Returns table:
       $Found              (bool)  â€” whether fallback found tradeable offers
       $TradeList           (list)  â€” sorted trade list (empty if not found)
       $FallbackMaxDistance (int)   â€” the reduced search radius that was used
-->
<aiscript name="lib.gt.fallback.search" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="ship"                  default="this.ship"/>
    <param name="homeSector"            comment="Original home sector (for distance guard in tradematch)"/>
    <param name="maxDistance"           comment="Original pilot maxDistance (for distance guard in tradematch)"/>
    <param name="minROI"               default="0"      comment="Normal pipeline minROI (will be halved)"/>
    <param name="distancePenalty"      default="0.1"    comment="Distance penalty multiplier"/>
    <param name="factionPriority"      default="null"   comment="Faction priority filter"/>
    <param name="wareBasket"           default="[]"     comment="Ware basket for search"/>
    <param name="allowIllegal"         default="false"  comment="Allow illegal wares"/>
    <param name="enforceRouteIllegalLegality" default="false" comment="If true, illegal wares must be legal on full jump path"/>
    <param name="ignoreMK1Supply"      default="true"   comment="Ignore MK1 supply stations"/>
    <param name="ignoreTradeRules"     default="false"  comment="Ignore trade rules"/>
    <param name="ignoreBuildStorage"   default="false"  comment="Ignore build storage"/>
    <param name="ignoreCarrierAux"     default="false"  comment="Ignore carrier aux storage"/>
    <param name="blacklistGroup"       default="blacklistgroup.civilian" comment="Blacklist group for pathfinding"/>
    <param name="debugchance"          default="0"      comment="Debug log chance"/>
    <param name="priorityWares"        default="[]"     comment="Optional: MK3 Priority Wares for score boost"/>
    <param name="priorityScoreMultiplier" default="125"  comment="Optional: score multiplier for priority wares (125=+25%%, 200=2x)"/>
    <!-- MK3 'Ignore Player Pricing' companion flag: when true, bypass player-set pricing on player-owned suppliers
         (supplemental scan without relativeprice tradepartner) and exclude player-owned buy offers from the match. -->
    <param name="ignorePlayerPricing"  default="false"  comment="MK3: bypass player-seller pricing and disallow player buyers"/>
  </params>
  <attention min="unknown">
    <actions>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Calculate fallback parameters
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <!-- Distance: max(1, floor(maxDistance / 3)) â€” search near the ship -->
      <set_value name="$fallbackMaxDistance" exact="[($maxDistance / 3)i, 1].max"/>

      <!-- Profit: ROI halved (min 0), absolute profit fixed at 100 Cr (10000 units) -->
      <set_value name="$fallbackMinROI" exact="[$minROI / 2, 0].max"/>
      <set_value name="$fallbackMinAbsoluteProfit" exact="10000"/>

      <!-- Price ranges from fallback config -->
      <set_value name="$fallbackSellPriceMax" exact="if global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$FallbackSellPriceMax? then @global.$GT_Config.$Trading.$FallbackSellPriceMax else 0.2"/>
      <set_value name="$fallbackBuyPriceMin" exact="if global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$FallbackBuyPriceMin? then @global.$GT_Config.$Trading.$FallbackBuyPriceMin else -0.2"/>

      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Fallback] ' + $ship.idcode + ': Starting fallback search. ' +
          'OrigDist=' + $maxDistance + ' FallbackDist=' + $fallbackMaxDistance +
          ' OrigROI=' + $minROI + ' FallbackROI=' + $fallbackMinROI +
          ' FallbackProfit=100Cr PriceRange=[' + $fallbackSellPriceMax + ',' + $fallbackBuyPriceMin + ']'" chance="100"/>
      </do_if>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           1) Pathfinding center selection
              - Use ship sector only while ship is still within home maxDistance
              - If ship drifted beyond home range, center fallback on home sector
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <set_value name="$fallbackCenter" exact="$ship.sector"/>
      <set_value name="$fallbackCenterReason" exact="'ship'"/>
      <set_value name="$homeToShipDistance" exact="-1"/>
      <do_if value="$homeSector? and $homeSector.exists and $ship? and $ship.sector? and $ship.sector.exists">
        <set_value name="$homeToShipDistance" exact="$homeSector.gatedistance.{$ship.sector}"/>
        <do_if value="$homeToShipDistance lt 0 or $homeToShipDistance gt $maxDistance">
          <set_value name="$fallbackCenter" exact="$homeSector"/>
          <set_value name="$fallbackCenterReason" exact="'home'"/>
        </do_if>
      </do_if>
      <do_if value="$fallbackCenter == null">
        <set_value name="$fallbackCenter" exact="$ship.sector"/>
        <set_value name="$fallbackCenterReason" exact="'ship'"/>
      </do_if>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Fallback] ' + $ship.idcode + ': center=' + (if $fallbackCenter? then @$fallbackCenter.knownname else 'null') + ' reason=' + $fallbackCenterReason + ' homeToShip=' + $homeToShipDistance + ' maxDist=' + $maxDistance" chance="100"/>
      </do_if>

      <run_script name="'lib.gt.pathfinding'" result="$pathResult">
        <param name="ship" value="$ship"/>
        <param name="homeSector" value="$fallbackCenter"/>
        <param name="maxDistance" value="$fallbackMaxDistance"/>
        <param name="blacklistGroup" value="$blacklistGroup"/>
      </run_script>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           2) Live search with fallback price ranges
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <run_script name="'lib.gt.live.search'" result="$liveResult">
        <param name="ship" value="$ship"/>
        <param name="searchMode" value="'buy_and_sell'"/>
        <param name="buySpaces" value="$pathResult.$BuySpaces"/>
        <param name="sellSpaces" value="$pathResult.$SellSpaces"/>
        <param name="homeSector" value="$fallbackCenter"/>
        <param name="maxDistance" value="$fallbackMaxDistance"/>
        <param name="wareBasket" value="$wareBasket"/>
        <param name="allowIllegal" value="$allowIllegal"/>
        <param name="ownerFilter" value="'any'"/>
        <param name="ignoreMK1Supply" value="$ignoreMK1Supply"/>
        <param name="ignoreTradeRules" value="$ignoreTradeRules"/>
        <param name="maxOffersPerWare" value="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
        <param name="sellPriceMax" value="$fallbackSellPriceMax"/>
        <param name="buyPriceMin" value="$fallbackBuyPriceMin"/>
        <param name="priorityWares" value="if $priorityWares? then $priorityWares else []"/>
        <param name="bypassPlayerSellerPricing" value="$ignorePlayerPricing"/>
        <param name="excludePlayerBuyers" value="$ignorePlayerPricing"/>
        <param name="debugchance" value="$debugchance"/>
      </run_script>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           3) Trade matching â€” SAFETY: uses original homeSector + maxDistance
              to prevent trades outside the ship's authorized range
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <run_script name="'lib.gt.tradematch'" result="$matchResult">
        <param name="ship" value="$ship"/>
        <param name="sellOffers" value="$liveResult.$SellOffers"/>
        <param name="buyOffers" value="$liveResult.$BuyOffers"/>
        <param name="homeSector" value="$homeSector"/>
        <param name="maxDistance" value="$maxDistance"/>
        <param name="minROI" value="$fallbackMinROI"/>
        <param name="minAbsoluteProfit" value="$fallbackMinAbsoluteProfit"/>
        <param name="distancePenalty" value="$distancePenalty"/>
        <param name="factionPriority" value="$factionPriority"/>
        <param name="ignoreBuildStorage" value="$ignoreBuildStorage"/>
        <param name="ignoreCarrierAux" value="$ignoreCarrierAux"/>
        <param name="allowIllegal" value="$allowIllegal"/>
        <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
        <param name="blacklistGroup" value="$blacklistGroup"/>
        <param name="scoreMode" value="'sell'"/>
        <param name="excludePlayerBuyers" value="$ignorePlayerPricing"/>
        <param name="playerSupplierFreeProduction" value="$ignorePlayerPricing"/>
      </run_script>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           4) Score and sort
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <set_value name="$matchTradeList" exact="[]"/>
      <do_if value="$matchResult?">
        <do_if value="$matchResult.$TradeList?">
          <set_value name="$matchTradeList" exact="@$matchResult.$TradeList"/>
        </do_if>
      </do_if>
      <run_script name="'lib.gt.score.trades'" result="$scoreResult">
        <param name="tradeList" value="$matchTradeList"/>
        <param name="priorityWares" value="if $priorityWares? then $priorityWares else []"/>
        <param name="priorityScoreMultiplier" value="if $priorityScoreMultiplier? then $priorityScoreMultiplier else 125"/>
      </run_script>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Build result
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <set_value name="$found" exact="false"/>
      <set_value name="$tradeList" exact="[]"/>
      <do_if value="$scoreResult?">
        <do_if value="$scoreResult.$Found?">
          <set_value name="$found" exact="@$scoreResult.$Found"/>
        </do_if>
        <do_if value="$found and $scoreResult.$SortedTrades?">
          <set_value name="$tradeList" exact="@$scoreResult.$SortedTrades"/>
        </do_if>
      </do_if>

      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Fallback] ' + $ship.idcode + ': Fallback search ' + (if $found then 'SUCCESS: ' + $tradeList.count + ' trades' else 'FAILED: no trades found even with relaxed parameters')" chance="100"/>
      </do_if>

      <return value="table[$Found = $found, $TradeList = $tradeList, $FallbackMaxDistance = $fallbackMaxDistance]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.idlepark" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Idle parking helpers for GT traders/miners (non-blocking: trader default order keeps searching).
    Modes: is_active | trigger | check_timed_release | resolve_park_station
    Dock feasibility uses lib.gt.dockcheck purpose=trade (trading bay + relation check).
    Do NOT run_script order.gt.idlepark for helpers â€” order params are validated at game load.
  -->
  <params>
    <param name="handoffMode" default="''"/>
    <param name="handoffShip" default="this.ship"/>
    <param name="home" default="null"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="$handoffMode == 'is_active'">
        <set_value name="$parkShip" exact="$handoffShip"/>
        <set_value name="$isActive" exact="false"/>
        <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{$parkShip}?">
          <set_value name="$isActive" exact="true"/>
        </do_if>
        <do_if value="not $isActive and $parkShip.order? and @$parkShip.order.id == 'GTIdlePark'">
          <set_value name="$isActive" exact="true"/>
        </do_if>
        <do_if value="not $isActive and $parkShip.order? and @$parkShip.order.id == 'DockAndWait' and $parkShip.order.$callerid? and @$parkShip.order.$callerid.id == 'GTIdlePark'">
          <set_value name="$isActive" exact="true"/>
        </do_if>
        <do_if value="not $isActive and $parkShip.orders.count gt 0">
          <do_all exact="$parkShip.orders.count" counter="$ipoi">
            <set_value name="$ipOrder" exact="$parkShip.orders.{$ipoi}"/>
            <do_if value="@$ipOrder.id == 'GTIdlePark'">
              <set_value name="$isActive" exact="true"/>
              <break/>
            </do_if>
            <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
              <set_value name="$isActive" exact="true"/>
              <break/>
            </do_elseif>
          </do_all>
        </do_if>
        <return value="$isActive"/>
      </do_if>

      <do_if value="$handoffMode == 'trigger'">
        <set_value name="$parkShip" exact="$handoffShip"/>
        <set_value name="$isActive" exact="false"/>
        <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{$parkShip}?">
          <set_value name="$isActive" exact="true"/>
        </do_if>
        <do_if value="not $isActive and $parkShip.order? and @$parkShip.order.id == 'GTIdlePark'">
          <set_value name="$isActive" exact="true"/>
        </do_if>
        <do_if value="not $isActive and $parkShip.order? and @$parkShip.order.id == 'DockAndWait' and $parkShip.order.$callerid? and @$parkShip.order.$callerid.id == 'GTIdlePark'">
          <set_value name="$isActive" exact="true"/>
        </do_if>
        <do_if value="not $isActive and $parkShip.orders.count gt 0">
          <do_all exact="$parkShip.orders.count" counter="$ipoi">
            <set_value name="$ipOrder" exact="$parkShip.orders.{$ipoi}"/>
            <do_if value="@$ipOrder.id == 'GTIdlePark'">
              <set_value name="$isActive" exact="true"/>
              <break/>
            </do_if>
            <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
              <set_value name="$isActive" exact="true"/>
              <break/>
            </do_elseif>
          </do_all>
        </do_if>
        <do_if value="$isActive">
          <return value="false"/>
        </do_if>
        <do_if value="not $home? or not $home.exists">
          <return value="false"/>
        </do_if>
        <run_script name="'lib.gt.idlepark'" result="$parkResolve">
          <param name="handoffMode" value="'resolve_park_station'"/>
          <param name="handoffShip" value="$parkShip"/>
          <param name="home" value="$home"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
        <do_if value="not $parkResolve.$ParkStation? or $parkResolve.$ParkStation == null or not $parkResolve.$ParkStation.exists">
          <do_if value="not global.$GT_IdleParkingReleased?">
            <set_value name="global.$GT_IdleParkingReleased" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_IdleParkingReleased.{$parkShip}" exact="true"/>
          <debug_text text="'[GT-IdlePark] ' + $parkShip.idcode + ': idle parking skipped â€” no dockable trading station for ship size ' + $parkShip.docksize + ' near ' + $home.knownname" chance="$debugchance"/>
          <return value="false"/>
        </do_if>
        <set_value name="$releaseMinutes" exact="1"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet?">
          <do_all exact="global.$GT_GlobalSettings.$Fleet.keys.count" counter="$fki">
            <set_value name="$fleetKey" exact="global.$GT_GlobalSettings.$Fleet.keys.{$fki}"/>
            <do_if value="$fleetKey == '$IdleParkingReleaseMinutes'">
              <set_value name="$releaseMinutes" exact="[[global.$GT_GlobalSettings.$Fleet.{$fleetKey}, 0].max, 60].min"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not global.$GT_IdleParkingHold?">
          <set_value name="global.$GT_IdleParkingHold" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_IdleParkingHoldUntil?">
          <set_value name="global.$GT_IdleParkingHoldUntil" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_IdleParkingHold.{$parkShip}" exact="true"/>
        <do_if value="$releaseMinutes gt 0">
          <set_value name="global.$GT_IdleParkingHoldUntil.{$parkShip}" exact="player.age + $releaseMinutes * 1min"/>
        </do_if>
        <do_else>
          <do_if value="global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{$parkShip}?">
            <remove_value name="global.$GT_IdleParkingHoldUntil.{$parkShip}"/>
          </do_if>
        </do_else>
        <debug_text text="'[GT-IdlePark] ' + $parkShip.idcode + ': idle parking threshold reached - parking at ' + $home.knownname" chance="$debugchance"/>
        <create_order name="$idleParkOrder" object="$parkShip" id="'GTIdlePark'" immediate="false">
          <param name="home" value="$home"/>
          <param name="debugchance" value="$debugchance"/>
        </create_order>
        <return value="true"/>
      </do_if>

      <do_if value="$handoffMode == 'resolve_park_station'">
        <set_value name="$parkShip" exact="$handoffShip"/>
        <set_value name="$parkStation" exact="null"/>
        <set_value name="$parkSector" exact="null"/>
        <do_if value="not $home? or not $home.exists">
          <return value="table[$ParkStation = null, $ParkSector = null]"/>
        </do_if>
        <do_if value="$home.isclass.station">
          <set_value name="$parkSector" exact="$home.sector"/>
          <run_script name="'lib.gt.dockcheck'" result="$homeDockCheck">
            <param name="ship" value="$parkShip"/>
            <param name="station" value="$home"/>
            <param name="purpose" value="'trade'"/>
            <param name="allowPlayerOnly" value="true"/>
          </run_script>
          <do_if value="$homeDockCheck.$CanDock">
            <set_value name="$parkStation" exact="$home"/>
          </do_if>
        </do_if>
        <do_elseif value="$home.isclass.sector">
          <set_value name="$parkSector" exact="$home"/>
        </do_elseif>
        <do_if value="(not $parkStation? or $parkStation == null) and $parkSector? and $parkSector.exists">
          <find_station name="$sectorStations" space="$parkSector" checkoperational="true" multiple="true"/>
          <set_value name="$stationIndex" exact="1"/>
          <do_while value="$sectorStations? and $stationIndex le $sectorStations.count and (not $parkStation? or $parkStation == null)">
            <set_value name="$candidateStation" exact="$sectorStations.{$stationIndex}"/>
            <do_if value="$candidateStation? and $candidateStation.exists and $candidateStation.isclass.station and $candidateStation.isoperational and $candidateStation.isplayerowned">
              <run_script name="'lib.gt.dockcheck'" result="$candidateDockCheck">
                <param name="ship" value="$parkShip"/>
                <param name="station" value="$candidateStation"/>
                <param name="purpose" value="'trade'"/>
                <param name="allowPlayerOnly" value="true"/>
              </run_script>
              <do_if value="$candidateDockCheck.$CanDock">
                <set_value name="$parkStation" exact="$candidateStation"/>
              </do_if>
            </do_if>
            <set_value name="$stationIndex" operation="add"/>
          </do_while>
          <set_value name="$stationIndex" exact="1"/>
          <do_while value="$sectorStations? and $stationIndex le $sectorStations.count and (not $parkStation? or $parkStation == null)">
            <set_value name="$candidateStation" exact="$sectorStations.{$stationIndex}"/>
            <do_if value="$candidateStation? and $candidateStation.exists and $candidateStation.isclass.station and $candidateStation.isoperational and not $candidateStation.isplayerowned and (not @$candidateStation.owner or not $parkShip.hasrelation.enemy.{@$candidateStation.owner})">
              <run_script name="'lib.gt.dockcheck'" result="$candidateDockCheck">
                <param name="ship" value="$parkShip"/>
                <param name="station" value="$candidateStation"/>
                <param name="purpose" value="'trade'"/>
                <param name="allowPlayerOnly" value="true"/>
              </run_script>
              <do_if value="$candidateDockCheck.$CanDock">
                <set_value name="$parkStation" exact="$candidateStation"/>
              </do_if>
            </do_if>
            <set_value name="$stationIndex" operation="add"/>
          </do_while>
          <remove_value name="$sectorStations"/>
          <remove_value name="$stationIndex"/>
        </do_if>
        <return value="table[$ParkStation = $parkStation, $ParkSector = $parkSector]"/>
      </do_if>

      <do_if value="$handoffMode == 'check_timed_release'">
        <set_value name="$parkShip" exact="if $handoffShip? and $handoffShip.exists then $handoffShip else this.ship"/>
        <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{$parkShip}? and global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{$parkShip}? and player.age ge global.$GT_IdleParkingHoldUntil.{$parkShip}">
          <remove_value name="global.$GT_IdleParkingHold.{$parkShip}"/>
          <remove_value name="global.$GT_IdleParkingHoldUntil.{$parkShip}"/>
          <do_if value="global.$GT_IdleParkingDockedSince? and global.$GT_IdleParkingDockedSince.{$parkShip}?">
            <remove_value name="global.$GT_IdleParkingDockedSince.{$parkShip}"/>
          </do_if>
          <set_value name="global.$GT_IdleParkingReleased.{$parkShip}" exact="true"/>
          <debug_text text="'[GT-IdlePark] ' + $parkShip.idcode + ': timed idle release - undocking to free port'" chance="$debugchance"/>
          <do_if value="$parkShip.dock or $parkShip.parkedat">
            <create_order object="$parkShip" id="'Undock'" immediate="true"/>
          </do_if>
        </do_if>
        <return value="true"/>
      </do_if>

      <return value="false"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.live.search" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="6">
  <params>
    <param name="ship" default="this.ship"/>
    <param name="searchMode" default="'buy_and_sell'"/>
    <param name="buySpaces" default="[]"/>
    <param name="sellSpaces" default="[]"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="wareBasket" default="[]"/>
    <param name="allowIllegal" default="false"/>
    <param name="ownerFilter" default="'any'"/>
    <param name="ignoreMK1Supply" default="false"/>
    <param name="ignoreTradeRules" default="false"/>
    <param name="maxOffersPerWare" default="20"/>
    <param name="maxOffersPerSearch" default="200"/> <!-- Legacy / unused â€” kept for call-site compat, per-ware cap is used instead -->
    <param name="sellPriceMax" default="1.0" comment="Max relative price for sell offers (ship buys from station). Range: -1.0 to 1.0. Default 1.0 = no filter"/>
    <param name="buyPriceMin" default="-1.0" comment="Min relative price for buy offers (ship sells to station). Range: -1.0 to 1.0. Default -1.0 = no filter"/>
    <!-- MK4 compatibility params (accepted for call-site compatibility) -->
    <param name="ignoreTradeRulesPlayerBuyOffersRequireCargoNeed" default="false"/>
    <param name="includePlayerBuyOffers" default="true"/>
    <param name="includePlayerSellOffers" default="true"/>
    <param name="requirePlayerBuyOfferOwner" default="false" comment="When true, collected buy offers must be player-owned buyers (MK4 customer policy prefilter)."/>
    <param name="priorityWares" default="[]" comment="Optional: MK3 priority wares to explicitly search for (ensures they enter the tradeable set for scoring)"/>
    <!-- MK3 'Ignore Player Pricing' option: include player sell offers unconditionally, and drop player buyers. -->
    <param name="bypassPlayerSellerPricing" default="false" comment="When true, run a supplemental player-only sell scan without relativeprice filter so player stations are purchased from regardless of price."/>
    <param name="excludePlayerBuyers" default="false" comment="When true, exclude player-owned buy offers entirely (used with bypassPlayerSellerPricing to sell only to NPC factions)."/>
    <!-- MK1 sell_only: keep top-N buyers per ware by estimated sell profit (not scan order). -->
    <param name="sourceSellOffers" default="[]" comment="Home-station sell offers keyed by ware for score-aware buyer cap (MK1 export)."/>
    <param name="scoreAwareBuyCap" default="false" comment="When true with sourceSellOffers, retain best maxOffersPerWare buyers by estimated score across full scan."/>
    <param name="distancePenalty" default="0.1" comment="Distance divisor for scoreAwareBuyCap estimate (matches lib.gt.tradematch sell scoring)."/>
    <param name="demandLedSupplierScan" default="false" comment="MK4: collect buy offers first, then limit supplier scan to demand wares only (S4)."/>
    <param name="mk4BuildStorageOnlyMode" default="false" comment="MK4: implicit BS-on + all ware-category toggles off â€” in-scope build storage buyers only."/>
    <param name="mk4AnchorHome" default="null" comment="MK4 home anchor for build-storage-only scope (station or sector)."/>
    <param name="maxDistanceSell" default="0" comment="MK4 jumpDistanceCoverage â€” max gate distance from home for BS delivery buyers (0 = use maxDistance)."/>
    <param name="searchPurpose" default="'direct_live'" comment="cache_refresh = fleet-min totalvolume for shared cache; direct_live = this ship min/max"/>
    <param name="cargoTargetPercent" default="0" comment="Override cargotarget percent (0 = resolve from ship/order)"/>
    <param name="debugchance" default="0"/>
  </params>
  <patch sinceversion="5">
    <debug_text text="'[GT-LiveSearch] lib.gt.live.search v6: global scratch + gtls_ensure_state resume guards'" chance="100" filter="savegame"/>
  </patch>
  <attention min="unknown">
    <actions>
      <create_list name="$sellOffers"/>
      <create_list name="$buyOffers"/>
      <!-- Per-ware offer tracking: ensures EVERY tradeable ware gets representation.
           Without this, the first few busy sectors would fill a blind cap with the same
           10-15 high-volume wares, starving niche wares and distant sectors.
           Old version used MaxOffersPerWare=200 (collection) + MaxOffersPerWareForMatching=20. -->
      <set_value name="$sellOffersPerWare" exact="table[]"/>
      <set_value name="$buyOffersPerWare" exact="table[]"/>
      <set_value name="$gtlsSeenBuyOffers" exact="table[]"/>
      <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
      <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
      <!-- Read AI yield interval from global settings -->
      <set_value name="$gtYieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="$gtYieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>
      <!-- Copy params to locals; sector-loop waits restore from global.$GT_LiveSearchScratch (lib.gt.tradematch pattern). -->
      <set_value name="$gtlsShip" exact="$ship"/>
      <set_value name="$gtlsSearchMode" exact="$searchMode"/>
      <set_value name="$gtlsBuySpaces" exact="if $buySpaces? then $buySpaces else []"/>
      <set_value name="$gtlsSellSpaces" exact="if $sellSpaces? then $sellSpaces else []"/>
      <set_value name="$gtlsHomeSector" exact="$homeSector"/>
      <set_value name="$gtlsMaxDistance" exact="$maxDistance"/>
      <set_value name="$gtlsMaxDistanceSell" exact="if $maxDistanceSell? then $maxDistanceSell else 0"/>
      <set_value name="$gtlsWareBasket" exact="$wareBasket"/>
      <set_value name="$gtlsAllowIllegal" exact="$allowIllegal"/>
      <set_value name="$gtlsOwnerFilter" exact="$ownerFilter"/>
      <set_value name="$gtlsIgnoreMK1Supply" exact="$ignoreMK1Supply"/>
      <set_value name="$gtlsIgnoreTradeRules" exact="$ignoreTradeRules"/>
      <set_value name="$gtlsMaxOffersPerWare" exact="$maxOffersPerWare"/>
      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $maxOffersPerWare].min].max"/>
      <set_value name="$gtlsMaxOffersPerSearch" exact="$maxOffersPerSearch"/>
      <set_value name="$gtlsSellPriceMax" exact="$sellPriceMax"/>
      <set_value name="$gtlsBuyPriceMin" exact="$buyPriceMin"/>
      <set_value name="$gtlsIncludePlayerBuyOffers" exact="$includePlayerBuyOffers"/>
      <set_value name="$gtlsIncludePlayerSellOffers" exact="$includePlayerSellOffers"/>
      <set_value name="$gtlsRequirePlayerBuyOfferOwner" exact="$requirePlayerBuyOfferOwner"/>
      <set_value name="$gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed" exact="$ignoreTradeRulesPlayerBuyOffersRequireCargoNeed"/>
      <set_value name="$gtlsBypassPlayerSellerPricing" exact="$bypassPlayerSellerPricing"/>
      <set_value name="$gtlsExcludePlayerBuyers" exact="$excludePlayerBuyers"/>
      <set_value name="$gtlsPriorityWares" exact="if $priorityWares? then $priorityWares else []"/>
      <set_value name="$gtlsDebugchance" exact="$debugchance"/>
      <set_value name="this.$gtlsDemandLedSupplierScan" exact="if $demandLedSupplierScan? then $demandLedSupplierScan else false"/>
      <do_if value="this.$gtlsDemandLedSupplierScan">
        <set_value name="this.$gtlsDemandLedSellDone" exact="false"/>
      </do_if>
      <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="if $mk4BuildStorageOnlyMode? then $mk4BuildStorageOnlyMode else false"/>
      <set_value name="$gtlsMk4AnchorHome" exact="if $mk4AnchorHome? then $mk4AnchorHome else null"/>
      <set_value name="$gtlsDistancePenalty" exact="if $distancePenalty? then $distancePenalty else 0.1"/>
      <set_value name="$gtlsSourceSellByWare" exact="table[]"/>
      <set_value name="$gtlsUseScoreAwareBuyCap" exact="false"/>
      <set_value name="$gtlsTopBuyOffersPerWare" exact="table[]"/>
      <set_value name="$gtlsTopBuyScoresPerWare" exact="table[]"/>
      <set_value name="$gtlsScoreAwareCandidatesSeen" exact="0"/>
      <do_if value="$scoreAwareBuyCap and $sourceSellOffers? and $sourceSellOffers.count gt 0">
        <do_all exact="$sourceSellOffers.count" counter="$gtlsSsi">
          <set_value name="$gtlsSourceSellOffer" exact="$sourceSellOffers.{$gtlsSsi}"/>
          <do_if value="$gtlsSourceSellOffer? and $gtlsSourceSellOffer.ware? and @$gtlsSourceSellOffer.exists and $gtlsSourceSellOffer.available and $gtlsSourceSellOffer.amount gt 0">
            <set_value name="$gtlsSourceSellByWare.{$gtlsSourceSellOffer.ware}" exact="$gtlsSourceSellOffer"/>
            <set_value name="$gtlsUseScoreAwareBuyCap" exact="true"/>
          </do_if>
        </do_all>
      </do_if>
      <!-- Fleet-min / per-ship totalvolume thresholds (persist in this.$ across cooperative waits). -->
      <set_value name="this.$gtlsSearchPurpose" exact="if $searchPurpose? then $searchPurpose else 'direct_live'"/>
      <set_value name="$gtlsCargoTargetPct" exact="80"/>
      <do_if value="$cargoTargetPercent? and $cargoTargetPercent gt 0">
        <set_value name="$gtlsCargoTargetPct" exact="[10, [$cargoTargetPercent, 100].min].max"/>
      </do_if>
      <do_elseif value="$gtlsShip.commander? and $gtlsShip.commander.exists and $gtlsShip.commander != $gtlsShip and $gtlsShip.commander.defaultorder? and $gtlsShip.commander.defaultorder.$cargotarget?">
        <set_value name="$gtlsCargoTargetPct" exact="[10, [$gtlsShip.commander.defaultorder.$cargotarget, 100].min].max"/>
      </do_elseif>
      <do_elseif value="$gtlsShip.defaultorder? and $gtlsShip.defaultorder.$cargotarget?">
        <set_value name="$gtlsCargoTargetPct" exact="[10, [$gtlsShip.defaultorder.$cargotarget, 100].min].max"/>
      </do_elseif>
      <set_value name="this.$gtlsTvMinContainer" exact="1"/>
      <set_value name="this.$gtlsTvMinSolid" exact="1"/>
      <set_value name="this.$gtlsTvMinLiquid" exact="1"/>
      <set_value name="this.$gtlsTvMaxContainer" exact="0"/>
      <set_value name="this.$gtlsTvMaxSolid" exact="0"/>
      <set_value name="this.$gtlsTvMaxLiquid" exact="0"/>
      <do_if value="this.$gtlsSearchPurpose == 'cache_refresh'">
        <do_if value="$gtlsHomeSector? and $gtlsHomeSector.exists and global.$GT_HomeFleetCargoProfile? and global.$GT_HomeFleetCargoProfile.{$gtlsHomeSector}? and global.$GT_HomeFleetCargoProfile.{$gtlsHomeSector}.$MinRequired?">
          <set_value name="$gtlsFleetMin" exact="global.$GT_HomeFleetCargoProfile.{$gtlsHomeSector}.$MinRequired"/>
          <do_if value="$gtlsFleetMin.$container? and $gtlsFleetMin.$container gt 0">
            <set_value name="this.$gtlsTvMinContainer" exact="$gtlsFleetMin.$container"/>
          </do_if>
          <do_if value="$gtlsFleetMin.$solid? and $gtlsFleetMin.$solid gt 0">
            <set_value name="this.$gtlsTvMinSolid" exact="$gtlsFleetMin.$solid"/>
          </do_if>
          <do_if value="$gtlsFleetMin.$liquid? and $gtlsFleetMin.$liquid gt 0">
            <set_value name="this.$gtlsTvMinLiquid" exact="$gtlsFleetMin.$liquid"/>
          </do_if>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$gtlsTvMinAll" exact="($gtlsShip.cargo.capacity.all * $gtlsCargoTargetPct / 100)i"/>
        <set_value name="this.$gtlsTvMinContainer" exact="$gtlsTvMinAll"/>
        <set_value name="this.$gtlsTvMinSolid" exact="$gtlsTvMinAll"/>
        <set_value name="this.$gtlsTvMinLiquid" exact="$gtlsTvMinAll"/>
        <set_value name="this.$gtlsTvMaxContainer" exact="$gtlsShip.cargo.free.container + $gtlsShip.cargo.free.universal"/>
        <set_value name="this.$gtlsTvMaxSolid" exact="$gtlsShip.cargo.free.solid + $gtlsShip.cargo.free.universal"/>
        <set_value name="this.$gtlsTvMaxLiquid" exact="$gtlsShip.cargo.free.liquid + $gtlsShip.cargo.free.universal"/>
      </do_else>
      <!-- sell_only: bound offers by cargo ON BOARD (not free hold). Full holds must still find buyers. -->
      <do_if value="$gtlsSearchMode == 'sell_only'">
        <set_value name="this.$gtlsTvMinContainer" exact="1"/>
        <set_value name="this.$gtlsTvMinSolid" exact="1"/>
        <set_value name="this.$gtlsTvMinLiquid" exact="1"/>
        <set_value name="this.$gtlsTvMaxContainer" exact="999999999"/>
        <set_value name="this.$gtlsTvMaxSolid" exact="999999999"/>
        <set_value name="this.$gtlsTvMaxLiquid" exact="999999999"/>
      </do_if>
      <set_value name="$gtlsUseAllWares" exact="(not $gtlsWareBasket? or $gtlsWareBasket.count == 0)"/>
      <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
      <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
      <!-- Rebuild locals after save/load resume or cooperative wait (lib.gt.tradematch pattern). -->
      <label name="gtls_ensure_state"/>
      <do_if value="not $gtlsMk4BuildStorageOnlyMode?">
        <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="false"/>
      </do_if>
      <set_value name="$gtlsScratchShip" exact="null"/>
      <do_if value="$ship? and $ship.exists">
        <set_value name="$gtlsScratchShip" exact="$ship"/>
      </do_if>
      <do_elseif value="global.$GT_LiveSearchActiveShip? and global.$GT_LiveSearchActiveShip.exists">
        <set_value name="$gtlsScratchShip" exact="global.$GT_LiveSearchActiveShip"/>
      </do_elseif>
      <do_if value="$gtlsScratchShip? and global.$GT_LiveSearchScratch? and global.$GT_LiveSearchScratch.{$gtlsScratchShip}?">
        <set_value name="$gtlsSnap" exact="global.$GT_LiveSearchScratch.{$gtlsScratchShip}"/>
        <set_value name="$gtlsShip" exact="$gtlsSnap.$Ship"/>
        <set_value name="$gtlsSearchMode" exact="$gtlsSnap.$SearchMode"/>
        <set_value name="$gtlsBuySpaces" exact="if $gtlsSnap.$BuySpaces? then $gtlsSnap.$BuySpaces else []"/>
        <set_value name="$gtlsSellSpaces" exact="if $gtlsSnap.$SellSpaces? then $gtlsSnap.$SellSpaces else []"/>
        <set_value name="$gtlsHomeSector" exact="$gtlsSnap.$HomeSector"/>
        <set_value name="$gtlsMaxDistance" exact="$gtlsSnap.$MaxDistance"/>
        <set_value name="$gtlsWareBasket" exact="$gtlsSnap.$WareBasket"/>
        <set_value name="$gtlsAllowIllegal" exact="$gtlsSnap.$AllowIllegal"/>
        <set_value name="$gtlsOwnerFilter" exact="$gtlsSnap.$OwnerFilter"/>
        <set_value name="$gtlsIgnoreMK1Supply" exact="$gtlsSnap.$IgnoreMK1Supply"/>
        <set_value name="$gtlsIgnoreTradeRules" exact="$gtlsSnap.$IgnoreTradeRules"/>
        <set_value name="$gtlsMaxOffersPerWare" exact="$gtlsSnap.$MaxOffersPerWare"/>
        <set_value name="$gtlsBuildStorageReservePerWare" exact="$gtlsSnap.$BuildStorageReservePerWare"/>
        <set_value name="$gtlsSellPriceMax" exact="$gtlsSnap.$SellPriceMax"/>
        <set_value name="$gtlsBuyPriceMin" exact="$gtlsSnap.$BuyPriceMin"/>
        <set_value name="$gtlsIncludePlayerBuyOffers" exact="$gtlsSnap.$IncludePlayerBuyOffers"/>
        <set_value name="$gtlsIncludePlayerSellOffers" exact="$gtlsSnap.$IncludePlayerSellOffers"/>
        <set_value name="$gtlsRequirePlayerBuyOfferOwner" exact="$gtlsSnap.$RequirePlayerBuyOfferOwner"/>
        <set_value name="$gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed" exact="$gtlsSnap.$IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed"/>
        <set_value name="$gtlsBypassPlayerSellerPricing" exact="$gtlsSnap.$BypassPlayerSellerPricing"/>
        <set_value name="$gtlsExcludePlayerBuyers" exact="$gtlsSnap.$ExcludePlayerBuyers"/>
        <set_value name="$gtlsPriorityWares" exact="$gtlsSnap.$PriorityWares"/>
        <set_value name="$gtlsDebugchance" exact="$gtlsSnap.$Debugchance"/>
        <set_value name="$gtlsUseAllWares" exact="$gtlsSnap.$UseAllWares"/>
        <do_if value="$gtlsSnap.$DemandLedSupplierScan?">
          <set_value name="this.$gtlsDemandLedSupplierScan" exact="$gtlsSnap.$DemandLedSupplierScan"/>
        </do_if>
        <do_elseif value="not this.$gtlsDemandLedSupplierScan?">
          <set_value name="this.$gtlsDemandLedSupplierScan" exact="false"/>
        </do_elseif>
        <do_if value="$gtlsSnap.$DemandLedSellDone?">
          <set_value name="this.$gtlsDemandLedSellDone" exact="$gtlsSnap.$DemandLedSellDone"/>
        </do_if>
        <do_if value="$gtlsSnap.$Mk4BuildStorageOnlyMode?">
          <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="$gtlsSnap.$Mk4BuildStorageOnlyMode"/>
        </do_if>
        <do_elseif value="not $gtlsMk4BuildStorageOnlyMode?">
          <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="false"/>
        </do_elseif>
        <do_if value="$gtlsSnap.$Mk4AnchorHome?">
          <set_value name="$gtlsMk4AnchorHome" exact="$gtlsSnap.$Mk4AnchorHome"/>
        </do_if>
        <set_value name="$gtlsDistancePenalty" exact="$gtlsSnap.$DistancePenalty"/>
        <set_value name="$gtlsSourceSellByWare" exact="$gtlsSnap.$SourceSellByWare"/>
        <set_value name="$gtlsUseScoreAwareBuyCap" exact="$gtlsSnap.$UseScoreAwareBuyCap"/>
        <set_value name="$gtlsTopBuyOffersPerWare" exact="$gtlsSnap.$TopBuyOffersPerWare"/>
        <set_value name="$gtlsTopBuyScoresPerWare" exact="$gtlsSnap.$TopBuyScoresPerWare"/>
        <set_value name="$gtlsScoreAwareCandidatesSeen" exact="$gtlsSnap.$ScoreAwareCandidatesSeen"/>
        <set_value name="$gtlsSeenBuyOffers" exact="$gtlsSnap.$SeenBuyOffers"/>
        <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="$gtlsSnap.$BuyBuildStorageOffersPerWare"/>
        <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="$gtlsSnap.$BuildStorageBuyOffersAdded"/>
        <set_value name="$gtYieldMs" exact="$gtlsSnap.$YieldMs"/>
        <set_value name="$buyOffers" exact="$gtlsSnap.$BuyOffers"/>
        <set_value name="$sellOffers" exact="$gtlsSnap.$SellOffers"/>
        <set_value name="$buyOffersPerWare" exact="$gtlsSnap.$BuyOffersPerWare"/>
        <set_value name="$sellOffersPerWare" exact="$gtlsSnap.$SellOffersPerWare"/>
        <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
      </do_if>
      <do_else>
        <do_if value="not $sellOffers?">
          <create_list name="$sellOffers"/>
        </do_if>
        <do_if value="not $buyOffers?">
          <create_list name="$buyOffers"/>
        </do_if>
        <do_if value="not $sellOffersPerWare?">
          <set_value name="$sellOffersPerWare" exact="table[]"/>
        </do_if>
        <do_if value="not $buyOffersPerWare?">
          <set_value name="$buyOffersPerWare" exact="table[]"/>
        </do_if>
        <do_if value="not $gtlsSeenBuyOffers?">
          <set_value name="$gtlsSeenBuyOffers" exact="table[]"/>
        </do_if>
        <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
          <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
        </do_if>
        <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
          <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
        </do_if>
        <do_if value="not $gtYieldMs?">
          <set_value name="$gtYieldMs" exact="1"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
            <set_value name="$gtYieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
          </do_if>
        </do_if>
        <do_if value="$ship? and $ship.exists">
          <set_value name="$gtlsShip" exact="$ship"/>
          <set_value name="$gtlsSearchMode" exact="$searchMode"/>
          <set_value name="$gtlsBuySpaces" exact="if $buySpaces? then $buySpaces else []"/>
          <set_value name="$gtlsSellSpaces" exact="if $sellSpaces? then $sellSpaces else []"/>
          <set_value name="$gtlsHomeSector" exact="$homeSector"/>
          <set_value name="$gtlsMaxDistance" exact="$maxDistance"/>
          <set_value name="$gtlsWareBasket" exact="$wareBasket"/>
          <set_value name="$gtlsAllowIllegal" exact="$allowIllegal"/>
          <set_value name="$gtlsOwnerFilter" exact="$ownerFilter"/>
          <set_value name="$gtlsIgnoreMK1Supply" exact="$ignoreMK1Supply"/>
          <set_value name="$gtlsIgnoreTradeRules" exact="$ignoreTradeRules"/>
          <set_value name="$gtlsMaxOffersPerWare" exact="$maxOffersPerWare"/>
          <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $maxOffersPerWare].min].max"/>
          <set_value name="$gtlsSellPriceMax" exact="$sellPriceMax"/>
          <set_value name="$gtlsBuyPriceMin" exact="$buyPriceMin"/>
          <set_value name="$gtlsIncludePlayerBuyOffers" exact="$includePlayerBuyOffers"/>
          <set_value name="$gtlsIncludePlayerSellOffers" exact="$includePlayerSellOffers"/>
          <set_value name="$gtlsRequirePlayerBuyOfferOwner" exact="$requirePlayerBuyOfferOwner"/>
          <set_value name="$gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed" exact="$ignoreTradeRulesPlayerBuyOffersRequireCargoNeed"/>
          <set_value name="$gtlsBypassPlayerSellerPricing" exact="$bypassPlayerSellerPricing"/>
          <set_value name="$gtlsExcludePlayerBuyers" exact="$excludePlayerBuyers"/>
          <set_value name="$gtlsPriorityWares" exact="if $priorityWares? then $priorityWares else []"/>
          <set_value name="$gtlsDebugchance" exact="$debugchance"/>
          <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="if $mk4BuildStorageOnlyMode? then $mk4BuildStorageOnlyMode else false"/>
          <set_value name="$gtlsMk4AnchorHome" exact="if $mk4AnchorHome? then $mk4AnchorHome else null"/>
          <do_if value="not this.$gtlsDemandLedSupplierScan?">
            <set_value name="this.$gtlsDemandLedSupplierScan" exact="if $demandLedSupplierScan? then $demandLedSupplierScan else false"/>
          </do_if>
          <set_value name="$gtlsDistancePenalty" exact="if $distancePenalty? then $distancePenalty else 0.1"/>
          <set_value name="$gtlsSourceSellByWare" exact="table[]"/>
          <set_value name="$gtlsUseScoreAwareBuyCap" exact="false"/>
          <set_value name="$gtlsTopBuyOffersPerWare" exact="table[]"/>
          <set_value name="$gtlsTopBuyScoresPerWare" exact="table[]"/>
          <set_value name="$gtlsScoreAwareCandidatesSeen" exact="0"/>
          <do_if value="$scoreAwareBuyCap? and $scoreAwareBuyCap and $sourceSellOffers? and $sourceSellOffers.count gt 0">
            <do_all exact="$sourceSellOffers.count" counter="$gtlsSsi">
              <set_value name="$gtlsSourceSellOffer" exact="$sourceSellOffers.{$gtlsSsi}"/>
              <do_if value="$gtlsSourceSellOffer? and $gtlsSourceSellOffer.ware? and @$gtlsSourceSellOffer.exists and $gtlsSourceSellOffer.available and $gtlsSourceSellOffer.amount gt 0">
                <set_value name="$gtlsSourceSellByWare.{$gtlsSourceSellOffer.ware}" exact="$gtlsSourceSellOffer"/>
                <set_value name="$gtlsUseScoreAwareBuyCap" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$gtlsUseAllWares" exact="(not $gtlsWareBasket? or $gtlsWareBasket.count == 0)"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
        </do_if>
      </do_else>
      <do_if value="not this.$gtlsDemandLedSupplierScan?">
        <set_value name="this.$gtlsDemandLedSupplierScan" exact="false"/>
      </do_if>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': params: sellPriceMax=' + $gtlsSellPriceMax + ' buyPriceMin=' + $gtlsBuyPriceMin + ' mode=' + $gtlsSearchMode + ' buySpaces=' + $gtlsBuySpaces.count + ' sellSpaces=' + $gtlsSellSpaces.count + (if this.$gtlsDemandLedSupplierScan? and this.$gtlsDemandLedSupplierScan then ' demandLed=true' else '')" chance="$gtlsDebugchance"/>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Collect seller offers (ship buys from seller)
           Per-ware cap applied: each ware gets up to $maxOffersPerWare offers.
           Demand-led mode defers this until buy offers define the ware basket (S4).
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <label name="gtls_collect_sell_offers"/>
      <!-- MK4 supply: max customer buy unitprice per ware â€” prefilter suppliers before clamp (mirrors tradematch price cap). -->
      <set_value name="this.$gtlsMaxBuyUnitPriceByWare" exact="table[]"/>
      <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" exact="0"/>
      <do_if value="$gtlsRequirePlayerBuyOfferOwner and $buyOffers? and $buyOffers.count gt 0">
        <do_all exact="$buyOffers.count" counter="$gtlsMbpIdx">
          <set_value name="$gtlsMbpOffer" exact="$buyOffers.{$gtlsMbpIdx}"/>
          <set_value name="$gtlsMbpWare" exact="@$gtlsMbpOffer.ware"/>
          <do_if value="$gtlsMbpWare? and $gtlsMbpOffer.unitprice?">
            <do_if value="not this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWare}? or $gtlsMbpOffer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWare}">
              <set_value name="this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWare}" exact="$gtlsMbpOffer.unitprice"/>
            </do_if>
          </do_if>
        </do_all>
      </do_if>
      <do_if value="$gtlsSearchMode != 'sell_only' and $gtlsBuySpaces? and $gtlsBuySpaces.count gt 0 and (not this.$gtlsDemandLedSupplierScan? or not this.$gtlsDemandLedSupplierScan or this.$gtlsDemandLedSellDone?)">
        <do_all exact="$gtlsBuySpaces.count" counter="$si">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <set_value name="$space" exact="$gtlsBuySpaces.{$si}"/>
          <do_if value="$gtlsUseAllWares">
            <do_if value="$gtlsIncludePlayerSellOffers">
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_if>
            <do_else>
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_else>
            <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
              <do_all exact="$foundSellOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <!-- MK4 supply: supplier unitprice must not exceed max customer buy price for this ware. -->
                <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing and $offer.ware?">
                  <set_value name="$gtlsMbpWareCheck" exact="@$offer.ware"/>
                  <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWareCheck}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWareCheck}">
                    <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>
                <!-- Reject broker phantoms: relativeprice/offeramount can pass while seller has
                     no exportable stock (trade_found clamp â†’ seller_cargo=0). Mirrors tradematch
                     and order.trade.galaxytrader executable-filter seller resolution. -->
                <set_value name="$gtlsSellClampSeller" exact="null"/>
                <do_if value="$offer.seller?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.seller"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller == null and $offer.owner?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.owner"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller != null">
                  <set_value name="$gtlsSellClampAmt" exact="0"/>
                  <do_if value="$offer.offeramount.{$gtlsShip}? and $offer.offeramount.{$gtlsShip} gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.offeramount.{$gtlsShip}"/>
                  </do_if>
                  <do_elseif value="$offer.amount? and $offer.amount gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.amount"/>
                  </do_elseif>
                  <do_else>
                    <set_value name="$gtlsSellClampAmt" exact="1"/>
                  </do_else>
                  <set_value name="$gtlsSellClampReason" exact="null"/>
                  <clamp_trade_amount trade="$offer" amount="$gtlsSellClampAmt" buyer="$gtlsShip" seller="$gtlsSellClampSeller" result="$gtlsSellClampAmt" reason="$gtlsSellClampReason"/>
                  <do_if value="not $gtlsSellClampAmt? or $gtlsSellClampAmt le 0">
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
                <!-- Per-ware cap: ensure ware diversity. Build-storage suppliers get a reserved
                     slot budget (mirrors buy-side build-storage reserve) so HQ supply is not
                     crowded out when NPC/trading-station offers fill the base cap first. -->
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <do_if value="not $sellOffersPerWare.{$offerWare}?">
                    <set_value name="$sellOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <set_value name="$isBuildStorageSellSupplier" exact="$offer.owner? and $offer.owner.isclass.buildstorage"/>
                  <do_if value="$isBuildStorageSellSupplier">
                    <do_if value="not $gtlsBuildStorageReservePerWare?">
                      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$sellOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                      <continue/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="$sellOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                  </do_else>
                  <set_value name="$sellOffersPerWare.{$offerWare}" operation="add"/>
                </do_if>
                <append_to_list name="$sellOffers" exact="$offer"/>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
          <do_all exact="$gtlsWareBasket.count" counter="$wi">
            <set_value name="$ware" exact="$gtlsWareBasket.{$wi}"/>
            <!-- Skip this ware entirely if we already have enough sell offers for it -->
            <do_if value="$sellOffersPerWare.{$ware}? and $sellOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
              <continue/>
            </do_if>
            <do_if value="$gtlsIncludePlayerSellOffers">
              <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
              <set_value name="$gtlsWareTvMax" exact="999999999"/>
              <do_if value="$ware.waretransport == waretransport.solid">
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinSolid? then this.$gtlsTvMinSolid else 1"/>
              </do_if>
              <do_elseif value="$ware.waretransport == waretransport.liquid">
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinLiquid? then this.$gtlsTvMinLiquid else 1"/>
              </do_elseif>
              <do_if value="this.$gtlsSearchPurpose == 'direct_live'">
                <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxContainer? then this.$gtlsTvMaxContainer else 0"/>
                <do_if value="$ware.waretransport == waretransport.solid">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxSolid? then this.$gtlsTvMaxSolid else 0"/>
                </do_if>
                <do_elseif value="$ware.waretransport == waretransport.liquid">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxLiquid? then this.$gtlsTvMaxLiquid else 0"/>
                </do_elseif>
              </do_if>
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <totalvolume min="$gtlsWareTvMin"/>
                <mintotalvolume max="$gtlsWareTvMax"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_if>
            <do_else>
              <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
              <set_value name="$gtlsWareTvMax" exact="999999999"/>
              <do_if value="$ware.waretransport == waretransport.solid">
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinSolid? then this.$gtlsTvMinSolid else 1"/>
              </do_if>
              <do_elseif value="$ware.waretransport == waretransport.liquid">
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinLiquid? then this.$gtlsTvMinLiquid else 1"/>
              </do_elseif>
              <do_if value="this.$gtlsSearchPurpose == 'direct_live'">
                <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxContainer? then this.$gtlsTvMaxContainer else 0"/>
                <do_if value="$ware.waretransport == waretransport.solid">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxSolid? then this.$gtlsTvMaxSolid else 0"/>
                </do_if>
                <do_elseif value="$ware.waretransport == waretransport.liquid">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxLiquid? then this.$gtlsTvMaxLiquid else 0"/>
                </do_elseif>
              </do_if>
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <totalvolume min="$gtlsWareTvMin"/>
                <mintotalvolume max="$gtlsWareTvMax"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_else>
            <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
              <do_if value="not $sellOffersPerWare.{$ware}?">
                <set_value name="$sellOffersPerWare.{$ware}" exact="0"/>
              </do_if>
              <do_all exact="$foundSellOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
                <set_value name="$isBuildStorageSellSupplier" exact="$offer.owner? and $offer.owner.isclass.buildstorage"/>
                <do_if value="$isBuildStorageSellSupplier">
                  <do_if value="not $gtlsBuildStorageReservePerWare?">
                    <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="$sellOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                    <break/>
                  </do_if>
                </do_else>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <!-- MK4 supply: supplier unitprice must not exceed max customer buy price for this ware. -->
                <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing">
                  <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$ware}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$ware}">
                    <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>
                <set_value name="$gtlsSellClampSeller" exact="null"/>
                <do_if value="$offer.seller?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.seller"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller == null and $offer.owner?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.owner"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller != null">
                  <set_value name="$gtlsSellClampAmt" exact="0"/>
                  <do_if value="$offer.offeramount.{$gtlsShip}? and $offer.offeramount.{$gtlsShip} gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.offeramount.{$gtlsShip}"/>
                  </do_if>
                  <do_elseif value="$offer.amount? and $offer.amount gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.amount"/>
                  </do_elseif>
                  <do_else>
                    <set_value name="$gtlsSellClampAmt" exact="1"/>
                  </do_else>
                  <set_value name="$gtlsSellClampReason" exact="null"/>
                  <clamp_trade_amount trade="$offer" amount="$gtlsSellClampAmt" buyer="$gtlsShip" seller="$gtlsSellClampSeller" result="$gtlsSellClampAmt" reason="$gtlsSellClampReason"/>
                  <do_if value="not $gtlsSellClampAmt? or $gtlsSellClampAmt le 0">
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
                <append_to_list name="$sellOffers" exact="$offer"/>
                <set_value name="$sellOffersPerWare.{$ware}" operation="add"/>
              </do_all>
            </do_if>
          </do_all>
          </do_else>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after sell-offer sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
      </do_if>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': sell-offers collected=' + $sellOffers.count + ' (sellPriceMax=' + $gtlsSellPriceMax + (if $gtlsRequirePlayerBuyOfferOwner and this.$gtlsMk4PriceCapPrefilterSkipped? and this.$gtlsMk4PriceCapPrefilterSkipped gt 0 then ', mk4PriceCapPrefilterSkipped=' + this.$gtlsMk4PriceCapPrefilterSkipped else '') + ')'" chance="$gtlsDebugchance"/>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           MK3 'Ignore Player Pricing' supplemental scan: collect player-owned
           sell offers without relativeprice filtering so the ship buys from
           player stations regardless of the player-set sell price band.
           Deduplicates against offers already added by the main scan.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="$gtlsBypassPlayerSellerPricing and $gtlsSearchMode != 'sell_only' and $gtlsBuySpaces? and $gtlsBuySpaces.count gt 0 and $gtlsOwnerFilter != 'npc_only' and (not this.$gtlsDemandLedSupplierScan? or not this.$gtlsDemandLedSupplierScan or this.$gtlsDemandLedSellDone?)">
        <set_value name="$gtlsSeenSellOffers" exact="table[]"/>
        <do_all exact="$sellOffers.count" counter="$bpInit">
          <set_value name="$gtlsSeenSellOffers.{$sellOffers.{$bpInit}}" exact="true"/>
        </do_all>
        <set_value name="$playerSellOffersAdded" exact="0"/>
        <do_all exact="$gtlsBuySpaces.count" counter="$bpSi">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>

          <set_value name="$space" exact="$gtlsBuySpaces.{$bpSi}"/>
          <do_if value="$gtlsUseAllWares">
            <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$bpSellOffers" multiple="true">
              <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
              </match_seller>
              <amount min="1"/>
            </find_sell_offer>
            <do_if value="$bpSellOffers? and $bpSellOffers.count gt 0">
              <do_all exact="$bpSellOffers.count" counter="$bpOi">
                <set_value name="$offer" exact="$bpSellOffers.{$bpOi}"/>
                <do_if value="$gtlsSeenSellOffers.{$offer}?">
                  <continue/>
                </do_if>
                <do_if value="not $offer.owner? or not @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <do_if value="not $sellOffersPerWare.{$offerWare}?">
                    <set_value name="$sellOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                    <continue/>
                  </do_if>
                  <set_value name="$sellOffersPerWare.{$offerWare}" operation="add"/>
                </do_if>
                <set_value name="$gtlsSeenSellOffers.{$offer}" exact="true"/>
                <append_to_list name="$sellOffers" exact="$offer"/>
                <set_value name="$playerSellOffersAdded" operation="add"/>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
            <do_all exact="$gtlsWareBasket.count" counter="$bpWi">
              <set_value name="$ware" exact="$gtlsWareBasket.{$bpWi}"/>
              <do_if value="$sellOffersPerWare.{$ware}? and $sellOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                <continue/>
              </do_if>
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$bpSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                </match_seller>
                <amount min="1"/>
                <totalvolume min="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
              </find_sell_offer>
              <do_if value="$bpSellOffers? and $bpSellOffers.count gt 0">
                <do_if value="not $sellOffersPerWare.{$ware}?">
                  <set_value name="$sellOffersPerWare.{$ware}" exact="0"/>
                </do_if>
                <do_all exact="$bpSellOffers.count" counter="$bpOi">
                  <do_if value="$sellOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                    <break/>
                  </do_if>
                  <set_value name="$offer" exact="$bpSellOffers.{$bpOi}"/>
                  <do_if value="$gtlsSeenSellOffers.{$offer}?">
                    <continue/>
                  </do_if>
                  <do_if value="not $offer.owner? or not @$offer.owner.isplayerowned">
                    <continue/>
                  </do_if>
                  <set_value name="$gtlsSeenSellOffers.{$offer}" exact="true"/>
                  <append_to_list name="$sellOffers" exact="$offer"/>
                  <set_value name="$sellOffersPerWare.{$ware}" operation="add"/>
                  <set_value name="$playerSellOffersAdded" operation="add"/>
                </do_all>
              </do_if>
            </do_all>
          </do_else>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after player-seller supplement sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': bypassPlayerSellerPricing supplement added=' + $playerSellOffersAdded + ' player sell offers (total sell=' + $sellOffers.count + ')'" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           MK4 single-trip completion pass (auto-wares only):
           Pre-collect player buy offers whose remaining cargo need fits in one ship load
           (deficit <= freeCargo / ware.volume). These bypass the per-ware cap so small
           remainder deliveries (e.g. 54 Quantum Tubes) are not crowded out. Gate uses only
           station target/count and ship cargo â€” no fixed unit or percent thresholds.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>
      <do_if value="$gtlsRequirePlayerBuyOfferOwner and $gtlsUseAllWares and $gtlsSearchMode != 'buy_only' and $gtlsSellSpaces? and $gtlsSellSpaces.count gt 0">
        <set_value name="$completionBuyOffersAdded" exact="0"/>
        <do_all exact="$gtlsSellSpaces.count" counter="$cpsi">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>

          <set_value name="$space" exact="$gtlsSellSpaces.{$cpsi}"/>
          <find_buy_offer space="$space" result="$completionBuyOffers" multiple="true">
            <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
              <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
              <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
            </match_buyer>
            <amount min="1"/>
          </find_buy_offer>
          <do_if value="$completionBuyOffers? and $completionBuyOffers.count gt 0">
            <do_all exact="$completionBuyOffers.count" counter="$cpoi">
              <set_value name="$offer" exact="$completionBuyOffers.{$cpoi}"/>
              <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                <continue/>
              </do_if>
              <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                <continue/>
              </do_if>
              <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                <continue/>
              </do_if>
              <set_value name="$offerWare" exact="if $offer.ware? then @$offer.ware else null"/>
              <set_value name="$offerCustomer" exact="if $offer.buyer? and @$offer.buyer.exists then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
              <do_if value="not $offerWare? or not $offerCustomer? or not @$offerCustomer.exists">
                <continue/>
              </do_if>
              <do_if value="if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false">
                <do_if value="not @$offerCustomer.isclass.buildstorage">
                  <continue/>
                </do_if>
              </do_if>
              <do_elseif value="$offerCustomer.isclass.buildstorage">
                <continue/>
              </do_elseif>
              <set_value name="$cpTarget" exact="$offerCustomer.cargo.{$offerWare}.target"/>
              <set_value name="$cpCount" exact="$offerCustomer.cargo.{$offerWare}.count"/>
              <set_value name="$cpDeficit" exact="[$cpTarget - $cpCount, 0].max"/>
              <do_if value="$cpDeficit le 0">
                <continue/>
              </do_if>
              <set_value name="$cpVolPerUnit" exact="if $offerWare.volume? and $offerWare.volume gt 0 then $offerWare.volume else 1"/>
              <set_value name="$cpOneTripUnits" exact="($gtlsShip.cargo.free.all / $cpVolPerUnit)i"/>
              <do_if value="$cpOneTripUnits le 0 or $cpDeficit gt $cpOneTripUnits">
                <continue/>
              </do_if>
              <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
              <append_to_list name="$buyOffers" exact="$offer"/>
              <set_value name="$completionBuyOffersAdded" operation="add"/>
            </do_all>
          </do_if>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after MK4 completion buy-offer sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': MK4 single-trip completion pass added=' + $completionBuyOffersAdded + ' player buy offers (total buy=' + $buyOffers.count + ')'" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Collect buyer offers (ship sells to buyer)
           Per-ware cap applied: each ware gets up to $maxOffersPerWare offers.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="$gtlsSearchMode != 'buy_only'">
        <do_if value="$gtlsSellSpaces.count gt 0">
        <do_all exact="$gtlsSellSpaces.count" counter="$si">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <set_value name="$space" exact="$gtlsSellSpaces.{$si}"/>
          <do_if value="$gtlsUseAllWares">
            <!-- Always start with partner-filtered offers so normal execution constraints stay intact. -->
            <find_buy_offer tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
              <match_buyer tradesknownto="$gtlsShip.owner">
                <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1" tradepartner="$gtlsShip"/>
              <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
            </find_buy_offer>
            <do_if value="$gtlsIgnoreTradeRules">
              <!-- ignoreTradeRules scope: only bypass player-station trade rules.
                   Do not broaden to non-player stations or bypass other partner checks. -->
              <find_buy_offer space="$space" result="$ignoreRulesBuyOffers" multiple="true">
                <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <amount min="1"/>
              </find_buy_offer>
              <do_if value="not $foundBuyOffers?">
                <create_list name="$foundBuyOffers"/>
              </do_if>
              <do_if value="$ignoreRulesBuyOffers? and $ignoreRulesBuyOffers.count gt 0">
                <do_all exact="$ignoreRulesBuyOffers.count" counter="$iri">
                  <append_to_list name="$foundBuyOffers" exact="$ignoreRulesBuyOffers.{$iri}"/>
                </do_all>
              </do_if>
            </do_if>
            <do_if value="$foundBuyOffers? and $foundBuyOffers.count gt 0">
              <do_all exact="$foundBuyOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundBuyOffers.{$oi}"/>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                  <continue/>
                </do_if>
                <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                  <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                  <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                    <do_if value="@$gtlsBuyerObj.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_if>
                    <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $gtlsPlayerBuyerOk">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                  <continue/>
                </do_if>
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <set_value name="$capWare" exact="$offerWare"/>
                  <set_value name="$capAccepted" exact="false"/>
                  <set_value name="$capScoreAwareCandidate" exact="false"/>
                  <do_if value="$gtlsUseScoreAwareBuyCap and $gtlsSourceSellByWare.{$capWare}?">
                    <set_value name="$homeSellOffer" exact="$gtlsSourceSellByWare.{$capWare}"/>
                    <do_if value="$homeSellOffer? and @$homeSellOffer.exists and $homeSellOffer.available">
                      <set_value name="$unitProfit" exact="$offer.unitprice - $homeSellOffer.unitprice"/>
                      <do_if value="$unitProfit ge 0">
                        <set_value name="$buyOfferAmount" exact="@$offer.offeramount.{$gtlsShip}"/>
                        <do_if value="$buyOfferAmount == null">
                          <set_value name="$buyOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$sellOfferAmount" exact="@$homeSellOffer.offeramount.{$gtlsShip}"/>
                        <do_if value="$sellOfferAmount == null">
                          <set_value name="$sellOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$tradeAmount" exact="[[$buyOfferAmount, $sellOfferAmount].min, 0].max"/>
                        <do_if value="$tradeAmount gt 0">
                          <set_value name="$buyerStation" exact="null"/>
                          <do_if value="$offer.buyer? and @$offer.buyer.exists">
                            <set_value name="$buyerStation" exact="@$offer.buyer"/>
                          </do_if>
                          <do_elseif value="$offer.owner?">
                            <set_value name="$buyerStation" exact="@$offer.owner"/>
                          </do_elseif>
                          <set_value name="$buyerDist" exact="if $buyerStation? and $gtlsHomeSector? then $gtlsHomeSector.gatedistance.{$buyerStation.sector} else -1"/>
                          <do_if value="$buyerDist ge 0 and ($gtlsMaxDistance le 0 or $buyerDist le $gtlsMaxDistance)">
                            <set_value name="$distFactor" exact="1.0 + ($buyerDist * $gtlsDistancePenalty)"/>
                            <set_value name="$grossProfitCr" exact="(($unitProfit * $tradeAmount) / 1Cr)i"/>
                            <set_value name="$capScore" exact="$grossProfitCr / $distFactor"/>
                            <set_value name="$capScoreAwareCandidate" exact="true"/>
                            <do_if value="not $gtlsTopBuyOffersPerWare.{$capWare}?">
                              <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="[]"/>
                              <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="[]"/>
                            </do_if>
                            <set_value name="$topOffers" exact="$gtlsTopBuyOffersPerWare.{$capWare}"/>
                            <set_value name="$topScores" exact="$gtlsTopBuyScoresPerWare.{$capWare}"/>
                            <do_if value="$topOffers.count lt $gtlsMaxOffersPerWare">
                              <append_to_list name="$topOffers" exact="$offer"/>
                              <append_to_list name="$topScores" exact="$capScore"/>
                              <set_value name="$capAccepted" exact="true"/>
                            </do_if>
                            <do_else>
                              <set_value name="$minScore" exact="$topScores.{1}"/>
                              <set_value name="$minScoreIdx" exact="1"/>
                              <do_all exact="$topScores.count" counter="$tsi">
                                <do_if value="$topScores.{$tsi} lt $minScore">
                                  <set_value name="$minScore" exact="$topScores.{$tsi}"/>
                                  <set_value name="$minScoreIdx" exact="$tsi"/>
                                </do_if>
                              </do_all>
                              <do_if value="$capScore gt $minScore">
                                <set_value name="$topOffers.{$minScoreIdx}" exact="$offer"/>
                                <set_value name="$topScores.{$minScoreIdx}" exact="$capScore"/>
                                <set_value name="$capAccepted" exact="true"/>
                              </do_if>
                            </do_else>
                            <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="$topOffers"/>
                            <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="$topScores"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="not $buyOffersPerWare.{$capWare}?">
                      <set_value name="$buyOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$capWare}?">
                      <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                    <set_value name="$capFull" exact="false"/>
                    <do_if value="$isBuildStorageBuyer">
                      <do_if value="$buyOffersPerWare.{$capWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="$buyOffersPerWare.{$capWare} ge $gtlsMaxOffersPerWare">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_else>
                    <do_if value="not $capFull">
                      <do_if value="$isBuildStorageBuyer">
                        <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" operation="add"/>
                        <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                      </do_if>
                      <append_to_list name="$buyOffers" exact="$offer"/>
                      <set_value name="$buyOffersPerWare.{$capWare}" operation="add"/>
                      <set_value name="$capAccepted" exact="true"/>
                    </do_if>
                  </do_else>
                  <do_if value="$capAccepted">
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <do_if value="$capScoreAwareCandidate">
                      <set_value name="$gtlsScoreAwareCandidatesSeen" operation="add"/>
                    </do_if>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
          <do_all exact="$gtlsWareBasket.count" counter="$wi">
            <set_value name="$ware" exact="$gtlsWareBasket.{$wi}"/>
            <!-- Skip this ware entirely if we already have enough buy offers for it -->
            <do_if value="not $gtlsBuildStorageReservePerWare?">
              <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
            </do_if>
            <do_if value="not $gtlsUseScoreAwareBuyCap and $buyOffersPerWare.{$ware}? and $buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
              <continue/>
            </do_if>
            <!-- Always start with partner-filtered offers so normal execution constraints stay intact. -->
            <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
            <set_value name="$gtlsWareTvMax" exact="999999999"/>
            <do_if value="$ware.waretransport == waretransport.solid">
              <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinSolid? then this.$gtlsTvMinSolid else 1"/>
            </do_if>
            <do_elseif value="$ware.waretransport == waretransport.liquid">
              <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinLiquid? then this.$gtlsTvMinLiquid else 1"/>
            </do_elseif>
            <do_if value="this.$gtlsSearchPurpose == 'direct_live'">
              <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxContainer? then this.$gtlsTvMaxContainer else 0"/>
              <do_if value="$ware.waretransport == waretransport.solid">
                <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxSolid? then this.$gtlsTvMaxSolid else 0"/>
              </do_if>
              <do_elseif value="$ware.waretransport == waretransport.liquid">
                <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxLiquid? then this.$gtlsTvMaxLiquid else 0"/>
              </do_elseif>
            </do_if>
            <find_buy_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
              <match_buyer tradesknownto="$gtlsShip.owner">
                <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1" tradepartner="$gtlsShip"/>
              <totalvolume min="$gtlsWareTvMin"/>
              <mintotalvolume max="$gtlsWareTvMax"/>
              <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
            </find_buy_offer>
            <do_if value="$gtlsIgnoreTradeRules">
              <!-- ignoreTradeRules scope: only bypass player-station trade rules.
                   Do not broaden to non-player stations or bypass other partner checks. -->
              <find_buy_offer wares="$ware" space="$space" result="$ignoreRulesBuyOffers" multiple="true">
                <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <amount min="1"/>
                <totalvolume min="$gtlsWareTvMin"/>
                <mintotalvolume max="$gtlsWareTvMax"/>
              </find_buy_offer>
              <do_if value="not $foundBuyOffers?">
                <create_list name="$foundBuyOffers"/>
              </do_if>
              <do_if value="$ignoreRulesBuyOffers? and $ignoreRulesBuyOffers.count gt 0">
                <do_all exact="$ignoreRulesBuyOffers.count" counter="$iri">
                  <append_to_list name="$foundBuyOffers" exact="$ignoreRulesBuyOffers.{$iri}"/>
                </do_all>
              </do_if>
            </do_if>
            <do_if value="$foundBuyOffers? and $foundBuyOffers.count gt 0">
              <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
              </do_if>
              <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
              </do_if>
              <do_if value="not $buyOffersPerWare.{$ware}?">
                <set_value name="$buyOffersPerWare.{$ware}" exact="0"/>
              </do_if>
              <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$ware}?">
                <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$ware}" exact="0"/>
              </do_if>
              <do_all exact="$foundBuyOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundBuyOffers.{$oi}"/>
                <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                <do_if value="$isBuildStorageBuyer">
                  <do_if value="not $gtlsBuildStorageReservePerWare?">
                    <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="not $gtlsUseScoreAwareBuyCap and $buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                    <continue/>
                  </do_if>
                </do_if>
                <do_elseif value="not $gtlsUseScoreAwareBuyCap">
                  <do_if value="$buyOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                    <break/>
                  </do_if>
                </do_elseif>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                  <continue/>
                </do_if>
                <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                  <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                  <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                    <do_if value="@$gtlsBuyerObj.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_if>
                    <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $gtlsPlayerBuyerOk">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                  <continue/>
                </do_if>
                <set_value name="$capWare" exact="$ware"/>
                <set_value name="$capAccepted" exact="false"/>
                  <set_value name="$capScoreAwareCandidate" exact="false"/>
                  <do_if value="$gtlsUseScoreAwareBuyCap and $gtlsSourceSellByWare.{$capWare}?">
                    <set_value name="$homeSellOffer" exact="$gtlsSourceSellByWare.{$capWare}"/>
                    <do_if value="$homeSellOffer? and @$homeSellOffer.exists and $homeSellOffer.available">
                      <set_value name="$unitProfit" exact="$offer.unitprice - $homeSellOffer.unitprice"/>
                      <do_if value="$unitProfit ge 0">
                        <set_value name="$buyOfferAmount" exact="@$offer.offeramount.{$gtlsShip}"/>
                        <do_if value="$buyOfferAmount == null">
                          <set_value name="$buyOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$sellOfferAmount" exact="@$homeSellOffer.offeramount.{$gtlsShip}"/>
                        <do_if value="$sellOfferAmount == null">
                          <set_value name="$sellOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$tradeAmount" exact="[[$buyOfferAmount, $sellOfferAmount].min, 0].max"/>
                        <do_if value="$tradeAmount gt 0">
                          <set_value name="$buyerStation" exact="null"/>
                          <do_if value="$offer.buyer? and @$offer.buyer.exists">
                            <set_value name="$buyerStation" exact="@$offer.buyer"/>
                          </do_if>
                          <do_elseif value="$offer.owner?">
                            <set_value name="$buyerStation" exact="@$offer.owner"/>
                          </do_elseif>
                          <set_value name="$buyerDist" exact="if $buyerStation? and $gtlsHomeSector? then $gtlsHomeSector.gatedistance.{$buyerStation.sector} else -1"/>
                          <do_if value="$buyerDist ge 0 and ($gtlsMaxDistance le 0 or $buyerDist le $gtlsMaxDistance)">
                            <set_value name="$distFactor" exact="1.0 + ($buyerDist * $gtlsDistancePenalty)"/>
                            <set_value name="$grossProfitCr" exact="(($unitProfit * $tradeAmount) / 1Cr)i"/>
                            <set_value name="$capScore" exact="$grossProfitCr / $distFactor"/>
                            <set_value name="$capScoreAwareCandidate" exact="true"/>
                            <do_if value="not $gtlsTopBuyOffersPerWare.{$capWare}?">
                              <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="[]"/>
                              <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="[]"/>
                            </do_if>
                            <set_value name="$topOffers" exact="$gtlsTopBuyOffersPerWare.{$capWare}"/>
                            <set_value name="$topScores" exact="$gtlsTopBuyScoresPerWare.{$capWare}"/>
                            <do_if value="$topOffers.count lt $gtlsMaxOffersPerWare">
                              <append_to_list name="$topOffers" exact="$offer"/>
                              <append_to_list name="$topScores" exact="$capScore"/>
                              <set_value name="$capAccepted" exact="true"/>
                            </do_if>
                            <do_else>
                              <set_value name="$minScore" exact="$topScores.{1}"/>
                              <set_value name="$minScoreIdx" exact="1"/>
                              <do_all exact="$topScores.count" counter="$tsi">
                                <do_if value="$topScores.{$tsi} lt $minScore">
                                  <set_value name="$minScore" exact="$topScores.{$tsi}"/>
                                  <set_value name="$minScoreIdx" exact="$tsi"/>
                                </do_if>
                              </do_all>
                              <do_if value="$capScore gt $minScore">
                                <set_value name="$topOffers.{$minScoreIdx}" exact="$offer"/>
                                <set_value name="$topScores.{$minScoreIdx}" exact="$capScore"/>
                                <set_value name="$capAccepted" exact="true"/>
                              </do_if>
                            </do_else>
                            <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="$topOffers"/>
                            <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="$topScores"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="not $buyOffersPerWare.{$capWare}?">
                      <set_value name="$buyOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$capWare}?">
                      <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                    <set_value name="$capFull" exact="false"/>
                    <do_if value="$isBuildStorageBuyer">
                      <do_if value="$buyOffersPerWare.{$capWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="$buyOffersPerWare.{$capWare} ge $gtlsMaxOffersPerWare">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_else>
                    <do_if value="not $capFull">
                      <do_if value="$isBuildStorageBuyer">
                        <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" operation="add"/>
                        <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                      </do_if>
                      <append_to_list name="$buyOffers" exact="$offer"/>
                      <set_value name="$buyOffersPerWare.{$capWare}" operation="add"/>
                      <set_value name="$capAccepted" exact="true"/>
                    </do_if>
                  </do_else>
                  <do_if value="$capAccepted">
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <do_if value="$capScoreAwareCandidate">
                      <set_value name="$gtlsScoreAwareCandidatesSeen" operation="add"/>
                    </do_if>
                  </do_if>
              </do_all>
            </do_if>
          </do_all>
          </do_else>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after buy-offer sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        </do_if>
      </do_if>
      <!-- MK4 compatibility:
           include player buy offers even when tradepartner-filtered query returns none.
           This is intentionally scoped to player-owned buyers and still respects ware caps;
           downstream AI validation re-checks tradepartner constraints before order creation. -->
      <do_if value="not $gtlsExcludePlayerBuyers and $gtlsIncludePlayerBuyOffers and $gtlsOwnerFilter != 'npc_only' and ($gtlsIgnoreTradeRules or $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed) and $gtlsSearchMode != 'buy_only' and $gtlsSellSpaces? and $gtlsSellSpaces.count gt 0">
        <set_value name="$playerBuyOffersAdded" exact="0"/>
        <set_value name="$suppHasWareBasket" exact="$gtlsWareBasket? and $gtlsWareBasket.count gt 0"/>
        <do_all exact="$gtlsSellSpaces.count" counter="$si">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <set_value name="$space" exact="$gtlsSellSpaces.{$si}"/>
          <do_if value="$gtlsUseAllWares">
            <find_buy_offer space="$space" result="$playerBuyOffers" multiple="true">
              <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1"/>
            </find_buy_offer>
            <do_if value="$playerBuyOffers? and $playerBuyOffers.count gt 0">
              <do_all exact="$playerBuyOffers.count" counter="$oi">
                <set_value name="$offer" exact="$playerBuyOffers.{$oi}"/>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <!-- Honor manual ware basket even in supplemental player-buy scan. -->
                <do_if value="$suppHasWareBasket">
                  <set_value name="$offerWareInBasket" exact="false"/>
                  <set_value name="$offerWare" exact="if $offer.ware? then @$offer.ware else null"/>
                  <do_if value="$offerWare?">
                    <do_all exact="$gtlsWareBasket.count" counter="$wbi">
                      <do_if value="$gtlsWareBasket.{$wbi} == $offerWare">
                        <set_value name="$offerWareInBasket" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  <do_if value="not $offerWareInBasket">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                  <continue/>
                </do_if>
                <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                  <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                  <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                    <do_if value="@$gtlsBuyerObj.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_if>
                    <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $gtlsPlayerBuyerOk">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                  <continue/>
                </do_if>
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
                  </do_if>
                  <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
                  </do_if>
                  <do_if value="not $buyOffersPerWare.{$offerWare}?">
                    <set_value name="$buyOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$offerWare}?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                  <do_if value="$isBuildStorageBuyer">
                    <do_if value="not $gtlsBuildStorageReservePerWare?">
                      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                      <continue/>
                    </do_if>
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$offerWare}" operation="add"/>
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                  </do_if>
                  <do_else>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                  </do_else>
                  <set_value name="$buyOffersPerWare.{$offerWare}" operation="add"/>
                </do_if>
                <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                <append_to_list name="$buyOffers" exact="$offer"/>
                <set_value name="$playerBuyOffersAdded" operation="add"/>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
            <do_all exact="$gtlsWareBasket.count" counter="$wi">
              <set_value name="$ware" exact="$gtlsWareBasket.{$wi}"/>
              <do_if value="not $gtlsBuildStorageReservePerWare?">
                <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
              </do_if>
              <do_if value="$buyOffersPerWare.{$ware}? and $buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                <continue/>
              </do_if>
              <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
              <set_value name="$gtlsWareTvMax" exact="999999999"/>
              <do_if value="$ware.waretransport == waretransport.solid">
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinSolid? then this.$gtlsTvMinSolid else 1"/>
              </do_if>
              <do_elseif value="$ware.waretransport == waretransport.liquid">
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinLiquid? then this.$gtlsTvMinLiquid else 1"/>
              </do_elseif>
              <do_if value="this.$gtlsSearchPurpose == 'direct_live'">
                <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxContainer? then this.$gtlsTvMaxContainer else 0"/>
                <do_if value="$ware.waretransport == waretransport.solid">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxSolid? then this.$gtlsTvMaxSolid else 0"/>
                </do_if>
                <do_elseif value="$ware.waretransport == waretransport.liquid">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxLiquid? then this.$gtlsTvMaxLiquid else 0"/>
                </do_elseif>
              </do_if>
              <find_buy_offer wares="$ware" space="$space" result="$playerBuyOffers" multiple="true">
                <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <offeramount min="1"/>
                <totalvolume min="$gtlsWareTvMin"/>
                <mintotalvolume max="$gtlsWareTvMax"/>
              </find_buy_offer>
              <do_if value="$playerBuyOffers? and $playerBuyOffers.count gt 0">
                <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                  <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
                </do_if>
                <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                  <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
                </do_if>
                <do_if value="not $buyOffersPerWare.{$ware}?">
                  <set_value name="$buyOffersPerWare.{$ware}" exact="0"/>
                </do_if>
                <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$ware}?">
                  <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$ware}" exact="0"/>
                </do_if>
                <do_all exact="$playerBuyOffers.count" counter="$oi">
                  <set_value name="$offer" exact="$playerBuyOffers.{$oi}"/>
                  <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                  <do_if value="$isBuildStorageBuyer">
                    <do_if value="not $gtlsBuildStorageReservePerWare?">
                      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                      <continue/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="$buyOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                      <break/>
                    </do_if>
                  </do_else>
                  <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                    <continue/>
                  </do_if>
                  <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                    <continue/>
                  </do_if>
                  <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                    <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                    <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                    <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                      <do_if value="@$gtlsBuyerObj.isplayerowned">
                        <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                      </do_if>
                      <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                        <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                      </do_elseif>
                    </do_if>
                    <do_if value="not $gtlsPlayerBuyerOk">
                      <continue/>
                    </do_if>
                  </do_if>
                  <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                    <continue/>
                  </do_if>
                  <do_if value="$isBuildStorageBuyer">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$ware}" operation="add"/>
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                  </do_if>
                  <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                  <append_to_list name="$buyOffers" exact="$offer"/>
                  <set_value name="$buyOffersPerWare.{$ware}" operation="add"/>
                  <set_value name="$playerBuyOffersAdded" operation="add"/>
                </do_all>
              </do_if>
            </do_all>
          </do_else>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after player buy-offer supplement"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': player buy-offer supplement added=' + $playerBuyOffersAdded + ' (ignoreTradeRules=' + $gtlsIgnoreTradeRules + ', ignoreCargoNeed=' + $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed + ')'" chance="$gtlsDebugchance"/>
      </do_if>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>
      <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
        <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
      </do_if>
      <do_if value="not $gtlsBuildStorageReservePerWare?">
        <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
      </do_if>
      <!-- Score-aware cap: flatten per-ware top-N tables into the buy-offer result list. -->
      <do_if value="$gtlsUseScoreAwareBuyCap">
        <set_value name="$buyOffers" exact="[]"/>
        <set_value name="$buyOffersPerWare" exact="table[]"/>
        <set_value name="$gtlsFinalizeWareKeys" exact="$gtlsTopBuyOffersPerWare.keys.list"/>
        <do_all exact="$gtlsFinalizeWareKeys.count" counter="$gtlsFwi">
          <set_value name="$gtlsFinalizeWare" exact="$gtlsFinalizeWareKeys.{$gtlsFwi}"/>
          <set_value name="$gtlsFinalizeOffers" exact="$gtlsTopBuyOffersPerWare.{$gtlsFinalizeWare}"/>
          <do_if value="$gtlsFinalizeOffers? and $gtlsFinalizeOffers.count gt 0">
            <do_all exact="$gtlsFinalizeOffers.count" counter="$gtlsFoi">
              <append_to_list name="$buyOffers" exact="$gtlsFinalizeOffers.{$gtlsFoi}"/>
            </do_all>
            <set_value name="$buyOffersPerWare.{$gtlsFinalizeWare}" exact="$gtlsFinalizeOffers.count"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': score-aware buy cap finalized candidatesSeen=' + $gtlsScoreAwareCandidatesSeen + ' retained=' + $buyOffers.count + ' wares=' + $gtlsFinalizeWareKeys.count" chance="$gtlsDebugchance"/>
      </do_if>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buy-offers collected=' + $buyOffers.count + ' (buyPriceMin=' + $gtlsBuyPriceMin + ', buildStorageBuyOffers=' + $gtlsBuildStorageBuyOffersAdded + ', reservePerWare=' + $gtlsBuildStorageReservePerWare + (if $gtlsUseScoreAwareBuyCap then ', scoreAwareCap=true' else '') + ')'" chance="$gtlsDebugchance"/>
      <!-- Demand-led supplier scan (MK4 S4): derive ware basket from collected buy offers, then collect sell offers for those wares only. -->
      <do_if value="this.$gtlsDemandLedSupplierScan? and this.$gtlsDemandLedSupplierScan and $gtlsSearchMode == 'buy_and_sell' and not this.$gtlsDemandLedSellDone?">
        <create_list name="$gtlsDemandWareBasket"/>
        <set_value name="$gtlsDemandWareSeen" exact="table[]"/>
        <do_all exact="$buyOffers.count" counter="$dlwi">
          <set_value name="$dlwo" exact="$buyOffers.{$dlwi}"/>
          <set_value name="$dlww" exact="@$dlwo.ware"/>
          <do_if value="$dlww? and not $gtlsDemandWareSeen.{$dlww}?">
            <set_value name="$gtlsDemandWareSeen.{$dlww}" exact="true"/>
            <append_to_list name="$gtlsDemandWareBasket" exact="$dlww"/>
          </do_if>
        </do_all>
        <set_value name="$gtlsWareBasket" exact="$gtlsDemandWareBasket"/>
        <set_value name="$gtlsUseAllWares" exact="false"/>
        <set_value name="this.$gtlsDemandLedSellDone" exact="true"/>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': demand-led supplier scan: demandWares=' + $gtlsDemandWareBasket.count + ' from buyOffers=' + $buyOffers.count" chance="$gtlsDebugchance"/>
        <do_if value="global.$GT_LiveSearchScratch? and global.$GT_LiveSearchScratch.{$gtlsShip}?">
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$WareBasket" exact="$gtlsWareBasket"/>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$UseAllWares" exact="$gtlsUseAllWares"/>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$DemandLedSupplierScan" exact="this.$gtlsDemandLedSupplierScan"/>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$DemandLedSellDone" exact="true"/>
        </do_if>
        <resume label="gtls_collect_sell_offers"/>
      </do_if>
      <!-- Normalize priority wares before first use to avoid null .count lookups
           on resumed/search-resume contexts. -->
      <do_if value="not $gtlsPriorityWares? or $gtlsPriorityWares == null">
        <set_value name="$gtlsPriorityWares" exact="[]"/>
      </do_if>
      <set_value name="$priorityWaresCount" exact="$gtlsPriorityWares.count"/>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Explicit priority-ware pass: ensures MK3 priority wares enter the
           tradeable set even if they were omitted from the main search results
           (e.g. engine limits, rare wares). If no offers found, ship still
           trades other wares; scoring will pick the best available.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="$priorityWaresCount gt 0 and $gtlsSearchMode == 'buy_and_sell'">
        <set_value name="$pwSellBefore" exact="$sellOffers.count"/>
        <set_value name="$pwBuyBefore" exact="$buyOffers.count"/>
        <set_value name="$pwNames" exact="''"/>
        <do_all exact="$priorityWaresCount" counter="$pn">
          <set_value name="$pnw" exact="$gtlsPriorityWares.{$pn}"/>
          <set_value name="$pwNames" exact="$pwNames + (if $pn gt 1 then ', ' else '') + (if $pnw? and $pnw != null then @$pnw.name else '?')"/>
        </do_all>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority-ware pass: searching ' + $priorityWaresCount + ' wares: [' + $pwNames + '] allowIllegal=' + $gtlsAllowIllegal" chance="100"/>
        </do_if>
        <do_all exact="$priorityWaresCount" counter="$pwi">
          <set_value name="$pw" exact="$gtlsPriorityWares.{$pwi}"/>
          <do_if value="not $pw? or $pw == null">
            <continue/>
          </do_if>
          <do_if value="not $gtlsAllowIllegal and $pw.illegal">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority ware ' + (if $pw? and $pw != null then @$pw.name else '?') + ' SKIPPED (illegal, allowIllegal=false)'" chance="100"/>
            </do_if>
            <continue/>
          </do_if>
          <!-- Sell offers for this priority ware (ship buys) -->
          <do_if value="$gtlsBuySpaces? and $gtlsBuySpaces.count gt 0">
            <do_if value="not $sellOffersPerWare.{$pw}? or $sellOffersPerWare.{$pw} lt $gtlsMaxOffersPerWare">
              <do_all exact="$gtlsBuySpaces.count" counter="$psi">
                <do_if value="not $gtYieldMs? or not $gtlsShip?">
                  <resume label="gtls_ensure_state"/>
                </do_if>
                <set_value name="$space" exact="$gtlsBuySpaces.{$psi}"/>
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
                <set_value name="$gtlsWareTvMax" exact="999999999"/>
                <do_if value="$pw.waretransport == waretransport.solid">
                  <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinSolid? then this.$gtlsTvMinSolid else 1"/>
                </do_if>
                <do_elseif value="$pw.waretransport == waretransport.liquid">
                  <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinLiquid? then this.$gtlsTvMinLiquid else 1"/>
                </do_elseif>
                <do_if value="this.$gtlsSearchPurpose == 'direct_live'">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxContainer? then this.$gtlsTvMaxContainer else 0"/>
                  <do_if value="$pw.waretransport == waretransport.solid">
                    <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxSolid? then this.$gtlsTvMaxSolid else 0"/>
                  </do_if>
                  <do_elseif value="$pw.waretransport == waretransport.liquid">
                    <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxLiquid? then this.$gtlsTvMaxLiquid else 0"/>
                  </do_elseif>
                </do_if>
                <do_if value="$gtlsIncludePlayerSellOffers">
                  <find_sell_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                    <match_seller tradesknownto="$gtlsShip.owner">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_seller>
                    <amount min="1"/>
                    <totalvolume min="$gtlsWareTvMin"/>
                    <mintotalvolume max="$gtlsWareTvMax"/>
                    <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_sell_offer>
                </do_if>
                <do_else>
                  <find_sell_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                    <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_seller>
                    <amount min="1"/>
                    <totalvolume min="$gtlsWareTvMin"/>
                    <mintotalvolume max="$gtlsWareTvMax"/>
                    <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_sell_offer>
                </do_else>
                <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
                  <do_if value="not $sellOffersPerWare.{$pw}?">
                    <set_value name="$sellOffersPerWare.{$pw}" exact="0"/>
                  </do_if>
                  <do_all exact="$foundSellOffers.count" counter="$oi">
                    <do_if value="$sellOffersPerWare.{$pw} ge $gtlsMaxOffersPerWare">
                      <break/>
                    </do_if>
                    <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
                    <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <!-- MK4 supply: supplier unitprice must not exceed max customer buy price for this ware. -->
                    <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing">
                      <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$pw}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$pw}">
                        <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                        <continue/>
                      </do_if>
                    </do_if>
                    <append_to_list name="$sellOffers" exact="$offer"/>
                    <set_value name="$sellOffersPerWare.{$pw}" operation="add"/>
                  </do_all>
                </do_if>
                <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield priority-ware sell sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

              </do_all>
            </do_if>
          </do_if>
          <!-- Buy offers for this priority ware (ship sells) -->
          <do_if value="$gtlsSellSpaces? and $gtlsSellSpaces.count gt 0">
            <do_if value="not $gtlsBuildStorageReservePerWare?">
              <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
            </do_if>
            <do_if value="not $buyOffersPerWare.{$pw}? or $buyOffersPerWare.{$pw} lt ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
              <do_all exact="$gtlsSellSpaces.count" counter="$psi">
                <do_if value="not $gtYieldMs? or not $gtlsShip?">
                  <resume label="gtls_ensure_state"/>
                </do_if>
                <set_value name="$space" exact="$gtlsSellSpaces.{$psi}"/>
                <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinContainer? then this.$gtlsTvMinContainer else 1"/>
                <set_value name="$gtlsWareTvMax" exact="999999999"/>
                <do_if value="$pw.waretransport == waretransport.solid">
                  <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinSolid? then this.$gtlsTvMinSolid else 1"/>
                </do_if>
                <do_elseif value="$pw.waretransport == waretransport.liquid">
                  <set_value name="$gtlsWareTvMin" exact="if this.$gtlsTvMinLiquid? then this.$gtlsTvMinLiquid else 1"/>
                </do_elseif>
                <do_if value="this.$gtlsSearchPurpose == 'direct_live'">
                  <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxContainer? then this.$gtlsTvMaxContainer else 0"/>
                  <do_if value="$pw.waretransport == waretransport.solid">
                    <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxSolid? then this.$gtlsTvMaxSolid else 0"/>
                  </do_if>
                  <do_elseif value="$pw.waretransport == waretransport.liquid">
                    <set_value name="$gtlsWareTvMax" exact="if this.$gtlsTvMaxLiquid? then this.$gtlsTvMaxLiquid else 0"/>
                  </do_elseif>
                </do_if>
                <find_buy_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$gtlsShip.owner">
                    <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <offeramount min="1" tradepartner="$gtlsShip"/>
                  <totalvolume min="$gtlsWareTvMin"/>
                  <mintotalvolume max="$gtlsWareTvMax"/>
                  <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                </find_buy_offer>
                <do_if value="$foundBuyOffers? and $foundBuyOffers.count gt 0">
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
                  </do_if>
                  <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
                  </do_if>
                  <do_if value="not $buyOffersPerWare.{$pw}?">
                    <set_value name="$buyOffersPerWare.{$pw}" exact="0"/>
                  </do_if>
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$pw}?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$pw}" exact="0"/>
                  </do_if>
                  <do_all exact="$foundBuyOffers.count" counter="$oi">
                    <set_value name="$offer" exact="$foundBuyOffers.{$oi}"/>
                    <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                    <do_if value="$isBuildStorageBuyer">
                      <do_if value="not $gtlsBuildStorageReservePerWare?">
                        <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                      </do_if>
                      <do_if value="$buyOffersPerWare.{$pw} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <continue/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="$buyOffersPerWare.{$pw} ge $gtlsMaxOffersPerWare">
                        <break/>
                      </do_if>
                    </do_else>
                    <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                      <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                      <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                      <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                        <do_if value="@$gtlsBuyerObj.isplayerowned">
                          <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                        </do_if>
                        <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                          <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                        </do_elseif>
                      </do_if>
                      <do_if value="not $gtlsPlayerBuyerOk">
                        <continue/>
                      </do_if>
                    </do_if>
                    <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                      <continue/>
                    </do_if>
                    <do_if value="$isBuildStorageBuyer">
                      <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$pw}" operation="add"/>
                      <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                    </do_if>
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$pw}" operation="add"/>
                  </do_all>
                </do_if>
                <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield priority-ware buy sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

              </do_all>
            </do_if>
          </do_if>
          <set_value name="$pwSellCount" exact="if $sellOffersPerWare.{$pw}? then $sellOffersPerWare.{$pw} else 0"/>
          <set_value name="$pwBuyCount" exact="if $buyOffersPerWare.{$pw}? then $buyOffersPerWare.{$pw} else 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority ware ' + (if $pw? and $pw != null then @$pw.name else '?') + ': sellOffers=' + $pwSellCount + ' buyOffers=' + $pwBuyCount" chance="100"/>
          </do_if>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield priority-ware"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority-ware pass complete: added sellOffers=' + ($sellOffers.count - $pwSellBefore) + ' buyOffers=' + ($buyOffers.count - $pwBuyBefore) + ' (total sell=' + $sellOffers.count + ' buy=' + $buyOffers.count + ')'" chance="100"/>
        </do_if>
      </do_if>
      <!-- MK4 build-storage-only: query buy offers per build-storage buyer (generic player
           buy-offer scans return station owners; construction demand is on buyer=buildstorage).
           Enumerate via player station.buildstorage (vanilla trade.station.xml pattern) plus
           standalone class.buildstorage objects; BS demand may exist without credits (excludeempty=false). -->
      <do_if value="if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false">
        <set_value name="$gtlsBsoDirectBuyAdded" exact="0"/>
        <set_value name="$gtlsBsoHasWareBasket" exact="$gtlsWareBasket? and $gtlsWareBasket.count gt 0"/>
        <set_value name="$gtlsBsoCoverageMax" exact="if $gtlsMaxDistanceSell? and $gtlsMaxDistanceSell gt 0 then $gtlsMaxDistanceSell else $gtlsMaxDistance"/>
        <set_value name="$gtlsBsoScanSpaces" exact="if $gtlsBuySpaces? and $gtlsBuySpaces.count gt 0 then $gtlsBuySpaces else $gtlsSellSpaces"/>
        <set_value name="$gtlsBsoStationsScanned" exact="0"/>
        <set_value name="$gtlsBsoBuyersFound" exact="0"/>
        <do_if value="$gtlsSearchMode != 'buy_only' and $gtlsBsoScanSpaces? and $gtlsBsoScanSpaces.count gt 0">
          <set_value name="$gtlsBsoSeenBuyers" exact="table[]"/>
          <do_all exact="$gtlsBsoScanSpaces.count" counter="$gtlsBsoPsi">
            <do_if value="not $gtYieldMs? or not $gtlsShip?">
              <resume label="gtls_ensure_state"/>
            </do_if>
            <set_value name="$gtlsBsoSpace" exact="$gtlsBsoScanSpaces.{$gtlsBsoPsi}"/>
            <do_if value="not $gtlsBsoSpace? or not @$gtlsBsoSpace.exists">
              <continue/>
            </do_if>
            <find_station name="$gtlsBsoStations" space="$gtlsBsoSpace" checkoperational="true" multiple="true"/>
            <do_if value="$gtlsBsoStations? and $gtlsBsoStations.count gt 0">
              <do_all exact="$gtlsBsoStations.count" counter="$gtlsBsoSti">
                <set_value name="$gtlsBsoStation" exact="$gtlsBsoStations.{$gtlsBsoSti}"/>
                <set_value name="$gtlsBsoStationsScanned" operation="add"/>
                <do_if value="not $gtlsBsoStation? or not @$gtlsBsoStation.exists or not @$gtlsBsoStation.isplayerowned">
                  <continue/>
                </do_if>
                <set_value name="$gtlsBsoBuyer" exact="null"/>
                <do_if value="$gtlsBsoStation.buildstorage? and $gtlsBsoStation.buildstorage.exists">
                  <set_value name="$gtlsBsoBuyer" exact="$gtlsBsoStation.buildstorage"/>
                </do_if>
                <do_elseif value="@$gtlsBsoStation.isclass.buildstorage">
                  <set_value name="$gtlsBsoBuyer" exact="$gtlsBsoStation"/>
                </do_elseif>
                <do_if value="not $gtlsBsoBuyer? or not @$gtlsBsoBuyer.exists or $gtlsBsoSeenBuyers.{$gtlsBsoBuyer}?">
                  <continue/>
                </do_if>
                <set_value name="$gtlsBsoSeenBuyers.{$gtlsBsoBuyer}" exact="true"/>
                <set_value name="$gtlsBsoBuyersFound" operation="add"/>
                <do_if value="$gtlsIgnoreTradeRules">
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <amount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1" tradepartner="$gtlsShip"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$gtlsBsoOffers? and $gtlsBsoOffers.count gt 0">
                  <do_all exact="$gtlsBsoOffers.count" counter="$gtlsBsoBi">
                    <set_value name="$offer" exact="$gtlsBsoOffers.{$gtlsBsoBi}"/>
                    <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and $offer.owner? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                      <continue/>
                    </do_if>
                    <set_value name="$offerWare" exact="@$offer.ware"/>
                    <do_if value="not $offerWare?">
                      <continue/>
                    </do_if>
                    <do_if value="not $gtlsBsoHasWareBasket">
                      <set_value name="$offerWareInBasket" exact="true"/>
                    </do_if>
                    <do_else>
                      <set_value name="$offerWareInBasket" exact="false"/>
                      <do_all exact="$gtlsWareBasket.count" counter="$gtlsBsoWbi">
                        <do_if value="$gtlsWareBasket.{$gtlsBsoWbi} == $offerWare">
                          <set_value name="$offerWareInBasket" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_else>
                    <do_if value="not $offerWareInBasket">
                      <continue/>
                    </do_if>
                    <do_if value="not $buyOffersPerWare.{$offerWare}?">
                      <set_value name="$buyOffersPerWare.{$offerWare}" exact="0"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$offerWare}" operation="add"/>
                    <set_value name="$gtlsBsoDirectBuyAdded" operation="add"/>
                  </do_all>
                </do_if>
              </do_all>
            </do_if>
            <find_object name="$gtlsBsoObjects" class="class.buildstorage" space="$gtlsBsoSpace" owner="faction.player" multiple="true"/>
            <do_if value="$gtlsBsoObjects? and $gtlsBsoObjects.count gt 0">
              <do_all exact="$gtlsBsoObjects.count" counter="$gtlsBsoOi">
                <set_value name="$gtlsBsoBuyer" exact="$gtlsBsoObjects.{$gtlsBsoOi}"/>
                <do_if value="not $gtlsBsoBuyer? or not @$gtlsBsoBuyer.exists or $gtlsBsoSeenBuyers.{$gtlsBsoBuyer}?">
                  <continue/>
                </do_if>
                <set_value name="$gtlsBsoSeenBuyers.{$gtlsBsoBuyer}" exact="true"/>
                <set_value name="$gtlsBsoBuyersFound" operation="add"/>
                <do_if value="$gtlsIgnoreTradeRules">
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <amount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1" tradepartner="$gtlsShip"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$gtlsBsoOffers? and $gtlsBsoOffers.count gt 0">
                  <do_all exact="$gtlsBsoOffers.count" counter="$gtlsBsoBi">
                    <set_value name="$offer" exact="$gtlsBsoOffers.{$gtlsBsoBi}"/>
                    <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and $offer.owner? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                      <continue/>
                    </do_if>
                    <set_value name="$offerWare" exact="@$offer.ware"/>
                    <do_if value="not $offerWare?">
                      <continue/>
                    </do_if>
                    <do_if value="not $gtlsBsoHasWareBasket">
                      <set_value name="$offerWareInBasket" exact="true"/>
                    </do_if>
                    <do_else>
                      <set_value name="$offerWareInBasket" exact="false"/>
                      <do_all exact="$gtlsWareBasket.count" counter="$gtlsBsoWbi">
                        <do_if value="$gtlsWareBasket.{$gtlsBsoWbi} == $offerWare">
                          <set_value name="$offerWareInBasket" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_else>
                    <do_if value="not $offerWareInBasket">
                      <continue/>
                    </do_if>
                    <do_if value="not $buyOffersPerWare.{$offerWare}?">
                      <set_value name="$buyOffersPerWare.{$offerWare}" exact="0"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$offerWare}" operation="add"/>
                    <set_value name="$gtlsBsoDirectBuyAdded" operation="add"/>
                  </do_all>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $gtYieldMs? or not $gtlsShip?">
              <resume label="gtls_ensure_state"/>
            </do_if>
          </do_all>
        </do_if>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buildStorageOnly direct BS buy scan added=' + $gtlsBsoDirectBuyAdded + ' buyers=' + $gtlsBsoBuyersFound + ' stationsScanned=' + $gtlsBsoStationsScanned + ' coverageMax=' + $gtlsBsoCoverageMax + 'j'" chance="100"/>
      </do_if>
      <!-- MK4 build-storage-only: drop non-BS buyers, out-of-coverage BS buyers, and BS supplier sell offers. -->
      <do_if value="if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false">
        <set_value name="$gtlsBsoCoverageMax" exact="if $gtlsMaxDistanceSell? and $gtlsMaxDistanceSell gt 0 then $gtlsMaxDistanceSell else $gtlsMaxDistance"/>
        <create_list name="$sellOffersBsoFiltered"/>
        <do_all exact="$sellOffers.count" counter="$gtlsBsoSi">
          <set_value name="$gtlsBsoSellOffer" exact="$sellOffers.{$gtlsBsoSi}"/>
          <set_value name="$gtlsBsoSeller" exact="if $gtlsBsoSellOffer.seller? then @$gtlsBsoSellOffer.seller else (if $gtlsBsoSellOffer.owner? then @$gtlsBsoSellOffer.owner else null)"/>
          <do_if value="not $gtlsBsoSeller? or not @$gtlsBsoSeller.isclass.buildstorage">
            <append_to_list name="$sellOffersBsoFiltered" exact="$gtlsBsoSellOffer"/>
          </do_if>
        </do_all>
        <set_value name="$sellOffers" exact="$sellOffersBsoFiltered"/>
        <create_list name="$buyOffersBsoFiltered"/>
        <do_all exact="$buyOffers.count" counter="$gtlsBsoBi">
          <set_value name="$gtlsBsoBuyOffer" exact="$buyOffers.{$gtlsBsoBi}"/>
          <set_value name="$gtlsBsoBuyer" exact="if $gtlsBsoBuyOffer.buyer? then @$gtlsBsoBuyOffer.buyer else (if $gtlsBsoBuyOffer.owner? then @$gtlsBsoBuyOffer.owner else null)"/>
          <do_if value="$gtlsBsoBuyer? and @$gtlsBsoBuyer.isclass.buildstorage">
            <set_value name="$gtlsBsoInScope" exact="false"/>
            <set_value name="$gtlsBsoBuyerDist" exact="if $gtlsHomeSector? and $gtlsBsoBuyer.sector? then $gtlsHomeSector.gatedistance.{$gtlsBsoBuyer.sector} else -1"/>
            <do_if value="$gtlsBsoBuyerDist ge 0 and ($gtlsBsoCoverageMax le 0 or $gtlsBsoBuyerDist le $gtlsBsoCoverageMax)">
              <set_value name="$gtlsBsoInScope" exact="true"/>
            </do_if>
            <do_if value="$gtlsBsoInScope">
              <append_to_list name="$buyOffersBsoFiltered" exact="$gtlsBsoBuyOffer"/>
            </do_if>
          </do_if>
        </do_all>
        <set_value name="$buyOffers" exact="$buyOffersBsoFiltered"/>
        <set_value name="$buyOffersPerWare" exact="table[]"/>
        <do_all exact="$buyOffers.count" counter="$gtlsBsoPwIdx">
          <set_value name="$gtlsBsoPwOffer" exact="$buyOffers.{$gtlsBsoPwIdx}"/>
          <set_value name="$gtlsBsoPwWare" exact="if $gtlsBsoPwOffer.ware? then @$gtlsBsoPwOffer.ware else null"/>
          <do_if value="$gtlsBsoPwWare?">
            <do_if value="not $buyOffersPerWare.{$gtlsBsoPwWare}?">
              <set_value name="$buyOffersPerWare.{$gtlsBsoPwWare}" exact="0"/>
            </do_if>
            <set_value name="$buyOffersPerWare.{$gtlsBsoPwWare}" operation="add"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buildStorageOnly offer filter sell=' + $sellOffers.count + ' buy=' + $buyOffers.count" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- Buyer cargo.free prefilter (C1-C3): drop delivery customers with no ware-type storage (all append paths). -->
      <create_list name="$buyOffersCargoFiltered"/>
      <set_value name="$buyOffersPerWareCargo" exact="table[]"/>
      <do_all exact="$buyOffers.count" counter="$gtlsBcfi">
        <set_value name="$gtlsBcfOffer" exact="$buyOffers.{$gtlsBcfi}"/>
        <set_value name="$gtlsBcfBuyer" exact="null"/>
        <do_if value="$gtlsBcfOffer.buyer? and @$gtlsBcfOffer.buyer.exists">
          <set_value name="$gtlsBcfBuyer" exact="$gtlsBcfOffer.buyer"/>
        </do_if>
        <do_elseif value="$gtlsBcfOffer.owner? and @$gtlsBcfOffer.owner.exists">
          <set_value name="$gtlsBcfBuyer" exact="$gtlsBcfOffer.owner"/>
        </do_elseif>
        <do_if value="not ($gtlsBcfBuyer? and $gtlsBcfOffer.ware? and @$gtlsBcfBuyer.cargo.{$gtlsBcfOffer.ware}.free gt 0)">
          <continue/>
        </do_if>
        <append_to_list name="$buyOffersCargoFiltered" exact="$gtlsBcfOffer"/>
        <set_value name="$gtlsBcfWare" exact="@$gtlsBcfOffer.ware"/>
        <do_if value="$gtlsBcfWare?">
          <do_if value="not $buyOffersPerWareCargo.{$gtlsBcfWare}?">
            <set_value name="$buyOffersPerWareCargo.{$gtlsBcfWare}" exact="0"/>
          </do_if>
          <set_value name="$buyOffersPerWareCargo.{$gtlsBcfWare}" operation="add"/>
        </do_if>
      </do_all>
      <set_value name="$buyOffers" exact="$buyOffersCargoFiltered"/>
      <set_value name="$buyOffersPerWare" exact="$buyOffersPerWareCargo"/>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buy-offers after cargo.free filter=' + $buyOffers.count" chance="$gtlsDebugchance"/>
      <!-- No blind total cap â€” per-ware limits above ensure manageable totals.
           With ~50 wares x 20 offers/ware = ~1000 offers max per side.
           The matching step (lib.gt.tradematch) handles O(sell*buy) by ware-skipping. -->
      <return value="table[
        $SellOffers = $sellOffers,
        $BuyOffers = $buyOffers,
        $SellOfferCount = $sellOffers.count,
        $BuyOfferCount = $buyOffers.count,
        $SellWaresFound = $sellOffersPerWare.keys.count,
        $BuyWaresFound = $buyOffersPerWare.keys.count
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.miner_find_target" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Single-pass miner resource locate: one do_for_each over gather sectors with early break,
    optional per-sector resource-probe branch, cooperative yield after each engine call.
    Replaces the vanilla routine's separate probe pre-scan + wareÃ—sector do_all loops + old-method fallback.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="ware" default="null"/>
    <param name="gatherSpaces" default="[]"/>
    <param name="minrating" default="3"/>
    <param name="deepspace" default="false"/>
    <param name="preferownspace" default="false"/>
    <param name="effectiveskill" default="100"/>
    <param name="secwares" default="[]"/>
    <param name="searchYieldMs" default="15"/>
    <param name="staggerMs" default="0"/>
    <param name="blacklistgroup" default="null"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$result" exact="table[$Found = false, $Discoverable = not $ship.isplayerowned]"/>
      <do_if value="not $ware? or $ware == null">
        <return value="$result"/>
      </do_if>
      <do_if value="not $gatherSpaces? or $gatherSpaces.count le 0">
        <return value="$result"/>
      </do_if>

      <set_value name="$yieldMs" exact="if $searchYieldMs? and $searchYieldMs gt 0 then $searchYieldMs else 15"/>
      <set_value name="$yieldMaxMs" exact="[$yieldMs * 3, $yieldMs + 1].max"/>
      <set_value name="$yieldMinTime" exact="$yieldMs * 1ms"/>
      <set_value name="$yieldMaxTime" exact="$yieldMaxMs * 1ms"/>
      <do_if value="$staggerMs? and $staggerMs gt 0">
        <set_value name="$staggerWait" exact="$staggerMs * 1ms"/>
        <wait exact="$staggerWait"/>
        <remove_value name="$staggerWait"/>
      </do_if>

      <set_value name="$trySector" exact="null"/>
      <set_value name="$tryPos" exact="null"/>
      <set_value name="$hostileSector" exact="null"/>
      <set_value name="$hostilePos" exact="null"/>
      <set_value name="$relaxedPass" exact="false"/>
      <set_value name="$passDone" exact="false"/>

      <label name="search_pass"/>
      <do_for_each name="$gatherSpace" in="$gatherSpaces">
        <do_if value="$passDone">
          <break/>
        </do_if>
        <do_if value="not $gatherSpace? or not $gatherSpace.exists">
          <continue/>
        </do_if>

        <set_value name="$baserating" exact="$minrating"/>
        <do_if value="$gatherSpace.isclass.sector">
          <set_value name="$locyieldrating" exact="@$gatherSpace.yieldrating.{$ware}"/>
          <do_if value="not $relaxedPass">
            <set_value name="$baserating" min="$baserating" max="[$baserating, (($locyieldrating)f * ($ship.combinedskill / 100.0))i].max"/>
          </do_if>
          <do_else>
            <set_value name="$baserating" exact="1"/>
          </do_else>
          <do_if value="$baserating gt 6">
            <set_value name="$baserating" exact="6"/>
          </do_if>
          <remove_value name="$locyieldrating"/>
        </do_if>
        <do_elseif value="$relaxedPass">
          <set_value name="$baserating" exact="1"/>
        </do_elseif>

        <set_value name="$sectorSafeForSearch" exact="false"/>
        <do_if value="$gatherSpace.isclass.sector">
          <set_value name="$sectorSafeForSearch" exact="true"/>
          <do_if value="$gatherSpace == $ship.sector or ($ship.commander? and $ship.commander.exists and $ship.commander.sector? and $gatherSpace == @ship.commander.sector)">
            <!-- always search current / commander sector -->
          </do_if>
          <do_else>
            <do_if value="$gatherSpace.owner and $ship.hasrelation.enemy.{$gatherSpace.owner}">
              <set_value name="$sectorSafeForSearch" exact="false"/>
            </do_if>
            <do_if value="$sectorSafeForSearch and $gatherSpace.hashazardousregion and not $gatherSpace.containsthewave and $ship.takesregiondamage">
              <set_value name="$sectorSafeForSearch" exact="false"/>
            </do_if>
            <do_if value="$sectorSafeForSearch and $gatherSpace.iscontested and not $gatherSpace.contestingfactions.indexof.{$ship.owner}">
              <do_for_each name="$contestingFaction" in="$gatherSpace.contestingfactions">
                <do_if value="$contestingFaction.mayattack.{$ship}">
                  <set_value name="$sectorSafeForSearch" exact="false"/>
                  <break/>
                </do_if>
              </do_for_each>
            </do_if>
            <do_if value="$sectorSafeForSearch and $ship.isplayerowned and $blacklistgroup? and $ship.hasblacklist.{blacklisttype.sectoractivity}.{$blacklistgroup} and $gatherSpace.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship}">
              <set_value name="$sectorSafeForSearch" exact="false"/>
            </do_if>
          </do_else>
        </do_if>

        <do_if value="$gatherSpace.isclass.sector and $sectorSafeForSearch and (not $preferownspace or $gatherSpace.owner == $ship.trueowner) and $gatherSpace.resources.{$ware}.exists">
          <set_value name="$trySector" exact="null"/>
          <set_value name="$tryPos" exact="null"/>

          <do_if value="$ship.isplayerowned">
            <find_object name="$sectorProbes" class="class.resourceprobe" space="$gatherSpace" owner="$ship.owner" multiple="true"/>
            <do_if value="$sectorProbes.count">
              <set_value name="$bestProbeYield" exact="0"/>
              <do_for_each name="$sectorProbe" in="$sectorProbes">
                <do_if value="$sectorProbe.isoperational">
                  <set_value name="$probeYield" exact="@$sectorProbe.bestyieldrating.{$ware}"/>
                  <do_if value="$probeYield and $probeYield ge $baserating and (not $bestProbeYield? or $probeYield gt $bestProbeYield)">
                    <set_value name="$bestProbeYield" exact="$probeYield"/>
                    <find_closest_resource sector="$trySector" position="$tryPos" wares="$secwares" distance="$probeDistance" ware="$ware" refobject="$gatherSpace" minrating="$probeYield">
                      <refposition value="$gatherSpace.coreposition" object="$gatherSpace" max="$gatherSpace.coresize / 4m"/>
                    </find_closest_resource>
                    <wait min="$yieldMinTime" max="$yieldMaxTime"/>
                    <remove_value name="$probeDistance"/>
                  </do_if>
                  <remove_value name="$probeYield"/>
                </do_if>
              </do_for_each>
              <remove_value name="$bestProbeYield"/>
            </do_if>
            <remove_value name="$sectorProbes"/>
          </do_if>

          <do_if value="not $trySector? or not @$trySector.exists">
            <do_if value="$ship.hascontext.{$gatherSpace}">
              <do_if value="$ship.isplayerowned and $ship.attention ge attention.visible and $ware.hastag.mineral">
                <find_asteroid_with_yield_in_sector name="$closestAsteroid" sector="$ship.sector" refobject="$ship" canpickup="false" maxdistance="120km" ware="$ware"/>
                <do_if value="@$closestAsteroid.hascontext.{$gatherSpace}">
                  <set_value name="$trySector" exact="$closestAsteroid.sector"/>
                  <create_position name="$tryPos" space="$trySector" object="$closestAsteroid"/>
                </do_if>
                <remove_value name="$closestAsteroid"/>
              </do_if>
              <do_if value="not $trySector? or not @$trySector.exists">
                <find_closest_resource sector="$trySector" position="$tryPos" wares="$secwares" ware="$ware" refobject="$ship" minrating="$baserating"/>
                <wait min="$yieldMinTime" max="$yieldMaxTime"/>
              </do_if>
            </do_if>
            <do_else>
              <find_closest_resource sector="$trySector" position="$tryPos" wares="$secwares" ware="$ware" refobject="$gatherSpace" minrating="$baserating">
                <refposition value="$gatherSpace.coreposition" object="$gatherSpace" max="$gatherSpace.coresize / 4m"/>
              </find_closest_resource>
              <wait min="$yieldMinTime" max="$yieldMaxTime"/>
            </do_else>
          </do_if>

          <do_if value="$trySector? and @$trySector.exists and $gatherSpaces.indexof.{$trySector}">
            <set_value name="$mineSafe" exact="true"/>
            <do_if value="($trySector.hashazardousregion and not $trySector.containsthewave and $ship.takesregiondamage) or ($trySector.owner and $ship.hasrelation.enemy.{$trySector.owner}) or ($trySector.policefaction and not ($ship.owner == $trySector.policefaction) and $ware.illegalto.{$trySector.policefaction}.{$ship.owner})">
              <set_value name="$mineSafe" exact="false"/>
            </do_if>
            <do_if value="$mineSafe and $trySector.iscontested and not $trySector.contestingfactions.indexof.{$ship.owner}">
              <do_for_each name="$locfaction" in="$trySector.contestingfactions">
                <do_if value="$locfaction.mayattack.{$ship}">
                  <set_value name="$mineSafe" exact="false"/>
                  <break/>
                </do_if>
              </do_for_each>
            </do_if>
            <do_if value="$mineSafe">
              <set_value name="$result" exact="table[$Found = true, $Sector = $trySector, $Pos = $tryPos, $Discoverable = true, $Ware = $ware]"/>
              <set_value name="$passDone" exact="true"/>
              <break/>
            </do_if>
            <do_if value="not $ship.isplayerowned or ($ship.hasblacklist.{blacklisttype.sectoractivity}.{$blacklistgroup} and not $trySector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship})">
              <set_value name="$hostileSector" exact="$trySector"/>
              <set_value name="$hostilePos" exact="$tryPos"/>
            </do_if>
          </do_if>
          <remove_value name="$trySector"/>
          <remove_value name="$tryPos"/>
        </do_if>
        <do_elseif value="not $gatherSpace.isclass.sector and $gatherSpace.resources.{$ware}.exists">
          <do_if value="$ship.hascontext.{$gatherSpace}">
            <find_resource sector="$trySector" position="$tryPos" wares="$secwares" ware="$ware" refobject="$ship" minrating="$baserating"/>
          </do_if>
          <do_else>
            <find_resource sector="$trySector" position="$tryPos" wares="$secwares" ware="$ware" refobject="$gatherSpace" minrating="$baserating"/>
          </do_else>
          <wait min="$yieldMinTime" max="$yieldMaxTime"/>
          <do_if value="$trySector? and @$trySector.exists">
            <set_value name="$result" exact="table[$Found = true, $Sector = $trySector, $Pos = $tryPos, $Discoverable = not $ship.isplayerowned, $Ware = $ware]"/>
            <set_value name="$passDone" exact="true"/>
            <break/>
          </do_if>
          <remove_value name="$trySector"/>
          <remove_value name="$tryPos"/>
        </do_elseif>
        <remove_value name="$sectorSafeForSearch"/>
      </do_for_each>

      <do_if value="not $passDone and not $relaxedPass">
        <set_value name="$relaxedPass" exact="true"/>
        <resume label="search_pass"/>
      </do_if>

      <do_if value="not $result.$Found and $hostileSector? and @$hostileSector.exists">
        <set_value name="$result" exact="table[$Found = true, $Sector = $hostileSector, $Pos = $hostilePos, $Discoverable = not $ship.isplayerowned, $Ware = $ware, $HostileFallback = true]"/>
      </do_if>

      <remove_value name="$trySector"/>
      <remove_value name="$tryPos"/>
      <remove_value name="$hostileSector"/>
      <remove_value name="$hostilePos"/>
      <remove_value name="$relaxedPass"/>
      <remove_value name="$passDone"/>
      <remove_value name="$yieldMinTime"/>
      <remove_value name="$yieldMaxTime"/>
      <remove_value name="$gatherSpace"/>
      <remove_value name="$baserating"/>
      <return value="$result"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.miner_physical_storage_gate" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Galaxy Miner in-routine physical storage gate (v1).
    Returns table[$Trips = bool, optional $OpenAltWare, optional debug fields when $Trips is true].
    Uses live station physical cargo + sum of relevant miners' bay cargo â€” not intent estimates.
    Pass $altWareCandidates (+ optional $altWareUrgency) to scan alternates in one invocation.
  -->
  <params>
    <param name="ship" default="this.ship"/>
    <param name="ware" default="null"/>
    <param name="primaryTargetStations" default="[]"/>
    <param name="physicalStorageAbortPercent" default="0"/>
    <param name="checkDemandFirst" default="true"/>
    <param name="resourcescout" default="false"/>
    <param name="debugchance" default="0"/>
    <param name="altWareCandidates" default="[]"/>
    <param name="altWareUrgency" default="table[]"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$result" exact="table[$Trips = false]"/>

      <do_if value="not $ware? or $ware == null">
        <return value="$result"/>
      </do_if>
      <do_if value="$physicalStorageAbortPercent le 0">
        <return value="$result"/>
      </do_if>
      <do_if value="not $checkDemandFirst">
        <return value="$result"/>
      </do_if>
      <do_if value="$resourcescout">
        <return value="$result"/>
      </do_if>
      <do_if value="not $primaryTargetStations? or $primaryTargetStations.count le 0">
        <return value="$result"/>
      </do_if>

      <set_value name="$pilotLevelOk" exact="false"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly">
        <do_if value="$ship.pilot? and $ship.pilot.skill.piloting ge 6">
          <set_value name="$pilotLevelOk" exact="true"/>
        </do_if>
      </do_if>
      <do_else>
        <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level ge 6">
          <set_value name="$pilotLevelOk" exact="true"/>
        </do_if>
      </do_else>
      <do_if value="not $pilotLevelOk">
        <return value="$result"/>
      </do_if>

      <set_value name="$headroomPct" exact="$physicalStorageAbortPercent"/>

      <!-- Check primary ware -->
      <set_value name="$gateCheckWare" exact="$ware"/>
      <set_value name="$gateCheckTrips" exact="false"/>
      <set_value name="$gateCheckReturnAlt" exact="false"/>
      <resume label="gate_check_ware"/>
      <label name="gate_check_return_primary"/>
      <set_value name="$physGateAltScanActive" exact="false"/>
      <do_if value="$gateCheckTrips and $altWareCandidates? and $altWareCandidates.count gt 0">
        <set_value name="$physGateAltScanActive" exact="true"/>
        <set_value name="$physGateBestOpenAlt" exact="null"/>
        <set_value name="$physGateBestOpenUrgency" exact="-1"/>
        <set_value name="$physGateAltIndex" exact="1"/>
        <resume label="gate_alt_loop"/>
      </do_if>

      <label name="gate_alt_done"/>
      <do_if value="$physGateAltScanActive? and $physGateAltScanActive">
        <do_if value="$physGateBestOpenAlt? and $physGateBestOpenAlt != null">
          <set_value name="$result" exact="table[$Trips = false, $OpenAltWare = $physGateBestOpenAlt]"/>
          <remove_value name="$physGateBestOpenAlt"/>
          <remove_value name="$physGateBestOpenUrgency"/>
          <remove_value name="$physGateAltIndex"/>
          <remove_value name="$physGateAltCandidate"/>
          <remove_value name="$physGateAltScanActive"/>
          <remove_value name="$gateCheckWare"/>
          <remove_value name="$gateCheckTrips"/>
          <remove_value name="$gateCheckReturnAlt"/>
          <return value="$result"/>
        </do_if>
        <remove_value name="$physGateBestOpenAlt"/>
        <remove_value name="$physGateBestOpenUrgency"/>
        <remove_value name="$physGateAltIndex"/>
        <remove_value name="$physGateAltCandidate"/>
        <remove_value name="$physGateAltScanActive"/>
      </do_if>
      <do_if value="$gateCheckTrips">
        <set_value name="$result" exact="$gateCheckTripResult"/>
        <remove_value name="$gateCheckWare"/>
        <remove_value name="$gateCheckTrips"/>
        <remove_value name="$gateCheckTripResult"/>
        <remove_value name="$gateCheckReturnAlt"/>
        <return value="$result"/>
      </do_if>

      <remove_value name="$gateCheckWare"/>
      <remove_value name="$gateCheckTrips"/>
      <remove_value name="$gateCheckReturnAlt"/>
      <return value="$result"/>

      <label name="gate_alt_loop"/>
      <do_if value="not $physGateAltIndex? or not $altWareCandidates? or $physGateAltIndex gt $altWareCandidates.count">
        <resume label="gate_alt_done"/>
      </do_if>
      <set_value name="$physGateAltCandidate" exact="$altWareCandidates.{$physGateAltIndex}"/>
      <do_if value="not $physGateAltCandidate? or $physGateAltCandidate == $ware">
        <set_value name="$physGateAltIndex" exact="$physGateAltIndex + 1"/>
        <resume label="gate_alt_loop"/>
      </do_if>
      <set_value name="$gateCheckWare" exact="$physGateAltCandidate"/>
      <set_value name="$gateCheckTrips" exact="false"/>
      <set_value name="$gateCheckReturnAlt" exact="true"/>
      <resume label="gate_check_ware"/>

      <label name="gate_check_return_alt"/>
      <do_if value="not $gateCheckTrips">
        <set_value name="$physGateAltUrgency" exact="if $altWareUrgency? and $altWareUrgency.{$physGateAltCandidate}? then $altWareUrgency.{$physGateAltCandidate} else 0"/>
        <do_if value="not $physGateBestOpenAlt? or $physGateBestOpenAlt == null or $physGateAltUrgency gt $physGateBestOpenUrgency">
          <set_value name="$physGateBestOpenAlt" exact="$physGateAltCandidate"/>
          <set_value name="$physGateBestOpenUrgency" exact="$physGateAltUrgency"/>
        </do_if>
        <remove_value name="$physGateAltUrgency"/>
      </do_if>
      <set_value name="$physGateAltIndex" exact="$physGateAltIndex + 1"/>
      <do_if value="$physGateAltIndex? and $altWareCandidates? and $physGateAltIndex le $altWareCandidates.count">
        <wait exact="1ms"/>
      </do_if>
      <resume label="gate_alt_loop"/>

      <label name="gate_check_ware"/>
      <create_list name="$relevantShips"/>
      <do_if value="$ship? and $ship.exists">
        <append_to_list name="$relevantShips" exact="$ship"/>
      </do_if>

      <set_value name="$stationIndex" exact="1"/>
      <do_while value="$stationIndex le $primaryTargetStations.count">
        <set_value name="$chunkEnd" exact="[[$stationIndex + 4, $primaryTargetStations.count].min, $primaryTargetStations.count].max"/>
        <do_all exact="$chunkEnd - $stationIndex + 1" counter="$chunkOffset">
          <set_value name="$si" exact="$stationIndex + $chunkOffset - 1"/>
          <set_value name="$gateStation" exact="$primaryTargetStations.{$si}"/>
          <do_if value="not $gateStation? or not $gateStation.exists">
            <continue/>
          </do_if>
          <do_if value="global.$GT_MinerStationAssignments? and global.$GT_MinerStationAssignments.{$gateStation}? and global.$GT_MinerStationAssignments.{$gateStation}.{$gateCheckWare}?">
            <set_value name="$assignShips" exact="global.$GT_MinerStationAssignments.{$gateStation}.{$gateCheckWare}.keys.list"/>
            <do_all exact="$assignShips.count" counter="$asi">
              <set_value name="$assignShip" exact="$assignShips.{$asi}"/>
              <set_value name="$shipA" exact="$ship"/>
              <set_value name="$shipB" exact="$assignShip"/>
              <include_interrupt_actions ref="MinerSameFleetMatch"/>
              <do_if value="$assignShip? and $assignShip.exists and $fleetMatch and not $relevantShips.indexof.{$assignShip}">
                <append_to_list name="$relevantShips" exact="$assignShip"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_MinerIntents? and global.$GT_MinerIntents.{$gateStation}? and global.$GT_MinerIntents.{$gateStation}.{$gateCheckWare}?">
            <set_value name="$intentShips" exact="global.$GT_MinerIntents.{$gateStation}.{$gateCheckWare}.keys.list"/>
            <do_all exact="$intentShips.count" counter="$isi">
              <set_value name="$intentShip" exact="$intentShips.{$isi}"/>
              <set_value name="$shipA" exact="$ship"/>
              <set_value name="$shipB" exact="$intentShip"/>
              <include_interrupt_actions ref="MinerSameFleetMatch"/>
              <do_if value="$intentShip? and $intentShip.exists and $fleetMatch and not $relevantShips.indexof.{$intentShip}">
                <append_to_list name="$relevantShips" exact="$intentShip"/>
              </do_if>
            </do_all>
          </do_if>
        </do_all>
        <set_value name="$stationIndex" exact="$chunkEnd + 1"/>
        <do_if value="$stationIndex le $primaryTargetStations.count">
          <wait exact="1ms"/>
        </do_if>
      </do_while>

      <set_value name="$stationIndex" exact="1"/>
      <do_while value="$stationIndex le $primaryTargetStations.count">
        <set_value name="$chunkEnd" exact="[[$stationIndex + 4, $primaryTargetStations.count].min, $primaryTargetStations.count].max"/>
        <do_all exact="$chunkEnd - $stationIndex + 1" counter="$chunkOffset">
          <set_value name="$si" exact="$stationIndex + $chunkOffset - 1"/>
          <set_value name="$gateStation" exact="$primaryTargetStations.{$si}"/>
          <do_if value="not $gateStation? or not $gateStation.exists">
            <continue/>
          </do_if>
          <set_value name="$targetAmount" exact="$gateStation.cargo.{$gateCheckWare}.target"/>
          <do_if value="$targetAmount le 0">
            <continue/>
          </do_if>
          <set_value name="$stationPhysical" exact="$gateStation.cargo.{$gateCheckWare}.count"/>
          <set_value name="$incomingCargo" exact="0"/>
          <set_value name="$shipIndex" exact="1"/>
          <do_while value="$shipIndex le $relevantShips.count">
            <set_value name="$shipChunkEnd" exact="[[$shipIndex + 9, $relevantShips.count].min, $relevantShips.count].max"/>
            <do_all exact="$shipChunkEnd - $shipIndex + 1" counter="$shipChunkOffset">
              <set_value name="$ri" exact="$shipIndex + $shipChunkOffset - 1"/>
              <set_value name="$minerShip" exact="$relevantShips.{$ri}"/>
              <set_value name="$minerShipIsMinerControlled" exact="false"/>
              <do_if value="$minerShip? and $minerShip.exists and $minerShip.isoperational and $minerShip.isplayerowned">
                <do_if value="$minerShip.defaultorder? and @$minerShip.defaultorder.id == 'GalaxyMiner'">
                  <set_value name="$minerShipIsMinerControlled" exact="true"/>
                </do_if>
                <do_elseif value="$minerShip.defaultorder? and @$minerShip.defaultorder.id == 'Assist' and $minerShip.defaultorder.$baseorder? and @$minerShip.defaultorder.$baseorder.id == 'GalaxyMiner'">
                  <set_value name="$minerShipIsMinerControlled" exact="true"/>
                </do_elseif>
                <do_elseif value="$minerShip.commander? and $minerShip.commander.exists and $minerShip.commander.defaultorder? and @$minerShip.commander.defaultorder.id == 'GalaxyMiner'">
                  <set_value name="$minerShipIsMinerControlled" exact="true"/>
                </do_elseif>
                <do_elseif value="$minerShip.commander? and $minerShip.commander.exists and $minerShip.commander.defaultorder? and @$minerShip.commander.defaultorder.id == 'Assist' and $minerShip.commander.defaultorder.$baseorder? and @$minerShip.commander.defaultorder.$baseorder.id == 'GalaxyMiner'">
                  <set_value name="$minerShipIsMinerControlled" exact="true"/>
                </do_elseif>
                <do_if value="$minerShipIsMinerControlled">
                  <set_value name="$shipInContext" exact="false"/>
                  <do_if value="$minerShip == $ship">
                    <set_value name="$shipInContext" exact="true"/>
                  </do_if>
                  <do_if value="not $shipInContext and global.$GT_MinerStationAssignments? and global.$GT_MinerStationAssignments.{$gateStation}? and global.$GT_MinerStationAssignments.{$gateStation}.{$gateCheckWare}? and global.$GT_MinerStationAssignments.{$gateStation}.{$gateCheckWare}.{$minerShip}?">
                    <set_value name="$shipInContext" exact="true"/>
                  </do_if>
                  <do_if value="not $shipInContext and global.$GT_MinerIntents? and global.$GT_MinerIntents.{$gateStation}? and global.$GT_MinerIntents.{$gateStation}.{$gateCheckWare}? and global.$GT_MinerIntents.{$gateStation}.{$gateCheckWare}.{$minerShip}?">
                    <set_value name="$shipInContext" exact="true"/>
                  </do_if>
                  <do_if value="$shipInContext">
                    <set_value name="$incomingCargo" exact="$incomingCargo + $minerShip.cargo.{$gateCheckWare}.count"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_all>
            <set_value name="$shipIndex" exact="$shipChunkEnd + 1"/>
            <do_if value="$shipIndex le $relevantShips.count">
              <wait exact="1ms"/>
            </do_if>
          </do_while>
          <set_value name="$projectedPhysical" exact="$stationPhysical + $incomingCargo"/>
          <!-- Integer-safe headroom: (physical * (100 + headroomPct)) / 100 â€” NOT 1 + (headroomPct/100) which truncates to 1. -->
          <set_value name="$abortThreshold" exact="($stationPhysical * (100 + $headroomPct)) / 100"/>
          <set_value name="$gateTripsForStation" exact="false"/>
          <do_if value="$stationPhysical gt 0">
            <do_if value="$projectedPhysical ge $abortThreshold">
              <set_value name="$gateTripsForStation" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$incomingCargo gt 0">
            <set_value name="$gateTripsForStation" exact="true"/>
          </do_elseif>
          <do_if value="$gateTripsForStation">
            <set_value name="$gateCheckTrips" exact="true"/>
            <set_value name="$gateCheckTripResult" exact="table[
              $Trips = true,
              $Station = $gateStation,
              $StationPhysical = $stationPhysical,
              $IncomingCargo = $incomingCargo,
              $ProjectedPhysical = $projectedPhysical,
              $AbortThreshold = $abortThreshold,
              $HeadroomPct = $headroomPct,
              $Ware = $gateCheckWare
            ]"/>
            <set_value name="$pilotLevelDbg" exact="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly and $ship.pilot? then $ship.pilot.skill.piloting else (if $ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level? then global.$GT_Pilots.{$ship.pilot}.$Level else 0)"/>
            <debug_text text="'[GT-Miner] ' + $ship.idcode + ': Physical storage gate TRIP pilotLevel=' + $pilotLevelDbg + ' ware=' + $gateCheckWare.name + ' station=' + $gateStation.idcode + ' physical=' + $stationPhysical + ' incoming=' + $incomingCargo + ' projected=' + $projectedPhysical + ' threshold=' + $abortThreshold + ' headroomPct=' + $headroomPct" chance="$debugchance"/>
            <remove_value name="$relevantShips"/>
            <do_if value="$gateCheckReturnAlt? and $gateCheckReturnAlt">
              <resume label="gate_check_return_alt"/>
            </do_if>
            <resume label="gate_check_return_primary"/>
          </do_if>
        </do_all>
        <set_value name="$stationIndex" exact="$chunkEnd + 1"/>
        <do_if value="$stationIndex le $primaryTargetStations.count">
          <wait exact="1ms"/>
        </do_if>
      </do_while>

      <remove_value name="$relevantShips"/>
      <do_if value="$gateCheckReturnAlt? and $gateCheckReturnAlt">
        <resume label="gate_check_return_alt"/>
      </do_if>
      <resume label="gate_check_return_primary"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.miner_same_fleet" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Non-blocking interrupt library: sets $fleetMatch (bool) from caller-scoped $shipA and $shipB.
    Named X4 fleet first; unfleeted Assist subordinates fall back to the same direct commander.
    Solo miners (no fleet name, no commander) only match themselves.
    Must not have blocking actions â€” use include_interrupt_actions instead of run_script in loops.
  -->
  <interrupts>
    <library>
      <actions name="MinerSameFleetMatch">
        <set_value name="$fleetMatch" exact="false"/>
        <do_if value="not $shipA? or not $shipA.exists or not $shipB? or not $shipB.exists">
          <return/>
        </do_if>
        <do_if value="$shipA == $shipB">
          <set_value name="$fleetMatch" exact="true"/>
          <return/>
        </do_if>
        <set_value name="$fleetKeyA" exact="null"/>
        <set_value name="$fleetKeyB" exact="null"/>
        <do_if value="$shipA.fleet? and $shipA.fleet.commander? and $shipA.fleet.commander.fleet? and $shipA.fleet.commander.fleet.name? and $shipA.fleet.commander.fleet.name != ''">
          <set_value name="$fleetKeyA" exact="$shipA.fleet.commander.fleet.name"/>
        </do_if>
        <do_elseif value="$shipA.fleet? and $shipA.fleet.name? and $shipA.fleet.name != ''">
          <set_value name="$fleetKeyA" exact="$shipA.fleet.name"/>
        </do_elseif>
        <do_elseif value="$shipA.commander? and $shipA.commander.exists and $shipA.commander != $shipA">
          <set_value name="$fleetKeyA" exact="$shipA.commander"/>
        </do_elseif>
        <do_if value="$shipB.fleet? and $shipB.fleet.commander? and $shipB.fleet.commander.fleet? and $shipB.fleet.commander.fleet.name? and $shipB.fleet.commander.fleet.name != ''">
          <set_value name="$fleetKeyB" exact="$shipB.fleet.commander.fleet.name"/>
        </do_if>
        <do_elseif value="$shipB.fleet? and $shipB.fleet.name? and $shipB.fleet.name != ''">
          <set_value name="$fleetKeyB" exact="$shipB.fleet.name"/>
        </do_elseif>
        <do_elseif value="$shipB.commander? and $shipB.commander.exists and $shipB.commander != $shipB">
          <set_value name="$fleetKeyB" exact="$shipB.commander"/>
        </do_elseif>
        <do_if value="$fleetKeyA? and $fleetKeyB? and $fleetKeyA == $fleetKeyB">
          <set_value name="$fleetMatch" exact="true"/>
        </do_if>
        <remove_value name="$fleetKeyA"/>
        <remove_value name="$fleetKeyB"/>
      </actions>
    </library>
  </interrupts>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.mk42.cache.search" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="4">
  <params>
    <param name="ship" default="this.ship"/>
    <param name="searchMode" default="'buy_and_sell'"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="wareBasket" default="[]"/>
    <param name="minROI" default="0"/>
    <param name="minAbsoluteProfit" default="0"/>
    <param name="ignoreBuildStorage" default="false"/>
    <param name="ignoreCarrierAux" default="false"/>
    <param name="maxEntries" default="100"/>
    <param name="cacheMaxAge" default="300s"/> <!-- Matches $Fleet.$CacheTTL default -->
    <param name="cacheDropoffTolerance" default="15"/> <!-- Max % profit drop from cached value before rejection (0 = disabled) -->
    <param name="minCargoUtilPercent" default="10"/> <!-- Hard minimum cargo utilization threshold (10-100) -->
    <param name="enableMinCargoUtil" default="true"/>
    <!-- MK4 compatibility params (accepted for call-site compatibility; current cache filter logic is generic) -->
    <param name="mk4AllowResources" default="true"/>
    <param name="mk4AllowIntermediates" default="true"/>
    <param name="mk4AllowTradewares" default="true"/>
    <param name="mk4DedicatedServe" default="false"/>
    <param name="mk4AnchorHome" default="null"/>
    <param name="mk4BuildStorageOnlyMode" default="false"/>
    <param name="maxDistanceBuy" default="0"/>
    <param name="maxDistanceSell" default="0"/>
    <param name="requirePlayerDeliveryStation" default="false"/>
    <param name="requirePlayerSupplierStation" default="false"/>
    <param name="requireNonPlayerSupplierStation" default="false"/>
    <!-- MK3 'Ignore Player Pricing' companion filter: when true, drop cache entries whose delivery (customer) station is player-owned. -->
    <param name="requireNonPlayerDeliveryStation" default="false"/>
    <!-- When false, enforce station-to-station trade rules (offer.cantradewith) at read time, mirroring
         the order's trade_found validation: a customer (e.g. player build storage restricted to own
         faction) that disallows a foreign source is rejected here instead of after the ship hauls out. -->
    <param name="ignoreTradeRules" default="false"/>
    <param name="debugchance" default="0"/>
    <param name="mk42Priorities" default="table[]" comment="Class sliders table"/>
  </params>
  <patch sinceversion="3">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
  </patch>
  <attention min="unknown">
    <actions>
      <create_list name="$tradeList"/>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <set_value name="this.$gt_mk42Only" exact="true"/>
      <!-- Per-search memo for build-storage re-discovery (find_buy_offer by sector+ware). Instance var
           so it survives the loop's cooperative waits; reset every search since live offers change. -->
      <set_value name="this.$reBuyMemo" exact="table[]"/>
      <set_value name="$cacheHomeKey" exact="$homeSector"/>
      <set_value name="$homeCache" exact="null"/>
      <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK42.{$homeSector}"/>
      <set_value name="$homeCacheCount" exact="0"/>
      <do_if value="$homeCache?">
        <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
      </do_if>
      <!-- Sector table-key reconciliation: lookup can miss when homeSector ref differs from writer key. -->
      <do_if value="$homeCacheCount == 0 and true and global.$GT_TradeCacheMK42? and $homeSector? and $homeSector.exists">
        <set_value name="$mk4CacheKeyCount" exact="0"/>
        <do_if value="global.$GT_TradeCacheMK42.keys?">
          <set_value name="$mk4CacheKeys" exact="global.$GT_TradeCacheMK42.keys.list"/>
          <set_value name="$mk4CacheKeyCount" exact="$mk4CacheKeys.count"/>
        </do_if>
        <do_if value="$mk4CacheKeyCount gt 0">
          <do_all exact="$mk4CacheKeyCount" counter="$cki">
            <set_value name="$ckiSector" exact="@$mk4CacheKeys.{$cki}"/>
            <do_if value="$ckiSector? and $ckiSector.exists and $ckiSector == $homeSector">
              <set_value name="$cacheHomeKey" exact="$ckiSector"/>
              <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK42.{$ckiSector}"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$homeCache?">
          <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
        </do_if>
      </do_if>
      <set_value name="$purgedStaleCount" exact="0"/>
      <do_if value="$homeCacheCount == 0">
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = $tradeList,
          $PurgedStale = 0,
          $PoolSizeAfter = 0
        ]"/>
      </do_if>

      <set_value name="this.$cleanupBatchSize" exact="50"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize?">
        <set_value name="this.$cleanupBatchSize" exact="[10, @global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize].max"/>
      </do_if>
      <set_value name="this.$cleanupBatchSize" exact="(this.$cleanupBatchSize)i"/>
      <set_value name="$now" exact="player.age"/>
      <!-- Read-time purge: remove universally stale rows (mirrors lib.gt.cache.write cleanup).
           Dead delivery refs inflate pool size and block mk4live from refreshing via live search. -->
      <do_all exact="$homeCacheCount" counter="$pci" reverse="true">
        <set_value name="$livePurgeCount" exact="if @global.$GT_TradeCacheMK42.{$cacheHomeKey}.count != null then @global.$GT_TradeCacheMK42.{$cacheHomeKey}.count else 0"/>
        <do_if value="$pci gt $livePurgeCount">
          <continue/>
        </do_if>
        <set_value name="$purgeEntry" exact="null"/>
        <do_if value="true">
          <set_value name="$purgeEntry" exact="@global.$GT_TradeCacheMK42.{$cacheHomeKey}.{$pci}"/>
        </do_if>
        <do_else>
          <set_value name="$purgeEntry" exact="@global.$GT_TradeCache.{$cacheHomeKey}.{$pci}"/>
        </do_else>
        <set_value name="$purgeRemove" exact="false"/>
        <do_if value="not $purgeEntry?">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <do_if value="not $purgeRemove and (not $purgeEntry.$Score? or $purgeEntry.$Score le 0)">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <set_value name="$purgeTs" exact="null"/>
        <do_if value="not $purgeRemove">
          <set_value name="$purgeTs" exact="@$purgeEntry.$CachedAt"/>
          <do_if value="$purgeTs == null">
            <set_value name="$purgeTs" exact="@$purgeEntry.$Timestamp"/>
          </do_if>
          <do_if value="$purgeTs != null and ($now - $purgeTs) gt $cacheMaxAge">
            <set_value name="$purgeRemove" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $purgeRemove and @$purgeEntry.$BuyOffer != null and not @$purgeEntry.$BuyOffer.exists">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <!-- Build-storage delivery rows have their offer/build-storage/base recreated continuously, so a
             dead $SellOffer / $SellStation is NORMAL and must NOT trigger eviction: cache.search re-discovers
             the live offer from the permanent keys (sell sector + ware + delivery idcode). Only TTL and a
             dead supplier (buy side) evict these. Rows without permanent keys keep the strict ref check. -->
        <set_value name="$purgeReResolvable" exact="(@$purgeEntry.$Ware != null or @$purgeEntry.$DeliveryStationName != null) and (@$purgeEntry.$DeliveryStationId != null or @$purgeEntry.$DeliveryStationName != null) and ((@$purgeEntry.$SellSector != null and @$purgeEntry.$SellSector.exists) or @$purgeEntry.$SellSectorId != null or @$purgeEntry.$DeliveryStationId != null)"/>
        <do_if value="not $purgeRemove and not $purgeReResolvable and @$purgeEntry.$SellOffer != null and not @$purgeEntry.$SellOffer.exists">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <do_if value="not $purgeRemove and not $purgeReResolvable and @$purgeEntry.$SellStation != null and not @$purgeEntry.$SellStation.exists">
          <set_value name="$purgeRemove" exact="true"/>
        </do_if>
        <!-- Universal station resolution: drop rows no ship can use (dead delivery/supplier refs). -->
        <do_if value="not $purgeRemove and not $purgeReResolvable">
          <set_value name="$purgeSellStation" exact="null"/>
          <do_if value="$purgeEntry.$SellOffer? and @$purgeEntry.$SellOffer.exists and $purgeEntry.$SellOffer.buyer? and @$purgeEntry.$SellOffer.buyer.exists">
            <set_value name="$purgeSellStation" exact="@$purgeEntry.$SellOffer.buyer"/>
          </do_if>
          <do_if value="not $purgeSellStation? and $purgeEntry.$SellStation? and @$purgeEntry.$SellStation.exists">
            <set_value name="$purgeSellStation" exact="$purgeEntry.$SellStation"/>
          </do_if>
          <do_if value="not $purgeSellStation? and $purgeEntry.$SellOffer? and @$purgeEntry.$SellOffer.exists and $purgeEntry.$SellOffer.owner? and @$purgeEntry.$SellOffer.owner.exists">
            <set_value name="$purgeSellStation" exact="@$purgeEntry.$SellOffer.owner"/>
          </do_if>
          <do_if value="not $purgeSellStation? or not @$purgeSellStation.exists">
            <set_value name="$purgeRemove" exact="true"/>
          </do_if>
        </do_if>
        <!-- Supplier (buy side) is a normal station whose refs persist, so a dead supplier means the row
             is genuinely gone - check this for ALL rows, including re-resolvable build-storage rows. -->
        <do_if value="not $purgeRemove and not ($purgeEntry.$IsSellOnly? and $purgeEntry.$IsSellOnly)">
          <set_value name="$purgeBuyStation" exact="null"/>
          <do_if value="$purgeEntry.$BuyStation? and @$purgeEntry.$BuyStation.exists">
            <set_value name="$purgeBuyStation" exact="$purgeEntry.$BuyStation"/>
          </do_if>
          <do_if value="not $purgeBuyStation? and $purgeEntry.$BuyOffer? and @$purgeEntry.$BuyOffer.exists">
            <do_if value="$purgeEntry.$BuyOffer.seller? and @$purgeEntry.$BuyOffer.seller.exists">
              <set_value name="$purgeBuyStation" exact="@$purgeEntry.$BuyOffer.seller"/>
            </do_if>
            <do_elseif value="$purgeEntry.$BuyOffer.owner? and @$purgeEntry.$BuyOffer.owner.exists">
              <set_value name="$purgeBuyStation" exact="@$purgeEntry.$BuyOffer.owner"/>
            </do_elseif>
          </do_if>
          <do_if value="not $purgeBuyStation? or not @$purgeBuyStation.exists">
            <set_value name="$purgeRemove" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$purgeRemove">
          <set_value name="$liveBeforeRemove" exact="if @global.$GT_TradeCacheMK42.{$cacheHomeKey}.count != null then @global.$GT_TradeCacheMK42.{$cacheHomeKey}.count else 0"/>
          <do_if value="$pci le $liveBeforeRemove">
            <remove_value name="global.$GT_TradeCacheMK42.{$cacheHomeKey}.{$pci}"/>
            <set_value name="$purgedStaleCount" operation="add"/>
          </do_if>
        </do_if>
        <set_value name="$pciInt" exact="($pci)i"/>
        <do_if value="($pciInt % this.$cleanupBatchSize) == 0">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield read-time purge loop"/>
        </do_if>
      </do_all>
      <do_if value="$purgedStaleCount gt 0">
        <set_value name="$homeCache" exact="null"/>
        <do_if value="true">
          <set_value name="$homeCache" exact="@global.$GT_TradeCacheMK42.{$cacheHomeKey}"/>
        </do_if>
        <do_else>
          <set_value name="$homeCache" exact="@global.$GT_TradeCache.{$cacheHomeKey}"/>
        </do_else>
        <set_value name="$homeCacheCount" exact="0"/>
        <do_if value="$homeCache?">
          <set_value name="$homeCacheCount" exact="@$homeCache.count"/>
        </do_if>
        <set_value name="$poolLabel" exact="if true then 'MK42' else 'MK3'"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-CacheSearch] ' + $ship.idcode + ': (' + $poolLabel + ') Read-time purge removed ' + $purgedStaleCount + ' stale entries from ' + $cacheHomeKey.knownname + ' (remaining: ' + $homeCacheCount + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_if value="$homeCacheCount == 0">
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = $tradeList,
          $PurgedStale = $purgedStaleCount,
          $PoolSizeAfter = 0
        ]"/>
      </do_if>

      <set_value name="$maxDistanceBuyLeg" exact="if $maxDistanceBuy? and $maxDistanceBuy gt 0 then $maxDistanceBuy else $maxDistance"/>
      <set_value name="$maxDistanceSellLeg" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
      <!-- If cache was populated with a smaller search radius than this ship needs, treat as miss
           so live search (with completion pass) can find trades outside the cached radius. -->
      <set_value name="$foundCount" exact="0"/>
      <!-- DIAGNOSTIC: per-reason rejection tally (cheap; emitted only when debug logging is on).
           Lets the MISS log explain WHY every cached entry was discarded for this specific ship. -->
      <set_value name="$rejReasons" exact="table[]"/>
      <set_value name="$rejTotal" exact="0"/>
      <set_value name="$isSellOnlySearch" exact="$searchMode == 'sell_only'"/>
      <set_value name="$wareBasketCount" exact="if $wareBasket? and typeof $wareBasket == datatype.list then $wareBasket.count else 0"/>
      <set_value name="$isIsolatedMode" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?"/>
      <set_value name="$cargoUtilThresholdPct" exact="[10,[$minCargoUtilPercent,100].min].max"/>
      <!-- Per-ware diversification: each ware gets a slice of the result window so low-score
           wares (e.g. small remainder deliveries) are not crowded out by a few dominant wares. -->
      <set_value name="$foundPerWare" exact="table[]"/>
      <set_value name="$maxTradesPerWareSetting" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
        <set_value name="$maxTradesPerWareSetting" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
      </do_if>
      <do_if value="$maxTradesPerWareSetting lt 1">
        <set_value name="$maxTradesPerWareSetting" exact="1"/>
      </do_if>
      <set_value name="$perWareCap" exact="$maxTradesPerWareSetting"/>
      <do_if value="$wareBasketCount gt 0">
        <set_value name="$perWareCapFromBudget" exact="[1, ($maxEntries / $wareBasketCount)i].max"/>
        <set_value name="$perWareCap" exact="[$perWareCapFromBudget, $maxTradesPerWareSetting].min"/>
      </do_if>
      <do_else>
        <set_value name="$perWareCap" exact="[2, [$maxTradesPerWareSetting, 5].min].max"/>
      </do_else>
      <!-- Iterate start-to-end; collect up to $perWareCap valid trades per (ware, delivery-class) bucket. -->
      <!-- NOTE: $homeCacheCount is a snapshot; the list can shrink mid-loop (MD purge/cleanup
           runs while this AI script yields). Guard with bounds check before access. -->
      <do_all exact="$homeCacheCount" counter="$i">
        <!-- Bounds guard: list may have shrunk since $homeCacheCount was captured -->
        <do_if value="$i gt $homeCache.count">
          <break/>
        </do_if>
        <set_value name="$entry" exact="@$homeCache.{$i}"/>
        <!-- Faction/trade-rule fast-reject (S2): the trade-rule outcome (cantradewith between the
             cached buy/sell pair) is ship-independent; only the $ignoreTradeRules gate is ship-side.
             cache.write stamps $TradeRuleBlocked once (while refs are fresh) for pairs a player
             faction-restricted build storage will refuse. Skip such rows HERE - before the costly
             build-storage re-resolve below - for ships that enforce trade rules. Rows lacking the
             flag (older/un-stamped) still fall through to the authoritative live check further down.
             Entries stay cached so ignoreTradeRules ships can still use them. -->
        <do_if value="not $ignoreTradeRules and $entry.$TradeRuleBlocked? and $entry.$TradeRuleBlocked">
          <set_value name="$rejReasons.$traderules_flagged" exact="if $rejReasons.$traderules_flagged? then $rejReasons.$traderules_flagged+1 else 1"/>
          <set_value name="$rejTotal" operation="add"/>
          <continue/>
        </do_if>
        <!-- Ship-scoped cache failure fast-reject (S1b): skip entries this ship already tried and
             failed (docking denied, path blocked, distance, trade rules, etc. flagged via
             GT_Cache_Flag_Ship). Done HERE - before the costly build-storage re-resolve below - so a
             ship does not re-resolve and re-attempt the same dead-for-it entry every search. Other
             ships are unaffected; this is per-ship state on the shared entry. -->
        <do_if value="$entry.$FailedShips? and $entry.$FailedShips.count gt 0">
          <set_value name="$shipFailedOnEntry" exact="false"/>
          <do_all exact="$entry.$FailedShips.count" counter="$fsi">
            <do_if value="$entry.$FailedShips.{$fsi} == $ship">
              <set_value name="$shipFailedOnEntry" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="$shipFailedOnEntry">
            <set_value name="$rejReasons.$ship_failed_before" exact="if $rejReasons.$ship_failed_before? then $rejReasons.$ship_failed_before+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>
        <!-- Initialize per-entry offer capacities to avoid undefined-variable lookups -->
        <set_value name="$preCheckBuyAmt" exact="0"/>
        <set_value name="$preCheckSellAmt" exact="0"/>
        <!-- Resolve supplier/delivery stations: cached component refs go stale (0x0L) when
             stations are destroyed; prefer live offer seller/buyer when the stored ref is dead. -->
        <set_value name="$entryBuyStation" exact="null"/>
        <do_if value="$entry.$BuyStation? and @$entry.$BuyStation.exists">
          <set_value name="$entryBuyStation" exact="$entry.$BuyStation"/>
        </do_if>
        <do_if value="not $entryBuyStation? and $entry.$BuyOffer? and @$entry.$BuyOffer.exists">
          <do_if value="$entry.$BuyOffer.seller? and @$entry.$BuyOffer.seller.exists">
            <set_value name="$entryBuyStation" exact="@$entry.$BuyOffer.seller"/>
          </do_if>
          <do_elseif value="$entry.$BuyOffer.owner? and @$entry.$BuyOffer.owner.exists">
            <set_value name="$entryBuyStation" exact="@$entry.$BuyOffer.owner"/>
          </do_elseif>
        </do_if>
        <set_value name="$entrySellStationFromBuyer" exact="null"/>
        <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.buyer? and @$entry.$SellOffer.buyer.exists">
          <set_value name="$entrySellStationFromBuyer" exact="@$entry.$SellOffer.buyer"/>
        </do_if>
        <set_value name="$entrySellStation" exact="null"/>
        <!-- MK4 BS-only: delivery buy-offer buyer is authoritative (stored SellStation may be parent HQ). -->
        <do_if value="$mk4BuildStorageOnlyMode and $entrySellStationFromBuyer? and @$entrySellStationFromBuyer.exists">
          <set_value name="$entrySellStation" exact="$entrySellStationFromBuyer"/>
        </do_if>
        <do_if value="not $entrySellStation? and $entry.$SellStation? and @$entry.$SellStation.exists">
          <set_value name="$entrySellStation" exact="$entry.$SellStation"/>
        </do_if>
        <!-- Prefer buildstorage buyer when stored component ref is parent station. -->
        <do_if value="$entrySellStation? and @$entrySellStation.exists and not @$entrySellStation.isclass.buildstorage and $entrySellStationFromBuyer? and @$entrySellStationFromBuyer.isclass.buildstorage">
          <set_value name="$entrySellStation" exact="$entrySellStationFromBuyer"/>
        </do_if>
        <do_if value="not $entrySellStation? and $entrySellStationFromBuyer?">
          <set_value name="$entrySellStation" exact="$entrySellStationFromBuyer"/>
        </do_if>
        <do_if value="not $entrySellStation? and $entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.owner? and @$entry.$SellOffer.owner.exists">
          <set_value name="$entrySellStation" exact="@$entry.$SellOffer.owner"/>
        </do_if>
        <!-- Build-storage / player-construction deliveries recreate their trade offer, their build
             storage AND its base station every construction tick, so EVERY captured component handle
             (SellOffer, SellStation, SellStationBase) dies within tens of seconds -> sellstation_gone.
             Caching a component reference can therefore never work for these rows. Instead we
             re-DISCOVER the current live buy offer from PERMANENT keys: the cached sell SECTOR + WARE,
             restricted to player-owned buyers, disambiguated by the delivery station's stable idcode.
             This mirrors vanilla trade.station.xml, which always re-runs find_buy_offer against
             station.buildstorage rather than caching the offer. The shared cache entry is repaired in
             place so the rest of the fleet (and the order's own execution re-resolution) reuse it. -->
        <do_if value="not $entrySellStation? or not @$entrySellStation.exists">
          <!-- Fast path: base anchor still alive -> re-derive its current build storage cheaply. -->
          <do_if value="$entry.$SellStationBase? and @$entry.$SellStationBase.exists">
            <set_value name="$entryBaseBuildStorage" exact="@$entry.$SellStationBase.buildstorage"/>
            <do_if value="$entryBaseBuildStorage? and @$entryBaseBuildStorage.exists">
              <set_value name="$entrySellStation" exact="$entryBaseBuildStorage"/>
              <set_value name="$entry.$SellStation" exact="$entryBaseBuildStorage"/>
            </do_if>
          </do_if>
          <!-- Robust path: rediscover the live buy offer with the PROVEN MK4-2 player buy-offer query
               (lib.gt.mk42.live.search.xml ~1368): scan player-owned buy offers for the ware in the sell
               sector with a BARE <offeramount min="1"/> (NO tradepartner). The bare offeramount lets the
               engine read the build storage's desiredamount (construction demand carries no funds);
               specifying tradepartner forces the money-trade path that reads the 0 funds-amount -> nothing
               found -> false sellstation_gone (XSD common.xsd offeramount: "uses the desired amount if money
               would NOT change hands"). Disambiguate by the cached stable delivery idcode; repair the entry
               in place so the rest of the fleet reuses it. -->
          <do_if value="(not $entrySellStation? or not @$entrySellStation.exists) and $entry.$DeliveryStationId? and $entry.$Ware? and $homeSector? and @$homeSector.exists">
            <set_value name="$mk42DelIdTarget" exact="null"/>
            <find_sector_in_range name="$mk42DelIdScanSectors" object="$homeSector" maxdistance="[$maxDistance, $maxDistanceBuyLeg, $maxDistanceSellLeg, 1].max + 2" multiple="true"/>
            <do_if value="$mk42DelIdScanSectors? and $mk42DelIdScanSectors.count gt 0">
              <do_for_each name="$mk42DelIdScanSec" in="$mk42DelIdScanSectors">
                <do_if value="not $mk42DelIdTarget? and $mk42DelIdScanSec? and @$mk42DelIdScanSec.exists">
                  <find_station name="$mk42DelIdScanStations" space="$mk42DelIdScanSec" multiple="true"/>
                  <do_if value="$mk42DelIdScanStations? and $mk42DelIdScanStations.count gt 0">
                    <do_for_each name="$mk42DelIdScanSt" in="$mk42DelIdScanStations">
                      <do_if value="not $mk42DelIdTarget? and $mk42DelIdScanSt? and @$mk42DelIdScanSt.exists and $mk42DelIdScanSt.idcode? and @$mk42DelIdScanSt.idcode == $entry.$DeliveryStationId">
                        <set_value name="$mk42DelIdTarget" exact="$mk42DelIdScanSt"/>
                      </do_if>
                    </do_for_each>
                  </do_if>
                  <do_if value="not $mk42DelIdTarget?">
                    <find_object name="$mk42DelIdScanBsObjs" class="class.buildstorage" space="$mk42DelIdScanSec" owner="faction.player" multiple="true"/>
                    <do_if value="$mk42DelIdScanBsObjs? and $mk42DelIdScanBsObjs.count gt 0">
                      <do_for_each name="$mk42DelIdScanBsCand" in="$mk42DelIdScanBsObjs">
                        <do_if value="not $mk42DelIdTarget? and $mk42DelIdScanBsCand? and @$mk42DelIdScanBsCand.exists and $mk42DelIdScanBsCand.base? and @$mk42DelIdScanBsCand.base.exists and @$mk42DelIdScanBsCand.base.idcode == $entry.$DeliveryStationId">
                          <set_value name="$mk42DelIdTarget" exact="$mk42DelIdScanBsCand"/>
                        </do_if>
                      </do_for_each>
                    </do_if>
                  </do_if>
                </do_if>
              </do_for_each>
            </do_if>
            <do_if value="$mk42DelIdTarget? and @$mk42DelIdTarget.exists">
              <set_value name="$entrySellStation" exact="$mk42DelIdTarget"/>
              <set_value name="$entry.$SellStation" exact="$mk42DelIdTarget"/>
              <do_if value="not $entry.$SellSectorId? and $mk42DelIdTarget.sector? and @$mk42DelIdTarget.sector.exists and $mk42DelIdTarget.sector.idcode?">
                <set_value name="$entry.$SellSectorId" exact="@$mk42DelIdTarget.sector.idcode"/>
              </do_if>
            </do_if>
          </do_if>
          <set_value name="$reSellSector" exact="null"/>
          <do_if value="$entry.$SellSector? and @$entry.$SellSector.exists">
            <set_value name="$reSellSector" exact="$entry.$SellSector"/>
          </do_if>
          <do_elseif value="$entry.$SellSectorId? and $homeSector? and @$homeSector.exists">
            <find_sector_in_range name="$mk42SecIdScanSectors" object="$homeSector" maxdistance="[$maxDistance, $maxDistanceBuyLeg, $maxDistanceSellLeg, 1].max + 2" multiple="true"/>
            <do_if value="$mk42SecIdScanSectors? and $mk42SecIdScanSectors.count gt 0">
              <do_for_each name="$mk42SecIdScanSec" in="$mk42SecIdScanSectors">
                <do_if value="not $reSellSector? and $mk42SecIdScanSec? and @$mk42SecIdScanSec.exists and $mk42SecIdScanSec.idcode? and @$mk42SecIdScanSec.idcode == $entry.$SellSectorId">
                  <set_value name="$reSellSector" exact="$mk42SecIdScanSec"/>
                </do_if>
              </do_for_each>
            </do_if>
          </do_elseif>
          <do_if value="(not $entrySellStation? or not @$entrySellStation.exists) and $reSellSector? and @$reSellSector.exists and $entry.$Ware? and $entry.$DeliveryStationId?">
            <find_buy_offer wares="$entry.$Ware" space="$reSellSector" result="$reBsOffers" multiple="true">
              <match_buyer tradesknownto="$ship.owner" owner="faction.player">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1"/>
            </find_buy_offer>
            <do_if value="$reBsOffers? and $reBsOffers.count gt 0">
              <do_for_each name="$reBsO" in="$reBsOffers">
                <do_if value="(not $entrySellStation? or not @$entrySellStation.exists) and $reBsO? and @$reBsO.exists">
                  <set_value name="$reBsCand" exact="null"/>
                  <do_if value="$reBsO.buyer? and @$reBsO.buyer.exists">
                    <set_value name="$reBsCand" exact="@$reBsO.buyer"/>
                  </do_if>
                  <do_elseif value="$reBsO.owner? and @$reBsO.owner.exists">
                    <set_value name="$reBsCand" exact="@$reBsO.owner"/>
                  </do_elseif>
                  <do_if value="$reBsCand? and @$reBsCand.exists">
                    <set_value name="$reBsCandId" exact="if @$reBsCand.isclass.buildstorage and $reBsCand.base? and @$reBsCand.base.exists then @$reBsCand.base.idcode else @$reBsCand.idcode"/>
                    <do_if value="$reBsCandId == $entry.$DeliveryStationId">
                      <set_value name="$entrySellStation" exact="$reBsCand"/>
                      <set_value name="$entry.$SellStation" exact="$reBsCand"/>
                      <set_value name="$entry.$SellOffer" exact="$reBsO"/>
                      <do_if value="@$reBsCand.isclass.buildstorage and $reBsCand.base? and @$reBsCand.base.exists">
                        <set_value name="$entry.$SellStationBase" exact="@$reBsCand.base"/>
                        <set_value name="$entry.$DeliveryStationId" exact="@$reBsCand.base.idcode"/>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_if>
              </do_for_each>
            </do_if>
          </do_if>
        </do_if>

        <!-- Basic validity -->
        <do_if value="not $entry? or not $entry.$Score? or $entry.$Score le 0">
          <set_value name="$rejReasons.$bad_score" exact="if $rejReasons.$bad_score? then $rejReasons.$bad_score+1 else 1"/>
          <set_value name="$rejTotal" operation="add"/>
          <continue/>
        </do_if>

        <!-- Search-mode guard:
             - sell_only: only sell-only entries for wares this ship is currently carrying
             - buy_and_sell: never pick sell-only disposal entries -->
        <do_if value="$isSellOnlySearch">
          <do_if value="not $entry.$IsSellOnly? or not $entry.$IsSellOnly">
            <set_value name="$rejReasons.$mode_not_sellonly" exact="if $rejReasons.$mode_not_sellonly? then $rejReasons.$mode_not_sellonly+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="not $entry.$Ware? or $ship.cargo.{$entry.$Ware}.count le 0">
            <set_value name="$rejReasons.$sellonly_no_cargo" exact="if $rejReasons.$sellonly_no_cargo? then $rejReasons.$sellonly_no_cargo+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="$entry.$IsSellOnly? and $entry.$IsSellOnly">
            <set_value name="$rejReasons.$mode_is_sellonly" exact="if $rejReasons.$mode_is_sellonly? then $rejReasons.$mode_is_sellonly+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_else>

        <!-- Cargo bay compatibility: shared MK4 pool may contain trades from solid/liquid ships;
             skip wares this ship cannot carry (mirrors trade_found + GT_FilterTrade).
             $CargoWareTransport on MK4 entries survives stale ware refs. -->
        <do_if value="not $isSellOnlySearch">
          <set_value name="$cargoCompatWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$cargoCompatWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$cargoCompatWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$cargoCompatWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$cargoCompatWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <set_value name="$entryCargoTransport" exact="null"/>
          <do_if value="$entry.$CargoWareTransport?">
            <set_value name="$entryCargoTransport" exact="@$entry.$CargoWareTransport"/>
          </do_if>
          <do_elseif value="$cargoCompatWare?">
            <set_value name="$entryCargoTransport" exact="@$cargoCompatWare.waretransport"/>
          </do_elseif>
          <set_value name="$cargoHoldOk" exact="false"/>
          <do_if value="$cargoCompatWare? and @$ship.cargo.{$cargoCompatWare}.max gt 0">
            <set_value name="$cargoHoldOk" exact="true"/>
          </do_if>
          <do_elseif value="$entryCargoTransport? and $ship.waretransport.indexof.{$entryCargoTransport}">
            <set_value name="$cargoHoldOk" exact="true"/>
          </do_elseif>
          <do_if value="not $cargoHoldOk">
            <set_value name="$rejReasons.$cargo_incompatible" exact="if $rejReasons.$cargo_incompatible? then $rejReasons.$cargo_incompatible+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- Ware basket filter (applies to all cache search modes when basket is non-empty). -->
        <do_if value="$wareBasketCount gt 0">
          <set_value name="$entryWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$entryWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$entryWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$entryWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$entryWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <set_value name="$wareAllowed" exact="false"/>
          <do_all exact="$wareBasketCount" counter="$wbIdx">
            <do_if value="$wareBasket.{$wbIdx} == $entryWare">
              <set_value name="$wareAllowed" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $wareAllowed">
            <set_value name="$rejReasons.$ware_basket" exact="if $rejReasons.$ware_basket? then $rejReasons.$ware_basket+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- TTL / age check -->
        <do_if value="$entry.$CachedAt? and ($now - $entry.$CachedAt) gt $cacheMaxAge">
          <set_value name="$rejReasons.$ttl_expired" exact="if $rejReasons.$ttl_expired? then $rejReasons.$ttl_expired+1 else 1"/>
          <set_value name="$rejTotal" operation="add"/>
          <continue/>
        </do_if>

        <!-- Station existence (before distance / MK4 ware-type property access on station). -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="not $entryBuyStation? or not @$entryBuyStation.exists">
            <set_value name="$rejReasons.$buystation_gone" exact="if $rejReasons.$buystation_gone? then $rejReasons.$buystation_gone+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>
        <do_if value="not $entrySellStation? or not @$entrySellStation.exists">
          <set_value name="$rejReasons.$sellstation_gone" exact="if $rejReasons.$sellstation_gone? then $rejReasons.$sellstation_gone+1 else 1"/>
          <!-- Sub-diagnose [ANCHORv4]: record each raw fact INDEPENDENTLY (no elseif chain) so the
               breakdown cannot hide a state we did not anticipate. -->
          <do_if value="$entrySellStation?">
            <!-- $entrySellStation was set but dead: an earlier resolution branch (281/289/292/303)
                 produced a ref that did not survive to this check. -->
            <set_value name="$rejReasons.$ssg_es_set_dead" exact="if $rejReasons.$ssg_es_set_dead? then $rejReasons.$ssg_es_set_dead+1 else 1"/>
          </do_if>
          <do_if value="not $entry.$SellStationBase?">
            <set_value name="$rejReasons.$ssg_no_base_field" exact="if $rejReasons.$ssg_no_base_field? then $rejReasons.$ssg_no_base_field+1 else 1"/>
          </do_if>
          <do_if value="$entry.$SellStationBase? and not @$entry.$SellStationBase.exists">
            <set_value name="$rejReasons.$ssg_base_dead" exact="if $rejReasons.$ssg_base_dead? then $rejReasons.$ssg_base_dead+1 else 1"/>
          </do_if>
          <do_if value="$entry.$SellStationBase? and @$entry.$SellStationBase.exists and not (@$entry.$SellStationBase.buildstorage and @$entry.$SellStationBase.buildstorage.exists)">
            <set_value name="$rejReasons.$ssg_base_bs_dead" exact="if $rejReasons.$ssg_base_bs_dead? then $rejReasons.$ssg_base_bs_dead+1 else 1"/>
          </do_if>
          <do_if value="$entry.$SellStationBase? and @$entry.$SellStationBase.exists and @$entry.$SellStationBase.buildstorage and @$entry.$SellStationBase.buildstorage.exists">
            <!-- Anchor IS resolvable here yet the row is gone: means $entrySellStation was set-dead and
                 line-300 re-resolution was skipped because it was already non-null. -->
            <set_value name="$rejReasons.$ssg_anchor_ok_but_gone" exact="if $rejReasons.$ssg_anchor_ok_but_gone? then $rejReasons.$ssg_anchor_ok_but_gone+1 else 1"/>
          </do_if>
          <set_value name="$rejTotal" operation="add"/>
          <continue/>
        </do_if>

        <!-- MK4 policy filters (no-op for callers that don't pass these flags). -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$requirePlayerDeliveryStation">
            <set_value name="$mk4DeliveryPlayerOk" exact="false"/>
            <do_if value="$entrySellStation? and @$entrySellStation.exists and @$entrySellStation.isplayerowned">
              <set_value name="$mk4DeliveryPlayerOk" exact="true"/>
            </do_if>
            <do_elseif value="$entrySellStation? and $entrySellStation.isclass.buildstorage and $entrySellStation.base? and @$entrySellStation.base.isplayerowned">
              <set_value name="$mk4DeliveryPlayerOk" exact="true"/>
            </do_elseif>
            <do_if value="not $mk4DeliveryPlayerOk">
              <set_value name="$rejReasons.$delivery_not_player" exact="if $rejReasons.$delivery_not_player? then $rejReasons.$delivery_not_player+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
          <do_if value="$requirePlayerSupplierStation and (not $entryBuyStation? or not @$entryBuyStation.isplayerowned)">
            <set_value name="$rejReasons.$supplier_not_player" exact="if $rejReasons.$supplier_not_player? then $rejReasons.$supplier_not_player+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$requireNonPlayerSupplierStation and (not $entryBuyStation? or @$entryBuyStation.isplayerowned)">
            <set_value name="$rejReasons.$supplier_is_player" exact="if $rejReasons.$supplier_is_player? then $rejReasons.$supplier_is_player+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>
        <!-- 'Ignore Player Pricing' companion filter: drop any entry (including sell-only disposal)
             whose delivery destination is a player-owned station. -->
        <do_if value="$requireNonPlayerDeliveryStation and $entrySellStation? and @$entrySellStation.isplayerowned">
          <set_value name="$rejReasons.$delivery_is_player" exact="if $rejReasons.$delivery_is_player? then $rejReasons.$delivery_is_player+1 else 1"/>
          <set_value name="$rejTotal" operation="add"/>
          <continue/>
        </do_if>
        <!-- Station-to-station trade rules: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
        <do_if value="not $ignoreTradeRules and not $entry.$IsSellOnly?">
          <set_value name="$trPlayerStationInvolved" exact="false"/>
          <do_if value="$entryBuyStation? and @$entryBuyStation.exists">
            <do_if value="@$entryBuyStation.isplayerowned">
              <set_value name="$trPlayerStationInvolved" exact="true"/>
            </do_if>
            <do_elseif value="@$entryBuyStation.isclass.buildstorage and $entryBuyStation.base? and @$entryBuyStation.base.exists and @$entryBuyStation.base.isplayerowned">
              <set_value name="$trPlayerStationInvolved" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="not $trPlayerStationInvolved and $entrySellStation? and @$entrySellStation.exists">
            <do_if value="@$entrySellStation.isplayerowned">
              <set_value name="$trPlayerStationInvolved" exact="true"/>
            </do_if>
            <do_elseif value="@$entrySellStation.isclass.buildstorage and $entrySellStation.base? and @$entrySellStation.base.exists and @$entrySellStation.base.isplayerowned">
              <set_value name="$trPlayerStationInvolved" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="$trPlayerStationInvolved">
            <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $entryBuyStation? and @$entryBuyStation.exists and not $entry.$SellOffer.cantradewith.{$entryBuyStation}">
              <set_value name="$rejReasons.$traderules" exact="if $rejReasons.$traderules? then $rejReasons.$traderules+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists and $entrySellStation? and @$entrySellStation.exists and not $entry.$BuyOffer.cantradewith.{$entrySellStation}">
              <set_value name="$rejReasons.$traderules" exact="if $rejReasons.$traderules? then $rejReasons.$traderules+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
        </do_if>
        <!-- MK4 serveHomeOnly: delivery must match home anchor (station + build storage, or sector). -->
        <do_if value="$mk4DedicatedServe and not $mk4BuildStorageOnlyMode">
          <set_value name="$serveHomeAnchor" exact="if $mk4AnchorHome? and $mk4AnchorHome.exists then $mk4AnchorHome else $homeSector"/>
          <set_value name="$serveHomeSector" exact="if $serveHomeAnchor? and $serveHomeAnchor.isclass.sector then $serveHomeAnchor else (if $serveHomeAnchor? and $serveHomeAnchor.sector? then @$serveHomeAnchor.sector else $homeSector)"/>
          <set_value name="$serveHomeMatch" exact="false"/>
          <do_if value="$serveHomeAnchor? and $serveHomeAnchor.isclass.station">
            <do_if value="$entrySellStation? and $entrySellStation.exists and $serveHomeAnchor.exists">
              <do_if value="$entrySellStation == $serveHomeAnchor">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_if>
              <do_elseif value="$serveHomeAnchor.buildstorage? and $serveHomeAnchor.buildstorage.exists and $entrySellStation == $serveHomeAnchor.buildstorage">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
              <do_elseif value="$entrySellStation.isclass.buildstorage and $entrySellStation.base? and $entrySellStation.base.exists and $entrySellStation.base == $serveHomeAnchor">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
              <do_elseif value="$entrySellStation.hascontext.{$serveHomeAnchor}">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
              <do_elseif value="$serveHomeAnchor.hascontext.{$entrySellStation}">
                <set_value name="$serveHomeMatch" exact="true"/>
              </do_elseif>
            </do_if>
            <do_if value="not $serveHomeMatch">
              <set_value name="$rejReasons.$servehome_station" exact="if $rejReasons.$servehome_station? then $rejReasons.$servehome_station+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
          <do_elseif value="$serveHomeSector? and $serveHomeSector.exists">
            <do_if value="not $entrySellStation? or not $entrySellStation.sector? or @$entrySellStation.sector != $serveHomeSector">
              <set_value name="$rejReasons.$servehome_sector" exact="if $rejReasons.$servehome_sector? then $rejReasons.$servehome_sector+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_elseif>
        </do_if>
        <!-- MK4 build-storage-only mode: BS buyers within jumpDistanceCoverage; no BS supplier legs. -->
        <do_if value="$mk4BuildStorageOnlyMode and not $entry.$IsSellOnly?">
          <do_if value="$entryBuyStation? and @$entryBuyStation.isclass.buildstorage">
            <set_value name="$rejReasons.$bso_buy_is_bs" exact="if $rejReasons.$bso_buy_is_bs? then $rejReasons.$bso_buy_is_bs+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="not $entrySellStation? or not @$entrySellStation.isclass.buildstorage">
            <set_value name="$rejReasons.$bso_sell_not_bs" exact="if $rejReasons.$bso_sell_not_bs? then $rejReasons.$bso_sell_not_bs+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
          <!-- BS-only delivery scope: player build storage within jumpDistanceCoverage from home.
               Pass the build-storage COMPONENT to gatedistance (mirror of the main distance fix);
               a build storage often has no .sector accessor, so the old '.sector?'-guarded form
               yielded dist = -1 and rejected EVERY entry in BS-only mode. -->
          <set_value name="$mk4BsoCoverageMax" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
          <set_value name="$mk4BsoInScope" exact="false"/>
          <set_value name="$mk4BsoDist" exact="if $homeSector? and $entrySellStation? then $homeSector.gatedistance.{$entrySellStation} else -1"/>
          <do_if value="$mk4BsoDist ge 0 and ($mk4BsoCoverageMax le 0 or $mk4BsoDist le $mk4BsoCoverageMax)">
            <set_value name="$mk4BsoInScope" exact="true"/>
          </do_if>
          <do_if value="not $mk4BsoInScope">
            <set_value name="$rejReasons.$bso_out_of_scope" exact="if $rejReasons.$bso_out_of_scope? then $rejReasons.$bso_out_of_scope+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>
        <!-- MK4 ware-type policy filter (cache-phase parity with match-phase). -->
        <do_if value="not $entry.$IsSellOnly? and $entrySellStation? and (not $entrySellStation.isclass.buildstorage or $ignoreBuildStorage)">
          <set_value name="$entryTypeWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
          <do_if value="$entryTypeWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
            <set_value name="$entryTypeWare" exact="@$entry.$BuyOffer.ware"/>
          </do_if>
          <do_if value="$entryTypeWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
            <set_value name="$entryTypeWare" exact="@$entry.$SellOffer.ware"/>
          </do_if>
          <do_if value="$entryTypeWare?">
            <set_value name="$mk4IsTradeWare" exact="$entrySellStation.tradewares.{$entryTypeWare}.exists"/>
            <set_value name="$mk4IsResource" exact="$entrySellStation.resources.{$entryTypeWare}.exists"/>
            <set_value name="$mk4IsProduct" exact="$entrySellStation.products.{$entryTypeWare}.exists"/>
            <set_value name="$mk4IsIntermediate" exact="false"/>
            <do_if value="$entrySellStation.resources.{$entryTypeWare}.exists and @$entrySellStation.resources.{$entryTypeWare}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <do_if value="$entrySellStation.products.{$entryTypeWare}.exists and @$entrySellStation.products.{$entryTypeWare}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <set_value name="$mk4IsPureResource" exact="$mk4IsResource and not $mk4IsIntermediate"/>
            <set_value name="$mk4IsIntermediateOrProduct" exact="$mk4IsIntermediate or $mk4IsProduct"/>
            <set_value name="$mk4HasKnownType" exact="$mk4IsTradeWare or $mk4IsResource or $mk4IsProduct"/>
            <set_value name="$mk4AllowedByType" exact="false"/>
            <do_if value="$mk4IsTradeWare and $mk4AllowTradewares">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsPureResource and $mk4AllowResources">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsIntermediateOrProduct and $mk4AllowIntermediates">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="$mk4HasKnownType and not $mk4AllowedByType">
              <set_value name="$rejReasons.$waretype" exact="if $rejReasons.$waretype? then $rejReasons.$waretype+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Distance check with per-leg limits.
             Pass the station COMPONENT directly to gatedistance (mirrors lib.gt.tradematch
             lines 1023/1029, which work). Resolving via $station.sector breaks for build-storage
             deliveries: a build storage often has no .sector accessor (see gt_context_diagnose
             "Stations carry no .sector by themselves in some hierarchies"), leaving distance = -1
             and silently rejecting EVERY cached build-storage entry. gatedistance returns -1 (not
             null) when unreachable and 0 when same-sector, so a single component call is correct. -->
        <do_if value="$maxDistanceBuyLeg gt 0 and $entryBuyStation?">
          <set_value name="$distBuy" exact="$homeSector.gatedistance.{$entryBuyStation}"/>
          <do_if value="$distBuy lt 0 or $distBuy gt $maxDistanceBuyLeg">
            <set_value name="$rejReasons.$dist_buy" exact="if $rejReasons.$dist_buy? then $rejReasons.$dist_buy+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>
        <do_if value="$maxDistanceSellLeg gt 0 and $entrySellStation?">
          <set_value name="$distSell" exact="$homeSector.gatedistance.{$entrySellStation}"/>
          <do_if value="$distSell lt 0 or $distSell gt $maxDistanceSellLeg">
            <set_value name="$rejReasons.$dist_sell" exact="if $rejReasons.$dist_sell? then $rejReasons.$dist_sell+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- ROI / absolute profit check (sell-mode trades only) -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$minAbsoluteProfit gt 0 and $entry.$Profit? and $entry.$Profit lt $minAbsoluteProfit">
            <set_value name="$rejReasons.$min_abs_profit" exact="if $rejReasons.$min_abs_profit? then $rejReasons.$min_abs_profit+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$minROI gt 0 and $entry.$BuyPrice? and $entry.$BuyPrice gt 0">
            <set_value name="$entryROI" exact="($entry.$UnitProfit * 100) / $entry.$BuyPrice"/>
            <do_if value="$entryROI lt $minROI">
              <set_value name="$rejReasons.$min_roi" exact="if $rejReasons.$min_roi? then $rejReasons.$min_roi+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Cache Dropoff Tolerance: reject if profit dropped too much since caching.
             SKIPPED for MK4-2 supply: MK4-2 is a need-driven supply order, not a profit trader.
             A supply route is valid whenever the price thresholds match (buy<=cap, sell>=floor);
             there is no margin/ROI requirement, so a profit-drop re-check here would reject
             thin/zero-margin supply rows on every re-read and make the cache permanently miss. -->
        <do_if value="not $mk42Priorities? and $cacheDropoffTolerance gt 0 and not $entry.$IsSellOnly? and $entry.$UnitProfit? and $entry.$UnitProfit gt 0 and $entry.$BuyOffer? and $entry.$SellOffer?">
          <!-- Only check if both offers still exist (otherwise station-existence check will catch it) -->
          <do_if value="@$entry.$BuyOffer.exists and @$entry.$SellOffer.exists">
            <set_value name="$currentBuyPrice" exact="@$entry.$BuyOffer.unitprice"/>
            <set_value name="$currentSellPrice" exact="@$entry.$SellOffer.unitprice"/>
            <do_if value="$currentBuyPrice? and $currentSellPrice? and $currentBuyPrice gt 0">
              <set_value name="$currentUnitProfit" exact="$currentSellPrice - $currentBuyPrice"/>
              <!-- Calculate how much profit has dropped as % of original -->
              <do_if value="$currentUnitProfit le 0">
                <!-- Profit went negative â€” always reject -->
                <set_value name="$rejReasons.$dropoff_negative" exact="if $rejReasons.$dropoff_negative? then $rejReasons.$dropoff_negative+1 else 1"/>
                <set_value name="$rejTotal" operation="add"/>
                <continue/>
              </do_if>
              <set_value name="$profitDropPct" exact="(($entry.$UnitProfit - $currentUnitProfit) * 100) / $entry.$UnitProfit"/>
              <do_if value="$profitDropPct gt $cacheDropoffTolerance">
                <set_value name="$rejReasons.$dropoff_pct" exact="if $rejReasons.$dropoff_pct? then $rejReasons.$dropoff_pct+1 else 1"/>
                <set_value name="$rejTotal" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>

        <!-- Build storage exclusion (legacy â€” skipped when MK4-2 priorities active). -->
        <do_if value="not $mk42Priorities? and $ignoreBuildStorage">
          <do_if value="($entryBuyStation? and @$entryBuyStation.isclass.buildstorage) or ($entrySellStation? and @$entrySellStation.isclass.buildstorage)">
            <set_value name="$rejReasons.$ignore_buildstorage" exact="if $rejReasons.$ignore_buildstorage? then $rejReasons.$ignore_buildstorage+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- MK4-2 class-at-0 filter on cached delivery customer (Â§4.4 O(1) prefilter).
             Use the stored $CustomerClass tag (ship-/policy-agnostic, written at tradematch);
             only classify inline when the tag is missing (legacy entries). prioSig invalidation
             clears the home cache on any slider change, so stored class + current multiplier stay consistent. -->
        <do_if value="$mk42Priorities? and $entrySellStation? and @$entrySellStation.exists">
          <set_value name="$mk42CacheClass" exact="if $entry.$CustomerClass? then @$entry.$CustomerClass else 'None'"/>
          <do_if value="$mk42CacheClass == 'None'">
            <do_if value="@$entrySellStation.isclass.buildstorage and @$entrySellStation.isplayerowned">
              <set_value name="$mk42CacheClass" exact="'Buildstorage'"/>
            </do_if>
            <do_elseif value="@$entrySellStation.isclass.station and @$entrySellStation.isplayerowned">
              <set_value name="$mk42CacheClass" exact="'Stations'"/>
            </do_elseif>
            <do_elseif value="@$entrySellStation.isclass.ship and @$entrySellStation.type == shiptype.carrier and @$entrySellStation.isplayerowned">
              <set_value name="$mk42CacheClass" exact="'Carrier'"/>
            </do_elseif>
            <do_elseif value="@$entrySellStation.isclass.ship and @$entrySellStation.primarypurpose == purpose.auxiliary and @$entrySellStation.isplayerowned">
              <set_value name="$mk42CacheClass" exact="'Aux'"/>
            </do_elseif>
            <do_elseif value="@$entrySellStation.isclass.buildstorage and $entrySellStation.base? and @$entrySellStation.base.isplayerowned">
              <set_value name="$mk42CacheClass" exact="'Buildstorage'"/>
            </do_elseif>
          </do_if>
          <set_value name="$mk42CacheMult" exact="0"/>
          <do_if value="$mk42CacheClass == 'Buildstorage'">
            <set_value name="$mk42CacheMult" exact="if $mk42Priorities.$Buildstorage? then $mk42Priorities.$Buildstorage else 0"/>
          </do_if>
          <do_elseif value="$mk42CacheClass == 'Stations'">
            <set_value name="$mk42CacheMult" exact="if $mk42Priorities.$Stations? then $mk42Priorities.$Stations else 0"/>
          </do_elseif>
          <do_elseif value="$mk42CacheClass == 'Aux'">
            <set_value name="$mk42CacheMult" exact="if $mk42Priorities.$Aux? then $mk42Priorities.$Aux else 0"/>
          </do_elseif>
          <do_elseif value="$mk42CacheClass == 'Carrier'">
            <set_value name="$mk42CacheMult" exact="if $mk42Priorities.$Carrier? then $mk42Priorities.$Carrier else 0"/>
          </do_elseif>
          <do_if value="$mk42CacheMult le 0">
            <set_value name="$rejReasons.$class_mult_zero" exact="if $rejReasons.$class_mult_zero? then $rejReasons.$class_mult_zero+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- Carrier / auxiliary exclusion (legacy â€” skipped when MK4-2 priorities active). -->
        <do_if value="not $mk42Priorities? and $ignoreCarrierAux">
          <do_if value="($entryBuyStation? and @$entryBuyStation.isclass.ship and (@$entryBuyStation.type == shiptype.carrier or @$entryBuyStation.type == shiptype.resupplier)) or ($entrySellStation? and @$entrySellStation.isclass.ship and (@$entrySellStation.type == shiptype.carrier or @$entrySellStation.type == shiptype.resupplier))">
            <set_value name="$rejReasons.$carrier_aux" exact="if $rejReasons.$carrier_aux? then $rejReasons.$carrier_aux+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- Offer amount pre-filter (CHEAP: universal amount check; do NOT gate on .available alone).
             Build-storage delivery buy-offers often keep .available=false while cargo deficit exists. -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists">
            <set_value name="$preBuyAmtQuick" exact="@$entry.$BuyOffer.amount"/>
            <do_if value="not $preBuyAmtQuick? or $preBuyAmtQuick le 0">
              <set_value name="$preBuyAmtQuick" exact="0"/>
              <do_if value="$entryBuyStation? and @$entryBuyStation.exists">
                <set_value name="$preBuyWareQuick" exact="if $entry.$Ware? then $entry.$Ware else null"/>
                <do_if value="not $preBuyWareQuick? and @$entry.$BuyOffer.ware != null">
                  <set_value name="$preBuyWareQuick" exact="@$entry.$BuyOffer.ware"/>
                </do_if>
                <do_if value="$preBuyWareQuick?">
                  <get_ware_reservation object="$entryBuyStation" ware="$preBuyWareQuick" type="buy" virtual="false" result="$preBuyResQuick"/>
                  <set_value name="$preBuyAmtQuick" exact="[$entryBuyStation.cargo.{$preBuyWareQuick}.count - $preBuyResQuick, 0].max"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="not $preBuyAmtQuick? or $preBuyAmtQuick le 0">
              <set_value name="$rejReasons.$buy_amount_zero" exact="if $rejReasons.$buy_amount_zero? then $rejReasons.$buy_amount_zero+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists">
          <do_if value="@$entry.$SellOffer.amount le 0">
            <set_value name="$sellOfferDemandFallback" exact="0"/>
            <do_if value="$entrySellStation? and @$entrySellStation.exists">
              <set_value name="$sellOfferDemandWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
              <do_if value="not $sellOfferDemandWare? and @$entry.$SellOffer.ware != null">
                <set_value name="$sellOfferDemandWare" exact="@$entry.$SellOffer.ware"/>
              </do_if>
              <do_if value="$sellOfferDemandWare?">
                <set_value name="$sellOfferDemandFallback" exact="[0, $entrySellStation.cargo.{$sellOfferDemandWare}.target - $entrySellStation.cargo.{$sellOfferDemandWare}.count].max"/>
              </do_if>
            </do_if>
            <do_if value="$sellOfferDemandFallback le 0">
              <set_value name="$rejReasons.$sell_amount_zero" exact="if $rejReasons.$sell_amount_zero? then $rejReasons.$sell_amount_zero+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Offer capacity check (EXPENSIVE: per-ship, considers pending trade reservations).
             Skip entries where offeramount.{ship} is 0 â€” station capacity is fully reserved
             by other ships' pending trades. Without this check, the scanner would return 50
             entries all pointing to saturated stations while valid entries deeper in the cache
             go unseen. Per-ware quota below restores diversification without skipping saturated entries entirely. -->
        <do_if value="not $entry.$IsSellOnly?">
          <do_if value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists">
            <set_value name="$preCheckBuyAmt" exact="@$entry.$BuyOffer.offeramount.{$ship}"/>
            <do_if value="(not $preCheckBuyAmt? or $preCheckBuyAmt le 0) and @$entry.$BuyOffer.amount gt 0">
              <set_value name="$preCheckBuyAmt" exact="@$entry.$BuyOffer.amount"/>
            </do_if>
            <!-- Target-count demand fallback (mirrors lib.gt.tradematch + gt_context_diagnose). -->
            <do_if value="(not $preCheckBuyAmt? or $preCheckBuyAmt le 0) and $entrySellStation? and $entrySellStation.exists">
              <set_value name="$preCheckBuyWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
              <do_if value="not $preCheckBuyWare? and @$entry.$BuyOffer.ware != null">
                <set_value name="$preCheckBuyWare" exact="@$entry.$BuyOffer.ware"/>
              </do_if>
              <do_if value="$preCheckBuyWare?">
                <set_value name="$preCheckBuyAmt" exact="[0, $entrySellStation.cargo.{$preCheckBuyWare}.target - $entrySellStation.cargo.{$preCheckBuyWare}.count].max"/>
              </do_if>
            </do_if>
            <do_if value="not $preCheckBuyAmt? or $preCheckBuyAmt le 0">
              <set_value name="$rejReasons.$buy_offeramount_zero" exact="if $rejReasons.$buy_offeramount_zero? then $rejReasons.$buy_offeramount_zero+1 else 1"/>
              <set_value name="$rejTotal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists">
          <set_value name="$preCheckSellAmt" exact="@$entry.$SellOffer.offeramount.{$ship}"/>
          <do_if value="(not $preCheckSellAmt? or $preCheckSellAmt le 0) and @$entry.$SellOffer.amount gt 0">
            <set_value name="$preCheckSellAmt" exact="@$entry.$SellOffer.amount"/>
          </do_if>
          <!-- Target-count demand fallback (mirrors lib.gt.tradematch + gt_context_diagnose). -->
          <do_if value="(not $preCheckSellAmt? or $preCheckSellAmt le 0) and $entrySellStation? and $entrySellStation.exists">
            <set_value name="$preCheckSellWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
            <do_if value="not $preCheckSellWare? and @$entry.$SellOffer.ware != null">
              <set_value name="$preCheckSellWare" exact="@$entry.$SellOffer.ware"/>
            </do_if>
            <do_if value="$preCheckSellWare?">
              <set_value name="$preCheckSellAmt" exact="[0, $entrySellStation.cargo.{$preCheckSellWare}.target - $entrySellStation.cargo.{$preCheckSellWare}.count].max"/>
            </do_if>
          </do_if>
          <do_if value="not $preCheckSellAmt? or $preCheckSellAmt le 0">
            <set_value name="$rejReasons.$sell_offeramount_zero" exact="if $rejReasons.$sell_offeramount_zero? then $rejReasons.$sell_offeramount_zero+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- Hard minimum cargo utilization pre-filter (cache path only, excluded in isolated mode).
             Uses available reserved-aware offer amounts to estimate max feasible load. -->
        <do_if value="$enableMinCargoUtil and not $isIsolatedMode and not $entry.$IsSellOnly?">
          <set_value name="$minUtilVolumePerUnit" exact="1"/>
          <do_if value="$entry.$VolumePerUnit? and $entry.$VolumePerUnit gt 0">
            <set_value name="$minUtilVolumePerUnit" exact="$entry.$VolumePerUnit"/>
          </do_if>
          <do_elseif value="$entry.$Ware? and $entry.$Ware.volume?">
            <set_value name="$minUtilVolumePerUnit" exact="$entry.$Ware.volume"/>
          </do_elseif>
          <set_value name="$minUtilAmountLimit" exact="$preCheckSellAmt"/>
          <do_if value="$preCheckBuyAmt? and $preCheckBuyAmt lt $minUtilAmountLimit">
            <set_value name="$minUtilAmountLimit" exact="$preCheckBuyAmt"/>
          </do_if>
          <set_value name="$minUtilTradeVolume" exact="$minUtilAmountLimit * $minUtilVolumePerUnit"/>
          <set_value name="$minUtilRequiredVolume" exact="($ship.cargo.capacity.all * $cargoUtilThresholdPct) / 100.0"/>
          <do_if value="$minUtilTradeVolume lt $minUtilRequiredVolume">
            <set_value name="$rejReasons.$min_cargo_util" exact="if $rejReasons.$min_cargo_util? then $rejReasons.$min_cargo_util+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- Reservation check: skip trades reserved by other ships (same rule as MD reservations).
             Uses SellOffer object as key (Method B from GT_GenerateTradeKey â€” most reliable, offer.id often unavailable). -->
        <do_if value="global.$GT_Reservations? and $entry.$SellOffer?">
          <set_value name="$resKey" exact="$entry.$SellOffer"/>
          <do_if value="global.$GT_Reservations.{$resKey}?">
            <set_value name="$resData" exact="global.$GT_Reservations.{$resKey}"/>
            <!-- Only skip if reservation is unexpired AND belongs to a different ship.
                 Build-storage deliveries are multi-ship by design (construction feed); do not
                 let one ship's selection lock starve fleet mates of the same BS row. -->
            <do_if value="$resData.$Until? and player.age lt @$resData.$Until and $resData.$Ship? and @$resData.$Ship != $ship">
              <set_value name="$skipForOtherReservation" exact="true"/>
              <do_if value="$entrySellStation? and @$entrySellStation.exists and @$entrySellStation.isclass.buildstorage">
                <set_value name="$skipForOtherReservation" exact="false"/>
              </do_if>
              <do_if value="$skipForOtherReservation">
                <set_value name="$rejReasons.$reserved_by_other" exact="if $rejReasons.$reserved_by_other? then $rejReasons.$reserved_by_other+1 else 1"/>
                <set_value name="$rejTotal" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>

        <!-- Per-ware + delivery-class quota: same ware to BS and to a station are separate buckets
             (otherwise two station claytronics fills block the BS claytronics row before re-score). -->
        <set_value name="$quotaWare" exact="if $entry.$Ware? then $entry.$Ware else null"/>
        <do_if value="not $quotaWare? and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
          <set_value name="$quotaWare" exact="@$entry.$BuyOffer.ware"/>
        </do_if>
        <do_if value="not $quotaWare? and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
          <set_value name="$quotaWare" exact="@$entry.$SellOffer.ware"/>
        </do_if>
        <set_value name="$quotaDeliveryClass" exact="if $entry.$CustomerClass? then @$entry.$CustomerClass else 'None'"/>
        <do_if value="$quotaDeliveryClass == 'None' and $entrySellStation? and @$entrySellStation.exists">
          <do_if value="@$entrySellStation.isclass.buildstorage and @$entrySellStation.isplayerowned">
            <set_value name="$quotaDeliveryClass" exact="'Buildstorage'"/>
          </do_if>
          <do_elseif value="@$entrySellStation.isclass.station and @$entrySellStation.isplayerowned">
            <set_value name="$quotaDeliveryClass" exact="'Stations'"/>
          </do_elseif>
          <do_elseif value="@$entrySellStation.isclass.ship and @$entrySellStation.isplayerowned and @$entrySellStation.type == shiptype.carrier">
            <set_value name="$quotaDeliveryClass" exact="'Carrier'"/>
          </do_elseif>
          <do_elseif value="@$entrySellStation.isclass.ship and @$entrySellStation.isplayerowned and @$entrySellStation.primarypurpose == purpose.auxiliary">
            <set_value name="$quotaDeliveryClass" exact="'Aux'"/>
          </do_elseif>
          <do_elseif value="@$entrySellStation.isclass.buildstorage and $entrySellStation.base? and @$entrySellStation.base.isplayerowned">
            <set_value name="$quotaDeliveryClass" exact="'Buildstorage'"/>
          </do_elseif>
        </do_if>
        <do_if value="$quotaWare? and ($quotaDeliveryClass == 'Buildstorage' or $quotaDeliveryClass == 'Stations' or $quotaDeliveryClass == 'Aux' or $quotaDeliveryClass == 'Carrier')">
          <do_if value="not $foundPerWare.{$quotaWare}?">
            <set_value name="$foundPerWare.{$quotaWare}" exact="table[$Buildstorage = 0, $Stations = 0, $Aux = 0, $Carrier = 0]"/>
          </do_if>
          <set_value name="$quotaWareFoundCount" exact="0"/>
          <do_if value="$quotaDeliveryClass == 'Buildstorage'">
            <set_value name="$quotaWareFoundCount" exact="if $foundPerWare.{$quotaWare}.$Buildstorage? then $foundPerWare.{$quotaWare}.$Buildstorage else 0"/>
          </do_if>
          <do_elseif value="$quotaDeliveryClass == 'Stations'">
            <set_value name="$quotaWareFoundCount" exact="if $foundPerWare.{$quotaWare}.$Stations? then $foundPerWare.{$quotaWare}.$Stations else 0"/>
          </do_elseif>
          <do_elseif value="$quotaDeliveryClass == 'Aux'">
            <set_value name="$quotaWareFoundCount" exact="if $foundPerWare.{$quotaWare}.$Aux? then $foundPerWare.{$quotaWare}.$Aux else 0"/>
          </do_elseif>
          <do_elseif value="$quotaDeliveryClass == 'Carrier'">
            <set_value name="$quotaWareFoundCount" exact="if $foundPerWare.{$quotaWare}.$Carrier? then $foundPerWare.{$quotaWare}.$Carrier else 0"/>
          </do_elseif>
          <do_if value="$quotaWareFoundCount ge $perWareCap">
            <set_value name="$rejReasons.$per_ware_quota" exact="if $rejReasons.$per_ware_quota? then $rejReasons.$per_ware_quota+1 else 1"/>
            <set_value name="$rejTotal" operation="add"/>
            <continue/>
          </do_if>
        </do_if>

        <!-- Entry passed all filters -->
        <append_to_list name="$tradeList" exact="$entry"/>
        <set_value name="$foundCount" operation="add"/>
        <do_if value="$quotaWare? and ($quotaDeliveryClass == 'Buildstorage' or $quotaDeliveryClass == 'Stations' or $quotaDeliveryClass == 'Aux' or $quotaDeliveryClass == 'Carrier')">
          <do_if value="not $foundPerWare.{$quotaWare}?">
            <set_value name="$foundPerWare.{$quotaWare}" exact="table[$Buildstorage = 0, $Stations = 0, $Aux = 0, $Carrier = 0]"/>
          </do_if>
          <do_if value="$quotaDeliveryClass == 'Buildstorage'">
            <set_value name="$foundPerWare.{$quotaWare}.$Buildstorage" exact="if $foundPerWare.{$quotaWare}.$Buildstorage? then ($foundPerWare.{$quotaWare}.$Buildstorage + 1) else 1"/>
          </do_if>
          <do_elseif value="$quotaDeliveryClass == 'Stations'">
            <set_value name="$foundPerWare.{$quotaWare}.$Stations" exact="if $foundPerWare.{$quotaWare}.$Stations? then ($foundPerWare.{$quotaWare}.$Stations + 1) else 1"/>
          </do_elseif>
          <do_elseif value="$quotaDeliveryClass == 'Aux'">
            <set_value name="$foundPerWare.{$quotaWare}.$Aux" exact="if $foundPerWare.{$quotaWare}.$Aux? then ($foundPerWare.{$quotaWare}.$Aux + 1) else 1"/>
          </do_elseif>
          <do_elseif value="$quotaDeliveryClass == 'Carrier'">
            <set_value name="$foundPerWare.{$quotaWare}.$Carrier" exact="if $foundPerWare.{$quotaWare}.$Carrier? then ($foundPerWare.{$quotaWare}.$Carrier + 1) else 1"/>
          </do_elseif>
        </do_if>
        <do_if value="$entry.$Score gt $bestScore">
          <set_value name="$bestScore" exact="$entry.$Score"/>
          <set_value name="$bestTrade" exact="$entry"/>
        </do_if>
        <!-- Scan the full MK4-2 pool; per-ship class re-score + searchDepth cap happen in the order script. -->
        <do_if value="($i % 10) == 0">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield cache scan loop"/>
        </do_if>
      </do_all>

      <!-- DIAGNOSTIC: when the cache search yields nothing, log a per-reason rejection breakdown so the
           cause is visible instead of an opaque "MISS". Gated on debug logging; cheap string build. -->
      <do_if value="$foundCount le 0 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$rejBreakdownStr" exact="''"/>
        <do_if value="$rejReasons.$bad_score?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' bad_score=' + $rejReasons.$bad_score"/></do_if>
        <do_if value="$rejReasons.$ship_failed_before?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' ship_failed_before=' + $rejReasons.$ship_failed_before"/></do_if>
        <do_if value="$rejReasons.$mode_not_sellonly?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' mode_not_sellonly=' + $rejReasons.$mode_not_sellonly"/></do_if>
        <do_if value="$rejReasons.$sellonly_no_cargo?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' sellonly_no_cargo=' + $rejReasons.$sellonly_no_cargo"/></do_if>
        <do_if value="$rejReasons.$mode_is_sellonly?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' mode_is_sellonly=' + $rejReasons.$mode_is_sellonly"/></do_if>
        <do_if value="$rejReasons.$cargo_incompatible?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' cargo_incompatible=' + $rejReasons.$cargo_incompatible"/></do_if>
        <do_if value="$rejReasons.$ware_basket?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' ware_basket=' + $rejReasons.$ware_basket"/></do_if>
        <do_if value="$rejReasons.$ttl_expired?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' ttl_expired=' + $rejReasons.$ttl_expired"/></do_if>
        <do_if value="$rejReasons.$buystation_gone?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' buystation_gone=' + $rejReasons.$buystation_gone"/></do_if>
        <do_if value="$rejReasons.$sellstation_gone?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' sellstation_gone=' + $rejReasons.$sellstation_gone"/></do_if>
        <do_if value="$rejReasons.$ssg_no_base_field?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' (ssg_no_base_field=' + $rejReasons.$ssg_no_base_field + ')'"/></do_if>
        <do_if value="$rejReasons.$ssg_base_dead?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' (ssg_base_dead=' + $rejReasons.$ssg_base_dead + ')'"/></do_if>
        <do_if value="$rejReasons.$ssg_base_bs_dead?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' (ssg_base_bs_dead=' + $rejReasons.$ssg_base_bs_dead + ')'"/></do_if>
        <do_if value="$rejReasons.$ssg_es_set_dead?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' (ssg_es_set_dead=' + $rejReasons.$ssg_es_set_dead + ')'"/></do_if>
        <do_if value="$rejReasons.$ssg_anchor_ok_but_gone?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' (ssg_anchor_ok_but_gone=' + $rejReasons.$ssg_anchor_ok_but_gone + ')'"/></do_if>
        <do_if value="$rejReasons.$delivery_not_player?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' delivery_not_player=' + $rejReasons.$delivery_not_player"/></do_if>
        <do_if value="$rejReasons.$supplier_not_player?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' supplier_not_player=' + $rejReasons.$supplier_not_player"/></do_if>
        <do_if value="$rejReasons.$supplier_is_player?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' supplier_is_player=' + $rejReasons.$supplier_is_player"/></do_if>
        <do_if value="$rejReasons.$delivery_is_player?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' delivery_is_player=' + $rejReasons.$delivery_is_player"/></do_if>
        <do_if value="$rejReasons.$traderules?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' traderules=' + $rejReasons.$traderules"/></do_if>
        <do_if value="$rejReasons.$traderules_flagged?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' traderules_flagged=' + $rejReasons.$traderules_flagged"/></do_if>
        <do_if value="$rejReasons.$servehome_station?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' servehome_station=' + $rejReasons.$servehome_station"/></do_if>
        <do_if value="$rejReasons.$servehome_sector?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' servehome_sector=' + $rejReasons.$servehome_sector"/></do_if>
        <do_if value="$rejReasons.$bso_buy_is_bs?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' bso_buy_is_bs=' + $rejReasons.$bso_buy_is_bs"/></do_if>
        <do_if value="$rejReasons.$bso_sell_not_bs?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' bso_sell_not_bs=' + $rejReasons.$bso_sell_not_bs"/></do_if>
        <do_if value="$rejReasons.$bso_out_of_scope?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' bso_out_of_scope=' + $rejReasons.$bso_out_of_scope"/></do_if>
        <do_if value="$rejReasons.$waretype?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' waretype=' + $rejReasons.$waretype"/></do_if>
        <do_if value="$rejReasons.$dist_buy?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' dist_buy=' + $rejReasons.$dist_buy"/></do_if>
        <do_if value="$rejReasons.$dist_sell?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' dist_sell=' + $rejReasons.$dist_sell"/></do_if>
        <do_if value="$rejReasons.$min_abs_profit?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' min_abs_profit=' + $rejReasons.$min_abs_profit"/></do_if>
        <do_if value="$rejReasons.$min_roi?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' min_roi=' + $rejReasons.$min_roi"/></do_if>
        <do_if value="$rejReasons.$dropoff_negative?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' dropoff_negative=' + $rejReasons.$dropoff_negative"/></do_if>
        <do_if value="$rejReasons.$dropoff_pct?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' dropoff_pct=' + $rejReasons.$dropoff_pct"/></do_if>
        <do_if value="$rejReasons.$ignore_buildstorage?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' ignore_buildstorage=' + $rejReasons.$ignore_buildstorage"/></do_if>
        <do_if value="$rejReasons.$class_mult_zero?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' class_mult_zero=' + $rejReasons.$class_mult_zero"/></do_if>
        <do_if value="$rejReasons.$carrier_aux?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' carrier_aux=' + $rejReasons.$carrier_aux"/></do_if>
        <do_if value="$rejReasons.$buy_amount_zero?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' buy_amount_zero=' + $rejReasons.$buy_amount_zero"/></do_if>
        <do_if value="$rejReasons.$sell_amount_zero?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' sell_amount_zero=' + $rejReasons.$sell_amount_zero"/></do_if>
        <do_if value="$rejReasons.$buy_offeramount_zero?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' buy_offeramount_zero=' + $rejReasons.$buy_offeramount_zero"/></do_if>
        <do_if value="$rejReasons.$sell_offeramount_zero?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' sell_offeramount_zero=' + $rejReasons.$sell_offeramount_zero"/></do_if>
        <do_if value="$rejReasons.$min_cargo_util?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' min_cargo_util=' + $rejReasons.$min_cargo_util"/></do_if>
        <do_if value="$rejReasons.$reserved_by_other?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' reserved_by_other=' + $rejReasons.$reserved_by_other"/></do_if>
        <do_if value="$rejReasons.$per_ware_quota?"><set_value name="$rejBreakdownStr" exact="$rejBreakdownStr + ' per_ware_quota=' + $rejReasons.$per_ware_quota"/></do_if>
        <debug_text text="'[GT-AI] ' + $ship.idcode + ': Cache search REJECT breakdown [ANCHORv4] (pool=' + $homeCacheCount + ', rejected=' + $rejTotal + ', home=' + (if $homeSector? then $homeSector.name else '?') + '):' + (if $rejBreakdownStr != '' then $rejBreakdownStr else ' (none - empty/stale pool)')" chance="100"/>
      </do_if>

      <return value="table[
        $Found = ($bestTrade != null),
        $BestTrade = $bestTrade,
        $BestScore = $bestScore,
        $TradeList = $tradeList,
        $PurgedStale = $purgedStaleCount,
        $PoolSizeAfter = $homeCacheCount,
        $RejBreakdown = $rejReasons
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.mk42.cache.write" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="tradeList" default="[]"/>
    <param name="homeSector"/>
    <param name="cacheTTL" default="300s"/>
    <param name="maxSearchDistance" default="0"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>
      <set_value name="this.$writeBatchSize" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize?">
        <set_value name="this.$writeBatchSize" exact="[1, @global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize].max"/>
      </do_if>
      <set_value name="this.$writeBatchSize" exact="(this.$writeBatchSize)i"/>
      <set_value name="this.$cleanupBatchSize" exact="50"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize?">
        <set_value name="this.$cleanupBatchSize" exact="[10, @global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize].max"/>
      </do_if>
      <set_value name="this.$cleanupBatchSize" exact="(this.$cleanupBatchSize)i"/>

      <do_if value="$tradeList.count == 0 or not $homeSector?">
        <return value="table[$Written = 0, $Cleaned = 0, $CacheSize = 0]"/>
      </do_if>

      <do_if value="not global.$GT_TradeCacheMK42?">
        <set_value name="global.$GT_TradeCacheMK42" exact="table[]"/>
      </do_if>
      <do_if value="not global.$GT_TradeCacheMK42.{$homeSector}?">
        <set_value name="global.$GT_TradeCacheMK42.{$homeSector}" exact="[]"/>
      </do_if>

      <set_value name="$cacheNow" exact="player.age"/>
      <set_value name="$expiredCount" exact="0"/>
      <set_value name="$cleanupSize" exact="if @global.$GT_TradeCacheMK42.{$homeSector}.count != null then @global.$GT_TradeCacheMK42.{$homeSector}.count else 0"/>

      <do_all exact="$cleanupSize" counter="$ci" reverse="true">
        <set_value name="$oldEntry" exact="@global.$GT_TradeCacheMK42.{$homeSector}.{$ci}"/>
        <set_value name="$isStale" exact="false"/>
        <do_if value="not $oldEntry?">
          <set_value name="$isStale" exact="true"/>
        </do_if>
        <set_value name="$oldTs" exact="null"/>
        <do_if value="not $isStale">
          <set_value name="$oldTs" exact="@$oldEntry.$CachedAt"/>
          <do_if value="$oldTs == null">
            <set_value name="$oldTs" exact="@$oldEntry.$Timestamp"/>
          </do_if>
          <do_if value="$oldTs != null and ($cacheNow - $oldTs) gt $cacheTTL">
            <set_value name="$isStale" exact="true"/>
          </do_if>
        </do_if>
        <!-- Positive resolvability (same dead-ref-returns-null reasoning as the sell side below):
             keep only if the supplier is still resolvable live. -->
        <set_value name="$buyResolvable" exact="(@$oldEntry.$BuyStation != null and @$oldEntry.$BuyStation.exists) or (@$oldEntry.$BuyOffer != null and @$oldEntry.$BuyOffer.exists)"/>
        <do_if value="not $isStale and not $buyResolvable">
          <set_value name="$isStale" exact="true"/>
        </do_if>
        <!-- Positive resolvability check: a dead component ref returns null under @, so the old
             "!= null and not .exists" guard silently MISSED dead build-storage refs and broken rows
             accumulated forever. Instead, keep a row only if its delivery is still resolvable live -
             directly (SellStation/SellOffer) or, for build storages, via the stable base anchor
             (base.buildstorage). Mirrors lib.gt.mk42.cache.search resolution; anything else is broken
             and gets evicted. -->
        <set_value name="$oldHasLiveBase" exact="@$oldEntry.$SellStationBase != null and @$oldEntry.$SellStationBase.exists and @$oldEntry.$SellStationBase.buildstorage != null and @$oldEntry.$SellStationBase.buildstorage.exists"/>
        <!-- Build-storage rows legitimately have ALL component handles dead at any instant (offer, build
             storage and base are recreated each construction tick) yet remain valid: cache.search
             re-discovers the live offer from the permanent keys (sell sector + ware + delivery idcode).
             So a row with live permanent keys is resolvable here too; TTL still evicts genuinely-gone
             stations, keeping the cache bounded without an expensive per-entry find_buy_offer in purge. -->
        <set_value name="$oldHasPermanentKeys" exact="(@$oldEntry.$Ware != null or @$oldEntry.$DeliveryStationName != null) and (@$oldEntry.$DeliveryStationId != null or @$oldEntry.$DeliveryStationName != null) and ((@$oldEntry.$SellSector != null and @$oldEntry.$SellSector.exists) or @$oldEntry.$SellSectorId != null or @$oldEntry.$DeliveryStationId != null)"/>
        <set_value name="$sellResolvable" exact="$oldHasLiveBase or $oldHasPermanentKeys or (@$oldEntry.$SellStation != null and @$oldEntry.$SellStation.exists) or (@$oldEntry.$SellOffer != null and @$oldEntry.$SellOffer.exists)"/>
        <do_if value="not $isStale and not $sellResolvable">
          <set_value name="$isStale" exact="true"/>
        </do_if>
        <do_if value="$isStale">
          <remove_value name="global.$GT_TradeCacheMK42.{$homeSector}.{$ci}"/>
          <set_value name="$expiredCount" operation="add"/>
        </do_if>
        <set_value name="$ciInt" exact="($ci)i"/>
        <do_if value="($ciInt % this.$cleanupBatchSize) == 0">
          <wait exact="this.$gt_yieldMs * 1ms"/>
        </do_if>
      </do_all>

      <do_all exact="$tradeList.count" counter="$ti">
        <set_value name="$newTrade" exact="$tradeList.{$ti}"/>
        <set_value name="$newTrade.$CachedAt" exact="$cacheNow"/>
        <set_value name="$newTrade.$Timestamp" exact="$cacheNow"/>
        <!-- Stamp the stable build-storage base anchor at write time, when the sell refs are still
             fresh. Done here (the single chokepoint every cached trade passes through) so it is
             independent of which matcher built the trade. The base station survives while the
             transient build storage component/offer die; cache.search re-resolves base.buildstorage. -->
        <do_if value="not $newTrade.$SellStationBase?">
          <set_value name="$wAnchorSell" exact="null"/>
          <do_if value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists">
            <set_value name="$wAnchorSell" exact="@$newTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $newTrade.$SellOffer.buyer? and @$newTrade.$SellOffer.buyer.exists">
            <set_value name="$wAnchorSell" exact="@$newTrade.$SellOffer.buyer"/>
          </do_elseif>
          <do_if value="$wAnchorSell? and @$wAnchorSell.isclass.buildstorage and $wAnchorSell.base? and @$wAnchorSell.base.exists">
            <set_value name="$newTrade.$SellStationBase" exact="@$wAnchorSell.base"/>
          </do_if>
        </do_if>
        <do_if value="not $newTrade.$DeliveryStationName? and $newTrade.$SellStation? and @$newTrade.$SellStation.exists and @$newTrade.$SellStation.knownname">
          <set_value name="$newTrade.$DeliveryStationName" exact="@$newTrade.$SellStation.knownname"/>
        </do_if>
        <!-- Stamp the delivery station's STABLE idcode (a string that outlives the recreated build-storage
             and base entities). cache.search uses it to disambiguate which re-discovered player buy offer
             corresponds to this cached row. For build storage we store the parent base station's idcode. -->
        <do_if value="not $newTrade.$DeliveryStationId? and $newTrade.$SellStation? and @$newTrade.$SellStation.exists">
          <do_if value="@$newTrade.$SellStation.isclass.buildstorage and $newTrade.$SellStation.base? and @$newTrade.$SellStation.base.exists">
            <set_value name="$newTrade.$DeliveryStationId" exact="@$newTrade.$SellStation.base.idcode"/>
          </do_if>
          <do_else>
            <set_value name="$newTrade.$DeliveryStationId" exact="@$newTrade.$SellStation.idcode"/>
          </do_else>
        </do_if>
        <do_if value="not $newTrade.$SellSectorId?">
          <set_value name="$wSecSell" exact="null"/>
          <do_if value="$newTrade.$SellSector? and @$newTrade.$SellSector.exists and $newTrade.$SellSector.idcode?">
            <set_value name="$wSecSell" exact="@$newTrade.$SellSector.idcode"/>
          </do_if>
          <do_elseif value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists and $newTrade.$SellStation.sector? and @$newTrade.$SellStation.sector.exists and $newTrade.$SellStation.sector.idcode?">
            <set_value name="$wSecSell" exact="@$newTrade.$SellStation.sector.idcode"/>
          </do_elseif>
          <do_if value="$wSecSell?">
            <set_value name="$newTrade.$SellSectorId" exact="$wSecSell"/>
          </do_if>
        </do_if>
        <!-- Stamp a ship-independent faction/trade-rule verdict while the offer refs are still fresh.
             A player build storage restricted to its own faction reports cantradewith=false against a
             foreign (NPC) supplier, so the trade can never execute for a ship that enforces trade rules
             - yet it keeps the 10x build-storage score and dominates the top of the score-sorted cache,
             making every enforcing ship pay the expensive build-storage re-resolve before rejecting it.
             cache.search reads this flag to fast-reject such rows up front (only when not ignoreTradeRules);
             ignoreTradeRules ships still see the entry. The verdict depends only on the cached buy/sell
             pair (not the hauling ship), so it is stable to cache; TTL + rewrite bound any policy drift. -->
        <do_if value="not $newTrade.$IsSellOnly?">
          <set_value name="$trbBuyStation" exact="null"/>
          <do_if value="$newTrade.$BuyStation? and @$newTrade.$BuyStation.exists">
            <set_value name="$trbBuyStation" exact="@$newTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $newTrade.$BuyOffer.seller? and @$newTrade.$BuyOffer.seller.exists">
            <set_value name="$trbBuyStation" exact="@$newTrade.$BuyOffer.seller"/>
          </do_elseif>
          <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $newTrade.$BuyOffer.owner? and @$newTrade.$BuyOffer.owner.exists">
            <set_value name="$trbBuyStation" exact="@$newTrade.$BuyOffer.owner"/>
          </do_elseif>
          <set_value name="$trbSellStation" exact="null"/>
          <do_if value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $newTrade.$SellOffer.buyer? and @$newTrade.$SellOffer.buyer.exists">
            <set_value name="$trbSellStation" exact="@$newTrade.$SellOffer.buyer"/>
          </do_if>
          <do_elseif value="$newTrade.$SellStation? and @$newTrade.$SellStation.exists">
            <set_value name="$trbSellStation" exact="@$newTrade.$SellStation"/>
          </do_elseif>
          <set_value name="$newTrade.$TradeRuleBlocked" exact="false"/>
          <set_value name="$trbPlayerStationInvolved" exact="false"/>
          <do_if value="$trbBuyStation? and @$trbBuyStation.exists">
            <do_if value="@$trbBuyStation.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_if>
            <do_elseif value="@$trbBuyStation.isclass.buildstorage and $trbBuyStation.base? and @$trbBuyStation.base.exists and @$trbBuyStation.base.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="not $trbPlayerStationInvolved and $trbSellStation? and @$trbSellStation.exists">
            <do_if value="@$trbSellStation.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_if>
            <do_elseif value="@$trbSellStation.isclass.buildstorage and $trbSellStation.base? and @$trbSellStation.base.exists and @$trbSellStation.base.isplayerowned">
              <set_value name="$trbPlayerStationInvolved" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="$trbPlayerStationInvolved">
            <do_if value="$newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and $trbBuyStation? and @$trbBuyStation.exists and not $newTrade.$SellOffer.cantradewith.{$trbBuyStation}">
              <set_value name="$newTrade.$TradeRuleBlocked" exact="true"/>
            </do_if>
            <do_elseif value="$newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and $trbSellStation? and @$trbSellStation.exists and not $newTrade.$BuyOffer.cantradewith.{$trbSellStation}">
              <set_value name="$newTrade.$TradeRuleBlocked" exact="true"/>
            </do_elseif>
          </do_if>
        </do_if>
        <do_if value="not $newTrade.$CargoWareTransport?">
          <set_value name="$cacheTagWare" exact="if $newTrade.$Ware? then $newTrade.$Ware else null"/>
          <do_if value="not $cacheTagWare? and $newTrade.$BuyOffer? and @$newTrade.$BuyOffer.exists and @$newTrade.$BuyOffer.ware != null">
            <set_value name="$cacheTagWare" exact="@$newTrade.$BuyOffer.ware"/>
          </do_if>
          <do_if value="not $cacheTagWare? and $newTrade.$SellOffer? and @$newTrade.$SellOffer.exists and @$newTrade.$SellOffer.ware != null">
            <set_value name="$cacheTagWare" exact="@$newTrade.$SellOffer.ware"/>
          </do_if>
          <do_if value="$cacheTagWare?">
            <set_value name="$newTrade.$CargoWareTransport" exact="@$cacheTagWare.waretransport"/>
            <do_if value="not $newTrade.$VolumePerUnit? and $cacheTagWare? and $cacheTagWare.volume?">
              <set_value name="$newTrade.$VolumePerUnit" exact="$cacheTagWare.volume"/>
            </do_if>
          </do_if>
        </do_if>
        <set_value name="$newScore" exact="if $newTrade.$Score? then @$newTrade.$Score else 0"/>

        <set_value name="$insertIdx" exact="0"/>
        <set_value name="$insertFound" exact="false"/>
        <set_value name="$cacheSize" exact="if @global.$GT_TradeCacheMK42.{$homeSector}.count != null then @global.$GT_TradeCacheMK42.{$homeSector}.count else 0"/>
        <do_if value="$cacheSize gt 0">
          <do_all exact="$cacheSize" counter="$si">
            <set_value name="$existingScore" exact="if @global.$GT_TradeCacheMK42.{$homeSector}.{$si}.$Score != null then @global.$GT_TradeCacheMK42.{$homeSector}.{$si}.$Score else 0"/>
            <do_if value="$newScore gt $existingScore">
              <set_value name="$insertIdx" exact="$si"/>
              <set_value name="$insertFound" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="$insertFound">
          <set_value name="global.$GT_TradeCacheMK42.{$homeSector}.{$insertIdx}" exact="$newTrade" operation="insert"/>
        </do_if>
        <do_else>
          <append_to_list name="global.$GT_TradeCacheMK42.{$homeSector}" exact="$newTrade"/>
        </do_else>

        <set_value name="$tiInt" exact="($ti)i"/>
        <do_if value="($tiInt % this.$writeBatchSize) == 0">
          <wait exact="this.$gt_yieldMs * 1ms"/>
        </do_if>
      </do_all>

      <set_value name="$finalCacheSize" exact="if @global.$GT_TradeCacheMK42.{$homeSector}.count != null then @global.$GT_TradeCacheMK42.{$homeSector}.count else 0"/>
      <set_value name="$metadataUpdated" exact="false"/>
      <do_if value="$maxSearchDistance gt 0">
        <do_if value="not global.$GT_TradeCacheMK42MaxDistance?">
          <set_value name="global.$GT_TradeCacheMK42MaxDistance" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_TradeCacheMK42MaxDistance.{$homeSector}? or $maxSearchDistance gt global.$GT_TradeCacheMK42MaxDistance.{$homeSector}">
          <set_value name="global.$GT_TradeCacheMK42MaxDistance.{$homeSector}" exact="$maxSearchDistance"/>
          <set_value name="$metadataUpdated" exact="true"/>
        </do_if>
      </do_if>
      <do_if value="$homeSector? and $homeSector.exists and ($tradeList.count gt 0 or $metadataUpdated)">
        <signal_objects object="player.galaxy" param="'GT_MK42_Cache_Updated'" param2="table[
          $HomeSector = $homeSector,
          $MaxDistance = $maxSearchDistance,
          $Written = $tradeList.count,
          $CacheSize = $finalCacheSize
        ]"/>
      </do_if>

      <return value="table[$Written = $tradeList.count, $Cleaned = $expiredCount, $CacheSize = $finalCacheSize]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- lib.gt.mk42.classify â€” single trade-object classification + priority helper for MK4-2 supply (OPEN_GALAXYTRADER_MK4-2_SUPPLY_ORDER.md Â§2). -->
<aiscript name="lib.gt.mk42.classify" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="customer" default="null" comment="Delivery target (buy-offer owner / need customer)"/>
    <param name="priorities" default="table[]" comment="table[$Buildstorage=N, $Stations=N, $Aux=N, $Carrier=N]"/>
    <param name="mode" default="'classify'" comment="classify | multiplier | both"/>
  </params>
  <attention min="unknown">
    <actions>
      <!-- Class enum strings: Buildstorage | Stations | Carrier | Aux | None -->
      <set_value name="$class" exact="'None'"/>
      <set_value name="$multiplier" exact="0"/>
      <set_value name="$eligible" exact="false"/>

      <do_if value="not $customer? or not @$customer.exists">
        <return value="table[$Class = 'None', $Multiplier = 0, $Eligible = false]"/>
      </do_if>

      <!-- Precedence: Buildstorage > Stations > Carrier > Aux (Â§2.1) -->
      <do_if value="@$customer.isclass.buildstorage and @$customer.isplayerowned">
        <set_value name="$class" exact="'Buildstorage'"/>
      </do_if>
      <do_elseif value="@$customer.isclass.station and @$customer.isplayerowned">
        <set_value name="$class" exact="'Stations'"/>
      </do_elseif>
      <do_elseif value="@$customer.isclass.ship and @$customer.isplayerowned and @$customer.type == shiptype.carrier">
        <set_value name="$class" exact="'Carrier'"/>
      </do_elseif>
      <do_elseif value="@$customer.isclass.ship and @$customer.isplayerowned and @$customer.primarypurpose == purpose.auxiliary">
        <set_value name="$class" exact="'Aux'"/>
      </do_elseif>
      <do_elseif value="@$customer.isclass.buildstorage and $customer.base? and @$customer.base.isplayerowned">
        <set_value name="$class" exact="'Buildstorage'"/>
      </do_elseif>

      <do_if value="$class != 'None' and $priorities?">
        <do_if value="$class == 'Buildstorage'">
          <set_value name="$multiplier" exact="if $priorities.$Buildstorage? then $priorities.$Buildstorage else 0"/>
        </do_if>
        <do_elseif value="$class == 'Stations'">
          <set_value name="$multiplier" exact="if $priorities.$Stations? then $priorities.$Stations else 0"/>
        </do_elseif>
        <do_elseif value="$class == 'Aux'">
          <set_value name="$multiplier" exact="if $priorities.$Aux? then $priorities.$Aux else 0"/>
        </do_elseif>
        <do_elseif value="$class == 'Carrier'">
          <set_value name="$multiplier" exact="if $priorities.$Carrier? then $priorities.$Carrier else 0"/>
        </do_elseif>
      </do_if>

      <set_value name="$eligible" exact="$class != 'None' and $multiplier gt 0"/>

      <return value="table[$Class = $class, $Multiplier = $multiplier, $Eligible = $eligible]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.mk42.live.search" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="6">
  <params>
    <param name="ship" default="this.ship"/>
    <param name="searchMode" default="'buy_and_sell'"/>
    <param name="buySpaces" default="[]"/>
    <param name="sellSpaces" default="[]"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="wareBasket" default="[]"/>
    <param name="allowIllegal" default="false"/>
    <param name="ownerFilter" default="'any'"/>
    <param name="ignoreMK1Supply" default="false"/>
    <param name="ignoreTradeRules" default="false"/>
    <param name="maxOffersPerWare" default="20"/>
    <param name="maxOffersPerSearch" default="200"/> <!-- Legacy / unused â€” kept for call-site compat, per-ware cap is used instead -->
    <param name="sellPriceMax" default="1.0" comment="Max relative price for sell offers (ship buys from station). Range: -1.0 to 1.0. Default 1.0 = no filter"/>
    <param name="buyPriceMin" default="-1.0" comment="Min relative price for buy offers (ship sells to station). Range: -1.0 to 1.0. Default -1.0 = no filter"/>
    <!-- MK4 compatibility params (accepted for call-site compatibility) -->
    <param name="ignoreTradeRulesPlayerBuyOffersRequireCargoNeed" default="false"/>
    <param name="includePlayerBuyOffers" default="true"/>
    <param name="includePlayerSellOffers" default="true" comment="When false, supplier scan excludes player-owned sell offers (MK4 buyFromPlayer=0 early cut)."/>
    <param name="includeNpcSellOffers" default="true" comment="When false, supplier scan excludes non-player sell offers (MK4 buyFromFaction=0 early cut)."/>
    <param name="requirePlayerBuyOfferOwner" default="false" comment="When true, collected buy offers must be player-owned buyers (MK4 customer policy). Also uses engine-level owner=faction.player on find_buy_offer to skip NPC delivery scan."/>
    <param name="priorityWares" default="[]" comment="Optional: MK3 priority wares to explicitly search for (ensures they enter the tradeable set for scoring)"/>
    <!-- MK3 'Ignore Player Pricing' option: include player sell offers unconditionally, and drop player buyers. -->
    <param name="bypassPlayerSellerPricing" default="false" comment="When true, run a supplemental player-only sell scan without relativeprice filter so player stations are purchased from regardless of price."/>
    <param name="excludePlayerBuyers" default="false" comment="When true, exclude player-owned buy offers entirely (used with bypassPlayerSellerPricing to sell only to NPC factions)."/>
    <!-- MK1 sell_only: keep top-N buyers per ware by estimated sell profit (not scan order). -->
    <param name="sourceSellOffers" default="[]" comment="Home-station sell offers keyed by ware for score-aware buyer cap (MK1 export)."/>
    <param name="scoreAwareBuyCap" default="false" comment="When true with sourceSellOffers, retain best maxOffersPerWare buyers by estimated score across full scan."/>
    <param name="distancePenalty" default="0.1" comment="Distance divisor for scoreAwareBuyCap estimate (matches lib.gt.tradematch sell scoring)."/>
    <param name="demandLedSupplierScan" default="false" comment="MK4: collect buy offers first, then limit supplier scan to demand wares only (S4)."/>
    <param name="mk4BuildStorageOnlyMode" default="false" comment="Legacy MK4 v1 â€” prefer mk42Priorities for MK4-2"/>
    <param name="mk42Priorities" default="table[]" comment="MK4-2 class sliders â€” bitmask + classify-at-ingest"/>
    <param name="mk4AnchorHome" default="null" comment="MK4 home anchor for build-storage-only scope (station or sector)."/>
    <param name="maxDistanceSell" default="0" comment="MK4 jumpDistanceCoverage â€” max gate distance from home for BS delivery buyers (0 = use maxDistance)."/>
    <param name="debugchance" default="0"/>
  </params>
  <patch sinceversion="5">
    <debug_text text="'[GT-LiveSearch] lib.gt.live.search v6: global scratch + gtls_ensure_state resume guards'" chance="100" filter="savegame"/>
  </patch>
  <attention min="unknown">
    <actions>
      <create_list name="$sellOffers"/>
      <create_list name="$buyOffers"/>
      <!-- Per-ware offer tracking: ensures EVERY tradeable ware gets representation.
           Without this, the first few busy sectors would fill a blind cap with the same
           10-15 high-volume wares, starving niche wares and distant sectors.
           Old version used MaxOffersPerWare=200 (collection) + MaxOffersPerWareForMatching=20. -->
      <set_value name="$sellOffersPerWare" exact="table[]"/>
      <set_value name="$buyOffersPerWare" exact="table[]"/>
      <set_value name="$gtlsSeenBuyOffers" exact="table[]"/>
      <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
      <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
      <!-- Read AI yield interval from global settings -->
      <set_value name="$gtYieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="$gtYieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>
      <!-- Copy params to locals; sector-loop waits restore from global.$GT_LiveSearchScratch (lib.gt.tradematch pattern). -->
      <set_value name="$gtlsShip" exact="$ship"/>
      <set_value name="$gtlsSearchMode" exact="$searchMode"/>
      <set_value name="$gtlsBuySpaces" exact="$buySpaces"/>
      <set_value name="$gtlsSellSpaces" exact="$sellSpaces"/>
      <set_value name="$gtlsHomeSector" exact="$homeSector"/>
      <set_value name="$gtlsMaxDistance" exact="$maxDistance"/>
      <set_value name="$gtlsMaxDistanceSell" exact="if $maxDistanceSell? then $maxDistanceSell else 0"/>
      <set_value name="$gtlsWareBasket" exact="$wareBasket"/>
      <set_value name="$gtlsAllowIllegal" exact="$allowIllegal"/>
      <set_value name="$gtlsOwnerFilter" exact="$ownerFilter"/>
      <set_value name="$gtlsIgnoreMK1Supply" exact="$ignoreMK1Supply"/>
      <set_value name="$gtlsIgnoreTradeRules" exact="$ignoreTradeRules"/>
      <set_value name="$gtlsMaxOffersPerWare" exact="$maxOffersPerWare"/>
      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $maxOffersPerWare].min].max"/>
      <set_value name="$gtlsMaxOffersPerSearch" exact="$maxOffersPerSearch"/>
      <set_value name="$gtlsSellPriceMax" exact="$sellPriceMax"/>
      <set_value name="$gtlsBuyPriceMin" exact="$buyPriceMin"/>
      <set_value name="$gtlsIncludePlayerBuyOffers" exact="$includePlayerBuyOffers"/>
      <set_value name="$gtlsIncludePlayerSellOffers" exact="$includePlayerSellOffers"/>
      <set_value name="$gtlsIncludeNpcSellOffers" exact="if $includeNpcSellOffers? then $includeNpcSellOffers else true"/>
      <set_value name="$gtlsPlayerSupplierReservePerWare" exact="0"/>
      <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
        <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $maxOffersPerWare].min].max"/>
      </do_if>
      <set_value name="$gtlsSkipSupplierScan" exact="not $gtlsIncludePlayerSellOffers and not $gtlsIncludeNpcSellOffers"/>
      <set_value name="$gtlsRequirePlayerBuyOfferOwner" exact="$requirePlayerBuyOfferOwner"/>
      <set_value name="$gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed" exact="$ignoreTradeRulesPlayerBuyOffersRequireCargoNeed"/>
      <set_value name="$gtlsBypassPlayerSellerPricing" exact="$bypassPlayerSellerPricing"/>
      <set_value name="$gtlsExcludePlayerBuyers" exact="$excludePlayerBuyers"/>
      <set_value name="$gtlsPriorityWares" exact="if $priorityWares? then $priorityWares else []"/>
      <set_value name="$gtlsDebugchance" exact="$debugchance"/>
      <set_value name="this.$gtlsDemandLedSupplierScan" exact="if $demandLedSupplierScan? then $demandLedSupplierScan else false"/>
      <do_if value="this.$gtlsDemandLedSupplierScan">
        <set_value name="this.$gtlsDemandLedSellDone" exact="false"/>
      </do_if>
      <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="if $mk4BuildStorageOnlyMode? then $mk4BuildStorageOnlyMode else false"/>
      <set_value name="$gtlsMk42Priorities" exact="if $mk42Priorities? then $mk42Priorities else table[]"/>
      <set_value name="$gtlsMk42BuildStorageOnlyMode" exact="false"/>
      <do_if value="$gtlsMk42Priorities? and $gtlsMk42Priorities.$Buildstorage? and $gtlsMk42Priorities.$Buildstorage gt 0 and (not $gtlsMk42Priorities.$Stations? or $gtlsMk42Priorities.$Stations == 0) and (not $gtlsMk42Priorities.$Aux? or $gtlsMk42Priorities.$Aux == 0) and (not $gtlsMk42Priorities.$Carrier? or $gtlsMk42Priorities.$Carrier == 0)">
        <set_value name="$gtlsMk42BuildStorageOnlyMode" exact="true"/>
      </do_if>
      <set_value name="$gtlsMk4AnchorHome" exact="if $mk4AnchorHome? then $mk4AnchorHome else null"/>
      <set_value name="$gtlsDistancePenalty" exact="if $distancePenalty? then $distancePenalty else 0.1"/>
      <set_value name="$gtlsSourceSellByWare" exact="table[]"/>
      <set_value name="$gtlsUseScoreAwareBuyCap" exact="false"/>
      <set_value name="$gtlsTopBuyOffersPerWare" exact="table[]"/>
      <set_value name="$gtlsTopBuyScoresPerWare" exact="table[]"/>
      <set_value name="$gtlsScoreAwareCandidatesSeen" exact="0"/>
      <do_if value="$scoreAwareBuyCap and $sourceSellOffers? and $sourceSellOffers.count gt 0">
        <do_all exact="$sourceSellOffers.count" counter="$gtlsSsi">
          <set_value name="$gtlsSourceSellOffer" exact="$sourceSellOffers.{$gtlsSsi}"/>
          <do_if value="$gtlsSourceSellOffer? and $gtlsSourceSellOffer.ware? and @$gtlsSourceSellOffer.exists and $gtlsSourceSellOffer.available and $gtlsSourceSellOffer.amount gt 0">
            <set_value name="$gtlsSourceSellByWare.{$gtlsSourceSellOffer.ware}" exact="$gtlsSourceSellOffer"/>
            <set_value name="$gtlsUseScoreAwareBuyCap" exact="true"/>
          </do_if>
        </do_all>
      </do_if>
      <set_value name="$gtlsUseAllWares" exact="(not $gtlsWareBasket? or $gtlsWareBasket.count == 0)"/>
      <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
      <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $MaxDistanceSell = $gtlsMaxDistanceSell,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $IncludeNpcSellOffers = $gtlsIncludeNpcSellOffers,
            $SkipSupplierScan = $gtlsSkipSupplierScan,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
      <!-- Rebuild locals after save/load resume or cooperative wait (lib.gt.tradematch pattern). -->
      <label name="gtls_ensure_state"/>
      <do_if value="not $gtlsMk4BuildStorageOnlyMode?">
        <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="false"/>
      </do_if>
      <set_value name="$gtlsScratchShip" exact="null"/>
      <do_if value="$ship? and $ship.exists">
        <set_value name="$gtlsScratchShip" exact="$ship"/>
      </do_if>
      <do_elseif value="global.$GT_LiveSearchActiveShip? and global.$GT_LiveSearchActiveShip.exists">
        <set_value name="$gtlsScratchShip" exact="global.$GT_LiveSearchActiveShip"/>
      </do_elseif>
      <do_if value="$gtlsScratchShip? and global.$GT_LiveSearchScratch? and global.$GT_LiveSearchScratch.{$gtlsScratchShip}?">
        <set_value name="$gtlsSnap" exact="global.$GT_LiveSearchScratch.{$gtlsScratchShip}"/>
        <set_value name="$gtlsShip" exact="$gtlsSnap.$Ship"/>
        <set_value name="$gtlsSearchMode" exact="$gtlsSnap.$SearchMode"/>
        <set_value name="$gtlsBuySpaces" exact="$gtlsSnap.$BuySpaces"/>
        <set_value name="$gtlsSellSpaces" exact="$gtlsSnap.$SellSpaces"/>
        <set_value name="$gtlsHomeSector" exact="$gtlsSnap.$HomeSector"/>
        <set_value name="$gtlsMaxDistance" exact="$gtlsSnap.$MaxDistance"/>
        <do_if value="$gtlsSnap.$MaxDistanceSell?">
          <set_value name="$gtlsMaxDistanceSell" exact="$gtlsSnap.$MaxDistanceSell"/>
        </do_if>
        <do_elseif value="not $gtlsMaxDistanceSell?">
          <set_value name="$gtlsMaxDistanceSell" exact="0"/>
        </do_elseif>
        <set_value name="$gtlsWareBasket" exact="$gtlsSnap.$WareBasket"/>
        <set_value name="$gtlsAllowIllegal" exact="$gtlsSnap.$AllowIllegal"/>
        <set_value name="$gtlsOwnerFilter" exact="$gtlsSnap.$OwnerFilter"/>
        <set_value name="$gtlsIgnoreMK1Supply" exact="$gtlsSnap.$IgnoreMK1Supply"/>
        <set_value name="$gtlsIgnoreTradeRules" exact="$gtlsSnap.$IgnoreTradeRules"/>
        <set_value name="$gtlsMaxOffersPerWare" exact="$gtlsSnap.$MaxOffersPerWare"/>
        <set_value name="$gtlsBuildStorageReservePerWare" exact="$gtlsSnap.$BuildStorageReservePerWare"/>
        <set_value name="$gtlsSellPriceMax" exact="$gtlsSnap.$SellPriceMax"/>
        <set_value name="$gtlsBuyPriceMin" exact="$gtlsSnap.$BuyPriceMin"/>
        <set_value name="$gtlsIncludePlayerBuyOffers" exact="$gtlsSnap.$IncludePlayerBuyOffers"/>
        <set_value name="$gtlsIncludePlayerSellOffers" exact="$gtlsSnap.$IncludePlayerSellOffers"/>
        <do_if value="$gtlsSnap.$IncludeNpcSellOffers?">
          <set_value name="$gtlsIncludeNpcSellOffers" exact="$gtlsSnap.$IncludeNpcSellOffers"/>
        </do_if>
        <do_else>
          <set_value name="$gtlsIncludeNpcSellOffers" exact="true"/>
        </do_else>
        <set_value name="$gtlsSkipSupplierScan" exact="if $gtlsSnap.$SkipSupplierScan? then $gtlsSnap.$SkipSupplierScan else (not $gtlsIncludePlayerSellOffers and not $gtlsIncludeNpcSellOffers)"/>
        <set_value name="$gtlsPlayerSupplierReservePerWare" exact="0"/>
        <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
          <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
        </do_if>
        <set_value name="$gtlsRequirePlayerBuyOfferOwner" exact="$gtlsSnap.$RequirePlayerBuyOfferOwner"/>
        <set_value name="$gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed" exact="$gtlsSnap.$IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed"/>
        <set_value name="$gtlsBypassPlayerSellerPricing" exact="$gtlsSnap.$BypassPlayerSellerPricing"/>
        <set_value name="$gtlsExcludePlayerBuyers" exact="$gtlsSnap.$ExcludePlayerBuyers"/>
        <set_value name="$gtlsPriorityWares" exact="$gtlsSnap.$PriorityWares"/>
        <set_value name="$gtlsDebugchance" exact="$gtlsSnap.$Debugchance"/>
        <set_value name="$gtlsUseAllWares" exact="$gtlsSnap.$UseAllWares"/>
        <do_if value="$gtlsSnap.$DemandLedSupplierScan?">
          <set_value name="this.$gtlsDemandLedSupplierScan" exact="$gtlsSnap.$DemandLedSupplierScan"/>
        </do_if>
        <do_elseif value="not this.$gtlsDemandLedSupplierScan?">
          <set_value name="this.$gtlsDemandLedSupplierScan" exact="false"/>
        </do_elseif>
        <do_if value="$gtlsSnap.$DemandLedSellDone?">
          <set_value name="this.$gtlsDemandLedSellDone" exact="$gtlsSnap.$DemandLedSellDone"/>
        </do_if>
        <do_if value="$gtlsSnap.$Mk4BuildStorageOnlyMode?">
          <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="$gtlsSnap.$Mk4BuildStorageOnlyMode"/>
        </do_if>
        <do_elseif value="not $gtlsMk4BuildStorageOnlyMode?">
          <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="false"/>
        </do_elseif>
        <do_if value="$gtlsSnap.$Mk4AnchorHome?">
          <set_value name="$gtlsMk4AnchorHome" exact="$gtlsSnap.$Mk4AnchorHome"/>
        </do_if>
        <set_value name="$gtlsDistancePenalty" exact="$gtlsSnap.$DistancePenalty"/>
        <set_value name="$gtlsSourceSellByWare" exact="$gtlsSnap.$SourceSellByWare"/>
        <set_value name="$gtlsUseScoreAwareBuyCap" exact="$gtlsSnap.$UseScoreAwareBuyCap"/>
        <set_value name="$gtlsTopBuyOffersPerWare" exact="$gtlsSnap.$TopBuyOffersPerWare"/>
        <set_value name="$gtlsTopBuyScoresPerWare" exact="$gtlsSnap.$TopBuyScoresPerWare"/>
        <set_value name="$gtlsScoreAwareCandidatesSeen" exact="$gtlsSnap.$ScoreAwareCandidatesSeen"/>
        <set_value name="$gtlsSeenBuyOffers" exact="$gtlsSnap.$SeenBuyOffers"/>
        <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="$gtlsSnap.$BuyBuildStorageOffersPerWare"/>
        <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="$gtlsSnap.$BuildStorageBuyOffersAdded"/>
        <set_value name="$gtYieldMs" exact="$gtlsSnap.$YieldMs"/>
        <set_value name="$buyOffers" exact="$gtlsSnap.$BuyOffers"/>
        <set_value name="$sellOffers" exact="$gtlsSnap.$SellOffers"/>
        <set_value name="$buyOffersPerWare" exact="$gtlsSnap.$BuyOffersPerWare"/>
        <set_value name="$sellOffersPerWare" exact="$gtlsSnap.$SellOffersPerWare"/>
        <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
      </do_if>
      <do_else>
        <do_if value="not $sellOffers?">
          <create_list name="$sellOffers"/>
        </do_if>
        <do_if value="not $buyOffers?">
          <create_list name="$buyOffers"/>
        </do_if>
        <do_if value="not $sellOffersPerWare?">
          <set_value name="$sellOffersPerWare" exact="table[]"/>
        </do_if>
        <do_if value="not $buyOffersPerWare?">
          <set_value name="$buyOffersPerWare" exact="table[]"/>
        </do_if>
        <do_if value="not $gtlsSeenBuyOffers?">
          <set_value name="$gtlsSeenBuyOffers" exact="table[]"/>
        </do_if>
        <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
          <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
        </do_if>
        <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
          <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
        </do_if>
        <do_if value="not $gtYieldMs?">
          <set_value name="$gtYieldMs" exact="1"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
            <set_value name="$gtYieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
          </do_if>
        </do_if>
        <do_if value="$ship? and $ship.exists">
          <set_value name="$gtlsShip" exact="$ship"/>
          <set_value name="$gtlsSearchMode" exact="$searchMode"/>
          <set_value name="$gtlsBuySpaces" exact="$buySpaces"/>
          <set_value name="$gtlsSellSpaces" exact="$sellSpaces"/>
          <set_value name="$gtlsHomeSector" exact="$homeSector"/>
          <set_value name="$gtlsMaxDistance" exact="$maxDistance"/>
          <set_value name="$gtlsMaxDistanceSell" exact="if $maxDistanceSell? then $maxDistanceSell else 0"/>
          <set_value name="$gtlsWareBasket" exact="$wareBasket"/>
          <set_value name="$gtlsAllowIllegal" exact="$allowIllegal"/>
          <set_value name="$gtlsOwnerFilter" exact="$ownerFilter"/>
          <set_value name="$gtlsIgnoreMK1Supply" exact="$ignoreMK1Supply"/>
          <set_value name="$gtlsIgnoreTradeRules" exact="$ignoreTradeRules"/>
          <set_value name="$gtlsMaxOffersPerWare" exact="$maxOffersPerWare"/>
          <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $maxOffersPerWare].min].max"/>
          <set_value name="$gtlsSellPriceMax" exact="$sellPriceMax"/>
          <set_value name="$gtlsBuyPriceMin" exact="$buyPriceMin"/>
          <set_value name="$gtlsIncludePlayerBuyOffers" exact="$includePlayerBuyOffers"/>
          <set_value name="$gtlsIncludePlayerSellOffers" exact="$includePlayerSellOffers"/>
          <set_value name="$gtlsIncludeNpcSellOffers" exact="if $includeNpcSellOffers? then $includeNpcSellOffers else true"/>
          <set_value name="$gtlsPlayerSupplierReservePerWare" exact="0"/>
          <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
            <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $maxOffersPerWare].min].max"/>
          </do_if>
          <set_value name="$gtlsSkipSupplierScan" exact="not $gtlsIncludePlayerSellOffers and not $gtlsIncludeNpcSellOffers"/>
          <set_value name="$gtlsRequirePlayerBuyOfferOwner" exact="$requirePlayerBuyOfferOwner"/>
          <set_value name="$gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed" exact="$ignoreTradeRulesPlayerBuyOffersRequireCargoNeed"/>
          <set_value name="$gtlsBypassPlayerSellerPricing" exact="$bypassPlayerSellerPricing"/>
          <set_value name="$gtlsExcludePlayerBuyers" exact="$excludePlayerBuyers"/>
          <set_value name="$gtlsPriorityWares" exact="if $priorityWares? then $priorityWares else []"/>
          <set_value name="$gtlsDebugchance" exact="$debugchance"/>
          <set_value name="$gtlsMk4BuildStorageOnlyMode" exact="if $mk4BuildStorageOnlyMode? then $mk4BuildStorageOnlyMode else false"/>
          <set_value name="$gtlsMk42Priorities" exact="if $mk42Priorities? then $mk42Priorities else table[]"/>
          <set_value name="$gtlsMk42BuildStorageOnlyMode" exact="false"/>
          <do_if value="$gtlsMk42Priorities? and $gtlsMk42Priorities.$Buildstorage? and $gtlsMk42Priorities.$Buildstorage gt 0 and (not $gtlsMk42Priorities.$Stations? or $gtlsMk42Priorities.$Stations == 0) and (not $gtlsMk42Priorities.$Aux? or $gtlsMk42Priorities.$Aux == 0) and (not $gtlsMk42Priorities.$Carrier? or $gtlsMk42Priorities.$Carrier == 0)">
            <set_value name="$gtlsMk42BuildStorageOnlyMode" exact="true"/>
          </do_if>
          <set_value name="$gtlsMk4AnchorHome" exact="if $mk4AnchorHome? then $mk4AnchorHome else null"/>
          <do_if value="not this.$gtlsDemandLedSupplierScan?">
            <set_value name="this.$gtlsDemandLedSupplierScan" exact="if $demandLedSupplierScan? then $demandLedSupplierScan else false"/>
          </do_if>
          <set_value name="$gtlsDistancePenalty" exact="if $distancePenalty? then $distancePenalty else 0.1"/>
          <set_value name="$gtlsSourceSellByWare" exact="table[]"/>
          <set_value name="$gtlsUseScoreAwareBuyCap" exact="false"/>
          <set_value name="$gtlsTopBuyOffersPerWare" exact="table[]"/>
          <set_value name="$gtlsTopBuyScoresPerWare" exact="table[]"/>
          <set_value name="$gtlsScoreAwareCandidatesSeen" exact="0"/>
          <do_if value="$scoreAwareBuyCap? and $scoreAwareBuyCap and $sourceSellOffers? and $sourceSellOffers.count gt 0">
            <do_all exact="$sourceSellOffers.count" counter="$gtlsSsi">
              <set_value name="$gtlsSourceSellOffer" exact="$sourceSellOffers.{$gtlsSsi}"/>
              <do_if value="$gtlsSourceSellOffer? and $gtlsSourceSellOffer.ware? and @$gtlsSourceSellOffer.exists and $gtlsSourceSellOffer.available and $gtlsSourceSellOffer.amount gt 0">
                <set_value name="$gtlsSourceSellByWare.{$gtlsSourceSellOffer.ware}" exact="$gtlsSourceSellOffer"/>
                <set_value name="$gtlsUseScoreAwareBuyCap" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$gtlsUseAllWares" exact="(not $gtlsWareBasket? or $gtlsWareBasket.count == 0)"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
        </do_if>
      </do_else>
      <do_if value="not this.$gtlsDemandLedSupplierScan?">
        <set_value name="this.$gtlsDemandLedSupplierScan" exact="false"/>
      </do_if>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': params: sellPriceMax=' + $gtlsSellPriceMax + ' buyPriceMin=' + $gtlsBuyPriceMin + ' mode=' + $gtlsSearchMode + ' buySpaces=' + $gtlsBuySpaces.count + ' sellSpaces=' + $gtlsSellSpaces.count + (if this.$gtlsDemandLedSupplierScan? and this.$gtlsDemandLedSupplierScan then ' demandLed=true' else '')" chance="$gtlsDebugchance"/>
      <!-- MK4-2: one-shot player-station discovery (gate distance from home) replaces per-sector find_station for delivery/supplier scans. -->
      <set_value name="$gtlsUsePlayerStationDiscovery" exact="false"/>
      <create_list name="$gtlsPlayerBuyersInRange"/>
      <create_list name="$gtlsPlayerSuppliersInRange"/>
      <set_value name="$gtlsDeliveryCoverageMax" exact="if $gtlsMaxDistanceSell? and $gtlsMaxDistanceSell gt 0 then $gtlsMaxDistanceSell else $gtlsMaxDistance"/>
      <set_value name="$gtlsSupplierCoverageMax" exact="$gtlsMaxDistance"/>
      <set_value name="$gtlsSectorSupplierNpcOnly" exact="false"/>
      <do_if value="$gtlsRequirePlayerBuyOfferOwner and $gtlsHomeSector? and @$gtlsHomeSector.exists">
        <set_value name="$gtlsUsePlayerStationDiscovery" exact="true"/>
        <set_value name="$gtlsSectorSupplierNpcOnly" exact="$gtlsIncludeNpcSellOffers"/>
        <do_if value="global.$GT_LiveSearchScratch? and $gtlsShip? and global.$GT_LiveSearchScratch.{$gtlsShip}.$PlayerBuyersInRange? and global.$GT_LiveSearchScratch.{$gtlsShip}.$PlayerSuppliersInRange?">
          <set_value name="$gtlsPlayerBuyersInRange" exact="global.$GT_LiveSearchScratch.{$gtlsShip}.$PlayerBuyersInRange"/>
          <set_value name="$gtlsPlayerSuppliersInRange" exact="global.$GT_LiveSearchScratch.{$gtlsShip}.$PlayerSuppliersInRange"/>
          <do_if value="global.$GT_LiveSearchScratch.{$gtlsShip}.$DeliveryCoverageMax?">
            <set_value name="$gtlsDeliveryCoverageMax" exact="global.$GT_LiveSearchScratch.{$gtlsShip}.$DeliveryCoverageMax"/>
          </do_if>
          <do_if value="global.$GT_LiveSearchScratch.{$gtlsShip}.$SupplierCoverageMax?">
            <set_value name="$gtlsSupplierCoverageMax" exact="global.$GT_LiveSearchScratch.{$gtlsShip}.$SupplierCoverageMax"/>
          </do_if>
        </do_if>
        <do_else>
          <run_script name="'lib.gt.mk42.player.stations'" result="$gtlsPsd">
            <param name="homeSector" value="$gtlsHomeSector"/>
            <param name="maxDistance" value="$gtlsMaxDistance"/>
            <param name="maxDistanceSell" value="$gtlsMaxDistanceSell"/>
            <param name="includePlayerSuppliers" value="$gtlsIncludePlayerSellOffers"/>
            <param name="debugchance" value="$gtlsDebugchance"/>
            <param name="ship" value="$gtlsShip"/>
          </run_script>
          <set_value name="$gtlsPlayerBuyersInRange" exact="$gtlsPsd.$BuyersInRange"/>
          <set_value name="$gtlsPlayerSuppliersInRange" exact="$gtlsPsd.$SuppliersInRange"/>
          <set_value name="$gtlsDeliveryCoverageMax" exact="$gtlsPsd.$DeliveryCoverageMax"/>
          <set_value name="$gtlsSupplierCoverageMax" exact="$gtlsPsd.$SupplierCoverageMax"/>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <do_if value="global.$GT_LiveSearchScratch.{$gtlsShip}?">
            <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$PlayerBuyersInRange" exact="$gtlsPlayerBuyersInRange"/>
            <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$PlayerSuppliersInRange" exact="$gtlsPlayerSuppliersInRange"/>
            <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$DeliveryCoverageMax" exact="$gtlsDeliveryCoverageMax"/>
            <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$SupplierCoverageMax" exact="$gtlsSupplierCoverageMax"/>
          </do_if>
        </do_else>
      </do_if>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Collect seller offers (ship buys from seller)
           Per-ware cap applied: each ware gets up to $maxOffersPerWare offers.
           Demand-led mode defers this until buy offers define the ware basket (S4).
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <label name="gtls_collect_sell_offers"/>
      <!-- MK4 supply: max customer buy unitprice per ware â€” prefilter suppliers before clamp (mirrors tradematch price cap). -->
      <set_value name="this.$gtlsMaxBuyUnitPriceByWare" exact="table[]"/>
      <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" exact="0"/>
      <do_if value="$gtlsRequirePlayerBuyOfferOwner and $buyOffers? and $buyOffers.count gt 0">
        <do_all exact="$buyOffers.count" counter="$gtlsMbpIdx">
          <set_value name="$gtlsMbpOffer" exact="$buyOffers.{$gtlsMbpIdx}"/>
          <set_value name="$gtlsMbpWare" exact="@$gtlsMbpOffer.ware"/>
          <do_if value="$gtlsMbpWare? and $gtlsMbpOffer.unitprice?">
            <do_if value="not this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWare}? or $gtlsMbpOffer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWare}">
              <set_value name="this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWare}" exact="$gtlsMbpOffer.unitprice"/>
            </do_if>
          </do_if>
        </do_all>
      </do_if>
      <!-- MK4-2 player supplier scan: station-centric find_sell_offer (skips buySpaces sector loop when SF=0). -->
      <do_if value="$gtlsSearchMode != 'sell_only' and not $gtlsSkipSupplierScan and (not this.$gtlsDemandLedSupplierScan? or not this.$gtlsDemandLedSupplierScan or this.$gtlsDemandLedSellDone?) and $gtlsUsePlayerStationDiscovery and $gtlsIncludePlayerSellOffers and $gtlsUseAllWares and $gtlsPlayerSuppliersInRange.count gt 0">
        <do_all exact="$gtlsPlayerSuppliersInRange.count" counter="$gtlsPssi">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <set_value name="$gtlsPst" exact="$gtlsPlayerSuppliersInRange.{$gtlsPssi}"/>
          <set_value name="$space" exact="if $gtlsPst.sector? then @$gtlsPst.sector else null"/>
          <do_if value="not $space? or not @$space.exists">
            <continue/>
          </do_if>
          <find_sell_offer seller="$gtlsPst" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
            <match_seller tradesknownto="$gtlsShip.owner">
              <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
              <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
            </match_seller>
            <amount min="1"/>
            <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
          </find_sell_offer>
          <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
            <do_all exact="$foundSellOffers.count" counter="$oi">
              <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
              <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                <continue/>
              </do_if>
              <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                <continue/>
              </do_if>
              <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                <continue/>
              </do_if>
              <do_if value="not $gtlsIncludePlayerSellOffers and $offer.owner? and @$offer.owner.isplayerowned">
                <continue/>
              </do_if>
              <do_if value="not $gtlsIncludeNpcSellOffers and (not $offer.owner? or not @$offer.owner.isplayerowned)">
                <continue/>
              </do_if>
              <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing and $offer.ware?">
                <set_value name="$gtlsMbpWareCheck" exact="@$offer.ware"/>
                <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWareCheck}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWareCheck}">
                  <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                  <continue/>
                </do_if>
              </do_if>
              <set_value name="$gtlsSellClampSeller" exact="null"/>
              <do_if value="$offer.seller?">
                <set_value name="$gtlsSellClampSeller" exact="@$offer.seller"/>
              </do_if>
              <do_if value="$gtlsSellClampSeller == null and $offer.owner?">
                <set_value name="$gtlsSellClampSeller" exact="@$offer.owner"/>
              </do_if>
              <do_if value="$gtlsSellClampSeller != null">
                <set_value name="$gtlsSellClampAmt" exact="0"/>
                <do_if value="$offer.offeramount.{$gtlsShip}? and $offer.offeramount.{$gtlsShip} gt 0">
                  <set_value name="$gtlsSellClampAmt" exact="$offer.offeramount.{$gtlsShip}"/>
                </do_if>
                <do_elseif value="$offer.amount? and $offer.amount gt 0">
                  <set_value name="$gtlsSellClampAmt" exact="$offer.amount"/>
                </do_elseif>
                <do_else>
                  <set_value name="$gtlsSellClampAmt" exact="1"/>
                </do_else>
                <set_value name="$gtlsSellClampReason" exact="null"/>
                <clamp_trade_amount trade="$offer" amount="$gtlsSellClampAmt" buyer="$gtlsShip" seller="$gtlsSellClampSeller" result="$gtlsSellClampAmt" reason="$gtlsSellClampReason"/>
                <do_if value="not $gtlsSellClampAmt? or $gtlsSellClampAmt le 0">
                  <continue/>
                </do_if>
              </do_if>
              <do_else>
                <continue/>
              </do_else>
              <set_value name="$offerWare" exact="@$offer.ware"/>
              <do_if value="$offerWare?">
                <do_if value="not $sellOffersPerWare.{$offerWare}?">
                  <set_value name="$sellOffersPerWare.{$offerWare}" exact="0"/>
                </do_if>
                <set_value name="$isBuildStorageSellSupplier" exact="$offer.owner? and $offer.owner.isclass.buildstorage"/>
                <set_value name="$isPlayerSellSupplier" exact="$offer.owner? and @$offer.owner.isplayerowned and not $isBuildStorageSellSupplier"/>
                <do_if value="$isBuildStorageSellSupplier">
                  <do_if value="not $gtlsBuildStorageReservePerWare?">
                    <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                    <continue/>
                  </do_if>
                </do_if>
                <do_elseif value="$isPlayerSellSupplier and $gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
                  <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                    <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare)">
                    <continue/>
                  </do_if>
                </do_elseif>
                <do_else>
                  <do_if value="$sellOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                    <continue/>
                  </do_if>
                </do_else>
                <set_value name="$sellOffersPerWare.{$offerWare}" operation="add"/>
              </do_if>
              <append_to_list name="$sellOffers" exact="$offer"/>
            </do_all>
          </do_if>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after player-supplier station"/>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
        </do_all>
      </do_if>
      <do_if value="$gtlsSearchMode != 'sell_only' and $gtlsBuySpaces? and $gtlsBuySpaces.count gt 0 and not $gtlsSkipSupplierScan and (not this.$gtlsDemandLedSupplierScan? or not this.$gtlsDemandLedSupplierScan or this.$gtlsDemandLedSellDone?) and not ($gtlsUsePlayerStationDiscovery and not $gtlsIncludeNpcSellOffers)">
        <do_all exact="$gtlsBuySpaces.count" counter="$si">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <set_value name="$space" exact="$gtlsBuySpaces.{$si}"/>
          <do_if value="$gtlsUseAllWares">
            <do_if value="$gtlsSectorSupplierNpcOnly">
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_if>
            <do_elseif value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_elseif>
            <do_elseif value="$gtlsIncludeNpcSellOffers">
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_elseif>
            <do_elseif value="$gtlsIncludePlayerSellOffers">
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_elseif>
            <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
              <do_all exact="$foundSellOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="not $gtlsIncludePlayerSellOffers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="not $gtlsIncludeNpcSellOffers and (not $offer.owner? or not @$offer.owner.isplayerowned)">
                  <continue/>
                </do_if>
                <!-- MK4 supply: supplier unitprice must not exceed max customer buy price for this ware. -->
                <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing and $offer.ware?">
                  <set_value name="$gtlsMbpWareCheck" exact="@$offer.ware"/>
                  <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWareCheck}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$gtlsMbpWareCheck}">
                    <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>
                <!-- Reject broker phantoms: relativeprice/offeramount can pass while seller has
                     no exportable stock (trade_found clamp â†’ seller_cargo=0). Mirrors tradematch
                     and order.trade.galaxytrader executable-filter seller resolution. -->
                <set_value name="$gtlsSellClampSeller" exact="null"/>
                <do_if value="$offer.seller?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.seller"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller == null and $offer.owner?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.owner"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller != null">
                  <set_value name="$gtlsSellClampAmt" exact="0"/>
                  <do_if value="$offer.offeramount.{$gtlsShip}? and $offer.offeramount.{$gtlsShip} gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.offeramount.{$gtlsShip}"/>
                  </do_if>
                  <do_elseif value="$offer.amount? and $offer.amount gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.amount"/>
                  </do_elseif>
                  <do_else>
                    <set_value name="$gtlsSellClampAmt" exact="1"/>
                  </do_else>
                  <set_value name="$gtlsSellClampReason" exact="null"/>
                  <clamp_trade_amount trade="$offer" amount="$gtlsSellClampAmt" buyer="$gtlsShip" seller="$gtlsSellClampSeller" result="$gtlsSellClampAmt" reason="$gtlsSellClampReason"/>
                  <do_if value="not $gtlsSellClampAmt? or $gtlsSellClampAmt le 0">
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
                <!-- Per-ware cap: ensure ware diversity. Build-storage suppliers get a reserved
                     slot budget (mirrors buy-side build-storage reserve) so HQ supply is not
                     crowded out when NPC/trading-station offers fill the base cap first.
                     Player-owned suppliers get the same reserve when both player and NPC scans run,
                     so buyFromFaction priority only affects scoring, not supplier availability. -->
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <do_if value="not $sellOffersPerWare.{$offerWare}?">
                    <set_value name="$sellOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <set_value name="$isBuildStorageSellSupplier" exact="$offer.owner? and $offer.owner.isclass.buildstorage"/>
                  <set_value name="$isPlayerSellSupplier" exact="$offer.owner? and @$offer.owner.isplayerowned and not $isBuildStorageSellSupplier"/>
                  <do_if value="$isBuildStorageSellSupplier">
                    <do_if value="not $gtlsBuildStorageReservePerWare?">
                      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$sellOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                      <continue/>
                    </do_if>
                  </do_if>
                  <do_elseif value="$isPlayerSellSupplier and $gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
                    <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                      <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$sellOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare)">
                      <continue/>
                    </do_if>
                  </do_elseif>
                  <do_else>
                    <do_if value="$sellOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                  </do_else>
                  <set_value name="$sellOffersPerWare.{$offerWare}" operation="add"/>
                </do_if>
                <append_to_list name="$sellOffers" exact="$offer"/>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
          <do_all exact="$gtlsWareBasket.count" counter="$wi">
            <set_value name="$ware" exact="$gtlsWareBasket.{$wi}"/>
            <!-- Skip this ware entirely if we already have enough sell offers for it -->
            <set_value name="$gtlsSellWareSkipCap" exact="$gtlsMaxOffersPerWare"/>
            <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
              <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
              </do_if>
              <do_if value="not $gtlsBuildStorageReservePerWare?">
                <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
              </do_if>
              <set_value name="$gtlsSellWareSkipCap" exact="$gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare + $gtlsBuildStorageReservePerWare"/>
            </do_if>
            <do_if value="$sellOffersPerWare.{$ware}? and $sellOffersPerWare.{$ware} ge $gtlsSellWareSkipCap">
              <continue/>
            </do_if>
            <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_if>
            <do_elseif value="$gtlsIncludeNpcSellOffers">
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_elseif>
            <do_elseif value="$gtlsIncludePlayerSellOffers">
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_seller>
                <amount min="1"/>
                <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_sell_offer>
            </do_elseif>
            <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
              <do_if value="not $sellOffersPerWare.{$ware}?">
                <set_value name="$sellOffersPerWare.{$ware}" exact="0"/>
              </do_if>
              <do_all exact="$foundSellOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
                <set_value name="$isBuildStorageSellSupplier" exact="$offer.owner? and $offer.owner.isclass.buildstorage"/>
                <set_value name="$isPlayerSellSupplier" exact="$offer.owner? and @$offer.owner.isplayerowned and not $isBuildStorageSellSupplier"/>
                <do_if value="$isBuildStorageSellSupplier">
                  <do_if value="not $gtlsBuildStorageReservePerWare?">
                    <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                    <continue/>
                  </do_if>
                </do_if>
                <do_elseif value="$isPlayerSellSupplier and $gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
                  <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                    <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare)">
                    <continue/>
                  </do_if>
                </do_elseif>
                <do_else>
                  <do_if value="$sellOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                    <break/>
                  </do_if>
                </do_else>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="not $gtlsIncludePlayerSellOffers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="not $gtlsIncludeNpcSellOffers and (not $offer.owner? or not @$offer.owner.isplayerowned)">
                  <continue/>
                </do_if>
                <!-- MK4 supply: supplier unitprice must not exceed max customer buy price for this ware. -->
                <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing">
                  <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$ware}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$ware}">
                    <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>
                <set_value name="$gtlsSellClampSeller" exact="null"/>
                <do_if value="$offer.seller?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.seller"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller == null and $offer.owner?">
                  <set_value name="$gtlsSellClampSeller" exact="@$offer.owner"/>
                </do_if>
                <do_if value="$gtlsSellClampSeller != null">
                  <set_value name="$gtlsSellClampAmt" exact="0"/>
                  <do_if value="$offer.offeramount.{$gtlsShip}? and $offer.offeramount.{$gtlsShip} gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.offeramount.{$gtlsShip}"/>
                  </do_if>
                  <do_elseif value="$offer.amount? and $offer.amount gt 0">
                    <set_value name="$gtlsSellClampAmt" exact="$offer.amount"/>
                  </do_elseif>
                  <do_else>
                    <set_value name="$gtlsSellClampAmt" exact="1"/>
                  </do_else>
                  <set_value name="$gtlsSellClampReason" exact="null"/>
                  <clamp_trade_amount trade="$offer" amount="$gtlsSellClampAmt" buyer="$gtlsShip" seller="$gtlsSellClampSeller" result="$gtlsSellClampAmt" reason="$gtlsSellClampReason"/>
                  <do_if value="not $gtlsSellClampAmt? or $gtlsSellClampAmt le 0">
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
                <append_to_list name="$sellOffers" exact="$offer"/>
                <set_value name="$sellOffersPerWare.{$ware}" operation="add"/>
              </do_all>
            </do_if>
          </do_all>
          </do_else>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $MaxDistanceSell = $gtlsMaxDistanceSell,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $IncludeNpcSellOffers = $gtlsIncludeNpcSellOffers,
            $SkipSupplierScan = $gtlsSkipSupplierScan,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after sell-offer sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
      </do_if>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': sell-offers collected=' + $sellOffers.count + ' (sellPriceMax=' + $gtlsSellPriceMax + (if $gtlsRequirePlayerBuyOfferOwner and this.$gtlsMk4PriceCapPrefilterSkipped? and this.$gtlsMk4PriceCapPrefilterSkipped gt 0 then ', mk4PriceCapPrefilterSkipped=' + this.$gtlsMk4PriceCapPrefilterSkipped else '') + ')'" chance="$gtlsDebugchance"/>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           MK3 'Ignore Player Pricing' supplemental scan: collect player-owned
           sell offers without relativeprice filtering so the ship buys from
           player stations regardless of the player-set sell price band.
           Deduplicates against offers already added by the main scan.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <set_value name="$gtlsBpScanUseStations" exact="$gtlsUsePlayerStationDiscovery and $gtlsPlayerSuppliersInRange.count gt 0"/>
      <do_if value="$gtlsBypassPlayerSellerPricing and $gtlsIncludePlayerSellOffers and $gtlsSearchMode != 'sell_only' and ($gtlsBpScanUseStations or ($gtlsBuySpaces? and $gtlsBuySpaces.count gt 0)) and $gtlsOwnerFilter != 'npc_only' and (not this.$gtlsDemandLedSupplierScan? or not this.$gtlsDemandLedSupplierScan or this.$gtlsDemandLedSellDone?)">
        <set_value name="$gtlsSeenSellOffers" exact="table[]"/>
        <do_all exact="$sellOffers.count" counter="$bpInit">
          <set_value name="$gtlsSeenSellOffers.{$sellOffers.{$bpInit}}" exact="true"/>
        </do_all>
        <set_value name="$playerSellOffersAdded" exact="0"/>
        <set_value name="$gtlsBpScanCount" exact="if $gtlsBpScanUseStations then $gtlsPlayerSuppliersInRange.count else $gtlsBuySpaces.count"/>
        <do_all exact="$gtlsBpScanCount" counter="$bpSi">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>

          <do_if value="$gtlsBpScanUseStations">
            <set_value name="$gtlsPst" exact="$gtlsPlayerSuppliersInRange.{$bpSi}"/>
            <set_value name="$space" exact="if $gtlsPst.sector? then @$gtlsPst.sector else null"/>
            <do_if value="not $space? or not @$space.exists">
              <continue/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$gtlsPst" exact="null"/>
            <set_value name="$space" exact="$gtlsBuySpaces.{$bpSi}"/>
          </do_else>
          <do_if value="$gtlsUseAllWares">
            <do_if value="$gtlsPst? and @$gtlsPst.exists">
              <find_sell_offer seller="$gtlsPst" tradepartner="$gtlsShip" space="$space" result="$bpSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                </match_seller>
                <amount min="1"/>
              </find_sell_offer>
            </do_if>
            <do_else>
              <find_sell_offer tradepartner="$gtlsShip" space="$space" result="$bpSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                </match_seller>
                <amount min="1"/>
              </find_sell_offer>
            </do_else>
            <do_if value="$bpSellOffers? and $bpSellOffers.count gt 0">
              <do_all exact="$bpSellOffers.count" counter="$bpOi">
                <set_value name="$offer" exact="$bpSellOffers.{$bpOi}"/>
                <do_if value="$gtlsSeenSellOffers.{$offer}?">
                  <continue/>
                </do_if>
                <do_if value="not $offer.owner? or not @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <do_if value="not $sellOffersPerWare.{$offerWare}?">
                    <set_value name="$sellOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <set_value name="$gtlsBpSellCap" exact="$gtlsMaxOffersPerWare"/>
                  <do_if value="$gtlsIncludeNpcSellOffers">
                    <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                      <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <set_value name="$gtlsBpSellCap" exact="$gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$offerWare} ge $gtlsBpSellCap">
                    <continue/>
                  </do_if>
                  <set_value name="$sellOffersPerWare.{$offerWare}" operation="add"/>
                </do_if>
                <set_value name="$gtlsSeenSellOffers.{$offer}" exact="true"/>
                <append_to_list name="$sellOffers" exact="$offer"/>
                <set_value name="$playerSellOffersAdded" operation="add"/>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
            <do_all exact="$gtlsWareBasket.count" counter="$bpWi">
              <set_value name="$ware" exact="$gtlsWareBasket.{$bpWi}"/>
              <set_value name="$gtlsBpWareSkipCap" exact="$gtlsMaxOffersPerWare"/>
              <do_if value="$gtlsIncludeNpcSellOffers">
                <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                  <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                </do_if>
                <set_value name="$gtlsBpWareSkipCap" exact="$gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare"/>
              </do_if>
              <do_if value="$sellOffersPerWare.{$ware}? and $sellOffersPerWare.{$ware} ge $gtlsBpWareSkipCap">
                <continue/>
              </do_if>
              <find_sell_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$bpSellOffers" multiple="true">
                <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                </match_seller>
                <amount min="1"/>
              </find_sell_offer>
              <do_if value="$bpSellOffers? and $bpSellOffers.count gt 0">
                <do_if value="not $sellOffersPerWare.{$ware}?">
                  <set_value name="$sellOffersPerWare.{$ware}" exact="0"/>
                </do_if>
                <do_all exact="$bpSellOffers.count" counter="$bpOi">
                  <set_value name="$gtlsBpSellCap" exact="$gtlsMaxOffersPerWare"/>
                  <do_if value="$gtlsIncludeNpcSellOffers">
                    <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                      <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <set_value name="$gtlsBpSellCap" exact="$gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare"/>
                  </do_if>
                  <do_if value="$sellOffersPerWare.{$ware} ge $gtlsBpSellCap">
                    <break/>
                  </do_if>
                  <set_value name="$offer" exact="$bpSellOffers.{$bpOi}"/>
                  <do_if value="$gtlsSeenSellOffers.{$offer}?">
                    <continue/>
                  </do_if>
                  <do_if value="not $offer.owner? or not @$offer.owner.isplayerowned">
                    <continue/>
                  </do_if>
                  <set_value name="$gtlsSeenSellOffers.{$offer}" exact="true"/>
                  <append_to_list name="$sellOffers" exact="$offer"/>
                  <set_value name="$sellOffersPerWare.{$ware}" operation="add"/>
                  <set_value name="$playerSellOffersAdded" operation="add"/>
                </do_all>
              </do_if>
            </do_all>
          </do_else>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after player-seller supplement sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': bypassPlayerSellerPricing supplement added=' + $playerSellOffersAdded + ' player sell offers (total sell=' + $sellOffers.count + ')'" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           MK4 single-trip completion pass (auto-wares only):
           Pre-collect player buy offers whose remaining cargo need fits in one ship load
           (deficit <= freeCargo / ware.volume). These bypass the per-ware cap so small
           remainder deliveries (e.g. 54 Quantum Tubes) are not crowded out. Gate uses only
           station target/count and ship cargo â€” no fixed unit or percent thresholds.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>
      <set_value name="$gtlsCompletionScanUseBuyers" exact="$gtlsUsePlayerStationDiscovery and $gtlsPlayerBuyersInRange.count gt 0"/>
      <do_if value="$gtlsRequirePlayerBuyOfferOwner and $gtlsUseAllWares and $gtlsSearchMode != 'buy_only' and ($gtlsCompletionScanUseBuyers or ($gtlsSellSpaces? and $gtlsSellSpaces.count gt 0))">
        <set_value name="$completionBuyOffersAdded" exact="0"/>
        <set_value name="$gtlsCompletionScanCount" exact="if $gtlsCompletionScanUseBuyers then $gtlsPlayerBuyersInRange.count else $gtlsSellSpaces.count"/>
        <do_all exact="$gtlsCompletionScanCount" counter="$cpsi">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>

          <do_if value="$gtlsCompletionScanUseBuyers">
            <set_value name="$gtlsScanBuyer" exact="$gtlsPlayerBuyersInRange.{$cpsi}"/>
            <set_value name="$space" exact="if $gtlsScanBuyer.sector? then @$gtlsScanBuyer.sector else null"/>
            <do_if value="not $space? or not @$space.exists">
              <continue/>
            </do_if>
            <find_buy_offer buyer="$gtlsScanBuyer" space="$space" result="$completionBuyOffers" multiple="true">
              <amount min="1"/>
            </find_buy_offer>
          </do_if>
          <do_else>
            <set_value name="$space" exact="$gtlsSellSpaces.{$cpsi}"/>
            <find_buy_offer space="$space" result="$completionBuyOffers" multiple="true">
              <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <amount min="1"/>
            </find_buy_offer>
          </do_else>
          <do_if value="$completionBuyOffers? and $completionBuyOffers.count gt 0">
            <do_all exact="$completionBuyOffers.count" counter="$cpoi">
              <set_value name="$offer" exact="$completionBuyOffers.{$cpoi}"/>
              <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                <continue/>
              </do_if>
              <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                <continue/>
              </do_if>
              <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                <continue/>
              </do_if>
              <set_value name="$offerWare" exact="if $offer.ware? then @$offer.ware else null"/>
              <set_value name="$offerCustomer" exact="if $offer.buyer? and @$offer.buyer.exists then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
              <do_if value="not $offerWare? or not $offerCustomer? or not @$offerCustomer.exists">
                <continue/>
              </do_if>
              <do_if value="if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false">
                <do_if value="not @$offerCustomer.isclass.buildstorage">
                  <continue/>
                </do_if>
              </do_if>
              <do_elseif value="$offerCustomer.isclass.buildstorage">
                <continue/>
              </do_elseif>
              <set_value name="$cpTarget" exact="$offerCustomer.cargo.{$offerWare}.target"/>
              <set_value name="$cpCount" exact="$offerCustomer.cargo.{$offerWare}.count"/>
              <set_value name="$cpDeficit" exact="[$cpTarget - $cpCount, 0].max"/>
              <do_if value="$cpDeficit le 0">
                <continue/>
              </do_if>
              <set_value name="$cpVolPerUnit" exact="if $offerWare.volume? and $offerWare.volume gt 0 then $offerWare.volume else 1"/>
              <set_value name="$cpOneTripUnits" exact="($gtlsShip.cargo.free.all / $cpVolPerUnit)i"/>
              <do_if value="$cpOneTripUnits le 0 or $cpDeficit gt $cpOneTripUnits">
                <continue/>
              </do_if>
              <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
              <append_to_list name="$buyOffers" exact="$offer"/>
              <set_value name="$completionBuyOffersAdded" operation="add"/>
            </do_all>
          </do_if>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $MaxDistanceSell = $gtlsMaxDistanceSell,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $IncludeNpcSellOffers = $gtlsIncludeNpcSellOffers,
            $SkipSupplierScan = $gtlsSkipSupplierScan,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after MK4 completion buy-offer sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': MK4 single-trip completion pass added=' + $completionBuyOffersAdded + ' player buy offers (total buy=' + $buyOffers.count + ')'" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Collect buyer offers (ship sells to buyer)
           Per-ware cap applied: each ware gets up to $maxOffersPerWare offers.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <set_value name="$gtlsBuyScanUseBuyers" exact="$gtlsUsePlayerStationDiscovery and $gtlsPlayerBuyersInRange.count gt 0"/>
      <do_if value="$gtlsSearchMode != 'buy_only' and ($gtlsBuyScanUseBuyers or ($gtlsSellSpaces? and $gtlsSellSpaces.count gt 0))">
        <set_value name="$gtlsBuyScanCount" exact="if $gtlsBuyScanUseBuyers then $gtlsPlayerBuyersInRange.count else $gtlsSellSpaces.count"/>
        <do_all exact="$gtlsBuyScanCount" counter="$si">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="$gtlsBuyScanUseBuyers">
            <set_value name="$gtlsScanBuyer" exact="$gtlsPlayerBuyersInRange.{$si}"/>
            <set_value name="$space" exact="if $gtlsScanBuyer.sector? then @$gtlsScanBuyer.sector else null"/>
            <do_if value="not $space? or not @$space.exists">
              <continue/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$gtlsScanBuyer" exact="null"/>
            <set_value name="$space" exact="$gtlsSellSpaces.{$si}"/>
          </do_else>
          <do_if value="$gtlsUseAllWares">
            <!-- MK4-2: player delivery only â€” skip NPC buy-offer engine scan when requirePlayerBuyOfferOwner. -->
            <do_if value="$gtlsRequirePlayerBuyOfferOwner">
              <do_if value="$gtlsScanBuyer? and @$gtlsScanBuyer.exists">
                <find_buy_offer buyer="$gtlsScanBuyer" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                  <offeramount min="1" tradepartner="$gtlsShip"/>
                  <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                </find_buy_offer>
              </do_if>
              <do_else>
                <find_buy_offer tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                    <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <offeramount min="1" tradepartner="$gtlsShip"/>
                  <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                </find_buy_offer>
              </do_else>
            </do_if>
            <do_else>
              <find_buy_offer tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                <match_buyer tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <offeramount min="1" tradepartner="$gtlsShip"/>
                <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_buy_offer>
            </do_else>
            <do_if value="$gtlsIgnoreTradeRules">
              <!-- ignoreTradeRules scope: only bypass player-station trade rules.
                   Do not broaden to non-player stations or bypass other partner checks. -->
              <do_if value="$gtlsScanBuyer? and @$gtlsScanBuyer.exists">
                <find_buy_offer buyer="$gtlsScanBuyer" space="$space" result="$ignoreRulesBuyOffers" multiple="true">
                  <amount min="1"/>
                </find_buy_offer>
              </do_if>
              <do_else>
                <find_buy_offer space="$space" result="$ignoreRulesBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                    <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <amount min="1"/>
                </find_buy_offer>
              </do_else>
              <do_if value="not $foundBuyOffers?">
                <create_list name="$foundBuyOffers"/>
              </do_if>
              <do_if value="$ignoreRulesBuyOffers? and $ignoreRulesBuyOffers.count gt 0">
                <do_all exact="$ignoreRulesBuyOffers.count" counter="$iri">
                  <append_to_list name="$foundBuyOffers" exact="$ignoreRulesBuyOffers.{$iri}"/>
                </do_all>
              </do_if>
            </do_if>
            <do_if value="$foundBuyOffers? and $foundBuyOffers.count gt 0">
              <do_all exact="$foundBuyOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundBuyOffers.{$oi}"/>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                  <continue/>
                </do_if>
                <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                  <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                  <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                    <do_if value="@$gtlsBuyerObj.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_if>
                    <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $gtlsPlayerBuyerOk">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                  <continue/>
                </do_if>
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <set_value name="$capWare" exact="$offerWare"/>
                  <set_value name="$capAccepted" exact="false"/>
                  <set_value name="$capScoreAwareCandidate" exact="false"/>
                  <do_if value="$gtlsUseScoreAwareBuyCap and $gtlsSourceSellByWare.{$capWare}?">
                    <set_value name="$homeSellOffer" exact="$gtlsSourceSellByWare.{$capWare}"/>
                    <do_if value="$homeSellOffer? and @$homeSellOffer.exists and $homeSellOffer.available">
                      <set_value name="$unitProfit" exact="$offer.unitprice - $homeSellOffer.unitprice"/>
                      <do_if value="$unitProfit ge 0">
                        <set_value name="$buyOfferAmount" exact="@$offer.offeramount.{$gtlsShip}"/>
                        <do_if value="$buyOfferAmount == null">
                          <set_value name="$buyOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$sellOfferAmount" exact="@$homeSellOffer.offeramount.{$gtlsShip}"/>
                        <do_if value="$sellOfferAmount == null">
                          <set_value name="$sellOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$tradeAmount" exact="[[$buyOfferAmount, $sellOfferAmount].min, 0].max"/>
                        <do_if value="$tradeAmount gt 0">
                          <set_value name="$buyerStation" exact="null"/>
                          <do_if value="$offer.buyer? and @$offer.buyer.exists">
                            <set_value name="$buyerStation" exact="@$offer.buyer"/>
                          </do_if>
                          <do_elseif value="$offer.owner?">
                            <set_value name="$buyerStation" exact="@$offer.owner"/>
                          </do_elseif>
                          <set_value name="$buyerDist" exact="if $buyerStation? and $gtlsHomeSector? then $gtlsHomeSector.gatedistance.{$buyerStation.sector} else -1"/>
                          <do_if value="$buyerDist ge 0 and ($gtlsMaxDistance le 0 or $buyerDist le $gtlsMaxDistance)">
                            <set_value name="$distFactor" exact="1.0 + ($buyerDist * $gtlsDistancePenalty)"/>
                            <set_value name="$grossProfitCr" exact="(($unitProfit * $tradeAmount) / 1Cr)i"/>
                            <set_value name="$capScore" exact="$grossProfitCr / $distFactor"/>
                            <set_value name="$capScoreAwareCandidate" exact="true"/>
                            <do_if value="not $gtlsTopBuyOffersPerWare.{$capWare}?">
                              <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="[]"/>
                              <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="[]"/>
                            </do_if>
                            <set_value name="$topOffers" exact="$gtlsTopBuyOffersPerWare.{$capWare}"/>
                            <set_value name="$topScores" exact="$gtlsTopBuyScoresPerWare.{$capWare}"/>
                            <do_if value="$topOffers.count lt $gtlsMaxOffersPerWare">
                              <append_to_list name="$topOffers" exact="$offer"/>
                              <append_to_list name="$topScores" exact="$capScore"/>
                              <set_value name="$capAccepted" exact="true"/>
                            </do_if>
                            <do_else>
                              <set_value name="$minScore" exact="$topScores.{1}"/>
                              <set_value name="$minScoreIdx" exact="1"/>
                              <do_all exact="$topScores.count" counter="$tsi">
                                <do_if value="$topScores.{$tsi} lt $minScore">
                                  <set_value name="$minScore" exact="$topScores.{$tsi}"/>
                                  <set_value name="$minScoreIdx" exact="$tsi"/>
                                </do_if>
                              </do_all>
                              <do_if value="$capScore gt $minScore">
                                <set_value name="$topOffers.{$minScoreIdx}" exact="$offer"/>
                                <set_value name="$topScores.{$minScoreIdx}" exact="$capScore"/>
                                <set_value name="$capAccepted" exact="true"/>
                              </do_if>
                            </do_else>
                            <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="$topOffers"/>
                            <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="$topScores"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="not $buyOffersPerWare.{$capWare}?">
                      <set_value name="$buyOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$capWare}?">
                      <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                    <set_value name="$capFull" exact="false"/>
                    <do_if value="$isBuildStorageBuyer">
                      <do_if value="$buyOffersPerWare.{$capWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="$buyOffersPerWare.{$capWare} ge $gtlsMaxOffersPerWare">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_else>
                    <do_if value="not $capFull">
                      <do_if value="$isBuildStorageBuyer">
                        <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" operation="add"/>
                        <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                      </do_if>
                      <append_to_list name="$buyOffers" exact="$offer"/>
                      <set_value name="$buyOffersPerWare.{$capWare}" operation="add"/>
                      <set_value name="$capAccepted" exact="true"/>
                    </do_if>
                  </do_else>
                  <do_if value="$capAccepted">
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <do_if value="$capScoreAwareCandidate">
                      <set_value name="$gtlsScoreAwareCandidatesSeen" operation="add"/>
                    </do_if>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
          <do_all exact="$gtlsWareBasket.count" counter="$wi">
            <set_value name="$ware" exact="$gtlsWareBasket.{$wi}"/>
            <!-- Skip this ware entirely if we already have enough buy offers for it -->
            <do_if value="not $gtlsBuildStorageReservePerWare?">
              <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
            </do_if>
            <do_if value="not $gtlsUseScoreAwareBuyCap and $buyOffersPerWare.{$ware}? and $buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
              <continue/>
            </do_if>
            <!-- MK4-2: player delivery only â€” skip NPC buy-offer engine scan when requirePlayerBuyOfferOwner. -->
            <do_if value="$gtlsRequirePlayerBuyOfferOwner">
              <do_if value="$gtlsScanBuyer? and @$gtlsScanBuyer.exists">
                <find_buy_offer wares="$ware" buyer="$gtlsScanBuyer" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                  <offeramount min="1" tradepartner="$gtlsShip"/>
                  <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                </find_buy_offer>
              </do_if>
              <do_else>
                <find_buy_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                    <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <offeramount min="1" tradepartner="$gtlsShip"/>
                  <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                </find_buy_offer>
              </do_else>
            </do_if>
            <do_else>
              <find_buy_offer wares="$ware" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                <match_buyer tradesknownto="$gtlsShip.owner">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <offeramount min="1" tradepartner="$gtlsShip"/>
                <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
              </find_buy_offer>
            </do_else>
            <do_if value="$gtlsIgnoreTradeRules">
              <!-- ignoreTradeRules scope: only bypass player-station trade rules.
                   Do not broaden to non-player stations or bypass other partner checks. -->
              <do_if value="$gtlsScanBuyer? and @$gtlsScanBuyer.exists">
                <find_buy_offer wares="$ware" buyer="$gtlsScanBuyer" space="$space" result="$ignoreRulesBuyOffers" multiple="true">
                  <amount min="1"/>
                </find_buy_offer>
              </do_if>
              <do_else>
                <find_buy_offer wares="$ware" space="$space" result="$ignoreRulesBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                    <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <amount min="1"/>
                </find_buy_offer>
              </do_else>
              <do_if value="not $foundBuyOffers?">
                <create_list name="$foundBuyOffers"/>
              </do_if>
              <do_if value="$ignoreRulesBuyOffers? and $ignoreRulesBuyOffers.count gt 0">
                <do_all exact="$ignoreRulesBuyOffers.count" counter="$iri">
                  <append_to_list name="$foundBuyOffers" exact="$ignoreRulesBuyOffers.{$iri}"/>
                </do_all>
              </do_if>
            </do_if>
            <do_if value="$foundBuyOffers? and $foundBuyOffers.count gt 0">
              <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
              </do_if>
              <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
              </do_if>
              <do_if value="not $buyOffersPerWare.{$ware}?">
                <set_value name="$buyOffersPerWare.{$ware}" exact="0"/>
              </do_if>
              <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$ware}?">
                <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$ware}" exact="0"/>
              </do_if>
              <do_all exact="$foundBuyOffers.count" counter="$oi">
                <set_value name="$offer" exact="$foundBuyOffers.{$oi}"/>
                <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                <do_if value="$isBuildStorageBuyer">
                  <do_if value="not $gtlsBuildStorageReservePerWare?">
                    <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                  </do_if>
                  <do_if value="not $gtlsUseScoreAwareBuyCap and $buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                    <continue/>
                  </do_if>
                </do_if>
                <do_elseif value="not $gtlsUseScoreAwareBuyCap">
                  <do_if value="$buyOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                    <break/>
                  </do_if>
                </do_elseif>
                <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                  <continue/>
                </do_if>
                <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                  <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                  <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                    <do_if value="@$gtlsBuyerObj.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_if>
                    <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $gtlsPlayerBuyerOk">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                  <continue/>
                </do_if>
                <set_value name="$capWare" exact="$ware"/>
                <set_value name="$capAccepted" exact="false"/>
                  <set_value name="$capScoreAwareCandidate" exact="false"/>
                  <do_if value="$gtlsUseScoreAwareBuyCap and $gtlsSourceSellByWare.{$capWare}?">
                    <set_value name="$homeSellOffer" exact="$gtlsSourceSellByWare.{$capWare}"/>
                    <do_if value="$homeSellOffer? and @$homeSellOffer.exists and $homeSellOffer.available">
                      <set_value name="$unitProfit" exact="$offer.unitprice - $homeSellOffer.unitprice"/>
                      <do_if value="$unitProfit ge 0">
                        <set_value name="$buyOfferAmount" exact="@$offer.offeramount.{$gtlsShip}"/>
                        <do_if value="$buyOfferAmount == null">
                          <set_value name="$buyOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$sellOfferAmount" exact="@$homeSellOffer.offeramount.{$gtlsShip}"/>
                        <do_if value="$sellOfferAmount == null">
                          <set_value name="$sellOfferAmount" exact="0"/>
                        </do_if>
                        <set_value name="$tradeAmount" exact="[[$buyOfferAmount, $sellOfferAmount].min, 0].max"/>
                        <do_if value="$tradeAmount gt 0">
                          <set_value name="$buyerStation" exact="null"/>
                          <do_if value="$offer.buyer? and @$offer.buyer.exists">
                            <set_value name="$buyerStation" exact="@$offer.buyer"/>
                          </do_if>
                          <do_elseif value="$offer.owner?">
                            <set_value name="$buyerStation" exact="@$offer.owner"/>
                          </do_elseif>
                          <set_value name="$buyerDist" exact="if $buyerStation? and $gtlsHomeSector? then $gtlsHomeSector.gatedistance.{$buyerStation.sector} else -1"/>
                          <do_if value="$buyerDist ge 0 and ($gtlsMaxDistance le 0 or $buyerDist le $gtlsMaxDistance)">
                            <set_value name="$distFactor" exact="1.0 + ($buyerDist * $gtlsDistancePenalty)"/>
                            <set_value name="$grossProfitCr" exact="(($unitProfit * $tradeAmount) / 1Cr)i"/>
                            <set_value name="$capScore" exact="$grossProfitCr / $distFactor"/>
                            <set_value name="$capScoreAwareCandidate" exact="true"/>
                            <do_if value="not $gtlsTopBuyOffersPerWare.{$capWare}?">
                              <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="[]"/>
                              <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="[]"/>
                            </do_if>
                            <set_value name="$topOffers" exact="$gtlsTopBuyOffersPerWare.{$capWare}"/>
                            <set_value name="$topScores" exact="$gtlsTopBuyScoresPerWare.{$capWare}"/>
                            <do_if value="$topOffers.count lt $gtlsMaxOffersPerWare">
                              <append_to_list name="$topOffers" exact="$offer"/>
                              <append_to_list name="$topScores" exact="$capScore"/>
                              <set_value name="$capAccepted" exact="true"/>
                            </do_if>
                            <do_else>
                              <set_value name="$minScore" exact="$topScores.{1}"/>
                              <set_value name="$minScoreIdx" exact="1"/>
                              <do_all exact="$topScores.count" counter="$tsi">
                                <do_if value="$topScores.{$tsi} lt $minScore">
                                  <set_value name="$minScore" exact="$topScores.{$tsi}"/>
                                  <set_value name="$minScoreIdx" exact="$tsi"/>
                                </do_if>
                              </do_all>
                              <do_if value="$capScore gt $minScore">
                                <set_value name="$topOffers.{$minScoreIdx}" exact="$offer"/>
                                <set_value name="$topScores.{$minScoreIdx}" exact="$capScore"/>
                                <set_value name="$capAccepted" exact="true"/>
                              </do_if>
                            </do_else>
                            <set_value name="$gtlsTopBuyOffersPerWare.{$capWare}" exact="$topOffers"/>
                            <set_value name="$gtlsTopBuyScoresPerWare.{$capWare}" exact="$topScores"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="not $buyOffersPerWare.{$capWare}?">
                      <set_value name="$buyOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$capWare}?">
                      <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" exact="0"/>
                    </do_if>
                    <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                    <set_value name="$capFull" exact="false"/>
                    <do_if value="$isBuildStorageBuyer">
                      <do_if value="$buyOffersPerWare.{$capWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="$buyOffersPerWare.{$capWare} ge $gtlsMaxOffersPerWare">
                        <set_value name="$capFull" exact="true"/>
                      </do_if>
                    </do_else>
                    <do_if value="not $capFull">
                      <do_if value="$isBuildStorageBuyer">
                        <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$capWare}" operation="add"/>
                        <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                      </do_if>
                      <append_to_list name="$buyOffers" exact="$offer"/>
                      <set_value name="$buyOffersPerWare.{$capWare}" operation="add"/>
                      <set_value name="$capAccepted" exact="true"/>
                    </do_if>
                  </do_else>
                  <do_if value="$capAccepted">
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <do_if value="$capScoreAwareCandidate">
                      <set_value name="$gtlsScoreAwareCandidatesSeen" operation="add"/>
                    </do_if>
                  </do_if>
              </do_all>
            </do_if>
          </do_all>
          </do_else>
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="not global.$GT_LiveSearchScratch?">
            <set_value name="global.$GT_LiveSearchScratch" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}" exact="table[
            $Ship = $gtlsShip,
            $SearchMode = $gtlsSearchMode,
            $BuySpaces = $gtlsBuySpaces,
            $SellSpaces = $gtlsSellSpaces,
            $HomeSector = $gtlsHomeSector,
            $MaxDistance = $gtlsMaxDistance,
            $MaxDistanceSell = $gtlsMaxDistanceSell,
            $WareBasket = $gtlsWareBasket,
            $AllowIllegal = $gtlsAllowIllegal,
            $OwnerFilter = $gtlsOwnerFilter,
            $IgnoreMK1Supply = $gtlsIgnoreMK1Supply,
            $IgnoreTradeRules = $gtlsIgnoreTradeRules,
            $MaxOffersPerWare = $gtlsMaxOffersPerWare,
            $BuildStorageReservePerWare = $gtlsBuildStorageReservePerWare,
            $SellPriceMax = $gtlsSellPriceMax,
            $BuyPriceMin = $gtlsBuyPriceMin,
            $IncludePlayerBuyOffers = $gtlsIncludePlayerBuyOffers,
            $IncludePlayerSellOffers = $gtlsIncludePlayerSellOffers,
            $IncludeNpcSellOffers = $gtlsIncludeNpcSellOffers,
            $SkipSupplierScan = $gtlsSkipSupplierScan,
            $RequirePlayerBuyOfferOwner = $gtlsRequirePlayerBuyOfferOwner,
            $IgnoreTradeRulesPlayerBuyOffersRequireCargoNeed = $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed,
            $BypassPlayerSellerPricing = $gtlsBypassPlayerSellerPricing,
            $ExcludePlayerBuyers = $gtlsExcludePlayerBuyers,
            $PriorityWares = $gtlsPriorityWares,
            $Debugchance = $gtlsDebugchance,
            $UseAllWares = $gtlsUseAllWares,
            $DistancePenalty = $gtlsDistancePenalty,
            $SourceSellByWare = $gtlsSourceSellByWare,
            $UseScoreAwareBuyCap = $gtlsUseScoreAwareBuyCap,
            $TopBuyOffersPerWare = $gtlsTopBuyOffersPerWare,
            $TopBuyScoresPerWare = $gtlsTopBuyScoresPerWare,
            $ScoreAwareCandidatesSeen = $gtlsScoreAwareCandidatesSeen,
            $SeenBuyOffers = $gtlsSeenBuyOffers,
            $BuyBuildStorageOffersPerWare = $gtlsBuyBuildStorageOffersPerWare,
            $BuildStorageBuyOffersAdded = $gtlsBuildStorageBuyOffersAdded,
            $YieldMs = $gtYieldMs,
            $BuyOffers = $buyOffers,
            $SellOffers = $sellOffers,
            $BuyOffersPerWare = $buyOffersPerWare,
            $SellOffersPerWare = $sellOffersPerWare,
            $DemandLedSupplierScan = if this.$gtlsDemandLedSupplierScan? then this.$gtlsDemandLedSupplierScan else false,
            $DemandLedSellDone = if this.$gtlsDemandLedSellDone? then this.$gtlsDemandLedSellDone else false,
            $Mk4BuildStorageOnlyMode = if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false,
            $Mk4AnchorHome = if $gtlsMk4AnchorHome? then $gtlsMk4AnchorHome else null
          ]"/>
          <set_value name="global.$GT_LiveSearchActiveShip" exact="$gtlsShip"/>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after buy-offer sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
      </do_if>
      <!-- MK4 compatibility:
           include player buy offers even when tradepartner-filtered query returns none.
           This is intentionally scoped to player-owned buyers and still respects ware caps;
           downstream AI validation re-checks tradepartner constraints before order creation. -->
      <set_value name="$gtlsSuppScanUseBuyers" exact="$gtlsUsePlayerStationDiscovery and $gtlsPlayerBuyersInRange.count gt 0"/>
      <do_if value="not $gtlsExcludePlayerBuyers and $gtlsIncludePlayerBuyOffers and $gtlsOwnerFilter != 'npc_only' and ($gtlsIgnoreTradeRules or $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed) and $gtlsSearchMode != 'buy_only' and ($gtlsSuppScanUseBuyers or ($gtlsSellSpaces? and $gtlsSellSpaces.count gt 0))">
        <set_value name="$playerBuyOffersAdded" exact="0"/>
        <set_value name="$suppHasWareBasket" exact="$gtlsWareBasket? and $gtlsWareBasket.count gt 0"/>
        <set_value name="$gtlsSuppScanCount" exact="if $gtlsSuppScanUseBuyers then $gtlsPlayerBuyersInRange.count else $gtlsSellSpaces.count"/>
        <do_all exact="$gtlsSuppScanCount" counter="$si">
          <do_if value="not $gtYieldMs? or not $gtlsShip?">
            <resume label="gtls_ensure_state"/>
          </do_if>
          <do_if value="$gtlsSuppScanUseBuyers">
            <set_value name="$gtlsScanBuyer" exact="$gtlsPlayerBuyersInRange.{$si}"/>
            <set_value name="$space" exact="if $gtlsScanBuyer.sector? then @$gtlsScanBuyer.sector else null"/>
            <do_if value="not $space? or not @$space.exists">
              <continue/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$gtlsScanBuyer" exact="null"/>
            <set_value name="$space" exact="$gtlsSellSpaces.{$si}"/>
          </do_else>
          <do_if value="$gtlsUseAllWares">
            <do_if value="$gtlsScanBuyer? and @$gtlsScanBuyer.exists">
              <find_buy_offer buyer="$gtlsScanBuyer" space="$space" result="$playerBuyOffers" multiple="true">
                <offeramount min="1"/>
              </find_buy_offer>
            </do_if>
            <do_else>
              <find_buy_offer space="$space" result="$playerBuyOffers" multiple="true">
                <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                  <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <offeramount min="1"/>
              </find_buy_offer>
            </do_else>
            <do_if value="$playerBuyOffers? and $playerBuyOffers.count gt 0">
              <do_all exact="$playerBuyOffers.count" counter="$oi">
                <set_value name="$offer" exact="$playerBuyOffers.{$oi}"/>
                <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                  <continue/>
                </do_if>
                <!-- Honor manual ware basket even in supplemental player-buy scan. -->
                <do_if value="$suppHasWareBasket">
                  <set_value name="$offerWareInBasket" exact="false"/>
                  <set_value name="$offerWare" exact="if $offer.ware? then @$offer.ware else null"/>
                  <do_if value="$offerWare?">
                    <do_all exact="$gtlsWareBasket.count" counter="$wbi">
                      <do_if value="$gtlsWareBasket.{$wbi} == $offerWare">
                        <set_value name="$offerWareInBasket" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  <do_if value="not $offerWareInBasket">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                  <continue/>
                </do_if>
                <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                  <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                  <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                    <do_if value="@$gtlsBuyerObj.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_if>
                    <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                      <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $gtlsPlayerBuyerOk">
                    <continue/>
                  </do_if>
                </do_if>
                <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                  <continue/>
                </do_if>
                <set_value name="$offerWare" exact="@$offer.ware"/>
                <do_if value="$offerWare?">
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
                  </do_if>
                  <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
                  </do_if>
                  <do_if value="not $buyOffersPerWare.{$offerWare}?">
                    <set_value name="$buyOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$offerWare}?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$offerWare}" exact="0"/>
                  </do_if>
                  <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                  <do_if value="$isBuildStorageBuyer">
                    <do_if value="not $gtlsBuildStorageReservePerWare?">
                      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                      <continue/>
                    </do_if>
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$offerWare}" operation="add"/>
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                  </do_if>
                  <do_else>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                  </do_else>
                  <set_value name="$buyOffersPerWare.{$offerWare}" operation="add"/>
                </do_if>
                <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                <append_to_list name="$buyOffers" exact="$offer"/>
                <set_value name="$playerBuyOffersAdded" operation="add"/>
              </do_all>
            </do_if>
          </do_if>
          <do_else>
            <do_all exact="$gtlsWareBasket.count" counter="$wi">
              <set_value name="$ware" exact="$gtlsWareBasket.{$wi}"/>
              <do_if value="not $gtlsBuildStorageReservePerWare?">
                <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
              </do_if>
              <do_if value="$buyOffersPerWare.{$ware}? and $buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                <continue/>
              </do_if>
              <do_if value="$gtlsScanBuyer? and @$gtlsScanBuyer.exists">
                <find_buy_offer wares="$ware" buyer="$gtlsScanBuyer" space="$space" result="$playerBuyOffers" multiple="true">
                  <offeramount min="1"/>
                </find_buy_offer>
              </do_if>
              <do_else>
                <find_buy_offer wares="$ware" space="$space" result="$playerBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                    <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <offeramount min="1"/>
                </find_buy_offer>
              </do_else>
              <do_if value="$playerBuyOffers? and $playerBuyOffers.count gt 0">
                <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                  <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
                </do_if>
                <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                  <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
                </do_if>
                <do_if value="not $buyOffersPerWare.{$ware}?">
                  <set_value name="$buyOffersPerWare.{$ware}" exact="0"/>
                </do_if>
                <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$ware}?">
                  <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$ware}" exact="0"/>
                </do_if>
                <do_all exact="$playerBuyOffers.count" counter="$oi">
                  <set_value name="$offer" exact="$playerBuyOffers.{$oi}"/>
                  <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                  <do_if value="$isBuildStorageBuyer">
                    <do_if value="not $gtlsBuildStorageReservePerWare?">
                      <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$ware} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                      <continue/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="$buyOffersPerWare.{$ware} ge $gtlsMaxOffersPerWare">
                      <break/>
                    </do_if>
                  </do_else>
                  <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                    <continue/>
                  </do_if>
                  <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                    <continue/>
                  </do_if>
                  <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                    <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                    <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                    <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                      <do_if value="@$gtlsBuyerObj.isplayerowned">
                        <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                      </do_if>
                      <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                        <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                      </do_elseif>
                    </do_if>
                    <do_if value="not $gtlsPlayerBuyerOk">
                      <continue/>
                    </do_if>
                  </do_if>
                  <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                    <continue/>
                  </do_if>
                  <do_if value="$isBuildStorageBuyer">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$ware}" operation="add"/>
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                  </do_if>
                  <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                  <append_to_list name="$buyOffers" exact="$offer"/>
                  <set_value name="$buyOffersPerWare.{$ware}" operation="add"/>
                  <set_value name="$playerBuyOffersAdded" operation="add"/>
                </do_all>
              </do_if>
            </do_all>
          </do_else>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield after player buy-offer supplement"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': player buy-offer supplement added=' + $playerBuyOffersAdded + ' (ignoreTradeRules=' + $gtlsIgnoreTradeRules + ', ignoreCargoNeed=' + $gtlsIgnoreTradeRulesPlayerBuyOffersRequireCargoNeed + ')'" chance="$gtlsDebugchance"/>
      </do_if>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>
      <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
        <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
      </do_if>
      <do_if value="not $gtlsBuildStorageReservePerWare?">
        <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
      </do_if>
      <!-- Score-aware cap: flatten per-ware top-N tables into the buy-offer result list. -->
      <do_if value="$gtlsUseScoreAwareBuyCap">
        <set_value name="$buyOffers" exact="[]"/>
        <set_value name="$buyOffersPerWare" exact="table[]"/>
        <set_value name="$gtlsFinalizeWareKeys" exact="$gtlsTopBuyOffersPerWare.keys.list"/>
        <do_all exact="$gtlsFinalizeWareKeys.count" counter="$gtlsFwi">
          <set_value name="$gtlsFinalizeWare" exact="$gtlsFinalizeWareKeys.{$gtlsFwi}"/>
          <set_value name="$gtlsFinalizeOffers" exact="$gtlsTopBuyOffersPerWare.{$gtlsFinalizeWare}"/>
          <do_if value="$gtlsFinalizeOffers? and $gtlsFinalizeOffers.count gt 0">
            <do_all exact="$gtlsFinalizeOffers.count" counter="$gtlsFoi">
              <append_to_list name="$buyOffers" exact="$gtlsFinalizeOffers.{$gtlsFoi}"/>
            </do_all>
            <set_value name="$buyOffersPerWare.{$gtlsFinalizeWare}" exact="$gtlsFinalizeOffers.count"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': score-aware buy cap finalized candidatesSeen=' + $gtlsScoreAwareCandidatesSeen + ' retained=' + $buyOffers.count + ' wares=' + $gtlsFinalizeWareKeys.count" chance="$gtlsDebugchance"/>
      </do_if>
      <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buy-offers collected=' + $buyOffers.count + ' (buyPriceMin=' + $gtlsBuyPriceMin + ', buildStorageBuyOffers=' + $gtlsBuildStorageBuyOffersAdded + ', reservePerWare=' + $gtlsBuildStorageReservePerWare + (if $gtlsUseScoreAwareBuyCap then ', scoreAwareCap=true' else '') + ')'" chance="$gtlsDebugchance"/>
      <!-- Demand-led supplier scan (MK4 S4): derive ware basket from collected buy offers, then collect sell offers for those wares only. -->
      <do_if value="this.$gtlsDemandLedSupplierScan? and this.$gtlsDemandLedSupplierScan and $gtlsSearchMode == 'buy_and_sell' and not this.$gtlsDemandLedSellDone?">
        <create_list name="$gtlsDemandWareBasket"/>
        <set_value name="$gtlsDemandWareSeen" exact="table[]"/>
        <do_all exact="$buyOffers.count" counter="$dlwi">
          <set_value name="$dlwo" exact="$buyOffers.{$dlwi}"/>
          <set_value name="$dlww" exact="@$dlwo.ware"/>
          <do_if value="$dlww? and not $gtlsDemandWareSeen.{$dlww}?">
            <set_value name="$gtlsDemandWareSeen.{$dlww}" exact="true"/>
            <append_to_list name="$gtlsDemandWareBasket" exact="$dlww"/>
          </do_if>
        </do_all>
        <set_value name="$gtlsWareBasket" exact="$gtlsDemandWareBasket"/>
        <set_value name="$gtlsUseAllWares" exact="false"/>
        <set_value name="this.$gtlsDemandLedSellDone" exact="true"/>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': demand-led supplier scan: demandWares=' + $gtlsDemandWareBasket.count + ' from buyOffers=' + $buyOffers.count" chance="$gtlsDebugchance"/>
        <do_if value="global.$GT_LiveSearchScratch? and global.$GT_LiveSearchScratch.{$gtlsShip}?">
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$WareBasket" exact="$gtlsWareBasket"/>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$UseAllWares" exact="$gtlsUseAllWares"/>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$DemandLedSupplierScan" exact="this.$gtlsDemandLedSupplierScan"/>
          <set_value name="global.$GT_LiveSearchScratch.{$gtlsShip}.$DemandLedSellDone" exact="true"/>
        </do_if>
        <resume label="gtls_collect_sell_offers"/>
      </do_if>
      <!-- Normalize priority wares before first use to avoid null .count lookups
           on resumed/search-resume contexts. -->
      <do_if value="not $gtlsPriorityWares? or $gtlsPriorityWares == null">
        <set_value name="$gtlsPriorityWares" exact="[]"/>
      </do_if>
      <set_value name="$priorityWaresCount" exact="$gtlsPriorityWares.count"/>
      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           Explicit priority-ware pass: ensures MK3 priority wares enter the
           tradeable set even if they were omitted from the main search results
           (e.g. engine limits, rare wares). If no offers found, ship still
           trades other wares; scoring will pick the best available.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="$priorityWaresCount gt 0 and $gtlsSearchMode == 'buy_and_sell'">
        <set_value name="$pwSellBefore" exact="$sellOffers.count"/>
        <set_value name="$pwBuyBefore" exact="$buyOffers.count"/>
        <set_value name="$pwNames" exact="''"/>
        <do_all exact="$priorityWaresCount" counter="$pn">
          <set_value name="$pnw" exact="$gtlsPriorityWares.{$pn}"/>
          <set_value name="$pwNames" exact="$pwNames + (if $pn gt 1 then ', ' else '') + (if $pnw? and $pnw != null then @$pnw.name else '?')"/>
        </do_all>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority-ware pass: searching ' + $priorityWaresCount + ' wares: [' + $pwNames + '] allowIllegal=' + $gtlsAllowIllegal" chance="100"/>
        </do_if>
        <do_all exact="$priorityWaresCount" counter="$pwi">
          <set_value name="$pw" exact="$gtlsPriorityWares.{$pwi}"/>
          <do_if value="not $pw? or $pw == null">
            <continue/>
          </do_if>
          <do_if value="not $gtlsAllowIllegal and $pw.illegal">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority ware ' + (if $pw? and $pw != null then @$pw.name else '?') + ' SKIPPED (illegal, allowIllegal=false)'" chance="100"/>
            </do_if>
            <continue/>
          </do_if>
          <!-- Sell offers for this priority ware (ship buys) -->
          <do_if value="not $gtlsSkipSupplierScan and $gtlsBuySpaces? and $gtlsBuySpaces.count gt 0">
            <set_value name="$gtlsPwSellSkipCap" exact="$gtlsMaxOffersPerWare"/>
            <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
              <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
              </do_if>
              <do_if value="not $gtlsBuildStorageReservePerWare?">
                <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
              </do_if>
              <set_value name="$gtlsPwSellSkipCap" exact="$gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare + $gtlsBuildStorageReservePerWare"/>
            </do_if>
            <do_if value="not $sellOffersPerWare.{$pw}? or $sellOffersPerWare.{$pw} lt $gtlsPwSellSkipCap">
              <do_all exact="$gtlsBuySpaces.count" counter="$psi">
                <do_if value="not $gtYieldMs? or not $gtlsShip?">
                  <resume label="gtls_ensure_state"/>
                </do_if>
                <set_value name="$space" exact="$gtlsBuySpaces.{$psi}"/>
                <do_if value="$gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
                  <find_sell_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                    <match_seller tradesknownto="$gtlsShip.owner">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_seller>
                    <amount min="1"/>
                    <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_sell_offer>
                </do_if>
                <do_elseif value="$gtlsIncludeNpcSellOffers">
                  <find_sell_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                    <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player" negateownerfilter="true">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_seller>
                    <amount min="1"/>
                    <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_sell_offer>
                </do_elseif>
                <do_elseif value="$gtlsIncludePlayerSellOffers">
                  <find_sell_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundSellOffers" multiple="true">
                    <match_seller tradesknownto="$gtlsShip.owner" owner="faction.player">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_seller>
                    <amount min="1"/>
                    <relativeprice max="$gtlsSellPriceMax" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_sell_offer>
                </do_elseif>
                <do_if value="$foundSellOffers? and $foundSellOffers.count gt 0">
                  <do_if value="not $sellOffersPerWare.{$pw}?">
                    <set_value name="$sellOffersPerWare.{$pw}" exact="0"/>
                  </do_if>
                  <do_all exact="$foundSellOffers.count" counter="$oi">
                    <set_value name="$offer" exact="$foundSellOffers.{$oi}"/>
                    <set_value name="$isBuildStorageSellSupplier" exact="$offer.owner? and $offer.owner.isclass.buildstorage"/>
                    <set_value name="$isPlayerSellSupplier" exact="$offer.owner? and @$offer.owner.isplayerowned and not $isBuildStorageSellSupplier"/>
                    <do_if value="$isBuildStorageSellSupplier">
                      <do_if value="not $gtlsBuildStorageReservePerWare?">
                        <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                      </do_if>
                      <do_if value="$sellOffersPerWare.{$pw} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <continue/>
                      </do_if>
                    </do_if>
                    <do_elseif value="$isPlayerSellSupplier and $gtlsIncludePlayerSellOffers and $gtlsIncludeNpcSellOffers">
                      <do_if value="not $gtlsPlayerSupplierReservePerWare?">
                        <set_value name="$gtlsPlayerSupplierReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                      </do_if>
                      <do_if value="$sellOffersPerWare.{$pw} ge ($gtlsMaxOffersPerWare + $gtlsPlayerSupplierReservePerWare)">
                        <continue/>
                      </do_if>
                    </do_elseif>
                    <do_else>
                      <do_if value="$sellOffersPerWare.{$pw} ge $gtlsMaxOffersPerWare">
                        <break/>
                      </do_if>
                    </do_else>
                    <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="not $gtlsIncludePlayerSellOffers and $offer.owner? and @$offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="not $gtlsIncludeNpcSellOffers and (not $offer.owner? or not @$offer.owner.isplayerowned)">
                      <continue/>
                    </do_if>
                    <!-- MK4 supply: supplier unitprice must not exceed max customer buy price for this ware. -->
                    <do_if value="$gtlsRequirePlayerBuyOfferOwner and not $gtlsBypassPlayerSellerPricing">
                      <do_if value="this.$gtlsMaxBuyUnitPriceByWare? and this.$gtlsMaxBuyUnitPriceByWare.{$pw}? and $offer.unitprice gt this.$gtlsMaxBuyUnitPriceByWare.{$pw}">
                        <set_value name="this.$gtlsMk4PriceCapPrefilterSkipped" operation="add"/>
                        <continue/>
                      </do_if>
                    </do_if>
                    <append_to_list name="$sellOffers" exact="$offer"/>
                    <set_value name="$sellOffersPerWare.{$pw}" operation="add"/>
                  </do_all>
                </do_if>
                <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield priority-ware sell sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

              </do_all>
            </do_if>
          </do_if>
          <!-- Buy offers for this priority ware (ship sells) -->
          <do_if value="$gtlsSellSpaces? and $gtlsSellSpaces.count gt 0">
            <do_if value="not $gtlsBuildStorageReservePerWare?">
              <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
            </do_if>
            <do_if value="not $buyOffersPerWare.{$pw}? or $buyOffersPerWare.{$pw} lt ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
              <do_all exact="$gtlsSellSpaces.count" counter="$psi">
                <do_if value="not $gtYieldMs? or not $gtlsShip?">
                  <resume label="gtls_ensure_state"/>
                </do_if>
                <set_value name="$space" exact="$gtlsSellSpaces.{$psi}"/>
                <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                  <find_buy_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                    <match_buyer tradesknownto="$gtlsShip.owner" owner="faction.player">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$gtlsShip"/>
                    <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer wares="$pw" tradepartner="$gtlsShip" space="$space" result="$foundBuyOffers" multiple="true">
                    <match_buyer tradesknownto="$gtlsShip.owner">
                      <match_relation_to object="$gtlsShip" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$gtlsShip.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$gtlsShip"/>
                    <relativeprice min="$gtlsBuyPriceMin" tradepartner="if $gtlsShip.isplayerowned then $gtlsShip else null"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$foundBuyOffers? and $foundBuyOffers.count gt 0">
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare" exact="table[]"/>
                  </do_if>
                  <do_if value="not $gtlsBuildStorageBuyOffersAdded?">
                    <set_value name="$gtlsBuildStorageBuyOffersAdded" exact="0"/>
                  </do_if>
                  <do_if value="not $buyOffersPerWare.{$pw}?">
                    <set_value name="$buyOffersPerWare.{$pw}" exact="0"/>
                  </do_if>
                  <do_if value="not $gtlsBuyBuildStorageOffersPerWare.{$pw}?">
                    <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$pw}" exact="0"/>
                  </do_if>
                  <do_all exact="$foundBuyOffers.count" counter="$oi">
                    <set_value name="$offer" exact="$foundBuyOffers.{$oi}"/>
                    <set_value name="$isBuildStorageBuyer" exact="$offer.owner? and $offer.owner.isplayerowned and $offer.owner.isclass.buildstorage"/>
                    <do_if value="$isBuildStorageBuyer">
                      <do_if value="not $gtlsBuildStorageReservePerWare?">
                        <set_value name="$gtlsBuildStorageReservePerWare" exact="[1, [4, $gtlsMaxOffersPerWare].min].max"/>
                      </do_if>
                      <do_if value="$buyOffersPerWare.{$pw} ge ($gtlsMaxOffersPerWare + $gtlsBuildStorageReservePerWare)">
                        <continue/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="$buyOffersPerWare.{$pw} ge $gtlsMaxOffersPerWare">
                        <break/>
                      </do_if>
                    </do_else>
                    <do_if value="$gtlsOwnerFilter == 'npc_only' and $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsOwnerFilter == 'player_only' and not $offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsExcludePlayerBuyers and $offer.owner? and @$offer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsRequirePlayerBuyOfferOwner">
                      <set_value name="$gtlsPlayerBuyerOk" exact="false"/>
                      <set_value name="$gtlsBuyerObj" exact="if $offer.buyer? then @$offer.buyer else (if $offer.owner? then @$offer.owner else null)"/>
                      <do_if value="$gtlsBuyerObj? and @$gtlsBuyerObj.exists">
                        <do_if value="@$gtlsBuyerObj.isplayerowned">
                          <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                        </do_if>
                        <do_elseif value="$gtlsBuyerObj.isclass.buildstorage and $gtlsBuyerObj.base? and @$gtlsBuyerObj.base.isplayerowned">
                          <set_value name="$gtlsPlayerBuyerOk" exact="true"/>
                        </do_elseif>
                      </do_if>
                      <do_if value="not $gtlsPlayerBuyerOk">
                        <continue/>
                      </do_if>
                    </do_if>
                    <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                      <continue/>
                    </do_if>
                    <do_if value="$isBuildStorageBuyer">
                      <set_value name="$gtlsBuyBuildStorageOffersPerWare.{$pw}" operation="add"/>
                      <set_value name="$gtlsBuildStorageBuyOffersAdded" operation="add"/>
                    </do_if>
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$pw}" operation="add"/>
                  </do_all>
                </do_if>
                <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield priority-ware buy sector"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

              </do_all>
            </do_if>
          </do_if>
          <set_value name="$pwSellCount" exact="if $sellOffersPerWare.{$pw}? then $sellOffersPerWare.{$pw} else 0"/>
          <set_value name="$pwBuyCount" exact="if $buyOffersPerWare.{$pw}? then $buyOffersPerWare.{$pw} else 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority ware ' + (if $pw? and $pw != null then @$pw.name else '?') + ': sellOffers=' + $pwSellCount + ' buyOffers=' + $pwBuyCount" chance="100"/>
          </do_if>
          <wait exact="if global.$GT_LiveSearchScratch? and $ship? and global.$GT_LiveSearchScratch.{$ship}.$YieldMs? then global.$GT_LiveSearchScratch.{$ship}.$YieldMs * 1ms else 1ms" comment="Yield priority-ware"/>
      <do_if value="not $gtYieldMs? or not $gtlsShip?">
        <resume label="gtls_ensure_state"/>
      </do_if>

        </do_all>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': priority-ware pass complete: added sellOffers=' + ($sellOffers.count - $pwSellBefore) + ' buyOffers=' + ($buyOffers.count - $pwBuyBefore) + ' (total sell=' + $sellOffers.count + ' buy=' + $buyOffers.count + ')'" chance="100"/>
        </do_if>
      </do_if>
      <!-- MK4 build-storage-only: query buy offers per build-storage buyer (generic player
           buy-offer scans return station owners; construction demand is on buyer=buildstorage).
           Enumerate via player station.buildstorage (vanilla trade.station.xml pattern) plus
           standalone class.buildstorage objects; BS demand may exist without credits (excludeempty=false). -->
      <do_if value="(if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false) and not $gtlsUsePlayerStationDiscovery">
        <set_value name="$gtlsBsoDirectBuyAdded" exact="0"/>
        <set_value name="$gtlsBsoHasWareBasket" exact="$gtlsWareBasket? and $gtlsWareBasket.count gt 0"/>
        <set_value name="$gtlsBsoCoverageMax" exact="if $gtlsMaxDistanceSell? and $gtlsMaxDistanceSell gt 0 then $gtlsMaxDistanceSell else $gtlsMaxDistance"/>
        <set_value name="$gtlsBsoScanSpaces" exact="if $gtlsBuySpaces? and $gtlsBuySpaces.count gt 0 then $gtlsBuySpaces else $gtlsSellSpaces"/>
        <set_value name="$gtlsBsoStationsScanned" exact="0"/>
        <set_value name="$gtlsBsoBuyersFound" exact="0"/>
        <do_if value="$gtlsSearchMode != 'buy_only' and $gtlsBsoScanSpaces? and $gtlsBsoScanSpaces.count gt 0">
          <set_value name="$gtlsBsoSeenBuyers" exact="table[]"/>
          <do_all exact="$gtlsBsoScanSpaces.count" counter="$gtlsBsoPsi">
            <do_if value="not $gtYieldMs? or not $gtlsShip?">
              <resume label="gtls_ensure_state"/>
            </do_if>
            <set_value name="$gtlsBsoSpace" exact="$gtlsBsoScanSpaces.{$gtlsBsoPsi}"/>
            <do_if value="not $gtlsBsoSpace? or not @$gtlsBsoSpace.exists">
              <continue/>
            </do_if>
            <find_station name="$gtlsBsoStations" space="$gtlsBsoSpace" checkoperational="true" multiple="true"/>
            <do_if value="$gtlsBsoStations? and $gtlsBsoStations.count gt 0">
              <do_all exact="$gtlsBsoStations.count" counter="$gtlsBsoSti">
                <set_value name="$gtlsBsoStation" exact="$gtlsBsoStations.{$gtlsBsoSti}"/>
                <set_value name="$gtlsBsoStationsScanned" operation="add"/>
                <do_if value="not $gtlsBsoStation? or not @$gtlsBsoStation.exists or not @$gtlsBsoStation.isplayerowned">
                  <continue/>
                </do_if>
                <set_value name="$gtlsBsoBuyer" exact="null"/>
                <do_if value="$gtlsBsoStation.buildstorage? and $gtlsBsoStation.buildstorage.exists">
                  <set_value name="$gtlsBsoBuyer" exact="$gtlsBsoStation.buildstorage"/>
                </do_if>
                <do_elseif value="@$gtlsBsoStation.isclass.buildstorage">
                  <set_value name="$gtlsBsoBuyer" exact="$gtlsBsoStation"/>
                </do_elseif>
                <do_if value="not $gtlsBsoBuyer? or not @$gtlsBsoBuyer.exists or $gtlsBsoSeenBuyers.{$gtlsBsoBuyer}?">
                  <continue/>
                </do_if>
                <set_value name="$gtlsBsoSeenBuyers.{$gtlsBsoBuyer}" exact="true"/>
                <set_value name="$gtlsBsoBuyersFound" operation="add"/>
                <do_if value="$gtlsIgnoreTradeRules">
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <amount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1" tradepartner="$gtlsShip"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$gtlsBsoOffers? and $gtlsBsoOffers.count gt 0">
                  <do_all exact="$gtlsBsoOffers.count" counter="$gtlsBsoBi">
                    <set_value name="$offer" exact="$gtlsBsoOffers.{$gtlsBsoBi}"/>
                    <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and $offer.owner? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                      <continue/>
                    </do_if>
                    <set_value name="$offerWare" exact="@$offer.ware"/>
                    <do_if value="not $offerWare?">
                      <continue/>
                    </do_if>
                    <do_if value="not $gtlsBsoHasWareBasket">
                      <set_value name="$offerWareInBasket" exact="true"/>
                    </do_if>
                    <do_else>
                      <set_value name="$offerWareInBasket" exact="false"/>
                      <do_all exact="$gtlsWareBasket.count" counter="$gtlsBsoWbi">
                        <do_if value="$gtlsWareBasket.{$gtlsBsoWbi} == $offerWare">
                          <set_value name="$offerWareInBasket" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_else>
                    <do_if value="not $offerWareInBasket">
                      <continue/>
                    </do_if>
                    <do_if value="not $buyOffersPerWare.{$offerWare}?">
                      <set_value name="$buyOffersPerWare.{$offerWare}" exact="0"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$offerWare}" operation="add"/>
                    <set_value name="$gtlsBsoDirectBuyAdded" operation="add"/>
                  </do_all>
                </do_if>
              </do_all>
            </do_if>
            <find_object name="$gtlsBsoObjects" class="class.buildstorage" space="$gtlsBsoSpace" owner="faction.player" multiple="true"/>
            <do_if value="$gtlsBsoObjects? and $gtlsBsoObjects.count gt 0">
              <do_all exact="$gtlsBsoObjects.count" counter="$gtlsBsoOi">
                <set_value name="$gtlsBsoBuyer" exact="$gtlsBsoObjects.{$gtlsBsoOi}"/>
                <do_if value="not $gtlsBsoBuyer? or not @$gtlsBsoBuyer.exists or $gtlsBsoSeenBuyers.{$gtlsBsoBuyer}?">
                  <continue/>
                </do_if>
                <set_value name="$gtlsBsoSeenBuyers.{$gtlsBsoBuyer}" exact="true"/>
                <set_value name="$gtlsBsoBuyersFound" operation="add"/>
                <do_if value="$gtlsIgnoreTradeRules">
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <amount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$gtlsBsoBuyer" tradepartner="$gtlsShip" space="$gtlsBsoSpace" result="$gtlsBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1" tradepartner="$gtlsShip"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$gtlsBsoOffers? and $gtlsBsoOffers.count gt 0">
                  <do_all exact="$gtlsBsoOffers.count" counter="$gtlsBsoBi">
                    <set_value name="$offer" exact="$gtlsBsoOffers.{$gtlsBsoBi}"/>
                    <do_if value="not $gtlsAllowIllegal and $offer.ware? and @$offer.ware.illegal">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsIgnoreMK1Supply and global.$GT_MK1SuppliedStations? and $offer.owner? and global.$GT_MK1SuppliedStations.{$offer.owner}?">
                      <continue/>
                    </do_if>
                    <do_if value="$gtlsSeenBuyOffers.{$offer}?">
                      <continue/>
                    </do_if>
                    <set_value name="$offerWare" exact="@$offer.ware"/>
                    <do_if value="not $offerWare?">
                      <continue/>
                    </do_if>
                    <do_if value="not $gtlsBsoHasWareBasket">
                      <set_value name="$offerWareInBasket" exact="true"/>
                    </do_if>
                    <do_else>
                      <set_value name="$offerWareInBasket" exact="false"/>
                      <do_all exact="$gtlsWareBasket.count" counter="$gtlsBsoWbi">
                        <do_if value="$gtlsWareBasket.{$gtlsBsoWbi} == $offerWare">
                          <set_value name="$offerWareInBasket" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_else>
                    <do_if value="not $offerWareInBasket">
                      <continue/>
                    </do_if>
                    <do_if value="not $buyOffersPerWare.{$offerWare}?">
                      <set_value name="$buyOffersPerWare.{$offerWare}" exact="0"/>
                    </do_if>
                    <do_if value="$buyOffersPerWare.{$offerWare} ge $gtlsMaxOffersPerWare">
                      <continue/>
                    </do_if>
                    <set_value name="$gtlsSeenBuyOffers.{$offer}" exact="true"/>
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$offerWare}" operation="add"/>
                    <set_value name="$gtlsBsoDirectBuyAdded" operation="add"/>
                  </do_all>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $gtYieldMs? or not $gtlsShip?">
              <resume label="gtls_ensure_state"/>
            </do_if>
          </do_all>
        </do_if>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buildStorageOnly direct BS buy scan added=' + $gtlsBsoDirectBuyAdded + ' buyers=' + $gtlsBsoBuyersFound + ' stationsScanned=' + $gtlsBsoStationsScanned + ' coverageMax=' + $gtlsBsoCoverageMax + 'j'" chance="100"/>
      </do_if>
      <!-- MK4-2 / legacy build-storage-only: drop non-BS buyers, out-of-coverage BS buyers, and BS supplier sell offers. -->
      <do_if value="(if $gtlsMk42BuildStorageOnlyMode? then $gtlsMk42BuildStorageOnlyMode else false) or (if $gtlsMk4BuildStorageOnlyMode? then $gtlsMk4BuildStorageOnlyMode else false)">
        <set_value name="$gtlsBsoCoverageMax" exact="if $gtlsMaxDistanceSell? and $gtlsMaxDistanceSell gt 0 then $gtlsMaxDistanceSell else $gtlsMaxDistance"/>
        <create_list name="$sellOffersBsoFiltered"/>
        <do_all exact="$sellOffers.count" counter="$gtlsBsoSi">
          <set_value name="$gtlsBsoSellOffer" exact="$sellOffers.{$gtlsBsoSi}"/>
          <set_value name="$gtlsBsoSeller" exact="if $gtlsBsoSellOffer.seller? then @$gtlsBsoSellOffer.seller else (if $gtlsBsoSellOffer.owner? then @$gtlsBsoSellOffer.owner else null)"/>
          <do_if value="not $gtlsBsoSeller? or not @$gtlsBsoSeller.isclass.buildstorage">
            <append_to_list name="$sellOffersBsoFiltered" exact="$gtlsBsoSellOffer"/>
          </do_if>
        </do_all>
        <set_value name="$sellOffers" exact="$sellOffersBsoFiltered"/>
        <create_list name="$buyOffersBsoFiltered"/>
        <do_all exact="$buyOffers.count" counter="$gtlsBsoBi">
          <set_value name="$gtlsBsoBuyOffer" exact="$buyOffers.{$gtlsBsoBi}"/>
          <set_value name="$gtlsBsoBuyer" exact="if $gtlsBsoBuyOffer.buyer? then @$gtlsBsoBuyOffer.buyer else (if $gtlsBsoBuyOffer.owner? then @$gtlsBsoBuyOffer.owner else null)"/>
          <do_if value="$gtlsBsoBuyer? and @$gtlsBsoBuyer.isclass.buildstorage">
            <set_value name="$gtlsBsoInScope" exact="false"/>
            <set_value name="$gtlsBsoBuyerDist" exact="if $gtlsHomeSector? and $gtlsBsoBuyer.sector? then $gtlsHomeSector.gatedistance.{$gtlsBsoBuyer.sector} else -1"/>
            <do_if value="$gtlsBsoBuyerDist ge 0 and ($gtlsBsoCoverageMax le 0 or $gtlsBsoBuyerDist le $gtlsBsoCoverageMax)">
              <set_value name="$gtlsBsoInScope" exact="true"/>
            </do_if>
            <do_if value="$gtlsBsoInScope">
              <append_to_list name="$buyOffersBsoFiltered" exact="$gtlsBsoBuyOffer"/>
            </do_if>
          </do_if>
        </do_all>
        <set_value name="$buyOffers" exact="$buyOffersBsoFiltered"/>
        <set_value name="$buyOffersPerWare" exact="table[]"/>
        <do_all exact="$buyOffers.count" counter="$gtlsBsoPwIdx">
          <set_value name="$gtlsBsoPwOffer" exact="$buyOffers.{$gtlsBsoPwIdx}"/>
          <set_value name="$gtlsBsoPwWare" exact="if $gtlsBsoPwOffer.ware? then @$gtlsBsoPwOffer.ware else null"/>
          <do_if value="$gtlsBsoPwWare?">
            <do_if value="not $buyOffersPerWare.{$gtlsBsoPwWare}?">
              <set_value name="$buyOffersPerWare.{$gtlsBsoPwWare}" exact="0"/>
            </do_if>
            <set_value name="$buyOffersPerWare.{$gtlsBsoPwWare}" operation="add"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': buildStorageOnly offer filter sell=' + $sellOffers.count + ' buy=' + $buyOffers.count" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- MK4-2 Â§7.2: classify-at-ingest â€” filter buy offers by enabled class sliders; build buyByClass buckets. -->
      <set_value name="$buyByClass" exact="table[]"/>
      <do_if value="$gtlsMk42Priorities?">
        <create_list name="$buyOffersMk42Filtered"/>
        <do_all exact="$buyOffers.count" counter="$mk42bi">
          <set_value name="$mk42BuyOffer" exact="$buyOffers.{$mk42bi}"/>
          <set_value name="$mk42Buyer" exact="if $mk42BuyOffer.buyer? then @$mk42BuyOffer.buyer else (if $mk42BuyOffer.owner? then @$mk42BuyOffer.owner else null)"/>
          <do_if value="$mk42Buyer? and $mk42Buyer.exists">
            <set_value name="$mk42LiveClass" exact="'None'"/>
            <set_value name="$mk42LiveMult" exact="0"/>
            <do_if value="@$mk42Buyer.isclass.buildstorage and @$mk42Buyer.isplayerowned">
              <set_value name="$mk42LiveClass" exact="'Buildstorage'"/>
            </do_if>
            <do_elseif value="@$mk42Buyer.isclass.station and @$mk42Buyer.isplayerowned">
              <set_value name="$mk42LiveClass" exact="'Stations'"/>
            </do_elseif>
            <do_elseif value="@$mk42Buyer.isclass.ship and @$mk42Buyer.isplayerowned and @$mk42Buyer.type == shiptype.carrier">
              <set_value name="$mk42LiveClass" exact="'Carrier'"/>
            </do_elseif>
            <do_elseif value="@$mk42Buyer.isclass.ship and @$mk42Buyer.isplayerowned and @$mk42Buyer.primarypurpose == purpose.auxiliary">
              <set_value name="$mk42LiveClass" exact="'Aux'"/>
            </do_elseif>
            <do_elseif value="@$mk42Buyer.isclass.buildstorage and $mk42Buyer.base? and @$mk42Buyer.base.isplayerowned">
              <set_value name="$mk42LiveClass" exact="'Buildstorage'"/>
            </do_elseif>
            <do_if value="$mk42LiveClass == 'Buildstorage'">
              <set_value name="$mk42LiveMult" exact="if $gtlsMk42Priorities.$Buildstorage? then $gtlsMk42Priorities.$Buildstorage else 0"/>
            </do_if>
            <do_elseif value="$mk42LiveClass == 'Stations'">
              <set_value name="$mk42LiveMult" exact="if $gtlsMk42Priorities.$Stations? then $gtlsMk42Priorities.$Stations else 0"/>
            </do_elseif>
            <do_elseif value="$mk42LiveClass == 'Aux'">
              <set_value name="$mk42LiveMult" exact="if $gtlsMk42Priorities.$Aux? then $gtlsMk42Priorities.$Aux else 0"/>
            </do_elseif>
            <do_elseif value="$mk42LiveClass == 'Carrier'">
              <set_value name="$mk42LiveMult" exact="if $gtlsMk42Priorities.$Carrier? then $gtlsMk42Priorities.$Carrier else 0"/>
            </do_elseif>
            <do_if value="$mk42LiveClass != 'None' and $mk42LiveMult gt 0">
              <append_to_list name="$buyOffersMk42Filtered" exact="$mk42BuyOffer"/>
              <do_if value="$mk42LiveClass == 'Buildstorage'">
                <do_if value="not $buyByClass.$Buildstorage?">
                  <create_list name="$buyByClass.$Buildstorage"/>
                </do_if>
                <append_to_list name="$buyByClass.$Buildstorage" exact="$mk42BuyOffer"/>
              </do_if>
              <do_elseif value="$mk42LiveClass == 'Stations'">
                <do_if value="not $buyByClass.$Stations?">
                  <create_list name="$buyByClass.$Stations"/>
                </do_if>
                <append_to_list name="$buyByClass.$Stations" exact="$mk42BuyOffer"/>
              </do_elseif>
              <do_elseif value="$mk42LiveClass == 'Aux'">
                <do_if value="not $buyByClass.$Aux?">
                  <create_list name="$buyByClass.$Aux"/>
                </do_if>
                <append_to_list name="$buyByClass.$Aux" exact="$mk42BuyOffer"/>
              </do_elseif>
              <do_elseif value="$mk42LiveClass == 'Carrier'">
                <do_if value="not $buyByClass.$Carrier?">
                  <create_list name="$buyByClass.$Carrier"/>
                </do_if>
                <append_to_list name="$buyByClass.$Carrier" exact="$mk42BuyOffer"/>
              </do_elseif>
            </do_if>
          </do_if>
        </do_all>
        <set_value name="$buyOffers" exact="$buyOffersMk42Filtered"/>
        <set_value name="$buyOffersPerWare" exact="table[]"/>
        <do_all exact="$buyOffers.count" counter="$mk42pwIdx">
          <set_value name="$mk42pwOffer" exact="$buyOffers.{$mk42pwIdx}"/>
          <set_value name="$mk42pwWare" exact="if $mk42pwOffer.ware? then @$mk42pwOffer.ware else null"/>
          <do_if value="$mk42pwWare?">
            <do_if value="not $buyOffersPerWare.{$mk42pwWare}?">
              <set_value name="$buyOffersPerWare.{$mk42pwWare}" exact="0"/>
            </do_if>
            <set_value name="$buyOffersPerWare.{$mk42pwWare}" operation="add"/>
          </do_if>
        </do_all>
        <set_value name="$mk42BuyBucketCount" exact="0"/>
        <do_if value="$buyByClass.$Buildstorage?"><set_value name="$mk42BuyBucketCount" exact="$mk42BuyBucketCount + $buyByClass.$Buildstorage.count"/></do_if>
        <do_if value="$buyByClass.$Stations?"><set_value name="$mk42BuyBucketCount" exact="$mk42BuyBucketCount + $buyByClass.$Stations.count"/></do_if>
        <do_if value="$buyByClass.$Aux?"><set_value name="$mk42BuyBucketCount" exact="$mk42BuyBucketCount + $buyByClass.$Aux.count"/></do_if>
        <do_if value="$buyByClass.$Carrier?"><set_value name="$mk42BuyBucketCount" exact="$mk42BuyBucketCount + $buyByClass.$Carrier.count"/></do_if>
        <debug_text text="'[GT-LiveSearch] ' + $gtlsShip.idcode + ': MK4-2 class filter buy=' + $buyOffers.count + ' bucketOffers=' + $mk42BuyBucketCount" chance="$gtlsDebugchance"/>
      </do_if>
      <!-- No blind total cap â€” per-ware limits above ensure manageable totals.
           With ~50 wares x 20 offers/ware = ~1000 offers max per side.
           The matching step (lib.gt.tradematch) handles O(sell*buy) by ware-skipping. -->
      <return value="table[
        $SellOffers = $sellOffers,
        $BuyOffers = $buyOffers,
        $SellOfferCount = $sellOffers.count,
        $BuyOfferCount = $buyOffers.count,
        $SellWaresFound = $sellOffersPerWare.keys.count,
        $BuyWaresFound = $buyOffersPerWare.keys.count,
        $BuyByClass = if $buyByClass? then $buyByClass else table[]
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.mk42.offer.filters" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="offer" default="null"/>
    <param name="wareBasket" default="[]"/>
    <param name="allowIllegal" default="false"/>
    <param name="ignoreMK1Supply" default="false"/>
    <param name="priorities" default="table[]" comment="MK4-2 class sliders for delivery customer on buy offers"/>
    <param name="isBuyOffer" default="true" comment="When true, offer.owner is delivery customer"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$pass" exact="true"/>
      <set_value name="$reason" exact="'ok'"/>
      <set_value name="$wareMatch" exact="false"/>
      <set_value name="$hasExplicitBasket" exact="false"/>

      <do_if value="not $offer? or not $offer.exists or not $offer.ware?">
        <set_value name="$pass" exact="false"/>
        <set_value name="$reason" exact="'invalid_offer'"/>
      </do_if>

      <do_if value="$pass and $wareBasket? and $wareBasket.count gt 0">
        <set_value name="$hasExplicitBasket" exact="true"/>
        <do_all exact="$wareBasket.count" counter="$wi">
          <do_if value="$wareBasket.{$wi} == $offer.ware">
            <set_value name="$wareMatch" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="not $wareMatch">
          <set_value name="$pass" exact="false"/>
          <set_value name="$reason" exact="'warebasket'"/>
        </do_if>
      </do_if>

      <do_if value="$pass and not $allowIllegal and not ($hasExplicitBasket and $wareMatch)">
        <do_if value="$offer.ware != null and @$offer.ware.illegal gt 0">
          <set_value name="$pass" exact="false"/>
          <set_value name="$reason" exact="'illegal'"/>
        </do_if>
      </do_if>

      <set_value name="$station" exact="null"/>
      <do_if value="$offer.owner?">
        <set_value name="$station" exact="$offer.owner"/>
      </do_if>

      <!-- MK4-2: class-at-0 reject on delivery customer (buy offers). -->
      <do_if value="$pass and $isBuyOffer and $station? and $priorities?">
        <run_script name="'lib.gt.mk42.classify'" result="$cls">
          <param name="customer" value="$station"/>
          <param name="priorities" value="$priorities"/>
        </run_script>
        <do_if value="not $cls.$Eligible? or not $cls.$Eligible">
          <set_value name="$pass" exact="false"/>
          <set_value name="$reason" exact="'mk42_class_disabled'"/>
        </do_if>
      </do_if>

      <do_if value="$pass and $station? and $ignoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$station}?">
        <set_value name="$pass" exact="false"/>
        <set_value name="$reason" exact="'mk1_supply'"/>
      </do_if>

      <return value="table[$Pass = $pass, $Reason = $reason, $WareMatch = $wareMatch]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.mk42.player.stations" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="homeSector" default="null"/>
    <param name="maxDistance" default="0" comment="Supplier coverage (pilot jump distance). 0 = unlimited."/>
    <param name="maxDistanceSell" default="0" comment="Delivery buyer coverage (jumpDistanceCoverage). 0 = use maxDistance."/>
    <param name="includePlayerSuppliers" default="true"/>
    <param name="debugchance" default="0"/>
    <param name="ship" default="null" comment="Optional idcode for debug logging."/>
  </params>
  <attention min="unknown">
    <actions>
      <create_list name="$buyersInRange"/>
      <create_list name="$suppliersInRange"/>
      <set_value name="$deliveryCoverageMax" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
      <set_value name="$supplierCoverageMax" exact="$maxDistance"/>
      <set_value name="$stationsFound" exact="0"/>
      <set_value name="$buyersSeen" exact="table[]"/>

      <do_if value="$homeSector? and @$homeSector.exists">
        <find_station_by_true_owner name="$allPlayerStations" faction="faction.player" space="player.galaxy" checkoperational="true" multiple="true"/>
        <do_if value="$allPlayerStations? and $allPlayerStations.count gt 0">
          <do_all exact="$allPlayerStations.count" counter="$psi">
            <set_value name="$pst" exact="$allPlayerStations.{$psi}"/>
            <do_if value="not $pst? or not @$pst.exists">
              <continue/>
            </do_if>
            <set_value name="$stationsFound" operation="add"/>
            <set_value name="$pstSector" exact="if $pst.sector? then @$pst.sector else null"/>
            <do_if value="not $pstSector? or not @$pstSector.exists">
              <continue/>
            </do_if>
            <set_value name="$pstGateDist" exact="$homeSector.gatedistance.{$pstSector}"/>
            <do_if value="$pstGateDist lt 0">
              <continue/>
            </do_if>
            <set_value name="$pstInDeliveryRange" exact="$deliveryCoverageMax le 0 or $pstGateDist le $deliveryCoverageMax"/>
            <set_value name="$pstInSupplierRange" exact="$supplierCoverageMax le 0 or $pstGateDist le $supplierCoverageMax"/>
            <do_if value="$pstInSupplierRange and $includePlayerSuppliers">
              <append_to_list name="$suppliersInRange" exact="$pst"/>
            </do_if>
            <do_if value="$pstInDeliveryRange">
              <do_if value="not $buyersSeen.{$pst}?">
                <set_value name="$buyersSeen.{$pst}" exact="true"/>
                <append_to_list name="$buyersInRange" exact="$pst"/>
              </do_if>
              <do_if value="$pst.buildstorage? and @$pst.buildstorage.exists and not $buyersSeen.{$pst.buildstorage}?">
                <set_value name="$buyersSeen.{$pst.buildstorage}" exact="true"/>
                <append_to_list name="$buyersInRange" exact="$pst.buildstorage"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <find_object name="$standaloneBuildStorages" class="class.buildstorage" space="player.galaxy" owner="faction.player" multiple="true"/>
        <do_if value="$standaloneBuildStorages? and $standaloneBuildStorages.count gt 0">
          <do_all exact="$standaloneBuildStorages.count" counter="$bsi">
            <set_value name="$bs" exact="$standaloneBuildStorages.{$bsi}"/>
            <do_if value="not $bs? or not @$bs.exists or $buyersSeen.{$bs}?">
              <continue/>
            </do_if>
            <set_value name="$bsSector" exact="if $bs.sector? then @$bs.sector else null"/>
            <do_if value="not $bsSector? or not @$bsSector.exists">
              <continue/>
            </do_if>
            <set_value name="$bsGateDist" exact="$homeSector.gatedistance.{$bsSector}"/>
            <do_if value="$bsGateDist lt 0">
              <continue/>
            </do_if>
            <do_if value="$deliveryCoverageMax le 0 or $bsGateDist le $deliveryCoverageMax">
              <set_value name="$buyersSeen.{$bs}" exact="true"/>
              <append_to_list name="$buyersInRange" exact="$bs"/>
            </do_if>
          </do_all>
        </do_if>
      </do_if>

      <do_if value="$debugchance gt 0 and $ship?">
        <debug_text text="'[GT-LiveSearch] ' + $ship.idcode + ': player-station discovery home=' + (if $homeSector? then @$homeSector.knownname else '?') + ' stations=' + $stationsFound + ' buyersInRange=' + $buyersInRange.count + ' suppliersInRange=' + $suppliersInRange.count + ' deliveryMax=' + $deliveryCoverageMax + 'j supplierMax=' + $supplierCoverageMax + 'j'" chance="$debugchance"/>
      </do_if>

      <return value="table[
        $BuyersInRange = $buyersInRange,
        $SuppliersInRange = $suppliersInRange,
        $DeliveryCoverageMax = $deliveryCoverageMax,
        $SupplierCoverageMax = $supplierCoverageMax
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- lib.gt.mk42.policy.resolve â€” MK4-2 priority sliders, prioSig, delivery-class policy (OPEN_GALAXYTRADER_MK4-2_SUPPLY_ORDER.md Â§3.1 / Â§4.3). -->
<aiscript name="lib.gt.mk42.policy.resolve" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="priorityBuildstorage" default="null"/>
    <param name="priorityStations" default="null"/>
    <param name="priorityAux" default="null"/>
    <param name="priorityCarrier" default="null"/>
    <param name="prioritywares" default="[]"/>
    <param name="priorityscoremultiplier" default="null"/>
    <param name="buyFromPlayer" default="null" comment="Player supplier priority slider (0-10); folded into prioSig so supplier-priority changes invalidate the per-ship cache view like delivery-class sliders"/>
    <param name="buyFromFaction" default="null" comment="Faction supplier priority slider (0-10); folded into prioSig"/>
    <param name="seedNullSliders" default="true" comment="When true, null/unset sliders get fresh-order defaults (Â§3.1.1a)"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$bs" exact="if $priorityBuildstorage? then $priorityBuildstorage else (if $seedNullSliders then 10 else 0)"/>
      <set_value name="$st" exact="if $priorityStations? then $priorityStations else (if $seedNullSliders then 8 else 0)"/>
      <set_value name="$ax" exact="if $priorityAux? then $priorityAux else 0"/>
      <set_value name="$cr" exact="if $priorityCarrier? then $priorityCarrier else 0"/>
      <set_value name="$seededNulls" exact="false"/>
      <do_if value="$seedNullSliders">
        <do_if value="not $priorityBuildstorage? or not $priorityStations? or not $priorityAux? or not $priorityCarrier?">
          <set_value name="$seededNulls" exact="true"/>
        </do_if>
      </do_if>

      <do_if value="$bs lt 0"><set_value name="$bs" exact="0"/></do_if>
      <do_if value="$bs gt 10"><set_value name="$bs" exact="10"/></do_if>
      <do_if value="$st lt 0"><set_value name="$st" exact="0"/></do_if>
      <do_if value="$st gt 10"><set_value name="$st" exact="10"/></do_if>
      <do_if value="$ax lt 0"><set_value name="$ax" exact="0"/></do_if>
      <do_if value="$ax gt 10"><set_value name="$ax" exact="10"/></do_if>
      <do_if value="$cr lt 0"><set_value name="$cr" exact="0"/></do_if>
      <do_if value="$cr gt 10"><set_value name="$cr" exact="10"/></do_if>

      <set_value name="$psm" exact="if $priorityscoremultiplier? then $priorityscoremultiplier else 1"/>
      <do_if value="$psm lt 1"><set_value name="$psm" exact="1"/></do_if>
      <do_if value="$psm gt 10"><set_value name="$psm" exact="10"/></do_if>

      <!-- Supplier sliders: default to the neutral 5 when unset so an order that never set them keeps a
           stable signature. Clamp 0-10. These do not gate delivery classes; they live in prioSig only so a
           change to player/faction supplier preference invalidates each ship's cached trade ranking. -->
      <set_value name="$sp" exact="if $buyFromPlayer? then $buyFromPlayer else 5"/>
      <set_value name="$sf" exact="if $buyFromFaction? then $buyFromFaction else 5"/>
      <do_if value="$sp lt 0"><set_value name="$sp" exact="0"/></do_if>
      <do_if value="$sp gt 10"><set_value name="$sp" exact="10"/></do_if>
      <do_if value="$sf lt 0"><set_value name="$sf" exact="0"/></do_if>
      <do_if value="$sf gt 10"><set_value name="$sf" exact="10"/></do_if>

      <set_value name="$priorities" exact="table[$Buildstorage = $bs, $Stations = $st, $Aux = $ax, $Carrier = $cr]"/>
      <set_value name="$enabledAny" exact="$bs gt 0 or $st gt 0 or $ax gt 0 or $cr gt 0"/>
      <set_value name="$noDeliveryTargets" exact="$bs == 0 and $st == 0 and $ax == 0 and $cr == 0"/>

      <!-- Canonical prioritywares: stable sort by ware id before stringifying (Â§4.3). -->
      <set_value name="$canonicalPw" exact="'0'"/>
      <do_if value="$prioritywares? and typeof $prioritywares == datatype.list and $prioritywares.count gt 0">
        <set_value name="$pwIds" exact="[]"/>
        <do_all exact="$prioritywares.count" counter="$pwi">
          <set_value name="$pw" exact="$prioritywares.{$pwi}"/>
          <do_if value="$pw? and $pw != null and $pw.id?">
            <append_to_list name="$pwIds" exact="@$pw.id"/>
          </do_if>
        </do_all>
        <do_if value="$pwIds.count gt 0">
          <sort_list list="$pwIds"/>
          <set_value name="$canonicalPw" exact="''"/>
          <do_all exact="$pwIds.count" counter="$pwi2">
            <set_value name="$canonicalPw" exact="$canonicalPw + (if $pwi2 gt 1 then ',' else '') + $pwIds.{$pwi2}"/>
          </do_all>
        </do_if>
      </do_if>

      <set_value name="$prioSig" exact="'BS=' + $bs + '|ST=' + $st + '|AX=' + $ax + '|CR=' + $cr + '|PSM=' + $psm + '|SP=' + $sp + '|SF=' + $sf + '|PW=' + $canonicalPw"/>

      <return value="table[
        $Priorities = $priorities,
        $PrioSig = $prioSig,
        $CanonicalPriorityWares = $canonicalPw,
        $PriorityScoreMultiplier = $psm,
        $Buildstorage = $bs,
        $Stations = $st,
        $Aux = $ax,
        $Carrier = $cr,
        $EnabledAny = $enabledAny,
        $NoDeliveryTargets = $noDeliveryTargets,
        $SeededNulls = $seededNulls
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- MK4-2 supply scoring: global batch norm (raw / maxRaw), linear class slider multiply.
     Close sliders (max/min mult lt 5): norm x mult - demand tips races (BS=5 ST=4).
     Wide gap (max/min mult ge 5): class tier dominates - all BS beat all ST at BS=10 ST=1. -->
<aiscript name="lib.gt.mk42.score.trades" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="tradeList" default="[]"/>
    <param name="priorities" default="table[]" comment="table[$Buildstorage, $Stations, $Aux, $Carrier] - when set, class mult is resolved from $CustomerClass for per-ship cache re-score"/>
    <param name="priorityWares" default="[]"/>
    <param name="priorityScoreMultiplier" default="1" comment="1=no ware bonus; 2-10 additive on normalised base"/>
    <param name="playerSupplierPriority" default="5" comment="buyFromPlayer slider (0-10); self-normalised supplier-side score weight"/>
    <param name="aiSupplierPriority" default="5" comment="buyFromFaction slider (0-10); self-normalised supplier-side score weight"/>
    <param name="distancePenalty" default="0.5" comment="Runtime multiplier (UI 0-100% converted by caller)"/>
    <param name="diversifyByWare" default="false"/>
    <param name="priorityFirstInDiversify" default="false"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>
      <create_list name="$sortedTrades"/>
      <set_value name="$safePriorityWares" exact="if $priorityWares? and $priorityWares != null then $priorityWares else []"/>
      <set_value name="$wareMult" exact="if $priorityScoreMultiplier? then $priorityScoreMultiplier else 1"/>
      <do_if value="$wareMult lt 1"><set_value name="$wareMult" exact="1"/></do_if>
      <do_if value="$wareMult gt 10"><set_value name="$wareMult" exact="10"/></do_if>

      <set_value name="$supPlayerPrio" exact="if $playerSupplierPriority? then $playerSupplierPriority else 5"/>
      <set_value name="$supAiPrio" exact="if $aiSupplierPriority? then $aiSupplierPriority else 5"/>
      <set_value name="$supPrioMax" exact="[$supPlayerPrio, $supAiPrio].max"/>

      <do_if value="not $tradeList? or $tradeList.count == 0">
        <wait exact="1ms"/>
        <return value="table[$Found = false, $BestTrade = null, $BestScore = 0, $SortedTrades = $sortedTrades]"/>
      </do_if>

      <set_value name="$maxRawGlobal" exact="0"/>
      <set_value name="$prioMultMin" exact="0"/>
      <set_value name="$prioMultMax" exact="0"/>
      <set_value name="$dominantClassTag" exact="'None'"/>
      <set_value name="$strictClassTier" exact="false"/>
      <set_value name="$classTierScale" exact="1000000"/>
      <do_if value="$priorities?">
        <set_value name="$prioScanMult" exact="if $priorities.$Buildstorage? then $priorities.$Buildstorage else 0"/>
        <do_if value="$prioScanMult gt 0">
          <do_if value="$prioMultMin == 0 or $prioScanMult lt $prioMultMin"><set_value name="$prioMultMin" exact="$prioScanMult"/></do_if>
          <do_if value="$prioScanMult gt $prioMultMax"><set_value name="$prioMultMax" exact="$prioScanMult"/><set_value name="$dominantClassTag" exact="'Buildstorage'"/></do_if>
        </do_if>
        <set_value name="$prioScanMult" exact="if $priorities.$Stations? then $priorities.$Stations else 0"/>
        <do_if value="$prioScanMult gt 0">
          <do_if value="$prioMultMin == 0 or $prioScanMult lt $prioMultMin"><set_value name="$prioMultMin" exact="$prioScanMult"/></do_if>
          <do_if value="$prioScanMult gt $prioMultMax"><set_value name="$prioMultMax" exact="$prioScanMult"/><set_value name="$dominantClassTag" exact="'Stations'"/></do_if>
        </do_if>
        <set_value name="$prioScanMult" exact="if $priorities.$Aux? then $priorities.$Aux else 0"/>
        <do_if value="$prioScanMult gt 0">
          <do_if value="$prioMultMin == 0 or $prioScanMult lt $prioMultMin"><set_value name="$prioMultMin" exact="$prioScanMult"/></do_if>
          <do_if value="$prioScanMult gt $prioMultMax"><set_value name="$prioMultMax" exact="$prioScanMult"/><set_value name="$dominantClassTag" exact="'Aux'"/></do_if>
        </do_if>
        <set_value name="$prioScanMult" exact="if $priorities.$Carrier? then $priorities.$Carrier else 0"/>
        <do_if value="$prioScanMult gt 0">
          <do_if value="$prioMultMin == 0 or $prioScanMult lt $prioMultMin"><set_value name="$prioMultMin" exact="$prioScanMult"/></do_if>
          <do_if value="$prioScanMult gt $prioMultMax"><set_value name="$prioMultMax" exact="$prioScanMult"/><set_value name="$dominantClassTag" exact="'Carrier'"/></do_if>
        </do_if>
        <do_if value="$prioMultMin gt 0 and $prioMultMax ge ($prioMultMin * 5)">
          <set_value name="$strictClassTier" exact="true"/>
        </do_if>
      </do_if>

      <!-- Pass 1: global max raw $baseSupplyScore across enabled classes (shared 0..1 scale for cross-class compare). -->
      <do_all exact="$tradeList.count" counter="$maxi">
        <set_value name="$maxTrade" exact="$tradeList.{$maxi}"/>
        <set_value name="$maxClassTag" exact="if $maxTrade.$CustomerClass? then @$maxTrade.$CustomerClass else 'None'"/>
        <set_value name="$maxRaw" exact="0"/>
        <do_if value="$maxClassTag != 'None'">
          <do_if value="$maxTrade.$baseSupplyScore?">
            <set_value name="$maxRaw" exact="$maxTrade.$baseSupplyScore"/>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$maxRaw" exact="if $maxTrade.$baseSupplyScore? then $maxTrade.$baseSupplyScore else (if $maxTrade.$Score? then $maxTrade.$Score else 0)"/>
        </do_else>
        <set_value name="$maxClassMult" exact="if $maxTrade.$ClassMultiplier? then $maxTrade.$ClassMultiplier else 1"/>
        <do_if value="$priorities? and $maxClassTag != 'None'">
          <do_if value="$maxClassTag == 'Buildstorage'">
            <set_value name="$maxClassMult" exact="if $priorities.$Buildstorage? then $priorities.$Buildstorage else 0"/>
          </do_if>
          <do_elseif value="$maxClassTag == 'Stations'">
            <set_value name="$maxClassMult" exact="if $priorities.$Stations? then $priorities.$Stations else 0"/>
          </do_elseif>
          <do_elseif value="$maxClassTag == 'Aux'">
            <set_value name="$maxClassMult" exact="if $priorities.$Aux? then $priorities.$Aux else 0"/>
          </do_elseif>
          <do_elseif value="$maxClassTag == 'Carrier'">
            <set_value name="$maxClassMult" exact="if $priorities.$Carrier? then $priorities.$Carrier else 0"/>
          </do_elseif>
        </do_if>
        <do_if value="$maxClassMult gt 0 and $maxRaw gt 0">
          <do_if value="$maxRaw gt $maxRawGlobal">
            <set_value name="$maxRawGlobal" exact="$maxRaw"/>
          </do_if>
        </do_if>
      </do_all>

      <!-- Pass 2: normBase = rawBase / maxRawGlobal; final = normBase x classMult (+ ware bonus on normBase). -->
      <do_all exact="$tradeList.count" counter="$i">
        <set_value name="$trade" exact="$tradeList.{$i}"/>
        <set_value name="$classTag" exact="if $trade.$CustomerClass? then @$trade.$CustomerClass else 'None'"/>
        <set_value name="$rawBase" exact="0"/>
        <do_if value="$classTag != 'None'">
          <do_if value="$trade.$baseSupplyScore?">
            <set_value name="$rawBase" exact="$trade.$baseSupplyScore"/>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$rawBase" exact="if $trade.$baseSupplyScore? then $trade.$baseSupplyScore else (if $trade.$Score? then $trade.$Score else 0)"/>
        </do_else>
        <set_value name="$classMult" exact="if $trade.$ClassMultiplier? then $trade.$ClassMultiplier else 1"/>
        <do_if value="$priorities? and $classTag != 'None'">
          <do_if value="$classTag == 'Buildstorage'">
            <set_value name="$classMult" exact="if $priorities.$Buildstorage? then $priorities.$Buildstorage else 0"/>
          </do_if>
          <do_elseif value="$classTag == 'Stations'">
            <set_value name="$classMult" exact="if $priorities.$Stations? then $priorities.$Stations else 0"/>
          </do_elseif>
          <do_elseif value="$classTag == 'Aux'">
            <set_value name="$classMult" exact="if $priorities.$Aux? then $priorities.$Aux else 0"/>
          </do_elseif>
          <do_elseif value="$classTag == 'Carrier'">
            <set_value name="$classMult" exact="if $priorities.$Carrier? then $priorities.$Carrier else 0"/>
          </do_elseif>
        </do_if>
        <do_if value="$classMult le 0 or $rawBase le 0">
          <continue/>
        </do_if>
        <set_value name="$normBase" exact="if $maxRawGlobal gt 0 then ($rawBase / ($maxRawGlobal * 1.0)) else 0"/>
        <do_if value="$normBase le 0">
          <continue/>
        </do_if>
        <set_value name="$typeScore" exact="$normBase * $classMult"/>
        <set_value name="$wareBonus" exact="0"/>
        <do_if value="$wareMult gt 1 and $trade.$Ware? and $safePriorityWares.count gt 0">
          <do_all exact="$safePriorityWares.count" counter="$pw">
            <do_if value="$safePriorityWares.{$pw} == $trade.$Ware">
              <set_value name="$wareBonus" exact="$normBase * ($wareMult - 1)"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <set_value name="$fineScore" exact="$typeScore + $wareBonus"/>
        <do_if value="$strictClassTier">
          <set_value name="$finalScore" exact="($classMult * $classTierScale) + $fineScore"/>
        </do_if>
        <do_else>
          <set_value name="$finalScore" exact="$fineScore"/>
        </do_else>
        <do_if value="$supPrioMax gt 0">
          <set_value name="$supThisPrio" exact="if $trade.$BuyStation? and @$trade.$BuyStation.exists and @$trade.$BuyStation.isplayerowned then $supPlayerPrio else $supAiPrio"/>
          <set_value name="$supFactor" exact="$supThisPrio / ($supPrioMax * 1.0)"/>
          <set_value name="$finalScore" exact="$finalScore * $supFactor"/>
        </do_if>
        <set_value name="$trade.$baseSupplyScore" exact="$rawBase"/>
        <set_value name="$trade.$normBase" exact="$normBase"/>
        <set_value name="$trade.$ClassMultiplier" exact="$classMult"/>
        <set_value name="$trade.$finalScore" exact="$finalScore"/>
        <set_value name="$trade.$Score" exact="$finalScore"/>
        <append_to_list name="$sortedTrades" exact="$trade"/>
        <do_if value="$finalScore gt $bestScore">
          <set_value name="$bestScore" exact="$finalScore"/>
          <set_value name="$bestTrade" exact="$trade"/>
        </do_if>
      </do_all>

      <sort_list list="$sortedTrades" sortbyvalue="loop.element.$Score" sortdescending="true"/>

      <do_if value="$diversifyByWare and $sortedTrades.count gt 1">
        <create_list name="$diversifiedTrades"/>
        <set_value name="$diversifyPicked" exact="table[]"/>
        <set_value name="$usePriorityFirst" exact="$priorityFirstInDiversify and $safePriorityWares.count gt 0"/>
        <do_while value="$diversifiedTrades.count lt $sortedTrades.count">
          <set_value name="$diversifyRoundServed" exact="table[]"/>
          <set_value name="$diversifyRoundAdded" exact="0"/>
          <do_if value="$usePriorityFirst">
            <do_all exact="$safePriorityWares.count" counter="$dpp">
              <set_value name="$dpw" exact="$safePriorityWares.{$dpp}"/>
              <do_if value="not $dpw? or $dpw == null or $diversifyRoundServed.{$dpw}?">
                <continue/>
              </do_if>
              <do_all exact="$sortedTrades.count" counter="$dpwi">
                <do_if value="not $diversifyPicked.{$dpwi}? and $sortedTrades.{$dpwi}.$Ware? and $sortedTrades.{$dpwi}.$Ware == $dpw">
                  <append_to_list name="$diversifiedTrades" exact="$sortedTrades.{$dpwi}"/>
                  <set_value name="$diversifyPicked.{$dpwi}" exact="true"/>
                  <set_value name="$diversifyRoundServed.{$dpw}" exact="true"/>
                  <set_value name="$diversifyRoundAdded" operation="add"/>
                  <break/>
                </do_if>
              </do_all>
            </do_all>
          </do_if>
          <do_all exact="$sortedTrades.count" counter="$dwi">
            <do_if value="not $diversifyPicked.{$dwi}?">
              <set_value name="$dwTrade" exact="$sortedTrades.{$dwi}"/>
              <set_value name="$dwWare" exact="if $dwTrade.$Ware? then $dwTrade.$Ware else null"/>
              <do_if value="$dwWare? and not $diversifyRoundServed.{$dwWare}?">
                <append_to_list name="$diversifiedTrades" exact="$dwTrade"/>
                <set_value name="$diversifyPicked.{$dwi}" exact="true"/>
                <set_value name="$diversifyRoundServed.{$dwWare}" exact="true"/>
                <set_value name="$diversifyRoundAdded" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
          <do_if value="$diversifyRoundAdded == 0">
            <break/>
          </do_if>
        </do_while>
        <do_all exact="$sortedTrades.count" counter="$dwt">
          <do_if value="not $diversifyPicked.{$dwt}?">
            <append_to_list name="$diversifiedTrades" exact="$sortedTrades.{$dwt}"/>
          </do_if>
        </do_all>
        <set_value name="$sortedTrades" exact="$diversifiedTrades"/>
        <set_value name="$bestTrade" exact="if $sortedTrades.count gt 0 then $sortedTrades.{1} else null"/>
        <set_value name="$bestScore" exact="if $bestTrade? and $bestTrade.$Score? then $bestTrade.$Score else 0"/>
      </do_if>

      <wait exact="1ms"/>
      <return value="table[$Found = ($bestTrade != null), $BestTrade = $bestTrade, $BestScore = $bestScore, $SortedTrades = $sortedTrades, $StrictClassTier = $strictClassTier, $DominantClassTag = $dominantClassTag, $PrioMultMin = $prioMultMin, $PrioMultMax = $prioMultMax]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.mk42.tradematch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="8">
  <params>
    <param name="ship" default="this.ship"/>
    <param name="sellOffers" default="[]"/>
    <param name="buyOffers" default="[]"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="minROI" default="0"/>
    <param name="minAbsoluteProfit" default="0"/>
    <param name="distancePenalty" default="0.1"/>
    <param name="factionPriority" default="0"/>
    <param name="ignoreBuildStorage" default="false"/>
    <param name="ignoreCarrierAux" default="false"/>
    <param name="allowIllegal" default="false"/>
    <param name="enforceRouteIllegalLegality" default="false"/>
    <param name="blacklistGroup" default="null"/>
    <param name="scoreMode" default="'sell'"/>
    <param name="maxTradesPerWare" default="20"/>
    <param name="maxTradesPerBucket" default="30" comment="MK4-2 dual-axis merge: top-K per delivery-class x supplier-source bucket"/>
    <param name="debugchance" default="0"/>
    <param name="mode" default="'match'"/>
    <param name="lineType" default="'source'"/>
    <param name="sourceStation" default="null"/>
    <param name="station" default="null"/>
    <param name="wareText" default="null"/>
    <param name="isPlayerOwned" default="false"/>
    <param name="diagMode" default="'unknown'"/>
    <param name="unavailableFlag" default="'0'"/>
    <param name="amountText" default="'n/a'"/>
    <param name="altUnavailableFlag" default="'n/a'"/>
    <param name="altAmountText" default="'n/a'"/>
    <param name="cargoCount" default="0"/>
    <param name="cargoTarget" default="0"/>
    <param name="cargoRatio" default="0"/>
    <param name="ignoreTradeRules" default="false"/>
    <param name="tradeListInput" default="[]"/>
    <param name="rawNeedAmount" default="0"/>
    <param name="incomingReservedAmount" default="0"/>
    <param name="shipChunkAmount" default="1"/>
    <param name="availableTradeWaresCount" default="1"/>
    <param name="reservedCount" default="0"/>
    <param name="alreadyReservedByThisShip" default="false"/>
    <param name="fairnessCap" default="2"/>
    <param name="synthesizeAmount" default="0"/>
    <param name="tradeOffer" default="null"/>
    <param name="operation" default="'find'"/>
    <param name="wareExchangeLegs" default="[]"/>
    <param name="sourceRatio" default="0"/>
    <param name="sourceOfferAmount" default="0"/>
    <param name="destOfferAmount" default="0"/>
    <param name="sourceStorageDiscovery" default="false"/>
    <param name="destStorageDiscovery" default="false"/>
    <param name="mk2StaticStorage" default="0"/>
    <param name="mk2MinStorage" default="0"/>
    <param name="mk2MaxStorage" default="0"/>
    <param name="pilotLevelProfile" default="1"/>
    <param name="routeAlpha" default="0"/>
    <param name="routeBeta" default="0"/>
    <param name="routeLaneBonus" default="1"/>
    <param name="minCargoFillPercent" default="25"/>
    <param name="allowLowVolume" default="false"/>
    <param name="lowVolumeFloorEffPercent" default="50"/>
    <param name="bidirectional" default="false"/>
    <param name="fleetCoordination" default="false"/>
    <param name="sourceUsageCount" default="0"/>
    <param name="destUsageCount" default="0"/>
    <param name="stickyCyclesLeft" default="0"/>
    <param name="stickySource" default="null"/>
    <param name="stickyDestination" default="null"/>
    <param name="stickyWare" default="null"/>
    <param name="lastTradeDestination" default="null"/>
    <param name="lastTradeSource" default="null"/>
    <param name="lastTradeWare" default="null"/>
    <param name="sourceStationRef" default="null"/>
    <param name="mk2SourceOffer" default="null"/>
    <param name="mk2DestOffer" default="null"/>
    <!-- MK4 compatibility params (accepted for call-site compatibility) -->
    <param name="mk4AllowResources" default="true"/>
    <param name="mk4AllowIntermediates" default="true"/>
    <param name="mk4AllowTradewares" default="true"/>
    <param name="mk4DedicatedServe" default="false"/>
    <param name="mk4AnchorHome" default="null"/>
    <param name="mk4BuildStorageOnlyMode" default="false"/>
    <param name="mk4AllowPlayerSuppliers" default="true"/>
    <param name="mk4AllowAiSuppliers" default="true"/>
    <param name="mk4CustomerMustBePlayer" default="false"/>
    <param name="mk42Priorities" default="table[]" comment="MK4-2 class sliders â€” delivery customer filter + ClassMultiplier"/>
    <param name="maxDistanceBuy" default="0"/>
    <param name="maxDistanceSell" default="0"/>
    <param name="backtrackTolerance" default="0"/>
    <param name="allowZeroProfitSell" default="false"/>
    <!-- MK3 'Ignore Player Pricing' companion filter: when true, reject any match whose delivery (customer) station is player-owned. -->
    <param name="excludePlayerBuyers" default="false"/>
    <!-- MK3 'Ignore Player Pricing' profit-semantics override: when true AND the supplier (buy-leg owner) is player-owned,
         treat the supplier-side cost as zero (production is "free" from the player's perspective). This bypasses the
         negative/zero/min-profit rejections for player-sourced trades and scores them by gross sell income (sellPrice * amount).
         NPC-sourced trades in the same scan continue to use the normal profit gates and scoring. -->
    <param name="playerSupplierFreeProduction" default="false"/>
    <param name="allowStorageDock" default="false"/>
  </params>
  <!-- v3: restore outer-loop cooperative wait (blocking action index 1 for save compat).
       v4: save/load resume at that wait skips setup; this.$ is not persisted on library contexts. -->
  <patch sinceversion="2">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
  </patch>
  <patch sinceversion="3">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v3 patch applied (blocking wait index 1 restored; match accumulators on this.$tm_*)'" chance="100" filter="savegame"/>
  </patch>
  <patch sinceversion="4">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v4 patch applied (save/load resume rebuild guard for this.$tm_* snapshots)'" chance="100" filter="savegame"/>
  </patch>
  <patch sinceversion="5">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
  </patch>
  <patch sinceversion="7">
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v7: reset match accumulators on each fresh run_script entry (fixes stale MK3 trades leaking into MK1 export)'" chance="100" filter="savegame"/>
  </patch>
  <patch sinceversion="8">
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v8: post-wait resume only when offer scratch lost (fixes MK3 live-search freeze from v7 unconditional resume)'" chance="100" filter="savegame"/>
  </patch>
  <attention min="unknown">
    <actions>
      <do_if value="$mode == 'count_distinct_wares'">
        <create_list name="$distinctWares"/>
        <set_value name="$distinctCount" exact="0"/>
        <do_if value="$tradeListInput? and $tradeListInput.count gt 0">
          <do_all exact="$tradeListInput.count" counter="$dwi">
            <set_value name="$dwTrade" exact="$tradeListInput.{$dwi}"/>
            <set_value name="$dwWare" exact="null"/>
            <do_if value="$dwTrade? and $dwTrade.$Ware?">
              <set_value name="$dwWare" exact="$dwTrade.$Ware"/>
            </do_if>
            <do_if value="$dwWare?">
              <set_value name="$dwSeen" exact="false"/>
              <do_all exact="$distinctWares.count" counter="$dwj">
                <do_if value="$distinctWares.{$dwj} == $dwWare">
                  <set_value name="$dwSeen" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not $dwSeen">
                <append_to_list name="$distinctWares" exact="$dwWare"/>
                <set_value name="$distinctCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <return value="table[
          $DistinctWares = $distinctWares,
          $DistinctCount = $distinctCount
        ]"/>
      </do_if>

      <do_if value="$mode == 'ware_fairness'">
        <set_value name="$chunkSafe" exact="[1, $shipChunkAmount].max"/>
        <set_value name="$effectiveNeedAmount" exact="[$rawNeedAmount - $incomingReservedAmount, 0].max"/>
        <set_value name="$maxShipsForWare" exact="0"/>
        <do_if value="$effectiveNeedAmount gt 0">
          <set_value name="$maxShipsForWare" exact="(($effectiveNeedAmount + $chunkSafe - 1) / $chunkSafe)i"/>
          <do_if value="$availableTradeWaresCount gt 1 and $fairnessCap gt 0">
            <set_value name="$maxShipsForWare" exact="[$maxShipsForWare, $fairnessCap].min"/>
          </do_if>
        </do_if>
        <set_value name="$reservationAllowsTrade" exact="false"/>
        <do_if value="$alreadyReservedByThisShip or $reservedCount lt $maxShipsForWare">
          <set_value name="$reservationAllowsTrade" exact="true"/>
        </do_if>
        <return value="table[
          $EffectiveNeedAmount = $effectiveNeedAmount,
          $MaxShipsForWare = $maxShipsForWare,
          $ReservationAllowsTrade = $reservationAllowsTrade
        ]"/>
      </do_if>

      <do_if value="$mode == 'offerdiag_probe'">
        <set_value name="$diagModeResult" exact="'partner-filtered'"/>
        <set_value name="$altUnavailableFlagResult" exact="'n/a'"/>
        <set_value name="$altAmountTextResult" exact="'n/a'"/>
        <do_if value="$ignoreTradeRules and $station.isplayerowned">
          <set_value name="$diagModeResult" exact="'ignore-rules(player-owned)'"/>
          <set_value name="$altUnavailableFlagResult" exact="'1'"/>
          <set_value name="$altAmountTextResult" exact="'n/a'"/>
          <do_if value="$lineType == 'dest'">
            <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" result="$altOfferWithRules"/>
          </do_if>
          <do_else>
            <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" result="$altOfferWithRules"/>
          </do_else>
          <do_if value="$altOfferWithRules == null or not $altOfferWithRules.available">
            <set_value name="$altUnavailableFlagResult" exact="'0'"/>
          </do_if>
          <do_if value="$altOfferWithRules != null">
            <set_value name="$altAmountTextResult" exact="$altOfferWithRules.offeramount.{$ship}"/>
          </do_if>
        </do_if>
        <return value="table[
          $Mode = $diagModeResult,
          $AltUnavailableFlag = $altUnavailableFlagResult,
          $AltAmountText = $altAmountTextResult
        ]"/>
      </do_if>

      <do_if value="$mode == 'offerdiag'">
        <set_value name="$ownerText" exact="if $isPlayerOwned then 'player' else 'foreign'"/>
        <set_value name="$detail" exact="''"/>
        <do_if value="$lineType == 'dest'">
          <set_value name="$detail" exact="$sourceStation.idcode + '->' + $station.idcode + ':' + $wareText + ' owner=' + $ownerText + ' mode=' + $diagMode + ' buy(unavailable=' + $unavailableFlag + ',amount=' + $amountText + ') altWithRules(unavailable=' + $altUnavailableFlag + ',amount=' + $altAmountText + ') cargo=' + $cargoCount + '/' + $cargoTarget + ' (' + $cargoRatio + '%)'"/>
        </do_if>
        <do_else>
          <set_value name="$detail" exact="$station.knownname + ' [' + $station.idcode + ']:' + $wareText + ' owner=' + $ownerText + ' mode=' + $diagMode + ' offer(unavailable=' + $unavailableFlag + ',amount=' + $amountText + ') altWithRules(unavailable=' + $altUnavailableFlag + ',amount=' + $altAmountText + ')'"/>
        </do_else>
        <return value="$detail"/>
      </do_if>

      <!-- MK2 player-station offer resolve: extended find fallbacks. -->
      <do_if value="$mode == 'mk2_ware_exchange_invoke'">
        <set_value name="$mk2WxRequestId" exact="$ship.idcode + '|WX|' + (player.age / 1ms)i"/>
        <set_value name="player.entity.$GT_MK2_WareExchangeRequest" exact="table[$RequestId = $mk2WxRequestId, $Ship = $ship, $ShipIdCode = $ship.idcode, $Legs = $wareExchangeLegs]"/>
        <raise_lua_event name="'gt.mk2QueueWareExchange'" param="$mk2WxRequestId"/>
        <set_value name="$mk2WxSuccess" exact="false"/>
        <set_value name="$mk2WxError" exact="'timeout'"/>
        <set_value name="$mk2WxQueueLegs" exact="[]"/>
        <set_value name="$mk2WxQueued" exact="0"/>
        <wait max="5s">
          <interrupt>
            <conditions>
              <event_object_signalled object="$ship" param="'gt_mk2_ware_exchange_done'"/>
            </conditions>
            <actions>
              <set_value name="$mk2WxResult" exact="player.entity.$GT_MK2_WareExchangeResult"/>
              <do_if value="$mk2WxResult? and $mk2WxResult.$RequestId == $mk2WxRequestId">
                <do_if value="$mk2WxResult.$Success? and $mk2WxResult.$Success">
                  <set_value name="$mk2WxSuccess" exact="true"/>
                  <set_value name="$mk2WxError" exact="''"/>
                  <do_if value="$mk2WxResult.$Queued?">
                    <set_value name="$mk2WxQueued" exact="$mk2WxResult.$Queued"/>
                  </do_if>
                  <do_if value="$mk2WxResult.$QueueLegs?">
                    <set_value name="$mk2WxQueueLegs" exact="$mk2WxResult.$QueueLegs"/>
                  </do_if>
                </do_if>
                <do_elseif value="$mk2WxResult.$Error?">
                  <set_value name="$mk2WxError" exact="$mk2WxResult.$Error"/>
                </do_elseif>
              </do_if>
            </actions>
          </interrupt>
        </wait>
        <remove_value name="player.entity.$GT_MK2_WareExchangeRequest"/>
        <remove_value name="player.entity.$GT_MK2_WareExchangeResult"/>
        <return value="table[
          $Success = $mk2WxSuccess,
          $Error = $mk2WxError,
          $Queued = $mk2WxQueued,
          $QueueLegs = $mk2WxQueueLegs
        ]"/>
      </do_if>

      <do_if value="$mode == 'mk2_player_offer'">
        <set_value name="$mk2OfferResult" exact="null"/>
        <set_value name="$mk2OfferFound" exact="false"/>
        <set_value name="$mk2OfferSynthetic" exact="false"/>
        <!-- operation == 'find' (default) -->
        <do_if value="$ignoreTradeRules and $station.isplayerowned">
          <do_if value="$lineType == 'dest'">
            <find_buy_offer buyer="$station" wares="$wareText" result="$mk2OfferResult"/>
            <do_if value="$mk2OfferResult == null">
              <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_buy_offer buyer="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
          </do_if>
          <do_else>
            <find_sell_offer seller="$station" wares="$wareText" result="$mk2OfferResult"/>
            <do_if value="$mk2OfferResult == null">
              <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_sell_offer seller="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="$lineType == 'dest'">
            <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" result="$mk2OfferResult"/>
          </do_if>
          <do_else>
            <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" result="$mk2OfferResult"/>
          </do_else>
        </do_else>
        <do_if value="$mk2OfferResult != null">
          <set_value name="$mk2OfferFound" exact="true"/>
        </do_if>
        <return value="table[
          $Offer = $mk2OfferResult,
          $Found = $mk2OfferFound,
          $Synthetic = $mk2OfferSynthetic
        ]"/>
      </do_if>

      <do_if value="$mode == 'mk2_storage_pair_score'">
        <set_value name="$mk2TradeEntry" exact="null"/>
        <set_value name="$mk2SkipType" exact="'none'"/>
        <set_value name="$needBucket" exact="'none'"/>
        <set_value name="$bucketWeight" exact="1.0"/>
        <set_value name="$isCriticalNeed" exact="false"/>
        <set_value name="$shouldDistribute" exact="false"/>
        <do_if value="$pilotLevelProfile ge 4">
          <do_if value="$cargoRatio le 5">
            <set_value name="$needBucket" exact="'A'"/>
            <set_value name="$bucketWeight" exact="3.0"/>
            <set_value name="$isCriticalNeed" exact="true"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_if>
          <do_elseif value="$cargoRatio le 20">
            <set_value name="$needBucket" exact="'B'"/>
            <set_value name="$bucketWeight" exact="2.0"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
          <do_elseif value="$cargoRatio le $mk2MinStorage">
            <set_value name="$needBucket" exact="'C'"/>
            <set_value name="$bucketWeight" exact="1.4"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
          <do_elseif value="$sourceRatio gt $mk2MaxStorage and $sourceRatio gt ($cargoRatio + 10)">
            <set_value name="$needBucket" exact="'D'"/>
            <set_value name="$bucketWeight" exact="1.0"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
        </do_if>
        <do_else>
          <do_if value="$cargoRatio le 5">
            <set_value name="$needBucket" exact="'A'"/>
            <set_value name="$bucketWeight" exact="2.4"/>
            <set_value name="$isCriticalNeed" exact="true"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_if>
          <do_elseif value="$cargoRatio le $mk2MinStorage">
            <set_value name="$needBucket" exact="'C'"/>
            <set_value name="$bucketWeight" exact="1.2"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
          <do_elseif value="$sourceRatio gt $mk2MaxStorage and $sourceRatio gt ($cargoRatio + 10)">
            <set_value name="$needBucket" exact="'D'"/>
            <set_value name="$bucketWeight" exact="1.0"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
        </do_else>
        <do_if value="not $shouldDistribute">
          <set_value name="$mk2SkipType" exact="'noNeed'"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <do_if value="$lastTradeSource? and $lastTradeSource.exists and $lastTradeDestination? and $lastTradeDestination.exists and $lastTradeWare? and $sourceStation == $lastTradeDestination and $station == $lastTradeSource and $wareText == $lastTradeWare and $needBucket != 'A'">
          <set_value name="$mk2SkipType" exact="'pingPong'"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <set_value name="$cargoCapacity" exact="$ship.cargo.{$wareText}.max"/>
        <set_value name="$incomingReservedAmount" exact="0"/>
        <set_value name="$reservedShipCount" exact="0"/>
        <set_value name="$effectiveDestOfferAmount" exact="$destOfferAmount"/>
        <do_if value="$fleetCoordination and $station? and $station.exists">
          <get_ware_reservation object="$station" ware="$wareText" type="sell" virtual="false" result="$incomingReservedAmount"/>
          <set_value name="$reservedShipCount" exact="(($incomingReservedAmount + [1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max - 1) / [1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max)i"/>
        </do_if>
        <set_value name="$shipChunkAmount" exact="[1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max"/>
        <set_value name="$effectiveNeedAmount" exact="[$destOfferAmount - 0, 0].max"/>
        <set_value name="$maxShipsForWare" exact="0"/>
        <do_if value="$effectiveNeedAmount gt 0">
          <set_value name="$maxShipsForWare" exact="(($effectiveNeedAmount + $shipChunkAmount - 1) / $shipChunkAmount)i"/>
        </do_if>
        <set_value name="$effectiveDestOfferAmount" exact="$effectiveNeedAmount"/>
        <do_if value="$effectiveDestOfferAmount le 0">
          <set_value name="$mk2SkipType" exact="'reserved'"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <set_value name="$tradeAmount" exact="[$ship.cargo.{$wareText}.free, $sourceOfferAmount, $effectiveDestOfferAmount].min"/>
        <set_value name="$normalMinimumTrade" exact="[1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max"/>
        <set_value name="$minimumTrade" exact="$normalMinimumTrade"/>
        <set_value name="$usedLowVolume" exact="false"/>
        <set_value name="$canLowVolume" exact="false"/>
        <do_if value="$allowLowVolume">
          <do_if value="$pilotLevelProfile ge 6 or $isCriticalNeed">
            <set_value name="$canLowVolume" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$canLowVolume">
          <set_value name="$minimumTrade" exact="[1, (($cargoCapacity * $lowVolumeFloorEffPercent) / 100)i].max"/>
          <do_if value="$isCriticalNeed">
            <set_value name="$minimumTrade" exact="[1, ($minimumTrade / 2)i].max"/>
          </do_if>
          <set_value name="$usedLowVolume" exact="true"/>
        </do_if>
        <do_if value="$tradeAmount lt $minimumTrade">
          <set_value name="$mk2SkipType" exact="'minTrade'"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <set_value name="$urgencyMultiplier" exact="$bucketWeight"/>
        <set_value name="$balanceFactor" exact="[0, ($sourceRatio - $cargoRatio)].max / 100"/>
        <set_value name="$baseScore" exact="(($sourceRatio - $mk2StaticStorage) * $urgencyMultiplier * ($tradeAmount / [$cargoCapacity, 1].max)) + $balanceFactor - (($sourceUsageCount + $destUsageCount) * 0.2)"/>
        <set_value name="$shipToSourceGates" exact="$ship.gatedistance.{$sourceStation}"/>
        <set_value name="$sourceToDestGates" exact="$sourceStation.gatedistance.{$station}"/>
        <set_value name="$forwardGates" exact="[0, $shipToSourceGates].max + [0, $sourceToDestGates].max"/>
        <set_value name="$baselineGates" exact="$forwardGates"/>
        <do_if value="$sourceStationRef? and $sourceStationRef.exists and $lastTradeDestination? and $lastTradeDestination.exists">
          <set_value name="$baseShipToSourceGates" exact="$ship.gatedistance.{$sourceStationRef}"/>
          <set_value name="$baseSourceToDestGates" exact="$sourceStationRef.gatedistance.{$lastTradeDestination}"/>
          <do_if value="$baseShipToSourceGates ge 0 and $baseSourceToDestGates ge 0">
            <set_value name="$baselineGates" exact="$baseShipToSourceGates + $baseSourceToDestGates"/>
          </do_if>
        </do_if>
        <set_value name="$deltaGates" exact="[0, $forwardGates - $baselineGates].max"/>
        <set_value name="$backtrackPenalty" exact="0"/>
        <do_if value="not $bidirectional and (not $lastTradeDestination? or not $lastTradeDestination.exists or $sourceStation != $lastTradeDestination)">
        <do_if value="$lastTradeDestination? and $lastTradeDestination.exists">
          <set_value name="$prevToDestGates" exact="$lastTradeDestination.gatedistance.{$station}"/>
          <set_value name="$prevToSourceGates" exact="$lastTradeDestination.gatedistance.{$sourceStation}"/>
          <do_if value="$prevToDestGates ge 0 and $prevToSourceGates ge 0 and $prevToDestGates gt ($prevToSourceGates + 1)">
            <set_value name="$backtrackPenalty" exact="1"/>
          </do_if>
        </do_if>
        </do_if>
        <set_value name="$laneBonus" exact="1.0"/>
        <do_if value="$stickyCyclesLeft gt 0 and $stickySource? and $stickyDestination? and $stickyWare? and $stickySource == $sourceStation and $stickyDestination == $station and $stickyWare == $wareText">
          <set_value name="$laneBonus" exact="$routeLaneBonus"/>
        </do_if>
        <set_value name="$routeT" exact="$pilotLevelProfile / 15.0"/>
        <set_value name="$nearStationFactor" exact="1.0"/>
        <do_if value="$lastTradeDestination? and $lastTradeDestination.exists">
          <do_if value="$sourceStation == $lastTradeDestination">
            <set_value name="$nearStationFactor" exact="$routeLaneBonus"/>
            <do_if value="$shipToSourceGates == 0">
              <set_value name="$nearStationFactor" exact="$nearStationFactor * 1.10"/>
            </do_if>
          </do_if>
          <do_elseif value="$pilotLevelProfile ge 4">
            <set_value name="$nearStationFactor" exact="0.80 + (0.20 * $routeT)"/>
          </do_elseif>
        </do_if>
        <set_value name="$costFactor" exact="1.0"/>
        <do_if value="$pilotLevelProfile ge 4">
          <set_value name="$costFactor" exact="1.0 + ($routeAlpha * $deltaGates) + ($routeBeta * $backtrackPenalty)"/>
          <do_if value="$lastTradeDestination? and $lastTradeDestination.exists and $sourceStation != $lastTradeDestination">
            <set_value name="$detourFromLastGates" exact="$lastTradeDestination.gatedistance.{$sourceStation}"/>
            <do_if value="$detourFromLastGates ge 0">
              <set_value name="$costFactor" exact="$costFactor + ($routeAlpha * $detourFromLastGates)"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$costFactor" exact="1.0 + (0.20 * $forwardGates)"/>
        </do_else>
        <set_value name="$score" exact="($baseScore * $laneBonus * $nearStationFactor) / [1.0, $costFactor].max"/>
        <set_value name="$mk2TradeEntry" exact="table[
          $Ware = $wareText,
          $Source = $sourceStation,
          $Destination = $station,
          $Amount = $tradeAmount,
          $Urgent = $isCriticalNeed,
          $NeedBucket = $needBucket,
          $Score = $score,
          $SourceOffer = $mk2SourceOffer,
          $DestOffer = $mk2DestOffer,
          $SourceOfferAmount = $sourceOfferAmount,
          $DestOfferAmount = $destOfferAmount,
          $EffectiveDestOfferAmount = $effectiveDestOfferAmount,
          $IncomingReservedAmount = $incomingReservedAmount,
          $NormalMinimumTrade = $normalMinimumTrade,
          $UsedLowVolume = $usedLowVolume,
          $DeltaGates = $deltaGates,
          $BacktrackPenalty = $backtrackPenalty,
          $SourceStorageDiscovery = $sourceStorageDiscovery,
          $DestStorageDiscovery = $destStorageDiscovery
        ]"/>
        <return value="table[$TradeEntry = $mk2TradeEntry, $SkipType = $mk2SkipType]"/>
      </do_if>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <do_if value="not $sellOffers? or not $buyOffers? or $sellOffers.count == 0 or $buyOffers.count == 0">
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = [],
          $TradesEvaluated = 0,
          $TradesRejected = 0,
          $TradesRejectedRouteIllegal = 0,
          $TradesRejectedMk4CustomerPolicy = 0,
          $TradesRejectedMk4SupplierPolicy = 0,
          $TradesRejectedMk4TypePolicy = 0,
          $TradesRejectedMk4DemandGate = 0,
          $TradesRejectedMk4PriceCap = 0,
          $TradesRejectedDistance = 0
        ]"/>
      </do_if>

      <!-- Fresh run_script entry resets match accumulators. Library this.$ persists on the same ship;
           without this, a prior MK3 buy_and_sell scan leaves sector arbitrage rows in $TradeList and
           MK1 export (home sellOffers + NPC buyOffers) scores/selects those stale trades. -->
      <create_list name="this.$tm_tradeList"/>
      <set_value name="this.$tm_bestTrade" exact="null"/>
      <set_value name="this.$tm_bestScore" exact="0"/>
      <set_value name="this.$tm_tradesEvaluated" exact="0"/>
      <set_value name="this.$tm_tradesRejected" exact="0"/>
      <set_value name="this.$tm_tradesRejectedRouteIllegal" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4TypePolicy" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4DemandGate" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4PriceCap" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk42Class" exact="0"/>
      <set_value name="this.$tm_tradesRejectedTradeRules" exact="0"/>
      <set_value name="this.$tm_tradesRejectedDistance" exact="0"/>
      <set_value name="this.$tm_tradesPerWare" exact="table[]"/>
      <set_value name="this.$tm_supplyScoreDiagCount" exact="0"/>
      <!-- MK4-2 dual-axis buckets: delivery class x supplier source (Player/Npc). -->
      <set_value name="this.$tm_useDualAxisBuckets" exact="false"/>
      <do_if value="$scoreMode == 'supply' and $mk42Priorities?">
        <set_value name="this.$tm_useDualAxisBuckets" exact="true"/>
        <set_value name="this.$tm_maxTradesPerBucket" exact="if $maxTradesPerBucket? and $maxTradesPerBucket gt 0 then $maxTradesPerBucket else 30"/>
        <set_value name="this.$tm_tradesByBucket" exact="table[$BS_P = [], $BS_N = [], $ST_P = [], $ST_N = [], $AX_P = [], $AX_N = [], $CR_P = [], $CR_N = []]"/>
        <set_value name="this.$tm_tradesPerBucketWare" exact="table[$BS_P = table[], $BS_N = table[], $ST_P = table[], $ST_N = table[], $AX_P = table[], $AX_N = table[], $CR_P = table[], $CR_N = table[]]"/>
      </do_if>
      <remove_value name="this.$tm_abortMatch"/>

      <!-- Rebuild match state after save/load resume at blocking wait (index 1).
           In-loop waits resume at tm_ensure_state below (skip accumulator reset above). -->
      <label name="tm_ensure_state"/>
      <do_if value="this.$tm_abortMatch?">
        <remove_value name="this.$tm_abortMatch"/>
      </do_if>
      <do_if value="not this.$tm_tradeList?">
        <create_list name="this.$tm_tradeList"/>
      </do_if>
      <do_if value="not this.$tm_bestTrade?">
        <set_value name="this.$tm_bestTrade" exact="null"/>
      </do_if>
      <do_if value="not this.$tm_bestScore?">
        <set_value name="this.$tm_bestScore" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesEvaluated?">
        <set_value name="this.$tm_tradesEvaluated" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejected?">
        <set_value name="this.$tm_tradesRejected" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedRouteIllegal?">
        <set_value name="this.$tm_tradesRejectedRouteIllegal" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4CustomerPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4SupplierPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4TypePolicy?">
        <set_value name="this.$tm_tradesRejectedMk4TypePolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4DemandGate?">
        <set_value name="this.$tm_tradesRejectedMk4DemandGate" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4PriceCap?">
        <set_value name="this.$tm_tradesRejectedMk4PriceCap" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4BuildStorageOnly?">
        <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedDistance?">
        <set_value name="this.$tm_tradesRejectedDistance" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_supplyScoreDiagCount?">
        <set_value name="this.$tm_supplyScoreDiagCount" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesPerWare?">
        <set_value name="this.$tm_tradesPerWare" exact="table[]"/>
      </do_if>
      <do_if value="this.$tm_useDualAxisBuckets?">
        <do_if value="not this.$tm_tradesByBucket? or not this.$tm_tradesByBucket.$BS_P?">
          <set_value name="this.$tm_tradesByBucket" exact="table[$BS_P = [], $BS_N = [], $ST_P = [], $ST_N = [], $AX_P = [], $AX_N = [], $CR_P = [], $CR_N = []]"/>
        </do_if>
        <do_if value="not this.$tm_tradesPerBucketWare? or not this.$tm_tradesPerBucketWare.$BS_P?">
          <set_value name="this.$tm_tradesPerBucketWare" exact="table[$BS_P = table[], $BS_N = table[], $ST_P = table[], $ST_N = table[], $AX_P = table[], $AX_N = table[], $CR_P = table[], $CR_N = table[]]"/>
        </do_if>
        <do_if value="not this.$tm_maxTradesPerBucket?">
          <set_value name="this.$tm_maxTradesPerBucket" exact="if $maxTradesPerBucket? and $maxTradesPerBucket gt 0 then $maxTradesPerBucket else 30"/>
        </do_if>
      </do_if>
      <do_if value="not global.$GT_TradeMatchScratch?">
        <set_value name="global.$GT_TradeMatchScratch" exact="table[]"/>
      </do_if>
      <set_value name="global.$GT_TradeMatchScratch.{$ship}" exact="table[$SellOffers = $sellOffers, $BuyOffers = $buyOffers]"/>
      <set_value name="$scratchSellOffers" exact="$sellOffers"/>
      <set_value name="$scratchBuyOffers" exact="$buyOffers"/>
      <do_if value="not $scratchSellOffers? and global.$GT_TradeMatchScratch.{$ship}.$SellOffers?">
        <set_value name="$scratchSellOffers" exact="global.$GT_TradeMatchScratch.{$ship}.$SellOffers"/>
      </do_if>
      <do_if value="not $scratchBuyOffers? and global.$GT_TradeMatchScratch.{$ship}.$BuyOffers?">
        <set_value name="$scratchBuyOffers" exact="global.$GT_TradeMatchScratch.{$ship}.$BuyOffers"/>
      </do_if>
      <create_list name="this.$tm_matchSellOffers"/>
      <set_value name="$scratchSellCount" exact="if $scratchSellOffers? then $scratchSellOffers.count else 0"/>
      <do_all exact="$scratchSellCount" counter="$sosi">
        <set_value name="$soCand" exact="@$scratchSellOffers.{$sosi}"/>
        <do_if value="$soCand? and @$soCand.exists">
          <append_to_list name="this.$tm_matchSellOffers" exact="$soCand"/>
        </do_if>
      </do_all>
      <create_list name="this.$tm_matchBuyOffers"/>
      <set_value name="$scratchBuyCount" exact="if $scratchBuyOffers? then $scratchBuyOffers.count else 0"/>
      <do_all exact="$scratchBuyCount" counter="$bosi">
        <set_value name="$boCand" exact="@$scratchBuyOffers.{$bosi}"/>
        <do_if value="$boCand? and @$boCand.exists">
          <append_to_list name="this.$tm_matchBuyOffers" exact="$boCand"/>
        </do_if>
      </do_all>
      <!-- Ware-indexed buy offers: inner pairing loop iterates matching ware only (S5). -->
      <set_value name="this.$tm_buyOffersByWare" exact="table[]"/>
      <set_value name="this.$tm_buyIndexByWare" exact="table[]"/>
      <set_value name="this.$tm_mk42ClassByOffer" exact="table[]"/>
      <set_value name="this.$tm_mk42MultByOffer" exact="table[]"/>
      <set_value name="$tmBuyIndexCount" exact="this.$tm_matchBuyOffers.count"/>
      <do_all exact="$tmBuyIndexCount" counter="$boi">
        <set_value name="$boIdx" exact="this.$tm_matchBuyOffers.{$boi}"/>
        <do_if value="$boIdx? and $boIdx.ware?">
          <set_value name="$boWare" exact="@$boIdx.ware"/>
          <do_if value="$boWare != null">
            <do_if value="not this.$tm_buyOffersByWare.{$boWare}?">
              <create_list name="this.$tm_buyOffersByWare.{$boWare}"/>
            </do_if>
            <append_to_list name="this.$tm_buyOffersByWare.{$boWare}" exact="$boIdx"/>
            <!-- MK4-2 Â§7.2: buyIndex[ware][class] â€” inline classify (no run_script; avoids AIDirector wake loop). -->
            <do_if value="$mk42Priorities?">
              <set_value name="$boClassTag" exact="'None'"/>
              <set_value name="$boClassMult" exact="0"/>
              <set_value name="$boBuyerForClass" exact="if $boIdx.buyer? then @$boIdx.buyer else (if $boIdx.owner? then @$boIdx.owner else null)"/>
              <do_if value="$boBuyerForClass? and $boBuyerForClass.exists">
                <do_if value="@$boBuyerForClass.isclass.buildstorage and @$boBuyerForClass.isplayerowned">
                  <set_value name="$boClassTag" exact="'Buildstorage'"/>
                </do_if>
                <do_elseif value="@$boBuyerForClass.isclass.station and @$boBuyerForClass.isplayerowned">
                  <set_value name="$boClassTag" exact="'Stations'"/>
                </do_elseif>
                <do_elseif value="@$boBuyerForClass.isclass.ship and @$boBuyerForClass.isplayerowned and @$boBuyerForClass.type == shiptype.carrier">
                  <set_value name="$boClassTag" exact="'Carrier'"/>
                </do_elseif>
                <do_elseif value="@$boBuyerForClass.isclass.ship and @$boBuyerForClass.isplayerowned and @$boBuyerForClass.primarypurpose == purpose.auxiliary">
                  <set_value name="$boClassTag" exact="'Aux'"/>
                </do_elseif>
                <do_elseif value="@$boBuyerForClass.isclass.buildstorage and $boBuyerForClass.base? and @$boBuyerForClass.base.isplayerowned">
                  <set_value name="$boClassTag" exact="'Buildstorage'"/>
                </do_elseif>
                <do_if value="$boClassTag == 'Buildstorage'">
                  <set_value name="$boClassMult" exact="if $mk42Priorities.$Buildstorage? then $mk42Priorities.$Buildstorage else 0"/>
                </do_if>
                <do_elseif value="$boClassTag == 'Stations'">
                  <set_value name="$boClassMult" exact="if $mk42Priorities.$Stations? then $mk42Priorities.$Stations else 0"/>
                </do_elseif>
                <do_elseif value="$boClassTag == 'Aux'">
                  <set_value name="$boClassMult" exact="if $mk42Priorities.$Aux? then $mk42Priorities.$Aux else 0"/>
                </do_elseif>
                <do_elseif value="$boClassTag == 'Carrier'">
                  <set_value name="$boClassMult" exact="if $mk42Priorities.$Carrier? then $mk42Priorities.$Carrier else 0"/>
                </do_elseif>
              </do_if>
              <do_if value="$boClassTag != 'None' and $boClassMult gt 0">
                <set_value name="this.$tm_mk42ClassByOffer.{$boIdx}" exact="$boClassTag"/>
                <set_value name="this.$tm_mk42MultByOffer.{$boIdx}" exact="$boClassMult"/>
                <do_if value="not this.$tm_buyIndexByWare.{$boWare}?">
                  <set_value name="this.$tm_buyIndexByWare.{$boWare}" exact="table[]"/>
                </do_if>
                <do_if value="$boClassTag == 'Buildstorage'">
                  <do_if value="not this.$tm_buyIndexByWare.{$boWare}.$Buildstorage?">
                    <create_list name="this.$tm_buyIndexByWare.{$boWare}.$Buildstorage"/>
                  </do_if>
                  <append_to_list name="this.$tm_buyIndexByWare.{$boWare}.$Buildstorage" exact="$boIdx"/>
                </do_if>
                <do_elseif value="$boClassTag == 'Stations'">
                  <do_if value="not this.$tm_buyIndexByWare.{$boWare}.$Stations?">
                    <create_list name="this.$tm_buyIndexByWare.{$boWare}.$Stations"/>
                  </do_if>
                  <append_to_list name="this.$tm_buyIndexByWare.{$boWare}.$Stations" exact="$boIdx"/>
                </do_elseif>
                <do_elseif value="$boClassTag == 'Aux'">
                  <do_if value="not this.$tm_buyIndexByWare.{$boWare}.$Aux?">
                    <create_list name="this.$tm_buyIndexByWare.{$boWare}.$Aux"/>
                  </do_if>
                  <append_to_list name="this.$tm_buyIndexByWare.{$boWare}.$Aux" exact="$boIdx"/>
                </do_elseif>
                <do_elseif value="$boClassTag == 'Carrier'">
                  <do_if value="not this.$tm_buyIndexByWare.{$boWare}.$Carrier?">
                    <create_list name="this.$tm_buyIndexByWare.{$boWare}.$Carrier"/>
                  </do_if>
                  <append_to_list name="this.$tm_buyIndexByWare.{$boWare}.$Carrier" exact="$boIdx"/>
                </do_elseif>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
      </do_all>
      <do_if value="this.$tm_matchSellOffers.count == 0 or this.$tm_matchBuyOffers.count == 0">
        <set_value name="this.$tm_abortMatch" exact="true"/>
      </do_if>

      <label name="tm_match_run"/>
      <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
        <resume label="tm_ensure_state"/>
      </do_if>
      <do_if value="this.$tm_abortMatch?">
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = this.$tm_tradeList,
          $TradesEvaluated = 0,
          $TradesRejected = 0,
          $TradesRejectedRouteIllegal = 0,
          $TradesRejectedMk4CustomerPolicy = 0,
          $TradesRejectedMk4SupplierPolicy = 0,
          $TradesRejectedMk4TypePolicy = 0,
          $TradesRejectedMk4DemandGate = 0,
          $TradesRejectedMk4PriceCap = 0,
          $TradesRejectedDistance = 0
        ]"/>
      </do_if>
      <set_value name="$tmSellLoopCount" exact="this.$tm_matchSellOffers.count"/>

      <do_all exact="$tmSellLoopCount" counter="$si">
        <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
          <resume label="tm_ensure_state"/>
        </do_if>
        <do_if value="this.$tm_abortMatch?">
          <return value="table[
            $Found = false,
            $BestTrade = null,
            $BestScore = 0,
            $TradeList = this.$tm_tradeList,
            $TradesEvaluated = 0,
            $TradesRejected = 0,
            $TradesRejectedRouteIllegal = 0,
            $TradesRejectedMk4CustomerPolicy = 0,
            $TradesRejectedMk4SupplierPolicy = 0,
            $TradesRejectedMk4TypePolicy = 0,
            $TradesRejectedMk4DemandGate = 0,
            $TradesRejectedMk4PriceCap = 0,
            $TradesRejectedDistance = 0
          ]"/>
        </do_if>
        <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
          <resume label="tm_ensure_state"/>
        </do_if>
        <do_if value="this.$tm_abortMatch?">
          <return value="table[
            $Found = false,
            $BestTrade = null,
            $BestScore = 0,
            $TradeList = this.$tm_tradeList,
            $TradesEvaluated = 0,
            $TradesRejected = 0,
            $TradesRejectedRouteIllegal = 0,
            $TradesRejectedMk4CustomerPolicy = 0,
            $TradesRejectedMk4SupplierPolicy = 0,
            $TradesRejectedMk4TypePolicy = 0,
            $TradesRejectedMk4DemandGate = 0,
            $TradesRejectedMk4PriceCap = 0,
            $TradesRejectedDistance = 0
          ]"/>
        </do_if>
        <set_value name="$sellOffer" exact="this.$tm_matchSellOffers.{$si}"/>
        <set_value name="$ware" exact="@$sellOffer.ware"/>
        <!-- Supplier station: prefer game sell-offer seller (matches trade execution / MK4 validation). -->
        <set_value name="$buyStation" exact="null"/>
        <do_if value="$sellOffer?">
          <do_if value="$sellOffer.seller? and @$sellOffer.seller.exists">
            <set_value name="$buyStation" exact="@$sellOffer.seller"/>
          </do_if>
          <do_elseif value="$sellOffer.owner?">
            <set_value name="$buyStation" exact="@$sellOffer.owner"/>
          </do_elseif>
        </do_if>

        <!-- Per-ware early skip (flat list only; dual-axis uses per-bucket per-ware caps). -->
        <do_if value="not this.$tm_useDualAxisBuckets?">
          <do_if value="$ware? and this.$tm_tradesPerWare.{$ware}? and this.$tm_tradesPerWare.{$ware} ge $maxTradesPerWare">
            <continue/>
          </do_if>
        </do_if>

        <set_value name="$tmBuyListForWare" exact="[]"/>
        <do_if value="$mk42Priorities? and $ware? and this.$tm_buyIndexByWare? and this.$tm_buyIndexByWare.{$ware}?">
          <set_value name="$tmWareClassBuckets" exact="this.$tm_buyIndexByWare.{$ware}"/>
          <do_if value="$mk42Priorities.$Buildstorage? and $mk42Priorities.$Buildstorage gt 0 and $tmWareClassBuckets.$Buildstorage?">
            <do_all exact="$tmWareClassBuckets.$Buildstorage.count" counter="$bcixBs">
              <append_to_list name="$tmBuyListForWare" exact="$tmWareClassBuckets.$Buildstorage.{$bcixBs}"/>
            </do_all>
          </do_if>
          <do_if value="$mk42Priorities.$Stations? and $mk42Priorities.$Stations gt 0 and $tmWareClassBuckets.$Stations?">
            <do_all exact="$tmWareClassBuckets.$Stations.count" counter="$bcixSt">
              <append_to_list name="$tmBuyListForWare" exact="$tmWareClassBuckets.$Stations.{$bcixSt}"/>
            </do_all>
          </do_if>
          <do_if value="$mk42Priorities.$Aux? and $mk42Priorities.$Aux gt 0 and $tmWareClassBuckets.$Aux?">
            <do_all exact="$tmWareClassBuckets.$Aux.count" counter="$bcixAx">
              <append_to_list name="$tmBuyListForWare" exact="$tmWareClassBuckets.$Aux.{$bcixAx}"/>
            </do_all>
          </do_if>
          <do_if value="$mk42Priorities.$Carrier? and $mk42Priorities.$Carrier gt 0 and $tmWareClassBuckets.$Carrier?">
            <do_all exact="$tmWareClassBuckets.$Carrier.count" counter="$bcixCr">
              <append_to_list name="$tmBuyListForWare" exact="$tmWareClassBuckets.$Carrier.{$bcixCr}"/>
            </do_all>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$tmBuyListForWare" exact="if $ware? and this.$tm_buyOffersByWare? and this.$tm_buyOffersByWare.{$ware}? then this.$tm_buyOffersByWare.{$ware} else []"/>
        </do_else>
        <set_value name="$tmBuyLoopCount" exact="$tmBuyListForWare.count"/>
        <do_if value="$tmBuyLoopCount == 0">
          <continue/>
        </do_if>
        <do_all exact="$tmBuyLoopCount" counter="$bi">
          <set_value name="$buyOffer" exact="$tmBuyListForWare.{$bi}"/>
          <!-- Delivery customer: prefer game buy-offer buyer (matches trade execution / MK4 validation). -->
          <set_value name="$sellStation" exact="null"/>
          <do_if value="$buyOffer?">
            <do_if value="$buyOffer.buyer? and @$buyOffer.buyer.exists">
              <set_value name="$sellStation" exact="@$buyOffer.buyer"/>
            </do_if>
            <do_elseif value="$buyOffer.owner?">
              <set_value name="$sellStation" exact="@$buyOffer.owner"/>
            </do_elseif>
          </do_if>
          <!-- Per-ware trade cap (inner loop, flat list only). -->
          <do_if value="not this.$tm_useDualAxisBuckets?">
            <do_if value="$ware? and this.$tm_tradesPerWare.{$ware}? and this.$tm_tradesPerWare.{$ware} ge $maxTradesPerWare">
              <break/>
            </do_if>
          </do_if>
          <do_if value="$buyStation == null or $sellStation == null">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- MK3 'Ignore Player Pricing' companion filter: reject any trade whose delivery
               customer ($sellStation) is player-owned. The MK3 ship must sell only to NPCs. -->
          <do_if value="$excludePlayerBuyers and @$sellStation.isplayerowned">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- MK3 'Ignore Player Pricing' profit-semantics override:
               When the supplier is player-owned and the override is enabled, the player's
               production cost for this ware is treated as zero (the station produced it for
               "free" within the player's economy). Every credit the NPC customer pays is then
               pure income, so the negative/zero/min-profit rejections must be skipped for
               this pair, and gross income (sellPrice * amount) is used as the score basis.
               NPC->NPC pairs in the same scan continue to use the normal profit gates. -->
          <set_value name="$playerFreeSupplier" exact="$playerSupplierFreeProduction and @$buyStation.isplayerowned"/>

          <!-- MK4 supply hard policy (early gate):
               Delivery customer is $sellStation (game buy-offer owner). -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer">
            <do_if value="not @$sellStation.isplayerowned">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4-2 class-at-0 gate (delivery customer = buy-offer owner; cached at index time). -->
          <set_value name="$mk42CustomerClass" exact="'None'"/>
          <set_value name="$mk42ClassMultiplier" exact="1"/>
          <do_if value="$scoreMode == 'supply' and $mk42Priorities?">
            <do_if value="$buyOffer? and this.$tm_mk42MultByOffer? and this.$tm_mk42MultByOffer.{$buyOffer}?">
              <set_value name="$mk42CustomerClass" exact="if this.$tm_mk42ClassByOffer? and this.$tm_mk42ClassByOffer.{$buyOffer}? then this.$tm_mk42ClassByOffer.{$buyOffer} else 'None'"/>
              <set_value name="$mk42ClassMultiplier" exact="this.$tm_mk42MultByOffer.{$buyOffer}"/>
            </do_if>
            <do_else>
              <set_value name="$mk42ClsCustomer" exact="$sellStation"/>
              <set_value name="$mk42CustomerClass" exact="'None'"/>
              <set_value name="$mk42ClassMultiplier" exact="0"/>
              <do_if value="$mk42ClsCustomer? and $mk42ClsCustomer.exists">
                <do_if value="@$mk42ClsCustomer.isclass.buildstorage and @$mk42ClsCustomer.isplayerowned">
                  <set_value name="$mk42CustomerClass" exact="'Buildstorage'"/>
                </do_if>
                <do_elseif value="@$mk42ClsCustomer.isclass.station and @$mk42ClsCustomer.isplayerowned">
                  <set_value name="$mk42CustomerClass" exact="'Stations'"/>
                </do_elseif>
                <do_elseif value="@$mk42ClsCustomer.isclass.ship and @$mk42ClsCustomer.isplayerowned and @$mk42ClsCustomer.type == shiptype.carrier">
                  <set_value name="$mk42CustomerClass" exact="'Carrier'"/>
                </do_elseif>
                <do_elseif value="@$mk42ClsCustomer.isclass.ship and @$mk42ClsCustomer.isplayerowned and @$mk42ClsCustomer.primarypurpose == purpose.auxiliary">
                  <set_value name="$mk42CustomerClass" exact="'Aux'"/>
                </do_elseif>
                <do_elseif value="@$mk42ClsCustomer.isclass.buildstorage and $mk42ClsCustomer.base? and @$mk42ClsCustomer.base.isplayerowned">
                  <set_value name="$mk42CustomerClass" exact="'Buildstorage'"/>
                </do_elseif>
                <do_if value="$mk42CustomerClass == 'Buildstorage'">
                  <set_value name="$mk42ClassMultiplier" exact="if $mk42Priorities.$Buildstorage? then $mk42Priorities.$Buildstorage else 0"/>
                </do_if>
                <do_elseif value="$mk42CustomerClass == 'Stations'">
                  <set_value name="$mk42ClassMultiplier" exact="if $mk42Priorities.$Stations? then $mk42Priorities.$Stations else 0"/>
                </do_elseif>
                <do_elseif value="$mk42CustomerClass == 'Aux'">
                  <set_value name="$mk42ClassMultiplier" exact="if $mk42Priorities.$Aux? then $mk42Priorities.$Aux else 0"/>
                </do_elseif>
                <do_elseif value="$mk42CustomerClass == 'Carrier'">
                  <set_value name="$mk42ClassMultiplier" exact="if $mk42Priorities.$Carrier? then $mk42Priorities.$Carrier else 0"/>
                </do_elseif>
              </do_if>
            </do_else>
            <do_if value="$mk42ClassMultiplier le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk42Class" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4 supplier policy (early gate):
               Supplier station is $buyStation (game sell-offer owner). -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer">
            <do_if value="not $mk4AllowPlayerSuppliers and @$buyStation.isplayerowned">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="not $mk4AllowAiSuppliers and not @$buyStation.isplayerowned">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4-2 dual-axis per-bucket per-ware cap (after class + supplier gates). -->
          <set_value name="$tmBucketSrc" exact="if @$buyStation.isplayerowned then 'Player' else 'Npc'"/>
          <set_value name="$tmBucketKey" exact="null"/>
          <do_if value="$mk42CustomerClass == 'Buildstorage'">
            <set_value name="$tmBucketKey" exact="if $tmBucketSrc == 'Player' then 'BS_P' else 'BS_N'"/>
          </do_if>
          <do_elseif value="$mk42CustomerClass == 'Stations'">
            <set_value name="$tmBucketKey" exact="if $tmBucketSrc == 'Player' then 'ST_P' else 'ST_N'"/>
          </do_elseif>
          <do_elseif value="$mk42CustomerClass == 'Aux'">
            <set_value name="$tmBucketKey" exact="if $tmBucketSrc == 'Player' then 'AX_P' else 'AX_N'"/>
          </do_elseif>
          <do_elseif value="$mk42CustomerClass == 'Carrier'">
            <set_value name="$tmBucketKey" exact="if $tmBucketSrc == 'Player' then 'CR_P' else 'CR_N'"/>
          </do_elseif>
          <do_if value="this.$tm_useDualAxisBuckets? and $ware? and $tmBucketKey?">
            <set_value name="$tmBucketWareCapHit" exact="false"/>
            <do_if value="$tmBucketKey == 'BS_P'">
              <do_if value="this.$tm_tradesPerBucketWare.$BS_P.{$ware}? and this.$tm_tradesPerBucketWare.$BS_P.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_if>
            <do_elseif value="$tmBucketKey == 'BS_N'">
              <do_if value="this.$tm_tradesPerBucketWare.$BS_N.{$ware}? and this.$tm_tradesPerBucketWare.$BS_N.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'ST_P'">
              <do_if value="this.$tm_tradesPerBucketWare.$ST_P.{$ware}? and this.$tm_tradesPerBucketWare.$ST_P.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'ST_N'">
              <do_if value="this.$tm_tradesPerBucketWare.$ST_N.{$ware}? and this.$tm_tradesPerBucketWare.$ST_N.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'AX_P'">
              <do_if value="this.$tm_tradesPerBucketWare.$AX_P.{$ware}? and this.$tm_tradesPerBucketWare.$AX_P.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'AX_N'">
              <do_if value="this.$tm_tradesPerBucketWare.$AX_N.{$ware}? and this.$tm_tradesPerBucketWare.$AX_N.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'CR_P'">
              <do_if value="this.$tm_tradesPerBucketWare.$CR_P.{$ware}? and this.$tm_tradesPerBucketWare.$CR_P.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'CR_N'">
              <do_if value="this.$tm_tradesPerBucketWare.$CR_N.{$ware}? and this.$tm_tradesPerBucketWare.$CR_N.{$ware} ge $maxTradesPerWare">
                <set_value name="$tmBucketWareCapHit" exact="true"/>
              </do_if>
            </do_elseif>
            <do_if value="$tmBucketWareCapHit">
              <continue/>
            </do_if>
          </do_if>

          <!-- Trade rules feasibility (player-owned stations only): pairs that cannot execute are
               not candidates. Supplier priority sliders only affect score, not whether a pair exists. -->
          <do_if value="not $ignoreTradeRules">
            <set_value name="$tmPlayerStationInvolved" exact="false"/>
            <do_if value="$buyStation? and @$buyStation.exists">
              <do_if value="@$buyStation.isplayerowned">
                <set_value name="$tmPlayerStationInvolved" exact="true"/>
              </do_if>
              <do_elseif value="@$buyStation.isclass.buildstorage and $buyStation.base? and @$buyStation.base.exists and @$buyStation.base.isplayerowned">
                <set_value name="$tmPlayerStationInvolved" exact="true"/>
              </do_elseif>
            </do_if>
            <do_if value="not $tmPlayerStationInvolved and $sellStation? and @$sellStation.exists">
              <do_if value="@$sellStation.isplayerowned">
                <set_value name="$tmPlayerStationInvolved" exact="true"/>
              </do_if>
              <do_elseif value="@$sellStation.isclass.buildstorage and $sellStation.base? and @$sellStation.base.exists and @$sellStation.base.isplayerowned">
                <set_value name="$tmPlayerStationInvolved" exact="true"/>
              </do_elseif>
            </do_if>
            <do_if value="$tmPlayerStationInvolved">
              <do_if value="$buyOffer? and @$buyOffer.exists and $buyStation? and @$buyStation.exists and not $buyOffer.cantradewith.{$buyStation}">
                <set_value name="this.$tm_tradesRejected" operation="add"/>
                <set_value name="this.$tm_tradesRejectedTradeRules" operation="add"/>
                <continue/>
              </do_if>
              <do_if value="$sellOffer? and @$sellOffer.exists and $sellStation? and @$sellStation.exists and not $sellOffer.cantradewith.{$sellStation}">
                <set_value name="this.$tm_tradesRejected" operation="add"/>
                <set_value name="this.$tm_tradesRejectedTradeRules" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
          </do_if>

          <!-- MK4-2 build-storage-only (slider-derived) / MK4 legacy BSO: BS delivery within jumpDistanceCoverage; BS supplier legs blocked. -->
          <set_value name="$mk42BuildStorageOnlyMode" exact="false"/>
          <do_if value="$mk42Priorities? and $mk42Priorities.$Buildstorage? and $mk42Priorities.$Buildstorage gt 0 and (not $mk42Priorities.$Stations? or $mk42Priorities.$Stations == 0) and (not $mk42Priorities.$Aux? or $mk42Priorities.$Aux == 0) and (not $mk42Priorities.$Carrier? or $mk42Priorities.$Carrier == 0)">
            <set_value name="$mk42BuildStorageOnlyMode" exact="true"/>
          </do_if>
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer and ($mk42BuildStorageOnlyMode or $mk4BuildStorageOnlyMode)">
            <do_if value="$buyStation.isclass.buildstorage">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="not $sellStation.isclass.buildstorage">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" operation="add"/>
              <continue/>
            </do_if>
            <!-- BS-only delivery scope: player build storage within jumpDistanceCoverage from home. -->
            <set_value name="$mk4BsoCoverageMax" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
            <set_value name="$mk4BsoInScope" exact="false"/>
            <set_value name="$mk4BsoDist" exact="if $homeSector? and $sellStation? and $sellStation.sector? then $homeSector.gatedistance.{$sellStation.sector} else -1"/>
            <do_if value="$mk4BsoDist ge 0 and ($mk4BsoCoverageMax le 0 or $mk4BsoDist le $mk4BsoCoverageMax)">
              <set_value name="$mk4BsoInScope" exact="true"/>
            </do_if>
            <do_if value="not $mk4BsoInScope">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4 ware-type policy gate (evaluated against customer station context):
               - Resources: pure resources (non-intermediate)
               - Intermediates: intermediate wares and products
               - Tradewares: station tradewares -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer and $sellStation? and $ware? and ($mk42CustomerClass != 'Buildstorage' and (not $sellStation.isclass.buildstorage or $ignoreBuildStorage))">
            <set_value name="$mk4IsTradeWare" exact="$sellStation.tradewares.{$ware}.exists"/>
            <set_value name="$mk4IsResource" exact="$sellStation.resources.{$ware}.exists"/>
            <set_value name="$mk4IsProduct" exact="$sellStation.products.{$ware}.exists"/>
            <set_value name="$mk4IsIntermediate" exact="false"/>
            <do_if value="$sellStation.resources.{$ware}.exists and @$sellStation.resources.{$ware}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <do_if value="$sellStation.products.{$ware}.exists and @$sellStation.products.{$ware}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <set_value name="$mk4IsPureResource" exact="$mk4IsResource and not $mk4IsIntermediate"/>
            <set_value name="$mk4IsIntermediateOrProduct" exact="$mk4IsIntermediate or $mk4IsProduct"/>
            <set_value name="$mk4HasKnownType" exact="$mk4IsTradeWare or $mk4IsResource or $mk4IsProduct"/>
            <set_value name="$mk4AllowedByType" exact="false"/>
            <do_if value="$mk4IsTradeWare and $mk4AllowTradewares">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsPureResource and $mk4AllowResources">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsIntermediateOrProduct and $mk4AllowIntermediates">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="$mk4HasKnownType and not $mk4AllowedByType">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4TypePolicy" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Legacy MK4 v1 class exclusions (skipped when MK4-2 priorities drive classification). -->
          <do_if value="not $mk42Priorities?">
            <do_if value="$ignoreBuildStorage">
              <do_if value="$buyStation.isclass.buildstorage or $sellStation.isclass.buildstorage">
                <set_value name="this.$tm_tradesRejected" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
            <do_if value="$ignoreCarrierAux">
              <do_if value="($buyStation.isclass.ship and ($buyStation.type == shiptype.carrier or $buyStation.type == shiptype.resupplier)) or ($sellStation.isclass.ship and ($sellStation.type == shiptype.carrier or $sellStation.type == shiptype.resupplier))">
                <set_value name="this.$tm_tradesRejected" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
          </do_if>

          <!-- MK4 supply early economics gates: price cap + per-leg distance before dock/clamp (perf). -->
          <set_value name="$unitProfit" exact="$buyOffer.unitprice - $sellOffer.unitprice"/>
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer and $unitProfit lt 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedMk4PriceCap" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$maxDistanceBuyLeg" exact="if $maxDistanceBuy? and $maxDistanceBuy gt 0 then $maxDistanceBuy else $maxDistance"/>
          <set_value name="$maxDistanceSellLeg" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
          <set_value name="$distBuy" exact="$homeSector.gatedistance.{$buyStation}"/>
          <do_if value="$distBuy lt 0 or $distBuy gt $maxDistanceBuyLeg">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$distSell" exact="$homeSector.gatedistance.{$sellStation}"/>
          <do_if value="$distSell lt 0 or $distSell gt $maxDistanceSellLeg">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$scoreMode == 'supply' and $backtrackTolerance? and $backtrackTolerance ge 0 and (not $maxDistanceBuy? or $maxDistanceBuy le 0)">
            <set_value name="$maxSupplierDistance" exact="$maxDistanceSellLeg + $backtrackTolerance"/>
            <do_if value="$distBuy gt $maxSupplierDistance">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Dock feasibility (vanilla order.dock.xml: trading dock on destination).
               Build-storage legs use $buyOffer.buyer â€” not the parent station. -->
          <do_if value="$scoreMode == 'supply'">
            <run_script name="'lib.gt.dockcheck'" result="$tmBuyDockResult">
              <param name="ship" value="$ship"/>
              <param name="station" value="$buyStation"/>
              <param name="purpose" value="'trade'"/>
              <param name="useMemo" value="true"/>
            </run_script>
            <run_script name="'lib.gt.dockcheck'" result="$tmSellDockResult">
              <param name="ship" value="$ship"/>
              <param name="station" value="$sellStation"/>
              <param name="purpose" value="'trade'"/>
              <param name="useMemo" value="true"/>
            </run_script>
            <do_if value="not $tmBuyDockResult.$CanDock or not $tmSellDockResult.$CanDock">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Shared amount semantics:
               Prefer per-ship effective offer amounts (offeramount.{ship}) to match vanilla
               trade resolution, especially for internal/no-money flows. Fallback to raw amount
               when offeramount is unavailable. -->
          <set_value name="$sellOfferAmount" exact="0"/>
          <do_if value="$sellOffer.offeramount.{$ship}?">
            <set_value name="$sellOfferAmount" exact="$sellOffer.offeramount.{$ship}"/>
          </do_if>
          <do_elseif value="$sellOffer.amount?">
            <set_value name="$sellOfferAmount" exact="$sellOffer.amount"/>
          </do_elseif>
          <!-- Diagnose parity: offeramount.{ship} may exist but be 0 (build storage / internal flows). -->
          <do_if value="$sellOfferAmount le 0 and $sellOffer.amount? and $sellOffer.amount gt 0">
            <set_value name="$sellOfferAmount" exact="$sellOffer.amount"/>
          </do_if>
          <set_value name="$buyOfferAmount" exact="0"/>
          <do_if value="$buyOffer.offeramount.{$ship}?">
            <set_value name="$buyOfferAmount" exact="$buyOffer.offeramount.{$ship}"/>
          </do_if>
          <do_elseif value="$buyOffer.amount?">
            <set_value name="$buyOfferAmount" exact="$buyOffer.amount"/>
          </do_elseif>
          <do_if value="$buyOfferAmount le 0 and $buyOffer.amount? and $buyOffer.amount gt 0">
            <set_value name="$buyOfferAmount" exact="$buyOffer.amount"/>
          </do_if>
          <do_if value="$buyOfferAmount le 0 and $sellStation? and $sellStation.exists and $ware?">
            <!-- Target-count demand fallback (mirrors gt_context_diagnose pair eval for all modes). -->
            <set_value name="$buyOfferDemandFallback" exact="[0, $sellStation.cargo.{$ware}.target - $sellStation.cargo.{$ware}.count].max"/>
            <do_if value="$buyOfferDemandFallback gt 0">
              <set_value name="$buyOfferAmount" exact="$buyOfferDemandFallback"/>
            </do_if>
          </do_if>

          <!-- Demand reservation gate (all modes):
               Subtract incoming vanilla reservations from destination demand before scoring.
               Also subtract in-flight GT reservations for the same destination offer.
               If effective need is exhausted, skip this ware pair early so saturated wares
               do not dominate top candidates and storage is not overfilled.
               Baseline uses max(per-ship offeramount, raw offer.amount, cargo deficit) because
               a single offer slice can understate build-storage / station need while
               get_ware_reservation is station-wide for the ware. -->
          <set_value name="$demandBaseline" exact="$buyOfferAmount"/>
          <do_if value="$buyOffer? and $buyOffer.amount? and $buyOffer.amount gt $demandBaseline">
            <set_value name="$demandBaseline" exact="$buyOffer.amount"/>
          </do_if>
          <do_if value="$sellStation? and $sellStation.exists and $ware?">
            <set_value name="$cargoDeficit" exact="[0, $sellStation.cargo.{$ware}.target - $sellStation.cargo.{$ware}.count].max"/>
            <do_if value="$cargoDeficit gt $demandBaseline">
              <set_value name="$demandBaseline" exact="$cargoDeficit"/>
            </do_if>
          </do_if>
          <do_if value="$sellStation? and $sellStation.exists and $ware?">
            <set_value name="$incomingReservedAmount" exact="0"/>
            <get_ware_reservation object="$sellStation" ware="$ware" type="sell" virtual="false" result="$incomingReservedAmount"/>
            <!-- GT in-flight reservation demand gate:
                 subtract fleet pre-selection reservations for the same destination offer. -->
            <set_value name="$gtIncomingReservedAmount" exact="0"/>
            <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$buyOffer}?">
              <set_value name="$gtResData" exact="global.$GT_Reservations.{$buyOffer}"/>
              <do_if value="$gtResData.$Until? and player.age lt @$gtResData.$Until">
                <do_if value="not $gtResData.$Ship? or @$gtResData.$Ship != $ship">
                  <set_value name="$gtResAmount" exact="0"/>
                  <do_if value="$gtResData.$Amount? and @$gtResData.$Amount gt 0">
                    <set_value name="$gtResAmount" exact="$gtResData.$Amount"/>
                  </do_if>
                  <do_else>
                    <set_value name="$gtResAmount" exact="1"/>
                  </do_else>
                  <set_value name="$gtIncomingReservedAmount" exact="$gtIncomingReservedAmount + $gtResAmount"/>
                </do_if>
              </do_if>
            </do_if>
            <set_value name="$effectiveBuyNeedAmount" exact="[$demandBaseline - $incomingReservedAmount - $gtIncomingReservedAmount, 0].max"/>
            <do_if value="$effectiveBuyNeedAmount le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer">
                <set_value name="this.$tm_tradesRejectedMk4DemandGate" operation="add"/>
              </do_if>
              <continue/>
            </do_if>
            <set_value name="$buyOfferAmount" exact="$effectiveBuyNeedAmount"/>
          </do_if>

          <!-- UNIVERSAL CACHE BASIS:
               Do not bind cached trade amount/score to the writer ship's free cargo.
               Cache entries should represent station-side opportunity; per-ship execution
               amount is resolved later via clamp_trade_amount in order.trade.galaxytrader. -->
          <set_value name="$tradeAmount" exact="[$sellOfferAmount, $buyOfferAmount].min"/>
          <set_value name="$stationDemandMax" exact="$tradeAmount"/>
          <do_if value="$tradeAmount le 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- clamp_trade_amount preview (mirrors order.trade.galaxytrader trade_found).
               Rejects broker/warehouse offers that list amount/offeramount but have no
               exportable seller stock at execution time.
               Seller/buyer resolution MUST match trade_found validation: prefer offer.seller
               when seller? is set â€” do NOT gate on .exists or fall back to owner while seller?
               is set (trading-station brokers clamp to seller_cargo=0 at validation). -->
          <set_value name="$tmClampBuySeller" exact="null"/>
          <do_if value="$sellOffer?">
            <do_if value="$sellOffer.seller?">
              <set_value name="$tmClampBuySeller" exact="@$sellOffer.seller"/>
            </do_if>
            <do_if value="$tmClampBuySeller == null and $sellOffer.owner?">
              <set_value name="$tmClampBuySeller" exact="@$sellOffer.owner"/>
            </do_if>
          </do_if>
          <do_if value="$tmClampBuySeller != null">
            <set_value name="$tmClampPreview" exact="$tradeAmount"/>
            <set_value name="$tmClampReason" exact="null"/>
            <set_value name="$tmTradePartner" exact="if this.assignedcontrolled? then this.assignedcontrolled else $ship"/>
            <clamp_trade_amount trade="$sellOffer" amount="$tmClampPreview" buyer="$tmTradePartner" seller="$tmClampBuySeller" result="$tmClampPreview" reason="$tmClampReason"/>
            <do_if value="not $tmClampPreview? or $tmClampPreview le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
            <set_value name="$tradeAmount" exact="$tmClampPreview"/>
            <set_value name="$sellOfferAmount" exact="[$sellOfferAmount, $tradeAmount].min"/>
          </do_if>
          <do_else>
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_else>
          <set_value name="$tmClampSellBuyer" exact="null"/>
          <do_if value="$buyOffer?">
            <do_if value="$buyOffer.buyer?">
              <set_value name="$tmClampSellBuyer" exact="@$buyOffer.buyer"/>
            </do_if>
            <do_if value="$tmClampSellBuyer == null and $buyOffer.owner?">
              <set_value name="$tmClampSellBuyer" exact="@$buyOffer.owner"/>
            </do_if>
          </do_if>
          <do_if value="$tmClampSellBuyer != null">
            <set_value name="$tmSellClampPreview" exact="$tradeAmount"/>
            <set_value name="$tmSellClampReason" exact="null"/>
            <clamp_trade_amount trade="$buyOffer" amount="$tmSellClampPreview" buyer="$tmClampSellBuyer" result="$tmSellClampPreview" reason="$tmSellClampReason"/>
            <do_if value="not $tmSellClampPreview? or $tmSellClampPreview le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
            <set_value name="$tradeAmount" exact="[$tradeAmount, $tmSellClampPreview].min"/>
            <set_value name="$buyOfferAmount" exact="[$buyOfferAmount, $tradeAmount].min"/>
          </do_if>
          <do_else>
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_else>
          <do_if value="$tradeAmount le 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <set_value name="$unitProfit" exact="$buyOffer.unitprice - $sellOffer.unitprice"/>
          <!-- Default sell-mode behavior requires positive unit profit.
               MK1 can opt in to allow zero-profit station-price sells.
               MK3 'Ignore Player Pricing' bypasses both gates for player-supplier trades
               (cost is virtual zero, so any non-negative sell price is income). -->
          <do_if value="$scoreMode == 'sell' and not $playerFreeSupplier and $unitProfit lt 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$scoreMode == 'sell' and not $allowZeroProfitSell and not $playerFreeSupplier and $unitProfit == 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- Optional route-illegal filter: contraband only â€” legal wares skip jump-path probe. -->
          <do_if value="$allowIllegal and $enforceRouteIllegalLegality and @$ware.illegal gt 0">
            <run_script name="'lib.gt.pathfinding'" result="$routeLegality">
              <param name="mode" value="'route_legality'"/>
              <param name="ship" value="$ship"/>
              <param name="homeSector" value="$homeSector"/>
              <param name="blacklistGroup" value="$blacklistGroup"/>
              <param name="allowIllegal" value="$allowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
              <param name="startSector" value="$ship.sector"/>
              <param name="buySector" value="$buyStation.sector"/>
              <param name="sellSector" value="$sellStation.sector"/>
              <param name="ware" value="$ware"/>
            </run_script>
            <do_if value="not $routeLegality.$IsLegal">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedRouteIllegal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
          <!-- Route-aware score distance: homeâ†’buy + buyâ†’sell (territorial gates above stay per-leg). -->
          <set_value name="$buySector" exact="$buyStation.sector"/>
          <set_value name="$sellSector" exact="$sellStation.sector"/>
          <set_value name="$routeLeg" exact="0"/>
          <do_if value="$buySector != $sellSector">
            <do_if value="$blacklistGroup? and $blacklistGroup != null and $ship?">
              <set_value name="$routeLeg" exact="$buySector.gatedistance.{$sellSector}.{$blacklistGroup}.{$ship}"/>
            </do_if>
            <do_else>
              <set_value name="$routeLeg" exact="$buySector.gatedistance.{$sellSector}"/>
            </do_else>
          </do_if>
          <do_if value="$routeLeg lt 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$distance" exact="$distBuy + $routeLeg"/>

          <set_value name="$distanceFactor" exact="1.0 + ($distance * $distancePenalty)"/>
          <set_value name="$score" exact="0"/>
          <set_value name="$volumePerUnit" exact="if $ware? and $ware.volume? then $ware.volume else 1"/>

          <do_if value="$scoreMode == 'supply'">
            <!-- MK4-2 Â§4.1.1: MK4-Spec urgency Ã— ship-agnostic amount Ã· route distance (price-neutral). -->
            <set_value name="$mk42Target" exact="1"/>
            <set_value name="$mk42Current" exact="0"/>
            <do_if value="$sellStation? and $sellStation.exists and $ware?">
              <set_value name="$mk42Target" exact="[$sellStation.cargo.{$ware}.target, 1].max"/>
              <set_value name="$mk42Current" exact="$sellStation.cargo.{$ware}.count"/>
            </do_if>
            <set_value name="$mk42Deficit" exact="[$mk42Target - $mk42Current, 0].max"/>
            <set_value name="$mk42FillRatio" exact="if $mk42Target gt 0 then ($mk42Current / $mk42Target) else 0"/>
            <set_value name="$mk42DeficitPct" exact="if $mk42Target gt 0 then (($mk42Deficit * 100) / $mk42Target) else 0"/>
            <set_value name="$mk42BuildBonus" exact="0"/>
            <do_if value="@$sellStation.isclass.buildstorage">
              <set_value name="$mk42BuildBonus" exact="20"/>
            </do_if>
            <set_value name="$mk42CriticalBonus" exact="0"/>
            <do_if value="$mk42FillRatio lt 0.10">
              <set_value name="$mk42CriticalBonus" exact="15"/>
            </do_if>
            <set_value name="$urgencyScore" exact="$mk42DeficitPct + $mk42BuildBonus + $mk42CriticalBonus"/>
            <set_value name="$baseSupplyScore" exact="($urgencyScore * $stationDemandMax) / $distanceFactor"/>
            <set_value name="$score" exact="$baseSupplyScore"/>
            <!-- Supplier-side player/faction preference is applied in lib.gt.mk42.score.trades via the
                 buyFromPlayer / buyFromFaction priority sliders (replaces the old playerBuyMod knob). -->
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and this.$tm_supplyScoreDiagCount lt 8">
              <debug_text text="'[GT-TradeMatch] ' + $ship.idcode + ': mk42-supply-score ware=' + $ware + ' urgency=' + $urgencyScore + ' demandMax=' + $stationDemandMax + ' distFactor=' + $distanceFactor + ' base=' + $baseSupplyScore + ' class=' + $mk42CustomerClass + ' src=' + $tmBucketSrc + ' mult=' + $mk42ClassMultiplier" chance="100"/>
              <set_value name="this.$tm_supplyScoreDiagCount" operation="add"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- MK3 'Ignore Player Pricing': for player suppliers, treat the supplier-side
                 cost as zero so the full sell price counts as gain. This affects both the
                 min-profit/ROI gate and the score basis. NPC suppliers use unmodified math. -->
            <do_if value="$playerFreeSupplier">
              <set_value name="$grossProfit" exact="$buyOffer.unitprice * $tradeAmount"/>
              <set_value name="$roi" exact="if $buyOffer.unitprice gt 0 then 100 else 0"/>
            </do_if>
            <do_else>
              <set_value name="$grossProfit" exact="$unitProfit * $tradeAmount"/>
              <set_value name="$roi" exact="if $sellOffer.unitprice gt 0 then ($unitProfit * 100) / $sellOffer.unitprice else 0"/>
            </do_else>
            <do_if value="not $playerFreeSupplier and ($grossProfit lt $minAbsoluteProfit or $roi lt $minROI)">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
            <!-- Keep score numeric (credits) to avoid float*money conversion warnings in bonuses. -->
            <set_value name="$grossProfitCr" exact="($grossProfit / 1Cr)i"/>
            <set_value name="$score" exact="$grossProfitCr / $distanceFactor"/>

            <!-- Faction priority bonus: boost score for trades involving player-owned stations -->
            <do_if value="$factionPriority gt 0">
              <set_value name="$factionBonus" exact="1.0"/>
              <do_if value="$buyStation.isplayerowned or $sellStation.isplayerowned">
                <set_value name="$factionBonus" exact="1.0 + ($factionPriority * 0.1)"/>
              </do_if>
              <set_value name="$score" exact="$score * $factionBonus"/>
            </do_if>
          </do_else>

          <!-- MK3 'Ignore Player Pricing' profit reporting:
               When the supplier is player-owned and the override is enabled, the player's
               wallet net of the trade is the full sell income (the buy-leg credits flow
               within the player's own economy). Report Profit / UnitProfit accordingly so
               the queued-trade logbook entry shows the actual gain to the player rather
               than the negative ship-wallet delta. The $PlayerFreeSupplier tag lets the
               logging cue switch to a buy-price-suppressed message format. -->
          <set_value name="$reportedUnitProfit" exact="if $playerFreeSupplier then $buyOffer.unitprice else $unitProfit"/>
          <set_value name="$reportedProfit" exact="$reportedUnitProfit * $tradeAmount"/>

          <set_value name="$trade" exact="table[
            $Ware = $ware,
            $CargoWareTransport = if $ware? then @$ware.waretransport else null,
            $BuyOffer = $sellOffer,
            $SellOffer = $buyOffer,
            $Amount = $tradeAmount,
            $OfferMaxAmount = $tradeAmount,
            $BuyOfferAmount = $sellOfferAmount,
            $SellOfferAmount = $buyOfferAmount,
            $Score = $score,
            $baseSupplyScore = if $scoreMode == 'supply' and $baseSupplyScore? then $baseSupplyScore else $score,
            $urgencyScore = if $scoreMode == 'supply' and $urgencyScore? then $urgencyScore else 0,
            $StationDemandMax = if $scoreMode == 'supply' and $stationDemandMax? then $stationDemandMax else $tradeAmount,
            $CustomerClass = if $scoreMode == 'supply' then $mk42CustomerClass else 'None',
            $SupplierSource = if $scoreMode == 'supply' and this.$tm_useDualAxisBuckets? then $tmBucketSrc else 'Any',
            $ClassMultiplier = if $scoreMode == 'supply' then $mk42ClassMultiplier else 1,
            $BuyStation = $buyStation,
            $SellStation = $sellStation,
            $SellStationBase = if $sellStation? and $sellStation.isclass.buildstorage and $sellStation.base? then @$sellStation.base else null,
            $BuySector = $buyStation.sector,
            $SellSector = $sellStation.sector,
            $Distance = $distance,
            $HomeToBuyDistance = $distBuy,
            $HomeToSellDistance = $distSell,
            $RouteDistance = $routeLeg,
            $UnitProfit = $reportedUnitProfit,
            $BuyPrice = $sellOffer.unitprice,
            $SellPrice = $buyOffer.unitprice,
            $ProfitPerUnit = $reportedUnitProfit,
            $VolumePerUnit = $volumePerUnit,
            $Profit = $reportedProfit,
            $PlayerFreeSupplier = $playerFreeSupplier
          ]"/>
          <do_if value="this.$tm_useDualAxisBuckets? and $tmBucketKey?">
            <do_if value="$tmBucketKey == 'BS_P'">
              <append_to_list name="this.$tm_tradesByBucket.$BS_P" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$BS_P.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$BS_P.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$BS_P.{$ware}" operation="add"/>
            </do_if>
            <do_elseif value="$tmBucketKey == 'BS_N'">
              <append_to_list name="this.$tm_tradesByBucket.$BS_N" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$BS_N.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$BS_N.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$BS_N.{$ware}" operation="add"/>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'ST_P'">
              <append_to_list name="this.$tm_tradesByBucket.$ST_P" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$ST_P.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$ST_P.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$ST_P.{$ware}" operation="add"/>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'ST_N'">
              <append_to_list name="this.$tm_tradesByBucket.$ST_N" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$ST_N.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$ST_N.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$ST_N.{$ware}" operation="add"/>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'AX_P'">
              <append_to_list name="this.$tm_tradesByBucket.$AX_P" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$AX_P.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$AX_P.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$AX_P.{$ware}" operation="add"/>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'AX_N'">
              <append_to_list name="this.$tm_tradesByBucket.$AX_N" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$AX_N.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$AX_N.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$AX_N.{$ware}" operation="add"/>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'CR_P'">
              <append_to_list name="this.$tm_tradesByBucket.$CR_P" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$CR_P.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$CR_P.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$CR_P.{$ware}" operation="add"/>
            </do_elseif>
            <do_elseif value="$tmBucketKey == 'CR_N'">
              <append_to_list name="this.$tm_tradesByBucket.$CR_N" exact="$trade"/>
              <do_if value="not this.$tm_tradesPerBucketWare.$CR_N.{$ware}?">
                <set_value name="this.$tm_tradesPerBucketWare.$CR_N.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerBucketWare.$CR_N.{$ware}" operation="add"/>
            </do_elseif>
          </do_if>
          <do_else>
            <append_to_list name="this.$tm_tradeList" exact="$trade"/>
            <!-- Track per-ware trade count (flat list mode). -->
            <do_if value="$ware?">
              <do_if value="not this.$tm_tradesPerWare.{$ware}?">
                <set_value name="this.$tm_tradesPerWare.{$ware}" exact="0"/>
              </do_if>
              <set_value name="this.$tm_tradesPerWare.{$ware}" operation="add"/>
            </do_if>
          </do_else>
          <set_value name="this.$tm_tradesEvaluated" operation="add"/>

          <do_if value="$score gt this.$tm_bestScore">
            <set_value name="this.$tm_bestScore" exact="$score"/>
            <set_value name="this.$tm_bestTrade" exact="$trade"/>
          </do_if>
        </do_all>

        <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after each sell-offer loop (blocking action index 1; match state on this.$tm_*)"/>
        <!-- Save/load only: rebuild offer scratch if library state was dropped mid-wait (never on normal yield). -->
        <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
          <resume label="tm_ensure_state"/>
        </do_if>
      </do_all>

      <!-- MK4-2 dual-axis bucket merge: top-K per enabled class x source, then flat TradeList for score.trades. -->
      <do_if value="this.$tm_useDualAxisBuckets?">
        <create_list name="this.$tm_tradeList"/>
        <set_value name="this.$tm_bucketPreBsP" exact="0"/>
        <set_value name="this.$tm_bucketPreBsN" exact="0"/>
        <set_value name="this.$tm_bucketPreStP" exact="0"/>
        <set_value name="this.$tm_bucketPreStN" exact="0"/>
        <set_value name="this.$tm_bucketPreAxP" exact="0"/>
        <set_value name="this.$tm_bucketPreAxN" exact="0"/>
        <set_value name="this.$tm_bucketPreCrP" exact="0"/>
        <set_value name="this.$tm_bucketPreCrN" exact="0"/>
        <set_value name="this.$tm_bucketOutBsP" exact="0"/>
        <set_value name="this.$tm_bucketOutBsN" exact="0"/>
        <set_value name="this.$tm_bucketOutStP" exact="0"/>
        <set_value name="this.$tm_bucketOutStN" exact="0"/>
        <set_value name="this.$tm_bucketOutAxP" exact="0"/>
        <set_value name="this.$tm_bucketOutAxN" exact="0"/>
        <set_value name="this.$tm_bucketOutCrP" exact="0"/>
        <set_value name="this.$tm_bucketOutCrN" exact="0"/>
        <!-- Buildstorage -->
        <do_if value="$mk42Priorities.$Buildstorage? and $mk42Priorities.$Buildstorage gt 0 and $mk4AllowPlayerSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$BS_P" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreBsP" exact="this.$tm_tradesByBucket.$BS_P.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$BS_P.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$BS_P.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutBsP" exact="$tmMergeCap"/>
        </do_if>
        <do_if value="$mk42Priorities.$Buildstorage? and $mk42Priorities.$Buildstorage gt 0 and $mk4AllowAiSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$BS_N" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreBsN" exact="this.$tm_tradesByBucket.$BS_N.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$BS_N.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$BS_N.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutBsN" exact="$tmMergeCap"/>
        </do_if>
        <!-- Stations -->
        <do_if value="$mk42Priorities.$Stations? and $mk42Priorities.$Stations gt 0 and $mk4AllowPlayerSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$ST_P" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreStP" exact="this.$tm_tradesByBucket.$ST_P.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$ST_P.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$ST_P.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutStP" exact="$tmMergeCap"/>
        </do_if>
        <do_if value="$mk42Priorities.$Stations? and $mk42Priorities.$Stations gt 0 and $mk4AllowAiSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$ST_N" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreStN" exact="this.$tm_tradesByBucket.$ST_N.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$ST_N.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$ST_N.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutStN" exact="$tmMergeCap"/>
        </do_if>
        <!-- Aux -->
        <do_if value="$mk42Priorities.$Aux? and $mk42Priorities.$Aux gt 0 and $mk4AllowPlayerSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$AX_P" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreAxP" exact="this.$tm_tradesByBucket.$AX_P.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$AX_P.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$AX_P.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutAxP" exact="$tmMergeCap"/>
        </do_if>
        <do_if value="$mk42Priorities.$Aux? and $mk42Priorities.$Aux gt 0 and $mk4AllowAiSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$AX_N" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreAxN" exact="this.$tm_tradesByBucket.$AX_N.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$AX_N.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$AX_N.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutAxN" exact="$tmMergeCap"/>
        </do_if>
        <!-- Carrier -->
        <do_if value="$mk42Priorities.$Carrier? and $mk42Priorities.$Carrier gt 0 and $mk4AllowPlayerSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$CR_P" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreCrP" exact="this.$tm_tradesByBucket.$CR_P.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$CR_P.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$CR_P.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutCrP" exact="$tmMergeCap"/>
        </do_if>
        <do_if value="$mk42Priorities.$Carrier? and $mk42Priorities.$Carrier gt 0 and $mk4AllowAiSuppliers gt 0">
          <sort_list list="this.$tm_tradesByBucket.$CR_N" sortbyvalue="loop.element.$baseSupplyScore" sortdescending="true"/>
          <set_value name="this.$tm_bucketPreCrN" exact="this.$tm_tradesByBucket.$CR_N.count"/>
          <set_value name="$tmMergeCap" exact="[this.$tm_tradesByBucket.$CR_N.count, this.$tm_maxTradesPerBucket].min"/>
          <do_all exact="$tmMergeCap" counter="$tmMi">
            <append_to_list name="this.$tm_tradeList" exact="this.$tm_tradesByBucket.$CR_N.{$tmMi}"/>
          </do_all>
          <set_value name="this.$tm_bucketOutCrN" exact="$tmMergeCap"/>
        </do_if>
        <set_value name="this.$tm_bestTrade" exact="null"/>
        <set_value name="this.$tm_bestScore" exact="0"/>
        <do_all exact="this.$tm_tradeList.count" counter="$tmBix">
          <set_value name="$tmBestCand" exact="this.$tm_tradeList.{$tmBix}"/>
          <do_if value="$tmBestCand.$Score gt this.$tm_bestScore">
            <set_value name="this.$tm_bestScore" exact="$tmBestCand.$Score"/>
            <set_value name="this.$tm_bestTrade" exact="$tmBestCand"/>
          </do_if>
        </do_all>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeMatch] ' + $ship.idcode + ': dual-axis-buckets pre=BS_P=' + this.$tm_bucketPreBsP + '/BS_N=' + this.$tm_bucketPreBsN + '/ST_P=' + this.$tm_bucketPreStP + '/ST_N=' + this.$tm_bucketPreStN + '/AX_P=' + this.$tm_bucketPreAxP + '/AX_N=' + this.$tm_bucketPreAxN + '/CR_P=' + this.$tm_bucketPreCrP + '/CR_N=' + this.$tm_bucketPreCrN + ' out=BS_P=' + this.$tm_bucketOutBsP + '/BS_N=' + this.$tm_bucketOutBsN + '/ST_P=' + this.$tm_bucketOutStP + '/ST_N=' + this.$tm_bucketOutStN + '/AX_P=' + this.$tm_bucketOutAxP + '/AX_N=' + this.$tm_bucketOutAxN + '/CR_P=' + this.$tm_bucketOutCrP + '/CR_N=' + this.$tm_bucketOutCrN + ' merged=' + this.$tm_tradeList.count + ' cap=' + this.$tm_maxTradesPerBucket + ' rejRules=' + this.$tm_tradesRejectedTradeRules" chance="100"/>
        </do_if>
      </do_if>

      <!-- Save/load may drop some this.$tm_* counters while the loop still completes; never fail the return table. -->
      <do_if value="not this.$tm_tradeList?">
        <create_list name="this.$tm_tradeList"/>
      </do_if>
      <do_if value="not this.$tm_bestTrade?">
        <set_value name="this.$tm_bestTrade" exact="null"/>
      </do_if>
      <do_if value="not this.$tm_bestScore?">
        <set_value name="this.$tm_bestScore" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesEvaluated?">
        <set_value name="this.$tm_tradesEvaluated" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejected?">
        <set_value name="this.$tm_tradesRejected" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedRouteIllegal?">
        <set_value name="this.$tm_tradesRejectedRouteIllegal" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4CustomerPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4SupplierPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4TypePolicy?">
        <set_value name="this.$tm_tradesRejectedMk4TypePolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4DemandGate?">
        <set_value name="this.$tm_tradesRejectedMk4DemandGate" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4PriceCap?">
        <set_value name="this.$tm_tradesRejectedMk4PriceCap" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4BuildStorageOnly?">
        <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedDistance?">
        <set_value name="this.$tm_tradesRejectedDistance" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk42Class?">
        <set_value name="this.$tm_tradesRejectedMk42Class" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedTradeRules?">
        <set_value name="this.$tm_tradesRejectedTradeRules" exact="0"/>
      </do_if>
      <return value="table[
        $Found = (this.$tm_bestTrade != null),
        $BestTrade = this.$tm_bestTrade,
        $BestScore = this.$tm_bestScore,
        $TradeList = this.$tm_tradeList,
        $TradesEvaluated = this.$tm_tradesEvaluated,
        $TradesRejected = this.$tm_tradesRejected,
        $TradesRejectedRouteIllegal = this.$tm_tradesRejectedRouteIllegal,
        $TradesRejectedMk4CustomerPolicy = this.$tm_tradesRejectedMk4CustomerPolicy,
        $TradesRejectedMk4SupplierPolicy = this.$tm_tradesRejectedMk4SupplierPolicy,
        $TradesRejectedMk4TypePolicy = this.$tm_tradesRejectedMk4TypePolicy,
        $TradesRejectedMk4DemandGate = this.$tm_tradesRejectedMk4DemandGate,
        $TradesRejectedMk4PriceCap = this.$tm_tradesRejectedMk4PriceCap,
        $TradesRejectedMk4BuildStorageOnly = this.$tm_tradesRejectedMk4BuildStorageOnly,
        $TradesRejectedDistance = this.$tm_tradesRejectedDistance,
        $TradesRejectedMk42Class = this.$tm_tradesRejectedMk42Class,
        $TradesRejectedTradeRules = this.$tm_tradesRejectedTradeRules,
        $DualAxisBuckets = if this.$tm_useDualAxisBuckets? then true else false,
        $BucketMergeCap = if this.$tm_useDualAxisBuckets? and this.$tm_maxTradesPerBucket? then this.$tm_maxTradesPerBucket else 0,
        $BucketPreBsP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreBsP else 0,
        $BucketPreBsN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreBsN else 0,
        $BucketPreStP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreStP else 0,
        $BucketPreStN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreStN else 0,
        $BucketPreAxP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreAxP else 0,
        $BucketPreAxN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreAxN else 0,
        $BucketPreCrP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreCrP else 0,
        $BucketPreCrN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketPreCrN else 0,
        $BucketOutBsP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutBsP else 0,
        $BucketOutBsN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutBsN else 0,
        $BucketOutStP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutStP else 0,
        $BucketOutStN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutStN else 0,
        $BucketOutAxP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutAxP else 0,
        $BucketOutAxN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutAxN else 0,
        $BucketOutCrP = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutCrP else 0,
        $BucketOutCrN = if this.$tm_useDualAxisBuckets? then this.$tm_bucketOutCrN else 0
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- lib.gt.offer.filters â€” shared per-offer validation used by MK3 live/cached workers.
     NOTE: Explicitly selected warebasket wares are always allowed, including illegal wares
     when allowIllegal is false (player intent override). -->
<aiscript name="lib.gt.offer.filters" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="offer" default="null"/>
    <param name="wareBasket" default="[]"/>
    <param name="allowIllegal" default="false"/>
    <param name="ignoreBuildStorage" default="false"/>
    <param name="ignoreCarrierAux" default="false"/>
    <param name="ignoreMK1Supply" default="false"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$pass" exact="true"/>
      <set_value name="$reason" exact="'ok'"/>
      <set_value name="$wareMatch" exact="false"/>
      <set_value name="$hasExplicitBasket" exact="false"/>

      <do_if value="not $offer? or not $offer.exists or not $offer.ware?">
        <set_value name="$pass" exact="false"/>
        <set_value name="$reason" exact="'invalid_offer'"/>
      </do_if>

      <!-- Ware basket gate (if configured). -->
      <do_if value="$pass and $wareBasket? and $wareBasket.count gt 0">
        <set_value name="$hasExplicitBasket" exact="true"/>
        <set_value name="$wareMatch" exact="false"/>
        <do_all exact="$wareBasket.count" counter="$wi">
          <do_if value="$wareBasket.{$wi} == $offer.ware">
            <set_value name="$wareMatch" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="not $wareMatch">
          <set_value name="$pass" exact="false"/>
          <set_value name="$reason" exact="'warebasket'"/>
        </do_if>
      </do_if>

      <!-- Illegal gate. Explicit warebasket match overrides allowIllegal=false. -->
      <do_if value="$pass and not $allowIllegal and not ($hasExplicitBasket and $wareMatch)">
        <do_if value="$offer.ware != null and @$offer.ware.illegal gt 0">
          <set_value name="$pass" exact="false"/>
          <set_value name="$reason" exact="'illegal'"/>
        </do_if>
      </do_if>

      <set_value name="$station" exact="null"/>
      <do_if value="$offer.owner?">
        <set_value name="$station" exact="$offer.owner"/>
      </do_if>

      <!-- Build storage / carrier-aux station type gates. -->
      <do_if value="$pass and $station? and $ignoreBuildStorage and $station.isclass.buildstorage">
        <set_value name="$pass" exact="false"/>
        <set_value name="$reason" exact="'buildstorage'"/>
      </do_if>

      <do_if value="$pass and $station? and $ignoreCarrierAux">
        <do_if value="$station.isclass.ship and ($station.type == shiptype.carrier or $station.type == shiptype.resupplier)">
          <set_value name="$pass" exact="false"/>
          <set_value name="$reason" exact="'carrier_aux'"/>
        </do_if>
      </do_if>

      <!-- MK1-supplied station gate. -->
      <do_if value="$pass and $station? and $ignoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$station}?">
        <set_value name="$pass" exact="false"/>
        <set_value name="$reason" exact="'mk1_supply'"/>
      </do_if>

      <return value="table[$Pass = $pass, $Reason = $reason, $WareMatch = $wareMatch]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.pathfinding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="mode" default="'spaces'"/>
    <param name="ship" default="this.ship"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="blacklistGroup" default="null"/>
    <param name="allowIllegal" default="false"/>
    <param name="enforceRouteIllegalLegality" default="false"/>
    <param name="startSector" default="null"/>
    <param name="buySector" default="null"/>
    <param name="sellSector" default="null"/>
    <param name="ware" default="null"/>
    <param name="checkSector" default="null"/>
    <param name="routeCacheTtl" default="300s"/>
    <param name="pilotSkill" default="null"/>
    <param name="includeCommander" default="false"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <!-- ================================================================= -->
      <!-- MODE: effective_pilot_level                                        -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'effective_pilot_level'">
        <set_value name="$resolvedLevel" exact="null"/>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>

        <do_if value="$ship? and $ship.pilot?">
          <do_if value="$useVanillaXPOnly">
            <do_if value="$ship.pilot.skill.piloting?">
              <set_value name="$resolvedLevel" exact="$ship.pilot.skill.piloting"/>
            </do_if>
          </do_if>
          <do_elseif value="global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
            <set_value name="$resolvedLevel" exact="global.$GT_Pilots.{$ship.pilot}.$Level"/>
          </do_elseif>
        </do_if>

        <do_if value="$includeCommander and $ship? and $ship.commander? and $ship.commander.pilot?">
          <set_value name="$commanderLevel" exact="null"/>
          <do_if value="$useVanillaXPOnly">
            <do_if value="$ship.commander.pilot.skill.piloting?">
              <set_value name="$commanderLevel" exact="$ship.commander.pilot.skill.piloting"/>
            </do_if>
          </do_if>
          <do_elseif value="global.$GT_Pilots? and global.$GT_Pilots.{$ship.commander.pilot}? and global.$GT_Pilots.{$ship.commander.pilot}.$Level?">
            <set_value name="$commanderLevel" exact="global.$GT_Pilots.{$ship.commander.pilot}.$Level"/>
          </do_elseif>

          <do_if value="$commanderLevel != null">
            <do_if value="$resolvedLevel == null">
              <set_value name="$resolvedLevel" exact="$commanderLevel"/>
            </do_if>
            <do_else>
              <set_value name="$resolvedLevel" exact="[$resolvedLevel, $commanderLevel].max"/>
            </do_else>
          </do_if>
        </do_if>

        <return value="$resolvedLevel"/>
      </do_if>

      <!-- ================================================================= -->
      <!-- MODE: pilot_max_jumps                                              -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'pilot_max_jumps'">
        <set_value name="$maxJumps" exact="null"/>
        <do_if value="$pilotSkill != null">
          <do_if value="$pilotSkill le 2">
            <set_value name="$maxJumps" exact="1"/>
          </do_if>
          <do_elseif value="$pilotSkill le 5">
            <set_value name="$maxJumps" exact="3"/>
          </do_elseif>
          <do_elseif value="$pilotSkill le 8">
            <set_value name="$maxJumps" exact="5"/>
          </do_elseif>
          <do_elseif value="$pilotSkill le 11">
            <set_value name="$maxJumps" exact="10"/>
          </do_elseif>
          <do_elseif value="$pilotSkill le 13">
            <set_value name="$maxJumps" exact="15"/>
          </do_elseif>
          <do_else>
            <set_value name="$maxJumps" exact="25"/>
          </do_else>
        </do_if>
        <return value="$maxJumps"/>
      </do_if>

      <!-- ================================================================= -->
      <!-- MODE: sector_cargo_legality                                       -->
      <!-- Check whether Monitored contraband may enter $checkSector.        -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'sector_cargo_legality'">
        <set_value name="$result" exact="table[
          $IsLegal = true,
          $Reason = 'skipped',
          $BlockedWare = null,
          $BlockedPoliceFaction = null,
          $ShouldEnforce = false
        ]"/>
        <do_if value="not $allowIllegal or not $enforceRouteIllegalLegality">
          <return value="$result"/>
        </do_if>
        <do_if value="$ship == null or $checkSector == null">
          <set_value name="$result.$IsLegal" exact="false"/>
          <set_value name="$result.$Reason" exact="'invalid_context'"/>
          <set_value name="$result.$ShouldEnforce" exact="true"/>
          <return value="$result"/>
        </do_if>
        <set_value name="$result.$ShouldEnforce" exact="true"/>
        <set_value name="$shipOwner" exact="$ship.owner"/>
        <do_if value="$shipOwner == null">
          <set_value name="$result.$IsLegal" exact="false"/>
          <set_value name="$result.$Reason" exact="'invalid_owner'"/>
          <return value="$result"/>
        </do_if>
        <do_if value="not $checkSector.policefaction or ($checkSector.policefaction == $shipOwner)">
          <set_value name="$result.$Reason" exact="'no_police'"/>
          <return value="$result"/>
        </do_if>
        <set_value name="$cargoList" exact="$ship.cargo.list"/>
        <do_if value="$cargoList.count == 0">
          <set_value name="$result.$Reason" exact="'no_cargo'"/>
          <return value="$result"/>
        </do_if>
        <do_all exact="$cargoList.count" counter="$ci">
          <set_value name="$cargoWare" exact="$cargoList.{$ci}"/>
          <do_if value="$cargoWare? and @$cargoWare.illegal gt 0 and $cargoWare.illegalto.{$checkSector.policefaction}.{$shipOwner}">
            <set_value name="$result.$IsLegal" exact="false"/>
            <set_value name="$result.$Reason" exact="'illegal_on_route'"/>
            <set_value name="$result.$BlockedWare" exact="$cargoWare"/>
            <set_value name="$result.$BlockedPoliceFaction" exact="$checkSector.policefaction"/>
            <break/>
          </do_if>
        </do_all>
        <return value="$result"/>
      </do_if>

      <!-- ================================================================= -->
      <!-- MODE: invalidate_route_legality_cache                             -->
      <!-- Clear cached route_legality verdict for one trade tuple (R3).     -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'invalidate_route_legality_cache'">
        <set_value name="$result" exact="table[$Invalidated = false]"/>
        <do_if value="$homeSector? and $buySector? and $sellSector? and $ware? and $ship? and $ship.owner?">
          <set_value name="$cacheOwner" exact="$ship.owner"/>
          <set_value name="$cacheBlacklist" exact="$blacklistGroup"/>
          <do_if value="$cacheBlacklist == null">
            <set_value name="$cacheBlacklist" exact="blacklistgroup.civilian"/>
          </do_if>
          <set_value name="$cacheStart" exact="$startSector"/>
          <do_if value="$cacheStart == null">
            <set_value name="$cacheStart" exact="if $ship.sector? then $ship.sector else $buySector"/>
          </do_if>
          <do_if value="global.$GT_RouteLegalityCache? and global.$GT_RouteLegalityCache.{$homeSector}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$cacheOwner}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$cacheOwner}.{$cacheBlacklist}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$cacheOwner}.{$cacheBlacklist}.{$cacheStart}?">
            <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$cacheOwner}.{$cacheBlacklist}.{$cacheStart}" exact="[]"/>
            <set_value name="$result.$Invalidated" exact="true"/>
          </do_if>
        </do_if>
        <return value="$result"/>
      </do_if>

      <!-- ================================================================= -->
      <!-- MODE: route_enforce_precheck                                        -->
      <!-- Pre-transit guard: read ActiveTradePolicy, check next sector.       -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'route_enforce_precheck'">
        <set_value name="$result" exact="table[
          $ShouldAbort = false,
          $IsLegal = true,
          $Reason = 'skipped',
          $BlockedWare = null,
          $BlockedPoliceFaction = null,
          $CacheInvalidated = false
        ]"/>
        <do_if value="$ship == null or $checkSector == null">
          <return value="$result"/>
        </do_if>
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{$ship}? or not global.$GT_Ships.{$ship}.$ActiveTradePolicy?">
          <return value="$result"/>
        </do_if>
        <set_value name="$policy" exact="global.$GT_Ships.{$ship}.$ActiveTradePolicy"/>
        <do_if value="not $policy.$AllowIllegal? or not $policy.$AllowIllegal or not $policy.$EnforceRouteIllegalLegality? or not $policy.$EnforceRouteIllegalLegality">
          <return value="$result"/>
        </do_if>
        <!-- Inline sector cargo legality (avoid recursive lib.gt.pathfinding run_script; breaks caller result= binding). -->
        <set_value name="$legality" exact="table[
          $IsLegal = true,
          $Reason = 'skipped',
          $BlockedWare = null,
          $BlockedPoliceFaction = null
        ]"/>
        <set_value name="$shipOwner" exact="$ship.owner"/>
        <do_if value="$shipOwner == null">
          <set_value name="$legality.$IsLegal" exact="false"/>
          <set_value name="$legality.$Reason" exact="'invalid_owner'"/>
        </do_if>
        <do_elseif value="not $checkSector.policefaction or ($checkSector.policefaction == $shipOwner)">
          <set_value name="$legality.$Reason" exact="'no_police'"/>
        </do_elseif>
        <do_else>
          <set_value name="$cargoList" exact="$ship.cargo.list"/>
          <do_if value="$cargoList.count == 0">
            <set_value name="$legality.$Reason" exact="'no_cargo'"/>
          </do_if>
          <do_else>
            <do_all exact="$cargoList.count" counter="$ci">
              <set_value name="$cargoWare" exact="$cargoList.{$ci}"/>
              <do_if value="$cargoWare? and @$cargoWare.illegal gt 0 and $cargoWare.illegalto.{$checkSector.policefaction}.{$shipOwner}">
                <set_value name="$legality.$IsLegal" exact="false"/>
                <set_value name="$legality.$Reason" exact="'illegal_on_route'"/>
                <set_value name="$legality.$BlockedWare" exact="$cargoWare"/>
                <set_value name="$legality.$BlockedPoliceFaction" exact="$checkSector.policefaction"/>
                <break/>
              </do_if>
            </do_all>
          </do_else>
        </do_else>
        <do_if value="$legality.$IsLegal">
          <return value="$result"/>
        </do_if>
        <set_value name="$result.$IsLegal" exact="false"/>
        <set_value name="$result.$Reason" exact="$legality.$Reason"/>
        <set_value name="$result.$BlockedWare" exact="$legality.$BlockedWare"/>
        <set_value name="$result.$BlockedPoliceFaction" exact="$legality.$BlockedPoliceFaction"/>
        <set_value name="$result.$ShouldAbort" exact="true"/>
        <set_value name="global.$GT_Ships.{$ship}.$RouteIllegalAbort" exact="table[
          $Reason = 'route_illegal_pre_transit',
          $NextSector = $checkSector,
          $NextSectorName = if $checkSector? then @$checkSector.knownname else 'Unknown',
          $Ware = $legality.$BlockedWare,
          $WareName = if $legality.$BlockedWare? then @$legality.$BlockedWare.name else 'Unknown',
          $ActiveWare = if $policy.$Ware? then $policy.$Ware else null,
          $ActiveWareName = if $policy.$Ware? then @$policy.$Ware.name else 'none',
          $PoliceFaction = $legality.$BlockedPoliceFaction,
          $PoliceFactionName = if $legality.$BlockedPoliceFaction? then @$legality.$BlockedPoliceFaction.knownname else 'Unknown',
          $PoliceFactionId = if $legality.$BlockedPoliceFaction? and $legality.$BlockedPoliceFaction.id? then $legality.$BlockedPoliceFaction.id else 'none',
          $Timestamp = player.age
        ]"/>
        <do_if value="$policy.$Ware? and $legality.$BlockedWare? and $legality.$BlockedWare == $policy.$Ware and $policy.$HomeSector? and $policy.$BuySector? and $policy.$SellSector?">
          <run_script name="'lib.gt.pathfinding'" result="$cacheBust">
            <param name="mode" value="'invalidate_route_legality_cache'"/>
            <param name="ship" value="$ship"/>
            <param name="homeSector" value="$policy.$HomeSector"/>
            <param name="buySector" value="$policy.$BuySector"/>
            <param name="sellSector" value="$policy.$SellSector"/>
            <param name="ware" value="$policy.$Ware"/>
            <param name="allowIllegal" value="true"/>
            <param name="enforceRouteIllegalLegality" value="true"/>
            <param name="startSector" value="if $policy.$RouteStart? then $policy.$RouteStart else (if $ship.sector? then $ship.sector else $policy.$BuySector)"/>
            <param name="blacklistGroup" value="if $blacklistGroup? then $blacklistGroup else blacklistgroup.civilian"/>
          </run_script>
          <set_value name="$result.$CacheInvalidated" exact="if $cacheBust.$Invalidated? then $cacheBust.$Invalidated else false"/>
        </do_if>
        <remove_value name="global.$GT_Ships.{$ship}.$ActiveTradePolicy"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-RouteEnforce] BLOCK ' + $ship.idcode + ': next=' + @$checkSector.knownname + ', ware=' + (if $legality.$BlockedWare? then @$legality.$BlockedWare.name else 'null') + ', police=' + (if $legality.$BlockedPoliceFaction? then @$legality.$BlockedPoliceFaction.id else 'null') + ', cacheBust=' + $result.$CacheInvalidated" chance="100"/>
        </do_if>
        <return value="$result"/>
      </do_if>

      <!-- ================================================================= -->
      <!-- MODE: route_legality                                              -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'route_legality'">
        <set_value name="$result" exact="table[
          $IsLegal = true,
          $Reason = 'skipped',
          $BlockedSector = null,
          $BlockedPoliceFaction = null,
          $RouteSectors = [],
          $RouteSignature = '',
          $BlacklistEpoch = if global.$GT_BlacklistEpoch? then global.$GT_BlacklistEpoch else 0
        ]"/>

        <!-- Route legality filtering only applies when illegal wares are allowed and the feature is enabled. -->
        <do_if value="not $allowIllegal or not $enforceRouteIllegalLegality">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PATH] route_legality skipped: allowIllegal=' + $allowIllegal + ', filter=' + $enforceRouteIllegalLegality" chance="100"/>
          </do_if>
          <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="$result"/>
        </do_if>

        <!-- Legal wares cannot trigger route-illegal blocks; skip expensive jump-path build (parity with GT_CheckRouteLegality). -->
        <do_if value="not $ware? or @$ware.illegal le 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PATH] route_legality skipped: legal ware (' + (if $ware? then @$ware.id else 'null') + ')'" chance="100"/>
          </do_if>
          <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="$result"/>
        </do_if>

        <!-- Defensive guard: if required context is missing, fail closed for this candidate. -->
        <do_if value="$ship == null or $buySector == null or $sellSector == null or $ware == null">
          <set_value name="$result.$IsLegal" exact="false"/>
          <set_value name="$result.$Reason" exact="'invalid_context'"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PATH] route_legality invalid_context: ship=' + $ship + ', buy=' + $buySector + ', sell=' + $sellSector + ', ware=' + $ware" chance="100"/>
          </do_if>
          <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="$result"/>
        </do_if>

        <set_value name="$shipOwner" exact="$ship.owner"/>
        <do_if value="$shipOwner == null">
          <set_value name="$result.$IsLegal" exact="false"/>
          <set_value name="$result.$Reason" exact="'invalid_owner'"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PATH] route_legality invalid_owner for ship=' + $ship" chance="100"/>
          </do_if>
          <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="$result"/>
        </do_if>

        <set_value name="$routeStart" exact="$startSector"/>
        <do_if value="$routeStart == null and $ship.sector?">
          <set_value name="$routeStart" exact="$ship.sector"/>
        </do_if>
        <do_if value="$routeStart == null">
          <set_value name="$routeStart" exact="$buySector"/>
        </do_if>

        <set_value name="$resolvedBlacklistGroup" exact="$blacklistGroup"/>
        <do_if value="$resolvedBlacklistGroup == null">
          <set_value name="$resolvedBlacklistGroup" exact="blacklistgroup.civilian"/>
        </do_if>

        <!-- Phase B (R2): align highway flag with vanilla DockAndWait / move.generic -->
        <set_value name="$useLocalHighways" exact="true"/>
        <do_if value="$ship? and ($ship.isclass.ship_l or $ship.isclass.ship_xl)">
          <set_value name="$useLocalHighways" exact="false"/>
        </do_if>

        <!-- Build route sectors: ship/start -> buy -> sell -->
        <set_value name="$routeSectors" exact="[]"/>
        <set_value name="$lastRouteSector" exact="null"/>
        <append_to_list name="$routeSectors" exact="$routeStart"/>
        <set_value name="$lastRouteSector" exact="$routeStart"/>

        <set_value name="$pathToBuy" exact="[]"/>
        <do_if value="$routeStart != $buySector">
          <get_jump_path component="$pathToBuy" multiple="true" uselocalhighways="$useLocalHighways" useblacklist="$resolvedBlacklistGroup" refobject="$ship" useknownpath="$ship.isplayerowned">
            <start object="$ship"/>
            <end object="$buySector"/>
          </get_jump_path>
        </do_if>
        <set_value name="this.$rlPathToBuyList" exact="$pathToBuy"/>
        <set_value name="this.$rlRouteSectors" exact="$routeSectors"/>
        <set_value name="this.$rlLastRouteSector" exact="$lastRouteSector"/>
        <set_value name="this.$rlPathToBuyIdx" exact="1"/>
        <do_while value="this.$rlPathToBuyIdx le this.$rlPathToBuyList.count">
          <set_value name="$pathToBuyChunkEnd" exact="[this.$rlPathToBuyIdx + 24, this.$rlPathToBuyList.count].min"/>
          <do_while value="this.$rlPathToBuyIdx le $pathToBuyChunkEnd">
            <set_value name="$pathComponent" exact="this.$rlPathToBuyList.{this.$rlPathToBuyIdx}"/>
            <do_if value="$pathComponent? and @$pathComponent.sector != null">
              <set_value name="$pathSector" exact="@$pathComponent.sector"/>
              <do_if value="this.$rlLastRouteSector == null or $pathSector != this.$rlLastRouteSector">
                <append_to_list name="this.$rlRouteSectors" exact="$pathSector"/>
                <set_value name="this.$rlLastRouteSector" exact="$pathSector"/>
              </do_if>
            </do_if>
            <set_value name="this.$rlPathToBuyIdx" exact="this.$rlPathToBuyIdx + 1"/>
          </do_while>
          <do_if value="this.$rlPathToBuyIdx le this.$rlPathToBuyList.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$routeSectors" exact="this.$rlRouteSectors"/>
        <set_value name="$lastRouteSector" exact="this.$rlLastRouteSector"/>
        <remove_value name="this.$rlPathToBuyList"/>
        <remove_value name="this.$rlRouteSectors"/>
        <remove_value name="this.$rlLastRouteSector"/>
        <remove_value name="this.$rlPathToBuyIdx"/>
        <do_if value="$lastRouteSector != $buySector">
          <append_to_list name="$routeSectors" exact="$buySector"/>
          <set_value name="$lastRouteSector" exact="$buySector"/>
        </do_if>

        <set_value name="$pathToSell" exact="[]"/>
        <do_if value="$buySector != $sellSector">
          <get_jump_path component="$pathToSell" multiple="true" uselocalhighways="$useLocalHighways" useblacklist="$resolvedBlacklistGroup" refobject="$ship" useknownpath="$ship.isplayerowned">
            <start object="$buySector"/>
            <end object="$sellSector"/>
          </get_jump_path>
        </do_if>
        <set_value name="this.$rlPathToSellList" exact="$pathToSell"/>
        <set_value name="this.$rlRouteSectors" exact="$routeSectors"/>
        <set_value name="this.$rlLastRouteSector" exact="$lastRouteSector"/>
        <set_value name="this.$rlPathToSellIdx" exact="1"/>
        <do_while value="this.$rlPathToSellIdx le this.$rlPathToSellList.count">
          <set_value name="$pathToSellChunkEnd" exact="[this.$rlPathToSellIdx + 24, this.$rlPathToSellList.count].min"/>
          <do_while value="this.$rlPathToSellIdx le $pathToSellChunkEnd">
            <set_value name="$pathComponent2" exact="this.$rlPathToSellList.{this.$rlPathToSellIdx}"/>
            <do_if value="$pathComponent2? and @$pathComponent2.sector != null">
              <set_value name="$pathSector2" exact="@$pathComponent2.sector"/>
              <do_if value="this.$rlLastRouteSector == null or $pathSector2 != this.$rlLastRouteSector">
                <append_to_list name="this.$rlRouteSectors" exact="$pathSector2"/>
                <set_value name="this.$rlLastRouteSector" exact="$pathSector2"/>
              </do_if>
            </do_if>
            <set_value name="this.$rlPathToSellIdx" exact="this.$rlPathToSellIdx + 1"/>
          </do_while>
          <do_if value="this.$rlPathToSellIdx le this.$rlPathToSellList.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$routeSectors" exact="this.$rlRouteSectors"/>
        <set_value name="$lastRouteSector" exact="this.$rlLastRouteSector"/>
        <remove_value name="this.$rlPathToSellList"/>
        <remove_value name="this.$rlRouteSectors"/>
        <remove_value name="this.$rlLastRouteSector"/>
        <remove_value name="this.$rlPathToSellIdx"/>
        <do_if value="$lastRouteSector != $sellSector">
          <append_to_list name="$routeSectors" exact="$sellSector"/>
        </do_if>

        <!-- Build topology signature (path-aware cache key component). -->
        <set_value name="$routeSignature" exact="'E' + (if global.$GT_BlacklistEpoch? then global.$GT_BlacklistEpoch else 0) + '_'" />
        <set_value name="this.$rlRouteSectorsForSig" exact="$routeSectors"/>
        <set_value name="this.$rlRouteSignature" exact="$routeSignature"/>
        <set_value name="this.$rlRouteSigIdx" exact="1"/>
        <do_while value="this.$rlRouteSigIdx le this.$rlRouteSectorsForSig.count">
          <set_value name="$routeSigChunkEnd" exact="[this.$rlRouteSigIdx + 24, this.$rlRouteSectorsForSig.count].min"/>
          <do_while value="this.$rlRouteSigIdx le $routeSigChunkEnd">
            <set_value name="$rsec" exact="this.$rlRouteSectorsForSig.{this.$rlRouteSigIdx}"/>
            <!-- Cache key safety: use idcode-only tokens (no localized names/spaces/symbols). -->
            <set_value name="$rsecKey" exact="'S' + this.$rlRouteSigIdx" />
            <do_if value="$rsec? and $rsec.idcode?">
              <set_value name="$rsecKey" exact="$rsec.idcode"/>
            </do_if>
            <set_value name="this.$rlRouteSignature" exact="this.$rlRouteSignature + (if this.$rlRouteSigIdx gt 1 then '_' else '') + $rsecKey"/>
            <set_value name="this.$rlRouteSigIdx" exact="this.$rlRouteSigIdx + 1"/>
          </do_while>
          <do_if value="this.$rlRouteSigIdx le this.$rlRouteSectorsForSig.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$routeSignature" exact="this.$rlRouteSignature"/>
        <remove_value name="this.$rlRouteSectorsForSig"/>
        <remove_value name="this.$rlRouteSignature"/>
        <remove_value name="this.$rlRouteSigIdx"/>

        <!-- Cache lookup (path-aware key). -->
        <do_if value="not global.$GT_RouteLegalityCache?">
          <set_value name="global.$GT_RouteLegalityCache" exact="table[]"/>
        </do_if>
        <set_value name="$cachedEntry" exact="null"/>
        <do_if value="global.$GT_RouteLegalityCache.{$homeSector}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}? and global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}.{$routeStart}?">
          <set_value name="$routeEntryList" exact="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}.{$routeStart}"/>
          <do_if value="$routeEntryList? and $routeEntryList.count gt 0">
            <do_all exact="$routeEntryList.count" counter="$reli">
              <do_if value="$routeEntryList.{$reli}? and $routeEntryList.{$reli}.$RouteSignature? and $routeEntryList.{$reli}.$RouteSignature == $routeSignature">
                <set_value name="$cachedEntry" exact="$routeEntryList.{$reli}"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <do_if value="$cachedEntry? and $cachedEntry.$CheckedAt? and (player.age - $cachedEntry.$CheckedAt) le $routeCacheTtl">
          <set_value name="$result" exact="$cachedEntry"/>
          <set_value name="$result.$RouteSectors" exact="$routeSectors"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PATH] route_legality cache_hit: legal=' + $result.$IsLegal + ', reason=' + $result.$Reason + ', routeSectors=' + $routeSectors.count + ', sig=' + $routeSignature" chance="100"/>
          </do_if>
          <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="$result"/>
        </do_if>

        <!-- Evaluate sector legality against police factions on the actual route. -->
        <set_value name="$isLegal" exact="true"/>
        <set_value name="$blockedSector" exact="null"/>
        <set_value name="$blockedPolice" exact="null"/>
        <set_value name="$reason" exact="'ok'"/>
        <set_value name="this.$rlRouteSectorsForLegality" exact="$routeSectors"/>
        <set_value name="this.$rlIsLegal" exact="$isLegal"/>
        <set_value name="this.$rlBlockedSector" exact="$blockedSector"/>
        <set_value name="this.$rlBlockedPolice" exact="$blockedPolice"/>
        <set_value name="this.$rlReason" exact="$reason"/>
        <set_value name="this.$rlLegalityIdx" exact="1"/>
        <do_while value="this.$rlLegalityIdx le this.$rlRouteSectorsForLegality.count and this.$rlIsLegal">
          <set_value name="$legalityChunkEnd" exact="[this.$rlLegalityIdx + 24, this.$rlRouteSectorsForLegality.count].min"/>
          <do_while value="this.$rlLegalityIdx le $legalityChunkEnd and this.$rlIsLegal">
            <set_value name="$checkSector" exact="this.$rlRouteSectorsForLegality.{this.$rlLegalityIdx}"/>
            <do_if value="$checkSector? and $checkSector.policefaction and ($checkSector.policefaction != $shipOwner)">
              <do_if value="$ware.illegalto.{$checkSector.policefaction}.{$shipOwner}">
                <set_value name="this.$rlIsLegal" exact="false"/>
                <set_value name="this.$rlBlockedSector" exact="$checkSector"/>
                <set_value name="this.$rlBlockedPolice" exact="$checkSector.policefaction"/>
                <set_value name="this.$rlReason" exact="'illegal_on_route'"/>
                <break/>
              </do_if>
            </do_if>
            <set_value name="this.$rlLegalityIdx" exact="this.$rlLegalityIdx + 1"/>
          </do_while>
          <do_if value="this.$rlLegalityIdx le this.$rlRouteSectorsForLegality.count and this.$rlIsLegal">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$isLegal" exact="this.$rlIsLegal"/>
        <set_value name="$blockedSector" exact="this.$rlBlockedSector"/>
        <set_value name="$blockedPolice" exact="this.$rlBlockedPolice"/>
        <set_value name="$reason" exact="this.$rlReason"/>
        <remove_value name="this.$rlRouteSectorsForLegality"/>
        <remove_value name="this.$rlIsLegal"/>
        <remove_value name="this.$rlBlockedSector"/>
        <remove_value name="this.$rlBlockedPolice"/>
        <remove_value name="this.$rlReason"/>
        <remove_value name="this.$rlLegalityIdx"/>

        <set_value name="$result" exact="table[
          $IsLegal = $isLegal,
          $Reason = $reason,
          $BlockedSector = $blockedSector,
          $BlockedPoliceFaction = $blockedPolice,
          $RouteSectors = $routeSectors,
          $RouteSignature = $routeSignature,
          $BlacklistEpoch = if global.$GT_BlacklistEpoch? then global.$GT_BlacklistEpoch else 0,
          $CheckedAt = player.age
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-PATH] route_legality evaluated: legal=' + $result.$IsLegal + ', reason=' + $result.$Reason + ', blockedSector=' + $result.$BlockedSector + ', blockedPolice=' + $result.$BlockedPoliceFaction + ', routeSectors=' + $routeSectors.count + ', sig=' + $routeSignature" chance="100"/>
        </do_if>

        <!-- Cache store -->
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}.{$routeStart}?">
          <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}.{$routeStart}" exact="[]"/>
        </do_if>
        <set_value name="$routeEntryList" exact="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}.{$routeStart}"/>
        <set_value name="$routeEntryUpdated" exact="false"/>
        <do_if value="$routeEntryList? and $routeEntryList.count gt 0">
          <do_all exact="$routeEntryList.count" counter="$reli2">
            <do_if value="$routeEntryList.{$reli2}? and $routeEntryList.{$reli2}.$RouteSignature? and $routeEntryList.{$reli2}.$RouteSignature == $routeSignature">
              <set_value name="$routeEntryList.{$reli2}" exact="$result"/>
              <set_value name="$routeEntryUpdated" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $routeEntryUpdated">
          <append_to_list name="$routeEntryList" exact="$result"/>
        </do_if>
        <set_value name="global.$GT_RouteLegalityCache.{$homeSector}.{$buySector}.{$sellSector}.{$ware}.{$allowIllegal}.{$enforceRouteIllegalLegality}.{$shipOwner}.{$resolvedBlacklistGroup}.{$routeStart}" exact="$routeEntryList"/>

        <wait exact="1ms" comment="Cooperative yield before return (wake-loop guard)"/>
        <return value="$result"/>
      </do_if>

      <!-- ================================================================= -->
      <!-- MODE: spaces (legacy behavior)                                    -->
      <!-- ================================================================= -->
      <do_if value="$mode == 'spaces'">
      <set_value name="$refobject" exact="$homeSector"/>
      <do_if value="not $refobject? or not $refobject.exists">
        <set_value name="$refobject" exact="if $ship? and $ship.sector? then $ship.sector else null"/>
      </do_if>
      <do_if value="not $refobject? or not $refobject.exists">
        <do_if value="$ship? and @$ship.zone.issuperhighway">
          <set_value name="$refobject" exact="$ship.zone.destination.sector"/>
        </do_if>
      </do_if>
      <do_if value="not $refobject? or not $refobject.exists">
        <set_value name="$spaces" exact="[]"/>
        <set_value name="$result" exact="table[
          $BuySpaces = $spaces,
          $SellSpaces = $spaces,
          $ShipIsIsolated = true
        ]"/>
        <return value="$result"/>
      </do_if>

      <run_script name="'lib.find.sectors.inrange'" result="$spaces">
        <param name="refobject" value="$refobject"/>
        <param name="mingatedistance" value="0"/>
        <param name="maxgatedistance" value="$maxDistance"/>
        <param name="applyblacklist" value="true"/>
        <param name="blacklistgroup" value="$blacklistGroup"/>
        <param name="returndistancetable" value="false"/>
        <param name="debugchance" value="$debugchance"/>
      </run_script>

      <do_if value="not $spaces?">
        <set_value name="$spaces" exact="[]"/>
      </do_if>

      <!-- Filter out threat-blacklisted sectors -->
      <do_if value="$spaces.count gt 0 and global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.$BlacklistedSectors? and global.$GT_ThreatIntelligence.$BlacklistedSectors.count gt 0">
        <create_list name="$filteredSpaces"/>
        <do_all exact="$spaces.count" counter="$si">
          <set_value name="$sector" exact="$spaces.{$si}"/>
          <set_value name="$isThreatened" exact="false"/>
          <do_all exact="global.$GT_ThreatIntelligence.$BlacklistedSectors.count" counter="$bli">
            <do_if value="global.$GT_ThreatIntelligence.$BlacklistedSectors.{$bli} == $sector">
              <set_value name="$isThreatened" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $isThreatened">
            <append_to_list name="$filteredSpaces" exact="$sector"/>
          </do_if>
        </do_all>
        <set_value name="$spaces" exact="$filteredSpaces"/>
      </do_if>

      <set_value name="$result" exact="table[
        $BuySpaces = $spaces,
        $SellSpaces = $spaces,
        $ShipIsIsolated = ($spaces.count == 0)
      ]"/>
      <return value="$result"/>
      </do_if>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.priority_wares.resolve" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <!--
    Priority-ware resolver shared by GalaxyTrader MK3 / MK4.

    Walks the priority-ware source chain in this fixed order and returns the
    first non-empty list found:
      1) `instanceWares` (typically `this.$effectivePriorityWares` from the caller)
      2) `localWares`    (typically a workunit-local `$effectivePriorityWares`)
      3) `ship.commander.defaultorder.$prioritywares`
         - direct, when commander.defaultorder.id is in `validOrderIds`
         - via `defaultorder.$baseorder.$prioritywares` when the commander runs
           the vanilla `Assist` order over a GalaxyTrader baseorder
      4) `[]` (no priority wares anywhere)

    Replaces the ~1.5 KB nested ternary previously inlined at order.trade.galaxytrader:3843
    and order.trade.galaxytradermk4:4190 (see DOCS/MK3_PIPELINE_REFACTOR.md Â§3.8).
    The single-pass walk also guarantees that callers never see a "?-true but null"
    handle for a priority-wares property â€” every step here applies the
    `<existence>? and != null and .count gt 0` triple guard.
  -->
  <params>
    <param name="instanceWares" default="null"/>
    <param name="localWares" default="null"/>
    <param name="ship" default="this.ship"/>
    <param name="validOrderIds" default="['GalaxyTraderMK3']"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="$instanceWares? and $instanceWares != null and $instanceWares.count gt 0">
        <return value="$instanceWares"/>
      </do_if>
      <do_if value="$localWares? and $localWares != null and $localWares.count gt 0">
        <return value="$localWares"/>
      </do_if>
      <do_if value="$ship? and $ship.commander? and $ship.commander.defaultorder?">
        <set_value name="$cmdOrder" exact="$ship.commander.defaultorder"/>
        <do_if value="$validOrderIds? and $validOrderIds.indexof.{@$cmdOrder.id} and $cmdOrder.$prioritywares? and $cmdOrder.$prioritywares != null and $cmdOrder.$prioritywares.count gt 0">
          <return value="$cmdOrder.$prioritywares"/>
        </do_if>
        <do_if value="@$cmdOrder.id == 'Assist' and $cmdOrder.$baseorder? and $validOrderIds? and $validOrderIds.indexof.{@$cmdOrder.$baseorder.id} and $cmdOrder.$baseorder.$prioritywares? and $cmdOrder.$baseorder.$prioritywares != null and $cmdOrder.$baseorder.$prioritywares.count gt 0">
          <return value="$cmdOrder.$baseorder.$prioritywares"/>
        </do_if>
      </do_if>
      <return value="[]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<!-- Per-ship validation sort: selectionScore = adjustedScore / (1 + shipâ†’buy Ã— shipProximityWeight).
     adjustedScore is trade.$Score (already includes priority-ware multiplier from lib.gt.score.trades).
     Does not mutate cache semantics â€” $Score unchanged; $SelectionScore is sort key only. -->
<aiscript name="lib.gt.score.selection_sort" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <params>
    <param name="tradeList" default="[]"/>
    <param name="ship"/>
    <param name="blacklistGroup" default="blacklistgroup.civilian"/>
    <param name="debugchance" default="0"/>
  </params>
  <attention min="unknown">
    <actions>
      <do_if value="not $tradeList? or $tradeList.count == 0">
        <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[$SortedTrades = if $tradeList? then $tradeList else []]"/>
      </do_if>

      <set_value name="$proxWeight" exact="0.04"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Trading? and global.$GT_GlobalSettings.$Trading.$ShipProximityWeight?">
        <set_value name="$tmpWeight" exact="@global.$GT_GlobalSettings.$Trading.$ShipProximityWeight"/>
        <do_if value="$tmpWeight? and $tmpWeight ge 0">
          <set_value name="$proxWeight" exact="$tmpWeight"/>
        </do_if>
      </do_if>

      <do_all exact="$tradeList.count" counter="$i">
        <set_value name="$trade" exact="$tradeList.{$i}"/>

        <!-- Cache/live ship-route: keep priority-adjusted $SelectionScore from lib.gt.score.trades when set. -->
        <do_if value="$trade.$ShipRouteScored? and $trade.$ShipRouteScored">
          <set_value name="$selectionScore" exact="if $trade.$SelectionScore? then $trade.$SelectionScore else (if $trade.$ShipScore? then $trade.$ShipScore else 0)"/>
          <set_value name="$trade.$SelectionScore" exact="$selectionScore"/>
        </do_if>
        <do_else>
        <set_value name="$adjustedScore" exact="if $trade.$Score? then $trade.$Score else 0"/>
        <set_value name="$selectionScore" exact="$adjustedScore"/>

        <do_if value="$proxWeight gt 0 and not ($trade.$IsSellOnly? and $trade.$IsSellOnly)">
          <set_value name="$buySector" exact="null"/>
          <do_if value="$trade.$BuySector?">
            <set_value name="$buySector" exact="$trade.$BuySector"/>
          </do_if>
          <do_elseif value="$trade.$BuyStation? and $trade.$BuyStation.sector?">
            <set_value name="$buySector" exact="$trade.$BuyStation.sector"/>
          </do_elseif>
          <do_elseif value="$trade.$BuyOffer? and $trade.$BuyOffer.owner? and $trade.$BuyOffer.owner.sector?">
            <set_value name="$buySector" exact="$trade.$BuyOffer.owner.sector"/>
          </do_elseif>

          <set_value name="$shipToBuy" exact="-1"/>
          <do_if value="$buySector? and $ship? and $ship.sector?">
            <do_if value="$buySector == $ship.sector">
              <set_value name="$shipToBuy" exact="0"/>
            </do_if>
            <do_elseif value="$blacklistGroup? and $blacklistGroup != null">
              <set_value name="$shipToBuy" exact="$ship.gatedistance.{$buySector}.{$blacklistGroup}.{$ship}"/>
            </do_elseif>
            <do_else>
              <set_value name="$shipToBuy" exact="$ship.gatedistance.{$buySector}"/>
            </do_else>
          </do_if>

          <do_if value="$shipToBuy ge 0">
            <set_value name="$proxFactor" exact="1.0 + ($shipToBuy * $proxWeight)"/>
            <do_if value="$proxFactor gt 0">
              <set_value name="$selectionScore" exact="$adjustedScore / $proxFactor"/>
            </do_if>
          </do_if>
        </do_if>

        <set_value name="$trade.$SelectionScore" exact="$selectionScore"/>
        </do_else>
      </do_all>

      <sort_list list="$tradeList" sortbyvalue="loop.element.$SelectionScore" sortdescending="true"/>

      <wait exact="1ms" comment="Cooperative yield before return (wake-loop guard)"/>
      <return value="table[$SortedTrades = $tradeList]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.score.trades" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="3">
  <params>
    <param name="tradeList" default="[]"/>
    <param name="debugchance" default="0"/>
    <param name="priorityWares" default="[]" comment="Optional: wares to boost (MK3 Priority Wares). Applied last."/>
    <param name="priorityScoreMultiplier" default="125" comment="Optional: score multiplier for priority wares (125=+25%%, 150=+50%%, 200=2x). Applied last."/>
    <!-- MK4 auto-wares: round-robin one trade per ware per pass so niche wares (e.g. Quantum Tubes)
         are not buried behind a global score sort dominated by high-volume cheap wares. -->
    <param name="diversifyByWare" default="false"/>
    <!-- MK4 supply: priority wares lead each diversify round before other wares (still one slot/ware/round). -->
    <param name="priorityFirstInDiversify" default="false"/>
    <!-- MK3 live_ship_route: rank/diversify on $ShipScore via $SelectionScore; leave home $Score unchanged for cache rows. -->
    <param name="useShipRouteScore" default="false"/>
  </params>
  <attention min="unknown">
    <actions>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>
      <set_value name="$haveBest" exact="false"/>
      <create_list name="$sortedTrades"/>

      <!-- null-safe: never read .count when $tradeList is null (X4 evaluates both sides of 'or'). -->
      <do_if value="not $tradeList?">
        <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $SortedTrades = $sortedTrades
        ]"/>
      </do_if>
      <do_if value="$tradeList.count == 0">
        <wait exact="1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $SortedTrades = $sortedTrades
        ]"/>
      </do_if>

      <!-- Apply priority ware score multiplier LAST (after all other scoring).
           Normalize nullable incoming list first (save/load resume safety). -->
      <set_value name="$safePriorityWares" exact="if $priorityWares? and $priorityWares != null then $priorityWares else []"/>
      <set_value name="$hasPriorityWares" exact="$safePriorityWares.count gt 0"/>
      <set_value name="$multPct" exact="if $priorityScoreMultiplier? then $priorityScoreMultiplier else 125"/>
      <do_if value="$multPct lt 125"><set_value name="$multPct" exact="125"/></do_if>
      <do_if value="$multPct gt 300"><set_value name="$multPct" exact="300"/></do_if>
      <set_value name="$mult" exact="$multPct / 100.0"/>

      <do_all exact="$tradeList.count" counter="$i">
        <set_value name="$trade" exact="$tradeList.{$i}"/>
        <set_value name="$baseScore" exact="if $trade.$Score? then $trade.$Score else 0"/>
        <do_if value="$useShipRouteScore and $trade.$ShipRouteScored? and $trade.$ShipRouteScored and $trade.$ShipScore?">
          <set_value name="$baseScore" exact="$trade.$ShipScore"/>
        </do_if>
        <set_value name="$finalScore" exact="$baseScore"/>
        <do_if value="$hasPriorityWares and $trade.$Ware?">
          <set_value name="$isPriority" exact="false"/>
          <do_all exact="$safePriorityWares.count" counter="$pw">
            <do_if value="$safePriorityWares.{$pw} == $trade.$Ware">
              <set_value name="$isPriority" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="$isPriority">
            <set_value name="$finalScore" exact="$baseScore * $mult"/>
          </do_if>
        </do_if>
        <do_if value="$useShipRouteScore">
          <set_value name="$trade.$SelectionScore" exact="$finalScore"/>
        </do_if>
        <do_else>
          <set_value name="$trade.$Score" exact="$finalScore"/>
        </do_else>
        <append_to_list name="$sortedTrades" exact="$trade"/>
        <!-- Candidates are already fully validated upstream (profit/ROI/offers/amount), so the
             score is a pure ranking heuristic and may legitimately be <= 0 (e.g. a tiny base
             score overwhelmed by the fleet-usage penalty). Always keep the highest-scoring
             candidate regardless of sign; a 0-init floor with "gt 0" would drop every
             non-positive candidate and wrongly report no trade. -->
        <do_if value="not $haveBest or $finalScore gt $bestScore">
          <set_value name="$bestScore" exact="$finalScore"/>
          <set_value name="$bestTrade" exact="$trade"/>
          <set_value name="$haveBest" exact="true"/>
        </do_if>
      </do_all>

      <do_if value="$useShipRouteScore">
        <sort_list list="$sortedTrades" sortbyvalue="loop.element.$SelectionScore" sortdescending="true"/>
      </do_if>
      <do_else>
        <sort_list list="$sortedTrades" sortbyvalue="loop.element.$Score" sortdescending="true"/>
      </do_else>

      <!-- Per-ware quota (floor): after score sort, interleave so each ware's best trade
           appears in the validation window before lower-ranked trades from dominant wares. -->
      <do_if value="$diversifyByWare and $sortedTrades.count gt 1">
        <create_list name="$diversifiedTrades"/>
        <set_value name="$diversifyPicked" exact="table[]"/>
        <set_value name="$usePriorityFirst" exact="$priorityFirstInDiversify and $hasPriorityWares"/>
        <do_while value="$diversifiedTrades.count lt $sortedTrades.count">
          <set_value name="$diversifyRoundServed" exact="table[]"/>
          <set_value name="$diversifyRoundAdded" exact="0"/>
          <!-- Priority wares first each round (MK4 supply fairness + priority boost placement). -->
          <do_if value="$usePriorityFirst">
            <do_all exact="$safePriorityWares.count" counter="$dpp">
              <set_value name="$dpw" exact="$safePriorityWares.{$dpp}"/>
              <do_if value="not $dpw? or $dpw == null">
                <continue/>
              </do_if>
              <do_if value="$diversifyRoundServed.{$dpw}?">
                <continue/>
              </do_if>
              <do_all exact="$sortedTrades.count" counter="$dpwi">
                <do_if value="not $diversifyPicked.{$dpwi}?">
                  <set_value name="$dpTrade" exact="$sortedTrades.{$dpwi}"/>
                  <set_value name="$dpWare" exact="if $dpTrade.$Ware? then $dpTrade.$Ware else null"/>
                  <do_if value="$dpWare? and $dpWare == $dpw">
                    <append_to_list name="$diversifiedTrades" exact="$dpTrade"/>
                    <set_value name="$diversifyPicked.{$dpwi}" exact="true"/>
                    <set_value name="$diversifyRoundServed.{$dpw}" exact="true"/>
                    <set_value name="$diversifyRoundAdded" operation="add"/>
                    <break/>
                  </do_if>
                </do_if>
              </do_all>
            </do_all>
          </do_if>
          <do_all exact="$sortedTrades.count" counter="$dwi">
            <do_if value="not $diversifyPicked.{$dwi}?">
              <set_value name="$dwTrade" exact="$sortedTrades.{$dwi}"/>
              <set_value name="$dwWare" exact="if $dwTrade.$Ware? then $dwTrade.$Ware else null"/>
              <do_if value="$dwWare? and not $diversifyRoundServed.{$dwWare}?">
                <append_to_list name="$diversifiedTrades" exact="$dwTrade"/>
                <set_value name="$diversifyPicked.{$dwi}" exact="true"/>
                <set_value name="$diversifyRoundServed.{$dwWare}" exact="true"/>
                <set_value name="$diversifyRoundAdded" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
          <do_if value="$diversifyRoundAdded == 0">
            <break/>
          </do_if>
        </do_while>
        <!-- Trades without a ware tag (should not happen) append at tail in score order. -->
        <do_all exact="$sortedTrades.count" counter="$dwt">
          <do_if value="not $diversifyPicked.{$dwt}?">
            <append_to_list name="$diversifiedTrades" exact="$sortedTrades.{$dwt}"/>
            <set_value name="$diversifyPicked.{$dwt}" exact="true"/>
          </do_if>
        </do_all>
        <set_value name="$sortedTrades" exact="$diversifiedTrades"/>
        <set_value name="$bestTrade" exact="if $sortedTrades.count gt 0 then $sortedTrades.{1} else null"/>
        <do_if value="$useShipRouteScore">
          <set_value name="$bestScore" exact="if $bestTrade? and $bestTrade.$SelectionScore? then $bestTrade.$SelectionScore else 0"/>
        </do_if>
        <do_else>
          <set_value name="$bestScore" exact="if $bestTrade? and $bestTrade.$Score? then $bestTrade.$Score else 0"/>
        </do_else>
        <debug_text text="'[GT-ScoreTrades] diversifyByWare: interleaved ' + $sortedTrades.count + ' trades (best=' + (if $bestTrade? and $bestTrade.$Ware? then $bestTrade.$Ware.name else '?') + ' score=' + $bestScore + ' priorityFirst=' + $usePriorityFirst + ')'" chance="$debugchance"/>
      </do_if>

      <wait exact="1ms" comment="Cooperative yield before return (wake-loop guard)"/>
      <return value="table[
        $Found = ($bestTrade != null),
        $BestTrade = $bestTrade,
        $BestScore = $bestScore,
        $SortedTrades = $sortedTrades
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="lib.gt.tradematch" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="8">
  <params>
    <param name="ship" default="this.ship"/>
    <param name="sellOffers" default="[]"/>
    <param name="buyOffers" default="[]"/>
    <param name="homeSector" default="this.ship.sector"/>
    <param name="maxDistance" default="0"/>
    <param name="minROI" default="0"/>
    <param name="minAbsoluteProfit" default="0"/>
    <param name="distancePenalty" default="0.1"/>
    <param name="factionPriority" default="0"/>
    <param name="ignoreBuildStorage" default="false"/>
    <param name="ignoreCarrierAux" default="false"/>
    <param name="allowIllegal" default="false"/>
    <param name="enforceRouteIllegalLegality" default="false"/>
    <param name="blacklistGroup" default="null"/>
    <param name="scoreMode" default="'sell'"/>
    <param name="maxTradesPerWare" default="20"/>
    <param name="debugchance" default="0"/>
    <param name="mode" default="'match'"/>
    <param name="lineType" default="'source'"/>
    <param name="sourceStation" default="null"/>
    <param name="station" default="null"/>
    <param name="wareText" default="null"/>
    <param name="isPlayerOwned" default="false"/>
    <param name="diagMode" default="'unknown'"/>
    <param name="unavailableFlag" default="'0'"/>
    <param name="amountText" default="'n/a'"/>
    <param name="altUnavailableFlag" default="'n/a'"/>
    <param name="altAmountText" default="'n/a'"/>
    <param name="cargoCount" default="0"/>
    <param name="cargoTarget" default="0"/>
    <param name="cargoRatio" default="0"/>
    <param name="ignoreTradeRules" default="false"/>
    <param name="tradeListInput" default="[]"/>
    <param name="rawNeedAmount" default="0"/>
    <param name="incomingReservedAmount" default="0"/>
    <param name="shipChunkAmount" default="1"/>
    <param name="availableTradeWaresCount" default="1"/>
    <param name="reservedCount" default="0"/>
    <param name="alreadyReservedByThisShip" default="false"/>
    <param name="fairnessCap" default="2"/>
    <param name="synthesizeAmount" default="0"/>
    <param name="tradeOffer" default="null"/>
    <param name="operation" default="'find'"/>
    <param name="wareExchangeLegs" default="[]"/>
    <param name="sourceRatio" default="0"/>
    <param name="sourceOfferAmount" default="0"/>
    <param name="destOfferAmount" default="0"/>
    <param name="sourceStorageDiscovery" default="false"/>
    <param name="destStorageDiscovery" default="false"/>
    <param name="mk2StaticStorage" default="0"/>
    <param name="mk2MinStorage" default="0"/>
    <param name="mk2MaxStorage" default="0"/>
    <param name="pilotLevelProfile" default="1"/>
    <param name="routeAlpha" default="0"/>
    <param name="routeBeta" default="0"/>
    <param name="routeLaneBonus" default="1"/>
    <param name="minCargoFillPercent" default="25"/>
    <param name="allowLowVolume" default="false"/>
    <param name="lowVolumeFloorEffPercent" default="50"/>
    <param name="bidirectional" default="false"/>
    <param name="fleetCoordination" default="false"/>
    <param name="sourceUsageCount" default="0"/>
    <param name="destUsageCount" default="0"/>
    <param name="stickyCyclesLeft" default="0"/>
    <param name="stickySource" default="null"/>
    <param name="stickyDestination" default="null"/>
    <param name="stickyWare" default="null"/>
    <param name="lastTradeDestination" default="null"/>
    <param name="lastTradeSource" default="null"/>
    <param name="lastTradeWare" default="null"/>
    <param name="sourceStationRef" default="null"/>
    <param name="mk2SourceOffer" default="null"/>
    <param name="mk2DestOffer" default="null"/>
    <!-- MK4 compatibility params (accepted for call-site compatibility) -->
    <param name="mk4AllowResources" default="true"/>
    <param name="mk4AllowIntermediates" default="true"/>
    <param name="mk4AllowTradewares" default="true"/>
    <param name="mk4DedicatedServe" default="false"/>
    <param name="mk4AnchorHome" default="null"/>
    <param name="mk4BuildStorageOnlyMode" default="false"/>
    <param name="mk4AllowPlayerSuppliers" default="true"/>
    <param name="mk4AllowAiSuppliers" default="true"/>
    <param name="mk4CustomerMustBePlayer" default="false"/>
    <param name="mk4PlayerBuyModPct" default="0"/>
    <param name="maxDistanceBuy" default="0"/>
    <param name="maxDistanceSell" default="0"/>
    <param name="backtrackTolerance" default="0"/>
    <param name="allowZeroProfitSell" default="false"/>
    <!-- MK3 'Ignore Player Pricing' companion filter: when true, reject any match whose delivery (customer) station is player-owned. -->
    <param name="excludePlayerBuyers" default="false"/>
    <!-- MK3 'Ignore Player Pricing' profit-semantics override: when true AND the supplier (buy-leg owner) is player-owned,
         treat the supplier-side cost as zero (production is "free" from the player's perspective). This bypasses the
         negative/zero/min-profit rejections for player-sourced trades and scores them by gross sell income (sellPrice * amount).
         NPC-sourced trades in the same scan continue to use the normal profit gates and scoring. -->
    <param name="playerSupplierFreeProduction" default="false"/>
    <param name="allowStorageDock" default="false"/>
  </params>
  <!-- v3: restore outer-loop cooperative wait (blocking action index 1 for save compat).
       v4: save/load resume at that wait skips setup; this.$ is not persisted on library contexts. -->
  <patch sinceversion="2">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
  </patch>
  <patch sinceversion="3">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v3 patch applied (blocking wait index 1 restored; match accumulators on this.$tm_*)'" chance="100" filter="savegame"/>
  </patch>
  <patch sinceversion="4">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v4 patch applied (save/load resume rebuild guard for this.$tm_* snapshots)'" chance="100" filter="savegame"/>
  </patch>
  <patch sinceversion="5">
    <do_if value="not this.$gt_yieldMs?">
      <set_value name="this.$gt_yieldMs" exact="1"/>
    </do_if>
  </patch>
  <patch sinceversion="7">
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v7: reset match accumulators on each fresh run_script entry (fixes stale MK3 trades leaking into MK1 export)'" chance="100" filter="savegame"/>
  </patch>
  <patch sinceversion="8">
    <debug_text text="'[GT-TradeMatch] lib.gt.tradematch v8: post-wait resume only when offer scratch lost (fixes MK3 live-search freeze from v7 unconditional resume)'" chance="100" filter="savegame"/>
  </patch>
  <attention min="unknown">
    <actions>
      <!-- Yield interval must be set before any fast-return mode (MK2 hot loops call these back-to-back). -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <do_if value="$mode == 'count_distinct_wares'">
        <create_list name="$distinctWares"/>
        <set_value name="$distinctCount" exact="0"/>
        <do_if value="$tradeListInput? and $tradeListInput.count gt 0">
          <do_all exact="$tradeListInput.count" counter="$dwi">
            <set_value name="$dwTrade" exact="$tradeListInput.{$dwi}"/>
            <set_value name="$dwWare" exact="null"/>
            <do_if value="$dwTrade? and $dwTrade.$Ware?">
              <set_value name="$dwWare" exact="$dwTrade.$Ware"/>
            </do_if>
            <do_if value="$dwWare?">
              <set_value name="$dwSeen" exact="false"/>
              <do_all exact="$distinctWares.count" counter="$dwj">
                <do_if value="$distinctWares.{$dwj} == $dwWare">
                  <set_value name="$dwSeen" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not $dwSeen">
                <append_to_list name="$distinctWares" exact="$dwWare"/>
                <set_value name="$distinctCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $DistinctWares = $distinctWares,
          $DistinctCount = $distinctCount
        ]"/>
      </do_if>

      <do_if value="$mode == 'ware_fairness'">
        <set_value name="$chunkSafe" exact="[1, $shipChunkAmount].max"/>
        <set_value name="$effectiveNeedAmount" exact="[$rawNeedAmount - $incomingReservedAmount, 0].max"/>
        <set_value name="$maxShipsForWare" exact="0"/>
        <do_if value="$effectiveNeedAmount gt 0">
          <set_value name="$maxShipsForWare" exact="(($effectiveNeedAmount + $chunkSafe - 1) / $chunkSafe)i"/>
          <do_if value="$availableTradeWaresCount gt 1 and $fairnessCap gt 0">
            <set_value name="$maxShipsForWare" exact="[$maxShipsForWare, $fairnessCap].min"/>
          </do_if>
        </do_if>
        <set_value name="$reservationAllowsTrade" exact="false"/>
        <do_if value="$alreadyReservedByThisShip or $reservedCount lt $maxShipsForWare">
          <set_value name="$reservationAllowsTrade" exact="true"/>
        </do_if>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $EffectiveNeedAmount = $effectiveNeedAmount,
          $MaxShipsForWare = $maxShipsForWare,
          $ReservationAllowsTrade = $reservationAllowsTrade
        ]"/>
      </do_if>

      <do_if value="$mode == 'offerdiag_probe'">
        <set_value name="$diagModeResult" exact="'partner-filtered'"/>
        <set_value name="$altUnavailableFlagResult" exact="'n/a'"/>
        <set_value name="$altAmountTextResult" exact="'n/a'"/>
        <do_if value="$ignoreTradeRules and $station.isplayerowned">
          <set_value name="$diagModeResult" exact="'ignore-rules(player-owned)'"/>
          <set_value name="$altUnavailableFlagResult" exact="'1'"/>
          <set_value name="$altAmountTextResult" exact="'n/a'"/>
          <do_if value="$lineType == 'dest'">
            <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" result="$altOfferWithRules"/>
          </do_if>
          <do_else>
            <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" result="$altOfferWithRules"/>
          </do_else>
          <do_if value="$altOfferWithRules == null or not $altOfferWithRules.available">
            <set_value name="$altUnavailableFlagResult" exact="'0'"/>
          </do_if>
          <do_if value="$altOfferWithRules != null">
            <set_value name="$altAmountTextResult" exact="$altOfferWithRules.offeramount.{$ship}"/>
          </do_if>
        </do_if>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $Mode = $diagModeResult,
          $AltUnavailableFlag = $altUnavailableFlagResult,
          $AltAmountText = $altAmountTextResult
        ]"/>
      </do_if>

      <do_if value="$mode == 'offerdiag'">
        <set_value name="$ownerText" exact="if $isPlayerOwned then 'player' else 'foreign'"/>
        <set_value name="$detail" exact="''"/>
        <do_if value="$lineType == 'dest'">
          <set_value name="$detail" exact="$sourceStation.idcode + '->' + $station.idcode + ':' + $wareText + ' owner=' + $ownerText + ' mode=' + $diagMode + ' buy(unavailable=' + $unavailableFlag + ',amount=' + $amountText + ') altWithRules(unavailable=' + $altUnavailableFlag + ',amount=' + $altAmountText + ') cargo=' + $cargoCount + '/' + $cargoTarget + ' (' + $cargoRatio + '%)'"/>
        </do_if>
        <do_else>
          <set_value name="$detail" exact="$station.knownname + ' [' + $station.idcode + ']:' + $wareText + ' owner=' + $ownerText + ' mode=' + $diagMode + ' offer(unavailable=' + $unavailableFlag + ',amount=' + $amountText + ') altWithRules(unavailable=' + $altUnavailableFlag + ',amount=' + $altAmountText + ')'"/>
        </do_else>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="$detail"/>
      </do_if>

      <!-- MK2 player-station offer resolve: extended find fallbacks. -->
      <do_if value="$mode == 'mk2_ware_exchange_invoke'">
        <set_value name="$mk2WxRequestId" exact="$ship.idcode + '|WX|' + (player.age / 1ms)i"/>
        <set_value name="player.entity.$GT_MK2_WareExchangeRequest" exact="table[$RequestId = $mk2WxRequestId, $Ship = $ship, $ShipIdCode = $ship.idcode, $Legs = $wareExchangeLegs]"/>
        <raise_lua_event name="'gt.mk2QueueWareExchange'" param="$mk2WxRequestId"/>
        <set_value name="$mk2WxSuccess" exact="false"/>
        <set_value name="$mk2WxError" exact="'timeout'"/>
        <set_value name="$mk2WxQueueLegs" exact="[]"/>
        <set_value name="$mk2WxQueued" exact="0"/>
        <wait max="5s">
          <interrupt>
            <conditions>
              <event_object_signalled object="$ship" param="'gt_mk2_ware_exchange_done'"/>
            </conditions>
            <actions>
              <set_value name="$mk2WxResult" exact="player.entity.$GT_MK2_WareExchangeResult"/>
              <do_if value="$mk2WxResult? and $mk2WxResult.$RequestId == $mk2WxRequestId">
                <do_if value="$mk2WxResult.$Success? and $mk2WxResult.$Success">
                  <set_value name="$mk2WxSuccess" exact="true"/>
                  <set_value name="$mk2WxError" exact="''"/>
                  <do_if value="$mk2WxResult.$Queued?">
                    <set_value name="$mk2WxQueued" exact="$mk2WxResult.$Queued"/>
                  </do_if>
                  <do_if value="$mk2WxResult.$QueueLegs?">
                    <set_value name="$mk2WxQueueLegs" exact="$mk2WxResult.$QueueLegs"/>
                  </do_if>
                </do_if>
                <do_elseif value="$mk2WxResult.$Error?">
                  <set_value name="$mk2WxError" exact="$mk2WxResult.$Error"/>
                </do_elseif>
              </do_if>
            </actions>
          </interrupt>
        </wait>
        <remove_value name="player.entity.$GT_MK2_WareExchangeRequest"/>
        <remove_value name="player.entity.$GT_MK2_WareExchangeResult"/>
        <return value="table[
          $Success = $mk2WxSuccess,
          $Error = $mk2WxError,
          $Queued = $mk2WxQueued,
          $QueueLegs = $mk2WxQueueLegs
        ]"/>
      </do_if>

      <do_if value="$mode == 'mk2_player_offer'">
        <set_value name="$mk2OfferResult" exact="null"/>
        <set_value name="$mk2OfferFound" exact="false"/>
        <set_value name="$mk2OfferSynthetic" exact="false"/>
        <!-- operation == 'find' (default) -->
        <do_if value="$ignoreTradeRules and $station.isplayerowned">
          <do_if value="$lineType == 'dest'">
            <find_buy_offer buyer="$station" wares="$wareText" result="$mk2OfferResult"/>
            <do_if value="$mk2OfferResult == null">
              <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_buy_offer buyer="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
          </do_if>
          <do_else>
            <find_sell_offer seller="$station" wares="$wareText" result="$mk2OfferResult"/>
            <do_if value="$mk2OfferResult == null">
              <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_sell_offer seller="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
            <do_if value="$mk2OfferResult == null">
              <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" excludeempty="false" result="$mk2OfferResult"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="$lineType == 'dest'">
            <find_buy_offer tradepartner="$ship" buyer="$station" wares="$wareText" result="$mk2OfferResult"/>
          </do_if>
          <do_else>
            <find_sell_offer tradepartner="$ship" seller="$station" wares="$wareText" result="$mk2OfferResult"/>
          </do_else>
        </do_else>
        <do_if value="$mk2OfferResult != null">
          <set_value name="$mk2OfferFound" exact="true"/>
        </do_if>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $Offer = $mk2OfferResult,
          $Found = $mk2OfferFound,
          $Synthetic = $mk2OfferSynthetic
        ]"/>
      </do_if>

      <do_if value="$mode == 'mk2_storage_pair_score'">
        <set_value name="$mk2TradeEntry" exact="null"/>
        <set_value name="$mk2SkipType" exact="'none'"/>
        <set_value name="$needBucket" exact="'none'"/>
        <set_value name="$bucketWeight" exact="1.0"/>
        <set_value name="$isCriticalNeed" exact="false"/>
        <set_value name="$shouldDistribute" exact="false"/>
        <do_if value="$pilotLevelProfile ge 4">
          <do_if value="$cargoRatio le 5">
            <set_value name="$needBucket" exact="'A'"/>
            <set_value name="$bucketWeight" exact="3.0"/>
            <set_value name="$isCriticalNeed" exact="true"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_if>
          <do_elseif value="$cargoRatio le 20">
            <set_value name="$needBucket" exact="'B'"/>
            <set_value name="$bucketWeight" exact="2.0"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
          <do_elseif value="$cargoRatio le $mk2MinStorage">
            <set_value name="$needBucket" exact="'C'"/>
            <set_value name="$bucketWeight" exact="1.4"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
          <do_elseif value="$sourceRatio gt $mk2MaxStorage and $sourceRatio gt ($cargoRatio + 10)">
            <set_value name="$needBucket" exact="'D'"/>
            <set_value name="$bucketWeight" exact="1.0"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
        </do_if>
        <do_else>
          <do_if value="$cargoRatio le 5">
            <set_value name="$needBucket" exact="'A'"/>
            <set_value name="$bucketWeight" exact="2.4"/>
            <set_value name="$isCriticalNeed" exact="true"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_if>
          <do_elseif value="$cargoRatio le $mk2MinStorage">
            <set_value name="$needBucket" exact="'C'"/>
            <set_value name="$bucketWeight" exact="1.2"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
          <do_elseif value="$sourceRatio gt $mk2MaxStorage and $sourceRatio gt ($cargoRatio + 10)">
            <set_value name="$needBucket" exact="'D'"/>
            <set_value name="$bucketWeight" exact="1.0"/>
            <set_value name="$shouldDistribute" exact="true"/>
          </do_elseif>
        </do_else>
        <do_if value="not $shouldDistribute">
          <set_value name="$mk2SkipType" exact="'noNeed'"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <do_if value="$lastTradeSource? and $lastTradeSource.exists and $lastTradeDestination? and $lastTradeDestination.exists and $lastTradeWare? and $sourceStation == $lastTradeDestination and $station == $lastTradeSource and $wareText == $lastTradeWare and $needBucket != 'A'">
          <set_value name="$mk2SkipType" exact="'pingPong'"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <set_value name="$cargoCapacity" exact="$ship.cargo.{$wareText}.max"/>
        <set_value name="$incomingReservedAmount" exact="0"/>
        <set_value name="$reservedShipCount" exact="0"/>
        <set_value name="$effectiveDestOfferAmount" exact="$destOfferAmount"/>
        <do_if value="$fleetCoordination and $station? and $station.exists">
          <get_ware_reservation object="$station" ware="$wareText" type="sell" virtual="false" result="$incomingReservedAmount"/>
          <set_value name="$reservedShipCount" exact="(($incomingReservedAmount + [1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max - 1) / [1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max)i"/>
        </do_if>
        <set_value name="$shipChunkAmount" exact="[1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max"/>
        <set_value name="$effectiveNeedAmount" exact="[$destOfferAmount - 0, 0].max"/>
        <set_value name="$maxShipsForWare" exact="0"/>
        <do_if value="$effectiveNeedAmount gt 0">
          <set_value name="$maxShipsForWare" exact="(($effectiveNeedAmount + $shipChunkAmount - 1) / $shipChunkAmount)i"/>
        </do_if>
        <set_value name="$effectiveDestOfferAmount" exact="$effectiveNeedAmount"/>
        <do_if value="$effectiveDestOfferAmount le 0">
          <set_value name="$mk2SkipType" exact="'reserved'"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <set_value name="$tradeAmount" exact="[$ship.cargo.{$wareText}.free, $sourceOfferAmount, $effectiveDestOfferAmount].min"/>
        <set_value name="$normalMinimumTrade" exact="[1, (($cargoCapacity * $minCargoFillPercent) / 100)i].max"/>
        <set_value name="$minimumTrade" exact="$normalMinimumTrade"/>
        <set_value name="$usedLowVolume" exact="false"/>
        <set_value name="$canLowVolume" exact="false"/>
        <do_if value="$allowLowVolume">
          <do_if value="$pilotLevelProfile ge 6 or $isCriticalNeed">
            <set_value name="$canLowVolume" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$canLowVolume">
          <set_value name="$minimumTrade" exact="[1, (($cargoCapacity * $lowVolumeFloorEffPercent) / 100)i].max"/>
          <do_if value="$isCriticalNeed">
            <set_value name="$minimumTrade" exact="[1, ($minimumTrade / 2)i].max"/>
          </do_if>
          <set_value name="$usedLowVolume" exact="true"/>
        </do_if>
        <do_if value="$tradeAmount lt $minimumTrade">
          <set_value name="$mk2SkipType" exact="'minTrade'"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="table[$TradeEntry = null, $SkipType = $mk2SkipType]"/>
        </do_if>
        <set_value name="$urgencyMultiplier" exact="$bucketWeight"/>
        <set_value name="$balanceFactor" exact="[0, ($sourceRatio - $cargoRatio)].max / 100"/>
        <set_value name="$baseScore" exact="(($sourceRatio - $mk2StaticStorage) * $urgencyMultiplier * ($tradeAmount / [$cargoCapacity, 1].max)) + $balanceFactor - (($sourceUsageCount + $destUsageCount) * 0.2)"/>
        <set_value name="$shipToSourceGates" exact="$ship.gatedistance.{$sourceStation}"/>
        <set_value name="$sourceToDestGates" exact="$sourceStation.gatedistance.{$station}"/>
        <set_value name="$forwardGates" exact="[0, $shipToSourceGates].max + [0, $sourceToDestGates].max"/>
        <set_value name="$baselineGates" exact="$forwardGates"/>
        <do_if value="$sourceStationRef? and $sourceStationRef.exists and $lastTradeDestination? and $lastTradeDestination.exists">
          <set_value name="$baseShipToSourceGates" exact="$ship.gatedistance.{$sourceStationRef}"/>
          <set_value name="$baseSourceToDestGates" exact="$sourceStationRef.gatedistance.{$lastTradeDestination}"/>
          <do_if value="$baseShipToSourceGates ge 0 and $baseSourceToDestGates ge 0">
            <set_value name="$baselineGates" exact="$baseShipToSourceGates + $baseSourceToDestGates"/>
          </do_if>
        </do_if>
        <set_value name="$deltaGates" exact="[0, $forwardGates - $baselineGates].max"/>
        <set_value name="$backtrackPenalty" exact="0"/>
        <do_if value="not $bidirectional and (not $lastTradeDestination? or not $lastTradeDestination.exists or $sourceStation != $lastTradeDestination)">
        <do_if value="$lastTradeDestination? and $lastTradeDestination.exists">
          <set_value name="$prevToDestGates" exact="$lastTradeDestination.gatedistance.{$station}"/>
          <set_value name="$prevToSourceGates" exact="$lastTradeDestination.gatedistance.{$sourceStation}"/>
          <do_if value="$prevToDestGates ge 0 and $prevToSourceGates ge 0 and $prevToDestGates gt ($prevToSourceGates + 1)">
            <set_value name="$backtrackPenalty" exact="1"/>
          </do_if>
        </do_if>
        </do_if>
        <set_value name="$laneBonus" exact="1.0"/>
        <do_if value="$stickyCyclesLeft gt 0 and $stickySource? and $stickyDestination? and $stickyWare? and $stickySource == $sourceStation and $stickyDestination == $station and $stickyWare == $wareText">
          <set_value name="$laneBonus" exact="$routeLaneBonus"/>
        </do_if>
        <set_value name="$routeT" exact="$pilotLevelProfile / 15.0"/>
        <set_value name="$nearStationFactor" exact="1.0"/>
        <do_if value="$lastTradeDestination? and $lastTradeDestination.exists">
          <do_if value="$sourceStation == $lastTradeDestination">
            <set_value name="$nearStationFactor" exact="$routeLaneBonus"/>
            <do_if value="$shipToSourceGates == 0">
              <set_value name="$nearStationFactor" exact="$nearStationFactor * 1.10"/>
            </do_if>
          </do_if>
          <do_elseif value="$pilotLevelProfile ge 4">
            <set_value name="$nearStationFactor" exact="0.80 + (0.20 * $routeT)"/>
          </do_elseif>
        </do_if>
        <set_value name="$costFactor" exact="1.0"/>
        <do_if value="$pilotLevelProfile ge 4">
          <set_value name="$costFactor" exact="1.0 + ($routeAlpha * $deltaGates) + ($routeBeta * $backtrackPenalty)"/>
          <do_if value="$lastTradeDestination? and $lastTradeDestination.exists and $sourceStation != $lastTradeDestination">
            <set_value name="$detourFromLastGates" exact="$lastTradeDestination.gatedistance.{$sourceStation}"/>
            <do_if value="$detourFromLastGates ge 0">
              <set_value name="$costFactor" exact="$costFactor + ($routeAlpha * $detourFromLastGates)"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$costFactor" exact="1.0 + (0.20 * $forwardGates)"/>
        </do_else>
        <set_value name="$score" exact="($baseScore * $laneBonus * $nearStationFactor) / [1.0, $costFactor].max"/>
        <set_value name="$mk2TradeEntry" exact="table[
          $Ware = $wareText,
          $Source = $sourceStation,
          $Destination = $station,
          $Amount = $tradeAmount,
          $Urgent = $isCriticalNeed,
          $NeedBucket = $needBucket,
          $Score = $score,
          $SourceOffer = $mk2SourceOffer,
          $DestOffer = $mk2DestOffer,
          $SourceOfferAmount = $sourceOfferAmount,
          $DestOfferAmount = $destOfferAmount,
          $EffectiveDestOfferAmount = $effectiveDestOfferAmount,
          $IncomingReservedAmount = $incomingReservedAmount,
          $NormalMinimumTrade = $normalMinimumTrade,
          $UsedLowVolume = $usedLowVolume,
          $DeltaGates = $deltaGates,
          $BacktrackPenalty = $backtrackPenalty,
          $SourceStorageDiscovery = $sourceStorageDiscovery,
          $DestStorageDiscovery = $destStorageDiscovery
        ]"/>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[$TradeEntry = $mk2TradeEntry, $SkipType = $mk2SkipType]"/>
      </do_if>

      <do_if value="not $sellOffers? or not $buyOffers? or $sellOffers.count == 0 or $buyOffers.count == 0">
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = [],
          $TradesEvaluated = 0,
          $TradesRejected = 0,
          $TradesRejectedRouteIllegal = 0,
          $TradesRejectedMk4CustomerPolicy = 0,
          $TradesRejectedMk4SupplierPolicy = 0,
          $TradesRejectedMk4TypePolicy = 0,
          $TradesRejectedMk4DemandGate = 0,
          $TradesRejectedMk4PriceCap = 0,
          $TradesRejectedDistance = 0
        ]"/>
      </do_if>

      <!-- Fresh run_script entry resets match accumulators. Library this.$ persists on the same ship;
           without this, a prior MK3 buy_and_sell scan leaves sector arbitrage rows in $TradeList and
           MK1 export (home sellOffers + NPC buyOffers) scores/selects those stale trades. -->
      <create_list name="this.$tm_tradeList"/>
      <set_value name="this.$tm_bestTrade" exact="null"/>
      <set_value name="this.$tm_bestScore" exact="0"/>
      <set_value name="this.$tm_tradesEvaluated" exact="0"/>
      <set_value name="this.$tm_tradesRejected" exact="0"/>
      <set_value name="this.$tm_tradesRejectedRouteIllegal" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4TypePolicy" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4DemandGate" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4PriceCap" exact="0"/>
      <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" exact="0"/>
      <set_value name="this.$tm_tradesRejectedDistance" exact="0"/>
      <set_value name="this.$tm_tradesRejectedSameStation" exact="0"/>
      <set_value name="this.$tm_tradesPerWare" exact="table[]"/>
      <set_value name="this.$tm_supplyScoreDiagCount" exact="0"/>
      <remove_value name="this.$tm_abortMatch"/>

      <!-- Rebuild match state after save/load resume at blocking wait (index 1).
           In-loop waits resume at tm_ensure_state below (skip accumulator reset above). -->
      <label name="tm_ensure_state"/>
      <do_if value="this.$tm_abortMatch?">
        <remove_value name="this.$tm_abortMatch"/>
      </do_if>
      <do_if value="not this.$tm_tradeList?">
        <create_list name="this.$tm_tradeList"/>
      </do_if>
      <do_if value="not this.$tm_bestTrade?">
        <set_value name="this.$tm_bestTrade" exact="null"/>
      </do_if>
      <do_if value="not this.$tm_bestScore?">
        <set_value name="this.$tm_bestScore" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesEvaluated?">
        <set_value name="this.$tm_tradesEvaluated" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejected?">
        <set_value name="this.$tm_tradesRejected" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedRouteIllegal?">
        <set_value name="this.$tm_tradesRejectedRouteIllegal" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4CustomerPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4SupplierPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4TypePolicy?">
        <set_value name="this.$tm_tradesRejectedMk4TypePolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4DemandGate?">
        <set_value name="this.$tm_tradesRejectedMk4DemandGate" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4PriceCap?">
        <set_value name="this.$tm_tradesRejectedMk4PriceCap" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4BuildStorageOnly?">
        <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedDistance?">
        <set_value name="this.$tm_tradesRejectedDistance" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_supplyScoreDiagCount?">
        <set_value name="this.$tm_supplyScoreDiagCount" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesPerWare?">
        <set_value name="this.$tm_tradesPerWare" exact="table[]"/>
      </do_if>
      <do_if value="not global.$GT_TradeMatchScratch?">
        <set_value name="global.$GT_TradeMatchScratch" exact="table[]"/>
      </do_if>
      <set_value name="global.$GT_TradeMatchScratch.{$ship}" exact="table[$SellOffers = $sellOffers, $BuyOffers = $buyOffers]"/>
      <set_value name="$scratchSellOffers" exact="$sellOffers"/>
      <set_value name="$scratchBuyOffers" exact="$buyOffers"/>
      <do_if value="not $scratchSellOffers? and global.$GT_TradeMatchScratch.{$ship}.$SellOffers?">
        <set_value name="$scratchSellOffers" exact="global.$GT_TradeMatchScratch.{$ship}.$SellOffers"/>
      </do_if>
      <do_if value="not $scratchBuyOffers? and global.$GT_TradeMatchScratch.{$ship}.$BuyOffers?">
        <set_value name="$scratchBuyOffers" exact="global.$GT_TradeMatchScratch.{$ship}.$BuyOffers"/>
      </do_if>
      <create_list name="this.$tm_matchSellOffers"/>
      <set_value name="$scratchSellCount" exact="if $scratchSellOffers? then $scratchSellOffers.count else 0"/>
      <do_all exact="$scratchSellCount" counter="$sosi">
        <set_value name="$soCand" exact="@$scratchSellOffers.{$sosi}"/>
        <do_if value="$soCand? and @$soCand.exists">
          <append_to_list name="this.$tm_matchSellOffers" exact="$soCand"/>
        </do_if>
      </do_all>
      <create_list name="this.$tm_matchBuyOffers"/>
      <set_value name="$scratchBuyCount" exact="if $scratchBuyOffers? then $scratchBuyOffers.count else 0"/>
      <do_all exact="$scratchBuyCount" counter="$bosi">
        <set_value name="$boCand" exact="@$scratchBuyOffers.{$bosi}"/>
        <do_if value="$boCand? and @$boCand.exists">
          <append_to_list name="this.$tm_matchBuyOffers" exact="$boCand"/>
        </do_if>
      </do_all>
      <!-- Ware-indexed buy offers: inner pairing loop iterates matching ware only (S5). -->
      <set_value name="this.$tm_buyOffersByWare" exact="table[]"/>
      <set_value name="$tmBuyIndexCount" exact="this.$tm_matchBuyOffers.count"/>
      <do_all exact="$tmBuyIndexCount" counter="$boi">
        <set_value name="$boIdx" exact="this.$tm_matchBuyOffers.{$boi}"/>
        <do_if value="$boIdx? and $boIdx.ware?">
          <set_value name="$boWare" exact="@$boIdx.ware"/>
          <do_if value="$boWare != null">
            <do_if value="not this.$tm_buyOffersByWare.{$boWare}?">
              <create_list name="this.$tm_buyOffersByWare.{$boWare}"/>
            </do_if>
            <append_to_list name="this.$tm_buyOffersByWare.{$boWare}" exact="$boIdx"/>
          </do_if>
        </do_if>
      </do_all>
      <do_if value="this.$tm_matchSellOffers.count == 0 or this.$tm_matchBuyOffers.count == 0">
        <set_value name="this.$tm_abortMatch" exact="true"/>
      </do_if>

      <label name="tm_match_run"/>
      <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
        <resume label="tm_ensure_state"/>
      </do_if>
      <do_if value="this.$tm_abortMatch?">
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
        <return value="table[
          $Found = false,
          $BestTrade = null,
          $BestScore = 0,
          $TradeList = this.$tm_tradeList,
          $TradesEvaluated = 0,
          $TradesRejected = 0,
          $TradesRejectedRouteIllegal = 0,
          $TradesRejectedMk4CustomerPolicy = 0,
          $TradesRejectedMk4SupplierPolicy = 0,
          $TradesRejectedMk4TypePolicy = 0,
          $TradesRejectedMk4DemandGate = 0,
          $TradesRejectedMk4PriceCap = 0,
          $TradesRejectedDistance = 0
        ]"/>
      </do_if>
      <set_value name="$tmSellLoopCount" exact="this.$tm_matchSellOffers.count"/>

      <do_all exact="$tmSellLoopCount" counter="$si">
        <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
          <resume label="tm_ensure_state"/>
        </do_if>
        <do_if value="this.$tm_abortMatch?">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="table[
            $Found = false,
            $BestTrade = null,
            $BestScore = 0,
            $TradeList = this.$tm_tradeList,
            $TradesEvaluated = 0,
            $TradesRejected = 0,
            $TradesRejectedRouteIllegal = 0,
            $TradesRejectedMk4CustomerPolicy = 0,
            $TradesRejectedMk4SupplierPolicy = 0,
            $TradesRejectedMk4TypePolicy = 0,
            $TradesRejectedMk4DemandGate = 0,
            $TradesRejectedMk4PriceCap = 0,
            $TradesRejectedDistance = 0
          ]"/>
        </do_if>
        <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
          <resume label="tm_ensure_state"/>
        </do_if>
        <do_if value="this.$tm_abortMatch?">
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before immediate return (wake-loop guard)"/>
          <return value="table[
            $Found = false,
            $BestTrade = null,
            $BestScore = 0,
            $TradeList = this.$tm_tradeList,
            $TradesEvaluated = 0,
            $TradesRejected = 0,
            $TradesRejectedRouteIllegal = 0,
            $TradesRejectedMk4CustomerPolicy = 0,
            $TradesRejectedMk4SupplierPolicy = 0,
            $TradesRejectedMk4TypePolicy = 0,
            $TradesRejectedMk4DemandGate = 0,
            $TradesRejectedMk4PriceCap = 0,
            $TradesRejectedDistance = 0
          ]"/>
        </do_if>
        <set_value name="$sellOffer" exact="this.$tm_matchSellOffers.{$si}"/>
        <set_value name="$ware" exact="@$sellOffer.ware"/>
        <!-- Supplier station: prefer game sell-offer seller (matches trade execution / MK4 validation). -->
        <set_value name="$buyStation" exact="null"/>
        <do_if value="$sellOffer?">
          <do_if value="$sellOffer.seller? and @$sellOffer.seller.exists">
            <set_value name="$buyStation" exact="@$sellOffer.seller"/>
          </do_if>
          <do_elseif value="$sellOffer.owner?">
            <set_value name="$buyStation" exact="@$sellOffer.owner"/>
          </do_elseif>
        </do_if>

        <!-- Per-ware early skip: if this ware already has max trades, skip entire inner loop -->
        <do_if value="$ware? and this.$tm_tradesPerWare.{$ware}? and this.$tm_tradesPerWare.{$ware} ge $maxTradesPerWare">
          <continue/>
        </do_if>

        <set_value name="$tmBuyListForWare" exact="if $ware? and this.$tm_buyOffersByWare? and this.$tm_buyOffersByWare.{$ware}? then this.$tm_buyOffersByWare.{$ware} else []"/>
        <set_value name="$tmBuyLoopCount" exact="$tmBuyListForWare.count"/>
        <do_if value="$tmBuyLoopCount == 0">
          <continue/>
        </do_if>
        <do_all exact="$tmBuyLoopCount" counter="$bi">
          <set_value name="$buyOffer" exact="$tmBuyListForWare.{$bi}"/>
          <!-- Delivery customer: prefer game buy-offer buyer (matches trade execution / MK4 validation). -->
          <set_value name="$sellStation" exact="null"/>
          <do_if value="$buyOffer?">
            <do_if value="$buyOffer.buyer? and @$buyOffer.buyer.exists">
              <set_value name="$sellStation" exact="@$buyOffer.buyer"/>
            </do_if>
            <do_elseif value="$buyOffer.owner?">
              <set_value name="$sellStation" exact="@$buyOffer.owner"/>
            </do_elseif>
          </do_if>
          <!-- Per-ware trade cap (inner loop): stop producing more trades for this ware
               once the limit is reached. The outer-loop early skip handles the next sell offer,
               but a single sell offer can pair with hundreds of buy offers for the same ware. -->
          <do_if value="$ware? and this.$tm_tradesPerWare.{$ware}? and this.$tm_tradesPerWare.{$ware} ge $maxTradesPerWare">
            <break/>
          </do_if>
          <do_if value="$buyStation == null or $sellStation == null">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$buyStation == $sellStation">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedSameStation" operation="add"/>
            <continue/>
          </do_if>

          <!-- MK3 'Ignore Player Pricing' companion filter: reject any trade whose delivery
               customer ($sellStation) is player-owned. The MK3 ship must sell only to NPCs. -->
          <do_if value="$excludePlayerBuyers and @$sellStation.isplayerowned">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- MK3 'Ignore Player Pricing' profit-semantics override:
               When the supplier is player-owned and the override is enabled, the player's
               production cost for this ware is treated as zero (the station produced it for
               "free" within the player's economy). Every credit the NPC customer pays is then
               pure income, so the negative/zero/min-profit rejections must be skipped for
               this pair, and gross income (sellPrice * amount) is used as the score basis.
               NPC->NPC pairs in the same scan continue to use the normal profit gates. -->
          <set_value name="$playerFreeSupplier" exact="$playerSupplierFreeProduction and @$buyStation.isplayerowned"/>

          <!-- MK4 supply hard policy (early gate):
               Delivery customer is $sellStation (game buy-offer owner). -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer">
            <do_if value="not @$sellStation.isplayerowned">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4 supplier policy (early gate):
               Supplier station is $buyStation (game sell-offer owner). -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer">
            <do_if value="not $mk4AllowPlayerSuppliers and @$buyStation.isplayerowned">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="not $mk4AllowAiSuppliers and not @$buyStation.isplayerowned">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4 build-storage-only mode (implicit: allowBuildstorage on, all ware-category toggles off):
               delivery buyer must be player build storage within jumpDistanceCoverage; BS supplier legs blocked. -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer and $mk4BuildStorageOnlyMode">
            <do_if value="$buyStation.isclass.buildstorage">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="not $sellStation.isclass.buildstorage">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" operation="add"/>
              <continue/>
            </do_if>
            <!-- BS-only delivery scope: player build storage within jumpDistanceCoverage from home. -->
            <set_value name="$mk4BsoCoverageMax" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
            <set_value name="$mk4BsoInScope" exact="false"/>
            <set_value name="$mk4BsoDist" exact="if $homeSector? and $sellStation? and $sellStation.sector? then $homeSector.gatedistance.{$sellStation.sector} else -1"/>
            <do_if value="$mk4BsoDist ge 0 and ($mk4BsoCoverageMax le 0 or $mk4BsoDist le $mk4BsoCoverageMax)">
              <set_value name="$mk4BsoInScope" exact="true"/>
            </do_if>
            <do_if value="not $mk4BsoInScope">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4 ware-type policy gate (evaluated against customer station context):
               - Resources: pure resources (non-intermediate)
               - Intermediates: intermediate wares and products
               - Tradewares: station tradewares -->
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer and $sellStation? and $ware? and (not $sellStation.isclass.buildstorage or $ignoreBuildStorage)">
            <set_value name="$mk4IsTradeWare" exact="$sellStation.tradewares.{$ware}.exists"/>
            <set_value name="$mk4IsResource" exact="$sellStation.resources.{$ware}.exists"/>
            <set_value name="$mk4IsProduct" exact="$sellStation.products.{$ware}.exists"/>
            <set_value name="$mk4IsIntermediate" exact="false"/>
            <do_if value="$sellStation.resources.{$ware}.exists and @$sellStation.resources.{$ware}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <do_if value="$sellStation.products.{$ware}.exists and @$sellStation.products.{$ware}.intermediate">
              <set_value name="$mk4IsIntermediate" exact="true"/>
            </do_if>
            <set_value name="$mk4IsPureResource" exact="$mk4IsResource and not $mk4IsIntermediate"/>
            <set_value name="$mk4IsIntermediateOrProduct" exact="$mk4IsIntermediate or $mk4IsProduct"/>
            <set_value name="$mk4HasKnownType" exact="$mk4IsTradeWare or $mk4IsResource or $mk4IsProduct"/>
            <set_value name="$mk4AllowedByType" exact="false"/>
            <do_if value="$mk4IsTradeWare and $mk4AllowTradewares">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsPureResource and $mk4AllowResources">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="not $mk4AllowedByType and $mk4IsIntermediateOrProduct and $mk4AllowIntermediates">
              <set_value name="$mk4AllowedByType" exact="true"/>
            </do_if>
            <do_if value="$mk4HasKnownType and not $mk4AllowedByType">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedMk4TypePolicy" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Build storage exclusion -->
          <do_if value="$ignoreBuildStorage">
            <do_if value="$buyStation.isclass.buildstorage or $sellStation.isclass.buildstorage">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Carrier / auxiliary exclusion (stations are never carriers/auxiliaries, only ships can be) -->
          <do_if value="$ignoreCarrierAux">
            <do_if value="($buyStation.isclass.ship and ($buyStation.type == shiptype.carrier or $buyStation.type == shiptype.resupplier)) or ($sellStation.isclass.ship and ($sellStation.type == shiptype.carrier or $sellStation.type == shiptype.resupplier))">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- MK4 supply early economics gates: price cap + per-leg distance before dock/clamp (perf). -->
          <set_value name="$unitProfit" exact="$buyOffer.unitprice - $sellOffer.unitprice"/>
          <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer and $unitProfit lt 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedMk4PriceCap" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$maxDistanceBuyLeg" exact="if $maxDistanceBuy? and $maxDistanceBuy gt 0 then $maxDistanceBuy else $maxDistance"/>
          <set_value name="$maxDistanceSellLeg" exact="if $maxDistanceSell? and $maxDistanceSell gt 0 then $maxDistanceSell else $maxDistance"/>
          <set_value name="$distBuy" exact="$homeSector.gatedistance.{$buyStation}"/>
          <do_if value="$distBuy lt 0 or $distBuy gt $maxDistanceBuyLeg">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$distSell" exact="$homeSector.gatedistance.{$sellStation}"/>
          <do_if value="$distSell lt 0 or $distSell gt $maxDistanceSellLeg">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$scoreMode == 'supply' and $backtrackTolerance? and $backtrackTolerance ge 0 and (not $maxDistanceBuy? or $maxDistanceBuy le 0)">
            <set_value name="$maxSupplierDistance" exact="$maxDistanceSellLeg + $backtrackTolerance"/>
            <do_if value="$distBuy gt $maxSupplierDistance">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Dock feasibility (vanilla order.dock.xml: trading dock on destination).
               Build-storage legs use $buyOffer.buyer â€” not the parent station. -->
          <do_if value="$scoreMode == 'supply'">
            <run_script name="'lib.gt.dockcheck'" result="$tmBuyDockResult">
              <param name="ship" value="$ship"/>
              <param name="station" value="$buyStation"/>
              <param name="purpose" value="'trade'"/>
              <param name="useMemo" value="true"/>
            </run_script>
            <run_script name="'lib.gt.dockcheck'" result="$tmSellDockResult">
              <param name="ship" value="$ship"/>
              <param name="station" value="$sellStation"/>
              <param name="purpose" value="'trade'"/>
              <param name="useMemo" value="true"/>
            </run_script>
            <do_if value="not $tmBuyDockResult.$CanDock or not $tmSellDockResult.$CanDock">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <!-- Shared amount semantics:
               Prefer per-ship effective offer amounts (offeramount.{ship}) to match vanilla
               trade resolution, especially for internal/no-money flows. Fallback to raw amount
               when offeramount is unavailable. -->
          <set_value name="$sellOfferAmount" exact="0"/>
          <do_if value="$sellOffer.offeramount.{$ship}?">
            <set_value name="$sellOfferAmount" exact="$sellOffer.offeramount.{$ship}"/>
          </do_if>
          <do_elseif value="$sellOffer.amount?">
            <set_value name="$sellOfferAmount" exact="$sellOffer.amount"/>
          </do_elseif>
          <!-- Diagnose parity: offeramount.{ship} may exist but be 0 (build storage / internal flows). -->
          <do_if value="$sellOfferAmount le 0 and $sellOffer.amount? and $sellOffer.amount gt 0">
            <set_value name="$sellOfferAmount" exact="$sellOffer.amount"/>
          </do_if>
          <set_value name="$buyOfferAmount" exact="0"/>
          <do_if value="$buyOffer.offeramount.{$ship}?">
            <set_value name="$buyOfferAmount" exact="$buyOffer.offeramount.{$ship}"/>
          </do_if>
          <do_elseif value="$buyOffer.amount?">
            <set_value name="$buyOfferAmount" exact="$buyOffer.amount"/>
          </do_elseif>
          <do_if value="$buyOfferAmount le 0 and $buyOffer.amount? and $buyOffer.amount gt 0">
            <set_value name="$buyOfferAmount" exact="$buyOffer.amount"/>
          </do_if>
          <do_if value="$buyOfferAmount le 0 and $sellStation? and $sellStation.exists and $ware?">
            <!-- Target-count demand fallback (mirrors gt_context_diagnose pair eval for all modes). -->
            <set_value name="$buyOfferDemandFallback" exact="[0, $sellStation.cargo.{$ware}.target - $sellStation.cargo.{$ware}.count].max"/>
            <do_if value="$buyOfferDemandFallback gt 0">
              <set_value name="$buyOfferAmount" exact="$buyOfferDemandFallback"/>
            </do_if>
          </do_if>

          <!-- Demand reservation gate (all modes):
               Subtract incoming vanilla reservations from destination demand before scoring.
               Also subtract in-flight GT reservations for the same destination offer.
               If effective need is exhausted, skip this ware pair early so saturated wares
               do not dominate top candidates and storage is not overfilled.
               Baseline uses max(per-ship offeramount, raw offer.amount, cargo deficit) because
               a single offer slice can understate build-storage / station need while
               get_ware_reservation is station-wide for the ware. -->
          <set_value name="$demandBaseline" exact="$buyOfferAmount"/>
          <do_if value="$buyOffer? and $buyOffer.amount? and $buyOffer.amount gt $demandBaseline">
            <set_value name="$demandBaseline" exact="$buyOffer.amount"/>
          </do_if>
          <do_if value="$sellStation? and $sellStation.exists and $ware?">
            <set_value name="$cargoDeficit" exact="[0, $sellStation.cargo.{$ware}.target - $sellStation.cargo.{$ware}.count].max"/>
            <do_if value="$cargoDeficit gt $demandBaseline">
              <set_value name="$demandBaseline" exact="$cargoDeficit"/>
            </do_if>
          </do_if>
          <do_if value="$sellStation? and $sellStation.exists and $ware?">
            <set_value name="$incomingReservedAmount" exact="0"/>
            <get_ware_reservation object="$sellStation" ware="$ware" type="sell" virtual="false" result="$incomingReservedAmount"/>
            <!-- GT in-flight reservation demand gate:
                 subtract fleet pre-selection reservations for the same destination offer. -->
            <set_value name="$gtIncomingReservedAmount" exact="0"/>
            <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$buyOffer}?">
              <set_value name="$gtResData" exact="global.$GT_Reservations.{$buyOffer}"/>
              <do_if value="$gtResData.$Until? and player.age lt @$gtResData.$Until">
                <do_if value="not $gtResData.$Ship? or @$gtResData.$Ship != $ship">
                  <set_value name="$gtResAmount" exact="0"/>
                  <do_if value="$gtResData.$Amount? and @$gtResData.$Amount gt 0">
                    <set_value name="$gtResAmount" exact="$gtResData.$Amount"/>
                  </do_if>
                  <do_else>
                    <set_value name="$gtResAmount" exact="1"/>
                  </do_else>
                  <set_value name="$gtIncomingReservedAmount" exact="$gtIncomingReservedAmount + $gtResAmount"/>
                </do_if>
              </do_if>
            </do_if>
            <set_value name="$effectiveBuyNeedAmount" exact="[$demandBaseline - $incomingReservedAmount - $gtIncomingReservedAmount, 0].max"/>
            <do_if value="$effectiveBuyNeedAmount le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <do_if value="$scoreMode == 'supply' and $mk4CustomerMustBePlayer">
                <set_value name="this.$tm_tradesRejectedMk4DemandGate" operation="add"/>
              </do_if>
              <continue/>
            </do_if>
            <set_value name="$buyOfferAmount" exact="$effectiveBuyNeedAmount"/>
          </do_if>

          <!-- UNIVERSAL CACHE BASIS:
               Do not bind cached trade amount/score to the writer ship's free cargo.
               Cache entries should represent station-side opportunity; per-ship execution
               amount is resolved later via clamp_trade_amount in order.trade.galaxytrader. -->
          <set_value name="$tradeAmount" exact="[$sellOfferAmount, $buyOfferAmount].min"/>
          <do_if value="$tradeAmount le 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- clamp_trade_amount preview (mirrors order.trade.galaxytrader trade_found).
               Rejects broker/warehouse offers that list amount/offeramount but have no
               exportable seller stock at execution time.
               Seller/buyer resolution MUST match trade_found validation: prefer offer.seller
               when seller? is set â€” do NOT gate on .exists or fall back to owner while seller?
               is set (trading-station brokers clamp to seller_cargo=0 at validation). -->
          <set_value name="$tmClampBuySeller" exact="null"/>
          <do_if value="$sellOffer?">
            <do_if value="$sellOffer.seller?">
              <set_value name="$tmClampBuySeller" exact="@$sellOffer.seller"/>
            </do_if>
            <do_if value="$tmClampBuySeller == null and $sellOffer.owner?">
              <set_value name="$tmClampBuySeller" exact="@$sellOffer.owner"/>
            </do_if>
          </do_if>
          <do_if value="$tmClampBuySeller != null">
            <set_value name="$tmClampPreview" exact="$tradeAmount"/>
            <set_value name="$tmClampReason" exact="null"/>
            <set_value name="$tmTradePartner" exact="if this.assignedcontrolled? then this.assignedcontrolled else $ship"/>
            <clamp_trade_amount trade="$sellOffer" amount="$tmClampPreview" buyer="$tmTradePartner" seller="$tmClampBuySeller" result="$tmClampPreview" reason="$tmClampReason"/>
            <do_if value="not $tmClampPreview? or $tmClampPreview le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
            <set_value name="$tradeAmount" exact="$tmClampPreview"/>
            <set_value name="$sellOfferAmount" exact="[$sellOfferAmount, $tradeAmount].min"/>
          </do_if>
          <do_else>
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_else>
          <set_value name="$tmClampSellBuyer" exact="null"/>
          <do_if value="$buyOffer?">
            <do_if value="$buyOffer.buyer?">
              <set_value name="$tmClampSellBuyer" exact="@$buyOffer.buyer"/>
            </do_if>
            <do_if value="$tmClampSellBuyer == null and $buyOffer.owner?">
              <set_value name="$tmClampSellBuyer" exact="@$buyOffer.owner"/>
            </do_if>
          </do_if>
          <do_if value="$tmClampSellBuyer != null">
            <set_value name="$tmSellClampPreview" exact="$tradeAmount"/>
            <set_value name="$tmSellClampReason" exact="null"/>
            <clamp_trade_amount trade="$buyOffer" amount="$tmSellClampPreview" buyer="$tmClampSellBuyer" result="$tmSellClampPreview" reason="$tmSellClampReason"/>
            <do_if value="not $tmSellClampPreview? or $tmSellClampPreview le 0">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
            <set_value name="$tradeAmount" exact="[$tradeAmount, $tmSellClampPreview].min"/>
            <set_value name="$buyOfferAmount" exact="[$buyOfferAmount, $tradeAmount].min"/>
          </do_if>
          <do_else>
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_else>
          <do_if value="$tradeAmount le 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <set_value name="$unitProfit" exact="$buyOffer.unitprice - $sellOffer.unitprice"/>
          <!-- Default sell-mode behavior requires positive unit profit.
               MK1 can opt in to allow zero-profit station-price sells.
               MK3 'Ignore Player Pricing' bypasses both gates for player-supplier trades
               (cost is virtual zero, so any non-negative sell price is income). -->
          <do_if value="$scoreMode == 'sell' and not $playerFreeSupplier and $unitProfit lt 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>
          <do_if value="$scoreMode == 'sell' and not $allowZeroProfitSell and not $playerFreeSupplier and $unitProfit == 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <continue/>
          </do_if>

          <!-- Optional route-illegal filter: contraband only â€” legal wares skip jump-path probe. -->
          <do_if value="$allowIllegal and $enforceRouteIllegalLegality and @$ware.illegal gt 0">
            <run_script name="'lib.gt.pathfinding'" result="$routeLegality">
              <param name="mode" value="'route_legality'"/>
              <param name="ship" value="$ship"/>
              <param name="homeSector" value="$homeSector"/>
              <param name="blacklistGroup" value="$blacklistGroup"/>
              <param name="allowIllegal" value="$allowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
              <param name="startSector" value="$ship.sector"/>
              <param name="buySector" value="$buyStation.sector"/>
              <param name="sellSector" value="$sellStation.sector"/>
              <param name="ware" value="$ware"/>
            </run_script>
            <do_if value="not $routeLegality.$IsLegal">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <set_value name="this.$tm_tradesRejectedRouteIllegal" operation="add"/>
              <continue/>
            </do_if>
          </do_if>
          <!-- Route-aware score distance: homeâ†’buy + buyâ†’sell (territorial gates above stay per-leg). -->
          <set_value name="$buySector" exact="$buyStation.sector"/>
          <set_value name="$sellSector" exact="$sellStation.sector"/>
          <set_value name="$routeLeg" exact="0"/>
          <do_if value="$buySector != $sellSector">
            <do_if value="$blacklistGroup? and $blacklistGroup != null and $ship?">
              <set_value name="$routeLeg" exact="$buySector.gatedistance.{$sellSector}.{$blacklistGroup}.{$ship}"/>
            </do_if>
            <do_else>
              <set_value name="$routeLeg" exact="$buySector.gatedistance.{$sellSector}"/>
            </do_else>
          </do_if>
          <do_if value="$routeLeg lt 0">
            <set_value name="this.$tm_tradesRejected" operation="add"/>
            <set_value name="this.$tm_tradesRejectedDistance" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$distance" exact="$distBuy + $routeLeg"/>

          <set_value name="$distanceFactor" exact="1.0 + ($distance * $distancePenalty)"/>
          <set_value name="$score" exact="0"/>
          <set_value name="$volumePerUnit" exact="if $ware? and $ware.volume? then $ware.volume else 1"/>

          <do_if value="$scoreMode == 'supply'">
            <!-- MK4 supply scoring: demand over distance (tradeAmount is post demand-gate min of
                 supplier cap and effective destination need). Unit price must not skew fleet supply. -->
            <set_value name="$score" exact="$tradeAmount / $distanceFactor"/>
            <!-- MK4 playerBuyMod (scoring-only): bias player-owned suppliers when both sources allowed. -->
            <do_if value="$mk4CustomerMustBePlayer and $mk4AllowPlayerSuppliers and $mk4AllowAiSuppliers and $mk4PlayerBuyModPct gt 0 and $buyStation? and $buyStation.isplayerowned">
              <set_value name="$mk4BuyModPctSafe" exact="[0, [99, $mk4PlayerBuyModPct].min].max"/>
              <do_if value="$mk4BuyModPctSafe gt 0">
                <set_value name="$score" exact="$score * 100 / (100 - $mk4BuyModPctSafe)"/>
              </do_if>
            </do_if>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and this.$tm_supplyScoreDiagCount lt 8">
              <debug_text text="'[GT-TradeMatch] ' + $ship.idcode + ': supply-score diag ware=' + $ware + ' tradeAmount=' + $tradeAmount + ' distFactor=' + $distanceFactor + ' expr=' + $tradeAmount + '/' + $distanceFactor" chance="100"/>
              <set_value name="this.$tm_supplyScoreDiagCount" operation="add"/>
            </do_if>
            <!-- Build-storage delivery priority tier:
                 Lift build-storage deliveries into a dedicated top tier (additive base larger than
                 any realistic non-build-storage supply score) so they sort to the front and survive
                 truncation across cache write, cache read, and MK4 selection. -->
            <do_if value="$sellStation? and $sellStation.isclass.buildstorage">
              <set_value name="$score" exact="$score + 1000000"/>
            </do_if>
            <!-- Player-station single-trip completion scoring (MK4 supply / auto-ware basket):
                 When remaining need fits in one ship load, score by target/deficit/distance
                 without priceFactor â€” expensive wares are not penalized for near-complete fills. -->
            <do_if value="$mk4CustomerMustBePlayer and $sellStation? and $sellStation.exists and $sellStation.isplayerowned and not $sellStation.isclass.buildstorage and $ware?">
              <set_value name="$mk4CompletionTarget" exact="$sellStation.cargo.{$ware}.target"/>
              <do_if value="$mk4CompletionTarget gt 0">
                <set_value name="$mk4CompletionCount" exact="$sellStation.cargo.{$ware}.count"/>
                <set_value name="$mk4CompletionDeficit" exact="[$mk4CompletionTarget - $mk4CompletionCount, 0].max"/>
                <set_value name="$mk4TripVolPerUnit" exact="if $volumePerUnit gt 0 then $volumePerUnit else 1"/>
                <set_value name="$mk4OneTripUnits" exact="($ship.cargo.free.all / $mk4TripVolPerUnit)i"/>
                <do_if value="$mk4CompletionDeficit gt 0 and $mk4OneTripUnits gt 0 and $mk4CompletionDeficit le $mk4OneTripUnits">
                  <set_value name="$score" exact="$mk4CompletionTarget / ($distanceFactor * $mk4CompletionDeficit)"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- MK3 'Ignore Player Pricing': for player suppliers, treat the supplier-side
                 cost as zero so the full sell price counts as gain. This affects both the
                 min-profit/ROI gate and the score basis. NPC suppliers use unmodified math. -->
            <do_if value="$playerFreeSupplier">
              <set_value name="$grossProfit" exact="$buyOffer.unitprice * $tradeAmount"/>
              <set_value name="$roi" exact="if $buyOffer.unitprice gt 0 then 100 else 0"/>
            </do_if>
            <do_else>
              <set_value name="$grossProfit" exact="$unitProfit * $tradeAmount"/>
              <set_value name="$roi" exact="if $sellOffer.unitprice gt 0 then ($unitProfit * 100) / $sellOffer.unitprice else 0"/>
            </do_else>
            <do_if value="not $playerFreeSupplier and ($grossProfit lt $minAbsoluteProfit or $roi lt $minROI)">
              <set_value name="this.$tm_tradesRejected" operation="add"/>
              <continue/>
            </do_if>
            <!-- Keep score numeric (credits) to avoid float*money conversion warnings in bonuses. -->
            <set_value name="$grossProfitCr" exact="($grossProfit / 1Cr)i"/>
            <set_value name="$score" exact="$grossProfitCr / $distanceFactor"/>

            <!-- Faction priority bonus: boost score for trades involving player-owned stations -->
            <do_if value="$factionPriority gt 0">
              <set_value name="$factionBonus" exact="1.0"/>
              <do_if value="$buyStation.isplayerowned or $sellStation.isplayerowned">
                <set_value name="$factionBonus" exact="1.0 + ($factionPriority * 0.1)"/>
              </do_if>
              <set_value name="$score" exact="$score * $factionBonus"/>
            </do_if>
          </do_else>

          <!-- MK3 'Ignore Player Pricing' profit reporting:
               When the supplier is player-owned and the override is enabled, the player's
               wallet net of the trade is the full sell income (the buy-leg credits flow
               within the player's own economy). Report Profit / UnitProfit accordingly so
               the queued-trade logbook entry shows the actual gain to the player rather
               than the negative ship-wallet delta. The $PlayerFreeSupplier tag lets the
               logging cue switch to a buy-price-suppressed message format. -->
          <set_value name="$reportedUnitProfit" exact="if $playerFreeSupplier then $buyOffer.unitprice else $unitProfit"/>
          <set_value name="$reportedProfit" exact="$reportedUnitProfit * $tradeAmount"/>

          <set_value name="$trade" exact="table[
            $Ware = $ware,
            $CargoWareTransport = if $ware? then @$ware.waretransport else null,
            $BuyOffer = $sellOffer,
            $SellOffer = $buyOffer,
            $Amount = $tradeAmount,
            $OfferMaxAmount = $tradeAmount,
            $BuyOfferAmount = $sellOfferAmount,
            $SellOfferAmount = $buyOfferAmount,
            $Score = $score,
            $BuyStation = $buyStation,
            $SellStation = $sellStation,
            $SellStationBase = if $sellStation? and $sellStation.isclass.buildstorage and $sellStation.base? then @$sellStation.base else null,
            $SupplierStationId = if $buyStation? and $buyStation.idcode? then @$buyStation.idcode else null,
            $BuySector = $buyStation.sector,
            $BuySectorId = if $buyStation.sector? and $buyStation.sector.idcode? then @$buyStation.sector.idcode else null,
            $SellSector = $sellStation.sector,
            $SellSectorId = if $sellStation.sector? and $sellStation.sector.idcode? then @$sellStation.sector.idcode else null,
            $Distance = $distance,
            $HomeToBuyDistance = $distBuy,
            $HomeToSellDistance = $distSell,
            $RouteDistance = $routeLeg,
            $UnitProfit = $reportedUnitProfit,
            $BuyPrice = $sellOffer.unitprice,
            $SellPrice = $buyOffer.unitprice,
            $ProfitPerUnit = $reportedUnitProfit,
            $VolumePerUnit = $volumePerUnit,
            $Profit = $reportedProfit,
            $PlayerFreeSupplier = $playerFreeSupplier
          ]"/>
          <append_to_list name="this.$tm_tradeList" exact="$trade"/>
          <set_value name="this.$tm_tradesEvaluated" operation="add"/>

          <!-- Track per-ware trade count -->
          <do_if value="$ware?">
            <do_if value="not this.$tm_tradesPerWare.{$ware}?">
              <set_value name="this.$tm_tradesPerWare.{$ware}" exact="0"/>
            </do_if>
            <set_value name="this.$tm_tradesPerWare.{$ware}" operation="add"/>
          </do_if>

          <do_if value="$score gt this.$tm_bestScore">
            <set_value name="this.$tm_bestScore" exact="$score"/>
            <set_value name="this.$tm_bestTrade" exact="$trade"/>
          </do_if>
        </do_all>

        <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after each sell-offer loop (blocking action index 1; match state on this.$tm_*)"/>
        <!-- Save/load only: rebuild offer scratch if library state was dropped mid-wait (never on normal yield). -->
        <do_if value="not this.$tm_matchSellOffers? or not this.$tm_matchBuyOffers?">
          <resume label="tm_ensure_state"/>
        </do_if>
      </do_all>

      <!-- Save/load may drop some this.$tm_* counters while the loop still completes; never fail the return table. -->
      <do_if value="not this.$tm_tradeList?">
        <create_list name="this.$tm_tradeList"/>
      </do_if>
      <do_if value="not this.$tm_bestTrade?">
        <set_value name="this.$tm_bestTrade" exact="null"/>
      </do_if>
      <do_if value="not this.$tm_bestScore?">
        <set_value name="this.$tm_bestScore" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesEvaluated?">
        <set_value name="this.$tm_tradesEvaluated" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejected?">
        <set_value name="this.$tm_tradesRejected" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedRouteIllegal?">
        <set_value name="this.$tm_tradesRejectedRouteIllegal" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4CustomerPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4CustomerPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4SupplierPolicy?">
        <set_value name="this.$tm_tradesRejectedMk4SupplierPolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4TypePolicy?">
        <set_value name="this.$tm_tradesRejectedMk4TypePolicy" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4DemandGate?">
        <set_value name="this.$tm_tradesRejectedMk4DemandGate" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4PriceCap?">
        <set_value name="this.$tm_tradesRejectedMk4PriceCap" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedMk4BuildStorageOnly?">
        <set_value name="this.$tm_tradesRejectedMk4BuildStorageOnly" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedDistance?">
        <set_value name="this.$tm_tradesRejectedDistance" exact="0"/>
      </do_if>
      <do_if value="not this.$tm_tradesRejectedSameStation?">
        <set_value name="this.$tm_tradesRejectedSameStation" exact="0"/>
      </do_if>
      <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before return (wake-loop guard)"/>
      <return value="table[
        $Found = (this.$tm_bestTrade != null),
        $BestTrade = this.$tm_bestTrade,
        $BestScore = this.$tm_bestScore,
        $TradeList = this.$tm_tradeList,
        $TradesEvaluated = this.$tm_tradesEvaluated,
        $TradesRejected = this.$tm_tradesRejected,
        $TradesRejectedRouteIllegal = this.$tm_tradesRejectedRouteIllegal,
        $TradesRejectedMk4CustomerPolicy = this.$tm_tradesRejectedMk4CustomerPolicy,
        $TradesRejectedMk4SupplierPolicy = this.$tm_tradesRejectedMk4SupplierPolicy,
        $TradesRejectedMk4TypePolicy = this.$tm_tradesRejectedMk4TypePolicy,
        $TradesRejectedMk4DemandGate = this.$tm_tradesRejectedMk4DemandGate,
        $TradesRejectedMk4PriceCap = this.$tm_tradesRejectedMk4PriceCap,
        $TradesRejectedMk4BuildStorageOnly = this.$tm_tradesRejectedMk4BuildStorageOnly,
        $TradesRejectedDistance = this.$tm_tradesRejectedDistance,
        $TradesRejectedSameStation = this.$tm_tradesRejectedSameStation
      ]"/>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8" ?>
<!--
  GalaxyTrader â€” Station Subordinate Order Access
  
  Patches vanilla lib.request.orders to protect GT orders from being overwritten
  by the station manager when a ship is assigned as a station subordinate.
  
  Without this patch: assigning a GT ship to a station causes the station manager
  to replace the GT order with vanilla TradeRoutine.
  
  With this patch: if the ship's default order ID is in global.$GT_ProtectedOrderIDs,
  the vanilla TradeRoutine/MiningRoutine creation is skipped entirely.
  
  Pattern based on mules_and_warehouses_extended, but uses a global list for extensibility.
  
  Requires: global.$GT_ProtectedOrderIDs (initialized in gt_core_system.xml)
-->
<diff>
  <!--
    INJECTION POINT 1: Detection
    
    Prepend a flag check at the top of the station-assignment do_elseif block
    (the block starting with: $commander.isclass.[class.station, class.buildstorage])
    
    If the ship already has a default order whose ID is in our protected list,
    set a flag variable so we can intercept the trade/mining assignment below.
    
    Vanilla structure at this point:
      do_else (commander exists)
        do_if (unit subordinate)
        do_elseif ($commander.isclass.[class.station, class.buildstorage])  <â€” WE PREPEND HERE
          do_if (positiondefence validity check)
          do_if (defence)
          do_elseif (positiondefence and valid)
          do_elseif (trade or mining)           <â€” WE INTERCEPT THIS
          ...
  -->
  <add sel="/aiscript[@name='lib.request.orders']/attention/actions/do_else/do_elseif" pos="prepend">
    <!-- GalaxyTrader: Detect if this ship has a protected GT order -->
    <do_if value="$object.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{($object.defaultorder).id}">
      <set_value name="$flag_gt_protected" exact="true"/>
      <debug_text text="'[GT] Ship %1 (%2) has protected GT order: %3 â€” will skip station manager override'.[$object.knownname, $object, $object.defaultorder.id]" chance="$debugchance"/>
    </do_if>
  </add>

  <!--
    INJECTION POINT 2: Protection
    
    Insert a do_elseif BEFORE the trade/mining assignment block.
    If our flag was set above, this catches the ship and does nothing â€”
    preventing vanilla from creating TradeRoutine or MiningRoutine.
    
    We target the first do_elseif inside the station-assignment block,
    which is the positiondefence check. We insert BEFORE it so our
    protection check comes right after the defence do_if.
    
    Vanilla structure:
      do_if (defence)
      [OUR do_elseif INSERTED HERE]
      do_elseif (positiondefence and valid)
      do_elseif (trade or mining)
      ...
  -->
  <add sel="/aiscript[@name='lib.request.orders']/attention/actions/do_else/do_elseif/do_elseif[1]" pos="before">
    <!-- GalaxyTrader: If this ship has a protected GT order, skip all station manager assignment logic -->
    <do_elseif value="$flag_gt_protected?">
      <debug_text text="'[GT] Ship %1 (%2) order %3 is protected â€” station manager override skipped'.[$object.knownname, $object, $object.defaultorder.id]" chance="$debugchance"/>
    </do_elseif>
  </add>
</diff>
<?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Sector-Change Rerouting for TradePerform orders -->
  
  <!-- Sector-Change Rerouting: Check destination reachability when entering new sector -->
  <!-- This handler runs DURING move.generic execution for all GT ships (trade, repair, supply, etc.) -->
  <!-- move.generic handles sector changes and prevents them from bubbling to parent scripts -->
  <!-- Add BEFORE SectorChangeHandler so our handler fires first -->
  <add sel="//aiscript[@name='move.generic']/interrupts/handler[@ref='SectorChangeHandler']" pos="before">
    <handler comment="GT Sector-Change Rerouting: Check destination reachability on sector change (for all GT ship activities)">
      <conditions>
        <check_any>
          <event_object_entered_gate object="this.ship"/>
          <event_object_entered_anomaly object="this.ship"/>
        </check_any>
      </conditions>
      <actions>
        <!-- Get new sector from event (needed for both rerouting and logging) -->
        <set_value name="$newSectorFromEvent" exact="null"/>
        <do_if value="event.param2?">
          <do_if value="event.param2.sector?">
            <set_value name="$newSectorFromEvent" exact="event.param2.sector"/>
          </do_if>
        </do_if>
        <set_value name="$newSector" exact="if $newSectorFromEvent then $newSectorFromEvent else this.ship.sector"/>
        
        <!-- Process for all GT ships (trade, repair, supply, etc.) -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
          <!-- Log sector change for GT ships -->
          <set_value name="$oldSector" exact="null"/>
          <do_if value="event.param?">
            <do_if value="event.param.sector?">
              <set_value name="$oldSector" exact="event.param.sector"/>
            </do_if>
          </do_if>
          <set_value name="$oldSectorName" exact="if $oldSector then @$oldSector.knownname else 'Unknown'"/>
          <set_value name="$newSectorName" exact="@$newSector.knownname"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-MoveGeneric] ' + this.ship.idcode + ': SECTOR CHANGE: ' + $oldSectorName + ' ' + $newSectorName" chance="100"/>
          </do_if>
          
          <!-- Check destination reachability for rerouting (applies to all GT ship activities) -->
          <!-- Only Level 12+ pilots have tactical awareness for mid-route analysis -->
          <!-- Only check blacklist-aware paths if threat avoidance and dynamic blacklist are enabled -->
          <do_if value="this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
            
            <do_if value="$pilotLevel ge 12">
              <!-- Get current destination from move.generic's $destination parameter -->
              <set_value name="$currentDestination" exact="$destination"/>
              
              <!-- Check if destination is valid and in different sector -->
              <do_if value="@$currentDestination.exists and @$currentDestination.sector != null and $newSector != null and $newSector != @$currentDestination.sector">
                <set_value name="$destinationSector" exact="@$currentDestination.sector"/>

                <!-- Prefer showing the destination's container (station/ship) in logbook messages.
                     move.generic callers often pass a dockingbay component as destination, whose knownname is unhelpful ("S Standard Docking Bay"). -->
                <set_value name="$destinationDisplay" exact="$currentDestination"/>
                <set_value name="$destinationContainer" exact="@$currentDestination.container"/>
                <do_if value="$destinationContainer != null">
                  <set_value name="$destinationDisplay" exact="$destinationContainer"/>
                </do_if>
                <set_value name="$destinationDisplayName" exact="@$destinationDisplay.knownname"/>
                
                <!-- Check if threat avoidance and dynamic blacklist are enabled -->
                <set_value name="$threatAvoidanceEnabled" exact="false"/>
                <set_value name="$useDynamicBlacklist" exact="false"/>
                <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ThreatAvoidance?">
                  <set_value name="$threatAvoidanceEnabled" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled"/>
                  <set_value name="$useDynamicBlacklist" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>
                </do_if>

                <!-- Determine ship blacklist group -->
                <set_value name="$blacklistgroup" exact="blacklistgroup.civilian"/>
                <do_if value="this.ship.isclass.[class.ship_m, class.ship_l, class.ship_xl]">
                  <set_value name="$blacklistgroup" exact="blacklistgroup.military"/>
                </do_if>

                <!-- Calculate normal distance (shortest path) -->
                <set_value name="$normalDistance" exact="this.ship.gatedistance.{$destinationSector}"/>

                <!-- Calculate blacklist-aware distance (avoiding threats) - only if threat avoidance is enabled -->
                <set_value name="$blacklistDistance" exact="-1"/>
                <do_if value="$threatAvoidanceEnabled and $useDynamicBlacklist">
                  <set_value name="$blacklistDistance" exact="this.ship.gatedistance.{$destinationSector}.{$blacklistgroup}.{this.ship}"/>
                </do_if>

                <!-- Epoch-based route cache + topology compare (catches equal-jump reroutes) -->
                <set_value name="$currentBlacklistEpoch" exact="if global.$GT_BlacklistEpoch? then global.$GT_BlacklistEpoch else 0"/>
                <set_value name="$epochChanged" exact="false"/>
                <set_value name="$haveCachedPath" exact="false"/>
                <set_value name="$routeChangedByEpoch" exact="false"/>
                <set_value name="$cachedRemainingSectors" exact="[]"/>
                <set_value name="$needsPathRebuild" exact="false"/>

                <do_if value="global.$GT_Ships.{this.ship}.$RoutePathCache?">
                  <set_value name="$routeCache" exact="global.$GT_Ships.{this.ship}.$RoutePathCache"/>
                  <do_if value="$routeCache.$DestinationSector? and $routeCache.$DestinationSector == $destinationSector and $routeCache.$BlacklistGroup? and $routeCache.$BlacklistGroup == $blacklistgroup and $routeCache.$RemainingSectors?">
                    <set_value name="$haveCachedPath" exact="true"/>
                    <set_value name="$cachedRemainingSectors" exact="$routeCache.$RemainingSectors"/>
                    <set_value name="$cachedEpoch" exact="if $routeCache.$BlacklistEpoch? then $routeCache.$BlacklistEpoch else 0"/>
                    <set_value name="$epochChanged" exact="$cachedEpoch != $currentBlacklistEpoch"/>

                    <!-- Exclude already passed sectors from cached path by trimming to current sector -->
                    <set_value name="$foundCurrentIndex" exact="0"/>
                    <do_all exact="$cachedRemainingSectors.count" counter="$idx">
                      <do_if value="$foundCurrentIndex == 0 and $cachedRemainingSectors.{$idx} == $newSector">
                        <set_value name="$foundCurrentIndex" exact="$idx"/>
                      </do_if>
                    </do_all>
                    <do_if value="$foundCurrentIndex gt 1">
                      <set_value name="$trimmedCachedSectors" exact="[]"/>
                      <do_all exact="$cachedRemainingSectors.count - $foundCurrentIndex + 1" counter="$trimIdx">
                        <set_value name="$sourceIdx" exact="$foundCurrentIndex + $trimIdx - 1"/>
                        <append_to_list name="$trimmedCachedSectors" exact="$cachedRemainingSectors.{$sourceIdx}"/>
                      </do_all>
                      <set_value name="$cachedRemainingSectors" exact="$trimmedCachedSectors"/>
                    </do_if>
                    <do_elseif value="$foundCurrentIndex == 0 and $cachedRemainingSectors.count gt 0">
                      <!-- Cached route no longer anchored at current sector -->
                      <set_value name="$haveCachedPath" exact="false"/>
                    </do_elseif>
                  </do_if>
                </do_if>

                <do_if value="not $haveCachedPath or $epochChanged">
                  <set_value name="$needsPathRebuild" exact="true"/>
                </do_if>

                <set_value name="$recalculatedRemainingSectors" exact="[]"/>
                <do_if value="$needsPathRebuild and $threatAvoidanceEnabled and $useDynamicBlacklist">
                  <set_value name="$jumppath" exact="[]"/>
                  <get_jump_path component="$jumppath" multiple="true" uselocalhighways="true" useblacklist="$blacklistgroup" refobject="this.assignedcontrolled" useknownpath="this.isplayerowned">
                    <start object="this.ship"/>
                    <end object="$destinationSector"/>
                  </get_jump_path>
                  <do_if value="$jumppath.count lt 2">
                    <get_jump_path component="$jumppath" multiple="true" uselocalhighways="false" useblacklist="$blacklistgroup" refobject="this.assignedcontrolled" useknownpath="this.isplayerowned">
                      <start object="this.ship"/>
                      <end object="$destinationSector"/>
                    </get_jump_path>
                  </do_if>

                  <set_value name="$lastRouteSector" exact="null"/>
                  <append_to_list name="$recalculatedRemainingSectors" exact="$newSector"/>
                  <set_value name="$lastRouteSector" exact="$newSector"/>
                  <do_all exact="$jumppath.count" counter="$jpidx">
                    <set_value name="$pathComponent" exact="$jumppath.{$jpidx}"/>
                    <do_if value="$pathComponent? and @$pathComponent.sector != null">
                      <set_value name="$pathSector" exact="@$pathComponent.sector"/>
                      <do_if value="$lastRouteSector == null or $pathSector != $lastRouteSector">
                        <append_to_list name="$recalculatedRemainingSectors" exact="$pathSector"/>
                        <set_value name="$lastRouteSector" exact="$pathSector"/>
                      </do_if>
                    </do_if>
                  </do_all>
                  <do_if value="$lastRouteSector != $destinationSector">
                    <append_to_list name="$recalculatedRemainingSectors" exact="$destinationSector"/>
                  </do_if>

                  <do_if value="$epochChanged and $haveCachedPath">
                    <!-- Compare route topology excluding current sector (index 1):
                         once we're already in the sector, rerouting based on that hop is too late. -->
                    <set_value name="$cachedCompareSectors" exact="[]"/>
                    <set_value name="$recalculatedCompareSectors" exact="[]"/>
                    <do_if value="$cachedRemainingSectors.count gt 1">
                      <do_all exact="$cachedRemainingSectors.count - 1" counter="$csi">
                        <append_to_list name="$cachedCompareSectors" exact="$cachedRemainingSectors.{$csi + 1}"/>
                      </do_all>
                    </do_if>
                    <do_if value="$recalculatedRemainingSectors.count gt 1">
                      <do_all exact="$recalculatedRemainingSectors.count - 1" counter="$nsi">
                        <append_to_list name="$recalculatedCompareSectors" exact="$recalculatedRemainingSectors.{$nsi + 1}"/>
                      </do_all>
                    </do_if>

                    <set_value name="$pathsMatch" exact="true"/>
                    <do_if value="$cachedCompareSectors.count != $recalculatedCompareSectors.count">
                      <set_value name="$pathsMatch" exact="false"/>
                    </do_if>
                    <do_else>
                      <do_all exact="$cachedCompareSectors.count" counter="$cmpidx">
                        <do_if value="$cachedCompareSectors.{$cmpidx} != $recalculatedCompareSectors.{$cmpidx}">
                          <set_value name="$pathsMatch" exact="false"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_else>
                    <do_if value="not $pathsMatch">
                      <set_value name="$routeChangedByEpoch" exact="true"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <set_value name="$cachedPathText" exact="''"/>
                        <set_value name="$newPathText" exact="''"/>
                        <set_value name="$cachedLimit" exact="[$cachedRemainingSectors.count, 20].min"/>
                        <set_value name="$newLimit" exact="[$recalculatedRemainingSectors.count, 20].min"/>

                        <do_all exact="$cachedLimit" counter="$cti">
                          <set_value name="$csec" exact="$cachedRemainingSectors.{$cti}"/>
                          <set_value name="$cname" exact="'Unknown'"/>
                          <do_if value="$csec? and @$csec.knownname != null">
                            <set_value name="$cname" exact="@$csec.knownname"/>
                          </do_if>
                          <do_if value="$cachedPathText == ''">
                            <set_value name="$cachedPathText" exact="$cname"/>
                          </do_if>
                          <do_else>
                            <set_value name="$cachedPathText" exact="$cachedPathText + ' -> ' + $cname"/>
                          </do_else>
                        </do_all>
                        <do_if value="$cachedRemainingSectors.count gt 20">
                          <set_value name="$cachedPathText" exact="$cachedPathText + ' -> ... (+' + ($cachedRemainingSectors.count - 20) + ')'"/>
                        </do_if>
                        <do_if value="$cachedPathText == ''">
                          <set_value name="$cachedPathText" exact="'(empty)'"/>
                        </do_if>

                        <do_all exact="$newLimit" counter="$nti">
                          <set_value name="$nsec" exact="$recalculatedRemainingSectors.{$nti}"/>
                          <set_value name="$nname" exact="'Unknown'"/>
                          <do_if value="$nsec? and @$nsec.knownname != null">
                            <set_value name="$nname" exact="@$nsec.knownname"/>
                          </do_if>
                          <do_if value="$newPathText == ''">
                            <set_value name="$newPathText" exact="$nname"/>
                          </do_if>
                          <do_else>
                            <set_value name="$newPathText" exact="$newPathText + ' -> ' + $nname"/>
                          </do_else>
                        </do_all>
                        <do_if value="$recalculatedRemainingSectors.count gt 20">
                          <set_value name="$newPathText" exact="$newPathText + ' -> ... (+' + ($recalculatedRemainingSectors.count - 20) + ')'"/>
                        </do_if>
                        <do_if value="$newPathText == ''">
                          <set_value name="$newPathText" exact="'(empty)'"/>
                        </do_if>

                        <debug_text text="'[GT-MoveGeneric] ' + this.ship.idcode + ': EPOCH ROUTE MISMATCH:' +
                          '\n  Epoch old/new: ' + $cachedEpoch + ' -> ' + $currentBlacklistEpoch +
                          '\n  Cached sectors (' + $cachedRemainingSectors.count + '): ' + $cachedPathText +
                          '\n  New sectors (' + $recalculatedRemainingSectors.count + '): ' + $newPathText" chance="100"/>
                      </do_if>
                    </do_if>
                  </do_if>

                  <set_value name="global.$GT_Ships.{this.ship}.$RoutePathCache" exact="table[
                    $DestinationSector = $destinationSector,
                    $BlacklistGroup = $blacklistgroup,
                    $BlacklistEpoch = $currentBlacklistEpoch,
                    $RemainingSectors = $recalculatedRemainingSectors
                  ]"/>
                </do_if>
                <do_elseif value="$haveCachedPath">
                  <set_value name="global.$GT_Ships.{this.ship}.$RoutePathCache.$RemainingSectors" exact="$cachedRemainingSectors"/>
                </do_elseif>

                <!-- Debug: log performed validation checks -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$blacklistGroupDisplay" exact="if $threatAvoidanceEnabled and $useDynamicBlacklist then $blacklistgroup else 'N/A (threat avoidance disabled)'"/>
                  <debug_text text="'[GT-MoveGeneric] ' + this.ship.idcode + ': SECTOR CHANGE CHECK: dest=' + $destinationDisplayName + ' (sector ' + @$destinationSector.knownname + '), normal=' + $normalDistance + ', blacklist=' + $blacklistDistance + ', group=' + $blacklistGroupDisplay + ', threatAvoidance=' + $threatAvoidanceEnabled + ', useBlacklist=' + $useDynamicBlacklist + ', epoch=' + $currentBlacklistEpoch + ', epochChanged=' + $epochChanged + ', routeChangedByEpoch=' + $routeChangedByEpoch" chance="100"/>
                </do_if>

                <!-- Unified reroute decision -->
                <set_value name="$shouldReroute" exact="false"/>
                <set_value name="$normalDistanceForLog" exact="$normalDistance"/>
                <set_value name="$blacklistDistanceText" exact="if $blacklistDistance lt 0 then 'UNREACHABLE' else $blacklistDistance + ' jumps'"/>
                <set_value name="$statusText" exact="'Path unchanged'"/>

                <!-- Case 1: Normal path doesn't exist -->
                <do_if value="$normalDistance lt 0">
                  <set_value name="$shouldReroute" exact="true"/>
                  <set_value name="$normalDistanceForLog" exact="-1"/>
                  <set_value name="$blacklistDistanceText" exact="'UNREACHABLE'"/>
                  <set_value name="$statusText" exact="'No path available'"/>
                </do_if>
                <!-- Case 2: blacklist-aware path blocked/longer -->
                <do_elseif value="$threatAvoidanceEnabled and $useDynamicBlacklist and ($blacklistDistance lt 0 or $blacklistDistance gt $normalDistance)">
                  <set_value name="$shouldReroute" exact="true"/>
                  <set_value name="$statusText" exact="if $blacklistDistance lt 0 then 'No safe path available' else 'Path requires detour'"/>
                </do_elseif>
                <!-- Case 3: epoch changed and route topology changed -->
                <do_elseif value="$routeChangedByEpoch">
                  <set_value name="$shouldReroute" exact="true"/>
                  <set_value name="$statusText" exact="'Route topology changed after blacklist update'"/>
                </do_elseif>

                <do_if value="$shouldReroute">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-MoveGeneric] ' + this.ship.idcode + ': SECTOR CHANGE REROUTE: Destination ' + @$currentDestination.knownname + ' changed (normal: ' + $normalDistance + ' jumps, blacklist-aware: ' + $blacklistDistance + ' jumps, epochRouteChanged: ' + $routeChangedByEpoch + ') - aborting movement'" chance="100"/>
                  </do_if>

                  <!-- Set reroute flag for ship name -->
                  <set_value name="global.$GT_Ships.{this.ship}.$Rerouting" exact="true"/>

                  <!-- Trigger ship rename to show [REROUTE] state -->
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>

                  <!-- Player logbook notification about route change -->
                  <set_value name="$logbookMessage" exact="{77000,3218}.[@$newSector.knownname, $destinationDisplayName, @$destinationSector.knownname, $normalDistanceForLog, $blacklistDistanceText, $statusText, this.ship.knownname]"/>
                  <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                    $Message = $logbookMessage,
                    $Category = 'alerts',
                    $Title = 'Route Path Changed: ' + this.ship.knownname,
                    $Object = this.ship,
                    $Interaction = 'showonmap',
                    $Highlighted = false
                  ]"/>

                  <!-- Signal dock failure to parent order (TradePerform, Repair, Supply, etc.) -->
                  <do_if value="not global.$GT_DockFailures?">
                    <set_value name="global.$GT_DockFailures" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_DockFailures.{this.ship}" exact="table[
                    $Reason = 'ROUTE_PATH_CHANGED',
                    $FailureText = {1045, 124},
                    $Destination = $destination,
                    $Timestamp = player.age
                  ]"/>

                  <!-- Abort move.generic - this will return control to parent order -->
                  <set_value name="$returnvalue" exact="false"/>
                  <abort_called_scripts resume="finish"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </handler>
  </add>
  
  <!-- Enemy Ship Departure Detection: Track when enemy ships leave blacklisted sectors -->
  <!-- This handler runs for ALL ships when they change sectors -->
  <!-- If a tracked enemy ship leaves a blacklisted sector, remove it from tracking -->
  <add sel="//aiscript[@name='move.generic']/interrupts/handler[@ref='SectorChangeHandler']" pos="before">
    <handler comment="GT Enemy Departure Detection: Remove tracked enemies when they leave sectors">
      <conditions>
        <check_any>
          <event_object_entered_gate object="this.ship"/>
          <event_object_entered_anomaly object="this.ship"/>
          <event_object_changed_sector object="this.ship"/>
        </check_any>
      </conditions>
      <actions>
        <!-- Get new sector from event -->
        <set_value name="$newSectorFromEvent" exact="null"/>
        <do_if value="event.param2?">
          <do_if value="event.param2.sector?">
            <set_value name="$newSectorFromEvent" exact="event.param2.sector"/>
          </do_if>
        </do_if>
        <set_value name="$newSector" exact="if $newSectorFromEvent then $newSectorFromEvent else this.ship.sector"/>
        
        <!-- Get old sector from event -->
        <set_value name="$oldSector" exact="null"/>
        <do_if value="event.param?">
          <do_if value="event.param.sector?">
            <set_value name="$oldSector" exact="event.param.sector"/>
          </do_if>
        </do_if>
        
        <!-- Check if threat intelligence system exists -->
        <do_if value="global.$GT_ThreatIntelligence?">
          <set_value name="$sectorsToCheck" exact="global.$GT_ThreatIntelligence.keys.list"/>
          
          <!-- Iterate through all tracked sectors -->
          <do_all exact="$sectorsToCheck.count" counter="$i">
            <set_value name="$trackedSector" exact="$sectorsToCheck.{$i}"/>
            <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$trackedSector}"/>
            
            <!-- Check if this sector has tracked ships -->
            <do_if value="$threatData.$TrackedEnemyShips? and $threatData.$TrackedEnemyShips.count gt 0">
              <set_value name="$trackedShips" exact="$threatData.$TrackedEnemyShips"/>
              <set_value name="$shipFound" exact="false"/>
              
              <!-- Find and remove this ship from tracking if it's in the list -->
              <do_all exact="$trackedShips.count" counter="$j" reverse="true">
                <set_value name="$trackedShip" exact="$trackedShips.{$j}"/>
                <do_if value="$trackedShip == this.ship">
                  <set_value name="$shipFound" exact="true"/>
                  
                  <!-- Get sector name for logbook (before removal) -->
                  <set_value name="$leftSectorName" exact="@$trackedSector.knownname"/>
                  <set_value name="$newSectorName" exact="@$newSector.knownname"/>
                  <set_value name="$shipName" exact="@this.ship.knownname"/>
                  
                  <!-- Remove ship from tracking list and MD destroy-watch group -->
                  <remove_from_list name="global.$GT_ThreatIntelligence.{$trackedSector}.$TrackedEnemyShips" exact="$trackedShip"/>
                  <do_if value="global.$GT_TrackedEnemyShipsGroup?">
                    <remove_from_group group="global.$GT_TrackedEnemyShipsGroup" object="$trackedShip"/>
                  </do_if>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Threat] Tracked enemy ship ' + $shipName + ' left sector ' + $leftSectorName + ' and moved to ' + $newSectorName" chance="100"/>
                  </do_if>
                  
                  <!-- Check if all ships gone from this sector -->
                  <set_value name="$remainingShips" exact="@global.$GT_ThreatIntelligence.{$trackedSector}.$TrackedEnemyShips"/>
                  <do_if value="$remainingShips == null">
                    <set_value name="$remainingShips" exact="[]"/>
                  </do_if>
                  <do_if value="$remainingShips.count == 0">
                    <!-- All tracked ships eliminated - signal MD cue to clear sector -->
                    <signal_objects object="player.galaxy" param="'GT_ClearSectorIfAllShipsGone'" param2="table[$Sector=$trackedSector]"/>
                  </do_if>
                  <do_else>
                    <!-- Ship left but others remain - send logbook message about lost track -->
                    <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$LogbookEntries? and global.$GT_GlobalSettings.$LogbookEntries">
                      <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
                      <set_value name="$logbookMessage" exact="{77000,3220}.[$leftSectorName, $newSectorName, $shipName]"/>
                      
                      <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                        $Message = $logbookMessage,
                        $Category = 'alerts',
                        $Title = 'Enemy Ship Escaped: ' + $leftSectorName,
                        $Object = $trackedSector,
                        $Interaction = 'showonmap',
                        $Highlighted = false
                      ]"/>
                    </do_if>
                  </do_else>
                  
                  <break/>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </handler>
  </add>

  <!-- Tracked enemy destruction: backup path when MD group destroy event is delayed -->
  <add sel="//aiscript[@name='move.generic']/interrupts/handler[@ref='SectorChangeHandler']" pos="before">
    <handler comment="GT Enemy Destruction Detection: Remove tracked enemies when destroyed">
      <conditions>
        <event_object_destroyed object="this.ship" check="false"/>
      </conditions>
      <actions>
        <do_if value="global.$GT_ThreatIntelligence?">
          <set_value name="$sectorsToCheck" exact="global.$GT_ThreatIntelligence.keys.list"/>
          <do_all exact="$sectorsToCheck.count" counter="$i">
            <set_value name="$trackedSector" exact="$sectorsToCheck.{$i}"/>
            <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$trackedSector}"/>
            <do_if value="$threatData.$TrackedEnemyShips? and $threatData.$TrackedEnemyShips.count gt 0">
              <set_value name="$trackedShips" exact="$threatData.$TrackedEnemyShips"/>
              <do_all exact="$trackedShips.count" counter="$j" reverse="true">
                <set_value name="$trackedShip" exact="$trackedShips.{$j}"/>
                <do_if value="$trackedShip == this.ship">
                  <remove_from_list name="global.$GT_ThreatIntelligence.{$trackedSector}.$TrackedEnemyShips" exact="$trackedShip"/>
                  <do_if value="global.$GT_TrackedEnemyShipsGroup?">
                    <remove_from_group group="global.$GT_TrackedEnemyShipsGroup" object="$trackedShip"/>
                  </do_if>
                  <signal_objects object="player.galaxy" param="'GT_ClearSectorIfAllShipsGone'" param2="table[$Sector=$trackedSector]"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </handler>
  </add>

  <!-- Player combat fleet arrival: re-evaluate whether sector should stay blacklisted -->
  <add sel="//aiscript[@name='move.generic']/interrupts/handler[@ref='SectorChangeHandler']" pos="before">
    <handler comment="GT ThreatAvoidance: re-evaluate sector when player combat ship arrives">
      <conditions>
        <check_any>
          <event_object_entered_gate object="this.ship"/>
          <event_object_entered_anomaly object="this.ship"/>
          <event_object_changed_sector object="this.ship"/>
        </check_any>
        <check_value value="this.ship.isplayerowned"/>
        <check_value value="this.ship.primarypurpose == purpose.fight"/>
      </conditions>
      <actions>
        <set_value name="$arrivalSector" exact="this.ship.sector"/>
        <do_if value="$arrivalSector? and global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.{$arrivalSector}?">
          <signal_objects object="player.galaxy" param="'GT_ReevaluateSectorThreat'" param2="table[$Sector=$arrivalSector]"/>
        </do_if>
      </actions>
    </handler>
  </add>

  <!-- ThreatAvoidance: Hostile gravidar contact detection (event-driven, vanilla-pattern) -->
  <!-- WHY HERE: move.generic runs for all movement; ships may not currently be running order.trade.galaxytrader when contacts appear.
       This provides the most reliable hook with minimal overhead by gating on min=1 contacts (no work when none). -->
  <add sel="//aiscript[@name='move.generic']/interrupts/handler[@ref='SectorChangeHandler']" pos="before">
    <handler comment="GT ThreatAvoidance: hostile gravidar contact detection (move.generic)">
      <conditions>
        <!-- Vanilla event: fires on gravidar scans -->
        <event_gravidar_has_scanned object="this.assignedcontrolled"/>
        <!-- Vanilla safety gates (avoid highways / critical order state) -->
        <check_value value="this.sector and not this.zone.isclass.highway"/>
        <check_value value="this.assignedcontrolled.order and this.assignedcontrolled.order.state != orderstate.critical"/>

        <!-- Only for GT ships and only if ThreatAvoidance + DynamicBlacklist are enabled -->
        <check_value value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?"/>
        <check_value value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ThreatAvoidance? and global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled"/>
        <check_value value="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>

        <!-- PERFORMANCE: Do not run actions unless at least 1 hostile ship contact exists (vanilla pattern: min=1 + maybeattackedby) -->
        <count_gravidar_contacts result="$_detectedHostiles" object="this.assignedcontrolled" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" maybeattackedby="this.assignedcontrolled" checkoperational="false" masstraffic="false" docked="false" multiple="true" min="1">
          <match_context macro="this.sector.macro"/>
          <match_context class="class.highway" negate="true"/>
          <match class="class.buildstorage" negate="true"/>
          <match state="componentstate.wreck" negate="true"/>
        </count_gravidar_contacts>
      </conditions>
      <actions>
        <!-- Get pilot skill level - only Level 6+ pilots can broadcast threat warnings to fleet -->
        <set_value name="$pilotLevel" exact="1"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        
        <!-- Per-ship throttle (global table; survives across move.generic instances) -->
        <do_if value="not global.$GT_ThreatDetectThrottle?">
          <set_value name="global.$GT_ThreatDetectThrottle" exact="table[]"/>
        </do_if>
        <set_value name="$_last" exact="@global.$GT_ThreatDetectThrottle.{this.ship}"/>
        <do_if value="$_last == null">
          <set_value name="$_last" exact="0s"/>
        </do_if>

        <!-- Always LOG when hostiles are detected, but avoid log spam by throttling to at most once per 10s per ship -->
        <set_value name="$_logAllowed" exact="player.age - $_last ge 10s"/>

        <set_value name="$hostiles" exact="$_detectedHostiles"/>
        <!-- IMPORTANT: $hostiles.count may include non-operational contacts (checkoperational="false").
             We want HostileCount to match the class breakdown we compute below, so we derive it from class counters. -->
        <set_value name="$hostileListCount" exact="$hostiles.count"/>
        <set_value name="$hostileCount" exact="0"/>

        <!-- Compute threat (stop early once we exceed common thresholds) -->
        <set_value name="$threatScore" exact="0"/>
        <set_value name="$shipClass_XL" exact="0"/>
        <set_value name="$shipClass_L" exact="0"/>
        <set_value name="$shipClass_M" exact="0"/>
        <set_value name="$shipClass_S" exact="0"/>
        <set_value name="$factionCounts" exact="table[]"/>

        <do_all exact="$hostileListCount" counter="$i">
          <set_value name="$h" exact="$hostiles.{$i}"/>
          <do_if value="@$h.exists and @$h.isoperational">
            <do_if value="$h.isclass.ship_xl">
              <set_value name="$threatScore" exact="$threatScore + 5"/>
              <set_value name="$shipClass_XL" operation="add"/>
            </do_if>
            <do_elseif value="$h.isclass.ship_l">
              <set_value name="$threatScore" exact="$threatScore + 3"/>
              <set_value name="$shipClass_L" operation="add"/>
            </do_elseif>
            <do_elseif value="$h.isclass.ship_m">
              <set_value name="$threatScore" exact="$threatScore + 2"/>
              <set_value name="$shipClass_M" operation="add"/>
            </do_elseif>
            <do_else>
              <set_value name="$threatScore" exact="$threatScore + 1"/>
              <set_value name="$shipClass_S" operation="add"/>
            </do_else>

            <do_if value="@$h.owner != null">
              <set_value name="$f" exact="$h.owner"/>
              <set_value name="$factionCounts.{$f}" exact="@$factionCounts.{$f} + 1"/>
            </do_if>
          </do_if>
        </do_all>

        <!-- Make HostileCount match class counters -->
        <set_value name="$hostileCount" exact="$shipClass_XL + $shipClass_L + $shipClass_M + $shipClass_S"/>

        <!-- Determine primary faction (best-effort; used for logging/telemetry) -->
        <set_value name="$primaryFaction" exact="null"/>
        <set_value name="$maxFactionCount" exact="0"/>
        <do_all exact="$factionCounts.keys.count" counter="$fi">
          <set_value name="$f" exact="$factionCounts.keys.{$fi}"/>
          <do_if value="$factionCounts.{$f} gt $maxFactionCount">
            <set_value name="$primaryFaction" exact="$f"/>
            <set_value name="$maxFactionCount" exact="$factionCounts.{$f}"/>
          </do_if>
        </do_all>

        <!-- Convert score to threat level (1-5), matching GT_ThreatIntelligence receiver expectations -->
        <set_value name="$threatLevel" exact="2"/>
        <do_if value="$shipClass_XL gt 0 or $shipClass_L gt 0">
          <set_value name="$threatLevel" exact="4"/>
        </do_if>
        <do_elseif value="$threatScore ge 6">
          <set_value name="$threatLevel" exact="3"/>
        </do_elseif>

        <!-- Compare to configured threshold (fallback 3) -->
        <set_value name="$threshold" exact="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold"/>
        <do_if value="not $threshold?">
          <set_value name="$threshold" exact="3"/>
        </do_if>

        <!-- Broadcast throttle (separate from logging throttle) -->
        <set_value name="$_broadcastAllowed" exact="player.age - $_last ge 30s"/>
        
        <!-- Only combat ships (purpose.fight) may broadcast blacklist-triggering warnings -->
        <do_if value="$pilotLevel ge 6 and this.ship.primarypurpose == purpose.fight">
          <do_if value="$hostileCount gt 0 and $_broadcastAllowed and $threatLevel ge $threshold">
            <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
              $Sector = this.sector,
              $DetectedBy = this.ship,
              $HostileCount = $hostileCount,
              $PrimaryFaction = $primaryFaction,
              $ShipClass_XL = $shipClass_XL,
              $ShipClass_L = $shipClass_L,
              $ShipClass_M = $shipClass_M,
              $ShipClass_S = $shipClass_S,
              $ThreatScore = $threatScore,
              $Timestamp = player.age
            ]"/>
          </do_if>
        </do_if>

        <do_if value="$hostileCount gt 0 and $_logAllowed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="global.$GT_ThreatDetectThrottle.{this.ship}" exact="player.age"/>
          <set_value name="$_primaryFactionName" exact="if $primaryFaction? then @$primaryFaction.knownname else 'UNKNOWN'"/>
          <set_value name="$_broadcasted" exact="if ($pilotLevel ge 6 and this.ship.primarypurpose == purpose.fight and $_broadcastAllowed and $threatLevel ge $threshold) then 'YES' else 'NO'"/>
          <set_value name="$_broadcastReason" exact="if this.ship.primarypurpose != purpose.fight then 'CIVILIAN SHIP (requires purpose.fight)' else if $pilotLevel lt 6 then 'PILOT LEVEL TOO LOW (Lv.' + $pilotLevel + ', requires Lv.6+)' else if not $_broadcastAllowed then 'THROTTLED' else if $threatLevel lt $threshold then 'THREAT BELOW THRESHOLD' else 'OK'"/>
          <debug_text text="'[GT-Threat-Detect] ' + this.ship.idcode + ' (Pilot Lv.' + $pilotLevel + ') in ' + this.sector.knownname
            + ' - hostiles=' + $hostileCount
            + ' (XL=' + $shipClass_XL + ', L=' + $shipClass_L + ', M=' + $shipClass_M + ', S=' + $shipClass_S + ')'
            + ', threatScore=' + $threatScore + ', threatLevel=' + $threatLevel + ', threshold=' + $threshold
            + ', primaryFaction=' + $_primaryFactionName
            + ', broadcasted=' + $_broadcasted + ' (' + $_broadcastReason + ')'" chance="100"/>
        </do_if>
      </actions>
    </handler>
  </add>

  <!-- Phase A: Pre-transit illegal-route guard before capital-ship gate crossing (R5).
       Inlined here (no run_script result=): X4 binds result= to the next run_script (move.gate). -->
  <add sel="//aiscript[@name='move.generic']/attention/actions/do_if/do_if[@value='$intersector? and not @this.zone.isclass.highway and (@$waitforsubordinates or $waitforatgate or this.assignedcontrolled.iscapitalship)']/set_value[@name='$nextsector']" pos="after">
    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and $nextsector?">
      <set_value name="$gtPrecheckShouldAbort" exact="false"/>
      <do_if value="global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
        <set_value name="$gtPrecheckPolicy" exact="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
        <do_if value="$gtPrecheckPolicy.$AllowIllegal? and $gtPrecheckPolicy.$AllowIllegal and $gtPrecheckPolicy.$EnforceRouteIllegalLegality? and $gtPrecheckPolicy.$EnforceRouteIllegalLegality">
          <set_value name="$gtPrecheckOwner" exact="this.ship.owner"/>
          <do_if value="$gtPrecheckOwner? and $nextsector.policefaction? and $nextsector.policefaction != $gtPrecheckOwner">
            <set_value name="$gtPrecheckCargo" exact="this.ship.cargo.list"/>
            <do_all exact="$gtPrecheckCargo.count" counter="$gtpci">
              <set_value name="$gtPrecheckWare" exact="$gtPrecheckCargo.{$gtpci}"/>
              <do_if value="$gtPrecheckWare? and @$gtPrecheckWare.illegal gt 0 and $gtPrecheckWare.illegalto.{$nextsector.policefaction}.{$gtPrecheckOwner}">
                <set_value name="global.$GT_Ships.{this.ship}.$RouteIllegalAbort" exact="table[
                  $Reason = 'route_illegal_pre_transit',
                  $NextSector = $nextsector,
                  $NextSectorName = if $nextsector? then @$nextsector.knownname else 'Unknown',
                  $Ware = $gtPrecheckWare,
                  $WareName = if $gtPrecheckWare? then @$gtPrecheckWare.name else 'Unknown',
                  $ActiveWare = if $gtPrecheckPolicy.$Ware? then $gtPrecheckPolicy.$Ware else null,
                  $ActiveWareName = if $gtPrecheckPolicy.$Ware? then @$gtPrecheckPolicy.$Ware.name else 'none',
                  $PoliceFaction = $nextsector.policefaction,
                  $PoliceFactionName = if $nextsector.policefaction? then @$nextsector.policefaction.knownname else 'Unknown',
                  $PoliceFactionId = if $nextsector.policefaction? and $nextsector.policefaction.id? then $nextsector.policefaction.id else 'none',
                  $Timestamp = player.age
                ]"/>
                <do_if value="$gtPrecheckPolicy.$Ware? and $gtPrecheckWare == $gtPrecheckPolicy.$Ware and $gtPrecheckPolicy.$HomeSector? and $gtPrecheckPolicy.$BuySector? and $gtPrecheckPolicy.$SellSector?">
                  <set_value name="$gtCacheOwner" exact="this.ship.owner"/>
                  <set_value name="$gtCacheBlacklist" exact="blacklistgroup.civilian"/>
                  <do_if value="this.ship.isclass.[class.ship_m, class.ship_l, class.ship_xl]">
                    <set_value name="$gtCacheBlacklist" exact="blacklistgroup.military"/>
                  </do_if>
                  <set_value name="$gtCacheStart" exact="if $gtPrecheckPolicy.$RouteStart? then $gtPrecheckPolicy.$RouteStart else this.ship.sector"/>
                  <do_if value="global.$GT_RouteLegalityCache? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}.{$gtCacheBlacklist}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}.{$gtCacheBlacklist}.{$gtCacheStart}?">
                    <set_value name="global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}.{$gtCacheBlacklist}.{$gtCacheStart}" exact="[]"/>
                  </do_if>
                </do_if>
                <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-RouteEnforce] BLOCK ' + this.ship.idcode + ': next=' + @$nextsector.knownname + ', ware=' + @$gtPrecheckWare.name + ', police=' + @$nextsector.policefaction.id" chance="100"/>
                </do_if>
                <set_value name="$gtPrecheckShouldAbort" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
      </do_if>
      <do_if value="$gtPrecheckShouldAbort">
        <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
        <signal_objects object="this.assignedcontrolled" param="'tradeperform_abort'"/>
        <signal_objects object="this.assignedcontrolled" param="'GT_Trade_Failed'" param2="table[
          $Reason = 'route_illegal_pre_transit',
          $ReasonType = 'ROUTE_ILLEGAL',
          $ShouldTryNext = false
        ]" delay="1ms"/>
        <set_value name="$returnvalue" exact="false"/>
        <resume label="cleanup"/>
      </do_if>
    </do_if>
  </add>

  <!-- Phase A: Pre-transit illegal-route guard before non-capital inter-sector move_to (R5). -->
  <add sel="//aiscript[@name='move.generic']/attention/actions/do_if/do_else/set_value[@name='$locblacklistgroup']" pos="after">
    <do_if value="$intersector? and global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
      <set_value name="$gtRouteNextSector" exact="$targetsector"/>
      <do_if value="$jumppath.{1}? and ($jumppath.{1}.isclass.gate or $jumppath.{1}.isclass.highwayentrygate) and $jumppath.{1}.destination? and $jumppath.{1}.destination.sector?">
        <set_value name="$gtRouteNextSector" exact="$jumppath.{1}.destination.sector"/>
      </do_if>
      <set_value name="$gtPrecheckShouldAbort" exact="false"/>
      <do_if value="global.$GT_Ships.{this.ship}.$ActiveTradePolicy? and $gtRouteNextSector?">
        <set_value name="$gtPrecheckPolicy" exact="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
        <do_if value="$gtPrecheckPolicy.$AllowIllegal? and $gtPrecheckPolicy.$AllowIllegal and $gtPrecheckPolicy.$EnforceRouteIllegalLegality? and $gtPrecheckPolicy.$EnforceRouteIllegalLegality">
          <set_value name="$gtPrecheckOwner" exact="this.ship.owner"/>
          <do_if value="$gtPrecheckOwner? and $gtRouteNextSector.policefaction? and $gtRouteNextSector.policefaction != $gtPrecheckOwner">
            <set_value name="$gtPrecheckCargo" exact="this.ship.cargo.list"/>
            <do_all exact="$gtPrecheckCargo.count" counter="$gtpci">
              <set_value name="$gtPrecheckWare" exact="$gtPrecheckCargo.{$gtpci}"/>
              <do_if value="$gtPrecheckWare? and @$gtPrecheckWare.illegal gt 0 and $gtPrecheckWare.illegalto.{$gtRouteNextSector.policefaction}.{$gtPrecheckOwner}">
                <set_value name="global.$GT_Ships.{this.ship}.$RouteIllegalAbort" exact="table[
                  $Reason = 'route_illegal_pre_transit',
                  $NextSector = $gtRouteNextSector,
                  $NextSectorName = if $gtRouteNextSector? then @$gtRouteNextSector.knownname else 'Unknown',
                  $Ware = $gtPrecheckWare,
                  $WareName = if $gtPrecheckWare? then @$gtPrecheckWare.name else 'Unknown',
                  $ActiveWare = if $gtPrecheckPolicy.$Ware? then $gtPrecheckPolicy.$Ware else null,
                  $ActiveWareName = if $gtPrecheckPolicy.$Ware? then @$gtPrecheckPolicy.$Ware.name else 'none',
                  $PoliceFaction = $gtRouteNextSector.policefaction,
                  $PoliceFactionName = if $gtRouteNextSector.policefaction? then @$gtRouteNextSector.policefaction.knownname else 'Unknown',
                  $PoliceFactionId = if $gtRouteNextSector.policefaction? and $gtRouteNextSector.policefaction.id? then $gtRouteNextSector.policefaction.id else 'none',
                  $Timestamp = player.age
                ]"/>
                <do_if value="$gtPrecheckPolicy.$Ware? and $gtPrecheckWare == $gtPrecheckPolicy.$Ware and $gtPrecheckPolicy.$HomeSector? and $gtPrecheckPolicy.$BuySector? and $gtPrecheckPolicy.$SellSector?">
                  <set_value name="$gtCacheOwner" exact="this.ship.owner"/>
                  <set_value name="$gtCacheBlacklist" exact="$locblacklistgroup"/>
                  <set_value name="$gtCacheStart" exact="if $gtPrecheckPolicy.$RouteStart? then $gtPrecheckPolicy.$RouteStart else this.ship.sector"/>
                  <do_if value="global.$GT_RouteLegalityCache? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}.{$gtCacheBlacklist}? and global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}.{$gtCacheBlacklist}.{$gtCacheStart}?">
                    <set_value name="global.$GT_RouteLegalityCache.{$gtPrecheckPolicy.$HomeSector}.{$gtPrecheckPolicy.$BuySector}.{$gtPrecheckPolicy.$SellSector}.{$gtPrecheckPolicy.$Ware}.{true}.{true}.{$gtCacheOwner}.{$gtCacheBlacklist}.{$gtCacheStart}" exact="[]"/>
                  </do_if>
                </do_if>
                <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-RouteEnforce] BLOCK ' + this.ship.idcode + ': next=' + @$gtRouteNextSector.knownname + ', ware=' + @$gtPrecheckWare.name + ', police=' + @$gtRouteNextSector.policefaction.id" chance="100"/>
                </do_if>
                <set_value name="$gtPrecheckShouldAbort" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
      </do_if>
      <do_if value="$gtPrecheckShouldAbort">
        <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
        <signal_objects object="this.assignedcontrolled" param="'tradeperform_abort'"/>
        <signal_objects object="this.assignedcontrolled" param="'GT_Trade_Failed'" param2="table[
          $Reason = 'route_illegal_pre_transit',
          $ReasonType = 'ROUTE_ILLEGAL',
          $ShouldTryNext = false
        ]" delay="1ms"/>
        <set_value name="$returnvalue" exact="false"/>
        <resume label="cleanup"/>
      </do_if>
    </do_if>
  </add>

  <!-- Guard vanilla endzone check: $endzone is only set as move_to output; probing undefined var errors. -->
  <replace sel="//aiscript[@name='move.generic']/attention/actions/do_if/do_else/do_if[@value='$endzone == null']">
    <do_if value="not $endzone? or $endzone == null">
      <debug_text text="'2: no path generated.\ndestination: %s %s %s\npositionspace: %s %s %s\nposition: %s'.[$destination.class, $destination.knownname, $destination, $positionspace.class, $positionspace.knownname, $positionspace, $position]" chance="$debugchance"/>
      <set_value name="$failedattempts" exact="@$failedattempts + 1"/>
      <do_if value="$failedattempts ge 3">
        <debug_text text="'aborting movement.'" chance="$debugchance"/>
        <resume label="cleanup"/>
      </do_if>
      <debug_text text="'plotting new position.'" chance="$debugchance"/>
      <set_value name="$position" exact="null"/>
      <resume label="move"/>
    </do_if>
  </replace>
  
</diff>
<?xml version='1.0' encoding='utf-8'?>
<diff>
  <!-- GalaxyTrader MK3: Support for GT order inheritance by subordinates -->
  <add sel="/aiscript/attention/actions/do_if[@value='$order.exists or (@$orderdef and $createdefaultorder?)']/do_if[@value='(@$orderdef and $createdefaultorder?) or not $order.requiredskill or (this.combinedskill ge $order.requiredskill)']">
    <do_elseif value="$orderdef.$id == 'GalaxyTraderMK3'">
      <set_value name="$added"/>
      <do_if value="$createdefaultorder?">
        <create_order id="$orderdef.$id" object="this.assignedcontrolled" default="true">
          <param name="home" value="$orderdef.$home"/>
          <param name="maxbuy" value="$orderdef.$maxbuy"/>
          <param name="maxsell" value="$orderdef.$maxsell"/>
          <param name="autowares" value="$orderdef.$autowares"/>
          <param name="warebasket" value="$orderdef.$warebasket"/>
          <param name="prioritywares" value="$orderdef.$prioritywares"/>
          <param name="priorityscoremultiplier" value="$orderdef.$priorityscoremultiplier"/>
          <param name="allowillegal" value="$orderdef.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="$orderdef.$enforceRouteIllegalLegality"/>
          <param name="distancepenalty" value="$orderdef.$distancepenalty"/>
          <param name="notifications" value="$orderdef.$notifications"/>
          <param name="cargotarget" value="$orderdef.$cargotarget"/>
          <param name="marketupdatefreq" value="$orderdef.$marketupdatefreq"/>
          <param name="debuglevel" value="$orderdef.$debuglevel"/>
          <param name="tradeeval" value="$orderdef.$tradeeval"/>
          <param name="idleParking" value="if $orderdef.$idleParking? then $orderdef.$idleParking else false"/>
        </create_order>
        <!-- SAFEST: Persist inherited GT params for PLAYER ships only (used to restore default order if promoted commander loses it) -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $Home = $orderdef.$home,
            $MaxBuy = $orderdef.$maxbuy,
            $MaxSell = $orderdef.$maxsell,
            $AutoWares = $orderdef.$autowares,
            $WareBasket = $orderdef.$warebasket,
            $PriorityWares = $orderdef.$prioritywares,
            $PriorityScoreMultiplier = $orderdef.$priorityscoremultiplier,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = $orderdef.$enforceRouteIllegalLegality,
            $DistancePenalty = $orderdef.$distancepenalty,
            $Notifications = $orderdef.$notifications,
            $CargoTarget = $orderdef.$cargotarget,
            $MarketUpdateFreq = $orderdef.$marketupdatefreq,
            $DebugLevel = $orderdef.$debuglevel,
            $TradeEval = $orderdef.$tradeeval,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false
          ]"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$orderdef.$home" exact="$order.$home"/>
        <set_value name="$orderdef.$maxbuy" exact="$order.$maxbuy"/>
        <set_value name="$orderdef.$maxsell" exact="$order.$maxsell"/>
        <set_value name="$orderdef.$autowares" exact="$order.$autowares"/>
        <set_value name="$orderdef.$warebasket" exact="$order.$warebasket"/>
        <set_value name="$orderdef.$prioritywares" exact="$order.$prioritywares"/>
        <set_value name="$orderdef.$priorityscoremultiplier" exact="$order.$priorityscoremultiplier"/>
        <set_value name="$orderdef.$allowillegal" exact="$order.$allowillegal"/>
        <set_value name="$orderdef.$enforceRouteIllegalLegality" exact="$order.$enforceRouteIllegalLegality"/>
        <set_value name="$orderdef.$distancepenalty" exact="$order.$distancepenalty"/>
        <set_value name="$orderdef.$notifications" exact="$order.$notifications"/>
        <set_value name="$orderdef.$cargotarget" exact="$order.$cargotarget"/>
        <set_value name="$orderdef.$marketupdatefreq" exact="$order.$marketupdatefreq"/>
        <set_value name="$orderdef.$debuglevel" exact="$order.$debuglevel"/>
        <set_value name="$orderdef.$tradeeval" exact="$order.$tradeeval"/>
        <set_value name="$orderdef.$idleParking" exact="if $order.$idleParking? then $order.$idleParking else false"/>
        <!-- CRITICAL: Ensure subordinate is registered in GT_Ships when inheriting GT order -->
        <!-- This ensures detection works even if AI script doesn't register the ship -->
        <!-- PERFORMANCE: Optimized to reduce property lookups when many ships register simultaneously -->
        <do_if value="global.$GT_Ships?">
          <!-- Table exists - quick check if ship already registered -->
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Registered subordinate in GT_Ships registry (inheriting GT order from commander)'" chance="10"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Table doesn't exist - initialize and register -->
          <set_value name="global.$GT_Ships" exact="table[]"/>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Registered subordinate in GT_Ships registry (inheriting GT order from commander)'" chance="10"/>
          </do_if>
        </do_else>

        <!-- SAFEST: Persist inherited GT params for PLAYER ships only (used to restore default order if promoted commander loses it) -->
        <do_if value="this.assignedcontrolled.isplayerowned and global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?">
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $Home = $order.$home,
            $MaxBuy = $order.$maxbuy,
            $MaxSell = $order.$maxsell,
            $AutoWares = $order.$autowares,
            $WareBasket = $order.$warebasket,
            $PriorityWares = $order.$prioritywares,
            $PriorityScoreMultiplier = $order.$priorityscoremultiplier,
            $AllowIllegal = $order.$allowillegal,
            $EnforceRouteIllegalLegality = $order.$enforceRouteIllegalLegality,
            $DistancePenalty = $order.$distancepenalty,
            $Notifications = $order.$notifications,
            $CargoTarget = $order.$cargotarget,
            $MarketUpdateFreq = $order.$marketupdatefreq,
            $DebugLevel = $order.$debuglevel,
            $TradeEval = $order.$tradeeval,
            $IdleParking = if $order.$idleParking? then $order.$idleParking else false
          ]"/>
        </do_if>
        
        <run_script name="$scriptname">
          <param name="home" value="$order.$home"/>
          <param name="maxbuy" value="$order.$maxbuy"/>
          <param name="maxsell" value="$order.$maxsell"/>
          <param name="autowares" value="$order.$autowares"/>
          <param name="warebasket" value="$order.$warebasket"/>
          <param name="prioritywares" value="$order.$prioritywares"/>
          <param name="priorityscoremultiplier" value="$order.$priorityscoremultiplier"/>
          <param name="allowillegal" value="$order.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="$order.$enforceRouteIllegalLegality"/>
          <param name="distancepenalty" value="$order.$distancepenalty"/>
          <param name="notifications" value="$order.$notifications"/>
          <param name="cargotarget" value="$order.$cargotarget"/>
          <param name="marketupdatefreq" value="$order.$marketupdatefreq"/>
          <param name="debuglevel" value="$order.$debuglevel"/>
          <param name="tradeeval" value="$order.$tradeeval"/>
          <param name="idleParking" value="if $order.$idleParking? then $order.$idleParking else false"/>
        </run_script>
      </do_else>
    </do_elseif>
    <do_elseif value="$orderdef.$id == 'GalaxyTraderMK4Supply'">
      <set_value name="$added"/>
      <do_if value="$createdefaultorder?">
        <create_order id="$orderdef.$id" object="this.assignedcontrolled" default="true">
          <param name="home" value="if $orderdef.$home? then $orderdef.$home else (if $orderdef.$homeStation? then $orderdef.$homeStation else (if $orderdef.$homeSector? then $orderdef.$homeSector else this.assignedcontrolled.sector))"/>
          <param name="assignHome" value="if $orderdef.$assignHome? then $orderdef.$assignHome else false"/>
          <param name="jumpDistanceCoverage" value="if $orderdef.$jumpDistanceCoverage? then $orderdef.$jumpDistanceCoverage else 1"/>
          <param name="jumpDistanceBuy" value="if $orderdef.$jumpDistanceBuy? then $orderdef.$jumpDistanceBuy else 1"/>
          <param name="serveHomeOnly" value="if $orderdef.$serveHomeOnly? then $orderdef.$serveHomeOnly else (if $orderdef.$dedicatedServe? then $orderdef.$dedicatedServe else false)"/>
          <param name="buyFromPlayer" value="if $orderdef.$buyFromPlayer? then $orderdef.$buyFromPlayer else (if $orderdef.$allowPlayerSuppliers? then $orderdef.$allowPlayerSuppliers else true)"/>
          <param name="buyFromFaction" value="if $orderdef.$buyFromFaction? then $orderdef.$buyFromFaction else (if $orderdef.$allowAiSuppliers? then $orderdef.$allowAiSuppliers else true)"/>
          <param name="allowBuildstorage" value="if $orderdef.$allowBuildstorage? then $orderdef.$allowBuildstorage else (if $orderdef.$buildStationsOnly? then $orderdef.$buildStationsOnly else true)"/>
          <param name="allowResources" value="if $orderdef.$allowResources? then $orderdef.$allowResources else true"/>
          <param name="allowIntermediates" value="if $orderdef.$allowIntermediates? then $orderdef.$allowIntermediates else (if $orderdef.$allowProducts? then $orderdef.$allowProducts else true)"/>
          <param name="allowTradewares" value="if $orderdef.$allowTradewares? then $orderdef.$allowTradewares else true"/>
          <param name="autowares" value="if $orderdef.$autowares? then $orderdef.$autowares else true"/>
          <param name="warebasket" value="if $orderdef.$warebasket? then $orderdef.$warebasket else []"/>
          <param name="ignoretraderules" value="if $orderdef.$ignoretraderules? then $orderdef.$ignoretraderules else (if $orderdef.$ignoreTradeRules? then $orderdef.$ignoreTradeRules else false)"/>
          <param name="notifications" value="if $orderdef.$notifications? then $orderdef.$notifications else 1"/>
          <param name="debuglevel" value="if $orderdef.$debuglevel? then $orderdef.$debuglevel else 1"/>
          <param name="idleParking" value="if $orderdef.$idleParking? then $orderdef.$idleParking else false"/>
        </create_order>
        <!-- Persist inherited MK4 params for promotion recovery parity with MK3. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply',
            $Home = if $orderdef.$home? then $orderdef.$home else (if $orderdef.$homeStation? then $orderdef.$homeStation else (if $orderdef.$homeSector? then $orderdef.$homeSector else this.assignedcontrolled.sector)),
            $AssignHome = if $orderdef.$assignHome? then $orderdef.$assignHome else false,
            $JumpDistanceCoverage = if $orderdef.$jumpDistanceCoverage? then $orderdef.$jumpDistanceCoverage else 1,
            $JumpDistanceBuy = if $orderdef.$jumpDistanceBuy? then $orderdef.$jumpDistanceBuy else 1,
            $DedicatedServe = if $orderdef.$serveHomeOnly? then $orderdef.$serveHomeOnly else (if $orderdef.$dedicatedServe? then $orderdef.$dedicatedServe else false),
            $AllowPlayerSuppliers = if $orderdef.$buyFromPlayer? then $orderdef.$buyFromPlayer else (if $orderdef.$allowPlayerSuppliers? then $orderdef.$allowPlayerSuppliers else true),
            $AllowAiSuppliers = if $orderdef.$buyFromFaction? then $orderdef.$buyFromFaction else (if $orderdef.$allowAiSuppliers? then $orderdef.$allowAiSuppliers else true),
            $AllowBuildstorage = if $orderdef.$allowBuildstorage? then $orderdef.$allowBuildstorage else (if $orderdef.$buildStationsOnly? then $orderdef.$buildStationsOnly else true),
            $AllowResources = if $orderdef.$allowResources? then $orderdef.$allowResources else true,
            $AllowIntermediates = if $orderdef.$allowIntermediates? then $orderdef.$allowIntermediates else (if $orderdef.$allowProducts? then $orderdef.$allowProducts else true),
            $AllowTradewares = if $orderdef.$allowTradewares? then $orderdef.$allowTradewares else true,
            $AutoWares = if $orderdef.$autowares? then $orderdef.$autowares else true,
            $WareBasket = if $orderdef.$warebasket? then $orderdef.$warebasket else [],
            $IgnoreTradeRules = if $orderdef.$ignoretraderules? then $orderdef.$ignoretraderules else (if $orderdef.$ignoreTradeRules? then $orderdef.$ignoreTradeRules else false),
            $Notifications = if $orderdef.$notifications? then $orderdef.$notifications else 1,
            $DebugLevel = if $orderdef.$debuglevel? then $orderdef.$debuglevel else 1,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false
          ]"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$orderdef.$home" exact="if $order.$home? then $order.$home else (if $order.$homeStation? then $order.$homeStation else (if $order.$homeSector? then $order.$homeSector else null))"/>
        <set_value name="$orderdef.$assignHome" exact="if $order.$assignHome? then $order.$assignHome else (if $order.$assignToStation? then $order.$assignToStation else false)"/>
        <set_value name="$orderdef.$jumpDistanceCoverage" exact="if $order.$jumpDistanceCoverage? then $order.$jumpDistanceCoverage else 1"/>
        <set_value name="$orderdef.$jumpDistanceBuy" exact="if $order.$jumpDistanceBuy? then $order.$jumpDistanceBuy else 1"/>
        <set_value name="$orderdef.$serveHomeOnly" exact="if $order.$serveHomeOnly? then $order.$serveHomeOnly else (if $order.$dedicatedServe? then $order.$dedicatedServe else false)"/>
        <set_value name="$orderdef.$buyFromPlayer" exact="if $order.$buyFromPlayer? then $order.$buyFromPlayer else (if $order.$allowPlayerSuppliers? then $order.$allowPlayerSuppliers else true)"/>
        <set_value name="$orderdef.$buyFromFaction" exact="if $order.$buyFromFaction? then $order.$buyFromFaction else (if $order.$allowAiSuppliers? then $order.$allowAiSuppliers else true)"/>
        <set_value name="$orderdef.$allowBuildstorage" exact="if $order.$allowBuildstorage? then $order.$allowBuildstorage else (if $order.$buildStationsOnly? then $order.$buildStationsOnly else true)"/>
        <set_value name="$orderdef.$allowResources" exact="if $order.$allowResources? then $order.$allowResources else true"/>
        <set_value name="$orderdef.$allowIntermediates" exact="if $order.$allowIntermediates? then $order.$allowIntermediates else (if $order.$allowProducts? then $order.$allowProducts else true)"/>
        <set_value name="$orderdef.$allowTradewares" exact="if $order.$allowTradewares? then $order.$allowTradewares else true"/>
        <set_value name="$orderdef.$autowares" exact="if $order.$autowares? then $order.$autowares else true"/>
        <set_value name="$orderdef.$warebasket" exact="if $order.$warebasket? then $order.$warebasket else []"/>
        <set_value name="$orderdef.$ignoretraderules" exact="if $order.$ignoretraderules? then $order.$ignoretraderules else (if $order.$ignoreTradeRules? then $order.$ignoreTradeRules else false)"/>
        <set_value name="$orderdef.$notifications" exact="if $order.$notifications? then $order.$notifications else 1"/>
        <set_value name="$orderdef.$debuglevel" exact="if $order.$debuglevel? then $order.$debuglevel else 1"/>
        <set_value name="$orderdef.$idleParking" exact="if $order.$idleParking? then $order.$idleParking else false"/>
        <!-- Persist inherited MK4 params for promotion recovery parity with MK3. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="global.$GT_Ships?">
            <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
              <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="global.$GT_Ships" exact="table[]"/>
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_else>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply',
            $Home = if $order.$home? then $order.$home else (if $order.$homeStation? then $order.$homeStation else (if $order.$homeSector? then $order.$homeSector else this.assignedcontrolled.sector)),
            $AssignHome = if $order.$assignHome? then $order.$assignHome else (if $order.$assignToStation? then $order.$assignToStation else false),
            $JumpDistanceCoverage = if $order.$jumpDistanceCoverage? then $order.$jumpDistanceCoverage else 1,
            $JumpDistanceBuy = if $order.$jumpDistanceBuy? then $order.$jumpDistanceBuy else 1,
            $DedicatedServe = if $order.$serveHomeOnly? then $order.$serveHomeOnly else (if $order.$dedicatedServe? then $order.$dedicatedServe else false),
            $AllowPlayerSuppliers = if $order.$buyFromPlayer? then $order.$buyFromPlayer else (if $order.$allowPlayerSuppliers? then $order.$allowPlayerSuppliers else true),
            $AllowAiSuppliers = if $order.$buyFromFaction? then $order.$buyFromFaction else (if $order.$allowAiSuppliers? then $order.$allowAiSuppliers else true),
            $AllowBuildstorage = if $order.$allowBuildstorage? then $order.$allowBuildstorage else (if $order.$buildStationsOnly? then $order.$buildStationsOnly else true),
            $AllowResources = if $order.$allowResources? then $order.$allowResources else true,
            $AllowIntermediates = if $order.$allowIntermediates? then $order.$allowIntermediates else (if $order.$allowProducts? then $order.$allowProducts else true),
            $AllowTradewares = if $order.$allowTradewares? then $order.$allowTradewares else true,
            $AutoWares = if $order.$autowares? then $order.$autowares else true,
            $WareBasket = if $order.$warebasket? then $order.$warebasket else [],
            $IgnoreTradeRules = if $order.$ignoretraderules? then $order.$ignoretraderules else (if $order.$ignoreTradeRules? then $order.$ignoreTradeRules else false),
            $Notifications = if $order.$notifications? then $order.$notifications else 1,
            $DebugLevel = if $order.$debuglevel? then $order.$debuglevel else 1,
            $IdleParking = if $order.$idleParking? then $order.$idleParking else false
          ]"/>
        </do_if>
        <run_script name="$scriptname">
          <param name="home" value="if $order.$home? then $order.$home else (if $order.$homeStation? then $order.$homeStation else (if $order.$homeSector? then $order.$homeSector else this.assignedcontrolled.sector))"/>
          <param name="assignHome" value="if $order.$assignHome? then $order.$assignHome else (if $order.$assignToStation? then $order.$assignToStation else false)"/>
          <param name="jumpDistanceCoverage" value="if $order.$jumpDistanceCoverage? then $order.$jumpDistanceCoverage else 1"/>
          <param name="jumpDistanceBuy" value="if $order.$jumpDistanceBuy? then $order.$jumpDistanceBuy else 1"/>
          <param name="serveHomeOnly" value="if $order.$serveHomeOnly? then $order.$serveHomeOnly else (if $order.$dedicatedServe? then $order.$dedicatedServe else false)"/>
          <param name="buyFromPlayer" value="if $order.$buyFromPlayer? then $order.$buyFromPlayer else (if $order.$allowPlayerSuppliers? then $order.$allowPlayerSuppliers else true)"/>
          <param name="buyFromFaction" value="if $order.$buyFromFaction? then $order.$buyFromFaction else (if $order.$allowAiSuppliers? then $order.$allowAiSuppliers else true)"/>
          <param name="allowBuildstorage" value="if $order.$allowBuildstorage? then $order.$allowBuildstorage else (if $order.$buildStationsOnly? then $order.$buildStationsOnly else true)"/>
          <param name="allowResources" value="if $order.$allowResources? then $order.$allowResources else true"/>
          <param name="allowIntermediates" value="if $order.$allowIntermediates? then $order.$allowIntermediates else (if $order.$allowProducts? then $order.$allowProducts else true)"/>
          <param name="allowTradewares" value="if $order.$allowTradewares? then $order.$allowTradewares else true"/>
          <param name="autowares" value="if $order.$autowares? then $order.$autowares else true"/>
          <param name="warebasket" value="if $order.$warebasket? then $order.$warebasket else []"/>
          <param name="ignoretraderules" value="if $order.$ignoretraderules? then $order.$ignoretraderules else (if $order.$ignoreTradeRules? then $order.$ignoreTradeRules else false)"/>
          <param name="notifications" value="if $order.$notifications? then $order.$notifications else 1"/>
          <param name="debuglevel" value="if $order.$debuglevel? then $order.$debuglevel else 1"/>
          <param name="idleParking" value="if $order.$idleParking? then $order.$idleParking else false"/>
        </run_script>
      </do_else>
    </do_elseif>
    <do_elseif value="$orderdef.$id == 'GalaxyTraderMK4Supply2'">
      <set_value name="$added"/>
      <do_if value="$createdefaultorder?">
        <create_order id="$orderdef.$id" object="this.assignedcontrolled" default="true">
          <param name="home" value="if $orderdef.$home? then $orderdef.$home else this.assignedcontrolled.sector"/>
          <param name="assignHome" value="if $orderdef.$assignHome? then $orderdef.$assignHome else false"/>
          <param name="jumpDistanceCoverage" value="if $orderdef.$jumpDistanceCoverage? then $orderdef.$jumpDistanceCoverage else 1"/>
          <param name="jumpDistanceBuy" value="if $orderdef.$jumpDistanceBuy? then $orderdef.$jumpDistanceBuy else 1"/>
          <param name="serveHomeOnly" value="if $orderdef.$serveHomeOnly? then $orderdef.$serveHomeOnly else false"/>
          <param name="buyFromPlayer" value="if $orderdef.$buyFromPlayer? then $orderdef.$buyFromPlayer else true"/>
          <param name="buyFromFaction" value="if $orderdef.$buyFromFaction? then $orderdef.$buyFromFaction else true"/>
          <param name="priorityBuildstorage" value="if $orderdef.$priorityBuildstorage? then $orderdef.$priorityBuildstorage else 10"/>
          <param name="priorityStations" value="if $orderdef.$priorityStations? then $orderdef.$priorityStations else 8"/>
          <param name="priorityAux" value="if $orderdef.$priorityAux? then $orderdef.$priorityAux else 0"/>
          <param name="priorityCarrier" value="if $orderdef.$priorityCarrier? then $orderdef.$priorityCarrier else 0"/>
          <param name="prioritywares" value="if $orderdef.$prioritywares? then $orderdef.$prioritywares else []"/>
          <param name="priorityscoremultiplier" value="if $orderdef.$priorityscoremultiplier? then $orderdef.$priorityscoremultiplier else 1"/>
          <param name="allowResources" value="if $orderdef.$allowResources? then $orderdef.$allowResources else true"/>
          <param name="allowIntermediates" value="if $orderdef.$allowIntermediates? then $orderdef.$allowIntermediates else true"/>
          <param name="allowTradewares" value="if $orderdef.$allowTradewares? then $orderdef.$allowTradewares else true"/>
          <param name="autowares" value="if $orderdef.$autowares? then $orderdef.$autowares else true"/>
          <param name="warebasket" value="if $orderdef.$warebasket? then $orderdef.$warebasket else []"/>
          <param name="ignoretraderules" value="if $orderdef.$ignoretraderules? then $orderdef.$ignoretraderules else false"/>
          <param name="debuglevel" value="if $orderdef.$debuglevel? then $orderdef.$debuglevel else 1"/>
          <param name="idleParking" value="if $orderdef.$idleParking? then $orderdef.$idleParking else false"/>
          <param name="logbookentries" value="if $orderdef.$logbookentries? then $orderdef.$logbookentries else true"/>
        </create_order>
        <!-- Persist inherited MK4-2 params for promotion recovery parity with MK3/MK4. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply2',
            $Home = if $orderdef.$home? then $orderdef.$home else (if $orderdef.$homeStation? then $orderdef.$homeStation else (if $orderdef.$homeSector? then $orderdef.$homeSector else this.assignedcontrolled.sector)),
            $AssignHome = if $orderdef.$assignHome? then $orderdef.$assignHome else false,
            $JumpDistanceCoverage = if $orderdef.$jumpDistanceCoverage? then $orderdef.$jumpDistanceCoverage else 1,
            $JumpDistanceBuy = if $orderdef.$jumpDistanceBuy? then $orderdef.$jumpDistanceBuy else 1,
            $DedicatedServe = if $orderdef.$serveHomeOnly? then $orderdef.$serveHomeOnly else (if $orderdef.$dedicatedServe? then $orderdef.$dedicatedServe else false),
            $AllowPlayerSuppliers = if $orderdef.$buyFromPlayer? then $orderdef.$buyFromPlayer else (if $orderdef.$allowPlayerSuppliers? then $orderdef.$allowPlayerSuppliers else true),
            $AllowAiSuppliers = if $orderdef.$buyFromFaction? then $orderdef.$buyFromFaction else (if $orderdef.$allowAiSuppliers? then $orderdef.$allowAiSuppliers else true),
            $PriorityBuildstorage = if $orderdef.$priorityBuildstorage? then $orderdef.$priorityBuildstorage else 10,
            $PriorityStations = if $orderdef.$priorityStations? then $orderdef.$priorityStations else 8,
            $PriorityAux = if $orderdef.$priorityAux? then $orderdef.$priorityAux else 0,
            $PriorityCarrier = if $orderdef.$priorityCarrier? then $orderdef.$priorityCarrier else 0,
            $PriorityWares = if $orderdef.$prioritywares? then $orderdef.$prioritywares else [],
            $PriorityScoreMultiplier = if $orderdef.$priorityscoremultiplier? then $orderdef.$priorityscoremultiplier else 1,
            $AllowResources = if $orderdef.$allowResources? then $orderdef.$allowResources else true,
            $AllowIntermediates = if $orderdef.$allowIntermediates? then $orderdef.$allowIntermediates else true,
            $AllowTradewares = if $orderdef.$allowTradewares? then $orderdef.$allowTradewares else true,
            $AutoWares = if $orderdef.$autowares? then $orderdef.$autowares else true,
            $WareBasket = if $orderdef.$warebasket? then $orderdef.$warebasket else [],
            $MaxTrades = if $orderdef.$maxTrades? then $orderdef.$maxTrades else 3,
            $BacktrackTolerance = if $orderdef.$backtrackTolerance? then $orderdef.$backtrackTolerance else 1,
            $UseMinCargoThreshold = if $orderdef.$useMinCargoThreshold? then $orderdef.$useMinCargoThreshold else false,
            $MinCargoUsed = if $orderdef.$minCargoUsed? then $orderdef.$minCargoUsed else 80,
            $PlayerBuyMod = if $orderdef.$playerBuyMod? then $orderdef.$playerBuyMod else 0,
            $AllowIllegal = if $orderdef.$allowillegal? then $orderdef.$allowillegal else false,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $IgnoreTradeRules = if $orderdef.$ignoretraderules? then $orderdef.$ignoretraderules else false,
            $IgnoreMK1Supply = if $orderdef.$ignoremk1supply? then $orderdef.$ignoremk1supply else true,
            $LogbookEntries = if $orderdef.$logbookentries? then $orderdef.$logbookentries else true,
            $DistancePenalty = if $orderdef.$distancepenalty? then $orderdef.$distancepenalty else 50,
            $FleetCoordination = if $orderdef.$fleetcoordination? then $orderdef.$fleetcoordination else true,
            $MarketUpdateFreq = if $orderdef.$marketupdatefreq? then $orderdef.$marketupdatefreq else 60s,
            $DebugLevel = if $orderdef.$debuglevel? then $orderdef.$debuglevel else 1,
            $TradeEval = if $orderdef.$tradeeval? then $orderdef.$tradeeval else false,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false,
            $SectorWhitelist = if $orderdef.$sectorwhitelist? then $orderdef.$sectorwhitelist else [],
            $AutoJumpDistanceByLevel = if $orderdef.$autoJumpDistanceByLevel? then $orderdef.$autoJumpDistanceByLevel else false
          ]"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$orderdef.$home" exact="if $order.$home? then $order.$home else (if $order.$homeStation? then $order.$homeStation else (if $order.$homeSector? then $order.$homeSector else null))"/>
        <set_value name="$orderdef.$assignHome" exact="if $order.$assignHome? then $order.$assignHome else (if $order.$assignToStation? then $order.$assignToStation else false)"/>
        <set_value name="$orderdef.$jumpDistanceCoverage" exact="if $order.$jumpDistanceCoverage? then $order.$jumpDistanceCoverage else 1"/>
        <set_value name="$orderdef.$jumpDistanceBuy" exact="if $order.$jumpDistanceBuy? then $order.$jumpDistanceBuy else 1"/>
        <set_value name="$orderdef.$serveHomeOnly" exact="if $order.$serveHomeOnly? then $order.$serveHomeOnly else (if $order.$dedicatedServe? then $order.$dedicatedServe else false)"/>
        <set_value name="$orderdef.$buyFromPlayer" exact="if $order.$buyFromPlayer? then $order.$buyFromPlayer else (if $order.$allowPlayerSuppliers? then $order.$allowPlayerSuppliers else true)"/>
        <set_value name="$orderdef.$buyFromFaction" exact="if $order.$buyFromFaction? then $order.$buyFromFaction else (if $order.$allowAiSuppliers? then $order.$allowAiSuppliers else true)"/>
        <set_value name="$orderdef.$priorityBuildstorage" exact="if $order.$priorityBuildstorage? then $order.$priorityBuildstorage else 10"/>
        <set_value name="$orderdef.$priorityStations" exact="if $order.$priorityStations? then $order.$priorityStations else 8"/>
        <set_value name="$orderdef.$priorityAux" exact="if $order.$priorityAux? then $order.$priorityAux else 0"/>
        <set_value name="$orderdef.$priorityCarrier" exact="if $order.$priorityCarrier? then $order.$priorityCarrier else 0"/>
        <set_value name="$orderdef.$prioritywares" exact="if $order.$prioritywares? then $order.$prioritywares else []"/>
        <set_value name="$orderdef.$priorityscoremultiplier" exact="if $order.$priorityscoremultiplier? then $order.$priorityscoremultiplier else 1"/>
        <set_value name="$orderdef.$allowResources" exact="if $order.$allowResources? then $order.$allowResources else true"/>
        <set_value name="$orderdef.$allowIntermediates" exact="if $order.$allowIntermediates? then $order.$allowIntermediates else true"/>
        <set_value name="$orderdef.$allowTradewares" exact="if $order.$allowTradewares? then $order.$allowTradewares else true"/>
        <set_value name="$orderdef.$autowares" exact="if $order.$autowares? then $order.$autowares else true"/>
        <set_value name="$orderdef.$warebasket" exact="if $order.$warebasket? then $order.$warebasket else []"/>
        <set_value name="$orderdef.$maxTrades" exact="if $order.$maxTrades? then $order.$maxTrades else 3"/>
        <set_value name="$orderdef.$backtrackTolerance" exact="if $order.$backtrackTolerance? then $order.$backtrackTolerance else 1"/>
        <set_value name="$orderdef.$useMinCargoThreshold" exact="if $order.$useMinCargoThreshold? then $order.$useMinCargoThreshold else false"/>
        <set_value name="$orderdef.$minCargoUsed" exact="if $order.$minCargoUsed? then $order.$minCargoUsed else 80"/>
        <set_value name="$orderdef.$playerBuyMod" exact="if $order.$playerBuyMod? then $order.$playerBuyMod else 0"/>
        <set_value name="$orderdef.$allowillegal" exact="if $order.$allowillegal? then $order.$allowillegal else false"/>
        <set_value name="$orderdef.$enforceRouteIllegalLegality" exact="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
        <set_value name="$orderdef.$ignoretraderules" exact="if $order.$ignoretraderules? then $order.$ignoretraderules else false"/>
        <set_value name="$orderdef.$ignoremk1supply" exact="if $order.$ignoremk1supply? then $order.$ignoremk1supply else true"/>
        <set_value name="$orderdef.$logbookentries" exact="if $order.$logbookentries? then $order.$logbookentries else true"/>
        <set_value name="$orderdef.$distancepenalty" exact="if $order.$distancepenalty? then $order.$distancepenalty else 50"/>
        <set_value name="$orderdef.$fleetcoordination" exact="if $order.$fleetcoordination? then $order.$fleetcoordination else true"/>
        <set_value name="$orderdef.$marketupdatefreq" exact="if $order.$marketupdatefreq? then $order.$marketupdatefreq else 60s"/>
        <set_value name="$orderdef.$debuglevel" exact="if $order.$debuglevel? then $order.$debuglevel else 1"/>
        <set_value name="$orderdef.$tradeeval" exact="if $order.$tradeeval? then $order.$tradeeval else false"/>
        <set_value name="$orderdef.$idleParking" exact="if $order.$idleParking? then $order.$idleParking else false"/>
        <set_value name="$orderdef.$sectorwhitelist" exact="if $order.$sectorwhitelist? then $order.$sectorwhitelist else []"/>
        <set_value name="$orderdef.$autoJumpDistanceByLevel" exact="if $order.$autoJumpDistanceByLevel? then $order.$autoJumpDistanceByLevel else false"/>
        <!-- Persist inherited MK4-2 params for promotion recovery parity with MK3/MK4. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="global.$GT_Ships?">
            <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
              <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="global.$GT_Ships" exact="table[]"/>
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_else>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply2',
            $Home = if $order.$home? then $order.$home else (if $order.$homeStation? then $order.$homeStation else (if $order.$homeSector? then $order.$homeSector else this.assignedcontrolled.sector)),
            $AssignHome = if $order.$assignHome? then $order.$assignHome else (if $order.$assignToStation? then $order.$assignToStation else false),
            $JumpDistanceCoverage = if $order.$jumpDistanceCoverage? then $order.$jumpDistanceCoverage else 1,
            $JumpDistanceBuy = if $order.$jumpDistanceBuy? then $order.$jumpDistanceBuy else 1,
            $DedicatedServe = if $order.$serveHomeOnly? then $order.$serveHomeOnly else (if $order.$dedicatedServe? then $order.$dedicatedServe else false),
            $AllowPlayerSuppliers = if $order.$buyFromPlayer? then $order.$buyFromPlayer else (if $order.$allowPlayerSuppliers? then $order.$allowPlayerSuppliers else true),
            $AllowAiSuppliers = if $order.$buyFromFaction? then $order.$buyFromFaction else (if $order.$allowAiSuppliers? then $order.$allowAiSuppliers else true),
            $PriorityBuildstorage = if $order.$priorityBuildstorage? then $order.$priorityBuildstorage else 10,
            $PriorityStations = if $order.$priorityStations? then $order.$priorityStations else 8,
            $PriorityAux = if $order.$priorityAux? then $order.$priorityAux else 0,
            $PriorityCarrier = if $order.$priorityCarrier? then $order.$priorityCarrier else 0,
            $PriorityWares = if $order.$prioritywares? then $order.$prioritywares else [],
            $PriorityScoreMultiplier = if $order.$priorityscoremultiplier? then $order.$priorityscoremultiplier else 1,
            $AllowResources = if $order.$allowResources? then $order.$allowResources else true,
            $AllowIntermediates = if $order.$allowIntermediates? then $order.$allowIntermediates else true,
            $AllowTradewares = if $order.$allowTradewares? then $order.$allowTradewares else true,
            $AutoWares = if $order.$autowares? then $order.$autowares else true,
            $WareBasket = if $order.$warebasket? then $order.$warebasket else [],
            $MaxTrades = if $order.$maxTrades? then $order.$maxTrades else 3,
            $BacktrackTolerance = if $order.$backtrackTolerance? then $order.$backtrackTolerance else 1,
            $UseMinCargoThreshold = if $order.$useMinCargoThreshold? then $order.$useMinCargoThreshold else false,
            $MinCargoUsed = if $order.$minCargoUsed? then $order.$minCargoUsed else 80,
            $PlayerBuyMod = if $order.$playerBuyMod? then $order.$playerBuyMod else 0,
            $AllowIllegal = if $order.$allowillegal? then $order.$allowillegal else false,
            $EnforceRouteIllegalLegality = if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false,
            $IgnoreTradeRules = if $order.$ignoretraderules? then $order.$ignoretraderules else false,
            $IgnoreMK1Supply = if $order.$ignoremk1supply? then $order.$ignoremk1supply else true,
            $LogbookEntries = if $order.$logbookentries? then $order.$logbookentries else true,
            $DistancePenalty = if $order.$distancepenalty? then $order.$distancepenalty else 50,
            $FleetCoordination = if $order.$fleetcoordination? then $order.$fleetcoordination else true,
            $MarketUpdateFreq = if $order.$marketupdatefreq? then $order.$marketupdatefreq else 60s,
            $DebugLevel = if $order.$debuglevel? then $order.$debuglevel else 1,
            $TradeEval = if $order.$tradeeval? then $order.$tradeeval else false,
            $IdleParking = if $order.$idleParking? then $order.$idleParking else false,
            $SectorWhitelist = if $order.$sectorwhitelist? then $order.$sectorwhitelist else [],
            $AutoJumpDistanceByLevel = if $order.$autoJumpDistanceByLevel? then $order.$autoJumpDistanceByLevel else false
          ]"/>
        </do_if>
        <run_script name="$scriptname">
          <param name="home" value="if $order.$home? then $order.$home else this.assignedcontrolled.sector"/>
          <param name="assignHome" value="if $order.$assignHome? then $order.$assignHome else false"/>
          <param name="jumpDistanceCoverage" value="if $order.$jumpDistanceCoverage? then $order.$jumpDistanceCoverage else 1"/>
          <param name="jumpDistanceBuy" value="if $order.$jumpDistanceBuy? then $order.$jumpDistanceBuy else 1"/>
          <param name="serveHomeOnly" value="if $order.$serveHomeOnly? then $order.$serveHomeOnly else false"/>
          <param name="buyFromPlayer" value="if $order.$buyFromPlayer? then $order.$buyFromPlayer else true"/>
          <param name="buyFromFaction" value="if $order.$buyFromFaction? then $order.$buyFromFaction else true"/>
          <param name="priorityBuildstorage" value="if $order.$priorityBuildstorage? then $order.$priorityBuildstorage else 10"/>
          <param name="priorityStations" value="if $order.$priorityStations? then $order.$priorityStations else 8"/>
          <param name="priorityAux" value="if $order.$priorityAux? then $order.$priorityAux else 0"/>
          <param name="priorityCarrier" value="if $order.$priorityCarrier? then $order.$priorityCarrier else 0"/>
          <param name="prioritywares" value="if $order.$prioritywares? then $order.$prioritywares else []"/>
          <param name="priorityscoremultiplier" value="if $order.$priorityscoremultiplier? then $order.$priorityscoremultiplier else 1"/>
          <param name="allowResources" value="if $order.$allowResources? then $order.$allowResources else true"/>
          <param name="allowIntermediates" value="if $order.$allowIntermediates? then $order.$allowIntermediates else true"/>
          <param name="allowTradewares" value="if $order.$allowTradewares? then $order.$allowTradewares else true"/>
          <param name="autowares" value="if $order.$autowares? then $order.$autowares else true"/>
          <param name="warebasket" value="if $order.$warebasket? then $order.$warebasket else []"/>
          <param name="ignoretraderules" value="if $order.$ignoretraderules? then $order.$ignoretraderules else false"/>
          <param name="debuglevel" value="if $order.$debuglevel? then $order.$debuglevel else 1"/>
          <param name="idleParking" value="if $order.$idleParking? then $order.$idleParking else false"/>
        </run_script>
      </do_else>
    </do_elseif>
    <do_elseif value="$orderdef.$id == 'GalaxyTraderMK1'">
      <set_value name="$added"/>
      <do_if value="$createdefaultorder?">
        <create_order id="$orderdef.$id" object="this.assignedcontrolled" default="true">
          <param name="homeStation" value="$orderdef.$homeStation"/>
          <param name="maxsell" value="$orderdef.$maxsell"/>
          <param name="ignoretraderules" value="$orderdef.$ignoretraderules"/>
          <param name="allowillegal" value="$orderdef.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false"/>
          <param name="warebasket" value="$orderdef.$warebasket"/>
          <param name="selltarget" value="$orderdef.$selltarget"/>
          <param name="sellselectionmode" value="if $orderdef.$sellselectionmode? then $orderdef.$sellselectionmode else 2"/>
          <param name="buytarget" value="$orderdef.$buytarget"/>
          <param name="backtrackTolerance" value="$orderdef.$backtrackTolerance"/>
          <param name="logbookentries" value="$orderdef.$logbookentries"/>
          <param name="notifications" value="$orderdef.$notifications"/>
          <param name="fleetcoordination" value="$orderdef.$fleetcoordination"/>
          <param name="debuglevel" value="$orderdef.$debuglevel"/>
          <param name="supply" value="$orderdef.$supply"/>
          <param name="minstorage" value="$orderdef.$minstorage"/>
          <param name="minsellstorage" value="if $orderdef.$minsellstorage? then $orderdef.$minsellstorage else 0"/>
          <param name="pricerange" value="if $orderdef.$pricerange? then $orderdef.$pricerange else 90"/>
          <param name="returnhome" value="if $orderdef.$returnhome? then $orderdef.$returnhome else false"/>
        </create_order>
        <!-- Persist inherited MK1 params for promotion recovery. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK1',
            $HomeStation = $orderdef.$homeStation,
            $MaxSell = $orderdef.$maxsell,
            $IgnoreTradeRules = $orderdef.$ignoretraderules,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $WareBasket = $orderdef.$warebasket,
            $SellTarget = $orderdef.$selltarget,
            $SellSelectionMode = if $orderdef.$sellselectionmode? then $orderdef.$sellselectionmode else 2,
            $BuyTarget = $orderdef.$buytarget,
            $BacktrackTolerance = $orderdef.$backtrackTolerance,
            $LogbookEntries = $orderdef.$logbookentries,
            $Notifications = $orderdef.$notifications,
            $FleetCoordination = $orderdef.$fleetcoordination,
            $DebugLevel = $orderdef.$debuglevel,
            $Supply = $orderdef.$supply,
            $MinStorage = $orderdef.$minstorage,
            $MinSellStorage = if $orderdef.$minsellstorage? then $orderdef.$minsellstorage else 0,
            $PriceRange = if $orderdef.$pricerange? then $orderdef.$pricerange else 90,
            $ReturnHome = if $orderdef.$returnhome? then $orderdef.$returnhome else false
          ]"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$orderdef.$homeStation" exact="$order.$homeStation"/>
        <set_value name="$orderdef.$maxsell" exact="$order.$maxsell"/>
        <set_value name="$orderdef.$ignoretraderules" exact="$order.$ignoretraderules"/>
        <set_value name="$orderdef.$allowillegal" exact="$order.$allowillegal"/>
        <set_value name="$orderdef.$enforceRouteIllegalLegality" exact="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
        <set_value name="$orderdef.$warebasket" exact="$order.$warebasket"/>
        <set_value name="$orderdef.$selltarget" exact="$order.$selltarget"/>
        <set_value name="$orderdef.$sellselectionmode" exact="if $order.$sellselectionmode? then $order.$sellselectionmode else 2"/>
        <set_value name="$orderdef.$buytarget" exact="$order.$buytarget"/>
        <set_value name="$orderdef.$backtrackTolerance" exact="$order.$backtrackTolerance"/>
        <set_value name="$orderdef.$logbookentries" exact="$order.$logbookentries"/>
        <set_value name="$orderdef.$notifications" exact="$order.$notifications"/>
        <set_value name="$orderdef.$fleetcoordination" exact="$order.$fleetcoordination"/>
        <set_value name="$orderdef.$debuglevel" exact="$order.$debuglevel"/>
        <set_value name="$orderdef.$supply" exact="$order.$supply"/>
        <set_value name="$orderdef.$minstorage" exact="$order.$minstorage"/>
        <set_value name="$orderdef.$minsellstorage" exact="if $order.$minsellstorage? then $order.$minsellstorage else 0"/>
        <set_value name="$orderdef.$pricerange" exact="if $order.$pricerange? then $order.$pricerange else 90"/>
        <set_value name="$orderdef.$returnhome" exact="if $order.$returnhome? then $order.$returnhome else false"/>
        <!-- Persist inherited MK1 params for promotion recovery. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="global.$GT_Ships?">
            <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
              <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="global.$GT_Ships" exact="table[]"/>
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_else>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK1',
            $HomeStation = $order.$homeStation,
            $MaxSell = $order.$maxsell,
            $IgnoreTradeRules = $order.$ignoretraderules,
            $AllowIllegal = $order.$allowillegal,
            $EnforceRouteIllegalLegality = if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false,
            $WareBasket = $order.$warebasket,
            $SellTarget = $order.$selltarget,
            $SellSelectionMode = if $order.$sellselectionmode? then $order.$sellselectionmode else 2,
            $BuyTarget = $order.$buytarget,
            $BacktrackTolerance = $order.$backtrackTolerance,
            $LogbookEntries = $order.$logbookentries,
            $Notifications = $order.$notifications,
            $FleetCoordination = $order.$fleetcoordination,
            $DebugLevel = $order.$debuglevel,
            $Supply = $order.$supply,
            $MinStorage = $order.$minstorage,
            $MinSellStorage = if $order.$minsellstorage? then $order.$minsellstorage else 0,
            $PriceRange = if $order.$pricerange? then $order.$pricerange else 90,
            $ReturnHome = if $order.$returnhome? then $order.$returnhome else false
          ]"/>
        </do_if>
        <run_script name="$scriptname">
          <param name="homeStation" value="$order.$homeStation"/>
          <param name="maxsell" value="$order.$maxsell"/>
          <param name="ignoretraderules" value="$order.$ignoretraderules"/>
          <param name="allowillegal" value="$order.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
          <param name="warebasket" value="$order.$warebasket"/>
          <param name="selltarget" value="$order.$selltarget"/>
          <param name="sellselectionmode" value="if $order.$sellselectionmode? then $order.$sellselectionmode else 2"/>
          <param name="buytarget" value="$order.$buytarget"/>
          <param name="backtrackTolerance" value="$order.$backtrackTolerance"/>
          <param name="logbookentries" value="$order.$logbookentries"/>
          <param name="notifications" value="$order.$notifications"/>
          <param name="fleetcoordination" value="$order.$fleetcoordination"/>
          <param name="debuglevel" value="$order.$debuglevel"/>
          <param name="supply" value="$order.$supply"/>
          <param name="minstorage" value="$order.$minstorage"/>
          <param name="minsellstorage" value="if $order.$minsellstorage? then $order.$minsellstorage else 0"/>
          <param name="returnhome" value="if $order.$returnhome? then $order.$returnhome else false"/>
        </run_script>
      </do_else>
    </do_elseif>
    <do_elseif value="$orderdef.$id == 'GalaxyTraderMK2'">
      <set_value name="$added"/>
      <do_if value="$createdefaultorder?">
        <create_order id="$orderdef.$id" object="this.assignedcontrolled" default="true">
          <param name="sourceStation" value="$orderdef.$sourceStation"/>
          <param name="sourceList" value="$orderdef.$sourceList"/>
          <param name="homeStation" value="null"/>
          <param name="homeSector" value="if $orderdef.$homeSector? then $orderdef.$homeSector else null"/>
          <param name="destList" value="$orderdef.$destList"/>
          <param name="minStorage" value="$orderdef.$minStorage"/>
          <param name="staticStorage" value="$orderdef.$staticStorage"/>
          <param name="maxStorage" value="$orderdef.$maxStorage"/>
          <param name="autowares" value="$orderdef.$autowares"/>
          <param name="warebasket" value="$orderdef.$warebasket"/>
          <param name="ignoretraderules" value="$orderdef.$ignoretraderules"/>
          <param name="ignoreoffersettings" value="if $orderdef.$ignoreoffersettings? then $orderdef.$ignoreoffersettings else false"/>
          <param name="allowillegal" value="$orderdef.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false"/>
          <param name="bidirectional" value="$orderdef.$bidirectional"/>
          <param name="maxDistance" value="$orderdef.$maxDistance"/>
          <param name="fleetcoordination" value="$orderdef.$fleetcoordination"/>
          <param name="notifications" value="$orderdef.$notifications"/>
          <param name="debuglevel" value="$orderdef.$debuglevel"/>
          <param name="idleParking" value="if $orderdef.$idleParking? then $orderdef.$idleParking else false"/>
        </create_order>
        <!-- Persist inherited MK2 params for promotion recovery. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK2',
            $SourceStation = $orderdef.$sourceStation,
            $SourceList = $orderdef.$sourceList,
            $HomeSector = if $orderdef.$homeSector? then $orderdef.$homeSector else null,
            $DestList = $orderdef.$destList,
            $MinStorage = $orderdef.$minStorage,
            $StaticStorage = $orderdef.$staticStorage,
            $MaxStorage = $orderdef.$maxStorage,
            $AutoWares = $orderdef.$autowares,
            $WareBasket = $orderdef.$warebasket,
            $IgnoreTradeRules = $orderdef.$ignoretraderules,
            $IgnoreOfferSettings = if $orderdef.$ignoreoffersettings? then $orderdef.$ignoreoffersettings else false,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $Bidirectional = $orderdef.$bidirectional,
            $MaxDistance = $orderdef.$maxDistance,
            $FleetCoordination = $orderdef.$fleetcoordination,
            $Notifications = $orderdef.$notifications,
            $DebugLevel = $orderdef.$debuglevel,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false
          ]"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$orderdef.$sourceStation" exact="$order.$sourceStation"/>
        <set_value name="$orderdef.$sourceList" exact="$order.$sourceList"/>
        <set_value name="$orderdef.$homeStation" exact="null"/>
        <set_value name="$orderdef.$homeSector" exact="if $order.$homeSector? then $order.$homeSector else null"/>
        <set_value name="$orderdef.$destList" exact="$order.$destList"/>
        <set_value name="$orderdef.$minStorage" exact="$order.$minStorage"/>
        <set_value name="$orderdef.$staticStorage" exact="$order.$staticStorage"/>
        <set_value name="$orderdef.$maxStorage" exact="$order.$maxStorage"/>
        <set_value name="$orderdef.$autowares" exact="$order.$autowares"/>
        <set_value name="$orderdef.$warebasket" exact="$order.$warebasket"/>
        <set_value name="$orderdef.$ignoretraderules" exact="$order.$ignoretraderules"/>
        <set_value name="$orderdef.$ignoreoffersettings" exact="if $order.$ignoreoffersettings? then $order.$ignoreoffersettings else false"/>
        <set_value name="$orderdef.$allowillegal" exact="$order.$allowillegal"/>
        <set_value name="$orderdef.$enforceRouteIllegalLegality" exact="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
        <set_value name="$orderdef.$bidirectional" exact="$order.$bidirectional"/>
        <set_value name="$orderdef.$maxDistance" exact="$order.$maxDistance"/>
        <set_value name="$orderdef.$fleetcoordination" exact="$order.$fleetcoordination"/>
        <set_value name="$orderdef.$notifications" exact="$order.$notifications"/>
        <set_value name="$orderdef.$debuglevel" exact="$order.$debuglevel"/>
        <set_value name="$orderdef.$idleParking" exact="if $order.$idleParking? then $order.$idleParking else false"/>
        <!-- Persist inherited MK2 params for promotion recovery. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="global.$GT_Ships?">
            <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
              <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="global.$GT_Ships" exact="table[]"/>
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_else>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyTraderMK2',
            $SourceStation = $order.$sourceStation,
            $SourceList = $order.$sourceList,
            $HomeSector = if $order.$homeSector? then $order.$homeSector else null,
            $DestList = $order.$destList,
            $MinStorage = $order.$minStorage,
            $StaticStorage = $order.$staticStorage,
            $MaxStorage = $order.$maxStorage,
            $AutoWares = $order.$autowares,
            $WareBasket = $order.$warebasket,
            $IgnoreTradeRules = $order.$ignoretraderules,
            $IgnoreOfferSettings = if $order.$ignoreoffersettings? then $order.$ignoreoffersettings else false,
            $AllowIllegal = $order.$allowillegal,
            $EnforceRouteIllegalLegality = if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false,
            $Bidirectional = $order.$bidirectional,
            $MaxDistance = $order.$maxDistance,
            $FleetCoordination = $order.$fleetcoordination,
            $Notifications = $order.$notifications,
            $DebugLevel = $order.$debuglevel,
            $IdleParking = if $order.$idleParking? then $order.$idleParking else false
          ]"/>
        </do_if>
        <run_script name="$scriptname">
          <param name="sourceStation" value="$order.$sourceStation"/>
          <param name="sourceList" value="$order.$sourceList"/>
          <param name="homeStation" value="null"/>
          <param name="homeSector" value="if $order.$homeSector? then $order.$homeSector else null"/>
          <param name="destList" value="$order.$destList"/>
          <param name="minStorage" value="$order.$minStorage"/>
          <param name="staticStorage" value="$order.$staticStorage"/>
          <param name="maxStorage" value="$order.$maxStorage"/>
          <param name="autowares" value="$order.$autowares"/>
          <param name="warebasket" value="$order.$warebasket"/>
          <param name="ignoretraderules" value="$order.$ignoretraderules"/>
          <param name="ignoreoffersettings" value="if $order.$ignoreoffersettings? then $order.$ignoreoffersettings else false"/>
          <param name="allowillegal" value="$order.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
          <param name="bidirectional" value="$order.$bidirectional"/>
          <param name="maxDistance" value="$order.$maxDistance"/>
          <param name="fleetcoordination" value="$order.$fleetcoordination"/>
          <param name="notifications" value="$order.$notifications"/>
          <param name="debuglevel" value="$order.$debuglevel"/>
          <param name="idleParking" value="if $order.$idleParking? then $order.$idleParking else false"/>
        </run_script>
      </do_else>
    </do_elseif>
    <do_elseif value="$orderdef.$id == 'GalaxyMiner'">
      <set_value name="$added"/>
      <do_if value="$createdefaultorder?">
        <create_order id="$orderdef.$id" object="this.assignedcontrolled" default="true">
          <param name="homeStation" value="$orderdef.$homeStation"/>
          <param name="homePosition" value="if $orderdef.$homePosition? then $orderdef.$homePosition else null"/>
          <param name="homeSector" value="$orderdef.$homeSector"/>
          <param name="resourceBasket" value="$orderdef.$resourceBasket"/>
          <param name="stationList" value="$orderdef.$stationList"/>
          <param name="overflowThreshold" value="$orderdef.$overflowThreshold"/>
          <param name="allowOverflowSellToOthers" value="$orderdef.$allowOverflowSellToOthers"/>
          <param name="assignToStation" value="$orderdef.$assignToStation"/>
          <param name="playerStationsOnly" value="$orderdef.$playerStationsOnly"/>
          <param name="checkDemandFirst" value="if $orderdef.$checkDemandFirst? then $orderdef.$checkDemandFirst else true"/>
          <param name="stayAtHome" value="$orderdef.$stayAtHome"/>
          <param name="idleParking" value="if $orderdef.$idleParking? then $orderdef.$idleParking else false"/>
          <param name="maxGatherDistance" value="$orderdef.$maxGatherDistance"/>
          <param name="maxSellDistance" value="$orderdef.$maxSellDistance"/>
          <param name="fleetBalancing" value="$orderdef.$fleetBalancing"/>
          <param name="demandRecheckInterval" value="$orderdef.$demandRecheckInterval"/>
          <param name="physicalStorageAbortPercent" value="if $orderdef.$physicalStorageAbortPercent? then $orderdef.$physicalStorageAbortPercent else 20"/>
          <param name="criticalDemandDelta" value="$orderdef.$criticalDemandDelta"/>
          <param name="minSwitchCooldown" value="$orderdef.$minSwitchCooldown"/>
          <param name="minCargoCommitPercent" value="$orderdef.$minCargoCommitPercent"/>
          <param name="hardEmergencyDelta" value="$orderdef.$hardEmergencyDelta"/>
          <param name="allowillegal" value="if $orderdef.$allowillegal? then $orderdef.$allowillegal else false"/>
          <param name="enforceRouteIllegalLegality" value="if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false"/>
          <param name="notifications" value="$orderdef.$notifications"/>
          <param name="debuglevel" value="$orderdef.$debuglevel"/>
        </create_order>
        <!-- Persist inherited Miner params for promotion recovery. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyMiner',
            $HomeStation = $orderdef.$homeStation,
            $HomePosition = if $orderdef.$homePosition? then $orderdef.$homePosition else null,
            $HomeSector = $orderdef.$homeSector,
            $ResourceBasket = $orderdef.$resourceBasket,
            $StationList = $orderdef.$stationList,
            $OverflowThreshold = $orderdef.$overflowThreshold,
            $AllowOverflowSellToOthers = $orderdef.$allowOverflowSellToOthers,
            $AssignToStation = $orderdef.$assignToStation,
            $PlayerStationsOnly = $orderdef.$playerStationsOnly,
            $CheckDemandFirst = if $orderdef.$checkDemandFirst? then $orderdef.$checkDemandFirst else true,
            $StayAtHome = $orderdef.$stayAtHome,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false,
            $MaxGatherDistance = $orderdef.$maxGatherDistance,
            $MaxSellDistance = $orderdef.$maxSellDistance,
            $FleetBalancing = $orderdef.$fleetBalancing,
            $DemandRecheckInterval = $orderdef.$demandRecheckInterval,
            $PhysicalStorageAbortPercent = if $orderdef.$physicalStorageAbortPercent? then $orderdef.$physicalStorageAbortPercent else 20,
            $CriticalDemandDelta = $orderdef.$criticalDemandDelta,
            $MinSwitchCooldown = $orderdef.$minSwitchCooldown,
            $MinCargoCommitPercent = $orderdef.$minCargoCommitPercent,
            $HardEmergencyDelta = $orderdef.$hardEmergencyDelta,
            $AllowIllegal = if $orderdef.$allowillegal? then $orderdef.$allowillegal else false,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $Notifications = $orderdef.$notifications,
            $DebugLevel = $orderdef.$debuglevel
          ]"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$orderdef.$homeStation" exact="$order.$homeStation"/>
        <set_value name="$orderdef.$homePosition" exact="if $order.$homePosition? then $order.$homePosition else null"/>
        <set_value name="$orderdef.$homeSector" exact="$order.$homeSector"/>
        <set_value name="$orderdef.$resourceBasket" exact="$order.$resourceBasket"/>
        <set_value name="$orderdef.$stationList" exact="$order.$stationList"/>
        <set_value name="$orderdef.$overflowThreshold" exact="$order.$overflowThreshold"/>
        <set_value name="$orderdef.$allowOverflowSellToOthers" exact="$order.$allowOverflowSellToOthers"/>
        <set_value name="$orderdef.$assignToStation" exact="$order.$assignToStation"/>
        <set_value name="$orderdef.$playerStationsOnly" exact="$order.$playerStationsOnly"/>
        <set_value name="$orderdef.$checkDemandFirst" exact="if $order.$checkDemandFirst? then $order.$checkDemandFirst else true"/>
        <set_value name="$orderdef.$stayAtHome" exact="$order.$stayAtHome"/>
        <set_value name="$orderdef.$idleParking" exact="if $order.$idleParking? then $order.$idleParking else false"/>
        <set_value name="$orderdef.$maxGatherDistance" exact="$order.$maxGatherDistance"/>
        <set_value name="$orderdef.$maxSellDistance" exact="$order.$maxSellDistance"/>
        <set_value name="$orderdef.$fleetBalancing" exact="$order.$fleetBalancing"/>
        <set_value name="$orderdef.$demandRecheckInterval" exact="$order.$demandRecheckInterval"/>
        <set_value name="$orderdef.$physicalStorageAbortPercent" exact="if $order.$physicalStorageAbortPercent? then $order.$physicalStorageAbortPercent else 20"/>
        <set_value name="$orderdef.$criticalDemandDelta" exact="$order.$criticalDemandDelta"/>
        <set_value name="$orderdef.$minSwitchCooldown" exact="$order.$minSwitchCooldown"/>
        <set_value name="$orderdef.$minCargoCommitPercent" exact="$order.$minCargoCommitPercent"/>
        <set_value name="$orderdef.$hardEmergencyDelta" exact="$order.$hardEmergencyDelta"/>
        <set_value name="$orderdef.$allowillegal" exact="if $order.$allowillegal? then $order.$allowillegal else false"/>
        <set_value name="$orderdef.$enforceRouteIllegalLegality" exact="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
        <set_value name="$orderdef.$notifications" exact="$order.$notifications"/>
        <set_value name="$orderdef.$debuglevel" exact="$order.$debuglevel"/>
        <!-- Persist inherited Miner params for promotion recovery. -->
        <do_if value="this.assignedcontrolled.isplayerowned">
          <do_if value="global.$GT_Ships?">
            <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
              <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="global.$GT_Ships" exact="table[]"/>
            <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
          </do_else>
          <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams" exact="table[
            $OrderId = 'GalaxyMiner',
            $HomeStation = $order.$homeStation,
            $HomePosition = if $order.$homePosition? then $order.$homePosition else null,
            $HomeSector = $order.$homeSector,
            $ResourceBasket = $order.$resourceBasket,
            $StationList = $order.$stationList,
            $OverflowThreshold = $order.$overflowThreshold,
            $AllowOverflowSellToOthers = $order.$allowOverflowSellToOthers,
            $AssignToStation = $order.$assignToStation,
            $PlayerStationsOnly = $order.$playerStationsOnly,
            $CheckDemandFirst = if $order.$checkDemandFirst? then $order.$checkDemandFirst else true,
            $StayAtHome = $order.$stayAtHome,
            $IdleParking = if $order.$idleParking? then $order.$idleParking else false,
            $MaxGatherDistance = $order.$maxGatherDistance,
            $MaxSellDistance = $order.$maxSellDistance,
            $FleetBalancing = $order.$fleetBalancing,
            $DemandRecheckInterval = $order.$demandRecheckInterval,
            $PhysicalStorageAbortPercent = if $order.$physicalStorageAbortPercent? then $order.$physicalStorageAbortPercent else 20,
            $CriticalDemandDelta = $order.$criticalDemandDelta,
            $MinSwitchCooldown = $order.$minSwitchCooldown,
            $MinCargoCommitPercent = $order.$minCargoCommitPercent,
            $HardEmergencyDelta = $order.$hardEmergencyDelta,
            $AllowIllegal = if $order.$allowillegal? then $order.$allowillegal else false,
            $EnforceRouteIllegalLegality = if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false,
            $Notifications = $order.$notifications,
            $DebugLevel = $order.$debuglevel
          ]"/>
        </do_if>
        <run_script name="$scriptname">
          <param name="homeStation" value="$order.$homeStation"/>
          <param name="homePosition" value="if $order.$homePosition? then $order.$homePosition else null"/>
          <param name="homeSector" value="$order.$homeSector"/>
          <param name="resourceBasket" value="$order.$resourceBasket"/>
          <param name="stationList" value="$order.$stationList"/>
          <param name="overflowThreshold" value="$order.$overflowThreshold"/>
          <param name="allowOverflowSellToOthers" value="$order.$allowOverflowSellToOthers"/>
          <param name="assignToStation" value="$order.$assignToStation"/>
          <param name="playerStationsOnly" value="$order.$playerStationsOnly"/>
          <param name="checkDemandFirst" value="if $order.$checkDemandFirst? then $order.$checkDemandFirst else true"/>
          <param name="stayAtHome" value="$order.$stayAtHome"/>
          <param name="idleParking" value="if $order.$idleParking? then $order.$idleParking else false"/>
          <param name="maxGatherDistance" value="$order.$maxGatherDistance"/>
          <param name="maxSellDistance" value="$order.$maxSellDistance"/>
          <param name="fleetBalancing" value="$order.$fleetBalancing"/>
          <param name="demandRecheckInterval" value="$order.$demandRecheckInterval"/>
          <param name="physicalStorageAbortPercent" value="if $order.$physicalStorageAbortPercent? then $order.$physicalStorageAbortPercent else 20"/>
          <param name="criticalDemandDelta" value="$order.$criticalDemandDelta"/>
          <param name="minSwitchCooldown" value="$order.$minSwitchCooldown"/>
          <param name="minCargoCommitPercent" value="$order.$minCargoCommitPercent"/>
          <param name="hardEmergencyDelta" value="$order.$hardEmergencyDelta"/>
          <param name="allowillegal" value="if $order.$allowillegal? then $order.$allowillegal else false"/>
          <param name="enforceRouteIllegalLegality" value="if $order.$enforceRouteIllegalLegality? then $order.$enforceRouteIllegalLegality else false"/>
          <param name="notifications" value="$order.$notifications"/>
          <param name="debuglevel" value="$order.$debuglevel"/>
        </run_script>
      </do_else>
    </do_elseif>
  </add>

  <!-- SAFEST: If a GT-managed PLAYER ship is promoted to commander but loses its default order,
       restore it from cached inherited params so subordinates can inherit again. -->
  <add sel="//aiscript[@name='order.assist']/attention/actions/do_if[@value='not $added?']/debug_text[@filter='error' and contains(@text, 'default order not inherited from commander.')]" pos="before">
    <!-- IMPORTANT: Do NOT rely on a local $commander variable existing in this scope.
         Always derive the commander from the subordinate ship (this matches the vanilla error case). -->
    <!-- DEBUG: Log that we're attempting to fix the promotion window issue -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-Assist] PROMOTION FIX: Attempting to restore default order for promoted commander (subordinate: ' + this.assignedcontrolled.idcode + ')'" chance="100"/>
    </do_if>
    <set_value name="$gtCommander" exact="@this.assignedcontrolled.commander"/>
    <do_if value="$gtCommander? and $gtCommander.exists and $gtCommander.isplayerowned">
      <!-- DEBUG: Log commander details -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$defaultOrderExists" exact="false"/>
        <set_value name="$defaultOrderId" exact="'null'"/>
        <do_if value="$gtCommander.defaultorder?">
          <set_value name="$defaultOrderExists" exact="true"/>
          <do_if value="@$gtCommander.defaultorder != null">
            <set_value name="$defaultOrderId" exact="@$gtCommander.defaultorder.id"/>
          </do_if>
        </do_if>
        <debug_text text="'[GT-Assist] PROMOTION FIX: Commander found: ' + $gtCommander.idcode + ', defaultorder exists: ' + (if $defaultOrderExists then 'yes' else 'no') + ', defaultorder value: ' + $defaultOrderId" chance="100"/>
      </do_if>
      <!-- Commander has no actionable default order (promotion window) -->
      <!-- CRITICAL FIX: Treat Assist as non-actionable for promoted GT commander in this error path -->
      <set_value name="$commanderNeedsRestore" exact="true"/>
      <do_if value="$gtCommander.defaultorder?">
        <do_if value="@$gtCommander.defaultorder != null">
          <set_value name="$commanderNeedsRestore" exact="false"/>
          <do_if value="@$gtCommander.defaultorder.id == 'Assist'">
            <set_value name="$commanderNeedsRestore" exact="true"/>
          </do_if>
        </do_if>
      </do_if>
      <do_if value="$commanderNeedsRestore">
        <!-- Never restore GT on non-GT inherit failures (e.g. TaterTrader): orderdef is authoritative. -->
        <set_value name="$promotionFixBlocked" exact="false"/>
        <do_if value="@$orderdef.$id and global.$GT_ProtectedOrderIDs? and not global.$GT_ProtectedOrderIDs.indexof.{@$orderdef.$id}">
          <set_value name="$promotionFixBlocked" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] PROMOTION FIX: Skipping restore - inherit target is non-GT order (' + @$orderdef.$id + ') on ' + this.assignedcontrolled.idcode" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="not $promotionFixBlocked">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist] PROMOTION FIX: Commander default order is non-actionable during promotion (' + (if @$gtCommander.defaultorder.id then @$gtCommander.defaultorder.id else 'null') + ') - restoring GT default order'" chance="100"/>
        </do_if>
        <!-- Restore from cached GT params when live GT context is provable.
             Fallback chain (cache/AI paths gated by $promotionFixAllowCacheFallbacks):
             1. Promoted commander's own cached params (it was a subordinate moments ago)
             2. THIS subordinate's cached params
             3. ANY other subordinate's cached params (they all inherited from destroyed commander)
             4. GT_AIParameters for commander (if available) -->
        <remove_value name="$gtParams"/>
        <set_value name="$paramsSource" exact="'none'"/>
        <remove_value name="$restoreOrderId"/>

        <!-- Source 0a (authoritative): inherited Assist orderdef in current script context -->
        <do_if value="not $gtParams? and @$orderdef.$id == 'GalaxyTraderMK3'">
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK3',
            $Home = if $orderdef.$home? then $orderdef.$home else (if this.assignedcontrolled.sector? then this.assignedcontrolled.sector else $gtCommander.sector),
            $MaxBuy = $orderdef.$maxbuy,
            $MaxSell = $orderdef.$maxsell,
            $AutoWares = $orderdef.$autowares,
            $WareBasket = $orderdef.$warebasket,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = $orderdef.$enforceRouteIllegalLegality,
            $DistancePenalty = $orderdef.$distancepenalty,
            $Notifications = $orderdef.$notifications,
            $CargoTarget = $orderdef.$cargotarget,
            $MarketUpdateFreq = $orderdef.$marketupdatefreq,
            $DebugLevel = $orderdef.$debuglevel,
            $TradeEval = $orderdef.$tradeeval,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK3'"/>
          <set_value name="$paramsSource" exact="'assist_orderdef'"/>
        </do_if>
        <do_elseif value="not $gtParams? and @$orderdef.$id == 'GalaxyTraderMK4Supply'">
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply',
            $Home = if $orderdef.$home? then $orderdef.$home else (if $orderdef.$homeStation? then $orderdef.$homeStation else (if $orderdef.$homeSector? then $orderdef.$homeSector else (if this.assignedcontrolled.sector? then this.assignedcontrolled.sector else $gtCommander.sector))),
            $AssignHome = $orderdef.$assignHome,
            $JumpDistanceCoverage = $orderdef.$jumpDistanceCoverage,
            $JumpDistanceBuy = $orderdef.$jumpDistanceBuy,
            $DedicatedServe = if $orderdef.$serveHomeOnly? then $orderdef.$serveHomeOnly else $orderdef.$dedicatedServe,
            $AllowPlayerSuppliers = if $orderdef.$buyFromPlayer? then $orderdef.$buyFromPlayer else $orderdef.$allowPlayerSuppliers,
            $AllowAiSuppliers = if $orderdef.$buyFromFaction? then $orderdef.$buyFromFaction else $orderdef.$allowAiSuppliers,
            $AllowBuildstorage = $orderdef.$allowBuildstorage,
            $AllowResources = $orderdef.$allowResources,
            $AllowIntermediates = $orderdef.$allowIntermediates,
            $AllowTradewares = $orderdef.$allowTradewares,
            $AutoWares = $orderdef.$autowares,
            $WareBasket = $orderdef.$warebasket,
            $MaxTrades = $orderdef.$maxTrades,
            $BacktrackTolerance = $orderdef.$backtrackTolerance,
            $MinCargoUsed = $orderdef.$minCargoUsed,
            $PlayerBuyMod = $orderdef.$playerBuyMod,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = $orderdef.$enforceRouteIllegalLegality,
            $IgnoreCarrierAux = $orderdef.$ignorecarrieraux,
            $IgnoreTradeRules = $orderdef.$ignoretraderules,
            $IgnoreMK1Supply = $orderdef.$ignoremk1supply,
            $LogbookEntries = $orderdef.$logbookentries,
            $DistancePenalty = $orderdef.$distancepenalty,
            $Notifications = $orderdef.$notifications,
            $CargoTarget = $orderdef.$cargotarget,
            $MarketUpdateFreq = $orderdef.$marketupdatefreq,
            $DebugLevel = $orderdef.$debuglevel,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK4Supply'"/>
          <set_value name="$paramsSource" exact="'assist_orderdef'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and @$orderdef.$id == 'GalaxyTraderMK4Supply2'">
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply2',
            $Home = if $orderdef.$home? then $orderdef.$home else (if $orderdef.$homeStation? then $orderdef.$homeStation else (if $orderdef.$homeSector? then $orderdef.$homeSector else (if this.assignedcontrolled.sector? then this.assignedcontrolled.sector else $gtCommander.sector))),
            $AssignHome = $orderdef.$assignHome,
            $JumpDistanceCoverage = $orderdef.$jumpDistanceCoverage,
            $JumpDistanceBuy = $orderdef.$jumpDistanceBuy,
            $DedicatedServe = if $orderdef.$serveHomeOnly? then $orderdef.$serveHomeOnly else $orderdef.$dedicatedServe,
            $AllowPlayerSuppliers = if $orderdef.$buyFromPlayer? then $orderdef.$buyFromPlayer else $orderdef.$allowPlayerSuppliers,
            $AllowAiSuppliers = if $orderdef.$buyFromFaction? then $orderdef.$buyFromFaction else $orderdef.$allowAiSuppliers,
            $PriorityBuildstorage = if $orderdef.$priorityBuildstorage? then $orderdef.$priorityBuildstorage else 10,
            $PriorityStations = if $orderdef.$priorityStations? then $orderdef.$priorityStations else 8,
            $PriorityAux = if $orderdef.$priorityAux? then $orderdef.$priorityAux else 0,
            $PriorityCarrier = if $orderdef.$priorityCarrier? then $orderdef.$priorityCarrier else 0,
            $PriorityWares = if $orderdef.$prioritywares? then $orderdef.$prioritywares else [],
            $PriorityScoreMultiplier = if $orderdef.$priorityscoremultiplier? then $orderdef.$priorityscoremultiplier else 1,
            $AllowResources = $orderdef.$allowResources,
            $AllowIntermediates = $orderdef.$allowIntermediates,
            $AllowTradewares = $orderdef.$allowTradewares,
            $AutoWares = $orderdef.$autowares,
            $WareBasket = $orderdef.$warebasket,
            $MaxTrades = $orderdef.$maxTrades,
            $BacktrackTolerance = $orderdef.$backtrackTolerance,
            $UseMinCargoThreshold = $orderdef.$useMinCargoThreshold,
            $MinCargoUsed = $orderdef.$minCargoUsed,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = $orderdef.$enforceRouteIllegalLegality,
            $IgnoreTradeRules = $orderdef.$ignoretraderules,
            $IgnoreMK1Supply = $orderdef.$ignoremk1supply,
            $LogbookEntries = $orderdef.$logbookentries,
            $DistancePenalty = $orderdef.$distancepenalty,
            $FleetCoordination = $orderdef.$fleetcoordination,
            $MarketUpdateFreq = $orderdef.$marketupdatefreq,
            $DebugLevel = $orderdef.$debuglevel,
            $TradeEval = $orderdef.$tradeeval,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false,
            $SectorWhitelist = if $orderdef.$sectorwhitelist? then $orderdef.$sectorwhitelist else [],
            $AutoJumpDistanceByLevel = if $orderdef.$autoJumpDistanceByLevel? then $orderdef.$autoJumpDistanceByLevel else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK4Supply2'"/>
          <set_value name="$paramsSource" exact="'assist_orderdef'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and @$orderdef.$id == 'GalaxyTraderMK1' and $orderdef.$homeStation?">
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK1',
            $HomeStation = $orderdef.$homeStation,
            $MaxSell = $orderdef.$maxsell,
            $IgnoreTradeRules = $orderdef.$ignoretraderules,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $WareBasket = $orderdef.$warebasket,
            $SellTarget = $orderdef.$selltarget,
            $SellSelectionMode = if $orderdef.$sellselectionmode? then $orderdef.$sellselectionmode else 2,
            $BuyTarget = $orderdef.$buytarget,
            $BacktrackTolerance = $orderdef.$backtrackTolerance,
            $LogbookEntries = $orderdef.$logbookentries,
            $Notifications = $orderdef.$notifications,
            $FleetCoordination = $orderdef.$fleetcoordination,
            $DebugLevel = $orderdef.$debuglevel,
            $Supply = $orderdef.$supply,
            $MinStorage = $orderdef.$minstorage,
            $MinSellStorage = if $orderdef.$minsellstorage? then $orderdef.$minsellstorage else 0,
            $PriceRange = if $orderdef.$pricerange? then $orderdef.$pricerange else 90,
            $ReturnHome = if $orderdef.$returnhome? then $orderdef.$returnhome else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK1'"/>
          <set_value name="$paramsSource" exact="'assist_orderdef'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and @$orderdef.$id == 'GalaxyTraderMK2' and $orderdef.$sourceStation?">
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK2',
            $SourceStation = $orderdef.$sourceStation,
            $SourceList = $orderdef.$sourceList,
            $HomeSector = if $orderdef.$homeSector? then $orderdef.$homeSector else null,
            $DestList = $orderdef.$destList,
            $MinStorage = $orderdef.$minStorage,
            $StaticStorage = $orderdef.$staticStorage,
            $MaxStorage = $orderdef.$maxStorage,
            $AutoWares = $orderdef.$autowares,
            $WareBasket = $orderdef.$warebasket,
            $IgnoreTradeRules = $orderdef.$ignoretraderules,
            $IgnoreOfferSettings = if $orderdef.$ignoreoffersettings? then $orderdef.$ignoreoffersettings else false,
            $AllowIllegal = $orderdef.$allowillegal,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $Bidirectional = $orderdef.$bidirectional,
            $MaxDistance = $orderdef.$maxDistance,
            $FleetCoordination = $orderdef.$fleetcoordination,
            $Notifications = $orderdef.$notifications,
            $DebugLevel = $orderdef.$debuglevel,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK2'"/>
          <set_value name="$paramsSource" exact="'assist_orderdef'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and @$orderdef.$id == 'GalaxyMiner' and ($orderdef.$homePosition? or $orderdef.$homeSector? or $orderdef.$homeStation?)">
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyMiner',
            $HomeStation = $orderdef.$homeStation,
            $HomePosition = if $orderdef.$homePosition? then $orderdef.$homePosition else null,
            $HomeSector = $orderdef.$homeSector,
            $ResourceBasket = $orderdef.$resourceBasket,
            $StationList = $orderdef.$stationList,
            $OverflowThreshold = $orderdef.$overflowThreshold,
            $AllowOverflowSellToOthers = $orderdef.$allowOverflowSellToOthers,
            $AssignToStation = $orderdef.$assignToStation,
            $PlayerStationsOnly = $orderdef.$playerStationsOnly,
            $CheckDemandFirst = if $orderdef.$checkDemandFirst? then $orderdef.$checkDemandFirst else true,
            $StayAtHome = $orderdef.$stayAtHome,
            $IdleParking = if $orderdef.$idleParking? then $orderdef.$idleParking else false,
            $MaxGatherDistance = $orderdef.$maxGatherDistance,
            $MaxSellDistance = $orderdef.$maxSellDistance,
            $FleetBalancing = $orderdef.$fleetBalancing,
            $DemandRecheckInterval = $orderdef.$demandRecheckInterval,
            $PhysicalStorageAbortPercent = if $orderdef.$physicalStorageAbortPercent? then $orderdef.$physicalStorageAbortPercent else 20,
            $CriticalDemandDelta = $orderdef.$criticalDemandDelta,
            $MinSwitchCooldown = $orderdef.$minSwitchCooldown,
            $MinCargoCommitPercent = $orderdef.$minCargoCommitPercent,
            $HardEmergencyDelta = $orderdef.$hardEmergencyDelta,
            $AllowIllegal = if $orderdef.$allowillegal? then $orderdef.$allowillegal else false,
            $EnforceRouteIllegalLegality = if $orderdef.$enforceRouteIllegalLegality? then $orderdef.$enforceRouteIllegalLegality else false,
            $Notifications = $orderdef.$notifications,
            $DebugLevel = $orderdef.$debuglevel
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyMiner'"/>
          <set_value name="$paramsSource" exact="'assist_orderdef'"/>
        </do_elseif>

        <!-- Source 0b (authoritative): subordinate Assist baseorder payload -->
        <do_if value="not $gtParams? and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id == 'GalaxyTraderMK3'">
          <set_value name="$gtBaseOrder" exact="this.assignedcontrolled.defaultorder.$baseorder"/>
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK3',
            $Home = if $gtBaseOrder.$home? then $gtBaseOrder.$home else (if this.assignedcontrolled.sector? then this.assignedcontrolled.sector else $gtCommander.sector),
            $MaxBuy = $gtBaseOrder.$maxbuy,
            $MaxSell = $gtBaseOrder.$maxsell,
            $AutoWares = $gtBaseOrder.$autowares,
            $WareBasket = $gtBaseOrder.$warebasket,
            $AllowIllegal = $gtBaseOrder.$allowillegal,
            $EnforceRouteIllegalLegality = $gtBaseOrder.$enforceRouteIllegalLegality,
            $DistancePenalty = $gtBaseOrder.$distancepenalty,
            $Notifications = $gtBaseOrder.$notifications,
            $CargoTarget = $gtBaseOrder.$cargotarget,
            $MarketUpdateFreq = $gtBaseOrder.$marketupdatefreq,
            $DebugLevel = $gtBaseOrder.$debuglevel,
            $TradeEval = $gtBaseOrder.$tradeeval,
            $IdleParking = if $gtBaseOrder.$idleParking? then $gtBaseOrder.$idleParking else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK3'"/>
          <set_value name="$paramsSource" exact="'assist_baseorder'"/>
        </do_if>
        <do_elseif value="not $gtParams? and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply'">
          <set_value name="$gtBaseOrder" exact="this.assignedcontrolled.defaultorder.$baseorder"/>
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply',
            $Home = if $gtBaseOrder.$home? then $gtBaseOrder.$home else (if $gtBaseOrder.$homeStation? then $gtBaseOrder.$homeStation else (if $gtBaseOrder.$homeSector? then $gtBaseOrder.$homeSector else (if this.assignedcontrolled.sector? then this.assignedcontrolled.sector else $gtCommander.sector))),
            $AssignHome = $gtBaseOrder.$assignHome,
            $JumpDistanceCoverage = $gtBaseOrder.$jumpDistanceCoverage,
            $JumpDistanceBuy = $gtBaseOrder.$jumpDistanceBuy,
            $DedicatedServe = if $gtBaseOrder.$serveHomeOnly? then $gtBaseOrder.$serveHomeOnly else $gtBaseOrder.$dedicatedServe,
            $AllowPlayerSuppliers = if $gtBaseOrder.$buyFromPlayer? then $gtBaseOrder.$buyFromPlayer else $gtBaseOrder.$allowPlayerSuppliers,
            $AllowAiSuppliers = if $gtBaseOrder.$buyFromFaction? then $gtBaseOrder.$buyFromFaction else $gtBaseOrder.$allowAiSuppliers,
            $AllowBuildstorage = $gtBaseOrder.$allowBuildstorage,
            $AllowResources = $gtBaseOrder.$allowResources,
            $AllowIntermediates = $gtBaseOrder.$allowIntermediates,
            $AllowTradewares = $gtBaseOrder.$allowTradewares,
            $AutoWares = $gtBaseOrder.$autowares,
            $WareBasket = $gtBaseOrder.$warebasket,
            $MaxTrades = $gtBaseOrder.$maxTrades,
            $BacktrackTolerance = $gtBaseOrder.$backtrackTolerance,
            $MinCargoUsed = $gtBaseOrder.$minCargoUsed,
            $PlayerBuyMod = $gtBaseOrder.$playerBuyMod,
            $AllowIllegal = $gtBaseOrder.$allowillegal,
            $EnforceRouteIllegalLegality = $gtBaseOrder.$enforceRouteIllegalLegality,
            $IgnoreCarrierAux = $gtBaseOrder.$ignorecarrieraux,
            $IgnoreTradeRules = $gtBaseOrder.$ignoretraderules,
            $IgnoreMK1Supply = $gtBaseOrder.$ignoremk1supply,
            $LogbookEntries = $gtBaseOrder.$logbookentries,
            $DistancePenalty = $gtBaseOrder.$distancepenalty,
            $Notifications = $gtBaseOrder.$notifications,
            $CargoTarget = $gtBaseOrder.$cargotarget,
            $MarketUpdateFreq = $gtBaseOrder.$marketupdatefreq,
            $DebugLevel = $gtBaseOrder.$debuglevel,
            $IdleParking = if $gtBaseOrder.$idleParking? then $gtBaseOrder.$idleParking else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK4Supply'"/>
          <set_value name="$paramsSource" exact="'assist_baseorder'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2'">
          <set_value name="$gtBaseOrder" exact="this.assignedcontrolled.defaultorder.$baseorder"/>
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK4Supply2',
            $Home = if $gtBaseOrder.$home? then $gtBaseOrder.$home else (if $gtBaseOrder.$homeStation? then $gtBaseOrder.$homeStation else (if $gtBaseOrder.$homeSector? then $gtBaseOrder.$homeSector else (if this.assignedcontrolled.sector? then this.assignedcontrolled.sector else $gtCommander.sector))),
            $AssignHome = $gtBaseOrder.$assignHome,
            $JumpDistanceCoverage = $gtBaseOrder.$jumpDistanceCoverage,
            $JumpDistanceBuy = $gtBaseOrder.$jumpDistanceBuy,
            $DedicatedServe = if $gtBaseOrder.$serveHomeOnly? then $gtBaseOrder.$serveHomeOnly else $gtBaseOrder.$dedicatedServe,
            $AllowPlayerSuppliers = if $gtBaseOrder.$buyFromPlayer? then $gtBaseOrder.$buyFromPlayer else $gtBaseOrder.$allowPlayerSuppliers,
            $AllowAiSuppliers = if $gtBaseOrder.$buyFromFaction? then $gtBaseOrder.$buyFromFaction else $gtBaseOrder.$allowAiSuppliers,
            $PriorityBuildstorage = if $gtBaseOrder.$priorityBuildstorage? then $gtBaseOrder.$priorityBuildstorage else 10,
            $PriorityStations = if $gtBaseOrder.$priorityStations? then $gtBaseOrder.$priorityStations else 8,
            $PriorityAux = if $gtBaseOrder.$priorityAux? then $gtBaseOrder.$priorityAux else 0,
            $PriorityCarrier = if $gtBaseOrder.$priorityCarrier? then $gtBaseOrder.$priorityCarrier else 0,
            $PriorityWares = if $gtBaseOrder.$prioritywares? then $gtBaseOrder.$prioritywares else [],
            $PriorityScoreMultiplier = if $gtBaseOrder.$priorityscoremultiplier? then $gtBaseOrder.$priorityscoremultiplier else 1,
            $AllowResources = $gtBaseOrder.$allowResources,
            $AllowIntermediates = $gtBaseOrder.$allowIntermediates,
            $AllowTradewares = $gtBaseOrder.$allowTradewares,
            $AutoWares = $gtBaseOrder.$autowares,
            $WareBasket = $gtBaseOrder.$warebasket,
            $MaxTrades = $gtBaseOrder.$maxTrades,
            $BacktrackTolerance = $gtBaseOrder.$backtrackTolerance,
            $UseMinCargoThreshold = $gtBaseOrder.$useMinCargoThreshold,
            $MinCargoUsed = $gtBaseOrder.$minCargoUsed,
            $AllowIllegal = $gtBaseOrder.$allowillegal,
            $EnforceRouteIllegalLegality = $gtBaseOrder.$enforceRouteIllegalLegality,
            $IgnoreTradeRules = $gtBaseOrder.$ignoretraderules,
            $IgnoreMK1Supply = $gtBaseOrder.$ignoremk1supply,
            $LogbookEntries = $gtBaseOrder.$logbookentries,
            $DistancePenalty = $gtBaseOrder.$distancepenalty,
            $FleetCoordination = $gtBaseOrder.$fleetcoordination,
            $MarketUpdateFreq = $gtBaseOrder.$marketupdatefreq,
            $DebugLevel = $gtBaseOrder.$debuglevel,
            $TradeEval = $gtBaseOrder.$tradeeval,
            $IdleParking = if $gtBaseOrder.$idleParking? then $gtBaseOrder.$idleParking else false,
            $SectorWhitelist = if $gtBaseOrder.$sectorwhitelist? then $gtBaseOrder.$sectorwhitelist else [],
            $AutoJumpDistanceByLevel = if $gtBaseOrder.$autoJumpDistanceByLevel? then $gtBaseOrder.$autoJumpDistanceByLevel else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK4Supply2'"/>
          <set_value name="$paramsSource" exact="'assist_baseorder'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id == 'GalaxyTraderMK1' and this.assignedcontrolled.defaultorder.$baseorder.$homeStation?">
          <set_value name="$gtBaseOrder" exact="this.assignedcontrolled.defaultorder.$baseorder"/>
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK1',
            $HomeStation = $gtBaseOrder.$homeStation,
            $MaxSell = $gtBaseOrder.$maxsell,
            $IgnoreTradeRules = $gtBaseOrder.$ignoretraderules,
            $AllowIllegal = $gtBaseOrder.$allowillegal,
            $EnforceRouteIllegalLegality = if $gtBaseOrder.$enforceRouteIllegalLegality? then $gtBaseOrder.$enforceRouteIllegalLegality else false,
            $WareBasket = $gtBaseOrder.$warebasket,
            $SellTarget = $gtBaseOrder.$selltarget,
            $SellSelectionMode = if $gtBaseOrder.$sellselectionmode? then $gtBaseOrder.$sellselectionmode else 2,
            $BuyTarget = $gtBaseOrder.$buytarget,
            $BacktrackTolerance = $gtBaseOrder.$backtrackTolerance,
            $LogbookEntries = $gtBaseOrder.$logbookentries,
            $Notifications = $gtBaseOrder.$notifications,
            $FleetCoordination = $gtBaseOrder.$fleetcoordination,
            $DebugLevel = $gtBaseOrder.$debuglevel,
            $Supply = $gtBaseOrder.$supply,
            $MinStorage = $gtBaseOrder.$minstorage,
            $MinSellStorage = if $gtBaseOrder.$minsellstorage? then $gtBaseOrder.$minsellstorage else 0,
            $PriceRange = if $gtBaseOrder.$pricerange? then $gtBaseOrder.$pricerange else 90,
            $ReturnHome = if $gtBaseOrder.$returnhome? then $gtBaseOrder.$returnhome else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK1'"/>
          <set_value name="$paramsSource" exact="'assist_baseorder'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id == 'GalaxyTraderMK2' and this.assignedcontrolled.defaultorder.$baseorder.$sourceStation?">
          <set_value name="$gtBaseOrder" exact="this.assignedcontrolled.defaultorder.$baseorder"/>
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyTraderMK2',
            $SourceStation = $gtBaseOrder.$sourceStation,
            $SourceList = $gtBaseOrder.$sourceList,
            $HomeSector = if $gtBaseOrder.$homeSector? then $gtBaseOrder.$homeSector else null,
            $DestList = $gtBaseOrder.$destList,
            $MinStorage = $gtBaseOrder.$minStorage,
            $StaticStorage = $gtBaseOrder.$staticStorage,
            $MaxStorage = $gtBaseOrder.$maxStorage,
            $AutoWares = $gtBaseOrder.$autowares,
            $WareBasket = $gtBaseOrder.$warebasket,
            $IgnoreTradeRules = $gtBaseOrder.$ignoretraderules,
            $IgnoreOfferSettings = if $gtBaseOrder.$ignoreoffersettings? then $gtBaseOrder.$ignoreoffersettings else false,
            $AllowIllegal = $gtBaseOrder.$allowillegal,
            $EnforceRouteIllegalLegality = if $gtBaseOrder.$enforceRouteIllegalLegality? then $gtBaseOrder.$enforceRouteIllegalLegality else false,
            $Bidirectional = $gtBaseOrder.$bidirectional,
            $MaxDistance = $gtBaseOrder.$maxDistance,
            $FleetCoordination = $gtBaseOrder.$fleetcoordination,
            $Notifications = $gtBaseOrder.$notifications,
            $DebugLevel = $gtBaseOrder.$debuglevel,
            $IdleParking = if $gtBaseOrder.$idleParking? then $gtBaseOrder.$idleParking else false
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyTraderMK2'"/>
          <set_value name="$paramsSource" exact="'assist_baseorder'"/>
        </do_elseif>
        <do_elseif value="not $gtParams? and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id == 'GalaxyMiner' and (this.assignedcontrolled.defaultorder.$baseorder.$homePosition? or this.assignedcontrolled.defaultorder.$baseorder.$homeSector? or this.assignedcontrolled.defaultorder.$baseorder.$homeStation?)">
          <set_value name="$gtBaseOrder" exact="this.assignedcontrolled.defaultorder.$baseorder"/>
          <set_value name="$gtParams" exact="table[
            $OrderId = 'GalaxyMiner',
            $HomeStation = $gtBaseOrder.$homeStation,
            $HomePosition = if $gtBaseOrder.$homePosition? then $gtBaseOrder.$homePosition else null,
            $HomeSector = $gtBaseOrder.$homeSector,
            $ResourceBasket = $gtBaseOrder.$resourceBasket,
            $StationList = $gtBaseOrder.$stationList,
            $OverflowThreshold = $gtBaseOrder.$overflowThreshold,
            $AllowOverflowSellToOthers = $gtBaseOrder.$allowOverflowSellToOthers,
            $AssignToStation = $gtBaseOrder.$assignToStation,
            $PlayerStationsOnly = $gtBaseOrder.$playerStationsOnly,
            $CheckDemandFirst = if $gtBaseOrder.$checkDemandFirst? then $gtBaseOrder.$checkDemandFirst else true,
            $StayAtHome = $gtBaseOrder.$stayAtHome,
            $IdleParking = if $gtBaseOrder.$idleParking? then $gtBaseOrder.$idleParking else false,
            $MaxGatherDistance = $gtBaseOrder.$maxGatherDistance,
            $MaxSellDistance = $gtBaseOrder.$maxSellDistance,
            $FleetBalancing = $gtBaseOrder.$fleetBalancing,
            $DemandRecheckInterval = $gtBaseOrder.$demandRecheckInterval,
            $PhysicalStorageAbortPercent = if $gtBaseOrder.$physicalStorageAbortPercent? then $gtBaseOrder.$physicalStorageAbortPercent else 20,
            $CriticalDemandDelta = $gtBaseOrder.$criticalDemandDelta,
            $MinSwitchCooldown = $gtBaseOrder.$minSwitchCooldown,
            $MinCargoCommitPercent = $gtBaseOrder.$minCargoCommitPercent,
            $HardEmergencyDelta = $gtBaseOrder.$hardEmergencyDelta,
            $AllowIllegal = if $gtBaseOrder.$allowillegal? then $gtBaseOrder.$allowillegal else false,
            $EnforceRouteIllegalLegality = if $gtBaseOrder.$enforceRouteIllegalLegality? then $gtBaseOrder.$enforceRouteIllegalLegality else false,
            $Notifications = $gtBaseOrder.$notifications,
            $DebugLevel = $gtBaseOrder.$debuglevel
          ]"/>
          <set_value name="$restoreOrderId" exact="'GalaxyMiner'"/>
          <set_value name="$paramsSource" exact="'assist_baseorder'"/>
        </do_elseif>
        
        <!-- Cache/AI fallbacks require live GT context (orderdef, Assist baseorder, or commander GT state). -->
        <set_value name="$promotionFixAllowCacheFallbacks" exact="false"/>
        <do_if value="global.$GT_ProtectedOrderIDs? and @$orderdef.$id and global.$GT_ProtectedOrderIDs.indexof.{@$orderdef.$id}">
          <set_value name="$promotionFixAllowCacheFallbacks" exact="true"/>
        </do_if>
        <do_if value="not $promotionFixAllowCacheFallbacks and this.assignedcontrolled.defaultorder? and @this.assignedcontrolled.defaultorder.id == 'Assist' and this.assignedcontrolled.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.assignedcontrolled.defaultorder.$baseorder.id}">
          <set_value name="$promotionFixAllowCacheFallbacks" exact="true"/>
        </do_if>
        <do_if value="not $promotionFixAllowCacheFallbacks and global.$GT_CommanderGTState? and global.$GT_CommanderGTState.{$gtCommander}? and global.$GT_CommanderGTState.{$gtCommander}.$IsGTActive? and global.$GT_CommanderGTState.{$gtCommander}.$IsGTActive">
          <set_value name="$promotionFixAllowCacheFallbacks" exact="true"/>
        </do_if>
        
        <!-- Fallback 1: Commander's own cached params -->
        <do_if value="$promotionFixAllowCacheFallbacks and not $gtParams? and global.$GT_Ships? and global.$GT_Ships.{$gtCommander}? and global.$GT_Ships.{$gtCommander}.$InheritedGTDefaultOrderParams?">
          <set_value name="$gtParams" exact="global.$GT_Ships.{$gtCommander}.$InheritedGTDefaultOrderParams"/>
          <set_value name="$restoreOrderId" exact="$gtParams.$OrderId"/>
          <set_value name="$paramsSource" exact="'commander_own'"/>
        </do_if>
        
        <!-- Fallback 2: THIS subordinate's cached params -->
        <do_if value="$promotionFixAllowCacheFallbacks and not $gtParams? and global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}? and global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams?">
          <set_value name="$gtParams" exact="global.$GT_Ships.{this.assignedcontrolled}.$InheritedGTDefaultOrderParams"/>
          <set_value name="$restoreOrderId" exact="$gtParams.$OrderId"/>
          <set_value name="$paramsSource" exact="'this_subordinate'"/>
        </do_if>
        
        <!-- Fallback 3: Check commander's OTHER subordinates for cached params (they all inherited from destroyed commander) -->
        <do_if value="$promotionFixAllowCacheFallbacks and not $gtParams? and $gtCommander.allsubordinates?">
          <set_value name="$commanderSubordinates" exact="@$gtCommander.allsubordinates"/>
          <do_if value="(if $commanderSubordinates != null then $commanderSubordinates.count else 0) gt 0">
            <do_all exact="$commanderSubordinates.count" counter="$subIdx">
              <set_value name="$otherSubordinate" exact="$commanderSubordinates.{$subIdx}"/>
              <do_if value="not $gtParams? and $otherSubordinate.exists and global.$GT_Ships? and global.$GT_Ships.{$otherSubordinate}? and global.$GT_Ships.{$otherSubordinate}.$InheritedGTDefaultOrderParams?">
                <set_value name="$gtParams" exact="global.$GT_Ships.{$otherSubordinate}.$InheritedGTDefaultOrderParams"/>
                <set_value name="$restoreOrderId" exact="$gtParams.$OrderId"/>
                <set_value name="$paramsSource" exact="'other_subordinate'"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        
        <!-- Fallback 4: Check GT_AIParameters for commander (if it has a HomeBase, we can derive params) -->
        <do_if value="$promotionFixAllowCacheFallbacks and not $gtParams? and global.$GT_AIParameters? and global.$GT_AIParameters.{$gtCommander}? and global.$GT_AIParameters.{$gtCommander}.$HomeBase?">
          <set_value name="$homeBase" exact="global.$GT_AIParameters.{$gtCommander}.$HomeBase"/>
          <set_value name="$homeSector" exact="null"/>
          <do_if value="$homeBase.exists">
            <do_if value="$homeBase.isclass.station">
              <set_value name="$homeSector" exact="$homeBase.sector"/>
            </do_if>
            <do_elseif value="$homeBase.isclass.sector">
              <set_value name="$homeSector" exact="$homeBase"/>
            </do_elseif>
          </do_if>
          <do_if value="$homeSector? and $homeSector.exists">
            <!-- Build minimal params from GT_AIParameters -->
            <set_value name="$gtParams" exact="table[
              $OrderId = 'GalaxyTraderMK3',
              $Home = $homeSector,
              $MaxBuy = if global.$GT_AIParameters.{$gtCommander}.$MaxBuy? then global.$GT_AIParameters.{$gtCommander}.$MaxBuy else 100,
              $MaxSell = if global.$GT_AIParameters.{$gtCommander}.$MaxSell? then global.$GT_AIParameters.{$gtCommander}.$MaxSell else 100,
              $AutoWares = if global.$GT_AIParameters.{$gtCommander}.$AutoWares? then global.$GT_AIParameters.{$gtCommander}.$AutoWares else true,
              $WareBasket = if global.$GT_AIParameters.{$gtCommander}.$WareBasket? then global.$GT_AIParameters.{$gtCommander}.$WareBasket else [],
              $AllowIllegal = if global.$GT_AIParameters.{$gtCommander}.$AllowIllegal? then global.$GT_AIParameters.{$gtCommander}.$AllowIllegal else false,
              $EnforceRouteIllegalLegality = if global.$GT_AIParameters.{$gtCommander}.$EnforceRouteIllegalLegality? then global.$GT_AIParameters.{$gtCommander}.$EnforceRouteIllegalLegality else false,
              $DistancePenalty = if global.$GT_AIParameters.{$gtCommander}.$DistancePenalty? then global.$GT_AIParameters.{$gtCommander}.$DistancePenalty else 0.1,
              $Notifications = if global.$GT_AIParameters.{$gtCommander}.$Notifications? then global.$GT_AIParameters.{$gtCommander}.$Notifications else true,
              $CargoTarget = if global.$GT_AIParameters.{$gtCommander}.$CargoTarget? then global.$GT_AIParameters.{$gtCommander}.$CargoTarget else 0.9,
              $MarketUpdateFreq = if global.$GT_AIParameters.{$gtCommander}.$MarketUpdateFreq? then global.$GT_AIParameters.{$gtCommander}.$MarketUpdateFreq else 300,
              $DebugLevel = if global.$GT_AIParameters.{$gtCommander}.$DebugLevel? then global.$GT_AIParameters.{$gtCommander}.$DebugLevel else 1,
              $TradeEval = if global.$GT_AIParameters.{$gtCommander}.$TradeEval? then global.$GT_AIParameters.{$gtCommander}.$TradeEval else 'profit',
              $IdleParking = false
            ]"/>
            <set_value name="$restoreOrderId" exact="'GalaxyTraderMK3'"/>
            <set_value name="$paramsSource" exact="'gt_aiparameters'"/>
          </do_if>
        </do_if>
        
        <!-- Reject cache-sourced restore without a protected order id (no invented MK3 defaults). -->
        <do_if value="$gtParams? and $restoreOrderId? and global.$GT_ProtectedOrderIDs? and not global.$GT_ProtectedOrderIDs.indexof.{$restoreOrderId}">
          <remove_value name="$gtParams"/>
          <remove_value name="$restoreOrderId"/>
          <set_value name="$paramsSource" exact="'rejected_unprotected_order'"/>
        </do_if>
        
        <!-- Create order if we found params -->
        <do_if value="$gtParams? and $gtParams != null and $restoreOrderId? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$restoreOrderId}">
            <do_if value="$restoreOrderId == 'GalaxyTraderMK3' and $gtParams.$Home?">
              <create_order id="'GalaxyTraderMK3'" object="$gtCommander" default="true">
                <param name="home" value="$gtParams.$Home"/>
                <param name="maxbuy" value="$gtParams.$MaxBuy"/>
                <param name="maxsell" value="$gtParams.$MaxSell"/>
                <param name="autowares" value="$gtParams.$AutoWares"/>
                <param name="warebasket" value="$gtParams.$WareBasket"/>
                <param name="allowillegal" value="$gtParams.$AllowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="if $gtParams.$EnforceRouteIllegalLegality? then $gtParams.$EnforceRouteIllegalLegality else false"/>
                <param name="distancepenalty" value="$gtParams.$DistancePenalty"/>
                <param name="notifications" value="$gtParams.$Notifications"/>
                <param name="cargotarget" value="$gtParams.$CargoTarget"/>
                <param name="marketupdatefreq" value="$gtParams.$MarketUpdateFreq"/>
                <param name="debuglevel" value="$gtParams.$DebugLevel"/>
                <param name="tradeeval" value="$gtParams.$TradeEval"/>
                <param name="idleParking" value="if $gtParams.$IdleParking? then $gtParams.$IdleParking else false"/>
              </create_order>
            </do_if>
            <do_elseif value="$restoreOrderId == 'GalaxyTraderMK4Supply' and $gtParams.$Home?">
              <create_order id="'GalaxyTraderMK4Supply'" object="$gtCommander" default="true">
                <param name="home" value="$gtParams.$Home"/>
                <param name="assignHome" value="if $gtParams.$AssignHome? then $gtParams.$AssignHome else false"/>
                <param name="jumpDistanceCoverage" value="if $gtParams.$JumpDistanceCoverage? then $gtParams.$JumpDistanceCoverage else 1"/>
                <param name="jumpDistanceBuy" value="if $gtParams.$JumpDistanceBuy? then $gtParams.$JumpDistanceBuy else 1"/>
                <param name="serveHomeOnly" value="if $gtParams.$DedicatedServe? then $gtParams.$DedicatedServe else false"/>
                <param name="buyFromPlayer" value="if $gtParams.$AllowPlayerSuppliers? then $gtParams.$AllowPlayerSuppliers else true"/>
                <param name="buyFromFaction" value="if $gtParams.$AllowAiSuppliers? then $gtParams.$AllowAiSuppliers else true"/>
                <param name="dedicatedServe" value="if $gtParams.$DedicatedServe? then $gtParams.$DedicatedServe else false"/>
                <param name="allowPlayerSuppliers" value="if $gtParams.$AllowPlayerSuppliers? then $gtParams.$AllowPlayerSuppliers else true"/>
                <param name="allowAiSuppliers" value="if $gtParams.$AllowAiSuppliers? then $gtParams.$AllowAiSuppliers else true"/>
                <param name="allowBuildstorage" value="if $gtParams.$AllowBuildstorage? then $gtParams.$AllowBuildstorage else true"/>
                <param name="allowResources" value="if $gtParams.$AllowResources? then $gtParams.$AllowResources else true"/>
                <param name="allowIntermediates" value="if $gtParams.$AllowIntermediates? then $gtParams.$AllowIntermediates else true"/>
                <param name="allowTradewares" value="if $gtParams.$AllowTradewares? then $gtParams.$AllowTradewares else true"/>
                <param name="autowares" value="if $gtParams.$AutoWares? then $gtParams.$AutoWares else true"/>
                <param name="warebasket" value="if $gtParams.$WareBasket? then $gtParams.$WareBasket else []"/>
                <param name="maxTrades" value="if $gtParams.$MaxTrades? then $gtParams.$MaxTrades else 4"/>
                <param name="backtrackTolerance" value="if $gtParams.$BacktrackTolerance? then $gtParams.$BacktrackTolerance else 15"/>
                <param name="minCargoUsed" value="if $gtParams.$MinCargoUsed? then $gtParams.$MinCargoUsed else 0.5"/>
                <param name="playerBuyMod" value="if $gtParams.$PlayerBuyMod? then $gtParams.$PlayerBuyMod else 1"/>
                <param name="allowillegal" value="if $gtParams.$AllowIllegal? then $gtParams.$AllowIllegal else false"/>
                <param name="enforceRouteIllegalLegality" value="if $gtParams.$EnforceRouteIllegalLegality? then $gtParams.$EnforceRouteIllegalLegality else false"/>
                <param name="ignorecarrieraux" value="if $gtParams.$IgnoreCarrierAux? then $gtParams.$IgnoreCarrierAux else false"/>
                <param name="ignoretraderules" value="if $gtParams.$IgnoreTradeRules? then $gtParams.$IgnoreTradeRules else false"/>
                <param name="ignoremk1supply" value="if $gtParams.$IgnoreMK1Supply? then $gtParams.$IgnoreMK1Supply else false"/>
                <param name="logbookentries" value="if $gtParams.$LogbookEntries? then $gtParams.$LogbookEntries else true"/>
                <param name="distancepenalty" value="if $gtParams.$DistancePenalty? then $gtParams.$DistancePenalty else 0.1"/>
                <param name="notifications" value="if $gtParams.$Notifications? then $gtParams.$Notifications else true"/>
                <param name="marketupdatefreq" value="if $gtParams.$MarketUpdateFreq? then $gtParams.$MarketUpdateFreq else 300"/>
                <param name="debuglevel" value="if $gtParams.$DebugLevel? then $gtParams.$DebugLevel else 1"/>
                <param name="idleParking" value="if $gtParams.$IdleParking? then $gtParams.$IdleParking else false"/>
              </create_order>
            </do_elseif>
            <do_elseif value="$restoreOrderId == 'GalaxyTraderMK4Supply2' and $gtParams.$Home?">
              <create_order id="'GalaxyTraderMK4Supply2'" object="$gtCommander" default="true">
                <param name="home" value="$gtParams.$Home"/>
                <param name="assignHome" value="if $gtParams.$AssignHome? then $gtParams.$AssignHome else false"/>
                <param name="jumpDistanceCoverage" value="if $gtParams.$JumpDistanceCoverage? then $gtParams.$JumpDistanceCoverage else 1"/>
                <param name="jumpDistanceBuy" value="if $gtParams.$JumpDistanceBuy? then $gtParams.$JumpDistanceBuy else 1"/>
                <param name="serveHomeOnly" value="if $gtParams.$DedicatedServe? then $gtParams.$DedicatedServe else false"/>
                <param name="buyFromPlayer" value="if $gtParams.$AllowPlayerSuppliers? then $gtParams.$AllowPlayerSuppliers else true"/>
                <param name="buyFromFaction" value="if $gtParams.$AllowAiSuppliers? then $gtParams.$AllowAiSuppliers else true"/>
                <param name="priorityBuildstorage" value="if $gtParams.$PriorityBuildstorage? then $gtParams.$PriorityBuildstorage else 10"/>
                <param name="priorityStations" value="if $gtParams.$PriorityStations? then $gtParams.$PriorityStations else 8"/>
                <param name="priorityAux" value="if $gtParams.$PriorityAux? then $gtParams.$PriorityAux else 0"/>
                <param name="priorityCarrier" value="if $gtParams.$PriorityCarrier? then $gtParams.$PriorityCarrier else 0"/>
                <param name="prioritywares" value="if $gtParams.$PriorityWares? then $gtParams.$PriorityWares else []"/>
                <param name="priorityscoremultiplier" value="if $gtParams.$PriorityScoreMultiplier? then $gtParams.$PriorityScoreMultiplier else 1"/>
                <param name="allowResources" value="if $gtParams.$AllowResources? then $gtParams.$AllowResources else true"/>
                <param name="allowIntermediates" value="if $gtParams.$AllowIntermediates? then $gtParams.$AllowIntermediates else true"/>
                <param name="allowTradewares" value="if $gtParams.$AllowTradewares? then $gtParams.$AllowTradewares else true"/>
                <param name="autowares" value="if $gtParams.$AutoWares? then $gtParams.$AutoWares else true"/>
                <param name="warebasket" value="if $gtParams.$WareBasket? then $gtParams.$WareBasket else []"/>
                <param name="maxTrades" value="if $gtParams.$MaxTrades? then $gtParams.$MaxTrades else 3"/>
                <param name="backtrackTolerance" value="if $gtParams.$BacktrackTolerance? then $gtParams.$BacktrackTolerance else 1"/>
                <param name="useMinCargoThreshold" value="if $gtParams.$UseMinCargoThreshold? then $gtParams.$UseMinCargoThreshold else false"/>
                <param name="minCargoUsed" value="if $gtParams.$MinCargoUsed? then $gtParams.$MinCargoUsed else 80"/>
                <param name="allowillegal" value="if $gtParams.$AllowIllegal? then $gtParams.$AllowIllegal else false"/>
                <param name="enforceRouteIllegalLegality" value="if $gtParams.$EnforceRouteIllegalLegality? then $gtParams.$EnforceRouteIllegalLegality else false"/>
                <param name="ignoretraderules" value="if $gtParams.$IgnoreTradeRules? then $gtParams.$IgnoreTradeRules else false"/>
                <param name="ignoremk1supply" value="if $gtParams.$IgnoreMK1Supply? then $gtParams.$IgnoreMK1Supply else true"/>
                <param name="logbookentries" value="if $gtParams.$LogbookEntries? then $gtParams.$LogbookEntries else true"/>
                <param name="distancepenalty" value="if $gtParams.$DistancePenalty? then $gtParams.$DistancePenalty else 50"/>
                <param name="fleetcoordination" value="if $gtParams.$FleetCoordination? then $gtParams.$FleetCoordination else true"/>
                <param name="marketupdatefreq" value="if $gtParams.$MarketUpdateFreq? then $gtParams.$MarketUpdateFreq else 60s"/>
                <param name="debuglevel" value="if $gtParams.$DebugLevel? then $gtParams.$DebugLevel else 1"/>
                <param name="tradeeval" value="if $gtParams.$TradeEval? then $gtParams.$TradeEval else false"/>
                <param name="idleParking" value="if $gtParams.$IdleParking? then $gtParams.$IdleParking else false"/>
                <param name="sectorwhitelist" value="if $gtParams.$SectorWhitelist? then $gtParams.$SectorWhitelist else []"/>
                <param name="autoJumpDistanceByLevel" value="if $gtParams.$AutoJumpDistanceByLevel? then $gtParams.$AutoJumpDistanceByLevel else false"/>
              </create_order>
            </do_elseif>
            <do_elseif value="$restoreOrderId == 'GalaxyTraderMK1' and $gtParams.$HomeStation?">
              <create_order id="'GalaxyTraderMK1'" object="$gtCommander" default="true">
                <param name="homeStation" value="$gtParams.$HomeStation"/>
                <param name="maxsell" value="$gtParams.$MaxSell"/>
                <param name="ignoretraderules" value="$gtParams.$IgnoreTradeRules"/>
                <param name="allowillegal" value="$gtParams.$AllowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="if $gtParams.$EnforceRouteIllegalLegality? then $gtParams.$EnforceRouteIllegalLegality else false"/>
                <param name="warebasket" value="$gtParams.$WareBasket"/>
                <param name="selltarget" value="$gtParams.$SellTarget"/>
                <param name="sellselectionmode" value="if $gtParams.$SellSelectionMode? then $gtParams.$SellSelectionMode else 2"/>
                <param name="buytarget" value="$gtParams.$BuyTarget"/>
                <param name="backtrackTolerance" value="$gtParams.$BacktrackTolerance"/>
                <param name="logbookentries" value="$gtParams.$LogbookEntries"/>
                <param name="notifications" value="$gtParams.$Notifications"/>
                <param name="fleetcoordination" value="$gtParams.$FleetCoordination"/>
                <param name="debuglevel" value="$gtParams.$DebugLevel"/>
                <param name="supply" value="$gtParams.$Supply"/>
                <param name="minstorage" value="$gtParams.$MinStorage"/>
                <param name="minsellstorage" value="if $gtParams.$MinSellStorage? then $gtParams.$MinSellStorage else 0"/>
                <param name="pricerange" value="if $gtParams.$PriceRange? then $gtParams.$PriceRange else 90"/>
                <param name="returnhome" value="if $gtParams.$ReturnHome? then $gtParams.$ReturnHome else false"/>
              </create_order>
            </do_elseif>
            <do_elseif value="$restoreOrderId == 'GalaxyTraderMK2' and $gtParams.$SourceStation?">
              <create_order id="'GalaxyTraderMK2'" object="$gtCommander" default="true">
                <param name="sourceStation" value="$gtParams.$SourceStation"/>
                <param name="sourceList" value="$gtParams.$SourceList"/>
                <param name="homeStation" value="null"/>
                <param name="homeSector" value="if $gtParams.$HomeSector? then $gtParams.$HomeSector else null"/>
                <param name="destList" value="$gtParams.$DestList"/>
                <param name="minStorage" value="$gtParams.$MinStorage"/>
                <param name="staticStorage" value="$gtParams.$StaticStorage"/>
                <param name="maxStorage" value="$gtParams.$MaxStorage"/>
                <param name="autowares" value="$gtParams.$AutoWares"/>
                <param name="warebasket" value="$gtParams.$WareBasket"/>
                <param name="ignoretraderules" value="$gtParams.$IgnoreTradeRules"/>
                <param name="ignoreoffersettings" value="if $gtParams.$IgnoreOfferSettings? then $gtParams.$IgnoreOfferSettings else false"/>
                <param name="allowillegal" value="$gtParams.$AllowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="if $gtParams.$EnforceRouteIllegalLegality? then $gtParams.$EnforceRouteIllegalLegality else false"/>
                <param name="bidirectional" value="$gtParams.$Bidirectional"/>
                <param name="maxDistance" value="$gtParams.$MaxDistance"/>
                <param name="fleetcoordination" value="$gtParams.$FleetCoordination"/>
                <param name="notifications" value="$gtParams.$Notifications"/>
                <param name="debuglevel" value="$gtParams.$DebugLevel"/>
                <param name="idleParking" value="if $gtParams.$IdleParking? then $gtParams.$IdleParking else false"/>
              </create_order>
            </do_elseif>
            <do_elseif value="$restoreOrderId == 'GalaxyMiner' and ($gtParams.$HomePosition? or $gtParams.$HomeSector? or $gtParams.$HomeStation?)">
              <create_order id="'GalaxyMiner'" object="$gtCommander" default="true">
                <param name="homeStation" value="$gtParams.$HomeStation"/>
                <param name="homePosition" value="if $gtParams.$HomePosition? then $gtParams.$HomePosition else null"/>
                <param name="homeSector" value="$gtParams.$HomeSector"/>
                <param name="resourceBasket" value="$gtParams.$ResourceBasket"/>
                <param name="stationList" value="$gtParams.$StationList"/>
                <param name="overflowThreshold" value="$gtParams.$OverflowThreshold"/>
                <param name="allowOverflowSellToOthers" value="$gtParams.$AllowOverflowSellToOthers"/>
                <param name="assignToStation" value="$gtParams.$AssignToStation"/>
                <param name="playerStationsOnly" value="$gtParams.$PlayerStationsOnly"/>
                <param name="checkDemandFirst" value="if $gtParams.$CheckDemandFirst? then $gtParams.$CheckDemandFirst else true"/>
                <param name="stayAtHome" value="$gtParams.$StayAtHome"/>
                <param name="idleParking" value="if $gtParams.$IdleParking? then $gtParams.$IdleParking else false"/>
                <param name="maxGatherDistance" value="$gtParams.$MaxGatherDistance"/>
                <param name="maxSellDistance" value="$gtParams.$MaxSellDistance"/>
                <param name="fleetBalancing" value="$gtParams.$FleetBalancing"/>
                <param name="demandRecheckInterval" value="$gtParams.$DemandRecheckInterval"/>
                <param name="physicalStorageAbortPercent" value="if $gtParams.$PhysicalStorageAbortPercent? then $gtParams.$PhysicalStorageAbortPercent else 20"/>
                <param name="criticalDemandDelta" value="$gtParams.$CriticalDemandDelta"/>
                <param name="minSwitchCooldown" value="$gtParams.$MinSwitchCooldown"/>
                <param name="minCargoCommitPercent" value="$gtParams.$MinCargoCommitPercent"/>
                <param name="hardEmergencyDelta" value="$gtParams.$HardEmergencyDelta"/>
                <param name="allowillegal" value="if $gtParams.$AllowIllegal? then $gtParams.$AllowIllegal else false"/>
                <param name="enforceRouteIllegalLegality" value="if $gtParams.$EnforceRouteIllegalLegality? then $gtParams.$EnforceRouteIllegalLegality else false"/>
                <param name="notifications" value="$gtParams.$Notifications"/>
                <param name="debuglevel" value="$gtParams.$DebugLevel"/>
              </create_order>
            </do_elseif>
            <!-- Optional: ensure commander is registered (doesn't change behavior, just preserves data) -->
            <do_if value="not global.$GT_Ships.{$gtCommander}?">
              <set_value name="global.$GT_Ships.{$gtCommander}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{$gtCommander}.$InheritedGTDefaultOrderParams" exact="$gtParams"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ': Restored missing default GT order on promoted commander ' + $gtCommander.idcode + ' (promotion window; source: ' + $paramsSource + ')'" chance="100"/>
            </do_if>
            <!-- Restart assist evaluation now that commander has an actionable default order -->
            <resume label="init"/>
        </do_if>
        <do_else>
          <!-- Log if we couldn't restore order -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] WARNING: ' + this.assignedcontrolled.idcode + ': Could not restore default GT order on promoted commander ' + $gtCommander.idcode + ' (params source unresolved; orderdef.id=' + (if @$orderdef.$id then @$orderdef.$id else 'null') + ', assist.baseorder=' + (if this.assignedcontrolled.defaultorder? and this.assignedcontrolled.defaultorder.$baseorder? and @this.assignedcontrolled.defaultorder.$baseorder.id then @this.assignedcontrolled.defaultorder.$baseorder.id else 'null') + ', commander.default=' + (if @$gtCommander.defaultorder.id then @$gtCommander.defaultorder.id else 'null') + ')'" chance="100"/>
          </do_if>
        </do_else>
        </do_if>
        <!-- End: not $promotionFixBlocked -->
      </do_if>
      <!-- End: Commander has no default order -->
    </do_if>
    <!-- End: Commander exists and is player owned -->
    <do_else>
      <!-- DEBUG: Log why we're not fixing -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$gtCommanderCheck" exact="@this.assignedcontrolled.commander"/>
        <debug_text text="'[GT-Assist] PROMOTION FIX: Skipping fix - commander check failed (commander exists: ' + (if $gtCommanderCheck? and $gtCommanderCheck.exists then 'yes' else 'no') + ', is player owned: ' + (if $gtCommanderCheck? and $gtCommanderCheck.exists and $gtCommanderCheck.isplayerowned then 'yes' else 'no') + ')'" chance="100"/>
      </do_if>
    </do_else>
  </add>
  
  <!-- PHASE 7: Detect when subordinate is removed (no commander detected) -->
  <!-- When a subordinate is removed, Assist order detects no commander and cancels itself -->
  <!-- This is the perfect place to detect GT order removal for subordinates -->
  <add sel="//aiscript[@name='order.assist']/attention/actions/do_if[@value='not @this.assignedcontrolled.commander.isclass.ship']" pos="after">
    
    <!-- PHASE 7: Detect GT order removal when subordinate is removed -->
    <!-- CRITICAL: This patch triggers when commander.isclass.ship is false -->
    <!-- This can mean: 1) Commander doesn't exist (removed), OR 2) Commander is station/buildstorage (still subordinate!) -->
    <!-- We must ONLY trigger if commander was actually REMOVED, not if commander is just a station -->
    
    <!-- CRITICAL FIX: Check if commander actually exists before processing -->
    <!-- If commander exists (even if not a ship), ship is still subordinate - don't trigger removal -->
    <set_value name="$commanderExists" exact="false"/>
    <do_if value="this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists">
      <set_value name="$commanderExists" exact="true"/>
    </do_if>
    
    <!-- Only process if commander was actually removed (doesn't exist) -->
    <do_if value="not $commanderExists">
      <!-- FIX 2: State-independent cleanup - check commander directly, initialize state if needed -->
      
      <!-- Initialize state registry if missing -->
      <do_if value="not global.$GT_Ship_State?">
        <set_value name="global.$GT_Ship_State" exact="table[]"/>
      </do_if>
      
      <!-- Initialize ship state if missing (lazy initialization) -->
      <do_if value="not global.$GT_Ship_State.{this.assignedcontrolled}?">
        <set_value name="global.$GT_Ship_State.{this.assignedcontrolled}" exact="table[
          $OperationalState = 'idle',
          $SubordinateState = 'independent',
          $Commander = null,
          $CommanderHasGT = false,
          $HasGTOrder = false,
          $HasAssistOrder = false,
          $ActiveTradeOrders = 0,
          $LastStateUpdate = player.age,
          $MacroShipName = null,
          $OriginalShipName = null
        ]"/>
      </do_if>
      
      <set_value name="$state" exact="global.$GT_Ship_State.{this.assignedcontrolled}"/>
      
      <!-- CRITICAL FIX: Check if ship is being newly assigned to a commander -->
      <!-- During assignment transition, commander might not be detected yet, but ship might have been idle before -->
      <!-- Get old commander from state (if tracked) -->
      <set_value name="$oldCommander" exact="null"/>
      <do_if value="$state.$Commander? and $state.$Commander.exists">
        <set_value name="$oldCommander" exact="$state.$Commander"/>
      </do_if>
      
      <!-- Check if ship is being newly assigned (had no commander before, now has one) -->
      <set_value name="$newlyAssignedToCommander" exact="false"/>
      <do_if value="(not $oldCommander.exists or $oldCommander == null) and this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists">
        <set_value name="$newlyAssignedToCommander" exact="true"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - NEWLY ASSIGNED to commander ' + this.assignedcontrolled.commander.idcode + ' (was idle before) - skipping cleanup'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Only proceed if ship was NOT newly assigned -->
      <do_if value="not $newlyAssignedToCommander">
        <!-- Check if ship was subordinate to GT commander (commander was removed) -->
        <set_value name="$wasSubordinateToGTCommander" exact="false"/>
        
        <!-- Method 1: Check state (if it was tracked) -->
        <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
          <do_if value="$state.$CommanderHasGT? and $state.$CommanderHasGT">
            <set_value name="$wasSubordinateToGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Method 2: PRIMARY CHECK - Ship is in GT_Ships registry (indicates it was GT-controlled) -->
        <!-- ALL ships with GT orders are in global.$GT_Ships, regardless of modifications -->
        <do_if value="not $wasSubordinateToGTCommander and global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?">
          <set_value name="$wasSubordinateToGTCommander" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Ship is in GT_Ships registry - treating as GT subordinate removal'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- If ship was subordinate to GT commander and is now removed, restore name and send cancellation signal -->
        <do_if value="$wasSubordinateToGTCommander">
        <!-- CRITICAL FIX: Check if ship still has GT order (direct or via new commander) BEFORE sending cancellation -->
        <!-- Ship might have been reassigned to another GT commander or got direct GT order -->
        <set_value name="$stillHasGTOrder" exact="false"/>
        
        <!-- Check 1: Direct GT order -->
        <do_if value="this.assignedcontrolled.defaultorder? and (@this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.defaultorder.id == 'GalaxyMiner')">
          <set_value name="$stillHasGTOrder" exact="true"/>
        </do_if>
        
        <!-- Check 2: Subordinate to GT commander (new commander) -->
        <do_if value="not $stillHasGTOrder and this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists and this.assignedcontrolled.commander != this.assignedcontrolled">
          <do_if value="this.assignedcontrolled.commander.defaultorder? and ((@this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyExplorer') or (@this.assignedcontrolled.commander.defaultorder.id == 'Assist' and this.assignedcontrolled.commander.defaultorder.$baseorder? and (@this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyExplorer')))">
            <set_value name="$stillHasGTOrder" exact="true"/>
          </do_if>
        </do_if>
      
        <!-- Only send cancellation signal if ship NO LONGER has GT order -->
        <do_if value="not $stillHasGTOrder">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 7: ' + this.assignedcontrolled.idcode + ' - Subordinate removed from GT commander (detected in Assist order) - GT order truly cancelled'" chance="100"/>
          </do_if>
          
          <!-- Update state to reflect GT order cancellation -->
          <set_value name="$state.$HasGTOrder" exact="false"/>
          <set_value name="$state.$OperationalState" exact="'orphaned'"/>
          <set_value name="$state.$ActiveTradeOrders" exact="0"/>
          <set_value name="$state.$Commander" exact="null"/>
          <set_value name="$state.$CommanderHasGT" exact="false"/>
          <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
          <set_value name="$state.$LastStateUpdate" exact="player.age"/>
          
          <!-- MOD REMOVAL: Send GT_Ship_State_Update signal for mod removal system -->
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.assignedcontrolled,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
          
            <!-- EVENT-DRIVEN: Trigger orphaned ship check for subordinate -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?">
              <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.assignedcontrolled]"/>
            </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 7: ' + this.assignedcontrolled.idcode + ' - Subordinate removed from GT commander BUT ship still has GT order (direct or via new commander) - NOT sending cancellation'" chance="100"/>
          </do_if>
        </do_else>
        </do_if>
      <!-- End: Only proceed if ship was NOT newly assigned -->
      </do_if>
      
      <!-- NAME RESTORATION: Restore ship name (only if no GT order) -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <do_if value="this.assignedcontrolled.defaultorder? and (@this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.defaultorder.id == 'GalaxyMiner')">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <do_if value="not $hasDirectGTOrder and this.assignedcontrolled.pilot?">
        <set_value name="$originalName" exact="null"/>
        <do_if value="$state.$OriginalShipName?">
          <set_value name="$originalName" exact="$state.$OriginalShipName"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots? and global.$GT_Pilots.{this.assignedcontrolled.pilot}? and global.$GT_Pilots.{this.assignedcontrolled.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{this.assignedcontrolled.pilot}.$OriginalShipName"/>
        </do_elseif>
        
        <do_if value="$originalName">
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.assignedcontrolled,
            $Pilot = this.assignedcontrolled.pilot,
            $Reason = 'Subordinate removed from GT commander - restoring original name',
            $OriginalName = $originalName
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 7: Name restoration signal sent for ' + this.assignedcontrolled.idcode + ' (removed from GT commander, original name: ' + $originalName + ')'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
    </do_if>
    <!-- End: Only process if commander was actually removed -->
    
  </add>
  
  <!-- FIX: Add null check for this.assignedcontrolled.order before accessing .isrunning (vanilla bug) -->
  <!-- Vanilla code has multiple instances of order.isrunning without null check -->
  <!-- Instance 1: Line 853 - after "not $added?" check -->
  <!-- Note: Selector uses contains() to match the value with "and" operator -->
  <replace sel="//aiscript[@name='order.assist']/attention/actions/do_if[@value='not $added?']/do_if[contains(@value, 'this.assignedcontrolled.order.isrunning')]">
    <do_if value="$failurereason?">
      <do_if value="this.assignedcontrolled.order?">
        <do_if value="this.assignedcontrolled.order.isrunning">
          <set_order_failed order="this.assignedcontrolled.order" text="$failurereason"/>
        </do_if>
      </do_if>
    </do_if>
  </replace>
  
  <!-- Instance 2: Line 870 - after remove_value $added, before wait -->
  <!-- Use a more specific path that includes context -->
  <replace sel="//aiscript[@name='order.assist']/attention/actions/remove_value[@name='$added']/following-sibling::*[1][self::do_if[@value='this.assignedcontrolled.order.isrunning']]">
    <do_if value="this.assignedcontrolled.order?">
      <do_if value="@this.assignedcontrolled.order.isrunning">
        <set_order_syncpoint_reached order="this.assignedcontrolled.order"/>
      </do_if>
    </do_if>
  </replace>
  
  <!-- PHASE 7: Detect when Assist order is aborted (catches "remove all commands and orders") -->
  <!-- When Assist order terminates, check if subordinate was GT-controlled and trigger cleanup -->
  <add sel="//aiscript[@name='order.assist']/attention" pos="after">
    <on_abort>
      <!-- Intentional GT handoff guard:
           MK1 can hand off to DockAndReturnHome; MK2/MK3/MK4/Miner idle parking uses GTIdlePark.
           Assist abort during these transitions is expected and must not trigger cleanup/restore logic. -->
      <set_value name="$isGTNavHandoff" exact="false"/>
      <do_if value="this.assignedcontrolled.order? and (@this.assignedcontrolled.order.id == 'DockAndReturnHome' or @this.assignedcontrolled.order.id == 'GTIdlePark')">
        <set_value name="$isGTNavHandoff" exact="true"/>
      </do_if>
      <do_elseif value="this.assignedcontrolled.order? and @this.assignedcontrolled.order.id == 'DockAndWait' and this.assignedcontrolled.order.$callerid? and (@this.assignedcontrolled.order.$callerid.id == 'DockAndReturnHome' or @this.assignedcontrolled.order.$callerid.id == 'GTIdlePark')">
        <set_value name="$isGTNavHandoff" exact="true"/>
      </do_elseif>
      <!-- Current order can still be Assist while navigation handoff orders are queued/running.
           Scan active orders list as authoritative handoff signal. -->
      <do_if value="not $isGTNavHandoff and this.assignedcontrolled.orders.count gt 0">
        <do_all exact="this.assignedcontrolled.orders.count" counter="$rhoi">
          <set_value name="$rhOrder" exact="this.assignedcontrolled.orders.{$rhoi}"/>
          <do_if value="$rhOrder.id == 'DockAndReturnHome' or $rhOrder.id == 'GTIdlePark'">
            <set_value name="$isGTNavHandoff" exact="true"/>
            <break/>
          </do_if>
          <do_elseif value="$rhOrder.id == 'DockAndWait' and $rhOrder.$callerid? and (@$rhOrder.$callerid.id == 'DockAndReturnHome' or @$rhOrder.$callerid.id == 'GTIdlePark')">
            <set_value name="$isGTNavHandoff" exact="true"/>
            <break/>
          </do_elseif>
        </do_all>
      </do_if>
      <do_if value="$isGTNavHandoff">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Assist on_abort ignored during GT navigation handoff'" chance="100"/>
        </do_if>
        <return/>
      </do_if>

      <!-- PERFORMANCE FIX: Early exit check BEFORE any logging or property lookups -->
      <!-- If ship is not GT-controlled, exit immediately to prevent stutter -->
      <set_value name="$isGTControlled" exact="false"/>
      
      <!-- Quick check: Is ship in GT_Ships registry? -->
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?">
        <set_value name="$isGTControlled" exact="true"/>
      </do_if>
      
      <!-- Fallback check: Is ship tracked as subordinate to GT commander? -->
      <do_if value="not $isGTControlled and global.$GT_Ship_State? and global.$GT_Ship_State.{this.assignedcontrolled}?">
        <set_value name="$state" exact="global.$GT_Ship_State.{this.assignedcontrolled}"/>
        <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
          <do_if value="$state.$CommanderHasGT? and $state.$CommanderHasGT">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Extra detach-race fallback:
           pilot registry can still be linked to the ship after GT_Ships/state already flipped. -->
      <do_if value="not $isGTControlled and this.assignedcontrolled.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.assignedcontrolled.pilot}? and global.$GT_Pilots.{this.assignedcontrolled.pilot}.$OriginalShipName?">
        <set_value name="$pilotData" exact="global.$GT_Pilots.{this.assignedcontrolled.pilot}"/>
        <do_if value="($pilotData.$Ship? and $pilotData.$Ship == this.assignedcontrolled) or ($pilotData.$AssociatedShip? and $pilotData.$AssociatedShip == this.assignedcontrolled) or ($pilotData.$ShipID? and $pilotData.$ShipID == this.assignedcontrolled.idcode)">
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- EARLY EXIT: If ship is not GT-controlled, exit immediately without any processing -->
      <do_if value="not $isGTControlled">
        <!-- Ship is not GT-controlled - no cleanup needed, exit silently -->
        <!-- This prevents stutter from constant property lookups for non-GT ships -->
        <return/>
      </do_if>
      
      <!-- Ship IS GT-controlled - proceed with cleanup logic -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Assist order aborted - checking if GT cleanup needed'" chance="100"/>
      </do_if>
      
      <!-- Check if ship was GT-controlled (is in GT_Ships registry) -->
      <!-- ALL ships with GT orders are in global.$GT_Ships, regardless of modifications -->
      <set_value name="$needsCleanup" exact="false"/>
      <set_value name="$wasGTControlled" exact="false"/>
      
      <!-- Initialize state registry reference for debug logging -->
      <set_value name="$state" exact="null"/>
      <do_if value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.assignedcontrolled}?">
        <set_value name="$state" exact="global.$GT_Ship_State.{this.assignedcontrolled}"/>
      </do_if>
      
      <!-- Self-heal stale registry entries:
           A ship can be left in GT_Ships after cleanup while already marked orphaned.
           In that case, suppress repeated Assist-abort verification loops. -->
      <set_value name="$hasDirectGTOrderNow" exact="false"/>
      <do_if value="this.assignedcontrolled.defaultorder? and (@this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.defaultorder.id == 'GalaxyMiner')">
        <set_value name="$hasDirectGTOrderNow" exact="true"/>
      </do_if>
      <set_value name="$hasGTCommanderNow" exact="false"/>
      <do_if value="this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists and this.assignedcontrolled.commander != this.assignedcontrolled">
        <do_if value="this.assignedcontrolled.commander.defaultorder? and ((@this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyExplorer') or (@this.assignedcontrolled.commander.defaultorder.id == 'Assist' and this.assignedcontrolled.commander.defaultorder.$baseorder? and (@this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyExplorer')))">
          <set_value name="$hasGTCommanderNow" exact="true"/>
        </do_if>
      </do_if>
      <set_value name="$stateMarkedOrphaned" exact="false"/>
      <do_if value="$state? and $state.$SubordinateState? and $state.$SubordinateState == 'orphaned'">
        <set_value name="$stateMarkedOrphaned" exact="true"/>
      </do_if>
      <do_if value="$isGTControlled and $stateMarkedOrphaned and not $hasDirectGTOrderNow and not $hasGTCommanderNow">
        <remove_value name="global.$GT_Ships.{this.assignedcontrolled}"/>
        <set_value name="$isGTControlled" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Removed stale GT_Ships registry entry (orphaned state, no GT control)'" chance="100"/>
        </do_if>
        <return/>
      </do_if>
      
      <!-- PRIMARY CHECK: Ship is in GT_Ships registry (indicates it was GT-controlled) -->
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?">
        <set_value name="$wasGTControlled" exact="true"/>
        <set_value name="$needsCleanup" exact="true"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Ship is in GT_Ships registry - was GT-controlled'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- FALLBACK: Check state registry (if ship was tracked as subordinate) -->
      <do_if value="not $wasGTControlled and $state?">
        <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
          <do_if value="$state.$CommanderHasGT? and $state.$CommanderHasGT">
            <set_value name="$wasGTControlled" exact="true"/>
            <set_value name="$needsCleanup" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Ship was tracked as subordinate to GT commander - needs cleanup'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
      
      <do_if value="not $wasGTControlled and this.assignedcontrolled.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.assignedcontrolled.pilot}? and global.$GT_Pilots.{this.assignedcontrolled.pilot}.$OriginalShipName?">
        <set_value name="$pilotData" exact="global.$GT_Pilots.{this.assignedcontrolled.pilot}"/>
        <do_if value="($pilotData.$Ship? and $pilotData.$Ship == this.assignedcontrolled) or ($pilotData.$AssociatedShip? and $pilotData.$AssociatedShip == this.assignedcontrolled) or ($pilotData.$ShipID? and $pilotData.$ShipID == this.assignedcontrolled.idcode)">
          <set_value name="$wasGTControlled" exact="true"/>
          <set_value name="$needsCleanup" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - pilot registry still linked during Assist abort - needs cleanup'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- If cleanup needed, trust the removal signal -->
      <!-- CRITICAL: Assist order aborting means subordinate was removed -->
      <!-- COMPREHENSIVE DEBUG LOGGING: Ship state and orders at removal detection -->
      <do_if value="$needsCleanup and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$debugShip" exact="this.assignedcontrolled"/>
        <set_value name="$debugDefaultOrder" exact="@$debugShip.defaultorder.id"/>
        <set_value name="$debugCommander" exact="@$debugShip.commander"/>
        <set_value name="$debugCommanderId" exact="if @$debugCommander.exists then @$debugCommander.idcode else 'NONE'"/>
        <set_value name="$debugCommanderOrder" exact="if @$debugCommander.exists and @$debugCommander.defaultorder != null then @$debugCommander.defaultorder.id else 'NONE'"/>
        <set_value name="$debugPilot" exact="@$debugShip.pilot"/>
        <set_value name="$debugPilotName" exact="if $debugPilot != null then @$debugPilot.knownname else 'NONE'"/>
        
        <!-- Build orders list -->
        <set_value name="$debugOrdersList" exact="[]"/>
        <set_value name="$debugOrdersCount" exact="$debugShip.orders.count"/>
        <do_all exact="$debugOrdersCount" counter="$i">
          <set_value name="$orderId" exact="@$debugShip.orders.{$i}.id"/>
          <append_to_list name="$debugOrdersList" exact="if $orderId then $orderId else 'UNKNOWN'"/>
        </do_all>
        <set_value name="$debugOrdersStr" exact="if $debugOrdersList.count gt 0 then $debugOrdersList.{1} + (if $debugOrdersList.count gt 1 then ', ' + $debugOrdersList.{2} else '') + (if $debugOrdersList.count gt 2 then ', ' + $debugOrdersList.{3} else '') + (if $debugOrdersList.count gt 3 then ', ' + $debugOrdersList.{4} else '') + (if $debugOrdersList.count gt 4 then ', ...' else '') else 'NONE'"/>
        
        <!-- Check GT order status -->
        <set_value name="$debugHasDirectGT" exact="false"/>
        <do_if value="$debugDefaultOrder == 'GalaxyTraderMK4Supply' or $debugDefaultOrder == 'GalaxyTraderMK4Supply2' or $debugDefaultOrder == 'GalaxyTraderMK3' or $debugDefaultOrder == 'GalaxyTraderMK2' or $debugDefaultOrder == 'GalaxyTraderMK1' or $debugDefaultOrder == 'GalaxyMiner' or $debugDefaultOrder == 'GalaxyExplorer'">
          <set_value name="$debugHasDirectGT" exact="true"/>
        </do_if>
        <set_value name="$debugHasGTCommander" exact="false"/>
        <do_if value="@$debugCommander.exists and ($debugCommanderOrder == 'GalaxyTraderMK4Supply' or $debugCommanderOrder == 'GalaxyTraderMK4Supply2' or $debugCommanderOrder == 'GalaxyTraderMK3' or $debugCommanderOrder == 'GalaxyTraderMK2' or $debugCommanderOrder == 'GalaxyTraderMK1' or $debugCommanderOrder == 'GalaxyMiner' or $debugCommanderOrder == 'GalaxyExplorer')">
          <set_value name="$debugHasGTCommander" exact="true"/>
        </do_if>
        
        <!-- Check if in GT_Ships registry -->
        <set_value name="$debugInRegistry" exact="global.$GT_Ships? and global.$GT_Ships.{$debugShip}?"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist] REMOVAL DETECTION DEBUG: ' + $debugShip.idcode + ' - COMPREHENSIVE STATE'" chance="100"/>
          <debug_text text="'[GT-Assist]   Ship: ' + $debugShip.idcode + ' (' + (if $debugShip.knownname then $debugShip.knownname else 'UNNAMED') + ')'" chance="100"/>
          <debug_text text="'[GT-Assist]   Pilot: ' + $debugPilotName + (if $debugPilot? then ' (exists)' else ' (NONE)')" chance="100"/>
          <debug_text text="'[GT-Assist]   Default Order: ' + (if $debugDefaultOrder then $debugDefaultOrder else 'NONE')" chance="100"/>
          <debug_text text="'[GT-Assist]   Active Orders (' + $debugOrdersCount + '): ' + $debugOrdersStr" chance="100"/>
          <debug_text text="'[GT-Assist]   Commander: ' + $debugCommanderId + ' (Order: ' + $debugCommanderOrder + ')'" chance="100"/>
          <debug_text text="'[GT-Assist]   GT Status: Direct=' + $debugHasDirectGT + ', ViaCommander=' + $debugHasGTCommander + ', InRegistry=' + $debugInRegistry" chance="100"/>
          <set_value name="$debugSubordinateState" exact="'NONE'"/>
          <set_value name="$debugCommanderHasGT" exact="'NONE'"/>
          <do_if value="$state?">
            <set_value name="$debugSubordinateState" exact="if $state.$SubordinateState? then $state.$SubordinateState else 'NONE'"/>
            <set_value name="$debugCommanderHasGT" exact="if $state.$CommanderHasGT? then $state.$CommanderHasGT else 'NONE'"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist]   State: SubordinateState=' + $debugSubordinateState + ', CommanderHasGT=' + $debugCommanderHasGT" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- During abort window, ship.commander may still point to old commander (race condition) -->
      <!-- Solution: Snapshot commander before abort, then emit cleanup unconditionally if it was GT-controlled -->
      <do_if value="$needsCleanup">
        <!-- Snapshot commander BEFORE checking (captures state before abort clears it) -->
        <set_value name="$oldCommander" exact="@this.assignedcontrolled.commander"/>
        <set_value name="$oldCommanderHadGT" exact="false"/>
        <do_if value="@$oldCommander.exists and $oldCommander != this.assignedcontrolled">
          <do_if value="$oldCommander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$oldCommander.defaultorder.id}">
            <set_value name="$oldCommanderHadGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if ship was subordinate to GT commander (before abort) -->
        <set_value name="$wasSubordinateToGT" exact="false"/>
        <do_if value="$oldCommanderHadGT">
          <set_value name="$wasSubordinateToGT" exact="true"/>
        </do_if>
        <do_elseif value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
          <do_if value="$state.$CommanderHasGT? and $state.$CommanderHasGT">
            <set_value name="$wasSubordinateToGT" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship has direct GT order (not via commander) -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <do_if value="this.assignedcontrolled.defaultorder? and (@this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.defaultorder.id == 'GalaxyMiner')">
          <set_value name="$hasDirectGTOrder" exact="true"/>
        </do_if>
        
        <!-- Check if reassigned to NEW GT commander OR newly assigned to GT commander (protect against immediate reassignment/new assignment) -->
        <set_value name="$reassignedToGTCommander" exact="false"/>
        <set_value name="$newlyAssignedToGTCommander" exact="false"/>
        <do_if value="this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists and this.assignedcontrolled.commander != this.assignedcontrolled">
          <!-- Check if this is a new assignment (ship had no commander before) -->
          <do_if value="not @$oldCommander.exists or $oldCommander == null">
            <!-- Ship had no commander before - this is a NEW assignment -->
            <do_if value="this.assignedcontrolled.commander.defaultorder? and ((@this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyExplorer') or (@this.assignedcontrolled.commander.defaultorder.id == 'Assist' and this.assignedcontrolled.commander.defaultorder.$baseorder? and (@this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyExplorer')))">
              <set_value name="$newlyAssignedToGTCommander" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - NEWLY ASSIGNED to GT commander ' + this.assignedcontrolled.commander.idcode + ' - skipping cleanup (Assist order will restart)'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          <do_elseif value="this.assignedcontrolled.commander != $oldCommander">
            <!-- Commander changed from one to another - check if new commander has GT order -->
            <do_if value="this.assignedcontrolled.commander.defaultorder? and ((@this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.id == 'GalaxyExplorer') or (@this.assignedcontrolled.commander.defaultorder.id == 'Assist' and this.assignedcontrolled.commander.defaultorder.$baseorder? and (@this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK2' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK1' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyMiner' or @this.assignedcontrolled.commander.defaultorder.$baseorder.id == 'GalaxyExplorer')))">
              <set_value name="$reassignedToGTCommander" exact="true"/>
            </do_if>
          </do_elseif>
        </do_if>
        
        <!-- CRITICAL FIX: Check if ship is STILL subordinate to SAME GT commander -->
        <!-- Assist order can restart (e.g., commander order change) without subordinate being removed -->
        <!-- Key insight: If default order is still "Assist" AND commander is SAME AND commander still has GT, ship is still subordinate -->
        <!-- If commander changed OR commander lost GT order OR default order changed, subordinate relationship ended -->
        <set_value name="$currentDefaultOrder" exact="@this.assignedcontrolled.defaultorder.id"/>
        <set_value name="$currentCommander" exact="null"/>
        <set_value name="$stillHasGTCommander" exact="false"/>
        <set_value name="$isStillSubordinate" exact="false"/>
        
        <!-- Get current commander -->
        <do_if value="this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists and this.assignedcontrolled.commander != this.assignedcontrolled">
          <set_value name="$currentCommander" exact="this.assignedcontrolled.commander"/>
        </do_if>
        
        <!-- Check if ship is still a subordinate to SAME GT commander -->
        <!-- CRITICAL: Must check if commander is SAME (not just if commander exists) -->
        <do_if value="$currentDefaultOrder == 'Assist' and $currentCommander? and $currentCommander == $oldCommander">
          <set_value name="$isStillSubordinate" exact="true"/>
          <!-- If still subordinate to SAME commander, check if commander still has GT order -->
          <do_if value="$currentCommander.defaultorder? and ((@$currentCommander.defaultorder.id == 'GalaxyTraderMK4Supply' or @$currentCommander.defaultorder.id == 'GalaxyTraderMK4Supply2' or @$currentCommander.defaultorder.id == 'GalaxyTraderMK3' or @$currentCommander.defaultorder.id == 'GalaxyTraderMK2' or @$currentCommander.defaultorder.id == 'GalaxyTraderMK1' or @$currentCommander.defaultorder.id == 'GalaxyMiner' or @$currentCommander.defaultorder.id == 'GalaxyExplorer') or (@$currentCommander.defaultorder.id == 'Assist' and $currentCommander.defaultorder.$baseorder? and (@$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK2' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK1' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyMiner' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyExplorer')))">
            <set_value name="$stillHasGTCommander" exact="true"/>
          </do_if>
        </do_if>

        <!-- Promotion handoff guard:
             old commander had GT and subordinate is still on Assist, but commander link is temporarily missing.
             This can happen during commander destruction + subordinate promotion and must be verified before cleanup. -->
        <set_value name="$promotionTransitionLikely" exact="false"/>
        <do_if value="$currentDefaultOrder == 'Assist' and (not $currentCommander? or not $currentCommander.exists) and $oldCommanderHadGT">
          <set_value name="$promotionTransitionLikely" exact="true"/>
        </do_if>

        <!-- Trust the removal signal: If Assist order is aborting and ship was subordinate to GT commander, emit cleanup -->
        <!-- Only suppress if ship is STILL subordinate to SAME GT commander OR was reassigned/newly assigned to another GT commander -->
        <!-- CRITICAL: If commander changed OR commander lost GT order OR default order changed, subordinate was removed -->
        <!-- EXCEPTION: Newly assigned ships (had no commander, now have GT commander) should skip cleanup - Assist order will restart -->
        <do_if value="$wasSubordinateToGT and not $reassignedToGTCommander and not $newlyAssignedToGTCommander and not ($isStillSubordinate and $stillHasGTCommander) and not $promotionTransitionLikely">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Assist order aborted (subordinate removed from GT commander) - triggering cleanup unconditionally'" chance="100"/>
          </do_if>
          
          <!-- Initialize state if missing -->
          <do_if value="not global.$GT_Ship_State?">
            <set_value name="global.$GT_Ship_State" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ship_State.{this.assignedcontrolled}?">
            <set_value name="global.$GT_Ship_State.{this.assignedcontrolled}" exact="table[
              $OperationalState = 'orphaned',
              $SubordinateState = 'orphaned',
              $Commander = null,
              $CommanderHasGT = false,
              $HasGTOrder = false,
              $HasAssistOrder = false,
              $ActiveTradeOrders = 0,
              $LastStateUpdate = player.age
            ]"/>
          </do_if>
          
          <set_value name="$state" exact="global.$GT_Ship_State.{this.assignedcontrolled}"/>
          
          <!-- Update state -->
          <set_value name="$state.$HasGTOrder" exact="false"/>
          <set_value name="$state.$OperationalState" exact="'orphaned'"/>
          <set_value name="$state.$ActiveTradeOrders" exact="0"/>
          <set_value name="$state.$Commander" exact="null"/>
          <set_value name="$state.$CommanderHasGT" exact="false"/>
          <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
          <set_value name="$state.$LastStateUpdate" exact="player.age"/>
          
          <!-- Send cleanup signals -->
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.assignedcontrolled,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
          
          <!-- EVENT-DRIVEN: Trigger orphaned ship check for subordinate -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?">
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.assignedcontrolled]"/>
          </do_if>
          
          <set_value name="$pilot" exact="@this.assignedcontrolled.pilot"/>
          <set_value name="$originalName" exact="null"/>
          <do_if value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
          </do_if>
          <do_elseif value="$state.$OriginalShipName?">
            <set_value name="$originalName" exact="$state.$OriginalShipName"/>
          </do_elseif>
          <do_else>
            <set_value name="$originalName" exact="@this.assignedcontrolled.macro.name"/>
          </do_else>
          
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.assignedcontrolled,
            $Pilot = $pilot,
            $Reason = 'Assist order aborted - GT order lost - restoring original name',
            $OriginalName = $originalName
          ]"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Cleanup signals sent (on_abort handler)'" chance="100"/>
          </do_if>
        </do_if>
        <do_elseif value="$promotionTransitionLikely">
          <set_value name="$cleanupTraceId" exact="this.assignedcontrolled.idcode + '|ASSIST_ABORT_PROMOTION_WINDOW|' + (player.age / 1s)i"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Assist abort in promotion handoff window (Assist + no commander). Deferring orphan cleanup verification.'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
            $Ship = this.assignedcontrolled,
            $Source = 'ASSIST_ABORT_PROMOTION_WINDOW',
            $TraceId = $cleanupTraceId
          ]"/>
        </do_elseif>
        <do_elseif value="$hasDirectGTOrder">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Ship has direct GT order - no cleanup needed'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$reassignedToGTCommander">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Ship reassigned to new GT commander - no cleanup needed'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$isStillSubordinate and $stillHasGTCommander">
          <!-- NORMAL RESTART: Default order is still "Assist" and commander still has GT order -->
          <!-- This is a normal Assist order restart - ship is still a valid subordinate -->
          <!-- FALLBACK: Schedule delayed verification as safety net if DetectSubordinateRemoval didn't fire -->
          <!-- If ship was actually removed, state might be stale - delayed verification will catch it -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Default order still Assist, commander still has GT - normal restart (scheduling delayed verification as fallback)'" chance="100"/>
          </do_if>
          
          <!-- Only schedule if ship was GT-controlled (fallback for when DetectSubordinateRemoval doesn't fire) -->
          <do_if value="$wasGTControlled and $oldCommanderHadGT">
            <set_value name="$cleanupTraceId" exact="this.assignedcontrolled.idcode + '|ASSIST_ABORT_FALLBACK|' + (player.age / 1s)i"/>
            <set_value name="$subDefaultOrder" exact="'NONE'"/>
            <do_if value="this.assignedcontrolled.defaultorder?">
              <set_value name="$subDefaultOrder" exact="@this.assignedcontrolled.defaultorder.id"/>
            </do_if>
            <!-- Create the same bounded detach-intent window used by explicit subordinate-removal detection.
                 This prevents delayed verification from trusting a stale commander link immediately after remove assignment. -->
            <do_if value="not global.$GT_CleanupIntent?">
              <set_value name="global.$GT_CleanupIntent" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_CleanupIntent.{this.assignedcontrolled}" exact="table[
              $Active = true,
              $StartTime = player.age,
              $ExpireTime = player.age + 8s,
              $Source = 'ASSIST_ABORT_FALLBACK',
              $TraceId = $cleanupTraceId,
              $DefaultOrderAtSignal = $subDefaultOrder,
              $CommanderAtSignal = if @$oldCommander.exists then @$oldCommander.idcode else 'NONE'
            ]"/>
            
            <!-- Initialize delayed verification registry if needed -->
            <do_if value="not global.$GT_DelayedVerification?">
              <set_value name="global.$GT_DelayedVerification" exact="table[]"/>
            </do_if>
            
            <!-- Signal MD system to perform delayed verification -->
            <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
              $Ship = this.assignedcontrolled,
              $CheckTime = player.age,
              $Source = 'ASSIST_ABORT_FALLBACK',
              $TraceId = $cleanupTraceId
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Scheduled delayed verification with detach intent fallback (DetectSubordinateRemoval may not have fired)'" chance="100"/>
            </do_if>
          </do_if>
        </do_elseif>
        <do_elseif value="$isStillSubordinate and not $stillHasGTCommander">
          <!-- DELAYED VERIFICATION: Default order is still "Assist" but commander no longer has GT order -->
          <!-- State might not have updated immediately - schedule delayed verification -->
          <!-- This catches cases where "remove all commands and orders" is used but default order hasn't changed yet -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Default order still Assist but commander lost GT order - scheduling delayed verification (5s)'" chance="100"/>
          </do_if>
          
          <!-- Initialize delayed verification registry if needed -->
          <do_if value="not global.$GT_DelayedVerification?">
            <set_value name="global.$GT_DelayedVerification" exact="table[]"/>
          </do_if>
          
          <!-- Schedule delayed verification (5 seconds) -->
          <set_value name="global.$GT_DelayedVerification.{this.assignedcontrolled}" exact="player.age + 5s"/>
          
          <!-- Signal MD system to perform delayed verification -->
          <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
            $Ship = this.assignedcontrolled,
            $CheckTime = player.age + 5s
          ]"/>
        </do_elseif>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Assist] ' + this.assignedcontrolled.idcode + ' - Ship not subordinate to GT commander (default order: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ') - no cleanup needed'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
    </on_abort>
  </add>

  <!-- GT FLEET PRESERVATION: vanilla cancels the subordinate's Assist default order when
       the commander has no orders at all (no defaultorder, no active orders). When a player
       strips orders + assignments from a GT commander, this vanilla path detaches every
       subordinate that wasn't actively running an inherited child order (typical for ships
       in scout / searching-resources / standing-by states). The user expects the fleet
       hierarchy to stay intact across player intervention.
       Strategy: for player-owned subordinates that were GT-controlled and whose commander
       is still a player ship, suppress the cancel and wait. Vanilla's interrupt handlers
       (event_object_order_ready, event_object_commander_set, event_object_destroyed,
       event_object_abandoned) will resume init when the commander gets a new order or
       goes away, so this is safe and self-recovering. -->
  <replace sel='//aiscript[@name="order.assist"]/attention/actions/do_if[@value="not this.assignedcontrolled.commander.defaultorder and not this.assignedcontrolled.commander.orders.count"]'>
    <do_if value="not this.assignedcontrolled.commander.defaultorder and not this.assignedcontrolled.commander.orders.count">
      <set_value name="$gtFleetPreserve" exact="false"/>
      <do_if value="this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists and this.assignedcontrolled.commander.isclass.ship and this.assignedcontrolled.commander.owner == faction.player">
        <do_if value="(global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?) or (global.$GT_Ship_State? and global.$GT_Ship_State.{this.assignedcontrolled}? and @global.$GT_Ship_State.{this.assignedcontrolled}.$HasGTOrder)">
          <set_value name="$gtFleetPreserve" exact="true"/>
        </do_if>
      </do_if>
      <do_if value="$gtFleetPreserve">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Assist-FLEET-PRESERVE] ' + this.assignedcontrolled.idcode + ' - subordinate kept attached to commander ' + this.assignedcontrolled.commander.idcode + ' while commander has no orders (player likely stripped commander orders); waiting for new commander order before re-inheriting.'" chance="100"/>
        </do_if>
        <wait min="10s" max="20s"/>
        <resume label="init"/>
      </do_if>
      <do_else>
        <debug_text text="'commander: %s %s %s %s does not use orders.'.[this.assignedcontrolled.commander.class, this.assignedcontrolled.commander.idcode, this.assignedcontrolled.commander.knownname, this.assignedcontrolled.commander]" filter="error"/>
        <do_if value="@this.assignedcontrolled.defaultorder.id == 'Assist'">
          <cancel_order order="this.assignedcontrolled.defaultorder"/>
          <set_value name="$removeassignment"/>
        </do_if>
        <resume label="finish"/>
      </do_else>
    </do_if>
  </replace>

  <!-- Do not restart mimic run_script while GT navigation handoff orders are active.
       Commander default-order syncpoints otherwise abort subordinate traders mid-idle-park. -->
  <replace sel="//aiscript[@name='order.assist']/interrupts/handler[@comment='redirect to init.']/actions">
    <set_value name="$isGTNavHandoff" exact="false"/>
    <do_if value="this.assignedcontrolled.order? and (@this.assignedcontrolled.order.id == 'DockAndReturnHome' or @this.assignedcontrolled.order.id == 'GTIdlePark')">
      <set_value name="$isGTNavHandoff" exact="true"/>
    </do_if>
    <do_elseif value="this.assignedcontrolled.order? and @this.assignedcontrolled.order.id == 'DockAndWait' and this.assignedcontrolled.order.$callerid? and (@this.assignedcontrolled.order.$callerid.id == 'DockAndReturnHome' or @this.assignedcontrolled.order.$callerid.id == 'GTIdlePark')">
      <set_value name="$isGTNavHandoff" exact="true"/>
    </do_elseif>
    <do_if value="not $isGTNavHandoff and this.assignedcontrolled.orders.count gt 0">
      <do_all exact="this.assignedcontrolled.orders.count" counter="$gnhi">
        <set_value name="$gnhOrder" exact="this.assignedcontrolled.orders.{$gnhi}"/>
        <do_if value="$gnhOrder.id == 'DockAndReturnHome' or $gnhOrder.id == 'GTIdlePark'">
          <set_value name="$isGTNavHandoff" exact="true"/>
          <break/>
        </do_if>
        <do_elseif value="$gnhOrder.id == 'DockAndWait' and $gnhOrder.$callerid? and (@$gnhOrder.$callerid.id == 'DockAndReturnHome' or @$gnhOrder.$callerid.id == 'GTIdlePark')">
          <set_value name="$isGTNavHandoff" exact="true"/>
          <break/>
        </do_elseif>
      </do_all>
    </do_if>
    <do_if value="$isGTNavHandoff">
      <debug_text text="'conditions changed during GT navigation handoff (event: %s). ignoring Assist restart.'.[event.name]" chance="$debugchance"/>
    </do_if>
    <do_else>
      <debug_text text="'conditions changed. event: %s. restarting.'.[event.name]" chance="$debugchance"/>
      <abort_called_scripts resume="init"/>
    </do_else>
  </replace>
</diff> <?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Build.Equip completion signalling patch -->
  <!-- This patch adds completion signalling to notify the GT system when build.equip (resupply) is complete -->
  
  <!-- ========================================================================= -->
  <!-- START SIGNALING: Trigger ship name update when Equip starts (subordinates) -->
  <!-- ========================================================================= -->
  <!-- Subordinates can be in Equip without GT_ResupplyOrders tracking; UpdateShipName can derive [RESUPPLY]/[MAINTENANCE]
       from active order id (Equip/Resupply/Repair) + GT relationship checks. We just need to trigger the rename. -->
  <add sel="//aiscript[@name='order.build.equip']/attention[@min='unknown']/actions/label[@name='init']" pos="after">
    <set_value name="$gtRelated" exact="false"/>
    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
      <set_value name="$gtRelated" exact="true"/>
    </do_if>
    <do_elseif value="this.ship.commander? and this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
      <set_value name="$gtRelated" exact="true"/>
    </do_elseif>
    
    <do_if value="$gtRelated">
      <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
        $Ship = this.ship,
        $pilot = @this.ship.pilot,
        $nameType = 'trader'
      ]"/>
    </do_if>
  </add>
  
  <!-- ========================================================================= -->
  <!-- COMPLETION SIGNALING: Notify GT system when Build.Equip completes       -->
  <!-- ========================================================================= -->
  <add sel="//aiscript[@name='order.build.equip']/attention[@min='unknown']/actions/label[@name='finish']" pos="before">
    <!-- Signal completion to GalaxyTrader system if this is a GT ship -->
    <do_if value="this.ship.pilot and this.ship.isplayerowned and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-BuildEquip] Build.Equip (Resupply) complete for ' + this.ship.idcode" chance="100"/>
      </do_if>
      
      <!-- LOGGING: Show what was actually restocked when order finishes -->
      <set_value name="$resupplyOrder" exact="@global.$GT_ResupplyOrders.{this.ship}"/>
      <do_if value="$resupplyOrder?">
        <!-- Get "before" values from resupply order tracking -->
        <!-- FIX: Initialize to 0 if null (defensive check) -->
        <set_value name="$beforeCM" exact="@$resupplyOrder.$CountermeasuresBefore"/>
        <set_value name="$beforeCM" exact="if $beforeCM? then $beforeCM else 0"/>
        <set_value name="$beforeUnits" exact="@$resupplyOrder.$UnitsBefore"/>
        <set_value name="$beforeUnits" exact="if $beforeUnits? then $beforeUnits else 0"/>
        <set_value name="$beforeDefenseDrones" exact="@$resupplyOrder.$DefenseDronesBefore"/>
        <set_value name="$beforeDefenseDrones" exact="if $beforeDefenseDrones? then $beforeDefenseDrones else 0"/>
        <set_value name="$beforeCargoDrones" exact="@$resupplyOrder.$CargoDronesBefore"/>
        <set_value name="$beforeCargoDrones" exact="if $beforeCargoDrones? then $beforeCargoDrones else 0"/>
        <set_value name="$beforeLaserTowers" exact="@$resupplyOrder.$LaserTowersBefore"/>
        <set_value name="$beforeLaserTowers" exact="if $beforeLaserTowers? then $beforeLaserTowers else 0"/>
        <set_value name="$beforeRepairDrones" exact="@$resupplyOrder.$RepairDronesBefore"/>
        <set_value name="$beforeRepairDrones" exact="if $beforeRepairDrones? then $beforeRepairDrones else 0"/>
        
        <!-- Get current values -->
        <set_value name="$currentCM" exact="this.ship.ammostorage.countermeasure.count"/>
        <set_value name="$currentUnits" exact="this.ship.units.count"/>
        <set_value name="$currentDefenseDrones" exact="this.ship.units.{macro.ship_gen_s_fightingdrone_01_a_macro}.count"/>
        <set_value name="$currentCargoDrones" exact="this.ship.units.{macro.ship_gen_xs_cargodrone_empty_01_a_macro}.count"/>
        <do_if value="this.ship.units.maxcount == 0">
          <set_value name="$currentLaserTowers" exact="this.ship.ammostorage.{deployablecategory.lasertower}.count"/>
        </do_if>
        <do_else>
          <set_value name="$currentLaserTowers" exact="this.ship.units.{macro.ship_gen_xs_lasertower_01_a_macro}.count"/>
        </do_else>
        <set_value name="$currentRepairDrones" exact="this.ship.units.{macro.ship_gen_xs_repairdrone_01_a_macro}.count"/>
        
        <!-- DEBUG: Log before values to see what we're reading -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-BuildEquip] Reading resupply order tracking for ' + this.ship.idcode + ': BeforeCM=' + $beforeCM + ', BeforeUnits=' + $beforeUnits" chance="100"/>
        </do_if>
        
        <!-- Calculate what was gained -->
        <set_value name="$cmGained" exact="$currentCM - $beforeCM"/>
        <set_value name="$defenseGained" exact="$currentDefenseDrones - $beforeDefenseDrones"/>
        <set_value name="$cargoGained" exact="$currentCargoDrones - $beforeCargoDrones"/>
        <set_value name="$towersGained" exact="$currentLaserTowers - $beforeLaserTowers"/>
        <set_value name="$repairGained" exact="$currentRepairDrones - $beforeRepairDrones"/>
        <set_value name="$unitsGained" exact="$currentUnits - $beforeUnits"/>
        
        <!-- Build summary of what was restocked -->
        <set_value name="$restockedItems" exact="[]"/>
        <do_if value="$cmGained gt 0">
          <append_to_list name="$restockedItems" exact="'CM +' + $cmGained"/>
        </do_if>
        <do_if value="$defenseGained gt 0">
          <append_to_list name="$restockedItems" exact="'Defense Drones +' + $defenseGained"/>
        </do_if>
        <do_if value="$cargoGained gt 0">
          <append_to_list name="$restockedItems" exact="'Cargo Drones +' + $cargoGained"/>
        </do_if>
        <do_if value="$towersGained gt 0">
          <append_to_list name="$restockedItems" exact="'Laser Towers +' + $towersGained"/>
        </do_if>
        <do_if value="$repairGained gt 0">
          <append_to_list name="$restockedItems" exact="'Repair Drones +' + $repairGained"/>
        </do_if>
        
        <set_value name="$restockedSummary" exact="if $restockedItems.count gt 0 then $restockedItems.{1} + (if $restockedItems.count gt 1 then ', ' + $restockedItems.{2} else '') + (if $restockedItems.count gt 2 then ', ' + $restockedItems.{3} else '') + (if $restockedItems.count gt 3 then ', ' + $restockedItems.{4} else '') + (if $restockedItems.count gt 4 then ', ' + $restockedItems.{5} else '') else 'NOTHING'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-BuildEquip] RESTOCKED for ' + this.ship.idcode + ': ' + $restockedSummary" chance="100"/>
          <debug_text text="'[GT-BuildEquip] DETAILED RESTOCK for ' + this.ship.idcode + ':'" chance="100"/>
          <debug_text text="'[GT-BuildEquip]   Countermeasures: ' + $beforeCM + ' ' + $currentCM + ' (gained: ' + $cmGained + ')'" chance="100"/>
          <debug_text text="'[GT-BuildEquip]   Defense Drones: ' + $beforeDefenseDrones + ' ' + $currentDefenseDrones + ' (gained: ' + $defenseGained + ')'" chance="100"/>
          <debug_text text="'[GT-BuildEquip]   Cargo Drones: ' + $beforeCargoDrones + ' ' + $currentCargoDrones + ' (gained: ' + $cargoGained + ')'" chance="100"/>
          <debug_text text="'[GT-BuildEquip]   Laser Towers: ' + $beforeLaserTowers + ' ' + $currentLaserTowers + ' (gained: ' + $towersGained + ')'" chance="100"/>
          <debug_text text="'[GT-BuildEquip]   Repair Drones: ' + $beforeRepairDrones + ' ' + $currentRepairDrones + ' (gained: ' + $repairGained + ')'" chance="100"/>
          <debug_text text="'[GT-BuildEquip]   Total Units: ' + $beforeUnits + ' ' + $currentUnits + ' (gained: ' + $unitsGained + ')'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Queue completion notification -->
      <do_if value="not global.$GT_ResupplyCompleteQueue?">
        <set_value name="global.$GT_ResupplyCompleteQueue" exact="[]"/>
      </do_if>
      
      <append_to_list name="global.$GT_ResupplyCompleteQueue" exact="table[
        $ship = this.ship,
        $time = player.age
      ]"/>
      
      <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
      <signal_objects object="player.galaxy" param="'GT_ResupplyComplete'"/>
    </do_if>
  </add>
  
</diff>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.dock.pilotexchange" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <order id="DockAndPilotExchange" name="{77000, 10004}" description="{77000, 10104}" category="navigation" infinite="false">
    <params>
      <param name="destination" type="object" text="{1041, 10141}" comment="Rendezvous station for pilot exchange">
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="partner" type="object" default="null" text="{1001, 1612}" comment="Other ship in the pilot exchange pair">
        <input_param name="class" value="[class.ship]"/>
      </param>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
    <location object="$destination" condition="@$destination.exists"/>
  </order>

  <interrupts>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="AttackHandler"/>
  </interrupts>

  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_command command="command.dockat" param="$destination"/>
    <set_command_action commandaction="commandaction.waitingtodock" param="$destination"/>
    <debug_text text="'[GT PilotExchange] init ship=' + this.ship.idcode + ' destination=' + (if $destination? then $destination.idcode else 'NONE') + ' partner=' + (if $partner? then $partner.idcode else 'NONE')" chance="100"/>
    <do_if value="not $destination or not this.ship.pilot">
      <debug_text text="'[GT PilotExchange] init failed ship=' + this.ship.idcode + ' destination=' + (if $destination? then $destination.idcode else 'NONE') + ' hasPilot=' + (if this.ship.pilot? then 'yes' else 'no')" chance="100"/>
      <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
        $Ship = this.ship,
        $ShipID = this.ship.idcode,
        $State = 'failed',
        $StationID = if $destination? then $destination.idcode else ''
      ]"/>
      <set_order_state order="this.ship.order" state="orderstate.critical"/>
      <return/>
    </do_if>
    <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
      $Ship = this.ship,
      $ShipID = this.ship.idcode,
      $State = 'started',
      $StationID = $destination.idcode,
      $PartnerID = if $partner? then $partner.idcode else ''
    ]"/>
  </init>

  <attention min="unknown">
    <actions>
      <set_value name="$holdTime" exact="2h"/>
      <set_value name="$arrived" exact="false"/>

      <do_if value="(this.ship.dock and (this.ship.dock.container == $destination)) or (this.ship.parkedat and ((this.ship.parkedat == $destination) or this.ship.parkedat.hascontext.{$destination}))">
        <debug_text text="'[GT PilotExchange] already docked ship=' + this.ship.idcode + ' station=' + $destination.idcode" chance="100"/>
        <set_command_action commandaction="commandaction.standingby"/>
        <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
          $Ship = this.ship,
          $ShipID = this.ship.idcode,
          $State = 'arrived',
          $StationID = $destination.idcode,
          $PartnerID = if $partner? then $partner.idcode else ''
        ]"/>
        <set_value name="$arrived" exact="true"/>
      </do_if>
      <do_if value="not $arrived">
        <debug_text text="'[GT PilotExchange] create DockAndWait ship=' + this.ship.idcode + ' station=' + $destination.idcode" chance="100"/>
        <set_command_action commandaction="commandaction.waitingtodock" param="$destination"/>
        <create_order name="$dockOrder" id="'DockAndWait'" object="this.ship" immediate="true">
          <param name="destination" value="$destination"/>
          <param name="building" value="false"/>
          <param name="trading" value="false"/>
          <param name="dockfollowers" value="$destination.isclass.station"/>
          <param name="callerid" value="this.ship.order"/>
        </create_order>

        <wait>
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship" order="$dockOrder"/>
            </conditions>
          </interrupt>
        </wait>

        <do_if value="(this.ship.dock and (this.ship.dock.container == $destination)) or (this.ship.parkedat and ((this.ship.parkedat == $destination) or this.ship.parkedat.hascontext.{$destination}))">
          <debug_text text="'[GT PilotExchange] arrived ship=' + this.ship.idcode + ' station=' + $destination.idcode" chance="100"/>
          <set_command_action commandaction="commandaction.standingby"/>
          <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
            $Ship = this.ship,
            $ShipID = this.ship.idcode,
            $State = 'arrived',
            $StationID = $destination.idcode,
            $PartnerID = if $partner? then $partner.idcode else ''
          ]"/>
          <set_value name="$arrived" exact="true"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT PilotExchange] failed to dock ship=' + this.ship.idcode + ' station=' + $destination.idcode" chance="100"/>
          <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
            $Ship = this.ship,
            $ShipID = this.ship.idcode,
            $State = 'failed',
            $StationID = $destination.idcode,
            $PartnerID = if $partner? then $partner.idcode else ''
          ]"/>
          <set_command_action commandaction="commandaction.orderfailed"/>
          <return/>
        </do_else>
      </do_if>

      <!-- Keep ship docked for exchange until explicit release signal.
           Failsafe timeout is aligned with MD swap-tracker timeout. -->
      <wait max="$holdTime">
        <interrupt>
          <conditions>
            <event_object_signalled object="this.ship" param="'GT_PilotExchange_Release'"/>
          </conditions>
        </interrupt>
      </wait>
      <debug_text text="'[GT PilotExchange] release/timeout ship=' + this.ship.idcode + ' station=' + $destination.idcode" chance="100"/>
      <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
        $Ship = this.ship,
        $ShipID = this.ship.idcode,
        $State = 'released',
        $StationID = if $destination? then $destination.idcode else '',
        $PartnerID = if $partner? then $partner.idcode else ''
      ]"/>
    </actions>
  </attention>

  <on_abort>
    <!-- Always emit aborted for this order instance so MD can reliably clear PilotExchange state on cancel. -->
    <signal_objects object="player.galaxy" param="'GT_PilotExchange_OrderState'" param2="table[
      $Ship = this.ship,
      $ShipID = this.ship.idcode,
      $State = 'aborted',
      $StationID = if $destination? then $destination.idcode else '',
      $PartnerID = if $partner? then $partner.idcode else ''
    ]"/>
  </on_abort>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.dock.train" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <order id="DockAndTrain" name="{77000, 10003}" description="{77000, 10103}" category="navigation" infinite="false">
    <params>
      <param name="destination" type="object" text="{1041, 10141}" comment="Training station to dock at">
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="debugchance" default="100" type="number" text="{1041, 10086}" comment="Chance to show debug output">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="10"/>
      </param>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
    <location object="$destination" condition="@$destination.exists"/>
  </order>
  
  <interrupts>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="AttackHandler"/>
  </interrupts>
  
  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    
    <!-- Validate parameters (component.{0x0L} is truthy for "not $destination" - use .exists) -->
    <do_if value="not $destination? or not $destination.exists or not this.ship.pilot">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Training] ' + this.ship.idcode + ': ABORT: Invalid destination or no pilot'" chance="$debugchance"/>
      </do_if>
      <do_if value="this.ship.order.state == orderstate.started">
        <set_order_state order="this.ship.order" state="orderstate.critical"/>
      </do_if>
      <do_if value="this.ship.pilot">
        <signal_objects object="player.galaxy" param="'GT_Abort_Training'" param2="table[
          $Pilot = this.ship.pilot,
          $Ship = this.ship,
          $Reason = 'Invalid destination'
        ]"/>
      </do_if>
      <signal_objects object="this.ship" param="'training_aborted'" param2="'Invalid parameters'"/>
      <cancel_order order="this.ship.order"/>
      <return/>
    </do_if>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Starting training at ' + @$destination.knownname + ' for pilot ' + this.ship.pilot.name" chance="$debugchance"/>
    </do_if>
    
    <!-- Signal MD system that training script is starting -->
    <signal_objects object="player.galaxy" param="'GT_Training_Script_Starting'" param2="table[
      $Ship = this.ship,
      $Pilot = this.ship.pilot,
      $Station = $destination
    ]"/>
    
  </init>
  
  <attention min="unknown">
    <actions>
      
      <!-- ========================================================================= -->
      <!-- HIGH-PERFORMANCE EVENT-DRIVEN TRAINING ORDER (NO POLLING)               -->
      <!-- ========================================================================= -->
      
      <do_if value="not $destination? or not $destination.exists or not this.ship.pilot">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': ABORT: Invalid destination or no pilot (attention)'" chance="$debugchance"/>
        </do_if>
        <do_if value="this.ship.order.state == orderstate.started">
          <set_order_state order="this.ship.order" state="orderstate.critical"/>
        </do_if>
        <do_if value="this.ship.pilot">
          <signal_objects object="player.galaxy" param="'GT_Abort_Training'" param2="table[
            $Pilot = this.ship.pilot,
            $Ship = this.ship,
            $Reason = 'Invalid destination'
          ]"/>
        </do_if>
        <signal_objects object="this.ship" param="'training_aborted'" param2="'Invalid parameters'"/>
        <cancel_order order="this.ship.order"/>
        <return/>
      </do_if>

      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Event-driven training started at ' + @$destination.knownname" chance="$debugchance"/>
      </do_if>
      
      <!-- Get training requirements directly from global data (instant, no signals) -->
      <set_value name="$trainingRequired" exact="false"/>
      <set_value name="$requiredLevel" exact="1"/>
      
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
          <set_value name="$trainingRequired" exact="true"/>
          <set_value name="$requiredLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
          <set_value name="$trainingRequired" exact="true"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
            <set_value name="$requiredLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          </do_if>
        </do_elseif>
        <do_elseif value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment? or (global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested)">
          <set_value name="$trainingRequired" exact="true"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
            <set_value name="$requiredLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          </do_if>
          <do_elseif value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment.$Level?">
            <set_value name="$requiredLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment.$Level"/>
          </do_elseif>
        </do_elseif>
      </do_if>
      
      <!-- Validate training requirements -->
      <do_if value="not $trainingRequired">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': No training required - completing immediately'" chance="$debugchance"/>
        </do_if>
        <signal_objects object="this.ship" param="'GT_Training_Complete'" param2="table[
          $Level = 0,
          $Station = $destination,
          $Reason = 'No training needed'
        ]"/>
        <return/>
      </do_if>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training required for level ' + $requiredLevel" chance="$debugchance"/>
      </do_if>
      
      <!-- STEP 1: High-Performance Docking (VALIDATED AGAINST WORKING REFERENCE) -->
      <do_if value="(this.ship.dock and (this.ship.dock.container == $destination)) or (this.ship.parkedat and ((this.ship.parkedat == $destination) or this.ship.parkedat.hascontext.{$destination}))">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Already docked at ' + @$destination.knownname + ' - proceeding directly to training'" chance="$debugchance"/>
        </do_if>
      </do_if>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Not docked at target (dock: ' + @this.ship.dock + ', parked: ' + @this.ship.parkedat + ', target: ' + $destination + ') - initiating dock sequence'" chance="$debugchance"/>
        </do_if>
        
        <!-- Event-driven docking (no polling wait) -->
        <!-- Only pass debugchance > 0 if GT debug logging is enabled globally -->
        <set_value name="$dockDebugChance" exact="0"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$dockDebugChance" exact="$debugchance"/>
        </do_if>
        <!-- Parent DockAndTrain pauses while DockAndWait runs; flag handoff so on_abort does not treat this as failure. -->
        <set_value name="this.$trainingDockHandoff" exact="true"/>
        <create_order name="$trainingDockOrder" id="'DockAndWait'" object="this.ship" immediate="true">
          <param name="destination" value="$destination"/>
          <param name="building" value="false"/>
          <param name="trading" value="false"/>
          <param name="dockfollowers" value="$destination.isclass.station"/>
          <param name="callerid" value="this.ship.order"/>
          <param name="debugchance" value="$dockDebugChance"/>
        </create_order>
        
        <!-- Event-driven wait for docking completion -->
        <wait>
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship" order="$trainingDockOrder"/>
            </conditions>
          </interrupt>
        </wait>
        
        <remove_value name="this.$trainingDockHandoff"/>
        <remove_value name="this.$trainingDockOrder"/>
        
        <!-- Validate docking success (VALIDATED AGAINST WORKING REFERENCE) -->
        <do_if value="not ((this.ship.dock and (this.ship.dock.container == $destination)) or (this.ship.parkedat and ((this.ship.parkedat == $destination) or this.ship.parkedat.hascontext.{$destination})))">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Training] ' + this.ship.idcode + ': CRITICAL: Docking failed (dock: ' + @this.ship.dock + ', parked: ' + @this.ship.parkedat + ', target: ' + $destination + ') - aborting training'" chance="$debugchance"/>
          </do_if>
          
          <!-- Notify MD system: Training failed -->
          <signal_objects object="player.galaxy" param="'GT_Abort_Training'" param2="table[
            $Pilot = this.ship.pilot,
            $Ship = this.ship,
            $Reason = 'Docking failed'
          ]"/>
          
          <signal_objects object="this.ship" param="'GT_Training_Failed'" param2="table[
            $Reason = 'Docking failed',
            $Station = $destination
          ]"/>
          <cancel_order order="this.ship.order"/>
          <return/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Docking successful - training can proceed'" chance="$debugchance"/>
        </do_if>
      </do_else>
      
      <!-- STEP 2: Commit training at dock (payment + duration live in MD).
           GT_Start_Training MUST fire only after a successful dock so academy
           fees are not debited while the ship is still in transit. -->
      <signal_objects object="player.galaxy" param="'GT_Start_Training'" param2="table[
        $Ship = this.ship,
        $Pilot = this.ship.pilot,
        $TrainingLevel = $requiredLevel,
        $TrainingStation = $destination
      ]"/>
      <!-- Yield so HandleStartTraining commits payment + $TrainingDuration
           before this script reads registry timer fields (signal_objects is
           queued across AI/MD boundaries). -->
      <wait exact="1ms"/>
      
      <!-- Send immersive training message to logbook - only if enabled -->
      <do_if value="@this.ship.commander.defaultorder.$logbookentries or @this.ship.defaultorder.$logbookentries">
        <set_value name="$actualDuration" exact="@global.$GT_Pilots.{this.ship.pilot}.$TrainingDuration"/>
        
        <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTrainingStarted'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Station = $destination,
          $TrainingLevel = $requiredLevel,
          $Duration = $actualDuration
        ]"/>
      </do_if>
      
       <!-- STEP 3: Training Simulation - Get duration calculated by MD script (PRODUCTION MODE) -->
       <set_value name="$trainingDuration" exact="@global.$GT_Pilots.{this.ship.pilot}.$TrainingDuration"/>
       
       <!-- Fallback to 10 minutes if duration not set (should never happen) -->
       <do_if value="not $trainingDuration?">
         <set_value name="$trainingDuration" exact="600s"/>
         <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
           <debug_text text="'[GT-Training] ' + this.ship.idcode + ': WARNING - Training duration not set, using fallback 10 minutes'" chance="100"/>
         </do_if>
       </do_if>
       
       <!-- CRITICAL FIX: Ensure duration is a time value, not an integer -->
       <!-- Match against datatype.time (vanilla pattern) so values arriving
            as long-fixed / float (e.g. via the Lua-written academy
            blackboard) are promoted too, not only literal integers. -->
       <do_if value="$trainingDuration and typeof $trainingDuration != datatype.time">
         <set_value name="$trainingDuration" exact="$trainingDuration * 1s"/>
         <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
           <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Converted integer duration to time: ' + ($trainingDuration / 1s) + 's'" chance="100"/>
         </do_if>
       </do_if>
       <!-- Rebuild a fresh local time literal for <wait>. Registry reads can
            keep datatype.time while still using the engine's 1/12-second raw
            unit count; (x / 1s) * 1s normalizes to whole seconds (e.g. 600s
            was completing in ~50s game time when passed straight to wait max). -->
       <set_value name="$trainingWaitTime" exact="($trainingDuration / 1s) * 1s"/>
       
       <!-- Save/load: continue from remaining course time when the timer was
            already started before the save (HandleStartTraining stamps both).
            Ignore the stub stamp HandleStartTraining sets in the same frame as
            a fresh dock commit (elapsed le 1s). -->
       <set_value name="$skipTrainingWait" exact="false"/>
       <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingStarted?">
         <set_value name="$elapsedTraining" exact="player.age - global.$GT_Pilots.{this.ship.pilot}.$TrainingStarted"/>
         <do_if value="$elapsedTraining gt 1s">
           <set_value name="$remainingTraining" exact="$trainingWaitTime - $elapsedTraining"/>
           <do_if value="$remainingTraining le 0s">
             <set_value name="$skipTrainingWait" exact="true"/>
             <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
               <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training timer expired during save/load - completing immediately'" chance="100"/>
             </do_if>
           </do_if>
           <do_else>
             <set_value name="$trainingWaitTime" exact="($remainingTraining / 1s) * 1s"/>
             <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
               <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Resuming training with ' + ($trainingWaitTime / 1s) + 's remaining'" chance="100"/>
             </do_if>
           </do_else>
         </do_if>
       </do_if>
       
       <set_value name="this.$trainingEndsAt" exact="player.age + $trainingWaitTime"/>
       
       <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
         <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Level ' + $requiredLevel + ' training duration: ' + ($trainingWaitTime / 1s) + 's (ends at ' + this.$trainingEndsAt + ')'" chance="$debugchance"/>
       </do_if>
      
       <!-- Event-driven training wait (no polling) -->
       <!-- min=max keeps the full course length while still allowing the
            GT_Abort_Training interrupt to fire immediately (vanilla/GT pattern). -->
       <do_if value="not $skipTrainingWait">
       <wait min="$trainingWaitTime" max="$trainingWaitTime">
         <interrupt>
           <conditions>
             <event_object_signalled object="this.ship" param="'GT_Abort_Training'"/>
           </conditions>
           <actions>
             <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
               <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training interrupted by abort signal'" chance="$debugchance"/>
             </do_if>
      
             <signal_objects object="player.galaxy" param="'GT_Abort_Training'" param2="table[
               $Pilot = this.ship.pilot,
               $Ship = this.ship,
               $Reason = 'Training interrupted'
             ]"/>
             
             <signal_objects object="this.ship" param="'GT_Training_Failed'" param2="table[
               $Reason = 'Training interrupted',
               $Station = $destination
             ]"/>
             <return/>
           </actions>
         </interrupt>
       </wait>
       </do_if>
       
       <!-- STEP 4: Complete Training -->
       <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
         <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training completed - processing results'" chance="$debugchance"/>
       </do_if>
      
       <!-- Notify MD system: Training completed -->
      <signal_objects object="player.galaxy" param="'GT_Complete_Training'" param2="table[
        $Pilot = this.ship.pilot,
        $Ship = this.ship,
         $Level = $requiredLevel
      ]"/>
      
       <!-- Send training completion message to logbook - only if enabled -->
       <do_if value="@this.ship.commander.defaultorder.$logbookentries or @this.ship.defaultorder.$logbookentries">
         <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTrainingCompleted'" param2="table[
           $Ship = this.ship,
           $Pilot = this.ship.pilot,
           $Level = $requiredLevel
         ]"/>
       </do_if>
      
      <!-- STEP 5: Event-Driven Undocking -->
      <do_if value="@this.ship.dockingbay.container">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Initiating undock sequence'" chance="$debugchance"/>
        </do_if>
        
        <create_order object="this.ship" id="'Undock'" immediate="true"/>
        
        <!-- Event-driven undocking wait -->
        <wait>
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship"/>
            </conditions>
          </interrupt>
        </wait>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Undocking completed'" chance="$debugchance"/>
        </do_if>
      </do_if>
      
      <!-- STEP 6: Signal Completion -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training sequence completed successfully for level ' + $requiredLevel" chance="$debugchance"/>
      </do_if>
      
      <signal_objects object="this.ship" param="'GT_Training_Complete'" param2="table[
        $Level = $requiredLevel,
        $Station = $destination,
        $Duration = $trainingWaitTime
      ]"/>
      
    </actions>
  </attention>
  
  <on_abort>
    <!-- DockAndWait child pauses this script while the ship flies to the station.
         That engine pause fires on_abort; it is NOT a player cancel or failure. -->
    <set_value name="$isDockTransitHandoff" exact="false"/>
    <do_if value="this.$trainingDockOrder? and this.$trainingDockOrder.exists">
      <set_value name="$isDockTransitHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isDockTransitHandoff and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'DockAndTrain'">
      <set_value name="$isDockTransitHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isDockTransitHandoff and this.ship.orders? and this.ship.orders.count gt 0">
      <do_all exact="this.ship.orders.count" counter="$toai">
        <set_value name="$toOrder" exact="this.ship.orders.{$toai}"/>
        <do_if value="@$toOrder.id == 'DockAndWait' and $toOrder.$callerid? and @$toOrder.$callerid.id == 'DockAndTrain'">
          <set_value name="$isDockTransitHandoff" exact="true"/>
          <break/>
        </do_if>
      </do_all>
    </do_if>
    <do_if value="$isDockTransitHandoff">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Training] ' + this.ship.idcode + ': on_abort skipped (DockAndWait transit handoff - training still in progress)'" chance="$debugchance"/>
      </do_if>
      <return/>
    </do_if>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training order cancelled'" chance="$debugchance"/>
    </do_if>
    
    <!-- CRITICAL: Check if GT order is still active before sending signals -->
    <!-- Training order can abort normally (completion) - only send signals if GT order is still active -->
    <set_value name="$trainAbortDefaultOrder" exact="null"/>
    <do_if value="this.ship.defaultorder?">
      <set_value name="$trainAbortDefaultOrder" exact="@this.ship.defaultorder.id"/>
    </do_if>
    <set_value name="$hasDirectGTOrder" exact="false"/>
    <set_value name="$hasGTCommander" exact="false"/>
    <do_if value="$trainAbortDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$trainAbortDefaultOrder}">
      <set_value name="$hasDirectGTOrder" exact="true"/>
    </do_if>
    <do_elseif value="$trainAbortDefaultOrder == 'Assist' and this.ship.defaultorder? and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
      <set_value name="$hasDirectGTOrder" exact="true"/>
    </do_elseif>
    <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
      <set_value name="$hasGTCommander" exact="true"/>
    </do_if>
    <do_elseif value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
      <set_value name="$hasGTCommander" exact="true"/>
    </do_elseif>
    
    <!-- Only send signals if GT order is still active (direct or via commander) -->
    <do_if value="$hasDirectGTOrder or $hasGTCommander">
      <!-- Notify MD system about training abortion -->
      <signal_objects object="player.galaxy" param="'GT_Abort_Training'" param2="table[
        $Pilot = this.ship.pilot,
        $Ship = this.ship,
        $Reason = 'Training order cancelled'
      ]"/>
      
      <!-- Signal abortion to main trading script -->
      <signal_objects object="this.ship" param="'training_aborted'" param2="'Training order cancelled'"/>
    </do_if>
    <do_else>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Training] ' + this.ship.idcode + ': Training order aborted but GT order no longer active - skipping signals'" chance="$debugchance"/>
      </do_if>
    </do_else>
  </on_abort>
  
</aiscript> <?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Capture dock failure reasons for trade orders -->
  
  <!-- CRITICAL: When dock fails due to "no path to destination", signal parent trade order -->
  <add sel="//aiscript[@name='order.dock']/attention/actions/label[@name='nodestination']" pos="after">
    
    <!-- GALAXYTRADER MK3: Signal dock failure to parent trade order -->
    <do_if value="@$callerid.id == 'TradePerform'">
      <!-- This dock order was created by a trade order - signal the failure reason -->
      <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$thisship.pilot}?">
        <!-- Only for GT-managed pilots -->
        
        <!-- Determine specific failure reason -->
        <set_value name="$gt_dock_failure" exact="'ERR_NO_PATH_TO_DESTINATION'"/>
        <set_value name="$failuretext" exact="{1045, 124}" comment="No path to destination"/>
        
        <!-- Check if it's a blacklist issue -->
        <include_interrupt_actions ref="GetBlacklistgroup"/>
        <do_if value="$internalorder and @$destination.exists">
          <!-- Check if destination is blacklisted -->
          <do_if value="$destination.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{$thisship}">
            <set_value name="$gt_dock_failure" exact="'ERR_DESTINATION_BLACKLISTED'"/>
            <set_value name="$failuretext" exact="{1045, 124}" comment="Destination is blacklisted"/>
          </do_if>
          <do_elseif value="@$destination.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{$thisship}">
            <set_value name="$gt_dock_failure" exact="'ERR_SECTOR_BLACKLISTED'"/>
            <set_value name="$failuretext" exact="{1045, 124}" comment="Sector is blacklisted"/>
          </do_elseif>
        </do_if>
        
        <!-- Store failure reason in global table for parent trade order to check -->
        <do_if value="not global.$GT_DockFailures?">
          <set_value name="global.$GT_DockFailures" exact="table[]"/>
        </do_if>
        
        <set_value name="global.$GT_DockFailures.{$thisship}" exact="table[
          $Reason = $gt_dock_failure,
          $FailureText = $failuretext,
          $Destination = $destination,
          $Timestamp = player.age
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Dock] âš  Dock FAILED for ' + $thisship.idcode + ': ' + $gt_dock_failure + ' (destination: ' + @$destination.knownname + ')'" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    
  </add>
  
</diff>
<?xml version="1.0" encoding="utf-8"?>

<aiscript name="order.gt.idlepark" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="3">

  <order id="GTIdlePark" name="{77000, 1096}" description="{77000, 1097}" category="navigation" infinite="false" canplayercancel="true">

    <params>

      <param name="home" type="object" text="{77000, 1002}" comment="{77000, 1020}">

        <input_param name="class" value="[class.station,class.sector]"/>

      </param>

      <param name="debugchance" default="0" type="number" text="{1001, 9074}" comment="{1001, 9075}">

        <input_param name="min" value="0"/>

        <input_param name="max" value="100"/>

      </param>

    </params>

    <requires>

      <match shiptype="shiptype.lasertower" negate="true"/>

    </requires>

    <location object="$home" condition="@$home.exists"/>

  </order>



  <interrupts>

    <handler ref="TargetInvalidHandler"/>

    <handler ref="AttackHandler"/>

  </interrupts>



  <init>

    <set_order_syncpoint_reached order="this.ship.order"/>

    <set_value name="this.$idleParkOrder" exact="this.ship.order"/>

    <set_value name="this.$idleParkDockHandoff" exact="false"/>

    <set_command command="command.wait"/>

    <set_command_action commandaction="commandaction.standingby"/>

    <set_value name="$releaseMinutes" exact="1"/>

    <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet?">

      <do_all exact="global.$GT_GlobalSettings.$Fleet.keys.count" counter="$fki">

        <set_value name="$fleetKey" exact="global.$GT_GlobalSettings.$Fleet.keys.{$fki}"/>

        <do_if value="$fleetKey == '$IdleParkingReleaseMinutes'">

          <set_value name="$releaseMinutes" exact="[[global.$GT_GlobalSettings.$Fleet.{$fleetKey}, 0].max, 60].min"/>

        </do_if>

      </do_all>

    </do_if>

    <do_if value="not global.$GT_IdleParkingHold?">

      <set_value name="global.$GT_IdleParkingHold" exact="table[]"/>

    </do_if>

    <do_if value="not global.$GT_IdleParkingHoldUntil?">

      <set_value name="global.$GT_IdleParkingHoldUntil" exact="table[]"/>

    </do_if>

    <do_if value="not global.$GT_IdleParkingDockedSince?">

      <set_value name="global.$GT_IdleParkingDockedSince" exact="table[]"/>

    </do_if>

    <do_if value="not global.$GT_IdleParkingReleased?">

      <set_value name="global.$GT_IdleParkingReleased" exact="table[]"/>

    </do_if>

    <set_value name="global.$GT_IdleParkingHold.{this.ship}" exact="true"/>

    <do_if value="$releaseMinutes gt 0">

      <set_value name="global.$GT_IdleParkingHoldUntil.{this.ship}" exact="player.age + $releaseMinutes * 1min"/>

    </do_if>

    <do_else>

      <do_if value="global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{this.ship}?">

        <remove_value name="global.$GT_IdleParkingHoldUntil.{this.ship}"/>

      </do_if>

    </do_else>

  </init>



  <patch sinceversion="2">

    <do_if value="not global.$GT_IdleParkingHold?">

      <set_value name="global.$GT_IdleParkingHold" exact="table[]"/>

    </do_if>

    <do_if value="not global.$GT_IdleParkingHoldUntil?">

      <set_value name="global.$GT_IdleParkingHoldUntil" exact="table[]"/>

    </do_if>

    <do_if value="not global.$GT_IdleParkingHold.{this.ship}?">

      <set_value name="global.$GT_IdleParkingHold.{this.ship}" exact="true"/>

      <set_value name="global.$GT_IdleParkingHoldUntil.{this.ship}" exact="player.age + 6h"/>

    </do_if>

  </patch>



  <attention min="unknown">

    <actions>

      <do_if value="not $home? or not $home.exists">

        <set_command_action commandaction="commandaction.orderfailed"/>

        <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>

        <do_if value="global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{this.ship}?">

          <remove_value name="global.$GT_IdleParkingHoldUntil.{this.ship}"/>

        </do_if>

        <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>

        <return/>

      </do_if>



      <run_script name="'lib.gt.idlepark'" result="$parkResolve">
        <param name="handoffMode" value="'resolve_park_station'"/>
        <param name="handoffShip" value="this.ship"/>
        <param name="home" value="$home"/>
        <param name="debugchance" value="$debugchance"/>
      </run_script>
      <set_value name="$parkStation" exact="if $parkResolve.$ParkStation? then $parkResolve.$ParkStation else null"/>
      <set_value name="$parkSector" exact="if $parkResolve.$ParkSector? then $parkResolve.$ParkSector else null"/>

      <do_if value="$parkStation? and $parkStation != null and $parkStation.exists">

        <set_value name="$alreadyDocked" exact="(this.ship.dock and this.ship.dock.container == $parkStation) or (this.ship.parkedat and ((this.ship.parkedat == $parkStation) or this.ship.parkedat.hascontext.{$parkStation}))"/>

        <do_if value="not $alreadyDocked">

          <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': docking at ' + $parkStation.knownname + ' (trader keeps searching)'" chance="$debugchance"/>

          <set_value name="this.$idleParkDockHandoff" exact="true"/>

          <create_order name="$dockOrder" id="'DockAndWait'" object="this.ship" immediate="true">

            <param name="destination" value="$parkStation"/>

            <param name="building" value="false"/>

            <param name="trading" value="true"/>

            <param name="dockfollowers" value="false"/>

            <param name="allowplayeronly" value="true"/>

            <param name="callerid" value="this.$idleParkOrder"/>

            <param name="debugchance" value="$debugchance"/>

          </create_order>



          <wait>

            <interrupt>

              <conditions>

                <event_object_order_ready object="this.ship" order="$dockOrder"/>

              </conditions>

            </interrupt>

          </wait>

          <set_value name="this.$idleParkDockHandoff" exact="false"/>



          <set_value name="$isDockedAtPark" exact="(this.ship.dock and this.ship.dock.container == $parkStation) or (this.ship.parkedat and ((this.ship.parkedat == $parkStation) or this.ship.parkedat.hascontext.{$parkStation}))"/>

          <do_if value="not $isDockedAtPark">

            <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': dock attempt did not complete at park station - releasing for search retry'" chance="$debugchance"/>

            <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>

            <do_if value="global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{this.ship}?">

              <remove_value name="global.$GT_IdleParkingHoldUntil.{this.ship}"/>

            </do_if>

            <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>

            <return/>

          </do_if>

        </do_if>

        <do_else>

          <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': already docked at ' + $parkStation.knownname + ' (trader keeps searching)'" chance="$debugchance"/>

        </do_else>



        <do_if value="not global.$GT_IdleParkingDockedSince.{this.ship}?">

          <set_value name="global.$GT_IdleParkingDockedSince.{this.ship}" exact="player.age"/>

        </do_if>



        <set_command command="command.wait" param="$parkStation"/>

        <set_command_action commandaction="commandaction.standingby"/>

        <!-- Hold globals stay active; GalaxyTrader main_loop keeps searching (MK1 return-home pattern). -->
        <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': docked at ' + $parkStation.knownname + ' - trader keeps searching'" chance="$debugchance"/>

        <return/>

      </do_if>



      <do_if value="$parkSector? and $parkSector.exists">

        <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': no dockable station in home sector - hold cleared for search retry'" chance="$debugchance"/>

      </do_if>



      <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>

      <do_if value="global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{this.ship}?">

        <remove_value name="global.$GT_IdleParkingHoldUntil.{this.ship}"/>

      </do_if>

      <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>

      <set_command_action commandaction="commandaction.orderfailed"/>

    </actions>

  </attention>



  <on_abort>

    <!-- Parent order still queued while DockAndWait runs â€” not a player cancel. -->
    <set_value name="$isOrderPause" exact="false"/>

    <do_if value="this.$idleParkOrder? and this.$idleParkOrder.exists">

      <set_value name="$isOrderPause" exact="true"/>

    </do_if>

    <do_if value="not $isOrderPause and this.$idleParkDockHandoff? and this.$idleParkDockHandoff">

      <set_value name="$isOrderPause" exact="true"/>

    </do_if>

    <do_if value="not $isOrderPause and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'GTIdlePark'">

      <set_value name="$isOrderPause" exact="true"/>

    </do_if>

    <do_if value="not $isOrderPause and this.ship.orders.count gt 0">

      <do_all exact="this.ship.orders.count" counter="$ipoi">

        <set_value name="$ipOrder" exact="this.ship.orders.{$ipoi}"/>

        <do_if value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">

          <set_value name="$isOrderPause" exact="true"/>

          <break/>

        </do_if>

      </do_all>

    </do_if>

    <do_if value="$isOrderPause">

      <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': on_abort skipped (order still active)'" chance="$debugchance"/>

    </do_if>

    <do_elseif value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">

      <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>

      <do_if value="global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{this.ship}?">

        <remove_value name="global.$GT_IdleParkingHoldUntil.{this.ship}"/>

      </do_if>

      <do_if value="global.$GT_IdleParkingDockedSince? and global.$GT_IdleParkingDockedSince.{this.ship}?">

        <remove_value name="global.$GT_IdleParkingDockedSince.{this.ship}"/>

      </do_if>

      <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>

      <debug_text text="'[GT-IdlePark] ' + this.ship.idcode + ': idle parking cancelled - resuming search'" chance="$debugchance"/>

      <do_if value="this.ship.dock or this.ship.parkedat">

        <create_order object="this.ship" id="'Undock'" immediate="true"/>

      </do_if>

    </do_elseif>

  </on_abort>

</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.gt.returnhome" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <order id="DockAndReturnHome" name="{77000, 10006}" description="{77000, 10106}" category="navigation" infinite="false">
    <params>
      <param name="destination" type="object" text="{1041, 10141}" comment="Home station to dock at">
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="debugchance" default="0" type="number" text="{1001, 9074}" comment="{1001, 9075}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
      </param>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
    <location object="$destination" condition="@$destination.exists"/>
  </order>

  <interrupts>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="AttackHandler"/>
  </interrupts>

  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_command command="command.dockat" param="$destination"/>
    <set_command_action commandaction="commandaction.flyingto" param="$destination"/>
    <set_value name="$holdTimeout" exact="6h"/>
    <do_if value="not global.$GT_ReturnHomeHold?">
      <set_value name="global.$GT_ReturnHomeHold" exact="table[]"/>
    </do_if>
    <do_if value="not global.$GT_ReturnHomeHoldUntil?">
      <set_value name="global.$GT_ReturnHomeHoldUntil" exact="table[]"/>
    </do_if>
    <do_if value="not global.$GT_MK1DockedSince?">
      <set_value name="global.$GT_MK1DockedSince" exact="table[]"/>
    </do_if>
    <!-- Keep ship docked after return-home until MK1 explicitly queues new trade orders. -->
    <set_value name="global.$GT_ReturnHomeHold.{this.ship}" exact="true"/>
    <!-- Keep hold active across potentially long return flights; MK1 handles timed undock retries while docked. -->
    <set_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}" exact="player.age + $holdTimeout"/>
  </init>

  <attention min="unknown">
    <actions>
      <do_if value="not $destination? or not $destination.exists">
        <set_command_action commandaction="commandaction.orderfailed"/>
        <return/>
      </do_if>

      <set_value name="$alreadyDocked" exact="(this.ship.dock and this.ship.dock.container == $destination) or (this.ship.parkedat and ((this.ship.parkedat == $destination) or this.ship.parkedat.hascontext.{$destination}))"/>
      <do_if value="not $alreadyDocked">
        <run_script name="'lib.gt.dockcheck'" result="$returnHomeDockCheck">
          <param name="ship" value="this.ship"/>
          <param name="station" value="$destination"/>
          <param name="purpose" value="'trade'"/>
          <param name="allowPlayerOnly" value="true"/>
        </run_script>
        <do_if value="not $returnHomeDockCheck.$CanDock">
          <debug_text text="'[GT-ReturnHome] ' + this.ship.idcode + ': no operational trading dock at ' + $destination.knownname + ' (size=' + this.ship.docksize + ')'" chance="$debugchance"/>
          <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}?">
            <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
            <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
          </do_if>
          <set_command_action commandaction="commandaction.orderfailed"/>
          <return/>
        </do_if>
        <create_order name="$dockOrder" id="'DockAndWait'" object="this.ship" immediate="true">
          <param name="destination" value="$destination"/>
          <param name="building" value="false"/>
          <param name="trading" value="true"/>
          <param name="dockfollowers" value="false"/>
          <param name="allowplayeronly" value="true"/>
          <param name="callerid" value="this.ship.order"/>
          <param name="debugchance" value="$debugchance"/>
        </create_order>

        <wait>
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship" order="$dockOrder"/>
            </conditions>
          </interrupt>
        </wait>
      </do_if>

      <set_value name="$isDockedAtDestination" exact="(this.ship.dock and this.ship.dock.container == $destination) or (this.ship.parkedat and ((this.ship.parkedat == $destination) or this.ship.parkedat.hascontext.{$destination}))"/>
      <do_if value="$isDockedAtDestination">
        <!-- Anchor timeout to real dock completion time (not return-flight start). -->
        <set_value name="global.$GT_MK1DockedSince.{this.ship}" exact="player.age"/>
        <set_command_action commandaction="commandaction.standingby"/>
      </do_if>
      <do_else>
        <debug_text text="'[GT-ReturnHome] ' + this.ship.idcode + ': dock attempt did not complete at ' + $destination.knownname" chance="$debugchance"/>
        <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}?">
          <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
        </do_if>
        <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
          <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
        </do_if>
        <set_command_action commandaction="commandaction.orderfailed"/>
      </do_else>
    </actions>
  </attention>
</aiscript>
<?xml version="1.0" encoding="utf-8" ?>
<aiscript name="order.mining.routine.gt" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="33">
  <!--
  This script will try to automatically supply stations and will only work with
  a valid warebasket parameter (defined via jobs). It can do gas and mineral
  mining and works for all ship classes. 
  
  Supports:
   * Range: space class or space string 'zone', 'sector', 'cluster'
   * Buy/Sell with Min/Max gate distances from $range
  
  If there is a valid commander, it will gather resources to supply the commander (homebase)
  
  -->
  <order id="MiningRoutine_GT" name="{1041, 341}" description="{1041, 342}" category="internal" allowinloop="false">
    <params>
      <param name="warebasket" required="true" default="this.ship.warebasket.list" type="list" text="{1041, 10146}" comment="Wares. list of wares that takes precedence over any defined warebasket">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
        <input_param name="isminable" value="true"/>
        <input_param name="canplayeroverride" value="true"/>
      </param>
      <param name="range" default="if @this.ship.commanderentity.$config_subordinate_range then @this.ship.commanderentity.$config_subordinate_range 
            else (if @this.ship.commander.jobmainsector then this.ship.commander.jobmainsector
              else (if @this.ship.commander.isclass.[class.station, class.buildstorage] then this.ship.commander.sector
                else (if this.ship.jobmainsector then this.ship.jobmainsector
                  else this.sector)))" type="internal" text="{1041, 10005}" comment="Anchor space"/>
      <param name="strictgathersector" default="null" type="internal" comment="If set, gathering spaces are hard-locked to this sector."/>

      <param name="minbuy" default="0" type="number" advanced="true" text="{1041, 10067}" comment="Min gate distance to gather resources. Gathering range supported if $minsell and $maxsell are provided">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 24 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 0 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 2 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 4 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 9 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 14 else 24) else 0), 0].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="maxbuy" default="0" type="number" text="{1041, 10056}" comment="Max gate distance to gather resources. Gathering range supported if $minsell and $maxsell are provided">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
        <patch condition="$resourcescout and this.ship.isjobship" value="5" sinceversion="15"/>
      </param>
      <param name="minsell" default="0" type="number" advanced="true" text="{1041, 10069}" comment="Min gate distance to sell resources. Sell range supported if $minsell and $maxsell are provided">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 24 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 0 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 2 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 4 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 9 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 14 else 24) else 0), 0].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="maxsell" default="0" type="number" text="{1041, 10058}" comment="Max gate distance to sell resources. Sell range supported if $minsell and $maxsell are provided">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>

      <param name="deepspace" default="false" type="bool" text="{1041, 10082}" advanced="true" comment="Operate in deep space. Operate only in deep space. Currently defined as 100 +/- 50km from sector core edge"/>
      <param name="resourcescout" default="false" type="bool" text="{1041, 10109}" advanced="true" comment="Scout for resources. Visibly look for resources before mining"/>
      <param name="logbookentries" default="true" type="internal" comment="Forwarded from GalaxyMiner order setup. Controls miner queue-time logbook messages while leaving XP transfer signals active."/>
      <param name="allowIllegal" default="false" type="internal" comment="Forwarded from GalaxyMiner order setup. When true, ship may carry/trade illegal wares."/>
      <param name="enforceRouteIllegalLegality" default="false" type="internal" comment="Forwarded from GalaxyMiner order setup. Illegal Route Filter for sell-leg path planning."/>
      <param name="duration" default="0s" type="time" infinitevalue="0s" advanced="true" text="{1041, 10034}" comment="Duration. Only accounts for time spent executing this order.">
        <input_param name="startvalue" value="0s"/>
        <input_param name="min" value="0s"/>
        <input_param name="max" value="24h"/>
        <input_param name="step" value="1min"/>
        <patch value="0s" sinceversion="7"/>
      </param>
      <param name="endtime" default="0s" type="internal" comment="Absolute game time in seconds, after which order will end. Overrides duration. For internal use. Do not use with default orders."/>
      <param name="effectiveskill" default="this.ship.combinedskill" type="internal" comment="Effective skill level used for skill checks"/>
      <param name="preferownspace" default="false" type="internal" comment="Only search for resources in spaces owned by our faction. If none are found, a fallback sector will be used.">
        <patch value="false" sinceversion="20"/>
      </param>
      <param name="playerStationsOnly" default="false" type="internal" comment="If true, only player-owned stations are valid demand/sell targets for free miners."/>
      <param name="primaryTargetStations" default="[]" type="internal" comment="Primary Galaxy Miner delivery stations (home + explicit targets).">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="blockedstations" default="[]" type="internal" comment="Stations excluded by the Galaxy Miner order setup.">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="overflowSellMode" default="false" type="internal" comment="When true, all primary stations are at/above overflow threshold for current ware."/>
      <param name="allowOverflowSellToOthers" default="false" type="internal" comment="If true, overflow may be sold beyond primary target stations."/>
      <param name="overflowThreshold" default="90" type="internal" comment="Primary station fill threshold (percent) before overflow behavior applies."/>
      <param name="physicalStorageAbortPercent" default="20" type="internal" comment="Headroom above station physical stock (percent) before level-6+ pilots stop collecting slice ware. 0 = disabled. Forwarded from GalaxyMiner order."/>
      <param name="checkDemandFirst" default="true" type="internal" comment="Forwarded from GalaxyMiner order. Physical storage gate is skipped when false (stockpile mode)."/>
      <param name="warebasket_override" default="[]" type="internal" comment="Wares (Manual). Only use this warebasket or a subset thereof.">
        <input_param name="type" value="'ware'"/>
        <input_param name="uitype" value="'list'"/>
        <input_param name="cancarry" value="this.ship"/>
        <input_param name="optionsource" value="'commanderwarebasket'"/>
        <patch value="[]" sinceversion="24"/>
      </param>
      <param name="precomputedgatherspaces" default="[]" type="internal" comment="Caller-supplied gather sector list (skips lib.find.sectors.inrange when non-empty)."/>
      <param name="resolvedsector" default="null" type="internal" comment="Caller-resolved mining sector (skips engine resource search when set with resolvedpos)."/>
      <param name="resolvedpos" default="null" type="internal" comment="Caller-resolved mining position paired with resolvedsector."/>
      <param name="debugchance" type="bool" default="0" advanced="true" text="{1041, 10086}" comment="Print debug output">
        <input_param name="truevalue" value="100"/>
      </param>
      <param name="debugchance2" type="bool" default="0" advanced="true" text="{1041, 10142}" comment="Verbose debug output">
        <input_param name="truevalue" value="100"/>
      </param>
    </params>
    <requires primarypurpose="purpose.mine"/>
    <icon name="order_miningroutine_manual" condition="this.ship.commander and $warebasket_override.count"/>
  </order>
  <interrupts>
    <handler ref="SectorChangeHandler"/>
    <handler ref="AttackHandler" />
    <handler ref="MissileLockHandler" />
    <handler ref="ScannedHandler" />
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler" />
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>
    <handler comment="handler kept local since it modifies a value local to this script">
      <conditions>
        <event_object_signalled object="this.assignedcontrolled" param="'range_setting_updated'" />
      </conditions>
      <actions>
        <set_value name="$range" exact="if @event.param2 then event.param2 else this.assignedcontrolled.commanderentity.$config_subordinate_range" />
        <debug_text text="'updated operational range for %1(%2) to %3(%4)'.[this.assignedcontrolled.knownname, this.assignedcontrolled, $range.knownname, $range]" chance="$debugchance" />
      </actions>
    </handler>
    <handler>
      <conditions>
        <event_object_changed_sector object="this.assignedcontrolled.commander" check="false"/>
        <check_value value="event.param.exists and ($range != event.param)"/>
        <check_value value="this.assignedcontrolled.assignment != assignment.assist"/>
        <check_value value="not @this.assignedcontrolled.commanderentity.$config_subordinate_range"/>
      </conditions>
      <actions>
        <set_value name="$range" exact="event.param"/>
        <do_if value="@$thisorder.exists">
          <edit_order_param order="$thisorder" param="'range'" value="$range"/>
        </do_if>
      </actions>
    </handler>
  </interrupts>
  <init>
    <set_command command="command.freemining" />
    <!-- Mining for commander (Must to be Station) -->
    <do_if value="@this.assignedcontrolled.commander.isclass.[class.station, class.buildstorage]">
      <set_value name="$homebase" exact="this.assignedcontrolled.commander" />
    </do_if>
    <do_elseif value="this.assignedcontrolled.assignment == assignment.assist and this.assignedcontrolled.toplevelcommander.isclass.station">
      <set_value name="$homebase" exact="this.assignedcontrolled.toplevelcommander" />
    </do_elseif>

    <set_value name="$time_start" exact="player.age"/>
    <do_if value="(this.assignedcontrolled.order.id == 'MiningRoutine') or (this.assignedcontrolled.order.id == 'MiningRoutine_Basic') or (this.assignedcontrolled.order.id == 'MiningRoutine_Advanced') or (this.assignedcontrolled.order.id == 'MiningRoutine_Expert')">
      <set_value name="$thisorder" exact="this.assignedcontrolled.order"/>
    </do_if>

    <!-- update effective skill everytime the script starts. -->
    <do_if value="($effectiveskill != 0) and ($effectiveskill != 100)">
      <set_value name="$effectiveskill" exact="this.assignedcontrolled.combinedskill"/>
    </do_if>

    <do_if value="$endtime">
      <set_value name="$duration" exact="$endtime - player.age" comment="can be negative"/>
    </do_if>
    <!-- Match vanilla order.mining.routine.xml: yield *rating* threshold for find_closest_resource / find_resource in-sector. -->
    <set_value name="$minrating" exact="3"/>
  </init>
  <patch sinceversion="2">
    <do_if value="$minbuy == -1">
      <set_value name="$minbuy" exact="0"/>
    </do_if>
    <do_if value="$maxbuy == -1">
      <set_value name="$maxbuy" exact="0"/>
    </do_if>
    <do_if value="$minsell == -1">
      <set_value name="$minsell" exact="0"/>
    </do_if>
    <do_if value="$maxsell == -1">
      <set_value name="$maxsell" exact="0"/>
    </do_if>
    <do_if value="($minbuy gt 0) and ($minbuy ge $maxbuy)">
      <debug_text text="'PATCH: minbuy is greater than maxbuy. cannot find spaces. resetting minbuy to 0.'" filter="savegame"/>
      <set_value name="$minbuy" exact="0"/>
    </do_if>
    <do_if value="($minsell gt 0) and ($minsell ge $maxsell)">
      <debug_text text="'PATCH: minsell is greater than maxsell. cannot find spaces. resetting minsell to 0.'" filter="savegame"/>
      <set_value name="$minsell" exact="0"/>
    </do_if>
  </patch>
  <patch sinceversion="4">
    <do_if value="this.assignedcontrolled.order.id == 'MiningRoutine'">
      <edit_order_param order="this.assignedcontrolled.order" param="'effectiveskill'" value="this.assignedcontrolled.combinedskill"/>
    </do_if>
  </patch>
  <patch sinceversion="7">
    <set_value name="$time_start" exact="player.age"/>
    <set_value name="$duration" exact="0s"/>

    <do_if value="(this.assignedcontrolled.order.id == 'MiningRoutine') or (this.assignedcontrolled.order.id == 'MiningRoutine_Basic') or (this.assignedcontrolled.order.id == 'MiningRoutine_Advanced') or (this.assignedcontrolled.order.id == 'MiningRoutine_Expert')">
      <!-- NB: if this is not the current order, variables will be correctly set when the script starts/restarts. -->
      <set_value name="$thisorder" exact="this.assignedcontrolled.order"/>
    </do_if>
  </patch>
  <patch sinceversion="10">
    <!-- if $gatheringspaces has not yet been defined, $range will be re-evaluated after it is defined. -->
    <do_if value="this.hasrelation.enemy.{$range.owner} and @$gatheringspaces.count and not @this.assignedcontrolled.commander.hascontext.{$range}">
      <do_all exact="$gatheringspaces.count" counter="$i">
        <do_if value="$gatheringspaces.{$i}.exists">
          <do_if value="$gatheringspaces.{$i}.owner == this.owner">
            <set_value name="$locrange" exact="$gatheringspaces.{$i}"/>
            <break/>
          </do_if>
          <do_elseif value="not this.hasrelation.enemy.{$gatheringspaces.{$i}.owner}">
            <set_value name="$locfallback" exact="$gatheringspaces.{$i}"/>
          </do_elseif>
        </do_if>
      </do_all>

      <do_if value="not $locrange? and $locfallback?">
        <set_value name="$locrange" exact="$locfallback"/>
      </do_if>
      <remove_value name="$locfallback"/>

      <do_if value="$locrange?">
        <set_value name="$range" exact="$locrange"/>
        <debug_text text="'PATCH: old anchor space was hostile. changing to %s %s.'.[$range.class, $range.knownname]" filter="savegame"/>
        <do_if value="@this.assignedcontrolled.order.$range.isclass.space">
          <edit_order_param order="this.assignedcontrolled.order" param="'range'" value="$range"/>
          <do_if value="this.assignedcontrolled.defaultorder == this.assignedcontrolled.order">
            <edit_order_param order="this.assignedcontrolled.defaultorder" param="'range'" value="$range"/>
          </do_if>
        </do_if>
      </do_if>
      <remove_value name="$locrange"/>
    </do_if>
  </patch>
  <patch sinceversion="12">
    <do_if value="$evalware?">
      <set_value name="$thissector" exact="this.sector"/>
      <do_if value="not $resourceprobe_table?">
        <set_value name="$resourceprobe_table" exact="table[]"/>
      </do_if>
    </do_if>
  </patch>
  <patch sinceversion="13">
    <set_value name="$probesectors" exact="[]"/>
    <do_if value="@$miningbasket.count and @$gatheringspaces.count">
      <do_for_each name="$locspace" in="$gatheringspaces">
        <find_object name="$_resourceprobe" class="class.resourceprobe" space="$locspace" owner="this.owner"/>
        <append_to_list name="$probesectors" exact="$locspace"/>
        <remove_value name="$_resourceprobe"/>
      </do_for_each>
      <debug_text text="'PATCH: probesectors populated with %s sectors.'.[$probesectors.count]" filter="savegame"/>
    </do_if>
  </patch>
  <patch sinceversion="14">
    <!-- $thissector just convenient since it's created when in the section where $evalware is used then cleaned up after. -->
    <do_if value="@$miningbasket.count and $thissector?">
      <!-- $evalware changed from iterator to $miningbasket.{1} -->
      <set_value name="$evalware" exact="$miningbasket.{1}"/>
      <remove_value name="$found"/>
    </do_if>
  </patch>
  <patch sinceversion="17">
    <include_interrupt_actions ref="GetBlacklistgroup"/>
  </patch>
  <patch sinceversion="19">
    <!-- patch here rather than in order.assist so we patch only those ships that are affected. -->
    <do_if value="(@this.assignedcontrolled.defaultorder.id == 'Assist') and this.assignedcontrolled.defaultorder.$baseorder.$range and (this.assignedcontrolled.defaultorder.$baseorder.$range != $range)">
      <debug_text text="'PATCH: Resetting anchor from %s %s to %s %s.'.[@$range.knownname, $range, @this.assignedcontrolled.defaultorder.$baseorder.$range.knownname, @this.assignedcontrolled.defaultorder.$baseorder.$range]" filter="savegame"/>
      <set_value name="$range" exact="this.assignedcontrolled.defaultorder.$baseorder.$range"/>
      <clear_order_failure order="this.assignedcontrolled.defaultorder"/>
      <edit_order_param order="this.assignedcontrolled.defaultorder" param="'debugchance'" value="$debugchance"/>
    </do_if>
  </patch>
  <patch sinceversion="20">
    <set_value name="$preferownspace" exact="false"/>
  </patch>
  <patch sinceversion="21">
    <do_if value="$ware? and not $warebasket.indexof.{$ware}">
      <debug_text text="'PATCH: $ware %s not in warebasket. restarting.'.[$ware]" filter="savegame"/>
      <edit_order_param order="this.assignedcontrolled.order" param="'debugchance'" value="$debugchance"/>
    </do_if>
  </patch>
  <patch sinceversion="23">
    <do_if value="$ware?">
      <set_value name="$freecargo" exact="this.assignedcontrolled.cargo.{$ware}.free"/>
    </do_if>
    <do_if value="$spacedistancefactor?">
      <remove_value name="$spacedistancefactor"/>
    </do_if>
  </patch>
  <patch sinceversion="24">
    <set_value name="$warebasket_override" exact="[]"/>
  </patch>
  <patch sinceversion="25">
    <do_if value="not $secwares?">
      <set_value name="$secwares" exact="[]"/>
    </do_if>
  </patch>
  <patch sinceversion="27">
    <set_value name="$minrating" exact="3"/>
  </patch>
  <patch sinceversion="29">
    <do_if value="not $logbookentries?">
      <set_value name="$logbookentries" exact="true"/>
    </do_if>
  </patch>
  <patch sinceversion="30">
    <do_if value="not $allowIllegal?">
      <set_value name="$allowIllegal" exact="false"/>
    </do_if>
    <do_if value="not $enforceRouteIllegalLegality?">
      <set_value name="$enforceRouteIllegalLegality" exact="false"/>
    </do_if>
  </patch>
  <attention min="unknown">
    <actions>
      <do_if value="not $logbookentries?">
        <set_value name="$logbookentries" exact="true"/>
      </do_if>
      <do_if value="not $allowIllegal?">
        <set_value name="$allowIllegal" exact="false"/>
      </do_if>
      <do_if value="not $enforceRouteIllegalLegality?">
        <set_value name="$enforceRouteIllegalLegality" exact="false"/>
      </do_if>
      <do_if value="($minbuy gt 0) and ($minbuy ge $maxbuy)">
        <debug_text text="'minbuy is greater than maxbuy. cannot find spaces. resetting minbuy to 0.'" filter="error"/>
        <set_value name="$minbuy" exact="0"/>
      </do_if>
      <do_if value="($minsell gt 0) and ($minsell ge $maxsell)">
        <debug_text text="'minsell is greater than maxsell. cannot find spaces. resetting minsell to 0.'" filter="error"/>
        <set_value name="$minsell" exact="0"/>
      </do_if>

      <do_if value="this.assignedcontrolled.isonlineobject and not this.isplayerowned">
        <debug_text text="'Venture ship %s %s %s ordered to mine. num wares in basket: %s.'.[this.assignedcontrolled.idcode, this.assignedcontrolled.knownname, this.assignedcontrolled, @$warebasket.count]" chance="$debugchance"/>
        <do_if value="not @$warebasket.count">
          <debug_text text="'no warebasket defined. populating ware basket with cargo in hold. adding %s wares to the warebasket.'.[this.assignedcontrolled.cargo.count]" chance="$debugchance"/>
          <set_value name="$warebasket" exact="this.assignedcontrolled.cargo.list.clone"/>
        </do_if>

        <do_if value="this.assignedcontrolled.cargo.capacity.solid or this.assignedcontrolled.cargo.capacity.universal">
          <set_value name="$canminesolid"/>
        </do_if>
        <do_if value="this.assignedcontrolled.cargo.capacity.liquid or this.assignedcontrolled.cargo.capacity.universal">
          <set_value name="$canmineliquid"/>
        </do_if>

        <set_value name="$isvalidventure" exact="false"/>
        <do_if value="@$warebasket.count and ($canminesolid? or $canmineliquid?)">
          <do_all exact="$warebasket.count" counter="$i">
            <do_if value="this.assignedcontrolled.cargo.{$warebasket.{$i}}.max">
              <do_if value="($canminesolid? and ($warebasket.{$i}.waretransport == waretransport.solid)) or ($canmineliquid? and ($warebasket.{$i}.waretransport == waretransport.liquid))">
                <set_value name="$isvalidventure" exact="true"/>
                <debug_text text="'Venture ship %s %s %s can mine ware %s.'.[this.assignedcontrolled.idcode, this.assignedcontrolled.knownname, this.assignedcontrolled, $warebasket.{$i}]" chance="$debugchance"/>
                <break/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <do_else>
          <debug_text text="'Venture ship %s %s %s either does not have a ware basket or cannot carry mineable wares.'.[this.assignedcontrolled.idcode, this.assignedcontrolled.knownname, this.assignedcontrolled]" chance="$debugchance"/>
        </do_else>
        <remove_value name="$canminesolid"/>
        <remove_value name="$canmineliquid"/>

        <do_if value="not $isvalidventure">
          <debug_text text="'Venture ship %s %s %s was ordered to mine but cannot. Getting new orders.'.[this.assignedcontrolled.idcode, this.assignedcontrolled.knownname, this.assignedcontrolled, this.assignedcontrolled.defaultorder.id]" chance="$debugchance"/>
          <cancel_all_orders object="this.assignedcontrolled"/>
          <run_script name="'lib.request.orders'" sinceversion="1">
            <param name="object" value="this.assignedcontrolled"/>
            <param name="debugchance" value="$debugchance"/>
          </run_script>
        </do_if>
      </do_if>

      <include_interrupt_actions ref="GetBlacklistgroup"/>

      <label name="prep"/>

      <do_if value="$forceidle? or (not this.isplayerowned and this.sector and not this.hasrelation.enemy.{this.sector.owner})">
        <set_value name="$idleduration" min="20s" max="70s"/>
      </do_if>
      <remove_value name="$forceidle"/>

      <!-- Idle for a while -->
      <do_if value="$idleduration?">
        <run_script name="'move.idle'" >
          <param name="TimeOut" value="$idleduration"/>
        </run_script>
        <remove_value name="$idleduration"/>
      </do_if>

      <do_if value="$resourcescout or this.assignedcontrolled.iscapitalship">
        <remove_value name="$resupplying"/>
        <do_if value="$resourcescout">
          <do_if value="not this.assignedcontrolled.ammostorage.{deployablecategory.resourceprobe}.count">
            <debug_text text="'%s %s %s starting MiningRoutine as resource scout. trying to get resource probes.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled]" chance="$debugchance"/>
            <signal_objects object="this.assignedcontrolled" param="'resupply'" param2="[this.assignedcontrolled.ammostorage.{deployablecategory.resourceprobe}.count lt 1, null, deployablecategory.resourceprobe]" param3="$debugchance" comment="param2 = [urgent?, resupplystationID, $override_deployablecategory], param3 = $debugchance"/>
            <set_value name="$resupplying"/>
          </do_if>
        </do_if>
        <do_elseif value="this.assignedcontrolled.waretransport.indexof.{waretransport.solid} and not this.assignedcontrolled.units.{unitcategory.orecollector}.count">
          <debug_text text="'%s %s %s starting MiningRoutine with no ore collectors. trying to get some.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled]" chance="$debugchance"/>
          <signal_objects object="this.assignedcontrolled" param="'resupply'" param2="[true]" param3="$debugchance" comment="param2 = [urgent?, resupplystationID], param3 = $debugchance"/>
          <set_value name="$resupplying"/>
        </do_elseif>
        <do_elseif value="this.assignedcontrolled.waretransport.indexof.{waretransport.liquid} and not this.assignedcontrolled.units.{unitcategory.gascollector}.count">
          <debug_text text="'%s %s %s starting MiningRoutine with no gas collectors. trying to get some.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled]" chance="$debugchance"/>
          <signal_objects object="this.assignedcontrolled" param="'resupply'" param2="[true]" param3="$debugchance" comment="param2 = [urgent?, resupplystationID], param3 = $debugchance"/>
          <set_value name="$resupplying"/>
        </do_elseif>

        <do_if value="$resupplying?">
          <remove_value name="$resupplying"/>
          <wait exact="1s" sinceversion="9"/>

          <!-- NB: if we're still here, interrupt.restock couldn't find any places to buy ore collectors. idle and try again later. -->
          <do_if value="$resourcescout">
            <debug_text text="'unable to get resource probes. idling and trying again later.'" chance="$debugchance"/>
          </do_if>
          <do_else>
            <do_if value="@this.assignedcontrolled.order.isrunning">
              <set_order_failed order="this.assignedcontrolled.order" text="{1045,138}" comment="No available mining drones."/>
            </do_if>
            <debug_text text="'unable to get collector drones. idling and trying again later.'" chance="$debugchance"/>
          </do_else>
          <set_value name="$forceidle"/>
          <resume label="prep"/>
        </do_if>
      </do_if>

      <!-- basic checks first -->
      <label name="start" />

      <!-- check cargo capacity -->
      <do_if value="this.assignedcontrolled.cargo.capacity.all" max="0">
        <debug_text text="'%1 has cargo capacity of %2!'.[this.assignedcontrolled.knownname, this.assignedcontrolled.cargo.capacity.all]" chance="$debugchance" />
        <set_value name="$failreason" exact="'ERR_NO_CARGOSPACE'" />
        <set_value name="$failreason2" exact="'Macro: ' + this.assignedcontrolled.macro.name" />
        <resume label="finish" />
      </do_if>

      <!-- check basket -->
      <do_if value="not $warebasket.count and not @$homebase.isoperational">
        <do_if value="this.assignedcontrolled.job and this.assignedcontrolled.warebasket.count">
          <debug_text text="'job ship %s %s %s with job %s had no warebasket. recovering with job-defined basket: %s'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled, this.assignedcontrolled.job, this.assignedcontrolled.warebasket.list]" chance="$debugchance"/>
          <set_value name="$warebasket" exact="this.assignedcontrolled.warebasket.list"/>
          <do_if value="@$thisorder.exists">
            <edit_order_param order="this.assignedcontrolled.order" param="'warebasket'" value="$warebasket"/>
          </do_if>
          <wait exact="1s" sinceversion="8"/>
        </do_if>
        <do_else>
          <debug_text text="'mining without warebasket defined in jobs not supported!'" chance="$debugchance" />
          <set_value name="$failreason" exact="'ERR_NO_WAREBASKET'" />
          <set_value name="$failreason2" exact="'Job: ' + this.assignedcontrolled.job" />
          <resume label="finish" />
        </do_else>
      </do_if>

      <!-- Ranges -->
      <do_if value="not $range">
        <debug_text text="'range is null. attempting to recover.\ncommander setting: %s\ncommander sector: %s\njobmainsector: %s\ncurrent sector: %s'.[@this.assignedcontrolled.commanderentity.$config_subordinate_range, @this.assignedcontrolled.commanderentity.sector.knownname, @this.assignedcontrolled.jobmainsector.knownname, @this.assignedcontrolled.sector.knownname]" filter="error"/>
        <do_if value="@this.assignedcontrolled.jobmainsector">
          <set_value name="$range" exact="this.assignedcontrolled.jobmainsector"/>
        </do_if>
        <do_elseif value="this.assignedcontrolled.sector">
          <set_value name="$range" exact="this.assignedcontrolled.sector"/>
        </do_elseif>
        <do_elseif value="this.assignedcontrolled.zone.isclass.highway and this.assignedcontrolled.zone.destination.sector">
          <set_value name="$range" exact="this.assignedcontrolled.zone.destination.sector"/>
        </do_elseif>
        <do_else>
          <debug_text text="'failed to recover. $range is null. object is neither in a sector nor in a highway that goes to a sector.\nzone: %s %s\nzone parent: %s %s %s'.[@this.assignedcontrolled.zone.knownname, this.assignedcontrolled.zone, this.assignedcontrolled.zone.parent.class, @this.assignedcontrolled.zone.parent.knownname, this.assignedcontrolled.zone.parent]" filter="error"/>
        </do_else>
        <do_if value="$range and $thisorder.exists and $thisorder.$range?">
          <edit_order_param order="$thisorder" param="'range'" value="$range"/>
          <wait exact="1s" sinceversion="22"/>
        </do_if>
      </do_if>
      <do_elseif value="(typeof $range == datatype.keyword) and (($range == 'cluster') or ($range == 'sector') or ($range == 'zone'))">
        <!-- For jobs, get the string range 'zone', 'sector', 'cluster' -->
        <set_value name="$range" exact="this.assignedcontrolled.{$range}"/>
      </do_elseif>
      <do_elseif value="this.assignedcontrolled.commander and not this.assignedcontrolled.commander.hascontext.{$range} and this.assignedcontrolled.commander.sector.exists and (this.assignedcontrolled.order.id != 'Assist')">
        <set_value name="$range" exact="this.assignedcontrolled.commander.sector"/>
      </do_elseif>

      <do_if value="not $range">
        <debug_text text="'$range: %s still null after attempted recovery. idling before trying again later.\njobmainsector: %s %s, exists: %s\ncurrent sector: %s %s\nin highway: %s, highway destination sector: %s %s'.[@$range, @this.assignedcontrolled.jobmainsector.knownname, this.assignedcontrolled.jobmainsector, this.assignedcontrolled.jobmainsector.exists, @this.assignedcontrolled.sector.knownname, this.assignedcontrolled.sector, this.assignedcontrolled.zone.isclass.highway, @this.assignedcontrolled.zone.destination.sector.knownname, @this.assignedcontrolled.zone.destination.sector]" filter="error"/>
        <set_value name="$forceidle"/>
        <resume label="prep"/>
      </do_if>

      <set_value name="$samebuysellrange" exact="$minsell == $minbuy and $maxsell == $maxbuy"/>
      <do_if value="$strictgathersector? and $strictgathersector.exists and $strictgathersector.isclass.sector">
        <set_value name="$gatheringspaces" exact="[$strictgathersector]"/>
      </do_if>
      <do_elseif value="$precomputedgatherspaces? and $precomputedgatherspaces.count gt 0">
        <set_value name="$gatheringspaces" exact="$precomputedgatherspaces.clone"/>
      </do_elseif>
      <do_else>
        <run_script name="'lib.find.sectors.inrange'" result="$gatheringspaces" sinceversion="5">
          <param name="refobject" value="$range"/>
          <param name="mingatedistance" value="$minbuy"/>
          <param name="maxgatedistance" value="$maxbuy"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
      </do_else>
      <do_if value="$samebuysellrange">
        <!--The buy and sell ranges are the same, so clone the sectors.inrange results-->
        <set_value name="$sellspaces" exact="$gatheringspaces.clone"/>
      </do_if>
      <do_if value="this.isplayerowned and $maxbuy le 0 and not $gatheringspaces.indexof.{$range} and $range.isclass.sector">
        <debug_text text="'adding %s to gatheringspaces'.[$range.knownname]" chance="$debugchance"/>
        <append_to_list name="$gatheringspaces" exact="$range"/>
        <!-- if maxbuy is 0 and $range is not in $gatheringspaces, we must assume that the player wants us to go back to $range regardless of blacklist. -->
        <set_value name="$blacklist_overridebuy"/>
      </do_if>
      <debug_text text="'%s %s %s found %s gathering spaces.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled, $gatheringspaces.count]" chance="$debugchance"/>

      <do_if value="not $samebuysellrange">
        <run_script name="'lib.find.sectors.inrange'" result="$sellspaces" sinceversion="5">
          <param name="refobject" value="$range"/>
          <param name="mingatedistance" value="$minsell"/>
          <param name="maxgatedistance" value="$maxsell"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
      </do_if>
      <do_if value="this.isplayerowned and $maxsell le 0 and not $sellspaces.indexof.{$range} and $range.isclass.sector">
        <debug_text text="'adding %s to sellspaces'.[$range.knownname]" chance="$debugchance"/>
        <append_to_list name="$sellspaces" exact="$range"/>
        <!-- if maxsell is 0 and $range is not in $sellspaces, we must assume that the player wants us to go back to $range regardless of blacklist. -->
        <set_value name="$blacklist_overridesell"/>
      </do_if>
      <debug_text text="'%s %s %s found %s sell spaces.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled, $sellspaces.count]" chance="$debugchance"/>
      <remove_value name="$samebuysellrange"/>

      <do_if value="not $gatheringspaces.count and not $sellspaces.count">
        <debug_text text="'No gatheringspaces and no sellspaces. %s %s %s in sector %s cannot operate. Idling for a while and trying again later in case conditions change.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled, @this.assignedcontrolled.sector.knownname]"/>
        <do_if value="$debugchance">
          <debug_text text="'[GT-MiningRoutine][ship=' + this.assignedcontrolled.idcode + '] NO_GATHER_OR_SELL minbuy=' + $minbuy + ' maxbuy=' + $maxbuy + ' minsell=' + $minsell + ' maxsell=' + $maxsell + ' range=' + $range + ' strictGather=' + (if $strictgathersector? and $strictgathersector.exists then $strictgathersector.knownname else 'null')" chance="$debugchance"/>
        </do_if>
        <set_value name="$forceidle"/>
        <resume label="prep"/>
      </do_if>

      <do_if value="this.isplayerowned and $gatheringspaces.count gt 1">
        <do_for_each name="$locspace" in="$gatheringspaces">
          <do_if value="$locspace.cluster">
            <do_if value="not $loccluster?">
              <set_value name="$loccluster" exact="$locspace.cluster"/>
            </do_if>
            <do_elseif value="$loccluster != $locspace.cluster">
              <set_value name="$multicluster"/>
              <break/>
            </do_elseif>
          </do_if>
        </do_for_each>
        <do_if value="@$loccluster and not $multicluster?">
          <set_value name="$singlecluster"/>
        </do_if>
        <remove_value name="$multicluster"/>
        <remove_value name="$loccluster"/>
      </do_if>

      <do_if value="@this.hasrelation.enemy.{$range.owner} and not @this.assignedcontrolled.commander.hascontext.{$range}">
        <do_all exact="$gatheringspaces.count" counter="$i">
          <do_if value="$gatheringspaces.{$i}.owner == this.owner">
            <set_value name="$locrange" exact="$gatheringspaces.{$i}"/>
            <break/>
          </do_if>
          <do_elseif value="not this.hasrelation.enemy.{$gatheringspaces.{$i}.owner}">
            <set_value name="$locfallback" exact="$gatheringspaces.{$i}"/>
          </do_elseif>
        </do_all>

        <do_if value="not $locrange? and $locfallback?">
          <set_value name="$locrange" exact="$locfallback"/>
        </do_if>
        <remove_value name="$locfallback"/>

        <do_if value="$locrange?">
          <set_value name="$range" exact="$locrange"/>
          <debug_text text="'old anchor space was hostile. changing to %s %s.'.[$range.class, $range.knownname]" chance="$debugchance"/>
          <do_if value="@$thisorder.$range.isclass.space">
            <edit_order_param order="$thisorder" param="'range'" value="$range"/>
            <do_if value="this.assignedcontrolled.defaultorder == $thisorder">
              <edit_order_param order="this.assignedcontrolled.defaultorder" param="'range'" value="$range"/>
            </do_if>
            <!-- wait until order is restarted by param changing. -->
            <wait sinceversion="10"/>
          </do_if>
        </do_if>
        <remove_value name="$locrange"/>
      </do_if>

      <do_if value="this.sector and this.hasrelation.enemy.{this.sector.owner} and not @this.hasrelation.enemy.{$range.owner} and not @this.assignedcontrolled.commander.hascontext.{$range}">
        <debug_text text="'sector we are currently in is hostile. moving to safe space.'" chance="$debugchance"/>
        <!-- handling for nopath unnecessary -->
        <run_script name="'move.generic'" sinceversion="10">
          <param name="destination" value="$range"/>
          <param name="endintargetzone" value="true"/>
          <param name="debugchance" value="$debugchance" />
        </run_script>
        <resume label="prep"/>
      </do_if>

      <!-- primary loop start -->
      <label name="loop" />

      <do_if value="$duration and ((player.age - $time_start) gt $duration)">
        <resume label="finish"/>
      </do_if>

      <do_if value="$primaryTargetStations.count gt 0 and $warebasket.count == 1 and not $resourcescout and $physicalStorageAbortPercent gt 0 and $checkDemandFirst">
        <set_value name="$physGateWare" exact="$warebasket.{1}"/>
        <run_script name="'lib.gt.miner_physical_storage_gate'" result="$physGate">
          <param name="ship" value="this.ship"/>
          <param name="ware" value="$physGateWare"/>
          <param name="primaryTargetStations" value="$primaryTargetStations"/>
          <param name="physicalStorageAbortPercent" value="$physicalStorageAbortPercent"/>
          <param name="checkDemandFirst" value="$checkDemandFirst"/>
          <param name="resourcescout" value="$resourcescout"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
        <do_if value="$physGate.$Trips? and $physGate.$Trips">
          <set_value name="$physGateAction" exact="if this.assignedcontrolled.cargo.{$physGateWare}.count gt 0 then 'sellwares' else 'finish'"/>
          <debug_text text="'[GT-MiningRoutine] ' + this.assignedcontrolled.idcode + ': Physical storage gate action=' + $physGateAction + ' ware=' + $physGateWare.name" chance="$debugchance"/>
          <do_if value="this.assignedcontrolled.cargo.{$physGateWare}.count gt 0">
            <resume label="sellwares"/>
          </do_if>
          <resume label="finish"/>
        </do_if>
        <remove_value name="$physGateWare"/>
        <remove_value name="$physGate"/>
        <remove_value name="$physGateAction"/>
      </do_if>

      <!-- v0.13.11: probe lifecycle (DEPLOY -> RECOVER -> BUY) was previously located here
           at the top of the loop. It has been ported back to v8's structure and lives AFTER
           the MiningCollect immediate sub-order at the end of this loop iteration so probes
           are deployed on freshly-mined asteroid fields (and stale probes are recovered
           against the same sector the ship just finished collecting in). See the new block
           right after the `<create_order id='MiningCollect' immediate='true'>` call. -->

      <do_if value="not $resourcescout and this.assignedcontrolled.iscapitalship and ((this.assignedcontrolled.waretransport.indexof.{waretransport.solid} and not this.assignedcontrolled.units.{unitcategory.orecollector}.count) or (this.assignedcontrolled.waretransport.indexof.{waretransport.liquid} and not this.assignedcontrolled.units.{unitcategory.gascollector}.count))">
        <debug_text text="'%s %s %s has no collector drones. looping back to prep.'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled]" chance="$debugchance"/>
        <resume label="prep"/>
      </do_if>

      <do_if value="player.age gt @$next_resupply_check" chance="30">
        <debug_text text="'%1 (%2) ready to resupply.'.[this.assignedcontrolled.knownname, this.assignedcontrolled]" chance="$debugchance"/>
        <signal_objects object="this.assignedcontrolled" param="'resupply'" param2="[false]" param3="$debugchance" comment="param2 = [urgent?, resupplystationID], param3 = $debugchance"/>
        <set_value name="$next_resupply_check" exact="player.age + 30min"/>
      </do_if>

      <!-- sell wares first if cargo full or less than 50% free cargo -->
      <do_if value="this.assignedcontrolled.cargo.free.all le 0 or (not $cannotsell? and this.assignedcontrolled.cargo.capacity.all gt 0 and ((this.assignedcontrolled.cargo.free.all)f / this.assignedcontrolled.cargo.capacity.all le 0.5))">
        <resume label="sellwares" />
      </do_if>
      <do_else>
        <debug_text text="player.age + ' looking good, starting new mining run'" chance="$debugchance" />
      </do_else>
      <remove_value name="$cannotsell"/>

      <!-- command action -->
      <set_command_action commandaction="commandaction.searchingresources" />
      <!-- Optional: vanilla leaves resourceprobescantime unused (disabled wait in order.mining.routine). When off, GT matches that. When on, apply engine wait (+5s per extra faction probe in sector), scaled by GT pilot level. -->
      <do_if value="this.assignedcontrolled.resourceprobescantime and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Miner? and global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel? and global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel">
        <set_value name="$scanWaitBase" exact="this.assignedcontrolled.resourceprobescantime"/>
        <set_value name="$scanWaitScaled" exact="$scanWaitBase"/>
        <!-- GT XP mode: linear probe-scan reduction from full wait at level 1 to 5s at level 15. -->
        <do_if value="not (global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) and $scanWaitBase gt 5s">
          <set_value name="$gtPilotLevel" exact="1"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
            <set_value name="$gtPilotLevel" exact="[(global.$GT_Pilots.{this.ship.pilot}.$Level), 15].min"/>
            <do_if value="$gtPilotLevel lt 1">
              <set_value name="$gtPilotLevel" exact="1"/>
            </do_if>
          </do_if>
          <set_value name="$scanWaitBaseSec" exact="($scanWaitBase / 1s)f"/>
          <set_value name="$scanWaitScaledSec" exact="$scanWaitBaseSec - (($scanWaitBaseSec - 5.0) * ($gtPilotLevel - 1) / 14.0)"/>
          <set_value name="$scanWaitScaled" exact="($scanWaitScaledSec * 1s)"/>
          <debug_text text="'[GT-MiningRoutine] ' + this.assignedcontrolled.idcode + ': Probe scan wait GT level ' + $gtPilotLevel + ' base=' + $scanWaitBase + ' scaled=' + $scanWaitScaled" chance="$debugchance"/>
          <remove_value name="$gtPilotLevel"/>
          <remove_value name="$scanWaitBaseSec"/>
          <remove_value name="$scanWaitScaledSec"/>
        </do_if>
        <wait exact="$scanWaitScaled" sinceversion="28"/>
        <remove_value name="$scanWaitBase"/>
        <remove_value name="$scanWaitScaled"/>
      </do_if>

      <!-- Create the mining basket -->
      <create_list name="$miningbasket" />
      <!-- Galaxy Miner passes one pre-selected ware per slice. Skip the expensive homebase
           shortage-report pass (can take tens of seconds on large stations) and go straight to
           find_resource. This fast path used to run after generate_shortage_reports, leaving ships
           stuck in commandaction.searchingresources while blocked on shortage scan. -->
      <do_if value="$primaryTargetStations.count gt 0 and $warebasket.count == 1">
        <set_value name="$miningbasket" exact="$warebasket.clone"/>
        <debug_text text="'[GT-MiningRoutine] ' + this.assignedcontrolled.idcode + ': Preserve selected ware from caller: ' + $warebasket.{1}.name" chance="$debugchance"/>
      </do_if>
      <!-- When Mining for commander -->
      <do_elseif value="@$homebase.isoperational">
        <!-- update the wares we deal with for a new trade run - ensure that we don't miss any wares if the list has changed due to the homebase being expanded -->
        <set_value name="$resources" exact="$homebase.resources.list" />

        <set_value name="$supplyresources" exact="$homebase.supplyresources.list" />
        <do_all exact="$supplyresources.count" counter="$i">
          <do_if value="not $resources.indexof.{$supplyresources.{$i}}">
            <append_to_list name="$resources" exact="$supplyresources.{$i}"/>
          </do_if>
        </do_all>

        <!-- support working for trade stations / warehouses as well -->
        <set_value name="$tradewares" exact="$homebase.tradewares.list" />
        <do_all exact="$tradewares.count" counter="$i">
          <do_if value="not $resources.indexof.{$tradewares.{$i}}">
            <append_to_list name="$resources" exact="$tradewares.{$i}" />
          </do_if>
        </do_all>
        <remove_value name="$tradewares" />

        <do_if value="$homebase.exists and not $homebase.iswreck and not $homebase.isrealclass.ship">
          <do_if value="not $skipshortage?">
            <set_value name="$resources_shortage" exact="[]"/>
            <set_value name="$resources_critical" exact="[]"/>
            <set_value name="$resources_to_check" exact="[]"/>
            <do_for_each name="$locresource" in="$resources">
              <do_if value="this.assignedcontrolled.cargo.{$locresource}.max gt 0">
                <append_to_list name="$resources_to_check" exact="$locresource"/>
              </do_if>
            </do_for_each>
            <debug_text text="'%s resources to check'.[$resources_to_check.count]" chance="$debugchance"/>
            <do_for_each name="$shortagetype" in="[class.production, class.buildmodule]">
              <generate_shortage_reports object="$homebase" type="$shortagetype" relevantwares="$resources_to_check"
                                         insufficient="$table_insufficient" insufficientthreshold="param.criticalwares.insufficientthreshold" insufficientthresholdcutoff="param.criticalwares.insufficientthresholdcutoff"
                                         shortage="$table_shortage" shortagethreshold="param.criticalwares.shortagethreshold"/>

              <do_for_each name="$locware" in="$table_insufficient">
                <!--Remove insufficient wares from the resources to check as they are already added to both lists-->
                <remove_from_list name="$resources_to_check" exact="$locware"/>
                <append_to_list name="$resources_shortage" exact="$locware"/>
                <append_to_list name="$resources_critical" exact="$locware"/>
              </do_for_each>
              <do_for_each name="$locware" in="$table_shortage">
                <do_if value="not $resources_shortage.indexof.{$locware}">
                  <append_to_list name="$resources_shortage" exact="$locware"/>
                </do_if>
              </do_for_each>
            </do_for_each>
            <remove_value name="$resources_to_check"/>
            <remove_value name="$table_shortage"/>
            <remove_value name="$table_insufficient"/>

            <do_if value="@$resources_shortage.count">
              <do_for_each name="$locware" in="$resources_shortage" reverse="true">
                <find_buy_offer result="$evalbuyoffer" tradepartner="this.assignedcontrolled" buyer="$homebase" wares="$locware"/>
                <do_if value="not $evalbuyoffer or not $homebase.maybuyfrom.[this.owner, $locware]">
                  <do_if value="$resources_critical.indexof.{$locware}">
                    <debug_text text="'critical ware: %s not wanted by station. ignoring shortage.'.[$locware]" chance="$debugchance"/>
                    <remove_from_list name="$resources_critical" exact="$locware"/>
                  </do_if>
                  <debug_text text="'shortage ware: %s not wanted by station. ignoring shortage.'.[$locware]" chance="$debugchance"/>
                  <remove_value name="$resources_shortage.{loop.index}"/>
                </do_if>
              </do_for_each>
              <remove_value name="$evalbuyoffer"/>

              <do_if value="$resources_shortage.count">
                <set_value name="$usedshortage"/>
                <debug_text text="'shortage detected. will try to purchase %s wares for %s %s %s. num critical wares: %s'.[$resources_shortage.count, @$homebase.idcode, @$homebase.knownname, $homebase, $resources_critical.count]" chance="$debugchance"/>
                <set_value name="$resources" exact="$resources_shortage"/>
                <do_if value="$resources_critical.count">
                  <debug_text text="'critical shortage detected of %s wares.'.[$resources_critical.count]" chance="$debugchance"/>
                  <set_value name="$resources" exact="$resources_critical"/>
                </do_if>
              </do_if>
            </do_if>

          </do_if>
        </do_if>

        <do_if value="$warebasket_override.count">
          <do_for_each name="$locware" in="$resources" reverse="true">
            <do_if value="not $warebasket_override.indexof.{$locware}">
              <remove_from_list name="$resources" exact="$locware"/>
              <debug_text text="'%s not in manual ware basket. removing.'.[$locware]" chance="$debugchance2"/>
            </do_if>
          </do_for_each>
          <do_if value="not $resources.count">
            <debug_text text="'no wares left after filtering through manual ware basket.'" chance="$debugchance2"/>
            <do_if value="$usedshortage?">
              <debug_text text="'skipping shortages and trying again.'" chance="$debugchance2"/>
              <remove_value name="$usedshortage"/>
              <set_value name="$skipshortage"/>
              <resume label="loop"/>
            </do_if>
            <set_value name="$failreason" exact="'ERR_EMPTY_WAREBASKET'"/>
            <debug_text text="'no wares left after filtering through manual ware basket.'" chance="$debugchance2"/>
            <set_value name="$failurereason" exact="{1045, 113}" comment="No matching trade offer found."/>
            <do_if value="@this.assignedcontrolled.order.isrunning">
              <set_order_failed order="this.assignedcontrolled.order" text="$failurereason"/>
            </do_if>
          </do_if>
        </do_if>

          <!-- start with an empty list in case warebasket contains outdated wares. -->
          <create_list name="$locwares"/>
          <!-- Resources + Tradewares to Warebasket -->
          <do_for_each name="$locware" in="$resources">
            <!-- Minable wares, with capacity to carry them and that are not already in the ware list -->
            <do_if value="($locware.hastag.minable) and (this.assignedcontrolled.cargo.{$locware}.max gt 0) and (not $locwares.indexof.{$locware})">
              <!-- either is not a big ship, or the ware is not mineral, or it is mineral and needs collectors -->
              <do_if value="(not this.assignedcontrolled.iscapitalship) or (not $locware.hastag.mineral) or (this.object.units.collect.{$locware}.count)">
                <append_to_list name="$locwares" exact="$locware"/>
                <do_if value="not $warebasket.indexof.{$locware}">
                  <set_value name="$basketchanged"/>
                </do_if>
              </do_if>
            </do_if>
          </do_for_each>

          <!-- check to see if we either added something or removed something from our warebasket. -->
          <do_if value="$basketchanged? or ($warebasket.count != $locwares.count)">
            <debug_text text="'%s %s %s updating warebasket. wares added? %s, wares removed? %s\nnew warebasket: %s'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled, $basketchanged?, $locwares.count != $warebasket.count, $warebasket]" chance="$debugchance"/>
            <set_value name="$warebasket" exact="$locwares.clone"/>
            <!-- edit_order_param deprecated here since shortage wares are now shown in the UI -->
            <wait exact="1ms" sinceversion="6" chance="0"/>
          </do_if>
          <remove_value name="$locwares"/>

          <do_if value="not $warebasket.count">
            <debug_text text="'Home base: %s %s %s does not need anything at the moment. Waiting to check again.'.[@$homebase.idcode, @$homebase.knownname, $homebase]" chance="$debugchance"/>
            <set_value name="$forceidle"/>
            <resume label="prep"/>
          </do_if>

          <!-- we build our shopping list by intersecting our warebasket and the resources of our homebase -->
          <set_value name="$shoppinglist" exact="table[]" />
          <!-- Get the buy offers with this ships as partner -->
          <find_buy_offer buyer="$homebase" multiple="true" result="$buyoffers" wares="$warebasket" tradepartner="this.assignedcontrolled"/>
          <debug_text text="player.age + ' homebase %1 [%2] has %3 offers for %4'.[$homebase.knownname, $homebase, $buyoffers.count, $warebasket]" chance="$debugchance" />
          <!-- Create the shoppinglist table -->
          <do_if value="$buyoffers.count" min="1">
            <!-- use the buyoffers on our homebase to determine resource need -->
            <do_all counter="$b" exact="$buyoffers.count">
              <set_value name="$buyoffer" exact="$buyoffers.{$b}" />
              <set_value name="$buyofferamount" exact="$buyoffer.offeramount.{this.assignedcontrolled}" />
              <get_ware_reservation object="$homebase" ware="$buyoffer.ware" type="sell" virtual="true" result="$reserved" />
              <debug_text text="player.age + ' %1 wants %5(want %2, expecting %4) units of %3'.[$homebase.knownname, $buyofferamount, $buyoffer.ware, $reserved, [$buyofferamount - $reserved, 0].max]" chance="$debugchance" />
              <!-- Table key: buyoffer, value: needed amount (buy offer amount - reserved) / target amount -->
              <set_value name="$shoppinglist.{$buyoffer}" exact="[$buyofferamount - $reserved, 0].max / ([$homebase.cargo.{$buyoffer.ware}.target, 1].max)f"/>
            </do_all>
            <remove_value name="$reserved" />
            <remove_value name="$buyoffer" />
            <remove_value name="$buyoffers" />
          </do_if>
          <!-- Minable resources that the station wants -->
          <do_if value="$shoppinglist.keys.count">
            <!-- Sorted by needed  -->
            <set_value name="$neededbuyoffers" exact="$shoppinglist.keys.sorted" />
            <create_list name="$miningbasket" comment="Ware list sorted by most needed wares" />
            <create_list name="$neededamounts" comment="Associated offer amounts for the sorted wares" />
            <create_list name="$priorities"/>
            <!-- Iterate in reverse to put the most needed (last) into the first places -->
            <do_all exact="$neededbuyoffers.count" counter="$i" reverse="true">
              <!-- key: buy offer ware, value: offer amount -->
              <append_to_list name="$miningbasket" exact="$neededbuyoffers.{$i}.ware" />
              <append_to_list name="$neededamounts" exact="$neededbuyoffers.{$i}.offeramount.{this.assignedcontrolled}"/>
              <append_to_list name="$priorities" exact="$shoppinglist.{$neededbuyoffers.{$i}}"/>
            </do_all>
            <do_all exact="$miningbasket.count" counter="$i" chance="$debugchance">
              <debug_text text="'ware: %s, amount: %s, priority: %s'.[$miningbasket.{$i}, $neededamounts.{$i}, $priorities.{$i}]"/>
            </do_all>
            <remove_value name="$shoppinglist" />
            <remove_value name="$neededbuyoffers" />
          </do_if>
          <do_else>
            <!-- Free-miner path (aiscript below) falls back to $warebasket when buy-offer scoring fails. Station miners used to leave $miningbasket empty here, so find_resource never ran even with fields in-sector. Galaxy Miner passes a pre-filtered basket â€” still mine if offers are missing/stale. -->
            <debug_text text="player.age + ' homebase: no shoppinglist from buy offers â€” falling back to warebasket for mining'" chance="$debugchance" />
            <set_value name="$miningbasket" exact="$warebasket.clone"/>
            <shuffle_list list="$miningbasket"/>
          </do_else>
      </do_elseif>
      <!-- Free miner -->
      <do_else>
        <!-- Ware Selection: two choices. Either:
                Look through everything in $sellspaces and pick the ware that sells for the biggest price. (Barring travel cost, that would be the most profitable because costs are only capital. Ideal, but more expensive since more buy offers will have to be processed.)
                Or tally three (or some arbitrary number. only important that it's consistent.) prices, get the average (or just add them if you can always relibaly get the same number of offers for everything in the ware basket) and compare those. (Cheaper, but not as smart.)
                
                Idea is to guess which ware will be in high demand AFTER we're done mining.
                So we look at what's selling well now, but we don't do a comprehensive search because we have no idea if those conditions will hold later. -->
        <do_if value="($warebasket.count gt 1) and ((global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly and this.ship.pilot? and this.ship.pilot.skill.piloting ge 6) or ((not global.$GT_GlobalSettings? or not global.$GT_GlobalSettings.$XP? or not global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? or not global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) and this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level ge 6) or ($effectiveskill == 100))">
          <set_value name="$buyoffers_evaluate" exact="[]"/>
          <set_value name="$miningtable" exact="table[]"/>

          <!-- iterate over all of the clusters in the defined range. sellspaces is sorted by distance. -->
          <do_all exact="$sellspaces.count" counter="$i">
            <!-- find all buy offers in each space. -->
            <find_buy_offer tradepartner="this.assignedcontrolled" wares="$warebasket" space="$sellspaces.{$i}" result="$buyoffers_evaluate" multiple="true"/>
            <do_if value="$playerStationsOnly and $buyoffers_evaluate.count">
              <set_value name="$buyoffers_filtered" exact="[]"/>
              <do_for_each name="$locoffer" in="$buyoffers_evaluate">
                <do_if value="$locoffer? and $locoffer.buyer? and $locoffer.buyer.exists and $locoffer.buyer.owner == this.owner">
                  <append_to_list name="$buyoffers_filtered" exact="$locoffer"/>
                </do_if>
              </do_for_each>
              <set_value name="$buyoffers_evaluate" exact="$buyoffers_filtered"/>
              <remove_value name="$buyoffers_filtered"/>
            </do_if>
            <debug_text text="player.age + ' found %1 buy offers in %2. ware basket: %3'.[$buyoffers_evaluate.count, $sellspaces.{$i}.knownname, $warebasket]" chance="0"/>
            <wait min="30ms" max="70ms"/>
            <!-- if we found any ... -->
            <do_if value="$buyoffers_evaluate.count">
              <!-- shuffle list so that offers with the same relprice are still in a random order and not in the consistent order that the stations were found in -->
              <shuffle_list list="$buyoffers_evaluate"/>
              <!-- sort buy offers by relative price. relative price is the amount of deviation from average price. -->
              <sort_trades name="$buyoffers_evaluate" tradelist="$buyoffers_evaluate" sorter="relativeprice"/>
              <do_all exact="$buyoffers_evaluate.count" counter="$j" reverse="true">
                <!-- record this trade if:
                      we have not recorded a trade for this ware yet,
                      or we found a better price for this ware. (only relevant if we ever evaluate more than one cluster) -->
                <do_if value="not $miningtable.{$buyoffers_evaluate.{$j}.ware}? or ($buyoffers_evaluate.{$j}.relativeprice gt $miningtable.{$buyoffers_evaluate.{$j}.ware})">
                  <set_value name="$miningtable.{$buyoffers_evaluate.{$j}.ware}" exact="$buyoffers_evaluate.{$j}.relativeprice"/>
                  <debug_text text="'adding %1 to mining basket. price: %2. mining table: %3.'.[$buyoffers_evaluate.{$j}.ware, $buyoffers_evaluate.{$j}.relativeprice, $miningtable]" chance="$debugchance"/>
                </do_if>
                <!-- if we have records for all wares we are interested in, we need not look any further to get an estimate.
                      update: we don't really need the whole basket because we'll end up only getting one ware. stop after finding offers for two wares to limit the number of times we have to iterate.
                        update reverted because it could introduce the problem of mining ships never going after a third ware in their basket because two wares are always in demand in their starting cluster.
                        reduces the number of clusters evaluated from around 9 on average to 1 or 2 though, so performance gain could be substantial. might prove necessary. -->
                <!--<do_if value="$miningtable.keys.count == [2, $warebasket.count].min">-->
                <do_if value="$miningtable.keys.count == $warebasket.count">
                  <debug_text text="'offers found for everything in the basket! looked through ' + $i + ' clusters.'" chance="$debugchance"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="$miningtable.keys.count == $warebasket.count">
                <break/>
              </do_if>
            </do_if>
          </do_all>

          <do_if value="$miningtable.keys.count">
            <debug_text text="'trade offers for %1 wares found. %2 wares in the ware basket.'.[$miningtable.keys.count, $warebasket.count]" chance="$debugchance"/>
            <!-- if the miner is really good, the list will be sorted by best price over the space evaluated. again, only relevant if more than one cluster is ever evaluated. -->
            <do_if value="true" chance="$effectiveskill">
              <set_value name="$sortedbasket" exact="$miningtable.keys.sorted"/>
              <do_all exact="$sortedbasket.count" counter="$i" reverse="true">
                <append_to_list name="$miningbasket" exact="$sortedbasket.{$i}"/>
              </do_all>
              <remove_value name="$sortedbasket"/>
            </do_if>
            <do_else>
              <set_value name="$miningbasket" exact="$miningtable.keys.list"/>
              <shuffle_list list="$miningbasket"/>
            </do_else>
            <debug_text text="'mining basket assembled: ' + $miningbasket" chance="$debugchance"/>
          </do_if>
          <do_else>
            <set_value name="$failurereason" exact="{1045, 107}" comment="No buyers found in range."/>
            <debug_text text="'no offers found after going through %1 clusters. %2 wares in the warebasket.'.[$sellspaces.count, $warebasket.count]" chance="$debugchance"/>
          </do_else>
          <!--<debug_text text="'%1 selected. prices: %2, %3, %4'.[$miningbasket.{1}, $miningtable.{$miningbasket.{1}}, $miningtable.{$miningbasket.{2}}, $miningtable.{$miningbasket.{3}}]" chance="$debugchance"/>-->

          <!-- if we are ever in a situation where we do not find buy offers for everything in our ware basket, add everything in the ware basket anyway
                  because there might not be demand for these wares right now, but there might be demand for them later. they will have lower priority. -->
          <do_if value="$miningbasket.count lt $warebasket.count">
            <do_all exact="$warebasket.count" counter="$i">
              <do_if value="not $miningbasket.indexof.{$warebasket.{$i}}">
                <append_to_list name="$miningbasket" exact="$warebasket.{$i}"/>
              </do_if>
            </do_all>
          </do_if>
          <remove_value name="$miningtable"/>
          <remove_value name="$buyoffers_evaluate"/>
        </do_if>
        <do_else>
          <!-- Really bad miners just get whatever is handy. -->
          <set_value name="$miningbasket" exact="$warebasket.clone"/>
          <shuffle_list list="$miningbasket"/>
          <debug_text text="'backup mining basket: ' + $miningbasket" chance="$debugchance"/>
        </do_else>
      </do_else>

      <!-- No minable resources -->
      <do_if value="not $miningbasket.count" >
        <debug_text text="player.age + ' unable to find minable resources, waiting...'" chance="$debugchance" />
        <do_if value="$debugchance">
          <debug_text text="'[GT-MiningRoutine][ship=' + this.assignedcontrolled.idcode + '] EMPTY_MINING_BASKET warebasket=' + $warebasket + ' homebase=' + (if @$homebase.exists then $homebase.idcode else 'null') + ' homebaseOp=' + @$homebase.isoperational + ' playerStationsOnly=' + $playerStationsOnly" chance="$debugchance"/>
        </do_if>
        <do_if value="@$failurereason and @this.assignedcontrolled.order.isrunning">
          <do_if value="$debugchance">
            <debug_text text="'[GT-Miner-DIAG] FAIL_EMPTY_BASKET ship=' + this.assignedcontrolled.idcode + ', reason=' + $failurereason + ', default=' + (if this.assignedcontrolled.defaultorder? then @this.assignedcontrolled.defaultorder.id else 'NONE') + ', current=' + (if this.assignedcontrolled.order? then @this.assignedcontrolled.order.id else 'NONE') + ', commander=' + (if this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists then this.assignedcontrolled.commander.idcode else 'NONE') + ', warebasket=' + $warebasket + ', miningbasket=' + $miningbasket" chance="100"/>
          </do_if>
          <set_order_failed order="this.assignedcontrolled.order" text="$failurereason"/>
        </do_if>
        <remove_value name="$failurereason"/>
        <!-- Idle for a while -->
        <run_script name="'move.idle'" >
          <param name="Min" value="30s" />
          <param name="Max" value="90s" />
        </run_script>
        <resume label="loop"/>
      </do_if>
      <remove_value name="$failurereason"/>

      <!-- Re-check cargo before resource search: drones may have filled hold during prep -->
      <do_if value="this.assignedcontrolled.cargo.free.all le 0">
        <resume label="sellwares" />
      </do_if>

      <!-- Unified resource locate (lib.gt.miner_find_target): single pass per ware, optional caller-resolved target, cooperative yields. -->
      <set_value name="$secwares" exact="[]"/>
      <remove_value name="$sector"/>
      <remove_value name="$pos_sector"/>
      <remove_value name="$ware"/>

      <do_if value="$resolvedsector? and $resolvedsector.exists and $resolvedpos? and $miningbasket.count">
        <set_value name="$ware" exact="$miningbasket.{1}"/>
        <set_value name="$sector" exact="$resolvedsector"/>
        <set_value name="$pos_sector" exact="$resolvedpos"/>
        <debug_text text="'[GT-MiningRoutine] ' + this.assignedcontrolled.idcode + ': Caller-resolved target ware=' + $ware.name + ' sector=' + $sector.knownname" chance="$debugchance"/>
      </do_if>
      <do_else>
        <include_interrupt_actions ref="GetBlacklistgroup"/>
        <set_value name="$findBlacklistGroup" exact="if $blacklistgroup? then $blacklistgroup else null"/>
        <set_value name="$searchYieldMs" exact="15"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs?">
          <set_value name="$searchYieldMs" exact="global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs"/>
        </do_if>
        <do_if value="$searchYieldMs lt 1">
          <set_value name="$searchYieldMs" exact="1"/>
        </do_if>
        <do_if value="$searchYieldMs gt 100">
          <set_value name="$searchYieldMs" exact="100"/>
        </do_if>
        <wait min="1ms" max="19ms"/>
        <do_for_each name="$locWare" in="$miningbasket">
          <do_if value="@$sector.exists">
            <break/>
          </do_if>
          <set_value name="$ware" exact="$locWare"/>
          <run_script name="'lib.gt.miner_find_target'" result="$findTargetResult">
            <param name="ship" value="this.assignedcontrolled"/>
            <param name="ware" value="$ware"/>
            <param name="gatherSpaces" value="$gatheringspaces"/>
            <param name="minrating" value="$minrating"/>
            <param name="deepspace" value="$deepspace"/>
            <param name="preferownspace" value="$preferownspace"/>
            <param name="effectiveskill" value="$effectiveskill"/>
            <param name="secwares" value="$secwares"/>
            <param name="searchYieldMs" value="$searchYieldMs"/>
            <param name="staggerMs" value="0"/>
            <param name="blacklistgroup" value="$findBlacklistGroup"/>
            <param name="debugchance" value="$debugchance"/>
          </run_script>
          <do_if value="$findTargetResult.$Found? and $findTargetResult.$Found and $findTargetResult.$Sector? and @$findTargetResult.$Sector.exists">
            <set_value name="$sector" exact="$findTargetResult.$Sector"/>
            <set_value name="$pos_sector" exact="$findTargetResult.$Pos"/>
          </do_if>
          <remove_value name="$findTargetResult"/>
        </do_for_each>
        <remove_value name="$findBlacklistGroup"/>
        <remove_value name="$searchYieldMs"/>
        <do_if value="$blacklistgroup?">
          <remove_value name="$blacklistgroup"/>
        </do_if>
      </do_else>

      <!-- Check the result zone -->
      <do_if value="@$sector.exists">
        <debug_text text="player.age + ' there is %1 in sector %2'.[$ware, $sector.knownname]" chance="$debugchance" />
        <!-- Check the secondary wares vs the warebasket -->
        <do_all exact="$secwares.count" counter="$i" reverse="true">
          <do_if value="(not $miningbasket.indexof.{$secwares.{$i}}) or ($secwares.{$i} == $ware)">
            <remove_value name="$secwares.{$i}" />
          </do_if>
        </do_all>
        <!-- When Mining for commander, make a virtual reservation (to coordinate other miners) -->
        <do_if value="@$homebase.isoperational">
          <!-- min amount of ware. Default: max free space in cargo ship or amount homebase wants, whichever is the smaller value -->
          <set_value name="$minamount" exact="this.assignedcontrolled.cargo.{$ware}.free" />
          <set_value name="$neededIdx" exact="$miningbasket.indexof.{$ware}"/>
          <do_if value="$neededamounts? and $neededIdx? and $neededIdx gt 0 and $neededIdx le $neededamounts.count and $neededamounts.{$neededIdx}?">
            <set_value name="$minamount" exact="$neededamounts.{$neededIdx}" />
          </do_if>
          <do_if value="$minamount gt this.assignedcontrolled.cargo.{$ware}.free">
            <set_value name="$minamount" exact="this.assignedcontrolled.cargo.{$ware}.free" />
          </do_if>
          <debug_text text="'reserving storage for %s %s'.[$minamount, $ware]" chance="$debugchance"/>
          <!-- virtual reservation -->
          <add_ware_reservation amount="$minamount" type="sell" reserver="this.assignedcontrolled" object="$homebase" duration="5h" virtual="true" ware="$ware" replace="true" />
          <!-- Clear values that are not needed anymore -->
          <remove_value name="$minamount" />
          <remove_value name="$neededIdx" />
          <remove_value name="$neededamounts" />
        </do_if>
      </do_if>
      <do_else>
        <!-- v0.13.11: the scout-fallback that flew the ship to a sector with `resources.exists`
             and ran `order.move.recon resourcescout=true` is REMOVED. The v8 baseline does not
             have it; instead, vanilla mining routine semantics are restored â€” when the basket
             is exhausted the ship reports the failure and the parent miner script handles
             reassignment / idle. Probe-driven discovery happens organically through the
             post-MiningCollect DEPLOY block at the end of every successful slice. -->
        <do_if value="@this.assignedcontrolled.order.isrunning">
          <set_value name="$failurereason" exact="{1045, 105}" comment="No resources found in range."/>
          <do_if value="this.assignedcontrolled.hasblacklist.{blacklisttype.sectoractivity}.{$blacklistgroup} or this.assignedcontrolled.hasblacklist.{blacklisttype.sectortravel}.{$blacklistgroup} or this.assignedcontrolled.hasblacklist.{blacklisttype.objectactivity}.{$blacklistgroup}">
            <set_value name="$failurereason" exact="{1045, 106}" comment="No resources found in allowed sectors."/>
          </do_if>
          <do_if value="$debugchance">
            <debug_text text="'[GT-Miner-DIAG] FAIL_NO_RESOURCE ship=' + this.assignedcontrolled.idcode + ', reason=' + $failurereason + ', default=' + (if this.assignedcontrolled.defaultorder? then @this.assignedcontrolled.defaultorder.id else 'NONE') + ', current=' + (if this.assignedcontrolled.order? then @this.assignedcontrolled.order.id else 'NONE') + ', commander=' + (if this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists then this.assignedcontrolled.commander.idcode else 'NONE') + ', miningbasket=' + $miningbasket + ', gatherN=' + $gatheringspaces.count + ', sellN=' + $sellspaces.count" chance="100"/>
          </do_if>
          <set_order_failed order="this.assignedcontrolled.order" text="$failurereason"/>
          <remove_value name="$failurereason"/>
        </do_if>
        <!-- Debug info: Enable to see the mining ships unable to gather resources on the defined spaces -->
        <do_if value="$debugchance">
          <debug_text text="'%1 %5 %3 %4 Could not find any ware, waiting. Mining basket: %2'.[player.age, $miningbasket, this.assignedcontrolled.idcode, this.assignedcontrolled.knownname, this.assignedcontrolled.class]"/>
          <set_value name="$gt_bl_seca" exact="this.assignedcontrolled.hasblacklist.{blacklisttype.sectoractivity}.{$blacklistgroup}"/>
          <set_value name="$gt_bl_trv" exact="this.assignedcontrolled.hasblacklist.{blacklisttype.sectortravel}.{$blacklistgroup}"/>
          <set_value name="$gt_bl_obj" exact="this.assignedcontrolled.hasblacklist.{blacklisttype.objectactivity}.{$blacklistgroup}"/>
          <debug_text text="'[GT-MiningRoutine][ship=' + this.assignedcontrolled.idcode + '] NO_SECTOR_FOR_WARE lastWare=' + (if $ware? then $ware.name else 'null') + ' miningbasket=' + $miningbasket + ' minrating=' + $minrating + ' gatherN=' + $gatheringspaces.count + ' sellN=' + $sellspaces.count + ' minbuy=' + $minbuy + ' maxbuy=' + $maxbuy + ' minsell=' + $minsell + ' maxsell=' + $maxsell + ' deepspace=' + $deepspace + ' BLsectorActivity=' + $gt_bl_seca + ' BLsectorTravel=' + $gt_bl_trv + ' BLobjectActivity=' + $gt_bl_obj" chance="$debugchance"/>
          <remove_value name="$gt_bl_seca"/>
          <remove_value name="$gt_bl_trv"/>
          <remove_value name="$gt_bl_obj"/>
          <do_all exact="$gatheringspaces.count" counter="$i">
            <do_if value="$ware? and $gatheringspaces.{$i}.isclass.sector">
              <debug_text text="'[GT-MiningRoutine][ship=' + this.assignedcontrolled.idcode + '] gather#' + $i + ' ' + $gatheringspaces.{$i}.knownname + ' resExists=' + $gatheringspaces.{$i}.resources.{$ware}.exists + ' yieldR=' + @$gatheringspaces.{$i}.yieldrating.{$ware} + ' minrating=' + $minrating" chance="$debugchance"/>
            </do_if>
            <do_else>
              <debug_text text="'[GT-MiningRoutine][ship=' + this.assignedcontrolled.idcode + '] gather#' + $i + ' ' + $gatheringspaces.{$i}.class + ' ' + $gatheringspaces.{$i}.knownname + ' (non-sector)'" chance="$debugchance"/>
            </do_else>
          </do_all>
        </do_if>
        <!-- Nothing found, idle a while -->
        <run_script name="'move.idle'" >
          <param name="Min" value="50s" />
          <param name="Max" value="70s" />
        </run_script>
        <resume label="loop"/>
      </do_else>

      <debug_text text="'decided to mine %1 in %2, %3. secwares: %4'.[$ware, $sector.knownname, $sector.cluster.knownname, $secwares]" chance="$debugchance"/>

      <label name="movetocollect" />

      <!-- debug_eco - start -->
      <do_if value="this.assignedcontrolled.isclass.ship_m and $ware.hastag.mineral">
        <set_value name="$debug_eco" exact="0"/>
        <set_value name="$time_started" exact="player.age"/>
        <do_if value="this.$time_donemining?">
          <debug_to_file name="'eco_report.csv'" directory="'mining'" text="'%1;travel_from_location;%2;%3;%4;%5'.[player.age, this.assignedcontrolled.knownname, this.assignedcontrolled, this.assignedcontrolled.owner, player.age - this.$time_donemining]" output="$debugchance" chance="$debug_eco"/>
          <remove_value name="this.$time_donemining"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$debug_eco" exact="0"/>
        <set_value name="$time_started" exact="null"/>
      </do_else>

      <!-- move.generic was here. moved to MiningCollect order and call to MiningCollect made an immediate order because SectorChangeHandler was causing this script to reinitialize and potentially change destinations every time the ship changes sectors. -->

      <wait min="1s" max="3s" />

      <label name="collect"/>

      <do_if value="$resourcescout">
        <do_if value="this.sector != $sector or this.assignedcontrolled.distanceto.[$sector, $pos_sector] gt 10km">
          <debug_text text="'going long-distance to %1 relative to %2 %3.'.[$pos_sector, $sector.class, $sector]" chance="$debugchance"/>
          <run_script name="'move.generic'" result="$movesuccess">
            <param name="destination" value="$sector"/>
            <param name="position" value="$pos_sector"/>
            <param name="endintargetzone" value="true"/>
            <param name="debugchance" value="$debugchance" />
          </run_script>
          <do_if value="not $movesuccess">
            <do_if value="@this.assignedcontrolled.order.isrunning">
              <set_order_failed order="this.assignedcontrolled.order" text="{1045, 101}" comment="Unable to reach destination."/>
            </do_if>
            <debug_text text="'Unable to reach destination. Aborting.'" chance="$debugchance"/>
            <resume label="finish"/>
          </do_if>
        </do_if>
        <run_script name="'order.move.recon'">
          <param name="targetspace" value="this.sector"/>
          <param name="targetclasses" value="[class.collectable, class.lockbox]"/>
          <param name="resourcescout" value="true"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
        <resume label="loop"/>
      </do_if>
      <do_else>
        <!-- we already know where we want to mine, just need the resource area at that location. -->
        <find_closest_resource resourcearea="$resourcearea" ware="$ware" sector="$locsector" position="$locpos" refobject="$sector">
          <refposition value="$pos_sector" object="$sector"/>
        </find_closest_resource>
        <remove_value name="$locsector"/>
        <remove_value name="$locpos"/>
        <do_if value="not @$resourcearea">
          <debug_text text="'resource area no longer valid. looping back to search again.'" chance="$debugchance"/>
          <resume label="loop"/>
        </do_if>
        <add_yield_reservation reserver="this.assignedcontrolled" resourcearea="$resourcearea"/>
      </do_else>

      <do_if value="@this.assignedcontrolled.order.isrunning">
        <clear_order_failure order="this.assignedcontrolled.order"/>
      </do_if>

      <debug_text text="'%s %s %s moving to mine %s in %s %s'.[@this.assignedcontrolled.idcode, @this.assignedcontrolled.knownname, this.assignedcontrolled, $ware, $sector.class, $sector.knownname]" chance="$debugchance"/>
      <do_if value="$primaryTargetStations.count gt 0 and $warebasket.count == 1 and not $resourcescout and $physicalStorageAbortPercent gt 0 and $checkDemandFirst">
        <run_script name="'lib.gt.miner_physical_storage_gate'" result="$physGatePreCollect">
          <param name="ship" value="this.ship"/>
          <param name="ware" value="$ware"/>
          <param name="primaryTargetStations" value="$primaryTargetStations"/>
          <param name="physicalStorageAbortPercent" value="$physicalStorageAbortPercent"/>
          <param name="checkDemandFirst" value="$checkDemandFirst"/>
          <param name="resourcescout" value="$resourcescout"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
        <do_if value="$physGatePreCollect.$Trips? and $physGatePreCollect.$Trips">
          <set_value name="$physGatePreCollectAction" exact="if this.assignedcontrolled.cargo.{$ware}.count gt 0 then 'sellwares' else 'finish'"/>
          <debug_text text="'[GT-MiningRoutine] ' + this.assignedcontrolled.idcode + ': Physical storage gate (pre-collect) action=' + $physGatePreCollectAction + ' ware=' + $ware.name" chance="$debugchance"/>
          <do_if value="this.assignedcontrolled.cargo.{$ware}.count gt 0">
            <resume label="sellwares"/>
          </do_if>
          <resume label="finish"/>
        </do_if>
        <remove_value name="$physGatePreCollect"/>
        <remove_value name="$physGatePreCollectAction"/>
      </do_if>
      <!-- collecting is done in an external script -->
      <create_order object="this.assignedcontrolled" id="'MiningCollect'" immediate="true">
        <param name="destination" value="[$sector, $pos_sector]"/>
        <param name="ware" value="$ware"/>
        <param name="secwares" value="if $effectiveskill then $secwares else []"/>
        <param name="resourcearea" value="@$resourcearea"/>
        <param name="internalorder" value="not $blacklist_overridebuy?"/>
        <param name="debugchance" value="$debugchance"/>

        <!-- debug_eco -->
        <param name="time_started" value="$time_started"/>
        <param name="debug_eco" value="$debug_eco"/>
      </create_order>
      <!-- very short wait to allow the newly-created order to start and prevent the following logic from needlessly being processed. -->
      <wait exact="1ms" sinceversion="4"/>

      <label name="sellwares" />

      <!-- Use GT trade pipeline for selling (same as GalaxyTrader cargo disposal).
           Prioritizes home/attached station (distance 0 from home sector), falls back to other stations when full. -->
      <set_value name="$buyoffers" exact="[]" />
      <set_value name="$failurereason" exact="null"/>
      <do_if value="this.assignedcontrolled.cargo.count and $sellspaces? and $sellspaces.count gt 0">
        <!-- Build an explicit list of currently sellable cargo wares.
             Using an explicit list avoids engine quirks with bare cargo.list snapshots in nested script calls. -->
        <create_list name="$sellCargoWares"/>
        <do_all exact="this.assignedcontrolled.cargo.list.count" counter="$cwi">
          <set_value name="$cargoWare" exact="this.assignedcontrolled.cargo.list.{$cwi}"/>
          <do_if value="$cargoWare? and this.assignedcontrolled.cargo.{$cargoWare}.count gt 0 and not $sellCargoWares.indexof.{$cargoWare}">
            <append_to_list name="$sellCargoWares" exact="$cargoWare"/>
          </do_if>
        </do_all>
        <set_value name="$sellCargoDetail" exact="''"/>
        <do_if value="$sellCargoWares.count gt 0">
          <do_all exact="$sellCargoWares.count" counter="$scwi">
            <set_value name="$scWare" exact="$sellCargoWares.{$scwi}"/>
            <do_if value="$sellCargoDetail != ''">
              <set_value name="$sellCargoDetail" exact="$sellCargoDetail + ', '"/>
            </do_if>
            <set_value name="$sellCargoDetail" exact="$sellCargoDetail + $scWare.name + '=' + this.assignedcontrolled.cargo.{$scWare}.count"/>
          </do_all>
        </do_if>
        <do_else>
          <set_value name="$sellCargoDetail" exact="'none'"/>
        </do_else>
        <set_value name="$searchHomeSector" exact="if $homebase? and $homebase.exists and $homebase.sector? then @$homebase.sector else (if $range? and $range.isclass.sector then $range else (if $range? and $range.sector? then @$range.sector else this.assignedcontrolled.sector))"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}? and global.$GT_Ships.{this.assignedcontrolled}.$ActiveTradePolicy?">
          <remove_value name="global.$GT_Ships.{this.assignedcontrolled}.$ActiveTradePolicy"/>
        </do_if>
        <set_value name="$searchMaxDistance" exact="$maxsell"/>
        <set_value name="$gt_distancepenalty" exact="if global.$GT_AIParameters? and global.$GT_AIParameters.{this.assignedcontrolled}? and global.$GT_AIParameters.{this.assignedcontrolled}.$DistancePenalty? then (global.$GT_AIParameters.{this.assignedcontrolled}.$DistancePenalty / 50.0) else 0.02"/>
        <set_value name="$sellOwnerFilter" exact="'any'"/>
        <set_value name="$sellIgnoreTradeRules" exact="false"/>
        <set_value name="$blockedStationsForSell" exact="if $blockedstations? and $blockedstations != null then $blockedstations else []"/>
        <!-- Policy:
             - pre-overflow: sell only into primary stations
             - overflow + playerOnly: expand to other player stations
             - overflow + not playerOnly + allowOverflow: allow any faction -->
        <do_if value="$overflowSellMode and ($playerStationsOnly or (not $allowOverflowSellToOthers))">
          <set_value name="$sellOwnerFilter" exact="'player_only'"/>
          <set_value name="$sellIgnoreTradeRules" exact="true"/>
        </do_if>
        <!-- Demand-first primary delivery: sector-wide live search caps at maxOffersPerWare (20)
             and may never collect the home-station buyer. Query primary targets directly (same
             loose tradepartner scan diagnose uses) and merge before policy filtering. -->
        <create_list name="$primaryBuyOffers"/>
        <set_value name="$primaryDirectBuyOffers" exact="0"/>
        <do_if value="not $overflowSellMode and $primaryTargetStations? and $primaryTargetStations.count gt 0 and $sellCargoWares.count gt 0">
          <do_all exact="$primaryTargetStations.count" counter="$pdsi">
            <set_value name="$pdsStation" exact="$primaryTargetStations.{$pdsi}"/>
            <do_if value="not $pdsStation? or not $pdsStation.exists">
              <continue/>
            </do_if>
            <find_buy_offer buyer="$pdsStation" wares="$sellCargoWares" tradepartner="this.assignedcontrolled" multiple="true" result="$pdsOffers"/>
            <do_if value="$pdsOffers? and $pdsOffers.count gt 0">
              <do_all exact="$pdsOffers.count" counter="$pdsoi">
                <set_value name="$pdsOffer" exact="$pdsOffers.{$pdsoi}"/>
                <do_if value="not $pdsOffer? or not $pdsOffer.exists">
                  <continue/>
                </do_if>
                <set_value name="$pdsDup" exact="false"/>
                <do_if value="$primaryBuyOffers.count gt 0">
                  <do_all exact="$primaryBuyOffers.count" counter="$pddi">
                    <do_if value="$primaryBuyOffers.{$pddi}? and $primaryBuyOffers.{$pddi} == $pdsOffer">
                      <set_value name="$pdsDup" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $pdsDup">
                  <append_to_list name="$primaryBuyOffers" exact="$pdsOffer"/>
                  <set_value name="$primaryDirectBuyOffers" operation="add"/>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
        </do_if>
        <run_script name="'lib.gt.live.search'" result="$liveResult">
          <param name="ship" value="this.assignedcontrolled"/>
          <param name="searchMode" value="'sell_only'"/>
          <param name="sellSpaces" value="$sellspaces"/>
          <param name="homeSector" value="$searchHomeSector"/>
          <param name="maxDistance" value="$searchMaxDistance"/>
          <param name="wareBasket" value="$sellCargoWares"/>
          <param name="allowIllegal" value="true"/>
          <param name="ownerFilter" value="$sellOwnerFilter"/>
          <param name="ignoreTradeRules" value="$sellIgnoreTradeRules"/>
          <param name="debugchance" value="$debugchance"/>
        </run_script>
        <set_value name="$liveBuyOffers" exact="[]"/>
        <do_if value="$liveResult? and $liveResult.$BuyOffers?">
          <set_value name="$liveBuyOffers" exact="@$liveResult.$BuyOffers"/>
        </do_if>
        <set_value name="$liveBuyOffersFromSearch" exact="$liveBuyOffers.count"/>
        <do_if value="$primaryBuyOffers.count gt 0 or $liveBuyOffers.count gt 0">
          <create_list name="$mergedSellBuyOffers"/>
          <do_if value="$primaryBuyOffers.count gt 0">
            <do_all exact="$primaryBuyOffers.count" counter="$pmbi">
              <append_to_list name="$mergedSellBuyOffers" exact="$primaryBuyOffers.{$pmbi}"/>
            </do_all>
          </do_if>
          <do_if value="$liveBuyOffers.count gt 0">
            <do_all exact="$liveBuyOffers.count" counter="$lmbi">
              <set_value name="$lmbOffer" exact="$liveBuyOffers.{$lmbi}"/>
              <set_value name="$lmbDup" exact="false"/>
              <do_if value="$mergedSellBuyOffers.count gt 0">
                <do_all exact="$mergedSellBuyOffers.count" counter="$mbi">
                  <do_if value="$mergedSellBuyOffers.{$mbi}? and $mergedSellBuyOffers.{$mbi} == $lmbOffer">
                    <set_value name="$lmbDup" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $lmbDup">
                <append_to_list name="$mergedSellBuyOffers" exact="$lmbOffer"/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$liveBuyOffers" exact="$mergedSellBuyOffers"/>
        </do_if>
        <debug_text text="'[GT-Miner] ' + this.assignedcontrolled.idcode + ': Sell search result: playerOnly=' + $playerStationsOnly + ', overflow=' + $overflowSellMode + ', ownerFilter=' + $sellOwnerFilter + ', ignoreTradeRules=' + $sellIgnoreTradeRules + ', primaryTargets=' + (if $primaryTargetStations? then $primaryTargetStations.count else 0) + ', primaryDirectOffers=' + $primaryDirectBuyOffers + ', sellSpaces=' + (if $sellspaces? then $sellspaces.count else 0) + ', maxSell=' + $searchMaxDistance + ', home=' + (if $searchHomeSector? and $searchHomeSector.exists then $searchHomeSector.knownname else 'NONE') + ', cargoWares=' + $sellCargoWares.count + ' [' + $sellCargoDetail + '], liveBuyOffers=' + $liveBuyOffers.count + ' (sectorScan=' + $liveBuyOffersFromSearch + ')'" chance="$debugchance"/>
        <do_if value="$playerStationsOnly and $liveBuyOffers.count == 0">
          <do_all exact="$sellspaces.count" counter="$ssi" chance="$debugchance">
            <set_value name="$dbgSpace" exact="$sellspaces.{$ssi}"/>
            <debug_text text="'[GT-Miner] ' + this.assignedcontrolled.idcode + ': player-only search space[' + $ssi + ']=' + (if $dbgSpace? and $dbgSpace.exists then $dbgSpace.knownname else 'NULL') + ', gatedistanceFromHome=' + (if $dbgSpace? and $dbgSpace.exists and $searchHomeSector? and $searchHomeSector.exists then $searchHomeSector.gatedistance.{$dbgSpace} else -1)" chance="$debugchance"/>
          </do_all>
        </do_if>
        <create_list name="$sellOnlyTrades"/>
        <set_value name="$sellSkipNoWare" exact="0"/>
        <set_value name="$sellSkipNoAmount" exact="0"/>
        <set_value name="$sellSkipOutOfRange" exact="0"/>
        <set_value name="$sellSkipPolicy" exact="0"/>
        <set_value name="$sellSkipBlockedStation" exact="0"/>
        <set_value name="$sellSkipRouteIllegal" exact="0"/>
        <set_value name="$sellAcceptedOffers" exact="0"/>
        <do_if value="$liveBuyOffers.count gt 0">
          <do_all exact="$liveBuyOffers.count" counter="$offerIdx">
            <set_value name="$sellOffer" exact="$liveBuyOffers.{$offerIdx}"/>
            <set_value name="$sellWare" exact="if $sellOffer? and $sellOffer.ware? then @$sellOffer.ware else null"/>
            <set_value name="$sellStation" exact="if $sellOffer? and $sellOffer.owner? then @$sellOffer.owner else null"/>
            <set_value name="$primaryMatchStation" exact="$sellStation"/>
            <do_if value="$sellOffer? and $sellOffer.buyer? and @$sellOffer.buyer.exists">
              <set_value name="$primaryMatchStation" exact="@$sellOffer.buyer"/>
            </do_if>
            <do_elseif value="$sellStation? and $sellStation.exists and $sellStation.isclass.buildstorage and $sellStation.base? and @$sellStation.base.exists">
              <set_value name="$primaryMatchStation" exact="@$sellStation.base"/>
            </do_elseif>
            <set_value name="$isPrimarySellStation" exact="false"/>
            <do_if value="$primaryMatchStation? and $primaryMatchStation.exists and $primaryTargetStations? and $primaryTargetStations.count gt 0">
              <do_all exact="$primaryTargetStations.count" counter="$ptsi">
                <do_if value="$primaryTargetStations.{$ptsi}? and $primaryTargetStations.{$ptsi}.exists and $primaryTargetStations.{$ptsi} == $primaryMatchStation">
                  <set_value name="$isPrimarySellStation" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $sellWare?">
              <set_value name="$sellSkipNoWare" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="$blockedStationsForSell.count gt 0 and $sellStation?">
              <set_value name="$sellStationBlocked" exact="false"/>
              <do_all exact="$blockedStationsForSell.count" counter="$blockedSellIdx">
                <do_if value="$blockedStationsForSell.{$blockedSellIdx}? and $sellStation == $blockedStationsForSell.{$blockedSellIdx}">
                  <set_value name="$sellStationBlocked" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="$sellStationBlocked">
                <set_value name="$sellSkipBlockedStation" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
            <!-- Primary-first policy:
                 - before overflow: accept only primary stations below overflow threshold for this ware
                 - overflow + playerOnly: accept only non-primary player stations ("other player stations") -->
            <do_if value="not $overflowSellMode">
              <do_if value="not $isPrimarySellStation">
                <set_value name="$sellSkipPolicy" operation="add"/>
                <continue/>
              </do_if>
              <set_value name="$stationTargetAmount" exact="$sellStation.cargo.{$sellWare}.target"/>
              <do_if value="$stationTargetAmount le 0">
                <set_value name="$sellSkipPolicy" operation="add"/>
                <continue/>
              </do_if>
              <set_value name="$stationStoragePercent" exact="($sellStation.cargo.{$sellWare}.count * 100) / [$stationTargetAmount, 1].max"/>
              <do_if value="$stationStoragePercent ge $overflowThreshold">
                <set_value name="$sellSkipPolicy" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
            <do_elseif value="$playerStationsOnly">
              <do_if value="not $sellStation? or not $sellStation.exists or not $sellStation.isplayerowned or $isPrimarySellStation">
                <set_value name="$sellSkipPolicy" operation="add"/>
                <continue/>
              </do_if>
            </do_elseif>
            <set_value name="$shipWareAmount" exact="this.assignedcontrolled.cargo.{$sellWare}.count"/>
            <set_value name="$offerAmountForShip" exact="if $sellOffer.offeramount? and $sellOffer.offeramount.{this.assignedcontrolled}? then $sellOffer.offeramount.{this.assignedcontrolled} else $sellOffer.amount"/>
            <do_if value="$offerAmountForShip == null">
              <set_value name="$offerAmountForShip" exact="0"/>
            </do_if>
            <set_value name="$tradeAmount" exact="[$shipWareAmount, $offerAmountForShip].min"/>
            <do_if value="$tradeAmount le 0">
              <set_value name="$sellSkipNoAmount" operation="add"/>
              <continue/>
            </do_if>
            <set_value name="$sellDistance" exact="$searchHomeSector.gatedistance.{$sellOffer.owner}"/>
            <do_if value="$sellDistance lt 0 or $sellDistance gt $searchMaxDistance">
              <set_value name="$sellSkipOutOfRange" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="$allowIllegal and $enforceRouteIllegalLegality and @$sellWare.illegal gt 0">
              <run_script name="'lib.gt.pathfinding'" result="$minerRouteLegality">
                <param name="mode" value="'route_legality'"/>
                <param name="ship" value="this.assignedcontrolled"/>
                <param name="homeSector" value="$searchHomeSector"/>
                <param name="allowIllegal" value="$allowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                <param name="startSector" value="this.assignedcontrolled.sector"/>
                <param name="buySector" value="this.assignedcontrolled.sector"/>
                <param name="sellSector" value="if $sellStation? and $sellStation.exists and $sellStation.sector? then @$sellStation.sector else null"/>
                <param name="ware" value="$sellWare"/>
              </run_script>
              <do_if value="not $minerRouteLegality.$IsLegal">
                <set_value name="$sellSkipRouteIllegal" operation="add"/>
                <continue/>
              </do_if>
              <wait exact="1ms" comment="Cooperative yield after route_legality call (wake-loop guard)"/>
            </do_if>
            <set_value name="$distanceFactor" exact="1.0 + ($sellDistance * $gt_distancepenalty)"/>
            <!-- Convert money to numeric credits explicitly before float math to avoid money/float conversion warnings. -->
            <set_value name="$sellUnitPriceCredits" exact="(($sellOffer.unitprice / 1ct)f) / 100.0"/>
            <set_value name="$sellScore" exact="($tradeAmount * [1.0, $sellUnitPriceCredits].max) / $distanceFactor"/>
            <append_to_list name="$sellOnlyTrades" exact="table[
              $IsSellOnly = true,
              $Ware = $sellWare,
              $SellOffer = $sellOffer,
              $SellStation = $sellOffer.owner,
              $Amount = $tradeAmount,
              $Score = $sellScore,
              $BuyStation = this.assignedcontrolled,
              $BuySector = this.assignedcontrolled.sector,
              $Distance = $sellDistance,
              $UnitProfit = $sellOffer.unitprice,
              $BuyPrice = 0,
              $SellPrice = $sellOffer.unitprice,
              $ProfitPerUnit = $sellOffer.unitprice,
              $Profit = ($sellOffer.unitprice * $tradeAmount)
            ]"/>
            <set_value name="$sellAcceptedOffers" operation="add"/>
          </do_all>
        </do_if>
        <debug_text text="'[GT-Miner] ' + this.assignedcontrolled.idcode + ': Sell offer filtering: raw=' + $liveBuyOffers.count + ', accepted=' + $sellAcceptedOffers + ', skipNoWare=' + $sellSkipNoWare + ', skipNoAmount=' + $sellSkipNoAmount + ', skipOutOfRange=' + $sellSkipOutOfRange + ', skipPolicy=' + $sellSkipPolicy + ', skipBlockedStation=' + $sellSkipBlockedStation + ', skipRouteIllegal=' + $sellSkipRouteIllegal + ', builtTrades=' + $sellOnlyTrades.count" chance="$debugchance"/>
        <do_if value="$sellOnlyTrades.count gt 0">
          <run_script name="'lib.gt.score.trades'" result="$scoreResult">
            <param name="tradeList" value="$sellOnlyTrades"/>
            <param name="debugchance" value="$debugchance"/>
          </run_script>
          <set_value name="$bestTrade" exact="null"/>
          <do_if value="$scoreResult? and $scoreResult.$Found? and $scoreResult.$BestTrade?">
            <set_value name="$bestTrade" exact="$scoreResult.$BestTrade"/>
          </do_if>
          <do_if value="$bestTrade? and $bestTrade.$SellOffer?">
            <set_value name="$minerBestRouteOk" exact="true"/>
            <do_if value="$allowIllegal and $enforceRouteIllegalLegality and @$bestTrade.$Ware.illegal gt 0">
              <run_script name="'lib.gt.pathfinding'" result="$minerBestRouteLegality">
                <param name="mode" value="'route_legality'"/>
                <param name="ship" value="this.assignedcontrolled"/>
                <param name="homeSector" value="$searchHomeSector"/>
                <param name="allowIllegal" value="$allowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                <param name="startSector" value="this.assignedcontrolled.sector"/>
                <param name="buySector" value="this.assignedcontrolled.sector"/>
                <param name="sellSector" value="if $bestTrade.$SellStation? and $bestTrade.$SellStation.exists and $bestTrade.$SellStation.sector? then @$bestTrade.$SellStation.sector else null"/>
                <param name="ware" value="$bestTrade.$Ware"/>
              </run_script>
              <do_if value="not $minerBestRouteLegality.$IsLegal">
                <set_value name="$minerBestRouteOk" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$minerBestRouteOk">
            <append_to_list name="$buyoffers" exact="$bestTrade.$SellOffer"/>
            <do_if value="$homebase? and $homebase.exists and $bestTrade.$SellStation? and $bestTrade.$SellStation == $homebase">
              <do_if value="$homebase.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or $homebase.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}">
                <set_value name="$blacklist_overridesell"/>
              </do_if>
            </do_if>
            <debug_text text="'[GT-Miner] %s using GT pipeline: selling to %s (distance=%s, score=%s)'.[this.assignedcontrolled.idcode, $bestTrade.$SellStation.knownname, $bestTrade.$Distance, $bestTrade.$Score]" chance="$debugchance"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$sellOnlyTrades.count gt 0 and not $buyoffers.count">
          <debug_text text="'[GT-Miner] ' + this.assignedcontrolled.idcode + ': Trades built but no buyoffer selected by scorer. tradeCount=' + $sellOnlyTrades.count" chance="$debugchance"/>
        </do_if>
        <do_if value="not $buyoffers.count and not $failurereason?">
          <set_value name="$failurereason" exact="{1045, 107}" comment="No buyers found in range."/>
        </do_if>
      </do_if>

      <do_if value="(this.assignedcontrolled.order.id == 'MiningRoutine') or (this.assignedcontrolled.order.id == 'MiningRoutine_Basic') or (this.assignedcontrolled.order.id == 'MiningRoutine_Advanced') or (this.assignedcontrolled.order.id == 'MiningRoutine_Expert')">
        <!-- NB: order will not be interrupted until after a blocking action is hit so, if a trade order is to be added and this order is to be interrupted, the trade order will be added first. -->
        <set_order_syncpoint_reached order="this.assignedcontrolled.order"/>
      </do_if>

      <do_if value="@this.assignedcontrolled.order.isrunning">
        <do_if value="$buyoffers.count">
          <clear_order_failure order="this.assignedcontrolled.order"/>
        </do_if>
        <do_else>
          <do_if value="not @$failurereason">
            <set_value name="$failurereason" exact="{1045, 107}" comment="No buyers found in range."/>
            <do_if value="this.assignedcontrolled.hasblacklist.{blacklisttype.sectoractivity}.{$blacklistgroup} or this.assignedcontrolled.hasblacklist.{blacklisttype.sectortravel}.{$blacklistgroup} or this.assignedcontrolled.hasblacklist.{blacklisttype.objectactivity}.{$blacklistgroup}">
              <set_value name="$failurereason" exact="{1045, 108}" comment="No buyers found in allowed sectors."/>
            </do_if>
          </do_if>
          <!-- NB: this used to depend on @this.assignedcontrolled.order.isrunning no longer being true if $tradeorder is successfully created. -->
          <!-- $miningbasket is created in the gathering branch (lines ~618-905). This FAIL_NO_BUYER
               branch can be reached on cycles where the ship arrived with cargo already and the
               gathering branch was skipped entirely - the variable is then undefined, not just
               empty. Coalesce defensively so the diag itself does not raise a property-lookup
               error on top of the legitimate "no buyer" failure we are trying to diagnose. -->
          <do_if value="$debugchance">
            <debug_text text="'[GT-Miner-DIAG] FAIL_NO_BUYER ship=' + this.assignedcontrolled.idcode + ', reason=' + $failurereason + ', default=' + (if this.assignedcontrolled.defaultorder? then @this.assignedcontrolled.defaultorder.id else 'NONE') + ', current=' + (if this.assignedcontrolled.order? then @this.assignedcontrolled.order.id else 'NONE') + ', commander=' + (if this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists then this.assignedcontrolled.commander.idcode else 'NONE') + ', buyoffers=' + (if $buyoffers? then $buyoffers.count else 'undef') + ', sellspaces=' + (if $sellspaces? then $sellspaces.count else 'undef') + ', miningbasket=' + (if $miningbasket? then $miningbasket else 'undef (gathering branch was skipped this cycle - ship likely arrived with cargo)')" chance="100"/>
          </do_if>
          <set_order_failed order="this.assignedcontrolled.order" text="$failurereason"/>
        </do_else>
      </do_if>
      <remove_value name="$failurereason"/>

      <do_for_each name="$buyoffer" in="$buyoffers">
        <!-- For the buyoffer (I sell) -->
        <set_value name="$buyofferamount" exact="if $buyoffer.available then $buyoffer.offeramount.{this.assignedcontrolled} else 0"/>
        <do_if value="$buyofferamount">
          <!-- I want to sell after gathering resources, I limit what I want to sell to what I gathered (selloffer-offer amount of this) -->
          <clamp_trade_amount trade="$buyoffer" seller="this.assignedcontrolled" amount="$buyofferamount" buyer="$buyoffer.buyer" result="$amount"/>

          <debug_text text="'clamped amount: %s, buyoffer amount: %s, buyoffer desiredamount: %s, amount in hold: %s\ntrade price: %s, station cash: %s'.[$amount, $buyofferamount, $buyoffer.desiredamount, this.assignedcontrolled.cargo.{$buyoffer.ware}.count, ($amount * $buyoffer.unitprice).formatted.default, $buyoffer.buyer.money.formatted.default]" chance="$debugchance"/>
          <!-- Add sell trade perform (if available) => This object sells (create_trade_order adds the reservation automatically) -->
          <do_if value="$amount">
            <!-- cache values as $buyoffer may no longer be an offer after a trade order has been created from it, make sure we still know the relevant bits for removing any virtual reservations for that ware -->
            <set_value name="$resource_buyer" exact="$buyoffer.buyer"/>
            <set_value name="$resource_ware" exact="$buyoffer.ware"/>
            <set_value name="$tradeorder_internal" exact="this.assignedcontrolled.isplayerowned and $resource_buyer? and $resource_buyer.exists and $resource_buyer.isplayerowned"/>
            <set_value name="$queuedSaleValueRaw" exact="$amount * $buyoffer.unitprice"/>
            <debug_text text="'creating trade order to sell %1 %2 to %3 (%4, %5) for %6Cr'.[$amount, $resource_ware, $resource_buyer.knownname, $resource_buyer, $resource_buyer.idcode, ($amount * $buyoffer.unitprice).formatted.default]" chance="$debugchance" />
            <!-- Queue-time miner logbook signal (tradequeue semantics): announce intent before trade executes. -->
            <do_if value="$logbookentries">
              <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogMinerCargoSale'" param2="table[
                $Ship = this.assignedcontrolled,
                $station = $resource_buyer,
                $ware = $resource_ware,
                $transferredAmount = $amount,
                $saleValueRaw = $queuedSaleValueRaw,
                $timestamp = player.age
              ]"/>
            </do_if>
            <create_trade_order name="$tradeorder" object="this.object" tradeoffer="$buyoffer" amount="$amount" internal="$tradeorder_internal" immediate="true"/>
            <do_if value="$allowIllegal and $enforceRouteIllegalLegality">
              <do_if value="not global.$GT_Ships?">
                <set_value name="global.$GT_Ships" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Ships.{this.assignedcontrolled}?">
                <set_value name="global.$GT_Ships.{this.assignedcontrolled}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.assignedcontrolled}.$ActiveTradePolicy" exact="table[
                $AllowIllegal = $allowIllegal,
                $EnforceRouteIllegalLegality = $enforceRouteIllegalLegality,
                $Ware = $resource_ware,
                $BuySector = this.assignedcontrolled.sector,
                $SellSector = if $resource_buyer? and $resource_buyer.exists and $resource_buyer.sector? then @$resource_buyer.sector else null,
                $HomeSector = $searchHomeSector,
                $RouteStart = this.assignedcontrolled.sector,
                $Leg = 'sell',
                $LogbookEntries = $logbookentries,
                $SetAt = player.age
              ]"/>
            </do_if>
            <!-- if we are now actually selling, remove any virtual reservation for this ware as we have a real one as part of the trade order -->
            <remove_ware_reservation object="$resource_buyer" reserver="this.assignedcontrolled" type="sell" virtual="true" ware="$resource_ware"/>
            <remove_value name="$resource_buyer" />
            <remove_value name="$resource_ware" />
            <remove_value name="$tradeorder_internal" />
            <remove_value name="$queuedSaleValueRaw" />
          </do_if>
          <!-- if a trade order has been made, move.idle should be interrupted as soon as it hits a blocking action. -->
          <set_value name="$idle"/>
        </do_if>
      </do_for_each>

      <!-- if we have wares that cannot be sold, just dump them -->
      <do_if value="not @$tradeorder.exists">
        <do_if value="this.assignedcontrolled.cargo.count">
          <do_if value="not this.isplayerowned">
            <do_all exact="$warebasket.count" counter="$i">
              <set_value name="$possibleware" exact="$warebasket.{$i}"/>
              <set_value name="$maxamount" exact="this.assignedcontrolled.cargo.{$possibleware}.max"/>
              <!-- Drop cargo -->
              <do_if value="$maxamount">
                <drop_cargo object="this.assignedcontrolled" ware="$possibleware" min="($maxamount * 0.1f)i" max="($maxamount * 0.2f)i" amounts="$droppedamounts" wares="$droppedwares"/>
                <do_all exact="$droppedwares.count" counter="$d" chance="$debugchance">
                  <debug_text text="'%1 (%2) dropped %3 %4 because that ware is unsellable in %5'.[this.assignedcontrolled.knownname, this.assignedcontrolled, $droppedamounts.{$d}, $droppedwares.{$d}, this.cluster.knownname]"/>
                </do_all>
              </do_if>
            </do_all>
            <remove_value name="$possibleware" />
            <remove_value name="$maxamount" />
            <remove_value name="$droppedwares" />
          </do_if>
          <do_elseif value="this.assignedcontrolled.cargo.free.all">
            <set_value name="$cannotsell"/>
          </do_elseif>
          <set_value name="$idle"/>
        </do_if>
      </do_if>
      <remove_value name="$buyofferamount" />

      <do_if value="$idle?">
        <remove_value name="$idle"/>
        <!-- command action -->
        <set_command_action commandaction="commandaction.calculating" />

        <run_script name="'move.idle'" >
          <param name="Min" value="10s" />
          <param name="Max" value="40s" />
        </run_script>
      </do_if>

      <!-- No offer found, restart -->
      <do_if value="not @this.assignedcontrolled.isjobship or not this.assignedcontrolled.jobexpired">
        <resume label="loop" />
      </do_if>

      <label name="finish" />

      <do_if value="@$homebase.isoperational">
        <!-- clean up any virtual reservation we may have made if this script ends (as opposed to going into a subscript) -->
        <remove_ware_reservation object="$homebase" reserver="this.assignedcontrolled" type="sell" virtual="true"/>
      </do_if>

      <do_if value="$failreason?">
        <do_if value="@$sector and @$pos_sector">
          <debug_text text="'script ends with reason %1. Looking to gather %4 for job \'%5\'. This ship %2 m away from destination, destination %3'.[$failreason, this.assignedcontrolled.distanceto.[$sector, $pos_sector], $sector.knownname, @$warebasket, this.assignedcontrolled.job]"/>
        </do_if>
        <do_else>
          <debug_text text="'script ends with reason %s. Looking to gather %s for job \'%s\'.'.[$failreason, @$warebasket, this.assignedcontrolled.job]"/>
        </do_else>
      </do_if>
      <do_if value="$failreason2?">
        <debug_text text="$failreason2" />
      </do_if>

      <!-- check if this is a jobship at the end of its lifetime -->
      <do_if value="this.assignedcontrolled.jobexpired">
        <debug_text text="'%1 doing job %2 has expired, die!'.[this.assignedcontrolled.knownname, this.assignedcontrolled.job]" chance="$debugchance" />
        <create_order object="this.assignedcontrolled" id="'MoveDie'" immediate="true">
          <param name="byhighway" value="not this.assignedcontrolled.isclass.[class.ship_l, class.ship_xl]" />
        </create_order>
      </do_if>

    </actions>
  </attention>
  <on_abort>
    <do_if value="@$homebase.isoperational and this.assignedcontrolled.isoperational and $thisorder? and not @$thisorder.exists">
      <debug_text text="'on_abort: removing ware reservation. current order: %s, this order exists: %s'.[@this.assignedcontrolled.order.id, $thisorder.exists]" chance="$debugchance"/>
      <!-- clean up any virtual reservation we may have made if this script is aborted -->
      <remove_ware_reservation object="$homebase" reserver="this.assignedcontrolled" type="sell" virtual="true"/>
    </do_if>
    <do_if value="$duration and @$tradeorder.exists and @$thisorder.exists">
      <!-- do not reduce duration to 0s since that would make the order infinite. -->
      <debug_text text="'on_abort: updating duration from %s to %s'.[$duration, $duration - [(player.age - $time_start), $duration - 1s].min]" chance="$debugchance"/>
      <edit_order_param order="$thisorder" param="'duration'" value="[$duration - (player.age - $time_start), 1s].max"/>
    </do_if>
    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}.$ActiveTradePolicy?">
      <remove_value name="global.$GT_Ships.{this.assignedcontrolled}.$ActiveTradePolicy"/>
    </do_if>
  </on_abort>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Repair completion signalling patch -->
  <!-- This patch adds immediate completion signalling when repair orders finish -->
  
  <add sel="//aiscript[@name='order.repair']/attention/actions/wait[@exact='10min']/interrupt/actions/debug_text" pos="after">
    
    <!-- GALAXYTRADER MK3: Repair completion signalling -->
    <do_if value="this.ship.pilot and this.ship.isplayerowned">
      <!-- Check if this pilot is managed by GalaxyTrader MK3 -->
      <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        
        <!-- Queue repair completion event -->
        <do_if value="not global.$GT_RepairCompleteQueue?">
          <set_value name="global.$GT_RepairCompleteQueue" exact="[]"/>
        </do_if>
        
        <set_value name="$repair_data" exact="table[
          $ship = this.ship,
          $pilot = this.ship.pilot,
          $timestamp = player.age
        ]"/>
        
        <append_to_list name="global.$GT_RepairCompleteQueue" exact="$repair_data"/>
        
        <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
        <signal_objects object="player.galaxy" param="'GT_RepairComplete'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Repair] Repair complete for ' + this.ship.idcode + ', signalling completion'" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    
  </add>
</diff>
<?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Restock (Resupply) completion signalling patch -->
  <!-- This patch adds completion signalling to notify the GT system when resupply is complete -->
  
  <!-- ========================================================================= -->
  <!-- COMPLETION SIGNALING: Notify GT system when Restock/Resupply completes  -->
  <!-- ========================================================================= -->
  <add sel="//aiscript[@name='order.restock']/attention[@min='unknown']" pos="after">
    <on_abort>
      <!-- PERFORMANCE FIX: Early exit check BEFORE any logging or property lookups -->
      <!-- If ship is not GT-controlled, exit immediately to prevent stutter -->
      <set_value name="$isGTControlled" exact="false"/>
      
      <!-- Quick check: Does ship have direct GT order (or Assist baseorder)? -->
      <do_if value="this.ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.id}">
        <set_value name="$isGTControlled" exact="true"/>
      </do_if>
      <do_elseif value="this.ship.defaultorder? and @this.ship.defaultorder.id == 'Assist' and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
        <set_value name="$isGTControlled" exact="true"/>
      </do_elseif>
      
      <!-- Fallback check: Is ship subordinate to GT commander? -->
      <do_if value="not $isGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <do_if value="this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
        <do_elseif value="this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
          <set_value name="$isGTControlled" exact="true"/>
        </do_elseif>
      </do_if>
      
      <!-- EARLY EXIT: If ship is not GT-controlled, exit immediately without any processing -->
      <do_if value="not $isGTControlled">
        <!-- Ship is not GT-controlled - no signals needed, exit silently -->
        <!-- This prevents stutter from constant property lookups for non-GT ships -->
        <return/>
      </do_if>
      
      <!-- Ship IS GT-controlled - proceed with completion signaling -->
      <!-- CRITICAL: Check if GT order is still active before sending signals -->
      <!-- Resupply order can abort normally (completion) - only send signals if GT order is still active -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <set_value name="$hasGTCommander" exact="false"/>
      <do_if value="this.ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.id}">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      <do_elseif value="this.ship.defaultorder? and @this.ship.defaultorder.id == 'Assist' and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_elseif>
      
      <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
        <set_value name="$hasGTCommander" exact="true"/>
      </do_if>
      <do_elseif value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
        <set_value name="$hasGTCommander" exact="true"/>
      </do_elseif>
      
      <!-- Signal completion to GalaxyTrader system if this is a GT ship AND GT order is still active -->
      <do_if value="this.ship.pilot and this.ship.isplayerowned and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and ($hasDirectGTOrder or $hasGTCommander)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Restock] Restock/Resupply complete for ' + this.ship.idcode" chance="100"/>
        </do_if>
        
        <!-- LOGGING: Show what was actually restocked when order finishes -->
        <set_value name="$resupplyOrder" exact="@global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="$resupplyOrder?">
          <!-- Get "before" values from resupply order tracking -->
          <set_value name="$beforeCM" exact="@$resupplyOrder.$CountermeasuresBefore"/>
          <set_value name="$beforeUnits" exact="@$resupplyOrder.$UnitsBefore"/>
          <set_value name="$beforeDefenseDrones" exact="@$resupplyOrder.$DefenseDronesBefore"/>
          <set_value name="$beforeCargoDrones" exact="@$resupplyOrder.$CargoDronesBefore"/>
          <set_value name="$beforeLaserTowers" exact="@$resupplyOrder.$LaserTowersBefore"/>
          <set_value name="$beforeRepairDrones" exact="@$resupplyOrder.$RepairDronesBefore"/>
          
          <!-- Get current values -->
          <set_value name="$currentCM" exact="this.ship.ammostorage.countermeasure.count"/>
          <set_value name="$currentUnits" exact="this.ship.units.count"/>
          <set_value name="$currentDefenseDrones" exact="this.ship.units.{macro.ship_gen_s_fightingdrone_01_a_macro}.count"/>
          <set_value name="$currentCargoDrones" exact="this.ship.units.{macro.ship_gen_xs_cargodrone_empty_01_a_macro}.count"/>
          <set_value name="$currentLaserTowers" exact="this.ship.units.{macro.ship_gen_xs_lasertower_01_a_macro}.count"/>
          <set_value name="$currentRepairDrones" exact="this.ship.units.{macro.ship_gen_xs_repairdrone_01_a_macro}.count"/>
          
          <!-- Calculate what was gained -->
          <set_value name="$cmGained" exact="$currentCM - $beforeCM"/>
          <set_value name="$defenseGained" exact="$currentDefenseDrones - $beforeDefenseDrones"/>
          <set_value name="$cargoGained" exact="$currentCargoDrones - $beforeCargoDrones"/>
          <set_value name="$towersGained" exact="$currentLaserTowers - $beforeLaserTowers"/>
          <set_value name="$repairGained" exact="$currentRepairDrones - $beforeRepairDrones"/>
          <set_value name="$unitsGained" exact="$currentUnits - $beforeUnits"/>
          
          <!-- Build summary of what was restocked -->
          <set_value name="$restockedItems" exact="[]"/>
          <do_if value="$cmGained gt 0">
            <append_to_list name="$restockedItems" exact="'CM +' + $cmGained"/>
          </do_if>
          <do_if value="$defenseGained gt 0">
            <append_to_list name="$restockedItems" exact="'Defense Drones +' + $defenseGained"/>
          </do_if>
          <do_if value="$cargoGained gt 0">
            <append_to_list name="$restockedItems" exact="'Cargo Drones +' + $cargoGained"/>
          </do_if>
          <do_if value="$towersGained gt 0">
            <append_to_list name="$restockedItems" exact="'Laser Towers +' + $towersGained"/>
          </do_if>
          <do_if value="$repairGained gt 0">
            <append_to_list name="$restockedItems" exact="'Repair Drones +' + $repairGained"/>
          </do_if>
          
          <set_value name="$restockedSummary" exact="if $restockedItems.count gt 0 then $restockedItems.{1} + (if $restockedItems.count gt 1 then ', ' + $restockedItems.{2} else '') + (if $restockedItems.count gt 2 then ', ' + $restockedItems.{3} else '') + (if $restockedItems.count gt 3 then ', ' + $restockedItems.{4} else '') + (if $restockedItems.count gt 4 then ', ' + $restockedItems.{5} else '') else 'NOTHING'"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Restock] RESTOCKED for ' + this.ship.idcode + ': ' + $restockedSummary" chance="100"/>
            <debug_text text="'[GT-Restock] DETAILED RESTOCK for ' + this.ship.idcode + ':'" chance="100"/>
            <debug_text text="'[GT-Restock]   Countermeasures: ' + $beforeCM + ' ' + $currentCM + ' (gained: ' + $cmGained + ')'" chance="100"/>
            <debug_text text="'[GT-Restock]   Defense Drones: ' + $beforeDefenseDrones + ' ' + $currentDefenseDrones + ' (gained: ' + $defenseGained + ')'" chance="100"/>
            <debug_text text="'[GT-Restock]   Cargo Drones: ' + $beforeCargoDrones + ' ' + $currentCargoDrones + ' (gained: ' + $cargoGained + ')'" chance="100"/>
            <debug_text text="'[GT-Restock]   Laser Towers: ' + $beforeLaserTowers + ' ' + $currentLaserTowers + ' (gained: ' + $towersGained + ')'" chance="100"/>
            <debug_text text="'[GT-Restock]   Repair Drones: ' + $beforeRepairDrones + ' ' + $currentRepairDrones + ' (gained: ' + $repairGained + ')'" chance="100"/>
            <debug_text text="'[GT-Restock]   Total Units: ' + $beforeUnits + ' ' + $currentUnits + ' (gained: ' + $unitsGained + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Queue completion notification -->
        <do_if value="not global.$GT_ResupplyCompleteQueue?">
          <set_value name="global.$GT_ResupplyCompleteQueue" exact="[]"/>
        </do_if>
        
        <append_to_list name="global.$GT_ResupplyCompleteQueue" exact="table[
          $ship = this.ship,
          $time = player.age
        ]"/>
        
        <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
        <signal_objects object="player.galaxy" param="'GT_ResupplyComplete'"/>
      </do_if>
      <do_else>
        <!-- Edge case: GT-controlled ship lost GT order during resupply -->
        <!-- This is rare, so reduce logging chance -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Restock] ' + this.ship.idcode + ': Resupply order aborted but GT order no longer active - skipping signals'" chance="10"/>
        </do_if>
      </do_else>
    </on_abort>
  </add>
  
</diff>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.trade.galaxyminer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="10">
  <order id="GalaxyMiner" name="{77000, 31002}" description="{77000, 31102}" category="mining" infinite="true" allowinloop="false" canplayercancel="true">
    <params>
      <param name="homeStation" type="object" default="null" text="{77000, 31010}" comment="{77000, 31110}">
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="homePosition" type="position" default="null" text="{77000, 31011}" comment="{77000, 31111}">
        <input_param name="class" value="class.sector"/>
      </param>
      <param name="homeSector" type="internal" default="null">
      </param>
      <param name="resourceBasket" default="this.ship.warebasket.list" type="list" text="{77000, 31012}" comment="{77000, 31112}">
        <input_param name="type" value="'ware'"/>
        <input_param name="isminable" value="true"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="stationList" default="[]" type="list" text="{77000, 31013}" comment="{77000, 31113}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="blockedstations" default="[]" type="list" text="{77000,1094}" comment="{77000,1095}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
        <patch value="[]" sinceversion="3"/>
      </param>
      <param name="overflowThreshold" default="90" type="number" text="{77000, 31014}" comment="{77000, 31114}">
        <input_param name="min" value="70"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="allowOverflowSellToOthers" default="false" type="bool" text="{77000, 31015}" comment="{77000, 31115}"/>
      <param name="assignToStation" default="true" type="bool" text="{77000, 31016}" comment="{77000, 31116}"/>
      <param name="playerStationsOnly" default="false" type="bool" text="{77000, 31028}" comment="{77000, 31128}"/>
      <param name="checkDemandFirst" default="true" type="bool" text="{77000, 31031}" comment="{77000, 31131}">
        <patch value="true" sinceversion="9"/>
      </param>
      <param name="allowillegal" default="false" type="bool" text="{77000,1011}" comment="{77000,1025}"/>
      <param name="enforceRouteIllegalLegality" default="false" type="bool" text="{77000,1070}" comment="{77000,1071}"/>
      <param name="stayAtHome" default="false" type="bool" text="{77000, 31017}" comment="{77000, 31117}" />
      <param name="idleParking" default="false" type="bool" text="{77000, 1096}" comment="{77000, 1097}">
        <patch value="false" sinceversion="4"/>
      </param>
      <param name="autoJumpDistanceByLevel" default="false" type="bool" text="{77000,1098}" comment="{77000,1099}">
        <patch value="false" sinceversion="7"/>
      </param>
      <!-- Collector ("mining") drone buy amount. Capital miners need ore/gas collector drones to
           mine; this slider sets how many GT buys when the ship has run OUT of the needed collector
           type. The purchase is gated on count==0 (see gt_maintenance.xml $needsCollectorDrones), so
           a ship that already has at least one collector is never topped up / re-bought. Capped at the
           ship's unit-bay capacity. 0 disables automatic collector-drone purchases entirely (manage
           drones manually). Default 5 matches the previous hard-coded behaviour (a full vanilla drone
           set for proper mining speed). -->
      <param name="maxCollectorDronesToBuy" default="5" type="number" text="{77000, 31030}" comment="{77000, 31130}">
        <input_param name="startvalue" value="5"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="[@this.ship.units.maxcount, 0].max"/>
        <input_param name="step" value="1"/>
        <patch value="5" sinceversion="6"/>
      </param>
      <param name="maxGatherDistance" default="0" type="number" text="{77000, 31019}" comment="{77000, 31119}">
        <!-- min/startvalue lowered from 1 to 0 to match the param's default. Previously the slider
             showed 1 while the stored value (when the player never moved the slider) was 0, and
             the diag tool correctly reported the stored 0 â€” UI / runtime mismatch. 0 is a fully
             supported value and means "mine in home/current sector only" (see the
             $maxGatherDistance le 0 branch in the runtime ~line 662 that always keeps the ref
             sector in the gather list). -->
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="maxSellDistance" default="0" type="number" text="{77000, 31020}" comment="{77000, 31120}">
        <!-- min/startvalue lowered from 1 to 0 to match the param's default; same reasoning as
             maxGatherDistance above. 0 means "sell only in home/current sector" â€” a supported
             value, and the slider must be able to display it. -->
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="fleetBalancing" default="true" type="bool" text="{77000, 31021}" comment="{77000, 31121}" advanced="true"/>
      <param name="demandRecheckInterval" default="60s" type="time" text="{77000, 31022}" comment="{77000, 31122}" advanced="true"/>
      <param name="physicalStorageAbortPercent" default="20" type="number" text="{77000, 31032}" comment="{77000, 31132}" advanced="true">
        <input_param name="startvalue" value="20"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
        <patch value="20" sinceversion="10"/>
      </param>
      <param name="criticalDemandDelta" default="20" type="number" text="{77000, 31023}" comment="{77000, 31123}" advanced="true"/>
      <param name="minSwitchCooldown" default="180s" type="time" text="{77000, 31024}" comment="{77000, 31124}" advanced="true"/>
      <param name="minCargoCommitPercent" default="25" type="number" text="{77000, 31025}" comment="{77000, 31125}" advanced="true"/>
      <param name="hardEmergencyDelta" default="45" type="number" text="{77000, 31026}" comment="{77000, 31126}" advanced="true"/>
      <param name="notifications" default="1" type="number" text="{77000, 31027}" comment="{77000, 31127}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="logbookentries" default="true" type="bool" text="{77000,1012}" comment="{77000,1041}">
        <patch value="true" sinceversion="5"/>
      </param>
      <param name="debuglevel" default="1" type="number" text="{77000, 30020}" comment="{77000, 30120}" advanced="true">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
    </params>
    <requires primarypurpose="purpose.mine">
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
    <icon name="order_miningroutine_manual"/>
  </order>

  <interrupts>
    <handler ref="SectorChangeHandler"/>
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>
    <!-- Mirror MK training dispatch bridge -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$trainingStation" exact="$trainingData.$Station"/>
        <!-- Academy enrollments append DockAndTrain to the queue (immediate=false)
             so the ship finishes its current task first and the player sees the
             training order lined up. Natural ladder keeps immediate dispatch. -->
        <set_value name="$isAcademy" exact="@$trainingData.$IsAcademy"/>
        <set_value name="$useImmediate" exact="not $isAcademy"/>
        <!-- Assist subordinates inherit this aicontext; immediate DockAndTrain
             aborts training when the parent context tears down (see MD dispatch). -->
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist'">
          <set_value name="$useImmediate" exact="false"/>
        </do_if>
        <set_value name="$hasActiveTrainingOrder" exact="false"/>
        <do_all exact="this.ship.orders.count" counter="$oi">
          <do_if value="this.ship.orders.{$oi}.id == 'DockAndTrain'">
            <set_value name="$hasActiveTrainingOrder" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="$trainingStation? and $trainingStation.exists and not $hasActiveTrainingOrder">
          <create_order object="this.ship" id="'DockAndTrain'" immediate="$useImmediate">
            <param name="destination" value="$trainingStation"/>
            <param name="debugchance" value="this.$debugchance"/>
          </create_order>
          <set_value name="this.$miner_lastTrainingSignalAt" exact="player.age"/>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': DockAndTrain queued for ' + $trainingStation.knownname + ' (academy=' + $isAcademy + ', immediate=' + $useImmediate + ')'" chance="this.$debugchance"/>
        </do_if>
      </actions>
    </handler>
  </interrupts>

  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_value name="$debugchance" exact="if $debuglevel ge 1 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
    <set_value name="this.$debugchance" exact="$debugchance"/>
    <set_value name="this.$homeConfigValid" exact="true"/>
    <set_value name="$homePositionValid" exact="false"/>

    <!-- Resolve UI Home Position into legacy sector anchor (vanilla position tuple: [space, position]). -->
    <do_if value="$homePosition? and $homePosition.{1}? and $homePosition.{1}.exists and $homePosition.{1}.isclass.sector">
      <set_value name="$homeSector" exact="$homePosition.{1}"/>
      <set_value name="$homePositionValid" exact="true"/>
    </do_if>
    <do_elseif value="$homePosition? and $homePosition.{1}? and $homePosition.{1}.sector? and $homePosition.{1}.sector.exists">
      <set_value name="$homeSector" exact="$homePosition.{1}.sector"/>
      <set_value name="$homePositionValid" exact="true"/>
    </do_elseif>
    <do_if value="not $homePositionValid and $homeSector? and $homeSector.exists">
      <set_value name="$homePosition" exact="[$homeSector, $homeSector.coreposition]"/>
      <set_value name="$homePositionValid" exact="true"/>
      <do_if value="this.ship.order? and this.ship.order.exists and @this.ship.order.id == 'GalaxyMiner'">
        <edit_order_param order="this.ship.order" param="'homePosition'" value="$homePosition"/>
      </do_if>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.exists and this.ship.defaultorder.id == 'GalaxyMiner'">
        <edit_order_param order="this.ship.defaultorder" param="'homePosition'" value="$homePosition"/>
      </do_if>
    </do_if>

    <!-- Canonicalize home config:
         keep both values when provided, but runtime anchoring prefers the station sector.
         The explicit home sector is a fallback for stationless miners. -->
    <do_if value="($homeStation? and $homeStation.exists) and ($homePositionValid and $homeSector? and $homeSector.exists)">
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Home config has station+position; preserving both (station=' + $homeStation.idcode + ', sector=' + $homeSector.knownname + ')'" chance="$debugchance"/>
    </do_if>
    <do_if value="not $assignToStation and $homeStation? and $homeStation.exists">
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': assignToStation disabled -> clearing homeStation ' + $homeStation.idcode" chance="$debugchance"/>
      <set_value name="$homeStation" exact="null"/>
      <do_if value="this.ship.order? and this.ship.order.exists and @this.ship.order.id == 'GalaxyMiner'">
        <edit_order_param order="this.ship.order" param="'homeStation'" value="null"/>
      </do_if>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.exists and this.ship.defaultorder.id == 'GalaxyMiner'">
        <edit_order_param order="this.ship.defaultorder" param="'homeStation'" value="null"/>
      </do_if>
    </do_if>
    <do_if value="not $assignToStation and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.isclass.station">
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': assignToStation disabled -> removing station assignment from commander ' + this.ship.commander.idcode" chance="$debugchance"/>
      <remove_object_commander object="this.ship"/>
    </do_if>
    <do_if value="(not $homeStation? or not $homeStation.exists) and (not $homeSector? or not $homeSector.exists) and this.sector? and this.sector.exists">
      <set_value name="$homeSector" exact="this.sector"/>
      <set_value name="$homePosition" exact="[$homeSector, $homeSector.coreposition]"/>
      <set_value name="$homePositionValid" exact="true"/>
      <do_if value="this.ship.order? and this.ship.order.exists and @this.ship.order.id == 'GalaxyMiner'">
        <edit_order_param order="this.ship.order" param="'homePosition'" value="$homePosition"/>
        <edit_order_param order="this.ship.order" param="'homeSector'" value="$homeSector"/>
      </do_if>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.exists and this.ship.defaultorder.id == 'GalaxyMiner'">
        <edit_order_param order="this.ship.defaultorder" param="'homePosition'" value="$homePosition"/>
        <edit_order_param order="this.ship.defaultorder" param="'homeSector'" value="$homeSector"/>
      </do_if>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': No home configured -> auto-set Home Position to current sector core position in ' + $homeSector.knownname" chance="$debugchance"/>
    </do_if>
    <do_if value="(not $homeStation? or not $homeStation.exists) and (not $homeSector? or not $homeSector.exists)">
      <show_notification text="{77000, 31201}" timeout="10s"/>
      <set_command_action commandaction="commandaction.standingby"/>
      <set_value name="this.$homeConfigValid" exact="false"/>
    </do_if>

    <!-- Optional station assignment -->
    <do_if value="$assignToStation and $homeStation? and $homeStation.exists and $homeStation.isclass.station and (not this.ship.commander? or not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and ((not this.ship.commander?) or this.ship.commander != $homeStation)">
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <remove_object_commander object="this.ship"/>
      </do_if>
      <set_object_commander object="this.ship" commander="$homeStation" assignment="assignment.mining"/>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Assigned to home station commander ' + $homeStation.idcode + ' (assignment=mining)'" chance="$debugchance"/>
    </do_if>

    <!-- Persist resolved config -->
    <set_value name="this.$homeStation" exact="$homeStation"/>
    <set_value name="this.$homeSector" exact="$homeSector"/>
    <set_value name="this.$homePosition" exact="$homePosition"/>
    <set_value name="this.$resourceBasket" exact="$resourceBasket"/>
    <set_value name="this.$stationList" exact="$stationList"/>
    <set_value name="this.$effectiveBlockedStations" exact="if $blockedstations? then $blockedstations else []"/>
    <set_value name="this.$overflowThreshold" exact="[70, [100, $overflowThreshold].min].max"/>
    <set_value name="this.$physicalStorageAbortPercent" exact="[0, [100, if $physicalStorageAbortPercent? then $physicalStorageAbortPercent else 20].min].max"/>
    <set_value name="this.$allowOverflowSellToOthers" exact="$allowOverflowSellToOthers"/>
    <set_value name="this.$assignToStation" exact="$assignToStation"/>
    <set_value name="this.$playerStationsOnly" exact="$playerStationsOnly"/>
    <set_value name="this.$checkDemandFirst" exact="if $checkDemandFirst? then $checkDemandFirst else true"/>
    <set_value name="this.$allowillegal" exact="$allowillegal"/>
    <set_value name="this.$enforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <set_value name="this.$stayAtHome" exact="$stayAtHome"/>
    <set_value name="this.$idleParking" exact="$idleParking"/>
    <set_value name="this.$logbookentries" exact="$logbookentries"/>
    <!-- Clamp collector-drone buy amount to [0, ship's unit-bay capacity]. Published to
         GT_AIParameters so gt_maintenance.xml reads the target from
         global.$GT_AIParameters.{ship}.$MaxCollectorDronesToBuy. -->
    <set_value name="this.$maxCollectorDronesToBuy" exact="[0, [@this.ship.units.maxcount, $maxCollectorDronesToBuy].min].max"/>
    <set_value name="$useVanillaXPOnlyInit" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
    <do_if value="$useVanillaXPOnlyInit">
      <set_value name="this.$maxGatherDistance" exact="$maxGatherDistance"/>
      <set_value name="this.$maxSellDistance" exact="$maxSellDistance"/>
    </do_if>
    <do_else>
      <set_value name="$pilotLevelForParamCap" exact="1"/>
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
        <set_value name="$pilotLevelForParamCap" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
      </do_if>
      <set_value name="$pilotMaxParamDistance" exact="1"/>
      <do_if value="$pilotLevelForParamCap le 2">
        <set_value name="$pilotMaxParamDistance" exact="1"/>
      </do_if>
      <do_elseif value="$pilotLevelForParamCap le 5">
        <set_value name="$pilotMaxParamDistance" exact="3"/>
      </do_elseif>
      <do_elseif value="$pilotLevelForParamCap le 8">
        <set_value name="$pilotMaxParamDistance" exact="5"/>
      </do_elseif>
      <do_elseif value="$pilotLevelForParamCap le 11">
        <set_value name="$pilotMaxParamDistance" exact="10"/>
      </do_elseif>
      <do_elseif value="$pilotLevelForParamCap le 13">
        <set_value name="$pilotMaxParamDistance" exact="15"/>
      </do_elseif>
      <do_else>
        <set_value name="$pilotMaxParamDistance" exact="25"/>
      </do_else>
      <set_value name="this.$maxGatherDistance" exact="[$maxGatherDistance, $pilotMaxParamDistance].min"/>
      <set_value name="this.$maxSellDistance" exact="[$maxSellDistance, $pilotMaxParamDistance].min"/>
    </do_else>
    <set_value name="this.$fleetBalancing" exact="$fleetBalancing"/>
    <set_value name="this.$demandRecheckInterval" exact="[10s, [300s, $demandRecheckInterval].min].max"/>
    <!-- The four switch-gate clamps (`this.$criticalDemandDelta`, `this.$minSwitchCooldown`,
         `this.$minCargoCommitPercent`, `this.$hardEmergencyDelta`) and the `hardEmergencyDelta lt
         criticalDemandDelta` normalization that used to live here have been removed alongside the
         switch-gate at the post-scoring selection block: ware selection is now "highest-scoring
         this slice, full stop". The order params are still declared in the params block for
         save-game compatibility but are no longer read anywhere. `this.$lastWareSwitchAt` was
         likewise gate-only state and is removed. -->
    <!-- A3: minrating=1 (any non-zero yield) so low-yield-but-actually-mineable wares are not pre-filtered.
         The mining routine itself adapts the per-sector rating threshold (see order.mining.routine.gt.xml ~1064)
         so a yield-rating-1 sector can still produce a successful find_resource. Keeping the order's pre-filter
         at 3 prevented low-pilot-level / single-sector miners from ever picking valid low-yield wares. -->
    <set_value name="this.$minReachableYieldRating" exact="1"/>
    <set_value name="this.$debuglevel" exact="$debuglevel"/>
    <set_value name="this.$notifications" exact="$notifications"/>
    <set_value name="this.$activeMiningWare" exact="null"/>
    <set_value name="this.$activeMiningUrgency" exact="0"/>
    <set_value name="this.$minerAssignedStations" exact="[]"/>
    <set_value name="this.$minerAssignedWare" exact="null"/>
    <set_value name="this.$minerIntentStations" exact="[]"/>
    <set_value name="this.$minerIntentWare" exact="null"/>
    <set_value name="this.$minerOverflowCommanderBackup" exact="null"/>
    <set_value name="this.$minerDetachedForOverflow" exact="false"/>
    <set_value name="this.$minerIdleNoWorkCount" exact="0"/>

    <do_if value="this.$homeConfigValid">
      <set_command_action commandaction="commandaction.searchingresources"/>
    </do_if>
    <do_else>
      <set_command_action commandaction="commandaction.standingby"/>
    </do_else>

    <!-- Feed GT maintenance / shared systems -->
    <do_if value="not global.$GT_AIParameters?">
      <set_value name="global.$GT_AIParameters" exact="table[]"/>
    </do_if>
    <!-- $HomeBase resolution mirrors the order's own homeSector resolver (lines ~109-127):
         prefer station, then resolved sector, then fall back to homePosition.{1} chain so a
         player who set only the position param (the most natural UI flow) still ends up with
         a non-null $HomeBase for downstream consumers (GT_GetHomeSector etc.). -->
    <set_value name="global.$GT_AIParameters.{this.ship}" exact="table[
      $HomeBase = if $homeStation? and $homeStation.exists then $homeStation
                  else if $homeSector? and $homeSector.exists then $homeSector
                  else if $homePosition? and $homePosition.{1}? and $homePosition.{1}.exists and $homePosition.{1}.isclass.sector then $homePosition.{1}
                  else if $homePosition? and $homePosition.{1}? and $homePosition.{1}.sector? and $homePosition.{1}.sector.exists then $homePosition.{1}.sector
                  else null,
      $MaxDistance = if $stayAtHome then 0 else $maxGatherDistance,
      $MaxCollectorDronesToBuy = this.$maxCollectorDronesToBuy,
      $maxCollectorDronesToBuy = this.$maxCollectorDronesToBuy,
      $RequestTime = player.age
    ]"/>
    <do_if value="not global.$GT_MinerStationAssignments?">
      <set_value name="global.$GT_MinerStationAssignments" exact="table[]"/>
    </do_if>
    <do_if value="not global.$GT_MinerIntents?">
      <set_value name="global.$GT_MinerIntents" exact="table[]"/>
    </do_if>
    <!-- Self-heal on (re)assignment: clear stale detached-cleanup tracking that can
         survive older abort storms and keep ships in pseudo-orphan state. -->
    <do_if value="global.$GT_CleanupIntent? and global.$GT_CleanupIntent.{this.ship}?">
      <remove_value name="global.$GT_CleanupIntent.{this.ship}"/>
    </do_if>
    <do_if value="global.$GT_OrphanVerifyPending? and global.$GT_OrphanVerifyPending.{this.ship}?">
      <remove_value name="global.$GT_OrphanVerifyPending.{this.ship}"/>
    </do_if>
    <do_if value="global.$GT_DelayedVerificationState? and global.$GT_DelayedVerificationState.{this.ship}?">
      <remove_value name="global.$GT_DelayedVerificationState.{this.ship}"/>
    </do_if>
    <do_if value="global.$GT_CleanupSignalState? and global.$GT_CleanupSignalState.{this.ship}?">
      <remove_value name="global.$GT_CleanupSignalState.{this.ship}"/>
    </do_if>

    <!-- Register with GT lifecycle -->
    <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
      $Ship = this.ship,
      $Config = table[
        $debuglevel = $debuglevel,
        $orderType = 'Miner'
      ]
    ]"/>
    <do_if value="this.ship.pilot">
      <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
        $updateType = 'pilot_change',
        $Ship = this.ship,
        $pilot = this.ship.pilot,
        $oldPilot = null
      ]"/>
    </do_if>
    <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
      $Ship = this.ship,
      $UpdateType = 'GT_Order_Assigned',
      $MacroShipName = @this.ship.macro.name
    ]"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Init complete. homeConfigValid=' + this.$homeConfigValid + ', default=' + (if this.ship.defaultorder? then @this.ship.defaultorder.id else 'NONE') + ', commander=' + (if this.ship.commander? and this.ship.commander.exists then this.ship.commander.idcode else 'NONE') + ', debugChance=' + this.$debugchance" chance="this.$debugchance"/>
  </init>

  <!-- =================================================================== -->
  <!-- Save-game compatibility patches                                      -->
  <!-- =================================================================== -->
  <patch sinceversion="3">
    <do_if value="not $blockedstations?">
      <set_value name="$blockedstations" exact="[]"/>
    </do_if>
    <do_if value="not this.$effectiveBlockedStations?">
      <set_value name="this.$effectiveBlockedStations" exact="$blockedstations"/>
    </do_if>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v2->v3 patch applied (blockedstations=' + this.$effectiveBlockedStations.count + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="4">
    <do_if value="not $idleParking?">
      <set_value name="$idleParking" exact="false"/>
    </do_if>
    <set_value name="this.$idleParking" exact="$idleParking"/>
    <do_if value="not this.$minerIdleNoWorkCount?">
      <set_value name="this.$minerIdleNoWorkCount" exact="0"/>
    </do_if>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v3->v4 patch applied (idleParking=' + this.$idleParking + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="5">
    <do_if value="not $logbookentries?">
      <set_value name="$logbookentries" exact="true"/>
    </do_if>
    <set_value name="this.$logbookentries" exact="$logbookentries"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v4->v5 patch applied (logbookentries=' + this.$logbookentries + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="6">
    <!-- Defensive param backfill: the per-<param> <patch sinceversion="6"/> is supposed to
         restore $maxCollectorDronesToBuy for v5 orders, but the loader does NOT guarantee it
         resolves before this script-level patch runs (same idiom as the v2 probe-slider patch
         above, mirroring vanilla move.flee.xml's "not $foo?" guard). -->
    <do_if value="not $maxCollectorDronesToBuy?">
      <set_value name="$maxCollectorDronesToBuy" exact="5"/>
    </do_if>
    <!-- Re-populate the this.$ instance var that <init> would have set; <init> does NOT re-run on
         save load, so without this the main_loop keep-up-to-date block throws "Property lookup
         failed: this.$maxCollectorDronesToBuy". -->
    <set_value name="this.$maxCollectorDronesToBuy" exact="[0, [@this.ship.units.maxcount, $maxCollectorDronesToBuy].min].max"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v5->v6 patch applied (maxCollectorDrones=' + this.$maxCollectorDronesToBuy + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="7">
    <do_if value="not $autoJumpDistanceByLevel?">
      <set_value name="$autoJumpDistanceByLevel" exact="false"/>
    </do_if>
    <set_value name="this.$prevAutoJumpDistance" exact="$autoJumpDistanceByLevel"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v6->v7 patch applied (autoJumpDistanceByLevel=' + $autoJumpDistanceByLevel + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="8">
    <do_if value="not $allowillegal?">
      <set_value name="$allowillegal" exact="false"/>
    </do_if>
    <do_if value="not $enforceRouteIllegalLegality?">
      <set_value name="$enforceRouteIllegalLegality" exact="false"/>
    </do_if>
    <set_value name="this.$allowillegal" exact="$allowillegal"/>
    <set_value name="this.$enforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v7->v8 patch applied (allowillegal=' + $allowillegal + ', enforceRouteIllegalLegality=' + $enforceRouteIllegalLegality + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="9">
    <do_if value="not $checkDemandFirst?">
      <set_value name="$checkDemandFirst" exact="true"/>
    </do_if>
    <set_value name="this.$checkDemandFirst" exact="$checkDemandFirst"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v8->v9 patch applied (checkDemandFirst=' + $checkDemandFirst + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="10">
    <do_if value="not $physicalStorageAbortPercent?">
      <set_value name="$physicalStorageAbortPercent" exact="20"/>
    </do_if>
    <set_value name="this.$physicalStorageAbortPercent" exact="[0, [100, $physicalStorageAbortPercent].min].max"/>
    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': v9->v10 patch applied (physicalStorageAbortPercent=' + this.$physicalStorageAbortPercent + ')'" filter="savegame"/>
  </patch>

  <attention min="unknown">
    <actions>
      <label name="main_loop"/>

      <!-- Save-load / hot-reload backfill: <init> does not re-run; patch may not have fired yet. -->
      <do_if value="not this.$physicalStorageAbortPercent?">
        <set_value name="this.$physicalStorageAbortPercent" exact="[0, [100, if $physicalStorageAbortPercent? then $physicalStorageAbortPercent else 20].min].max"/>
      </do_if>

      <!-- Legacy save cleanup: auto-deploy resource probes removed (idempotent). -->
      <do_if value="not this.$gtProbeLegacyCleaned?">
        <set_value name="this.$gtProbeLegacyCleaned" exact="true"/>
        <do_if value="this.$autoDeployResourceProbes?"><remove_value name="this.$autoDeployResourceProbes"/></do_if>
        <do_if value="this.$maxResourceProbesToBuy?"><remove_value name="this.$maxResourceProbesToBuy"/></do_if>
        <do_if value="this.$gtNextScoutAt?"><remove_value name="this.$gtNextScoutAt"/></do_if>
        <do_if value="this.$gtNextProbeResupplyAt?"><remove_value name="this.$gtNextProbeResupplyAt"/></do_if>
        <do_if value="this.$scoutLastProbe?"><remove_value name="this.$scoutLastProbe"/></do_if>
        <do_if value="this.$gtScoutClaimWare?"><remove_value name="this.$gtScoutClaimWare"/></do_if>
        <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}?">
          <do_if value="global.$GT_AIParameters.{this.ship}.$AutoDeployResourceProbes?"><remove_value name="global.$GT_AIParameters.{this.ship}.$AutoDeployResourceProbes"/></do_if>
          <do_if value="global.$GT_AIParameters.{this.ship}.$autoDeployResourceProbes?"><remove_value name="global.$GT_AIParameters.{this.ship}.$autoDeployResourceProbes"/></do_if>
          <do_if value="global.$GT_AIParameters.{this.ship}.$MaxResourceProbesToBuy?"><remove_value name="global.$GT_AIParameters.{this.ship}.$MaxResourceProbesToBuy"/></do_if>
          <do_if value="global.$GT_AIParameters.{this.ship}.$maxResourceProbesToBuy?"><remove_value name="global.$GT_AIParameters.{this.ship}.$maxResourceProbesToBuy"/></do_if>
        </do_if>
      </do_if>

      <!-- Idle park timed release (miner keeps searching; hold expiry handled here). -->
      <run_script name="'lib.gt.idlepark'">
        <param name="handoffMode" value="'check_timed_release'"/>
        <param name="handoffShip" value="this.ship"/>
        <param name="home" value="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else this.ship.sector)"/>
        <param name="debugchance" value="if this.$debugchance? then this.$debugchance else 0"/>
      </run_script>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Entered main loop. default=' + (if this.ship.defaultorder? then @this.ship.defaultorder.id else 'NONE') + ', commander=' + (if this.ship.commander? and this.ship.commander.exists then this.ship.commander.idcode else 'NONE') + ', homeValid=' + this.$homeConfigValid" chance="this.$debugchance"/>

      <!-- Unified ship name refresh (home sector, op-state, XP â€” content dedupe in MD) -->
      <run_script name="'lib.gt.attention.refresh_ship_name'">
        <param name="ship" value="this.ship"/>
      </run_script>
      <run_script name="'lib.gt.attention.autojump_distance_toggle'">
        <param name="autoJumpDistanceByLevel" value="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
      </run_script>

      <!-- In-flight academy / DockAndTrain: hold the default order while the ship
           completes training (MD timer + order.dock.train survive save/load). -->
      <set_value name="$gtHasDockAndTrain" exact="false"/>
      <do_if value="this.ship.orders? and this.ship.orders.count gt 0">
        <do_all exact="this.ship.orders.count" counter="$gtToi">
          <do_if value="this.ship.orders.{$gtToi}.id == 'DockAndTrain'">
            <set_value name="$gtHasDockAndTrain" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      <set_value name="$gtMdTrainingActive" exact="false"/>
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
        <set_value name="$gtMdTrainingActive" exact="true"/>
      </do_if>
      <do_if value="$gtHasDockAndTrain or $gtMdTrainingActive">
        <set_command_action commandaction="commandaction.standingby"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Holding for in-flight training (DockAndTrain=' + $gtHasDockAndTrain + ', MD timer=' + $gtMdTrainingActive + ')'" chance="100"/>
        </do_if>
        <wait max="10s">
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship"/>
            </conditions>
          </interrupt>
        </wait>
        <resume label="main_loop"/>
      </do_if>

      <!-- Runtime sync for assignToStation toggle edits -->
      <set_value name="this.$assignToStation" exact="$assignToStation"/>
      <set_value name="this.$playerStationsOnly" exact="$playerStationsOnly"/>
      <set_value name="this.$checkDemandFirst" exact="if $checkDemandFirst? then $checkDemandFirst else true"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyMiner' and this.ship.defaultorder.$checkDemandFirst?">
        <set_value name="this.$checkDemandFirst" exact="this.ship.defaultorder.$checkDemandFirst"/>
      </do_if>
      <do_elseif value="this.ship.commander.exists and this.ship.commander != this.ship and this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist' and this.ship.commander.defaultorder?">
        <set_value name="$minerPolicyOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$minerPolicyOrder.id == 'Assist' and $minerPolicyOrder.$baseorder?">
          <set_value name="$minerPolicyOrder" exact="$minerPolicyOrder.$baseorder"/>
        </do_if>
        <do_if value="$minerPolicyOrder? and $minerPolicyOrder.id == 'GalaxyMiner' and $minerPolicyOrder.$checkDemandFirst?">
          <set_value name="this.$checkDemandFirst" exact="$minerPolicyOrder.$checkDemandFirst"/>
        </do_if>
      </do_elseif>
      <set_value name="this.$idleParking" exact="if $idleParking? then $idleParking else false"/>
      <set_value name="this.$logbookentries" exact="if $logbookentries? then $logbookentries else true"/>
      <set_value name="this.$allowillegal" exact="if $allowillegal? then $allowillegal else false"/>
      <set_value name="this.$enforceRouteIllegalLegality" exact="if $enforceRouteIllegalLegality? then $enforceRouteIllegalLegality else false"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyMiner'">
        <do_if value="this.ship.defaultorder.$allowillegal?">
          <set_value name="this.$allowillegal" exact="this.ship.defaultorder.$allowillegal"/>
        </do_if>
        <do_if value="this.ship.defaultorder.$enforceRouteIllegalLegality?">
          <set_value name="this.$enforceRouteIllegalLegality" exact="this.ship.defaultorder.$enforceRouteIllegalLegality"/>
        </do_if>
      </do_if>
      <do_elseif value="this.ship.commander.exists and this.ship.commander != this.ship and this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist' and this.ship.commander.defaultorder?">
        <set_value name="$minerPolicyOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$minerPolicyOrder.id == 'Assist' and $minerPolicyOrder.$baseorder?">
          <set_value name="$minerPolicyOrder" exact="$minerPolicyOrder.$baseorder"/>
        </do_if>
        <do_if value="$minerPolicyOrder? and $minerPolicyOrder.id == 'GalaxyMiner'">
          <do_if value="$minerPolicyOrder.$allowillegal?">
            <set_value name="this.$allowillegal" exact="$minerPolicyOrder.$allowillegal"/>
          </do_if>
          <do_if value="$minerPolicyOrder.$enforceRouteIllegalLegality?">
            <set_value name="this.$enforceRouteIllegalLegality" exact="$minerPolicyOrder.$enforceRouteIllegalLegality"/>
          </do_if>
        </do_if>
      </do_elseif>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyMiner' and this.ship.defaultorder.$resourceBasket?">
        <set_value name="this.$resourceBasket" exact="this.ship.defaultorder.$resourceBasket"/>
      </do_if>
      <set_value name="$minerBlockedStations" exact="if $blockedstations? then $blockedstations else (if this.$effectiveBlockedStations? then this.$effectiveBlockedStations else [])"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyMiner' and this.ship.defaultorder.$blockedstations?">
        <set_value name="$minerBlockedStations" exact="this.ship.defaultorder.$blockedstations"/>
      </do_if>
      <do_elseif value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist' and this.ship.commander.defaultorder?">
        <set_value name="$minerInheritedBlockedOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$minerInheritedBlockedOrder.id == 'Assist' and $minerInheritedBlockedOrder.$baseorder?">
          <set_value name="$minerInheritedBlockedOrder" exact="$minerInheritedBlockedOrder.$baseorder"/>
        </do_if>
        <do_if value="$minerInheritedBlockedOrder? and $minerInheritedBlockedOrder.id == 'GalaxyMiner' and $minerInheritedBlockedOrder.$blockedstations?">
          <set_value name="$minerBlockedStations" exact="$minerInheritedBlockedOrder.$blockedstations"/>
        </do_if>
      </do_elseif>
      <do_if value="not $minerBlockedStations? or $minerBlockedStations == null">
        <set_value name="$minerBlockedStations" exact="[]"/>
      </do_if>
      <set_value name="this.$effectiveBlockedStations" exact="$minerBlockedStations"/>
      <do_if value="not this.$assignToStation">
        <do_if value="$homeStation? and $homeStation.exists">
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': assignToStation runtime-off -> clearing homeStation ' + $homeStation.idcode" chance="this.$debugchance"/>
          <set_value name="$homeStation" exact="null"/>
          <set_value name="this.$homeStation" exact="null"/>
          <do_if value="this.ship.order? and this.ship.order.exists and @this.ship.order.id == 'GalaxyMiner'">
            <edit_order_param order="this.ship.order" param="'homeStation'" value="null"/>
          </do_if>
          <do_if value="this.ship.defaultorder? and this.ship.defaultorder.exists and this.ship.defaultorder.id == 'GalaxyMiner'">
            <edit_order_param order="this.ship.defaultorder" param="'homeStation'" value="null"/>
          </do_if>
        </do_if>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.isclass.station">
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': assignToStation runtime-off -> removing station commander ' + this.ship.commander.idcode" chance="this.$debugchance"/>
          <remove_object_commander object="this.ship"/>
        </do_if>
      </do_if>

      <!-- Re-read distance params from the active order source and apply GT pilot cap.
           Must run before demand/station/ware scoring. Vanilla XP mode uses order values only. -->
      <set_value name="$minerRuntimeMaxGatherRaw" exact="if $maxGatherDistance? then $maxGatherDistance else this.$maxGatherDistance"/>
      <set_value name="$minerRuntimeMaxSellRaw" exact="if $maxSellDistance? then $maxSellDistance else this.$maxSellDistance"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyMiner'">
        <set_value name="$minerRuntimeMaxGatherRaw" exact="if this.ship.defaultorder.$maxGatherDistance? then this.ship.defaultorder.$maxGatherDistance else $minerRuntimeMaxGatherRaw"/>
        <set_value name="$minerRuntimeMaxSellRaw" exact="if this.ship.defaultorder.$maxSellDistance? then this.ship.defaultorder.$maxSellDistance else $minerRuntimeMaxSellRaw"/>
      </do_if>
      <do_elseif value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist' and this.ship.commander.defaultorder?">
        <set_value name="$minerInheritedOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$minerInheritedOrder.id == 'Assist' and $minerInheritedOrder.$baseorder?">
          <set_value name="$minerInheritedOrder" exact="$minerInheritedOrder.$baseorder"/>
        </do_if>
        <do_if value="$minerInheritedOrder? and $minerInheritedOrder.id == 'GalaxyMiner'">
          <set_value name="$minerRuntimeMaxGatherRaw" exact="if $minerInheritedOrder.$maxGatherDistance? then $minerInheritedOrder.$maxGatherDistance else $minerRuntimeMaxGatherRaw"/>
          <set_value name="$minerRuntimeMaxSellRaw" exact="if $minerInheritedOrder.$maxSellDistance? then $minerInheritedOrder.$maxSellDistance else $minerRuntimeMaxSellRaw"/>
        </do_if>
      </do_elseif>
      <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
      <do_if value="$useVanillaXPOnly">
        <set_value name="this.$maxGatherDistance" exact="$minerRuntimeMaxGatherRaw"/>
        <set_value name="this.$maxSellDistance" exact="$minerRuntimeMaxSellRaw"/>
      </do_if>
      <do_else>
        <set_value name="$pilotMaxJumps" exact="1"/>
        <set_value name="$pilotLevelForDistance" exact="1"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
          <set_value name="$pilotLevelForDistance" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        <do_if value="$pilotLevelForDistance le 2">
          <set_value name="$pilotMaxJumps" exact="1"/>
        </do_if>
        <do_elseif value="$pilotLevelForDistance le 5">
          <set_value name="$pilotMaxJumps" exact="3"/>
        </do_elseif>
        <do_elseif value="$pilotLevelForDistance le 8">
          <set_value name="$pilotMaxJumps" exact="5"/>
        </do_elseif>
        <do_elseif value="$pilotLevelForDistance le 11">
          <set_value name="$pilotMaxJumps" exact="10"/>
        </do_elseif>
        <do_elseif value="$pilotLevelForDistance le 13">
          <set_value name="$pilotMaxJumps" exact="15"/>
        </do_elseif>
        <do_else>
          <set_value name="$pilotMaxJumps" exact="25"/>
        </do_else>
        <set_value name="this.$maxGatherDistance" exact="[$minerRuntimeMaxGatherRaw, $pilotMaxJumps].min"/>
        <set_value name="this.$maxSellDistance" exact="[$minerRuntimeMaxSellRaw, $pilotMaxJumps].min"/>
      </do_else>

      <!-- Keep maintenance params up-to-date for shared GT maintenance -->
      <set_value name="global.$GT_AIParameters.{this.ship}.$MaxDistance" exact="if this.$stayAtHome then 0 else this.$maxGatherDistance"/>
      <set_value name="global.$GT_AIParameters.{this.ship}.$MaxCollectorDronesToBuy" exact="this.$maxCollectorDronesToBuy"/>
      <set_value name="global.$GT_AIParameters.{this.ship}.$maxCollectorDronesToBuy" exact="this.$maxCollectorDronesToBuy"/>

      <!-- Never return from default order on invalid home config; stay idle and retry -->
      <do_if value="not this.$homeConfigValid">
        <set_command_action commandaction="commandaction.standingby"/>
        <wait exact="10s"/>
        <resume label="main_loop"/>
      </do_if>

      <!-- Periodic training re-request for blocked pilots -->
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
        <set_value name="$blockedLevel" exact="0"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel?">
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <set_value name="$needsTrainingDispatch" exact="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded? or $blockedLevel gt 1"/>
        <set_value name="$gtSkipTrainingDispatch" exact="false"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
          <set_value name="$gtSkipTrainingDispatch" exact="true"/>
        </do_if>
        <do_if value="not $gtSkipTrainingDispatch and this.ship.orders? and this.ship.orders.count gt 0">
          <do_all exact="this.ship.orders.count" counter="$gtToi2">
            <do_if value="this.ship.orders.{$gtToi2}.id == 'DockAndTrain'">
              <set_value name="$gtSkipTrainingDispatch" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$needsTrainingDispatch and not $gtSkipTrainingDispatch and (not this.$miner_lastTrainingSignalAt? or (player.age - this.$miner_lastTrainingSignalAt) ge 60s)">
          <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $RequiredLevel = $blockedLevel
          ]"/>
          <set_value name="this.$miner_lastTrainingSignalAt" exact="player.age"/>
        </do_if>
      </do_if>

      <!-- Shared GT maintenance -->
      <signal_objects object="player.galaxy" param="'GT_DoMaintenance'" param2="this.ship"/>
      <wait exact="2s"/>

      <!-- =========================================================================
           RESUPPLY EXECUTOR: turn the shopping list gt_maintenance.xml prepared into
           an actual wharf build. gt_maintenance.xml's DoMaintenance / ExecuteMaintenance
           cues only build $ammotable + $unittable and stash them in
           global.$GT_ResupplyOrders.{$ship} - they do NOT call add_build_to_modify_ship
           themselves. The trader scripts (order.trade.galaxytrader.xml ~2052-2205,
           order.trade.galaxytradermk4.xml ~2237-2310) host the executor for trader
           ships; without an equivalent block here collector-drone restock from GT_Maintenance
           sat in $GT_ResupplyOrders forever and the ship never undocked. Mirrors the
           trader pattern: docking-bay verify -> add_build_to_modify_ship -> wait up
           to 900s for GT_Maintenance_Complete (signaled by gt_maintenance.xml's
           ProcessResupplyComplete after order.build.equip.xml's completion patch
           queues GT_ResupplyComplete on wharf finish).

           ALIGNED WITH v8 (proven baseline). Differences vs the prior v9 draft:
           - No separate Repair branch: gt_maintenance.xml's RepairOrders flow is not
             produced for miners in the current pipeline; if it is later, mirror the
             trader pattern. Adding a stub create_order here was speculative and could
             have raced with the resupply wait below.
           - No this.$maintenance_transition flag: nothing in v9 actually consumes it,
             and leaving stale state on aborts requires extra cleanup.
           - The 900s wait is gated on $buildSuccessful: a failed wharf call never
             fires GT_Maintenance_Complete, so the prior "wait whenever a tracking
             entry exists" branch could hang for 900s on every dead station.
           - On a failed build we apply a 5min cooldown via global.$GT_MaintenanceFailedResupply.
           ========================================================================= -->
      <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
        <set_value name="$resupplyData" exact="global.$GT_ResupplyOrders.{this.ship}"/>
        <set_value name="$ammoTableKeys" exact="@$resupplyData.$AmmoTable.keys"/>
        <set_value name="$ammoTableCount" exact="@$ammoTableKeys.count"/>
        <set_value name="$unitTableKeys" exact="@$resupplyData.$UnitTable.keys"/>
        <set_value name="$unitTableCount" exact="@$unitTableKeys.count"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Found pending resupply order at ' + @$resupplyData.$Station.knownname + ' (Ammo types=' + $ammoTableCount + ', Unit types=' + $unitTableCount + ') - executing add_build_to_modify_ship'" chance="100"/>
        </do_if>

        <do_if value="$ammoTableCount? or $unitTableCount?">
          <set_value name="$resupplyStation" exact="$resupplyData.$Station"/>
          <set_value name="$canDockResupply" exact="false"/>
          <do_if value="@$resupplyStation.exists">
            <run_script name="'lib.gt.dockcheck'" result="$minerResupplyDockResult">
              <param name="ship" value="this.ship"/>
              <param name="station" value="$resupplyStation"/>
              <param name="purpose" value="'service_ai'"/>
            </run_script>
            <set_value name="$canDockResupply" exact="$minerResupplyDockResult.$CanDock"/>
          </do_if>

          <do_if value="$canDockResupply">
            <set_value name="$buildSuccessful" exact="false"/>
            <add_build_to_modify_ship
                object="$resupplyStation"
                buildobject="this.ship"
                ammo="$resupplyData.$AmmoTable"
                units="$resupplyData.$UnitTable"
                immediate="false"
                internal="true"
                result="$buildSuccessful"/>

            <do_if value="$buildSuccessful">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': add_build_to_modify_ship OK at ' + $resupplyStation.knownname + ' - waiting up to 900s for GT_Maintenance_Complete'" chance="100"/>
              </do_if>

              <wait max="900s">
                <interrupt>
                  <conditions>
                    <event_object_signalled object="this.ship" param="'GT_Maintenance_Complete'"/>
                  </conditions>
                  <actions>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': GT_Maintenance_Complete received, resuming mining'" chance="100"/>
                    </do_if>
                  </actions>
                </interrupt>
              </wait>

              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': resupply wait ended (completion or 900s timeout) - continuing main_loop'" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <!-- Build call rejected (station cannot fulfill the order, e.g. no probe stock).
                   Drop the tracking so DoMaintenance can retry on the next cycle, and apply a
                   5-min cooldown on the AI side so we do not hammer the same dead station. The
                   same blackboard variable is read by the mining routine's BUY block to
                   throttle its own GT_DoMaintenance signal. -->
              <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': add_build_to_modify_ship FAILED at ' + $resupplyStation.knownname + ' - clearing tracking + 5min cooldown'" chance="100"/>
              <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
              <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
                <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
              </do_if>
              <do_if value="not global.$GT_MaintenanceFailedResupply?">
                <set_value name="global.$GT_MaintenanceFailedResupply" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_MaintenanceFailedResupply.{this.ship}" exact="player.age + 300s"/>
            </do_else>
          </do_if>
          <do_else>
            <!-- Resupply station is no longer reachable for this ship's dock size. Drop the
                 tracking so the next cycle picks a different station. -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': resupply station ' + @$resupplyStation.knownname + ' has no compatible dock (ship size=' + this.ship.docksize + ') - clearing tracking'" chance="100"/>
            </do_if>
            <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
              <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <!-- Empty shopping list - nothing to buy, just clean up. -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': empty resupply shopping list - clearing tracking'" chance="100"/>
          </do_if>
          <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
          <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
            <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
          </do_if>
        </do_else>
      </do_if>

      <!-- Resolve home anchor.
           Home Station defines the operating anchor when set; Home Sector is the fallback
           for stationless miners. This keeps diagnostics and runtime range policy aligned. -->
      <set_value name="$range" exact="null"/>
      <do_if value="this.$homeStation? and this.$homeStation.exists and this.$homeStation.sector?">
        <set_value name="$range" exact="this.$homeStation.sector"/>
      </do_if>
      <do_elseif value="this.$homeSector? and this.$homeSector.exists">
        <set_value name="$range" exact="this.$homeSector"/>
      </do_elseif>
      <do_else>
        <set_value name="$range" exact="this.sector"/>
      </do_else>

      <!-- Resolve target stations -->
      <create_list name="$targetStations"/>
      <do_if value="this.$stationList? and this.$stationList.count gt 0">
        <do_all exact="this.$stationList.count" counter="$si">
          <set_value name="$stationCandidate" exact="this.$stationList.{$si}"/>
          <do_if value="$stationCandidate? and $stationCandidate.exists and $stationCandidate.isclass.station and $stationCandidate.isoperational">
            <set_value name="$allowStation" exact="true"/>
            <do_if value="this.$playerStationsOnly and $stationCandidate.owner != this.owner">
              <set_value name="$allowStation" exact="false"/>
            </do_if>
            <!-- B2: do not silently drop user-supplied stations just because they're outside the ship's current sector.
                 Use the effective home anchor (home station sector first, then home sector) as the real cap.
                 gatedistance == -1 means "unreachable / not connected"; gatedistance is unitless jumps. -->
            <do_if value="$allowStation and $stationCandidate.sector?">
              <set_value name="$stationListRefSector" exact="if this.$homeStation? and this.$homeStation.exists and this.$homeStation.sector? then this.$homeStation.sector else if this.$homeSector? and this.$homeSector.exists then this.$homeSector else this.ship.sector"/>
              <set_value name="$stationListGateDistance" exact="$stationListRefSector.gatedistance.{$stationCandidate.sector}"/>
              <do_if value="$stationListGateDistance lt 0 or $stationListGateDistance gt this.$maxSellDistance">
                <set_value name="$allowStation" exact="false"/>
                <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': stationList drop ' + $stationCandidate.idcode + ' sector=' + $stationCandidate.sector.knownname + ' dist=' + $stationListGateDistance + ' maxSell=' + this.$maxSellDistance" chance="this.$debugchance"/>
              </do_if>
            </do_if>
            <do_if value="$allowStation and not $targetStations.indexof.{$stationCandidate}">
              <append_to_list name="$targetStations" exact="$stationCandidate"/>
            </do_if>
          </do_if>
        </do_all>
      </do_if>
      <do_else>
        <do_if value="this.$homeStation? and this.$homeStation.exists and this.$homeStation.isoperational and ((not this.$playerStationsOnly) or (this.$homeStation.owner == this.owner))">
          <append_to_list name="$targetStations" exact="this.$homeStation"/>
        </do_if>
        <do_elseif value="this.$homeSector? and this.$homeSector.exists">
          <!-- No home station: derive demand stations by sell radius around home sector. -->
          <run_script name="'lib.find.sectors.inrange'" result="$demandSectors">
            <param name="refobject" value="this.$homeSector"/>
            <param name="mingatedistance" value="0"/>
            <param name="maxgatedistance" value="this.$maxSellDistance"/>
            <param name="debugchance" value="this.$debugchance"/>
          </run_script>
          <set_value name="this.$minerDemandSectorsScanList" exact="$demandSectors"/>
          <set_value name="this.$minerDemandSectorsScanIndex" exact="1"/>
          <do_while value="this.$minerDemandSectorsScanIndex? and this.$minerDemandSectorsScanList? and this.$minerDemandSectorsScanIndex le this.$minerDemandSectorsScanList.count">
            <set_value name="$chunkEnd" exact="[this.$minerDemandSectorsScanIndex + 4, this.$minerDemandSectorsScanList.count].min"/>
            <do_all exact="$chunkEnd - this.$minerDemandSectorsScanIndex + 1" counter="$chunkOffset">
              <set_value name="$dsi" exact="this.$minerDemandSectorsScanIndex + $chunkOffset - 1"/>
              <set_value name="$demandSector" exact="this.$minerDemandSectorsScanList.{$dsi}"/>
              <find_station name="$sectorStations" space="$demandSector" checkoperational="true" multiple="true"/>
              <do_all exact="$sectorStations.count" counter="$ssi">
                <set_value name="$sectorStation" exact="$sectorStations.{$ssi}"/>
                <do_if value="$sectorStation? and $sectorStation.exists and $sectorStation.isclass.station and $sectorStation.isoperational and ((not this.$playerStationsOnly) or ($sectorStation.owner == this.owner)) and not $targetStations.indexof.{$sectorStation}">
                  <append_to_list name="$targetStations" exact="$sectorStation"/>
                </do_if>
              </do_all>
            </do_all>
            <set_value name="this.$minerDemandSectorsScanIndex" exact="$chunkEnd + 1"/>
            <do_if value="this.$minerDemandSectorsScanIndex? and this.$minerDemandSectorsScanList? and this.$minerDemandSectorsScanIndex le this.$minerDemandSectorsScanList.count">
              <wait exact="1ms"/>
            </do_if>
          </do_while>
          <remove_value name="this.$minerDemandSectorsScanList"/>
          <remove_value name="this.$minerDemandSectorsScanIndex"/>
        </do_elseif>
        <do_else>
          <find_station name="$sectorStations" space="this.sector" checkoperational="true" multiple="true"/>
          <set_value name="this.$minerSectorStationsScanList" exact="$sectorStations"/>
          <set_value name="this.$minerSectorStationsScanIndex" exact="1"/>
          <do_while value="this.$minerSectorStationsScanIndex? and this.$minerSectorStationsScanList? and this.$minerSectorStationsScanIndex le this.$minerSectorStationsScanList.count">
            <set_value name="$chunkEnd" exact="[this.$minerSectorStationsScanIndex + 12, this.$minerSectorStationsScanList.count].min"/>
            <do_all exact="$chunkEnd - this.$minerSectorStationsScanIndex + 1" counter="$chunkOffset">
              <set_value name="$ssi" exact="this.$minerSectorStationsScanIndex + $chunkOffset - 1"/>
              <set_value name="$sectorStation" exact="this.$minerSectorStationsScanList.{$ssi}"/>
              <do_if value="$sectorStation? and $sectorStation.exists and $sectorStation.isclass.station and $sectorStation.isoperational and ((not this.$playerStationsOnly) or ($sectorStation.owner == this.owner)) and not $targetStations.indexof.{$sectorStation}">
                <append_to_list name="$targetStations" exact="$sectorStation"/>
              </do_if>
            </do_all>
            <set_value name="this.$minerSectorStationsScanIndex" exact="$chunkEnd + 1"/>
            <do_if value="this.$minerSectorStationsScanIndex? and this.$minerSectorStationsScanList? and this.$minerSectorStationsScanIndex le this.$minerSectorStationsScanList.count">
              <wait exact="1ms"/>
            </do_if>
          </do_while>
          <remove_value name="this.$minerSectorStationsScanList"/>
          <remove_value name="this.$minerSectorStationsScanIndex"/>
        </do_else>
      </do_else>

      <do_if value="$minerBlockedStations? and $minerBlockedStations.count gt 0 and $targetStations.count gt 0">
        <set_value name="$targetStationsBeforeBlockedFilter" exact="$targetStations.count"/>
        <create_list name="$targetStationsFiltered"/>
        <do_all exact="$targetStations.count" counter="$blockedTargetIdx">
          <set_value name="$targetStationCandidate" exact="$targetStations.{$blockedTargetIdx}"/>
          <set_value name="$targetStationBlocked" exact="false"/>
          <do_all exact="$minerBlockedStations.count" counter="$blockedStationIdx">
            <do_if value="$minerBlockedStations.{$blockedStationIdx}? and $targetStationCandidate == $minerBlockedStations.{$blockedStationIdx}">
              <set_value name="$targetStationBlocked" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $targetStationBlocked">
            <append_to_list name="$targetStationsFiltered" exact="$targetStationCandidate"/>
          </do_if>
        </do_all>
        <set_value name="$targetStations" exact="$targetStationsFiltered"/>
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Blocked-station filter: before=' + $targetStationsBeforeBlockedFilter + ', after=' + $targetStations.count + ', removed=' + ($targetStationsBeforeBlockedFilter - $targetStations.count)" chance="this.$debugchance"/>
      </do_if>

      <!-- Demand is derived from the actively served station set. -->
      <create_list name="$demandStations"/>
      <set_value name="this.$minerDemandStationsBuildTargetStations" exact="$targetStations"/>
      <set_value name="this.$minerDemandStationsBuildIndex" exact="1"/>
      <do_while value="this.$minerDemandStationsBuildIndex? and this.$minerDemandStationsBuildTargetStations? and this.$minerDemandStationsBuildIndex le this.$minerDemandStationsBuildTargetStations.count">
        <set_value name="$chunkEnd" exact="[this.$minerDemandStationsBuildIndex + 10, this.$minerDemandStationsBuildTargetStations.count].min"/>
        <do_all exact="$chunkEnd - this.$minerDemandStationsBuildIndex + 1" counter="$chunkOffset">
          <set_value name="$dsi" exact="this.$minerDemandStationsBuildIndex + $chunkOffset - 1"/>
          <set_value name="$demandStation" exact="this.$minerDemandStationsBuildTargetStations.{$dsi}"/>
          <do_if value="$demandStation? and $demandStation.exists and ((not this.$playerStationsOnly) or ($demandStation.owner == this.owner)) and not $demandStations.indexof.{$demandStation}">
            <append_to_list name="$demandStations" exact="$demandStation"/>
          </do_if>
        </do_all>
        <set_value name="this.$minerDemandStationsBuildIndex" exact="$chunkEnd + 1"/>
        <do_if value="this.$minerDemandStationsBuildIndex? and this.$minerDemandStationsBuildTargetStations? and this.$minerDemandStationsBuildIndex le this.$minerDemandStationsBuildTargetStations.count">
          <wait exact="1ms"/>
        </do_if>
      </do_while>
      <remove_value name="this.$minerDemandStationsBuildTargetStations"/>
      <remove_value name="this.$minerDemandStationsBuildIndex"/>

      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Loop anchor=' + (if $range? then $range.knownname else 'null') + ', homeStation=' + (if this.$homeStation? and this.$homeStation.exists then this.$homeStation.idcode else 'NONE') + ', homeSector=' + (if this.$homeSector? and this.$homeSector.exists then this.$homeSector.knownname else 'NONE') + ', playerStationsOnly=' + this.$playerStationsOnly + ', commander=' + (if this.ship.commander? and this.ship.commander.exists then this.ship.commander.idcode else 'NONE') + ', default=' + (if this.ship.defaultorder? then @this.ship.defaultorder.id else 'NONE') + ', targetStations=' + $targetStations.count + ', demandStations=' + $demandStations.count" chance="this.$debugchance"/>

      <!-- Resolve candidate wares -->
      <create_list name="$candidateWares"/>
      <set_value name="$shipMineableBasket" exact="this.ship.warebasket.list"/>
      <set_value name="$restrictToShipBasket" exact="$shipMineableBasket? and $shipMineableBasket.count gt 0"/>
      <do_if value="not $restrictToShipBasket">
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': ship.warebasket empty -> using fallback ware discovery from configured targets'" chance="this.$debugchance"/>
      </do_if>
      <do_if value="this.$resourceBasket? and this.$resourceBasket.count gt 0">
        <do_all exact="this.$resourceBasket.count" counter="$wi">
          <set_value name="$candidateWare" exact="this.$resourceBasket.{$wi}"/>
          <do_if value="$candidateWare? and ($candidateWare.waretransport == waretransport.solid or $candidateWare.waretransport == waretransport.liquid) and this.ship.cargo.{$candidateWare}.max gt 0 and (($restrictToShipBasket and $shipMineableBasket.indexof.{$candidateWare}) or (not $restrictToShipBasket)) and not $candidateWares.indexof.{$candidateWare}">
            <append_to_list name="$candidateWares" exact="$candidateWare"/>
          </do_if>
        </do_all>
      </do_if>
      <do_elseif value="this.$checkDemandFirst">
        <set_value name="this.$minerCandidateScanDemandStations" exact="$demandStations"/>
        <set_value name="this.$minerCandidateScanIndex" exact="1"/>
        <do_while value="this.$minerCandidateScanIndex? and this.$minerCandidateScanDemandStations? and this.$minerCandidateScanIndex le this.$minerCandidateScanDemandStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerCandidateScanIndex + 9, this.$minerCandidateScanDemandStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerCandidateScanIndex + 1" counter="$chunkOffset">
            <set_value name="$tsi" exact="this.$minerCandidateScanIndex + $chunkOffset - 1"/>
            <set_value name="$stationCandidate" exact="this.$minerCandidateScanDemandStations.{$tsi}"/>
            <set_value name="$stationCargoList" exact="$stationCandidate.cargo.list"/>
            <do_all exact="$stationCargoList.count" counter="$sci">
              <set_value name="$candidateWare" exact="$stationCargoList.{$sci}"/>
              <!-- A1: require hastag.minable so non-mineable solids/liquids (food, hull parts, ...) cannot enter the ware pool when shipMineableBasket is empty. -->
              <do_if value="$candidateWare? and $candidateWare.hastag.minable and ($candidateWare.waretransport == waretransport.solid or $candidateWare.waretransport == waretransport.liquid) and this.ship.cargo.{$candidateWare}.max gt 0 and (($restrictToShipBasket and $shipMineableBasket.indexof.{$candidateWare}) or (not $restrictToShipBasket)) and not $candidateWares.indexof.{$candidateWare}">
                <append_to_list name="$candidateWares" exact="$candidateWare"/>
              </do_if>
            </do_all>
          </do_all>
          <set_value name="this.$minerCandidateScanIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerCandidateScanIndex? and this.$minerCandidateScanDemandStations? and this.$minerCandidateScanIndex le this.$minerCandidateScanDemandStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <remove_value name="this.$minerCandidateScanDemandStations"/>
        <remove_value name="this.$minerCandidateScanIndex"/>
      </do_elseif>
      <do_else>
        <!-- Demand-off fixed basket: Resource Basket if set, else ship warebasket, else vanilla empty-basket
             fallback (home/target station configured resources â€” not live demand scoring). -->
        <do_if value="$shipMineableBasket? and $shipMineableBasket.count gt 0">
          <do_all exact="$shipMineableBasket.count" counter="$wi">
            <set_value name="$candidateWare" exact="$shipMineableBasket.{$wi}"/>
            <do_if value="$candidateWare? and $candidateWare.hastag.minable and ($candidateWare.waretransport == waretransport.solid or $candidateWare.waretransport == waretransport.liquid) and this.ship.cargo.{$candidateWare}.max gt 0 and not $candidateWares.indexof.{$candidateWare}">
              <append_to_list name="$candidateWares" exact="$candidateWare"/>
            </do_if>
          </do_all>
        </do_if>
        <do_else>
          <!-- Mirror vanilla order.mining.routine.xml: empty manual basket â†’ populate from homebase
               resources.list + supplyresources + tradewares (station configuration, not buy-offer scan). -->
          <set_value name="this.$minerVanillaSeedStations" exact="[]"/>
          <do_if value="$demandStations? and $demandStations.count gt 0">
            <set_value name="this.$minerVanillaSeedStations" exact="$demandStations"/>
          </do_if>
          <do_elseif value="this.$homeStation? and this.$homeStation.exists">
            <append_to_list name="this.$minerVanillaSeedStations" exact="this.$homeStation"/>
          </do_elseif>
          <set_value name="this.$minerVanillaSeedIndex" exact="1"/>
          <do_while value="this.$minerVanillaSeedIndex? and this.$minerVanillaSeedStations? and this.$minerVanillaSeedIndex le this.$minerVanillaSeedStations.count">
            <set_value name="$chunkEnd" exact="[this.$minerVanillaSeedIndex + 4, this.$minerVanillaSeedStations.count].min"/>
            <do_all exact="$chunkEnd - this.$minerVanillaSeedIndex + 1" counter="$chunkOffset">
              <set_value name="$vsi" exact="this.$minerVanillaSeedIndex + $chunkOffset - 1"/>
              <set_value name="$vanillaSeedStation" exact="this.$minerVanillaSeedStations.{$vsi}"/>
              <do_if value="$vanillaSeedStation? and $vanillaSeedStation.exists">
                <set_value name="$vanillaResources" exact="$vanillaSeedStation.resources.list"/>
                <set_value name="$vanillaSupply" exact="$vanillaSeedStation.supplyresources.list"/>
                <do_all exact="$vanillaSupply.count" counter="$vri">
                  <do_if value="not $vanillaResources.indexof.{$vanillaSupply.{$vri}}">
                    <append_to_list name="$vanillaResources" exact="$vanillaSupply.{$vri}"/>
                  </do_if>
                </do_all>
                <set_value name="$vanillaTradewares" exact="$vanillaSeedStation.tradewares.list"/>
                <do_all exact="$vanillaTradewares.count" counter="$vti">
                  <do_if value="not $vanillaResources.indexof.{$vanillaTradewares.{$vti}}">
                    <append_to_list name="$vanillaResources" exact="$vanillaTradewares.{$vti}"/>
                  </do_if>
                </do_all>
                <do_for_each name="$vanillaWare" in="$vanillaResources">
                  <do_if value="$vanillaWare? and $vanillaWare.hastag.minable and ($vanillaWare.waretransport == waretransport.solid or $vanillaWare.waretransport == waretransport.liquid) and this.ship.cargo.{$vanillaWare}.max gt 0 and not $candidateWares.indexof.{$vanillaWare}">
                    <append_to_list name="$candidateWares" exact="$vanillaWare"/>
                  </do_if>
                </do_for_each>
                <remove_value name="$vanillaResources"/>
                <remove_value name="$vanillaSupply"/>
                <remove_value name="$vanillaTradewares"/>
              </do_if>
            </do_all>
            <set_value name="this.$minerVanillaSeedIndex" exact="$chunkEnd + 1"/>
            <do_if value="this.$minerVanillaSeedIndex? and this.$minerVanillaSeedStations? and this.$minerVanillaSeedIndex le this.$minerVanillaSeedStations.count">
              <wait exact="1ms"/>
            </do_if>
          </do_while>
          <remove_value name="this.$minerVanillaSeedIndex"/>
          <remove_value name="this.$minerVanillaSeedStations"/>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Demand-off empty basket â€” vanilla seed from station config: ' + $candidateWares.count + ' mineable ware(s)'" chance="this.$debugchance"/>
        </do_else>
      </do_else>

      <!-- Always-on buy-offer pass (demand-first mode only). station.cargo.list returns wares the station has currently
           configured / has cargo for; station.find_buy_offer returns wares the station actively
           buys regardless of current stock. A refinery that consumes Ore + Silicon with Silicon in
           stock and Ore at zero would otherwise expose only Silicon to scoring (cargo.list omits
           Ore), making Ore permanently invisible. The previous gate `$candidateWares.count == 0`
           skipped this pass whenever the cargo.list pass produced any candidate, hiding Ore behind
           Silicon's mere presence. Dedup is enforced by `not $candidateWares.indexof.{$candidateWare}`
           in the inner accept gate so wares discovered by both passes are not added twice.
           The previous `global.$GT_FallbackActivations.{'Miner.BuyOfferCandidateFallback'}` increment
           is removed: the AI-script expression evaluator resolves `set_value name="global.$X.{'key'}"`
           against a value-snapshot of $X (not the real storage) and crashes the slice as soon as
           this path runs in production. The same pattern is intentionally still used MD-side. -->
      <do_if value="this.$checkDemandFirst and $demandStations.count gt 0">
        <set_value name="this.$minerBuyOfferScanDemandStations" exact="$demandStations"/>
        <set_value name="this.$minerBuyOfferScanIndex" exact="1"/>
        <do_while value="this.$minerBuyOfferScanIndex? and this.$minerBuyOfferScanDemandStations? and this.$minerBuyOfferScanIndex le this.$minerBuyOfferScanDemandStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerBuyOfferScanIndex + 4, this.$minerBuyOfferScanDemandStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerBuyOfferScanIndex + 1" counter="$chunkOffset">
            <set_value name="$tsi" exact="this.$minerBuyOfferScanIndex + $chunkOffset - 1"/>
            <set_value name="$stationCandidate" exact="this.$minerBuyOfferScanDemandStations.{$tsi}"/>
            <find_buy_offer buyer="$stationCandidate" tradepartner="this.ship" result="$stationBuyOffers" multiple="true"/>
            <do_all exact="$stationBuyOffers.count" counter="$boi">
              <set_value name="$buyOffer" exact="$stationBuyOffers.{$boi}"/>
              <set_value name="$candidateWare" exact="$buyOffer.ware"/>
              <do_if value="$candidateWare? and $candidateWare.hastag.minable and this.ship.cargo.{$candidateWare}.max gt 0 and (($restrictToShipBasket and $shipMineableBasket.indexof.{$candidateWare}) or (not $restrictToShipBasket)) and (not this.$resourceBasket? or this.$resourceBasket.count == 0 or this.$resourceBasket.indexof.{$candidateWare}) and not $candidateWares.indexof.{$candidateWare}">
                <append_to_list name="$candidateWares" exact="$candidateWare"/>
              </do_if>
            </do_all>
          </do_all>
          <set_value name="this.$minerBuyOfferScanIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerBuyOfferScanIndex? and this.$minerBuyOfferScanDemandStations? and this.$minerBuyOfferScanIndex le this.$minerBuyOfferScanDemandStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <remove_value name="this.$minerBuyOfferScanDemandStations"/>
        <remove_value name="this.$minerBuyOfferScanIndex"/>
      </do_if>

      <!-- Defensive normalization: remove null/duplicate ware entries before scoring.
           This prevents null table keys if upstream scans ever produce sparse entries. -->
      <create_list name="$normalizedCandidateWares"/>
      <do_all exact="$candidateWares.count" counter="$ncwi">
        <set_value name="$normalizedWare" exact="$candidateWares.{$ncwi}"/>
        <do_if value="$normalizedWare? and not $normalizedCandidateWares.indexof.{$normalizedWare}">
          <append_to_list name="$normalizedCandidateWares" exact="$normalizedWare"/>
        </do_if>
      </do_all>
      <set_value name="$candidateWares" exact="$normalizedCandidateWares"/>

      <!-- ============================================================================ -->
      <!-- CARGO-FIRST INJECTION (pre-scoring guard)                                    -->
      <!--                                                                              -->
      <!--                                                                              -->
      <!-- Fix: BEFORE the no-candidates early-return, scan the ship's actual cargo for -->
      <!-- any ware that some $demandStations entry has capacity for. If found, append  -->
      <!-- it to $candidateWares so:                                                    -->
      <!--   (a) the no-candidates early-return below does not fire,                    -->
      <!--   (b) scoring sees the ware (it scores low because there's no asteroid       -->
      <!--       demand context but that's fine - scoring stays a "what to MINE" pass), -->
      <!--   (c) the post-scoring CARGO-FIRST OVERRIDE block at line ~1044 picks the    -->
      <!--       ware as $selectedWare and the standard primary-delivery block at line  -->
      <!--       ~1437 routes the ship to the buyer.                                    -->
      <!--                                                                              -->
      <!-- Acceptance gate per cargo ware:                                              -->
      <!--   1. Non-zero count in this.ship.cargo.{ware}                                -->
      <!--   2. Ware is minable AND of waretransport solid/liquid (consistent with the  -->
      <!--      candidate-build filters at lines 677/694 - no manufactured wares get    -->
      <!--      injected even if a player accidentally loaded some)                     -->
      <!--   3. SOME station in $demandStations has target > 0 for the ware AND         -->
      <!--      currentStock/target < $overflowThreshold (capacity left for delivery).  -->
      <!--                                                                              -->
      <!-- Cargo may only influence the delivery-first path when it is still allowed by -->
      <!-- the Resource Basket. The basket is authoritative for what the miner mines;   -->
      <!-- accidental/off-basket cargo is handled by the sell path, not by promoting it -->
      <!-- back into mining candidates.                                                -->
      <!-- ============================================================================ -->
      <do_if value="this.ship.cargo.list? and this.ship.cargo.list.count gt 0 and $demandStations? and $demandStations.count gt 0">
        <do_for_each name="$cargoInjectWare" in="this.ship.cargo.list">
          <set_value name="$cargoInjectInResourceBasket" exact="true"/>
          <do_if value="$cargoInjectWare? and $cargoInjectWare != null and this.$resourceBasket? and this.$resourceBasket.count gt 0 and (not this.$resourceBasket.indexof.{$cargoInjectWare})">
            <set_value name="$cargoInjectInResourceBasket" exact="false"/>
          </do_if>
          <do_if value="$cargoInjectWare? and $cargoInjectWare != null and $restrictToShipBasket and not $shipMineableBasket.indexof.{$cargoInjectWare}">
            <set_value name="$cargoInjectInResourceBasket" exact="false"/>
          </do_if>
          <do_if value="$cargoInjectWare? and $cargoInjectWare != null and $cargoInjectInResourceBasket and not $candidateWares.indexof.{$cargoInjectWare} and $cargoInjectWare.hastag.minable and ($cargoInjectWare.waretransport == waretransport.solid or $cargoInjectWare.waretransport == waretransport.liquid) and this.ship.cargo.{$cargoInjectWare}.count gt 0">
            <set_value name="$cargoInjectHasBuyer" exact="false"/>
            <do_for_each name="$cargoInjectStation" in="$demandStations">
              <do_if value="$cargoInjectHasBuyer">
                <break/>
              </do_if>
              <do_if value="$cargoInjectStation? and $cargoInjectStation.exists">
                <set_value name="$cargoInjectTarget" exact="@$cargoInjectStation.cargo.{$cargoInjectWare}.target"/>
                <do_if value="$cargoInjectTarget? and $cargoInjectTarget gt 0">
                  <set_value name="$cargoInjectCount" exact="@$cargoInjectStation.cargo.{$cargoInjectWare}.count"/>
                  <set_value name="$cargoInjectPercent" exact="if $cargoInjectTarget gt 0 then ($cargoInjectCount * 100) / $cargoInjectTarget else 100"/>
                  <do_if value="$cargoInjectPercent lt this.$overflowThreshold">
                    <set_value name="$cargoInjectHasBuyer" exact="true"/>
                  </do_if>
                  <remove_value name="$cargoInjectCount"/>
                  <remove_value name="$cargoInjectPercent"/>
                </do_if>
                <do_if value="$cargoInjectTarget?"><remove_value name="$cargoInjectTarget"/></do_if>
              </do_if>
            </do_for_each>
            <do_if value="$cargoInjectHasBuyer">
              <append_to_list name="$candidateWares" exact="$cargoInjectWare"/>
              <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': CARGO-FIRST inject - ware ' + $cargoInjectWare.name + ' x' + this.ship.cargo.{$cargoInjectWare}.count + ' is in cargo and has a willing primary buyer; appended to candidate set so scoring + primary-delivery can route the ship to deliver instead of stalling at no-candidates wait.'" chance="this.$debugchance"/>
            </do_if>
            <remove_value name="$cargoInjectHasBuyer"/>
          </do_if>
          <remove_value name="$cargoInjectInResourceBasket"/>
        </do_for_each>
        <do_if value="$cargoInjectStation?"><remove_value name="$cargoInjectStation"/></do_if>
        <do_if value="$cargoInjectWare?"><remove_value name="$cargoInjectWare"/></do_if>
      </do_if>

      <do_if value="$candidateWares.count == 0">
        <!-- Differentiated diagnostic: distinguish "no demand stations have anything we     -->
        <!-- can mine" (the original case) from "no demand AND no deliverable cargo" (the    -->
        <!-- truly stuck case). Both still fall through to the wait, but the log line tells  -->
        <!-- the player which lever fixes it (add a buyer station vs. unload manually).      -->
        <set_value name="$noCandHasCargo" exact="this.ship.cargo.list? and this.ship.cargo.list.count gt 0 and (this.ship.cargo.capacity.all - this.ship.cargo.free.all) gt 0"/>
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': No mineable wares. demandStationCount=' + $demandStations.count + ', resourceBasketCount=' + (if this.$resourceBasket? then this.$resourceBasket.count else 0) + ', shipMineableCount=' + (if $shipMineableBasket? then $shipMineableBasket.count else 0) + ', restrictToShipBasket=' + $restrictToShipBasket + ', cargoUsed=' + (this.ship.cargo.capacity.all - this.ship.cargo.free.all) + '/' + this.ship.cargo.capacity.all + (if $noCandHasCargo then ' (cargo present but NO demand station has capacity for any ware in the bay - all primary buyers are full or the cargo wares are not in any buyer config; lower threshold or add a buyer to free this ship)' else '')" chance="this.$debugchance"/>
        <!-- Resolve the fleet name: top-level fleet commander's fleet name when this miner is a
             subordinate, else its own fleet name. fleet.name is an empty string for non-fleet ships.
             fleet.commander? alone is insufficient â€” commander is null for non-fleet-commander ships. -->
        <set_value name="$minerFleetName" exact="'-'"/>
        <do_if value="this.ship.fleet? and this.ship.fleet.commander? and this.ship.fleet.commander.fleet? and this.ship.fleet.commander.fleet.name?">
          <set_value name="$minerFleetName" exact="this.ship.fleet.commander.fleet.name"/>
        </do_if>
        <do_elseif value="this.ship.fleet? and this.ship.fleet.name?">
          <set_value name="$minerFleetName" exact="this.ship.fleet.name"/>
        </do_elseif>
        <do_if value="$minerFleetName == ''">
          <set_value name="$minerFleetName" exact="'-'"/>
        </do_if>
        <show_notification text="{77000, 31200}.[this.ship.knownname, this.ship.idcode, $minerFleetName]" timeout="8s"/>
        <remove_value name="$minerFleetName"/>
        <remove_value name="$noCandHasCargo"/>
        <set_value name="this.$minerIdleNoWorkCount" exact="[this.$minerIdleNoWorkCount + 1, 5].min"/>
        <do_if value="this.$idleParking and this.$minerIdleNoWorkCount ge 5 and this.ship.cargo.count == 0">
          <set_value name="$minerIdleHome" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
          <do_if value="$minerIdleHome? and $minerIdleHome != null">
            <run_script name="'lib.gt.idlepark'">
              <param name="handoffMode" value="'trigger'"/>
              <param name="handoffShip" value="this.ship"/>
              <param name="home" value="$minerIdleHome"/>
              <param name="debugchance" value="this.$debugchance"/>
            </run_script>
          </do_if>
        </do_if>
        <wait exact="this.$demandRecheckInterval"/>
        <resume label="main_loop"/>
      </do_if>

      <!-- Clear previous cycle assignment/intent records for this ship -->
      <do_if value="this.$minerAssignedWare? and this.$minerAssignedStations? and this.$minerAssignedStations.count gt 0">
        <set_value name="this.$minerCleanupAssignedIndex" exact="1"/>
        <do_while value="this.$minerCleanupAssignedIndex? and this.$minerAssignedStations? and this.$minerCleanupAssignedIndex le this.$minerAssignedStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerCleanupAssignedIndex + 12, this.$minerAssignedStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerCleanupAssignedIndex + 1" counter="$chunkOffset">
            <set_value name="$asi" exact="this.$minerCleanupAssignedIndex + $chunkOffset - 1"/>
            <set_value name="$assignedStation" exact="this.$minerAssignedStations.{$asi}"/>
            <remove_value name="global.$GT_MinerStationAssignments.{$assignedStation}.{this.$minerAssignedWare}.{this.ship}"/>
          </do_all>
          <set_value name="this.$minerCleanupAssignedIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerCleanupAssignedIndex? and this.$minerAssignedStations? and this.$minerCleanupAssignedIndex le this.$minerAssignedStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <remove_value name="this.$minerCleanupAssignedIndex"/>
      </do_if>
      <do_if value="this.$minerIntentWare? and this.$minerIntentWare != null and this.$minerIntentStations? and this.$minerIntentStations.count gt 0">
        <set_value name="this.$minerCleanupIntentIndex" exact="1"/>
        <do_while value="this.$minerCleanupIntentIndex? and this.$minerIntentStations? and this.$minerCleanupIntentIndex le this.$minerIntentStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerCleanupIntentIndex + 12, this.$minerIntentStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerCleanupIntentIndex + 1" counter="$chunkOffset">
            <set_value name="$isi" exact="this.$minerCleanupIntentIndex + $chunkOffset - 1"/>
            <set_value name="$intentStation" exact="this.$minerIntentStations.{$isi}"/>
            <remove_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}"/>
          </do_all>
          <set_value name="this.$minerCleanupIntentIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerCleanupIntentIndex? and this.$minerIntentStations? and this.$minerCleanupIntentIndex le this.$minerIntentStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <remove_value name="this.$minerCleanupIntentIndex"/>
      </do_if>
      <set_value name="this.$minerAssignedStations" exact="[]"/>
      <set_value name="this.$minerAssignedWare" exact="null"/>
      <set_value name="this.$minerIntentStations" exact="[]"/>
      <set_value name="this.$minerIntentWare" exact="null"/>

      <!-- Score each ware by live station demand urgency -->
      <set_value name="$wareUrgency" exact="table[]"/>
      <set_value name="$wareHasPrimaryCapacity" exact="table[]"/>
      <set_value name="$wareReachable" exact="table[]"/>
      <set_value name="$bestWare" exact="null"/>
      <set_value name="$bestUrgency" exact="-1"/>
      <create_list name="$bestWares"/>
      <set_value name="$wareReachabilityRefSector" exact="if $range? and $range.isclass.sector then $range else (if $range? and $range.sector? then @$range.sector else this.sector)"/>
      <run_script name="'lib.find.sectors.inrange'" result="$wareReachabilityGatherSpaces">
        <param name="refobject" value="$wareReachabilityRefSector"/>
        <param name="mingatedistance" value="0"/>
        <param name="maxgatedistance" value="if this.$stayAtHome then 0 else this.$maxGatherDistance"/>
        <param name="debugchance" value="this.$debugchance"/>
      </run_script>
      <do_if value="this.ship.isplayerowned and (if this.$stayAtHome then 0 else this.$maxGatherDistance) le 0 and $wareReachabilityRefSector.isclass.sector and not $wareReachabilityGatherSpaces.indexof.{$wareReachabilityRefSector}">
        <append_to_list name="$wareReachabilityGatherSpaces" exact="$wareReachabilityRefSector"/>
      </do_if>
      <!-- A4: Pre-filter gather sectors so wares whose only reachable resource sector is hostile, hazardous,
           contested-by-attackers, or sector-activity-blacklisted are not promoted to "reachable".
           Mirrors the checks the routine itself applies (order.mining.routine.gt.xml ~942 and ~1115).
           Always keep the ship's current sector and the commander's sector regardless, matching routine behavior. -->
      <include_interrupt_actions ref="GetBlacklistgroup"/>
      <!-- GetBlacklistgroup only sets $blacklistgroup if $loctarget is operational; guard the capture so
           a momentary non-operational ship state doesn't cause a property lookup error in the filter below. -->
      <set_value name="$gatherSectorBlacklistGroup" exact="if $blacklistgroup? then $blacklistgroup else null"/>
      <do_if value="$blacklistgroup?">
        <remove_value name="$blacklistgroup"/>
      </do_if>
      <set_value name="this.$minerGatherFilterIn" exact="$wareReachabilityGatherSpaces"/>
      <set_value name="this.$minerGatherFilterOut" exact="[]"/>
      <set_value name="this.$minerGatherFilterIndex" exact="1"/>
      <do_while value="this.$minerGatherFilterIndex? and this.$minerGatherFilterIn? and this.$minerGatherFilterIndex le this.$minerGatherFilterIn.count">
        <set_value name="$chunkEnd" exact="[this.$minerGatherFilterIndex + 5, this.$minerGatherFilterIn.count].min"/>
        <do_all exact="$chunkEnd - this.$minerGatherFilterIndex + 1" counter="$chunkOffset">
          <set_value name="$gfi" exact="this.$minerGatherFilterIndex + $chunkOffset - 1"/>
          <set_value name="$gatherSpaceFilter" exact="this.$minerGatherFilterIn.{$gfi}"/>
          <do_if value="$gatherSpaceFilter? and $gatherSpaceFilter.exists and $gatherSpaceFilter.isclass.sector">
            <set_value name="$keepGatherSector" exact="true"/>
            <do_if value="$gatherSpaceFilter == this.ship.sector or (this.ship.commander? and this.ship.commander.exists and this.ship.commander.sector? and $gatherSpaceFilter == @this.ship.commander.sector)">
              <!-- always keep current/commander sector -->
            </do_if>
            <do_else>
              <do_if value="$gatherSpaceFilter.owner? and this.hasrelation.enemy.{$gatherSpaceFilter.owner}">
                <set_value name="$keepGatherSector" exact="false"/>
              </do_if>
              <do_if value="$keepGatherSector and $gatherSpaceFilter.hashazardousregion and not $gatherSpaceFilter.containsthewave and this.ship.takesregiondamage">
                <set_value name="$keepGatherSector" exact="false"/>
              </do_if>
              <do_if value="$keepGatherSector and $gatherSpaceFilter.iscontested and not $gatherSpaceFilter.contestingfactions.indexof.{this.owner}">
                <do_for_each name="$contestingFaction" in="$gatherSpaceFilter.contestingfactions">
                  <do_if value="$contestingFaction.mayattack.{this.ship}">
                    <set_value name="$keepGatherSector" exact="false"/>
                    <break/>
                  </do_if>
                </do_for_each>
              </do_if>
              <do_if value="$keepGatherSector and this.ship.isplayerowned and $gatherSectorBlacklistGroup? and this.ship.hasblacklist.{blacklisttype.sectoractivity}.{$gatherSectorBlacklistGroup} and $gatherSpaceFilter.isblacklisted.{blacklisttype.sectoractivity}.{$gatherSectorBlacklistGroup}.{this.ship}">
                <set_value name="$keepGatherSector" exact="false"/>
              </do_if>
            </do_else>
            <do_if value="$keepGatherSector">
              <append_to_list name="this.$minerGatherFilterOut" exact="$gatherSpaceFilter"/>
            </do_if>
          </do_if>
        </do_all>
        <set_value name="this.$minerGatherFilterIndex" exact="$chunkEnd + 1"/>
        <do_if value="this.$minerGatherFilterIndex? and this.$minerGatherFilterIn? and this.$minerGatherFilterIndex le this.$minerGatherFilterIn.count">
          <wait exact="1ms"/>
        </do_if>
      </do_while>
      <set_value name="$wareReachabilityGatherSpaces" exact="this.$minerGatherFilterOut"/>
      <remove_value name="this.$minerGatherFilterIn"/>
      <remove_value name="this.$minerGatherFilterOut"/>
      <remove_value name="this.$minerGatherFilterIndex"/>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Gather sector filter kept=' + $wareReachabilityGatherSpaces.count + ', blacklistGroup=' + (if $gatherSectorBlacklistGroup? then $gatherSectorBlacklistGroup else 'NONE')" chance="this.$debugchance"/>
      <!-- Chunked ware scoring with cooperative yields between chunks.
           Uses persisted state because AI locals do not survive across wait yields. -->
      <set_value name="this.$minerScoreCandidateWares" exact="$candidateWares"/>
      <set_value name="this.$minerScoreGatherSpaces" exact="$wareReachabilityGatherSpaces"/>
      <set_value name="this.$minerScoreDemandStations" exact="$demandStations"/>
      <set_value name="this.$minerScoreWareUrgency" exact="table[]"/>
      <set_value name="this.$minerScoreWareHasPrimaryCapacity" exact="table[]"/>
      <set_value name="this.$minerScoreWareReachable" exact="table[]"/>
      <!-- Discoverability map (separate from reachable): authoritative per-ware result of the
           find_closest_resource discovery probe for player ships (true for NPC ships).
           Published in the diag snapshot so the diagnose tool can show the engine's actual discovery
           state (rather than relying on the probe-presence MD proxy). -->
      <set_value name="this.$minerScoreWareDiscoverable" exact="table[]"/>
      <set_value name="this.$minerScoreReachablePickList" exact="[]"/>
      <set_value name="this.$minerScoreBestUrgency" exact="-1"/>
      <set_value name="this.$minerScoreBestWares" exact="[]"/>
      <set_value name="this.$minerScoreIndex" exact="1"/>
      <do_while value="this.$minerScoreIndex? and this.$minerScoreCandidateWares? and this.$minerScoreIndex le this.$minerScoreCandidateWares.count">
        <set_value name="$chunkEnd" exact="[this.$minerScoreIndex + 9, this.$minerScoreCandidateWares.count].min"/>
        <do_all exact="$chunkEnd - this.$minerScoreIndex + 1" counter="$chunkOffset">
          <set_value name="$wi" exact="this.$minerScoreIndex + $chunkOffset - 1"/>
          <set_value name="$wareEval" exact="this.$minerScoreCandidateWares.{$wi}"/>
          <do_if value="not $wareEval?">
            <continue/>
          </do_if>
          <!-- Reachability check (vanilla-aligned, mirrors order.mining.routine.xml ~1086-1141):
               - Primary signal is sector.resources.{ware}.exists; vanilla does not require a non-zero
                 sector.yieldrating before it calls find_closest_resource. A resource probe can report
                 sector/probe yield 0 while the engine can still resolve a valid discovered field.
               - Yield is still read for diagnostics, but it must not be a hard pre-filter.
               - For player-owned ships, a single per-ware find_closest_resource probe verifies the
                 engine can actually locate a discovered asteroid before promoting the ware to
                 "reachable" (otherwise the routine downstream falls through and the miner stalls on
                 "found nothing"). NPC ships skip the probe. NOTE: the legacy "useundiscovered"
                 attribute does NOT exist on find_closest_resource in the XSD and has been removed;
                 vanilla order.mining.routine.xml passes no discovered-filter, so the engine applies
                 faction-appropriate discovery by default. -->
          <!-- ============================================================================ -->
          <!-- FUSED REACHABILITY + DISCOVERY PROBE                                         -->
          <!--                                                                              -->
          <!-- Single pass over gather sectors, doing the cheap checks before the expensive -->
          <!-- engine call, with proper early exit. Replaces a previous two-pass design     -->
          <!-- that had three real efficiency problems:                                     -->
          <!--                                                                              -->
          <!--   1. Reachability used <do_all> with <break/>. <break> in MD only works in   -->
          <!--      do_while / do_for_each / do_each - NOT do_all (fixed-count iteration).  -->
          <!--      So the loop scanned every gather sector even after finding a hit.       -->
          <!--                                                                              -->
          <!--   2. Reachability and discovery were separate loops over the same gather     -->
          <!--      list. Two passes through the same data.                                 -->
          <!--                                                                              -->
          <!--   3. The discovery loop called find_closest_resource on EVERY gather sector  -->
          <!--      regardless of whether the sector even had asteroids of this ware. The   -->
          <!--      cheap MD check (sector.resources.{ware}.exists) was only consulted by   -->
          <!--      the reachability pass; the discovery pass blindly hit the engine. For   -->
          <!--      a fleet of 50 miners with 3 wares and 13 gather sectors, that's ~2000  -->
          <!--      engine calls per minute, many of them wasted on empty sectors.          -->
          <!--                                                                              -->
          <!-- This fused loop:                                                             -->
          <!--   - Iterates gather sectors via do_for_each so <break/> actually works.      -->
          <!--   - Does the cheap MD checks first (sector validity, resources.exists)        -->
          <!--     BEFORE the expensive engine call.                                        -->
          <!--   - For player ships with a sector that passes the cheap checks, immediately -->
          <!--     runs find_closest_resource useundiscovered="false" anchored on THAT     -->
          <!--     sector (vanilla pattern - see comment block below for the ship-anchor    -->
          <!--     bug history). NPC ships skip the engine call entirely (always            -->
          <!--     discoverable, mirroring vanilla useundiscovered="not isplayerowned").    -->
          <!--   - Breaks out as soon as both flags are true (ware is reachable AND         -->
          <!--     discoverable - we have everything we need). NPC ships break out as soon  -->
          <!--     as reachable becomes true (discoverable is initialized true for them).   -->
          <!--                                                                              -->
          <!-- PER-SAFE-SECTOR ANCHORING (mirrors gt_context_diagnose.xml:1925-1956 fix):   -->
          <!-- Previously used refobject="this.ship" for the discovery probe. That call    -->
          <!-- folds the ship's current position / accessibility into the resolution -      -->
          <!-- sibling player-owned miners at the exact same wall-clock tick disagreed     -->
          <!-- on whether Silicon was discovered (ship A in Heretic's End said             -->
          <!-- undiscovered, ship B in Watchful Gaze said discovered) even though          -->
          <!-- player faction-wide discovery state was identical for both. Vanilla         -->
          <!-- order.mining.routine.xml never anchors find_closest_resource on this.ship - -->
          <!-- it iterates gather spaces and anchors on each sector. We mirror that here.  -->
          <!--                                                                              -->
          <!-- Cost per ware (typical: 3 wares, 13 gather sectors):                        -->
          <!--   Old: 13 cheap + 13 engine calls = 26 ops, no early exit                   -->
          <!--   New: <=13 cheap + <=13 engine calls (only sectors with asteroids), with   -->
          <!--        early exit on first hit. Real-world: typically 2-4 engine calls per  -->
          <!--        ware before break, ~80% reduction.                                   -->
          <!-- ============================================================================ -->
          <set_value name="$wareHasResourceInRange" exact="false"/>
          <set_value name="$wareIsMineable" exact="not this.ship.isplayerowned"/>
          <set_value name="$wareIsDiscoverable" exact="not this.ship.isplayerowned"/>
          <do_for_each name="$gatherSectorEval" in="this.$minerScoreGatherSpaces">
            <do_if value="$wareIsMineable">
              <break/>
            </do_if>
            <do_if value="$gatherSectorEval? and $gatherSectorEval.exists and $gatherSectorEval.isclass.sector and $gatherSectorEval.resources.{$wareEval}.exists">
              <set_value name="$wareHasResourceInRange" exact="true"/>
              <do_if value="not this.ship.isplayerowned">
                <set_value name="$wareIsMineable" exact="true"/>
                <set_value name="$wareIsDiscoverable" exact="true"/>
                <break/>
              </do_if>
              <do_else>
                <set_value name="$scoreDiscTrySec" exact="null"/>
                <set_value name="$scoreDiscTryPos" exact="null"/>
                <find_closest_resource sector="$scoreDiscTrySec" position="$scoreDiscTryPos" ware="$wareEval" refobject="$gatherSectorEval" minamount="1">
                  <refposition value="$gatherSectorEval.coreposition" object="$gatherSectorEval" max="$gatherSectorEval.coresize / 4m"/>
                </find_closest_resource>
                <wait exact="1ms"/>
                <do_if value="$scoreDiscTrySec? and @$scoreDiscTrySec.exists">
                  <set_value name="$wareIsMineable" exact="true"/>
                  <set_value name="$wareIsDiscoverable" exact="true"/>
                  <break/>
                </do_if>
                <do_if value="$scoreDiscTrySec?"><remove_value name="$scoreDiscTrySec"/></do_if>
                <do_if value="$scoreDiscTryPos?"><remove_value name="$scoreDiscTryPos"/></do_if>
              </do_else>
            </do_if>
          </do_for_each>
          <do_if value="$gatherSectorEval?"><remove_value name="$gatherSectorEval"/></do_if>
          <do_if value="$wareEval?">
            <!-- Reachable for downstream gates (CARGO-FIRST, overflow, phys gate) means the engine
                 can route to a discovered asteroid this slice â€” not merely that resources.exists. -->
            <set_value name="this.$minerScoreWareReachable.{$wareEval}" exact="$wareIsMineable"/>
            <set_value name="this.$minerScoreWareDiscoverable.{$wareEval}" exact="$wareIsDiscoverable"/>
          </do_if>
          <set_value name="$urgency" exact="0"/>
          <set_value name="$hasPrimaryCapacity" exact="false"/>
          <do_if value="not this.$checkDemandFirst and $wareIsMineable and $wareEval? and not this.$minerScoreReachablePickList.indexof.{$wareEval}">
            <append_to_list name="this.$minerScoreReachablePickList" exact="$wareEval"/>
          </do_if>
          <do_if value="this.$checkDemandFirst and $wareHasResourceInRange">
            <do_all exact="this.$minerScoreDemandStations.count" counter="$tsi">
              <set_value name="$stationEval" exact="this.$minerScoreDemandStations.{$tsi}"/>
              <set_value name="$targetAmount" exact="$stationEval.cargo.{$wareEval}.target"/>
              <do_if value="$targetAmount gt 0">
                <set_value name="$currentAmount" exact="$stationEval.cargo.{$wareEval}.count"/>
                <set_value name="$projectedIncoming" exact="0"/>
                <set_value name="$reservedIncoming" exact="0"/>
                <do_if value="this.$fleetBalancing and global.$GT_MinerIntents? and global.$GT_MinerIntents.{$stationEval}? and global.$GT_MinerIntents.{$stationEval}.{$wareEval}?">
                  <set_value name="$intentShips" exact="global.$GT_MinerIntents.{$stationEval}.{$wareEval}.keys.list"/>
                  <set_value name="$intentHorizon" exact="player.age + (this.$demandRecheckInterval * 2)"/>
                  <do_all exact="$intentShips.count" counter="$ii">
                    <set_value name="$intentShip" exact="$intentShips.{$ii}"/>
                    <set_value name="$intent" exact="global.$GT_MinerIntents.{$stationEval}.{$wareEval}.{$intentShip}"/>
                    <set_value name="$intentShipIsMinerControlled" exact="false"/>
                    <do_if value="$intentShip? and $intentShip.exists and $intentShip.defaultorder? and @$intentShip.defaultorder.id == 'GalaxyMiner'">
                      <set_value name="$intentShipIsMinerControlled" exact="true"/>
                    </do_if>
                    <do_elseif value="$intentShip? and $intentShip.exists and $intentShip.commander? and $intentShip.commander.exists and $intentShip.commander.defaultorder? and @$intentShip.commander.defaultorder.id == 'GalaxyMiner'">
                      <set_value name="$intentShipIsMinerControlled" exact="true"/>
                    </do_elseif>
                    <set_value name="$shipA" exact="this.ship"/>
                    <set_value name="$shipB" exact="$intentShip"/>
                    <include_interrupt_actions ref="MinerSameFleetMatch"/>
                    <do_if value="$intent? and $intent.$intentAmount? and $intent.$intentAmount gt 0 and $intent.$eta? and $intent.$eta le $intentHorizon and $intent.$phase? and ($intent.$phase == 'mining' or $intent.$phase == 'hauling' or $intent.$phase == 'delivering') and $intentShip? and $intentShip.exists and $intentShip.isoperational and $intentShipIsMinerControlled and $fleetMatch">
                      <set_value name="$projectedIncoming" exact="$projectedIncoming + $intent.$intentAmount"/>
                    </do_if>
                  </do_all>
                </do_if>
                <!-- Count vanilla real trade reservations and merge with GT intents without double counting overlap. -->
                <get_ware_reservation object="$stationEval" ware="$wareEval" type="sell" result="$reservedIncoming"/>
                <set_value name="$effectiveIncoming" exact="[$projectedIncoming, $reservedIncoming].max"/>
                <set_value name="$projectedStock" exact="$currentAmount + $effectiveIncoming"/>
                <set_value name="$deficitAmount" exact="[0, $targetAmount - $projectedStock].max"/>
                <set_value name="$urgency" exact="$urgency + (($deficitAmount * 100) / [$targetAmount, 1].max)"/>
                <set_value name="$storagePercent" exact="($projectedStock * 100) / [$targetAmount, 1].max"/>
                <do_if value="$storagePercent lt this.$overflowThreshold">
                  <set_value name="$hasPrimaryCapacity" exact="true"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$wareEval?">
            <set_value name="this.$minerScoreWareUrgency.{$wareEval}" exact="$urgency"/>
            <set_value name="this.$minerScoreWareHasPrimaryCapacity.{$wareEval}" exact="$hasPrimaryCapacity"/>
          </do_if>
          <do_if value="this.$checkDemandFirst and $wareEval? and $wareIsMineable and $urgency gt this.$minerScoreBestUrgency">
            <set_value name="this.$minerScoreBestUrgency" exact="$urgency"/>
            <set_value name="this.$minerScoreBestWares" exact="[$wareEval]"/>
          </do_if>
          <do_elseif value="this.$checkDemandFirst and $wareEval? and $wareIsMineable and $urgency == this.$minerScoreBestUrgency and not this.$minerScoreBestWares.indexof.{$wareEval}">
            <append_to_list name="this.$minerScoreBestWares" exact="$wareEval"/>
          </do_elseif>
        </do_all>
        <set_value name="this.$minerScoreIndex" exact="$chunkEnd + 1"/>
        <do_if value="this.$minerScoreIndex? and this.$minerScoreCandidateWares? and this.$minerScoreIndex le this.$minerScoreCandidateWares.count">
          <set_value name="$scoreChunkYieldMs" exact="15"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs?">
            <set_value name="$scoreChunkYieldMs" exact="[global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs, 1].max"/>
          </do_if>
          <wait exact="$scoreChunkYieldMs * 1ms"/>
          <remove_value name="$scoreChunkYieldMs"/>
        </do_if>
      </do_while>
      <set_value name="$wareUrgency" exact="this.$minerScoreWareUrgency"/>
      <set_value name="$wareHasPrimaryCapacity" exact="this.$minerScoreWareHasPrimaryCapacity"/>
      <set_value name="$wareReachable" exact="this.$minerScoreWareReachable"/>
      <set_value name="$wareDiscoverable" exact="this.$minerScoreWareDiscoverable"/>
      <!-- Persist gather-sector list for the post-select locate pass (same footprint as scoring). -->
      <set_value name="this.$minerSliceGatherSpaces" exact="this.$minerScoreGatherSpaces"/>
      <!-- Persist the per-ware discoverability map on a blackboard variable so it survives the
           wait yields between this scoring pass and the diag snapshot publish further down. The
           diag tool reads this through the snapshot to show the engine's authoritative
           "discovered asteroid" answer instead of the probe-presence MD proxy. -->
      <set_value name="this.$activeMiningWareDiscoverable" exact="this.$minerScoreWareDiscoverable"/>
      <set_value name="$bestUrgency" exact="this.$minerScoreBestUrgency"/>
      <set_value name="$bestWares" exact="this.$minerScoreBestWares"/>
      <remove_value name="this.$minerScoreCandidateWares"/>
      <remove_value name="this.$minerScoreGatherSpaces"/>
      <remove_value name="this.$minerScoreDemandStations"/>
      <remove_value name="this.$minerScoreWareUrgency"/>
      <remove_value name="this.$minerScoreWareHasPrimaryCapacity"/>
      <remove_value name="this.$minerScoreWareReachable"/>
      <remove_value name="this.$minerScoreWareDiscoverable"/>
      <remove_value name="this.$minerScoreBestUrgency"/>
      <remove_value name="this.$minerScoreBestWares"/>
      <remove_value name="this.$minerScoreIndex"/>
      <do_if value="this.$checkDemandFirst">
        <do_if value="$bestWares.count gt 0">
          <set_value name="$bestWare" exact="$bestWares.random"/>
        </do_if>
      </do_if>
      <do_else>
        <set_value name="$bestWares" exact="this.$minerScoreReachablePickList"/>
        <shuffle_list list="$bestWares"/>
        <do_if value="$bestWares.count gt 0">
          <set_value name="$bestWare" exact="$bestWares.{1}"/>
        </do_if>
        <set_value name="$bestUrgency" exact="0"/>
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Demand-off slice-committed pick from fixed basket. reachableCount=' + $bestWares.count + ', selected=' + (if $bestWare? and $bestWare != null then $bestWare.name else 'NONE')" chance="this.$debugchance"/>
      </do_else>
      <remove_value name="this.$minerScoreReachablePickList"/>

      <!-- Pick the highest-scoring ware THIS slice, full stop. Per-slice granularity is preserved
           by run_script (one full mine -> deliver round trip per slice), so we still don't churn
           wares mid-cargo. The previous sticky-read of `this.$activeMiningWare` plus switch-gate
           (criticalDemandDelta / minSwitchCooldown / minCargoCommitPercent / hardEmergencyDelta +
           pilot-level branch) was removed because its combined preconditions almost never opened
           the switch window simultaneously: the gate required (delta exceeded) AND (cooldown
           elapsed) AND (cargo-commit low), but the slice that just completed produced a full
           cargo, so cargo-commit was effectively never below the threshold at decision time. Once
           a ware won an early cycle (often by a one-refinery lead in range or from a `.random`
           tie-break), the gate locked it in forever and players reported permanent silicon-only
           or ore-only behaviour despite the other ware being more urgent. The four order params
           (`criticalDemandDelta`, `hardEmergencyDelta`, `minSwitchCooldown`, `minCargoCommitPercent`)
           remain declared in the order params block for save-game compatibility but are no longer
           read. `this.$activeMiningWare` and `this.$activeMiningUrgency` are still WRITTEN further
           down (and used by the diagnose snapshot to show "currently mining: X"); they are just
           never read back as an input to selection. -->
      <set_value name="$selectedWare" exact="$bestWare"/>

      <!-- ============================================================================ -->
      <!-- CARGO-FIRST OVERRIDE                                                         -->
      <!--                                                                              -->
      <!-- Player report (live log 851806/851868/851930/851992/852054 for BLV-869):     -->
      <!--   "Overflow wait. selected=Ore, urgency=9, overflowAllowed=0,                -->
      <!--    cargoFree=0/35800 (0% free). Standing by until a buyer becomes available  -->
      <!--    or the player intervenes."                                                 -->
      <!-- BLV-869's cargo bay is full of SILICON, the player has stations that BUY     -->
      <!-- Silicon with capacity, yet the ship sits idle for >250s because demand       -->
      <!-- scoring picked Ore (higher urgency this slice) and the overflow-wait branch  -->
      <!-- only checks the SELECTED ware. With Ore primary-capped and overflow-sell     -->
      <!-- disabled, the loop loops back to demand-recheck forever - never even         -->
      <!-- considering the Silicon already in the bay.                                  -->
      <!--                                                                              -->
      <!-- Vanilla mining routine handles the "deliver-then-mine" cycle internally     -->
      <!-- as long as the ware passed in matches what the cargo holds. By forcing       -->
      <!-- $selectedWare to a cargo ware with a buyer here, we hand the mining routine  -->
      <!-- the right target and it does the delivery as the first action of the slice. -->
      <!-- After the slice the cargo is empty, the next main_loop iteration re-scores  -->
      <!-- normally, and the miner can then pursue Ore (or whatever scored highest).    -->
      <!--                                                                              -->
      <!-- Acceptance gate per cargo ware:                                              -->
      <!--   1. $cargoWare in this.ship.cargo.list with count > 0                       -->
      <!--   2. $cargoWare in $candidateWares (so it was already deemed mineable +      -->
      <!--      relevant for this ship - prevents force-delivering wares to stations    -->
      <!--      outside the ship's restricted basket / range)                            -->
      <!--   3. SOME station in $demandStations has capacity for $cargoWare             -->
      <!--      (storagePercent < $overflowThreshold AND target > 0). Reuses the same   -->
      <!--      $demandStations list and the same threshold the primary-delivery        -->
      <!--      block at line 1437 uses - if a station qualifies as a primary buyer     -->
      <!--      for the SELECTED ware there, it qualifies as a primary buyer for the    -->
      <!--      CARGO ware here too (the only delta is the ware in question).           -->
      <!--                                                                              -->
      <!-- We pick the cargo ware with the LARGEST in-bay amount (greedy: clear the    -->
      <!-- biggest stack first; any leftover gets handled the next slice). Scoring      -->
      <!-- here would just delay the inevitable.                                        -->
      <!--                                                                              -->
      <!-- We do NOT route this through the overflow-sell-mode branch. Overflow-sell    -->
      <!-- is for "primary stations are full, find anyone willing to buy". Here we have -->
      <!-- a willing PRIMARY buyer; the standard primary delivery path at line 1437     -->
      <!-- handles it cleanly.                                                          -->
      <!-- ============================================================================ -->
      <set_value name="$demandOffCargoHasWillingBuyer" exact="false"/>
      <do_if value="this.ship.cargo.list? and this.ship.cargo.list.count gt 0 and $demandStations? and $demandStations.count gt 0">
        <set_value name="$cargoFirstBestWare" exact="null"/>
        <set_value name="$cargoFirstBestAmount" exact="0"/>
        <set_value name="$cargoFirstReason" exact="''"/>
        <!-- Keep the Resource Basket authoritative: the pre-scoring candidate pass is the
             only place that can admit a ware for mining. Cargo not present in
             $candidateWares may still be sold by the routine's sell path, but it must not
             replace $selectedWare and cause a miner to mine outside the configured basket. -->
        <do_for_each name="$cargoWare" in="this.ship.cargo.list">
          <do_if value="$cargoWare? and $cargoWare != null and $candidateWares.indexof.{$cargoWare} and this.ship.cargo.{$cargoWare}.count gt 0 and $cargoWare.hastag.minable">
            <set_value name="$cargoWareAmount" exact="this.ship.cargo.{$cargoWare}.count"/>
            <set_value name="$cargoWareHasBuyer" exact="false"/>
            <!-- Scan demand stations once per cargo ware. Break on first qualifying station to
                 keep the slice cheap (we only need to know IF a buyer exists, not which one;
                 the primary delivery block at line 1437 will pick the best one with full
                 deficit + reservation accounting). -->
            <do_for_each name="$cfStation" in="$demandStations">
              <do_if value="$cargoWareHasBuyer">
                <break/>
              </do_if>
              <do_if value="$cfStation? and $cfStation.exists">
                <set_value name="$cfTarget" exact="@$cfStation.cargo.{$cargoWare}.target"/>
                <do_if value="$cfTarget? and $cfTarget gt 0">
                  <set_value name="$cfCurrent" exact="@$cfStation.cargo.{$cargoWare}.count"/>
                  <set_value name="$cfPercent" exact="if $cfTarget gt 0 then ($cfCurrent * 100) / $cfTarget else 100"/>
                  <do_if value="$cfPercent lt this.$overflowThreshold">
                    <set_value name="$cargoWareHasBuyer" exact="true"/>
                  </do_if>
                  <remove_value name="$cfCurrent"/>
                  <remove_value name="$cfPercent"/>
                </do_if>
                <do_if value="$cfTarget?"><remove_value name="$cfTarget"/></do_if>
              </do_if>
            </do_for_each>
            <do_if value="$cargoWareHasBuyer and $cargoWareAmount gt $cargoFirstBestAmount">
              <set_value name="$cargoFirstBestAmount" exact="$cargoWareAmount"/>
              <set_value name="$cargoFirstBestWare" exact="$cargoWare"/>
              <set_value name="$demandOffCargoHasWillingBuyer" exact="true"/>
            </do_if>
            <remove_value name="$cargoWareAmount"/>
            <remove_value name="$cargoWareHasBuyer"/>
          </do_if>
        </do_for_each>
        <do_if value="$cfStation?"><remove_value name="$cfStation"/></do_if>
        <do_if value="$cargoWare?"><remove_value name="$cargoWare"/></do_if>
        <do_if value="$cargoFirstBestWare? and $cargoFirstBestWare != null">
          <!-- ============================================================================ -->
          <!-- TRIGGER GATE: only override when the ship CANNOT mine productively this      -->
          <!-- slice. If the ship can keep mining (scored a reachable ware AND has free     -->
          <!-- cargo space), let the standard flow proceed - the vanilla mining routine     -->
          <!-- will naturally deliver any in-bay cargo as part of its mine-then-deliver     -->
          <!-- cycle, or the overflow-wait branch downstream will trigger this override     -->
          <!-- on the NEXT slice if the cargo situation persists.                            -->
          <!--                                                                              -->
          <!-- "Cannot mine productively" means ANY of:                                     -->
          <!--   (a) $selectedWare is null - scoring picked nothing to mine                 -->
          <!--   (b) Selected ware is not reachable - no asteroid discovered for it         -->
          <!--   (c) Cargo is FULL (free.all <= 0) - even if scored & reachable, the ship   -->
          <!--       has zero room to mine another cubic meter so it MUST deliver first     -->
          <!--       (this is exactly the BLV-869 report: cargoFree=0/35800, full of        -->
          <!--       Silicon, scored Ore, stuck in overflow wait forever)                    -->
          <!--                                                                              -->
          <!-- The "scoring picked a different ware than cargo" condition that previously   -->
          <!-- gated this block was too aggressive: a ship with 5% Ice in the bay and 95%   -->
          <!-- free space scored on a fresh, reachable Ore opportunity should KEEP mining   -->
          <!-- Ore, not divert to deliver 5% of Ice. The vanilla mining routine handles     -->
          <!-- the Ice on the natural deliver-cycle once Ore is mined.                      -->
          <!-- ============================================================================ -->
          <set_value name="$cargoFirstNoScoring" exact="not $selectedWare? or $selectedWare == null"/>
          <set_value name="$cargoFirstUnreachable" exact="not $cargoFirstNoScoring and $wareReachable? and $wareReachable.{$selectedWare}? and not $wareReachable.{$selectedWare}"/>
          <set_value name="$cargoFirstCargoFull" exact="this.ship.cargo.free.all le 0"/>
          <set_value name="$cargoFirstShouldOverride" exact="$cargoFirstNoScoring or $cargoFirstUnreachable or $cargoFirstCargoFull"/>
          <do_if value="$cargoFirstShouldOverride and ($cargoFirstNoScoring or $selectedWare != $cargoFirstBestWare)">
            <set_value name="$cargoFirstReason" exact="if $cargoFirstNoScoring then 'no scoring winner' else (if $cargoFirstCargoFull then 'cargo is FULL (' + (this.ship.cargo.capacity.all - this.ship.cargo.free.all) + '/' + this.ship.cargo.capacity.all + ') - cannot mine more without delivering, scoring picked ' + $selectedWare.name + ' (urgency=' + (if $wareUrgency? and $wareUrgency.{$selectedWare}? then $wareUrgency.{$selectedWare} else 0) + ')' else 'scoring picked ' + $selectedWare.name + ' (urgency=' + (if $wareUrgency? and $wareUrgency.{$selectedWare}? then $wareUrgency.{$selectedWare} else 0) + ') but it is unreachable - no discovered asteroid in range') + '; cargo holds ' + $cargoFirstBestAmount + ' ' + $cargoFirstBestWare.name + ' with a willing primary buyer'"/>
            <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': CARGO-FIRST override - ' + $cargoFirstReason + '. Switching selected to ' + $cargoFirstBestWare.name + ' so the mining routine delivers existing cargo before mining anything new.'" chance="this.$debugchance"/>
            <set_value name="$selectedWare" exact="$cargoFirstBestWare"/>
            <set_value name="$bestWare" exact="$cargoFirstBestWare"/>
            <!-- Force-clear the overflow flag for the new selected ware so the standard
                 primary-delivery block (line 1437) handles delivery rather than the
                 overflow-wait branch (which is keyed on the OLD selectedWare's primary
                 capacity flag from scoring). The primary-delivery block computes its own
                 deficit / capacity per station so this is safe. -->
            <do_if value="$wareHasPrimaryCapacity?">
              <set_value name="$wareHasPrimaryCapacity.{$cargoFirstBestWare}" exact="true"/>
            </do_if>
            <!-- Also mark reachable (we're not mining anything - just delivering existing
                 cargo - so the asteroid-discovery question is moot for this slice). -->
            <do_if value="$wareReachable?">
              <set_value name="$wareReachable.{$cargoFirstBestWare}" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="not $cargoFirstShouldOverride">
            <!-- Diagnostic: ship has deliverable cargo with a willing buyer but the gate
                 says it can keep mining. Useful to confirm the gate isn't suppressing
                 obviously needed deliveries during testing. Logged at debug-chance only. -->
            <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': CARGO-FIRST evaluated but suppressed - ship can keep mining ' + (if $selectedWare? and $selectedWare != null then $selectedWare.name else 'NONE') + ' (mineable, cargoFree=' + this.ship.cargo.free.all + '/' + this.ship.cargo.capacity.all + '). Cargo holds ' + $cargoFirstBestAmount + ' ' + $cargoFirstBestWare.name + ' which will be delivered on the natural mine-then-deliver cycle.'" chance="this.$debugchance"/>
          </do_if>
          <remove_value name="$cargoFirstNoScoring"/>
          <remove_value name="$cargoFirstUnreachable"/>
          <remove_value name="$cargoFirstCargoFull"/>
          <remove_value name="$cargoFirstShouldOverride"/>
        </do_if>
        <do_if value="$cargoFirstBestWare?"><remove_value name="$cargoFirstBestWare"/></do_if>
        <do_if value="$cargoFirstBestAmount?"><remove_value name="$cargoFirstBestAmount"/></do_if>
        <do_if value="$cargoFirstReason?"><remove_value name="$cargoFirstReason"/></do_if>
      </do_if>

      <!-- Hardening: $selectedWare? is true even when set_value stored null (X4 set_value always materializes the variable).
           When scoring produces no reachable wares $bestWare stays null, the prior selection block then sets
           $selectedWare = null, and downstream lookups like $wareUrgency.{$selectedWare} or
           $stationEval.cargo.{$selectedWare}.target crash on .{null}. Force the early-return whenever the selected
           ware is missing OR null, and clear the stale active ware so the next cycle does not re-pick the same
           null fallback. -->
      <do_if value="not $selectedWare? or $selectedWare == null">
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': No selected ware after demand scoring. bestWare=' + (if $bestWare? and $bestWare != null then $bestWare.name else 'NONE') + ', bestUrgency=' + $bestUrgency + ', activeWare=' + (if this.$activeMiningWare? and this.$activeMiningWare != null then this.$activeMiningWare.name else 'NONE')" chance="this.$debugchance"/>
        <set_value name="this.$activeMiningWare" exact="null"/>
        <set_value name="this.$activeMiningUrgency" exact="0"/>
        <set_value name="this.$minerIdleNoWorkCount" exact="[this.$minerIdleNoWorkCount + 1, 5].min"/>
        <do_if value="this.$idleParking and this.$minerIdleNoWorkCount ge 5 and this.ship.cargo.count == 0">
          <set_value name="$minerIdleHome" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
          <do_if value="$minerIdleHome? and $minerIdleHome != null">
            <run_script name="'lib.gt.idlepark'">
              <param name="handoffMode" value="'trigger'"/>
              <param name="handoffShip" value="this.ship"/>
              <param name="home" value="$minerIdleHome"/>
              <param name="debugchance" value="this.$debugchance"/>
            </run_script>
          </do_if>
        </do_if>
        <wait exact="this.$demandRecheckInterval"/>
        <resume label="main_loop"/>
      </do_if>
      <set_value name="this.$activeMiningWare" exact="$selectedWare"/>
      <set_value name="this.$activeMiningUrgency" exact="$wareUrgency.{$selectedWare}"/>
      <set_value name="this.$minerIdleNoWorkCount" exact="0"/>
      <do_if value="global.$GT_IdleParkingReleased? and global.$GT_IdleParkingReleased.{this.ship}?">
        <remove_value name="global.$GT_IdleParkingReleased.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
        <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>
        <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>
      </do_if>

      <!-- Overflow handling: if all primary targets are full, optionally allow overflow sell -->
      <set_value name="$overflowSellMode" exact="false"/>
      <set_value name="$primaryCapacityAvailable" exact="true"/>
      <do_if value="not this.$checkDemandFirst and this.ship.cargo.capacity.all gt 0 and this.ship.cargo.free.all le 0 and this.$allowOverflowSellToOthers">
        <set_value name="$overflowSellMode" exact="true"/>
        <set_value name="$primaryCapacityAvailable" exact="false"/>
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Demand-off full bay with overflow sell enabled - searching for external buyers.'" chance="this.$debugchance"/>
      </do_if>
      <do_elseif value="this.$checkDemandFirst and $wareHasPrimaryCapacity.{$selectedWare}? and not $wareHasPrimaryCapacity.{$selectedWare}">
        <set_value name="$overflowSellMode" exact="true"/>
        <set_value name="$primaryCapacityAvailable" exact="false"/>
      </do_elseif>
      <do_if value="not this.$checkDemandFirst and this.ship.cargo.capacity.all gt 0 and this.ship.cargo.free.all le 0 and not this.$allowOverflowSellToOthers and not $demandOffCargoHasWillingBuyer">
        <set_command_action commandaction="commandaction.standingby"/>
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Demand-off full-bay standby. selected=' + (if $selectedWare? and $selectedWare != null then $selectedWare.name else 'NONE') + ', cargoFree=0/' + this.ship.cargo.capacity.all + '. Standing by until a buyer becomes available or the player intervenes.'" chance="this.$debugchance"/>
        <set_value name="this.$minerDiagPayload" exact="table[$Ship = this.ship, $Timestamp = player.age, $StallReason = 'demand_off_full_bay', $TargetStationCount = $demandStations.count, $OverflowMode = false, $PrimaryCapacityAvailable = false]"/>
        <do_if value="$selectedWare? and $selectedWare != null">
          <set_value name="this.$minerDiagPayload.$SelectedWare" exact="$selectedWare"/>
        </do_if>
        <do_if value="this.$activeMiningUrgency?">
          <set_value name="this.$minerDiagPayload.$Urgency" exact="this.$activeMiningUrgency"/>
        </do_if>
        <do_if value="this.$allowOverflowSellToOthers?">
          <set_value name="this.$minerDiagPayload.$OverflowFallbackAllowed" exact="this.$allowOverflowSellToOthers"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Miner_Diag_Update'" param2="this.$minerDiagPayload"/>
        <remove_value name="this.$minerDiagPayload"/>
        <set_value name="$minerFleetName" exact="'-'"/>
        <do_if value="this.ship.fleet? and this.ship.fleet.commander? and this.ship.fleet.commander.fleet? and this.ship.fleet.commander.fleet.name?">
          <set_value name="$minerFleetName" exact="this.ship.fleet.commander.fleet.name"/>
        </do_if>
        <do_elseif value="this.ship.fleet? and this.ship.fleet.name?">
          <set_value name="$minerFleetName" exact="this.ship.fleet.name"/>
        </do_elseif>
        <do_if value="$minerFleetName == ''">
          <set_value name="$minerFleetName" exact="'-'"/>
        </do_if>
        <show_notification text="{77000, 31200}.[this.ship.knownname, this.ship.idcode, $minerFleetName]" timeout="8s"/>
        <remove_value name="$minerFleetName"/>
        <set_value name="this.$minerIdleNoWorkCount" exact="[this.$minerIdleNoWorkCount + 1, 5].min"/>
        <do_if value="this.$idleParking and this.$minerIdleNoWorkCount ge 5">
          <set_value name="$minerIdleHome" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
          <do_if value="$minerIdleHome? and $minerIdleHome != null">
            <run_script name="'lib.gt.idlepark'">
              <param name="handoffMode" value="'trigger'"/>
              <param name="handoffShip" value="this.ship"/>
              <param name="home" value="$minerIdleHome"/>
              <param name="debugchance" value="this.$debugchance"/>
            </run_script>
          </do_if>
        </do_if>
        <wait exact="this.$demandRecheckInterval"/>
        <resume label="main_loop"/>
      </do_if>
      <do_if value="$demandOffCargoHasWillingBuyer?"><remove_value name="$demandOffCargoHasWillingBuyer"/></do_if>

      <!-- Overflow exception:
           if all player demand stations are full, only mine wares that currently have sell opportunities. -->
      <do_if value="$overflowSellMode and this.$allowOverflowSellToOthers">
        <!-- Removed `global.$GT_FallbackActivations.{'Miner.OverflowSellFallback'}` increment for
             the same reason as the BuyOfferCandidateFallback site above: the AI-script expression
             evaluator crashes on `set_value name="global.$X.{'key'}"` (value-snapshot LHS). The
             counter never produced usable telemetry and aborted the slice mid-run as soon as the
             overflow-sell path actually fired. -->
        <set_value name="$overflowSearchRefSector" exact="if $range? and $range.isclass.sector then $range else (if $range? and $range.sector? then @$range.sector else this.sector)"/>
        <run_script name="'lib.find.sectors.inrange'" result="$overflowSellSpaces">
          <param name="refobject" value="$overflowSearchRefSector"/>
          <param name="mingatedistance" value="0"/>
          <param name="maxgatedistance" value="this.$maxSellDistance"/>
          <param name="debugchance" value="this.$debugchance"/>
        </run_script>
        <do_if value="this.ship.isplayerowned and this.$maxSellDistance le 0 and $overflowSearchRefSector.isclass.sector and not $overflowSellSpaces.indexof.{$overflowSearchRefSector}">
          <append_to_list name="$overflowSellSpaces" exact="$overflowSearchRefSector"/>
        </do_if>
        <set_value name="$overflowSearchHomeSector" exact="if this.$homeStation? and this.$homeStation.exists and this.$homeStation.sector? then @$this.$homeStation.sector else $overflowSearchRefSector"/>
        <set_value name="this.$minerOverflowCandidateWares" exact="$candidateWares"/>
        <set_value name="this.$minerOverflowBestWare" exact="null"/>
        <set_value name="this.$minerOverflowBestOffers" exact="0"/>
        <set_value name="this.$minerOverflowIndex" exact="1"/>
        <do_while value="this.$minerOverflowIndex? and this.$minerOverflowCandidateWares? and this.$minerOverflowIndex le this.$minerOverflowCandidateWares.count">
          <set_value name="$chunkEnd" exact="[this.$minerOverflowIndex + 1, this.$minerOverflowCandidateWares.count].min"/>
          <do_all exact="$chunkEnd - this.$minerOverflowIndex + 1" counter="$chunkOffset">
            <set_value name="$owi" exact="this.$minerOverflowIndex + $chunkOffset - 1"/>
            <set_value name="$overflowWare" exact="this.$minerOverflowCandidateWares.{$owi}"/>
            <set_value name="$overflowOfferCount" exact="0"/>
            <do_if value="$wareReachable.{$overflowWare}? and $wareReachable.{$overflowWare}">
              <run_script name="'lib.gt.live.search'" result="$overflowSearchResult">
                <param name="ship" value="this.ship"/>
                <param name="searchMode" value="'sell_only'"/>
                <param name="sellSpaces" value="$overflowSellSpaces"/>
                <param name="homeSector" value="$overflowSearchHomeSector"/>
                <param name="maxDistance" value="this.$maxSellDistance"/>
                <param name="wareBasket" value="[$overflowWare]"/>
                <param name="allowIllegal" value="this.$allowillegal"/>
                <param name="ownerFilter" value="if this.$playerStationsOnly then 'player_only' else 'any'"/>
                <param name="ignoreTradeRules" value="this.$playerStationsOnly"/>
                <param name="debugchance" value="this.$debugchance"/>
              </run_script>
              <do_if value="$overflowSearchResult? and $overflowSearchResult.$BuyOffers?">
                <set_value name="$overflowOfferCount" exact="$overflowSearchResult.$BuyOffers.count"/>
                <do_if value="$minerBlockedStations? and $minerBlockedStations.count gt 0 and $overflowOfferCount gt 0">
                  <set_value name="$overflowOfferCount" exact="0"/>
                  <do_all exact="$overflowSearchResult.$BuyOffers.count" counter="$overflowOfferIdx">
                    <set_value name="$overflowOffer" exact="$overflowSearchResult.$BuyOffers.{$overflowOfferIdx}"/>
                    <set_value name="$overflowOfferBlocked" exact="false"/>
                    <do_if value="$overflowOffer? and $overflowOffer.owner?">
                      <do_all exact="$minerBlockedStations.count" counter="$overflowBlockedIdx">
                        <do_if value="$minerBlockedStations.{$overflowBlockedIdx}? and @$overflowOffer.owner == $minerBlockedStations.{$overflowBlockedIdx}">
                          <set_value name="$overflowOfferBlocked" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    <do_if value="not $overflowOfferBlocked">
                      <set_value name="$overflowOfferCount" operation="add"/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$overflowOfferCount gt this.$minerOverflowBestOffers">
              <set_value name="this.$minerOverflowBestOffers" exact="$overflowOfferCount"/>
              <set_value name="this.$minerOverflowBestWare" exact="$overflowWare"/>
            </do_if>
          </do_all>
          <set_value name="this.$minerOverflowIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerOverflowIndex? and this.$minerOverflowCandidateWares? and this.$minerOverflowIndex le this.$minerOverflowCandidateWares.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$overflowBestWare" exact="this.$minerOverflowBestWare"/>
        <set_value name="$overflowBestOffers" exact="this.$minerOverflowBestOffers"/>
        <remove_value name="this.$minerOverflowCandidateWares"/>
        <remove_value name="this.$minerOverflowBestWare"/>
        <remove_value name="this.$minerOverflowBestOffers"/>
        <remove_value name="this.$minerOverflowIndex"/>
        <do_if value="$overflowBestWare? and $overflowBestOffers gt 0">
          <set_value name="$selectedWare" exact="$overflowBestWare"/>
          <set_value name="this.$activeMiningWare" exact="$selectedWare"/>
          <set_value name="this.$activeMiningUrgency" exact="0"/>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Overflow mining ware selected by live sell opportunities: ' + $selectedWare.name + ' (offers=' + $overflowBestOffers + ')'" chance="this.$debugchance"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Overflow mode but no sell opportunities for candidate wares. Waiting.'" chance="this.$debugchance"/>
          <set_value name="this.$minerDiagPayload" exact="table[$Ship = this.ship, $Timestamp = player.age, $StallReason = 'overflow_no_opportunities', $TargetStationCount = $demandStations.count, $OverflowMode = true, $PrimaryCapacityAvailable = false]"/>
          <do_if value="$selectedWare? and $selectedWare != null">
            <set_value name="this.$minerDiagPayload.$SelectedWare" exact="$selectedWare"/>
          </do_if>
          <do_if value="this.$allowOverflowSellToOthers?">
            <set_value name="this.$minerDiagPayload.$OverflowFallbackAllowed" exact="this.$allowOverflowSellToOthers"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Miner_Diag_Update'" param2="this.$minerDiagPayload"/>
          <remove_value name="this.$minerDiagPayload"/>
          <set_value name="this.$minerIdleNoWorkCount" exact="[this.$minerIdleNoWorkCount + 1, 5].min"/>
          <do_if value="this.$idleParking and this.$minerIdleNoWorkCount ge 5 and this.ship.cargo.count == 0">
            <set_value name="$minerIdleHome" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
            <do_if value="$minerIdleHome? and $minerIdleHome != null">
              <run_script name="'lib.gt.idlepark'">
                <param name="handoffMode" value="'trigger'"/>
                <param name="handoffShip" value="this.ship"/>
                <param name="home" value="$minerIdleHome"/>
                <param name="debugchance" value="this.$debugchance"/>
              </run_script>
            </do_if>
          </do_if>
          <wait exact="this.$demandRecheckInterval"/>
          <resume label="main_loop"/>
        </do_else>
      </do_if>

      <do_if value="$overflowSellMode and not this.$allowOverflowSellToOthers">
        <!-- Genuine standby: full or near-full cargo cannot be delivered (primary capped,
             overflow disabled). Set command action to standingby so the UI reflects reality
             instead of the stale "searching resources" carried over from script init. -->
        <set_command_action commandaction="commandaction.standingby"/>
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Overflow wait. selected=' + $selectedWare.name + ', urgency=' + this.$activeMiningUrgency + ', overflowAllowed=0, cargoFree=' + this.ship.cargo.free.all + '/' + this.ship.cargo.capacity.all + ' (' + (if this.ship.cargo.capacity.all gt 0 then (this.ship.cargo.free.all * 100) / this.ship.cargo.capacity.all else 0) + '% free). Standing by until a buyer becomes available or the player intervenes.'" chance="this.$debugchance"/>
        <set_value name="this.$minerDiagPayload" exact="table[$Ship = this.ship, $Timestamp = player.age, $StallReason = 'overflow_wait', $TargetStationCount = $demandStations.count, $OverflowMode = true, $PrimaryCapacityAvailable = false]"/>
        <do_if value="$selectedWare? and $selectedWare != null">
          <set_value name="this.$minerDiagPayload.$SelectedWare" exact="$selectedWare"/>
        </do_if>
        <do_if value="this.$activeMiningUrgency?">
          <set_value name="this.$minerDiagPayload.$Urgency" exact="this.$activeMiningUrgency"/>
        </do_if>
        <do_if value="this.$allowOverflowSellToOthers?">
          <set_value name="this.$minerDiagPayload.$OverflowFallbackAllowed" exact="this.$allowOverflowSellToOthers"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Miner_Diag_Update'" param2="this.$minerDiagPayload"/>
        <remove_value name="this.$minerDiagPayload"/>
        <set_value name="this.$minerIdleNoWorkCount" exact="[this.$minerIdleNoWorkCount + 1, 5].min"/>
        <do_if value="this.$idleParking and this.$minerIdleNoWorkCount ge 5 and this.ship.cargo.count == 0">
          <set_value name="$minerIdleHome" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
          <do_if value="$minerIdleHome? and $minerIdleHome != null">
            <run_script name="'lib.gt.idlepark'">
              <param name="handoffMode" value="'trigger'"/>
              <param name="handoffShip" value="this.ship"/>
              <param name="home" value="$minerIdleHome"/>
              <param name="debugchance" value="this.$debugchance"/>
            </run_script>
          </do_if>
        </do_if>
        <wait exact="this.$demandRecheckInterval"/>
        <resume label="main_loop"/>
      </do_if>

      <!-- Choose concrete primary delivery station for selected ware -->
      <set_value name="$primaryDeliveryStation" exact="null"/>
      <set_value name="$primaryBestDeficit" exact="-1"/>
      <do_if value="$selectedWare? and $demandStations.count gt 0 and not $overflowSellMode">
        <!-- Chunk primary-station search to avoid long single-frame scans on large station lists. -->
        <set_value name="this.$minerPrimaryDemandStations" exact="$demandStations"/>
        <set_value name="this.$minerPrimarySelectedWare" exact="$selectedWare"/>
        <set_value name="this.$minerPrimaryBestDeficit" exact="-1"/>
        <set_value name="this.$minerPrimaryDeliveryStation" exact="null"/>
        <set_value name="this.$minerPrimaryIndex" exact="1"/>
        <do_while value="this.$minerPrimaryIndex? and this.$minerPrimaryDemandStations? and this.$minerPrimaryIndex le this.$minerPrimaryDemandStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerPrimaryIndex + 9, this.$minerPrimaryDemandStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerPrimaryIndex + 1" counter="$chunkOffset">
            <set_value name="$tsi" exact="this.$minerPrimaryIndex + $chunkOffset - 1"/>
            <set_value name="$stationEval" exact="this.$minerPrimaryDemandStations.{$tsi}"/>
            <set_value name="$targetAmount" exact="$stationEval.cargo.{this.$minerPrimarySelectedWare}.target"/>
            <do_if value="$targetAmount gt 0">
              <set_value name="$currentAmount" exact="$stationEval.cargo.{this.$minerPrimarySelectedWare}.count"/>
              <set_value name="$projectedIncoming" exact="0"/>
              <set_value name="$reservedIncoming" exact="0"/>
              <do_if value="this.$fleetBalancing and global.$GT_MinerIntents? and global.$GT_MinerIntents.{$stationEval}? and global.$GT_MinerIntents.{$stationEval}.{this.$minerPrimarySelectedWare}?">
                <set_value name="$intentShips" exact="global.$GT_MinerIntents.{$stationEval}.{this.$minerPrimarySelectedWare}.keys.list"/>
                <set_value name="$intentHorizon" exact="player.age + (this.$demandRecheckInterval * 2)"/>
                <do_all exact="$intentShips.count" counter="$ii">
                  <set_value name="$intentShip" exact="$intentShips.{$ii}"/>
                  <set_value name="$intent" exact="global.$GT_MinerIntents.{$stationEval}.{this.$minerPrimarySelectedWare}.{$intentShip}"/>
                  <set_value name="$intentShipIsMinerControlled" exact="false"/>
                  <do_if value="$intentShip? and $intentShip.exists and $intentShip.defaultorder? and @$intentShip.defaultorder.id == 'GalaxyMiner'">
                    <set_value name="$intentShipIsMinerControlled" exact="true"/>
                  </do_if>
                  <do_elseif value="$intentShip? and $intentShip.exists and $intentShip.commander? and $intentShip.commander.exists and $intentShip.commander.defaultorder? and @$intentShip.commander.defaultorder.id == 'GalaxyMiner'">
                    <set_value name="$intentShipIsMinerControlled" exact="true"/>
                  </do_elseif>
                  <set_value name="$shipA" exact="this.ship"/>
                  <set_value name="$shipB" exact="$intentShip"/>
                  <include_interrupt_actions ref="MinerSameFleetMatch"/>
                  <do_if value="$intent? and $intent.$intentAmount? and $intent.$intentAmount gt 0 and $intent.$eta? and $intent.$eta le $intentHorizon and $intent.$phase? and ($intent.$phase == 'mining' or $intent.$phase == 'hauling' or $intent.$phase == 'delivering') and $intentShip? and $intentShip.exists and $intentShip.isoperational and $intentShipIsMinerControlled and $fleetMatch">
                    <set_value name="$projectedIncoming" exact="$projectedIncoming + $intent.$intentAmount"/>
                  </do_if>
                </do_all>
              </do_if>
              <get_ware_reservation object="$stationEval" ware="this.$minerPrimarySelectedWare" type="sell" result="$reservedIncoming"/>
              <set_value name="$effectiveIncoming" exact="[$projectedIncoming, $reservedIncoming].max"/>
              <set_value name="$projectedStock" exact="$currentAmount + $effectiveIncoming"/>
              <set_value name="$storagePercent" exact="($projectedStock * 100) / [$targetAmount, 1].max"/>
              <set_value name="$deficitAmount" exact="[0, $targetAmount - $projectedStock].max"/>
              <do_if value="$storagePercent lt this.$overflowThreshold and $deficitAmount gt this.$minerPrimaryBestDeficit">
                <set_value name="this.$minerPrimaryBestDeficit" exact="$deficitAmount"/>
                <set_value name="this.$minerPrimaryDeliveryStation" exact="$stationEval"/>
              </do_if>
            </do_if>
          </do_all>
          <set_value name="this.$minerPrimaryIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerPrimaryIndex? and this.$minerPrimaryDemandStations? and this.$minerPrimaryIndex le this.$minerPrimaryDemandStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$primaryBestDeficit" exact="this.$minerPrimaryBestDeficit"/>
        <set_value name="$primaryDeliveryStation" exact="this.$minerPrimaryDeliveryStation"/>
        <remove_value name="this.$minerPrimaryDemandStations"/>
        <remove_value name="this.$minerPrimarySelectedWare"/>
        <remove_value name="this.$minerPrimaryBestDeficit"/>
        <remove_value name="this.$minerPrimaryDeliveryStation"/>
        <remove_value name="this.$minerPrimaryIndex"/>
      </do_if>

      <!-- Enforce primary station delivery by assignment when possible -->
      <do_if value="this.$assignToStation and this.$homeStation? and this.$homeStation.exists and $primaryDeliveryStation? and $primaryDeliveryStation.exists and (not $overflowSellMode)">
        <do_if value="(not this.ship.commander? or not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and ((not this.ship.commander?) or this.ship.commander != $primaryDeliveryStation)">
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <remove_object_commander object="this.ship"/>
          </do_if>
          <set_object_commander object="this.ship" commander="$primaryDeliveryStation" assignment="assignment.mining"/>
        </do_if>
      </do_if>

      <!-- Overflow fallback:
           keep station commander assignment intact.
           Detaching here can leave the ship effectively unassigned during long/no-offer slices. -->
      <set_value name="this.$minerDetachedForOverflow" exact="false"/>
      <set_value name="this.$minerOverflowCommanderBackup" exact="null"/>

      <!-- Register deterministic station assignments and live intents -->
      <do_if value="this.$checkDemandFirst and this.$fleetBalancing and $selectedWare? and $demandStations.count gt 0">
        <set_value name="this.$minerAssignedWare" exact="$selectedWare"/>
        <set_value name="this.$minerAssignDemandStations" exact="$demandStations"/>
        <set_value name="this.$minerAssignSelectedWare" exact="$selectedWare"/>
        <set_value name="this.$minerAssignIndex" exact="1"/>
        <do_while value="this.$minerAssignIndex? and this.$minerAssignDemandStations? and this.$minerAssignIndex le this.$minerAssignDemandStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerAssignIndex + 9, this.$minerAssignDemandStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerAssignIndex + 1" counter="$chunkOffset">
            <set_value name="$tsi" exact="this.$minerAssignIndex + $chunkOffset - 1"/>
            <set_value name="$stationEval" exact="this.$minerAssignDemandStations.{$tsi}"/>
            <do_if value="not global.$GT_MinerStationAssignments.{$stationEval}?">
              <set_value name="global.$GT_MinerStationAssignments.{$stationEval}" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerAssignSelectedWare}?">
              <set_value name="global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerAssignSelectedWare}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerAssignSelectedWare}.{this.ship}" exact="true"/>
            <append_to_list name="this.$minerAssignedStations" exact="$stationEval"/>
          </do_all>
          <set_value name="this.$minerAssignIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerAssignIndex? and this.$minerAssignDemandStations? and this.$minerAssignIndex le this.$minerAssignDemandStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <remove_value name="this.$minerAssignDemandStations"/>
        <remove_value name="this.$minerAssignSelectedWare"/>
        <remove_value name="this.$minerAssignIndex"/>

        <do_if value="not $overflowSellMode">
          <set_value name="this.$minerIntentWare" exact="$selectedWare"/>
          <set_value name="this.$minerIntentBuildDemandStations" exact="$demandStations"/>
          <set_value name="this.$minerIntentBuildSelectedWare" exact="$selectedWare"/>
          <set_value name="this.$minerIntentBuildIndex" exact="1"/>
          <do_while value="this.$minerIntentBuildIndex? and this.$minerIntentBuildDemandStations? and this.$minerIntentBuildIndex le this.$minerIntentBuildDemandStations.count">
            <set_value name="$chunkEnd" exact="[this.$minerIntentBuildIndex + 9, this.$minerIntentBuildDemandStations.count].min"/>
            <do_all exact="$chunkEnd - this.$minerIntentBuildIndex + 1" counter="$chunkOffset">
              <set_value name="$tsi" exact="this.$minerIntentBuildIndex + $chunkOffset - 1"/>
              <set_value name="$stationEval" exact="this.$minerIntentBuildDemandStations.{$tsi}"/>
              <set_value name="$targetAmount" exact="$stationEval.cargo.{this.$minerIntentBuildSelectedWare}.target"/>
              <set_value name="$currentAmount" exact="$stationEval.cargo.{this.$minerIntentBuildSelectedWare}.count"/>
              <set_value name="$projectedIncoming" exact="0"/>
              <set_value name="$reservedIncoming" exact="0"/>
              <do_if value="this.$fleetBalancing and global.$GT_MinerIntents? and global.$GT_MinerIntents.{$stationEval}? and global.$GT_MinerIntents.{$stationEval}.{this.$minerIntentBuildSelectedWare}?">
                <set_value name="$intentShips" exact="global.$GT_MinerIntents.{$stationEval}.{this.$minerIntentBuildSelectedWare}.keys.list"/>
                <set_value name="$intentHorizon" exact="player.age + (this.$demandRecheckInterval * 2)"/>
                <do_all exact="$intentShips.count" counter="$ii">
                  <set_value name="$intentShip" exact="$intentShips.{$ii}"/>
                  <set_value name="$intent" exact="global.$GT_MinerIntents.{$stationEval}.{this.$minerIntentBuildSelectedWare}.{$intentShip}"/>
                  <set_value name="$intentShipIsMinerControlled" exact="false"/>
                  <do_if value="$intentShip? and $intentShip.exists and $intentShip.defaultorder? and @$intentShip.defaultorder.id == 'GalaxyMiner'">
                    <set_value name="$intentShipIsMinerControlled" exact="true"/>
                  </do_if>
                  <do_elseif value="$intentShip? and $intentShip.exists and $intentShip.commander? and $intentShip.commander.exists and $intentShip.commander.defaultorder? and @$intentShip.commander.defaultorder.id == 'GalaxyMiner'">
                    <set_value name="$intentShipIsMinerControlled" exact="true"/>
                  </do_elseif>
                  <set_value name="$shipA" exact="this.ship"/>
                  <set_value name="$shipB" exact="$intentShip"/>
                  <include_interrupt_actions ref="MinerSameFleetMatch"/>
                  <do_if value="$intent? and $intent.$intentAmount? and $intent.$intentAmount gt 0 and $intent.$eta? and $intent.$eta le $intentHorizon and $intent.$phase? and ($intent.$phase == 'mining' or $intent.$phase == 'hauling' or $intent.$phase == 'delivering') and $intentShip? and $intentShip.exists and $intentShip.isoperational and $intentShipIsMinerControlled and $fleetMatch">
                    <set_value name="$projectedIncoming" exact="$projectedIncoming + $intent.$intentAmount"/>
                  </do_if>
                </do_all>
              </do_if>
              <get_ware_reservation object="$stationEval" ware="this.$minerIntentBuildSelectedWare" type="sell" result="$reservedIncoming"/>
              <set_value name="$effectiveIncoming" exact="[$projectedIncoming, $reservedIncoming].max"/>
              <set_value name="$deficitAmount" exact="[0, $targetAmount - ($currentAmount + $effectiveIncoming)].max"/>
              <set_value name="$supplierCount" exact="0"/>
              <do_if value="global.$GT_MinerStationAssignments? and global.$GT_MinerStationAssignments.{$stationEval}? and global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerIntentBuildSelectedWare}?">
                <set_value name="$assignKeys" exact="global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerIntentBuildSelectedWare}.keys.list"/>
                <do_all exact="$assignKeys.count" counter="$asci">
                  <set_value name="$assignKeyShip" exact="$assignKeys.{$asci}"/>
                  <set_value name="$shipA" exact="this.ship"/>
                  <set_value name="$shipB" exact="$assignKeyShip"/>
                  <include_interrupt_actions ref="MinerSameFleetMatch"/>
                  <do_if value="$assignKeyShip? and $assignKeyShip.exists and $fleetMatch">
                    <set_value name="$supplierCount" operation="add"/>
                  </do_if>
                </do_all>
              </do_if>
              <set_value name="$supplierCount" exact="[$supplierCount, 1].max"/>
              <set_value name="$shipShareTarget" exact="($deficitAmount / $supplierCount)i"/>
              <set_value name="$intentAmount" exact="[$shipShareTarget, this.ship.cargo.{this.$minerIntentBuildSelectedWare}.max].min"/>
              <do_if value="$intentAmount gt 0">
                <do_if value="not global.$GT_MinerIntents.{$stationEval}?">
                  <set_value name="global.$GT_MinerIntents.{$stationEval}" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_MinerIntents.{$stationEval}.{this.$minerIntentBuildSelectedWare}?">
                  <set_value name="global.$GT_MinerIntents.{$stationEval}.{this.$minerIntentBuildSelectedWare}" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_MinerIntents.{$stationEval}.{this.$minerIntentBuildSelectedWare}.{this.ship}" exact="table[
                  $phase = 'mining',
                  $intentAmount = $intentAmount,
                  $eta = player.age + this.$demandRecheckInterval
                ]"/>
                <append_to_list name="this.$minerIntentStations" exact="$stationEval"/>
              </do_if>
            </do_all>
            <set_value name="this.$minerIntentBuildIndex" exact="$chunkEnd + 1"/>
            <do_if value="this.$minerIntentBuildIndex? and this.$minerIntentBuildDemandStations? and this.$minerIntentBuildIndex le this.$minerIntentBuildDemandStations.count">
              <wait exact="1ms"/>
            </do_if>
          </do_while>
          <remove_value name="this.$minerIntentBuildDemandStations"/>
          <remove_value name="this.$minerIntentBuildSelectedWare"/>
          <remove_value name="this.$minerIntentBuildIndex"/>
        </do_if>
      </do_if>

      <!-- Intent phase update before run: mining if empty cargo, hauling once cargo exists -->
      <set_value name="$intentPhase" exact="'mining'"/>
      <set_value name="$hasIntentWare" exact="this.$minerIntentWare? and this.$minerIntentWare != null"/>
      <do_if value="$hasIntentWare and this.ship.cargo.{this.$minerIntentWare}.count gt 0">
        <set_value name="$intentPhase" exact="'hauling'"/>
      </do_if>
      <do_if value="$hasIntentWare and this.$minerIntentStations? and this.$minerIntentStations.count gt 0">
        <set_value name="this.$minerIntentPhaseIndex" exact="1"/>
        <do_while value="this.$minerIntentPhaseIndex? and this.$minerIntentStations? and this.$minerIntentPhaseIndex le this.$minerIntentStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerIntentPhaseIndex + 8, this.$minerIntentStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerIntentPhaseIndex + 1" counter="$chunkOffset">
            <set_value name="$isi" exact="this.$minerIntentPhaseIndex + $chunkOffset - 1"/>
            <set_value name="$intentStation" exact="this.$minerIntentStations.{$isi}"/>
            <do_if value="global.$GT_MinerIntents? and global.$GT_MinerIntents.{$intentStation}? and global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}? and global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}?">
              <set_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}.$phase" exact="$intentPhase"/>
              <set_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}.$eta" exact="player.age + this.$demandRecheckInterval"/>
            </do_if>
          </do_all>
          <set_value name="this.$minerIntentPhaseIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerIntentPhaseIndex? and this.$minerIntentStations? and this.$minerIntentPhaseIndex le this.$minerIntentStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <remove_value name="this.$minerIntentPhaseIndex"/>
      </do_if>

      <!-- Lightweight diagnostics snapshot for GT Diagnose -->
      <set_value name="$diagSupplierCount" exact="0"/>
      <set_value name="$diagIntentCount" exact="0"/>
      <do_if value="$selectedWare? and $demandStations.count gt 0">
        <set_value name="this.$minerDiagDemandStations" exact="$demandStations"/>
        <set_value name="this.$minerDiagSelectedWare" exact="$selectedWare"/>
        <set_value name="this.$minerDiagIndex" exact="1"/>
        <set_value name="this.$minerDiagSupplierCount" exact="$diagSupplierCount"/>
        <set_value name="this.$minerDiagIntentCount" exact="$diagIntentCount"/>
        <do_while value="this.$minerDiagIndex? and this.$minerDiagDemandStations? and this.$minerDiagIndex le this.$minerDiagDemandStations.count">
          <set_value name="$chunkEnd" exact="[this.$minerDiagIndex + 10, this.$minerDiagDemandStations.count].min"/>
          <do_all exact="$chunkEnd - this.$minerDiagIndex + 1" counter="$chunkOffset">
            <set_value name="$tsi" exact="this.$minerDiagIndex + $chunkOffset - 1"/>
            <set_value name="$stationEval" exact="this.$minerDiagDemandStations.{$tsi}"/>
            <do_if value="global.$GT_MinerStationAssignments? and global.$GT_MinerStationAssignments.{$stationEval}? and global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerDiagSelectedWare}?">
              <set_value name="this.$minerDiagSupplierCount" exact="this.$minerDiagSupplierCount + global.$GT_MinerStationAssignments.{$stationEval}.{this.$minerDiagSelectedWare}.keys.count"/>
            </do_if>
            <do_if value="global.$GT_MinerIntents? and global.$GT_MinerIntents.{$stationEval}? and global.$GT_MinerIntents.{$stationEval}.{this.$minerDiagSelectedWare}?">
              <set_value name="this.$minerDiagIntentCount" exact="this.$minerDiagIntentCount + global.$GT_MinerIntents.{$stationEval}.{this.$minerDiagSelectedWare}.keys.count"/>
            </do_if>
          </do_all>
          <set_value name="this.$minerDiagIndex" exact="$chunkEnd + 1"/>
          <do_if value="this.$minerDiagIndex? and this.$minerDiagDemandStations? and this.$minerDiagIndex le this.$minerDiagDemandStations.count">
            <wait exact="1ms"/>
          </do_if>
        </do_while>
        <set_value name="$diagSupplierCount" exact="this.$minerDiagSupplierCount"/>
        <set_value name="$diagIntentCount" exact="this.$minerDiagIntentCount"/>
        <remove_value name="this.$minerDiagDemandStations"/>
        <remove_value name="this.$minerDiagSelectedWare"/>
        <remove_value name="this.$minerDiagIndex"/>
        <remove_value name="this.$minerDiagSupplierCount"/>
        <remove_value name="this.$minerDiagIntentCount"/>
      </do_if>
      <!-- Diagnostic snapshot: lightweight payload for the in-game GT Diagnose UI.
           The diagnose tool runs its own dedicated resource scan (gt_context_diagnose.xml
           SECTION 3b) using sector.resources.{ware} / sector.yieldrating.{ware} on the
           same gather-distance footprint, so we no longer ship the full per-ware scoring
           table here â€” only the runtime fields the UI needs to render coordination /
           policy / active-mining state.

           CRITICAL: X4 inline table-literals truncate from the first null field onward, so
           building this payload as `table[$A=$a, $B=$b, ...]` would silently drop fields
           whenever any optional source ($selectedWare, $primaryDeliveryStation,
           this.$activeMiningUrgency, $primaryCapacityAvailable, $intentPhase) is null
           between mining slices. Build the payload field-by-field on a blackboard variable
           so the UI always receives the full set of populated keys regardless of which
           runtime fields happen to be unset on this iteration. -->
      <set_value name="this.$minerDiagPayload" exact="table[$Ship = this.ship, $Timestamp = player.age, $TargetStationCount = $demandStations.count, $SupplierCount = $diagSupplierCount, $IntentCount = $diagIntentCount]"/>
      <do_if value="$selectedWare? and $selectedWare != null">
        <set_value name="this.$minerDiagPayload.$SelectedWare" exact="$selectedWare"/>
      </do_if>
      <do_if value="$primaryDeliveryStation? and $primaryDeliveryStation != null and $primaryDeliveryStation.exists">
        <set_value name="this.$minerDiagPayload.$PrimaryDeliveryStation" exact="$primaryDeliveryStation"/>
      </do_if>
      <do_if value="this.$activeMiningUrgency?">
        <set_value name="this.$minerDiagPayload.$Urgency" exact="this.$activeMiningUrgency"/>
      </do_if>
      <do_if value="$overflowSellMode?">
        <set_value name="this.$minerDiagPayload.$OverflowMode" exact="$overflowSellMode"/>
      </do_if>
      <do_if value="$primaryCapacityAvailable?">
        <set_value name="this.$minerDiagPayload.$PrimaryCapacityAvailable" exact="$primaryCapacityAvailable"/>
      </do_if>
      <do_if value="this.$allowOverflowSellToOthers?">
        <set_value name="this.$minerDiagPayload.$OverflowFallbackAllowed" exact="this.$allowOverflowSellToOthers"/>
      </do_if>
      <do_if value="this.$minerDetachedForOverflow?">
        <set_value name="this.$minerDiagPayload.$OverflowDetachedCommander" exact="this.$minerDetachedForOverflow"/>
      </do_if>
      <do_if value="$intentPhase? and $intentPhase != null">
        <set_value name="this.$minerDiagPayload.$IntentPhase" exact="$intentPhase"/>
      </do_if>
      <!-- Per-ware discoverability map (authoritative engine answer for player ships):
           {ware -> bool} where true means the most recent find_closest_resource useundiscovered="false"
           probe found a discovered asteroid for that ware. NPC ships are always reported as true,
           matching vanilla useundiscovered="not this.isplayerowned". The diag tool consumes this
           directly so it can show "needs discovery" without relying on the probe-presence proxy. -->
      <do_if value="this.$activeMiningWareDiscoverable?">
        <set_value name="this.$minerDiagPayload.$DiscoverableWares" exact="this.$activeMiningWareDiscoverable"/>
        <set_value name="this.$minerDiagPayload.$IsPlayerOwned" exact="this.ship.isplayerowned"/>
      </do_if>
      <signal_objects object="player.galaxy" param="'GT_Miner_Diag_Update'" param2="this.$minerDiagPayload"/>
      <remove_value name="this.$minerDiagPayload"/>

      <!-- Map Galaxy-Miner params to vanilla mining routine (distances refreshed at main_loop start). -->
      <set_value name="$effectiveMaxGatherDistance" exact="this.$maxGatherDistance"/>
      <set_value name="$effectiveMaxSellDistance" exact="this.$maxSellDistance"/>
      <!-- With Home Station as the operating anchor, the home station is distance 0.
           Do not widen sell range from the ship's current position; that would let overflow
           searches exceed the player-configured station-centered radius after mining elsewhere. -->
      <set_value name="$effectiveMaxSellDistanceHomeSafe" exact="$effectiveMaxSellDistance"/>
      <set_value name="$runWareBasket" exact="[$selectedWare]"/>
      <set_value name="$minbuy" exact="0"/>
      <set_value name="$maxbuy" exact="if this.$stayAtHome then 0 else $effectiveMaxGatherDistance"/>
      <set_value name="$minsell" exact="0"/>
      <set_value name="$maxsell" exact="$effectiveMaxSellDistanceHomeSafe"/>
      <!-- Never pass scout-only mode: vanilla treats $resourcescout as probe-only recon. -->
      <set_value name="$resourcescout" exact="false"/>
      <set_value name="this.$miner_prevCargoTotal" exact="0"/>
      <set_value name="this.$miner_prevCargoByWare" exact="table[]"/>
      <set_value name="this.$miner_prevStationCargoByStation" exact="table[]"/>
      <set_value name="this.$miner_prevDockedStation" exact="if this.ship.dockedat? and this.ship.dockedat.exists and this.ship.dockedat.isclass.station then this.ship.dockedat else null"/>
      <do_all exact="$runWareBasket.count" counter="$wbi">
        <set_value name="$wareCheck" exact="$runWareBasket.{$wbi}"/>
        <set_value name="this.$miner_prevCargoByWare.{$wareCheck}" exact="this.ship.cargo.{$wareCheck}.count"/>
        <set_value name="this.$miner_prevCargoTotal" exact="this.$miner_prevCargoTotal + this.ship.cargo.{$wareCheck}.count"/>
      </do_all>
      <set_value name="this.$minerPrevStationDemandStations" exact="$demandStations"/>
      <set_value name="this.$minerPrevStationSelectedWare" exact="$selectedWare"/>
      <set_value name="this.$minerPrevStationIndex" exact="1"/>
      <do_while value="this.$minerPrevStationIndex? and this.$minerPrevStationDemandStations? and this.$minerPrevStationIndex le this.$minerPrevStationDemandStations.count">
        <set_value name="$chunkEnd" exact="[this.$minerPrevStationIndex + 10, this.$minerPrevStationDemandStations.count].min"/>
        <do_all exact="$chunkEnd - this.$minerPrevStationIndex + 1" counter="$chunkOffset">
          <set_value name="$tsi" exact="this.$minerPrevStationIndex + $chunkOffset - 1"/>
          <set_value name="$stationEval" exact="this.$minerPrevStationDemandStations.{$tsi}"/>
          <set_value name="this.$miner_prevStationCargoByStation.{$stationEval}" exact="$stationEval.cargo.{this.$minerPrevStationSelectedWare}.count"/>
        </do_all>
        <set_value name="this.$minerPrevStationIndex" exact="$chunkEnd + 1"/>
        <do_if value="this.$minerPrevStationIndex? and this.$minerPrevStationDemandStations? and this.$minerPrevStationIndex le this.$minerPrevStationDemandStations.count">
          <wait exact="1ms"/>
        </do_if>
      </do_while>
      <remove_value name="this.$minerPrevStationDemandStations"/>
      <remove_value name="this.$minerPrevStationSelectedWare"/>
      <remove_value name="this.$minerPrevStationIndex"/>
      <do_if value="this.$miner_prevDockedStation? and this.$miner_prevDockedStation.exists and not this.$miner_prevStationCargoByStation.{this.$miner_prevDockedStation}?">
        <set_value name="this.$miner_prevStationCargoByStation.{this.$miner_prevDockedStation}" exact="this.$miner_prevDockedStation.cargo.{$selectedWare}.count"/>
      </do_if>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Run mining slice ware=' + $selectedWare.name + ', urgency=' + this.$activeMiningUrgency + ', overflow=' + $overflowSellMode + ', primaryStation=' + (if $primaryDeliveryStation? and $primaryDeliveryStation.exists then $primaryDeliveryStation.idcode else 'NONE') + ', range=' + (if $range? then $range.knownname else 'null') + ', rangeClass=' + (if $range? then $range.class else 'null') + ', stayAtHome=' + this.$stayAtHome + ', minbuy=' + $minbuy + ', maxbuy=' + $maxbuy + ', minsell=' + $minsell + ', maxsell=' + $maxsell + ', cargoBefore=' + this.$miner_prevCargoTotal + ', commander=' + (if this.ship.commander? and this.ship.commander.exists then this.ship.commander.idcode else 'NONE') + ', default=' + (if this.ship.defaultorder? then @this.ship.defaultorder.id else 'NONE')" chance="this.$debugchance"/>

      <!-- ============================================================================ -->
      <!-- Equipment pre-check: capital miners require ore-collector / gas-collector    -->
      <!-- drones to actually mine. Vanilla order.mining.routine.xml ~364-401 already   -->
      <!-- guards this case INSIDE the routine, but the failure path there is:          -->
      <!--   1. signal_objects param='resupply' (urgent)                                -->
      <!--   2. wait 1s                                                                 -->
      <!--   3. if interrupt.restock didn't supply -> set_order_failed + force idle +   -->
      <!--      resume label="prep" (loops back inside the routine)                     -->
      <!-- The outer GalaxyMiner order has no awareness of that internal failure: when  -->
      <!-- the routine eventually returns it just continues to the next mining slice    -->
      <!-- and re-runs the routine, which re-fails the same way. Each iteration emits   -->
      <!-- a fresh set_order_failed event, the UI floods with "order failed" toasts /   -->
      <!-- map-update events, and the menu becomes unresponsive (player report).        -->
      <!--                                                                              -->
      <!-- Fix: short-circuit at the outer level. If the SELECTED ware's transport      -->
      <!-- class needs a collector category the ship lacks, skip the mining routine     -->
      <!-- entirely this slice. When AutoResupply is enabled in GT settings, fire the   -->
      <!-- exact same vanilla 'resupply' signal the routine would have fired (so        -->
      <!-- interrupt.restock buys the collectors using its proven loadout/macro logic), -->
      <!-- plus our GT_DoMaintenance signal so any other restock work piggybacks on the -->
      <!-- same trip. When AutoResupply is disabled, just log + stand by; the player    -->
      <!-- gets a clear actionable message instead of a UI lockup.                      -->
      <!--                                                                              -->
      <!-- Selected-ware-keyed (not ship.waretransport-keyed) so a dual-bay ship        -->
      <!-- carrying both solid and liquid cargo capacity isn't blocked when only ONE    -->
      <!-- collector type is missing and the current target ware uses the other type.   -->
      <!-- Non-capital miners (S/M) use mining lasers directly and bypass this check    -->
      <!-- entirely, mirroring the vanilla iscapitalship gate at routine line 364.      -->
      <!-- ============================================================================ -->
      <set_value name="$collectorPrecheckOK" exact="true"/>
      <set_value name="$collectorMissing" exact="''"/>
      <do_if value="$selectedWare? and $selectedWare != null and this.ship.iscapitalship">
        <do_if value="$selectedWare.waretransport == waretransport.solid and not this.ship.units.{unitcategory.orecollector}.count">
          <set_value name="$collectorPrecheckOK" exact="false"/>
          <set_value name="$collectorMissing" exact="'ore-collector'"/>
        </do_if>
        <do_elseif value="$selectedWare.waretransport == waretransport.liquid and not this.ship.units.{unitcategory.gascollector}.count">
          <set_value name="$collectorPrecheckOK" exact="false"/>
          <set_value name="$collectorMissing" exact="'gas-collector'"/>
        </do_elseif>
      </do_if>
      <do_if value="not $collectorPrecheckOK">
        <set_value name="$autoResupplyEnabled" exact="if global.$GT_Config? and global.$GT_Config.$Maintenance? and global.$GT_Config.$Maintenance.$AutoResupply? then global.$GT_Config.$Maintenance.$AutoResupply else 1"/>
        <do_if value="$autoResupplyEnabled">
          <!-- Mirrors the exact urgent-resupply signal vanilla mining routine fires at lines 375 / 380.
               interrupt.restock picks it up, finds an equipment dock selling the matching collector
               drones, and routes the build through add_build_to_modify_ship. Throttle on this.$gtNextCollectorResupplyAt
               so we don't spam the signal between slices when the wharf trip is already in flight. -->
          <do_if value="not this.$gtNextCollectorResupplyAt? or player.age ge this.$gtNextCollectorResupplyAt">
            <!-- Route collector restock through GT_Maintenance ONLY (add_build_to_modify_ship with the
                 $maxCollectorDronesToBuy slider amount). We deliberately DO NOT fire the vanilla
                 'resupply' signal here anymore: vanilla interrupt.restock tops collector drones up to
                 the ship's LOADOUT (a fixed drones+probes ratio) regardless of the player's chosen
                 buy amount, which defeats the slider. GT_Maintenance buys exactly the slider amount
                 and is already gated on collectors==0, so a miner that still has at least one
                 collector is never re-bought. -->
            <signal_objects object="player.galaxy" param="'GT_DoMaintenance'" param2="this.ship"/>
            <set_value name="this.$gtNextCollectorResupplyAt" exact="player.age + 5min"/>
            <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': COLLECTOR PRE-CHECK FAILED - missing ' + $collectorMissing + ' drones for selected ware ' + $selectedWare.name + ' (capital, waretransport=' + $selectedWare.waretransport + '). Signaled GT_DoMaintenance (slider-driven collector buy). Standing by ' + this.$demandRecheckInterval + 's; throttled next collector resupply for 5min.'" chance="100"/>
          </do_if>
          <do_else>
            <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': COLLECTOR PRE-CHECK FAILED - missing ' + $collectorMissing + ' drones for ' + $selectedWare.name + '; collector resupply already in flight (' + (this.$gtNextCollectorResupplyAt - player.age) + 's TTL remaining). Standing by ' + this.$demandRecheckInterval + 's.'" chance="100"/>
          </do_else>
        </do_if>
        <do_else>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': COLLECTOR PRE-CHECK FAILED - missing ' + $collectorMissing + ' drones for ' + $selectedWare.name + '. AutoResupply is DISABLED in GT settings - cannot auto-buy. Standing by ' + this.$demandRecheckInterval + 's. Enable Settings -> Maintenance -> AutoResupply, or manually equip the missing collector drones at any wharf, to allow this miner to mine.'" chance="100"/>
        </do_else>
        <set_command_action commandaction="commandaction.standingby"/>
        <wait exact="this.$demandRecheckInterval"/>
        <resume label="main_loop"/>
      </do_if>

      <!-- Physical storage gate (level 6+): before committing to a mining slice, re-check live
           station physical stock + in-flight miner cargo. When tripped with an empty bay, try
           another scored ware; when tripped with cargo, enter the routine so sellwares runs. -->
      <create_list name="$physGateAltCandidates"/>
      <do_if value="$candidateWares? and $candidateWares.count gt 0">
        <do_all exact="$candidateWares.count" counter="$paci">
          <set_value name="$physGateAltCandidate" exact="$candidateWares.{$paci}"/>
          <do_if value="not $physGateAltCandidate? or $physGateAltCandidate == $selectedWare">
            <continue/>
          </do_if>
          <do_if value="$wareReachable? and $wareReachable.{$physGateAltCandidate}? and not $wareReachable.{$physGateAltCandidate}">
            <continue/>
          </do_if>
          <append_to_list name="$physGateAltCandidates" exact="$physGateAltCandidate"/>
        </do_all>
      </do_if>
      <run_script name="'lib.gt.miner_physical_storage_gate'" result="$physGateOuter">
        <param name="ship" value="this.ship"/>
        <param name="ware" value="$selectedWare"/>
        <param name="primaryTargetStations" value="$demandStations"/>
        <param name="physicalStorageAbortPercent" value="this.$physicalStorageAbortPercent"/>
        <param name="checkDemandFirst" value="this.$checkDemandFirst"/>
        <param name="resourcescout" value="false"/>
        <param name="debugchance" value="this.$debugchance"/>
        <param name="altWareCandidates" value="$physGateAltCandidates"/>
        <param name="altWareUrgency" value="if $wareUrgency? then $wareUrgency else table[]"/>
      </run_script>
      <remove_value name="$physGateAltCandidates"/>
      <do_if value="$physGateOuter.$OpenAltWare? and $physGateOuter.$OpenAltWare != null and this.ship.cargo.{$selectedWare}.count le 0">
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Physical storage gate switched ware ' + $selectedWare.name + ' -> ' + $physGateOuter.$OpenAltWare.name" chance="this.$debugchance"/>
        <set_value name="$selectedWare" exact="$physGateOuter.$OpenAltWare"/>
        <set_value name="this.$activeMiningWare" exact="$selectedWare"/>
        <set_value name="this.$activeMiningUrgency" exact="if $wareUrgency? and $wareUrgency.{$selectedWare}? then $wareUrgency.{$selectedWare} else this.$activeMiningUrgency"/>
        <set_value name="$runWareBasket" exact="[$selectedWare]"/>
      </do_if>
      <do_elseif value="$physGateOuter.$Trips? and $physGateOuter.$Trips">
        <do_if value="this.ship.cargo.{$selectedWare}.count le 0">
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Physical storage gate blocked ware=' + $selectedWare.name + ' with empty bay and no alternate open projection. Waiting ' + this.$demandRecheckInterval + ' for demand to drain.'" chance="this.$debugchance"/>
          <set_command_action commandaction="commandaction.standingby"/>
          <wait exact="this.$demandRecheckInterval"/>
          <resume label="main_loop"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Physical storage gate tripped for ' + $selectedWare.name + ' with cargo in bay â€” entering routine to sell.'" chance="this.$debugchance"/>
        </do_else>
      </do_elseif>
      <remove_value name="$physGateAltCandidate"/>
      <remove_value name="$physGateOuter"/>

      <!-- Single engine locate for the selected ware (scoring uses resources.exists only). -->
      <set_value name="$resolvedSector" exact="null"/>
      <set_value name="$resolvedPos" exact="null"/>
      <set_value name="$sliceGatherSpaces" exact="if this.$minerSliceGatherSpaces? then this.$minerSliceGatherSpaces else []"/>
      <do_if value="this.ship.cargo.free.all gt 0 and $selectedWare? and $selectedWare != null and $sliceGatherSpaces.count gt 0">
        <include_interrupt_actions ref="GetBlacklistgroup"/>
        <set_value name="$locateBlacklistGroup" exact="if $blacklistgroup? then $blacklistgroup else null"/>
        <set_value name="$searchYieldMs" exact="15"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs?">
          <set_value name="$searchYieldMs" exact="global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs"/>
        </do_if>
        <do_if value="$searchYieldMs lt 1">
          <set_value name="$searchYieldMs" exact="1"/>
        </do_if>
        <do_if value="$searchYieldMs gt 100">
          <set_value name="$searchYieldMs" exact="100"/>
        </do_if>
        <!-- Desync fleet locate bursts (ship components have no numeric .id). -->
        <wait min="1ms" max="19ms"/>
        <run_script name="'lib.gt.miner_find_target'" result="$locateResult">
          <param name="ship" value="this.ship"/>
          <param name="ware" value="$selectedWare"/>
          <param name="gatherSpaces" value="$sliceGatherSpaces"/>
          <param name="minrating" value="3"/>
          <param name="searchYieldMs" value="$searchYieldMs"/>
          <param name="staggerMs" value="0"/>
          <param name="blacklistgroup" value="$locateBlacklistGroup"/>
          <param name="debugchance" value="this.$debugchance"/>
        </run_script>
        <do_if value="$locateResult.$Found? and $locateResult.$Found and $locateResult.$Sector? and @$locateResult.$Sector.exists">
          <set_value name="$resolvedSector" exact="$locateResult.$Sector"/>
          <set_value name="$resolvedPos" exact="$locateResult.$Pos"/>
          <do_if value="not this.$activeMiningWareDiscoverable?">
            <set_value name="this.$activeMiningWareDiscoverable" exact="table[]"/>
          </do_if>
          <set_value name="this.$activeMiningWareDiscoverable.{$selectedWare}" exact="if $locateResult.$Discoverable? then $locateResult.$Discoverable else true"/>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Located target ware=' + $selectedWare.name + ' sector=' + $resolvedSector.knownname" chance="this.$debugchance"/>
        </do_if>
        <do_elseif value="this.ship.isplayerowned">
          <do_if value="not this.$activeMiningWareDiscoverable?">
            <set_value name="this.$activeMiningWareDiscoverable" exact="table[]"/>
          </do_if>
          <set_value name="this.$activeMiningWareDiscoverable.{$selectedWare}" exact="false"/>
          <do_if value="$wareReachable?">
            <set_value name="$wareReachable.{$selectedWare}" exact="false"/>
          </do_if>
          <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': No discovered asteroid for selected ware=' + $selectedWare.name + ' in gather range â€” will re-score and try the next mineable demand ware. Standing by ' + this.$demandRecheckInterval + 's.'" chance="this.$debugchance"/>
          <set_command_action commandaction="commandaction.standingby"/>
          <remove_value name="$locateResult"/>
          <remove_value name="$locateBlacklistGroup"/>
          <remove_value name="$searchYieldMs"/>
          <remove_value name="$sliceGatherSpaces"/>
          <do_if value="$blacklistgroup?">
            <remove_value name="$blacklistgroup"/>
          </do_if>
          <wait exact="this.$demandRecheckInterval"/>
          <resume label="main_loop"/>
        </do_elseif>
        <remove_value name="$locateResult"/>
        <remove_value name="$locateBlacklistGroup"/>
        <remove_value name="$searchYieldMs"/>
        <do_if value="$blacklistgroup?">
          <remove_value name="$blacklistgroup"/>
        </do_if>
      </do_if>
      <remove_value name="$sliceGatherSpaces"/>

      <!-- Run GT mining routine fork in time slices so GT maintenance/training can run between cycles -->
      <set_value name="$strictGatherSector" exact="if this.$stayAtHome and this.$homeSector? and this.$homeSector.exists then this.$homeSector else null"/>
      <run_script name="'order.mining.routine.gt'">
        <param name="warebasket" value="$runWareBasket"/>
        <param name="range" value="$range"/>
        <param name="strictgathersector" value="$strictGatherSector"/>
        <param name="precomputedgatherspaces" value="if this.$minerSliceGatherSpaces? then this.$minerSliceGatherSpaces else []"/>
        <param name="resolvedsector" value="$resolvedSector"/>
        <param name="resolvedpos" value="$resolvedPos"/>
        <param name="playerStationsOnly" value="this.$playerStationsOnly"/>
        <param name="primaryTargetStations" value="$demandStations"/>
        <param name="blockedstations" value="if this.$effectiveBlockedStations? then this.$effectiveBlockedStations else []"/>
        <param name="overflowSellMode" value="$overflowSellMode"/>
        <param name="allowOverflowSellToOthers" value="this.$allowOverflowSellToOthers"/>
        <param name="overflowThreshold" value="this.$overflowThreshold"/>
        <param name="physicalStorageAbortPercent" value="this.$physicalStorageAbortPercent"/>
        <param name="checkDemandFirst" value="this.$checkDemandFirst"/>
        <param name="minbuy" value="$minbuy"/>
        <param name="maxbuy" value="$maxbuy"/>
        <param name="minsell" value="$minsell"/>
        <param name="maxsell" value="$maxsell"/>
        <param name="resourcescout" value="$resourcescout"/>
        <param name="logbookentries" value="this.$logbookentries"/>
        <param name="allowIllegal" value="this.$allowillegal"/>
        <param name="enforceRouteIllegalLegality" value="this.$enforceRouteIllegalLegality"/>
        <param name="duration" value="this.$demandRecheckInterval"/>
        <param name="debugchance" value="this.$debugchance"/>
      </run_script>
      <remove_value name="this.$minerSliceGatherSpaces"/>
      <remove_value name="$resolvedSector"/>
      <remove_value name="$resolvedPos"/>

      <!-- Detect delivery completion and emit one XP event per delivery slice -->
      <set_value name="$cargoAfterDelivery" exact="0"/>
      <do_all exact="$runWareBasket.count" counter="$wbi">
        <set_value name="$wareCheck" exact="$runWareBasket.{$wbi}"/>
        <set_value name="$cargoAfterDelivery" exact="$cargoAfterDelivery + this.ship.cargo.{$wareCheck}.count"/>
      </do_all>
      <set_value name="$netCargoDelta" exact="this.$miner_prevCargoTotal - $cargoAfterDelivery"/>
      <set_value name="$currentDockedStation" exact="if this.ship.dockedat? and this.ship.dockedat.exists and this.ship.dockedat.isclass.station then this.ship.dockedat else null"/>
      <set_value name="$confirmedStationDelivery" exact="0"/>
      <set_value name="$deliveryStation" exact="null"/>
      <do_if value="$currentDockedStation? and this.$miner_prevStationCargoByStation? and this.$miner_prevStationCargoByStation.{$currentDockedStation}?">
        <set_value name="$stationBefore" exact="this.$miner_prevStationCargoByStation.{$currentDockedStation}"/>
        <set_value name="$stationAfter" exact="$currentDockedStation.cargo.{$selectedWare}.count"/>
        <set_value name="$stationDelta" exact="$stationAfter - $stationBefore"/>
        <do_if value="$stationDelta gt 0">
          <set_value name="$confirmedStationDelivery" exact="$stationDelta"/>
          <set_value name="$deliveryStation" exact="$currentDockedStation"/>
        </do_if>
      </do_if>
      <do_elseif value="this.$miner_prevDockedStation? and this.$miner_prevDockedStation.exists and this.$miner_prevStationCargoByStation? and this.$miner_prevStationCargoByStation.{this.$miner_prevDockedStation}?">
        <set_value name="$stationBefore" exact="this.$miner_prevStationCargoByStation.{this.$miner_prevDockedStation}"/>
        <set_value name="$stationAfter" exact="this.$miner_prevDockedStation.cargo.{$selectedWare}.count"/>
        <set_value name="$stationDelta" exact="$stationAfter - $stationBefore"/>
        <do_if value="$stationDelta gt 0">
          <set_value name="$confirmedStationDelivery" exact="$stationDelta"/>
          <set_value name="$deliveryStation" exact="this.$miner_prevDockedStation"/>
        </do_if>
      </do_elseif>
      <set_value name="$deliveredAmount" exact="[$confirmedStationDelivery, $netCargoDelta].max"/>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': Slice complete ware=' + $selectedWare.name + ', cargoAfter=' + $cargoAfterDelivery + ', cargoDelta=' + $netCargoDelta + ', stationDelivery=' + $confirmedStationDelivery + ', delivered=' + $deliveredAmount + ', dockedAt=' + (if $currentDockedStation? and $currentDockedStation.exists then $currentDockedStation.idcode else 'NONE') + ', commander=' + (if this.ship.commander? and this.ship.commander.exists then this.ship.commander.idcode else 'NONE') + ', default=' + (if this.ship.defaultorder? then @this.ship.defaultorder.id else 'NONE')" chance="this.$debugchance"/>
      <set_value name="$intentPhaseAfterRun" exact="'mining'"/>
      <set_value name="$hasIntentWareAfterRun" exact="this.$minerIntentWare? and this.$minerIntentWare != null"/>
      <do_if value="$hasIntentWareAfterRun and this.ship.cargo.{this.$minerIntentWare}.count gt 0">
        <set_value name="$intentPhaseAfterRun" exact="'hauling'"/>
      </do_if>
      <do_if value="$deliveredAmount gt 0">
        <set_value name="$intentPhaseAfterRun" exact="'delivering'"/>
      </do_if>
      <!-- B5: After a slice, drop intents whose phase reached 'delivering' (cargo already on the station, no more incoming
           from this ship for this cycle) so they stop inflating $projectedIncoming for everyone else.
           For 'mining' / 'hauling' phases, refresh the ETA to one full demand-recheck interval forward â€” long enough to stay
           in-horizon for the next scoring pass, short enough that abandoned intents naturally fall out without a janitor. -->
      <do_if value="$hasIntentWareAfterRun and this.$minerIntentStations? and this.$minerIntentStations.count gt 0">
        <do_all exact="this.$minerIntentStations.count" counter="$isi">
          <set_value name="$intentStation" exact="this.$minerIntentStations.{$isi}"/>
          <do_if value="global.$GT_MinerIntents? and global.$GT_MinerIntents.{$intentStation}? and global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}? and global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}?">
            <do_if value="$intentPhaseAfterRun == 'delivering'">
              <remove_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}"/>
            </do_if>
            <do_else>
              <set_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}.$phase" exact="$intentPhaseAfterRun"/>
              <set_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}.$eta" exact="player.age + this.$demandRecheckInterval"/>
            </do_else>
          </do_if>
        </do_all>
      </do_if>

      <!-- Restore station assignment after overflow fallback run -->
      <do_if value="this.$minerDetachedForOverflow and this.$assignToStation and this.$homeStation? and this.$homeStation.exists">
        <do_if value="this.$minerOverflowCommanderBackup? and this.$minerOverflowCommanderBackup.exists">
          <set_object_commander object="this.ship" commander="this.$minerOverflowCommanderBackup" assignment="assignment.mining"/>
        </do_if>
        <do_elseif value="this.$assignToStation and this.$homeStation? and this.$homeStation.exists and (not this.ship.commander? or not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station)">
          <set_object_commander object="this.ship" commander="this.$homeStation" assignment="assignment.mining"/>
        </do_elseif>
        <set_value name="this.$minerDetachedForOverflow" exact="false"/>
        <set_value name="this.$minerOverflowCommanderBackup" exact="null"/>
      </do_if>
      <do_if value="$deliveredAmount gt 0">
        <set_value name="$deliveredWare" exact="$selectedWare"/>
        <set_value name="$minerTransferPayload" exact="table[
          $Ship = this.ship,
          $ware = $deliveredWare,
          $transferredAmount = $deliveredAmount,
          $station = $deliveryStation,
          $timestamp = player.age
        ]"/>

        <!-- XP is optional metadata on the transfer payload; logbook routing must not depend on XP eligibility. -->
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <!-- Miner XP scales with delivery value so bigger ships and pricier wares gain more XP -->
          <set_value name="$baseXP" exact="@global.$GT_Config.$XP.$BaseXPPerTrade"/>
          <set_value name="$minerValueDivisor" exact="@global.$GT_Config.$XP.$MinerValueDivisor"/>
          <set_value name="$xpMin" exact="@global.$GT_Config.$XP.$MinXPPerTrade"/>
          <set_value name="$xpMax" exact="@global.$GT_Config.$XP.$MaxXPPerTrade"/>
          <set_value name="$xpMultiplier" exact="100"/>
          <do_if value="not $baseXP?">
            <set_value name="$baseXP" exact="8"/>
          </do_if>
          <do_if value="not $minerValueDivisor? or $minerValueDivisor le 0">
            <set_value name="$minerValueDivisor" exact="200000"/>
          </do_if>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$XPMultiplier?">
            <set_value name="$xpMultiplier" exact="global.$GT_GlobalSettings.$XP.$XPMultiplier"/>
          </do_if>
          <set_value name="$deliveredUnitPrice" exact="$deliveredWare.averageprice"/>
          <set_value name="$deliveredValueMultiplier" exact="(($deliveredAmount * $deliveredUnitPrice) / ($minerValueDivisor * 1Cr))f"/>
          <set_value name="$minerXPAmount" exact="($baseXP * $deliveredValueMultiplier)i"/>
          <set_value name="$minerXPAmount" exact="(($minerXPAmount * $xpMultiplier) / 100)i"/>
          <set_value name="$minerXPAmount" exact="[1, [$minerXPAmount, $xpMax].min].max"/>
          <set_value name="$minerXPAmount" exact="[$xpMin, $minerXPAmount].max"/>
          <set_value name="$minerTransferPayload.$pilot" exact="this.ship.pilot"/>
          <set_value name="$minerTransferPayload.$xpAmount" exact="$minerXPAmount"/>
        </do_if>

        <signal_objects object="player.galaxy" param="'GT_MinerTransfer'" param2="$minerTransferPayload"/>
      </do_if>

      <resume label="main_loop"/>
    </actions>
  </attention>

  <on_abort>
    <!-- Intentional handoff: idle parking delegates to GTIdlePark for visible queued docking. -->
    <set_value name="$isIdleParkHandoff" exact="false"/>
    <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.orders.count gt 0">
      <do_all exact="this.ship.orders.count" counter="$ipoi">
        <set_value name="$ipOrder" exact="this.ship.orders.{$ipoi}"/>
        <do_if value="@$ipOrder.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_if>
        <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_elseif>
      </do_all>
    </do_if>
    <do_if value="$isIdleParkHandoff">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': on_abort skipped (handoff to GTIdlePark)'" chance="100"/>
      </do_if>
      <return/>
    </do_if>

    <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': on_abort cleanup start. commander=' + (if this.ship.commander? and this.ship.commander.exists then this.ship.commander.idcode else 'NONE') + ', default=' + (if this.ship.defaultorder? then @this.ship.defaultorder.id else 'NONE') + ', overflowDetached=' + this.$minerDetachedForOverflow" chance="this.$debugchance"/>
    <!-- Safety reattach:
         if abort happens while temporarily detached for overflow fallback,
         restore station assignment so subordinates do not remain orphaned. -->
    <do_if value="this.$minerDetachedForOverflow and this.$assignToStation and this.$homeStation? and this.$homeStation.exists and (not this.ship.commander? or not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station)">
      <do_if value="this.$minerOverflowCommanderBackup? and this.$minerOverflowCommanderBackup.exists">
        <set_object_commander object="this.ship" commander="this.$minerOverflowCommanderBackup" assignment="assignment.mining"/>
      </do_if>
      <do_else>
        <set_object_commander object="this.ship" commander="this.$homeStation" assignment="assignment.mining"/>
      </do_else>
      <set_value name="this.$minerDetachedForOverflow" exact="false"/>
      <set_value name="this.$minerOverflowCommanderBackup" exact="null"/>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': on_abort restored commander assignment after overflow detach'" chance="this.$debugchance"/>
    </do_if>
    <do_if value="this.$minerAssignedWare? and this.$minerAssignedStations? and this.$minerAssignedStations.count gt 0">
      <do_all exact="this.$minerAssignedStations.count" counter="$asi">
        <set_value name="$assignedStation" exact="this.$minerAssignedStations.{$asi}"/>
        <remove_value name="global.$GT_MinerStationAssignments.{$assignedStation}.{this.$minerAssignedWare}.{this.ship}"/>
      </do_all>
    </do_if>
    <do_if value="this.$minerIntentWare? and this.$minerIntentWare != null and this.$minerIntentStations? and this.$minerIntentStations.count gt 0">
      <do_all exact="this.$minerIntentStations.count" counter="$isi">
        <set_value name="$intentStation" exact="this.$minerIntentStations.{$isi}"/>
        <remove_value name="global.$GT_MinerIntents.{$intentStation}.{this.$minerIntentWare}.{this.ship}"/>
      </do_all>
    </do_if>
    <!-- Abort can happen during subordinate Assist restarts while GT control is still valid.
         Only emit cancellation/orphan checks when GT control is really gone. -->
    <set_value name="$abortDefaultOrder" exact="if this.ship.defaultorder? then @this.ship.defaultorder.id else null"/>
    <set_value name="$abortHasDirectGTOrder" exact="false"/>
    <set_value name="$abortHasGTCommander" exact="false"/>
    <do_if value="$abortDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$abortDefaultOrder}">
      <set_value name="$abortHasDirectGTOrder" exact="true"/>
    </do_if>
    <do_elseif value="$abortDefaultOrder == 'Assist' and this.ship.defaultorder? and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
      <set_value name="$abortHasDirectGTOrder" exact="true"/>
    </do_elseif>
    <do_if value="not $abortHasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
      <set_value name="$abortHasGTCommander" exact="true"/>
    </do_if>
    <do_elseif value="not $abortHasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
      <set_value name="$abortHasGTCommander" exact="true"/>
    </do_elseif>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-Miner-DIAG] ON_ABORT ship=' + this.ship.idcode + ', default=' + (if $abortDefaultOrder? then $abortDefaultOrder else 'NONE') + ', current=' + (if this.ship.order? then @this.ship.order.id else 'NONE') + ', hasDirectGT=' + $abortHasDirectGTOrder + ', hasGTCommander=' + $abortHasGTCommander + ', commander=' + (if this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship then this.ship.commander.idcode else 'NONE') + ', orders=' + (if this.ship.orders? then this.ship.orders.count else 0)" chance="100"/>
    </do_if>
    <do_if value="not $abortHasDirectGTOrder and not $abortHasGTCommander">
      <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
        $Ship = this.ship,
        $UpdateType = 'GT_Order_Cancelled'
      ]"/>
      <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
    </do_if>
    <do_else>
      <debug_text text="'[GT-Miner] ' + this.ship.idcode + ': on_abort detected active GT control (default=' + (if $abortDefaultOrder? then $abortDefaultOrder else 'NONE') + ', hasDirect=' + $abortHasDirectGTOrder + ', hasGTCommander=' + $abortHasGTCommander + ') - skipping GT_Order_Cancelled'" chance="this.$debugchance"/>
    </do_else>
    <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}?">
      <remove_value name="global.$GT_AIParameters.{this.ship}"/>
    </do_if>
    <do_if value="global.$GT_MinerDiag? and global.$GT_MinerDiag.{this.ship}?">
      <remove_value name="global.$GT_MinerDiag.{this.ship}"/>
    </do_if>
    <!-- E1: drop persisted chunked-loop scratch state so an abort mid-scan does not leak entries on the ship blackboard. -->
    <do_if value="this.$minerDemandSectorsScanList?"><remove_value name="this.$minerDemandSectorsScanList"/></do_if>
    <do_if value="this.$minerDemandSectorsScanIndex?"><remove_value name="this.$minerDemandSectorsScanIndex"/></do_if>
    <do_if value="this.$minerSectorStationsScanList?"><remove_value name="this.$minerSectorStationsScanList"/></do_if>
    <do_if value="this.$minerSectorStationsScanIndex?"><remove_value name="this.$minerSectorStationsScanIndex"/></do_if>
    <do_if value="this.$minerDemandStationsBuildTargetStations?"><remove_value name="this.$minerDemandStationsBuildTargetStations"/></do_if>
    <do_if value="this.$minerDemandStationsBuildIndex?"><remove_value name="this.$minerDemandStationsBuildIndex"/></do_if>
    <do_if value="this.$minerCandidateScanDemandStations?"><remove_value name="this.$minerCandidateScanDemandStations"/></do_if>
    <do_if value="this.$minerCandidateScanIndex?"><remove_value name="this.$minerCandidateScanIndex"/></do_if>
    <do_if value="this.$minerBuyOfferScanDemandStations?"><remove_value name="this.$minerBuyOfferScanDemandStations"/></do_if>
    <do_if value="this.$minerBuyOfferScanIndex?"><remove_value name="this.$minerBuyOfferScanIndex"/></do_if>
    <do_if value="this.$minerCleanupAssignedIndex?"><remove_value name="this.$minerCleanupAssignedIndex"/></do_if>
    <do_if value="this.$minerCleanupIntentIndex?"><remove_value name="this.$minerCleanupIntentIndex"/></do_if>
    <do_if value="this.$minerGatherFilterIn?"><remove_value name="this.$minerGatherFilterIn"/></do_if>
    <do_if value="this.$minerGatherFilterOut?"><remove_value name="this.$minerGatherFilterOut"/></do_if>
    <do_if value="this.$minerGatherFilterIndex?"><remove_value name="this.$minerGatherFilterIndex"/></do_if>
    <do_if value="this.$minerScoreCandidateWares?"><remove_value name="this.$minerScoreCandidateWares"/></do_if>
    <do_if value="this.$minerScoreGatherSpaces?"><remove_value name="this.$minerScoreGatherSpaces"/></do_if>
    <do_if value="this.$minerSliceGatherSpaces?"><remove_value name="this.$minerSliceGatherSpaces"/></do_if>
    <do_if value="this.$minerScoreDemandStations?"><remove_value name="this.$minerScoreDemandStations"/></do_if>
    <do_if value="this.$minerScoreWareUrgency?"><remove_value name="this.$minerScoreWareUrgency"/></do_if>
    <do_if value="this.$minerScoreWareHasPrimaryCapacity?"><remove_value name="this.$minerScoreWareHasPrimaryCapacity"/></do_if>
    <do_if value="this.$minerScoreWareReachable?"><remove_value name="this.$minerScoreWareReachable"/></do_if>
    <do_if value="this.$minerScoreWareDiscoverable?"><remove_value name="this.$minerScoreWareDiscoverable"/></do_if>
    <do_if value="this.$minerScoreBestUrgency?"><remove_value name="this.$minerScoreBestUrgency"/></do_if>
    <do_if value="this.$minerScoreBestWares?"><remove_value name="this.$minerScoreBestWares"/></do_if>
    <do_if value="this.$minerScoreIndex?"><remove_value name="this.$minerScoreIndex"/></do_if>
    <do_if value="this.$minerOverflowCandidateWares?"><remove_value name="this.$minerOverflowCandidateWares"/></do_if>
    <do_if value="this.$minerOverflowBestWare?"><remove_value name="this.$minerOverflowBestWare"/></do_if>
    <do_if value="this.$minerOverflowBestOffers?"><remove_value name="this.$minerOverflowBestOffers"/></do_if>
    <do_if value="this.$minerOverflowIndex?"><remove_value name="this.$minerOverflowIndex"/></do_if>
    <do_if value="this.$minerPrimaryDemandStations?"><remove_value name="this.$minerPrimaryDemandStations"/></do_if>
    <do_if value="this.$minerPrimarySelectedWare?"><remove_value name="this.$minerPrimarySelectedWare"/></do_if>
    <do_if value="this.$minerPrimaryBestDeficit?"><remove_value name="this.$minerPrimaryBestDeficit"/></do_if>
    <do_if value="this.$minerPrimaryDeliveryStation?"><remove_value name="this.$minerPrimaryDeliveryStation"/></do_if>
    <do_if value="this.$minerPrimaryIndex?"><remove_value name="this.$minerPrimaryIndex"/></do_if>
    <do_if value="this.$minerAssignDemandStations?"><remove_value name="this.$minerAssignDemandStations"/></do_if>
    <do_if value="this.$minerAssignSelectedWare?"><remove_value name="this.$minerAssignSelectedWare"/></do_if>
    <do_if value="this.$minerAssignIndex?"><remove_value name="this.$minerAssignIndex"/></do_if>
    <do_if value="this.$minerIntentBuildDemandStations?"><remove_value name="this.$minerIntentBuildDemandStations"/></do_if>
    <do_if value="this.$minerIntentBuildSelectedWare?"><remove_value name="this.$minerIntentBuildSelectedWare"/></do_if>
    <do_if value="this.$minerIntentBuildIndex?"><remove_value name="this.$minerIntentBuildIndex"/></do_if>
    <do_if value="this.$minerIntentPhaseIndex?"><remove_value name="this.$minerIntentPhaseIndex"/></do_if>
    <do_if value="this.$minerDiagDemandStations?"><remove_value name="this.$minerDiagDemandStations"/></do_if>
    <do_if value="this.$minerDiagSelectedWare?"><remove_value name="this.$minerDiagSelectedWare"/></do_if>
    <do_if value="this.$minerDiagIndex?"><remove_value name="this.$minerDiagIndex"/></do_if>
    <do_if value="this.$minerDiagSupplierCount?"><remove_value name="this.$minerDiagSupplierCount"/></do_if>
    <do_if value="this.$minerDiagIntentCount?"><remove_value name="this.$minerDiagIntentCount"/></do_if>
    <do_if value="this.$minerDiagPayload?"><remove_value name="this.$minerDiagPayload"/></do_if>
    <do_if value="this.$activeMiningWareDiscoverable?"><remove_value name="this.$activeMiningWareDiscoverable"/></do_if>
    <do_if value="this.$minerPrevStationDemandStations?"><remove_value name="this.$minerPrevStationDemandStations"/></do_if>
    <do_if value="this.$minerPrevStationSelectedWare?"><remove_value name="this.$minerPrevStationSelectedWare"/></do_if>
    <do_if value="this.$minerPrevStationIndex?"><remove_value name="this.$minerPrevStationIndex"/></do_if>
  </on_abort>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.trade.galaxytrader" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="7">
  <order id="GalaxyTraderMK3" name="{77000, 10002}" description="{77000, 10102}" category="trade" infinite="true" allowinloop="false" canplayercancel="true">
    <params>
      <!-- ========================================== -->
      <!-- BASIC TRADING SETTINGS                    -->
      <!-- ========================================== -->
              <param name="home" default="this.sector" type="object" text="{77000,1002}" comment="Home base for trading operations (sector or station)">
        <input_param name="class" value="[class.sector,class.station]"/>
      </param>
      <param name="maxbuy" default="1" type="number" text="{1041, 10054}" comment="Maximum gate distance for buy opportunities (skill-based: Lv1-2=1j, Lv3-5=3j, Lv6-8=5j, Lv9-11=10j, Lv12-13=15j, Lv14+=25j)">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="maxsell" default="1" type="number" text="{1041, 10057}" comment="Maximum gate distance for sell opportunities (skill-based: Lv1-2=1j, Lv3-5=3j, Lv6-8=5j, Lv9-11=10j, Lv12-13=15j, Lv14+=25j)">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="allowillegal" default="false" type="bool" text="{77000,1011}" comment="{77000,1025}"/>
      <param name="enforceRouteIllegalLegality" default="false" type="bool" text="{77000,1070}" comment="{77000,1071}"/>
      <param name="ignorecarrieraux" default="false" type="bool" text="{77000,1054}" comment="{77000,1055}"/>
      <param name="ignorebuildstorage" default="false" type="bool" text="{77000,1056}" comment="{77000,1057}"/>
      <param name="ignoretraderules" default="false" type="bool" text="{77000,1058}" comment="{77000,1059}"/>
      <param name="ignoreplayerpricing" default="false" type="bool" text="{77000,1092}" comment="{77000,1093}">
        <!-- Backfill for v1/v2/v3 saves that were created before the "Ignore Player Pricing" toggle existed. -->
        <patch value="false" sinceversion="4"/>
      </param>
      <param name="ignoremk1supply" default="true" type="bool" text="{77000,1060}" comment="{77000,1061}"/>
      <param name="logbookentries" default="true" type="bool" text="{77000,1012}" comment="{77000,1041}"/>
      <param name="idleParking" default="false" type="bool" text="{77000,1096}" comment="{77000,1097}">
        <patch value="false" sinceversion="6"/>
      </param>
      <param name="autoJumpDistanceByLevel" default="false" type="bool" text="{77000,1098}" comment="{77000,1099}">
        <patch value="false" sinceversion="7"/>
      </param>
      <param name="factionpriority" default="false" type="bool" text="{77000,1014}" comment="{77000,1062}"/>
      
      <!-- ========================================== -->
      <!-- WARE SELECTION                           -->
      <!-- ========================================== -->
      <param name="autowares" default="true" type="bool" text="{77000,1015}" comment="{77000,1023}"/>
      <param name="warebasket" default="[]" type="list" text="{77000,1069}" comment="Manual ware selection (only used if Auto Wares is disabled)">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="sectorwhitelist" default="[]" type="list" text="{77000,1052}" comment="{77000,1053}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.sector]"/>
      </param>
      <param name="blockedstations" default="[]" type="list" text="{77000,1094}" comment="{77000,1095}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
        <patch value="[]" sinceversion="5"/>
      </param>
      <param name="prioritywares" default="[]" type="list" text="{77000,1064}" comment="{77000,1066}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="priorityscoremultiplier" default="150" type="number" text="{77000,1065}" comment="{77000,1067}">
        <input_param name="min" value="125"/>
        <input_param name="max" value="300"/>
        <input_param name="step" value="25"/>
      </param>
      
      <!-- ========================================== -->
      <!-- TRADING RANGE (Ship-specific)             -->
      <!-- ========================================== -->
      <param name="distancepenalty" default="50" type="number" text="{77000,1016}" comment="Distance impact on trade scoring: 0%=Ignore distance (pure profit), 50%=Balanced, 100%=Prefer close trades (2x distance penalty)">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      
      <!-- ========================================== -->
      <!-- NOTIFICATION LEVEL (Global setting override) -->
      <!-- ========================================== -->
      <param name="notifications" default="1" type="number" text="{77000,1017}" comment="{77000,1032}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      
      <!-- ========================================== -->
      <!-- ADVANCED SETTINGS                         -->
      <!-- ========================================== -->
      <param name="fleetcoordination" default="true" type="bool" text="{77000,1018}" advanced="true" comment="{77000,1029}"/>
      <param name="cargotarget" default="80" type="number" text="{77000,1019}" comment="{77000,1033}">
        <input_param name="min" value="10"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      <param name="marketupdatefreq" default="60s" type="time" text="{77000,1050}" advanced="true" comment="{77000,1034}">
        <input_param name="min" value="30s"/>
        <input_param name="max" value="300s"/>
        <input_param name="step" value="30s"/>
      </param>
      <param name="debuglevel" default="1" type="number" text="{1041, 10086}" advanced="true" comment="{77000,1035}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="tradeeval" default="false" type="bool" text="{77000,1051}" advanced="true" comment="{77000,1040}"/>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
  </order>
  
  <interrupts>
    <handler ref="SectorChangeHandler"/>
    
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>
    
    <!-- Trade Found Event Handler: Catches GT_Trade_Found signal regardless of ship state -->
    <!-- This ensures trades are processed immediately even if ship is in main_loop or other code paths -->
    <!-- Note: Cannot use <resume> in interrupt handlers, so we set a flag that main_loop checks -->
    <!-- Trade data is passed in signal param2 (like GT_Training_Station_Found) -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
      </conditions>
      <actions>
        <!-- Extract trade data from signal param2 (like GT_Training_Station_Found handler) -->
        <set_value name="$signalData" exact="event.param2"/>
        <set_value name="$signalTradeList" exact="[]"/>
        <set_value name="$signalSearchMethod" exact="''"/>
        <do_if value="$signalData? and $signalData != null">
          <set_value name="$signalTradeList" exact="@$signalData.$TradeList"/>
          <set_value name="$signalSearchMethod" exact="@$signalData.$SearchMethod"/>
        </do_if>
        
        <!-- FALLBACK: If param2 is empty or null, read from global storage (backward compatibility) -->
        <!-- This handles cases where ProcessTradeFoundSignalQueue fails to populate param2 -->
        <do_if value="($signalTradeList == null or $signalTradeList.count == 0) and global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
          <set_value name="$signalTradeList" exact="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <set_value name="$signalSearchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
        </do_if>
        
        <!-- Only set the interrupt flag if we actually have trades to process.
             Empty signals cause pointless trade_found processing with 0 trades. -->
        <do_if value="$signalTradeList != null and $signalTradeList.count gt 0">
          <set_value name="this.$tradeFoundViaInterrupt" exact="true"/>
          <set_value name="this.$tradeListFromSignal" exact="$signalTradeList"/>
          <set_value name="this.$searchMethodFromSignal" exact="if $signalSearchMethod != null and $signalSearchMethod != '' then $signalSearchMethod else ''"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$dataSource" exact="if (event.param2? and event.param2 != null) then 'param2' else 'global storage'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received via interrupt handler - stored ' + $signalTradeList.count + ' trades from ' + $dataSource" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received but trade list is empty - ignoring (no interrupt flag set)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <!-- High-Performance Training Event Handlers -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$trainingStation" exact="$trainingData.$Station"/>
        <set_value name="$requiredLevel" exact="$trainingData.$Level"/>
        <!-- Academy enrollments must NOT interrupt the current order; they
             append DockAndTrain so the ship finishes the active task first
             and the queued training is visible in the order list. The
             natural training ladder keeps using immediate dispatch. -->
        <set_value name="$isAcademy" exact="@$trainingData.$IsAcademy"/>
        <set_value name="$useImmediate" exact="not $isAcademy"/>
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist'">
          <set_value name="$useImmediate" exact="false"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸŽ“ Training station found: ' + $trainingStation.knownname + ' for level ' + $requiredLevel + ' (academy=' + $isAcademy + ', immediate=' + $useImmediate + ')'" chance="100"/>
        </do_if>
        
        <!-- Create training order: immediate for natural ladder, queued for academy -->
        <create_order object="this.ship" id="'DockAndTrain'" immediate="$useImmediate">
          <param name="destination" value="$trainingStation"/>
          <param name="debugchance" value="@this.$debugchance"/>
        </create_order>
        
        <!-- Set flag to indicate training is in progress -->
        <set_value name="this.$training_in_progress" exact="true"/>
        <!-- Set flag to indicate training transition for on_abort handler -->
        <set_value name="this.$training_transition" exact="true"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': DockAndTrain order created for ' + $trainingStation.knownname" chance="100"/>
        </do_if>
        
        <!-- Set flag to prevent race condition in on_abort handler -->
        <!-- Ensures the on_abort handler knows a training order was just created -->
        <set_value name="this.$training_order_created" exact="player.age"/>
      </actions>
    </handler>
    
    <!-- Event-Driven Mobile Satellite Intelligence: Detect stations entering radar range -->
    <!-- 
    OPTIMIZED: Event-driven station detection (replaces polling-based MobileSatelliteIntelligence)
    - Uses vanilla gravidar scan events (zero CPU when no stations detected)
    - Only Level 9+ pilots can detect stations (skill gate maintained)
    - Signals MD immediately when stations detected (no polling overhead)
    - Same functionality as old polling system but much more efficient
    -->
    <handler comment="Detect stations entering radar range for mobile satellite intelligence">
      <conditions>
        <event_gravidar_has_scanned object="this.ship"/>
        <check_value value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?"/>
        <check_value value="this.sector"/>
        <!-- Only Level 9+ pilots and when Mobile Intel is enabled -->
        <check_value value="@global.$GT_Pilots.{this.ship.pilot}.$Level ge 9"/>
        <check_value value="not global.$GT_GlobalSettings.$MobileIntel? or global.$GT_GlobalSettings.$MobileIntel.$Enable"/>
        <!-- PERFORMANCE: Do not run actions unless there is at least 1 station contact -->
        <!-- Vanilla pattern: use count_gravidar_contacts with min="1" to avoid per-scan work when nothing is detected -->
        <count_gravidar_contacts result="$_detectedStations" object="this.ship" class="class.station" docked="false" checkoperational="true" multiple="true" min="1"/>
      </conditions>
      <actions>
        <!-- Stations were detected (min=1 in conditions). Process a small capped number per scan to smooth spikes. -->
        <set_value name="$level" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        <set_value name="$detectedStations" exact="$_detectedStations"/>
        
        <!-- Cap work per scan event (prevents large bursts when many stations are in radar range) -->
        <set_value name="$stationsToProcess" exact="[$detectedStations.count, 5].min"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI-Intel] ' + this.ship.idcode + ' detected ' + $detectedStations.count + ' station(s) - processing ' + $stationsToProcess" chance="20"/>
        </do_if>
        
        <do_all exact="$stationsToProcess" counter="$i">
          <set_value name="$station" exact="$detectedStations.{$i}"/>
          <do_if value="$station.exists and $station.isoperational">
            <!-- Signal MD to process this station -->
            <signal_objects object="player.galaxy" param="'GT_Station_Detected'" param2="table[$Ship=this.ship, $station=$station, $pilotLevel=$level]"/>
          </do_if>
        </do_all>
      </actions>
    </handler>

    <!-- Event-Driven Threat Avoidance: Detect hostile ships entering radar range (gravidar) -->
    <!-- Uses vanilla event_gravidar_has_scanned + count_gravidar_contacts (no polling).
         Only broadcasts when computed threat level meets ThreatAvoidance.BlacklistThreshold to avoid spam. -->
    <handler comment="ThreatAvoidance: hostile gravidar contact detection">
      <conditions>
        <event_gravidar_has_scanned object="this.ship"/>
        <check_value value="this.sector"/>
        <!-- Feature gate -->
        <check_value value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ThreatAvoidance? and global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled"/>
        <check_value value="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>
        <!-- Only run actions if at least 1 hostile ship contact exists -->
        <count_gravidar_contacts result="$_detectedHostiles" object="this.ship" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" maybeattackedby="this.ship" checkoperational="false" masstraffic="false" docked="false" multiple="true" min="1">
          <match_context macro="this.sector.macro"/>
          <match_context class="class.highway" negate="true"/>
          <match state="componentstate.wreck" negate="true"/>
        </count_gravidar_contacts>
      </conditions>
      <actions>
        <!-- Get pilot skill level - only Level 6+ pilots can broadcast threat warnings to fleet -->
        <set_value name="$pilotLevel" exact="1"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        
        <!-- Shared throttle with move.generic detection (single source of truth across scripts).
             This prevents duplicate logs/broadcasts when both move.generic and this order detect the same contact. -->
        <do_if value="not global.$GT_ThreatDetectThrottle?">
          <set_value name="global.$GT_ThreatDetectThrottle" exact="table[]"/>
        </do_if>
        <set_value name="$_last" exact="@global.$GT_ThreatDetectThrottle.{this.ship}"/>
        <do_if value="$_last == null">
          <set_value name="$_last" exact="0s"/>
        </do_if>
        <set_value name="$_logAllowed" exact="player.age - $_last ge 10s"/>
        <set_value name="$_broadcastAllowed" exact="player.age - $_last ge 30s"/>

        <set_value name="$hostiles" exact="$_detectedHostiles"/>
        <!-- IMPORTANT: $hostiles.count may include non-operational contacts (checkoperational="false").
             We want HostileCount to match the class breakdown we compute below, so we derive it from class counters. -->
        <set_value name="$hostileListCount" exact="$hostiles.count"/>
        <set_value name="$hostileCount" exact="0"/>

        <!-- Compute threat score and class breakdown (cheap: based on detected hostiles only) -->
        <set_value name="$threatScore" exact="0"/>
        <set_value name="$shipClass_XL" exact="0"/>
        <set_value name="$shipClass_L" exact="0"/>
        <set_value name="$shipClass_M" exact="0"/>
        <set_value name="$shipClass_S" exact="0"/>
        <set_value name="$factionCounts" exact="table[]"/>

        <do_all exact="$hostileListCount" counter="$i">
          <set_value name="$h" exact="$hostiles.{$i}"/>
          <do_if value="@$h.exists and @$h.isoperational">
            <do_if value="$h.isclass.ship_xl">
              <set_value name="$threatScore" exact="$threatScore + 5"/>
              <set_value name="$shipClass_XL" operation="add"/>
            </do_if>
            <do_elseif value="$h.isclass.ship_l">
              <set_value name="$threatScore" exact="$threatScore + 3"/>
              <set_value name="$shipClass_L" operation="add"/>
            </do_elseif>
            <do_elseif value="$h.isclass.ship_m">
              <set_value name="$threatScore" exact="$threatScore + 2"/>
              <set_value name="$shipClass_M" operation="add"/>
            </do_elseif>
            <do_else>
              <set_value name="$threatScore" exact="$threatScore + 1"/>
              <set_value name="$shipClass_S" operation="add"/>
            </do_else>

            <do_if value="@$h.owner != null">
              <set_value name="$f" exact="$h.owner"/>
              <set_value name="$factionCounts.{$f}" exact="@$factionCounts.{$f} + 1"/>
            </do_if>
          </do_if>
        </do_all>

        <!-- Make HostileCount match class counters -->
        <set_value name="$hostileCount" exact="$shipClass_XL + $shipClass_L + $shipClass_M + $shipClass_S"/>

        <!-- Determine primary faction -->
        <set_value name="$primaryFaction" exact="null"/>
        <set_value name="$maxFactionCount" exact="0"/>
        <do_all exact="$factionCounts.keys.count" counter="$fi">
          <set_value name="$f" exact="$factionCounts.keys.{$fi}"/>
          <do_if value="$factionCounts.{$f} gt $maxFactionCount">
            <set_value name="$primaryFaction" exact="$f"/>
            <set_value name="$maxFactionCount" exact="$factionCounts.{$f}"/>
          </do_if>
        </do_all>

        <!-- Convert score to threat level (1-5), matching GT_ThreatIntelligence receiver expectations -->
        <set_value name="$threatLevel" exact="2"/>
        <do_if value="$shipClass_XL gt 0 or $shipClass_L gt 0">
          <set_value name="$threatLevel" exact="4"/>
        </do_if>
        <do_elseif value="$threatScore ge 6">
          <set_value name="$threatLevel" exact="3"/>
        </do_elseif>

        <!-- Compare to configured threshold -->
        <set_value name="$threshold" exact="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold"/>
        <do_if value="not $threshold?">
          <set_value name="$threshold" exact="3"/>
        </do_if>

        <!-- Only Level 6+ pilots broadcast to fleet (matches ShipUnderAttack handler pattern) -->
        <do_if value="$pilotLevel ge 6">
          <do_if value="$hostileCount gt 0 and $_broadcastAllowed and $threatLevel ge $threshold">
            <!-- Broadcast to MD threat system (event-driven) -->
            <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
              $Sector = this.sector,
              $DetectedBy = this.ship,
              $HostileCount = $hostileCount,
              $PrimaryFaction = $primaryFaction,
              $ShipClass_XL = $shipClass_XL,
              $ShipClass_L = $shipClass_L,
              $ShipClass_M = $shipClass_M,
              $ShipClass_S = $shipClass_S,
              $ThreatScore = $threatScore,
              $Timestamp = player.age
            ]"/>
          </do_if>
        </do_if>

        <!-- Logging: emit whenever detection fires (hostiles detected), but respect shared log throttle -->
        <!-- Lower level pilots (1-5) can detect but don't broadcast - log for debugging -->
        <do_if value="$hostileCount gt 0 and $_logAllowed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="global.$GT_ThreatDetectThrottle.{this.ship}" exact="player.age"/>
          <set_value name="$_primaryFactionName" exact="if $primaryFaction? then @$primaryFaction.knownname else 'UNKNOWN'"/>
          <set_value name="$_broadcasted" exact="if ($pilotLevel ge 6 and $_broadcastAllowed and $threatLevel ge $threshold) then 'YES' else 'NO'"/>
          <set_value name="$_broadcastReason" exact="if $pilotLevel lt 6 then 'PILOT LEVEL TOO LOW (Lv.' + $pilotLevel + ', requires Lv.6+)' else if not $_broadcastAllowed then 'THROTTLED' else if $threatLevel lt $threshold then 'THREAT BELOW THRESHOLD' else 'OK'"/>
          <debug_text text="'[GT-Threat-Detect] ' + this.ship.idcode + ' (Pilot Lv.' + $pilotLevel + ') in ' + this.sector.knownname
            + ' - hostiles=' + $hostileCount
            + ' (XL=' + $shipClass_XL + ', L=' + $shipClass_L + ', M=' + $shipClass_M + ', S=' + $shipClass_S + ')'
            + ', threatScore=' + $threatScore + ', threatLevel=' + $threatLevel + ', threshold=' + $threshold
            + ', primaryFaction=' + $_primaryFactionName
            + ', broadcasted=' + $_broadcasted + ' (' + $_broadcastReason + ')'" chance="100"/>
        </do_if>
      </actions>
    </handler>
    
    <!-- Subordinate Resync Handler: Listen for commander order changes (like vanilla order.assist) -->
    <handler comment="Subordinate resync on commander order change">
      <conditions>
        <check_all>
          <event_object_order_ready object="this.ship.commander" check="false" comment="Commander's order ready"/>
          <check_value value="event.param == event.object.defaultorder" comment="It's the default order"/>
        </check_all>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Commander order changed - restarting to resync settings'" chance="100"/>
        </do_if>
        <!-- Use abort_called_scripts like vanilla - forcefully restart at init label -->
        <abort_called_scripts resume="init"/>
      </actions>
    </handler>
    
    <!-- Commander change detection handler -->
    <!-- Tests if commander change detection interferes with trade execution -->
    <!-- This handler fires BEFORE the subordinate resync handler restarts the script -->
    <!-- Using this.assignedcontrolled like vanilla order.assist.xml -->
    <handler comment="Commander removed or changed">
      <conditions>
        <event_object_commander_set object="this.assignedcontrolled"/>
      </conditions>
      <actions>
        <set_value name="$newCommander" exact="event.param"/>
        
        <!-- Update state machine BEFORE script restarts -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and (@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (commander: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <!-- NOTE: Script will restart via subordinate resync handler if commander has order change -->
        <!-- But signal is sent FIRST, so state manager can process it -->
      </actions>
    </handler>
    
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Complete'"/>
      </conditions>
      <actions>
        <set_value name="$completionData" exact="event.param2"/>
        <set_value name="$completedLevel" exact="$completionData.$Level"/>
        
        <!-- Ignore spurious early-complete (Level 0) while academy or MD timer still active -->
        <set_value name="$shouldResumeTrading" exact="true"/>
        <do_if value="$completedLevel? and $completedLevel le 0">
          <set_value name="$shouldResumeTrading" exact="false"/>
        </do_if>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
        </do_if>
        
        <do_if value="$shouldResumeTrading">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training completed for level ' + $completedLevel + ' - setting flag to resume trading'" chance="100"/>
        </do_if>
        
        <!-- Set flag to resume trading (can't use resume in interrupt handler) -->
        <set_value name="this.$training_complete" exact="true"/>
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$training_order_created"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ignoring spurious training-complete signal (level=' + $completedLevel + ', academy/timer still active)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Failed'"/>
      </conditions>
      <actions>
        <set_value name="$failureData" exact="event.param2"/>
        <set_value name="$reason" exact="$failureData.$Reason"/>
        
        <!-- Do not resume trading while pilot is still blocked or academy course active -->
        <set_value name="$shouldResumeTrading" exact="true"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
        </do_if>
        
        <do_if value="$shouldResumeTrading">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training failed: ' + $reason + ' - setting flag to resume trading'" chance="100"/>
        </do_if>
        
        <!-- Set flag to resume trading (can't use resume in interrupt handler) -->
        <set_value name="this.$training_complete" exact="true"/>
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$training_order_created"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training failed (' + $reason + ') but pilot still blocked - not resuming trading'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <!-- Order cancellation detection handler -->
    <!-- Detects when GT default order is cancelled -->
    <!-- Note: Ships always have a default order (Wait, Assist, etc.), so we check:
         1. If cancelled order was GT order (event.param.id == 'GalaxyTraderMK3')
         2. If ship is still GT-controlled (direct GT order OR subordinate with GT commander via Assist)
         3. Only act if ship is no longer GT-controlled -->
    <handler comment="GT order cancelled">
      <conditions>
        <event_object_order_cancelled object="this.ship" immediate="true"/>
        <!-- Note: Ships always have a default order (Wait, Assist, etc.), so we check the cancelled order ID and current default order -->
      </conditions>
      <actions>
        <!-- Check which order was cancelled -->
        <set_value name="$cancelledOrderId" exact="@event.param.id"/>
        <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <!-- Unified GT order status check (inline for AI scripts) -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <set_value name="$hasGTCommander" exact="false"/>
        <set_value name="$isGTControlled" exact="false"/>
        
        <!-- Check direct GT order -->
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3'">
          <set_value name="$hasDirectGTOrder" exact="true"/>
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
        
        <!-- Check commander status -->
        <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$hasGTCommander" exact="true"/>
            <do_if value="$currentDefaultOrder == 'Assist'">
              <set_value name="$isGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Only act if GT order was actually cancelled (ship is no longer GT-controlled) -->
        <do_if value="not $isGTControlled">
          <!-- Check if GT order was explicitly cancelled OR if current default is not GT/Assist-with-GT-commander -->
          <do_if value="$cancelledOrderId == 'GalaxyTraderMK3' or not $cancelledOrderId">
            <!-- GT order is being cancelled â†’ send Phase 7 signal -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (interrupt handler, cancelled order: ' + (if $cancelledOrderId then $cancelledOrderId else 'NONE') + ', current default: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isGTControlled + ')'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
            
            <!-- EVENT-DRIVEN: Trigger orphaned ship check -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
              <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
            </do_if>
            
            <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
            <do_if value="not $hasDirectGTOrder and not $hasGTCommander and this.ship.pilot?">
              <set_value name="$originalName" exact="null"/>
              <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
              </do_if>
              
              <do_if value="$originalName">
                <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                  $Ship = this.ship,
                  $Pilot = this.ship.pilot,
                  $Reason = 'GT order cancelled - restoring original name',
                  $OriginalName = $originalName
                ]"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Ship is still GT-controlled (direct GT order or subordinate with GT commander) - skip -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Order cancelled interrupt fired but ship still GT-controlled (cancelled: ' + (if $cancelledOrderId then $cancelledOrderId else 'NONE') + ', current default: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isGTControlled + ') - skipping Phase 7'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>

  </interrupts>
  
  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_command command="command.searchtrades"/>
    <set_command_action commandaction="commandaction.searchingtrades"/>

    <!-- Vanilla parity: clean up stale temporary ship accounts when no tradeorders exist.
         Prevents clamp_trade_amount false buyer_money on ships left with orphan temp accounts. -->
    <do_if value="this.ship.hasownaccount and not this.ship.tradeorders.count">
      <remove_object_account object="this.ship" transfer="true"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale ship account before trading init (no active tradeorders)'" chance="100"/>
      </do_if>
    </do_if>

    <!-- CRITICAL: Ensure instance wait time storage ALWAYS exists before any <wait ...> evaluates it.
         Vanilla pattern: instance vars are accessed with safe operator @this.$var (e.g. @this.$resupplier...). -->
    <!-- Purpose A: Pre-request wait for GT_Trade_Found signal (milliseconds) -->
    <set_value name="this.$tradeFoundSignalWaitTime" exact="5ms"/>
    <!-- Purpose B: No-trade retry cooldown (seconds) -->
    <set_value name="this.$retryCooldown" exact="10s"/>
    
    <!-- Legacy persistent variables removed - no longer needed with unified maintenance system -->
    
    <!-- ============================================================================= -->
    <!-- SAVE GAME CLEANUP: Clear stale tracking data when loading from a save game  -->
    <!-- ============================================================================= -->
    <!-- Check if resupply tracking exists and verify if the order is still active.   -->
    <!-- Only remove tracking if the order no longer exists (stale data).             -->
    <!-- ============================================================================= -->
    <!-- PERFORMANCE: Optimized resupply order check - use order.id property instead of iterating all orders -->
    <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
      <!-- Check if ship has active resupply/repair/equipment order using order.id (more efficient than iterating) -->
      <set_value name="$hasActiveResupplyOrder" exact="false"/>
      <!-- Our resupply uses order.build.equip, whose order id is 'Equip' (vanilla) -->
      <do_if value="this.ship.order? and (this.ship.order.id == 'Resupply' or this.ship.order.id == 'Repair' or this.ship.order.id == 'Equip')">
        <set_value name="$hasActiveResupplyOrder" exact="true"/>
      </do_if>
      
      <do_if value="not $hasActiveResupplyOrder">
        <!-- No active order - tracking is stale, remove it -->
        <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale resupply tracking (no active order)'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- Order still active - keep tracking -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resupply order still active after save load - keeping tracking'" chance="100"/>
        </do_if>
      </do_else>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- MODULAR INITIALIZATION - REPLACES ~200 LINES OF COMPLEX INITIALIZATION CODE -->
    <!-- ============================================================================= -->
    
    <!-- CRITICAL DEBUG: Log that init block started -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === INIT BLOCK STARTED === (Ship: ' + this.ship.knownname + ', Pilot: ' + (if this.ship.pilot then this.ship.pilot.name else 'NONE') + ')'" chance="100"/>
    </do_if>
    
    <!-- Create order parameters table for library compatibility -->
    <set_value name="$orderParams" exact="table[]"/>
    
    <!-- Legacy maintenance variables removed - no longer needed with unified maintenance system -->
    
    <!-- SUBORDINATE HOME BASE INHERITANCE: If subordinate, ALWAYS inherit commander's home -->
    <set_value name="$effectiveHome" exact="$home"/>
    <do_if value="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship">
      <!-- Ship is a subordinate - ALWAYS inherit commander's home sector -->
      <do_if value="this.ship.commander.defaultorder and this.ship.commander.defaultorder.$home?">
        <set_value name="$effectiveHome" exact="this.ship.commander.defaultorder.$home"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting home base from commander ' + this.ship.commander.idcode + ': ' + $effectiveHome.knownname" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    
    <!-- Store as script variable for persistence throughout execution -->
    <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
    
    <!-- ============================================================================= -->
    <!-- STATION ASSIGNMENT: If home is a station, assign ship as station subordinate -->
    <!-- The lib.request.orders.xml patch protects the GT order from being overwritten -->
    <!-- The gt_subordinate_access.lua hook keeps order params editable in the UI -->
    <!-- ============================================================================= -->
    <do_if value="this.$effectiveHome.isclass.station">
      <!-- Home is a station â€” assign only if ship is top-level or already station-assigned.
           Ship-subordinates must remain under their ship commander. -->
      <do_if value="(not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and this.ship.commander != this.$effectiveHome">
        <!-- Unassign from old commander first (if any) -->
        <do_if value="this.ship.commander.exists and this.ship.commander != this.ship">
          <remove_object_commander object="this.ship"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Removed old commander before station assignment'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Assign to station as trade subordinate -->
        <set_object_commander object="this.ship" commander="this.$effectiveHome" assignment="assignment.trade"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Assigned to station ' + this.$effectiveHome.knownname + ' as trade subordinate'" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    <do_elseif value="this.$effectiveHome.isclass.sector">
      <!-- Home is a sector â€” unassign from any station if previously assigned -->
      <do_if value="this.ship.commander.exists and this.ship.commander.isclass.station">
        <remove_object_commander object="this.ship"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Removed station assignment â€” home changed to sector ' + this.$effectiveHome.knownname" chance="100"/>
        </do_if>
      </do_if>
    </do_elseif>
    
    <!-- ============================================================================= -->
    <!-- SUBORDINATE SETTINGS INHERITANCE: Inherit strategic settings from commander -->
    <!-- Note: excludes station commanders â€” only ship-to-ship subordinates inherit -->
    <!-- ============================================================================= -->
    <set_value name="$isSubordinate" exact="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station"/>
    <set_value name="$commanderOrder" exact="null"/>
    <do_if value="$isSubordinate">
      <set_value name="$commanderOrder" exact="this.ship.commander.defaultorder"/>
    </do_if>
    
    <!-- Sector Whitelist -->
    <set_value name="$effectiveSectorWhitelist" exact="$sectorwhitelist"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$sectorwhitelist?">
      <set_value name="$effectiveSectorWhitelist" exact="$commanderOrder.$sectorwhitelist"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting sector whitelist from commander ' + this.ship.commander.idcode" chance="100"/>
        </do_if>
    </do_if>

    <!-- Blocked Stations -->
    <set_value name="$effectiveBlockedStations" exact="if $blockedstations? then $blockedstations else []"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$blockedstations?">
      <set_value name="$effectiveBlockedStations" exact="$commanderOrder.$blockedstations"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting blocked station list from commander ' + this.ship.commander.idcode" chance="100"/>
        </do_if>
    </do_if>
    
    <!-- Fleet Coordination -->
    <set_value name="$effectiveFleetCoordination" exact="$fleetcoordination"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$fleetcoordination?">
      <set_value name="$effectiveFleetCoordination" exact="$commanderOrder.$fleetcoordination"/>
    </do_if>
    
    <!-- Allow Illegal Wares -->
    <set_value name="$effectiveAllowIllegal" exact="$allowillegal"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$allowillegal?">
      <set_value name="$effectiveAllowIllegal" exact="$commanderOrder.$allowillegal"/>
    </do_if>
    
    <!-- Illegal Route Filter -->
    <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$enforceRouteIllegalLegality?">
      <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$commanderOrder.$enforceRouteIllegalLegality"/>
    </do_if>
    
    <!-- Ignore Carrier/Aux -->
    <!-- Initialize with safe default first to prevent property lookup errors -->
    <set_value name="$effectiveIgnoreCarrierAux" exact="false"/>
    <do_if value="$ignorecarrieraux?">
      <set_value name="$effectiveIgnoreCarrierAux" exact="$ignorecarrieraux"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignorecarrieraux?">
      <set_value name="$effectiveIgnoreCarrierAux" exact="$commanderOrder.$ignorecarrieraux"/>
    </do_if>
    
    <!-- Ignore Build Storage -->
    <!-- Initialize with safe default first to prevent property lookup errors -->
    <set_value name="$effectiveIgnoreBuildStorage" exact="false"/>
    <do_if value="$ignorebuildstorage?">
      <set_value name="$effectiveIgnoreBuildStorage" exact="$ignorebuildstorage"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignorebuildstorage?">
      <set_value name="$effectiveIgnoreBuildStorage" exact="$commanderOrder.$ignorebuildstorage"/>
    </do_if>

    <!-- Ignore Trade Rules -->
    <!-- Initialize with safe default first to prevent property lookup errors -->
    <set_value name="$effectiveIgnoreTradeRules" exact="false"/>
    <do_if value="$ignoretraderules?">
      <set_value name="$effectiveIgnoreTradeRules" exact="$ignoretraderules"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoretraderules?">
      <set_value name="$effectiveIgnoreTradeRules" exact="$commanderOrder.$ignoretraderules"/>
    </do_if>
    
    <!-- Ignore MK1-Supplied Stations -->
    <set_value name="$effectiveIgnoreMK1Supply" exact="true"/>
    <do_if value="$ignoremk1supply?">
      <set_value name="$effectiveIgnoreMK1Supply" exact="$ignoremk1supply"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoremk1supply?">
      <set_value name="$effectiveIgnoreMK1Supply" exact="$commanderOrder.$ignoremk1supply"/>
    </do_if>

    <!-- Idle Parking -->
    <set_value name="$effectiveIdleParking" exact="false"/>
    <do_if value="$idleParking?">
      <set_value name="$effectiveIdleParking" exact="$idleParking"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$idleParking?">
      <set_value name="$effectiveIdleParking" exact="$commanderOrder.$idleParking"/>
    </do_if>

    <!-- Ignore Player Pricing (MK3): always buy from player-owned stations regardless of their
         player-set sell prices, and restrict the ship to selling only to NPC buyers. -->
    <set_value name="$effectiveIgnorePlayerPricing" exact="false"/>
    <do_if value="$ignoreplayerpricing?">
      <set_value name="$effectiveIgnorePlayerPricing" exact="$ignoreplayerpricing"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoreplayerpricing?">
      <set_value name="$effectiveIgnorePlayerPricing" exact="$commanderOrder.$ignoreplayerpricing"/>
    </do_if>
    
    <!-- Faction Priority (bool checkbox â†’ numeric: true=1 boost player stations, false=0 equal) -->
    <!-- Backward compat: old saves may have numeric 0/1/2; normalize to bool then to numeric -->
    <set_value name="$effectiveFactionPriority" exact="if $factionpriority then 1 else 0"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$factionpriority?">
      <set_value name="$effectiveFactionPriority" exact="if $commanderOrder.$factionpriority then 1 else 0"/>
    </do_if>
    
    <!-- Auto Wares -->
    <set_value name="$effectiveAutoWares" exact="$autowares"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$autowares?">
      <set_value name="$effectiveAutoWares" exact="$commanderOrder.$autowares"/>
    </do_if>
    
    <!-- Ware Basket -->
    <set_value name="$effectiveWareBasket" exact="$warebasket"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$warebasket?">
      <set_value name="$effectiveWareBasket" exact="$commanderOrder.$warebasket"/>
    </do_if>
    
    <!-- Distance Penalty -->
    <set_value name="$effectiveDistancePenalty" exact="$distancepenalty"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$distancepenalty?">
      <set_value name="$effectiveDistancePenalty" exact="$commanderOrder.$distancepenalty"/>
    </do_if>
    
    <!-- Priority Wares (MK3) - wares to boost in trade scoring -->
    <set_value name="$effectivePriorityWares" exact="if $prioritywares? then $prioritywares else []"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$prioritywares?">
      <set_value name="$effectivePriorityWares" exact="$commanderOrder.$prioritywares"/>
    </do_if>
    
    <!-- Priority Score Multiplier (MK3) - applied last in scoring; 100=normal, 150=+50%%, 200=2x -->
    <set_value name="$effectivePriorityScoreMultiplier" exact="if $priorityscoremultiplier? then $priorityscoremultiplier else 125"/>
    <do_if value="$effectivePriorityScoreMultiplier lt 125"><set_value name="$effectivePriorityScoreMultiplier" exact="125"/></do_if>
    <do_if value="$effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$priorityscoremultiplier?">
      <set_value name="$effectivePriorityScoreMultiplier" exact="[$commanderOrder.$priorityscoremultiplier, 125].max"/>
      <do_if value="$effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
    </do_if>
    
    <!-- Logbook Entries -->
    <set_value name="$effectiveLogbookEntries" exact="$logbookentries"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$logbookentries?">
      <set_value name="$effectiveLogbookEntries" exact="$commanderOrder.$logbookentries"/>
    </do_if>
    
    <!-- Notifications -->
    <set_value name="$effectiveNotifications" exact="$notifications"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$notifications?">
      <set_value name="$effectiveNotifications" exact="$commanderOrder.$notifications"/>
    </do_if>

    <!-- Minimum Cargo Utilization (%) -->
    <set_value name="$effectiveCargoTarget" exact="$cargotarget"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$cargotarget?">
      <set_value name="$effectiveCargoTarget" exact="$commanderOrder.$cargotarget"/>
    </do_if>
    
    <!-- Debug Level -->
    <set_value name="$effectiveDebugLevel" exact="$debuglevel"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$debuglevel?">
      <set_value name="$effectiveDebugLevel" exact="$commanderOrder.$debuglevel"/>
    </do_if>
    
    <!-- Trade Evaluation Logging -->
    <set_value name="$effectiveTradeEval" exact="$tradeeval"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$tradeeval?">
      <set_value name="$effectiveTradeEval" exact="$commanderOrder.$tradeeval"/>
    </do_if>
    
    <!-- PERFORMANCE: Calculate pilot skill once and reuse for both MaxBuy and MaxSell -->
    <!-- Calculate subordinate's pilot capability (only if subordinate) -->
    <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
    <set_value name="$pilotMaxJumps" exact="null"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <set_value name="$pilotSkill" exact="if $useVanillaXPOnly then (if this.ship.pilot? and this.ship.pilot.skill.piloting? then this.ship.pilot.skill.piloting else null) else (if this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level? then global.$GT_Pilots.{this.ship.pilot}.$Level else null)"/>
      <!-- <init> context does not allow run_script for max-jump map; keep local mapping here. -->
      <do_if value="not $useVanillaXPOnly and $pilotSkill != null">
        <do_if value="$pilotSkill le 2"><set_value name="$pilotMaxJumps" exact="1"/></do_if>
        <do_elseif value="$pilotSkill le 5"><set_value name="$pilotMaxJumps" exact="3"/></do_elseif>
        <do_elseif value="$pilotSkill le 8"><set_value name="$pilotMaxJumps" exact="5"/></do_elseif>
        <do_elseif value="$pilotSkill le 11"><set_value name="$pilotMaxJumps" exact="10"/></do_elseif>
        <do_elseif value="$pilotSkill le 13"><set_value name="$pilotMaxJumps" exact="15"/></do_elseif>
        <do_else><set_value name="$pilotMaxJumps" exact="25"/></do_else>
      </do_if>
    </do_if>
    
    <!-- Max Buy Distance - Inherit from commander, capped at pilot capability -->
    <set_value name="$effectiveMaxBuy" exact="$maxbuy"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$maxbuy?">
      <set_value name="$commanderMaxBuy" exact="$commanderOrder.$maxbuy"/>
      <do_if value="$useVanillaXPOnly or $pilotMaxJumps == null">
        <set_value name="$effectiveMaxBuy" exact="$commanderMaxBuy"/>
      </do_if>
      <do_else>
        <set_value name="$effectiveMaxBuy" exact="[$commanderMaxBuy, $pilotMaxJumps].min"/>
      </do_else>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MaxBuy inherited: commander=' + $commanderMaxBuy + ', pilot_cap=' + (if $pilotMaxJumps != null then $pilotMaxJumps else 'none') + ', vanilla_mode=' + $useVanillaXPOnly + ', effective=' + $effectiveMaxBuy" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Max Sell Distance - Inherit from commander, capped at pilot capability -->
    <set_value name="$effectiveMaxSell" exact="$maxsell"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$maxsell?">
      <set_value name="$commanderMaxSell" exact="$commanderOrder.$maxsell"/>
      <do_if value="$useVanillaXPOnly or $pilotMaxJumps == null">
        <set_value name="$effectiveMaxSell" exact="$commanderMaxSell"/>
      </do_if>
      <do_else>
        <set_value name="$effectiveMaxSell" exact="[$commanderMaxSell, $pilotMaxJumps].min"/>
      </do_else>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MaxSell inherited: commander=' + $commanderMaxSell + ', pilot_cap=' + (if $pilotMaxJumps != null then $pilotMaxJumps else 'none') + ', vanilla_mode=' + $useVanillaXPOnly + ', effective=' + $effectiveMaxSell" chance="100"/>
      </do_if>
    </do_if>

    <!-- Persist effective settings on the order instance so they survive save/load resume -->
    <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
    <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
    <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
    <set_value name="this.$effectiveIgnorePlayerPricing" exact="$effectiveIgnorePlayerPricing"/>
    <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
    <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
    <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
    <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
    <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
    <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
    <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
    <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
    <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
    <set_value name="this.$effectivePriorityWares" exact="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
    <set_value name="this.$effectivePriorityScoreMultiplier" exact="$effectivePriorityScoreMultiplier"/>
    <set_value name="this.$effectiveBlockedStations" exact="if $effectiveBlockedStations? then $effectiveBlockedStations else []"/>
    <set_value name="this.$effectiveIdleParking" exact="$effectiveIdleParking"/>
    
    <!-- Debug message for subordinates showing inherited settings -->
    <!-- PERFORMANCE: Only build inherited settings string if debug logging is enabled -->
    <!-- Skip expensive string concatenation loop if not needed -->
    <do_if value="$isSubordinate and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$inheritedSettings" exact="[]"/>
      <do_if value="$effectiveFleetCoordination != $fleetcoordination"><append_to_list name="$inheritedSettings" exact="'FleetCoord=' + $effectiveFleetCoordination"/></do_if>
      <do_if value="$effectiveAllowIllegal != $allowillegal"><append_to_list name="$inheritedSettings" exact="'AllowIllegal=' + $effectiveAllowIllegal"/></do_if>
      <do_if value="$effectiveEnforceRouteIllegalLegality != $enforceRouteIllegalLegality"><append_to_list name="$inheritedSettings" exact="'IllegalRouteFilter=' + $effectiveEnforceRouteIllegalLegality"/></do_if>
      <do_if value="$effectiveFactionPriority != $factionpriority"><append_to_list name="$inheritedSettings" exact="'FactionPri=' + $effectiveFactionPriority"/></do_if>
      <do_if value="$effectiveAutoWares != $autowares"><append_to_list name="$inheritedSettings" exact="'AutoWares=' + $effectiveAutoWares"/></do_if>
      <do_if value="$effectiveDistancePenalty != $distancepenalty"><append_to_list name="$inheritedSettings" exact="'DistPenalty=' + $effectiveDistancePenalty + '%'"/></do_if>
      <do_if value="$effectiveLogbookEntries != $logbookentries"><append_to_list name="$inheritedSettings" exact="'Logbook=' + $effectiveLogbookEntries"/></do_if>
      <do_if value="$effectiveNotifications != $notifications"><append_to_list name="$inheritedSettings" exact="'Notify=' + $effectiveNotifications"/></do_if>
      <do_if value="$effectiveCargoTarget != $cargotarget"><append_to_list name="$inheritedSettings" exact="'MinCargoUtil=' + $effectiveCargoTarget + '%'"/></do_if>
      <do_if value="$effectiveDebugLevel != $debuglevel"><append_to_list name="$inheritedSettings" exact="'Debug=' + $effectiveDebugLevel"/></do_if>
      <do_if value="$effectiveTradeEval != $tradeeval"><append_to_list name="$inheritedSettings" exact="'TradeEval=' + $effectiveTradeEval"/></do_if>
      <do_if value="$effectiveMaxBuy != $maxbuy"><append_to_list name="$inheritedSettings" exact="'MaxBuy=' + $effectiveMaxBuy + 'j'"/></do_if>
      <do_if value="$effectiveMaxSell != $maxsell"><append_to_list name="$inheritedSettings" exact="'MaxSell=' + $effectiveMaxSell + 'j'"/></do_if>
      
      <do_if value="$inheritedSettings.count gt 0">
        <set_value name="$inheritedSettingsText" exact="''"/>
        <do_all exact="$inheritedSettings.count" counter="$i">
          <set_value name="$inheritedSettingsText" exact="$inheritedSettingsText + $inheritedSettings.{$i}"/>
          <do_if value="$i lt $inheritedSettings.count">
            <set_value name="$inheritedSettingsText" exact="$inheritedSettingsText + ', '"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inherited settings from ' + this.ship.commander.idcode + ': ' + $inheritedSettingsText" chance="100"/>
      </do_if>
    </do_if>
    
    <set_value name="$orderParams.$home" exact="$effectiveHome"/>
    <set_value name="$orderParams.$maxbuy" exact="$effectiveMaxBuy"/>
    <set_value name="$orderParams.$maxsell" exact="$effectiveMaxSell"/>
    <set_value name="$orderParams.$allowillegal" exact="$effectiveAllowIllegal"/>
    <set_value name="$orderParams.$enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="$orderParams.$factionpriority" exact="$effectiveFactionPriority"/>
    <set_value name="$orderParams.$autowares" exact="$effectiveAutoWares"/>
    <set_value name="$orderParams.$warebasket" exact="$effectiveWareBasket"/>
    <set_value name="$orderParams.$prioritywares" exact="$effectivePriorityWares"/>
    <set_value name="$orderParams.$priorityscoremultiplier" exact="$effectivePriorityScoreMultiplier"/>
    <set_value name="$orderParams.$distancepenalty" exact="$effectiveDistancePenalty"/>
    <set_value name="$orderParams.$notifications" exact="$effectiveNotifications"/>
    <set_value name="$orderParams.$cargotarget" exact="$effectiveCargoTarget"/>
    <set_value name="$orderParams.$marketupdatefreq" exact="$marketupdatefreq"/>
    <set_value name="$orderParams.$debuglevel" exact="$effectiveDebugLevel"/>
    <set_value name="$orderParams.$tradeeval" exact="$effectiveTradeEval"/>
    <set_value name="$orderParams.$fleetcoordination" exact="$effectiveFleetCoordination"/>
    <set_value name="$orderParams.$logbookentries" exact="$effectiveLogbookEntries"/>
    <set_value name="$orderParams.$sectorwhitelist" exact="$effectiveSectorWhitelist"/>
    <set_value name="$orderParams.$blockedstations" exact="$effectiveBlockedStations"/>
    
    <!-- =========================================== -->
    <!-- HIGH-PERFORMANCE INITIALIZATION (Option A) -->
    <!-- =========================================== -->
    
    <!-- Fast variable assignment - using effective (inherited) values -->
    <set_value name="$gt_debuglevel" exact="$effectiveDebugLevel"/>
    <!-- Only set debugchance > 0 if GT debug logging is enabled globally -->
    <set_value name="$debugchance" exact="0"/>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$debugchance" exact="if $gt_debuglevel ge 2 then 100 else if $gt_debuglevel ge 1 then 50 else 0"/>
    </do_if>
    <set_value name="this.$debugchance" exact="$debugchance"/>
    
    <!-- Cache blacklistgroup once (avoids 6 repeated lookups) -->
    <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
    <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
      <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
    </do_if>
    
    <!-- Core trading parameters (performance optimized) - using effective (inherited) values -->
    <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
    <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="$gt_factionpriority" exact="$effectiveFactionPriority"/>
    <!-- Convert distance penalty from 0-100% to multiplier: 0%=0.0, 50%=1.0, 100%=2.0 -->
    <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
    <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
    <set_value name="this.$gt_cargotarget" exact="$gt_cargotarget"/>
    <set_value name="$gt_marketupdatefreq" exact="$marketupdatefreq"/>
    <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
    
    <!-- Global defaults (fastest approach - direct assignment) -->
    <set_value name="$gt_autotraining" exact="true"/>
    <set_value name="$gt_fleetcoord" exact="false"/>
    
    <!-- Ware selection (optimized) - using effective inherited values -->
    <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>
    
    <!-- Single non-blocking signal to MD system -->
    <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
      $Ship = this.ship,
      $Config = table[
        $allowillegal = $gt_allowillegal,
        $debuglevel = $gt_debuglevel,
        $autotraining = $gt_autotraining
      ]
    ]"/>
    <set_value name="$initHomeSector" exact="if $effectiveHome? and $effectiveHome.isclass.sector then $effectiveHome else (if $effectiveHome? and $effectiveHome.sector? then @$effectiveHome.sector else null)"/>
    <signal_objects object="player.galaxy" param="'GT_HomeFleetProfile_Update'" param2="table[$Ship = this.ship, $HomeSector = $initHomeSector]"/>
    <set_value name="$initFpHomeName" exact="if $initHomeSector? and $initHomeSector.knownname? then @$initHomeSector.knownname else '?'"/>
    <set_value name="this.$trackedFleetProfileSig" exact="'H=' + $initFpHomeName + '|CT=' + $gt_cargotarget"/>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': High-performance initialization complete'" chance="@this.$debugchance"/>
      <do_if value="@$effectiveHome.exists">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Operating with home base: ' + @$effectiveHome.knownname + ' (maxbuy=' + $effectiveMaxBuy + ', maxsell=' + $effectiveMaxSell + ')'" chance="@this.$debugchance"/>
      </do_if>
    </do_if>
    
    <!-- Log configuration summary -->
    <do_if value="$gt_debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === CONFIGURATION SUMMARY ==='" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Illegal=' + $effectiveAllowIllegal + ', IllegalRouteFilter=' + $effectiveEnforceRouteIllegalLegality + ', DistancePenalty=' + $effectiveDistancePenalty + '%'" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FleetCoord=' + $effectiveFleetCoordination + ', LogbookEntries=' + $effectiveLogbookEntries + ', Notifications=' + $effectiveNotifications" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Distance limits: MaxBuy=' + $effectiveMaxBuy + ' jumps, MaxSell=' + $effectiveMaxSell + ' jumps'" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': AutoWares=' + $effectiveAutoWares + ', WareBasket=' + $effectiveWareBasket.count + ' wares, TradeEval=' + $effectiveTradeEval" chance="100"/>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- END MODULAR INITIALIZATION                                                   -->
    <!-- ============================================================================= -->
    
    <!-- Initialize pilot tracking for event-driven pilot change detection -->
    <!-- Pilot changes are detected at natural restart points: -->
    <!-- - After successful trade completion (trade_completed label) -->
    <!-- - On script restart (init label) -->
    <set_value name="this.$trackedPilot" exact="this.ship.pilot"/>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Tracking pilot: ' + @this.$trackedPilot.name + ' (event-driven detection enabled)'" chance="@this.$debugchance"/>
    </do_if>
    
    <!-- Do not initialize commander tracking here - let init label handle it -->
    <!-- This prevents false positives when script restarts after commander assignment -->
    <!-- The init label will detect changes by comparing with previous value -->
    
    <!-- Register pilot on first run (for initial assignment or ship with existing cargo) -->
    <!-- This ensures ships get renamed even when first assigned to GT order -->
    <do_if value="this.ship.pilot">
      <!-- NOTE: Cannot use wait/do_while in init block - pilot transfer check moved to main loop -->
      <!-- Pilot transfer takes time (crew transfer pod travel), but UI shows pilot as assigned immediately -->
      <!-- Main loop will check if pilot is actually on ship before proceeding -->
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INITIAL REGISTRATION: Registering pilot ' + @this.ship.pilot.name + ' on order start'" chance="100"/>
      </do_if>
      <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
        $updateType = 'pilot_change',
        $Ship = this.ship,
        $pilot = this.ship.pilot,
        $oldPilot = null
      ]"/>
      
      <!-- NOTE: Cannot use wait in init block - registration check will happen in main loop -->
      <!-- Registration happens synchronously via run_actions, but signal processing is asynchronous -->
      <!-- Main loop will check registration status before requesting trade search -->
    </do_if>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GalaxyTrader MK3] ' + this.ship.idcode + ': === INITIALIZATION COMPLETE === Starting main trading loop...'" chance="100"/>
    </do_if>
    
  </init>

  <!-- =================================================================== -->
  <!-- Save-game compatibility patches                                      -->
  <!-- =================================================================== -->
  <!-- Script bumped to version="4" when $ignoreplayerpricing was added.
       The per-<param> patch above backfills the PARAM value for legacy
       (v1/v2/v3) orders, but the corresponding this.$effectiveIgnorePlayerPricing
       INSTANCE variable is populated from <init>, and <init> does NOT re-run
       on save load. Without this patch, the attention-block rehydration guard
       would still run and resolve to false, but any code path that reads the
       instance var directly before the first rehydration pass would throw.
       Mirrors the order.trade.galaxyminer.xml v1->v2 pattern. -->
  <patch sinceversion="4">
    <do_if value="not $ignoreplayerpricing?">
      <set_value name="$ignoreplayerpricing" exact="false"/>
    </do_if>
    <do_if value="not this.$effectiveIgnorePlayerPricing?">
      <set_value name="this.$effectiveIgnorePlayerPricing" exact="$ignoreplayerpricing"/>
    </do_if>
    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': v3->v4 patch applied (ignoreplayerpricing=' + this.$effectiveIgnorePlayerPricing + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="5">
    <do_if value="not $blockedstations?">
      <set_value name="$blockedstations" exact="[]"/>
    </do_if>
    <do_if value="not this.$effectiveBlockedStations?">
      <set_value name="this.$effectiveBlockedStations" exact="$blockedstations"/>
    </do_if>
    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': v4->v5 patch applied (blockedstations=' + this.$effectiveBlockedStations.count + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="6">
    <do_if value="not $idleParking?">
      <set_value name="$idleParking" exact="false"/>
    </do_if>
    <set_value name="this.$effectiveIdleParking" exact="$idleParking"/>
    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': v5->v6 patch applied (idleParking=' + this.$effectiveIdleParking + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="7">
    <do_if value="not $autoJumpDistanceByLevel?">
      <set_value name="$autoJumpDistanceByLevel" exact="false"/>
    </do_if>
    <set_value name="this.$prevAutoJumpDistance" exact="$autoJumpDistanceByLevel"/>
    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': v6->v7 patch applied (autoJumpDistanceByLevel=' + $autoJumpDistanceByLevel + ')'" filter="savegame"/>
  </patch>

  <attention min="unknown">
    <actions>
      
      <!-- Debug: Confirm we entered attention block -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === ATTENTION BLOCK ENTERED ==='" chance="100"/>
      </do_if>
      
      <!-- Subordinate reinitialization: Jump here to restart and re-inherit commander settings -->
      <label name="init"/>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <!-- CRITICAL: Ensure instance wait time storage ALWAYS exists on restarts/resumes. -->
      <!-- Purpose A: Pre-request wait for GT_Trade_Found signal (milliseconds) -->
      <set_value name="this.$tradeFoundSignalWaitTime" exact="5ms"/>
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <set_value name="this.$retryCooldown" exact="10s"/>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (Script Restart) -->
      <!-- ======================================= -->
      <!-- Check for pilot changes when script restarts (natural restart point) -->
      <set_value name="$currentPilot" exact="@this.ship.pilot"/>
      <do_if value="this.$trackedPilot? and $currentPilot != this.$trackedPilot">
        <!-- Pilot changed! Send signal to MD system -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PILOT CHANGE DETECTED on script restart! Old: ' + @this.$trackedPilot.name + ', New: ' + @$currentPilot.name" chance="100"/>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
          $updateType = 'pilot_change',
          $Ship = this.ship,
          $pilot = $currentPilot,
          $oldPilot = this.$trackedPilot
        ]"/>
      </do_if>
      <!-- Update tracked pilot (always, even if no change) -->
      <set_value name="this.$trackedPilot" exact="$currentPilot"/>
      
      <!-- CRITICAL: Check if pilot is missing (pilot was transferred away) -->
      <!-- If GT order is running but ship has no pilot, cleanup and self-cancel -->
      <do_if value="not $currentPilot">
        <!-- Vanilla transfer pods can take minutes; if a paused GT pilot is already linked to this
             ship id, keep the GT order alive briefly until the pilot physically arrives. -->
        <set_value name="$pendingTransferredPilot" exact="false"/>
        <set_value name="$pendingPilotName" exact="'NONE'"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$pk">
            <set_value name="$candidatePilot" exact="$pilotKeys.{$pk}"/>
            <do_if value="$candidatePilot and global.$GT_Pilots.{$candidatePilot}? and global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == this.ship.idcode and global.$GT_Pilots.{$candidatePilot}.$Status? and global.$GT_Pilots.{$candidatePilot}.$Status == 'paused'">
              <set_value name="$pendingTransferredPilot" exact="true"/>
              <set_value name="$pendingPilotName" exact="if $candidatePilot.name? then $candidatePilot.name else 'UNKNOWN'"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$pendingTransferredPilot">
          <do_if value="not this.$pendingPilotTransferSince?">
            <set_value name="this.$pendingPilotTransferSince" exact="player.age"/>
          </do_if>
          <set_value name="$pendingTransferElapsed" exact="player.age - this.$pendingPilotTransferSince"/>
          
          <do_if value="$pendingTransferElapsed lt 15min">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Missing pilot but transfer is in progress for ' + $pendingPilotName + ' (elapsed=' + ($pendingTransferElapsed / 1s) + 's) - waiting before cancellation'" chance="100"/>
            </do_if>
            <wait exact="5s"/>
            <return/>
          </do_if>
        </do_if>
        
        <remove_value name="this.$pendingPilotTransferSince"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MISSING PILOT DETECTED - pilot was transferred away, cleaning up and self-canceling GT order'" chance="100"/>
        </do_if>
        
        <!-- Get original ship name from ship registry -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{this.ship}.$OriginalShipName"/>
        </do_if>
        
        <!-- Send cleanup signal (name restoration handled by MD system) -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = null,
          $Reason = 'Pilot transferred away - GT order cannot run without pilot',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Cancel all active orders (trade orders, etc.) -->
        <cancel_all_orders object="this.ship"/>
        
        <!-- Self-cancel GT order -->
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Restore XPBlocked if BlockedLevel still exists (ship restart/reinit) -->
      <!-- Also update ship name to show ADVANCE label when XPBlocked is restored -->
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <set_value name="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] Restored XPBlocked for pilot ' + this.ship.pilot.name + ' on ship restart (BlockedLevel: ' + global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel + ')'" chance="100"/>
          </do_if>
          
          <!-- Update ship name to show ADVANCE label when XPBlocked is restored -->
          <!-- This ensures the ship name reflects the blocked state after restart -->
          <!-- Calculate rank title based on blocked level -->
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          <set_value name="$rankTitle" exact="'Lehrling'"/>
          <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
            <set_value name="$rankIndex" exact="($blockedLevel / 3)i + 1"/>
            <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
              <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
            </do_if>
            <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
              <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
            </do_if>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
            $Ship = this.ship,
            $pilot = this.ship.pilot,
            $xp = @global.$GT_Pilots.{this.ship.pilot}.$XP,
            $level = $blockedLevel,
            $rank = $rankTitle,
            $nameType = 'blocked'
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] Updated ship name to show ADVANCE label after XPBlocked restoration: ' + this.ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Initialize default order tracking -->
      <!-- Track the current default order to detect when GT order is removed -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="not this.$trackedDefaultOrder?">
        <!-- First time - initialize tracked order -->
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
        
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3'">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] GT order assigned to ' + this.ship.idcode + ' - sending GT_Order_Assigned signal'" chance="100"/>
          </do_if>
          <run_script name="'lib.gt.attention.emit_gt_state_changed'">
            <param name="ship" value="this.ship"/>
            <param name="isGTActive" value="true"/>
            <param name="source" value="'AI_INIT_ASSIGN'"/>
          </run_script>
        </do_if>
      </do_if>
      <do_elseif value="this.$trackedDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder == 'GalaxyTraderMK3'">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] GT order reassigned to ' + this.ship.idcode + ' (old: ' + this.$trackedDefaultOrder + ', new: ' + $currentDefaultOrder + ') - sending GT_Order_Assigned signal'" chance="100"/>
        </do_if>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="true"/>
          <param name="source" value="'AI_INIT_REASSIGN'"/>
        </run_script>
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_elseif>
      <do_if value="this.$trackedDefaultOrder == 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK3'">
        <!-- CRITICAL FIX: Check if ship is still GT-controlled via commander BEFORE sending cancellation -->
        <!-- When a subordinate is assigned to a commander, default order changes from GalaxyTraderMK3 to Assist -->
        <!-- But ship is still GT-controlled via commander - don't send cancellation signal -->
        <set_value name="$isStillGTControlled" exact="false"/>
        
        <!-- Check 1: Direct GT order -->
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3'">
          <set_value name="$isStillGTControlled" exact="true"/>
        </do_if>
        
        <!-- Check 2: Subordinate to GT commander with Assist order -->
        <do_if value="not $isStillGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <do_if value="$currentDefaultOrder == 'Assist'">
              <set_value name="$isStillGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <do_if value="not $isStillGTControlled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in init label, old: ' + this.$trackedDefaultOrder + ', new: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isStillGTControlled + ')'" chance="100"/>
          </do_if>
          <run_script name="'lib.gt.attention.emit_gt_state_changed'">
            <param name="ship" value="this.ship"/>
            <param name="isGTActive" value="false"/>
            <param name="source" value="'AI_INIT_CANCEL'"/>
          </run_script>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: Default order changed from GalaxyTraderMK3 to ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ' BUT ship still GT-controlled via commander - NOT sending cancellation'" chance="100"/>
          </do_if>
        </do_else>
        
        <run_script name="'lib.gt.attention.restore_original_name'">
          <param name="ship" value="this.ship"/>
          <param name="reason" value="'GT order cancelled - restoring original name'"/>
          <param name="skipIfStillGT" value="true"/>
          <param name="validOrderIds" value="['GalaxyTraderMK3']"/>
        </run_script>
        
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_elseif value="this.$trackedDefaultOrder != $currentDefaultOrder">
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_elseif>
      
      <!-- Initialize commander tracking and detect commander assignment -->
      <!-- This runs when script restarts (e.g., after commander assignment) -->
      <!-- Check for changes BEFORE initializing trackedCommander -->
      <set_value name="$currentCommander" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$currentCommander" exact="this.ship.commander"/>
      </do_if>
      
      <!-- Store previous tracked commander BEFORE checking/updating -->
      <set_value name="$previousTrackedCommander" exact="null"/>
      <do_if value="this.$trackedCommander?">
        <set_value name="$previousTrackedCommander" exact="this.$trackedCommander"/>
      </do_if>
      
      <!-- Log current state -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] PHASE 6 DEBUG: ' + this.ship.idcode + ' - currentCommander: ' + (if @$currentCommander.exists then @$currentCommander.idcode else 'NONE') + ', previousTrackedCommander: ' + (if @$previousTrackedCommander.exists then @$previousTrackedCommander.idcode else 'NONE')" chance="100"/>
      </do_if>
      
      <!-- Check if commander changed (compare with previous tracked value BEFORE updating) -->
      <do_if value="not this.$trackedCommander?">
        <!-- First time - initialize tracked commander and send signal if commander exists -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
        <do_if value="@$currentCommander.exists">
          <!-- Commander exists on first check - send initialization signal -->
          <set_value name="$newCommanderHasGT" exact="false"/>
          <do_if value="$currentCommander.defaultorder? and (@$currentCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$currentCommander.defaultorder.id == 'Assist' and $currentCommander.defaultorder.$baseorder? and @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'Commander_Changed',
            $Commander = $currentCommander,
            $CommanderHasGT = $newCommanderHasGT
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 6: Commander initialized for ' + this.ship.idcode + ' (commander: ' + $currentCommander.idcode + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="((@$previousTrackedCommander.exists == true) and not (@$currentCommander.exists == true)) or (not (@$previousTrackedCommander.exists == true) and (@$currentCommander.exists == true))">
        <!-- Commander state changed (was null, now exists OR was exists, now null) -->
        <set_value name="$oldCommander" exact="$previousTrackedCommander"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if old commander had GT order (for name restoration when subordinate removed) -->
        <set_value name="$oldCommanderHasGT" exact="false"/>
        <do_if value="@$oldCommander.exists">
          <do_if value="$oldCommander.defaultorder? and (@$oldCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$oldCommander.defaultorder.id == 'Assist' and $oldCommander.defaultorder.$baseorder? and @$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$oldCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and (@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + (if @$oldCommander.exists then @$oldCommander.idcode else 'NONE') + ', new: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <do_if value="$oldCommanderHasGT and not $newCommanderHasGT and this.ship.pilot?">
          <run_script name="'lib.gt.attention.restore_original_name'">
            <param name="ship" value="this.ship"/>
            <param name="reason" value="'Subordinate removed from GT commander - restoring original name'"/>
            <param name="skipIfStillGT" value="true"/>
            <param name="validOrderIds" value="['GalaxyTraderMK3']"/>
          </run_script>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      <do_elseif value="(@$previousTrackedCommander.exists == true) and (@$currentCommander.exists == true) and $previousTrackedCommander != $currentCommander">
        <!-- Commander changed to different commander -->
        <set_value name="$oldCommander" exact="$previousTrackedCommander"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="$newCommander.defaultorder? and (@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
          <set_value name="$newCommanderHasGT" exact="true"/>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + $oldCommander.idcode + ', new: ' + $newCommander.idcode + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      <do_else>
        <!-- Commander is the same - no change, but ensure tracked value is updated -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_else>
      
      <!-- Re-inherit settings from commander if this is a subordinate -->
      <do_if value="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$commanderOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$commanderOrder?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Re-inheriting settings from commander ' + this.ship.commander.idcode" chance="100"/>
          </do_if>
          <!-- Re-inherit all commander settings -->
          <do_if value="$commanderOrder.$fleetcoordination?"><set_value name="$effectiveFleetCoordination" exact="$commanderOrder.$fleetcoordination"/></do_if>
          <do_if value="$commanderOrder.$allowillegal?"><set_value name="$effectiveAllowIllegal" exact="$commanderOrder.$allowillegal"/></do_if>
          <do_if value="$commanderOrder.$enforceRouteIllegalLegality?"><set_value name="$effectiveEnforceRouteIllegalLegality" exact="$commanderOrder.$enforceRouteIllegalLegality"/></do_if>
          <do_if value="$commanderOrder.$factionpriority?"><set_value name="$effectiveFactionPriority" exact="if $commanderOrder.$factionpriority then 1 else 0"/></do_if>
          <do_if value="$commanderOrder.$ignorecarrieraux?"><set_value name="$effectiveIgnoreCarrierAux" exact="$commanderOrder.$ignorecarrieraux"/></do_if>
          <do_if value="$commanderOrder.$ignorebuildstorage?"><set_value name="$effectiveIgnoreBuildStorage" exact="$commanderOrder.$ignorebuildstorage"/></do_if>
          <do_if value="$commanderOrder.$ignoretraderules?"><set_value name="$effectiveIgnoreTradeRules" exact="$commanderOrder.$ignoretraderules"/></do_if>
          <do_if value="$commanderOrder.$ignoreplayerpricing?"><set_value name="$effectiveIgnorePlayerPricing" exact="$commanderOrder.$ignoreplayerpricing"/></do_if>
          <do_if value="$commanderOrder.$ignoremk1supply?"><set_value name="$effectiveIgnoreMK1Supply" exact="$commanderOrder.$ignoremk1supply"/></do_if>
          <do_if value="$commanderOrder.$home?"><set_value name="$effectiveHome" exact="$commanderOrder.$home"/></do_if>
          <do_if value="$commanderOrder.$sectorwhitelist?"><set_value name="$effectiveSectorWhitelist" exact="$commanderOrder.$sectorwhitelist"/></do_if>
          <do_if value="$commanderOrder.$blockedstations?"><set_value name="$effectiveBlockedStations" exact="$commanderOrder.$blockedstations"/></do_if>
          <!-- Ware filter / scoring settings -->
          <do_if value="$commanderOrder.$autowares?"><set_value name="$effectiveAutoWares" exact="$commanderOrder.$autowares"/></do_if>
          <do_if value="$commanderOrder.$warebasket?"><set_value name="$effectiveWareBasket" exact="$commanderOrder.$warebasket"/></do_if>
          <do_if value="$commanderOrder.$prioritywares?"><set_value name="$effectivePriorityWares" exact="$commanderOrder.$prioritywares"/></do_if>
          <do_if value="$commanderOrder.$priorityscoremultiplier?"><set_value name="$effectivePriorityScoreMultiplier" exact="[$commanderOrder.$priorityscoremultiplier, 125].max"/></do_if>
          <do_if value="$effectivePriorityScoreMultiplier? and $effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
          <do_if value="$commanderOrder.$distancepenalty?"><set_value name="$effectiveDistancePenalty" exact="$commanderOrder.$distancepenalty"/></do_if>
          <do_if value="$commanderOrder.$cargotarget?"><set_value name="$effectiveCargoTarget" exact="$commanderOrder.$cargotarget"/></do_if>
          <do_if value="$commanderOrder.$logbookentries?"><set_value name="$effectiveLogbookEntries" exact="$commanderOrder.$logbookentries"/></do_if>
          <do_if value="$commanderOrder.$notifications?"><set_value name="$effectiveNotifications" exact="$commanderOrder.$notifications"/></do_if>
          <do_if value="$commanderOrder.$debuglevel?"><set_value name="$effectiveDebugLevel" exact="$commanderOrder.$debuglevel"/></do_if>
          <do_if value="$commanderOrder.$tradeeval?"><set_value name="$effectiveTradeEval" exact="$commanderOrder.$tradeeval"/></do_if>
          <!-- Re-inherit max jump distances with pilot capability cap (disabled in vanilla mode). -->
          <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
          <set_value name="$pilotMaxJumps" exact="null"/>
          <run_script name="'lib.gt.pathfinding'" result="$pilotSkill">
            <param name="mode" value="'effective_pilot_level'"/>
            <param name="ship" value="this.ship"/>
            <param name="includeCommander" value="false"/>
          </run_script>
          <do_if value="not $useVanillaXPOnly">
            <run_script name="'lib.gt.pathfinding'" result="$pilotMaxJumps">
              <param name="mode" value="'pilot_max_jumps'"/>
              <param name="pilotSkill" value="$pilotSkill"/>
            </run_script>
          </do_if>
          <do_if value="$commanderOrder.$maxbuy?">
            <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderOrder.$maxbuy else [$commanderOrder.$maxbuy, $pilotMaxJumps].min"/>
          </do_if>
          <do_if value="$commanderOrder.$maxsell?">
            <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderOrder.$maxsell else [$commanderOrder.$maxsell, $pilotMaxJumps].min"/>
          </do_if>
          <!-- Refresh derived variables used by the trading loop / MD requests -->
          <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
          <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
          <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
          <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
          <set_value name="this.$gt_cargotarget" exact="$gt_cargotarget"/>
          <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
          <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
          <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Settings re-inherited successfully'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Rehydrate missing local effective vars before persisting.
           AI local $vars can be missing on some resume paths. -->
      <do_if value="not $effectiveMaxBuy?">
        <set_value name="$effectiveMaxBuy" exact="if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else $maxbuy"/>
      </do_if>
      <do_if value="not $effectiveMaxSell?">
        <set_value name="$effectiveMaxSell" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else $maxsell"/>
      </do_if>
      <do_if value="not $effectiveIgnoreTradeRules?">
        <set_value name="$effectiveIgnoreTradeRules" exact="if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false"/>
      </do_if>
      <do_if value="not $effectiveIgnorePlayerPricing?">
        <set_value name="$effectiveIgnorePlayerPricing" exact="if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false"/>
      </do_if>
      <do_if value="not $effectiveIgnoreMK1Supply?">
        <set_value name="$effectiveIgnoreMK1Supply" exact="if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true"/>
      </do_if>
      <do_if value="not $effectiveIgnoreCarrierAux?">
        <set_value name="$effectiveIgnoreCarrierAux" exact="if this.$effectiveIgnoreCarrierAux? then this.$effectiveIgnoreCarrierAux else false"/>
      </do_if>
      <do_if value="not $effectiveIgnoreBuildStorage?">
        <set_value name="$effectiveIgnoreBuildStorage" exact="if this.$effectiveIgnoreBuildStorage? then this.$effectiveIgnoreBuildStorage else false"/>
      </do_if>
      <do_if value="not $effectiveDistancePenalty?">
        <set_value name="$effectiveDistancePenalty" exact="if this.$effectiveDistancePenalty? then this.$effectiveDistancePenalty else $distancepenalty"/>
      </do_if>
      <do_if value="not $effectiveFleetCoordination?">
        <set_value name="$effectiveFleetCoordination" exact="if this.$effectiveFleetCoordination? then this.$effectiveFleetCoordination else $fleetcoordination"/>
      </do_if>
      <do_if value="not $effectiveFactionPriority?">
        <set_value name="$effectiveFactionPriority" exact="if this.$effectiveFactionPriority? then this.$effectiveFactionPriority else (if $factionpriority then 1 else 0)"/>
      </do_if>
      <do_if value="not $effectiveAllowIllegal?">
        <set_value name="$effectiveAllowIllegal" exact="if this.$effectiveAllowIllegal? then this.$effectiveAllowIllegal else $allowillegal"/>
      </do_if>
      <do_if value="not $effectiveEnforceRouteIllegalLegality?">
        <set_value name="$effectiveEnforceRouteIllegalLegality" exact="if this.$effectiveEnforceRouteIllegalLegality? then this.$effectiveEnforceRouteIllegalLegality else $enforceRouteIllegalLegality"/>
      </do_if>
      <do_if value="not $effectiveLogbookEntries?">
        <set_value name="$effectiveLogbookEntries" exact="if this.$effectiveLogbookEntries? then this.$effectiveLogbookEntries else $logbookentries"/>
      </do_if>
      <do_if value="not $effectiveCargoTarget?">
        <set_value name="$effectiveCargoTarget" exact="if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else (if $cargotarget? then $cargotarget else 80)"/>
      </do_if>
      <set_value name="$gt_cargotarget" exact="[10,[(if this.$gt_cargotarget? then this.$gt_cargotarget else $effectiveCargoTarget), 100].min].max"/>
      <set_value name="this.$gt_cargotarget" exact="$gt_cargotarget"/>
      <do_if value="not $effectivePriorityWares?">
        <set_value name="$effectivePriorityWares" exact="if this.$effectivePriorityWares? then this.$effectivePriorityWares else (if $prioritywares? then $prioritywares else [])"/>
      </do_if>
      <do_if value="not $effectivePriorityScoreMultiplier?">
        <set_value name="$effectivePriorityScoreMultiplier" exact="if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else (if $priorityscoremultiplier? then $priorityscoremultiplier else 125)"/>
      </do_if>
      <do_if value="not $effectiveBlockedStations?">
        <set_value name="$effectiveBlockedStations" exact="if this.$effectiveBlockedStations? then this.$effectiveBlockedStations else (if $blockedstations? then $blockedstations else [])"/>
      </do_if>

      <!-- Persist effective settings (survive save/load resume) -->
      <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
      <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
      <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
      <set_value name="this.$effectiveIgnorePlayerPricing" exact="$effectiveIgnorePlayerPricing"/>
      <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
      <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
      <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
      <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
      <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
      <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
      <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
      <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
      <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
      <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
      <set_value name="this.$effectiveBlockedStations" exact="if $effectiveBlockedStations? then $effectiveBlockedStations else []"/>
      
      <!-- Initialize subordinate count tracking -->
      <!-- Track when this ship becomes a commander (gets subordinates) -->
      <set_value name="$currentSubordinateCount" exact="0"/>
      <do_if value="this.ship.subordinates?">
        <set_value name="$currentSubordinateCount" exact="this.ship.subordinates.count"/>
      </do_if>
      <do_if value="not this.$trackedSubordinateCount?">
        <!-- First time - initialize tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_if>
      
      <!-- Reset was_subordinate flag based on CURRENT state, not previous state -->
      <!-- This prevents false positives when a ship transitions from subordinate â†’ independent -->
      <!-- If ship has a direct GT order, it's independent, not orphaned -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <do_if value="this.ship.defaultorder? and @this.ship.defaultorder.id == 'GalaxyTraderMK3'">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <!-- Reset was_subordinate based on current commander status -->
      <set_value name="$isCurrentlySubordinate" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship"/>
      <set_value name="this.$was_subordinate" exact="$isCurrentlySubordinate"/>
      
      <!-- If ship has direct GT order but was previously subordinate, clear the flag -->
      <!-- This allows ships to transition from subordinate â†’ independent without being treated as orphaned -->
      <do_if value="$hasDirectGTOrder and not $isCurrentlySubordinate">
        <set_value name="this.$was_subordinate" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Reset was_subordinate flag (has direct GT order, not subordinate)'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- =============================================== -->
      <!-- MAIN TRADING LOOP (Modularized)                -->
      <!-- =============================================== -->
      
      <label name="main_loop"/>

      <!-- Idle park timed release (trader keeps searching; hold expiry handled here). -->
      <run_script name="'lib.gt.idlepark'">
        <param name="handoffMode" value="'check_timed_release'"/>
        <param name="handoffShip" value="this.ship"/>
        <param name="home" value="if this.$effectiveHome? and this.$effectiveHome != null and this.$effectiveHome.exists then this.$effectiveHome else this.ship.sector"/>
        <param name="debugchance" value="if this.$debugchance? then this.$debugchance else 0"/>
      </run_script>
      
      <!-- Unified ship name refresh (home sector, op-state, XP â€” content dedupe in MD) -->
      <run_script name="'lib.gt.attention.refresh_ship_name'">
        <param name="ship" value="this.ship"/>
      </run_script>
      <run_script name="'lib.gt.attention.autojump_distance_toggle'">
        <param name="autoJumpDistanceByLevel" value="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
      </run_script>

      <!-- NOTE: Signal check removed from here - maintenance must ALWAYS run before trade execution -->
      <!-- Signals will be checked AFTER maintenance completes (line 2147) to ensure maintenance is never skipped -->
      <!-- NOTE: Do NOT clear global.$GT_TradesAwaitingValidation here - it may contain fresh trade data -->
      <!-- The data will be cleared after trade execution completes (in trade_completed label) -->
      <!-- Cache will be checked by MD system when trade request is sent -->
      <!-- MD system will trigger cache search work unit if cache entries exist -->
      <!-- Cache search work unit will properly filter entries by distance/profit/etc before signaling back -->
      
      <!-- Work-unit processing removed by AI pipeline migration -->
      
      <!-- SAVEGAME GUARD: Re-initialize instance vars that may be missing after save/load resume -->
      <do_if value="not this.$blacklistgroup?">
        <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
        <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
          <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
        </do_if>
      </do_if>
      <do_if value="not this.$minPlayerMoney?">
        <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      </do_if>
      <!-- SAVEGAME GUARD: Restore training session flag from persisted MD state
           or an active DockAndTrain order (instance flag is lost on load). -->
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$sgHasDockAndTrain" exact="false"/>
        <do_if value="this.ship.orders.count gt 0">
          <do_all exact="this.ship.orders.count" counter="$sgOi">
            <do_if value="this.ship.orders.{$sgOi}.id == 'DockAndTrain'">
              <set_value name="$sgHasDockAndTrain" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <set_value name="$sgMdTrainingActive" exact="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'"/>
        <do_if value="$sgHasDockAndTrain or $sgMdTrainingActive">
          <set_value name="this.$training_in_progress" exact="true"/>
        </do_if>
      </do_if>

      <!-- Clear ESCAPE state once we are no longer in a blacklisted sector (whitelist overrides blacklist) -->
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Escaping? and global.$GT_Ships.{this.ship}.$Escaping">
        <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        <set_value name="$validationWhitelist" exact="[]"/>
        <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
          <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
        </do_if>
        <set_value name="$currentSector" exact="this.ship.sector"/>
        <set_value name="$curActivityBL" exact="false"/>
        <set_value name="$curTravelBL" exact="false"/>
        <set_value name="$curWhitelisted" exact="false"/>
        <do_if value="$validationWhitelist.count gt 0">
          <do_all exact="$validationWhitelist.count" counter="$swIdx">
            <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
              <set_value name="$curWhitelisted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $curWhitelisted">
          <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
          <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
        </do_if>
        <do_if value="not ($curActivityBL or $curTravelBL)">
          <remove_value name="global.$GT_Ships.{this.ship}.$Escaping"/>
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship=this.ship,
              $pilot=this.ship.pilot,
              $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
              $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType='trader'
            ]"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Debug: Confirm we reached main loop -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === MAIN LOOP STARTED === (Pilot: ' + (if this.ship.pilot then this.ship.pilot.name else 'NONE') + ')'" chance="100"/>
      </do_if>
      
      <!-- Read MinPlayerMoney once per loop iteration â€” used by money gates, authoritative guard, and logbook.
           Persisted on instance so it survives <wait> yields within this iteration. -->
      <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      
      <!-- Check if GT order was removed (main loop detection) -->
      <!-- This catches cases where GT order is manually removed but script continues running -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="not this.$trackedDefaultOrder?">
        <!-- First time - initialize tracked order -->
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder == 'GalaxyTraderMK3'">
        <debug_text text="'[GT-AI] GT order reassigned for ' + this.ship.idcode + ' (detected in main loop, old: ' + this.$trackedDefaultOrder + ', new: ' + $currentDefaultOrder + ')'" chance="100"/>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="true"/>
          <param name="source" value="'AI_LOOP_REASSIGN'"/>
        </run_script>
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder == 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK3'">
        <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in main loop, old: ' + this.$trackedDefaultOrder + ', new: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ')'" chance="100"/>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="false"/>
          <param name="source" value="'AI_LOOP_CANCEL'"/>
        </run_script>
        
        <run_script name="'lib.gt.attention.restore_original_name'">
          <param name="ship" value="this.ship"/>
          <param name="reason" value="'GT order cancelled - restoring original name'"/>
          <param name="skipIfStillGT" value="true"/>
          <param name="validOrderIds" value="['GalaxyTraderMK3']"/>
        </run_script>
        
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder != $currentDefaultOrder">
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- MANDATORY TRAINING CHECK (BLOCKS ALL TRADING) -->
      <!-- ======================================= -->
      
      <!-- Check if training was completed by interrupt handler -->
      <do_if value="this.$training_complete?">
        <remove_value name="this.$training_complete"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training completed - continuing with trading'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Clear stale training flags when not in training -->
      <!-- These flags can persist when AI context is reused after rapid abort/restart -->
      <do_if value="this.$training_transition? or this.$training_order_created?">
        <do_if value="not this.ship.pilot or not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
          <!-- Pilot is not XP blocked, so training flags are stale - clear them -->
          <remove_value name="this.$training_transition"/>
          <remove_value name="this.$training_order_created"/>
          <remove_value name="this.$training_in_progress"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale training flags (pilot not XP blocked)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (Event-Driven)  -->
      <!-- ======================================= -->
      <!-- NOTE: Pilot change detection moved to restart points (trade_completed, init) -->
      <!-- Polling removed - detection happens at natural restart points where GT order reruns -->
      <!-- This ensures detection happens when order naturally restarts, not constantly polling -->
      
      <!-- ======================================= -->
      <!-- Commander change detection (Main Loop) -->
      <!-- ======================================= -->
      <!-- Track the current commander and detect if it changes (assignment, removal, or change) -->
      <!-- This is more reliable than event_object_commander_set which may not fire during script restart -->
      <set_value name="$currentCommander" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$currentCommander" exact="this.ship.commander"/>
      </do_if>
      
      <!-- Check if commander changed (null to exists, exists to null, or different commander) -->
      <do_if value="not this.$trackedCommander?">
        <!-- First time check - initialize tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_if>
      <do_elseif value="this.$trackedCommander != $currentCommander">
        <!-- Commander changed: nullâ†’exists, existsâ†’null, or different commander -->
        <set_value name="$oldCommander" exact="if this.$trackedCommander? then this.$trackedCommander else null"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if old commander had GT order (for name restoration) -->
        <set_value name="$oldCommanderHasGT" exact="false"/>
        <do_if value="@$oldCommander.exists">
          <do_if value="$oldCommander.defaultorder? and (@$oldCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$oldCommander.defaultorder.id == 'Assist' and $oldCommander.defaultorder.$baseorder? and @$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$oldCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and (@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + (if @$oldCommander.exists then @$oldCommander.idcode else 'NONE') + ', new: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <do_if value="$oldCommanderHasGT and not $newCommanderHasGT and this.ship.pilot?">
          <run_script name="'lib.gt.attention.restore_original_name'">
            <param name="ship" value="this.ship"/>
            <param name="reason" value="'Commander changed - no longer subordinate to GT commander'"/>
            <param name="skipIfStillGT" value="true"/>
            <param name="validOrderIds" value="['GalaxyTraderMK3']"/>
          </run_script>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      
      <!-- ======================================= -->
      <!-- Subordinate count detection (Main Loop) -->
      <!-- ======================================= -->
      <!-- Track when this ship becomes a commander (gets subordinates) or stops being one (loses all subordinates) -->
      <!-- This is important for ships that transition from subordinate â†’ commander -->
      <set_value name="$currentSubordinateCount" exact="0"/>
      <do_if value="this.ship.subordinates?">
        <set_value name="$currentSubordinateCount" exact="this.ship.subordinates.count"/>
      </do_if>
      
      <!-- Check if subordinate count changed -->
      <do_if value="not this.$trackedSubordinateCount?">
        <!-- First time check - initialize tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_if>
      <do_elseif value="this.$trackedSubordinateCount != $currentSubordinateCount">
        <!-- Subordinate count changed -->
        <set_value name="$oldSubordinateCount" exact="this.$trackedSubordinateCount"/>
        <set_value name="$newSubordinateCount" exact="$currentSubordinateCount"/>
        
        <!-- Determine if ship became a commander or stopped being one -->
        <set_value name="$wasCommander" exact="($oldSubordinateCount gt 0)"/>
        <set_value name="$isCommander" exact="($newSubordinateCount gt 0)"/>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Subordinate_Count_Changed',
          $OldSubordinateCount = $oldSubordinateCount,
          $NewSubordinateCount = $newSubordinateCount,
          $WasCommander = $wasCommander,
          $IsCommander = $isCommander
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Subordinate count changed for ' + this.ship.idcode + ' (old: ' + $oldSubordinateCount + ', new: ' + $newSubordinateCount + ', was commander: ' + $wasCommander + ', is commander: ' + $isCommander + ')'" chance="100"/>
        </do_if>
        
        <!-- Update tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_elseif>
      
      <!-- ======================================= -->
      <!-- SUBORDINATE COMMANDER CHECK            -->
      <!-- ======================================= -->
      <!-- Check if ship was a subordinate but lost its commander completely -->
      <!-- Track if ship was a subordinate when order started -->
      <do_if value="not this.$was_subordinate?">
        <!-- First time check - store if ship is currently a subordinate -->
        <set_value name="this.$was_subordinate" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship"/>
      </do_if>
      
      <!-- Check if subordinate lost its commander or commander lost GT order -->
      <!-- Unified GT order status check (inline for AI scripts) -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <set_value name="$hasGTCommander" exact="false"/>
      <set_value name="$commanderExists" exact="false"/>
      <set_value name="$isSubordinate" exact="false"/>
      
      <!-- Check direct GT order -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3'">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <!-- Check commander status -->
      <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$commanderExists" exact="true"/>
        <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
          <set_value name="$hasGTCommander" exact="true"/>
          <do_if value="$currentDefaultOrder == 'Assist'">
            <set_value name="$isSubordinate" exact="true"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Check if ship was subordinate and lost commander completely -->
      <do_if value="this.$was_subordinate and not $hasDirectGTOrder">
        <do_if value="not $commanderExists">
          <!-- Subordinate lost its commander completely - restore name and self-abort -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SUBORDINATE ORPHANED: Commander assignment completely removed - restoring ship name and self-aborting'" chance="100"/>
          </do_if>
          
          <!-- Send cleanup signal unconditionally (with safe original-name fallback). -->
          <set_value name="$originalName" exact="null"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          <do_elseif value="this.ship.macro?">
            <set_value name="$originalName" exact="@this.ship.macro.name"/>
          </do_elseif>
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'Commander lost GT order',
            $OriginalName = $originalName
          ]"/>
          
          <!-- Set flag only after signal was emitted -->
          <set_value name="this.$subordinate_cleanup_sent" exact="true"/>
          
          <!-- Self-cancel GT order since subordinate is no longer assigned -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Self-canceling GT order - commander assignment removed'" chance="100"/>
          </do_if>
          <cancel_order order="this.ship.defaultorder"/>
          <return/>
        </do_if>
      </do_if>
      
      <!-- If subordinate and commander no longer has GT order, restore ship name and self-abort -->
      <do_if value="$commanderExists and not $hasGTCommander">
        <!-- Commander no longer has GT order - subordinate will follow commander's new order via Assist -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SUBORDINATE ORPHANED: Commander ' + this.ship.commander.idcode + ' no longer has GT order - restoring ship name and self-aborting'" chance="100"/>
        </do_if>
        
        <!-- Send cleanup signal unconditionally (with safe original-name fallback). -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="this.ship.macro?">
          <set_value name="$originalName" exact="@this.ship.macro.name"/>
        </do_elseif>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Commander lost GT order',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Set flag only after signal was emitted -->
        <set_value name="this.$subordinate_cleanup_sent" exact="true"/>
        
        <!-- Self-cancel GT order since X4 will make us follow commander's new order anyway -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Self-canceling GT order - will follow commander via Assist'" chance="100"/>
        </do_if>
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Update subordinate tracking flag -->
      <do_if value="$isSubordinate">
        <set_value name="this.$was_subordinate" exact="true"/>
      </do_if>
      <do_else>
        <!-- Not a subordinate anymore - clear flag -->
        <set_value name="this.$was_subordinate" exact="false"/>
      </do_else>
      
      <!-- MANDATORY TRAINING GATE: shared decision logic -->
      <set_value name="$pilotXPBlocked" exact="false"/>
      <set_value name="$pilotMustTrainNow" exact="false"/>
      <set_value name="$pilotNameForDebug" exact="'No Pilot'"/>
      <set_value name="$pilotLevel" exact="1"/>
      <set_value name="$blockedLevel" exact="1"/>
      <set_value name="$trainingGateReason" exact="'none'"/>
      <set_value name="$hardForceTraining" exact="true"/>
      <set_value name="$manualTrainingRequested" exact="false"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
        <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
      </do_if>
      
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$pilotNameForDebug" exact="this.ship.pilot.name"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$Level?">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>

        <set_value name="$pilotXPBlocked" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else (global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?)"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested">
          <set_value name="$manualTrainingRequested" exact="true"/>
        </do_if>
        <set_value name="$pilotMustTrainNow" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else ($pilotXPBlocked or ($hardForceTraining and $blockedLevel gt 1))"/>

        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?">
          <set_value name="$trainingGateReason" exact="'paused_training_needed'"/>
        </do_if>
        <do_elseif value="$pilotXPBlocked">
          <set_value name="$trainingGateReason" exact="'xp_blocked'"/>
        </do_elseif>
        <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
          <set_value name="$trainingGateReason" exact="'hard_force_blocked_level'"/>
        </do_elseif>
        <do_elseif value="$blockedLevel gt 1">
          <set_value name="$trainingGateReason" exact="'soft_force_blocked_level'"/>
        </do_elseif>
      </do_if>
      
      <!-- Show the decision logic -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': DECISION LOGIC: XPBlocked=' + $pilotXPBlocked + ', MustTrainNow=' + $pilotMustTrainNow + ', HardForce=' + $hardForceTraining + ', ManagementLevel=' + $pilotLevel + ', BlockedLevel=' + $blockedLevel + ', Reason=' + $trainingGateReason + ', Pilot=' + $pilotNameForDebug" chance="100"/>
      </do_if>
      
      <do_if value="$pilotMustTrainNow">
        <!-- Check if this is a legitimate training requirement (blocked level > 1) -->
        <do_if value="$blockedLevel gt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': TRAINING MANDATORY: Pilot ' + $pilotNameForDebug + ' needs Level ' + $blockedLevel + ' training - no trading allowed until training completes'" chance="100"/>
          </do_if>
          <resume label="handle_mandatory_training"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pilot marked for training but BlockedLevel is invalid - clearing block and proceeding with trading'" chance="100"/>
          <!-- Clear the incorrect XP block for invalid Level 1 edge cases -->
          <signal_objects object="player.galaxy" param="'GT_Clear_XP_Block'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'Training gate invalid: BlockedLevel lte 1'
          ]"/>
        </do_else>
      </do_if>
      <do_else>
        <!-- Soft-force behavior: keep trading, but still retry training each loop when auto-training is enabled -->
        <set_value name="$academyEnrollmentPending" exact="false"/>
        <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
          <set_value name="$academyEnrollmentPending" exact="true"/>
        </do_if>
        <do_if value="not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) and ($gt_autotraining or $manualTrainingRequested or $academyEnrollmentPending) and this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and $blockedLevel gt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Soft-force/manual mode active - continuing trading but retrying training this loop (blocked level ' + $blockedLevel + ', manual=' + $manualTrainingRequested + ')'" chance="100"/>
          </do_if>
          <resume label="handle_mandatory_training"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training gate allows trading - proceeding to maintenance check'" chance="100"/>
          </do_if>
          <!-- Check maintenance needs before trading starts -->
          <resume label="check_maintenance"/>
        </do_else>
      </do_else>
      
      <!-- ======================================= -->
      <!-- INITIAL MAINTENANCE CHECK              -->
      <!-- ======================================= -->
      
      <label name="check_maintenance"/>
      
      <!-- ============================================================================= -->
      <!-- PRE-TRADE MAINTENANCE CHECK (UNIFIED SYSTEM)                                  -->
      <!-- ============================================================================= -->
      <!-- Signal unified maintenance system and wait for completion.                    -->
      <!-- MD system handles ALL logic: checking, finding stations, creating orders,     -->
      <!-- and monitoring. AI script just triggers and waits - clean separation!         -->
      <!-- ============================================================================= -->
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Requesting maintenance check'" chance="100"/>
      </do_if>
      
      <!-- Signal unified maintenance system to analyze and prepare data -->
      <signal_objects object="player.galaxy" param="'GT_DoMaintenance'" param2="this.ship"/>
      
      <!-- Wait for MD system to prepare data -->
      <wait exact="0.5s"/>
      
      <!-- DIAGNOSTIC: Log what MD prepared after the wait -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$diagHasRepair" exact="global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?"/>
        <set_value name="$diagHasResupply" exact="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?"/>
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Maintenance check result: RepairOrder=' + $diagHasRepair + ', ResupplyOrder=' + $diagHasResupply + ', HullPct=' + this.ship.hullpercentage + '%'" chance="100"/>
      </do_if>
      
      <!-- Create Repair order if data prepared -->
      <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?">
        <set_value name="$repairData" exact="global.$GT_RepairOrders.{this.ship}"/>
        <set_value name="$repairStation" exact="$repairData.$Station"/>
        
        <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=service_ai -->
        <set_value name="$canDockRepair" exact="false"/>
        <do_if value="@$repairStation.exists">
          <run_script name="'lib.gt.dockcheck'" result="$repairDockResult">
            <param name="ship" value="this.ship"/>
            <param name="station" value="$repairStation"/>
            <param name="purpose" value="'service_ai'"/>
          </run_script>
          <set_value name="$canDockRepair" exact="$repairDockResult.$CanDock"/>
          <do_if value="not $canDockRepair">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Repair docking check FAILED: ' + @$repairStation.knownname + 
                '\n  Sector: ' + @$repairStation.sector.knownname + 
                '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                '\n  â†’ Clearing repair order and continuing trading...'" 
                chance="100"/>
            </do_if>
            <remove_value name="global.$GT_RepairOrders.{this.ship}"/>
          </do_if>
        </do_if>
        
        <!-- Only create repair order if docking check passed -->
        <do_if value="$canDockRepair">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Creating Repair order at ' + $repairStation.knownname" chance="100"/>
        
        <!-- Set flag to indicate maintenance transition for on_abort handler -->
        <set_value name="this.$maintenance_transition" exact="true"/>
        
        <create_order object="this.ship" id="'Repair'" immediate="false" priority="true">
            <param name="destination" value="$repairStation"/>
          <param name="hullpercent" value="100"/>
          <param name="repairall" value="true"/>
          <param name="acceptedcost" value="$repairData.$AcceptedCost"/>
          <param name="urgent" value="false"/>
          <param name="internalorder" value="true"/>
        </create_order>
        </do_if>
      </do_if>
      
      <!-- Create Resupply order if data prepared -->
      <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
        <set_value name="$resupplyData" exact="global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': CREATING RESUPPLY BUILD ORDER'" chance="100"/>
          <debug_text text="'[GT-AI]    Target Station: ' + $resupplyData.$Station.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station Owner: ' + @$resupplyData.$Station.owner.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station Sector: ' + @$resupplyData.$Station.sector.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station exists: ' + $resupplyData.$Station.exists" chance="100"/>
          <debug_text text="'[GT-AI]    Station operational: ' + @$resupplyData.$Station.isoperational" chance="100"/>
          <debug_text text="'[GT-AI]    Distance from ship: ' + this.ship.gatedistance.{$resupplyData.$Station} + ' jumps'" chance="100"/>
        </do_if>
        
        <!-- Use vanilla's pattern: add_build_to_modify_ship with shopping list -->
        <!-- This is what actually creates the order with specific items to buy -->
        <set_value name="$buildSuccessful" exact="false"/>
        
        <!-- add_build_to_modify_ship SETS inventory, doesn't ADD to it -->
        <!-- Tables now include CURRENT equipment + NEW equipment (preserves existing) -->
        <!-- Check if tables have keys (they should always have keys now since we preserve existing equipment) -->
        <set_value name="$ammoTableKeys" exact="@$resupplyData.$AmmoTable.keys"/>
        <set_value name="$ammoTableCount" exact="@$ammoTableKeys.count"/>
        <set_value name="$unitTableKeys" exact="@$resupplyData.$UnitTable.keys"/>
        <set_value name="$unitTableCount" exact="@$unitTableKeys.count"/>
        
        <!-- Always call add_build_to_modify_ship if we have a resupply order (tables include existing + new equipment) -->
        <do_if value="$ammoTableCount? or $unitTableCount?">
          <set_value name="$resupplyStation" exact="$resupplyData.$Station"/>
          
          <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=service_ai -->
          <set_value name="$canDockResupply" exact="false"/>
          <do_if value="@$resupplyStation.exists">
            <run_script name="'lib.gt.dockcheck'" result="$resupplyDockResult">
              <param name="ship" value="this.ship"/>
              <param name="station" value="$resupplyStation"/>
              <param name="purpose" value="'service_ai'"/>
            </run_script>
            <set_value name="$canDockResupply" exact="$resupplyDockResult.$CanDock"/>
            <do_if value="not $canDockResupply">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resupply docking check FAILED: ' + @$resupplyStation.knownname + 
                  '\n  Sector: ' + @$resupplyStation.sector.knownname + 
                  '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                  '\n  â†’ Clearing resupply order and continuing trading...'" 
                  chance="100"/>
              </do_if>
              <!-- Clear resupply order data so we don't try again -->
              <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            </do_if>
          </do_if>
          
          <!-- Only create resupply order if docking check passed -->
          <do_if value="$canDockResupply">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Shopping list - Ammo types: ' + $ammoTableCount + ', Unit types: ' + $unitTableCount" chance="100"/>
          </do_if>
          
          <!-- Set flag to indicate maintenance transition for on_abort handler -->
          <set_value name="this.$maintenance_transition" exact="true"/>
          
          <!-- Use vanilla's add_build_to_modify_ship action -->
          <!-- Tables now include CURRENT equipment (preserves it) + NEW equipment (adds to it) -->
          <!-- Use immediate="false" so GT order waits for build order to complete -->
          <add_build_to_modify_ship 
              object="$resupplyStation" 
            buildobject="this.ship" 
            ammo="$resupplyData.$AmmoTable" 
            units="$resupplyData.$UnitTable" 
            immediate="false"
            internal="true"
            result="$buildSuccessful"/>
          
          <do_if value="$buildSuccessful">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Build order created successfully - waiting for completion'" chance="100"/>
              <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
            </do_if>
            <!-- Build order will complete and trigger our order.build.equip patch to signal completion -->
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FAILED to create build order!'" chance="100"/>
              <debug_text text="'[GT-AI]    This usually means the station cannot build the requested items'" chance="100"/>
              <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Build order creation failed - station cannot fulfill order'" chance="100"/>
            </do_if>
            
            <!-- Clean up resupply data -->
            <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            
            <!-- Apply cooldown to prevent immediate retry -->
            <do_if value="not global.$GT_MaintenanceFailedResupply?">
              <set_value name="global.$GT_MaintenanceFailedResupply" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_MaintenanceFailedResupply.{this.ship}" exact="player.age + 300s"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸ•’ Applied 5-minute cooldown due to failed build order'" chance="100"/>
            
            <!-- Remove maintenance order flag -->
            <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
              <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
            </do_if>
            
            <!-- Signal MD that we're done (failed) -->
            <signal_objects object="this.ship" param="'GT_Maintenance_Complete'"/>
          </do_else>
          </do_if>
          <!-- End: Only create resupply order if docking check passed -->
          <!-- End: Only create resupply order if docking check passed -->
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Empty shopping list - nothing to buy'" chance="100"/>
          </do_if>
          
          <!-- Clean up and skip -->
          <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
          <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
            <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
          </do_if>
          
          <signal_objects object="this.ship" param="'GT_Maintenance_Complete'"/>
        </do_else>
      </do_if>
      
      <!-- Wait for maintenance to complete -->
      <do_if value="(global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?) or (global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â³ Waiting for maintenance orders to complete (max 900s)...'" chance="100"/>
        </do_if>
        
        <wait max="900s">
          <interrupt>
            <conditions>
              <event_object_signalled object="this.ship" param="'GT_Maintenance_Complete'"/>
            </conditions>
            <actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Maintenance complete signal received, proceeding to trade search'" chance="100"/>
              </do_if>
              
              <!-- Clear maintenance transition flag -->
              <remove_value name="this.$maintenance_transition"/>
            </actions>
          </interrupt>
        </wait>
        
        <!-- Timeout fallback -->
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â±ï¸ Maintenance timeout after 900s, proceeding anyway'" chance="100"/>
        
        <!-- Clear maintenance transition flag on timeout as well -->
        <remove_value name="this.$maintenance_transition"/>
      </do_if>
      <do_else>
        <!-- No maintenance needed -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No maintenance needed, proceeding to trade search'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- CRITICAL: Check for signal that arrived during maintenance wait -->
      <!-- This must happen AFTER maintenance completes but BEFORE proceeding to start_trading -->
      <!-- Signals can arrive during the maintenance wait block (line 2118), so we check here -->
      <do_if value="this.$tradeFoundViaInterrupt? and this.$tradeFoundViaInterrupt">
        <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received during maintenance wait - processing from param2 data'" chance="100"/>
        </do_if>
        
        <!-- Reset retry counter on successful trade -->
        <set_value name="this.$searchFailed" exact="0"/>
        
        <!-- Clear per-ship no-trade attempt history on success -->
        <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
          <remove_value name="global.$GT_NoTradeHistory.{this.ship}"/>
        </do_if>
        
        <!-- CARGO DISPOSAL: Reset cargo disposal failure counter on successful trade -->
        <do_if value="this.$cargoDisposalFailed?">
          <set_value name="this.$cargoDisposalFailed" exact="0"/>
        </do_if>
        
        <resume label="trade_found"/>
      </do_if>
      
      <!-- Proceed to trading -->
      <resume label="start_trading"/>
      
      <!-- ======================================= -->
      <!-- HIGH-PERFORMANCE TRADING LOOP          -->
      <!-- ======================================= -->
      
      <!-- ========================================= -->
      <!-- MANDATORY TRAINING HANDLER              -->
      <!-- ========================================= -->
      
      <label name="handle_mandatory_training"/>
      
      <!-- Check if ship has an active DockAndTrain order -->
      <set_value name="$hasActiveTrainingOrder" exact="false"/>
      <do_if value="this.ship.orders.count gt 0">
        <do_all exact="this.ship.orders.count" counter="$i">
          <do_if value="this.ship.orders.{$i}.id == 'DockAndTrain'">
            <set_value name="$hasActiveTrainingOrder" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      
      <!-- ENHANCED LOGIC: Auto-restart training if it was previously interrupted -->
      <!-- Conditions for starting/restarting training:
           1. Auto-training is enabled
           2. Ship has a pilot with GT pilot data
           3. Either: training not in progress OR no active training order (interrupted training)
      -->
      <set_value name="$manualTrainingRequested" exact="false"/>
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested">
        <set_value name="$manualTrainingRequested" exact="true"/>
      </do_if>
      <set_value name="$academyEnrollmentPending" exact="false"/>
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
        <set_value name="$academyEnrollmentPending" exact="true"/>
      </do_if>
      <do_if value="($gt_autotraining or $manualTrainingRequested or $academyEnrollmentPending) and this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}">
        <set_value name="$shouldStartTraining" exact="false"/>
        <set_value name="$mdTrainingInProgress" exact="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'"/>
        
        <!-- Case 0: Active DockAndTrain or MD timer (save/load) - wait, do not re-dispatch -->
        <do_if value="$hasActiveTrainingOrder or $mdTrainingInProgress">
          <do_if value="not this.$training_in_progress?">
            <set_value name="this.$training_in_progress" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Restored in-flight training session after save/load (DockAndTrain=' + $hasActiveTrainingOrder + ', MD timer=' + $mdTrainingInProgress + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Case 1: Training not currently in progress -->
        <do_elseif value="not this.$training_in_progress?">
          <set_value name="$shouldStartTraining" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training not in progress - can start training'" chance="100"/>
          </do_if>
        </do_elseif>
        <!-- Case 2: Training was marked as in progress but no active training order (interrupted) -->
        <do_elseif value="this.$training_in_progress? and not $hasActiveTrainingOrder">
          <set_value name="$shouldStartTraining" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': TRAINING INTERRUPTED: Previous training was aborted - restarting automatically'" chance="100"/>
          </do_if>
          <!-- Clear the stale flag -->
          <remove_value name="this.$training_in_progress"/>
        </do_elseif>
        
        <do_if value="$shouldStartTraining">
          <!-- Inline training gate evaluation (AI scripts cannot call MD libraries) -->
          <set_value name="$hardForceTraining" exact="true"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
            <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
          </do_if>
          <set_value name="$blockedLevel" exact="1"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          </do_if>
          <set_value name="$mustTrainNow" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else (global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded? or ($hardForceTraining and $blockedLevel gt 1))"/>
          <set_value name="$shouldRetryTraining" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else ($mustTrainNow or ((not $hardForceTraining) and $blockedLevel gt 1) or ($manualTrainingRequested and $blockedLevel gt 1))"/>
          <set_value name="$trainingGateReason" exact="'none'"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?">
            <set_value name="$trainingGateReason" exact="'paused_training_needed'"/>
          </do_if>
          <do_elseif value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
            <set_value name="$trainingGateReason" exact="'xp_blocked'"/>
          </do_elseif>
          <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
            <set_value name="$trainingGateReason" exact="'hard_force_blocked_level'"/>
          </do_elseif>
          <do_elseif value="$blockedLevel gt 1">
            <set_value name="$trainingGateReason" exact="'soft_force_blocked_level'"/>
          </do_elseif>
          
          <do_if value="$shouldRetryTraining">
            <!-- Get blocked level with safety check -->
            <do_if value="not (global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0)">
              <!-- Calculate current skill level as fallback -->
              <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XP?">
                <set_value name="$currentXP" exact="global.$GT_Pilots.{this.ship.pilot}.$XP"/>
                <do_all exact="15" counter="$skillLevel">
                  <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                    <set_value name="$blockedLevel" exact="$skillLevel"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸŽ“ Initiating mandatory training for pilot ' + $pilotNameForDebug + ' (Level ' + $blockedLevel + ', reason=' + $trainingGateReason + ', hardforce=' + $hardForceTraining + ')'" chance="100"/>
            </do_if>
            
            <!-- Respect retry backoff only in hard-force mode -->
            <set_value name="$retryReady" exact="true"/>
            <do_if value="$hardForceTraining and global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt? and player.age lt global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt">
              <set_value name="$retryReady" exact="false"/>
            </do_if>
            
            <do_if value="$retryReady">
              <!-- Signal MD system to handle training -->
              <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $RequiredLevel = $blockedLevel
              ]"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training signal sent to MD system for pilot ' + $pilotNameForDebug" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$retryRemaining" exact="(global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt - player.age) / 1s"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training retry backoff active (' + $retryRemaining + 's remaining)'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <!-- Training is not mandatory under current gate policy -->
            <set_value name="$blockedLevelForDebug" exact="'none'"/>
            <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel?">
              <set_value name="$blockedLevelForDebug" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training gate allows trading in mandatory handler (reason=' + $trainingGateReason + ', blockedLevel=' + $blockedLevelForDebug + ', hardforce=' + $hardForceTraining + ')'" chance="100"/>
            </do_if>
            <!-- Break out of training handler and continue to trading -->
            <resume label="check_maintenance"/>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â³ Training already in progress (active order: ' + $hasActiveTrainingOrder + ') - waiting'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Auto-training disabled or no pilot data - waiting'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- Wait and check again - training is mandatory -->
      <wait max="10s">
        <interrupt>
          <conditions>
            <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
          </conditions>
          <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training station found during wait - proceeding immediately'" chance="100"/>
            </do_if>
          </actions>
        </interrupt>
      </wait>
      <resume label="main_loop"/>
      
      <!-- ========================================= -->
      <!-- EVENT-DRIVEN TRADE SEARCH WITH RETRY     -->
      <!-- ========================================= -->
      
      <label name="start_trading"/>

      <!-- HARD RULE: no silent fallbacks for pilot skill timing issues. -->
      <!-- If GT pilot level isn't available yet, do NOT request a trade search with bogus caps. -->
      <!-- Wait is only allowed at top-level; use a bounded loop here (not inside any do_if). -->
      <set_value name="$pilotSkillMissing" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and (not this.ship.pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{this.ship.pilot}? or not global.$GT_Pilots.{this.ship.pilot}.$Level?)"/>
      <set_value name="this.$pilotSkillWaitTries" exact="0"/>
      <do_while value="$pilotSkillMissing and this.$pilotSkillWaitTries lt 10">
        <wait exact="1s"/>
        <set_value name="$pilotSkillMissing" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and (not this.ship.pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{this.ship.pilot}? or not global.$GT_Pilots.{this.ship.pilot}.$Level?)"/>
        <set_value name="this.$pilotSkillWaitTries" exact="this.$pilotSkillWaitTries + 1"/>
      </do_while>
      <do_if value="$pilotSkillMissing">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ERROR: GT pilot level unavailable after ' + this.$pilotSkillWaitTries + 's - NOT sending trade search request. Will retry on next loop (this is a timing bug we want to SEE).'" chance="100"/>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- effectiveMaxBuy/effectiveMaxSell initialized in <init> block -->

      <!-- ========================================= -->
      <!-- SUBORDINATE SETTINGS REFRESH (ON REQUEST) -->
      <!-- ========================================= -->
      <!-- Problem: Commander default-order param edits do not reliably trigger event_object_order_ready.
           Solution: When a subordinate is ABOUT to request a new trade, refresh inherited commander settings if they changed.
           effectiveAutoWares/effectiveWareBasket/effectiveDistancePenalty initialized in <init> block. -->

      <set_value name="$_isSubordinateNow" exact="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship"/>
      <do_if value="$_isSubordinateNow">
        <set_value name="$_commanderOrderNow" exact="this.ship.commander.defaultorder"/>
        <do_if value="$_commanderOrderNow?">
          <!-- Build a signature for commander settings that affect trade searching / routing -->
          <set_value name="$_cmdAutoWares" exact="if $_commanderOrderNow.$autowares? then $_commanderOrderNow.$autowares else $effectiveAutoWares"/>
          <set_value name="$_cmdDistancePenalty" exact="if $_commanderOrderNow.$distancepenalty? then $_commanderOrderNow.$distancepenalty else $effectiveDistancePenalty"/>
          <set_value name="$_cmdWareBasket" exact="if $_commanderOrderNow.$warebasket? then $_commanderOrderNow.$warebasket else $effectiveWareBasket"/>

          <set_value name="$_cmdFleetCoord" exact="if $_commanderOrderNow.$fleetcoordination? then $_commanderOrderNow.$fleetcoordination else $effectiveFleetCoordination"/>
          <set_value name="$_cmdAllowIllegal" exact="if $_commanderOrderNow.$allowillegal? then $_commanderOrderNow.$allowillegal else $effectiveAllowIllegal"/>
          <set_value name="$_cmdIllegalRouteFilter" exact="if $_commanderOrderNow.$enforceRouteIllegalLegality? then $_commanderOrderNow.$enforceRouteIllegalLegality else $effectiveEnforceRouteIllegalLegality"/>
          <set_value name="$_cmdFactionPriority" exact="if $_commanderOrderNow.$factionpriority? then (if $_commanderOrderNow.$factionpriority then 1 else 0) else $effectiveFactionPriority"/>
          <set_value name="$_cmdIgnoreCarrierAux" exact="if $_commanderOrderNow.$ignorecarrieraux? then $_commanderOrderNow.$ignorecarrieraux else $effectiveIgnoreCarrierAux"/>
          <set_value name="$_cmdIgnoreBuildStorage" exact="if $_commanderOrderNow.$ignorebuildstorage? then $_commanderOrderNow.$ignorebuildstorage else $effectiveIgnoreBuildStorage"/>
          <set_value name="$_cmdIgnoreTradeRules" exact="if $_commanderOrderNow.$ignoretraderules? then $_commanderOrderNow.$ignoretraderules else $effectiveIgnoreTradeRules"/>
          <!-- Defensive fallback through this.$ instance var so legacy v3 saves resumed mid-attention
               (where the v4-only $effectiveIgnorePlayerPricing local has not been re-initialized) do not throw. -->
          <set_value name="$_cmdIgnorePlayerPricing" exact="if $_commanderOrderNow.$ignoreplayerpricing? then $_commanderOrderNow.$ignoreplayerpricing else (if $effectiveIgnorePlayerPricing? then $effectiveIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false))"/>
          <set_value name="$_cmdIgnoreMK1Supply" exact="if $_commanderOrderNow.$ignoremk1supply? then $_commanderOrderNow.$ignoremk1supply else $effectiveIgnoreMK1Supply"/>
          <set_value name="$_cmdLogbookEntries" exact="if $_commanderOrderNow.$logbookentries? then $_commanderOrderNow.$logbookentries else $effectiveLogbookEntries"/>
          <set_value name="$_cmdNotifications" exact="if $_commanderOrderNow.$notifications? then $_commanderOrderNow.$notifications else $effectiveNotifications"/>
          <set_value name="$_cmdCargoTarget" exact="if $_commanderOrderNow.$cargotarget? then $_commanderOrderNow.$cargotarget else $effectiveCargoTarget"/>
          <set_value name="$_cmdDebugLevel" exact="if $_commanderOrderNow.$debuglevel? then $_commanderOrderNow.$debuglevel else $effectiveDebugLevel"/>
          <set_value name="$_cmdTradeEval" exact="if $_commanderOrderNow.$tradeeval? then $_commanderOrderNow.$tradeeval else $effectiveTradeEval"/>
          <set_value name="$_cmdHome" exact="if $_commanderOrderNow.$home? then $_commanderOrderNow.$home else this.$effectiveHome"/>
          <set_value name="$_cmdMaxBuy" exact="if $_commanderOrderNow.$maxbuy? then $_commanderOrderNow.$maxbuy else $effectiveMaxBuy"/>
          <set_value name="$_cmdMaxSell" exact="if $_commanderOrderNow.$maxsell? then $_commanderOrderNow.$maxsell else $effectiveMaxSell"/>
          <set_value name="$_cmdSectorWhitelist" exact="if $_commanderOrderNow.$sectorwhitelist? then $_commanderOrderNow.$sectorwhitelist else $effectiveSectorWhitelist"/>
          <set_value name="$_cmdBlockedStations" exact="if $_commanderOrderNow.$blockedstations? then $_commanderOrderNow.$blockedstations else (if $effectiveBlockedStations? then $effectiveBlockedStations else (if this.$effectiveBlockedStations? then this.$effectiveBlockedStations else []))"/>
          
          <!-- IMPORTANT:
               In X4 AI script expressions, `?` checks existence, NOT null, and boolean `and` is not safe to rely on for short-circuiting.
               Normalize a null sectorwhitelist to an empty list so we can safely use `.count`. -->
          <do_if value="not $_cmdSectorWhitelist? or $_cmdSectorWhitelist == null">
            <set_value name="$_cmdSectorWhitelist" exact="[]"/>
          </do_if>
          <do_if value="not $_cmdBlockedStations? or $_cmdBlockedStations == null">
            <set_value name="$_cmdBlockedStations" exact="[]"/>
          </do_if>

          <set_value name="$_cmdHomeName" exact="if $_cmdHome? then @$_cmdHome.knownname else 'NULL'"/>
          <!-- Include subordinate pilot level in signature so level-up forces inherited cap refresh. -->
          <set_value name="$_pilotLevelSig" exact="0"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
            <set_value name="$_pilotLevelSig" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
          </do_if>

          <set_value name="$_commanderSettingsSig" exact="'AW=' + $_cmdAutoWares
            + '|DP=' + $_cmdDistancePenalty
            + '|FC=' + $_cmdFleetCoord
            + '|IL=' + $_cmdAllowIllegal
            + '|IRF=' + $_cmdIllegalRouteFilter
            + '|FP=' + $_cmdFactionPriority
            + '|ICA=' + $_cmdIgnoreCarrierAux
            + '|IBS=' + $_cmdIgnoreBuildStorage
            + '|ITR=' + $_cmdIgnoreTradeRules
            + '|IPP=' + $_cmdIgnorePlayerPricing
            + '|IM1=' + $_cmdIgnoreMK1Supply
            + '|HB=' + $_cmdHomeName
            + '|MB=' + $_cmdMaxBuy
            + '|MS=' + $_cmdMaxSell
            + '|LB=' + $_cmdLogbookEntries
            + '|NT=' + $_cmdNotifications
            + '|CT=' + $_cmdCargoTarget
            + '|DL=' + $_cmdDebugLevel
            + '|TE=' + $_cmdTradeEval
            + '|PL=' + $_pilotLevelSig
            + '|SW='"/>

          <!-- Include sector whitelist content -->
          <do_if value="$_cmdSectorWhitelist.count gt 0">
            <do_all exact="$_cmdSectorWhitelist.count" counter="$_sw_i">
              <set_value name="$_sw" exact="$_cmdSectorWhitelist.{$_sw_i}"/>
              <set_value name="$_swName" exact="if $_sw? then @$_sw.knownname else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_sw_i gt 1 then ',' else '') + $_swName"/>
            </do_all>
          </do_if>

          <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + '|BS='"/>
          <do_if value="$_cmdBlockedStations.count gt 0">
            <do_all exact="$_cmdBlockedStations.count" counter="$_bs_i">
              <set_value name="$_bs" exact="$_cmdBlockedStations.{$_bs_i}"/>
              <set_value name="$_bsName" exact="if $_bs? then @$_bs.knownname else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_bs_i gt 1 then ',' else '') + $_bsName"/>
            </do_all>
          </do_if>

          <!-- Include ware basket content (only when autowares is disabled) -->
          <do_if value="not $_cmdAutoWares">
            <do_all exact="$_cmdWareBasket.count" counter="$_i">
              <set_value name="$_w" exact="$_cmdWareBasket.{$_i}"/>
              <set_value name="$_wName" exact="if $_w? then @$_w.name else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_i gt 1 then ',' else '') + $_wName"/>
            </do_all>
          </do_if>

          <do_if value="not this.$trackedCommanderSettingsSig? or this.$trackedCommanderSettingsSig != $_commanderSettingsSig">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Commander settings changed (refreshing inherited settings). NewSig=' + $_commanderSettingsSig" chance="100"/>
            </do_if>

            <!-- Apply commander settings to this subordinate immediately -->
            <set_value name="$effectiveAutoWares" exact="$_cmdAutoWares"/>
            <set_value name="$effectiveWareBasket" exact="$_cmdWareBasket"/>
            <set_value name="$effectiveDistancePenalty" exact="$_cmdDistancePenalty"/>
            <set_value name="$effectiveFleetCoordination" exact="$_cmdFleetCoord"/>
            <set_value name="$effectiveAllowIllegal" exact="$_cmdAllowIllegal"/>
            <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$_cmdIllegalRouteFilter"/>
            <set_value name="$effectiveFactionPriority" exact="$_cmdFactionPriority"/>
            <set_value name="$effectiveIgnoreCarrierAux" exact="$_cmdIgnoreCarrierAux"/>
            <set_value name="$effectiveIgnoreBuildStorage" exact="$_cmdIgnoreBuildStorage"/>
            <set_value name="$effectiveIgnoreTradeRules" exact="$_cmdIgnoreTradeRules"/>
            <set_value name="$effectiveIgnorePlayerPricing" exact="$_cmdIgnorePlayerPricing"/>
            <set_value name="$effectiveIgnoreMK1Supply" exact="$_cmdIgnoreMK1Supply"/>
            <set_value name="$effectiveLogbookEntries" exact="$_cmdLogbookEntries"/>
            <set_value name="$effectiveNotifications" exact="$_cmdNotifications"/>
            <set_value name="$effectiveCargoTarget" exact="$_cmdCargoTarget"/>
            <set_value name="$effectiveDebugLevel" exact="$_cmdDebugLevel"/>
            <set_value name="$effectiveTradeEval" exact="$_cmdTradeEval"/>
            <set_value name="$effectiveSectorWhitelist" exact="$_cmdSectorWhitelist"/>
            <set_value name="$effectiveBlockedStations" exact="$_cmdBlockedStations"/>

            <!-- Home base affects distance filtering/scoring; ensure both local and persisted value update -->
            <set_value name="$_fleetProfOldHome" exact="if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else null)"/>
            <do_if value="$_cmdHome?">
              <set_value name="$effectiveHome" exact="$_cmdHome"/>
              <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
            </do_if>

            <!-- Jump distance caps: disable in vanilla mode, cap in GT mode. -->
            <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
            <run_script name="'lib.gt.pathfinding'" result="$_pilotSkill">
              <param name="mode" value="'effective_pilot_level'"/>
              <param name="ship" value="this.ship"/>
              <param name="includeCommander" value="false"/>
            </run_script>
            <set_value name="$_pilotMaxJumps" exact="null"/>
            <do_if value="not $useVanillaXPOnly">
              <run_script name="'lib.gt.pathfinding'" result="$_pilotMaxJumps">
                <param name="mode" value="'pilot_max_jumps'"/>
                <param name="pilotSkill" value="$_pilotSkill"/>
              </run_script>
            </do_if>

            <do_if value="$_commanderOrderNow.$maxbuy?">
              <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $_pilotMaxJumps == null then $_cmdMaxBuy else [$_cmdMaxBuy, $_pilotMaxJumps].min"/>
              <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
            </do_if>
            <do_if value="$_commanderOrderNow.$maxsell?">
              <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $_pilotMaxJumps == null then $_cmdMaxSell else [$_cmdMaxSell, $_pilotMaxJumps].min"/>
              <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
            </do_if>

            <!-- Persist updated effective settings (survive save/load resume) -->
            <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
            <set_value name="this.$effectiveIgnorePlayerPricing" exact="$effectiveIgnorePlayerPricing"/>
            <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
            <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
            <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
            <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
            <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
            <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
            <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
            <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
            <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
            <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
            <set_value name="this.$effectiveBlockedStations" exact="if $effectiveBlockedStations? then $effectiveBlockedStations else []"/>

            <!-- Refresh derived variables used by the MD requests -->
            <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
            <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
            <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
            <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
            <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
            <set_value name="this.$gt_cargotarget" exact="$gt_cargotarget"/>
            <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>

            <!-- CRITICAL: Drop stale trades awaiting validation produced under the previous commander settings.
                 Otherwise the AI can execute old trades (wrong ware filter, wrong distances, etc.) via stale data. -->
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
            </do_if>
            <!-- Clear interrupt flag when clearing trades awaiting validation (commander settings changed) -->
            <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
            <!-- Reset retry counter: we want a clean fresh request under the new settings -->
            <do_if value="this.$searchFailed?">
              <set_value name="this.$searchFailed" exact="0"/>
            </do_if>
            <set_value name="$_fleetProfHome" exact="if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else null)"/>
            <set_value name="$_fleetProfAlsoHome" exact="if $_fleetProfOldHome? and $_fleetProfOldHome.exists and $_fleetProfHome? and $_fleetProfHome.exists and $_fleetProfOldHome != $_fleetProfHome then $_fleetProfOldHome else null"/>
            <signal_objects object="player.galaxy" param="'GT_HomeFleetProfile_Update'" param2="table[$Ship = this.ship, $HomeSector = $_fleetProfHome, $AlsoHomeSector = $_fleetProfAlsoHome]"/>
          </do_if>

          <!-- Track last applied signature (always) -->
          <set_value name="this.$trackedCommanderSettingsSig" exact="$_commanderSettingsSig"/>
        </do_if>
      </do_if>

      <!-- Commander / standalone MK3: refresh fleet profile when home or cargotarget order params change -->
      <do_if value="not $_isSubordinateNow">
        <set_value name="$_fpOrderHome" exact="if $home? then $home else this.$effectiveHome"/>
        <set_value name="$_fpHomeSector" exact="if $_fpOrderHome? and $_fpOrderHome.isclass.sector then $_fpOrderHome else (if $_fpOrderHome? and $_fpOrderHome.sector? then @$_fpOrderHome.sector else null)"/>
        <set_value name="$_fpCargoTarget" exact="[10,[(if $cargotarget? then $cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 80)), 100].min].max"/>
        <set_value name="$_fpHomeName" exact="if $_fpHomeSector? and $_fpHomeSector.knownname? then @$_fpHomeSector.knownname else '?'"/>
        <set_value name="$_fleetProfileSig" exact="'H=' + $_fpHomeName + '|CT=' + $_fpCargoTarget"/>
        <do_if value="not this.$trackedFleetProfileSig? or this.$trackedFleetProfileSig != $_fleetProfileSig">
          <set_value name="$_fleetProfOldHome" exact="if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else null)"/>
          <do_if value="$_fpOrderHome?">
            <set_value name="$effectiveHome" exact="$_fpOrderHome"/>
            <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
          </do_if>
          <set_value name="$effectiveCargoTarget" exact="$_fpCargoTarget"/>
          <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
          <set_value name="$gt_cargotarget" exact="$_fpCargoTarget"/>
          <set_value name="this.$gt_cargotarget" exact="$_fpCargoTarget"/>
          <set_value name="$_fleetProfAlsoHome" exact="if $_fleetProfOldHome? and $_fleetProfOldHome.exists and $_fpHomeSector? and $_fpHomeSector.exists and $_fleetProfOldHome != $_fpHomeSector then $_fleetProfOldHome else null"/>
          <signal_objects object="player.galaxy" param="'GT_HomeFleetProfile_Update'" param2="table[$Ship = this.ship, $HomeSector = $_fpHomeSector, $AlsoHomeSector = $_fleetProfAlsoHome]"/>
          <set_value name="this.$trackedFleetProfileSig" exact="$_fleetProfileSig"/>
        </do_if>
      </do_if>
      
      <!-- Initialize retry counter if not exists -->
      <do_if value="not this.$searchFailed?">
        <set_value name="this.$searchFailed" exact="0"/>
      </do_if>
      
      <!-- Signal MD system for trade opportunities -->
      <!-- Check if ship already has trade orders BEFORE requesting new trade -->
      <set_value name="$hasTradeOrders" exact="false"/>
      <do_if value="this.ship.tradeorders? and this.ship.tradeorders.count gt 0">
        <set_value name="$hasTradeOrders" exact="true"/>
      </do_if>
      
      <do_if value="$hasTradeOrders">
        <!-- Ship already has pending trade orders - wait instead of requesting more -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Ship already has ' + this.ship.tradeorders.count + ' trade orders - waiting for completion'" chance="100"/>
        </do_if>
        
        <!-- Wait for trade completion -->
        <wait max="10s">
          <interrupt>
            <conditions>
              <check_any>
                <event_object_signalled object="this.ship" param="'GT_Trade_Completed'"/>
                <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
              </check_any>
            </conditions>
            <actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade order completed early - checking status immediately'" chance="100"/>
              </do_if>
            </actions>
          </interrupt>
        </wait>
        <resume label="main_loop"/>
      </do_if>
      <do_else>
        <!-- Ship ready for new trade - ensure ship is registered before requesting trade search -->
        <!-- This is critical when pilot is transferred to a new ship -->
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
          <!-- Ship not registered yet - wait a moment for registration to complete -->
          <!-- Registration happens via GT_Register_Ship signal handled by gt_core_system.HandleShipRegistration -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship not yet registered - waiting for registration to complete...'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Wait for registration using a top-level loop (no waits inside conditionals).
             Bounded to prevent the prior unbounded spin: 20*500ms = 10s, then re-fire GT_Register_Ship
             once (queue stall / lost signal recovery) and give the queue another 10*500ms = 5s.
             If still missing, bounce back to main_loop so the next iteration can retry instead of
             spinning the AI block forever. Counter is on `this.` because locals are lost across <wait>. -->
        <set_value name="this.$regSpinCount" exact="0"/>
        <do_while value="(not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?) and this.$regSpinCount lt 20">
          <wait exact="500ms"/>
          <set_value name="this.$regSpinCount" operation="add"/>
        </do_while>
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARN Registration missing after 10s spin - re-emitting GT_Register_Ship'" chance="100"/>
          <signal_objects object="player.galaxy" param="'GT_Register_Ship'" param2="table[$Ship = this.ship, $Config = table[]]"/>
          <set_value name="this.$regSpinCount" exact="0"/>
          <do_while value="(not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?) and this.$regSpinCount lt 10">
            <wait exact="500ms"/>
            <set_value name="this.$regSpinCount" operation="add"/>
          </do_while>
          <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARN Registration still missing after retry - bouncing to main_loop'" chance="100"/>
            <remove_value name="this.$regSpinCount"/>
            <resume label="main_loop"/>
          </do_if>
        </do_if>
        <remove_value name="this.$regSpinCount"/>
        
        <!-- Check cargo status -->
        <!-- Only trade if cargo is EMPTY -->
        <set_value name="$hasCargo" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
        
        <do_if value="$hasCargo">
          <!-- Ship has cargo - sell it first using our trade search -->
          <!-- CARGO DISPOSAL: Only log initial message once (prevent spam) -->
          <set_value name="$isFirstCargoDisposalAttempt" exact="false"/>
          <do_if value="not this.$cargoDisposalFailed? or this.$cargoDisposalFailed == 0">
            <set_value name="$isFirstCargoDisposalAttempt" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship has cargo - finding best buyer using trade search...'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Set cargo disposal flag for ship name -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
            <set_value name="global.$GT_Ships.{this.ship}.$CargoDisposal" exact="true"/>
          </do_if>
          
          <!-- Trigger ship rename to show [CLEARANCE] state -->
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship=this.ship, 
              $pilot=this.ship.pilot, 
              $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
              $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType='trader'
            ]"/>
          </do_if>
          
          <!-- Write logbook entry about cargo safety - ONLY ON FIRST ATTEMPT -->
          <do_if value="$isFirstCargoDisposalAttempt and $gt_logbookentries">
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3204}.[this.ship.knownname]"/>
            
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'tips',
              $Title = 'Cargo Safety: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
          </do_if>
          
          <!-- effectiveXxx variables initialized in <init> block -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': CARGO DISPOSAL: Sending GT_Find_Sell at age ' + player.age + ' (MaxSell=' + (if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $maxsell? then $maxsell else 1)) + ' jumps)'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Find_Sell'" param2="table[
            $Ship = this.ship,
            $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
            $MaxSell = if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $maxsell? then $maxsell else 1),
            $DistancePenalty = @this.$effectiveDistancePenalty,
            $FleetCoordination = @this.$effectiveFleetCoordination,
            $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
            $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
            $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
            $IgnorePlayerPricing = if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false,
            $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true
          ]"/>
        </do_if>
        <do_else>
          <!-- Ship cargo is EMPTY - look for buy opportunities -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cargo empty - looking for trade opportunities...'" chance="100"/>
          </do_if>

          <!-- Clear cargo disposal flag (cargo is now empty) -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal? and this.ship.cargo.count == 0">
            <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
            
            <!-- CARGO DISPOSAL: Reset cargo disposal failure counter when cargo is cleared -->
            <do_if value="this.$cargoDisposalFailed?">
              <set_value name="this.$cargoDisposalFailed" exact="0"/>
            </do_if>
            
            <!-- Trigger ship rename to remove [CLEARANCE] state -->
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship, 
                $pilot=this.ship.pilot, 
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Runtime self-heal (no reattach required):
               Vanilla temp ship accounts can survive interrupted order transitions.
               If a ship has an own account but no active tradeorders, clear it before search. -->
          <do_if value="this.ship.hasownaccount and not this.ship.tradeorders.count">
            <remove_object_account object="this.ship" transfer="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Runtime self-heal: cleared stale ship account before trade search (no active tradeorders)'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- ==================================================================================== -->
          <!-- MECHANIC 2: Early money gate - skip entire trade search pipeline when player is broke -->
          <!-- Threshold: MinPlayerMoney + 1000 Cr safety buffer.                                   -->
          <!-- This prevents the expensive cache search / work loop from running when there is      -->
          <!-- no meaningful budget left. Ships go directly to insufficient_funds cooldown.          -->
          <!-- Works with MECHANIC 1 (authoritative guard budget clamp at trade creation):           -->
          <!--   Mechanic 1 = clamp trade volume to fit budget  (trade creation)                    -->
          <!--   Mechanic 2 = stop searching when budget is exhausted (search start)                -->
          <!-- ==================================================================================== -->
          <set_value name="$earlyMoneyCheck" exact="player.money"/>
          <do_if value="not this.$minPlayerMoney?">
            <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
          </do_if>
          <set_value name="$moneyGateThreshold" exact="(this.$minPlayerMoney + 1000)Cr"/>
          <do_if value="$earlyMoneyCheck le $moneyGateThreshold">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': EARLY MONEY GATE: player money=' + ($earlyMoneyCheck / 100) + ' Cr at or below threshold=' + (this.$minPlayerMoney + 1000) + ' Cr (MinPlayerMoney=' + this.$minPlayerMoney + ' + 1000 buffer) - skipping trade search'" chance="100"/>
            <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
            <resume label="no_trade_retry"/>
          </do_if>
          
          <!-- GLOBAL MONEY CAP heal: reaching this line means we already passed the early money
               gate above, so player.money is greater than MinPlayerMoney + 1000 Cr (i.e. the
               fleet is solvent). The fleet-wide cap is only meaningful while the player is broke,
               and that case is already handled by the early gate. Clearing it here prevents a
               solvent fleet from staying frozen on a stale wealth snapshot (the cap could have
               been recorded at a higher balance than the player currently holds). The per-trade
               authoritative budget guard still blocks any individual unaffordable trade. -->
          <do_if value="global.$GT_MoneyCapActive? and global.$GT_MoneyCapActive">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP CLEARED (solvent): player money=' + ($earlyMoneyCheck / 100) + ' Cr above gate threshold (' + ($moneyGateThreshold / 100) + ' Cr) - resuming fleet trade searches'" chance="100"/>
            </do_if>
            <set_value name="global.$GT_MoneyCapActive" exact="false"/>
            <remove_value name="global.$GT_MoneyCapMoney"/>
          </do_if>
          
          <!-- Wait briefly for any pending GT_Trade_Found signals before sending new request.
               Configured delay + 5ms buffer. If signal arrives during wait, interrupt processes it. -->
          <set_value name="$signalDelayMs" exact="0"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay?">
            <set_value name="$tmpDelay" exact="@global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay"/>
            <do_if value="$tmpDelay ge 0 and $tmpDelay le 1000">
              <set_value name="$signalDelayMs" exact="$tmpDelay"/>
            </do_if>
          </do_if>
          <set_value name="this.$tradeFoundSignalWaitTime" exact="($signalDelayMs + 5) * 1ms"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Waiting ' + ($signalDelayMs + 5) + 'ms for GT_Trade_Found signal (delay=' + $signalDelayMs + 'ms + 5ms buffer)'" chance="100"/>
          </do_if>
          <wait max="if @this.$tradeFoundSignalWaitTime != null then @this.$tradeFoundSignalWaitTime else 5ms" comment="Wait for pending GT_Trade_Found signals">
            <interrupt>
              <conditions>
                <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
              </conditions>
              <actions>
                <!-- Capture signal payload before resuming so trade_found gets the correct source/list -->
                <set_value name="$intSignalData" exact="event.param2"/>
                <set_value name="$intSignalTradeList" exact="[]"/>
                <set_value name="$intSignalSearchMethod" exact="''"/>
                <do_if value="$intSignalData? and $intSignalData != null">
                  <set_value name="$intSignalTradeList" exact="@$intSignalData.$TradeList"/>
                  <set_value name="$intSignalSearchMethod" exact="@$intSignalData.$SearchMethod"/>
                </do_if>
                <set_value name="this.$tradeListFromSignal" exact="$intSignalTradeList"/>
                <set_value name="this.$searchMethodFromSignal" exact="if $intSignalSearchMethod != null and $intSignalSearchMethod != '' then $intSignalSearchMethod else ''"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received during pre-request wait - stored ' + (if $intSignalTradeList != null then $intSignalTradeList.count else 0) + ' trades from interrupt payload'" chance="100"/>
                </do_if>
                <!-- Signal received - jump to trade_found label to process it -->
                <resume label="trade_found"/>
              </actions>
            </interrupt>
          </wait>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-request wait completed - no signal received, sending new request'" chance="100"/>
          </do_if>
          
          <!-- effectiveXxx variables initialized in <init> block -->
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SENDING GT_Search_Request signal to MD at game time ' + player.age" chance="100"/>
          </do_if>
          <remove_value name="this.$cacheValidationRetried"/>
          <set_value name="$requestForceLiveSearch" exact="false"/>
          <do_if value="this.$forceLiveAfterLiveReject? and this.$forceLiveAfterLiveReject">
            <set_value name="$requestForceLiveSearch" exact="true"/>
            <set_value name="this.$forceLiveAfterLiveReject" exact="false"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
            $Ship = this.ship,
            $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
            $MaxBuy = if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else (if $maxbuy? then $maxbuy else 1),
            $MaxSell = if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $maxsell? then $maxsell else 1),
            $CargoTarget = $gt_cargotarget,
            $WareBasket = $warebasket,
            $AllowIllegal = $gt_allowillegal,
            $EnforceRouteIllegalLegality = $gt_enforceRouteIllegalLegality,
            $FactionPriority = $gt_factionpriority,
            $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
            $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
            $DistancePenalty = @this.$effectiveDistancePenalty,
            $FleetCoordination = @this.$effectiveFleetCoordination,
            $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
            $IgnorePlayerPricing = if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false,
            $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
            $ForceLiveSearch = $requestForceLiveSearch
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Search_Request signal SENT, now at game time ' + player.age" chance="100"/>
          </do_if>
        </do_else>
      </do_else>
      
      <!-- Wait for MD system response with interrupt -->
      <!-- Under large fleets, serialized batch matching can exceed 90s. Use 60s timeout to balance reliability with responsiveness. -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Entering wait state for MD response at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- Clear previous no-trade reason (prevents stale reason affecting timeout retry logic) -->
      <set_value name="this.$lastNoTradeReason" exact="''"/>
      <label name="wait_for_response"/>
      <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
      <label name="wait_for_response_continue"/>
      <do_if value="not this.$waitForResponseStartedAt?">
        <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
      </do_if>
      <do_if value="(player.age - this.$waitForResponseStartedAt) ge 60s">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT: 60s expired without semaphore grant (GT_Search_Go) at game time ' + player.age + ' â€” cleaning up queue entry and retrying'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
        <resume label="no_trade_retry"/>
      </do_if>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Wait interrupt handler ACTIVE at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- IMPORTANT: In X4, wait without min is RANDOM (0..max). Use min=max to avoid instant timeouts.
           Guard startedAt for save-load resume mid-wait (instance var may be absent on older saves). -->
      <wait min="if this.$waitForResponseStartedAt? then (if (60s - (player.age - this.$waitForResponseStartedAt)) gt 1ms then (60s - (player.age - this.$waitForResponseStartedAt)) else 1ms) else 60s" max="if this.$waitForResponseStartedAt? then (if (60s - (player.age - this.$waitForResponseStartedAt)) gt 1ms then (60s - (player.age - this.$waitForResponseStartedAt)) else 1ms) else 60s" comment="Wait for MD system response (60s total; interrupted immediately on response)">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
              <event_object_signalled object="this.ship" param="'GT_No_Trade_Found'"/>
              <!-- Duplicate request while MD search lock is still held:
                   MD responds with a non-backoff "still working" or "reset" signal to prevent AI cooldown escalation under fleet load. -->
              <event_object_signalled object="this.ship" param="'GT_TradeSearch_InProgress'"/>
              <event_object_signalled object="this.ship" param="'GT_TradeSearch_Reset'"/>
              <!-- New AI pipeline semaphore grant -->
              <event_object_signalled object="this.ship" param="'GT_Search_Go'"/>
            </check_any>
          </conditions>
          <actions>
            <do_if value="event.param == 'GT_Search_Go'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_Search_Go received at age ' + player.age + ' - queueing AI search pipeline'" chance="100"/>
              </do_if>
              <!-- Persist interrupt payload across wait/resume boundaries. -->
              <set_value name="this.$pendingSearchParams" exact="event.param2"/>
              <resume label="run_search_pipeline"/>
            </do_if>
            <do_elseif value="event.param == 'GT_Trade_Found'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_Trade_Found received at game time ' + player.age" chance="100"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade found by MD system - proceeding with execution'" chance="100"/>
              </do_if>
              <!-- Reset retry counter on successful trade -->
              <set_value name="this.$searchFailed" exact="0"/>
              <do_if value="global.$GT_IdleParkingReleased? and global.$GT_IdleParkingReleased.{this.ship}?">
                <remove_value name="global.$GT_IdleParkingReleased.{this.ship}"/>
              </do_if>
              <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
                <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>
                <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>
              </do_if>
              
              <!-- Clear per-ship no-trade attempt history on success (prevents stale attempts from polluting later reports) -->
              <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
                <remove_value name="global.$GT_NoTradeHistory.{this.ship}"/>
              </do_if>
              
              <!-- CARGO DISPOSAL: Reset cargo disposal failure counter on successful trade -->
              <do_if value="this.$cargoDisposalFailed?">
                <set_value name="this.$cargoDisposalFailed" exact="0"/>
              </do_if>
              
              <!-- Clear reroute flag (new destination found) -->
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Rerouting?">
                <remove_value name="global.$GT_Ships.{this.ship}.$Rerouting"/>
                
                <!-- Trigger ship rename to remove [REROUTE] state -->
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship, 
                    $pilot=this.ship.pilot, 
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
              </do_if>
              
              <resume label="trade_found"/>
            </do_elseif>
            <do_elseif value="event.param == 'GT_TradeSearch_InProgress'">
              <do_if value="not this.$waitForResponseStartedAt?">
                <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
              </do_if>
              <do_if value="(player.age - this.$waitForResponseStartedAt) ge 60s">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT after InProgress keepalives (60s) - aborting search and retrying'" chance="100"/>
                </do_if>
                <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
                <resume label="main_loop"/>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_TradeSearch_InProgress received at game time ' + player.age + ' - continuing to wait (no backoff)'" chance="100"/>
                </do_if>
                <resume label="wait_for_response_continue"/>
              </do_else>
            </do_elseif>
            <do_elseif value="event.param == 'GT_TradeSearch_Reset'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_TradeSearch_Reset received at game time ' + player.age + ' - retrying request immediately (no backoff)'" chance="100"/>
              </do_if>
              <resume label="main_loop"/>
            </do_elseif>
            <do_elseif value="event.param == 'GT_No_Trade_Found'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_No_Trade_Found received at age ' + player.age + ' (reason=' + (if event.param2? then event.param2 else '') + ')'" chance="100"/>
              </do_if>
              <!-- Capture reason (MD may pass param2='busy' for cache-search slots busy, etc.) -->
              <set_value name="this.$lastNoTradeReason" exact="if event.param2? and event.param2 != null then event.param2 else ''"/>
              <!-- Isolated mode is intra-sector by design; UR is not meaningful there. -->
              <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}? and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
                <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
              </do_if>
              <!-- ESCAPE FALLBACK:
                   If we are stuck in a blacklisted sector and got "no trade found", move toward home sector
                   (skipping blacklisted sectors along the route until we hit a non-blacklisted sector OR the home sector).
                   Whitelist overrides blacklist (matches GT_IsSectorBlacklisted). -->
              <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <set_value name="$validationWhitelist" exact="[]"/>
              <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
              </do_if>
              <set_value name="$currentSector" exact="this.ship.sector"/>
              <set_value name="$needsEscape" exact="false"/>
              <do_if value="$currentSector? and $currentSector.exists">
                <set_value name="$curWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                      <set_value name="$curWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $curWhitelisted">
                  <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$needsEscape" exact="$curActivityBL or $curTravelBL"/>
                </do_if>
              </do_if>
              <do_if value="$needsEscape">
                <!-- Set escape flag for ship naming -->
                <do_if value="global.$GT_Ships?">
                  <do_if value="not global.$GT_Ships.{this.ship}?">
                    <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
                </do_if>
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: No trade found while in blacklisted sector (' + @$currentSector.knownname + ') - moving toward home sector'" chance="100"/>
                </do_if>
                <resume label="escape_from_blacklisted"/>
              </do_if>
              
              <!-- Check if this is a cargo disposal attempt -->
              <set_value name="$isCargoDisposal" exact="false"/>
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
                <set_value name="$isCargoDisposal" exact="true"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': RECEIVED GT_No_Trade_Found signal - starting retry logic (cargo disposal: ' + $isCargoDisposal + ')'" chance="100"/>
              </do_if>
              <resume label="no_trade_retry"/>
            </do_elseif>
          </actions>
        </interrupt>
      </wait>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           TIMEOUT GUARD: If execution reaches here, the 60s wait expired WITHOUT
           any interrupt firing. The ship NEVER received GT_Search_Go from the
           semaphore. We MUST NOT fall through to run_search_pipeline â€” that would
           bypass the semaphore and allow unlimited concurrent live searches.
           Clean up the pending queue entry and retry with cooldown.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT: 60s expired without semaphore grant (GT_Search_Go) at game time ' + player.age + ' â€” cleaning up queue entry and retrying'" chance="100"/>
      </do_if>
      <!-- Remove this ship from the scheduler queue so it doesn't block the slot -->
      <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
      <resume label="no_trade_retry"/>

      <label name="run_search_pipeline"/>
      <set_value name="$searchParams" exact="if this.$pendingSearchParams? then this.$pendingSearchParams else null"/>
      <set_value name="this.$pendingSearchParams" exact="null"/>
      <!-- Belt-and-suspenders: verify $searchParams is a real table, not null.
           X4's '?' operator can return true for set_value-created variables even when null.
           Use typeof check to ensure we have actual search parameters from GT_Search_Go. -->
      <do_if value="typeof $searchParams == datatype.table">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Running AI search pipeline (semaphore-granted) at game time ' + player.age" chance="100"/>
        </do_if>

        <set_value name="$searchHome" exact="if $searchParams.$HomeBase? then @$searchParams.$HomeBase else (if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null))"/>
        <set_value name="$searchHomeSector" exact="if $searchParams.$HomeSector? then @$searchParams.$HomeSector else (if $searchHome? and $searchHome.isclass.sector then $searchHome else (if $searchHome? and $searchHome.sector? then @$searchHome.sector else this.ship.sector))"/>
        <set_value name="$searchMaxDistance" exact="if $searchParams.$MaxSell? then @$searchParams.$MaxSell else (if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $maxsell? then $maxsell else 1))"/>
        <set_value name="$searchWareBasket" exact="if $searchParams.$WareBasket? then @$searchParams.$WareBasket else $warebasket"/>
        <set_value name="$searchAllowIllegal" exact="if $searchParams.$AllowIllegal? then @$searchParams.$AllowIllegal else $gt_allowillegal"/>
        <set_value name="$searchEnforceRouteIllegalLegality" exact="if $searchParams.$EnforceRouteIllegalLegality? then @$searchParams.$EnforceRouteIllegalLegality else $gt_enforceRouteIllegalLegality"/>
        <set_value name="$searchIgnoreTradeRules" exact="if $searchParams.$IgnoreTradeRules? then @$searchParams.$IgnoreTradeRules else $effectiveIgnoreTradeRules"/>
        <!-- Defensive: $effectiveIgnorePlayerPricing is a v4-only local. Legacy saves resumed mid-attention
             may not have it (the per-script <patch> backfills only the this.$ instance var, not the local). -->
        <set_value name="$searchIgnorePlayerPricing" exact="if $searchParams.$IgnorePlayerPricing? then @$searchParams.$IgnorePlayerPricing else (if $effectiveIgnorePlayerPricing? then $effectiveIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false))"/>
        <set_value name="$searchIgnoreMK1Supply" exact="if $searchParams.$IgnoreMK1Supply? then @$searchParams.$IgnoreMK1Supply else $effectiveIgnoreMK1Supply"/>
        <set_value name="$searchIgnoreBuildStorage" exact="if $searchParams.$IgnoreBuildStorage? then @$searchParams.$IgnoreBuildStorage else $effectiveIgnoreBuildStorage"/>
        <set_value name="$searchIgnoreCarrierAux" exact="if $searchParams.$IgnoreCarrierAux? then @$searchParams.$IgnoreCarrierAux else $effectiveIgnoreCarrierAux"/>
        <set_value name="$searchFactionPriority" exact="if $searchParams.$FactionPriority? then @$searchParams.$FactionPriority else $gt_factionpriority"/>
        <set_value name="$searchMode" exact="if $searchParams.$SearchMode? then @$searchParams.$SearchMode else 'buy_and_sell'"/>
        <set_value name="$forceLiveSearch" exact="if $searchParams.$ForceLiveSearch? then @$searchParams.$ForceLiveSearch else false"/>
        <set_value name="$searchPhase" exact="if $searchParams.$Phase? then @$searchParams.$Phase else 'live'"/>
        <set_value name="$searchCacheReadOffset" exact="if $searchParams.$CacheReadOffset? then @$searchParams.$CacheReadOffset else 0"/>
        <set_value name="$skipCacheRead" exact="false"/>
        <set_value name="$mk3HomeCacheCount" exact="0"/>
        <do_if value="$searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCache? and global.$GT_TradeCache.{$searchHomeSector}?">
          <set_value name="$mk3HomeCacheCount" exact="@global.$GT_TradeCache.{$searchHomeSector}.count"/>
        </do_if>
        <!-- Only skip cache re-read when prior cache phase missed AND pool is still empty. -->
        <do_if value="$searchParams.$CachePhaseMiss? and $searchParams.$CachePhaseMiss and $mk3HomeCacheCount == 0">
          <set_value name="$skipCacheRead" exact="true"/>
        </do_if>
        <!-- live slot: force expensive live refresh only when pool is empty or explicitly requested. -->
        <do_if value="$searchPhase == 'live'">
          <do_if value="($searchParams.$ForceLiveSearch? and $searchParams.$ForceLiveSearch) or $mk3HomeCacheCount == 0">
            <set_value name="$forceLiveSearch" exact="true"/>
          </do_if>
          <do_else>
            <set_value name="$forceLiveSearch" exact="false"/>
          </do_else>
        </do_if>

        <!-- Derive minROI/minAbsoluteProfit from pilot skill level -->
        <set_value name="$searchMinROI" exact="0"/>
        <set_value name="$searchMinAbsoluteProfit" exact="0"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
          <!-- Higher skill pilots demand higher ROI -->
          <do_if value="$pilotLevel ge 5">
            <set_value name="$searchMinROI" exact="($pilotLevel - 4) * 2"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Trading? and global.$GT_GlobalSettings.$Trading.$MinAbsoluteProfit?">
          <set_value name="$searchMinAbsoluteProfit" exact="@global.$GT_GlobalSettings.$Trading.$MinAbsoluteProfit"/>
        </do_if>

        <!-- Priority wares change detection:
             only clear cache when an existing signature changed (real order-setup delta).
             First-time baseline initialization must not invalidate cache.
             Also folds in $effectiveIgnorePlayerPricing and $searchFactionPriority so toggling
             MK3 "Ignore Player Pricing" or faction priority invalidates cache entries produced
             under the old policy (scores bake faction bonus at write time). -->
        <set_value name="$ippTag" exact="if $searchIgnorePlayerPricing? and $searchIgnorePlayerPricing then '1' else '0'"/>
        <set_value name="$fpTag" exact="if $searchFactionPriority? then $searchFactionPriority else 0"/>
        <set_value name="$pwSig" exact="'0|' + (if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125) + '|IPP=' + $ippTag + '|FP=' + $fpTag"/>
        <do_if value="$effectivePriorityWares? and typeof $effectivePriorityWares == datatype.list and $effectivePriorityWares.count gt 0">
          <set_value name="$pwSig" exact="'' + $effectivePriorityWares.count + '|' + (if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125) + '|IPP=' + $ippTag + '|FP=' + $fpTag + '|'"/>
          <do_all exact="$effectivePriorityWares.count" counter="$pwi">
            <set_value name="$pw" exact="$effectivePriorityWares.{$pwi}"/>
            <set_value name="$pwSig" exact="$pwSig + (if $pwi gt 1 then ',' else '') + (if $pw? and $pw != null and $pw.id? then @$pw.id else '?')"/>
          </do_all>
        </do_if>
        <set_value name="$priorityWaresChanged" exact="this.$lastPriorityWaresSig? and this.$lastPriorityWaresSig != $pwSig"/>
        <do_if value="$priorityWaresChanged and $searchHomeSector? and $searchHomeSector.exists">
          <!-- Clear cache for this home sector only (triggers live search on next lookup) -->
          <do_if value="global.$GT_TradeCache? and global.$GT_TradeCache.{$searchHomeSector}?">
            <remove_value name="global.$GT_TradeCache.{$searchHomeSector}"/>
            <do_if value="global.$GT_TradeCacheByWare? and global.$GT_TradeCacheByWare.{$searchHomeSector}?">
              <remove_value name="global.$GT_TradeCacheByWare.{$searchHomeSector}"/>
            </do_if>
            <do_if value="global.$GT_TradeCacheMaxDistance? and global.$GT_TradeCacheMaxDistance.{$searchHomeSector}?">
              <remove_value name="global.$GT_TradeCacheMaxDistance.{$searchHomeSector}"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority wares changed - cleared cache for home sector ' + (if $searchHomeSector.knownname? then @$searchHomeSector.knownname else '?') + ' (next search will run live)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Always update baseline after evaluation (prevents false "changed" on first run/restart). -->
        <set_value name="this.$lastPriorityWaresSig" exact="$pwSig"/>
        <set_value name="this.$lastPriorityWaresHome" exact="$searchHomeSector"/>

        <!-- Resolve price range once for cache read purge + live search (mode/isolated/fallback/sell_only). -->
        <set_value name="$searchSellPriceMax" exact="1.0"/>
        <set_value name="$searchBuyPriceMin" exact="-1.0"/>
        <do_if value="global.$GT_Config? and global.$GT_Config.$Trading?">
          <do_if value="$searchMode? and $searchMode == 'sell_only'">
            <set_value name="$searchSellPriceMax" exact="if global.$GT_Config.$Trading.$FallbackSellPriceMax? then @global.$GT_Config.$Trading.$FallbackSellPriceMax else 1.0"/>
            <set_value name="$searchBuyPriceMin" exact="if global.$GT_Config.$Trading.$FallbackBuyPriceMin? then @global.$GT_Config.$Trading.$FallbackBuyPriceMin else -1.0"/>
          </do_if>
          <do_elseif value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?">
            <set_value name="$searchSellPriceMax" exact="if global.$GT_Config.$Trading.$IsolatedSellPriceMax? then @global.$GT_Config.$Trading.$IsolatedSellPriceMax else 1.0"/>
            <set_value name="$searchBuyPriceMin" exact="if global.$GT_Config.$Trading.$IsolatedBuyPriceMin? then @global.$GT_Config.$Trading.$IsolatedBuyPriceMin else -1.0"/>
          </do_elseif>
          <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
            <set_value name="$searchSellPriceMax" exact="if global.$GT_Config.$Trading.$FallbackSellPriceMax? then @global.$GT_Config.$Trading.$FallbackSellPriceMax else 1.0"/>
            <set_value name="$searchBuyPriceMin" exact="if global.$GT_Config.$Trading.$FallbackBuyPriceMin? then @global.$GT_Config.$Trading.$FallbackBuyPriceMin else -1.0"/>
          </do_elseif>
          <do_else>
            <set_value name="$searchSellPriceMax" exact="if global.$GT_Config.$Trading.$SellPriceMax? then @global.$GT_Config.$Trading.$SellPriceMax else 1.0"/>
            <set_value name="$searchBuyPriceMin" exact="if global.$GT_Config.$Trading.$BuyPriceMin? then @global.$GT_Config.$Trading.$BuyPriceMin else -1.0"/>
          </do_else>
        </do_if>
        <set_value name="$searchBypassPlayerSellerPricing" exact="if $searchIgnorePlayerPricing? then $searchIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false)"/>

        <!-- Phase 1 (cache-only): run lightweight cache lookup and return control to scheduler.
             sell_only clearance is live-only (scheduler never dispatches cache for it). -->
        <do_if value="$searchPhase == 'cache'">
          <set_value name="$cacheFoundOnlyResult" exact="null"/>
          <set_value name="$cacheFoundOnly" exact="false"/>
          <set_value name="$cacheFoundOnlyTradeList" exact="[]"/>
          <set_value name="$cachePhaseSkipped" exact="not ($searchMode? and not $forceLiveSearch) or ($searchMode? and $searchMode == 'sell_only')"/>
          <do_if value="not $cachePhaseSkipped">
            <run_script name="'lib.gt.cache.search'" result="$cacheFoundOnlyResult">
              <param name="ship" value="this.ship"/>
              <param name="searchMode" value="$searchMode"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchMaxDistance"/>
              <param name="wareBasket" value="$searchWareBasket"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
              <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else (if this.$gt_cargotarget? then this.$gt_cargotarget else 80))"/>
              <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
              <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
              <param name="requireNonPlayerDeliveryStation" value="if $searchIgnorePlayerPricing? then $searchIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false)"/>
              <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
              <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
              <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
              <param name="sellPriceMax" value="$searchSellPriceMax"/>
              <param name="buyPriceMin" value="$searchBuyPriceMin"/>
              <param name="bypassPlayerSellerPricing" value="$searchBypassPlayerSellerPricing"/>
              <param name="ignoreTradeRules" value="$searchIgnoreTradeRules"/>
              <param name="cacheReadOffset" value="$searchCacheReadOffset"/>
              <param name="distancePenalty" value="if $gt_distancepenalty? then $gt_distancepenalty else (if this.$effectiveDistancePenalty? then (this.$effectiveDistancePenalty / 50.0) else 0.1)"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
            </run_script>
            <set_value name="this.$lastCacheReadOffset" exact="$searchCacheReadOffset"/>
            <do_if value="$cacheFoundOnlyResult? and $cacheFoundOnlyResult.$Found?">
              <set_value name="$cacheFoundOnly" exact="@$cacheFoundOnlyResult.$Found"/>
            </do_if>
            <do_if value="$cacheFoundOnly and $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$TradeList?">
              <set_value name="$cacheFoundOnlyTradeList" exact="@$cacheFoundOnlyResult.$TradeList"/>
            </do_if>
            <!-- Pool has entries but this ship got zero: clear stale per-ship failure flags. -->
            <set_value name="$cacheMissPoolCount" exact="if $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$PoolSizeAfter? then @$cacheFoundOnlyResult.$PoolSizeAfter else $mk3HomeCacheCount"/>
            <do_if value="not $cacheFoundOnly and $cacheMissPoolCount gt 0 and $searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCache? and global.$GT_TradeCache.{$searchHomeSector}?">
              <do_all exact="global.$GT_TradeCache.{$searchHomeSector}.count" counter="$cacheMissFsi">
                <set_value name="$cacheMissEntry" exact="global.$GT_TradeCache.{$searchHomeSector}.{$cacheMissFsi}"/>
                <do_if value="$cacheMissEntry? and $cacheMissEntry.$FailedShips? and $cacheMissEntry.$FailedShips.count gt 0">
                  <set_value name="$cacheMissNewFailed" exact="[]"/>
                  <do_all exact="$cacheMissEntry.$FailedShips.count" counter="$cacheMissFsi2">
                    <do_if value="$cacheMissEntry.$FailedShips.{$cacheMissFsi2} != this.ship">
                      <append_to_list name="$cacheMissNewFailed" exact="$cacheMissEntry.$FailedShips.{$cacheMissFsi2}"/>
                    </do_if>
                  </do_all>
                  <set_value name="$cacheMissEntry.$FailedShips" exact="$cacheMissNewFailed"/>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$cachePhaseCount" exact="if $cacheFoundOnlyTradeList? then $cacheFoundOnlyTradeList.count else 0"/>
            <set_value name="$cachePhaseOutcome" exact="if $cachePhaseSkipped then 'SKIP' else (if $cacheFoundOnly then 'HIT' else 'MISS')"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache phase ' + $cachePhaseOutcome + ' (mode=' + $searchMode + ', trades=' + $cachePhaseCount + ', home=' + (if $searchHomeSector? and $searchHomeSector.exists then $searchHomeSector.knownname else 'null') + ')'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Done'" param2="table[
            $Ship = this.ship,
            $Found = $cacheFoundOnly,
            $TradeList = $cacheFoundOnlyTradeList,
            $SearchMethod = 'cache',
            $SearchType = 'cache',
            $HomeSector = $searchHomeSector,
            $PoolSizeAfter = if $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$PoolSizeAfter? then @$cacheFoundOnlyResult.$PoolSizeAfter else (if $searchHomeSector? and global.$GT_TradeCache? and global.$GT_TradeCache.{$searchHomeSector}? then @global.$GT_TradeCache.{$searchHomeSector}.count else 0)
          ]"/>
          <resume label="wait_for_response"/>
        </do_if>

        <set_value name="$pipelineFound" exact="false"/>
        <set_value name="$pipelineTradeList" exact="[]"/>
        <set_value name="$pipelineSearchMethod" exact="'live'"/>
        <set_value name="$cacheSearchResult" exact="null"/>
        <set_value name="$cacheFound" exact="false"/>
        <do_if value="$searchMode? and not $forceLiveSearch and not $skipCacheRead and not ($searchMode == 'sell_only')">
          <!-- 1) Cache path -->
          <run_script name="'lib.gt.cache.search'" result="$cacheSearchResult">
            <param name="ship" value="this.ship"/>
            <param name="searchMode" value="$searchMode"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchMaxDistance"/>
            <param name="wareBasket" value="$searchWareBasket"/>
            <param name="minROI" value="$searchMinROI"/>
            <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
            <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else (if this.$gt_cargotarget? then this.$gt_cargotarget else 80))"/>
            <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
            <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
            <param name="requireNonPlayerDeliveryStation" value="if $searchIgnorePlayerPricing? then $searchIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false)"/>
            <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
            <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
            <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
            <param name="sellPriceMax" value="$searchSellPriceMax"/>
            <param name="buyPriceMin" value="$searchBuyPriceMin"/>
            <param name="bypassPlayerSellerPricing" value="$searchBypassPlayerSellerPricing"/>
            <param name="ignoreTradeRules" value="$searchIgnoreTradeRules"/>
            <param name="cacheReadOffset" value="$searchCacheReadOffset"/>
            <param name="distancePenalty" value="if $gt_distancepenalty? then $gt_distancepenalty else (if this.$effectiveDistancePenalty? then (this.$effectiveDistancePenalty / 50.0) else 0.1)"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <set_value name="this.$lastCacheReadOffset" exact="$searchCacheReadOffset"/>
        </do_if>
        <!-- SAVEGAME GUARD: If save/load interrupted the run_script above, all locals are lost.
             Detect and bail to retry instead of cascading property lookup errors. -->
        <do_if value="not $searchMode?">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>
        <do_if value="$cacheSearchResult?">
          <do_if value="$cacheSearchResult.$Found?">
            <set_value name="$cacheFound" exact="@$cacheSearchResult.$Found"/>
          </do_if>
        </do_if>
        <do_if value="$cacheFound">
          <set_value name="$pipelineFound" exact="true"/>
          <set_value name="$pipelineSearchMethod" exact="'cache'"/>
          <set_value name="$pipelineTradeList" exact="if $cacheSearchResult.$TradeList? then @$cacheSearchResult.$TradeList else []"/>
        </do_if>
        <do_else>
          <!-- 2) Pathfinding -->
          <run_script name="'lib.gt.pathfinding'" result="$pathResult">
            <param name="ship" value="this.ship"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchMaxDistance"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <!-- SAVEGAME GUARD -->
          <do_if value="not $searchMode?">
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
            <resume label="no_trade_retry"/>
          </do_if>

          <!-- 3) Live offers -->
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PriceRange: SellPriceMax=' + $searchSellPriceMax + ' BuyPriceMin=' + $searchBuyPriceMin" chance="@this.$debugchance"/>
          <run_script name="'lib.gt.live.search'" result="$liveResult">
            <param name="ship" value="this.ship"/>
            <param name="searchMode" value="$searchMode"/>
            <param name="buySpaces" value="$pathResult.$BuySpaces"/>
            <param name="sellSpaces" value="$pathResult.$SellSpaces"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchMaxDistance"/>
            <param name="wareBasket" value="$searchWareBasket"/>
            <param name="allowIllegal" value="$searchAllowIllegal"/>
            <param name="ownerFilter" value="'any'"/>
            <param name="ignoreMK1Supply" value="$searchIgnoreMK1Supply"/>
            <param name="ignoreTradeRules" value="$searchIgnoreTradeRules"/>
            <param name="maxOffersPerWare" value="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
            <param name="sellPriceMax" value="$searchSellPriceMax"/>
            <param name="buyPriceMin" value="$searchBuyPriceMin"/>
            <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
            <param name="bypassPlayerSellerPricing" value="$searchBypassPlayerSellerPricing"/>
            <param name="excludePlayerBuyers" value="$searchBypassPlayerSellerPricing"/>
            <param name="searchPurpose" value="if $searchMode? and $searchMode == 'sell_only' then 'direct_live' else 'cache_refresh'"/>
            <param name="cargoTargetPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 80)"/>
            <param name="debugchance" value="@this.$debugchance"/>
          </run_script>
          <!-- SAVEGAME GUARD -->
          <do_if value="not $searchMode?">
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
            <resume label="no_trade_retry"/>
          </do_if>

          <do_if value="$searchMode? and $searchMode == 'sell_only'">
            <create_list name="$sellOnlyTrades"/>
            <set_value name="$liveBuyOffers" exact="[]"/>
            <do_if value="$liveResult?">
              <do_if value="$liveResult.$BuyOffers?">
                <set_value name="$liveBuyOffers" exact="@$liveResult.$BuyOffers"/>
              </do_if>
            </do_if>
            <do_if value="$liveBuyOffers.count gt 0">
              <do_all exact="$liveBuyOffers.count" counter="$offerIdx">
                <set_value name="$sellOffer" exact="$liveBuyOffers.{$offerIdx}"/>
                <set_value name="$sellWare" exact="if $sellOffer? and $sellOffer.ware? then @$sellOffer.ware else null"/>
                <do_if value="not $sellWare?">
                  <continue/>
                </do_if>

                <set_value name="$shipWareAmount" exact="this.ship.cargo.{$sellWare}.count"/>
                <set_value name="$tradeAmount" exact="[$shipWareAmount, $sellOffer.amount].min"/>
                <do_if value="$tradeAmount le 0">
                  <continue/>
                </do_if>

                <set_value name="$sellDistance" exact="$searchHomeSector.gatedistance.{$sellOffer.owner}"/>
                <do_if value="$sellDistance lt 0 or $sellDistance gt $searchMaxDistance">
                  <continue/>
                </do_if>

                <set_value name="$distanceFactor" exact="1.0 + ($sellDistance * $gt_distancepenalty)"/>
                <set_value name="$sellUnitPriceCr" exact="($sellOffer.unitprice / 1Cr)i"/>
                <set_value name="$sellScore" exact="($tradeAmount * [$sellUnitPriceCr, 1].max) / $distanceFactor"/>
                <append_to_list name="$sellOnlyTrades" exact="table[
                  $IsSellOnly = true,
                  $Ware = $sellWare,
                  $SellOffer = $sellOffer,
                  $SellStation = $sellOffer.owner,
                  $Amount = $tradeAmount,
                  $Score = $sellScore,
                  $BuyStation = this.ship,
                  $BuySector = this.ship.sector,
                  $Distance = $sellDistance,
                  $UnitProfit = $sellOffer.unitprice,
                  $BuyPrice = 0,
                  $SellPrice = $sellOffer.unitprice,
                  $ProfitPerUnit = $sellOffer.unitprice,
                  $Profit = ($sellOffer.unitprice * $tradeAmount)
                ]"/>
              </do_all>
              <!-- AI locals do not survive waits inside do_all loops; yield once after the batch. -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
            </do_if>

            <run_script name="'lib.gt.score.trades'" result="$scoreResult">
              <param name="tradeList" value="$sellOnlyTrades"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125"/>
            </run_script>
            <set_value name="$pipelineSearchMethod" exact="'live_sell_only'"/>
            <set_value name="$scoreFound" exact="false"/>
            <do_if value="$scoreResult?">
              <do_if value="$scoreResult.$Found?">
                <set_value name="$scoreFound" exact="@$scoreResult.$Found"/>
              </do_if>
            </do_if>
            <do_if value="$scoreFound">
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $scoreResult.$SortedTrades? then @$scoreResult.$SortedTrades else []"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- 4) Trade matching -->
            <run_script name="'lib.gt.tradematch'" result="$matchResult">
              <param name="ship" value="this.ship"/>
              <param name="sellOffers" value="$liveResult.$SellOffers"/>
              <param name="buyOffers" value="$liveResult.$BuyOffers"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchMaxDistance"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
              <param name="distancePenalty" value="$gt_distancepenalty"/>
              <param name="factionPriority" value="$searchFactionPriority"/>
              <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
              <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
              <param name="allowIllegal" value="$searchAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$searchEnforceRouteIllegalLegality"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="scoreMode" value="'sell'"/>
              <param name="excludePlayerBuyers" value="if $searchIgnorePlayerPricing? then $searchIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false)"/>
              <param name="playerSupplierFreeProduction" value="if $searchIgnorePlayerPricing? then $searchIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false)"/>
            </run_script>
            <!-- SAVEGAME GUARD -->
            <do_if value="not $searchMode?">
              <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
              <resume label="no_trade_retry"/>
            </do_if>

            <!-- 4b) Executable filter (trade_found parity) before scoring. -->
            <set_value name="$matchTradeListRaw" exact="[]"/>
            <do_if value="$matchResult? and $matchResult.$TradeList?">
              <set_value name="$matchTradeListRaw" exact="@$matchResult.$TradeList"/>
            </do_if>
            <set_value name="$execCargoUtilPct" exact="[10,[(if this.$gt_cargotarget? then this.$gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 80)), 100].min].max"/>
            <set_value name="$execIsIsolated" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
            <set_value name="$execApplyCargoUtil" exact="not $execIsIsolated"/>
            <set_value name="$execFilterPassLabel" exact="'pre-score'"/>
            <set_value name="$matchBeforeExecFilter" exact="$matchTradeListRaw.count"/>
            <create_list name="$matchTradeList"/>
            <do_if value="$matchTradeListRaw.count gt 0">
              <do_all exact="$matchTradeListRaw.count" counter="$execIdx">
                <set_value name="$execTrade" exact="$matchTradeListRaw.{$execIdx}"/>
                <set_value name="$execKeep" exact="false"/>
                <set_value name="$execIsSellOnly" exact="$execTrade.$IsSellOnly? and $execTrade.$IsSellOnly"/>
                <do_if value="$execIsSellOnly and $execTrade.$SellOffer? and $execTrade.$Amount? and $execTrade.$Amount gt 0">
                  <set_value name="$execSellAmt" exact="$execTrade.$Amount"/>
                  <set_value name="$execSellReason" exact="null"/>
                  <set_value name="$execSellBuyer" exact="null"/>
                  <do_if value="$execTrade.$SellOffer.buyer?">
                    <set_value name="$execSellBuyer" exact="@$execTrade.$SellOffer.buyer"/>
                  </do_if>
                  <do_if value="$execSellBuyer == null and $execTrade.$SellOffer.owner?">
                    <set_value name="$execSellBuyer" exact="@$execTrade.$SellOffer.owner"/>
                  </do_if>
                  <do_if value="$execSellBuyer != null">
                    <clamp_trade_amount trade="$execTrade.$SellOffer" amount="$execSellAmt" buyer="$execSellBuyer" seller="this.assignedcontrolled" result="$execSellAmt" reason="$execSellReason"/>
                    <do_if value="$execSellAmt? and $execSellAmt gt 0">
                      <set_value name="$execTrade.$Amount" exact="$execSellAmt"/>
                      <set_value name="$execKeep" exact="true"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_elseif value="$execTrade? and $execTrade.$BuyOffer? and $execTrade.$SellOffer? and $execTrade.$Amount? and $execTrade.$Amount gt 0">
                  <set_value name="$execBuyAmt" exact="$execTrade.$Amount"/>
                  <set_value name="$execSellAmt" exact="$execTrade.$Amount"/>
                  <set_value name="$execBuyReason" exact="null"/>
                  <set_value name="$execSellReason" exact="null"/>
                  <set_value name="$execBuySeller" exact="null"/>
                  <do_if value="$execTrade.$BuyOffer.seller?">
                    <set_value name="$execBuySeller" exact="@$execTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_if value="$execBuySeller == null and $execTrade.$BuyOffer.owner?">
                    <set_value name="$execBuySeller" exact="@$execTrade.$BuyOffer.owner"/>
                  </do_if>
                  <do_if value="$execBuySeller != null">
                    <clamp_trade_amount trade="$execTrade.$BuyOffer" amount="$execBuyAmt" buyer="this.assignedcontrolled" seller="$execBuySeller" result="$execBuyAmt" reason="$execBuyReason"/>
                  </do_if>
                  <do_if value="$execBuyAmt? and $execBuyAmt gt 0">
                    <set_value name="$execSellBuyer" exact="null"/>
                    <do_if value="$execTrade.$SellOffer.buyer?">
                      <set_value name="$execSellBuyer" exact="@$execTrade.$SellOffer.buyer"/>
                    </do_if>
                    <do_if value="$execSellBuyer == null and $execTrade.$SellOffer.owner?">
                      <set_value name="$execSellBuyer" exact="@$execTrade.$SellOffer.owner"/>
                    </do_if>
                    <do_if value="$execSellBuyer != null">
                      <clamp_trade_amount trade="$execTrade.$SellOffer" amount="$execSellAmt" buyer="$execSellBuyer" result="$execSellAmt" reason="$execSellReason"/>
                    </do_if>
                  </do_if>
                  <do_if value="$execBuyAmt? and $execBuyAmt gt 0 and $execSellAmt? and $execSellAmt gt 0">
                    <set_value name="$execFinalAmt" exact="[$execBuyAmt, $execSellAmt].min"/>
                    <do_if value="$execFinalAmt gt 0">
                      <set_value name="$execPassCargoUtil" exact="true"/>
                      <do_if value="$execApplyCargoUtil">
                        <set_value name="$execUtilWare" exact="if $execTrade.$Ware? then $execTrade.$Ware else (if $execTrade.$BuyOffer.ware? then @$execTrade.$BuyOffer.ware else null)"/>
                        <set_value name="$execVolPerUnit" exact="if $execUtilWare? and $execUtilWare.volume? and $execUtilWare.volume gt 0 then $execUtilWare.volume else 1"/>
                        <set_value name="$execTradeVol" exact="$execFinalAmt * $execVolPerUnit"/>
                        <set_value name="$execRequiredVol" exact="(this.ship.cargo.capacity.all * $execCargoUtilPct) / 100.0"/>
                        <set_value name="$execIsPriorityWare" exact="false"/>
                        <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0 and $execUtilWare?">
                          <do_all exact="$effectivePriorityWares.count" counter="$execPwi">
                            <do_if value="$effectivePriorityWares.{$execPwi} == $execUtilWare">
                              <set_value name="$execIsPriorityWare" exact="true"/>
                              <break/>
                            </do_if>
                          </do_all>
                        </do_if>
                        <do_if value="$execTradeVol lt $execRequiredVol and not $execIsPriorityWare">
                          <set_value name="$execPassCargoUtil" exact="false"/>
                        </do_if>
                      </do_if>
                      <do_if value="$execPassCargoUtil and $execTrade.$BuyOffer.unitprice? and $execTrade.$SellOffer.unitprice?">
                        <set_value name="$execPfs" exact="$execTrade.$PlayerFreeSupplier? and $execTrade.$PlayerFreeSupplier"/>
                        <set_value name="$execProfitRaw" exact="if $execPfs then ($execTrade.$SellOffer.unitprice * $execFinalAmt) else (($execTrade.$SellOffer.unitprice - $execTrade.$BuyOffer.unitprice) * $execFinalAmt)"/>
                        <do_if value="$execProfitRaw gt 0">
                          <set_value name="$execTrade.$Amount" exact="$execFinalAmt"/>
                          <set_value name="$execTrade.$Profit" exact="$execProfitRaw"/>
                          <set_value name="$execKeep" exact="true"/>
                        </do_if>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_elseif>
                <do_if value="$execKeep">
                  <append_to_list name="$matchTradeList" exact="$execTrade"/>
                </do_if>
              </do_all>
              <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after executable filter batch"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $matchBeforeExecFilter gt 0">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Executable filter (' + $execFilterPassLabel + '): before=' + $matchBeforeExecFilter + ', after=' + $matchTradeList.count + ', removed=' + ($matchBeforeExecFilter - $matchTradeList.count)" chance="100"/>
            </do_if>

            <!-- 5a) Ship-route ranking for this ship (unified consumer Target B). -->
            <set_value name="$liveRouteMaxEntries" exact="50"/>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries?">
              <set_value name="$liveRouteMaxEntries" exact="@global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries"/>
            </do_if>
            <set_value name="$liveRouteDistPenalty" exact="if $gt_distancepenalty? then ($gt_distancepenalty / 50.0) else (if this.$effectiveDistancePenalty? then (this.$effectiveDistancePenalty / 50.0) else 0.1)"/>
            <run_script name="'lib.gt.cache.score_for_ship'" result="$shipRouteScoreResult">
              <param name="tradeList" value="$matchTradeList"/>
              <param name="ship" value="this.ship"/>
              <param name="distancePenalty" value="$liveRouteDistPenalty"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="maxEntries" value="$liveRouteMaxEntries"/>
              <param name="debugchance" value="@this.$debugchance"/>
            </run_script>
            <set_value name="$shipRouteTradeList" exact="[]"/>
            <do_if value="$shipRouteScoreResult? and $shipRouteScoreResult.$SortedTrades?">
              <set_value name="$shipRouteTradeList" exact="@$shipRouteScoreResult.$SortedTrades"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $shipRouteTradeList.count gt 0">
              <set_value name="$liveRouteTopScore" exact="if $shipRouteScoreResult? and $shipRouteScoreResult.$BestScore? then @$shipRouteScoreResult.$BestScore else 0"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Live ship-route scored ' + $shipRouteTradeList.count + ' trades (top ShipScore=' + $liveRouteTopScore + ', pool=' + $matchTradeList.count + ')'" chance="100"/>
            </do_if>

            <!-- 5b) Cache refresh: write all executable survivors; strip per-ship fields on insert (LC2/LC4). -->
            <do_if value="$matchTradeList.count gt 0">
              <run_script name="'lib.gt.cache.write'" result="$liveCacheWriteResult">
                <param name="tradeList" value="$matchTradeList"/>
                <param name="homeSector" value="$searchHomeSector"/>
                <param name="cacheTTL" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
                <param name="maxSearchDistance" value="$searchMaxDistance"/>
                <param name="sellPriceMax" value="$searchSellPriceMax"/>
                <param name="buyPriceMin" value="$searchBuyPriceMin"/>
                <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
              </run_script>
            </do_if>

            <!-- 5c) Priority wares + diversify on ship-route list (home $Score unchanged on rows). -->
            <run_script name="'lib.gt.score.trades'" result="$scoreResult">
              <param name="tradeList" value="$shipRouteTradeList"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125"/>
              <param name="diversifyByWare" value="true"/>
              <param name="useShipRouteScore" value="true"/>
            </run_script>

            <set_value name="$pipelineSearchMethod" exact="'live_ship_route'"/>
            <set_value name="$scoreFound" exact="false"/>
            <do_if value="$scoreResult?">
              <do_if value="$scoreResult.$Found?">
                <set_value name="$scoreFound" exact="@$scoreResult.$Found"/>
              </do_if>
            </do_if>
            <do_if value="$scoreFound">
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $scoreResult.$SortedTrades? then @$scoreResult.$SortedTrades else []"/>
            </do_if>
          </do_else>
        </do_else>

        <!-- Savegame compatibility: local pipeline vars can be missing on migrated/running states.
             Normalize them before any unconditional reads below. -->
        <do_if value="not $pipelineFound?">
          <set_value name="$pipelineFound" exact="false"/>
        </do_if>
        <do_if value="not $pipelineTradeList?">
          <set_value name="$pipelineTradeList" exact="[]"/>
        </do_if>
        <do_if value="not $pipelineSearchMethod?">
          <set_value name="$pipelineSearchMethod" exact="'live'"/>
        </do_if>

        <!-- Cap MK3 validation list to MaxTradesToReturn (MK4 still uses this setting on its order).
             Cache write uses full executable survivor set above; not capped by MaxTradesToReturn. -->
        <set_value name="$maxTradesReturn" exact="20"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn?">
          <set_value name="$maxTradesReturn" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn"/>
        </do_if>
        <do_if value="$maxTradesReturn lt 1">
          <set_value name="$maxTradesReturn" exact="1"/>
        </do_if>
        <do_if value="$pipelineTradeList.count gt $maxTradesReturn">
          <create_list name="$pipelineTradeListCapped"/>
          <do_all exact="$maxTradesReturn" counter="$mtrCap">
            <append_to_list name="$pipelineTradeListCapped" exact="$pipelineTradeList.{$mtrCap}"/>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListCapped"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Capped trade list to MaxTradesToReturn=' + $maxTradesReturn" chance="100"/>
          </do_if>
        </do_if>

        <!-- SAVEGAME GUARD -->
        <do_if value="not $pipelineFound?">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
             FALLBACK SEARCH: When normal pipeline yields no trades, attempt a fallback
             search with relaxed parameters before giving up.
             See lib.gt.fallback.search.xml for the full pipeline (pathfinding / live /
             tradematch / scoring with relaxed params, centered on ship position).
             â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
        <do_if value="not $pipelineFound and $searchMode? and $searchMode == 'buy_and_sell'">
          <!-- Check conditions: not isolated, not already in fallback -->
          <set_value name="$isIsolated" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
          <set_value name="$isFallbackAlready" exact="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?"/>

          <do_if value="not $isIsolated and not $isFallbackAlready">
            <run_script name="'lib.gt.fallback.search'" result="$fallbackResult">
              <param name="ship" value="this.ship"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchMaxDistance"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="distancePenalty" value="$gt_distancepenalty"/>
              <param name="factionPriority" value="$searchFactionPriority"/>
              <param name="wareBasket" value="$searchWareBasket"/>
              <param name="allowIllegal" value="$searchAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$searchEnforceRouteIllegalLegality"/>
              <param name="ignoreMK1Supply" value="$searchIgnoreMK1Supply"/>
              <param name="ignoreTradeRules" value="$searchIgnoreTradeRules"/>
              <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
              <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="debugchance" value="@this.$debugchance"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125"/>
              <param name="ignorePlayerPricing" value="if $searchIgnorePlayerPricing? then $searchIgnorePlayerPricing else (if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false)"/>
            </run_script>
            <!-- SAVEGAME GUARD -->
            <do_if value="not $searchMode?">
              <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
              <resume label="no_trade_retry"/>
            </do_if>

            <do_if value="$fallbackResult? and $fallbackResult.$Found">
              <!-- FALLBACK SUCCESS: update pipeline (flag is set only when trade is actually created from fallback) -->
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $fallbackResult.$TradeList? then @$fallbackResult.$TradeList else []"/>
              <set_value name="$pipelineSearchMethod" exact="'live_fallback'"/>

              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FALLBACK SUCCESS: Found ' + $pipelineTradeList.count + ' trades with relaxed parameters (flag will be set only if selected trade is created).'" chance="100"/>
              </do_if>

              <!-- Logbook entry for fallback activation -->
              <do_if value="$gt_logbookentries">
                <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
                <do_if value="not $sectorName?">
                  <set_value name="$sectorName" exact="'Unknown Sector'"/>
                </do_if>
                <set_value name="$fallbackMaxDistance" exact="if $fallbackResult.$FallbackMaxDistance? then $fallbackResult.$FallbackMaxDistance else 1"/>
                <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                  $Message = 'Commander,\n\nNormal search found no trades. Falling back to nearby search.\n\nShip: ' + this.ship.knownname + '\nSector: ' + $sectorName + '\nNormal range: ' + $searchMaxDistance + ' jump(s)\nFallback range: ' + $fallbackMaxDistance + ' jump(s) from current position\nPrice filter relaxed to fallback settings.\n\nStanding by,\nAboard ' + this.ship.knownname,
                  $Category = 'alerts',
                  $Title = 'Fallback Search: ' + this.ship.knownname,
                  $Object = this.ship,
                  $Interaction = 'showonmap',
                  $CheckGlobalSettings = true
                ]"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FALLBACK SEARCH: No trades found even with relaxed parameters. Proceeding to no_trade_retry.'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FALLBACK SEARCH skipped: isIsolated=' + $isIsolated + ' isFallbackAlready=' + $isFallbackAlready" chance="100"/>
            </do_if>
          </do_else>
        </do_if>

        <!-- Final pipeline result check -->
        <do_if value="not $pipelineFound">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- Per-order blocked station filter:
             Drop trades touching stations selected in the MK3 setup before validation. -->
        <set_value name="$blockedStationsDispatch" exact="if $effectiveBlockedStations? then $effectiveBlockedStations else (if this.$effectiveBlockedStations? then this.$effectiveBlockedStations else [])"/>
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and $blockedStationsDispatch? and $blockedStationsDispatch.count gt 0">
          <set_value name="$pipelineTradeListBeforeStationFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListStationFiltered"/>
          <do_all exact="$pipelineTradeList.count" counter="$stationFilterIdx">
            <set_value name="$stationFilterTrade" exact="$pipelineTradeList.{$stationFilterIdx}"/>
            <set_value name="$stationFilterKeepTrade" exact="true"/>
            <set_value name="$stationFilterIsSellOnly" exact="false"/>
            <set_value name="$stationFilterBuyStation" exact="null"/>
            <set_value name="$stationFilterSellStation" exact="null"/>
            <do_if value="$stationFilterTrade?">
              <do_if value="$stationFilterTrade.$IsSellOnly?">
                <set_value name="$stationFilterIsSellOnly" exact="$stationFilterTrade.$IsSellOnly"/>
              </do_if>
            </do_if>

            <do_if value="$stationFilterTrade? and not $stationFilterIsSellOnly">
              <do_if value="$stationFilterTrade.$BuyStation?">
                <set_value name="$stationFilterBuyStation" exact="$stationFilterTrade.$BuyStation"/>
              </do_if>
              <do_else>
                <do_if value="$stationFilterTrade.$BuyOffer?">
                  <do_if value="$stationFilterTrade.$BuyOffer.owner?">
                    <set_value name="$stationFilterBuyStation" exact="@$stationFilterTrade.$BuyOffer.owner"/>
                  </do_if>
                </do_if>
              </do_else>
            </do_if>
            <do_if value="$stationFilterTrade?">
              <do_if value="$stationFilterTrade.$SellStation?">
                <set_value name="$stationFilterSellStation" exact="$stationFilterTrade.$SellStation"/>
              </do_if>
              <do_else>
                <do_if value="$stationFilterTrade.$SellOffer?">
                  <do_if value="$stationFilterTrade.$SellOffer.owner?">
                    <set_value name="$stationFilterSellStation" exact="@$stationFilterTrade.$SellOffer.owner"/>
                  </do_if>
                </do_if>
              </do_else>
            </do_if>

            <do_all exact="$blockedStationsDispatch.count" counter="$stationBlockIdx">
              <set_value name="$stationBlockItem" exact="$blockedStationsDispatch.{$stationBlockIdx}"/>
              <do_if value="$stationBlockItem? and (($stationFilterBuyStation? and $stationFilterBuyStation == $stationBlockItem) or ($stationFilterSellStation? and $stationFilterSellStation == $stationBlockItem))">
                <set_value name="$stationFilterKeepTrade" exact="false"/>
                <break/>
              </do_if>
            </do_all>

            <do_if value="$stationFilterKeepTrade">
              <append_to_list name="$pipelineTradeListStationFiltered" exact="$stationFilterTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListStationFiltered"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Dispatch blocked-station filter: before=' + $pipelineTradeListBeforeStationFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineTradeListBeforeStationFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Per-ship dispatch filter:
             Keep cache content faction-agnostic for reuse by other fleets/ships,
             but remove blocked-faction entries from the list sent to validation. -->
        <set_value name="$mk3BlacklistOwnerDispatch" exact="this.ship"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
          <set_value name="$mk3BlacklistOwnerDispatch" exact="this.ship.commander"/>
        </do_if>
        <set_value name="$mk3FactionBlacklistDispatch" exact="table[]"/>
        <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerDispatch}?">
          <set_value name="$mk3FactionBlacklistDispatch" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerDispatch}"/>
        </do_if>
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and $mk3FactionBlacklistDispatch.keys.count gt 0">
          <set_value name="$pipelineTradeListBeforeDispatchFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListFiltered"/>
          <do_all exact="$pipelineTradeList.count" counter="$dispatchIdx">
            <set_value name="$dispatchTrade" exact="$pipelineTradeList.{$dispatchIdx}"/>
            <set_value name="$dispatchKeepTrade" exact="true"/>

            <do_if value="$dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly) and $dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.owner?">
              <set_value name="$dispatchBuyOwnerContainer" exact="@$dispatchTrade.$BuyOffer.owner"/>
              <set_value name="$dispatchBuyFaction" exact="null"/>
              <do_if value="$dispatchBuyOwnerContainer.owner?">
                <set_value name="$dispatchBuyFaction" exact="$dispatchBuyOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$dispatchBuyFaction" exact="$dispatchBuyOwnerContainer"/>
              </do_else>
              <do_if value="$dispatchBuyFaction? and $mk3FactionBlacklistDispatch.{$dispatchBuyFaction}?">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and $dispatchTrade.$SellOffer? and $dispatchTrade.$SellOffer.owner?">
              <set_value name="$dispatchSellOwnerContainer" exact="@$dispatchTrade.$SellOffer.owner"/>
              <set_value name="$dispatchSellFaction" exact="null"/>
              <do_if value="$dispatchSellOwnerContainer.owner?">
                <set_value name="$dispatchSellFaction" exact="$dispatchSellOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$dispatchSellFaction" exact="$dispatchSellOwnerContainer"/>
              </do_else>
              <do_if value="$dispatchSellFaction? and $mk3FactionBlacklistDispatch.{$dispatchSellFaction}?">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade">
              <append_to_list name="$pipelineTradeListFiltered" exact="$dispatchTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListFiltered"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Dispatch MK3 faction filter: before=' + $pipelineTradeListBeforeDispatchFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineTradeListBeforeDispatchFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Live search can run 1+ seconds. Re-check per-ship offer amounts immediately before dispatch
             so trades reserved/exhausted during matching are not sent to expensive validation. -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ($pipelineSearchMethod == 'live_ship_route' or $pipelineSearchMethod == 'live_sell_only' or $pipelineSearchMethod == 'live_fallback')">
          <set_value name="$pipelineBeforeFreshFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListFresh"/>
          <do_all exact="$pipelineTradeList.count" counter="$freshIdx">
            <set_value name="$freshTrade" exact="$pipelineTradeList.{$freshIdx}"/>
            <set_value name="$freshKeep" exact="false"/>
            <do_if value="$freshTrade? and $freshTrade.$IsSellOnly? and $freshTrade.$SellOffer?">
              <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and @$freshTrade.$SellOffer.amount gt 0">
                <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.amount"/>
              </do_if>
              <do_if value="$freshSellAmt? and $freshSellAmt gt 0">
                <set_value name="$freshKeep" exact="true"/>
              </do_if>
            </do_if>
            <do_elseif value="$freshTrade? and $freshTrade.$BuyOffer? and $freshTrade.$SellOffer?">
              <set_value name="$freshBuyAmt" exact="@$freshTrade.$BuyOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshBuyAmt? or $freshBuyAmt le 0) and @$freshTrade.$BuyOffer.amount gt 0">
                <set_value name="$freshBuyAmt" exact="@$freshTrade.$BuyOffer.amount"/>
              </do_if>
              <do_if value="(not $freshBuyAmt? or $freshBuyAmt le 0) and $freshTrade.$SellOffer.owner? and @$freshTrade.$SellOffer.owner.exists">
                <set_value name="$freshBuyWare" exact="if $freshTrade.$Ware? then $freshTrade.$Ware else null"/>
                <do_if value="not $freshBuyWare? and @$freshTrade.$BuyOffer.ware != null">
                  <set_value name="$freshBuyWare" exact="@$freshTrade.$BuyOffer.ware"/>
                </do_if>
                <do_if value="$freshBuyWare?">
                  <set_value name="$freshBuyAmt" exact="[0, $freshTrade.$SellOffer.owner.cargo.{$freshBuyWare}.target - $freshTrade.$SellOffer.owner.cargo.{$freshBuyWare}.count].max"/>
                </do_if>
              </do_if>
              <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and @$freshTrade.$SellOffer.amount gt 0">
                <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.amount"/>
              </do_if>
              <do_if value="$freshBuyAmt? and $freshBuyAmt gt 0 and $freshSellAmt? and $freshSellAmt gt 0">
                <set_value name="$freshKeep" exact="true"/>
              </do_if>
            </do_elseif>
            <do_if value="$freshKeep">
              <append_to_list name="$pipelineTradeListFresh" exact="$freshTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListFresh"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fresh offer filter: before=' + $pipelineBeforeFreshFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineBeforeFreshFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Notify scheduler that this ship finished its search slot (semaphore release + dispatch) -->
        <signal_objects object="player.galaxy" param="'GT_Search_Done'" param2="table[
          $Ship = this.ship,
          $Found = $pipelineFound,
          $TradeList = $pipelineTradeList,
          $SearchMethod = $pipelineSearchMethod,
          $SearchType = if $searchMode? and $searchMode == 'sell_only' then 'clearance' else 'live',
          $HomeSector = $searchHomeSector
        ]"/>
        <resume label="wait_for_response"/>
      </do_if>
      
      <!-- Safety net: if $searchParams was not a valid table (should not happen after timeout guard above,
           but defense-in-depth). Clean up and retry. -->
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARNING: run_search_pipeline reached with invalid searchParams (typeof=' + typeof $searchParams + ') at game time ' + player.age + ' â€” this should not happen, aborting to retry'" chance="100"/>
      <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
      <resume label="no_trade_retry"/>
      
      <!-- ========================================= -->
      <!-- TRADE FOUND - VALIDATE BLACKLIST FIRST   -->
      <!-- ========================================= -->
      <label name="trade_found"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': REACHED trade_found label - starting blacklist validation at game time ' + player.age" chance="100"/>
      </do_if>
      
      <!-- Initialize validation variables BEFORE do_if block to ensure they always exist -->
      <set_value name="$validTradeFound" exact="false"/>
      <set_value name="$pendingTrade" exact="null"/>
      <set_value name="$buyStation" exact="null"/>
      <set_value name="$sellStation" exact="null"/>
      <set_value name="$tradesChecked" exact="0"/>
      <set_value name="$tradesBlacklisted" exact="0"/>
      <set_value name="$tradesRejectedDocking" exact="0"/>
      <set_value name="$tradesRejectedOfferInvalid" exact="0"/>
      <set_value name="$tradesRejectedPath" exact="0"/>
      <set_value name="$tradesRejectedDistance" exact="0"/>
      <set_value name="$tradesRejectedCargo" exact="0"/>
      <set_value name="$tradesRejectedProfit" exact="0"/>
      <set_value name="$tradesRejectedRestriction" exact="0"/>
      
      <!-- Iterate through trade list and validate each one -->
      <!-- Priority order: Signal param2 (from cache search work unit or live search) > Global storage (for threat intelligence compatibility) -->
      <!-- Cache search work units filter entries and signal results via GT_Trade_Found with param2 -->
      <!-- Initialize $tradeList and $searchMethod to prevent property lookup failures -->
      <set_value name="$tradeList" exact="[]"/>
      <set_value name="$searchMethod" exact="''"/>

      <!-- Locals like $gt_cargotarget are lost across <wait>; resolve from persisted instance vars. -->
      <set_value name="$cargoUtilThresholdPct" exact="[10,[(if this.$gt_cargotarget? then this.$gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 80)), 100].min].max"/>

      <!-- Priority 1: Use trade list from signal param2 (from cache search work unit or live search) -->
      <do_if value="this.$tradeListFromSignal? and this.$tradeListFromSignal.count gt 0">
        <set_value name="$tradeList" exact="this.$tradeListFromSignal"/>
        <set_value name="$searchMethod" exact="if this.$searchMethodFromSignal? and this.$searchMethodFromSignal != '' then this.$searchMethodFromSignal else 'signal'"/>
        <!-- Clear instance variables after use -->
        <remove_value name="this.$tradeListFromSignal"/>
        <remove_value name="this.$searchMethodFromSignal"/>
      </do_if>
      <do_else>
        <!-- Priority 2: Fallback to global storage (for threat intelligence compatibility) -->
        <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
          <set_value name="$tradeList" exact="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <set_value name="$searchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <do_if value="$searchMethod == ''">
            <set_value name="$searchMethod" exact="'global'"/>
          </do_if>
        </do_if>
      </do_else>

      <!-- Ensure it's a list -->
      <do_if value="typeof $tradeList != datatype.list">
        <!-- Backward compat: single trade stored as table -->
        <set_value name="$tradeList" exact="[$tradeList]"/>
      </do_if>
      
      <!-- Use safe access for debug text -->
      <set_value name="$tradeListCountForDebug" exact="if $tradeList != null then $tradeList.count else 0"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Received ' + $tradeListCountForDebug + ' trades to validate (source: ' + (if $searchMethod == 'cache' then 'CACHE' else if $searchMethod == 'live' then 'LIVE' else if $searchMethod != '' then $searchMethod else 'UNKNOWN') + ')'" chance="100"/>
      </do_if>

      <!-- FAST MONEY CHECK: Short-circuit validation when player money is exhausted.
           MK3 IPP player-supplier trades treat the buy leg as zero player-economy cost (see
           lib.gt.tradematch.xml $PlayerFreeSupplier) â€” skip this gate when such a candidate exists. -->
      <set_value name="$tradeListHasIppPlayerSupplier" exact="false"/>
      <set_value name="$fastMoneyIppEnabled" exact="if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false"/>
      <do_if value="$fastMoneyIppEnabled and $tradeList.count gt 0">
        <do_all exact="$tradeList.count" counter="$ippScanIdx">
          <set_value name="$ippScanTrade" exact="$tradeList.{$ippScanIdx}"/>
          <do_if value="$ippScanTrade? and not ($ippScanTrade.$IsSellOnly? and $ippScanTrade.$IsSellOnly)">
            <do_if value="$ippScanTrade.$PlayerFreeSupplier? and $ippScanTrade.$PlayerFreeSupplier">
              <set_value name="$tradeListHasIppPlayerSupplier" exact="true"/>
              <break/>
            </do_if>
            <do_if value="not $tradeListHasIppPlayerSupplier and $ippScanTrade.$BuyOffer? and @$ippScanTrade.$BuyOffer.owner.isplayerowned">
              <set_value name="$tradeListHasIppPlayerSupplier" exact="true"/>
              <break/>
            </do_if>
          </do_if>
        </do_all>
      </do_if>
      <do_if value="not $tradeListHasIppPlayerSupplier">
        <do_if value="not this.$minPlayerMoney?">
          <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
        </do_if>
        <set_value name="$fastMoneyThreshold" exact="(this.$minPlayerMoney + 1000)Cr"/>
        <!-- The fleet money cap is NOT consulted here: it is a wealth snapshot and must never
             block a ship that already holds more than the threshold. The per-trade authoritative
             guard handles unaffordable trades. -->
        <do_if value="player.money le $fastMoneyThreshold">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FAST MONEY CHECK at trade_found: player.money=' + (player.money / 100) + ' Cr, threshold=' + (this.$minPlayerMoney + 1000) + ' Cr - skipping validation, backing off'" chance="100"/>
          </do_if>
          <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
          <resume label="no_trade_retry"/>
        </do_if>
      </do_if>
      
      <!-- Cap extra cache-detail logs to avoid spam -->
      <set_value name="$cacheDetailLogMax" exact="8"/>
      <set_value name="$cacheDetailLogCount" exact="0"/>
      
      <!-- gatedistance memoization: cache results per (fromSector, toSector) to avoid
           redundant C++ pathfinding calls when multiple trades share the same sectors.
           Separate tables for non-blacklist vs blacklist-aware variants.
           Valid for the duration of this validation loop (ship doesn't move). -->
      <set_value name="$gdCache" exact="table[]"/>
      <set_value name="$gdCacheBL" exact="table[]"/>
      
      <!-- Resolve enforcement flags once before loop (MD-stored AI parameters override order params) -->
      <set_value name="$enfIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
      <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}? and global.$GT_AIParameters.{this.ship}.$IgnoreBuildStorage?">
        <set_value name="$enfIgnoreBuildStorage" exact="global.$GT_AIParameters.{this.ship}.$IgnoreBuildStorage"/>
      </do_if>
      <set_value name="$enfIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
      <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}? and global.$GT_AIParameters.{this.ship}.$IgnoreCarrierAux?">
        <set_value name="$enfIgnoreCarrierAux" exact="global.$GT_AIParameters.{this.ship}.$IgnoreCarrierAux"/>
      </do_if>

      <!-- Resolve MK3 faction blacklist once for this validation pass (commander for subordinates). -->
      <set_value name="$mk3BlacklistOwnerLoop" exact="this.ship"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
        <set_value name="$mk3BlacklistOwnerLoop" exact="this.ship.commander"/>
      </do_if>
      <set_value name="$mk3FactionBlacklistLoop" exact="table[]"/>
      <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerLoop}?">
        <set_value name="$mk3FactionBlacklistLoop" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerLoop}"/>
      </do_if>
      
      <!-- Priority-first reorder: when priority wares are set, put priority-ware trades at the front.
           Score multiplier alone cannot overcome large profit gaps (e.g. 238k Cr vs 2k Cr).
           This guarantees priority wares are tried first during validation. -->
      <!-- Resolved via lib.gt.priority_wares.resolve: walks instance -> local -> commander.defaultorder
           (or commander.defaultorder.$baseorder via Assist) once and returns [] when no source has wares.
           Replaces the prior 1.5KB nested ternary at this site (see DOCS/MK3_PIPELINE_REFACTOR.md Â§3.8). -->
      <run_script name="'lib.gt.priority_wares.resolve'" result="$pwForReorder">
        <param name="instanceWares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else null"/>
        <param name="localWares" value="if $effectivePriorityWares? then $effectivePriorityWares else null"/>
        <param name="ship" value="this.ship"/>
        <param name="validOrderIds" value="['GalaxyTraderMK3']"/>
      </run_script>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList? and $tradeList.count gt 0">
        <do_if value="not $pwForReorder? or $pwForReorder == null or $pwForReorder.count == 0">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder SKIPPED: no priority wares (this.$effectivePriorityWares=' + (if this.$effectivePriorityWares? and this.$effectivePriorityWares != null then this.$effectivePriorityWares.count else 'null') + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_if value="$pwForReorder? and $pwForReorder != null and $pwForReorder.count gt 0 and $tradeList? and $tradeList.count gt 0">
        <create_list name="$priorityTrades"/>
        <create_list name="$nonPriorityTrades"/>
        <do_all exact="$tradeList.count" counter="$ti">
          <set_value name="$t" exact="$tradeList.{$ti}"/>
          <set_value name="$tWare" exact="if $t.$Ware? then $t.$Ware else (if $t.$BuyOffer? then @$t.$BuyOffer.ware else null)"/>
          <set_value name="$isPriority" exact="false"/>
          <do_if value="$tWare?">
            <do_all exact="$pwForReorder.count" counter="$pwi">
              <set_value name="$pwItem" exact="$pwForReorder.{$pwi}"/>
              <!-- Compare by identity first; fallback to .id if references differ (e.g. across save/load) -->
              <do_if value="$pwItem == $tWare or ($pwItem? and $tWare? and $pwItem.id? and $tWare.id? and $pwItem.id == $tWare.id)">
                <set_value name="$isPriority" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$isPriority">
            <append_to_list name="$priorityTrades" exact="$t"/>
          </do_if>
          <do_else>
            <append_to_list name="$nonPriorityTrades" exact="$t"/>
          </do_else>
        </do_all>
        <run_script name="'lib.gt.score.selection_sort'" result="$prioSelectionSort">
          <param name="tradeList" value="$priorityTrades"/>
          <param name="ship" value="this.ship"/>
          <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        </run_script>
        <do_if value="$prioSelectionSort? and $prioSelectionSort.$SortedTrades?">
          <set_value name="$priorityTrades" exact="$prioSelectionSort.$SortedTrades"/>
        </do_if>
        <run_script name="'lib.gt.score.selection_sort'" result="$nonPrioSelectionSort">
          <param name="tradeList" value="$nonPriorityTrades"/>
          <param name="ship" value="this.ship"/>
          <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        </run_script>
        <do_if value="$nonPrioSelectionSort? and $nonPrioSelectionSort.$SortedTrades?">
          <set_value name="$nonPriorityTrades" exact="$nonPrioSelectionSort.$SortedTrades"/>
        </do_if>
        <create_list name="$reorderedList"/>
        <do_all exact="$priorityTrades.count" counter="$pi">
          <append_to_list name="$reorderedList" exact="$priorityTrades.{$pi}"/>
        </do_all>
        <do_all exact="$nonPriorityTrades.count" counter="$ni">
          <append_to_list name="$reorderedList" exact="$nonPriorityTrades.{$ni}"/>
        </do_all>
        <set_value name="$tradeList" exact="$reorderedList"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <do_if value="$priorityTrades.count gt 0">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder: ' + $priorityTrades.count + ' priority-ware trades moved to front of ' + $tradeList.count + ' (validation will try priority wares first)'" chance="100"/>
          </do_if>
          <do_else>
            <!-- Diagnostic: priority wares configured but no matching trades found -->
            <set_value name="$pwDiagNames" exact="''"/>
            <do_all exact="[$pwForReorder.count, 3].min" counter="$pdi">
              <set_value name="$pwDiagNames" exact="$pwDiagNames + (if $pdi gt 1 then ', ' else '') + (if $pwForReorder.{$pdi}? and $pwForReorder.{$pdi} != null then @$pwForReorder.{$pdi}.name else '?')"/>
            </do_all>
            <set_value name="$tDiagNames" exact="''"/>
            <do_all exact="[3, $tradeList.count].min" counter="$tdi">
              <set_value name="$td" exact="$tradeList.{$tdi}"/>
              <set_value name="$tdw" exact="if $td.$Ware? then $td.$Ware else (if $td.$BuyOffer? then @$td.$BuyOffer.ware else null)"/>
              <set_value name="$tDiagNames" exact="$tDiagNames + (if $tdi gt 1 then ', ' else '') + (if $tdw? and $tdw != null then @$tdw.name else '?')"/>
            </do_all>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder: 0 priority-ware trades in ' + $tradeList.count + ' (priority wares: [' + $pwDiagNames + '], first trades: [' + $tDiagNames + '])'" chance="100"/>
          </do_else>
        </do_if>
      </do_if>
      <do_else>
        <!-- Diagnostic: reorder skipped because priority wares not available (e.g. not persisted after interrupt) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList? and $tradeList.count gt 0 and (not $pwForReorder? or $pwForReorder == null or $pwForReorder.count == 0)">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder SKIPPED: no priority wares (this.$effectivePriorityWares=' + (if this.$effectivePriorityWares? and this.$effectivePriorityWares != null then this.$effectivePriorityWares.count else 'null') + ')'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- Per-ship selection score sort (shipâ†’buy proximity) within each priority bucket or full list. -->
      <do_if value="not ($pwForReorder? and $pwForReorder != null and $pwForReorder.count gt 0 and $tradeList? and $tradeList.count gt 0)">
        <do_if value="$tradeList? and $tradeList.count gt 0">
          <run_script name="'lib.gt.score.selection_sort'" result="$fullSelectionSort">
            <param name="tradeList" value="$tradeList"/>
            <param name="ship" value="this.ship"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <do_if value="$fullSelectionSort? and $fullSelectionSort.$SortedTrades?">
            <set_value name="$tradeList" exact="$fullSelectionSort.$SortedTrades"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Fleet spread (cache only): after ship-route cache sort (lib.gt.cache.score_for_ship), rotate
           the list by scheduler cacheReadOffset so concurrent ships validate different trades first. -->
      <do_if value="$searchMethod == 'cache' and $tradeList? and $tradeList.count gt 1 and this.$lastCacheReadOffset?">
        <set_value name="$fleetSpreadStart" exact="this.$lastCacheReadOffset % $tradeList.count"/>
        <do_if value="$fleetSpreadStart gt 0">
          <set_value name="$fleetSpreadCount" exact="$tradeList.count"/>
          <create_list name="$fleetSpreadList"/>
          <do_all exact="$fleetSpreadCount" counter="$fleetSpreadIdx">
            <set_value name="$fleetSpreadPick" exact="((($fleetSpreadStart + $fleetSpreadIdx - 1) % $fleetSpreadCount) + 1)"/>
            <append_to_list name="$fleetSpreadList" exact="$tradeList.{$fleetSpreadPick}"/>
          </do_all>
          <set_value name="$tradeList" exact="$fleetSpreadList"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet-spread rotated cache trade list by ' + $fleetSpreadStart + ' of ' + $fleetSpreadCount + ' (reduces herd collision on top trade)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Iterate through trade list -->
      <!-- Check if tradeList exists and has items before looping -->
      <do_if value="(if $tradeList != null then $tradeList.count else 0) gt 0">
        <set_value name="this.$gt_dockMemo" exact="table[]"/>
        <do_all exact="$tradeList.count" counter="$tradeIdx">
          <set_value name="$currentTrade" exact="$tradeList.{$tradeIdx}"/>
          <set_value name="$tradesChecked" operation="add"/>
          
          <!-- Check if currentTrade is valid before processing -->
          <do_if value="$currentTrade? and $currentTrade != null">
              <!-- Extract stations from trade (handle both new list format and old single-trade format) -->
              <!-- Initialize stations to null first, then extract -->
              <set_value name="$buyStation" exact="null"/>
              <set_value name="$sellStation" exact="null"/>
              
              <!-- Check if this is a sell-only trade first -->
              <set_value name="$isSellOnlyTrade" exact="false"/>
              <do_if value="$currentTrade.$IsSellOnly? and $currentTrade.$IsSellOnly">
                <set_value name="$isSellOnlyTrade" exact="true"/>
              </do_if>
              
              <!-- Extract buy station (may be null for sell-only trades) -->
              <do_if value="$currentTrade.$BuyStation?">
                <set_value name="$buyStation" exact="$currentTrade.$BuyStation"/>
              </do_if>
              <do_else>
                <do_if value="$currentTrade.$BuyOffer?">
                  <set_value name="$buyStation" exact="@$currentTrade.$BuyOffer.owner"/>
                </do_if>
              </do_else>
              
              <!-- Extract sell station (always required) -->
              <do_if value="$currentTrade.$SellStation?">
                <set_value name="$sellStation" exact="$currentTrade.$SellStation"/>
              </do_if>
              <do_else>
                <do_if value="$currentTrade.$SellOffer?">
                  <set_value name="$sellStation" exact="@$currentTrade.$SellOffer.owner"/>
                </do_if>
              </do_else>

              <set_value name="$blockedStationsValidation" exact="if $effectiveBlockedStations? then $effectiveBlockedStations else (if this.$effectiveBlockedStations? then this.$effectiveBlockedStations else [])"/>
              <do_if value="$blockedStationsValidation? and $blockedStationsValidation.count gt 0">
                <set_value name="$tradeUsesBlockedStation" exact="false"/>
                <set_value name="$blockedStationRole" exact="'UNKNOWN'"/>
                <set_value name="$blockedStationMatched" exact="null"/>
                <do_all exact="$blockedStationsValidation.count" counter="$blockedStationIdx">
                  <set_value name="$blockedStationCandidate" exact="$blockedStationsValidation.{$blockedStationIdx}"/>
                  <do_if value="$blockedStationCandidate? and not $isSellOnlyTrade and $buyStation? and $buyStation == $blockedStationCandidate">
                    <set_value name="$tradeUsesBlockedStation" exact="true"/>
                    <set_value name="$blockedStationRole" exact="'BUY'"/>
                    <set_value name="$blockedStationMatched" exact="$buyStation"/>
                    <break/>
                  </do_if>
                  <do_if value="$blockedStationCandidate? and $sellStation? and $sellStation == $blockedStationCandidate">
                    <set_value name="$tradeUsesBlockedStation" exact="true"/>
                    <set_value name="$blockedStationRole" exact="'SELL'"/>
                    <set_value name="$blockedStationMatched" exact="$sellStation"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="$tradeUsesBlockedStation">
                  <set_value name="$tradesBlacklisted" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + (if $tradeIdx? then $tradeIdx else 0) + '/' + (if $tradeList != null then $tradeList.count else 0) + ' BLOCKED BY STATION LIST: ' + (if $blockedStationMatched? then @$blockedStationMatched.knownname else 'Unknown') + ' (' + $blockedStationRole + ') - trying next trade'" chance="100"/>
                  </do_if>
                  <continue/>
                </do_if>
              </do_if>
              
              <!-- For sell-only trades, only require sellStation; for normal trades, require both -->
              <do_if value="$isSellOnlyTrade">
                <!-- Sell-only trade: only sellStation required -->
                <do_if value="$sellStation? and $sellStation != null">
                  <!-- Use safe access for tradeIdx in debug text -->
                  <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                  <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validating SELL-ONLY trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ': ' + (if $currentTrade.$Ware? then @$currentTrade.$Ware.name else 'Unknown') + ' (Ship cargo â†’ ' + (if $sellStation? then @$sellStation.knownname else 'Unknown') + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Check docking permissions FIRST (most common failure, cheapest check) -->
                  <!-- Skip buy-station checks for sell-only trades (ship already has cargo) -->
                  <!-- Also check if BuyStation is not a station (could be ship for sell-only trades) -->
                  <set_value name="$buyStationIsStation" exact="false"/>
                  <do_if value="$buyStation?">
                    <set_value name="$buyStationIsStation" exact="@$buyStation.isclass.station"/>
                  </do_if>
                  
                  <!-- Only check buy-station docking if it's NOT a sell-only trade (always true for sell-only) -->
                  <set_value name="$canDockAtBuyStation" exact="true"/>
                  
                  <!-- Delivery dock: lib.gt.dockcheck purpose=trade -->
                  <run_script name="'lib.gt.dockcheck'" result="$mk3SellOnlyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtSellStation" exact="$mk3SellOnlyDockResult.$CanDock"/>
        
                <do_if value="not $canDockAtBuyStation or not $canDockAtSellStation">
                  <!-- DOCKING NOT ALLOWED - Skip to next trade -->
                  <set_value name="$tradesRejectedDocking" operation="add"/>
                  <set_value name="$deniedStation" exact="if not $canDockAtBuyStation then $buyStation else $sellStation"/>
                  <set_value name="$deniedType" exact="if not $canDockAtBuyStation then 'BUY' else 'SELL'"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' DOCKING DENIED:' +
                      '\n  Station: ' + @$deniedStation.knownname + 
                      '\n  Sector: ' + @$deniedStation.sector.knownname + 
                      '\n  Type: ' + $deniedType + 
                      '\n  Reason: Docking not allowed (reputation, war, or permissions)' + 
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>

                    <!-- Extra cache-only detail (capped): log raw docking flags + dockbay match test -->
                    <do_if value="$searchMethod == 'cache' and $cacheDetailLogCount lt $cacheDetailLogMax">
                      <set_value name="$cacheDetailLogCount" operation="add"/>
                      <set_value name="$dockAllowedBuyText" exact="if $canDockAtBuyStation? then $canDockAtBuyStation else 'null'"/>
                      <set_value name="$dockAllowedSellText" exact="if $canDockAtSellStation? then $canDockAtSellStation else 'null'"/>
                      <set_value name="$sellOfferId" exact="null"/>
                      <do_if value="$currentTrade.$SellOffer?">
                        <set_value name="$sellOfferId" exact="@$currentTrade.$SellOffer.id"/>
                      </do_if>
                      <find_dockingbay name="$cacheDeniedDock" object="$deniedStation" checkoperational="true" multiple="false">
                        <match_dock size="this.ship.docksize" trading="true" storage="false"/>
                        <match_relation_to object="this.ship" comparison="not" relation="enemy"/>
                      </find_dockingbay>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': [CACHE-DETAIL] DockingDenied trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe +
                        '\n  DeniedType: ' + $deniedType +
                        '\n  DockingAllowed BUY=' + $dockAllowedBuyText + ' SELL=' + $dockAllowedSellText +
                        '\n  ShipDocksize: ' + this.ship.docksize +
                        '\n  SellOfferId: ' + (if $sellOfferId? and $sellOfferId != null then $sellOfferId else 'null') +
                        '\n  find_dockingbay(trading+not-enemy): ' + (if $cacheDeniedDock then 'FOUND' else 'NONE')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Scenario 3: Flag ship-specific docking failure on cache entry -->
                  <do_if value="$searchMethod == 'cache'">
                    <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'docking_denied']"/>
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- Use cached blacklistgroup from init -->
                <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                
                <!-- Resolve sector whitelist for blacklist checks (whitelist overrides blacklist, matches GT_IsSectorBlacklisted) -->
                <set_value name="$validationWhitelist" exact="[]"/>
                <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                  <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
                </do_if>
                
                <!-- Check path reachability BEFORE blacklist (faster to fail on unreachable) -->
                <!-- For sell-only trades, skip buy-station pathfinding (ship already has cargo) -->
                <set_value name="$currentSector" exact="this.ship.sector"/>
                <!-- For sell-only trades, buySector is current sector (ship already has cargo) -->
                <set_value name="$buySector" exact="$currentSector"/>
                <do_if value="not $isSellOnlyTrade and $buyStation?">
                  <set_value name="$buySector" exact="$buyStation.sector"/>
                </do_if>
                <set_value name="$sellSector" exact="$sellStation.sector"/>
                
                <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
                <set_value name="$currentSectorIsBlacklisted" exact="false"/>
                <do_if value="$blacklistgroup?">
                  <set_value name="$currentSectorWhitelisted" exact="false"/>
                  <do_if value="$validationWhitelist.count gt 0">
                    <do_all exact="$validationWhitelist.count" counter="$swIdx">
                      <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                        <set_value name="$currentSectorWhitelisted" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  <do_if value="not $currentSectorWhitelisted">
                    <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                    <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                    <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                  </do_if>
                </do_if>
        
        <!-- Calculate path distances with escape support -->
        <!-- Buy path calculation with escape support -->
        <!-- For sell-only trades, buy distance is always 0 (ship already has cargo, no buy travel needed) -->
        <set_value name="$buyDistance" exact="-1"/>
        <do_if value="$isSellOnlyTrade">
          <set_value name="$buyDistance" exact="0"/>
        </do_if>
        <do_elseif value="$buySector == $currentSector">
          <set_value name="$buyDistance" exact="0"/>
        </do_elseif>
        <do_elseif value="$currentSectorIsBlacklisted">
          <!-- Escape: non-blacklist gatedistance (memoized) -->
          <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$buySector}?">
            <set_value name="$buyDistance" exact="$gdCache.{$currentSector}.{$buySector}"/>
          </do_if>
          <do_else>
            <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}"/>
            <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
            <set_value name="$gdCache.{$currentSector}.{$buySector}" exact="$buyDistance"/>
          </do_else>
        </do_elseif>
        <do_else>
          <!-- Normal: blacklist-aware gatedistance (memoized) -->
          <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$buySector}?">
            <set_value name="$buyDistance" exact="$gdCacheBL.{$currentSector}.{$buySector}"/>
          </do_if>
          <do_else>
            <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}.{$blacklistgroup}.{this.ship}"/>
            <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
            <set_value name="$gdCacheBL.{$currentSector}.{$buySector}" exact="$buyDistance"/>
          </do_else>
        </do_else>
        
        <!-- Sell path: Calculate based on buy location -->
        <set_value name="$sellDistance" exact="-1"/>
        <do_if value="$sellSector == $buySector">
          <set_value name="$sellDistance" exact="0"/>
        </do_if>
        <do_elseif value="$buySector == $currentSector">
          <!-- Ship in buy sector: escape vs normal path to sell sector -->
          <do_if value="$currentSectorIsBlacklisted">
            <!-- Escape: non-blacklist gatedistance (memoized) -->
            <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$sellSector}?">
              <set_value name="$sellDistance" exact="$gdCache.{$currentSector}.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}"/>
              <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
              <set_value name="$gdCache.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
            </do_else>
          </do_if>
          <do_else>
            <!-- Normal: blacklist-aware gatedistance (memoized) -->
            <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$sellSector}?">
              <set_value name="$sellDistance" exact="$gdCacheBL.{$currentSector}.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
              <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
              <set_value name="$gdCacheBL.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
            </do_else>
          </do_else>
        </do_elseif>
        <do_else>
          <!-- Normal: buyâ†’sell blacklist-aware gatedistance (memoized) -->
          <do_if value="$gdCacheBL.{$buySector}? and $gdCacheBL.{$buySector}.{$sellSector}?">
            <set_value name="$sellDistance" exact="$gdCacheBL.{$buySector}.{$sellSector}"/>
          </do_if>
          <do_else>
            <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
            <do_if value="not $gdCacheBL.{$buySector}?"><set_value name="$gdCacheBL.{$buySector}" exact="table[]"/></do_if>
            <set_value name="$gdCacheBL.{$buySector}.{$sellSector}" exact="$sellDistance"/>
          </do_else>
        </do_else>
        
        <!-- Always log distance check to diagnose issues -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
          <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PATH check (blacklist-aware):' +
            '\n  Current sector: ' + @$currentSector.knownname +
            '\n  BUY: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance: ' + $buyDistance + ')' +
            '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance: ' + $sellDistance + ')' +
            '\n  Blacklist group: ' + $blacklistgroup +
            '\n  Result: ' + (if ($buyDistance lt 0 and not $isSellOnlyTrade) or $sellDistance lt 0 then 'BLOCKED' else 'OK')" 
            chance="100"/>
        </do_if>
        
        <!-- For sell-only trades, only check sell path (buy path is always 0) -->
        <set_value name="$pathBlocked" exact="false"/>
        <do_if value="not $isSellOnlyTrade">
          <do_if value="$buyDistance lt 0">
            <set_value name="$pathBlocked" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$sellDistance lt 0">
          <set_value name="$pathBlocked" exact="true"/>
        </do_if>
        
        <do_if value="$pathBlocked">
          <!-- PATH BLOCKED - Skip to next trade -->
          <set_value name="$tradesRejectedPath" operation="add"/>
          <set_value name="$unreachableStation" exact="if ($buyDistance lt 0 and not $isSellOnlyTrade) then $buyStation else $sellStation"/>
          <set_value name="$unreachableType" exact="if ($buyDistance lt 0 and not $isSellOnlyTrade) then 'BUY' else 'SELL'"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' PATH BLOCKED:' +
              '\n  Station: ' + @$unreachableStation.knownname + 
              '\n  Type: ' + $unreachableType + 
              '\n  Reason: No path exists (disconnected sectors, war, or gates destroyed)' + 
              '\n  â†’ Trying next trade in list...'" 
              chance="100"/>
          </do_if>
          
          <!-- Scenario 3: Flag ship-specific path failure on cache entry -->
          <do_if value="$searchMethod == 'cache'">
            <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'path_blocked']"/>
          </do_if>
          
          <!-- Continue to next trade in list -->
          <continue/>
        </do_if>
              </do_if>
              <do_else>
                <!-- Sell-only trade missing sellStation - skip this trade -->
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' MISSING SELL STATION (sell-only trade requires sellStation)'" chance="100"/>
                <continue/>
              </do_else>
            </do_if>
            <do_else>
                <!-- Normal trade: require both buyStation and sellStation -->
                <do_if value="$buyStation? and $buyStation != null and $sellStation? and $sellStation != null">
                  <!-- Normal trade validation continues here - same as before but with buy checks -->
                  <!-- Use safe access for tradeIdx in debug text -->
                  <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                  <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validating trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ': ' + (if $currentTrade.$BuyOffer? then @$currentTrade.$BuyOffer.ware.name else 'Unknown') + ' (' + (if $buyStation? then @$buyStation.knownname else 'Unknown') + ' â†’ ' + (if $sellStation? then @$sellStation.knownname else 'Unknown') + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Check docking FIRST: lib.gt.dockcheck purpose=trade (aligned with MK4). -->
                  <run_script name="'lib.gt.dockcheck'" result="$mk3BuyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$buyStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtBuyStation" exact="$mk3BuyDockResult.$CanDock"/>
                  <run_script name="'lib.gt.dockcheck'" result="$mk3SellDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtSellStation" exact="$mk3SellDockResult.$CanDock"/>
                  
                  <do_if value="not $canDockAtBuyStation or not $canDockAtSellStation">
                    <!-- DOCKING NOT ALLOWED - Skip to next trade -->
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <set_value name="$deniedStation" exact="if not $canDockAtBuyStation then $buyStation else $sellStation"/>
                    <set_value name="$deniedType" exact="if not $canDockAtBuyStation then 'BUY' else 'SELL'"/>
                    
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' DOCKING DENIED:' +
                      '\n  Station: ' + @$deniedStation.knownname + 
                      '\n  Sector: ' + @$deniedStation.sector.knownname + 
                      '\n  Type: ' + $deniedType + 
                      '\n  Reason: Docking not allowed (reputation, war, or permissions)' + 
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>

                    <!-- Extra cache-only detail (capped): log raw docking flags + dockbay match test -->
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMethod == 'cache' and $cacheDetailLogCount lt $cacheDetailLogMax">
                      <set_value name="$cacheDetailLogCount" operation="add"/>
                      <set_value name="$dockAllowedBuyText" exact="if $canDockAtBuyStation? then $canDockAtBuyStation else 'null'"/>
                      <set_value name="$dockAllowedSellText" exact="if $canDockAtSellStation? then $canDockAtSellStation else 'null'"/>
                      <set_value name="$buyOfferId" exact="null"/>
                      <set_value name="$sellOfferId" exact="null"/>
                      <do_if value="$currentTrade.$BuyOffer?">
                        <set_value name="$buyOfferId" exact="@$currentTrade.$BuyOffer.id"/>
                      </do_if>
                      <do_if value="$currentTrade.$SellOffer?">
                        <set_value name="$sellOfferId" exact="@$currentTrade.$SellOffer.id"/>
                      </do_if>
                      <find_dockingbay name="$cacheDeniedDock" object="$deniedStation" checkoperational="true" multiple="false">
                        <match_dock size="this.ship.docksize" trading="true" storage="false"/>
                        <match_relation_to object="this.ship" comparison="not" relation="enemy"/>
                      </find_dockingbay>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': [CACHE-DETAIL] DockingDenied trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe +
                        '\n  DeniedType: ' + $deniedType +
                        '\n  DockingAllowed BUY=' + $dockAllowedBuyText + ' SELL=' + $dockAllowedSellText +
                        '\n  ShipDocksize: ' + this.ship.docksize +
                        '\n  BuyOfferId: ' + (if $buyOfferId? and $buyOfferId != null then $buyOfferId else 'null') +
                        '\n  SellOfferId: ' + (if $sellOfferId? and $sellOfferId != null then $sellOfferId else 'null') +
                        '\n  find_dockingbay(trading+not-enemy): ' + (if $cacheDeniedDock then 'FOUND' else 'NONE')"
                        chance="100"/>
                    </do_if>
                    
                    <!-- Scenario 3: Flag ship-specific docking failure on cache entry -->
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'docking_denied']"/>
                    </do_if>
                    
                    <!-- Continue to next trade in list -->
                    <continue/>
                  </do_if>
                  
                  <!-- Use cached blacklistgroup from init -->
                  <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                  
                  <!-- Resolve sector whitelist for blacklist checks (whitelist overrides blacklist, matches GT_IsSectorBlacklisted) -->
                  <set_value name="$validationWhitelist" exact="[]"/>
                  <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                    <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
                  </do_if>
                  
                  <!-- Check path reachability BEFORE blacklist (faster to fail on unreachable) -->
                  <set_value name="$currentSector" exact="this.ship.sector"/>
                  <set_value name="$buySector" exact="$buyStation.sector"/>
                  <set_value name="$sellSector" exact="$sellStation.sector"/>
                  
                  <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
                  <set_value name="$currentSectorIsBlacklisted" exact="false"/>
                  <do_if value="$blacklistgroup?">
                    <set_value name="$currentSectorWhitelisted" exact="false"/>
                    <do_if value="$validationWhitelist.count gt 0">
                      <do_all exact="$validationWhitelist.count" counter="$swIdx">
                        <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                          <set_value name="$currentSectorWhitelisted" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    <do_if value="not $currentSectorWhitelisted">
                      <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                      <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                      <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Calculate path distances with escape support -->
                  <!-- Buy path calculation with escape support -->
                  <!-- Buy path: If ship is already in buy sector, distance is 0 (no travel needed) -->
                  <set_value name="$buyDistance" exact="-1"/>
                  <do_if value="$buySector == $currentSector">
                    <set_value name="$buyDistance" exact="0"/>
                  </do_if>
                  <do_elseif value="$currentSectorIsBlacklisted">
                    <!-- Escape: non-blacklist gatedistance (memoized) -->
                    <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$buySector}?">
                      <set_value name="$buyDistance" exact="$gdCache.{$currentSector}.{$buySector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}"/>
                      <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
                      <set_value name="$gdCache.{$currentSector}.{$buySector}" exact="$buyDistance"/>
                    </do_else>
                  </do_elseif>
                  <do_else>
                    <!-- Normal: blacklist-aware gatedistance (memoized) -->
                    <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$buySector}?">
                      <set_value name="$buyDistance" exact="$gdCacheBL.{$currentSector}.{$buySector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}.{$blacklistgroup}.{this.ship}"/>
                      <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
                      <set_value name="$gdCacheBL.{$currentSector}.{$buySector}" exact="$buyDistance"/>
                    </do_else>
                  </do_else>
                  
                  <!-- Sell path: Calculate based on buy location -->
                  <set_value name="$sellDistance" exact="-1"/>
                  <do_if value="$sellSector == $buySector">
                    <set_value name="$sellDistance" exact="0"/>
                  </do_if>
                  <do_elseif value="$buySector == $currentSector">
                    <!-- Ship in buy sector: escape vs normal path to sell sector -->
                    <do_if value="$currentSectorIsBlacklisted">
                      <!-- Escape: non-blacklist gatedistance (memoized) -->
                      <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$sellSector}?">
                        <set_value name="$sellDistance" exact="$gdCache.{$currentSector}.{$sellSector}"/>
                      </do_if>
                      <do_else>
                        <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}"/>
                        <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
                        <set_value name="$gdCache.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
                      </do_else>
                    </do_if>
                    <do_else>
                      <!-- Normal: blacklist-aware gatedistance (memoized) -->
                      <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$sellSector}?">
                        <set_value name="$sellDistance" exact="$gdCacheBL.{$currentSector}.{$sellSector}"/>
                      </do_if>
                      <do_else>
                        <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
                        <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
                        <set_value name="$gdCacheBL.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
                      </do_else>
                    </do_else>
                  </do_elseif>
                  <do_else>
                    <!-- Normal: buyâ†’sell blacklist-aware gatedistance (memoized) -->
                    <do_if value="$gdCacheBL.{$buySector}? and $gdCacheBL.{$buySector}.{$sellSector}?">
                      <set_value name="$sellDistance" exact="$gdCacheBL.{$buySector}.{$sellSector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
                      <do_if value="not $gdCacheBL.{$buySector}?"><set_value name="$gdCacheBL.{$buySector}" exact="table[]"/></do_if>
                      <set_value name="$gdCacheBL.{$buySector}.{$sellSector}" exact="$sellDistance"/>
                    </do_else>
                  </do_else>
                  
                  <!-- Always log distance check to diagnose issues -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PATH check (blacklist-aware):' +
                      '\n  Current sector: ' + @$currentSector.knownname +
                      '\n  BUY: ' + @$buyStation.knownname + ' (Sector: ' + @$buyStation.sector.knownname + ', Distance: ' + $buyDistance + ')' +
                      '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance: ' + $sellDistance + ')' +
                      '\n  Blacklist group: ' + $blacklistgroup +
                      '\n  Result: ' + (if $buyDistance lt 0 or $sellDistance lt 0 then 'BLOCKED' else 'OK')" 
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="$buyDistance lt 0 or $sellDistance lt 0">
                    <!-- PATH BLOCKED - Skip to next trade -->
                    <set_value name="$tradesRejectedPath" operation="add"/>
                    <set_value name="$unreachableStation" exact="if $buyDistance lt 0 then $buyStation else $sellStation"/>
                    <set_value name="$unreachableType" exact="if $buyDistance lt 0 then 'BUY' else 'SELL'"/>
                    
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' PATH BLOCKED:' +
                        '\n  Station: ' + @$unreachableStation.knownname + 
                        '\n  Type: ' + $unreachableType + 
                        '\n  Reason: No path exists (disconnected sectors, war, or gates destroyed)' + 
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                    
                    <!-- Scenario 3: Flag ship-specific path failure on cache entry -->
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'path_blocked']"/>
                    </do_if>
                    
                    <!-- Continue to next trade in list -->
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Normal trade missing stations - skip this trade -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' MISSING STATIONS (normal trade requires both buy and sell stations)'" chance="100"/>
                  </do_if>
                  <continue/>
                </do_else>
              </do_else>
              
              <!-- Both sell-only and normal trades continue here (only if they passed initial checks) -->
              <!-- Validate distance from HOME SECTOR (not ship position) -->
              <!-- Subordinates ALWAYS use commander's home sector (via $effectiveHome) -->
              <!-- For non-subordinates: Always use defaultorder.$home as PRIMARY source (fixed value in order) -->
              <!-- Home sector is a fixed value in the order settings and should NEVER drift -->
              <!-- Ships must only trade with stations within maxbuy/maxsell from home sector -->
              <!-- Note: $effectiveHome already handles subordinates correctly (set at initialization) -->
              <set_value name="$homeBase" exact="this.$effectiveHome"/>
              
              <!-- Fallback: Only if effectiveHome is not available, check defaultorder.$home -->
              <do_if value="not $homeBase? or not $homeBase.exists">
                <set_value name="$homeBase" exact="@this.ship.defaultorder.$home"/>
                <do_if value="not $homeBase? or not $homeBase.exists">
                  <!-- REMOVED: Never fall back to ship.sector (causes cascading drift) -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI-ERROR] Home sector not found for ' + this.ship.idcode + ' - effectiveHome and defaultorder.$home are null! This should never happen.'" chance="100"/>
                  </do_if>
                  <!-- Emergency fallback only - this should never happen -->
                  <set_value name="$homeBase" exact="this.ship.sector"/>
                </do_if>
              </do_if>
              
              <!-- Extract home sector -->
              <set_value name="$homeSector" exact="null"/>
              <do_if value="@$homeBase.exists">
                <do_if value="$homeBase.isclass.station">
                  <set_value name="$homeSector" exact="$homeBase.sector"/>
                </do_if>
                <do_elseif value="$homeBase.isclass.sector">
                  <set_value name="$homeSector" exact="$homeBase"/>
                </do_elseif>
              </do_if>
              
              <do_if value="not $homeSector? or not $homeSector.exists">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI-ERROR] Failed to extract home sector from homeBase for ' + this.ship.idcode + ' - using ship.sector as emergency fallback (THIS WILL CAUSE DRIFT!)'" chance="100"/>
                </do_if>
                <!-- Emergency fallback only - this should never happen -->
                <set_value name="$homeSector" exact="this.ship.sector"/>
              </do_if>
              
              <!-- Calculate distance from HOME SECTOR to stations (range-only, no blacklist) -->
              <!-- For sell-only trades, skip buy distance check (no buy station) -->
              <set_value name="$buyDistanceFromHome" exact="0"/>
              <set_value name="$sellDistanceFromHome" exact="-1"/>
              
              <do_if value="not $isSellOnlyTrade">
                <!-- Normal trade: check buy distance from home (memoized) -->
                <set_value name="$buyDistanceFromHome" exact="-1"/>
                <do_if value="$buySector == $homeSector">
                  <set_value name="$buyDistanceFromHome" exact="0"/>
                </do_if>
                <do_else>
                  <do_if value="$gdCache.{$homeSector}? and $gdCache.{$homeSector}.{$buySector}?">
                    <set_value name="$buyDistanceFromHome" exact="$gdCache.{$homeSector}.{$buySector}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$buyDistanceFromHome" exact="$homeSector.gatedistance.{$buySector}"/>
                    <do_if value="not $gdCache.{$homeSector}?"><set_value name="$gdCache.{$homeSector}" exact="table[]"/></do_if>
                    <set_value name="$gdCache.{$homeSector}.{$buySector}" exact="$buyDistanceFromHome"/>
                  </do_else>
                </do_else>
              </do_if>
              
              <!-- Always check sell distance from home (memoized) -->
              <do_if value="$sellSector == $homeSector">
                <set_value name="$sellDistanceFromHome" exact="0"/>
              </do_if>
              <do_else>
                <do_if value="$gdCache.{$homeSector}? and $gdCache.{$homeSector}.{$sellSector}?">
                  <set_value name="$sellDistanceFromHome" exact="$gdCache.{$homeSector}.{$sellSector}"/>
                </do_if>
                <do_else>
                  <set_value name="$sellDistanceFromHome" exact="$homeSector.gatedistance.{$sellSector}"/>
                  <do_if value="not $gdCache.{$homeSector}?"><set_value name="$gdCache.{$homeSector}" exact="table[]"/></do_if>
                  <set_value name="$gdCache.{$homeSector}.{$sellSector}" exact="$sellDistanceFromHome"/>
                </do_else>
              </do_else>
              
              <!-- Resolve max distances safely â€” instance vars may be missing after hot-reload -->
              <set_value name="$_maxBuy" exact="if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else $searchMaxDistance"/>
              <set_value name="$_maxSell" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else $searchMaxDistance"/>

              <!-- Show calculated distances for diagnosis -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
                <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': HOME SECTOR distance check (trade ' + $tradeIdx + '):' +
                  '\n  Home sector: ' + @$homeSector.knownname +
                  '\n  BUY station: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance from home: ' + $buyDistanceFromHome + '/' + $_maxBuy + ' jumps)' +
                  '\n  SELL station: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance from home: ' + $sellDistanceFromHome + '/' + $_maxSell + ' jumps)' +
                  '\n  Ship position: ' + @this.ship.sector.knownname +
                  '\n  Validation: ' + (if ($buyDistanceFromHome lt 0 or $sellDistanceFromHome lt 0 or ($buyDistanceFromHome gt $_maxBuy and not $isSellOnlyTrade) or $sellDistanceFromHome gt $_maxSell) then 'REJECTED' else 'PASSED')"
                  chance="100"/>
              </do_if>
              
              <!-- Reject if stations exceed maxDistance from home -->
              <set_value name="$distanceCheckFailed" exact="false"/>
              <do_if value="not $isSellOnlyTrade">
                <do_if value="$buyDistanceFromHome lt 0 or $buyDistanceFromHome gt $_maxBuy">
                  <set_value name="$distanceCheckFailed" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$sellDistanceFromHome lt 0 or $sellDistanceFromHome gt $_maxSell">
                <set_value name="$distanceCheckFailed" exact="true"/>
              </do_if>
              
              <do_if value="$distanceCheckFailed">
                <set_value name="$tradesRejectedDistance" operation="add"/>
                
                <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
                <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' DISTANCE EXCEEDED:' +
                    '\n  BUY: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance from home: ' + $buyDistanceFromHome + '/' + $_maxBuy + ' jumps)' +
                    '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance from home: ' + $sellDistanceFromHome + '/' + $_maxSell + ' jumps)' +
                    '\n  Home sector: ' + @$homeSector.knownname +
                    '\n  Ship position: ' + @this.ship.sector.knownname +
                    '\n  Reason: Station(s) exceed maximum distance from home sector' +
                    '\n  â†’ Trying next trade in list...'"
                    chance="100"/>
                </do_if>
                
                <!-- Scenario 3: Flag ship-specific distance failure on cache entry -->
                <do_if value="$searchMethod == 'cache'">
                  <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'distance_exceeded']"/>
                </do_if>
                
                <!-- Continue to next trade in list -->
                <continue/>
              </do_if>
              
              <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
              <set_value name="$currentSectorIsBlacklisted" exact="false"/>
              <do_if value="$blacklistgroup?">
                <set_value name="$currentSectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                      <set_value name="$currentSectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $currentSectorWhitelisted">
                  <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                </do_if>
              </do_if>
              
              <!-- Check if buy station OR its sector is blacklisted -->
              <!-- Always check target sector blacklist - escape only affects PATH, not destination -->
              <!-- For sell-only trades, skip buy station blacklist check (no buy station) -->
              <!-- Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted) -->
              <set_value name="$buyBlacklisted" exact="false"/>
              <do_if value="not $isSellOnlyTrade and $blacklistgroup? and $buyStation?">
                <!-- Check station itself (objectactivity) -->
                <set_value name="$buyStationBlacklisted" exact="@$buyStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                <!-- Check sector (sectoractivity AND sectortravel) unless whitelisted -->
                <set_value name="$buySectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $buyStation.sector">
                      <set_value name="$buySectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <set_value name="$buySectorActivityBlacklisted" exact="false"/>
                <set_value name="$buySectorTravelBlacklisted" exact="false"/>
                <do_if value="not $buySectorWhitelisted">
                  <set_value name="$buySectorActivityBlacklisted" exact="@$buyStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$buySectorTravelBlacklisted" exact="@$buyStation.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                </do_if>
                
                <!-- Block buying in blacklisted sector (force escape) -->
                <!-- Ship in blacklisted sector must NOT buy in that sector -->
                <!-- Ship must escape by buying from a different (non-blacklisted) sector -->
                <do_if value="$buySectorActivityBlacklisted or $buySectorTravelBlacklisted">
                  <!-- Block buying in blacklisted sector (even if ship is already there) -->
                  <set_value name="$buyBlacklisted" exact="true"/>
                </do_if>
                <do_else>
                  <!-- Target sector is not blacklisted - only check station -->
                  <set_value name="$buyBlacklisted" exact="$buyStationBlacklisted"/>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$buyStationNameForDebug" exact="if $buyStation? then @$buyStation.knownname else 'Unknown'"/>
                  <set_value name="$buySectorNameForDebug" exact="if $buyStation? then @$buyStation.sector.knownname else 'Unknown'"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BUY blacklist check:' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (blacklisted: ' + $currentSectorIsBlacklisted + ')' +
                    '\n  Station: ' + $buyStationNameForDebug + 
                    '\n  Sector: ' + $buySectorNameForDebug + 
                    '\n  Station (objectactivity): ' + $buyStationBlacklisted + 
                    '\n  Sector (sectoractivity): ' + $buySectorActivityBlacklisted + 
                    '\n  Sector (sectortravel): ' + $buySectorTravelBlacklisted + 
                    '\n  Ship in buy sector: ' + ($buySector == $currentSector) +
                    '\n  Final result: ' + $buyBlacklisted" 
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Check if sell station OR its sector is blacklisted -->
              <!-- Always check target sector blacklist - escape only affects PATH, not destination -->
              <!-- Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted) -->
              <set_value name="$sellBlacklisted" exact="false"/>
              <do_if value="$blacklistgroup?">
                <!-- Check station itself (objectactivity) -->
                <set_value name="$sellStationBlacklisted" exact="@$sellStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                <!-- Check sector (sectoractivity AND sectortravel) unless whitelisted -->
                <set_value name="$sellSectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $sellStation.sector">
                      <set_value name="$sellSectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <set_value name="$sellSectorActivityBlacklisted" exact="false"/>
                <set_value name="$sellSectorTravelBlacklisted" exact="false"/>
                <do_if value="not $sellSectorWhitelisted">
                  <set_value name="$sellSectorActivityBlacklisted" exact="@$sellStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$sellSectorTravelBlacklisted" exact="@$sellStation.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                </do_if>
                
                <!-- Always check if target sector is blacklisted -->
                <!-- Escape exception: Allow sell sector if ship is already IN it (escape FROM) -->
                <!-- But still block if ship needs to travel TO a blacklisted sector -->
                <do_if value="$sellSectorActivityBlacklisted or $sellSectorTravelBlacklisted">
                  <do_if value="$sellSector == $currentSector">
                    <!-- Ship is already in sell sector - allow escape FROM blacklisted sector -->
                    <!-- Only block if station itself is blacklisted -->
                    <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
                  </do_if>
                  <do_else>
                    <!-- Ship needs to travel TO a blacklisted sector - BLOCK -->
                    <set_value name="$sellBlacklisted" exact="true"/>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- Target sector is not blacklisted - only check station -->
                  <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SELL blacklist check:' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (blacklisted: ' + $currentSectorIsBlacklisted + ')' +
                    '\n  Station: ' + @$sellStation.knownname + 
                    '\n  Sector: ' + @$sellStation.sector.knownname + 
                    '\n  Station (objectactivity): ' + $sellStationBlacklisted + 
                    '\n  Sector (sectoractivity): ' + $sellSectorActivityBlacklisted + 
                    '\n  Sector (sectortravel): ' + $sellSectorTravelBlacklisted + 
                    '\n  Ship in sell sector: ' + ($sellSector == $currentSector) +
                    '\n  Final result: ' + $sellBlacklisted" 
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Block intra-sector trades in blacklisted sectors -->
              <!-- If ship is in blacklisted sector and both buy/sell are in same sector, block to force escape -->
              <set_value name="$isIntraSectorTradeInBlacklisted" exact="false"/>
              <do_if value="$currentSectorIsBlacklisted and $buySector == $currentSector and $sellSector == $currentSector">
                <set_value name="$isIntraSectorTradeInBlacklisted" exact="true"/>
                <set_value name="$buyBlacklisted" exact="true"/>  <!-- Block by marking as blacklisted -->
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Intra-sector trade BLOCKED (escape required):' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (BLACKLISTED)' +
                    '\n  Buy/Sell: Both in ' + @$currentSector.knownname +
                    '\n  Reason: Ship must escape from blacklisted sector'"
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Check if buy/sell station is MK1-supplied (final safety check) -->
              <do_if value="not $buyBlacklisted and not $sellBlacklisted and $effectiveIgnoreMK1Supply? and $effectiveIgnoreMK1Supply and global.$GT_MK1SuppliedStations?">
                <do_if value="$buyStation? and global.$GT_MK1SuppliedStations.{$buyStation}?">
                  <set_value name="$buyBlacklisted" exact="true"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” buy station ' + @$buyStation.knownname + ' is MK1-supplied'" chance="@this.$debugchance"/>
                </do_if>
                <do_if value="not $buyBlacklisted and $sellStation? and global.$GT_MK1SuppliedStations.{$sellStation}?">
                  <set_value name="$sellBlacklisted" exact="true"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” sell station ' + @$sellStation.knownname + ' is MK1-supplied'" chance="@this.$debugchance"/>
                </do_if>
              </do_if>

              <!-- Check if trade is blacklisted -->
              <do_if value="$buyBlacklisted or $sellBlacklisted">
                <!-- BLACKLISTED - Skip to next trade in list -->
                <set_value name="$tradesBlacklisted" operation="add"/>
                <set_value name="$blacklistedStation" exact="if $buyBlacklisted then $buyStation else $sellStation"/>
                <set_value name="$tradeType" exact="if $buyBlacklisted then 'BUY' else 'SELL'"/>
                
                <!-- Determine what was blacklisted (station or sector) -->
                <set_value name="$blacklistReason" exact="'Sector (sectortravel)'"/>  <!-- Default to most common case -->
                <do_if value="$buyBlacklisted">
                  <do_if value="$buyStationBlacklisted">
                    <set_value name="$blacklistReason" exact="'Station (objectactivity)'"/>
                  </do_if>
                  <do_elseif value="$buySectorActivityBlacklisted">
                    <set_value name="$blacklistReason" exact="'Sector (sectoractivity)'"/>
                  </do_elseif>
                </do_if>
                <do_else>
                  <do_if value="$sellStationBlacklisted">
                    <set_value name="$blacklistReason" exact="'Station (objectactivity)'"/>
                  </do_if>
                  <do_elseif value="$sellSectorActivityBlacklisted">
                    <set_value name="$blacklistReason" exact="'Sector (sectoractivity)'"/>
                  </do_elseif>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' BLACKLISTED:' +
                    '\n  Station: ' + @$blacklistedStation.knownname + 
                    '\n  Sector: ' + @$blacklistedStation.sector.knownname + 
                    '\n  Type: ' + $tradeType + 
                    '\n  Reason: ' + $blacklistReason + 
                    '\n  â†’ Trying next trade in list...'" 
                    chance="100"/>
                </do_if>
                
                <!-- Record failed sector for future filtering -->
                <signal_objects object="player.galaxy" param="'GT_Trade_Failed'" param2="table[
                  $Ship = this.ship,
                  $Reason = 'TRADEPARTNER_BLACKLISTED',
                  $FailureText = 'Trade partner is blacklisted (pre-validation)',
                  $Partner = $blacklistedStation,
                  $IsBuying = $buyBlacklisted,
                  $Ware = @$currentTrade.$Ware
                ]"/>
                
                <!-- Scenario 3: Flag ship-specific blacklist failure on cache entry -->
                <do_if value="$searchMethod == 'cache'">
                  <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'blacklisted']"/>
                </do_if>
                
                <!-- Continue to next trade in list -->
                <continue/>
              </do_if>
              
              <!-- Fleet reservation check: skip trades reserved by other ships.
                   Restored from pre-migration gt_trading_search.xml reservation flow.
                   Uses SellOffer object as key (Method B from GT_GenerateTradeKey). -->
              <do_if value="global.$GT_Reservations? and $currentTrade.$SellOffer?">
                <set_value name="$resKey" exact="$currentTrade.$SellOffer"/>
                <do_if value="global.$GT_Reservations.{$resKey}?">
                  <set_value name="$resData" exact="global.$GT_Reservations.{$resKey}"/>
                  <do_if value="$resData.$Until? and player.age lt @$resData.$Until and $resData.$Ship? and @$resData.$Ship != this.ship">
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' RESERVED by ' + @$resData.$Ship.idcode + ' (expires in ' + (@$resData.$Until - player.age) + ') - skipping'" chance="100"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- Check if ship can carry this ware type (cargo bay compatibility) -->
              <!-- Some wares (like Methane/gas) require special cargo bays that normal ships don't have -->
              <!-- For sell-only trades, use $Ware instead of $BuyOffer.ware -->
              <set_value name="$ware" exact="null"/>
              <do_if value="$isSellOnlyTrade and $currentTrade.$Ware?">
                <set_value name="$ware" exact="$currentTrade.$Ware"/>
              </do_if>
              <do_elseif value="$currentTrade.$BuyOffer?">
                <set_value name="$ware" exact="@$currentTrade.$BuyOffer.ware"/>
              </do_elseif>
              
              <do_if value="$ware? and $ware != null">
                <set_value name="$canCarryWareType" exact="this.ship.cargo.{$ware}.max gt 0"/>
                
                <do_if value="not $canCarryWareType">
                  <!-- SHIP CANNOT CARRY THIS WARE TYPE - Skip to next trade -->
                  <set_value name="$tradesRejectedCargo" operation="add"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' INCOMPATIBLE CARGO TYPE:' +
                      '\n  Ware: ' + @$ware.name + 
                      '\n  Reason: Ship does not have required cargo bay type (e.g., liquid/gas requires special containment)' +
                      '\n  Ship cargo max for this ware: ' + this.ship.cargo.{$ware}.max +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  
                  <!-- Scenario 3: Flag ship-specific cargo incompatibility on cache entry -->
                  <do_if value="$searchMethod == 'cache'">
                    <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'cargo_incompatible']"/>
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- Validation passed - this trade is valid -->
                <!-- Note: Cargo space and money validation will be handled by clamp_trade_amount before order creation -->
                <!-- Use safe access for tradeIdx -->
                <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' passed validation - checking offer availability...'" chance="100"/>
                </do_if>
                
                <!-- Check offer validity INSIDE loop before breaking -->
                <!-- This allows us to try the next trade if offers are consumed -->
                <!-- Initialize variables before conditionals to prevent property lookup errors -->
                <set_value name="$buyOfferStillValid" exact="true"/>
                <set_value name="$sellOfferStillValid" exact="false"/>
                <set_value name="$buyOfferAvailable" exact="null"/>
                <set_value name="$buyOfferAmount" exact="null"/>
                <set_value name="$sellOfferAvailable" exact="null"/>
                <set_value name="$sellOfferAmount" exact="null"/>
                <set_value name="$buyOfferOwnerValid" exact="true"/>
                <set_value name="$sellOfferOwnerValid" exact="true"/>
                
                <do_if value="$isSellOnlyTrade">
                  <!-- Sell-only trade: only check sell offer -->
                  <do_if value="$currentTrade.$SellOffer?">
                    <set_value name="$sellOfferAvailable" exact="$currentTrade.$SellOffer.available"/>
                    <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and @$currentTrade.$SellOffer.amount gt 0">
                      <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.amount"/>
                    </do_if>
                    <set_value name="$sellOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$SellOffer.owner?">
                      <set_value name="$sellOwnerTmp" exact="@$currentTrade.$SellOffer.owner"/>
                      <do_if value="$sellOwnerTmp? and $sellOwnerTmp.exists">
                        <set_value name="$sellOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$sellOfferStillValid" exact="$sellOfferAvailable and ($sellOfferAmount? and $sellOfferAmount gt 0) and $sellOfferOwnerValid"/>
                    <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$sellDesiredBefore" exact="@$currentTrade.$SellOffer.desiredamount"/>
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': pre-validate SELL-ONLY' +
                        '\n  needed=' + $currentTrade.$Amount +
                        '\n  sell offeramount(ship)=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') +
                        '\n  sell desiredamount=' + (if $sellDesiredBefore? then $sellDesiredBefore else 'null')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Sell-only trade but no sell offer - invalid -->
                    <set_value name="$sellOfferStillValid" exact="false"/>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- Normal trade: check both offers -->
                  <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$SellOffer?">
                    <!-- Check buy offer: available AND has SOME amount (clamping will handle exact amount reduction) -->
                    <set_value name="$buyOfferAvailable" exact="$currentTrade.$BuyOffer.available"/>
                    <set_value name="$buyOfferAmount" exact="@$currentTrade.$BuyOffer.offeramount.{this.ship}"/>
                    <do_if value="(not $buyOfferAmount? or $buyOfferAmount le 0) and @$currentTrade.$BuyOffer.amount gt 0">
                      <set_value name="$buyOfferAmount" exact="@$currentTrade.$BuyOffer.amount"/>
                    </do_if>
                    <do_if value="(not $buyOfferAmount? or $buyOfferAmount le 0) and $currentTrade.$SellOffer.owner? and @$currentTrade.$SellOffer.owner.exists">
                      <set_value name="$preValBuyWare" exact="if $currentTrade.$Ware? then $currentTrade.$Ware else null"/>
                      <do_if value="not $preValBuyWare? and @$currentTrade.$BuyOffer.ware != null">
                        <set_value name="$preValBuyWare" exact="@$currentTrade.$BuyOffer.ware"/>
                      </do_if>
                      <do_if value="$preValBuyWare?">
                        <set_value name="$buyOfferAmount" exact="[0, $currentTrade.$SellOffer.owner.cargo.{$preValBuyWare}.target - $currentTrade.$SellOffer.owner.cargo.{$preValBuyWare}.count].max"/>
                      </do_if>
                    </do_if>
                    <set_value name="$buyOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$BuyOffer.owner?">
                      <set_value name="$buyOwnerTmp" exact="@$currentTrade.$BuyOffer.owner"/>
                      <do_if value="$buyOwnerTmp? and $buyOwnerTmp.exists">
                        <set_value name="$buyOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$buyOfferStillValid" exact="$buyOfferAvailable and ($buyOfferAmount? and $buyOfferAmount gt 0) and $buyOfferOwnerValid"/>
                    
                    <!-- Check sell offer: available AND has SOME amount (clamping will handle exact amount reduction) -->
                    <set_value name="$sellOfferAvailable" exact="$currentTrade.$SellOffer.available"/>
                    <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and @$currentTrade.$SellOffer.amount gt 0">
                      <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.amount"/>
                    </do_if>
                    <set_value name="$sellOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$SellOffer.owner?">
                      <set_value name="$sellOwnerTmp" exact="@$currentTrade.$SellOffer.owner"/>
                      <do_if value="$sellOwnerTmp? and $sellOwnerTmp.exists">
                        <set_value name="$sellOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$sellOfferStillValid" exact="$sellOfferAvailable and ($sellOfferAmount? and $sellOfferAmount gt 0) and $sellOfferOwnerValid"/>
                    
                    <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$buyDesiredBefore" exact="@$currentTrade.$BuyOffer.desiredamount"/>
                      <set_value name="$sellDesiredBefore" exact="@$currentTrade.$SellOffer.desiredamount"/>
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': pre-validate NORMAL' +
                        '\n  needed=' + $currentTrade.$Amount +
                        '\n  buy offeramount(ship)=' + (if $buyOfferAmount? then $buyOfferAmount else 'null') +
                        '\n  buy desiredamount=' + (if $buyDesiredBefore? then $buyDesiredBefore else 'null') +
                        '\n  sell offeramount(ship)=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') +
                        '\n  sell desiredamount=' + (if $sellDesiredBefore? then $sellDesiredBefore else 'null')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Normal trade but missing offers - invalid -->
                    <set_value name="$buyOfferStillValid" exact="false"/>
                    <set_value name="$sellOfferStillValid" exact="false"/>
                  </do_else>
                </do_else>
                
                <!-- Check if offers are valid - conditional based on trade type -->
                <set_value name="$offersInvalid" exact="false"/>
                <do_if value="$isSellOnlyTrade">
                  <!-- Sell-only trade: only check sell offer -->
                  <set_value name="$offersInvalid" exact="not $sellOfferStillValid"/>
                </do_if>
                <do_else>
                  <!-- Normal trade: check both offers -->
                  <set_value name="$offersInvalid" exact="not $buyOfferStillValid or not $sellOfferStillValid"/>
                </do_else>
                
                <do_if value="$offersInvalid">
                  <!-- Offer became invalid - try next trade in list -->
                  <set_value name="$tradesRejectedOfferInvalid" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <!-- Compute precise invalid reason (buy/sell availability vs amount shortfall) -->
                    <set_value name="$offerInvalidReason" exact="''"/>
                    <do_if value="$isSellOnlyTrade">
                      <do_if value="not $sellOfferAvailable">
                        <set_value name="$offerInvalidReason" exact="'sell_not_available'"/>
                      </do_if>
                      <do_elseif value="not $sellOfferAmount?">
                        <set_value name="$offerInvalidReason" exact="'sell_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$sellOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$offerInvalidReason" exact="'sell_amount_lt_needed'"/>
                      </do_elseif>
                      <do_else>
                        <set_value name="$offerInvalidReason" exact="'sell_unknown'"/>
                      </do_else>
                    </do_if>
                    <do_else>
                      <set_value name="$buyInvalidReason" exact="'ok'"/>
                      <set_value name="$sellInvalidReason" exact="'ok'"/>
                      <do_if value="not $buyOfferAvailable">
                        <set_value name="$buyInvalidReason" exact="'buy_not_available'"/>
                      </do_if>
                      <do_elseif value="not $buyOfferAmount?">
                        <set_value name="$buyInvalidReason" exact="'buy_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$buyOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$buyInvalidReason" exact="'buy_amount_lt_needed'"/>
                      </do_elseif>
                      <do_if value="not $sellOfferAvailable">
                        <set_value name="$sellInvalidReason" exact="'sell_not_available'"/>
                      </do_if>
                      <do_elseif value="not $sellOfferAmount?">
                        <set_value name="$sellInvalidReason" exact="'sell_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$sellOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$sellInvalidReason" exact="'sell_amount_lt_needed'"/>
                      </do_elseif>
                      <set_value name="$offerInvalidReason" exact="'buy=' + $buyInvalidReason + ', sell=' + $sellInvalidReason"/>
                    </do_else>

                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' offer became invalid:' +
                      '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                      '\n  Buy offer: ' + (if $isSellOnlyTrade then 'N/A' else (if $buyOfferAvailable? then ('available=' + $buyOfferAvailable + ', amount=' + (if $buyOfferAmount? then $buyOfferAmount else 'null') + ' (needed: ' + $currentTrade.$Amount + ')') else 'MISSING')) +
                      '\n  Sell offer: available=' + (if $sellOfferAvailable? then $sellOfferAvailable else 'null') + ', amount=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') + ' (needed: ' + $currentTrade.$Amount + ')' +
                      '\n  Failure: ' + $offerInvalidReason +
                      '\n  Reason: offer unavailable or amount is 0/null (clamping would handle partial amounts, but offer is completely unavailable)' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  
                  <!-- Cache maintenance: distinguish universally dead offers (PURGE) from
                       temporary saturation (SKIP) from permanent ship-specific failure (FLAG).
                       .available and .owner.exists are universal; offeramount.{ship} is transient. -->
                  <do_if value="$searchMethod == 'cache'">
                    <!-- Determine if offers are universally dead (not available / owner destroyed) -->
                    <set_value name="$universallyDead" exact="false"/>
                    <do_if value="not $isSellOnlyTrade">
                      <do_if value="(not $buyOfferAvailable) or (not $buyOfferOwnerValid)">
                        <set_value name="$universallyDead" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_if value="(not $sellOfferAvailable) or (not $sellOfferOwnerValid)">
                      <set_value name="$universallyDead" exact="true"/>
                    </do_if>
                    
                    <do_if value="$universallyDead">
                      <!-- Scenario 1: Offer genuinely dead â€” purge from cache -->
                      <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                        $Ship = this.ship,
                        $BuyOffer = @$currentTrade.$BuyOffer,
                        $SellOffer = @$currentTrade.$SellOffer,
                        $HomeSector = $searchHomeSector,
                        $Reason = 'offer_dead'
                      ]"/>
                    </do_if>
                    <!-- If offers are alive but amount=0: fleet saturation (capacity reserved by
                         other ships' pending trades). This is TRANSIENT â€” capacity frees up when
                         trades complete. Do NOT flag or purge; just skip silently. Flagging would
                         permanently blacklist this ship for a temporary condition. -->
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- HYBRID APPROACH: Use clamp_trade_amount for final amount validation BEFORE breaking -->
                <!-- This handles cargo space, money, and offer availability automatically -->
                <!-- If clamping results in 0, continue to next trade instead of breaking -->
                <set_value name="$finalBuyAmount" exact="$currentTrade.$Amount"/>
                <set_value name="$finalSellAmount" exact="$currentTrade.$Amount"/>
                <set_value name="$buyClampReason" exact="null"/>
                <set_value name="$sellClampReason" exact="null"/>
                <set_value name="$clampFailed" exact="false"/>
                <set_value name="$buyClampSeller" exact="null"/>
                <set_value name="$sellClampBuyer" exact="null"/>
                
                <!-- PROFIT DEBUG: Log original amount before clamping -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                  <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') AMOUNT CLAMPING START:' + 
                    '\n  Ware: ' + $wareName +
                    '\n  Original Amount (from trade object): ' + $currentTrade.$Amount + ' units' +
                    '\n  Trade Profit (RAW): ' + (if $currentTrade.$Profit? then $currentTrade.$Profit else 'NULL') + ' = ' + (if $currentTrade.$Profit? then ($currentTrade.$Profit/100) + ' Cr' else 'NULL') +
                    '\n  Trade BuyPrice (RAW): ' + (if $currentTrade.$BuyPrice? then $currentTrade.$BuyPrice else 'NULL') + ' = ' + (if $currentTrade.$BuyPrice? then ($currentTrade.$BuyPrice/100) + ' Cr' else 'NULL') +
                    '\n  Trade SellPrice (RAW): ' + (if $currentTrade.$SellPrice? then $currentTrade.$SellPrice else 'NULL') + ' = ' + (if $currentTrade.$SellPrice? then ($currentTrade.$SellPrice/100) + ' Cr' else 'NULL')" chance="100"/>
                </do_if>
                
                <!-- Clamp buy order amount (for non-sell-only trades) -->
                <do_if value="not $isSellOnlyTrade and $currentTrade.$BuyOffer?">
                  <set_value name="$buyClampSeller" exact="null"/>
                  <do_if value="$currentTrade.$BuyOffer.seller?">
                    <set_value name="$buyClampSeller" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_if value="$buyClampSeller == null and $currentTrade.$BuyOffer.owner?">
                    <set_value name="$buyClampSeller" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_if>
                  <do_if value="$buyClampSeller != null">
                    <clamp_trade_amount 
                      trade="$currentTrade.$BuyOffer" 
                      amount="$finalBuyAmount" 
                      buyer="this.assignedcontrolled" 
                      seller="$buyClampSeller" 
                      result="$finalBuyAmount"
                      reason="$buyClampReason"/>
                  </do_if>
                  <do_else>
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <set_value name="$buyClampReason" exact="'seller_missing'"/>
                  </do_else>
                  <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$buyOfferAmountAfterClamp" exact="@$currentTrade.$BuyOffer.offeramount.{this.ship}"/>
                    <set_value name="$buyDesiredAfterClamp" exact="@$currentTrade.$BuyOffer.desiredamount"/>
                    <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': post-clamp BUY' +
                      '\n  original=' + $currentTrade.$Amount +
                      '\n  clamped=' + $finalBuyAmount +
                      '\n  buy offeramount(ship)=' + (if $buyOfferAmountAfterClamp? then $buyOfferAmountAfterClamp else 'null') +
                      '\n  buy desiredamount=' + (if $buyDesiredAfterClamp? then $buyDesiredAfterClamp else 'null') +
                      '\n  clampReason=' + (if $buyClampReason? then $buyClampReason else 'null')"
                      chance="100"/>
                  </do_if>

                  <do_if value="not $finalBuyAmount? or $finalBuyAmount == 0 or $finalBuyAmount lt 0">
                    <!-- Amount clamped to 0 or invalid - try next trade -->
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$clampReasonText" exact="if $buyClampReason? then $buyClampReason else 'unknown'"/>
                      <set_value name="$amountStatus" exact="if not $finalBuyAmount? then 'null' else if $finalBuyAmount lt 0 then 'negative (' + $finalBuyAmount + ')' else 'zero'"/>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' buy amount clamped to invalid value:' +
                        '\n  Original amount: ' + $currentTrade.$Amount +
                        '\n  Clamped amount: ' + $amountStatus +
                        '\n  Clamp reason: ' + $clampReasonText +
                        '\n  Reason: ' + (if $buyClampReason == 'buyer_cargo' then 'Insufficient cargo space' else if $buyClampReason == 'buyer_money' then 'Insufficient funds' else if $buyClampReason == 'seller_cargo' then 'Seller has insufficient stock' else 'Offer constraints') +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <do_if value="not $clampFailed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $finalBuyAmount != $currentTrade.$Amount">
                    <set_value name="$clampReasonText" exact="if $buyClampReason? then $buyClampReason else 'unknown'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' buy amount adjusted:' +
                      '\n  Original: ' + $currentTrade.$Amount +
                      '\n  Clamped: ' + $finalBuyAmount +
                      '\n  Reason: ' + $clampReasonText"
                      chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- Clamp sell order amount -->
                <do_if value="not $clampFailed and $currentTrade.$SellOffer?">
                  <set_value name="$sellClampBuyer" exact="null"/>
                  <do_if value="$currentTrade.$SellOffer.buyer?">
                    <set_value name="$sellClampBuyer" exact="@$currentTrade.$SellOffer.buyer"/>
                  </do_if>
                  <do_if value="$sellClampBuyer == null and $currentTrade.$SellOffer.owner?">
                    <set_value name="$sellClampBuyer" exact="@$currentTrade.$SellOffer.owner"/>
                  </do_if>
                  <do_if value="$sellClampBuyer == null">
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <set_value name="$sellClampReason" exact="'buyer_missing'"/>
                  </do_if>
                  
                  <do_if value="$isSellOnlyTrade">
                    <!-- Sell-only trade: Ship already has cargo, validate against ship cargo -->
                    <do_if value="not $clampFailed">
                      <clamp_trade_amount 
                        trade="$currentTrade.$SellOffer" 
                        amount="$finalSellAmount" 
                        buyer="$sellClampBuyer" 
                        seller="this.ship" 
                        result="$finalSellAmount"
                        reason="$sellClampReason"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Normal trade: Ship doesn't have cargo yet (will buy first), don't check seller cargo -->
                    <!-- Match vanilla pattern: clamp without seller parameter (only checks buyer constraints) -->
                    <!-- Vanilla comment: "it is possible that this doesn't have the wares yet if they still need to be bought" -->
                    <do_if value="not $clampFailed">
                      <clamp_trade_amount 
                        trade="$currentTrade.$SellOffer" 
                        amount="$finalSellAmount" 
                        buyer="$sellClampBuyer" 
                        result="$finalSellAmount"
                        reason="$sellClampReason"/>
                    </do_if>
                  </do_else>
                  
                  <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$sellOfferAmountAfterClamp" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <set_value name="$sellDesiredAfterClamp" exact="@$currentTrade.$SellOffer.desiredamount"/>
                    <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': post-clamp SELL' +
                      '\n  original=' + $currentTrade.$Amount +
                      '\n  clamped=' + $finalSellAmount +
                      '\n  sell offeramount(ship)=' + (if $sellOfferAmountAfterClamp? then $sellOfferAmountAfterClamp else 'null') +
                      '\n  sell desiredamount=' + (if $sellDesiredAfterClamp? then $sellDesiredAfterClamp else 'null') +
                      '\n  clampReason=' + (if $sellClampReason? then $sellClampReason else 'null')"
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="not $finalSellAmount? or $finalSellAmount == 0 or $finalSellAmount lt 0">
                    <!-- Amount clamped to 0 or invalid - try next trade -->
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$clampReasonText" exact="if $sellClampReason? then $sellClampReason else 'unknown'"/>
                      <set_value name="$amountStatus" exact="if not $finalSellAmount? then 'null' else if $finalSellAmount lt 0 then 'negative (' + $finalSellAmount + ')' else 'zero'"/>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' sell amount clamped to invalid value:' +
                        '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                        '\n  Original amount: ' + $currentTrade.$Amount +
                        '\n  Clamped amount: ' + $amountStatus +
                        '\n  Clamp reason: ' + $clampReasonText +
                        '\n  Reason: ' + (if $sellClampReason == 'buyer_cargo' then 'Buyer has insufficient cargo space' else if $sellClampReason == 'buyer_money' then 'Buyer has insufficient funds' else if $sellClampReason == 'seller_cargo' then 'Ship has insufficient cargo' else 'Offer constraints') +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <do_if value="not $clampFailed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $finalSellAmount != $currentTrade.$Amount">
                    <set_value name="$clampReasonText" exact="if $sellClampReason? then $sellClampReason else 'unknown'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' sell amount adjusted:' +
                      '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                      '\n  Original: ' + $currentTrade.$Amount +
                      '\n  Clamped: ' + $finalSellAmount +
                      '\n  Reason: ' + $clampReasonText"
                      chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- If clamping failed, continue to next trade -->
                <do_if value="$clampFailed">
                  <continue/>
                </do_if>

                <!-- CRITICAL: For NORMAL trades, BUY and SELL amounts must match.
                     clamp_trade_amount can clamp BUY (ship cargo/money) and SELL (buyer constraints) independently.
                     Final executed amount must be the minimum of both. -->
                <do_if value="not $isSellOnlyTrade">
                  <set_value name="$finalAmount" exact="[$finalBuyAmount, $finalSellAmount].min"/>
                  
                  <!-- PROFIT DEBUG: Log amount syncing details -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') AMOUNT SYNCING:' + 
                      '\n  Ware: ' + $wareName +
                      '\n  Original Amount: ' + $currentTrade.$Amount + ' units' +
                      '\n  Clamped Buy Amount: ' + $finalBuyAmount + ' units' +
                      '\n  Clamped Sell Amount: ' + $finalSellAmount + ' units' +
                      '\n  Final Amount (min): ' + $finalAmount + ' units' +
                      '\n  Amount changed: ' + (if $finalAmount != $currentTrade.$Amount then 'YES (was ' + $currentTrade.$Amount + ', now ' + $finalAmount + ')' else 'NO') +
                      '\n  Trade Profit (unchanged): ' + (if $currentTrade.$Profit? then ($currentTrade.$Profit/100) + ' Cr' else 'NULL')" chance="100"/>
                  </do_if>
                  
                  <set_value name="$finalBuyAmount" exact="$finalAmount"/>
                  <set_value name="$finalSellAmount" exact="$finalAmount"/>
                </do_if>

                <!-- HARD FILTER: Minimum cargo utilization threshold (live/cache/fallback only; excluded in isolated mode) -->
                <set_value name="$isIsolatedForCargoFilter" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
                <set_value name="$applyMinCargoUtilFilter" exact="not $isSellOnlyTrade and not $isIsolatedForCargoFilter and ($searchMethod == 'live' or $searchMethod == 'live_ship_route' or $searchMethod == 'cache' or $searchMethod == 'live_fallback')"/>
                <do_if value="$applyMinCargoUtilFilter">
                  <set_value name="$utilWare" exact="null"/>
                  <do_if value="$currentTrade.$Ware?">
                    <set_value name="$utilWare" exact="$currentTrade.$Ware"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware?">
                    <set_value name="$utilWare" exact="@$currentTrade.$BuyOffer.ware"/>
                  </do_elseif>
                  <do_elseif value="$currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware?">
                    <set_value name="$utilWare" exact="@$currentTrade.$SellOffer.ware"/>
                  </do_elseif>

                  <set_value name="$utilVolumePerUnit" exact="1"/>
                  <do_if value="$utilWare?">
                    <do_if value="$utilWare.volume?">
                      <set_value name="$utilVolumePerUnit" exact="$utilWare.volume"/>
                    </do_if>
                  </do_if>

                  <set_value name="$shipCargoCapacityVol" exact="this.ship.cargo.capacity.all"/>
                  <set_value name="$tradeCargoVolume" exact="$finalBuyAmount * $utilVolumePerUnit"/>
                  <set_value name="$requiredCargoVolume" exact="($shipCargoCapacityVol * $cargoUtilThresholdPct) / 100.0"/>
                  <set_value name="$cargoUtilizationPct" exact="if $shipCargoCapacityVol gt 0 then ($tradeCargoVolume * 100.0) / $shipCargoCapacityVol else 0"/>

                  <!-- Bypass cargo utilization for priority wares: player explicitly wants these even if low volume -->
                  <set_value name="$isPriorityWareForCargo" exact="false"/>
                  <do_if value="$pwForReorder? and $pwForReorder.count gt 0 and $utilWare?">
                    <do_all exact="$pwForReorder.count" counter="$pwc">
                      <set_value name="$pwcItem" exact="$pwForReorder.{$pwc}"/>
                      <do_if value="$pwcItem == $utilWare or ($pwcItem? and $pwcItem.id? and $utilWare.id? and $pwcItem.id == $utilWare.id)">
                        <set_value name="$isPriorityWareForCargo" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>

                  <do_if value="$tradeCargoVolume lt $requiredCargoVolume and not $isPriorityWareForCargo">
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by minimum cargo utilization filter:' +
                        '\n  Threshold: ' + $cargoUtilThresholdPct + '%' +
                        '\n  Actual: ' + $cargoUtilizationPct + '%' +
                        '\n  Amount: ' + $finalBuyAmount +
                        '\n  Volume/unit: ' + $utilVolumePerUnit +
                        '\n  Trade volume: ' + $tradeCargoVolume + ' / Capacity: ' + $shipCargoCapacityVol +
                        '\n  Search method: ' + $searchMethod +
                        '\n  Isolated mode: ' + $isIsolatedForCargoFilter +
                        '\n  â†’ Trying next trade in list...'" chance="100"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
                
                <!-- CRITICAL FIX: Always recalculate profit using live offer prices and final amount -->
                <!-- Cache is only a hint - market prices change constantly, so we must always validate -->
                <set_value name="$buyPriceForRecalc" exact="null"/>
                <set_value name="$sellPriceForRecalc" exact="null"/>
                
                <!-- Use actual offer prices only (no stored-price fallback). -->
                <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.unitprice?">
                  <set_value name="$buyPriceForRecalc" exact="$currentTrade.$BuyOffer.unitprice"/>
                </do_if>
                
                <do_if value="$currentTrade.$SellOffer? and $currentTrade.$SellOffer.unitprice?">
                  <set_value name="$sellPriceForRecalc" exact="$currentTrade.$SellOffer.unitprice"/>
                </do_if>
                
                <!-- ALWAYS recalculate profit when prices are available (regardless of amount change) -->
                <!-- This ensures cached trades with wrong profit are caught and validated -->
                <set_value name="$amountChanged" exact="if $isSellOnlyTrade then ($finalSellAmount != $currentTrade.$Amount) else ($finalBuyAmount != $currentTrade.$Amount)"/>
                <set_value name="$finalProfitRAW" exact="null"/>
                <set_value name="$profitRecalculated" exact="false"/>
                
                <do_if value="$currentTrade.$Amount? and $buyPriceForRecalc? and $sellPriceForRecalc?">
                  <!-- Store original values before recalculation -->
                  <set_value name="$originalAmount" exact="$currentTrade.$Amount"/>
                  <set_value name="$originalProfitRAW" exact="if $currentTrade.$Profit? then $currentTrade.$Profit else 0"/>
                  
                  <!-- Calculate final amount for profit calculation -->
                  <set_value name="$finalAmountForProfit" exact="if $isSellOnlyTrade then $finalSellAmount else $finalBuyAmount"/>
                  
                  <!-- ALWAYS recalculate profit: (sellPrice - buyPrice) * finalAmount -->
                  <!-- This validates against current market prices, not cached values -->
                  <set_value name="$recalculatedProfitRAW" exact="($sellPriceForRecalc - $buyPriceForRecalc) * $finalAmountForProfit"/>
                  <set_value name="$finalProfitRAW" exact="$recalculatedProfitRAW"/>
                  <set_value name="$profitRecalculated" exact="true"/>
                  
                  <!-- Update trade object profit (for logbook display) -->
                  <set_value name="$currentTrade.$Profit" exact="$recalculatedProfitRAW"/>
                  
                  <!-- Always refresh price snapshots to match live offers used for profit validation. -->
                  <set_value name="$currentTrade.$BuyPrice" exact="$buyPriceForRecalc"/>
                  <set_value name="$currentTrade.$SellPrice" exact="$sellPriceForRecalc"/>
                  
                  <!-- PROFIT DEBUG: Log profit recalculation -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <set_value name="$priceSource" exact="'live_offer_at_validation'"/>
                    <set_value name="$amountStatus" exact="if $amountChanged then 'YES (was ' + $originalAmount + ', now ' + $finalAmountForProfit + ')' else 'NO (unchanged: ' + $finalAmountForProfit + ')'"/>
                    <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') PROFIT RECALCULATION (ALWAYS):' + 
                      '\n  Ware: ' + $wareName +
                      '\n  Price Source: ' + $priceSource +
                      '\n  Amount Changed: ' + $amountStatus +
                      '\n  Original Amount: ' + $originalAmount + ' units' +
                      '\n  Final Amount: ' + $finalAmountForProfit + ' units' +
                      '\n  Original Profit (cached): ' + ($originalProfitRAW/100) + ' Cr (RAW: ' + $originalProfitRAW + ')' +
                      '\n  Recalculated Profit (validated): ' + ($recalculatedProfitRAW/100) + ' Cr (RAW: ' + $recalculatedProfitRAW + ')' +
                      '\n  Buy Price: ' + ($buyPriceForRecalc/100) + ' Cr (RAW: ' + $buyPriceForRecalc + ')' +
                      '\n  Sell Price: ' + ($sellPriceForRecalc/100) + ' Cr (RAW: ' + $sellPriceForRecalc + ')' +
                      '\n  Verification: (' + ($sellPriceForRecalc/100) + ' - ' + ($buyPriceForRecalc/100) + ') * ' + $finalAmountForProfit + ' = ' + (($sellPriceForRecalc - $buyPriceForRecalc) * $finalAmountForProfit / 100) + ' Cr'" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Prices missing - cannot recalculate profit, reject trade -->
                  <set_value name="$tradesRejectedProfit" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' REJECTED: Cannot validate profit' +
                      '\n  Ware: ' + $wareName +
                      '\n  Reason: Prices missing from trade object and offers, cannot recalculate/validate profit' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  <continue/>
                </do_else>
                
                <!-- CRITICAL: Validate recalculated profit - reject negative or zero profit trades -->
                <do_if value="not $finalProfitRAW? or $finalProfitRAW le 0">
                  <set_value name="$tradesRejectedProfit" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <set_value name="$profitStatus" exact="if not $finalProfitRAW? then 'NULL' else if $finalProfitRAW == 0 then 'ZERO' else 'NEGATIVE (' + ($finalProfitRAW/100) + ' Cr)'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' REJECTED: Profit validation failed' +
                      '\n  Ware: ' + $wareName +
                      '\n  Final Profit (recalculated): ' + $profitStatus +
                      '\n  Reason: Trade is unprofitable (market prices changed or cached profit was wrong)' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  <continue/>
                </do_if>
                
                <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=trade -->
                <set_value name="$finalDockingCheck" exact="true"/>
                
                <!-- Check buy station docking (for non-sell-only trades) -->
                <do_if value="not $isSellOnlyTrade and $finalDockingCheck and $buyStation?">
                  <run_script name="'lib.gt.dockcheck'" result="$mk3FinalBuyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$buyStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <do_if value="not $mk3FinalBuyDockResult.$CanDock">
                    <set_value name="$finalDockingCheck" exact="false"/>
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' Final docking check FAILED (buy station): ' + @$buyStation.knownname + 
                        '\n  Sector: ' + @$buyStation.sector.knownname + 
                        '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- Check sell station docking -->
                <do_if value="$finalDockingCheck and $sellStation?">
                  <run_script name="'lib.gt.dockcheck'" result="$mk3FinalSellDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <do_if value="not $mk3FinalSellDockResult.$CanDock">
                    <set_value name="$finalDockingCheck" exact="false"/>
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' Final docking check FAILED (sell station): ' + @$sellStation.knownname + 
                        '\n  Sector: ' + @$sellStation.sector.knownname + 
                        '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- If final docking check failed, continue to next trade -->
                <do_if value="not $finalDockingCheck">
                  <continue/>
                </do_if>
                
                <!-- Buildstorage enforcement (inside loop so rejected trades try next) -->
                <do_if value="$enfIgnoreBuildStorage">
                  <set_value name="$_buyIsBuildStorage" exact="false"/>
                  <do_if value="$buyStation?">
                    <set_value name="$_buyIsBuildStorage" exact="$buyStation.isclass.buildstorage"/>
                  </do_if>
                  <set_value name="$_sellIsBuildStorage" exact="false"/>
                  <do_if value="$sellStation?">
                    <set_value name="$_sellIsBuildStorage" exact="$sellStation.isclass.buildstorage"/>
                  </do_if>
                  <do_if value="$_buyIsBuildStorage or $_sellIsBuildStorage">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by buildstorage restriction (buy=' + $_buyIsBuildStorage + ', sell=' + $_sellIsBuildStorage + ') â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'buildstorage_blocked']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
                
                <!-- Carrier/Aux enforcement (inside loop so rejected trades try next) -->
                <!-- Vanilla pattern: carriers = type==shiptype.carrier, aux = primarypurpose==purpose.auxiliary -->
                <!-- Do NOT use purpose.fight â€” that catches wharfs/shipyards (they build combat ships) -->
                <do_if value="$enfIgnoreCarrierAux">
                  <set_value name="$_rejectCarrierAux" exact="false"/>
                  <do_if value="$buyStation?">
                    <do_if value="@$buyStation.type == shiptype.carrier or @$buyStation.primarypurpose == purpose.auxiliary">
                      <set_value name="$_rejectCarrierAux" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_if value="not $_rejectCarrierAux and $sellStation?">
                    <do_if value="@$sellStation.type == shiptype.carrier or @$sellStation.primarypurpose == purpose.auxiliary">
                      <set_value name="$_rejectCarrierAux" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_if value="$_rejectCarrierAux">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by carrier/aux restriction â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'carrier_aux_blocked']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- MK3 faction blacklist enforcement in validation loop:
                     blocked entries must be skipped here (not only at final gate), otherwise
                     trade 1 can abort the whole cycle without trying trade 2..N. -->
                <do_if value="$mk3FactionBlacklistLoop.keys.count gt 0">
                  <set_value name="$_mk3BlockedTrade" exact="false"/>
                  <set_value name="$_mk3BlockedSide" exact="''"/>
                  <set_value name="$_mk3BlockedFaction" exact="null"/>

                  <do_if value="not $isSellOnlyTrade and $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.owner?">
                    <set_value name="$_mk3BuyOwnerContainer" exact="@$currentTrade.$BuyOffer.owner"/>
                    <do_if value="$_mk3BuyOwnerContainer.owner?">
                      <set_value name="$_mk3BuyFaction" exact="$_mk3BuyOwnerContainer.owner"/>
                    </do_if>
                    <do_else>
                      <set_value name="$_mk3BuyFaction" exact="$_mk3BuyOwnerContainer"/>
                    </do_else>
                    <do_if value="$_mk3BuyFaction? and $mk3FactionBlacklistLoop.{$_mk3BuyFaction}?">
                      <set_value name="$_mk3BlockedTrade" exact="true"/>
                      <set_value name="$_mk3BlockedSide" exact="'buy'"/>
                      <set_value name="$_mk3BlockedFaction" exact="$_mk3BuyFaction"/>
                    </do_if>
                  </do_if>

                  <do_if value="not $_mk3BlockedTrade and $currentTrade.$SellOffer? and $currentTrade.$SellOffer.owner?">
                    <set_value name="$_mk3SellOwnerContainer" exact="@$currentTrade.$SellOffer.owner"/>
                    <do_if value="$_mk3SellOwnerContainer.owner?">
                      <set_value name="$_mk3SellFaction" exact="$_mk3SellOwnerContainer.owner"/>
                    </do_if>
                    <do_else>
                      <set_value name="$_mk3SellFaction" exact="$_mk3SellOwnerContainer"/>
                    </do_else>
                    <do_if value="$_mk3SellFaction? and $mk3FactionBlacklistLoop.{$_mk3SellFaction}?">
                      <set_value name="$_mk3BlockedTrade" exact="true"/>
                      <set_value name="$_mk3BlockedSide" exact="'sell'"/>
                      <set_value name="$_mk3BlockedFaction" exact="$_mk3SellFaction"/>
                    </do_if>
                  </do_if>

                  <do_if value="$_mk3BlockedTrade">
                    <set_value name="$tradesBlacklisted" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by MK3 faction blacklist (' + $_mk3BlockedSide + ' faction): ' + (if $_mk3BlockedFaction? then $_mk3BlockedFaction.name else 'Unknown') + ' â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'mk3_faction_blacklist']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- Trade-rule enforcement: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
                <do_if value="not (if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false) and not $isSellOnlyTrade">
                  <set_value name="$_applyTradeRules" exact="false"/>
                  <do_if value="$buyStation? and @$buyStation.exists">
                    <do_if value="@$buyStation.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_if>
                    <do_elseif value="@$buyStation.isclass.buildstorage and $buyStation.base? and @$buyStation.base.exists and @$buyStation.base.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $_applyTradeRules and $sellStation? and @$sellStation.exists">
                    <do_if value="@$sellStation.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_if>
                    <do_elseif value="@$sellStation.isclass.buildstorage and $sellStation.base? and @$sellStation.base.exists and @$sellStation.base.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="$_applyTradeRules">
                    <set_value name="$_tradeRuleBlocked" exact="false"/>
                    <set_value name="$_tradeRuleReason" exact="''"/>
                    <do_if value="$currentTrade.$SellOffer? and $buyStation? and $buyStation.exists and not $currentTrade.$SellOffer.cantradewith.{$buyStation}">
                      <set_value name="$_tradeRuleBlocked" exact="true"/>
                      <set_value name="$_tradeRuleReason" exact="'customer ' + @$sellStation.knownname + ' disallows source ' + @$buyStation.knownname"/>
                    </do_if>
                    <do_if value="not $_tradeRuleBlocked and $currentTrade.$BuyOffer? and $sellStation? and $sellStation.exists and not $currentTrade.$BuyOffer.cantradewith.{$sellStation}">
                      <set_value name="$_tradeRuleBlocked" exact="true"/>
                      <set_value name="$_tradeRuleReason" exact="'source ' + @$buyStation.knownname + ' disallows delivery to ' + @$sellStation.knownname"/>
                    </do_if>
                    <do_if value="$_tradeRuleBlocked">
                      <set_value name="$tradesRejectedRestriction" operation="add"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by trade rules (' + $_tradeRuleReason + ') â†’ Trying next trade...'" chance="100"/>
                      </do_if>
                      <do_if value="$searchMethod == 'cache'">
                        <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'trade_rules_failed']"/>
                      </do_if>
                      <continue/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- All checks passed including clamping and final docking verification - this trade is valid -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' is VALID - using this trade!'" chance="100"/>
                </do_if>
                <set_value name="$validTradeFound" exact="true"/>
                <set_value name="$pendingTrade" exact="$currentTrade"/>
                <!-- Store clamped amounts in pendingTrade for use after loop -->
                <set_value name="$pendingTrade.$FinalBuyAmount" exact="$finalBuyAmount"/>
                <set_value name="$pendingTrade.$FinalSellAmount" exact="$finalSellAmount"/>
                <!-- Logbook price snapshot at validation (before create_trade_order mutates offer.unitprice). -->
                <set_value name="$pendingTrade.$LogbookBuyPriceRaw" exact="if $buyPriceForRecalc? then $buyPriceForRecalc else 0"/>
                <set_value name="$pendingTrade.$LogbookSellPriceRaw" exact="if $sellPriceForRecalc? then $sellPriceForRecalc else 0"/>
                
                <!-- Create fleet reservation (restored from pre-migration gt_trading_search.xml).
                     Prevents other ships from selecting this trade during the search-to-execution gap.
                     TTL=10s matches original release version. Cleared after create_trade_order (native takes over). -->
                <do_if value="global.$GT_Reservations? and $currentTrade.$SellOffer?">
                  <set_value name="global.$GT_Reservations.{$currentTrade.$SellOffer}" exact="table[
                    $Ship = this.ship,
                    $Until = player.age + 10s
                  ]"/>
                  <!-- Store reservation key on instance for cleanup in on_abort -->
                  <set_value name="this.$activeReservationKey" exact="$currentTrade.$SellOffer"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet reservation CREATED (TTL=10s, key=SellOffer)'" chance="100"/>
                  </do_if>
                  <!-- Update reservation stats -->
                  <do_if value="global.$GT_ReservationStats?">
                    <set_value name="global.$GT_ReservationStats.$Active" operation="add"/>
                  </do_if>
                </do_if>
                
                <!-- Break out of loop - we found a valid trade -->
                <break/>
              </do_if>
              <do_else>
                <!-- Ware couldn't be extracted - skip this trade -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' SKIPPED: Could not extract ware from trade data'" chance="100"/>
                </do_if>
                <continue/>
              </do_else>
            </do_if>
          
          <!-- Skip trade if currentTrade is null -->
          <do_else>
            <!-- Don't access $tradeIdx here - it might not exist if loop didn't execute -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade SKIPPED: Trade data is null'" chance="100"/>
            </do_if>
            <!-- Only use continue if we're actually in the loop -->
            <do_if value="$tradeIdx?">
              <continue/>
            </do_if>
          </do_else>
          </do_all>
        </do_if>
        <do_else>
          <!-- Trade list is empty or null - no trades to validate -->
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade list is empty or null - no trades to validate'" chance="100"/>
          <set_value name="$validTradeFound" exact="false"/>
        </do_else>
        
        <!-- After loop: Check if we found a valid trade -->
        <!-- Use safe access and check existence before accessing -->
        <do_if value="$validTradeFound? and $validTradeFound">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validation PASSED - creating trade orders (checked ' + $tradesChecked + ' trades, ' + $tradesRejectedPath + ' unreachable, ' + $tradesRejectedDocking + ' docking denied, ' + $tradesRejectedDistance + ' distance exceeded, ' + $tradesRejectedCargo + ' insufficient cargo, ' + $tradesBlacklisted + ' blacklisted, ' + $tradesRejectedRestriction + ' restriction blocked)'" chance="100"/>
          </do_if>
          
          <!-- Update pending trade entry with ACTUAL trade being executed -->
          <!-- Failure handler expects table with $BuyStation, $SellStation, $Ware -->
          <!-- Replace trade list with specific trade data for failure tracking -->
          <!-- Handle sell-only trades (BuyOffer may be null) -->
          <!-- Extract values from pendingTrade since loop variables may be out of scope -->
          <set_value name="$isSellOnlyTradeForPending" exact="false"/>
          <do_if value="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly">
            <set_value name="$isSellOnlyTradeForPending" exact="true"/>
          </do_if>
          
          <!-- Extract stations from pendingTrade (may have been set in loop, but extract to be safe) -->
          <set_value name="$buyStationForPending" exact="null"/>
          <set_value name="$sellStationForPending" exact="null"/>
          <do_if value="$pendingTrade.$BuyStation?">
            <set_value name="$buyStationForPending" exact="$pendingTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$pendingTrade.$BuyOffer?">
            <set_value name="$buyStationForPending" exact="@$pendingTrade.$BuyOffer.owner"/>
          </do_elseif>
          <do_else>
            <!-- Use loop variable if available, otherwise null (for sell-only trades) -->
            <set_value name="$buyStationForPending" exact="$buyStation"/>
          </do_else>
          
          <do_if value="$pendingTrade.$SellStation?">
            <set_value name="$sellStationForPending" exact="$pendingTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$pendingTrade.$SellOffer?">
            <set_value name="$sellStationForPending" exact="@$pendingTrade.$SellOffer.owner"/>
          </do_elseif>
          <do_else>
            <!-- Use loop variable if available -->
            <set_value name="$sellStationForPending" exact="$sellStation"/>
          </do_else>
          
          <set_value name="$wareForPendingTrade" exact="null"/>
          <do_if value="$isSellOnlyTradeForPending and $pendingTrade.$Ware?">
            <set_value name="$wareForPendingTrade" exact="$pendingTrade.$Ware"/>
          </do_if>
          <do_elseif value="$pendingTrade.$BuyOffer?">
            <set_value name="$wareForPendingTrade" exact="@$pendingTrade.$BuyOffer.ware"/>
          </do_elseif>
          
          <!-- Store the ACTIVE trade for failure tracking (do NOT overwrite the pending-results list). -->
          <do_if value="not global.$GT_ActiveTrade?">
            <set_value name="global.$GT_ActiveTrade" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_ActiveTrade.{this.ship}" exact="table[
            $BuyStation = $buyStationForPending,
            $SellStation = $sellStationForPending,
            $Ware = $wareForPendingTrade
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTradeForPending then 'N/A (sell-only)' else (if $buyStationForPending? then @$buyStationForPending.knownname else 'Unknown')"/>
            <set_value name="$sellStationNameForDebug" exact="if $sellStationForPending? then @$sellStationForPending.knownname else 'Unknown'"/>
            <set_value name="$wareNameForDebug" exact="if $wareForPendingTrade? then @$wareForPendingTrade.name else 'Unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Updated pending trade entry for failure tracking:' +
              '\n  Buy: ' + $buyStationNameForDebug +
              '\n  Sell: ' + $sellStationNameForDebug +
              '\n  Ware: ' + $wareNameForDebug"
              chance="100"/>
          </do_if>
          
          <!-- Final offer validity check and clamping moved inside loop -->
          <!-- Offers are validated and clamped before breaking out of the loop -->
          <!-- Final docking verification also moved inside loop - allows trying next trade if docking fails -->
          <!-- All checks passed including final docking verification (checked in loop) - safe to create orders with clamped amounts -->
          <!-- Clamped amounts are stored in $pendingTrade.$FinalBuyAmount and $pendingTrade.$FinalSellAmount -->
          <!-- Create X4 native TradePerform orders with blacklist routing -->
          <!-- CRITICAL: internal="true" is REQUIRED for vanilla to track pending trades and display count -->
          <!-- Without internal="true", vanilla won't set $internalorder in TradePerform, and pending trades won't be displayed -->
          <!-- For sell-only trades, skip buy order (ship already has cargo) -->
          <set_value name="$finalBuyAmount" exact="if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount"/>
          <set_value name="$finalSellAmount" exact="if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount"/>
          
          <!-- Re-resolve MK3 faction blacklist at final stage (path-independent safety). -->
          <set_value name="$mk3BlacklistOwnerFinal" exact="this.ship"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$mk3BlacklistOwnerFinal" exact="this.ship.commander"/>
          </do_if>
          <set_value name="$mk3FactionBlacklistFinal" exact="table[]"/>
          <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerFinal}?">
            <set_value name="$mk3FactionBlacklistFinal" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerFinal}"/>
          </do_if>
          
          <!-- CRITICAL FIX: Final validation immediately before order creation -->
          <!-- This catches cases where trade rules changed between earlier validation and order creation -->
          <!-- Re-check offers with tradepartner to ensure trade rules are still respected -->
          <set_value name="$finalBuyOfferValid" exact="true"/>
          <set_value name="$finalSellOfferValid" exact="true"/>
          <set_value name="$finalMK3BlacklistValid" exact="true"/>
          <set_value name="$finalRouteIllegalValid" exact="true"/>
          
          <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer?">
            <set_value name="$finalBuyStation" exact="if $pendingTrade.$BuyStation? then $pendingTrade.$BuyStation else (if $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner else null)"/>
            <set_value name="$finalBuyWare" exact="if $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else null"/>
            
            <do_if value="$finalBuyStation? and $finalBuyStation.exists and $finalBuyWare != null">
              <find_sell_offer seller="$finalBuyStation" wares="$finalBuyWare" tradepartner="this.ship" result="$finalValidatedBuyOffer"/>
              <do_if value="not $finalValidatedBuyOffer.available">
                <set_value name="$finalBuyOfferValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - Buy offer invalid (trade rules?) - station: ' + @$finalBuyStation.knownname + ', ware: ' + @$finalBuyWare.name" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
          
          <do_if value="$pendingTrade.$SellOffer?">
            <set_value name="$finalSellStation" exact="if $pendingTrade.$SellStation? then $pendingTrade.$SellStation else (if $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner else null)"/>
            <set_value name="$finalSellWare" exact="if $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else null"/>
            
            <do_if value="$finalSellStation? and $finalSellStation.exists and $finalSellWare != null">
              <find_buy_offer buyer="$finalSellStation" wares="$finalSellWare" tradepartner="this.ship" result="$finalValidatedSellOffer"/>
              <do_if value="not $finalValidatedSellOffer.available">
                <set_value name="$finalSellOfferValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - Sell offer invalid (trade rules?) - station: ' + @$finalSellStation.knownname + ', ware: ' + @$finalSellWare.name" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>

          <!-- Final MK3 faction blacklist safety net (applies to all sources: cache/live/fallback). -->
          <do_if value="$mk3FactionBlacklistFinal.keys.count gt 0">
            <set_value name="$finalBuyFaction" exact="null"/>
            <set_value name="$finalSellFaction" exact="null"/>

            <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner?">
              <set_value name="$finalBuyOwnerContainer" exact="@$pendingTrade.$BuyOffer.owner"/>
              <do_if value="$finalBuyOwnerContainer.owner?">
                <set_value name="$finalBuyFaction" exact="$finalBuyOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$finalBuyFaction" exact="$finalBuyOwnerContainer"/>
              </do_else>
            </do_if>

            <do_if value="$pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner?">
              <set_value name="$finalSellOwnerContainer" exact="@$pendingTrade.$SellOffer.owner"/>
              <do_if value="$finalSellOwnerContainer.owner?">
                <set_value name="$finalSellFaction" exact="$finalSellOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$finalSellFaction" exact="$finalSellOwnerContainer"/>
              </do_else>
            </do_if>

            <do_if value="$finalBuyFaction? and $mk3FactionBlacklistFinal.{$finalBuyFaction}?">
              <set_value name="$finalMK3BlacklistValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL MK3 blacklist block (buy faction): ' + $finalBuyFaction.name" chance="100"/>
              </do_if>
            </do_if>
            <do_if value="$finalMK3BlacklistValid and $finalSellFaction? and $mk3FactionBlacklistFinal.{$finalSellFaction}?">
              <set_value name="$finalMK3BlacklistValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL MK3 blacklist block (sell faction): ' + $finalSellFaction.name" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Final illegal-route safety net (path can change between scoring and order creation). -->
          <set_value name="$finalRouteWare" exact="if $pendingTrade.$Ware? then $pendingTrade.$Ware else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else null))"/>
          <do_if value="$effectiveAllowIllegal and $effectiveEnforceRouteIllegalLegality and @$finalRouteWare.illegal gt 0">
            <set_value name="$finalRouteBuySector" exact="this.ship.sector"/>
            <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner?">
              <set_value name="$finalRouteBuySector" exact="@$pendingTrade.$BuyOffer.owner.sector"/>
            </do_if>
            <set_value name="$finalRouteSellSector" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.sector else null"/>
            <run_script name="'lib.gt.pathfinding'" result="$finalRouteLegality">
              <param name="mode" value="'route_legality'"/>
              <param name="ship" value="this.ship"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="allowIllegal" value="$effectiveAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$effectiveEnforceRouteIllegalLegality"/>
              <param name="startSector" value="this.ship.sector"/>
              <param name="buySector" value="$finalRouteBuySector"/>
              <param name="sellSector" value="$finalRouteSellSector"/>
              <param name="ware" value="$finalRouteWare"/>
            </run_script>
            <do_if value="not $finalRouteLegality.$IsLegal">
              <set_value name="$finalRouteIllegalValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL ILLEGAL ROUTE BLOCK: route changed or sector legality mismatch before order creation'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- If final validation failed, abort order creation -->
          <do_if value="not $finalBuyOfferValid or not $finalSellOfferValid or not $finalMK3BlacklistValid or not $finalRouteIllegalValid">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - safety check blocked trade immediately before order creation'" chance="100"/>
            </do_if>
            <!-- Scenario 3: Flag ship-specific failure â€” final validation uses tradepartner="this.ship",
                 so trade rules are ship-specific. Another ship may still pass. -->
            <do_if value="$searchMethod == 'cache'">
              <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$pendingTrade.$BuyOffer, $SellOffer = @$pendingTrade.$SellOffer, $HomeSector = $searchHomeSector, $Reason = 'trade_rules_failed']"/>
            </do_if>
            <signal_objects object="this.ship" param="'GT_No_Trade_Found'" param2="'trade_rules_violation'"/>
            <return/>
          </do_if>
          
          <!-- Offers valid - proceed with order creation -->
          <!-- CRITICAL FIX: Explicitly set internal="false" to ensure vanilla counts trade orders in "credits due from trades" -->
          <!-- Vanilla's GetCreditsDueFromPlayerTrades() only counts trade orders with internal="false" -->
          <!-- INVESTIGATION: Subordinates still not counted - may be vanilla limitation (excludes ships with commanders) -->
          <!-- Vanilla TradeRoutine pattern: internal="not $blacklist_override?" (usually false) -->
          <!-- NOTE: Even with internal="false", vanilla may exclude subordinates from credits due count -->
          <!-- This appears to be a vanilla design decision - subordinates' finances are part of commander's finances -->
          <set_value name="$tradeOrderInternal" exact="false"/>

          <!-- AUTHORITATIVE MinPlayerMoney guard â€” BUDGET CLAMP (race-free) -->
          <!-- This runs in the AI script with NO yield between check and create_trade_order,
               so player.money is guaranteed to reflect all prior create_trade_order deductions.
               Mechanic 1: If the full trade would drain below MinPlayerMoney, reduce volume
               to fit (player.money - MinPlayerMoney). If even 1 unit is unaffordable, block
               and back off via no_trade_retry with insufficient_funds.
               MK3 IPP player-supplier pairs skip this gate: buy-leg credits stay in the player
               economy (matches lib.gt.tradematch.xml scoring and logbook Money=0 semantics). -->
          <set_value name="$ippPlayerSupplier" exact="false"/>
          <do_if value="$pendingTrade.$PlayerFreeSupplier? and $pendingTrade.$PlayerFreeSupplier">
            <set_value name="$ippPlayerSupplier" exact="true"/>
          </do_if>
          <do_elseif value="this.$effectiveIgnorePlayerPricing? and not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and @$pendingTrade.$BuyOffer.owner.isplayerowned">
            <set_value name="$ippPlayerSupplier" exact="true"/>
          </do_elseif>
          <do_if value="not $ippPlayerSupplier">
          <set_value name="$aiBuyPrice" exact="0"/>
          <do_if value="$pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.unitprice?">
            <set_value name="$aiBuyPrice" exact="$pendingTrade.$BuyOffer.unitprice"/>
          </do_if>
          <set_value name="$aiPurchaseCost" exact="if $isSellOnlyTradeForPending then 0 else ($aiBuyPrice * $finalBuyAmount)"/>
          <set_value name="$aiMinPlayerMoney" exact="if this.$minPlayerMoney? then this.$minPlayerMoney else 1000"/>
          <do_if value="(player.money - $aiPurchaseCost) lt ($aiMinPlayerMoney)Cr">
            <!-- Full clamped amount would drain below MinPlayerMoney.
                 Try to reduce amount further to fit the available budget.
                 availableBudget = player.money - MinPlayerMoney (in cents). -->
            <do_if value="not $isSellOnlyTradeForPending and $aiBuyPrice gt 0">
              <set_value name="$aiAvailableBudget" exact="player.money - ($aiMinPlayerMoney)Cr"/>
              <set_value name="$aiAffordableUnits" exact="$aiAvailableBudget / $aiBuyPrice"/>
              <do_if value="$aiAffordableUnits ge 1">
                <!-- Player can afford a reduced amount - clamp and proceed -->
                <set_value name="$finalBuyAmount" exact="$aiAffordableUnits"/>
                <set_value name="$finalSellAmount" exact="$aiAffordableUnits"/>
                <set_value name="$aiPurchaseCost" exact="$aiBuyPrice * $aiAffordableUnits"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BUDGET CLAMP (authoritative guard): reduced from original to ' + $aiAffordableUnits + ' units, cost=' + ($aiPurchaseCost / 100) + ' Cr, player.money=' + (player.money / 100) + ' Cr, remaining=' + ((player.money - $aiPurchaseCost) / 100) + ' Cr (threshold: ' + $aiMinPlayerMoney + ' Cr)'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- Can't afford even 1 unit - truly insufficient funds -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BLOCKED trade (authoritative guard): player.money=' + (player.money / 100) + ' Cr, unitPrice=' + ($aiBuyPrice / 100) + ' Cr -- cannot afford even 1 unit above MinPlayerMoney threshold (' + $aiMinPlayerMoney + ' Cr)'" chance="100"/>
                </do_if>
                <!-- GLOBAL MONEY CAP: If even 1 unit is unaffordable, stop ALL ships from searching.
                     Record player.money so the flag auto-clears when money increases from any source. -->
                <set_value name="global.$GT_MoneyCapActive" exact="true"/>
                <set_value name="global.$GT_MoneyCapMoney" exact="player.money"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP SET: player.money=' + (player.money / 100) + ' Cr â€” all ships blocked until money increases'" chance="100"/>
                <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
                <resume label="no_trade_retry"/>
              </do_else>
            </do_if>
            <do_else>
              <!-- Sell-only trade should never fail this check (cost=0), but block as safety -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BLOCKED trade (authoritative guard, edge case): player.money=' + (player.money / 100) + ' Cr, purchaseCost=' + ($aiPurchaseCost / 100) + ' Cr -- below MinPlayerMoney threshold (' + $aiMinPlayerMoney + ' Cr)'" chance="100"/>
              </do_if>
              <set_value name="global.$GT_MoneyCapActive" exact="true"/>
              <set_value name="global.$GT_MoneyCapMoney" exact="player.money"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP SET: player.money=' + (player.money / 100) + ' Cr â€” all ships blocked until money increases'" chance="100"/>
              <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
              <resume label="no_trade_retry"/>
            </do_else>
          </do_if>
          </do_if>

          <!-- Queued logbook / UI P/L snapshot: validation-time prices BEFORE create_trade_order.
               create_trade_order mutates offer.unitprice; logbook must match economics at acceptance. -->
          <set_value name="$uiLogAmount" exact="if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount"/>
          <set_value name="$buyPriceRawCanonical" exact="if $pendingTrade.$LogbookBuyPriceRaw? then $pendingTrade.$LogbookBuyPriceRaw else (if $pendingTrade.$BuyPrice? then $pendingTrade.$BuyPrice else 0)"/>
          <set_value name="$sellPriceRawCanonical" exact="if $pendingTrade.$LogbookSellPriceRaw? then $pendingTrade.$LogbookSellPriceRaw else (if $pendingTrade.$SellPrice? then $pendingTrade.$SellPrice else 0)"/>
          <set_value name="$profitRawForSignal" exact="0"/>
          <do_if value="$ippPlayerSupplier">
            <set_value name="$profitRawForSignal" exact="$sellPriceRawCanonical * $uiLogAmount"/>
          </do_if>
          <do_elseif value="$isSellOnlyTradeForPending">
            <set_value name="$profitRawForSignal" exact="$sellPriceRawCanonical * $uiLogAmount"/>
          </do_elseif>
          <do_else>
            <set_value name="$profitRawForSignal" exact="($sellPriceRawCanonical - $buyPriceRawCanonical) * $uiLogAmount"/>
          </do_else>
          <set_value name="$uiMoneyRawForSignal" exact="if $ippPlayerSupplier then 0 else (-$uiLogAmount * $buyPriceRawCanonical)"/>
          <set_value name="$pendingTrade.$BuyPrice" exact="$buyPriceRawCanonical"/>
          <set_value name="$pendingTrade.$SellPrice" exact="$sellPriceRawCanonical"/>
          <set_value name="$pendingTrade.$Profit" exact="$profitRawForSignal"/>

          <!-- Vanilla pattern (order.trade.routine): queue SELL first as immediate,
               then queue BUY as immediate so BUY displaces SELL and runs first. -->
          <do_if value="$pendingTrade.$SellOffer?">
            <create_trade_order object="this.ship" tradeoffer="$pendingTrade.$SellOffer" amount="$finalSellAmount" immediate="true" internal="$tradeOrderInternal"/>
            <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$sellOfferAmountAfterOrder" exact="@$pendingTrade.$SellOffer.offeramount.{this.ship}"/>
              <set_value name="$sellDesiredAfterOrder" exact="@$pendingTrade.$SellOffer.desiredamount"/>
              <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': after create_trade_order SELL' +
                '\n  orderAmount=' + $finalSellAmount +
                '\n  sell offeramount(ship)=' + (if $sellOfferAmountAfterOrder? then $sellOfferAmountAfterOrder else 'null') +
                '\n  sell desiredamount=' + (if $sellDesiredAfterOrder? then $sellDesiredAfterOrder else 'null')"
                chance="100"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Created SELL trade order (internal=' + $tradeOrderInternal + ', isSubordinate=' + $isSubordinate + ', hasCommander=' + (if this.ship.commander? and this.ship.commander.exists then 'true' else 'false') + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer?">
            <create_trade_order object="this.ship" tradeoffer="$pendingTrade.$BuyOffer" amount="$finalBuyAmount" immediate="true" internal="$tradeOrderInternal"/>
            <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$buyOfferAmountAfterOrder" exact="@$pendingTrade.$BuyOffer.offeramount.{this.ship}"/>
              <set_value name="$buyDesiredAfterOrder" exact="@$pendingTrade.$BuyOffer.desiredamount"/>
              <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': after create_trade_order BUY' +
                '\n  orderAmount=' + $finalBuyAmount +
                '\n  buy offeramount(ship)=' + (if $buyOfferAmountAfterOrder? then $buyOfferAmountAfterOrder else 'null') +
                '\n  buy desiredamount=' + (if $buyDesiredAfterOrder? then $buyDesiredAfterOrder else 'null')"
                chance="100"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Created BUY trade order (internal=' + $tradeOrderInternal + ', isSubordinate=' + $isSubordinate + ', hasCommander=' + (if this.ship.commander? and this.ship.commander.exists then 'true' else 'false') + ')'" chance="100"/>
            </do_if>
          </do_if>

          <!-- Phase C: runtime illegal-route policy snapshot (cleared on completion/abort). -->
          <do_if value="$effectiveAllowIllegal and $effectiveEnforceRouteIllegalLegality">
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{this.ship}?">
              <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
            </do_if>
            <set_value name="$atpBuySector" exact="if not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner.sector else null"/>
            <set_value name="$atpSellSector" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.sector else null"/>
            <set_value name="$atpWare" exact="if $pendingTrade.$Ware? then $pendingTrade.$Ware else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else null))"/>
            <set_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy" exact="table[
              $AllowIllegal = $effectiveAllowIllegal,
              $EnforceRouteIllegalLegality = $effectiveEnforceRouteIllegalLegality,
              $Ware = $atpWare,
              $BuySector = $atpBuySector,
              $SellSector = $atpSellSector,
              $HomeSector = $searchHomeSector,
              $RouteStart = this.ship.sector,
              $Leg = if $isSellOnlyTradeForPending then 'sell' else 'buy',
              $LogbookEntries = $gt_logbookentries,
              $SetAt = player.age
            ]"/>
          </do_if>
          <do_else>
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
              <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
            </do_if>
          </do_else>

          <!-- Fallback flag follows the source of the CURRENT created trade order. -->
          <do_if value="$searchMethod == 'live_fallback'">
            <do_if value="not global.$GT_FallbackTradeActive?">
              <set_value name="global.$GT_FallbackTradeActive" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_FallbackTradeActive.{this.ship}" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Set [FALLBACK] flag - created trade from live_fallback'" chance="100"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='fallback'
              ]"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <remove_value name="global.$GT_FallbackTradeActive.{this.ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Cleared [FALLBACK] flag - created trade from ' + (if $searchMethod != '' then $searchMethod else 'unknown source') + ' (not live_fallback)'" chance="100"/>
              </do_if>
              <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                  $Ship=this.ship,
                  $pilot=this.ship.pilot,
                  $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                  $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                  $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                  $nameType='trader'
                ]"/>
              </do_if>
            </do_if>
          </do_else>
          
          <!-- Clear fleet reservation: create_trade_order has been called, X4 native offeramount.{ship}
               now handles capacity coordination. Remove our pre-selection reservation. -->
          <do_if value="this.$activeReservationKey? and global.$GT_Reservations? and global.$GT_Reservations.{this.$activeReservationKey}?">
            <remove_value name="global.$GT_Reservations.{this.$activeReservationKey}"/>
            <do_if value="global.$GT_ReservationStats? and global.$GT_ReservationStats.$Active gt 0">
              <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
            </do_if>
            <do_if value="global.$GT_ReservationStats?">
              <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet reservation CLEARED (trade orders created, native system active)'" chance="100"/>
            </do_if>
          </do_if>
          <remove_value name="this.$activeReservationKey"/>
          
          <!-- Scenario 2: Purge consumed trade from cache so other ships don't pick it -->
          <do_if value="$searchMethod == 'cache'">
            <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
              $Ship = this.ship,
              $BuyOffer = @$pendingTrade.$BuyOffer,
              $SellOffer = @$pendingTrade.$SellOffer,
              $HomeSector = $searchHomeSector,
              $Reason = 'consumed'
            ]"/>
          </do_if>
          
          <!-- Purge trades awaiting validation after we successfully queued trade orders.
               Keeping them causes stale execution via old trade data. -->
          <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <!-- Clear interrupt flag when clearing trades awaiting validation (trades successfully processed) -->
          <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>

          <!-- Add state update signal AFTER order creation -->
          <!-- This tests if sending a signal immediately after create_trade_order interferes with TradePerform initialization -->
          <!-- NOTE: No handler exists yet (Phase 3) - signal will be sent but not processed -->
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'Trade_Order_Created',
            $TradeOrderCount = this.ship.tradeorders.count
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PHASE 2: State update signal sent (Trade_Order_Created)'" chance="100"/>
            
            <!-- Handle sell-only trades in debug output -->
              <set_value name="$buyOrderText" exact="if $isSellOnlyTradeForPending then 'N/A (sell-only - ship already has cargo)' else (if $buyStationForPending? then @$buyStationForPending.knownname + ' â†’ ' + (if $wareForPendingTrade? then @$wareForPendingTrade.name else 'Unknown') + ' (x' + $finalBuyAmount + ')' else 'Unknown')"/>
            <set_value name="$sellOrderText" exact="if $sellStationForPending? then @$sellStationForPending.knownname else 'Unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade orders created:' +
              '\n  BUY: ' + $buyOrderText +
              '\n  SELL: ' + $sellOrderText"
              chance="100"/>
          </do_if>
          
          <!-- Send logbook message when ship is escaping from blacklisted sector -->
          <set_value name="$isEscapeTrade" exact="false"/>
          <do_if value="$currentSectorIsBlacklisted">
            <!-- Check if trade leads to a different sector (escape route) -->
            <set_value name="$isEscapeTrade" exact="($buySector != $currentSector) or ($sellSector != $currentSector)"/>
          </do_if>
          
          <do_if value="$isEscapeTrade">
            <!-- Set escape flag for ship naming -->
            <do_if value="global.$GT_Ships?">
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>

            <!-- Build escape route message using translation -->
            <!-- Extract values safely with null checks -->
            <set_value name="$escapeWare" exact="null"/>
            <set_value name="$escapeAmount" exact="0"/>
            <set_value name="$escapeProfit" exact="0"/>
            
            <!-- Extract ware from BuyOffer (more reliable than $Ware property) -->
            <do_if value="$pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware?">
              <set_value name="$escapeWare" exact="$pendingTrade.$BuyOffer.ware.name"/>
            </do_if>
            <do_elseif value="$pendingTrade.$Ware?">
              <set_value name="$escapeWare" exact="$pendingTrade.$Ware.name"/>
            </do_elseif>
            
            <!-- Extract amount -->
            <set_value name="$escapeAmount" exact="if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount"/>
            
            <!-- Extract profit (creation-time snapshot; set after create_trade_order) -->
            <set_value name="$escapeProfit" exact="if $profitRawForSignal? then $profitRawForSignal else (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 0)"/>
            
            <!-- Safe defaults for missing values -->
            <set_value name="$currentSectorName" exact="'Unknown Sector'"/>
            <do_if value="$currentSector?">
              <set_value name="$currentSectorNameTemp" exact="@$currentSector.knownname"/>
              <do_if value="$currentSectorNameTemp?">
                <set_value name="$currentSectorName" exact="$currentSectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$buyStationName" exact="'Unknown Station'"/>
            <do_if value="$buyStation?">
              <set_value name="$buyStationNameTemp" exact="@$buyStation.knownname"/>
              <do_if value="$buyStationNameTemp?">
                <set_value name="$buyStationName" exact="$buyStationNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$buySectorName" exact="'Unknown Sector'"/>
            <do_if value="$buySector?">
              <set_value name="$buySectorNameTemp" exact="@$buySector.knownname"/>
              <do_if value="$buySectorNameTemp?">
                <set_value name="$buySectorName" exact="$buySectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$sellStationName" exact="'Unknown Station'"/>
            <do_if value="$sellStation?">
              <set_value name="$sellStationNameTemp" exact="@$sellStation.knownname"/>
              <do_if value="$sellStationNameTemp?">
                <set_value name="$sellStationName" exact="$sellStationNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$sellSectorName" exact="'Unknown Sector'"/>
            <do_if value="$sellSector?">
              <set_value name="$sellSectorNameTemp" exact="@$sellSector.knownname"/>
              <do_if value="$sellSectorNameTemp?">
                <set_value name="$sellSectorName" exact="$sellSectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$wareInfo" exact="'Unknown Ware'"/>
            <do_if value="$escapeWare?">
              <set_value name="$wareInfo" exact="$escapeWare"/>
            </do_if>
            
            <!-- Build message using translation ID 3210 with 8 parameters -->
            <!-- Parameters: currentSector, buyStation, buySector, sellStation, sellSector, ware, amount, profit -->
            <set_value name="$escapeMessage" exact="{77000,3210}.[$currentSectorName,$buyStationName,$buySectorName,$sellStationName,$sellSectorName,$wareInfo,$escapeAmount,($escapeProfit / 100)]"/>
            
            <!-- Log the message being written -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE ROUTE LOGBOOK DEBUG:' + '\n  Current Sector: ' + $currentSectorName + '\n  Buy: ' + $buyStationName + ' (' + $buySectorName + ')' + '\n  Sell: ' + $sellStationName + ' (' + $sellSectorName + ')' + '\n  Ware: ' + $wareInfo + ' (x' + $escapeAmount + ')' + '\n  Profit: ' + ($escapeProfit / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <!-- Log the full message text that will be written to logbook -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE ROUTE LOGBOOK MESSAGE:' + '\n' + $escapeMessage" chance="100"/>
            </do_if>
            
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3210}.[$currentSectorName,$buyStationName,$buySectorName,$sellStationName,$sellSectorName,$wareInfo,$escapeAmount,($escapeProfit / 100)]"/>
            
            <!-- Write to ship logbook -->
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'general',
              $Title = 'Escape Route: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Escape route logbook entry created'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clear UR state once a valid trade was selected for execution. -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
            <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Log to ship logbook if enabled (moved from MD execution to after validation) -->
          <set_value name="$logbookEnabled" exact="false"/>
          <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK3' and @this.ship.defaultorder.$logbookentries">
            <set_value name="$logbookEnabled" exact="true"/>
          </do_if>
          <do_elseif value="@this.ship.defaultorder.id == 'Assist' and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
            <set_value name="$logbookEnabled" exact="true"/>
          </do_elseif>

          <!-- UI bridge: always publish queued-trade values (independent of per-ship logbook setting).
               $buyPriceRawCanonical / $sellPriceRawCanonical / $profitRawForSignal / $uiMoneyRawForSignal
               were snapshotted from live offers immediately after create_trade_order. -->
          <set_value name="$uiBuyPriceRawForSignal" exact="$buyPriceRawCanonical"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$rawBuyOfferUnitPrice" exact="if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.unitprice? then $pendingTrade.$BuyOffer.unitprice else -1"/>
            <set_value name="$rawSellOfferUnitPrice" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.unitprice? then $pendingTrade.$SellOffer.unitprice else -1"/>
            <set_value name="$rawPendingTradeBuyPrice" exact="$buyPriceRawCanonical"/>
            <set_value name="$rawPendingTradeSellPrice" exact="$sellPriceRawCanonical"/>
            <set_value name="$rawPendingTradeProfit" exact="$profitRawForSignal"/>
            <set_value name="$rawSignalSum" exact="abs($uiMoneyRawForSignal) + $rawPendingTradeProfit"/>
            <debug_text text="'[GT-AI-UI-DUE] ' + this.ship.idcode +
              '\n  Amount: ' + $uiLogAmount +
              '\n  BuyOffer.unitprice (RAW): ' + $rawBuyOfferUnitPrice +
              '\n  SellOffer.unitprice (RAW): ' + $rawSellOfferUnitPrice +
              '\n  pendingTrade.BuyPrice (RAW?): ' + $rawPendingTradeBuyPrice +
              '\n  pendingTrade.SellPrice (RAW?): ' + $rawPendingTradeSellPrice +
              '\n  Canonical buy price (RAW): ' + $uiBuyPriceRawForSignal +
              '\n  Canonical sell price (RAW): ' + $sellPriceRawCanonical +
              '\n  MoneyRaw sent: ' + $uiMoneyRawForSignal + ' (' + ($uiMoneyRawForSignal / 100) + ' Cr)' +
              '\n  Profit sent (RAW): ' + $rawPendingTradeProfit + ' (' + ($rawPendingTradeProfit / 100) + ' Cr)' +
              '\n  Expected due sum RAW: ' + $rawSignalSum + ' (' + ($rawSignalSum / 100) + ' Cr)'" chance="100"/>
          </do_if>
          <do_if value="$logbookEnabled">
            <set_value name="$logAmount" exact="$uiLogAmount"/>
            
            <!-- PROFIT DEBUG: Log trade data before sending to logbook -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$wareName" exact="if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware.name else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware.name else 'NULL')"/>
              <set_value name="$buyStationName" exact="if $pendingTrade.$BuyStation? then @$pendingTrade.$BuyStation.knownname else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner.knownname else 'NULL')"/>
              <set_value name="$sellStationName" exact="if $pendingTrade.$SellStation? then @$pendingTrade.$SellStation.knownname else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.knownname else 'NULL')"/>
              <set_value name="$originalAmount" exact="if $pendingTrade.$Amount? then $pendingTrade.$Amount else 'NULL'"/>
              <set_value name="$buyPrice" exact="$buyPriceRawCanonical"/>
              <set_value name="$sellPrice" exact="$sellPriceRawCanonical"/>
              <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') LOGBOOK ENTRY PREPARATION:' + 
                '\n  Ware: ' + $wareName +
                '\n  Buy Station: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr (RAW: ' + $buyPrice + ')' +
                '\n  Sell Station: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr (RAW: ' + $sellPrice + ')' +
                '\n  Original Amount (from trade): ' + $originalAmount + ' units' +
                '\n  Final Buy Amount (clamped): ' + $finalBuyAmount + ' units' +
                '\n  Final Sell Amount (clamped): ' + $finalSellAmount + ' units' +
                '\n  Log Amount (used for display): ' + $logAmount + ' units' +
                '\n  Profit (RAW): ' + $profitRawForSignal + ' = ' + ($profitRawForSignal/100) + ' Cr' +
                '\n  Verification with log amount: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $logAmount + ' = ' + (($sellPrice - $buyPrice) * $logAmount / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <set_value name="$buyPriceForSignal" exact="$buyPriceRawCanonical / 100"/>
            <set_value name="$sellPriceForSignal" exact="$sellPriceRawCanonical / 100"/>
            
            <!-- Determine search pipeline type for logbook display -->
            <set_value name="$logSearchPipeline" exact="'normal'"/>
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?">
              <set_value name="$logSearchPipeline" exact="'isolated'"/>
            </do_if>
            <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <set_value name="$logSearchPipeline" exact="'fallback'"/>
            </do_elseif>
            <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
              $Ship = this.ship,
              $BuyOffer = if $pendingTrade.$BuyOffer? then $pendingTrade.$BuyOffer else null,
              $SellOffer = if $pendingTrade.$SellOffer? then $pendingTrade.$SellOffer else null,
              $Amount = $logAmount,
              $Profit = $profitRawForSignal,
              $BuyPrice = $buyPriceForSignal,
              $SellPrice = $sellPriceForSignal,
              $BuyPriceRaw = $buyPriceRawCanonical,
              $SellPriceRaw = $sellPriceRawCanonical,
              $MoneyRaw = $uiMoneyRawForSignal,
              $IsSellOnly = $isSellOnlyTradeForPending,
              $SearchPipeline = $logSearchPipeline,
              $PlayerFreeSupplier = if $ippPlayerSupplier then true else (if $pendingTrade.$PlayerFreeSupplier? then @$pendingTrade.$PlayerFreeSupplier else false)
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI-LOG-SIGNAL] ' + this.ship.idcode +
                '\n  sell-only: ' + $isSellOnlyTradeForPending + ', pipeline: ' + $logSearchPipeline +
                '\n  Amount sent: ' + $logAmount +
                '\n  BuyPrice sent (Cr): ' + $buyPriceForSignal +
                '\n  SellPrice sent (Cr): ' + $sellPriceForSignal +
                '\n  BuyPrice sent (RAW): ' + $buyPriceRawCanonical +
                '\n  SellPrice sent (RAW): ' + $sellPriceRawCanonical +
                '\n  Profit sent (RAW): ' + $profitRawForSignal +
                '\n  MoneyRaw sent: ' + $uiMoneyRawForSignal + ' (' + ($uiMoneyRawForSignal / 100) + ' Cr)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- All trades in list were rejected - check reason -->
          <!-- Use safe access for variables that might not exist -->
          <set_value name="$tradesRejectedPathSafe" exact="if $tradesRejectedPath? then $tradesRejectedPath else 0"/>
          <set_value name="$tradesRejectedDockingSafe" exact="if $tradesRejectedDocking? then $tradesRejectedDocking else 0"/>
          <set_value name="$tradesRejectedOfferInvalidSafe" exact="if $tradesRejectedOfferInvalid? then $tradesRejectedOfferInvalid else 0"/>
          <set_value name="$tradesRejectedDistanceSafe" exact="if $tradesRejectedDistance? then $tradesRejectedDistance else 0"/>
          <set_value name="$tradesRejectedCargoSafe" exact="if $tradesRejectedCargo? then $tradesRejectedCargo else 0"/>
          <set_value name="$tradesRejectedRestrictionSafe" exact="if $tradesRejectedRestriction? then $tradesRejectedRestriction else 0"/>
          <set_value name="$tradesBlacklistedSafe" exact="if $tradesBlacklisted? then $tradesBlacklisted else 0"/>
          <!-- Use safe access for $tradeList.count -->
          <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
          <!-- UR must mean route-blocked by blacklist/pathing only (not distance-limit rejects). -->
          <set_value name="$unreachableRejectedSafe" exact="$tradesBlacklistedSafe + $tradesRejectedPathSafe"/>
          <set_value name="$isIsolatedMode" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
          <set_value name="$isUnreachableOnly" exact="$tradeListCountSafe gt 0 and ($searchMethod == 'live' or $searchMethod == 'live_ship_route') and $unreachableRejectedSafe == $tradeListCountSafe"/>
          
          <!-- Search method already captured earlier in trade_found label -->
          <!-- (from cache, signal param2, or global storage) -->
          
          <!-- Enhanced logging for cache trade rejections -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$searchSource" exact="if $searchMethod == 'cache' then 'CACHE' else if $searchMethod == 'live' then 'LIVE' else 'UNKNOWN'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ALL ' + $tradeListCountSafe + ' trades from ' + $searchSource + ' were rejected:' +
              '\n  Path blocked: ' + $tradesRejectedPathSafe +
              '\n  Docking denied: ' + $tradesRejectedDockingSafe +
              '\n  Offer invalid: ' + $tradesRejectedOfferInvalidSafe +
              '\n  Distance unreachable: ' + $tradesRejectedDistanceSafe +
              '\n  Cargo insufficient: ' + $tradesRejectedCargoSafe +
              '\n  Restriction blocked: ' + $tradesRejectedRestrictionSafe +
              '\n  Blacklisted: ' + $tradesBlacklistedSafe +
              '\n  Total rejected: ' + $tradeListCountSafe +
              (if $searchMethod == 'cache' then '\n  Cache exhausted: all ' + $tradeListCountSafe + ' cache candidates failed validation (Restriction=' + $tradesRejectedRestrictionSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Path=' + $tradesRejectedPathSafe + ', Blacklist=' + $tradesBlacklistedSafe + ')' else '') +
              ' - entering retry logic'" chance="100"/>
          </do_if>
          
          <!-- CRITICAL:
               If ALL trades were rejected (often because offers changed), we MUST purge trades awaiting validation.
               Otherwise the ship can loop forever on stale global.$GT_TradesAwaitingValidation.{this.ship} and never request fresh trades. -->
          <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <!-- Clear interrupt flag when clearing trades awaiting validation to prevent re-entry loop -->
          <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
          <!-- Reduce escalating backoff after purging stale results: next retry will start at 10s again -->
          <set_value name="this.$searchFailed" exact="0"/>

          <!-- Isolated mode is current-sector-only. Remove stale UR and do not re-apply it while isolated. -->
          <do_if value="$isIsolatedMode and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
            <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Mark unreachable-routes state when all evaluated live trades are blocked by blacklist/path reachability. -->
          <do_if value="$isUnreachableOnly and not $isIsolatedMode">
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{this.ship}?">
              <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{this.ship}.$Unreachable" exact="true"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>

            <!-- Roleplay logbook message (throttled) for blacklist/path unreachable profitable routes. -->
            <do_if value="$gt_logbookentries">
              <set_value name="$lastUnreachableLogbook" exact="0"/>
              <do_if value="this.$lastUnreachableLogbookTime?">
                <set_value name="$lastUnreachableLogbook" exact="this.$lastUnreachableLogbookTime"/>
              </do_if>
              <set_value name="$unreachableSinceLast" exact="player.age - $lastUnreachableLogbook"/>
              <do_if value="$lastUnreachableLogbook == 0 or $unreachableSinceLast ge 300s">
                <set_value name="$urCurrentSectorName" exact="if this.ship.sector? then @this.ship.sector.knownname else 'Unknown Sector'"/>
                <set_value name="$urNormalRange" exact="if $searchMaxDistance? and $searchMaxDistance gt 0 then $searchMaxDistance else 1"/>
                <set_value name="$urNearbyRange" exact="[1, ($urNormalRange / 3)i].max"/>
                <set_value name="$urMessage" exact="{77000,3221}.[this.ship.knownname, $urCurrentSectorName, $urNormalRange, $urNearbyRange]"/>
                <set_value name="$redColor" exact="'\033#FFCC0000#'"/>
                <set_value name="$colorReset" exact="'\033X'"/>
                <set_value name="$urTitle" exact="$redColor + 'Unreachable Routes: ' + $colorReset + this.ship.knownname"/>
                <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                  $Message = $urMessage,
                  $Category = 'alerts',
                  $Title = $urTitle,
                  $Object = this.ship,
                  $Interaction = 'showonmap',
                  $CheckGlobalSettings = true
                ]"/>
                <set_value name="this.$lastUnreachableLogbookTime" exact="player.age"/>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Keep UR sticky across unsuccessful search cycles.
                 UR is intentionally cleared only when a valid trade is selected for execution. -->
          </do_else>
          
          <!-- If ALL trades rejected due to cargo space, trigger cargo disposal -->
          <!-- Use safe access for variable check -->
          <do_if value="$tradesRejectedCargoSafe gt 0 and $tradesRejectedCargoSafe == $tradeListCountSafe">
            <set_value name="$hasCargo" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
            <do_if value="$hasCargo">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  ALL trades rejected due to insufficient cargo space - triggering cargo disposal'" chance="100"/>
              </do_if>
              <!-- Ship has cargo but not enough space for any trade - find buyer for existing cargo -->
              <signal_objects object="player.galaxy" param="'GT_Find_Sell'" param2="table[
                $Ship = this.ship,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnorePlayerPricing = if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true
              ]"/>
              <!-- CRITICAL: Resume to wait_for_response so ship is ready to receive GT_Search_Go immediately.
                   Resuming to main_loop caused GT_Search_Go to arrive while ship was busy elsewhere (no matching
                   interrupt), leading to missed signals and up-to-60s waits for sell-order discovery. -->
              <resume label="wait_for_response"/>
            </do_if>
          </do_if>

          <!-- ESCAPE FALLBACK (trade list exists but none can move us out safely):
               If we are in a blacklisted sector and we have no non-blacklisted escape trade, force a move toward home.
               Whitelist overrides blacklist (matches GT_IsSectorBlacklisted). -->
          <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          <set_value name="$validationWhitelist" exact="[]"/>
          <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
            <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
          </do_if>
          <set_value name="$currentSector" exact="this.ship.sector"/>
          <set_value name="$needsEscape" exact="false"/>
          <do_if value="$currentSector? and $currentSector.exists">
            <set_value name="$curWhitelisted" exact="false"/>
            <do_if value="$validationWhitelist.count gt 0">
              <do_all exact="$validationWhitelist.count" counter="$swIdx">
                <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                  <set_value name="$curWhitelisted" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $curWhitelisted">
              <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
              <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
              <set_value name="$needsEscape" exact="$curActivityBL or $curTravelBL"/>
            </do_if>
          </do_if>
          <do_if value="$needsEscape and ($tradeListCountSafe == 0 or $tradesBlacklistedSafe == $tradeListCountSafe)">
            <!-- Set escape flag for ship naming -->
            <do_if value="global.$GT_Ships?">
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: No valid escape trade found (all trades blacklisted) - moving toward home sector'" chance="100"/>
            </do_if>
            <resume label="escape_from_blacklisted"/>
          </do_if>
          
          <!-- Check if trades came from cache - retry cache once after per-ship FailedShips flags, then live. -->
          <do_if value="$searchMethod == 'cache'">
            <do_if value="not this.$cacheValidationRetried? or not this.$cacheValidationRetried">
              <set_value name="this.$cacheValidationRetried" exact="true"/>
              <set_value name="$retryHomeBase" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector)"/>
              <set_value name="$retryHomeSector" exact="if $retryHomeBase? and $retryHomeBase.isclass.sector then $retryHomeBase else (if $retryHomeBase? and $retryHomeBase.sector? then @$retryHomeBase.sector else this.ship.sector)"/>
              <set_value name="$retryMaxDistance" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $maxsell? then $maxsell else 1)"/>
              <set_value name="$retryBypassPlayerSellerPricing" exact="if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false"/>
              <set_value name="$retryCacheResult" exact="null"/>
              <set_value name="$retryCacheReadOffset" exact="if this.$lastCacheReadOffset? then (this.$lastCacheReadOffset + 1) else ($searchCacheReadOffset + 1)"/>
              <run_script name="'lib.gt.cache.search'" result="$retryCacheResult">
                <param name="ship" value="this.ship"/>
                <param name="searchMode" value="'buy_and_sell'"/>
                <param name="homeSector" value="$retryHomeSector"/>
                <param name="maxDistance" value="$retryMaxDistance"/>
                <param name="wareBasket" value="$warebasket"/>
                <param name="minROI" value="0"/>
                <param name="minAbsoluteProfit" value="0"/>
                <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else (if this.$gt_cargotarget? then this.$gt_cargotarget else 80))"/>
                <param name="ignoreBuildStorage" value="@this.$effectiveIgnoreBuildStorage"/>
                <param name="ignoreCarrierAux" value="@this.$effectiveIgnoreCarrierAux"/>
                <param name="requireNonPlayerDeliveryStation" value="$retryBypassPlayerSellerPricing"/>
                <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
                <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
                <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
                <param name="sellPriceMax" value="if this.$effectiveSellPriceMax? then this.$effectiveSellPriceMax else (if $gt_sellpricemax? then $gt_sellpricemax else 1.0)"/>
                <param name="buyPriceMin" value="if this.$effectiveBuyPriceMin? then this.$effectiveBuyPriceMin else (if $gt_buypricemin? then $gt_buypricemin else -1.0)"/>
                <param name="bypassPlayerSellerPricing" value="$retryBypassPlayerSellerPricing"/>
                <param name="ignoreTradeRules" value="@this.$effectiveIgnoreTradeRules"/>
                <param name="cacheReadOffset" value="$retryCacheReadOffset"/>
                <param name="distancePenalty" value="if $gt_distancepenalty? then $gt_distancepenalty else (if this.$effectiveDistancePenalty? then (this.$effectiveDistancePenalty / 50.0) else 0.1)"/>
                <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              </run_script>
              <do_if value="$retryCacheResult? and $retryCacheResult.$Found? and @$retryCacheResult.$Found and $retryCacheResult.$TradeList? and @$retryCacheResult.$TradeList.count gt 0">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache retry after validation reject found ' + $retryCacheResult.$TradeList.count + ' trades - re-validating'" chance="100"/>
                </do_if>
                <set_value name="this.$tradeListFromSignal" exact="@$retryCacheResult.$TradeList"/>
                <set_value name="this.$searchMethodFromSignal" exact="'cache'"/>
                <resume label="trade_found"/>
              </do_if>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache exhausted â€” all ' + $tradeListCountSafe + ' cache candidates failed validation, triggering LIVE market search' +
                '\n  Rejection breakdown: Path=' + $tradesRejectedPathSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Distance=' + $tradesRejectedDistanceSafe + ', Cargo=' + $tradesRejectedCargoSafe + ', Restriction=' + $tradesRejectedRestrictionSafe + ', Blacklist=' + $tradesBlacklistedSafe" chance="100"/>
            </do_if>
            <!-- Send signal to force live search (bypass cache) -->
            <!-- Include MaxBuy/MaxSell - use effective values if available, otherwise use defaults from order params -->
            <set_value name="$signalMaxBuy" exact="$maxbuy"/>
            <set_value name="$signalMaxSell" exact="$maxsell"/>
            <do_if value="this.$effectiveMaxBuy?">
              <set_value name="$signalMaxBuy" exact="this.$effectiveMaxBuy"/>
            </do_if>
            <do_if value="this.$effectiveMaxSell?">
              <set_value name="$signalMaxSell" exact="this.$effectiveMaxSell"/>
            </do_if>
            <!-- effectiveIgnoreCarrierAux/BuildStorage/TradeRules initialized in <init> -->
            
            <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
              $Ship = this.ship,
              $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
              $MaxBuy = $signalMaxBuy,
              $MaxSell = $signalMaxSell,
              $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
              $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
              $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
              $IgnorePlayerPricing = if this.$effectiveIgnorePlayerPricing? then this.$effectiveIgnorePlayerPricing else false,
              $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
              $ForceLiveSearch = true
            ]"/>
            <!-- CRITICAL: Resume to wait_for_response instead of main_loop -->
            <!-- This ensures the ship waits for the live search result instead of sending a duplicate request -->
            <!-- The wait block will catch GT_Trade_Found signal when live search completes -->
            <resume label="wait_for_response"/>
          </do_if>
          <do_elseif value="$searchMethod == 'live' or $searchMethod == 'live_ship_route' or $searchMethod == 'live_sell_only' or $searchMethod == 'live_fallback'">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': All live trades rejected - releasing scheduler slot, backing off before fresh live search' +
                '\n  Rejection breakdown: Path=' + $tradesRejectedPathSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Distance=' + $tradesRejectedDistanceSafe + ', Cargo=' + $tradesRejectedCargoSafe + ', Restriction=' + $tradesRejectedRestrictionSafe + ', Blacklist=' + $tradesBlacklistedSafe +
                '\n  All ' + $tradeListCountSafe + ' live trades invalid at validation - skip stale cache on next attempt'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
            <set_value name="this.$forceLiveAfterLiveReject" exact="true"/>
            <resume label="no_trade_retry"/>
          </do_elseif>
          <do_else>
            <!-- Trades came from unknown source - use normal retry -->
            <resume label="no_trade_retry"/>
          </do_else>
        </do_else>
      
      <!-- Stability: vanilla-style micro-yield after creating trade orders -->
      <!-- NOTE: wait must be at top level (not inside any do_if/do_else) -->
      <wait exact="this.$gt_yieldMs * 1ms"/>
      
      <!-- Set ship to trading state -->
      <set_command command="command.trade"/>
      
      <!-- Wait for trade completion or failure signal from diff patch (event-driven, no polling) -->
      <wait max="300s" comment="Wait for trade completion or failure signal">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Completed'"/>
              <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
            </check_any>
          </conditions>
          <actions>
            <!-- Check which signal was received -->
            <do_if value="event.param == 'GT_Trade_Completed'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] Trade completed signal received for ' + this.ship.idcode" chance="100"/>
              </do_if>
              <set_value name="this.$tradeComplete" exact="true"/>
              
              <!-- Restore XPBlocked if BlockedLevel still exists (training stations may have become available) -->
              <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
                <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
                  <set_value name="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked" exact="true"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ðŸ”’ Restored XPBlocked for pilot ' + this.ship.pilot.name + ' after trade completion (BlockedLevel: ' + global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel + ')'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
            <do_elseif value="event.param == 'GT_Trade_Failed'">
              <!-- Note: fallback flag is now managed only at trade creation based on search source. -->
              <!-- Isolated flag state will be verified by batch processor on next state check. -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Trade failed - keeping current fallback state until next trade creation; isolation state will be checked by batch processor'" chance="100"/>
              </do_if>
              <!-- Read structured payload (with legacy guard for backward compatibility) -->
              <set_value name="$failurePayload" exact="event.param2"/>
              
              <!-- Handle legacy payloads (string) vs new structured payloads (table) -->
              <set_value name="$isLegacyPayload" exact="false"/>
              <do_if value="typeof $failurePayload == datatype.string">
                <set_value name="$isLegacyPayload" exact="true"/>
                <set_value name="this.$failureReason" exact="$failurePayload"/>
                <set_value name="this.$tradeFailed" exact="true"/>
                <set_value name="this.$tryNextTrade" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] Trade failed (legacy payload) for ' + this.ship.idcode + ': ' + this.$failureReason" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- New structured payload -->
                <!-- Extract properties with safe access, then check if they exist -->
                <set_value name="$reasonTypeValue" exact="@$failurePayload.$ReasonType"/>
                <set_value name="$shouldTryNextValue" exact="@$failurePayload.$ShouldTryNext"/>
                <set_value name="$reasonType" exact="if $reasonTypeValue? then $reasonTypeValue else 'MARKET'"/>
                <set_value name="$shouldTryNext" exact="if $shouldTryNextValue? then $shouldTryNextValue else false"/>
                
                <set_value name="this.$failureReason" exact="$failurePayload.$Reason"/>
                <set_value name="this.$tradeFailed" exact="true"/>
                <set_value name="this.$tryNextTrade" exact="$shouldTryNext"/>
                
                <do_if value="this.$failureReason == 'route_illegal_pre_transit'">
                  <set_value name="this.$lastNoTradeReason" exact="'route_illegal_pre_transit'"/>
                  <do_if value="$gt_logbookentries and global.$GT_Ships? and global.$GT_Ships.{this.ship}.$RouteIllegalAbort?">
                    <set_value name="$ria" exact="global.$GT_Ships.{this.ship}.$RouteIllegalAbort"/>
                    <set_value name="$riaNextSectorName" exact="if $ria.$NextSector? then @$ria.$NextSector.knownname else 'Unknown'"/>
                    <set_value name="$riaWareName" exact="if $ria.$Ware? then @$ria.$Ware.name else 'Unknown'"/>
                    <set_value name="$riaPoliceName" exact="if $ria.$PoliceFaction? then @$ria.$PoliceFaction.knownname else 'Unknown'"/>
                    <set_value name="$logbookMessage" exact="'Commander,\n\nILLEGAL ROUTE BLOCKED\n\nBefore entering sector ' + $riaNextSectorName + ', sector policing now prohibits cargo ware ' + $riaWareName + ' for our owner (police faction: ' + $riaPoliceName + ').\n\nI have aborted the current trade run and will search for an alternative route.\n\nWith vigilance,\nAboard ' + this.ship.knownname"/>
                    <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                      $Message = $logbookMessage,
                      $Category = 'alerts',
                      $Title = 'Illegal Route Blocked: ' + this.ship.knownname,
                      $Object = this.ship,
                      $Interaction = 'showonmap',
                      $Highlighted = false
                    ]"/>
                  </do_if>
                </do_if>
                
                <do_if value="$shouldTryNext">
                  <debug_text text="'[GT-AI] Pathfinding failed for ' + this.ship.idcode + ': ' + this.$failureReason + ' - trying next cached alternative'" chance="100"/>
                </do_if>
                <do_else>
                  <debug_text text="'[GT-AI] Trade failed for ' + this.ship.idcode + ': ' + this.$failureReason + ' - will search for new trade'" chance="100"/>
                </do_else>
              </do_else>
            </do_elseif>
            <resume label="trade_completed"/>
          </actions>
        </interrupt>
      </wait>
      
      <!-- Timeout fallback -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade completion timeout after 300s - resuming anyway'" chance="100"/>
      </do_if>
      
      <label name="trade_completed"/>
      
      <!-- Sell-leg gate / market failure with cargo: skip market refresh wait and enter disposal immediately. -->
      <set_value name="$hasCargoAfterTrade" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
      <do_if value="this.$tradeFailed? and $hasCargoAfterTrade and not (this.$tryNextTrade? and this.$tryNextTrade)">
        <remove_value name="this.$tradeFailed"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade failed with cargo aboard - skipping market wait, entering main loop for disposal'" chance="100"/>
        </do_if>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- NOTE: Global money cap (global.$GT_MoneyCapActive) auto-clears in the early money gate
           when player.money rises above global.$GT_MoneyCapMoney. No per-ship clearing needed. -->
      
      <!-- Fallback flag is intentionally NOT changed on trade completion.
           It is set/cleared only when a new trade order is created and source is known. -->
      
      <!-- CRITICAL: Clear trades awaiting validation after trade execution completes -->
      <!-- This ensures ships always check cache first on next search, not stale pending trades -->
      <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
      </do_if>
      <!-- Clear active trade tracking -->
      <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{this.ship}?">
        <remove_value name="global.$GT_ActiveTrade.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
        <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (After Trade)   -->
      <!-- ======================================= -->
      <!-- Check for pilot changes after successful trade completion -->
      <!-- This is a natural restart point where the GT default order reruns -->
      <set_value name="$currentPilot" exact="this.ship.pilot"/>
      <do_if value="this.$trackedPilot? and $currentPilot != this.$trackedPilot">
        <!-- Pilot changed! Send signal to MD system -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PILOT CHANGE DETECTED after trade completion! Old: ' + @this.$trackedPilot.name + ', New: ' + @$currentPilot.name" chance="100"/>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
          $updateType = 'pilot_change',
          $Ship = this.ship,
          $pilot = $currentPilot,
          $oldPilot = this.$trackedPilot
        ]"/>
      </do_if>
      <!-- Update tracked pilot (always, even if no change) -->
      <set_value name="this.$trackedPilot" exact="$currentPilot"/>
      
      <!-- CRITICAL: Check if pilot is missing (pilot was transferred away) -->
      <!-- If GT order is running but ship has no pilot, cleanup and self-cancel -->
      <do_if value="not $currentPilot">
        <set_value name="$pendingTransferredPilot" exact="false"/>
        <set_value name="$pendingPilotName" exact="'NONE'"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$pk">
            <set_value name="$candidatePilot" exact="$pilotKeys.{$pk}"/>
            <do_if value="$candidatePilot and global.$GT_Pilots.{$candidatePilot}? and global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == this.ship.idcode and global.$GT_Pilots.{$candidatePilot}.$Status? and global.$GT_Pilots.{$candidatePilot}.$Status == 'paused'">
              <set_value name="$pendingTransferredPilot" exact="true"/>
              <set_value name="$pendingPilotName" exact="if $candidatePilot.name? then $candidatePilot.name else 'UNKNOWN'"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$pendingTransferredPilot">
          <do_if value="not this.$pendingPilotTransferSince?">
            <set_value name="this.$pendingPilotTransferSince" exact="player.age"/>
          </do_if>
          <set_value name="$pendingTransferElapsed" exact="player.age - this.$pendingPilotTransferSince"/>
          
          <do_if value="$pendingTransferElapsed lt 15min">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Missing pilot after trade completion but transfer is in progress for ' + $pendingPilotName + ' (elapsed=' + ($pendingTransferElapsed / 1s) + 's) - waiting before cancellation'" chance="100"/>
            </do_if>
            <wait exact="5s"/>
            <return/>
          </do_if>
        </do_if>
        
        <remove_value name="this.$pendingPilotTransferSince"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MISSING PILOT DETECTED after trade completion - pilot was transferred away, cleaning up and self-canceling GT order'" chance="100"/>
        </do_if>
        
        <!-- Get original ship name from ship registry -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{this.ship}.$OriginalShipName"/>
        </do_if>
        
        <!-- Send cleanup signal (name restoration handled by MD system) -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = null,
          $Reason = 'Pilot transferred away - GT order cannot run without pilot',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Cancel all active orders (trade orders, etc.) -->
        <cancel_all_orders object="this.ship"/>
        
        <!-- Self-cancel GT order -->
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Check if this is a pathfinding retry (try next cached alternative) -->
      <do_if value="this.$tryNextTrade?">
        <remove_value name="this.$tryNextTrade"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Immediately requesting next trade (cache will skip failed trades)'" chance="100"/>
        </do_if>
        <!-- Skip market update wait - immediately try next cached trade -->
        <resume label="main_loop"/>
      </do_if>
      
      <!-- NOTE: Auto-repair check has been moved to MD system (gt_trading_ai.xml TradeCompleted cue) -->
      <!-- This ensures it runs even when the order is aborted/replaced during trade execution -->
      
      <!-- Update market data interval -->
      <wait max="$gt_marketupdatefreq">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Found'" comment="New trade found"/>
              <event_object_signalled object="this.ship" param="'GT_No_Trade_Found'" comment="Wake-up signal"/>
            </check_any>
          </conditions>
          <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Signal received during market update wait - resuming immediately'" chance="100"/>
            </do_if>
          </actions>
        </interrupt>
      </wait>
      <resume label="main_loop"/>
      
      <!-- ========================================= -->
      <!-- NO TRADE FOUND - ESCALATING RETRY LOGIC  -->
      <!-- ========================================= -->
      <label name="escape_from_blacklisted"/>
      
      <!-- Determine home sector -->
      <set_value name="$homeBase" exact="this.$effectiveHome"/>
      <set_value name="$homeSector" exact="null"/>
      <do_if value="$homeBase? and $homeBase.exists">
        <do_if value="$homeBase.isclass.station">
          <set_value name="$homeSector" exact="$homeBase.sector"/>
        </do_if>
        <do_elseif value="$homeBase.isclass.sector">
          <set_value name="$homeSector" exact="$homeBase"/>
        </do_elseif>
      </do_if>
      <do_if value="not $homeSector? or not $homeSector.exists">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: Home sector not available - cannot escape, continuing retry logic'" chance="100"/>
        </do_if>
        <resume label="no_trade_retry"/>
      </do_if>
      
      <set_value name="$currentSector" exact="this.ship.sector"/>
      <do_if value="$currentSector == $homeSector">
        <!-- Already in home sector; just retry normally -->
        <resume label="main_loop"/>
      </do_if>
      
      <!-- Use cached blacklist group from init -->
      <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
      
      <!-- Resolve sector whitelist for escape candidate selection (whitelist overrides blacklist) -->
      <set_value name="$validationWhitelist" exact="[]"/>
      <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
        <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
      </do_if>
      
      <!-- Build a jump path to home (ignoring blacklist so we can walk 'toward home') -->
      <get_jump_path component="$jumppath" multiple="true" uselocalhighways="true">
        <start object="this.ship"/>
        <end object="$homeSector"/>
      </get_jump_path>
      
      <!-- Choose the first non-blacklisted sector along the route (or the home sector) -->
      <set_value name="$escapeSector" exact="$homeSector"/>
      <do_all exact="$jumppath.count" counter="$pi">
        <set_value name="$entry" exact="$jumppath.{$pi}"/>
        <do_if value="$entry? and ($entry.isclass.gate or $entry.isclass.highwayentrygate)">
          <set_value name="$candidateSector" exact="$entry.destination.sector"/>
          <set_value name="$candWhitelisted" exact="false"/>
          <do_if value="$validationWhitelist.count gt 0">
            <do_all exact="$validationWhitelist.count" counter="$swIdx">
              <do_if value="$validationWhitelist.{$swIdx} == $candidateSector">
                <set_value name="$candWhitelisted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$candActivityBL" exact="false"/>
          <set_value name="$candTravelBL" exact="false"/>
          <do_if value="not $candWhitelisted">
            <set_value name="$candActivityBL" exact="@$candidateSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
            <set_value name="$candTravelBL" exact="@$candidateSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
          </do_if>
          <set_value name="$candBL" exact="$candActivityBL or $candTravelBL"/>
          <do_if value="not $candBL or $candidateSector == $homeSector">
            <set_value name="$escapeSector" exact="$candidateSector"/>
            <break/>
          </do_if>
        </do_if>
      </do_all>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: Moving toward home sector' +
          '\n  Current: ' + @$currentSector.knownname +
          '\n  Home:    ' + @$homeSector.knownname +
          '\n  Target:  ' + @$escapeSector.knownname" chance="100"/>
      </do_if>
      
      <!-- Logbook: escape fallback (rate-limited, respects per-ship logbook setting) -->
      <set_value name="$logEnabled" exact="false"/>
      <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK3' and @this.ship.defaultorder.$logbookentries">
        <set_value name="$logEnabled" exact="true"/>
      </do_if>
      <!-- Subordinates inherit logbook setting from commander -->
      <do_elseif value="@this.ship.defaultorder.id == 'Assist' and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
        <set_value name="$logEnabled" exact="true"/>
      </do_elseif>
      
      <do_if value="$logEnabled">
        <set_value name="$lastEscapeLogbookTime" exact="0"/>
        <do_if value="this.$lastEscapeFallbackLogbookEntryTime?">
          <set_value name="$lastEscapeLogbookTime" exact="this.$lastEscapeFallbackLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastEscapeLogbook" exact="player.age - $lastEscapeLogbookTime"/>
        <do_if value="$timeSinceLastEscapeLogbook ge 300s or $lastEscapeLogbookTime == 0">
          <set_value name="$logbookMessage" exact="'Commander,\n\nI am currently in a blacklisted sector and could not find any trade route that safely moves me out.\n\nEscape fallback activated: moving toward my home sector.\n\nCurrent: ' + @$currentSector.knownname + '\nHome: ' + @$homeSector.knownname + '\nTarget: ' + @$escapeSector.knownname + '\n\nStatus: Escaping blacklist lock\n\nAboard ' + this.ship.knownname"/>
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'general',
            $Title = 'Escape Fallback: ' + this.ship.knownname,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          <set_value name="this.$lastEscapeFallbackLogbookEntryTime" exact="player.age"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Escape fallback logbook entry created'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Create a visible, native navigation order for the player ("Fly and Wait") toward the escape sector.
           Timeout is the post-arrival hold (NOT how long the AI waits â€” the AI resumes immediately because
           of immediate="true" + <resume>). The previous 1s value caused the order to settle within a single
           AI tick after arrival, so the next main_loop pass would re-blacklist and re-fire MoveWait in a
           tight loop. Scale by the planned jump count (one hop minimum) so the ship has a realistic
           settling window before GT re-evaluates. -->
      <set_value name="$escapeTimeout" exact="if $jumppath? and $jumppath.count gt 0 then $jumppath.count * 60s else 60s"/>
      <!-- CRITICAL: Set escape flag RIGHT BEFORE creating order to ensure it's set when ship starts fleeing -->
      <do_if value="global.$GT_Ships?">
        <do_if value="not global.$GT_Ships.{this.ship}?">
          <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
      </do_if>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship=this.ship,
          $pilot=this.ship.pilot,
          $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType='trader'
        ]"/>
      </do_if>
      
      <create_order object="this.ship" id="'MoveWait'" immediate="true">
        <param name="destination" value="[$escapeSector, position.[0,0,0]]"/>
        <param name="timeout" value="$escapeTimeout"/>
        <param name="debugchance" value="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </create_order>
      
      <!-- After moving (or attempting to), retry trading immediately -->
      <resume label="main_loop"/>
      
      <label name="no_trade_retry"/>

      <!-- CRITICAL: Initialize retryCooldown with safe default FIRST to prevent property lookup errors -->
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <!-- IMPORTANT (AI script lifetime): local $vars may not persist across <wait/> yields. -->
      <!-- Persist the computed cooldown time on the order instance for any post-wait logic. -->
      <set_value name="this.$retryCooldown" exact="10s"/>

      <!-- SPECIAL CASE: system busy / home refresh in progress (MD queues are saturated OR a home-sector cache refresh is running)
           â†’ fixed retry, do NOT escalate cooldown.
           Smooth gameplay > throughput: wait longer here to reduce request churn and let the scheduler/queues drain.
           TODO: keep hardcoded for now; consider exposing as tuning later. -->
      <set_value name="$noTradeReason" exact="if this.$lastNoTradeReason? then this.$lastNoTradeReason else ''"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': no_trade_retry entered: reason=\'' + $noTradeReason + '\' player.money=' + (player.money / 100) + ' Cr'" chance="100"/>
      </do_if>
      <do_if value="$noTradeReason == 'busy' or $noTradeReason == 'busy_batch' or $noTradeReason == 'home_refresh' or $noTradeReason == 'insufficient_funds'">
        <set_value name="this.$lastNoTradeReason" exact="''"/>
        <!-- NOTE: Global money cap (global.$GT_MoneyCapActive) is set by the authoritative guard
             when blocking. No per-ship state needed here â€” the global flag stops all ships. -->
        <!-- Fixed retry for special reasons (do NOT use escalating cooldown). -->
        <!-- For home_refresh: shorter wait (3s) to allow cache retry while home refresh populates cache -->
        <!-- For busy/busy_batch: longer wait (8-12s) to let queues drain -->
        <!-- For insufficient_funds: long wait (90-150s) - budget exhausted, no point retrying quickly.
             Jitter prevents thundering herd: ships spread across 60s window instead of all waking simultaneously.
             On wake-up, the early money gate and global money cap prevent futile searches. -->
        <set_value name="this.$retryCooldown" exact="if $noTradeReason == 'home_refresh' then 3s else (if $noTradeReason == 'insufficient_funds' then 120s else 10s)"/>
        <!-- JITTER: Compute per-ship min/max wait for <wait> element.
             insufficient_funds: 90s-150s (Â±25%), busy: 8s-12s (Â±20%), home_refresh: 3s (no jitter, needs responsiveness) -->
        <set_value name="this.$retryWaitMin" exact="if $noTradeReason == 'insufficient_funds' then 90s else (if $noTradeReason == 'home_refresh' then 3s else 8s)"/>
        <set_value name="this.$retryWaitMax" exact="if $noTradeReason == 'insufficient_funds' then 150s else (if $noTradeReason == 'home_refresh' then 3s else 12s)"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': System busy/home refresh/insufficient funds - waiting ' + (this.$retryWaitMin/1s) + '-' + (this.$retryWaitMax/1s) + 's then retrying cache (reason: ' + $noTradeReason + ')'" chance="100"/>
        </do_if>
        
        <!-- Record attempt summary (bounded history) -->
        <do_if value="not global.$GT_NoTradeHistory?">
          <set_value name="global.$GT_NoTradeHistory" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_NoTradeHistory.{this.ship}? or global.$GT_NoTradeHistory.{this.ship} == null or typeof global.$GT_NoTradeHistory.{this.ship} != datatype.list">
          <set_value name="global.$GT_NoTradeHistory.{this.ship}" exact="[]"/>
        </do_if>
        <append_to_list name="global.$GT_NoTradeHistory.{this.ship}" exact="table[
          $Time = player.age,
          $Reason = $noTradeReason,
          $Wait = this.$retryCooldown,
          $Sector = @this.ship.sector.knownname,
          $Home = if @this.$effectiveHome != null then @this.$effectiveHome.knownname else (if @this.ship.defaultorder.$home != null then @this.ship.defaultorder.$home.knownname else ''),
          $MaxDistance = if this.$effectiveMaxDistance? then this.$effectiveMaxDistance else null
        ]"/>
        <!-- Keep last 12 entries max -->
        <do_if value="global.$GT_NoTradeHistory.{this.ship}.count gt 12">
          <set_value name="$old" exact="global.$GT_NoTradeHistory.{this.ship}.{1}"/>
          <remove_from_list name="global.$GT_NoTradeHistory.{this.ship}" exact="$old"/>
        </do_if>
        
        <!-- Logbook entry for insufficient funds (throttled: once per 5 minutes per ship) -->
        <do_if value="$noTradeReason == 'insufficient_funds' and $gt_logbookentries">
          <set_value name="$lastInsufficientFundsLogbook" exact="0"/>
          <do_if value="this.$lastInsufficientFundsLogbookTime?">
            <set_value name="$lastInsufficientFundsLogbook" exact="this.$lastInsufficientFundsLogbookTime"/>
          </do_if>
          <set_value name="$timeSinceLastInsufficientFundsLogbook" exact="player.age - $lastInsufficientFundsLogbook"/>
          <do_if value="$timeSinceLastInsufficientFundsLogbook ge 300s or $lastInsufficientFundsLogbook == 0">
            <set_value name="$playerMoneyDisplay" exact="player.money / 100"/>
            <set_value name="$thresholdDisplay" exact="if this.$minPlayerMoney? then this.$minPlayerMoney else 1000"/>
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrading operations paused â€” insufficient funds.\n\nPlayer account: ' + $playerMoneyDisplay + ' Cr\nMinimum required: ' + $thresholdDisplay + ' Cr\n\nI will resume trading automatically once funds are above the threshold.\n\nYou can adjust the minimum in:\nGalaxyTrader Settings &gt; Fleet &gt; Min Player Money\n\nStanding by,\nAboard ' + this.ship.knownname"/>
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'alerts',
              $Title = 'Insufficient Funds: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
            <set_value name="this.$lastInsufficientFundsLogbookTime" exact="player.age"/>
          </do_if>
        </do_if>

        <set_command command="command.wait"/>
        <set_command_action commandaction="commandaction.standingby"/>
        <!-- JITTER: Use per-ship min/max to spread retries across a time window (prevents thundering herd).
             For insufficient_funds: 90s-150s window. For busy: 8s-12s. For home_refresh: fixed 3s. -->
        <wait min="if @this.$retryWaitMin != null then @this.$retryWaitMin else 10s" max="if @this.$retryWaitMax != null then @this.$retryWaitMax else 10s"/>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- CARGO DISPOSAL: Track cargo disposal failures separately -->
      <set_value name="$isCargoDisposal" exact="false"/>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
        <set_value name="$isCargoDisposal" exact="true"/>
        <!-- Initialize cargo disposal failure counter if not exists -->
        <do_if value="not this.$cargoDisposalFailed?">
          <set_value name="this.$cargoDisposalFailed" exact="0"/>
        </do_if>
        <!-- Increment cargo disposal failure counter -->
        <set_value name="this.$cargoDisposalFailed" exact="this.$cargoDisposalFailed + 1"/>
      </do_if>
      <do_else>
        <!-- Normal trade search failure - increment normal counter -->
        <!-- Increment failure counter -->
        <set_value name="this.$searchFailed" exact="this.$searchFailed + 1"/>
      </do_else>
      
      <!-- Calculate escalating wait time: ~10s, ~20s, ~30s, ~40s, ~50s, ~60s (max) -->
      <!-- Use cargo disposal counter if this is cargo disposal, otherwise use normal counter -->
      <set_value name="$failureCount" exact="if $isCargoDisposal then this.$cargoDisposalFailed else this.$searchFailed"/>
      <!-- Escalating cooldown (cap 60s). This is also required for "no trade found" logbook notifications (they trigger at 60s). -->
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <set_value name="this.$retryCooldown" exact="([$failureCount, 6].min) * 10s"/>
      <!-- JITTER: Â±20% around the base cooldown to prevent ships at the same escalation level
           from all retrying in the same frame (thundering herd prevention).
           Example: failureCount=3 â†’ base=30s â†’ min=24s, max=36s -->
      <set_value name="this.$retryCooldownMin" exact="[this.$retryCooldown * 0.8, 5s].max"/>
      <set_value name="this.$retryCooldownMax" exact="this.$retryCooldown * 1.2"/>
      
      <!-- Record attempt summary (bounded history).
           We capture the most recent MD rejection statistics (if available) so the 60s logbook report can show a timeline. -->
      <do_if value="not global.$GT_NoTradeHistory?">
        <set_value name="global.$GT_NoTradeHistory" exact="table[]"/>
      </do_if>
      <do_if value="not global.$GT_NoTradeHistory.{this.ship}? or global.$GT_NoTradeHistory.{this.ship} == null or typeof global.$GT_NoTradeHistory.{this.ship} != datatype.list">
        <set_value name="global.$GT_NoTradeHistory.{this.ship}" exact="[]"/>
      </do_if>
      <set_value name="$lastRejectionStats" exact="null"/>
      <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.$LastRejectionStats? and global.$GT_SearchResult.$LastRejectionStats.{this.ship}?">
        <set_value name="$lastRejectionStats" exact="@global.$GT_SearchResult.$LastRejectionStats.{this.ship}"/>
      </do_if>
      <set_value name="$rsTotal" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Total != null then @$lastRejectionStats.$Total else null"/>
      <set_value name="$rsDock" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Docking != null then @$lastRejectionStats.$Docking else null"/>
      <set_value name="$rsProfit" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Profit != null then @$lastRejectionStats.$Profit else null"/>
      <set_value name="$rsAmount" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Amount != null then @$lastRejectionStats.$Amount else null"/>
      <set_value name="$rsBlacklist" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Blacklist != null then @$lastRejectionStats.$Blacklist else null"/>
      <set_value name="$rsSector" exact="if $lastRejectionStats != null and @$lastRejectionStats.$SectorName != null then @$lastRejectionStats.$SectorName else @this.ship.sector.knownname"/>
      <set_value name="$rsMaxDist" exact="if $lastRejectionStats != null and @$lastRejectionStats.$MaxDistance != null then @$lastRejectionStats.$MaxDistance else null"/>
      <set_value name="$rsMinProfit" exact="if $lastRejectionStats != null and @$lastRejectionStats.$MinAbsoluteProfit != null then @$lastRejectionStats.$MinAbsoluteProfit else null"/>
      <set_value name="$rsDistance" exact="0"/>
      <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{this.ship}? and global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance?">
        <set_value name="$rsDistance" exact="global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance"/>
      </do_if>
      <append_to_list name="global.$GT_NoTradeHistory.{this.ship}" exact="table[
        $Time = player.age,
        $Reason = $noTradeReason,
        $Wait = this.$retryCooldown,
        $Sector = $rsSector,
        $Home = if @this.$effectiveHome != null then @this.$effectiveHome.knownname else (if @this.ship.defaultorder.$home != null then @this.ship.defaultorder.$home.knownname else ''),
        $MaxDistance = $rsMaxDist,
        $MinAbsoluteProfit = $rsMinProfit,
        $Total = $rsTotal,
        $Docking = $rsDock,
        $Profit = $rsProfit,
        $Amount = $rsAmount,
        $Blacklist = $rsBlacklist,
        $Distance = $rsDistance
      ]"/>
      <!-- Keep last 12 entries max -->
      <do_if value="global.$GT_NoTradeHistory.{this.ship}.count gt 12">
        <set_value name="$old" exact="global.$GT_NoTradeHistory.{this.ship}.{1}"/>
        <remove_from_list name="global.$GT_NoTradeHistory.{this.ship}" exact="$old"/>
      </do_if>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No ' + (if $isCargoDisposal then 'cargo buyer' else 'profitable trades') + ' found (attempt ' + $failureCount + ') - waiting ' + (this.$retryCooldown/1s) + 's before retry'" chance="100"/>
      </do_if>
      
      <!-- Set ship to waiting state -->
      <set_command command="command.wait"/>
      <set_command_action commandaction="commandaction.standingby"/>
      
      <!-- Persist $isCargoDisposal and $noTradeReason before wait (local variables lost across wait yields) -->
      <set_value name="this.$isCargoDisposal" exact="$isCargoDisposal"/>
      <set_value name="this.$noTradeReason" exact="$noTradeReason"/>
      
      <!-- Wait with escalating delay -->
      <!-- Track if wait was interrupted (so we don't write logbook if interrupted) -->
      <set_value name="$waitInterrupted" exact="false"/>
      <set_value name="$tradeFoundDuringWait" exact="false"/>
      <set_value name="this.$waitInterrupted" exact="$waitInterrupted"/>
      <set_value name="this.$tradeFoundDuringWait" exact="$tradeFoundDuringWait"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Entering wait for ' + (this.$retryCooldownMin/1s) + '-' + (this.$retryCooldownMax/1s) + 's at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- JITTER: Use min/max range (Â±20%) to spread ships across a time window instead of all waking together -->
      <wait min="if @this.$retryCooldownMin != null then @this.$retryCooldownMin else 8s" max="if @this.$retryCooldownMax != null then @this.$retryCooldownMax else 12s" comment="Jittered escalating wait with interrupt">
        <interrupt>
          <conditions>
            <!-- Only GT_Trade_Found should interrupt retry wait -->
            <!-- GT_No_Trade_Found signals during retry wait are ignored to preserve escalating cooldown -->
            <event_object_signalled object="this.ship" param="'GT_Trade_Found'" comment="MD found a trade"/>
          </conditions>
          <actions>
            <!-- Capture signal payload before resuming so trade_found gets the correct source/list -->
            <set_value name="$intSignalData" exact="event.param2"/>
            <set_value name="$intSignalTradeList" exact="[]"/>
            <set_value name="$intSignalSearchMethod" exact="''"/>
            <do_if value="$intSignalData? and $intSignalData != null">
              <set_value name="$intSignalTradeList" exact="@$intSignalData.$TradeList"/>
              <set_value name="$intSignalSearchMethod" exact="@$intSignalData.$SearchMethod"/>
            </do_if>
            <set_value name="this.$tradeListFromSignal" exact="$intSignalTradeList"/>
            <set_value name="this.$searchMethodFromSignal" exact="if $intSignalSearchMethod != null and $intSignalSearchMethod != '' then $intSignalSearchMethod else ''"/>
            <set_value name="this.$waitInterrupted" exact="true"/>
            <set_value name="this.$tradeFoundDuringWait" exact="true"/>
            <set_value name="$waitInterrupted" exact="true"/>
            <set_value name="$tradeFoundDuringWait" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade found during retry wait - stored ' + (if $intSignalTradeList != null then $intSignalTradeList.count else 0) + ' trades from interrupt payload'" chance="100"/>
            </do_if>
            <!-- Resume to trade_found label to process the trade -->
            <resume label="trade_found"/>
          </actions>
        </interrupt>
      </wait>
      <!-- Restore variables after wait (they may have been lost across yield) -->
      <set_value name="$waitInterrupted" exact="this.$waitInterrupted"/>
      <set_value name="$tradeFoundDuringWait" exact="this.$tradeFoundDuringWait"/>
      <set_value name="$isCargoDisposal" exact="this.$isCargoDisposal"/>
      <set_value name="$noTradeReason" exact="if this.$noTradeReason? then this.$noTradeReason else ''"/>
      <!-- Recompute $failureCount from persisted instance variables (local was lost across wait) -->
      <set_value name="$failureCount" exact="if $isCargoDisposal then (if this.$cargoDisposalFailed? then this.$cargoDisposalFailed else 0) else (if this.$searchFailed? then this.$searchFailed else 0)"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Wait completed at game time ' + player.age + ' - continuing retry logic (trade found: ' + this.$tradeFoundDuringWait + ')'" chance="100"/>
      </do_if>
      
      <!-- Write logbook entry only if we've reached max wait (60s) AND wait completed naturally (not interrupted by trade found) -->
      <!-- Also check if we've already written a logbook entry recently to prevent duplicates -->
      <set_value name="$shouldWriteLogbook" exact="false"/>
      <set_value name="$shouldWriteCargoDisposalLogbook" exact="false"/>
      
      <!-- CARGO DISPOSAL: Separate logbook entry for cargo disposal failures -->
      <do_if value="this.$isCargoDisposal and this.$retryCooldown == 60s and not this.$tradeFoundDuringWait">
        <!-- Check if we've already written a cargo disposal failure logbook entry in the last 5 minutes (300s) -->
        <set_value name="$lastCargoDisposalLogbookTime" exact="0"/>
        <do_if value="this.$lastCargoDisposalLogbookEntryTime?">
          <set_value name="$lastCargoDisposalLogbookTime" exact="this.$lastCargoDisposalLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastCargoDisposalLogbook" exact="player.age - $lastCargoDisposalLogbookTime"/>
        <do_if value="$timeSinceLastCargoDisposalLogbook ge 300s or $lastCargoDisposalLogbookTime == 0">
          <!-- Haven't written cargo disposal failure logbook recently (or never) - OK to write -->
          <set_value name="$shouldWriteCargoDisposalLogbook" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- Determine if this is a "critical persistent" reason that should trigger logbook earlier -->
      <!-- Critical reasons: ship is fundamentally unable to trade, not just temporarily busy -->
      <set_value name="$isCriticalReason" exact="$noTradeReason == 'blacklist' or $noTradeReason == 'all_rejected' or $noTradeReason == 'trade_rules_violation'"/>
      
      <!-- Normal trade search logbook entry -->
      <!-- Trigger conditions:
           - Standard: 60s cooldown reached (6th failure)
           - Critical: 2nd consecutive failure with a persistent reason (blacklist/all_rejected/trade_rules) 
           Either way, wait must have completed naturally (not interrupted by trade found) -->
      <do_if value="not $isCargoDisposal and not $tradeFoundDuringWait and (this.$retryCooldown == 60s or ($isCriticalReason and $failureCount ge 2))">
        <!-- Check if we've already written a logbook entry in the last 5 minutes (300s) -->
        <set_value name="$lastLogbookTime" exact="0"/>
        <do_if value="this.$lastLogbookEntryTime?">
          <set_value name="$lastLogbookTime" exact="this.$lastLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastLogbook" exact="player.age - $lastLogbookTime"/>
        <do_if value="$timeSinceLastLogbook ge 300s or $lastLogbookTime == 0">
          <!-- Haven't written logbook recently (or never) - OK to write -->
          <set_value name="$shouldWriteLogbook" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- CARGO DISPOSAL: Write separate failure message for cargo disposal -->
      <do_if value="$shouldWriteCargoDisposalLogbook">
        <!-- Check if logbook enabled -->
        <set_value name="$logEnabled" exact="false"/>
        <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK3' and @this.ship.defaultorder.$logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        <!-- Subordinates inherit logbook setting from commander -->
        <do_elseif value="@this.ship.defaultorder.id == 'Assist' and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
          <set_value name="$logEnabled" exact="true"/>
        </do_elseif>
        
        <do_if value="$logEnabled">
          <!-- Get cargo info for logbook message -->
          <set_value name="$cargoList" exact="this.ship.cargo.list"/>
          <set_value name="$cargoTypes" exact="[]"/>
          <do_all exact="$cargoList.count" counter="$i">
            <set_value name="$ware" exact="$cargoList.{$i}"/>
            <set_value name="$amount" exact="this.ship.cargo.{$ware}.count"/>
            <append_to_list name="$cargoTypes" exact="@$ware.name + ' x' + $amount"/>
          </do_all>
          <set_value name="$cargoDescription" exact="if $cargoTypes.count gt 0 then $cargoTypes.{1} + (if $cargoTypes.count gt 1 then ', ' + $cargoTypes.{2} else '') + (if $cargoTypes.count gt 2 then ', ...' else '') else 'Unknown'"/>
          
          <!-- Write cargo disposal failure logbook entry -->
          <set_value name="$logbookMessage" exact="'Commander,\n\nI have been unable to find a buyer for my cargo after multiple attempts. My cargo hold contains: ' + $cargoDescription + '\n\nI have tried ' + $failureCount + ' times but cannot locate a suitable buyer within my trading range. This may be due to:\n- No stations buying these wares nearby\n- All potential buyers are blacklisted\n- Docking restrictions at available stations\n\nI will continue waiting and retrying periodically. You may want to manually assign a sell order or adjust my trading parameters.\n\nStatus: Waiting for buyer opportunity\n\nWith patience,\nAboard ' + this.ship.knownname"/>
          
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'alerts',
            $Title = 'Cargo Disposal Failed: ' + this.ship.knownname,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          
          <!-- Update last cargo disposal logbook entry time -->
          <set_value name="this.$lastCargoDisposalLogbookEntryTime" exact="player.age"/>
        </do_if>
      </do_if>
      
      <do_if value="$shouldWriteLogbook">
        <!-- Check if logbook enabled -->
        <set_value name="$logEnabled" exact="false"/>
        <!-- Use the already-computed effective logbook flag (matches other GT logbook messages). -->
        <do_if value="$gt_logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        
        <do_if value="$logEnabled">
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               COMMON DATA RETRIEVAL: Gather rejection stats, sector info, etc.
               Used by ALL logbook message templates below.
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          <set_value name="$lastRejectionStats" exact="null"/>
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.$LastRejectionStats? and global.$GT_SearchResult.$LastRejectionStats != null and global.$GT_SearchResult.$LastRejectionStats.{this.ship}?">
            <set_value name="$lastRejectionStats" exact="global.$GT_SearchResult.$LastRejectionStats.{this.ship}"/>
          </do_if>
          <set_value name="$totalRejected" exact="0"/>
          <set_value name="$tradesRejectedDocking" exact="0"/>
          <set_value name="$tradesRejectedProfit" exact="0"/>
          <set_value name="$tradesRejectedAmount" exact="0"/>
          <set_value name="$tradesRejectedBlacklist" exact="0"/>
          <set_value name="$sectorName" exact="''"/>
          <set_value name="$maxDistance" exact="10"/>
          <set_value name="$minAbsoluteProfit" exact="100"/>
          
          <do_if value="$lastRejectionStats != null">
            <set_value name="$tradesRejectedDockingTemp" exact="@$lastRejectionStats.$Docking"/>
            <set_value name="$tradesRejectedDocking" exact="if $tradesRejectedDockingTemp? and $tradesRejectedDockingTemp != null then $tradesRejectedDockingTemp else 0"/>
            <set_value name="$tradesRejectedProfitTemp" exact="@$lastRejectionStats.$Profit"/>
            <set_value name="$tradesRejectedProfit" exact="if $tradesRejectedProfitTemp? and $tradesRejectedProfitTemp != null then $tradesRejectedProfitTemp else 0"/>
            <set_value name="$tradesRejectedAmountTemp" exact="@$lastRejectionStats.$Amount"/>
            <set_value name="$tradesRejectedAmount" exact="if $tradesRejectedAmountTemp? and $tradesRejectedAmountTemp != null then $tradesRejectedAmountTemp else 0"/>
            <set_value name="$tradesRejectedBlacklistTemp" exact="@$lastRejectionStats.$Blacklist"/>
            <set_value name="$tradesRejectedBlacklist" exact="if $tradesRejectedBlacklistTemp? and $tradesRejectedBlacklistTemp != null then $tradesRejectedBlacklistTemp else 0"/>
            <set_value name="$totalRejectedTemp" exact="@$lastRejectionStats.$Total"/>
            <set_value name="$totalRejectedFromStats" exact="if $totalRejectedTemp? and $totalRejectedTemp != null then $totalRejectedTemp else 0"/>
            <set_value name="$sumOfRejections" exact="$tradesRejectedDocking + $tradesRejectedProfit + $tradesRejectedAmount + $tradesRejectedBlacklist"/>
            <set_value name="$totalRejected" exact="if $totalRejectedFromStats gt $sumOfRejections then $totalRejectedFromStats else $sumOfRejections"/>
            
            <set_value name="$sectorNameTemp" exact="@$lastRejectionStats.$SectorName"/>
            <do_if value="$sectorNameTemp? and $sectorNameTemp != null and $sectorNameTemp != ''">
              <set_value name="$sectorName" exact="$sectorNameTemp"/>
            </do_if>
            <do_else>
              <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
            </do_else>
            <set_value name="$maxDistanceTemp" exact="@$lastRejectionStats.$MaxDistance"/>
            <do_if value="$maxDistanceTemp? and $maxDistanceTemp != null">
              <set_value name="$maxDistance" exact="$maxDistanceTemp"/>
            </do_if>
            <set_value name="$minAbsoluteProfitTemp" exact="@$lastRejectionStats.$MinAbsoluteProfit"/>
            <do_if value="$minAbsoluteProfitTemp? and $minAbsoluteProfitTemp != null">
              <set_value name="$minAbsoluteProfit" exact="$minAbsoluteProfitTemp"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
          </do_else>
          
          <!-- Final safety check: Ensure sector name is not null -->
          <do_if value="not $sectorName? or $sectorName == null or $sectorName == ''">
            <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
            <do_if value="not $sectorName? or $sectorName == null or $sectorName == ''">
              <set_value name="$sectorName" exact="'Unknown Sector'"/>
            </do_if>
          </do_if>
          
          <set_value name="$hasRejectionStats" exact="false"/>
          <do_if value="$lastRejectionStats != null">
            <do_if value="($lastRejectionStats.$Total? and $lastRejectionStats.$Total != null) or ($lastRejectionStats.$Profit? and $lastRejectionStats.$Profit != null) or ($lastRejectionStats.$Docking? and $lastRejectionStats.$Docking != null) or ($lastRejectionStats.$Amount? and $lastRejectionStats.$Amount != null) or ($lastRejectionStats.$Blacklist? and $lastRejectionStats.$Blacklist != null)">
              <set_value name="$hasRejectionStats" exact="true"/>
            </do_if>
          </do_if>
          <set_value name="$totalEvaluated" exact="0"/>
          <do_if value="$hasRejectionStats and $lastRejectionStats.$Total? and $lastRejectionStats.$Total != null">
            <set_value name="$totalEvaluated" exact="$lastRejectionStats.$Total"/>
          </do_if>
          <set_value name="$tradesRejectedDistance" exact="0"/>
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{this.ship}? and global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance?">
            <set_value name="$tradesRejectedDistance" exact="global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance"/>
          </do_if>
          
          <!-- Log the logbook message data before generating -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': LOGBOOK (reason=' + $noTradeReason + ', attempt=' + $failureCount + ', critical=' + $isCriticalReason + ')'" chance="100"/>
          </do_if>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               LOGBOOK TITLE â€” reason-specific for clarity in the logbook list
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          <set_value name="$logbookTitle" exact="'No Trades: ' + this.ship.knownname"/>
          <do_if value="$noTradeReason == 'blacklist'">
            <set_value name="$logbookTitle" exact="'Routes Blocked: ' + this.ship.knownname"/>
          </do_if>
          <do_elseif value="$noTradeReason == 'all_rejected'">
            <set_value name="$logbookTitle" exact="'All Trades Rejected: ' + this.ship.knownname"/>
          </do_elseif>
          <do_elseif value="$noTradeReason == 'trade_rules_violation'">
            <set_value name="$logbookTitle" exact="'Trade Rules Violation: ' + this.ship.knownname"/>
          </do_elseif>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               LOGBOOK MESSAGE â€” reason-specific templates
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          
          <!-- â”€â”€â”€ BLACKLIST: All viable routes pass through blocked sectors â”€â”€â”€ -->
          <do_if value="$noTradeReason == 'blacklist'">
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrading blocked â€” all viable routes pass through blacklisted sectors.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'All trade routes within range are blocked by threat intelligence or blacklist settings. ' +
              'The ship cannot reach any profitable stations safely.\n\n' +
              'Suggestions:\n' +
              '- Review blacklist settings (GalaxyTrader Settings &gt; Trade)\n' +
              '- Increase trading range to find routes around blocked sectors\n' +
              '- Relocate this ship to a sector with better connectivity\n' +
              '- Check if threat levels have changed recently'"/>
          </do_if>
          
          <!-- â”€â”€â”€ ALL_REJECTED: Every trade candidate was filtered out â”€â”€â”€ -->
          <do_elseif value="$noTradeReason == 'all_rejected'">
            <!-- Display strings -->
            <set_value name="$evalDisplay" exact="if $hasRejectionStats then $totalEvaluated else 'â€”'"/>
            <set_value name="$profitDisplay" exact="if $hasRejectionStats then $tradesRejectedProfit else 'â€”'"/>
            <set_value name="$dockDisplay" exact="if $hasRejectionStats then $tradesRejectedDocking else 'â€”'"/>
            <set_value name="$amountDisplay" exact="if $hasRejectionStats then $tradesRejectedAmount else 'â€”'"/>
            <set_value name="$distDisplay" exact="if $hasRejectionStats then $tradesRejectedDistance else 'â€”'"/>
            <set_value name="$blDisplay" exact="if $hasRejectionStats then $tradesRejectedBlacklist else 'â€”'"/>
            
            <set_value name="$logbookMessage" exact="'Commander,\n\nAll trade candidates were rejected after evaluation.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Min profit: ' + ($minAbsoluteProfit/100) + ' Cr\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'Rejection breakdown (evaluated ' + $evalDisplay + '):\n' +
              '  Profit too low: ' + $profitDisplay + '\n' +
              '  Docking restricted: ' + $dockDisplay + '\n' +
              '  Amount too small: ' + $amountDisplay + '\n' +
              '  Out of range: ' + $distDisplay + '\n' +
              '  Blacklisted/path blocked: ' + $blDisplay + '\n'"/>
            
            <!-- Add targeted hint based on dominant rejection reason -->
            <set_value name="$hint" exact="''"/>
            <do_if value="not $hasRejectionStats or $totalEvaluated == 0">
              <set_value name="$hint" exact="'No offers were evaluated. Check if markets are discovered and unblocked.'"/>
            </do_if>
            <do_elseif value="$tradesRejectedProfit gt ($tradesRejectedDocking + $tradesRejectedBlacklist + $tradesRejectedDistance)">
              <set_value name="$hint" exact="'Most candidates failed profit checks. Lower min profit/ROI or increase range.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDocking gt 0 and $tradesRejectedDocking ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates failed docking checks. Check docking restrictions at stations.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedBlacklist gt 0 and $tradesRejectedBlacklist ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Blacklist restrictions filtered many routes. Review threat settings.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDistance gt 0 and $tradesRejectedDistance ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates were out of range. Increase max distance if appropriate.'"/>
            </do_elseif>
            <do_if value="$hint != ''">
              <set_value name="$logbookMessage" exact="$logbookMessage + '\nHint: ' + $hint"/>
            </do_if>
          </do_elseif>
          
          <!-- â”€â”€â”€ TRADE_RULES_VIOLATION: Station trade rules prevent trading â”€â”€â”€ -->
          <do_elseif value="$noTradeReason == 'trade_rules_violation'">
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrade rules violation â€” target stations reject trades from this ship.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'This may be caused by:\n' +
              '- Build storage restrictions (station is a build storage)\n' +
              '- Carrier/auxiliary station trading restrictions\n' +
              '- Trade rule changes after search started\n' +
              '- Station ownership or faction restrictions\n\n' +
              'Suggestions:\n' +
              '- Check station trade rule settings\n' +
              '- Review IgnoreCarrierAux / IgnoreBuildStorage in GT Settings\n' +
              '- Increase trading range to find alternative stations'"/>
          </do_elseif>
          
          <!-- â”€â”€â”€ GENERIC: Standard "no profitable trades" with full diagnostics â”€â”€â”€ -->
          <do_else>
            <!-- Display strings (show 'â€”' when stats were not recorded) -->
            <set_value name="$evalDisplay" exact="if $hasRejectionStats then $totalEvaluated else 'â€”'"/>
            <set_value name="$profitDisplay" exact="if $hasRejectionStats then $tradesRejectedProfit else 'â€”'"/>
            <set_value name="$dockDisplay" exact="if $hasRejectionStats then $tradesRejectedDocking else 'â€”'"/>
            <set_value name="$amountDisplay" exact="if $hasRejectionStats then $tradesRejectedAmount else 'â€”'"/>
            <set_value name="$distDisplay" exact="if $hasRejectionStats then $tradesRejectedDistance else 'â€”'"/>
            <set_value name="$blDisplay" exact="if $hasRejectionStats then $tradesRejectedBlacklist else 'â€”'"/>
            
            <!-- Friendly reason string for the generic header -->
            <set_value name="$reasonFriendly" exact="
              if $noTradeReason == 'reserved' then 'all trades reserved by fleet'
              else if $noTradeReason == 'offers_expired' then 'trade offers expired during validation'
              else if $noTradeReason == 'no_trade' then 'no profitable trades found'
              else if $noTradeReason == 'invalid_trade' then 'trade data became invalid'
              else 'no profitable trades found'"/>
            
            <set_value name="$logbookMessage" exact="'Commander,\n\nNo trades available â€” ' + $reasonFriendly + '.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Min profit: ' + ($minAbsoluteProfit/100) + ' Cr\n' +
              'Attempts: ' + $failureCount + ' (cooldown reached ' + (this.$retryCooldown/1s) + 's)\n\n' +
              'Latest rejection stats (evaluated ' + $evalDisplay + '):\n' +
              '  Profit too low: ' + $profitDisplay + '\n' +
              '  Docking restricted: ' + $dockDisplay + '\n' +
              '  Amount too small: ' + $amountDisplay + '\n' +
              '  Out of range: ' + $distDisplay + '\n' +
              '  Blacklisted/path blocked: ' + $blDisplay +
              (if not $hasRejectionStats then '\n  (no stats recorded for this attempt)' else '') + '\n\n' +
              'Recent attempts (newest first):'"/>

            <!-- Append up to last 4 history rows (most recent first) -->
            <set_value name="$hist" exact="null"/>
            <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
              <set_value name="$hist" exact="global.$GT_NoTradeHistory.{this.ship}"/>
            </do_if>
            <set_value name="$histCount" exact="if $hist != null then $hist.count else 0"/>
            <set_value name="$linesToShow" exact="[$histCount, 4].min"/>
            <do_all exact="$linesToShow" counter="$li">
              <!-- Reverse index: last entry is most recent -->
              <set_value name="$idx" exact="$histCount - ($li - 1)"/>
              <set_value name="$h" exact="$hist.{$idx}"/>
              
              <!-- Age formatting: mm:ss ago -->
              <set_value name="$ageSec" exact="0"/>
              <do_if value="$h.$Time? and $h.$Time != null">
                <set_value name="$ageSec" exact="((player.age - $h.$Time) / 1s)i"/>
              </do_if>
              <do_if value="$ageSec lt 0">
                <set_value name="$ageSec" exact="0"/>
              </do_if>
              <set_value name="$ageMin" exact="($ageSec / 60)i"/>
              <set_value name="$ageRem" exact="$ageSec - ($ageMin * 60)"/>
              <set_value name="$ageRemStr" exact="if $ageRem lt 10 then '0' + $ageRem else $ageRem"/>
              <set_value name="$ageStr" exact="$ageMin + ':' + $ageRemStr + ' ago'"/>
              
              <!-- Reason (friendly) -->
              <set_value name="$rRaw" exact="if $h.$Reason? and $h.$Reason != null and $h.$Reason != '' then $h.$Reason else 'none'"/>
              <set_value name="$r" exact="
                if $rRaw == 'busy' then 'busy'
                else if $rRaw == 'busy_batch' then 'busy (batch)'
                else if $rRaw == 'home_refresh' then 'home refresh'
                else if $rRaw == 'reserved' then 'reserved (fleet)'
                else if $rRaw == 'blacklist' then 'BLACKLISTED'
                else if $rRaw == 'all_rejected' then 'all rejected'
                else if $rRaw == 'trade_rules_violation' then 'trade rules'
                else if $rRaw == 'offers_expired' then 'offers expired'
                else if $rRaw == 'insufficient_funds' then 'low funds'
                else if $rRaw == 'invalid_trade' then 'invalid trade'
                else if $rRaw == 'no_trade' then 'no trade'
                else if $rRaw == 'no_cargo' then 'no cargo'
                else if $rRaw == 'no_gt_order' then 'no GT order'
                else if $rRaw == 'forced_sell_failed' then 'sell failed'
                else if $rRaw == 'no_training_stations' then 'no training'
                else $rRaw"/>
              
              <!-- Build compact rejection summary -->
              <set_value name="$p" exact="if $h.$Profit? and $h.$Profit != null then $h.$Profit else 0"/>
              <set_value name="$d" exact="if $h.$Docking? and $h.$Docking != null then $h.$Docking else 0"/>
              <set_value name="$a" exact="if $h.$Amount? and $h.$Amount != null then $h.$Amount else 0"/>
              <set_value name="$bl" exact="if $h.$Blacklist? and $h.$Blacklist != null then $h.$Blacklist else 0"/>
              <set_value name="$dist" exact="if $h.$Distance? and $h.$Distance != null then $h.$Distance else 0"/>
              <set_value name="$w" exact="if $h.$Wait? and $h.$Wait != null then (($h.$Wait / 1s)i) else 0"/>
              
              <set_value name="$rej" exact="''"/>
              <do_if value="$p gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'profit ' + $p"/></do_if>
              <do_if value="$d gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'dock ' + $d"/></do_if>
              <do_if value="$a gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'amount ' + $a"/></do_if>
              <do_if value="$dist gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'dist ' + $dist"/></do_if>
              <do_if value="$bl gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'blacklist ' + $bl"/></do_if>
              <do_if value="$rej == ''"><set_value name="$rej" exact="'â€”'"/></do_if>
              
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n  ' + $ageStr + ' | ' + $r + ' | rej: ' + $rej"/>
            </do_all>

            <!-- Quick hints (bounded) -->
            <set_value name="$hint" exact="''"/>
            <do_if value="not $hasRejectionStats">
              <set_value name="$hint" exact="'No rejection stats were recorded yet (likely no evaluation completed for this ship).'" />
            </do_if>
            <do_elseif value="$totalEvaluated == 0">
              <set_value name="$hint" exact="'No offers were evaluated. Consider increasing range or checking if markets are visible/unblocked.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedProfit gt ($tradesRejectedDocking + $tradesRejectedBlacklist + $tradesRejectedDistance)">
              <set_value name="$hint" exact="'Most candidates failed profit checks. Lower min profit/ROI or increase range.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDocking gt 0 and $tradesRejectedDocking ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates failed docking checks. Check docking restrictions at stations.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedBlacklist gt 0">
              <set_value name="$hint" exact="'Blacklist/path restrictions filtered many routes. Review blacklists/threat settings.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDistance gt 0">
              <set_value name="$hint" exact="'Many candidates were out of range. Increase max distance (buy/sell) if appropriate.'"/>
            </do_elseif>
            <do_if value="$hint != ''">
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n\nHint: ' + $hint"/>
            </do_if>
          </do_else>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               SEND LOGBOOK ENTRY (common for all reason-specific templates)
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          
          <!-- Dump the final logbook message to DebugLog for diagnosis/copy-paste.
               Rate-limited by the existing escalation + 5min per-ship logbook cooldown. -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-LogbookDump] (' + this.ship.idcode + ') reason=' + $noTradeReason + ':\n' + $logbookMessage" chance="100"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'tips',
            $Title = $logbookTitle,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          
          <!-- Log that logbook entry was created -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Logbook entry created (reason=' + $noTradeReason + ', title=' + $logbookTitle + ')'" chance="100"/>
          </do_if>
          
          <!-- Mark that we've written a logbook entry now -->
          <set_value name="this.$lastLogbookEntryTime" exact="player.age"/>
        </do_if>
      </do_if>
      
      <!-- Reset command state and resume search -->
      <do_if value="this.$effectiveIdleParking and not $isCargoDisposal and not $tradeFoundDuringWait and $failureCount ge 6 and this.ship.cargo.count == 0">
        <set_value name="$gtIdleHome" exact="if this.$effectiveHome? and this.$effectiveHome != null and this.$effectiveHome.exists then this.$effectiveHome else null"/>
        <do_if value="$gtIdleHome? and $gtIdleHome != null">
          <run_script name="'lib.gt.idlepark'">
            <param name="handoffMode" value="'trigger'"/>
            <param name="handoffShip" value="this.ship"/>
            <param name="home" value="$gtIdleHome"/>
            <param name="debugchance" value="this.$debugchance"/>
          </run_script>
        </do_if>
      </do_if>
      <set_command command="command.searchtrades"/>
      <set_command_action commandaction="commandaction.searchingtrades"/>
      
      <!-- Resume main trading loop -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resuming main_loop label'" chance="100"/>
      </do_if>
      <resume label="main_loop"/>
    </actions>
  </attention>
  
  <on_abort>
    <!-- Intentional handoff: idle parking delegates to GTIdlePark for visible queued docking. -->
    <set_value name="$isIdleParkHandoff" exact="false"/>
    <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.orders.count gt 0">
      <do_all exact="this.ship.orders.count" counter="$ipoi">
        <set_value name="$ipOrder" exact="this.ship.orders.{$ipoi}"/>
        <do_if value="@$ipOrder.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_if>
        <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_elseif>
      </do_all>
    </do_if>
    <do_if value="$isIdleParkHandoff">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': on_abort skipped (handoff to GTIdlePark)'" chance="100"/>
      </do_if>
      <return/>
    </do_if>

    <!-- Release new scheduler semaphore slot if this ship aborts mid-search -->
    <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>

    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
      <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
    </do_if>

    <!-- Release fleet reservation if ship aborts with an active reservation.
         Restored from pre-migration reservation flow: prevents stale reservations blocking fleet. -->
    <do_if value="this.$activeReservationKey? and global.$GT_Reservations? and global.$GT_Reservations.{this.$activeReservationKey}?">
      <remove_value name="global.$GT_Reservations.{this.$activeReservationKey}"/>
      <do_if value="global.$GT_ReservationStats? and global.$GT_ReservationStats.$Active gt 0">
        <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
      </do_if>
      <do_if value="global.$GT_ReservationStats?">
        <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
      </do_if>
    </do_if>

    <!-- Clear stale clearance naming flag on order abort only when cargo is actually empty.
         Keep [CLEARANCE]/CL during active disposal with remaining cargo. -->
    <do_if value="this.ship.cargo.count == 0 and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
      <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship = this.ship,
          $pilot = this.ship.pilot,
          $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType = 'trader'
        ]"/>
      </do_if>
    </do_if>

    <!-- Enhanced cleanup when order is aborted/replaced -->
    <!-- Preserve pilot XP data when order is manually replaced by player -->
    <!-- Only completely wipe data in genuine cleanup scenarios (ship destroyed, pilot changed, etc.) -->
    <set_value name="$isActivelyTrading" exact="false"/>
    <set_value name="$isTrainingTransition" exact="false"/>
    
    <!-- Clean up resupply tracking if order aborted mid-resupply -->
    <!-- IMPORTANT: Do NOT clear during maintenance transitions (subordinates can be aborted/replaced while resupply order is active) -->
    <do_if value="not this.$maintenance_transition? and global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
      <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleaned up resupply tracking on order abort'" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Check if ship has active TradePerform orders -->
    <do_if value="this.ship.orders.count gt 1">
      <do_all exact="this.ship.orders.count" counter="$i">
        <do_if value="this.ship.orders.{$i}.id == 'TradePerform'">
          <set_value name="$isActivelyTrading" exact="true"/>
          <break/>
        </do_if>
      </do_all>
    </do_if>
    
    <!-- Check if a training order was recently created (within last 5 seconds) -->
    <do_if value="this.$training_order_created? and (player.age - this.$training_order_created) lt 5s">
      <set_value name="$isTrainingTransition" exact="true"/>
    </do_if>
    
    <!-- Also check the flag-based detection -->
    <do_if value="this.$training_transition?">
      <set_value name="$isTrainingTransition" exact="true"/>
    </do_if>
    
    <!-- Check if a maintenance order was recently created (repair/resupply) -->
    <set_value name="$isMaintenanceTransition" exact="false"/>
    <do_if value="this.$maintenance_transition?">
      <set_value name="$isMaintenanceTransition" exact="true"/>
    </do_if>
    
    <!-- Ship state and orders at removal detection -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$debugShip" exact="this.ship"/>
      <set_value name="$debugDefaultOrder" exact="@$debugShip.defaultorder.id"/>
      <set_value name="$debugCommander" exact="@$debugShip.commander"/>
      <set_value name="$debugCommanderId" exact="if @$debugCommander.exists then @$debugCommander.idcode else 'NONE'"/>
      <set_value name="$debugCommanderOrder" exact="if @$debugCommander.exists and @$debugCommander.defaultorder != null then @$debugCommander.defaultorder.id else 'NONE'"/>
      <set_value name="$debugPilot" exact="@$debugShip.pilot"/>
      <set_value name="$debugPilotName" exact="if $debugPilot != null then @$debugPilot.knownname else 'NONE'"/>
      
      <!-- Build orders list -->
      <set_value name="$debugOrdersList" exact="[]"/>
      <set_value name="$debugOrdersCount" exact="$debugShip.orders.count"/>
      <do_all exact="$debugOrdersCount" counter="$i">
        <set_value name="$orderId" exact="@$debugShip.orders.{$i}.id"/>
        <append_to_list name="$debugOrdersList" exact="if $orderId then $orderId else 'UNKNOWN'"/>
      </do_all>
      <set_value name="$debugOrdersStr" exact="if $debugOrdersList.count gt 0 then $debugOrdersList.{1} + (if $debugOrdersList.count gt 1 then ', ' + $debugOrdersList.{2} else '') + (if $debugOrdersList.count gt 2 then ', ' + $debugOrdersList.{3} else '') + (if $debugOrdersList.count gt 3 then ', ' + $debugOrdersList.{4} else '') + (if $debugOrdersList.count gt 4 then ', ...' else '') else 'NONE'"/>
      
      <!-- Check GT order status -->
      <set_value name="$debugHasDirectGT" exact="false"/>
      <do_if value="$debugDefaultOrder == 'GalaxyTraderMK3'">
        <set_value name="$debugHasDirectGT" exact="true"/>
      </do_if>
      <set_value name="$debugHasGTCommander" exact="false"/>
      <do_if value="@$debugCommander.exists and $debugCommanderOrder == 'GalaxyTraderMK3'">
        <set_value name="$debugHasGTCommander" exact="true"/>
      </do_if>
      
      <!-- Check if in GT_Ships registry -->
      <set_value name="$debugInRegistry" exact="global.$GT_Ships? and global.$GT_Ships.{$debugShip}?"/>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] REMOVAL DETECTION DEBUG: ' + $debugShip.idcode + ' - COMPREHENSIVE STATE'" chance="100"/>
        <debug_text text="'[GT-AI]   Ship: ' + $debugShip.idcode + ' (' + (if $debugShip.knownname then $debugShip.knownname else 'UNNAMED') + ')'" chance="100"/>
        <debug_text text="'[GT-AI]   Pilot: ' + $debugPilotName + (if $debugPilot != null then ' (exists)' else ' (NONE)')" chance="100"/>
        <debug_text text="'[GT-AI]   Default Order: ' + (if $debugDefaultOrder then $debugDefaultOrder else 'NONE')" chance="100"/>
        <debug_text text="'[GT-AI]   Active Orders (' + $debugOrdersCount + '): ' + $debugOrdersStr" chance="100"/>
        <debug_text text="'[GT-AI]   Commander: ' + $debugCommanderId + ' (Order: ' + $debugCommanderOrder + ')'" chance="100"/>
        <debug_text text="'[GT-AI]   GT Status: Direct=' + $debugHasDirectGT + ', ViaCommander=' + $debugHasGTCommander + ', InRegistry=' + $debugInRegistry" chance="100"/>
        <debug_text text="'[GT-AI]   Flags: ActivelyTrading=' + $isActivelyTrading + ', TrainingTransition=' + $isTrainingTransition + ', MaintenanceTransition=' + $isMaintenanceTransition" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Order cancellation detection -->
    <!-- Only send signal if GT default order is actually cancelled -->
    <!-- on_abort can fire when trade orders are cancelled, but GT order might still be active -->
    <!-- Unified GT order status check (inline for AI scripts) -->
    <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
    <set_value name="$hasDirectGTOrder" exact="false"/>
    <set_value name="$hasGTCommander" exact="false"/>
    <set_value name="$isGTControlled" exact="false"/>
    
    <!-- Check direct GT order -->
    <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3'">
      <set_value name="$hasDirectGTOrder" exact="true"/>
      <set_value name="$isGTControlled" exact="true"/>
    </do_if>
    
    <!-- Check commander status -->
    <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
      <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
        <set_value name="$hasGTCommander" exact="true"/>
        <do_if value="$currentDefaultOrder == 'Assist'">
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
      </do_if>
    </do_if>
    
    <set_value name="$isGTOrderCancelled" exact="false"/>
    
    <!-- If GT order is gone, process cleanup REGARDLESS of training/maintenance transitions -->
    <!-- Only skip Phase 7 if GT order is STILL ACTIVE AND there's a training/maintenance transition -->
    <do_if value="not $isGTControlled and $currentDefaultOrder != 'Assist'">
      <!-- GT order is gone - process cleanup even if training/maintenance/disposal orders exist -->
      <!-- Check if GT default order is still active -->
      <!-- If defaultorder.id is null, different, or not GalaxyTraderMK3, GT order was cancelled -->
      <do_if value="not $currentDefaultOrder">
        <!-- No default order â†’ GT order was cancelled -->
        <set_value name="$isGTOrderCancelled" exact="true"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: NONE)'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'GT_Order_Cancelled'
        ]"/>
        
        <!-- EVENT-DRIVEN: Trigger orphaned ship check -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
          <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
        </do_if>
        
        <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
        <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
        <!-- Use this.$was_subordinate flag or check state manager state -->
        <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
        <do_if value="this.$was_subordinate?">
          <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
          <!-- Check state manager to see if ship was a subordinate -->
          <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship is CURRENTLY subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$isSubordinateOfGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Restore name if:
             1. Ship was NOT a subordinate before cancellation, OR
             2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
        <set_value name="$shouldRestoreName" exact="false"/>
        <do_if value="not $wasSubordinateBeforeCancellation">
          <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
          <do_if value="not $isSubordinateOfGTCommander">
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
          <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_elseif>
        
        <do_if value="$shouldRestoreName and this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'GT order cancelled - restoring original name',
              $OriginalName = $originalName
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="$currentDefaultOrder != 'GalaxyTraderMK3'">
        <!-- Different default order â†’ Check if GT order was actually cancelled -->
        <!-- For subordinates with Assist order, trade order termination is NORMAL -->
        <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
        <set_value name="$actualDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <!-- Check if ship has direct GT order -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <do_if value="$actualDefaultOrder == 'GalaxyTraderMK3'">
          <set_value name="$hasDirectGTOrder" exact="true"/>
        </do_if>
        
        <!-- Check if ship is subordinate to GT commander (current commander, not old) -->
        <set_value name="$hasGTCommander" exact="false"/>
        <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$hasGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
        <!-- For subordinates, Assist order termination is handled by Assist order's on_abort -->
        <!-- Trade order termination is NORMAL and should NOT trigger cleanup -->
        <set_value name="$shouldEmitCleanup" exact="false"/>
        <do_if value="not $hasDirectGTOrder and not $hasGTCommander and $currentDefaultOrder != 'Assist'">
          <!-- No direct GT order and no GT commander = GT order truly gone -->
          <set_value name="$shouldEmitCleanup" exact="true"/>
        </do_if>
        
        <!-- Emit cleanup signal if GT order is gone -->
        <do_if value="$shouldEmitCleanup">
          <set_value name="$isGTOrderCancelled" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ')'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI]  PHASE 7: Trade order aborted but GT order still active for ' + this.ship.idcode + ' (default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ') - NOT sending GT_Order_Cancelled'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
        <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
        <!-- Use this.$was_subordinate flag or check state manager state -->
        <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
        <do_if value="this.$was_subordinate?">
          <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
          <!-- Check state manager to see if ship was a subordinate -->
          <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship is CURRENTLY subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
            <set_value name="$isSubordinateOfGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Restore name if:
             1. Ship was NOT a subordinate before cancellation, OR
             2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
        <set_value name="$shouldRestoreName" exact="false"/>
        <do_if value="not $wasSubordinateBeforeCancellation">
          <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
          <do_if value="not $isSubordinateOfGTCommander">
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
          <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_elseif>
        
        <do_if value="$shouldRestoreName and this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'GT order cancelled - restoring original name',
              $OriginalName = $originalName
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_elseif>
    </do_if>
    <do_elseif value="$hasDirectGTOrder or $hasGTCommander">
      <!-- GT order still active - only skip Phase 7 if there's a training/maintenance transition -->
      <!-- This prevents cleanup when GT order creates training/maintenance orders (normal behavior) -->
      <do_if value="not $isTrainingTransition and not $isMaintenanceTransition">
        <!-- GT order active, no transitions - check if default order changed -->
        <!-- (This is the original Phase 7 logic for when GT order is still active) -->
        <!-- Check if GT default order is still active -->
        <!-- If defaultorder.id is null, different, or not GalaxyTraderMK3, GT order was cancelled -->
        <do_if value="not $currentDefaultOrder">
          <!-- No default order â†’ GT order was cancelled -->
          <set_value name="$isGTOrderCancelled" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: NONE)'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
          
          <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
          <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
          <!-- Use this.$was_subordinate flag or check state manager state -->
          <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
          <do_if value="this.$was_subordinate?">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
            <!-- Check state manager to see if ship was a subordinate -->
            <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
            <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
              <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
            </do_if>
          </do_elseif>
          
          <!-- Check if ship is CURRENTLY subordinate to GT commander -->
          <set_value name="$isSubordinateOfGTCommander" exact="false"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
              <set_value name="$isSubordinateOfGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Restore name if:
               1. Ship was NOT a subordinate before cancellation, OR
               2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
          <set_value name="$shouldRestoreName" exact="false"/>
          <do_if value="not $wasSubordinateBeforeCancellation">
            <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
            <do_if value="not $isSubordinateOfGTCommander">
              <set_value name="$shouldRestoreName" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
            <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_elseif>
          
          <do_if value="$shouldRestoreName and this.ship.pilot?">
            <set_value name="$originalName" exact="null"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
            </do_if>
            
            <do_if value="$originalName">
              <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $Reason = 'GT order cancelled - restoring original name',
                $OriginalName = $originalName
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$currentDefaultOrder != 'GalaxyTraderMK3'">
          <!-- Different default order â†’ Check if GT order was actually cancelled -->
          <!-- For subordinates with Assist order, trade order termination is NORMAL -->
          <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
          <set_value name="$actualDefaultOrder" exact="@this.ship.defaultorder.id"/>
          
          <!-- Check if ship has direct GT order -->
          <set_value name="$hasDirectGTOrder" exact="false"/>
          <do_if value="$actualDefaultOrder == 'GalaxyTraderMK3'">
            <set_value name="$hasDirectGTOrder" exact="true"/>
          </do_if>
          
          <!-- Check if ship is subordinate to GT commander (current commander, not old) -->
          <set_value name="$hasGTCommander" exact="false"/>
          <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
              <set_value name="$hasGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
          <!-- For subordinates, Assist order termination is handled by Assist order's on_abort -->
          <!-- Trade order termination is NORMAL and should NOT trigger cleanup -->
          <set_value name="$shouldEmitCleanup" exact="false"/>
          <do_if value="not $hasDirectGTOrder and not $hasGTCommander">
            <!-- No direct GT order and no GT commander = GT order truly gone -->
            <set_value name="$shouldEmitCleanup" exact="true"/>
          </do_if>
          
          <!-- Emit cleanup signal if GT order is gone -->
          <do_if value="$shouldEmitCleanup">
            <set_value name="$isGTOrderCancelled" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ')'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI]  PHASE 7: Trade order aborted but GT order still active for ' + this.ship.idcode + ' (default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ') - NOT sending GT_Order_Cancelled'" chance="100"/>
            </do_if>
          </do_else>
          
          <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
          <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
          <!-- Use this.$was_subordinate flag or check state manager state -->
          <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
          <do_if value="this.$was_subordinate?">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
            <!-- Check state manager to see if ship was a subordinate -->
            <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
            <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
              <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
            </do_if>
          </do_elseif>
          
          <!-- Check if ship is CURRENTLY subordinate to GT commander -->
          <set_value name="$isSubordinateOfGTCommander" exact="false"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and (@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
              <set_value name="$isSubordinateOfGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Restore name if:
               1. Ship was NOT a subordinate before cancellation, OR
               2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
          <set_value name="$shouldRestoreName" exact="false"/>
          <do_if value="not $wasSubordinateBeforeCancellation">
            <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
            <do_if value="not $isSubordinateOfGTCommander">
              <set_value name="$shouldRestoreName" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
            <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_elseif>
          
          <do_if value="$shouldRestoreName and this.ship.pilot?">
            <set_value name="$originalName" exact="null"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
            </do_if>
            
            <do_if value="$originalName">
              <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $Reason = 'GT order cancelled - restoring original name',
                $OriginalName = $originalName
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_elseif>
        <do_else>
          <!-- GT order still active - this is just trade order cancellation, not GT order cancellation -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': on_abort fired but GT order still active (default order: ' + $currentDefaultOrder + ') - skipping Phase 7 (trade order cancellation, not GT order cancellation)'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
      <do_else>
        <!-- GT order still active AND training/maintenance transition - skip Phase 7 (normal behavior) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order still active with training/maintenance transition - skipping Phase 7 (normal transition, not removal)'" chance="100"/>
        </do_if>
      </do_else>
    </do_elseif>
    
    <!-- Check if subordinate cleanup already sent signal (to avoid duplicate) -->
    <do_if value="this.$subordinate_cleanup_sent?">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate cleanup signal already sent - skipping duplicate'" chance="100"/>
    </do_if>
    <do_else>
      <!-- Check for permanent removal FIRST, regardless of trading state -->
      <!-- When player stops order, we MUST restore name even if TradePerform orders are still active -->
      <!-- Unified GT order status check (inline for AI scripts) -->
      <!-- If GT order is gone (no direct, no commander), it's permanent removal REGARDLESS of trading state -->
      <set_value name="$isPermanentRemoval" exact="not $hasDirectGTOrder and not $hasGTCommander and $currentDefaultOrder != 'Assist'"/>
      
      <do_if value="$isPermanentRemoval">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$debugOrdersCount" exact="this.ship.orders.count"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order removed (no direct GT, no GT commander) â†’ PERMANENT REMOVAL (actively trading: ' + $isActivelyTrading + ', orders count: ' + $debugOrdersCount + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- GT order still active - check other conditions -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order still active (direct: ' + $hasDirectGTOrder + ', commander: ' + $hasGTCommander + ') - checking other removal conditions'" chance="100"/>
        </do_if>
        
        <!-- Additional checks: no default order, different order, or not registered -->
        <do_if value="not $currentDefaultOrder">
          <!-- No default order at all â†’ PERMANENT REMOVAL -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No default order detected â†’ PERMANENT REMOVAL'" chance="100"/>
        </do_if>
        <do_elseif value="$currentDefaultOrder and $currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'Assist'">
          <!-- Ship has a DIFFERENT permanent default order â†’ PERMANENT REMOVAL -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Different default order (' + $currentDefaultOrder + ') detected â†’ PERMANENT REMOVAL'" chance="100"/>
        </do_elseif>
        <do_elseif value="not (global.$GT_Ships? and global.$GT_Ships.{this.ship}?)">
          <!-- Ship was removed from GT (unregistered), definitely restore name -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship no longer registered in GT_Ships â†’ PERMANENT REMOVAL (even if actively trading)'" chance="100"/>
        </do_elseif>
      </do_else>
      
      <!-- Calculate subordinate status (needed for both permanent removal and pause checks) -->
      <set_value name="$isSubordinate" exact="$currentDefaultOrder == 'Assist' and $hasGTCommander"/>
      
      <!-- Always restore name on permanent removal, even if actively trading -->
      <do_if value="$isPermanentRemoval">
        <!-- Send ABORT signal: Restore ship name and clean up completely -->
        <do_if value="this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'Order permanently removed by player',
              $OriginalName = $originalName
            ]"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Sending ABORT signal (restore name, preserve XP) - permanent removal detected'" chance="100"/>
        </do_if>
        
        <!-- Clear training and maintenance flags -->
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_order_created"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$maintenance_transition"/>
      </do_if>
      <!-- Only send PAUSE signal if NOT permanently removed AND NOT actively trading AND NOT transitioning -->
      <!-- CRITICAL: Don't pause subordinates with Assist order - they should stay registered -->
      <do_elseif value="not $isActivelyTrading and not $isTrainingTransition and not $isMaintenanceTransition and not $isSubordinate">
        <!-- Send PAUSE signal: Preserve everything (name and XP) for potential resume -->
        <set_value name="$pauseData" exact="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Order temporarily replaced - preserving pilot data',
          $PreserveData = true
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Sending PAUSE signal (preserve everything for resume)'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Paused'" param2="$pauseData"/>
        
        <!-- Clear training and maintenance flags -->
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_order_created"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$maintenance_transition"/>
      </do_elseif>
      <do_elseif value="$isSubordinate">
        <!-- Subordinate with Assist order - don't pause, stay registered -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate with Assist order - NOT sending PAUSE (staying registered)'" chance="100"/>
        </do_if>
      </do_elseif>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship still actively trading/training/maintenance - NOT sending signals (will handle when orders complete)'" chance="100"/>
        </do_if>
      </do_else>
    </do_else>
  </on_abort>
  
</aiscript> <?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.trade.galaxytraderMK1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="4">
  <order id="GalaxyTraderMK1" name="{77000, 30002}" description="{77000, 30102}" category="trade" infinite="true" allowinloop="false" canplayercancel="true">
    <params>
      <!-- Home Station (required â€” must be player-owned station) -->
      <param name="homeStation" type="object" default="null" text="{77000, 30010}" comment="{77000, 30110}">
        <input_param name="class" value="[class.station]"/>
      </param>

      <!-- Max Sell Distance (skill-gated; MK1 commander is always station so use pilot only) -->
      <param name="maxsell" default="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max" type="number" text="{77000, 30011}" comment="{77000, 30111}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>

      <!-- Trade Rule Bypass -->
      <param name="ignoretraderules" default="false" type="bool" text="{77000, 30012}" comment="{77000, 30112}"/>

      <!-- Allow Illegal Wares -->
      <param name="allowillegal" default="false" type="bool" text="{77000, 30023}" comment="{77000, 30123}"/>
      <param name="enforceRouteIllegalLegality" default="false" type="bool" text="{77000,1070}" comment="{77000,1071}"/>

      <!-- Ware Filter (empty = auto-derive from station) -->
      <param name="warebasket" default="[]" type="list" text="{77000, 30013}" comment="{77000, 30113}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>

      <!-- Sell Cargo Fill Target -->
      <param name="selltarget" default="10" type="number" text="{77000, 30014}" comment="{77000, 30114}">
        <input_param name="min" value="10"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>

      <!-- Sell Selection Mode (1=Cargo, 2=Profit) -->
      <param name="sellselectionmode" default="2" type="number" text="{77000, 30024}" comment="{77000, 30124}">
        <input_param name="min" value="1"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>

      <!-- Supply Cargo Fill Target -->
      <param name="buytarget" default="80" type="number" text="{77000, 30016}" comment="{77000, 30116}">
        <input_param name="min" value="10"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>

      <!-- Backtrack Tolerance (extra jumps for multi-ware) -->
      <param name="backtrackTolerance" default="1" type="number" text="{77000, 30015}" comment="{77000, 30115}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="5"/>
        <input_param name="step" value="1"/>
      </param>

      <!-- Allow Multi-Trade chaining -->
      <param name="allowmultitrade" default="true" type="bool" text="{77000, 30025}" comment="{77000, 30125}"/>

      <!-- Logbook Entries -->
      <param name="logbookentries" default="true" type="bool" text="{77000, 30017}" comment="{77000, 30117}"/>

      <!-- Notification Level -->
      <param name="notifications" default="1" type="number" text="{77000, 30018}" comment="{77000, 30118}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>

      <!-- Fleet Coordination -->
      <param name="fleetcoordination" default="true" type="bool" text="{77000, 30019}" comment="{77000, 30119}" advanced="true"/>

      <!-- Debug Level -->
      <param name="debuglevel" default="1" type="number" text="{77000, 30020}" comment="{77000, 30120}" advanced="true">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>

      <!-- Supply Station (buy resources for home station) -->
      <param name="supply" default="false" type="bool" text="{77000, 30021}" comment="{77000, 30121}"/>

      <!-- Min Station Storage % (supply priority threshold) -->
      <param name="minstorage" default="50" type="number" text="{77000, 30022}" comment="{77000, 30122}">
        <input_param name="startvalue" value="50"/>
        <input_param name="min" value="10"/>
        <input_param name="max" value="90"/>
        <input_param name="step" value="5"/>
      </param>

      <!-- Min Product Storage % (export gate â€” products/tradewares only) -->
      <param name="minsellstorage" default="0" type="number" text="{77000, 30027}" comment="{77000, 30127}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>

      <!-- Buyer/supplier relative price range (stored 0-200 UI offset: 100 = 0.0 normalized, maps to -1.0..+1.0; default 90 = slightly below average) -->
      <param name="pricerange" default="90" type="number" text="{77000, 30029}" comment="{77000, 30129}">
        <input_param name="startvalue" value="90"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="200"/>
        <input_param name="step" value="5"/>
      </param>

      <!-- Return Home Between Cycles -->
      <param name="returnhome" default="false" type="bool" text="{77000, 30026}" comment="{77000, 30126}"/>
      <param name="autoJumpDistanceByLevel" default="false" type="bool" text="{77000,1098}" comment="{77000,1099}">
        <patch value="false" sinceversion="2"/>
      </param>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
  </order>

  <interrupts>
    <handler ref="SectorChangeHandler"/>
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>

    <!-- MK1 threat broadcast hook: level 6+ pilots can warn fleet when attacked -->
    <handler>
      <conditions>
        <event_object_attacked object="this.ship"/>
      </conditions>
      <actions>
        <set_value name="$pilotLevel" exact="1"/>
        <set_value name="$primaryFaction" exact="null"/>
        <do_if value="event.param? and event.param.owner?">
          <set_value name="$primaryFaction" exact="event.param.owner"/>
        </do_if>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        <do_if value="$pilotLevel ge 6">
          <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
            $Sector = this.ship.sector,
            $DetectedBy = this.ship,
            $HostileCount = 1,
            $PrimaryFaction = $primaryFaction,
            $ShipClass_XL = 0,
            $ShipClass_L = 0,
            $ShipClass_M = 1,
            $ShipClass_S = 0,
            $ThreatScore = 2,
            $Timestamp = player.age
          ]"/>
        </do_if>
      </actions>
    </handler>

    <!-- Training dispatch bridge: MK1 also needs to react to MD training station results -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$trainingStation" exact="$trainingData.$Station"/>
        <set_value name="$requiredLevel" exact="$trainingData.$Level"/>
        <!-- Academy enrollments append DockAndTrain to the queue (immediate=false)
             so the ship finishes its current task first and the player sees the
             training order lined up. Natural ladder keeps immediate dispatch. -->
        <set_value name="$isAcademy" exact="@$trainingData.$IsAcademy"/>
        <set_value name="$useImmediate" exact="not $isAcademy"/>
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist'">
          <set_value name="$useImmediate" exact="false"/>
        </do_if>
        <set_value name="$hasActiveTrainingOrder" exact="false"/>
        <do_all exact="this.ship.orders.count" counter="$oi">
          <do_if value="this.ship.orders.{$oi}.id == 'DockAndTrain'">
            <set_value name="$hasActiveTrainingOrder" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="$trainingStation? and $trainingStation.exists and not $hasActiveTrainingOrder">
          <create_order object="this.ship" id="'DockAndTrain'" immediate="$useImmediate">
            <param name="destination" value="$trainingStation"/>
            <param name="debugchance" value="this.$debugchance"/>
          </create_order>
          <set_value name="this.$mk1_lastTrainingSignalAt" exact="player.age"/>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Training station received - DockAndTrain created for ' + $trainingStation.knownname + ' (level ' + $requiredLevel + ', academy=' + $isAcademy + ', immediate=' + $useImmediate + ')'" chance="this.$debugchance"/>
        </do_if>
        <do_elseif value="$hasActiveTrainingOrder">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Training station signal ignored - DockAndTrain already active'" chance="this.$debugchance"/>
        </do_elseif>
      </actions>
    </handler>
  </interrupts>

  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <!-- ================================================================ -->
    <!-- MK1 INITIALIZATION                                               -->
    <!-- ================================================================ -->
    <set_value name="$debugchance" exact="if $debuglevel ge 1 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>

    <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': === MK1 INIT STARTED === (Ship: ' + this.ship.knownname + ', Pilot: ' + @this.ship.pilot.knownname + ')'" chance="$debugchance"/>

    <!-- Validate home station -->
    <do_if value="not $homeStation? or not $homeStation.exists or not $homeStation.isclass.station">
      <show_notification text="'GalaxyTrader MK1: ' + {77000, 30204}" timeout="10s"/>
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ABORT â€” no valid station assigned'" chance="100"/>
      <set_command_action commandaction="commandaction.standingby"/>
      <return/>
    </do_if>

    <do_if value="not $homeStation.isplayerowned">
      <show_notification text="'GalaxyTrader MK1: ' + {77000, 30203}.[$homeStation.knownname]" timeout="10s"/>
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ABORT â€” station not player-owned: ' + $homeStation.knownname" chance="100"/>
      <set_command_action commandaction="commandaction.standingby"/>
      <return/>
    </do_if>

    <!-- Station assignment: only for top-level or station-assigned ships.
         Ship-subordinates must remain assigned to their ship commander. -->
    <do_if value="(not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and this.ship.commander != $homeStation">
      <do_if value="this.ship.commander.exists and this.ship.commander != this.ship">
        <remove_object_commander object="this.ship"/>
      </do_if>
      <set_object_commander object="this.ship" commander="$homeStation" assignment="assignment.trade"/>
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Assigned to station ' + $homeStation.knownname + ' as trade subordinate'" chance="$debugchance"/>
    </do_if>

    <!-- Store effective values -->
    <set_value name="this.$homeStation" exact="$homeStation"/>
    <set_value name="this.$maxsell" exact="$maxsell"/>
    <set_value name="this.$ignoretraderules" exact="$ignoretraderules"/>
    <set_value name="this.$allowillegal" exact="$allowillegal"/>
    <set_value name="this.$enforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <set_value name="this.$warebasket" exact="$warebasket"/>
    <set_value name="this.$selltarget" exact="$selltarget"/>
    <set_value name="this.$sellselectionmode" exact="$sellselectionmode"/>
    <set_value name="this.$buytarget" exact="$buytarget"/>
    <set_value name="this.$backtrackTolerance" exact="$backtrackTolerance"/>
    <set_value name="this.$allowmultitrade" exact="$allowmultitrade"/>
    <set_value name="this.$logbookentries" exact="$logbookentries"/>
    <set_value name="this.$notifications" exact="$notifications"/>
    <set_value name="this.$fleetcoordination" exact="$fleetcoordination"/>
    <set_value name="this.$debuglevel" exact="$debuglevel"/>
    <set_value name="this.$debugchance" exact="$debugchance"/>
    <set_value name="this.$supply" exact="$supply"/>
    <set_value name="this.$minstorage" exact="$minstorage"/>
    <set_value name="this.$minsellstorage" exact="[0, [$minsellstorage, 100].min].max"/>
    <set_value name="this.$pricerange" exact="90"/>
    <do_if value="$pricerange?">
      <!-- New offset encoding: 0=min, 100=neutral, 200=max. Must be checked before legacy norm*100 (-100..+100). -->
      <do_if value="$pricerange ge 0 and $pricerange le 200">
        <set_value name="this.$pricerange" exact="$pricerange"/>
      </do_if>
      <do_elseif value="$pricerange ge -100 and $pricerange lt 0">
        <set_value name="this.$pricerange" exact="$pricerange + 100"/>
      </do_elseif>
    </do_if>
    <set_value name="this.$pricerange" exact="[this.$pricerange, 0].max"/>
    <set_value name="this.$pricerange" exact="[this.$pricerange, 200].min"/>
    <set_value name="this.$pricerangeNorm" exact="(this.$pricerange - 100) / 100"/>
    <set_value name="this.$returnhome" exact="$returnhome"/>
    <!-- Wait time when no trades found (from global settings or default 60s) -->
    <set_value name="this.$waitTimeNoTrades" exact="if global.$GT_MK1_GlobalSettings.$StationTrader.$WaitTimeNoTrades? then global.$GT_MK1_GlobalSettings.$StationTrader.$WaitTimeNoTrades else 60s"/>

    <set_command_action commandaction="commandaction.searchingtrades"/>

    <!-- Signal MD: ship registered as MK1 station trader -->
    <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
      $Ship = this.ship,
      $Config = table[
        $allowillegal = $allowillegal,
        $debuglevel = $debuglevel,
        $orderType = 'MK1'
      ]
    ]"/>
    <!-- Mirror MK3 lifecycle: register pilot/ship through GT_Update_Ship on init -->
    <do_if value="this.ship.pilot">
      <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
        $updateType = 'pilot_change',
        $Ship = this.ship,
        $pilot = this.ship.pilot,
        $oldPilot = null
      ]"/>
    </do_if>
    <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
      $Ship = this.ship,
      $UpdateType = 'GT_Order_Assigned',
      $MacroShipName = @this.ship.macro.name
    ]"/>

    <!-- Register station as MK1-supplied (if supply is enabled) -->
    <do_if value="this.$supply">
      <do_if value="not global.$GT_MK1SuppliedStations?">
        <set_value name="global.$GT_MK1SuppliedStations" exact="table[]"/>
      </do_if>
      <set_value name="global.$GT_MK1SuppliedStations.{this.$homeStation}" exact="this.ship"/>
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Registered station ' + this.$homeStation.knownname + ' as MK1-supplied'" chance="$debugchance"/>
    </do_if>

    <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': === MK1 INIT COMPLETE === Home: ' + $homeStation.knownname + ', MaxSell: ' + $maxsell + ', IgnoreRules: ' + $ignoretraderules + ', Supply: ' + $supply" chance="$debugchance"/>
  </init>

  <patch sinceversion="2">
    <do_if value="not $autoJumpDistanceByLevel?">
      <set_value name="$autoJumpDistanceByLevel" exact="false"/>
    </do_if>
    <set_value name="this.$prevAutoJumpDistance" exact="$autoJumpDistanceByLevel"/>
    <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': v1->v2 patch applied (autoJumpDistanceByLevel=' + $autoJumpDistanceByLevel + ')'" filter="savegame"/>
  </patch>

  <patch sinceversion="3">
    <do_if value="not $minsellstorage?">
      <set_value name="$minsellstorage" exact="0"/>
    </do_if>
    <set_value name="this.$minsellstorage" exact="[0, [$minsellstorage, 100].min].max"/>
    <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': v2->v3 patch applied (minsellstorage=' + this.$minsellstorage + ')'" filter="savegame"/>
  </patch>

  <patch sinceversion="4">
    <do_if value="not $enforceRouteIllegalLegality?">
      <set_value name="$enforceRouteIllegalLegality" exact="false"/>
    </do_if>
    <set_value name="this.$enforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': v3->v4 patch applied (enforceRouteIllegalLegality=' + $enforceRouteIllegalLegality + ')'" filter="savegame"/>
  </patch>

  <attention min="unknown">
    <actions>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <!-- ================================================================ -->
      <!-- MK1 MAIN LOOP                                                    -->
      <!-- ================================================================ -->
      <label name="main_loop"/>

      <!-- Drop orphaned live-search scratch if this order resumes at loop top after save/load. -->
      <do_if value="global.$GT_LiveSearchScratch? and global.$GT_LiveSearchScratch.{this.ship}?">
        <remove_value name="global.$GT_LiveSearchScratch.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_LiveSearchActiveShip? and global.$GT_LiveSearchActiveShip == this.ship">
        <remove_value name="global.$GT_LiveSearchActiveShip"/>
      </do_if>

      <!-- Unified ship name refresh (home sector, op-state, XP â€” content dedupe in MD) -->
      <run_script name="'lib.gt.attention.refresh_ship_name'">
        <param name="ship" value="this.ship"/>
      </run_script>
      <run_script name="'lib.gt.attention.autojump_distance_toggle'">
        <param name="autoJumpDistanceByLevel" value="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
      </run_script>

      <!-- In-flight academy / DockAndTrain: hold the default order while the ship
           completes training (MD timer + order.dock.train survive save/load). -->
      <set_value name="$gtHasDockAndTrain" exact="false"/>
      <do_if value="this.ship.orders? and this.ship.orders.count gt 0">
        <do_all exact="this.ship.orders.count" counter="$gtToi">
          <do_if value="this.ship.orders.{$gtToi}.id == 'DockAndTrain'">
            <set_value name="$gtHasDockAndTrain" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      <set_value name="$gtMdTrainingActive" exact="false"/>
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
        <set_value name="$gtMdTrainingActive" exact="true"/>
      </do_if>
      <do_if value="$gtHasDockAndTrain or $gtMdTrainingActive">
        <set_command_action commandaction="commandaction.standingby"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Holding for in-flight training (DockAndTrain=' + $gtHasDockAndTrain + ', MD timer=' + $gtMdTrainingActive + ')'" chance="100"/>
        </do_if>
        <wait max="10s">
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship"/>
            </conditions>
          </interrupt>
        </wait>
        <resume label="main_loop"/>
      </do_if>

      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': === MAIN LOOP START ==='" chance="this.$debugchance"/>
      <!-- Restore persistent released-undocked state (survives AI restarts/order handoffs). -->
      <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
        <set_value name="this.$mk1_returnhomeReleased" exact="true"/>
      </do_if>
      <do_elseif value="this.$mk1_returnhomeReleased?">
        <remove_value name="this.$mk1_returnhomeReleased"/>
      </do_elseif>

      <!-- Periodic training re-request for already blocked pilots (e.g. saves created before this handler existed). -->
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
        <set_value name="$blockedLevel" exact="0"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel?">
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <set_value name="$needsTrainingDispatch" exact="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded? or $blockedLevel gt 1"/>
        <set_value name="$gtSkipTrainingDispatch" exact="false"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
          <set_value name="$gtSkipTrainingDispatch" exact="true"/>
        </do_if>
        <do_if value="not $gtSkipTrainingDispatch and this.ship.orders? and this.ship.orders.count gt 0">
          <do_all exact="this.ship.orders.count" counter="$gtToi2">
            <do_if value="this.ship.orders.{$gtToi2}.id == 'DockAndTrain'">
              <set_value name="$gtSkipTrainingDispatch" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$needsTrainingDispatch and not $gtSkipTrainingDispatch">
          <set_value name="$dispatchReady" exact="false"/>
          <do_if value="not this.$mk1_lastTrainingSignalAt? or (player.age - this.$mk1_lastTrainingSignalAt) ge 60s">
            <set_value name="$dispatchReady" exact="true"/>
          </do_if>
          <do_if value="$dispatchReady">
            <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $RequiredLevel = $blockedLevel
            ]"/>
            <set_value name="this.$mk1_lastTrainingSignalAt" exact="player.age"/>
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Re-requested training dispatch for blocked pilot (level ' + $blockedLevel + ')'" chance="this.$debugchance"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 1: Validate station still exists and is player-owned      -->
      <!-- ============================================================== -->
      <do_if value="not this.$homeStation.exists">
        <do_if value="this.$notifications ge 1">
          <show_notification text="'GalaxyTrader MK1: ' + {77000, 30202}.['(destroyed)']" timeout="10s"/>
        </do_if>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ABORT â€” home station destroyed'" chance="100"/>
        <!-- Unregister from supply registry (station may still be in table if it was just destroyed) -->
        <do_if value="global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{this.$homeStation}? and global.$GT_MK1SuppliedStations.{this.$homeStation} == this.ship">
          <remove_value name="global.$GT_MK1SuppliedStations.{this.$homeStation}"/>
        </do_if>
        <set_command_action commandaction="commandaction.standingby"/>
        <return/>
      </do_if>

      <do_if value="not this.$homeStation.isplayerowned">
        <do_if value="this.$notifications ge 1">
          <show_notification text="'GalaxyTrader MK1: ' + {77000, 30203}.[this.$homeStation.knownname]" timeout="10s"/>
        </do_if>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ABORT â€” station no longer player-owned'" chance="100"/>
        <!-- Unregister from supply registry -->
        <do_if value="global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{this.$homeStation}? and global.$GT_MK1SuppliedStations.{this.$homeStation} == this.ship">
          <remove_value name="global.$GT_MK1SuppliedStations.{this.$homeStation}"/>
        </do_if>
        <set_command_action commandaction="commandaction.standingby"/>
        <return/>
      </do_if>

      <!-- Refresh params from effective MK1 order source:
           own defaultorder first, commander MK1 order for subordinates otherwise. -->
      <set_value name="$effectiveMK1Order" exact="null"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyTraderMK1'">
        <set_value name="$effectiveMK1Order" exact="this.ship.defaultorder"/>
      </do_if>
      <do_elseif value="this.ship.commander.exists and this.ship.commander != this.ship and this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist' and this.ship.commander.defaultorder?">
        <!-- Vanilla-aligned subordinate inheritance:
             Assist references commander's defaultorder; if that default is Assist, use its baseorder. -->
        <set_value name="$mk1InheritedOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$mk1InheritedOrder.id == 'Assist' and $mk1InheritedOrder.$baseorder?">
          <set_value name="$mk1InheritedOrder" exact="$mk1InheritedOrder.$baseorder"/>
        </do_if>
        <do_if value="$mk1InheritedOrder? and $mk1InheritedOrder.id == 'GalaxyTraderMK1'">
          <set_value name="$effectiveMK1Order" exact="$mk1InheritedOrder"/>
        </do_if>
      </do_elseif>
      <do_if value="$effectiveMK1Order? and $effectiveMK1Order != null">
        <do_if value="$effectiveMK1Order.$homeStation? and $effectiveMK1Order.$homeStation.exists and $effectiveMK1Order.$homeStation.isclass.station">
          <set_value name="this.$homeStation" exact="$effectiveMK1Order.$homeStation"/>
        </do_if>
        <set_value name="this.$maxsell" exact="$effectiveMK1Order.$maxsell"/>
        <set_value name="this.$ignoretraderules" exact="$effectiveMK1Order.$ignoretraderules"/>
        <set_value name="this.$allowillegal" exact="$effectiveMK1Order.$allowillegal"/>
        <set_value name="this.$enforceRouteIllegalLegality" exact="if $effectiveMK1Order.$enforceRouteIllegalLegality? then $effectiveMK1Order.$enforceRouteIllegalLegality else false"/>
        <set_value name="this.$warebasket" exact="$effectiveMK1Order.$warebasket"/>
        <set_value name="this.$selltarget" exact="$effectiveMK1Order.$selltarget"/>
        <set_value name="this.$sellselectionmode" exact="if $effectiveMK1Order.$sellselectionmode? then $effectiveMK1Order.$sellselectionmode else 2"/>
        <set_value name="this.$buytarget" exact="$effectiveMK1Order.$buytarget"/>
        <set_value name="this.$backtrackTolerance" exact="$effectiveMK1Order.$backtrackTolerance"/>
        <set_value name="this.$allowmultitrade" exact="if $effectiveMK1Order.$allowmultitrade? then $effectiveMK1Order.$allowmultitrade else true"/>
        <set_value name="this.$logbookentries" exact="$effectiveMK1Order.$logbookentries"/>
        <set_value name="this.$notifications" exact="$effectiveMK1Order.$notifications"/>
        <set_value name="this.$fleetcoordination" exact="$effectiveMK1Order.$fleetcoordination"/>
        <set_value name="this.$debuglevel" exact="$effectiveMK1Order.$debuglevel"/>
        <set_value name="this.$debugchance" exact="if this.$debuglevel ge 1 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
        <set_value name="this.$supply" exact="$effectiveMK1Order.$supply"/>
        <set_value name="this.$minstorage" exact="$effectiveMK1Order.$minstorage"/>
        <set_value name="this.$minsellstorage" exact="if $effectiveMK1Order.$minsellstorage? then [0, [$effectiveMK1Order.$minsellstorage, 100].min].max else 0"/>
        <set_value name="this.$pricerange" exact="90"/>
        <do_if value="$effectiveMK1Order.$pricerange?">
          <do_if value="$effectiveMK1Order.$pricerange ge 0 and $effectiveMK1Order.$pricerange le 200">
            <set_value name="this.$pricerange" exact="$effectiveMK1Order.$pricerange"/>
          </do_if>
          <do_elseif value="$effectiveMK1Order.$pricerange ge -100 and $effectiveMK1Order.$pricerange lt 0">
            <set_value name="this.$pricerange" exact="$effectiveMK1Order.$pricerange + 100"/>
          </do_elseif>
        </do_if>
        <set_value name="this.$pricerange" exact="[this.$pricerange, 0].max"/>
        <set_value name="this.$pricerange" exact="[this.$pricerange, 200].min"/>
        <set_value name="this.$pricerangeNorm" exact="(this.$pricerange - 100) / 100"/>
        <set_value name="this.$returnhome" exact="if $effectiveMK1Order.$returnhome? then $effectiveMK1Order.$returnhome else false"/>

        <!-- Update supply station registry if supply toggled -->
        <do_if value="not global.$GT_MK1SuppliedStations?">
          <set_value name="global.$GT_MK1SuppliedStations" exact="table[]"/>
        </do_if>
        <do_if value="this.$supply">
          <set_value name="global.$GT_MK1SuppliedStations.{this.$homeStation}" exact="this.ship"/>
        </do_if>
        <do_elseif value="global.$GT_MK1SuppliedStations.{this.$homeStation}? and global.$GT_MK1SuppliedStations.{this.$homeStation} == this.ship">
          <remove_value name="global.$GT_MK1SuppliedStations.{this.$homeStation}"/>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Unregistered station ' + this.$homeStation.knownname + ' (supply toggled off)'" chance="this.$debugchance"/>
        </do_elseif>
      </do_if>
      <!-- Re-apply pilot-level cap each cycle so level-up/down updates effective sell range immediately. -->
      <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
      <do_if value="not $useVanillaXPOnly">
        <set_value name="$mk1PilotLevelCap" exact="1"/>
        <run_script name="'lib.gt.pathfinding'" result="$mk1PilotLevelCap">
          <param name="mode" value="'effective_pilot_level'"/>
          <param name="ship" value="this.ship"/>
          <param name="includeCommander" value="false"/>
        </run_script>
        <run_script name="'lib.gt.pathfinding'" result="$mk1PilotMaxDistance">
          <param name="mode" value="'pilot_max_jumps'"/>
          <param name="pilotSkill" value="$mk1PilotLevelCap"/>
        </run_script>
        <do_if value="$mk1PilotMaxDistance == null">
          <set_value name="$mk1PilotMaxDistance" exact="1"/>
        </do_if>
        <set_value name="this.$maxsell" exact="[this.$maxsell, $mk1PilotMaxDistance].min"/>
      </do_if>

      <!-- Hot-reload backfill: init does not re-run on script reload; default 90 = slightly below average (norm -0.1). -->
      <do_if value="not this.$pricerangeNorm?">
        <set_value name="this.$pricerange" exact="if this.$pricerange? then this.$pricerange else 90"/>
        <set_value name="this.$pricerange" exact="[this.$pricerange, 0].max"/>
        <set_value name="this.$pricerange" exact="[this.$pricerange, 200].min"/>
        <set_value name="this.$pricerangeNorm" exact="(this.$pricerange - 100) / 100"/>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 1b: Anchor loop at home dock before new search cycle      -->
      <!-- ============================================================== -->
      <!-- MK1 can be restarted by order transitions (e.g. after queued trades).
           Enforce a home-docked start so new cycles do not begin from remote stations. -->
      <set_value name="$mk1LoopDockedHome" exact="(this.ship.dock and this.ship.dock.container == this.$homeStation) or (this.ship.parkedat and ((this.ship.parkedat == this.$homeStation) or this.ship.parkedat.hascontext.{this.$homeStation}))"/>
      <do_if value="not this.$returnhome and this.$mk1_returnhomeReleased? and this.$mk1_returnhomeReleased">
        <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
          <remove_value name="global.$GT_MK1ReturnHomeReleased.{this.ship}"/>
        </do_if>
        <remove_value name="this.$mk1_returnhomeReleased"/>
      </do_if>
      <do_if value="this.$returnhome and (not this.$mk1_returnhomeReleased? or not this.$mk1_returnhomeReleased) and not $mk1LoopDockedHome and this.ship.orders.count == 0 and this.ship.cargo.count == 0">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Loop start away from home â€” docking at home before maintenance/search'" chance="this.$debugchance"/>
        <resume label="return_home_and_dock"/>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 1c: Home trading dock required for load/supply legs       -->
      <!-- ============================================================== -->
      <run_script name="'lib.gt.dockcheck'" result="$mk1HomeDockGate">
        <param name="ship" value="this.ship"/>
        <param name="station" value="this.$homeStation"/>
        <param name="purpose" value="'trade'"/>
        <param name="allowPlayerOnly" value="true"/>
      </run_script>
      <set_value name="this.$mk1_homeCanDock" exact="$mk1HomeDockGate.$CanDock"/>
      <do_if value="not this.$mk1_homeCanDock">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': no operational trading dock at home ' + this.$homeStation.knownname + ' â€” skipping supply/export until dock available (size=' + this.ship.docksize + ')'" chance="this.$debugchance"/>
        <set_command_action commandaction="commandaction.orderfailed"/>
        <wait exact="this.$waitTimeNoTrades"/>
        <resume label="main_loop"/>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 2: Maintenance check (shared GT system)                   -->
      <!-- ============================================================== -->
      <signal_objects object="player.galaxy" param="'GT_Check_Maintenance'" param2="table[$Ship = this.ship]"/>
      <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield"/>

      <!-- Leftover cargo must be cleared before supply or export search â€” otherwise cancelled
           load/sell pairs leave cargo aboard and STEP 2c/4+ queue fresh buy/sell orders. -->
      <!-- ============================================================== -->
      <!-- STEP 3: Handle leftover cargo from interrupted trades          -->
      <!-- ============================================================== -->
      <do_while value="this.ship.cargo.count gt 0">
        <set_command_action commandaction="commandaction.executingtrade"/>
        <!-- Mirror GT naming-state behavior: mark ship as being in clearance mode while disposing leftover cargo. -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
          <set_value name="global.$GT_Ships.{this.ship}.$CargoDisposal" exact="true"/>
        </do_if>
        <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
            $Ship = this.ship,
            $pilot = this.ship.pilot,
            $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
            $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
            $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
            $nameType = 'trader'
          ]"/>
        </do_if>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Leftover cargo detected â€” selling at nearest buyer'" chance="this.$debugchance"/>

        <!-- Build sector list for leftover cargo clearance -->
        <create_list name="$clearSectors"/>
        <append_to_list name="$clearSectors" exact="this.ship.sector"/>
        <do_if value="this.$maxsell gt 0">
          <find_sector name="$clearNearbySectors" space="player.galaxy" multiple="true">
            <match_gate_distance object="this.ship.sector" min="0" max="this.$maxsell"/>
          </find_sector>
          <do_if value="$clearNearbySectors? and $clearNearbySectors.count gt 0">
            <do_all exact="$clearNearbySectors.count" counter="$csi">
              <do_if value="$clearNearbySectors.{$csi} != this.ship.sector">
                <append_to_list name="$clearSectors" exact="$clearNearbySectors.{$csi}"/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>

        <!-- For each ware in cargo, find nearest NPC buyer and sell -->
        <set_value name="$cargoWares" exact="this.ship.cargo.list"/>
        <do_all exact="$cargoWares.count" counter="$mk1ClrWareIdx">
          <set_value name="$cWare" exact="$cargoWares.{$mk1ClrWareIdx}"/>
          <set_value name="$cAmount" exact="this.ship.cargo.{$cWare}.count"/>
          <do_if value="$cAmount gt 0">
            <!-- Find nearest buyer for this ware across sectors in range -->
            <set_value name="$clearBuyOffer" exact="null"/>
            <do_all exact="$clearSectors.count" counter="$csi">
              <find_buy_offer wares="$cWare" space="$clearSectors.{$csi}" tradepartner="this.ship" result="$secClearOffer">
                <match_buyer tradesknownto="this.ship.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="this.ship" relation="dock" comparison="ge"/>
                  <match_relation_to faction="this.ship.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <amount min="1"/>
              </find_buy_offer>
              <do_if value="$secClearOffer.available">
                <do_if value="this.$ignoretraderules or $secClearOffer.cantradewith.{this.$homeStation}">
                  <set_value name="$clearBuyOffer" exact="$secClearOffer"/>
                  <break/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$clearBuyOffer? and $clearBuyOffer != null and $clearBuyOffer.available">
              <set_value name="$clearAmount" exact="[$cAmount, $clearBuyOffer.amount].min"/>
              <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}?">
                <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
                <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
                  <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
                </do_if>
              </do_if>
              <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
                <remove_value name="global.$GT_MK1DockedSince.{this.ship}"/>
              </do_if>
              <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
                <remove_value name="global.$GT_MK1ReturnHomeReleased.{this.ship}"/>
              </do_if>
              <remove_value name="this.$mk1_dockedSince"/>
              <remove_value name="this.$mk1_returnhomeReleased"/>
              <create_trade_order object="this.ship" tradeoffer="$clearBuyOffer" amount="$clearAmount" immediate="true" internal="false"/>
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Clearing leftover ' + $clearAmount + ' ' + $cWare.name + ' at ' + $clearBuyOffer.owner.knownname" chance="this.$debugchance"/>
            </do_if>
          </do_if>
        </do_all>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield after clearance ware scan"/>

        <!-- Wait for trade orders to execute -->
        <do_if value="this.ship.orders.count gt 0">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Waiting for leftover cargo clearance...'" chance="this.$debugchance"/>
          <wait>
            <interrupt>
              <conditions>
                <event_object_order_ready object="this.ship"/>
              </conditions>
            </interrupt>
          </wait>
        </do_if>
        <!-- Orders finished or cancelled but cargo remains â€” retry clearance; do not export/supply. -->
        <do_if value="this.ship.cargo.count gt 0">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Leftover cargo remains after clearance attempt â€” retrying (skip export/supply until empty)'" chance="this.$debugchance"/>
          <wait exact="10s" comment="Backoff before retrying clearance buyer search"/>
        </do_if>
      </do_while>

      <!-- Clear clearance flag as soon as cargo is empty so ship state/name reverts immediately. -->
      <do_if value="this.ship.cargo.count == 0 and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
        <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
        <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
            $Ship = this.ship,
            $pilot = this.ship.pilot,
            $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
            $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
            $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
            $nameType = 'trader'
          ]"/>
        </do_if>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 2b: Supply mode â€” affordability + threshold check         -->
      <!-- ============================================================== -->
      <do_if value="this.ship.cargo.count == 0">
      <set_value name="this.$supplyPriority" exact="false"/>
      <set_value name="this.$supplySkipped" exact="false"/>

      <do_if value="this.$supply">
        <!-- Check if station can afford at least 1 unit of any resource -->
        <set_value name="$stationResources" exact="this.$homeStation.resources.list"/>
        <set_value name="$canAffordAny" exact="false"/>

        <do_if value="$stationResources.count gt 0">
          <do_all exact="$stationResources.count" counter="$ri">
            <set_value name="$res" exact="$stationResources.{$ri}"/>
            <do_if value="$res.averageprice? and this.$homeStation.money ge $res.averageprice">
              <set_value name="$canAffordAny" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="not $canAffordAny">
          <!-- Station can't afford any resources â€” skip supply entirely -->
          <set_value name="this.$supplySkipped" exact="true"/>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply SKIPPED â€” station cannot afford any resources (balance: ' + this.$homeStation.money + ')'" chance="this.$debugchance"/>
        </do_if>
        <do_else>
          <!-- Check per-ware: is ANY resource below minstorage threshold? -->
          <do_all exact="$stationResources.count" counter="$ri">
            <set_value name="$res" exact="$stationResources.{$ri}"/>
            <set_value name="$resCurrent" exact="this.$homeStation.cargo.{$res}.count"/>
            <set_value name="$resTarget" exact="this.$homeStation.cargo.{$res}.target"/>
            <do_if value="$resTarget gt 0">
              <set_value name="$resPercent" exact="($resCurrent * 100) / $resTarget"/>
              <do_if value="$resPercent lt this.$minstorage">
                <set_value name="this.$supplyPriority" exact="true"/>
                <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply PRIORITY â€” ' + $res.name + ' at ' + $resPercent + '% (threshold: ' + this.$minstorage + '%)'" chance="this.$debugchance"/>
                <break/>
              </do_if>
            </do_if>
          </do_all>
        </do_else>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 2c: Priority supply phase (runs before sell when urgent)  -->
      <!-- ============================================================== -->
      <do_if value="this.$supplyPriority and this.ship.cargo.count == 0">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': === SUPPLY PHASE START (priority) ==='" chance="this.$debugchance"/>
        <set_command_action commandaction="commandaction.searchingtrades"/>

        <!-- Build list of under-threshold resources -->
        <create_list name="$supplyWares"/>
        <set_value name="$stationResources" exact="this.$homeStation.resources.list"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Station resources count: ' + $stationResources.count + ', station money: ' + this.$homeStation.money" chance="this.$debugchance"/>
        <do_all exact="$stationResources.count" counter="$ri">
          <set_value name="$res" exact="$stationResources.{$ri}"/>
          <set_value name="$resTarget" exact="this.$homeStation.cargo.{$res}.target"/>
          <do_if value="$resTarget gt 0">
            <set_value name="$resCurrent" exact="this.$homeStation.cargo.{$res}.count"/>
            <set_value name="$resPercent" exact="($resCurrent * 100) / $resTarget"/>
            <do_if value="$resPercent lt this.$minstorage and this.ship.cargo.{$res}.max gt 0">
              <append_to_list name="$supplyWares" exact="$res"/>
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ':   Need ' + $res.name + ': ' + $resCurrent + '/' + $resTarget + ' (' + $resPercent + '%)'" chance="this.$debugchance"/>
            </do_if>
          </do_if>
        </do_all>

        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply wares to find: ' + $supplyWares.count" chance="this.$debugchance"/>
        <!-- Small stagger to reduce same-tick herd selection across many subordinates. -->
        <wait min="200ms" max="900ms"/>

        <!-- Shared pipeline: pathfinding + live search + trade match -->
        <run_script name="'lib.gt.pathfinding'" result="$supplySpaces">
          <param name="ship" value="this.ship"/>
          <param name="homeSector" value="this.$homeStation.sector"/>
          <param name="maxDistance" value="this.$maxsell"/>
        </run_script>
        <set_value name="$mk1ResolvedBuySpaces" exact="[]"/>
        <do_if value="$supplySpaces?">
          <do_if value="$supplySpaces.$BuySpaces?">
            <set_value name="$mk1ResolvedBuySpaces" exact="@$supplySpaces.$BuySpaces"/>
          </do_if>
        </do_if>

        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Searching ' + $mk1ResolvedBuySpaces.count + ' sectors (maxsell=' + this.$maxsell + ')'" chance="this.$debugchance"/>

        <!-- MK1 order price range: UI offset 0-200 (100 = neutral) maps to normalized -1.0..+1.0 -->
        <set_value name="$mk1BuyPriceMin" exact="this.$pricerangeNorm"/>
        <set_value name="$mk1SellPriceMax" exact="0 - this.$pricerangeNorm"/>
        <run_script name="'lib.gt.live.search'" result="$supplyLiveResult">
          <param name="ship" value="this.ship"/>
          <param name="searchMode" value="'buy_only'"/>
          <param name="buySpaces" value="$mk1ResolvedBuySpaces"/>
          <param name="sellSpaces" value="[]"/>
          <param name="homeSector" value="this.$homeStation.sector"/>
          <param name="maxDistance" value="this.$maxsell"/>
          <param name="wareBasket" value="$supplyWares"/>
          <param name="allowIllegal" value="this.$allowillegal"/>
          <param name="ownerFilter" value="'npc_only'"/>
          <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
          <param name="ignoreMK1Supply" value="false"/>
          <param name="sellPriceMax" value="$mk1SellPriceMax"/>
          <param name="buyPriceMin" value="$mk1BuyPriceMin"/>
          <param name="debugchance" value="this.$debugchance"/>
        </run_script>
        <set_value name="this.$mk1_supplyLiveResult" exact="$supplyLiveResult"/>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield after supply live search"/>
        <set_value name="$supplyLiveResult" exact="this.$mk1_supplyLiveResult"/>

        <!-- Safety filter: supply mode must not buy from the same home station.
             This prevents degenerate self-trades (buy+deliver on identical station). -->
        <create_list name="$supplySellOffersFiltered"/>
        <do_if value="$supplyLiveResult.$SellOffers? and $supplyLiveResult.$SellOffers.count gt 0">
          <do_all exact="$supplyLiveResult.$SellOffers.count" counter="$ssfi">
            <set_value name="$candSellOffer" exact="$supplyLiveResult.$SellOffers.{$ssfi}"/>
            <do_if value="$candSellOffer? and $candSellOffer.available and $candSellOffer.owner? and $candSellOffer.owner.exists and $candSellOffer.owner != this.$homeStation">
              <append_to_list name="$supplySellOffersFiltered" exact="$candSellOffer"/>
            </do_if>
            <do_elseif value="$candSellOffer? and $candSellOffer.owner? and $candSellOffer.owner == this.$homeStation">
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply filter dropped self-station seller offer for ' + $candSellOffer.ware.name + ' at ' + this.$homeStation.knownname" chance="this.$debugchance"/>
            </do_elseif>
          </do_all>
        </do_if>

        <!-- Home-station buy offers: mirror MK2/vanilla (tradepartner + offeramount.{ship}).
             Raw .amount can be 0 while desiredamount/offeramount reflect real station demand
             (e.g. player-faction-only rules, internal player economy). -->
        <create_list name="$stationBuyOffers"/>
        <do_all exact="$supplyWares.count" counter="$swi">
          <set_value name="$supplyWare" exact="$supplyWares.{$swi}"/>
          <set_value name="$stationBuyOffer" exact="null"/>
          <run_script name="'lib.gt.tradematch'" result="$mk1HomeBuyOfferResolve">
            <param name="mode" value="'mk2_player_offer'"/>
            <param name="operation" value="'find'"/>
            <param name="lineType" value="'dest'"/>
            <param name="ship" value="this.ship"/>
            <param name="station" value="this.$homeStation"/>
            <param name="wareText" value="$supplyWare"/>
            <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
          </run_script>
          <set_value name="$stationBuyOffer" exact="$mk1HomeBuyOfferResolve.$Offer"/>
          <set_value name="$stationBuyOfferAmount" exact="0"/>
          <do_if value="$stationBuyOffer? and $stationBuyOffer.exists and $stationBuyOffer.available">
            <set_value name="$stationBuyOfferAmount" exact="@$stationBuyOffer.offeramount.{this.ship}"/>
            <do_if value="$stationBuyOfferAmount == null">
              <set_value name="$stationBuyOfferAmount" exact="0"/>
            </do_if>
          </do_if>
          <do_if value="$stationBuyOffer? and $stationBuyOffer.exists and $stationBuyOffer.available and $stationBuyOfferAmount gt 0">
            <append_to_list name="$stationBuyOffers" exact="$stationBuyOffer"/>
          </do_if>
          <do_elseif value="this.$debuglevel ge 1">
            <set_value name="$mk1HomeBuyRawAmount" exact="if $stationBuyOffer? and $stationBuyOffer.exists and $stationBuyOffer.amount? then $stationBuyOffer.amount else 0"/>
            <set_value name="$mk1HomeBuyDesired" exact="if $stationBuyOffer? and $stationBuyOffer.exists and $stationBuyOffer.desiredamount? then $stationBuyOffer.desiredamount else 0"/>
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply home buy offer rejected for ' + $supplyWare.name + ' at ' + this.$homeStation.knownname + ' (available=' + (if $stationBuyOffer? and $stationBuyOffer.exists and $stationBuyOffer.available then 1 else 0) + ' offeramount=' + $stationBuyOfferAmount + ' amount=' + $mk1HomeBuyRawAmount + ' desired=' + $mk1HomeBuyDesired + ' ignoreRules=' + this.$ignoretraderules + ')'" chance="this.$debugchance"/>
          </do_elseif>
        </do_all>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply home buy offers resolved=' + $stationBuyOffers.count + '/' + $supplyWares.count" chance="this.$debugchance"/>
        </do_if>

        <run_script name="'lib.gt.tradematch'" result="$supplyMatchResult">
          <param name="ship" value="this.ship"/>
          <param name="sellOffers" value="$supplySellOffersFiltered"/>
          <param name="buyOffers" value="$stationBuyOffers"/>
          <param name="homeSector" value="this.$homeStation.sector"/>
          <param name="maxDistance" value="this.$maxsell"/>
          <param name="scoreMode" value="'supply'"/>
          <param name="distancePenalty" value="0.1"/>
          <param name="allowIllegal" value="this.$allowillegal"/>
          <param name="enforceRouteIllegalLegality" value="this.$enforceRouteIllegalLegality"/>
        </run_script>
        <set_value name="this.$mk1_supplyMatchResult" exact="$supplyMatchResult"/>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after shared tradematch call"/>
        <set_value name="$supplyMatchResult" exact="this.$mk1_supplyMatchResult"/>

        <set_value name="$bestSupplyTrade" exact="null"/>
        <set_value name="$bestSupplyScore" exact="-1"/>
        <set_value name="this.$mk1_bestSupplyScore" exact="-1"/>
        <remove_value name="this.$mk1_bestSupplyTrade"/>
        <set_value name="$availableSupplyTradeWaresCount" exact="0"/>
        <do_if value="$supplyMatchResult.$Found and $supplyMatchResult.$TradeList? and $supplyMatchResult.$TradeList.count gt 0">
          <run_script name="'lib.gt.tradematch'" result="$mk1DistinctWaresResult">
            <param name="mode" value="'count_distinct_wares'"/>
            <param name="tradeListInput" value="$supplyMatchResult.$TradeList"/>
          </run_script>
          <set_value name="this.$mk1_distinctWaresCount" exact="if $mk1DistinctWaresResult.$DistinctCount? then $mk1DistinctWaresResult.$DistinctCount else 0"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after distinct-ware helper call"/>
          <set_value name="$availableSupplyTradeWaresCount" exact="this.$mk1_distinctWaresCount"/>

          <do_if value="this.$debuglevel ge 1">
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': supply candidate wares available now=' + $availableSupplyTradeWaresCount" chance="this.$debugchance"/>
          </do_if>

          <do_all exact="$supplyMatchResult.$TradeList.count" counter="$smti">
            <set_value name="$candidateCoreTrade" exact="$supplyMatchResult.$TradeList.{$smti}"/>
            <set_value name="$candidateAmount" exact="$candidateCoreTrade.$Amount"/>

            <!-- Enforce home-station trade rules when ignoretraderules=false (mirror of sell phase).
                 $SellOffer = NPC seller offer, $BuyOffer = home-station buy offer (see remap below).
                 Skip NPC sources the station's rules disallow so supply respects station trade rules. -->
            <do_if value="not this.$ignoretraderules">
              <do_if value="$candidateCoreTrade.$SellOffer == null or not $candidateCoreTrade.$SellOffer.exists or $candidateCoreTrade.$BuyOffer == null or not $candidateCoreTrade.$BuyOffer.exists">
                <continue/>
              </do_if>
              <do_if value="not $candidateCoreTrade.$SellOffer.cantradewith.{this.$homeStation}">
                <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply trade-rule reject: ' + $candidateCoreTrade.$SellOffer.owner.knownname + ' cannot trade with home ' + this.$homeStation.knownname" chance="this.$debugchance"/>
                <continue/>
              </do_if>
              <do_if value="not $candidateCoreTrade.$BuyOffer.cantradewith.{$candidateCoreTrade.$SellOffer.owner}">
                <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply trade-rule reject: home ' + this.$homeStation.knownname + ' buy offer disallows seller ' + $candidateCoreTrade.$SellOffer.owner.knownname" chance="this.$debugchance"/>
                <continue/>
              </do_if>
            </do_if>

            <set_value name="$supCandSellerStation" exact="if $candidateCoreTrade.$SellOffer? and $candidateCoreTrade.$SellOffer.owner? and $candidateCoreTrade.$SellOffer.owner.exists then $candidateCoreTrade.$SellOffer.owner else null"/>
            <do_if value="$supCandSellerStation? and $supCandSellerStation.exists">
              <run_script name="'lib.gt.dockcheck'" result="$mk1SupCandDockCheck">
                <param name="ship" value="this.ship"/>
                <param name="station" value="$supCandSellerStation"/>
                <param name="purpose" value="'trade'"/>
              </run_script>
              <do_if value="not $mk1SupCandDockCheck.$CanDock">
                <continue/>
              </do_if>
            </do_if>

            <!-- Soft buytarget cap: don't force full cargo in supply mode -->
            <set_value name="$candidateTargetAmount" exact="$candidateAmount"/>
            <do_if value="$candidateCoreTrade.$Ware.volume gt 0 and this.$buytarget lt 100">
              <set_value name="$candidateTargetAmount" exact="[1, ((this.ship.cargo.capacity.all * this.$buytarget / 100) / $candidateCoreTrade.$Ware.volume)i].max"/>
            </do_if>
            <set_value name="$candidateAmount" exact="[$candidateAmount, $candidateTargetAmount].min"/>

            <do_if value="$candidateAmount gt 0">
              <!-- Use vanilla reservation state for supply fairness (no custom tracking tables). -->
              <set_value name="$reservedCount" exact="0"/>
              <set_value name="$alreadyReservedByThisShip" exact="false"/>
              <set_value name="$incomingReservedAmount" exact="0"/>
              <set_value name="$selfIncomingReservedAmount" exact="0"/>
              <get_ware_reservation object="this.$homeStation" ware="$candidateCoreTrade.$Ware" type="sell" virtual="false" result="$incomingReservedAmount"/>
              <get_ware_reservation object="this.$homeStation" ware="$candidateCoreTrade.$Ware" type="sell" reserver="this.ship" virtual="false" result="$selfIncomingReservedAmount"/>
              <do_if value="$selfIncomingReservedAmount gt 0">
                <set_value name="$alreadyReservedByThisShip" exact="true"/>
              </do_if>

              <!-- Dynamic slot count per ware:
                   max ships ~= ceil(remaining need / ship chunk). -->
              <set_value name="$needAmount" exact="0"/>
              <set_value name="$effectiveNeedAmount" exact="0"/>
              <set_value name="$targetAmount" exact="this.$homeStation.cargo.{$candidateCoreTrade.$Ware}.target"/>
              <set_value name="$currentAmount" exact="this.$homeStation.cargo.{$candidateCoreTrade.$Ware}.count"/>
              <do_if value="$targetAmount gt $currentAmount">
                <set_value name="$needAmount" exact="$targetAmount - $currentAmount"/>
              </do_if>
              <set_value name="$effectiveNeedAmount" exact="[$needAmount - $incomingReservedAmount, 0].max"/>
              <set_value name="$shipChunkAmount" exact="this.ship.cargo.{$candidateCoreTrade.$Ware}.max"/>
              <do_if value="this.$buytarget lt 100">
                <set_value name="$shipChunkAmount" exact="[1, ($shipChunkAmount * this.$buytarget / 100)i].max"/>
              </do_if>
              <do_if value="$shipChunkAmount lt 1">
                <set_value name="$shipChunkAmount" exact="1"/>
              </do_if>
              <set_value name="$reservedCount" exact="(($incomingReservedAmount + $shipChunkAmount - 1) / $shipChunkAmount)i"/>

              <run_script name="'lib.gt.tradematch'" result="$mk1FairnessResult">
                <param name="mode" value="'ware_fairness'"/>
                <param name="rawNeedAmount" value="$needAmount"/>
                <param name="incomingReservedAmount" value="$incomingReservedAmount"/>
                <param name="shipChunkAmount" value="$shipChunkAmount"/>
                <param name="availableTradeWaresCount" value="$availableSupplyTradeWaresCount"/>
                <param name="reservedCount" value="$reservedCount"/>
                <param name="alreadyReservedByThisShip" value="$alreadyReservedByThisShip"/>
                <param name="fairnessCap" value="2"/>
              </run_script>
              <set_value name="$effectiveNeedAmount" exact="$mk1FairnessResult.$EffectiveNeedAmount"/>
              <set_value name="$maxShipsForWare" exact="$mk1FairnessResult.$MaxShipsForWare"/>
              <set_value name="$reservationAllowsTrade" exact="$mk1FairnessResult.$ReservationAllowsTrade"/>
              <set_value name="$candidateAmount" exact="[$candidateAmount, $effectiveNeedAmount].min"/>

              <do_if value="$candidateAmount gt 0 and $candidateCoreTrade.$Score gt this.$mk1_bestSupplyScore">
                <set_value name="this.$mk1_bestSupplyScore" exact="$candidateCoreTrade.$Score"/>
                <set_value name="$bestSupplyScore" exact="$candidateCoreTrade.$Score"/>
                <set_value name="$bestSupplyTrade" exact="table[
                  $Ware = $candidateCoreTrade.$Ware,
                  $SellOffer = $candidateCoreTrade.$BuyOffer,
                  $BuyOffer = $candidateCoreTrade.$SellOffer,
                  $Amount = $candidateAmount,
                  $BuyStation = if $candidateCoreTrade.$BuyStation? and $candidateCoreTrade.$BuyStation.exists then $candidateCoreTrade.$BuyStation else (if $candidateCoreTrade.$BuyOffer? and $candidateCoreTrade.$BuyOffer.owner? and $candidateCoreTrade.$BuyOffer.owner.exists then $candidateCoreTrade.$BuyOffer.owner else null),
                  $SellStation = if $candidateCoreTrade.$SellStation? and $candidateCoreTrade.$SellStation.exists then $candidateCoreTrade.$SellStation else (if $candidateCoreTrade.$SellOffer? and $candidateCoreTrade.$SellOffer.owner? and $candidateCoreTrade.$SellOffer.owner.exists then $candidateCoreTrade.$SellOffer.owner else null),
                  $SellerStation = if $candidateCoreTrade.$BuyStation? and $candidateCoreTrade.$BuyStation.exists then $candidateCoreTrade.$BuyStation else (if $candidateCoreTrade.$BuyOffer? and $candidateCoreTrade.$BuyOffer.owner? and $candidateCoreTrade.$BuyOffer.owner.exists then $candidateCoreTrade.$BuyOffer.owner else null),
                  $BuyPrice = if $candidateCoreTrade.$BuyPrice? then $candidateCoreTrade.$BuyPrice else (if $candidateCoreTrade.$BuyOffer? and $candidateCoreTrade.$BuyOffer.unitprice? then $candidateCoreTrade.$BuyOffer.unitprice else 0),
                  $SellPrice = if $candidateCoreTrade.$SellPrice? then $candidateCoreTrade.$SellPrice else (if $candidateCoreTrade.$SellOffer? and $candidateCoreTrade.$SellOffer.unitprice? then $candidateCoreTrade.$SellOffer.unitprice else 0),
                  $Distance = $candidateCoreTrade.$Distance,
                  $ReservedCount = $reservedCount,
                  $MaxShipsForWare = $maxShipsForWare,
                  $IncomingReservedAmount = $incomingReservedAmount,
                  $NeedAmount = $needAmount,
                  $EffectiveNeedAmount = $effectiveNeedAmount
                ]"/>
                <set_value name="this.$mk1_bestSupplyTrade" exact="$bestSupplyTrade"/>
              </do_if>
            </do_if>
            <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield after supply candidate evaluation"/>
          </do_all>
        </do_if>

        <do_if value="this.$mk1_bestSupplyTrade?">
          <set_value name="$bestSupplyTrade" exact="this.$mk1_bestSupplyTrade"/>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply trade found: buy ' + $bestSupplyTrade.$Amount + ' ' + $bestSupplyTrade.$Ware.name + ' from ' + $bestSupplyTrade.$SellerStation.knownname + ' (dist: ' + $bestSupplyTrade.$Distance + ', slots: ' + $bestSupplyTrade.$ReservedCount + '/' + $bestSupplyTrade.$MaxShipsForWare + ', incoming=' + $bestSupplyTrade.$IncomingReservedAmount + ', need=' + $bestSupplyTrade.$NeedAmount + ', effectiveNeed=' + $bestSupplyTrade.$EffectiveNeedAmount + ')'" chance="this.$debugchance"/>

          <!-- Create BOTH trade orders upfront so reservations are visible immediately.
               Pattern matches vanilla order.trade.routine: "create_trade_order adds the reservation automatically".
               The engine executes queued orders in sequence (buy first, then deliver). -->
          <set_command_action commandaction="commandaction.flying"/>
          <set_value name="this.$mk1_supplyOrdersCreated" exact="0"/>

          <do_if value="$bestSupplyTrade.$BuyOffer? and @$bestSupplyTrade.$BuyOffer.exists and $bestSupplyTrade.$SellOffer? and @$bestSupplyTrade.$SellOffer.exists and $bestSupplyTrade.$SellOffer.available and $bestSupplyTrade.$BuyOffer.available">
            <set_value name="$supOfferAmount" exact="@$bestSupplyTrade.$BuyOffer.offeramount.{this.ship}"/>
            <do_if value="$supOfferAmount == null">
              <set_value name="$supOfferAmount" exact="0"/>
            </do_if>
            <set_value name="$supBuyAmount" exact="[$bestSupplyTrade.$Amount, $supOfferAmount].min"/>
            <do_if value="$bestSupplyTrade.$BuyOffer.unitprice gt 0">
              <set_value name="$supAffordableAmount" exact="(this.$homeStation.money / $bestSupplyTrade.$BuyOffer.unitprice)i"/>
              <set_value name="$supBuyAmount" exact="[$supBuyAmount, $supAffordableAmount].min"/>
            </do_if>
            <do_if value="$supBuyAmount gt 0">
              <set_value name="this.$mk1_supRouteOk" exact="true"/>
              <do_if value="this.$allowillegal and this.$enforceRouteIllegalLegality and @$bestSupplyTrade.$Ware.illegal gt 0">
                <run_script name="'lib.gt.pathfinding'" result="$supRouteLegality">
                  <param name="mode" value="'route_legality'"/>
                  <param name="ship" value="this.ship"/>
                  <param name="homeSector" value="this.$homeStation.sector"/>
                  <param name="allowIllegal" value="this.$allowillegal"/>
                  <param name="enforceRouteIllegalLegality" value="this.$enforceRouteIllegalLegality"/>
                  <param name="startSector" value="this.ship.sector"/>
                  <param name="buySector" value="if $bestSupplyTrade.$SellerStation? then $bestSupplyTrade.$SellerStation.sector else (if $bestSupplyTrade.$SellOffer? and $bestSupplyTrade.$SellOffer.owner? then @$bestSupplyTrade.$SellOffer.owner.sector else null)"/>
                  <param name="sellSector" value="this.$homeStation.sector"/>
                  <param name="ware" value="$bestSupplyTrade.$Ware"/>
                </run_script>
                <do_if value="not $supRouteLegality.$IsLegal">
                  <set_value name="this.$mk1_supRouteOk" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="this.$mk1_supRouteOk">
              <set_value name="$supSellerStation" exact="if $bestSupplyTrade.$SellOffer? and $bestSupplyTrade.$SellOffer.owner? and $bestSupplyTrade.$SellOffer.owner.exists then $bestSupplyTrade.$SellOffer.owner else null"/>
              <do_if value="$supSellerStation? and $supSellerStation.exists">
                <run_script name="'lib.gt.dockcheck'" result="$mk1SupSellerDockCheck">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$supSellerStation"/>
                  <param name="purpose" value="'trade'"/>
                </run_script>
                <do_if value="not $mk1SupSellerDockCheck.$CanDock">
                  <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply skipped â€” no trading dock at source ' + $supSellerStation.knownname" chance="this.$debugchance"/>
                  <set_value name="this.$mk1_supRouteOk" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="this.$mk1_supRouteOk">
              <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}?">
                <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
                <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
                  <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
                </do_if>
              </do_if>
              <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
                <remove_value name="global.$GT_MK1DockedSince.{this.ship}"/>
              </do_if>
              <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
                <remove_value name="global.$GT_MK1ReturnHomeReleased.{this.ship}"/>
              </do_if>
              <remove_value name="this.$mk1_dockedSince"/>
              <remove_value name="this.$mk1_returnhomeReleased"/>
              <!-- Queue delivery first, then buy. With immediate="true", later created orders execute first
                   (vanilla TradeRoutine: "sell first, buy displaces it" â†’ buy runs first).
                   So create DELIVER (BuyOffer) first, BUY (SellOffer) second â†’ BUY executes first. -->
              <create_trade_order object="this.ship" tradeoffer="$bestSupplyTrade.$BuyOffer" amount="$supBuyAmount" immediate="true" internal="false"/>
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Queued DELIVER order: ' + $supBuyAmount + ' ' + $bestSupplyTrade.$Ware.name + ' to ' + this.$homeStation.knownname + ' (vanilla reservation expected)'" chance="this.$debugchance"/>

              <create_trade_order object="this.ship" tradeoffer="$bestSupplyTrade.$SellOffer" amount="$supBuyAmount" immediate="true" internal="false"/>
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Queued BUY order: ' + $supBuyAmount + ' ' + $bestSupplyTrade.$Ware.name + ' from ' + $bestSupplyTrade.$SellerStation.knownname" chance="this.$debugchance"/>
              <do_if value="this.$logbookentries">
                <set_value name="$mk1SupplyAmount" exact="if $supBuyAmount? and $supBuyAmount != null then $supBuyAmount else 0"/>
                <do_if value="$mk1SupplyAmount gt 0 and $bestSupplyTrade.$SellOffer != null and $bestSupplyTrade.$BuyOffer != null">
                  <set_value name="$mk1SupWare" exact="$bestSupplyTrade.$Ware"/>
                  <set_value name="$mk1SupSrcStation" exact="if $bestSupplyTrade.$BuyStation? and $bestSupplyTrade.$BuyStation.exists then $bestSupplyTrade.$BuyStation else $bestSupplyTrade.$SellerStation"/>
                  <set_value name="$mk1SupDstStation" exact="if $bestSupplyTrade.$SellStation? and $bestSupplyTrade.$SellStation.exists then $bestSupplyTrade.$SellStation else this.$homeStation"/>
                  <set_value name="$mk1SupSrcTarget" exact="[$mk1SupSrcStation.cargo.{$mk1SupWare}.target, 1].max"/>
                  <set_value name="$mk1SupSrcCount" exact="$mk1SupSrcStation.cargo.{$mk1SupWare}.count"/>
                  <get_ware_reservation object="$mk1SupSrcStation" ware="$mk1SupWare" type="buy" virtual="false" result="$mk1SupSrcReserved"/>
                  <set_value name="$mk1SupSrcEff" exact="[$mk1SupSrcCount - $mk1SupSrcReserved, 0].max"/>
                  <set_value name="$mk1SupSourceFill" exact="(($mk1SupSrcEff * 100) / $mk1SupSrcTarget)i"/>
                  <set_value name="$mk1SupDstTarget" exact="[$mk1SupDstStation.cargo.{$mk1SupWare}.target, 1].max"/>
                  <set_value name="$mk1SupDestFill" exact="(($mk1SupDstStation.cargo.{$mk1SupWare}.count * 100) / $mk1SupDstTarget)i"/>
                  <set_value name="$mk1SupBuyPriceRaw" exact="if $bestSupplyTrade.$BuyPrice? and $bestSupplyTrade.$BuyPrice != null then $bestSupplyTrade.$BuyPrice else (if $bestSupplyTrade.$SellOffer? and $bestSupplyTrade.$SellOffer.unitprice? then $bestSupplyTrade.$SellOffer.unitprice else 0)"/>
                  <set_value name="$mk1SupSellPriceRaw" exact="if $bestSupplyTrade.$SellPrice? and $bestSupplyTrade.$SellPrice != null then $bestSupplyTrade.$SellPrice else (if $bestSupplyTrade.$BuyOffer? and $bestSupplyTrade.$BuyOffer.unitprice? then $bestSupplyTrade.$BuyOffer.unitprice else 0)"/>
                  <set_value name="$mk1SupProfitRaw" exact="($mk1SupSellPriceRaw - $mk1SupBuyPriceRaw) * $mk1SupplyAmount"/>
                  <set_value name="$mk1SupMoneyRaw" exact="-($mk1SupBuyPriceRaw * $mk1SupplyAmount)"/>
                  <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
                    $Ship = this.ship,
                    $IsMk1Supply = true,
                    $BuyOffer = $bestSupplyTrade.$BuyOffer,
                    $SellOffer = $bestSupplyTrade.$SellOffer,
                    $BuyStation = $mk1SupSrcStation,
                    $SellStation = $mk1SupDstStation,
                    $Ware = $mk1SupWare,
                    $Amount = $mk1SupplyAmount,
                    $BuyPriceRaw = $mk1SupBuyPriceRaw,
                    $SellPriceRaw = $mk1SupSellPriceRaw,
                    $BuyPrice = $mk1SupBuyPriceRaw / 100,
                    $SellPrice = $mk1SupSellPriceRaw / 100,
                    $Profit = $mk1SupProfitRaw,
                    $MoneyRaw = $mk1SupMoneyRaw,
                    $SourceFillPercent = $mk1SupSourceFill,
                    $DestFillPercent = $mk1SupDestFill,
                    $IsSellOnly = false,
                    $SearchPipeline = 'normal'
                  ]"/>
                </do_if>
              </do_if>

              <set_value name="this.$mk1_supplyOrdersCreated" exact="1"/>
              <do_if value="this.$allowillegal and this.$enforceRouteIllegalLegality">
                <do_if value="not global.$GT_Ships?">
                  <set_value name="global.$GT_Ships" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_Ships.{this.ship}?">
                  <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy" exact="table[
                  $AllowIllegal = this.$allowillegal,
                  $EnforceRouteIllegalLegality = this.$enforceRouteIllegalLegality,
                  $Ware = $bestSupplyTrade.$Ware,
                  $BuySector = if $bestSupplyTrade.$SellerStation? then $bestSupplyTrade.$SellerStation.sector else null,
                  $SellSector = this.$homeStation.sector,
                  $HomeSector = this.$homeStation.sector,
                  $RouteStart = this.ship.sector,
                  $Leg = 'buy',
                  $LogbookEntries = this.$logbookentries,
                  $SetAt = player.age
                ]"/>
              </do_if>
            </do_if>
            </do_if>
          </do_if>
          </do_if>

          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield after supply order queue attempt"/>

          <do_if value="not this.$mk1_supplyOrdersCreated? or this.$mk1_supplyOrdersCreated == 0">
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Supply trade offers no longer available â€” skipping'" chance="this.$debugchance"/>
          </do_if>

          <!-- Wait for both orders to complete (buy + deliver) -->
          <do_if value="this.$mk1_supplyOrdersCreated? and this.$mk1_supplyOrdersCreated == 1">
            <do_while value="this.ship.orders.count gt 0">
              <wait exact="5s">
                <interrupt>
                  <conditions>
                    <event_object_order_ready object="this.ship"/>
                  </conditions>
                </interrupt>
              </wait>
            </do_while>
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
              <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
            </do_if>
          </do_if>

          <!-- XP only if supply orders were actually created and executed -->
          <do_if value="this.$mk1_supplyOrdersCreated? and this.$mk1_supplyOrdersCreated == 1">
            <!-- XP for supply run -->
            <do_if value="this.ship.pilot">
              <signal_objects object="player.galaxy" param="'GT_Update_Pilot_XP'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot
              ]"/>
            </do_if>
          </do_if>

          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': === SUPPLY PHASE COMPLETE === Re-evaluating...'" chance="this.$debugchance"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield"/>
          <resume label="main_loop"/>
        </do_if>
        <do_else>
          <!-- Reset priority flag so the no-sell fallback can attempt supply again with a short retry -->
          <set_value name="this.$supplyPriority" exact="false"/>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': No supply trades found â€” falling through to sell phase'" chance="this.$debugchance"/>
        </do_else>
      </do_if>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 4: Build effective ware basket from station               -->
      <!-- ============================================================== -->
      <set_command_action commandaction="commandaction.searchingtrades"/>

      <!-- Inline: Build effective ware basket from station products/tradewares -->
      <create_list name="$effectiveWares"/>
      <create_list name="$candidateWares"/>
      <create_list name="$stationProducts"/>
      <create_list name="$stationTradewares"/>
      <create_list name="$stationProductIntermediates"/>

      <do_if value="this.$warebasket? and this.$warebasket.count gt 0">
        <!-- Manual filter: use only user-specified wares -->
        <do_all exact="this.$warebasket.count" counter="$wi">
          <append_to_list name="$candidateWares" exact="this.$warebasket.{$wi}"/>
        </do_all>
      </do_if>
      <do_else>
        <!-- Auto-derive: station products + tradewares -->
        <set_value name="$stationProducts" exact="this.$homeStation.products.list"/>
        <set_value name="$stationTradewares" exact="this.$homeStation.tradewares.list"/>
        <!-- Safe diagnostic view: derive intermediates from products list.
             resources.intermediate can be unavailable in this AI context. -->
        <do_all exact="$stationProducts.count" counter="$sip">
          <set_value name="$sipw" exact="$stationProducts.{$sip}"/>
          <do_if value="this.$homeStation.products.{$sipw}.intermediate">
            <append_to_list name="$stationProductIntermediates" exact="$sipw"/>
          </do_if>
        </do_all>

        <do_all exact="$stationProducts.count" counter="$pi">
          <set_value name="$pw" exact="$stationProducts.{$pi}"/>
          <set_value name="$dupCheck" exact="false"/>
          <do_all exact="$candidateWares.count" counter="$dci">
            <do_if value="$candidateWares.{$dci} == $pw">
              <set_value name="$dupCheck" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $dupCheck">
            <append_to_list name="$candidateWares" exact="$pw"/>
          </do_if>
        </do_all>

        <do_all exact="$stationTradewares.count" counter="$ti">
          <set_value name="$tw" exact="$stationTradewares.{$ti}"/>
          <set_value name="$dupCheck" exact="false"/>
          <do_all exact="$candidateWares.count" counter="$dci">
            <do_if value="$candidateWares.{$dci} == $tw">
              <set_value name="$dupCheck" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $dupCheck">
            <append_to_list name="$candidateWares" exact="$tw"/>
          </do_if>
        </do_all>
      </do_else>

      <!-- Filter candidates: cargo compatibility, processed, illegal -->
      <do_all exact="$candidateWares.count" counter="$fi">
        <set_value name="$fw" exact="$candidateWares.{$fi}"/>
        <do_if value="this.ship.cargo.{$fw}.max le 0">
          <continue/>
        </do_if>
        <do_if value="$fw.isprocessed">
          <continue/>
        </do_if>
        <do_if value="not this.$allowillegal and $fw.illegal">
          <continue/>
        </do_if>
        <append_to_list name="$effectiveWares" exact="$fw"/>
      </do_all>

      <set_value name="$mk1DbgMax" exact="20"/>

      <!-- STEP 4b: Export storage gate (Min Product Storage %) -->
      <set_value name="$mk1PreGateEffectiveCount" exact="$effectiveWares.count"/>
      <set_value name="$mk1SellStorageGateStr" exact="''"/>
      <set_value name="$mk1SellStorageGateDiagCount" exact="0"/>
      <set_value name="$mk1SellStorageGateDiagMax" exact="20"/>
      <do_if value="this.$minsellstorage gt 0 and $effectiveWares.count gt 0">
        <create_list name="$mk1GatedEffectiveWares"/>
        <do_all exact="$effectiveWares.count" counter="$msgi">
          <set_value name="$msgw" exact="$effectiveWares.{$msgi}"/>
          <set_value name="$msgConfiguredMax" exact="this.$homeStation.cargo.{$msgw}.target"/>
          <do_if value="$msgConfiguredMax le 0">
            <do_if value="this.$debuglevel ge 2 and $mk1SellStorageGateDiagCount lt $mk1SellStorageGateDiagMax">
              <set_value name="$mk1SellStorageGateStr" exact="$mk1SellStorageGateStr + (if $mk1SellStorageGateDiagCount gt 0 then ' | ' else '') + (if $msgw? and $msgw.name? then @$msgw.name else '?') + ':drop(no configured max)'"/>
              <set_value name="$mk1SellStorageGateDiagCount" operation="add"/>
            </do_if>
            <continue/>
          </do_if>
          <set_value name="$msgCount" exact="this.$homeStation.cargo.{$msgw}.count"/>
          <get_ware_reservation object="this.$homeStation" ware="$msgw" type="buy" virtual="false" result="$msgResTotal"/>
          <get_ware_reservation object="this.$homeStation" ware="$msgw" type="buy" reserver="this.ship" virtual="false" result="$msgResSelf"/>
          <set_value name="$msgResOther" exact="[($msgResTotal - $msgResSelf), 0].max"/>
          <set_value name="$msgEffectiveCount" exact="[($msgCount - $msgResOther), 0].max"/>
          <set_value name="$msgFillPct" exact="($msgEffectiveCount * 100) / $msgConfiguredMax"/>
          <do_if value="$msgFillPct ge this.$minsellstorage">
            <append_to_list name="$mk1GatedEffectiveWares" exact="$msgw"/>
            <do_if value="this.$debuglevel ge 2 and $mk1SellStorageGateDiagCount lt $mk1SellStorageGateDiagMax">
              <set_value name="$mk1SellStorageGateStr" exact="$mk1SellStorageGateStr + (if $mk1SellStorageGateDiagCount gt 0 then ' | ' else '') + (if $msgw? and $msgw.name? then @$msgw.name else '?') + ':keep(' + $msgFillPct + '%)'"/>
              <set_value name="$mk1SellStorageGateDiagCount" operation="add"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="this.$debuglevel ge 2 and $mk1SellStorageGateDiagCount lt $mk1SellStorageGateDiagMax">
              <set_value name="$mk1SellStorageGateStr" exact="$mk1SellStorageGateStr + (if $mk1SellStorageGateDiagCount gt 0 then ' | ' else '') + (if $msgw? and $msgw.name? then @$msgw.name else '?') + ':drop(' + $msgFillPct + '% lt ' + this.$minsellstorage + '%)'"/>
              <set_value name="$mk1SellStorageGateDiagCount" operation="add"/>
            </do_if>
          </do_else>
        </do_all>
        <set_value name="$effectiveWares" exact="$mk1GatedEffectiveWares"/>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': SELL_STORAGE_GATE min=' + this.$minsellstorage + '% pre=' + $mk1PreGateEffectiveCount + ' post=' + $effectiveWares.count + (if $mk1SellStorageGateStr != '' then ' [' + $mk1SellStorageGateStr + ']' else '')" chance="this.$debugchance"/>
        </do_if>
      </do_if>
      <set_value name="$mk1SellStorageGateSig" exact="'min=' + this.$minsellstorage + '|pre=' + $mk1PreGateEffectiveCount + '|post=' + $effectiveWares.count + (if $mk1SellStorageGateStr != '' then '|' + $mk1SellStorageGateStr else '')"/>
      <set_value name="this.$mk1_lastSellStorageGateSig" exact="$mk1SellStorageGateSig"/>

      <!-- Verbose ware snapshot for MK1 diagnostics:
           shows raw station lists and the effective basket after filters. -->
      <set_value name="$mk1ProductsStr" exact="''"/>
      <set_value name="$mk1TradewaresStr" exact="''"/>
      <set_value name="$mk1IntermediatesStr" exact="''"/>
      <set_value name="$mk1ManualBasketStr" exact="''"/>
      <set_value name="$mk1CandidateStr" exact="''"/>
      <set_value name="$mk1EffectiveStr" exact="''"/>

      <do_all exact="$stationProducts.count" counter="$msp">
        <do_if value="$msp gt $mk1DbgMax">
          <set_value name="$mk1ProductsStr" exact="$mk1ProductsStr + '...+' + ($stationProducts.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mk1Pw" exact="$stationProducts.{$msp}"/>
        <set_value name="$mk1ProductsStr" exact="$mk1ProductsStr + (if $msp gt 1 then ', ' else '') + (if $mk1Pw? and $mk1Pw != null and $mk1Pw.name? then @$mk1Pw.name else '?')"/>
      </do_all>
      <do_all exact="$stationTradewares.count" counter="$mst">
        <do_if value="$mst gt $mk1DbgMax">
          <set_value name="$mk1TradewaresStr" exact="$mk1TradewaresStr + '...+' + ($stationTradewares.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mk1Tw" exact="$stationTradewares.{$mst}"/>
        <set_value name="$mk1TradewaresStr" exact="$mk1TradewaresStr + (if $mst gt 1 then ', ' else '') + (if $mk1Tw? and $mk1Tw != null and $mk1Tw.name? then @$mk1Tw.name else '?')"/>
      </do_all>
      <do_all exact="$stationProductIntermediates.count" counter="$msi">
        <do_if value="$msi gt $mk1DbgMax">
          <set_value name="$mk1IntermediatesStr" exact="$mk1IntermediatesStr + '...+' + ($stationProductIntermediates.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mk1Iw" exact="$stationProductIntermediates.{$msi}"/>
        <set_value name="$mk1IntermediatesStr" exact="$mk1IntermediatesStr + (if $msi gt 1 then ', ' else '') + (if $mk1Iw? and $mk1Iw != null and $mk1Iw.name? then @$mk1Iw.name else '?')"/>
      </do_all>
      <do_all exact="if this.$warebasket? then this.$warebasket.count else 0" counter="$msm">
        <do_if value="$msm gt $mk1DbgMax">
          <set_value name="$mk1ManualBasketStr" exact="$mk1ManualBasketStr + '...+' + (this.$warebasket.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mk1Mw" exact="this.$warebasket.{$msm}"/>
        <set_value name="$mk1ManualBasketStr" exact="$mk1ManualBasketStr + (if $msm gt 1 then ', ' else '') + (if $mk1Mw? and $mk1Mw != null and $mk1Mw.name? then @$mk1Mw.name else '?')"/>
      </do_all>
      <do_all exact="$candidateWares.count" counter="$msc">
        <do_if value="$msc gt $mk1DbgMax">
          <set_value name="$mk1CandidateStr" exact="$mk1CandidateStr + '...+' + ($candidateWares.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mk1Cw" exact="$candidateWares.{$msc}"/>
        <set_value name="$mk1CandidateStr" exact="$mk1CandidateStr + (if $msc gt 1 then ', ' else '') + (if $mk1Cw? and $mk1Cw != null and $mk1Cw.name? then @$mk1Cw.name else '?')"/>
      </do_all>
      <do_all exact="$effectiveWares.count" counter="$mse">
        <do_if value="$mse gt $mk1DbgMax">
          <set_value name="$mk1EffectiveStr" exact="$mk1EffectiveStr + '...+' + ($effectiveWares.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mk1Ew" exact="$effectiveWares.{$mse}"/>
        <set_value name="$mk1EffectiveStr" exact="$mk1EffectiveStr + (if $mse gt 1 then ', ' else '') + (if $mk1Ew? and $mk1Ew != null and $mk1Ew.name? then @$mk1Ew.name else '?')"/>
      </do_all>

      <set_value name="$mk1AutoMode" exact="not (this.$warebasket? and this.$warebasket.count gt 0)"/>
      <set_value name="$mk1WaresSnapshotSig" exact="'A=' + $mk1AutoMode + '|P=' + $stationProducts.count + '[' + $mk1ProductsStr + ']|T=' + $stationTradewares.count + '[' + $mk1TradewaresStr + ']|I=' + $stationProductIntermediates.count + '[' + $mk1IntermediatesStr + ']|M=' + (if this.$warebasket? then this.$warebasket.count else 0) + '[' + $mk1ManualBasketStr + ']|C=' + $candidateWares.count + '[' + $mk1CandidateStr + ']|E=' + $effectiveWares.count + '[' + $mk1EffectiveStr + ']'"/>
      <do_if value="this.$debuglevel ge 1 and (this.$debuglevel ge 2 or not this.$mk1_lastWaresSnapshotSig? or this.$mk1_lastWaresSnapshotSig != $mk1WaresSnapshotSig)">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': WARE_SNAPSHOT mode=' + (if $mk1AutoMode then 'auto' else 'manual') + ' station=' + this.$homeStation.knownname + ' products=' + $stationProducts.count + ' tradewares=' + $stationTradewares.count + ' products.intermediate=' + $stationProductIntermediates.count + ' manualBasket=' + (if this.$warebasket? then this.$warebasket.count else 0) + ' candidates=' + $candidateWares.count + ' effective=' + $effectiveWares.count" chance="this.$debugchance"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': WARE_SNAPSHOT_LISTS products=[' + $mk1ProductsStr + '] tradewares=[' + $mk1TradewaresStr + '] products.intermediate=[' + $mk1IntermediatesStr + '] manual=[' + $mk1ManualBasketStr + ']'" chance="this.$debugchance"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': WARE_SNAPSHOT_RESOLVED candidates=[' + $mk1CandidateStr + '] effective=[' + $mk1EffectiveStr + ']'" chance="this.$debugchance"/>
      </do_if>
      <set_value name="this.$mk1_lastWaresSnapshotSig" exact="$mk1WaresSnapshotSig"/>

      <set_value name="$mk1NoWaresReason" exact="if this.$minsellstorage gt 0 and $mk1PreGateEffectiveCount gt 0 then 'all products below Min Product Storage % (' + this.$minsellstorage + ')' else 'no wares available from station'"/>

      <do_if value="$effectiveWares.count == 0">
        <do_if value="this.$returnhome">
          <do_if value="this.$mk1_returnhomeReleased? and this.$mk1_returnhomeReleased">
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ' + $mk1NoWaresReason + ' â€” return-home released state active, staying undocked and waiting ' + this.$waitTimeNoTrades" chance="this.$debugchance"/>
            <remove_value name="this.$mk1_opportunisticSupplyTried"/>
            <wait exact="this.$waitTimeNoTrades"/>
            <resume label="main_loop"/>
          </do_if>
          <do_else>
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ' + $mk1NoWaresReason + ' â€” returning home to dock and waiting ' + this.$waitTimeNoTrades" chance="this.$debugchance"/>
            <remove_value name="this.$mk1_opportunisticSupplyTried"/>
            <set_value name="this.$mk1_pendingRetryWait" exact="this.$waitTimeNoTrades"/>
            <resume label="return_home_and_dock"/>
          </do_else>
        </do_if>
        <do_else>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ' + $mk1NoWaresReason + ' â€” waiting ' + this.$waitTimeNoTrades + ' (returnhome disabled)'" chance="this.$debugchance"/>
          <remove_value name="this.$mk1_opportunisticSupplyTried"/>
          <wait exact="this.$waitTimeNoTrades"/>
          <resume label="main_loop"/>
        </do_else>
      </do_if>

      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Effective ware basket: ' + $effectiveWares.count + ' wares'" chance="this.$debugchance"/>

      <!-- ============================================================== -->
      <!-- STEP 5: Find best sale opportunity                             -->
      <!-- ============================================================== -->
      <!-- Shared pipeline: pathfinding + live search + trade match -->
      <run_script name="'lib.gt.pathfinding'" result="$sellSpaces">
        <param name="ship" value="this.ship"/>
        <param name="homeSector" value="this.$homeStation.sector"/>
        <param name="maxDistance" value="this.$maxsell"/>
      </run_script>
      <set_value name="$mk1ResolvedSellSpaces" exact="[]"/>
      <do_if value="$sellSpaces?">
        <do_if value="$sellSpaces.$SellSpaces?">
          <set_value name="$mk1ResolvedSellSpaces" exact="@$sellSpaces.$SellSpaces"/>
        </do_if>
      </do_if>

      <!-- Re-read MK1 order price range (may have changed since supply search) -->
      <set_value name="$mk1BuyPriceMin" exact="this.$pricerangeNorm"/>
      <set_value name="$mk1SellPriceMax" exact="0 - this.$pricerangeNorm"/>

      <!-- Resolve home-station sell offers before buyer scan so live search can rank buyers by estimated profit. -->
      <create_list name="$stationSellOffers"/>
      <do_all exact="$effectiveWares.count" counter="$ewi">
        <set_value name="$ware" exact="$effectiveWares.{$ewi}"/>
        <set_value name="$stationSellOffer" exact="null"/>
        <do_if value="this.$ignoretraderules">
          <find_sell_offer seller="this.$homeStation" wares="$ware" result="$stationSellOffer"/>
        </do_if>
        <do_else>
          <find_sell_offer seller="this.$homeStation" wares="$ware" tradepartner="this.ship" result="$stationSellOffer"/>
        </do_else>
        <do_if value="$stationSellOffer? and $stationSellOffer.available and $stationSellOffer.amount gt 0 and $stationSellOffer.ware == $ware">
          <append_to_list name="$stationSellOffers" exact="$stationSellOffer"/>
        </do_if>
      </do_all>

      <run_script name="'lib.gt.live.search'" result="$sellLiveResult">
        <param name="ship" value="this.ship"/>
        <param name="searchMode" value="'sell_only'"/>
        <param name="buySpaces" value="[]"/>
        <param name="sellSpaces" value="$mk1ResolvedSellSpaces"/>
        <param name="homeSector" value="this.$homeStation.sector"/>
        <param name="maxDistance" value="this.$maxsell"/>
        <param name="wareBasket" value="$effectiveWares"/>
        <param name="allowIllegal" value="this.$allowillegal"/>
        <param name="ownerFilter" value="'npc_only'"/>
        <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
        <param name="ignoreMK1Supply" value="false"/>
        <param name="sellPriceMax" value="$mk1SellPriceMax"/>
        <param name="buyPriceMin" value="$mk1BuyPriceMin"/>
        <param name="sourceSellOffers" value="$stationSellOffers"/>
        <param name="scoreAwareBuyCap" value="true"/>
        <param name="distancePenalty" value="0.1"/>
        <param name="debugchance" value="this.$debugchance"/>
      </run_script>
      <set_value name="this.$mk1_sellLiveResult" exact="$sellLiveResult"/>
      <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield after sell live search"/>
      <set_value name="$sellLiveResult" exact="this.$mk1_sellLiveResult"/>

      <!-- Enforce home-station trade rules when ignoretraderules=false.
           Candidate buyers must be valid with the station as tradepartner,
           otherwise MK1 could sell to factions blocked by station rules. -->
      <create_list name="$sellPhaseBuyOffers"/>
      <do_if value="this.$ignoretraderules">
        <set_value name="$sellPhaseBuyOffers" exact="$sellLiveResult.$BuyOffers"/>
      </do_if>
      <do_else>
        <do_if value="$sellLiveResult.$BuyOffers? and $sellLiveResult.$BuyOffers.count gt 0">
          <do_all exact="$sellLiveResult.$BuyOffers.count" counter="$sbi">
            <set_value name="$candidateBuyOffer" exact="$sellLiveResult.$BuyOffers.{$sbi}"/>
            <do_if value="not $candidateBuyOffer? or not $candidateBuyOffer.owner? or not $candidateBuyOffer.ware?">
              <continue/>
            </do_if>
            <!-- Enforce station-side trade restrictions:
                 buyer offer must allow the home station as a counterparty. -->
            <do_if value="$candidateBuyOffer.cantradewith.{this.$homeStation}">
              <append_to_list name="$sellPhaseBuyOffers" exact="$candidateBuyOffer"/>
            </do_if>
          </do_all>
        </do_if>
      </do_else>

      <set_value name="$mk1SellOfferStr" exact="''"/>
      <do_all exact="$stationSellOffers.count" counter="$msoi">
        <do_if value="$msoi gt $mk1DbgMax">
          <set_value name="$mk1SellOfferStr" exact="$mk1SellOfferStr + '...+' + ($stationSellOffers.count - $mk1DbgMax)"/>
          <break/>
        </do_if>
        <set_value name="$mso" exact="$stationSellOffers.{$msoi}"/>
        <set_value name="$mk1Sow" exact="if $mso? and $mso.ware? then $mso.ware else null"/>
        <set_value name="$mk1SowName" exact="if $mk1Sow? and $mk1Sow.name? then @$mk1Sow.name else '?'"/>
        <set_value name="$mk1SellOfferStr" exact="$mk1SellOfferStr + (if $msoi gt 1 then ', ' else '') + $mk1SowName + ':' + (if $mso and $mso.amount? then $mso.amount else 0)"/>
      </do_all>
      <set_value name="$mk1SellOffersSnapshotSig" exact="'BO=' + (if $sellPhaseBuyOffers? then $sellPhaseBuyOffers.count else 0) + '|SO=' + $stationSellOffers.count + '[' + $mk1SellOfferStr + ']'"/>
      <do_if value="this.$debuglevel ge 1 and (this.$debuglevel ge 2 or not this.$mk1_lastSellOffersSnapshotSig? or this.$mk1_lastSellOffersSnapshotSig != $mk1SellOffersSnapshotSig)">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': SELL_OFFER_SNAPSHOT buyerOffers=' + (if $sellPhaseBuyOffers? then $sellPhaseBuyOffers.count else 0) + ' stationSellOffers=' + $stationSellOffers.count + ' [' + $mk1SellOfferStr + ']'" chance="this.$debugchance"/>
      </do_if>
      <set_value name="this.$mk1_lastSellOffersSnapshotSig" exact="$mk1SellOffersSnapshotSig"/>

      <run_script name="'lib.gt.tradematch'" result="$matchResult">
        <param name="ship" value="this.ship"/>
        <param name="sellOffers" value="$stationSellOffers"/>
        <param name="buyOffers" value="$sellPhaseBuyOffers"/>
        <param name="homeSector" value="this.$homeStation.sector"/>
        <param name="maxDistance" value="this.$maxsell"/>
        <param name="distancePenalty" value="0.1"/>
        <param name="scoreMode" value="'sell'"/>
        <param name="allowZeroProfitSell" value="true"/>
        <param name="allowIllegal" value="this.$allowillegal"/>
        <param name="enforceRouteIllegalLegality" value="this.$enforceRouteIllegalLegality"/>
      </run_script>
      <set_value name="this.$mk1_matchResult" exact="$matchResult"/>
      <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after shared tradematch call"/>
      <set_value name="$matchResult" exact="this.$mk1_matchResult"/>

      <create_list name="$allTrades"/>
      <set_value name="$matchedTrades" exact="[]"/>
      <do_if value="$matchResult?">
        <do_if value="$matchResult.$TradeList?">
          <set_value name="$matchedTrades" exact="@$matchResult.$TradeList"/>
        </do_if>
      </do_if>
      <do_if value="$matchedTrades.count gt 0">
        <do_all exact="$matchedTrades.count" counter="$ti">
          <set_value name="$trade" exact="$matchedTrades.{$ti}"/>
          <set_value name="$keepTrade" exact="true"/>

          <!-- Keep old fleet reservation filter behavior -->
          <do_if value="$keepTrade and this.$fleetcoordination and global.$GT_TradeReservations?">
            <set_value name="$tradeKey" exact="'' + $trade.$Ware + '_' + $trade.$BuyStation"/>
            <do_if value="global.$GT_TradeReservations.{$tradeKey}? and global.$GT_TradeReservations.{$tradeKey} != this.ship">
              <set_value name="$keepTrade" exact="false"/>
            </do_if>
          </do_if>

          <!-- Keep old blacklist filter behavior -->
          <do_if value="$keepTrade and global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.$BlacklistedSectors?">
            <do_all exact="global.$GT_ThreatIntelligence.$BlacklistedSectors.count" counter="$bli">
              <do_if value="global.$GT_ThreatIntelligence.$BlacklistedSectors.{$bli} == $trade.$BuySector">
                <set_value name="$keepTrade" exact="false"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>

          <!-- Hard safety net (trade rules ON):
               1) buyer offer must allow home station as seller-side counterparty
               2) home-station sell offer must allow the selected buyer station -->
          <do_if value="$keepTrade and not this.$ignoretraderules and ($trade.$SellOffer == null or not $trade.$SellOffer.exists or $trade.$BuyOffer == null or not $trade.$BuyOffer.exists)">
            <set_value name="$keepTrade" exact="false"/>
          </do_if>
          <do_if value="$keepTrade and not this.$ignoretraderules and not $trade.$SellOffer.cantradewith.{this.$homeStation}">
            <set_value name="$keepTrade" exact="false"/>
          </do_if>
          <do_if value="$keepTrade and not this.$ignoretraderules and not $trade.$BuyOffer.cantradewith.{$trade.$SellOffer.owner}">
            <set_value name="$keepTrade" exact="false"/>
          </do_if>

          <!-- Docking: load and sell stations must have operational trading bays for this ship -->
          <do_if value="$keepTrade and $trade.$BuyStation? and $trade.$BuyStation.exists">
            <run_script name="'lib.gt.dockcheck'" result="$mk1DockCheck">
              <param name="ship" value="this.ship"/>
              <param name="station" value="$trade.$BuyStation"/>
              <param name="purpose" value="'trade'"/>
            </run_script>
            <do_if value="not $mk1DockCheck.$CanDock">
              <set_value name="$keepTrade" exact="false"/>
            </do_if>
          </do_if>
          <do_if value="$keepTrade and $trade.$SellStation? and $trade.$SellStation.exists">
            <set_value name="$mk1NeedSellDockCheck" exact="true"/>
            <do_if value="$trade.$BuyStation? and $trade.$BuyStation.exists and $trade.$BuyStation == $trade.$SellStation">
              <set_value name="$mk1NeedSellDockCheck" exact="false"/>
            </do_if>
            <do_if value="$mk1NeedSellDockCheck">
              <run_script name="'lib.gt.dockcheck'" result="$mk1DockCheck">
                <param name="ship" value="this.ship"/>
                <param name="station" value="$trade.$SellStation"/>
                <param name="purpose" value="'trade'"/>
              </run_script>
              <do_if value="not $mk1DockCheck.$CanDock">
                <set_value name="$keepTrade" exact="false"/>
              </do_if>
            </do_if>
          </do_if>

          <do_if value="$keepTrade">
            <append_to_list name="$allTrades" exact="$trade"/>
          </do_if>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Yield after export trade dock filter"/>
        </do_all>
      </do_if>

      <label name="select_best_trade"/>
      <set_value name="$bestTradeCandidatePool" exact="$allTrades"/>
      <do_if value="this.$sellselectionmode == 1 and $allTrades.count gt 0">
        <!-- Cargo mode: highest station fill tie-break; soft selltarget station filter only when export gate is off -->
        <do_if value="this.$minsellstorage le 0">
          <create_list name="$cargoThresholdTrades"/>
          <do_all exact="$allTrades.count" counter="$cfi">
            <set_value name="$cTrade" exact="$allTrades.{$cfi}"/>
            <set_value name="$cWareTarget" exact="this.$homeStation.cargo.{$cTrade.$Ware}.target"/>
            <set_value name="$cWareCount" exact="this.$homeStation.cargo.{$cTrade.$Ware}.count"/>
            <get_ware_reservation object="this.$homeStation" ware="$cTrade.$Ware" type="buy" virtual="false" result="$cWareReservedTotal"/>
            <get_ware_reservation object="this.$homeStation" ware="$cTrade.$Ware" type="buy" reserver="this.ship" virtual="false" result="$cWareReservedSelf"/>
            <set_value name="$cWareReservedOther" exact="[($cWareReservedTotal - $cWareReservedSelf), 0].max"/>
            <set_value name="$cWareEffectiveCount" exact="[($cWareCount - $cWareReservedOther), 0].max"/>
            <set_value name="$cWareFillPct" exact="if $cWareTarget gt 0 then (($cWareEffectiveCount * 100) / $cWareTarget) else 0"/>
            <do_if value="$cWareFillPct ge this.$selltarget">
              <append_to_list name="$cargoThresholdTrades" exact="$cTrade"/>
            </do_if>
          </do_all>
          <do_if value="$cargoThresholdTrades.count gt 0">
            <set_value name="$bestTradeCandidatePool" exact="$cargoThresholdTrades"/>
          </do_if>
        </do_if>

        <set_value name="$maxWareFillPct" exact="-1"/>
        <do_all exact="$bestTradeCandidatePool.count" counter="$mfi">
          <set_value name="$mTrade" exact="$bestTradeCandidatePool.{$mfi}"/>
          <set_value name="$mWareTarget" exact="this.$homeStation.cargo.{$mTrade.$Ware}.target"/>
          <set_value name="$mWareCount" exact="this.$homeStation.cargo.{$mTrade.$Ware}.count"/>
          <get_ware_reservation object="this.$homeStation" ware="$mTrade.$Ware" type="buy" virtual="false" result="$mWareReservedTotal"/>
          <get_ware_reservation object="this.$homeStation" ware="$mTrade.$Ware" type="buy" reserver="this.ship" virtual="false" result="$mWareReservedSelf"/>
          <set_value name="$mWareReservedOther" exact="[($mWareReservedTotal - $mWareReservedSelf), 0].max"/>
          <set_value name="$mWareEffectiveCount" exact="[($mWareCount - $mWareReservedOther), 0].max"/>
          <set_value name="$mWareFillPct" exact="if $mWareTarget gt 0 then (($mWareEffectiveCount * 100) / $mWareTarget) else 0"/>
          <do_if value="$mWareFillPct gt $maxWareFillPct">
            <set_value name="$maxWareFillPct" exact="$mWareFillPct"/>
          </do_if>
        </do_all>

        <create_list name="$maxFillTrades"/>
        <do_all exact="$bestTradeCandidatePool.count" counter="$mfti">
          <set_value name="$mfTrade" exact="$bestTradeCandidatePool.{$mfti}"/>
          <set_value name="$mfWareTarget" exact="this.$homeStation.cargo.{$mfTrade.$Ware}.target"/>
          <set_value name="$mfWareCount" exact="this.$homeStation.cargo.{$mfTrade.$Ware}.count"/>
          <get_ware_reservation object="this.$homeStation" ware="$mfTrade.$Ware" type="buy" virtual="false" result="$mfWareReservedTotal"/>
          <get_ware_reservation object="this.$homeStation" ware="$mfTrade.$Ware" type="buy" reserver="this.ship" virtual="false" result="$mfWareReservedSelf"/>
          <set_value name="$mfWareReservedOther" exact="[($mfWareReservedTotal - $mfWareReservedSelf), 0].max"/>
          <set_value name="$mfWareEffectiveCount" exact="[($mfWareCount - $mfWareReservedOther), 0].max"/>
          <set_value name="$mfWareFillPct" exact="if $mfWareTarget gt 0 then (($mfWareEffectiveCount * 100) / $mfWareTarget) else 0"/>
          <do_if value="$mfWareFillPct == $maxWareFillPct">
            <append_to_list name="$maxFillTrades" exact="$mfTrade"/>
          </do_if>
        </do_all>
        <do_if value="$maxFillTrades.count gt 0">
          <set_value name="$bestTradeCandidatePool" exact="$maxFillTrades"/>
        </do_if>
      </do_if>

      <run_script name="'lib.gt.score.trades'" result="$scoreResult">
        <param name="tradeList" value="$bestTradeCandidatePool"/>
      </run_script>
      <set_value name="$bestTrade" exact="$scoreResult.$BestTrade"/>

      <do_if value="$bestTrade == null">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': No sell trades found'" chance="this.$debugchance"/>

        <!-- If supply is enabled and not skipped, try opportunistic supply before waiting -->
        <do_if value="this.$supply and not this.$supplySkipped and not this.$supplyPriority and not (this.$mk1_opportunisticSupplyTried? and this.$mk1_opportunisticSupplyTried) and this.ship.cargo.count == 0">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': No sells â€” attempting opportunistic supply (one-shot before fallback)'" chance="this.$debugchance"/>
          <set_value name="this.$mk1_opportunisticSupplyTried" exact="true"/>
          <set_value name="this.$supplyPriority" exact="true"/>
          <resume label="main_loop"/>
        </do_if>

        <do_if value="this.$notifications ge 2">
          <show_notification text="'MK1 ' + this.ship.knownname + ': ' + {77000, 30201}.[this.$maxsell]" timeout="5s"/>
        </do_if>
        <!-- Short retry when supply is active (trade offers may not be populated yet), full wait otherwise -->
        <set_value name="$retryWait" exact="if this.$supply then 10s else this.$waitTimeNoTrades"/>
        <do_if value="this.$returnhome">
          <do_if value="this.$mk1_returnhomeReleased? and this.$mk1_returnhomeReleased">
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': No sells â€” return-home released state active, staying undocked and waiting ' + $retryWait + ' (supply=' + this.$supply + ')'" chance="this.$debugchance"/>
            <remove_value name="this.$mk1_opportunisticSupplyTried"/>
            <wait exact="$retryWait"/>
            <resume label="main_loop"/>
          </do_if>
          <do_else>
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': No sells â€” returning home to dock, then waiting ' + $retryWait + ' before retry (supply=' + this.$supply + ')'" chance="this.$debugchance"/>
            <remove_value name="this.$mk1_opportunisticSupplyTried"/>
            <set_value name="this.$mk1_pendingRetryWait" exact="$retryWait"/>
            <resume label="return_home_and_dock"/>
          </do_else>
        </do_if>
        <do_else>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Waiting ' + $retryWait + ' before retry (returnhome disabled, supply=' + this.$supply + ')'" chance="this.$debugchance"/>
          <remove_value name="this.$mk1_opportunisticSupplyTried"/>
          <wait exact="$retryWait"/>
          <resume label="main_loop"/>
        </do_else>
      </do_if>

      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Best export: ' + $bestTrade.$Ware.name + ' from ' + this.$homeStation.knownname + ' -> ' + (if $bestTrade.$SellStation? and $bestTrade.$SellStation.knownname? then @$bestTrade.$SellStation.knownname else '?') + ' (score: ' + $bestTrade.$Score + ', amount: ' + $bestTrade.$Amount + ', dist: ' + $bestTrade.$Distance + ')'" chance="this.$debugchance"/>

      <!-- ============================================================== -->
      <!-- STEP 6: Multi-ware loading (no-backtrack rule)                 -->
      <!-- ============================================================== -->
      <create_list name="$deliveryRoute"/>
      <append_to_list name="$deliveryRoute" exact="$bestTrade"/>

      <!-- Calculate how full cargo will be after primary trade -->
      <set_value name="$primaryVolume" exact="$bestTrade.$Amount * $bestTrade.$Ware.volume"/>
      <set_value name="$cargoCapacity" exact="this.ship.cargo.capacity.all"/>
      <set_value name="$fillPercent" exact="if $cargoCapacity gt 0 then ($primaryVolume * 100 / $cargoCapacity) else 100"/>

      <!-- Prefer a single full-cargo run over multi-ware chaining when possible. -->
      <do_if value="this.$allowmultitrade and $fillPercent lt this.$selltarget and $allTrades.count gt 1">
        <set_value name="$singleFullTrade" exact="null"/>
        <set_value name="$singleFullScore" exact="-1"/>
        <set_value name="$singleFullFillPct" exact="-1"/>
        <set_value name="$singleFullAmount" exact="0"/>
        <set_value name="$mk1SingleDiagStr" exact="''"/>
        <set_value name="$mk1SingleDiagMax" exact="30"/>
        <set_value name="$mk1SingleDiagCount" exact="0"/>
        <do_all exact="$allTrades.count" counter="$sfti">
          <set_value name="$singleCandidate" exact="$allTrades.{$sfti}"/>
          <set_value name="$singleLoadOfferAmount" exact="if $singleCandidate.$BuyOffer? and @$singleCandidate.$BuyOffer.exists then @$singleCandidate.$BuyOffer.offeramount.{this.ship} else 0"/>
          <do_if value="$singleLoadOfferAmount == null">
            <set_value name="$singleLoadOfferAmount" exact="0"/>
          </do_if>
          <set_value name="$singleSellOfferAmount" exact="if $singleCandidate.$SellOffer? and @$singleCandidate.$SellOffer.exists then @$singleCandidate.$SellOffer.offeramount.{this.ship} else 0"/>
          <do_if value="$singleSellOfferAmount == null">
            <set_value name="$singleSellOfferAmount" exact="0"/>
          </do_if>
          <set_value name="$singleQueueAmount" exact="[$singleCandidate.$Amount, $singleLoadOfferAmount, $singleSellOfferAmount].min"/>
          <do_if value="$singleCandidate.$Ware.volume gt 0">
            <set_value name="$singleMaxByVolume" exact="($cargoCapacity / $singleCandidate.$Ware.volume)i"/>
            <set_value name="$singleQueueAmount" exact="[$singleQueueAmount, $singleMaxByVolume].min"/>
          </do_if>
          <do_if value="$singleQueueAmount le 0">
            <continue/>
          </do_if>

          <set_value name="$singleCandidateVolume" exact="$singleQueueAmount * $singleCandidate.$Ware.volume"/>
          <set_value name="$singleCandidateFillPct" exact="if $cargoCapacity gt 0 then ($singleCandidateVolume * 100 / $cargoCapacity) else 100"/>
          <do_if value="this.$debuglevel ge 2 and $mk1SingleDiagCount lt $mk1SingleDiagMax">
            <set_value name="$mk1SingleDiagStr" exact="$mk1SingleDiagStr + (if $mk1SingleDiagCount gt 0 then ' | ' else '') + (if $singleCandidate.$Ware? and $singleCandidate.$Ware.name? then @$singleCandidate.$Ware.name else '?') + '@' + (if $singleCandidate.$BuyStation? and $singleCandidate.$BuyStation.knownname? then @$singleCandidate.$BuyStation.knownname else '?') + ':amt=' + $singleCandidate.$Amount + ',load=' + $singleLoadOfferAmount + ',sell=' + $singleSellOfferAmount + ',queue=' + $singleQueueAmount + ',fill=' + $singleCandidateFillPct + ',score=' + $singleCandidate.$Score"/>
            <set_value name="$mk1SingleDiagCount" operation="add"/>
          </do_if>
          <do_if value="$singleCandidateFillPct ge this.$selltarget">
            <do_if value="this.$sellselectionmode == 1">
              <set_value name="$singleCandidateTarget" exact="this.$homeStation.cargo.{$singleCandidate.$Ware}.target"/>
              <set_value name="$singleCandidateCount" exact="this.$homeStation.cargo.{$singleCandidate.$Ware}.count"/>
              <get_ware_reservation object="this.$homeStation" ware="$singleCandidate.$Ware" type="buy" virtual="false" result="$singleCandidateReservedTotal"/>
              <get_ware_reservation object="this.$homeStation" ware="$singleCandidate.$Ware" type="buy" reserver="this.ship" virtual="false" result="$singleCandidateReservedSelf"/>
              <set_value name="$singleCandidateReservedOther" exact="[($singleCandidateReservedTotal - $singleCandidateReservedSelf), 0].max"/>
              <set_value name="$singleCandidateEffectiveCount" exact="[($singleCandidateCount - $singleCandidateReservedOther), 0].max"/>
              <set_value name="$singleCandidateWareFillPct" exact="if $singleCandidateTarget gt 0 then (($singleCandidateEffectiveCount * 100) / $singleCandidateTarget) else 0"/>
              <do_if value="$singleCandidateWareFillPct gt $singleFullFillPct or ($singleCandidateWareFillPct == $singleFullFillPct and $singleCandidate.$Score gt $singleFullScore)">
                <set_value name="$singleFullTrade" exact="$singleCandidate"/>
                <set_value name="$singleFullScore" exact="$singleCandidate.$Score"/>
                <set_value name="$singleFullFillPct" exact="$singleCandidateWareFillPct"/>
                <set_value name="$singleFullAmount" exact="$singleQueueAmount"/>
              </do_if>
            </do_if>
            <do_elseif value="$singleCandidate.$Score gt $singleFullScore">
              <set_value name="$singleFullTrade" exact="$singleCandidate"/>
              <set_value name="$singleFullScore" exact="$singleCandidate.$Score"/>
              <set_value name="$singleFullAmount" exact="$singleQueueAmount"/>
            </do_elseif>
          </do_if>
        </do_all>
        <do_if value="this.$debuglevel ge 2">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': SINGLE_FULL_SCAN selltarget=' + this.$selltarget + ' baseFill=' + $fillPercent + ' candidates=' + $allTrades.count + ' scanned=' + $mk1SingleDiagCount + ' [' + $mk1SingleDiagStr + ']'" chance="this.$debugchance"/>
        </do_if>
        <do_if value="$singleFullTrade != null">
          <set_value name="$bestTrade" exact="$singleFullTrade"/>
          <set_value name="$bestTrade.$Amount" exact="$singleFullAmount"/>
          <set_value name="$primaryVolume" exact="$singleFullAmount * $bestTrade.$Ware.volume"/>
          <set_value name="$fillPercent" exact="if $cargoCapacity gt 0 then ($primaryVolume * 100 / $cargoCapacity) else 100"/>
          <set_value name="$deliveryRoute" exact="[]"/>
          <append_to_list name="$deliveryRoute" exact="$bestTrade"/>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Single full-cargo trade preferred over multi-ware: ' + $bestTrade.$Ware.name + ' from ' + this.$homeStation.knownname + ' -> ' + (if $bestTrade.$SellStation? and $bestTrade.$SellStation.knownname? then @$bestTrade.$SellStation.knownname else '?') + ' (fill: ' + $fillPercent + '%)'" chance="this.$debugchance"/>
        </do_if>
      </do_if>

      <do_if value="this.$allowmultitrade and this.$selltarget gt 0 and $fillPercent lt this.$selltarget and $allTrades.count gt 1">
        <set_value name="$mk1TargetVolume" exact="this.$selltarget * $cargoCapacity / 100"/>
        <set_value name="$mk1MinLegVolume" exact="$mk1TargetVolume / 3"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Cargo fill ' + $fillPercent + '% lt selltarget ' + this.$selltarget + '% â€” checking for secondary wares (MIN_LEG_VOLUME floor=' + $mk1MinLegVolume + ')'" chance="this.$debugchance"/>

        <!-- Try to add up to 2 more wares (max 3 total) -->
        <set_value name="$additionalCount" exact="0"/>
        <set_value name="$remainingRouteVolume" exact="[0, $cargoCapacity - $primaryVolume].max"/>
        <do_while value="$additionalCount lt 2 and $remainingRouteVolume gt 0">
          <set_value name="$bestSecondaryTrade" exact="null"/>
          <set_value name="$bestSecondaryAmount" exact="0"/>
          <set_value name="$bestSecondaryPlannedVolume" exact="0"/>
          <set_value name="$bestSecondaryFillPct" exact="-1"/>
          <set_value name="$bestSecondaryScore" exact="-1"/>

          <do_all exact="$allTrades.count" counter="$ti">
            <set_value name="$candidateTrade" exact="$allTrades.{$ti}"/>

            <!-- Allow any ware combination (including repeated wares).
                 Only skip exact duplicate offer-pairs already in the route,
                 otherwise we can chain the same ware to different destinations. -->
            <set_value name="$alreadyInRoute" exact="false"/>
            <do_all exact="$deliveryRoute.count" counter="$ri">
              <set_value name="$routeTrade" exact="$deliveryRoute.{$ri}"/>
              <do_if value="$routeTrade.$BuyOffer == $candidateTrade.$BuyOffer and $routeTrade.$SellOffer == $candidateTrade.$SellOffer">
                <set_value name="$alreadyInRoute" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="$alreadyInRoute">
              <continue/>
            </do_if>

            <!-- SELL-destination cluster tolerance:
                 candidate destination must be within backtrackTolerance jumps of
                 every already selected SELL destination in the route. -->
            <set_value name="$candidateSellSector" exact="if $candidateTrade.$SellSector? then $candidateTrade.$SellSector else (if $candidateTrade.$SellStation? then $candidateTrade.$SellStation.sector else null)"/>
            <do_if value="not $candidateSellSector?">
              <continue/>
            </do_if>
            <set_value name="$mk1ClusterReject" exact="false"/>
            <set_value name="$mk1ClusterFailDistance" exact="-1"/>
            <set_value name="$mk1ClusterFailRouteSector" exact="null"/>
            <do_all exact="$deliveryRoute.count" counter="$cri">
              <set_value name="$clusterRouteTrade" exact="$deliveryRoute.{$cri}"/>
              <set_value name="$routeSellSector" exact="if $clusterRouteTrade.$SellSector? then $clusterRouteTrade.$SellSector else (if $clusterRouteTrade.$SellStation? then $clusterRouteTrade.$SellStation.sector else null)"/>
              <do_if value="not $routeSellSector?">
                <set_value name="$mk1ClusterReject" exact="true"/>
                <break/>
              </do_if>
              <set_value name="$routeSectorDistance" exact="$routeSellSector.gatedistance.{$candidateSellSector}"/>
              <do_if value="$routeSectorDistance lt 0 or $routeSectorDistance gt this.$backtrackTolerance">
                <set_value name="$mk1ClusterReject" exact="true"/>
                <set_value name="$mk1ClusterFailDistance" exact="$routeSectorDistance"/>
                <set_value name="$mk1ClusterFailRouteSector" exact="$routeSellSector"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="$mk1ClusterReject">
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Secondary ' + $candidateTrade.$Ware.name + ' â†’ ' + $candidateTrade.$SellStation.knownname + ' REJECTED (cluster tolerance: ' + $mk1ClusterFailDistance + ' gt ' + this.$backtrackTolerance + ', routeSector=' + (if $mk1ClusterFailRouteSector? and $mk1ClusterFailRouteSector.knownname? then @$mk1ClusterFailRouteSector.knownname else '?') + ', candidateSector=' + (if $candidateSellSector? and $candidateSellSector.knownname? then @$candidateSellSector.knownname else '?') + ')'" chance="this.$debugchance"/>
              <continue/>
            </do_if>

            <!-- Max feasible load (includes home load offer; gate uses volume before buyer cap). -->
            <set_value name="$secondaryLoadOfferAmount" exact="if $candidateTrade.$BuyOffer? and @$candidateTrade.$BuyOffer.exists then @$candidateTrade.$BuyOffer.offeramount.{this.ship} else 0"/>
            <do_if value="$secondaryLoadOfferAmount == null">
              <set_value name="$secondaryLoadOfferAmount" exact="0"/>
            </do_if>
            <set_value name="$secondaryBuyerDemand" exact="if $candidateTrade.$SellOffer? and @$candidateTrade.$SellOffer.exists then @$candidateTrade.$SellOffer.offeramount.{this.ship} else 0"/>
            <do_if value="$secondaryBuyerDemand == null">
              <set_value name="$secondaryBuyerDemand" exact="0"/>
            </do_if>
            <set_value name="$remainingCargo" exact="this.ship.cargo.{$candidateTrade.$Ware}.free"/>
            <set_value name="$maxFeasibleAmount" exact="[$candidateTrade.$Amount, $secondaryLoadOfferAmount, $remainingCargo].min"/>
            <do_if value="$candidateTrade.$Ware.volume gt 0">
              <set_value name="$secondaryMaxByVolume" exact="($remainingRouteVolume / $candidateTrade.$Ware.volume)i"/>
              <set_value name="$maxFeasibleAmount" exact="[$maxFeasibleAmount, $secondaryMaxByVolume].min"/>
            </do_if>
            <do_if value="$maxFeasibleAmount le 0">
              <continue/>
            </do_if>
            <set_value name="$maxFeasibleVolume" exact="if $candidateTrade.$Ware.volume gt 0 then ($maxFeasibleAmount * $candidateTrade.$Ware.volume) else 0"/>
            <do_if value="$maxFeasibleVolume le 0">
              <continue/>
            </do_if>
            <set_value name="$plannedAmount" exact="[$maxFeasibleAmount, $secondaryBuyerDemand].min"/>
            <do_if value="$plannedAmount le 0">
              <continue/>
            </do_if>
            <set_value name="$plannedVolume" exact="$plannedAmount * $candidateTrade.$Ware.volume"/>

            <!-- MIN_LEG_VOLUME: each extra leg must carry at least selltarget/3 of hold volume. -->
            <do_if value="$mk1MinLegVolume gt 0 and $maxFeasibleVolume lt $mk1MinLegVolume">
              <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Secondary ' + $candidateTrade.$Ware.name + ' â†’ ' + $candidateTrade.$SellStation.knownname + ' REJECTED (MIN_LEG_VOLUME: feasibleVol=' + $maxFeasibleVolume + ' minLeg=' + $mk1MinLegVolume + ' selltarget=' + this.$selltarget + '%)'" chance="this.$debugchance"/>
              <continue/>
            </do_if>

            <!-- Secondary selection: highest planned volume among admitted candidates; mode tie-breaks. -->
            <do_if value="this.$sellselectionmode == 1">
              <set_value name="$candidateTarget" exact="this.$homeStation.cargo.{$candidateTrade.$Ware}.target"/>
              <set_value name="$candidateCount" exact="this.$homeStation.cargo.{$candidateTrade.$Ware}.count"/>
              <get_ware_reservation object="this.$homeStation" ware="$candidateTrade.$Ware" type="buy" virtual="false" result="$candidateReservedTotal"/>
              <get_ware_reservation object="this.$homeStation" ware="$candidateTrade.$Ware" type="buy" reserver="this.ship" virtual="false" result="$candidateReservedSelf"/>
              <set_value name="$candidateReservedOther" exact="[($candidateReservedTotal - $candidateReservedSelf), 0].max"/>
              <set_value name="$candidateEffectiveCount" exact="[($candidateCount - $candidateReservedOther), 0].max"/>
              <set_value name="$candidateFillPct" exact="if $candidateTarget gt 0 then (($candidateEffectiveCount * 100) / $candidateTarget) else 0"/>
              <do_if value="$plannedVolume gt $bestSecondaryPlannedVolume or ($plannedVolume == $bestSecondaryPlannedVolume and ($candidateFillPct gt $bestSecondaryFillPct or ($candidateFillPct == $bestSecondaryFillPct and $candidateTrade.$Score gt $bestSecondaryScore)))">
                <set_value name="$bestSecondaryTrade" exact="$candidateTrade"/>
                <set_value name="$bestSecondaryAmount" exact="$plannedAmount"/>
                <set_value name="$bestSecondaryPlannedVolume" exact="$plannedVolume"/>
                <set_value name="$bestSecondaryFillPct" exact="$candidateFillPct"/>
                <set_value name="$bestSecondaryScore" exact="$candidateTrade.$Score"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="$plannedVolume gt $bestSecondaryPlannedVolume or ($plannedVolume == $bestSecondaryPlannedVolume and $candidateTrade.$Score gt $bestSecondaryScore)">
                <set_value name="$bestSecondaryTrade" exact="$candidateTrade"/>
                <set_value name="$bestSecondaryAmount" exact="$plannedAmount"/>
                <set_value name="$bestSecondaryPlannedVolume" exact="$plannedVolume"/>
                <set_value name="$bestSecondaryScore" exact="$candidateTrade.$Score"/>
              </do_if>
            </do_else>
          </do_all>

          <do_if value="$bestSecondaryTrade == null">
            <break/>
          </do_if>

          <!-- Update selected secondary amount and add to route -->
          <set_value name="$bestSecondaryTrade.$Amount" exact="$bestSecondaryAmount"/>
          <append_to_list name="$deliveryRoute" exact="$bestSecondaryTrade"/>
          <set_value name="$additionalCount" operation="add"/>
          <do_if value="$bestSecondaryTrade.$Ware.volume gt 0">
            <set_value name="$remainingRouteVolume" exact="[0, $remainingRouteVolume - ($bestSecondaryAmount * $bestSecondaryTrade.$Ware.volume)].max"/>
          </do_if>
          <set_value name="$currentRouteFillPct" exact="if $cargoCapacity gt 0 then ((($cargoCapacity - $remainingRouteVolume) * 100) / $cargoCapacity) else 100"/>

          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Secondary ' + $bestSecondaryTrade.$Ware.name + ' â†’ ' + $bestSecondaryTrade.$SellStation.knownname + ' ADMIT_MIN_LEG SELECT_FILL (amount: ' + $bestSecondaryAmount + ', vol: ' + $bestSecondaryPlannedVolume + ')'" chance="this.$debugchance"/>
          <!-- Route builder is "up to 3 trades":
               stop early once selltarget is reached, so 2 trades can be enough. -->
          <do_if value="$currentRouteFillPct ge this.$selltarget">
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Secondary route reached selltarget (' + $currentRouteFillPct + '% >= ' + this.$selltarget + '%) â€” stopping route expansion'" chance="this.$debugchance"/>
            <break/>
          </do_if>
        </do_while>
      </do_if>

      <do_if value="$deliveryRoute.count gt 1 and this.$notifications ge 2">
        <show_notification text="'MK1 ' + this.ship.knownname + ': ' + {77000, 30207}.[$deliveryRoute.count, $deliveryRoute.count]" timeout="5s"/>
      </do_if>

      <!-- Hard selltarget rule:
           evaluate the actually queueable load amount (post offeramount clamps).
           If we cannot meet the configured minimum fill %, skip this cycle. -->
      <set_value name="$plannedLoadVolume" exact="0"/>
      <do_all exact="$deliveryRoute.count" counter="$pri">
        <set_value name="$rt" exact="$deliveryRoute.{$pri}"/>
        <do_if value="$rt.$BuyOffer? and @$rt.$BuyOffer.exists and $rt.$SellOffer? and @$rt.$SellOffer.exists and $rt.$SellOffer.available and $rt.$BuyOffer.available">
          <set_value name="$loadOfferAmount" exact="@$rt.$BuyOffer.offeramount.{this.ship}"/>
          <do_if value="$loadOfferAmount == null">
            <set_value name="$loadOfferAmount" exact="0"/>
          </do_if>
          <set_value name="$sellOfferAmount" exact="@$rt.$SellOffer.offeramount.{this.ship}"/>
          <do_if value="$sellOfferAmount == null">
            <set_value name="$sellOfferAmount" exact="0"/>
          </do_if>
          <set_value name="$tradePairAmount" exact="[$rt.$Amount, $loadOfferAmount, $sellOfferAmount].min"/>
          <do_if value="$tradePairAmount gt 0 and $rt.$Ware.volume gt 0">
            <set_value name="$plannedLoadVolume" exact="$plannedLoadVolume + ($tradePairAmount * $rt.$Ware.volume)"/>
          </do_if>
        </do_if>
      </do_all>
      <set_value name="$plannedFillPercent" exact="if this.ship.cargo.capacity.all gt 0 then ($plannedLoadVolume * 100 / this.ship.cargo.capacity.all) else 100"/>
      <do_if value="$plannedFillPercent lt this.$selltarget">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Hard selltarget check failed for best trade: achievable fill=' + $plannedFillPercent + '% lt minimum=' + this.$selltarget + '%; trying next candidate'" chance="this.$debugchance"/>
        <!-- Remove current best candidate and re-score alternatives in the same cycle.
             This prevents repeatedly reselecting the same underfilled best offer. -->
        <create_list name="$remainingTrades"/>
        <do_all exact="$allTrades.count" counter="$hfi">
          <set_value name="$hTrade" exact="$allTrades.{$hfi}"/>
          <do_if value="$hTrade.$Ware == $bestTrade.$Ware and $hTrade.$BuyStation == $bestTrade.$BuyStation and $hTrade.$SellStation == $bestTrade.$SellStation">
            <continue/>
          </do_if>
          <append_to_list name="$remainingTrades" exact="$hTrade"/>
        </do_all>
        <do_if value="$remainingTrades.count gt 0">
          <set_value name="$allTrades" exact="$remainingTrades"/>
          <resume label="select_best_trade"/>
        </do_if>
        <set_value name="$retryWait" exact="if this.$supply then 10s else this.$waitTimeNoTrades"/>
        <do_if value="this.$returnhome">
          <do_if value="this.$mk1_returnhomeReleased? and this.$mk1_returnhomeReleased">
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Hard selltarget failed for all candidates â€” return-home released state active, staying undocked and waiting ' + $retryWait" chance="this.$debugchance"/>
            <wait exact="$retryWait"/>
            <resume label="main_loop"/>
          </do_if>
          <do_else>
            <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Hard selltarget failed for all candidates â€” returning home to dock, then waiting ' + $retryWait + ' before retry'" chance="this.$debugchance"/>
            <set_value name="this.$mk1_pendingRetryWait" exact="$retryWait"/>
            <resume label="return_home_and_dock"/>
          </do_else>
        </do_if>
        <do_else>
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Hard selltarget failed for all candidates â€” waiting ' + $retryWait + ' before retry (returnhome disabled)'" chance="this.$debugchance"/>
          <wait exact="$retryWait"/>
          <resume label="main_loop"/>
        </do_else>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 7: Reserve trades (fleet coordination)                    -->
      <!-- ============================================================== -->
      <do_if value="this.$fleetcoordination and global.$GT_TradeReservations?">
        <do_all exact="$deliveryRoute.count" counter="$ri">
          <set_value name="$rt" exact="$deliveryRoute.{$ri}"/>
          <set_value name="$tradeKey" exact="'' + $rt.$Ware + '_' + $rt.$BuyStation"/>
          <set_value name="global.$GT_TradeReservations.{$tradeKey}" exact="this.ship"/>
        </do_all>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 8/9: Queue paired load+sell orders safely                 -->
      <!-- ============================================================== -->
      <set_command_action commandaction="commandaction.flying"/>

      <!-- Build queueable trade set once, then queue in two phases:
           create all SELL orders first and all LOAD orders second.
           With immediate="true" (LIFO), this executes as LOAD phase then SELL phase,
           avoiding alternating buy/sell mini-runs while still preventing sell-before-load. -->
      <create_list name="$queueableTrades"/>
      <set_value name="$mk1QueueRemainingVolume" exact="this.ship.cargo.capacity.all"/>
      <do_all exact="$deliveryRoute.count" counter="$ri">
        <set_value name="$rt" exact="$deliveryRoute.{$ri}"/>
        <do_if value="$rt.$BuyOffer? and @$rt.$BuyOffer.exists and $rt.$SellOffer? and @$rt.$SellOffer.exists and $rt.$SellOffer.available and $rt.$BuyOffer.available">
          <set_value name="$loadOfferAmount" exact="@$rt.$BuyOffer.offeramount.{this.ship}"/>
          <do_if value="$loadOfferAmount == null">
            <set_value name="$loadOfferAmount" exact="0"/>
          </do_if>

          <set_value name="$sellOfferAmount" exact="@$rt.$SellOffer.offeramount.{this.ship}"/>
          <do_if value="$sellOfferAmount == null">
            <set_value name="$sellOfferAmount" exact="0"/>
          </do_if>

          <set_value name="$tradePairAmount" exact="[$rt.$Amount, $loadOfferAmount, $sellOfferAmount].min"/>
          <do_if value="$rt.$Ware.volume gt 0">
            <set_value name="$mk1MaxByRemainingVolume" exact="($mk1QueueRemainingVolume / $rt.$Ware.volume)i"/>
            <set_value name="$tradePairAmount" exact="[$tradePairAmount, $mk1MaxByRemainingVolume].min"/>
          </do_if>
          <do_if value="$tradePairAmount gt 0">
            <set_value name="$mk1QueueDockOk" exact="true"/>
            <do_if value="$rt.$BuyStation? and $rt.$BuyStation.exists">
              <run_script name="'lib.gt.dockcheck'" result="$mk1QueueDockCheck">
                <param name="ship" value="this.ship"/>
                <param name="station" value="$rt.$BuyStation"/>
                <param name="purpose" value="'trade'"/>
              </run_script>
              <do_if value="not $mk1QueueDockCheck.$CanDock">
                <set_value name="$mk1QueueDockOk" exact="false"/>
                <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Queue skip - no trading dock at ' + $rt.$BuyStation.knownname + ' for ' + $rt.$Ware.name" chance="this.$debugchance"/>
              </do_if>
            </do_if>
            <do_if value="$mk1QueueDockOk and $rt.$SellStation? and $rt.$SellStation.exists">
              <set_value name="$mk1QueueNeedSellDockCheck" exact="true"/>
              <do_if value="$rt.$BuyStation? and $rt.$BuyStation.exists and $rt.$BuyStation == $rt.$SellStation">
                <set_value name="$mk1QueueNeedSellDockCheck" exact="false"/>
              </do_if>
              <do_if value="$mk1QueueNeedSellDockCheck">
                <run_script name="'lib.gt.dockcheck'" result="$mk1QueueDockCheck">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$rt.$SellStation"/>
                  <param name="purpose" value="'trade'"/>
                </run_script>
                <do_if value="not $mk1QueueDockCheck.$CanDock">
                  <set_value name="$mk1QueueDockOk" exact="false"/>
                  <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Queue skip - no trading dock at ' + $rt.$SellStation.knownname + ' for ' + $rt.$Ware.name" chance="this.$debugchance"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$mk1QueueDockOk">
            <set_value name="$rt.$QueuedAmount" exact="$tradePairAmount"/>
            <append_to_list name="$queueableTrades" exact="$rt"/>
            <do_if value="$rt.$Ware.volume gt 0">
              <set_value name="$mk1QueueRemainingVolume" exact="[0, $mk1QueueRemainingVolume - ($tradePairAmount * $rt.$Ware.volume)].max"/>
            </do_if>
            </do_if>
          </do_if>
        </do_if>
      </do_all>
      <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield after queue dock filter"/>

      <!-- Execution-order compaction by SELL destination sector:
           1) collapse A->B->A into grouped sector blocks
           2) order sector blocks by increasing home->sector distance so routes
              progress outward (e.g. C->D->E from home A), not E->C->D. -->
      <create_list name="$mk1SectorOrder"/>
      <do_all exact="$queueableTrades.count" counter="$qoi">
        <set_value name="$qot" exact="$queueableTrades.{$qoi}"/>
        <set_value name="$qos" exact="if $qot.$SellSector? then $qot.$SellSector else (if $qot.$SellStation? then $qot.$SellStation.sector else (if $qot.$SellOffer? and $qot.$SellOffer.owner? then $qot.$SellOffer.owner.sector else null))"/>
        <do_if value="$qos?">
          <set_value name="$mk1SeenSector" exact="false"/>
          <do_all exact="$mk1SectorOrder.count" counter="$sci">
            <do_if value="$mk1SectorOrder.{$sci} == $qos">
              <set_value name="$mk1SeenSector" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $mk1SeenSector">
            <append_to_list name="$mk1SectorOrder" exact="$qos"/>
          </do_if>
        </do_if>
      </do_all>

      <set_value name="$mk1HomeSector" exact="if this.$homeStation? then this.$homeStation.sector else this.ship.sector"/>
      <create_list name="$mk1SectorOrderSorted"/>
      <do_if value="$mk1HomeSector? and $mk1SectorOrder.count gt 1">
        <do_while value="$mk1SectorOrderSorted.count lt $mk1SectorOrder.count">
          <set_value name="$mk1BestSector" exact="null"/>
          <set_value name="$mk1BestDistance" exact="999999"/>
          <do_all exact="$mk1SectorOrder.count" counter="$ssoi">
            <set_value name="$mk1SectorCandidate" exact="$mk1SectorOrder.{$ssoi}"/>
            <set_value name="$mk1AlreadySorted" exact="false"/>
            <do_all exact="$mk1SectorOrderSorted.count" counter="$ssj">
              <do_if value="$mk1SectorOrderSorted.{$ssj} == $mk1SectorCandidate">
                <set_value name="$mk1AlreadySorted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="$mk1AlreadySorted">
              <continue/>
            </do_if>
            <set_value name="$mk1SectorDistance" exact="$mk1HomeSector.gatedistance.{$mk1SectorCandidate}"/>
            <do_if value="$mk1SectorDistance lt 0">
              <set_value name="$mk1SectorDistance" exact="999999"/>
            </do_if>
            <do_if value="not $mk1BestSector? or $mk1SectorDistance lt $mk1BestDistance">
              <set_value name="$mk1BestSector" exact="$mk1SectorCandidate"/>
              <set_value name="$mk1BestDistance" exact="$mk1SectorDistance"/>
            </do_if>
          </do_all>
          <do_if value="$mk1BestSector?">
            <append_to_list name="$mk1SectorOrderSorted" exact="$mk1BestSector"/>
          </do_if>
          <do_else>
            <break/>
          </do_else>
        </do_while>
      </do_if>
      <do_else>
        <set_value name="$mk1SectorOrderSorted" exact="$mk1SectorOrder"/>
      </do_else>

      <create_list name="$mk1QueueCompacted"/>
      <do_all exact="$mk1SectorOrderSorted.count" counter="$soi">
        <set_value name="$sectorKey" exact="$mk1SectorOrderSorted.{$soi}"/>
        <do_all exact="$queueableTrades.count" counter="$qci">
          <set_value name="$qct" exact="$queueableTrades.{$qci}"/>
          <set_value name="$qctSector" exact="if $qct.$SellSector? then $qct.$SellSector else (if $qct.$SellStation? then $qct.$SellStation.sector else (if $qct.$SellOffer? and $qct.$SellOffer.owner? then $qct.$SellOffer.owner.sector else null))"/>
          <do_if value="$qctSector? and $qctSector == $sectorKey">
            <append_to_list name="$mk1QueueCompacted" exact="$qct"/>
          </do_if>
        </do_all>
      </do_all>
      <do_if value="$mk1QueueCompacted.count == $queueableTrades.count">
        <set_value name="$queueableTrades" exact="$mk1QueueCompacted"/>
      </do_if>

      <set_value name="$mk1RoutePlanStr" exact="''"/>
      <set_value name="$mk1RoutePlanMax" exact="12"/>
      <do_all exact="$queueableTrades.count" counter="$rpi">
        <do_if value="$rpi gt $mk1RoutePlanMax">
          <set_value name="$mk1RoutePlanStr" exact="$mk1RoutePlanStr + ' | ...+' + ($queueableTrades.count - $mk1RoutePlanMax)"/>
          <break/>
        </do_if>
        <set_value name="$rpTrade" exact="$queueableTrades.{$rpi}"/>
        <set_value name="$mk1RoutePlanStr" exact="$mk1RoutePlanStr + (if $rpi gt 1 then ' | ' else '') + (if $rpTrade.$Ware? and $rpTrade.$Ware.name? then @$rpTrade.$Ware.name else '?') + '->' + (if $rpTrade.$SellStation? and $rpTrade.$SellStation.knownname? then @$rpTrade.$SellStation.knownname else '?') + '(' + $rpTrade.$QueuedAmount + ')'"/>
      </do_all>
      <set_value name="this.$mk1_lastRoutePlanSig" exact="'count=' + $queueableTrades.count + ' [' + $mk1RoutePlanStr + ']'"/>
      <do_if value="this.$debuglevel ge 1">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': ROUTE_PLAN ' + this.$mk1_lastRoutePlanSig" chance="this.$debugchance"/>
      </do_if>

      <!-- Phase 1: create all SELL orders -->
      <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}? and $queueableTrades.count gt 0">
        <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
        <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
          <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
        </do_if>
      </do_if>
      <do_if value="$queueableTrades.count gt 0">
        <remove_value name="this.$mk1_dockedSince"/>
        <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
          <remove_value name="global.$GT_MK1DockedSince.{this.ship}"/>
        </do_if>
        <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
          <remove_value name="global.$GT_MK1ReturnHomeReleased.{this.ship}"/>
        </do_if>
        <remove_value name="this.$mk1_returnhomeReleased"/>
        <remove_value name="this.$mk1_opportunisticSupplyTried"/>
      </do_if>
      <do_all exact="$queueableTrades.count" counter="$qsi">
        <set_value name="$qt" exact="$queueableTrades.{$qsi}"/>
        <create_trade_order object="this.ship" tradeoffer="$qt.$SellOffer" amount="$qt.$QueuedAmount" immediate="true" internal="false"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Queued SELL ' + $qt.$QueuedAmount + ' ' + $qt.$Ware.name + ' to ' + $qt.$SellStation.knownname" chance="this.$debugchance"/>
      </do_all>

      <!-- Phase 2: create all LOAD orders (executed first due to LIFO immediate queue) -->
      <set_value name="$mk1CycleProfitRaw" exact="0"/>
      <set_value name="$mk1CycleLegCount" exact="0"/>
      <set_value name="$mk1QueueMoneyRawTotal" exact="0"/>
      <set_value name="$mk1QueueAmountTotal" exact="0"/>
      <set_value name="$mk1MultiTradeLegs" exact="[]"/>
      <do_all exact="$queueableTrades.count" counter="$qli">
        <set_value name="$qt" exact="$queueableTrades.{$qli}"/>
        <create_trade_order object="this.ship" tradeoffer="$qt.$BuyOffer" amount="$qt.$QueuedAmount" immediate="true" internal="false"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Queued LOAD ' + $qt.$QueuedAmount + ' ' + $qt.$Ware.name + ' from ' + $qt.$BuyOffer.owner.knownname" chance="this.$debugchance"/>
        <do_if value="this.$logbookentries">
          <!-- MK1 export sell queue-time logbook (single leg uses 3103; multitrade summary uses 3113). -->
          <set_value name="$mk1QueuedAmount" exact="if $qt.$QueuedAmount? and $qt.$QueuedAmount != null then $qt.$QueuedAmount else 0"/>
          <do_if value="$mk1QueuedAmount gt 0 and $qt.$SellOffer != null and $qt.$BuyOffer != null">
            <!-- Use trade-match snapshot prices for stable per-leg P/L reporting.
                 Live offers can move before queueing and would skew displayed profit. -->
            <set_value name="$mk1BuyPriceRaw" exact="if $qt.$BuyPrice? and $qt.$BuyPrice != null then $qt.$BuyPrice else (if $qt.$BuyOffer.unitprice? and $qt.$BuyOffer.unitprice != null then $qt.$BuyOffer.unitprice else 0)"/>
            <set_value name="$mk1SellPriceRaw" exact="if $qt.$SellPrice? and $qt.$SellPrice != null then $qt.$SellPrice else (if $qt.$SellOffer.unitprice? and $qt.$SellOffer.unitprice != null then $qt.$SellOffer.unitprice else 0)"/>
            <set_value name="$mk1ProfitRaw" exact="($mk1SellPriceRaw - $mk1BuyPriceRaw) * $mk1QueuedAmount"/>
            <set_value name="$mk1MoneyRaw" exact="-($mk1BuyPriceRaw * $mk1QueuedAmount)"/>
            <set_value name="$mk1CycleProfitRaw" exact="$mk1CycleProfitRaw + $mk1ProfitRaw"/>
            <set_value name="$mk1CycleLegCount" exact="$mk1CycleLegCount + 1"/>
            <set_value name="$mk1QueueMoneyRawTotal" exact="$mk1QueueMoneyRawTotal + $mk1MoneyRaw"/>
            <set_value name="$mk1QueueAmountTotal" exact="$mk1QueueAmountTotal + $mk1QueuedAmount"/>
            <do_if value="$queueableTrades.count gt 1">
              <set_value name="$mk1BuyStationObj" exact="if $qt.$BuyStation? and $qt.$BuyStation.exists then $qt.$BuyStation else (if $qt.$BuyOffer? and $qt.$BuyOffer.owner? and $qt.$BuyOffer.owner.exists then $qt.$BuyOffer.owner else null)"/>
              <set_value name="$mk1SellStationObj" exact="if $qt.$SellStation? and $qt.$SellStation.exists then $qt.$SellStation else (if $qt.$SellOffer? and $qt.$SellOffer.owner? and $qt.$SellOffer.owner.exists then $qt.$SellOffer.owner else null)"/>
              <append_to_list name="$mk1MultiTradeLegs" exact="table[
                $Amount = $mk1QueuedAmount,
                $Ware = $qt.$Ware,
                $BuyPriceRaw = $mk1BuyPriceRaw,
                $SellPriceRaw = $mk1SellPriceRaw,
                $BuyStation = $mk1BuyStationObj,
                $SellStation = $mk1SellStationObj
              ]"/>
            </do_if>
            <do_else>
              <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
                $Ship = this.ship,
                $BuyOffer = $qt.$BuyOffer,
                $SellOffer = $qt.$SellOffer,
                $Amount = $mk1QueuedAmount,
                $Profit = $mk1ProfitRaw,
                $BuyPriceRaw = $mk1BuyPriceRaw,
                $SellPriceRaw = $mk1SellPriceRaw,
                $MoneyRaw = $mk1MoneyRaw,
                $BuyPrice = $mk1BuyPriceRaw / 100,
                $SellPrice = $mk1SellPriceRaw / 100,
                $IsMk1Export = true,
                $IsSellOnly = false,
                $SearchPipeline = 'normal'
              ]"/>
            </do_else>
          </do_if>
        </do_if>
      </do_all>
      <do_if value="$queueableTrades.count gt 0 and this.$allowillegal and this.$enforceRouteIllegalLegality">
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{this.ship}?">
          <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
        </do_if>
        <set_value name="$mk1PrimaryTrade" exact="$queueableTrades.{1}"/>
        <set_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy" exact="table[
          $AllowIllegal = this.$allowillegal,
          $EnforceRouteIllegalLegality = this.$enforceRouteIllegalLegality,
          $Ware = $mk1PrimaryTrade.$Ware,
          $BuySector = if $mk1PrimaryTrade.$BuySector? then $mk1PrimaryTrade.$BuySector else (if $mk1PrimaryTrade.$BuyOffer? and $mk1PrimaryTrade.$BuyOffer.owner? then @$mk1PrimaryTrade.$BuyOffer.owner.sector else null),
          $SellSector = if $mk1PrimaryTrade.$SellSector? then $mk1PrimaryTrade.$SellSector else (if $mk1PrimaryTrade.$SellOffer? and $mk1PrimaryTrade.$SellOffer.owner? then @$mk1PrimaryTrade.$SellOffer.owner.sector else null),
          $HomeSector = this.$homeStation.sector,
          $RouteStart = this.ship.sector,
          $Leg = 'buy',
          $LogbookEntries = this.$logbookentries,
          $SetAt = player.age
        ]"/>
      </do_if>
      <do_if value="this.$logbookentries and $queueableTrades.count gt 1 and $mk1CycleLegCount gt 0">
        <set_value name="$mk1SummaryBuyOffer" exact="null"/>
        <set_value name="$mk1SummarySellOffer" exact="null"/>
        <do_if value="$queueableTrades.{1}?">
          <set_value name="$mk1SummaryBuyOffer" exact="$queueableTrades.{1}.$BuyOffer"/>
          <set_value name="$mk1SummarySellOffer" exact="$queueableTrades.{1}.$SellOffer"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
          $Ship = this.ship,
          $BuyOffer = $mk1SummaryBuyOffer,
          $SellOffer = $mk1SummarySellOffer,
          $Amount = $mk1QueueAmountTotal,
          $Profit = $mk1CycleProfitRaw,
          $BuyPriceRaw = 0,
          $SellPriceRaw = 0,
          $MoneyRaw = $mk1QueueMoneyRawTotal,
          $BuyPrice = 0,
          $SellPrice = 0,
          $IsMk1Export = true,
          $IsSellOnly = false,
          $IsMultiTrade = true,
          $MultiTradeLegs = $mk1MultiTradeLegs,
          $SearchPipeline = 'normal'
        ]"/>
      </do_if>

      <!-- Wait for all trade orders to execute -->
      <do_while value="this.ship.orders.count gt 0">
        <wait exact="5s">
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship"/>
            </conditions>
          </interrupt>
        </wait>
      </do_while>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
        <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
      </do_if>

      <!-- ============================================================== -->
      <!-- STEP 10: Post-trade â€” log, XP, release reservations            -->
      <!-- ============================================================== -->

      <!-- Release fleet reservations -->
      <do_if value="this.$fleetcoordination and global.$GT_TradeReservations?">
        <do_all exact="$deliveryRoute.count" counter="$ri">
          <set_value name="$rt" exact="$deliveryRoute.{$ri}"/>
          <set_value name="$tradeKey" exact="'' + $rt.$Ware + '_' + $rt.$BuyStation"/>
          <do_if value="global.$GT_TradeReservations.{$tradeKey}? and global.$GT_TradeReservations.{$tradeKey} == this.ship">
            <remove_value name="global.$GT_TradeReservations.{$tradeKey}"/>
          </do_if>
        </do_all>
      </do_if>

      <!-- Logbook entry (via signal, same pattern as MK3) -->
      <do_if value="this.$logbookentries">
        <set_value name="$mk1CycleLogProfitRaw" exact="0"/>
        <do_all exact="$deliveryRoute.count" counter="$ri">
          <set_value name="$rt" exact="$deliveryRoute.{$ri}"/>
          <set_value name="$mk1RouteAmount" exact="if $rt.$QueuedAmount? and $rt.$QueuedAmount != null then $rt.$QueuedAmount else $rt.$Amount"/>
          <set_value name="$mk1RouteBuyPriceRaw" exact="if $rt.$BuyPrice? and $rt.$BuyPrice != null then $rt.$BuyPrice else (if $rt.$BuyOffer? and $rt.$BuyOffer.unitprice? and $rt.$BuyOffer.unitprice != null then $rt.$BuyOffer.unitprice else 0)"/>
          <set_value name="$mk1RouteSellPriceRaw" exact="if $rt.$SellPrice? and $rt.$SellPrice != null then $rt.$SellPrice else (if $rt.$SellOffer? and $rt.$SellOffer.unitprice? and $rt.$SellOffer.unitprice != null then $rt.$SellOffer.unitprice else 0)"/>
          <set_value name="$mk1RouteProfitRaw" exact="($mk1RouteSellPriceRaw - $mk1RouteBuyPriceRaw) * $mk1RouteAmount"/>
          <set_value name="$mk1CycleLogProfitRaw" exact="$mk1CycleLogProfitRaw + $mk1RouteProfitRaw"/>
          <set_value name="$logMsg" exact="'Trip ' + $ri + '/' + $deliveryRoute.count + ': ' + $mk1RouteAmount + ' ' + $rt.$Ware.name + ' ' + (if $rt.$BuyOffer? and $rt.$BuyOffer.owner? then 'from ' + $rt.$BuyOffer.owner.knownname + ' to ' else '') + $rt.$BuyStation.knownname + ' | buy ' + ($mk1RouteBuyPriceRaw / 100) + ' Cr -> sell ' + ($mk1RouteSellPriceRaw / 100) + ' Cr | profit ' + ($mk1RouteProfitRaw / 100) + ' Cr'"/>
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logMsg,
            $Category = 'upkeep',
            $Title = 'MK1 Sale: ' + $rt.$Ware.name,
            $Object = this.ship,
            $CheckGlobalSettings = false
          ]"/>
        </do_all>
        <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
          $Message = 'MK1 route summary: ' + $deliveryRoute.count + ' trips, total profit ' + ($mk1CycleLogProfitRaw / 100) + ' Cr',
          $Category = 'upkeep',
          $Title = 'MK1 Route Summary',
          $Object = this.ship,
          $CheckGlobalSettings = false
        ]"/>
      </do_if>

      <!-- Signal XP update (one per completed cycle, same as MK3) -->
      <do_if value="this.ship.pilot">
        <signal_objects object="player.galaxy" param="'GT_Update_Pilot_XP'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot
        ]"/>
      </do_if>

      <!-- Notification -->
      <do_if value="this.$notifications ge 1 and $deliveryRoute.count gt 0">
        <set_value name="$firstTrade" exact="$deliveryRoute.{1}"/>
        <set_value name="$mk1NotifyTotalProfitRaw" exact="if $mk1CycleProfitRaw? then $mk1CycleProfitRaw else 0"/>
        <show_notification text="'MK1 ' + this.ship.knownname + ': ' + {77000, 30206}.[$firstTrade.$Amount, $firstTrade.$Ware.name, $firstTrade.$BuyStation.knownname, ($firstTrade.$UnitProfit * $firstTrade.$Amount), ($firstTrade.$UnitProfit * $firstTrade.$Amount)] + ' | trips=' + $deliveryRoute.count + ', total=' + ($mk1NotifyTotalProfitRaw / 100) + ' Cr'" timeout="5s"/>
      </do_if>

      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': === SELL CYCLE COMPLETE === Delivered ' + $deliveryRoute.count + ' trades'" chance="this.$debugchance"/>

      <!-- ============================================================== -->
      <!-- STEP 11: Opportunistic supply (after sell, if enabled)         -->
      <!-- ============================================================== -->
      <do_if value="this.$supply and not this.$supplySkipped and not this.$supplyPriority and this.ship.cargo.count == 0">
        <!-- Check if any resource is below target (not threshold â€” just below target) -->
        <set_value name="$needsSupply" exact="false"/>
        <set_value name="$stationResources" exact="this.$homeStation.resources.list"/>
        <do_if value="$stationResources.count gt 0 and this.$homeStation.money gt 0">
          <do_all exact="$stationResources.count" counter="$ri">
            <set_value name="$res" exact="$stationResources.{$ri}"/>
            <do_if value="this.$homeStation.cargo.{$res}.count lt this.$homeStation.cargo.{$res}.target">
              <set_value name="$needsSupply" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="$needsSupply">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Attempting opportunistic supply after sell cycle'" chance="this.$debugchance"/>
          <!-- Trigger supply phase on next iteration by setting the flag -->
          <set_value name="this.$supplyPriority" exact="true"/>
          <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield"/>
          <resume label="main_loop"/>
        </do_if>
      </do_if>

      <do_if value="this.$returnhome">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Post-cycle complete â€” returning to home station to dock'" chance="this.$debugchance"/>
        <resume label="return_home_and_dock"/>
      </do_if>
      <do_else>
        <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before next cycle (returnhome disabled)"/>
        <resume label="main_loop"/>
      </do_else>

      <label name="return_home_and_dock"/>

      <!-- Keep MK1 parked at home between cycles; trade orders will undock the ship naturally when needed.
           Return-home is delegated to dedicated DockAndReturnHome order for visible queued pathing. -->
      <set_value name="$mk1AlreadyDockedHome" exact="(this.ship.dock and this.ship.dock.container == this.$homeStation) or (this.ship.parkedat and ((this.ship.parkedat == this.$homeStation) or this.ship.parkedat.hascontext.{this.$homeStation}))"/>
      <do_if value="not $mk1AlreadyDockedHome">
        <remove_value name="this.$mk1_dockedSince"/>
        <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
          <remove_value name="global.$GT_MK1DockedSince.{this.ship}"/>
        </do_if>
        <run_script name="'lib.gt.dockcheck'" result="$mk1HomeDockCheck">
          <param name="ship" value="this.ship"/>
          <param name="station" value="this.$homeStation"/>
          <param name="purpose" value="'trade'"/>
          <param name="allowPlayerOnly" value="true"/>
        </run_script>
        <do_if value="not $mk1HomeDockCheck.$CanDock">
          <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': return-home skipped â€” no operational trading dock at ' + this.$homeStation.knownname + ' (size=' + this.ship.docksize + ')'" chance="this.$debugchance"/>
          <set_command_action commandaction="commandaction.orderfailed"/>
          <do_if value="not this.$mk1_pendingRetryWait? or this.$mk1_pendingRetryWait le 0s">
            <set_value name="this.$mk1_pendingRetryWait" exact="this.$waitTimeNoTrades"/>
          </do_if>
          <wait exact="this.$mk1_pendingRetryWait"/>
          <remove_value name="this.$mk1_pendingRetryWait"/>
          <resume label="main_loop"/>
        </do_if>
        <create_order object="this.ship" id="'DockAndReturnHome'" immediate="true">
          <param name="destination" value="this.$homeStation"/>
          <param name="debugchance" value="this.$debugchance"/>
        </create_order>
        <return/>
      </do_if>
      <do_if value="not this.$mk1_dockedSince?">
        <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
          <set_value name="this.$mk1_dockedSince" exact="global.$GT_MK1DockedSince.{this.ship}"/>
        </do_if>
        <do_else>
          <set_value name="this.$mk1_dockedSince" exact="player.age"/>
          <do_if value="not global.$GT_MK1DockedSince?">
            <set_value name="global.$GT_MK1DockedSince" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_MK1DockedSince.{this.ship}" exact="this.$mk1_dockedSince"/>
        </do_else>
      </do_if>

      <set_command_action commandaction="commandaction.searchingtrades"/>
      <do_if value="this.$mk1_pendingRetryWait? and this.$mk1_pendingRetryWait gt 0s">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Docked idle wait ' + this.$mk1_pendingRetryWait + ' before next search'" chance="this.$debugchance"/>
        <wait exact="this.$mk1_pendingRetryWait"/>
        <remove_value name="this.$mk1_pendingRetryWait"/>
      </do_if>
      <do_if value="this.$returnhome and (not this.$mk1_returnhomeReleased? or not this.$mk1_returnhomeReleased) and global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}? and global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}? and player.age - global.$GT_MK1DockedSince.{this.ship} ge 60s">
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': Docked without trades for 60s â€” forcing undock retry to free docking port'" chance="this.$debugchance"/>
        <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}?">
          <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
        </do_if>
        <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
          <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
        </do_if>
        <!-- Persist released-undocked state BEFORE creating immediate Undock order.
             Immediate order handoff can abort this AI context before later lines execute. -->
        <do_if value="not global.$GT_MK1ReturnHomeReleased?">
          <set_value name="global.$GT_MK1ReturnHomeReleased" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_MK1ReturnHomeReleased.{this.ship}" exact="true"/>
        <set_value name="this.$mk1_returnhomeReleased" exact="true"/>
        <create_order object="this.ship" id="'Undock'" immediate="true"/>
        <wait max="30s">
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship"/>
            </conditions>
          </interrupt>
        </wait>
        <remove_value name="this.$mk1_dockedSince"/>
        <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
          <remove_value name="global.$GT_MK1DockedSince.{this.ship}"/>
        </do_if>
      </do_if>
      <wait exact="this.$gt_yieldMs * 1ms" comment="Cooperative yield before next cycle"/>
      <resume label="main_loop"/>

    </actions>
  </attention>
  <on_abort>
    <!-- Intentional handoff: MK1 can spawn DockAndReturnHome to get visible queued pathing.
         Do not run GT cleanup/cancel bridge in this case. -->
    <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': on_abort skipped (released-undocked transition state active)'" chance="100"/>
      <return/>
    </do_if>
    <do_if value="this.ship.order? and @this.ship.order.id == 'DockAndReturnHome'">
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': on_abort skipped (handoff to DockAndReturnHome)'" chance="100"/>
      <return/>
    </do_if>

    <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{this.ship}?">
      <remove_value name="global.$GT_ReturnHomeHold.{this.ship}"/>
      <do_if value="global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{this.ship}?">
        <remove_value name="global.$GT_ReturnHomeHoldUntil.{this.ship}"/>
      </do_if>
    </do_if>
    <remove_value name="this.$mk1_dockedSince"/>
    <do_if value="global.$GT_MK1DockedSince? and global.$GT_MK1DockedSince.{this.ship}?">
      <remove_value name="global.$GT_MK1DockedSince.{this.ship}"/>
    </do_if>
    <do_if value="global.$GT_MK1ReturnHomeReleased? and global.$GT_MK1ReturnHomeReleased.{this.ship}?">
      <remove_value name="global.$GT_MK1ReturnHomeReleased.{this.ship}"/>
    </do_if>
    <remove_value name="this.$mk1_returnhomeReleased"/>
    <remove_value name="this.$mk1_opportunisticSupplyTried"/>

    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
      <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
    </do_if>

    <!-- Clear stale clearance naming flag on order abort only when cargo is actually empty.
         Keep [CLEARANCE]/CL during active disposal with remaining cargo. -->
    <do_if value="this.ship.cargo.count == 0 and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
      <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship = this.ship,
          $pilot = this.ship.pilot,
          $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType = 'trader'
        ]"/>
      </do_if>
    </do_if>

    <!-- Cleanup: unregister station from MK1 supply registry -->
    <do_if value="this.$homeStation? and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{this.$homeStation}? and global.$GT_MK1SuppliedStations.{this.$homeStation} == this.ship">
      <remove_value name="global.$GT_MK1SuppliedStations.{this.$homeStation}"/>
      <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': on_abort â€” unregistered station from supply registry'" chance="100"/>
    </do_if>
    <!-- Bridge MK1 aborts into MD cleanup pipeline (name restore, registry cleanup, mod cleanup). -->
    <set_value name="$cleanupTraceId" exact="this.ship.idcode + '|MK1_ON_ABORT|' + (player.age / 1s)i"/>
    <set_value name="$cleanupDefaultOrder" exact="'NONE'"/>
    <do_if value="this.ship.defaultorder?">
      <set_value name="$cleanupDefaultOrder" exact="@$this.ship.defaultorder.id"/>
    </do_if>
    <set_value name="$cleanupCommanderId" exact="'NONE'"/>
    <set_value name="$cleanupCommanderOrder" exact="'NONE'"/>
    <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
      <set_value name="$cleanupCommanderId" exact="@$this.ship.commander.idcode"/>
      <do_if value="this.ship.commander.defaultorder?">
        <set_value name="$cleanupCommanderOrder" exact="@$this.ship.commander.defaultorder.id"/>
      </do_if>
    </do_if>
    <set_value name="$abortHasDirectGTOrder" exact="false"/>
    <set_value name="$abortHasGTCommander" exact="false"/>
    <do_if value="$cleanupDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$cleanupDefaultOrder}">
      <set_value name="$abortHasDirectGTOrder" exact="true"/>
    </do_if>
    <do_elseif value="$cleanupDefaultOrder == 'Assist' and this.ship.defaultorder? and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
      <set_value name="$abortHasDirectGTOrder" exact="true"/>
    </do_elseif>
    <do_if value="not $abortHasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
      <set_value name="$abortHasGTCommander" exact="true"/>
    </do_if>
    <do_elseif value="not $abortHasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
      <set_value name="$abortHasGTCommander" exact="true"/>
    </do_elseif>
    <do_if value="not $abortHasDirectGTOrder and not $abortHasGTCommander">
      <do_if value="not global.$GT_CleanupIntent?">
        <set_value name="global.$GT_CleanupIntent" exact="table[]"/>
      </do_if>
      <set_value name="global.$GT_CleanupIntent.{this.ship}" exact="table[
        $Active = true,
        $StartTime = player.age,
        $ExpireTime = player.age + 8s,
        $Source = 'MK1_ON_ABORT',
        $TraceId = $cleanupTraceId,
        $DefaultOrderAtSignal = $cleanupDefaultOrder,
        $CommanderAtSignal = $cleanupCommanderId
      ]"/>
      <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
        $Ship = this.ship,
        $UpdateType = 'GT_Order_Cancelled',
        $Source = 'MK1_ON_ABORT',
        $TraceId = $cleanupTraceId
      ]"/>
      <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
        $Ship = this.ship,
        $Source = 'MK1_ON_ABORT',
        $TraceId = $cleanupTraceId
      ]"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=MK1_ON_ABORT ship=' + this.ship.idcode + ' default=' + $cleanupDefaultOrder + ' commander=' + $cleanupCommanderId + ' commanderOrder=' + $cleanupCommanderOrder + ' action=SIGNAL_GT_ORDER_CANCELLED+ORPHAN_CHECK'" chance="100"/>
        <debug_text text="'[GT-MK1] ' + this.ship.idcode + ': on_abort -> triggered orphan cleanup check'" chance="100"/>
      </do_if>
    </do_if>
    <do_else>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=MK1_ON_ABORT ship=' + this.ship.idcode + ' default=' + $cleanupDefaultOrder + ' commander=' + $cleanupCommanderId + ' commanderOrder=' + $cleanupCommanderOrder + ' action=SKIP_GT_ORDER_CANCELLED_ACTIVE_GT_CONTROL'" chance="100"/>
      </do_if>
    </do_else>
  </on_abort>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.trade.galaxytraderMK2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="7">
  <order id="GalaxyTraderMK2" name="{77000, 20002}" description="{77000, 20102}" category="trade" infinite="true" allowinloop="false" canplayercancel="true">
    <params>
      <param name="homeStation" type="object" default="null" text="{77000, 20017}" comment="{77000, 20117}">
        <input_param name="class" value="[class.station]"/>
        <patch value="null" sinceversion="3"/>
      </param>
      <param name="homeSector" type="object" default="null" text="{77000, 20032}" comment="{77000, 20132}">
        <input_param name="class" value="[class.sector]"/>
        <patch value="null" sinceversion="3"/>
      </param>
      <param name="sourceList" type="list" default="[]" text="{77000, 20010}" comment="{77000, 20110}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="sourceStation" type="object" default="null" text="{77000, 20010}" comment="{77000, 20110}" advanced="true">
        <input_param name="class" value="[class.station]"/>
      </param>
      <param name="destList" type="list" default="[]" text="{77000, 20011}" comment="{77000, 20111}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.station]"/>
      </param>
              <param name="minStorage" type="number" default="if global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMinStorage? then global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMinStorage else 20" text="{77000, 20012}" comment="{77000, 20112}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="98"/>
        <input_param name="step" value="1"/>
      </param>
              <param name="staticStorage" type="number" default="if global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$DefaultStaticStorage? then global.$GT_MK2_GlobalSettings.$Distribution.$DefaultStaticStorage else 40" text="{77000, 20013}" comment="{77000, 20113}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="99"/>
        <input_param name="step" value="1"/>
      </param>
              <param name="maxStorage" type="number" default="if global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMaxStorage? then global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMaxStorage else 70" text="{77000, 20014}" comment="{77000, 20114}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="autowares" default="true" type="bool" text="{77000, 1015}" comment="{77000, 1023}"/>
      <param name="warebasket" default="[]" type="list" text="{77000, 20015}" comment="{77000, 20115}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="ignoretraderules" default="false" type="bool" text="{77000, 30012}" comment="{77000, 30112}"/>
      <param name="ignoreoffersettings" default="false" type="bool" text="{77000, 30028}" comment="{77000, 30128}"/>
      <param name="allowillegal" default="false" type="bool" text="{77000, 1011}" comment="{77000, 1025}"/>
      <param name="enforceRouteIllegalLegality" default="false" type="bool" text="{77000,1070}" comment="{77000,1071}"/>
      <param name="bidirectional" default="false" type="bool" text="{77000, 20016}" comment="{77000, 20116}"/>
      <param name="maxDistance" default="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max" type="number" text="{77000, 20018}" comment="{77000, 20118}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="fleetcoordination" default="true" type="bool" text="{77000, 30019}" comment="{77000, 30119}"/>
              <param name="notifications" default="if global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Notifications? and global.$GT_MK2_GlobalSettings.$Notifications.$Verbosity? then global.$GT_MK2_GlobalSettings.$Notifications.$Verbosity else 1" type="number" text="{77000, 30018}" comment="{77000, 30118}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
              <param name="debuglevel" default="if global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Debug? and global.$GT_MK2_GlobalSettings.$Debug.$DebugLevel? then global.$GT_MK2_GlobalSettings.$Debug.$DebugLevel else 1" type="number" text="{77000, 30020}" comment="{77000, 30120}" advanced="true">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="allowlowvolume" default="false" type="bool" text="{77000, 20030}" comment="{77000, 20130}"/>
      <param name="lowvolumefloorpercent" default="10" type="number" text="{77000, 20031}" comment="{77000, 20131}">
        <input_param name="min" value="1"/>
        <input_param name="max" value="50"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="idleParking" default="false" type="bool" text="{77000, 1096}" comment="{77000, 1097}">
        <patch value="false" sinceversion="3"/>
      </param>
      <param name="autoJumpDistanceByLevel" default="false" type="bool" text="{77000,1098}" comment="{77000,1099}">
        <patch value="false" sinceversion="4"/>
      </param>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
  </order>

  <interrupts>
    <handler ref="SectorChangeHandler"/>
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>

    <!-- MK2 threat broadcast hook: level 6+ pilots can warn fleet when attacked -->
    <handler>
      <conditions>
        <event_object_attacked object="this.ship"/>
      </conditions>
      <actions>
        <set_value name="$pilotLevel" exact="1"/>
        <set_value name="$primaryFaction" exact="null"/>
        <do_if value="event.param? and event.param.owner?">
          <set_value name="$primaryFaction" exact="event.param.owner"/>
        </do_if>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        <do_if value="$pilotLevel ge 6">
          <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
            $Sector = this.ship.sector,
            $DetectedBy = this.ship,
            $HostileCount = 1,
            $PrimaryFaction = $primaryFaction,
            $ShipClass_XL = 0,
            $ShipClass_L = 0,
            $ShipClass_M = 1,
            $ShipClass_S = 0,
            $ThreatScore = 2,
            $Timestamp = player.age
          ]"/>
        </do_if>
      </actions>
    </handler>

    <!-- Training dispatch bridge: MK2 also needs to react to MD training station results -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$trainingStation" exact="$trainingData.$Station"/>
        <set_value name="$requiredLevel" exact="$trainingData.$Level"/>
        <!-- Academy enrollments append DockAndTrain to the queue (immediate=false)
             so the ship finishes its current task first and the player sees the
             training order lined up. Natural ladder keeps immediate dispatch. -->
        <set_value name="$isAcademy" exact="@$trainingData.$IsAcademy"/>
        <set_value name="$useImmediate" exact="not $isAcademy"/>
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist'">
          <set_value name="$useImmediate" exact="false"/>
        </do_if>
        <set_value name="$hasActiveTrainingOrder" exact="false"/>
        <do_all exact="this.ship.orders.count" counter="$oi">
          <do_if value="this.ship.orders.{$oi}.id == 'DockAndTrain'">
            <set_value name="$hasActiveTrainingOrder" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="$trainingStation? and $trainingStation.exists and not $hasActiveTrainingOrder">
          <create_order object="this.ship" id="'DockAndTrain'" immediate="$useImmediate">
            <param name="destination" value="$trainingStation"/>
            <param name="debugchance" value="this.$debugchance"/>
          </create_order>
          <set_value name="this.$mk2_lastTrainingSignalAt" exact="player.age"/>
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': Training station received - DockAndTrain created for ' + $trainingStation.knownname + ' (level ' + $requiredLevel + ', academy=' + $isAcademy + ', immediate=' + $useImmediate + ')'" chance="this.$debugchance"/>
        </do_if>
        <do_elseif value="$hasActiveTrainingOrder">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': Training station signal ignored - DockAndTrain already active'" chance="this.$debugchance"/>
        </do_elseif>
      </actions>
    </handler>
  </interrupts>

  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_value name="$debugchance" exact="if $debuglevel ge 1 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>

    <create_list name="$activeSources"/>
    <do_if value="$sourceList? and $sourceList.count gt 0">
      <do_all exact="$sourceList.count" counter="$si">
        <set_value name="$s" exact="$sourceList.{$si}"/>
        <do_if value="$s? and $s.exists and $s.isclass.station">
          <append_to_list name="$activeSources" exact="$s"/>
        </do_if>
      </do_all>
    </do_if>
    <do_if value="$activeSources.count == 0 and $sourceStation? and $sourceStation.exists and $sourceStation.isclass.station">
      <append_to_list name="$activeSources" exact="$sourceStation"/>
    </do_if>
    <do_if value="$activeSources.count == 0">
      <do_if value="$notifications ge 1">
        <show_notification text="'GalaxyTrader MK2: ' + {77000, 20203}" timeout="10s"/>
      </do_if>
      <set_command_action commandaction="commandaction.standingby"/>
    </do_if>
    <do_if value="not $destList? or $destList.count == 0">
      <do_if value="$notifications ge 1">
        <show_notification text="'GalaxyTrader MK2: ' + {77000, 20204}" timeout="10s"/>
      </do_if>
      <set_command_action commandaction="commandaction.standingby"/>
    </do_if>

    <!-- Range-clamp each threshold to its valid band only. The three thresholds are
         INDEPENDENT controls (min = destination accept-until ceiling; static = source
         drain floor; max = source rebalance trigger). We do NOT force a min<static<max
         ladder here - forcing it silently rewrote configs like 98/0/0 into 98/99/100 and
         froze the trader. The main_loop normalization re-applies the ordering ladder ONLY
         in bidirectional mode (where it prevents ping-pong); unidirectional routes keep the
         thresholds independent. -->
    <set_value name="$minStorage" exact="[0, [$minStorage, 98].min].max"/>
    <set_value name="$staticStorage" exact="[0, [$staticStorage, 99].min].max"/>
    <set_value name="$maxStorage" exact="[0, [$maxStorage, 100].min].max"/>

    <set_value name="this.$sourceStation" exact="$activeSources.{1}"/>
    <set_value name="this.$sourceList" exact="$activeSources"/>
    <set_value name="this.$homeStation" exact="$homeStation"/>
    <set_value name="this.$homeSector" exact="$homeSector"/>
    <!-- Optional MK2 home: snapshot current sector at order apply when unset (fixed for naming/MD; not live drift). -->
    <do_if value="not this.$homeStation? or not this.$homeStation.exists">
      <do_if value="not this.$homeSector? or not this.$homeSector.exists">
        <do_if value="this.ship.sector? and this.ship.sector.exists">
          <set_value name="this.$homeSector" exact="this.ship.sector"/>
          <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyTraderMK2'">
            <edit_order_param order="this.ship.defaultorder" param="'homeSector'" value="this.$homeSector"/>
          </do_if>
        </do_if>
      </do_if>
    </do_if>
    <set_value name="$mk2HomeBase" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
    <do_if value="$mk2HomeBase? and $mk2HomeBase.exists">
      <do_if value="not global.$GT_AIParameters?">
        <set_value name="global.$GT_AIParameters" exact="table[]"/>
      </do_if>
      <do_if value="not global.$GT_AIParameters.{this.ship}?">
        <set_value name="global.$GT_AIParameters.{this.ship}" exact="table[]"/>
      </do_if>
      <set_value name="global.$GT_AIParameters.{this.ship}.$HomeBase" exact="$mk2HomeBase"/>
    </do_if>
    <set_value name="this.$destList" exact="$destList"/>
    <set_value name="this.$minStorage" exact="$minStorage"/>
    <set_value name="this.$staticStorage" exact="$staticStorage"/>
    <set_value name="this.$maxStorage" exact="$maxStorage"/>
    <set_value name="this.$autowares" exact="$autowares"/>
    <set_value name="this.$warebasket" exact="$warebasket"/>
    <set_value name="this.$ignoretraderules" exact="$ignoretraderules"/>
    <set_value name="this.$ignoreoffersettings" exact="$ignoreoffersettings"/>
    <set_value name="this.$mk2UseWareExchange" exact="$ignoreoffersettings"/>
    <set_value name="this.$allowillegal" exact="$allowillegal"/>
    <set_value name="this.$enforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <set_value name="this.$bidirectional" exact="$bidirectional"/>
    <set_value name="this.$maxDistance" exact="$maxDistance"/>
    <set_value name="this.$fleetcoordination" exact="$fleetcoordination"/>
    <set_value name="this.$notifications" exact="$notifications"/>
    <set_value name="this.$debuglevel" exact="$debuglevel"/>
    <set_value name="this.$debugchance" exact="$debugchance"/>
    <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
    <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
      <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
    </do_if>
    <set_value name="this.$allowlowvolume" exact="$allowlowvolume"/>
    <set_value name="this.$lowvolumefloorpercent" exact="[1, [50, $lowvolumefloorpercent].min].max"/>
    <set_value name="this.$idleParking" exact="$idleParking"/>
                <set_value name="this.$minCargoFillPercent" exact="25"/>
                <do_if value="global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent?">
                  <set_value name="this.$minCargoFillPercent" exact="[10, [100, global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent].min].max"/>
                </do_if>
    <set_value name="this.$sourceUsage" exact="table[]"/>
    <set_value name="this.$destUsage" exact="table[]"/>
    <set_value name="this.$initLogged" exact="false"/>
    <set_value name="this.$lastResolvedWaresDisplay" exact="''"/>
    <set_value name="this.$noTradeRetryCount" exact="0"/>
    <set_value name="this.$lastTradeDestination" exact="null"/>
    <set_value name="this.$lastTradeSource" exact="null"/>
    <set_value name="this.$lastTradeWare" exact="null"/>
    <set_value name="this.$stickySource" exact="null"/>
    <set_value name="this.$stickyDestination" exact="null"/>
    <set_value name="this.$stickyWare" exact="null"/>
    <set_value name="this.$stickyCyclesLeft" exact="0"/>
    <set_value name="this.$mk2PilotLevelProfile" exact="1"/>
    <set_value name="this.$mk2RouteT" exact="0.0666667"/>
    <set_value name="this.$mk2RouteAlpha" exact="0.436667"/>
    <set_value name="this.$mk2RouteBeta" exact="0.973333"/>
    <set_value name="this.$mk2RouteLaneBonus" exact="1.06333"/>
    <set_value name="this.$mk2LowVolumeFloorEffPercent" exact="this.$lowvolumefloorpercent"/>
    <set_value name="this.$mk2StickinessTTLProfile" exact="4"/>
    <set_value name="this.$mk2BestTrade" exact="null"/>
    <set_value name="this.$mk2DenyTrade" exact="false"/>
    <set_value name="this.$mk2SellAmount" exact="0"/>
    <set_value name="this.$mk2QueueTrades" exact="[]"/>
    <set_value name="this.$mk2FinalQueueTrades" exact="[]"/>
    <set_value name="this.$mk2DirectDestPairs" exact="[]"/>
    <set_value name="this.$mk2CandidateBuyOffers" exact="[]"/>
    <set_value name="this.$mk2ScoringWare" exact="null"/>
    <set_value name="this.$mk2ScoringSource" exact="null"/>
    <set_value name="this.$mk2_notifiedAllSourcesInvalid" exact="false"/>
    <set_value name="this.$mk2_notifiedAllDestInvalid" exact="false"/>

    <!-- Payment-source control:
         - with player homeStation: assign to station (station account pays non-internal trades)
         - without homeStation: unassign from station (player account pays non-internal trades)
         Ship-subordinates must remain under their ship commander. -->
    <do_if value="this.$homeStation? and this.$homeStation.exists and this.$homeStation.isplayerowned and (not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and this.ship.commander != this.$homeStation">
      <do_if value="this.ship.commander.exists and this.ship.commander != this.ship">
        <remove_object_commander object="this.ship"/>
      </do_if>
      <set_object_commander object="this.ship" commander="this.$homeStation" assignment="assignment.trade"/>
    </do_if>
    <do_elseif value="(not this.$homeStation? or not this.$homeStation.exists or not this.$homeStation.isplayerowned) and this.ship.commander.exists and this.ship.commander.isclass.station">
      <remove_object_commander object="this.ship"/>
    </do_elseif>

    <set_command_action commandaction="commandaction.searchingtrades"/>
    <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
      $Ship = this.ship,
      $Config = table[
        $allowillegal = this.$allowillegal,
        $debuglevel = this.$debuglevel,
        $orderType = 'MK2'
      ]
    ]"/>
    <!-- Mirror MK3 lifecycle: register pilot/ship through GT_Update_Ship on init -->
    <do_if value="this.ship.pilot">
      <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
        $updateType = 'pilot_change',
        $Ship = this.ship,
        $pilot = this.ship.pilot,
        $oldPilot = null
      ]"/>
    </do_if>
    <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
      $Ship = this.ship,
      $UpdateType = 'GT_Order_Assigned',
      $MacroShipName = @this.ship.macro.name
    ]"/>
  </init>

  <patch sinceversion="3">
    <do_if value="not $homeSector?">
      <set_value name="$homeSector" exact="null"/>
    </do_if>
    <do_if value="not $idleParking?">
      <set_value name="$idleParking" exact="false"/>
    </do_if>
    <set_value name="this.$homeSector" exact="$homeSector"/>
    <set_value name="this.$idleParking" exact="$idleParking"/>
    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': v2->v3 patch applied (idleParking=' + this.$idleParking + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="4">
    <do_if value="not $autoJumpDistanceByLevel?">
      <set_value name="$autoJumpDistanceByLevel" exact="false"/>
    </do_if>
    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': v3->v4 patch applied (autoJumpDistanceByLevel=' + $autoJumpDistanceByLevel + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="5">
    <do_if value="not $enforceRouteIllegalLegality?">
      <set_value name="$enforceRouteIllegalLegality" exact="false"/>
    </do_if>
    <set_value name="this.$enforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': v4->v5 patch applied (enforceRouteIllegalLegality=' + $enforceRouteIllegalLegality + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="7">
    <!-- v6 and earlier clamped staticStorage up to min+1 at init, persisting e.g.
         98/99/100 for a configured 98/0/0 and freezing the trader. Recompute the live
         thresholds from the raw params under the new rule: range-clamp only, with the
         min<static<max ladder re-applied ONLY in bidirectional mode (where it prevents
         ping-pong). main_loop re-normalizes every cycle thereafter; this just corrects
         migrated saves immediately. Params are baseline (since v1) but guarded defensively
         per the patch-ordering caveat. -->
    <do_if value="not $minStorage?">
      <set_value name="$minStorage" exact="20"/>
    </do_if>
    <do_if value="not $staticStorage?">
      <set_value name="$staticStorage" exact="40"/>
    </do_if>
    <do_if value="not $maxStorage?">
      <set_value name="$maxStorage" exact="70"/>
    </do_if>
    <do_if value="not $bidirectional?">
      <set_value name="$bidirectional" exact="false"/>
    </do_if>
    <set_value name="this.$minStorage" exact="[0, [$minStorage, 98].min].max"/>
    <set_value name="this.$staticStorage" exact="[0, [$staticStorage, 99].min].max"/>
    <set_value name="this.$maxStorage" exact="[0, [$maxStorage, 100].min].max"/>
    <do_if value="$bidirectional">
      <do_if value="this.$staticStorage le this.$minStorage">
        <set_value name="this.$staticStorage" exact="[99, this.$minStorage + 1].min"/>
      </do_if>
      <do_if value="this.$maxStorage le this.$staticStorage">
        <set_value name="this.$maxStorage" exact="[100, this.$staticStorage + 1].min"/>
      </do_if>
    </do_if>
    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': v6->v7 patch applied (thresholds normalized to ' + this.$minStorage + '/' + this.$staticStorage + '/' + this.$maxStorage + ', bidir=' + $bidirectional + ')'" filter="savegame"/>
  </patch>

  <attention min="unknown">
    <actions>
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <set_value name="this.$gt_criticalYieldMs" exact="10"/>
      <set_value name="this.$searchCadenceMinSec" exact="8"/>
      <set_value name="this.$searchCadenceMaxSec" exact="12"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>
      <do_if value="global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$SearchCadenceMinSec?">
        <set_value name="this.$searchCadenceMinSec" exact="[1, [300, @global.$GT_MK2_GlobalSettings.$Distribution.$SearchCadenceMinSec].min].max"/>
      </do_if>
      <do_if value="global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$SearchCadenceMaxSec?">
        <set_value name="this.$searchCadenceMaxSec" exact="[this.$searchCadenceMinSec, [600, @global.$GT_MK2_GlobalSettings.$Distribution.$SearchCadenceMaxSec].min].max"/>
      </do_if>

      <label name="main_loop"/>

      <!-- Idle park timed release (trader keeps searching; hold expiry handled here). -->
      <run_script name="'lib.gt.idlepark'">
        <param name="handoffMode" value="'check_timed_release'"/>
        <param name="handoffShip" value="this.ship"/>
        <param name="home" value="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else this.ship.sector)"/>
        <param name="debugchance" value="if this.$debugchance? then this.$debugchance else 0"/>
      </run_script>

      <!-- Unified ship name refresh (home sector, op-state, XP â€” content dedupe in MD) -->
      <run_script name="'lib.gt.attention.refresh_ship_name'">
        <param name="ship" value="this.ship"/>
      </run_script>
      <run_script name="'lib.gt.attention.autojump_distance_toggle'">
        <param name="autoJumpDistanceByLevel" value="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
      </run_script>

      <do_if value="not this.$blacklistgroup?">
        <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
        <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
          <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
        </do_if>
      </do_if>

      <!-- In-flight academy / DockAndTrain: hold the default order while the ship
           completes training (MD timer + order.dock.train survive save/load). -->
      <set_value name="$gtHasDockAndTrain" exact="false"/>
      <do_if value="this.ship.orders? and this.ship.orders.count gt 0">
        <do_all exact="this.ship.orders.count" counter="$gtToi">
          <do_if value="this.ship.orders.{$gtToi}.id == 'DockAndTrain'">
            <set_value name="$gtHasDockAndTrain" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      <set_value name="$gtMdTrainingActive" exact="false"/>
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
        <set_value name="$gtMdTrainingActive" exact="true"/>
      </do_if>
      <do_if value="$gtHasDockAndTrain or $gtMdTrainingActive">
        <set_command_action commandaction="commandaction.standingby"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': Holding for in-flight training (DockAndTrain=' + $gtHasDockAndTrain + ', MD timer=' + $gtMdTrainingActive + ')'" chance="100"/>
        </do_if>
        <wait max="10s">
          <interrupt>
            <conditions>
              <event_object_order_ready object="this.ship"/>
            </conditions>
          </interrupt>
        </wait>
        <resume label="main_loop"/>
      </do_if>

      <!-- Periodic training re-request for already blocked pilots (e.g. saves created before this handler existed). -->
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
        <set_value name="$blockedLevel" exact="0"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel?">
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <set_value name="$needsTrainingDispatch" exact="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded? or $blockedLevel gt 1"/>
        <set_value name="$gtSkipTrainingDispatch" exact="false"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
          <set_value name="$gtSkipTrainingDispatch" exact="true"/>
        </do_if>
        <do_if value="not $gtSkipTrainingDispatch and this.ship.orders? and this.ship.orders.count gt 0">
          <do_all exact="this.ship.orders.count" counter="$gtToi2">
            <do_if value="this.ship.orders.{$gtToi2}.id == 'DockAndTrain'">
              <set_value name="$gtSkipTrainingDispatch" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$needsTrainingDispatch and not $gtSkipTrainingDispatch">
          <set_value name="$dispatchReady" exact="false"/>
          <do_if value="not this.$mk2_lastTrainingSignalAt? or (player.age - this.$mk2_lastTrainingSignalAt) ge 60s">
            <set_value name="$dispatchReady" exact="true"/>
          </do_if>
          <do_if value="$dispatchReady">
            <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $RequiredLevel = $blockedLevel
            ]"/>
            <set_value name="this.$mk2_lastTrainingSignalAt" exact="player.age"/>
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': Re-requested training dispatch for blocked pilot (level ' + $blockedLevel + ')'" chance="this.$debugchance"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Keep runtime values in sync only when this ship has a direct MK2 default order.
           Assist subordinates receive inherited params from order.assist -> run_script. -->
      <set_value name="$mk2OrderToEdit" exact="null"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyTraderMK2'">
        <set_value name="this.$sourceList" exact="[]"/>
        <do_if value="this.ship.defaultorder.$sourceList? and this.ship.defaultorder.$sourceList.count gt 0">
          <set_value name="this.$sourceList" exact="this.ship.defaultorder.$sourceList"/>
        </do_if>
        <do_if value="not this.$sourceList? or this.$sourceList.count == 0">
          <do_if value="this.ship.defaultorder.$sourceStation? and this.ship.defaultorder.$sourceStation.exists and this.ship.defaultorder.$sourceStation.isclass.station">
            <append_to_list name="this.$sourceList" exact="this.ship.defaultorder.$sourceStation"/>
          </do_if>
        </do_if>
        <set_value name="this.$destList" exact="this.ship.defaultorder.$destList"/>
        <set_value name="this.$minStorage" exact="this.ship.defaultorder.$minStorage"/>
        <set_value name="this.$staticStorage" exact="this.ship.defaultorder.$staticStorage"/>
        <set_value name="this.$maxStorage" exact="this.ship.defaultorder.$maxStorage"/>
        <set_value name="this.$autowares" exact="if this.ship.defaultorder.$autowares? then this.ship.defaultorder.$autowares else true"/>
        <set_value name="this.$warebasket" exact="this.ship.defaultorder.$warebasket"/>
        <set_value name="this.$ignoretraderules" exact="this.ship.defaultorder.$ignoretraderules"/>
        <set_value name="this.$ignoreoffersettings" exact="if this.ship.defaultorder.$ignoreoffersettings? then this.ship.defaultorder.$ignoreoffersettings else false"/>
        <set_value name="this.$mk2UseWareExchange" exact="this.$ignoreoffersettings"/>
        <set_value name="this.$allowillegal" exact="this.ship.defaultorder.$allowillegal"/>
        <set_value name="this.$enforceRouteIllegalLegality" exact="if this.ship.defaultorder.$enforceRouteIllegalLegality? then this.ship.defaultorder.$enforceRouteIllegalLegality else false"/>
        <set_value name="this.$bidirectional" exact="this.ship.defaultorder.$bidirectional"/>
        <set_value name="this.$homeStation" exact="this.ship.defaultorder.$homeStation"/>
        <set_value name="this.$homeSector" exact="if this.ship.defaultorder.$homeSector? then this.ship.defaultorder.$homeSector else null"/>
        <set_value name="this.$maxDistance" exact="this.ship.defaultorder.$maxDistance"/>
        <set_value name="this.$fleetcoordination" exact="this.ship.defaultorder.$fleetcoordination"/>
        <set_value name="this.$notifications" exact="this.ship.defaultorder.$notifications"/>
        <set_value name="this.$debuglevel" exact="this.ship.defaultorder.$debuglevel"/>
        <set_value name="this.$debugchance" exact="if this.$debuglevel ge 1 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
        <set_value name="this.$allowlowvolume" exact="if this.ship.defaultorder.$allowlowvolume? then this.ship.defaultorder.$allowlowvolume else false"/>
        <set_value name="this.$lowvolumefloorpercent" exact="if this.ship.defaultorder.$lowvolumefloorpercent? then [1, [50, this.ship.defaultorder.$lowvolumefloorpercent].min].max else 10"/>
        <set_value name="this.$idleParking" exact="if this.ship.defaultorder.$idleParking? then this.ship.defaultorder.$idleParking else false"/>
        <set_value name="$mk2OrderToEdit" exact="this.ship.defaultorder"/>
      </do_if>
      <do_elseif value="this.ship.commander.exists and this.ship.commander != this.ship and this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist' and this.ship.commander.defaultorder?">
        <!-- Vanilla-aligned subordinate inheritance:
             Assist references commander's defaultorder; if that default is Assist, use its baseorder. -->
        <set_value name="$mk2InheritedOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$mk2InheritedOrder.id == 'Assist' and $mk2InheritedOrder.$baseorder?">
          <set_value name="$mk2InheritedOrder" exact="$mk2InheritedOrder.$baseorder"/>
        </do_if>
        <do_if value="$mk2InheritedOrder? and $mk2InheritedOrder.id == 'GalaxyTraderMK2'">
          <set_value name="this.$sourceList" exact="[]"/>
          <do_if value="$mk2InheritedOrder.$sourceList? and $mk2InheritedOrder.$sourceList.count gt 0">
            <set_value name="this.$sourceList" exact="$mk2InheritedOrder.$sourceList"/>
          </do_if>
          <do_if value="not this.$sourceList? or this.$sourceList.count == 0">
            <do_if value="$mk2InheritedOrder.$sourceStation? and $mk2InheritedOrder.$sourceStation.exists and $mk2InheritedOrder.$sourceStation.isclass.station">
              <append_to_list name="this.$sourceList" exact="$mk2InheritedOrder.$sourceStation"/>
            </do_if>
          </do_if>
          <set_value name="this.$destList" exact="$mk2InheritedOrder.$destList"/>
          <set_value name="this.$minStorage" exact="$mk2InheritedOrder.$minStorage"/>
          <set_value name="this.$staticStorage" exact="$mk2InheritedOrder.$staticStorage"/>
          <set_value name="this.$maxStorage" exact="$mk2InheritedOrder.$maxStorage"/>
          <set_value name="this.$autowares" exact="if $mk2InheritedOrder.$autowares? then $mk2InheritedOrder.$autowares else true"/>
          <set_value name="this.$warebasket" exact="$mk2InheritedOrder.$warebasket"/>
          <set_value name="this.$ignoretraderules" exact="$mk2InheritedOrder.$ignoretraderules"/>
          <set_value name="this.$ignoreoffersettings" exact="if $mk2InheritedOrder.$ignoreoffersettings? then $mk2InheritedOrder.$ignoreoffersettings else false"/>
          <set_value name="this.$mk2UseWareExchange" exact="this.$ignoreoffersettings"/>
          <set_value name="this.$allowillegal" exact="$mk2InheritedOrder.$allowillegal"/>
          <set_value name="this.$enforceRouteIllegalLegality" exact="if $mk2InheritedOrder.$enforceRouteIllegalLegality? then $mk2InheritedOrder.$enforceRouteIllegalLegality else false"/>
          <set_value name="this.$bidirectional" exact="$mk2InheritedOrder.$bidirectional"/>
          <set_value name="this.$homeStation" exact="$mk2InheritedOrder.$homeStation"/>
          <set_value name="this.$homeSector" exact="if $mk2InheritedOrder.$homeSector? then $mk2InheritedOrder.$homeSector else null"/>
          <set_value name="this.$maxDistance" exact="$mk2InheritedOrder.$maxDistance"/>
          <set_value name="this.$fleetcoordination" exact="$mk2InheritedOrder.$fleetcoordination"/>
          <set_value name="this.$notifications" exact="$mk2InheritedOrder.$notifications"/>
          <set_value name="this.$debuglevel" exact="$mk2InheritedOrder.$debuglevel"/>
          <set_value name="this.$debugchance" exact="if this.$debuglevel ge 1 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
          <set_value name="this.$allowlowvolume" exact="if $mk2InheritedOrder.$allowlowvolume? then $mk2InheritedOrder.$allowlowvolume else false"/>
          <set_value name="this.$lowvolumefloorpercent" exact="if $mk2InheritedOrder.$lowvolumefloorpercent? then [1, [50, $mk2InheritedOrder.$lowvolumefloorpercent].min].max else 10"/>
          <set_value name="this.$idleParking" exact="if $mk2InheritedOrder.$idleParking? then $mk2InheritedOrder.$idleParking else false"/>
          <set_value name="$mk2OrderToEdit" exact="$mk2InheritedOrder"/>
        </do_if>
      </do_elseif>
      <!-- Optional MK2 home: snapshot current sector when unset (persists via homeSector param). -->
      <do_if value="not this.$homeStation? or not this.$homeStation.exists">
        <do_if value="not this.$homeSector? or not this.$homeSector.exists">
          <do_if value="this.ship.sector? and this.ship.sector.exists">
            <set_value name="this.$homeSector" exact="this.ship.sector"/>
            <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyTraderMK2'">
              <edit_order_param order="this.ship.defaultorder" param="'homeSector'" value="this.$homeSector"/>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
      <set_value name="$mk2HomeBase" exact="if this.$homeStation? and this.$homeStation.exists then this.$homeStation else (if this.$homeSector? and this.$homeSector.exists then this.$homeSector else null)"/>
      <do_if value="$mk2HomeBase? and $mk2HomeBase.exists">
        <do_if value="not global.$GT_AIParameters?">
          <set_value name="global.$GT_AIParameters" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_AIParameters.{this.ship}?">
          <set_value name="global.$GT_AIParameters.{this.ship}" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_AIParameters.{this.ship}.$HomeBase" exact="$mk2HomeBase"/>
      </do_if>
      <!-- Threshold normalization (runs every cycle on the live this.$ values, after the
           direct/inherited refresh above and the one-time init):
           - Range-clamp each threshold to its valid band.
           - Enforce the min<static<max ladder ONLY in bidirectional mode. When every
             station can both supply and receive, a static floor below the destination min
             ceiling can ping-pong stock (drain a low station into a fuller one and back),
             so we keep the ordering guard there. Unidirectional routes have fixed
             source/dest roles, so the three thresholds stay independent (e.g. 98/0/0 means
             "fill destinations to 98%, drain sources fully"). -->
      <set_value name="this.$minStorage" exact="[0, [this.$minStorage, 98].min].max"/>
      <set_value name="this.$staticStorage" exact="[0, [this.$staticStorage, 99].min].max"/>
      <set_value name="this.$maxStorage" exact="[0, [this.$maxStorage, 100].min].max"/>
      <do_if value="this.$bidirectional">
        <do_if value="this.$staticStorage le this.$minStorage">
          <set_value name="this.$staticStorage" exact="[99, this.$minStorage + 1].min"/>
        </do_if>
        <do_if value="this.$maxStorage le this.$staticStorage">
          <set_value name="this.$maxStorage" exact="[100, this.$staticStorage + 1].min"/>
        </do_if>
      </do_if>

      <!-- Re-apply pilot-level cap each cycle so level-up/down updates effective range immediately. -->
      <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
      <do_if value="not $useVanillaXPOnly">
        <set_value name="$mk2PilotLevelCap" exact="1"/>
        <run_script name="'lib.gt.pathfinding'" result="$mk2PilotLevelCap">
          <param name="mode" value="'effective_pilot_level'"/>
          <param name="ship" value="this.ship"/>
          <param name="includeCommander" value="false"/>
        </run_script>
        <run_script name="'lib.gt.pathfinding'" result="$mk2PilotMaxDistance">
          <param name="mode" value="'pilot_max_jumps'"/>
          <param name="pilotSkill" value="$mk2PilotLevelCap"/>
        </run_script>
        <do_if value="$mk2PilotMaxDistance == null">
          <set_value name="$mk2PilotMaxDistance" exact="1"/>
        </do_if>
        <set_value name="this.$maxDistance" exact="[this.$maxDistance, $mk2PilotMaxDistance].min"/>
      </do_if>
                  <set_value name="this.$minCargoFillPercent" exact="25"/>
                  <do_if value="global.$GT_MK2_GlobalSettings? and global.$GT_MK2_GlobalSettings.$Distribution? and global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent?">
                    <set_value name="this.$minCargoFillPercent" exact="[10, [100, global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent].min].max"/>
                  </do_if>

      <!-- Prune destroyed/invalid stations from order lists and persist to defaultorder. -->
      <set_value name="$mk2MayNotify" exact="this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyTraderMK2'"/>
      <set_value name="$prunedSourceList" exact="[]"/>
      <set_value name="$mk2SourcesRemoved" exact="0"/>
      <do_if value="this.$sourceList? and this.$sourceList.count gt 0">
        <do_all exact="this.$sourceList.count" counter="$psi">
          <set_value name="$ps" exact="this.$sourceList.{$psi}"/>
          <do_if value="$ps? and $ps.exists and $ps.isclass.station">
            <append_to_list name="$prunedSourceList" exact="$ps"/>
          </do_if>
          <do_else>
            <set_value name="$mk2SourcesRemoved" operation="add"/>
          </do_else>
        </do_all>
      </do_if>
      <set_value name="$prunedDestList" exact="[]"/>
      <set_value name="$mk2DestsRemoved" exact="0"/>
      <do_if value="this.$destList? and this.$destList.count gt 0">
        <do_all exact="this.$destList.count" counter="$pdi">
          <set_value name="$pd" exact="this.$destList.{$pdi}"/>
          <do_if value="$pd? and $pd.exists and $pd.isclass.station">
            <append_to_list name="$prunedDestList" exact="$pd"/>
          </do_if>
          <do_else>
            <set_value name="$mk2DestsRemoved" operation="add"/>
          </do_else>
        </do_all>
      </do_if>
      <do_if value="$mk2SourcesRemoved gt 0 or $mk2DestsRemoved gt 0">
        <set_value name="this.$sourceList" exact="$prunedSourceList"/>
        <set_value name="this.$destList" exact="$prunedDestList"/>
        <do_if value="$mk2OrderToEdit?">
          <edit_order_param order="$mk2OrderToEdit" param="'sourceList'" value="$prunedSourceList"/>
          <edit_order_param order="$mk2OrderToEdit" param="'destList'" value="$prunedDestList"/>
          <do_if value="$prunedSourceList.count gt 0">
            <edit_order_param order="$mk2OrderToEdit" param="'sourceStation'" value="$prunedSourceList.{1}"/>
          </do_if>
          <do_else>
            <edit_order_param order="$mk2OrderToEdit" param="'sourceStation'" value="null"/>
          </do_else>
        </do_if>
        <do_if value="$mk2MayNotify and this.$notifications ge 1">
          <do_if value="$mk2SourcesRemoved gt 0">
            <do_if value="$prunedSourceList.count gt 0">
              <show_notification text="'GalaxyTrader MK2: ' + {77000, 20205}.['(destroyed)']" timeout="10s"/>
            </do_if>
            <do_elseif value="not this.$mk2_notifiedAllSourcesInvalid? or not this.$mk2_notifiedAllSourcesInvalid">
              <show_notification text="'GalaxyTrader MK2: ' + {77000, 20203}" timeout="10s"/>
              <set_value name="this.$mk2_notifiedAllSourcesInvalid" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="$mk2DestsRemoved gt 0">
            <do_if value="$prunedDestList.count gt 0">
              <show_notification text="'GalaxyTrader MK2: ' + {77000, 20206}.['(destroyed)']" timeout="10s"/>
            </do_if>
            <do_elseif value="not this.$mk2_notifiedAllDestInvalid? or not this.$mk2_notifiedAllDestInvalid">
              <show_notification text="'GalaxyTrader MK2: ' + {77000, 20204}" timeout="10s"/>
              <set_value name="this.$mk2_notifiedAllDestInvalid" exact="true"/>
            </do_elseif>
          </do_if>
        </do_if>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': pruned invalid stations from order (sources removed=' + $mk2SourcesRemoved + ', remaining=' + $prunedSourceList.count + ', dests removed=' + $mk2DestsRemoved + ', remaining=' + $prunedDestList.count + ')'" chance="this.$debugchance"/>
        </do_if>
      </do_if>

      <create_list name="$activeSources"/>
      <do_all exact="this.$sourceList.count" counter="$si">
        <set_value name="$s" exact="this.$sourceList.{$si}"/>
        <do_if value="$s? and $s.exists and $s.isclass.station">
          <append_to_list name="$activeSources" exact="$s"/>
        </do_if>
      </do_all>
      <do_if value="$activeSources.count == 0">
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': no active sources (sourceList count=' + this.$sourceList.count + ', homeStation=' + (if this.$homeStation? then this.$homeStation.knownname else '(none)') + ')'" chance="this.$debugchance"/>
        </do_if>
        <do_if value="$mk2MayNotify and this.$notifications ge 1 and (not this.$mk2_notifiedAllSourcesInvalid? or not this.$mk2_notifiedAllSourcesInvalid)">
          <show_notification text="'GalaxyTrader MK2: ' + {77000, 20203}" timeout="10s"/>
          <set_value name="this.$mk2_notifiedAllSourcesInvalid" exact="true"/>
        </do_if>
        <set_command_action commandaction="commandaction.standingby"/>
        <resume label="no_trade_retry"/>
      </do_if>
      <set_value name="this.$mk2_notifiedAllSourcesInvalid" exact="false"/>
      <set_value name="this.$activeSources" exact="$activeSources"/>
      <set_value name="this.$sourceStation" exact="$activeSources.{1}"/>

      <!-- Reconcile commander assignment each loop so runtime order edits
           (setting/clearing homeStation) immediately switch payment source. -->
      <do_if value="this.$homeStation? and this.$homeStation.exists and this.$homeStation.isplayerowned and (not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and this.ship.commander != this.$homeStation">
        <do_if value="this.ship.commander.exists and this.ship.commander != this.ship">
          <remove_object_commander object="this.ship"/>
        </do_if>
        <set_object_commander object="this.ship" commander="this.$homeStation" assignment="assignment.trade"/>
      </do_if>
      <do_elseif value="(not this.$homeStation? or not this.$homeStation.exists or not this.$homeStation.isplayerowned) and this.ship.commander.exists and this.ship.commander.isclass.station">
        <remove_object_commander object="this.ship"/>
      </do_elseif>

      <create_list name="$activeDestinations"/>
      <set_value name="$destInvalidCount" exact="0"/>
      <do_all exact="this.$destList.count" counter="$di">
        <set_value name="$d" exact="this.$destList.{$di}"/>
        <do_if value="not $d? or not $d.exists or not $d.isclass.station">
          <set_value name="$destInvalidCount" operation="add"/>
        </do_if>
        <do_else>
          <append_to_list name="$activeDestinations" exact="$d"/>
        </do_else>
      </do_all>
      <set_value name="$sourceNames" exact="''"/>
      <do_all exact="$activeSources.count" counter="$sn">
        <do_if value="$sn gt 1">
          <set_value name="$sourceNames" exact="$sourceNames + ', '"/>
        </do_if>
        <set_value name="$sourceNames" exact="$sourceNames + $activeSources.{$sn}.knownname + ' [' + $activeSources.{$sn}.idcode + ']'"/>
      </do_all>
      <set_value name="$destNames" exact="''"/>
      <do_all exact="$activeDestinations.count" counter="$dn">
        <do_if value="$dn gt 1">
          <set_value name="$destNames" exact="$destNames + ', '"/>
        </do_if>
        <set_value name="$destNames" exact="$destNames + $activeDestinations.{$dn}.knownname + ' [' + $activeDestinations.{$dn}.idcode + ']'"/>
      </do_all>

      <!-- One-time startup dump of resolved MK2 setup for diagnostics.
           Must run before early no-destination resume paths. -->
      <do_if value="this.$debuglevel ge 1 and (not this.$initLogged? or not this.$initLogged)">
        <set_value name="$homeName" exact="'(none)'"/>
        <do_if value="this.$homeStation? and this.$homeStation.exists">
          <set_value name="$homeName" exact="this.$homeStation.knownname + ' [' + this.$homeStation.idcode + ']'"/>
        </do_if>
        <set_value name="$sourceListMode" exact="'auto dynamic'"/>
        <do_if value="not this.$autowares">
          <set_value name="$sourceListMode" exact="'manual basket only'"/>
        </do_if>
        <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': INIT setup | home=' + $homeName + ' | sourceCursor=' + (if this.$sourceStation? and this.$sourceStation.exists then this.$sourceStation.knownname else '(none)') + ' [' + (if this.$sourceStation? and this.$sourceStation.exists then this.$sourceStation.idcode else '(n/a)') + ']' + ' | src=' + this.$activeSources.count + ' [' + $sourceNames + ']' + ' | dst=' + $activeDestinations.count + ' [' + $destNames + ']' + ' | min/static/max=' + this.$minStorage + '/' + this.$staticStorage + '/' + this.$maxStorage + ' | maxDist=' + this.$maxDistance + ' | minFill=' + this.$minCargoFillPercent + '% | bidir=' + this.$bidirectional + ' | ignoreRules=' + this.$ignoretraderules + ' | ignoreOffers=' + this.$ignoreoffersettings + ' | allowIllegal=' + this.$allowillegal + ' | wareMode=' + $sourceListMode + ' | notifications=' + this.$notifications + ' | fleet=' + this.$fleetcoordination + ' | destInvalid=' + $destInvalidCount + ' | diagRev=mk2-ware-exchange-r7'" chance="this.$debugchance"/>
        <!-- Detailed one-time diagnostics for all involved stations and relevant wares. -->
        <set_value name="$diagWareLimit" exact="12"/>
        <do_all exact="this.$activeSources.count" counter="$dsi">
          <set_value name="$diagStation" exact="this.$activeSources.{$dsi}"/>
          <set_value name="$diagProducts" exact="$diagStation.products.list"/>
          <set_value name="$diagTradewares" exact="$diagStation.tradewares.list"/>
          <set_value name="$diagResources" exact="$diagStation.resources.list"/>
          <set_value name="$diagWareNames" exact="''"/>
          <set_value name="$diagWareLogged" exact="0"/>
          <create_list name="$diagSourceWares"/>
          <do_all exact="$diagProducts.count" counter="$dpi">
            <append_to_list name="$diagSourceWares" exact="$diagProducts.{$dpi}"/>
          </do_all>
          <do_all exact="$diagTradewares.count" counter="$dti">
            <set_value name="$dw" exact="$diagTradewares.{$dti}"/>
            <set_value name="$dup" exact="false"/>
            <do_all exact="$diagSourceWares.count" counter="$ddi">
              <do_if value="$diagSourceWares.{$ddi} == $dw">
                <set_value name="$dup" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $dup">
              <append_to_list name="$diagSourceWares" exact="$dw"/>
            </do_if>
          </do_all>
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': STATION src ' + $diagStation.knownname + ' [' + $diagStation.idcode + '] owner=' + (if $diagStation.isplayerowned then 'player' else 'foreign') + ' products=' + $diagProducts.count + ' tradewares=' + $diagTradewares.count + ' resources=' + $diagResources.count + ' waresForOffers=' + $diagSourceWares.count" chance="this.$debugchance"/>
          <do_all exact="$diagSourceWares.count" counter="$dwi">
            <do_if value="$diagWareLogged ge $diagWareLimit">
              <break/>
            </do_if>
            <set_value name="$diagWare" exact="$diagSourceWares.{$dwi}"/>
            <set_value name="$cargoCount" exact="$diagStation.cargo.{$diagWare}.count"/>
            <set_value name="$cargoTarget" exact="$diagStation.cargo.{$diagWare}.target"/>
            <set_value name="$cargoTargetSafe" exact="[$cargoTarget, 1].max"/>
            <set_value name="$cargoRatio" exact="($cargoCount * 100) / $cargoTargetSafe"/>
            <find_sell_offer tradepartner="this.ship" seller="$diagStation" wares="$diagWare" result="$diagSellPartner"/>
            <find_buy_offer tradepartner="this.ship" buyer="$diagStation" wares="$diagWare" result="$diagBuyPartner"/>
            <set_value name="$sellPartnerAvail" exact="'0'"/>
            <set_value name="$sellPartnerAmount" exact="'n/a'"/>
            <do_if value="$diagSellPartner != null">
              <set_value name="$sellPartnerAmount" exact="$diagSellPartner.amount"/>
              <do_if value="$diagSellPartner.available">
                <set_value name="$sellPartnerAvail" exact="'1'"/>
              </do_if>
            </do_if>
            <set_value name="$buyPartnerAvail" exact="'0'"/>
            <set_value name="$buyPartnerAmount" exact="'n/a'"/>
            <do_if value="$diagBuyPartner != null">
              <set_value name="$buyPartnerAmount" exact="$diagBuyPartner.amount"/>
              <do_if value="$diagBuyPartner.available">
                <set_value name="$buyPartnerAvail" exact="'1'"/>
              </do_if>
            </do_if>
            <set_value name="$sellIgnoreAvail" exact="'n/a'"/>
            <set_value name="$sellIgnoreAmount" exact="'n/a'"/>
            <set_value name="$buyIgnoreAvail" exact="'n/a'"/>
            <set_value name="$buyIgnoreAmount" exact="'n/a'"/>
            <do_if value="this.$ignoretraderules and $diagStation.isplayerowned">
              <find_sell_offer seller="$diagStation" wares="$diagWare" result="$diagSellIgnore"/>
              <find_buy_offer buyer="$diagStation" wares="$diagWare" result="$diagBuyIgnore"/>
              <set_value name="$sellIgnoreAvail" exact="'0'"/>
              <set_value name="$sellIgnoreAmount" exact="'n/a'"/>
              <do_if value="$diagSellIgnore != null">
                <set_value name="$sellIgnoreAmount" exact="$diagSellIgnore.amount"/>
                <do_if value="$diagSellIgnore.available">
                  <set_value name="$sellIgnoreAvail" exact="'1'"/>
                </do_if>
              </do_if>
              <set_value name="$buyIgnoreAvail" exact="'0'"/>
              <set_value name="$buyIgnoreAmount" exact="'n/a'"/>
              <do_if value="$diagBuyIgnore != null">
                <set_value name="$buyIgnoreAmount" exact="$diagBuyIgnore.amount"/>
                <do_if value="$diagBuyIgnore.available">
                  <set_value name="$buyIgnoreAvail" exact="'1'"/>
                </do_if>
              </do_if>
            </do_if>
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': STATION src ' + $diagStation.idcode + ' ware=' + $diagWare + ' cargo=' + $cargoCount + '/' + $cargoTarget + ' (' + $cargoRatio + '%)' + ' sell(partner:a=' + $sellPartnerAvail + ',m=' + $sellPartnerAmount + '; ignore:a=' + $sellIgnoreAvail + ',m=' + $sellIgnoreAmount + ')' + ' buy(partner:a=' + $buyPartnerAvail + ',m=' + $buyPartnerAmount + '; ignore:a=' + $buyIgnoreAvail + ',m=' + $buyIgnoreAmount + ')'" chance="this.$debugchance"/>
            <set_value name="$diagWareLogged" operation="add"/>
          </do_all>
        </do_all>

        <do_all exact="$activeDestinations.count" counter="$ddi">
          <set_value name="$diagStation" exact="$activeDestinations.{$ddi}"/>
          <set_value name="$diagProducts" exact="$diagStation.products.list"/>
          <set_value name="$diagTradewares" exact="$diagStation.tradewares.list"/>
          <set_value name="$diagResources" exact="$diagStation.resources.list"/>
          <set_value name="$diagWareLogged" exact="0"/>
          <!-- Build the union of resources + tradewares to mirror the basket-side semantics.
               Trading Posts / Equipment Docks expose what they buy/sell via tradewares only,
               so probing only resources hides them from this per-ware diagnostic dump. -->
          <create_list name="$diagDestWares"/>
          <do_all exact="$diagResources.count" counter="$ddri">
            <append_to_list name="$diagDestWares" exact="$diagResources.{$ddri}"/>
          </do_all>
          <do_all exact="$diagTradewares.count" counter="$ddti">
            <set_value name="$ddw" exact="$diagTradewares.{$ddti}"/>
            <set_value name="$dup" exact="false"/>
            <do_all exact="$diagDestWares.count" counter="$dddi">
              <do_if value="$diagDestWares.{$dddi} == $ddw">
                <set_value name="$dup" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $dup">
              <append_to_list name="$diagDestWares" exact="$ddw"/>
            </do_if>
          </do_all>
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': STATION dst ' + $diagStation.knownname + ' [' + $diagStation.idcode + '] owner=' + (if $diagStation.isplayerowned then 'player' else 'foreign') + ' products=' + $diagProducts.count + ' tradewares=' + $diagTradewares.count + ' resources=' + $diagResources.count + ' waresForOffers=' + $diagDestWares.count" chance="this.$debugchance"/>
          <do_all exact="$diagDestWares.count" counter="$dri">
            <do_if value="$diagWareLogged ge $diagWareLimit">
              <break/>
            </do_if>
            <set_value name="$diagWare" exact="$diagDestWares.{$dri}"/>
            <set_value name="$cargoCount" exact="$diagStation.cargo.{$diagWare}.count"/>
            <set_value name="$cargoTarget" exact="$diagStation.cargo.{$diagWare}.target"/>
            <set_value name="$cargoTargetSafe" exact="[$cargoTarget, 1].max"/>
            <set_value name="$cargoRatio" exact="($cargoCount * 100) / $cargoTargetSafe"/>
            <find_sell_offer tradepartner="this.ship" seller="$diagStation" wares="$diagWare" result="$diagSellPartner"/>
            <find_buy_offer tradepartner="this.ship" buyer="$diagStation" wares="$diagWare" result="$diagBuyPartner"/>
            <set_value name="$sellPartnerAvail" exact="'0'"/>
            <set_value name="$sellPartnerAmount" exact="'n/a'"/>
            <do_if value="$diagSellPartner != null">
              <set_value name="$sellPartnerAmount" exact="$diagSellPartner.amount"/>
              <do_if value="$diagSellPartner.available">
                <set_value name="$sellPartnerAvail" exact="'1'"/>
              </do_if>
            </do_if>
            <set_value name="$buyPartnerAvail" exact="'0'"/>
            <set_value name="$buyPartnerAmount" exact="'n/a'"/>
            <do_if value="$diagBuyPartner != null">
              <set_value name="$buyPartnerAmount" exact="$diagBuyPartner.amount"/>
              <do_if value="$diagBuyPartner.available">
                <set_value name="$buyPartnerAvail" exact="'1'"/>
              </do_if>
            </do_if>
            <set_value name="$sellIgnoreAvail" exact="'n/a'"/>
            <set_value name="$sellIgnoreAmount" exact="'n/a'"/>
            <set_value name="$buyIgnoreAvail" exact="'n/a'"/>
            <set_value name="$buyIgnoreAmount" exact="'n/a'"/>
            <do_if value="this.$ignoretraderules and $diagStation.isplayerowned">
              <find_sell_offer seller="$diagStation" wares="$diagWare" result="$diagSellIgnore"/>
              <find_buy_offer buyer="$diagStation" wares="$diagWare" result="$diagBuyIgnore"/>
              <set_value name="$sellIgnoreAvail" exact="'0'"/>
              <set_value name="$sellIgnoreAmount" exact="'n/a'"/>
              <do_if value="$diagSellIgnore != null">
                <set_value name="$sellIgnoreAmount" exact="$diagSellIgnore.amount"/>
                <do_if value="$diagSellIgnore.available">
                  <set_value name="$sellIgnoreAvail" exact="'1'"/>
                </do_if>
              </do_if>
              <set_value name="$buyIgnoreAvail" exact="'0'"/>
              <set_value name="$buyIgnoreAmount" exact="'n/a'"/>
              <do_if value="$diagBuyIgnore != null">
                <set_value name="$buyIgnoreAmount" exact="$diagBuyIgnore.amount"/>
                <do_if value="$diagBuyIgnore.available">
                  <set_value name="$buyIgnoreAvail" exact="'1'"/>
                </do_if>
              </do_if>
            </do_if>
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': STATION dst ' + $diagStation.idcode + ' ware=' + $diagWare + ' cargo=' + $cargoCount + '/' + $cargoTarget + ' (' + $cargoRatio + '%)' + ' buy(partner:a=' + $buyPartnerAvail + ',m=' + $buyPartnerAmount + '; ignore:a=' + $buyIgnoreAvail + ',m=' + $buyIgnoreAmount + ')' + ' sell(partner:a=' + $sellPartnerAvail + ',m=' + $sellPartnerAmount + '; ignore:a=' + $sellIgnoreAvail + ',m=' + $sellIgnoreAmount + ')'" chance="this.$debugchance"/>
            <set_value name="$diagWareLogged" operation="add"/>
          </do_all>
        </do_all>
        <set_value name="this.$initLogged" exact="true"/>
      </do_if>

      <do_if value="$activeDestinations.count == 0">
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': no active destinations (destList=' + this.$destList.count + ', sourceCursor=' + (if this.$sourceStation? and this.$sourceStation.exists then this.$sourceStation.knownname else '(none)') + ' [' + (if this.$sourceStation? and this.$sourceStation.exists then this.$sourceStation.idcode else '(n/a)') + '], srcList=' + this.$activeSources.count + ' [' + $sourceNames + '], invalid=' + $destInvalidCount + ')'" chance="this.$debugchance"/>
        </do_if>
        <do_if value="$mk2MayNotify and this.$notifications ge 1 and (not this.$mk2_notifiedAllDestInvalid? or not this.$mk2_notifiedAllDestInvalid)">
          <show_notification text="'GalaxyTrader MK2: ' + {77000, 20204}" timeout="10s"/>
          <set_value name="this.$mk2_notifiedAllDestInvalid" exact="true"/>
        </do_if>
        <set_command_action commandaction="commandaction.standingby"/>
        <resume label="no_trade_retry"/>
      </do_if>
      <set_value name="this.$mk2_notifiedAllDestInvalid" exact="false"/>
      <set_value name="this.$activeDestinations" exact="$activeDestinations"/>

      <!-- Bidirectional mode: deduped union of every participating station (any can supply or receive). -->
      <create_list name="$mk2ActiveStations"/>
      <do_all exact="this.$activeSources.count" counter="$masi">
        <set_value name="$masStation" exact="this.$activeSources.{$masi}"/>
        <set_value name="$masDup" exact="false"/>
        <do_all exact="$mk2ActiveStations.count" counter="$masdi">
          <do_if value="$mk2ActiveStations.{$masdi} == $masStation">
            <set_value name="$masDup" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="not $masDup">
          <append_to_list name="$mk2ActiveStations" exact="$masStation"/>
        </do_if>
      </do_all>
      <do_all exact="this.$activeDestinations.count" counter="$masi2">
        <set_value name="$masStation" exact="this.$activeDestinations.{$masi2}"/>
        <set_value name="$masDup" exact="false"/>
        <do_all exact="$mk2ActiveStations.count" counter="$masdi2">
          <do_if value="$mk2ActiveStations.{$masdi2} == $masStation">
            <set_value name="$masDup" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="not $masDup">
          <append_to_list name="$mk2ActiveStations" exact="$masStation"/>
        </do_if>
      </do_all>

      <signal_objects object="player.galaxy" param="'GT_Check_Maintenance'" param2="table[$Ship = this.ship]"/>
      <wait exact="this.$gt_yieldMs * 1ms"/>

      <do_if value="this.ship.cargo.count gt 0">
        <!-- Sector whitelist needed for clearance blacklist preflight (same source as distribution scoring). -->
        <set_value name="this.$mk2SectorWhitelist" exact="[]"/>
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.$sectorwhitelist? and this.ship.defaultorder.$sectorwhitelist.count gt 0">
          <set_value name="this.$mk2SectorWhitelist" exact="this.ship.defaultorder.$sectorwhitelist"/>
        </do_if>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and this.ship.commander.defaultorder.$sectorwhitelist? and this.ship.commander.defaultorder.$sectorwhitelist.count gt 0">
          <set_value name="this.$mk2SectorWhitelist" exact="this.ship.commander.defaultorder.$sectorwhitelist"/>
        </do_if>
        <!-- Align with MK3 clearance tagging: [CLEARANCE] name, diagnose, info menu -->
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{this.ship}?">
          <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Ships.{this.ship}.$CargoDisposal" exact="true"/>
        <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
            $Ship = this.ship,
            $pilot = this.ship.pilot,
            $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
            $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
            $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
            $nameType = 'trader'
          ]"/>
        </do_if>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': cargo clearance - selling hold cargo before distribution cycle'" chance="this.$debugchance"/>
        </do_if>
        <set_value name="$cargoWares" exact="this.ship.cargo.list"/>
        <do_all exact="$cargoWares.count" counter="$ci">
          <set_value name="$cWare" exact="$cargoWares.{$ci}"/>
          <set_value name="$cAmount" exact="this.ship.cargo.{$cWare}.count"/>
          <do_if value="$cAmount gt 0">
            <set_value name="$clearOffer" exact="null"/>
            <set_value name="$clearStation" exact="null"/>
            <set_value name="$clearBestAmount" exact="0"/>
            <do_all exact="if this.$bidirectional then $mk2ActiveStations.count else this.$activeSources.count" counter="$sci">
              <set_value name="$clearSource" exact="if this.$bidirectional then $mk2ActiveStations.{$sci} else this.$activeSources.{$sci}"/>
              <set_value name="$clearCandidate" exact="null"/>
              <do_if value="this.$ignoretraderules and $clearSource.isplayerowned">
                <find_buy_offer buyer="$clearSource" wares="$cWare" result="$clearCandidate"/>
              </do_if>
              <do_else>
                <find_buy_offer tradepartner="this.ship" buyer="$clearSource" wares="$cWare" result="$clearCandidate"/>
              </do_else>
              <do_if value="$clearCandidate == null and this.$ignoretraderules and $clearSource.isplayerowned">
                <!-- Fallback: ignore-rules lookup may return null while partner-filtered returns a usable offer. -->
                <find_buy_offer tradepartner="this.ship" buyer="$clearSource" wares="$cWare" result="$clearCandidate"/>
              </do_if>
              <set_value name="$clearCandidateAmount" exact="0"/>
              <do_if value="$clearCandidate != null">
                <set_value name="$clearCandidateAmount" exact="$clearCandidate.offeramount.{this.ship}"/>
              </do_if>
              <do_if value="$clearCandidateAmount == null and $clearCandidate != null">
                <set_value name="$clearCandidateAmount" exact="$clearCandidate.amount"/>
              </do_if>
              <do_if value="$clearCandidateAmount == null">
                <set_value name="$clearCandidateAmount" exact="0"/>
              </do_if>
              <set_value name="$clearPreflightOk" exact="false"/>
              <do_if value="$clearCandidate != null and $clearCandidate.available and $clearCandidateAmount gt 0">
                <run_script name="'lib.gt.blacklist.validate_lane'" result="$mk2ClearLaneBL">
                  <param name="ship" value="this.ship"/>
                  <param name="sellStation" value="$clearSource"/>
                  <param name="sellOnly" value="true"/>
                  <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                  <param name="sectorWhitelist" value="if this.$mk2SectorWhitelist? then this.$mk2SectorWhitelist else []"/>
                  <param name="checkPath" value="true"/>
                  <param name="debugchance" value="0"/>
                </run_script>
                <set_value name="this.$mk2ClearLaneBL" exact="$mk2ClearLaneBL"/>
                <do_if value="not (this.$mk2ClearLaneBL.$Blocked? and this.$mk2ClearLaneBL.$Blocked)">
                  <run_script name="'lib.gt.dockcheck'" result="$mk2ClearDock">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$clearSource"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="allowStorageDock" value="this.$mk2UseWareExchange and $clearSource.isplayerowned"/>
                    <param name="useMemo" value="false"/>
                  </run_script>
                  <set_value name="this.$mk2ClearDock" exact="$mk2ClearDock"/>
                  <do_if value="this.$mk2ClearDock.$CanDock? and this.$mk2ClearDock.$CanDock">
                    <set_value name="$clearPreflightOk" exact="true"/>
                  </do_if>
                  <do_elseif value="this.$debuglevel ge 1">
                    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': clearance buyer skipped (dock: ' + (if this.$mk2ClearDock.$Reason? then this.$mk2ClearDock.$Reason else 'unknown') + ') ' + $clearSource.knownname" chance="this.$debugchance"/>
                  </do_elseif>
                </do_if>
                <do_elseif value="this.$debuglevel ge 1">
                  <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': clearance buyer skipped (blacklist ' + (if this.$mk2ClearLaneBL.$Leg? then this.$mk2ClearLaneBL.$Leg else '') + ': ' + (if this.$mk2ClearLaneBL.$Reason? then this.$mk2ClearLaneBL.$Reason else '') + ') ' + $clearSource.knownname" chance="this.$debugchance"/>
                </do_elseif>
              </do_if>
              <do_if value="$clearPreflightOk and $clearCandidateAmount gt $clearBestAmount">
                <set_value name="$clearBestAmount" exact="$clearCandidateAmount"/>
                <set_value name="$clearOffer" exact="$clearCandidate"/>
                <set_value name="$clearStation" exact="$clearSource"/>
              </do_if>
            </do_all>
            <do_if value="$clearOffer != null and $clearOffer.available and $clearBestAmount gt 0">
              <set_value name="$clearAmount" exact="[$cAmount, $clearBestAmount].min"/>
              <set_value name="this.$mk2ClearInternal" exact="if $clearStation? and $clearStation.isplayerowned then true else false"/>
              <set_value name="this.$mk2ClearOffer" exact="$clearOffer"/>
              <set_value name="this.$mk2ClearAmount" exact="$clearAmount"/>
              <wait exact="this.$gt_criticalYieldMs * 1ms" comment="Desync cargo-clear trade creation across ships"/>
              <create_trade_order object="this.ship" tradeoffer="this.$mk2ClearOffer" amount="this.$mk2ClearAmount" immediate="true" internal="this.$mk2ClearInternal"/>
            </do_if>
          </do_if>
        </do_all>
        <do_while value="this.ship.orders.count gt 0">
          <wait exact="5s">
            <interrupt>
              <conditions>
                <event_object_order_ready object="this.ship"/>
              </conditions>
            </interrupt>
          </wait>
        </do_while>
        <do_if value="global.$GT_Ships.{this.ship}.$CargoDisposal? and this.ship.cargo.count == 0">
          <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship = this.ship,
              $pilot = this.ship.pilot,
              $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
              $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType = 'trader'
            ]"/>
          </do_if>
        </do_if>
      </do_if>

      <create_list name="$manualSourceWares"/>
      <do_if value="not this.$autowares and this.$warebasket? and this.$warebasket.count gt 0">
        <do_all exact="this.$warebasket.count" counter="$wi">
          <append_to_list name="$manualSourceWares" exact="this.$warebasket.{$wi}"/>
        </do_all>
      </do_if>

      <!-- Build the union of every ware any active destination is willing to receive.
           A destination accepts a ware via two channels:
             1. resources  - production inputs the station consumes (factories/wharves).
             2. tradewares - "wares that are bought/sold at the container but are neither
                product nor resource" (per stock_game scriptproperties.xml). Trading Posts,
                Equipment Docks and similar pass-through stations expose what they buy/sell
                here, NOT in resources. Skipping tradewares hid e.g. a Trading Post buyer of
                Energy Cells from the auto-basket even though the station openly trades them.
           The variable name is kept for backward reference; the contents are the union. -->
      <create_list name="$targetResourceWares"/>
      <do_all exact="this.$activeDestinations.count" counter="$di">
        <set_value name="$dest" exact="this.$activeDestinations.{$di}"/>
        <set_value name="$destResources" exact="$dest.resources.list"/>
        <do_all exact="$destResources.count" counter="$ri">
          <set_value name="$rw" exact="$destResources.{$ri}"/>
          <set_value name="$dup" exact="false"/>
          <do_all exact="$targetResourceWares.count" counter="$dri">
            <do_if value="$targetResourceWares.{$dri} == $rw">
              <set_value name="$dup" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $dup">
            <append_to_list name="$targetResourceWares" exact="$rw"/>
          </do_if>
        </do_all>
        <set_value name="$destTradewares" exact="$dest.tradewares.list"/>
        <do_all exact="$destTradewares.count" counter="$dti">
          <set_value name="$tw" exact="$destTradewares.{$dti}"/>
          <set_value name="$dup" exact="false"/>
          <do_all exact="$targetResourceWares.count" counter="$dtri">
            <do_if value="$targetResourceWares.{$dtri} == $tw">
              <set_value name="$dup" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $dup">
            <append_to_list name="$targetResourceWares" exact="$tw"/>
          </do_if>
        </do_all>
      </do_all>
      <!-- Bidirectional: sources can also receive, so union their acceptable wares into the target list. -->
      <do_if value="this.$bidirectional">
        <do_all exact="this.$activeSources.count" counter="$bdi">
          <set_value name="$bds" exact="this.$activeSources.{$bdi}"/>
          <set_value name="$bdResources" exact="$bds.resources.list"/>
          <do_all exact="$bdResources.count" counter="$bdri">
            <set_value name="$brw" exact="$bdResources.{$bdri}"/>
            <set_value name="$dup" exact="false"/>
            <do_all exact="$targetResourceWares.count" counter="$bddi">
              <do_if value="$targetResourceWares.{$bddi} == $brw">
                <set_value name="$dup" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $dup">
              <append_to_list name="$targetResourceWares" exact="$brw"/>
            </do_if>
          </do_all>
          <set_value name="$bdTradewares" exact="$bds.tradewares.list"/>
          <do_all exact="$bdTradewares.count" counter="$bdti">
            <set_value name="$btw" exact="$bdTradewares.{$bdti}"/>
            <set_value name="$dup" exact="false"/>
            <do_all exact="$targetResourceWares.count" counter="$bddti">
              <do_if value="$targetResourceWares.{$bddti} == $btw">
                <set_value name="$dup" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $dup">
              <append_to_list name="$targetResourceWares" exact="$btw"/>
            </do_if>
          </do_all>
        </do_all>
      </do_if>

      <set_value name="$resolvedWaresDisplay" exact="''"/>
      <set_value name="$resolvedWaresCount" exact="0"/>
      <do_if value="not this.$autowares">
        <do_all exact="$manualSourceWares.count" counter="$mwi">
          <do_if value="$mwi gt 1">
            <set_value name="$resolvedWaresDisplay" exact="$resolvedWaresDisplay + ', '"/>
          </do_if>
          <set_value name="$resolvedWaresDisplay" exact="$resolvedWaresDisplay + $manualSourceWares.{$mwi}"/>
        </do_all>
        <set_value name="$resolvedWaresCount" exact="$manualSourceWares.count"/>
      </do_if>
      <do_else>
        <create_list name="$autoSelectedWares"/>
        <do_if value="this.$bidirectional">
          <do_all exact="$mk2ActiveStations.count" counter="$basketSellerIdx">
            <set_value name="$basketSeller" exact="$mk2ActiveStations.{$basketSellerIdx}"/>
            <set_value name="$basketSellerProducts" exact="$basketSeller.products.list"/>
            <set_value name="$basketSellerTradewares" exact="$basketSeller.tradewares.list"/>
            <create_list name="$basketSellerSellable"/>
            <do_all exact="$basketSellerProducts.count" counter="$bspi">
              <append_to_list name="$basketSellerSellable" exact="$basketSellerProducts.{$bspi}"/>
            </do_all>
            <do_all exact="$basketSellerTradewares.count" counter="$bsti">
              <set_value name="$bstw" exact="$basketSellerTradewares.{$bsti}"/>
              <set_value name="$dup" exact="false"/>
              <do_all exact="$basketSellerSellable.count" counter="$bsdi">
                <do_if value="$basketSellerSellable.{$bsdi} == $bstw">
                  <set_value name="$dup" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not $dup">
                <append_to_list name="$basketSellerSellable" exact="$bstw"/>
              </do_if>
            </do_all>
            <do_all exact="$mk2ActiveStations.count" counter="$basketBuyerIdx">
              <do_if value="$basketBuyerIdx == $basketSellerIdx">
                <continue/>
              </do_if>
              <set_value name="$basketBuyer" exact="$mk2ActiveStations.{$basketBuyerIdx}"/>
              <set_value name="$basketBuyerResources" exact="$basketBuyer.resources.list"/>
              <set_value name="$basketBuyerTradewares" exact="$basketBuyer.tradewares.list"/>
              <create_list name="$basketBuyerAcceptable"/>
              <do_all exact="$basketBuyerResources.count" counter="$bbri">
                <append_to_list name="$basketBuyerAcceptable" exact="$basketBuyerResources.{$bbri}"/>
              </do_all>
              <do_all exact="$basketBuyerTradewares.count" counter="$bbti">
                <set_value name="$bbtw" exact="$basketBuyerTradewares.{$bbti}"/>
                <set_value name="$dup" exact="false"/>
                <do_all exact="$basketBuyerAcceptable.count" counter="$bbdi">
                  <do_if value="$basketBuyerAcceptable.{$bbdi} == $bbtw">
                    <set_value name="$dup" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="not $dup">
                  <append_to_list name="$basketBuyerAcceptable" exact="$bbtw"/>
                </do_if>
              </do_all>
              <do_all exact="$basketSellerSellable.count" counter="$bswi">
                <set_value name="$bswv" exact="$basketSellerSellable.{$bswi}"/>
                <do_all exact="$basketBuyerAcceptable.count" counter="$bbwi">
                  <do_if value="$bswv == $basketBuyerAcceptable.{$bbwi}">
                    <set_value name="$dup" exact="false"/>
                    <do_all exact="$autoSelectedWares.count" counter="$bdupi">
                      <do_if value="$autoSelectedWares.{$bdupi} == $bswv">
                        <set_value name="$dup" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                    <do_if value="not $dup">
                      <append_to_list name="$autoSelectedWares" exact="$bswv"/>
                    </do_if>
                    <break/>
                  </do_if>
                </do_all>
              </do_all>
            </do_all>
          </do_all>
        </do_if>
        <do_else>
        <do_all exact="this.$activeSources.count" counter="$as">
          <set_value name="$autoSource" exact="this.$activeSources.{$as}"/>
          <set_value name="$autoSourceProducts" exact="$autoSource.products.list"/>
          <set_value name="$autoSourceTradewares" exact="$autoSource.tradewares.list"/>
          <create_list name="$autoSourceSellable"/>
          <do_all exact="$autoSourceProducts.count" counter="$ap">
            <append_to_list name="$autoSourceSellable" exact="$autoSourceProducts.{$ap}"/>
          </do_all>
          <do_all exact="$autoSourceTradewares.count" counter="$at">
            <set_value name="$atw" exact="$autoSourceTradewares.{$at}"/>
            <set_value name="$dup" exact="false"/>
            <do_all exact="$autoSourceSellable.count" counter="$ad">
              <do_if value="$autoSourceSellable.{$ad} == $atw">
                <set_value name="$dup" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $dup">
              <append_to_list name="$autoSourceSellable" exact="$atw"/>
            </do_if>
          </do_all>
          <do_all exact="$autoSourceSellable.count" counter="$aw">
            <set_value name="$awv" exact="$autoSourceSellable.{$aw}"/>
            <do_all exact="$targetResourceWares.count" counter="$trw">
              <do_if value="$awv == $targetResourceWares.{$trw}">
                <set_value name="$dup" exact="false"/>
                <do_all exact="$autoSelectedWares.count" counter="$dupi">
                  <do_if value="$autoSelectedWares.{$dupi} == $awv">
                    <set_value name="$dup" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="not $dup">
                  <append_to_list name="$autoSelectedWares" exact="$awv"/>
                </do_if>
                <break/>
              </do_if>
            </do_all>
          </do_all>
        </do_all>
        </do_else>
        <do_all exact="$autoSelectedWares.count" counter="$awi">
          <do_if value="$awi gt 1">
            <set_value name="$resolvedWaresDisplay" exact="$resolvedWaresDisplay + ', '"/>
          </do_if>
          <set_value name="$resolvedWaresDisplay" exact="$resolvedWaresDisplay + $autoSelectedWares.{$awi}"/>
        </do_all>
        <set_value name="$resolvedWaresCount" exact="$autoSelectedWares.count"/>
      </do_else>
      <set_value name="$currentWaresDisplay" exact="''"/>
      <do_if value="this.$warebasket? and this.$warebasket.count gt 0">
        <do_all exact="this.$warebasket.count" counter="$cwi">
          <do_if value="$cwi gt 1">
            <set_value name="$currentWaresDisplay" exact="$currentWaresDisplay + ', '"/>
          </do_if>
          <set_value name="$currentWaresDisplay" exact="$currentWaresDisplay + this.$warebasket.{$cwi}"/>
        </do_all>
      </do_if>

      <!-- Keep the UI-selected ware list in sync while AutoWares is enabled,
           but ONLY when the actual default-order warebasket differs. -->
      <do_if value="this.$autowares and $resolvedWaresDisplay != $currentWaresDisplay and this.ship.defaultorder? and this.ship.defaultorder.id == 'GalaxyTraderMK2'">
        <set_value name="this.$warebasket" exact="$autoSelectedWares"/>
        <edit_order_param order="this.ship.defaultorder" param="'warebasket'" value="$autoSelectedWares"/>
      </do_if>

      <do_if value="this.$debuglevel ge 1 and $resolvedWaresDisplay != this.$lastResolvedWaresDisplay">
        <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': resolved wares (' + (if this.$autowares then 'auto' else 'manual') + ') count=' + $resolvedWaresCount + ' [' + $resolvedWaresDisplay + ']'" chance="this.$debugchance"/>
        <!-- AUTOWARES selection trace: when the resolved basket changes, dump the full
             input lists (per-source sellable wares, per-destination acceptable wares) and
             the union/intersection that produced the outgoing selection. Bounded to the
             change-detection gate above so it does not spam every trade cycle. The trace
             only makes sense in auto mode; manual mode just echoes $manualSourceWares. -->
        <do_if value="this.$autowares">
          <set_value name="$awTargetUnionDisplay" exact="''"/>
          <do_all exact="$targetResourceWares.count" counter="$awtui">
            <do_if value="$awtui gt 1">
              <set_value name="$awTargetUnionDisplay" exact="$awTargetUnionDisplay + ', '"/>
            </do_if>
            <set_value name="$awTargetUnionDisplay" exact="$awTargetUnionDisplay + $targetResourceWares.{$awtui}"/>
          </do_all>
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': AUTOWARES receiver-union (resources + tradewares across ' + this.$activeDestinations.count + ' destinations' + (if this.$bidirectional then ' + ' + this.$activeSources.count + ' sources [bidirectional]' else '') + ') count=' + $targetResourceWares.count + ' [' + $awTargetUnionDisplay + ']'" chance="this.$debugchance"/>
          <do_all exact="this.$activeSources.count" counter="$awsi">
            <set_value name="$awSrc" exact="this.$activeSources.{$awsi}"/>
            <set_value name="$awSrcProducts" exact="$awSrc.products.list"/>
            <set_value name="$awSrcTradewares" exact="$awSrc.tradewares.list"/>
            <create_list name="$awSrcSellable"/>
            <do_all exact="$awSrcProducts.count" counter="$awspi">
              <append_to_list name="$awSrcSellable" exact="$awSrcProducts.{$awspi}"/>
            </do_all>
            <do_all exact="$awSrcTradewares.count" counter="$awsti">
              <set_value name="$awstw" exact="$awSrcTradewares.{$awsti}"/>
              <set_value name="$dup" exact="false"/>
              <do_all exact="$awSrcSellable.count" counter="$awsdi">
                <do_if value="$awSrcSellable.{$awsdi} == $awstw">
                  <set_value name="$dup" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not $dup">
                <append_to_list name="$awSrcSellable" exact="$awstw"/>
              </do_if>
            </do_all>
            <set_value name="$awSrcDisplay" exact="''"/>
            <do_all exact="$awSrcSellable.count" counter="$awsdi2">
              <do_if value="$awsdi2 gt 1">
                <set_value name="$awSrcDisplay" exact="$awSrcDisplay + ', '"/>
              </do_if>
              <set_value name="$awSrcDisplay" exact="$awSrcDisplay + $awSrcSellable.{$awsdi2}"/>
            </do_all>
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': AUTOWARES src ' + $awSrc.knownname + ' [' + $awSrc.idcode + '] products=' + $awSrcProducts.count + ' tradewares=' + $awSrcTradewares.count + ' sellable=' + $awSrcSellable.count + ' [' + $awSrcDisplay + ']'" chance="this.$debugchance"/>
          </do_all>
          <do_all exact="this.$activeDestinations.count" counter="$awdi">
            <set_value name="$awDst" exact="this.$activeDestinations.{$awdi}"/>
            <set_value name="$awDstResources" exact="$awDst.resources.list"/>
            <set_value name="$awDstTradewares" exact="$awDst.tradewares.list"/>
            <create_list name="$awDstAcceptable"/>
            <do_all exact="$awDstResources.count" counter="$awdri">
              <append_to_list name="$awDstAcceptable" exact="$awDstResources.{$awdri}"/>
            </do_all>
            <do_all exact="$awDstTradewares.count" counter="$awdti">
              <set_value name="$awdtw" exact="$awDstTradewares.{$awdti}"/>
              <set_value name="$dup" exact="false"/>
              <do_all exact="$awDstAcceptable.count" counter="$awddi">
                <do_if value="$awDstAcceptable.{$awddi} == $awdtw">
                  <set_value name="$dup" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not $dup">
                <append_to_list name="$awDstAcceptable" exact="$awdtw"/>
              </do_if>
            </do_all>
            <set_value name="$awDstDisplay" exact="''"/>
            <do_all exact="$awDstAcceptable.count" counter="$awddi2">
              <do_if value="$awddi2 gt 1">
                <set_value name="$awDstDisplay" exact="$awDstDisplay + ', '"/>
              </do_if>
              <set_value name="$awDstDisplay" exact="$awDstDisplay + $awDstAcceptable.{$awddi2}"/>
            </do_all>
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': AUTOWARES dst ' + $awDst.knownname + ' [' + $awDst.idcode + '] resources=' + $awDstResources.count + ' tradewares=' + $awDstTradewares.count + ' acceptable=' + $awDstAcceptable.count + ' [' + $awDstDisplay + ']'" chance="this.$debugchance"/>
          </do_all>
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': AUTOWARES selection (' + (if this.$bidirectional then 'bidirectional pair mesh' else 'sources sellable INTERSECT destinations acceptable') + ') count=' + $resolvedWaresCount + ' [' + $resolvedWaresDisplay + ']'" chance="this.$debugchance"/>
        </do_if>
      </do_if>
      <set_value name="this.$lastResolvedWaresDisplay" exact="$resolvedWaresDisplay"/>

      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestSourceOffer" exact="null"/>
      <set_value name="$bestDestOffer" exact="null"/>
      <set_value name="$bestSourceOfferAmount" exact="0"/>
      <set_value name="$bestDestOfferAmount" exact="0"/>
      <set_value name="$bestScore" exact="-1"/>
      <create_list name="this.$mk2TradeList"/>
      <set_value name="this.$gt_dockMemo" exact="table[]"/>
      <set_value name="$evalPairs" exact="0"/>
      <set_value name="$skipIllegalOrNoCargo" exact="0"/>
      <set_value name="$skipNoSourceOffer" exact="0"/>
      <set_value name="$skipSourceNoTarget" exact="0"/>
      <set_value name="$skipSourceBelowStatic" exact="0"/>
      <set_value name="$skipSelfTarget" exact="0"/>
      <set_value name="$skipDistance" exact="0"/>
      <set_value name="$skipNoDestOffer" exact="0"/>
      <set_value name="$skipNoNeed" exact="0"/>
      <set_value name="$skipMinTrade" exact="0"/>
      <set_value name="$skipReserved" exact="0"/>
      <set_value name="$skipDocking" exact="0"/>
      <set_value name="$skipPingPong" exact="0"/>
      <set_value name="$skipBlacklist" exact="0"/>
      <set_value name="this.$mk2SectorWhitelist" exact="[]"/>
      <do_if value="this.ship.defaultorder? and this.ship.defaultorder.$sectorwhitelist? and this.ship.defaultorder.$sectorwhitelist.count gt 0">
        <set_value name="this.$mk2SectorWhitelist" exact="this.ship.defaultorder.$sectorwhitelist"/>
      </do_if>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and this.ship.commander.defaultorder.$sectorwhitelist? and this.ship.commander.defaultorder.$sectorwhitelist.count gt 0">
        <set_value name="this.$mk2SectorWhitelist" exact="this.ship.commander.defaultorder.$sectorwhitelist"/>
      </do_if>
      <set_value name="$sourceBelowStaticDetails" exact="''"/>
      <set_value name="$sourceBelowStaticDetailCount" exact="0"/>
      <set_value name="$noSourceOfferDetails" exact="''"/>
      <set_value name="$noSourceOfferDetailCount" exact="0"/>
      <set_value name="$noDestOfferDetails" exact="''"/>
      <set_value name="$noDestOfferDetailCount" exact="0"/>
      <set_value name="$noNeedDetails" exact="''"/>
      <set_value name="$noNeedDetailCount" exact="0"/>
      <set_value name="$pilotLevelProfile" exact="1"/>
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
        <set_value name="$pilotLevelProfile" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
      </do_if>
      <set_value name="$pilotLevelProfile" exact="[1, [15, $pilotLevelProfile].min].max"/>
      <set_value name="$routeT" exact="$pilotLevelProfile / 15.0"/>
      <set_value name="$routeAlpha" exact="0.45 - (0.20 * $routeT)"/>
      <set_value name="$routeBeta" exact="1.00 - (0.40 * $routeT)"/>
      <set_value name="$routeLaneBonus" exact="1.05 + (0.20 * $routeT)"/>
      <set_value name="$stickinessTTLProfile" exact="[4, 1 + (($pilotLevelProfile - 1) / 4)i].min"/>
      <set_value name="$lowFloorProfileMin" exact="[1, 20 - ($pilotLevelProfile / 3)i].max"/>
      <set_value name="$lowVolumeFloorEffPercent" exact="if this.$allowlowvolume then [this.$lowvolumefloorpercent, $lowFloorProfileMin].max else this.$lowvolumefloorpercent"/>
      <set_value name="this.$mk2PilotLevelProfile" exact="$pilotLevelProfile"/>
      <set_value name="this.$mk2RouteT" exact="$routeT"/>
      <set_value name="this.$mk2RouteAlpha" exact="$routeAlpha"/>
      <set_value name="this.$mk2RouteBeta" exact="$routeBeta"/>
      <set_value name="this.$mk2RouteLaneBonus" exact="$routeLaneBonus"/>
      <set_value name="this.$mk2LowVolumeFloorEffPercent" exact="$lowVolumeFloorEffPercent"/>
      <set_value name="this.$mk2StickinessTTLProfile" exact="$stickinessTTLProfile"/>
      <do_if value="this.$stickyCyclesLeft gt 0">
        <do_if value="not this.$stickySource? or not this.$stickySource.exists or not this.$stickyDestination? or not this.$stickyDestination.exists">
          <set_value name="this.$stickySource" exact="null"/>
          <set_value name="this.$stickyDestination" exact="null"/>
          <set_value name="this.$stickyWare" exact="null"/>
          <set_value name="this.$stickyCyclesLeft" exact="0"/>
        </do_if>
      </do_if>

      <create_list name="$mk2LoopSuppliers"/>
      <create_list name="$mk2LoopCustomers"/>
      <do_if value="this.$bidirectional">
        <do_all exact="$mk2ActiveStations.count" counter="$mli">
          <append_to_list name="$mk2LoopSuppliers" exact="$mk2ActiveStations.{$mli}"/>
          <append_to_list name="$mk2LoopCustomers" exact="$mk2ActiveStations.{$mli}"/>
        </do_all>
      </do_if>
      <do_else>
        <do_all exact="this.$activeSources.count" counter="$mli">
          <append_to_list name="$mk2LoopSuppliers" exact="this.$activeSources.{$mli}"/>
        </do_all>
        <do_all exact="this.$activeDestinations.count" counter="$mli2">
          <append_to_list name="$mk2LoopCustomers" exact="this.$activeDestinations.{$mli2}"/>
        </do_all>
      </do_else>

      <do_all exact="$mk2LoopSuppliers.count" counter="$sidx">
        <set_value name="$source" exact="$mk2LoopSuppliers.{$sidx}"/>
        <create_list name="$effectiveWares"/>
        <do_if value="not this.$autowares">
          <do_all exact="$manualSourceWares.count" counter="$mwi">
            <append_to_list name="$effectiveWares" exact="$manualSourceWares.{$mwi}"/>
          </do_all>
        </do_if>
        <do_else>
          <set_value name="$sourceProducts" exact="$source.products.list"/>
          <set_value name="$sourceTradewares" exact="$source.tradewares.list"/>
          <create_list name="$sourceSellableWares"/>
          <do_all exact="$sourceProducts.count" counter="$pi">
            <append_to_list name="$sourceSellableWares" exact="$sourceProducts.{$pi}"/>
          </do_all>
          <do_all exact="$sourceTradewares.count" counter="$ti">
            <set_value name="$tw" exact="$sourceTradewares.{$ti}"/>
            <set_value name="$dup" exact="false"/>
            <do_all exact="$sourceSellableWares.count" counter="$dci">
              <do_if value="$sourceSellableWares.{$dci} == $tw">
                <set_value name="$dup" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $dup">
              <append_to_list name="$sourceSellableWares" exact="$tw"/>
            </do_if>
          </do_all>
          <do_if value="this.$mk2UseWareExchange and $source.isplayerowned">
            <set_value name="$sourceCargoWares" exact="$source.cargo.list"/>
            <do_all exact="$sourceCargoWares.count" counter="$sci">
              <set_value name="$cw" exact="$sourceCargoWares.{$sci}"/>
              <do_if value="$source.cargo.{$cw}.target gt 0 and $source.cargo.{$cw}.count gt 0">
                <set_value name="$dup" exact="false"/>
                <do_all exact="$sourceSellableWares.count" counter="$scdi">
                  <do_if value="$sourceSellableWares.{$scdi} == $cw">
                    <set_value name="$dup" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="not $dup">
                  <append_to_list name="$sourceSellableWares" exact="$cw"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          <do_all exact="$sourceSellableWares.count" counter="$siw">
            <set_value name="$sw" exact="$sourceSellableWares.{$siw}"/>
            <do_all exact="$targetResourceWares.count" counter="$trw">
              <do_if value="$sw == $targetResourceWares.{$trw}">
                <append_to_list name="$effectiveWares" exact="$sw"/>
                <break/>
              </do_if>
            </do_all>
          </do_all>
        </do_else>

        <do_all exact="$effectiveWares.count" counter="$wi">
          <set_value name="$ware" exact="$effectiveWares.{$wi}"/>
          <set_value name="this.$mk2ScoringWare" exact="$ware"/>
          <set_value name="this.$mk2ScoringSource" exact="$source"/>
          <set_value name="$evalPairs" operation="add"/>
          <do_if value="this.ship.cargo.{$ware}.max le 0 or (not this.$allowillegal and $ware.illegal)">
            <set_value name="$skipIllegalOrNoCargo" operation="add"/>
            <continue/>
          </do_if>
          <set_value name="$sourceStorageDiscovery" exact="false"/>
          <set_value name="$sourceOffer" exact="null"/>
          <run_script name="'lib.gt.tradematch'" result="$mk2SourceOfferResolve">
            <param name="mode" value="'mk2_player_offer'"/>
            <param name="operation" value="'find'"/>
            <param name="lineType" value="'source'"/>
            <param name="ship" value="this.ship"/>
            <param name="station" value="$source"/>
            <param name="wareText" value="$ware"/>
            <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
          </run_script>
          <set_value name="$sourceOffer" exact="$mk2SourceOfferResolve.$Offer"/>
          <set_value name="$sourceTarget" exact="$source.cargo.{$ware}.target"/>
          <set_value name="$sourceCargoCount" exact="$source.cargo.{$ware}.count"/>
          <get_ware_reservation object="$source" ware="$ware" type="buy" virtual="false" result="$sourceOutgoingReserved"/>
          <set_value name="$sourceEffectiveCount" exact="[$sourceCargoCount - $sourceOutgoingReserved, 0].max"/>
          <set_value name="$sourceTargetSafe" exact="[$sourceTarget, 1].max"/>
          <set_value name="$sourceRatio" exact="($sourceEffectiveCount * 100) / $sourceTargetSafe"/>
          <set_value name="$sourceFillRatio" exact="($sourceCargoCount * 100) / $sourceTargetSafe"/>
          <do_if value="this.$mk2UseWareExchange and $source.isplayerowned and $sourceTarget gt 0 and $sourceEffectiveCount gt 0 and $sourceFillRatio ge this.$staticStorage">
            <set_value name="$sourceStorageDiscovery" exact="true"/>
            <set_value name="$sourceOfferAmount" exact="[$sourceEffectiveCount, this.ship.cargo.{$ware}.max].min"/>
          </do_if>
          <do_if value="not $sourceStorageDiscovery">
            <do_if value="$sourceOffer == null">
              <set_value name="$skipNoSourceOffer" operation="add"/>
              <do_if value="this.$debuglevel ge 1 and $noSourceOfferDetailCount lt 10">
                <do_if value="$noSourceOfferDetailCount gt 0">
                  <set_value name="$noSourceOfferDetails" exact="$noSourceOfferDetails + '; '"/>
                </do_if>
                <set_value name="$sourceOfferAvailableFlag" exact="'0'"/>
                <set_value name="$sourceOfferAmountText" exact="'n/a'"/>
                <run_script name="'lib.gt.tradematch'" result="$sourceOfferDiagProbe">
                  <param name="mode" value="'offerdiag_probe'"/>
                  <param name="lineType" value="'source'"/>
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$source"/>
                  <param name="wareText" value="$ware"/>
                  <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
                </run_script>
                <set_value name="$sourceOfferMode" exact="$sourceOfferDiagProbe.$Mode"/>
                <set_value name="$sourceOfferAltAvailableFlag" exact="$sourceOfferDiagProbe.$AltUnavailableFlag"/>
                <set_value name="$sourceOfferAltAmountText" exact="$sourceOfferDiagProbe.$AltAmountText"/>
                <run_script name="'lib.gt.tradematch'" result="$sourceOfferDetailText">
                  <param name="mode" value="'offerdiag'"/>
                  <param name="lineType" value="'source'"/>
                  <param name="station" value="$source"/>
                  <param name="wareText" value="$ware"/>
                  <param name="isPlayerOwned" value="$source.isplayerowned"/>
                  <param name="diagMode" value="$sourceOfferMode"/>
                  <param name="unavailableFlag" value="$sourceOfferAvailableFlag"/>
                  <param name="amountText" value="$sourceOfferAmountText"/>
                  <param name="altUnavailableFlag" value="$sourceOfferAltAvailableFlag"/>
                  <param name="altAmountText" value="$sourceOfferAltAmountText"/>
                </run_script>
                <set_value name="$noSourceOfferDetails" exact="$noSourceOfferDetails + $sourceOfferDetailText + ' storageDiscovery=0 cargo=' + $sourceCargoCount + '/' + $sourceTarget + ' fill=' + $sourceFillRatio + '% eff=' + $sourceEffectiveCount + ' (' + $sourceRatio + '%)'"/>
                <set_value name="$noSourceOfferDetailCount" operation="add"/>
              </do_if>
              <continue/>
            </do_if>
            <set_value name="$sourceOfferAmount" exact="$sourceOffer.offeramount.{this.ship}"/>
            <do_if value="($sourceOfferAmount == null or $sourceOfferAmount le 0) and this.$mk2UseWareExchange and $source.isplayerowned">
              <!-- Internal player-owned flow: derive transferable amount if offeramount is unresolved/zero. -->
              <set_value name="$sourceOfferAmount" exact="[$source.cargo.{$ware}.count, this.ship.cargo.{$ware}.max].min"/>
            </do_if>
            <do_if value="$sourceOfferAmount == null">
              <set_value name="$sourceOfferAmount" exact="0"/>
            </do_if>
            <do_if value="not $sourceOffer.available or $sourceOfferAmount le 0">
              <set_value name="$skipNoSourceOffer" operation="add"/>
              <do_if value="this.$debuglevel ge 1 and $noSourceOfferDetailCount lt 10">
                <do_if value="$noSourceOfferDetailCount gt 0">
                  <set_value name="$noSourceOfferDetails" exact="$noSourceOfferDetails + '; '"/>
                </do_if>
                <set_value name="$sourceOfferAvailableFlag" exact="'1'"/>
                <set_value name="$sourceOfferAmountText" exact="'n/a'"/>
                <do_if value="not $sourceOffer.available">
                  <set_value name="$sourceOfferAvailableFlag" exact="'0'"/>
                </do_if>
                <set_value name="$sourceOfferAmountText" exact="$sourceOfferAmount"/>
                <run_script name="'lib.gt.tradematch'" result="$sourceOfferDiagProbe">
                  <param name="mode" value="'offerdiag_probe'"/>
                  <param name="lineType" value="'source'"/>
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$source"/>
                  <param name="wareText" value="$ware"/>
                  <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
                </run_script>
                <set_value name="$sourceOfferMode" exact="$sourceOfferDiagProbe.$Mode"/>
                <set_value name="$sourceOfferAltAvailableFlag" exact="$sourceOfferDiagProbe.$AltUnavailableFlag"/>
                <set_value name="$sourceOfferAltAmountText" exact="$sourceOfferDiagProbe.$AltAmountText"/>
                <run_script name="'lib.gt.tradematch'" result="$sourceOfferDetailText">
                  <param name="mode" value="'offerdiag'"/>
                  <param name="lineType" value="'source'"/>
                  <param name="station" value="$source"/>
                  <param name="wareText" value="$ware"/>
                  <param name="isPlayerOwned" value="$source.isplayerowned"/>
                  <param name="diagMode" value="$sourceOfferMode"/>
                  <param name="unavailableFlag" value="$sourceOfferAvailableFlag"/>
                  <param name="amountText" value="$sourceOfferAmountText"/>
                  <param name="altUnavailableFlag" value="$sourceOfferAltAvailableFlag"/>
                  <param name="altAmountText" value="$sourceOfferAltAmountText"/>
                </run_script>
                <set_value name="$noSourceOfferDetails" exact="$noSourceOfferDetails + $sourceOfferDetailText"/>
                <set_value name="$noSourceOfferDetailCount" operation="add"/>
              </do_if>
              <continue/>
            </do_if>
            <do_if value="$sourceTarget le 0">
              <set_value name="$skipSourceNoTarget" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="$sourceRatio le this.$staticStorage">
              <set_value name="$skipSourceBelowStatic" operation="add"/>
              <do_if value="this.$debuglevel ge 1 and $sourceBelowStaticDetailCount lt 8">
                <do_if value="$sourceBelowStaticDetailCount gt 0">
                  <set_value name="$sourceBelowStaticDetails" exact="$sourceBelowStaticDetails + '; '"/>
                </do_if>
                <set_value name="$sourceBelowStaticDetails" exact="$sourceBelowStaticDetails + $source.knownname + ' [' + $source.idcode + ']:' + $ware + '=' + $sourceRatio + '% LE ' + this.$staticStorage + '%'"/>
                <set_value name="$sourceBelowStaticDetailCount" operation="add"/>
              </do_if>
              <continue/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="this.$debuglevel ge 2">
              <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': storage-discovery source ' + $source.idcode + ':' + $ware + ' cargo=' + $sourceEffectiveCount + '/' + $sourceTarget + ' (' + $sourceRatio + '%)'" chance="this.$debugchance"/>
            </do_if>
          </do_else>

          <set_value name="this.$mk2ScoringSource" exact="$source"/>
          <set_value name="this.$mk2ScoringWare" exact="$ware"/>
          <set_value name="this.$mk2ScoringSourceOffer" exact="$sourceOffer"/>
          <set_value name="this.$mk2ScoringSourceOfferAmount" exact="if $sourceOfferAmount? then $sourceOfferAmount else 0"/>
          <set_value name="this.$mk2ScoringSourceStorageDiscovery" exact="$sourceStorageDiscovery"/>
          <set_value name="this.$mk2ScoringSourceRatio" exact="$sourceRatio"/>
          <set_value name="this.$mk2ScoringSourceFillRatio" exact="$sourceFillRatio"/>
          <set_value name="this.$mk2DirectDestPairs" exact="[]"/>
          <set_value name="this.$mk2CandidateBuyOffers" exact="[]"/>
          <do_all exact="$mk2LoopCustomers.count" counter="$di">
            <set_value name="$dest" exact="$mk2LoopCustomers.{$di}"/>
            <set_value name="$source" exact="this.$mk2ScoringSource"/>
            <set_value name="$ware" exact="this.$mk2ScoringWare"/>
            <do_if value="$dest == $source">
              <set_value name="$skipSelfTarget" operation="add"/>
              <continue/>
            </do_if>
            <run_script name="'lib.gt.blacklist.validate_lane'" result="$mk2LaneBL">
              <param name="ship" value="this.ship"/>
              <param name="buyStation" value="$source"/>
              <param name="sellStation" value="$dest"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="sectorWhitelist" value="if this.$mk2SectorWhitelist? then this.$mk2SectorWhitelist else []"/>
              <param name="checkPath" value="false"/>
              <param name="debugchance" value="0"/>
            </run_script>
            <set_value name="this.$mk2LaneBL" exact="$mk2LaneBL"/>
            <do_if value="this.$mk2LaneBL.$Blocked? and this.$mk2LaneBL.$Blocked">
              <set_value name="$skipBlacklist" operation="add"/>
              <continue/>
            </do_if>
            <do_if value="this.$maxDistance gt 0">
              <set_value name="$dist" exact="-1"/>
              <do_if value="$source.sector == $dest.sector">
                <set_value name="$dist" exact="0"/>
              </do_if>
              <do_else>
                <set_value name="$dist" exact="$source.sector.gatedistance.{$dest.sector}.{if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian}.{this.ship}"/>
              </do_else>
              <do_if value="$dist lt 0 or $dist gt this.$maxDistance">
                <set_value name="$skipDistance" operation="add"/>
                <continue/>
              </do_if>
            </do_if>

            <set_value name="$destStorageDiscovery" exact="false"/>
            <set_value name="$destOffer" exact="null"/>
            <run_script name="'lib.gt.tradematch'" result="$mk2DestOfferResolve">
              <param name="mode" value="'mk2_player_offer'"/>
              <param name="operation" value="'find'"/>
              <param name="lineType" value="'dest'"/>
              <param name="ship" value="this.ship"/>
              <param name="station" value="$dest"/>
              <param name="wareText" value="$ware"/>
              <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
            </run_script>
            <set_value name="$destOffer" exact="$mk2DestOfferResolve.$Offer"/>
            <set_value name="$destTargetPeek" exact="[$dest.cargo.{$ware}.target, 1].max"/>
            <set_value name="$destRatioPeek" exact="($dest.cargo.{$ware}.count * 100) / $destTargetPeek"/>
            <do_if value="this.$mk2UseWareExchange and $dest.isplayerowned">
              <set_value name="$destGapPeek" exact="[0, $dest.cargo.{$ware}.target - $dest.cargo.{$ware}.count].max"/>
              <do_if value="$destGapPeek gt 0">
                <set_value name="$destStorageDiscovery" exact="true"/>
                <set_value name="$destOfferAmount" exact="$destGapPeek"/>
              </do_if>
            </do_if>
            <do_if value="not $destStorageDiscovery">
              <do_if value="$destOffer == null">
                <set_value name="$skipNoDestOffer" operation="add"/>
                <do_if value="this.$debuglevel ge 1 and $noDestOfferDetailCount lt 12">
                  <do_if value="$noDestOfferDetailCount gt 0">
                    <set_value name="$noDestOfferDetails" exact="$noDestOfferDetails + '; '"/>
                  </do_if>
                  <set_value name="$destOfferAvailableFlag" exact="'0'"/>
                  <set_value name="$destOfferAmountText" exact="'n/a'"/>
                  <run_script name="'lib.gt.tradematch'" result="$destOfferDiagProbe">
                    <param name="mode" value="'offerdiag_probe'"/>
                    <param name="lineType" value="'dest'"/>
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$dest"/>
                    <param name="wareText" value="$ware"/>
                    <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
                  </run_script>
                  <set_value name="$destOfferMode" exact="$destOfferDiagProbe.$Mode"/>
                  <set_value name="$destOfferAltAvailableFlag" exact="$destOfferDiagProbe.$AltUnavailableFlag"/>
                  <set_value name="$destOfferAltAmountText" exact="$destOfferDiagProbe.$AltAmountText"/>
                  <run_script name="'lib.gt.tradematch'" result="$destOfferDetailText">
                    <param name="mode" value="'offerdiag'"/>
                    <param name="lineType" value="'dest'"/>
                    <param name="sourceStation" value="$source"/>
                    <param name="station" value="$dest"/>
                    <param name="wareText" value="$ware"/>
                    <param name="isPlayerOwned" value="$dest.isplayerowned"/>
                    <param name="diagMode" value="$destOfferMode"/>
                    <param name="unavailableFlag" value="$destOfferAvailableFlag"/>
                    <param name="amountText" value="$destOfferAmountText"/>
                    <param name="altUnavailableFlag" value="$destOfferAltAvailableFlag"/>
                    <param name="altAmountText" value="$destOfferAltAmountText"/>
                    <param name="cargoCount" value="$dest.cargo.{$ware}.count"/>
                    <param name="cargoTarget" value="$destTargetPeek"/>
                    <param name="cargoRatio" value="$destRatioPeek"/>
                  </run_script>
                  <set_value name="$noDestOfferDetails" exact="$noDestOfferDetails + $destOfferDetailText + ' storageDiscovery=0'"/>
                  <set_value name="$noDestOfferDetailCount" operation="add"/>
                </do_if>
                <continue/>
              </do_if>
              <set_value name="$destOfferAmount" exact="$destOffer.offeramount.{this.ship}"/>
              <do_if value="($destOfferAmount == null or $destOfferAmount le 0) and this.$mk2UseWareExchange and $dest.isplayerowned">
                <set_value name="$destOfferAmount" exact="[0, $dest.cargo.{$ware}.target - $dest.cargo.{$ware}.count].max"/>
              </do_if>
              <do_if value="$destOfferAmount == null">
                <set_value name="$destOfferAmount" exact="0"/>
              </do_if>
              <do_if value="not $destOffer.available or $destOfferAmount le 0">
                <set_value name="$skipNoDestOffer" operation="add"/>
                <do_if value="this.$debuglevel ge 1 and $noDestOfferDetailCount lt 12">
                  <do_if value="$noDestOfferDetailCount gt 0">
                    <set_value name="$noDestOfferDetails" exact="$noDestOfferDetails + '; '"/>
                  </do_if>
                  <set_value name="$destOfferAvailableFlag" exact="'1'"/>
                  <set_value name="$destOfferAmountText" exact="$destOfferAmount"/>
                  <do_if value="not $destOffer.available">
                    <set_value name="$destOfferAvailableFlag" exact="'0'"/>
                  </do_if>
                  <run_script name="'lib.gt.tradematch'" result="$destOfferDiagProbe">
                    <param name="mode" value="'offerdiag_probe'"/>
                    <param name="lineType" value="'dest'"/>
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$dest"/>
                    <param name="wareText" value="$ware"/>
                    <param name="ignoreTradeRules" value="this.$ignoretraderules"/>
                  </run_script>
                  <set_value name="$destOfferMode" exact="$destOfferDiagProbe.$Mode"/>
                  <set_value name="$destOfferAltAvailableFlag" exact="$destOfferDiagProbe.$AltUnavailableFlag"/>
                  <set_value name="$destOfferAltAmountText" exact="$destOfferDiagProbe.$AltAmountText"/>
                  <run_script name="'lib.gt.tradematch'" result="$destOfferDetailText">
                    <param name="mode" value="'offerdiag'"/>
                    <param name="lineType" value="'dest'"/>
                    <param name="sourceStation" value="$source"/>
                    <param name="station" value="$dest"/>
                    <param name="wareText" value="$ware"/>
                    <param name="isPlayerOwned" value="$dest.isplayerowned"/>
                    <param name="diagMode" value="$destOfferMode"/>
                    <param name="unavailableFlag" value="$destOfferAvailableFlag"/>
                    <param name="amountText" value="$destOfferAmountText"/>
                    <param name="altUnavailableFlag" value="$destOfferAltAvailableFlag"/>
                    <param name="altAmountText" value="$destOfferAltAmountText"/>
                    <param name="cargoCount" value="$dest.cargo.{$ware}.count"/>
                    <param name="cargoTarget" value="$destTargetPeek"/>
                    <param name="cargoRatio" value="$destRatioPeek"/>
                  </run_script>
                  <set_value name="$noDestOfferDetails" exact="$noDestOfferDetails + $destOfferDetailText"/>
                  <set_value name="$noDestOfferDetailCount" operation="add"/>
                </do_if>
                <continue/>
              </do_if>
            </do_if>
            <do_if value="$sourceStorageDiscovery or $destStorageDiscovery">
              <run_script name="'lib.gt.dockcheck'" result="$mk2PairSourceDock">
                <param name="ship" value="this.ship"/>
                <param name="station" value="$source"/>
                <param name="purpose" value="'trade'"/>
                <param name="allowStorageDock" value="this.$mk2UseWareExchange and $source.isplayerowned"/>
                <param name="useMemo" value="true"/>
              </run_script>
              <set_value name="this.$mk2PairSourceDock" exact="$mk2PairSourceDock"/>
              <run_script name="'lib.gt.dockcheck'" result="$mk2PairDestDock">
                <param name="ship" value="this.ship"/>
                <param name="station" value="$dest"/>
                <param name="purpose" value="'trade'"/>
                <param name="allowStorageDock" value="this.$mk2UseWareExchange and $dest.isplayerowned"/>
                <param name="useMemo" value="true"/>
              </run_script>
              <set_value name="this.$mk2PairDestDock" exact="$mk2PairDestDock"/>
              <do_if value="not this.$mk2PairSourceDock.$CanDock or not this.$mk2PairDestDock.$CanDock">
                <set_value name="$skipDocking" operation="add"/>
                <continue/>
              </do_if>
              <append_to_list name="this.$mk2DirectDestPairs" exact="table[
                $Dest = $dest,
                $DestOffer = $destOffer,
                $DestOfferAmount = $destOfferAmount,
                $DestStorageDiscovery = $destStorageDiscovery,
                $DestTarget = $destTargetPeek,
                $DestRatio = $destRatioPeek
              ]"/>
              <continue/>
            </do_if>
            <append_to_list name="this.$mk2CandidateBuyOffers" exact="$destOffer"/>
          </do_all>

          <do_if value="this.$mk2DirectDestPairs? and this.$mk2DirectDestPairs.count gt 0">
            <set_value name="$mk2AvailableTradeWaresCount" exact="1"/>
            <do_all exact="this.$mk2DirectDestPairs.count" counter="$mdpi">
              <set_value name="this.$mk2DirectPair" exact="this.$mk2DirectDestPairs.{$mdpi}"/>
              <do_if value="not this.$mk2DirectPair? or this.$mk2DirectPair == null">
                <continue/>
              </do_if>
              <set_value name="$dest" exact="this.$mk2DirectPair.$Dest"/>
              <set_value name="$destOffer" exact="this.$mk2DirectPair.$DestOffer"/>
              <set_value name="$destOfferAmount" exact="this.$mk2DirectPair.$DestOfferAmount"/>
              <set_value name="$destStorageDiscovery" exact="this.$mk2DirectPair.$DestStorageDiscovery"/>
              <set_value name="$destTarget" exact="this.$mk2DirectPair.$DestTarget"/>
              <set_value name="$destRatio" exact="this.$mk2DirectPair.$DestRatio"/>
              <set_value name="$mk2SrcUsageCount" exact="0"/>
              <set_value name="$mk2DstUsageCount" exact="0"/>
              <do_if value="this.$sourceUsage? and this.$sourceUsage.{this.$mk2ScoringSource}?">
                <set_value name="$mk2SrcUsageCount" exact="this.$sourceUsage.{this.$mk2ScoringSource}"/>
              </do_if>
              <set_value name="$mk2DstUsageCount" exact="0"/>
              <do_if value="this.$destUsage? and this.$destUsage.{$dest}?">
                <set_value name="$mk2DstUsageCount" exact="this.$destUsage.{$dest}"/>
              </do_if>
              <set_value name="$mk2ScoreSourceRatio" exact="if this.$mk2ScoringSourceStorageDiscovery then this.$mk2ScoringSourceFillRatio else this.$mk2ScoringSourceRatio"/>
              <run_script name="'lib.gt.tradematch'" result="$mk2StorageScore">
                <param name="mode" value="'mk2_storage_pair_score'"/>
                <param name="ship" value="this.ship"/>
                <param name="sourceStation" value="this.$mk2ScoringSource"/>
                <param name="station" value="$dest"/>
                <param name="wareText" value="this.$mk2ScoringWare"/>
                <param name="sourceRatio" value="$mk2ScoreSourceRatio"/>
                <param name="cargoRatio" value="$destRatio"/>
                <param name="cargoTarget" value="$destTarget"/>
                <param name="sourceOfferAmount" value="this.$mk2ScoringSourceOfferAmount"/>
                <param name="destOfferAmount" value="$destOfferAmount"/>
                <param name="sourceStorageDiscovery" value="this.$mk2ScoringSourceStorageDiscovery"/>
                <param name="destStorageDiscovery" value="$destStorageDiscovery"/>
                <param name="mk2SourceOffer" value="this.$mk2ScoringSourceOffer"/>
                <param name="mk2DestOffer" value="$destOffer"/>
                <param name="mk2StaticStorage" value="this.$staticStorage"/>
                <param name="mk2MinStorage" value="this.$minStorage"/>
                <param name="mk2MaxStorage" value="this.$maxStorage"/>
                <param name="pilotLevelProfile" value="this.$mk2PilotLevelProfile"/>
                <param name="routeAlpha" value="this.$mk2RouteAlpha"/>
                <param name="routeBeta" value="this.$mk2RouteBeta"/>
                <param name="routeLaneBonus" value="this.$mk2RouteLaneBonus"/>
                <param name="minCargoFillPercent" value="this.$minCargoFillPercent"/>
                <param name="allowLowVolume" value="this.$allowlowvolume"/>
                <param name="lowVolumeFloorEffPercent" value="this.$mk2LowVolumeFloorEffPercent"/>
                <param name="bidirectional" value="this.$bidirectional"/>
                <param name="fleetCoordination" value="this.$fleetcoordination"/>
                <param name="sourceUsageCount" value="$mk2SrcUsageCount"/>
                <param name="destUsageCount" value="$mk2DstUsageCount"/>
                <param name="stickyCyclesLeft" value="this.$stickyCyclesLeft"/>
                <param name="stickySource" value="this.$stickySource"/>
                <param name="stickyDestination" value="this.$stickyDestination"/>
                <param name="stickyWare" value="this.$stickyWare"/>
                <param name="lastTradeDestination" value="this.$lastTradeDestination"/>
                <param name="lastTradeSource" value="this.$lastTradeSource"/>
                <param name="lastTradeWare" value="this.$lastTradeWare"/>
                <param name="sourceStationRef" value="this.$sourceStation"/>
              </run_script>
              <set_value name="this.$mk2StorageScore" exact="$mk2StorageScore"/>
              <do_if value="this.$mk2StorageScore.$TradeEntry? and this.$mk2StorageScore.$TradeEntry != null">
                <append_to_list name="this.$mk2TradeList" exact="this.$mk2StorageScore.$TradeEntry"/>
              </do_if>
              <do_elseif value="this.$mk2StorageScore.$SkipType == 'noNeed'">
                <set_value name="$skipNoNeed" operation="add"/>
              </do_elseif>
              <do_elseif value="this.$mk2StorageScore.$SkipType == 'minTrade'">
                <set_value name="$skipMinTrade" operation="add"/>
              </do_elseif>
              <do_elseif value="this.$mk2StorageScore.$SkipType == 'reserved'">
                <set_value name="$skipReserved" operation="add"/>
              </do_elseif>
              <do_elseif value="this.$mk2StorageScore.$SkipType == 'pingPong'">
                <set_value name="$skipPingPong" operation="add"/>
              </do_elseif>
            </do_all>
          </do_if>
          <do_if value="this.$mk2CandidateBuyOffers? and this.$mk2CandidateBuyOffers.count gt 0">
          <create_list name="$candidateSellOffers"/>
          <append_to_list name="$candidateSellOffers" exact="this.$mk2ScoringSourceOffer"/>
          <run_script name="'lib.gt.tradematch'" result="$mk2MatchResult">
            <param name="ship" value="this.ship"/>
            <param name="sellOffers" value="$candidateSellOffers"/>
            <param name="buyOffers" value="this.$mk2CandidateBuyOffers"/>
            <param name="homeSector" value="this.$mk2ScoringSource.sector"/>
            <param name="maxDistance" value="this.$maxDistance"/>
            <param name="scoreMode" value="'supply'"/>
            <param name="distancePenalty" value="0"/>
            <param name="maxTradesPerWare" value="100"/>
            <param name="debugchance" value="0"/>
            <param name="allowIllegal" value="this.$allowillegal"/>
            <param name="enforceRouteIllegalLegality" value="this.$enforceRouteIllegalLegality"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <set_value name="this.$mk2MatchResult" exact="$mk2MatchResult"/>

          <do_if value="this.$mk2MatchResult? and this.$mk2MatchResult.$Found and this.$mk2MatchResult.$TradeList? and this.$mk2MatchResult.$TradeList.count gt 0">
            <set_value name="this.$mk2AvailableTradeWaresCount" exact="1"/>
            <run_script name="'lib.gt.tradematch'" result="$mk2DistinctWaresResult">
              <param name="mode" value="'count_distinct_wares'"/>
              <param name="tradeListInput" value="this.$mk2MatchResult.$TradeList"/>
            </run_script>
            <set_value name="this.$mk2DistinctWaresResult" exact="$mk2DistinctWaresResult"/>
            <do_if value="this.$mk2DistinctWaresResult.$DistinctCount? and this.$mk2DistinctWaresResult.$DistinctCount gt 0">
              <set_value name="this.$mk2AvailableTradeWaresCount" exact="this.$mk2DistinctWaresResult.$DistinctCount"/>
            </do_if>
            <do_if value="this.$mk2AvailableTradeWaresCount le 0">
              <set_value name="this.$mk2AvailableTradeWaresCount" exact="1"/>
            </do_if>
            <do_all exact="this.$mk2MatchResult.$TradeList.count" counter="$mti">
              <set_value name="this.$mk2MatchIter" exact="$mti"/>
              <set_value name="$matchedTrade" exact="this.$mk2MatchResult.$TradeList.{this.$mk2MatchIter}"/>
              <set_value name="$destOffer" exact="$matchedTrade.$SellOffer"/>
              <set_value name="$hasValidDest" exact="false"/>
              <set_value name="$dest" exact="null"/>
              <set_value name="$destOfferAmount" exact="0"/>
              <set_value name="$destTarget" exact="1"/>
              <set_value name="$destRatio" exact="999"/>
              <do_if value="$destOffer? and $destOffer.available">
                <set_value name="$dest" exact="@$destOffer.owner"/>
                <do_if value="$dest? and $dest.exists">
                  <set_value name="$hasValidDest" exact="true"/>
                  <set_value name="$destOfferAmount" exact="if $matchedTrade.$SellOfferAmount? then $matchedTrade.$SellOfferAmount else $destOffer.offeramount.{this.ship}"/>
                  <do_if value="$destOfferAmount == null">
                    <set_value name="$destOfferAmount" exact="0"/>
                  </do_if>
                  <set_value name="$destTarget" exact="[$dest.cargo.{this.$mk2ScoringWare}.target, 1].max"/>
                  <set_value name="$destRatio" exact="($dest.cargo.{this.$mk2ScoringWare}.count * 100) / $destTarget"/>
                </do_if>
              </do_if>

              <do_if value="not $hasValidDest">
                <set_value name="$skipNoDestOffer" operation="add"/>
                <continue/>
              </do_if>
              <set_value name="$destStorageDiscovery" exact="false"/>
                <set_value name="$needBucket" exact="'none'"/>
                <set_value name="$bucketWeight" exact="1.0"/>
                <set_value name="$isCriticalNeed" exact="false"/>
                <set_value name="$shouldDistribute" exact="false"/>
                <do_if value="this.$mk2PilotLevelProfile ge 4">
                  <do_if value="$destRatio le 5">
                    <set_value name="$needBucket" exact="'A'"/>
                    <set_value name="$bucketWeight" exact="3.0"/>
                    <set_value name="$isCriticalNeed" exact="true"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_if>
                  <do_elseif value="$destRatio le 20">
                    <set_value name="$needBucket" exact="'B'"/>
                    <set_value name="$bucketWeight" exact="2.0"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$destRatio le this.$minStorage">
                    <set_value name="$needBucket" exact="'C'"/>
                    <set_value name="$bucketWeight" exact="1.4"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_elseif>
                  <do_elseif value="this.$mk2ScoringSourceRatio gt this.$maxStorage and this.$mk2ScoringSourceRatio gt ($destRatio + 10)">
                    <set_value name="$needBucket" exact="'D'"/>
                    <set_value name="$bucketWeight" exact="1.0"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_else>
                  <do_if value="$destRatio le 5">
                    <set_value name="$needBucket" exact="'A'"/>
                    <set_value name="$bucketWeight" exact="2.4"/>
                    <set_value name="$isCriticalNeed" exact="true"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_if>
                  <do_elseif value="$destRatio le this.$minStorage">
                    <set_value name="$needBucket" exact="'C'"/>
                    <set_value name="$bucketWeight" exact="1.2"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_elseif>
                  <do_elseif value="this.$mk2ScoringSourceRatio gt this.$maxStorage and this.$mk2ScoringSourceRatio gt ($destRatio + 10)">
                    <set_value name="$needBucket" exact="'D'"/>
                    <set_value name="$bucketWeight" exact="1.0"/>
                    <set_value name="$shouldDistribute" exact="true"/>
                  </do_elseif>
                </do_else>
                <set_value name="$urgent" exact="$isCriticalNeed"/>
                <do_if value="not $shouldDistribute">
                  <set_value name="$skipNoNeed" operation="add"/>
                  <do_if value="this.$debuglevel ge 1 and $noNeedDetailCount lt 10">
                    <do_if value="$noNeedDetailCount gt 0">
                      <set_value name="$noNeedDetails" exact="$noNeedDetails + '; '"/>
                    </do_if>
                <set_value name="$noNeedDetails" exact="$noNeedDetails + this.$mk2ScoringSource.idcode + '->' + $dest.idcode + ':' + this.$mk2ScoringWare + ' src=' + this.$mk2ScoringSourceRatio + '% dst=' + $destRatio + '% bucket=' + $needBucket + ' thresholds(min=' + this.$minStorage + ',max=' + this.$maxStorage + ')'"/>
                    <set_value name="$noNeedDetailCount" operation="add"/>
                  </do_if>
                  <continue/>
                </do_if>

                <do_if value="this.$lastTradeSource? and this.$lastTradeSource.exists and this.$lastTradeDestination? and this.$lastTradeDestination.exists and this.$lastTradeWare? and this.$mk2ScoringSource == this.$lastTradeDestination and $dest == this.$lastTradeSource and this.$mk2ScoringWare == this.$lastTradeWare and $needBucket != 'A'">
                  <set_value name="$skipPingPong" operation="add"/>
                  <continue/>
                </do_if>

                <set_value name="$cargoCapacity" exact="this.ship.cargo.{this.$mk2ScoringWare}.max"/>
                <set_value name="$incomingReservedAmount" exact="0"/>
                <set_value name="$reservedShipCount" exact="0"/>
                <set_value name="$alreadyReservedByThisShip" exact="false"/>
                <set_value name="$effectiveDestOfferAmount" exact="$destOfferAmount"/>
                <do_if value="this.$fleetcoordination">
                  <!-- VANILLA reservations on destination buy offer side (ships selling to destination). -->
                  <get_ware_reservation object="$dest" ware="this.$mk2ScoringWare" type="sell" virtual="false" result="$incomingReservedAmount"/>
                  <set_value name="$reservedShipCount" exact="(($incomingReservedAmount + [1, (($cargoCapacity * this.$minCargoFillPercent) / 100)i].max - 1) / [1, (($cargoCapacity * this.$minCargoFillPercent) / 100)i].max)i"/>
                </do_if>
                <set_value name="$shipChunkAmount" exact="[1, (($cargoCapacity * this.$minCargoFillPercent) / 100)i].max"/>
                <!-- $destOfferAmount comes from matchedTrade.$SellOfferAmount, which lib.gt.tradematch
                     already reduced via get_ware_reservation on the destination. Do not subtract
                     incoming reservations again here â€” that falsely zeroed effective need when one
                     in-flight delivery existed but the station still had a large storage deficit. -->
                <run_script name="'lib.gt.tradematch'" result="$mk2FairnessResult">
                  <param name="mode" value="'ware_fairness'"/>
                  <param name="rawNeedAmount" value="$destOfferAmount"/>
                  <param name="incomingReservedAmount" value="0"/>
                  <param name="shipChunkAmount" value="$shipChunkAmount"/>
                  <param name="availableTradeWaresCount" value="this.$mk2AvailableTradeWaresCount"/>
                  <param name="reservedCount" value="$reservedShipCount"/>
                  <param name="alreadyReservedByThisShip" value="$alreadyReservedByThisShip"/>
                  <param name="fairnessCap" value="2"/>
                </run_script>
                <set_value name="this.$mk2FairnessResult" exact="$mk2FairnessResult"/>
                <set_value name="$effectiveDestOfferAmount" exact="if this.$mk2FairnessResult? then this.$mk2FairnessResult.$EffectiveNeedAmount else 0"/>
                <set_value name="$maxShipsForWare" exact="if this.$mk2FairnessResult? then this.$mk2FairnessResult.$MaxShipsForWare else 0"/>
                <set_value name="$reservationAllowsTrade" exact="if this.$mk2FairnessResult? then this.$mk2FairnessResult.$ReservationAllowsTrade else false"/>
                <do_if value="$effectiveDestOfferAmount le 0">
                  <set_value name="$skipReserved" operation="add"/>
                  <continue/>
                </do_if>

                <set_value name="$tradeAmount" exact="[this.ship.cargo.{this.$mk2ScoringWare}.free, this.$mk2ScoringSourceOfferAmount, $effectiveDestOfferAmount].min"/>
                <set_value name="$normalMinimumTrade" exact="[1, (($cargoCapacity * this.$minCargoFillPercent) / 100)i].max"/>
                <set_value name="$minimumTrade" exact="$normalMinimumTrade"/>
                <set_value name="$usedLowVolume" exact="false"/>
                <set_value name="$canLowVolume" exact="false"/>
                <do_if value="this.$allowlowvolume">
                  <do_if value="this.$mk2PilotLevelProfile ge 6 or $isCriticalNeed">
                  <set_value name="$canLowVolume" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$canLowVolume">
                <set_value name="$minimumTrade" exact="[1, (($cargoCapacity * this.$mk2LowVolumeFloorEffPercent) / 100)i].max"/>
                <do_if value="$isCriticalNeed">
                  <set_value name="$minimumTrade" exact="[1, ($minimumTrade / 2)i].max"/>
                </do_if>
                <set_value name="$usedLowVolume" exact="true"/>
              </do_if>
              <do_if value="$tradeAmount lt $minimumTrade">
                <set_value name="$skipMinTrade" operation="add"/>
                <continue/>
              </do_if>

              <set_value name="$sourceUsage" exact="0"/>
              <set_value name="$destUsage" exact="0"/>
              <do_if value="this.$sourceUsage? and this.$sourceUsage.{this.$mk2ScoringSource}?">
                <set_value name="$sourceUsage" exact="this.$sourceUsage.{this.$mk2ScoringSource}"/>
              </do_if>
              <do_if value="this.$destUsage? and this.$destUsage.{$dest}?">
                <set_value name="$destUsage" exact="this.$destUsage.{$dest}"/>
              </do_if>
              <set_value name="$urgencyMultiplier" exact="$bucketWeight"/>
              <set_value name="$mk2ScoreSourceRatio" exact="if this.$mk2ScoringSourceStorageDiscovery then this.$mk2ScoringSourceFillRatio else this.$mk2ScoringSourceRatio"/>
              <set_value name="$balanceFactor" exact="[0, ($mk2ScoreSourceRatio - $destRatio)].max / 100"/>
              <set_value name="$baseScore" exact="(($mk2ScoreSourceRatio - this.$staticStorage) * $urgencyMultiplier * ($tradeAmount / [$cargoCapacity, 1].max)) + $balanceFactor - (($sourceUsage + $destUsage) * 0.2)"/>
              <set_value name="$shipToSourceGates" exact="this.ship.gatedistance.{this.$mk2ScoringSource}"/>
              <set_value name="$sourceToDestGates" exact="this.$mk2ScoringSource.gatedistance.{$dest}"/>
              <set_value name="$forwardGates" exact="[0, $shipToSourceGates].max + [0, $sourceToDestGates].max"/>
              <set_value name="$baselineGates" exact="$forwardGates"/>
              <do_if value="this.$sourceStation? and this.$sourceStation.exists and this.$lastTradeDestination? and this.$lastTradeDestination.exists">
                <set_value name="$baseShipToSourceGates" exact="this.ship.gatedistance.{this.$sourceStation}"/>
                <set_value name="$baseSourceToDestGates" exact="this.$sourceStation.gatedistance.{this.$lastTradeDestination}"/>
                <do_if value="$baseShipToSourceGates ge 0 and $baseSourceToDestGates ge 0">
                  <set_value name="$baselineGates" exact="$baseShipToSourceGates + $baseSourceToDestGates"/>
                </do_if>
              </do_if>
              <set_value name="$deltaGates" exact="[0, $forwardGates - $baselineGates].max"/>
              <set_value name="$backtrackPenalty" exact="0"/>
              <do_if value="not this.$bidirectional and (not this.$lastTradeDestination? or not this.$lastTradeDestination.exists or this.$mk2ScoringSource != this.$lastTradeDestination)">
              <do_if value="this.$lastTradeDestination? and this.$lastTradeDestination.exists">
                <set_value name="$prevToDestGates" exact="this.$lastTradeDestination.gatedistance.{$dest}"/>
                <set_value name="$prevToSourceGates" exact="this.$lastTradeDestination.gatedistance.{this.$mk2ScoringSource}"/>
                <do_if value="$prevToDestGates ge 0 and $prevToSourceGates ge 0 and $prevToDestGates gt ($prevToSourceGates + 1)">
                  <set_value name="$backtrackPenalty" exact="1"/>
                </do_if>
              </do_if>
              </do_if>
              <set_value name="$laneBonus" exact="1.0"/>
              <do_if value="this.$stickyCyclesLeft gt 0 and this.$stickySource? and this.$stickyDestination? and this.$stickyWare? and this.$stickySource == this.$mk2ScoringSource and this.$stickyDestination == $dest and this.$stickyWare == this.$mk2ScoringWare">
                <set_value name="$laneBonus" exact="this.$mk2RouteLaneBonus"/>
              </do_if>
              <!-- Lane continuity: prefer picking up at the station we just delivered to. -->
              <set_value name="$nearStationFactor" exact="1.0"/>
              <do_if value="this.$lastTradeDestination? and this.$lastTradeDestination.exists">
                <do_if value="this.$mk2ScoringSource == this.$lastTradeDestination">
                  <set_value name="$nearStationFactor" exact="this.$mk2RouteLaneBonus"/>
                  <do_if value="$shipToSourceGates == 0">
                    <set_value name="$nearStationFactor" exact="$nearStationFactor * 1.10"/>
                  </do_if>
                </do_if>
                <do_elseif value="this.$mk2PilotLevelProfile ge 4">
                  <set_value name="$nearStationFactor" exact="0.80 + (0.20 * this.$mk2RouteT)"/>
                </do_elseif>
              </do_if>
              <set_value name="$costFactor" exact="1.0"/>
              <do_if value="this.$mk2PilotLevelProfile ge 4">
                <set_value name="$costFactor" exact="1.0 + (this.$mk2RouteAlpha * $deltaGates) + (this.$mk2RouteBeta * $backtrackPenalty)"/>
                <do_if value="this.$lastTradeDestination? and this.$lastTradeDestination.exists and this.$mk2ScoringSource != this.$lastTradeDestination">
                  <set_value name="$detourFromLastGates" exact="this.$lastTradeDestination.gatedistance.{this.$mk2ScoringSource}"/>
                  <do_if value="$detourFromLastGates ge 0">
                    <set_value name="$costFactor" exact="$costFactor + (this.$mk2RouteAlpha * $detourFromLastGates)"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <set_value name="$costFactor" exact="1.0 + (0.20 * $forwardGates)"/>
              </do_else>
              <set_value name="$score" exact="($baseScore * $laneBonus * $nearStationFactor) / [1.0, $costFactor].max"/>
              <append_to_list name="this.$mk2TradeList" exact="table[
                $Ware = this.$mk2ScoringWare,
                $Source = this.$mk2ScoringSource,
                $Destination = $dest,
                $Amount = $tradeAmount,
                $Urgent = $urgent,
                $NeedBucket = $needBucket,
                $Score = $score,
                $SourceOffer = this.$mk2ScoringSourceOffer,
                $DestOffer = $destOffer,
                $SourceOfferAmount = this.$mk2ScoringSourceOfferAmount,
                $DestOfferAmount = $destOfferAmount,
                $EffectiveDestOfferAmount = $effectiveDestOfferAmount,
                $IncomingReservedAmount = $incomingReservedAmount,
                $NormalMinimumTrade = $normalMinimumTrade,
                $UsedLowVolume = $usedLowVolume,
                $DeltaGates = $deltaGates,
                $BacktrackPenalty = $backtrackPenalty,
                $SourceStorageDiscovery = false,
                $DestStorageDiscovery = false
              ]"/>
            </do_all>
          </do_if>
          </do_if>
          <do_if value="(not this.$mk2DirectDestPairs? or this.$mk2DirectDestPairs.count == 0) and (not this.$mk2CandidateBuyOffers? or this.$mk2CandidateBuyOffers.count == 0)">
            <continue/>
          </do_if>
        </do_all>
      </do_all>

      <!-- Shared ranking: use the common scorer to pick the best MK2 candidate by precomputed $Score. -->
      <run_script name="'lib.gt.score.trades'" result="$mk2ScoreResult">
        <param name="tradeList" value="this.$mk2TradeList"/>
        <param name="debugchance" value="this.$debugchance"/>
      </run_script>
      <do_if value="$mk2ScoreResult?">
        <set_value name="this.$mk2ScoreResult" exact="$mk2ScoreResult"/>
      </do_if>
      <do_else>
        <set_value name="this.$mk2ScoreResult" exact="null"/>
      </do_else>
      <set_value name="this.$mk2BestTrade" exact="null"/>
      <set_value name="this.$mk2BestScore" exact="-1"/>
      <set_value name="this.$mk2BestSourceOffer" exact="null"/>
      <set_value name="this.$mk2BestDestOffer" exact="null"/>
      <set_value name="this.$mk2BestSourceOfferAmount" exact="0"/>
      <set_value name="this.$mk2BestDestOfferAmount" exact="0"/>
      <do_if value="this.$mk2ScoreResult? and this.$mk2ScoreResult.$Found? and this.$mk2ScoreResult.$Found and this.$mk2ScoreResult.$BestTrade?">
        <set_value name="this.$mk2BestTrade" exact="this.$mk2ScoreResult.$BestTrade"/>
        <set_value name="this.$mk2BestScore" exact="this.$mk2ScoreResult.$BestScore"/>
        <set_value name="this.$mk2BestSourceOffer" exact="this.$mk2BestTrade.$SourceOffer"/>
        <set_value name="this.$mk2BestDestOffer" exact="this.$mk2BestTrade.$DestOffer"/>
        <set_value name="this.$mk2BestSourceOfferAmount" exact="this.$mk2BestTrade.$SourceOfferAmount"/>
        <set_value name="this.$mk2BestDestOfferAmount" exact="if this.$mk2BestTrade.$EffectiveDestOfferAmount? then this.$mk2BestTrade.$EffectiveDestOfferAmount else this.$mk2BestTrade.$DestOfferAmount"/>
      </do_if>

      <do_if value="this.$mk2BestTrade == null">
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': no trade selected. src=' + this.$activeSources.count + ', dst=' + this.$activeDestinations.count + ', eval=' + $evalPairs + ', candidates=' + this.$mk2TradeList.count + ', skips: illegal/cargo=' + $skipIllegalOrNoCargo + ', noSrcOffer=' + $skipNoSourceOffer + ', srcNoTarget=' + $skipSourceNoTarget + ', srcBelowStatic=' + $skipSourceBelowStatic + ', self=' + $skipSelfTarget + ', blacklist=' + $skipBlacklist + ', distance=' + $skipDistance + ', noDstOffer=' + $skipNoDestOffer + ', noNeed=' + $skipNoNeed + ', minTrade=' + $skipMinTrade + ', reserved=' + $skipReserved + ', pingPong=' + $skipPingPong + ', docking=' + $skipDocking" chance="this.$debugchance"/>
          <do_if value="$noSourceOfferDetailCount gt 0">
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': noSrcOffer details: ' + $noSourceOfferDetails" chance="this.$debugchance"/>
          </do_if>
          <do_if value="$noDestOfferDetailCount gt 0">
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': noDstOffer details: ' + $noDestOfferDetails" chance="this.$debugchance"/>
          </do_if>
          <do_if value="$sourceBelowStaticDetailCount gt 0">
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': srcBelowStatic details: ' + $sourceBelowStaticDetails" chance="this.$debugchance"/>
          </do_if>
          <do_if value="$noNeedDetailCount gt 0">
            <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': noNeed details: ' + $noNeedDetails" chance="this.$debugchance"/>
          </do_if>
        </do_if>
        <do_if value="this.$notifications ge 2">
          <show_notification text="'MK2 ' + this.ship.knownname + ': ' + {77000, 20202}" timeout="5s"/>
        </do_if>
        <resume label="no_trade_retry"/>
      </do_if>

      <set_value name="this.$mk2DenyTrade" exact="false"/>
      <run_script name="'lib.gt.blacklist.validate_lane'" result="$mk2BestLaneBL">
        <param name="ship" value="this.ship"/>
        <param name="buyStation" value="this.$mk2BestTrade.$Source"/>
        <param name="sellStation" value="this.$mk2BestTrade.$Destination"/>
        <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        <param name="sectorWhitelist" value="if this.$mk2SectorWhitelist? then this.$mk2SectorWhitelist else []"/>
        <param name="checkPath" value="true"/>
        <param name="debugchance" value="if this.$debuglevel ge 1 then this.$debugchance else 0"/>
      </run_script>
      <set_value name="this.$mk2BestLaneBL" exact="$mk2BestLaneBL"/>
      <do_if value="this.$mk2BestLaneBL.$Blocked? and this.$mk2BestLaneBL.$Blocked">
        <set_value name="this.$mk2DenyTrade" exact="true"/>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': trade denied by blacklist pre-queue (' + this.$mk2BestLaneBL.$Leg + ': ' + this.$mk2BestLaneBL.$Reason + ') ' + this.$mk2BestTrade.$Source.knownname + ' -> ' + this.$mk2BestTrade.$Destination.knownname" chance="this.$debugchance"/>
        </do_if>
      </do_if>
      <do_if value="this.$mk2DenyTrade">
        <resume label="no_trade_retry"/>
      </do_if>

      <do_if value="not this.$mk2DenyTrade">
        <set_value name="this.$mk2TradeOrderInternal" exact="this.$mk2BestTrade.$Source.isplayerowned and this.$mk2BestTrade.$Destination.isplayerowned"/>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': selected trade ' + this.$mk2BestTrade.$Ware + ' from ' + this.$mk2BestTrade.$Source.knownname + ' to ' + this.$mk2BestTrade.$Destination.knownname + ' amount=' + this.$mk2BestTrade.$Amount + ' score=' + this.$mk2BestScore + ' incomingReserved=' + (if this.$mk2BestTrade.$IncomingReservedAmount? then this.$mk2BestTrade.$IncomingReservedAmount else 0) + ' effectiveNeed=' + this.$mk2BestDestOfferAmount + ' internal=' + this.$mk2TradeOrderInternal + ' ignoreRules=' + this.$ignoretraderules" chance="this.$debugchance"/>
        </do_if>
        <set_value name="this.$lastTradeSource" exact="this.$mk2BestTrade.$Source"/>
        <set_value name="this.$lastTradeDestination" exact="this.$mk2BestTrade.$Destination"/>
        <set_value name="this.$lastTradeWare" exact="this.$mk2BestTrade.$Ware"/>

        <do_if value="not this.$mk2DenyTrade">
          <set_command_action commandaction="commandaction.flying"/>
          <set_value name="this.$mk2SellAmount" exact="0"/>
          <set_value name="$mk2QueueTradeMax" exact="3"/>
          <set_value name="this.$mk2QueueTrades" exact="[]"/>
          <set_value name="$mk2PrimaryAmount" exact="[this.$mk2BestTrade.$Amount, this.$mk2BestSourceOfferAmount, this.$mk2BestDestOfferAmount].min"/>
          <do_if value="$mk2PrimaryAmount gt 0">
            <append_to_list name="this.$mk2QueueTrades" exact="table[
              $Ware = this.$mk2BestTrade.$Ware,
              $Source = this.$mk2BestTrade.$Source,
              $Destination = this.$mk2BestTrade.$Destination,
              $SourceOffer = this.$mk2BestTrade.$SourceOffer,
              $DestOffer = this.$mk2BestTrade.$DestOffer,
              $QueuedAmount = $mk2PrimaryAmount,
              $Score = this.$mk2BestTrade.$Score,
              $SourceStorageDiscovery = if this.$mk2BestTrade.$SourceStorageDiscovery? then this.$mk2BestTrade.$SourceStorageDiscovery else false,
              $DestStorageDiscovery = if this.$mk2BestTrade.$DestStorageDiscovery? then this.$mk2BestTrade.$DestStorageDiscovery else false,
              $SourceOfferAmount = this.$mk2BestTrade.$SourceOfferAmount,
              $DestOfferAmount = if this.$mk2BestTrade.$EffectiveDestOfferAmount? then this.$mk2BestTrade.$EffectiveDestOfferAmount else this.$mk2BestTrade.$DestOfferAmount
            ]"/>
          </do_if>
          <do_if value="this.$mk2QueueTrades.count gt 0 and this.$mk2TradeList.count gt 1">
            <set_value name="$mk2RemainingVolume" exact="[0, this.ship.cargo.capacity.all - ($mk2PrimaryAmount * this.$mk2BestTrade.$Ware.volume)].max"/>
            <set_value name="$mk2AddedTrades" exact="0"/>
            <do_while value="$mk2AddedTrades lt ($mk2QueueTradeMax - 1) and $mk2RemainingVolume gt 0">
              <set_value name="$mk2BestSecondary" exact="null"/>
              <set_value name="$mk2BestSecondaryVolume" exact="0"/>
              <set_value name="$mk2BestSecondaryScore" exact="-999999"/>
              <do_all exact="this.$mk2TradeList.count" counter="$m2i">
                <set_value name="$mk2Candidate" exact="this.$mk2TradeList.{$m2i}"/>
                <do_if value="$mk2Candidate == null or $mk2Candidate == this.$mk2BestTrade">
                  <continue/>
                </do_if>
                <!-- MK2 multi-ware batching: only same lane as primary trade -->
                <do_if value="$mk2Candidate.$Source != this.$mk2BestTrade.$Source or $mk2Candidate.$Destination != this.$mk2BestTrade.$Destination">
                  <continue/>
                </do_if>
                <set_value name="$mk2AlreadyQueued" exact="false"/>
                <do_all exact="this.$mk2QueueTrades.count" counter="$m2qi">
                  <set_value name="$mk2QueuedTrade" exact="this.$mk2QueueTrades.{$m2qi}"/>
                  <do_if value="$mk2QueuedTrade.$SourceOffer == $mk2Candidate.$SourceOffer and $mk2QueuedTrade.$DestOffer == $mk2Candidate.$DestOffer">
                    <set_value name="$mk2AlreadyQueued" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="$mk2AlreadyQueued">
                  <continue/>
                </do_if>
                <set_value name="$mk2CandNeedAmount" exact="if $mk2Candidate.$EffectiveDestOfferAmount? then $mk2Candidate.$EffectiveDestOfferAmount else $mk2Candidate.$DestOfferAmount"/>
                <set_value name="$mk2CandAmount" exact="[$mk2Candidate.$Amount, $mk2Candidate.$SourceOfferAmount, $mk2CandNeedAmount, this.ship.cargo.{$mk2Candidate.$Ware}.max].min"/>
                <do_if value="$mk2Candidate.$Ware.volume gt 0">
                  <set_value name="$mk2CandMaxByVolume" exact="($mk2RemainingVolume / $mk2Candidate.$Ware.volume)i"/>
                  <set_value name="$mk2CandAmount" exact="[$mk2CandAmount, $mk2CandMaxByVolume].min"/>
                </do_if>
                <do_if value="$mk2CandAmount le 0">
                  <continue/>
                </do_if>
                <set_value name="$mk2CandVolume" exact="$mk2CandAmount * $mk2Candidate.$Ware.volume"/>
                <do_if value="$mk2CandVolume gt $mk2BestSecondaryVolume or ($mk2CandVolume == $mk2BestSecondaryVolume and $mk2Candidate.$Score gt $mk2BestSecondaryScore)">
                  <set_value name="$mk2BestSecondary" exact="$mk2Candidate"/>
                  <set_value name="$mk2BestSecondaryVolume" exact="$mk2CandVolume"/>
                  <set_value name="$mk2BestSecondaryScore" exact="$mk2Candidate.$Score"/>
                  <set_value name="$mk2BestSecondaryAmount" exact="$mk2CandAmount"/>
                </do_if>
              </do_all>
              <do_if value="$mk2BestSecondary == null or $mk2BestSecondaryAmount le 0">
                <break/>
              </do_if>
              <append_to_list name="this.$mk2QueueTrades" exact="table[
                $Ware = $mk2BestSecondary.$Ware,
                $Source = $mk2BestSecondary.$Source,
                $Destination = $mk2BestSecondary.$Destination,
                $SourceOffer = $mk2BestSecondary.$SourceOffer,
                $DestOffer = $mk2BestSecondary.$DestOffer,
                $QueuedAmount = $mk2BestSecondaryAmount,
                $Score = $mk2BestSecondary.$Score,
                $SourceStorageDiscovery = if $mk2BestSecondary.$SourceStorageDiscovery? then $mk2BestSecondary.$SourceStorageDiscovery else false,
                $DestStorageDiscovery = if $mk2BestSecondary.$DestStorageDiscovery? then $mk2BestSecondary.$DestStorageDiscovery else false,
                $SourceOfferAmount = $mk2BestSecondary.$SourceOfferAmount,
                $DestOfferAmount = if $mk2BestSecondary.$EffectiveDestOfferAmount? then $mk2BestSecondary.$EffectiveDestOfferAmount else $mk2BestSecondary.$DestOfferAmount
              ]"/>
              <set_value name="$mk2AddedTrades" operation="add"/>
              <do_if value="$mk2BestSecondary.$Ware.volume gt 0">
                <set_value name="$mk2RemainingVolume" exact="[0, $mk2RemainingVolume - ($mk2BestSecondaryAmount * $mk2BestSecondary.$Ware.volume)].max"/>
              </do_if>
            </do_while>
          </do_if>

          <set_value name="this.$mk2FinalQueueTrades" exact="[]"/>
          <set_value name="this.$mk2RoutePlan" exact="''"/>
          <set_value name="this.$mk2RoutePlanCount" exact="0"/>
          <do_if value="not this.$mk2QueueTrades?">
            <set_value name="this.$mk2QueueTrades" exact="[]"/>
          </do_if>
          <set_value name="this.$mk2QueueTradeCount" exact="this.$mk2QueueTrades.count"/>
          <set_value name="this.$mk2QueueIdx" exact="1"/>
          <do_while value="this.$mk2QueueIdx? and this.$mk2QueueTradeCount? and this.$mk2QueueIdx le this.$mk2QueueTradeCount">
          <set_value name="this.$mk2QueueIsPrimary" exact="this.$mk2QueueIdx == 1"/>
          <set_value name="this.$mk2QueuedTrade" exact="this.$mk2QueueTrades.{this.$mk2QueueIdx}"/>
            <set_value name="$mk2SourceOfferStillAmount" exact="if this.$mk2QueuedTrade.$SourceOffer? and this.$mk2QueuedTrade.$SourceOffer != null and this.$mk2QueuedTrade.$SourceOffer.available and this.$mk2QueuedTrade.$SourceOffer.offeramount.{this.ship}? then this.$mk2QueuedTrade.$SourceOffer.offeramount.{this.ship} else 0"/>
            <do_if value="$mk2SourceOfferStillAmount == null and this.$mk2QueuedTrade.$SourceOffer? and this.$mk2QueuedTrade.$SourceOffer != null and this.$mk2QueuedTrade.$SourceOffer.available">
              <set_value name="$mk2SourceOfferStillAmount" exact="@this.$mk2QueuedTrade.$SourceOffer.amount"/>
            </do_if>
            <do_if value="($mk2SourceOfferStillAmount == null or $mk2SourceOfferStillAmount le 0) and this.$mk2QueuedTrade.$SourceStorageDiscovery? and this.$mk2QueuedTrade.$SourceStorageDiscovery">
              <set_value name="$mk2SourceOfferStillAmount" exact="if this.$mk2QueuedTrade.$SourceOfferAmount? then this.$mk2QueuedTrade.$SourceOfferAmount else [this.$mk2QueuedTrade.$Source.cargo.{this.$mk2QueuedTrade.$Ware}.count, this.ship.cargo.{this.$mk2QueuedTrade.$Ware}.max].min"/>
            </do_if>
            <do_if value="$mk2SourceOfferStillAmount == null">
              <set_value name="$mk2SourceOfferStillAmount" exact="0"/>
            </do_if>
            <set_value name="$mk2DestOfferStillAmount" exact="if this.$mk2QueuedTrade.$DestOffer? and this.$mk2QueuedTrade.$DestOffer.offeramount.{this.ship}? then this.$mk2QueuedTrade.$DestOffer.offeramount.{this.ship} else 0"/>
            <do_if value="($mk2DestOfferStillAmount == null or $mk2DestOfferStillAmount le 0) and this.$mk2UseWareExchange and this.$mk2QueuedTrade.$DestOffer? and this.$mk2QueuedTrade.$DestOffer.owner? and this.$mk2QueuedTrade.$DestOffer.owner.isplayerowned">
              <set_value name="$mk2DestOfferStillAmount" exact="[0, this.$mk2QueuedTrade.$DestOffer.owner.cargo.{this.$mk2QueuedTrade.$Ware}.target - this.$mk2QueuedTrade.$DestOffer.owner.cargo.{this.$mk2QueuedTrade.$Ware}.count].max"/>
            </do_if>
            <do_if value="($mk2DestOfferStillAmount == null or $mk2DestOfferStillAmount le 0) and this.$mk2QueuedTrade.$DestStorageDiscovery? and this.$mk2QueuedTrade.$DestStorageDiscovery">
              <set_value name="$mk2DestOfferStillAmount" exact="if this.$mk2QueuedTrade.$DestOfferAmount? then this.$mk2QueuedTrade.$DestOfferAmount else [0, this.$mk2QueuedTrade.$Destination.cargo.{this.$mk2QueuedTrade.$Ware}.target - this.$mk2QueuedTrade.$Destination.cargo.{this.$mk2QueuedTrade.$Ware}.count].max"/>
            </do_if>
            <do_if value="$mk2DestOfferStillAmount == null">
              <set_value name="$mk2DestOfferStillAmount" exact="0"/>
            </do_if>
            <set_value name="$mk2QueuedAmountClamped" exact="[this.$mk2QueuedTrade.$QueuedAmount, $mk2SourceOfferStillAmount, $mk2DestOfferStillAmount].min"/>
            <set_value name="$mk2SourceLegOk" exact="false"/>
            <do_if value="this.$mk2QueuedTrade.$SourceStorageDiscovery? and this.$mk2QueuedTrade.$SourceStorageDiscovery">
              <set_value name="$mk2SourceLegOk" exact="true"/>
            </do_if>
            <do_elseif value="this.$mk2QueuedTrade.$SourceOffer? and this.$mk2QueuedTrade.$SourceOffer.available">
              <set_value name="$mk2SourceLegOk" exact="true"/>
            </do_elseif>
            <set_value name="$mk2DestLegOk" exact="false"/>
            <do_if value="this.$mk2QueuedTrade.$DestStorageDiscovery? and this.$mk2QueuedTrade.$DestStorageDiscovery">
              <set_value name="$mk2DestLegOk" exact="true"/>
            </do_if>
            <do_elseif value="this.$mk2QueuedTrade.$DestOffer? and this.$mk2QueuedTrade.$DestOffer.available">
              <set_value name="$mk2DestLegOk" exact="true"/>
            </do_elseif>
            <do_if value="$mk2QueuedAmountClamped le 0 or not $mk2SourceLegOk or not $mk2DestLegOk">
              <do_if value="this.$mk2QueueIsPrimary">
                <set_value name="this.$mk2DenyTrade" exact="true"/>
                <do_if value="this.$debuglevel ge 1">
                  <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': selected primary trade invalid before queueing (source/dest changed) -- retrying'" chance="this.$debugchance"/>
                </do_if>
              </do_if>
              <set_value name="this.$mk2QueueIdx" operation="add"/>
              <continue/>
            </do_if>
            <set_value name="this.$mk2QueuedTrade.$QueuedAmount" exact="$mk2QueuedAmountClamped"/>
            <set_value name="$mk2RouteOk" exact="true"/>
            <do_if value="this.$allowillegal and this.$enforceRouteIllegalLegality and @this.$mk2QueuedTrade.$Ware.illegal gt 0">
              <set_value name="$mk2RouteHome" exact="if this.$homeSector? and this.$homeSector.exists then this.$homeSector else (if this.$sourceStation? and this.$sourceStation.exists then this.$sourceStation.sector else this.ship.sector)"/>
              <run_script name="'lib.gt.pathfinding'" result="$mk2RouteLegality">
                <param name="mode" value="'route_legality'"/>
                <param name="ship" value="this.ship"/>
                <param name="homeSector" value="$mk2RouteHome"/>
                <param name="allowIllegal" value="this.$allowillegal"/>
                <param name="enforceRouteIllegalLegality" value="this.$enforceRouteIllegalLegality"/>
                <param name="startSector" value="this.ship.sector"/>
                <param name="buySector" value="if this.$mk2QueuedTrade.$Source? and this.$mk2QueuedTrade.$Source.sector? then this.$mk2QueuedTrade.$Source.sector else (if this.$mk2QueuedTrade.$SourceOffer? and this.$mk2QueuedTrade.$SourceOffer.owner? then @this.$mk2QueuedTrade.$SourceOffer.owner.sector else null)"/>
                <param name="sellSector" value="if this.$mk2QueuedTrade.$Destination? and this.$mk2QueuedTrade.$Destination.sector? then this.$mk2QueuedTrade.$Destination.sector else (if this.$mk2QueuedTrade.$DestOffer? and this.$mk2QueuedTrade.$DestOffer.owner? then @this.$mk2QueuedTrade.$DestOffer.owner.sector else null)"/>
                <param name="ware" value="this.$mk2QueuedTrade.$Ware"/>
                <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              </run_script>
              <do_if value="$mk2RouteLegality?">
                <set_value name="this.$mk2RouteLegality" exact="$mk2RouteLegality"/>
              </do_if>
              <do_if value="not this.$mk2RouteLegality? or not this.$mk2RouteLegality.$IsLegal">
                <set_value name="$mk2RouteOk" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$mk2RouteOk">
            <set_value name="$mk2WxNeedsDockCheck" exact="(this.$mk2QueuedTrade.$SourceStorageDiscovery? and this.$mk2QueuedTrade.$SourceStorageDiscovery) or (this.$mk2QueuedTrade.$DestStorageDiscovery? and this.$mk2QueuedTrade.$DestStorageDiscovery)"/>
            <do_if value="$mk2WxNeedsDockCheck">
              <run_script name="'lib.gt.dockcheck'" result="$mk2QueueSourceDock">
                <param name="ship" value="this.ship"/>
                <param name="station" value="this.$mk2QueuedTrade.$Source"/>
                <param name="purpose" value="'trade'"/>
                <param name="allowStorageDock" value="this.$mk2UseWareExchange and this.$mk2QueuedTrade.$Source.isplayerowned"/>
                <param name="useMemo" value="true"/>
              </run_script>
              <set_value name="this.$mk2QueueSourceDock" exact="$mk2QueueSourceDock"/>
              <run_script name="'lib.gt.dockcheck'" result="$mk2QueueDestDock">
                <param name="ship" value="this.ship"/>
                <param name="station" value="this.$mk2QueuedTrade.$Destination"/>
                <param name="purpose" value="'trade'"/>
                <param name="allowStorageDock" value="this.$mk2UseWareExchange and this.$mk2QueuedTrade.$Destination.isplayerowned"/>
                <param name="useMemo" value="true"/>
              </run_script>
              <set_value name="this.$mk2QueueDestDock" exact="$mk2QueueDestDock"/>
              <do_if value="not this.$mk2QueueSourceDock? or not this.$mk2QueueDestDock? or not this.$mk2QueueSourceDock.$CanDock or not this.$mk2QueueDestDock.$CanDock">
                <do_if value="this.$mk2QueueIsPrimary">
                  <set_value name="this.$mk2DenyTrade" exact="true"/>
                  <do_if value="this.$debuglevel ge 1">
                    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': ware-exchange trade denied (docking check failed) -- retrying'" chance="this.$debugchance"/>
                  </do_if>
                </do_if>
                <set_value name="this.$mk2QueueIdx" operation="add"/>
                <continue/>
              </do_if>
            </do_if>
            <append_to_list name="this.$mk2FinalQueueTrades" exact="this.$mk2QueuedTrade"/>
            <set_value name="this.$mk2SellAmount" exact="this.$mk2SellAmount + $mk2QueuedAmountClamped"/>
            <set_value name="this.$mk2RoutePlan" exact="this.$mk2RoutePlan + (if this.$mk2RoutePlanCount gt 0 then ' | ' else '') + (if this.$mk2QueuedTrade.$Ware? and this.$mk2QueuedTrade.$Ware.name? then @this.$mk2QueuedTrade.$Ware.name else '?') + '(' + $mk2QueuedAmountClamped + ')'"/>
            <set_value name="this.$mk2RoutePlanCount" exact="this.$mk2RoutePlanCount + 1"/>
            </do_if>
            <set_value name="this.$mk2QueueIdx" operation="add"/>
          </do_while>

          <do_if value="not this.$mk2DenyTrade and this.$mk2FinalQueueTrades? and this.$mk2FinalQueueTrades.count gt 0 and this.$mk2SellAmount? and this.$mk2SellAmount gt 0">
            <do_if value="this.$debuglevel ge 1">
              <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': queued multi-ware lane ' + this.$mk2BestTrade.$Source.knownname + ' -> ' + this.$mk2BestTrade.$Destination.knownname + ' trades=' + this.$mk2FinalQueueTrades.count + ' [' + this.$mk2RoutePlan + ']'" chance="this.$debugchance"/>
            </do_if>
            <set_value name="this.$mk2CycleDenyTrade" exact="this.$mk2DenyTrade"/>
            <set_value name="this.$mk2CycleBestTrade" exact="this.$mk2BestTrade"/>
            <set_value name="this.$mk2CycleSellAmount" exact="this.$mk2SellAmount"/>
            <set_value name="this.$mk2CycleStickinessTTL" exact="this.$mk2StickinessTTLProfile"/>
            <set_value name="this.$mk2CyclePilotLevel" exact="this.$mk2PilotLevelProfile"/>
            <set_value name="this.$mk2CycleRouteAlpha" exact="this.$mk2RouteAlpha"/>
            <set_value name="this.$mk2CycleRouteBeta" exact="this.$mk2RouteBeta"/>
            <set_value name="this.$mk2CycleRouteLaneBonus" exact="this.$mk2RouteLaneBonus"/>
            <set_value name="this.$mk2CycleLowVolumeFloor" exact="this.$mk2LowVolumeFloorEffPercent"/>
            <wait exact="this.$gt_criticalYieldMs * 1ms" comment="Desync MK2 multi-ware queue creation across ships"/>
            <create_list name="this.$mk2WareExchangeLegs"/>
            <!-- Phase 1: queue all buys first (official offers + ware-exchange pickups). -->
            <do_all exact="this.$mk2FinalQueueTrades.count" counter="$mqbi">
              <set_value name="this.$mk2QueuedTrade" exact="this.$mk2FinalQueueTrades.{$mqbi}"/>
              <do_if value="this.$mk2QueuedTrade.$SourceStorageDiscovery? and this.$mk2QueuedTrade.$SourceStorageDiscovery">
                <append_to_list name="this.$mk2WareExchangeLegs" exact="table[$Station = this.$mk2QueuedTrade.$Source, $StationId = this.$mk2QueuedTrade.$Source.idcode, $Ware = this.$mk2QueuedTrade.$Ware, $WareName = @this.$mk2QueuedTrade.$Ware.name, $Amount = this.$mk2QueuedTrade.$QueuedAmount, $Direction = 'pickup']"/>
              </do_if>
              <do_elseif value="this.$mk2QueuedTrade.$SourceOffer? and this.$mk2QueuedTrade.$SourceOffer != null and this.$mk2QueuedTrade.$SourceOffer.available">
                <create_trade_order object="this.ship" tradeoffer="this.$mk2QueuedTrade.$SourceOffer" amount="this.$mk2QueuedTrade.$QueuedAmount" immediate="false" internal="this.$mk2TradeOrderInternal"/>
              </do_elseif>
            </do_all>
            <!-- Phase 2: queue all sells (official offers + ware-exchange deliveries). -->
            <do_all exact="this.$mk2FinalQueueTrades.count" counter="$mqsi">
              <set_value name="this.$mk2QueuedTrade" exact="this.$mk2FinalQueueTrades.{$mqsi}"/>
              <do_if value="this.$mk2QueuedTrade.$DestStorageDiscovery? and this.$mk2QueuedTrade.$DestStorageDiscovery">
                <append_to_list name="this.$mk2WareExchangeLegs" exact="table[$Station = this.$mk2QueuedTrade.$Destination, $StationId = this.$mk2QueuedTrade.$Destination.idcode, $Ware = this.$mk2QueuedTrade.$Ware, $WareName = @this.$mk2QueuedTrade.$Ware.name, $Amount = this.$mk2QueuedTrade.$QueuedAmount, $Direction = 'deliver']"/>
              </do_if>
              <do_elseif value="this.$mk2QueuedTrade.$DestOffer? and this.$mk2QueuedTrade.$DestOffer != null and this.$mk2QueuedTrade.$DestOffer.available">
                <create_trade_order object="this.ship" tradeoffer="this.$mk2QueuedTrade.$DestOffer" amount="this.$mk2QueuedTrade.$QueuedAmount" immediate="false" internal="this.$mk2TradeOrderInternal"/>
              </do_elseif>
              <set_value name="$mk2QueuedAmount" exact="if this.$mk2QueuedTrade.$QueuedAmount? and this.$mk2QueuedTrade.$QueuedAmount != null then this.$mk2QueuedTrade.$QueuedAmount else 0"/>
              <do_if value="$mk2QueuedAmount gt 0">
                <set_value name="$mk2LogWare" exact="this.$mk2QueuedTrade.$Ware"/>
                <set_value name="$mk2LogSrcTarget" exact="[this.$mk2QueuedTrade.$Source.cargo.{$mk2LogWare}.target, 1].max"/>
                <set_value name="$mk2LogSrcCount" exact="this.$mk2QueuedTrade.$Source.cargo.{$mk2LogWare}.count"/>
                <get_ware_reservation object="this.$mk2QueuedTrade.$Source" ware="$mk2LogWare" type="buy" virtual="false" result="$mk2LogSrcReserved"/>
                <set_value name="$mk2LogSrcEff" exact="[$mk2LogSrcCount - $mk2LogSrcReserved, 0].max"/>
                <set_value name="$mk2LogSourceFill" exact="(($mk2LogSrcEff * 100) / $mk2LogSrcTarget)i"/>
                <set_value name="$mk2LogDstTarget" exact="[this.$mk2QueuedTrade.$Destination.cargo.{$mk2LogWare}.target, 1].max"/>
                <set_value name="$mk2LogDestFill" exact="((this.$mk2QueuedTrade.$Destination.cargo.{$mk2LogWare}.count * 100) / $mk2LogDstTarget)i"/>
                <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
                  $Ship = this.ship,
                  $IsMk2Distribution = true,
                  $BuyOffer = if this.$mk2QueuedTrade.$SourceOffer? and this.$mk2QueuedTrade.$SourceOffer != null then this.$mk2QueuedTrade.$SourceOffer else null,
                  $SellOffer = if this.$mk2QueuedTrade.$DestOffer? and this.$mk2QueuedTrade.$DestOffer != null then this.$mk2QueuedTrade.$DestOffer else null,
                  $BuyStation = this.$mk2QueuedTrade.$Source,
                  $SellStation = this.$mk2QueuedTrade.$Destination,
                  $Ware = this.$mk2QueuedTrade.$Ware,
                  $Amount = $mk2QueuedAmount,
                  $SourceFillPercent = $mk2LogSourceFill,
                  $DestFillPercent = $mk2LogDestFill,
                  $IsSellOnly = false,
                  $SearchPipeline = 'normal'
                ]"/>
              </do_if>
            </do_all>
            <do_if value="this.$mk2UseWareExchange and this.$mk2WareExchangeLegs.count gt 0">
              <set_value name="this.$mk2WxDockOk" exact="true"/>
              <do_all exact="this.$mk2WareExchangeLegs.count" counter="$mk2Wxdi">
                <set_value name="this.$mk2WxLeg" exact="this.$mk2WareExchangeLegs.{$mk2Wxdi}"/>
                <run_script name="'lib.gt.dockcheck'" result="$mk2WxLegDock">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="this.$mk2WxLeg.$Station"/>
                  <param name="purpose" value="'trade'"/>
                  <param name="allowStorageDock" value="this.$mk2WxLeg.$Station.isplayerowned"/>
                  <param name="useMemo" value="true"/>
                </run_script>
                <set_value name="this.$mk2WxLegDock" exact="$mk2WxLegDock"/>
                <do_if value="not this.$mk2WxLegDock.$CanDock">
                  <set_value name="this.$mk2WxDockOk" exact="false"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not this.$mk2WxDockOk">
                <set_value name="this.$mk2DenyTrade" exact="true"/>
                <do_if value="this.$debuglevel ge 1">
                  <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': ware-exchange queue blocked (leg docking check failed) -- retrying'" chance="this.$debugchance"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="not this.$mk2DenyTrade and this.$mk2UseWareExchange and this.$mk2WareExchangeLegs.count gt 0">
              <run_script name="'lib.gt.tradematch'" result="$mk2WxResolveResult">
                <param name="mode" value="'mk2_ware_exchange_invoke'"/>
                <param name="ship" value="this.ship"/>
                <param name="wareExchangeLegs" value="this.$mk2WareExchangeLegs"/>
              </run_script>
              <set_value name="this.$mk2WxResolveResult" exact="$mk2WxResolveResult"/>
              <do_if value="not this.$mk2WxResolveResult.$Success">
                <set_value name="this.$mk2DenyTrade" exact="true"/>
                <do_if value="this.$debuglevel ge 1">
                  <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': ware-exchange resolve failed (' + (if this.$mk2WxResolveResult.$Error? then this.$mk2WxResolveResult.$Error else 'unknown') + ') -- retrying'" chance="this.$debugchance"/>
                </do_if>
              </do_if>
              <do_if value="not this.$mk2DenyTrade and this.$mk2WxResolveResult.$Success? and this.$mk2WxResolveResult.$Success">
                <do_if value="not this.$mk2WxResolveResult.$Queued? or this.$mk2WxResolveResult.$Queued lt this.$mk2WareExchangeLegs.count">
                  <set_value name="this.$mk2DenyTrade" exact="true"/>
                  <do_if value="this.$debuglevel ge 1">
                    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': ware-exchange queue incomplete (queued=' + (if this.$mk2WxResolveResult.$Queued? then this.$mk2WxResolveResult.$Queued else 0) + ' expected=' + this.$mk2WareExchangeLegs.count + ') -- retrying'" chance="this.$debugchance"/>
                  </do_if>
                </do_if>
                <do_if value="not this.$mk2DenyTrade and this.$debuglevel ge 1">
                  <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': ware-exchange queued buy+sell legs=' + this.$mk2WxResolveResult.$Queued" chance="this.$debugchance"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="not this.$mk2DenyTrade and this.$allowillegal and this.$enforceRouteIllegalLegality">
              <do_if value="not global.$GT_Ships?">
                <set_value name="global.$GT_Ships" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="$mk2PrimaryTrade" exact="this.$mk2FinalQueueTrades.{1}"/>
              <set_value name="$mk2PolicyHome" exact="if this.$homeSector? and this.$homeSector.exists then this.$homeSector else (if this.$sourceStation? and this.$sourceStation.exists then this.$sourceStation.sector else this.ship.sector)"/>
              <set_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy" exact="table[
                $AllowIllegal = this.$allowillegal,
                $EnforceRouteIllegalLegality = this.$enforceRouteIllegalLegality,
                $Ware = $mk2PrimaryTrade.$Ware,
                $BuySector = if $mk2PrimaryTrade.$Source? and $mk2PrimaryTrade.$Source.sector? then $mk2PrimaryTrade.$Source.sector else null,
                $SellSector = if $mk2PrimaryTrade.$Destination? and $mk2PrimaryTrade.$Destination.sector? then $mk2PrimaryTrade.$Destination.sector else null,
                $HomeSector = $mk2PolicyHome,
                $RouteStart = this.ship.sector,
                $Leg = 'buy',
                $LogbookEntries = false,
                $SetAt = player.age
              ]"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="this.$mk2DenyTrade" exact="true"/>
            <do_if value="this.$debuglevel ge 1">
              <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': selected trade collapsed during pre-queue clamp -- retrying'" chance="this.$debugchance"/>
            </do_if>
          </do_else>
        </do_if>
        <!-- Refresh cycle snapshot before order-completion wait (AI locals do not survive <wait>). -->
        <set_value name="this.$mk2CycleDenyTrade" exact="this.$mk2DenyTrade"/>
        <set_value name="this.$mk2CycleBestTrade" exact="this.$mk2BestTrade"/>
        <set_value name="this.$mk2CycleSellAmount" exact="this.$mk2SellAmount"/>
        <set_value name="this.$mk2CycleStickinessTTL" exact="if this.$mk2StickinessTTLProfile? then this.$mk2StickinessTTLProfile else 4"/>
        <set_value name="this.$mk2CyclePilotLevel" exact="if this.$mk2PilotLevelProfile? then this.$mk2PilotLevelProfile else 1"/>
        <set_value name="this.$mk2CycleRouteAlpha" exact="if this.$mk2RouteAlpha? then this.$mk2RouteAlpha else 0.436667"/>
        <set_value name="this.$mk2CycleRouteBeta" exact="if this.$mk2RouteBeta? then this.$mk2RouteBeta else 0.973333"/>
        <set_value name="this.$mk2CycleRouteLaneBonus" exact="if this.$mk2RouteLaneBonus? then this.$mk2RouteLaneBonus else 1.06333"/>
        <set_value name="this.$mk2CycleLowVolumeFloor" exact="if this.$mk2LowVolumeFloorEffPercent? then this.$mk2LowVolumeFloorEffPercent else this.$lowvolumefloorpercent"/>
        <set_value name="this.$mk2CycleTradeFailed" exact="false"/>
        <do_while value="this.ship.orders.count gt 0">
          <wait exact="5s">
            <interrupt>
              <conditions>
                <check_any>
                  <event_object_order_ready object="this.ship"/>
                  <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
                </check_any>
              </conditions>
              <actions>
                <do_if value="event.param == 'GT_Trade_Failed'">
                  <set_value name="this.$mk2CycleTradeFailed" exact="true"/>
                  <do_if value="this.$debuglevel ge 1">
                    <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': GT_Trade_Failed during order wait - will retry without counting success'" chance="this.$debugchance"/>
                  </do_if>
                </do_if>
              </actions>
            </interrupt>
          </wait>
        </do_while>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
          <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
        </do_if>
        <do_if value="this.$mk2CycleDenyTrade or (this.$mk2CycleTradeFailed? and this.$mk2CycleTradeFailed)">
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- Successful trade cycle: reset no-trade backoff. -->
        <set_value name="this.$noTradeRetryCount" exact="0"/>
        <do_if value="global.$GT_IdleParkingReleased? and global.$GT_IdleParkingReleased.{this.ship}?">
          <remove_value name="global.$GT_IdleParkingReleased.{this.ship}"/>
        </do_if>
        <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
          <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>
          <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>
        </do_if>
        <set_value name="this.$sourceUsage.{this.$mk2CycleBestTrade.$Source}" exact="if this.$sourceUsage? and this.$sourceUsage.{this.$mk2CycleBestTrade.$Source}? then this.$sourceUsage.{this.$mk2CycleBestTrade.$Source} + 1 else 1"/>
        <set_value name="this.$destUsage.{this.$mk2CycleBestTrade.$Destination}" exact="if this.$destUsage? and this.$destUsage.{this.$mk2CycleBestTrade.$Destination}? then this.$destUsage.{this.$mk2CycleBestTrade.$Destination} + 1 else 1"/>
        <set_value name="$stickinessTTLUse" exact="this.$mk2CycleStickinessTTL"/>
        <do_if value="$stickinessTTLUse le 0">
          <set_value name="$stickinessTTLUse" exact="1"/>
        </do_if>
        <set_value name="$isSameStickyLane" exact="false"/>
        <do_if value="this.$stickyCyclesLeft gt 0 and this.$stickySource? and this.$stickyDestination? and this.$stickyWare? and this.$stickySource == this.$mk2CycleBestTrade.$Source and this.$stickyDestination == this.$mk2CycleBestTrade.$Destination and this.$stickyWare == this.$mk2CycleBestTrade.$Ware">
          <set_value name="$isSameStickyLane" exact="true"/>
        </do_if>
        <do_if value="this.$mk2CycleBestTrade.$NeedBucket? and this.$mk2CycleBestTrade.$NeedBucket == 'A'">
          <set_value name="this.$stickySource" exact="this.$mk2CycleBestTrade.$Source"/>
          <set_value name="this.$stickyDestination" exact="this.$mk2CycleBestTrade.$Destination"/>
          <set_value name="this.$stickyWare" exact="this.$mk2CycleBestTrade.$Ware"/>
          <set_value name="this.$stickyCyclesLeft" exact="$stickinessTTLUse"/>
        </do_if>
        <do_elseif value="$isSameStickyLane and this.$stickyCyclesLeft gt 0">
          <set_value name="this.$stickyCyclesLeft" exact="[0, this.$stickyCyclesLeft - 1].max"/>
          <do_if value="this.$stickyCyclesLeft le 0">
            <set_value name="this.$stickySource" exact="null"/>
            <set_value name="this.$stickyDestination" exact="null"/>
            <set_value name="this.$stickyWare" exact="null"/>
            <set_value name="this.$stickyCyclesLeft" exact="0"/>
          </do_if>
        </do_elseif>
        <do_else>
          <set_value name="this.$stickySource" exact="this.$mk2CycleBestTrade.$Source"/>
          <set_value name="this.$stickyDestination" exact="this.$mk2CycleBestTrade.$Destination"/>
          <set_value name="this.$stickyWare" exact="this.$mk2CycleBestTrade.$Ware"/>
          <set_value name="this.$stickyCyclesLeft" exact="$stickinessTTLUse"/>
        </do_else>
        <do_if value="this.$debuglevel ge 1">
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': routeProfile lvl=' + this.$mk2CyclePilotLevel + ' alpha=' + this.$mk2CycleRouteAlpha + ' beta=' + this.$mk2CycleRouteBeta + ' lane=' + this.$mk2CycleRouteLaneBonus + ' stickyTTL=' + this.$stickyCyclesLeft + ' lowFloor=' + this.$mk2CycleLowVolumeFloor + '%'" chance="this.$debugchance"/>
        </do_if>

        <do_if value="this.ship.pilot">
          <signal_objects object="player.galaxy" param="'GT_Update_Pilot_XP'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot
          ]"/>
        </do_if>

      </do_if>

      <do_if value="this.$mk2CycleDenyTrade? and this.$mk2CycleDenyTrade">
        <resume label="no_trade_retry"/>
      </do_if>
      <do_if value="not this.$searchCadenceMinSec?">
        <set_value name="this.$searchCadenceMinSec" exact="8"/>
      </do_if>
      <do_if value="not this.$searchCadenceMaxSec?">
        <set_value name="this.$searchCadenceMaxSec" exact="12"/>
      </do_if>
      <set_value name="this.$postCycleExtraSec" exact="0"/>
      <do_if value="not this.$mk2CycleDenyTrade? or not this.$mk2CycleDenyTrade">
        <do_if value="this.$mk2CycleBestTrade? and this.$mk2CycleBestTrade.$UsedLowVolume? and this.$mk2CycleBestTrade.$UsedLowVolume and this.$mk2CycleBestTrade.$NormalMinimumTrade? and this.$mk2CycleBestTrade.$Amount lt this.$mk2CycleBestTrade.$NormalMinimumTrade">
          <set_value name="this.$postCycleExtraSec" exact="2"/>
        </do_if>
      </do_if>
      <wait min="(this.$searchCadenceMinSec + (if this.$postCycleExtraSec? then this.$postCycleExtraSec else 0)) * 1s" max="(this.$searchCadenceMaxSec + (if this.$postCycleExtraSec? then this.$postCycleExtraSec else 0)) * 1s"/>
      <resume label="main_loop"/>

      <label name="no_trade_retry"/>
      <!-- Escalating retry: 10s, 20s, 30s, 40s, 50s, 60s (cap), with jitter. -->
      <set_value name="$retryStep" exact="[this.$noTradeRetryCount, 5].min"/>
      <set_value name="$retryBase" exact="(10 + ($retryStep * 10)) * 1s"/>
      <set_value name="$retryJitter" exact="($retryBase / 5)i * 1s"/>
      <set_value name="this.$retryMin" exact="[8s, $retryBase - $retryJitter].max"/>
      <set_value name="this.$retryMax" exact="[60s, $retryBase + $retryJitter].min"/>
      <do_if value="this.$retryMin lt (this.$searchCadenceMinSec * 1s)">
        <set_value name="this.$retryMin" exact="this.$searchCadenceMinSec * 1s"/>
      </do_if>
      <do_if value="this.$retryMax lt (this.$searchCadenceMaxSec * 1s)">
        <set_value name="this.$retryMax" exact="this.$searchCadenceMaxSec * 1s"/>
      </do_if>
      <do_if value="this.$retryMax lt this.$retryMin">
        <set_value name="this.$retryMax" exact="this.$retryMin"/>
      </do_if>
      <do_if value="this.$debuglevel ge 1">
        <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': retry backoff (count=' + this.$noTradeRetryCount + ', wait=' + (this.$retryMin / 1s)i + '-' + (this.$retryMax / 1s)i + 's)'" chance="this.$debugchance"/>
      </do_if>
      <wait min="this.$retryMin" max="this.$retryMax"/>
      <do_if value="this.$idleParking and this.$noTradeRetryCount ge 5 and this.ship.cargo.count == 0">
        <set_value name="$mk2IdleHome" exact="null"/>
        <do_if value="this.$homeStation? and this.$homeStation.exists">
          <set_value name="$mk2IdleHome" exact="this.$homeStation"/>
        </do_if>
        <do_elseif value="this.$homeSector? and this.$homeSector.exists">
          <set_value name="$mk2IdleHome" exact="this.$homeSector"/>
        </do_elseif>
        <do_if value="$mk2IdleHome? and $mk2IdleHome != null">
          <run_script name="'lib.gt.idlepark'">
            <param name="handoffMode" value="'trigger'"/>
            <param name="handoffShip" value="this.ship"/>
            <param name="home" value="$mk2IdleHome"/>
            <param name="debugchance" value="this.$debugchance"/>
          </run_script>
        </do_if>
      </do_if>
      <set_value name="this.$noTradeRetryCount" exact="[this.$noTradeRetryCount + 1, 5].min"/>
      <resume label="main_loop"/>
    </actions>
  </attention>

  <on_abort>
    <!-- Intentional handoff: idle parking delegates to GTIdlePark for visible queued docking. -->
    <set_value name="$isIdleParkHandoff" exact="false"/>
    <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.orders.count gt 0">
      <do_all exact="this.ship.orders.count" counter="$ipoi">
        <set_value name="$ipOrder" exact="this.ship.orders.{$ipoi}"/>
        <do_if value="@$ipOrder.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_if>
        <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_elseif>
      </do_all>
    </do_if>
    <do_if value="$isIdleParkHandoff">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': on_abort skipped (handoff to GTIdlePark)'" chance="100"/>
      </do_if>
      <return/>
    </do_if>

    <!-- Clear stale clearance naming flag on order abort only when cargo is actually empty. -->
    <do_if value="this.ship.cargo.count == 0 and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
      <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship = this.ship,
          $pilot = this.ship.pilot,
          $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType = 'trader'
        ]"/>
      </do_if>
    </do_if>

    <!-- Bridge MK2 aborts into MD cleanup pipeline (name restore, registry cleanup, etc.). -->
    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
      <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
    </do_if>
    <set_value name="$abortTraceId" exact="this.ship.idcode + '|MK2_ON_ABORT_ENTRY|' + (player.age / 1s)i"/>
    <set_value name="$abortInRegistry" exact="false"/>
    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
      <set_value name="$abortInRegistry" exact="true"/>
    </do_if>
    <set_value name="$abortDefaultOrder" exact="'NONE'"/>
    <do_if value="this.ship.defaultorder?">
      <set_value name="$abortDefaultOrder" exact="@$this.ship.defaultorder.id"/>
    </do_if>
    <set_value name="$abortCommanderId" exact="'NONE'"/>
    <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
      <set_value name="$abortCommanderId" exact="@$this.ship.commander.idcode"/>
    </do_if>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-CleanupTrace] trace=' + $abortTraceId + ' source=MK2_ON_ABORT cue=order.trade.galaxytraderMK2 ship=' + this.ship.idcode + ' inRegistry=' + $abortInRegistry + ' default=' + $abortDefaultOrder + ' commander=' + $abortCommanderId + ' action=ON_ABORT_ENTRY'" chance="100"/>
    </do_if>
    <do_if value="this.ship? and this.ship.exists">
      <set_value name="$cleanupTraceId" exact="this.ship.idcode + '|MK2_ON_ABORT|' + (player.age / 1s)i"/>
      <set_value name="$cleanupDefaultOrder" exact="@$this.ship.defaultorder.id"/>
      <set_value name="$cleanupCommanderId" exact="'NONE'"/>
      <set_value name="$cleanupCommanderOrder" exact="'NONE'"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$cleanupCommanderId" exact="@$this.ship.commander.idcode"/>
        <do_if value="this.ship.commander.defaultorder?">
          <set_value name="$cleanupCommanderOrder" exact="@$this.ship.commander.defaultorder.id"/>
        </do_if>
      </do_if>
      <set_value name="$abortHasDirectGTOrder" exact="false"/>
      <set_value name="$abortHasGTCommander" exact="false"/>
      <do_if value="$cleanupDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$cleanupDefaultOrder}">
        <set_value name="$abortHasDirectGTOrder" exact="true"/>
      </do_if>
      <do_elseif value="$cleanupDefaultOrder == 'Assist' and this.ship.defaultorder? and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
        <set_value name="$abortHasDirectGTOrder" exact="true"/>
      </do_elseif>
      <do_if value="not $abortHasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
        <set_value name="$abortHasGTCommander" exact="true"/>
      </do_if>
      <do_elseif value="not $abortHasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
        <set_value name="$abortHasGTCommander" exact="true"/>
      </do_elseif>
      <do_if value="not $abortHasDirectGTOrder and not $abortHasGTCommander">
        <!-- Detach intent latch: commander/default order state can be stale for a few seconds. -->
        <do_if value="not global.$GT_CleanupIntent?">
          <set_value name="global.$GT_CleanupIntent" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_CleanupIntent.{this.ship}" exact="table[
          $Active = true,
          $StartTime = player.age,
          $ExpireTime = player.age + 8s,
          $Source = 'MK2_ON_ABORT',
          $TraceId = $cleanupTraceId,
          $DefaultOrderAtSignal = $cleanupDefaultOrder,
          $CommanderAtSignal = $cleanupCommanderId
        ]"/>
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'GT_Order_Cancelled',
          $Source = 'MK2_ON_ABORT',
          $TraceId = $cleanupTraceId
        ]"/>
        <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
          $Ship = this.ship,
          $Source = 'MK2_ON_ABORT',
          $TraceId = $cleanupTraceId
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=MK2_ON_ABORT ship=' + this.ship.idcode + ' default=' + (if $cleanupDefaultOrder then $cleanupDefaultOrder else 'NONE') + ' commander=' + $cleanupCommanderId + ' commanderOrder=' + $cleanupCommanderOrder + ' action=SIGNAL_GT_ORDER_CANCELLED+ORPHAN_CHECK'" chance="100"/>
          <debug_text text="'[GT-MK2] ' + this.ship.idcode + ': on_abort -> triggered orphan cleanup check'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=MK2_ON_ABORT ship=' + this.ship.idcode + ' default=' + (if $cleanupDefaultOrder then $cleanupDefaultOrder else 'NONE') + ' commander=' + $cleanupCommanderId + ' commanderOrder=' + $cleanupCommanderOrder + ' action=SKIP_GT_ORDER_CANCELLED_ACTIVE_GT_CONTROL'" chance="100"/>
        </do_if>
      </do_else>
    </do_if>
  </on_abort>
</aiscript>
<?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.trade.galaxytradermk4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="5">
  <order id="GalaxyTraderMK4Supply" name="{77000, 10005}" description="{77000, 10105}" category="trade" infinite="true" allowinloop="false" canplayercancel="true">
    <params>
      <!-- MK4 Galaxy-Supply â€” parameter names per OPEN_GALAXYTRADER_MK4_GALAXY_SUPPLY_ORDER.md Â§3 (dual jump model Â§3.1) -->
      <param name="home" default="this.sector" type="object" text="{77000,1002}" comment="Home anchor (sector or station) for supply operations">
        <input_param name="class" value="[class.sector,class.station]"/>
      </param>
      <param name="assignHome" default="true" type="bool" text="{77000,1085}" comment="When home is a station: assign ship as station trade subordinate (Â§1.5)"/>
      <param name="jumpDistanceCoverage" default="1" type="number" text="{77000,1086}" comment="{77000,1088}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="jumpDistanceBuy" default="1" type="number" text="{77000,1021}" comment="{77000,1021}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="serveHomeOnly" default="false" type="bool" text="{77000,1072}" comment="{77000,1089}"/>
      <param name="buyFromPlayer" default="true" type="bool" text="{77000,1073}" comment="Allow purchases from player-owned stations (canonical MK4 flag)"/>
      <param name="buyFromFaction" default="true" type="bool" text="{77000,1074}" comment="Allow purchases from non-player stations (canonical MK4 flag)"/>
      <!-- Legacy aliases kept for save/UI compatibility; canonical flags above take priority. -->
      <param name="dedicatedServe" default="false" type="bool" text="{77000,1072}" comment="Legacy alias for serveHomeOnly" advanced="true"/>
      <param name="allowPlayerSuppliers" default="true" type="bool" text="{77000,1073}" comment="Legacy alias for buyFromPlayer" advanced="true"/>
      <param name="allowAiSuppliers" default="true" type="bool" text="{77000,1074}" comment="Legacy alias for buyFromFaction" advanced="true"/>
      <param name="allowBuildstorage" default="true" type="bool" text="{77000,1075}" comment="Consider build storage needs (Â§3) â€” maps to internal ignorebuildstorage inverse"/>
      <param name="allowResources" default="true" type="bool" text="{77000,1076}" comment="Supply resource-class wares"/>
      <param name="allowIntermediates" default="true" type="bool" text="{77000,1077}" comment="Supply intermediate/product wares"/>
      <param name="allowTradewares" default="true" type="bool" text="{77000,1078}" comment="{77000,1090}"/>
      <param name="autowares" default="true" type="bool" text="{77000,1015}" comment="{77000,1023}"/>
      <param name="warebasket" default="[]" type="list" text="{77000,1069}" comment="{77000,1024}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="maxTrades" default="3" type="number" text="{77000,1080}" comment="Chained trade rounds per cycle (cap 3 per Â§4.0.1)">
        <input_param name="min" value="1"/>
        <input_param name="max" value="3"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="backtrackTolerance" default="1" type="number" text="{77000,1081}" comment="Extra jumps tolerated when chaining suppliers (Â§3 / MK1 parity)">
        <input_param name="min" value="0"/>
        <input_param name="max" value="5"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="useMinCargoThreshold" default="false" type="bool" text="{77000,1082}" comment="Enable minimum cargo utilization filter; disabled = no min cargo threshold"/>
      <param name="minCargoUsed" default="80" type="number" text="{77000,1082}" comment="Target cargo fill % per chunk (Â§3 minCargoUsed)">
        <input_param name="min" value="10"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      <param name="playerBuyMod" default="0" type="number" text="{77000,1083}" comment="{77000,1091}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      <param name="allowillegal" default="false" type="bool" text="{77000,1011}" comment="{77000,1025}"/>
      <param name="enforceRouteIllegalLegality" default="false" type="bool" text="{77000,1070}" comment="{77000,1071}"/>
      <param name="ignorecarrieraux" default="false" type="bool" text="{77000,1054}" comment="{77000,1055}"/>
      <param name="ignoretraderules" default="false" type="bool" text="{77000,1058}" comment="{77000,1059}"/>
      <param name="ignoremk1supply" default="true" type="bool" text="{77000,1060}" comment="{77000,1061}"/>
      <param name="logbookentries" default="true" type="bool" text="{77000,1012}" comment="{77000,1041}"/>
      <param name="idleParking" default="false" type="bool" text="{77000,1096}" comment="{77000,1097}">
        <patch value="false" sinceversion="4"/>
      </param>
      <param name="autoJumpDistanceByLevel" default="false" type="bool" text="{77000,1098}" comment="{77000,1099}">
        <patch value="false" sinceversion="5"/>
      </param>
      
      <param name="sectorwhitelist" default="[]" type="list" text="{77000,1052}" comment="{77000,1053}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.sector]"/>
      </param>
      <param name="prioritywares" default="[]" type="list" text="{77000,1064}" comment="{77000,1066}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="priorityscoremultiplier" default="150" type="number" text="{77000,1065}" comment="{77000,1067}">
        <input_param name="min" value="125"/>
        <input_param name="max" value="300"/>
        <input_param name="step" value="25"/>
      </param>
      
      <!-- ========================================== -->
      <!-- TRADING RANGE (Ship-specific)             -->
      <!-- ========================================== -->
      <param name="distancepenalty" default="50" type="number" text="{77000,1016}" comment="Distance impact on trade scoring: 0%=Ignore distance (pure profit), 50%=Balanced, 100%=Prefer close trades (2x distance penalty)">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      
      <!-- ========================================== -->
      <!-- NOTIFICATION LEVEL (Global setting override) -->
      <!-- ========================================== -->
      <param name="notifications" default="1" type="number" text="{77000,1017}" comment="{77000,1032}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      
      <!-- ========================================== -->
      <!-- ADVANCED SETTINGS                         -->
      <!-- ========================================== -->
      <param name="fleetcoordination" default="true" type="bool" text="{77000,1018}" advanced="true" comment="{77000,1029}"/>
      <param name="marketupdatefreq" default="60s" type="time" text="{77000,1050}" advanced="true" comment="{77000,1034}">
        <input_param name="min" value="30s"/>
        <input_param name="max" value="300s"/>
        <input_param name="step" value="30s"/>
      </param>
      <param name="debuglevel" default="1" type="number" text="{1041, 10086}" advanced="true" comment="{77000,1035}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="tradeeval" default="false" type="bool" text="{77000,1051}" advanced="true" comment="{77000,1040}"/>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
  </order>
  
  <interrupts>
    <handler ref="SectorChangeHandler"/>
    
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>
    
    <!-- Trade Found Event Handler: Catches GT_Trade_Found signal regardless of ship state -->
    <!-- This ensures trades are processed immediately even if ship is in main_loop or other code paths -->
    <!-- Note: Cannot use <resume> in interrupt handlers, so we set a flag that main_loop checks -->
    <!-- Trade data is passed in signal param2 (like GT_Training_Station_Found) -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
      </conditions>
      <actions>
        <!-- Extract trade data from signal param2 (like GT_Training_Station_Found handler) -->
        <set_value name="$signalData" exact="event.param2"/>
        <set_value name="$signalTradeList" exact="[]"/>
        <set_value name="$signalSearchMethod" exact="''"/>
        <do_if value="$signalData? and $signalData != null">
          <set_value name="$signalTradeList" exact="@$signalData.$TradeList"/>
          <set_value name="$signalSearchMethod" exact="@$signalData.$SearchMethod"/>
        </do_if>
        
        <!-- FALLBACK: If param2 is empty or null, read from global storage (backward compatibility) -->
        <!-- This handles cases where ProcessTradeFoundSignalQueue fails to populate param2 -->
        <do_if value="($signalTradeList == null or $signalTradeList.count == 0) and global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
          <set_value name="$signalTradeList" exact="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <set_value name="$signalSearchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
        </do_if>
        
        <!-- Only set the interrupt flag if we actually have trades to process.
             Empty signals cause pointless trade_found processing with 0 trades. -->
        <do_if value="$signalTradeList != null and $signalTradeList.count gt 0">
          <do_if value="$signalSearchMethod? and ($signalSearchMethod == 'LIVE' or $signalSearchMethod == 'live' or $signalSearchMethod == 'mk4live')">
            <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
          </do_if>
          <set_value name="this.$tradeFoundViaInterrupt" exact="true"/>
          <set_value name="this.$tradeListFromSignal" exact="$signalTradeList"/>
          <set_value name="this.$searchMethodFromSignal" exact="if $signalSearchMethod != null and $signalSearchMethod != '' then $signalSearchMethod else ''"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$dataSource" exact="if (event.param2? and event.param2 != null) then 'param2' else 'global storage'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received via interrupt handler - stored ' + $signalTradeList.count + ' trades from ' + $dataSource" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received but trade list is empty - ignoring (no interrupt flag set)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>

    <!-- Search Go Event Handler: capture scheduler grants even outside wait_for_response -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Search_Go'"/>
      </conditions>
      <actions>
        <set_value name="$searchGoData" exact="event.param2"/>
        <do_if value="$searchGoData? and $searchGoData != null and typeof $searchGoData == datatype.table">
          <set_value name="this.$pendingSearchParams" exact="$searchGoData"/>
          <set_value name="this.$searchGoViaInterrupt" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$searchGoPhase" exact="if $searchGoData.$Phase? then @$searchGoData.$Phase else 'unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Search_Go captured via global interrupt (phase=' + $searchGoPhase + ')'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </handler>
    
    <!-- High-Performance Training Event Handlers -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$trainingStation" exact="$trainingData.$Station"/>
        <set_value name="$requiredLevel" exact="$trainingData.$Level"/>
        <!-- Academy enrollments must NOT interrupt the current order; they
             append DockAndTrain so the ship finishes the active task first
             and the queued training is visible in the order list. The
             natural training ladder keeps using immediate dispatch. -->
        <set_value name="$isAcademy" exact="@$trainingData.$IsAcademy"/>
        <set_value name="$useImmediate" exact="not $isAcademy"/>
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist'">
          <set_value name="$useImmediate" exact="false"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸŽ“ Training station found: ' + $trainingStation.knownname + ' for level ' + $requiredLevel + ' (academy=' + $isAcademy + ', immediate=' + $useImmediate + ')'" chance="100"/>
        </do_if>
        
        <!-- Create training order: immediate for natural ladder, queued for academy -->
        <create_order object="this.ship" id="'DockAndTrain'" immediate="$useImmediate">
          <param name="destination" value="$trainingStation"/>
          <param name="debugchance" value="@this.$debugchance"/>
        </create_order>
        
        <!-- Set flag to indicate training is in progress -->
        <set_value name="this.$training_in_progress" exact="true"/>
        <!-- Set flag to indicate training transition for on_abort handler -->
        <set_value name="this.$training_transition" exact="true"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': DockAndTrain order created for ' + $trainingStation.knownname" chance="100"/>
        </do_if>
        
        <!-- Set flag to prevent race condition in on_abort handler -->
        <!-- Ensures the on_abort handler knows a training order was just created -->
        <set_value name="this.$training_order_created" exact="player.age"/>
      </actions>
    </handler>
    
    <!-- Event-Driven Mobile Satellite Intelligence: Detect stations entering radar range -->
    <!-- 
    OPTIMIZED: Event-driven station detection (replaces polling-based MobileSatelliteIntelligence)
    - Uses vanilla gravidar scan events (zero CPU when no stations detected)
    - Only Level 9+ pilots can detect stations (skill gate maintained)
    - Signals MD immediately when stations detected (no polling overhead)
    - Same functionality as old polling system but much more efficient
    -->
    <handler comment="Detect stations entering radar range for mobile satellite intelligence">
      <conditions>
        <event_gravidar_has_scanned object="this.ship"/>
        <check_value value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?"/>
        <check_value value="this.sector"/>
        <!-- Only Level 9+ pilots and when Mobile Intel is enabled -->
        <check_value value="@global.$GT_Pilots.{this.ship.pilot}.$Level ge 9"/>
        <check_value value="not global.$GT_GlobalSettings.$MobileIntel? or global.$GT_GlobalSettings.$MobileIntel.$Enable"/>
        <!-- PERFORMANCE: Do not run actions unless there is at least 1 station contact -->
        <!-- Vanilla pattern: use count_gravidar_contacts with min="1" to avoid per-scan work when nothing is detected -->
        <count_gravidar_contacts result="$_detectedStations" object="this.ship" class="class.station" docked="false" checkoperational="true" multiple="true" min="1"/>
      </conditions>
      <actions>
        <!-- Stations were detected (min=1 in conditions). Process a small capped number per scan to smooth spikes. -->
        <set_value name="$level" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        <set_value name="$detectedStations" exact="$_detectedStations"/>
        
        <!-- Cap work per scan event (prevents large bursts when many stations are in radar range) -->
        <set_value name="$stationsToProcess" exact="[$detectedStations.count, 5].min"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI-Intel] ' + this.ship.idcode + ' detected ' + $detectedStations.count + ' station(s) - processing ' + $stationsToProcess" chance="20"/>
        </do_if>
        
        <do_all exact="$stationsToProcess" counter="$i">
          <set_value name="$station" exact="$detectedStations.{$i}"/>
          <do_if value="$station.exists and $station.isoperational">
            <!-- Signal MD to process this station -->
            <signal_objects object="player.galaxy" param="'GT_Station_Detected'" param2="table[$Ship=this.ship, $station=$station, $pilotLevel=$level]"/>
          </do_if>
        </do_all>
      </actions>
    </handler>

    <!-- Event-Driven Threat Avoidance: Detect hostile ships entering radar range (gravidar) -->
    <!-- Uses vanilla event_gravidar_has_scanned + count_gravidar_contacts (no polling).
         Only broadcasts when computed threat level meets ThreatAvoidance.BlacklistThreshold to avoid spam. -->
    <handler comment="ThreatAvoidance: hostile gravidar contact detection">
      <conditions>
        <event_gravidar_has_scanned object="this.ship"/>
        <check_value value="this.sector"/>
        <!-- Feature gate -->
        <check_value value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ThreatAvoidance? and global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled"/>
        <check_value value="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>
        <!-- Only run actions if at least 1 hostile ship contact exists -->
        <count_gravidar_contacts result="$_detectedHostiles" object="this.ship" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" maybeattackedby="this.ship" checkoperational="false" masstraffic="false" docked="false" multiple="true" min="1">
          <match_context macro="this.sector.macro"/>
          <match_context class="class.highway" negate="true"/>
          <match state="componentstate.wreck" negate="true"/>
        </count_gravidar_contacts>
      </conditions>
      <actions>
        <!-- Get pilot skill level - only Level 6+ pilots can broadcast threat warnings to fleet -->
        <set_value name="$pilotLevel" exact="1"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        
        <!-- Shared throttle with move.generic detection (single source of truth across scripts).
             This prevents duplicate logs/broadcasts when both move.generic and this order detect the same contact. -->
        <do_if value="not global.$GT_ThreatDetectThrottle?">
          <set_value name="global.$GT_ThreatDetectThrottle" exact="table[]"/>
        </do_if>
        <set_value name="$_last" exact="@global.$GT_ThreatDetectThrottle.{this.ship}"/>
        <do_if value="$_last == null">
          <set_value name="$_last" exact="0s"/>
        </do_if>
        <set_value name="$_logAllowed" exact="player.age - $_last ge 10s"/>
        <set_value name="$_broadcastAllowed" exact="player.age - $_last ge 30s"/>

        <set_value name="$hostiles" exact="$_detectedHostiles"/>
        <!-- IMPORTANT: $hostiles.count may include non-operational contacts (checkoperational="false").
             We want HostileCount to match the class breakdown we compute below, so we derive it from class counters. -->
        <set_value name="$hostileListCount" exact="$hostiles.count"/>
        <set_value name="$hostileCount" exact="0"/>

        <!-- Compute threat score and class breakdown (cheap: based on detected hostiles only) -->
        <set_value name="$threatScore" exact="0"/>
        <set_value name="$shipClass_XL" exact="0"/>
        <set_value name="$shipClass_L" exact="0"/>
        <set_value name="$shipClass_M" exact="0"/>
        <set_value name="$shipClass_S" exact="0"/>
        <set_value name="$factionCounts" exact="table[]"/>

        <do_all exact="$hostileListCount" counter="$i">
          <set_value name="$h" exact="$hostiles.{$i}"/>
          <do_if value="@$h.exists and @$h.isoperational">
            <do_if value="$h.isclass.ship_xl">
              <set_value name="$threatScore" exact="$threatScore + 5"/>
              <set_value name="$shipClass_XL" operation="add"/>
            </do_if>
            <do_elseif value="$h.isclass.ship_l">
              <set_value name="$threatScore" exact="$threatScore + 3"/>
              <set_value name="$shipClass_L" operation="add"/>
            </do_elseif>
            <do_elseif value="$h.isclass.ship_m">
              <set_value name="$threatScore" exact="$threatScore + 2"/>
              <set_value name="$shipClass_M" operation="add"/>
            </do_elseif>
            <do_else>
              <set_value name="$threatScore" exact="$threatScore + 1"/>
              <set_value name="$shipClass_S" operation="add"/>
            </do_else>

            <do_if value="@$h.owner != null">
              <set_value name="$f" exact="$h.owner"/>
              <set_value name="$factionCounts.{$f}" exact="@$factionCounts.{$f} + 1"/>
            </do_if>
          </do_if>
        </do_all>

        <!-- Make HostileCount match class counters -->
        <set_value name="$hostileCount" exact="$shipClass_XL + $shipClass_L + $shipClass_M + $shipClass_S"/>

        <!-- Determine primary faction -->
        <set_value name="$primaryFaction" exact="null"/>
        <set_value name="$maxFactionCount" exact="0"/>
        <do_all exact="$factionCounts.keys.count" counter="$fi">
          <set_value name="$f" exact="$factionCounts.keys.{$fi}"/>
          <do_if value="$factionCounts.{$f} gt $maxFactionCount">
            <set_value name="$primaryFaction" exact="$f"/>
            <set_value name="$maxFactionCount" exact="$factionCounts.{$f}"/>
          </do_if>
        </do_all>

        <!-- Convert score to threat level (1-5), matching GT_ThreatIntelligence receiver expectations -->
        <set_value name="$threatLevel" exact="2"/>
        <do_if value="$shipClass_XL gt 0 or $shipClass_L gt 0">
          <set_value name="$threatLevel" exact="4"/>
        </do_if>
        <do_elseif value="$threatScore ge 6">
          <set_value name="$threatLevel" exact="3"/>
        </do_elseif>

        <!-- Compare to configured threshold -->
        <set_value name="$threshold" exact="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold"/>
        <do_if value="not $threshold?">
          <set_value name="$threshold" exact="3"/>
        </do_if>

        <!-- Only Level 6+ pilots broadcast to fleet (matches ShipUnderAttack handler pattern) -->
        <do_if value="$pilotLevel ge 6">
          <do_if value="$hostileCount gt 0 and $_broadcastAllowed and $threatLevel ge $threshold">
            <!-- Broadcast to MD threat system (event-driven) -->
            <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
              $Sector = this.sector,
              $DetectedBy = this.ship,
              $HostileCount = $hostileCount,
              $PrimaryFaction = $primaryFaction,
              $ShipClass_XL = $shipClass_XL,
              $ShipClass_L = $shipClass_L,
              $ShipClass_M = $shipClass_M,
              $ShipClass_S = $shipClass_S,
              $ThreatScore = $threatScore,
              $Timestamp = player.age
            ]"/>
          </do_if>
        </do_if>

        <!-- Logging: emit whenever detection fires (hostiles detected), but respect shared log throttle -->
        <!-- Lower level pilots (1-5) can detect but don't broadcast - log for debugging -->
        <do_if value="$hostileCount gt 0 and $_logAllowed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="global.$GT_ThreatDetectThrottle.{this.ship}" exact="player.age"/>
          <set_value name="$_primaryFactionName" exact="if $primaryFaction? then @$primaryFaction.knownname else 'UNKNOWN'"/>
          <set_value name="$_broadcasted" exact="if ($pilotLevel ge 6 and $_broadcastAllowed and $threatLevel ge $threshold) then 'YES' else 'NO'"/>
          <set_value name="$_broadcastReason" exact="if $pilotLevel lt 6 then 'PILOT LEVEL TOO LOW (Lv.' + $pilotLevel + ', requires Lv.6+)' else if not $_broadcastAllowed then 'THROTTLED' else if $threatLevel lt $threshold then 'THREAT BELOW THRESHOLD' else 'OK'"/>
          <debug_text text="'[GT-Threat-Detect] ' + this.ship.idcode + ' (Pilot Lv.' + $pilotLevel + ') in ' + this.sector.knownname
            + ' - hostiles=' + $hostileCount
            + ' (XL=' + $shipClass_XL + ', L=' + $shipClass_L + ', M=' + $shipClass_M + ', S=' + $shipClass_S + ')'
            + ', threatScore=' + $threatScore + ', threatLevel=' + $threatLevel + ', threshold=' + $threshold
            + ', primaryFaction=' + $_primaryFactionName
            + ', broadcasted=' + $_broadcasted + ' (' + $_broadcastReason + ')'" chance="100"/>
        </do_if>
      </actions>
    </handler>
    
    <!-- Subordinate Resync Handler: Listen for commander order changes (like vanilla order.assist) -->
    <handler comment="Subordinate resync on commander order change">
      <conditions>
        <check_all>
          <event_object_order_ready object="this.ship.commander" check="false" comment="Commander's order ready"/>
          <check_value value="event.param == event.object.defaultorder" comment="It's the default order"/>
        </check_all>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Commander order changed - restarting to resync settings'" chance="100"/>
        </do_if>
        <!-- Use abort_called_scripts like vanilla - forcefully restart at init label -->
        <abort_called_scripts resume="init"/>
      </actions>
    </handler>
    
    <!-- Commander change detection handler -->
    <!-- Tests if commander change detection interferes with trade execution -->
    <!-- This handler fires BEFORE the subordinate resync handler restarts the script -->
    <!-- Using this.assignedcontrolled like vanilla order.assist.xml -->
    <handler comment="Commander removed or changed">
      <conditions>
        <event_object_commander_set object="this.assignedcontrolled"/>
      </conditions>
      <actions>
        <set_value name="$newCommander" exact="event.param"/>
        
        <!-- Update state machine BEFORE script restarts -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (commander: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <!-- NOTE: Script will restart via subordinate resync handler if commander has order change -->
        <!-- But signal is sent FIRST, so state manager can process it -->
      </actions>
    </handler>
    
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Complete'"/>
      </conditions>
      <actions>
        <set_value name="$completionData" exact="event.param2"/>
        <set_value name="$completedLevel" exact="$completionData.$Level"/>
        
        <!-- Ignore spurious early-complete (Level 0) while academy or MD timer still active -->
        <set_value name="$shouldResumeTrading" exact="true"/>
        <do_if value="$completedLevel? and $completedLevel le 0">
          <set_value name="$shouldResumeTrading" exact="false"/>
        </do_if>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
        </do_if>
        
        <do_if value="$shouldResumeTrading">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training completed for level ' + $completedLevel + ' - setting flag to resume trading'" chance="100"/>
        </do_if>
        
        <!-- Set flag to resume trading (can't use resume in interrupt handler) -->
        <set_value name="this.$training_complete" exact="true"/>
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$training_order_created"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ignoring spurious training-complete signal (level=' + $completedLevel + ', academy/timer still active)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Failed'"/>
      </conditions>
      <actions>
        <set_value name="$failureData" exact="event.param2"/>
        <set_value name="$reason" exact="$failureData.$Reason"/>
        
        <!-- Do not resume trading while pilot is still blocked or academy course active -->
        <set_value name="$shouldResumeTrading" exact="true"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
        </do_if>
        
        <do_if value="$shouldResumeTrading">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training failed: ' + $reason + ' - setting flag to resume trading'" chance="100"/>
        </do_if>
        
        <!-- Set flag to resume trading (can't use resume in interrupt handler) -->
        <set_value name="this.$training_complete" exact="true"/>
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$training_order_created"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training failed (' + $reason + ') but pilot still blocked - not resuming trading'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <!-- Order cancellation detection handler -->
    <!-- Detects when GT default order is cancelled -->
    <!-- Note: Ships always have a default order (Wait, Assist, etc.), so we check:
         1. If cancelled order was GT order (event.param.id == 'GalaxyTraderMK3')
         2. If ship is still GT-controlled (direct GT order OR subordinate with GT commander via Assist)
         3. Only act if ship is no longer GT-controlled -->
    <handler comment="GT order cancelled">
      <conditions>
        <event_object_order_cancelled object="this.ship" immediate="true"/>
        <!-- Note: Ships always have a default order (Wait, Assist, etc.), so we check the cancelled order ID and current default order -->
      </conditions>
      <actions>
        <!-- Check which order was cancelled -->
        <set_value name="$cancelledOrderId" exact="@event.param.id"/>
        <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <!-- Unified GT order status check (inline for AI scripts) -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <set_value name="$hasGTCommander" exact="false"/>
        <set_value name="$isGTControlled" exact="false"/>
        
        <!-- Check direct GT order -->
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply'">
          <set_value name="$hasDirectGTOrder" exact="true"/>
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
        
        <!-- Check commander status -->
        <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$hasGTCommander" exact="true"/>
            <do_if value="$currentDefaultOrder == 'Assist'">
              <set_value name="$isGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Only act if GT order was actually cancelled (ship is no longer GT-controlled) -->
        <do_if value="not $isGTControlled">
          <!-- Check if GT order was explicitly cancelled OR if current default is not GT/Assist-with-GT-commander -->
          <do_if value="$cancelledOrderId == 'GalaxyTraderMK3' or $cancelledOrderId == 'GalaxyTraderMK4Supply' or not $cancelledOrderId">
            <!-- GT order is being cancelled â†’ send Phase 7 signal -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (interrupt handler, cancelled order: ' + (if $cancelledOrderId then $cancelledOrderId else 'NONE') + ', current default: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isGTControlled + ')'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
            
            <!-- EVENT-DRIVEN: Trigger orphaned ship check -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
              <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
            </do_if>
            
            <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
            <do_if value="not $hasDirectGTOrder and not $hasGTCommander and this.ship.pilot?">
              <set_value name="$originalName" exact="null"/>
              <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
              </do_if>
              
              <do_if value="$originalName">
                <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                  $Ship = this.ship,
                  $Pilot = this.ship.pilot,
                  $Reason = 'GT order cancelled - restoring original name',
                  $OriginalName = $originalName
                ]"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Ship is still GT-controlled (direct GT order or subordinate with GT commander) - skip -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Order cancelled interrupt fired but ship still GT-controlled (cancelled: ' + (if $cancelledOrderId then $cancelledOrderId else 'NONE') + ', current default: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isGTControlled + ') - skipping Phase 7'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>

  </interrupts>
  
  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_command command="command.searchtrades"/>
    <set_command_action commandaction="commandaction.searchingtrades"/>

    <!-- CRITICAL: Ensure instance wait time storage ALWAYS exists before any <wait ...> evaluates it.
         Vanilla pattern: instance vars are accessed with safe operator @this.$var (e.g. @this.$resupplier...). -->
    <!-- Purpose A: Pre-request wait for GT_Trade_Found signal (milliseconds) -->
    <set_value name="this.$tradeFoundSignalWaitTime" exact="5ms"/>
    <!-- Purpose B: No-trade retry cooldown (seconds) -->
    <set_value name="this.$retryCooldown" exact="10s"/>
    <!-- Tracks GT_Search_Go captured outside wait_for_response -->
    <set_value name="this.$searchGoViaInterrupt" exact="false"/>
    
    <!-- Legacy persistent variables removed - no longer needed with unified maintenance system -->
    
    <!-- ============================================================================= -->
    <!-- SAVE GAME CLEANUP: Clear stale tracking data when loading from a save game  -->
    <!-- ============================================================================= -->
    <!-- Check if resupply tracking exists and verify if the order is still active.   -->
    <!-- Only remove tracking if the order no longer exists (stale data).             -->
    <!-- ============================================================================= -->
    <!-- PERFORMANCE: Optimized resupply order check - use order.id property instead of iterating all orders -->
    <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
      <!-- Check if ship has active resupply/repair/equipment order using order.id (more efficient than iterating) -->
      <set_value name="$hasActiveResupplyOrder" exact="false"/>
      <!-- Our resupply uses order.build.equip, whose order id is 'Equip' (vanilla) -->
      <do_if value="this.ship.order? and (this.ship.order.id == 'Resupply' or this.ship.order.id == 'Repair' or this.ship.order.id == 'Equip')">
        <set_value name="$hasActiveResupplyOrder" exact="true"/>
      </do_if>
      
      <do_if value="not $hasActiveResupplyOrder">
        <!-- No active order - tracking is stale, remove it -->
        <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale resupply tracking (no active order)'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- Order still active - keep tracking -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resupply order still active after save load - keeping tracking'" chance="100"/>
        </do_if>
      </do_else>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- MODULAR INITIALIZATION - REPLACES ~200 LINES OF COMPLEX INITIALIZATION CODE -->
    <!-- ============================================================================= -->
    
    <!-- CRITICAL DEBUG: Log that init block started -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === INIT BLOCK STARTED === (Ship: ' + this.ship.knownname + ', Pilot: ' + (if this.ship.pilot then this.ship.pilot.name else 'NONE') + ')'" chance="100"/>
    </do_if>
    
    <!-- Create order parameters table for library compatibility -->
    <set_value name="$orderParams" exact="table[]"/>
    
    <!-- Legacy maintenance variables removed - no longer needed with unified maintenance system -->
    
    <!-- SUBORDINATE HOME BASE INHERITANCE:
         only ship-subordinates inherit commander's home.
         Station-assigned ships must keep their own station home anchor for serveHomeOnly. -->
    <set_value name="$effectiveHome" exact="$home"/>
    <do_if value="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
      <!-- Ship is a subordinate - ALWAYS inherit commander's home sector -->
      <do_if value="this.ship.commander.defaultorder and this.ship.commander.defaultorder.$home?">
        <set_value name="$effectiveHome" exact="this.ship.commander.defaultorder.$home"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting home base from commander ' + this.ship.commander.idcode + ': ' + $effectiveHome.knownname" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    
    <!-- Store as script variable for persistence throughout execution -->
    <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
    <!-- Order restart (trade revoke / maintenance transition): drop stale force-live flags and
         per-ship cache skip markers so a fresh search can use repopulated MK4 cache immediately. -->
    <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
    <set_value name="this.$forceLiveAfterLiveReject" exact="false"/>
    <set_value name="$initMk4HomeSector" exact="if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else null)"/>
    <do_if value="$initMk4HomeSector? and $initMk4HomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$initMk4HomeSector}?">
      <do_all exact="global.$GT_TradeCacheMK4.{$initMk4HomeSector}.count" counter="$initCi">
        <set_value name="$initEntry" exact="global.$GT_TradeCacheMK4.{$initMk4HomeSector}.{$initCi}"/>
        <do_if value="$initEntry? and $initEntry.$FailedShips? and $initEntry.$FailedShips.count gt 0">
          <set_value name="$initNewFailed" exact="[]"/>
          <do_all exact="$initEntry.$FailedShips.count" counter="$initFsi">
            <do_if value="$initEntry.$FailedShips.{$initFsi} != this.ship">
              <append_to_list name="$initNewFailed" exact="$initEntry.$FailedShips.{$initFsi}"/>
            </do_if>
          </do_all>
          <set_value name="$initEntry.$FailedShips" exact="$initNewFailed"/>
          <set_value name="global.$GT_TradeCacheMK4.{$initMk4HomeSector}.{$initCi}" exact="$initEntry"/>
        </do_if>
      </do_all>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- STATION ASSIGNMENT: If home is a station, assign ship as station subordinate -->
    <!-- The lib.request.orders.xml patch protects the GT order from being overwritten -->
    <!-- The gt_subordinate_access.lua hook keeps order params editable in the UI -->
    <!-- ============================================================================= -->
    <do_if value="$assignHome and this.$effectiveHome.isclass.station">
      <!-- Home is a station â€” assign only if ship is top-level or already station-assigned.
           Ship-subordinates must remain under their ship commander. -->
      <do_if value="(not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and this.ship.commander != this.$effectiveHome">
        <!-- Unassign from old commander first (if any) -->
        <do_if value="this.ship.commander.exists and this.ship.commander != this.ship">
          <remove_object_commander object="this.ship"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Removed old commander before station assignment'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Assign to station as trade subordinate -->
        <set_object_commander object="this.ship" commander="this.$effectiveHome" assignment="assignment.trade"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Assigned to station ' + this.$effectiveHome.knownname + ' as trade subordinate'" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    <do_elseif value="this.$effectiveHome.isclass.sector">
      <!-- Home is a sector â€” unassign from any station if previously assigned -->
      <do_if value="this.ship.commander.exists and this.ship.commander.isclass.station">
        <remove_object_commander object="this.ship"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Removed station assignment â€” home changed to sector ' + this.$effectiveHome.knownname" chance="100"/>
        </do_if>
      </do_if>
    </do_elseif>
    
    <!-- ============================================================================= -->
    <!-- SUBORDINATE SETTINGS INHERITANCE: Inherit strategic settings from commander -->
    <!-- Note: excludes station commanders â€” only ship-to-ship subordinates inherit -->
    <!-- ============================================================================= -->
    <set_value name="$isSubordinate" exact="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station"/>
    <set_value name="$commanderOrder" exact="null"/>
    <do_if value="$isSubordinate">
      <set_value name="$commanderOrder" exact="this.ship.commander.defaultorder"/>
    </do_if>

    <!-- MK4 Â§3: map spec params â†’ legacy GT pipeline names (MaxSell=need/delivery radius, MaxBuy=supplier radius) -->
    <set_value name="$useMinCargoThresholdFilter" exact="if $useMinCargoThreshold? then $useMinCargoThreshold else false"/>
    <set_value name="$cargotarget" exact="if $minCargoUsed? then $minCargoUsed else 80"/>
    <set_value name="$ignorebuildstorage" exact="not $allowBuildstorage"/>
    <set_value name="$maxsell" exact="$jumpDistanceCoverage"/>
    <set_value name="$maxbuy" exact="$jumpDistanceBuy"/>
    <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
    <do_if value="not $useVanillaXPOnly">
      <set_value name="$jumpMaxPilot" exact="25"/>
      <set_value name="$psJump" exact="if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then global.$GT_Pilots.{this.ship.pilot}.$Level else null"/>
      <do_if value="$psJump != null">
        <do_if value="$psJump le 2"><set_value name="$jumpMaxPilot" exact="1"/></do_if>
        <do_elseif value="$psJump le 5"><set_value name="$jumpMaxPilot" exact="3"/></do_elseif>
        <do_elseif value="$psJump le 8"><set_value name="$jumpMaxPilot" exact="5"/></do_elseif>
        <do_elseif value="$psJump le 11"><set_value name="$jumpMaxPilot" exact="10"/></do_elseif>
        <do_elseif value="$psJump le 13"><set_value name="$jumpMaxPilot" exact="15"/></do_elseif>
        <do_else><set_value name="$jumpMaxPilot" exact="25"/></do_else>
      </do_if>
      <set_value name="$maxsell" exact="[$maxsell, $jumpMaxPilot].min"/>
      <set_value name="$maxbuy" exact="[$maxbuy, $jumpMaxPilot].min"/>
    </do_if>
    
    <!-- Sector Whitelist -->
    <set_value name="$effectiveSectorWhitelist" exact="$sectorwhitelist"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$sectorwhitelist?">
      <set_value name="$effectiveSectorWhitelist" exact="$commanderOrder.$sectorwhitelist"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting sector whitelist from commander ' + this.ship.commander.idcode" chance="100"/>
        </do_if>
    </do_if>
    
    <!-- Fleet Coordination -->
    <set_value name="$effectiveFleetCoordination" exact="$fleetcoordination"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$fleetcoordination?">
      <set_value name="$effectiveFleetCoordination" exact="$commanderOrder.$fleetcoordination"/>
    </do_if>
    
    <!-- Allow Illegal Wares -->
    <set_value name="$effectiveAllowIllegal" exact="$allowillegal"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$allowillegal?">
      <set_value name="$effectiveAllowIllegal" exact="$commanderOrder.$allowillegal"/>
    </do_if>
    
    <!-- Illegal Route Filter -->
    <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$enforceRouteIllegalLegality?">
      <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$commanderOrder.$enforceRouteIllegalLegality"/>
    </do_if>
    
    <!-- Ignore Carrier/Aux -->
    <!-- Initialize with safe default first to prevent property lookup errors -->
    <set_value name="$effectiveIgnoreCarrierAux" exact="false"/>
    <do_if value="$ignorecarrieraux?">
      <set_value name="$effectiveIgnoreCarrierAux" exact="$ignorecarrieraux"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignorecarrieraux?">
      <set_value name="$effectiveIgnoreCarrierAux" exact="$commanderOrder.$ignorecarrieraux"/>
    </do_if>
    
    <!-- Ignore Build Storage (inverse of Â§3 allowBuildstorage) -->
    <set_value name="$effectiveIgnoreBuildStorage" exact="not $allowBuildstorage"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$allowBuildstorage?">
      <set_value name="$effectiveIgnoreBuildStorage" exact="not $commanderOrder.$allowBuildstorage"/>
    </do_if>

    <!-- Ignore Trade Rules -->
    <!-- Initialize with safe default first to prevent property lookup errors -->
    <set_value name="$effectiveIgnoreTradeRules" exact="false"/>
    <do_if value="$ignoretraderules?">
      <set_value name="$effectiveIgnoreTradeRules" exact="$ignoretraderules"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoretraderules?">
      <set_value name="$effectiveIgnoreTradeRules" exact="$commanderOrder.$ignoretraderules"/>
    </do_if>
    
    <!-- Ignore MK1-Supplied Stations -->
    <set_value name="$effectiveIgnoreMK1Supply" exact="true"/>
    <do_if value="$ignoremk1supply?">
      <set_value name="$effectiveIgnoreMK1Supply" exact="$ignoremk1supply"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoremk1supply?">
      <set_value name="$effectiveIgnoreMK1Supply" exact="$commanderOrder.$ignoremk1supply"/>
    </do_if>

    <!-- Idle Parking -->
    <set_value name="$effectiveIdleParking" exact="false"/>
    <do_if value="$idleParking?">
      <set_value name="$effectiveIdleParking" exact="$idleParking"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$idleParking?">
      <set_value name="$effectiveIdleParking" exact="$commanderOrder.$idleParking"/>
    </do_if>
    
    <!-- MK4: "Prioritize Player Stations" removed.
         Keep internal value fixed to 0 for save/backward compatibility payloads. -->
    <set_value name="$effectiveFactionPriority" exact="0"/>
    
    <!-- Auto wares / manual basket (MK3 parity). Legacy orders may still expose lockWares / specialWareBasket. -->
    <set_value name="$effectiveAutoWares" exact="if $autowares? then $autowares else true"/>
    <do_if value="$lockWares?">
      <set_value name="$effectiveAutoWares" exact="not $lockWares"/>
    </do_if>
    <set_value name="$effectiveWareBasket" exact="if $warebasket? and $warebasket.count gt 0 then $warebasket else (if $specialWareBasket? then $specialWareBasket else [])"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <do_if value="$commanderOrder.$autowares?">
        <set_value name="$effectiveAutoWares" exact="$commanderOrder.$autowares"/>
      </do_if>
      <do_elseif value="$commanderOrder.$lockWares?">
        <set_value name="$effectiveAutoWares" exact="not $commanderOrder.$lockWares"/>
      </do_elseif>
      <do_if value="$commanderOrder.$warebasket? and $commanderOrder.$warebasket.count gt 0">
        <set_value name="$effectiveWareBasket" exact="$commanderOrder.$warebasket"/>
      </do_if>
      <do_elseif value="$commanderOrder.$specialWareBasket?">
        <set_value name="$effectiveWareBasket" exact="$commanderOrder.$specialWareBasket"/>
      </do_elseif>
    </do_if>
    
    <!-- Distance Penalty -->
    <set_value name="$effectiveDistancePenalty" exact="$distancepenalty"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$distancepenalty?">
      <set_value name="$effectiveDistancePenalty" exact="$commanderOrder.$distancepenalty"/>
    </do_if>
    
    <!-- Priority Wares (MK3) - wares to boost in trade scoring -->
    <set_value name="$effectivePriorityWares" exact="if $prioritywares? then $prioritywares else []"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$prioritywares?">
      <set_value name="$effectivePriorityWares" exact="$commanderOrder.$prioritywares"/>
    </do_if>
    
    <!-- Priority Score Multiplier (MK3) - applied last in scoring; 100=normal, 150=+50%%, 200=2x -->
    <set_value name="$effectivePriorityScoreMultiplier" exact="if $priorityscoremultiplier? then $priorityscoremultiplier else 125"/>
    <do_if value="$effectivePriorityScoreMultiplier lt 125"><set_value name="$effectivePriorityScoreMultiplier" exact="125"/></do_if>
    <do_if value="$effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$priorityscoremultiplier?">
      <set_value name="$effectivePriorityScoreMultiplier" exact="[$commanderOrder.$priorityscoremultiplier, 125].max"/>
      <do_if value="$effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
    </do_if>
    
    <!-- Logbook Entries -->
    <set_value name="$effectiveLogbookEntries" exact="$logbookentries"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$logbookentries?">
      <set_value name="$effectiveLogbookEntries" exact="$commanderOrder.$logbookentries"/>
    </do_if>
    
    <!-- Notifications -->
    <set_value name="$effectiveNotifications" exact="$notifications"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$notifications?">
      <set_value name="$effectiveNotifications" exact="$commanderOrder.$notifications"/>
    </do_if>

    <!-- Minimum Cargo Utilization (%) â€” Â§3 minCargoUsed -->
    <set_value name="$effectiveUseMinCargoThresholdFilter" exact="$useMinCargoThresholdFilter"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$useMinCargoThreshold?">
      <set_value name="$effectiveUseMinCargoThresholdFilter" exact="$commanderOrder.$useMinCargoThreshold"/>
    </do_if>
    <set_value name="$effectiveCargoTarget" exact="$cargotarget"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$minCargoUsed?">
      <set_value name="$effectiveCargoTarget" exact="$commanderOrder.$minCargoUsed"/>
    </do_if>
    
    <!-- Debug Level -->
    <set_value name="$effectiveDebugLevel" exact="$debuglevel"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$debuglevel?">
      <set_value name="$effectiveDebugLevel" exact="$commanderOrder.$debuglevel"/>
    </do_if>
    
    <!-- Trade Evaluation Logging -->
    <set_value name="$effectiveTradeEval" exact="$tradeeval"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$tradeeval?">
      <set_value name="$effectiveTradeEval" exact="$commanderOrder.$tradeeval"/>
    </do_if>
    
    <!-- PERFORMANCE: Calculate pilot skill once and reuse for both MaxBuy and MaxSell -->
    <!-- Calculate subordinate's pilot capability (only if subordinate) -->
    <set_value name="$pilotMaxJumps" exact="null"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <set_value name="$pilotSkill" exact="if $useVanillaXPOnly then (if this.ship.pilot? and this.ship.pilot.skill.piloting? then this.ship.pilot.skill.piloting else null) else (if this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level? then global.$GT_Pilots.{this.ship.pilot}.$Level else null)"/>
      <!-- <init> context does not allow run_script; keep local non-blocking mapping here. -->
      <do_if value="not $useVanillaXPOnly and $pilotSkill != null">
        <do_if value="$pilotSkill le 2"><set_value name="$pilotMaxJumps" exact="1"/></do_if>
        <do_elseif value="$pilotSkill le 5"><set_value name="$pilotMaxJumps" exact="3"/></do_elseif>
        <do_elseif value="$pilotSkill le 8"><set_value name="$pilotMaxJumps" exact="5"/></do_elseif>
        <do_elseif value="$pilotSkill le 11"><set_value name="$pilotMaxJumps" exact="10"/></do_elseif>
        <do_elseif value="$pilotSkill le 13"><set_value name="$pilotMaxJumps" exact="15"/></do_elseif>
        <do_else><set_value name="$pilotMaxJumps" exact="25"/></do_else>
      </do_if>
    </do_if>
    
    <!-- Jump distances: inherit commander's jumpDistanceBuy/jumpDistanceCoverage, capped at subordinate pilot -->
    <set_value name="$effectiveMaxBuy" exact="$maxbuy"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$jumpDistanceBuy?">
      <set_value name="$commanderMaxBuy" exact="$commanderOrder.$jumpDistanceBuy"/>
      <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderMaxBuy else [$commanderMaxBuy, $pilotMaxJumps].min"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': jumpDistanceBuy inherited: commander=' + $commanderMaxBuy + ', pilot_cap=' + (if $pilotMaxJumps != null then $pilotMaxJumps else 'none') + ', vanilla_mode=' + $useVanillaXPOnly + ', effective=' + $effectiveMaxBuy" chance="100"/>
      </do_if>
    </do_if>
    
    <set_value name="$effectiveMaxSell" exact="$maxsell"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$jumpDistanceCoverage?">
      <set_value name="$commanderMaxSell" exact="$commanderOrder.$jumpDistanceCoverage"/>
      <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderMaxSell else [$commanderMaxSell, $pilotMaxJumps].min"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': jumpDistanceCoverage inherited: commander=' + $commanderMaxSell + ', pilot_cap=' + (if $pilotMaxJumps != null then $pilotMaxJumps else 'none') + ', vanilla_mode=' + $useVanillaXPOnly + ', effective=' + $effectiveMaxSell" chance="100"/>
      </do_if>
    </do_if>

    <!-- MK4: fixed trade-candidate cap (internal; not player-facing) -->
    <set_value name="$effectiveSearchDepth" exact="30"/>
    <set_value name="$effectiveMaxTrades" exact="[1, [3, if $maxTrades? then $maxTrades else 3].min].max"/>
    <set_value name="$effectiveBacktrackTolerance" exact="[0, [5, if $backtrackTolerance? then $backtrackTolerance else 1].min].max"/>
    <set_value name="$mk4DedicatedServe" exact="if $serveHomeOnly? then $serveHomeOnly else (if $dedicatedServe? then $dedicatedServe else false)"/>
    <set_value name="$mk4AllowPlayerSuppliers" exact="if $buyFromPlayer? then $buyFromPlayer else (if $allowPlayerSuppliers? then $allowPlayerSuppliers else true)"/>
    <set_value name="$mk4AllowAiSuppliers" exact="if $buyFromFaction? then $buyFromFaction else (if $allowAiSuppliers? then $allowAiSuppliers else true)"/>
    <set_value name="$mk4AllowResources" exact="if $allowResources? then $allowResources else true"/>
    <set_value name="$mk4AllowIntermediates" exact="if $allowIntermediates? then $allowIntermediates else true"/>
    <set_value name="$mk4AllowTradewares" exact="if $allowTradewares? then $allowTradewares else true"/>
    <set_value name="$mk4PlayerBuyMod" exact="if $playerBuyMod? then $playerBuyMod else 0"/>
    <set_value name="$mk4BuildStorageOnlyMode" exact="false"/>
    <do_if value="not $effectiveIgnoreBuildStorage and not $mk4AllowResources and not $mk4AllowIntermediates and not $mk4AllowTradewares">
      <set_value name="$mk4BuildStorageOnlyMode" exact="true"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder">
      <do_if value="$commanderOrder.$maxTrades?">
        <set_value name="$effectiveMaxTrades" exact="[1, [3, $commanderOrder.$maxTrades].min].max"/>
      </do_if>
      <do_if value="$commanderOrder.$backtrackTolerance?">
        <set_value name="$effectiveBacktrackTolerance" exact="[0, [5, $commanderOrder.$backtrackTolerance].min].max"/>
      </do_if>
      <do_if value="$commanderOrder.$serveHomeOnly?">
        <set_value name="$mk4DedicatedServe" exact="$commanderOrder.$serveHomeOnly"/>
      </do_if>
      <do_elseif value="$commanderOrder.$dedicatedServe?">
        <set_value name="$mk4DedicatedServe" exact="$commanderOrder.$dedicatedServe"/>
      </do_elseif>
      <do_if value="$commanderOrder.$buyFromPlayer?">
        <set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$buyFromPlayer"/>
      </do_if>
      <do_elseif value="$commanderOrder.$allowPlayerSuppliers?">
        <set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$allowPlayerSuppliers"/>
      </do_elseif>
      <do_if value="$commanderOrder.$buyFromFaction?">
        <set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$buyFromFaction"/>
      </do_if>
      <do_elseif value="$commanderOrder.$allowAiSuppliers?">
        <set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$allowAiSuppliers"/>
      </do_elseif>
      <do_if value="$commanderOrder.$allowResources?">
        <set_value name="$mk4AllowResources" exact="$commanderOrder.$allowResources"/>
      </do_if>
      <do_if value="$commanderOrder.$allowIntermediates?">
        <set_value name="$mk4AllowIntermediates" exact="$commanderOrder.$allowIntermediates"/>
      </do_if>
      <do_if value="$commanderOrder.$allowTradewares?">
        <set_value name="$mk4AllowTradewares" exact="$commanderOrder.$allowTradewares"/>
      </do_if>
      <do_if value="$commanderOrder.$playerBuyMod?">
        <set_value name="$mk4PlayerBuyMod" exact="$commanderOrder.$playerBuyMod"/>
      </do_if>
    </do_if>

    <!-- Persist effective settings on the order instance so they survive save/load resume -->
    <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
    <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
    <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
    <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
    <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
    <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
    <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
    <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
    <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
    <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
    <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
    <set_value name="this.$effectiveUseMinCargoThresholdFilter" exact="$effectiveUseMinCargoThresholdFilter"/>
    <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
    <set_value name="this.$effectivePriorityWares" exact="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
    <set_value name="this.$effectivePriorityScoreMultiplier" exact="$effectivePriorityScoreMultiplier"/>
    <set_value name="this.$effectiveSearchDepth" exact="$effectiveSearchDepth"/>
    <set_value name="this.$effectiveIdleParking" exact="$effectiveIdleParking"/>
    <set_value name="this.$effectiveMaxTrades" exact="$effectiveMaxTrades"/>
    <set_value name="this.$effectiveBacktrackTolerance" exact="$effectiveBacktrackTolerance"/>
    <set_value name="this.$mk4DedicatedServe" exact="$mk4DedicatedServe"/>
    <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4AllowPlayerSuppliers"/>
    <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4AllowAiSuppliers"/>
    <set_value name="this.$mk4AllowResources" exact="$mk4AllowResources"/>
    <set_value name="this.$mk4AllowIntermediates" exact="$mk4AllowIntermediates"/>
    <set_value name="this.$mk4AllowTradewares" exact="$mk4AllowTradewares"/>
    <set_value name="this.$mk4PlayerBuyMod" exact="$mk4PlayerBuyMod"/>
    <set_value name="this.$mk4BuildStorageOnlyMode" exact="$mk4BuildStorageOnlyMode"/>
    
    <!-- Debug message for subordinates showing inherited settings -->
    <!-- PERFORMANCE: Only build inherited settings string if debug logging is enabled -->
    <!-- Skip expensive string concatenation loop if not needed -->
    <do_if value="$isSubordinate and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$inheritedSettings" exact="[]"/>
      <do_if value="$effectiveFleetCoordination != $fleetcoordination"><append_to_list name="$inheritedSettings" exact="'FleetCoord=' + $effectiveFleetCoordination"/></do_if>
      <do_if value="$effectiveAllowIllegal != $allowillegal"><append_to_list name="$inheritedSettings" exact="'AllowIllegal=' + $effectiveAllowIllegal"/></do_if>
      <do_if value="$effectiveEnforceRouteIllegalLegality != $enforceRouteIllegalLegality"><append_to_list name="$inheritedSettings" exact="'IllegalRouteFilter=' + $effectiveEnforceRouteIllegalLegality"/></do_if>
      <do_if value="$effectiveAutoWares != (if $autowares? then $autowares else true)"><append_to_list name="$inheritedSettings" exact="'AutoWares=' + $effectiveAutoWares"/></do_if>
      <do_if value="$effectiveDistancePenalty != $distancepenalty"><append_to_list name="$inheritedSettings" exact="'DistPenalty=' + $effectiveDistancePenalty + '%'"/></do_if>
      <do_if value="$effectiveLogbookEntries != $logbookentries"><append_to_list name="$inheritedSettings" exact="'Logbook=' + $effectiveLogbookEntries"/></do_if>
      <do_if value="$effectiveNotifications != $notifications"><append_to_list name="$inheritedSettings" exact="'Notify=' + $effectiveNotifications"/></do_if>
      <do_if value="$effectiveUseMinCargoThresholdFilter != $useMinCargoThresholdFilter"><append_to_list name="$inheritedSettings" exact="'UseMinCargo=' + $effectiveUseMinCargoThresholdFilter"/></do_if>
      <do_if value="$effectiveCargoTarget != $cargotarget"><append_to_list name="$inheritedSettings" exact="'MinCargoUtil=' + $effectiveCargoTarget + '%'"/></do_if>
      <do_if value="$effectiveDebugLevel != $debuglevel"><append_to_list name="$inheritedSettings" exact="'Debug=' + $effectiveDebugLevel"/></do_if>
      <do_if value="$effectiveTradeEval != $tradeeval"><append_to_list name="$inheritedSettings" exact="'TradeEval=' + $effectiveTradeEval"/></do_if>
      <do_if value="$effectiveMaxBuy != $jumpDistanceBuy"><append_to_list name="$inheritedSettings" exact="'JumpBuy=' + $effectiveMaxBuy + 'j'"/></do_if>
      <do_if value="$effectiveMaxSell != $jumpDistanceCoverage"><append_to_list name="$inheritedSettings" exact="'JumpCov=' + $effectiveMaxSell + 'j'"/></do_if>
      
      <do_if value="$inheritedSettings.count gt 0">
        <set_value name="$inheritedSettingsText" exact="''"/>
        <do_all exact="$inheritedSettings.count" counter="$i">
          <set_value name="$inheritedSettingsText" exact="$inheritedSettingsText + $inheritedSettings.{$i}"/>
          <do_if value="$i lt $inheritedSettings.count">
            <set_value name="$inheritedSettingsText" exact="$inheritedSettingsText + ', '"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inherited settings from ' + this.ship.commander.idcode + ': ' + $inheritedSettingsText" chance="100"/>
      </do_if>
    </do_if>
    
    <set_value name="$orderParams.$home" exact="$effectiveHome"/>
    <set_value name="$orderParams.$maxbuy" exact="$effectiveMaxBuy"/>
    <set_value name="$orderParams.$maxsell" exact="$effectiveMaxSell"/>
    <set_value name="$orderParams.$allowillegal" exact="$effectiveAllowIllegal"/>
    <set_value name="$orderParams.$enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="$orderParams.$factionpriority" exact="0"/>
    <set_value name="$orderParams.$autowares" exact="$effectiveAutoWares"/>
    <set_value name="$orderParams.$warebasket" exact="$effectiveWareBasket"/>
    <set_value name="$orderParams.$prioritywares" exact="$effectivePriorityWares"/>
    <set_value name="$orderParams.$priorityscoremultiplier" exact="$effectivePriorityScoreMultiplier"/>
    <set_value name="$orderParams.$distancepenalty" exact="$effectiveDistancePenalty"/>
    <set_value name="$orderParams.$notifications" exact="$effectiveNotifications"/>
    <set_value name="$orderParams.$useMinCargoThreshold" exact="$effectiveUseMinCargoThresholdFilter"/>
    <set_value name="$orderParams.$cargotarget" exact="$effectiveCargoTarget"/>
    <set_value name="$orderParams.$marketupdatefreq" exact="$marketupdatefreq"/>
    <set_value name="$orderParams.$debuglevel" exact="$effectiveDebugLevel"/>
    <set_value name="$orderParams.$tradeeval" exact="$effectiveTradeEval"/>
    <set_value name="$orderParams.$fleetcoordination" exact="$effectiveFleetCoordination"/>
    <set_value name="$orderParams.$logbookentries" exact="$effectiveLogbookEntries"/>
    <set_value name="$orderParams.$sectorwhitelist" exact="$effectiveSectorWhitelist"/>
    
    <!-- =========================================== -->
    <!-- HIGH-PERFORMANCE INITIALIZATION (Option A) -->
    <!-- =========================================== -->
    
    <!-- Fast variable assignment - using effective (inherited) values -->
    <set_value name="$gt_debuglevel" exact="$effectiveDebugLevel"/>
    <!-- Only set debugchance > 0 if GT debug logging is enabled globally -->
    <set_value name="$debugchance" exact="0"/>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$debugchance" exact="if $gt_debuglevel ge 2 then 100 else if $gt_debuglevel ge 1 then 50 else 0"/>
    </do_if>
    <set_value name="this.$debugchance" exact="$debugchance"/>
    
    <!-- Cache blacklistgroup once (avoids 6 repeated lookups) -->
    <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
    <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
      <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
    </do_if>
    
    <!-- Core trading parameters (performance optimized) - using effective (inherited) values -->
    <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
    <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="$gt_factionpriority" exact="0"/>
    <!-- Convert distance penalty from 0-100% to multiplier: 0%=0.0, 50%=1.0, 100%=2.0 -->
    <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
    <set_value name="$gt_useMinCargoThreshold" exact="$effectiveUseMinCargoThresholdFilter"/>
    <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
    <set_value name="$gt_marketupdatefreq" exact="$marketupdatefreq"/>
    <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
    
    <!-- Global defaults (fastest approach - direct assignment) -->
    <set_value name="$gt_autotraining" exact="true"/>
    <set_value name="$gt_fleetcoord" exact="false"/>
    
    <!-- Ware selection (optimized) - using effective inherited values -->
    <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>
    
    <!-- Single non-blocking signal to MD system -->
    <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
      $Ship = this.ship,
      $Config = table[
        $allowillegal = $gt_allowillegal,
        $debuglevel = $gt_debuglevel,
        $autotraining = $gt_autotraining
      ]
    ]"/>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': High-performance initialization complete'" chance="@this.$debugchance"/>
      <do_if value="@$effectiveHome.exists">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Operating with home base: ' + @$effectiveHome.knownname + ' (maxbuy=' + $effectiveMaxBuy + ', maxsell=' + $effectiveMaxSell + ')'" chance="@this.$debugchance"/>
      </do_if>
    </do_if>
    
    <!-- Log configuration summary -->
    <do_if value="$gt_debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === CONFIGURATION SUMMARY ==='" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Illegal=' + $effectiveAllowIllegal + ', IllegalRouteFilter=' + $effectiveEnforceRouteIllegalLegality + ', DistancePenalty=' + $effectiveDistancePenalty + '%'" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FleetCoord=' + $effectiveFleetCoordination + ', LogbookEntries=' + $effectiveLogbookEntries + ', Notifications=' + $effectiveNotifications" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Distance limits: MaxBuy=' + $effectiveMaxBuy + ' jumps, MaxSell=' + $effectiveMaxSell + ' jumps'" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': AutoWares=' + $effectiveAutoWares + ', WareBasket=' + $effectiveWareBasket.count + ' wares, TradeEval=' + $effectiveTradeEval" chance="100"/>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- END MODULAR INITIALIZATION                                                   -->
    <!-- ============================================================================= -->
    
    <!-- Initialize pilot tracking for event-driven pilot change detection -->
    <!-- Pilot changes are detected at natural restart points: -->
    <!-- - After successful trade completion (trade_completed label) -->
    <!-- - On script restart (init label) -->
    <set_value name="this.$trackedPilot" exact="this.ship.pilot"/>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Tracking pilot: ' + @this.$trackedPilot.name + ' (event-driven detection enabled)'" chance="@this.$debugchance"/>
    </do_if>
    
    <!-- Do not initialize commander tracking here - let init label handle it -->
    <!-- This prevents false positives when script restarts after commander assignment -->
    <!-- The init label will detect changes by comparing with previous value -->
    
    <!-- Register pilot on first run (for initial assignment or ship with existing cargo) -->
    <!-- This ensures ships get renamed even when first assigned to GT order -->
    <do_if value="this.ship.pilot">
      <!-- NOTE: Cannot use wait/do_while in init block - pilot transfer check moved to main loop -->
      <!-- Pilot transfer takes time (crew transfer pod travel), but UI shows pilot as assigned immediately -->
      <!-- Main loop will check if pilot is actually on ship before proceeding -->
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INITIAL REGISTRATION: Registering pilot ' + @this.ship.pilot.name + ' on order start'" chance="100"/>
      </do_if>
      <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
        $updateType = 'pilot_change',
        $Ship = this.ship,
        $pilot = this.ship.pilot,
        $oldPilot = null
      ]"/>
      
      <!-- NOTE: Cannot use wait in init block - registration check will happen in main loop -->
      <!-- Registration happens synchronously via run_actions, but signal processing is asynchronous -->
      <!-- Main loop will check registration status before requesting trade search -->
    </do_if>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GalaxyTrader MK3] ' + this.ship.idcode + ': === INITIALIZATION COMPLETE === Starting main trading loop...'" chance="100"/>
    </do_if>
    
  </init>

  <patch sinceversion="4">
    <do_if value="not $idleParking?">
      <set_value name="$idleParking" exact="false"/>
    </do_if>
    <set_value name="this.$effectiveIdleParking" exact="$idleParking"/>
    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': v3->v4 patch applied (idleParking=' + this.$effectiveIdleParking + ')'" filter="savegame"/>
  </patch>
  <patch sinceversion="5">
    <do_if value="not $autoJumpDistanceByLevel?">
      <set_value name="$autoJumpDistanceByLevel" exact="false"/>
    </do_if>
    <set_value name="this.$prevAutoJumpDistance" exact="$autoJumpDistanceByLevel"/>
    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': v4->v5 patch applied (autoJumpDistanceByLevel=' + $autoJumpDistanceByLevel + ')'" filter="savegame"/>
  </patch>
  
  <attention min="unknown">
    <actions>
      
      <!-- Debug: Confirm we entered attention block -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === ATTENTION BLOCK ENTERED ==='" chance="100"/>
      </do_if>
      
      <!-- Subordinate reinitialization: Jump here to restart and re-inherit commander settings -->
      <label name="init"/>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <!-- CRITICAL: Ensure instance wait time storage ALWAYS exists on restarts/resumes. -->
      <!-- Purpose A: Pre-request wait for GT_Trade_Found signal (milliseconds) -->
      <set_value name="this.$tradeFoundSignalWaitTime" exact="5ms"/>
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <set_value name="this.$retryCooldown" exact="10s"/>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (Script Restart) -->
      <!-- ======================================= -->
      <!-- Check for pilot changes when script restarts (natural restart point) -->
      <set_value name="$currentPilot" exact="@this.ship.pilot"/>
      <do_if value="this.$trackedPilot? and $currentPilot != this.$trackedPilot">
        <!-- Pilot changed! Send signal to MD system -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PILOT CHANGE DETECTED on script restart! Old: ' + @this.$trackedPilot.name + ', New: ' + @$currentPilot.name" chance="100"/>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
          $updateType = 'pilot_change',
          $Ship = this.ship,
          $pilot = $currentPilot,
          $oldPilot = this.$trackedPilot
        ]"/>
      </do_if>
      <!-- Update tracked pilot (always, even if no change) -->
      <set_value name="this.$trackedPilot" exact="$currentPilot"/>
      
      <!-- CRITICAL: Check if pilot is missing (pilot was transferred away) -->
      <!-- If GT order is running but ship has no pilot, cleanup and self-cancel -->
      <do_if value="not $currentPilot">
        <!-- Vanilla transfer pods can take minutes; if a paused GT pilot is already linked to this
             ship id, keep the GT order alive briefly until the pilot physically arrives. -->
        <set_value name="$pendingTransferredPilot" exact="false"/>
        <set_value name="$pendingPilotName" exact="'NONE'"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$pk">
            <set_value name="$candidatePilot" exact="$pilotKeys.{$pk}"/>
            <do_if value="$candidatePilot and global.$GT_Pilots.{$candidatePilot}? and global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == this.ship.idcode and global.$GT_Pilots.{$candidatePilot}.$Status? and global.$GT_Pilots.{$candidatePilot}.$Status == 'paused'">
              <set_value name="$pendingTransferredPilot" exact="true"/>
              <set_value name="$pendingPilotName" exact="if $candidatePilot.name? then $candidatePilot.name else 'UNKNOWN'"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$pendingTransferredPilot">
          <do_if value="not this.$pendingPilotTransferSince?">
            <set_value name="this.$pendingPilotTransferSince" exact="player.age"/>
          </do_if>
          <set_value name="$pendingTransferElapsed" exact="player.age - this.$pendingPilotTransferSince"/>
          
          <do_if value="$pendingTransferElapsed lt 15min">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Missing pilot but transfer is in progress for ' + $pendingPilotName + ' (elapsed=' + ($pendingTransferElapsed / 1s) + 's) - waiting before cancellation'" chance="100"/>
            </do_if>
            <wait exact="5s"/>
            <return/>
          </do_if>
        </do_if>
        
        <remove_value name="this.$pendingPilotTransferSince"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MISSING PILOT DETECTED - pilot was transferred away, cleaning up and self-canceling GT order'" chance="100"/>
        </do_if>
        
        <!-- Get original ship name from ship registry -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{this.ship}.$OriginalShipName"/>
        </do_if>
        
        <!-- Send cleanup signal (name restoration handled by MD system) -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = null,
          $Reason = 'Pilot transferred away - GT order cannot run without pilot',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Cancel all active orders (trade orders, etc.) -->
        <cancel_all_orders object="this.ship"/>
        
        <!-- Self-cancel GT order -->
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Restore XPBlocked if BlockedLevel still exists (ship restart/reinit) -->
      <!-- Also update ship name to show ADVANCE label when XPBlocked is restored -->
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <set_value name="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] Restored XPBlocked for pilot ' + this.ship.pilot.name + ' on ship restart (BlockedLevel: ' + global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel + ')'" chance="100"/>
          </do_if>
          
          <!-- Update ship name to show ADVANCE label when XPBlocked is restored -->
          <!-- This ensures the ship name reflects the blocked state after restart -->
          <!-- Calculate rank title based on blocked level -->
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          <set_value name="$rankTitle" exact="'Lehrling'"/>
          <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
            <set_value name="$rankIndex" exact="($blockedLevel / 3)i + 1"/>
            <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
              <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
            </do_if>
            <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
              <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
            </do_if>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
            $Ship = this.ship,
            $pilot = this.ship.pilot,
            $xp = @global.$GT_Pilots.{this.ship.pilot}.$XP,
            $level = $blockedLevel,
            $rank = $rankTitle,
            $nameType = 'blocked'
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] Updated ship name to show ADVANCE label after XPBlocked restoration: ' + this.ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Initialize default order tracking -->
      <!-- Track the current default order to detect when GT order is removed -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="not this.$trackedDefaultOrder?">
        <!-- First time - initialize tracked order -->
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
        
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply'">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] GT order assigned to ' + this.ship.idcode + ' - sending GT_Order_Assigned signal'" chance="100"/>
          </do_if>
          <run_script name="'lib.gt.attention.emit_gt_state_changed'">
            <param name="ship" value="this.ship"/>
            <param name="isGTActive" value="true"/>
            <param name="source" value="'AI_INIT_ASSIGN'"/>
          </run_script>
        </do_if>
      </do_if>
      <do_elseif value="this.$trackedDefaultOrder != 'GalaxyTraderMK3' and this.$trackedDefaultOrder != 'GalaxyTraderMK4Supply' and ($currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply')">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] GT order reassigned to ' + this.ship.idcode + ' (old: ' + this.$trackedDefaultOrder + ', new: ' + $currentDefaultOrder + ') - sending GT_Order_Assigned signal'" chance="100"/>
        </do_if>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="true"/>
          <param name="source" value="'AI_INIT_REASSIGN'"/>
        </run_script>
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_elseif>
      <do_if value="(this.$trackedDefaultOrder == 'GalaxyTraderMK3' or this.$trackedDefaultOrder == 'GalaxyTraderMK4Supply') and ($currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply')">
        <!-- CRITICAL FIX: Check if ship is still GT-controlled via commander BEFORE sending cancellation -->
        <!-- When a subordinate is assigned to a commander, default order changes from GalaxyTraderMK4Supply to Assist -->
        <!-- But ship is still GT-controlled via commander - don't send cancellation signal -->
        <set_value name="$isStillGTControlled" exact="false"/>
        
        <!-- Check 1: Direct GT order -->
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply'">
          <set_value name="$isStillGTControlled" exact="true"/>
        </do_if>
        
        <!-- Check 2: Subordinate to GT commander with Assist order -->
        <do_if value="not $isStillGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <do_if value="$currentDefaultOrder == 'Assist'">
              <set_value name="$isStillGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <do_if value="not $isStillGTControlled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in init label, old: ' + this.$trackedDefaultOrder + ', new: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isStillGTControlled + ')'" chance="100"/>
          </do_if>
          <run_script name="'lib.gt.attention.emit_gt_state_changed'">
            <param name="ship" value="this.ship"/>
            <param name="isGTActive" value="false"/>
            <param name="source" value="'AI_INIT_CANCEL'"/>
          </run_script>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: Default order changed from GalaxyTraderMK3 to ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ' BUT ship still GT-controlled via commander - NOT sending cancellation'" chance="100"/>
          </do_if>
        </do_else>
        
        <run_script name="'lib.gt.attention.restore_original_name'">
          <param name="ship" value="this.ship"/>
          <param name="reason" value="'GT order cancelled - restoring original name'"/>
          <param name="skipIfStillGT" value="true"/>
          <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply']"/>
        </run_script>
        
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_elseif value="this.$trackedDefaultOrder != $currentDefaultOrder">
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_elseif>
      
      <!-- Initialize commander tracking and detect commander assignment -->
      <!-- This runs when script restarts (e.g., after commander assignment) -->
      <!-- Check for changes BEFORE initializing trackedCommander -->
      <set_value name="$currentCommander" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$currentCommander" exact="this.ship.commander"/>
      </do_if>
      
      <!-- Store previous tracked commander BEFORE checking/updating -->
      <set_value name="$previousTrackedCommander" exact="null"/>
      <do_if value="this.$trackedCommander?">
        <set_value name="$previousTrackedCommander" exact="this.$trackedCommander"/>
      </do_if>
      
      <!-- Log current state -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] PHASE 6 DEBUG: ' + this.ship.idcode + ' - currentCommander: ' + (if @$currentCommander.exists then @$currentCommander.idcode else 'NONE') + ', previousTrackedCommander: ' + (if @$previousTrackedCommander.exists then @$previousTrackedCommander.idcode else 'NONE')" chance="100"/>
      </do_if>
      
      <!-- Check if commander changed (compare with previous tracked value BEFORE updating) -->
      <do_if value="not this.$trackedCommander?">
        <!-- First time - initialize tracked commander and send signal if commander exists -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
        <do_if value="@$currentCommander.exists">
          <!-- Commander exists on first check - send initialization signal -->
          <set_value name="$newCommanderHasGT" exact="false"/>
          <do_if value="$currentCommander.defaultorder? and ((@$currentCommander.defaultorder.id == 'GalaxyTraderMK3' or @$currentCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$currentCommander.defaultorder.id == 'Assist' and $currentCommander.defaultorder.$baseorder? and (@$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'Commander_Changed',
            $Commander = $currentCommander,
            $CommanderHasGT = $newCommanderHasGT
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 6: Commander initialized for ' + this.ship.idcode + ' (commander: ' + $currentCommander.idcode + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="((@$previousTrackedCommander.exists == true) and not (@$currentCommander.exists == true)) or (not (@$previousTrackedCommander.exists == true) and (@$currentCommander.exists == true))">
        <!-- Commander state changed (was null, now exists OR was exists, now null) -->
        <set_value name="$oldCommander" exact="$previousTrackedCommander"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if old commander had GT order (for name restoration when subordinate removed) -->
        <set_value name="$oldCommanderHasGT" exact="false"/>
        <do_if value="@$oldCommander.exists">
          <do_if value="$oldCommander.defaultorder? and ((@$oldCommander.defaultorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$oldCommander.defaultorder.id == 'Assist' and $oldCommander.defaultorder.$baseorder? and (@$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$oldCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + (if @$oldCommander.exists then @$oldCommander.idcode else 'NONE') + ', new: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <do_if value="$oldCommanderHasGT and not $newCommanderHasGT and this.ship.pilot?">
          <run_script name="'lib.gt.attention.restore_original_name'">
            <param name="ship" value="this.ship"/>
            <param name="reason" value="'Subordinate removed from GT commander - restoring original name'"/>
            <param name="skipIfStillGT" value="true"/>
            <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply']"/>
          </run_script>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      <do_elseif value="(@$previousTrackedCommander.exists == true) and (@$currentCommander.exists == true) and $previousTrackedCommander != $currentCommander">
        <!-- Commander changed to different commander -->
        <set_value name="$oldCommander" exact="$previousTrackedCommander"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
          <set_value name="$newCommanderHasGT" exact="true"/>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + $oldCommander.idcode + ', new: ' + $newCommander.idcode + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      <do_else>
        <!-- Commander is the same - no change, but ensure tracked value is updated -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_else>
      
      <!-- Re-inherit settings only for ship-subordinates.
           Station commanders must not override MK4 station-home scope. -->
      <do_if value="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
        <set_value name="$commanderOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$commanderOrder?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Re-inheriting settings from commander ' + this.ship.commander.idcode" chance="100"/>
          </do_if>
          <!-- Re-inherit all commander settings -->
          <do_if value="$commanderOrder.$fleetcoordination?"><set_value name="$effectiveFleetCoordination" exact="$commanderOrder.$fleetcoordination"/></do_if>
          <do_if value="$commanderOrder.$allowillegal?"><set_value name="$effectiveAllowIllegal" exact="$commanderOrder.$allowillegal"/></do_if>
          <do_if value="$commanderOrder.$enforceRouteIllegalLegality?"><set_value name="$effectiveEnforceRouteIllegalLegality" exact="$commanderOrder.$enforceRouteIllegalLegality"/></do_if>
          <do_if value="$commanderOrder.$ignorecarrieraux?"><set_value name="$effectiveIgnoreCarrierAux" exact="$commanderOrder.$ignorecarrieraux"/></do_if>
          <do_if value="$commanderOrder.$allowBuildstorage?"><set_value name="$effectiveIgnoreBuildStorage" exact="not $commanderOrder.$allowBuildstorage"/></do_if>
          <do_if value="$commanderOrder.$ignoretraderules?"><set_value name="$effectiveIgnoreTradeRules" exact="$commanderOrder.$ignoretraderules"/></do_if>
          <do_if value="$commanderOrder.$ignoremk1supply?"><set_value name="$effectiveIgnoreMK1Supply" exact="$commanderOrder.$ignoremk1supply"/></do_if>
          <do_if value="$commanderOrder.$home?"><set_value name="$effectiveHome" exact="$commanderOrder.$home"/></do_if>
          <do_if value="$commanderOrder.$sectorwhitelist?"><set_value name="$effectiveSectorWhitelist" exact="$commanderOrder.$sectorwhitelist"/></do_if>
          <!-- Ware filter (MK3 parity; legacy lockWares / specialWareBasket) -->
          <do_if value="$commanderOrder.$autowares?"><set_value name="$effectiveAutoWares" exact="$commanderOrder.$autowares"/></do_if>
          <do_elseif value="$commanderOrder.$lockWares?"><set_value name="$effectiveAutoWares" exact="not $commanderOrder.$lockWares"/></do_elseif>
          <do_if value="$commanderOrder.$warebasket? and $commanderOrder.$warebasket.count gt 0"><set_value name="$effectiveWareBasket" exact="$commanderOrder.$warebasket"/></do_if>
          <do_elseif value="$commanderOrder.$specialWareBasket?"><set_value name="$effectiveWareBasket" exact="$commanderOrder.$specialWareBasket"/></do_elseif>
          <do_if value="$commanderOrder.$prioritywares?"><set_value name="$effectivePriorityWares" exact="$commanderOrder.$prioritywares"/></do_if>
          <do_if value="$commanderOrder.$priorityscoremultiplier?"><set_value name="$effectivePriorityScoreMultiplier" exact="[$commanderOrder.$priorityscoremultiplier, 125].max"/></do_if>
          <do_if value="$effectivePriorityScoreMultiplier? and $effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
          <do_if value="$commanderOrder.$distancepenalty?"><set_value name="$effectiveDistancePenalty" exact="$commanderOrder.$distancepenalty"/></do_if>
          <do_if value="$commanderOrder.$logbookentries?"><set_value name="$effectiveLogbookEntries" exact="$commanderOrder.$logbookentries"/></do_if>
          <do_if value="$commanderOrder.$notifications?"><set_value name="$effectiveNotifications" exact="$commanderOrder.$notifications"/></do_if>
          <do_if value="$commanderOrder.$useMinCargoThreshold?"><set_value name="$effectiveUseMinCargoThresholdFilter" exact="$commanderOrder.$useMinCargoThreshold"/></do_if>
          <do_if value="$commanderOrder.$minCargoUsed?"><set_value name="$effectiveCargoTarget" exact="$commanderOrder.$minCargoUsed"/></do_if>
          <do_if value="$commanderOrder.$maxTrades?"><set_value name="$effectiveMaxTrades" exact="[1, [3, $commanderOrder.$maxTrades].min].max"/></do_if>
          <do_if value="$commanderOrder.$backtrackTolerance?"><set_value name="$effectiveBacktrackTolerance" exact="[0, [5, $commanderOrder.$backtrackTolerance].min].max"/></do_if>
          <do_if value="$commanderOrder.$serveHomeOnly?"><set_value name="$mk4DedicatedServe" exact="$commanderOrder.$serveHomeOnly"/></do_if>
          <do_elseif value="$commanderOrder.$dedicatedServe?"><set_value name="$mk4DedicatedServe" exact="$commanderOrder.$dedicatedServe"/></do_elseif>
          <do_if value="$commanderOrder.$buyFromPlayer?"><set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$buyFromPlayer"/></do_if>
          <do_elseif value="$commanderOrder.$allowPlayerSuppliers?"><set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$allowPlayerSuppliers"/></do_elseif>
          <do_if value="$commanderOrder.$buyFromFaction?"><set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$buyFromFaction"/></do_if>
          <do_elseif value="$commanderOrder.$allowAiSuppliers?"><set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$allowAiSuppliers"/></do_elseif>
          <do_if value="$commanderOrder.$allowResources?"><set_value name="$mk4AllowResources" exact="$commanderOrder.$allowResources"/></do_if>
          <do_if value="$commanderOrder.$allowIntermediates?"><set_value name="$mk4AllowIntermediates" exact="$commanderOrder.$allowIntermediates"/></do_if>
          <do_if value="$commanderOrder.$allowTradewares?"><set_value name="$mk4AllowTradewares" exact="$commanderOrder.$allowTradewares"/></do_if>
          <do_if value="$commanderOrder.$playerBuyMod?"><set_value name="$mk4PlayerBuyMod" exact="$commanderOrder.$playerBuyMod"/></do_if>
          <do_if value="$commanderOrder.$debuglevel?"><set_value name="$effectiveDebugLevel" exact="$commanderOrder.$debuglevel"/></do_if>
          <do_if value="$commanderOrder.$tradeeval?"><set_value name="$effectiveTradeEval" exact="$commanderOrder.$tradeeval"/></do_if>
          <!-- Re-inherit max jump distances with pilot capability cap -->
          <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
          <run_script name="'lib.gt.pathfinding'" result="$pilotSkill">
            <param name="mode" value="'effective_pilot_level'"/>
            <param name="ship" value="this.ship"/>
            <param name="includeCommander" value="false"/>
          </run_script>
          <set_value name="$pilotMaxJumps" exact="null"/>
          <do_if value="not $useVanillaXPOnly">
            <run_script name="'lib.gt.pathfinding'" result="$pilotMaxJumps">
              <param name="mode" value="'pilot_max_jumps'"/>
              <param name="pilotSkill" value="$pilotSkill"/>
            </run_script>
          </do_if>
          <do_if value="$commanderOrder.$jumpDistanceBuy?">
            <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderOrder.$jumpDistanceBuy else [$commanderOrder.$jumpDistanceBuy, $pilotMaxJumps].min"/>
          </do_if>
          <do_if value="$commanderOrder.$jumpDistanceCoverage?">
            <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderOrder.$jumpDistanceCoverage else [$commanderOrder.$jumpDistanceCoverage, $pilotMaxJumps].min"/>
          </do_if>
          <!-- Refresh derived variables used by the trading loop / MD requests -->
          <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
          <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
          <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
          <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
          <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Settings re-inherited successfully'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Rehydrate missing local effective vars before persisting.
           AI local $vars can be missing on some resume paths. -->
      <do_if value="not $effectiveMaxBuy?">
        <set_value name="$effectiveMaxBuy" exact="if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else $jumpDistanceBuy"/>
      </do_if>
      <do_if value="not $effectiveMaxSell?">
        <set_value name="$effectiveMaxSell" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else $jumpDistanceCoverage"/>
      </do_if>
      <do_if value="not $effectiveSearchDepth?">
        <set_value name="$effectiveSearchDepth" exact="if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30"/>
      </do_if>
      <do_if value="not $effectiveMaxTrades?">
        <set_value name="$effectiveMaxTrades" exact="if this.$effectiveMaxTrades? then this.$effectiveMaxTrades else [1, [3, if $maxTrades? then $maxTrades else 3].min].max"/>
      </do_if>
      <do_if value="not $effectiveBacktrackTolerance?">
        <set_value name="$effectiveBacktrackTolerance" exact="if this.$effectiveBacktrackTolerance? then this.$effectiveBacktrackTolerance else [0, [5, if $backtrackTolerance? then $backtrackTolerance else 1].min].max"/>
      </do_if>
      <do_if value="not $mk4DedicatedServe?">
        <set_value name="$mk4DedicatedServe" exact="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else (if $serveHomeOnly? then $serveHomeOnly else (if $dedicatedServe? then $dedicatedServe else false))"/>
      </do_if>
      <do_if value="not $mk4AllowPlayerSuppliers?">
        <set_value name="$mk4AllowPlayerSuppliers" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else (if $buyFromPlayer? then $buyFromPlayer else (if $allowPlayerSuppliers? then $allowPlayerSuppliers else true))"/>
      </do_if>
      <do_if value="not $mk4AllowAiSuppliers?">
        <set_value name="$mk4AllowAiSuppliers" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else (if $buyFromFaction? then $buyFromFaction else (if $allowAiSuppliers? then $allowAiSuppliers else true))"/>
      </do_if>
      <do_if value="not $mk4AllowResources?">
        <set_value name="$mk4AllowResources" exact="if this.$mk4AllowResources? then this.$mk4AllowResources else (if $allowResources? then $allowResources else true)"/>
      </do_if>
      <do_if value="not $mk4AllowIntermediates?">
        <set_value name="$mk4AllowIntermediates" exact="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else (if $allowIntermediates? then $allowIntermediates else true)"/>
      </do_if>
      <do_if value="not $mk4AllowTradewares?">
        <set_value name="$mk4AllowTradewares" exact="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else (if $allowTradewares? then $allowTradewares else true)"/>
      </do_if>
      <do_if value="not $mk4PlayerBuyMod?">
        <set_value name="$mk4PlayerBuyMod" exact="if this.$mk4PlayerBuyMod? then this.$mk4PlayerBuyMod else (if $playerBuyMod? then $playerBuyMod else 0)"/>
      </do_if>
      <do_if value="not $effectiveIgnoreBuildStorage?">
        <set_value name="$effectiveIgnoreBuildStorage" exact="if this.$effectiveIgnoreBuildStorage? then this.$effectiveIgnoreBuildStorage else false"/>
      </do_if>
      <set_value name="$mk4BuildStorageOnlyMode" exact="false"/>
      <do_if value="not $effectiveIgnoreBuildStorage and not $mk4AllowResources and not $mk4AllowIntermediates and not $mk4AllowTradewares">
        <set_value name="$mk4BuildStorageOnlyMode" exact="true"/>
      </do_if>
      <do_if value="not $effectiveIgnoreTradeRules?">
        <set_value name="$effectiveIgnoreTradeRules" exact="if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false"/>
      </do_if>
      <do_if value="not $effectiveIgnoreMK1Supply?">
        <set_value name="$effectiveIgnoreMK1Supply" exact="if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true"/>
      </do_if>
      <do_if value="not $effectiveIgnoreCarrierAux?">
        <set_value name="$effectiveIgnoreCarrierAux" exact="if this.$effectiveIgnoreCarrierAux? then this.$effectiveIgnoreCarrierAux else false"/>
      </do_if>
      <do_if value="not $effectiveIgnoreBuildStorage?">
        <set_value name="$effectiveIgnoreBuildStorage" exact="if this.$effectiveIgnoreBuildStorage? then this.$effectiveIgnoreBuildStorage else false"/>
      </do_if>
      <do_if value="not $effectiveDistancePenalty?">
        <set_value name="$effectiveDistancePenalty" exact="if this.$effectiveDistancePenalty? then this.$effectiveDistancePenalty else $distancepenalty"/>
      </do_if>
      <do_if value="not $effectiveFleetCoordination?">
        <set_value name="$effectiveFleetCoordination" exact="if this.$effectiveFleetCoordination? then this.$effectiveFleetCoordination else $fleetcoordination"/>
      </do_if>
      <do_if value="not $effectiveFactionPriority?">
        <set_value name="$effectiveFactionPriority" exact="0"/>
      </do_if>
      <do_if value="not $effectiveAllowIllegal?">
        <set_value name="$effectiveAllowIllegal" exact="if this.$effectiveAllowIllegal? then this.$effectiveAllowIllegal else $allowillegal"/>
      </do_if>
      <do_if value="not $effectiveEnforceRouteIllegalLegality?">
        <set_value name="$effectiveEnforceRouteIllegalLegality" exact="if this.$effectiveEnforceRouteIllegalLegality? then this.$effectiveEnforceRouteIllegalLegality else $enforceRouteIllegalLegality"/>
      </do_if>
      <do_if value="not $effectiveLogbookEntries?">
        <set_value name="$effectiveLogbookEntries" exact="if this.$effectiveLogbookEntries? then this.$effectiveLogbookEntries else $logbookentries"/>
      </do_if>
      <do_if value="not $effectiveUseMinCargoThresholdFilter?">
        <set_value name="$effectiveUseMinCargoThresholdFilter" exact="if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else (if $useMinCargoThreshold? then $useMinCargoThreshold else false)"/>
      </do_if>
      <do_if value="not $effectivePriorityWares?">
        <set_value name="$effectivePriorityWares" exact="if this.$effectivePriorityWares? then this.$effectivePriorityWares else (if $prioritywares? then $prioritywares else [])"/>
      </do_if>
      <do_if value="not $effectivePriorityScoreMultiplier?">
        <set_value name="$effectivePriorityScoreMultiplier" exact="if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else (if $priorityscoremultiplier? then $priorityscoremultiplier else 125)"/>
      </do_if>

      <!-- Persist effective settings (survive save/load resume) -->
      <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
      <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
      <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
      <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
      <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
      <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
      <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
      <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
      <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
      <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
      <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
      <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
      <set_value name="this.$effectiveUseMinCargoThresholdFilter" exact="$effectiveUseMinCargoThresholdFilter"/>
      <set_value name="this.$effectiveSearchDepth" exact="$effectiveSearchDepth"/>
      <set_value name="this.$effectiveMaxTrades" exact="$effectiveMaxTrades"/>
      <set_value name="this.$effectiveBacktrackTolerance" exact="$effectiveBacktrackTolerance"/>
      <set_value name="this.$mk4DedicatedServe" exact="$mk4DedicatedServe"/>
      <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4AllowPlayerSuppliers"/>
      <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4AllowAiSuppliers"/>
      <set_value name="this.$mk4AllowResources" exact="$mk4AllowResources"/>
      <set_value name="this.$mk4AllowIntermediates" exact="$mk4AllowIntermediates"/>
      <set_value name="this.$mk4AllowTradewares" exact="$mk4AllowTradewares"/>
      <set_value name="this.$mk4PlayerBuyMod" exact="$mk4PlayerBuyMod"/>
      <set_value name="this.$mk4BuildStorageOnlyMode" exact="$mk4BuildStorageOnlyMode"/>
      
      <!-- Initialize subordinate count tracking -->
      <!-- Track when this ship becomes a commander (gets subordinates) -->
      <set_value name="$currentSubordinateCount" exact="0"/>
      <do_if value="this.ship.subordinates?">
        <set_value name="$currentSubordinateCount" exact="this.ship.subordinates.count"/>
      </do_if>
      <do_if value="not this.$trackedSubordinateCount?">
        <!-- First time - initialize tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_if>
      
      <!-- Reset was_subordinate flag based on CURRENT state, not previous state -->
      <!-- This prevents false positives when a ship transitions from subordinate â†’ independent -->
      <!-- If ship has a direct GT order, it's independent, not orphaned -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <do_if value="this.ship.defaultorder? and @this.ship.defaultorder.id == 'GalaxyTraderMK4Supply'">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <!-- Reset was_subordinate based on current commander status -->
      <set_value name="$isCurrentlySubordinate" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship"/>
      <set_value name="this.$was_subordinate" exact="$isCurrentlySubordinate"/>
      
      <!-- If ship has direct GT order but was previously subordinate, clear the flag -->
      <!-- This allows ships to transition from subordinate â†’ independent without being treated as orphaned -->
      <do_if value="$hasDirectGTOrder and not $isCurrentlySubordinate">
        <set_value name="this.$was_subordinate" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Reset was_subordinate flag (has direct GT order, not subordinate)'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- =============================================== -->
      <!-- MAIN TRADING LOOP (Modularized)                -->
      <!-- =============================================== -->
      
      <label name="main_loop"/>

      <!-- Idle park timed release (trader keeps searching; hold expiry handled here). -->
      <run_script name="'lib.gt.idlepark'">
        <param name="handoffMode" value="'check_timed_release'"/>
        <param name="handoffShip" value="this.ship"/>
        <param name="home" value="if this.$effectiveHome? and this.$effectiveHome != null and this.$effectiveHome.exists then this.$effectiveHome else this.ship.sector"/>
        <param name="debugchance" value="if this.$debugchance? then this.$debugchance else 0"/>
      </run_script>
      
      <!-- Unified ship name refresh (home sector, op-state, XP â€” content dedupe in MD) -->
      <run_script name="'lib.gt.attention.refresh_ship_name'">
        <param name="ship" value="this.ship"/>
      </run_script>
      <run_script name="'lib.gt.attention.autojump_distance_toggle'">
        <param name="autoJumpDistanceByLevel" value="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
      </run_script>

      <!-- NOTE: Signal check removed from here - maintenance must ALWAYS run before trade execution -->
      <!-- Signals will be checked AFTER maintenance completes (line 2147) to ensure maintenance is never skipped -->
      <!-- NOTE: Do NOT clear global.$GT_TradesAwaitingValidation here - it may contain fresh trade data -->
      <!-- The data will be cleared after trade execution completes (in trade_completed label) -->
      <!-- Cache will be checked by MD system when trade request is sent -->
      <!-- MD system will trigger cache search work unit if cache entries exist -->
      <!-- Cache search work unit will properly filter entries by distance/profit/etc before signaling back -->
      
      <!-- Work-unit processing removed by AI pipeline migration -->
      
      <!-- SAVEGAME GUARD: Re-initialize instance vars that may be missing after save/load resume -->
      <do_if value="not this.$blacklistgroup?">
        <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
        <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
          <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
        </do_if>
      </do_if>
      <do_if value="not this.$minPlayerMoney?">
        <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      </do_if>
      <!-- SAVEGAME GUARD: Restore training session flag from persisted MD state
           or an active DockAndTrain order (instance flag is lost on load). -->
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$sgHasDockAndTrain" exact="false"/>
        <do_if value="this.ship.orders.count gt 0">
          <do_all exact="this.ship.orders.count" counter="$sgOi">
            <do_if value="this.ship.orders.{$sgOi}.id == 'DockAndTrain'">
              <set_value name="$sgHasDockAndTrain" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <set_value name="$sgMdTrainingActive" exact="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'"/>
        <do_if value="$sgHasDockAndTrain or $sgMdTrainingActive">
          <set_value name="this.$training_in_progress" exact="true"/>
        </do_if>
      </do_if>

      <!-- Clear ESCAPE state once we are no longer in a blacklisted sector (whitelist overrides blacklist) -->
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Escaping? and global.$GT_Ships.{this.ship}.$Escaping">
        <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        <set_value name="$validationWhitelist" exact="[]"/>
        <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
          <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
        </do_if>
        <set_value name="$currentSector" exact="this.ship.sector"/>
        <set_value name="$curActivityBL" exact="false"/>
        <set_value name="$curTravelBL" exact="false"/>
        <set_value name="$curWhitelisted" exact="false"/>
        <do_if value="$validationWhitelist.count gt 0">
          <do_all exact="$validationWhitelist.count" counter="$swIdx">
            <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
              <set_value name="$curWhitelisted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $curWhitelisted">
          <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
          <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
        </do_if>
        <do_if value="not ($curActivityBL or $curTravelBL)">
          <remove_value name="global.$GT_Ships.{this.ship}.$Escaping"/>
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship=this.ship,
              $pilot=this.ship.pilot,
              $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
              $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType='trader'
            ]"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Debug: Confirm we reached main loop -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === MAIN LOOP STARTED === (Pilot: ' + (if this.ship.pilot then this.ship.pilot.name else 'NONE') + ')'" chance="100"/>
      </do_if>
      
      <!-- Read MinPlayerMoney once per loop iteration â€” used by money gates, authoritative guard, and logbook.
           Persisted on instance so it survives <wait> yields within this iteration. -->
      <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      
      <!-- Check if GT order was removed (main loop detection) -->
      <!-- This catches cases where GT order is manually removed but script continues running -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="not this.$trackedDefaultOrder?">
        <!-- First time - initialize tracked order -->
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder != 'GalaxyTraderMK3' and this.$trackedDefaultOrder != 'GalaxyTraderMK4Supply' and ($currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply')">
        <debug_text text="'[GT-AI] GT order reassigned for ' + this.ship.idcode + ' (detected in main loop, old: ' + this.$trackedDefaultOrder + ', new: ' + $currentDefaultOrder + ')'" chance="100"/>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="true"/>
          <param name="source" value="'AI_LOOP_REASSIGN'"/>
        </run_script>
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="(this.$trackedDefaultOrder == 'GalaxyTraderMK3' or this.$trackedDefaultOrder == 'GalaxyTraderMK4Supply') and ($currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply')">
        <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in main loop, old: ' + this.$trackedDefaultOrder + ', new: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ')'" chance="100"/>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="false"/>
          <param name="source" value="'AI_LOOP_CANCEL'"/>
        </run_script>
        
        <run_script name="'lib.gt.attention.restore_original_name'">
          <param name="ship" value="this.ship"/>
          <param name="reason" value="'GT order cancelled - restoring original name'"/>
          <param name="skipIfStillGT" value="true"/>
          <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply']"/>
        </run_script>
        
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder != $currentDefaultOrder">
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- MANDATORY TRAINING CHECK (BLOCKS ALL TRADING) -->
      <!-- ======================================= -->
      
      <!-- Check if training was completed by interrupt handler -->
      <do_if value="this.$training_complete?">
        <remove_value name="this.$training_complete"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training completed - continuing with trading'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Clear stale training flags when not in training -->
      <!-- These flags can persist when AI context is reused after rapid abort/restart -->
      <do_if value="this.$training_transition? or this.$training_order_created?">
        <do_if value="not this.ship.pilot or not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
          <!-- Pilot is not XP blocked, so training flags are stale - clear them -->
          <remove_value name="this.$training_transition"/>
          <remove_value name="this.$training_order_created"/>
          <remove_value name="this.$training_in_progress"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale training flags (pilot not XP blocked)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (Event-Driven)  -->
      <!-- ======================================= -->
      <!-- NOTE: Pilot change detection moved to restart points (trade_completed, init) -->
      <!-- Polling removed - detection happens at natural restart points where GT order reruns -->
      <!-- This ensures detection happens when order naturally restarts, not constantly polling -->
      
      <!-- ======================================= -->
      <!-- Commander change detection (Main Loop) -->
      <!-- ======================================= -->
      <!-- Track the current commander and detect if it changes (assignment, removal, or change) -->
      <!-- This is more reliable than event_object_commander_set which may not fire during script restart -->
      <set_value name="$currentCommander" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$currentCommander" exact="this.ship.commander"/>
      </do_if>
      
      <!-- Check if commander changed (null to exists, exists to null, or different commander) -->
      <do_if value="not this.$trackedCommander?">
        <!-- First time check - initialize tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_if>
      <do_elseif value="this.$trackedCommander != $currentCommander">
        <!-- Commander changed: nullâ†’exists, existsâ†’null, or different commander -->
        <set_value name="$oldCommander" exact="if this.$trackedCommander? then this.$trackedCommander else null"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if old commander had GT order (for name restoration) -->
        <set_value name="$oldCommanderHasGT" exact="false"/>
        <do_if value="@$oldCommander.exists">
          <do_if value="$oldCommander.defaultorder? and ((@$oldCommander.defaultorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$oldCommander.defaultorder.id == 'Assist' and $oldCommander.defaultorder.$baseorder? and (@$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$oldCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + (if @$oldCommander.exists then @$oldCommander.idcode else 'NONE') + ', new: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <do_if value="$oldCommanderHasGT and not $newCommanderHasGT and this.ship.pilot?">
          <run_script name="'lib.gt.attention.restore_original_name'">
            <param name="ship" value="this.ship"/>
            <param name="reason" value="'Commander changed - no longer subordinate to GT commander'"/>
            <param name="skipIfStillGT" value="true"/>
            <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply']"/>
          </run_script>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      
      <!-- ======================================= -->
      <!-- Subordinate count detection (Main Loop) -->
      <!-- ======================================= -->
      <!-- Track when this ship becomes a commander (gets subordinates) or stops being one (loses all subordinates) -->
      <!-- This is important for ships that transition from subordinate â†’ commander -->
      <set_value name="$currentSubordinateCount" exact="0"/>
      <do_if value="this.ship.subordinates?">
        <set_value name="$currentSubordinateCount" exact="this.ship.subordinates.count"/>
      </do_if>
      
      <!-- Check if subordinate count changed -->
      <do_if value="not this.$trackedSubordinateCount?">
        <!-- First time check - initialize tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_if>
      <do_elseif value="this.$trackedSubordinateCount != $currentSubordinateCount">
        <!-- Subordinate count changed -->
        <set_value name="$oldSubordinateCount" exact="this.$trackedSubordinateCount"/>
        <set_value name="$newSubordinateCount" exact="$currentSubordinateCount"/>
        
        <!-- Determine if ship became a commander or stopped being one -->
        <set_value name="$wasCommander" exact="($oldSubordinateCount gt 0)"/>
        <set_value name="$isCommander" exact="($newSubordinateCount gt 0)"/>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Subordinate_Count_Changed',
          $OldSubordinateCount = $oldSubordinateCount,
          $NewSubordinateCount = $newSubordinateCount,
          $WasCommander = $wasCommander,
          $IsCommander = $isCommander
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Subordinate count changed for ' + this.ship.idcode + ' (old: ' + $oldSubordinateCount + ', new: ' + $newSubordinateCount + ', was commander: ' + $wasCommander + ', is commander: ' + $isCommander + ')'" chance="100"/>
        </do_if>
        
        <!-- Update tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_elseif>
      
      <!-- ======================================= -->
      <!-- SUBORDINATE COMMANDER CHECK            -->
      <!-- ======================================= -->
      <!-- Check if ship was a subordinate but lost its commander completely -->
      <!-- Track if ship was a subordinate when order started -->
      <do_if value="not this.$was_subordinate?">
        <!-- First time check - store if ship is currently a subordinate -->
        <set_value name="this.$was_subordinate" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship"/>
      </do_if>
      
      <!-- Check if subordinate lost its commander or commander lost GT order -->
      <!-- Unified GT order status check (inline for AI scripts) -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <set_value name="$hasGTCommander" exact="false"/>
      <set_value name="$commanderExists" exact="false"/>
      <set_value name="$isSubordinate" exact="false"/>
      
      <!-- Check direct GT order -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply'">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <!-- Check commander status -->
      <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$commanderExists" exact="true"/>
        <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
          <set_value name="$hasGTCommander" exact="true"/>
          <do_if value="$currentDefaultOrder == 'Assist'">
            <set_value name="$isSubordinate" exact="true"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Check if ship was subordinate and lost commander completely -->
      <do_if value="this.$was_subordinate and not $hasDirectGTOrder">
        <do_if value="not $commanderExists">
          <!-- Subordinate lost its commander completely - restore name and self-abort -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SUBORDINATE ORPHANED: Commander assignment completely removed - restoring ship name and self-aborting'" chance="100"/>
          </do_if>
          
          <!-- Send cleanup signal unconditionally (with safe original-name fallback). -->
          <set_value name="$originalName" exact="null"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          <do_elseif value="this.ship.macro?">
            <set_value name="$originalName" exact="@this.ship.macro.name"/>
          </do_elseif>
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'Commander lost GT order',
            $OriginalName = $originalName
          ]"/>
          
          <!-- Set flag only after signal was emitted -->
          <set_value name="this.$subordinate_cleanup_sent" exact="true"/>
          
          <!-- Self-cancel GT order since subordinate is no longer assigned -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Self-canceling GT order - commander assignment removed'" chance="100"/>
          </do_if>
          <cancel_order order="this.ship.defaultorder"/>
          <return/>
        </do_if>
      </do_if>
      
      <!-- If subordinate and commander no longer has GT order, restore ship name and self-abort -->
      <do_if value="$commanderExists and not $hasGTCommander">
        <!-- Commander no longer has GT order - subordinate will follow commander's new order via Assist -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SUBORDINATE ORPHANED: Commander ' + this.ship.commander.idcode + ' no longer has GT order - restoring ship name and self-aborting'" chance="100"/>
        </do_if>
        
        <!-- Send cleanup signal unconditionally (with safe original-name fallback). -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="this.ship.macro?">
          <set_value name="$originalName" exact="@this.ship.macro.name"/>
        </do_elseif>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Commander lost GT order',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Set flag only after signal was emitted -->
        <set_value name="this.$subordinate_cleanup_sent" exact="true"/>
        
        <!-- Self-cancel GT order since X4 will make us follow commander's new order anyway -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Self-canceling GT order - will follow commander via Assist'" chance="100"/>
        </do_if>
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Update subordinate tracking flag -->
      <do_if value="$isSubordinate">
        <set_value name="this.$was_subordinate" exact="true"/>
      </do_if>
      <do_else>
        <!-- Not a subordinate anymore - clear flag -->
        <set_value name="this.$was_subordinate" exact="false"/>
      </do_else>
      
      <!-- MANDATORY TRAINING GATE: shared decision logic -->
      <set_value name="$pilotXPBlocked" exact="false"/>
      <set_value name="$pilotMustTrainNow" exact="false"/>
      <set_value name="$pilotNameForDebug" exact="'No Pilot'"/>
      <set_value name="$pilotLevel" exact="1"/>
      <set_value name="$blockedLevel" exact="1"/>
      <set_value name="$trainingGateReason" exact="'none'"/>
      <set_value name="$hardForceTraining" exact="true"/>
      <set_value name="$manualTrainingRequested" exact="false"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
        <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
      </do_if>
      
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$pilotNameForDebug" exact="this.ship.pilot.name"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$Level?">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>

        <set_value name="$pilotXPBlocked" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else (global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?)"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested">
          <set_value name="$manualTrainingRequested" exact="true"/>
        </do_if>
        <set_value name="$pilotMustTrainNow" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else ($pilotXPBlocked or ($hardForceTraining and $blockedLevel gt 1))"/>

        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?">
          <set_value name="$trainingGateReason" exact="'paused_training_needed'"/>
        </do_if>
        <do_elseif value="$pilotXPBlocked">
          <set_value name="$trainingGateReason" exact="'xp_blocked'"/>
        </do_elseif>
        <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
          <set_value name="$trainingGateReason" exact="'hard_force_blocked_level'"/>
        </do_elseif>
        <do_elseif value="$blockedLevel gt 1">
          <set_value name="$trainingGateReason" exact="'soft_force_blocked_level'"/>
        </do_elseif>
      </do_if>
      
      <!-- Show the decision logic -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': DECISION LOGIC: XPBlocked=' + $pilotXPBlocked + ', MustTrainNow=' + $pilotMustTrainNow + ', HardForce=' + $hardForceTraining + ', ManagementLevel=' + $pilotLevel + ', BlockedLevel=' + $blockedLevel + ', Reason=' + $trainingGateReason + ', Pilot=' + $pilotNameForDebug" chance="100"/>
      </do_if>
      
      <do_if value="$pilotMustTrainNow">
        <!-- Check if this is a legitimate training requirement (blocked level > 1) -->
        <do_if value="$blockedLevel gt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': TRAINING MANDATORY: Pilot ' + $pilotNameForDebug + ' needs Level ' + $blockedLevel + ' training - no trading allowed until training completes'" chance="100"/>
          </do_if>
          <resume label="handle_mandatory_training"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pilot marked for training but BlockedLevel is invalid - clearing block and proceeding with trading'" chance="100"/>
          <!-- Clear the incorrect XP block for invalid Level 1 edge cases -->
          <signal_objects object="player.galaxy" param="'GT_Clear_XP_Block'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'Training gate invalid: BlockedLevel lte 1'
          ]"/>
        </do_else>
      </do_if>
      <do_else>
        <!-- Soft-force behavior: keep trading, but still retry training each loop when auto-training is enabled -->
        <set_value name="$academyEnrollmentPending" exact="false"/>
        <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
          <set_value name="$academyEnrollmentPending" exact="true"/>
        </do_if>
        <do_if value="not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) and ($gt_autotraining or $manualTrainingRequested or $academyEnrollmentPending) and this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and $blockedLevel gt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Soft-force/manual mode active - continuing trading but retrying training this loop (blocked level ' + $blockedLevel + ', manual=' + $manualTrainingRequested + ')'" chance="100"/>
          </do_if>
          <resume label="handle_mandatory_training"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training gate allows trading - proceeding to maintenance check'" chance="100"/>
          </do_if>
          <!-- Check maintenance needs before trading starts -->
          <resume label="check_maintenance"/>
        </do_else>
      </do_else>
      
      <!-- ======================================= -->
      <!-- INITIAL MAINTENANCE CHECK              -->
      <!-- ======================================= -->
      
      <label name="check_maintenance"/>
      
      <!-- ============================================================================= -->
      <!-- PRE-TRADE MAINTENANCE CHECK (UNIFIED SYSTEM)                                  -->
      <!-- ============================================================================= -->
      <!-- Signal unified maintenance system and wait for completion.                    -->
      <!-- MD system handles ALL logic: checking, finding stations, creating orders,     -->
      <!-- and monitoring. AI script just triggers and waits - clean separation!         -->
      <!-- ============================================================================= -->
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Requesting maintenance check'" chance="100"/>
      </do_if>
      
      <!-- Signal unified maintenance system to analyze and prepare data -->
      <signal_objects object="player.galaxy" param="'GT_DoMaintenance'" param2="this.ship"/>
      
      <!-- Wait for MD system to prepare data -->
      <wait exact="0.5s"/>
      
      <!-- DIAGNOSTIC: Log what MD prepared after the wait -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$diagHasRepair" exact="global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?"/>
        <set_value name="$diagHasResupply" exact="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?"/>
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Maintenance check result: RepairOrder=' + $diagHasRepair + ', ResupplyOrder=' + $diagHasResupply + ', HullPct=' + this.ship.hullpercentage + '%'" chance="100"/>
      </do_if>
      
      <!-- Create Repair order if data prepared -->
      <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?">
        <set_value name="$repairData" exact="global.$GT_RepairOrders.{this.ship}"/>
        <set_value name="$repairStation" exact="$repairData.$Station"/>
        
        <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=service_ai -->
        <set_value name="$canDockRepair" exact="false"/>
        <do_if value="@$repairStation.exists">
          <run_script name="'lib.gt.dockcheck'" result="$repairDockResult">
            <param name="ship" value="this.ship"/>
            <param name="station" value="$repairStation"/>
            <param name="purpose" value="'service_ai'"/>
          </run_script>
          <set_value name="$canDockRepair" exact="$repairDockResult.$CanDock"/>
          <do_if value="not $canDockRepair">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Repair docking check FAILED: ' + @$repairStation.knownname + 
                '\n  Sector: ' + @$repairStation.sector.knownname + 
                '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                '\n  â†’ Clearing repair order and continuing trading...'" 
                chance="100"/>
            </do_if>
            <remove_value name="global.$GT_RepairOrders.{this.ship}"/>
          </do_if>
        </do_if>
        
        <!-- Only create repair order if docking check passed -->
        <do_if value="$canDockRepair">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Creating Repair order at ' + $repairStation.knownname" chance="100"/>
        
        <!-- Set flag to indicate maintenance transition for on_abort handler -->
        <set_value name="this.$maintenance_transition" exact="true"/>
        
        <create_order object="this.ship" id="'Repair'" immediate="false" priority="true">
            <param name="destination" value="$repairStation"/>
          <param name="hullpercent" value="100"/>
          <param name="repairall" value="true"/>
          <param name="acceptedcost" value="$repairData.$AcceptedCost"/>
          <param name="urgent" value="false"/>
          <param name="internalorder" value="true"/>
        </create_order>
        </do_if>
      </do_if>
      
      <!-- Create Resupply order if data prepared -->
      <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
        <set_value name="$resupplyData" exact="global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': CREATING RESUPPLY BUILD ORDER'" chance="100"/>
          <debug_text text="'[GT-AI]    Target Station: ' + $resupplyData.$Station.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station Owner: ' + @$resupplyData.$Station.owner.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station Sector: ' + @$resupplyData.$Station.sector.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station exists: ' + $resupplyData.$Station.exists" chance="100"/>
          <debug_text text="'[GT-AI]    Station operational: ' + @$resupplyData.$Station.isoperational" chance="100"/>
          <debug_text text="'[GT-AI]    Distance from ship: ' + this.ship.gatedistance.{$resupplyData.$Station} + ' jumps'" chance="100"/>
        </do_if>
        
        <!-- Use vanilla's pattern: add_build_to_modify_ship with shopping list -->
        <!-- This is what actually creates the order with specific items to buy -->
        <set_value name="$buildSuccessful" exact="false"/>
        
        <!-- add_build_to_modify_ship SETS inventory, doesn't ADD to it -->
        <!-- Tables now include CURRENT equipment + NEW equipment (preserves existing) -->
        <!-- Check if tables have keys (they should always have keys now since we preserve existing equipment) -->
        <set_value name="$ammoTableKeys" exact="@$resupplyData.$AmmoTable.keys"/>
        <set_value name="$ammoTableCount" exact="@$ammoTableKeys.count"/>
        <set_value name="$unitTableKeys" exact="@$resupplyData.$UnitTable.keys"/>
        <set_value name="$unitTableCount" exact="@$unitTableKeys.count"/>
        
        <!-- Always call add_build_to_modify_ship if we have a resupply order (tables include existing + new equipment) -->
        <do_if value="$ammoTableCount? or $unitTableCount?">
          <set_value name="$resupplyStation" exact="$resupplyData.$Station"/>
          
          <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=service_ai -->
          <set_value name="$canDockResupply" exact="false"/>
          <do_if value="@$resupplyStation.exists">
            <run_script name="'lib.gt.dockcheck'" result="$resupplyDockResult">
              <param name="ship" value="this.ship"/>
              <param name="station" value="$resupplyStation"/>
              <param name="purpose" value="'service_ai'"/>
            </run_script>
            <set_value name="$canDockResupply" exact="$resupplyDockResult.$CanDock"/>
            <do_if value="not $canDockResupply">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resupply docking check FAILED: ' + @$resupplyStation.knownname + 
                  '\n  Sector: ' + @$resupplyStation.sector.knownname + 
                  '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                  '\n  â†’ Clearing resupply order and continuing trading...'" 
                  chance="100"/>
              </do_if>
              <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            </do_if>
          </do_if>
          
          <!-- Only create resupply order if docking check passed -->
          <do_if value="$canDockResupply">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Shopping list - Ammo types: ' + $ammoTableCount + ', Unit types: ' + $unitTableCount" chance="100"/>
          </do_if>
          
          <!-- Set flag to indicate maintenance transition for on_abort handler -->
          <set_value name="this.$maintenance_transition" exact="true"/>
          
          <!-- Use vanilla's add_build_to_modify_ship action -->
          <!-- Tables now include CURRENT equipment (preserves it) + NEW equipment (adds to it) -->
          <!-- Use immediate="false" so GT order waits for build order to complete -->
          <add_build_to_modify_ship 
              object="$resupplyStation" 
            buildobject="this.ship" 
            ammo="$resupplyData.$AmmoTable" 
            units="$resupplyData.$UnitTable" 
            immediate="false"
            internal="true"
            result="$buildSuccessful"/>
          
          <do_if value="$buildSuccessful">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Build order created successfully - waiting for completion'" chance="100"/>
              <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
            </do_if>
            <!-- Build order will complete and trigger our order.build.equip patch to signal completion -->
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FAILED to create build order!'" chance="100"/>
              <debug_text text="'[GT-AI]    This usually means the station cannot build the requested items'" chance="100"/>
              <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Build order creation failed - station cannot fulfill order'" chance="100"/>
            </do_if>
            
            <!-- Clean up resupply data -->
            <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            
            <!-- Apply cooldown to prevent immediate retry -->
            <do_if value="not global.$GT_MaintenanceFailedResupply?">
              <set_value name="global.$GT_MaintenanceFailedResupply" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_MaintenanceFailedResupply.{this.ship}" exact="player.age + 300s"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸ•’ Applied 5-minute cooldown due to failed build order'" chance="100"/>
            
            <!-- Remove maintenance order flag -->
            <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
              <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
            </do_if>
            
            <!-- Signal MD that we're done (failed) -->
            <signal_objects object="this.ship" param="'GT_Maintenance_Complete'"/>
          </do_else>
          </do_if>
          <!-- End: Only create resupply order if docking check passed -->
          <!-- End: Only create resupply order if docking check passed -->
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Empty shopping list - nothing to buy'" chance="100"/>
          </do_if>
          
          <!-- Clean up and skip -->
          <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
          <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
            <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
          </do_if>
          
          <signal_objects object="this.ship" param="'GT_Maintenance_Complete'"/>
        </do_else>
      </do_if>
      
      <!-- Wait for maintenance to complete -->
      <do_if value="(global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?) or (global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â³ Waiting for maintenance orders to complete (max 900s)...'" chance="100"/>
        </do_if>
        
        <wait max="900s">
          <interrupt>
            <conditions>
              <event_object_signalled object="this.ship" param="'GT_Maintenance_Complete'"/>
            </conditions>
            <actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Maintenance complete signal received, proceeding to trade search'" chance="100"/>
              </do_if>
              
              <!-- Clear maintenance transition flag -->
              <remove_value name="this.$maintenance_transition"/>
            </actions>
          </interrupt>
        </wait>
        
        <!-- Timeout fallback -->
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â±ï¸ Maintenance timeout after 900s, proceeding anyway'" chance="100"/>
        
        <!-- Clear maintenance transition flag on timeout as well -->
        <remove_value name="this.$maintenance_transition"/>
      </do_if>
      <do_else>
        <!-- No maintenance needed -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No maintenance needed, proceeding to trade search'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- CRITICAL: Check for signal that arrived during maintenance wait -->
      <!-- This must happen AFTER maintenance completes but BEFORE proceeding to start_trading -->
      <!-- Signals can arrive during the maintenance wait block (line 2118), so we check here -->
      <do_if value="this.$tradeFoundViaInterrupt? and this.$tradeFoundViaInterrupt">
        <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received during maintenance wait - processing from param2 data'" chance="100"/>
        </do_if>
        
        <!-- Reset retry counter on successful trade -->
        <set_value name="this.$searchFailed" exact="0"/>
        
        <!-- Clear per-ship no-trade attempt history on success -->
        <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
          <remove_value name="global.$GT_NoTradeHistory.{this.ship}"/>
        </do_if>
        
        <!-- CARGO DISPOSAL: Reset cargo disposal failure counter on successful trade -->
        <do_if value="this.$cargoDisposalFailed?">
          <set_value name="this.$cargoDisposalFailed" exact="0"/>
        </do_if>
        
        <resume label="trade_found"/>
      </do_if>
      
      <!-- Proceed to trading -->
      <resume label="start_trading"/>
      
      <!-- ======================================= -->
      <!-- HIGH-PERFORMANCE TRADING LOOP          -->
      <!-- ======================================= -->
      
      <!-- ========================================= -->
      <!-- MANDATORY TRAINING HANDLER              -->
      <!-- ========================================= -->
      
      <label name="handle_mandatory_training"/>
      
      <!-- Check if ship has an active DockAndTrain order -->
      <set_value name="$hasActiveTrainingOrder" exact="false"/>
      <do_if value="this.ship.orders.count gt 0">
        <do_all exact="this.ship.orders.count" counter="$i">
          <do_if value="this.ship.orders.{$i}.id == 'DockAndTrain'">
            <set_value name="$hasActiveTrainingOrder" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      
      <!-- ENHANCED LOGIC: Auto-restart training if it was previously interrupted -->
      <!-- Conditions for starting/restarting training:
           1. Auto-training is enabled
           2. Ship has a pilot with GT pilot data
           3. Either: training not in progress OR no active training order (interrupted training)
      -->
      <set_value name="$manualTrainingRequested" exact="false"/>
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested">
        <set_value name="$manualTrainingRequested" exact="true"/>
      </do_if>
      <set_value name="$academyEnrollmentPending" exact="false"/>
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
        <set_value name="$academyEnrollmentPending" exact="true"/>
      </do_if>
      <do_if value="($gt_autotraining or $manualTrainingRequested or $academyEnrollmentPending) and this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}">
        <set_value name="$shouldStartTraining" exact="false"/>
        <set_value name="$mdTrainingInProgress" exact="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'"/>
        
        <!-- Case 0: Active DockAndTrain or MD timer (save/load) - wait, do not re-dispatch -->
        <do_if value="$hasActiveTrainingOrder or $mdTrainingInProgress">
          <do_if value="not this.$training_in_progress?">
            <set_value name="this.$training_in_progress" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Restored in-flight training session after save/load (DockAndTrain=' + $hasActiveTrainingOrder + ', MD timer=' + $mdTrainingInProgress + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Case 1: Training not currently in progress -->
        <do_elseif value="not this.$training_in_progress?">
          <set_value name="$shouldStartTraining" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training not in progress - can start training'" chance="100"/>
          </do_if>
        </do_elseif>
        <!-- Case 2: Training was marked as in progress but no active training order (interrupted) -->
        <do_elseif value="this.$training_in_progress? and not $hasActiveTrainingOrder">
          <set_value name="$shouldStartTraining" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': TRAINING INTERRUPTED: Previous training was aborted - restarting automatically'" chance="100"/>
          </do_if>
          <!-- Clear the stale flag -->
          <remove_value name="this.$training_in_progress"/>
        </do_elseif>
        
        <do_if value="$shouldStartTraining">
          <!-- Inline training gate evaluation (AI scripts cannot call MD libraries) -->
          <set_value name="$hardForceTraining" exact="true"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
            <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
          </do_if>
          <set_value name="$blockedLevel" exact="1"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          </do_if>
          <set_value name="$mustTrainNow" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else (global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded? or ($hardForceTraining and $blockedLevel gt 1))"/>
          <set_value name="$shouldRetryTraining" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else ($mustTrainNow or ((not $hardForceTraining) and $blockedLevel gt 1) or ($manualTrainingRequested and $blockedLevel gt 1))"/>
          <set_value name="$trainingGateReason" exact="'none'"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?">
            <set_value name="$trainingGateReason" exact="'paused_training_needed'"/>
          </do_if>
          <do_elseif value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
            <set_value name="$trainingGateReason" exact="'xp_blocked'"/>
          </do_elseif>
          <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
            <set_value name="$trainingGateReason" exact="'hard_force_blocked_level'"/>
          </do_elseif>
          <do_elseif value="$blockedLevel gt 1">
            <set_value name="$trainingGateReason" exact="'soft_force_blocked_level'"/>
          </do_elseif>
          
          <do_if value="$shouldRetryTraining">
            <!-- Get blocked level with safety check -->
            <do_if value="not (global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0)">
              <!-- Calculate current skill level as fallback -->
              <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XP?">
                <set_value name="$currentXP" exact="global.$GT_Pilots.{this.ship.pilot}.$XP"/>
                <do_all exact="15" counter="$skillLevel">
                  <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                    <set_value name="$blockedLevel" exact="$skillLevel"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸŽ“ Initiating mandatory training for pilot ' + $pilotNameForDebug + ' (Level ' + $blockedLevel + ', reason=' + $trainingGateReason + ', hardforce=' + $hardForceTraining + ')'" chance="100"/>
            </do_if>
            
            <!-- Respect retry backoff only in hard-force mode -->
            <set_value name="$retryReady" exact="true"/>
            <do_if value="$hardForceTraining and global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt? and player.age lt global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt">
              <set_value name="$retryReady" exact="false"/>
            </do_if>
            
            <do_if value="$retryReady">
              <!-- Signal MD system to handle training -->
              <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $RequiredLevel = $blockedLevel
              ]"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training signal sent to MD system for pilot ' + $pilotNameForDebug" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$retryRemaining" exact="(global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt - player.age) / 1s"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training retry backoff active (' + $retryRemaining + 's remaining)'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <!-- Training is not mandatory under current gate policy -->
            <set_value name="$blockedLevelForDebug" exact="'none'"/>
            <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel?">
              <set_value name="$blockedLevelForDebug" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training gate allows trading in mandatory handler (reason=' + $trainingGateReason + ', blockedLevel=' + $blockedLevelForDebug + ', hardforce=' + $hardForceTraining + ')'" chance="100"/>
            </do_if>
            <!-- Break out of training handler and continue to trading -->
            <resume label="check_maintenance"/>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â³ Training already in progress (active order: ' + $hasActiveTrainingOrder + ') - waiting'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Auto-training disabled or no pilot data - waiting'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- Wait and check again - training is mandatory -->
      <wait max="10s">
        <interrupt>
          <conditions>
            <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
          </conditions>
          <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training station found during wait - proceeding immediately'" chance="100"/>
            </do_if>
          </actions>
        </interrupt>
      </wait>
      <resume label="main_loop"/>
      
      <!-- ========================================= -->
      <!-- EVENT-DRIVEN TRADE SEARCH WITH RETRY     -->
      <!-- ========================================= -->
      
      <label name="start_trading"/>

      <!-- HARD RULE: no silent fallbacks for pilot skill timing issues. -->
      <!-- If GT pilot level isn't available yet, do NOT request a trade search with bogus caps. -->
      <!-- Wait is only allowed at top-level; use a bounded loop here (not inside any do_if). -->
      <set_value name="$pilotSkillMissing" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and (not this.ship.pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{this.ship.pilot}? or not global.$GT_Pilots.{this.ship.pilot}.$Level?)"/>
      <set_value name="this.$pilotSkillWaitTries" exact="0"/>
      <do_while value="$pilotSkillMissing and this.$pilotSkillWaitTries lt 10">
        <wait exact="1s"/>
        <set_value name="$pilotSkillMissing" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and (not this.ship.pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{this.ship.pilot}? or not global.$GT_Pilots.{this.ship.pilot}.$Level?)"/>
        <set_value name="this.$pilotSkillWaitTries" exact="this.$pilotSkillWaitTries + 1"/>
      </do_while>
      <do_if value="$pilotSkillMissing">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ERROR: GT pilot level unavailable after ' + this.$pilotSkillWaitTries + 's - NOT sending trade search request. Will retry on next loop (this is a timing bug we want to SEE).'" chance="100"/>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- effectiveMaxBuy/effectiveMaxSell initialized in <init> block -->

      <!-- ========================================= -->
      <!-- SUBORDINATE SETTINGS REFRESH (ON REQUEST) -->
      <!-- ========================================= -->
      <!-- Problem: Commander default-order param edits do not reliably trigger event_object_order_ready.
           Solution: When a subordinate is ABOUT to request a new trade, refresh inherited commander settings if they changed.
           effectiveAutoWares/effectiveWareBasket/effectiveDistancePenalty initialized in <init> block. -->

      <set_value name="$_isSubordinateNow" exact="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship"/>
      <do_if value="$_isSubordinateNow">
        <set_value name="$_commanderOrderNow" exact="this.ship.commander.defaultorder"/>
        <do_if value="$_commanderOrderNow?">
          <!-- Build a signature for commander settings that affect trade searching / routing -->
          <set_value name="$_cmdAutoWares" exact="if $_commanderOrderNow.$autowares? then $_commanderOrderNow.$autowares else (if $_commanderOrderNow.$lockWares? then not $_commanderOrderNow.$lockWares else $effectiveAutoWares)"/>
          <set_value name="$_cmdDistancePenalty" exact="if $_commanderOrderNow.$distancepenalty? then $_commanderOrderNow.$distancepenalty else $effectiveDistancePenalty"/>
          <set_value name="$_cmdWareBasket" exact="if $_commanderOrderNow.$warebasket? and $_commanderOrderNow.$warebasket.count gt 0 then $_commanderOrderNow.$warebasket else (if $_commanderOrderNow.$specialWareBasket? then $_commanderOrderNow.$specialWareBasket else $effectiveWareBasket)"/>

          <set_value name="$_cmdFleetCoord" exact="if $_commanderOrderNow.$fleetcoordination? then $_commanderOrderNow.$fleetcoordination else $effectiveFleetCoordination"/>
          <set_value name="$_cmdAllowIllegal" exact="if $_commanderOrderNow.$allowillegal? then $_commanderOrderNow.$allowillegal else $effectiveAllowIllegal"/>
          <set_value name="$_cmdIllegalRouteFilter" exact="if $_commanderOrderNow.$enforceRouteIllegalLegality? then $_commanderOrderNow.$enforceRouteIllegalLegality else $effectiveEnforceRouteIllegalLegality"/>
          <set_value name="$_cmdFactionPriority" exact="0"/>
          <set_value name="$_cmdIgnoreCarrierAux" exact="if $_commanderOrderNow.$ignorecarrieraux? then $_commanderOrderNow.$ignorecarrieraux else $effectiveIgnoreCarrierAux"/>
          <set_value name="$_cmdIgnoreBuildStorage" exact="if $_commanderOrderNow.$allowBuildstorage? then not $_commanderOrderNow.$allowBuildstorage else $effectiveIgnoreBuildStorage"/>
          <set_value name="$_cmdIgnoreTradeRules" exact="if $_commanderOrderNow.$ignoretraderules? then $_commanderOrderNow.$ignoretraderules else $effectiveIgnoreTradeRules"/>
          <set_value name="$_cmdIgnoreMK1Supply" exact="if $_commanderOrderNow.$ignoremk1supply? then $_commanderOrderNow.$ignoremk1supply else $effectiveIgnoreMK1Supply"/>
          <set_value name="$_cmdLogbookEntries" exact="if $_commanderOrderNow.$logbookentries? then $_commanderOrderNow.$logbookentries else $effectiveLogbookEntries"/>
          <set_value name="$_cmdNotifications" exact="if $_commanderOrderNow.$notifications? then $_commanderOrderNow.$notifications else $effectiveNotifications"/>
          <set_value name="$_cmdUseMinCargoThresholdFilter" exact="if $_commanderOrderNow.$useMinCargoThreshold? then $_commanderOrderNow.$useMinCargoThreshold else $effectiveUseMinCargoThresholdFilter"/>
          <set_value name="$_cmdCargoTarget" exact="if $_commanderOrderNow.$minCargoUsed? then $_commanderOrderNow.$minCargoUsed else $effectiveCargoTarget"/>
          <set_value name="$_cmdDebugLevel" exact="if $_commanderOrderNow.$debuglevel? then $_commanderOrderNow.$debuglevel else $effectiveDebugLevel"/>
          <set_value name="$_cmdTradeEval" exact="if $_commanderOrderNow.$tradeeval? then $_commanderOrderNow.$tradeeval else $effectiveTradeEval"/>
          <set_value name="$_cmdHome" exact="if $_commanderOrderNow.$home? then $_commanderOrderNow.$home else this.$effectiveHome"/>
          <set_value name="$_cmdMaxBuy" exact="if $_commanderOrderNow.$jumpDistanceBuy? then $_commanderOrderNow.$jumpDistanceBuy else $effectiveMaxBuy"/>
          <set_value name="$_cmdMaxSell" exact="if $_commanderOrderNow.$jumpDistanceCoverage? then $_commanderOrderNow.$jumpDistanceCoverage else $effectiveMaxSell"/>
          <set_value name="$_cmdSectorWhitelist" exact="if $_commanderOrderNow.$sectorwhitelist? then $_commanderOrderNow.$sectorwhitelist else $effectiveSectorWhitelist"/>
          <set_value name="$_cmdM4Res" exact="if $_commanderOrderNow.$allowResources? then $_commanderOrderNow.$allowResources else (if this.$mk4AllowResources? then this.$mk4AllowResources else true)"/>
          <set_value name="$_cmdM4Int" exact="if $_commanderOrderNow.$allowIntermediates? then $_commanderOrderNow.$allowIntermediates else (if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true)"/>
          <set_value name="$_cmdM4Tw" exact="if $_commanderOrderNow.$allowTradewares? then $_commanderOrderNow.$allowTradewares else (if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true)"/>
          <set_value name="$_cmdM4Aps" exact="if $_commanderOrderNow.$buyFromPlayer? then $_commanderOrderNow.$buyFromPlayer else (if $_commanderOrderNow.$allowPlayerSuppliers? then $_commanderOrderNow.$allowPlayerSuppliers else (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true))"/>
          <set_value name="$_cmdM4Aas" exact="if $_commanderOrderNow.$buyFromFaction? then $_commanderOrderNow.$buyFromFaction else (if $_commanderOrderNow.$allowAiSuppliers? then $_commanderOrderNow.$allowAiSuppliers else (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true))"/>
          <set_value name="$_cmdM4Ded" exact="if $_commanderOrderNow.$serveHomeOnly? then $_commanderOrderNow.$serveHomeOnly else (if $_commanderOrderNow.$dedicatedServe? then $_commanderOrderNow.$dedicatedServe else (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false))"/>
          
          <!-- IMPORTANT:
               In X4 AI script expressions, `?` checks existence, NOT null, and boolean `and` is not safe to rely on for short-circuiting.
               Normalize a null sectorwhitelist to an empty list so we can safely use `.count`. -->
          <do_if value="not $_cmdSectorWhitelist? or $_cmdSectorWhitelist == null">
            <set_value name="$_cmdSectorWhitelist" exact="[]"/>
          </do_if>

          <set_value name="$_cmdHomeName" exact="if $_cmdHome? then @$_cmdHome.knownname else 'NULL'"/>
          <!-- Include subordinate pilot level in signature so level-up forces inherited cap refresh. -->
          <set_value name="$_pilotLevelSig" exact="0"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
            <set_value name="$_pilotLevelSig" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
          </do_if>

          <set_value name="$_commanderSettingsSig" exact="'AW=' + $_cmdAutoWares
            + '|DP=' + $_cmdDistancePenalty
            + '|FC=' + $_cmdFleetCoord
            + '|IL=' + $_cmdAllowIllegal
            + '|IRF=' + $_cmdIllegalRouteFilter
            + '|FP=' + $_cmdFactionPriority
            + '|ICA=' + $_cmdIgnoreCarrierAux
            + '|IBS=' + $_cmdIgnoreBuildStorage
            + '|ITR=' + $_cmdIgnoreTradeRules
            + '|IM1=' + $_cmdIgnoreMK1Supply
            + '|HB=' + $_cmdHomeName
            + '|MB=' + $_cmdMaxBuy
            + '|MS=' + $_cmdMaxSell
            + '|LB=' + $_cmdLogbookEntries
            + '|NT=' + $_cmdNotifications
            + '|UC=' + $_cmdUseMinCargoThresholdFilter
            + '|CT=' + $_cmdCargoTarget
            + '|DL=' + $_cmdDebugLevel
            + '|TE=' + $_cmdTradeEval
            + '|PL=' + $_pilotLevelSig
            + '|M4R=' + $_cmdM4Res
            + '|M4I=' + $_cmdM4Int
            + '|M4T=' + $_cmdM4Tw
            + '|M4APS=' + $_cmdM4Aps
            + '|M4AAS=' + $_cmdM4Aas
            + '|M4DED=' + $_cmdM4Ded
            + '|SW='"/>

          <!-- Include sector whitelist content -->
          <do_if value="$_cmdSectorWhitelist.count gt 0">
            <do_all exact="$_cmdSectorWhitelist.count" counter="$_sw_i">
              <set_value name="$_sw" exact="$_cmdSectorWhitelist.{$_sw_i}"/>
              <set_value name="$_swName" exact="if $_sw? then @$_sw.knownname else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_sw_i gt 1 then ',' else '') + $_swName"/>
            </do_all>
          </do_if>

          <!-- Include ware basket content (only when autowares is disabled) -->
          <do_if value="not $_cmdAutoWares">
            <do_all exact="$_cmdWareBasket.count" counter="$_i">
              <set_value name="$_w" exact="$_cmdWareBasket.{$_i}"/>
              <set_value name="$_wName" exact="if $_w? then @$_w.name else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_i gt 1 then ',' else '') + $_wName"/>
            </do_all>
          </do_if>

          <do_if value="not this.$trackedCommanderSettingsSig? or this.$trackedCommanderSettingsSig != $_commanderSettingsSig">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Commander settings changed (refreshing inherited settings). NewSig=' + $_commanderSettingsSig" chance="100"/>
            </do_if>

            <!-- Apply commander settings to this subordinate immediately -->
            <set_value name="$effectiveAutoWares" exact="$_cmdAutoWares"/>
            <set_value name="$effectiveWareBasket" exact="$_cmdWareBasket"/>
            <set_value name="$effectiveDistancePenalty" exact="$_cmdDistancePenalty"/>
            <set_value name="$effectiveFleetCoordination" exact="$_cmdFleetCoord"/>
            <set_value name="$effectiveAllowIllegal" exact="$_cmdAllowIllegal"/>
            <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$_cmdIllegalRouteFilter"/>
            <set_value name="$effectiveFactionPriority" exact="0"/>
            <set_value name="$effectiveIgnoreCarrierAux" exact="$_cmdIgnoreCarrierAux"/>
            <set_value name="$effectiveIgnoreBuildStorage" exact="$_cmdIgnoreBuildStorage"/>
            <set_value name="$effectiveIgnoreTradeRules" exact="$_cmdIgnoreTradeRules"/>
            <set_value name="$effectiveIgnoreMK1Supply" exact="$_cmdIgnoreMK1Supply"/>
            <set_value name="$effectiveLogbookEntries" exact="$_cmdLogbookEntries"/>
            <set_value name="$effectiveNotifications" exact="$_cmdNotifications"/>
            <set_value name="$effectiveUseMinCargoThresholdFilter" exact="$_cmdUseMinCargoThresholdFilter"/>
            <set_value name="$effectiveCargoTarget" exact="$_cmdCargoTarget"/>
            <set_value name="$effectiveDebugLevel" exact="$_cmdDebugLevel"/>
            <set_value name="$effectiveTradeEval" exact="$_cmdTradeEval"/>
            <set_value name="$effectiveSectorWhitelist" exact="$_cmdSectorWhitelist"/>
            <set_value name="$mk4AllowResources" exact="$_cmdM4Res"/>
            <set_value name="$mk4AllowIntermediates" exact="$_cmdM4Int"/>
            <set_value name="$mk4AllowTradewares" exact="$_cmdM4Tw"/>
            <set_value name="$mk4AllowPlayerSuppliers" exact="$_cmdM4Aps"/>
            <set_value name="$mk4AllowAiSuppliers" exact="$_cmdM4Aas"/>
            <set_value name="$mk4DedicatedServe" exact="$_cmdM4Ded"/>
            <set_value name="this.$mk4AllowResources" exact="$mk4AllowResources"/>
            <set_value name="this.$mk4AllowIntermediates" exact="$mk4AllowIntermediates"/>
            <set_value name="this.$mk4AllowTradewares" exact="$mk4AllowTradewares"/>
            <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4AllowPlayerSuppliers"/>
            <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4AllowAiSuppliers"/>
            <set_value name="this.$mk4DedicatedServe" exact="$mk4DedicatedServe"/>
            <set_value name="$mk4BuildStorageOnlyMode" exact="false"/>
            <do_if value="not $effectiveIgnoreBuildStorage and not $mk4AllowResources and not $mk4AllowIntermediates and not $mk4AllowTradewares">
              <set_value name="$mk4BuildStorageOnlyMode" exact="true"/>
            </do_if>
            <set_value name="this.$mk4BuildStorageOnlyMode" exact="$mk4BuildStorageOnlyMode"/>
            <set_value name="$mk4PolicySigNow" exact="'DED=' + (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) + '|BSO=' + (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) + '|APS=' + (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true) + '|AAS=' + (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true) + '|RES=' + (if this.$mk4AllowResources? then this.$mk4AllowResources else true) + '|INT=' + (if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true) + '|TW=' + (if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true)"/>
            <set_value name="$mk4PolicyChangedInCmd" exact="not this.$lastMk4PolicySig? or this.$lastMk4PolicySig != $mk4PolicySigNow"/>
            <do_if value="$mk4PolicyChangedInCmd">
              <set_value name="$mk4PolicyHome" exact="$_cmdHome"/>
              <set_value name="$mk4PolicyHomeSector" exact="if $mk4PolicyHome? and $mk4PolicyHome.isclass.sector then $mk4PolicyHome else (if $mk4PolicyHome? and $mk4PolicyHome.sector? then @$mk4PolicyHome.sector else null)"/>
              <set_value name="$mk4PolicyCacheEmpty" exact="true"/>
              <do_if value="$mk4PolicyHomeSector? and $mk4PolicyHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}? and global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.count gt 0">
                <set_value name="$mk4PolicyCacheEmpty" exact="false"/>
              </do_if>
              <do_if value="$mk4PolicyCacheEmpty">
                <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="true"/>
              </do_if>
              <do_else>
                <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
                <!-- Policy widened but cache still valid â€” clear this ship from FailedShips only (do not nuke shared pool). -->
                <do_all exact="global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.count" counter="$polFsiCmd">
                  <set_value name="$polEntryCmd" exact="global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.{$polFsiCmd}"/>
                  <do_if value="$polEntryCmd? and $polEntryCmd.$FailedShips? and $polEntryCmd.$FailedShips.count gt 0">
                    <set_value name="$polNewFailedCmd" exact="[]"/>
                    <do_all exact="$polEntryCmd.$FailedShips.count" counter="$polFsi2Cmd">
                      <do_if value="$polEntryCmd.$FailedShips.{$polFsi2Cmd} != this.ship">
                        <append_to_list name="$polNewFailedCmd" exact="$polEntryCmd.$FailedShips.{$polFsi2Cmd}"/>
                      </do_if>
                    </do_all>
                    <set_value name="$polEntryCmd.$FailedShips" exact="$polNewFailedCmd"/>
                  </do_if>
                </do_all>
              </do_else>
            </do_if>
            <set_value name="this.$lastMk4PolicySig" exact="$mk4PolicySigNow"/>

            <!-- Home base affects distance filtering/scoring; ensure both local and persisted value update -->
            <do_if value="$_cmdHome?">
              <set_value name="$effectiveHome" exact="$_cmdHome"/>
              <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
            </do_if>

            <!-- Jump distance caps: disable in vanilla mode, cap in GT mode. -->
            <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
            <run_script name="'lib.gt.pathfinding'" result="$_pilotSkill">
              <param name="mode" value="'effective_pilot_level'"/>
              <param name="ship" value="this.ship"/>
              <param name="includeCommander" value="false"/>
            </run_script>
            <set_value name="$_pilotMaxJumps" exact="null"/>
            <do_if value="not $useVanillaXPOnly">
              <run_script name="'lib.gt.pathfinding'" result="$_pilotMaxJumps">
                <param name="mode" value="'pilot_max_jumps'"/>
                <param name="pilotSkill" value="$_pilotSkill"/>
              </run_script>
            </do_if>

            <do_if value="$_commanderOrderNow.$jumpDistanceBuy?">
              <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $_pilotMaxJumps == null then $_cmdMaxBuy else [$_cmdMaxBuy, $_pilotMaxJumps].min"/>
              <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
            </do_if>
            <do_if value="$_commanderOrderNow.$jumpDistanceCoverage?">
              <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $_pilotMaxJumps == null then $_cmdMaxSell else [$_cmdMaxSell, $_pilotMaxJumps].min"/>
              <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
            </do_if>

            <!-- Persist updated effective settings (survive save/load resume) -->
            <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
            <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
            <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
            <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
            <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
            <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
            <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
            <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
            <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
            <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
            <set_value name="this.$effectiveUseMinCargoThresholdFilter" exact="$effectiveUseMinCargoThresholdFilter"/>
            <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>

            <!-- Refresh derived variables used by the MD requests -->
            <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
            <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
            <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
            <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
            <set_value name="$gt_useMinCargoThreshold" exact="$effectiveUseMinCargoThresholdFilter"/>
            <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
            <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>

            <!-- CRITICAL: Drop stale trades awaiting validation produced under the previous commander settings.
                 Otherwise the AI can execute old trades (wrong ware filter, wrong distances, etc.) via stale data. -->
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
            </do_if>
            <!-- Clear interrupt flag when clearing trades awaiting validation (commander settings changed) -->
            <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
            <!-- Reset retry counter: we want a clean fresh request under the new settings -->
            <do_if value="this.$searchFailed?">
              <set_value name="this.$searchFailed" exact="0"/>
            </do_if>
          </do_if>

          <!-- Track last applied signature (always) -->
          <set_value name="this.$trackedCommanderSettingsSig" exact="$_commanderSettingsSig"/>
        </do_if>
      </do_if>
      
      <!-- Initialize retry counter if not exists -->
      <do_if value="not this.$searchFailed?">
        <set_value name="this.$searchFailed" exact="0"/>
      </do_if>

      <!-- Sync MK4 supply policy from live order object (UI edits update defaultorder, not this.$ copies). -->
      <set_value name="$mk4PolicyOrder" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
        <set_value name="$mk4PolicyOrder" exact="this.ship.commander.defaultorder"/>
      </do_if>
      <do_else>
        <set_value name="$mk4PolicyOrder" exact="if this.ship.defaultorder? then this.ship.defaultorder else null"/>
      </do_else>
      <do_if value="$mk4PolicyOrder? and @$mk4PolicyOrder.id == 'GalaxyTraderMK4Supply'">
        <do_if value="$mk4PolicyOrder.$allowBuildstorage?">
          <set_value name="this.$effectiveIgnoreBuildStorage" exact="not $mk4PolicyOrder.$allowBuildstorage"/>
          <set_value name="$effectiveIgnoreBuildStorage" exact="this.$effectiveIgnoreBuildStorage"/>
        </do_if>
        <do_if value="$mk4PolicyOrder.$allowResources?">
          <set_value name="this.$mk4AllowResources" exact="$mk4PolicyOrder.$allowResources"/>
        </do_if>
        <do_if value="$mk4PolicyOrder.$allowIntermediates?">
          <set_value name="this.$mk4AllowIntermediates" exact="$mk4PolicyOrder.$allowIntermediates"/>
        </do_if>
        <do_if value="$mk4PolicyOrder.$allowTradewares?">
          <set_value name="this.$mk4AllowTradewares" exact="$mk4PolicyOrder.$allowTradewares"/>
        </do_if>
        <do_if value="$mk4PolicyOrder.$buyFromPlayer?">
          <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4PolicyOrder.$buyFromPlayer"/>
        </do_if>
        <do_elseif value="$mk4PolicyOrder.$allowPlayerSuppliers?">
          <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4PolicyOrder.$allowPlayerSuppliers"/>
        </do_elseif>
        <do_if value="$mk4PolicyOrder.$buyFromFaction?">
          <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4PolicyOrder.$buyFromFaction"/>
        </do_if>
        <do_elseif value="$mk4PolicyOrder.$allowAiSuppliers?">
          <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4PolicyOrder.$allowAiSuppliers"/>
        </do_elseif>
        <do_if value="$mk4PolicyOrder.$serveHomeOnly?">
          <set_value name="this.$mk4DedicatedServe" exact="$mk4PolicyOrder.$serveHomeOnly"/>
        </do_if>
        <do_elseif value="$mk4PolicyOrder.$dedicatedServe?">
          <set_value name="this.$mk4DedicatedServe" exact="$mk4PolicyOrder.$dedicatedServe"/>
        </do_elseif>
        <set_value name="this.$mk4BuildStorageOnlyMode" exact="false"/>
        <do_if value="not this.$effectiveIgnoreBuildStorage and not this.$mk4AllowResources and not this.$mk4AllowIntermediates and not this.$mk4AllowTradewares">
          <set_value name="this.$mk4BuildStorageOnlyMode" exact="true"/>
        </do_if>
        <set_value name="$mk4PolicySigNow" exact="'DED=' + (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) + '|BSO=' + (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) + '|APS=' + (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true) + '|AAS=' + (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true) + '|RES=' + (if this.$mk4AllowResources? then this.$mk4AllowResources else true) + '|INT=' + (if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true) + '|TW=' + (if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true)"/>
        <set_value name="$mk4PolicyChangedNow" exact="this.$lastMk4PolicySig? and this.$lastMk4PolicySig != $mk4PolicySigNow"/>
        <do_if value="$mk4PolicyChangedNow">
          <set_value name="$mk4PolicyHome" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder? and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector)"/>
          <set_value name="$mk4PolicyHomeSector" exact="if $mk4PolicyHome? and $mk4PolicyHome.isclass.sector then $mk4PolicyHome else (if $mk4PolicyHome? and $mk4PolicyHome.sector? then @$mk4PolicyHome.sector else null)"/>
          <set_value name="$mk4PolicyCacheEmpty" exact="true"/>
          <do_if value="$mk4PolicyHomeSector? and $mk4PolicyHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}? and global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.count gt 0">
            <set_value name="$mk4PolicyCacheEmpty" exact="false"/>
          </do_if>
          <do_if value="$mk4PolicyCacheEmpty">
            <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="true"/>
          </do_if>
          <do_else>
            <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
            <!-- Policy widened but cache still valid â€” clear this ship from FailedShips on all home entries. -->
            <do_all exact="global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.count" counter="$polFsi">
              <set_value name="$polEntry" exact="global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.{$polFsi}"/>
              <do_if value="$polEntry? and $polEntry.$FailedShips? and $polEntry.$FailedShips.count gt 0">
                <set_value name="$polNewFailed" exact="[]"/>
                <do_all exact="$polEntry.$FailedShips.count" counter="$polFsi2">
                  <do_if value="$polEntry.$FailedShips.{$polFsi2} != this.ship">
                    <append_to_list name="$polNewFailed" exact="$polEntry.$FailedShips.{$polFsi2}"/>
                  </do_if>
                </do_all>
                <set_value name="$polEntry.$FailedShips" exact="$polNewFailed"/>
              </do_if>
            </do_all>
          </do_else>
        </do_if>
        <set_value name="this.$lastMk4PolicySig" exact="$mk4PolicySigNow"/>
      </do_if>

      <!-- Handle pending scheduler grant before issuing a fresh request.
           This closes a timing gap where GT_Search_Go can arrive before wait_for_response is active. -->
      <do_if value="this.$pendingSearchParams? and this.$pendingSearchParams != null and typeof this.$pendingSearchParams == datatype.table">
        <set_value name="this.$searchGoViaInterrupt" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$pendingPhaseNow" exact="if this.$pendingSearchParams.$Phase? then @this.$pendingSearchParams.$Phase else 'unknown'"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Processing pending GT_Search_Go before new request (phase=' + $pendingPhaseNow + ')'" chance="100"/>
        </do_if>
        <resume label="run_search_pipeline"/>
      </do_if>
      
      <!-- Signal MD system for trade opportunities -->
      <!-- Check if ship already has trade orders BEFORE requesting new trade -->
      <set_value name="$hasTradeOrders" exact="false"/>
      <do_if value="this.ship.tradeorders? and this.ship.tradeorders.count gt 0">
        <set_value name="$hasTradeOrders" exact="true"/>
      </do_if>
      
      <do_if value="$hasTradeOrders">
        <!-- Ship already has pending trade orders - wait instead of requesting more -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Ship already has ' + this.ship.tradeorders.count + ' trade orders - waiting for completion'" chance="100"/>
        </do_if>
        
        <!-- Wait for trade completion -->
        <wait max="10s">
          <interrupt>
            <conditions>
              <check_any>
                <event_object_signalled object="this.ship" param="'GT_Trade_Completed'"/>
                <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
              </check_any>
            </conditions>
            <actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade order completed early - checking status immediately'" chance="100"/>
              </do_if>
            </actions>
          </interrupt>
        </wait>
        <resume label="main_loop"/>
      </do_if>
      <do_else>
        <!-- Ship ready for new trade - ensure ship is registered before requesting trade search -->
        <!-- This is critical when pilot is transferred to a new ship -->
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
          <!-- Ship not registered yet - wait a moment for registration to complete -->
          <!-- Registration happens via GT_Register_Ship signal handled by gt_core_system.HandleShipRegistration -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship not yet registered - waiting for registration to complete...'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Wait for registration using a top-level loop (no waits inside conditionals).
             Bounded to prevent the prior unbounded spin: 20*500ms = 10s, then re-fire GT_Register_Ship
             once (queue stall / lost signal recovery) and give the queue another 10*500ms = 5s.
             If still missing, bounce back to main_loop so the next iteration can retry instead of
             spinning the AI block forever. Counter is on `this.` because locals are lost across <wait>. -->
        <set_value name="this.$regSpinCount" exact="0"/>
        <do_while value="(not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?) and this.$regSpinCount lt 20">
          <wait exact="500ms"/>
          <set_value name="this.$regSpinCount" operation="add"/>
        </do_while>
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARN Registration missing after 10s spin - re-emitting GT_Register_Ship'" chance="100"/>
          <signal_objects object="player.galaxy" param="'GT_Register_Ship'" param2="table[$Ship = this.ship, $Config = table[]]"/>
          <set_value name="this.$regSpinCount" exact="0"/>
          <do_while value="(not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?) and this.$regSpinCount lt 10">
            <wait exact="500ms"/>
            <set_value name="this.$regSpinCount" operation="add"/>
          </do_while>
          <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARN Registration still missing after retry - bouncing to main_loop'" chance="100"/>
            <remove_value name="this.$regSpinCount"/>
            <resume label="main_loop"/>
          </do_if>
        </do_if>
        <remove_value name="this.$regSpinCount"/>
        
        <!-- Check cargo status -->
        <!-- Only trade if cargo is EMPTY -->
        <set_value name="$hasCargo" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
        
        <do_if value="$hasCargo">
          <!-- Ship has cargo - sell it first using our trade search -->
          <!-- CARGO DISPOSAL: Only log initial message once (prevent spam) -->
          <set_value name="$isFirstCargoDisposalAttempt" exact="false"/>
          <do_if value="not this.$cargoDisposalFailed? or this.$cargoDisposalFailed == 0">
            <set_value name="$isFirstCargoDisposalAttempt" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship has cargo - finding best buyer using trade search...'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Set cargo disposal flag for ship name -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
            <set_value name="global.$GT_Ships.{this.ship}.$CargoDisposal" exact="true"/>
          </do_if>
          
          <!-- Trigger ship rename to show [CLEARANCE] state -->
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship=this.ship, 
              $pilot=this.ship.pilot, 
              $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
              $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType='trader'
            ]"/>
          </do_if>
          
          <!-- Write logbook entry about cargo safety - ONLY ON FIRST ATTEMPT -->
          <do_if value="$isFirstCargoDisposalAttempt and $gt_logbookentries">
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3204}.[this.ship.knownname]"/>
            
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'tips',
              $Title = 'Cargo Safety: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
          </do_if>
          
          <!-- effectiveXxx variables initialized in <init> block -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': CARGO DISPOSAL: Sending GT_Find_Sell at age ' + player.age + ' (MaxSell=' + (if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1)) + ' jumps)'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Find_Sell'" param2="table[
            $Ship = this.ship,
            $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
            $MaxSell = if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1),
            $DistancePenalty = @this.$effectiveDistancePenalty,
            $FleetCoordination = @this.$effectiveFleetCoordination,
            $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
            $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
            $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
            $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true
          ]"/>
        </do_if>
        <do_else>
          <!-- Ship cargo is EMPTY - look for buy opportunities -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cargo empty - looking for trade opportunities...'" chance="100"/>
          </do_if>

          <!-- Clear cargo disposal flag (cargo is now empty) -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal? and this.ship.cargo.count == 0">
            <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
            
            <!-- CARGO DISPOSAL: Reset cargo disposal failure counter when cargo is cleared -->
            <do_if value="this.$cargoDisposalFailed?">
              <set_value name="this.$cargoDisposalFailed" exact="0"/>
            </do_if>
            
            <!-- Trigger ship rename to remove [CLEARANCE] state -->
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship, 
                $pilot=this.ship.pilot, 
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>
          
          <!-- ==================================================================================== -->
          <!-- MECHANIC 2: Early money gate - skip entire trade search pipeline when player is broke -->
          <!-- Threshold: MinPlayerMoney + 1000 Cr safety buffer.                                   -->
          <!-- This prevents the expensive cache search / work loop from running when there is      -->
          <!-- no meaningful budget left. Ships go directly to insufficient_funds cooldown.          -->
          <!-- Works with MECHANIC 1 (authoritative guard budget clamp at trade creation):           -->
          <!--   Mechanic 1 = clamp trade volume to fit budget  (trade creation)                    -->
          <!--   Mechanic 2 = stop searching when budget is exhausted (search start)                -->
          <!-- ==================================================================================== -->
          <set_value name="$earlyMoneyCheck" exact="player.money"/>
          <do_if value="not this.$minPlayerMoney?">
            <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
          </do_if>
          <set_value name="$moneyGateThreshold" exact="(this.$minPlayerMoney + 1000)Cr"/>
          <do_if value="$earlyMoneyCheck le $moneyGateThreshold">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': EARLY MONEY GATE: player money=' + ($earlyMoneyCheck / 100) + ' Cr at or below threshold=' + (this.$minPlayerMoney + 1000) + ' Cr (MinPlayerMoney=' + this.$minPlayerMoney + ' + 1000 buffer) - skipping trade search'" chance="100"/>
            <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
            <resume label="no_trade_retry"/>
          </do_if>
          
          <!-- GLOBAL MONEY CAP heal: reaching this line means we already passed the early money
               gate above, so player.money is greater than MinPlayerMoney + 1000 Cr (i.e. the
               fleet is solvent). The fleet-wide cap is only meaningful while the player is broke,
               and that case is already handled by the early gate. Clearing it here prevents a
               solvent fleet from staying frozen on a stale wealth snapshot (the cap could have
               been recorded at a higher balance than the player currently holds). The per-trade
               authoritative budget guard still blocks any individual unaffordable trade. -->
          <do_if value="global.$GT_MoneyCapActive? and global.$GT_MoneyCapActive">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP CLEARED (solvent): player money=' + ($earlyMoneyCheck / 100) + ' Cr above gate threshold (' + ($moneyGateThreshold / 100) + ' Cr) - resuming fleet trade searches'" chance="100"/>
            </do_if>
            <set_value name="global.$GT_MoneyCapActive" exact="false"/>
            <remove_value name="global.$GT_MoneyCapMoney"/>
          </do_if>
          
          <!-- Wait briefly for any pending GT_Trade_Found signals before sending new request.
               Configured delay + 5ms buffer. If signal arrives during wait, interrupt processes it. -->
          <set_value name="$signalDelayMs" exact="0"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay?">
            <set_value name="$tmpDelay" exact="@global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay"/>
            <do_if value="$tmpDelay ge 0 and $tmpDelay le 1000">
              <set_value name="$signalDelayMs" exact="$tmpDelay"/>
            </do_if>
          </do_if>
          <set_value name="this.$tradeFoundSignalWaitTime" exact="($signalDelayMs + 5) * 1ms"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Waiting ' + ($signalDelayMs + 5) + 'ms for GT_Trade_Found signal (delay=' + $signalDelayMs + 'ms + 5ms buffer)'" chance="100"/>
          </do_if>
          <wait max="if @this.$tradeFoundSignalWaitTime != null then @this.$tradeFoundSignalWaitTime else 5ms" comment="Wait for pending GT_Trade_Found signals">
            <interrupt>
              <conditions>
                <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
              </conditions>
              <actions>
                <!-- Capture signal payload before resuming so trade_found gets the correct source/list -->
                <set_value name="$intSignalData" exact="event.param2"/>
                <set_value name="$intSignalTradeList" exact="[]"/>
                <set_value name="$intSignalSearchMethod" exact="''"/>
                <do_if value="$intSignalData? and $intSignalData != null">
                  <set_value name="$intSignalTradeList" exact="@$intSignalData.$TradeList"/>
                  <set_value name="$intSignalSearchMethod" exact="@$intSignalData.$SearchMethod"/>
                </do_if>
                <set_value name="this.$tradeListFromSignal" exact="$intSignalTradeList"/>
                <set_value name="this.$searchMethodFromSignal" exact="if $intSignalSearchMethod != null and $intSignalSearchMethod != '' then $intSignalSearchMethod else ''"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received during pre-request wait - stored ' + (if $intSignalTradeList != null then $intSignalTradeList.count else 0) + ' trades from interrupt payload'" chance="100"/>
                </do_if>
                <!-- Signal received - jump to trade_found label to process it -->
                <resume label="trade_found"/>
              </actions>
            </interrupt>
          </wait>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-request wait completed - no signal received, sending new request'" chance="100"/>
          </do_if>
          
          <!-- effectiveXxx variables initialized in <init> block -->
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SENDING GT_Search_Request signal to MD at game time ' + player.age" chance="100"/>
          </do_if>
          <set_value name="$requestForceLiveSearch" exact="false"/>
          <set_value name="$requestLiveSearchPriority" exact="false"/>
          <do_if value="this.$mk4PolicyNeedsLiveSearch? and this.$mk4PolicyNeedsLiveSearch">
            <set_value name="$mk4PolicyHomeBase" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector)"/>
            <set_value name="$mk4PolicyHomeSector" exact="if $mk4PolicyHomeBase? and $mk4PolicyHomeBase.isclass.sector then $mk4PolicyHomeBase else (if $mk4PolicyHomeBase? and $mk4PolicyHomeBase.sector? then @$mk4PolicyHomeBase.sector else null)"/>
            <set_value name="$mk4PolicyCacheEmpty" exact="true"/>
            <do_if value="$mk4PolicyHomeSector? and $mk4PolicyHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}? and global.$GT_TradeCacheMK4.{$mk4PolicyHomeSector}.count gt 0">
              <set_value name="$mk4PolicyCacheEmpty" exact="false"/>
            </do_if>
            <do_if value="$mk4PolicyCacheEmpty">
              <set_value name="$requestForceLiveSearch" exact="true"/>
              <set_value name="$requestLiveSearchPriority" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="this.$forceLiveAfterLiveReject? and this.$forceLiveAfterLiveReject">
            <set_value name="$requestForceLiveSearch" exact="true"/>
            <set_value name="$requestLiveSearchPriority" exact="true"/>
            <set_value name="this.$forceLiveAfterLiveReject" exact="false"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
            $Ship = this.ship,
            $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
            $MaxBuy = if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else (if $jumpDistanceBuy? then $jumpDistanceBuy else 1),
            $MaxSell = if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1),
            $CargoTarget = $gt_cargotarget,
            $WareBasket = $warebasket,
            $AllowIllegal = $gt_allowillegal,
            $EnforceRouteIllegalLegality = $gt_enforceRouteIllegalLegality,
            $FactionPriority = $gt_factionpriority,
            $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
            $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
            $DistancePenalty = @this.$effectiveDistancePenalty,
            $FleetCoordination = @this.$effectiveFleetCoordination,
            $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
            $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
            $SearchPool = 'mk4_supply',
            $SearchDepth = if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30,
            $ForceLiveSearch = $requestForceLiveSearch,
            $LiveSearchPriority = $requestLiveSearchPriority
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Search_Request signal SENT, now at game time ' + player.age" chance="100"/>
          </do_if>
        </do_else>
      </do_else>
      
      <!-- Wait for MD system response with interrupt -->
      <!-- Under large fleets, queued MK4 live-slot dispatch can exceed 60s.
           Use a wider timeout to avoid premature abort/requeue churn while still recovering from deadlocks. -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Entering wait state for MD response at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- Clear previous no-trade reason (prevents stale reason affecting timeout retry logic) -->
      <set_value name="this.$lastNoTradeReason" exact="''"/>
      <label name="wait_for_response"/>
      <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
      <label name="wait_for_response_continue"/>
      <do_if value="not this.$waitForResponseStartedAt?">
        <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
      </do_if>
      <do_if value="(player.age - this.$waitForResponseStartedAt) ge 120s">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT: 120s expired without semaphore grant (GT_Search_Go) at game time ' + player.age + ' â€” cleaning up queue entry and retrying'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
        <resume label="no_trade_retry"/>
      </do_if>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Wait interrupt handler ACTIVE at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- IMPORTANT: In X4, wait without min is RANDOM (0..max). Use min=max to avoid instant timeouts.
           Guard startedAt for save-load resume mid-wait (instance var may be absent on older saves). -->
      <wait min="if this.$waitForResponseStartedAt? then (if (120s - (player.age - this.$waitForResponseStartedAt)) gt 1ms then (120s - (player.age - this.$waitForResponseStartedAt)) else 1ms) else 120s" max="if this.$waitForResponseStartedAt? then (if (120s - (player.age - this.$waitForResponseStartedAt)) gt 1ms then (120s - (player.age - this.$waitForResponseStartedAt)) else 1ms) else 120s" comment="Wait for MD system response (120s total; interrupted immediately on response)">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
              <event_object_signalled object="this.ship" param="'GT_No_Trade_Found'"/>
              <!-- Duplicate request while MD search lock is still held:
                   MD responds with a non-backoff "still working" or "reset" signal to prevent AI cooldown escalation under fleet load. -->
              <event_object_signalled object="this.ship" param="'GT_TradeSearch_InProgress'"/>
              <event_object_signalled object="this.ship" param="'GT_TradeSearch_Reset'"/>
              <!-- New AI pipeline semaphore grant -->
              <event_object_signalled object="this.ship" param="'GT_Search_Go'"/>
            </check_any>
          </conditions>
          <actions>
            <do_if value="event.param == 'GT_Search_Go'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_Search_Go received at age ' + player.age + ' - queueing AI search pipeline'" chance="100"/>
              </do_if>
              <!-- Persist interrupt payload across wait/resume boundaries. -->
              <set_value name="this.$pendingSearchParams" exact="event.param2"/>
              <resume label="run_search_pipeline"/>
            </do_if>
            <do_elseif value="event.param == 'GT_Trade_Found'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_Trade_Found received at game time ' + player.age" chance="100"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade found by MD system - proceeding with execution'" chance="100"/>
              </do_if>
              <!-- Reset retry counter on successful trade -->
              <set_value name="this.$searchFailed" exact="0"/>
              <do_if value="global.$GT_IdleParkingReleased? and global.$GT_IdleParkingReleased.{this.ship}?">
                <remove_value name="global.$GT_IdleParkingReleased.{this.ship}"/>
              </do_if>
              <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
                <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>
                <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>
              </do_if>
              
              <!-- Clear per-ship no-trade attempt history on success (prevents stale attempts from polluting later reports) -->
              <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
                <remove_value name="global.$GT_NoTradeHistory.{this.ship}"/>
              </do_if>
              
              <!-- CARGO DISPOSAL: Reset cargo disposal failure counter on successful trade -->
              <do_if value="this.$cargoDisposalFailed?">
                <set_value name="this.$cargoDisposalFailed" exact="0"/>
              </do_if>
              
              <!-- Clear reroute flag (new destination found) -->
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Rerouting?">
                <remove_value name="global.$GT_Ships.{this.ship}.$Rerouting"/>
                
                <!-- Trigger ship rename to remove [REROUTE] state -->
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship, 
                    $pilot=this.ship.pilot, 
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
              </do_if>
              
              <resume label="trade_found"/>
            </do_elseif>
            <do_elseif value="event.param == 'GT_TradeSearch_InProgress'">
              <do_if value="not this.$waitForResponseStartedAt?">
                <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
              </do_if>
              <do_if value="(player.age - this.$waitForResponseStartedAt) ge 120s">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT after InProgress keepalives (120s) - aborting search and retrying'" chance="100"/>
                </do_if>
                <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
                <resume label="main_loop"/>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_TradeSearch_InProgress received at game time ' + player.age + ' - continuing to wait (no backoff)'" chance="100"/>
                </do_if>
                <resume label="wait_for_response_continue"/>
              </do_else>
            </do_elseif>
            <do_elseif value="event.param == 'GT_TradeSearch_Reset'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_TradeSearch_Reset received at game time ' + player.age + ' - retrying request immediately (no backoff)'" chance="100"/>
              </do_if>
              <!-- Stay in scheduler wait when already queued/active â€” avoid duplicate cache requests that lose mk4live queue position. -->
              <set_value name="$resetStillScheduled" exact="false"/>
              <do_if value="global.$GT_SearchSemaphore?">
                <do_if value="global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.count gt 0">
                  <set_value name="$resetWaiterHomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.list"/>
                  <do_all exact="$resetWaiterHomeKeys.count" counter="$rwhi">
                    <set_value name="$rwhHome" exact="$resetWaiterHomeKeys.{$rwhi}"/>
                    <do_if value="$rwhHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$rwhHome}?">
                      <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$rwhHome}.count" counter="$rwwi">
                        <do_if value="@global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$rwhHome}.{$rwwi} == this.ship">
                          <set_value name="$resetStillScheduled" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    <do_if value="$resetStillScheduled">
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
              <do_if value="$resetStillScheduled">
                <resume label="wait_for_response_continue"/>
              </do_if>
              <do_else>
                <resume label="main_loop"/>
              </do_else>
            </do_elseif>
            <do_elseif value="event.param == 'GT_No_Trade_Found'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_No_Trade_Found received at age ' + player.age + ' (reason=' + (if event.param2? then event.param2 else '') + ')'" chance="100"/>
              </do_if>
              <!-- Capture reason (MD may pass param2='busy' for cache-search slots busy, etc.) -->
              <set_value name="this.$lastNoTradeReason" exact="if event.param2? and event.param2 != null then event.param2 else ''"/>
              <!-- Isolated mode is intra-sector by design; UR is not meaningful there. -->
              <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}? and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
                <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
              </do_if>
              <!-- ESCAPE FALLBACK:
                   If we are stuck in a blacklisted sector and got "no trade found", move toward home sector
                   (skipping blacklisted sectors along the route until we hit a non-blacklisted sector OR the home sector).
                   Whitelist overrides blacklist (matches GT_IsSectorBlacklisted). -->
              <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <set_value name="$validationWhitelist" exact="[]"/>
              <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
              </do_if>
              <set_value name="$currentSector" exact="this.ship.sector"/>
              <set_value name="$needsEscape" exact="false"/>
              <do_if value="$currentSector? and $currentSector.exists">
                <set_value name="$curWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                      <set_value name="$curWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $curWhitelisted">
                  <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$needsEscape" exact="$curActivityBL or $curTravelBL"/>
                </do_if>
              </do_if>
              <do_if value="$needsEscape">
                <!-- Set escape flag for ship naming -->
                <do_if value="global.$GT_Ships?">
                  <do_if value="not global.$GT_Ships.{this.ship}?">
                    <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
                </do_if>
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: No trade found while in blacklisted sector (' + @$currentSector.knownname + ') - moving toward home sector'" chance="100"/>
                </do_if>
                <resume label="escape_from_blacklisted"/>
              </do_if>
              
              <!-- Check if this is a cargo disposal attempt -->
              <set_value name="$isCargoDisposal" exact="false"/>
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
                <set_value name="$isCargoDisposal" exact="true"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': RECEIVED GT_No_Trade_Found signal - starting retry logic (cargo disposal: ' + $isCargoDisposal + ')'" chance="100"/>
              </do_if>
              <resume label="no_trade_retry"/>
            </do_elseif>
          </actions>
        </interrupt>
      </wait>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           TIMEOUT GUARD: If execution reaches here, the 120s wait expired WITHOUT
           any interrupt firing. The ship NEVER received GT_Search_Go from the
           semaphore. We MUST NOT fall through to run_search_pipeline â€” that would
           bypass the semaphore and allow unlimited concurrent live searches.
           Clean up the pending queue entry and retry with cooldown.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT: 120s expired without semaphore grant (GT_Search_Go) at game time ' + player.age + ' â€” cleaning up queue entry and retrying'" chance="100"/>
      </do_if>
      <!-- Remove this ship from the scheduler queue so it doesn't block the slot -->
      <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
      <resume label="no_trade_retry"/>

      <label name="run_search_pipeline"/>
      <set_value name="$searchParams" exact="if this.$pendingSearchParams? then this.$pendingSearchParams else null"/>
      <set_value name="this.$pendingSearchParams" exact="null"/>
      <!-- Belt-and-suspenders: verify $searchParams is a real table, not null.
           X4's '?' operator can return true for set_value-created variables even when null.
           Use typeof check to ensure we have actual search parameters from GT_Search_Go. -->
      <do_if value="typeof $searchParams == datatype.table">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Running AI search pipeline (semaphore-granted) at game time ' + player.age" chance="100"/>
        </do_if>

        <set_value name="$searchHome" exact="if $searchParams.$HomeBase? then @$searchParams.$HomeBase else (if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null))"/>
        <set_value name="$searchHomeSector" exact="if $searchParams.$HomeSector? then @$searchParams.$HomeSector else (if $searchHome? and $searchHome.isclass.sector then $searchHome else (if $searchHome? and $searchHome.sector? then @$searchHome.sector else this.ship.sector))"/>
        <!-- Dual-radius: MaxSell = delivery/need coverage, MaxBuy = supplier leg; pathfinding/live need max of both. -->
        <set_value name="$searchMaxSell" exact="if $searchParams.$MaxSell? then @$searchParams.$MaxSell else (if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1))"/>
        <set_value name="$searchMaxBuy" exact="if $searchParams.$MaxBuy? then @$searchParams.$MaxBuy else (if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else 0)"/>
        <set_value name="$searchRadiusMax" exact="[$searchMaxBuy, $searchMaxSell].max"/>
        <!-- Legacy name: single radius for logs/fallback centering (use combined reach) -->
        <set_value name="$searchMaxDistance" exact="$searchRadiusMax"/>
        <set_value name="$searchWareBasket" exact="if $searchParams.$WareBasket? then @$searchParams.$WareBasket else $warebasket"/>
        <set_value name="$searchAllowIllegal" exact="if $searchParams.$AllowIllegal? then @$searchParams.$AllowIllegal else $gt_allowillegal"/>
        <set_value name="$searchEnforceRouteIllegalLegality" exact="if $searchParams.$EnforceRouteIllegalLegality? then @$searchParams.$EnforceRouteIllegalLegality else $gt_enforceRouteIllegalLegality"/>
        <set_value name="$searchIgnoreTradeRules" exact="if $searchParams.$IgnoreTradeRules? then @$searchParams.$IgnoreTradeRules else $effectiveIgnoreTradeRules"/>
        <set_value name="$searchIgnoreMK1Supply" exact="if $searchParams.$IgnoreMK1Supply? then @$searchParams.$IgnoreMK1Supply else $effectiveIgnoreMK1Supply"/>
        <set_value name="$searchIgnoreBuildStorage" exact="if $searchParams.$IgnoreBuildStorage? then @$searchParams.$IgnoreBuildStorage else $effectiveIgnoreBuildStorage"/>
        <set_value name="$searchIgnoreCarrierAux" exact="if $searchParams.$IgnoreCarrierAux? then @$searchParams.$IgnoreCarrierAux else $effectiveIgnoreCarrierAux"/>
        <set_value name="$searchFactionPriority" exact="0"/>
        <set_value name="$searchMode" exact="if $searchParams.$SearchMode? then @$searchParams.$SearchMode else 'buy_and_sell'"/>
        <set_value name="$forceLiveSearch" exact="if $searchParams.$ForceLiveSearch? then @$searchParams.$ForceLiveSearch else false"/>
        <set_value name="$searchPhase" exact="if $searchParams.$Phase? then @$searchParams.$Phase else 'live'"/>
        <set_value name="$skipCacheRead" exact="false"/>
        <set_value name="$mk4HomeCacheCount" exact="0"/>
        <do_if value="$searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$searchHomeSector}?">
          <set_value name="$mk4HomeCacheCount" exact="@global.$GT_TradeCacheMK4.{$searchHomeSector}.count"/>
        </do_if>
        <!-- Only skip cache re-read when prior cache phase missed AND pool is still empty. -->
        <do_if value="$searchParams.$CachePhaseMiss? and $searchParams.$CachePhaseMiss and $mk4HomeCacheCount == 0">
          <set_value name="$skipCacheRead" exact="true"/>
        </do_if>
        <!-- mk4live/live slot: after cache phase miss, force live refresh instead of retrying a dead pool. -->
        <do_if value="$searchPhase == 'live' or $searchPhase == 'mk4live'">
          <do_if value="($searchParams.$ForceLiveSearch? and $searchParams.$ForceLiveSearch) or $mk4HomeCacheCount == 0">
            <set_value name="$forceLiveSearch" exact="true"/>
          </do_if>
          <do_elseif value="$searchParams.$CachePhaseMiss? and $searchParams.$CachePhaseMiss">
            <set_value name="$forceLiveSearch" exact="true"/>
          </do_elseif>
          <do_else>
            <set_value name="$forceLiveSearch" exact="false"/>
          </do_else>
        </do_if>

        <!-- MK4 supply: score + price profile gate trades â€” no pilot ROI or profit floor. -->
        <set_value name="$searchMinROI" exact="0"/>
        <set_value name="$searchMinAbsoluteProfit" exact="0"/>

        <!-- Priority wares change detection:
             only clear cache when an existing signature changed (real order-setup delta).
             First-time baseline initialization must not invalidate cache. -->
        <!-- Belt-and-suspenders: re-sync MK4 policy from live order before cache/live (diag reads defaultorder; this.$ can lag UI edits). -->
        <set_value name="$mk4PolicyOrder" exact="null"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
          <set_value name="$mk4PolicyOrder" exact="this.ship.commander.defaultorder"/>
        </do_if>
        <do_else>
          <set_value name="$mk4PolicyOrder" exact="if this.ship.defaultorder? then this.ship.defaultorder else null"/>
        </do_else>
        <do_if value="$mk4PolicyOrder? and @$mk4PolicyOrder.id == 'GalaxyTraderMK4Supply'">
          <do_if value="$mk4PolicyOrder.$allowBuildstorage?">
            <set_value name="this.$effectiveIgnoreBuildStorage" exact="not $mk4PolicyOrder.$allowBuildstorage"/>
            <set_value name="$effectiveIgnoreBuildStorage" exact="this.$effectiveIgnoreBuildStorage"/>
          </do_if>
          <do_if value="$mk4PolicyOrder.$allowResources?">
            <set_value name="this.$mk4AllowResources" exact="$mk4PolicyOrder.$allowResources"/>
          </do_if>
          <do_if value="$mk4PolicyOrder.$allowIntermediates?">
            <set_value name="this.$mk4AllowIntermediates" exact="$mk4PolicyOrder.$allowIntermediates"/>
          </do_if>
          <do_if value="$mk4PolicyOrder.$allowTradewares?">
            <set_value name="this.$mk4AllowTradewares" exact="$mk4PolicyOrder.$allowTradewares"/>
          </do_if>
          <do_if value="$mk4PolicyOrder.$buyFromPlayer?">
            <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4PolicyOrder.$buyFromPlayer"/>
          </do_if>
          <do_elseif value="$mk4PolicyOrder.$allowPlayerSuppliers?">
            <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4PolicyOrder.$allowPlayerSuppliers"/>
          </do_elseif>
          <do_if value="$mk4PolicyOrder.$buyFromFaction?">
            <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4PolicyOrder.$buyFromFaction"/>
          </do_if>
          <do_elseif value="$mk4PolicyOrder.$allowAiSuppliers?">
            <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4PolicyOrder.$allowAiSuppliers"/>
          </do_elseif>
          <do_if value="$mk4PolicyOrder.$serveHomeOnly?">
            <set_value name="this.$mk4DedicatedServe" exact="$mk4PolicyOrder.$serveHomeOnly"/>
          </do_if>
          <do_elseif value="$mk4PolicyOrder.$dedicatedServe?">
            <set_value name="this.$mk4DedicatedServe" exact="$mk4PolicyOrder.$dedicatedServe"/>
          </do_elseif>
        </do_if>
        <set_value name="$pwSig" exact="'0|' + (if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125)"/>
        <do_if value="$effectivePriorityWares? and typeof $effectivePriorityWares == datatype.list and $effectivePriorityWares.count gt 0">
          <set_value name="$pwSig" exact="'' + $effectivePriorityWares.count + '|' + (if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125) + '|'"/>
          <do_all exact="$effectivePriorityWares.count" counter="$pwi">
            <set_value name="$pw" exact="$effectivePriorityWares.{$pwi}"/>
            <set_value name="$pwSig" exact="$pwSig + (if $pwi gt 1 then ',' else '') + (if $pw? and $pw != null and $pw.id? then @$pw.id else '?')"/>
          </do_all>
        </do_if>
        <set_value name="$priorityWaresChanged" exact="this.$lastPriorityWaresSig? and this.$lastPriorityWaresSig != $pwSig"/>
        <!-- Re-derive implicit build-storage-only mode before each search (toggle combo may have changed). -->
        <set_value name="this.$mk4BuildStorageOnlyMode" exact="false"/>
        <do_if value="not this.$effectiveIgnoreBuildStorage and not this.$mk4AllowResources and not this.$mk4AllowIntermediates and not this.$mk4AllowTradewares">
          <set_value name="this.$mk4BuildStorageOnlyMode" exact="true"/>
        </do_if>
        <!-- Also invalidate cache when MK4 policy knobs change, so cache/live behavior stays consistent. -->
        <set_value name="$mk4PolicySig" exact="'DED=' + (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) + '|BSO=' + (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) + '|APS=' + (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true) + '|AAS=' + (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true) + '|RES=' + (if this.$mk4AllowResources? then this.$mk4AllowResources else true) + '|INT=' + (if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true) + '|TW=' + (if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true)"/>
        <set_value name="$mk4PolicyChanged" exact="this.$lastMk4PolicySig? and this.$lastMk4PolicySig != $mk4PolicySig"/>
        <set_value name="$invalidateSearchCache" exact="$priorityWaresChanged"/>
        <do_if value="$priorityWaresChanged and $searchHomeSector? and $searchHomeSector.exists">
          <!-- Priority-ware signature changed: home cache may no longer match basket â€” clear MK4 pool only. -->
          <do_if value="global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$searchHomeSector}?">
            <remove_value name="global.$GT_TradeCacheMK4.{$searchHomeSector}"/>
            <do_if value="global.$GT_TradeCacheMK4ByWare? and global.$GT_TradeCacheMK4ByWare.{$searchHomeSector}?">
              <remove_value name="global.$GT_TradeCacheMK4ByWare.{$searchHomeSector}"/>
            </do_if>
            <do_if value="global.$GT_TradeCacheMK4MaxDistance? and global.$GT_TradeCacheMK4MaxDistance.{$searchHomeSector}?">
              <remove_value name="global.$GT_TradeCacheMK4MaxDistance.{$searchHomeSector}"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': priority wares changed - cleared cache for home sector ' + (if $searchHomeSector.knownname? then @$searchHomeSector.knownname else '?') + ' (next search will run live)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$mk4PolicyChanged and $searchHomeSector? and $searchHomeSector.exists">
          <set_value name="$mk4PolicyCacheEmpty" exact="true"/>
          <do_if value="global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$searchHomeSector}? and global.$GT_TradeCacheMK4.{$searchHomeSector}.count gt 0">
            <set_value name="$mk4PolicyCacheEmpty" exact="false"/>
          </do_if>
          <do_if value="$mk4PolicyCacheEmpty">
            <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="true"/>
          </do_if>
          <do_else>
            <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
            <do_all exact="global.$GT_TradeCacheMK4.{$searchHomeSector}.count" counter="$polFsiPipe">
              <set_value name="$polEntryPipe" exact="global.$GT_TradeCacheMK4.{$searchHomeSector}.{$polFsiPipe}"/>
              <do_if value="$polEntryPipe? and $polEntryPipe.$FailedShips? and $polEntryPipe.$FailedShips.count gt 0">
                <set_value name="$polNewFailedPipe" exact="[]"/>
                <do_all exact="$polEntryPipe.$FailedShips.count" counter="$polFsi2Pipe">
                  <do_if value="$polEntryPipe.$FailedShips.{$polFsi2Pipe} != this.ship">
                    <append_to_list name="$polNewFailedPipe" exact="$polEntryPipe.$FailedShips.{$polFsi2Pipe}"/>
                  </do_if>
                </do_all>
                <set_value name="$polEntryPipe.$FailedShips" exact="$polNewFailedPipe"/>
              </do_if>
            </do_all>
          </do_else>
        </do_if>
        <!-- Always update baselines after evaluation (prevents false "changed" on first run/restart). -->
        <set_value name="this.$lastPriorityWaresSig" exact="$pwSig"/>
        <set_value name="this.$lastMk4PolicySig" exact="$mk4PolicySig"/>
        <set_value name="this.$lastPriorityWaresHome" exact="$searchHomeSector"/>

        <!-- Phase 1 (cache-only): run lightweight cache lookup and return control to scheduler. -->
        <do_if value="$searchPhase == 'cache'">
          <set_value name="$cacheFoundOnlyResult" exact="null"/>
          <set_value name="$cacheFoundOnly" exact="false"/>
          <set_value name="$cacheFoundOnlyTradeList" exact="[]"/>
          <set_value name="$cachePhaseSkipped" exact="not ($searchMode? and not $forceLiveSearch)"/>
          <do_if value="not $cachePhaseSkipped">
            <run_script name="'lib.gt.cache.search'" result="$cacheFoundOnlyResult">
              <param name="cachePool" value="'mk4'"/>
              <param name="ship" value="this.ship"/>
              <param name="searchMode" value="$searchMode"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchRadiusMax"/>
              <param name="maxDistanceBuy" value="$searchMaxBuy"/>
              <param name="maxDistanceSell" value="$searchMaxSell"/>
              <param name="wareBasket" value="$searchWareBasket"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
              <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)"/>
              <param name="enableMinCargoUtil" value="if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)"/>
              <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
              <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
              <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
              <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
              <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
              <param name="requirePlayerDeliveryStation" value="true"/>
              <param name="requirePlayerSupplierStation" value="not (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true)"/>
              <param name="requireNonPlayerSupplierStation" value="not (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true)"/>
              <param name="mk4DedicatedServe" value="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
              <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
              <param name="mk4AllowResources" value="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
              <param name="mk4AllowIntermediates" value="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
              <param name="mk4AllowTradewares" value="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
              <param name="mk4BuildStorageOnlyMode" value="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false"/>
            </run_script>
            <do_if value="$cacheFoundOnlyResult? and $cacheFoundOnlyResult.$Found?">
              <set_value name="$cacheFoundOnly" exact="@$cacheFoundOnlyResult.$Found"/>
            </do_if>
            <do_if value="$cacheFoundOnly and $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$TradeList?">
              <set_value name="$cacheFoundOnlyTradeList" exact="@$cacheFoundOnlyResult.$TradeList"/>
            </do_if>
            <do_if value="$cacheFoundOnly and $cacheFoundOnlyTradeList? and $cacheFoundOnlyTradeList.count gt 0">
              <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
            </do_if>
            <!-- Pool has entries but this ship got zero: clear stale per-ship failure flags. -->
            <do_if value="not $cacheFoundOnly and $mk4HomeCacheCount gt 0 and $searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$searchHomeSector}?">
              <do_all exact="global.$GT_TradeCacheMK4.{$searchHomeSector}.count" counter="$cacheMissFsi">
                <set_value name="$cacheMissEntry" exact="global.$GT_TradeCacheMK4.{$searchHomeSector}.{$cacheMissFsi}"/>
                <do_if value="$cacheMissEntry? and $cacheMissEntry.$FailedShips? and $cacheMissEntry.$FailedShips.count gt 0">
                  <set_value name="$cacheMissNewFailed" exact="[]"/>
                  <do_all exact="$cacheMissEntry.$FailedShips.count" counter="$cacheMissFsi2">
                    <do_if value="$cacheMissEntry.$FailedShips.{$cacheMissFsi2} != this.ship">
                      <append_to_list name="$cacheMissNewFailed" exact="$cacheMissEntry.$FailedShips.{$cacheMissFsi2}"/>
                    </do_if>
                  </do_all>
                  <set_value name="$cacheMissEntry.$FailedShips" exact="$cacheMissNewFailed"/>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$cachePhaseCount" exact="if $cacheFoundOnlyTradeList? then $cacheFoundOnlyTradeList.count else 0"/>
            <set_value name="$cachePhaseOutcome" exact="if $cachePhaseSkipped then 'SKIP' else (if $cacheFoundOnly then 'HIT' else 'MISS')"/>
            <set_value name="$cachePhasePoolCount" exact="if $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$PoolSizeAfter? then @$cacheFoundOnlyResult.$PoolSizeAfter else (if $mk4HomeCacheCount? then $mk4HomeCacheCount else 0)"/>
            <set_value name="$cachePhasePurged" exact="if $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$PurgedStale? then @$cacheFoundOnlyResult.$PurgedStale else 0"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache phase ' + $cachePhaseOutcome + ' (mode=' + $searchMode + ', trades=' + $cachePhaseCount + ', pool=' + $cachePhasePoolCount + (if $cachePhasePurged gt 0 then (', purged=' + $cachePhasePurged) else '') + ', home=' + (if $searchHomeSector? and $searchHomeSector.exists then $searchHomeSector.knownname else 'null') + ')'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Done'" param2="table[
            $Ship = this.ship,
            $Found = $cacheFoundOnly,
            $TradeList = $cacheFoundOnlyTradeList,
            $SearchMethod = 'cache',
            $SearchType = 'cache',
            $HomeSector = $searchHomeSector
          ]"/>
          <resume label="wait_for_response"/>
        </do_if>

        <set_value name="$pipelineFound" exact="false"/>
        <set_value name="$pipelineTradeList" exact="[]"/>
        <set_value name="$pipelineSearchMethod" exact="'live'"/>
        <set_value name="$cacheSearchResult" exact="null"/>
        <set_value name="$cacheFound" exact="false"/>
        <do_if value="$searchMode? and not $forceLiveSearch and not $skipCacheRead">
          <!-- 1) Cache path -->
          <run_script name="'lib.gt.cache.search'" result="$cacheSearchResult">
            <param name="cachePool" value="'mk4'"/>
            <param name="ship" value="this.ship"/>
            <param name="searchMode" value="$searchMode"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchRadiusMax"/>
            <param name="maxDistanceBuy" value="$searchMaxBuy"/>
            <param name="maxDistanceSell" value="$searchMaxSell"/>
            <param name="wareBasket" value="$searchWareBasket"/>
            <param name="minROI" value="$searchMinROI"/>
            <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
            <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)"/>
            <param name="enableMinCargoUtil" value="if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)"/>
            <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
            <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
            <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
            <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
            <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
            <param name="requirePlayerDeliveryStation" value="true"/>
            <param name="requirePlayerSupplierStation" value="not (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true)"/>
            <param name="requireNonPlayerSupplierStation" value="not (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true)"/>
            <param name="mk4DedicatedServe" value="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
            <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
            <param name="mk4AllowResources" value="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
            <param name="mk4AllowIntermediates" value="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
            <param name="mk4AllowTradewares" value="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
            <param name="mk4BuildStorageOnlyMode" value="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false"/>
          </run_script>
        </do_if>
        <!-- SAVEGAME GUARD: If save/load interrupted the run_script above, all locals are lost.
             Detect and bail to retry instead of cascading property lookup errors. -->
        <do_if value="not $searchMode?">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>
        <do_if value="$cacheSearchResult?">
          <do_if value="$cacheSearchResult.$Found?">
            <set_value name="$cacheFound" exact="@$cacheSearchResult.$Found"/>
          </do_if>
        </do_if>
        <do_if value="$cacheFound">
          <set_value name="$pipelineFound" exact="true"/>
          <set_value name="$pipelineSearchMethod" exact="'cache'"/>
          <set_value name="$pipelineTradeList" exact="if $cacheSearchResult.$TradeList? then @$cacheSearchResult.$TradeList else []"/>
          <do_if value="$pipelineTradeList? and $pipelineTradeList.count gt 0">
            <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- 2) Pathfinding -->
          <run_script name="'lib.gt.pathfinding'" result="$pathResult">
            <param name="ship" value="this.ship"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchRadiusMax"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <!-- SAVEGAME GUARD -->
          <do_if value="not $searchMode?">
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
            <resume label="no_trade_retry"/>
          </do_if>

          <!-- 3) Live offers -->
          <!-- MK4 must search across all reachable offers; disable relative-price filtering for every mode/state. -->
          <set_value name="$searchSellPriceMax" exact="1.0"/>
          <set_value name="$searchBuyPriceMin" exact="-1.0"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PriceRange: SellPriceMax=' + $searchSellPriceMax + ' BuyPriceMin=' + $searchBuyPriceMin" chance="@this.$debugchance"/>
          <run_script name="'lib.gt.live.search'" result="$liveResult">
            <param name="ship" value="this.ship"/>
            <param name="searchMode" value="$searchMode"/>
            <param name="buySpaces" value="$pathResult.$BuySpaces"/>
            <param name="sellSpaces" value="$pathResult.$SellSpaces"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchRadiusMax"/>
            <param name="wareBasket" value="$searchWareBasket"/>
            <param name="allowIllegal" value="$searchAllowIllegal"/>
            <param name="ownerFilter" value="'any'"/>
            <param name="includePlayerBuyOffers" value="true"/>
            <param name="includePlayerSellOffers" value="true"/>
            <param name="requirePlayerBuyOfferOwner" value="true"/>
            <param name="ignoreTradeRulesPlayerBuyOffersRequireCargoNeed" value="true"/>
            <param name="ignoreMK1Supply" value="$searchIgnoreMK1Supply"/>
            <param name="ignoreTradeRules" value="$searchIgnoreTradeRules"/>
            <param name="maxOffersPerWare" value="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
            <param name="sellPriceMax" value="$searchSellPriceMax"/>
            <param name="buyPriceMin" value="$searchBuyPriceMin"/>
            <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
            <param name="demandLedSupplierScan" value="if $searchMode? and $searchMode == 'buy_and_sell' then true else false"/>
            <param name="mk4BuildStorageOnlyMode" value="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false"/>
            <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
            <param name="maxDistanceSell" value="$searchMaxSell"/>
            <param name="debugchance" value="@this.$debugchance"/>
          </run_script>
          <!-- SAVEGAME GUARD -->
          <do_if value="not $searchMode?">
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
            <resume label="no_trade_retry"/>
          </do_if>

          <!-- MK4 Galaxy-Supply: structured debug â€” delivery targets (buy offers), suppliers (sell offers), conditions -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMode? and $searchMode == 'buy_and_sell'">
            <set_value name="$mk4PriceProfile" exact="'normal'"/>
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?">
              <set_value name="$mk4PriceProfile" exact="'isolated'"/>
            </do_if>
            <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <set_value name="$mk4PriceProfile" exact="'fallback'"/>
            </do_elseif>
            <set_value name="$mk4HomeLabel" exact="if $searchHomeSector? and $searchHomeSector.exists then @$searchHomeSector.knownname else 'null'"/>
            <set_value name="$mk4EffHomeLabel" exact="if this.$effectiveHome? and this.$effectiveHome.exists then (if this.$effectiveHome.isclass.sector then ('SEC:' + @this.$effectiveHome.knownname) else ('ST:' + @this.$effectiveHome.knownname)) else 'null'"/>
            <set_value name="$mk4AutoW" exact="if $effectiveAutoWares? then $effectiveAutoWares else true"/>
            <set_value name="$mk4BasketN" exact="if $effectiveWareBasket? and $effectiveWareBasket.count? then $effectiveWareBasket.count else 0"/>
            <set_value name="$mk4BasketStr" exact="''"/>
            <do_if value="$effectiveWareBasket? and $effectiveWareBasket.count gt 0">
              <set_value name="$mk4Bmax" exact="[$effectiveWareBasket.count, 12].min"/>
              <do_all exact="$mk4Bmax" counter="$mk4bi">
                <set_value name="$mk4bw" exact="$effectiveWareBasket.{$mk4bi}"/>
                <set_value name="$mk4BasketStr" exact="$mk4BasketStr + (if $mk4bi gt 1 then ',' else '') + (if $mk4bw? and $mk4bw != null and $mk4bw.name? then @$mk4bw.name else '?')"/>
              </do_all>
              <do_if value="$effectiveWareBasket.count gt $mk4Bmax">
                <set_value name="$mk4BasketStr" exact="$mk4BasketStr + '...+' + ($effectiveWareBasket.count - $mk4Bmax)"/>
              </do_if>
            </do_if>
            <set_value name="$mk4PathIso" exact="if $pathResult.$ShipIsIsolated? then $pathResult.$ShipIsIsolated else false"/>
            <set_value name="$mk4BSn" exact="if $pathResult.$BuySpaces? then $pathResult.$BuySpaces.count else 0"/>
            <set_value name="$mk4SSn" exact="if $pathResult.$SellSpaces? then $pathResult.$SellSpaces.count else 0"/>
            <set_value name="$mk4SecSample" exact="''"/>
            <do_if value="$pathResult.$BuySpaces? and $pathResult.$BuySpaces.count gt 0">
              <set_value name="$mk4Smx" exact="[$pathResult.$BuySpaces.count, 6].min"/>
              <do_all exact="$mk4Smx" counter="$mk4si">
                <set_value name="$mk4s" exact="$pathResult.$BuySpaces.{$mk4si}"/>
                <set_value name="$mk4SecSample" exact="$mk4SecSample + (if $mk4si gt 1 then ',' else '') + (if $mk4s.knownname? then @$mk4s.knownname else '?')"/>
              </do_all>
            </do_if>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': CONDITIONS homeSector=' + $mk4HomeLabel + ' effectiveHome=' + $mk4EffHomeLabel + ' priceProfile=' + $mk4PriceProfile + ' SellPriceMax(rel)=' + $searchSellPriceMax + ' BuyPriceMin(rel)=' + $searchBuyPriceMin + ' ignoreTradeRules=' + $searchIgnoreTradeRules + ' allowIllegal=' + $searchAllowIllegal + ' enforceRouteIllegal=' + $searchEnforceRouteIllegalLegality + ' maxJumpBuy=' + $searchMaxBuy + ' maxJumpCoverage(delivery)=' + $searchMaxSell + ' pathRadiusMax=' + $searchRadiusMax + ' pathIsolated=' + $mk4PathIso + ' searchSectors=' + $mk4BSn + '/' + $mk4SSn + ' sampleSectors=[' + $mk4SecSample + ']'" chance="100"/>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': WARES autowares=' + $mk4AutoW + ' manualBasketCount=' + $mk4BasketN + ' manualBasket=[' + $mk4BasketStr + '] priorityWares=' + (if $effectivePriorityWares? and $effectivePriorityWares.count? then $effectivePriorityWares.count else 0)" chance="100"/>
            <set_value name="$mk4PlSup" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
            <set_value name="$mk4AiSup" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
            <set_value name="$mk4Ded" exact="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
            <set_value name="$mk4Res" exact="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
            <set_value name="$mk4Int" exact="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
            <set_value name="$mk4Tw" exact="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
            <set_value name="$mk4Bso" exact="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false"/>
            <set_value name="$mk4Pbm" exact="if this.$mk4PlayerBuyMod? then this.$mk4PlayerBuyMod else 0"/>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': MK4FILTERS customerMustBePlayer=true allowPlayerSuppliers=' + $mk4PlSup + ' allowAiSuppliers=' + $mk4AiSup + ' dedicatedServe=' + $mk4Ded + ' buildStorageOnly=' + $mk4Bso + ' allowRes/int/tw=' + $mk4Res + '/' + $mk4Int + '/' + $mk4Tw + ' foreignBuyModPct=' + $mk4Pbm" chance="100"/>
            <set_value name="$mk4SellC" exact="if $liveResult? and $liveResult.$SellOfferCount? then @$liveResult.$SellOfferCount else (if $liveResult? and $liveResult.$SellOffers? then $liveResult.$SellOffers.count else 0)"/>
            <set_value name="$mk4BuyC" exact="if $liveResult? and $liveResult.$BuyOfferCount? then @$liveResult.$BuyOfferCount else (if $liveResult? and $liveResult.$BuyOffers? then $liveResult.$BuyOffers.count else 0)"/>
            <set_value name="$mk4SWk" exact="if $liveResult? and $liveResult.$SellWaresFound? then @$liveResult.$SellWaresFound else 0"/>
            <set_value name="$mk4BWk" exact="if $liveResult? and $liveResult.$BuyWaresFound? then @$liveResult.$BuyWaresFound else 0"/>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': LIVE_OFFERS sellOffers=' + $mk4SellC + ' (distinctSellWares~' + $mk4SWk + ') buyOffers=' + $mk4BuyC + ' (distinctBuyWares~' + $mk4BWk + ')  [buyOffers=stations ship DELIVERS TO / sells to; sellOffers=NPCs ship BUYS FROM]'" chance="100"/>
            <!-- DELIVERY_TARGETS: MK4 only supplies player-owned customers â€” list player buy-offers only (not raw full list). -->
            <set_value name="$mk4DelivStr" exact="''"/>
            <set_value name="$mk4PlayerBuyTotal" exact="0"/>
            <set_value name="$mk4PlayerBuyListed" exact="0"/>
            <do_if value="$liveResult? and $liveResult.$BuyOffers? and $liveResult.$BuyOffers.count gt 0">
              <do_all exact="$liveResult.$BuyOffers.count" counter="$mk4di">
                <set_value name="$mk4bo" exact="$liveResult.$BuyOffers.{$mk4di}"/>
                <!-- Delivery customer: same as vanilla trade perform â€” buyer is the station that buys from the ship. -->
                <set_value name="$mk4boCustomer" exact="null"/>
                <do_if value="$mk4bo.buyer? and @$mk4bo.buyer.exists">
                  <set_value name="$mk4boCustomer" exact="@$mk4bo.buyer"/>
                </do_if>
                <do_elseif value="$mk4bo.owner?">
                  <set_value name="$mk4boCustomer" exact="@$mk4bo.owner"/>
                </do_elseif>
                <do_if value="not $mk4boCustomer? or not @$mk4boCustomer.exists">
                  <continue/>
                </do_if>
                <set_value name="$mk4boPlayerOk" exact="false"/>
                <do_if value="@$mk4boCustomer.isplayerowned">
                  <set_value name="$mk4boPlayerOk" exact="true"/>
                </do_if>
                <do_elseif value="$mk4boCustomer.isclass.buildstorage and $mk4boCustomer.base? and @$mk4boCustomer.base.isplayerowned">
                  <set_value name="$mk4boPlayerOk" exact="true"/>
                </do_elseif>
                <do_if value="not $mk4boPlayerOk">
                  <continue/>
                </do_if>
                <set_value name="$mk4PlayerBuyTotal" operation="add"/>
                <do_if value="$mk4PlayerBuyListed ge 40">
                  <continue/>
                </do_if>
                <set_value name="$mk4dst" exact="if @$mk4boCustomer.exists then @$mk4boCustomer.idcode else '?'"/>
                <set_value name="$mk4dsn" exact="if @$mk4boCustomer.knownname then @$mk4boCustomer.knownname else '?'"/>
                <set_value name="$mk4dwn" exact="if $mk4bo.ware? then @$mk4bo.ware.name else '?'"/>
                <set_value name="$mk4DelivStr" exact="$mk4DelivStr + (if $mk4DelivStr != '' then ' | ' else '') + $mk4dst + ':' + $mk4dsn + ':' + $mk4dwn"/>
                <set_value name="$mk4PlayerBuyListed" operation="add"/>
              </do_all>
              <!-- Safe cooperative yield after batch (never inside do_all in AI scripts). -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
              <do_if value="$mk4PlayerBuyTotal gt 40">
                <set_value name="$mk4DelivStr" exact="$mk4DelivStr + ' | ...+' + ($mk4PlayerBuyTotal - 40) + ' more player offers'"/>
              </do_if>
            </do_if>
            <do_if value="$mk4PlayerBuyTotal == 0">
              <set_value name="$mk4DelivStr" exact="'(no player-owned buy offers in live search â€” MK4 cannot deliver; check BuyPriceMin/tradepartner/ignoreTradeRules/jumps)'"/>
            </do_if>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': DELIVERY_TARGETS playerBuyOffers=' + $mk4PlayerBuyTotal + '/' + $mk4BuyC + ' (id:name:ware) ' + $mk4DelivStr" chance="100"/>
            <set_value name="$mk4SuppStr" exact="''"/>
            <do_if value="$liveResult? and $liveResult.$SellOffers? and $liveResult.$SellOffers.count gt 0">
              <set_value name="$mk4Slim" exact="[$liveResult.$SellOffers.count, 40].min"/>
              <do_all exact="$mk4Slim" counter="$mk4si2">
                <set_value name="$mk4so" exact="$liveResult.$SellOffers.{$mk4si2}"/>
                <set_value name="$mk4soSup" exact="null"/>
                <do_if value="$mk4so.seller? and @$mk4so.seller.exists">
                  <set_value name="$mk4soSup" exact="@$mk4so.seller"/>
                </do_if>
                <do_elseif value="$mk4so.owner?">
                  <set_value name="$mk4soSup" exact="@$mk4so.owner"/>
                </do_elseif>
                <set_value name="$mk4sst" exact="if $mk4soSup? and @$mk4soSup.exists then @$mk4soSup.idcode else '?'"/>
                <set_value name="$mk4ssn" exact="if $mk4soSup? and @$mk4soSup.knownname then @$mk4soSup.knownname else '?'"/>
                <set_value name="$mk4spl" exact="if $mk4soSup? and @$mk4soSup.isplayerowned then 'P' else 'N'"/>
                <set_value name="$mk4swn" exact="if $mk4so.ware? then @$mk4so.ware.name else '?'"/>
                <set_value name="$mk4SuppStr" exact="$mk4SuppStr + (if $mk4si2 gt 1 then ' | ' else '') + $mk4sst + ':' + $mk4ssn + '[' + $mk4spl + ']:' + $mk4swn"/>
              </do_all>
              <!-- Safe cooperative yield after batch (never inside do_all in AI scripts). -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
              <do_if value="$liveResult.$SellOffers.count gt $mk4Slim">
                <set_value name="$mk4SuppStr" exact="$mk4SuppStr + ' | ...+' + ($liveResult.$SellOffers.count - $mk4Slim) + ' more'"/>
              </do_if>
            </do_if>
            <do_else>
              <set_value name="$mk4SuppStr" exact="'(no sell offers â€” no supplier purchase candidates in live search)'"/>
            </do_else>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': SUPPLIERS (id:name[P/N]:ware) ' + $mk4SuppStr" chance="100"/>
          </do_if>

          <do_if value="$searchMode? and $searchMode == 'sell_only'">
            <create_list name="$sellOnlyTrades"/>
            <set_value name="$liveBuyOffers" exact="[]"/>
            <do_if value="$liveResult?">
              <do_if value="$liveResult.$BuyOffers?">
                <set_value name="$liveBuyOffers" exact="@$liveResult.$BuyOffers"/>
              </do_if>
            </do_if>
            <do_if value="$liveBuyOffers.count gt 0">
              <do_all exact="$liveBuyOffers.count" counter="$offerIdx">
                <set_value name="$sellOffer" exact="$liveBuyOffers.{$offerIdx}"/>
                <set_value name="$sellWare" exact="if $sellOffer? and $sellOffer.ware? then @$sellOffer.ware else null"/>
                <do_if value="not $sellWare?">
                  <continue/>
                </do_if>

                <set_value name="$shipWareAmount" exact="this.ship.cargo.{$sellWare}.count"/>
                <set_value name="$tradeAmount" exact="[$shipWareAmount, $sellOffer.amount].min"/>
                <do_if value="$tradeAmount le 0">
                  <continue/>
                </do_if>

                <set_value name="$sellDistance" exact="$searchHomeSector.gatedistance.{$sellOffer.owner}"/>
                <do_if value="$sellDistance lt 0 or $sellDistance gt $searchMaxSell">
                  <continue/>
                </do_if>

                <set_value name="$distanceFactor" exact="1.0 + ($sellDistance * $gt_distancepenalty)"/>
                <set_value name="$sellUnitPriceCr" exact="($sellOffer.unitprice / 1Cr)i"/>
                <set_value name="$sellScore" exact="($tradeAmount * [$sellUnitPriceCr, 1].max) / $distanceFactor"/>
                <append_to_list name="$sellOnlyTrades" exact="table[
                  $IsSellOnly = true,
                  $Ware = $sellWare,
                  $SellOffer = $sellOffer,
                  $SellStation = $sellOffer.owner,
                  $Amount = $tradeAmount,
                  $Score = $sellScore,
                  $BuyStation = this.ship,
                  $BuySector = this.ship.sector,
                  $Distance = $sellDistance,
                  $UnitProfit = $sellOffer.unitprice,
                  $BuyPrice = 0,
                  $SellPrice = $sellOffer.unitprice,
                  $ProfitPerUnit = $sellOffer.unitprice,
                  $Profit = ($sellOffer.unitprice * $tradeAmount)
                ]"/>
              </do_all>
              <!-- AI locals do not survive waits inside do_all loops; yield once after the batch. -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
            </do_if>

            <run_script name="'lib.gt.score.trades'" result="$scoreResult">
              <param name="tradeList" value="$sellOnlyTrades"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125"/>
            </run_script>
            <set_value name="$pipelineSearchMethod" exact="'live_sell_only'"/>
            <set_value name="$scoreFound" exact="false"/>
            <do_if value="$scoreResult?">
              <do_if value="$scoreResult.$Found?">
                <set_value name="$scoreFound" exact="@$scoreResult.$Found"/>
              </do_if>
            </do_if>
            <do_if value="$scoreFound">
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $scoreResult.$SortedTrades? then @$scoreResult.$SortedTrades else []"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- 4) Trade matching -->
            <set_value name="this.$gt_dockMemo" exact="table[]"/>
            <run_script name="'lib.gt.tradematch'" result="$matchResult">
              <param name="ship" value="this.ship"/>
              <param name="sellOffers" value="$liveResult.$SellOffers"/>
              <param name="buyOffers" value="$liveResult.$BuyOffers"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchRadiusMax"/>
              <param name="maxDistanceBuy" value="$searchMaxBuy"/>
              <param name="maxDistanceSell" value="$searchMaxSell"/>
              <param name="backtrackTolerance" value="if this.$effectiveBacktrackTolerance? then this.$effectiveBacktrackTolerance else 0"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
              <param name="distancePenalty" value="$gt_distancepenalty"/>
              <param name="factionPriority" value="$searchFactionPriority"/>
              <param name="ignoreBuildStorage" value="$searchIgnoreBuildStorage"/>
              <param name="ignoreCarrierAux" value="$searchIgnoreCarrierAux"/>
              <param name="allowIllegal" value="$searchAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$searchEnforceRouteIllegalLegality"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="scoreMode" value="'supply'"/>
              <param name="mk4CustomerMustBePlayer" value="true"/>
              <param name="mk4AllowPlayerSuppliers" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
              <param name="mk4AllowAiSuppliers" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
              <param name="mk4DedicatedServe" value="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
              <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
              <param name="mk4AllowResources" value="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
              <param name="mk4AllowIntermediates" value="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
              <param name="mk4AllowTradewares" value="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
              <param name="mk4BuildStorageOnlyMode" value="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false"/>
              <param name="mk4PlayerBuyModPct" value="if this.$mk4PlayerBuyMod? then this.$mk4PlayerBuyMod else 0"/>
            </run_script>
            <!-- SAVEGAME GUARD -->
            <do_if value="not $searchMode?">
              <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
              <resume label="no_trade_retry"/>
            </do_if>

            <!-- 5) Final score ranking -->
            <set_value name="$matchTradeList" exact="[]"/>
            <do_if value="$matchResult?">
              <do_if value="$matchResult.$TradeList?">
                <set_value name="$matchTradeList" exact="@$matchResult.$TradeList"/>
              </do_if>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$mk4Mev" exact="if $matchResult? and $matchResult.$TradesEvaluated? then @$matchResult.$TradesEvaluated else -1"/>
              <set_value name="$mk4Mrj" exact="if $matchResult? and $matchResult.$TradesRejected? then @$matchResult.$TradesRejected else -1"/>
              <set_value name="$mk4Mri" exact="if $matchResult? and $matchResult.$TradesRejectedRouteIllegal? then @$matchResult.$TradesRejectedRouteIllegal else -1"/>
              <set_value name="$mk4MrjCust" exact="if $matchResult? and $matchResult.$TradesRejectedMk4CustomerPolicy? then @$matchResult.$TradesRejectedMk4CustomerPolicy else -1"/>
              <set_value name="$mk4MrjSupp" exact="if $matchResult? and $matchResult.$TradesRejectedMk4SupplierPolicy? then @$matchResult.$TradesRejectedMk4SupplierPolicy else -1"/>
              <set_value name="$mk4MrjType" exact="if $matchResult? and $matchResult.$TradesRejectedMk4TypePolicy? then @$matchResult.$TradesRejectedMk4TypePolicy else -1"/>
              <set_value name="$mk4MrjDem" exact="if $matchResult? and $matchResult.$TradesRejectedMk4DemandGate? then @$matchResult.$TradesRejectedMk4DemandGate else -1"/>
              <set_value name="$mk4MrjPc" exact="if $matchResult? and $matchResult.$TradesRejectedMk4PriceCap? then @$matchResult.$TradesRejectedMk4PriceCap else -1"/>
              <set_value name="$mk4MrjBso" exact="if $matchResult? and $matchResult.$TradesRejectedMk4BuildStorageOnly? then @$matchResult.$TradesRejectedMk4BuildStorageOnly else -1"/>
              <set_value name="$mk4MrjDist" exact="if $matchResult? and $matchResult.$TradesRejectedDistance? then @$matchResult.$TradesRejectedDistance else -1"/>
              <set_value name="$mk4Mfound" exact="if $matchResult? and $matchResult.$Found? then @$matchResult.$Found else false"/>
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': TRADEMATCH supply-mode rawListCount=' + $matchTradeList.count + ' bestFound=' + $mk4Mfound + ' pairsEvaluated=' + $mk4Mev + ' pairsRejected=' + $mk4Mrj + ' routeIllegalRejected=' + $mk4Mri + ' rej(customer/supplier/type/demand/pricecap/bso/dist)=' + $mk4MrjCust + '/' + $mk4MrjSupp + '/' + $mk4MrjType + '/' + $mk4MrjDem + '/' + $mk4MrjPc + '/' + $mk4MrjBso + '/' + $mk4MrjDist" chance="100"/>
            </do_if>
            <run_script name="'lib.gt.score.trades'" result="$scoreResult">
              <param name="tradeList" value="$matchTradeList"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125"/>
              <param name="diversifyByWare" value="true"/>
              <param name="priorityFirstInDiversify" value="true"/>
              <param name="debugchance" value="@this.$debugchance"/>
            </run_script>

            <set_value name="$scoreFound" exact="false"/>
            <do_if value="$scoreResult?">
              <do_if value="$scoreResult.$Found?">
                <set_value name="$scoreFound" exact="@$scoreResult.$Found"/>
              </do_if>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$mk4ScCnt" exact="if $scoreResult? and $scoreResult.$SortedTrades? then $scoreResult.$SortedTrades.count else 0"/>
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': SCORE_TRADES found=' + $scoreFound + ' sortedTrades=' + $mk4ScCnt" chance="100"/>
            </do_if>
            <do_if value="$scoreFound">
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $scoreResult.$SortedTrades? then @$scoreResult.$SortedTrades else []"/>
            </do_if>
          </do_else>
        </do_else>

        <!-- Savegame compatibility: local pipeline vars can be missing on migrated/running states.
             Normalize them before any unconditional reads below. -->
        <do_if value="not $pipelineFound?">
          <set_value name="$pipelineFound" exact="false"/>
        </do_if>
        <do_if value="not $pipelineTradeList?">
          <set_value name="$pipelineTradeList" exact="[]"/>
        </do_if>
        <do_if value="not $pipelineSearchMethod?">
          <set_value name="$pipelineSearchMethod" exact="'live'"/>
        </do_if>

        <!-- serveHomeOnly / build-storage-only home-anchor scope:
             - buildStorageOnly => player BS within jumpDistanceCoverage from home
             - serveHomeOnly (non-BSO) => home station + its BS, or home sector -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ((if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) or (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false))">
          <set_value name="$serveHomeAnchor" exact="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
          <set_value name="$serveHomeSector" exact="if $serveHomeAnchor? and $serveHomeAnchor.isclass.sector then $serveHomeAnchor else (if $serveHomeAnchor? and $serveHomeAnchor.sector? then @$serveHomeAnchor.sector else $searchHomeSector)"/>
          <set_value name="$serveHomeBeforeCount" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListServeHomeFiltered"/>
          <do_all exact="$pipelineTradeList.count" counter="$shrIdx">
            <set_value name="$shrTrade" exact="$pipelineTradeList.{$shrIdx}"/>
            <set_value name="$shrKeep" exact="true"/>
            <set_value name="$shrDeliveryStation" exact="if $shrTrade.$SellStation? then $shrTrade.$SellStation else null"/>
            <do_if value="not $shrDeliveryStation? and $shrTrade.$SellOffer?">
              <do_if value="$shrTrade.$SellOffer.buyer? and @$shrTrade.$SellOffer.buyer.exists">
                <set_value name="$shrDeliveryStation" exact="@$shrTrade.$SellOffer.buyer"/>
              </do_if>
              <do_elseif value="$shrTrade.$SellOffer.owner?">
                <set_value name="$shrDeliveryStation" exact="@$shrTrade.$SellOffer.owner"/>
              </do_elseif>
            </do_if>
            <do_if value="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false">
              <set_value name="$shrSupplierStation" exact="if $shrTrade.$BuyStation? then $shrTrade.$BuyStation else null"/>
              <do_if value="not $shrSupplierStation? and $shrTrade.$BuyOffer?">
                <do_if value="$shrTrade.$BuyOffer.seller? and @$shrTrade.$BuyOffer.seller.exists">
                  <set_value name="$shrSupplierStation" exact="@$shrTrade.$BuyOffer.seller"/>
                </do_if>
                <do_elseif value="$shrTrade.$BuyOffer.owner?">
                  <set_value name="$shrSupplierStation" exact="@$shrTrade.$BuyOffer.owner"/>
                </do_elseif>
              </do_if>
              <do_if value="$shrSupplierStation? and @$shrSupplierStation.isclass.buildstorage">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
              <do_if value="$shrKeep and (not $shrDeliveryStation? or not @$shrDeliveryStation.isclass.buildstorage)">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
              <do_if value="$shrKeep">
                <set_value name="$shrBsoDist" exact="if $searchHomeSector? and $shrDeliveryStation? and $shrDeliveryStation.sector? then $searchHomeSector.gatedistance.{$shrDeliveryStation.sector} else -1"/>
                <do_if value="$shrBsoDist lt 0 or ($searchMaxSell gt 0 and $shrBsoDist gt $searchMaxSell)">
                  <set_value name="$shrKeep" exact="false"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$shrKeep and not (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) and (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) and $serveHomeAnchor? and $serveHomeAnchor.isclass.station">
              <set_value name="$shrServeHomeMatch" exact="false"/>
              <do_if value="$shrDeliveryStation? and $shrDeliveryStation.exists and $serveHomeAnchor.exists">
                <do_if value="$shrDeliveryStation == $serveHomeAnchor">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_if>
                <do_elseif value="$serveHomeAnchor.buildstorage? and $serveHomeAnchor.buildstorage.exists and $shrDeliveryStation == $serveHomeAnchor.buildstorage">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
                <do_elseif value="$shrDeliveryStation.isclass.buildstorage and $shrDeliveryStation.base? and $shrDeliveryStation.base.exists and $shrDeliveryStation.base == $serveHomeAnchor">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
                <do_elseif value="$shrDeliveryStation.hascontext.{$serveHomeAnchor}">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
                <do_elseif value="$serveHomeAnchor.hascontext.{$shrDeliveryStation}">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
              </do_if>
              <do_if value="not $shrServeHomeMatch">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$shrKeep and not (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) and (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) and $serveHomeSector? and $serveHomeSector.exists and (not $serveHomeAnchor? or not $serveHomeAnchor.isclass.station)">
              <do_if value="not $shrDeliveryStation? or not $shrDeliveryStation.sector? or @$shrDeliveryStation.sector != $serveHomeSector">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$shrKeep">
              <append_to_list name="$pipelineTradeListServeHomeFiltered" exact="$shrTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListServeHomeFiltered"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': homeScope filter: before=' + $serveHomeBeforeCount + ', after=' + $pipelineTradeList.count + ', dedicatedServe=' + (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) + ', buildStorageOnly=' + (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) + ', homeType=' + (if $serveHomeAnchor? and $serveHomeAnchor.isclass.station then 'station' else 'sector') + ', home=' + (if $serveHomeAnchor? and $serveHomeAnchor.exists then @$serveHomeAnchor.knownname else 'null')" chance="100"/>
          </do_if>
        </do_if>

        <!-- Â§3 searchDepth: breadth cap for validation. MK4 supply always keeps one candidate per
             distinct ware (post diversify) even when that exceeds searchDepth. -->
        <set_value name="$searchDepthCap" exact="if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30"/>
        <do_if value="$pipelineFound and $pipelineTradeList.count gt $searchDepthCap">
          <set_value name="$mk4PipelineDepthBefore" exact="$pipelineTradeList.count"/>
          <set_value name="$mk4DistinctWareCount" exact="0"/>
          <set_value name="$mk4DistinctWaresSeen" exact="table[]"/>
          <do_all exact="$pipelineTradeList.count" counter="$mk4DwIdx">
            <set_value name="$mk4DwTrade" exact="$pipelineTradeList.{$mk4DwIdx}"/>
            <set_value name="$mk4DwWare" exact="if $mk4DwTrade.$Ware? then $mk4DwTrade.$Ware else null"/>
            <do_if value="$mk4DwWare? and not $mk4DistinctWaresSeen.{$mk4DwWare}?">
              <set_value name="$mk4DistinctWaresSeen.{$mk4DwWare}" exact="true"/>
              <set_value name="$mk4DistinctWareCount" operation="add"/>
            </do_if>
          </do_all>
          <set_value name="$mk4EffectiveDepthCap" exact="$searchDepthCap"/>
          <do_if value="$searchMode? and $searchMode == 'buy_and_sell' and $mk4DistinctWareCount gt $searchDepthCap">
            <set_value name="$mk4EffectiveDepthCap" exact="$mk4DistinctWareCount"/>
          </do_if>
          <do_if value="$pipelineTradeList.count gt $mk4EffectiveDepthCap">
            <create_list name="$pipelineTradeListCapped"/>
            <do_all exact="$mk4EffectiveDepthCap" counter="$sdIdx">
              <append_to_list name="$pipelineTradeListCapped" exact="$pipelineTradeList.{$sdIdx}"/>
            </do_all>
            <set_value name="$pipelineTradeList" exact="$pipelineTradeListCapped"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMode? and $searchMode == 'buy_and_sell'">
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': searchDepth cap before=' + $mk4PipelineDepthBefore + ' after=' + $pipelineTradeList.count + ' configured=' + $searchDepthCap + ' effective=' + $mk4EffectiveDepthCap + ' distinctWares=' + $mk4DistinctWareCount" chance="100"/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Write live search results to cache (sorted insertion with AI-script yields).
             Includes sell-only live results so cargo disposal can reuse cache entries. -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ($pipelineSearchMethod == 'live' or $pipelineSearchMethod == 'live_sell_only') and $searchMode?">
          <run_script name="'lib.gt.cache.write'" result="$cacheWriteResult">
            <param name="cachePool" value="'mk4'"/>
            <param name="tradeList" value="$pipelineTradeList"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="cacheTTL" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
            <param name="maxSearchDistance" value="$searchRadiusMax"/>
          </run_script>
        </do_if>
        <!-- SAVEGAME GUARD -->
        <do_if value="not $pipelineFound?">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- MK4 Galaxy-Supply: fallback search disabled. lib.gt.fallback.search uses sell-mode tradematch without
             mk4CustomerMustBePlayer, which allows deliveries to non-player stations (foreign "customers"). -->

        <!-- Final pipeline result check -->
        <do_if value="not $pipelineFound">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- Per-ship dispatch filter:
             MK4 cache pool is supply-specific; remove blocked-faction entries from the list sent to validation. -->
        <set_value name="$mk3BlacklistOwnerDispatch" exact="this.ship"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
          <set_value name="$mk3BlacklistOwnerDispatch" exact="this.ship.commander"/>
        </do_if>
        <set_value name="$mk3FactionBlacklistDispatch" exact="table[]"/>
        <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerDispatch}?">
          <set_value name="$mk3FactionBlacklistDispatch" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerDispatch}"/>
        </do_if>
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and $mk3FactionBlacklistDispatch.keys.count gt 0">
          <set_value name="$pipelineTradeListBeforeDispatchFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListFiltered"/>
          <do_all exact="$pipelineTradeList.count" counter="$dispatchIdx">
            <set_value name="$dispatchTrade" exact="$pipelineTradeList.{$dispatchIdx}"/>
            <set_value name="$dispatchKeepTrade" exact="true"/>
            <!-- MK4 hard policy at dispatch stage: only player delivery customers, supplier side by policy -->
            <set_value name="$dispatchAllowPlayerSuppliers" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
            <set_value name="$dispatchAllowAiSuppliers" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly)">
              <!-- Delivery station: prefer game buy-offer buyer (matches lib.gt.tradematch / validation). -->
              <set_value name="$dispatchDeliveryStation" exact="if $dispatchTrade.$SellStation? then @$dispatchTrade.$SellStation else null"/>
              <do_if value="not $dispatchDeliveryStation? and $dispatchTrade.$SellOffer?">
                <do_if value="$dispatchTrade.$SellOffer.buyer? and @$dispatchTrade.$SellOffer.buyer.exists">
                  <set_value name="$dispatchDeliveryStation" exact="@$dispatchTrade.$SellOffer.buyer"/>
                </do_if>
                <do_elseif value="$dispatchTrade.$SellOffer.owner?">
                  <set_value name="$dispatchDeliveryStation" exact="@$dispatchTrade.$SellOffer.owner"/>
                </do_elseif>
              </do_if>
              <do_if value="not $dispatchDeliveryStation? or not @$dispatchDeliveryStation.isplayerowned">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly)">
              <!-- Supplier station is BuyOffer.seller (fallback owner) -->
              <set_value name="$dispatchSupplierStation" exact="null"/>
              <do_if value="$dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.seller? and @$dispatchTrade.$BuyOffer.seller.exists">
                <set_value name="$dispatchSupplierStation" exact="@$dispatchTrade.$BuyOffer.seller"/>
              </do_if>
              <do_elseif value="$dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.owner? and @$dispatchTrade.$BuyOffer.owner.exists">
                <set_value name="$dispatchSupplierStation" exact="@$dispatchTrade.$BuyOffer.owner"/>
              </do_elseif>

              <do_if value="not $dispatchAllowPlayerSuppliers and $dispatchSupplierStation? and @$dispatchSupplierStation.isplayerowned">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
              <do_if value="$dispatchKeepTrade and not $dispatchAllowAiSuppliers">
                <do_if value="not $dispatchSupplierStation? or not @$dispatchSupplierStation.isplayerowned">
                  <set_value name="$dispatchKeepTrade" exact="false"/>
                </do_if>
              </do_if>
            </do_if>

            <do_if value="$dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly) and $dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.owner?">
              <set_value name="$dispatchBuyOwnerContainer" exact="@$dispatchTrade.$BuyOffer.owner"/>
              <set_value name="$dispatchBuyFaction" exact="null"/>
              <do_if value="$dispatchBuyOwnerContainer.owner?">
                <set_value name="$dispatchBuyFaction" exact="$dispatchBuyOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$dispatchBuyFaction" exact="$dispatchBuyOwnerContainer"/>
              </do_else>
              <do_if value="$dispatchBuyFaction? and $mk3FactionBlacklistDispatch.{$dispatchBuyFaction}?">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and $dispatchTrade.$SellOffer? and $dispatchTrade.$SellOffer.owner?">
              <set_value name="$dispatchSellOwnerContainer" exact="@$dispatchTrade.$SellOffer.owner"/>
              <set_value name="$dispatchSellFaction" exact="null"/>
              <do_if value="$dispatchSellOwnerContainer.owner?">
                <set_value name="$dispatchSellFaction" exact="$dispatchSellOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$dispatchSellFaction" exact="$dispatchSellOwnerContainer"/>
              </do_else>
              <do_if value="$dispatchSellFaction? and $mk3FactionBlacklistDispatch.{$dispatchSellFaction}?">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade">
              <append_to_list name="$pipelineTradeListFiltered" exact="$dispatchTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListFiltered"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Dispatch MK3 faction filter: before=' + $pipelineTradeListBeforeDispatchFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineTradeListBeforeDispatchFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Live search can run 1+ seconds. Re-check per-ship offer amounts immediately before dispatch
             so trades reserved/exhausted during matching are not sent to expensive validation. -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ($pipelineSearchMethod == 'live' or $pipelineSearchMethod == 'live_sell_only' or $pipelineSearchMethod == 'live_fallback')">
          <set_value name="$pipelineBeforeFreshFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListFresh"/>
          <do_all exact="$pipelineTradeList.count" counter="$freshIdx">
            <set_value name="$freshTrade" exact="$pipelineTradeList.{$freshIdx}"/>
            <set_value name="$freshKeep" exact="false"/>
            <do_if value="$freshTrade? and $freshTrade.$IsSellOnly? and $freshTrade.$SellOffer?">
              <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and @$freshTrade.$SellOffer.amount gt 0">
                <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.amount"/>
              </do_if>
              <do_if value="$freshSellAmt? and $freshSellAmt gt 0">
                <set_value name="$freshKeep" exact="true"/>
              </do_if>
            </do_if>
            <do_elseif value="$freshTrade? and $freshTrade.$BuyOffer? and $freshTrade.$SellOffer?">
              <!-- Re-resolve embedded offers before amount checks (handles can go stale during live search). -->
              <set_value name="$freshBuyStation" exact="null"/>
              <set_value name="$freshSellStation" exact="null"/>
              <set_value name="$freshBuyWare" exact="if $freshTrade.$Ware? then $freshTrade.$Ware else null"/>
              <set_value name="$freshSellWare" exact="if $freshTrade.$Ware? then $freshTrade.$Ware else null"/>
              <do_if value="not $freshBuyWare? and @$freshTrade.$BuyOffer.ware != null">
                <set_value name="$freshBuyWare" exact="@$freshTrade.$BuyOffer.ware"/>
              </do_if>
              <do_if value="not $freshSellWare? and @$freshTrade.$SellOffer.ware != null">
                <set_value name="$freshSellWare" exact="@$freshTrade.$SellOffer.ware"/>
              </do_if>
              <do_if value="$freshTrade.$BuyStation? and @$freshTrade.$BuyStation.exists">
                <set_value name="$freshBuyStation" exact="$freshTrade.$BuyStation"/>
              </do_if>
              <do_elseif value="$freshTrade.$BuyOffer.seller? and @$freshTrade.$BuyOffer.seller.exists">
                <set_value name="$freshBuyStation" exact="@$freshTrade.$BuyOffer.seller"/>
              </do_elseif>
              <do_elseif value="$freshTrade.$BuyOffer.owner? and @$freshTrade.$BuyOffer.owner.exists">
                <set_value name="$freshBuyStation" exact="@$freshTrade.$BuyOffer.owner"/>
              </do_elseif>
              <do_if value="$freshTrade.$SellStation? and @$freshTrade.$SellStation.exists">
                <set_value name="$freshSellStation" exact="$freshTrade.$SellStation"/>
              </do_if>
              <do_elseif value="$freshTrade.$SellOffer.buyer? and @$freshTrade.$SellOffer.buyer.exists">
                <set_value name="$freshSellStation" exact="@$freshTrade.$SellOffer.buyer"/>
              </do_elseif>
              <do_elseif value="$freshTrade.$SellOffer.owner? and @$freshTrade.$SellOffer.owner.exists">
                <set_value name="$freshSellStation" exact="@$freshTrade.$SellOffer.owner"/>
              </do_elseif>
              <do_if value="$freshBuyStation? and $freshBuyStation.exists and $freshBuyWare != null">
                <find_sell_offer seller="$freshBuyStation" wares="$freshBuyWare" tradepartner="this.ship" result="$freshResolvedBuyOffer"/>
                <do_if value="$freshResolvedBuyOffer?">
                  <set_value name="$freshTrade.$BuyOffer" exact="$freshResolvedBuyOffer"/>
                </do_if>
              </do_if>
              <do_if value="$freshSellStation? and $freshSellStation.exists and $freshSellWare != null">
                <find_buy_offer buyer="$freshSellStation" wares="$freshSellWare" tradepartner="this.ship" result="$freshResolvedSellOffer"/>
                <do_if value="$freshResolvedSellOffer?">
                  <set_value name="$freshTrade.$SellOffer" exact="$freshResolvedSellOffer"/>
                </do_if>
              </do_if>
              <set_value name="$freshBuyAmt" exact="@$freshTrade.$BuyOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshBuyAmt? or $freshBuyAmt le 0) and @$freshTrade.$BuyOffer.amount gt 0">
                <set_value name="$freshBuyAmt" exact="@$freshTrade.$BuyOffer.amount"/>
              </do_if>
              <do_if value="(not $freshBuyAmt? or $freshBuyAmt le 0) and $freshSellStation? and $freshSellStation.exists and $freshBuyWare?">
                <set_value name="$freshBuyAmt" exact="[0, $freshSellStation.cargo.{$freshBuyWare}.target - $freshSellStation.cargo.{$freshBuyWare}.count].max"/>
              </do_if>
              <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and @$freshTrade.$SellOffer.amount gt 0">
                <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.amount"/>
              </do_if>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and $freshSellStation? and $freshSellStation.exists and $freshSellWare?">
                <set_value name="$freshSellAmt" exact="[0, $freshSellStation.cargo.{$freshSellWare}.target - $freshSellStation.cargo.{$freshSellWare}.count].max"/>
              </do_if>
              <do_if value="$freshBuyAmt? and $freshBuyAmt gt 0 and $freshSellAmt? and $freshSellAmt gt 0">
                <set_value name="$freshKeep" exact="true"/>
              </do_if>
            </do_elseif>
            <do_if value="$freshKeep">
              <append_to_list name="$pipelineTradeListFresh" exact="$freshTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListFresh"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fresh offer filter: before=' + $pipelineBeforeFreshFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineBeforeFreshFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Notify scheduler that this ship finished its search slot (semaphore release + dispatch) -->
        <set_value name="this.$mk4PolicyNeedsLiveSearch" exact="false"/>
        <signal_objects object="player.galaxy" param="'GT_Search_Done'" param2="table[
          $Ship = this.ship,
          $Found = $pipelineFound,
          $TradeList = $pipelineTradeList,
          $SearchMethod = $pipelineSearchMethod,
          $SearchType = if $searchMode? and $searchMode == 'sell_only' then 'clearance' else 'live'
        ]"/>
        <resume label="wait_for_response"/>
      </do_if>
      
      <!-- Safety net: if $searchParams was not a valid table (should not happen after timeout guard above,
           but defense-in-depth). Clean up and retry. -->
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARNING: run_search_pipeline reached with invalid searchParams (typeof=' + typeof $searchParams + ') at game time ' + player.age + ' â€” this should not happen, aborting to retry'" chance="100"/>
      <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
      <resume label="no_trade_retry"/>
      
      <!-- ========================================= -->
      <!-- TRADE FOUND - VALIDATE BLACKLIST FIRST   -->
      <!-- ========================================= -->
      <label name="trade_found"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': REACHED trade_found label - starting blacklist validation at game time ' + player.age" chance="100"/>
      </do_if>
      
      <!-- FAST MONEY CHECK: Short-circuit the expensive 20-trade validation loop when player
           money has dropped below the threshold since this ship's search started.
           Checks static threshold (MinPlayerMoney + 1000 buffer). The fleet money cap is NOT
           consulted here: it is a wealth snapshot and must never block a ship that already holds
           more than the threshold. The per-trade authoritative guard handles unaffordable trades. -->
      <do_if value="not this.$minPlayerMoney?">
        <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      </do_if>
      <set_value name="$fastMoneyThreshold" exact="(this.$minPlayerMoney + 1000)Cr"/>
      <do_if value="player.money le $fastMoneyThreshold">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FAST MONEY CHECK at trade_found: player.money=' + (player.money / 100) + ' Cr, threshold=' + (this.$minPlayerMoney + 1000) + ' Cr - skipping validation, backing off'" chance="100"/>
        </do_if>
        <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
        <resume label="no_trade_retry"/>
      </do_if>
      
      <!-- Initialize validation variables BEFORE do_if block to ensure they always exist -->
      <set_value name="$validTradeFound" exact="false"/>
      <set_value name="$pendingTrade" exact="null"/>
      <set_value name="$buyStation" exact="null"/>
      <set_value name="$sellStation" exact="null"/>
      <set_value name="$tradesChecked" exact="0"/>
      <set_value name="$tradesBlacklisted" exact="0"/>
      <set_value name="$tradesRejectedDocking" exact="0"/>
      <set_value name="$tradesRejectedOfferInvalid" exact="0"/>
      <set_value name="$tradesRejectedPath" exact="0"/>
      <set_value name="$tradesRejectedDistance" exact="0"/>
      <set_value name="$tradesRejectedCargo" exact="0"/>
      <set_value name="$tradesRejectedProfit" exact="0"/>
      <set_value name="$tradesRejectedRestriction" exact="0"/>
      <set_value name="$tradesRejectedDemandReserved" exact="0"/>
      <set_value name="$selectedTradeIdx" exact="0"/>
      <set_value name="$validTradesFound" exact="0"/>
      <create_list name="$validatedTradeCandidates"/>
      <set_value name="$selectedCurrentSectorIsBlacklisted" exact="false"/>
      <set_value name="$searchHomeSector" exact="if this.$lastPriorityWaresHome? and this.$lastPriorityWaresHome.exists then this.$lastPriorityWaresHome else (if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else this.ship.sector))"/>
      
      <!-- Iterate through trade list and validate each one -->
      <!-- Priority order: Signal param2 (from cache search work unit or live search) > Global storage (for threat intelligence compatibility) -->
      <!-- Cache search work units filter entries and signal results via GT_Trade_Found with param2 -->
      <!-- Initialize $tradeList and $searchMethod to prevent property lookup failures -->
      <set_value name="$tradeList" exact="[]"/>
      <set_value name="$searchMethod" exact="''"/>

      <!-- Priority 1: Use trade list from signal param2 (from cache search work unit or live search) -->
      <do_if value="this.$tradeListFromSignal? and this.$tradeListFromSignal.count gt 0">
        <set_value name="$tradeList" exact="this.$tradeListFromSignal"/>
        <set_value name="$searchMethod" exact="if this.$searchMethodFromSignal? and this.$searchMethodFromSignal != '' then this.$searchMethodFromSignal else 'signal'"/>
        <!-- Clear instance variables after use -->
        <remove_value name="this.$tradeListFromSignal"/>
        <remove_value name="this.$searchMethodFromSignal"/>
      </do_if>
      <do_else>
        <!-- Priority 2: Fallback to global storage (for threat intelligence compatibility) -->
        <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
          <set_value name="$tradeList" exact="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <set_value name="$searchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <do_if value="$searchMethod == ''">
            <set_value name="$searchMethod" exact="'global'"/>
          </do_if>
        </do_if>
      </do_else>

      <!-- Ensure it's a list -->
      <do_if value="typeof $tradeList != datatype.list">
        <!-- Backward compat: single trade stored as table -->
        <set_value name="$tradeList" exact="[$tradeList]"/>
      </do_if>

      <!-- Cache path: drop cargo-incompatible rows before validation (avoids FailedShips poisoning). -->
      <do_if value="$searchMethod == 'cache' and $tradeList? and $tradeList.count gt 0">
        <create_list name="$cargoFilteredTradeList"/>
        <do_all exact="$tradeList.count" counter="$cargoFilterIdx">
          <set_value name="$cargoFilterTrade" exact="$tradeList.{$cargoFilterIdx}"/>
          <set_value name="$cargoFilterWare" exact="if $cargoFilterTrade.$Ware? then $cargoFilterTrade.$Ware else (if $cargoFilterTrade.$BuyOffer? then @$cargoFilterTrade.$BuyOffer.ware else null)"/>
          <set_value name="$cargoFilterTransport" exact="if $cargoFilterTrade.$CargoWareTransport? then @$cargoFilterTrade.$CargoWareTransport else (if $cargoFilterWare? then @$cargoFilterWare.waretransport else null)"/>
          <set_value name="$cargoFilterOk" exact="false"/>
          <do_if value="$cargoFilterWare? and this.ship.cargo.{$cargoFilterWare}.max gt 0">
            <set_value name="$cargoFilterOk" exact="true"/>
          </do_if>
          <do_elseif value="$cargoFilterTransport? and this.ship.waretransport.indexof.{$cargoFilterTransport}">
            <set_value name="$cargoFilterOk" exact="true"/>
          </do_elseif>
          <do_if value="$cargoFilterOk">
            <append_to_list name="$cargoFilteredTradeList" exact="$cargoFilterTrade"/>
          </do_if>
        </do_all>
        <set_value name="$tradeList" exact="$cargoFilteredTradeList"/>
      </do_if>
      
      <!-- Use safe access for debug text -->
      <set_value name="$tradeListCountForDebug" exact="if $tradeList != null then $tradeList.count else 0"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Received ' + $tradeListCountForDebug + ' trades to validate (source: ' + (if $searchMethod == 'cache' then 'CACHE' else if $searchMethod == 'live' then 'LIVE' else if $searchMethod != '' then $searchMethod else 'UNKNOWN') + ')'" chance="100"/>
      </do_if>
      
      <!-- Cap extra cache-detail logs to avoid spam -->
      <set_value name="$cacheDetailLogMax" exact="8"/>
      <set_value name="$cacheDetailLogCount" exact="0"/>
      
      <!-- gatedistance memoization: cache results per (fromSector, toSector) to avoid
           redundant C++ pathfinding calls when multiple trades share the same sectors.
           Separate tables for non-blacklist vs blacklist-aware variants.
           Valid for the duration of this validation loop (ship doesn't move). -->
      <set_value name="$gdCache" exact="table[]"/>
      <set_value name="$gdCacheBL" exact="table[]"/>
      
      <!-- Resolve enforcement flags once before loop (MD-stored AI parameters override order params) -->
      <set_value name="$enfIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
      <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}? and global.$GT_AIParameters.{this.ship}.$IgnoreBuildStorage?">
        <set_value name="$enfIgnoreBuildStorage" exact="global.$GT_AIParameters.{this.ship}.$IgnoreBuildStorage"/>
      </do_if>
      <set_value name="$enfIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
      <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}? and global.$GT_AIParameters.{this.ship}.$IgnoreCarrierAux?">
        <set_value name="$enfIgnoreCarrierAux" exact="global.$GT_AIParameters.{this.ship}.$IgnoreCarrierAux"/>
      </do_if>

      <!-- Resolve MK3 faction blacklist once for this validation pass (commander for subordinates). -->
      <set_value name="$mk3BlacklistOwnerLoop" exact="this.ship"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
        <set_value name="$mk3BlacklistOwnerLoop" exact="this.ship.commander"/>
      </do_if>
      <set_value name="$mk3FactionBlacklistLoop" exact="table[]"/>
      <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerLoop}?">
        <set_value name="$mk3FactionBlacklistLoop" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerLoop}"/>
      </do_if>
      
      <!-- Priority-first reorder: when priority wares are set, put priority-ware trades at the front.
           Score multiplier alone cannot overcome large profit gaps (e.g. 238k Cr vs 2k Cr).
           This guarantees priority wares are tried first during validation. -->
      <!-- Resolved via lib.gt.priority_wares.resolve: walks instance -> local -> commander.defaultorder
           (or commander.defaultorder.$baseorder via Assist) once and returns [] when no source has wares.
           Replaces the prior 1.5KB nested ternary at this site (see DOCS/MK3_PIPELINE_REFACTOR.md Â§3.8). -->
      <run_script name="'lib.gt.priority_wares.resolve'" result="$pwForReorder">
        <param name="instanceWares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else null"/>
        <param name="localWares" value="if $effectivePriorityWares? then $effectivePriorityWares else null"/>
        <param name="ship" value="this.ship"/>
        <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply']"/>
      </run_script>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList? and $tradeList.count gt 0">
        <do_if value="not $pwForReorder? or $pwForReorder.count == 0">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder SKIPPED: no priority wares (this.$effectivePriorityWares=' + (if this.$effectivePriorityWares? then this.$effectivePriorityWares.count else '?') + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_if value="$pwForReorder? and $pwForReorder.count gt 0 and $tradeList? and $tradeList.count gt 0">
        <create_list name="$priorityTrades"/>
        <create_list name="$nonPriorityTrades"/>
        <do_all exact="$tradeList.count" counter="$ti">
          <set_value name="$t" exact="$tradeList.{$ti}"/>
          <set_value name="$tWare" exact="if $t.$Ware? then $t.$Ware else (if $t.$BuyOffer? then @$t.$BuyOffer.ware else null)"/>
          <set_value name="$isPriority" exact="false"/>
          <do_if value="$tWare?">
            <do_all exact="$pwForReorder.count" counter="$pwi">
              <set_value name="$pwItem" exact="$pwForReorder.{$pwi}"/>
              <!-- Compare by identity first; fallback to .id if references differ (e.g. across save/load) -->
              <do_if value="$pwItem == $tWare or ($pwItem? and $tWare? and $pwItem.id? and $tWare.id? and $pwItem.id == $tWare.id)">
                <set_value name="$isPriority" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$isPriority">
            <append_to_list name="$priorityTrades" exact="$t"/>
          </do_if>
          <do_else>
            <append_to_list name="$nonPriorityTrades" exact="$t"/>
          </do_else>
        </do_all>
        <run_script name="'lib.gt.score.selection_sort'" result="$prioSelectionSort">
          <param name="tradeList" value="$priorityTrades"/>
          <param name="ship" value="this.ship"/>
          <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        </run_script>
        <do_if value="$prioSelectionSort? and $prioSelectionSort.$SortedTrades?">
          <set_value name="$priorityTrades" exact="$prioSelectionSort.$SortedTrades"/>
        </do_if>
        <run_script name="'lib.gt.score.selection_sort'" result="$nonPrioSelectionSort">
          <param name="tradeList" value="$nonPriorityTrades"/>
          <param name="ship" value="this.ship"/>
          <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        </run_script>
        <do_if value="$nonPrioSelectionSort? and $nonPrioSelectionSort.$SortedTrades?">
          <set_value name="$nonPriorityTrades" exact="$nonPrioSelectionSort.$SortedTrades"/>
        </do_if>
        <create_list name="$reorderedList"/>
        <do_all exact="$priorityTrades.count" counter="$pi">
          <append_to_list name="$reorderedList" exact="$priorityTrades.{$pi}"/>
        </do_all>
        <do_all exact="$nonPriorityTrades.count" counter="$ni">
          <append_to_list name="$reorderedList" exact="$nonPriorityTrades.{$ni}"/>
        </do_all>
        <set_value name="$tradeList" exact="$reorderedList"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <do_if value="$priorityTrades.count gt 0">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder: ' + $priorityTrades.count + ' priority-ware trades moved to front of ' + $tradeList.count + ' (validation will try priority wares first)'" chance="100"/>
          </do_if>
          <do_else>
            <!-- Diagnostic: priority wares configured but no matching trades found -->
            <set_value name="$pwDiagNames" exact="''"/>
            <do_all exact="[$pwForReorder.count, 3].min" counter="$pdi">
              <set_value name="$pwDiagNames" exact="$pwDiagNames + (if $pdi gt 1 then ', ' else '') + (if $pwForReorder.{$pdi}? and $pwForReorder.{$pdi} != null then @$pwForReorder.{$pdi}.name else '?')"/>
            </do_all>
            <set_value name="$tDiagNames" exact="''"/>
            <do_all exact="[3, $tradeList.count].min" counter="$tdi">
              <set_value name="$td" exact="$tradeList.{$tdi}"/>
              <set_value name="$tdw" exact="if $td.$Ware? then $td.$Ware else (if $td.$BuyOffer? then @$td.$BuyOffer.ware else null)"/>
              <set_value name="$tDiagNames" exact="$tDiagNames + (if $tdi gt 1 then ', ' else '') + (if $tdw? and $tdw != null then @$tdw.name else '?')"/>
            </do_all>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder: 0 priority-ware trades in ' + $tradeList.count + ' (priority wares: [' + $pwDiagNames + '], first trades: [' + $tDiagNames + '])'" chance="100"/>
          </do_else>
        </do_if>
      </do_if>
      <do_else>
        <!-- Diagnostic: reorder skipped because priority wares not available (e.g. not persisted after interrupt) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList? and $tradeList.count gt 0 and (not $pwForReorder? or $pwForReorder.count == 0)">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder SKIPPED: no priority wares (this.$effectivePriorityWares=' + (if this.$effectivePriorityWares? then this.$effectivePriorityWares.count else 'null') + ')'" chance="100"/>
        </do_if>
      </do_else>

      <!-- Per-ship selection score sort when priority-first reorder did not run. -->
      <do_if value="not ($pwForReorder? and $pwForReorder.count gt 0 and $tradeList? and $tradeList.count gt 0)">
        <do_if value="$tradeList? and $tradeList.count gt 0">
          <run_script name="'lib.gt.score.selection_sort'" result="$fullSelectionSort">
            <param name="tradeList" value="$tradeList"/>
            <param name="ship" value="this.ship"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <do_if value="$fullSelectionSort? and $fullSelectionSort.$SortedTrades?">
            <set_value name="$tradeList" exact="$fullSelectionSort.$SortedTrades"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Single-trip player completion-first reorder (MK4 auto-wares):
           Player delivery targets whose remaining need fits in one load are validated before
           build-storage routes and broad scored trades. Within the bucket, smallest deficit first. -->
      <do_if value="$tradeList? and $tradeList.count gt 1">
        <create_list name="$mk4CompletionFirstTrades"/>
        <create_list name="$mk4CompletionRestTrades"/>
        <set_value name="$mk4CfShipFreeVol" exact="this.ship.cargo.free.all"/>
        <do_all exact="$tradeList.count" counter="$mk4Cfi">
          <set_value name="$mk4CfTrade" exact="$tradeList.{$mk4Cfi}"/>
          <set_value name="$mk4CfSellStation" exact="null"/>
          <set_value name="$mk4CfWare" exact="null"/>
          <do_if value="$mk4CfTrade.$SellStation?">
            <set_value name="$mk4CfSellStation" exact="$mk4CfTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$mk4CfTrade.$SellOffer? and $mk4CfTrade.$SellOffer.owner?">
            <set_value name="$mk4CfSellStation" exact="$mk4CfTrade.$SellOffer.owner"/>
          </do_elseif>
          <do_if value="$mk4CfTrade.$Ware?">
            <set_value name="$mk4CfWare" exact="$mk4CfTrade.$Ware"/>
          </do_if>
          <do_elseif value="$mk4CfTrade.$SellOffer? and $mk4CfTrade.$SellOffer.ware?">
            <set_value name="$mk4CfWare" exact="$mk4CfTrade.$SellOffer.ware"/>
          </do_elseif>
          <set_value name="$mk4CfIsCompletion" exact="false"/>
          <do_if value="$mk4CfSellStation? and $mk4CfSellStation.exists and $mk4CfSellStation.isplayerowned and not $mk4CfSellStation.isclass.buildstorage and $mk4CfWare?">
            <set_value name="$mk4CfTarget" exact="$mk4CfSellStation.cargo.{$mk4CfWare}.target"/>
            <do_if value="$mk4CfTarget gt 0">
              <set_value name="$mk4CfDeficit" exact="[$mk4CfTarget - $mk4CfSellStation.cargo.{$mk4CfWare}.count, 0].max"/>
              <set_value name="$mk4CfVolPerUnit" exact="if $mk4CfWare.volume? and $mk4CfWare.volume gt 0 then $mk4CfWare.volume else 1"/>
              <set_value name="$mk4CfOneTripUnits" exact="($mk4CfShipFreeVol / $mk4CfVolPerUnit)i"/>
              <do_if value="$mk4CfDeficit gt 0 and $mk4CfOneTripUnits gt 0 and $mk4CfDeficit le $mk4CfOneTripUnits">
                <set_value name="$mk4CfIsCompletion" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
          <do_if value="$mk4CfIsCompletion">
            <append_to_list name="$mk4CompletionFirstTrades" exact="$mk4CfTrade"/>
          </do_if>
          <do_else>
            <append_to_list name="$mk4CompletionRestTrades" exact="$mk4CfTrade"/>
          </do_else>
        </do_all>
        <do_if value="$mk4CompletionFirstTrades.count gt 0">
          <create_list name="$mk4CompletionOrdered"/>
          <set_value name="$mk4CfPicked" exact="table[]"/>
          <do_all exact="$mk4CompletionFirstTrades.count" counter="$mk4CfPass">
            <set_value name="$mk4CfBestIdx" exact="0"/>
            <set_value name="$mk4CfBestDeficit" exact="999999999"/>
            <do_all exact="$mk4CompletionFirstTrades.count" counter="$mk4CfIdx">
              <do_if value="not $mk4CfPicked.{$mk4CfIdx}?">
                <set_value name="$mk4CfCand" exact="$mk4CompletionFirstTrades.{$mk4CfIdx}"/>
                <set_value name="$mk4CfCandStation" exact="if $mk4CfCand.$SellStation? then $mk4CfCand.$SellStation else (if $mk4CfCand.$SellOffer? and $mk4CfCand.$SellOffer.owner? then $mk4CfCand.$SellOffer.owner else null)"/>
                <set_value name="$mk4CfCandWare" exact="if $mk4CfCand.$Ware? then $mk4CfCand.$Ware else (if $mk4CfCand.$SellOffer? and $mk4CfCand.$SellOffer.ware? then $mk4CfCand.$SellOffer.ware else null)"/>
                <set_value name="$mk4CfCandDeficit" exact="999999999"/>
                <do_if value="$mk4CfCandStation? and $mk4CfCandStation.exists and $mk4CfCandWare?">
                  <set_value name="$mk4CfCandTarget" exact="$mk4CfCandStation.cargo.{$mk4CfCandWare}.target"/>
                  <do_if value="$mk4CfCandTarget gt 0">
                    <set_value name="$mk4CfCandDeficit" exact="[$mk4CfCandTarget - $mk4CfCandStation.cargo.{$mk4CfCandWare}.count, 0].max"/>
                  </do_if>
                </do_if>
                <do_if value="$mk4CfCandDeficit lt $mk4CfBestDeficit">
                  <set_value name="$mk4CfBestDeficit" exact="$mk4CfCandDeficit"/>
                  <set_value name="$mk4CfBestIdx" exact="$mk4CfIdx"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$mk4CfBestIdx gt 0">
              <append_to_list name="$mk4CompletionOrdered" exact="$mk4CompletionFirstTrades.{$mk4CfBestIdx}"/>
              <set_value name="$mk4CfPicked.{$mk4CfBestIdx}" exact="true"/>
            </do_if>
          </do_all>
          <create_list name="$mk4CompletionMerged"/>
          <do_all exact="$mk4CompletionOrdered.count" counter="$mk4CfOut">
            <append_to_list name="$mk4CompletionMerged" exact="$mk4CompletionOrdered.{$mk4CfOut}"/>
          </do_all>
          <do_all exact="$mk4CompletionRestTrades.count" counter="$mk4CfRest">
            <append_to_list name="$mk4CompletionMerged" exact="$mk4CompletionRestTrades.{$mk4CfRest}"/>
          </do_all>
          <set_value name="$tradeList" exact="$mk4CompletionMerged"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Completion-first reorder: ' + $mk4CompletionFirstTrades.count + ' single-trip player deliveries moved before ' + $mk4CompletionRestTrades.count + ' other trades (smallest deficit first)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Build-storage-first reorder: when build storage trading is allowed, try
           build storage routes first while preserving existing order within each bucket.
           This keeps current scoring/priority-ware behavior intact, but promotes
           construction supply opportunities before non-build-storage routes. -->
      <do_if value="(not $effectiveIgnoreBuildStorage) and $tradeList? and $tradeList.count gt 0">
        <create_list name="$buildStorageTrades"/>
        <create_list name="$nonBuildStorageTrades"/>
        <do_all exact="$tradeList.count" counter="$bsi">
          <set_value name="$bsTrade" exact="$tradeList.{$bsi}"/>
          <set_value name="$bsBuyStation" exact="null"/>
          <set_value name="$bsSellStation" exact="null"/>
          <set_value name="$isBuildStorageTrade" exact="false"/>

          <do_if value="$bsTrade.$BuyStation?">
            <set_value name="$bsBuyStation" exact="$bsTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$bsTrade.$BuyOffer? and $bsTrade.$BuyOffer.owner?">
            <set_value name="$bsBuyStation" exact="$bsTrade.$BuyOffer.owner"/>
          </do_elseif>

          <do_if value="$bsTrade.$SellStation?">
            <set_value name="$bsSellStation" exact="$bsTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$bsTrade.$SellOffer?">
            <do_if value="$bsTrade.$SellOffer.buyer? and @$bsTrade.$SellOffer.buyer.exists">
              <set_value name="$bsSellStation" exact="$bsTrade.$SellOffer.buyer"/>
            </do_if>
            <do_elseif value="$bsTrade.$SellOffer.owner?">
              <set_value name="$bsSellStation" exact="$bsTrade.$SellOffer.owner"/>
            </do_elseif>
          </do_elseif>

          <do_if value="$bsBuyStation? and $bsBuyStation.isclass.buildstorage">
            <set_value name="$isBuildStorageTrade" exact="true"/>
          </do_if>
          <do_if value="$bsSellStation? and $bsSellStation.isclass.buildstorage">
            <set_value name="$isBuildStorageTrade" exact="true"/>
          </do_if>

          <do_if value="$isBuildStorageTrade">
            <append_to_list name="$buildStorageTrades" exact="$bsTrade"/>
          </do_if>
          <do_else>
            <append_to_list name="$nonBuildStorageTrades" exact="$bsTrade"/>
          </do_else>
        </do_all>

        <do_if value="$buildStorageTrades.count gt 0">
          <create_list name="$buildStorageReordered"/>
          <do_all exact="$buildStorageTrades.count" counter="$bsoi">
            <append_to_list name="$buildStorageReordered" exact="$buildStorageTrades.{$bsoi}"/>
          </do_all>
          <do_all exact="$nonBuildStorageTrades.count" counter="$nbsoi">
            <append_to_list name="$buildStorageReordered" exact="$nonBuildStorageTrades.{$nbsoi}"/>
          </do_all>
          <set_value name="$tradeList" exact="$buildStorageReordered"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BuildStorage-first reorder: ' + $buildStorageTrades.count + ' build-storage trades moved to front of ' + $tradeList.count + ' (allowBuildstorage=true)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Option A validation composition:
           Keep global maxTrades cap, but build validation sequence round-robin by delivery
           target (customer station). Enforce strict BuildStorage-first by consuming all
           BuildStorage target buckets before non-BuildStorage buckets. -->
      <do_if value="$tradeList? and $tradeList.count gt 1">
        <create_list name="$optABuildTrades"/>
        <create_list name="$optANonBuildTrades"/>
        <do_all exact="$tradeList.count" counter="$optaSplitIdx">
          <set_value name="$optaTrade" exact="$tradeList.{$optaSplitIdx}"/>
          <set_value name="$optaBuyStation" exact="null"/>
          <set_value name="$optaSellStation" exact="null"/>
          <set_value name="$optaIsBuildStorageTrade" exact="false"/>

          <do_if value="$optaTrade.$BuyStation?">
            <set_value name="$optaBuyStation" exact="$optaTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$optaTrade.$BuyOffer? and $optaTrade.$BuyOffer.owner?">
            <set_value name="$optaBuyStation" exact="$optaTrade.$BuyOffer.owner"/>
          </do_elseif>

          <do_if value="$optaTrade.$SellStation?">
            <set_value name="$optaSellStation" exact="$optaTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$optaTrade.$SellOffer?">
            <do_if value="$optaTrade.$SellOffer.buyer? and @$optaTrade.$SellOffer.buyer.exists">
              <set_value name="$optaSellStation" exact="$optaTrade.$SellOffer.buyer"/>
            </do_if>
            <do_elseif value="$optaTrade.$SellOffer.owner?">
              <set_value name="$optaSellStation" exact="$optaTrade.$SellOffer.owner"/>
            </do_elseif>
          </do_elseif>

          <do_if value="$optaBuyStation? and $optaBuyStation.isclass.buildstorage">
            <set_value name="$optaIsBuildStorageTrade" exact="true"/>
          </do_if>
          <do_if value="$optaSellStation? and $optaSellStation.isclass.buildstorage">
            <set_value name="$optaIsBuildStorageTrade" exact="true"/>
          </do_if>

          <do_if value="$optaIsBuildStorageTrade">
            <append_to_list name="$optABuildTrades" exact="$optaTrade"/>
          </do_if>
          <do_else>
            <append_to_list name="$optANonBuildTrades" exact="$optaTrade"/>
          </do_else>
        </do_all>

        <!-- BuildStorage remaining-need bias (simple rule):
             prioritize candidates with the smallest remaining destination demand first.
             This helps finish near-complete build storage requirements earlier. -->
        <do_if value="$optABuildTrades.count gt 1">
          <create_list name="$optABuildNeedOrdered"/>
          <set_value name="$optaBuildNeedPicked" exact="table[]"/>
          <do_all exact="$optABuildTrades.count" counter="$optaNeedPass">
            <set_value name="$optaBestNeedIdx" exact="0"/>
            <set_value name="$optaBestNeedValue" exact="999999999"/>
            <do_all exact="$optABuildTrades.count" counter="$optaNeedIdx">
              <set_value name="$optaNeedAlreadyPicked" exact="false"/>
              <do_if value="$optaBuildNeedPicked.{$optaNeedIdx}?">
                <set_value name="$optaNeedAlreadyPicked" exact="true"/>
              </do_if>
              <do_if value="not $optaNeedAlreadyPicked">
                <set_value name="$optaNeedTrade" exact="$optABuildTrades.{$optaNeedIdx}"/>
                <set_value name="$optaNeedValue" exact="999999999"/>
                <do_if value="$optaNeedTrade.$SellOfferAmount? and $optaNeedTrade.$SellOfferAmount ge 0">
                  <set_value name="$optaNeedValue" exact="$optaNeedTrade.$SellOfferAmount"/>
                </do_if>
                <do_elseif value="$optaNeedTrade.$SellOffer? and $optaNeedTrade.$SellOffer.amount? and $optaNeedTrade.$SellOffer.amount ge 0">
                  <set_value name="$optaNeedValue" exact="$optaNeedTrade.$SellOffer.amount"/>
                </do_elseif>
                <do_if value="$optaNeedValue lt $optaBestNeedValue">
                  <set_value name="$optaBestNeedValue" exact="$optaNeedValue"/>
                  <set_value name="$optaBestNeedIdx" exact="$optaNeedIdx"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$optaBestNeedIdx gt 0">
              <append_to_list name="$optABuildNeedOrdered" exact="$optABuildTrades.{$optaBestNeedIdx}"/>
              <set_value name="$optaBuildNeedPicked.{$optaBestNeedIdx}" exact="true"/>
            </do_if>
          </do_all>
          <set_value name="$optABuildTrades" exact="$optABuildNeedOrdered"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$optaNeedPreview" exact="''"/>
            <do_all exact="[3, $optABuildTrades.count].min" counter="$optaNeedPreviewIdx">
              <set_value name="$optaNeedPreviewTrade" exact="$optABuildTrades.{$optaNeedPreviewIdx}"/>
              <set_value name="$optaNeedPreviewValue" exact="if $optaNeedPreviewTrade.$SellOfferAmount? then $optaNeedPreviewTrade.$SellOfferAmount else 'n/a'"/>
              <set_value name="$optaNeedPreview" exact="$optaNeedPreview + (if $optaNeedPreviewIdx gt 1 then ', ' else '') + $optaNeedPreviewValue"/>
            </do_all>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BuildStorage remaining-need bias: ordered ' + $optABuildTrades.count + ' build-storage trades by smallest remaining amount first (first3=[' + $optaNeedPreview + '])'" chance="100"/>
          </do_if>
        </do_if>

        <create_list name="$optABuildOrdered"/>
        <set_value name="$optABuildRemaining" exact="$optABuildTrades.count"/>
        <set_value name="$optABuildPicked" exact="table[]"/>
        <do_all exact="$optABuildTrades.count" counter="$optaBuildPass">
          <do_if value="$optABuildRemaining gt 0">
            <create_list name="$optaBuildRoundTargets"/>
            <do_all exact="$optABuildTrades.count" counter="$optaBuildIdx">
              <set_value name="$optaBuildAlreadyPicked" exact="false"/>
              <do_if value="$optABuildPicked.{$optaBuildIdx}?">
                <set_value name="$optaBuildAlreadyPicked" exact="true"/>
              </do_if>
              <do_if value="$optABuildRemaining gt 0 and not $optaBuildAlreadyPicked">
                <set_value name="$optaBuildTrade" exact="$optABuildTrades.{$optaBuildIdx}"/>
                <set_value name="$optaBuildTarget" exact="if $optaBuildTrade.$SellStation? then $optaBuildTrade.$SellStation else (if $optaBuildTrade.$SellOffer? and $optaBuildTrade.$SellOffer.owner? then $optaBuildTrade.$SellOffer.owner else null)"/>
                <set_value name="$optaBuildSeenTarget" exact="false"/>
                <do_if value="$optaBuildRoundTargets.count gt 0">
                  <do_all exact="$optaBuildRoundTargets.count" counter="$optaBuildTargetIdx">
                    <set_value name="$optaBuildSeenTargetObj" exact="$optaBuildRoundTargets.{$optaBuildTargetIdx}"/>
                    <do_if value="$optaBuildSeenTargetObj == $optaBuildTarget or ($optaBuildSeenTargetObj? and $optaBuildTarget? and $optaBuildSeenTargetObj.id? and $optaBuildTarget.id? and $optaBuildSeenTargetObj.id == $optaBuildTarget.id)">
                      <set_value name="$optaBuildSeenTarget" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $optaBuildSeenTarget">
                  <append_to_list name="$optABuildOrdered" exact="$optaBuildTrade"/>
                  <append_to_list name="$optaBuildRoundTargets" exact="$optaBuildTarget"/>
                  <set_value name="$optABuildPicked.{$optaBuildIdx}" exact="true"/>
                  <set_value name="$optABuildRemaining" exact="$optABuildRemaining - 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
        </do_all>

        <create_list name="$optANonBuildOrdered"/>
        <set_value name="$optANonBuildRemaining" exact="$optANonBuildTrades.count"/>
        <set_value name="$optANonBuildPicked" exact="table[]"/>
        <do_all exact="$optANonBuildTrades.count" counter="$optaNonBuildPass">
          <do_if value="$optANonBuildRemaining gt 0">
            <create_list name="$optaNonBuildRoundTargets"/>
            <do_all exact="$optANonBuildTrades.count" counter="$optaNonBuildIdx">
              <set_value name="$optaNonBuildAlreadyPicked" exact="false"/>
              <do_if value="$optANonBuildPicked.{$optaNonBuildIdx}?">
                <set_value name="$optaNonBuildAlreadyPicked" exact="true"/>
              </do_if>
              <do_if value="$optANonBuildRemaining gt 0 and not $optaNonBuildAlreadyPicked">
                <set_value name="$optaNonBuildTrade" exact="$optANonBuildTrades.{$optaNonBuildIdx}"/>
                <set_value name="$optaNonBuildTarget" exact="if $optaNonBuildTrade.$SellStation? then $optaNonBuildTrade.$SellStation else (if $optaNonBuildTrade.$SellOffer? and $optaNonBuildTrade.$SellOffer.owner? then $optaNonBuildTrade.$SellOffer.owner else null)"/>
                <set_value name="$optaNonBuildSeenTarget" exact="false"/>
                <do_if value="$optaNonBuildRoundTargets.count gt 0">
                  <do_all exact="$optaNonBuildRoundTargets.count" counter="$optaNonBuildTargetIdx">
                    <set_value name="$optaNonBuildSeenTargetObj" exact="$optaNonBuildRoundTargets.{$optaNonBuildTargetIdx}"/>
                    <do_if value="$optaNonBuildSeenTargetObj == $optaNonBuildTarget or ($optaNonBuildSeenTargetObj? and $optaNonBuildTarget? and $optaNonBuildSeenTargetObj.id? and $optaNonBuildTarget.id? and $optaNonBuildSeenTargetObj.id == $optaNonBuildTarget.id)">
                      <set_value name="$optaNonBuildSeenTarget" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $optaNonBuildSeenTarget">
                  <append_to_list name="$optANonBuildOrdered" exact="$optaNonBuildTrade"/>
                  <append_to_list name="$optaNonBuildRoundTargets" exact="$optaNonBuildTarget"/>
                  <set_value name="$optANonBuildPicked.{$optaNonBuildIdx}" exact="true"/>
                  <set_value name="$optANonBuildRemaining" exact="$optANonBuildRemaining - 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
        </do_all>

        <create_list name="$optAFinalTradeList"/>
        <do_all exact="$optABuildOrdered.count" counter="$optaOutBuildIdx">
          <append_to_list name="$optAFinalTradeList" exact="$optABuildOrdered.{$optaOutBuildIdx}"/>
        </do_all>
        <do_all exact="$optANonBuildOrdered.count" counter="$optaOutNonBuildIdx">
          <append_to_list name="$optAFinalTradeList" exact="$optANonBuildOrdered.{$optaOutNonBuildIdx}"/>
        </do_all>
        <set_value name="$tradeList" exact="$optAFinalTradeList"/>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': OptionA round-robin compose: buildTargets=' + $optABuildOrdered.count + ', nonBuildTargets=' + $optANonBuildOrdered.count + ', total=' + $tradeList.count + ' (strict build-storage-first)'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Iterate through trade list -->
      <!-- Check if tradeList exists and has items before looping -->
      <do_if value="(if $tradeList != null then $tradeList.count else 0) gt 0">
        <!-- Full validation sweep:
             validate all generated candidates each cycle (no top-N truncation).
             This mirrors MK1's "evaluate complete candidate set" behavior and avoids
             starving lower-ranked but still valid trades when early entries fail. -->
        <set_value name="$validationTradeLimit" exact="$tradeList.count"/>
        <set_value name="$validatedCandidateLimit" exact="if this.$effectiveMaxTrades? and this.$effectiveMaxTrades gt 0 then this.$effectiveMaxTrades else 1"/>
        <set_value name="this.$gt_dockMemo" exact="table[]"/>
        <do_all exact="$validationTradeLimit" counter="$tradeIdx">
          <set_value name="$currentTrade" exact="$tradeList.{$tradeIdx}"/>
          <set_value name="$tradesChecked" operation="add"/>
          
          <!-- Check if currentTrade is valid before processing -->
          <do_if value="$currentTrade? and $currentTrade != null">
              <!-- Extract stations from trade (handle both new list format and old single-trade format) -->
              <!-- Initialize stations to null first, then extract -->
              <set_value name="$buyStation" exact="null"/>
              <set_value name="$sellStation" exact="null"/>
              
              <!-- Check if this is a sell-only trade first -->
              <set_value name="$isSellOnlyTrade" exact="false"/>
              <do_if value="$currentTrade.$IsSellOnly? and $currentTrade.$IsSellOnly">
                <set_value name="$isSellOnlyTrade" exact="true"/>
              </do_if>
              
              <!-- Extract buy station (may be null for sell-only trades) -->
              <do_if value="$currentTrade.$BuyStation?">
                <set_value name="$buyStation" exact="$currentTrade.$BuyStation"/>
              </do_if>
              <do_else>
                <do_if value="$currentTrade.$BuyOffer?">
                  <do_if value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                    <set_value name="$buyStation" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer.owner?">
                    <set_value name="$buyStation" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_else>
              
              <!-- Extract sell station (always required): prefer buy-offer buyer (vanilla trade perform / build storage). -->
              <do_if value="$currentTrade.$SellStation?">
                <set_value name="$sellStation" exact="$currentTrade.$SellStation"/>
              </do_if>
              <do_else>
                <do_if value="$currentTrade.$SellOffer?">
                  <do_if value="$currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists">
                    <set_value name="$sellStation" exact="@$currentTrade.$SellOffer.buyer"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$SellOffer.owner?">
                    <set_value name="$sellStation" exact="@$currentTrade.$SellOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_else>
              
              <!-- For sell-only trades, only require sellStation; for normal trades, require both -->
              <do_if value="$isSellOnlyTrade">
                <!-- Sell-only trade: only sellStation required -->
                <do_if value="$sellStation? and $sellStation != null">
                  <!-- Use safe access for tradeIdx in debug text -->
                  <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                  <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validating SELL-ONLY trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ': ' + (if $currentTrade.$Ware? then @$currentTrade.$Ware.name else 'Unknown') + ' (Ship cargo â†’ ' + (if $sellStation? then @$sellStation.knownname else 'Unknown') + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Check docking permissions FIRST (most common failure, cheapest check) -->
                  <!-- Skip buy-station checks for sell-only trades (ship already has cargo) -->
                  <!-- Also check if BuyStation is not a station (could be ship for sell-only trades) -->
                  <set_value name="$buyStationIsStation" exact="false"/>
                  <do_if value="$buyStation?">
                    <set_value name="$buyStationIsStation" exact="@$buyStation.isclass.station"/>
                  </do_if>
                  
                  <!-- Only check buy-station docking if it's NOT a sell-only trade (always true for sell-only) -->
                  <set_value name="$canDockAtBuyStation" exact="true"/>
                  
                  <!-- Delivery dock: trading dock on destination (build storage object when applicable). -->
                  <run_script name="'lib.gt.dockcheck'" result="$mk4SellOnlyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtSellStation" exact="$mk4SellOnlyDockResult.$CanDock"/>
        
                <do_if value="not $canDockAtBuyStation or not $canDockAtSellStation">
                  <!-- DOCKING NOT ALLOWED - Skip to next trade -->
                  <set_value name="$tradesRejectedDocking" operation="add"/>
                  <set_value name="$deniedStation" exact="if not $canDockAtBuyStation then $buyStation else $sellStation"/>
                  <set_value name="$deniedType" exact="if not $canDockAtBuyStation then 'BUY' else 'SELL'"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' DOCKING DENIED:' +
                      '\n  Station: ' + @$deniedStation.knownname + 
                      '\n  Sector: ' + @$deniedStation.sector.knownname + 
                      '\n  Type: ' + $deniedType + 
                      '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>

                    <!-- Extra cache-only detail (capped): log dock probe on denied station -->
                    <do_if value="$searchMethod == 'cache' and $cacheDetailLogCount lt $cacheDetailLogMax">
                      <set_value name="$cacheDetailLogCount" operation="add"/>
                      <set_value name="$dockAllowedBuyText" exact="if $canDockAtBuyStation? then $canDockAtBuyStation else 'null'"/>
                      <set_value name="$dockAllowedSellText" exact="if $canDockAtSellStation? then $canDockAtSellStation else 'null'"/>
                      <set_value name="$sellOfferId" exact="null"/>
                      <do_if value="$currentTrade.$SellOffer?">
                        <set_value name="$sellOfferId" exact="@$currentTrade.$SellOffer.id"/>
                      </do_if>
                      <set_value name="$cacheDeniedDockFound" exact="false"/>
                      <find_dockingbay name="$cacheDeniedDockBay" object="$deniedStation" checkoperational="true" multiple="false">
                        <match_dock size="this.ship.docksize" trading="true" storage="false"/>
                        <match_relation_to object="this.ship" comparison="not" relation="enemy"/>
                      </find_dockingbay>
                      <do_if value="$cacheDeniedDockBay">
                        <set_value name="$cacheDeniedDockFound" exact="true"/>
                      </do_if>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': [CACHE-DETAIL] DockingDenied trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe +
                        '\n  DeniedType: ' + $deniedType +
                        '\n  CanDock BUY=' + $dockAllowedBuyText + ' SELL=' + $dockAllowedSellText +
                        '\n  ShipDocksize: ' + this.ship.docksize +
                        '\n  SellOfferId: ' + (if $sellOfferId? and $sellOfferId != null then $sellOfferId else 'null') +
                        '\n  find_dockingbay(trading) on denied station: ' + (if $cacheDeniedDockFound then 'YES' else 'NO')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Scenario 3: Flag ship-specific docking failure on cache entry -->
                  <do_if value="$searchMethod == 'cache'">
                    <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'docking_denied']"/>
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- Use cached blacklistgroup from init -->
                <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                
                <!-- Resolve sector whitelist for blacklist checks (whitelist overrides blacklist, matches GT_IsSectorBlacklisted) -->
                <set_value name="$validationWhitelist" exact="[]"/>
                <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                  <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
                </do_if>
                
                <!-- Check path reachability BEFORE blacklist (faster to fail on unreachable) -->
                <!-- For sell-only trades, skip buy-station pathfinding (ship already has cargo) -->
                <set_value name="$currentSector" exact="this.ship.sector"/>
                <!-- For sell-only trades, buySector is current sector (ship already has cargo) -->
                <set_value name="$buySector" exact="$currentSector"/>
                <do_if value="not $isSellOnlyTrade and $buyStation?">
                  <set_value name="$buySector" exact="$buyStation.sector"/>
                </do_if>
                <set_value name="$sellSector" exact="$sellStation.sector"/>
                
                <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
                <set_value name="$currentSectorIsBlacklisted" exact="false"/>
                <do_if value="$blacklistgroup?">
                  <set_value name="$currentSectorWhitelisted" exact="false"/>
                  <do_if value="$validationWhitelist.count gt 0">
                    <do_all exact="$validationWhitelist.count" counter="$swIdx">
                      <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                        <set_value name="$currentSectorWhitelisted" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  <do_if value="not $currentSectorWhitelisted">
                    <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                    <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                    <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                  </do_if>
                </do_if>
        
        <!-- Calculate path distances with escape support -->
        <!-- Buy path calculation with escape support -->
        <!-- For sell-only trades, buy distance is always 0 (ship already has cargo, no buy travel needed) -->
        <set_value name="$buyDistance" exact="-1"/>
        <do_if value="$isSellOnlyTrade">
          <set_value name="$buyDistance" exact="0"/>
        </do_if>
        <do_elseif value="$buySector == $currentSector">
          <set_value name="$buyDistance" exact="0"/>
        </do_elseif>
        <do_elseif value="$currentSectorIsBlacklisted">
          <!-- Escape: non-blacklist gatedistance (memoized) -->
          <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$buySector}?">
            <set_value name="$buyDistance" exact="$gdCache.{$currentSector}.{$buySector}"/>
          </do_if>
          <do_else>
            <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}"/>
            <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
            <set_value name="$gdCache.{$currentSector}.{$buySector}" exact="$buyDistance"/>
          </do_else>
        </do_elseif>
        <do_else>
          <!-- Normal: blacklist-aware gatedistance (memoized) -->
          <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$buySector}?">
            <set_value name="$buyDistance" exact="$gdCacheBL.{$currentSector}.{$buySector}"/>
          </do_if>
          <do_else>
            <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}.{$blacklistgroup}.{this.ship}"/>
            <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
            <set_value name="$gdCacheBL.{$currentSector}.{$buySector}" exact="$buyDistance"/>
          </do_else>
        </do_else>
        
        <!-- Sell path: Calculate based on buy location -->
        <set_value name="$sellDistance" exact="-1"/>
        <do_if value="$sellSector == $buySector">
          <set_value name="$sellDistance" exact="0"/>
        </do_if>
        <do_elseif value="$buySector == $currentSector">
          <!-- Ship in buy sector: escape vs normal path to sell sector -->
          <do_if value="$currentSectorIsBlacklisted">
            <!-- Escape: non-blacklist gatedistance (memoized) -->
            <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$sellSector}?">
              <set_value name="$sellDistance" exact="$gdCache.{$currentSector}.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}"/>
              <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
              <set_value name="$gdCache.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
            </do_else>
          </do_if>
          <do_else>
            <!-- Normal: blacklist-aware gatedistance (memoized) -->
            <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$sellSector}?">
              <set_value name="$sellDistance" exact="$gdCacheBL.{$currentSector}.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
              <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
              <set_value name="$gdCacheBL.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
            </do_else>
          </do_else>
        </do_elseif>
        <do_else>
          <!-- Normal: buyâ†’sell blacklist-aware gatedistance (memoized) -->
          <do_if value="$gdCacheBL.{$buySector}? and $gdCacheBL.{$buySector}.{$sellSector}?">
            <set_value name="$sellDistance" exact="$gdCacheBL.{$buySector}.{$sellSector}"/>
          </do_if>
          <do_else>
            <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
            <do_if value="not $gdCacheBL.{$buySector}?"><set_value name="$gdCacheBL.{$buySector}" exact="table[]"/></do_if>
            <set_value name="$gdCacheBL.{$buySector}.{$sellSector}" exact="$sellDistance"/>
          </do_else>
        </do_else>
        
        <!-- Always log distance check to diagnose issues -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
          <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PATH check (blacklist-aware):' +
            '\n  Current sector: ' + @$currentSector.knownname +
            '\n  BUY: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance: ' + $buyDistance + ')' +
            '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance: ' + $sellDistance + ')' +
            '\n  Blacklist group: ' + $blacklistgroup +
            '\n  Result: ' + (if ($buyDistance lt 0 and not $isSellOnlyTrade) or $sellDistance lt 0 then 'BLOCKED' else 'OK')" 
            chance="100"/>
        </do_if>
        
        <!-- For sell-only trades, only check sell path (buy path is always 0) -->
        <set_value name="$pathBlocked" exact="false"/>
        <do_if value="not $isSellOnlyTrade">
          <do_if value="$buyDistance lt 0">
            <set_value name="$pathBlocked" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$sellDistance lt 0">
          <set_value name="$pathBlocked" exact="true"/>
        </do_if>
        
        <do_if value="$pathBlocked">
          <!-- PATH BLOCKED - Skip to next trade -->
          <set_value name="$tradesRejectedPath" operation="add"/>
          <set_value name="$unreachableStation" exact="if ($buyDistance lt 0 and not $isSellOnlyTrade) then $buyStation else $sellStation"/>
          <set_value name="$unreachableType" exact="if ($buyDistance lt 0 and not $isSellOnlyTrade) then 'BUY' else 'SELL'"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' PATH BLOCKED:' +
              '\n  Station: ' + @$unreachableStation.knownname + 
              '\n  Type: ' + $unreachableType + 
              '\n  Reason: No path exists (disconnected sectors, war, or gates destroyed)' + 
              '\n  â†’ Trying next trade in list...'" 
              chance="100"/>
          </do_if>
          
          <!-- Scenario 3: Flag ship-specific path failure on cache entry -->
          <do_if value="$searchMethod == 'cache'">
            <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'path_blocked']"/>
          </do_if>
          
          <!-- Continue to next trade in list -->
          <continue/>
        </do_if>
              </do_if>
              <do_else>
                <!-- Sell-only trade missing sellStation - skip this trade -->
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' MISSING SELL STATION (sell-only trade requires sellStation)'" chance="100"/>
                <continue/>
              </do_else>
            </do_if>
            <do_else>
                <!-- Normal trade: require both buyStation and sellStation -->
                <do_if value="$buyStation? and $buyStation != null and $sellStation? and $sellStation != null">
                  <!-- Normal trade validation continues here - same as before but with buy checks -->
                  <!-- Use safe access for tradeIdx in debug text -->
                  <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                  <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validating trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ': ' + (if $currentTrade.$BuyOffer? then @$currentTrade.$BuyOffer.ware.name else 'Unknown') + ' (' + (if $buyStation? then @$buyStation.knownname else 'Unknown') + ' â†’ ' + (if $sellStation? then @$sellStation.knownname else 'Unknown') + ')'" chance="100"/>
                  </do_if>

                  <!-- MK4 hard policy: always deliver to player-owned stations -->
                  <do_if value="not @$sellStation.isplayerowned">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <continue/>
                  </do_if>

                  <!-- MK4 supplier policy -->
                  <set_value name="$valMk4AISupLive" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
                  <set_value name="$valMk4PlSupLive" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
                  <set_value name="$mk4SupplierStationLive" exact="null"/>
                  <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                    <set_value name="$mk4SupplierStationLive" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.owner? and @$currentTrade.$BuyOffer.owner.exists">
                    <set_value name="$mk4SupplierStationLive" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_elseif>
                  <do_if value="not $valMk4PlSupLive and $mk4SupplierStationLive? and @$mk4SupplierStationLive.isplayerowned">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <continue/>
                  </do_if>
                  <do_if value="not $valMk4AISupLive">
                    <do_if value="not $mk4SupplierStationLive? or not @$mk4SupplierStationLive.isplayerowned">
                      <set_value name="$tradesRejectedRestriction" operation="add"/>
                      <continue/>
                    </do_if>
                  </do_if>
                  
                  <!-- Check docking FIRST (most common failure): lib.gt.dockcheck purpose=trade. -->
                  <run_script name="'lib.gt.dockcheck'" result="$mk4BuyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$buyStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtBuyStation" exact="$mk4BuyDockResult.$CanDock"/>
                  <run_script name="'lib.gt.dockcheck'" result="$mk4SellDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtSellStation" exact="$mk4SellDockResult.$CanDock"/>
                  
                  <do_if value="not $canDockAtBuyStation or not $canDockAtSellStation">
                    <!-- DOCKING NOT ALLOWED - Skip to next trade -->
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <set_value name="$deniedStation" exact="if not $canDockAtBuyStation then $buyStation else $sellStation"/>
                    <set_value name="$deniedType" exact="if not $canDockAtBuyStation then 'BUY' else 'SELL'"/>
                    
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' DOCKING DENIED:' +
                      '\n  Station: ' + @$deniedStation.knownname + 
                      '\n  Sector: ' + @$deniedStation.sector.knownname + 
                      '\n  Type: ' + $deniedType + 
                      '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>

                    <!-- Extra cache-only detail (capped): log dock probe on denied station -->
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMethod == 'cache' and $cacheDetailLogCount lt $cacheDetailLogMax">
                      <set_value name="$cacheDetailLogCount" operation="add"/>
                      <set_value name="$dockAllowedBuyText" exact="if $canDockAtBuyStation? then $canDockAtBuyStation else 'null'"/>
                      <set_value name="$dockAllowedSellText" exact="if $canDockAtSellStation? then $canDockAtSellStation else 'null'"/>
                      <set_value name="$buyOfferId" exact="null"/>
                      <set_value name="$sellOfferId" exact="null"/>
                      <do_if value="$currentTrade.$BuyOffer?">
                        <set_value name="$buyOfferId" exact="@$currentTrade.$BuyOffer.id"/>
                      </do_if>
                      <do_if value="$currentTrade.$SellOffer?">
                        <set_value name="$sellOfferId" exact="@$currentTrade.$SellOffer.id"/>
                      </do_if>
                      <set_value name="$cacheDeniedDockFound" exact="false"/>
                      <find_dockingbay name="$cacheDeniedDockBay" object="$deniedStation" checkoperational="true" multiple="false">
                        <match_dock size="this.ship.docksize" trading="true" storage="false"/>
                        <match_relation_to object="this.ship" comparison="not" relation="enemy"/>
                      </find_dockingbay>
                      <do_if value="$cacheDeniedDockBay">
                        <set_value name="$cacheDeniedDockFound" exact="true"/>
                      </do_if>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': [CACHE-DETAIL] DockingDenied trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe +
                        '\n  DeniedType: ' + $deniedType +
                        '\n  CanDock BUY=' + $dockAllowedBuyText + ' SELL=' + $dockAllowedSellText +
                        '\n  ShipDocksize: ' + this.ship.docksize +
                        '\n  BuyOfferId: ' + (if $buyOfferId? and $buyOfferId != null then $buyOfferId else 'null') +
                        '\n  SellOfferId: ' + (if $sellOfferId? and $sellOfferId != null then $sellOfferId else 'null') +
                        '\n  find_dockingbay(trading) on denied station: ' + (if $cacheDeniedDockFound then 'YES' else 'NO')"
                        chance="100"/>
                    </do_if>
                    
                    <!-- Scenario 3: Flag ship-specific docking failure on cache entry -->
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'docking_denied']"/>
                    </do_if>
                    
                    <!-- Continue to next trade in list -->
                    <continue/>
                  </do_if>
                  
                  <!-- Use cached blacklistgroup from init -->
                  <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                  
                  <!-- Resolve sector whitelist for blacklist checks (whitelist overrides blacklist, matches GT_IsSectorBlacklisted) -->
                  <set_value name="$validationWhitelist" exact="[]"/>
                  <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                    <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
                  </do_if>
                  
                  <!-- Check path reachability BEFORE blacklist (faster to fail on unreachable) -->
                  <set_value name="$currentSector" exact="this.ship.sector"/>
                  <set_value name="$buySector" exact="$buyStation.sector"/>
                  <set_value name="$sellSector" exact="$sellStation.sector"/>
                  
                  <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
                  <set_value name="$currentSectorIsBlacklisted" exact="false"/>
                  <do_if value="$blacklistgroup?">
                    <set_value name="$currentSectorWhitelisted" exact="false"/>
                    <do_if value="$validationWhitelist.count gt 0">
                      <do_all exact="$validationWhitelist.count" counter="$swIdx">
                        <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                          <set_value name="$currentSectorWhitelisted" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    <do_if value="not $currentSectorWhitelisted">
                      <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                      <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                      <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Calculate path distances with escape support -->
                  <!-- Buy path calculation with escape support -->
                  <!-- Buy path: If ship is already in buy sector, distance is 0 (no travel needed) -->
                  <set_value name="$buyDistance" exact="-1"/>
                  <do_if value="$buySector == $currentSector">
                    <set_value name="$buyDistance" exact="0"/>
                  </do_if>
                  <do_elseif value="$currentSectorIsBlacklisted">
                    <!-- Escape: non-blacklist gatedistance (memoized) -->
                    <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$buySector}?">
                      <set_value name="$buyDistance" exact="$gdCache.{$currentSector}.{$buySector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}"/>
                      <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
                      <set_value name="$gdCache.{$currentSector}.{$buySector}" exact="$buyDistance"/>
                    </do_else>
                  </do_elseif>
                  <do_else>
                    <!-- Normal: blacklist-aware gatedistance (memoized) -->
                    <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$buySector}?">
                      <set_value name="$buyDistance" exact="$gdCacheBL.{$currentSector}.{$buySector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}.{$blacklistgroup}.{this.ship}"/>
                      <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
                      <set_value name="$gdCacheBL.{$currentSector}.{$buySector}" exact="$buyDistance"/>
                    </do_else>
                  </do_else>
                  
                  <!-- Sell path: Calculate based on buy location -->
                  <set_value name="$sellDistance" exact="-1"/>
                  <do_if value="$sellSector == $buySector">
                    <set_value name="$sellDistance" exact="0"/>
                  </do_if>
                  <do_elseif value="$buySector == $currentSector">
                    <!-- Ship in buy sector: escape vs normal path to sell sector -->
                    <do_if value="$currentSectorIsBlacklisted">
                      <!-- Escape: non-blacklist gatedistance (memoized) -->
                      <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$sellSector}?">
                        <set_value name="$sellDistance" exact="$gdCache.{$currentSector}.{$sellSector}"/>
                      </do_if>
                      <do_else>
                        <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}"/>
                        <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
                        <set_value name="$gdCache.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
                      </do_else>
                    </do_if>
                    <do_else>
                      <!-- Normal: blacklist-aware gatedistance (memoized) -->
                      <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$sellSector}?">
                        <set_value name="$sellDistance" exact="$gdCacheBL.{$currentSector}.{$sellSector}"/>
                      </do_if>
                      <do_else>
                        <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
                        <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
                        <set_value name="$gdCacheBL.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
                      </do_else>
                    </do_else>
                  </do_elseif>
                  <do_else>
                    <!-- Normal: buyâ†’sell blacklist-aware gatedistance (memoized) -->
                    <do_if value="$gdCacheBL.{$buySector}? and $gdCacheBL.{$buySector}.{$sellSector}?">
                      <set_value name="$sellDistance" exact="$gdCacheBL.{$buySector}.{$sellSector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
                      <do_if value="not $gdCacheBL.{$buySector}?"><set_value name="$gdCacheBL.{$buySector}" exact="table[]"/></do_if>
                      <set_value name="$gdCacheBL.{$buySector}.{$sellSector}" exact="$sellDistance"/>
                    </do_else>
                  </do_else>
                  
                  <!-- Always log distance check to diagnose issues -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PATH check (blacklist-aware):' +
                      '\n  Current sector: ' + @$currentSector.knownname +
                      '\n  BUY: ' + @$buyStation.knownname + ' (Sector: ' + @$buyStation.sector.knownname + ', Distance: ' + $buyDistance + ')' +
                      '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance: ' + $sellDistance + ')' +
                      '\n  Blacklist group: ' + $blacklistgroup +
                      '\n  Result: ' + (if $buyDistance lt 0 or $sellDistance lt 0 then 'BLOCKED' else 'OK')" 
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="$buyDistance lt 0 or $sellDistance lt 0">
                    <!-- PATH BLOCKED - Skip to next trade -->
                    <set_value name="$tradesRejectedPath" operation="add"/>
                    <set_value name="$unreachableStation" exact="if $buyDistance lt 0 then $buyStation else $sellStation"/>
                    <set_value name="$unreachableType" exact="if $buyDistance lt 0 then 'BUY' else 'SELL'"/>
                    
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' PATH BLOCKED:' +
                        '\n  Station: ' + @$unreachableStation.knownname + 
                        '\n  Type: ' + $unreachableType + 
                        '\n  Reason: No path exists (disconnected sectors, war, or gates destroyed)' + 
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                    
                    <!-- Scenario 3: Flag ship-specific path failure on cache entry -->
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'path_blocked']"/>
                    </do_if>
                    
                    <!-- Continue to next trade in list -->
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Normal trade missing stations - skip this trade -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' MISSING STATIONS (normal trade requires both buy and sell stations)'" chance="100"/>
                  </do_if>
                  <continue/>
                </do_else>
              </do_else>
              
              <!-- Both sell-only and normal trades continue here (only if they passed initial checks) -->
              <!-- Validate distance from HOME SECTOR (not ship position) -->
              <!-- Subordinates ALWAYS use commander's home sector (via $effectiveHome) -->
              <!-- For non-subordinates: Always use defaultorder.$home as PRIMARY source (fixed value in order) -->
              <!-- Home sector is a fixed value in the order settings and should NEVER drift -->
              <!-- Ships must only trade with stations within maxbuy/maxsell from home sector -->
              <!-- Note: $effectiveHome already handles subordinates correctly (set at initialization) -->
              <set_value name="$homeBase" exact="this.$effectiveHome"/>
              
              <!-- Fallback: Only if effectiveHome is not available, check defaultorder.$home -->
              <do_if value="not $homeBase? or not $homeBase.exists">
                <set_value name="$homeBase" exact="@this.ship.defaultorder.$home"/>
                <do_if value="not $homeBase? or not $homeBase.exists">
                  <!-- REMOVED: Never fall back to ship.sector (causes cascading drift) -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI-ERROR] Home sector not found for ' + this.ship.idcode + ' - effectiveHome and defaultorder.$home are null! This should never happen.'" chance="100"/>
                  </do_if>
                  <!-- Emergency fallback only - this should never happen -->
                  <set_value name="$homeBase" exact="this.ship.sector"/>
                </do_if>
              </do_if>
              
              <!-- Extract home sector -->
              <set_value name="$homeSector" exact="null"/>
              <do_if value="@$homeBase.exists">
                <do_if value="$homeBase.isclass.station">
                  <set_value name="$homeSector" exact="$homeBase.sector"/>
                </do_if>
                <do_elseif value="$homeBase.isclass.sector">
                  <set_value name="$homeSector" exact="$homeBase"/>
                </do_elseif>
              </do_if>
              
              <do_if value="not $homeSector? or not $homeSector.exists">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI-ERROR] Failed to extract home sector from homeBase for ' + this.ship.idcode + ' - using ship.sector as emergency fallback (THIS WILL CAUSE DRIFT!)'" chance="100"/>
                </do_if>
                <!-- Emergency fallback only - this should never happen -->
                <set_value name="$homeSector" exact="this.ship.sector"/>
              </do_if>
              
              <!-- Calculate distance from HOME SECTOR to stations (range-only, no blacklist) -->
              <!-- For sell-only trades, skip buy distance check (no buy station) -->
              <set_value name="$buyDistanceFromHome" exact="0"/>
              <set_value name="$sellDistanceFromHome" exact="-1"/>
              
              <do_if value="not $isSellOnlyTrade">
                <!-- Normal trade: check buy distance from home (memoized) -->
                <set_value name="$buyDistanceFromHome" exact="-1"/>
                <do_if value="$buySector == $homeSector">
                  <set_value name="$buyDistanceFromHome" exact="0"/>
                </do_if>
                <do_else>
                  <do_if value="$gdCache.{$homeSector}? and $gdCache.{$homeSector}.{$buySector}?">
                    <set_value name="$buyDistanceFromHome" exact="$gdCache.{$homeSector}.{$buySector}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$buyDistanceFromHome" exact="$homeSector.gatedistance.{$buySector}"/>
                    <do_if value="not $gdCache.{$homeSector}?"><set_value name="$gdCache.{$homeSector}" exact="table[]"/></do_if>
                    <set_value name="$gdCache.{$homeSector}.{$buySector}" exact="$buyDistanceFromHome"/>
                  </do_else>
                </do_else>
              </do_if>
              
              <!-- Always check sell distance from home (memoized) -->
              <do_if value="$sellSector == $homeSector">
                <set_value name="$sellDistanceFromHome" exact="0"/>
              </do_if>
              <do_else>
                <do_if value="$gdCache.{$homeSector}? and $gdCache.{$homeSector}.{$sellSector}?">
                  <set_value name="$sellDistanceFromHome" exact="$gdCache.{$homeSector}.{$sellSector}"/>
                </do_if>
                <do_else>
                  <set_value name="$sellDistanceFromHome" exact="$homeSector.gatedistance.{$sellSector}"/>
                  <do_if value="not $gdCache.{$homeSector}?"><set_value name="$gdCache.{$homeSector}" exact="table[]"/></do_if>
                  <set_value name="$gdCache.{$homeSector}.{$sellSector}" exact="$sellDistanceFromHome"/>
                </do_else>
              </do_else>
              
              <!-- Resolve max distances safely â€” instance vars may be missing after hot-reload -->
              <set_value name="$_maxBuy" exact="if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else 15"/>
              <set_value name="$_maxSell" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else 15"/>

              <!-- Show calculated distances for diagnosis -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
                <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': HOME SECTOR distance check (trade ' + $tradeIdx + '):' +
                  '\n  Home sector: ' + @$homeSector.knownname +
                  '\n  BUY station: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance from home: ' + $buyDistanceFromHome + '/' + $_maxBuy + ' jumps)' +
                  '\n  SELL station: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance from home: ' + $sellDistanceFromHome + '/' + $_maxSell + ' jumps)' +
                  '\n  Ship position: ' + @this.ship.sector.knownname +
                  '\n  Validation: ' + (if ($buyDistanceFromHome lt 0 or $sellDistanceFromHome lt 0 or ($buyDistanceFromHome gt $_maxBuy and not $isSellOnlyTrade) or $sellDistanceFromHome gt $_maxSell) then 'REJECTED' else 'PASSED')"
                  chance="100"/>
              </do_if>
              
              <!-- Reject if stations exceed maxDistance from home -->
              <set_value name="$distanceCheckFailed" exact="false"/>
              <do_if value="not $isSellOnlyTrade">
                <do_if value="$buyDistanceFromHome lt 0 or $buyDistanceFromHome gt $_maxBuy">
                  <set_value name="$distanceCheckFailed" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$sellDistanceFromHome lt 0 or $sellDistanceFromHome gt $_maxSell">
                <set_value name="$distanceCheckFailed" exact="true"/>
              </do_if>
              
              <do_if value="$distanceCheckFailed">
                <set_value name="$tradesRejectedDistance" operation="add"/>
                
                <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
                <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' DISTANCE EXCEEDED:' +
                    '\n  BUY: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance from home: ' + $buyDistanceFromHome + '/' + $_maxBuy + ' jumps)' +
                    '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance from home: ' + $sellDistanceFromHome + '/' + $_maxSell + ' jumps)' +
                    '\n  Home sector: ' + @$homeSector.knownname +
                    '\n  Ship position: ' + @this.ship.sector.knownname +
                    '\n  Reason: Station(s) exceed maximum distance from home sector' +
                    '\n  â†’ Trying next trade in list...'"
                    chance="100"/>
                </do_if>
                
                <!-- Scenario 3: Flag ship-specific distance failure on cache entry -->
                <do_if value="$searchMethod == 'cache'">
                  <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'distance_exceeded']"/>
                </do_if>
                
                <!-- Continue to next trade in list -->
                <continue/>
              </do_if>
              
              <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
              <set_value name="$currentSectorIsBlacklisted" exact="false"/>
              <do_if value="$blacklistgroup?">
                <set_value name="$currentSectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                      <set_value name="$currentSectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $currentSectorWhitelisted">
                  <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                </do_if>
              </do_if>
              
              <!-- Check if buy station OR its sector is blacklisted -->
              <!-- Always check target sector blacklist - escape only affects PATH, not destination -->
              <!-- For sell-only trades, skip buy station blacklist check (no buy station) -->
              <!-- Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted) -->
              <set_value name="$buyBlacklisted" exact="false"/>
              <do_if value="not $isSellOnlyTrade and $blacklistgroup? and $buyStation?">
                <!-- Check station itself (objectactivity) -->
                <set_value name="$buyStationBlacklisted" exact="@$buyStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                <!-- Check sector (sectoractivity AND sectortravel) unless whitelisted -->
                <set_value name="$buySectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $buyStation.sector">
                      <set_value name="$buySectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <set_value name="$buySectorActivityBlacklisted" exact="false"/>
                <set_value name="$buySectorTravelBlacklisted" exact="false"/>
                <do_if value="not $buySectorWhitelisted">
                  <set_value name="$buySectorActivityBlacklisted" exact="@$buyStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$buySectorTravelBlacklisted" exact="@$buyStation.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                </do_if>
                
                <!-- Block buying in blacklisted sector (force escape) -->
                <!-- Ship in blacklisted sector must NOT buy in that sector -->
                <!-- Ship must escape by buying from a different (non-blacklisted) sector -->
                <do_if value="$buySectorActivityBlacklisted or $buySectorTravelBlacklisted">
                  <!-- Block buying in blacklisted sector (even if ship is already there) -->
                  <set_value name="$buyBlacklisted" exact="true"/>
                </do_if>
                <do_else>
                  <!-- Target sector is not blacklisted - only check station -->
                  <set_value name="$buyBlacklisted" exact="$buyStationBlacklisted"/>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$buyStationNameForDebug" exact="if $buyStation? then @$buyStation.knownname else 'Unknown'"/>
                  <set_value name="$buySectorNameForDebug" exact="if $buyStation? then @$buyStation.sector.knownname else 'Unknown'"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BUY blacklist check:' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (blacklisted: ' + $currentSectorIsBlacklisted + ')' +
                    '\n  Station: ' + $buyStationNameForDebug + 
                    '\n  Sector: ' + $buySectorNameForDebug + 
                    '\n  Station (objectactivity): ' + $buyStationBlacklisted + 
                    '\n  Sector (sectoractivity): ' + $buySectorActivityBlacklisted + 
                    '\n  Sector (sectortravel): ' + $buySectorTravelBlacklisted + 
                    '\n  Ship in buy sector: ' + ($buySector == $currentSector) +
                    '\n  Final result: ' + $buyBlacklisted" 
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Check if sell station OR its sector is blacklisted -->
              <!-- Always check target sector blacklist - escape only affects PATH, not destination -->
              <!-- Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted) -->
              <set_value name="$sellBlacklisted" exact="false"/>
              <do_if value="$blacklistgroup?">
                <!-- Check station itself (objectactivity) -->
                <set_value name="$sellStationBlacklisted" exact="@$sellStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                <!-- Check sector (sectoractivity AND sectortravel) unless whitelisted -->
                <set_value name="$sellSectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $sellStation.sector">
                      <set_value name="$sellSectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <set_value name="$sellSectorActivityBlacklisted" exact="false"/>
                <set_value name="$sellSectorTravelBlacklisted" exact="false"/>
                <do_if value="not $sellSectorWhitelisted">
                  <set_value name="$sellSectorActivityBlacklisted" exact="@$sellStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$sellSectorTravelBlacklisted" exact="@$sellStation.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                </do_if>
                
                <!-- Always check if target sector is blacklisted -->
                <!-- Escape exception: Allow sell sector if ship is already IN it (escape FROM) -->
                <!-- But still block if ship needs to travel TO a blacklisted sector -->
                <do_if value="$sellSectorActivityBlacklisted or $sellSectorTravelBlacklisted">
                  <do_if value="$sellSector == $currentSector">
                    <!-- Ship is already in sell sector - allow escape FROM blacklisted sector -->
                    <!-- Only block if station itself is blacklisted -->
                    <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
                  </do_if>
                  <do_else>
                    <!-- Ship needs to travel TO a blacklisted sector - BLOCK -->
                    <set_value name="$sellBlacklisted" exact="true"/>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- Target sector is not blacklisted - only check station -->
                  <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SELL blacklist check:' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (blacklisted: ' + $currentSectorIsBlacklisted + ')' +
                    '\n  Station: ' + @$sellStation.knownname + 
                    '\n  Sector: ' + @$sellStation.sector.knownname + 
                    '\n  Station (objectactivity): ' + $sellStationBlacklisted + 
                    '\n  Sector (sectoractivity): ' + $sellSectorActivityBlacklisted + 
                    '\n  Sector (sectortravel): ' + $sellSectorTravelBlacklisted + 
                    '\n  Ship in sell sector: ' + ($sellSector == $currentSector) +
                    '\n  Final result: ' + $sellBlacklisted" 
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Block intra-sector trades in blacklisted sectors -->
              <!-- If ship is in blacklisted sector and both buy/sell are in same sector, block to force escape -->
              <set_value name="$isIntraSectorTradeInBlacklisted" exact="false"/>
              <do_if value="$currentSectorIsBlacklisted and $buySector == $currentSector and $sellSector == $currentSector">
                <set_value name="$isIntraSectorTradeInBlacklisted" exact="true"/>
                <set_value name="$buyBlacklisted" exact="true"/>  <!-- Block by marking as blacklisted -->
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Intra-sector trade BLOCKED (escape required):' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (BLACKLISTED)' +
                    '\n  Buy/Sell: Both in ' + @$currentSector.knownname +
                    '\n  Reason: Ship must escape from blacklisted sector'"
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Check if buy/sell station is MK1-supplied (final safety check) -->
              <do_if value="not $buyBlacklisted and not $sellBlacklisted and $effectiveIgnoreMK1Supply? and $effectiveIgnoreMK1Supply and global.$GT_MK1SuppliedStations?">
                <do_if value="$buyStation? and global.$GT_MK1SuppliedStations.{$buyStation}?">
                  <set_value name="$buyBlacklisted" exact="true"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” buy station ' + @$buyStation.knownname + ' is MK1-supplied'" chance="@this.$debugchance"/>
                </do_if>
                <do_if value="not $buyBlacklisted and $sellStation? and global.$GT_MK1SuppliedStations.{$sellStation}?">
                  <set_value name="$sellBlacklisted" exact="true"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” sell station ' + @$sellStation.knownname + ' is MK1-supplied'" chance="@this.$debugchance"/>
                </do_if>
              </do_if>

              <!-- Check if trade is blacklisted -->
              <do_if value="$buyBlacklisted or $sellBlacklisted">
                <!-- BLACKLISTED - Skip to next trade in list -->
                <set_value name="$tradesBlacklisted" operation="add"/>
                <set_value name="$blacklistedStation" exact="if $buyBlacklisted then $buyStation else $sellStation"/>
                <set_value name="$tradeType" exact="if $buyBlacklisted then 'BUY' else 'SELL'"/>
                
                <!-- Determine what was blacklisted (station or sector) -->
                <set_value name="$blacklistReason" exact="'Sector (sectortravel)'"/>  <!-- Default to most common case -->
                <do_if value="$buyBlacklisted">
                  <do_if value="$buyStationBlacklisted">
                    <set_value name="$blacklistReason" exact="'Station (objectactivity)'"/>
                  </do_if>
                  <do_elseif value="$buySectorActivityBlacklisted">
                    <set_value name="$blacklistReason" exact="'Sector (sectoractivity)'"/>
                  </do_elseif>
                </do_if>
                <do_else>
                  <do_if value="$sellStationBlacklisted">
                    <set_value name="$blacklistReason" exact="'Station (objectactivity)'"/>
                  </do_if>
                  <do_elseif value="$sellSectorActivityBlacklisted">
                    <set_value name="$blacklistReason" exact="'Sector (sectoractivity)'"/>
                  </do_elseif>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' BLACKLISTED:' +
                    '\n  Station: ' + @$blacklistedStation.knownname + 
                    '\n  Sector: ' + @$blacklistedStation.sector.knownname + 
                    '\n  Type: ' + $tradeType + 
                    '\n  Reason: ' + $blacklistReason + 
                    '\n  â†’ Trying next trade in list...'" 
                    chance="100"/>
                </do_if>
                
                <!-- Record failed sector for future filtering -->
                <signal_objects object="player.galaxy" param="'GT_Trade_Failed'" param2="table[
                  $Ship = this.ship,
                  $Reason = 'TRADEPARTNER_BLACKLISTED',
                  $FailureText = 'Trade partner is blacklisted (pre-validation)',
                  $Partner = $blacklistedStation,
                  $IsBuying = $buyBlacklisted,
                  $Ware = @$currentTrade.$Ware
                ]"/>
                
                <!-- Scenario 3: Flag ship-specific blacklist failure on cache entry -->
                <do_if value="$searchMethod == 'cache'">
                  <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'blacklisted']"/>
                </do_if>
                
                <!-- Continue to next trade in list -->
                <continue/>
              </do_if>
              
              <!-- Fleet reservation check: skip trades reserved by other ships.
                   Restored from pre-migration gt_trading_search.xml reservation flow.
                   Uses SellOffer object as key (Method B from GT_GenerateTradeKey). -->
              <do_if value="global.$GT_Reservations? and $currentTrade.$SellOffer?">
                <set_value name="$resKey" exact="$currentTrade.$SellOffer"/>
                <do_if value="global.$GT_Reservations.{$resKey}?">
                  <set_value name="$resData" exact="global.$GT_Reservations.{$resKey}"/>
                  <do_if value="$resData.$Until? and player.age lt @$resData.$Until and $resData.$Ship? and @$resData.$Ship != this.ship">
                    <set_value name="$tradesRejectedDemandReserved" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' RESERVED by ' + @$resData.$Ship.idcode + ' (expires in ' + (@$resData.$Until - player.age) + ') - skipping'" chance="100"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- Check if ship can carry this ware type (cargo bay compatibility) -->
              <!-- Some wares (like Methane/gas) require special cargo bays that normal ships don't have -->
              <!-- For sell-only trades, use $Ware instead of $BuyOffer.ware -->
              <set_value name="$ware" exact="null"/>
              <do_if value="$isSellOnlyTrade and $currentTrade.$Ware?">
                <set_value name="$ware" exact="$currentTrade.$Ware"/>
              </do_if>
              <do_elseif value="$currentTrade.$BuyOffer?">
                <set_value name="$ware" exact="@$currentTrade.$BuyOffer.ware"/>
              </do_elseif>
              
              <do_if value="$ware? and $ware != null">
                <set_value name="$canCarryWareType" exact="this.ship.cargo.{$ware}.max gt 0"/>
                <do_if value="not $canCarryWareType and $currentTrade.$CargoWareTransport?">
                  <set_value name="$canCarryWareType" exact="this.ship.waretransport.indexof.{@$currentTrade.$CargoWareTransport}"/>
                </do_if>
                
                <do_if value="not $canCarryWareType">
                  <!-- SHIP CANNOT CARRY THIS WARE TYPE - Skip to next trade -->
                  <set_value name="$tradesRejectedCargo" operation="add"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' INCOMPATIBLE CARGO TYPE:' +
                      '\n  Ware: ' + @$ware.name + 
                      '\n  Reason: Ship does not have required cargo bay type (e.g., liquid/gas requires special containment)' +
                      '\n  Ship cargo max for this ware: ' + this.ship.cargo.{$ware}.max +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  
                  <!-- Do NOT GT_Cache_Flag_Ship: hold-type mismatch is not a per-ship trade failure. -->
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- Validation passed - this trade is valid -->
                <!-- Note: Cargo space and money validation will be handled by clamp_trade_amount before order creation -->
                <!-- Use safe access for tradeIdx -->
                <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' passed validation - checking offer availability...'" chance="100"/>
                </do_if>
                
                <!-- Check offer validity INSIDE loop before breaking -->
                <!-- This allows us to try the next trade if offers are consumed -->
                <!-- Initialize variables before conditionals to prevent property lookup errors -->
                <set_value name="$buyOfferStillValid" exact="true"/>
                <set_value name="$sellOfferStillValid" exact="false"/>
                <set_value name="$buyOfferAvailable" exact="null"/>
                <set_value name="$buyOfferAmount" exact="null"/>
                <set_value name="$sellOfferAvailable" exact="null"/>
                <set_value name="$sellOfferAmount" exact="null"/>
                <set_value name="$buyOfferOwnerValid" exact="true"/>
                <set_value name="$sellOfferOwnerValid" exact="true"/>
                
                <do_if value="$isSellOnlyTrade">
                  <!-- Sell-only trade: only check sell offer -->
                  <do_if value="$currentTrade.$SellOffer?">
                    <set_value name="$sellOfferAvailable" exact="$currentTrade.$SellOffer.available"/>
                    <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and @$currentTrade.$SellOffer.amount gt 0">
                      <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.amount"/>
                    </do_if>
                    <set_value name="$sellOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$SellOffer.owner?">
                      <set_value name="$sellOwnerTmp" exact="@$currentTrade.$SellOffer.owner"/>
                      <do_if value="$sellOwnerTmp? and $sellOwnerTmp.exists">
                        <set_value name="$sellOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$sellOfferStillValid" exact="$sellOfferAvailable and ($sellOfferAmount? and $sellOfferAmount gt 0) and $sellOfferOwnerValid"/>
                    <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$sellDesiredBefore" exact="@$currentTrade.$SellOffer.desiredamount"/>
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': pre-validate SELL-ONLY' +
                        '\n  needed=' + $currentTrade.$Amount +
                        '\n  sell offeramount(ship)=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') +
                        '\n  sell desiredamount=' + (if $sellDesiredBefore? then $sellDesiredBefore else 'null')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Sell-only trade but no sell offer - invalid -->
                    <set_value name="$sellOfferStillValid" exact="false"/>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- Normal trade: check both offers -->
                  <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$SellOffer?">
                    <!-- Re-resolve stale supplier offer before validity check (mirrors final order validation). -->
                    <set_value name="$preValBuyStation" exact="null"/>
                    <set_value name="$preValBuyWare" exact="if $ware? then $ware else null"/>
                    <do_if value="not $preValBuyWare? and $currentTrade.$BuyOffer.ware?">
                      <set_value name="$preValBuyWare" exact="@$currentTrade.$BuyOffer.ware"/>
                    </do_if>
                    <do_if value="$currentTrade.$BuyStation? and @$currentTrade.$BuyStation.exists">
                      <set_value name="$preValBuyStation" exact="$currentTrade.$BuyStation"/>
                    </do_if>
                    <do_elseif value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                      <set_value name="$preValBuyStation" exact="@$currentTrade.$BuyOffer.seller"/>
                    </do_elseif>
                    <do_elseif value="$currentTrade.$BuyOffer.owner? and @$currentTrade.$BuyOffer.owner.exists">
                      <set_value name="$preValBuyStation" exact="@$currentTrade.$BuyOffer.owner"/>
                    </do_elseif>
                    <do_if value="$preValBuyStation? and $preValBuyStation.exists and $preValBuyWare != null">
                      <find_sell_offer seller="$preValBuyStation" wares="$preValBuyWare" tradepartner="this.ship" result="$preValFreshBuyOffer"/>
                      <do_if value="$preValFreshBuyOffer?">
                        <set_value name="$currentTrade.$BuyOffer" exact="$preValFreshBuyOffer"/>
                      </do_if>
                    </do_if>

                    <!-- Re-resolve stale delivery offer before validity check (mirrors final order validation). -->
                    <set_value name="$preValSellStation" exact="null"/>
                    <set_value name="$preValSellWare" exact="if $ware? then $ware else null"/>
                    <do_if value="not $preValSellWare? and $currentTrade.$SellOffer.ware?">
                      <set_value name="$preValSellWare" exact="@$currentTrade.$SellOffer.ware"/>
                    </do_if>
                    <do_if value="$currentTrade.$SellStation? and @$currentTrade.$SellStation.exists">
                      <set_value name="$preValSellStation" exact="$currentTrade.$SellStation"/>
                    </do_if>
                    <do_elseif value="$currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists">
                      <set_value name="$preValSellStation" exact="@$currentTrade.$SellOffer.buyer"/>
                    </do_elseif>
                    <do_elseif value="$currentTrade.$SellOffer.owner? and @$currentTrade.$SellOffer.owner.exists">
                      <set_value name="$preValSellStation" exact="@$currentTrade.$SellOffer.owner"/>
                    </do_elseif>
                    <do_if value="$preValSellStation? and $preValSellStation.exists and $preValSellWare != null">
                      <find_buy_offer buyer="$preValSellStation" wares="$preValSellWare" tradepartner="this.ship" result="$preValFreshSellOffer"/>
                      <do_if value="$preValFreshSellOffer?">
                        <set_value name="$currentTrade.$SellOffer" exact="$preValFreshSellOffer"/>
                      </do_if>
                    </do_if>

                    <!-- Check buy offer: available AND has SOME amount (clamping will handle exact amount reduction) -->
                    <set_value name="$buyOfferAvailable" exact="$currentTrade.$BuyOffer.available"/>
                    <set_value name="$buyOfferAmount" exact="@$currentTrade.$BuyOffer.offeramount.{this.ship}"/>
                    <!-- Supplier-side fallback: only when offeramount is zero but the supplier
                         physically holds unreserved stock (avoids matching reserved-away offers). -->
                    <do_if value="(not $buyOfferAmount? or $buyOfferAmount le 0) and $currentTrade.$BuyOffer.amount? and @$currentTrade.$BuyOffer.amount gt 0">
                      <set_value name="$buyFallbackSeller" exact="null"/>
                      <do_if value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                        <set_value name="$buyFallbackSeller" exact="@$currentTrade.$BuyOffer.seller"/>
                      </do_if>
                      <do_if value="not $buyFallbackSeller? and $currentTrade.$BuyOffer.owner? and @$currentTrade.$BuyOffer.owner.exists">
                        <set_value name="$buyFallbackSeller" exact="@$currentTrade.$BuyOffer.owner"/>
                      </do_if>
                      <set_value name="$buyFallbackStock" exact="0"/>
                      <do_if value="$buyFallbackSeller? and $ware?">
                        <get_ware_reservation object="$buyFallbackSeller" ware="$ware" type="buy" virtual="false" result="$buyFallbackReserved"/>
                        <set_value name="$buyFallbackStock" exact="[$buyFallbackSeller.cargo.{$ware}.count - $buyFallbackReserved, 0].max"/>
                      </do_if>
                      <do_if value="$buyFallbackStock gt 0">
                        <set_value name="$buyOfferAmount" exact="[$buyFallbackStock, @$currentTrade.$BuyOffer.amount].min"/>
                      </do_if>
                    </do_if>
                    <do_if value="(not $buyOfferAmount? or $buyOfferAmount le 0) and $currentTrade.$SellOffer.owner? and @$currentTrade.$SellOffer.owner.exists">
                      <set_value name="$preValBuyWare" exact="if $currentTrade.$Ware? then $currentTrade.$Ware else null"/>
                      <do_if value="not $preValBuyWare? and @$currentTrade.$BuyOffer.ware != null">
                        <set_value name="$preValBuyWare" exact="@$currentTrade.$BuyOffer.ware"/>
                      </do_if>
                      <do_if value="$preValBuyWare?">
                        <set_value name="$buyOfferAmount" exact="[0, $currentTrade.$SellOffer.owner.cargo.{$preValBuyWare}.target - $currentTrade.$SellOffer.owner.cargo.{$preValBuyWare}.count].max"/>
                      </do_if>
                    </do_if>
                    <set_value name="$buyOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                      <set_value name="$buyOfferOwnerValid" exact="true"/>
                    </do_if>
                    <do_if value="not $buyOfferOwnerValid and $currentTrade.$BuyOffer.owner?">
                      <set_value name="$buyOwnerTmp" exact="@$currentTrade.$BuyOffer.owner"/>
                      <do_if value="$buyOwnerTmp? and $buyOwnerTmp.exists">
                        <set_value name="$buyOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$buyOfferStillValid" exact="$buyOfferAvailable and ($buyOfferAmount? and $buyOfferAmount gt 0) and $buyOfferOwnerValid"/>
                    
                    <!-- Check sell offer: effective amount (clamping will handle exact amount reduction) -->
                    <set_value name="$sellOfferAvailable" exact="$currentTrade.$SellOffer.available"/>
                    <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <!-- Symmetric fallback for destination offer amount handling. -->
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and $currentTrade.$SellOffer.amount? and @$currentTrade.$SellOffer.amount gt 0">
                      <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.amount"/>
                    </do_if>
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and $preValSellStation? and $preValSellStation.exists and $preValSellWare?">
                      <set_value name="$sellOfferAmount" exact="[0, $preValSellStation.cargo.{$preValSellWare}.target - $preValSellStation.cargo.{$preValSellWare}.count].max"/>
                    </do_if>
                    <set_value name="$sellOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$SellStation? and @$currentTrade.$SellStation.exists">
                      <set_value name="$sellOfferOwnerValid" exact="true"/>
                    </do_if>
                    <do_if value="not $sellOfferOwnerValid and $currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists">
                      <set_value name="$sellOfferOwnerValid" exact="true"/>
                    </do_if>
                    <do_if value="not $sellOfferOwnerValid and $currentTrade.$SellOffer.owner?">
                      <set_value name="$sellOwnerTmp" exact="@$currentTrade.$SellOffer.owner"/>
                      <do_if value="$sellOwnerTmp? and $sellOwnerTmp.exists">
                        <set_value name="$sellOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Build Storage / internal delivery: .available may stay false while cargo deficit exists. -->
                    <set_value name="$sellOfferStillValid" exact="$sellOfferOwnerValid and ($sellOfferAmount? and $sellOfferAmount gt 0)"/>
                    
                    <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$buyDesiredBefore" exact="@$currentTrade.$BuyOffer.desiredamount"/>
                      <set_value name="$sellDesiredBefore" exact="@$currentTrade.$SellOffer.desiredamount"/>
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': pre-validate NORMAL' +
                        '\n  needed=' + $currentTrade.$Amount +
                        '\n  buy offeramount(ship)=' + (if $buyOfferAmount? then $buyOfferAmount else 'null') +
                        '\n  buy desiredamount=' + (if $buyDesiredBefore? then $buyDesiredBefore else 'null') +
                        '\n  sell offeramount(ship)=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') +
                        '\n  sell desiredamount=' + (if $sellDesiredBefore? then $sellDesiredBefore else 'null')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Normal trade but missing offers - invalid -->
                    <set_value name="$buyOfferStillValid" exact="false"/>
                    <set_value name="$sellOfferStillValid" exact="false"/>
                  </do_else>
                </do_else>
                
                <!-- Check if offers are valid - conditional based on trade type -->
                <set_value name="$offersInvalid" exact="false"/>
                <do_if value="$isSellOnlyTrade">
                  <!-- Sell-only trade: only check sell offer -->
                  <set_value name="$offersInvalid" exact="not $sellOfferStillValid"/>
                </do_if>
                <do_else>
                  <!-- Normal trade: check both offers -->
                  <set_value name="$offersInvalid" exact="not $buyOfferStillValid or not $sellOfferStillValid"/>
                </do_else>
                
                <do_if value="$offersInvalid">
                  <!-- Offer became invalid - try next trade in list -->
                  <set_value name="$tradesRejectedOfferInvalid" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <!-- Compute precise invalid reason (buy/sell availability vs amount shortfall) -->
                    <set_value name="$offerInvalidReason" exact="''"/>
                    <do_if value="$isSellOnlyTrade">
                      <do_if value="not $sellOfferAvailable">
                        <set_value name="$offerInvalidReason" exact="'sell_not_available'"/>
                      </do_if>
                      <do_elseif value="not $sellOfferAmount?">
                        <set_value name="$offerInvalidReason" exact="'sell_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$sellOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$offerInvalidReason" exact="'sell_amount_lt_needed'"/>
                      </do_elseif>
                      <do_else>
                        <set_value name="$offerInvalidReason" exact="'sell_unknown'"/>
                      </do_else>
                    </do_if>
                    <do_else>
                      <set_value name="$buyInvalidReason" exact="'ok'"/>
                      <set_value name="$sellInvalidReason" exact="'ok'"/>
                      <do_if value="not $buyOfferOwnerValid">
                        <set_value name="$buyInvalidReason" exact="'buy_owner_missing'"/>
                      </do_if>
                      <do_elseif value="not $buyOfferAvailable">
                        <set_value name="$buyInvalidReason" exact="'buy_not_available'"/>
                      </do_elseif>
                      <do_elseif value="not $buyOfferAmount?">
                        <set_value name="$buyInvalidReason" exact="'buy_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$buyOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$buyInvalidReason" exact="'buy_amount_lt_needed'"/>
                      </do_elseif>
                      <do_if value="not $sellOfferOwnerValid">
                        <set_value name="$sellInvalidReason" exact="'sell_owner_missing'"/>
                      </do_if>
                      <do_elseif value="not $sellOfferAvailable">
                        <set_value name="$sellInvalidReason" exact="'sell_not_available'"/>
                      </do_elseif>
                      <do_elseif value="not $sellOfferAmount?">
                        <set_value name="$sellInvalidReason" exact="'sell_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$sellOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$sellInvalidReason" exact="'sell_amount_lt_needed'"/>
                      </do_elseif>
                      <set_value name="$offerInvalidReason" exact="'buy=' + $buyInvalidReason + ', sell=' + $sellInvalidReason"/>
                    </do_else>

                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' offer became invalid:' +
                      '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                      '\n  Buy offer: ' + (if $isSellOnlyTrade then 'N/A' else (if $buyOfferAvailable? then ('available=' + $buyOfferAvailable + ', amount=' + (if $buyOfferAmount? then $buyOfferAmount else 'null') + ' (needed: ' + $currentTrade.$Amount + ')') else 'MISSING')) +
                      '\n  Sell offer: available=' + (if $sellOfferAvailable? then $sellOfferAvailable else 'null') + ', amount=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') + ' (needed: ' + $currentTrade.$Amount + ')' +
                      '\n  Failure: ' + $offerInvalidReason +
                      '\n  Reason: offer unavailable or amount is 0/null (clamping would handle partial amounts, but offer is completely unavailable)' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  
                  <!-- Cache maintenance: distinguish universally dead offers (PURGE) from
                       temporary saturation (SKIP) from permanent ship-specific failure (FLAG).
                       .available and .owner.exists are universal; offeramount.{ship} is transient. -->
                  <do_if value="$searchMethod == 'cache'">
                    <!-- Determine if offers are universally dead (not available / owner destroyed) -->
                    <set_value name="$universallyDead" exact="false"/>
                    <do_if value="not $isSellOnlyTrade">
                      <do_if value="(not $buyOfferAvailable) or (not $buyOfferOwnerValid)">
                        <set_value name="$universallyDead" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_if value="(not $sellOfferAvailable) or (not $sellOfferOwnerValid)">
                      <!-- Build Storage delivery: .available may stay false while cargo deficit exists. -->
                      <do_if value="not $sellOfferOwnerValid or not ($sellOfferAmount? and $sellOfferAmount gt 0)">
                        <set_value name="$universallyDead" exact="true"/>
                      </do_if>
                    </do_if>
                    
                    <do_if value="$universallyDead">
                      <!-- Scenario 1: Offer genuinely dead â€” purge from cache -->
                      <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                        $Ship = this.ship,
                        $BuyOffer = @$currentTrade.$BuyOffer,
                        $SellOffer = @$currentTrade.$SellOffer,
                        $HomeSector = $searchHomeSector,
                        $CachePool = 'mk4',
                        $Reason = 'offer_dead'
                      ]"/>
                    </do_if>
                    <do_else>
                      <!-- Scenario 2: Transient saturation / per-ship amount â€” flag so next cache read tries another entry. -->
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[
                        $Ship = this.ship,
                        $BuyOffer = @$currentTrade.$BuyOffer,
                        $SellOffer = @$currentTrade.$SellOffer,
                        $HomeSector = $searchHomeSector,
                        $CachePool = 'mk4',
                        $Reason = 'offer_invalid'
                      ]"/>
                    </do_else>
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- HYBRID APPROACH: Use clamp_trade_amount for final amount validation BEFORE breaking -->
                <!-- This handles cargo space, money, and offer availability automatically -->
                <!-- If clamping results in 0, continue to next trade instead of breaking -->
                <set_value name="$finalBuyAmount" exact="$currentTrade.$Amount"/>
                <set_value name="$finalSellAmount" exact="$currentTrade.$Amount"/>
                <set_value name="$buyClampReason" exact="null"/>
                <set_value name="$sellClampReason" exact="null"/>
                <set_value name="$clampFailed" exact="false"/>
                <set_value name="$buyClampSeller" exact="null"/>
                <set_value name="$sellClampBuyer" exact="null"/>
                
                <!-- PROFIT DEBUG: Log original amount before clamping -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                  <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') AMOUNT CLAMPING START:' + 
                    '\n  Ware: ' + $wareName +
                    '\n  Original Amount (from trade object): ' + $currentTrade.$Amount + ' units' +
                    '\n  Trade Profit (RAW): ' + (if $currentTrade.$Profit? then $currentTrade.$Profit else 'NULL') + ' = ' + (if $currentTrade.$Profit? then ($currentTrade.$Profit/100) + ' Cr' else 'NULL') +
                    '\n  Trade BuyPrice (RAW): ' + (if $currentTrade.$BuyPrice? then $currentTrade.$BuyPrice else 'NULL') + ' = ' + (if $currentTrade.$BuyPrice? then ($currentTrade.$BuyPrice/100) + ' Cr' else 'NULL') +
                    '\n  Trade SellPrice (RAW): ' + (if $currentTrade.$SellPrice? then $currentTrade.$SellPrice else 'NULL') + ' = ' + (if $currentTrade.$SellPrice? then ($currentTrade.$SellPrice/100) + ' Cr' else 'NULL')" chance="100"/>
                </do_if>
                
                <!-- Clamp buy order amount (for non-sell-only trades) -->
                <do_if value="not $isSellOnlyTrade and $currentTrade.$BuyOffer?">
                  <set_value name="$buyClampSeller" exact="null"/>
                  <do_if value="$currentTrade.$BuyOffer.seller?">
                    <set_value name="$buyClampSeller" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_if value="$buyClampSeller == null and $currentTrade.$BuyOffer.owner?">
                    <set_value name="$buyClampSeller" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_if>
                  <do_if value="$buyClampSeller != null">
                    <clamp_trade_amount 
                      trade="$currentTrade.$BuyOffer" 
                      amount="$finalBuyAmount" 
                      buyer="this.ship" 
                      seller="$buyClampSeller" 
                      result="$finalBuyAmount"
                      reason="$buyClampReason"/>
                  </do_if>
                  <do_else>
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <set_value name="$buyClampReason" exact="'seller_missing'"/>
                  </do_else>
                  <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$buyOfferAmountAfterClamp" exact="@$currentTrade.$BuyOffer.offeramount.{this.ship}"/>
                    <set_value name="$buyDesiredAfterClamp" exact="@$currentTrade.$BuyOffer.desiredamount"/>
                    <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': post-clamp BUY' +
                      '\n  original=' + $currentTrade.$Amount +
                      '\n  clamped=' + $finalBuyAmount +
                      '\n  buy offeramount(ship)=' + (if $buyOfferAmountAfterClamp? then $buyOfferAmountAfterClamp else 'null') +
                      '\n  buy desiredamount=' + (if $buyDesiredAfterClamp? then $buyDesiredAfterClamp else 'null') +
                      '\n  clampReason=' + (if $buyClampReason? then $buyClampReason else 'null')"
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="not $finalBuyAmount? or $finalBuyAmount == 0 or $finalBuyAmount lt 0">
                    <!-- Amount clamped to 0 or invalid - try next trade -->
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$clampReasonText" exact="if $buyClampReason? then $buyClampReason else 'unknown'"/>
                      <set_value name="$amountStatus" exact="if not $finalBuyAmount? then 'null' else if $finalBuyAmount lt 0 then 'negative (' + $finalBuyAmount + ')' else 'zero'"/>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' buy amount clamped to invalid value:' +
                        '\n  Original amount: ' + $currentTrade.$Amount +
                        '\n  Clamped amount: ' + $amountStatus +
                        '\n  Clamp reason: ' + $clampReasonText +
                        '\n  Reason: ' + (if $buyClampReason == 'buyer_cargo' then 'Insufficient cargo space' else if $buyClampReason == 'buyer_money' then 'Insufficient funds' else if $buyClampReason == 'seller_cargo' then 'Seller has insufficient stock' else 'Offer constraints') +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <do_if value="not $clampFailed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $finalBuyAmount != $currentTrade.$Amount">
                    <set_value name="$clampReasonText" exact="if $buyClampReason? then $buyClampReason else 'unknown'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' buy amount adjusted:' +
                      '\n  Original: ' + $currentTrade.$Amount +
                      '\n  Clamped: ' + $finalBuyAmount +
                      '\n  Reason: ' + $clampReasonText"
                      chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- Clamp sell order amount -->
                <do_if value="not $clampFailed and $currentTrade.$SellOffer?">
                  <set_value name="$sellClampBuyer" exact="null"/>
                  <do_if value="$currentTrade.$SellOffer.buyer?">
                    <set_value name="$sellClampBuyer" exact="@$currentTrade.$SellOffer.buyer"/>
                  </do_if>
                  <do_if value="$sellClampBuyer == null and $currentTrade.$SellOffer.owner?">
                    <set_value name="$sellClampBuyer" exact="@$currentTrade.$SellOffer.owner"/>
                  </do_if>
                  <do_if value="$sellClampBuyer == null">
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <set_value name="$sellClampReason" exact="'buyer_missing'"/>
                  </do_if>
                  
                  <do_if value="$isSellOnlyTrade">
                    <!-- Sell-only trade: Ship already has cargo, validate against ship cargo -->
                    <do_if value="not $clampFailed">
                      <clamp_trade_amount 
                        trade="$currentTrade.$SellOffer" 
                        amount="$finalSellAmount" 
                        buyer="$sellClampBuyer" 
                        seller="this.ship" 
                        result="$finalSellAmount"
                        reason="$sellClampReason"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Normal trade: Ship doesn't have cargo yet (will buy first), don't check seller cargo -->
                    <!-- Match vanilla pattern: clamp without seller parameter (only checks buyer constraints) -->
                    <!-- Vanilla comment: "it is possible that this doesn't have the wares yet if they still need to be bought" -->
                    <do_if value="not $clampFailed">
                      <clamp_trade_amount 
                        trade="$currentTrade.$SellOffer" 
                        amount="$finalSellAmount" 
                        buyer="$sellClampBuyer" 
                        result="$finalSellAmount"
                        reason="$sellClampReason"/>
                    </do_if>
                  </do_else>
                  
                  <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$sellOfferAmountAfterClamp" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <set_value name="$sellDesiredAfterClamp" exact="@$currentTrade.$SellOffer.desiredamount"/>
                    <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': post-clamp SELL' +
                      '\n  original=' + $currentTrade.$Amount +
                      '\n  clamped=' + $finalSellAmount +
                      '\n  sell offeramount(ship)=' + (if $sellOfferAmountAfterClamp? then $sellOfferAmountAfterClamp else 'null') +
                      '\n  sell desiredamount=' + (if $sellDesiredAfterClamp? then $sellDesiredAfterClamp else 'null') +
                      '\n  clampReason=' + (if $sellClampReason? then $sellClampReason else 'null')"
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="not $finalSellAmount? or $finalSellAmount == 0 or $finalSellAmount lt 0">
                    <!-- Amount clamped to 0 or invalid - try next trade -->
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$clampReasonText" exact="if $sellClampReason? then $sellClampReason else 'unknown'"/>
                      <set_value name="$amountStatus" exact="if not $finalSellAmount? then 'null' else if $finalSellAmount lt 0 then 'negative (' + $finalSellAmount + ')' else 'zero'"/>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' sell amount clamped to invalid value:' +
                        '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                        '\n  Original amount: ' + $currentTrade.$Amount +
                        '\n  Clamped amount: ' + $amountStatus +
                        '\n  Clamp reason: ' + $clampReasonText +
                        '\n  Reason: ' + (if $sellClampReason == 'buyer_cargo' then 'Buyer has insufficient cargo space' else if $sellClampReason == 'buyer_money' then 'Buyer has insufficient funds' else if $sellClampReason == 'seller_cargo' then 'Ship has insufficient cargo' else 'Offer constraints') +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <do_if value="not $clampFailed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $finalSellAmount != $currentTrade.$Amount">
                    <set_value name="$clampReasonText" exact="if $sellClampReason? then $sellClampReason else 'unknown'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' sell amount adjusted:' +
                      '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                      '\n  Original: ' + $currentTrade.$Amount +
                      '\n  Clamped: ' + $finalSellAmount +
                      '\n  Reason: ' + $clampReasonText"
                      chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- If clamping failed, continue to next trade -->
                <do_if value="$clampFailed">
                  <continue/>
                </do_if>

                <!-- CRITICAL: For NORMAL trades, BUY and SELL amounts must match.
                     clamp_trade_amount can clamp BUY (ship cargo/money) and SELL (buyer constraints) independently.
                     Final executed amount must be the minimum of both. -->
                <do_if value="not $isSellOnlyTrade">
                  <set_value name="$finalAmount" exact="[$finalBuyAmount, $finalSellAmount].min"/>
                  
                  <!-- PROFIT DEBUG: Log amount syncing details -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') AMOUNT SYNCING:' + 
                      '\n  Ware: ' + $wareName +
                      '\n  Original Amount: ' + $currentTrade.$Amount + ' units' +
                      '\n  Clamped Buy Amount: ' + $finalBuyAmount + ' units' +
                      '\n  Clamped Sell Amount: ' + $finalSellAmount + ' units' +
                      '\n  Final Amount (min): ' + $finalAmount + ' units' +
                      '\n  Amount changed: ' + (if $finalAmount != $currentTrade.$Amount then 'YES (was ' + $currentTrade.$Amount + ', now ' + $finalAmount + ')' else 'NO') +
                      '\n  Trade Profit (unchanged): ' + (if $currentTrade.$Profit? then ($currentTrade.$Profit/100) + ' Cr' else 'NULL')" chance="100"/>
                  </do_if>
                  
                  <set_value name="$finalBuyAmount" exact="$finalAmount"/>
                  <set_value name="$finalSellAmount" exact="$finalAmount"/>
                </do_if>

                <!-- HARD FILTER: Minimum cargo utilization threshold (live/cache/fallback only; excluded in isolated mode) -->
                <set_value name="$isIsolatedForCargoFilter" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
                <set_value name="$applyMinCargoUtilFilter" exact="(if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)) and not $isSellOnlyTrade and not $isIsolatedForCargoFilter and ($searchMethod == 'live' or $searchMethod == 'cache' or $searchMethod == 'live_fallback')"/>
                <do_if value="$applyMinCargoUtilFilter">
                  <set_value name="$cargoUtilThresholdPct" exact="[10,[$gt_cargotarget,100].min].max"/>
                  <set_value name="$utilWare" exact="null"/>
                  <do_if value="$currentTrade.$Ware?">
                    <set_value name="$utilWare" exact="$currentTrade.$Ware"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware?">
                    <set_value name="$utilWare" exact="@$currentTrade.$BuyOffer.ware"/>
                  </do_elseif>
                  <do_elseif value="$currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware?">
                    <set_value name="$utilWare" exact="@$currentTrade.$SellOffer.ware"/>
                  </do_elseif>

                  <set_value name="$utilVolumePerUnit" exact="1"/>
                  <do_if value="$utilWare?">
                    <do_if value="$utilWare.volume?">
                      <set_value name="$utilVolumePerUnit" exact="$utilWare.volume"/>
                    </do_if>
                  </do_if>

                  <set_value name="$shipCargoCapacityVol" exact="this.ship.cargo.capacity.all"/>
                  <set_value name="$tradeCargoVolume" exact="$finalBuyAmount * $utilVolumePerUnit"/>
                  <set_value name="$requiredCargoVolume" exact="($shipCargoCapacityVol * $cargoUtilThresholdPct) / 100.0"/>
                  <set_value name="$cargoUtilizationPct" exact="if $shipCargoCapacityVol gt 0 then ($tradeCargoVolume * 100.0) / $shipCargoCapacityVol else 0"/>

                  <!-- Bypass cargo utilization for priority wares: player explicitly wants these even if low volume -->
                  <set_value name="$isPriorityWareForCargo" exact="false"/>
                  <do_if value="$pwForReorder? and $pwForReorder.count gt 0 and $utilWare?">
                    <do_all exact="$pwForReorder.count" counter="$pwc">
                      <set_value name="$pwcItem" exact="$pwForReorder.{$pwc}"/>
                      <do_if value="$pwcItem == $utilWare or ($pwcItem? and $pwcItem.id? and $utilWare.id? and $pwcItem.id == $utilWare.id)">
                        <set_value name="$isPriorityWareForCargo" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>

                  <do_if value="$tradeCargoVolume lt $requiredCargoVolume and not $isPriorityWareForCargo">
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by minimum cargo utilization filter:' +
                        '\n  Threshold: ' + $cargoUtilThresholdPct + '%' +
                        '\n  Actual: ' + $cargoUtilizationPct + '%' +
                        '\n  Amount: ' + $finalBuyAmount +
                        '\n  Volume/unit: ' + $utilVolumePerUnit +
                        '\n  Trade volume: ' + $tradeCargoVolume + ' / Capacity: ' + $shipCargoCapacityVol +
                        '\n  Search method: ' + $searchMethod +
                        '\n  Isolated mode: ' + $isIsolatedForCargoFilter +
                        '\n  â†’ Trying next trade in list...'" chance="100"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
                
                <!-- CRITICAL FIX: Always recalculate profit using live offer prices and final amount -->
                <!-- Cache is only a hint - market prices change constantly, so we must always validate -->
                <set_value name="$buyPriceForRecalc" exact="null"/>
                <set_value name="$sellPriceForRecalc" exact="null"/>
                
                <!-- Use actual offer prices only (no stored-price fallback). -->
                <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.unitprice?">
                  <set_value name="$buyPriceForRecalc" exact="$currentTrade.$BuyOffer.unitprice"/>
                </do_if>
                
                <do_if value="$currentTrade.$SellOffer? and $currentTrade.$SellOffer.unitprice?">
                  <set_value name="$sellPriceForRecalc" exact="$currentTrade.$SellOffer.unitprice"/>
                </do_if>
                
                <!-- ALWAYS recalculate profit when prices are available (regardless of amount change) -->
                <!-- This ensures cached trades with wrong profit are caught and validated -->
                <set_value name="$amountChanged" exact="if $isSellOnlyTrade then ($finalSellAmount != $currentTrade.$Amount) else ($finalBuyAmount != $currentTrade.$Amount)"/>
                <set_value name="$finalProfitRAW" exact="null"/>
                <set_value name="$profitRecalculated" exact="false"/>
                
                <do_if value="$currentTrade.$Amount? and $buyPriceForRecalc? and $sellPriceForRecalc?">
                  <!-- Store original values before recalculation -->
                  <set_value name="$originalAmount" exact="$currentTrade.$Amount"/>
                  <set_value name="$originalProfitRAW" exact="if $currentTrade.$Profit? then $currentTrade.$Profit else 0"/>
                  
                  <!-- Calculate final amount for profit calculation -->
                  <set_value name="$finalAmountForProfit" exact="if $isSellOnlyTrade then $finalSellAmount else $finalBuyAmount"/>
                  
                  <!-- ALWAYS recalculate profit: (sellPrice - buyPrice) * finalAmount -->
                  <!-- This validates against current market prices, not cached values -->
                  <set_value name="$recalculatedProfitRAW" exact="($sellPriceForRecalc - $buyPriceForRecalc) * $finalAmountForProfit"/>
                  <set_value name="$finalProfitRAW" exact="$recalculatedProfitRAW"/>
                  <set_value name="$profitRecalculated" exact="true"/>
                  
                  <!-- Update trade object profit (for logbook display) -->
                  <set_value name="$currentTrade.$Profit" exact="$recalculatedProfitRAW"/>
                  
                  <!-- Also update prices in trade object if they were missing (for future use) -->
                  <do_if value="not $currentTrade.$BuyPrice?">
                    <set_value name="$currentTrade.$BuyPrice" exact="$buyPriceForRecalc"/>
                  </do_if>
                  <do_if value="not $currentTrade.$SellPrice?">
                    <set_value name="$currentTrade.$SellPrice" exact="$sellPriceForRecalc"/>
                  </do_if>
                  
                  <!-- PROFIT DEBUG: Log profit recalculation -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <set_value name="$priceSource" exact="if $currentTrade.$BuyPrice? then 'trade_object' else 'extracted_from_offers'"/>
                    <set_value name="$amountStatus" exact="if $amountChanged then 'YES (was ' + $originalAmount + ', now ' + $finalAmountForProfit + ')' else 'NO (unchanged: ' + $finalAmountForProfit + ')'"/>
                    <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') PROFIT RECALCULATION (ALWAYS):' + 
                      '\n  Ware: ' + $wareName +
                      '\n  Price Source: ' + $priceSource +
                      '\n  Amount Changed: ' + $amountStatus +
                      '\n  Original Amount: ' + $originalAmount + ' units' +
                      '\n  Final Amount: ' + $finalAmountForProfit + ' units' +
                      '\n  Original Profit (cached): ' + ($originalProfitRAW/100) + ' Cr (RAW: ' + $originalProfitRAW + ')' +
                      '\n  Recalculated Profit (validated): ' + ($recalculatedProfitRAW/100) + ' Cr (RAW: ' + $recalculatedProfitRAW + ')' +
                      '\n  Buy Price: ' + ($buyPriceForRecalc/100) + ' Cr (RAW: ' + $buyPriceForRecalc + ')' +
                      '\n  Sell Price: ' + ($sellPriceForRecalc/100) + ' Cr (RAW: ' + $sellPriceForRecalc + ')' +
                      '\n  Verification: (' + ($sellPriceForRecalc/100) + ' - ' + ($buyPriceForRecalc/100) + ') * ' + $finalAmountForProfit + ' = ' + (($sellPriceForRecalc - $buyPriceForRecalc) * $finalAmountForProfit / 100) + ' Cr'" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Prices missing - cannot recalculate profit, reject trade -->
                  <set_value name="$tradesRejectedProfit" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' REJECTED: Cannot validate profit' +
                      '\n  Ware: ' + $wareName +
                      '\n  Reason: Prices missing from trade object and offers, cannot recalculate/validate profit' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  <continue/>
                </do_else>
                
                <!-- MK4 supply price-cap validation:
                     reject only when supplier price exceeds customer buy price (negative final profit).
                     Zero-profit trades are valid for supply fulfillment. -->
                <do_if value="not $finalProfitRAW? or $finalProfitRAW lt 0">
                  <set_value name="$tradesRejectedProfit" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <set_value name="$profitStatus" exact="if not $finalProfitRAW? then 'NULL' else 'NEGATIVE (' + ($finalProfitRAW/100) + ' Cr)'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' REJECTED: Profit validation failed' +
                      '\n  Ware: ' + $wareName +
                      '\n  Final Profit (recalculated): ' + $profitStatus +
                      '\n  Reason: MK4 price-cap exceeded (supplier price greater than customer buy price)' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  <continue/>
                </do_if>
                
                <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=trade -->
                <set_value name="$finalDockingCheck" exact="true"/>
                
                <!-- Check buy station docking (for non-sell-only trades) -->
                <do_if value="not $isSellOnlyTrade and $finalDockingCheck and $buyStation?">
                  <run_script name="'lib.gt.dockcheck'" result="$mk4FinalBuyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$buyStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <do_if value="not $mk4FinalBuyDockResult.$CanDock">
                    <set_value name="$finalDockingCheck" exact="false"/>
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' Final docking check FAILED (buy station): ' + @$buyStation.knownname + 
                        '\n  Sector: ' + @$buyStation.sector.knownname + 
                        '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- Check sell station docking -->
                <do_if value="$finalDockingCheck and $sellStation?">
                  <run_script name="'lib.gt.dockcheck'" result="$mk4FinalSellDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <do_if value="not $mk4FinalSellDockResult.$CanDock">
                    <set_value name="$finalDockingCheck" exact="false"/>
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' Final docking check FAILED (sell station): ' + @$sellStation.knownname + 
                        '\n  Sector: ' + @$sellStation.sector.knownname + 
                        '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- If final docking check failed, continue to next trade -->
                <do_if value="not $finalDockingCheck">
                  <continue/>
                </do_if>
                
                <!-- Buildstorage enforcement (inside loop so rejected trades try next) -->
                <do_if value="$enfIgnoreBuildStorage">
                  <set_value name="$_buyIsBuildStorage" exact="false"/>
                  <do_if value="$buyStation?">
                    <set_value name="$_buyIsBuildStorage" exact="$buyStation.isclass.buildstorage"/>
                  </do_if>
                  <set_value name="$_sellIsBuildStorage" exact="false"/>
                  <do_if value="$sellStation?">
                    <set_value name="$_sellIsBuildStorage" exact="$sellStation.isclass.buildstorage"/>
                  </do_if>
                  <do_if value="$_buyIsBuildStorage or $_sellIsBuildStorage">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by buildstorage restriction (buy=' + $_buyIsBuildStorage + ', sell=' + $_sellIsBuildStorage + ') â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'buildstorage_blocked']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
                
                <!-- Carrier/Aux enforcement (inside loop so rejected trades try next) -->
                <!-- Vanilla pattern: carriers = type==shiptype.carrier, aux = primarypurpose==purpose.auxiliary -->
                <!-- Do NOT use purpose.fight â€” that catches wharfs/shipyards (they build combat ships) -->
                <do_if value="$enfIgnoreCarrierAux">
                  <set_value name="$_rejectCarrierAux" exact="false"/>
                  <do_if value="$buyStation?">
                    <do_if value="@$buyStation.type == shiptype.carrier or @$buyStation.primarypurpose == purpose.auxiliary">
                      <set_value name="$_rejectCarrierAux" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_if value="not $_rejectCarrierAux and $sellStation?">
                    <do_if value="@$sellStation.type == shiptype.carrier or @$sellStation.primarypurpose == purpose.auxiliary">
                      <set_value name="$_rejectCarrierAux" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_if value="$_rejectCarrierAux">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by carrier/aux restriction â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'carrier_aux_blocked']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- MK3 faction blacklist enforcement in validation loop:
                     blocked entries must be skipped here (not only at final gate), otherwise
                     trade 1 can abort the whole cycle without trying trade 2..N. -->
                <do_if value="$mk3FactionBlacklistLoop.keys.count gt 0">
                  <set_value name="$_mk3BlockedTrade" exact="false"/>
                  <set_value name="$_mk3BlockedSide" exact="''"/>
                  <set_value name="$_mk3BlockedFaction" exact="null"/>

                  <do_if value="not $isSellOnlyTrade and $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.owner?">
                    <set_value name="$_mk3BuyOwnerContainer" exact="@$currentTrade.$BuyOffer.owner"/>
                    <do_if value="$_mk3BuyOwnerContainer.owner?">
                      <set_value name="$_mk3BuyFaction" exact="$_mk3BuyOwnerContainer.owner"/>
                    </do_if>
                    <do_else>
                      <set_value name="$_mk3BuyFaction" exact="$_mk3BuyOwnerContainer"/>
                    </do_else>
                    <do_if value="$_mk3BuyFaction? and $mk3FactionBlacklistLoop.{$_mk3BuyFaction}?">
                      <set_value name="$_mk3BlockedTrade" exact="true"/>
                      <set_value name="$_mk3BlockedSide" exact="'buy'"/>
                      <set_value name="$_mk3BlockedFaction" exact="$_mk3BuyFaction"/>
                    </do_if>
                  </do_if>

                  <do_if value="not $_mk3BlockedTrade and $currentTrade.$SellOffer? and $currentTrade.$SellOffer.owner?">
                    <set_value name="$_mk3SellOwnerContainer" exact="@$currentTrade.$SellOffer.owner"/>
                    <do_if value="$_mk3SellOwnerContainer.owner?">
                      <set_value name="$_mk3SellFaction" exact="$_mk3SellOwnerContainer.owner"/>
                    </do_if>
                    <do_else>
                      <set_value name="$_mk3SellFaction" exact="$_mk3SellOwnerContainer"/>
                    </do_else>
                    <do_if value="$_mk3SellFaction? and $mk3FactionBlacklistLoop.{$_mk3SellFaction}?">
                      <set_value name="$_mk3BlockedTrade" exact="true"/>
                      <set_value name="$_mk3BlockedSide" exact="'sell'"/>
                      <set_value name="$_mk3BlockedFaction" exact="$_mk3SellFaction"/>
                    </do_if>
                  </do_if>

                  <do_if value="$_mk3BlockedTrade">
                    <set_value name="$tradesBlacklisted" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by MK3 faction blacklist (' + $_mk3BlockedSide + ' faction): ' + (if $_mk3BlockedFaction? then $_mk3BlockedFaction.name else 'Unknown') + ' â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'mk3_faction_blacklist']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- Trade-rule enforcement: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
                <do_if value="not (if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false) and not $isSellOnlyTrade">
                  <set_value name="$_applyTradeRules" exact="false"/>
                  <do_if value="$buyStation? and @$buyStation.exists">
                    <do_if value="@$buyStation.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_if>
                    <do_elseif value="@$buyStation.isclass.buildstorage and $buyStation.base? and @$buyStation.base.exists and @$buyStation.base.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $_applyTradeRules and $sellStation? and @$sellStation.exists">
                    <do_if value="@$sellStation.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_if>
                    <do_elseif value="@$sellStation.isclass.buildstorage and $sellStation.base? and @$sellStation.base.exists and @$sellStation.base.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="$_applyTradeRules">
                    <set_value name="$_tradeRuleBlocked" exact="false"/>
                    <set_value name="$_tradeRuleReason" exact="''"/>
                    <do_if value="$currentTrade.$SellOffer? and $buyStation? and $buyStation.exists and not $currentTrade.$SellOffer.cantradewith.{$buyStation}">
                      <set_value name="$_tradeRuleBlocked" exact="true"/>
                      <set_value name="$_tradeRuleReason" exact="'customer ' + @$sellStation.knownname + ' disallows source ' + @$buyStation.knownname"/>
                    </do_if>
                    <do_if value="not $_tradeRuleBlocked and $currentTrade.$BuyOffer? and $sellStation? and $sellStation.exists and not $currentTrade.$BuyOffer.cantradewith.{$sellStation}">
                      <set_value name="$_tradeRuleBlocked" exact="true"/>
                      <set_value name="$_tradeRuleReason" exact="'source ' + @$buyStation.knownname + ' disallows delivery to ' + @$sellStation.knownname"/>
                    </do_if>
                    <do_if value="$_tradeRuleBlocked">
                      <set_value name="$tradesRejectedRestriction" operation="add"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by trade rules (' + $_tradeRuleReason + ') â†’ Trying next trade...'" chance="100"/>
                      </do_if>
                      <do_if value="$searchMethod == 'cache'">
                        <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'trade_rules_failed']"/>
                      </do_if>
                      <continue/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- All checks passed including clamping and final docking verification - this trade is valid -->
                <set_value name="$validTradesFound" operation="add"/>
                <!-- Persist clamped amounts on candidate so fallback retries can reuse validated values. -->
                <set_value name="$currentTrade.$FinalBuyAmount" exact="$finalBuyAmount"/>
                <set_value name="$currentTrade.$FinalSellAmount" exact="$finalSellAmount"/>
                <!-- Keep a bounded, prevalidated candidate window (MK4 maxTrades) for immediate same-cycle retries. -->
                <do_if value="$validatedTradeCandidates.count lt $validatedCandidateLimit">
                  <set_value name="$mk4PairAlreadyInWindow" exact="false"/>
                  <do_all exact="$validatedTradeCandidates.count" counter="$vdci">
                    <set_value name="$vdc" exact="$validatedTradeCandidates.{$vdci}"/>
                    <set_value name="$mk4VdcPairMatch" exact="false"/>
                    <do_if value="$vdc.$SellOffer == $currentTrade.$SellOffer">
                      <do_if value="$isSellOnlyTrade and $vdc.$IsSellOnly? and $vdc.$IsSellOnly">
                        <set_value name="$mk4VdcPairMatch" exact="true"/>
                      </do_if>
                      <do_elseif value="$vdc.$BuyOffer? and $currentTrade.$BuyOffer? and $vdc.$BuyOffer == $currentTrade.$BuyOffer">
                        <set_value name="$mk4VdcPairMatch" exact="true"/>
                      </do_elseif>
                    </do_if>
                    <do_if value="$mk4VdcPairMatch">
                      <set_value name="$mk4PairAlreadyInWindow" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                  <do_if value="not $mk4PairAlreadyInWindow">
                    <append_to_list name="$validatedTradeCandidates" exact="$currentTrade"/>
                  </do_if>
                </do_if>

                <!-- Keep selection stable: first valid candidate in ordered list stays primary.
                     We still finish the full sweep for diagnostics and fallback candidate capture. -->
                <do_if value="not $validTradeFound">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' is VALID - selected as primary candidate'" chance="100"/>
                  </do_if>
                  <set_value name="$validTradeFound" exact="true"/>
                  <set_value name="$pendingTrade" exact="$currentTrade"/>
                  <set_value name="$selectedTradeIdx" exact="if $tradeIdxSafe? then $tradeIdxSafe else 0"/>
                  <set_value name="$selectedCurrentSectorIsBlacklisted" exact="$currentSectorIsBlacklisted"/>

                  <!-- Create fleet reservation (restored from pre-migration gt_trading_search.xml).
                       Prevents other ships from selecting this trade during the search-to-execution gap.
                       TTL=10s matches original release version. Cleared after create_trade_order (native takes over). -->
                  <do_if value="global.$GT_Reservations? and $currentTrade.$SellOffer?">
                    <set_value name="global.$GT_Reservations.{$currentTrade.$SellOffer}" exact="table[
                      $Ship = this.ship,
                      $Until = player.age + 10s,
                      $Amount = if $finalSellAmount? and $finalSellAmount gt 0 then $finalSellAmount else (if $pendingTrade.$Amount? and $pendingTrade.$Amount gt 0 then $pendingTrade.$Amount else 1)
                    ]"/>
                    <!-- Store reservation key on instance for cleanup in on_abort -->
                    <set_value name="this.$activeReservationKey" exact="$currentTrade.$SellOffer"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet reservation CREATED (TTL=10s, key=SellOffer)'" chance="100"/>
                    </do_if>
                    <!-- Update reservation stats -->
                    <do_if value="global.$GT_ReservationStats?">
                      <set_value name="global.$GT_ReservationStats.$Active" operation="add"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' is VALID - kept as fallback candidate (primary already selected)'" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
              <do_else>
                <!-- Ware couldn't be extracted - skip this trade -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' SKIPPED: Could not extract ware from trade data'" chance="100"/>
                </do_if>
                <continue/>
              </do_else>
            </do_if>
          
          <!-- Skip trade if currentTrade is null -->
          <do_else>
            <!-- Don't access $tradeIdx here - it might not exist if loop didn't execute -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade SKIPPED: Trade data is null'" chance="100"/>
            </do_if>
            <!-- Only use continue if we're actually in the loop -->
            <do_if value="$tradeIdx?">
              <continue/>
            </do_if>
          </do_else>
          </do_all>
        </do_if>
        <do_else>
          <!-- Trade list is empty or null - no trades to validate -->
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade list is empty or null - no trades to validate'" chance="100"/>
          <set_value name="$validTradeFound" exact="false"/>
        </do_else>
        
        <!-- After loop: Check if we found a valid trade -->
        <!-- Use safe access and check existence before accessing -->
        <do_if value="$validTradeFound? and $validTradeFound">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validation PASSED - creating trade orders (checked ' + $tradesChecked + ' trades, valid=' + $validTradesFound + ', fallbackWindow=' + $validatedTradeCandidates.count + '/' + $validatedCandidateLimit + ', ' + $tradesRejectedPath + ' unreachable, ' + $tradesRejectedDocking + ' docking denied, ' + $tradesRejectedDistance + ' distance exceeded, ' + $tradesRejectedCargo + ' insufficient cargo, ' + $tradesBlacklisted + ' blacklisted, ' + $tradesRejectedRestriction + ' restriction blocked)'" chance="100"/>
          </do_if>
          
          <!-- Update pending trade entry with ACTUAL trade being executed -->
          <!-- Failure handler expects table with $BuyStation, $SellStation, $Ware -->
          <!-- Replace trade list with specific trade data for failure tracking -->
          <!-- Handle sell-only trades (BuyOffer may be null) -->
          <!-- Extract values from pendingTrade since loop variables may be out of scope -->
          <set_value name="$isSellOnlyTradeForPending" exact="false"/>
          <do_if value="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly">
            <set_value name="$isSellOnlyTradeForPending" exact="true"/>
          </do_if>
          
          <!-- Extract stations from pendingTrade (may have been set in loop, but extract to be safe) -->
          <set_value name="$buyStationForPending" exact="null"/>
          <set_value name="$sellStationForPending" exact="null"/>
          <do_if value="$pendingTrade.$BuyStation?">
            <set_value name="$buyStationForPending" exact="$pendingTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$pendingTrade.$BuyOffer?">
            <set_value name="$buyStationForPending" exact="@$pendingTrade.$BuyOffer.owner"/>
          </do_elseif>
          <do_else>
            <!-- Use loop variable if available, otherwise null (for sell-only trades) -->
            <set_value name="$buyStationForPending" exact="$buyStation"/>
          </do_else>
          
          <do_if value="$pendingTrade.$SellStation?">
            <set_value name="$sellStationForPending" exact="$pendingTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$pendingTrade.$SellOffer?">
            <set_value name="$sellStationForPending" exact="@$pendingTrade.$SellOffer.owner"/>
          </do_elseif>
          <do_else>
            <!-- Use loop variable if available -->
            <set_value name="$sellStationForPending" exact="$sellStation"/>
          </do_else>
          
          <set_value name="$wareForPendingTrade" exact="null"/>
          <do_if value="$isSellOnlyTradeForPending and $pendingTrade.$Ware?">
            <set_value name="$wareForPendingTrade" exact="$pendingTrade.$Ware"/>
          </do_if>
          <do_elseif value="$pendingTrade.$BuyOffer?">
            <set_value name="$wareForPendingTrade" exact="@$pendingTrade.$BuyOffer.ware"/>
          </do_elseif>
          <!-- With full-sweep validation, loop locals no longer necessarily point to
               the selected trade. Restore canonical context from selected snapshot. -->
          <set_value name="$buyStation" exact="$buyStationForPending"/>
          <set_value name="$sellStation" exact="$sellStationForPending"/>
          <set_value name="$currentSectorIsBlacklisted" exact="$selectedCurrentSectorIsBlacklisted"/>
          <set_value name="$buySector" exact="if $buyStationForPending? then $buyStationForPending.sector else this.ship.sector"/>
          <set_value name="$sellSector" exact="if $sellStationForPending? then $sellStationForPending.sector else this.ship.sector"/>
          
          <!-- Store the ACTIVE trade for failure tracking (do NOT overwrite the pending-results list). -->
          <do_if value="not global.$GT_ActiveTrade?">
            <set_value name="global.$GT_ActiveTrade" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_ActiveTrade.{this.ship}" exact="table[
            $BuyStation = $buyStationForPending,
            $SellStation = $sellStationForPending,
            $Ware = $wareForPendingTrade
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTradeForPending then 'N/A (sell-only)' else (if $buyStationForPending? then @$buyStationForPending.knownname else 'Unknown')"/>
            <set_value name="$sellStationNameForDebug" exact="if $sellStationForPending? then @$sellStationForPending.knownname else 'Unknown'"/>
            <set_value name="$wareNameForDebug" exact="if $wareForPendingTrade? then @$wareForPendingTrade.name else 'Unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Updated pending trade entry for failure tracking:' +
              '\n  Buy: ' + $buyStationNameForDebug +
              '\n  Sell: ' + $sellStationNameForDebug +
              '\n  Ware: ' + $wareNameForDebug"
              chance="100"/>
          </do_if>
          
          <!-- Final offer validity check and clamping moved inside loop -->
          <!-- Offers are validated and clamped before breaking out of the loop -->
          <!-- Final docking verification also moved inside loop - allows trying next trade if docking fails -->
          <!-- All checks passed including final docking verification (checked in loop) - safe to create orders with clamped amounts -->
          <!-- Clamped amounts are stored in $pendingTrade.$FinalBuyAmount and $pendingTrade.$FinalSellAmount -->
          <!-- Create X4 native TradePerform orders with blacklist routing -->
          <!-- CRITICAL: internal="true" is REQUIRED for vanilla to track pending trades and display count -->
          <!-- Without internal="true", vanilla won't set $internalorder in TradePerform, and pending trades won't be displayed -->
          <!-- For sell-only trades, skip buy order (ship already has cargo) -->
          <set_value name="$finalBuyAmount" exact="if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount"/>
          <set_value name="$finalSellAmount" exact="if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount"/>
          
          <!-- Re-resolve MK3 faction blacklist at final stage (path-independent safety). -->
          <set_value name="$mk3BlacklistOwnerFinal" exact="this.ship"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$mk3BlacklistOwnerFinal" exact="this.ship.commander"/>
          </do_if>
          <set_value name="$mk3FactionBlacklistFinal" exact="table[]"/>
          <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerFinal}?">
            <set_value name="$mk3FactionBlacklistFinal" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerFinal}"/>
          </do_if>
          
          <!-- CRITICAL FIX: Final validation immediately before order creation -->
          <!-- This catches cases where trade rules changed between earlier validation and order creation -->
          <!-- Re-check offers with tradepartner to ensure trade rules are still respected -->
          <set_value name="$finalBuyOfferValid" exact="true"/>
          <set_value name="$finalSellOfferValid" exact="true"/>
          <set_value name="$finalMK3BlacklistValid" exact="true"/>
          <set_value name="$finalRouteIllegalValid" exact="true"/>
          
          <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer?">
            <set_value name="$finalBuyStation" exact="if $pendingTrade.$BuyStation? then $pendingTrade.$BuyStation else (if $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner else null)"/>
            <set_value name="$finalBuyWare" exact="if $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else null"/>
            
            <do_if value="$finalBuyStation? and $finalBuyStation.exists and $finalBuyWare != null">
              <find_sell_offer seller="$finalBuyStation" wares="$finalBuyWare" tradepartner="this.ship" result="$finalValidatedBuyOffer"/>
              <do_if value="not $finalValidatedBuyOffer.available">
                <set_value name="$finalBuyOfferValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - Buy offer invalid (trade rules?) - station: ' + @$finalBuyStation.knownname + ', ware: ' + @$finalBuyWare.name" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
          
          <do_if value="$pendingTrade.$SellOffer?">
            <set_value name="$finalSellStation" exact="if $pendingTrade.$SellStation? then $pendingTrade.$SellStation else (if $pendingTrade.$SellOffer.buyer? and @$pendingTrade.$SellOffer.buyer.exists then @$pendingTrade.$SellOffer.buyer else (if $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner else null))"/>
            <set_value name="$finalSellWare" exact="if $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else null"/>
            
            <do_if value="$finalSellStation? and $finalSellStation.exists and $finalSellWare != null">
              <find_buy_offer buyer="$finalSellStation" wares="$finalSellWare" tradepartner="this.ship" result="$finalValidatedSellOffer"/>
              <set_value name="$finalSellEffectiveAmount" exact="0"/>
              <do_if value="$finalValidatedSellOffer?">
                <set_value name="$pendingTrade.$SellOffer" exact="$finalValidatedSellOffer"/>
                <set_value name="$finalSellEffectiveAmount" exact="@$finalValidatedSellOffer.offeramount.{this.ship}"/>
                <do_if value="(not $finalSellEffectiveAmount? or $finalSellEffectiveAmount le 0) and @$finalValidatedSellOffer.amount gt 0">
                  <set_value name="$finalSellEffectiveAmount" exact="@$finalValidatedSellOffer.amount"/>
                </do_if>
              </do_if>
              <do_if value="not $finalSellEffectiveAmount? or $finalSellEffectiveAmount le 0">
                <set_value name="$finalSellDemandFallback" exact="[0, $finalSellStation.cargo.{$finalSellWare}.target - $finalSellStation.cargo.{$finalSellWare}.count].max"/>
                <do_if value="$finalSellDemandFallback gt 0">
                  <set_value name="$finalSellEffectiveAmount" exact="$finalSellDemandFallback"/>
                </do_if>
              </do_if>
              <do_if value="not $finalSellEffectiveAmount? or $finalSellEffectiveAmount le 0">
                <set_value name="$finalSellOfferValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - Sell offer invalid (trade rules?) - station: ' + @$finalSellStation.knownname + ', ware: ' + @$finalSellWare.name" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>

          <!-- NOTE: Trade-rule sourcing enforcement (customer/source cantradewith) now runs inside the
               main validation loop, so every violating cache trade is rejected+flagged in one pass and
               the "all cached trades rejected -> force live search" escalation fires. It is intentionally
               NOT repeated here to avoid the late-stage single-candidate retry loop. -->

          <!-- Final MK3 faction blacklist safety net (applies to all sources: cache/live/fallback). -->
          <do_if value="$mk3FactionBlacklistFinal.keys.count gt 0">
            <set_value name="$finalBuyFaction" exact="null"/>
            <set_value name="$finalSellFaction" exact="null"/>

            <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner?">
              <set_value name="$finalBuyOwnerContainer" exact="@$pendingTrade.$BuyOffer.owner"/>
              <do_if value="$finalBuyOwnerContainer.owner?">
                <set_value name="$finalBuyFaction" exact="$finalBuyOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$finalBuyFaction" exact="$finalBuyOwnerContainer"/>
              </do_else>
            </do_if>

            <do_if value="$pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner?">
              <set_value name="$finalSellOwnerContainer" exact="@$pendingTrade.$SellOffer.owner"/>
              <do_if value="$finalSellOwnerContainer.owner?">
                <set_value name="$finalSellFaction" exact="$finalSellOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$finalSellFaction" exact="$finalSellOwnerContainer"/>
              </do_else>
            </do_if>

            <do_if value="$finalBuyFaction? and $mk3FactionBlacklistFinal.{$finalBuyFaction}?">
              <set_value name="$finalMK3BlacklistValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL MK3 blacklist block (buy faction): ' + $finalBuyFaction.name" chance="100"/>
              </do_if>
            </do_if>
            <do_if value="$finalMK3BlacklistValid and $finalSellFaction? and $mk3FactionBlacklistFinal.{$finalSellFaction}?">
              <set_value name="$finalMK3BlacklistValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL MK3 blacklist block (sell faction): ' + $finalSellFaction.name" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Final illegal-route safety net (path can change between scoring and order creation). -->
          <set_value name="$finalRouteWare" exact="if $pendingTrade.$Ware? then $pendingTrade.$Ware else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else null))"/>
          <do_if value="$effectiveAllowIllegal and $effectiveEnforceRouteIllegalLegality and @$finalRouteWare.illegal gt 0">
            <set_value name="$finalRouteBuySector" exact="this.ship.sector"/>
            <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner?">
              <set_value name="$finalRouteBuySector" exact="@$pendingTrade.$BuyOffer.owner.sector"/>
            </do_if>
            <set_value name="$finalRouteSellSector" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.sector else null"/>
            <run_script name="'lib.gt.pathfinding'" result="$finalRouteLegality">
              <param name="mode" value="'route_legality'"/>
              <param name="ship" value="this.ship"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="allowIllegal" value="$effectiveAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$effectiveEnforceRouteIllegalLegality"/>
              <param name="startSector" value="this.ship.sector"/>
              <param name="buySector" value="$finalRouteBuySector"/>
              <param name="sellSector" value="$finalRouteSellSector"/>
              <param name="ware" value="$finalRouteWare"/>
            </run_script>
            <do_if value="not $finalRouteLegality.$IsLegal">
              <set_value name="$finalRouteIllegalValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL ILLEGAL ROUTE BLOCK: route changed or sector legality mismatch before order creation'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- If final validation failed, abort order creation -->
          <do_if value="not $finalBuyOfferValid or not $finalSellOfferValid or not $finalMK3BlacklistValid or not $finalRouteIllegalValid">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - safety check blocked trade immediately before order creation'" chance="100"/>
            </do_if>
            <!-- Scenario 3: Flag ship-specific failure â€” final validation uses tradepartner="this.ship",
                 so trade rules are ship-specific. Another ship may still pass. -->
            <do_if value="$searchMethod == 'cache'">
              <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$pendingTrade.$BuyOffer, $SellOffer = @$pendingTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk4', $Reason = 'trade_rules_failed']"/>
            </do_if>

            <!-- Do not abort the full cycle on late failure: remove failed candidate and retry remaining list. -->
            <set_value name="$remainingTrades" exact="[]"/>
            <!-- Prefer already validated fallback window (bounded by MK4 maxTrades).
                 If unavailable, fall back to raw trade list minus selected candidate. -->
            <do_if value="$validatedTradeCandidates? and $validatedTradeCandidates.count gt 1">
              <do_all exact="$validatedTradeCandidates.count" counter="$rtIdx">
                <do_if value="$rtIdx gt 1">
                  <append_to_list name="$remainingTrades" exact="$validatedTradeCandidates.{$rtIdx}"/>
                </do_if>
              </do_all>
            </do_if>
            <do_elseif value="$tradeList? and $tradeList.count gt 0">
              <do_all exact="$tradeList.count" counter="$rtIdx">
                <do_if value="$rtIdx != $selectedTradeIdx">
                  <append_to_list name="$remainingTrades" exact="$tradeList.{$rtIdx}"/>
                </do_if>
              </do_all>
            </do_elseif>
            <do_if value="$remainingTrades.count gt 0">
              <set_value name="this.$tradeListFromSignal" exact="$remainingTrades"/>
              <set_value name="this.$searchMethodFromSignal" exact="if $searchMethod? and $searchMethod != '' then $searchMethod else 'signal'"/>
              <set_value name="this.$tradeFoundViaInterrupt" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Retrying validation with remaining candidates after final validation failure (remaining=' + $remainingTrades.count + ', source=' + (if $validatedTradeCandidates? and $validatedTradeCandidates.count gt 1 then 'prevalidated_window' else 'raw_trade_list') + ')'" chance="100"/>
              </do_if>
              <resume label="trade_found"/>
            </do_if>
            <do_else>
              <signal_objects object="this.ship" param="'GT_No_Trade_Found'" param2="'trade_rules_violation'"/>
              <return/>
            </do_else>
          </do_if>
          
          <!-- Offers valid - proceed with order creation -->
          <!-- MK4 internal economics (Â§1.4.1): per-leg internal="true" when the counterparty is
               player-owned so wares move without credit transfer (build storage with no funds,
               player-supplier buys). Foreign supplier legs stay internal="false". MK2 parity. -->

          <!-- Phase 2 (MK4 multitrade):
               Build route in MK1 style:
               - prepare unique valid candidates
               - prefer one full-threshold single trade when available
               - otherwise expand secondaries iteratively with backtrack clustering
                 and budget checks. -->
          <create_list name="$mk4QueueableTrades"/>
          <create_list name="$mk4PreparedCandidates"/>
          <set_value name="$mk4QueueBudgetMoney" exact="player.money"/>
          <set_value name="$mk4QueueMinMoney" exact="if this.$minPlayerMoney? then this.$minPlayerMoney else 1000"/>
          <set_value name="$mk4QueueSourceCount" exact="0"/>
          <set_value name="$mk4PrimaryBudgetBlocked" exact="false"/>
          <!-- TRUE only when the primary leg fails for a genuine money reason (cannot afford even
               1 unit above MinPlayerMoney). Non-money blocks (zero pair amount, destination
               capacity exhausted, no candidate) leave this false so they do NOT raise the
               fleet-wide money cap. -->
          <set_value name="$mk4FleetMoneyInsolvent" exact="false"/>
          <set_value name="$mk4SecondaryBudgetSkipped" exact="0"/>
          <set_value name="$mk4DestBudgetSkipped" exact="0"/>
          <set_value name="$mk4BacktrackSkipped" exact="0"/>
          <set_value name="$mk4DeliveryBudgetBySellOffer" exact="table[]"/>
          <set_value name="$mk4SupplierBudgetByBuyOffer" exact="table[]"/>
          <set_value name="$mk4SupBudgetSkipped" exact="0"/>
          <set_value name="$mk4ShipCargoBudgetByWare" exact="table[]"/>
          <set_value name="$mk4SinglePreferred" exact="false"/>
          <set_value name="$mk4UseMinCargoThresholdForRoute" exact="if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)"/>
          <set_value name="$mk4ThresholdPctForSingle" exact="[10,[(if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)),100].min].max"/>
          <set_value name="$mk4CargoCapacityVolForSingle" exact="if this.ship.cargo.capacity.all? then this.ship.cargo.capacity.all else 0"/>

          <!-- Normalize candidates once (amount clamps + pair dedupe). -->
          <do_if value="$validatedTradeCandidates? and $validatedTradeCandidates.count gt 0">
            <do_all exact="$validatedTradeCandidates.count" counter="$qci">
              <set_value name="$qt" exact="$validatedTradeCandidates.{$qci}"/>
              <set_value name="$qtIsSellOnly" exact="$qt.$IsSellOnly? and $qt.$IsSellOnly"/>
              <set_value name="$qtBuyAmount" exact="if $qt.$FinalBuyAmount? then $qt.$FinalBuyAmount else (if $qt.$Amount? then $qt.$Amount else 0)"/>
              <set_value name="$qtSellAmount" exact="if $qt.$FinalSellAmount? then $qt.$FinalSellAmount else (if $qt.$Amount? then $qt.$Amount else 0)"/>

              <set_value name="$qtSellOfferAmount" exact="0"/>
              <do_if value="$qt.$SellOffer? and $qt.$SellOffer.exists">
                <set_value name="$qtSellOfferAmount" exact="$qt.$SellOffer.offeramount.{this.ship}"/>
                <do_if value="$qtSellOfferAmount == null">
                  <set_value name="$qtSellOfferAmount" exact="0"/>
                </do_if>
                <set_value name="$qtSellAmount" exact="[$qtSellAmount, $qtSellOfferAmount].min"/>
              </do_if>
              <do_else>
                <continue/>
              </do_else>

              <do_if value="not $qtIsSellOnly">
                <set_value name="$qtBuyOfferAmount" exact="0"/>
                <do_if value="$qt.$BuyOffer? and $qt.$BuyOffer.exists">
                  <set_value name="$qtBuyOfferAmount" exact="$qt.$BuyOffer.offeramount.{this.ship}"/>
                  <do_if value="$qtBuyOfferAmount == null">
                    <set_value name="$qtBuyOfferAmount" exact="0"/>
                  </do_if>
                  <set_value name="$qtBuyAmount" exact="[$qtBuyAmount, $qtBuyOfferAmount].min"/>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
                <set_value name="$qtPairAmount" exact="[$qtBuyAmount, $qtSellAmount].min"/>
                <set_value name="$qtBuyAmount" exact="$qtPairAmount"/>
                <set_value name="$qtSellAmount" exact="$qtPairAmount"/>
              </do_if>
              <do_else>
                <set_value name="$qtPairAmount" exact="$qtSellAmount"/>
              </do_else>

              <do_if value="not $qtPairAmount? or $qtPairAmount le 0">
                <continue/>
              </do_if>

              <set_value name="$mk4PrepPairDuplicate" exact="false"/>
              <do_all exact="$mk4PreparedCandidates.count" counter="$ppi">
                <set_value name="$ppTrade" exact="$mk4PreparedCandidates.{$ppi}"/>
                <set_value name="$mk4PrepPairMatch" exact="false"/>
                <do_if value="$ppTrade.$SellOffer == $qt.$SellOffer">
                  <do_if value="$qtIsSellOnly and $ppTrade.$IsSellOnly? and $ppTrade.$IsSellOnly">
                    <set_value name="$mk4PrepPairMatch" exact="true"/>
                  </do_if>
                  <do_elseif value="$ppTrade.$BuyOffer? and $qt.$BuyOffer? and $ppTrade.$BuyOffer == $qt.$BuyOffer">
                    <set_value name="$mk4PrepPairMatch" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="$mk4PrepPairMatch">
                  <set_value name="$mk4PrepPairDuplicate" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="$mk4PrepPairDuplicate">
                <continue/>
              </do_if>

              <set_value name="$qt.$QueuedBuyAmount" exact="$qtBuyAmount"/>
              <set_value name="$qt.$QueuedSellAmount" exact="$qtSellAmount"/>
              <append_to_list name="$mk4PreparedCandidates" exact="$qt"/>
            </do_all>
          </do_if>
          <do_else>
            <set_value name="$pendingTrade.$QueuedBuyAmount" exact="$finalBuyAmount"/>
            <set_value name="$pendingTrade.$QueuedSellAmount" exact="$finalSellAmount"/>
            <append_to_list name="$mk4PreparedCandidates" exact="$pendingTrade"/>
          </do_else>

          <set_value name="$mk4QueueSourceCount" exact="if $mk4PreparedCandidates.count gt 0 then $mk4PreparedCandidates.count else 1"/>

          <!-- Prefer a single trade if it alone reaches threshold (MK1 parity). -->
          <set_value name="$mk4SingleThresholdCandidate" exact="null"/>
          <set_value name="$mk4SingleThresholdBestScore" exact="-999999"/>
          <set_value name="$mk4SingleThresholdFillPct" exact="0"/>
          <set_value name="$mk4SingleThresholdFound" exact="false"/>
          <do_if value="$mk4UseMinCargoThresholdForRoute and $mk4PreparedCandidates.count gt 1 and $mk4CargoCapacityVolForSingle gt 0">
            <do_all exact="$mk4PreparedCandidates.count" counter="$stci">
              <set_value name="$stTrade" exact="$mk4PreparedCandidates.{$stci}"/>
              <set_value name="$stIsSellOnly" exact="$stTrade.$IsSellOnly? and $stTrade.$IsSellOnly"/>
              <set_value name="$stBuyAmount" exact="if $stTrade.$QueuedBuyAmount? then $stTrade.$QueuedBuyAmount else (if $stTrade.$Amount? then $stTrade.$Amount else 0)"/>
              <set_value name="$stSellAmount" exact="if $stTrade.$QueuedSellAmount? then $stTrade.$QueuedSellAmount else (if $stTrade.$Amount? then $stTrade.$Amount else 0)"/>
              <set_value name="$stPairAmount" exact="if $stIsSellOnly then $stSellAmount else [$stBuyAmount, $stSellAmount].min"/>
              <do_if value="$stPairAmount le 0">
                <continue/>
              </do_if>
              <set_value name="$stBuyPrice" exact="if not $stIsSellOnly and $stTrade.$BuyOffer? and $stTrade.$BuyOffer.unitprice? then $stTrade.$BuyOffer.unitprice else 0"/>
              <set_value name="$stSupIsPlayer" exact="false"/>
              <do_if value="not $stIsSellOnly">
                <do_if value="$stTrade.$BuyStation? and $stTrade.$BuyStation.exists and $stTrade.$BuyStation.isplayerowned">
                  <set_value name="$stSupIsPlayer" exact="true"/>
                </do_if>
                <do_elseif value="$stTrade.$BuyOffer? and $stTrade.$BuyOffer.owner? and $stTrade.$BuyOffer.owner.exists and $stTrade.$BuyOffer.owner.isplayerowned">
                  <set_value name="$stSupIsPlayer" exact="true"/>
                </do_elseif>
              </do_if>
              <set_value name="$stPurchaseCost" exact="if $stIsSellOnly or $stSupIsPlayer then 0 else ($stBuyPrice * $stPairAmount)"/>
              <do_if value="$stPurchaseCost gt 0 and ($mk4QueueBudgetMoney - $stPurchaseCost) lt ($mk4QueueMinMoney)Cr">
                <do_if value="not $stIsSellOnly and $stBuyPrice gt 0 and not $stSupIsPlayer">
                  <set_value name="$stAvailableBudget" exact="$mk4QueueBudgetMoney - ($mk4QueueMinMoney)Cr"/>
                  <set_value name="$stAffordableUnits" exact="$stAvailableBudget / $stBuyPrice"/>
                  <do_if value="$stAffordableUnits ge 1">
                    <set_value name="$stPairAmount" exact="[$stPairAmount, $stAffordableUnits].min"/>
                  </do_if>
                  <do_else>
                    <continue/>
                  </do_else>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
              </do_if>
              <set_value name="$stVolumePerUnit" exact="if $stTrade.$Ware? and $stTrade.$Ware.volume? then $stTrade.$Ware.volume else 1"/>
              <set_value name="$stFillPct" exact="if $mk4CargoCapacityVolForSingle gt 0 then (($stPairAmount * $stVolumePerUnit * 100) / $mk4CargoCapacityVolForSingle) else 100"/>
              <set_value name="$stScore" exact="if $stTrade.$Score? then $stTrade.$Score else 0"/>
              <do_if value="$stFillPct ge $mk4ThresholdPctForSingle and (not $mk4SingleThresholdCandidate? or $stScore gt $mk4SingleThresholdBestScore)">
                <set_value name="$mk4SingleThresholdCandidate" exact="$stTrade"/>
                <set_value name="$mk4SingleThresholdBestScore" exact="$stScore"/>
                <set_value name="$mk4SingleThresholdFillPct" exact="$stFillPct"/>
                <set_value name="$mk4SingleThresholdFound" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$mk4SingleThresholdFound and $mk4SingleThresholdCandidate? and $mk4PreparedCandidates.count gt 1">
            <set_value name="$mk4SinglePreferred" exact="true"/>
            <create_list name="$mk4SinglePreferredTrades"/>
            <append_to_list name="$mk4SinglePreferredTrades" exact="$mk4SingleThresholdCandidate"/>
            <set_value name="$mk4PreparedCandidates" exact="$mk4SinglePreferredTrades"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 single-trade preference applied: fill=' + $mk4SingleThresholdFillPct + '% threshold=' + $mk4ThresholdPctForSingle + '% (multitrade deferred)'" chance="100"/>
            </do_if>
          </do_if>

          <!-- Clearance / sell-only: one buyer per cargo snapshot â€” multitrade would queue
               multiple sells for the same ware and cause ERR_NOTHING_TO_SELL on later legs. -->
          <do_if value="not $mk4SinglePreferred and $mk4PreparedCandidates.count gt 1 and $mk4PreparedCandidates.{1}.$IsSellOnly? and $mk4PreparedCandidates.{1}.$IsSellOnly">
            <set_value name="$mk4SinglePreferred" exact="true"/>
            <create_list name="$mk4SellOnlySingleTrades"/>
            <append_to_list name="$mk4SellOnlySingleTrades" exact="$mk4PreparedCandidates.{1}"/>
            <set_value name="$mk4PreparedCandidates" exact="$mk4SellOnlySingleTrades"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 sell-only single-leg enforced (clearance â€” multitrade deferred)'" chance="100"/>
            </do_if>
          </do_if>

          <set_value name="$mk4CargoCapacityVol" exact="if this.ship.cargo.capacity.all? then this.ship.cargo.capacity.all else 0"/>
          <set_value name="$mk4RemainingVolume" exact="$mk4CargoCapacityVol"/>
          <set_value name="$mk4CurrentFillPct" exact="0"/>
          <set_value name="$mk4PrimaryTrade" exact="if $mk4PreparedCandidates.count gt 0 then $mk4PreparedCandidates.{1} else null"/>

          <!-- Add primary trade with authoritative budget clamp. -->
          <do_if value="$mk4PrimaryTrade?">
            <set_value name="$pIsSellOnly" exact="$mk4PrimaryTrade.$IsSellOnly? and $mk4PrimaryTrade.$IsSellOnly"/>
            <set_value name="$pBuyAmount" exact="if $mk4PrimaryTrade.$QueuedBuyAmount? then $mk4PrimaryTrade.$QueuedBuyAmount else (if $mk4PrimaryTrade.$Amount? then $mk4PrimaryTrade.$Amount else 0)"/>
            <set_value name="$pSellAmount" exact="if $mk4PrimaryTrade.$QueuedSellAmount? then $mk4PrimaryTrade.$QueuedSellAmount else (if $mk4PrimaryTrade.$Amount? then $mk4PrimaryTrade.$Amount else 0)"/>
            <set_value name="$pPairAmount" exact="if $pIsSellOnly then $pSellAmount else [$pBuyAmount, $pSellAmount].min"/>
            <set_value name="$pBuyPrice" exact="if not $pIsSellOnly and $mk4PrimaryTrade.$BuyOffer? and $mk4PrimaryTrade.$BuyOffer.unitprice? then $mk4PrimaryTrade.$BuyOffer.unitprice else 0"/>
            <set_value name="$pSupIsPlayer" exact="false"/>
            <do_if value="not $pIsSellOnly">
              <do_if value="$mk4PrimaryTrade.$BuyStation? and $mk4PrimaryTrade.$BuyStation.exists and $mk4PrimaryTrade.$BuyStation.isplayerowned">
                <set_value name="$pSupIsPlayer" exact="true"/>
              </do_if>
              <do_elseif value="$mk4PrimaryTrade.$BuyOffer? and $mk4PrimaryTrade.$BuyOffer.owner? and $mk4PrimaryTrade.$BuyOffer.owner.exists and $mk4PrimaryTrade.$BuyOffer.owner.isplayerowned">
                <set_value name="$pSupIsPlayer" exact="true"/>
              </do_elseif>
            </do_if>
            <set_value name="$pPurchaseCost" exact="if $pIsSellOnly or $pSupIsPlayer then 0 else ($pBuyPrice * $pPairAmount)"/>
            <do_if value="$pPairAmount le 0">
              <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
            </do_if>
            <do_elseif value="$pPurchaseCost gt 0 and ($mk4QueueBudgetMoney - $pPurchaseCost) lt ($mk4QueueMinMoney)Cr">
              <do_if value="not $pIsSellOnly and $pBuyPrice gt 0 and not $pSupIsPlayer">
                <set_value name="$pAvailableBudget" exact="$mk4QueueBudgetMoney - ($mk4QueueMinMoney)Cr"/>
                <set_value name="$pAffordableUnits" exact="$pAvailableBudget / $pBuyPrice"/>
                <do_if value="$pAffordableUnits ge 1">
                  <set_value name="$pPairAmount" exact="[$pPairAmount, $pAffordableUnits].min"/>
                  <set_value name="$pBuyAmount" exact="$pPairAmount"/>
                  <set_value name="$pSellAmount" exact="$pPairAmount"/>
                  <set_value name="$pPurchaseCost" exact="$pBuyPrice * $pBuyAmount"/>
                </do_if>
                <do_else>
                  <!-- Cannot afford even 1 unit above MinPlayerMoney - genuine insolvency. -->
                  <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
                  <set_value name="$mk4FleetMoneyInsolvent" exact="true"/>
                </do_else>
              </do_if>
              <do_else>
                <!-- Purchase cost exceeds budget on a non-clampable buy leg - genuine insolvency. -->
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
                <set_value name="$mk4FleetMoneyInsolvent" exact="true"/>
              </do_else>
            </do_elseif>
            <!-- Destination delivery budget: cumulative sell amount per customer buy offer
                 must not exceed remaining destination capacity across multitrade legs. -->
            <do_if value="not $mk4PrimaryBudgetBlocked and $pPairAmount gt 0 and $mk4PrimaryTrade.$SellOffer?">
              <set_value name="$pDestSellOffer" exact="$mk4PrimaryTrade.$SellOffer"/>
              <do_if value="not $mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}?">
                <!-- Validated prep amount already reflects tradematch demand gate (vanilla
                     incoming + GT reservations). Re-subtracting get_ware_reservation from raw
                     offeramount double-counts in-flight deliveries on busy build storages. -->
                <set_value name="$pDestBudgetInit" exact="$pSellAmount"/>
                <set_value name="$pDestOfferAmt" exact="@$pDestSellOffer.offeramount.{this.ship}"/>
                <do_if value="$pDestOfferAmt? and $pDestOfferAmt gt 0">
                  <set_value name="$pDestBudgetInit" exact="[$pDestBudgetInit, $pDestOfferAmt].min"/>
                </do_if>
                <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$pDestSellOffer}?">
                  <set_value name="$pDestResData" exact="global.$GT_Reservations.{$pDestSellOffer}"/>
                  <do_if value="$pDestResData.$Until? and player.age lt @$pDestResData.$Until and $pDestResData.$Ship? and @$pDestResData.$Ship != this.ship">
                    <set_value name="$pDestResAmt" exact="if $pDestResData.$Amount? and @$pDestResData.$Amount gt 0 then $pDestResData.$Amount else 1"/>
                    <set_value name="$pDestBudgetInit" exact="[($pDestBudgetInit - $pDestResAmt), 0].max"/>
                  </do_if>
                </do_if>
                <set_value name="$mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}" exact="$pDestBudgetInit"/>
              </do_if>
              <set_value name="$pDestBudgetRem" exact="$mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}"/>
              <set_value name="$pPairAmount" exact="[$pPairAmount, $pDestBudgetRem].min"/>
              <do_if value="not $pIsSellOnly">
                <set_value name="$pBuyAmount" exact="[$pBuyAmount, $pPairAmount].min"/>
                <set_value name="$pSellAmount" exact="$pPairAmount"/>
              </do_if>
              <do_else>
                <set_value name="$pSellAmount" exact="$pPairAmount"/>
              </do_else>
              <set_value name="$pPurchaseCost" exact="if $pIsSellOnly or $pSupIsPlayer then 0 else ($pBuyPrice * $pPairAmount)"/>
              <do_if value="$pPairAmount le 0">
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
              </do_if>
            </do_if>
            <!-- Supplier pickup budget: cumulative buy per supplier sell offer must not
                 exceed effective physical stock (player factory cargo minus outbound pickups). -->
            <do_if value="not $mk4PrimaryBudgetBlocked and not $pIsSellOnly and $pPairAmount gt 0 and $mk4PrimaryTrade.$BuyOffer?">
              <set_value name="$pSupBuyOffer" exact="$mk4PrimaryTrade.$BuyOffer"/>
              <do_if value="not $mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}?">
                <set_value name="$pSupBudgetInit" exact="@$pSupBuyOffer.offeramount.{this.ship}"/>
                <do_if value="$pSupBudgetInit == null or $pSupBudgetInit le 0">
                  <do_if value="$pSupBuyOffer.amount?">
                    <set_value name="$pSupBudgetInit" exact="@$pSupBuyOffer.amount"/>
                  </do_if>
                  <do_else>
                    <set_value name="$pSupBudgetInit" exact="0"/>
                  </do_else>
                </do_if>
                <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$pSupBuyOffer}?">
                  <set_value name="$pSupResData" exact="global.$GT_Reservations.{$pSupBuyOffer}"/>
                  <do_if value="$pSupResData.$Until? and player.age lt @$pSupResData.$Until and $pSupResData.$Ship? and @$pSupResData.$Ship != this.ship">
                    <set_value name="$pSupResAmt" exact="if $pSupResData.$Amount? and @$pSupResData.$Amount gt 0 then $pSupResData.$Amount else 1"/>
                    <set_value name="$pSupBudgetInit" exact="[($pSupBudgetInit - $pSupResAmt), 0].max"/>
                  </do_if>
                </do_if>
                <set_value name="$pSupStation" exact="if $mk4PrimaryTrade.$BuyStation? and $mk4PrimaryTrade.$BuyStation.exists then $mk4PrimaryTrade.$BuyStation else null"/>
                <do_if value="not $pSupStation? and $pSupBuyOffer.seller? and @$pSupBuyOffer.seller.exists">
                  <set_value name="$pSupStation" exact="@$pSupBuyOffer.seller"/>
                </do_if>
                <do_if value="not $pSupStation? and $pSupBuyOffer.owner?">
                  <set_value name="$pSupStation" exact="@$pSupBuyOffer.owner"/>
                </do_if>
                <set_value name="$pSupWare" exact="if $mk4PrimaryTrade.$Ware? then $mk4PrimaryTrade.$Ware else (if $pSupBuyOffer.ware? then @$pSupBuyOffer.ware else null)"/>
                <do_if value="$pSupStation? and $pSupStation.exists and $pSupWare?">
                  <get_ware_reservation object="$pSupStation" ware="$pSupWare" type="buy" virtual="false" result="$pSupOutgoingTotal"/>
                  <get_ware_reservation object="$pSupStation" ware="$pSupWare" type="buy" reserver="this.ship" virtual="false" result="$pSupOutgoingSelf"/>
                  <set_value name="$pSupOutgoingOther" exact="[($pSupOutgoingTotal - $pSupOutgoingSelf), 0].max"/>
                  <set_value name="$pSupPhysicalStock" exact="[($pSupStation.cargo.{$pSupWare}.count - $pSupOutgoingOther), 0].max"/>
                  <set_value name="$pSupBudgetInit" exact="[$pSupBudgetInit, $pSupPhysicalStock].min"/>
                </do_if>
                <set_value name="$mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}" exact="$pSupBudgetInit"/>
              </do_if>
              <set_value name="$pSupBudgetRem" exact="$mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}"/>
              <set_value name="$pPairAmount" exact="[$pPairAmount, $pSupBudgetRem].min"/>
              <set_value name="$pBuyAmount" exact="[$pBuyAmount, $pPairAmount].min"/>
              <set_value name="$pSellAmount" exact="$pPairAmount"/>
              <set_value name="$pPurchaseCost" exact="if $pSupIsPlayer then 0 else ($pBuyPrice * $pPairAmount)"/>
              <do_if value="$pPairAmount le 0">
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
              </do_if>
            </do_if>
            <!-- Sell-only: cap by ship cargo remaining across legs (defense if multitrade ever runs). -->
            <do_if value="not $mk4PrimaryBudgetBlocked and $pIsSellOnly and $pPairAmount gt 0 and $mk4PrimaryTrade.$Ware?">
              <set_value name="$pCargoWare" exact="$mk4PrimaryTrade.$Ware"/>
              <do_if value="not $mk4ShipCargoBudgetByWare.{$pCargoWare}?">
                <set_value name="$mk4ShipCargoBudgetByWare.{$pCargoWare}" exact="this.ship.cargo.{$pCargoWare}.count"/>
              </do_if>
              <set_value name="$pCargoBudgetRem" exact="$mk4ShipCargoBudgetByWare.{$pCargoWare}"/>
              <set_value name="$pPairAmount" exact="[$pPairAmount, $pCargoBudgetRem].min"/>
              <set_value name="$pSellAmount" exact="$pPairAmount"/>
              <do_if value="$pPairAmount le 0">
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="not $mk4PrimaryBudgetBlocked and $pPairAmount gt 0">
              <set_value name="$mk4PrimaryTrade.$QueuedBuyAmount" exact="$pBuyAmount"/>
              <set_value name="$mk4PrimaryTrade.$QueuedSellAmount" exact="$pSellAmount"/>
              <append_to_list name="$mk4QueueableTrades" exact="$mk4PrimaryTrade"/>
              <set_value name="$mk4QueueBudgetMoney" exact="$mk4QueueBudgetMoney - $pPurchaseCost"/>
              <do_if value="$mk4PrimaryTrade.$SellOffer?">
                <set_value name="$pDestSellOffer" exact="$mk4PrimaryTrade.$SellOffer"/>
                <set_value name="$mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}" exact="[($mk4DeliveryBudgetBySellOffer.{$pDestSellOffer} - $pPairAmount), 0].max"/>
              </do_if>
              <do_if value="not $pIsSellOnly and $mk4PrimaryTrade.$BuyOffer?">
                <set_value name="$pSupBuyOffer" exact="$mk4PrimaryTrade.$BuyOffer"/>
                <set_value name="$mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}" exact="[($mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer} - $pPairAmount), 0].max"/>
              </do_if>
              <do_elseif value="$pIsSellOnly and $mk4PrimaryTrade.$Ware?">
                <set_value name="$pCargoWare" exact="$mk4PrimaryTrade.$Ware"/>
                <set_value name="$mk4ShipCargoBudgetByWare.{$pCargoWare}" exact="[($mk4ShipCargoBudgetByWare.{$pCargoWare} - $pPairAmount), 0].max"/>
              </do_elseif>
              <set_value name="$pVolumePerUnit" exact="if $mk4PrimaryTrade.$Ware? and $mk4PrimaryTrade.$Ware.volume? then $mk4PrimaryTrade.$Ware.volume else 1"/>
              <set_value name="$mk4RemainingVolume" exact="[0, $mk4RemainingVolume - ($pPairAmount * $pVolumePerUnit)].max"/>
              <set_value name="$mk4CurrentFillPct" exact="if $mk4CargoCapacityVol gt 0 then ((($mk4CargoCapacityVol - $mk4RemainingVolume) * 100) / $mk4CargoCapacityVol) else 100"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
          </do_else>

          <!-- Iteratively add secondary legs (MK1 style) until threshold is reached
               or no valid secondary remains. -->
          <do_if value="not $mk4PrimaryBudgetBlocked and not $mk4SinglePreferred and $mk4PreparedCandidates.count gt 1 and $mk4QueueableTrades.count gt 0">
            <set_value name="$mk4SecondaryBudgetBlocked" exact="table[]"/>
            <do_while value="$mk4QueueableTrades.count lt $validatedCandidateLimit and $mk4RemainingVolume gt 0 and ((not $mk4UseMinCargoThresholdForRoute) or ($mk4CurrentFillPct lt $mk4ThresholdPctForSingle))">
              <set_value name="$mk4BestSecondaryTrade" exact="null"/>
              <set_value name="$mk4BestSecondaryIndex" exact="0"/>
              <set_value name="$mk4BestSecondaryAmount" exact="0"/>
              <set_value name="$mk4BestSecondaryScore" exact="-1"/>

              <do_all exact="$mk4PreparedCandidates.count" counter="$sci">
                <set_value name="$scTrade" exact="$mk4PreparedCandidates.{$sci}"/>
                <do_if value="$mk4SecondaryBudgetBlocked.{$sci}?">
                  <continue/>
                </do_if>

                <!-- Skip exact duplicate offer-pairs already selected (MK1 parity). -->
                <set_value name="$mk4SecondaryAlreadySelected" exact="false"/>
                <do_all exact="$mk4QueueableTrades.count" counter="$qdupi">
                  <set_value name="$mk4DupTrade" exact="$mk4QueueableTrades.{$qdupi}"/>
                  <set_value name="$mk4SecPairMatch" exact="false"/>
                  <do_if value="$mk4DupTrade.$SellOffer == $scTrade.$SellOffer">
                    <do_if value="$scTrade.$IsSellOnly? and $scTrade.$IsSellOnly and $mk4DupTrade.$IsSellOnly? and $mk4DupTrade.$IsSellOnly">
                      <set_value name="$mk4SecPairMatch" exact="true"/>
                    </do_if>
                    <do_elseif value="$mk4DupTrade.$BuyOffer? and $scTrade.$BuyOffer? and $mk4DupTrade.$BuyOffer == $scTrade.$BuyOffer">
                      <set_value name="$mk4SecPairMatch" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="$mk4SecPairMatch">
                    <set_value name="$mk4SecondaryAlreadySelected" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="$mk4SecondaryAlreadySelected">
                  <continue/>
                </do_if>

                <!-- Backtrack cluster on supplier sectors. -->
                <set_value name="$mk4SecondaryBacktrackReject" exact="false"/>
                <set_value name="$scBuySector" exact="if $scTrade.$BuySector? then $scTrade.$BuySector else (if $scTrade.$BuyStation? then $scTrade.$BuyStation.sector else (if $scTrade.$BuyOffer? and $scTrade.$BuyOffer.owner? then $scTrade.$BuyOffer.owner.sector else null))"/>
                <do_if value="this.$effectiveBacktrackTolerance? and this.$effectiveBacktrackTolerance ge 0 and $scBuySector?">
                  <do_all exact="$mk4QueueableTrades.count" counter="$qbi">
                    <set_value name="$qTrade" exact="$mk4QueueableTrades.{$qbi}"/>
                    <set_value name="$qBuySector" exact="if $qTrade.$BuySector? then $qTrade.$BuySector else (if $qTrade.$BuyStation? then $qTrade.$BuyStation.sector else (if $qTrade.$BuyOffer? and $qTrade.$BuyOffer.owner? then $qTrade.$BuyOffer.owner.sector else null))"/>
                    <do_if value="not $qBuySector?">
                      <continue/>
                    </do_if>
                    <set_value name="$qBuyDist" exact="$qBuySector.gatedistance.{$scBuySector}"/>
                    <do_if value="$qBuyDist lt 0 or $qBuyDist gt this.$effectiveBacktrackTolerance">
                      <set_value name="$mk4SecondaryBacktrackReject" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$mk4SecondaryBacktrackReject">
                  <set_value name="$mk4BacktrackSkipped" operation="add"/>
                  <continue/>
                </do_if>

                <set_value name="$scIsSellOnly" exact="$scTrade.$IsSellOnly? and $scTrade.$IsSellOnly"/>
                <set_value name="$scBuyAmount" exact="if $scTrade.$QueuedBuyAmount? then $scTrade.$QueuedBuyAmount else (if $scTrade.$Amount? then $scTrade.$Amount else 0)"/>
                <set_value name="$scSellAmount" exact="if $scTrade.$QueuedSellAmount? then $scTrade.$QueuedSellAmount else (if $scTrade.$Amount? then $scTrade.$Amount else 0)"/>
                <set_value name="$scPairAmount" exact="if $scIsSellOnly then $scSellAmount else [$scBuyAmount, $scSellAmount].min"/>
                <set_value name="$scVolumePerUnit" exact="if $scTrade.$Ware? and $scTrade.$Ware.volume? then $scTrade.$Ware.volume else 1"/>
                <do_if value="$scVolumePerUnit gt 0">
                  <set_value name="$scMaxByVolume" exact="($mk4RemainingVolume / $scVolumePerUnit)i"/>
                  <set_value name="$scPairAmount" exact="[$scPairAmount, $scMaxByVolume].min"/>
                </do_if>
                <do_if value="$scPairAmount le 0">
                  <continue/>
                </do_if>

                <!-- Destination delivery budget (same customer buy offer across legs). -->
                <do_if value="$scTrade.$SellOffer?">
                  <set_value name="$scDestSellOffer" exact="$scTrade.$SellOffer"/>
                  <do_if value="not $mk4DeliveryBudgetBySellOffer.{$scDestSellOffer}?">
                    <set_value name="$scDestBudgetInit" exact="$scPairAmount"/>
                    <set_value name="$scDestOfferAmt" exact="@$scDestSellOffer.offeramount.{this.ship}"/>
                    <do_if value="$scDestOfferAmt? and $scDestOfferAmt gt 0">
                      <set_value name="$scDestBudgetInit" exact="[$scDestBudgetInit, $scDestOfferAmt].min"/>
                    </do_if>
                    <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$scDestSellOffer}?">
                      <set_value name="$scDestResData" exact="global.$GT_Reservations.{$scDestSellOffer}"/>
                      <do_if value="$scDestResData.$Until? and player.age lt @$scDestResData.$Until and $scDestResData.$Ship? and @$scDestResData.$Ship != this.ship">
                        <set_value name="$scDestResAmt" exact="if $scDestResData.$Amount? and @$scDestResData.$Amount gt 0 then $scDestResData.$Amount else 1"/>
                        <set_value name="$scDestBudgetInit" exact="[($scDestBudgetInit - $scDestResAmt), 0].max"/>
                      </do_if>
                    </do_if>
                    <set_value name="$mk4DeliveryBudgetBySellOffer.{$scDestSellOffer}" exact="$scDestBudgetInit"/>
                  </do_if>
                  <set_value name="$scDestBudgetRem" exact="$mk4DeliveryBudgetBySellOffer.{$scDestSellOffer}"/>
                  <set_value name="$scPairAmount" exact="[$scPairAmount, $scDestBudgetRem].min"/>
                  <do_if value="$scPairAmount le 0">
                    <set_value name="$mk4DestBudgetSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- Supplier pickup budget (cumulative per BuyOffer across multitrade legs). -->
                <do_if value="not $scIsSellOnly and $scPairAmount gt 0 and $scTrade.$BuyOffer?">
                  <set_value name="$scSupBuyOffer" exact="$scTrade.$BuyOffer"/>
                  <do_if value="not $mk4SupplierBudgetByBuyOffer.{$scSupBuyOffer}?">
                    <set_value name="$scSupBudgetInit" exact="@$scSupBuyOffer.offeramount.{this.ship}"/>
                    <do_if value="$scSupBudgetInit == null or $scSupBudgetInit le 0">
                      <do_if value="$scSupBuyOffer.amount?">
                        <set_value name="$scSupBudgetInit" exact="@$scSupBuyOffer.amount"/>
                      </do_if>
                      <do_else>
                        <set_value name="$scSupBudgetInit" exact="0"/>
                      </do_else>
                    </do_if>
                    <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$scSupBuyOffer}?">
                      <set_value name="$scSupResData" exact="global.$GT_Reservations.{$scSupBuyOffer}"/>
                      <do_if value="$scSupResData.$Until? and player.age lt @$scSupResData.$Until and $scSupResData.$Ship? and @$scSupResData.$Ship != this.ship">
                        <set_value name="$scSupResAmt" exact="if $scSupResData.$Amount? and @$scSupResData.$Amount gt 0 then $scSupResData.$Amount else 1"/>
                        <set_value name="$scSupBudgetInit" exact="[($scSupBudgetInit - $scSupResAmt), 0].max"/>
                      </do_if>
                    </do_if>
                    <set_value name="$scSupStation" exact="if $scTrade.$BuyStation? and $scTrade.$BuyStation.exists then $scTrade.$BuyStation else null"/>
                    <do_if value="not $scSupStation? and $scSupBuyOffer.seller? and @$scSupBuyOffer.seller.exists">
                      <set_value name="$scSupStation" exact="@$scSupBuyOffer.seller"/>
                    </do_if>
                    <do_if value="not $scSupStation? and $scSupBuyOffer.owner?">
                      <set_value name="$scSupStation" exact="@$scSupBuyOffer.owner"/>
                    </do_if>
                    <set_value name="$scSupWare" exact="if $scTrade.$Ware? then $scTrade.$Ware else (if $scSupBuyOffer.ware? then @$scSupBuyOffer.ware else null)"/>
                    <do_if value="$scSupStation? and $scSupStation.exists and $scSupWare?">
                      <get_ware_reservation object="$scSupStation" ware="$scSupWare" type="buy" virtual="false" result="$scSupOutgoingTotal"/>
                      <get_ware_reservation object="$scSupStation" ware="$scSupWare" type="buy" reserver="this.ship" virtual="false" result="$scSupOutgoingSelf"/>
                      <set_value name="$scSupOutgoingOther" exact="[($scSupOutgoingTotal - $scSupOutgoingSelf), 0].max"/>
                      <set_value name="$scSupPhysicalStock" exact="[($scSupStation.cargo.{$scSupWare}.count - $scSupOutgoingOther), 0].max"/>
                      <set_value name="$scSupBudgetInit" exact="[$scSupBudgetInit, $scSupPhysicalStock].min"/>
                    </do_if>
                    <set_value name="$mk4SupplierBudgetByBuyOffer.{$scSupBuyOffer}" exact="$scSupBudgetInit"/>
                  </do_if>
                  <set_value name="$scSupBudgetRem" exact="$mk4SupplierBudgetByBuyOffer.{$scSupBuyOffer}"/>
                  <set_value name="$scPairAmount" exact="[$scPairAmount, $scSupBudgetRem].min"/>
                  <do_if value="$scPairAmount le 0">
                    <set_value name="$mk4SupBudgetSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>

                <set_value name="$scScore" exact="if $scTrade.$Score? then $scTrade.$Score else 0"/>
                <do_if value="$scPairAmount gt $mk4BestSecondaryAmount or ($scPairAmount == $mk4BestSecondaryAmount and $scScore gt $mk4BestSecondaryScore)">
                  <set_value name="$mk4BestSecondaryTrade" exact="$scTrade"/>
                  <set_value name="$mk4BestSecondaryIndex" exact="$sci"/>
                  <set_value name="$mk4BestSecondaryAmount" exact="$scPairAmount"/>
                  <set_value name="$mk4BestSecondaryScore" exact="$scScore"/>
                </do_if>
              </do_all>

              <do_if value="not $mk4BestSecondaryTrade? or $mk4BestSecondaryAmount le 0">
                <break/>
              </do_if>

              <set_value name="$bsIsSellOnly" exact="$mk4BestSecondaryTrade.$IsSellOnly? and $mk4BestSecondaryTrade.$IsSellOnly"/>
              <set_value name="$bsBuyPrice" exact="if not $bsIsSellOnly and $mk4BestSecondaryTrade.$BuyOffer? and $mk4BestSecondaryTrade.$BuyOffer.unitprice? then $mk4BestSecondaryTrade.$BuyOffer.unitprice else 0"/>
              <set_value name="$bsSupIsPlayer" exact="false"/>
              <do_if value="not $bsIsSellOnly">
                <do_if value="$mk4BestSecondaryTrade.$BuyStation? and $mk4BestSecondaryTrade.$BuyStation.exists and $mk4BestSecondaryTrade.$BuyStation.isplayerowned">
                  <set_value name="$bsSupIsPlayer" exact="true"/>
                </do_if>
                <do_elseif value="$mk4BestSecondaryTrade.$BuyOffer? and $mk4BestSecondaryTrade.$BuyOffer.owner? and $mk4BestSecondaryTrade.$BuyOffer.owner.exists and $mk4BestSecondaryTrade.$BuyOffer.owner.isplayerowned">
                  <set_value name="$bsSupIsPlayer" exact="true"/>
                </do_elseif>
              </do_if>
              <set_value name="$bsPurchaseCost" exact="if $bsIsSellOnly or $bsSupIsPlayer then 0 else ($bsBuyPrice * $mk4BestSecondaryAmount)"/>
              <do_if value="$bsPurchaseCost gt 0 and ($mk4QueueBudgetMoney - $bsPurchaseCost) lt ($mk4QueueMinMoney)Cr">
                <do_if value="not $bsIsSellOnly and $bsBuyPrice gt 0 and not $bsSupIsPlayer">
                  <set_value name="$bsAvailableBudget" exact="$mk4QueueBudgetMoney - ($mk4QueueMinMoney)Cr"/>
                  <set_value name="$bsAffordableUnits" exact="$bsAvailableBudget / $bsBuyPrice"/>
                  <do_if value="$bsAffordableUnits ge 1">
                    <set_value name="$mk4BestSecondaryAmount" exact="[$mk4BestSecondaryAmount, $bsAffordableUnits].min"/>
                    <set_value name="$bsPurchaseCost" exact="$bsBuyPrice * $mk4BestSecondaryAmount"/>
                  </do_if>
                  <do_else>
                    <set_value name="$mk4SecondaryBudgetBlocked.{$mk4BestSecondaryIndex}" exact="true"/>
                    <set_value name="$mk4SecondaryBudgetSkipped" operation="add"/>
                    <continue/>
                  </do_else>
                </do_if>
                <do_else>
                  <set_value name="$mk4SecondaryBudgetBlocked.{$mk4BestSecondaryIndex}" exact="true"/>
                  <set_value name="$mk4SecondaryBudgetSkipped" operation="add"/>
                  <continue/>
                </do_else>
              </do_if>

              <do_if value="$mk4BestSecondaryAmount le 0">
                <set_value name="$mk4SecondaryBudgetBlocked.{$mk4BestSecondaryIndex}" exact="true"/>
                <set_value name="$mk4SecondaryBudgetSkipped" operation="add"/>
                <continue/>
              </do_if>

              <set_value name="$mk4BestSecondaryTrade.$QueuedBuyAmount" exact="if $bsIsSellOnly then 0 else $mk4BestSecondaryAmount"/>
              <set_value name="$mk4BestSecondaryTrade.$QueuedSellAmount" exact="$mk4BestSecondaryAmount"/>
              <append_to_list name="$mk4QueueableTrades" exact="$mk4BestSecondaryTrade"/>
              <set_value name="$mk4QueueBudgetMoney" exact="$mk4QueueBudgetMoney - $bsPurchaseCost"/>
              <do_if value="$mk4BestSecondaryTrade.$SellOffer?">
                <set_value name="$bsDestSellOffer" exact="$mk4BestSecondaryTrade.$SellOffer"/>
                <set_value name="$mk4DeliveryBudgetBySellOffer.{$bsDestSellOffer}" exact="[($mk4DeliveryBudgetBySellOffer.{$bsDestSellOffer} - $mk4BestSecondaryAmount), 0].max"/>
              </do_if>
              <do_if value="not $bsIsSellOnly and $mk4BestSecondaryTrade.$BuyOffer?">
                <set_value name="$bsSupBuyOffer" exact="$mk4BestSecondaryTrade.$BuyOffer"/>
                <set_value name="$mk4SupplierBudgetByBuyOffer.{$bsSupBuyOffer}" exact="[($mk4SupplierBudgetByBuyOffer.{$bsSupBuyOffer} - $mk4BestSecondaryAmount), 0].max"/>
              </do_if>
              <set_value name="$bsVolumePerUnit" exact="if $mk4BestSecondaryTrade.$Ware? and $mk4BestSecondaryTrade.$Ware.volume? then $mk4BestSecondaryTrade.$Ware.volume else 1"/>
              <set_value name="$mk4RemainingVolume" exact="[0, $mk4RemainingVolume - ($mk4BestSecondaryAmount * $bsVolumePerUnit)].max"/>
              <set_value name="$mk4CurrentFillPct" exact="if $mk4CargoCapacityVol gt 0 then ((($mk4CargoCapacityVol - $mk4RemainingVolume) * 100) / $mk4CargoCapacityVol) else 100"/>
            </do_while>
          </do_if>

          <do_if value="$mk4PrimaryBudgetBlocked or $mk4QueueableTrades.count == 0">
            <do_if value="$mk4FleetMoneyInsolvent">
              <!-- Genuine insolvency: the primary leg cannot afford even 1 unit above
                   MinPlayerMoney. Raise the fleet-wide money cap and back off long. -->
              <set_value name="global.$GT_MoneyCapActive" exact="true"/>
              <set_value name="global.$GT_MoneyCapMoney" exact="player.money"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP SET: player.money=' + (player.money / 100) + ' Cr â€” cannot afford 1 unit above MinPlayerMoney (' + $mk4QueueMinMoney + ' Cr)'" chance="100"/>
              <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
            </do_if>
            <do_else>
              <!-- Non-money queue failure: zero pair amount, destination capacity exhausted,
                   or no queueable candidate. This is NOT a budget problem, so it must not
                   freeze the fleet. Use a normal no_trade backoff (short escalating cooldown). -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': multitrade produced no queueable legs (capacity/route, not budget): player.money=' + (player.money / 100) + ' Cr â€” retrying as no_trade'" chance="100"/>
              </do_if>
              <set_value name="this.$lastNoTradeReason" exact="'no_trade'"/>
            </do_else>
            <resume label="no_trade_retry"/>
          </do_if>

          <do_if value="$mk4QueueableTrades.count gt 0">
            <!-- Optional compaction: keep primary leg fixed, then order remaining legs by
                 nearest sell-destination sector to reduce zig-zag routes (MK1 parity). -->
            <do_if value="$mk4QueueableTrades.count gt 2">
              <create_list name="$mk4CompactedTrades"/>
              <append_to_list name="$mk4CompactedTrades" exact="$mk4QueueableTrades.{1}"/>
              <set_value name="$mk4CompactionPicked" exact="table[]"/>
              <set_value name="$mk4CompactionPicked.{1}" exact="true"/>
              <set_value name="$mk4CompactionAnchorSector" exact="if $mk4QueueableTrades.{1}.$SellStation? then $mk4QueueableTrades.{1}.$SellStation.sector else (if $mk4QueueableTrades.{1}.$SellOffer? and $mk4QueueableTrades.{1}.$SellOffer.owner? then $mk4QueueableTrades.{1}.$SellOffer.owner.sector else null)"/>
              <do_while value="$mk4CompactedTrades.count lt $mk4QueueableTrades.count">
                <set_value name="$mk4CompactionBestIdx" exact="0"/>
                <set_value name="$mk4CompactionBestDist" exact="999999"/>
                <do_all exact="$mk4QueueableTrades.count" counter="$mci">
                  <do_if value="$mk4CompactionPicked.{$mci}?">
                    <continue/>
                  </do_if>
                  <set_value name="$mk4CompactionCandidate" exact="$mk4QueueableTrades.{$mci}"/>
                  <set_value name="$mk4CandidateSellSector" exact="if $mk4CompactionCandidate.$SellStation? then $mk4CompactionCandidate.$SellStation.sector else (if $mk4CompactionCandidate.$SellOffer? and $mk4CompactionCandidate.$SellOffer.owner? then $mk4CompactionCandidate.$SellOffer.owner.sector else null)"/>
                  <set_value name="$mk4CompactionDistance" exact="if $mk4CompactionAnchorSector? and $mk4CandidateSellSector? then $mk4CompactionAnchorSector.gatedistance.{$mk4CandidateSellSector} else 0"/>
                  <do_if value="$mk4CompactionDistance lt 0">
                    <set_value name="$mk4CompactionDistance" exact="999999"/>
                  </do_if>
                  <do_if value="$mk4CompactionBestIdx == 0 or $mk4CompactionDistance lt $mk4CompactionBestDist">
                    <set_value name="$mk4CompactionBestIdx" exact="$mci"/>
                    <set_value name="$mk4CompactionBestDist" exact="$mk4CompactionDistance"/>
                  </do_if>
                </do_all>
                <do_if value="$mk4CompactionBestIdx gt 0">
                  <set_value name="$mk4CompactionBestTrade" exact="$mk4QueueableTrades.{$mk4CompactionBestIdx}"/>
                  <append_to_list name="$mk4CompactedTrades" exact="$mk4CompactionBestTrade"/>
                  <set_value name="$mk4CompactionPicked.{$mk4CompactionBestIdx}" exact="true"/>
                  <set_value name="$mk4CompactionAnchorSector" exact="if $mk4CompactionBestTrade.$SellStation? then $mk4CompactionBestTrade.$SellStation.sector else (if $mk4CompactionBestTrade.$SellOffer? and $mk4CompactionBestTrade.$SellOffer.owner? then $mk4CompactionBestTrade.$SellOffer.owner.sector else $mk4CompactionAnchorSector)"/>
                </do_if>
                <do_else>
                  <break/>
                </do_else>
              </do_while>
              <do_if value="$mk4CompactedTrades.count == $mk4QueueableTrades.count">
                <set_value name="$mk4QueueableTrades" exact="$mk4CompactedTrades"/>
              </do_if>
            </do_if>

            <!-- Canonical trade context for follow-up logging/UI remains first selected leg. -->
            <set_value name="$pendingTrade" exact="$mk4QueueableTrades.{1}"/>
            <set_value name="$isSellOnlyTradeForPending" exact="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly"/>
            <set_value name="$finalBuyAmount" exact="if $pendingTrade.$QueuedBuyAmount? then $pendingTrade.$QueuedBuyAmount else (if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount)"/>
            <set_value name="$finalSellAmount" exact="if $pendingTrade.$QueuedSellAmount? then $pendingTrade.$QueuedSellAmount else (if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount)"/>

            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 multitrade execution set: queued=' + $mk4QueueableTrades.count + '/' + $mk4QueueSourceCount + ' (maxTrades=' + $validatedCandidateLimit + ', secondaryBudgetSkipped=' + $mk4SecondaryBudgetSkipped + ', destBudgetSkipped=' + $mk4DestBudgetSkipped + ', supBudgetSkipped=' + $mk4SupBudgetSkipped + ', backtrackSkipped=' + $mk4BacktrackSkipped + ', singlePreferred=' + $mk4SinglePreferred + ')'" chance="100"/>
            </do_if>

            <set_value name="$mk4CycleLegCount" exact="0"/>
            <set_value name="$mk4CycleAmountTotal" exact="0"/>
            <set_value name="$mk4CycleProfitRaw" exact="0"/>
            <set_value name="$mk4CycleMoneyRawTotal" exact="0"/>
            <set_value name="$mk4MultiTradeLegs" exact="[]"/>

            <!-- Pre-order re-clamp: supplier/customer offers may have changed since validation. -->
            <create_list name="$mk4ExecTrades"/>
            <do_all exact="$mk4QueueableTrades.count" counter="$mk4rci">
              <set_value name="$mk4rcTrade" exact="$mk4QueueableTrades.{$mk4rci}"/>
              <set_value name="$mk4rcIsSellOnly" exact="$mk4rcTrade.$IsSellOnly? and $mk4rcTrade.$IsSellOnly"/>
              <set_value name="$mk4rcBuyAmt" exact="if $mk4rcTrade.$QueuedBuyAmount? then $mk4rcTrade.$QueuedBuyAmount else (if $mk4rcTrade.$FinalBuyAmount? then $mk4rcTrade.$FinalBuyAmount else (if $mk4rcTrade.$Amount? then $mk4rcTrade.$Amount else 0))"/>
              <set_value name="$mk4rcSellAmt" exact="if $mk4rcTrade.$QueuedSellAmount? then $mk4rcTrade.$QueuedSellAmount else (if $mk4rcTrade.$FinalSellAmount? then $mk4rcTrade.$FinalSellAmount else (if $mk4rcTrade.$Amount? then $mk4rcTrade.$Amount else 0))"/>
              <set_value name="$mk4rcClampFailed" exact="false"/>

              <do_if value="not $mk4rcIsSellOnly and $mk4rcTrade.$BuyOffer? and @$mk4rcTrade.$BuyOffer.exists">
                <set_value name="$mk4rcBuySeller" exact="null"/>
                <do_if value="$mk4rcTrade.$BuyOffer.seller? and @$mk4rcTrade.$BuyOffer.seller.exists">
                  <set_value name="$mk4rcBuySeller" exact="@$mk4rcTrade.$BuyOffer.seller"/>
                </do_if>
                <do_if value="not $mk4rcBuySeller? and $mk4rcTrade.$BuyOffer.owner? and @$mk4rcTrade.$BuyOffer.owner.exists">
                  <set_value name="$mk4rcBuySeller" exact="@$mk4rcTrade.$BuyOffer.owner"/>
                </do_if>
                <do_if value="$mk4rcBuySeller?">
                  <clamp_trade_amount trade="$mk4rcTrade.$BuyOffer" amount="$mk4rcBuyAmt" buyer="this.ship" seller="$mk4rcBuySeller" result="$mk4rcBuyAmt" reason="$mk4rcBuyClampReason"/>
                </do_if>
                <do_else>
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_else>
                <do_if value="not $mk4rcClampFailed and (not $mk4rcBuyAmt? or $mk4rcBuyAmt le 0)">
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_if>
              </do_if>

              <do_if value="not $mk4rcClampFailed and $mk4rcTrade.$SellOffer? and @$mk4rcTrade.$SellOffer.exists">
                <set_value name="$mk4rcSellBuyer" exact="null"/>
                <do_if value="$mk4rcTrade.$SellOffer.buyer? and @$mk4rcTrade.$SellOffer.buyer.exists">
                  <set_value name="$mk4rcSellBuyer" exact="@$mk4rcTrade.$SellOffer.buyer"/>
                </do_if>
                <do_if value="not $mk4rcSellBuyer? and $mk4rcTrade.$SellOffer.owner? and @$mk4rcTrade.$SellOffer.owner.exists">
                  <set_value name="$mk4rcSellBuyer" exact="@$mk4rcTrade.$SellOffer.owner"/>
                </do_if>
                <do_if value="not $mk4rcSellBuyer?">
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_if>
                <do_if value="not $mk4rcClampFailed">
                  <do_if value="$mk4rcIsSellOnly">
                    <clamp_trade_amount trade="$mk4rcTrade.$SellOffer" amount="$mk4rcSellAmt" buyer="$mk4rcSellBuyer" seller="this.ship" result="$mk4rcSellAmt" reason="$mk4rcSellClampReason"/>
                  </do_if>
                  <do_else>
                    <clamp_trade_amount trade="$mk4rcTrade.$SellOffer" amount="$mk4rcSellAmt" buyer="$mk4rcSellBuyer" result="$mk4rcSellAmt" reason="$mk4rcSellClampReason"/>
                  </do_else>
                  <do_if value="not $mk4rcSellAmt? or $mk4rcSellAmt le 0">
                    <set_value name="$mk4rcClampFailed" exact="true"/>
                  </do_if>
                </do_if>
              </do_if>

              <do_if value="not $mk4rcClampFailed and not $mk4rcIsSellOnly">
                <set_value name="$mk4rcPairAmt" exact="[$mk4rcBuyAmt, $mk4rcSellAmt].min"/>
                <set_value name="$mk4rcBuyAmt" exact="$mk4rcPairAmt"/>
                <set_value name="$mk4rcSellAmt" exact="$mk4rcPairAmt"/>
                <do_if value="$mk4rcPairAmt le 0">
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_if>
              </do_if>

              <do_if value="not $mk4rcClampFailed">
                <set_value name="$mk4rcTrade.$QueuedBuyAmount" exact="$mk4rcBuyAmt"/>
                <set_value name="$mk4rcTrade.$QueuedSellAmount" exact="$mk4rcSellAmt"/>
                <append_to_list name="$mk4ExecTrades" exact="$mk4rcTrade"/>
              </do_if>
              <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 pre-order reclamp dropped leg (buy=' + (if $mk4rcBuyClampReason? then $mk4rcBuyClampReason else 'n/a') + ', sell=' + (if $mk4rcSellClampReason? then $mk4rcSellClampReason else 'n/a') + ')'" chance="100"/>
              </do_elseif>
            </do_all>
            <set_value name="$mk4QueueableTrades" exact="$mk4ExecTrades"/>
            <do_if value="$mk4QueueableTrades.count == 0">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 pre-order reclamp removed all legs â€” retrying search'" chance="100"/>
              </do_if>
              <set_value name="this.$lastNoTradeReason" exact="'no_trade'"/>
              <resume label="no_trade_retry"/>
            </do_if>
            <set_value name="$pendingTrade" exact="$mk4QueueableTrades.{1}"/>
            <set_value name="$isSellOnlyTradeForPending" exact="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly"/>
            <set_value name="$finalBuyAmount" exact="if $pendingTrade.$QueuedBuyAmount? then $pendingTrade.$QueuedBuyAmount else (if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount)"/>
            <set_value name="$finalSellAmount" exact="if $pendingTrade.$QueuedSellAmount? then $pendingTrade.$QueuedSellAmount else (if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount)"/>

            <!-- MK1 parity: two-phase queueing (all SELL first, then all BUY).
                 Use reverse candidate iteration so first selected candidate executes first under LIFO. -->
            <do_all exact="$mk4QueueableTrades.count" counter="$qri">
              <set_value name="$qidx" exact="$mk4QueueableTrades.count - $qri + 1"/>
              <set_value name="$qt" exact="$mk4QueueableTrades.{$qidx}"/>
              <set_value name="$qtIsSellOnlyExec" exact="$qt.$IsSellOnly? and $qt.$IsSellOnly"/>
              <set_value name="$qtExecBuyAmount" exact="if $qt.$QueuedBuyAmount? then $qt.$QueuedBuyAmount else (if $qt.$FinalBuyAmount? then $qt.$FinalBuyAmount else $qt.$Amount)"/>
              <set_value name="$qtExecSellAmount" exact="if $qt.$QueuedSellAmount? then $qt.$QueuedSellAmount else (if $qt.$FinalSellAmount? then $qt.$FinalSellAmount else $qt.$Amount)"/>
              <set_value name="$qtLogAmount" exact="if $qtIsSellOnlyExec then $qtExecSellAmount else $qtExecBuyAmount"/>
              <set_value name="$qtBuyPriceRaw" exact="if $qt.$BuyPrice? then $qt.$BuyPrice else (if $qt.$BuyOffer? and $qt.$BuyOffer.unitprice? then $qt.$BuyOffer.unitprice else 0)"/>
              <set_value name="$qtSellPriceRaw" exact="if $qt.$SellPrice? then $qt.$SellPrice else (if $qt.$SellOffer? and $qt.$SellOffer.unitprice? then $qt.$SellOffer.unitprice else 0)"/>
              <set_value name="$qtProfitRaw" exact="($qtSellPriceRaw - $qtBuyPriceRaw) * $qtLogAmount"/>
              <set_value name="$qtMoneyRaw" exact="-($qtBuyPriceRaw * $qtLogAmount)"/>
              <set_value name="$mk4CycleLegCount" exact="$mk4CycleLegCount + 1"/>
              <set_value name="$mk4CycleAmountTotal" exact="$mk4CycleAmountTotal + $qtLogAmount"/>
              <set_value name="$mk4CycleProfitRaw" exact="$mk4CycleProfitRaw + $qtProfitRaw"/>
              <set_value name="$mk4CycleMoneyRawTotal" exact="$mk4CycleMoneyRawTotal + $qtMoneyRaw"/>
              <set_value name="$mk4BuyStationObj" exact="if $qt.$BuyStation? and $qt.$BuyStation.exists then $qt.$BuyStation else (if $qt.$BuyOffer? and $qt.$BuyOffer.owner? and $qt.$BuyOffer.owner.exists then $qt.$BuyOffer.owner else null)"/>
              <set_value name="$mk4SellStationObj" exact="if $qt.$SellStation? and $qt.$SellStation.exists then $qt.$SellStation else (if $qt.$SellOffer? and $qt.$SellOffer.owner? and $qt.$SellOffer.owner.exists then $qt.$SellOffer.owner else null)"/>
              <append_to_list name="$mk4MultiTradeLegs" exact="table[
                $Amount = $qtLogAmount,
                $Ware = if $qt.$Ware? then $qt.$Ware else null,
                $BuyPriceRaw = $qtBuyPriceRaw,
                $SellPriceRaw = $qtSellPriceRaw,
                $BuyStation = $mk4BuyStationObj,
                $SellStation = $mk4SellStationObj
              ]"/>

              <set_value name="$qtSellLegInternal" exact="false"/>
              <do_if value="$qt.$SellStation? and $qt.$SellStation.exists and $qt.$SellStation.isplayerowned">
                <set_value name="$qtSellLegInternal" exact="true"/>
              </do_if>
              <do_elseif value="$qt.$SellOffer? and $qt.$SellOffer.owner? and $qt.$SellOffer.owner.exists and $qt.$SellOffer.owner.isplayerowned">
                <set_value name="$qtSellLegInternal" exact="true"/>
              </do_elseif>
              <do_if value="$qt.$SellOffer? and $qtExecSellAmount gt 0">
                <create_trade_order object="this.ship" tradeoffer="$qt.$SellOffer" amount="$qtExecSellAmount" immediate="true" internal="$qtSellLegInternal"/>
                <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$sellOfferAmountAfterOrder" exact="@$qt.$SellOffer.offeramount.{this.ship}"/>
                  <set_value name="$sellDesiredAfterOrder" exact="@$qt.$SellOffer.desiredamount"/>
                  <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': after create_trade_order SELL (phase=SELL, leg ' + $qidx + '/' + $mk4QueueableTrades.count + ')' +
                    '\n  orderAmount=' + $qtExecSellAmount +
                    '\n  sell offeramount(ship)=' + (if $sellOfferAmountAfterOrder? then $sellOfferAmountAfterOrder else 'null') +
                    '\n  sell desiredamount=' + (if $sellDesiredAfterOrder? then $sellDesiredAfterOrder else 'null')"
                    chance="100"/>
                </do_if>
              </do_if>
            </do_all>

            <!-- BUY-phase anti-zigzag compaction (MK1 parity intent):
                 group buy legs by supplier sector blocks so load execution does not
                 bounce A->B->A. Either A->A->B or B->B->A is acceptable. -->
            <set_value name="$mk4BuyPhaseTrades" exact="$mk4QueueableTrades"/>
            <do_if value="$mk4QueueableTrades.count gt 2">
              <create_list name="$mk4BuySectorOrder"/>
              <do_all exact="$mk4QueueableTrades.count" counter="$bsoi">
                <set_value name="$bst" exact="$mk4QueueableTrades.{$bsoi}"/>
                <set_value name="$bsSector" exact="if $bst.$BuySector? then $bst.$BuySector else (if $bst.$BuyStation? then $bst.$BuyStation.sector else (if $bst.$BuyOffer? and $bst.$BuyOffer.owner? then $bst.$BuyOffer.owner.sector else null))"/>
                <do_if value="$bsSector?">
                  <set_value name="$mk4SeenBuySector" exact="false"/>
                  <do_all exact="$mk4BuySectorOrder.count" counter="$bssj">
                    <do_if value="$mk4BuySectorOrder.{$bssj} == $bsSector">
                      <set_value name="$mk4SeenBuySector" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                  <do_if value="not $mk4SeenBuySector">
                    <append_to_list name="$mk4BuySectorOrder" exact="$bsSector"/>
                  </do_if>
                </do_if>
              </do_all>
              <create_list name="$mk4BuyPhaseCompacted"/>
              <do_all exact="$mk4BuySectorOrder.count" counter="$bsi">
                <set_value name="$buySectorKey" exact="$mk4BuySectorOrder.{$bsi}"/>
                <do_all exact="$mk4QueueableTrades.count" counter="$bci">
                  <set_value name="$bct" exact="$mk4QueueableTrades.{$bci}"/>
                  <set_value name="$bctSector" exact="if $bct.$BuySector? then $bct.$BuySector else (if $bct.$BuyStation? then $bct.$BuyStation.sector else (if $bct.$BuyOffer? and $bct.$BuyOffer.owner? then $bct.$BuyOffer.owner.sector else null))"/>
                  <do_if value="$bctSector? and $bctSector == $buySectorKey">
                    <append_to_list name="$mk4BuyPhaseCompacted" exact="$bct"/>
                  </do_if>
                </do_all>
              </do_all>
              <!-- Keep sell-only/no-buy-sector legs stable after clustered buy legs. -->
              <do_all exact="$mk4QueueableTrades.count" counter="$bni">
                <set_value name="$bnt" exact="$mk4QueueableTrades.{$bni}"/>
                <set_value name="$bntSector" exact="if $bnt.$BuySector? then $bnt.$BuySector else (if $bnt.$BuyStation? then $bnt.$BuyStation.sector else (if $bnt.$BuyOffer? and $bnt.$BuyOffer.owner? then $bnt.$BuyOffer.owner.sector else null))"/>
                <do_if value="not $bntSector?">
                  <append_to_list name="$mk4BuyPhaseCompacted" exact="$bnt"/>
                </do_if>
              </do_all>
              <do_if value="$mk4BuyPhaseCompacted.count == $mk4QueueableTrades.count">
                <set_value name="$mk4BuyPhaseTrades" exact="$mk4BuyPhaseCompacted"/>
              </do_if>
            </do_if>

            <do_all exact="$mk4BuyPhaseTrades.count" counter="$qri2">
              <set_value name="$qidx" exact="$mk4BuyPhaseTrades.count - $qri2 + 1"/>
              <set_value name="$qt" exact="$mk4BuyPhaseTrades.{$qidx}"/>
              <set_value name="$qtIsSellOnlyExec" exact="$qt.$IsSellOnly? and $qt.$IsSellOnly"/>
              <set_value name="$qtExecBuyAmount" exact="if $qt.$QueuedBuyAmount? then $qt.$QueuedBuyAmount else (if $qt.$FinalBuyAmount? then $qt.$FinalBuyAmount else $qt.$Amount)"/>
              <set_value name="$qtBuyLegInternal" exact="false"/>
              <do_if value="$qt.$BuyStation? and $qt.$BuyStation.exists and $qt.$BuyStation.isplayerowned">
                <set_value name="$qtBuyLegInternal" exact="true"/>
              </do_if>
              <do_elseif value="$qt.$BuyOffer? and $qt.$BuyOffer.owner? and $qt.$BuyOffer.owner.exists and $qt.$BuyOffer.owner.isplayerowned">
                <set_value name="$qtBuyLegInternal" exact="true"/>
              </do_elseif>
              <do_if value="not $qtIsSellOnlyExec and $qt.$BuyOffer? and $qtExecBuyAmount gt 0">
                <create_trade_order object="this.ship" tradeoffer="$qt.$BuyOffer" amount="$qtExecBuyAmount" immediate="true" internal="$qtBuyLegInternal"/>
                <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$buyOfferAmountAfterOrder" exact="@$qt.$BuyOffer.offeramount.{this.ship}"/>
                  <set_value name="$buyDesiredAfterOrder" exact="@$qt.$BuyOffer.desiredamount"/>
                  <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': after create_trade_order BUY (phase=BUY, leg ' + $qidx + '/' + $mk4BuyPhaseTrades.count + ')' +
                    '\n  orderAmount=' + $qtExecBuyAmount +
                    '\n  buy offeramount(ship)=' + (if $buyOfferAmountAfterOrder? then $buyOfferAmountAfterOrder else 'null') +
                    '\n  buy desiredamount=' + (if $buyDesiredAfterOrder? then $buyDesiredAfterOrder else 'null')"
                    chance="100"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>

          <!-- Phase C: runtime illegal-route policy snapshot (cleared on completion/abort). -->
          <do_if value="$effectiveAllowIllegal and $effectiveEnforceRouteIllegalLegality">
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{this.ship}?">
              <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
            </do_if>
            <set_value name="$atpBuySector" exact="if not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner.sector else null"/>
            <set_value name="$atpSellSector" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.sector else null"/>
            <set_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy" exact="table[
              $AllowIllegal = $effectiveAllowIllegal,
              $EnforceRouteIllegalLegality = $effectiveEnforceRouteIllegalLegality,
              $Ware = $finalRouteWare,
              $BuySector = $atpBuySector,
              $SellSector = $atpSellSector,
              $HomeSector = $searchHomeSector,
              $RouteStart = this.ship.sector,
              $Leg = if $isSellOnlyTradeForPending then 'sell' else 'buy',
              $LogbookEntries = $gt_logbookentries,
              $SetAt = player.age
            ]"/>
          </do_if>
          <do_else>
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
              <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
            </do_if>
          </do_else>

          <!-- Fallback flag follows the source of the CURRENT created trade order. -->
          <do_if value="$searchMethod == 'live_fallback'">
            <do_if value="not global.$GT_FallbackTradeActive?">
              <set_value name="global.$GT_FallbackTradeActive" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_FallbackTradeActive.{this.ship}" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Set [FALLBACK] flag - created trade from live_fallback'" chance="100"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='fallback'
              ]"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <remove_value name="global.$GT_FallbackTradeActive.{this.ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Cleared [FALLBACK] flag - created trade from ' + (if $searchMethod != '' then $searchMethod else 'unknown source') + ' (not live_fallback)'" chance="100"/>
              </do_if>
              <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                  $Ship=this.ship,
                  $pilot=this.ship.pilot,
                  $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                  $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                  $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                  $nameType='trader'
                ]"/>
              </do_if>
            </do_if>
          </do_else>
          
          <!-- Clear fleet reservation: create_trade_order has been called, X4 native offeramount.{ship}
               now handles capacity coordination. Remove our pre-selection reservation. -->
          <do_if value="this.$activeReservationKey? and global.$GT_Reservations? and global.$GT_Reservations.{this.$activeReservationKey}?">
            <remove_value name="global.$GT_Reservations.{this.$activeReservationKey}"/>
            <do_if value="global.$GT_ReservationStats? and global.$GT_ReservationStats.$Active gt 0">
              <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
            </do_if>
            <do_if value="global.$GT_ReservationStats?">
              <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet reservation CLEARED (trade orders created, native system active)'" chance="100"/>
            </do_if>
          </do_if>
          <remove_value name="this.$activeReservationKey"/>
          
          <!-- Scenario 2: Purge consumed trade from cache so other ships don't pick it -->
          <do_if value="$searchMethod == 'cache'">
            <do_if value="$mk4QueueableTrades? and $mk4QueueableTrades.count gt 0">
              <do_all exact="$mk4QueueableTrades.count" counter="$cpIdx">
                <set_value name="$cpTrade" exact="$mk4QueueableTrades.{$cpIdx}"/>
                <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                  $Ship = this.ship,
                  $BuyOffer = @$cpTrade.$BuyOffer,
                  $SellOffer = @$cpTrade.$SellOffer,
                  $HomeSector = $searchHomeSector,
                  $CachePool = 'mk4',
                  $Reason = 'consumed'
                ]"/>
              </do_all>
            </do_if>
            <do_else>
              <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                $Ship = this.ship,
                $BuyOffer = @$pendingTrade.$BuyOffer,
                $SellOffer = @$pendingTrade.$SellOffer,
                $HomeSector = $searchHomeSector,
                $CachePool = 'mk4',
                $Reason = 'consumed'
              ]"/>
            </do_else>
          </do_if>
          
          <!-- Purge trades awaiting validation after we successfully queued trade orders.
               Keeping them causes stale execution via old trade data. -->
          <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <!-- Clear interrupt flag when clearing trades awaiting validation (trades successfully processed) -->
          <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>

          <!-- Add state update signal AFTER order creation -->
          <!-- This tests if sending a signal immediately after create_trade_order interferes with TradePerform initialization -->
          <!-- NOTE: No handler exists yet (Phase 3) - signal will be sent but not processed -->
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'Trade_Order_Created',
            $TradeOrderCount = this.ship.tradeorders.count
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PHASE 2: State update signal sent (Trade_Order_Created)'" chance="100"/>
            
            <!-- Handle sell-only trades in debug output -->
              <set_value name="$buyOrderText" exact="if $isSellOnlyTradeForPending then 'N/A (sell-only - ship already has cargo)' else (if $buyStationForPending? then @$buyStationForPending.knownname + ' â†’ ' + (if $wareForPendingTrade? then @$wareForPendingTrade.name else 'Unknown') + ' (x' + $finalBuyAmount + ')' else 'Unknown')"/>
            <set_value name="$sellOrderText" exact="if $sellStationForPending? then @$sellStationForPending.knownname else 'Unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade orders created:' +
              '\n  BUY: ' + $buyOrderText +
              '\n  SELL: ' + $sellOrderText"
              chance="100"/>
          </do_if>
          
          <!-- Send logbook message when ship is escaping from blacklisted sector -->
          <set_value name="$isEscapeTrade" exact="false"/>
          <do_if value="$currentSectorIsBlacklisted">
            <!-- Check if trade leads to a different sector (escape route) -->
            <set_value name="$isEscapeTrade" exact="($buySector != $currentSector) or ($sellSector != $currentSector)"/>
          </do_if>
          
          <do_if value="$isEscapeTrade">
            <!-- Set escape flag for ship naming -->
            <do_if value="global.$GT_Ships?">
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>

            <!-- Build escape route message using translation -->
            <!-- Extract values safely with null checks -->
            <set_value name="$escapeWare" exact="null"/>
            <set_value name="$escapeAmount" exact="0"/>
            <set_value name="$escapeProfit" exact="0"/>
            
            <!-- Extract ware from BuyOffer (more reliable than $Ware property) -->
            <do_if value="$pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware?">
              <set_value name="$escapeWare" exact="$pendingTrade.$BuyOffer.ware.name"/>
            </do_if>
            <do_elseif value="$pendingTrade.$Ware?">
              <set_value name="$escapeWare" exact="$pendingTrade.$Ware.name"/>
            </do_elseif>
            
            <!-- Extract amount -->
            <set_value name="$escapeAmount" exact="if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount"/>
            
            <!-- Extract profit -->
            <do_if value="$pendingTrade.$Profit?">
              <set_value name="$escapeProfit" exact="$pendingTrade.$Profit"/>
            </do_if>
            
            <!-- Safe defaults for missing values -->
            <set_value name="$currentSectorName" exact="'Unknown Sector'"/>
            <do_if value="$currentSector?">
              <set_value name="$currentSectorNameTemp" exact="@$currentSector.knownname"/>
              <do_if value="$currentSectorNameTemp?">
                <set_value name="$currentSectorName" exact="$currentSectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$buyStationName" exact="'Unknown Station'"/>
            <do_if value="$buyStation?">
              <set_value name="$buyStationNameTemp" exact="@$buyStation.knownname"/>
              <do_if value="$buyStationNameTemp?">
                <set_value name="$buyStationName" exact="$buyStationNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$buySectorName" exact="'Unknown Sector'"/>
            <do_if value="$buySector?">
              <set_value name="$buySectorNameTemp" exact="@$buySector.knownname"/>
              <do_if value="$buySectorNameTemp?">
                <set_value name="$buySectorName" exact="$buySectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$sellStationName" exact="'Unknown Station'"/>
            <do_if value="$sellStation?">
              <set_value name="$sellStationNameTemp" exact="@$sellStation.knownname"/>
              <do_if value="$sellStationNameTemp?">
                <set_value name="$sellStationName" exact="$sellStationNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$sellSectorName" exact="'Unknown Sector'"/>
            <do_if value="$sellSector?">
              <set_value name="$sellSectorNameTemp" exact="@$sellSector.knownname"/>
              <do_if value="$sellSectorNameTemp?">
                <set_value name="$sellSectorName" exact="$sellSectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$wareInfo" exact="'Unknown Ware'"/>
            <do_if value="$escapeWare?">
              <set_value name="$wareInfo" exact="$escapeWare"/>
            </do_if>
            
            <!-- Build message using translation ID 3210 with 8 parameters -->
            <!-- Parameters: currentSector, buyStation, buySector, sellStation, sellSector, ware, amount, profit -->
            <set_value name="$escapeMessage" exact="{77000,3210}.[$currentSectorName,$buyStationName,$buySectorName,$sellStationName,$sellSectorName,$wareInfo,$escapeAmount,($escapeProfit / 100)]"/>
            
            <!-- Log the message being written -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE ROUTE LOGBOOK DEBUG:' + '\n  Current Sector: ' + $currentSectorName + '\n  Buy: ' + $buyStationName + ' (' + $buySectorName + ')' + '\n  Sell: ' + $sellStationName + ' (' + $sellSectorName + ')' + '\n  Ware: ' + $wareInfo + ' (x' + $escapeAmount + ')' + '\n  Profit: ' + ($escapeProfit / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <!-- Log the full message text that will be written to logbook -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE ROUTE LOGBOOK MESSAGE:' + '\n' + $escapeMessage" chance="100"/>
            </do_if>
            
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3210}.[$currentSectorName,$buyStationName,$buySectorName,$sellStationName,$sellSectorName,$wareInfo,$escapeAmount,($escapeProfit / 100)]"/>
            
            <!-- Write to ship logbook -->
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'general',
              $Title = 'Escape Route: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Escape route logbook entry created'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clear UR state once a valid trade was selected for execution. -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
            <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Log to ship logbook if enabled (moved from MD execution to after validation) -->
          <set_value name="$logbookEnabled" exact="false"/>
          <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK4Supply' and @this.ship.defaultorder.$logbookentries">
            <set_value name="$logbookEnabled" exact="true"/>
          </do_if>
          <do_elseif value="@this.ship.defaultorder.id == 'Assist' and (((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply') and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
            <set_value name="$logbookEnabled" exact="true"/>
          </do_elseif>

          <!-- Canonical queued trade prices in RAW: use pendingTrade snapshot first (real created-trade values). -->
          <set_value name="$buyPriceRawCanonical" exact="if $pendingTrade.$BuyPrice? then $pendingTrade.$BuyPrice else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.unitprice? then $pendingTrade.$BuyOffer.unitprice else 0)"/>
          <set_value name="$sellPriceRawCanonical" exact="if $pendingTrade.$SellPrice? then $pendingTrade.$SellPrice else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.unitprice? then $pendingTrade.$SellOffer.unitprice else 0)"/>
          <set_value name="$isMultiTradeSignal" exact="$mk4CycleLegCount gt 1"/>
          <set_value name="$uiProfitRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleProfitRaw else (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 0)"/>

          <!-- UI bridge: always publish queued-trade values (independent of per-ship logbook setting). -->
          <set_value name="$uiLogAmount" exact="if $isMultiTradeSignal then $mk4CycleAmountTotal else (if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount)"/>
          <set_value name="$uiBuyPriceRawForSignal" exact="if $isMultiTradeSignal then 0 else $buyPriceRawCanonical"/>
          <set_value name="$uiMoneyRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleMoneyRawTotal else (-$uiLogAmount * $uiBuyPriceRawForSignal)"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$rawBuyOfferUnitPrice" exact="if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.unitprice? then $pendingTrade.$BuyOffer.unitprice else -1"/>
            <set_value name="$rawSellOfferUnitPrice" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.unitprice? then $pendingTrade.$SellOffer.unitprice else -1"/>
            <set_value name="$rawPendingTradeBuyPrice" exact="if $pendingTrade.$BuyPrice? then $pendingTrade.$BuyPrice else -1"/>
            <set_value name="$rawPendingTradeSellPrice" exact="if $pendingTrade.$SellPrice? then $pendingTrade.$SellPrice else -1"/>
            <set_value name="$rawPendingTradeProfit" exact="$uiProfitRawForSignal"/>
            <set_value name="$rawSignalSum" exact="abs($uiMoneyRawForSignal) + $rawPendingTradeProfit"/>
            <debug_text text="'[GT-AI-UI-DUE] ' + this.ship.idcode +
              '\n  MultiTrade: ' + $isMultiTradeSignal + ' (legs=' + $mk4CycleLegCount + ')' +
              '\n  Amount: ' + $uiLogAmount +
              '\n  BuyOffer.unitprice (RAW): ' + $rawBuyOfferUnitPrice +
              '\n  SellOffer.unitprice (RAW): ' + $rawSellOfferUnitPrice +
              '\n  pendingTrade.BuyPrice (RAW?): ' + $rawPendingTradeBuyPrice +
              '\n  pendingTrade.SellPrice (RAW?): ' + $rawPendingTradeSellPrice +
              '\n  Canonical buy price (RAW): ' + $uiBuyPriceRawForSignal +
              '\n  Canonical sell price (RAW): ' + $sellPriceRawCanonical +
              '\n  MoneyRaw sent: ' + $uiMoneyRawForSignal + ' (' + ($uiMoneyRawForSignal / 100) + ' Cr)' +
              '\n  Profit sent (RAW): ' + $rawPendingTradeProfit + ' (' + ($rawPendingTradeProfit / 100) + ' Cr)' +
              '\n  Expected due sum RAW: ' + $rawSignalSum + ' (' + ($rawSignalSum / 100) + ' Cr)'" chance="100"/>
          </do_if>
          <do_if value="$logbookEnabled">
            <set_value name="$logAmount" exact="if $isMultiTradeSignal then $mk4CycleAmountTotal else (if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount)"/>
            <set_value name="$logProfitRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleProfitRaw else (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 0)"/>
            <set_value name="$logMoneyRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleMoneyRawTotal else (-$logAmount * $buyPriceRawCanonical)"/>
            
            <!-- PROFIT DEBUG: Log trade data before sending to logbook -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$wareName" exact="if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware.name else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware.name else 'NULL')"/>
              <set_value name="$buyStationName" exact="if $pendingTrade.$BuyStation? then @$pendingTrade.$BuyStation.knownname else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner.knownname else 'NULL')"/>
              <set_value name="$sellStationName" exact="if $pendingTrade.$SellStation? then @$pendingTrade.$SellStation.knownname else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.knownname else 'NULL')"/>
              <set_value name="$originalAmount" exact="if $pendingTrade.$Amount? then $pendingTrade.$Amount else 'NULL'"/>
              <!-- Use canonical raw snapshot prices to keep buy/sell/profit consistent. -->
              <set_value name="$buyPrice" exact="$buyPriceRawCanonical"/>
              <set_value name="$sellPrice" exact="$sellPriceRawCanonical"/>
              <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') LOGBOOK ENTRY PREPARATION:' + 
                '\n  Ware: ' + $wareName +
                '\n  Buy Station: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr (RAW: ' + $buyPrice + ')' +
                '\n  Sell Station: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr (RAW: ' + $sellPrice + ')' +
                '\n  Original Amount (from trade): ' + $originalAmount + ' units' +
                '\n  Final Buy Amount (clamped): ' + $finalBuyAmount + ' units' +
                '\n  Final Sell Amount (clamped): ' + $finalSellAmount + ' units' +
                '\n  Log Amount (used for display): ' + $logAmount + ' units' +
                '\n  Profit (RAW): ' + (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 'NULL') + ' = ' + (if $pendingTrade.$Profit? then ($pendingTrade.$Profit/100) + ' Cr' else 'NULL') +
                '\n  Verification with original amount: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $originalAmount + ' = ' + (if $originalAmount != 'NULL' then (($sellPrice - $buyPrice) * $originalAmount / 100) + ' Cr' else 'N/A') +
                '\n  Verification with log amount: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $logAmount + ' = ' + (($sellPrice - $buyPrice) * $logAmount / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <!-- Use canonical raw snapshot prices for queued trade message. -->
            <set_value name="$buyPriceForSignal" exact="if $isMultiTradeSignal then 0 else ($buyPriceRawCanonical / 100)"/>
            <set_value name="$sellPriceForSignal" exact="if $isMultiTradeSignal then 0 else ($sellPriceRawCanonical / 100)"/>
            <set_value name="$buyPriceRawForSignal" exact="if $isMultiTradeSignal then 0 else $buyPriceRawCanonical"/>
            <set_value name="$sellPriceRawForSignal" exact="if $isMultiTradeSignal then 0 else $sellPriceRawCanonical"/>
            
            <!-- Determine search pipeline type for logbook display -->
            <set_value name="$logSearchPipeline" exact="'normal'"/>
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?">
              <set_value name="$logSearchPipeline" exact="'isolated'"/>
            </do_if>
            <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <set_value name="$logSearchPipeline" exact="'fallback'"/>
            </do_elseif>
            <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
              $Ship = this.ship,
              $BuyOffer = if $pendingTrade.$BuyOffer? then $pendingTrade.$BuyOffer else null,
              $SellOffer = if $pendingTrade.$SellOffer? then $pendingTrade.$SellOffer else null,
              $Amount = $logAmount,
              $Profit = $logProfitRawForSignal,
              $BuyPrice = $buyPriceForSignal,
              $SellPrice = $sellPriceForSignal,
              $BuyPriceRaw = $buyPriceRawForSignal,
              $SellPriceRaw = $sellPriceRawForSignal,
              $MoneyRaw = $logMoneyRawForSignal,
              $IsSellOnly = $isSellOnlyTradeForPending,
              $IsMultiTrade = $isMultiTradeSignal,
              $MultiTradeLegs = if $isMultiTradeSignal then $mk4MultiTradeLegs else [],
              $MultiTradeSummaryMax = if $isMultiTradeSignal then 6 else 0,
              $SearchPipeline = $logSearchPipeline
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI-LOG-SIGNAL] ' + this.ship.idcode +
                '\n  sell-only: ' + $isSellOnlyTradeForPending + ', multitrade: ' + $isMultiTradeSignal + ' (legs=' + $mk4CycleLegCount + '), pipeline: ' + $logSearchPipeline +
                '\n  Amount sent: ' + $logAmount +
                '\n  BuyPrice sent (Cr): ' + $buyPriceForSignal +
                '\n  SellPrice sent (Cr): ' + $sellPriceForSignal +
                '\n  BuyPrice sent (RAW): ' + $buyPriceRawForSignal +
                '\n  SellPrice sent (RAW): ' + $sellPriceRawForSignal +
                '\n  Profit sent (RAW): ' + $logProfitRawForSignal +
                '\n  MoneyRaw sent: ' + $logMoneyRawForSignal + ' (' + ($logMoneyRawForSignal / 100) + ' Cr)' +
                (if $isMultiTradeSignal then '\n  MultiTradeLegs: ' + $mk4MultiTradeLegs.count else '')" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Full-sweep mode: no chunk continuation needed. -->
          <!-- All trades in list were rejected - check reason -->
          <!-- Use safe access for variables that might not exist -->
          <set_value name="$tradesRejectedPathSafe" exact="if $tradesRejectedPath? then $tradesRejectedPath else 0"/>
          <set_value name="$tradesRejectedDockingSafe" exact="if $tradesRejectedDocking? then $tradesRejectedDocking else 0"/>
          <set_value name="$tradesRejectedOfferInvalidSafe" exact="if $tradesRejectedOfferInvalid? then $tradesRejectedOfferInvalid else 0"/>
          <set_value name="$tradesRejectedDistanceSafe" exact="if $tradesRejectedDistance? then $tradesRejectedDistance else 0"/>
          <set_value name="$tradesRejectedCargoSafe" exact="if $tradesRejectedCargo? then $tradesRejectedCargo else 0"/>
          <set_value name="$tradesRejectedRestrictionSafe" exact="if $tradesRejectedRestriction? then $tradesRejectedRestriction else 0"/>
          <set_value name="$tradesRejectedDemandReservedSafe" exact="if $tradesRejectedDemandReserved? then $tradesRejectedDemandReserved else 0"/>
          <set_value name="$tradesBlacklistedSafe" exact="if $tradesBlacklisted? then $tradesBlacklisted else 0"/>
          <!-- Use safe access for $tradeList.count -->
          <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
          <!-- UR must mean route-blocked by blacklist/pathing only (not distance-limit rejects). -->
          <set_value name="$unreachableRejectedSafe" exact="$tradesBlacklistedSafe + $tradesRejectedPathSafe"/>
          <set_value name="$isIsolatedMode" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
          <set_value name="$isUnreachableOnly" exact="$tradeListCountSafe gt 0 and $searchMethod == 'live' and $unreachableRejectedSafe == $tradeListCountSafe"/>
          
          <!-- Search method already captured earlier in trade_found label -->
          <!-- (from cache, signal param2, or global storage) -->
          
          <!-- Enhanced logging for cache trade rejections -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$searchSource" exact="if $searchMethod == 'cache' then 'CACHE' else if $searchMethod == 'live' then 'LIVE' else 'UNKNOWN'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ALL ' + $tradeListCountSafe + ' trades from ' + $searchSource + ' were rejected:' +
              '\n  Path blocked: ' + $tradesRejectedPathSafe +
              '\n  Docking denied: ' + $tradesRejectedDockingSafe +
              '\n  Offer invalid: ' + $tradesRejectedOfferInvalidSafe +
              '\n  Distance unreachable: ' + $tradesRejectedDistanceSafe +
              '\n  Cargo insufficient: ' + $tradesRejectedCargoSafe +
              '\n  Restriction blocked: ' + $tradesRejectedRestrictionSafe +
              '\n  Demand reserved exhausted: ' + $tradesRejectedDemandReservedSafe +
              '\n  Blacklisted: ' + $tradesBlacklistedSafe +
              '\n  Total rejected: ' + $tradeListCountSafe +
              (if $searchMethod == 'cache' then '\n  Cache exhausted: all ' + $tradeListCountSafe + ' cache candidates failed validation (Restriction=' + $tradesRejectedRestrictionSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Path=' + $tradesRejectedPathSafe + ', Blacklist=' + $tradesBlacklistedSafe + ')' else '') +
              ' - entering retry logic'" chance="100"/>
          </do_if>
          
          <!-- CRITICAL:
               If ALL trades were rejected (often because offers changed), we MUST purge trades awaiting validation.
               Otherwise the ship can loop forever on stale global.$GT_TradesAwaitingValidation.{this.ship} and never request fresh trades. -->
          <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <!-- Clear interrupt flag when clearing trades awaiting validation to prevent re-entry loop -->
          <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
          <!-- Reduce escalating backoff after purging stale results: next retry will start at 10s again -->
          <set_value name="this.$searchFailed" exact="0"/>

          <!-- Isolated mode is current-sector-only. Remove stale UR and do not re-apply it while isolated. -->
          <do_if value="$isIsolatedMode and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
            <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Mark unreachable-routes state when all evaluated live trades are blocked by blacklist/path reachability. -->
          <do_if value="$isUnreachableOnly and not $isIsolatedMode">
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{this.ship}?">
              <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{this.ship}.$Unreachable" exact="true"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>

            <!-- Roleplay logbook message (throttled) for blacklist/path unreachable profitable routes. -->
            <do_if value="$gt_logbookentries">
              <set_value name="$lastUnreachableLogbook" exact="0"/>
              <do_if value="this.$lastUnreachableLogbookTime?">
                <set_value name="$lastUnreachableLogbook" exact="this.$lastUnreachableLogbookTime"/>
              </do_if>
              <set_value name="$unreachableSinceLast" exact="player.age - $lastUnreachableLogbook"/>
              <do_if value="$lastUnreachableLogbook == 0 or $unreachableSinceLast ge 300s">
                <set_value name="$urCurrentSectorName" exact="if this.ship.sector? then @this.ship.sector.knownname else 'Unknown Sector'"/>
                <set_value name="$urNormalRange" exact="if this.$effectiveMaxBuy? and this.$effectiveMaxSell? then [this.$effectiveMaxBuy, this.$effectiveMaxSell].max else (if this.$effectiveMaxSell? and this.$effectiveMaxSell gt 0 then this.$effectiveMaxSell else 1)"/>
                <set_value name="$urNearbyRange" exact="[1, ($urNormalRange / 3)i].max"/>
                <set_value name="$urMessage" exact="{77000,3221}.[this.ship.knownname, $urCurrentSectorName, $urNormalRange, $urNearbyRange]"/>
                <set_value name="$redColor" exact="'\033#FFCC0000#'"/>
                <set_value name="$colorReset" exact="'\033X'"/>
                <set_value name="$urTitle" exact="$redColor + 'Unreachable Routes: ' + $colorReset + this.ship.knownname"/>
                <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                  $Message = $urMessage,
                  $Category = 'alerts',
                  $Title = $urTitle,
                  $Object = this.ship,
                  $Interaction = 'showonmap',
                  $CheckGlobalSettings = true
                ]"/>
                <set_value name="this.$lastUnreachableLogbookTime" exact="player.age"/>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Keep UR sticky across unsuccessful search cycles.
                 UR is intentionally cleared only when a valid trade is selected for execution. -->
          </do_else>
          
          <!-- If ALL trades rejected due to cargo space, trigger cargo disposal -->
          <!-- Use safe access for variable check -->
          <do_if value="$tradesRejectedCargoSafe gt 0 and $tradesRejectedCargoSafe == $tradeListCountSafe">
            <set_value name="$hasCargo" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
            <do_if value="$hasCargo">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  ALL trades rejected due to insufficient cargo space - triggering cargo disposal'" chance="100"/>
              </do_if>
              <!-- Ship has cargo but not enough space for any trade - find buyer for existing cargo -->
              <signal_objects object="player.galaxy" param="'GT_Find_Sell'" param2="table[
                $Ship = this.ship,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true
              ]"/>
              <!-- CRITICAL: Resume to wait_for_response so ship is ready to receive GT_Search_Go immediately.
                   Resuming to main_loop caused GT_Search_Go to arrive while ship was busy elsewhere (no matching
                   interrupt), leading to missed signals and up-to-60s waits for sell-order discovery. -->
              <resume label="wait_for_response"/>
            </do_if>
          </do_if>

          <!-- ESCAPE FALLBACK (trade list exists but none can move us out safely):
               If we are in a blacklisted sector and we have no non-blacklisted escape trade, force a move toward home.
               Whitelist overrides blacklist (matches GT_IsSectorBlacklisted). -->
          <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          <set_value name="$validationWhitelist" exact="[]"/>
          <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
            <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
          </do_if>
          <set_value name="$currentSector" exact="this.ship.sector"/>
          <set_value name="$needsEscape" exact="false"/>
          <do_if value="$currentSector? and $currentSector.exists">
            <set_value name="$curWhitelisted" exact="false"/>
            <do_if value="$validationWhitelist.count gt 0">
              <do_all exact="$validationWhitelist.count" counter="$swIdx">
                <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                  <set_value name="$curWhitelisted" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $curWhitelisted">
              <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
              <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
              <set_value name="$needsEscape" exact="$curActivityBL or $curTravelBL"/>
            </do_if>
          </do_if>
          <do_if value="$needsEscape and ($tradeListCountSafe == 0 or $tradesBlacklistedSafe == $tradeListCountSafe)">
            <!-- Set escape flag for ship naming -->
            <do_if value="global.$GT_Ships?">
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: No valid escape trade found (all trades blacklisted) - moving toward home sector'" chance="100"/>
            </do_if>
            <resume label="escape_from_blacklisted"/>
          </do_if>
          
          <!-- Cache exhausted: retry remaining cache entries before forcing mk4live when rejections
               are transient-only (stale offers / demand saturation) and the home pool is larger. -->
          <do_if value="$searchMethod == 'cache'">
            <set_value name="$cacheHardRejectTotal" exact="$tradesRejectedPathSafe + $tradesRejectedDockingSafe + $tradesRejectedDistanceSafe + $tradesRejectedCargoSafe + $tradesRejectedRestrictionSafe + $tradesBlacklistedSafe"/>
            <set_value name="$cacheTransientRejectTotal" exact="$tradesRejectedOfferInvalidSafe + $tradesRejectedDemandReservedSafe"/>
            <set_value name="$cacheExhaustedTransientOnly" exact="$tradeListCountSafe gt 0 and $cacheHardRejectTotal == 0 and $cacheTransientRejectTotal == $tradeListCountSafe"/>
            <set_value name="$cacheExhaustHomeSector" exact="if this.$lastPriorityWaresHome? and this.$lastPriorityWaresHome.exists then this.$lastPriorityWaresHome else (if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else this.ship.sector))"/>
            <set_value name="$cacheExhaustPoolSize" exact="0"/>
            <do_if value="$cacheExhaustHomeSector? and $cacheExhaustHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$cacheExhaustHomeSector}?">
              <set_value name="$cacheExhaustPoolSize" exact="@global.$GT_TradeCacheMK4.{$cacheExhaustHomeSector}.count"/>
            </do_if>
            <do_if value="$cacheExhaustedTransientOnly and $cacheExhaustPoolSize gt $tradeListCountSafe">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache batch exhausted (transient-only) â€” retrying cache before live (' + $tradeListCountSafe + '/' + $cacheExhaustPoolSize + ' entries tried, home=' + (if $cacheExhaustHomeSector.knownname? then @$cacheExhaustHomeSector.knownname else '?') + ')'" chance="100"/>
              </do_if>
              <!-- Stale-offer rejections flag per-ship on entries; clear before retry so other pool rows can match. -->
              <do_if value="$cacheExhaustHomeSector? and $cacheExhaustHomeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$cacheExhaustHomeSector}?">
                <do_all exact="global.$GT_TradeCacheMK4.{$cacheExhaustHomeSector}.count" counter="$cacheRetryFsi">
                  <set_value name="$cacheRetryEntry" exact="global.$GT_TradeCacheMK4.{$cacheExhaustHomeSector}.{$cacheRetryFsi}"/>
                  <do_if value="$cacheRetryEntry? and $cacheRetryEntry.$FailedShips? and $cacheRetryEntry.$FailedShips.count gt 0">
                    <set_value name="$cacheRetryNewFailed" exact="[]"/>
                    <do_all exact="$cacheRetryEntry.$FailedShips.count" counter="$cacheRetryFsi2">
                      <do_if value="$cacheRetryEntry.$FailedShips.{$cacheRetryFsi2} != this.ship">
                        <append_to_list name="$cacheRetryNewFailed" exact="$cacheRetryEntry.$FailedShips.{$cacheRetryFsi2}"/>
                      </do_if>
                    </do_all>
                    <set_value name="$cacheRetryEntry.$FailedShips" exact="$cacheRetryNewFailed"/>
                  </do_if>
                </do_all>
              </do_if>
              <set_value name="$signalMaxBuy" exact="$maxbuy"/>
              <set_value name="$signalMaxSell" exact="$maxsell"/>
              <do_if value="this.$effectiveMaxBuy?">
                <set_value name="$signalMaxBuy" exact="this.$effectiveMaxBuy"/>
              </do_if>
              <do_if value="this.$effectiveMaxSell?">
                <set_value name="$signalMaxSell" exact="this.$effectiveMaxSell"/>
              </do_if>
              <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
                $Ship = this.ship,
                $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
                $MaxBuy = $signalMaxBuy,
                $MaxSell = $signalMaxSell,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
                $SearchPool = 'mk4_supply',
                $SearchDepth = if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30,
                $ForceLiveSearch = false,
                $LiveSearchPriority = false
              ]"/>
              <resume label="wait_for_response"/>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache exhausted â€” all ' + $tradeListCountSafe + ' cache candidates failed validation, triggering LIVE market search' +
                  '\n  Rejection breakdown: Path=' + $tradesRejectedPathSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Distance=' + $tradesRejectedDistanceSafe + ', Cargo=' + $tradesRejectedCargoSafe + ', Restriction=' + $tradesRejectedRestrictionSafe + ', DemandReserved=' + $tradesRejectedDemandReservedSafe + ', Blacklist=' + $tradesBlacklistedSafe +
                  (if $cacheExhaustPoolSize gt 0 then '\n  Home cache pool size: ' + $cacheExhaustPoolSize else '')" chance="100"/>
              </do_if>
              <!-- Send signal to force live search (bypass cache) -->
              <!-- Include MaxBuy/MaxSell - use effective values if available, otherwise use defaults from order params -->
              <set_value name="$signalMaxBuy" exact="$maxbuy"/>
              <set_value name="$signalMaxSell" exact="$maxsell"/>
              <do_if value="this.$effectiveMaxBuy?">
                <set_value name="$signalMaxBuy" exact="this.$effectiveMaxBuy"/>
              </do_if>
              <do_if value="this.$effectiveMaxSell?">
                <set_value name="$signalMaxSell" exact="this.$effectiveMaxSell"/>
              </do_if>
              <!-- effectiveIgnoreCarrierAux/BuildStorage/TradeRules initialized in <init> -->
              
              <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
                $Ship = this.ship,
                $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
                $MaxBuy = $signalMaxBuy,
                $MaxSell = $signalMaxSell,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
                $SearchPool = 'mk4_supply',
                $SearchDepth = if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30,
                $ForceLiveSearch = true,
                $LiveSearchPriority = true
              ]"/>
              <!-- CRITICAL: Resume to wait_for_response instead of main_loop -->
              <!-- This ensures the ship waits for the live search result instead of sending a duplicate request -->
              <!-- The wait block will catch GT_Trade_Found signal when live search completes -->
              <resume label="wait_for_response"/>
            </do_else>
          </do_if>
          <do_elseif value="$searchMethod == 'live' or $searchMethod == 'live_sell_only' or $searchMethod == 'live_fallback'">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': All live trades rejected - releasing scheduler slot, backing off before fresh live search' +
                '\n  Rejection breakdown: Path=' + $tradesRejectedPathSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Distance=' + $tradesRejectedDistanceSafe + ', Cargo=' + $tradesRejectedCargoSafe + ', Restriction=' + $tradesRejectedRestrictionSafe + ', DemandReserved=' + $tradesRejectedDemandReservedSafe + ', Blacklist=' + $tradesBlacklistedSafe +
                '\n  All ' + $tradeListCountSafe + ' live trades invalid at validation - skip stale cache on next attempt'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
            <set_value name="this.$forceLiveAfterLiveReject" exact="true"/>
            <resume label="no_trade_retry"/>
          </do_elseif>
          <do_else>
            <!-- Trades came from unknown source - use normal retry -->
            <resume label="no_trade_retry"/>
          </do_else>
        </do_else>
      
      <!-- Stability: vanilla-style micro-yield after creating trade orders -->
      <!-- NOTE: wait must be at top level (not inside any do_if/do_else) -->
      <wait exact="this.$gt_yieldMs * 1ms"/>
      
      <!-- Set ship to trading state -->
      <set_command command="command.trade"/>
      
      <!-- Wait for trade completion or failure signal from diff patch (event-driven, no polling) -->
      <wait max="300s" comment="Wait for trade completion or failure signal">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Completed'"/>
              <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
            </check_any>
          </conditions>
          <actions>
            <!-- Check which signal was received -->
            <do_if value="event.param == 'GT_Trade_Completed'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] Trade completed signal received for ' + this.ship.idcode" chance="100"/>
              </do_if>
              <set_value name="this.$tradeComplete" exact="true"/>
              
              <!-- Restore XPBlocked if BlockedLevel still exists (training stations may have become available) -->
              <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
                <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
                  <set_value name="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked" exact="true"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ðŸ”’ Restored XPBlocked for pilot ' + this.ship.pilot.name + ' after trade completion (BlockedLevel: ' + global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel + ')'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
            <do_elseif value="event.param == 'GT_Trade_Failed'">
              <!-- Note: fallback flag is now managed only at trade creation based on search source. -->
              <!-- Isolated flag state will be verified by batch processor on next state check. -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Trade failed - keeping current fallback state until next trade creation; isolation state will be checked by batch processor'" chance="100"/>
              </do_if>
              <!-- Read structured payload (with legacy guard for backward compatibility) -->
              <set_value name="$failurePayload" exact="event.param2"/>
              
              <!-- Handle legacy payloads (string) vs new structured payloads (table) -->
              <set_value name="$isLegacyPayload" exact="false"/>
              <do_if value="typeof $failurePayload == datatype.string">
                <set_value name="$isLegacyPayload" exact="true"/>
                <set_value name="this.$failureReason" exact="$failurePayload"/>
                <set_value name="this.$tradeFailed" exact="true"/>
                <set_value name="this.$tryNextTrade" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] Trade failed (legacy payload) for ' + this.ship.idcode + ': ' + this.$failureReason" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- New structured payload -->
                <!-- Extract properties with safe access, then check if they exist -->
                <set_value name="$reasonTypeValue" exact="@$failurePayload.$ReasonType"/>
                <set_value name="$shouldTryNextValue" exact="@$failurePayload.$ShouldTryNext"/>
                <set_value name="$reasonType" exact="if $reasonTypeValue? then $reasonTypeValue else 'MARKET'"/>
                <set_value name="$shouldTryNext" exact="if $shouldTryNextValue? then $shouldTryNextValue else false"/>
                
                <set_value name="this.$failureReason" exact="$failurePayload.$Reason"/>
                <set_value name="this.$tradeFailed" exact="true"/>
                <set_value name="this.$tryNextTrade" exact="$shouldTryNext"/>
                
                <do_if value="this.$failureReason == 'route_illegal_pre_transit'">
                  <set_value name="this.$lastNoTradeReason" exact="'route_illegal_pre_transit'"/>
                  <do_if value="$gt_logbookentries and global.$GT_Ships? and global.$GT_Ships.{this.ship}.$RouteIllegalAbort?">
                    <set_value name="$ria" exact="global.$GT_Ships.{this.ship}.$RouteIllegalAbort"/>
                    <set_value name="$riaNextSectorName" exact="if $ria.$NextSector? then @$ria.$NextSector.knownname else 'Unknown'"/>
                    <set_value name="$riaWareName" exact="if $ria.$Ware? then @$ria.$Ware.name else 'Unknown'"/>
                    <set_value name="$riaPoliceName" exact="if $ria.$PoliceFaction? then @$ria.$PoliceFaction.knownname else 'Unknown'"/>
                    <set_value name="$logbookMessage" exact="'Commander,\n\nILLEGAL ROUTE BLOCKED\n\nBefore entering sector ' + $riaNextSectorName + ', sector policing now prohibits cargo ware ' + $riaWareName + ' for our owner (police faction: ' + $riaPoliceName + ').\n\nI have aborted the current trade run and will search for an alternative route.\n\nWith vigilance,\nAboard ' + this.ship.knownname"/>
                    <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                      $Message = $logbookMessage,
                      $Category = 'alerts',
                      $Title = 'Illegal Route Blocked: ' + this.ship.knownname,
                      $Object = this.ship,
                      $Interaction = 'showonmap',
                      $Highlighted = false
                    ]"/>
                  </do_if>
                </do_if>
                
                <do_if value="$shouldTryNext">
                  <debug_text text="'[GT-AI] Pathfinding failed for ' + this.ship.idcode + ': ' + this.$failureReason + ' - trying next cached alternative'" chance="100"/>
                </do_if>
                <do_else>
                  <debug_text text="'[GT-AI] Trade failed for ' + this.ship.idcode + ': ' + this.$failureReason + ' - will search for new trade'" chance="100"/>
                </do_else>
              </do_else>
            </do_elseif>
            <resume label="trade_completed"/>
          </actions>
        </interrupt>
      </wait>
      
      <!-- Timeout fallback -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade completion timeout after 300s - resuming anyway'" chance="100"/>
      </do_if>
      
      <label name="trade_completed"/>
      
      <!-- NOTE: Global money cap (global.$GT_MoneyCapActive) auto-clears in the early money gate
           when player.money rises above global.$GT_MoneyCapMoney. No per-ship clearing needed. -->
      
      <!-- Fallback flag is intentionally NOT changed on trade completion.
           It is set/cleared only when a new trade order is created and source is known. -->
      
      <!-- CRITICAL: Clear trades awaiting validation after trade execution completes -->
      <!-- This ensures ships always check cache first on next search, not stale pending trades -->
      <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
      </do_if>
      <!-- Clear active trade tracking -->
      <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{this.ship}?">
        <remove_value name="global.$GT_ActiveTrade.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
        <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (After Trade)   -->
      <!-- ======================================= -->
      <!-- Check for pilot changes after successful trade completion -->
      <!-- This is a natural restart point where the GT default order reruns -->
      <set_value name="$currentPilot" exact="this.ship.pilot"/>
      <do_if value="this.$trackedPilot? and $currentPilot != this.$trackedPilot">
        <!-- Pilot changed! Send signal to MD system -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PILOT CHANGE DETECTED after trade completion! Old: ' + @this.$trackedPilot.name + ', New: ' + @$currentPilot.name" chance="100"/>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
          $updateType = 'pilot_change',
          $Ship = this.ship,
          $pilot = $currentPilot,
          $oldPilot = this.$trackedPilot
        ]"/>
      </do_if>
      <!-- Update tracked pilot (always, even if no change) -->
      <set_value name="this.$trackedPilot" exact="$currentPilot"/>
      
      <!-- CRITICAL: Check if pilot is missing (pilot was transferred away) -->
      <!-- If GT order is running but ship has no pilot, cleanup and self-cancel -->
      <do_if value="not $currentPilot">
        <set_value name="$pendingTransferredPilot" exact="false"/>
        <set_value name="$pendingPilotName" exact="'NONE'"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$pk">
            <set_value name="$candidatePilot" exact="$pilotKeys.{$pk}"/>
            <do_if value="$candidatePilot and global.$GT_Pilots.{$candidatePilot}? and global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == this.ship.idcode and global.$GT_Pilots.{$candidatePilot}.$Status? and global.$GT_Pilots.{$candidatePilot}.$Status == 'paused'">
              <set_value name="$pendingTransferredPilot" exact="true"/>
              <set_value name="$pendingPilotName" exact="if $candidatePilot.name? then $candidatePilot.name else 'UNKNOWN'"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$pendingTransferredPilot">
          <do_if value="not this.$pendingPilotTransferSince?">
            <set_value name="this.$pendingPilotTransferSince" exact="player.age"/>
          </do_if>
          <set_value name="$pendingTransferElapsed" exact="player.age - this.$pendingPilotTransferSince"/>
          
          <do_if value="$pendingTransferElapsed lt 15min">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Missing pilot after trade completion but transfer is in progress for ' + $pendingPilotName + ' (elapsed=' + ($pendingTransferElapsed / 1s) + 's) - waiting before cancellation'" chance="100"/>
            </do_if>
            <wait exact="5s"/>
            <return/>
          </do_if>
        </do_if>
        
        <remove_value name="this.$pendingPilotTransferSince"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MISSING PILOT DETECTED after trade completion - pilot was transferred away, cleaning up and self-canceling GT order'" chance="100"/>
        </do_if>
        
        <!-- Get original ship name from ship registry -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{this.ship}.$OriginalShipName"/>
        </do_if>
        
        <!-- Send cleanup signal (name restoration handled by MD system) -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = null,
          $Reason = 'Pilot transferred away - GT order cannot run without pilot',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Cancel all active orders (trade orders, etc.) -->
        <cancel_all_orders object="this.ship"/>
        
        <!-- Self-cancel GT order -->
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Check if this is a pathfinding retry (try next cached alternative) -->
      <do_if value="this.$tryNextTrade?">
        <remove_value name="this.$tryNextTrade"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Immediately requesting next trade (cache will skip failed trades)'" chance="100"/>
        </do_if>
        <!-- Skip market update wait - immediately try next cached trade -->
        <resume label="main_loop"/>
      </do_if>
      
      <!-- NOTE: Auto-repair check has been moved to MD system (gt_trading_ai.xml TradeCompleted cue) -->
      <!-- This ensures it runs even when the order is aborted/replaced during trade execution -->
      
      <!-- Update market data interval -->
      <wait max="$gt_marketupdatefreq">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Found'" comment="New trade found"/>
              <event_object_signalled object="this.ship" param="'GT_No_Trade_Found'" comment="Wake-up signal"/>
            </check_any>
          </conditions>
          <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Signal received during market update wait - resuming immediately'" chance="100"/>
            </do_if>
          </actions>
        </interrupt>
      </wait>
      <resume label="main_loop"/>
      
      <!-- ========================================= -->
      <!-- NO TRADE FOUND - ESCALATING RETRY LOGIC  -->
      <!-- ========================================= -->
      <label name="escape_from_blacklisted"/>
      
      <!-- Determine home sector -->
      <set_value name="$homeBase" exact="this.$effectiveHome"/>
      <set_value name="$homeSector" exact="null"/>
      <do_if value="$homeBase? and $homeBase.exists">
        <do_if value="$homeBase.isclass.station">
          <set_value name="$homeSector" exact="$homeBase.sector"/>
        </do_if>
        <do_elseif value="$homeBase.isclass.sector">
          <set_value name="$homeSector" exact="$homeBase"/>
        </do_elseif>
      </do_if>
      <do_if value="not $homeSector? or not $homeSector.exists">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: Home sector not available - cannot escape, continuing retry logic'" chance="100"/>
        </do_if>
        <resume label="no_trade_retry"/>
      </do_if>
      
      <set_value name="$currentSector" exact="this.ship.sector"/>
      <do_if value="$currentSector == $homeSector">
        <!-- Already in home sector; just retry normally -->
        <resume label="main_loop"/>
      </do_if>
      
      <!-- Use cached blacklist group from init -->
      <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
      
      <!-- Resolve sector whitelist for escape candidate selection (whitelist overrides blacklist) -->
      <set_value name="$validationWhitelist" exact="[]"/>
      <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
        <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
      </do_if>
      
      <!-- Build a jump path to home (ignoring blacklist so we can walk 'toward home') -->
      <get_jump_path component="$jumppath" multiple="true" uselocalhighways="true">
        <start object="this.ship"/>
        <end object="$homeSector"/>
      </get_jump_path>
      
      <!-- Choose the first non-blacklisted sector along the route (or the home sector) -->
      <set_value name="$escapeSector" exact="$homeSector"/>
      <do_all exact="$jumppath.count" counter="$pi">
        <set_value name="$entry" exact="$jumppath.{$pi}"/>
        <do_if value="$entry? and ($entry.isclass.gate or $entry.isclass.highwayentrygate)">
          <set_value name="$candidateSector" exact="$entry.destination.sector"/>
          <set_value name="$candWhitelisted" exact="false"/>
          <do_if value="$validationWhitelist.count gt 0">
            <do_all exact="$validationWhitelist.count" counter="$swIdx">
              <do_if value="$validationWhitelist.{$swIdx} == $candidateSector">
                <set_value name="$candWhitelisted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$candActivityBL" exact="false"/>
          <set_value name="$candTravelBL" exact="false"/>
          <do_if value="not $candWhitelisted">
            <set_value name="$candActivityBL" exact="@$candidateSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
            <set_value name="$candTravelBL" exact="@$candidateSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
          </do_if>
          <set_value name="$candBL" exact="$candActivityBL or $candTravelBL"/>
          <do_if value="not $candBL or $candidateSector == $homeSector">
            <set_value name="$escapeSector" exact="$candidateSector"/>
            <break/>
          </do_if>
        </do_if>
      </do_all>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: Moving toward home sector' +
          '\n  Current: ' + @$currentSector.knownname +
          '\n  Home:    ' + @$homeSector.knownname +
          '\n  Target:  ' + @$escapeSector.knownname" chance="100"/>
      </do_if>
      
      <!-- Logbook: escape fallback (rate-limited, respects per-ship logbook setting) -->
      <set_value name="$logEnabled" exact="false"/>
      <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK4Supply' and @this.ship.defaultorder.$logbookentries">
        <set_value name="$logEnabled" exact="true"/>
      </do_if>
      <!-- Subordinates inherit logbook setting from commander -->
      <do_elseif value="@this.ship.defaultorder.id == 'Assist' and (((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply') and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
        <set_value name="$logEnabled" exact="true"/>
      </do_elseif>
      
      <do_if value="$logEnabled">
        <set_value name="$lastEscapeLogbookTime" exact="0"/>
        <do_if value="this.$lastEscapeFallbackLogbookEntryTime?">
          <set_value name="$lastEscapeLogbookTime" exact="this.$lastEscapeFallbackLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastEscapeLogbook" exact="player.age - $lastEscapeLogbookTime"/>
        <do_if value="$timeSinceLastEscapeLogbook ge 300s or $lastEscapeLogbookTime == 0">
          <set_value name="$logbookMessage" exact="'Commander,\n\nI am currently in a blacklisted sector and could not find any trade route that safely moves me out.\n\nEscape fallback activated: moving toward my home sector.\n\nCurrent: ' + @$currentSector.knownname + '\nHome: ' + @$homeSector.knownname + '\nTarget: ' + @$escapeSector.knownname + '\n\nStatus: Escaping blacklist lock\n\nAboard ' + this.ship.knownname"/>
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'general',
            $Title = 'Escape Fallback: ' + this.ship.knownname,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          <set_value name="this.$lastEscapeFallbackLogbookEntryTime" exact="player.age"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Escape fallback logbook entry created'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Create a visible, native navigation order for the player ("Fly and Wait") toward the escape sector.
           Timeout is the post-arrival hold (NOT how long the AI waits â€” the AI resumes immediately because
           of immediate="true" + <resume>). The previous 1s value caused the order to settle within a single
           AI tick after arrival, so the next main_loop pass would re-blacklist and re-fire MoveWait in a
           tight loop. Scale by the planned jump count (one hop minimum) so the ship has a realistic
           settling window before GT re-evaluates. -->
      <set_value name="$escapeTimeout" exact="if $jumppath? and $jumppath.count gt 0 then $jumppath.count * 60s else 60s"/>
      <!-- CRITICAL: Set escape flag RIGHT BEFORE creating order to ensure it's set when ship starts fleeing -->
      <do_if value="global.$GT_Ships?">
        <do_if value="not global.$GT_Ships.{this.ship}?">
          <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
      </do_if>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship=this.ship,
          $pilot=this.ship.pilot,
          $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType='trader'
        ]"/>
      </do_if>
      
      <create_order object="this.ship" id="'MoveWait'" immediate="true">
        <param name="destination" value="[$escapeSector, position.[0,0,0]]"/>
        <param name="timeout" value="$escapeTimeout"/>
        <param name="debugchance" value="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </create_order>
      
      <!-- After moving (or attempting to), retry trading immediately -->
      <resume label="main_loop"/>
      
      <label name="no_trade_retry"/>

      <!-- CRITICAL: Initialize retryCooldown with safe default FIRST to prevent property lookup errors -->
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <!-- IMPORTANT (AI script lifetime): local $vars may not persist across <wait/> yields. -->
      <!-- Persist the computed cooldown time on the order instance for any post-wait logic. -->
      <set_value name="this.$retryCooldown" exact="10s"/>

      <!-- SPECIAL CASE: system busy / home refresh in progress (MD queues are saturated OR a home-sector cache refresh is running)
           â†’ fixed retry, do NOT escalate cooldown.
           Smooth gameplay > throughput: wait longer here to reduce request churn and let the scheduler/queues drain.
           TODO: keep hardcoded for now; consider exposing as tuning later. -->
      <set_value name="$noTradeReason" exact="if this.$lastNoTradeReason? then this.$lastNoTradeReason else ''"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': no_trade_retry entered: reason=\'' + $noTradeReason + '\' player.money=' + (player.money / 100) + ' Cr'" chance="100"/>
      </do_if>
      <do_if value="$noTradeReason == 'busy' or $noTradeReason == 'busy_batch' or $noTradeReason == 'home_refresh' or $noTradeReason == 'insufficient_funds'">
        <set_value name="this.$lastNoTradeReason" exact="''"/>
        <!-- NOTE: Global money cap (global.$GT_MoneyCapActive) is set by the authoritative guard
             when blocking. No per-ship state needed here â€” the global flag stops all ships. -->
        <!-- Fixed retry for special reasons (do NOT use escalating cooldown). -->
        <!-- For home_refresh: shorter wait (3s) to allow cache retry while home refresh populates cache -->
        <!-- For busy/busy_batch: longer wait (8-12s) to let queues drain -->
        <!-- For insufficient_funds: long wait (90-150s) - budget exhausted, no point retrying quickly.
             Jitter prevents thundering herd: ships spread across 60s window instead of all waking simultaneously.
             On wake-up, the early money gate and global money cap prevent futile searches. -->
        <set_value name="this.$retryCooldown" exact="if $noTradeReason == 'home_refresh' then 3s else (if $noTradeReason == 'insufficient_funds' then 120s else 10s)"/>
        <!-- JITTER: Compute per-ship min/max wait for <wait> element.
             insufficient_funds: 90s-150s (Â±25%), busy: 8s-12s (Â±20%), home_refresh: 3s (no jitter, needs responsiveness) -->
        <set_value name="this.$retryWaitMin" exact="if $noTradeReason == 'insufficient_funds' then 90s else (if $noTradeReason == 'home_refresh' then 3s else 8s)"/>
        <set_value name="this.$retryWaitMax" exact="if $noTradeReason == 'insufficient_funds' then 150s else (if $noTradeReason == 'home_refresh' then 3s else 12s)"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': System busy/home refresh/insufficient funds - waiting ' + (this.$retryWaitMin/1s) + '-' + (this.$retryWaitMax/1s) + 's then retrying cache (reason: ' + $noTradeReason + ')'" chance="100"/>
        </do_if>
        
        <!-- Record attempt summary (bounded history) -->
        <do_if value="not global.$GT_NoTradeHistory?">
          <set_value name="global.$GT_NoTradeHistory" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_NoTradeHistory.{this.ship}? or global.$GT_NoTradeHistory.{this.ship} == null or typeof global.$GT_NoTradeHistory.{this.ship} != datatype.list">
          <set_value name="global.$GT_NoTradeHistory.{this.ship}" exact="[]"/>
        </do_if>
        <append_to_list name="global.$GT_NoTradeHistory.{this.ship}" exact="table[
          $Time = player.age,
          $Reason = $noTradeReason,
          $Wait = this.$retryCooldown,
          $Sector = @this.ship.sector.knownname,
          $Home = if @this.$effectiveHome != null then @this.$effectiveHome.knownname else (if @this.ship.defaultorder.$home != null then @this.ship.defaultorder.$home.knownname else ''),
          $MaxDistance = if this.$effectiveMaxDistance? then this.$effectiveMaxDistance else null
        ]"/>
        <!-- Keep last 12 entries max -->
        <do_if value="global.$GT_NoTradeHistory.{this.ship}.count gt 12">
          <set_value name="$old" exact="global.$GT_NoTradeHistory.{this.ship}.{1}"/>
          <remove_from_list name="global.$GT_NoTradeHistory.{this.ship}" exact="$old"/>
        </do_if>
        
        <!-- Logbook entry for insufficient funds (throttled: once per 5 minutes per ship) -->
        <do_if value="$noTradeReason == 'insufficient_funds' and $gt_logbookentries">
          <set_value name="$lastInsufficientFundsLogbook" exact="0"/>
          <do_if value="this.$lastInsufficientFundsLogbookTime?">
            <set_value name="$lastInsufficientFundsLogbook" exact="this.$lastInsufficientFundsLogbookTime"/>
          </do_if>
          <set_value name="$timeSinceLastInsufficientFundsLogbook" exact="player.age - $lastInsufficientFundsLogbook"/>
          <do_if value="$timeSinceLastInsufficientFundsLogbook ge 300s or $lastInsufficientFundsLogbook == 0">
            <set_value name="$playerMoneyDisplay" exact="player.money / 100"/>
            <set_value name="$thresholdDisplay" exact="if this.$minPlayerMoney? then this.$minPlayerMoney else 1000"/>
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrading operations paused â€” insufficient funds.\n\nPlayer account: ' + $playerMoneyDisplay + ' Cr\nMinimum required: ' + $thresholdDisplay + ' Cr\n\nI will resume trading automatically once funds are above the threshold.\n\nYou can adjust the minimum in:\nGalaxyTrader Settings &gt; Fleet &gt; Min Player Money\n\nStanding by,\nAboard ' + this.ship.knownname"/>
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'alerts',
              $Title = 'Insufficient Funds: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
            <set_value name="this.$lastInsufficientFundsLogbookTime" exact="player.age"/>
          </do_if>
        </do_if>

        <set_command command="command.wait"/>
        <set_command_action commandaction="commandaction.standingby"/>
        <!-- JITTER: Use per-ship min/max to spread retries across a time window (prevents thundering herd).
             For insufficient_funds: 90s-150s window. For busy: 8s-12s. For home_refresh: fixed 3s. -->
        <wait min="if @this.$retryWaitMin != null then @this.$retryWaitMin else 10s" max="if @this.$retryWaitMax != null then @this.$retryWaitMax else 10s"/>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- CARGO DISPOSAL: Track cargo disposal failures separately -->
      <set_value name="$isCargoDisposal" exact="false"/>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
        <set_value name="$isCargoDisposal" exact="true"/>
        <!-- Initialize cargo disposal failure counter if not exists -->
        <do_if value="not this.$cargoDisposalFailed?">
          <set_value name="this.$cargoDisposalFailed" exact="0"/>
        </do_if>
        <!-- Increment cargo disposal failure counter -->
        <set_value name="this.$cargoDisposalFailed" exact="this.$cargoDisposalFailed + 1"/>
      </do_if>
      <do_else>
        <!-- Normal trade search failure - increment normal counter -->
        <!-- Increment failure counter -->
        <set_value name="this.$searchFailed" exact="this.$searchFailed + 1"/>
      </do_else>
      
      <!-- Calculate escalating wait time: ~10s, ~20s, ~30s, ~40s, ~50s, ~60s (max) -->
      <!-- Use cargo disposal counter if this is cargo disposal, otherwise use normal counter -->
      <set_value name="$failureCount" exact="if $isCargoDisposal then this.$cargoDisposalFailed else this.$searchFailed"/>
      <!-- Escalating cooldown (cap 60s). This is also required for "no trade found" logbook notifications (they trigger at 60s). -->
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <set_value name="this.$retryCooldown" exact="([$failureCount, 6].min) * 10s"/>
      <!-- JITTER: Â±20% around the base cooldown to prevent ships at the same escalation level
           from all retrying in the same frame (thundering herd prevention).
           Example: failureCount=3 â†’ base=30s â†’ min=24s, max=36s -->
      <set_value name="this.$retryCooldownMin" exact="[this.$retryCooldown * 0.8, 5s].max"/>
      <set_value name="this.$retryCooldownMax" exact="this.$retryCooldown * 1.2"/>
      
      <!-- Record attempt summary (bounded history).
           We capture the most recent MD rejection statistics (if available) so the 60s logbook report can show a timeline. -->
      <do_if value="not global.$GT_NoTradeHistory?">
        <set_value name="global.$GT_NoTradeHistory" exact="table[]"/>
      </do_if>
      <do_if value="not global.$GT_NoTradeHistory.{this.ship}? or global.$GT_NoTradeHistory.{this.ship} == null or typeof global.$GT_NoTradeHistory.{this.ship} != datatype.list">
        <set_value name="global.$GT_NoTradeHistory.{this.ship}" exact="[]"/>
      </do_if>
      <set_value name="$lastRejectionStats" exact="null"/>
      <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.$LastRejectionStats? and global.$GT_SearchResult.$LastRejectionStats.{this.ship}?">
        <set_value name="$lastRejectionStats" exact="@global.$GT_SearchResult.$LastRejectionStats.{this.ship}"/>
      </do_if>
      <set_value name="$rsTotal" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Total != null then @$lastRejectionStats.$Total else null"/>
      <set_value name="$rsDock" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Docking != null then @$lastRejectionStats.$Docking else null"/>
      <set_value name="$rsProfit" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Profit != null then @$lastRejectionStats.$Profit else null"/>
      <set_value name="$rsAmount" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Amount != null then @$lastRejectionStats.$Amount else null"/>
      <set_value name="$rsBlacklist" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Blacklist != null then @$lastRejectionStats.$Blacklist else null"/>
      <set_value name="$rsSector" exact="if $lastRejectionStats != null and @$lastRejectionStats.$SectorName != null then @$lastRejectionStats.$SectorName else @this.ship.sector.knownname"/>
      <set_value name="$rsMaxDist" exact="if $lastRejectionStats != null and @$lastRejectionStats.$MaxDistance != null then @$lastRejectionStats.$MaxDistance else null"/>
      <set_value name="$rsMinProfit" exact="if $lastRejectionStats != null and @$lastRejectionStats.$MinAbsoluteProfit != null then @$lastRejectionStats.$MinAbsoluteProfit else null"/>
      <set_value name="$rsDistance" exact="0"/>
      <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{this.ship}? and global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance?">
        <set_value name="$rsDistance" exact="global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance"/>
      </do_if>
      <append_to_list name="global.$GT_NoTradeHistory.{this.ship}" exact="table[
        $Time = player.age,
        $Reason = $noTradeReason,
        $Wait = this.$retryCooldown,
        $Sector = $rsSector,
        $Home = if @this.$effectiveHome != null then @this.$effectiveHome.knownname else (if @this.ship.defaultorder.$home != null then @this.ship.defaultorder.$home.knownname else ''),
        $MaxDistance = $rsMaxDist,
        $MinAbsoluteProfit = $rsMinProfit,
        $Total = $rsTotal,
        $Docking = $rsDock,
        $Profit = $rsProfit,
        $Amount = $rsAmount,
        $Blacklist = $rsBlacklist,
        $Distance = $rsDistance
      ]"/>
      <!-- Keep last 12 entries max -->
      <do_if value="global.$GT_NoTradeHistory.{this.ship}.count gt 12">
        <set_value name="$old" exact="global.$GT_NoTradeHistory.{this.ship}.{1}"/>
        <remove_from_list name="global.$GT_NoTradeHistory.{this.ship}" exact="$old"/>
      </do_if>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No ' + (if $isCargoDisposal then 'cargo buyer' else 'profitable trades') + ' found (attempt ' + $failureCount + ') - waiting ' + (this.$retryCooldown/1s) + 's before retry'" chance="100"/>
      </do_if>
      
      <!-- Set ship to waiting state -->
      <set_command command="command.wait"/>
      <set_command_action commandaction="commandaction.standingby"/>
      
      <!-- Persist $isCargoDisposal and $noTradeReason before wait (local variables lost across wait yields) -->
      <set_value name="this.$isCargoDisposal" exact="$isCargoDisposal"/>
      <set_value name="this.$noTradeReason" exact="$noTradeReason"/>
      
      <!-- Wait with escalating delay -->
      <!-- Track if wait was interrupted (so we don't write logbook if interrupted) -->
      <set_value name="$waitInterrupted" exact="false"/>
      <set_value name="$tradeFoundDuringWait" exact="false"/>
      <set_value name="this.$waitInterrupted" exact="$waitInterrupted"/>
      <set_value name="this.$tradeFoundDuringWait" exact="$tradeFoundDuringWait"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Entering wait for ' + (this.$retryCooldownMin/1s) + '-' + (this.$retryCooldownMax/1s) + 's at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- JITTER: Use min/max range (Â±20%) to spread ships across a time window instead of all waking together -->
      <wait min="if @this.$retryCooldownMin != null then @this.$retryCooldownMin else 8s" max="if @this.$retryCooldownMax != null then @this.$retryCooldownMax else 12s" comment="Jittered escalating wait with interrupt">
        <interrupt>
          <conditions>
            <!-- Only GT_Trade_Found should interrupt retry wait -->
            <!-- GT_No_Trade_Found signals during retry wait are ignored to preserve escalating cooldown -->
            <event_object_signalled object="this.ship" param="'GT_Trade_Found'" comment="MD found a trade"/>
          </conditions>
          <actions>
            <!-- Capture signal payload before resuming so trade_found gets the correct source/list -->
            <set_value name="$intSignalData" exact="event.param2"/>
            <set_value name="$intSignalTradeList" exact="[]"/>
            <set_value name="$intSignalSearchMethod" exact="''"/>
            <do_if value="$intSignalData? and $intSignalData != null">
              <set_value name="$intSignalTradeList" exact="@$intSignalData.$TradeList"/>
              <set_value name="$intSignalSearchMethod" exact="@$intSignalData.$SearchMethod"/>
            </do_if>
            <set_value name="this.$tradeListFromSignal" exact="$intSignalTradeList"/>
            <set_value name="this.$searchMethodFromSignal" exact="if $intSignalSearchMethod != null and $intSignalSearchMethod != '' then $intSignalSearchMethod else ''"/>
            <set_value name="this.$waitInterrupted" exact="true"/>
            <set_value name="this.$tradeFoundDuringWait" exact="true"/>
            <set_value name="$waitInterrupted" exact="true"/>
            <set_value name="$tradeFoundDuringWait" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade found during retry wait - stored ' + (if $intSignalTradeList != null then $intSignalTradeList.count else 0) + ' trades from interrupt payload'" chance="100"/>
            </do_if>
            <!-- Resume to trade_found label to process the trade -->
            <resume label="trade_found"/>
          </actions>
        </interrupt>
      </wait>
      <!-- Restore variables after wait (they may have been lost across yield) -->
      <set_value name="$waitInterrupted" exact="this.$waitInterrupted"/>
      <set_value name="$tradeFoundDuringWait" exact="this.$tradeFoundDuringWait"/>
      <set_value name="$isCargoDisposal" exact="this.$isCargoDisposal"/>
      <set_value name="$noTradeReason" exact="if this.$noTradeReason? then this.$noTradeReason else ''"/>
      <!-- Recompute $failureCount from persisted instance variables (local was lost across wait) -->
      <set_value name="$failureCount" exact="if $isCargoDisposal then (if this.$cargoDisposalFailed? then this.$cargoDisposalFailed else 0) else (if this.$searchFailed? then this.$searchFailed else 0)"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Wait completed at game time ' + player.age + ' - continuing retry logic (trade found: ' + this.$tradeFoundDuringWait + ')'" chance="100"/>
      </do_if>
      
      <!-- Write logbook entry only if we've reached max wait (60s) AND wait completed naturally (not interrupted by trade found) -->
      <!-- Also check if we've already written a logbook entry recently to prevent duplicates -->
      <set_value name="$shouldWriteLogbook" exact="false"/>
      <set_value name="$shouldWriteCargoDisposalLogbook" exact="false"/>
      
      <!-- CARGO DISPOSAL: Separate logbook entry for cargo disposal failures -->
      <do_if value="this.$isCargoDisposal and this.$retryCooldown == 60s and not this.$tradeFoundDuringWait">
        <!-- Check if we've already written a cargo disposal failure logbook entry in the last 5 minutes (300s) -->
        <set_value name="$lastCargoDisposalLogbookTime" exact="0"/>
        <do_if value="this.$lastCargoDisposalLogbookEntryTime?">
          <set_value name="$lastCargoDisposalLogbookTime" exact="this.$lastCargoDisposalLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastCargoDisposalLogbook" exact="player.age - $lastCargoDisposalLogbookTime"/>
        <do_if value="$timeSinceLastCargoDisposalLogbook ge 300s or $lastCargoDisposalLogbookTime == 0">
          <!-- Haven't written cargo disposal failure logbook recently (or never) - OK to write -->
          <set_value name="$shouldWriteCargoDisposalLogbook" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- Determine if this is a "critical persistent" reason that should trigger logbook earlier -->
      <!-- Critical reasons: ship is fundamentally unable to trade, not just temporarily busy -->
      <set_value name="$isCriticalReason" exact="$noTradeReason == 'blacklist' or $noTradeReason == 'all_rejected' or $noTradeReason == 'trade_rules_violation'"/>
      
      <!-- Normal trade search logbook entry -->
      <!-- Trigger conditions:
           - Standard: 60s cooldown reached (6th failure)
           - Critical: 2nd consecutive failure with a persistent reason (blacklist/all_rejected/trade_rules) 
           Either way, wait must have completed naturally (not interrupted by trade found) -->
      <do_if value="not $isCargoDisposal and not $tradeFoundDuringWait and (this.$retryCooldown == 60s or ($isCriticalReason and $failureCount ge 2))">
        <!-- Check if we've already written a logbook entry in the last 5 minutes (300s) -->
        <set_value name="$lastLogbookTime" exact="0"/>
        <do_if value="this.$lastLogbookEntryTime?">
          <set_value name="$lastLogbookTime" exact="this.$lastLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastLogbook" exact="player.age - $lastLogbookTime"/>
        <do_if value="$timeSinceLastLogbook ge 300s or $lastLogbookTime == 0">
          <!-- Haven't written logbook recently (or never) - OK to write -->
          <set_value name="$shouldWriteLogbook" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- CARGO DISPOSAL: Write separate failure message for cargo disposal -->
      <do_if value="$shouldWriteCargoDisposalLogbook">
        <!-- Check if logbook enabled -->
        <set_value name="$logEnabled" exact="false"/>
        <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK4Supply' and @this.ship.defaultorder.$logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        <!-- Subordinates inherit logbook setting from commander -->
        <do_elseif value="@this.ship.defaultorder.id == 'Assist' and (((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply') and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
          <set_value name="$logEnabled" exact="true"/>
        </do_elseif>
        
        <do_if value="$logEnabled">
          <!-- Get cargo info for logbook message -->
          <set_value name="$cargoList" exact="this.ship.cargo.list"/>
          <set_value name="$cargoTypes" exact="[]"/>
          <do_all exact="$cargoList.count" counter="$i">
            <set_value name="$ware" exact="$cargoList.{$i}"/>
            <set_value name="$amount" exact="this.ship.cargo.{$ware}.count"/>
            <append_to_list name="$cargoTypes" exact="@$ware.name + ' x' + $amount"/>
          </do_all>
          <set_value name="$cargoDescription" exact="if $cargoTypes.count gt 0 then $cargoTypes.{1} + (if $cargoTypes.count gt 1 then ', ' + $cargoTypes.{2} else '') + (if $cargoTypes.count gt 2 then ', ...' else '') else 'Unknown'"/>
          
          <!-- Write cargo disposal failure logbook entry -->
          <set_value name="$logbookMessage" exact="'Commander,\n\nI have been unable to find a buyer for my cargo after multiple attempts. My cargo hold contains: ' + $cargoDescription + '\n\nI have tried ' + $failureCount + ' times but cannot locate a suitable buyer within my trading range. This may be due to:\n- No stations buying these wares nearby\n- All potential buyers are blacklisted\n- Docking restrictions at available stations\n\nI will continue waiting and retrying periodically. You may want to manually assign a sell order or adjust my trading parameters.\n\nStatus: Waiting for buyer opportunity\n\nWith patience,\nAboard ' + this.ship.knownname"/>
          
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'alerts',
            $Title = 'Cargo Disposal Failed: ' + this.ship.knownname,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          
          <!-- Update last cargo disposal logbook entry time -->
          <set_value name="this.$lastCargoDisposalLogbookEntryTime" exact="player.age"/>
        </do_if>
      </do_if>
      
      <do_if value="$shouldWriteLogbook">
        <!-- Check if logbook enabled -->
        <set_value name="$logEnabled" exact="false"/>
        <!-- Use the already-computed effective logbook flag (matches other GT logbook messages). -->
        <do_if value="$gt_logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        
        <do_if value="$logEnabled">
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               COMMON DATA RETRIEVAL: Gather rejection stats, sector info, etc.
               Used by ALL logbook message templates below.
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          <set_value name="$lastRejectionStats" exact="null"/>
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.$LastRejectionStats? and global.$GT_SearchResult.$LastRejectionStats != null and global.$GT_SearchResult.$LastRejectionStats.{this.ship}?">
            <set_value name="$lastRejectionStats" exact="global.$GT_SearchResult.$LastRejectionStats.{this.ship}"/>
          </do_if>
          <set_value name="$totalRejected" exact="0"/>
          <set_value name="$tradesRejectedDocking" exact="0"/>
          <set_value name="$tradesRejectedProfit" exact="0"/>
          <set_value name="$tradesRejectedAmount" exact="0"/>
          <set_value name="$tradesRejectedBlacklist" exact="0"/>
          <set_value name="$sectorName" exact="''"/>
          <set_value name="$maxDistance" exact="10"/>
          <set_value name="$minAbsoluteProfit" exact="100"/>
          
          <do_if value="$lastRejectionStats != null">
            <set_value name="$tradesRejectedDockingTemp" exact="@$lastRejectionStats.$Docking"/>
            <set_value name="$tradesRejectedDocking" exact="if $tradesRejectedDockingTemp? and $tradesRejectedDockingTemp != null then $tradesRejectedDockingTemp else 0"/>
            <set_value name="$tradesRejectedProfitTemp" exact="@$lastRejectionStats.$Profit"/>
            <set_value name="$tradesRejectedProfit" exact="if $tradesRejectedProfitTemp? and $tradesRejectedProfitTemp != null then $tradesRejectedProfitTemp else 0"/>
            <set_value name="$tradesRejectedAmountTemp" exact="@$lastRejectionStats.$Amount"/>
            <set_value name="$tradesRejectedAmount" exact="if $tradesRejectedAmountTemp? and $tradesRejectedAmountTemp != null then $tradesRejectedAmountTemp else 0"/>
            <set_value name="$tradesRejectedBlacklistTemp" exact="@$lastRejectionStats.$Blacklist"/>
            <set_value name="$tradesRejectedBlacklist" exact="if $tradesRejectedBlacklistTemp? and $tradesRejectedBlacklistTemp != null then $tradesRejectedBlacklistTemp else 0"/>
            <set_value name="$totalRejectedTemp" exact="@$lastRejectionStats.$Total"/>
            <set_value name="$totalRejectedFromStats" exact="if $totalRejectedTemp? and $totalRejectedTemp != null then $totalRejectedTemp else 0"/>
            <set_value name="$sumOfRejections" exact="$tradesRejectedDocking + $tradesRejectedProfit + $tradesRejectedAmount + $tradesRejectedBlacklist"/>
            <set_value name="$totalRejected" exact="if $totalRejectedFromStats gt $sumOfRejections then $totalRejectedFromStats else $sumOfRejections"/>
            
            <set_value name="$sectorNameTemp" exact="@$lastRejectionStats.$SectorName"/>
            <do_if value="$sectorNameTemp? and $sectorNameTemp != null and $sectorNameTemp != ''">
              <set_value name="$sectorName" exact="$sectorNameTemp"/>
            </do_if>
            <do_else>
              <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
            </do_else>
            <set_value name="$maxDistanceTemp" exact="@$lastRejectionStats.$MaxDistance"/>
            <do_if value="$maxDistanceTemp? and $maxDistanceTemp != null">
              <set_value name="$maxDistance" exact="$maxDistanceTemp"/>
            </do_if>
            <set_value name="$minAbsoluteProfitTemp" exact="@$lastRejectionStats.$MinAbsoluteProfit"/>
            <do_if value="$minAbsoluteProfitTemp? and $minAbsoluteProfitTemp != null">
              <set_value name="$minAbsoluteProfit" exact="$minAbsoluteProfitTemp"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
          </do_else>
          
          <!-- Final safety check: Ensure sector name is not null -->
          <do_if value="not $sectorName? or $sectorName == null or $sectorName == ''">
            <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
            <do_if value="not $sectorName? or $sectorName == null or $sectorName == ''">
              <set_value name="$sectorName" exact="'Unknown Sector'"/>
            </do_if>
          </do_if>
          
          <set_value name="$hasRejectionStats" exact="false"/>
          <do_if value="$lastRejectionStats != null">
            <do_if value="($lastRejectionStats.$Total? and $lastRejectionStats.$Total != null) or ($lastRejectionStats.$Profit? and $lastRejectionStats.$Profit != null) or ($lastRejectionStats.$Docking? and $lastRejectionStats.$Docking != null) or ($lastRejectionStats.$Amount? and $lastRejectionStats.$Amount != null) or ($lastRejectionStats.$Blacklist? and $lastRejectionStats.$Blacklist != null)">
              <set_value name="$hasRejectionStats" exact="true"/>
            </do_if>
          </do_if>
          <set_value name="$totalEvaluated" exact="0"/>
          <do_if value="$hasRejectionStats and $lastRejectionStats.$Total? and $lastRejectionStats.$Total != null">
            <set_value name="$totalEvaluated" exact="$lastRejectionStats.$Total"/>
          </do_if>
          <set_value name="$tradesRejectedDistance" exact="0"/>
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{this.ship}? and global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance?">
            <set_value name="$tradesRejectedDistance" exact="global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance"/>
          </do_if>
          
          <!-- Log the logbook message data before generating -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': LOGBOOK (reason=' + $noTradeReason + ', attempt=' + $failureCount + ', critical=' + $isCriticalReason + ')'" chance="100"/>
          </do_if>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               LOGBOOK TITLE â€” reason-specific for clarity in the logbook list
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          <set_value name="$logbookTitle" exact="'No Trades: ' + this.ship.knownname"/>
          <do_if value="$noTradeReason == 'blacklist'">
            <set_value name="$logbookTitle" exact="'Routes Blocked: ' + this.ship.knownname"/>
          </do_if>
          <do_elseif value="$noTradeReason == 'all_rejected'">
            <set_value name="$logbookTitle" exact="'All Trades Rejected: ' + this.ship.knownname"/>
          </do_elseif>
          <do_elseif value="$noTradeReason == 'trade_rules_violation'">
            <set_value name="$logbookTitle" exact="'Trade Rules Violation: ' + this.ship.knownname"/>
          </do_elseif>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               LOGBOOK MESSAGE â€” reason-specific templates
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          
          <!-- â”€â”€â”€ BLACKLIST: All viable routes pass through blocked sectors â”€â”€â”€ -->
          <do_if value="$noTradeReason == 'blacklist'">
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrading blocked â€” all viable routes pass through blacklisted sectors.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'All trade routes within range are blocked by threat intelligence or blacklist settings. ' +
              'The ship cannot reach any profitable stations safely.\n\n' +
              'Suggestions:\n' +
              '- Review blacklist settings (GalaxyTrader Settings &gt; Trade)\n' +
              '- Increase trading range to find routes around blocked sectors\n' +
              '- Relocate this ship to a sector with better connectivity\n' +
              '- Check if threat levels have changed recently'"/>
          </do_if>
          
          <!-- â”€â”€â”€ ALL_REJECTED: Every trade candidate was filtered out â”€â”€â”€ -->
          <do_elseif value="$noTradeReason == 'all_rejected'">
            <!-- Display strings -->
            <set_value name="$evalDisplay" exact="if $hasRejectionStats then $totalEvaluated else 'â€”'"/>
            <set_value name="$profitDisplay" exact="if $hasRejectionStats then $tradesRejectedProfit else 'â€”'"/>
            <set_value name="$dockDisplay" exact="if $hasRejectionStats then $tradesRejectedDocking else 'â€”'"/>
            <set_value name="$amountDisplay" exact="if $hasRejectionStats then $tradesRejectedAmount else 'â€”'"/>
            <set_value name="$distDisplay" exact="if $hasRejectionStats then $tradesRejectedDistance else 'â€”'"/>
            <set_value name="$blDisplay" exact="if $hasRejectionStats then $tradesRejectedBlacklist else 'â€”'"/>
            
            <set_value name="$logbookMessage" exact="'Commander,\n\nAll trade candidates were rejected after evaluation.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Min profit: ' + ($minAbsoluteProfit/100) + ' Cr\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'Rejection breakdown (evaluated ' + $evalDisplay + '):\n' +
              '  Profit too low: ' + $profitDisplay + '\n' +
              '  Docking restricted: ' + $dockDisplay + '\n' +
              '  Amount too small: ' + $amountDisplay + '\n' +
              '  Out of range: ' + $distDisplay + '\n' +
              '  Blacklisted/path blocked: ' + $blDisplay + '\n'"/>
            
            <!-- Add targeted hint based on dominant rejection reason -->
            <set_value name="$hint" exact="''"/>
            <do_if value="not $hasRejectionStats or $totalEvaluated == 0">
              <set_value name="$hint" exact="'No offers were evaluated. Check if markets are discovered and unblocked.'"/>
            </do_if>
            <do_elseif value="$tradesRejectedProfit gt ($tradesRejectedDocking + $tradesRejectedBlacklist + $tradesRejectedDistance)">
              <set_value name="$hint" exact="'Most candidates failed profit checks. Lower min profit/ROI or increase range.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDocking gt 0 and $tradesRejectedDocking ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates failed docking checks. Check docking restrictions at stations.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedBlacklist gt 0 and $tradesRejectedBlacklist ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Blacklist restrictions filtered many routes. Review threat settings.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDistance gt 0 and $tradesRejectedDistance ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates were out of range. Increase max distance if appropriate.'"/>
            </do_elseif>
            <do_if value="$hint != ''">
              <set_value name="$logbookMessage" exact="$logbookMessage + '\nHint: ' + $hint"/>
            </do_if>
          </do_elseif>
          
          <!-- â”€â”€â”€ TRADE_RULES_VIOLATION: Station trade rules prevent trading â”€â”€â”€ -->
          <do_elseif value="$noTradeReason == 'trade_rules_violation'">
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrade rules violation â€” target stations reject trades from this ship.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'This may be caused by:\n' +
              '- Build storage restrictions (station is a build storage)\n' +
              '- Carrier/auxiliary station trading restrictions\n' +
              '- Trade rule changes after search started\n' +
              '- Station ownership or faction restrictions\n\n' +
              'Suggestions:\n' +
              '- Check station trade rule settings\n' +
              '- Review IgnoreCarrierAux / IgnoreBuildStorage in GT Settings\n' +
              '- Increase trading range to find alternative stations'"/>
          </do_elseif>
          
          <!-- â”€â”€â”€ GENERIC: Standard "no profitable trades" with full diagnostics â”€â”€â”€ -->
          <do_else>
            <!-- Display strings (show 'â€”' when stats were not recorded) -->
            <set_value name="$evalDisplay" exact="if $hasRejectionStats then $totalEvaluated else 'â€”'"/>
            <set_value name="$profitDisplay" exact="if $hasRejectionStats then $tradesRejectedProfit else 'â€”'"/>
            <set_value name="$dockDisplay" exact="if $hasRejectionStats then $tradesRejectedDocking else 'â€”'"/>
            <set_value name="$amountDisplay" exact="if $hasRejectionStats then $tradesRejectedAmount else 'â€”'"/>
            <set_value name="$distDisplay" exact="if $hasRejectionStats then $tradesRejectedDistance else 'â€”'"/>
            <set_value name="$blDisplay" exact="if $hasRejectionStats then $tradesRejectedBlacklist else 'â€”'"/>
            
            <!-- Friendly reason string for the generic header -->
            <set_value name="$reasonFriendly" exact="
              if $noTradeReason == 'reserved' then 'all trades reserved by fleet'
              else if $noTradeReason == 'offers_expired' then 'trade offers expired during validation'
              else if $noTradeReason == 'no_trade' then 'no profitable trades found'
              else if $noTradeReason == 'invalid_trade' then 'trade data became invalid'
              else 'no profitable trades found'"/>
            
            <set_value name="$logbookMessage" exact="'Commander,\n\nNo trades available â€” ' + $reasonFriendly + '.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Min profit: ' + ($minAbsoluteProfit/100) + ' Cr\n' +
              'Attempts: ' + $failureCount + ' (cooldown reached ' + (this.$retryCooldown/1s) + 's)\n\n' +
              'Latest rejection stats (evaluated ' + $evalDisplay + '):\n' +
              '  Profit too low: ' + $profitDisplay + '\n' +
              '  Docking restricted: ' + $dockDisplay + '\n' +
              '  Amount too small: ' + $amountDisplay + '\n' +
              '  Out of range: ' + $distDisplay + '\n' +
              '  Blacklisted/path blocked: ' + $blDisplay +
              (if not $hasRejectionStats then '\n  (no stats recorded for this attempt)' else '') + '\n\n' +
              'Recent attempts (newest first):'"/>

            <!-- Append up to last 4 history rows (most recent first) -->
            <set_value name="$hist" exact="null"/>
            <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
              <set_value name="$hist" exact="global.$GT_NoTradeHistory.{this.ship}"/>
            </do_if>
            <set_value name="$histCount" exact="if $hist != null then $hist.count else 0"/>
            <set_value name="$linesToShow" exact="[$histCount, 4].min"/>
            <do_all exact="$linesToShow" counter="$li">
              <!-- Reverse index: last entry is most recent -->
              <set_value name="$idx" exact="$histCount - ($li - 1)"/>
              <set_value name="$h" exact="$hist.{$idx}"/>
              
              <!-- Age formatting: mm:ss ago -->
              <set_value name="$ageSec" exact="0"/>
              <do_if value="$h.$Time? and $h.$Time != null">
                <set_value name="$ageSec" exact="((player.age - $h.$Time) / 1s)i"/>
              </do_if>
              <do_if value="$ageSec lt 0">
                <set_value name="$ageSec" exact="0"/>
              </do_if>
              <set_value name="$ageMin" exact="($ageSec / 60)i"/>
              <set_value name="$ageRem" exact="$ageSec - ($ageMin * 60)"/>
              <set_value name="$ageRemStr" exact="if $ageRem lt 10 then '0' + $ageRem else $ageRem"/>
              <set_value name="$ageStr" exact="$ageMin + ':' + $ageRemStr + ' ago'"/>
              
              <!-- Reason (friendly) -->
              <set_value name="$rRaw" exact="if $h.$Reason? and $h.$Reason != null and $h.$Reason != '' then $h.$Reason else 'none'"/>
              <set_value name="$r" exact="
                if $rRaw == 'busy' then 'busy'
                else if $rRaw == 'busy_batch' then 'busy (batch)'
                else if $rRaw == 'home_refresh' then 'home refresh'
                else if $rRaw == 'reserved' then 'reserved (fleet)'
                else if $rRaw == 'blacklist' then 'BLACKLISTED'
                else if $rRaw == 'all_rejected' then 'all rejected'
                else if $rRaw == 'trade_rules_violation' then 'trade rules'
                else if $rRaw == 'offers_expired' then 'offers expired'
                else if $rRaw == 'insufficient_funds' then 'low funds'
                else if $rRaw == 'invalid_trade' then 'invalid trade'
                else if $rRaw == 'no_trade' then 'no trade'
                else if $rRaw == 'no_cargo' then 'no cargo'
                else if $rRaw == 'no_gt_order' then 'no GT order'
                else if $rRaw == 'forced_sell_failed' then 'sell failed'
                else if $rRaw == 'no_training_stations' then 'no training'
                else $rRaw"/>
              
              <!-- Build compact rejection summary -->
              <set_value name="$p" exact="if $h.$Profit? and $h.$Profit != null then $h.$Profit else 0"/>
              <set_value name="$d" exact="if $h.$Docking? and $h.$Docking != null then $h.$Docking else 0"/>
              <set_value name="$a" exact="if $h.$Amount? and $h.$Amount != null then $h.$Amount else 0"/>
              <set_value name="$bl" exact="if $h.$Blacklist? and $h.$Blacklist != null then $h.$Blacklist else 0"/>
              <set_value name="$dist" exact="if $h.$Distance? and $h.$Distance != null then $h.$Distance else 0"/>
              <set_value name="$w" exact="if $h.$Wait? and $h.$Wait != null then (($h.$Wait / 1s)i) else 0"/>
              
              <set_value name="$rej" exact="''"/>
              <do_if value="$p gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'profit ' + $p"/></do_if>
              <do_if value="$d gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'dock ' + $d"/></do_if>
              <do_if value="$a gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'amount ' + $a"/></do_if>
              <do_if value="$dist gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'dist ' + $dist"/></do_if>
              <do_if value="$bl gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'blacklist ' + $bl"/></do_if>
              <do_if value="$rej == ''"><set_value name="$rej" exact="'â€”'"/></do_if>
              
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n  ' + $ageStr + ' | ' + $r + ' | rej: ' + $rej"/>
            </do_all>

            <!-- Quick hints (bounded) -->
            <set_value name="$hint" exact="''"/>
            <do_if value="not $hasRejectionStats">
              <set_value name="$hint" exact="'No rejection stats were recorded yet (likely no evaluation completed for this ship).'" />
            </do_if>
            <do_elseif value="$totalEvaluated == 0">
              <set_value name="$hint" exact="'No offers were evaluated. Consider increasing range or checking if markets are visible/unblocked.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedProfit gt ($tradesRejectedDocking + $tradesRejectedBlacklist + $tradesRejectedDistance)">
              <set_value name="$hint" exact="'Most candidates failed profit checks. Lower min profit/ROI or increase range.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDocking gt 0 and $tradesRejectedDocking ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates failed docking checks. Check docking restrictions at stations.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedBlacklist gt 0">
              <set_value name="$hint" exact="'Blacklist/path restrictions filtered many routes. Review blacklists/threat settings.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDistance gt 0">
              <set_value name="$hint" exact="'Many candidates were out of range. Increase max distance (buy/sell) if appropriate.'"/>
            </do_elseif>
            <do_if value="$hint != ''">
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n\nHint: ' + $hint"/>
            </do_if>
          </do_else>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               SEND LOGBOOK ENTRY (common for all reason-specific templates)
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          
          <!-- Dump the final logbook message to DebugLog for diagnosis/copy-paste.
               Rate-limited by the existing escalation + 5min per-ship logbook cooldown. -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-LogbookDump] (' + this.ship.idcode + ') reason=' + $noTradeReason + ':\n' + $logbookMessage" chance="100"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'tips',
            $Title = $logbookTitle,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          
          <!-- Log that logbook entry was created -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Logbook entry created (reason=' + $noTradeReason + ', title=' + $logbookTitle + ')'" chance="100"/>
          </do_if>
          
          <!-- Mark that we've written a logbook entry now -->
          <set_value name="this.$lastLogbookEntryTime" exact="player.age"/>
        </do_if>
      </do_if>
      
      <!-- Reset command state and resume search -->
      <do_if value="this.$effectiveIdleParking and not $isCargoDisposal and not $tradeFoundDuringWait and $failureCount ge 6 and this.ship.cargo.count == 0">
        <set_value name="$gtIdleHome" exact="if this.$effectiveHome? and this.$effectiveHome != null and this.$effectiveHome.exists then this.$effectiveHome else null"/>
        <do_if value="$gtIdleHome? and $gtIdleHome != null">
          <run_script name="'lib.gt.idlepark'">
            <param name="handoffMode" value="'trigger'"/>
            <param name="handoffShip" value="this.ship"/>
            <param name="home" value="$gtIdleHome"/>
            <param name="debugchance" value="this.$debugchance"/>
          </run_script>
        </do_if>
      </do_if>
      <set_command command="command.searchtrades"/>
      <set_command_action commandaction="commandaction.searchingtrades"/>
      
      <!-- Resume main trading loop -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resuming main_loop label'" chance="100"/>
      </do_if>
      <resume label="main_loop"/>
      
      <!-- ========================================================================= -->
      <!-- CARGO SAFETY HANDLERS (In-Parallel Monitoring)                           -->
      <!-- These run in parallel with main trading loop via interrupt-based waits   -->
      <!-- ========================================================================= -->
      
      <!-- ========================================================================= -->
      <!-- DEAD CODE REMOVED: Emergency/Alternative Cargo & Threat Handlers         -->
      <!-- These complex systems were replaced with simple inline cargo check        -->
      <!-- Current implementation: Cargo check at line ~844 sends GT_Find_Sell      -->
      <!-- Threat handler now in interrupt section at lines ~917-941                -->
      <!-- ========================================================================= -->
      
      <!-- ========================================= -->
      <!-- WORK UNIT PROCESSING                      -->
      <!-- ========================================= -->
      
      <!-- Process cache search work unit -->
      <label name="process_cache_workunit"/>
      
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': STARTING cache_search work unit processing'" chance="100"/>
      
      <!-- Extract parameters -->
      <set_value name="$homeSector" exact="@$workUnit.$HomeSector"/>
      <set_value name="$maxDistance" exact="@$workUnit.$MaxDistance"/>
      <set_value name="$minROI" exact="0"/>
      <set_value name="$minAbsoluteProfit" exact="0"/>
      <set_value name="$wareBasket" exact="if $workUnit.$WareBasket? then $workUnit.$WareBasket else $warebasket"/>
      <set_value name="$ignoreBuildStorage" exact="if $workUnit.$IgnoreBuildStorage? then $workUnit.$IgnoreBuildStorage else false"/>
      <set_value name="$ignoreCarrierAux" exact="if $workUnit.$IgnoreCarrierAux? then $workUnit.$IgnoreCarrierAux else false"/>
      
      <!-- Get ship settings for filtering -->
      <!-- Use safe access with defaults in case effective variables aren't initialized in this code path -->
      <set_value name="$allowIllegal" exact="if $workUnit.$AllowIllegal? then $workUnit.$AllowIllegal else (if $effectiveAllowIllegal? then @$effectiveAllowIllegal else false)"/>
      <set_value name="$enforceRouteIllegalLegality" exact="if $workUnit.$EnforceRouteIllegalLegality? then $workUnit.$EnforceRouteIllegalLegality else (if $effectiveEnforceRouteIllegalLegality? then @$effectiveEnforceRouteIllegalLegality else false)"/>
      <set_value name="$ignoreTradeRules" exact="if $workUnit.$IgnoreTradeRules? then $workUnit.$IgnoreTradeRules else (if $effectiveIgnoreTradeRules? then @$effectiveIgnoreTradeRules else false)"/>
      <set_value name="$ignoreMK1Supply" exact="if $workUnit.$IgnoreMK1Supply? then $workUnit.$IgnoreMK1Supply else (if $effectiveIgnoreMK1Supply? then @$effectiveIgnoreMK1Supply else true)"/>
      <set_value name="$shipDockSize" exact="this.ship.docksize"/>
      <set_value name="$isIsolatedForCargoFilter" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
      <set_value name="$useMinCargoThresholdFilter" exact="if $workUnit.$UseMinCargoThreshold? then $workUnit.$UseMinCargoThreshold else (if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false))"/>
      <set_value name="$cacheMinCargoUtilPct" exact="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)"/>
      <set_value name="$cargoUtilThresholdPct" exact="[10,[$cacheMinCargoUtilPct,100].min].max"/>
      
      <!-- Get cache list -->
      <set_value name="$rawCacheList" exact="[]"/>
      <do_if value="global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}?">
        <set_value name="$rawCacheList" exact="global.$GT_TradeCacheMK4.{$homeSector}"/>
      </do_if>
      
      <!-- Per-entry distance limits apply in lib.gt.cache.search; do not reject the whole pool on metadata alone. -->
      <!-- CRITICAL: Load GT_FailedSectorPairs for ship's current sector (prefilter failed sector pairs) -->
      <!-- This prevents revalidating entries that previously failed due to blacklisted routes -->
      <!-- Ships in the same sector share failed sector pairs (same connectivity/blacklist context) -->
      <!-- Ships in different sectors may still try (different path might exist) -->
      <set_value name="$currentSector" exact="this.ship.sector"/>
      <set_value name="$failedTrades" exact="table[]"/>
      <do_if value="$currentSector? and $currentSector.exists and global.$GT_FailedSectorPairs? and global.$GT_FailedSectorPairs.{$currentSector}?">
        <set_value name="$failedTradesRaw" exact="global.$GT_FailedSectorPairs.{$currentSector}"/>
        <set_value name="$expirationTime" exact="1800s"/> <!-- 30 minutes -->
        <run_script name="'lib.gt.failed_sector_pairs'" result="$failedTrades">
          <param name="rawEntry" value="$failedTradesRaw"/>
          <param name="expirationTime" value="$expirationTime"/>
        </run_script>
        <set_value name="$keptCount" exact="0"/>
        <set_value name="$fspBuyKeysNorm" exact="$failedTrades.keys"/>
        <do_all exact="$fspBuyKeysNorm.count" counter="$fspBkci">
          <set_value name="$fspBk" exact="$fspBuyKeysNorm.{$fspBkci}"/>
          <do_if value="$failedTrades.{$fspBk}?">
            <set_value name="$keptCount" exact="$keptCount + $failedTrades.{$fspBk}.keys.count"/>
          </do_if>
        </do_all>
        <do_if value="$keptCount == 0">
          <remove_value name="global.$GT_FailedSectorPairs.{$currentSector}"/>
        </do_if>
        <do_else>
          <set_value name="$fspRoot" exact="table[]"/>
          <do_if value="global.$GT_FailedSectorPairs? and typeof global.$GT_FailedSectorPairs == datatype.table">
            <set_value name="$fspRoot" exact="global.$GT_FailedSectorPairs"/>
          </do_if>
          <set_value name="$fspRoot.{$currentSector}" exact="$failedTrades"/>
          <set_value name="global.$GT_FailedSectorPairs" exact="$fspRoot"/>
        </do_else>
      </do_if>
      
      <!-- NOTE: Removed redundant cache pre-filter money check.
           The Early Money Gate and Fast Money Check already prevent reaching this point
           when player money is below threshold. The old check also had a unit bug
           (compared cents to credits). -->
      
      <!-- ==================================================================================== -->
      <!-- CRITICAL: Pre-filter cache entries by ALL cheap restrictions BEFORE processing -->
      <!-- This prevents validating entries that will never pass these checks -->
      <!-- ==================================================================================== -->
      <set_value name="$mk3BlacklistOwner" exact="this.ship"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
        <set_value name="$mk3BlacklistOwner" exact="this.ship.commander"/>
      </do_if>
      <set_value name="$mk3FactionBlacklist" exact="table[]"/>
      <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}?">
        <set_value name="$mk3FactionBlacklist" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}"/>
      </do_if>
      <set_value name="$cacheList" exact="[]"/>
      <set_value name="$rawCount" exact="$rawCacheList.count"/>
      <set_value name="$filterRejectCount" exact="table[
        $Distance = 0,
        $WareBasket = 0,
        $IllegalWare = 0,
        $IncompatibleCargo = 0,
        $RouteIllegal = 0,
        $FactionBlacklist = 0,
        $TradeRules = 0,
        $FailedSectorPairs = 0,
        $FailedShips = 0,
        $TargetType = 0,
        $MinCargoUtil = 0,
        $Mk4PlayerDelivery = 0,
        $Mk4SupplierPolicy = 0,
        $Mk4DedicatedHome = 0,
        $Mk4BuildStorageOnly = 0
      ]"/>
      <!-- Chunked pre-filter: process 50 entries per chunk with cooperative yielding to prevent frame spikes -->
      <set_value name="this.$pfProcessed" exact="0"/>
      <set_value name="this.$pfRouteMemoHits" exact="0"/>
      <label name="prefilter_work_loop"/>
      <set_value name="$pfChunkStart" exact="this.$pfProcessed + 1"/>
      <set_value name="$pfChunkEnd" exact="[this.$pfProcessed + 50, $rawCount].min"/>
      <!-- Chunk-local route-legality memo: skips repeated lib.gt.pathfinding run_script calls
           when multiple rows in this chunk share the same (buySector, sellSector, ware) triple.
           lib.gt.pathfinding already maintains a persistent global cache keyed on
           (home,buy,sell,ware) with $BlacklistEpoch invalidation, so the per-chunk memo only
           saves run_script interpreter overhead, not the underlying legality computation.
           Memo is locals-scoped so it is naturally freed at the cooperative yield, and we keep
           a running total on this.$pfRouteMemoHits so the post-chunk summary debug can report it.
           See DOCS/MK3_PIPELINE_REFACTOR.md Â§3.9. -->
      <set_value name="$pfRouteMemo" exact="table[]"/>
      
      <do_if value="$pfChunkStart le $rawCount">
        <do_all exact="($pfChunkEnd - $pfChunkStart + 1)" counter="$pfIdx">
          <set_value name="$rawIdx" exact="$pfChunkStart + $pfIdx - 1"/>
          <!-- Safe access: global cache list may shrink during cooperative yield between chunks -->
          <set_value name="$rawEntry" exact="@$rawCacheList.{$rawIdx}"/>
          <do_if value="$rawEntry?">
            <set_value name="$entryPassesFilters" exact="true"/>
            
            <!-- 1. Distance filter (using precomputed values from cache entry) -->
            <do_if value="$entryPassesFilters">
              <set_value name="$entryHomeToBuy" exact="@$rawEntry.$HomeToBuyDistance"/>
              <set_value name="$entryHomeToSell" exact="@$rawEntry.$HomeToSellDistance"/>
              <do_if value="$entryHomeToBuy? and $entryHomeToSell?">
                <set_value name="$entryMaxDist" exact="[$entryHomeToBuy, $entryHomeToSell].max"/>
                <do_if value="$entryHomeToBuy lt 0 or $entryHomeToSell lt 0 or $entryMaxDist gt $maxDistance">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Distance" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and ($filterRejectCount.$Distance le 20 or ($entryMaxDist le $maxDistance + 1 and $filterRejectCount.$Distance le 50))">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-filter REJECTED (distance): entryMaxDist=' + $entryMaxDist + ', allowed=' + $maxDistance + ', homeToBuy=' + $entryHomeToBuy + ', homeToSell=' + $entryHomeToSell + ', rawIdx=' + $rawIdx" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $rawIdx le 5">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-filter PASSED (distance): entryMaxDist=' + $entryMaxDist + ', allowed=' + $maxDistance + ', homeToBuy=' + $entryHomeToBuy + ', homeToSell=' + $entryHomeToSell + ', rawIdx=' + $rawIdx" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and ($rawIdx le 3)">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-filter WARNING: distances not cached for entry (will validate later)'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            
            <!-- 1b. Ware basket filter (manual basket active). -->
            <do_if value="$entryPassesFilters and $wareBasket.count gt 0">
              <set_value name="$entryWare" exact="if $rawEntry.$Ware? then $rawEntry.$Ware else null"/>
              <do_if value="$entryWare == null">
                <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
                <do_if value="$buyOffer? and $buyOffer.exists and $buyOffer.ware?">
                  <set_value name="$entryWare" exact="@$buyOffer.ware"/>
                </do_if>
              </do_if>
              <set_value name="$wareAllowed" exact="false"/>
              <do_if value="$entryWare?">
                <do_all exact="$wareBasket.count" counter="$wbi">
                  <do_if value="$wareBasket.{$wbi} == $entryWare">
                    <set_value name="$wareAllowed" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $wareAllowed">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$WareBasket" operation="add"/>
              </do_if>
            </do_if>

            <!-- 2. Illegal ware filter (if ship doesn't allow illegal) -->
            <do_if value="$entryPassesFilters and not $allowIllegal">
              <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
              <do_if value="$buyOffer? and $buyOffer.exists">
                <set_value name="$ware" exact="@$buyOffer.ware"/>
                <set_value name="$illegalExplicitlyAllowed" exact="false"/>
                <do_if value="$wareBasket.count gt 0 and $ware?">
                  <do_all exact="$wareBasket.count" counter="$ewi">
                    <do_if value="$wareBasket.{$ewi} == $ware">
                      <set_value name="$illegalExplicitlyAllowed" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$ware != null and @$ware.illegal gt 0 and not $illegalExplicitlyAllowed">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$IllegalWare" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 2a. Cargo bay compatibility (solid vs container; shared MK4 pool is ship-agnostic). -->
            <do_if value="$entryPassesFilters and not $rawEntry.$IsSellOnly?">
              <set_value name="$cargoCompatWare" exact="if $rawEntry.$Ware? then $rawEntry.$Ware else null"/>
              <do_if value="$cargoCompatWare == null">
                <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
                <do_if value="$buyOffer? and $buyOffer.exists and $buyOffer.ware?">
                  <set_value name="$cargoCompatWare" exact="@$buyOffer.ware"/>
                </do_if>
              </do_if>
              <set_value name="$cargoCompatTransport" exact="if $rawEntry.$CargoWareTransport? then @$rawEntry.$CargoWareTransport else (if $cargoCompatWare? then @$cargoCompatWare.waretransport else null)"/>
              <set_value name="$cargoCompatOk" exact="false"/>
              <do_if value="$cargoCompatWare? and this.ship.cargo.{$cargoCompatWare}.max gt 0">
                <set_value name="$cargoCompatOk" exact="true"/>
              </do_if>
              <do_elseif value="$cargoCompatTransport? and this.ship.waretransport.indexof.{$cargoCompatTransport}">
                <set_value name="$cargoCompatOk" exact="true"/>
              </do_elseif>
              <do_if value="not $cargoCompatOk">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$IncompatibleCargo" operation="add"/>
              </do_if>
            </do_if>

            <!-- 2b. Illegal route filter â€” contraband only -->
            <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
            <set_value name="$sellOffer" exact="@$rawEntry.$SellOffer"/>
            <set_value name="$ware" exact="if $buyOffer? and $buyOffer.ware? then @$buyOffer.ware else null"/>
            <do_if value="$entryPassesFilters and $allowIllegal and $enforceRouteIllegalLegality and @$ware.illegal gt 0">
              <set_value name="$entryBuySector" exact="if $buyOffer? and $buyOffer.owner? then @$buyOffer.owner.sector else null"/>
              <set_value name="$entrySellSector" exact="if $sellOffer? and $sellOffer.owner? then @$sellOffer.owner.sector else null"/>
              <!-- Chunk-local memo lookup before falling through to run_script. -->
              <set_value name="$routeLegality" exact="null"/>
              <do_if value="$entryBuySector? and $entrySellSector? and $ware? and $pfRouteMemo.{$entryBuySector}? and $pfRouteMemo.{$entryBuySector}.{$entrySellSector}? and $pfRouteMemo.{$entryBuySector}.{$entrySellSector}.{$ware}?">
                <set_value name="$routeLegality" exact="$pfRouteMemo.{$entryBuySector}.{$entrySellSector}.{$ware}"/>
                <set_value name="this.$pfRouteMemoHits" exact="this.$pfRouteMemoHits + 1"/>
              </do_if>
              <do_if value="$routeLegality == null">
                <run_script name="'lib.gt.pathfinding'" result="$routeLegality">
                  <param name="mode" value="'route_legality'"/>
                  <param name="ship" value="this.ship"/>
                  <param name="homeSector" value="$homeSector"/>
                  <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                  <param name="startSector" value="this.ship.sector"/>
                  <param name="buySector" value="$entryBuySector"/>
                  <param name="sellSector" value="$entrySellSector"/>
                  <param name="ware" value="$ware"/>
                </run_script>
                <do_if value="$entryBuySector? and $entrySellSector? and $ware?">
                  <do_if value="not $pfRouteMemo.{$entryBuySector}?">
                    <set_value name="$pfRouteMemo.{$entryBuySector}" exact="table[]"/>
                  </do_if>
                  <do_if value="not $pfRouteMemo.{$entryBuySector}.{$entrySellSector}?">
                    <set_value name="$pfRouteMemo.{$entryBuySector}.{$entrySellSector}" exact="table[]"/>
                  </do_if>
                  <set_value name="$pfRouteMemo.{$entryBuySector}.{$entrySellSector}.{$ware}" exact="$routeLegality"/>
                </do_if>
              </do_if>
              <do_if value="not $routeLegality.$IsLegal">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$RouteIllegal" operation="add"/>
              </do_if>
            </do_if>
            
            <!-- 3. MK3 faction blacklist filter (per-ship, test feature) -->
            <do_if value="$entryPassesFilters and $mk3FactionBlacklist.keys.count gt 0">
              <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
              <set_value name="$sellOffer" exact="@$rawEntry.$SellOffer"/>
              <do_if value="$buyOffer? and $buyOffer.exists and $buyOffer.owner?">
                <set_value name="$pfBuyOwnerContainer" exact="$buyOffer.owner"/>
                <set_value name="$pfBuyFaction" exact="null"/>
                <do_if value="$pfBuyOwnerContainer.owner?">
                  <set_value name="$pfBuyFaction" exact="$pfBuyOwnerContainer.owner"/>
                </do_if>
                <do_else>
                  <set_value name="$pfBuyFaction" exact="$pfBuyOwnerContainer"/>
                </do_else>
                <do_if value="$pfBuyFaction? and $mk3FactionBlacklist.{$pfBuyFaction}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$FactionBlacklist" operation="add"/>
                </do_if>
              </do_if>
              <do_if value="$entryPassesFilters and $sellOffer? and $sellOffer.exists and $sellOffer.owner?">
                <set_value name="$pfSellOwnerContainer" exact="$sellOffer.owner"/>
                <set_value name="$pfSellFaction" exact="null"/>
                <do_if value="$pfSellOwnerContainer.owner?">
                  <set_value name="$pfSellFaction" exact="$pfSellOwnerContainer.owner"/>
                </do_if>
                <do_else>
                  <set_value name="$pfSellFaction" exact="$pfSellOwnerContainer"/>
                </do_else>
                <do_if value="$pfSellFaction? and $mk3FactionBlacklist.{$pfSellFaction}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$FactionBlacklist" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 4. Trade rules filter (if ship requires trade rules) -->
            <do_if value="$entryPassesFilters and not $ignoreTradeRules">
              <set_value name="$tradeRulesRespected" exact="if $rawEntry.$TradeRulesRespected? then $rawEntry.$TradeRulesRespected else false"/>
              <do_if value="not $tradeRulesRespected">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$TradeRules" operation="add"/>
              </do_if>
            </do_if>
            
            <!-- 5. Failed sector pairs filter â€” O(1) nested table lookup (matching B2 pattern) -->
            <do_if value="$entryPassesFilters and $failedTrades.keys.count gt 0">
              <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
              <set_value name="$sellOffer" exact="@$rawEntry.$SellOffer"/>
              <do_if value="$buyOffer? and $buyOffer.exists and $sellOffer? and $sellOffer.exists">
                <set_value name="$entryBuySector" exact="$buyOffer.owner.sector"/>
                <set_value name="$entrySellSector" exact="$sellOffer.owner.sector"/>
                <do_if value="$failedTrades.{$entryBuySector}? and $failedTrades.{$entryBuySector}.{$entrySellSector}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$FailedSectorPairs" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 6. Ship already failed filter (check FailedShips list in cache entry) -->
            <do_if value="$entryPassesFilters">
              <set_value name="$failedShips" exact="@$rawEntry.$FailedShips"/>
              <do_if value="$failedShips != null and $failedShips.count gt 0">
                <do_all exact="$failedShips.count" counter="$f">
                  <do_if value="$failedShips.{$f} == this.ship">
                    <set_value name="$entryPassesFilters" exact="false"/>
                    <set_value name="$filterRejectCount.$FailedShips" operation="add"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
            
            <!-- 7. Target type filters (build storage, carrier/aux) -->
            <do_if value="$entryPassesFilters and ($ignoreBuildStorage or $ignoreCarrierAux)">
              <set_value name="$buyType" exact="@$rawEntry.$BuyTargetType"/>
              <set_value name="$sellType" exact="@$rawEntry.$SellTargetType"/>
              <do_if value="$ignoreBuildStorage and ($buyType == 'Buildstorage' or $sellType == 'Buildstorage')">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$TargetType" operation="add"/>
              </do_if>
              <do_elseif value="$ignoreCarrierAux and (($buyType == 'Aux' or $buyType == 'Carrier') or ($sellType == 'Aux' or $sellType == 'Carrier'))">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$TargetType" operation="add"/>
              </do_elseif>
            </do_if>
            
            <!-- 8. Hard minimum cargo utilization pre-filter (excluded in isolated mode) -->
            <do_if value="$entryPassesFilters and $useMinCargoThresholdFilter and not $isIsolatedForCargoFilter and not $rawEntry.$IsSellOnly?">
              <set_value name="$pfVolumePerUnit" exact="1"/>
              <do_if value="$rawEntry.$Ware? and $rawEntry.$Ware.volume?">
                <set_value name="$pfVolumePerUnit" exact="$rawEntry.$Ware.volume"/>
              </do_if>
              <set_value name="$pfOfferBuyAmount" exact="if $rawEntry.$BuyOffer? and @$rawEntry.$BuyOffer.exists then @$rawEntry.$BuyOffer.offeramount.{this.ship} else 0"/>
              <set_value name="$pfOfferSellAmount" exact="if $rawEntry.$SellOffer? and @$rawEntry.$SellOffer.exists then @$rawEntry.$SellOffer.offeramount.{this.ship} else 0"/>
              <set_value name="$pfAmountLimit" exact="[$pfOfferBuyAmount, $pfOfferSellAmount].min"/>
              <set_value name="$pfTradeVolume" exact="$pfAmountLimit * $pfVolumePerUnit"/>
              <set_value name="$pfRequiredVolume" exact="(this.ship.cargo.capacity.all * $cargoUtilThresholdPct) / 100.0"/>
              <do_if value="$pfTradeVolume lt $pfRequiredVolume">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$MinCargoUtil" operation="add"/>
              </do_if>
            </do_if>
            
            <!-- 9. MK4: delivery station must be player-owned (prefer buyer on cached SellOffer). -->
            <do_if value="$entryPassesFilters">
              <set_value name="$pfDeliveryStation" exact="if $rawEntry.$SellStation? then @$rawEntry.$SellStation else null"/>
              <do_if value="not $pfDeliveryStation? and $rawEntry.$SellOffer?">
                <do_if value="$rawEntry.$SellOffer.buyer? and @$rawEntry.$SellOffer.buyer.exists">
                  <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.buyer"/>
                </do_if>
                <do_elseif value="$rawEntry.$SellOffer.owner?">
                  <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.owner"/>
                </do_elseif>
              </do_if>
              <set_value name="$pfMk4PlayerDeliveryOk" exact="false"/>
              <do_if value="$pfDeliveryStation? and @$pfDeliveryStation.exists">
                <do_if value="@$pfDeliveryStation.isplayerowned">
                  <set_value name="$pfMk4PlayerDeliveryOk" exact="true"/>
                </do_if>
                <do_elseif value="$pfDeliveryStation.isclass.buildstorage and $pfDeliveryStation.base? and @$pfDeliveryStation.base.isplayerowned">
                  <set_value name="$pfMk4PlayerDeliveryOk" exact="true"/>
                </do_elseif>
              </do_if>
              <do_if value="not $pfMk4PlayerDeliveryOk">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4PlayerDelivery" operation="add"/>
              </do_if>
            </do_if>

            <!-- 9a. MK4 home-anchor scope (serveHomeOnly and/or build-storage-only mode). -->
            <do_if value="$entryPassesFilters and (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false)">
              <set_value name="$pfServeHomeAnchor" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null)"/>
              <set_value name="$pfServeHomeSector" exact="if $pfServeHomeAnchor? and $pfServeHomeAnchor.isclass.sector then $pfServeHomeAnchor else (if $pfServeHomeAnchor? and $pfServeHomeAnchor.sector? then @$pfServeHomeAnchor.sector else $homeSector)"/>
              <do_if value="not $pfDeliveryStation?">
                <set_value name="$pfDeliveryStation" exact="if $rawEntry.$SellStation? then @$rawEntry.$SellStation else null"/>
                <do_if value="not $pfDeliveryStation? and $rawEntry.$SellOffer?">
                  <do_if value="$rawEntry.$SellOffer.buyer? and @$rawEntry.$SellOffer.buyer.exists">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.buyer"/>
                  </do_if>
                  <do_elseif value="$rawEntry.$SellOffer.owner?">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_if>
              <set_value name="$pfSuppStationBso" exact="null"/>
              <do_if value="$rawEntry.$BuyOffer? and @$rawEntry.$BuyOffer.exists">
                <do_if value="$rawEntry.$BuyOffer.seller? and @$rawEntry.$BuyOffer.seller.exists">
                  <set_value name="$pfSuppStationBso" exact="@$rawEntry.$BuyOffer.seller"/>
                </do_if>
              </do_if>
              <do_if value="not $pfSuppStationBso? and $rawEntry.$BuyStation?">
                <set_value name="$pfSuppStationBso" exact="@$rawEntry.$BuyStation"/>
              </do_if>
              <do_if value="$pfSuppStationBso? and @$pfSuppStationBso.isclass.buildstorage">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4BuildStorageOnly" operation="add"/>
              </do_if>
              <do_if value="$entryPassesFilters and (not $pfDeliveryStation? or not @$pfDeliveryStation.isclass.buildstorage)">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4BuildStorageOnly" operation="add"/>
              </do_if>
              <do_if value="$entryPassesFilters">
                <set_value name="$pfBsoDist" exact="if $homeSector? and $pfDeliveryStation? and $pfDeliveryStation.sector? then $homeSector.gatedistance.{$pfDeliveryStation.sector} else -1"/>
                <set_value name="$pfBsoCoverageMax" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else $maxDistance"/>
                <do_if value="$pfBsoDist lt 0 or ($pfBsoCoverageMax gt 0 and $pfBsoDist gt $pfBsoCoverageMax)">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4BuildStorageOnly" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$entryPassesFilters and not (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) and (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false)">
              <set_value name="$pfServeHomeAnchor" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null)"/>
              <set_value name="$pfServeHomeSector" exact="if $pfServeHomeAnchor? and $pfServeHomeAnchor.isclass.sector then $pfServeHomeAnchor else (if $pfServeHomeAnchor? and $pfServeHomeAnchor.sector? then @$pfServeHomeAnchor.sector else $homeSector)"/>
              <do_if value="not $pfDeliveryStation?">
                <set_value name="$pfDeliveryStation" exact="if $rawEntry.$SellStation? then @$rawEntry.$SellStation else null"/>
                <do_if value="not $pfDeliveryStation? and $rawEntry.$SellOffer?">
                  <do_if value="$rawEntry.$SellOffer.buyer? and @$rawEntry.$SellOffer.buyer.exists">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.buyer"/>
                  </do_if>
                  <do_elseif value="$rawEntry.$SellOffer.owner?">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_if>
              <do_if value="$pfServeHomeAnchor? and $pfServeHomeAnchor.isclass.station">
                <set_value name="$pfServeHomeMatch" exact="false"/>
                <do_if value="$pfDeliveryStation? and $pfDeliveryStation.exists and $pfServeHomeAnchor.exists">
                  <do_if value="$pfDeliveryStation == $pfServeHomeAnchor">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_if>
                  <do_elseif value="$pfServeHomeAnchor.buildstorage? and $pfServeHomeAnchor.buildstorage.exists and $pfDeliveryStation == $pfServeHomeAnchor.buildstorage">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$pfDeliveryStation.isclass.buildstorage and $pfDeliveryStation.base? and $pfDeliveryStation.base.exists and $pfDeliveryStation.base == $pfServeHomeAnchor">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$pfDeliveryStation.hascontext.{$pfServeHomeAnchor}">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$pfServeHomeAnchor.hascontext.{$pfDeliveryStation}">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="not $pfServeHomeMatch">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4DedicatedHome" operation="add"/>
                </do_if>
              </do_if>
              <do_elseif value="$pfServeHomeSector? and $pfServeHomeSector.exists">
                <do_if value="not $pfDeliveryStation? or not $pfDeliveryStation.sector? or @$pfDeliveryStation.sector != $pfServeHomeSector">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4DedicatedHome" operation="add"/>
                </do_if>
              </do_elseif>
            </do_if>
            
            <!-- 9b. MK4: supplier ($BuyOffer = game sell offer; ship buys here) vs allowAiSuppliers / allowPlayerSuppliers -->
            <do_if value="$entryPassesFilters">
              <set_value name="$pfSuppStation" exact="null"/>
              <do_if value="$rawEntry.$BuyOffer? and @$rawEntry.$BuyOffer.exists">
                <do_if value="$rawEntry.$BuyOffer.seller? and @$rawEntry.$BuyOffer.seller.exists">
                  <set_value name="$pfSuppStation" exact="@$rawEntry.$BuyOffer.seller"/>
                </do_if>
              </do_if>
              <do_if value="not $pfSuppStation? and $rawEntry.$BuyStation?">
                <set_value name="$pfSuppStation" exact="@$rawEntry.$BuyStation"/>
              </do_if>
              <set_value name="$pfMk4AISup" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
              <set_value name="$pfMk4PlSup" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
              <do_if value="not $pfMk4PlSup and $pfSuppStation? and @$pfSuppStation.isplayerowned">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4SupplierPolicy" operation="add"/>
              </do_if>
              <do_if value="$entryPassesFilters and not $pfMk4AISup">
                <do_if value="not $pfSuppStation? or not @$pfSuppStation.isplayerowned">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4SupplierPolicy" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 10. MK1-supplied station filter -->
            <do_if value="$entryPassesFilters and $ignoreMK1Supply and global.$GT_MK1SuppliedStations?">
              <do_if value="$rawEntry.$BuyStation?">
                <do_if value="global.$GT_MK1SuppliedStations.{$rawEntry.$BuyStation}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="$entryPassesFilters and $rawEntry.$SellStation?">
                <do_if value="global.$GT_MK1SuppliedStations.{$rawEntry.$SellStation}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- Add entry to filtered list if it passed all pre-filters -->
            <do_if value="$entryPassesFilters">
              <append_to_list name="$cacheList" exact="$rawEntry"/>
            </do_if>
          </do_if>
        </do_all>
        
        <set_value name="this.$pfProcessed" exact="$pfChunkEnd"/>
        
        <!-- Cooperative yield between pre-filter chunks -->
        <wait exact="this.$gt_yieldMs * 1ms"/>
        
        <!-- Continue if more entries to process -->
        <do_if value="this.$pfProcessed lt $rawCount">
          <resume label="prefilter_work_loop"/>
        </do_if>
      </do_if>
      
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache search params: homeSector=' + (if $homeSector? then $homeSector.knownname else 'null') + ', maxDistance=' + $maxDistance + ', cacheMaxDistance=' + $cacheMaxDistance + ', minProfit=' + $minAbsoluteProfit + ', minROI=' + $minROI + ', rawEntries=' + $rawCount + ', preFilteredEntries=' + $cacheList.count + ', routeMemoHits=' + (if this.$pfRouteMemoHits? then this.$pfRouteMemoHits else 0) + ', filterRejections: Distance=' + $filterRejectCount.$Distance + ', WareBasket=' + $filterRejectCount.$WareBasket + ', IllegalWare=' + $filterRejectCount.$IllegalWare + ', IncompatibleCargo=' + $filterRejectCount.$IncompatibleCargo + ', RouteIllegal=' + $filterRejectCount.$RouteIllegal + ', FactionBlacklist=' + $filterRejectCount.$FactionBlacklist + ', TradeRules=' + $filterRejectCount.$TradeRules + ', FailedSectorPairs=' + $filterRejectCount.$FailedSectorPairs + ', FailedShips=' + $filterRejectCount.$FailedShips + ', TargetType=' + $filterRejectCount.$TargetType + ', Mk4PlayerDelivery=' + $filterRejectCount.$Mk4PlayerDelivery + ', Mk4SupplierPolicy=' + $filterRejectCount.$Mk4SupplierPolicy + ', Mk4DedicatedHome=' + $filterRejectCount.$Mk4DedicatedHome + ', Mk4BuildStorageOnly=' + $filterRejectCount.$Mk4BuildStorageOnly" chance="100"/>
      <do_if value="this.$pfRouteMemoHits?">
        <remove_value name="this.$pfRouteMemoHits"/>
      </do_if>
      
      <!-- Process cache entries with frame budgeting -->
      <!-- Get chunk size from global settings (default: 20) -->
      <set_value name="$chunkSize" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize?">
        <set_value name="$tmpChunk" exact="@global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize"/>
        <do_if value="$tmpChunk? and $tmpChunk != null and $tmpChunk gt 0">
          <set_value name="$chunkSize" exact="$tmpChunk"/>
        </do_if>
      </do_if>
      <!-- Clamp to reasonable bounds -->
      <do_if value="$chunkSize lt 10">
        <set_value name="$chunkSize" exact="10"/>
      </do_if>
      <do_if value="$chunkSize gt 200">
        <set_value name="$chunkSize" exact="200"/>
      </do_if>
      
      <!-- Get max trades to return from global settings -->
      <set_value name="$maxTradesToReturn" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn?">
        <set_value name="$tmpMax" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn"/>
        <do_if value="$tmpMax? and $tmpMax != null and $tmpMax gt 0">
          <set_value name="$maxTradesToReturn" exact="$tmpMax"/>
        </do_if>
      </do_if>
      
      <!-- Per-ware diversification for cache work-loop results (parity with lib.gt.cache.search). -->
      <set_value name="$cacheWorkWareBasketCount" exact="if $wareBasket? and typeof $wareBasket == datatype.list then $wareBasket.count else 0"/>
      <set_value name="$cacheWorkFoundPerWare" exact="table[]"/>
      <set_value name="$cacheWorkMaxTradesPerWare" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
        <set_value name="$cacheWorkMaxTradesPerWare" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
      </do_if>
      <do_if value="$cacheWorkMaxTradesPerWare lt 1">
        <set_value name="$cacheWorkMaxTradesPerWare" exact="1"/>
      </do_if>
      <set_value name="$cacheWorkPerWareCap" exact="$cacheWorkMaxTradesPerWare"/>
      <do_if value="$cacheWorkWareBasketCount gt 0">
        <set_value name="$cacheWorkPerWareCapFromBudget" exact="[1, ($maxTradesToReturn / $cacheWorkWareBasketCount)i].max"/>
        <set_value name="$cacheWorkPerWareCap" exact="[$cacheWorkPerWareCapFromBudget, $cacheWorkMaxTradesPerWare].min"/>
      </do_if>
      <do_else>
        <set_value name="$cacheWorkPerWareCap" exact="[2, [$cacheWorkMaxTradesPerWare, 5].min].max"/>
      </do_else>

      <set_value name="this.$processedCount" exact="0"/>
      <set_value name="this.$gt_dockMemo" exact="table[]"/>
      <set_value name="$validTrades" exact="[]"/>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>
      <set_value name="$cachePriorityBoostCount" exact="0"/>
      <set_value name="$bestWasPriority" exact="false"/>
      
      <!-- Debug: log when priority wares will be applied during cache scoring -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0">
          <set_value name="$pwNames" exact="''"/>
          <do_all exact="$effectivePriorityWares.count" counter="$pn">
            <set_value name="$pnw" exact="$effectivePriorityWares.{$pn}"/>
            <set_value name="$pwNames" exact="$pwNames + (if $pn gt 1 then ', ' else '') + (if $pnw? and $pnw != null then @$pnw.name else '?')"/>
          </do_all>
          <set_value name="$cacheMultPct" exact="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache search: priority wares active (' + $effectivePriorityWares.count + ' wares: [' + $pwNames + '], multiplier=' + $cacheMultPct + '%)'" chance="100"/>
        </do_if>
      </do_if>
      
      <label name="cache_work_loop"/>
      <set_value name="$startTime" exact="player.age"/>
      <set_value name="$chunkStart" exact="this.$processedCount + 1"/>
      <set_value name="$chunkEnd" exact="[this.$processedCount + $chunkSize, $cacheList.count].min"/>
      
      <do_if value="$chunkStart le $cacheList.count">
        <do_all exact="($chunkEnd - $chunkStart + 1)" counter="$i">
          <set_value name="$cacheIndex" exact="$chunkStart + $i - 1"/>
          <set_value name="$cacheEntry" exact="$cacheList.{$cacheIndex}"/>
          
          <!-- Validate cache entry -->
          <do_if value="$cacheEntry?">
            <set_value name="$cacheAge" exact="player.age - $cacheEntry.$Timestamp"/>
            <do_if value="$cacheAge le 600s">
              <!-- Validate cache entry with full filtering (aligned with lib.gt.cache.search + MD purge/reservation rules) -->
              <!-- Use ship-agnostic fields for validation -->
              <set_value name="$buyOffer" exact="@$cacheEntry.$BuyOffer"/>
              <set_value name="$sellOffer" exact="@$cacheEntry.$SellOffer"/>
              
              <!-- Get ship-agnostic fields from cache entry -->
              <set_value name="$offerMaxAmount" exact="@$cacheEntry.$OfferMaxAmount"/>
              <set_value name="$profitPerUnit" exact="@$cacheEntry.$ProfitPerUnit"/>
              <set_value name="$volumePerUnit" exact="@$cacheEntry.$VolumePerUnit"/>
              <set_value name="$buyPrice" exact="@$cacheEntry.$BuyPrice"/>
              <set_value name="$sellPrice" exact="@$cacheEntry.$SellPrice"/>
              
              <!-- Fallback to ship-biased fields for old cache entries (backward compatibility) -->
              <do_if value="not $offerMaxAmount? or $offerMaxAmount == null or $offerMaxAmount le 0">
                <set_value name="$offerMaxAmount" exact="@$cacheEntry.$Amount"/>
              </do_if>
              <do_if value="not $profitPerUnit? or $profitPerUnit == null">
                <set_value name="$cachedProfit" exact="@$cacheEntry.$Profit"/>
                <set_value name="$cachedAmount" exact="@$cacheEntry.$Amount"/>
                <do_if value="$cachedAmount? and $cachedAmount gt 0">
                  <set_value name="$profitPerUnit" exact="$cachedProfit / $cachedAmount"/>
                </do_if>
                <do_else>
                  <set_value name="$profitPerUnit" exact="0"/>
                </do_else>
              </do_if>
              <do_if value="not $volumePerUnit? or $volumePerUnit == null">
                <set_value name="$ware" exact="@$buyOffer.ware"/>
                <set_value name="$volumePerUnit" exact="if $ware? and $ware.volume? then $ware.volume else 1"/>
              </do_if>
              <do_if value="not $buyPrice? or $buyPrice == null">
                <set_value name="$buyPrice" exact="if $buyOffer? and $buyOffer.price? then $buyOffer.price else 0"/>
              </do_if>
              <do_if value="not $sellPrice? or $sellPrice == null">
                <set_value name="$sellPrice" exact="if $sellOffer? and $sellOffer.price? then $sellOffer.price else 0"/>
                <do_if value="$profitPerUnit == 0 and $sellPrice gt 0 and $buyPrice gt 0">
                  <set_value name="$profitPerUnit" exact="$sellPrice - $buyPrice"/>
                </do_if>
              </do_if>
              
              <!-- Track rejection reason for debugging -->
              <set_value name="$rejectReason" exact="''"/>
              <set_value name="$isValid" exact="true"/>
              
              <!-- Basic structure checks -->
              <do_if value="not $buyOffer? or not $buyOffer.exists or not $sellOffer? or not $sellOffer.exists">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$rejectReason" exact="'offers_invalid'"/>
              </do_if>
              <do_elseif value="not @$buyOffer.owner.isoperational or not @$sellOffer.owner.isoperational">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$rejectReason" exact="'station_not_operational'"/>
              </do_elseif>
              
              <!-- Cargo bay compatibility (solid vs container; shared MK4 pool). -->
              <do_if value="$isValid and not $cacheEntry.$IsSellOnly?">
                <set_value name="$cacheWorkCargoWare" exact="if $cacheEntry.$Ware? then $cacheEntry.$Ware else null"/>
                <do_if value="not $cacheWorkCargoWare? and $buyOffer? and $buyOffer.exists and $buyOffer.ware?">
                  <set_value name="$cacheWorkCargoWare" exact="@$buyOffer.ware"/>
                </do_if>
                <do_if value="not $cacheWorkCargoWare? and $sellOffer? and $sellOffer.exists and $sellOffer.ware?">
                  <set_value name="$cacheWorkCargoWare" exact="@$sellOffer.ware"/>
                </do_if>
                <set_value name="$cacheWorkCargoTransport" exact="if $cacheEntry.$CargoWareTransport? then @$cacheEntry.$CargoWareTransport else (if $cacheWorkCargoWare? then @$cacheWorkCargoWare.waretransport else null)"/>
                <set_value name="$cacheWorkCargoOk" exact="false"/>
                <do_if value="$cacheWorkCargoWare? and this.ship.cargo.{$cacheWorkCargoWare}.max gt 0">
                  <set_value name="$cacheWorkCargoOk" exact="true"/>
                </do_if>
                <do_elseif value="$cacheWorkCargoTransport? and this.ship.waretransport.indexof.{$cacheWorkCargoTransport}">
                  <set_value name="$cacheWorkCargoOk" exact="true"/>
                </do_elseif>
                <do_if value="not $cacheWorkCargoOk">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'incompatible_cargo'"/>
                </do_if>
              </do_if>
              
              <!-- MK4 Galaxy-Supply: delivery = cached $SellOffer (game buy offer); prefer buyer (lib.gt.tradematch). -->
              <do_if value="$isValid">
                <set_value name="$mk4DelivCustomer" exact="null"/>
                <do_if value="$sellOffer.buyer? and @$sellOffer.buyer.exists">
                  <set_value name="$mk4DelivCustomer" exact="@$sellOffer.buyer"/>
                </do_if>
                <do_elseif value="$sellOffer.owner?">
                  <set_value name="$mk4DelivCustomer" exact="@$sellOffer.owner"/>
                </do_elseif>
                <do_if value="not $mk4DelivCustomer? or not @$mk4DelivCustomer.isplayerowned">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk4_delivery_not_player'"/>
                </do_if>
              </do_if>
              
              <!-- MK4: supplier = cached $BuyOffer (game sell offer); prefer seller (lib.gt.tradematch). -->
              <do_if value="$isValid">
                <set_value name="$mk4SupplierStationVal" exact="null"/>
                <do_if value="$buyOffer.seller? and @$buyOffer.seller.exists">
                  <set_value name="$mk4SupplierStationVal" exact="@$buyOffer.seller"/>
                </do_if>
                <do_elseif value="$buyOffer.owner?">
                  <set_value name="$mk4SupplierStationVal" exact="@$buyOffer.owner"/>
                </do_elseif>
                <set_value name="$valMk4AISup" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
                <set_value name="$valMk4PlSup" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
                <do_if value="not $valMk4PlSup and $mk4SupplierStationVal? and @$mk4SupplierStationVal.isplayerowned">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk4_player_supplier_disallowed'"/>
                </do_if>
                <do_if value="$isValid and not $valMk4AISup">
                  <do_if value="not $mk4SupplierStationVal? or not @$mk4SupplierStationVal.isplayerowned">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'mk4_ai_supplier_disallowed'"/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- NOTE: Distance, illegal ware, trade rules, failed sector pairs, failed ships,
                   and target type checks are SKIPPED here â€” already verified by the pre-filter
                   loop (prefilter_work_loop). Only time-sensitive and ship-specific expensive
                   checks remain below (docking, dock size, offer availability, profit/ROI). -->
              
              <!-- ==================================================================================== -->
              <!-- EXPENSIVE CHECKS LAST: Property lookups on ship/station objects -->
              <!-- ==================================================================================== -->
              
              <!-- Dock feasibility (ship-specific): trading bays on stations, storage bays on build storage -->
              <do_if value="$isValid">
                <set_value name="$cacheValBuyStation" exact="null"/>
                <do_if value="$buyOffer.seller? and @$buyOffer.seller.exists">
                  <set_value name="$cacheValBuyStation" exact="@$buyOffer.seller"/>
                </do_if>
                <do_elseif value="$buyOffer.owner?">
                  <set_value name="$cacheValBuyStation" exact="@$buyOffer.owner"/>
                </do_elseif>
                <set_value name="$cacheValSellStation" exact="null"/>
                <do_if value="$sellOffer.buyer? and @$sellOffer.buyer.exists">
                  <set_value name="$cacheValSellStation" exact="@$sellOffer.buyer"/>
                </do_if>
                <do_elseif value="$sellOffer.owner?">
                  <set_value name="$cacheValSellStation" exact="@$sellOffer.owner"/>
                </do_elseif>
                <set_value name="$cacheValCanDockBuy" exact="false"/>
                <run_script name="'lib.gt.dockcheck'" result="$cacheValBuyDockResult">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$cacheValBuyStation"/>
                  <param name="purpose" value="'trade'"/>
                  <param name="useMemo" value="true"/>
                </run_script>
                <set_value name="$cacheValCanDockBuy" exact="$cacheValBuyDockResult.$CanDock"/>
                <set_value name="$cacheValCanDockSell" exact="false"/>
                <run_script name="'lib.gt.dockcheck'" result="$cacheValSellDockResult">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$cacheValSellStation"/>
                  <param name="purpose" value="'trade'"/>
                  <param name="useMemo" value="true"/>
                </run_script>
                <set_value name="$cacheValCanDockSell" exact="$cacheValSellDockResult.$CanDock"/>
                <do_if value="not $cacheValCanDockBuy or not $cacheValCanDockSell">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'docking_not_allowed'"/>
                </do_if>
              </do_if>
              
              <!-- ==================================================================================== -->
              <!-- SHIP-AGNOSTIC CACHE VALIDATION: Use ship-agnostic fields for prefiltering -->
              <!-- ==================================================================================== -->
              
              <!-- Validate offers are still available -->
              <do_if value="$isValid">
                <set_value name="$buyOfferObj" exact="@$cacheEntry.$BuyOffer"/>
                <set_value name="$sellOfferObj" exact="@$cacheEntry.$SellOffer"/>
                <do_if value="not $buyOfferObj? or $buyOfferObj == null or not $buyOfferObj.exists or not $sellOfferObj? or $sellOfferObj == null or not $sellOfferObj.exists">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'offers_no_longer_exist'"/>
                </do_if>
                <do_else>
                  <set_value name="$buyAvailNow" exact="@$buyOfferObj.available"/>
                  <set_value name="$sellAvailNow" exact="@$sellOfferObj.available"/>
                  <set_value name="$buyAmtNow" exact="@$buyOfferObj.amount"/>
                  <set_value name="$sellAmtNow" exact="@$sellOfferObj.amount"/>
                  <do_if value="$buyAmtNow == null">
                    <set_value name="$buyAmtNow" exact="0"/>
                  </do_if>
                  <do_if value="$sellAmtNow == null">
                    <set_value name="$sellAmtNow" exact="0"/>
                  </do_if>
                  <do_if value="not $buyAvailNow or not $sellAvailNow or $buyAmtNow le 0 or $sellAmtNow le 0">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'offers_insufficient_amount buyAvail=' + $buyAvailNow + ' buyAmt=' + $buyAmtNow + ' sellAvail=' + $sellAvailNow + ' sellAmt=' + $sellAmtNow + ' (both stations must have stock > 0)'"/>
                  </do_if>
                  <do_else>
                    <!-- Update offerMaxAmount with current offer amounts (may have changed since cache creation) -->
                    <set_value name="$currentOfferMaxAmount" exact="[$buyAmtNow, $sellAmtNow].min"/>
                    <do_if value="$currentOfferMaxAmount lt $offerMaxAmount">
                      <set_value name="$offerMaxAmount" exact="$currentOfferMaxAmount"/>
                    </do_if>
                  </do_else>
                </do_else>
              </do_if>
              
              <!-- ==================================================================================== -->
              <!-- SHIP-SPECIFIC PREFILTERING: Calculate max tradeable amount for THIS ship -->
              <!-- ==================================================================================== -->
              
              <!-- Calculate ship's max tradeable amount based on cargo capacity -->
              <do_if value="$isValid">
                <set_value name="$shipMaxByCargo" exact="0"/>
                <do_if value="$volumePerUnit gt 0">
                  <set_value name="$shipCargoCapacity" exact="this.ship.cargo.capacity.all"/>
                  <set_value name="$shipCargoFree" exact="this.ship.cargo.free.all"/>
                  <set_value name="$shipMaxByCargo" exact="$shipCargoFree / $volumePerUnit"/>
                </do_if>
                
                <!-- Calculate ship's max tradeable amount based on money (if applicable) -->
                <set_value name="$shipMaxByMoney" exact="999999999"/>
                <do_if value="$buyPrice gt 0">
                  <set_value name="$playerMoney" exact="player.money"/>
                  <set_value name="$shipMaxByMoney" exact="$playerMoney / $buyPrice"/>
                </do_if>
                
                <!-- Calculate ship's actual max tradeable amount -->
                <set_value name="$shipMaxAmount" exact="[$offerMaxAmount, $shipMaxByCargo, $shipMaxByMoney].min"/>
                
                <!-- Early rejection: ship cannot trade any amount -->
                <do_if value="$shipMaxAmount le 0">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'ship_cannot_carry_amount cargoMax=' + $shipMaxByCargo + ' moneyMax=' + $shipMaxByMoney + ' offerMax=' + $offerMaxAmount"/>
                </do_if>
                <do_else>
                  <!-- Hard minimum cargo utilization filter (excluded in isolated mode) -->
                  <do_if value="$useMinCargoThresholdFilter and not $isIsolatedForCargoFilter and not $cacheEntry.$IsSellOnly?">
                    <set_value name="$cacheTradeVolume" exact="$shipMaxAmount * $volumePerUnit"/>
                    <set_value name="$cacheRequiredVolume" exact="(this.ship.cargo.capacity.all * $cargoUtilThresholdPct) / 100.0"/>
                    <do_if value="$cacheTradeVolume lt $cacheRequiredVolume">
                      <set_value name="$isValid" exact="false"/>
                      <set_value name="$rejectReason" exact="'cargo_utilization_below_min actualVol=' + $cacheTradeVolume + ' requiredVol=' + $cacheRequiredVolume + ' threshold=' + $cargoUtilThresholdPct + '%'"/>
                    </do_if>
                  </do_if>

                  <do_if value="$isValid">
                    <!-- MK4 supply price-cap check:
                         allow equal price; reject only if source price is above customer buy price. -->
                    <do_if value="$sellPrice lt $buyPrice">
                      <set_value name="$isValid" exact="false"/>
                      <set_value name="$rejectReason" exact="'mk4_price_cap_exceeded source=' + $buyPrice + ' customer=' + $sellPrice"/>
                    </do_if>
                  </do_if>
                </do_else>
              </do_if>
              
              <!-- CRITICAL: Re-validate offers with tradepartner to ensure trade rules are respected -->
              <do_if value="$isValid and not $ignoreTradeRules">
                <set_value name="$buyStation" exact="null"/>
                <do_if value="$cacheEntry.$BuyOffer.seller? and @$cacheEntry.$BuyOffer.seller.exists">
                  <set_value name="$buyStation" exact="@$cacheEntry.$BuyOffer.seller"/>
                </do_if>
                <do_elseif value="$cacheEntry.$BuyOffer.owner?">
                  <set_value name="$buyStation" exact="@$cacheEntry.$BuyOffer.owner"/>
                </do_elseif>
                <set_value name="$buyWare" exact="@$cacheEntry.$BuyOffer.ware"/>
                <set_value name="$sellStation" exact="null"/>
                <do_if value="$cacheEntry.$SellOffer.buyer? and @$cacheEntry.$SellOffer.buyer.exists">
                  <set_value name="$sellStation" exact="@$cacheEntry.$SellOffer.buyer"/>
                </do_if>
                <do_elseif value="$cacheEntry.$SellOffer.owner?">
                  <set_value name="$sellStation" exact="@$cacheEntry.$SellOffer.owner"/>
                </do_elseif>
                <set_value name="$sellWare" exact="@$cacheEntry.$SellOffer.ware"/>
                
                <do_if value="$buyStation? and $buyStation.exists and $buyWare != null">
                  <find_sell_offer seller="$buyStation" wares="$buyWare" tradepartner="this.ship" result="$validatedBuyOffer"/>
                  <do_if value="not $validatedBuyOffer.available">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'trade_rules_buy_violation'"/>
                  </do_if>
                </do_if>
                
                <do_if value="$isValid and $sellStation? and $sellStation.exists and $sellWare != null">
                  <find_buy_offer buyer="$sellStation" wares="$sellWare" tradepartner="this.ship" result="$validatedSellOffer"/>
                  <do_if value="not $validatedSellOffer.available">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'trade_rules_sell_violation'"/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- MK3 faction blacklist safety net -->
              <do_if value="$isValid and $mk3FactionBlacklist.keys.count gt 0">
                <set_value name="$cacheBuyFaction" exact="null"/>
                <set_value name="$cacheSellFaction" exact="null"/>
                <do_if value="$cacheEntry.$BuyOffer? and $cacheEntry.$BuyOffer.owner?">
                  <set_value name="$cacheBuyOwnerContainer" exact="@$cacheEntry.$BuyOffer.owner"/>
                  <do_if value="$cacheBuyOwnerContainer.owner?">
                    <set_value name="$cacheBuyFaction" exact="$cacheBuyOwnerContainer.owner"/>
                  </do_if>
                  <do_else>
                    <set_value name="$cacheBuyFaction" exact="$cacheBuyOwnerContainer"/>
                  </do_else>
                </do_if>
                <do_if value="$cacheEntry.$SellOffer? and $cacheEntry.$SellOffer.owner?">
                  <set_value name="$cacheSellOwnerContainer" exact="@$cacheEntry.$SellOffer.owner"/>
                  <do_if value="$cacheSellOwnerContainer.owner?">
                    <set_value name="$cacheSellFaction" exact="$cacheSellOwnerContainer.owner"/>
                  </do_if>
                  <do_else>
                    <set_value name="$cacheSellFaction" exact="$cacheSellOwnerContainer"/>
                  </do_else>
                </do_if>
                <do_if value="$cacheBuyFaction? and $mk3FactionBlacklist.{$cacheBuyFaction}?">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk3_faction_blacklist_buy'"/>
                </do_if>
                <do_if value="$isValid and $cacheSellFaction? and $mk3FactionBlacklist.{$cacheSellFaction}?">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk3_faction_blacklist_sell'"/>
                </do_if>
              </do_if>
              
              <!-- Debug first few entries -->
              <do_if value="this.$processedCount + $i le 3">
                <!-- Log cache entry with distance information for debugging -->
                <set_value name="$entryHomeToBuy" exact="@$cacheEntry.$HomeToBuyDistance"/>
                <set_value name="$entryHomeToSell" exact="@$cacheEntry.$HomeToSellDistance"/>
                <set_value name="$entryMaxDist" exact="if ($entryHomeToBuy? and $entryHomeToSell? and $entryHomeToBuy ge 0 and $entryHomeToSell ge 0) then [$entryHomeToBuy, $entryHomeToSell].max else -1"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache entry ' + (this.$processedCount + $i) + ': profit=' + (if $shipMaxProfit? then $shipMaxProfit else 'null') + ', minProfit=' + $minAbsoluteProfit + ', roi=' + (if $shipROI? then $shipROI else 'null') + ', minROI=' + $minROI + ', shipMaxAmount=' + (if $shipMaxAmount? then $shipMaxAmount else 'null') + ', homeToBuy=' + (if $entryHomeToBuy? then $entryHomeToBuy else 'null') + ', homeToSell=' + (if $entryHomeToSell? then $entryHomeToSell else 'null') + ', maxDist=' + $entryMaxDist + ', allowed=' + $maxDistance + ', valid=' + $isValid + (if not $isValid then ' reason=' + $rejectReason else '')" chance="100"/>
              </do_if>
              
              <!-- Add to valid trades if all checks passed -->
              <do_if value="$isValid">
                <set_value name="$cacheWorkQuotaWare" exact="if $cacheEntry.$Ware? then $cacheEntry.$Ware else null"/>
                <do_if value="not $cacheWorkQuotaWare? and $cacheEntry.$BuyOffer? and @$cacheEntry.$BuyOffer.ware != null">
                  <set_value name="$cacheWorkQuotaWare" exact="@$cacheEntry.$BuyOffer.ware"/>
                </do_if>
                <do_if value="not $cacheWorkQuotaWare? and $cacheEntry.$SellOffer? and @$cacheEntry.$SellOffer.ware != null">
                  <set_value name="$cacheWorkQuotaWare" exact="@$cacheEntry.$SellOffer.ware"/>
                </do_if>
                <set_value name="$cacheWorkQuotaSkip" exact="false"/>
                <do_if value="$cacheWorkQuotaWare?">
                  <set_value name="$cacheWorkQuotaWareCount" exact="if $cacheWorkFoundPerWare.{$cacheWorkQuotaWare}? then $cacheWorkFoundPerWare.{$cacheWorkQuotaWare} else 0"/>
                  <do_if value="$cacheWorkQuotaWareCount ge $cacheWorkPerWareCap">
                    <set_value name="$cacheWorkQuotaSkip" exact="true"/>
                  </do_if>
                </do_if>
                <do_if value="not $cacheWorkQuotaSkip and $validTrades.count lt $maxTradesToReturn">
                  <append_to_list name="$validTrades" exact="$cacheEntry"/>
                  <do_if value="$cacheWorkQuotaWare?">
                    <set_value name="$cacheWorkFoundPerWare.{$cacheWorkQuotaWare}" exact="if $cacheWorkFoundPerWare.{$cacheWorkQuotaWare}? then ($cacheWorkFoundPerWare.{$cacheWorkQuotaWare} + 1) else 1"/>
                  </do_if>
                  <set_value name="$entryScore" exact="if $cacheEntry.$Score? then $cacheEntry.$Score else (if $shipMaxProfit? then $shipMaxProfit else 0)"/>
                  <!-- Reset per-iteration to avoid carry-over from prior entries (otherwise $bestWasPriority stays true after a non-priority best). -->
                  <set_value name="$cacheIsPriority" exact="false"/>
                  <!-- Apply priority ware score multiplier LAST (same as lib.gt.score.trades) -->
                  <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0 and $cacheEntry.$Ware?">
                    <do_all exact="$effectivePriorityWares.count" counter="$pw">
                      <do_if value="$effectivePriorityWares.{$pw} == $cacheEntry.$Ware">
                        <set_value name="$cacheIsPriority" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                    <do_if value="$cacheIsPriority">
                      <set_value name="$cacheMult" exact="[125, if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 125].max"/>
                      <do_if value="$cacheMult gt 300"><set_value name="$cacheMult" exact="300"/></do_if>
                      <set_value name="$cacheBaseScore" exact="$entryScore"/>
                      <set_value name="$entryScore" exact="$entryScore * ($cacheMult / 100.0)"/>
                      <set_value name="$cachePriorityBoostCount" operation="add"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache priority: ware ' + (if $cacheEntry.$Ware? and $cacheEntry.$Ware != null then @$cacheEntry.$Ware.name else '?') + ' baseScore=' + $cacheBaseScore + ' -> boostedScore=' + $entryScore + ' (mult=' + $cacheMult + '%)'" chance="100"/>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_if value="$entryScore gt $bestScore">
                    <set_value name="$bestTrade" exact="$cacheEntry"/>
                    <set_value name="$bestScore" exact="$entryScore"/>
                    <set_value name="$bestWasPriority" exact="$cacheIsPriority"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <!-- Log rejection reason for first few rejected entries -->
                <do_if value="this.$processedCount + $i le 5 and $rejectReason != ''">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache entry ' + (this.$processedCount + $i) + ' REJECTED: ' + $rejectReason" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
          </do_if>
        </do_all>
        
        <!-- Early exit if we have enough trades -->
        <do_if value="$validTrades.count ge $maxTradesToReturn">
          <break/>
        </do_if>
        
        <set_value name="this.$processedCount" exact="$chunkEnd"/>
        
        <!-- BUG C5 FIX: Unconditional cooperative yield (wait must be top-level in AI scripts, not inside do_if) -->
        <wait exact="this.$gt_yieldMs * 1ms"/>
        <set_value name="$startTime" exact="player.age"/>
        
        <!-- Continue if more to process -->
        <do_if value="this.$processedCount lt $cacheList.count">
          <resume label="cache_work_loop"/>
        </do_if>
      </do_if>
      
      <!-- Signal completion -->
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache search complete: processed=' + this.$processedCount + '/' + $cacheList.count + ', validTrades=' + $validTrades.count + ', bestTrade=' + (if $bestTrade != null then 'found' else 'null') + ', bestScore=' + $bestScore" chance="100"/>
      
      <!-- Debug: summary when priority scoring was applied during cache search -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0 and ($cachePriorityBoostCount gt 0 or $bestWasPriority)">
          <set_value name="$bestWareName" exact="if $bestTrade? and $bestTrade.$Ware? and $bestTrade.$Ware != null then @$bestTrade.$Ware.name else '?'"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache priority summary: priorityBoosted=' + $cachePriorityBoostCount + ' entries, bestTrade ware=' + $bestWareName + ', bestWasPriority=' + $bestWasPriority" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Legacy work-unit completion removed by AI pipeline migration -->
      <!-- CRITICAL: Go to wait_for_response (NOT main_loop) so the AI is in a wait state
           when the MD sends GT_Trade_Found or GT_No_Trade_Found after processing the results.
           Previously resumed to main_loop, which ran synchronously and missed the delayed signal. -->
      <resume label="wait_for_response"/>
      
      <!-- Process live offers work unit -->
      <label name="process_live_offers_workunit"/>
      
      <!-- Extract parameters -->
      <set_value name="$homeSector" exact="@$workUnit.$HomeSector"/>
      <set_value name="$sectors" exact="@$workUnit.$Sectors"/>
      <set_value name="$wareBasket" exact="if $workUnit.$WareBasket? then $workUnit.$WareBasket else []"/>
      <set_value name="$allowIllegal" exact="if $workUnit.$AllowIllegal? then $workUnit.$AllowIllegal else false"/>
      <set_value name="$ignoreBuildStorage" exact="if $workUnit.$IgnoreBuildStorage? then $workUnit.$IgnoreBuildStorage else false"/>
      <set_value name="$ignoreCarrierAux" exact="if $workUnit.$IgnoreCarrierAux? then $workUnit.$IgnoreCarrierAux else false"/>
      <set_value name="$ignoreMK1Supply" exact="if $workUnit.$IgnoreMK1Supply? then $workUnit.$IgnoreMK1Supply else (if $effectiveIgnoreMK1Supply? then @$effectiveIgnoreMK1Supply else true)"/>
      
      <!-- MK4 inline search must also include all reachable offers (no relative-price filtering). -->
      <set_value name="$inlineSellPriceMax" exact="1.0"/>
      <set_value name="$inlineBuyPriceMin" exact="-1.0"/>
      
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Inline PriceRange: SellPriceMax=' + $inlineSellPriceMax + ' BuyPriceMin=' + $inlineBuyPriceMin" chance="@this.$debugchance"/>
      
      <!-- Initialize work state -->
      <!-- Get chunk size from global settings (default: 3 sectors per chunk) -->
      <set_value name="$chunkSize" exact="3"/>
      <!-- Use LiveOfferSliceInterval to determine chunk size (convert ms to sectors) -->
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval?">
        <set_value name="$sliceInterval" exact="@global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval"/>
        <!-- Smaller interval = smaller chunks for smoother performance -->
        <do_if value="$sliceInterval? and $sliceInterval != null">
          <do_if value="$sliceInterval le 100">
            <set_value name="$chunkSize" exact="1"/>
          </do_if>
          <do_elseif value="$sliceInterval le 300">
            <set_value name="$chunkSize" exact="2"/>
          </do_elseif>
          <do_elseif value="$sliceInterval le 500">
            <set_value name="$chunkSize" exact="3"/>
          </do_elseif>
          <do_else>
            <set_value name="$chunkSize" exact="5"/>
          </do_else>
        </do_if>
      </do_if>
      
      <!-- Get max offers per ware from global settings (no fallback â€” missing value = init bug) -->
      <set_value name="$maxOffersPerWare" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
      
      <set_value name="$processedSectors" exact="0"/>
      <set_value name="$sellOffers" exact="[]"/>
      <set_value name="$buyOffers" exact="[]"/>
      
      <!-- Track offers per ware to enforce MaxOffersPerWare limit -->
      <set_value name="$sellOffersPerWare" exact="table[]"/>
      <set_value name="$buyOffersPerWare" exact="table[]"/>
      
      <!-- Process sectors in chunks with frame budgeting -->
      <label name="offers_work_loop"/>
      <set_value name="$startTime" exact="player.age"/>
      <set_value name="$chunkStart" exact="$processedSectors + 1"/>
      <set_value name="$chunkEnd" exact="[$processedSectors + $chunkSize, $sectors.count].min"/>
      
      <do_if value="$chunkStart le $sectors.count">
        <do_all exact="($chunkEnd - $chunkStart + 1)" counter="$i">
          <set_value name="$sectorIndex" exact="$chunkStart + $i - 1"/>
          <set_value name="$sector" exact="$sectors.{$sectorIndex}"/>
          
          <!-- Collect offers from sector -->
          <do_if value="$sector? and $sector.exists">
            <!-- Find sell offers (for buying) -->
            <find_sell_offer tradepartner="this.ship" space="$sector" result="$sectorSellOffers">
              <relativeprice max="$inlineSellPriceMax" tradepartner="if this.ship.isplayerowned then this.ship else null"/>
            </find_sell_offer>
            <do_if value="$sectorSellOffers?">
              <do_all exact="$sectorSellOffers.count" counter="$j">
                <set_value name="$offer" exact="$sectorSellOffers.{$j}"/>
                <set_value name="$isValid" exact="true"/>
                <run_script name="'lib.gt.offer.filters'" result="$offerFilterResult">
                  <param name="offer" value="$offer"/>
                  <param name="wareBasket" value="$wareBasket"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="ignoreBuildStorage" value="$ignoreBuildStorage"/>
                  <param name="ignoreCarrierAux" value="$ignoreCarrierAux"/>
                  <param name="ignoreMK1Supply" value="$ignoreMK1Supply"/>
                </run_script>
                <set_value name="$isValid" exact="if $offerFilterResult? and $offerFilterResult.$Pass? then $offerFilterResult.$Pass else false"/>
                <do_if value="$isValid">
                  <!-- Limit offers per ware -->
                  <set_value name="$ware" exact="@$offer.ware"/>
                  <set_value name="$wareOfferCount" exact="if $sellOffersPerWare.{$ware}? then $sellOffersPerWare.{$ware} else 0"/>
                  <do_if value="$wareOfferCount lt $maxOffersPerWare">
                    <append_to_list name="$sellOffers" exact="$offer"/>
                    <set_value name="$sellOffersPerWare.{$ware}" exact="$wareOfferCount + 1"/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
            
            <!-- Find buy offers (for selling) -->
            <find_buy_offer tradepartner="this.ship" space="$sector" result="$sectorBuyOffers">
              <relativeprice min="$inlineBuyPriceMin" tradepartner="if this.ship.isplayerowned then this.ship else null"/>
            </find_buy_offer>
            <do_if value="$sectorBuyOffers?">
              <do_all exact="$sectorBuyOffers.count" counter="$j">
                <set_value name="$offer" exact="$sectorBuyOffers.{$j}"/>
                <set_value name="$isValid" exact="true"/>
                <run_script name="'lib.gt.offer.filters'" result="$offerFilterResult">
                  <param name="offer" value="$offer"/>
                  <param name="wareBasket" value="$wareBasket"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="ignoreBuildStorage" value="$ignoreBuildStorage"/>
                  <param name="ignoreCarrierAux" value="$ignoreCarrierAux"/>
                  <param name="ignoreMK1Supply" value="$ignoreMK1Supply"/>
                </run_script>
                <set_value name="$isValid" exact="if $offerFilterResult? and $offerFilterResult.$Pass? then $offerFilterResult.$Pass else false"/>
                <do_if value="$isValid">
                  <!-- Limit offers per ware -->
                  <set_value name="$ware" exact="@$offer.ware"/>
                  <set_value name="$wareOfferCount" exact="if $buyOffersPerWare.{$ware}? then $buyOffersPerWare.{$ware} else 0"/>
                  <do_if value="$wareOfferCount lt $maxOffersPerWare">
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$ware}" exact="$wareOfferCount + 1"/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
        </do_all>
        
        <set_value name="$processedSectors" exact="$chunkEnd"/>
        
        <!-- BUG C5 FIX: Unconditional cooperative yield (wait must be top-level in AI scripts, not inside do_if) -->
        <wait exact="this.$gt_yieldMs * 1ms"/>
        <set_value name="$startTime" exact="player.age"/>
        
        <!-- Continue if more to process -->
        <do_if value="$processedSectors lt $sectors.count">
          <resume label="offers_work_loop"/>
        </do_if>
      </do_if>
      
      <!-- Legacy MD filter roundtrip removed by AI pipeline migration -->
      <set_value name="$filteredResult" exact="table[$SellOffers = $sellOffers, $BuyOffers = $buyOffers]"/>
      <!-- Legacy work-unit completion removed by AI pipeline migration -->
      <!-- CRITICAL: Go to wait_for_response so AI catches MD's GT_Trade_Found/GT_No_Trade_Found -->
      <resume label="wait_for_response"/>
      
      <!-- Process trade matching work unit -->
      <label name="process_trade_matching_workunit"/>
      
      <!-- Extract parameters -->
      <set_value name="$sellOffers" exact="@$workUnit.$SellOffers"/>
      <set_value name="$buyOffers" exact="@$workUnit.$BuyOffers"/>
      <set_value name="$homeSector" exact="@$workUnit.$HomeSector"/>
      <set_value name="$minROI" exact="0"/>
      <set_value name="$minAbsoluteProfit" exact="0"/>
      <set_value name="$distancePenaltyMultiplier" exact="if $workUnit.$DistancePenaltyMultiplier? then $workUnit.$DistancePenaltyMultiplier else 0.5"/>
      
      <!-- Resolve priority wares + multiplier ONCE per workunit so the per-pair scoring below can apply
           the same boost the cache_work_loop already applies. Without this, fleets with priority wares
           configured got priority ordering on cache hits but distance-optimized / priority-blind ordering
           when the live/matching pipeline produced the trade (see DOCS/MK3_PIPELINE_REFACTOR.md Â§3.10). -->
      <run_script name="'lib.gt.priority_wares.resolve'" result="$matchPriorityWares">
        <param name="instanceWares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else null"/>
        <param name="ship" value="this.ship"/>
        <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply']"/>
      </run_script>
      <set_value name="$matchPriorityMult" exact="if this.$effectivePriorityScoreMultiplier? then [125, this.$effectivePriorityScoreMultiplier].max else 125"/>
      <do_if value="$matchPriorityMult gt 300"><set_value name="$matchPriorityMult" exact="300"/></do_if>
      <set_value name="$matchPriorityBoostCount" exact="0"/>
      
      <!-- Initialize work state -->
      <!-- Get chunk size from global settings (default: 10 trade pairs per chunk) -->
      <set_value name="$chunkSize" exact="10"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$BatchChunkSize?">
        <set_value name="$tmpChunk" exact="@global.$GT_GlobalSettings.$Performance.$BatchChunkSize"/>
        <do_if value="$tmpChunk? and $tmpChunk != null and $tmpChunk gt 0">
          <!-- BatchChunkSize is for offers, scale for trade pairs (roughly square) -->
          <set_value name="$chunkSize" exact="$tmpChunk * 2"/>
        </do_if>
      </do_if>
      <!-- Clamp to reasonable bounds -->
      <do_if value="$chunkSize lt 5">
        <set_value name="$chunkSize" exact="5"/>
      </do_if>
      <do_if value="$chunkSize gt 50">
        <set_value name="$chunkSize" exact="50"/>
      </do_if>
      
      <!-- Get max trades per ware from global settings -->
      <set_value name="$maxTradesPerWare" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
        <set_value name="$tmpMax" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
        <do_if value="$tmpMax? and $tmpMax != null and $tmpMax gt 0">
          <set_value name="$maxTradesPerWare" exact="$tmpMax"/>
        </do_if>
      </do_if>
      
      <!-- Get early exit threshold from global settings -->
      <set_value name="$earlyExitThreshold" exact="2000"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold?">
        <set_value name="$tmpThreshold" exact="@global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold"/>
        <do_if value="$tmpThreshold? and $tmpThreshold != null and $tmpThreshold gt 0">
          <set_value name="$earlyExitThreshold" exact="$tmpThreshold"/>
        </do_if>
      </do_if>
      
      <set_value name="$processedPairs" exact="0"/>
      <set_value name="$validTrades" exact="[]"/>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>
      
      <!-- Initialize rejection counters for logging -->
      <set_value name="$profitRejectionCount" exact="0"/>
      <set_value name="$roiRejectionCount" exact="0"/>
      
      <!-- Get max offers per ware for matching from global settings -->
      <set_value name="$maxOffersPerWareForMatching" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching?">
        <set_value name="$tmpMaxOffers" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching"/>
        <do_if value="$tmpMaxOffers? and $tmpMaxOffers != null and $tmpMaxOffers gt 0">
          <set_value name="$maxOffersPerWareForMatching" exact="$tmpMaxOffers"/>
        </do_if>
      </do_if>
      
      <!-- Track trades per ware for limiting -->
      <set_value name="$tradesPerWare" exact="table[]"/>
      
      <!-- Index offers by ware (simplified - no MD library call) -->
      <!-- Limit offers per ware using MaxOffersPerWareForMatching -->
      <!-- FIX: Validate offers are available before indexing (prevents NULL owner/price issues) -->
      <set_value name="$sellOffersByWare" exact="table[]"/>
      <do_all exact="$sellOffers.count" counter="$i">
        <set_value name="$offer" exact="$sellOffers.{$i}"/>
        <!-- Validate offer exists and is available before indexing -->
        <do_if value="$offer? and $offer.available">
          <set_value name="$ware" exact="@$offer.ware"/>
          <do_if value="$ware?">
            <do_if value="not $sellOffersByWare.{$ware}?">
              <set_value name="$sellOffersByWare.{$ware}" exact="[]"/>
            </do_if>
            <!-- Limit offers per ware -->
            <do_if value="$sellOffersByWare.{$ware}.count lt $maxOffersPerWareForMatching">
              <append_to_list name="$sellOffersByWare.{$ware}" exact="$offer"/>
            </do_if>
          </do_if>
        </do_if>
      </do_all>
      
      <set_value name="$buyOffersByWare" exact="table[]"/>
      <do_all exact="$buyOffers.count" counter="$i">
        <set_value name="$offer" exact="$buyOffers.{$i}"/>
        <!-- Validate offer exists and is available before indexing -->
        <do_if value="$offer? and $offer.available">
          <set_value name="$ware" exact="@$offer.ware"/>
          <do_if value="$ware?">
            <do_if value="not $buyOffersByWare.{$ware}?">
              <set_value name="$buyOffersByWare.{$ware}" exact="[]"/>
            </do_if>
            <!-- Limit offers per ware -->
            <do_if value="$buyOffersByWare.{$ware}.count lt $maxOffersPerWareForMatching">
              <append_to_list name="$buyOffersByWare.{$ware}" exact="$offer"/>
            </do_if>
          </do_if>
        </do_if>
      </do_all>
      
      <!-- OPTIMIZATION: Lazy pair generation - generate pairs on-demand instead of upfront -->
      <!-- Get list of wares that have both sell and buy offers -->
      <set_value name="$wareKeys" exact="[]"/>
      <do_all exact="$sellOffersByWare.keys.count" counter="$i">
        <set_value name="$ware" exact="$sellOffersByWare.keys.{$i}"/>
        <do_if value="$buyOffersByWare.{$ware}? and $buyOffersByWare.{$ware}.count gt 0">
          <append_to_list name="$wareKeys" exact="$ware"/>
        </do_if>
      </do_all>
      
      <!-- Initialize lazy generation state -->
      <set_value name="this.$currentWareIndex" exact="0"/>
      <set_value name="this.$currentSellIndex" exact="0"/>
      <set_value name="this.$currentBuyIndex" exact="0"/>
      
      <!-- Process trade pairs in chunks with frame budgeting (lazy generation) -->
      <label name="matching_work_loop"/>
      <set_value name="$startTime" exact="player.age"/>
      <set_value name="$pairsProcessedThisChunk" exact="0"/>
      
      <!-- Generate and process pairs on-demand -->
      <do_if value="$wareKeys.count gt 0">
        <do_while value="$pairsProcessedThisChunk lt $chunkSize and (this.$currentWareIndex lt $wareKeys.count)">
        <!-- Check early exit threshold -->
        <do_if value="$validTrades.count ge $earlyExitThreshold">
          <break/>
        </do_if>
        
        <!-- Get current ware with safe access -->
        <set_value name="$ware" exact="@$wareKeys.{this.$currentWareIndex}"/>
        <do_if value="not $ware?">
          <!-- Invalid ware index, skip to next -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
          <continue/>
        </do_if>
        
        <!-- Validate lists exist and have items before accessing -->
        <set_value name="$listsValid" exact="false"/>
        <do_if value="$sellOffersByWare.{$ware}?">
          <do_if value="$buyOffersByWare.{$ware}?">
            <set_value name="$sellList" exact="$sellOffersByWare.{$ware}"/>
            <set_value name="$buyList" exact="$buyOffersByWare.{$ware}"/>
            <do_if value="$sellList.count gt 0">
              <do_if value="$buyList.count gt 0">
                <set_value name="$listsValid" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        
        <do_if value="not $listsValid">
          <!-- Invalid lists, skip to next ware -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
          <continue/>
        </do_if>
        
        <!-- At this point, $sellList and $buyList are guaranteed to be set and valid -->
        
        <!-- Check if current ware is complete (reached MaxTradesPerWare limit) -->
        <set_value name="$wareTradeCount" exact="if $tradesPerWare.{$ware}? then $tradesPerWare.{$ware} else 0"/>
        <do_if value="$wareTradeCount ge $maxTradesPerWare">
          <!-- OPTIMIZATION: Early termination per ware - skip to next ware immediately -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
          <continue/>
        </do_if>
        
        <!-- Generate next pair on-demand -->
        <do_if value="$listsValid and this.$currentSellIndex lt $sellList.count and this.$currentBuyIndex lt $buyList.count">
          <set_value name="$sellOffer" exact="@$sellList.{this.$currentSellIndex}"/>
          <set_value name="$buyOffer" exact="@$buyList.{this.$currentBuyIndex}"/>
          
          <!-- Validate offers exist AND are available (prevents NULL owner/price issues) -->
          <!-- FIX: Check offer.available - offers can exist but not be available, causing NULL owner/price -->
          <do_if value="$sellOffer? and $buyOffer? and $sellOffer.available and $buyOffer.available">
            <!-- OPTIMIZATION: Quick profit pre-filtering before full evaluation -->
            <!-- FIX: Use unitprice (price per unit) instead of price (total price) - price is total for entire offer amount -->
            <set_value name="$buyPrice" exact="@$sellOffer.unitprice"/>
            <set_value name="$sellPrice" exact="@$buyOffer.unitprice"/>
            <set_value name="$profitPerUnit" exact="$sellPrice - $buyPrice"/>
            <set_value name="$amount" exact="[@$sellOffer.amount, @$buyOffer.amount].min"/>
            <set_value name="$quickProfit" exact="$profitPerUnit * $amount"/>
            
            <!-- Increment processed pairs counter -->
            <set_value name="$processedPairs" exact="$processedPairs + 1"/>
            
            <!-- Quick profit check - skip if can't meet minimum -->
            <do_if value="$quickProfit ge $minAbsoluteProfit">
              <!-- Full evaluation -->
              <!-- Calculate ROI -->
              <set_value name="$investment" exact="$buyPrice * $amount"/>
              <set_value name="$roi" exact="if $investment gt 0 then (($quickProfit * 100) / $investment) else 0"/>
              
              <do_if value="$roi ge $minROI">
                <!-- Simplified distance calculation (use sector distance if available) -->
                <set_value name="$buyDistance" exact="0"/>
                <set_value name="$sellDistance" exact="0"/>
                <do_if value="$sellOffer.owner? and $sellOffer.owner.sector? and $homeSector?">
                  <set_value name="$buySector" exact="$sellOffer.owner.sector"/>
                  <do_if value="$buySector != $homeSector">
                    <set_value name="$buyDistance" exact="1"/> <!-- Simplified - assume 1 jump if different sector -->
                  </do_if>
                </do_if>
                <do_if value="$buyOffer.owner? and $buyOffer.owner.sector? and $homeSector?">
                  <set_value name="$sellSector" exact="$buyOffer.owner.sector"/>
                  <do_if value="$sellSector != $homeSector">
                    <set_value name="$sellDistance" exact="1"/> <!-- Simplified - assume 1 jump if different sector -->
                  </do_if>
                </do_if>
                
                <set_value name="$totalDistance" exact="$buyDistance + $sellDistance"/>
                <set_value name="$distancePenalty" exact="$totalDistance * $distancePenaltyMultiplier * 100"/> <!-- Scale penalty -->
                <set_value name="$baseScore" exact="$quickProfit - $distancePenalty"/>
                <!-- Priority-ware boost: mirrors cache_work_loop so cache vs matching pipelines order trades
                     consistently when the user has priority wares configured (see Â§3.10). -->
                <set_value name="$matchIsPriority" exact="false"/>
                <do_if value="$matchPriorityWares? and $matchPriorityWares.count gt 0 and $ware? and $matchPriorityWares.indexof.{$ware}">
                  <set_value name="$matchIsPriority" exact="true"/>
                </do_if>
                <do_if value="$matchIsPriority">
                  <set_value name="$score" exact="$baseScore * ($matchPriorityMult / 100.0)"/>
                  <set_value name="$matchPriorityBoostCount" exact="$matchPriorityBoostCount + 1"/>
                </do_if>
                <do_else>
                  <set_value name="$score" exact="$baseScore"/>
                </do_else>
                
                <!-- Check trades per ware limit -->
                <do_if value="$wareTradeCount lt $maxTradesPerWare">
                  <!-- Create trade entry -->
                  <!-- FIX: Store BuyPrice and SellPrice in trade object for profit recalculation -->
                  <set_value name="$trade" exact="table[
                    $BuyOffer = $sellOffer,
                    $SellOffer = $buyOffer,
                    $BuyPrice = $buyPrice,
                    $SellPrice = $sellPrice,
                    $Profit = $quickProfit,
                    $ROI = $roi,
                    $Amount = $amount,
                    $Score = $score,
                    $Distance = $totalDistance,
                    $IsPriority = $matchIsPriority,
                    $Ware = $ware
                  ]"/>
                  
                  <append_to_list name="$validTrades" exact="$trade"/>
                  <set_value name="$tradesPerWare.{$ware}" exact="$wareTradeCount + 1"/>
                  
                  <!-- Track best trade -->
                  <do_if value="$score gt $bestScore">
                    <set_value name="$bestTrade" exact="$trade"/>
                    <set_value name="$bestScore" exact="$score"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <!-- ROI check failed - log first few rejections -->
                <set_value name="$roiRejectionCount" exact="$roiRejectionCount + 1"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $roiRejectionCount le 10">
                  <set_value name="$wareName" exact="if $ware? then @$ware.name else 'NULL'"/>
                  <set_value name="$buyStationName" exact="if $sellOffer.owner? then @$sellOffer.owner.knownname else 'NULL'"/>
                  <set_value name="$sellStationName" exact="if $buyOffer.owner? then @$buyOffer.owner.knownname else 'NULL'"/>
                  <debug_text text="'[GT-AI-TradeMatching] ' + this.ship.idcode + ': Pair REJECTED (ROI): #' + $roiRejectionCount +
                    '\n  Ware: ' + $wareName +
                    '\n  Buy: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr' +
                    '\n  Sell: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr' +
                    '\n  ProfitPerUnit: ' + ($profitPerUnit/100) + ' Cr' +
                    '\n  Amount: ' + $amount + ' units' +
                    '\n  QuickProfit: ' + ($quickProfit/100) + ' Cr' +
                    '\n  Investment: ' + ($investment/100) + ' Cr' +
                    '\n  ROI: ' + $roi + '%' +
                    '\n  MinROI: ' + $minROI + '%'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <!-- Quick profit check failed - log first few rejections -->
              <set_value name="$profitRejectionCount" exact="$profitRejectionCount + 1"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $profitRejectionCount le 10">
                <set_value name="$wareName" exact="if $ware? then @$ware.name else 'NULL'"/>
                <set_value name="$buyStationName" exact="if $sellOffer.owner? then @$sellOffer.owner.knownname else 'NULL'"/>
                <set_value name="$sellStationName" exact="if $buyOffer.owner? then @$buyOffer.owner.knownname else 'NULL'"/>
                <debug_text text="'[GT-AI-TradeMatching] ' + this.ship.idcode + ': Pair REJECTED (profit): #' + $profitRejectionCount +
                  '\n  Ware: ' + $wareName +
                  '\n  Buy: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr' +
                  '\n  Sell: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr' +
                  '\n  ProfitPerUnit: ' + ($profitPerUnit/100) + ' Cr' +
                  '\n  Amount: ' + $amount + ' units' +
                  '\n  QuickProfit: ' + ($quickProfit/100) + ' Cr' +
                  '\n  MinProfit: ' + ($minAbsoluteProfit/100) + ' Cr'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          
          <!-- Advance to next pair -->
          <set_value name="this.$currentBuyIndex" exact="this.$currentBuyIndex + 1"/>
          <do_if value="this.$currentBuyIndex ge $buyList.count">
            <set_value name="this.$currentBuyIndex" exact="0"/>
            <set_value name="this.$currentSellIndex" exact="this.$currentSellIndex + 1"/>
            <do_if value="this.$currentSellIndex ge $sellList.count">
              <!-- Move to next ware -->
              <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
              <set_value name="this.$currentSellIndex" exact="0"/>
              <set_value name="this.$currentBuyIndex" exact="0"/>
            </do_if>
          </do_if>
          
          <set_value name="$pairsProcessedThisChunk" exact="$pairsProcessedThisChunk + 1"/>
        </do_if>
        <do_else>
          <!-- Current ware exhausted, move to next -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
        </do_else>
        </do_while>
      </do_if>
      
      <!-- BUG C5 FIX: Unconditional cooperative yield (wait must be top-level in AI scripts, not inside do_if) -->
      <wait exact="this.$gt_yieldMs * 1ms"/>
      <set_value name="$startTime" exact="player.age"/>
      
      <!-- Continue if more to process -->
      <do_if value="this.$currentWareIndex lt $wareKeys.count">
        <resume label="matching_work_loop"/>
      </do_if>
      
      <!-- Signal completion -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI-TradeMatching] ' + this.ship.idcode + ': Trade matching complete:' +
          '\n  ProcessedPairs: ' + $processedPairs +
          '\n  ValidTrades: ' + $validTrades.count +
          '\n  BestTrade: ' + (if $bestTrade != null then 'found' else 'null') +
          '\n  BestScore: ' + $bestScore +
          '\n  WareKeys: ' + $wareKeys.count +
          '\n  PriorityBoosts: ' + $matchPriorityBoostCount + ' (mult=' + $matchPriorityMult + '%, sources=' + (if $matchPriorityWares? then $matchPriorityWares.count else 0) + ')' +
          '\n  Rejected (profit): ' + $profitRejectionCount +
          '\n  Rejected (ROI): ' + $roiRejectionCount" chance="100"/>
      </do_if>
      <!-- Legacy work-unit completion removed by AI pipeline migration -->
      <!-- CRITICAL: Go to wait_for_response so AI catches MD's GT_Trade_Found/GT_No_Trade_Found -->
      <resume label="wait_for_response"/>
      
    </actions>
  </attention>
  
  <on_abort>
    <!-- Intentional handoff: idle parking delegates to GTIdlePark for visible queued docking. -->
    <set_value name="$isIdleParkHandoff" exact="false"/>
    <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.orders.count gt 0">
      <do_all exact="this.ship.orders.count" counter="$ipoi">
        <set_value name="$ipOrder" exact="this.ship.orders.{$ipoi}"/>
        <do_if value="@$ipOrder.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_if>
        <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_elseif>
      </do_all>
    </do_if>
    <do_if value="$isIdleParkHandoff">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': on_abort skipped (handoff to GTIdlePark)'" chance="100"/>
      </do_if>
      <return/>
    </do_if>

    <!-- Release new scheduler semaphore slot if this ship aborts mid-search -->
    <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>

    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
      <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
    </do_if>

    <!-- Release fleet reservation if ship aborts with an active reservation.
         Restored from pre-migration reservation flow: prevents stale reservations blocking fleet. -->
    <do_if value="this.$activeReservationKey? and global.$GT_Reservations? and global.$GT_Reservations.{this.$activeReservationKey}?">
      <remove_value name="global.$GT_Reservations.{this.$activeReservationKey}"/>
      <do_if value="global.$GT_ReservationStats? and global.$GT_ReservationStats.$Active gt 0">
        <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
      </do_if>
      <do_if value="global.$GT_ReservationStats?">
        <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
      </do_if>
    </do_if>

    <!-- Clear stale clearance naming flag on order abort only when cargo is actually empty.
         Keep [CLEARANCE]/CL during active disposal with remaining cargo. -->
    <do_if value="this.ship.cargo.count == 0 and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
      <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship = this.ship,
          $pilot = this.ship.pilot,
          $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType = 'trader'
        ]"/>
      </do_if>
    </do_if>

    <!-- Enhanced cleanup when order is aborted/replaced -->
    <!-- Preserve pilot XP data when order is manually replaced by player -->
    <!-- Only completely wipe data in genuine cleanup scenarios (ship destroyed, pilot changed, etc.) -->
    <set_value name="$isActivelyTrading" exact="false"/>
    <set_value name="$isTrainingTransition" exact="false"/>
    
    <!-- Clean up resupply tracking if order aborted mid-resupply -->
    <!-- IMPORTANT: Do NOT clear during maintenance transitions (subordinates can be aborted/replaced while resupply order is active) -->
    <do_if value="not this.$maintenance_transition? and global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
      <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleaned up resupply tracking on order abort'" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Check if ship has active TradePerform orders -->
    <do_if value="this.ship.orders.count gt 1">
      <do_all exact="this.ship.orders.count" counter="$i">
        <do_if value="this.ship.orders.{$i}.id == 'TradePerform'">
          <set_value name="$isActivelyTrading" exact="true"/>
          <break/>
        </do_if>
      </do_all>
    </do_if>
    
    <!-- Check if a training order was recently created (within last 5 seconds) -->
    <do_if value="this.$training_order_created? and (player.age - this.$training_order_created) lt 5s">
      <set_value name="$isTrainingTransition" exact="true"/>
    </do_if>
    
    <!-- Also check the flag-based detection -->
    <do_if value="this.$training_transition?">
      <set_value name="$isTrainingTransition" exact="true"/>
    </do_if>
    
    <!-- Check if a maintenance order was recently created (repair/resupply) -->
    <set_value name="$isMaintenanceTransition" exact="false"/>
    <do_if value="this.$maintenance_transition?">
      <set_value name="$isMaintenanceTransition" exact="true"/>
    </do_if>
    
    <!-- Ship state and orders at removal detection -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$debugShip" exact="this.ship"/>
      <set_value name="$debugDefaultOrder" exact="@$debugShip.defaultorder.id"/>
      <set_value name="$debugCommander" exact="@$debugShip.commander"/>
      <set_value name="$debugCommanderId" exact="if @$debugCommander.exists then @$debugCommander.idcode else 'NONE'"/>
      <set_value name="$debugCommanderOrder" exact="if @$debugCommander.exists and @$debugCommander.defaultorder != null then @$debugCommander.defaultorder.id else 'NONE'"/>
      <set_value name="$debugPilot" exact="@$debugShip.pilot"/>
      <set_value name="$debugPilotName" exact="if $debugPilot != null then @$debugPilot.knownname else 'NONE'"/>
      
      <!-- Build orders list -->
      <set_value name="$debugOrdersList" exact="[]"/>
      <set_value name="$debugOrdersCount" exact="$debugShip.orders.count"/>
      <do_all exact="$debugOrdersCount" counter="$i">
        <set_value name="$orderId" exact="@$debugShip.orders.{$i}.id"/>
        <append_to_list name="$debugOrdersList" exact="if $orderId then $orderId else 'UNKNOWN'"/>
      </do_all>
      <set_value name="$debugOrdersStr" exact="if $debugOrdersList.count gt 0 then $debugOrdersList.{1} + (if $debugOrdersList.count gt 1 then ', ' + $debugOrdersList.{2} else '') + (if $debugOrdersList.count gt 2 then ', ' + $debugOrdersList.{3} else '') + (if $debugOrdersList.count gt 3 then ', ' + $debugOrdersList.{4} else '') + (if $debugOrdersList.count gt 4 then ', ...' else '') else 'NONE'"/>
      
      <!-- Check GT order status -->
      <set_value name="$debugHasDirectGT" exact="false"/>
      <do_if value="$debugDefaultOrder == 'GalaxyTraderMK3' or $debugDefaultOrder == 'GalaxyTraderMK4Supply'">
        <set_value name="$debugHasDirectGT" exact="true"/>
      </do_if>
      <set_value name="$debugHasGTCommander" exact="false"/>
      <do_if value="@$debugCommander.exists and ($debugCommanderOrder == 'GalaxyTraderMK3' or $debugCommanderOrder == 'GalaxyTraderMK4Supply')">
        <set_value name="$debugHasGTCommander" exact="true"/>
      </do_if>
      
      <!-- Check if in GT_Ships registry -->
      <set_value name="$debugInRegistry" exact="global.$GT_Ships? and global.$GT_Ships.{$debugShip}?"/>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] REMOVAL DETECTION DEBUG: ' + $debugShip.idcode + ' - COMPREHENSIVE STATE'" chance="100"/>
        <debug_text text="'[GT-AI]   Ship: ' + $debugShip.idcode + ' (' + (if $debugShip.knownname then $debugShip.knownname else 'UNNAMED') + ')'" chance="100"/>
        <debug_text text="'[GT-AI]   Pilot: ' + $debugPilotName + (if $debugPilot != null then ' (exists)' else ' (NONE)')" chance="100"/>
        <debug_text text="'[GT-AI]   Default Order: ' + (if $debugDefaultOrder then $debugDefaultOrder else 'NONE')" chance="100"/>
        <debug_text text="'[GT-AI]   Active Orders (' + $debugOrdersCount + '): ' + $debugOrdersStr" chance="100"/>
        <debug_text text="'[GT-AI]   Commander: ' + $debugCommanderId + ' (Order: ' + $debugCommanderOrder + ')'" chance="100"/>
        <debug_text text="'[GT-AI]   GT Status: Direct=' + $debugHasDirectGT + ', ViaCommander=' + $debugHasGTCommander + ', InRegistry=' + $debugInRegistry" chance="100"/>
        <debug_text text="'[GT-AI]   Flags: ActivelyTrading=' + $isActivelyTrading + ', TrainingTransition=' + $isTrainingTransition + ', MaintenanceTransition=' + $isMaintenanceTransition" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Order cancellation detection -->
    <!-- Only send signal if GT default order is actually cancelled -->
    <!-- on_abort can fire when trade orders are cancelled, but GT order might still be active -->
    <!-- Unified GT order status check (inline for AI scripts) -->
    <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
    <set_value name="$hasDirectGTOrder" exact="false"/>
    <set_value name="$hasGTCommander" exact="false"/>
    <set_value name="$isGTControlled" exact="false"/>
    
    <!-- Check direct GT order -->
    <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply'">
      <set_value name="$hasDirectGTOrder" exact="true"/>
      <set_value name="$isGTControlled" exact="true"/>
    </do_if>
    
    <!-- Check commander status -->
    <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
      <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
        <set_value name="$hasGTCommander" exact="true"/>
        <do_if value="$currentDefaultOrder == 'Assist'">
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
      </do_if>
    </do_if>
    
    <set_value name="$isGTOrderCancelled" exact="false"/>
    
    <!-- If GT order is gone, process cleanup REGARDLESS of training/maintenance transitions -->
    <!-- Only skip Phase 7 if GT order is STILL ACTIVE AND there's a training/maintenance transition -->
    <do_if value="not $isGTControlled and $currentDefaultOrder != 'Assist'">
      <!-- GT order is gone - process cleanup even if training/maintenance/disposal orders exist -->
      <!-- Check if GT default order is still active -->
      <!-- If defaultorder.id is null, different, or not GalaxyTraderMK3/GalaxyTraderMK4Supply, GT order was cancelled -->
      <do_if value="not $currentDefaultOrder">
        <!-- No default order â†’ GT order was cancelled -->
        <set_value name="$isGTOrderCancelled" exact="true"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: NONE)'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'GT_Order_Cancelled'
        ]"/>
        
        <!-- EVENT-DRIVEN: Trigger orphaned ship check -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
          <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
        </do_if>
        
        <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
        <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
        <!-- Use this.$was_subordinate flag or check state manager state -->
        <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
        <do_if value="this.$was_subordinate?">
          <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
          <!-- Check state manager to see if ship was a subordinate -->
          <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship is CURRENTLY subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$isSubordinateOfGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Restore name if:
             1. Ship was NOT a subordinate before cancellation, OR
             2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
        <set_value name="$shouldRestoreName" exact="false"/>
        <do_if value="not $wasSubordinateBeforeCancellation">
          <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
          <do_if value="not $isSubordinateOfGTCommander">
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
          <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_elseif>
        
        <do_if value="$shouldRestoreName and this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'GT order cancelled - restoring original name',
              $OriginalName = $originalName
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="$currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply'">
        <!-- Different default order â†’ Check if GT order was actually cancelled -->
        <!-- For subordinates with Assist order, trade order termination is NORMAL -->
        <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
        <set_value name="$actualDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <!-- Check if ship has direct GT order -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <do_if value="$actualDefaultOrder == 'GalaxyTraderMK3' or $actualDefaultOrder == 'GalaxyTraderMK4Supply'">
          <set_value name="$hasDirectGTOrder" exact="true"/>
        </do_if>
        
        <!-- Check if ship is subordinate to GT commander (current commander, not old) -->
        <set_value name="$hasGTCommander" exact="false"/>
        <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$hasGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
        <!-- For subordinates, Assist order termination is handled by Assist order's on_abort -->
        <!-- Trade order termination is NORMAL and should NOT trigger cleanup -->
        <set_value name="$shouldEmitCleanup" exact="false"/>
        <do_if value="not $hasDirectGTOrder and not $hasGTCommander and $currentDefaultOrder != 'Assist'">
          <!-- No direct GT order and no GT commander = GT order truly gone -->
          <set_value name="$shouldEmitCleanup" exact="true"/>
        </do_if>
        
        <!-- Emit cleanup signal if GT order is gone -->
        <do_if value="$shouldEmitCleanup">
          <set_value name="$isGTOrderCancelled" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ')'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI]  PHASE 7: Trade order aborted but GT order still active for ' + this.ship.idcode + ' (default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ') - NOT sending GT_Order_Cancelled'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
        <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
        <!-- Use this.$was_subordinate flag or check state manager state -->
        <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
        <do_if value="this.$was_subordinate?">
          <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
          <!-- Check state manager to see if ship was a subordinate -->
          <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship is CURRENTLY subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
            <set_value name="$isSubordinateOfGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Restore name if:
             1. Ship was NOT a subordinate before cancellation, OR
             2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
        <set_value name="$shouldRestoreName" exact="false"/>
        <do_if value="not $wasSubordinateBeforeCancellation">
          <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
          <do_if value="not $isSubordinateOfGTCommander">
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
          <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_elseif>
        
        <do_if value="$shouldRestoreName and this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'GT order cancelled - restoring original name',
              $OriginalName = $originalName
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_elseif>
    </do_if>
    <do_elseif value="$hasDirectGTOrder or $hasGTCommander">
      <!-- GT order still active - only skip Phase 7 if there's a training/maintenance transition -->
      <!-- This prevents cleanup when GT order creates training/maintenance orders (normal behavior) -->
      <do_if value="not $isTrainingTransition and not $isMaintenanceTransition">
        <!-- GT order active, no transitions - check if default order changed -->
        <!-- (This is the original Phase 7 logic for when GT order is still active) -->
        <!-- Check if GT default order is still active -->
        <!-- If defaultorder.id is null, different, or not GalaxyTraderMK3/GalaxyTraderMK4Supply, GT order was cancelled -->
        <do_if value="not $currentDefaultOrder">
          <!-- No default order â†’ GT order was cancelled -->
          <set_value name="$isGTOrderCancelled" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: NONE)'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
          
          <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
          <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
          <!-- Use this.$was_subordinate flag or check state manager state -->
          <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
          <do_if value="this.$was_subordinate?">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
            <!-- Check state manager to see if ship was a subordinate -->
            <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
            <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
              <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
            </do_if>
          </do_elseif>
          
          <!-- Check if ship is CURRENTLY subordinate to GT commander -->
          <set_value name="$isSubordinateOfGTCommander" exact="false"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
              <set_value name="$isSubordinateOfGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Restore name if:
               1. Ship was NOT a subordinate before cancellation, OR
               2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
          <set_value name="$shouldRestoreName" exact="false"/>
          <do_if value="not $wasSubordinateBeforeCancellation">
            <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
            <do_if value="not $isSubordinateOfGTCommander">
              <set_value name="$shouldRestoreName" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
            <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_elseif>
          
          <do_if value="$shouldRestoreName and this.ship.pilot?">
            <set_value name="$originalName" exact="null"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
            </do_if>
            
            <do_if value="$originalName">
              <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $Reason = 'GT order cancelled - restoring original name',
                $OriginalName = $originalName
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply'">
          <!-- Different default order â†’ Check if GT order was actually cancelled -->
          <!-- For subordinates with Assist order, trade order termination is NORMAL -->
          <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
          <set_value name="$actualDefaultOrder" exact="@this.ship.defaultorder.id"/>
          
          <!-- Check if ship has direct GT order -->
          <set_value name="$hasDirectGTOrder" exact="false"/>
          <do_if value="$actualDefaultOrder == 'GalaxyTraderMK3' or $actualDefaultOrder == 'GalaxyTraderMK4Supply'">
            <set_value name="$hasDirectGTOrder" exact="true"/>
          </do_if>
          
          <!-- Check if ship is subordinate to GT commander (current commander, not old) -->
          <set_value name="$hasGTCommander" exact="false"/>
          <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
              <set_value name="$hasGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
          <!-- For subordinates, Assist order termination is handled by Assist order's on_abort -->
          <!-- Trade order termination is NORMAL and should NOT trigger cleanup -->
          <set_value name="$shouldEmitCleanup" exact="false"/>
          <do_if value="not $hasDirectGTOrder and not $hasGTCommander">
            <!-- No direct GT order and no GT commander = GT order truly gone -->
            <set_value name="$shouldEmitCleanup" exact="true"/>
          </do_if>
          
          <!-- Emit cleanup signal if GT order is gone -->
          <do_if value="$shouldEmitCleanup">
            <set_value name="$isGTOrderCancelled" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ')'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI]  PHASE 7: Trade order aborted but GT order still active for ' + this.ship.idcode + ' (default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ') - NOT sending GT_Order_Cancelled'" chance="100"/>
            </do_if>
          </do_else>
          
          <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
          <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
          <!-- Use this.$was_subordinate flag or check state manager state -->
          <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
          <do_if value="this.$was_subordinate?">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
            <!-- Check state manager to see if ship was a subordinate -->
            <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
            <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
              <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
            </do_if>
          </do_elseif>
          
          <!-- Check if ship is CURRENTLY subordinate to GT commander -->
          <set_value name="$isSubordinateOfGTCommander" exact="false"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply')))">
              <set_value name="$isSubordinateOfGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Restore name if:
               1. Ship was NOT a subordinate before cancellation, OR
               2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
          <set_value name="$shouldRestoreName" exact="false"/>
          <do_if value="not $wasSubordinateBeforeCancellation">
            <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
            <do_if value="not $isSubordinateOfGTCommander">
              <set_value name="$shouldRestoreName" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
            <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_elseif>
          
          <do_if value="$shouldRestoreName and this.ship.pilot?">
            <set_value name="$originalName" exact="null"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
            </do_if>
            
            <do_if value="$originalName">
              <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $Reason = 'GT order cancelled - restoring original name',
                $OriginalName = $originalName
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_elseif>
        <do_else>
          <!-- GT order still active - this is just trade order cancellation, not GT order cancellation -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': on_abort fired but GT order still active (default order: ' + $currentDefaultOrder + ') - skipping Phase 7 (trade order cancellation, not GT order cancellation)'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
      <do_else>
        <!-- GT order still active AND training/maintenance transition - skip Phase 7 (normal behavior) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order still active with training/maintenance transition - skipping Phase 7 (normal transition, not removal)'" chance="100"/>
        </do_if>
      </do_else>
    </do_elseif>
    
    <!-- Check if subordinate cleanup already sent signal (to avoid duplicate) -->
    <do_if value="this.$subordinate_cleanup_sent?">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate cleanup signal already sent - skipping duplicate'" chance="100"/>
    </do_if>
    <do_else>
      <!-- Check for permanent removal FIRST, regardless of trading state -->
      <!-- When player stops order, we MUST restore name even if TradePerform orders are still active -->
      <!-- Unified GT order status check (inline for AI scripts) -->
      <!-- If GT order is gone (no direct, no commander), it's permanent removal REGARDLESS of trading state -->
      <set_value name="$isPermanentRemoval" exact="not $hasDirectGTOrder and not $hasGTCommander and $currentDefaultOrder != 'Assist'"/>
      
      <do_if value="$isPermanentRemoval">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$debugOrdersCount" exact="this.ship.orders.count"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order removed (no direct GT, no GT commander) â†’ PERMANENT REMOVAL (actively trading: ' + $isActivelyTrading + ', orders count: ' + $debugOrdersCount + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- GT order still active - check other conditions -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order still active (direct: ' + $hasDirectGTOrder + ', commander: ' + $hasGTCommander + ') - checking other removal conditions'" chance="100"/>
        </do_if>
        
        <!-- Additional checks: no default order, different order, or not registered -->
        <do_if value="not $currentDefaultOrder">
          <!-- No default order at all â†’ PERMANENT REMOVAL -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No default order detected â†’ PERMANENT REMOVAL'" chance="100"/>
        </do_if>
        <do_elseif value="$currentDefaultOrder and $currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply' and $currentDefaultOrder != 'Assist'">
          <!-- Ship has a DIFFERENT permanent default order â†’ PERMANENT REMOVAL -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Different default order (' + $currentDefaultOrder + ') detected â†’ PERMANENT REMOVAL'" chance="100"/>
        </do_elseif>
        <do_elseif value="not (global.$GT_Ships? and global.$GT_Ships.{this.ship}?)">
          <!-- Ship was removed from GT (unregistered), definitely restore name -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship no longer registered in GT_Ships â†’ PERMANENT REMOVAL (even if actively trading)'" chance="100"/>
        </do_elseif>
      </do_else>
      
      <!-- Calculate subordinate status (needed for both permanent removal and pause checks) -->
      <set_value name="$isSubordinate" exact="$currentDefaultOrder == 'Assist' and $hasGTCommander"/>
      
      <!-- Always restore name on permanent removal, even if actively trading -->
      <do_if value="$isPermanentRemoval">
        <!-- Send ABORT signal: Restore ship name and clean up completely -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="this.ship.macro?">
          <set_value name="$originalName" exact="@this.ship.macro.name"/>
        </do_elseif>

        <!-- Always emit cleanup signal on permanent removal, even if no stored original name was found.
             MD cleanup will still run and name restoration falls back safely. -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Order permanently removed by player',
          $OriginalName = $originalName
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Sending ABORT signal (restore name, preserve XP) - permanent removal detected'" chance="100"/>
        </do_if>
        
        <!-- Clear training and maintenance flags -->
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_order_created"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$maintenance_transition"/>
      </do_if>
      <!-- Only send PAUSE signal if NOT permanently removed AND NOT actively trading AND NOT transitioning -->
      <!-- CRITICAL: Don't pause subordinates with Assist order - they should stay registered -->
      <do_elseif value="not $isActivelyTrading and not $isTrainingTransition and not $isMaintenanceTransition and not $isSubordinate">
        <!-- Send PAUSE signal: Preserve everything (name and XP) for potential resume -->
        <set_value name="$pauseData" exact="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Order temporarily replaced - preserving pilot data',
          $PreserveData = true
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Sending PAUSE signal (preserve everything for resume)'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Paused'" param2="$pauseData"/>
        
        <!-- Clear training and maintenance flags -->
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_order_created"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$maintenance_transition"/>
      </do_elseif>
      <do_elseif value="$isSubordinate">
        <!-- Subordinate with Assist order - don't pause, stay registered -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate with Assist order - NOT sending PAUSE (staying registered)'" chance="100"/>
        </do_if>
      </do_elseif>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship still actively trading/training/maintenance - NOT sending signals (will handle when orders complete)'" chance="100"/>
        </do_if>
      </do_else>
    </do_else>
  </on_abort>
  
</aiscript> <?xml version="1.0" encoding="utf-8"?>
<aiscript name="order.trade.galaxytradermk42" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/aiscripts.xsd" version="1">
  <order id="GalaxyTraderMK4Supply2" name="{77000, 10007}" description="{77000, 10107}" category="trade" infinite="true" allowinloop="false" canplayercancel="true">
    <params>
      <!-- MK4-2 Galaxy-Supply â€” OPEN_GALAXYTRADER_MK4-2_SUPPLY_ORDER.md -->
      <param name="home" default="this.sector" type="object" text="{77000,1002}" comment="Home anchor (sector or station) for supply operations">
        <input_param name="class" value="[class.sector,class.station]"/>
      </param>
      <param name="assignHome" default="true" type="bool" text="{77000,1085}" comment="When home is a station: assign ship as station trade subordinate"/>
      <param name="jumpDistanceCoverage" default="1" type="number" text="{77000,1086}" comment="{77000,1088}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="jumpDistanceBuy" default="1" type="number" text="{77000,1021}" comment="{77000,1021}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="[if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then 25 else (if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then (if global.$GT_Pilots.{this.ship.pilot}.$Level le 2 then 1 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 5 then 3 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 8 then 5 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 11 then 10 else if global.$GT_Pilots.{this.ship.pilot}.$Level le 13 then 15 else 25) else 1), 1].max"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="serveHomeOnly" default="false" type="bool" text="{77000,1072}" comment="{77000,1089}"/>
      <param name="buyFromPlayer" default="5" type="number" text="{77000,1073}" comment="Player supplier priority: 0 = exclude player-owned suppliers, 1-10 = preference vs faction suppliers">
        <input_param name="startvalue" value="5"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="buyFromFaction" default="5" type="number" text="{77000,1074}" comment="Faction supplier priority: 0 = exclude non-player suppliers, 1-10 = preference vs player suppliers">
        <input_param name="startvalue" value="5"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="priorityBuildstorage" default="10" type="number" text="{77000,11001}" comment="{77000,11005}">
        <input_param name="startvalue" value="10"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="priorityStations" default="8" type="number" text="{77000,11002}" comment="{77000,11005}">
        <input_param name="startvalue" value="8"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="priorityAux" default="0" type="number" text="{77000,11003}" comment="{77000,11005}">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="priorityCarrier" default="0" type="number" text="{77000,11004}" comment="{77000,11005}">
        <input_param name="startvalue" value="0"/>
        <input_param name="min" value="0"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="allowResources" default="true" type="bool" text="{77000,1076}" comment="Supply resource-class wares"/>
      <param name="allowIntermediates" default="true" type="bool" text="{77000,1077}" comment="Supply intermediate/product wares"/>
      <param name="allowTradewares" default="true" type="bool" text="{77000,1078}" comment="{77000,1090}"/>
      <param name="autowares" default="true" type="bool" text="{77000,1015}" comment="{77000,1023}"/>
      <param name="warebasket" default="[]" type="list" text="{77000,1069}" comment="{77000,1024}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="priorityscoremultiplier" default="1" type="number" text="{77000,11007}" comment="{77000,11006}">
        <input_param name="startvalue" value="1"/>
        <input_param name="min" value="1"/>
        <input_param name="max" value="10"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="prioritywares" default="[]" type="list" text="{77000,1064}" comment="{77000,1066}">
        <input_param name="type" value="'ware'"/>
        <input_param name="cancarry" value="this.ship"/>
      </param>
      <param name="maxTrades" default="3" type="number" text="{77000,1080}" comment="Chained trade rounds per cycle (cap 3)">
        <input_param name="min" value="1"/>
        <input_param name="max" value="3"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="backtrackTolerance" default="1" type="number" text="{77000,1081}" comment="Extra jumps tolerated when chaining suppliers">
        <input_param name="min" value="0"/>
        <input_param name="max" value="5"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="useMinCargoThreshold" default="false" type="bool" text="{77000,1082}" comment="Enable minimum cargo utilization filter"/>
      <param name="minCargoUsed" default="80" type="number" text="{77000,1082}" comment="Target cargo fill % per chunk">
        <input_param name="min" value="10"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      <param name="allowillegal" default="false" type="bool" text="{77000,1011}" comment="{77000,1025}"/>
      <param name="enforceRouteIllegalLegality" default="false" type="bool" text="{77000,1070}" comment="{77000,1071}"/>
      <param name="ignoretraderules" default="false" type="bool" text="{77000,1058}" comment="{77000,1059}"/>
      <param name="ignoremk1supply" default="true" type="bool" text="{77000,1060}" comment="{77000,1061}"/>
      <param name="logbookentries" default="true" type="bool" text="{77000,1012}" comment="{77000,1041}"/>
      <param name="idleParking" default="false" type="bool" text="{77000,1096}" comment="{77000,1097}"/>
      <param name="autoJumpDistanceByLevel" default="false" type="bool" text="{77000,1098}" comment="{77000,1099}"/>
      <param name="sectorwhitelist" default="[]" type="list" text="{77000,1052}" comment="{77000,1053}">
        <input_param name="type" value="'object'"/>
        <input_param name="class" value="[class.sector]"/>
      </param>
      <param name="distancepenalty" default="50" type="number" text="{77000,1016}" comment="Distance impact on supply scoring">
        <input_param name="min" value="0"/>
        <input_param name="max" value="100"/>
        <input_param name="step" value="5"/>
      </param>
      <param name="fleetcoordination" default="true" type="bool" text="{77000,1018}" advanced="true" comment="{77000,1029}"/>
      <param name="marketupdatefreq" default="60s" type="time" text="{77000,1050}" advanced="true" comment="{77000,1034}">
        <input_param name="min" value="30s"/>
        <input_param name="max" value="300s"/>
        <input_param name="step" value="30s"/>
      </param>
      <param name="debuglevel" default="1" type="number" text="{1041, 10086}" advanced="true" comment="{77000,1035}">
        <input_param name="min" value="0"/>
        <input_param name="max" value="2"/>
        <input_param name="step" value="1"/>
      </param>
      <param name="tradeeval" default="false" type="bool" text="{77000,1051}" advanced="true" comment="{77000,1040}"/>
    </params>
    <requires>
      <match shiptype="shiptype.lasertower" negate="true"/>
    </requires>
  </order>
  
  <interrupts>
    <handler ref="SectorChangeHandler"/>
    
    <handler ref="AttackHandler"/>
    <handler ref="MissileLockHandler"/>
    <handler ref="ScannedHandler"/>
    <handler ref="InspectedHandler"/>
    <handler ref="FoundAbandonedHandler"/>
    <handler ref="FoundLockboxHandler"/>
    <handler ref="ResupplyHandler"/>
    <handler ref="TargetInvalidHandler"/>
    <handler ref="TideHandler"/>
    
    <!-- Trade Found Event Handler: Catches GT_Trade_Found signal regardless of ship state -->
    <!-- This ensures trades are processed immediately even if ship is in main_loop or other code paths -->
    <!-- Note: Cannot use <resume> in interrupt handlers, so we set a flag that main_loop checks -->
    <!-- Trade data is passed in signal param2 (like GT_Training_Station_Found) -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
      </conditions>
      <actions>
        <!-- Extract trade data from signal param2 (like GT_Training_Station_Found handler) -->
        <set_value name="$signalData" exact="event.param2"/>
        <set_value name="$signalTradeList" exact="[]"/>
        <set_value name="$signalSearchMethod" exact="''"/>
        <do_if value="$signalData? and $signalData != null">
          <set_value name="$signalTradeList" exact="@$signalData.$TradeList"/>
          <set_value name="$signalSearchMethod" exact="@$signalData.$SearchMethod"/>
        </do_if>
        
        <!-- FALLBACK: If param2 is empty or null, read from global storage (backward compatibility) -->
        <!-- This handles cases where ProcessTradeFoundSignalQueue fails to populate param2 -->
        <do_if value="($signalTradeList == null or $signalTradeList.count == 0) and global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
          <set_value name="$signalTradeList" exact="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <set_value name="$signalSearchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
        </do_if>
        
        <!-- Only set the interrupt flag if we actually have trades to process.
             Empty signals cause pointless trade_found processing with 0 trades. -->
        <do_if value="$signalTradeList != null and $signalTradeList.count gt 0">
          <do_if value="$signalSearchMethod? and ($signalSearchMethod == 'LIVE' or $signalSearchMethod == 'live' or $signalSearchMethod == 'mk42live')">
            <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
          </do_if>
          <set_value name="this.$tradeFoundViaInterrupt" exact="true"/>
          <set_value name="this.$tradeListFromSignal" exact="$signalTradeList"/>
          <set_value name="this.$searchMethodFromSignal" exact="if $signalSearchMethod != null and $signalSearchMethod != '' then $signalSearchMethod else ''"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$dataSource" exact="if (event.param2? and event.param2 != null) then 'param2' else 'global storage'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received via interrupt handler - stored ' + $signalTradeList.count + ' trades from ' + $dataSource" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received but trade list is empty - ignoring (no interrupt flag set)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>

    <!-- Search Go Event Handler: capture scheduler grants even outside wait_for_response -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Search_Go'"/>
      </conditions>
      <actions>
        <set_value name="$searchGoData" exact="event.param2"/>
        <do_if value="$searchGoData? and $searchGoData != null and typeof $searchGoData == datatype.table">
          <set_value name="this.$pendingSearchParams" exact="$searchGoData"/>
          <set_value name="this.$searchGoViaInterrupt" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$searchGoPhase" exact="if $searchGoData.$Phase? then @$searchGoData.$Phase else 'unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Search_Go captured via global interrupt (phase=' + $searchGoPhase + ')'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </handler>
    
    <!-- High-Performance Training Event Handlers -->
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$trainingStation" exact="$trainingData.$Station"/>
        <set_value name="$requiredLevel" exact="$trainingData.$Level"/>
        <!-- Academy enrollments must NOT interrupt the current order; they
             append DockAndTrain so the ship finishes the active task first
             and the queued training is visible in the order list. The
             natural training ladder keeps using immediate dispatch. -->
        <set_value name="$isAcademy" exact="@$trainingData.$IsAcademy"/>
        <set_value name="$useImmediate" exact="not $isAcademy"/>
        <do_if value="this.ship.defaultorder? and this.ship.defaultorder.id == 'Assist'">
          <set_value name="$useImmediate" exact="false"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸŽ“ Training station found: ' + $trainingStation.knownname + ' for level ' + $requiredLevel + ' (academy=' + $isAcademy + ', immediate=' + $useImmediate + ')'" chance="100"/>
        </do_if>
        
        <!-- Create training order: immediate for natural ladder, queued for academy -->
        <create_order object="this.ship" id="'DockAndTrain'" immediate="$useImmediate">
          <param name="destination" value="$trainingStation"/>
          <param name="debugchance" value="@this.$debugchance"/>
        </create_order>
        
        <!-- Set flag to indicate training is in progress -->
        <set_value name="this.$training_in_progress" exact="true"/>
        <!-- Set flag to indicate training transition for on_abort handler -->
        <set_value name="this.$training_transition" exact="true"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': DockAndTrain order created for ' + $trainingStation.knownname" chance="100"/>
        </do_if>
        
        <!-- Set flag to prevent race condition in on_abort handler -->
        <!-- Ensures the on_abort handler knows a training order was just created -->
        <set_value name="this.$training_order_created" exact="player.age"/>
      </actions>
    </handler>
    
    <!-- Event-Driven Mobile Satellite Intelligence: Detect stations entering radar range -->
    <!-- 
    OPTIMIZED: Event-driven station detection (replaces polling-based MobileSatelliteIntelligence)
    - Uses vanilla gravidar scan events (zero CPU when no stations detected)
    - Only Level 9+ pilots can detect stations (skill gate maintained)
    - Signals MD immediately when stations detected (no polling overhead)
    - Same functionality as old polling system but much more efficient
    -->
    <handler comment="Detect stations entering radar range for mobile satellite intelligence">
      <conditions>
        <event_gravidar_has_scanned object="this.ship"/>
        <check_value value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?"/>
        <check_value value="this.sector"/>
        <!-- Only Level 9+ pilots and when Mobile Intel is enabled -->
        <check_value value="@global.$GT_Pilots.{this.ship.pilot}.$Level ge 9"/>
        <check_value value="not global.$GT_GlobalSettings.$MobileIntel? or global.$GT_GlobalSettings.$MobileIntel.$Enable"/>
        <!-- PERFORMANCE: Do not run actions unless there is at least 1 station contact -->
        <!-- Vanilla pattern: use count_gravidar_contacts with min="1" to avoid per-scan work when nothing is detected -->
        <count_gravidar_contacts result="$_detectedStations" object="this.ship" class="class.station" docked="false" checkoperational="true" multiple="true" min="1"/>
      </conditions>
      <actions>
        <!-- Stations were detected (min=1 in conditions). Process a small capped number per scan to smooth spikes. -->
        <set_value name="$level" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        <set_value name="$detectedStations" exact="$_detectedStations"/>
        
        <!-- Cap work per scan event (prevents large bursts when many stations are in radar range) -->
        <set_value name="$stationsToProcess" exact="[$detectedStations.count, 5].min"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI-Intel] ' + this.ship.idcode + ' detected ' + $detectedStations.count + ' station(s) - processing ' + $stationsToProcess" chance="20"/>
        </do_if>
        
        <do_all exact="$stationsToProcess" counter="$i">
          <set_value name="$station" exact="$detectedStations.{$i}"/>
          <do_if value="$station.exists and $station.isoperational">
            <!-- Signal MD to process this station -->
            <signal_objects object="player.galaxy" param="'GT_Station_Detected'" param2="table[$Ship=this.ship, $station=$station, $pilotLevel=$level]"/>
          </do_if>
        </do_all>
      </actions>
    </handler>

    <!-- Event-Driven Threat Avoidance: Detect hostile ships entering radar range (gravidar) -->
    <!-- Uses vanilla event_gravidar_has_scanned + count_gravidar_contacts (no polling).
         Only broadcasts when computed threat level meets ThreatAvoidance.BlacklistThreshold to avoid spam. -->
    <handler comment="ThreatAvoidance: hostile gravidar contact detection">
      <conditions>
        <event_gravidar_has_scanned object="this.ship"/>
        <check_value value="this.sector"/>
        <!-- Feature gate -->
        <check_value value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ThreatAvoidance? and global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled"/>
        <check_value value="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>
        <!-- Only run actions if at least 1 hostile ship contact exists -->
        <count_gravidar_contacts result="$_detectedHostiles" object="this.ship" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" maybeattackedby="this.ship" checkoperational="false" masstraffic="false" docked="false" multiple="true" min="1">
          <match_context macro="this.sector.macro"/>
          <match_context class="class.highway" negate="true"/>
          <match state="componentstate.wreck" negate="true"/>
        </count_gravidar_contacts>
      </conditions>
      <actions>
        <!-- Get pilot skill level - only Level 6+ pilots can broadcast threat warnings to fleet -->
        <set_value name="$pilotLevel" exact="1"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots.{this.ship.pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>
        
        <!-- Shared throttle with move.generic detection (single source of truth across scripts).
             This prevents duplicate logs/broadcasts when both move.generic and this order detect the same contact. -->
        <do_if value="not global.$GT_ThreatDetectThrottle?">
          <set_value name="global.$GT_ThreatDetectThrottle" exact="table[]"/>
        </do_if>
        <set_value name="$_last" exact="@global.$GT_ThreatDetectThrottle.{this.ship}"/>
        <do_if value="$_last == null">
          <set_value name="$_last" exact="0s"/>
        </do_if>
        <set_value name="$_logAllowed" exact="player.age - $_last ge 10s"/>
        <set_value name="$_broadcastAllowed" exact="player.age - $_last ge 30s"/>

        <set_value name="$hostiles" exact="$_detectedHostiles"/>
        <!-- IMPORTANT: $hostiles.count may include non-operational contacts (checkoperational="false").
             We want HostileCount to match the class breakdown we compute below, so we derive it from class counters. -->
        <set_value name="$hostileListCount" exact="$hostiles.count"/>
        <set_value name="$hostileCount" exact="0"/>

        <!-- Compute threat score and class breakdown (cheap: based on detected hostiles only) -->
        <set_value name="$threatScore" exact="0"/>
        <set_value name="$shipClass_XL" exact="0"/>
        <set_value name="$shipClass_L" exact="0"/>
        <set_value name="$shipClass_M" exact="0"/>
        <set_value name="$shipClass_S" exact="0"/>
        <set_value name="$factionCounts" exact="table[]"/>

        <do_all exact="$hostileListCount" counter="$i">
          <set_value name="$h" exact="$hostiles.{$i}"/>
          <do_if value="@$h.exists and @$h.isoperational">
            <do_if value="$h.isclass.ship_xl">
              <set_value name="$threatScore" exact="$threatScore + 5"/>
              <set_value name="$shipClass_XL" operation="add"/>
            </do_if>
            <do_elseif value="$h.isclass.ship_l">
              <set_value name="$threatScore" exact="$threatScore + 3"/>
              <set_value name="$shipClass_L" operation="add"/>
            </do_elseif>
            <do_elseif value="$h.isclass.ship_m">
              <set_value name="$threatScore" exact="$threatScore + 2"/>
              <set_value name="$shipClass_M" operation="add"/>
            </do_elseif>
            <do_else>
              <set_value name="$threatScore" exact="$threatScore + 1"/>
              <set_value name="$shipClass_S" operation="add"/>
            </do_else>

            <do_if value="@$h.owner != null">
              <set_value name="$f" exact="$h.owner"/>
              <set_value name="$factionCounts.{$f}" exact="@$factionCounts.{$f} + 1"/>
            </do_if>
          </do_if>
        </do_all>

        <!-- Make HostileCount match class counters -->
        <set_value name="$hostileCount" exact="$shipClass_XL + $shipClass_L + $shipClass_M + $shipClass_S"/>

        <!-- Determine primary faction -->
        <set_value name="$primaryFaction" exact="null"/>
        <set_value name="$maxFactionCount" exact="0"/>
        <do_all exact="$factionCounts.keys.count" counter="$fi">
          <set_value name="$f" exact="$factionCounts.keys.{$fi}"/>
          <do_if value="$factionCounts.{$f} gt $maxFactionCount">
            <set_value name="$primaryFaction" exact="$f"/>
            <set_value name="$maxFactionCount" exact="$factionCounts.{$f}"/>
          </do_if>
        </do_all>

        <!-- Convert score to threat level (1-5), matching GT_ThreatIntelligence receiver expectations -->
        <set_value name="$threatLevel" exact="2"/>
        <do_if value="$shipClass_XL gt 0 or $shipClass_L gt 0">
          <set_value name="$threatLevel" exact="4"/>
        </do_if>
        <do_elseif value="$threatScore ge 6">
          <set_value name="$threatLevel" exact="3"/>
        </do_elseif>

        <!-- Compare to configured threshold -->
        <set_value name="$threshold" exact="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold"/>
        <do_if value="not $threshold?">
          <set_value name="$threshold" exact="3"/>
        </do_if>

        <!-- Only Level 6+ pilots broadcast to fleet (matches ShipUnderAttack handler pattern) -->
        <do_if value="$pilotLevel ge 6">
          <do_if value="$hostileCount gt 0 and $_broadcastAllowed and $threatLevel ge $threshold">
            <!-- Broadcast to MD threat system (event-driven) -->
            <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
              $Sector = this.sector,
              $DetectedBy = this.ship,
              $HostileCount = $hostileCount,
              $PrimaryFaction = $primaryFaction,
              $ShipClass_XL = $shipClass_XL,
              $ShipClass_L = $shipClass_L,
              $ShipClass_M = $shipClass_M,
              $ShipClass_S = $shipClass_S,
              $ThreatScore = $threatScore,
              $Timestamp = player.age
            ]"/>
          </do_if>
        </do_if>

        <!-- Logging: emit whenever detection fires (hostiles detected), but respect shared log throttle -->
        <!-- Lower level pilots (1-5) can detect but don't broadcast - log for debugging -->
        <do_if value="$hostileCount gt 0 and $_logAllowed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="global.$GT_ThreatDetectThrottle.{this.ship}" exact="player.age"/>
          <set_value name="$_primaryFactionName" exact="if $primaryFaction? then @$primaryFaction.knownname else 'UNKNOWN'"/>
          <set_value name="$_broadcasted" exact="if ($pilotLevel ge 6 and $_broadcastAllowed and $threatLevel ge $threshold) then 'YES' else 'NO'"/>
          <set_value name="$_broadcastReason" exact="if $pilotLevel lt 6 then 'PILOT LEVEL TOO LOW (Lv.' + $pilotLevel + ', requires Lv.6+)' else if not $_broadcastAllowed then 'THROTTLED' else if $threatLevel lt $threshold then 'THREAT BELOW THRESHOLD' else 'OK'"/>
          <debug_text text="'[GT-Threat-Detect] ' + this.ship.idcode + ' (Pilot Lv.' + $pilotLevel + ') in ' + this.sector.knownname
            + ' - hostiles=' + $hostileCount
            + ' (XL=' + $shipClass_XL + ', L=' + $shipClass_L + ', M=' + $shipClass_M + ', S=' + $shipClass_S + ')'
            + ', threatScore=' + $threatScore + ', threatLevel=' + $threatLevel + ', threshold=' + $threshold
            + ', primaryFaction=' + $_primaryFactionName
            + ', broadcasted=' + $_broadcasted + ' (' + $_broadcastReason + ')'" chance="100"/>
        </do_if>
      </actions>
    </handler>
    
    <!-- Subordinate Resync Handler: Listen for commander order changes (like vanilla order.assist) -->
    <handler comment="Subordinate resync on commander order change">
      <conditions>
        <check_all>
          <event_object_order_ready object="this.ship.commander" check="false" comment="Commander's order ready"/>
          <check_value value="event.param == event.object.defaultorder" comment="It's the default order"/>
        </check_all>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Commander order changed - restarting to resync settings'" chance="100"/>
        </do_if>
        <!-- Release any scheduler registration BEFORE restarting. abort_called_scripts resume="init"
             jumps straight back to the main loop without passing through the normal abort/cleanup path,
             so a ship that was queued/active (e.g. $MK42LiveQueued after escalating to live) keeps that
             stale membership. The restarted loop then re-sends GT_Search_Request, which HandleSearchRequest
             REJECTS as a duplicate (reason=MK42LiveQueued), parks the ship in the InProgress wait, and the
             stale queue entry is never dispatched -> the ship is stuck until the 120s timeout while the
             cache it could read sits ready. The abort signal is queued and processed by the MD handler
             independently of the immediate script restart. -->
        <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
        <!-- Use abort_called_scripts like vanilla - forcefully restart at init label -->
        <abort_called_scripts resume="init"/>
      </actions>
    </handler>
    
    <!-- Commander change detection handler -->
    <!-- Tests if commander change detection interferes with trade execution -->
    <!-- This handler fires BEFORE the subordinate resync handler restarts the script -->
    <!-- Using this.assignedcontrolled like vanilla order.assist.xml -->
    <handler comment="Commander removed or changed">
      <conditions>
        <event_object_commander_set object="this.assignedcontrolled"/>
      </conditions>
      <actions>
        <set_value name="$newCommander" exact="event.param"/>
        
        <!-- Update state machine BEFORE script restarts -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (commander: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <!-- NOTE: Script will restart via subordinate resync handler if commander has order change -->
        <!-- But signal is sent FIRST, so state manager can process it -->
      </actions>
    </handler>
    
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Complete'"/>
      </conditions>
      <actions>
        <set_value name="$completionData" exact="event.param2"/>
        <set_value name="$completedLevel" exact="$completionData.$Level"/>
        
        <!-- Ignore spurious early-complete (Level 0) while academy or MD timer still active -->
        <set_value name="$shouldResumeTrading" exact="true"/>
        <do_if value="$completedLevel? and $completedLevel le 0">
          <set_value name="$shouldResumeTrading" exact="false"/>
        </do_if>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
        </do_if>
        
        <do_if value="$shouldResumeTrading">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training completed for level ' + $completedLevel + ' - setting flag to resume trading'" chance="100"/>
        </do_if>
        
        <!-- Set flag to resume trading (can't use resume in interrupt handler) -->
        <set_value name="this.$training_complete" exact="true"/>
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$training_order_created"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ignoring spurious training-complete signal (level=' + $completedLevel + ', academy/timer still active)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <handler>
      <conditions>
        <event_object_signalled object="this.ship" param="'GT_Training_Failed'"/>
      </conditions>
      <actions>
        <set_value name="$failureData" exact="event.param2"/>
        <set_value name="$reason" exact="$failureData.$Reason"/>
        
        <!-- Do not resume trading while pilot is still blocked or academy course active -->
        <set_value name="$shouldResumeTrading" exact="true"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'">
            <set_value name="$shouldResumeTrading" exact="false"/>
          </do_if>
        </do_if>
        
        <do_if value="$shouldResumeTrading">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training failed: ' + $reason + ' - setting flag to resume trading'" chance="100"/>
        </do_if>
        
        <!-- Set flag to resume trading (can't use resume in interrupt handler) -->
        <set_value name="this.$training_complete" exact="true"/>
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$training_order_created"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training failed (' + $reason + ') but pilot still blocked - not resuming trading'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>
    
    <!-- Order cancellation detection handler -->
    <!-- Detects when GT default order is cancelled -->
    <!-- Note: Ships always have a default order (Wait, Assist, etc.), so we check:
         1. If cancelled order was GT order (event.param.id == 'GalaxyTraderMK3')
         2. If ship is still GT-controlled (direct GT order OR subordinate with GT commander via Assist)
         3. Only act if ship is no longer GT-controlled -->
    <handler comment="GT order cancelled">
      <conditions>
        <event_object_order_cancelled object="this.ship" immediate="true"/>
        <!-- Note: Ships always have a default order (Wait, Assist, etc.), so we check the cancelled order ID and current default order -->
      </conditions>
      <actions>
        <!-- Check which order was cancelled -->
        <set_value name="$cancelledOrderId" exact="@event.param.id"/>
        <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <!-- Unified GT order status check (inline for AI scripts) -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <set_value name="$hasGTCommander" exact="false"/>
        <set_value name="$isGTControlled" exact="false"/>
        
        <!-- Check direct GT order -->
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2'">
          <set_value name="$hasDirectGTOrder" exact="true"/>
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
        
        <!-- Check commander status -->
        <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$hasGTCommander" exact="true"/>
            <do_if value="$currentDefaultOrder == 'Assist'">
              <set_value name="$isGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Only act if GT order was actually cancelled (ship is no longer GT-controlled) -->
        <do_if value="not $isGTControlled">
          <!-- Check if GT order was explicitly cancelled OR if current default is not GT/Assist-with-GT-commander -->
          <do_if value="$cancelledOrderId == 'GalaxyTraderMK3' or $cancelledOrderId == 'GalaxyTraderMK4Supply2' or not $cancelledOrderId">
            <!-- GT order is being cancelled â†’ send Phase 7 signal -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (interrupt handler, cancelled order: ' + (if $cancelledOrderId then $cancelledOrderId else 'NONE') + ', current default: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isGTControlled + ')'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
            
            <!-- EVENT-DRIVEN: Trigger orphaned ship check -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
              <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
            </do_if>
            
            <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
            <do_if value="not $hasDirectGTOrder and not $hasGTCommander and this.ship.pilot?">
              <set_value name="$originalName" exact="null"/>
              <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
              </do_if>
              
              <do_if value="$originalName">
                <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                  $Ship = this.ship,
                  $Pilot = this.ship.pilot,
                  $Reason = 'GT order cancelled - restoring original name',
                  $OriginalName = $originalName
                ]"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Ship is still GT-controlled (direct GT order or subordinate with GT commander) - skip -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Order cancelled interrupt fired but ship still GT-controlled (cancelled: ' + (if $cancelledOrderId then $cancelledOrderId else 'NONE') + ', current default: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isGTControlled + ') - skipping Phase 7'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </handler>

  </interrupts>
  
  <init>
    <set_order_syncpoint_reached order="this.ship.order"/>
    <set_command command="command.searchtrades"/>
    <set_command_action commandaction="commandaction.searchingtrades"/>

    <!-- CRITICAL: Ensure instance wait time storage ALWAYS exists before any <wait ...> evaluates it.
         Vanilla pattern: instance vars are accessed with safe operator @this.$var (e.g. @this.$resupplier...). -->
    <!-- Purpose A: Pre-request wait for GT_Trade_Found signal (milliseconds) -->
    <set_value name="this.$tradeFoundSignalWaitTime" exact="5ms"/>
    <!-- Purpose B: No-trade retry cooldown (seconds) -->
    <set_value name="this.$retryCooldown" exact="10s"/>
    <!-- Tracks GT_Search_Go captured outside wait_for_response -->
    <set_value name="this.$searchGoViaInterrupt" exact="false"/>
    
    <!-- Legacy persistent variables removed - no longer needed with unified maintenance system -->
    
    <!-- ============================================================================= -->
    <!-- SAVE GAME CLEANUP: Clear stale tracking data when loading from a save game  -->
    <!-- ============================================================================= -->
    <!-- Check if resupply tracking exists and verify if the order is still active.   -->
    <!-- Only remove tracking if the order no longer exists (stale data).             -->
    <!-- ============================================================================= -->
    <!-- PERFORMANCE: Optimized resupply order check - use order.id property instead of iterating all orders -->
    <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
      <!-- Check if ship has active resupply/repair/equipment order using order.id (more efficient than iterating) -->
      <set_value name="$hasActiveResupplyOrder" exact="false"/>
      <!-- Our resupply uses order.build.equip, whose order id is 'Equip' (vanilla) -->
      <do_if value="this.ship.order? and (this.ship.order.id == 'Resupply' or this.ship.order.id == 'Repair' or this.ship.order.id == 'Equip')">
        <set_value name="$hasActiveResupplyOrder" exact="true"/>
      </do_if>
      
      <do_if value="not $hasActiveResupplyOrder">
        <!-- No active order - tracking is stale, remove it -->
        <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale resupply tracking (no active order)'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- Order still active - keep tracking -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resupply order still active after save load - keeping tracking'" chance="100"/>
        </do_if>
      </do_else>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- MODULAR INITIALIZATION - REPLACES ~200 LINES OF COMPLEX INITIALIZATION CODE -->
    <!-- ============================================================================= -->
    
    <!-- CRITICAL DEBUG: Log that init block started -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === INIT BLOCK STARTED === (Ship: ' + this.ship.knownname + ', Pilot: ' + (if this.ship.pilot then this.ship.pilot.name else 'NONE') + ')'" chance="100"/>
    </do_if>
    
    <!-- Create order parameters table for library compatibility -->
    <set_value name="$orderParams" exact="table[]"/>
    
    <!-- Legacy maintenance variables removed - no longer needed with unified maintenance system -->
    
    <!-- SUBORDINATE HOME BASE INHERITANCE:
         only ship-subordinates inherit commander's home.
         Station-assigned ships must keep their own station home anchor for serveHomeOnly. -->
    <set_value name="$effectiveHome" exact="$home"/>
    <do_if value="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
      <!-- Ship is a subordinate - ALWAYS inherit commander's home sector -->
      <do_if value="this.ship.commander.defaultorder and this.ship.commander.defaultorder.$home?">
        <set_value name="$effectiveHome" exact="this.ship.commander.defaultorder.$home"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting home base from commander ' + this.ship.commander.idcode + ': ' + $effectiveHome.knownname" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    
    <!-- Store as script variable for persistence throughout execution -->
    <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
    <!-- Order restart (trade revoke / maintenance transition): drop stale force-live flags and
         per-ship cache skip markers so a fresh search can use repopulated MK4 cache immediately. -->
    <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
    <set_value name="this.$forceLiveAfterLiveReject" exact="false"/>
    <set_value name="$initMk4HomeSector" exact="if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else null)"/>
    <do_if value="$initMk4HomeSector? and $initMk4HomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$initMk4HomeSector}?">
      <do_all exact="global.$GT_TradeCacheMK42.{$initMk4HomeSector}.count" counter="$initCi">
        <set_value name="$initEntry" exact="global.$GT_TradeCacheMK42.{$initMk4HomeSector}.{$initCi}"/>
        <do_if value="$initEntry? and $initEntry.$FailedShips? and $initEntry.$FailedShips.count gt 0">
          <set_value name="$initNewFailed" exact="[]"/>
          <do_all exact="$initEntry.$FailedShips.count" counter="$initFsi">
            <do_if value="$initEntry.$FailedShips.{$initFsi} != this.ship">
              <append_to_list name="$initNewFailed" exact="$initEntry.$FailedShips.{$initFsi}"/>
            </do_if>
          </do_all>
          <set_value name="$initEntry.$FailedShips" exact="$initNewFailed"/>
          <set_value name="global.$GT_TradeCacheMK42.{$initMk4HomeSector}.{$initCi}" exact="$initEntry"/>
        </do_if>
      </do_all>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- STATION ASSIGNMENT: If home is a station, assign ship as station subordinate -->
    <!-- The lib.request.orders.xml patch protects the GT order from being overwritten -->
    <!-- The gt_subordinate_access.lua hook keeps order params editable in the UI -->
    <!-- ============================================================================= -->
    <do_if value="$assignHome and this.$effectiveHome.isclass.station">
      <!-- Home is a station â€” assign only if ship is top-level or already station-assigned.
           Ship-subordinates must remain under their ship commander. -->
      <do_if value="(not this.ship.commander.exists or this.ship.commander == this.ship or this.ship.commander.isclass.station) and this.ship.commander != this.$effectiveHome">
        <!-- Unassign from old commander first (if any) -->
        <do_if value="this.ship.commander.exists and this.ship.commander != this.ship">
          <remove_object_commander object="this.ship"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Removed old commander before station assignment'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Assign to station as trade subordinate -->
        <set_object_commander object="this.ship" commander="this.$effectiveHome" assignment="assignment.trade"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Assigned to station ' + this.$effectiveHome.knownname + ' as trade subordinate'" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    <do_elseif value="this.$effectiveHome.isclass.sector">
      <!-- Home is a sector â€” unassign from any station if previously assigned -->
      <do_if value="this.ship.commander.exists and this.ship.commander.isclass.station">
        <remove_object_commander object="this.ship"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Removed station assignment â€” home changed to sector ' + this.$effectiveHome.knownname" chance="100"/>
        </do_if>
      </do_if>
    </do_elseif>
    
    <!-- ============================================================================= -->
    <!-- SUBORDINATE SETTINGS INHERITANCE: Inherit strategic settings from commander -->
    <!-- Note: excludes station commanders â€” only ship-to-ship subordinates inherit -->
    <!-- ============================================================================= -->
    <set_value name="$isSubordinate" exact="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station"/>
    <set_value name="$commanderOrder" exact="null"/>
    <do_if value="$isSubordinate">
      <set_value name="$commanderOrder" exact="this.ship.commander.defaultorder"/>
    </do_if>

    <!-- MK4-2 Â§3: jump distances + class priority sliders (OPEN_GALAXYTRADER_MK4-2_SUPPLY_ORDER.md) -->
    <set_value name="$useMinCargoThresholdFilter" exact="if $useMinCargoThreshold? then $useMinCargoThreshold else false"/>
    <set_value name="$cargotarget" exact="if $minCargoUsed? then $minCargoUsed else 80"/>
    <set_value name="$maxsell" exact="$jumpDistanceCoverage"/>
    <set_value name="$maxbuy" exact="$jumpDistanceBuy"/>
    <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
    <do_if value="not $useVanillaXPOnly">
      <set_value name="$jumpMaxPilot" exact="25"/>
      <set_value name="$psJump" exact="if (this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?) then global.$GT_Pilots.{this.ship.pilot}.$Level else null"/>
      <do_if value="$psJump != null">
        <do_if value="$psJump le 2"><set_value name="$jumpMaxPilot" exact="1"/></do_if>
        <do_elseif value="$psJump le 5"><set_value name="$jumpMaxPilot" exact="3"/></do_elseif>
        <do_elseif value="$psJump le 8"><set_value name="$jumpMaxPilot" exact="5"/></do_elseif>
        <do_elseif value="$psJump le 11"><set_value name="$jumpMaxPilot" exact="10"/></do_elseif>
        <do_elseif value="$psJump le 13"><set_value name="$jumpMaxPilot" exact="15"/></do_elseif>
        <do_else><set_value name="$jumpMaxPilot" exact="25"/></do_else>
      </do_if>
      <set_value name="$maxsell" exact="[$maxsell, $jumpMaxPilot].min"/>
      <set_value name="$maxbuy" exact="[$maxbuy, $jumpMaxPilot].min"/>
    </do_if>

    <!-- MK4-2 class priority sliders (Â§3) â€” seed nulls in policy lib at runtime; init uses order defaults -->
    <set_value name="$effectivePriorityBuildstorage" exact="if $priorityBuildstorage? then $priorityBuildstorage else 10"/>
    <set_value name="$effectivePriorityStations" exact="if $priorityStations? then $priorityStations else 8"/>
    <set_value name="$effectivePriorityAux" exact="if $priorityAux? then $priorityAux else 0"/>
    <set_value name="$effectivePriorityCarrier" exact="if $priorityCarrier? then $priorityCarrier else 0"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <do_if value="$commanderOrder.$priorityBuildstorage?">
        <set_value name="$effectivePriorityBuildstorage" exact="$commanderOrder.$priorityBuildstorage"/>
      </do_if>
      <do_if value="$commanderOrder.$priorityStations?">
        <set_value name="$effectivePriorityStations" exact="$commanderOrder.$priorityStations"/>
      </do_if>
      <do_if value="$commanderOrder.$priorityAux?">
        <set_value name="$effectivePriorityAux" exact="$commanderOrder.$priorityAux"/>
      </do_if>
      <do_if value="$commanderOrder.$priorityCarrier?">
        <set_value name="$effectivePriorityCarrier" exact="$commanderOrder.$priorityCarrier"/>
      </do_if>
    </do_if>
    <set_value name="$mk42Priorities" exact="table[$Buildstorage = $effectivePriorityBuildstorage, $Stations = $effectivePriorityStations, $Aux = $effectivePriorityAux, $Carrier = $effectivePriorityCarrier]"/>
    <set_value name="$mk4BuildStorageOnlyMode" exact="$effectivePriorityBuildstorage gt 0 and $effectivePriorityStations == 0 and $effectivePriorityAux == 0 and $effectivePriorityCarrier == 0"/>
    <!-- Legacy compat for remaining v1-derived paths -->
    <set_value name="$effectiveIgnoreBuildStorage" exact="$effectivePriorityBuildstorage == 0"/>
    <set_value name="$effectiveIgnoreCarrierAux" exact="$effectivePriorityAux == 0 and $effectivePriorityCarrier == 0"/>

    <!-- Sector Whitelist -->
    <set_value name="$effectiveSectorWhitelist" exact="$sectorwhitelist"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$sectorwhitelist?">
      <set_value name="$effectiveSectorWhitelist" exact="$commanderOrder.$sectorwhitelist"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inheriting sector whitelist from commander ' + this.ship.commander.idcode" chance="100"/>
        </do_if>
    </do_if>

    <!-- Fleet Coordination -->
    <set_value name="$effectiveFleetCoordination" exact="$fleetcoordination"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$fleetcoordination?">
      <set_value name="$effectiveFleetCoordination" exact="$commanderOrder.$fleetcoordination"/>
    </do_if>

    <!-- Allow Illegal Wares -->
    <set_value name="$effectiveAllowIllegal" exact="$allowillegal"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$allowillegal?">
      <set_value name="$effectiveAllowIllegal" exact="$commanderOrder.$allowillegal"/>
    </do_if>

    <!-- Illegal Route Filter -->
    <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$enforceRouteIllegalLegality"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$enforceRouteIllegalLegality?">
      <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$commanderOrder.$enforceRouteIllegalLegality"/>
    </do_if>

    <!-- Ignore Trade Rules -->
    <set_value name="$effectiveIgnoreTradeRules" exact="false"/>
    <do_if value="$ignoretraderules?">
      <set_value name="$effectiveIgnoreTradeRules" exact="$ignoretraderules"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoretraderules?">
      <set_value name="$effectiveIgnoreTradeRules" exact="$commanderOrder.$ignoretraderules"/>
    </do_if>

    <!-- Ignore MK1-Supplied Stations -->
    <set_value name="$effectiveIgnoreMK1Supply" exact="true"/>
    <do_if value="$ignoremk1supply?">
      <set_value name="$effectiveIgnoreMK1Supply" exact="$ignoremk1supply"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$ignoremk1supply?">
      <set_value name="$effectiveIgnoreMK1Supply" exact="$commanderOrder.$ignoremk1supply"/>
    </do_if>

    <!-- Idle Parking -->
    <set_value name="$effectiveIdleParking" exact="false"/>
    <do_if value="$idleParking?">
      <set_value name="$effectiveIdleParking" exact="$idleParking"/>
    </do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$idleParking?">
      <set_value name="$effectiveIdleParking" exact="$commanderOrder.$idleParking"/>
    </do_if>

    <set_value name="$effectiveFactionPriority" exact="0"/>

    <!-- Auto wares / manual basket -->
    <set_value name="$effectiveAutoWares" exact="if $autowares? then $autowares else true"/>
    <do_if value="$lockWares?">
      <set_value name="$effectiveAutoWares" exact="not $lockWares"/>
    </do_if>
    <set_value name="$effectiveWareBasket" exact="if $warebasket? and $warebasket.count gt 0 then $warebasket else (if $specialWareBasket? then $specialWareBasket else [])"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <do_if value="$commanderOrder.$autowares?">
        <set_value name="$effectiveAutoWares" exact="$commanderOrder.$autowares"/>
      </do_if>
      <do_elseif value="$commanderOrder.$lockWares?">
        <set_value name="$effectiveAutoWares" exact="not $commanderOrder.$lockWares"/>
      </do_elseif>
      <do_if value="$commanderOrder.$warebasket? and $commanderOrder.$warebasket.count gt 0">
        <set_value name="$effectiveWareBasket" exact="$commanderOrder.$warebasket"/>
      </do_if>
      <do_elseif value="$commanderOrder.$specialWareBasket?">
        <set_value name="$effectiveWareBasket" exact="$commanderOrder.$specialWareBasket"/>
      </do_elseif>
    </do_if>

    <!-- Distance Penalty -->
    <set_value name="$effectiveDistancePenalty" exact="$distancepenalty"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$distancepenalty?">
      <set_value name="$effectiveDistancePenalty" exact="$commanderOrder.$distancepenalty"/>
    </do_if>

    <!-- Priority Wares -->
    <set_value name="$effectivePriorityWares" exact="if $prioritywares? then $prioritywares else []"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$prioritywares?">
      <set_value name="$effectivePriorityWares" exact="$commanderOrder.$prioritywares"/>
    </do_if>

    <!-- Priority Score Multiplier MK4-2: 1â€“10 (Â§3.4) -->
    <set_value name="$effectivePriorityScoreMultiplier" exact="if $priorityscoremultiplier? then $priorityscoremultiplier else 1"/>
    <do_if value="$effectivePriorityScoreMultiplier lt 1"><set_value name="$effectivePriorityScoreMultiplier" exact="1"/></do_if>
    <do_if value="$effectivePriorityScoreMultiplier gt 10"><set_value name="$effectivePriorityScoreMultiplier" exact="10"/></do_if>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$priorityscoremultiplier?">
      <set_value name="$effectivePriorityScoreMultiplier" exact="[$commanderOrder.$priorityscoremultiplier, 1].max"/>
      <do_if value="$effectivePriorityScoreMultiplier gt 10"><set_value name="$effectivePriorityScoreMultiplier" exact="10"/></do_if>
    </do_if>

    <!-- Logbook Entries -->
    <set_value name="$effectiveLogbookEntries" exact="$logbookentries"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$logbookentries?">
      <set_value name="$effectiveLogbookEntries" exact="$commanderOrder.$logbookentries"/>
    </do_if>

    <!-- Minimum Cargo Utilization -->
    <set_value name="$effectiveUseMinCargoThresholdFilter" exact="$useMinCargoThresholdFilter"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$useMinCargoThreshold?">
      <set_value name="$effectiveUseMinCargoThresholdFilter" exact="$commanderOrder.$useMinCargoThreshold"/>
    </do_if>
    <set_value name="$effectiveCargoTarget" exact="$cargotarget"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$minCargoUsed?">
      <set_value name="$effectiveCargoTarget" exact="$commanderOrder.$minCargoUsed"/>
    </do_if>

    <!-- Debug Level -->
    <set_value name="$effectiveDebugLevel" exact="$debuglevel"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$debuglevel?">
      <set_value name="$effectiveDebugLevel" exact="$commanderOrder.$debuglevel"/>
    </do_if>

    <!-- Trade Evaluation Logging -->
    <set_value name="$effectiveTradeEval" exact="$tradeeval"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$tradeeval?">
      <set_value name="$effectiveTradeEval" exact="$commanderOrder.$tradeeval"/>
    </do_if>

    <!-- Pilot skill cap for subordinate jump distances -->
    <set_value name="$pilotMaxJumps" exact="null"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <set_value name="$pilotSkill" exact="if $useVanillaXPOnly then (if this.ship.pilot? and this.ship.pilot.skill.piloting? then this.ship.pilot.skill.piloting else null) else (if this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level? then global.$GT_Pilots.{this.ship.pilot}.$Level else null)"/>
      <do_if value="not $useVanillaXPOnly and $pilotSkill != null">
        <do_if value="$pilotSkill le 2"><set_value name="$pilotMaxJumps" exact="1"/></do_if>
        <do_elseif value="$pilotSkill le 5"><set_value name="$pilotMaxJumps" exact="3"/></do_elseif>
        <do_elseif value="$pilotSkill le 8"><set_value name="$pilotMaxJumps" exact="5"/></do_elseif>
        <do_elseif value="$pilotSkill le 11"><set_value name="$pilotMaxJumps" exact="10"/></do_elseif>
        <do_elseif value="$pilotSkill le 13"><set_value name="$pilotMaxJumps" exact="15"/></do_elseif>
        <do_else><set_value name="$pilotMaxJumps" exact="25"/></do_else>
      </do_if>
    </do_if>

    <set_value name="$effectiveMaxBuy" exact="$maxbuy"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$jumpDistanceBuy?">
      <set_value name="$commanderMaxBuy" exact="$commanderOrder.$jumpDistanceBuy"/>
      <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderMaxBuy else [$commanderMaxBuy, $pilotMaxJumps].min"/>
    </do_if>

    <set_value name="$effectiveMaxSell" exact="$maxsell"/>
    <do_if value="$isSubordinate and $commanderOrder and $commanderOrder.$jumpDistanceCoverage?">
      <set_value name="$commanderMaxSell" exact="$commanderOrder.$jumpDistanceCoverage"/>
      <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderMaxSell else [$commanderMaxSell, $pilotMaxJumps].min"/>
    </do_if>

    <set_value name="$effectiveSearchDepth" exact="30"/>
    <set_value name="$effectiveMaxTrades" exact="[1, [3, if $maxTrades? then $maxTrades else 3].min].max"/>
    <set_value name="$effectiveBacktrackTolerance" exact="[0, [5, if $backtrackTolerance? then $backtrackTolerance else 1].min].max"/>
    <set_value name="$mk4DedicatedServe" exact="if $serveHomeOnly? then $serveHomeOnly else (if $dedicatedServe? then $dedicatedServe else false)"/>
    <set_value name="$mk4AllowPlayerSuppliers" exact="if $buyFromPlayer? then $buyFromPlayer else (if $allowPlayerSuppliers? then $allowPlayerSuppliers else true)"/>
    <set_value name="$mk4AllowAiSuppliers" exact="if $buyFromFaction? then $buyFromFaction else (if $allowAiSuppliers? then $allowAiSuppliers else true)"/>
    <set_value name="$mk4AllowResources" exact="if $allowResources? then $allowResources else true"/>
    <set_value name="$mk4AllowIntermediates" exact="if $allowIntermediates? then $allowIntermediates else true"/>
    <set_value name="$mk4AllowTradewares" exact="if $allowTradewares? then $allowTradewares else true"/>
    <do_if value="$isSubordinate and $commanderOrder">
      <do_if value="$commanderOrder.$maxTrades?">
        <set_value name="$effectiveMaxTrades" exact="[1, [3, $commanderOrder.$maxTrades].min].max"/>
      </do_if>
      <do_if value="$commanderOrder.$backtrackTolerance?">
        <set_value name="$effectiveBacktrackTolerance" exact="[0, [5, $commanderOrder.$backtrackTolerance].min].max"/>
      </do_if>
      <do_if value="$commanderOrder.$serveHomeOnly?">
        <set_value name="$mk4DedicatedServe" exact="$commanderOrder.$serveHomeOnly"/>
      </do_if>
      <do_elseif value="$commanderOrder.$dedicatedServe?">
        <set_value name="$mk4DedicatedServe" exact="$commanderOrder.$dedicatedServe"/>
      </do_elseif>
      <do_if value="$commanderOrder.$buyFromPlayer?">
        <set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$buyFromPlayer"/>
      </do_if>
      <do_elseif value="$commanderOrder.$allowPlayerSuppliers?">
        <set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$allowPlayerSuppliers"/>
      </do_elseif>
      <do_if value="$commanderOrder.$buyFromFaction?">
        <set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$buyFromFaction"/>
      </do_if>
      <do_elseif value="$commanderOrder.$allowAiSuppliers?">
        <set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$allowAiSuppliers"/>
      </do_elseif>
      <do_if value="$commanderOrder.$allowResources?">
        <set_value name="$mk4AllowResources" exact="$commanderOrder.$allowResources"/>
      </do_if>
      <do_if value="$commanderOrder.$allowIntermediates?">
        <set_value name="$mk4AllowIntermediates" exact="$commanderOrder.$allowIntermediates"/>
      </do_if>
      <do_if value="$commanderOrder.$allowTradewares?">
        <set_value name="$mk4AllowTradewares" exact="$commanderOrder.$allowTradewares"/>
      </do_if>
    </do_if>

    <!-- Persist effective settings on the order instance -->
    <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
    <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
    <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
    <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
    <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
    <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
    <set_value name="this.$mk42Priorities" exact="$mk42Priorities"/>
    <set_value name="this.$effectivePriorityBuildstorage" exact="$effectivePriorityBuildstorage"/>
    <set_value name="this.$effectivePriorityStations" exact="$effectivePriorityStations"/>
    <set_value name="this.$effectivePriorityAux" exact="$effectivePriorityAux"/>
    <set_value name="this.$effectivePriorityCarrier" exact="$effectivePriorityCarrier"/>
    <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
    <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
    <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
    <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
    <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
    <set_value name="this.$effectiveUseMinCargoThresholdFilter" exact="$effectiveUseMinCargoThresholdFilter"/>
    <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>
    <set_value name="this.$effectivePriorityWares" exact="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
    <set_value name="this.$effectivePriorityScoreMultiplier" exact="$effectivePriorityScoreMultiplier"/>
    <set_value name="this.$effectiveSearchDepth" exact="$effectiveSearchDepth"/>
    <set_value name="this.$effectiveIdleParking" exact="$effectiveIdleParking"/>
    <set_value name="this.$prevAutoJumpDistance" exact="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
    <set_value name="this.$effectiveMaxTrades" exact="$effectiveMaxTrades"/>
    <set_value name="this.$effectiveBacktrackTolerance" exact="$effectiveBacktrackTolerance"/>
    <set_value name="this.$mk4DedicatedServe" exact="$mk4DedicatedServe"/>
    <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4AllowPlayerSuppliers"/>
    <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4AllowAiSuppliers"/>
    <set_value name="this.$mk4AllowResources" exact="$mk4AllowResources"/>
    <set_value name="this.$mk4AllowIntermediates" exact="$mk4AllowIntermediates"/>
    <set_value name="this.$mk4AllowTradewares" exact="$mk4AllowTradewares"/>
    <set_value name="this.$mk4BuildStorageOnlyMode" exact="$mk4BuildStorageOnlyMode"/>
    
    <!-- Debug message for subordinates showing inherited settings -->
    <!-- PERFORMANCE: Only build inherited settings string if debug logging is enabled -->
    <!-- Skip expensive string concatenation loop if not needed -->
    <do_if value="$isSubordinate and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$inheritedSettings" exact="[]"/>
      <do_if value="$effectiveFleetCoordination != $fleetcoordination"><append_to_list name="$inheritedSettings" exact="'FleetCoord=' + $effectiveFleetCoordination"/></do_if>
      <do_if value="$effectiveAllowIllegal != $allowillegal"><append_to_list name="$inheritedSettings" exact="'AllowIllegal=' + $effectiveAllowIllegal"/></do_if>
      <do_if value="$effectiveEnforceRouteIllegalLegality != $enforceRouteIllegalLegality"><append_to_list name="$inheritedSettings" exact="'IllegalRouteFilter=' + $effectiveEnforceRouteIllegalLegality"/></do_if>
      <do_if value="$effectiveAutoWares != (if $autowares? then $autowares else true)"><append_to_list name="$inheritedSettings" exact="'AutoWares=' + $effectiveAutoWares"/></do_if>
      <do_if value="$effectiveDistancePenalty != $distancepenalty"><append_to_list name="$inheritedSettings" exact="'DistPenalty=' + $effectiveDistancePenalty + '%'"/></do_if>
      <do_if value="$effectiveLogbookEntries != $logbookentries"><append_to_list name="$inheritedSettings" exact="'Logbook=' + $effectiveLogbookEntries"/></do_if>
      <do_if value="$effectiveUseMinCargoThresholdFilter != $useMinCargoThresholdFilter"><append_to_list name="$inheritedSettings" exact="'UseMinCargo=' + $effectiveUseMinCargoThresholdFilter"/></do_if>
      <do_if value="$effectiveCargoTarget != $cargotarget"><append_to_list name="$inheritedSettings" exact="'MinCargoUtil=' + $effectiveCargoTarget + '%'"/></do_if>
      <do_if value="$effectiveDebugLevel != $debuglevel"><append_to_list name="$inheritedSettings" exact="'Debug=' + $effectiveDebugLevel"/></do_if>
      <do_if value="$effectiveTradeEval != $tradeeval"><append_to_list name="$inheritedSettings" exact="'TradeEval=' + $effectiveTradeEval"/></do_if>
      <do_if value="$effectiveMaxBuy != $jumpDistanceBuy"><append_to_list name="$inheritedSettings" exact="'JumpBuy=' + $effectiveMaxBuy + 'j'"/></do_if>
      <do_if value="$effectiveMaxSell != $jumpDistanceCoverage"><append_to_list name="$inheritedSettings" exact="'JumpCov=' + $effectiveMaxSell + 'j'"/></do_if>
      
      <do_if value="$inheritedSettings.count gt 0">
        <set_value name="$inheritedSettingsText" exact="''"/>
        <do_all exact="$inheritedSettings.count" counter="$i">
          <set_value name="$inheritedSettingsText" exact="$inheritedSettingsText + $inheritedSettings.{$i}"/>
          <do_if value="$i lt $inheritedSettings.count">
            <set_value name="$inheritedSettingsText" exact="$inheritedSettingsText + ', '"/>
          </do_if>
        </do_all>
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate inherited settings from ' + this.ship.commander.idcode + ': ' + $inheritedSettingsText" chance="100"/>
      </do_if>
    </do_if>
    
    <set_value name="$orderParams.$home" exact="$effectiveHome"/>
    <set_value name="$orderParams.$maxbuy" exact="$effectiveMaxBuy"/>
    <set_value name="$orderParams.$maxsell" exact="$effectiveMaxSell"/>
    <set_value name="$orderParams.$allowillegal" exact="$effectiveAllowIllegal"/>
    <set_value name="$orderParams.$enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="$orderParams.$factionpriority" exact="0"/>
    <set_value name="$orderParams.$autowares" exact="$effectiveAutoWares"/>
    <set_value name="$orderParams.$warebasket" exact="$effectiveWareBasket"/>
    <set_value name="$orderParams.$prioritywares" exact="$effectivePriorityWares"/>
    <set_value name="$orderParams.$priorityscoremultiplier" exact="$effectivePriorityScoreMultiplier"/>
    <set_value name="$orderParams.$distancepenalty" exact="$effectiveDistancePenalty"/>
    <set_value name="$orderParams.$useMinCargoThreshold" exact="$effectiveUseMinCargoThresholdFilter"/>
    <set_value name="$orderParams.$cargotarget" exact="$effectiveCargoTarget"/>
    <set_value name="$orderParams.$marketupdatefreq" exact="$marketupdatefreq"/>
    <set_value name="$orderParams.$debuglevel" exact="$effectiveDebugLevel"/>
    <set_value name="$orderParams.$tradeeval" exact="$effectiveTradeEval"/>
    <set_value name="$orderParams.$fleetcoordination" exact="$effectiveFleetCoordination"/>
    <set_value name="$orderParams.$logbookentries" exact="$effectiveLogbookEntries"/>
    <set_value name="$orderParams.$sectorwhitelist" exact="$effectiveSectorWhitelist"/>
    
    <!-- =========================================== -->
    <!-- HIGH-PERFORMANCE INITIALIZATION (Option A) -->
    <!-- =========================================== -->
    
    <!-- Fast variable assignment - using effective (inherited) values -->
    <set_value name="$gt_debuglevel" exact="$effectiveDebugLevel"/>
    <!-- Only set debugchance > 0 if GT debug logging is enabled globally -->
    <set_value name="$debugchance" exact="0"/>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$debugchance" exact="if $gt_debuglevel ge 2 then 100 else if $gt_debuglevel ge 1 then 50 else 0"/>
    </do_if>
    <set_value name="this.$debugchance" exact="$debugchance"/>
    
    <!-- Cache blacklistgroup once (avoids 6 repeated lookups) -->
    <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
    <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
      <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
    </do_if>
    
    <!-- Core trading parameters (performance optimized) - using effective (inherited) values -->
    <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
    <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
    <set_value name="$gt_factionpriority" exact="0"/>
    <!-- Convert distance penalty from 0-100% to multiplier: 0%=0.0, 50%=1.0, 100%=2.0 -->
    <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
    <set_value name="$gt_useMinCargoThreshold" exact="$effectiveUseMinCargoThresholdFilter"/>
    <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
    <set_value name="$gt_marketupdatefreq" exact="$marketupdatefreq"/>
    <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
    
    <!-- Global defaults (fastest approach - direct assignment) -->
    <set_value name="$gt_autotraining" exact="true"/>
    <set_value name="$gt_fleetcoord" exact="false"/>
    
    <!-- Ware selection (optimized) - using effective inherited values -->
    <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>
    
    <!-- Single non-blocking signal to MD system -->
    <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
      $Ship = this.ship,
      $Config = table[
        $allowillegal = $gt_allowillegal,
        $debuglevel = $gt_debuglevel,
        $autotraining = $gt_autotraining
      ]
    ]"/>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': High-performance initialization complete'" chance="@this.$debugchance"/>
      <do_if value="@$effectiveHome.exists">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Operating with home base: ' + @$effectiveHome.knownname + ' (maxbuy=' + $effectiveMaxBuy + ', maxsell=' + $effectiveMaxSell + ')'" chance="@this.$debugchance"/>
      </do_if>
    </do_if>
    
    <!-- Log configuration summary -->
    <do_if value="$gt_debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === CONFIGURATION SUMMARY ==='" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Illegal=' + $effectiveAllowIllegal + ', IllegalRouteFilter=' + $effectiveEnforceRouteIllegalLegality + ', DistancePenalty=' + $effectiveDistancePenalty + '%'" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FleetCoord=' + $effectiveFleetCoordination + ', LogbookEntries=' + $effectiveLogbookEntries" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Distance limits: MaxBuy=' + $effectiveMaxBuy + ' jumps, MaxSell=' + $effectiveMaxSell + ' jumps'" chance="100"/>
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': AutoWares=' + $effectiveAutoWares + ', WareBasket=' + $effectiveWareBasket.count + ' wares, TradeEval=' + $effectiveTradeEval" chance="100"/>
    </do_if>
    
    <!-- ============================================================================= -->
    <!-- END MODULAR INITIALIZATION                                                   -->
    <!-- ============================================================================= -->
    
    <!-- Initialize pilot tracking for event-driven pilot change detection -->
    <!-- Pilot changes are detected at natural restart points: -->
    <!-- - After successful trade completion (trade_completed label) -->
    <!-- - On script restart (init label) -->
    <set_value name="this.$trackedPilot" exact="this.ship.pilot"/>
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Tracking pilot: ' + @this.$trackedPilot.name + ' (event-driven detection enabled)'" chance="@this.$debugchance"/>
    </do_if>
    
    <!-- Do not initialize commander tracking here - let init label handle it -->
    <!-- This prevents false positives when script restarts after commander assignment -->
    <!-- The init label will detect changes by comparing with previous value -->
    
    <!-- Register pilot on first run (for initial assignment or ship with existing cargo) -->
    <!-- This ensures ships get renamed even when first assigned to GT order -->
    <do_if value="this.ship.pilot">
      <!-- NOTE: Cannot use wait/do_while in init block - pilot transfer check moved to main loop -->
      <!-- Pilot transfer takes time (crew transfer pod travel), but UI shows pilot as assigned immediately -->
      <!-- Main loop will check if pilot is actually on ship before proceeding -->
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INITIAL REGISTRATION: Registering pilot ' + @this.ship.pilot.name + ' on order start'" chance="100"/>
      </do_if>
      <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
        $updateType = 'pilot_change',
        $Ship = this.ship,
        $pilot = this.ship.pilot,
        $oldPilot = null
      ]"/>
      
      <!-- NOTE: Cannot use wait in init block - registration check will happen in main loop -->
      <!-- Registration happens synchronously via run_actions, but signal processing is asynchronous -->
      <!-- Main loop will check registration status before requesting trade search -->
    </do_if>
    
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <debug_text text="'[GalaxyTrader MK3] ' + this.ship.idcode + ': === INITIALIZATION COMPLETE === Starting main trading loop...'" chance="100"/>
    </do_if>
    
  </init>

  <attention min="unknown">
    <actions>
      
      <!-- Debug: Confirm we entered attention block -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === ATTENTION BLOCK ENTERED ==='" chance="100"/>
      </do_if>
      
      <!-- Subordinate reinitialization: Jump here to restart and re-inherit commander settings -->
      <label name="init"/>

      <!-- Read AI yield interval from global settings (persisted to instance var to survive waits) -->
      <set_value name="this.$gt_yieldMs" exact="1"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
        <set_value name="this.$gt_yieldMs" exact="[1, @global.$GT_GlobalSettings.$Performance.$AIYieldInterval].max"/>
      </do_if>

      <!-- CRITICAL: Ensure instance wait time storage ALWAYS exists on restarts/resumes. -->
      <!-- Purpose A: Pre-request wait for GT_Trade_Found signal (milliseconds) -->
      <set_value name="this.$tradeFoundSignalWaitTime" exact="5ms"/>
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <set_value name="this.$retryCooldown" exact="10s"/>

      <!-- Clear leaked active-trade tracking on (re)start. global.$GT_ActiveTrade.{ship} is written
           when a trade is selected (pre-execution) and normally cleared at trade_completed. A
           commander-settings restart (abort_called_scripts resume="init") bypasses that cleanup,
           leaving a phantom entry that the diagnostic reports as an active trade. Only clear it when
           the hold is empty (no haul in progress) â€” a ship carrying cargo keeps its entry. -->
      <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{this.ship}? and this.ship.cargo.free.all ge this.ship.cargo.capacity.all">
        <remove_value name="global.$GT_ActiveTrade.{this.ship}"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (Script Restart) -->
      <!-- ======================================= -->
      <!-- Check for pilot changes when script restarts (natural restart point) -->
      <set_value name="$currentPilot" exact="@this.ship.pilot"/>
      <do_if value="this.$trackedPilot? and $currentPilot != this.$trackedPilot">
        <!-- Pilot changed! Send signal to MD system -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PILOT CHANGE DETECTED on script restart! Old: ' + @this.$trackedPilot.name + ', New: ' + @$currentPilot.name" chance="100"/>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
          $updateType = 'pilot_change',
          $Ship = this.ship,
          $pilot = $currentPilot,
          $oldPilot = this.$trackedPilot
        ]"/>
      </do_if>
      <!-- Update tracked pilot (always, even if no change) -->
      <set_value name="this.$trackedPilot" exact="$currentPilot"/>
      
      <!-- CRITICAL: Check if pilot is missing (pilot was transferred away) -->
      <!-- If GT order is running but ship has no pilot, cleanup and self-cancel -->
      <do_if value="not $currentPilot">
        <!-- Vanilla transfer pods can take minutes; if a paused GT pilot is already linked to this
             ship id, keep the GT order alive briefly until the pilot physically arrives. -->
        <set_value name="$pendingTransferredPilot" exact="false"/>
        <set_value name="$pendingPilotName" exact="'NONE'"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$pk">
            <set_value name="$candidatePilot" exact="$pilotKeys.{$pk}"/>
            <do_if value="$candidatePilot and global.$GT_Pilots.{$candidatePilot}? and global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == this.ship.idcode and global.$GT_Pilots.{$candidatePilot}.$Status? and global.$GT_Pilots.{$candidatePilot}.$Status == 'paused'">
              <set_value name="$pendingTransferredPilot" exact="true"/>
              <set_value name="$pendingPilotName" exact="if $candidatePilot.name? then $candidatePilot.name else 'UNKNOWN'"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$pendingTransferredPilot">
          <do_if value="not this.$pendingPilotTransferSince?">
            <set_value name="this.$pendingPilotTransferSince" exact="player.age"/>
          </do_if>
          <set_value name="$pendingTransferElapsed" exact="player.age - this.$pendingPilotTransferSince"/>
          
          <do_if value="$pendingTransferElapsed lt 15min">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Missing pilot but transfer is in progress for ' + $pendingPilotName + ' (elapsed=' + ($pendingTransferElapsed / 1s) + 's) - waiting before cancellation'" chance="100"/>
            </do_if>
            <wait exact="5s"/>
            <return/>
          </do_if>
        </do_if>
        
        <remove_value name="this.$pendingPilotTransferSince"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MISSING PILOT DETECTED - pilot was transferred away, cleaning up and self-canceling GT order'" chance="100"/>
        </do_if>
        
        <!-- Get original ship name from ship registry -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{this.ship}.$OriginalShipName"/>
        </do_if>
        
        <!-- Send cleanup signal (name restoration handled by MD system) -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = null,
          $Reason = 'Pilot transferred away - GT order cannot run without pilot',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Cancel all active orders (trade orders, etc.) -->
        <cancel_all_orders object="this.ship"/>
        
        <!-- Self-cancel GT order -->
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Restore XPBlocked if BlockedLevel still exists (ship restart/reinit) -->
      <!-- Also update ship name to show ADVANCE label when XPBlocked is restored -->
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <set_value name="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] Restored XPBlocked for pilot ' + this.ship.pilot.name + ' on ship restart (BlockedLevel: ' + global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel + ')'" chance="100"/>
          </do_if>
          
          <!-- Update ship name to show ADVANCE label when XPBlocked is restored -->
          <!-- This ensures the ship name reflects the blocked state after restart -->
          <!-- Calculate rank title based on blocked level -->
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          <set_value name="$rankTitle" exact="'Lehrling'"/>
          <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
            <set_value name="$rankIndex" exact="($blockedLevel / 3)i + 1"/>
            <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
              <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
            </do_if>
            <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
              <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
            </do_if>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
            $Ship = this.ship,
            $pilot = this.ship.pilot,
            $xp = @global.$GT_Pilots.{this.ship.pilot}.$XP,
            $level = $blockedLevel,
            $rank = $rankTitle,
            $nameType = 'blocked'
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] Updated ship name to show ADVANCE label after XPBlocked restoration: ' + this.ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Initialize default order tracking -->
      <!-- Track the current default order to detect when GT order is removed -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="not this.$trackedDefaultOrder?">
        <!-- First time - initialize tracked order -->
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
        
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2'">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] GT order assigned to ' + this.ship.idcode + ' - sending GT_Order_Assigned signal'" chance="100"/>
          </do_if>
          <run_script name="'lib.gt.attention.emit_gt_state_changed'">
            <param name="ship" value="this.ship"/>
            <param name="isGTActive" value="true"/>
            <param name="source" value="'AI_INIT_ASSIGN'"/>
          </run_script>
        </do_if>
      </do_if>
      <do_elseif value="this.$trackedDefaultOrder != 'GalaxyTraderMK3' and this.$trackedDefaultOrder != 'GalaxyTraderMK4Supply2' and ($currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2')">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] GT order reassigned to ' + this.ship.idcode + ' (old: ' + this.$trackedDefaultOrder + ', new: ' + $currentDefaultOrder + ') - sending GT_Order_Assigned signal'" chance="100"/>
        </do_if>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="true"/>
          <param name="source" value="'AI_INIT_REASSIGN'"/>
        </run_script>
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_elseif>
      <do_if value="(this.$trackedDefaultOrder == 'GalaxyTraderMK3' or this.$trackedDefaultOrder == 'GalaxyTraderMK4Supply2') and ($currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply2')">
        <!-- CRITICAL FIX: Check if ship is still GT-controlled via commander BEFORE sending cancellation -->
        <!-- When a subordinate is assigned to a commander, default order changes from GalaxyTraderMK4Supply2 to Assist -->
        <!-- But ship is still GT-controlled via commander - don't send cancellation signal -->
        <set_value name="$isStillGTControlled" exact="false"/>
        
        <!-- Check 1: Direct GT order -->
        <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2'">
          <set_value name="$isStillGTControlled" exact="true"/>
        </do_if>
        
        <!-- Check 2: Subordinate to GT commander with Assist order -->
        <do_if value="not $isStillGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <do_if value="$currentDefaultOrder == 'Assist'">
              <set_value name="$isStillGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <do_if value="not $isStillGTControlled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in init label, old: ' + this.$trackedDefaultOrder + ', new: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', still GT-controlled: ' + $isStillGTControlled + ')'" chance="100"/>
          </do_if>
          <run_script name="'lib.gt.attention.emit_gt_state_changed'">
            <param name="ship" value="this.ship"/>
            <param name="isGTActive" value="false"/>
            <param name="source" value="'AI_INIT_CANCEL'"/>
          </run_script>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: Default order changed from GalaxyTraderMK3 to ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ' BUT ship still GT-controlled via commander - NOT sending cancellation'" chance="100"/>
          </do_if>
        </do_else>
        
        <run_script name="'lib.gt.attention.restore_original_name'">
          <param name="ship" value="this.ship"/>
          <param name="reason" value="'GT order cancelled - restoring original name'"/>
          <param name="skipIfStillGT" value="true"/>
          <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply2']"/>
        </run_script>
        
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_elseif value="this.$trackedDefaultOrder != $currentDefaultOrder">
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_elseif>
      
      <!-- Initialize commander tracking and detect commander assignment -->
      <!-- This runs when script restarts (e.g., after commander assignment) -->
      <!-- Check for changes BEFORE initializing trackedCommander -->
      <set_value name="$currentCommander" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$currentCommander" exact="this.ship.commander"/>
      </do_if>
      
      <!-- Store previous tracked commander BEFORE checking/updating -->
      <set_value name="$previousTrackedCommander" exact="null"/>
      <do_if value="this.$trackedCommander?">
        <set_value name="$previousTrackedCommander" exact="this.$trackedCommander"/>
      </do_if>
      
      <!-- Log current state -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] PHASE 6 DEBUG: ' + this.ship.idcode + ' - currentCommander: ' + (if @$currentCommander.exists then @$currentCommander.idcode else 'NONE') + ', previousTrackedCommander: ' + (if @$previousTrackedCommander.exists then @$previousTrackedCommander.idcode else 'NONE')" chance="100"/>
      </do_if>
      
      <!-- Check if commander changed (compare with previous tracked value BEFORE updating) -->
      <do_if value="not this.$trackedCommander?">
        <!-- First time - initialize tracked commander and send signal if commander exists -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
        <do_if value="@$currentCommander.exists">
          <!-- Commander exists on first check - send initialization signal -->
          <set_value name="$newCommanderHasGT" exact="false"/>
          <do_if value="$currentCommander.defaultorder? and ((@$currentCommander.defaultorder.id == 'GalaxyTraderMK3' or @$currentCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$currentCommander.defaultorder.id == 'Assist' and $currentCommander.defaultorder.$baseorder? and (@$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$currentCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'Commander_Changed',
            $Commander = $currentCommander,
            $CommanderHasGT = $newCommanderHasGT
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 6: Commander initialized for ' + this.ship.idcode + ' (commander: ' + $currentCommander.idcode + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="((@$previousTrackedCommander.exists == true) and not (@$currentCommander.exists == true)) or (not (@$previousTrackedCommander.exists == true) and (@$currentCommander.exists == true))">
        <!-- Commander state changed (was null, now exists OR was exists, now null) -->
        <set_value name="$oldCommander" exact="$previousTrackedCommander"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if old commander had GT order (for name restoration when subordinate removed) -->
        <set_value name="$oldCommanderHasGT" exact="false"/>
        <do_if value="@$oldCommander.exists">
          <do_if value="$oldCommander.defaultorder? and ((@$oldCommander.defaultorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$oldCommander.defaultorder.id == 'Assist' and $oldCommander.defaultorder.$baseorder? and (@$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$oldCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + (if @$oldCommander.exists then @$oldCommander.idcode else 'NONE') + ', new: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <do_if value="$oldCommanderHasGT and not $newCommanderHasGT and this.ship.pilot?">
          <run_script name="'lib.gt.attention.restore_original_name'">
            <param name="ship" value="this.ship"/>
            <param name="reason" value="'Subordinate removed from GT commander - restoring original name'"/>
            <param name="skipIfStillGT" value="true"/>
            <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply2']"/>
          </run_script>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      <do_elseif value="(@$previousTrackedCommander.exists == true) and (@$currentCommander.exists == true) and $previousTrackedCommander != $currentCommander">
        <!-- Commander changed to different commander -->
        <set_value name="$oldCommander" exact="$previousTrackedCommander"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
          <set_value name="$newCommanderHasGT" exact="true"/>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + $oldCommander.idcode + ', new: ' + $newCommander.idcode + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      <do_else>
        <!-- Commander is the same - no change, but ensure tracked value is updated -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_else>
      
      <!-- Re-inherit settings only for ship-subordinates.
           Station commanders must not override MK4 station-home scope. -->
      <do_if value="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
        <set_value name="$commanderOrder" exact="this.ship.commander.defaultorder"/>
        <do_if value="$commanderOrder?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Re-inheriting settings from commander ' + this.ship.commander.idcode" chance="100"/>
          </do_if>
          <!-- Re-inherit all commander settings -->
          <do_if value="$commanderOrder.$fleetcoordination?"><set_value name="$effectiveFleetCoordination" exact="$commanderOrder.$fleetcoordination"/></do_if>
          <do_if value="$commanderOrder.$allowillegal?"><set_value name="$effectiveAllowIllegal" exact="$commanderOrder.$allowillegal"/></do_if>
          <do_if value="$commanderOrder.$enforceRouteIllegalLegality?"><set_value name="$effectiveEnforceRouteIllegalLegality" exact="$commanderOrder.$enforceRouteIllegalLegality"/></do_if>
          <do_if value="$commanderOrder.$ignorecarrieraux?"><set_value name="$effectiveIgnoreCarrierAux" exact="$commanderOrder.$ignorecarrieraux"/></do_if>
          <do_if value="$commanderOrder.$priorityBuildstorage?"><set_value name="$effectivePriorityBuildstorage" exact="$commanderOrder.$priorityBuildstorage"/></do_if>
          <do_if value="$commanderOrder.$priorityStations?"><set_value name="$effectivePriorityStations" exact="$commanderOrder.$priorityStations"/></do_if>
          <do_if value="$commanderOrder.$priorityAux?"><set_value name="$effectivePriorityAux" exact="$commanderOrder.$priorityAux"/></do_if>
          <do_if value="$commanderOrder.$priorityCarrier?"><set_value name="$effectivePriorityCarrier" exact="$commanderOrder.$priorityCarrier"/></do_if>
          <set_value name="$effectiveIgnoreBuildStorage" exact="$effectivePriorityBuildstorage == 0"/>
          <set_value name="$effectiveIgnoreCarrierAux" exact="$effectivePriorityAux == 0 and $effectivePriorityCarrier == 0"/>
          <do_if value="$commanderOrder.$ignoretraderules?"><set_value name="$effectiveIgnoreTradeRules" exact="$commanderOrder.$ignoretraderules"/></do_if>
          <do_if value="$commanderOrder.$ignoremk1supply?"><set_value name="$effectiveIgnoreMK1Supply" exact="$commanderOrder.$ignoremk1supply"/></do_if>
          <do_if value="$commanderOrder.$home?"><set_value name="$effectiveHome" exact="$commanderOrder.$home"/></do_if>
          <do_if value="$commanderOrder.$sectorwhitelist?"><set_value name="$effectiveSectorWhitelist" exact="$commanderOrder.$sectorwhitelist"/></do_if>
          <!-- Ware filter (MK3 parity; legacy lockWares / specialWareBasket) -->
          <do_if value="$commanderOrder.$autowares?"><set_value name="$effectiveAutoWares" exact="$commanderOrder.$autowares"/></do_if>
          <do_elseif value="$commanderOrder.$lockWares?"><set_value name="$effectiveAutoWares" exact="not $commanderOrder.$lockWares"/></do_elseif>
          <do_if value="$commanderOrder.$warebasket? and $commanderOrder.$warebasket.count gt 0"><set_value name="$effectiveWareBasket" exact="$commanderOrder.$warebasket"/></do_if>
          <do_elseif value="$commanderOrder.$specialWareBasket?"><set_value name="$effectiveWareBasket" exact="$commanderOrder.$specialWareBasket"/></do_elseif>
          <do_if value="$commanderOrder.$prioritywares?"><set_value name="$effectivePriorityWares" exact="$commanderOrder.$prioritywares"/></do_if>
          <do_if value="$commanderOrder.$priorityscoremultiplier?"><set_value name="$effectivePriorityScoreMultiplier" exact="[$commanderOrder.$priorityscoremultiplier, 1].max"/><do_if value="$effectivePriorityScoreMultiplier gt 10"><set_value name="$effectivePriorityScoreMultiplier" exact="10"/></do_if></do_if>
          <do_if value="$effectivePriorityScoreMultiplier? and $effectivePriorityScoreMultiplier gt 300"><set_value name="$effectivePriorityScoreMultiplier" exact="300"/></do_if>
          <do_if value="$commanderOrder.$distancepenalty?"><set_value name="$effectiveDistancePenalty" exact="$commanderOrder.$distancepenalty"/></do_if>
          <do_if value="$commanderOrder.$logbookentries?"><set_value name="$effectiveLogbookEntries" exact="$commanderOrder.$logbookentries"/></do_if>
          <do_if value="$commanderOrder.$useMinCargoThreshold?"><set_value name="$effectiveUseMinCargoThresholdFilter" exact="$commanderOrder.$useMinCargoThreshold"/></do_if>
          <do_if value="$commanderOrder.$minCargoUsed?"><set_value name="$effectiveCargoTarget" exact="$commanderOrder.$minCargoUsed"/></do_if>
          <do_if value="$commanderOrder.$maxTrades?"><set_value name="$effectiveMaxTrades" exact="[1, [3, $commanderOrder.$maxTrades].min].max"/></do_if>
          <do_if value="$commanderOrder.$backtrackTolerance?"><set_value name="$effectiveBacktrackTolerance" exact="[0, [5, $commanderOrder.$backtrackTolerance].min].max"/></do_if>
          <do_if value="$commanderOrder.$serveHomeOnly?"><set_value name="$mk4DedicatedServe" exact="$commanderOrder.$serveHomeOnly"/></do_if>
          <do_elseif value="$commanderOrder.$dedicatedServe?"><set_value name="$mk4DedicatedServe" exact="$commanderOrder.$dedicatedServe"/></do_elseif>
          <do_if value="$commanderOrder.$buyFromPlayer?"><set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$buyFromPlayer"/></do_if>
          <do_elseif value="$commanderOrder.$allowPlayerSuppliers?"><set_value name="$mk4AllowPlayerSuppliers" exact="$commanderOrder.$allowPlayerSuppliers"/></do_elseif>
          <do_if value="$commanderOrder.$buyFromFaction?"><set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$buyFromFaction"/></do_if>
          <do_elseif value="$commanderOrder.$allowAiSuppliers?"><set_value name="$mk4AllowAiSuppliers" exact="$commanderOrder.$allowAiSuppliers"/></do_elseif>
          <do_if value="$commanderOrder.$allowResources?"><set_value name="$mk4AllowResources" exact="$commanderOrder.$allowResources"/></do_if>
          <do_if value="$commanderOrder.$allowIntermediates?"><set_value name="$mk4AllowIntermediates" exact="$commanderOrder.$allowIntermediates"/></do_if>
          <do_if value="$commanderOrder.$allowTradewares?"><set_value name="$mk4AllowTradewares" exact="$commanderOrder.$allowTradewares"/></do_if>
          <do_if value="$commanderOrder.$debuglevel?"><set_value name="$effectiveDebugLevel" exact="$commanderOrder.$debuglevel"/></do_if>
          <do_if value="$commanderOrder.$tradeeval?"><set_value name="$effectiveTradeEval" exact="$commanderOrder.$tradeeval"/></do_if>
          <!-- Re-inherit max jump distances with pilot capability cap -->
          <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
          <run_script name="'lib.gt.pathfinding'" result="$pilotSkill">
            <param name="mode" value="'effective_pilot_level'"/>
            <param name="ship" value="this.ship"/>
            <param name="includeCommander" value="false"/>
          </run_script>
          <set_value name="$pilotMaxJumps" exact="null"/>
          <do_if value="not $useVanillaXPOnly">
            <run_script name="'lib.gt.pathfinding'" result="$pilotMaxJumps">
              <param name="mode" value="'pilot_max_jumps'"/>
              <param name="pilotSkill" value="$pilotSkill"/>
            </run_script>
          </do_if>
          <do_if value="$commanderOrder.$jumpDistanceBuy?">
            <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderOrder.$jumpDistanceBuy else [$commanderOrder.$jumpDistanceBuy, $pilotMaxJumps].min"/>
          </do_if>
          <do_if value="$commanderOrder.$jumpDistanceCoverage?">
            <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $pilotMaxJumps == null then $commanderOrder.$jumpDistanceCoverage else [$commanderOrder.$jumpDistanceCoverage, $pilotMaxJumps].min"/>
          </do_if>
          <!-- Refresh derived variables used by the trading loop / MD requests -->
          <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
          <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
          <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
          <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
          <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Settings re-inherited successfully'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Rehydrate missing local effective vars before persisting.
           AI local $vars can be missing on some resume paths. -->
      <do_if value="not $effectiveMaxBuy?">
        <set_value name="$effectiveMaxBuy" exact="if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else $jumpDistanceBuy"/>
      </do_if>
      <do_if value="not $effectiveMaxSell?">
        <set_value name="$effectiveMaxSell" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else $jumpDistanceCoverage"/>
      </do_if>
      <do_if value="not $effectiveSearchDepth?">
        <set_value name="$effectiveSearchDepth" exact="if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30"/>
      </do_if>
      <do_if value="not $effectiveMaxTrades?">
        <set_value name="$effectiveMaxTrades" exact="if this.$effectiveMaxTrades? then this.$effectiveMaxTrades else [1, [3, if $maxTrades? then $maxTrades else 3].min].max"/>
      </do_if>
      <do_if value="not $effectiveBacktrackTolerance?">
        <set_value name="$effectiveBacktrackTolerance" exact="if this.$effectiveBacktrackTolerance? then this.$effectiveBacktrackTolerance else [0, [5, if $backtrackTolerance? then $backtrackTolerance else 1].min].max"/>
      </do_if>
      <do_if value="not $mk4DedicatedServe?">
        <set_value name="$mk4DedicatedServe" exact="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else (if $serveHomeOnly? then $serveHomeOnly else (if $dedicatedServe? then $dedicatedServe else false))"/>
      </do_if>
      <do_if value="not $mk4AllowPlayerSuppliers?">
        <set_value name="$mk4AllowPlayerSuppliers" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else (if $buyFromPlayer? then $buyFromPlayer else (if $allowPlayerSuppliers? then $allowPlayerSuppliers else true))"/>
      </do_if>
      <do_if value="not $mk4AllowAiSuppliers?">
        <set_value name="$mk4AllowAiSuppliers" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else (if $buyFromFaction? then $buyFromFaction else (if $allowAiSuppliers? then $allowAiSuppliers else true))"/>
      </do_if>
      <do_if value="not $mk4AllowResources?">
        <set_value name="$mk4AllowResources" exact="if this.$mk4AllowResources? then this.$mk4AllowResources else (if $allowResources? then $allowResources else true)"/>
      </do_if>
      <do_if value="not $mk4AllowIntermediates?">
        <set_value name="$mk4AllowIntermediates" exact="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else (if $allowIntermediates? then $allowIntermediates else true)"/>
      </do_if>
      <do_if value="not $mk4AllowTradewares?">
        <set_value name="$mk4AllowTradewares" exact="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else (if $allowTradewares? then $allowTradewares else true)"/>
      </do_if>
      <do_if value="not $effectiveIgnoreBuildStorage?">
        <set_value name="$effectiveIgnoreBuildStorage" exact="if this.$effectiveIgnoreBuildStorage? then this.$effectiveIgnoreBuildStorage else false"/>
      </do_if>
      <do_if value="not $mk42Priorities?">
        <set_value name="$mk42Priorities" exact="if this.$mk42Priorities? then this.$mk42Priorities else table[$Buildstorage = (if this.$effectivePriorityBuildstorage? then this.$effectivePriorityBuildstorage else 10), $Stations = (if this.$effectivePriorityStations? then this.$effectivePriorityStations else 8), $Aux = (if this.$effectivePriorityAux? then this.$effectivePriorityAux else 0), $Carrier = (if this.$effectivePriorityCarrier? then this.$effectivePriorityCarrier else 0)]"/>
      </do_if>
      <do_if value="not $effectiveIgnoreTradeRules?">
        <set_value name="$effectiveIgnoreTradeRules" exact="if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false"/>
      </do_if>
      <do_if value="not $effectiveIgnoreMK1Supply?">
        <set_value name="$effectiveIgnoreMK1Supply" exact="if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true"/>
      </do_if>
      <do_if value="not $effectiveIgnoreCarrierAux?">
        <set_value name="$effectiveIgnoreCarrierAux" exact="if this.$effectiveIgnoreCarrierAux? then this.$effectiveIgnoreCarrierAux else false"/>
      </do_if>
      <do_if value="not $effectiveIgnoreBuildStorage?">
        <set_value name="$effectiveIgnoreBuildStorage" exact="if this.$effectiveIgnoreBuildStorage? then this.$effectiveIgnoreBuildStorage else false"/>
      </do_if>
      <do_if value="not $effectiveDistancePenalty?">
        <set_value name="$effectiveDistancePenalty" exact="if this.$effectiveDistancePenalty? then this.$effectiveDistancePenalty else $distancepenalty"/>
      </do_if>
      <do_if value="not $effectiveFleetCoordination?">
        <set_value name="$effectiveFleetCoordination" exact="if this.$effectiveFleetCoordination? then this.$effectiveFleetCoordination else $fleetcoordination"/>
      </do_if>
      <do_if value="not $effectiveFactionPriority?">
        <set_value name="$effectiveFactionPriority" exact="0"/>
      </do_if>
      <do_if value="not $effectiveAllowIllegal?">
        <set_value name="$effectiveAllowIllegal" exact="if this.$effectiveAllowIllegal? then this.$effectiveAllowIllegal else $allowillegal"/>
      </do_if>
      <do_if value="not $effectiveEnforceRouteIllegalLegality?">
        <set_value name="$effectiveEnforceRouteIllegalLegality" exact="if this.$effectiveEnforceRouteIllegalLegality? then this.$effectiveEnforceRouteIllegalLegality else $enforceRouteIllegalLegality"/>
      </do_if>
      <do_if value="not $effectiveLogbookEntries?">
        <set_value name="$effectiveLogbookEntries" exact="if this.$effectiveLogbookEntries? then this.$effectiveLogbookEntries else $logbookentries"/>
      </do_if>
      <do_if value="not $effectiveUseMinCargoThresholdFilter?">
        <set_value name="$effectiveUseMinCargoThresholdFilter" exact="if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else (if $useMinCargoThreshold? then $useMinCargoThreshold else false)"/>
      </do_if>
      <do_if value="not $effectivePriorityWares?">
        <set_value name="$effectivePriorityWares" exact="if this.$effectivePriorityWares? then this.$effectivePriorityWares else (if $prioritywares? then $prioritywares else [])"/>
      </do_if>
      <do_if value="not $effectivePriorityScoreMultiplier?">
        <set_value name="$effectivePriorityScoreMultiplier" exact="if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else (if $priorityscoremultiplier? then $priorityscoremultiplier else 1)"/>
      </do_if>

      <!-- Persist effective settings (survive save/load resume) -->
      <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
      <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
      <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
      <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
      <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
      <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
      <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
      <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
      <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
      <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
      <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
      <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
      <set_value name="this.$effectiveUseMinCargoThresholdFilter" exact="$effectiveUseMinCargoThresholdFilter"/>
      <set_value name="this.$effectiveSearchDepth" exact="$effectiveSearchDepth"/>
      <set_value name="this.$effectiveMaxTrades" exact="$effectiveMaxTrades"/>
      <set_value name="this.$effectiveBacktrackTolerance" exact="$effectiveBacktrackTolerance"/>
      <set_value name="this.$mk4DedicatedServe" exact="$mk4DedicatedServe"/>
      <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4AllowPlayerSuppliers"/>
      <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4AllowAiSuppliers"/>
      <set_value name="this.$mk4AllowResources" exact="$mk4AllowResources"/>
      <set_value name="this.$mk4AllowIntermediates" exact="$mk4AllowIntermediates"/>
      <set_value name="this.$mk4AllowTradewares" exact="$mk4AllowTradewares"/>
        
      <!-- Initialize subordinate count tracking -->
      <!-- Track when this ship becomes a commander (gets subordinates) -->
      <set_value name="$currentSubordinateCount" exact="0"/>
      <do_if value="this.ship.subordinates?">
        <set_value name="$currentSubordinateCount" exact="this.ship.subordinates.count"/>
      </do_if>
      <do_if value="not this.$trackedSubordinateCount?">
        <!-- First time - initialize tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_if>
      
      <!-- Reset was_subordinate flag based on CURRENT state, not previous state -->
      <!-- This prevents false positives when a ship transitions from subordinate â†’ independent -->
      <!-- If ship has a direct GT order, it's independent, not orphaned -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <do_if value="this.ship.defaultorder? and @this.ship.defaultorder.id == 'GalaxyTraderMK4Supply2'">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <!-- Reset was_subordinate based on current commander status -->
      <set_value name="$isCurrentlySubordinate" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship"/>
      <set_value name="this.$was_subordinate" exact="$isCurrentlySubordinate"/>
      
      <!-- If ship has direct GT order but was previously subordinate, clear the flag -->
      <!-- This allows ships to transition from subordinate â†’ independent without being treated as orphaned -->
      <do_if value="$hasDirectGTOrder and not $isCurrentlySubordinate">
        <set_value name="this.$was_subordinate" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Reset was_subordinate flag (has direct GT order, not subordinate)'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- =============================================== -->
      <!-- MAIN TRADING LOOP (Modularized)                -->
      <!-- =============================================== -->
      
      <label name="main_loop"/>

      <!-- Idle park timed release (trader keeps searching; hold expiry handled here). -->
      <run_script name="'lib.gt.idlepark'">
        <param name="handoffMode" value="'check_timed_release'"/>
        <param name="handoffShip" value="this.ship"/>
        <param name="home" value="if this.$effectiveHome? and this.$effectiveHome != null and this.$effectiveHome.exists then this.$effectiveHome else this.ship.sector"/>
        <param name="debugchance" value="if this.$debugchance? then this.$debugchance else 0"/>
      </run_script>
      
      <!-- Unified ship name refresh (home sector, op-state, XP â€” content dedupe in MD) -->
      <run_script name="'lib.gt.attention.refresh_ship_name'">
        <param name="ship" value="this.ship"/>
      </run_script>
      <run_script name="'lib.gt.attention.autojump_distance_toggle'">
        <param name="autoJumpDistanceByLevel" value="if $autoJumpDistanceByLevel? then $autoJumpDistanceByLevel else false"/>
      </run_script>

      <!-- NOTE: Signal check removed from here - maintenance must ALWAYS run before trade execution -->
      <!-- Signals will be checked AFTER maintenance completes (line 2147) to ensure maintenance is never skipped -->
      <!-- NOTE: Do NOT clear global.$GT_TradesAwaitingValidation here - it may contain fresh trade data -->
      <!-- The data will be cleared after trade execution completes (in trade_completed label) -->
      <!-- Cache will be checked by MD system when trade request is sent -->
      <!-- MD system will trigger cache search work unit if cache entries exist -->
      <!-- Cache search work unit will properly filter entries by distance/profit/etc before signaling back -->
      
      <!-- Work-unit processing removed by AI pipeline migration -->
      
      <!-- SAVEGAME GUARD: Re-initialize instance vars that may be missing after save/load resume -->
      <do_if value="not this.$blacklistgroup?">
        <set_value name="this.$blacklistgroup" exact="blacklistgroup.civilian"/>
        <do_if value="(@this.assignedcontrolled.primarypurpose == purpose.fight) or (@this.assignedcontrolled.primarypurpose == purpose.auxiliary)">
          <set_value name="this.$blacklistgroup" exact="blacklistgroup.military"/>
        </do_if>
      </do_if>
      <do_if value="not this.$minPlayerMoney?">
        <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      </do_if>
      <!-- SAVEGAME GUARD: Restore training session flag from persisted MD state
           or an active DockAndTrain order (instance flag is lost on load). -->
      <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$sgHasDockAndTrain" exact="false"/>
        <do_if value="this.ship.orders.count gt 0">
          <do_all exact="this.ship.orders.count" counter="$sgOi">
            <do_if value="this.ship.orders.{$sgOi}.id == 'DockAndTrain'">
              <set_value name="$sgHasDockAndTrain" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <set_value name="$sgMdTrainingActive" exact="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'"/>
        <do_if value="$sgHasDockAndTrain or $sgMdTrainingActive">
          <set_value name="this.$training_in_progress" exact="true"/>
        </do_if>
      </do_if>

      <!-- Clear ESCAPE state once we are no longer in a blacklisted sector (whitelist overrides blacklist) -->
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Escaping? and global.$GT_Ships.{this.ship}.$Escaping">
        <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        <set_value name="$validationWhitelist" exact="[]"/>
        <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
          <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
        </do_if>
        <set_value name="$currentSector" exact="this.ship.sector"/>
        <set_value name="$curActivityBL" exact="false"/>
        <set_value name="$curTravelBL" exact="false"/>
        <set_value name="$curWhitelisted" exact="false"/>
        <do_if value="$validationWhitelist.count gt 0">
          <do_all exact="$validationWhitelist.count" counter="$swIdx">
            <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
              <set_value name="$curWhitelisted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $curWhitelisted">
          <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
          <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
        </do_if>
        <do_if value="not ($curActivityBL or $curTravelBL)">
          <remove_value name="global.$GT_Ships.{this.ship}.$Escaping"/>
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship=this.ship,
              $pilot=this.ship.pilot,
              $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
              $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType='trader'
            ]"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Debug: Confirm we reached main loop -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': === MAIN LOOP STARTED === (Pilot: ' + (if this.ship.pilot then this.ship.pilot.name else 'NONE') + ')'" chance="100"/>
      </do_if>
      
      <!-- Read MinPlayerMoney once per loop iteration â€” used by money gates, authoritative guard, and logbook.
           Persisted on instance so it survives <wait> yields within this iteration. -->
      <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      
      <!-- Check if GT order was removed (main loop detection) -->
      <!-- This catches cases where GT order is manually removed but script continues running -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="not this.$trackedDefaultOrder?">
        <!-- First time - initialize tracked order -->
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder != 'GalaxyTraderMK3' and this.$trackedDefaultOrder != 'GalaxyTraderMK4Supply2' and ($currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2')">
        <debug_text text="'[GT-AI] GT order reassigned for ' + this.ship.idcode + ' (detected in main loop, old: ' + this.$trackedDefaultOrder + ', new: ' + $currentDefaultOrder + ')'" chance="100"/>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="true"/>
          <param name="source" value="'AI_LOOP_REASSIGN'"/>
        </run_script>
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="(this.$trackedDefaultOrder == 'GalaxyTraderMK3' or this.$trackedDefaultOrder == 'GalaxyTraderMK4Supply2') and ($currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply2')">
        <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in main loop, old: ' + this.$trackedDefaultOrder + ', new: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ')'" chance="100"/>
        <run_script name="'lib.gt.attention.emit_gt_state_changed'">
          <param name="ship" value="this.ship"/>
          <param name="isGTActive" value="false"/>
          <param name="source" value="'AI_LOOP_CANCEL'"/>
        </run_script>
        
        <run_script name="'lib.gt.attention.restore_original_name'">
          <param name="ship" value="this.ship"/>
          <param name="reason" value="'GT order cancelled - restoring original name'"/>
          <param name="skipIfStillGT" value="true"/>
          <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply2']"/>
        </run_script>
        
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      <do_if value="this.$trackedDefaultOrder != $currentDefaultOrder">
        <set_value name="this.$trackedDefaultOrder" exact="$currentDefaultOrder"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- MANDATORY TRAINING CHECK (BLOCKS ALL TRADING) -->
      <!-- ======================================= -->
      
      <!-- Check if training was completed by interrupt handler -->
      <do_if value="this.$training_complete?">
        <remove_value name="this.$training_complete"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training completed - continuing with trading'" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Clear stale training flags when not in training -->
      <!-- These flags can persist when AI context is reused after rapid abort/restart -->
      <do_if value="this.$training_transition? or this.$training_order_created?">
        <do_if value="not this.ship.pilot or not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
          <!-- Pilot is not XP blocked, so training flags are stale - clear them -->
          <remove_value name="this.$training_transition"/>
          <remove_value name="this.$training_order_created"/>
          <remove_value name="this.$training_in_progress"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleared stale training flags (pilot not XP blocked)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (Event-Driven)  -->
      <!-- ======================================= -->
      <!-- NOTE: Pilot change detection moved to restart points (trade_completed, init) -->
      <!-- Polling removed - detection happens at natural restart points where GT order reruns -->
      <!-- This ensures detection happens when order naturally restarts, not constantly polling -->
      
      <!-- ======================================= -->
      <!-- Commander change detection (Main Loop) -->
      <!-- ======================================= -->
      <!-- Track the current commander and detect if it changes (assignment, removal, or change) -->
      <!-- This is more reliable than event_object_commander_set which may not fire during script restart -->
      <set_value name="$currentCommander" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$currentCommander" exact="this.ship.commander"/>
      </do_if>
      
      <!-- Check if commander changed (null to exists, exists to null, or different commander) -->
      <do_if value="not this.$trackedCommander?">
        <!-- First time check - initialize tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_if>
      <do_elseif value="this.$trackedCommander != $currentCommander">
        <!-- Commander changed: nullâ†’exists, existsâ†’null, or different commander -->
        <set_value name="$oldCommander" exact="if this.$trackedCommander? then this.$trackedCommander else null"/>
        <set_value name="$newCommander" exact="$currentCommander"/>
        
        <!-- Check if old commander had GT order (for name restoration) -->
        <set_value name="$oldCommanderHasGT" exact="false"/>
        <do_if value="@$oldCommander.exists">
          <do_if value="$oldCommander.defaultorder? and ((@$oldCommander.defaultorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$oldCommander.defaultorder.id == 'Assist' and $oldCommander.defaultorder.$baseorder? and (@$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$oldCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$oldCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if new commander has GT order -->
        <set_value name="$newCommanderHasGT" exact="false"/>
        <do_if value="@$newCommander.exists">
          <do_if value="$newCommander.defaultorder? and ((@$newCommander.defaultorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$newCommander.defaultorder.id == 'Assist' and $newCommander.defaultorder.$baseorder? and (@$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$newCommander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$newCommanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Commander_Changed',
          $Commander = $newCommander,
          $CommanderHasGT = $newCommanderHasGT
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Commander change detected for ' + this.ship.idcode + ' (old: ' + (if @$oldCommander.exists then @$oldCommander.idcode else 'NONE') + ', new: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $newCommanderHasGT + ')'" chance="100"/>
        </do_if>
        
        <do_if value="$oldCommanderHasGT and not $newCommanderHasGT and this.ship.pilot?">
          <run_script name="'lib.gt.attention.restore_original_name'">
            <param name="ship" value="this.ship"/>
            <param name="reason" value="'Commander changed - no longer subordinate to GT commander'"/>
            <param name="skipIfStillGT" value="true"/>
            <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply2']"/>
          </run_script>
        </do_if>
        
        <!-- Update tracked commander -->
        <set_value name="this.$trackedCommander" exact="$currentCommander"/>
      </do_elseif>
      
      <!-- ======================================= -->
      <!-- Subordinate count detection (Main Loop) -->
      <!-- ======================================= -->
      <!-- Track when this ship becomes a commander (gets subordinates) or stops being one (loses all subordinates) -->
      <!-- This is important for ships that transition from subordinate â†’ commander -->
      <set_value name="$currentSubordinateCount" exact="0"/>
      <do_if value="this.ship.subordinates?">
        <set_value name="$currentSubordinateCount" exact="this.ship.subordinates.count"/>
      </do_if>
      
      <!-- Check if subordinate count changed -->
      <do_if value="not this.$trackedSubordinateCount?">
        <!-- First time check - initialize tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_if>
      <do_elseif value="this.$trackedSubordinateCount != $currentSubordinateCount">
        <!-- Subordinate count changed -->
        <set_value name="$oldSubordinateCount" exact="this.$trackedSubordinateCount"/>
        <set_value name="$newSubordinateCount" exact="$currentSubordinateCount"/>
        
        <!-- Determine if ship became a commander or stopped being one -->
        <set_value name="$wasCommander" exact="($oldSubordinateCount gt 0)"/>
        <set_value name="$isCommander" exact="($newSubordinateCount gt 0)"/>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Subordinate_Count_Changed',
          $OldSubordinateCount = $oldSubordinateCount,
          $NewSubordinateCount = $newSubordinateCount,
          $WasCommander = $wasCommander,
          $IsCommander = $isCommander
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 6: Subordinate count changed for ' + this.ship.idcode + ' (old: ' + $oldSubordinateCount + ', new: ' + $newSubordinateCount + ', was commander: ' + $wasCommander + ', is commander: ' + $isCommander + ')'" chance="100"/>
        </do_if>
        
        <!-- Update tracked count -->
        <set_value name="this.$trackedSubordinateCount" exact="$currentSubordinateCount"/>
      </do_elseif>
      
      <!-- ======================================= -->
      <!-- SUBORDINATE COMMANDER CHECK            -->
      <!-- ======================================= -->
      <!-- Check if ship was a subordinate but lost its commander completely -->
      <!-- Track if ship was a subordinate when order started -->
      <do_if value="not this.$was_subordinate?">
        <!-- First time check - store if ship is currently a subordinate -->
        <set_value name="this.$was_subordinate" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship"/>
      </do_if>
      
      <!-- Check if subordinate lost its commander or commander lost GT order -->
      <!-- Unified GT order status check (inline for AI scripts) -->
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <set_value name="$hasGTCommander" exact="false"/>
      <set_value name="$commanderExists" exact="false"/>
      <set_value name="$isSubordinate" exact="false"/>
      
      <!-- Check direct GT order -->
      <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
      <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2'">
        <set_value name="$hasDirectGTOrder" exact="true"/>
      </do_if>
      
      <!-- Check commander status -->
      <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
        <set_value name="$commanderExists" exact="true"/>
        <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
          <set_value name="$hasGTCommander" exact="true"/>
          <do_if value="$currentDefaultOrder == 'Assist'">
            <set_value name="$isSubordinate" exact="true"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Check if ship was subordinate and lost commander completely -->
      <do_if value="this.$was_subordinate and not $hasDirectGTOrder">
        <do_if value="not $commanderExists">
          <!-- Subordinate lost its commander completely - restore name and self-abort -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SUBORDINATE ORPHANED: Commander assignment completely removed - restoring ship name and self-aborting'" chance="100"/>
          </do_if>
          
          <!-- Send cleanup signal unconditionally (with safe original-name fallback). -->
          <set_value name="$originalName" exact="null"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          <do_elseif value="this.ship.macro?">
            <set_value name="$originalName" exact="@this.ship.macro.name"/>
          </do_elseif>
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'Commander lost GT order',
            $OriginalName = $originalName
          ]"/>
          
          <!-- Set flag only after signal was emitted -->
          <set_value name="this.$subordinate_cleanup_sent" exact="true"/>
          
          <!-- Self-cancel GT order since subordinate is no longer assigned -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Self-canceling GT order - commander assignment removed'" chance="100"/>
          </do_if>
          <cancel_order order="this.ship.defaultorder"/>
          <return/>
        </do_if>
      </do_if>
      
      <!-- If subordinate and commander no longer has GT order, restore ship name and self-abort -->
      <do_if value="$commanderExists and not $hasGTCommander">
        <!-- Commander no longer has GT order - subordinate will follow commander's new order via Assist -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SUBORDINATE ORPHANED: Commander ' + this.ship.commander.idcode + ' no longer has GT order - restoring ship name and self-aborting'" chance="100"/>
        </do_if>
        
        <!-- Send cleanup signal unconditionally (with safe original-name fallback). -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="this.ship.macro?">
          <set_value name="$originalName" exact="@this.ship.macro.name"/>
        </do_elseif>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Commander lost GT order',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Set flag only after signal was emitted -->
        <set_value name="this.$subordinate_cleanup_sent" exact="true"/>
        
        <!-- Self-cancel GT order since X4 will make us follow commander's new order anyway -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Self-canceling GT order - will follow commander via Assist'" chance="100"/>
        </do_if>
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Update subordinate tracking flag -->
      <do_if value="$isSubordinate">
        <set_value name="this.$was_subordinate" exact="true"/>
      </do_if>
      <do_else>
        <!-- Not a subordinate anymore - clear flag -->
        <set_value name="this.$was_subordinate" exact="false"/>
      </do_else>
      
      <!-- MANDATORY TRAINING GATE: shared decision logic -->
      <set_value name="$pilotXPBlocked" exact="false"/>
      <set_value name="$pilotMustTrainNow" exact="false"/>
      <set_value name="$pilotNameForDebug" exact="'No Pilot'"/>
      <set_value name="$pilotLevel" exact="1"/>
      <set_value name="$blockedLevel" exact="1"/>
      <set_value name="$trainingGateReason" exact="'none'"/>
      <set_value name="$hardForceTraining" exact="true"/>
      <set_value name="$manualTrainingRequested" exact="false"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
        <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
      </do_if>
      
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$pilotNameForDebug" exact="this.ship.pilot.name"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$Level?">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
        </do_if>

        <set_value name="$pilotXPBlocked" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else (global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?)"/>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
          <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
        </do_if>
        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested">
          <set_value name="$manualTrainingRequested" exact="true"/>
        </do_if>
        <set_value name="$pilotMustTrainNow" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else ($pilotXPBlocked or ($hardForceTraining and $blockedLevel gt 1))"/>

        <do_if value="global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?">
          <set_value name="$trainingGateReason" exact="'paused_training_needed'"/>
        </do_if>
        <do_elseif value="$pilotXPBlocked">
          <set_value name="$trainingGateReason" exact="'xp_blocked'"/>
        </do_elseif>
        <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
          <set_value name="$trainingGateReason" exact="'hard_force_blocked_level'"/>
        </do_elseif>
        <do_elseif value="$blockedLevel gt 1">
          <set_value name="$trainingGateReason" exact="'soft_force_blocked_level'"/>
        </do_elseif>
      </do_if>
      
      <!-- Show the decision logic -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': DECISION LOGIC: XPBlocked=' + $pilotXPBlocked + ', MustTrainNow=' + $pilotMustTrainNow + ', HardForce=' + $hardForceTraining + ', ManagementLevel=' + $pilotLevel + ', BlockedLevel=' + $blockedLevel + ', Reason=' + $trainingGateReason + ', Pilot=' + $pilotNameForDebug" chance="100"/>
      </do_if>
      
      <do_if value="$pilotMustTrainNow">
        <!-- Check if this is a legitimate training requirement (blocked level > 1) -->
        <do_if value="$blockedLevel gt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': TRAINING MANDATORY: Pilot ' + $pilotNameForDebug + ' needs Level ' + $blockedLevel + ' training - no trading allowed until training completes'" chance="100"/>
          </do_if>
          <resume label="handle_mandatory_training"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pilot marked for training but BlockedLevel is invalid - clearing block and proceeding with trading'" chance="100"/>
          <!-- Clear the incorrect XP block for invalid Level 1 edge cases -->
          <signal_objects object="player.galaxy" param="'GT_Clear_XP_Block'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'Training gate invalid: BlockedLevel lte 1'
          ]"/>
        </do_else>
      </do_if>
      <do_else>
        <!-- Soft-force behavior: keep trading, but still retry training each loop when auto-training is enabled -->
        <set_value name="$academyEnrollmentPending" exact="false"/>
        <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
          <set_value name="$academyEnrollmentPending" exact="true"/>
        </do_if>
        <do_if value="not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) and ($gt_autotraining or $manualTrainingRequested or $academyEnrollmentPending) and this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and $blockedLevel gt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Soft-force/manual mode active - continuing trading but retrying training this loop (blocked level ' + $blockedLevel + ', manual=' + $manualTrainingRequested + ')'" chance="100"/>
          </do_if>
          <resume label="handle_mandatory_training"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training gate allows trading - proceeding to maintenance check'" chance="100"/>
          </do_if>
          <!-- Check maintenance needs before trading starts -->
          <resume label="check_maintenance"/>
        </do_else>
      </do_else>
      
      <!-- ======================================= -->
      <!-- INITIAL MAINTENANCE CHECK              -->
      <!-- ======================================= -->
      
      <label name="check_maintenance"/>
      
      <!-- ============================================================================= -->
      <!-- PRE-TRADE MAINTENANCE CHECK (UNIFIED SYSTEM)                                  -->
      <!-- ============================================================================= -->
      <!-- Signal unified maintenance system and wait for completion.                    -->
      <!-- MD system handles ALL logic: checking, finding stations, creating orders,     -->
      <!-- and monitoring. AI script just triggers and waits - clean separation!         -->
      <!-- ============================================================================= -->
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Requesting maintenance check'" chance="100"/>
      </do_if>
      
      <!-- Signal unified maintenance system to analyze and prepare data -->
      <signal_objects object="player.galaxy" param="'GT_DoMaintenance'" param2="this.ship"/>
      
      <!-- Wait for MD system to prepare data -->
      <wait exact="0.5s"/>
      
      <!-- DIAGNOSTIC: Log what MD prepared after the wait -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <set_value name="$diagHasRepair" exact="global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?"/>
        <set_value name="$diagHasResupply" exact="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?"/>
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Maintenance check result: RepairOrder=' + $diagHasRepair + ', ResupplyOrder=' + $diagHasResupply + ', HullPct=' + this.ship.hullpercentage + '%'" chance="100"/>
      </do_if>
      
      <!-- Create Repair order if data prepared -->
      <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?">
        <set_value name="$repairData" exact="global.$GT_RepairOrders.{this.ship}"/>
        <set_value name="$repairStation" exact="$repairData.$Station"/>
        
        <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=service_ai -->
        <set_value name="$canDockRepair" exact="false"/>
        <do_if value="@$repairStation.exists">
          <run_script name="'lib.gt.dockcheck'" result="$repairDockResult">
            <param name="ship" value="this.ship"/>
            <param name="station" value="$repairStation"/>
            <param name="purpose" value="'service_ai'"/>
          </run_script>
          <set_value name="$canDockRepair" exact="$repairDockResult.$CanDock"/>
          <do_if value="not $canDockRepair">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Repair docking check FAILED: ' + @$repairStation.knownname + 
                '\n  Sector: ' + @$repairStation.sector.knownname + 
                '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                '\n  â†’ Clearing repair order and continuing trading...'" 
                chance="100"/>
            </do_if>
            <remove_value name="global.$GT_RepairOrders.{this.ship}"/>
          </do_if>
        </do_if>
        
        <!-- Only create repair order if docking check passed -->
        <do_if value="$canDockRepair">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Creating Repair order at ' + $repairStation.knownname" chance="100"/>
        
        <!-- Set flag to indicate maintenance transition for on_abort handler -->
        <set_value name="this.$maintenance_transition" exact="true"/>
        
        <create_order object="this.ship" id="'Repair'" immediate="false" priority="true">
            <param name="destination" value="$repairStation"/>
          <param name="hullpercent" value="100"/>
          <param name="repairall" value="true"/>
          <param name="acceptedcost" value="$repairData.$AcceptedCost"/>
          <param name="urgent" value="false"/>
          <param name="internalorder" value="true"/>
        </create_order>
        </do_if>
      </do_if>
      
      <!-- Create Resupply order if data prepared -->
      <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
        <set_value name="$resupplyData" exact="global.$GT_ResupplyOrders.{this.ship}"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': CREATING RESUPPLY BUILD ORDER'" chance="100"/>
          <debug_text text="'[GT-AI]    Target Station: ' + $resupplyData.$Station.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station Owner: ' + @$resupplyData.$Station.owner.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station Sector: ' + @$resupplyData.$Station.sector.knownname" chance="100"/>
          <debug_text text="'[GT-AI]    Station exists: ' + $resupplyData.$Station.exists" chance="100"/>
          <debug_text text="'[GT-AI]    Station operational: ' + @$resupplyData.$Station.isoperational" chance="100"/>
          <debug_text text="'[GT-AI]    Distance from ship: ' + this.ship.gatedistance.{$resupplyData.$Station} + ' jumps'" chance="100"/>
        </do_if>
        
        <!-- Use vanilla's pattern: add_build_to_modify_ship with shopping list -->
        <!-- This is what actually creates the order with specific items to buy -->
        <set_value name="$buildSuccessful" exact="false"/>
        
        <!-- add_build_to_modify_ship SETS inventory, doesn't ADD to it -->
        <!-- Tables now include CURRENT equipment + NEW equipment (preserves existing) -->
        <!-- Check if tables have keys (they should always have keys now since we preserve existing equipment) -->
        <set_value name="$ammoTableKeys" exact="@$resupplyData.$AmmoTable.keys"/>
        <set_value name="$ammoTableCount" exact="@$ammoTableKeys.count"/>
        <set_value name="$unitTableKeys" exact="@$resupplyData.$UnitTable.keys"/>
        <set_value name="$unitTableCount" exact="@$unitTableKeys.count"/>
        
        <!-- Always call add_build_to_modify_ship if we have a resupply order (tables include existing + new equipment) -->
        <do_if value="$ammoTableCount? or $unitTableCount?">
          <set_value name="$resupplyStation" exact="$resupplyData.$Station"/>
          
          <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=service_ai -->
          <set_value name="$canDockResupply" exact="false"/>
          <do_if value="@$resupplyStation.exists">
            <run_script name="'lib.gt.dockcheck'" result="$resupplyDockResult">
              <param name="ship" value="this.ship"/>
              <param name="station" value="$resupplyStation"/>
              <param name="purpose" value="'service_ai'"/>
            </run_script>
            <set_value name="$canDockResupply" exact="$resupplyDockResult.$CanDock"/>
            <do_if value="not $canDockResupply">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resupply docking check FAILED: ' + @$resupplyStation.knownname + 
                  '\n  Sector: ' + @$resupplyStation.sector.knownname + 
                  '\n  Reason: No dock available for ship size ' + this.ship.docksize + ' (station may not have L/XL docks)' +
                  '\n  â†’ Clearing resupply order and continuing trading...'" 
                  chance="100"/>
              </do_if>
              <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            </do_if>
          </do_if>
          
          <!-- Only create resupply order if docking check passed -->
          <do_if value="$canDockResupply">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Shopping list - Ammo types: ' + $ammoTableCount + ', Unit types: ' + $unitTableCount" chance="100"/>
          </do_if>
          
          <!-- Set flag to indicate maintenance transition for on_abort handler -->
          <set_value name="this.$maintenance_transition" exact="true"/>
          
          <!-- Use vanilla's add_build_to_modify_ship action -->
          <!-- Tables now include CURRENT equipment (preserves it) + NEW equipment (adds to it) -->
          <!-- Use immediate="false" so GT order waits for build order to complete -->
          <add_build_to_modify_ship 
              object="$resupplyStation" 
            buildobject="this.ship" 
            ammo="$resupplyData.$AmmoTable" 
            units="$resupplyData.$UnitTable" 
            immediate="false"
            internal="true"
            result="$buildSuccessful"/>
          
          <do_if value="$buildSuccessful">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Build order created successfully - waiting for completion'" chance="100"/>
              <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
            </do_if>
            <!-- Build order will complete and trigger our order.build.equip patch to signal completion -->
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FAILED to create build order!'" chance="100"/>
              <debug_text text="'[GT-AI]    This usually means the station cannot build the requested items'" chance="100"/>
              <debug_text text="'[GT-AI] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Build order creation failed - station cannot fulfill order'" chance="100"/>
            </do_if>
            
            <!-- Clean up resupply data -->
            <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
            
            <!-- Apply cooldown to prevent immediate retry -->
            <do_if value="not global.$GT_MaintenanceFailedResupply?">
              <set_value name="global.$GT_MaintenanceFailedResupply" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_MaintenanceFailedResupply.{this.ship}" exact="player.age + 300s"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸ•’ Applied 5-minute cooldown due to failed build order'" chance="100"/>
            
            <!-- Remove maintenance order flag -->
            <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
              <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
            </do_if>
            
            <!-- Signal MD that we're done (failed) -->
            <signal_objects object="this.ship" param="'GT_Maintenance_Complete'"/>
          </do_else>
          </do_if>
          <!-- End: Only create resupply order if docking check passed -->
          <!-- End: Only create resupply order if docking check passed -->
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Empty shopping list - nothing to buy'" chance="100"/>
          </do_if>
          
          <!-- Clean up and skip -->
          <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
          <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{this.ship}?">
            <remove_value name="global.$GT_MaintenanceOrders.{this.ship}"/>
          </do_if>
          
          <signal_objects object="this.ship" param="'GT_Maintenance_Complete'"/>
        </do_else>
      </do_if>
      
      <!-- Wait for maintenance to complete -->
      <do_if value="(global.$GT_RepairOrders? and global.$GT_RepairOrders.{this.ship}?) or (global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â³ Waiting for maintenance orders to complete (max 900s)...'" chance="100"/>
        </do_if>
        
        <wait max="900s">
          <interrupt>
            <conditions>
              <event_object_signalled object="this.ship" param="'GT_Maintenance_Complete'"/>
            </conditions>
            <actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Maintenance complete signal received, proceeding to trade search'" chance="100"/>
              </do_if>
              
              <!-- Clear maintenance transition flag -->
              <remove_value name="this.$maintenance_transition"/>
            </actions>
          </interrupt>
        </wait>
        
        <!-- Timeout fallback -->
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â±ï¸ Maintenance timeout after 900s, proceeding anyway'" chance="100"/>
        
        <!-- Clear maintenance transition flag on timeout as well -->
        <remove_value name="this.$maintenance_transition"/>
      </do_if>
      <do_else>
        <!-- No maintenance needed -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No maintenance needed, proceeding to trade search'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- CRITICAL: Check for signal that arrived during maintenance wait -->
      <!-- This must happen AFTER maintenance completes but BEFORE proceeding to start_trading -->
      <!-- Signals can arrive during the maintenance wait block (line 2118), so we check here -->
      <do_if value="this.$tradeFoundViaInterrupt? and this.$tradeFoundViaInterrupt">
        <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received during maintenance wait - processing from param2 data'" chance="100"/>
        </do_if>
        
        <!-- Reset retry counter on successful trade -->
        <set_value name="this.$searchFailed" exact="0"/>
        
        <!-- Clear per-ship no-trade attempt history on success -->
        <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
          <remove_value name="global.$GT_NoTradeHistory.{this.ship}"/>
        </do_if>
        
        <!-- CARGO DISPOSAL: Reset cargo disposal failure counter on successful trade -->
        <do_if value="this.$cargoDisposalFailed?">
          <set_value name="this.$cargoDisposalFailed" exact="0"/>
        </do_if>
        
        <resume label="trade_found"/>
      </do_if>
      
      <!-- Proceed to trading -->
      <resume label="start_trading"/>
      
      <!-- ======================================= -->
      <!-- HIGH-PERFORMANCE TRADING LOOP          -->
      <!-- ======================================= -->
      
      <!-- ========================================= -->
      <!-- MANDATORY TRAINING HANDLER              -->
      <!-- ========================================= -->
      
      <label name="handle_mandatory_training"/>
      
      <!-- Check if ship has an active DockAndTrain order -->
      <set_value name="$hasActiveTrainingOrder" exact="false"/>
      <do_if value="this.ship.orders.count gt 0">
        <do_all exact="this.ship.orders.count" counter="$i">
          <do_if value="this.ship.orders.{$i}.id == 'DockAndTrain'">
            <set_value name="$hasActiveTrainingOrder" exact="true"/>
            <break/>
          </do_if>
        </do_all>
      </do_if>
      
      <!-- ENHANCED LOGIC: Auto-restart training if it was previously interrupted -->
      <!-- Conditions for starting/restarting training:
           1. Auto-training is enabled
           2. Ship has a pilot with GT pilot data
           3. Either: training not in progress OR no active training order (interrupted training)
      -->
      <set_value name="$manualTrainingRequested" exact="false"/>
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{this.ship.pilot}.$ManualTrainingRequested">
        <set_value name="$manualTrainingRequested" exact="true"/>
      </do_if>
      <set_value name="$academyEnrollmentPending" exact="false"/>
      <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$AcademyEnrollment?">
        <set_value name="$academyEnrollmentPending" exact="true"/>
      </do_if>
      <do_if value="($gt_autotraining or $manualTrainingRequested or $academyEnrollmentPending) and this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}">
        <set_value name="$shouldStartTraining" exact="false"/>
        <set_value name="$mdTrainingInProgress" exact="global.$GT_Pilots.{this.ship.pilot}.$TrainingState? and global.$GT_Pilots.{this.ship.pilot}.$TrainingState == 'training_in_progress'"/>
        
        <!-- Case 0: Active DockAndTrain or MD timer (save/load) - wait, do not re-dispatch -->
        <do_if value="$hasActiveTrainingOrder or $mdTrainingInProgress">
          <do_if value="not this.$training_in_progress?">
            <set_value name="this.$training_in_progress" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Restored in-flight training session after save/load (DockAndTrain=' + $hasActiveTrainingOrder + ', MD timer=' + $mdTrainingInProgress + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Case 1: Training not currently in progress -->
        <do_elseif value="not this.$training_in_progress?">
          <set_value name="$shouldStartTraining" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training not in progress - can start training'" chance="100"/>
          </do_if>
        </do_elseif>
        <!-- Case 2: Training was marked as in progress but no active training order (interrupted) -->
        <do_elseif value="this.$training_in_progress? and not $hasActiveTrainingOrder">
          <set_value name="$shouldStartTraining" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': TRAINING INTERRUPTED: Previous training was aborted - restarting automatically'" chance="100"/>
          </do_if>
          <!-- Clear the stale flag -->
          <remove_value name="this.$training_in_progress"/>
        </do_elseif>
        
        <do_if value="$shouldStartTraining">
          <!-- Inline training gate evaluation (AI scripts cannot call MD libraries) -->
          <set_value name="$hardForceTraining" exact="true"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
            <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
          </do_if>
          <set_value name="$blockedLevel" exact="1"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
          </do_if>
          <set_value name="$mustTrainNow" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else (global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? or global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded? or ($hardForceTraining and $blockedLevel gt 1))"/>
          <set_value name="$shouldRetryTraining" exact="if (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly) then false else ($mustTrainNow or ((not $hardForceTraining) and $blockedLevel gt 1) or ($manualTrainingRequested and $blockedLevel gt 1))"/>
          <set_value name="$trainingGateReason" exact="'none'"/>
          <do_if value="global.$GT_Pilots.{this.ship.pilot}.$PausedWithTrainingNeeded?">
            <set_value name="$trainingGateReason" exact="'paused_training_needed'"/>
          </do_if>
          <do_elseif value="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked?">
            <set_value name="$trainingGateReason" exact="'xp_blocked'"/>
          </do_elseif>
          <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
            <set_value name="$trainingGateReason" exact="'hard_force_blocked_level'"/>
          </do_elseif>
          <do_elseif value="$blockedLevel gt 1">
            <set_value name="$trainingGateReason" exact="'soft_force_blocked_level'"/>
          </do_elseif>
          
          <do_if value="$shouldRetryTraining">
            <!-- Get blocked level with safety check -->
            <do_if value="not (global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel gt 0)">
              <!-- Calculate current skill level as fallback -->
              <do_if value="global.$GT_Pilots.{this.ship.pilot}.$XP?">
                <set_value name="$currentXP" exact="global.$GT_Pilots.{this.ship.pilot}.$XP"/>
                <do_all exact="15" counter="$skillLevel">
                  <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                    <set_value name="$blockedLevel" exact="$skillLevel"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ðŸŽ“ Initiating mandatory training for pilot ' + $pilotNameForDebug + ' (Level ' + $blockedLevel + ', reason=' + $trainingGateReason + ', hardforce=' + $hardForceTraining + ')'" chance="100"/>
            </do_if>
            
            <!-- Respect retry backoff only in hard-force mode -->
            <set_value name="$retryReady" exact="true"/>
            <do_if value="$hardForceTraining and global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt? and player.age lt global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt">
              <set_value name="$retryReady" exact="false"/>
            </do_if>
            
            <do_if value="$retryReady">
              <!-- Signal MD system to handle training -->
              <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $RequiredLevel = $blockedLevel
              ]"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training signal sent to MD system for pilot ' + $pilotNameForDebug" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$retryRemaining" exact="(global.$GT_Pilots.{this.ship.pilot}.$NextTrainingRetryAt - player.age) / 1s"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training retry backoff active (' + $retryRemaining + 's remaining)'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <!-- Training is not mandatory under current gate policy -->
            <set_value name="$blockedLevelForDebug" exact="'none'"/>
            <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel?">
              <set_value name="$blockedLevelForDebug" exact="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training gate allows trading in mandatory handler (reason=' + $trainingGateReason + ', blockedLevel=' + $blockedLevelForDebug + ', hardforce=' + $hardForceTraining + ')'" chance="100"/>
            </do_if>
            <!-- Break out of training handler and continue to trading -->
            <resume label="check_maintenance"/>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': â³ Training already in progress (active order: ' + $hasActiveTrainingOrder + ') - waiting'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Auto-training disabled or no pilot data - waiting'" chance="100"/>
        </do_if>
      </do_else>
      
      <!-- Wait and check again - training is mandatory -->
      <wait max="10s">
        <interrupt>
          <conditions>
            <event_object_signalled object="this.ship" param="'GT_Training_Station_Found'"/>
          </conditions>
          <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Training station found during wait - proceeding immediately'" chance="100"/>
            </do_if>
          </actions>
        </interrupt>
      </wait>
      <resume label="main_loop"/>
      
      <!-- ========================================= -->
      <!-- EVENT-DRIVEN TRADE SEARCH WITH RETRY     -->
      <!-- ========================================= -->
      
      <label name="start_trading"/>

      <!-- MK4-2 Â§3.1.1b: all delivery-class sliders explicitly 0 â†’ idle, no search -->
      <run_script name="'lib.gt.mk42.policy.resolve'" result="$mk42StartPolicy">
        <param name="priorityBuildstorage" value="if this.$effectivePriorityBuildstorage? then this.$effectivePriorityBuildstorage else (if $priorityBuildstorage? then $priorityBuildstorage else 10)"/>
        <param name="priorityStations" value="if this.$effectivePriorityStations? then this.$effectivePriorityStations else (if $priorityStations? then $priorityStations else 8)"/>
        <param name="priorityAux" value="if this.$effectivePriorityAux? then this.$effectivePriorityAux else (if $priorityAux? then $priorityAux else 0)"/>
        <param name="priorityCarrier" value="if this.$effectivePriorityCarrier? then this.$effectivePriorityCarrier else (if $priorityCarrier? then $priorityCarrier else 0)"/>
        <param name="prioritywares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else []"/>
        <param name="priorityscoremultiplier" value="if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else 1"/>
        <param name="buyFromPlayer" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
        <param name="buyFromFaction" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
        <param name="seedNullSliders" value="true"/>
      </run_script>
      <do_if value="$mk42StartPolicy? and $mk42StartPolicy.$NoDeliveryTargets? and @$mk42StartPolicy.$NoDeliveryTargets">
        <do_if value="not this.$mk42NoDeliveryLogged?">
          <set_value name="this.$mk42NoDeliveryLogged" exact="true"/>
          <set_value name="$mk42LogbookEnabled" exact="if this.$effectiveLogbookEntries? then this.$effectiveLogbookEntries else (if $gt_logbookentries? then $gt_logbookentries else $logbookentries)"/>
          <do_if value="$mk42LogbookEnabled">
            <set_value name="$logbookMessage" exact="{77000,11008}.[this.ship.knownname]"/>
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'tips',
              $Title = 'MK4-2 Supply: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4-2 all delivery-class sliders are 0 â€” idling (no search)'" chance="100"/>
          </do_if>
        </do_if>
        <resume label="main_loop"/>
      </do_if>



      <!-- HARD RULE: no silent fallbacks for pilot skill timing issues. -->
      <!-- If GT pilot level isn't available yet, do NOT request a trade search with bogus caps. -->
      <!-- Wait is only allowed at top-level; use a bounded loop here (not inside any do_if). -->
      <set_value name="$pilotSkillMissing" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and (not this.ship.pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{this.ship.pilot}? or not global.$GT_Pilots.{this.ship.pilot}.$Level?)"/>
      <set_value name="this.$pilotSkillWaitTries" exact="0"/>
      <do_while value="$pilotSkillMissing and this.$pilotSkillWaitTries lt 10">
        <wait exact="1s"/>
        <set_value name="$pilotSkillMissing" exact="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and (not this.ship.pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{this.ship.pilot}? or not global.$GT_Pilots.{this.ship.pilot}.$Level?)"/>
        <set_value name="this.$pilotSkillWaitTries" exact="this.$pilotSkillWaitTries + 1"/>
      </do_while>
      <do_if value="$pilotSkillMissing">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ERROR: GT pilot level unavailable after ' + this.$pilotSkillWaitTries + 's - NOT sending trade search request. Will retry on next loop (this is a timing bug we want to SEE).'" chance="100"/>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- effectiveMaxBuy/effectiveMaxSell initialized in <init> block -->

      <!-- ========================================= -->
      <!-- SUBORDINATE SETTINGS REFRESH (ON REQUEST) -->
      <!-- ========================================= -->
      <!-- Problem: Commander default-order param edits do not reliably trigger event_object_order_ready.
           Solution: When a subordinate is ABOUT to request a new trade, refresh inherited commander settings if they changed.
           effectiveAutoWares/effectiveWareBasket/effectiveDistancePenalty initialized in <init> block. -->

      <set_value name="$_isSubordinateNow" exact="this.ship.commander and this.ship.commander.exists and this.ship.commander != this.ship"/>
      <do_if value="$_isSubordinateNow">
        <set_value name="$_commanderOrderNow" exact="this.ship.commander.defaultorder"/>
        <do_if value="$_commanderOrderNow?">
          <!-- Build a signature for commander settings that affect trade searching / routing -->
          <set_value name="$_cmdAutoWares" exact="if $_commanderOrderNow.$autowares? then $_commanderOrderNow.$autowares else (if $_commanderOrderNow.$lockWares? then not $_commanderOrderNow.$lockWares else $effectiveAutoWares)"/>
          <set_value name="$_cmdDistancePenalty" exact="if $_commanderOrderNow.$distancepenalty? then $_commanderOrderNow.$distancepenalty else $effectiveDistancePenalty"/>
          <set_value name="$_cmdWareBasket" exact="if $_commanderOrderNow.$warebasket? and $_commanderOrderNow.$warebasket.count gt 0 then $_commanderOrderNow.$warebasket else (if $_commanderOrderNow.$specialWareBasket? then $_commanderOrderNow.$specialWareBasket else $effectiveWareBasket)"/>

          <set_value name="$_cmdFleetCoord" exact="if $_commanderOrderNow.$fleetcoordination? then $_commanderOrderNow.$fleetcoordination else $effectiveFleetCoordination"/>
          <set_value name="$_cmdAllowIllegal" exact="if $_commanderOrderNow.$allowillegal? then $_commanderOrderNow.$allowillegal else $effectiveAllowIllegal"/>
          <set_value name="$_cmdIllegalRouteFilter" exact="if $_commanderOrderNow.$enforceRouteIllegalLegality? then $_commanderOrderNow.$enforceRouteIllegalLegality else $effectiveEnforceRouteIllegalLegality"/>
          <set_value name="$_cmdFactionPriority" exact="0"/>
          <do_if value="$_commanderOrderNow.$priorityBuildstorage?"><set_value name="this.$effectivePriorityBuildstorage" exact="$_commanderOrderNow.$priorityBuildstorage"/></do_if>
          <do_if value="$_commanderOrderNow.$priorityStations?"><set_value name="this.$effectivePriorityStations" exact="$_commanderOrderNow.$priorityStations"/></do_if>
          <do_if value="$_commanderOrderNow.$priorityAux?"><set_value name="this.$effectivePriorityAux" exact="$_commanderOrderNow.$priorityAux"/></do_if>
          <do_if value="$_commanderOrderNow.$priorityCarrier?"><set_value name="this.$effectivePriorityCarrier" exact="$_commanderOrderNow.$priorityCarrier"/></do_if>
          <do_if value="$_commanderOrderNow.$priorityscoremultiplier?"><set_value name="this.$effectivePriorityScoreMultiplier" exact="[$_commanderOrderNow.$priorityscoremultiplier, 1].max"/></do_if>
          <do_if value="$_commanderOrderNow.$prioritywares?"><set_value name="this.$effectivePriorityWares" exact="$_commanderOrderNow.$prioritywares"/></do_if>
          <set_value name="this.$mk42Priorities" exact="table[$Buildstorage = this.$effectivePriorityBuildstorage, $Stations = this.$effectivePriorityStations, $Aux = this.$effectivePriorityAux, $Carrier = this.$effectivePriorityCarrier]"/>
          <set_value name="$_cmdIgnoreBuildStorage" exact="this.$effectivePriorityBuildstorage == 0"/>
          <set_value name="$_cmdIgnoreCarrierAux" exact="this.$effectivePriorityAux == 0 and this.$effectivePriorityCarrier == 0"/>
          <set_value name="$_cmdIgnoreTradeRules" exact="if $_commanderOrderNow.$ignoretraderules? then $_commanderOrderNow.$ignoretraderules else $effectiveIgnoreTradeRules"/>
          <set_value name="$_cmdIgnoreMK1Supply" exact="if $_commanderOrderNow.$ignoremk1supply? then $_commanderOrderNow.$ignoremk1supply else $effectiveIgnoreMK1Supply"/>
          <set_value name="$_cmdLogbookEntries" exact="if $_commanderOrderNow.$logbookentries? then $_commanderOrderNow.$logbookentries else $effectiveLogbookEntries"/>
          <set_value name="$_cmdUseMinCargoThresholdFilter" exact="if $_commanderOrderNow.$useMinCargoThreshold? then $_commanderOrderNow.$useMinCargoThreshold else $effectiveUseMinCargoThresholdFilter"/>
          <set_value name="$_cmdCargoTarget" exact="if $_commanderOrderNow.$minCargoUsed? then $_commanderOrderNow.$minCargoUsed else $effectiveCargoTarget"/>
          <set_value name="$_cmdDebugLevel" exact="if $_commanderOrderNow.$debuglevel? then $_commanderOrderNow.$debuglevel else $effectiveDebugLevel"/>
          <set_value name="$_cmdTradeEval" exact="if $_commanderOrderNow.$tradeeval? then $_commanderOrderNow.$tradeeval else $effectiveTradeEval"/>
          <set_value name="$_cmdHome" exact="if $_commanderOrderNow.$home? then $_commanderOrderNow.$home else this.$effectiveHome"/>
          <set_value name="$_cmdMaxBuy" exact="if $_commanderOrderNow.$jumpDistanceBuy? then $_commanderOrderNow.$jumpDistanceBuy else $effectiveMaxBuy"/>
          <set_value name="$_cmdMaxSell" exact="if $_commanderOrderNow.$jumpDistanceCoverage? then $_commanderOrderNow.$jumpDistanceCoverage else $effectiveMaxSell"/>
          <set_value name="$_cmdSectorWhitelist" exact="if $_commanderOrderNow.$sectorwhitelist? then $_commanderOrderNow.$sectorwhitelist else $effectiveSectorWhitelist"/>
          <set_value name="$_cmdM4Res" exact="if $_commanderOrderNow.$allowResources? then $_commanderOrderNow.$allowResources else (if this.$mk4AllowResources? then this.$mk4AllowResources else true)"/>
          <set_value name="$_cmdM4Int" exact="if $_commanderOrderNow.$allowIntermediates? then $_commanderOrderNow.$allowIntermediates else (if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true)"/>
          <set_value name="$_cmdM4Tw" exact="if $_commanderOrderNow.$allowTradewares? then $_commanderOrderNow.$allowTradewares else (if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true)"/>
          <set_value name="$_cmdM4Aps" exact="if $_commanderOrderNow.$buyFromPlayer? then $_commanderOrderNow.$buyFromPlayer else (if $_commanderOrderNow.$allowPlayerSuppliers? then $_commanderOrderNow.$allowPlayerSuppliers else (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true))"/>
          <set_value name="$_cmdM4Aas" exact="if $_commanderOrderNow.$buyFromFaction? then $_commanderOrderNow.$buyFromFaction else (if $_commanderOrderNow.$allowAiSuppliers? then $_commanderOrderNow.$allowAiSuppliers else (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true))"/>
          <set_value name="$_cmdM4Ded" exact="if $_commanderOrderNow.$serveHomeOnly? then $_commanderOrderNow.$serveHomeOnly else (if $_commanderOrderNow.$dedicatedServe? then $_commanderOrderNow.$dedicatedServe else (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false))"/>
          
          <!-- IMPORTANT:
               In X4 AI script expressions, `?` checks existence, NOT null, and boolean `and` is not safe to rely on for short-circuiting.
               Normalize a null sectorwhitelist to an empty list so we can safely use `.count`. -->
          <do_if value="not $_cmdSectorWhitelist? or $_cmdSectorWhitelist == null">
            <set_value name="$_cmdSectorWhitelist" exact="[]"/>
          </do_if>

          <set_value name="$_cmdHomeName" exact="if $_cmdHome? then @$_cmdHome.knownname else 'NULL'"/>
          <!-- Include subordinate pilot level in signature so level-up forces inherited cap refresh. -->
          <set_value name="$_pilotLevelSig" exact="0"/>
          <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$Level?">
            <set_value name="$_pilotLevelSig" exact="global.$GT_Pilots.{this.ship.pilot}.$Level"/>
          </do_if>

          <set_value name="$_commanderSettingsSig" exact="'AW=' + $_cmdAutoWares
            + '|DP=' + $_cmdDistancePenalty
            + '|FC=' + $_cmdFleetCoord
            + '|IL=' + $_cmdAllowIllegal
            + '|IRF=' + $_cmdIllegalRouteFilter
            + '|FP=' + $_cmdFactionPriority
            + '|ICA=' + $_cmdIgnoreCarrierAux
            + '|IBS=' + $_cmdIgnoreBuildStorage
            + '|ITR=' + $_cmdIgnoreTradeRules
            + '|IM1=' + $_cmdIgnoreMK1Supply
            + '|HB=' + $_cmdHomeName
            + '|MB=' + $_cmdMaxBuy
            + '|MS=' + $_cmdMaxSell
            + '|LB=' + $_cmdLogbookEntries
            + '|UC=' + $_cmdUseMinCargoThresholdFilter
            + '|CT=' + $_cmdCargoTarget
            + '|DL=' + $_cmdDebugLevel
            + '|TE=' + $_cmdTradeEval
            + '|PL=' + $_pilotLevelSig
            + '|M4R=' + $_cmdM4Res
            + '|M4I=' + $_cmdM4Int
            + '|M4T=' + $_cmdM4Tw
            + '|M4APS=' + $_cmdM4Aps
            + '|M4AAS=' + $_cmdM4Aas
            + '|M4DED=' + $_cmdM4Ded
            + '|SW='"/>

          <!-- Include sector whitelist content -->
          <do_if value="$_cmdSectorWhitelist.count gt 0">
            <do_all exact="$_cmdSectorWhitelist.count" counter="$_sw_i">
              <set_value name="$_sw" exact="$_cmdSectorWhitelist.{$_sw_i}"/>
              <set_value name="$_swName" exact="if $_sw? then @$_sw.knownname else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_sw_i gt 1 then ',' else '') + $_swName"/>
            </do_all>
          </do_if>

          <!-- Include ware basket content (only when autowares is disabled) -->
          <do_if value="not $_cmdAutoWares">
            <do_all exact="$_cmdWareBasket.count" counter="$_i">
              <set_value name="$_w" exact="$_cmdWareBasket.{$_i}"/>
              <set_value name="$_wName" exact="if $_w? then @$_w.name else 'NULL'"/>
              <set_value name="$_commanderSettingsSig" exact="$_commanderSettingsSig + (if $_i gt 1 then ',' else '') + $_wName"/>
            </do_all>
          </do_if>

          <do_if value="not this.$trackedCommanderSettingsSig? or this.$trackedCommanderSettingsSig != $_commanderSettingsSig">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Commander settings changed (refreshing inherited settings). NewSig=' + $_commanderSettingsSig" chance="100"/>
            </do_if>

            <!-- Apply commander settings to this subordinate immediately -->
            <set_value name="$effectiveAutoWares" exact="$_cmdAutoWares"/>
            <set_value name="$effectiveWareBasket" exact="$_cmdWareBasket"/>
            <set_value name="$effectiveDistancePenalty" exact="$_cmdDistancePenalty"/>
            <set_value name="$effectiveFleetCoordination" exact="$_cmdFleetCoord"/>
            <set_value name="$effectiveAllowIllegal" exact="$_cmdAllowIllegal"/>
            <set_value name="$effectiveEnforceRouteIllegalLegality" exact="$_cmdIllegalRouteFilter"/>
            <set_value name="$effectiveFactionPriority" exact="0"/>
            <set_value name="$effectiveIgnoreCarrierAux" exact="$_cmdIgnoreCarrierAux"/>
            <set_value name="$effectiveIgnoreBuildStorage" exact="$_cmdIgnoreBuildStorage"/>
            <set_value name="$effectiveIgnoreTradeRules" exact="$_cmdIgnoreTradeRules"/>
            <set_value name="$effectiveIgnoreMK1Supply" exact="$_cmdIgnoreMK1Supply"/>
            <set_value name="$effectiveLogbookEntries" exact="$_cmdLogbookEntries"/>
            <set_value name="$effectiveUseMinCargoThresholdFilter" exact="$_cmdUseMinCargoThresholdFilter"/>
            <set_value name="$effectiveCargoTarget" exact="$_cmdCargoTarget"/>
            <set_value name="$effectiveDebugLevel" exact="$_cmdDebugLevel"/>
            <set_value name="$effectiveTradeEval" exact="$_cmdTradeEval"/>
            <set_value name="$effectiveSectorWhitelist" exact="$_cmdSectorWhitelist"/>
            <set_value name="$mk4AllowResources" exact="$_cmdM4Res"/>
            <set_value name="$mk4AllowIntermediates" exact="$_cmdM4Int"/>
            <set_value name="$mk4AllowTradewares" exact="$_cmdM4Tw"/>
            <set_value name="$mk4AllowPlayerSuppliers" exact="$_cmdM4Aps"/>
            <set_value name="$mk4AllowAiSuppliers" exact="$_cmdM4Aas"/>
            <set_value name="$mk4DedicatedServe" exact="$_cmdM4Ded"/>
            <set_value name="this.$mk4AllowResources" exact="$mk4AllowResources"/>
            <set_value name="this.$mk4AllowIntermediates" exact="$mk4AllowIntermediates"/>
            <set_value name="this.$mk4AllowTradewares" exact="$mk4AllowTradewares"/>
            <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk4AllowPlayerSuppliers"/>
            <set_value name="this.$mk4AllowAiSuppliers" exact="$mk4AllowAiSuppliers"/>
            <set_value name="this.$mk4DedicatedServe" exact="$mk4DedicatedServe"/>
            <run_script name="'lib.gt.mk42.policy.resolve'" result="$mk42PolicyCmd">
              <param name="priorityBuildstorage" value="if this.$effectivePriorityBuildstorage? then this.$effectivePriorityBuildstorage else 10"/>
              <param name="priorityStations" value="if this.$effectivePriorityStations? then this.$effectivePriorityStations else 8"/>
              <param name="priorityAux" value="if this.$effectivePriorityAux? then this.$effectivePriorityAux else 0"/>
              <param name="priorityCarrier" value="if this.$effectivePriorityCarrier? then this.$effectivePriorityCarrier else 0"/>
              <param name="prioritywares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else []"/>
              <param name="priorityscoremultiplier" value="if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else 1"/>
              <param name="buyFromPlayer" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
              <param name="buyFromFaction" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
            </run_script>
            <set_value name="$mk42PrioSigNow" exact="if $mk42PolicyCmd? and $mk42PolicyCmd.$PrioSig? then @$mk42PolicyCmd.$PrioSig else ''"/>
            <set_value name="$mk42PrioChangedInCmd" exact="not this.$lastMk42PrioSig? or this.$lastMk42PrioSig != $mk42PrioSigNow"/>
            <do_if value="$mk42PrioChangedInCmd">
              <set_value name="$mk4PolicyHome" exact="$_cmdHome"/>
              <set_value name="$mk4PolicyHomeSector" exact="if $mk4PolicyHome? and $mk4PolicyHome.isclass.sector then $mk4PolicyHome else (if $mk4PolicyHome? and $mk4PolicyHome.sector? then @$mk4PolicyHome.sector else null)"/>
              <set_value name="$mk4PolicyCacheEmpty" exact="true"/>
              <do_if value="$mk4PolicyHomeSector? and $mk4PolicyHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}? and global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}.count gt 0">
                <set_value name="$mk4PolicyCacheEmpty" exact="false"/>
              </do_if>
              <do_if value="$mk4PolicyCacheEmpty">
                <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="true"/>
              </do_if>
              <do_else>
                <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
                <!-- Policy widened but cache still valid â€” clear this ship from FailedShips only (do not nuke shared pool). -->
                <do_all exact="global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}.count" counter="$polFsiCmd">
                  <set_value name="$polEntryCmd" exact="global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}.{$polFsiCmd}"/>
                  <do_if value="$polEntryCmd? and $polEntryCmd.$FailedShips? and $polEntryCmd.$FailedShips.count gt 0">
                    <set_value name="$polNewFailedCmd" exact="[]"/>
                    <do_all exact="$polEntryCmd.$FailedShips.count" counter="$polFsi2Cmd">
                      <do_if value="$polEntryCmd.$FailedShips.{$polFsi2Cmd} != this.ship">
                        <append_to_list name="$polNewFailedCmd" exact="$polEntryCmd.$FailedShips.{$polFsi2Cmd}"/>
                      </do_if>
                    </do_all>
                    <set_value name="$polEntryCmd.$FailedShips" exact="$polNewFailedCmd"/>
                  </do_if>
                </do_all>
              </do_else>
            </do_if>
            <set_value name="this.$lastMk42PrioSig" exact="$mk42PrioSigNow"/>

            <!-- Home base affects distance filtering/scoring; ensure both local and persisted value update -->
            <do_if value="$_cmdHome?">
              <set_value name="$effectiveHome" exact="$_cmdHome"/>
              <set_value name="this.$effectiveHome" exact="$effectiveHome"/>
            </do_if>

            <!-- Jump distance caps: disable in vanilla mode, cap in GT mode. -->
            <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
            <run_script name="'lib.gt.pathfinding'" result="$_pilotSkill">
              <param name="mode" value="'effective_pilot_level'"/>
              <param name="ship" value="this.ship"/>
              <param name="includeCommander" value="false"/>
            </run_script>
            <set_value name="$_pilotMaxJumps" exact="null"/>
            <do_if value="not $useVanillaXPOnly">
              <run_script name="'lib.gt.pathfinding'" result="$_pilotMaxJumps">
                <param name="mode" value="'pilot_max_jumps'"/>
                <param name="pilotSkill" value="$_pilotSkill"/>
              </run_script>
            </do_if>

            <do_if value="$_commanderOrderNow.$jumpDistanceBuy?">
              <set_value name="$effectiveMaxBuy" exact="if $useVanillaXPOnly or $_pilotMaxJumps == null then $_cmdMaxBuy else [$_cmdMaxBuy, $_pilotMaxJumps].min"/>
              <set_value name="this.$effectiveMaxBuy" exact="$effectiveMaxBuy"/>
            </do_if>
            <do_if value="$_commanderOrderNow.$jumpDistanceCoverage?">
              <set_value name="$effectiveMaxSell" exact="if $useVanillaXPOnly or $_pilotMaxJumps == null then $_cmdMaxSell else [$_cmdMaxSell, $_pilotMaxJumps].min"/>
              <set_value name="this.$effectiveMaxSell" exact="$effectiveMaxSell"/>
            </do_if>

            <!-- Persist updated effective settings (survive save/load resume) -->
            <set_value name="this.$effectiveIgnoreTradeRules" exact="$effectiveIgnoreTradeRules"/>
            <set_value name="this.$effectiveIgnoreMK1Supply" exact="$effectiveIgnoreMK1Supply"/>
            <set_value name="this.$effectiveIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
            <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
            <set_value name="this.$effectiveDistancePenalty" exact="$effectiveDistancePenalty"/>
            <set_value name="this.$effectiveFleetCoordination" exact="$effectiveFleetCoordination"/>
            <set_value name="this.$effectiveFactionPriority" exact="$effectiveFactionPriority"/>
            <set_value name="this.$effectiveAllowIllegal" exact="$effectiveAllowIllegal"/>
            <set_value name="this.$effectiveEnforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
            <set_value name="this.$effectiveLogbookEntries" exact="$effectiveLogbookEntries"/>
            <set_value name="this.$effectiveUseMinCargoThresholdFilter" exact="$effectiveUseMinCargoThresholdFilter"/>
            <set_value name="this.$effectiveCargoTarget" exact="$effectiveCargoTarget"/>

            <!-- Refresh derived variables used by the MD requests -->
            <set_value name="$gt_allowillegal" exact="$effectiveAllowIllegal"/>
            <set_value name="$gt_enforceRouteIllegalLegality" exact="$effectiveEnforceRouteIllegalLegality"/>
            <set_value name="$gt_distancepenalty" exact="$effectiveDistancePenalty / 50.0"/>
            <set_value name="$gt_logbookentries" exact="$effectiveLogbookEntries"/>
            <set_value name="$gt_useMinCargoThreshold" exact="$effectiveUseMinCargoThresholdFilter"/>
            <set_value name="$gt_cargotarget" exact="[10,[$effectiveCargoTarget,100].min].max"/>
            <set_value name="$warebasket" exact="if $effectiveAutoWares then [] else $effectiveWareBasket"/>

            <!-- CRITICAL: Drop stale trades awaiting validation produced under the previous commander settings.
                 Otherwise the AI can execute old trades (wrong ware filter, wrong distances, etc.) via stale data. -->
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
            </do_if>
            <!-- Clear interrupt flag when clearing trades awaiting validation (commander settings changed) -->
            <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
            <!-- Reset retry counter: we want a clean fresh request under the new settings -->
            <do_if value="this.$searchFailed?">
              <set_value name="this.$searchFailed" exact="0"/>
            </do_if>
          </do_if>

          <!-- Track last applied signature (always) -->
          <set_value name="this.$trackedCommanderSettingsSig" exact="$_commanderSettingsSig"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- ORDER-HOLDER SELF-REFRESH (commander / standalone):
             Subordinates resync from the commander above, but the order-holder reads its params only in <init>.
             Re-read the live trade-rule toggle from its own default order each request so a runtime
             ignoretraderules edit takes effect without restarting the order. -->
        <do_if value="this.ship.defaultorder? and @this.ship.defaultorder.id == 'GalaxyTraderMK4Supply2' and this.ship.defaultorder.$ignoretraderules?">
          <set_value name="$_ownIgnoreTradeRules" exact="this.ship.defaultorder.$ignoretraderules"/>
          <do_if value="not this.$effectiveIgnoreTradeRules? or this.$effectiveIgnoreTradeRules != $_ownIgnoreTradeRules">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Own order ignoretraderules changed -> ' + $_ownIgnoreTradeRules + ' (refreshing)'" chance="100"/>
            </do_if>
            <set_value name="$effectiveIgnoreTradeRules" exact="$_ownIgnoreTradeRules"/>
            <set_value name="this.$effectiveIgnoreTradeRules" exact="$_ownIgnoreTradeRules"/>
            <!-- Drop stale trades validated under the previous trade-rule setting -->
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
              <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
            </do_if>
            <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
            <do_if value="this.$searchFailed?">
              <set_value name="this.$searchFailed" exact="0"/>
            </do_if>
          </do_if>
        </do_if>
      </do_else>
      
      <!-- Initialize retry counter if not exists -->
      <do_if value="not this.$searchFailed?">
        <set_value name="this.$searchFailed" exact="0"/>
      </do_if>

      <!-- Sync MK4 supply policy from live order object (UI edits update defaultorder, not this.$ copies). -->
      <set_value name="$mk42PolicyOrder" exact="null"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
        <set_value name="$mk42PolicyOrder" exact="this.ship.commander.defaultorder"/>
      </do_if>
      <do_else>
        <set_value name="$mk42PolicyOrder" exact="if this.ship.defaultorder? then this.ship.defaultorder else null"/>
      </do_else>
      <do_if value="$mk42PolicyOrder? and @$mk42PolicyOrder.id == 'GalaxyTraderMK4Supply2'">
        <do_if value="$mk42PolicyOrder.$allowResources?">
          <set_value name="this.$mk4AllowResources" exact="$mk42PolicyOrder.$allowResources"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$allowIntermediates?">
          <set_value name="this.$mk4AllowIntermediates" exact="$mk42PolicyOrder.$allowIntermediates"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$allowTradewares?">
          <set_value name="this.$mk4AllowTradewares" exact="$mk42PolicyOrder.$allowTradewares"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$buyFromPlayer?">
          <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk42PolicyOrder.$buyFromPlayer"/>
        </do_if>
        <do_elseif value="$mk42PolicyOrder.$allowPlayerSuppliers?">
          <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk42PolicyOrder.$allowPlayerSuppliers"/>
        </do_elseif>
        <do_if value="$mk42PolicyOrder.$buyFromFaction?">
          <set_value name="this.$mk4AllowAiSuppliers" exact="$mk42PolicyOrder.$buyFromFaction"/>
        </do_if>
        <do_elseif value="$mk42PolicyOrder.$allowAiSuppliers?">
          <set_value name="this.$mk4AllowAiSuppliers" exact="$mk42PolicyOrder.$allowAiSuppliers"/>
        </do_elseif>
        <do_if value="$mk42PolicyOrder.$serveHomeOnly?">
          <set_value name="this.$mk4DedicatedServe" exact="$mk42PolicyOrder.$serveHomeOnly"/>
        </do_if>
        <do_elseif value="$mk42PolicyOrder.$dedicatedServe?">
          <set_value name="this.$mk4DedicatedServe" exact="$mk42PolicyOrder.$dedicatedServe"/>
        </do_elseif>
        <!-- UI slider edits update defaultorder immediately; this.$ copies from <init> go stale without this. -->
        <do_if value="$mk42PolicyOrder.$priorityBuildstorage?">
          <set_value name="this.$effectivePriorityBuildstorage" exact="$mk42PolicyOrder.$priorityBuildstorage"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$priorityStations?">
          <set_value name="this.$effectivePriorityStations" exact="$mk42PolicyOrder.$priorityStations"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$priorityAux?">
          <set_value name="this.$effectivePriorityAux" exact="$mk42PolicyOrder.$priorityAux"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$priorityCarrier?">
          <set_value name="this.$effectivePriorityCarrier" exact="$mk42PolicyOrder.$priorityCarrier"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$priorityscoremultiplier?">
          <set_value name="this.$effectivePriorityScoreMultiplier" exact="[$mk42PolicyOrder.$priorityscoremultiplier, 1].max"/>
        </do_if>
        <do_if value="$mk42PolicyOrder.$prioritywares?">
          <set_value name="this.$effectivePriorityWares" exact="$mk42PolicyOrder.$prioritywares"/>
        </do_if>
        <run_script name="'lib.gt.mk42.policy.resolve'" result="$mk42PolicyCmdNow">
          <param name="priorityBuildstorage" value="if $mk42PolicyOrder.$priorityBuildstorage? then $mk42PolicyOrder.$priorityBuildstorage else (if this.$effectivePriorityBuildstorage? then this.$effectivePriorityBuildstorage else 10)"/>
          <param name="priorityStations" value="if $mk42PolicyOrder.$priorityStations? then $mk42PolicyOrder.$priorityStations else (if this.$effectivePriorityStations? then this.$effectivePriorityStations else 8)"/>
          <param name="priorityAux" value="if $mk42PolicyOrder.$priorityAux? then $mk42PolicyOrder.$priorityAux else (if this.$effectivePriorityAux? then this.$effectivePriorityAux else 0)"/>
          <param name="priorityCarrier" value="if $mk42PolicyOrder.$priorityCarrier? then $mk42PolicyOrder.$priorityCarrier else (if this.$effectivePriorityCarrier? then this.$effectivePriorityCarrier else 0)"/>
          <param name="prioritywares" value="if $mk42PolicyOrder.$prioritywares? then $mk42PolicyOrder.$prioritywares else (if this.$effectivePriorityWares? then this.$effectivePriorityWares else [])"/>
          <param name="priorityscoremultiplier" value="if $mk42PolicyOrder.$priorityscoremultiplier? then $mk42PolicyOrder.$priorityscoremultiplier else (if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else 1)"/>
          <param name="buyFromPlayer" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
          <param name="buyFromFaction" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
        </run_script>
        <do_if value="$mk42PolicyCmdNow?">
          <set_value name="this.$mk42Priorities" exact="if $mk42PolicyCmdNow.$Priorities? then @$mk42PolicyCmdNow.$Priorities else this.$mk42Priorities"/>
          <set_value name="this.$effectivePriorityBuildstorage" exact="if $mk42PolicyCmdNow.$Buildstorage? then @$mk42PolicyCmdNow.$Buildstorage else this.$effectivePriorityBuildstorage"/>
          <set_value name="this.$effectivePriorityStations" exact="if $mk42PolicyCmdNow.$Stations? then @$mk42PolicyCmdNow.$Stations else this.$effectivePriorityStations"/>
          <set_value name="this.$effectivePriorityAux" exact="if $mk42PolicyCmdNow.$Aux? then @$mk42PolicyCmdNow.$Aux else this.$effectivePriorityAux"/>
          <set_value name="this.$effectivePriorityCarrier" exact="if $mk42PolicyCmdNow.$Carrier? then @$mk42PolicyCmdNow.$Carrier else this.$effectivePriorityCarrier"/>
          <set_value name="this.$effectiveIgnoreBuildStorage" exact="this.$effectivePriorityBuildstorage == 0"/>
          <set_value name="this.$mk4BuildStorageOnlyMode" exact="this.$effectivePriorityBuildstorage gt 0 and this.$effectivePriorityStations == 0 and this.$effectivePriorityAux == 0 and this.$effectivePriorityCarrier == 0"/>
        </do_if>
        <set_value name="$mk42PrioSigNow" exact="if $mk42PolicyCmdNow? and $mk42PolicyCmdNow.$PrioSig? then @$mk42PolicyCmdNow.$PrioSig else ''"/>
        <set_value name="$mk42PrioSigPrev" exact="if this.$lastMk42PrioSig? then this.$lastMk42PrioSig else ''"/>
        <set_value name="$mk42PrioChangedNow" exact="$mk42PrioSigPrev != '' and $mk42PrioSigPrev != $mk42PrioSigNow"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $mk42PrioSigNow != ''">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4-2 live-order priorities ' + $mk42PrioSigNow + (if $mk42PrioChangedNow then ' (CHANGED from ' + $mk42PrioSigPrev + ')' else '')" chance="100"/>
        </do_if>
        <do_if value="$mk42PrioChangedNow">
          <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="true"/>
          <set_value name="$mk4PolicyHome" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder? and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector)"/>
          <set_value name="$mk4PolicyHomeSector" exact="if $mk4PolicyHome? and $mk4PolicyHome.isclass.sector then $mk4PolicyHome else (if $mk4PolicyHome? and $mk4PolicyHome.sector? then @$mk4PolicyHome.sector else null)"/>
          <!-- Policy widened but cache still valid â€” clear this ship from FailedShips on all home entries. -->
          <do_if value="$mk4PolicyHomeSector? and $mk4PolicyHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}?">
            <do_all exact="global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}.count" counter="$polFsi">
              <set_value name="$polEntry" exact="global.$GT_TradeCacheMK42.{$mk4PolicyHomeSector}.{$polFsi}"/>
              <do_if value="$polEntry? and $polEntry.$FailedShips? and $polEntry.$FailedShips.count gt 0">
                <set_value name="$polNewFailed" exact="[]"/>
                <do_all exact="$polEntry.$FailedShips.count" counter="$polFsi2">
                  <do_if value="$polEntry.$FailedShips.{$polFsi2} != this.ship">
                    <append_to_list name="$polNewFailed" exact="$polEntry.$FailedShips.{$polFsi2}"/>
                  </do_if>
                </do_all>
                <set_value name="$polEntry.$FailedShips" exact="$polNewFailed"/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <set_value name="this.$lastMk42PrioSig" exact="$mk42PrioSigNow"/>
      </do_if>

      <!-- Handle pending scheduler grant before issuing a fresh request.
           This closes a timing gap where GT_Search_Go can arrive before wait_for_response is active. -->
      <do_if value="this.$pendingSearchParams? and this.$pendingSearchParams != null and typeof this.$pendingSearchParams == datatype.table">
        <set_value name="this.$searchGoViaInterrupt" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$pendingPhaseNow" exact="if this.$pendingSearchParams.$Phase? then @this.$pendingSearchParams.$Phase else 'unknown'"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Processing pending GT_Search_Go before new request (phase=' + $pendingPhaseNow + ')'" chance="100"/>
        </do_if>
        <resume label="run_search_pipeline"/>
      </do_if>
      
      <!-- Signal MD system for trade opportunities -->
      <!-- Check if ship already has trade orders BEFORE requesting new trade -->
      <set_value name="$hasTradeOrders" exact="false"/>
      <do_if value="this.ship.tradeorders? and this.ship.tradeorders.count gt 0">
        <set_value name="$hasTradeOrders" exact="true"/>
      </do_if>
      
      <do_if value="$hasTradeOrders">
        <!-- Ship already has pending trade orders - wait instead of requesting more -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Ship already has ' + this.ship.tradeorders.count + ' trade orders - waiting for completion'" chance="100"/>
        </do_if>
        
        <!-- Wait for trade completion -->
        <wait max="10s">
          <interrupt>
            <conditions>
              <check_any>
                <event_object_signalled object="this.ship" param="'GT_Trade_Completed'"/>
                <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
              </check_any>
            </conditions>
            <actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade order completed early - checking status immediately'" chance="100"/>
              </do_if>
            </actions>
          </interrupt>
        </wait>
        <resume label="main_loop"/>
      </do_if>
      <do_else>
        <!-- Ship ready for new trade - ensure ship is registered before requesting trade search -->
        <!-- This is critical when pilot is transferred to a new ship -->
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
          <!-- Ship not registered yet - wait a moment for registration to complete -->
          <!-- Registration happens via GT_Register_Ship signal handled by gt_core_system.HandleShipRegistration -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship not yet registered - waiting for registration to complete...'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Wait for registration using a top-level loop (no waits inside conditionals).
             Bounded to prevent the prior unbounded spin: 20*500ms = 10s, then re-fire GT_Register_Ship
             once (queue stall / lost signal recovery) and give the queue another 10*500ms = 5s.
             If still missing, bounce back to main_loop so the next iteration can retry instead of
             spinning the AI block forever. Counter is on `this.` because locals are lost across <wait>. -->
        <set_value name="this.$regSpinCount" exact="0"/>
        <do_while value="(not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?) and this.$regSpinCount lt 20">
          <wait exact="500ms"/>
          <set_value name="this.$regSpinCount" operation="add"/>
        </do_while>
        <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARN Registration missing after 10s spin - re-emitting GT_Register_Ship'" chance="100"/>
          <signal_objects object="player.galaxy" param="'GT_Register_Ship'" param2="table[$Ship = this.ship, $Config = table[]]"/>
          <set_value name="this.$regSpinCount" exact="0"/>
          <do_while value="(not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?) and this.$regSpinCount lt 10">
            <wait exact="500ms"/>
            <set_value name="this.$regSpinCount" operation="add"/>
          </do_while>
          <do_if value="not global.$GT_Ships? or not global.$GT_Ships.{this.ship}?">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARN Registration still missing after retry - bouncing to main_loop'" chance="100"/>
            <remove_value name="this.$regSpinCount"/>
            <resume label="main_loop"/>
          </do_if>
        </do_if>
        <remove_value name="this.$regSpinCount"/>
        
        <!-- Check cargo status -->
        <!-- Only trade if cargo is EMPTY -->
        <set_value name="$hasCargo" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
        
        <do_if value="$hasCargo">
          <!-- Ship has cargo - sell it first using our trade search -->
          <!-- CARGO DISPOSAL: Only log initial message once (prevent spam) -->
          <set_value name="$isFirstCargoDisposalAttempt" exact="false"/>
          <do_if value="not this.$cargoDisposalFailed? or this.$cargoDisposalFailed == 0">
            <set_value name="$isFirstCargoDisposalAttempt" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship has cargo - finding best buyer using trade search...'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Set cargo disposal flag for ship name -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
            <set_value name="global.$GT_Ships.{this.ship}.$CargoDisposal" exact="true"/>
          </do_if>
          
          <!-- Trigger ship rename to show [CLEARANCE] state -->
          <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship=this.ship, 
              $pilot=this.ship.pilot, 
              $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
              $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
              $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
              $nameType='trader'
            ]"/>
          </do_if>
          
          <!-- Write logbook entry about cargo safety - ONLY ON FIRST ATTEMPT -->
          <do_if value="$isFirstCargoDisposalAttempt and $gt_logbookentries">
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3204}.[this.ship.knownname]"/>
            
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'tips',
              $Title = 'Cargo Safety: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
          </do_if>
          
          <!-- effectiveXxx variables initialized in <init> block -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': CARGO DISPOSAL: Sending GT_Find_Sell at age ' + player.age + ' (MaxSell=' + (if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1)) + ' jumps)'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Find_Sell'" param2="table[
            $Ship = this.ship,
            $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
            $MaxSell = if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1),
            $DistancePenalty = @this.$effectiveDistancePenalty,
            $FleetCoordination = @this.$effectiveFleetCoordination,
            $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
            $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
            $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
            $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true
          ]"/>
        </do_if>
        <do_else>
          <!-- Ship cargo is EMPTY - look for buy opportunities -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cargo empty - looking for trade opportunities...'" chance="100"/>
          </do_if>

          <!-- Clear cargo disposal flag (cargo is now empty) -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal? and this.ship.cargo.count == 0">
            <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
            
            <!-- CARGO DISPOSAL: Reset cargo disposal failure counter when cargo is cleared -->
            <do_if value="this.$cargoDisposalFailed?">
              <set_value name="this.$cargoDisposalFailed" exact="0"/>
            </do_if>
            
            <!-- Trigger ship rename to remove [CLEARANCE] state -->
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship, 
                $pilot=this.ship.pilot, 
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>
          
          <!-- ==================================================================================== -->
          <!-- MECHANIC 2: Early money gate - skip entire trade search pipeline when player is broke -->
          <!-- Threshold: MinPlayerMoney + 1000 Cr safety buffer.                                   -->
          <!-- This prevents the expensive cache search / work loop from running when there is      -->
          <!-- no meaningful budget left. Ships go directly to insufficient_funds cooldown.          -->
          <!-- Works with MECHANIC 1 (authoritative guard budget clamp at trade creation):           -->
          <!--   Mechanic 1 = clamp trade volume to fit budget  (trade creation)                    -->
          <!--   Mechanic 2 = stop searching when budget is exhausted (search start)                -->
          <!-- ==================================================================================== -->
          <set_value name="$earlyMoneyCheck" exact="player.money"/>
          <do_if value="not this.$minPlayerMoney?">
            <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
          </do_if>
          <set_value name="$moneyGateThreshold" exact="(this.$minPlayerMoney + 1000)Cr"/>
          <do_if value="$earlyMoneyCheck le $moneyGateThreshold">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': EARLY MONEY GATE: player money=' + ($earlyMoneyCheck / 100) + ' Cr at or below threshold=' + (this.$minPlayerMoney + 1000) + ' Cr (MinPlayerMoney=' + this.$minPlayerMoney + ' + 1000 buffer) - skipping trade search'" chance="100"/>
            <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
            <resume label="no_trade_retry"/>
          </do_if>
          
          <!-- GLOBAL MONEY CAP heal: reaching this line means we already passed the early money
               gate above, so player.money is greater than MinPlayerMoney + 1000 Cr (i.e. the
               fleet is solvent). The fleet-wide cap is only meaningful while the player is broke,
               and that case is already handled by the early gate. Clearing it here prevents a
               solvent fleet from staying frozen on a stale wealth snapshot (the cap could have
               been recorded at a higher balance than the player currently holds). The per-trade
               authoritative budget guard still blocks any individual unaffordable trade. -->
          <do_if value="global.$GT_MoneyCapActive? and global.$GT_MoneyCapActive">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP CLEARED (solvent): player money=' + ($earlyMoneyCheck / 100) + ' Cr above gate threshold (' + ($moneyGateThreshold / 100) + ' Cr) - resuming fleet trade searches'" chance="100"/>
            </do_if>
            <set_value name="global.$GT_MoneyCapActive" exact="false"/>
            <remove_value name="global.$GT_MoneyCapMoney"/>
          </do_if>
          
          <!-- Wait briefly for any pending GT_Trade_Found signals before sending new request.
               Configured delay + 5ms buffer. If signal arrives during wait, interrupt processes it. -->
          <set_value name="$signalDelayMs" exact="0"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay?">
            <set_value name="$tmpDelay" exact="@global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay"/>
            <do_if value="$tmpDelay ge 0 and $tmpDelay le 1000">
              <set_value name="$signalDelayMs" exact="$tmpDelay"/>
            </do_if>
          </do_if>
          <set_value name="this.$tradeFoundSignalWaitTime" exact="($signalDelayMs + 5) * 1ms"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Waiting ' + ($signalDelayMs + 5) + 'ms for GT_Trade_Found signal (delay=' + $signalDelayMs + 'ms + 5ms buffer)'" chance="100"/>
          </do_if>
          <wait max="if @this.$tradeFoundSignalWaitTime != null then @this.$tradeFoundSignalWaitTime else 5ms" comment="Wait for pending GT_Trade_Found signals">
            <interrupt>
              <conditions>
                <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
              </conditions>
              <actions>
                <!-- Capture signal payload before resuming so trade_found gets the correct source/list -->
                <set_value name="$intSignalData" exact="event.param2"/>
                <set_value name="$intSignalTradeList" exact="[]"/>
                <set_value name="$intSignalSearchMethod" exact="''"/>
                <do_if value="$intSignalData? and $intSignalData != null">
                  <set_value name="$intSignalTradeList" exact="@$intSignalData.$TradeList"/>
                  <set_value name="$intSignalSearchMethod" exact="@$intSignalData.$SearchMethod"/>
                </do_if>
                <set_value name="this.$tradeListFromSignal" exact="$intSignalTradeList"/>
                <set_value name="this.$searchMethodFromSignal" exact="if $intSignalSearchMethod != null and $intSignalSearchMethod != '' then $intSignalSearchMethod else ''"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Trade_Found signal received during pre-request wait - stored ' + (if $intSignalTradeList != null then $intSignalTradeList.count else 0) + ' trades from interrupt payload'" chance="100"/>
                </do_if>
                <!-- Signal received - jump to trade_found label to process it -->
                <resume label="trade_found"/>
              </actions>
            </interrupt>
          </wait>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-request wait completed - no signal received, sending new request'" chance="100"/>
          </do_if>
          
          <!-- effectiveXxx variables initialized in <init> block -->
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SENDING GT_Search_Request signal to MD at game time ' + player.age" chance="100"/>
          </do_if>
          <set_value name="$requestForceLiveSearch" exact="false"/>
          <set_value name="$requestLiveSearchPriority" exact="false"/>
          <do_if value="this.$mk42PolicyNeedsLiveSearch? and this.$mk42PolicyNeedsLiveSearch">
            <set_value name="$requestForceLiveSearch" exact="true"/>
            <set_value name="$requestLiveSearchPriority" exact="true"/>
          </do_if>
          <do_if value="this.$forceLiveAfterLiveReject? and this.$forceLiveAfterLiveReject">
            <set_value name="$requestForceLiveSearch" exact="true"/>
            <set_value name="$requestLiveSearchPriority" exact="true"/>
            <set_value name="this.$forceLiveAfterLiveReject" exact="false"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
            $Ship = this.ship,
            $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
            $MaxBuy = if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else (if $jumpDistanceBuy? then $jumpDistanceBuy else 1),
            $MaxSell = if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1),
            $CargoTarget = $gt_cargotarget,
            $WareBasket = $warebasket,
            $AllowIllegal = $gt_allowillegal,
            $EnforceRouteIllegalLegality = $gt_enforceRouteIllegalLegality,
            $FactionPriority = $gt_factionpriority,
            $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
            $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
            $DistancePenalty = @this.$effectiveDistancePenalty,
            $FleetCoordination = @this.$effectiveFleetCoordination,
            $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
            $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
            $SearchPool = 'mk4_supply_v2',
            $SearchDepth = if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30,
            $ForceLiveSearch = $requestForceLiveSearch,
            $LiveSearchPriority = $requestLiveSearchPriority
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT_Search_Request signal SENT, now at game time ' + player.age" chance="100"/>
          </do_if>
        </do_else>
      </do_else>
      
      <!-- Wait for MD system response with interrupt -->
      <!-- Under large fleets, queued MK4 live-slot dispatch can exceed 60s.
           Use a wider timeout to avoid premature abort/requeue churn while still recovering from deadlocks. -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Entering wait state for MD response at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- Clear previous no-trade reason (prevents stale reason affecting timeout retry logic) -->
      <set_value name="this.$lastNoTradeReason" exact="''"/>
      <label name="wait_for_response"/>
      <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
      <label name="wait_for_response_continue"/>
      <do_if value="not this.$waitForResponseStartedAt?">
        <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
      </do_if>
      <do_if value="(player.age - this.$waitForResponseStartedAt) ge 120s">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT: 120s expired without semaphore grant (GT_Search_Go) at game time ' + player.age + ' â€” cleaning up queue entry and retrying'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
        <resume label="no_trade_retry"/>
      </do_if>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Wait interrupt handler ACTIVE at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- IMPORTANT: In X4, wait without min is RANDOM (0..max). Use min=max to avoid instant timeouts.
           Guard startedAt for save-load resume mid-wait (instance var may be absent on older saves). -->
      <wait min="if this.$waitForResponseStartedAt? then (if (120s - (player.age - this.$waitForResponseStartedAt)) gt 1ms then (120s - (player.age - this.$waitForResponseStartedAt)) else 1ms) else 120s" max="if this.$waitForResponseStartedAt? then (if (120s - (player.age - this.$waitForResponseStartedAt)) gt 1ms then (120s - (player.age - this.$waitForResponseStartedAt)) else 1ms) else 120s" comment="Wait for MD system response (120s total; interrupted immediately on response)">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Found'"/>
              <event_object_signalled object="this.ship" param="'GT_No_Trade_Found'"/>
              <!-- Duplicate request while MD search lock is still held:
                   MD responds with a non-backoff "still working" or "reset" signal to prevent AI cooldown escalation under fleet load. -->
              <event_object_signalled object="this.ship" param="'GT_TradeSearch_InProgress'"/>
              <event_object_signalled object="this.ship" param="'GT_TradeSearch_Reset'"/>
              <!-- New AI pipeline semaphore grant -->
              <event_object_signalled object="this.ship" param="'GT_Search_Go'"/>
            </check_any>
          </conditions>
          <actions>
            <do_if value="event.param == 'GT_Search_Go'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_Search_Go received at age ' + player.age + ' - queueing AI search pipeline'" chance="100"/>
              </do_if>
              <!-- Persist interrupt payload across wait/resume boundaries. -->
              <set_value name="this.$pendingSearchParams" exact="event.param2"/>
              <resume label="run_search_pipeline"/>
            </do_if>
            <do_elseif value="event.param == 'GT_Trade_Found'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_Trade_Found received at game time ' + player.age" chance="100"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade found by MD system - proceeding with execution'" chance="100"/>
              </do_if>
              <!-- Reset retry counter on successful trade -->
              <set_value name="this.$searchFailed" exact="0"/>
              <do_if value="global.$GT_IdleParkingReleased? and global.$GT_IdleParkingReleased.{this.ship}?">
                <remove_value name="global.$GT_IdleParkingReleased.{this.ship}"/>
              </do_if>
              <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
                <remove_value name="global.$GT_IdleParkingHold.{this.ship}"/>
                <set_value name="global.$GT_IdleParkingReleased.{this.ship}" exact="true"/>
              </do_if>
              
              <!-- Clear per-ship no-trade attempt history on success (prevents stale attempts from polluting later reports) -->
              <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
                <remove_value name="global.$GT_NoTradeHistory.{this.ship}"/>
              </do_if>
              
              <!-- CARGO DISPOSAL: Reset cargo disposal failure counter on successful trade -->
              <do_if value="this.$cargoDisposalFailed?">
                <set_value name="this.$cargoDisposalFailed" exact="0"/>
              </do_if>
              
              <!-- Clear reroute flag (new destination found) -->
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Rerouting?">
                <remove_value name="global.$GT_Ships.{this.ship}.$Rerouting"/>
                
                <!-- Trigger ship rename to remove [REROUTE] state -->
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship, 
                    $pilot=this.ship.pilot, 
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP, 
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
              </do_if>
              
              <resume label="trade_found"/>
            </do_elseif>
            <do_elseif value="event.param == 'GT_TradeSearch_InProgress'">
              <do_if value="not this.$waitForResponseStartedAt?">
                <set_value name="this.$waitForResponseStartedAt" exact="player.age"/>
              </do_if>
              <do_if value="(player.age - this.$waitForResponseStartedAt) ge 120s">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT after InProgress keepalives (120s) - aborting search and retrying'" chance="100"/>
                </do_if>
                <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
                <resume label="main_loop"/>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_TradeSearch_InProgress received at game time ' + player.age + ' - continuing to wait (no backoff)'" chance="100"/>
                </do_if>
                <resume label="wait_for_response_continue"/>
              </do_else>
            </do_elseif>
            <do_elseif value="event.param == 'GT_TradeSearch_Reset'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_TradeSearch_Reset received at game time ' + player.age + ' - retrying request immediately (no backoff)'" chance="100"/>
              </do_if>
              <!-- Stay in scheduler wait when already queued/active â€” avoid duplicate cache requests that lose mk4live queue position. -->
              <set_value name="$resetStillScheduled" exact="false"/>
              <do_if value="global.$GT_SearchSemaphore?">
                <do_if value="global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{this.ship}?">
                  <set_value name="$resetStillScheduled" exact="true"/>
                </do_if>
                <!-- IMPORTANT: $LiveWaiterWakePending must NOT keep the ship in the wait. It is the
                     scheduler's "you were just woken â€” act now" marker (set by HandleMK42CacheUpdated /
                     HandleSearchAbort / starved-waiter promotion, which also DEQUEUE the ship and expect
                     it to re-issue a fresh request â€” "retry cache first"). The flag is cleared only inside
                     HandleSearchRequest, i.e. on the re-request. Treating it as "still scheduled" here
                     stranded woken ships in wait_for_response_continue with no pending GT_Search_Go until
                     the 120s timeout (e.g. a fleet ship never reading a freshly-written cache). Fall
                     through to main_loop so the wake deterministically produces a new search request. -->
                <do_if value="not $resetStillScheduled and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.count gt 0">
                  <set_value name="$resetWaiterHomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.list"/>
                  <do_all exact="$resetWaiterHomeKeys.count" counter="$rwhi">
                    <set_value name="$rwhHome" exact="$resetWaiterHomeKeys.{$rwhi}"/>
                    <do_if value="$rwhHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$rwhHome}?">
                      <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$rwhHome}.count" counter="$rwwi">
                        <do_if value="@global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$rwhHome}.{$rwwi} == this.ship">
                          <set_value name="$resetStillScheduled" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    <do_if value="$resetStillScheduled">
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
              <do_if value="$resetStillScheduled">
                <resume label="wait_for_response_continue"/>
              </do_if>
              <do_else>
                <!-- Cache/live waiters woken after a home-sector refresh must retry cache first.
                     ST-only MISS sets mk42PolicyNeedsLiveSearch for inline live escalation; clear it here
                     so GT_Search_Request does not re-enqueue phase=live behind the fleet refresh ship. -->
                <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
                <resume label="main_loop"/>
              </do_else>
            </do_elseif>
            <do_elseif value="event.param == 'GT_No_Trade_Found'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': INTERRUPT FIRED: GT_No_Trade_Found received at age ' + player.age + ' (reason=' + (if event.param2? then event.param2 else '') + ')'" chance="100"/>
              </do_if>
              <!-- Capture reason (MD may pass param2='busy' for cache-search slots busy, etc.) -->
              <set_value name="this.$lastNoTradeReason" exact="if event.param2? and event.param2 != null then event.param2 else ''"/>
              <!-- Isolated mode is intra-sector by design; UR is not meaningful there. -->
              <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}? and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
                <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
              </do_if>
              <!-- ESCAPE FALLBACK:
                   If we are stuck in a blacklisted sector and got "no trade found", move toward home sector
                   (skipping blacklisted sectors along the route until we hit a non-blacklisted sector OR the home sector).
                   Whitelist overrides blacklist (matches GT_IsSectorBlacklisted). -->
              <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <set_value name="$validationWhitelist" exact="[]"/>
              <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
              </do_if>
              <set_value name="$currentSector" exact="this.ship.sector"/>
              <set_value name="$needsEscape" exact="false"/>
              <do_if value="$currentSector? and $currentSector.exists">
                <set_value name="$curWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                      <set_value name="$curWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $curWhitelisted">
                  <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$needsEscape" exact="$curActivityBL or $curTravelBL"/>
                </do_if>
              </do_if>
              <do_if value="$needsEscape">
                <!-- Set escape flag for ship naming -->
                <do_if value="global.$GT_Ships?">
                  <do_if value="not global.$GT_Ships.{this.ship}?">
                    <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
                </do_if>
                <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship=this.ship,
                    $pilot=this.ship.pilot,
                    $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                    $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                    $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                    $nameType='trader'
                  ]"/>
                </do_if>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: No trade found while in blacklisted sector (' + @$currentSector.knownname + ') - moving toward home sector'" chance="100"/>
                </do_if>
                <resume label="escape_from_blacklisted"/>
              </do_if>
              
              <!-- Check if this is a cargo disposal attempt -->
              <set_value name="$isCargoDisposal" exact="false"/>
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
                <set_value name="$isCargoDisposal" exact="true"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': RECEIVED GT_No_Trade_Found signal - starting retry logic (cargo disposal: ' + $isCargoDisposal + ')'" chance="100"/>
              </do_if>
              <resume label="no_trade_retry"/>
            </do_elseif>
          </actions>
        </interrupt>
      </wait>

      <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
           TIMEOUT GUARD: If execution reaches here, the 120s wait expired WITHOUT
           any interrupt firing. The ship NEVER received GT_Search_Go from the
           semaphore. We MUST NOT fall through to run_search_pipeline â€” that would
           bypass the semaphore and allow unlimited concurrent live searches.
           Clean up the pending queue entry and retry with cooldown.
           â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WAIT TIMEOUT: 120s expired without semaphore grant (GT_Search_Go) at game time ' + player.age + ' â€” cleaning up queue entry and retrying'" chance="100"/>
      </do_if>
      <!-- Remove this ship from the scheduler queue so it doesn't block the slot -->
      <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
      <resume label="no_trade_retry"/>

      <label name="run_search_pipeline"/>
      <set_value name="$searchParams" exact="if this.$pendingSearchParams? then this.$pendingSearchParams else null"/>
      <set_value name="this.$pendingSearchParams" exact="null"/>
      <!-- Belt-and-suspenders: verify $searchParams is a real table, not null.
           X4's '?' operator can return true for set_value-created variables even when null.
           Use typeof check to ensure we have actual search parameters from GT_Search_Go. -->
      <do_if value="typeof $searchParams == datatype.table">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Running AI search pipeline (semaphore-granted) at game time ' + player.age" chance="100"/>
        </do_if>

        <set_value name="$searchHome" exact="if $searchParams.$HomeBase? then @$searchParams.$HomeBase else (if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null))"/>
        <set_value name="$searchHomeSector" exact="if $searchParams.$HomeSector? then @$searchParams.$HomeSector else (if $searchHome? and $searchHome.isclass.sector then $searchHome else (if $searchHome? and $searchHome.sector? then @$searchHome.sector else this.ship.sector))"/>
        <!-- Dual-radius: MaxSell = delivery/need coverage, MaxBuy = supplier leg; pathfinding/live need max of both. -->
        <set_value name="$searchMaxSell" exact="if $searchParams.$MaxSell? then @$searchParams.$MaxSell else (if this.$effectiveMaxSell? then this.$effectiveMaxSell else (if $jumpDistanceCoverage? then $jumpDistanceCoverage else 1))"/>
        <set_value name="$searchMaxBuy" exact="if $searchParams.$MaxBuy? then @$searchParams.$MaxBuy else (if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else 0)"/>
        <set_value name="$searchRadiusMax" exact="[$searchMaxBuy, $searchMaxSell].max"/>
        <!-- Legacy name: single radius for logs/fallback centering (use combined reach) -->
        <set_value name="$searchMaxDistance" exact="$searchRadiusMax"/>
        <set_value name="$searchWareBasket" exact="if $searchParams.$WareBasket? then @$searchParams.$WareBasket else $warebasket"/>
        <set_value name="$searchAllowIllegal" exact="if $searchParams.$AllowIllegal? then @$searchParams.$AllowIllegal else $gt_allowillegal"/>
        <set_value name="$searchEnforceRouteIllegalLegality" exact="if $searchParams.$EnforceRouteIllegalLegality? then @$searchParams.$EnforceRouteIllegalLegality else $gt_enforceRouteIllegalLegality"/>
        <set_value name="$searchIgnoreTradeRules" exact="if $searchParams.$IgnoreTradeRules? then @$searchParams.$IgnoreTradeRules else $effectiveIgnoreTradeRules"/>
        <set_value name="$searchIgnoreMK1Supply" exact="if $searchParams.$IgnoreMK1Supply? then @$searchParams.$IgnoreMK1Supply else $effectiveIgnoreMK1Supply"/>
        <set_value name="$searchIgnoreBuildStorage" exact="if $searchParams.$IgnoreBuildStorage? then @$searchParams.$IgnoreBuildStorage else $effectiveIgnoreBuildStorage"/>
        <set_value name="$searchIgnoreCarrierAux" exact="if $searchParams.$IgnoreCarrierAux? then @$searchParams.$IgnoreCarrierAux else $effectiveIgnoreCarrierAux"/>
        <set_value name="$searchFactionPriority" exact="0"/>
        <set_value name="$searchMode" exact="if $searchParams.$SearchMode? then @$searchParams.$SearchMode else 'buy_and_sell'"/>
        <set_value name="$forceLiveSearch" exact="if $searchParams.$ForceLiveSearch? then @$searchParams.$ForceLiveSearch else false"/>
        <set_value name="$searchPhase" exact="if $searchParams.$Phase? then @$searchParams.$Phase else 'live'"/>
        <set_value name="$skipCacheRead" exact="false"/>
        <set_value name="$mk4HomeCacheCount" exact="0"/>
        <do_if value="$searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$searchHomeSector}?">
          <set_value name="$mk4HomeCacheCount" exact="@global.$GT_TradeCacheMK42.{$searchHomeSector}.count"/>
        </do_if>
        <!-- Only skip cache re-read when prior cache phase missed AND pool is still empty. -->
        <do_if value="$searchParams.$CachePhaseMiss? and $searchParams.$CachePhaseMiss and $mk4HomeCacheCount == 0">
          <set_value name="$skipCacheRead" exact="true"/>
        </do_if>
        <!-- mk4live/live slot: after cache phase miss, force live refresh instead of retrying a dead pool. -->
        <do_if value="$searchPhase == 'live' or $searchPhase == 'mk42live'">
          <do_if value="($searchParams.$ForceLiveSearch? and $searchParams.$ForceLiveSearch) or $mk4HomeCacheCount == 0">
            <set_value name="$forceLiveSearch" exact="true"/>
          </do_if>
          <do_elseif value="$searchParams.$CachePhaseMiss? and $searchParams.$CachePhaseMiss">
            <set_value name="$forceLiveSearch" exact="true"/>
          </do_elseif>
          <do_else>
            <set_value name="$forceLiveSearch" exact="false"/>
          </do_else>
        </do_if>

        <!-- MK4 supply: score + price profile gate trades â€” no pilot ROI or profit floor. -->
        <set_value name="$searchMinROI" exact="0"/>
        <set_value name="$searchMinAbsoluteProfit" exact="0"/>

        <!-- Priority wares change detection:
             only clear cache when an existing signature changed (real order-setup delta).
             First-time baseline initialization must not invalidate cache. -->
        <!-- Belt-and-suspenders: re-sync MK4 policy from live order before cache/live (diag reads defaultorder; this.$ can lag UI edits). -->
        <set_value name="$mk42PolicyOrder" exact="null"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship and not this.ship.commander.isclass.station">
          <set_value name="$mk42PolicyOrder" exact="this.ship.commander.defaultorder"/>
        </do_if>
        <do_else>
          <set_value name="$mk42PolicyOrder" exact="if this.ship.defaultorder? then this.ship.defaultorder else null"/>
        </do_else>
        <do_if value="$mk42PolicyOrder? and @$mk42PolicyOrder.id == 'GalaxyTraderMK4Supply2'">
          <do_if value="$mk42PolicyOrder.$priorityBuildstorage?">
            <set_value name="this.$effectivePriorityBuildstorage" exact="$mk42PolicyOrder.$priorityBuildstorage"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$priorityStations?">
            <set_value name="this.$effectivePriorityStations" exact="$mk42PolicyOrder.$priorityStations"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$priorityAux?">
            <set_value name="this.$effectivePriorityAux" exact="$mk42PolicyOrder.$priorityAux"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$priorityCarrier?">
            <set_value name="this.$effectivePriorityCarrier" exact="$mk42PolicyOrder.$priorityCarrier"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$priorityscoremultiplier?">
            <set_value name="this.$effectivePriorityScoreMultiplier" exact="[$mk42PolicyOrder.$priorityscoremultiplier, 1].max"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$prioritywares?">
            <set_value name="this.$effectivePriorityWares" exact="$mk42PolicyOrder.$prioritywares"/>
          </do_if>

<do_if value="$mk42PolicyOrder.$allowResources?">
            <set_value name="this.$mk4AllowResources" exact="$mk42PolicyOrder.$allowResources"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$allowIntermediates?">
            <set_value name="this.$mk4AllowIntermediates" exact="$mk42PolicyOrder.$allowIntermediates"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$allowTradewares?">
            <set_value name="this.$mk4AllowTradewares" exact="$mk42PolicyOrder.$allowTradewares"/>
          </do_if>
          <do_if value="$mk42PolicyOrder.$buyFromPlayer?">
            <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk42PolicyOrder.$buyFromPlayer"/>
          </do_if>
          <do_elseif value="$mk42PolicyOrder.$allowPlayerSuppliers?">
            <set_value name="this.$mk4AllowPlayerSuppliers" exact="$mk42PolicyOrder.$allowPlayerSuppliers"/>
          </do_elseif>
          <do_if value="$mk42PolicyOrder.$buyFromFaction?">
            <set_value name="this.$mk4AllowAiSuppliers" exact="$mk42PolicyOrder.$buyFromFaction"/>
          </do_if>
          <do_elseif value="$mk42PolicyOrder.$allowAiSuppliers?">
            <set_value name="this.$mk4AllowAiSuppliers" exact="$mk42PolicyOrder.$allowAiSuppliers"/>
          </do_elseif>
          <do_if value="$mk42PolicyOrder.$serveHomeOnly?">
            <set_value name="this.$mk4DedicatedServe" exact="$mk42PolicyOrder.$serveHomeOnly"/>
          </do_if>
          <do_elseif value="$mk42PolicyOrder.$dedicatedServe?">
            <set_value name="this.$mk4DedicatedServe" exact="$mk42PolicyOrder.$dedicatedServe"/>
          </do_elseif>
        </do_if>
        <run_script name="'lib.gt.mk42.policy.resolve'" result="$mk42PolicyResult">
          <param name="priorityBuildstorage" value="if $mk42PolicyOrder? and $mk42PolicyOrder.$priorityBuildstorage? then $mk42PolicyOrder.$priorityBuildstorage else (if this.$effectivePriorityBuildstorage? then this.$effectivePriorityBuildstorage else (if $priorityBuildstorage? then $priorityBuildstorage else 10))"/>
          <param name="priorityStations" value="if $mk42PolicyOrder? and $mk42PolicyOrder.$priorityStations? then $mk42PolicyOrder.$priorityStations else (if this.$effectivePriorityStations? then this.$effectivePriorityStations else (if $priorityStations? then $priorityStations else 8))"/>
          <param name="priorityAux" value="if $mk42PolicyOrder? and $mk42PolicyOrder.$priorityAux? then $mk42PolicyOrder.$priorityAux else (if this.$effectivePriorityAux? then this.$effectivePriorityAux else (if $priorityAux? then $priorityAux else 0))"/>
          <param name="priorityCarrier" value="if $mk42PolicyOrder? and $mk42PolicyOrder.$priorityCarrier? then $mk42PolicyOrder.$priorityCarrier else (if this.$effectivePriorityCarrier? then this.$effectivePriorityCarrier else (if $priorityCarrier? then $priorityCarrier else 0))"/>
          <param name="prioritywares" value="if $mk42PolicyOrder? and $mk42PolicyOrder.$prioritywares? then $mk42PolicyOrder.$prioritywares else (if $effectivePriorityWares? then $effectivePriorityWares else [])"/>
          <param name="priorityscoremultiplier" value="if $mk42PolicyOrder? and $mk42PolicyOrder.$priorityscoremultiplier? then $mk42PolicyOrder.$priorityscoremultiplier else (if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 1)"/>
          <param name="buyFromPlayer" value="if $mk4AllowPlayerSuppliers? then $mk4AllowPlayerSuppliers else (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5)"/>
          <param name="buyFromFaction" value="if $mk4AllowAiSuppliers? then $mk4AllowAiSuppliers else (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5)"/>
          <param name="seedNullSliders" value="true"/>
        </run_script>
        <do_if value="$mk42PolicyResult?">
          <set_value name="$mk42Priorities" exact="if $mk42PolicyResult.$Priorities? then @$mk42PolicyResult.$Priorities else this.$mk42Priorities"/>
          <set_value name="this.$mk42Priorities" exact="$mk42Priorities"/>
          <set_value name="$mk42PrioSig" exact="@$mk42PolicyResult.$PrioSig"/>
          <set_value name="$pwSig" exact="@$mk42PolicyResult.$PrioSig"/>
          <set_value name="$effectivePriorityScoreMultiplier" exact="if $mk42PolicyResult.$PriorityScoreMultiplier? then @$mk42PolicyResult.$PriorityScoreMultiplier else $effectivePriorityScoreMultiplier"/>
          <set_value name="this.$effectivePriorityScoreMultiplier" exact="$effectivePriorityScoreMultiplier"/>
          <set_value name="$mk42NoDeliveryTargets" exact="if $mk42PolicyResult.$NoDeliveryTargets? then @$mk42PolicyResult.$NoDeliveryTargets else false"/>
          <do_if value="$mk42PolicyResult.$SeededNulls? and @$mk42PolicyResult.$SeededNulls and not this.$mk42SeededNullsLogged?">
            <set_value name="this.$mk42SeededNullsLogged" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4-2 seeded null priority sliders from defaults'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$mk42Priorities?">
          <set_value name="$effectivePriorityBuildstorage" exact="if $mk42Priorities.$Buildstorage? then $mk42Priorities.$Buildstorage else $effectivePriorityBuildstorage"/>
          <set_value name="$effectivePriorityStations" exact="if $mk42Priorities.$Stations? then $mk42Priorities.$Stations else $effectivePriorityStations"/>
          <set_value name="$effectivePriorityAux" exact="if $mk42Priorities.$Aux? then $mk42Priorities.$Aux else $effectivePriorityAux"/>
          <set_value name="$effectivePriorityCarrier" exact="if $mk42Priorities.$Carrier? then $mk42Priorities.$Carrier else $effectivePriorityCarrier"/>
          <set_value name="this.$effectivePriorityBuildstorage" exact="$effectivePriorityBuildstorage"/>
          <set_value name="this.$effectivePriorityStations" exact="$effectivePriorityStations"/>
          <set_value name="this.$effectivePriorityAux" exact="$effectivePriorityAux"/>
          <set_value name="this.$effectivePriorityCarrier" exact="$effectivePriorityCarrier"/>
          <set_value name="$effectiveIgnoreBuildStorage" exact="$effectivePriorityBuildstorage == 0"/>
          <set_value name="this.$effectiveIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
          <set_value name="$mk4BuildStorageOnlyMode" exact="$effectivePriorityBuildstorage gt 0 and $effectivePriorityStations == 0 and $effectivePriorityAux == 0 and $effectivePriorityCarrier == 0"/>
          <set_value name="this.$mk4BuildStorageOnlyMode" exact="$mk4BuildStorageOnlyMode"/>
        </do_if>
        <set_value name="$priorityWaresChanged" exact="this.$lastPriorityWaresSig? and this.$lastPriorityWaresSig != $pwSig"/>
        <set_value name="$mk42PrioSigPrevPipe" exact="if this.$lastMk42PrioSig? then this.$lastMk42PrioSig else ''"/>
        <set_value name="$mk42PrioChanged" exact="$mk42PrioSigPrevPipe != '' and $mk42PrioSigPrevPipe != $mk42PrioSig"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $mk42PrioSig?">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4-2 search-pipeline priorities ' + $mk42PrioSig + (if $mk42PrioChanged then ' (CHANGED from ' + $mk42PrioSigPrevPipe + ')' else '')" chance="100"/>
        </do_if>
        <!-- A priority-signature change is a PER-SHIP scoring concern, not a fleet-wide invalidation: the
             shared MK4-2 pool holds valid supply trades regardless of any one ship's priority sliders, and
             the cache reader re-filters/re-scores per ship. Wiping the global pool here let a single
             subordinate (whose sliders shift on staggered commander re-inheritance) erase the whole fleet's
             freshly-filled cache, starving every other ship (observed: DMB-935 wiped pool=30 0.5s after
             CUP-541 filled it). The non-destructive $mk42PrioChanged handler below already forces a live
             re-score for the affected ship when needed, so no global wipe is required. -->
        <do_if value="$mk42PrioChanged and $searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$searchHomeSector}?">
          <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="true"/>
          <do_all exact="global.$GT_TradeCacheMK42.{$searchHomeSector}.count" counter="$polFsiPipe">
              <set_value name="$polEntryPipe" exact="global.$GT_TradeCacheMK42.{$searchHomeSector}.{$polFsiPipe}"/>
              <do_if value="$polEntryPipe? and $polEntryPipe.$FailedShips? and $polEntryPipe.$FailedShips.count gt 0">
                <set_value name="$polNewFailedPipe" exact="[]"/>
                <do_all exact="$polEntryPipe.$FailedShips.count" counter="$polFsi2Pipe">
                  <do_if value="$polEntryPipe.$FailedShips.{$polFsi2Pipe} != this.ship">
                    <append_to_list name="$polNewFailedPipe" exact="$polEntryPipe.$FailedShips.{$polFsi2Pipe}"/>
                  </do_if>
                </do_all>
                <set_value name="$polEntryPipe.$FailedShips" exact="$polNewFailedPipe"/>
              </do_if>
            </do_all>
        </do_if>
        <!-- Always update baselines after evaluation (prevents false "changed" on first run/restart). -->
        <set_value name="this.$lastPriorityWaresSig" exact="$pwSig"/>
        <set_value name="this.$lastMk42PrioSig" exact="$mk42PrioSig"/>
        <set_value name="this.$lastPriorityWaresHome" exact="$searchHomeSector"/>

        <!-- Phase 1 (cache-only): run lightweight cache lookup and return control to scheduler. -->
        <do_if value="$searchPhase == 'cache'">
          <set_value name="$cacheFoundOnlyResult" exact="null"/>
          <set_value name="$cacheFoundOnly" exact="false"/>
          <set_value name="$cacheFoundOnlyTradeList" exact="[]"/>
          <set_value name="$cachePhaseSkipped" exact="not ($searchMode? and not $forceLiveSearch)"/>
          <do_if value="not $cachePhaseSkipped">
            <run_script name="'lib.gt.mk42.cache.search'" result="$cacheFoundOnlyResult">
              <param name="ship" value="this.ship"/>
              <param name="searchMode" value="$searchMode"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchRadiusMax"/>
              <param name="maxDistanceBuy" value="$searchMaxBuy"/>
              <param name="maxDistanceSell" value="$searchMaxSell"/>
              <param name="wareBasket" value="$searchWareBasket"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
              <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)"/>
              <param name="enableMinCargoUtil" value="if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)"/>
              <param name="mk42Priorities" value="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
              <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
              <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
              <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
              <param name="requirePlayerDeliveryStation" value="true"/>
              <param name="requirePlayerSupplierStation" value="not (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true)"/>
              <param name="requireNonPlayerSupplierStation" value="not (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true)"/>
              <param name="mk4DedicatedServe" value="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
              <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
              <param name="mk4AllowResources" value="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
              <param name="mk4AllowIntermediates" value="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
              <param name="mk4AllowTradewares" value="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
              <param name="ignoreTradeRules" value="if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false"/>
              
            </run_script>
            <do_if value="$cacheFoundOnlyResult? and $cacheFoundOnlyResult.$Found?">
              <set_value name="$cacheFoundOnly" exact="@$cacheFoundOnlyResult.$Found"/>
            </do_if>
            <do_if value="$cacheFoundOnly and $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$TradeList?">
              <set_value name="$cacheFoundOnlyTradeList" exact="@$cacheFoundOnlyResult.$TradeList"/>
            </do_if>
            <do_if value="$cacheFoundOnly and $cacheFoundOnlyTradeList? and $cacheFoundOnlyTradeList.count gt 0">
              <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
            </do_if>
            <!-- Pool has entries but this ship got zero: clear stale per-ship failure flags. -->
            <do_if value="not $cacheFoundOnly and $mk4HomeCacheCount gt 0 and $searchHomeSector? and $searchHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$searchHomeSector}?">
              <do_all exact="global.$GT_TradeCacheMK42.{$searchHomeSector}.count" counter="$cacheMissFsi">
                <set_value name="$cacheMissEntry" exact="global.$GT_TradeCacheMK42.{$searchHomeSector}.{$cacheMissFsi}"/>
                <do_if value="$cacheMissEntry? and $cacheMissEntry.$FailedShips? and $cacheMissEntry.$FailedShips.count gt 0">
                  <set_value name="$cacheMissNewFailed" exact="[]"/>
                  <do_all exact="$cacheMissEntry.$FailedShips.count" counter="$cacheMissFsi2">
                    <do_if value="$cacheMissEntry.$FailedShips.{$cacheMissFsi2} != this.ship">
                      <append_to_list name="$cacheMissNewFailed" exact="$cacheMissEntry.$FailedShips.{$cacheMissFsi2}"/>
                    </do_if>
                  </do_all>
                  <set_value name="$cacheMissEntry.$FailedShips" exact="$cacheMissNewFailed"/>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$cachePhaseCount" exact="if $cacheFoundOnlyTradeList? then $cacheFoundOnlyTradeList.count else 0"/>
            <set_value name="$cachePhaseOutcome" exact="if $cachePhaseSkipped then 'SKIP' else (if $cacheFoundOnly then 'HIT' else 'MISS')"/>
            <set_value name="$cachePhasePoolCount" exact="if $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$PoolSizeAfter? then @$cacheFoundOnlyResult.$PoolSizeAfter else (if $mk4HomeCacheCount? then $mk4HomeCacheCount else 0)"/>
            <set_value name="$cachePhasePurged" exact="if $cacheFoundOnlyResult? and $cacheFoundOnlyResult.$PurgedStale? then @$cacheFoundOnlyResult.$PurgedStale else 0"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache phase ' + $cachePhaseOutcome + ' (mode=' + $searchMode + ', trades=' + $cachePhaseCount + ', pool=' + $cachePhasePoolCount + (if $cachePhasePurged gt 0 then (', purged=' + $cachePhasePurged) else '') + ', home=' + (if $searchHomeSector? and $searchHomeSector.exists then $searchHomeSector.knownname else 'null') + ')'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Done'" param2="table[
            $Ship = this.ship,
            $Found = $cacheFoundOnly,
            $TradeList = $cacheFoundOnlyTradeList,
            $SearchMethod = 'cache',
            $SearchType = 'cache',
            $HomeSector = $searchHomeSector
          ]"/>
          <resume label="wait_for_response"/>
        </do_if>

        <set_value name="$pipelineFound" exact="false"/>
        <set_value name="$pipelineTradeList" exact="[]"/>
        <set_value name="$pipelineSearchMethod" exact="'live'"/>
        <set_value name="$cacheSearchResult" exact="null"/>
        <set_value name="$cacheFound" exact="false"/>
        <do_if value="$searchMode? and not $forceLiveSearch and not $skipCacheRead">
          <!-- 1) Cache path -->
          <run_script name="'lib.gt.mk42.cache.search'" result="$cacheSearchResult">
            <param name="ship" value="this.ship"/>
            <param name="searchMode" value="$searchMode"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchRadiusMax"/>
            <param name="maxDistanceBuy" value="$searchMaxBuy"/>
            <param name="maxDistanceSell" value="$searchMaxSell"/>
            <param name="wareBasket" value="$searchWareBasket"/>
            <param name="minROI" value="$searchMinROI"/>
            <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
            <param name="minCargoUtilPercent" value="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)"/>
            <param name="enableMinCargoUtil" value="if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)"/>
            <param name="mk42Priorities" value="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
            <param name="maxEntries" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? then @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries else 50"/>
            <param name="cacheMaxAge" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
            <param name="cacheDropoffTolerance" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance? then @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance else 15"/>
            <param name="requirePlayerDeliveryStation" value="true"/>
            <param name="requirePlayerSupplierStation" value="not (if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true)"/>
            <param name="requireNonPlayerSupplierStation" value="not (if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true)"/>
            <param name="mk4DedicatedServe" value="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
            <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
            <param name="mk4AllowResources" value="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
            <param name="mk4AllowIntermediates" value="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
            <param name="mk4AllowTradewares" value="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
            <param name="ignoreTradeRules" value="if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false"/>
            
          </run_script>
        </do_if>
        <!-- SAVEGAME GUARD: If save/load interrupted the run_script above, all locals are lost.
             Detect and bail to retry instead of cascading property lookup errors. -->
        <do_if value="not $searchMode?">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>
        <do_if value="$cacheSearchResult?">
          <do_if value="$cacheSearchResult.$Found?">
            <set_value name="$cacheFound" exact="@$cacheSearchResult.$Found"/>
          </do_if>
        </do_if>
        <do_if value="$cacheFound">
          <set_value name="$pipelineFound" exact="true"/>
          <set_value name="$pipelineSearchMethod" exact="'cache'"/>
          <set_value name="$pipelineTradeList" exact="if $cacheSearchResult.$TradeList? then @$cacheSearchResult.$TradeList else []"/>
          <!-- Per-ship re-score: normBase x class slider (reader priorities), same as live tradematch path. -->
          <do_if value="$pipelineTradeList? and $pipelineTradeList.count gt 0 and $searchMode? and $searchMode == 'buy_and_sell'">
            <run_script name="'lib.gt.mk42.score.trades'" result="$cacheScoreResult">
              <param name="tradeList" value="$pipelineTradeList"/>
              <param name="priorities" value="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 1"/>
              <param name="playerSupplierPriority" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
              <param name="aiSupplierPriority" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
              <param name="diversifyByWare" value="false"/>
              <param name="priorityFirstInDiversify" value="false"/>
              <param name="debugchance" value="@this.$debugchance"/>
            </run_script>
            <do_if value="$cacheScoreResult? and $cacheScoreResult.$SortedTrades? and $cacheScoreResult.$SortedTrades.count gt 0">
              <set_value name="$pipelineTradeList" exact="$cacheScoreResult.$SortedTrades"/>
            </do_if>
            <!-- Strict class tier (wide slider gap): stale ST-only cache must not win over BS=10 ST=1. -->
            <do_if value="$cacheScoreResult? and $cacheScoreResult.$StrictClassTier? and @$cacheScoreResult.$StrictClassTier">
              <set_value name="$cacheDominantTag" exact="if $cacheScoreResult.$DominantClassTag? then @$cacheScoreResult.$DominantClassTag else 'None'"/>
              <set_value name="$cacheHasDominantClass" exact="false"/>
              <do_if value="$cacheDominantTag != 'None' and $pipelineTradeList? and $pipelineTradeList.count gt 0">
                <do_all exact="$pipelineTradeList.count" counter="$cdi">
                  <set_value name="$cdTrade" exact="$pipelineTradeList.{$cdi}"/>
                  <do_if value="$cdTrade.$CustomerClass? and @$cdTrade.$CustomerClass == $cacheDominantTag">
                    <set_value name="$cacheHasDominantClass" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$cacheDominantTag != 'None' and not $cacheHasDominantClass">
                <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': cache rejected (strict tier dominant=' + $cacheDominantTag + ' absent in ' + (if $pipelineTradeList? then $pipelineTradeList.count else 0) + ' entries) - forcing live search'" chance="100"/>
                <set_value name="$cacheFound" exact="false"/>
                <set_value name="$pipelineFound" exact="false"/>
                <set_value name="$pipelineTradeList" exact="[]"/>
                <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
          <do_if value="$cacheFound and $pipelineTradeList? and $pipelineTradeList.count gt 0">
            <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
          </do_if>
        </do_if>
        <do_if value="not ($cacheFound and $pipelineFound)">
          <!-- 2) Pathfinding -->
          <run_script name="'lib.gt.pathfinding'" result="$pathResult">
            <param name="ship" value="this.ship"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchRadiusMax"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <!-- SAVEGAME GUARD -->
          <do_if value="not $searchMode?">
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
            <resume label="no_trade_retry"/>
          </do_if>

          <!-- 3) Live offers -->
          <!-- MK4 must search across all reachable offers; disable relative-price filtering for every mode/state. -->
          <set_value name="$searchSellPriceMax" exact="1.0"/>
          <set_value name="$searchBuyPriceMin" exact="-1.0"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PriceRange: SellPriceMax=' + $searchSellPriceMax + ' BuyPriceMin=' + $searchBuyPriceMin" chance="@this.$debugchance"/>
          <run_script name="'lib.gt.mk42.live.search'" result="$liveResult">
            <param name="ship" value="this.ship"/>
            <param name="searchMode" value="$searchMode"/>
            <param name="buySpaces" value="$pathResult.$BuySpaces"/>
            <param name="sellSpaces" value="$pathResult.$SellSpaces"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="maxDistance" value="$searchRadiusMax"/>
            <param name="wareBasket" value="$searchWareBasket"/>
            <param name="allowIllegal" value="$searchAllowIllegal"/>
            <param name="ownerFilter" value="'any'"/>
            <param name="includePlayerSellOffers" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers gt 0 else true"/>
            <param name="includeNpcSellOffers" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers gt 0 else true"/>
            <param name="includePlayerBuyOffers" value="true"/>
            <param name="requirePlayerBuyOfferOwner" value="true"/>
            <param name="ignoreTradeRulesPlayerBuyOffersRequireCargoNeed" value="true"/>
            <param name="ignoreMK1Supply" value="$searchIgnoreMK1Supply"/>
            <param name="ignoreTradeRules" value="$searchIgnoreTradeRules"/>
            <param name="maxOffersPerWare" value="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
            <param name="sellPriceMax" value="$searchSellPriceMax"/>
            <param name="buyPriceMin" value="$searchBuyPriceMin"/>
            <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
            <param name="demandLedSupplierScan" value="if $searchMode? and $searchMode == 'buy_and_sell' then true else false"/>
            <param name="mk42Priorities" value="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
            <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
            <param name="maxDistanceSell" value="$searchMaxSell"/>
            <param name="debugchance" value="@this.$debugchance"/>
          </run_script>
          <!-- SAVEGAME GUARD -->
          <do_if value="not $searchMode?">
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
            <resume label="no_trade_retry"/>
          </do_if>

          <!-- MK4 Galaxy-Supply: structured debug â€” delivery targets (buy offers), suppliers (sell offers), conditions -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMode? and $searchMode == 'buy_and_sell'">
            <set_value name="$mk4PriceProfile" exact="'normal'"/>
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?">
              <set_value name="$mk4PriceProfile" exact="'isolated'"/>
            </do_if>
            <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <set_value name="$mk4PriceProfile" exact="'fallback'"/>
            </do_elseif>
            <set_value name="$mk4HomeLabel" exact="if $searchHomeSector? and $searchHomeSector.exists then @$searchHomeSector.knownname else 'null'"/>
            <set_value name="$mk4EffHomeLabel" exact="if this.$effectiveHome? and this.$effectiveHome.exists then (if this.$effectiveHome.isclass.sector then ('SEC:' + @this.$effectiveHome.knownname) else ('ST:' + @this.$effectiveHome.knownname)) else 'null'"/>
            <set_value name="$mk4AutoW" exact="if $effectiveAutoWares? then $effectiveAutoWares else true"/>
            <set_value name="$mk4BasketN" exact="if $effectiveWareBasket? and $effectiveWareBasket.count? then $effectiveWareBasket.count else 0"/>
            <set_value name="$mk4BasketStr" exact="''"/>
            <do_if value="$effectiveWareBasket? and $effectiveWareBasket.count gt 0">
              <set_value name="$mk4Bmax" exact="[$effectiveWareBasket.count, 12].min"/>
              <do_all exact="$mk4Bmax" counter="$mk4bi">
                <set_value name="$mk4bw" exact="$effectiveWareBasket.{$mk4bi}"/>
                <set_value name="$mk4BasketStr" exact="$mk4BasketStr + (if $mk4bi gt 1 then ',' else '') + (if $mk4bw? and $mk4bw != null and $mk4bw.name? then @$mk4bw.name else '?')"/>
              </do_all>
              <do_if value="$effectiveWareBasket.count gt $mk4Bmax">
                <set_value name="$mk4BasketStr" exact="$mk4BasketStr + '...+' + ($effectiveWareBasket.count - $mk4Bmax)"/>
              </do_if>
            </do_if>
            <set_value name="$mk4PathIso" exact="if $pathResult.$ShipIsIsolated? then $pathResult.$ShipIsIsolated else false"/>
            <set_value name="$mk4BSn" exact="if $pathResult.$BuySpaces? then $pathResult.$BuySpaces.count else 0"/>
            <set_value name="$mk4SSn" exact="if $pathResult.$SellSpaces? then $pathResult.$SellSpaces.count else 0"/>
            <set_value name="$mk4SecSample" exact="''"/>
            <do_if value="$pathResult.$BuySpaces? and $pathResult.$BuySpaces.count gt 0">
              <set_value name="$mk4Smx" exact="[$pathResult.$BuySpaces.count, 6].min"/>
              <do_all exact="$mk4Smx" counter="$mk4si">
                <set_value name="$mk4s" exact="$pathResult.$BuySpaces.{$mk4si}"/>
                <set_value name="$mk4SecSample" exact="$mk4SecSample + (if $mk4si gt 1 then ',' else '') + (if $mk4s.knownname? then @$mk4s.knownname else '?')"/>
              </do_all>
            </do_if>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': CONDITIONS homeSector=' + $mk4HomeLabel + ' effectiveHome=' + $mk4EffHomeLabel + ' priceProfile=' + $mk4PriceProfile + ' SellPriceMax(rel)=' + $searchSellPriceMax + ' BuyPriceMin(rel)=' + $searchBuyPriceMin + ' ignoreTradeRules=' + $searchIgnoreTradeRules + ' allowIllegal=' + $searchAllowIllegal + ' enforceRouteIllegal=' + $searchEnforceRouteIllegalLegality + ' maxJumpBuy=' + $searchMaxBuy + ' maxJumpCoverage(delivery)=' + $searchMaxSell + ' pathRadiusMax=' + $searchRadiusMax + ' pathIsolated=' + $mk4PathIso + ' searchSectors=' + $mk4BSn + '/' + $mk4SSn + ' sampleSectors=[' + $mk4SecSample + ']'" chance="100"/>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': WARES autowares=' + $mk4AutoW + ' manualBasketCount=' + $mk4BasketN + ' manualBasket=[' + $mk4BasketStr + '] priorityWares=' + (if $effectivePriorityWares? and $effectivePriorityWares.count? then $effectivePriorityWares.count else 0)" chance="100"/>
            <set_value name="$mk4PlSup" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
            <set_value name="$mk4AiSup" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
            <set_value name="$mk4Ded" exact="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
            <set_value name="$mk4Res" exact="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
            <set_value name="$mk4Int" exact="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
            <set_value name="$mk4Tw" exact="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
            <set_value name="$mk4Bso" exact="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false"/>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': MK4FILTERS customerMustBePlayer=true allowPlayerSuppliers=' + $mk4PlSup + ' allowAiSuppliers=' + $mk4AiSup + ' dedicatedServe=' + $mk4Ded + ' buildStorageOnly=' + $mk4Bso + ' allowRes/int/tw=' + $mk4Res + '/' + $mk4Int + '/' + $mk4Tw" chance="100"/>
            <set_value name="$mk4SellC" exact="if $liveResult? and $liveResult.$SellOfferCount? then @$liveResult.$SellOfferCount else (if $liveResult? and $liveResult.$SellOffers? then $liveResult.$SellOffers.count else 0)"/>
            <set_value name="$mk4BuyC" exact="if $liveResult? and $liveResult.$BuyOfferCount? then @$liveResult.$BuyOfferCount else (if $liveResult? and $liveResult.$BuyOffers? then $liveResult.$BuyOffers.count else 0)"/>
            <set_value name="$mk4SWk" exact="if $liveResult? and $liveResult.$SellWaresFound? then @$liveResult.$SellWaresFound else 0"/>
            <set_value name="$mk4BWk" exact="if $liveResult? and $liveResult.$BuyWaresFound? then @$liveResult.$BuyWaresFound else 0"/>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': LIVE_OFFERS sellOffers=' + $mk4SellC + ' (distinctSellWares~' + $mk4SWk + ') buyOffers=' + $mk4BuyC + ' (distinctBuyWares~' + $mk4BWk + ')  [buyOffers=stations ship DELIVERS TO / sells to; sellOffers=NPCs ship BUYS FROM]'" chance="100"/>
            <!-- DELIVERY_TARGETS: MK4 only supplies player-owned customers â€” list player buy-offers only (not raw full list). -->
            <set_value name="$mk4DelivStr" exact="''"/>
            <set_value name="$mk4PlayerBuyTotal" exact="0"/>
            <set_value name="$mk4PlayerBuyListed" exact="0"/>
            <do_if value="$liveResult? and $liveResult.$BuyOffers? and $liveResult.$BuyOffers.count gt 0">
              <do_all exact="$liveResult.$BuyOffers.count" counter="$mk4di">
                <set_value name="$mk4bo" exact="$liveResult.$BuyOffers.{$mk4di}"/>
                <!-- Delivery customer: same as vanilla trade perform â€” buyer is the station that buys from the ship. -->
                <set_value name="$mk4boCustomer" exact="null"/>
                <do_if value="$mk4bo.buyer? and @$mk4bo.buyer.exists">
                  <set_value name="$mk4boCustomer" exact="@$mk4bo.buyer"/>
                </do_if>
                <do_elseif value="$mk4bo.owner?">
                  <set_value name="$mk4boCustomer" exact="@$mk4bo.owner"/>
                </do_elseif>
                <do_if value="not $mk4boCustomer? or not @$mk4boCustomer.exists">
                  <continue/>
                </do_if>
                <set_value name="$mk4boPlayerOk" exact="false"/>
                <do_if value="@$mk4boCustomer.isplayerowned">
                  <set_value name="$mk4boPlayerOk" exact="true"/>
                </do_if>
                <do_elseif value="$mk4boCustomer.isclass.buildstorage and $mk4boCustomer.base? and @$mk4boCustomer.base.isplayerowned">
                  <set_value name="$mk4boPlayerOk" exact="true"/>
                </do_elseif>
                <do_if value="not $mk4boPlayerOk">
                  <continue/>
                </do_if>
                <set_value name="$mk4PlayerBuyTotal" operation="add"/>
                <do_if value="$mk4PlayerBuyListed ge 40">
                  <continue/>
                </do_if>
                <set_value name="$mk4dst" exact="if @$mk4boCustomer.exists then @$mk4boCustomer.idcode else '?'"/>
                <set_value name="$mk4dsn" exact="if @$mk4boCustomer.knownname then @$mk4boCustomer.knownname else '?'"/>
                <set_value name="$mk4dwn" exact="if $mk4bo.ware? then @$mk4bo.ware.name else '?'"/>
                <set_value name="$mk4DelivStr" exact="$mk4DelivStr + (if $mk4DelivStr != '' then ' | ' else '') + $mk4dst + ':' + $mk4dsn + ':' + $mk4dwn"/>
                <set_value name="$mk4PlayerBuyListed" operation="add"/>
              </do_all>
              <!-- Safe cooperative yield after batch (never inside do_all in AI scripts). -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
              <do_if value="$mk4PlayerBuyTotal gt 40">
                <set_value name="$mk4DelivStr" exact="$mk4DelivStr + ' | ...+' + ($mk4PlayerBuyTotal - 40) + ' more player offers'"/>
              </do_if>
            </do_if>
            <do_if value="$mk4PlayerBuyTotal == 0">
              <set_value name="$mk4DelivStr" exact="'(no player-owned buy offers in live search â€” MK4 cannot deliver; check BuyPriceMin/tradepartner/ignoreTradeRules/jumps)'"/>
            </do_if>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': DELIVERY_TARGETS playerBuyOffers=' + $mk4PlayerBuyTotal + '/' + $mk4BuyC + ' (id:name:ware) ' + $mk4DelivStr" chance="100"/>
            <set_value name="$mk4SuppStr" exact="''"/>
            <do_if value="$liveResult? and $liveResult.$SellOffers? and $liveResult.$SellOffers.count gt 0">
              <set_value name="$mk4Slim" exact="[$liveResult.$SellOffers.count, 40].min"/>
              <do_all exact="$mk4Slim" counter="$mk4si2">
                <set_value name="$mk4so" exact="$liveResult.$SellOffers.{$mk4si2}"/>
                <set_value name="$mk4soSup" exact="null"/>
                <do_if value="$mk4so.seller? and @$mk4so.seller.exists">
                  <set_value name="$mk4soSup" exact="@$mk4so.seller"/>
                </do_if>
                <do_elseif value="$mk4so.owner?">
                  <set_value name="$mk4soSup" exact="@$mk4so.owner"/>
                </do_elseif>
                <set_value name="$mk4sst" exact="if $mk4soSup? and @$mk4soSup.exists then @$mk4soSup.idcode else '?'"/>
                <set_value name="$mk4ssn" exact="if $mk4soSup? and @$mk4soSup.knownname then @$mk4soSup.knownname else '?'"/>
                <set_value name="$mk4spl" exact="if $mk4soSup? and @$mk4soSup.isplayerowned then 'P' else 'N'"/>
                <set_value name="$mk4swn" exact="if $mk4so.ware? then @$mk4so.ware.name else '?'"/>
                <set_value name="$mk4SuppStr" exact="$mk4SuppStr + (if $mk4si2 gt 1 then ' | ' else '') + $mk4sst + ':' + $mk4ssn + '[' + $mk4spl + ']:' + $mk4swn"/>
              </do_all>
              <!-- Safe cooperative yield after batch (never inside do_all in AI scripts). -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
              <do_if value="$liveResult.$SellOffers.count gt $mk4Slim">
                <set_value name="$mk4SuppStr" exact="$mk4SuppStr + ' | ...+' + ($liveResult.$SellOffers.count - $mk4Slim) + ' more'"/>
              </do_if>
            </do_if>
            <do_else>
              <set_value name="$mk4SuppStr" exact="'(no sell offers â€” no supplier purchase candidates in live search)'"/>
            </do_else>
            <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': SUPPLIERS (id:name[P/N]:ware) ' + $mk4SuppStr" chance="100"/>
          </do_if>

          <do_if value="$searchMode? and $searchMode == 'sell_only'">
            <create_list name="$sellOnlyTrades"/>
            <set_value name="$liveBuyOffers" exact="[]"/>
            <do_if value="$liveResult?">
              <do_if value="$liveResult.$BuyOffers?">
                <set_value name="$liveBuyOffers" exact="@$liveResult.$BuyOffers"/>
              </do_if>
            </do_if>
            <do_if value="$liveBuyOffers.count gt 0">
              <do_all exact="$liveBuyOffers.count" counter="$offerIdx">
                <set_value name="$sellOffer" exact="$liveBuyOffers.{$offerIdx}"/>
                <set_value name="$sellWare" exact="if $sellOffer? and $sellOffer.ware? then @$sellOffer.ware else null"/>
                <do_if value="not $sellWare?">
                  <continue/>
                </do_if>

                <set_value name="$shipWareAmount" exact="this.ship.cargo.{$sellWare}.count"/>
                <set_value name="$tradeAmount" exact="[$shipWareAmount, $sellOffer.amount].min"/>
                <do_if value="$tradeAmount le 0">
                  <continue/>
                </do_if>

                <set_value name="$sellDistance" exact="$searchHomeSector.gatedistance.{$sellOffer.owner}"/>
                <do_if value="$sellDistance lt 0 or $sellDistance gt $searchMaxSell">
                  <continue/>
                </do_if>

                <set_value name="$distanceFactor" exact="1.0 + ($sellDistance * $gt_distancepenalty)"/>
                <set_value name="$sellUnitPriceCr" exact="($sellOffer.unitprice / 1Cr)i"/>
                <set_value name="$sellScore" exact="($tradeAmount * [$sellUnitPriceCr, 1].max) / $distanceFactor"/>
                <append_to_list name="$sellOnlyTrades" exact="table[
                  $IsSellOnly = true,
                  $Ware = $sellWare,
                  $SellOffer = $sellOffer,
                  $SellStation = $sellOffer.owner,
                  $Amount = $tradeAmount,
                  $Score = $sellScore,
                  $BuyStation = this.ship,
                  $BuySector = this.ship.sector,
                  $Distance = $sellDistance,
                  $UnitProfit = $sellOffer.unitprice,
                  $BuyPrice = 0,
                  $SellPrice = $sellOffer.unitprice,
                  $ProfitPerUnit = $sellOffer.unitprice,
                  $Profit = ($sellOffer.unitprice * $tradeAmount)
                ]"/>
              </do_all>
              <!-- AI locals do not survive waits inside do_all loops; yield once after the batch. -->
              <wait exact="this.$gt_yieldMs * 1ms"/>
            </do_if>

            <run_script name="'lib.gt.mk42.score.trades'" result="$scoreResult">
              <param name="tradeList" value="$sellOnlyTrades"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 1"/>
              <param name="playerSupplierPriority" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
              <param name="aiSupplierPriority" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
            </run_script>
            <set_value name="$pipelineSearchMethod" exact="'live_sell_only'"/>
            <set_value name="$scoreFound" exact="false"/>
            <do_if value="$scoreResult?">
              <do_if value="$scoreResult.$Found?">
                <set_value name="$scoreFound" exact="@$scoreResult.$Found"/>
              </do_if>
            </do_if>
            <do_if value="$scoreFound">
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $scoreResult.$SortedTrades? then @$scoreResult.$SortedTrades else []"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- 4) Trade matching -->
            <set_value name="this.$gt_dockMemo" exact="table[]"/>
            <run_script name="'lib.gt.mk42.tradematch'" result="$matchResult">
              <param name="ship" value="this.ship"/>
              <param name="sellOffers" value="$liveResult.$SellOffers"/>
              <param name="buyOffers" value="$liveResult.$BuyOffers"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="maxDistance" value="$searchRadiusMax"/>
              <param name="maxDistanceBuy" value="$searchMaxBuy"/>
              <param name="maxDistanceSell" value="$searchMaxSell"/>
              <param name="backtrackTolerance" value="if this.$effectiveBacktrackTolerance? then this.$effectiveBacktrackTolerance else 0"/>
              <param name="minROI" value="$searchMinROI"/>
              <param name="minAbsoluteProfit" value="$searchMinAbsoluteProfit"/>
              <param name="distancePenalty" value="$gt_distancepenalty"/>
              <param name="factionPriority" value="$searchFactionPriority"/>
              <param name="mk42Priorities" value="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
              <param name="allowIllegal" value="$searchAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$searchEnforceRouteIllegalLegality"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="scoreMode" value="'supply'"/>
              <param name="mk4CustomerMustBePlayer" value="true"/>
              <param name="mk4AllowPlayerSuppliers" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
              <param name="mk4AllowAiSuppliers" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
              <param name="mk4DedicatedServe" value="if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false"/>
              <param name="mk4AnchorHome" value="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
              <param name="mk4AllowResources" value="if this.$mk4AllowResources? then this.$mk4AllowResources else true"/>
              <param name="mk4AllowIntermediates" value="if this.$mk4AllowIntermediates? then this.$mk4AllowIntermediates else true"/>
              <param name="mk4AllowTradewares" value="if this.$mk4AllowTradewares? then this.$mk4AllowTradewares else true"/>
              <param name="maxTradesPerBucket" value="if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30"/>
            </run_script>
            <!-- SAVEGAME GUARD -->
            <do_if value="not $searchMode?">
              <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
              <resume label="no_trade_retry"/>
            </do_if>

            <!-- 5) Final score ranking -->
            <set_value name="$matchTradeList" exact="[]"/>
            <do_if value="$matchResult?">
              <do_if value="$matchResult.$TradeList?">
                <set_value name="$matchTradeList" exact="@$matchResult.$TradeList"/>
              </do_if>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$mk4Mev" exact="if $matchResult? and $matchResult.$TradesEvaluated? then @$matchResult.$TradesEvaluated else -1"/>
              <set_value name="$mk4Mrj" exact="if $matchResult? and $matchResult.$TradesRejected? then @$matchResult.$TradesRejected else -1"/>
              <set_value name="$mk4Mri" exact="if $matchResult? and $matchResult.$TradesRejectedRouteIllegal? then @$matchResult.$TradesRejectedRouteIllegal else -1"/>
              <set_value name="$mk4MrjCust" exact="if $matchResult? and $matchResult.$TradesRejectedMk4CustomerPolicy? then @$matchResult.$TradesRejectedMk4CustomerPolicy else -1"/>
              <set_value name="$mk4MrjSupp" exact="if $matchResult? and $matchResult.$TradesRejectedMk4SupplierPolicy? then @$matchResult.$TradesRejectedMk4SupplierPolicy else -1"/>
              <set_value name="$mk4MrjType" exact="if $matchResult? and $matchResult.$TradesRejectedMk4TypePolicy? then @$matchResult.$TradesRejectedMk4TypePolicy else -1"/>
              <set_value name="$mk4MrjDem" exact="if $matchResult? and $matchResult.$TradesRejectedMk4DemandGate? then @$matchResult.$TradesRejectedMk4DemandGate else -1"/>
              <set_value name="$mk4MrjPc" exact="if $matchResult? and $matchResult.$TradesRejectedMk4PriceCap? then @$matchResult.$TradesRejectedMk4PriceCap else -1"/>
              <set_value name="$mk4MrjBso" exact="if $matchResult? and $matchResult.$TradesRejectedMk4BuildStorageOnly? then @$matchResult.$TradesRejectedMk4BuildStorageOnly else -1"/>
              <set_value name="$mk4MrjDist" exact="if $matchResult? and $matchResult.$TradesRejectedDistance? then @$matchResult.$TradesRejectedDistance else -1"/>
              <set_value name="$mk4MrjRules" exact="if $matchResult? and $matchResult.$TradesRejectedTradeRules? then @$matchResult.$TradesRejectedTradeRules else -1"/>
              <set_value name="$mk4Mfound" exact="if $matchResult? and $matchResult.$Found? then @$matchResult.$Found else false"/>
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': TRADEMATCH supply-mode rawListCount=' + $matchTradeList.count + ' bestFound=' + $mk4Mfound + ' pairsEvaluated=' + $mk4Mev + ' pairsRejected=' + $mk4Mrj + ' routeIllegalRejected=' + $mk4Mri + ' rej(customer/supplier/type/demand/pricecap/bso/dist/rules)=' + $mk4MrjCust + '/' + $mk4MrjSupp + '/' + $mk4MrjType + '/' + $mk4MrjDem + '/' + $mk4MrjPc + '/' + $mk4MrjBso + '/' + $mk4MrjDist + '/' + $mk4MrjRules + (if $matchResult? and $matchResult.$DualAxisBuckets? then (' dualAxis=1 cap=' + (if $matchResult.$BucketMergeCap? then @$matchResult.$BucketMergeCap else 0) + ' pre=BS_P=' + (if $matchResult.$BucketPreBsP? then @$matchResult.$BucketPreBsP else 0) + '/BS_N=' + (if $matchResult.$BucketPreBsN? then @$matchResult.$BucketPreBsN else 0) + '/ST_P=' + (if $matchResult.$BucketPreStP? then @$matchResult.$BucketPreStP else 0) + '/ST_N=' + (if $matchResult.$BucketPreStN? then @$matchResult.$BucketPreStN else 0) + ' out=BS_P=' + (if $matchResult.$BucketOutBsP? then @$matchResult.$BucketOutBsP else 0) + '/BS_N=' + (if $matchResult.$BucketOutBsN? then @$matchResult.$BucketOutBsN else 0) + '/ST_P=' + (if $matchResult.$BucketOutStP? then @$matchResult.$BucketOutStP else 0) + '/ST_N=' + (if $matchResult.$BucketOutStN? then @$matchResult.$BucketOutStN else 0)) else '')" chance="100"/>
            </do_if>
            <run_script name="'lib.gt.mk42.score.trades'" result="$scoreResult">
              <param name="tradeList" value="$matchTradeList"/>
              <param name="priorities" value="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
              <param name="priorityWares" value="if $effectivePriorityWares? then $effectivePriorityWares else []"/>
              <param name="priorityScoreMultiplier" value="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 1"/>
              <param name="playerSupplierPriority" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
              <param name="aiSupplierPriority" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
              <param name="diversifyByWare" value="false"/>
              <param name="priorityFirstInDiversify" value="false"/>
              <param name="debugchance" value="@this.$debugchance"/>
            </run_script>

            <set_value name="$scoreFound" exact="false"/>
            <do_if value="$scoreResult?">
              <do_if value="$scoreResult.$Found?">
                <set_value name="$scoreFound" exact="@$scoreResult.$Found"/>
              </do_if>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$mk4ScCnt" exact="if $scoreResult? and $scoreResult.$SortedTrades? then $scoreResult.$SortedTrades.count else 0"/>
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': SCORE_TRADES found=' + $scoreFound + ' sortedTrades=' + $mk4ScCnt" chance="100"/>
            </do_if>
            <do_if value="$scoreFound">
              <set_value name="$pipelineFound" exact="true"/>
              <set_value name="$pipelineTradeList" exact="if $scoreResult.$SortedTrades? then @$scoreResult.$SortedTrades else []"/>
            </do_if>
          </do_else>
        </do_if>

        <!-- Savegame compatibility: local pipeline vars can be missing on migrated/running states.
             Normalize them before any unconditional reads below. -->
        <do_if value="not $pipelineFound?">
          <set_value name="$pipelineFound" exact="false"/>
        </do_if>
        <do_if value="not $pipelineTradeList?">
          <set_value name="$pipelineTradeList" exact="[]"/>
        </do_if>
        <do_if value="not $pipelineSearchMethod?">
          <set_value name="$pipelineSearchMethod" exact="'live'"/>
        </do_if>

        <!-- serveHomeOnly / build-storage-only home-anchor scope:
             - buildStorageOnly => player BS within jumpDistanceCoverage from home
             - serveHomeOnly (non-BSO) => home station + its BS, or home sector -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ((if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) or (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false))">
          <set_value name="$serveHomeAnchor" exact="if this.$effectiveHome? then this.$effectiveHome else $searchHome"/>
          <set_value name="$serveHomeSector" exact="if $serveHomeAnchor? and $serveHomeAnchor.isclass.sector then $serveHomeAnchor else (if $serveHomeAnchor? and $serveHomeAnchor.sector? then @$serveHomeAnchor.sector else $searchHomeSector)"/>
          <set_value name="$serveHomeBeforeCount" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListServeHomeFiltered"/>
          <do_all exact="$pipelineTradeList.count" counter="$shrIdx">
            <set_value name="$shrTrade" exact="$pipelineTradeList.{$shrIdx}"/>
            <set_value name="$shrKeep" exact="true"/>
            <set_value name="$shrDeliveryStation" exact="if $shrTrade.$SellStation? then $shrTrade.$SellStation else null"/>
            <do_if value="not $shrDeliveryStation? and $shrTrade.$SellOffer?">
              <do_if value="$shrTrade.$SellOffer.buyer? and @$shrTrade.$SellOffer.buyer.exists">
                <set_value name="$shrDeliveryStation" exact="@$shrTrade.$SellOffer.buyer"/>
              </do_if>
              <do_elseif value="$shrTrade.$SellOffer.owner?">
                <set_value name="$shrDeliveryStation" exact="@$shrTrade.$SellOffer.owner"/>
              </do_elseif>
            </do_if>
            <do_if value="if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false">
              <set_value name="$shrSupplierStation" exact="if $shrTrade.$BuyStation? then $shrTrade.$BuyStation else null"/>
              <do_if value="not $shrSupplierStation? and $shrTrade.$BuyOffer?">
                <do_if value="$shrTrade.$BuyOffer.seller? and @$shrTrade.$BuyOffer.seller.exists">
                  <set_value name="$shrSupplierStation" exact="@$shrTrade.$BuyOffer.seller"/>
                </do_if>
                <do_elseif value="$shrTrade.$BuyOffer.owner?">
                  <set_value name="$shrSupplierStation" exact="@$shrTrade.$BuyOffer.owner"/>
                </do_elseif>
              </do_if>
              <do_if value="$shrSupplierStation? and @$shrSupplierStation.isclass.buildstorage">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
              <do_if value="$shrKeep and (not $shrDeliveryStation? or not @$shrDeliveryStation.isclass.buildstorage)">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
              <do_if value="$shrKeep">
                <set_value name="$shrBsoDist" exact="if $searchHomeSector? and $shrDeliveryStation? and $shrDeliveryStation.sector? then $searchHomeSector.gatedistance.{$shrDeliveryStation.sector} else -1"/>
                <do_if value="$shrBsoDist lt 0 or ($searchMaxSell gt 0 and $shrBsoDist gt $searchMaxSell)">
                  <set_value name="$shrKeep" exact="false"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$shrKeep and not (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) and (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) and $serveHomeAnchor? and $serveHomeAnchor.isclass.station">
              <set_value name="$shrServeHomeMatch" exact="false"/>
              <do_if value="$shrDeliveryStation? and $shrDeliveryStation.exists and $serveHomeAnchor.exists">
                <do_if value="$shrDeliveryStation == $serveHomeAnchor">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_if>
                <do_elseif value="$serveHomeAnchor.buildstorage? and $serveHomeAnchor.buildstorage.exists and $shrDeliveryStation == $serveHomeAnchor.buildstorage">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
                <do_elseif value="$shrDeliveryStation.isclass.buildstorage and $shrDeliveryStation.base? and $shrDeliveryStation.base.exists and $shrDeliveryStation.base == $serveHomeAnchor">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
                <do_elseif value="$shrDeliveryStation.hascontext.{$serveHomeAnchor}">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
                <do_elseif value="$serveHomeAnchor.hascontext.{$shrDeliveryStation}">
                  <set_value name="$shrServeHomeMatch" exact="true"/>
                </do_elseif>
              </do_if>
              <do_if value="not $shrServeHomeMatch">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$shrKeep and not (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) and (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) and $serveHomeSector? and $serveHomeSector.exists and (not $serveHomeAnchor? or not $serveHomeAnchor.isclass.station)">
              <do_if value="not $shrDeliveryStation? or not $shrDeliveryStation.sector? or @$shrDeliveryStation.sector != $serveHomeSector">
                <set_value name="$shrKeep" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="$shrKeep">
              <append_to_list name="$pipelineTradeListServeHomeFiltered" exact="$shrTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListServeHomeFiltered"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': homeScope filter: before=' + $serveHomeBeforeCount + ', after=' + $pipelineTradeList.count + ', dedicatedServe=' + (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false) + ', buildStorageOnly=' + (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) + ', homeType=' + (if $serveHomeAnchor? and $serveHomeAnchor.isclass.station then 'station' else 'sector') + ', home=' + (if $serveHomeAnchor? and $serveHomeAnchor.exists then @$serveHomeAnchor.knownname else 'null')" chance="100"/>
          </do_if>
        </do_if>

        <!-- Â§3 searchDepth: breadth cap for validation. MK4 supply may extend cap to fit one
             candidate per distinct ware when that exceeds searchDepth (score order, no diversify). -->
        <set_value name="$searchDepthCap" exact="if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30"/>
        <do_if value="$pipelineFound and $pipelineTradeList.count gt $searchDepthCap">
          <set_value name="$mk4PipelineDepthBefore" exact="$pipelineTradeList.count"/>
          <set_value name="$mk4DistinctWareCount" exact="0"/>
          <set_value name="$mk4DistinctWaresSeen" exact="table[]"/>
          <do_all exact="$pipelineTradeList.count" counter="$mk4DwIdx">
            <set_value name="$mk4DwTrade" exact="$pipelineTradeList.{$mk4DwIdx}"/>
            <set_value name="$mk4DwWare" exact="if $mk4DwTrade.$Ware? then $mk4DwTrade.$Ware else null"/>
            <do_if value="$mk4DwWare? and not $mk4DistinctWaresSeen.{$mk4DwWare}?">
              <set_value name="$mk4DistinctWaresSeen.{$mk4DwWare}" exact="true"/>
              <set_value name="$mk4DistinctWareCount" operation="add"/>
            </do_if>
          </do_all>
          <set_value name="$mk4EffectiveDepthCap" exact="$searchDepthCap"/>
          <do_if value="$searchMode? and $searchMode == 'buy_and_sell' and $mk4DistinctWareCount gt $searchDepthCap">
            <set_value name="$mk4EffectiveDepthCap" exact="$mk4DistinctWareCount"/>
          </do_if>
          <do_if value="$pipelineTradeList.count gt $mk4EffectiveDepthCap">
            <create_list name="$pipelineTradeListCapped"/>
            <do_all exact="$mk4EffectiveDepthCap" counter="$sdIdx">
              <append_to_list name="$pipelineTradeListCapped" exact="$pipelineTradeList.{$sdIdx}"/>
            </do_all>
            <set_value name="$pipelineTradeList" exact="$pipelineTradeListCapped"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMode? and $searchMode == 'buy_and_sell'">
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': searchDepth cap before=' + $mk4PipelineDepthBefore + ' after=' + $pipelineTradeList.count + ' configured=' + $searchDepthCap + ' effective=' + $mk4EffectiveDepthCap + ' distinctWares=' + $mk4DistinctWareCount" chance="100"/>
            </do_if>
          </do_if>
        </do_if>

        <!-- Write live search results to cache (sorted insertion with AI-script yields).
             Includes sell-only live results so cargo disposal can reuse cache entries. -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ($pipelineSearchMethod == 'live' or $pipelineSearchMethod == 'live_sell_only') and $searchMode?">
          <run_script name="'lib.gt.mk42.cache.write'" result="$cacheWriteResult">
            <param name="tradeList" value="$pipelineTradeList"/>
            <param name="homeSector" value="$searchHomeSector"/>
            <param name="cacheTTL" value="if global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL? then @global.$GT_GlobalSettings.$Fleet.$CacheTTL else 300s"/>
            <param name="maxSearchDistance" value="$searchRadiusMax"/>
          </run_script>
        </do_if>
        <!-- SAVEGAME GUARD -->
        <do_if value="not $pipelineFound?">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- MK4 Galaxy-Supply: fallback search disabled. lib.gt.fallback.search uses sell-mode tradematch without
             mk4CustomerMustBePlayer, which allows deliveries to non-player stations (foreign "customers"). -->

        <!-- Final pipeline result check -->
        <do_if value="not $pipelineFound">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
          <resume label="no_trade_retry"/>
        </do_if>

        <!-- Per-ship dispatch filter:
             MK4 cache pool is supply-specific; remove blocked-faction entries from the list sent to validation. -->
        <set_value name="$mk3BlacklistOwnerDispatch" exact="this.ship"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
          <set_value name="$mk3BlacklistOwnerDispatch" exact="this.ship.commander"/>
        </do_if>
        <set_value name="$mk3FactionBlacklistDispatch" exact="table[]"/>
        <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerDispatch}?">
          <set_value name="$mk3FactionBlacklistDispatch" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerDispatch}"/>
        </do_if>
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and $mk3FactionBlacklistDispatch.keys.count gt 0">
          <set_value name="$pipelineTradeListBeforeDispatchFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListFiltered"/>
          <do_all exact="$pipelineTradeList.count" counter="$dispatchIdx">
            <set_value name="$dispatchTrade" exact="$pipelineTradeList.{$dispatchIdx}"/>
            <set_value name="$dispatchKeepTrade" exact="true"/>
            <!-- MK4 hard policy at dispatch stage: only player delivery customers, supplier side by policy -->
            <set_value name="$dispatchAllowPlayerSuppliers" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
            <set_value name="$dispatchAllowAiSuppliers" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly)">
              <!-- Delivery station: prefer game buy-offer buyer (matches lib.gt.mk42.tradematch / validation). -->
              <set_value name="$dispatchDeliveryStation" exact="if $dispatchTrade.$SellStation? then @$dispatchTrade.$SellStation else null"/>
              <do_if value="not $dispatchDeliveryStation? and $dispatchTrade.$SellOffer?">
                <do_if value="$dispatchTrade.$SellOffer.buyer? and @$dispatchTrade.$SellOffer.buyer.exists">
                  <set_value name="$dispatchDeliveryStation" exact="@$dispatchTrade.$SellOffer.buyer"/>
                </do_if>
                <do_elseif value="$dispatchTrade.$SellOffer.owner?">
                  <set_value name="$dispatchDeliveryStation" exact="@$dispatchTrade.$SellOffer.owner"/>
                </do_elseif>
              </do_if>
              <do_if value="not $dispatchDeliveryStation? or not @$dispatchDeliveryStation.isplayerowned">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly)">
              <!-- Supplier station is BuyOffer.seller (fallback owner) -->
              <set_value name="$dispatchSupplierStation" exact="null"/>
              <do_if value="$dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.seller? and @$dispatchTrade.$BuyOffer.seller.exists">
                <set_value name="$dispatchSupplierStation" exact="@$dispatchTrade.$BuyOffer.seller"/>
              </do_if>
              <do_elseif value="$dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.owner? and @$dispatchTrade.$BuyOffer.owner.exists">
                <set_value name="$dispatchSupplierStation" exact="@$dispatchTrade.$BuyOffer.owner"/>
              </do_elseif>

              <do_if value="not $dispatchAllowPlayerSuppliers and $dispatchSupplierStation? and @$dispatchSupplierStation.isplayerowned">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
              <do_if value="$dispatchKeepTrade and not $dispatchAllowAiSuppliers">
                <do_if value="not $dispatchSupplierStation? or not @$dispatchSupplierStation.isplayerowned">
                  <set_value name="$dispatchKeepTrade" exact="false"/>
                </do_if>
              </do_if>
            </do_if>

            <do_if value="$dispatchTrade? and not ($dispatchTrade.$IsSellOnly? and $dispatchTrade.$IsSellOnly) and $dispatchTrade.$BuyOffer? and $dispatchTrade.$BuyOffer.owner?">
              <set_value name="$dispatchBuyOwnerContainer" exact="@$dispatchTrade.$BuyOffer.owner"/>
              <set_value name="$dispatchBuyFaction" exact="null"/>
              <do_if value="$dispatchBuyOwnerContainer.owner?">
                <set_value name="$dispatchBuyFaction" exact="$dispatchBuyOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$dispatchBuyFaction" exact="$dispatchBuyOwnerContainer"/>
              </do_else>
              <do_if value="$dispatchBuyFaction? and $mk3FactionBlacklistDispatch.{$dispatchBuyFaction}?">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade and $dispatchTrade? and $dispatchTrade.$SellOffer? and $dispatchTrade.$SellOffer.owner?">
              <set_value name="$dispatchSellOwnerContainer" exact="@$dispatchTrade.$SellOffer.owner"/>
              <set_value name="$dispatchSellFaction" exact="null"/>
              <do_if value="$dispatchSellOwnerContainer.owner?">
                <set_value name="$dispatchSellFaction" exact="$dispatchSellOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$dispatchSellFaction" exact="$dispatchSellOwnerContainer"/>
              </do_else>
              <do_if value="$dispatchSellFaction? and $mk3FactionBlacklistDispatch.{$dispatchSellFaction}?">
                <set_value name="$dispatchKeepTrade" exact="false"/>
              </do_if>
            </do_if>

            <do_if value="$dispatchKeepTrade">
              <append_to_list name="$pipelineTradeListFiltered" exact="$dispatchTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListFiltered"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Dispatch MK3 faction filter: before=' + $pipelineTradeListBeforeDispatchFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineTradeListBeforeDispatchFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Live search can run 1+ seconds. Re-check per-ship offer amounts immediately before dispatch
             so trades reserved/exhausted during matching are not sent to expensive validation. -->
        <do_if value="$pipelineFound and $pipelineTradeList.count gt 0 and ($pipelineSearchMethod == 'live' or $pipelineSearchMethod == 'live_sell_only' or $pipelineSearchMethod == 'live_fallback')">
          <set_value name="$pipelineBeforeFreshFilter" exact="$pipelineTradeList.count"/>
          <create_list name="$pipelineTradeListFresh"/>
          <do_all exact="$pipelineTradeList.count" counter="$freshIdx">
            <set_value name="$freshTrade" exact="$pipelineTradeList.{$freshIdx}"/>
            <set_value name="$freshKeep" exact="false"/>
            <do_if value="$freshTrade? and $freshTrade.$IsSellOnly? and $freshTrade.$SellOffer?">
              <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and @$freshTrade.$SellOffer.amount gt 0">
                <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.amount"/>
              </do_if>
              <do_if value="$freshSellAmt? and $freshSellAmt gt 0">
                <set_value name="$freshKeep" exact="true"/>
              </do_if>
            </do_if>
            <do_elseif value="$freshTrade? and $freshTrade.$BuyOffer? and $freshTrade.$SellOffer?">
              <!-- Re-resolve embedded offers before amount checks (handles can go stale during live search). -->
              <set_value name="$freshBuyStation" exact="null"/>
              <set_value name="$freshSellStation" exact="null"/>
              <set_value name="$freshBuyWare" exact="if $freshTrade.$Ware? then $freshTrade.$Ware else null"/>
              <set_value name="$freshSellWare" exact="if $freshTrade.$Ware? then $freshTrade.$Ware else null"/>
              <do_if value="not $freshBuyWare? and @$freshTrade.$BuyOffer.ware != null">
                <set_value name="$freshBuyWare" exact="@$freshTrade.$BuyOffer.ware"/>
              </do_if>
              <do_if value="not $freshSellWare? and @$freshTrade.$SellOffer.ware != null">
                <set_value name="$freshSellWare" exact="@$freshTrade.$SellOffer.ware"/>
              </do_if>
              <do_if value="$freshTrade.$BuyStation? and @$freshTrade.$BuyStation.exists">
                <set_value name="$freshBuyStation" exact="$freshTrade.$BuyStation"/>
              </do_if>
              <do_elseif value="$freshTrade.$BuyOffer.seller? and @$freshTrade.$BuyOffer.seller.exists">
                <set_value name="$freshBuyStation" exact="@$freshTrade.$BuyOffer.seller"/>
              </do_elseif>
              <do_elseif value="$freshTrade.$BuyOffer.owner? and @$freshTrade.$BuyOffer.owner.exists">
                <set_value name="$freshBuyStation" exact="@$freshTrade.$BuyOffer.owner"/>
              </do_elseif>
              <do_if value="$freshTrade.$SellStation? and @$freshTrade.$SellStation.exists">
                <set_value name="$freshSellStation" exact="$freshTrade.$SellStation"/>
              </do_if>
              <do_elseif value="$freshTrade.$SellOffer.buyer? and @$freshTrade.$SellOffer.buyer.exists">
                <set_value name="$freshSellStation" exact="@$freshTrade.$SellOffer.buyer"/>
              </do_elseif>
              <do_elseif value="$freshTrade.$SellOffer.owner? and @$freshTrade.$SellOffer.owner.exists">
                <set_value name="$freshSellStation" exact="@$freshTrade.$SellOffer.owner"/>
              </do_elseif>
              <!-- Build-storage delivery refs go stale fast; recover the live build storage from the
                   stable base station captured at match time (mirrors lib.gt.mk42.cache.search). -->
              <do_elseif value="$freshTrade.$SellStationBase? and @$freshTrade.$SellStationBase.exists and @$freshTrade.$SellStationBase.buildstorage and @$freshTrade.$SellStationBase.buildstorage.exists">
                <set_value name="$freshSellStation" exact="@$freshTrade.$SellStationBase.buildstorage"/>
                <set_value name="$freshTrade.$SellStation" exact="$freshSellStation"/>
              </do_elseif>
              <do_if value="$freshBuyStation? and $freshBuyStation.exists and $freshBuyWare != null">
                <find_sell_offer seller="$freshBuyStation" wares="$freshBuyWare" tradepartner="this.ship" result="$freshResolvedBuyOffer"/>
                <do_if value="$freshResolvedBuyOffer?">
                  <set_value name="$freshTrade.$BuyOffer" exact="$freshResolvedBuyOffer"/>
                </do_if>
              </do_if>
              <do_if value="$freshSellStation? and $freshSellStation.exists and $freshSellWare != null">
                <!-- Build storages expose "empty" buy offers; fetch with excludeempty/usereservations=false. -->
                <do_if value="@$freshSellStation.isclass.buildstorage">
                  <find_buy_offer buyer="$freshSellStation" wares="$freshSellWare" tradepartner="this.ship" result="$freshResolvedSellOffer" excludeempty="false" usereservations="false"/>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$freshSellStation" wares="$freshSellWare" tradepartner="this.ship" result="$freshResolvedSellOffer"/>
                </do_else>
                <do_if value="$freshResolvedSellOffer?">
                  <set_value name="$freshTrade.$SellOffer" exact="$freshResolvedSellOffer"/>
                </do_if>
              </do_if>
              <set_value name="$freshBuyAmt" exact="@$freshTrade.$BuyOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshBuyAmt? or $freshBuyAmt le 0) and @$freshTrade.$BuyOffer.amount gt 0">
                <set_value name="$freshBuyAmt" exact="@$freshTrade.$BuyOffer.amount"/>
              </do_if>
              <do_if value="(not $freshBuyAmt? or $freshBuyAmt le 0) and $freshSellStation? and $freshSellStation.exists and $freshBuyWare?">
                <set_value name="$freshBuyAmt" exact="[0, $freshSellStation.cargo.{$freshBuyWare}.target - $freshSellStation.cargo.{$freshBuyWare}.count].max"/>
              </do_if>
              <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.offeramount.{this.ship}"/>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and @$freshTrade.$SellOffer.amount gt 0">
                <set_value name="$freshSellAmt" exact="@$freshTrade.$SellOffer.amount"/>
              </do_if>
              <do_if value="(not $freshSellAmt? or $freshSellAmt le 0) and $freshSellStation? and $freshSellStation.exists and $freshSellWare?">
                <set_value name="$freshSellAmt" exact="[0, $freshSellStation.cargo.{$freshSellWare}.target - $freshSellStation.cargo.{$freshSellWare}.count].max"/>
              </do_if>
              <do_if value="$freshBuyAmt? and $freshBuyAmt gt 0 and $freshSellAmt? and $freshSellAmt gt 0">
                <set_value name="$freshKeep" exact="true"/>
              </do_if>
            </do_elseif>
            <do_if value="$freshKeep">
              <append_to_list name="$pipelineTradeListFresh" exact="$freshTrade"/>
            </do_if>
          </do_all>
          <set_value name="$pipelineTradeList" exact="$pipelineTradeListFresh"/>
          <set_value name="$pipelineFound" exact="$pipelineTradeList.count gt 0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fresh offer filter: before=' + $pipelineBeforeFreshFilter + ', after=' + $pipelineTradeList.count + ', removed=' + ($pipelineBeforeFreshFilter - $pipelineTradeList.count)" chance="100"/>
          </do_if>
        </do_if>

        <!-- Notify scheduler that this ship finished its search slot (semaphore release + dispatch) -->
        <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="false"/>
        <signal_objects object="player.galaxy" param="'GT_Search_Done'" param2="table[
          $Ship = this.ship,
          $Found = $pipelineFound,
          $TradeList = $pipelineTradeList,
          $SearchMethod = $pipelineSearchMethod,
          $SearchType = if $searchMode? and $searchMode == 'sell_only' then 'clearance' else 'live'
        ]"/>
        <resume label="wait_for_response"/>
      </do_if>
      
      <!-- Safety net: if $searchParams was not a valid table (should not happen after timeout guard above,
           but defense-in-depth). Clean up and retry. -->
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': WARNING: run_search_pipeline reached with invalid searchParams (typeof=' + typeof $searchParams + ') at game time ' + player.age + ' â€” this should not happen, aborting to retry'" chance="100"/>
      <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>
      <resume label="no_trade_retry"/>
      
      <!-- ========================================= -->
      <!-- TRADE FOUND - VALIDATE BLACKLIST FIRST   -->
      <!-- ========================================= -->
      <label name="trade_found"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': REACHED trade_found label - starting blacklist validation at game time ' + player.age" chance="100"/>
      </do_if>
      
      <!-- FAST MONEY CHECK: Short-circuit the expensive 20-trade validation loop when player
           money has dropped below the threshold since this ship's search started.
           Checks static threshold (MinPlayerMoney + 1000 buffer). The fleet money cap is NOT
           consulted here: it is a wealth snapshot and must never block a ship that already holds
           more than the threshold. The per-trade authoritative guard handles unaffordable trades. -->
      <do_if value="not this.$minPlayerMoney?">
        <run_script name="'lib.gt.attention.min_player_money'" result="this.$minPlayerMoney"/>
      </do_if>
      <set_value name="$fastMoneyThreshold" exact="(this.$minPlayerMoney + 1000)Cr"/>
      <do_if value="player.money le $fastMoneyThreshold">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FAST MONEY CHECK at trade_found: player.money=' + (player.money / 100) + ' Cr, threshold=' + (this.$minPlayerMoney + 1000) + ' Cr - skipping validation, backing off'" chance="100"/>
        </do_if>
        <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
        <resume label="no_trade_retry"/>
      </do_if>
      
      <!-- Initialize validation variables BEFORE do_if block to ensure they always exist -->
      <set_value name="$validTradeFound" exact="false"/>
      <set_value name="$pendingTrade" exact="null"/>
      <set_value name="$buyStation" exact="null"/>
      <set_value name="$sellStation" exact="null"/>
      <set_value name="$tradesChecked" exact="0"/>
      <set_value name="$tradesBlacklisted" exact="0"/>
      <set_value name="$tradesRejectedDocking" exact="0"/>
      <set_value name="$tradesRejectedOfferInvalid" exact="0"/>
      <set_value name="$tradesRejectedPath" exact="0"/>
      <set_value name="$tradesRejectedDistance" exact="0"/>
      <set_value name="$tradesRejectedCargo" exact="0"/>
      <set_value name="$tradesRejectedProfit" exact="0"/>
      <set_value name="$tradesRejectedRestriction" exact="0"/>
      <set_value name="$tradesRejectedDemandReserved" exact="0"/>
      <set_value name="$selectedTradeIdx" exact="0"/>
      <set_value name="$validTradesFound" exact="0"/>
      <create_list name="$validatedTradeCandidates"/>
      <set_value name="$selectedCurrentSectorIsBlacklisted" exact="false"/>
      <set_value name="$searchHomeSector" exact="if this.$lastPriorityWaresHome? and this.$lastPriorityWaresHome.exists then this.$lastPriorityWaresHome else (if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else this.ship.sector))"/>
      
      <!-- Iterate through trade list and validate each one -->
      <!-- Priority order: Signal param2 (from cache search work unit or live search) > Global storage (for threat intelligence compatibility) -->
      <!-- Cache search work units filter entries and signal results via GT_Trade_Found with param2 -->
      <!-- Initialize $tradeList and $searchMethod to prevent property lookup failures -->
      <set_value name="$tradeList" exact="[]"/>
      <set_value name="$searchMethod" exact="''"/>

      <!-- Priority 1: Use trade list from signal param2 (from cache search work unit or live search) -->
      <do_if value="this.$tradeListFromSignal? and this.$tradeListFromSignal.count gt 0">
        <set_value name="$tradeList" exact="this.$tradeListFromSignal"/>
        <set_value name="$searchMethod" exact="if this.$searchMethodFromSignal? and this.$searchMethodFromSignal != '' then this.$searchMethodFromSignal else 'signal'"/>
        <!-- Clear instance variables after use -->
        <remove_value name="this.$tradeListFromSignal"/>
        <remove_value name="this.$searchMethodFromSignal"/>
      </do_if>
      <do_else>
        <!-- Priority 2: Fallback to global storage (for threat intelligence compatibility) -->
        <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
          <set_value name="$tradeList" exact="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <set_value name="$searchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <do_if value="$searchMethod == ''">
            <set_value name="$searchMethod" exact="'global'"/>
          </do_if>
        </do_if>
      </do_else>

      <!-- Ensure it's a list -->
      <do_if value="typeof $tradeList != datatype.list">
        <!-- Backward compat: single trade stored as table -->
        <set_value name="$tradeList" exact="[$tradeList]"/>
      </do_if>

      <!-- Cache path: drop cargo-incompatible rows before validation (avoids FailedShips poisoning). -->
      <do_if value="$searchMethod == 'cache' and $tradeList? and $tradeList.count gt 0">
        <create_list name="$cargoFilteredTradeList"/>
        <do_all exact="$tradeList.count" counter="$cargoFilterIdx">
          <set_value name="$cargoFilterTrade" exact="$tradeList.{$cargoFilterIdx}"/>
          <set_value name="$cargoFilterWare" exact="if $cargoFilterTrade.$Ware? then $cargoFilterTrade.$Ware else (if $cargoFilterTrade.$BuyOffer? then @$cargoFilterTrade.$BuyOffer.ware else null)"/>
          <set_value name="$cargoFilterTransport" exact="if $cargoFilterTrade.$CargoWareTransport? then @$cargoFilterTrade.$CargoWareTransport else (if $cargoFilterWare? then @$cargoFilterWare.waretransport else null)"/>
          <set_value name="$cargoFilterOk" exact="false"/>
          <do_if value="$cargoFilterWare? and this.ship.cargo.{$cargoFilterWare}.max gt 0">
            <set_value name="$cargoFilterOk" exact="true"/>
          </do_if>
          <do_elseif value="$cargoFilterTransport? and this.ship.waretransport.indexof.{$cargoFilterTransport}">
            <set_value name="$cargoFilterOk" exact="true"/>
          </do_elseif>
          <do_if value="$cargoFilterOk">
            <append_to_list name="$cargoFilteredTradeList" exact="$cargoFilterTrade"/>
          </do_if>
        </do_all>
        <set_value name="$tradeList" exact="$cargoFilteredTradeList"/>
      </do_if>
      
      <!-- Use safe access for debug text -->
      <set_value name="$tradeListCountForDebug" exact="if $tradeList != null then $tradeList.count else 0"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Received ' + $tradeListCountForDebug + ' trades to validate (source: ' + (if $searchMethod == 'cache' then 'CACHE' else if $searchMethod == 'live' then 'LIVE' else if $searchMethod != '' then $searchMethod else 'UNKNOWN') + ')'" chance="100"/>
      </do_if>

      <!-- MK4-2 per-ship re-score at validation entry (scheduler cache/live both signal GT_Trade_Found).
           Inline run_search_pipeline scores before GT_Search_Done, but trade_found must re-apply for every
           GT_Trade_Found path and become the authoritative validation order (no selection_sort override). -->
      <set_value name="$mk42RescoreApplied" exact="false"/>
      <set_value name="$mk42StrictClassTier" exact="false"/>
      <do_if value="this.$mk42Priorities? and $tradeList? and $tradeList.count gt 0">
        <set_value name="$mk42RescoreSupplyList" exact="[]"/>
        <set_value name="$mk42RescoreHasSupply" exact="false"/>
        <do_all exact="$tradeList.count" counter="$mk42Ri">
          <set_value name="$mk42Rt" exact="$tradeList.{$mk42Ri}"/>
          <do_if value="not ($mk42Rt.$IsSellOnly? and $mk42Rt.$IsSellOnly)">
            <append_to_list name="$mk42RescoreSupplyList" exact="$mk42Rt"/>
            <set_value name="$mk42RescoreHasSupply" exact="true"/>
          </do_if>
        </do_all>
        <do_if value="$mk42RescoreHasSupply and $mk42RescoreSupplyList.count gt 0">
          <run_script name="'lib.gt.mk42.score.trades'" result="$mk42ValScoreResult">
            <param name="tradeList" value="$mk42RescoreSupplyList"/>
            <param name="priorities" value="this.$mk42Priorities"/>
            <param name="priorityWares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else []"/>
            <param name="priorityScoreMultiplier" value="if this.$effectivePriorityScoreMultiplier? then this.$effectivePriorityScoreMultiplier else 1"/>
            <param name="playerSupplierPriority" value="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else 5"/>
            <param name="aiSupplierPriority" value="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else 5"/>
            <param name="diversifyByWare" value="false"/>
            <param name="priorityFirstInDiversify" value="false"/>
            <param name="debugchance" value="@this.$debugchance"/>
          </run_script>
          <do_if value="$mk42ValScoreResult? and $mk42ValScoreResult.$SortedTrades? and $mk42ValScoreResult.$SortedTrades.count gt 0">
            <set_value name="$tradeList" exact="$mk42ValScoreResult.$SortedTrades"/>
            <set_value name="$mk42RescoreApplied" exact="true"/>
            <do_if value="$mk42ValScoreResult.$StrictClassTier? and @$mk42ValScoreResult.$StrictClassTier">
              <set_value name="$mk42StrictClassTier" exact="true"/>
            </do_if>
            <!-- Strict tier + dominant class absent from cache batch: force live search (ST-only stale cache). -->
            <do_if value="$searchMethod == 'cache' and $mk42StrictClassTier">
              <set_value name="$mk42CacheDominantTag" exact="if $mk42ValScoreResult.$DominantClassTag? then @$mk42ValScoreResult.$DominantClassTag else 'None'"/>
              <set_value name="$mk42CacheHasDominant" exact="false"/>
              <do_if value="$mk42CacheDominantTag != 'None'">
                <do_all exact="$tradeList.count" counter="$mk42Cdi">
                  <set_value name="$mk42CdTrade" exact="$tradeList.{$mk42Cdi}"/>
                  <do_if value="$mk42CdTrade.$CustomerClass? and @$mk42CdTrade.$CustomerClass == $mk42CacheDominantTag">
                    <set_value name="$mk42CacheHasDominant" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$mk42CacheDominantTag != 'None' and not $mk42CacheHasDominant">
                <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': cache rejected at validation (strict tier dominant=' + $mk42CacheDominantTag + ' absent in ' + $tradeList.count + ' entries) - forcing live search'" chance="100"/>
                <set_value name="this.$mk42PolicyNeedsLiveSearch" exact="true"/>
                <set_value name="this.$lastNoTradeReason" exact="'cache_strict_tier_miss'"/>
                <resume label="no_trade_retry"/>
              </do_if>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MK4-Supply] ' + this.ship.idcode + ': validation re-score applied sorted=' + $tradeList.count + ' strictTier=' + $mk42StrictClassTier + ' source=' + $searchMethod" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Cap extra cache-detail logs to avoid spam -->
      <set_value name="$cacheDetailLogMax" exact="8"/>
      <set_value name="$cacheDetailLogCount" exact="0"/>
      
      <!-- gatedistance memoization: cache results per (fromSector, toSector) to avoid
           redundant C++ pathfinding calls when multiple trades share the same sectors.
           Separate tables for non-blacklist vs blacklist-aware variants.
           Valid for the duration of this validation loop (ship doesn't move). -->
      <set_value name="$gdCache" exact="table[]"/>
      <set_value name="$gdCacheBL" exact="table[]"/>
      
      <!-- Resolve enforcement flags once before loop (MD-stored AI parameters override order params) -->
      <set_value name="$enfIgnoreBuildStorage" exact="$effectiveIgnoreBuildStorage"/>
      <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}? and global.$GT_AIParameters.{this.ship}.$IgnoreBuildStorage?">
        <set_value name="$enfIgnoreBuildStorage" exact="global.$GT_AIParameters.{this.ship}.$IgnoreBuildStorage"/>
      </do_if>
      <set_value name="$enfIgnoreCarrierAux" exact="$effectiveIgnoreCarrierAux"/>
      <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{this.ship}? and global.$GT_AIParameters.{this.ship}.$IgnoreCarrierAux?">
        <set_value name="$enfIgnoreCarrierAux" exact="global.$GT_AIParameters.{this.ship}.$IgnoreCarrierAux"/>
      </do_if>

      <!-- Resolve MK3 faction blacklist once for this validation pass (commander for subordinates). -->
      <set_value name="$mk3BlacklistOwnerLoop" exact="this.ship"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
        <set_value name="$mk3BlacklistOwnerLoop" exact="this.ship.commander"/>
      </do_if>
      <set_value name="$mk3FactionBlacklistLoop" exact="table[]"/>
      <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerLoop}?">
        <set_value name="$mk3FactionBlacklistLoop" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerLoop}"/>
      </do_if>
      
      <!-- Priority-first reorder: when priority wares are set, put priority-ware trades at the front.
           Score multiplier alone cannot overcome large profit gaps (e.g. 238k Cr vs 2k Cr).
           This guarantees priority wares are tried first during validation. -->
      <!-- Resolved via lib.gt.priority_wares.resolve: walks instance -> local -> commander.defaultorder
           (or commander.defaultorder.$baseorder via Assist) once and returns [] when no source has wares.
           Replaces the prior 1.5KB nested ternary at this site (see DOCS/MK3_PIPELINE_REFACTOR.md Â§3.8). -->
      <run_script name="'lib.gt.priority_wares.resolve'" result="$pwForReorder">
        <param name="instanceWares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else null"/>
        <param name="localWares" value="if $effectivePriorityWares? then $effectivePriorityWares else null"/>
        <param name="ship" value="this.ship"/>
        <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply2']"/>
      </run_script>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList? and $tradeList.count gt 0">
        <do_if value="not $pwForReorder? or $pwForReorder.count == 0">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder SKIPPED: no priority wares (this.$effectivePriorityWares=' + (if this.$effectivePriorityWares? then this.$effectivePriorityWares.count else '?') + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_if value="$pwForReorder? and $pwForReorder.count gt 0 and $tradeList? and $tradeList.count gt 0">
        <create_list name="$priorityTrades"/>
        <create_list name="$nonPriorityTrades"/>
        <do_all exact="$tradeList.count" counter="$ti">
          <set_value name="$t" exact="$tradeList.{$ti}"/>
          <set_value name="$tWare" exact="if $t.$Ware? then $t.$Ware else (if $t.$BuyOffer? then @$t.$BuyOffer.ware else null)"/>
          <set_value name="$isPriority" exact="false"/>
          <do_if value="$tWare?">
            <do_all exact="$pwForReorder.count" counter="$pwi">
              <set_value name="$pwItem" exact="$pwForReorder.{$pwi}"/>
              <!-- Compare by identity first; fallback to .id if references differ (e.g. across save/load) -->
              <do_if value="$pwItem == $tWare or ($pwItem? and $tWare? and $pwItem.id? and $tWare.id? and $pwItem.id == $tWare.id)">
                <set_value name="$isPriority" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$isPriority">
            <append_to_list name="$priorityTrades" exact="$t"/>
          </do_if>
          <do_else>
            <append_to_list name="$nonPriorityTrades" exact="$t"/>
          </do_else>
        </do_all>
        <run_script name="'lib.gt.score.selection_sort'" result="$prioSelectionSort">
          <param name="tradeList" value="$priorityTrades"/>
          <param name="ship" value="this.ship"/>
          <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        </run_script>
        <do_if value="$prioSelectionSort? and $prioSelectionSort.$SortedTrades?">
          <set_value name="$priorityTrades" exact="$prioSelectionSort.$SortedTrades"/>
        </do_if>
        <run_script name="'lib.gt.score.selection_sort'" result="$nonPrioSelectionSort">
          <param name="tradeList" value="$nonPriorityTrades"/>
          <param name="ship" value="this.ship"/>
          <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
        </run_script>
        <do_if value="$nonPrioSelectionSort? and $nonPrioSelectionSort.$SortedTrades?">
          <set_value name="$nonPriorityTrades" exact="$nonPrioSelectionSort.$SortedTrades"/>
        </do_if>
        <create_list name="$reorderedList"/>
        <do_all exact="$priorityTrades.count" counter="$pi">
          <append_to_list name="$reorderedList" exact="$priorityTrades.{$pi}"/>
        </do_all>
        <do_all exact="$nonPriorityTrades.count" counter="$ni">
          <append_to_list name="$reorderedList" exact="$nonPriorityTrades.{$ni}"/>
        </do_all>
        <set_value name="$tradeList" exact="$reorderedList"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <do_if value="$priorityTrades.count gt 0">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder: ' + $priorityTrades.count + ' priority-ware trades moved to front of ' + $tradeList.count + ' (validation will try priority wares first)'" chance="100"/>
          </do_if>
          <do_else>
            <!-- Diagnostic: priority wares configured but no matching trades found -->
            <set_value name="$pwDiagNames" exact="''"/>
            <do_all exact="[$pwForReorder.count, 3].min" counter="$pdi">
              <set_value name="$pwDiagNames" exact="$pwDiagNames + (if $pdi gt 1 then ', ' else '') + (if $pwForReorder.{$pdi}? and $pwForReorder.{$pdi} != null then @$pwForReorder.{$pdi}.name else '?')"/>
            </do_all>
            <set_value name="$tDiagNames" exact="''"/>
            <do_all exact="[3, $tradeList.count].min" counter="$tdi">
              <set_value name="$td" exact="$tradeList.{$tdi}"/>
              <set_value name="$tdw" exact="if $td.$Ware? then $td.$Ware else (if $td.$BuyOffer? then @$td.$BuyOffer.ware else null)"/>
              <set_value name="$tDiagNames" exact="$tDiagNames + (if $tdi gt 1 then ', ' else '') + (if $tdw? and $tdw != null then @$tdw.name else '?')"/>
            </do_all>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder: 0 priority-ware trades in ' + $tradeList.count + ' (priority wares: [' + $pwDiagNames + '], first trades: [' + $tDiagNames + '])'" chance="100"/>
          </do_else>
        </do_if>
      </do_if>
      <do_else>
        <!-- Diagnostic: reorder skipped because priority wares not available (e.g. not persisted after interrupt) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $tradeList? and $tradeList.count gt 0 and (not $pwForReorder? or $pwForReorder.count == 0)">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Priority-first reorder SKIPPED: no priority wares (this.$effectivePriorityWares=' + (if this.$effectivePriorityWares? then this.$effectivePriorityWares.count else 'null') + ')'" chance="100"/>
        </do_if>
      </do_else>

      <!-- Per-ship selection score sort when priority-first reorder did not run (MK3 legacy path).
           Skip when MK4-2 score.trades already established validation order. -->
      <do_if value="not $mk42RescoreApplied and not ($pwForReorder? and $pwForReorder.count gt 0 and $tradeList? and $tradeList.count gt 0)">
        <do_if value="$tradeList? and $tradeList.count gt 0">
          <run_script name="'lib.gt.score.selection_sort'" result="$fullSelectionSort">
            <param name="tradeList" value="$tradeList"/>
            <param name="ship" value="this.ship"/>
            <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          </run_script>
          <do_if value="$fullSelectionSort? and $fullSelectionSort.$SortedTrades?">
            <set_value name="$tradeList" exact="$fullSelectionSort.$SortedTrades"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Single-trip player completion-first reorder (MK4 auto-wares):
           Player delivery targets whose remaining need fits in one load are validated before
           build-storage routes and broad scored trades. Within the bucket, smallest deficit first.
           Disabled when strict class tier is active (sliders own validation order). -->
      <do_if value="not $mk42StrictClassTier and $tradeList? and $tradeList.count gt 1">
        <create_list name="$mk4CompletionFirstTrades"/>
        <create_list name="$mk4CompletionRestTrades"/>
        <set_value name="$mk4CfShipFreeVol" exact="this.ship.cargo.free.all"/>
        <do_all exact="$tradeList.count" counter="$mk4Cfi">
          <set_value name="$mk4CfTrade" exact="$tradeList.{$mk4Cfi}"/>
          <set_value name="$mk4CfSellStation" exact="null"/>
          <set_value name="$mk4CfWare" exact="null"/>
          <do_if value="$mk4CfTrade.$SellStation?">
            <set_value name="$mk4CfSellStation" exact="$mk4CfTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$mk4CfTrade.$SellOffer? and $mk4CfTrade.$SellOffer.owner?">
            <set_value name="$mk4CfSellStation" exact="$mk4CfTrade.$SellOffer.owner"/>
          </do_elseif>
          <do_if value="$mk4CfTrade.$Ware?">
            <set_value name="$mk4CfWare" exact="$mk4CfTrade.$Ware"/>
          </do_if>
          <do_elseif value="$mk4CfTrade.$SellOffer? and $mk4CfTrade.$SellOffer.ware?">
            <set_value name="$mk4CfWare" exact="$mk4CfTrade.$SellOffer.ware"/>
          </do_elseif>
          <set_value name="$mk4CfIsCompletion" exact="false"/>
          <do_if value="$mk4CfSellStation? and $mk4CfSellStation.exists and $mk4CfSellStation.isplayerowned and not $mk4CfSellStation.isclass.buildstorage and $mk4CfWare?">
            <set_value name="$mk4CfTarget" exact="$mk4CfSellStation.cargo.{$mk4CfWare}.target"/>
            <do_if value="$mk4CfTarget gt 0">
              <set_value name="$mk4CfDeficit" exact="[$mk4CfTarget - $mk4CfSellStation.cargo.{$mk4CfWare}.count, 0].max"/>
              <set_value name="$mk4CfVolPerUnit" exact="if $mk4CfWare.volume? and $mk4CfWare.volume gt 0 then $mk4CfWare.volume else 1"/>
              <set_value name="$mk4CfOneTripUnits" exact="($mk4CfShipFreeVol / $mk4CfVolPerUnit)i"/>
              <do_if value="$mk4CfDeficit gt 0 and $mk4CfOneTripUnits gt 0 and $mk4CfDeficit le $mk4CfOneTripUnits">
                <set_value name="$mk4CfIsCompletion" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
          <do_if value="$mk4CfIsCompletion">
            <append_to_list name="$mk4CompletionFirstTrades" exact="$mk4CfTrade"/>
          </do_if>
          <do_else>
            <append_to_list name="$mk4CompletionRestTrades" exact="$mk4CfTrade"/>
          </do_else>
        </do_all>
        <do_if value="$mk4CompletionFirstTrades.count gt 0">
          <create_list name="$mk4CompletionOrdered"/>
          <set_value name="$mk4CfPicked" exact="table[]"/>
          <do_all exact="$mk4CompletionFirstTrades.count" counter="$mk4CfPass">
            <set_value name="$mk4CfBestIdx" exact="0"/>
            <set_value name="$mk4CfBestDeficit" exact="999999999"/>
            <do_all exact="$mk4CompletionFirstTrades.count" counter="$mk4CfIdx">
              <do_if value="not $mk4CfPicked.{$mk4CfIdx}?">
                <set_value name="$mk4CfCand" exact="$mk4CompletionFirstTrades.{$mk4CfIdx}"/>
                <set_value name="$mk4CfCandStation" exact="if $mk4CfCand.$SellStation? then $mk4CfCand.$SellStation else (if $mk4CfCand.$SellOffer? and $mk4CfCand.$SellOffer.owner? then $mk4CfCand.$SellOffer.owner else null)"/>
                <set_value name="$mk4CfCandWare" exact="if $mk4CfCand.$Ware? then $mk4CfCand.$Ware else (if $mk4CfCand.$SellOffer? and $mk4CfCand.$SellOffer.ware? then $mk4CfCand.$SellOffer.ware else null)"/>
                <set_value name="$mk4CfCandDeficit" exact="999999999"/>
                <do_if value="$mk4CfCandStation? and $mk4CfCandStation.exists and $mk4CfCandWare?">
                  <set_value name="$mk4CfCandTarget" exact="$mk4CfCandStation.cargo.{$mk4CfCandWare}.target"/>
                  <do_if value="$mk4CfCandTarget gt 0">
                    <set_value name="$mk4CfCandDeficit" exact="[$mk4CfCandTarget - $mk4CfCandStation.cargo.{$mk4CfCandWare}.count, 0].max"/>
                  </do_if>
                </do_if>
                <do_if value="$mk4CfCandDeficit lt $mk4CfBestDeficit">
                  <set_value name="$mk4CfBestDeficit" exact="$mk4CfCandDeficit"/>
                  <set_value name="$mk4CfBestIdx" exact="$mk4CfIdx"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$mk4CfBestIdx gt 0">
              <append_to_list name="$mk4CompletionOrdered" exact="$mk4CompletionFirstTrades.{$mk4CfBestIdx}"/>
              <set_value name="$mk4CfPicked.{$mk4CfBestIdx}" exact="true"/>
            </do_if>
          </do_all>
          <create_list name="$mk4CompletionMerged"/>
          <do_all exact="$mk4CompletionOrdered.count" counter="$mk4CfOut">
            <append_to_list name="$mk4CompletionMerged" exact="$mk4CompletionOrdered.{$mk4CfOut}"/>
          </do_all>
          <do_all exact="$mk4CompletionRestTrades.count" counter="$mk4CfRest">
            <append_to_list name="$mk4CompletionMerged" exact="$mk4CompletionRestTrades.{$mk4CfRest}"/>
          </do_all>
          <set_value name="$tradeList" exact="$mk4CompletionMerged"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Completion-first reorder: ' + $mk4CompletionFirstTrades.count + ' single-trip player deliveries moved before ' + $mk4CompletionRestTrades.count + ' other trades (smallest deficit first)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>

      <!-- Validation order: score.trades $SortedTrades (normBase x class slider). Sliders >0 bias score only; 0 hard-excludes at search/pair. -->
      
      <!-- Iterate through trade list -->
      <!-- Check if tradeList exists and has items before looping -->
      <do_if value="(if $tradeList != null then $tradeList.count else 0) gt 0">
        <!-- Full validation sweep:
             validate all generated candidates each cycle (no top-N truncation).
             This mirrors MK1's "evaluate complete candidate set" behavior and avoids
             starving lower-ranked but still valid trades when early entries fail. -->
        <set_value name="$validationTradeLimit" exact="$tradeList.count"/>
        <set_value name="$validatedCandidateLimit" exact="if this.$effectiveMaxTrades? and this.$effectiveMaxTrades gt 0 then this.$effectiveMaxTrades else 1"/>
        <set_value name="this.$gt_dockMemo" exact="table[]"/>
        <do_all exact="$validationTradeLimit" counter="$tradeIdx">
          <set_value name="$currentTrade" exact="$tradeList.{$tradeIdx}"/>
          <set_value name="$tradesChecked" operation="add"/>
          
          <!-- Check if currentTrade is valid before processing -->
          <do_if value="$currentTrade? and $currentTrade != null">
              <!-- Extract stations from trade (handle both new list format and old single-trade format) -->
              <!-- Initialize stations to null first, then extract -->
              <set_value name="$buyStation" exact="null"/>
              <set_value name="$sellStation" exact="null"/>
              
              <!-- Check if this is a sell-only trade first -->
              <set_value name="$isSellOnlyTrade" exact="false"/>
              <do_if value="$currentTrade.$IsSellOnly? and $currentTrade.$IsSellOnly">
                <set_value name="$isSellOnlyTrade" exact="true"/>
              </do_if>
              
              <!-- Extract buy station (may be null for sell-only trades) -->
              <do_if value="$currentTrade.$BuyStation?">
                <set_value name="$buyStation" exact="$currentTrade.$BuyStation"/>
              </do_if>
              <do_else>
                <do_if value="$currentTrade.$BuyOffer?">
                  <do_if value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                    <set_value name="$buyStation" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer.owner?">
                    <set_value name="$buyStation" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_else>
              
              <!-- Extract sell station (always required): prefer buy-offer buyer (vanilla trade perform / build storage). -->
              <do_if value="$currentTrade.$SellStation?">
                <set_value name="$sellStation" exact="$currentTrade.$SellStation"/>
              </do_if>
              <do_else>
                <do_if value="$currentTrade.$SellOffer?">
                  <do_if value="$currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists">
                    <set_value name="$sellStation" exact="@$currentTrade.$SellOffer.buyer"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$SellOffer.owner?">
                    <set_value name="$sellStation" exact="@$currentTrade.$SellOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_else>
              
              <!-- For sell-only trades, only require sellStation; for normal trades, require both -->
              <do_if value="$isSellOnlyTrade">
                <!-- Sell-only trade: only sellStation required -->
                <do_if value="$sellStation? and $sellStation != null">
                  <!-- Use safe access for tradeIdx in debug text -->
                  <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                  <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validating SELL-ONLY trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ': ' + (if $currentTrade.$Ware? then @$currentTrade.$Ware.name else 'Unknown') + ' (Ship cargo â†’ ' + (if $sellStation? then @$sellStation.knownname else 'Unknown') + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Check docking permissions FIRST (most common failure, cheapest check) -->
                  <!-- Skip buy-station checks for sell-only trades (ship already has cargo) -->
                  <!-- Also check if BuyStation is not a station (could be ship for sell-only trades) -->
                  <set_value name="$buyStationIsStation" exact="false"/>
                  <do_if value="$buyStation?">
                    <set_value name="$buyStationIsStation" exact="@$buyStation.isclass.station"/>
                  </do_if>
                  
                  <!-- Only check buy-station docking if it's NOT a sell-only trade (always true for sell-only) -->
                  <set_value name="$canDockAtBuyStation" exact="true"/>
                  
                  <!-- Delivery dock: trading dock on destination (build storage object when applicable). -->
                  <run_script name="'lib.gt.dockcheck'" result="$mk4SellOnlyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtSellStation" exact="$mk4SellOnlyDockResult.$CanDock"/>
        
                <do_if value="not $canDockAtBuyStation or not $canDockAtSellStation">
                  <!-- DOCKING NOT ALLOWED - Skip to next trade -->
                  <set_value name="$tradesRejectedDocking" operation="add"/>
                  <set_value name="$deniedStation" exact="if not $canDockAtBuyStation then $buyStation else $sellStation"/>
                  <set_value name="$deniedType" exact="if not $canDockAtBuyStation then 'BUY' else 'SELL'"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' DOCKING DENIED:' +
                      '\n  Station: ' + @$deniedStation.knownname + 
                      '\n  Sector: ' + @$deniedStation.sector.knownname + 
                      '\n  Type: ' + $deniedType + 
                      '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>

                    <!-- Extra cache-only detail (capped): log dock probe on denied station -->
                    <do_if value="$searchMethod == 'cache' and $cacheDetailLogCount lt $cacheDetailLogMax">
                      <set_value name="$cacheDetailLogCount" operation="add"/>
                      <set_value name="$dockAllowedBuyText" exact="if $canDockAtBuyStation? then $canDockAtBuyStation else 'null'"/>
                      <set_value name="$dockAllowedSellText" exact="if $canDockAtSellStation? then $canDockAtSellStation else 'null'"/>
                      <set_value name="$sellOfferId" exact="null"/>
                      <do_if value="$currentTrade.$SellOffer?">
                        <set_value name="$sellOfferId" exact="@$currentTrade.$SellOffer.id"/>
                      </do_if>
                      <set_value name="$cacheDeniedDockFound" exact="false"/>
                      <find_dockingbay name="$cacheDeniedDockBay" object="$deniedStation" checkoperational="true" multiple="false">
                        <match_dock size="this.ship.docksize" trading="true" storage="false"/>
                        <match_relation_to object="this.ship" comparison="not" relation="enemy"/>
                      </find_dockingbay>
                      <do_if value="$cacheDeniedDockBay">
                        <set_value name="$cacheDeniedDockFound" exact="true"/>
                      </do_if>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': [CACHE-DETAIL] DockingDenied trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe +
                        '\n  DeniedType: ' + $deniedType +
                        '\n  CanDock BUY=' + $dockAllowedBuyText + ' SELL=' + $dockAllowedSellText +
                        '\n  ShipDocksize: ' + this.ship.docksize +
                        '\n  SellOfferId: ' + (if $sellOfferId? and $sellOfferId != null then $sellOfferId else 'null') +
                        '\n  find_dockingbay(trading) on denied station: ' + (if $cacheDeniedDockFound then 'YES' else 'NO')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Scenario 3: Flag ship-specific docking failure on cache entry -->
                  <do_if value="$searchMethod == 'cache'">
                    <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'docking_denied']"/>
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- Use cached blacklistgroup from init -->
                <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                
                <!-- Resolve sector whitelist for blacklist checks (whitelist overrides blacklist, matches GT_IsSectorBlacklisted) -->
                <set_value name="$validationWhitelist" exact="[]"/>
                <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                  <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
                </do_if>
                
                <!-- Check path reachability BEFORE blacklist (faster to fail on unreachable) -->
                <!-- For sell-only trades, skip buy-station pathfinding (ship already has cargo) -->
                <set_value name="$currentSector" exact="this.ship.sector"/>
                <!-- For sell-only trades, buySector is current sector (ship already has cargo) -->
                <set_value name="$buySector" exact="$currentSector"/>
                <do_if value="not $isSellOnlyTrade and $buyStation?">
                  <set_value name="$buySector" exact="$buyStation.sector"/>
                </do_if>
                <set_value name="$sellSector" exact="$sellStation.sector"/>
                
                <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
                <set_value name="$currentSectorIsBlacklisted" exact="false"/>
                <do_if value="$blacklistgroup?">
                  <set_value name="$currentSectorWhitelisted" exact="false"/>
                  <do_if value="$validationWhitelist.count gt 0">
                    <do_all exact="$validationWhitelist.count" counter="$swIdx">
                      <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                        <set_value name="$currentSectorWhitelisted" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  <do_if value="not $currentSectorWhitelisted">
                    <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                    <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                    <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                  </do_if>
                </do_if>
        
        <!-- Calculate path distances with escape support -->
        <!-- Buy path calculation with escape support -->
        <!-- For sell-only trades, buy distance is always 0 (ship already has cargo, no buy travel needed) -->
        <set_value name="$buyDistance" exact="-1"/>
        <do_if value="$isSellOnlyTrade">
          <set_value name="$buyDistance" exact="0"/>
        </do_if>
        <do_elseif value="$buySector == $currentSector">
          <set_value name="$buyDistance" exact="0"/>
        </do_elseif>
        <do_elseif value="$currentSectorIsBlacklisted">
          <!-- Escape: non-blacklist gatedistance (memoized) -->
          <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$buySector}?">
            <set_value name="$buyDistance" exact="$gdCache.{$currentSector}.{$buySector}"/>
          </do_if>
          <do_else>
            <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}"/>
            <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
            <set_value name="$gdCache.{$currentSector}.{$buySector}" exact="$buyDistance"/>
          </do_else>
        </do_elseif>
        <do_else>
          <!-- Normal: blacklist-aware gatedistance (memoized) -->
          <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$buySector}?">
            <set_value name="$buyDistance" exact="$gdCacheBL.{$currentSector}.{$buySector}"/>
          </do_if>
          <do_else>
            <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}.{$blacklistgroup}.{this.ship}"/>
            <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
            <set_value name="$gdCacheBL.{$currentSector}.{$buySector}" exact="$buyDistance"/>
          </do_else>
        </do_else>
        
        <!-- Sell path: Calculate based on buy location -->
        <set_value name="$sellDistance" exact="-1"/>
        <do_if value="$sellSector == $buySector">
          <set_value name="$sellDistance" exact="0"/>
        </do_if>
        <do_elseif value="$buySector == $currentSector">
          <!-- Ship in buy sector: escape vs normal path to sell sector -->
          <do_if value="$currentSectorIsBlacklisted">
            <!-- Escape: non-blacklist gatedistance (memoized) -->
            <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$sellSector}?">
              <set_value name="$sellDistance" exact="$gdCache.{$currentSector}.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}"/>
              <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
              <set_value name="$gdCache.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
            </do_else>
          </do_if>
          <do_else>
            <!-- Normal: blacklist-aware gatedistance (memoized) -->
            <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$sellSector}?">
              <set_value name="$sellDistance" exact="$gdCacheBL.{$currentSector}.{$sellSector}"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
              <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
              <set_value name="$gdCacheBL.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
            </do_else>
          </do_else>
        </do_elseif>
        <do_else>
          <!-- Normal: buyâ†’sell blacklist-aware gatedistance (memoized) -->
          <do_if value="$gdCacheBL.{$buySector}? and $gdCacheBL.{$buySector}.{$sellSector}?">
            <set_value name="$sellDistance" exact="$gdCacheBL.{$buySector}.{$sellSector}"/>
          </do_if>
          <do_else>
            <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
            <do_if value="not $gdCacheBL.{$buySector}?"><set_value name="$gdCacheBL.{$buySector}" exact="table[]"/></do_if>
            <set_value name="$gdCacheBL.{$buySector}.{$sellSector}" exact="$sellDistance"/>
          </do_else>
        </do_else>
        
        <!-- Always log distance check to diagnose issues -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
          <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PATH check (blacklist-aware):' +
            '\n  Current sector: ' + @$currentSector.knownname +
            '\n  BUY: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance: ' + $buyDistance + ')' +
            '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance: ' + $sellDistance + ')' +
            '\n  Blacklist group: ' + $blacklistgroup +
            '\n  Result: ' + (if ($buyDistance lt 0 and not $isSellOnlyTrade) or $sellDistance lt 0 then 'BLOCKED' else 'OK')" 
            chance="100"/>
        </do_if>
        
        <!-- For sell-only trades, only check sell path (buy path is always 0) -->
        <set_value name="$pathBlocked" exact="false"/>
        <do_if value="not $isSellOnlyTrade">
          <do_if value="$buyDistance lt 0">
            <set_value name="$pathBlocked" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$sellDistance lt 0">
          <set_value name="$pathBlocked" exact="true"/>
        </do_if>
        
        <do_if value="$pathBlocked">
          <!-- PATH BLOCKED - Skip to next trade -->
          <set_value name="$tradesRejectedPath" operation="add"/>
          <set_value name="$unreachableStation" exact="if ($buyDistance lt 0 and not $isSellOnlyTrade) then $buyStation else $sellStation"/>
          <set_value name="$unreachableType" exact="if ($buyDistance lt 0 and not $isSellOnlyTrade) then 'BUY' else 'SELL'"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' PATH BLOCKED:' +
              '\n  Station: ' + @$unreachableStation.knownname + 
              '\n  Type: ' + $unreachableType + 
              '\n  Reason: No path exists (disconnected sectors, war, or gates destroyed)' + 
              '\n  â†’ Trying next trade in list...'" 
              chance="100"/>
          </do_if>
          
          <!-- Scenario 3: Flag ship-specific path failure on cache entry -->
          <do_if value="$searchMethod == 'cache'">
            <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'path_blocked']"/>
          </do_if>
          
          <!-- Continue to next trade in list -->
          <continue/>
        </do_if>
              </do_if>
              <do_else>
                <!-- Sell-only trade missing sellStation - skip this trade -->
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' MISSING SELL STATION (sell-only trade requires sellStation)'" chance="100"/>
                <continue/>
              </do_else>
            </do_if>
            <do_else>
                <!-- Normal trade: require both buyStation and sellStation -->
                <do_if value="$buyStation? and $buyStation != null and $sellStation? and $sellStation != null">
                  <!-- Normal trade validation continues here - same as before but with buy checks -->
                  <!-- Use safe access for tradeIdx in debug text -->
                  <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                  <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validating trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ': ' + (if $currentTrade.$BuyOffer? then @$currentTrade.$BuyOffer.ware.name else 'Unknown') + ' (' + (if $buyStation? then @$buyStation.knownname else 'Unknown') + ' â†’ ' + (if $sellStation? then @$sellStation.knownname else 'Unknown') + ')'" chance="100"/>
                  </do_if>

                  <!-- MK4 hard policy: always deliver to player-owned stations -->
                  <do_if value="not @$sellStation.isplayerowned">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <continue/>
                  </do_if>

                  <!-- MK4-2 class-at-0 gate (validation-time). Root cause: cache.write stamps the
                       delivery class while the build-storage offer is fresh, but build-storage offers
                       churn; by validation time the trade can re-resolve to the base station, so a
                       cached Buildstorage entry is queued as a Stations delivery even when the player
                       set that class slider to 0 (observed: ODE-762 -> 'Asteroid Belt Wharf I' with
                       priorityStations=0). Re-classify the LIVE sell station here and skip the trade
                       when its class priority is 0. Mirrors the classify precedence in
                       lib.gt.mk42.classify / tradematch. Build-storage deliveries (the common case)
                       keep their Buildstorage class and pass. -->
                  <do_if value="this.$mk42Priorities?">
                    <run_script name="'lib.gt.mk42.classify'" result="$valDelivCls">
                      <param name="customer" value="$sellStation"/>
                      <param name="priorities" value="this.$mk42Priorities"/>
                      <param name="mode" value="'both'"/>
                    </run_script>
                    <do_if value="$valDelivCls? and $valDelivCls != null and not @$valDelivCls.$Eligible">
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” delivery class ' + (if $valDelivCls.$Class? then $valDelivCls.$Class else 'None') + ' is disabled (priority 0): ' + @$sellStation.knownname" chance="100"/>
                      </do_if>
                      <set_value name="$tradesRejectedRestriction" operation="add"/>
                      <continue/>
                    </do_if>
                  </do_if>

                  <!-- MK4 supplier policy -->
                  <set_value name="$valMk4AISupLive" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
                  <set_value name="$valMk4PlSupLive" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
                  <set_value name="$mk4SupplierStationLive" exact="null"/>
                  <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                    <set_value name="$mk4SupplierStationLive" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.owner? and @$currentTrade.$BuyOffer.owner.exists">
                    <set_value name="$mk4SupplierStationLive" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_elseif>
                  <do_if value="not $valMk4PlSupLive and $mk4SupplierStationLive? and @$mk4SupplierStationLive.isplayerowned">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <continue/>
                  </do_if>
                  <do_if value="not $valMk4AISupLive">
                    <do_if value="not $mk4SupplierStationLive? or not @$mk4SupplierStationLive.isplayerowned">
                      <set_value name="$tradesRejectedRestriction" operation="add"/>
                      <continue/>
                    </do_if>
                  </do_if>
                  
                  <!-- Check docking FIRST (most common failure): lib.gt.dockcheck purpose=trade. -->
                  <run_script name="'lib.gt.dockcheck'" result="$mk4BuyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$buyStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtBuyStation" exact="$mk4BuyDockResult.$CanDock"/>
                  <run_script name="'lib.gt.dockcheck'" result="$mk4SellDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <set_value name="$canDockAtSellStation" exact="$mk4SellDockResult.$CanDock"/>
                  
                  <do_if value="not $canDockAtBuyStation or not $canDockAtSellStation">
                    <!-- DOCKING NOT ALLOWED - Skip to next trade -->
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <set_value name="$deniedStation" exact="if not $canDockAtBuyStation then $buyStation else $sellStation"/>
                    <set_value name="$deniedType" exact="if not $canDockAtBuyStation then 'BUY' else 'SELL'"/>
                    
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' DOCKING DENIED:' +
                      '\n  Station: ' + @$deniedStation.knownname + 
                      '\n  Sector: ' + @$deniedStation.sector.knownname + 
                      '\n  Type: ' + $deniedType + 
                      '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>

                    <!-- Extra cache-only detail (capped): log dock probe on denied station -->
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $searchMethod == 'cache' and $cacheDetailLogCount lt $cacheDetailLogMax">
                      <set_value name="$cacheDetailLogCount" operation="add"/>
                      <set_value name="$dockAllowedBuyText" exact="if $canDockAtBuyStation? then $canDockAtBuyStation else 'null'"/>
                      <set_value name="$dockAllowedSellText" exact="if $canDockAtSellStation? then $canDockAtSellStation else 'null'"/>
                      <set_value name="$buyOfferId" exact="null"/>
                      <set_value name="$sellOfferId" exact="null"/>
                      <do_if value="$currentTrade.$BuyOffer?">
                        <set_value name="$buyOfferId" exact="@$currentTrade.$BuyOffer.id"/>
                      </do_if>
                      <do_if value="$currentTrade.$SellOffer?">
                        <set_value name="$sellOfferId" exact="@$currentTrade.$SellOffer.id"/>
                      </do_if>
                      <set_value name="$cacheDeniedDockFound" exact="false"/>
                      <find_dockingbay name="$cacheDeniedDockBay" object="$deniedStation" checkoperational="true" multiple="false">
                        <match_dock size="this.ship.docksize" trading="true" storage="false"/>
                        <match_relation_to object="this.ship" comparison="not" relation="enemy"/>
                      </find_dockingbay>
                      <do_if value="$cacheDeniedDockBay">
                        <set_value name="$cacheDeniedDockFound" exact="true"/>
                      </do_if>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': [CACHE-DETAIL] DockingDenied trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe +
                        '\n  DeniedType: ' + $deniedType +
                        '\n  CanDock BUY=' + $dockAllowedBuyText + ' SELL=' + $dockAllowedSellText +
                        '\n  ShipDocksize: ' + this.ship.docksize +
                        '\n  BuyOfferId: ' + (if $buyOfferId? and $buyOfferId != null then $buyOfferId else 'null') +
                        '\n  SellOfferId: ' + (if $sellOfferId? and $sellOfferId != null then $sellOfferId else 'null') +
                        '\n  find_dockingbay(trading) on denied station: ' + (if $cacheDeniedDockFound then 'YES' else 'NO')"
                        chance="100"/>
                    </do_if>
                    
                    <!-- Scenario 3: Flag ship-specific docking failure on cache entry -->
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'docking_denied']"/>
                    </do_if>
                    
                    <!-- Continue to next trade in list -->
                    <continue/>
                  </do_if>
                  
                  <!-- Use cached blacklistgroup from init -->
                  <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                  
                  <!-- Resolve sector whitelist for blacklist checks (whitelist overrides blacklist, matches GT_IsSectorBlacklisted) -->
                  <set_value name="$validationWhitelist" exact="[]"/>
                  <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
                    <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
                  </do_if>
                  
                  <!-- Check path reachability BEFORE blacklist (faster to fail on unreachable) -->
                  <set_value name="$currentSector" exact="this.ship.sector"/>
                  <set_value name="$buySector" exact="$buyStation.sector"/>
                  <set_value name="$sellSector" exact="$sellStation.sector"/>
                  
                  <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
                  <set_value name="$currentSectorIsBlacklisted" exact="false"/>
                  <do_if value="$blacklistgroup?">
                    <set_value name="$currentSectorWhitelisted" exact="false"/>
                    <do_if value="$validationWhitelist.count gt 0">
                      <do_all exact="$validationWhitelist.count" counter="$swIdx">
                        <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                          <set_value name="$currentSectorWhitelisted" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    <do_if value="not $currentSectorWhitelisted">
                      <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                      <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                      <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Calculate path distances with escape support -->
                  <!-- Buy path calculation with escape support -->
                  <!-- Buy path: If ship is already in buy sector, distance is 0 (no travel needed) -->
                  <set_value name="$buyDistance" exact="-1"/>
                  <do_if value="$buySector == $currentSector">
                    <set_value name="$buyDistance" exact="0"/>
                  </do_if>
                  <do_elseif value="$currentSectorIsBlacklisted">
                    <!-- Escape: non-blacklist gatedistance (memoized) -->
                    <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$buySector}?">
                      <set_value name="$buyDistance" exact="$gdCache.{$currentSector}.{$buySector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}"/>
                      <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
                      <set_value name="$gdCache.{$currentSector}.{$buySector}" exact="$buyDistance"/>
                    </do_else>
                  </do_elseif>
                  <do_else>
                    <!-- Normal: blacklist-aware gatedistance (memoized) -->
                    <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$buySector}?">
                      <set_value name="$buyDistance" exact="$gdCacheBL.{$currentSector}.{$buySector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$buyDistance" exact="this.ship.gatedistance.{$buySector}.{$blacklistgroup}.{this.ship}"/>
                      <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
                      <set_value name="$gdCacheBL.{$currentSector}.{$buySector}" exact="$buyDistance"/>
                    </do_else>
                  </do_else>
                  
                  <!-- Sell path: Calculate based on buy location -->
                  <set_value name="$sellDistance" exact="-1"/>
                  <do_if value="$sellSector == $buySector">
                    <set_value name="$sellDistance" exact="0"/>
                  </do_if>
                  <do_elseif value="$buySector == $currentSector">
                    <!-- Ship in buy sector: escape vs normal path to sell sector -->
                    <do_if value="$currentSectorIsBlacklisted">
                      <!-- Escape: non-blacklist gatedistance (memoized) -->
                      <do_if value="$gdCache.{$currentSector}? and $gdCache.{$currentSector}.{$sellSector}?">
                        <set_value name="$sellDistance" exact="$gdCache.{$currentSector}.{$sellSector}"/>
                      </do_if>
                      <do_else>
                        <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}"/>
                        <do_if value="not $gdCache.{$currentSector}?"><set_value name="$gdCache.{$currentSector}" exact="table[]"/></do_if>
                        <set_value name="$gdCache.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
                      </do_else>
                    </do_if>
                    <do_else>
                      <!-- Normal: blacklist-aware gatedistance (memoized) -->
                      <do_if value="$gdCacheBL.{$currentSector}? and $gdCacheBL.{$currentSector}.{$sellSector}?">
                        <set_value name="$sellDistance" exact="$gdCacheBL.{$currentSector}.{$sellSector}"/>
                      </do_if>
                      <do_else>
                        <set_value name="$sellDistance" exact="this.ship.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
                        <do_if value="not $gdCacheBL.{$currentSector}?"><set_value name="$gdCacheBL.{$currentSector}" exact="table[]"/></do_if>
                        <set_value name="$gdCacheBL.{$currentSector}.{$sellSector}" exact="$sellDistance"/>
                      </do_else>
                    </do_else>
                  </do_elseif>
                  <do_else>
                    <!-- Normal: buyâ†’sell blacklist-aware gatedistance (memoized) -->
                    <do_if value="$gdCacheBL.{$buySector}? and $gdCacheBL.{$buySector}.{$sellSector}?">
                      <set_value name="$sellDistance" exact="$gdCacheBL.{$buySector}.{$sellSector}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$sellDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{this.ship}"/>
                      <do_if value="not $gdCacheBL.{$buySector}?"><set_value name="$gdCacheBL.{$buySector}" exact="table[]"/></do_if>
                      <set_value name="$gdCacheBL.{$buySector}.{$sellSector}" exact="$sellDistance"/>
                    </do_else>
                  </do_else>
                  
                  <!-- Always log distance check to diagnose issues -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PATH check (blacklist-aware):' +
                      '\n  Current sector: ' + @$currentSector.knownname +
                      '\n  BUY: ' + @$buyStation.knownname + ' (Sector: ' + @$buyStation.sector.knownname + ', Distance: ' + $buyDistance + ')' +
                      '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance: ' + $sellDistance + ')' +
                      '\n  Blacklist group: ' + $blacklistgroup +
                      '\n  Result: ' + (if $buyDistance lt 0 or $sellDistance lt 0 then 'BLOCKED' else 'OK')" 
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="$buyDistance lt 0 or $sellDistance lt 0">
                    <!-- PATH BLOCKED - Skip to next trade -->
                    <set_value name="$tradesRejectedPath" operation="add"/>
                    <set_value name="$unreachableStation" exact="if $buyDistance lt 0 then $buyStation else $sellStation"/>
                    <set_value name="$unreachableType" exact="if $buyDistance lt 0 then 'BUY' else 'SELL'"/>
                    
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' PATH BLOCKED:' +
                        '\n  Station: ' + @$unreachableStation.knownname + 
                        '\n  Type: ' + $unreachableType + 
                        '\n  Reason: No path exists (disconnected sectors, war, or gates destroyed)' + 
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                    
                    <!-- Scenario 3: Flag ship-specific path failure on cache entry -->
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'path_blocked']"/>
                    </do_if>
                    
                    <!-- Continue to next trade in list -->
                    <continue/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Normal trade missing stations - skip this trade -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' MISSING STATIONS (normal trade requires both buy and sell stations)'" chance="100"/>
                  </do_if>
                  <continue/>
                </do_else>
              </do_else>
              
              <!-- Both sell-only and normal trades continue here (only if they passed initial checks) -->
              <!-- Validate distance from HOME SECTOR (not ship position) -->
              <!-- Subordinates ALWAYS use commander's home sector (via $effectiveHome) -->
              <!-- For non-subordinates: Always use defaultorder.$home as PRIMARY source (fixed value in order) -->
              <!-- Home sector is a fixed value in the order settings and should NEVER drift -->
              <!-- Ships must only trade with stations within maxbuy/maxsell from home sector -->
              <!-- Note: $effectiveHome already handles subordinates correctly (set at initialization) -->
              <set_value name="$homeBase" exact="this.$effectiveHome"/>
              
              <!-- Fallback: Only if effectiveHome is not available, check defaultorder.$home -->
              <do_if value="not $homeBase? or not $homeBase.exists">
                <set_value name="$homeBase" exact="@this.ship.defaultorder.$home"/>
                <do_if value="not $homeBase? or not $homeBase.exists">
                  <!-- REMOVED: Never fall back to ship.sector (causes cascading drift) -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI-ERROR] Home sector not found for ' + this.ship.idcode + ' - effectiveHome and defaultorder.$home are null! This should never happen.'" chance="100"/>
                  </do_if>
                  <!-- Emergency fallback only - this should never happen -->
                  <set_value name="$homeBase" exact="this.ship.sector"/>
                </do_if>
              </do_if>
              
              <!-- Extract home sector -->
              <set_value name="$homeSector" exact="null"/>
              <do_if value="@$homeBase.exists">
                <do_if value="$homeBase.isclass.station">
                  <set_value name="$homeSector" exact="$homeBase.sector"/>
                </do_if>
                <do_elseif value="$homeBase.isclass.sector">
                  <set_value name="$homeSector" exact="$homeBase"/>
                </do_elseif>
              </do_if>
              
              <do_if value="not $homeSector? or not $homeSector.exists">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI-ERROR] Failed to extract home sector from homeBase for ' + this.ship.idcode + ' - using ship.sector as emergency fallback (THIS WILL CAUSE DRIFT!)'" chance="100"/>
                </do_if>
                <!-- Emergency fallback only - this should never happen -->
                <set_value name="$homeSector" exact="this.ship.sector"/>
              </do_if>
              
              <!-- Calculate distance from HOME SECTOR to stations (range-only, no blacklist) -->
              <!-- For sell-only trades, skip buy distance check (no buy station) -->
              <set_value name="$buyDistanceFromHome" exact="0"/>
              <set_value name="$sellDistanceFromHome" exact="-1"/>
              
              <do_if value="not $isSellOnlyTrade">
                <!-- Normal trade: check buy distance from home (memoized) -->
                <set_value name="$buyDistanceFromHome" exact="-1"/>
                <do_if value="$buySector == $homeSector">
                  <set_value name="$buyDistanceFromHome" exact="0"/>
                </do_if>
                <do_else>
                  <do_if value="$gdCache.{$homeSector}? and $gdCache.{$homeSector}.{$buySector}?">
                    <set_value name="$buyDistanceFromHome" exact="$gdCache.{$homeSector}.{$buySector}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$buyDistanceFromHome" exact="$homeSector.gatedistance.{$buySector}"/>
                    <do_if value="not $gdCache.{$homeSector}?"><set_value name="$gdCache.{$homeSector}" exact="table[]"/></do_if>
                    <set_value name="$gdCache.{$homeSector}.{$buySector}" exact="$buyDistanceFromHome"/>
                  </do_else>
                </do_else>
              </do_if>
              
              <!-- Always check sell distance from home (memoized) -->
              <do_if value="$sellSector == $homeSector">
                <set_value name="$sellDistanceFromHome" exact="0"/>
              </do_if>
              <do_else>
                <do_if value="$gdCache.{$homeSector}? and $gdCache.{$homeSector}.{$sellSector}?">
                  <set_value name="$sellDistanceFromHome" exact="$gdCache.{$homeSector}.{$sellSector}"/>
                </do_if>
                <do_else>
                  <set_value name="$sellDistanceFromHome" exact="$homeSector.gatedistance.{$sellSector}"/>
                  <do_if value="not $gdCache.{$homeSector}?"><set_value name="$gdCache.{$homeSector}" exact="table[]"/></do_if>
                  <set_value name="$gdCache.{$homeSector}.{$sellSector}" exact="$sellDistanceFromHome"/>
                </do_else>
              </do_else>
              
              <!-- Resolve max distances safely â€” instance vars may be missing after hot-reload -->
              <set_value name="$_maxBuy" exact="if this.$effectiveMaxBuy? then this.$effectiveMaxBuy else 15"/>
              <set_value name="$_maxSell" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else 15"/>

              <!-- Show calculated distances for diagnosis -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
                <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': HOME SECTOR distance check (trade ' + $tradeIdx + '):' +
                  '\n  Home sector: ' + @$homeSector.knownname +
                  '\n  BUY station: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance from home: ' + $buyDistanceFromHome + '/' + $_maxBuy + ' jumps)' +
                  '\n  SELL station: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance from home: ' + $sellDistanceFromHome + '/' + $_maxSell + ' jumps)' +
                  '\n  Ship position: ' + @this.ship.sector.knownname +
                  '\n  Validation: ' + (if ($buyDistanceFromHome lt 0 or $sellDistanceFromHome lt 0 or ($buyDistanceFromHome gt $_maxBuy and not $isSellOnlyTrade) or $sellDistanceFromHome gt $_maxSell) then 'REJECTED' else 'PASSED')"
                  chance="100"/>
              </do_if>
              
              <!-- Reject if stations exceed maxDistance from home -->
              <set_value name="$distanceCheckFailed" exact="false"/>
              <do_if value="not $isSellOnlyTrade">
                <do_if value="$buyDistanceFromHome lt 0 or $buyDistanceFromHome gt $_maxBuy">
                  <set_value name="$distanceCheckFailed" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$sellDistanceFromHome lt 0 or $sellDistanceFromHome gt $_maxSell">
                <set_value name="$distanceCheckFailed" exact="true"/>
              </do_if>
              
              <do_if value="$distanceCheckFailed">
                <set_value name="$tradesRejectedDistance" operation="add"/>
                
                <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.knownname else 'Unknown')"/>
                <set_value name="$buySectorNameForDebug" exact="if $isSellOnlyTrade then 'N/A (sell-only)' else (if $buyStation? then @$buyStation.sector.knownname else 'Unknown')"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' DISTANCE EXCEEDED:' +
                    '\n  BUY: ' + $buyStationNameForDebug + ' (Sector: ' + $buySectorNameForDebug + ', Distance from home: ' + $buyDistanceFromHome + '/' + $_maxBuy + ' jumps)' +
                    '\n  SELL: ' + @$sellStation.knownname + ' (Sector: ' + @$sellStation.sector.knownname + ', Distance from home: ' + $sellDistanceFromHome + '/' + $_maxSell + ' jumps)' +
                    '\n  Home sector: ' + @$homeSector.knownname +
                    '\n  Ship position: ' + @this.ship.sector.knownname +
                    '\n  Reason: Station(s) exceed maximum distance from home sector' +
                    '\n  â†’ Trying next trade in list...'"
                    chance="100"/>
                </do_if>
                
                <!-- Scenario 3: Flag ship-specific distance failure on cache entry -->
                <do_if value="$searchMethod == 'cache'">
                  <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'distance_exceeded']"/>
                </do_if>
                
                <!-- Continue to next trade in list -->
                <continue/>
              </do_if>
              
              <!-- Check if ship is in a blacklisted sector (whitelist overrides blacklist) -->
              <set_value name="$currentSectorIsBlacklisted" exact="false"/>
              <do_if value="$blacklistgroup?">
                <set_value name="$currentSectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                      <set_value name="$currentSectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="not $currentSectorWhitelisted">
                  <set_value name="$currentSectorActivityBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$currentSectorTravelBlacklisted" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$currentSectorIsBlacklisted" exact="$currentSectorActivityBlacklisted or $currentSectorTravelBlacklisted"/>
                </do_if>
              </do_if>
              
              <!-- Check if buy station OR its sector is blacklisted -->
              <!-- Always check target sector blacklist - escape only affects PATH, not destination -->
              <!-- For sell-only trades, skip buy station blacklist check (no buy station) -->
              <!-- Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted) -->
              <set_value name="$buyBlacklisted" exact="false"/>
              <do_if value="not $isSellOnlyTrade and $blacklistgroup? and $buyStation?">
                <!-- Check station itself (objectactivity) -->
                <set_value name="$buyStationBlacklisted" exact="@$buyStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                <!-- Check sector (sectoractivity AND sectortravel) unless whitelisted -->
                <set_value name="$buySectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $buyStation.sector">
                      <set_value name="$buySectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <set_value name="$buySectorActivityBlacklisted" exact="false"/>
                <set_value name="$buySectorTravelBlacklisted" exact="false"/>
                <do_if value="not $buySectorWhitelisted">
                  <set_value name="$buySectorActivityBlacklisted" exact="@$buyStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$buySectorTravelBlacklisted" exact="@$buyStation.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                </do_if>
                
                <!-- Block buying in blacklisted sector (force escape) -->
                <!-- Ship in blacklisted sector must NOT buy in that sector -->
                <!-- Ship must escape by buying from a different (non-blacklisted) sector -->
                <do_if value="$buySectorActivityBlacklisted or $buySectorTravelBlacklisted">
                  <!-- Block buying in blacklisted sector (even if ship is already there) -->
                  <set_value name="$buyBlacklisted" exact="true"/>
                </do_if>
                <do_else>
                  <!-- Target sector is not blacklisted - only check station -->
                  <set_value name="$buyBlacklisted" exact="$buyStationBlacklisted"/>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$buyStationNameForDebug" exact="if $buyStation? then @$buyStation.knownname else 'Unknown'"/>
                  <set_value name="$buySectorNameForDebug" exact="if $buyStation? then @$buyStation.sector.knownname else 'Unknown'"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': BUY blacklist check:' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (blacklisted: ' + $currentSectorIsBlacklisted + ')' +
                    '\n  Station: ' + $buyStationNameForDebug + 
                    '\n  Sector: ' + $buySectorNameForDebug + 
                    '\n  Station (objectactivity): ' + $buyStationBlacklisted + 
                    '\n  Sector (sectoractivity): ' + $buySectorActivityBlacklisted + 
                    '\n  Sector (sectortravel): ' + $buySectorTravelBlacklisted + 
                    '\n  Ship in buy sector: ' + ($buySector == $currentSector) +
                    '\n  Final result: ' + $buyBlacklisted" 
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Check if sell station OR its sector is blacklisted -->
              <!-- Always check target sector blacklist - escape only affects PATH, not destination -->
              <!-- Whitelist overrides sector blacklist (matches GT_IsSectorBlacklisted) -->
              <set_value name="$sellBlacklisted" exact="false"/>
              <do_if value="$blacklistgroup?">
                <!-- Check station itself (objectactivity) -->
                <set_value name="$sellStationBlacklisted" exact="@$sellStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                <!-- Check sector (sectoractivity AND sectortravel) unless whitelisted -->
                <set_value name="$sellSectorWhitelisted" exact="false"/>
                <do_if value="$validationWhitelist.count gt 0">
                  <do_all exact="$validationWhitelist.count" counter="$swIdx">
                    <do_if value="$validationWhitelist.{$swIdx} == $sellStation.sector">
                      <set_value name="$sellSectorWhitelisted" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <set_value name="$sellSectorActivityBlacklisted" exact="false"/>
                <set_value name="$sellSectorTravelBlacklisted" exact="false"/>
                <do_if value="not $sellSectorWhitelisted">
                  <set_value name="$sellSectorActivityBlacklisted" exact="@$sellStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                  <set_value name="$sellSectorTravelBlacklisted" exact="@$sellStation.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
                </do_if>
                
                <!-- Always check if target sector is blacklisted -->
                <!-- Escape exception: Allow sell sector if ship is already IN it (escape FROM) -->
                <!-- But still block if ship needs to travel TO a blacklisted sector -->
                <do_if value="$sellSectorActivityBlacklisted or $sellSectorTravelBlacklisted">
                  <do_if value="$sellSector == $currentSector">
                    <!-- Ship is already in sell sector - allow escape FROM blacklisted sector -->
                    <!-- Only block if station itself is blacklisted -->
                    <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
                  </do_if>
                  <do_else>
                    <!-- Ship needs to travel TO a blacklisted sector - BLOCK -->
                    <set_value name="$sellBlacklisted" exact="true"/>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- Target sector is not blacklisted - only check station -->
                  <set_value name="$sellBlacklisted" exact="$sellStationBlacklisted"/>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': SELL blacklist check:' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (blacklisted: ' + $currentSectorIsBlacklisted + ')' +
                    '\n  Station: ' + @$sellStation.knownname + 
                    '\n  Sector: ' + @$sellStation.sector.knownname + 
                    '\n  Station (objectactivity): ' + $sellStationBlacklisted + 
                    '\n  Sector (sectoractivity): ' + $sellSectorActivityBlacklisted + 
                    '\n  Sector (sectortravel): ' + $sellSectorTravelBlacklisted + 
                    '\n  Ship in sell sector: ' + ($sellSector == $currentSector) +
                    '\n  Final result: ' + $sellBlacklisted" 
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Block intra-sector trades in blacklisted sectors -->
              <!-- If ship is in blacklisted sector and both buy/sell are in same sector, block to force escape -->
              <set_value name="$isIntraSectorTradeInBlacklisted" exact="false"/>
              <do_if value="$currentSectorIsBlacklisted and $buySector == $currentSector and $sellSector == $currentSector">
                <set_value name="$isIntraSectorTradeInBlacklisted" exact="true"/>
                <set_value name="$buyBlacklisted" exact="true"/>  <!-- Block by marking as blacklisted -->
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ':   Intra-sector trade BLOCKED (escape required):' +
                    '\n  Current sector: ' + @$currentSector.knownname + ' (BLACKLISTED)' +
                    '\n  Buy/Sell: Both in ' + @$currentSector.knownname +
                    '\n  Reason: Ship must escape from blacklisted sector'"
                    chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Check if buy/sell station is MK1-supplied (final safety check) -->
              <do_if value="not $buyBlacklisted and not $sellBlacklisted and $effectiveIgnoreMK1Supply? and $effectiveIgnoreMK1Supply and global.$GT_MK1SuppliedStations?">
                <do_if value="$buyStation? and global.$GT_MK1SuppliedStations.{$buyStation}?">
                  <set_value name="$buyBlacklisted" exact="true"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” buy station ' + @$buyStation.knownname + ' is MK1-supplied'" chance="@this.$debugchance"/>
                </do_if>
                <do_if value="not $buyBlacklisted and $sellStation? and global.$GT_MK1SuppliedStations.{$sellStation}?">
                  <set_value name="$sellBlacklisted" exact="true"/>
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade REJECTED â€” sell station ' + @$sellStation.knownname + ' is MK1-supplied'" chance="@this.$debugchance"/>
                </do_if>
              </do_if>

              <!-- Check if trade is blacklisted -->
              <do_if value="$buyBlacklisted or $sellBlacklisted">
                <!-- BLACKLISTED - Skip to next trade in list -->
                <set_value name="$tradesBlacklisted" operation="add"/>
                <set_value name="$blacklistedStation" exact="if $buyBlacklisted then $buyStation else $sellStation"/>
                <set_value name="$tradeType" exact="if $buyBlacklisted then 'BUY' else 'SELL'"/>
                
                <!-- Determine what was blacklisted (station or sector) -->
                <set_value name="$blacklistReason" exact="'Sector (sectortravel)'"/>  <!-- Default to most common case -->
                <do_if value="$buyBlacklisted">
                  <do_if value="$buyStationBlacklisted">
                    <set_value name="$blacklistReason" exact="'Station (objectactivity)'"/>
                  </do_if>
                  <do_elseif value="$buySectorActivityBlacklisted">
                    <set_value name="$blacklistReason" exact="'Sector (sectoractivity)'"/>
                  </do_elseif>
                </do_if>
                <do_else>
                  <do_if value="$sellStationBlacklisted">
                    <set_value name="$blacklistReason" exact="'Station (objectactivity)'"/>
                  </do_if>
                  <do_elseif value="$sellSectorActivityBlacklisted">
                    <set_value name="$blacklistReason" exact="'Sector (sectoractivity)'"/>
                  </do_elseif>
                </do_else>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' BLACKLISTED:' +
                    '\n  Station: ' + @$blacklistedStation.knownname + 
                    '\n  Sector: ' + @$blacklistedStation.sector.knownname + 
                    '\n  Type: ' + $tradeType + 
                    '\n  Reason: ' + $blacklistReason + 
                    '\n  â†’ Trying next trade in list...'" 
                    chance="100"/>
                </do_if>
                
                <!-- Record failed sector for future filtering -->
                <signal_objects object="player.galaxy" param="'GT_Trade_Failed'" param2="table[
                  $Ship = this.ship,
                  $Reason = 'TRADEPARTNER_BLACKLISTED',
                  $FailureText = 'Trade partner is blacklisted (pre-validation)',
                  $Partner = $blacklistedStation,
                  $IsBuying = $buyBlacklisted,
                  $Ware = @$currentTrade.$Ware
                ]"/>
                
                <!-- Scenario 3: Flag ship-specific blacklist failure on cache entry -->
                <do_if value="$searchMethod == 'cache'">
                  <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'blacklisted']"/>
                </do_if>
                
                <!-- Continue to next trade in list -->
                <continue/>
              </do_if>
              
              <!-- Fleet reservation check: skip trades reserved by other ships.
                   Restored from pre-migration gt_trading_search.xml reservation flow.
                   Uses SellOffer object as key (Method B from GT_GenerateTradeKey). -->
              <do_if value="global.$GT_Reservations? and $currentTrade.$SellOffer?">
                <set_value name="$resKey" exact="$currentTrade.$SellOffer"/>
                <do_if value="global.$GT_Reservations.{$resKey}?">
                  <set_value name="$resData" exact="global.$GT_Reservations.{$resKey}"/>
                  <do_if value="$resData.$Until? and player.age lt @$resData.$Until and $resData.$Ship? and @$resData.$Ship != this.ship">
                    <set_value name="$skipForOtherReservation" exact="true"/>
                    <do_if value="$sellStation? and @$sellStation.exists and @$sellStation.isclass.buildstorage">
                      <set_value name="$skipForOtherReservation" exact="false"/>
                    </do_if>
                    <do_if value="$skipForOtherReservation">
                      <set_value name="$tradesRejectedDemandReserved" operation="add"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' RESERVED by ' + @$resData.$Ship.idcode + ' (expires in ' + (@$resData.$Until - player.age) + ') - skipping'" chance="100"/>
                      </do_if>
                      <continue/>
                    </do_if>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- Check if ship can carry this ware type (cargo bay compatibility) -->
              <!-- Some wares (like Methane/gas) require special cargo bays that normal ships don't have -->
              <!-- For sell-only trades, use $Ware instead of $BuyOffer.ware -->
              <set_value name="$ware" exact="null"/>
              <do_if value="$isSellOnlyTrade and $currentTrade.$Ware?">
                <set_value name="$ware" exact="$currentTrade.$Ware"/>
              </do_if>
              <do_elseif value="$currentTrade.$BuyOffer?">
                <set_value name="$ware" exact="@$currentTrade.$BuyOffer.ware"/>
              </do_elseif>
              
              <do_if value="$ware? and $ware != null">
                <set_value name="$canCarryWareType" exact="this.ship.cargo.{$ware}.max gt 0"/>
                <do_if value="not $canCarryWareType and $currentTrade.$CargoWareTransport?">
                  <set_value name="$canCarryWareType" exact="this.ship.waretransport.indexof.{@$currentTrade.$CargoWareTransport}"/>
                </do_if>
                
                <do_if value="not $canCarryWareType">
                  <!-- SHIP CANNOT CARRY THIS WARE TYPE - Skip to next trade -->
                  <set_value name="$tradesRejectedCargo" operation="add"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + $tradeIdx + '/' + (if $tradeList != null then $tradeList.count else 0) + ' INCOMPATIBLE CARGO TYPE:' +
                      '\n  Ware: ' + @$ware.name + 
                      '\n  Reason: Ship does not have required cargo bay type (e.g., liquid/gas requires special containment)' +
                      '\n  Ship cargo max for this ware: ' + this.ship.cargo.{$ware}.max +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  
                  <!-- Do NOT GT_Cache_Flag_Ship: hold-type mismatch is not a per-ship trade failure. -->
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- Validation passed - this trade is valid -->
                <!-- Note: Cargo space and money validation will be handled by clamp_trade_amount before order creation -->
                <!-- Use safe access for tradeIdx -->
                <set_value name="$tradeIdxSafe" exact="if $tradeIdx? then $tradeIdx else 0"/>
                <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' passed validation - checking offer availability...'" chance="100"/>
                </do_if>
                
                <!-- Check offer validity INSIDE loop before breaking -->
                <!-- This allows us to try the next trade if offers are consumed -->
                <!-- Initialize variables before conditionals to prevent property lookup errors -->
                <set_value name="$buyOfferStillValid" exact="true"/>
                <set_value name="$sellOfferStillValid" exact="false"/>
                <set_value name="$buyOfferAvailable" exact="null"/>
                <set_value name="$buyOfferAmount" exact="null"/>
                <set_value name="$sellOfferAvailable" exact="null"/>
                <set_value name="$sellOfferAmount" exact="null"/>
                <set_value name="$buyOfferOwnerValid" exact="true"/>
                <set_value name="$sellOfferOwnerValid" exact="true"/>
                
                <do_if value="$isSellOnlyTrade">
                  <!-- Sell-only trade: only check sell offer -->
                  <do_if value="$currentTrade.$SellOffer?">
                    <set_value name="$sellOfferAvailable" exact="$currentTrade.$SellOffer.available"/>
                    <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and @$currentTrade.$SellOffer.amount gt 0">
                      <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.amount"/>
                    </do_if>
                    <set_value name="$sellOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$SellOffer.owner?">
                      <set_value name="$sellOwnerTmp" exact="@$currentTrade.$SellOffer.owner"/>
                      <do_if value="$sellOwnerTmp? and $sellOwnerTmp.exists">
                        <set_value name="$sellOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$sellOfferStillValid" exact="$sellOfferAvailable and ($sellOfferAmount? and $sellOfferAmount gt 0) and $sellOfferOwnerValid"/>
                    <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$sellDesiredBefore" exact="@$currentTrade.$SellOffer.desiredamount"/>
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': pre-validate SELL-ONLY' +
                        '\n  needed=' + $currentTrade.$Amount +
                        '\n  sell offeramount(ship)=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') +
                        '\n  sell desiredamount=' + (if $sellDesiredBefore? then $sellDesiredBefore else 'null')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Sell-only trade but no sell offer - invalid -->
                    <set_value name="$sellOfferStillValid" exact="false"/>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- Normal trade: check both offers -->
                  <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$SellOffer?">
                    <!-- Re-resolve stale supplier offer before validity check (mirrors final order validation). -->
                    <set_value name="$preValBuyStation" exact="null"/>
                    <set_value name="$preValBuyWare" exact="if $ware? then $ware else null"/>
                    <do_if value="not $preValBuyWare? and $currentTrade.$BuyOffer.ware?">
                      <set_value name="$preValBuyWare" exact="@$currentTrade.$BuyOffer.ware"/>
                    </do_if>
                    <do_if value="$currentTrade.$BuyStation? and @$currentTrade.$BuyStation.exists">
                      <set_value name="$preValBuyStation" exact="$currentTrade.$BuyStation"/>
                    </do_if>
                    <do_elseif value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                      <set_value name="$preValBuyStation" exact="@$currentTrade.$BuyOffer.seller"/>
                    </do_elseif>
                    <do_elseif value="$currentTrade.$BuyOffer.owner? and @$currentTrade.$BuyOffer.owner.exists">
                      <set_value name="$preValBuyStation" exact="@$currentTrade.$BuyOffer.owner"/>
                    </do_elseif>
                    <do_if value="$preValBuyStation? and $preValBuyStation.exists and $preValBuyWare != null">
                      <find_sell_offer seller="$preValBuyStation" wares="$preValBuyWare" tradepartner="this.ship" result="$preValFreshBuyOffer"/>
                      <do_if value="$preValFreshBuyOffer?">
                        <set_value name="$currentTrade.$BuyOffer" exact="$preValFreshBuyOffer"/>
                      </do_if>
                    </do_if>

                    <!-- Re-resolve stale delivery offer before validity check (mirrors final order validation). -->
                    <set_value name="$preValSellStation" exact="null"/>
                    <set_value name="$preValSellWare" exact="if $ware? then $ware else null"/>
                    <do_if value="not $preValSellWare? and $currentTrade.$SellOffer.ware?">
                      <set_value name="$preValSellWare" exact="@$currentTrade.$SellOffer.ware"/>
                    </do_if>
                    <do_if value="$currentTrade.$SellStation? and @$currentTrade.$SellStation.exists">
                      <set_value name="$preValSellStation" exact="$currentTrade.$SellStation"/>
                    </do_if>
                    <do_elseif value="$currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists">
                      <set_value name="$preValSellStation" exact="@$currentTrade.$SellOffer.buyer"/>
                    </do_elseif>
                    <do_elseif value="$currentTrade.$SellOffer.owner? and @$currentTrade.$SellOffer.owner.exists">
                      <set_value name="$preValSellStation" exact="@$currentTrade.$SellOffer.owner"/>
                    </do_elseif>
                    <!-- Build-storage deliveries recreate their offer, build storage AND base every
                         construction tick, so all cached refs are dead by execution time (-> buyer_missing
                         at clamp). Re-discover the LIVE delivery the same way lib.gt.mk42.cache.search does:
                         first the cheap base anchor, then find the current player buy offer by the cached
                         sell sector + ware, disambiguated by the stored stable delivery idcode. -->
                    <do_if value="(not $preValSellStation? or not @$preValSellStation.exists) and $currentTrade.$SellStationBase? and @$currentTrade.$SellStationBase.exists and @$currentTrade.$SellStationBase.buildstorage and @$currentTrade.$SellStationBase.buildstorage.exists">
                      <set_value name="$preValSellStation" exact="@$currentTrade.$SellStationBase.buildstorage"/>
                    </do_if>
                    <!-- A build-storage component handle churns every construction tick but can still
                         report .exists=true while its offers have already moved to a fresh component.
                         So for ANY build-storage delivery (cached component dead OR still "existing", OR a
                         stored build-storage base/DeliveryStationId), always re-discover the LIVE offer by
                         sector + stable idcode instead of trusting the cached component (-> buyer_missing). -->
                    <set_value name="$preValForceBsRescan" exact="(not $preValSellStation? or not @$preValSellStation.exists) or (@$preValSellStation.exists and @$preValSellStation.isclass.buildstorage) or ($currentTrade.$SellStationBase? and @$currentTrade.$SellStationBase.exists and $currentTrade.$SellStationBase.buildstorage?)"/>
                    <set_value name="$preValBsBuyer" exact="null"/>
                    <set_value name="$preValRePick" exact="null"/>
                    <do_if value="$preValForceBsRescan and $currentTrade.$SellSector? and @$currentTrade.$SellSector.exists and $preValSellWare != null and $currentTrade.$DeliveryStationId?">
                      <!-- Re-resolve the live build-storage buy offer with the PROVEN MK4-2 player buy-offer
                           query (lib.gt.mk42.live.search.xml ~1368): scan player-owned buy offers for the ware
                           in the sell sector with a BARE <offeramount min="1"/> (NO tradepartner). The bare
                           offeramount lets the engine read the build storage's desiredamount (construction
                           demand carries no funds); specifying tradepartner=ship forces the money-trade path
                           that reads the 0 funds-amount -> nothing found -> false buyer_missing (XSD common.xsd
                           offeramount: "uses the desired amount if money would NOT change hands"). Disambiguate
                           the correct delivery by the cached stable base idcode. -->
                      <find_buy_offer wares="$preValSellWare" space="$currentTrade.$SellSector" result="$preValBsOffers" multiple="true">
                        <match_buyer tradesknownto="this.ship.owner" owner="faction.player">
                          <match_relation_to object="this.ship" relation="dock" comparison="ge"/>
                          <match_relation_to faction="this.ship.owner" relation="enemy" comparison="not"/>
                        </match_buyer>
                        <offeramount min="1"/>
                      </find_buy_offer>
                      <do_if value="$preValBsOffers? and $preValBsOffers.count gt 0">
                        <do_for_each name="$preValBsO" in="$preValBsOffers">
                          <do_if value="not ($preValRePick? and @$preValRePick.exists) and $preValBsO? and @$preValBsO.exists">
                            <set_value name="$preValBsCand" exact="null"/>
                            <do_if value="$preValBsO.buyer? and @$preValBsO.buyer.exists">
                              <set_value name="$preValBsCand" exact="@$preValBsO.buyer"/>
                            </do_if>
                            <do_elseif value="$preValBsO.owner? and @$preValBsO.owner.exists">
                              <set_value name="$preValBsCand" exact="@$preValBsO.owner"/>
                            </do_elseif>
                            <do_if value="$preValBsCand? and @$preValBsCand.exists">
                              <set_value name="$preValBsCandId" exact="if @$preValBsCand.isclass.buildstorage and $preValBsCand.base? and @$preValBsCand.base.exists then @$preValBsCand.base.idcode else @$preValBsCand.idcode"/>
                              <do_if value="$preValBsCandId == $currentTrade.$DeliveryStationId">
                                <set_value name="$preValRePick" exact="$preValBsO"/>
                                <set_value name="$preValBsBuyer" exact="$preValBsCand"/>
                                <set_value name="$preValSellStation" exact="$preValBsCand"/>
                                <set_value name="$currentTrade.$SellStation" exact="$preValBsCand"/>
                                <set_value name="$currentTrade.$SellOffer" exact="$preValBsO"/>
                              </do_if>
                            </do_if>
                          </do_if>
                        </do_for_each>
                      </do_if>
                    </do_if>
                    <!-- Non-build-storage normal-station refresh (build storage already handled above). -->
                    <do_if value="not $preValForceBsRescan and $preValSellStation? and $preValSellStation.exists and $preValSellWare != null and not @$preValSellStation.isclass.buildstorage">
                      <find_buy_offer buyer="$preValSellStation" wares="$preValSellWare" tradepartner="this.ship" result="$preValFreshSellOffer"/>
                      <do_if value="$preValFreshSellOffer?">
                        <set_value name="$currentTrade.$SellOffer" exact="$preValFreshSellOffer"/>
                      </do_if>
                    </do_if>
                    <do_if value="$preValForceBsRescan and @global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': BS re-resolve' +
                        '\n  ware=' + (if $preValSellWare? then $preValSellWare.name else 'null') +
                        '\n  deliveryId=' + (if $currentTrade.$DeliveryStationId? then $currentTrade.$DeliveryStationId else 'null') +
                        '\n  bsBuyer found=' + (if $preValBsBuyer? and @$preValBsBuyer.exists then 1 else 0) +
                        '\n  sellOffer.buyer alive=' + (if $currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists then 1 else 0) +
                        '\n  sellOffer.owner alive=' + (if $currentTrade.$SellOffer.owner? and @$currentTrade.$SellOffer.owner.exists then 1 else 0)"
                        chance="100"/>
                    </do_if>

                    <!-- Check buy offer: available AND has SOME amount (clamping will handle exact amount reduction) -->
                    <set_value name="$buyOfferAvailable" exact="$currentTrade.$BuyOffer.available"/>
                    <set_value name="$buyOfferAmount" exact="@$currentTrade.$BuyOffer.offeramount.{this.ship}"/>
                    <!-- Supplier-side fallback: only when offeramount is zero but the supplier
                         physically holds unreserved stock (avoids matching reserved-away offers). -->
                    <do_if value="(not $buyOfferAmount? or $buyOfferAmount le 0) and $currentTrade.$BuyOffer.amount? and @$currentTrade.$BuyOffer.amount gt 0">
                      <set_value name="$buyFallbackSeller" exact="null"/>
                      <do_if value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                        <set_value name="$buyFallbackSeller" exact="@$currentTrade.$BuyOffer.seller"/>
                      </do_if>
                      <do_if value="not $buyFallbackSeller? and $currentTrade.$BuyOffer.owner? and @$currentTrade.$BuyOffer.owner.exists">
                        <set_value name="$buyFallbackSeller" exact="@$currentTrade.$BuyOffer.owner"/>
                      </do_if>
                      <set_value name="$buyFallbackStock" exact="0"/>
                      <do_if value="$buyFallbackSeller? and $ware?">
                        <get_ware_reservation object="$buyFallbackSeller" ware="$ware" type="buy" virtual="false" result="$buyFallbackReserved"/>
                        <set_value name="$buyFallbackStock" exact="[$buyFallbackSeller.cargo.{$ware}.count - $buyFallbackReserved, 0].max"/>
                      </do_if>
                      <do_if value="$buyFallbackStock gt 0">
                        <set_value name="$buyOfferAmount" exact="[$buyFallbackStock, @$currentTrade.$BuyOffer.amount].min"/>
                      </do_if>
                    </do_if>
                    <do_if value="(not $buyOfferAmount? or $buyOfferAmount le 0) and $currentTrade.$SellOffer.owner? and @$currentTrade.$SellOffer.owner.exists">
                      <set_value name="$preValBuyWare" exact="if $currentTrade.$Ware? then $currentTrade.$Ware else null"/>
                      <do_if value="not $preValBuyWare? and @$currentTrade.$BuyOffer.ware != null">
                        <set_value name="$preValBuyWare" exact="@$currentTrade.$BuyOffer.ware"/>
                      </do_if>
                      <do_if value="$preValBuyWare?">
                        <set_value name="$buyOfferAmount" exact="[0, $currentTrade.$SellOffer.owner.cargo.{$preValBuyWare}.target - $currentTrade.$SellOffer.owner.cargo.{$preValBuyWare}.count].max"/>
                      </do_if>
                    </do_if>
                    <set_value name="$buyOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$BuyOffer.seller? and @$currentTrade.$BuyOffer.seller.exists">
                      <set_value name="$buyOfferOwnerValid" exact="true"/>
                    </do_if>
                    <do_if value="not $buyOfferOwnerValid and $currentTrade.$BuyOffer.owner?">
                      <set_value name="$buyOwnerTmp" exact="@$currentTrade.$BuyOffer.owner"/>
                      <do_if value="$buyOwnerTmp? and $buyOwnerTmp.exists">
                        <set_value name="$buyOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Only reject if offer is unavailable OR amount is 0/null - let clamping handle partial amounts -->
                    <set_value name="$buyOfferStillValid" exact="$buyOfferAvailable and ($buyOfferAmount? and $buyOfferAmount gt 0) and $buyOfferOwnerValid"/>
                    
                    <!-- Check sell offer: effective amount (clamping will handle exact amount reduction) -->
                    <set_value name="$sellOfferAvailable" exact="$currentTrade.$SellOffer.available"/>
                    <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <!-- Symmetric fallback for destination offer amount handling. -->
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and $currentTrade.$SellOffer.amount? and @$currentTrade.$SellOffer.amount gt 0">
                      <set_value name="$sellOfferAmount" exact="@$currentTrade.$SellOffer.amount"/>
                    </do_if>
                    <do_if value="(not $sellOfferAmount? or $sellOfferAmount le 0) and $preValSellStation? and $preValSellStation.exists and $preValSellWare?">
                      <set_value name="$sellOfferAmount" exact="[0, $preValSellStation.cargo.{$preValSellWare}.target - $preValSellStation.cargo.{$preValSellWare}.count].max"/>
                    </do_if>
                    <set_value name="$sellOfferOwnerValid" exact="false"/>
                    <do_if value="$currentTrade.$SellStation? and @$currentTrade.$SellStation.exists">
                      <set_value name="$sellOfferOwnerValid" exact="true"/>
                    </do_if>
                    <do_if value="not $sellOfferOwnerValid and $currentTrade.$SellOffer.buyer? and @$currentTrade.$SellOffer.buyer.exists">
                      <set_value name="$sellOfferOwnerValid" exact="true"/>
                    </do_if>
                    <do_if value="not $sellOfferOwnerValid and $currentTrade.$SellOffer.owner?">
                      <set_value name="$sellOwnerTmp" exact="@$currentTrade.$SellOffer.owner"/>
                      <do_if value="$sellOwnerTmp? and $sellOwnerTmp.exists">
                        <set_value name="$sellOfferOwnerValid" exact="true"/>
                      </do_if>
                    </do_if>
                    <!-- Build Storage / internal delivery: .available may stay false while cargo deficit exists. -->
                    <set_value name="$sellOfferStillValid" exact="$sellOfferOwnerValid and ($sellOfferAmount? and $sellOfferAmount gt 0)"/>
                    
                    <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$buyDesiredBefore" exact="@$currentTrade.$BuyOffer.desiredamount"/>
                      <set_value name="$sellDesiredBefore" exact="@$currentTrade.$SellOffer.desiredamount"/>
                      <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': pre-validate NORMAL' +
                        '\n  needed=' + $currentTrade.$Amount +
                        '\n  buy offeramount(ship)=' + (if $buyOfferAmount? then $buyOfferAmount else 'null') +
                        '\n  buy desiredamount=' + (if $buyDesiredBefore? then $buyDesiredBefore else 'null') +
                        '\n  sell offeramount(ship)=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') +
                        '\n  sell desiredamount=' + (if $sellDesiredBefore? then $sellDesiredBefore else 'null')"
                        chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Normal trade but missing offers - invalid -->
                    <set_value name="$buyOfferStillValid" exact="false"/>
                    <set_value name="$sellOfferStillValid" exact="false"/>
                  </do_else>
                </do_else>
                
                <!-- Check if offers are valid - conditional based on trade type -->
                <set_value name="$offersInvalid" exact="false"/>
                <do_if value="$isSellOnlyTrade">
                  <!-- Sell-only trade: only check sell offer -->
                  <set_value name="$offersInvalid" exact="not $sellOfferStillValid"/>
                </do_if>
                <do_else>
                  <!-- Normal trade: check both offers -->
                  <set_value name="$offersInvalid" exact="not $buyOfferStillValid or not $sellOfferStillValid"/>
                </do_else>
                
                <do_if value="$offersInvalid">
                  <!-- Offer became invalid - try next trade in list -->
                  <set_value name="$tradesRejectedOfferInvalid" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <!-- Compute precise invalid reason (buy/sell availability vs amount shortfall) -->
                    <set_value name="$offerInvalidReason" exact="''"/>
                    <do_if value="$isSellOnlyTrade">
                      <do_if value="not $sellOfferAvailable">
                        <set_value name="$offerInvalidReason" exact="'sell_not_available'"/>
                      </do_if>
                      <do_elseif value="not $sellOfferAmount?">
                        <set_value name="$offerInvalidReason" exact="'sell_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$sellOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$offerInvalidReason" exact="'sell_amount_lt_needed'"/>
                      </do_elseif>
                      <do_else>
                        <set_value name="$offerInvalidReason" exact="'sell_unknown'"/>
                      </do_else>
                    </do_if>
                    <do_else>
                      <set_value name="$buyInvalidReason" exact="'ok'"/>
                      <set_value name="$sellInvalidReason" exact="'ok'"/>
                      <do_if value="not $buyOfferOwnerValid">
                        <set_value name="$buyInvalidReason" exact="'buy_owner_missing'"/>
                      </do_if>
                      <do_elseif value="not $buyOfferAvailable">
                        <set_value name="$buyInvalidReason" exact="'buy_not_available'"/>
                      </do_elseif>
                      <do_elseif value="not $buyOfferAmount?">
                        <set_value name="$buyInvalidReason" exact="'buy_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$buyOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$buyInvalidReason" exact="'buy_amount_lt_needed'"/>
                      </do_elseif>
                      <do_if value="not $sellOfferOwnerValid">
                        <set_value name="$sellInvalidReason" exact="'sell_owner_missing'"/>
                      </do_if>
                      <do_elseif value="not $sellOfferAvailable">
                        <set_value name="$sellInvalidReason" exact="'sell_not_available'"/>
                      </do_elseif>
                      <do_elseif value="not $sellOfferAmount?">
                        <set_value name="$sellInvalidReason" exact="'sell_amount_null'"/>
                      </do_elseif>
                      <do_elseif value="$sellOfferAmount lt $currentTrade.$Amount">
                        <set_value name="$sellInvalidReason" exact="'sell_amount_lt_needed'"/>
                      </do_elseif>
                      <set_value name="$offerInvalidReason" exact="'buy=' + $buyInvalidReason + ', sell=' + $sellInvalidReason"/>
                    </do_else>

                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' offer became invalid:' +
                      '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                      '\n  Buy offer: ' + (if $isSellOnlyTrade then 'N/A' else (if $buyOfferAvailable? then ('available=' + $buyOfferAvailable + ', amount=' + (if $buyOfferAmount? then $buyOfferAmount else 'null') + ' (needed: ' + $currentTrade.$Amount + ')') else 'MISSING')) +
                      '\n  Sell offer: available=' + (if $sellOfferAvailable? then $sellOfferAvailable else 'null') + ', amount=' + (if $sellOfferAmount? then $sellOfferAmount else 'null') + ' (needed: ' + $currentTrade.$Amount + ')' +
                      '\n  Failure: ' + $offerInvalidReason +
                      '\n  Reason: offer unavailable or amount is 0/null (clamping would handle partial amounts, but offer is completely unavailable)' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  
                  <!-- Cache maintenance: distinguish universally dead offers (PURGE) from
                       temporary saturation (SKIP) from permanent ship-specific failure (FLAG).
                       .available and .owner.exists are universal; offeramount.{ship} is transient. -->
                  <do_if value="$searchMethod == 'cache'">
                    <!-- Determine if offers are universally dead (not available / owner destroyed) -->
                    <set_value name="$universallyDead" exact="false"/>
                    <do_if value="not $isSellOnlyTrade">
                      <do_if value="(not $buyOfferAvailable) or (not $buyOfferOwnerValid)">
                        <set_value name="$universallyDead" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_if value="(not $sellOfferAvailable) or (not $sellOfferOwnerValid)">
                      <!-- Build Storage delivery: .available may stay false while cargo deficit exists. -->
                      <do_if value="not $sellOfferOwnerValid or not ($sellOfferAmount? and $sellOfferAmount gt 0)">
                        <set_value name="$universallyDead" exact="true"/>
                      </do_if>
                    </do_if>
                    
                    <do_if value="$universallyDead">
                      <!-- Scenario 1: Offer genuinely dead â€” purge from cache -->
                      <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                        $Ship = this.ship,
                        $BuyOffer = @$currentTrade.$BuyOffer,
                        $SellOffer = @$currentTrade.$SellOffer,
                        $HomeSector = $searchHomeSector,
                        $CachePool = 'mk42',
                        $Reason = 'offer_dead'
                      ]"/>
                    </do_if>
                    <do_else>
                      <!-- Scenario 2: Transient saturation / per-ship amount â€” flag so next cache read tries another entry. -->
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[
                        $Ship = this.ship,
                        $BuyOffer = @$currentTrade.$BuyOffer,
                        $SellOffer = @$currentTrade.$SellOffer,
                        $HomeSector = $searchHomeSector,
                        $CachePool = 'mk42',
                        $Reason = 'offer_invalid'
                      ]"/>
                    </do_else>
                  </do_if>
                  
                  <!-- Continue to next trade in list -->
                  <continue/>
                </do_if>
                
                <!-- HYBRID APPROACH: Use clamp_trade_amount for final amount validation BEFORE breaking -->
                <!-- This handles cargo space, money, and offer availability automatically -->
                <!-- If clamping results in 0, continue to next trade instead of breaking -->
                <set_value name="$finalBuyAmount" exact="$currentTrade.$Amount"/>
                <set_value name="$finalSellAmount" exact="$currentTrade.$Amount"/>
                <set_value name="$buyClampReason" exact="null"/>
                <set_value name="$sellClampReason" exact="null"/>
                <set_value name="$clampFailed" exact="false"/>
                <set_value name="$buyClampSeller" exact="null"/>
                <set_value name="$sellClampBuyer" exact="null"/>
                
                <!-- PROFIT DEBUG: Log original amount before clamping -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                  <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') AMOUNT CLAMPING START:' + 
                    '\n  Ware: ' + $wareName +
                    '\n  Original Amount (from trade object): ' + $currentTrade.$Amount + ' units' +
                    '\n  Trade Profit (RAW): ' + (if $currentTrade.$Profit? then $currentTrade.$Profit else 'NULL') + ' = ' + (if $currentTrade.$Profit? then ($currentTrade.$Profit/100) + ' Cr' else 'NULL') +
                    '\n  Trade BuyPrice (RAW): ' + (if $currentTrade.$BuyPrice? then $currentTrade.$BuyPrice else 'NULL') + ' = ' + (if $currentTrade.$BuyPrice? then ($currentTrade.$BuyPrice/100) + ' Cr' else 'NULL') +
                    '\n  Trade SellPrice (RAW): ' + (if $currentTrade.$SellPrice? then $currentTrade.$SellPrice else 'NULL') + ' = ' + (if $currentTrade.$SellPrice? then ($currentTrade.$SellPrice/100) + ' Cr' else 'NULL')" chance="100"/>
                </do_if>
                
                <!-- Clamp buy order amount (for non-sell-only trades) -->
                <do_if value="not $isSellOnlyTrade and $currentTrade.$BuyOffer?">
                  <set_value name="$buyClampSeller" exact="null"/>
                  <do_if value="$currentTrade.$BuyOffer.seller?">
                    <set_value name="$buyClampSeller" exact="@$currentTrade.$BuyOffer.seller"/>
                  </do_if>
                  <do_if value="$buyClampSeller == null and $currentTrade.$BuyOffer.owner?">
                    <set_value name="$buyClampSeller" exact="@$currentTrade.$BuyOffer.owner"/>
                  </do_if>
                  <do_if value="$buyClampSeller != null">
                    <clamp_trade_amount 
                      trade="$currentTrade.$BuyOffer" 
                      amount="$finalBuyAmount" 
                      buyer="this.ship" 
                      seller="$buyClampSeller" 
                      result="$finalBuyAmount"
                      reason="$buyClampReason"/>
                  </do_if>
                  <do_else>
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <set_value name="$buyClampReason" exact="'seller_missing'"/>
                  </do_else>
                  <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$buyOfferAmountAfterClamp" exact="@$currentTrade.$BuyOffer.offeramount.{this.ship}"/>
                    <set_value name="$buyDesiredAfterClamp" exact="@$currentTrade.$BuyOffer.desiredamount"/>
                    <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': post-clamp BUY' +
                      '\n  original=' + $currentTrade.$Amount +
                      '\n  clamped=' + $finalBuyAmount +
                      '\n  buy offeramount(ship)=' + (if $buyOfferAmountAfterClamp? then $buyOfferAmountAfterClamp else 'null') +
                      '\n  buy desiredamount=' + (if $buyDesiredAfterClamp? then $buyDesiredAfterClamp else 'null') +
                      '\n  clampReason=' + (if $buyClampReason? then $buyClampReason else 'null')"
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="not $finalBuyAmount? or $finalBuyAmount == 0 or $finalBuyAmount lt 0">
                    <!-- Amount clamped to 0 or invalid - try next trade -->
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$clampReasonText" exact="if $buyClampReason? then $buyClampReason else 'unknown'"/>
                      <set_value name="$amountStatus" exact="if not $finalBuyAmount? then 'null' else if $finalBuyAmount lt 0 then 'negative (' + $finalBuyAmount + ')' else 'zero'"/>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' buy amount clamped to invalid value:' +
                        '\n  Original amount: ' + $currentTrade.$Amount +
                        '\n  Clamped amount: ' + $amountStatus +
                        '\n  Clamp reason: ' + $clampReasonText +
                        '\n  Reason: ' + (if $buyClampReason == 'buyer_cargo' then 'Insufficient cargo space' else if $buyClampReason == 'buyer_money' then 'Insufficient funds' else if $buyClampReason == 'seller_cargo' then 'Seller has insufficient stock' else 'Offer constraints') +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <do_if value="not $clampFailed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $finalBuyAmount != $currentTrade.$Amount">
                    <set_value name="$clampReasonText" exact="if $buyClampReason? then $buyClampReason else 'unknown'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' buy amount adjusted:' +
                      '\n  Original: ' + $currentTrade.$Amount +
                      '\n  Clamped: ' + $finalBuyAmount +
                      '\n  Reason: ' + $clampReasonText"
                      chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- Clamp sell order amount -->
                <do_if value="not $clampFailed and $currentTrade.$SellOffer?">
                  <set_value name="$sellClampBuyer" exact="null"/>
                  <do_if value="$currentTrade.$SellOffer.buyer?">
                    <set_value name="$sellClampBuyer" exact="@$currentTrade.$SellOffer.buyer"/>
                  </do_if>
                  <do_if value="$sellClampBuyer == null and $currentTrade.$SellOffer.owner?">
                    <set_value name="$sellClampBuyer" exact="@$currentTrade.$SellOffer.owner"/>
                  </do_if>
                  <do_if value="$sellClampBuyer == null">
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <set_value name="$sellClampReason" exact="'buyer_missing'"/>
                  </do_if>
                  
                  <do_if value="$isSellOnlyTrade">
                    <!-- Sell-only trade: Ship already has cargo, validate against ship cargo -->
                    <do_if value="not $clampFailed">
                      <clamp_trade_amount 
                        trade="$currentTrade.$SellOffer" 
                        amount="$finalSellAmount" 
                        buyer="$sellClampBuyer" 
                        seller="this.ship" 
                        result="$finalSellAmount"
                        reason="$sellClampReason"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <!-- Normal trade: Ship doesn't have cargo yet (will buy first), don't check seller cargo -->
                    <!-- Match vanilla pattern: clamp without seller parameter (only checks buyer constraints) -->
                    <!-- Vanilla comment: "it is possible that this doesn't have the wares yet if they still need to be bought" -->
                    <do_if value="not $clampFailed">
                      <clamp_trade_amount 
                        trade="$currentTrade.$SellOffer" 
                        amount="$finalSellAmount" 
                        buyer="$sellClampBuyer" 
                        result="$finalSellAmount"
                        reason="$sellClampReason"/>
                    </do_if>
                  </do_else>
                  
                  <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$sellOfferAmountAfterClamp" exact="@$currentTrade.$SellOffer.offeramount.{this.ship}"/>
                    <set_value name="$sellDesiredAfterClamp" exact="@$currentTrade.$SellOffer.desiredamount"/>
                    <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': post-clamp SELL' +
                      '\n  original=' + $currentTrade.$Amount +
                      '\n  clamped=' + $finalSellAmount +
                      '\n  sell offeramount(ship)=' + (if $sellOfferAmountAfterClamp? then $sellOfferAmountAfterClamp else 'null') +
                      '\n  sell desiredamount=' + (if $sellDesiredAfterClamp? then $sellDesiredAfterClamp else 'null') +
                      '\n  clampReason=' + (if $sellClampReason? then $sellClampReason else 'null')"
                      chance="100"/>
                  </do_if>
                  
                  <do_if value="not $finalSellAmount? or $finalSellAmount == 0 or $finalSellAmount lt 0">
                    <!-- Amount clamped to 0 or invalid - try next trade -->
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <set_value name="$clampFailed" exact="true"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$clampReasonText" exact="if $sellClampReason? then $sellClampReason else 'unknown'"/>
                      <set_value name="$amountStatus" exact="if not $finalSellAmount? then 'null' else if $finalSellAmount lt 0 then 'negative (' + $finalSellAmount + ')' else 'zero'"/>
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' sell amount clamped to invalid value:' +
                        '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                        '\n  Original amount: ' + $currentTrade.$Amount +
                        '\n  Clamped amount: ' + $amountStatus +
                        '\n  Clamp reason: ' + $clampReasonText +
                        '\n  Reason: ' + (if $sellClampReason == 'buyer_cargo' then 'Buyer has insufficient cargo space' else if $sellClampReason == 'buyer_money' then 'Buyer has insufficient funds' else if $sellClampReason == 'seller_cargo' then 'Ship has insufficient cargo' else 'Offer constraints') +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <do_if value="not $clampFailed and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $finalSellAmount != $currentTrade.$Amount">
                    <set_value name="$clampReasonText" exact="if $sellClampReason? then $sellClampReason else 'unknown'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' sell amount adjusted:' +
                      '\n  Trade type: ' + (if $isSellOnlyTrade then 'SELL-ONLY' else 'NORMAL') +
                      '\n  Original: ' + $currentTrade.$Amount +
                      '\n  Clamped: ' + $finalSellAmount +
                      '\n  Reason: ' + $clampReasonText"
                      chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- If clamping failed, continue to next trade -->
                <do_if value="$clampFailed">
                  <continue/>
                </do_if>

                <!-- CRITICAL: For NORMAL trades, BUY and SELL amounts must match.
                     clamp_trade_amount can clamp BUY (ship cargo/money) and SELL (buyer constraints) independently.
                     Final executed amount must be the minimum of both. -->
                <do_if value="not $isSellOnlyTrade">
                  <set_value name="$finalAmount" exact="[$finalBuyAmount, $finalSellAmount].min"/>
                  
                  <!-- PROFIT DEBUG: Log amount syncing details -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') AMOUNT SYNCING:' + 
                      '\n  Ware: ' + $wareName +
                      '\n  Original Amount: ' + $currentTrade.$Amount + ' units' +
                      '\n  Clamped Buy Amount: ' + $finalBuyAmount + ' units' +
                      '\n  Clamped Sell Amount: ' + $finalSellAmount + ' units' +
                      '\n  Final Amount (min): ' + $finalAmount + ' units' +
                      '\n  Amount changed: ' + (if $finalAmount != $currentTrade.$Amount then 'YES (was ' + $currentTrade.$Amount + ', now ' + $finalAmount + ')' else 'NO') +
                      '\n  Trade Profit (unchanged): ' + (if $currentTrade.$Profit? then ($currentTrade.$Profit/100) + ' Cr' else 'NULL')" chance="100"/>
                  </do_if>
                  
                  <set_value name="$finalBuyAmount" exact="$finalAmount"/>
                  <set_value name="$finalSellAmount" exact="$finalAmount"/>
                </do_if>

                <!-- HARD FILTER: Minimum cargo utilization threshold (live/cache/fallback only; excluded in isolated mode) -->
                <set_value name="$isIsolatedForCargoFilter" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
                <set_value name="$applyMinCargoUtilFilter" exact="(if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)) and not $isSellOnlyTrade and not $isIsolatedForCargoFilter and ($searchMethod == 'live' or $searchMethod == 'cache' or $searchMethod == 'live_fallback')"/>
                <do_if value="$applyMinCargoUtilFilter">
                  <set_value name="$cargoUtilThresholdPct" exact="[10,[$gt_cargotarget,100].min].max"/>
                  <set_value name="$utilWare" exact="null"/>
                  <do_if value="$currentTrade.$Ware?">
                    <set_value name="$utilWare" exact="$currentTrade.$Ware"/>
                  </do_if>
                  <do_elseif value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware?">
                    <set_value name="$utilWare" exact="@$currentTrade.$BuyOffer.ware"/>
                  </do_elseif>
                  <do_elseif value="$currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware?">
                    <set_value name="$utilWare" exact="@$currentTrade.$SellOffer.ware"/>
                  </do_elseif>

                  <set_value name="$utilVolumePerUnit" exact="1"/>
                  <do_if value="$utilWare?">
                    <do_if value="$utilWare.volume?">
                      <set_value name="$utilVolumePerUnit" exact="$utilWare.volume"/>
                    </do_if>
                  </do_if>

                  <set_value name="$shipCargoCapacityVol" exact="this.ship.cargo.capacity.all"/>
                  <set_value name="$tradeCargoVolume" exact="$finalBuyAmount * $utilVolumePerUnit"/>
                  <set_value name="$requiredCargoVolume" exact="($shipCargoCapacityVol * $cargoUtilThresholdPct) / 100.0"/>
                  <set_value name="$cargoUtilizationPct" exact="if $shipCargoCapacityVol gt 0 then ($tradeCargoVolume * 100.0) / $shipCargoCapacityVol else 0"/>

                  <!-- Bypass cargo utilization for priority wares: player explicitly wants these even if low volume -->
                  <set_value name="$isPriorityWareForCargo" exact="false"/>
                  <do_if value="$pwForReorder? and $pwForReorder.count gt 0 and $utilWare?">
                    <do_all exact="$pwForReorder.count" counter="$pwc">
                      <set_value name="$pwcItem" exact="$pwForReorder.{$pwc}"/>
                      <do_if value="$pwcItem == $utilWare or ($pwcItem? and $pwcItem.id? and $utilWare.id? and $pwcItem.id == $utilWare.id)">
                        <set_value name="$isPriorityWareForCargo" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>

                  <do_if value="$tradeCargoVolume lt $requiredCargoVolume and not $isPriorityWareForCargo">
                    <set_value name="$tradesRejectedCargo" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by minimum cargo utilization filter:' +
                        '\n  Threshold: ' + $cargoUtilThresholdPct + '%' +
                        '\n  Actual: ' + $cargoUtilizationPct + '%' +
                        '\n  Amount: ' + $finalBuyAmount +
                        '\n  Volume/unit: ' + $utilVolumePerUnit +
                        '\n  Trade volume: ' + $tradeCargoVolume + ' / Capacity: ' + $shipCargoCapacityVol +
                        '\n  Search method: ' + $searchMethod +
                        '\n  Isolated mode: ' + $isIsolatedForCargoFilter +
                        '\n  â†’ Trying next trade in list...'" chance="100"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
                
                <!-- CRITICAL FIX: Always recalculate profit using live offer prices and final amount -->
                <!-- Cache is only a hint - market prices change constantly, so we must always validate -->
                <set_value name="$buyPriceForRecalc" exact="null"/>
                <set_value name="$sellPriceForRecalc" exact="null"/>
                
                <!-- Use actual offer prices only (no stored-price fallback). -->
                <do_if value="$currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.unitprice?">
                  <set_value name="$buyPriceForRecalc" exact="$currentTrade.$BuyOffer.unitprice"/>
                </do_if>
                
                <do_if value="$currentTrade.$SellOffer? and $currentTrade.$SellOffer.unitprice?">
                  <set_value name="$sellPriceForRecalc" exact="$currentTrade.$SellOffer.unitprice"/>
                </do_if>
                
                <!-- ALWAYS recalculate profit when prices are available (regardless of amount change) -->
                <!-- This ensures cached trades with wrong profit are caught and validated -->
                <set_value name="$amountChanged" exact="if $isSellOnlyTrade then ($finalSellAmount != $currentTrade.$Amount) else ($finalBuyAmount != $currentTrade.$Amount)"/>
                <set_value name="$finalProfitRAW" exact="null"/>
                <set_value name="$profitRecalculated" exact="false"/>
                
                <do_if value="$currentTrade.$Amount? and $buyPriceForRecalc? and $sellPriceForRecalc?">
                  <!-- Store original values before recalculation -->
                  <set_value name="$originalAmount" exact="$currentTrade.$Amount"/>
                  <set_value name="$originalProfitRAW" exact="if $currentTrade.$Profit? then $currentTrade.$Profit else 0"/>
                  
                  <!-- Calculate final amount for profit calculation -->
                  <set_value name="$finalAmountForProfit" exact="if $isSellOnlyTrade then $finalSellAmount else $finalBuyAmount"/>
                  
                  <!-- ALWAYS recalculate profit: (sellPrice - buyPrice) * finalAmount -->
                  <!-- This validates against current market prices, not cached values -->
                  <set_value name="$recalculatedProfitRAW" exact="($sellPriceForRecalc - $buyPriceForRecalc) * $finalAmountForProfit"/>
                  <set_value name="$finalProfitRAW" exact="$recalculatedProfitRAW"/>
                  <set_value name="$profitRecalculated" exact="true"/>
                  
                  <!-- Update trade object profit (for logbook display) -->
                  <set_value name="$currentTrade.$Profit" exact="$recalculatedProfitRAW"/>
                  
                  <!-- Also update prices in trade object if they were missing (for future use) -->
                  <do_if value="not $currentTrade.$BuyPrice?">
                    <set_value name="$currentTrade.$BuyPrice" exact="$buyPriceForRecalc"/>
                  </do_if>
                  <do_if value="not $currentTrade.$SellPrice?">
                    <set_value name="$currentTrade.$SellPrice" exact="$sellPriceForRecalc"/>
                  </do_if>
                  
                  <!-- PROFIT DEBUG: Log profit recalculation -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <set_value name="$priceSource" exact="if $currentTrade.$BuyPrice? then 'trade_object' else 'extracted_from_offers'"/>
                    <set_value name="$amountStatus" exact="if $amountChanged then 'YES (was ' + $originalAmount + ', now ' + $finalAmountForProfit + ')' else 'NO (unchanged: ' + $finalAmountForProfit + ')'"/>
                    <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') PROFIT RECALCULATION (ALWAYS):' + 
                      '\n  Ware: ' + $wareName +
                      '\n  Price Source: ' + $priceSource +
                      '\n  Amount Changed: ' + $amountStatus +
                      '\n  Original Amount: ' + $originalAmount + ' units' +
                      '\n  Final Amount: ' + $finalAmountForProfit + ' units' +
                      '\n  Original Profit (cached): ' + ($originalProfitRAW/100) + ' Cr (RAW: ' + $originalProfitRAW + ')' +
                      '\n  Recalculated Profit (validated): ' + ($recalculatedProfitRAW/100) + ' Cr (RAW: ' + $recalculatedProfitRAW + ')' +
                      '\n  Buy Price: ' + ($buyPriceForRecalc/100) + ' Cr (RAW: ' + $buyPriceForRecalc + ')' +
                      '\n  Sell Price: ' + ($sellPriceForRecalc/100) + ' Cr (RAW: ' + $sellPriceForRecalc + ')' +
                      '\n  Verification: (' + ($sellPriceForRecalc/100) + ' - ' + ($buyPriceForRecalc/100) + ') * ' + $finalAmountForProfit + ' = ' + (($sellPriceForRecalc - $buyPriceForRecalc) * $finalAmountForProfit / 100) + ' Cr'" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Prices missing - cannot recalculate profit, reject trade -->
                  <set_value name="$tradesRejectedProfit" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' REJECTED: Cannot validate profit' +
                      '\n  Ware: ' + $wareName +
                      '\n  Reason: Prices missing from trade object and offers, cannot recalculate/validate profit' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  <continue/>
                </do_else>
                
                <!-- MK4 supply price-cap validation:
                     reject only when supplier price exceeds customer buy price (negative final profit).
                     Zero-profit trades are valid for supply fulfillment. -->
                <do_if value="not $finalProfitRAW? or $finalProfitRAW lt 0">
                  <set_value name="$tradesRejectedProfit" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$wareName" exact="if $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.ware? then @$currentTrade.$BuyOffer.ware.name else (if $currentTrade.$SellOffer? and $currentTrade.$SellOffer.ware? then @$currentTrade.$SellOffer.ware.name else 'NULL')"/>
                    <set_value name="$profitStatus" exact="if not $finalProfitRAW? then 'NULL' else 'NEGATIVE (' + ($finalProfitRAW/100) + ' Cr)'"/>
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' REJECTED: Profit validation failed' +
                      '\n  Ware: ' + $wareName +
                      '\n  Final Profit (recalculated): ' + $profitStatus +
                      '\n  Reason: MK4 price-cap exceeded (supplier price greater than customer buy price)' +
                      '\n  â†’ Trying next trade in list...'" 
                      chance="100"/>
                  </do_if>
                  <continue/>
                </do_if>
                
                <!-- FINAL DOCKING VERIFICATION: lib.gt.dockcheck purpose=trade -->
                <set_value name="$finalDockingCheck" exact="true"/>
                
                <!-- Check buy station docking (for non-sell-only trades) -->
                <do_if value="not $isSellOnlyTrade and $finalDockingCheck and $buyStation?">
                  <run_script name="'lib.gt.dockcheck'" result="$mk4FinalBuyDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$buyStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <do_if value="not $mk4FinalBuyDockResult.$CanDock">
                    <set_value name="$finalDockingCheck" exact="false"/>
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' Final docking check FAILED (buy station): ' + @$buyStation.knownname + 
                        '\n  Sector: ' + @$buyStation.sector.knownname + 
                        '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- Check sell station docking -->
                <do_if value="$finalDockingCheck and $sellStation?">
                  <run_script name="'lib.gt.dockcheck'" result="$mk4FinalSellDockResult">
                    <param name="ship" value="this.ship"/>
                    <param name="station" value="$sellStation"/>
                    <param name="purpose" value="'trade'"/>
                    <param name="useMemo" value="true"/>
                  </run_script>
                  <do_if value="not $mk4FinalSellDockResult.$CanDock">
                    <set_value name="$finalDockingCheck" exact="false"/>
                    <set_value name="$tradesRejectedDocking" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' Final docking check FAILED (sell station): ' + @$sellStation.knownname + 
                        '\n  Sector: ' + @$sellStation.sector.knownname + 
                        '\n  Reason: No compatible trading dock for ship size ' + this.ship.docksize +
                        '\n  â†’ Trying next trade in list...'" 
                        chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- If final docking check failed, continue to next trade -->
                <do_if value="not $finalDockingCheck">
                  <continue/>
                </do_if>
                
                <!-- Buildstorage enforcement (inside loop so rejected trades try next) -->
                <do_if value="$enfIgnoreBuildStorage">
                  <set_value name="$_buyIsBuildStorage" exact="false"/>
                  <do_if value="$buyStation?">
                    <set_value name="$_buyIsBuildStorage" exact="$buyStation.isclass.buildstorage"/>
                  </do_if>
                  <set_value name="$_sellIsBuildStorage" exact="false"/>
                  <do_if value="$sellStation?">
                    <set_value name="$_sellIsBuildStorage" exact="$sellStation.isclass.buildstorage"/>
                  </do_if>
                  <do_if value="$_buyIsBuildStorage or $_sellIsBuildStorage">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by buildstorage restriction (buy=' + $_buyIsBuildStorage + ', sell=' + $_sellIsBuildStorage + ') â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'buildstorage_blocked']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>
                
                <!-- Carrier/Aux enforcement (inside loop so rejected trades try next) -->
                <!-- Vanilla pattern: carriers = type==shiptype.carrier, aux = primarypurpose==purpose.auxiliary -->
                <!-- Do NOT use purpose.fight â€” that catches wharfs/shipyards (they build combat ships) -->
                <do_if value="$enfIgnoreCarrierAux">
                  <set_value name="$_rejectCarrierAux" exact="false"/>
                  <do_if value="$buyStation?">
                    <do_if value="@$buyStation.type == shiptype.carrier or @$buyStation.primarypurpose == purpose.auxiliary">
                      <set_value name="$_rejectCarrierAux" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_if value="not $_rejectCarrierAux and $sellStation?">
                    <do_if value="@$sellStation.type == shiptype.carrier or @$sellStation.primarypurpose == purpose.auxiliary">
                      <set_value name="$_rejectCarrierAux" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_if value="$_rejectCarrierAux">
                    <set_value name="$tradesRejectedRestriction" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by carrier/aux restriction â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'carrier_aux_blocked']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- MK3 faction blacklist enforcement in validation loop:
                     blocked entries must be skipped here (not only at final gate), otherwise
                     trade 1 can abort the whole cycle without trying trade 2..N. -->
                <do_if value="$mk3FactionBlacklistLoop.keys.count gt 0">
                  <set_value name="$_mk3BlockedTrade" exact="false"/>
                  <set_value name="$_mk3BlockedSide" exact="''"/>
                  <set_value name="$_mk3BlockedFaction" exact="null"/>

                  <do_if value="not $isSellOnlyTrade and $currentTrade.$BuyOffer? and $currentTrade.$BuyOffer.owner?">
                    <set_value name="$_mk3BuyOwnerContainer" exact="@$currentTrade.$BuyOffer.owner"/>
                    <do_if value="$_mk3BuyOwnerContainer.owner?">
                      <set_value name="$_mk3BuyFaction" exact="$_mk3BuyOwnerContainer.owner"/>
                    </do_if>
                    <do_else>
                      <set_value name="$_mk3BuyFaction" exact="$_mk3BuyOwnerContainer"/>
                    </do_else>
                    <do_if value="$_mk3BuyFaction? and $mk3FactionBlacklistLoop.{$_mk3BuyFaction}?">
                      <set_value name="$_mk3BlockedTrade" exact="true"/>
                      <set_value name="$_mk3BlockedSide" exact="'buy'"/>
                      <set_value name="$_mk3BlockedFaction" exact="$_mk3BuyFaction"/>
                    </do_if>
                  </do_if>

                  <do_if value="not $_mk3BlockedTrade and $currentTrade.$SellOffer? and $currentTrade.$SellOffer.owner?">
                    <set_value name="$_mk3SellOwnerContainer" exact="@$currentTrade.$SellOffer.owner"/>
                    <do_if value="$_mk3SellOwnerContainer.owner?">
                      <set_value name="$_mk3SellFaction" exact="$_mk3SellOwnerContainer.owner"/>
                    </do_if>
                    <do_else>
                      <set_value name="$_mk3SellFaction" exact="$_mk3SellOwnerContainer"/>
                    </do_else>
                    <do_if value="$_mk3SellFaction? and $mk3FactionBlacklistLoop.{$_mk3SellFaction}?">
                      <set_value name="$_mk3BlockedTrade" exact="true"/>
                      <set_value name="$_mk3BlockedSide" exact="'sell'"/>
                      <set_value name="$_mk3BlockedFaction" exact="$_mk3SellFaction"/>
                    </do_if>
                  </do_if>

                  <do_if value="$_mk3BlockedTrade">
                    <set_value name="$tradesBlacklisted" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by MK3 faction blacklist (' + $_mk3BlockedSide + ' faction): ' + (if $_mk3BlockedFaction? then $_mk3BlockedFaction.name else 'Unknown') + ' â†’ Trying next trade...'" chance="100"/>
                    </do_if>
                    <do_if value="$searchMethod == 'cache'">
                      <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'mk3_faction_blacklist']"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- Trade-rule enforcement: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
                <do_if value="not (if this.$effectiveIgnoreTradeRules? then this.$effectiveIgnoreTradeRules else false) and not $isSellOnlyTrade">
                  <set_value name="$_applyTradeRules" exact="false"/>
                  <do_if value="$buyStation? and @$buyStation.exists">
                    <do_if value="@$buyStation.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_if>
                    <do_elseif value="@$buyStation.isclass.buildstorage and $buyStation.base? and @$buyStation.base.exists and @$buyStation.base.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $_applyTradeRules and $sellStation? and @$sellStation.exists">
                    <do_if value="@$sellStation.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_if>
                    <do_elseif value="@$sellStation.isclass.buildstorage and $sellStation.base? and @$sellStation.base.exists and @$sellStation.base.isplayerowned">
                      <set_value name="$_applyTradeRules" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="$_applyTradeRules">
                    <set_value name="$_tradeRuleBlocked" exact="false"/>
                    <set_value name="$_tradeRuleReason" exact="''"/>
                    <do_if value="$currentTrade.$SellOffer? and $buyStation? and $buyStation.exists and not $currentTrade.$SellOffer.cantradewith.{$buyStation}">
                      <set_value name="$_tradeRuleBlocked" exact="true"/>
                      <set_value name="$_tradeRuleReason" exact="'customer ' + @$sellStation.knownname + ' disallows source ' + @$buyStation.knownname"/>
                    </do_if>
                    <do_if value="not $_tradeRuleBlocked and $currentTrade.$BuyOffer? and $sellStation? and $sellStation.exists and not $currentTrade.$BuyOffer.cantradewith.{$sellStation}">
                      <set_value name="$_tradeRuleBlocked" exact="true"/>
                      <set_value name="$_tradeRuleReason" exact="'source ' + @$buyStation.knownname + ' disallows delivery to ' + @$sellStation.knownname"/>
                    </do_if>
                    <do_if value="$_tradeRuleBlocked">
                      <set_value name="$tradesRejectedRestriction" operation="add"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' rejected by trade rules (' + $_tradeRuleReason + ') â†’ Trying next trade...'" chance="100"/>
                      </do_if>
                      <do_if value="$searchMethod == 'cache'">
                        <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$currentTrade.$BuyOffer, $SellOffer = @$currentTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'trade_rules_failed']"/>
                      </do_if>
                      <continue/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- All checks passed including clamping and final docking verification - this trade is valid -->
                <set_value name="$validTradesFound" operation="add"/>
                <!-- Persist clamped amounts on candidate so fallback retries can reuse validated values. -->
                <set_value name="$currentTrade.$FinalBuyAmount" exact="$finalBuyAmount"/>
                <set_value name="$currentTrade.$FinalSellAmount" exact="$finalSellAmount"/>
                <!-- Keep a bounded, prevalidated candidate window (MK4 maxTrades) for immediate same-cycle retries. -->
                <do_if value="$validatedTradeCandidates.count lt $validatedCandidateLimit">
                  <set_value name="$mk4PairAlreadyInWindow" exact="false"/>
                  <do_all exact="$validatedTradeCandidates.count" counter="$vdci">
                    <set_value name="$vdc" exact="$validatedTradeCandidates.{$vdci}"/>
                    <set_value name="$mk4VdcPairMatch" exact="false"/>
                    <do_if value="$vdc.$SellOffer == $currentTrade.$SellOffer">
                      <do_if value="$isSellOnlyTrade and $vdc.$IsSellOnly? and $vdc.$IsSellOnly">
                        <set_value name="$mk4VdcPairMatch" exact="true"/>
                      </do_if>
                      <do_elseif value="$vdc.$BuyOffer? and $currentTrade.$BuyOffer? and $vdc.$BuyOffer == $currentTrade.$BuyOffer">
                        <set_value name="$mk4VdcPairMatch" exact="true"/>
                      </do_elseif>
                    </do_if>
                    <do_if value="$mk4VdcPairMatch">
                      <set_value name="$mk4PairAlreadyInWindow" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                  <do_if value="not $mk4PairAlreadyInWindow">
                    <append_to_list name="$validatedTradeCandidates" exact="$currentTrade"/>
                  </do_if>
                </do_if>

                <!-- Keep selection stable: first valid candidate in ordered list stays primary.
                     We still finish the full sweep for diagnostics and fallback candidate capture. -->
                <do_if value="not $validTradeFound">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' is VALID - selected as primary candidate'" chance="100"/>
                  </do_if>
                  <set_value name="$validTradeFound" exact="true"/>
                  <set_value name="$pendingTrade" exact="$currentTrade"/>
                  <set_value name="$selectedTradeIdx" exact="if $tradeIdxSafe? then $tradeIdxSafe else 0"/>
                  <set_value name="$selectedCurrentSectorIsBlacklisted" exact="$currentSectorIsBlacklisted"/>

                  <!-- Create fleet reservation (restored from pre-migration gt_trading_search.xml).
                       Prevents other ships from selecting this trade during the search-to-execution gap.
                       TTL=10s matches original release version. Cleared after create_trade_order (native takes over). -->
                  <do_if value="global.$GT_Reservations? and $currentTrade.$SellOffer?">
                    <set_value name="global.$GT_Reservations.{$currentTrade.$SellOffer}" exact="table[
                      $Ship = this.ship,
                      $Until = player.age + 10s,
                      $Amount = if $finalSellAmount? and $finalSellAmount gt 0 then $finalSellAmount else (if $pendingTrade.$Amount? and $pendingTrade.$Amount gt 0 then $pendingTrade.$Amount else 1)
                    ]"/>
                    <!-- Store reservation key on instance for cleanup in on_abort -->
                    <set_value name="this.$activeReservationKey" exact="$currentTrade.$SellOffer"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet reservation CREATED (TTL=10s, key=SellOffer)'" chance="100"/>
                    </do_if>
                    <!-- Update reservation stats -->
                    <do_if value="global.$GT_ReservationStats?">
                      <set_value name="global.$GT_ReservationStats.$Active" operation="add"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade ' + $tradeIdxSafe + '/' + $tradeListCountSafe + ' is VALID - kept as fallback candidate (primary already selected)'" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
              <do_else>
                <!-- Ware couldn't be extracted - skip this trade -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade ' + (if $tradeIdx? then $tradeIdx else 0) + ' SKIPPED: Could not extract ware from trade data'" chance="100"/>
                </do_if>
                <continue/>
              </do_else>
            </do_if>
          
          <!-- Skip trade if currentTrade is null -->
          <do_else>
            <!-- Don't access $tradeIdx here - it might not exist if loop didn't execute -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade SKIPPED: Trade data is null'" chance="100"/>
            </do_if>
            <!-- Only use continue if we're actually in the loop -->
            <do_if value="$tradeIdx?">
              <continue/>
            </do_if>
          </do_else>
          </do_all>
        </do_if>
        <do_else>
          <!-- Trade list is empty or null - no trades to validate -->
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  Trade list is empty or null - no trades to validate'" chance="100"/>
          <set_value name="$validTradeFound" exact="false"/>
        </do_else>
        
        <!-- After loop: Check if we found a valid trade -->
        <!-- Use safe access and check existence before accessing -->
        <do_if value="$validTradeFound? and $validTradeFound">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Validation PASSED - creating trade orders (checked ' + $tradesChecked + ' trades, valid=' + $validTradesFound + ', fallbackWindow=' + $validatedTradeCandidates.count + '/' + $validatedCandidateLimit + ', ' + $tradesRejectedPath + ' unreachable, ' + $tradesRejectedDocking + ' docking denied, ' + $tradesRejectedDistance + ' distance exceeded, ' + $tradesRejectedCargo + ' insufficient cargo, ' + $tradesBlacklisted + ' blacklisted, ' + $tradesRejectedRestriction + ' restriction blocked)'" chance="100"/>
          </do_if>
          
          <!-- Update pending trade entry with ACTUAL trade being executed -->
          <!-- Failure handler expects table with $BuyStation, $SellStation, $Ware -->
          <!-- Replace trade list with specific trade data for failure tracking -->
          <!-- Handle sell-only trades (BuyOffer may be null) -->
          <!-- Extract values from pendingTrade since loop variables may be out of scope -->
          <set_value name="$isSellOnlyTradeForPending" exact="false"/>
          <do_if value="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly">
            <set_value name="$isSellOnlyTradeForPending" exact="true"/>
          </do_if>
          
          <!-- Extract stations from pendingTrade (may have been set in loop, but extract to be safe) -->
          <set_value name="$buyStationForPending" exact="null"/>
          <set_value name="$sellStationForPending" exact="null"/>
          <do_if value="$pendingTrade.$BuyStation?">
            <set_value name="$buyStationForPending" exact="$pendingTrade.$BuyStation"/>
          </do_if>
          <do_elseif value="$pendingTrade.$BuyOffer?">
            <set_value name="$buyStationForPending" exact="@$pendingTrade.$BuyOffer.owner"/>
          </do_elseif>
          <do_else>
            <!-- Use loop variable if available, otherwise null (for sell-only trades) -->
            <set_value name="$buyStationForPending" exact="$buyStation"/>
          </do_else>
          
          <do_if value="$pendingTrade.$SellStation?">
            <set_value name="$sellStationForPending" exact="$pendingTrade.$SellStation"/>
          </do_if>
          <do_elseif value="$pendingTrade.$SellOffer?">
            <set_value name="$sellStationForPending" exact="@$pendingTrade.$SellOffer.owner"/>
          </do_elseif>
          <do_else>
            <!-- Use loop variable if available -->
            <set_value name="$sellStationForPending" exact="$sellStation"/>
          </do_else>
          
          <set_value name="$wareForPendingTrade" exact="null"/>
          <do_if value="$isSellOnlyTradeForPending and $pendingTrade.$Ware?">
            <set_value name="$wareForPendingTrade" exact="$pendingTrade.$Ware"/>
          </do_if>
          <do_elseif value="$pendingTrade.$BuyOffer?">
            <set_value name="$wareForPendingTrade" exact="@$pendingTrade.$BuyOffer.ware"/>
          </do_elseif>
          <!-- With full-sweep validation, loop locals no longer necessarily point to
               the selected trade. Restore canonical context from selected snapshot. -->
          <set_value name="$buyStation" exact="$buyStationForPending"/>
          <set_value name="$sellStation" exact="$sellStationForPending"/>
          <set_value name="$currentSectorIsBlacklisted" exact="$selectedCurrentSectorIsBlacklisted"/>
          <set_value name="$buySector" exact="if $buyStationForPending? then $buyStationForPending.sector else this.ship.sector"/>
          <set_value name="$sellSector" exact="if $sellStationForPending? then $sellStationForPending.sector else this.ship.sector"/>
          
          <!-- Store the ACTIVE trade for failure tracking (do NOT overwrite the pending-results list). -->
          <do_if value="not global.$GT_ActiveTrade?">
            <set_value name="global.$GT_ActiveTrade" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_ActiveTrade.{this.ship}" exact="table[
            $BuyStation = $buyStationForPending,
            $SellStation = $sellStationForPending,
            $Ware = $wareForPendingTrade
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$buyStationNameForDebug" exact="if $isSellOnlyTradeForPending then 'N/A (sell-only)' else (if $buyStationForPending? then @$buyStationForPending.knownname else 'Unknown')"/>
            <set_value name="$sellStationNameForDebug" exact="if $sellStationForPending? then @$sellStationForPending.knownname else 'Unknown'"/>
            <set_value name="$wareNameForDebug" exact="if $wareForPendingTrade? then @$wareForPendingTrade.name else 'Unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Updated pending trade entry for failure tracking:' +
              '\n  Buy: ' + $buyStationNameForDebug +
              '\n  Sell: ' + $sellStationNameForDebug +
              '\n  Ware: ' + $wareNameForDebug"
              chance="100"/>
          </do_if>
          
          <!-- Final offer validity check and clamping moved inside loop -->
          <!-- Offers are validated and clamped before breaking out of the loop -->
          <!-- Final docking verification also moved inside loop - allows trying next trade if docking fails -->
          <!-- All checks passed including final docking verification (checked in loop) - safe to create orders with clamped amounts -->
          <!-- Clamped amounts are stored in $pendingTrade.$FinalBuyAmount and $pendingTrade.$FinalSellAmount -->
          <!-- Create X4 native TradePerform orders with blacklist routing -->
          <!-- CRITICAL: internal="true" is REQUIRED for vanilla to track pending trades and display count -->
          <!-- Without internal="true", vanilla won't set $internalorder in TradePerform, and pending trades won't be displayed -->
          <!-- For sell-only trades, skip buy order (ship already has cargo) -->
          <set_value name="$finalBuyAmount" exact="if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount"/>
          <set_value name="$finalSellAmount" exact="if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount"/>
          
          <!-- Re-resolve MK3 faction blacklist at final stage (path-independent safety). -->
          <set_value name="$mk3BlacklistOwnerFinal" exact="this.ship"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$mk3BlacklistOwnerFinal" exact="this.ship.commander"/>
          </do_if>
          <set_value name="$mk3FactionBlacklistFinal" exact="table[]"/>
          <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerFinal}?">
            <set_value name="$mk3FactionBlacklistFinal" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerFinal}"/>
          </do_if>
          
          <!-- CRITICAL FIX: Final validation immediately before order creation -->
          <!-- This catches cases where trade rules changed between earlier validation and order creation -->
          <!-- Re-check offers with tradepartner to ensure trade rules are still respected -->
          <set_value name="$finalBuyOfferValid" exact="true"/>
          <set_value name="$finalSellOfferValid" exact="true"/>
          <set_value name="$finalMK3BlacklistValid" exact="true"/>
          <set_value name="$finalRouteIllegalValid" exact="true"/>
          
          <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer?">
            <set_value name="$finalBuyStation" exact="if $pendingTrade.$BuyStation? then $pendingTrade.$BuyStation else (if $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner else null)"/>
            <set_value name="$finalBuyWare" exact="if $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else null"/>
            
            <do_if value="$finalBuyStation? and $finalBuyStation.exists and $finalBuyWare != null">
              <find_sell_offer seller="$finalBuyStation" wares="$finalBuyWare" tradepartner="this.ship" result="$finalValidatedBuyOffer"/>
              <do_if value="not $finalValidatedBuyOffer.available">
                <set_value name="$finalBuyOfferValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - Buy offer invalid (trade rules?) - station: ' + @$finalBuyStation.knownname + ', ware: ' + @$finalBuyWare.name" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
          
          <do_if value="$pendingTrade.$SellOffer?">
            <set_value name="$finalSellStation" exact="if $pendingTrade.$SellStation? and @$pendingTrade.$SellStation.exists then $pendingTrade.$SellStation else (if $pendingTrade.$SellOffer.buyer? and @$pendingTrade.$SellOffer.buyer.exists then @$pendingTrade.$SellOffer.buyer else (if $pendingTrade.$SellOffer.owner? and @$pendingTrade.$SellOffer.owner.exists then @$pendingTrade.$SellOffer.owner else null))"/>
            <set_value name="$finalSellWare" exact="if $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else (if $pendingTrade.$Ware? then $pendingTrade.$Ware else null)"/>
            <!-- Build-storage delivery refs die between clamp and order creation too; re-discover the live
                 delivery (base anchor, then player buy offer by sell sector + ware matching the stable
                 delivery idcode) so create_order gets a live offer. Mirrors lib.gt.mk42.cache.search. -->
            <do_if value="(not $finalSellStation? or not @$finalSellStation.exists) and $pendingTrade.$SellStationBase? and @$pendingTrade.$SellStationBase.exists and @$pendingTrade.$SellStationBase.buildstorage and @$pendingTrade.$SellStationBase.buildstorage.exists">
              <set_value name="$finalSellStation" exact="@$pendingTrade.$SellStationBase.buildstorage"/>
            </do_if>
            <!-- A build-storage component handle churns each construction tick but can still report
                 .exists=true with stale offers; always re-discover the live offer by sector + idcode. -->
            <set_value name="$finalForceBsRescan" exact="(not $finalSellStation? or not @$finalSellStation.exists) or (@$finalSellStation.exists and @$finalSellStation.isclass.buildstorage) or ($pendingTrade.$SellStationBase? and @$pendingTrade.$SellStationBase.exists and $pendingTrade.$SellStationBase.buildstorage?)"/>
            <set_value name="$finalBsBuyer" exact="null"/>
            <set_value name="$finalRePick" exact="null"/>
            <do_if value="$finalForceBsRescan and $pendingTrade.$SellSector? and @$pendingTrade.$SellSector.exists and $finalSellWare != null and $pendingTrade.$DeliveryStationId?">
              <!-- Re-resolve the live build-storage buy offer with the PROVEN MK4-2 player buy-offer query
                   (lib.gt.mk42.live.search.xml ~1368): bare <offeramount min="1"/> (NO tradepartner) so the
                   engine reads the build storage's desiredamount; tradepartner=ship would force the money path
                   that reads 0 funds-amount -> false buyer_missing. Disambiguate by stable base idcode. -->
              <find_buy_offer wares="$finalSellWare" space="$pendingTrade.$SellSector" result="$finalBsOffers" multiple="true">
                <match_buyer tradesknownto="this.ship.owner" owner="faction.player">
                  <match_relation_to object="this.ship" relation="dock" comparison="ge"/>
                  <match_relation_to faction="this.ship.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <offeramount min="1"/>
              </find_buy_offer>
              <do_if value="$finalBsOffers? and $finalBsOffers.count gt 0">
                <do_for_each name="$finalBsO" in="$finalBsOffers">
                  <do_if value="not ($finalRePick? and @$finalRePick.exists) and $finalBsO? and @$finalBsO.exists">
                    <set_value name="$finalBsCand" exact="null"/>
                    <do_if value="$finalBsO.buyer? and @$finalBsO.buyer.exists">
                      <set_value name="$finalBsCand" exact="@$finalBsO.buyer"/>
                    </do_if>
                    <do_elseif value="$finalBsO.owner? and @$finalBsO.owner.exists">
                      <set_value name="$finalBsCand" exact="@$finalBsO.owner"/>
                    </do_elseif>
                    <do_if value="$finalBsCand? and @$finalBsCand.exists">
                      <set_value name="$finalBsCandId" exact="if @$finalBsCand.isclass.buildstorage and $finalBsCand.base? and @$finalBsCand.base.exists then @$finalBsCand.base.idcode else @$finalBsCand.idcode"/>
                      <do_if value="$finalBsCandId == $pendingTrade.$DeliveryStationId">
                        <set_value name="$finalRePick" exact="$finalBsO"/>
                        <set_value name="$finalBsBuyer" exact="$finalBsCand"/>
                        <set_value name="$finalSellStation" exact="$finalBsCand"/>
                        <set_value name="$pendingTrade.$SellStation" exact="$finalBsCand"/>
                        <set_value name="$pendingTrade.$SellOffer" exact="$finalBsO"/>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_for_each>
              </do_if>
            </do_if>
            
            <do_if value="$finalSellStation? and $finalSellStation.exists and $finalSellWare != null">
              <set_value name="$finalValidatedSellOffer" exact="null"/>
              <do_if value="@$finalSellStation.isclass.buildstorage">
                <!-- Build storage already re-resolved above; reuse that live offer. -->
                <do_if value="$pendingTrade.$SellOffer? and @$pendingTrade.$SellOffer.exists">
                  <set_value name="$finalValidatedSellOffer" exact="@$pendingTrade.$SellOffer"/>
                </do_if>
              </do_if>
              <do_else>
                <find_buy_offer buyer="$finalSellStation" wares="$finalSellWare" tradepartner="this.ship" result="$finalValidatedSellOffer"/>
              </do_else>
              <set_value name="$finalSellEffectiveAmount" exact="0"/>
              <do_if value="$finalValidatedSellOffer?">
                <set_value name="$pendingTrade.$SellOffer" exact="$finalValidatedSellOffer"/>
                <set_value name="$finalSellEffectiveAmount" exact="@$finalValidatedSellOffer.offeramount.{this.ship}"/>
                <do_if value="(not $finalSellEffectiveAmount? or $finalSellEffectiveAmount le 0) and @$finalValidatedSellOffer.amount gt 0">
                  <set_value name="$finalSellEffectiveAmount" exact="@$finalValidatedSellOffer.amount"/>
                </do_if>
              </do_if>
              <do_if value="not $finalSellEffectiveAmount? or $finalSellEffectiveAmount le 0">
                <set_value name="$finalSellDemandFallback" exact="[0, $finalSellStation.cargo.{$finalSellWare}.target - $finalSellStation.cargo.{$finalSellWare}.count].max"/>
                <do_if value="$finalSellDemandFallback gt 0">
                  <set_value name="$finalSellEffectiveAmount" exact="$finalSellDemandFallback"/>
                </do_if>
              </do_if>
              <do_if value="not $finalSellEffectiveAmount? or $finalSellEffectiveAmount le 0">
                <set_value name="$finalSellOfferValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - Sell offer invalid (trade rules?) - station: ' + @$finalSellStation.knownname + ', ware: ' + @$finalSellWare.name" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>

          <!-- NOTE: Trade-rule sourcing enforcement (customer/source cantradewith) now runs inside the
               main validation loop, so every violating cache trade is rejected+flagged in one pass and
               the "all cached trades rejected -> force live search" escalation fires. It is intentionally
               NOT repeated here to avoid the late-stage single-candidate retry loop. -->

          <!-- Final MK3 faction blacklist safety net (applies to all sources: cache/live/fallback). -->
          <do_if value="$mk3FactionBlacklistFinal.keys.count gt 0">
            <set_value name="$finalBuyFaction" exact="null"/>
            <set_value name="$finalSellFaction" exact="null"/>

            <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner?">
              <set_value name="$finalBuyOwnerContainer" exact="@$pendingTrade.$BuyOffer.owner"/>
              <do_if value="$finalBuyOwnerContainer.owner?">
                <set_value name="$finalBuyFaction" exact="$finalBuyOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$finalBuyFaction" exact="$finalBuyOwnerContainer"/>
              </do_else>
            </do_if>

            <do_if value="$pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner?">
              <set_value name="$finalSellOwnerContainer" exact="@$pendingTrade.$SellOffer.owner"/>
              <do_if value="$finalSellOwnerContainer.owner?">
                <set_value name="$finalSellFaction" exact="$finalSellOwnerContainer.owner"/>
              </do_if>
              <do_else>
                <set_value name="$finalSellFaction" exact="$finalSellOwnerContainer"/>
              </do_else>
            </do_if>

            <do_if value="$finalBuyFaction? and $mk3FactionBlacklistFinal.{$finalBuyFaction}?">
              <set_value name="$finalMK3BlacklistValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL MK3 blacklist block (buy faction): ' + $finalBuyFaction.name" chance="100"/>
              </do_if>
            </do_if>
            <do_if value="$finalMK3BlacklistValid and $finalSellFaction? and $mk3FactionBlacklistFinal.{$finalSellFaction}?">
              <set_value name="$finalMK3BlacklistValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL MK3 blacklist block (sell faction): ' + $finalSellFaction.name" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Final illegal-route safety net (path can change between scoring and order creation). -->
          <set_value name="$finalRouteWare" exact="if $pendingTrade.$Ware? then $pendingTrade.$Ware else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware else null))"/>
          <do_if value="$effectiveAllowIllegal and $effectiveEnforceRouteIllegalLegality and @$finalRouteWare.illegal gt 0">
            <set_value name="$finalRouteBuySector" exact="this.ship.sector"/>
            <do_if value="not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner?">
              <set_value name="$finalRouteBuySector" exact="@$pendingTrade.$BuyOffer.owner.sector"/>
            </do_if>
            <set_value name="$finalRouteSellSector" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.sector else null"/>
            <run_script name="'lib.gt.pathfinding'" result="$finalRouteLegality">
              <param name="mode" value="'route_legality'"/>
              <param name="ship" value="this.ship"/>
              <param name="homeSector" value="$searchHomeSector"/>
              <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
              <param name="allowIllegal" value="$effectiveAllowIllegal"/>
              <param name="enforceRouteIllegalLegality" value="$effectiveEnforceRouteIllegalLegality"/>
              <param name="startSector" value="this.ship.sector"/>
              <param name="buySector" value="$finalRouteBuySector"/>
              <param name="sellSector" value="$finalRouteSellSector"/>
              <param name="ware" value="$finalRouteWare"/>
            </run_script>
            <do_if value="not $finalRouteLegality.$IsLegal">
              <set_value name="$finalRouteIllegalValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL ILLEGAL ROUTE BLOCK: route changed or sector legality mismatch before order creation'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- If final validation failed, abort order creation -->
          <do_if value="not $finalBuyOfferValid or not $finalSellOfferValid or not $finalMK3BlacklistValid or not $finalRouteIllegalValid">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': FINAL VALIDATION FAILED - safety check blocked trade immediately before order creation'" chance="100"/>
            </do_if>
            <!-- Scenario 3: Flag ship-specific failure â€” final validation uses tradepartner="this.ship",
                 so trade rules are ship-specific. Another ship may still pass. -->
            <do_if value="$searchMethod == 'cache'">
              <signal_objects object="player.galaxy" param="'GT_Cache_Flag_Ship'" param2="table[$Ship = this.ship, $BuyOffer = @$pendingTrade.$BuyOffer, $SellOffer = @$pendingTrade.$SellOffer, $HomeSector = $searchHomeSector, $CachePool = 'mk42', $Reason = 'trade_rules_failed']"/>
            </do_if>

            <!-- Do not abort the full cycle on late failure: remove failed candidate and retry remaining list. -->
            <set_value name="$remainingTrades" exact="[]"/>
            <!-- Prefer already validated fallback window (bounded by MK4 maxTrades).
                 If unavailable, fall back to raw trade list minus selected candidate. -->
            <do_if value="$validatedTradeCandidates? and $validatedTradeCandidates.count gt 1">
              <do_all exact="$validatedTradeCandidates.count" counter="$rtIdx">
                <do_if value="$rtIdx gt 1">
                  <append_to_list name="$remainingTrades" exact="$validatedTradeCandidates.{$rtIdx}"/>
                </do_if>
              </do_all>
            </do_if>
            <do_elseif value="$tradeList? and $tradeList.count gt 0">
              <do_all exact="$tradeList.count" counter="$rtIdx">
                <do_if value="$rtIdx != $selectedTradeIdx">
                  <append_to_list name="$remainingTrades" exact="$tradeList.{$rtIdx}"/>
                </do_if>
              </do_all>
            </do_elseif>
            <do_if value="$remainingTrades.count gt 0">
              <set_value name="this.$tradeListFromSignal" exact="$remainingTrades"/>
              <set_value name="this.$searchMethodFromSignal" exact="if $searchMethod? and $searchMethod != '' then $searchMethod else 'signal'"/>
              <set_value name="this.$tradeFoundViaInterrupt" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Retrying validation with remaining candidates after final validation failure (remaining=' + $remainingTrades.count + ', source=' + (if $validatedTradeCandidates? and $validatedTradeCandidates.count gt 1 then 'prevalidated_window' else 'raw_trade_list') + ')'" chance="100"/>
              </do_if>
              <resume label="trade_found"/>
            </do_if>
            <do_else>
              <signal_objects object="this.ship" param="'GT_No_Trade_Found'" param2="'trade_rules_violation'"/>
              <return/>
            </do_else>
          </do_if>
          
          <!-- Offers valid - proceed with order creation -->
          <!-- MK4 internal economics (Â§1.4.1): per-leg internal="true" when the counterparty is
               player-owned so wares move without credit transfer (build storage with no funds,
               player-supplier buys). Foreign supplier legs stay internal="false". MK2 parity. -->

          <!-- Phase 2 (MK4 multitrade):
               Build route in MK1 style:
               - prepare unique valid candidates
               - prefer one full-threshold single trade when available
               - otherwise expand secondaries iteratively with backtrack clustering
                 and budget checks. -->
          <create_list name="$mk4QueueableTrades"/>
          <create_list name="$mk4PreparedCandidates"/>
          <set_value name="$mk4QueueBudgetMoney" exact="player.money"/>
          <set_value name="$mk4QueueMinMoney" exact="if this.$minPlayerMoney? then this.$minPlayerMoney else 1000"/>
          <set_value name="$mk4QueueSourceCount" exact="0"/>
          <set_value name="$mk4PrimaryBudgetBlocked" exact="false"/>
          <!-- TRUE only when the primary leg fails for a genuine money reason (cannot afford even
               1 unit above MinPlayerMoney). Non-money blocks (zero pair amount, destination
               capacity exhausted, no candidate) leave this false so they do NOT raise the
               fleet-wide money cap. -->
          <set_value name="$mk4FleetMoneyInsolvent" exact="false"/>
          <set_value name="$mk4SecondaryBudgetSkipped" exact="0"/>
          <set_value name="$mk4DestBudgetSkipped" exact="0"/>
          <set_value name="$mk4BacktrackSkipped" exact="0"/>
          <set_value name="$mk4DeliveryBudgetBySellOffer" exact="table[]"/>
          <set_value name="$mk4SupplierBudgetByBuyOffer" exact="table[]"/>
          <set_value name="$mk4SupBudgetSkipped" exact="0"/>
          <set_value name="$mk4ShipCargoBudgetByWare" exact="table[]"/>
          <set_value name="$mk4SinglePreferred" exact="false"/>
          <set_value name="$mk4UseMinCargoThresholdForRoute" exact="if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false)"/>
          <set_value name="$mk4ThresholdPctForSingle" exact="[10,[(if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)),100].min].max"/>
          <set_value name="$mk4CargoCapacityVolForSingle" exact="if this.ship.cargo.capacity.all? then this.ship.cargo.capacity.all else 0"/>
          <set_value name="$mk4MinLegVolume" exact="0"/>
          <do_if value="$mk4UseMinCargoThresholdForRoute and $mk4CargoCapacityVolForSingle gt 0">
            <set_value name="$mk4TargetVolumeForLeg" exact="($mk4ThresholdPctForSingle * $mk4CargoCapacityVolForSingle) / 100"/>
            <set_value name="$mk4MinLegVolume" exact="$mk4TargetVolumeForLeg / 3"/>
          </do_if>
          <set_value name="$mk4MinLegSkipped" exact="0"/>

          <!-- Normalize candidates once (amount clamps + pair dedupe). -->
          <do_if value="$validatedTradeCandidates? and $validatedTradeCandidates.count gt 0">
            <do_all exact="$validatedTradeCandidates.count" counter="$qci">
              <set_value name="$qt" exact="$validatedTradeCandidates.{$qci}"/>
              <set_value name="$qtIsSellOnly" exact="$qt.$IsSellOnly? and $qt.$IsSellOnly"/>
              <set_value name="$qtBuyAmount" exact="if $qt.$FinalBuyAmount? then $qt.$FinalBuyAmount else (if $qt.$Amount? then $qt.$Amount else 0)"/>
              <set_value name="$qtSellAmount" exact="if $qt.$FinalSellAmount? then $qt.$FinalSellAmount else (if $qt.$Amount? then $qt.$Amount else 0)"/>

              <set_value name="$qtSellOfferAmount" exact="0"/>
              <do_if value="$qt.$SellOffer? and $qt.$SellOffer.exists">
                <!-- Build-storage construction offers report offeramount.{ship}=0 (no money
                     changes hands), so clamping the already-validated sell amount to offeramount
                     would zero it, drop the trade here, and leave only normal-station trades in
                     the queue. The validated $FinalSellAmount already reflects construction
                     demand, so skip the offeramount clamp for build-storage deliveries. -->
                <set_value name="$qtSellIsBuildStorage" exact="false"/>
                <do_if value="$qt.$SellStation? and @$qt.$SellStation.exists and @$qt.$SellStation.isclass.buildstorage">
                  <set_value name="$qtSellIsBuildStorage" exact="true"/>
                </do_if>
                <do_elseif value="$qt.$SellOffer.buyer? and @$qt.$SellOffer.buyer.exists and @$qt.$SellOffer.buyer.isclass.buildstorage">
                  <set_value name="$qtSellIsBuildStorage" exact="true"/>
                </do_elseif>
                <do_elseif value="$qt.$SellOffer.owner? and @$qt.$SellOffer.owner.exists and @$qt.$SellOffer.owner.isclass.buildstorage">
                  <set_value name="$qtSellIsBuildStorage" exact="true"/>
                </do_elseif>
                <do_if value="not $qtSellIsBuildStorage">
                  <set_value name="$qtSellOfferAmount" exact="$qt.$SellOffer.offeramount.{this.ship}"/>
                  <do_if value="$qtSellOfferAmount == null">
                    <set_value name="$qtSellOfferAmount" exact="0"/>
                  </do_if>
                  <set_value name="$qtSellAmount" exact="[$qtSellAmount, $qtSellOfferAmount].min"/>
                </do_if>
              </do_if>
              <do_else>
                <continue/>
              </do_else>

              <do_if value="not $qtIsSellOnly">
                <set_value name="$qtBuyOfferAmount" exact="0"/>
                <do_if value="$qt.$BuyOffer? and $qt.$BuyOffer.exists">
                  <set_value name="$qtBuyOfferAmount" exact="$qt.$BuyOffer.offeramount.{this.ship}"/>
                  <do_if value="$qtBuyOfferAmount == null">
                    <set_value name="$qtBuyOfferAmount" exact="0"/>
                  </do_if>
                  <set_value name="$qtBuyAmount" exact="[$qtBuyAmount, $qtBuyOfferAmount].min"/>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
                <set_value name="$qtPairAmount" exact="[$qtBuyAmount, $qtSellAmount].min"/>
                <set_value name="$qtBuyAmount" exact="$qtPairAmount"/>
                <set_value name="$qtSellAmount" exact="$qtPairAmount"/>
              </do_if>
              <do_else>
                <set_value name="$qtPairAmount" exact="$qtSellAmount"/>
              </do_else>

              <do_if value="not $qtPairAmount? or $qtPairAmount le 0">
                <continue/>
              </do_if>

              <set_value name="$mk4PrepPairDuplicate" exact="false"/>
              <do_all exact="$mk4PreparedCandidates.count" counter="$ppi">
                <set_value name="$ppTrade" exact="$mk4PreparedCandidates.{$ppi}"/>
                <set_value name="$mk4PrepPairMatch" exact="false"/>
                <do_if value="$ppTrade.$SellOffer == $qt.$SellOffer">
                  <do_if value="$qtIsSellOnly and $ppTrade.$IsSellOnly? and $ppTrade.$IsSellOnly">
                    <set_value name="$mk4PrepPairMatch" exact="true"/>
                  </do_if>
                  <do_elseif value="$ppTrade.$BuyOffer? and $qt.$BuyOffer? and $ppTrade.$BuyOffer == $qt.$BuyOffer">
                    <set_value name="$mk4PrepPairMatch" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="$mk4PrepPairMatch">
                  <set_value name="$mk4PrepPairDuplicate" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="$mk4PrepPairDuplicate">
                <continue/>
              </do_if>

              <set_value name="$qt.$QueuedBuyAmount" exact="$qtBuyAmount"/>
              <set_value name="$qt.$QueuedSellAmount" exact="$qtSellAmount"/>
              <append_to_list name="$mk4PreparedCandidates" exact="$qt"/>
            </do_all>
          </do_if>
          <do_else>
            <set_value name="$pendingTrade.$QueuedBuyAmount" exact="$finalBuyAmount"/>
            <set_value name="$pendingTrade.$QueuedSellAmount" exact="$finalSellAmount"/>
            <append_to_list name="$mk4PreparedCandidates" exact="$pendingTrade"/>
          </do_else>

          <set_value name="$mk4QueueSourceCount" exact="if $mk4PreparedCandidates.count gt 0 then $mk4PreparedCandidates.count else 1"/>

          <!-- Prefer a single trade if it alone reaches threshold (MK1 parity). -->
          <set_value name="$mk4SingleThresholdCandidate" exact="null"/>
          <set_value name="$mk4SingleThresholdBestScore" exact="-999999"/>
          <set_value name="$mk4SingleThresholdFillPct" exact="0"/>
          <set_value name="$mk4SingleThresholdFound" exact="false"/>
          <do_if value="$mk4UseMinCargoThresholdForRoute and $mk4PreparedCandidates.count gt 1 and $mk4CargoCapacityVolForSingle gt 0">
            <do_all exact="$mk4PreparedCandidates.count" counter="$stci">
              <set_value name="$stTrade" exact="$mk4PreparedCandidates.{$stci}"/>
              <set_value name="$stIsSellOnly" exact="$stTrade.$IsSellOnly? and $stTrade.$IsSellOnly"/>
              <set_value name="$stBuyAmount" exact="if $stTrade.$QueuedBuyAmount? then $stTrade.$QueuedBuyAmount else (if $stTrade.$Amount? then $stTrade.$Amount else 0)"/>
              <set_value name="$stSellAmount" exact="if $stTrade.$QueuedSellAmount? then $stTrade.$QueuedSellAmount else (if $stTrade.$Amount? then $stTrade.$Amount else 0)"/>
              <set_value name="$stPairAmount" exact="if $stIsSellOnly then $stSellAmount else [$stBuyAmount, $stSellAmount].min"/>
              <do_if value="$stPairAmount le 0">
                <continue/>
              </do_if>
              <set_value name="$stBuyPrice" exact="if not $stIsSellOnly and $stTrade.$BuyOffer? and $stTrade.$BuyOffer.unitprice? then $stTrade.$BuyOffer.unitprice else 0"/>
              <set_value name="$stSupIsPlayer" exact="false"/>
              <do_if value="not $stIsSellOnly">
                <do_if value="$stTrade.$BuyStation? and $stTrade.$BuyStation.exists and $stTrade.$BuyStation.isplayerowned">
                  <set_value name="$stSupIsPlayer" exact="true"/>
                </do_if>
                <do_elseif value="$stTrade.$BuyOffer? and $stTrade.$BuyOffer.owner? and $stTrade.$BuyOffer.owner.exists and $stTrade.$BuyOffer.owner.isplayerowned">
                  <set_value name="$stSupIsPlayer" exact="true"/>
                </do_elseif>
              </do_if>
              <set_value name="$stPurchaseCost" exact="if $stIsSellOnly or $stSupIsPlayer then 0 else ($stBuyPrice * $stPairAmount)"/>
              <do_if value="$stPurchaseCost gt 0 and ($mk4QueueBudgetMoney - $stPurchaseCost) lt ($mk4QueueMinMoney)Cr">
                <do_if value="not $stIsSellOnly and $stBuyPrice gt 0 and not $stSupIsPlayer">
                  <set_value name="$stAvailableBudget" exact="$mk4QueueBudgetMoney - ($mk4QueueMinMoney)Cr"/>
                  <set_value name="$stAffordableUnits" exact="$stAvailableBudget / $stBuyPrice"/>
                  <do_if value="$stAffordableUnits ge 1">
                    <set_value name="$stPairAmount" exact="[$stPairAmount, $stAffordableUnits].min"/>
                  </do_if>
                  <do_else>
                    <continue/>
                  </do_else>
                </do_if>
                <do_else>
                  <continue/>
                </do_else>
              </do_if>
              <set_value name="$stVolumePerUnit" exact="if $stTrade.$Ware? and $stTrade.$Ware.volume? then $stTrade.$Ware.volume else 1"/>
              <set_value name="$stFillPct" exact="if $mk4CargoCapacityVolForSingle gt 0 then (($stPairAmount * $stVolumePerUnit * 100) / $mk4CargoCapacityVolForSingle) else 100"/>
              <set_value name="$stScore" exact="if $stTrade.$Score? then $stTrade.$Score else 0"/>
              <do_if value="$stFillPct ge $mk4ThresholdPctForSingle and (not $mk4SingleThresholdCandidate? or $stScore gt $mk4SingleThresholdBestScore)">
                <set_value name="$mk4SingleThresholdCandidate" exact="$stTrade"/>
                <set_value name="$mk4SingleThresholdBestScore" exact="$stScore"/>
                <set_value name="$mk4SingleThresholdFillPct" exact="$stFillPct"/>
                <set_value name="$mk4SingleThresholdFound" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$mk4SingleThresholdFound and $mk4SingleThresholdCandidate? and $mk4PreparedCandidates.count gt 1">
            <set_value name="$mk4SinglePreferred" exact="true"/>
            <create_list name="$mk4SinglePreferredTrades"/>
            <append_to_list name="$mk4SinglePreferredTrades" exact="$mk4SingleThresholdCandidate"/>
            <set_value name="$mk4PreparedCandidates" exact="$mk4SinglePreferredTrades"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 single-trade preference applied: fill=' + $mk4SingleThresholdFillPct + '% threshold=' + $mk4ThresholdPctForSingle + '% (multitrade deferred)'" chance="100"/>
            </do_if>
          </do_if>

          <!-- Clearance / sell-only: one buyer per cargo snapshot â€” multitrade would queue
               multiple sells for the same ware and cause ERR_NOTHING_TO_SELL on later legs. -->
          <do_if value="not $mk4SinglePreferred and $mk4PreparedCandidates.count gt 1 and $mk4PreparedCandidates.{1}.$IsSellOnly? and $mk4PreparedCandidates.{1}.$IsSellOnly">
            <set_value name="$mk4SinglePreferred" exact="true"/>
            <create_list name="$mk4SellOnlySingleTrades"/>
            <append_to_list name="$mk4SellOnlySingleTrades" exact="$mk4PreparedCandidates.{1}"/>
            <set_value name="$mk4PreparedCandidates" exact="$mk4SellOnlySingleTrades"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 sell-only single-leg enforced (clearance â€” multitrade deferred)'" chance="100"/>
            </do_if>
          </do_if>

          <set_value name="$mk4CargoCapacityVol" exact="if this.ship.cargo.capacity.all? then this.ship.cargo.capacity.all else 0"/>
          <set_value name="$mk4RemainingVolume" exact="$mk4CargoCapacityVol"/>
          <set_value name="$mk4CurrentFillPct" exact="0"/>
          <set_value name="$mk4PrimaryTrade" exact="if $mk4PreparedCandidates.count gt 0 then $mk4PreparedCandidates.{1} else null"/>

          <!-- Add primary trade with authoritative budget clamp. -->
          <do_if value="$mk4PrimaryTrade?">
            <set_value name="$pIsSellOnly" exact="$mk4PrimaryTrade.$IsSellOnly? and $mk4PrimaryTrade.$IsSellOnly"/>
            <set_value name="$pBuyAmount" exact="if $mk4PrimaryTrade.$QueuedBuyAmount? then $mk4PrimaryTrade.$QueuedBuyAmount else (if $mk4PrimaryTrade.$Amount? then $mk4PrimaryTrade.$Amount else 0)"/>
            <set_value name="$pSellAmount" exact="if $mk4PrimaryTrade.$QueuedSellAmount? then $mk4PrimaryTrade.$QueuedSellAmount else (if $mk4PrimaryTrade.$Amount? then $mk4PrimaryTrade.$Amount else 0)"/>
            <set_value name="$pPairAmount" exact="if $pIsSellOnly then $pSellAmount else [$pBuyAmount, $pSellAmount].min"/>
            <set_value name="$pBuyPrice" exact="if not $pIsSellOnly and $mk4PrimaryTrade.$BuyOffer? and $mk4PrimaryTrade.$BuyOffer.unitprice? then $mk4PrimaryTrade.$BuyOffer.unitprice else 0"/>
            <set_value name="$pSupIsPlayer" exact="false"/>
            <do_if value="not $pIsSellOnly">
              <do_if value="$mk4PrimaryTrade.$BuyStation? and $mk4PrimaryTrade.$BuyStation.exists and $mk4PrimaryTrade.$BuyStation.isplayerowned">
                <set_value name="$pSupIsPlayer" exact="true"/>
              </do_if>
              <do_elseif value="$mk4PrimaryTrade.$BuyOffer? and $mk4PrimaryTrade.$BuyOffer.owner? and $mk4PrimaryTrade.$BuyOffer.owner.exists and $mk4PrimaryTrade.$BuyOffer.owner.isplayerowned">
                <set_value name="$pSupIsPlayer" exact="true"/>
              </do_elseif>
            </do_if>
            <set_value name="$pPurchaseCost" exact="if $pIsSellOnly or $pSupIsPlayer then 0 else ($pBuyPrice * $pPairAmount)"/>
            <do_if value="$pPairAmount le 0">
              <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
            </do_if>
            <do_elseif value="$pPurchaseCost gt 0 and ($mk4QueueBudgetMoney - $pPurchaseCost) lt ($mk4QueueMinMoney)Cr">
              <do_if value="not $pIsSellOnly and $pBuyPrice gt 0 and not $pSupIsPlayer">
                <set_value name="$pAvailableBudget" exact="$mk4QueueBudgetMoney - ($mk4QueueMinMoney)Cr"/>
                <set_value name="$pAffordableUnits" exact="$pAvailableBudget / $pBuyPrice"/>
                <do_if value="$pAffordableUnits ge 1">
                  <set_value name="$pPairAmount" exact="[$pPairAmount, $pAffordableUnits].min"/>
                  <set_value name="$pBuyAmount" exact="$pPairAmount"/>
                  <set_value name="$pSellAmount" exact="$pPairAmount"/>
                  <set_value name="$pPurchaseCost" exact="$pBuyPrice * $pBuyAmount"/>
                </do_if>
                <do_else>
                  <!-- Cannot afford even 1 unit above MinPlayerMoney - genuine insolvency. -->
                  <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
                  <set_value name="$mk4FleetMoneyInsolvent" exact="true"/>
                </do_else>
              </do_if>
              <do_else>
                <!-- Purchase cost exceeds budget on a non-clampable buy leg - genuine insolvency. -->
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
                <set_value name="$mk4FleetMoneyInsolvent" exact="true"/>
              </do_else>
            </do_elseif>
            <!-- Destination delivery budget: cumulative sell amount per customer buy offer
                 must not exceed remaining destination capacity across multitrade legs. -->
            <do_if value="not $mk4PrimaryBudgetBlocked and $pPairAmount gt 0 and $mk4PrimaryTrade.$SellOffer?">
              <set_value name="$pDestSellOffer" exact="$mk4PrimaryTrade.$SellOffer"/>
              <do_if value="not $mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}?">
                <!-- Validated prep amount already reflects tradematch demand gate (vanilla
                     incoming + GT reservations). Re-subtracting get_ware_reservation from raw
                     offeramount double-counts in-flight deliveries on busy build storages. -->
                <set_value name="$pDestBudgetInit" exact="$pSellAmount"/>
                <set_value name="$pDestOfferAmt" exact="@$pDestSellOffer.offeramount.{this.ship}"/>
                <do_if value="$pDestOfferAmt? and $pDestOfferAmt gt 0">
                  <set_value name="$pDestBudgetInit" exact="[$pDestBudgetInit, $pDestOfferAmt].min"/>
                </do_if>
                <!-- GT_Reservations is a single-slot (last-writer-wins) SELECTION lock consumed
                     during validation (skip-if-reserved-by-other). $pSellAmount already passed the
                     write-time tradematch demand gate which subtracts the same reservation, so
                     debiting it again here double-counts and zeroes the race-loser's per-leg budget
                     when a peer overwrote the slot. Do not re-subtract it. -->
                <set_value name="$mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}" exact="$pDestBudgetInit"/>
              </do_if>
              <set_value name="$pDestBudgetRem" exact="$mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}"/>
              <set_value name="$pPairAmount" exact="[$pPairAmount, $pDestBudgetRem].min"/>
              <do_if value="not $pIsSellOnly">
                <set_value name="$pBuyAmount" exact="[$pBuyAmount, $pPairAmount].min"/>
                <set_value name="$pSellAmount" exact="$pPairAmount"/>
              </do_if>
              <do_else>
                <set_value name="$pSellAmount" exact="$pPairAmount"/>
              </do_else>
              <set_value name="$pPurchaseCost" exact="if $pIsSellOnly or $pSupIsPlayer then 0 else ($pBuyPrice * $pPairAmount)"/>
              <do_if value="$pPairAmount le 0">
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
              </do_if>
            </do_if>
            <!-- Supplier pickup budget: cumulative buy per supplier sell offer must not
                 exceed effective physical stock (player factory cargo minus outbound pickups). -->
            <do_if value="not $mk4PrimaryBudgetBlocked and not $pIsSellOnly and $pPairAmount gt 0 and $mk4PrimaryTrade.$BuyOffer?">
              <set_value name="$pSupBuyOffer" exact="$mk4PrimaryTrade.$BuyOffer"/>
              <do_if value="not $mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}?">
                <set_value name="$pSupBudgetInit" exact="@$pSupBuyOffer.offeramount.{this.ship}"/>
                <do_if value="$pSupBudgetInit == null or $pSupBudgetInit le 0">
                  <do_if value="$pSupBuyOffer.amount?">
                    <set_value name="$pSupBudgetInit" exact="@$pSupBuyOffer.amount"/>
                  </do_if>
                  <do_else>
                    <set_value name="$pSupBudgetInit" exact="0"/>
                  </do_else>
                </do_if>
                <!-- Same selection-lock double-count reasoning as the destination budget above:
                     the GT reservation is consumed at validation and already gated at write time;
                     real outbound pickups are accounted by the physical-stock clamp below. -->
                <set_value name="$pSupStation" exact="if $mk4PrimaryTrade.$BuyStation? and $mk4PrimaryTrade.$BuyStation.exists then $mk4PrimaryTrade.$BuyStation else null"/>
                <do_if value="not $pSupStation? and $pSupBuyOffer.seller? and @$pSupBuyOffer.seller.exists">
                  <set_value name="$pSupStation" exact="@$pSupBuyOffer.seller"/>
                </do_if>
                <do_if value="not $pSupStation? and $pSupBuyOffer.owner?">
                  <set_value name="$pSupStation" exact="@$pSupBuyOffer.owner"/>
                </do_if>
                <set_value name="$pSupWare" exact="if $mk4PrimaryTrade.$Ware? then $mk4PrimaryTrade.$Ware else (if $pSupBuyOffer.ware? then @$pSupBuyOffer.ware else null)"/>
                <do_if value="$pSupStation? and $pSupStation.exists and $pSupWare?">
                  <get_ware_reservation object="$pSupStation" ware="$pSupWare" type="buy" virtual="false" result="$pSupOutgoingTotal"/>
                  <get_ware_reservation object="$pSupStation" ware="$pSupWare" type="buy" reserver="this.ship" virtual="false" result="$pSupOutgoingSelf"/>
                  <set_value name="$pSupOutgoingOther" exact="[($pSupOutgoingTotal - $pSupOutgoingSelf), 0].max"/>
                  <set_value name="$pSupPhysicalStock" exact="[($pSupStation.cargo.{$pSupWare}.count - $pSupOutgoingOther), 0].max"/>
                  <set_value name="$pSupBudgetInit" exact="[$pSupBudgetInit, $pSupPhysicalStock].min"/>
                </do_if>
                <set_value name="$mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}" exact="$pSupBudgetInit"/>
              </do_if>
              <set_value name="$pSupBudgetRem" exact="$mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}"/>
              <set_value name="$pPairAmount" exact="[$pPairAmount, $pSupBudgetRem].min"/>
              <set_value name="$pBuyAmount" exact="[$pBuyAmount, $pPairAmount].min"/>
              <set_value name="$pSellAmount" exact="$pPairAmount"/>
              <set_value name="$pPurchaseCost" exact="if $pSupIsPlayer then 0 else ($pBuyPrice * $pPairAmount)"/>
              <do_if value="$pPairAmount le 0">
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
              </do_if>
            </do_if>
            <!-- Sell-only: cap by ship cargo remaining across legs (defense if multitrade ever runs). -->
            <do_if value="not $mk4PrimaryBudgetBlocked and $pIsSellOnly and $pPairAmount gt 0 and $mk4PrimaryTrade.$Ware?">
              <set_value name="$pCargoWare" exact="$mk4PrimaryTrade.$Ware"/>
              <do_if value="not $mk4ShipCargoBudgetByWare.{$pCargoWare}?">
                <set_value name="$mk4ShipCargoBudgetByWare.{$pCargoWare}" exact="this.ship.cargo.{$pCargoWare}.count"/>
              </do_if>
              <set_value name="$pCargoBudgetRem" exact="$mk4ShipCargoBudgetByWare.{$pCargoWare}"/>
              <set_value name="$pPairAmount" exact="[$pPairAmount, $pCargoBudgetRem].min"/>
              <set_value name="$pSellAmount" exact="$pPairAmount"/>
              <do_if value="$pPairAmount le 0">
                <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="not $mk4PrimaryBudgetBlocked and $pPairAmount gt 0">
              <set_value name="$mk4PrimaryTrade.$QueuedBuyAmount" exact="$pBuyAmount"/>
              <set_value name="$mk4PrimaryTrade.$QueuedSellAmount" exact="$pSellAmount"/>
              <append_to_list name="$mk4QueueableTrades" exact="$mk4PrimaryTrade"/>
              <set_value name="$mk4QueueBudgetMoney" exact="$mk4QueueBudgetMoney - $pPurchaseCost"/>
              <do_if value="$mk4PrimaryTrade.$SellOffer?">
                <set_value name="$pDestSellOffer" exact="$mk4PrimaryTrade.$SellOffer"/>
                <set_value name="$mk4DeliveryBudgetBySellOffer.{$pDestSellOffer}" exact="[($mk4DeliveryBudgetBySellOffer.{$pDestSellOffer} - $pPairAmount), 0].max"/>
              </do_if>
              <do_if value="not $pIsSellOnly and $mk4PrimaryTrade.$BuyOffer?">
                <set_value name="$pSupBuyOffer" exact="$mk4PrimaryTrade.$BuyOffer"/>
                <set_value name="$mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer}" exact="[($mk4SupplierBudgetByBuyOffer.{$pSupBuyOffer} - $pPairAmount), 0].max"/>
              </do_if>
              <do_elseif value="$pIsSellOnly and $mk4PrimaryTrade.$Ware?">
                <set_value name="$pCargoWare" exact="$mk4PrimaryTrade.$Ware"/>
                <set_value name="$mk4ShipCargoBudgetByWare.{$pCargoWare}" exact="[($mk4ShipCargoBudgetByWare.{$pCargoWare} - $pPairAmount), 0].max"/>
              </do_elseif>
              <set_value name="$pVolumePerUnit" exact="if $mk4PrimaryTrade.$Ware? and $mk4PrimaryTrade.$Ware.volume? then $mk4PrimaryTrade.$Ware.volume else 1"/>
              <set_value name="$mk4RemainingVolume" exact="[0, $mk4RemainingVolume - ($pPairAmount * $pVolumePerUnit)].max"/>
              <set_value name="$mk4CurrentFillPct" exact="if $mk4CargoCapacityVol gt 0 then ((($mk4CargoCapacityVol - $mk4RemainingVolume) * 100) / $mk4CargoCapacityVol) else 100"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$mk4PrimaryBudgetBlocked" exact="true"/>
          </do_else>

          <!-- Iteratively add secondary legs (MK1 style) until threshold is reached
               or no valid secondary remains. -->
          <do_if value="not $mk4PrimaryBudgetBlocked and not $mk4SinglePreferred and $mk4PreparedCandidates.count gt 1 and $mk4QueueableTrades.count gt 0">
            <set_value name="$mk4SecondaryBudgetBlocked" exact="table[]"/>
            <do_while value="$mk4QueueableTrades.count lt $validatedCandidateLimit and $mk4RemainingVolume gt 0 and ((not $mk4UseMinCargoThresholdForRoute) or ($mk4CurrentFillPct lt $mk4ThresholdPctForSingle))">
              <set_value name="$mk4BestSecondaryTrade" exact="null"/>
              <set_value name="$mk4BestSecondaryIndex" exact="0"/>
              <set_value name="$mk4BestSecondaryAmount" exact="0"/>
              <set_value name="$mk4BestSecondaryScore" exact="-1"/>

              <do_all exact="$mk4PreparedCandidates.count" counter="$sci">
                <set_value name="$scTrade" exact="$mk4PreparedCandidates.{$sci}"/>
                <do_if value="$mk4SecondaryBudgetBlocked.{$sci}?">
                  <continue/>
                </do_if>

                <!-- Skip exact duplicate offer-pairs already selected (MK1 parity). -->
                <set_value name="$mk4SecondaryAlreadySelected" exact="false"/>
                <do_all exact="$mk4QueueableTrades.count" counter="$qdupi">
                  <set_value name="$mk4DupTrade" exact="$mk4QueueableTrades.{$qdupi}"/>
                  <set_value name="$mk4SecPairMatch" exact="false"/>
                  <do_if value="$mk4DupTrade.$SellOffer == $scTrade.$SellOffer">
                    <do_if value="$scTrade.$IsSellOnly? and $scTrade.$IsSellOnly and $mk4DupTrade.$IsSellOnly? and $mk4DupTrade.$IsSellOnly">
                      <set_value name="$mk4SecPairMatch" exact="true"/>
                    </do_if>
                    <do_elseif value="$mk4DupTrade.$BuyOffer? and $scTrade.$BuyOffer? and $mk4DupTrade.$BuyOffer == $scTrade.$BuyOffer">
                      <set_value name="$mk4SecPairMatch" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="$mk4SecPairMatch">
                    <set_value name="$mk4SecondaryAlreadySelected" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="$mk4SecondaryAlreadySelected">
                  <continue/>
                </do_if>

                <!-- Backtrack cluster on supplier sectors. -->
                <set_value name="$mk4SecondaryBacktrackReject" exact="false"/>
                <set_value name="$scBuySector" exact="if $scTrade.$BuySector? then $scTrade.$BuySector else (if $scTrade.$BuyStation? then $scTrade.$BuyStation.sector else (if $scTrade.$BuyOffer? and $scTrade.$BuyOffer.owner? then $scTrade.$BuyOffer.owner.sector else null))"/>
                <do_if value="this.$effectiveBacktrackTolerance? and this.$effectiveBacktrackTolerance ge 0 and $scBuySector?">
                  <do_all exact="$mk4QueueableTrades.count" counter="$qbi">
                    <set_value name="$qTrade" exact="$mk4QueueableTrades.{$qbi}"/>
                    <set_value name="$qBuySector" exact="if $qTrade.$BuySector? then $qTrade.$BuySector else (if $qTrade.$BuyStation? then $qTrade.$BuyStation.sector else (if $qTrade.$BuyOffer? and $qTrade.$BuyOffer.owner? then $qTrade.$BuyOffer.owner.sector else null))"/>
                    <do_if value="not $qBuySector?">
                      <continue/>
                    </do_if>
                    <set_value name="$qBuyDist" exact="$qBuySector.gatedistance.{$scBuySector}"/>
                    <do_if value="$qBuyDist lt 0 or $qBuyDist gt this.$effectiveBacktrackTolerance">
                      <set_value name="$mk4SecondaryBacktrackReject" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$mk4SecondaryBacktrackReject">
                  <set_value name="$mk4BacktrackSkipped" operation="add"/>
                  <continue/>
                </do_if>

                <set_value name="$scIsSellOnly" exact="$scTrade.$IsSellOnly? and $scTrade.$IsSellOnly"/>
                <set_value name="$scBuyAmount" exact="if $scTrade.$QueuedBuyAmount? then $scTrade.$QueuedBuyAmount else (if $scTrade.$Amount? then $scTrade.$Amount else 0)"/>
                <set_value name="$scSellAmount" exact="if $scTrade.$QueuedSellAmount? then $scTrade.$QueuedSellAmount else (if $scTrade.$Amount? then $scTrade.$Amount else 0)"/>
                <set_value name="$scPairAmount" exact="if $scIsSellOnly then $scSellAmount else [$scBuyAmount, $scSellAmount].min"/>
                <set_value name="$scVolumePerUnit" exact="if $scTrade.$Ware? and $scTrade.$Ware.volume? then $scTrade.$Ware.volume else 1"/>
                <do_if value="$scVolumePerUnit gt 0">
                  <set_value name="$scMaxByVolume" exact="($mk4RemainingVolume / $scVolumePerUnit)i"/>
                  <set_value name="$scPairAmount" exact="[$scPairAmount, $scMaxByVolume].min"/>
                </do_if>
                <set_value name="$scMaxFeasibleByVolume" exact="$scPairAmount"/>
                <do_if value="$scPairAmount le 0">
                  <continue/>
                </do_if>

                <!-- Destination delivery budget (same customer buy offer across legs). -->
                <do_if value="$scTrade.$SellOffer?">
                  <set_value name="$scDestSellOffer" exact="$scTrade.$SellOffer"/>
                  <do_if value="not $mk4DeliveryBudgetBySellOffer.{$scDestSellOffer}?">
                    <set_value name="$scDestBudgetInit" exact="$scPairAmount"/>
                    <set_value name="$scDestOfferAmt" exact="@$scDestSellOffer.offeramount.{this.ship}"/>
                    <do_if value="$scDestOfferAmt? and $scDestOfferAmt gt 0">
                      <set_value name="$scDestBudgetInit" exact="[$scDestBudgetInit, $scDestOfferAmt].min"/>
                    </do_if>
                    <!-- See primary-leg note: GT reservation is a selection lock already gated at
                         write time; do not re-subtract it (double-counts, zeroes race-loser legs). -->
                    <set_value name="$mk4DeliveryBudgetBySellOffer.{$scDestSellOffer}" exact="$scDestBudgetInit"/>
                  </do_if>
                  <set_value name="$scDestBudgetRem" exact="$mk4DeliveryBudgetBySellOffer.{$scDestSellOffer}"/>
                  <set_value name="$scPairAmount" exact="[$scPairAmount, $scDestBudgetRem].min"/>
                  <do_if value="$scPairAmount le 0">
                    <set_value name="$mk4DestBudgetSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- Supplier pickup budget (cumulative per BuyOffer across multitrade legs). -->
                <do_if value="not $scIsSellOnly and $scPairAmount gt 0 and $scTrade.$BuyOffer?">
                  <set_value name="$scSupBuyOffer" exact="$scTrade.$BuyOffer"/>
                  <do_if value="not $mk4SupplierBudgetByBuyOffer.{$scSupBuyOffer}?">
                    <set_value name="$scSupBudgetInit" exact="@$scSupBuyOffer.offeramount.{this.ship}"/>
                    <do_if value="$scSupBudgetInit == null or $scSupBudgetInit le 0">
                      <do_if value="$scSupBuyOffer.amount?">
                        <set_value name="$scSupBudgetInit" exact="@$scSupBuyOffer.amount"/>
                      </do_if>
                      <do_else>
                        <set_value name="$scSupBudgetInit" exact="0"/>
                      </do_else>
                    </do_if>
                    <!-- See primary-leg note: GT reservation already gated at write time; real
                         outbound pickups are handled by the physical-stock clamp below. -->
                    <set_value name="$scSupStation" exact="if $scTrade.$BuyStation? and $scTrade.$BuyStation.exists then $scTrade.$BuyStation else null"/>
                    <do_if value="not $scSupStation? and $scSupBuyOffer.seller? and @$scSupBuyOffer.seller.exists">
                      <set_value name="$scSupStation" exact="@$scSupBuyOffer.seller"/>
                    </do_if>
                    <do_if value="not $scSupStation? and $scSupBuyOffer.owner?">
                      <set_value name="$scSupStation" exact="@$scSupBuyOffer.owner"/>
                    </do_if>
                    <set_value name="$scSupWare" exact="if $scTrade.$Ware? then $scTrade.$Ware else (if $scSupBuyOffer.ware? then @$scSupBuyOffer.ware else null)"/>
                    <do_if value="$scSupStation? and $scSupStation.exists and $scSupWare?">
                      <get_ware_reservation object="$scSupStation" ware="$scSupWare" type="buy" virtual="false" result="$scSupOutgoingTotal"/>
                      <get_ware_reservation object="$scSupStation" ware="$scSupWare" type="buy" reserver="this.ship" virtual="false" result="$scSupOutgoingSelf"/>
                      <set_value name="$scSupOutgoingOther" exact="[($scSupOutgoingTotal - $scSupOutgoingSelf), 0].max"/>
                      <set_value name="$scSupPhysicalStock" exact="[($scSupStation.cargo.{$scSupWare}.count - $scSupOutgoingOther), 0].max"/>
                      <set_value name="$scSupBudgetInit" exact="[$scSupBudgetInit, $scSupPhysicalStock].min"/>
                    </do_if>
                    <set_value name="$mk4SupplierBudgetByBuyOffer.{$scSupBuyOffer}" exact="$scSupBudgetInit"/>
                  </do_if>
                  <set_value name="$scSupBudgetRem" exact="$mk4SupplierBudgetByBuyOffer.{$scSupBuyOffer}"/>
                  <set_value name="$scPairAmount" exact="[$scPairAmount, $scSupBudgetRem].min"/>
                  <do_if value="$scPairAmount le 0">
                    <set_value name="$mk4SupBudgetSkipped" operation="add"/>
                    <continue/>
                  </do_if>
                </do_if>

                <!-- MIN_LEG_VOLUME: each extra leg must carry at least minCargoUsed/3 of hold
                     volume (MK1 parity). Exception: admit when this leg fully covers remaining
                     destination demand (e.g. final ware cell for construction/research). -->
                <do_if value="$mk4MinLegVolume gt 0">
                  <set_value name="$scMaxFeasibleVolume" exact="if $scVolumePerUnit gt 0 then ($scMaxFeasibleByVolume * $scVolumePerUnit) else 0"/>
                  <do_if value="$scMaxFeasibleVolume le 0">
                    <continue/>
                  </do_if>
                  <set_value name="$scFillsDestCompletely" exact="false"/>
                  <set_value name="$scDestStation" exact="if $scTrade.$SellStation? and @$scTrade.$SellStation.exists then @$scTrade.$SellStation else (if $scTrade.$SellOffer? and $scTrade.$SellOffer.buyer? and @$scTrade.$SellOffer.buyer.exists then @$scTrade.$SellOffer.buyer else (if $scTrade.$SellOffer? and $scTrade.$SellOffer.owner? then @$scTrade.$SellOffer.owner else null))"/>
                  <set_value name="$scDestWare" exact="if $scTrade.$Ware? then $scTrade.$Ware else null"/>
                  <set_value name="$scDestNeedRemaining" exact="0"/>
                  <do_if value="$scDestStation? and $scDestStation.exists and $scDestWare?">
                    <set_value name="$scDestNeedRemaining" exact="[0, @$scDestStation.cargo.{$scDestWare}.target - @$scDestStation.cargo.{$scDestWare}.count].max"/>
                    <get_ware_reservation object="$scDestStation" ware="$scDestWare" type="sell" virtual="false" result="$scDestIncomingRes"/>
                    <set_value name="$scDestNeedRemaining" exact="[($scDestNeedRemaining - $scDestIncomingRes), 0].max"/>
                  </do_if>
                  <do_if value="$scTrade.$SellOffer? and global.$GT_Reservations? and global.$GT_Reservations.{$scTrade.$SellOffer}?">
                    <set_value name="$scGtResData" exact="global.$GT_Reservations.{$scTrade.$SellOffer}"/>
                    <do_if value="$scGtResData.$Until? and player.age lt @$scGtResData.$Until">
                      <do_if value="not $scGtResData.$Ship? or @$scGtResData.$Ship != this.ship">
                        <set_value name="$scGtResAmount" exact="0"/>
                        <do_if value="$scGtResData.$Amount? and @$scGtResData.$Amount gt 0">
                          <set_value name="$scGtResAmount" exact="$scGtResData.$Amount"/>
                        </do_if>
                        <do_else>
                          <set_value name="$scGtResAmount" exact="1"/>
                        </do_else>
                        <set_value name="$scDestNeedRemaining" exact="[($scDestNeedRemaining - $scGtResAmount), 0].max"/>
                      </do_if>
                    </do_if>
                  </do_if>
                  <set_value name="$scAlreadyQueuedToDest" exact="0"/>
                  <do_all exact="$mk4QueueableTrades.count" counter="$scqai">
                    <set_value name="$scqTrade" exact="$mk4QueueableTrades.{$scqai}"/>
                    <do_if value="$scTrade.$SellOffer? and $scqTrade.$SellOffer? and $scqTrade.$SellOffer == $scTrade.$SellOffer">
                      <set_value name="$scqAmt" exact="if $scqTrade.$QueuedSellAmount? then $scqTrade.$QueuedSellAmount else (if $scqTrade.$Amount? then $scqTrade.$Amount else 0)"/>
                      <set_value name="$scAlreadyQueuedToDest" exact="$scAlreadyQueuedToDest + $scqAmt"/>
                    </do_if>
                  </do_all>
                  <set_value name="$scDestNeedRemaining" exact="[($scDestNeedRemaining - $scAlreadyQueuedToDest), 0].max"/>
                  <do_if value="$scDestNeedRemaining gt 0 and $scPairAmount ge $scDestNeedRemaining">
                    <set_value name="$scFillsDestCompletely" exact="true"/>
                  </do_if>
                  <do_if value="not $scFillsDestCompletely and $scMaxFeasibleVolume lt $mk4MinLegVolume">
                    <set_value name="$mk4MinLegSkipped" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4-2 secondary REJECTED (MIN_LEG_VOLUME: feasibleVol=' + $scMaxFeasibleVolume + ' minLeg=' + $mk4MinLegVolume + ' planned=' + $scPairAmount + ' destNeed=' + $scDestNeedRemaining + ')'" chance="100"/>
                    </do_if>
                    <continue/>
                  </do_if>
                </do_if>

                <set_value name="$scScore" exact="if $scTrade.$Score? then $scTrade.$Score else 0"/>
                <do_if value="$scPairAmount gt $mk4BestSecondaryAmount or ($scPairAmount == $mk4BestSecondaryAmount and $scScore gt $mk4BestSecondaryScore)">
                  <set_value name="$mk4BestSecondaryTrade" exact="$scTrade"/>
                  <set_value name="$mk4BestSecondaryIndex" exact="$sci"/>
                  <set_value name="$mk4BestSecondaryAmount" exact="$scPairAmount"/>
                  <set_value name="$mk4BestSecondaryScore" exact="$scScore"/>
                </do_if>
              </do_all>

              <do_if value="not $mk4BestSecondaryTrade? or $mk4BestSecondaryAmount le 0">
                <break/>
              </do_if>

              <set_value name="$bsIsSellOnly" exact="$mk4BestSecondaryTrade.$IsSellOnly? and $mk4BestSecondaryTrade.$IsSellOnly"/>
              <set_value name="$bsBuyPrice" exact="if not $bsIsSellOnly and $mk4BestSecondaryTrade.$BuyOffer? and $mk4BestSecondaryTrade.$BuyOffer.unitprice? then $mk4BestSecondaryTrade.$BuyOffer.unitprice else 0"/>
              <set_value name="$bsSupIsPlayer" exact="false"/>
              <do_if value="not $bsIsSellOnly">
                <do_if value="$mk4BestSecondaryTrade.$BuyStation? and $mk4BestSecondaryTrade.$BuyStation.exists and $mk4BestSecondaryTrade.$BuyStation.isplayerowned">
                  <set_value name="$bsSupIsPlayer" exact="true"/>
                </do_if>
                <do_elseif value="$mk4BestSecondaryTrade.$BuyOffer? and $mk4BestSecondaryTrade.$BuyOffer.owner? and $mk4BestSecondaryTrade.$BuyOffer.owner.exists and $mk4BestSecondaryTrade.$BuyOffer.owner.isplayerowned">
                  <set_value name="$bsSupIsPlayer" exact="true"/>
                </do_elseif>
              </do_if>
              <set_value name="$bsPurchaseCost" exact="if $bsIsSellOnly or $bsSupIsPlayer then 0 else ($bsBuyPrice * $mk4BestSecondaryAmount)"/>
              <do_if value="$bsPurchaseCost gt 0 and ($mk4QueueBudgetMoney - $bsPurchaseCost) lt ($mk4QueueMinMoney)Cr">
                <do_if value="not $bsIsSellOnly and $bsBuyPrice gt 0 and not $bsSupIsPlayer">
                  <set_value name="$bsAvailableBudget" exact="$mk4QueueBudgetMoney - ($mk4QueueMinMoney)Cr"/>
                  <set_value name="$bsAffordableUnits" exact="$bsAvailableBudget / $bsBuyPrice"/>
                  <do_if value="$bsAffordableUnits ge 1">
                    <set_value name="$mk4BestSecondaryAmount" exact="[$mk4BestSecondaryAmount, $bsAffordableUnits].min"/>
                    <set_value name="$bsPurchaseCost" exact="$bsBuyPrice * $mk4BestSecondaryAmount"/>
                  </do_if>
                  <do_else>
                    <set_value name="$mk4SecondaryBudgetBlocked.{$mk4BestSecondaryIndex}" exact="true"/>
                    <set_value name="$mk4SecondaryBudgetSkipped" operation="add"/>
                    <continue/>
                  </do_else>
                </do_if>
                <do_else>
                  <set_value name="$mk4SecondaryBudgetBlocked.{$mk4BestSecondaryIndex}" exact="true"/>
                  <set_value name="$mk4SecondaryBudgetSkipped" operation="add"/>
                  <continue/>
                </do_else>
              </do_if>

              <do_if value="$mk4BestSecondaryAmount le 0">
                <set_value name="$mk4SecondaryBudgetBlocked.{$mk4BestSecondaryIndex}" exact="true"/>
                <set_value name="$mk4SecondaryBudgetSkipped" operation="add"/>
                <continue/>
              </do_if>

              <set_value name="$mk4BestSecondaryTrade.$QueuedBuyAmount" exact="if $bsIsSellOnly then 0 else $mk4BestSecondaryAmount"/>
              <set_value name="$mk4BestSecondaryTrade.$QueuedSellAmount" exact="$mk4BestSecondaryAmount"/>
              <append_to_list name="$mk4QueueableTrades" exact="$mk4BestSecondaryTrade"/>
              <set_value name="$mk4QueueBudgetMoney" exact="$mk4QueueBudgetMoney - $bsPurchaseCost"/>
              <do_if value="$mk4BestSecondaryTrade.$SellOffer?">
                <set_value name="$bsDestSellOffer" exact="$mk4BestSecondaryTrade.$SellOffer"/>
                <set_value name="$mk4DeliveryBudgetBySellOffer.{$bsDestSellOffer}" exact="[($mk4DeliveryBudgetBySellOffer.{$bsDestSellOffer} - $mk4BestSecondaryAmount), 0].max"/>
              </do_if>
              <do_if value="not $bsIsSellOnly and $mk4BestSecondaryTrade.$BuyOffer?">
                <set_value name="$bsSupBuyOffer" exact="$mk4BestSecondaryTrade.$BuyOffer"/>
                <set_value name="$mk4SupplierBudgetByBuyOffer.{$bsSupBuyOffer}" exact="[($mk4SupplierBudgetByBuyOffer.{$bsSupBuyOffer} - $mk4BestSecondaryAmount), 0].max"/>
              </do_if>
              <set_value name="$bsVolumePerUnit" exact="if $mk4BestSecondaryTrade.$Ware? and $mk4BestSecondaryTrade.$Ware.volume? then $mk4BestSecondaryTrade.$Ware.volume else 1"/>
              <set_value name="$mk4RemainingVolume" exact="[0, $mk4RemainingVolume - ($mk4BestSecondaryAmount * $bsVolumePerUnit)].max"/>
              <set_value name="$mk4CurrentFillPct" exact="if $mk4CargoCapacityVol gt 0 then ((($mk4CargoCapacityVol - $mk4RemainingVolume) * 100) / $mk4CargoCapacityVol) else 100"/>
            </do_while>
          </do_if>

          <do_if value="$mk4PrimaryBudgetBlocked or $mk4QueueableTrades.count == 0">
            <do_if value="$mk4FleetMoneyInsolvent">
              <!-- Genuine insolvency: the primary leg cannot afford even 1 unit above
                   MinPlayerMoney. Raise the fleet-wide money cap and back off long. -->
              <set_value name="global.$GT_MoneyCapActive" exact="true"/>
              <set_value name="global.$GT_MoneyCapMoney" exact="player.money"/>
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GLOBAL MONEY CAP SET: player.money=' + (player.money / 100) + ' Cr â€” cannot afford 1 unit above MinPlayerMoney (' + $mk4QueueMinMoney + ' Cr)'" chance="100"/>
              <set_value name="this.$lastNoTradeReason" exact="'insufficient_funds'"/>
            </do_if>
            <do_else>
              <!-- Non-money queue failure: zero pair amount, destination capacity exhausted,
                   or no queueable candidate. This is NOT a budget problem, so it must not
                   freeze the fleet. Use a normal no_trade backoff (short escalating cooldown). -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': multitrade produced no queueable legs (capacity/route, not budget): player.money=' + (player.money / 100) + ' Cr â€” retrying as no_trade'" chance="100"/>
              </do_if>
              <set_value name="this.$lastNoTradeReason" exact="'no_trade'"/>
            </do_else>
            <resume label="no_trade_retry"/>
          </do_if>

          <do_if value="$mk4QueueableTrades.count gt 0">
            <!-- Optional compaction: keep primary leg fixed, then order remaining legs by
                 nearest sell-destination sector to reduce zig-zag routes (MK1 parity). -->
            <do_if value="$mk4QueueableTrades.count gt 2">
              <create_list name="$mk4CompactedTrades"/>
              <append_to_list name="$mk4CompactedTrades" exact="$mk4QueueableTrades.{1}"/>
              <set_value name="$mk4CompactionPicked" exact="table[]"/>
              <set_value name="$mk4CompactionPicked.{1}" exact="true"/>
              <set_value name="$mk4CompactionAnchorSector" exact="if $mk4QueueableTrades.{1}.$SellStation? then $mk4QueueableTrades.{1}.$SellStation.sector else (if $mk4QueueableTrades.{1}.$SellOffer? and $mk4QueueableTrades.{1}.$SellOffer.owner? then $mk4QueueableTrades.{1}.$SellOffer.owner.sector else null)"/>
              <do_while value="$mk4CompactedTrades.count lt $mk4QueueableTrades.count">
                <set_value name="$mk4CompactionBestIdx" exact="0"/>
                <set_value name="$mk4CompactionBestDist" exact="999999"/>
                <do_all exact="$mk4QueueableTrades.count" counter="$mci">
                  <do_if value="$mk4CompactionPicked.{$mci}?">
                    <continue/>
                  </do_if>
                  <set_value name="$mk4CompactionCandidate" exact="$mk4QueueableTrades.{$mci}"/>
                  <set_value name="$mk4CandidateSellSector" exact="if $mk4CompactionCandidate.$SellStation? then $mk4CompactionCandidate.$SellStation.sector else (if $mk4CompactionCandidate.$SellOffer? and $mk4CompactionCandidate.$SellOffer.owner? then $mk4CompactionCandidate.$SellOffer.owner.sector else null)"/>
                  <set_value name="$mk4CompactionDistance" exact="if $mk4CompactionAnchorSector? and $mk4CandidateSellSector? then $mk4CompactionAnchorSector.gatedistance.{$mk4CandidateSellSector} else 0"/>
                  <do_if value="$mk4CompactionDistance lt 0">
                    <set_value name="$mk4CompactionDistance" exact="999999"/>
                  </do_if>
                  <do_if value="$mk4CompactionBestIdx == 0 or $mk4CompactionDistance lt $mk4CompactionBestDist">
                    <set_value name="$mk4CompactionBestIdx" exact="$mci"/>
                    <set_value name="$mk4CompactionBestDist" exact="$mk4CompactionDistance"/>
                  </do_if>
                </do_all>
                <do_if value="$mk4CompactionBestIdx gt 0">
                  <set_value name="$mk4CompactionBestTrade" exact="$mk4QueueableTrades.{$mk4CompactionBestIdx}"/>
                  <append_to_list name="$mk4CompactedTrades" exact="$mk4CompactionBestTrade"/>
                  <set_value name="$mk4CompactionPicked.{$mk4CompactionBestIdx}" exact="true"/>
                  <set_value name="$mk4CompactionAnchorSector" exact="if $mk4CompactionBestTrade.$SellStation? then $mk4CompactionBestTrade.$SellStation.sector else (if $mk4CompactionBestTrade.$SellOffer? and $mk4CompactionBestTrade.$SellOffer.owner? then $mk4CompactionBestTrade.$SellOffer.owner.sector else $mk4CompactionAnchorSector)"/>
                </do_if>
                <do_else>
                  <break/>
                </do_else>
              </do_while>
              <do_if value="$mk4CompactedTrades.count == $mk4QueueableTrades.count">
                <set_value name="$mk4QueueableTrades" exact="$mk4CompactedTrades"/>
              </do_if>
            </do_if>

            <!-- Canonical trade context for follow-up logging/UI remains first selected leg. -->
            <set_value name="$pendingTrade" exact="$mk4QueueableTrades.{1}"/>
            <set_value name="$isSellOnlyTradeForPending" exact="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly"/>
            <set_value name="$finalBuyAmount" exact="if $pendingTrade.$QueuedBuyAmount? then $pendingTrade.$QueuedBuyAmount else (if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount)"/>
            <set_value name="$finalSellAmount" exact="if $pendingTrade.$QueuedSellAmount? then $pendingTrade.$QueuedSellAmount else (if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount)"/>

            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 multitrade execution set: queued=' + $mk4QueueableTrades.count + '/' + $mk4QueueSourceCount + ' (maxTrades=' + $validatedCandidateLimit + ', secondaryBudgetSkipped=' + $mk4SecondaryBudgetSkipped + ', destBudgetSkipped=' + $mk4DestBudgetSkipped + ', supBudgetSkipped=' + $mk4SupBudgetSkipped + ', backtrackSkipped=' + $mk4BacktrackSkipped + ', minLegSkipped=' + $mk4MinLegSkipped + ', minLegFloor=' + $mk4MinLegVolume + ', singlePreferred=' + $mk4SinglePreferred + ')'" chance="100"/>
            </do_if>

            <set_value name="$mk4CycleLegCount" exact="0"/>
            <set_value name="$mk4CycleAmountTotal" exact="0"/>
            <set_value name="$mk4CycleProfitRaw" exact="0"/>
            <set_value name="$mk4CycleMoneyRawTotal" exact="0"/>
            <set_value name="$mk4MultiTradeLegs" exact="[]"/>

            <!-- Pre-order re-clamp: supplier/customer offers may have changed since validation. -->
            <create_list name="$mk4ExecTrades"/>
            <do_all exact="$mk4QueueableTrades.count" counter="$mk4rci">
              <set_value name="$mk4rcTrade" exact="$mk4QueueableTrades.{$mk4rci}"/>
              <set_value name="$mk4rcIsSellOnly" exact="$mk4rcTrade.$IsSellOnly? and $mk4rcTrade.$IsSellOnly"/>
              <set_value name="$mk4rcBuyAmt" exact="if $mk4rcTrade.$QueuedBuyAmount? then $mk4rcTrade.$QueuedBuyAmount else (if $mk4rcTrade.$FinalBuyAmount? then $mk4rcTrade.$FinalBuyAmount else (if $mk4rcTrade.$Amount? then $mk4rcTrade.$Amount else 0))"/>
              <set_value name="$mk4rcSellAmt" exact="if $mk4rcTrade.$QueuedSellAmount? then $mk4rcTrade.$QueuedSellAmount else (if $mk4rcTrade.$FinalSellAmount? then $mk4rcTrade.$FinalSellAmount else (if $mk4rcTrade.$Amount? then $mk4rcTrade.$Amount else 0))"/>
              <set_value name="$mk4rcClampFailed" exact="false"/>

              <do_if value="not $mk4rcIsSellOnly and $mk4rcTrade.$BuyOffer? and @$mk4rcTrade.$BuyOffer.exists">
                <set_value name="$mk4rcBuySeller" exact="null"/>
                <do_if value="$mk4rcTrade.$BuyOffer.seller? and @$mk4rcTrade.$BuyOffer.seller.exists">
                  <set_value name="$mk4rcBuySeller" exact="@$mk4rcTrade.$BuyOffer.seller"/>
                </do_if>
                <do_if value="not $mk4rcBuySeller? and $mk4rcTrade.$BuyOffer.owner? and @$mk4rcTrade.$BuyOffer.owner.exists">
                  <set_value name="$mk4rcBuySeller" exact="@$mk4rcTrade.$BuyOffer.owner"/>
                </do_if>
                <do_if value="$mk4rcBuySeller?">
                  <clamp_trade_amount trade="$mk4rcTrade.$BuyOffer" amount="$mk4rcBuyAmt" buyer="this.ship" seller="$mk4rcBuySeller" result="$mk4rcBuyAmt" reason="$mk4rcBuyClampReason"/>
                </do_if>
                <do_else>
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_else>
                <do_if value="not $mk4rcClampFailed and (not $mk4rcBuyAmt? or $mk4rcBuyAmt le 0)">
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_if>
              </do_if>

              <do_if value="not $mk4rcClampFailed and $mk4rcTrade.$SellOffer? and @$mk4rcTrade.$SellOffer.exists">
                <set_value name="$mk4rcSellBuyer" exact="null"/>
                <do_if value="$mk4rcTrade.$SellOffer.buyer? and @$mk4rcTrade.$SellOffer.buyer.exists">
                  <set_value name="$mk4rcSellBuyer" exact="@$mk4rcTrade.$SellOffer.buyer"/>
                </do_if>
                <do_if value="not $mk4rcSellBuyer? and $mk4rcTrade.$SellOffer.owner? and @$mk4rcTrade.$SellOffer.owner.exists">
                  <set_value name="$mk4rcSellBuyer" exact="@$mk4rcTrade.$SellOffer.owner"/>
                </do_if>
                <do_if value="not $mk4rcSellBuyer?">
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_if>
                <do_if value="not $mk4rcClampFailed">
                  <do_if value="$mk4rcIsSellOnly">
                    <clamp_trade_amount trade="$mk4rcTrade.$SellOffer" amount="$mk4rcSellAmt" buyer="$mk4rcSellBuyer" seller="this.ship" result="$mk4rcSellAmt" reason="$mk4rcSellClampReason"/>
                  </do_if>
                  <do_else>
                    <clamp_trade_amount trade="$mk4rcTrade.$SellOffer" amount="$mk4rcSellAmt" buyer="$mk4rcSellBuyer" result="$mk4rcSellAmt" reason="$mk4rcSellClampReason"/>
                  </do_else>
                  <do_if value="not $mk4rcSellAmt? or $mk4rcSellAmt le 0">
                    <set_value name="$mk4rcClampFailed" exact="true"/>
                  </do_if>
                </do_if>
              </do_if>

              <do_if value="not $mk4rcClampFailed and not $mk4rcIsSellOnly">
                <set_value name="$mk4rcPairAmt" exact="[$mk4rcBuyAmt, $mk4rcSellAmt].min"/>
                <set_value name="$mk4rcBuyAmt" exact="$mk4rcPairAmt"/>
                <set_value name="$mk4rcSellAmt" exact="$mk4rcPairAmt"/>
                <do_if value="$mk4rcPairAmt le 0">
                  <set_value name="$mk4rcClampFailed" exact="true"/>
                </do_if>
              </do_if>

              <do_if value="not $mk4rcClampFailed">
                <set_value name="$mk4rcTrade.$QueuedBuyAmount" exact="$mk4rcBuyAmt"/>
                <set_value name="$mk4rcTrade.$QueuedSellAmount" exact="$mk4rcSellAmt"/>
                <append_to_list name="$mk4ExecTrades" exact="$mk4rcTrade"/>
              </do_if>
              <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 pre-order reclamp dropped leg (buy=' + (if $mk4rcBuyClampReason? then $mk4rcBuyClampReason else 'n/a') + ', sell=' + (if $mk4rcSellClampReason? then $mk4rcSellClampReason else 'n/a') + ')'" chance="100"/>
              </do_elseif>
            </do_all>
            <set_value name="$mk4QueueableTrades" exact="$mk4ExecTrades"/>
            <do_if value="$mk4QueueableTrades.count == 0">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MK4 pre-order reclamp removed all legs â€” retrying search'" chance="100"/>
              </do_if>
              <set_value name="this.$lastNoTradeReason" exact="'no_trade'"/>
              <resume label="no_trade_retry"/>
            </do_if>
            <set_value name="$pendingTrade" exact="$mk4QueueableTrades.{1}"/>
            <set_value name="$isSellOnlyTradeForPending" exact="$pendingTrade.$IsSellOnly? and $pendingTrade.$IsSellOnly"/>
            <set_value name="$finalBuyAmount" exact="if $pendingTrade.$QueuedBuyAmount? then $pendingTrade.$QueuedBuyAmount else (if $pendingTrade.$FinalBuyAmount? then $pendingTrade.$FinalBuyAmount else $pendingTrade.$Amount)"/>
            <set_value name="$finalSellAmount" exact="if $pendingTrade.$QueuedSellAmount? then $pendingTrade.$QueuedSellAmount else (if $pendingTrade.$FinalSellAmount? then $pendingTrade.$FinalSellAmount else $pendingTrade.$Amount)"/>

            <!-- MK1 parity: two-phase queueing (all SELL first, then all BUY).
                 Use reverse candidate iteration so first selected candidate executes first under LIFO. -->
            <do_all exact="$mk4QueueableTrades.count" counter="$qri">
              <set_value name="$qidx" exact="$mk4QueueableTrades.count - $qri + 1"/>
              <set_value name="$qt" exact="$mk4QueueableTrades.{$qidx}"/>
              <set_value name="$qtIsSellOnlyExec" exact="$qt.$IsSellOnly? and $qt.$IsSellOnly"/>
              <set_value name="$qtExecBuyAmount" exact="if $qt.$QueuedBuyAmount? then $qt.$QueuedBuyAmount else (if $qt.$FinalBuyAmount? then $qt.$FinalBuyAmount else $qt.$Amount)"/>
              <set_value name="$qtExecSellAmount" exact="if $qt.$QueuedSellAmount? then $qt.$QueuedSellAmount else (if $qt.$FinalSellAmount? then $qt.$FinalSellAmount else $qt.$Amount)"/>
              <set_value name="$qtLogAmount" exact="if $qtIsSellOnlyExec then $qtExecSellAmount else $qtExecBuyAmount"/>
              <set_value name="$qtBuyPriceRaw" exact="if $qt.$BuyPrice? then $qt.$BuyPrice else (if $qt.$BuyOffer? and $qt.$BuyOffer.unitprice? then $qt.$BuyOffer.unitprice else 0)"/>
              <set_value name="$qtSellPriceRaw" exact="if $qt.$SellPrice? then $qt.$SellPrice else (if $qt.$SellOffer? and $qt.$SellOffer.unitprice? then $qt.$SellOffer.unitprice else 0)"/>
              <set_value name="$qtProfitRaw" exact="($qtSellPriceRaw - $qtBuyPriceRaw) * $qtLogAmount"/>
              <set_value name="$qtMoneyRaw" exact="-($qtBuyPriceRaw * $qtLogAmount)"/>
              <set_value name="$mk4CycleLegCount" exact="$mk4CycleLegCount + 1"/>
              <set_value name="$mk4CycleAmountTotal" exact="$mk4CycleAmountTotal + $qtLogAmount"/>
              <set_value name="$mk4CycleProfitRaw" exact="$mk4CycleProfitRaw + $qtProfitRaw"/>
              <set_value name="$mk4CycleMoneyRawTotal" exact="$mk4CycleMoneyRawTotal + $qtMoneyRaw"/>
              <set_value name="$mk4BuyStationObj" exact="if $qt.$BuyStation? and $qt.$BuyStation.exists then $qt.$BuyStation else (if $qt.$BuyOffer? and $qt.$BuyOffer.owner? and $qt.$BuyOffer.owner.exists then $qt.$BuyOffer.owner else null)"/>
              <set_value name="$mk4SellStationObj" exact="if $qt.$SellStation? and $qt.$SellStation.exists then $qt.$SellStation else (if $qt.$SellOffer? and $qt.$SellOffer.owner? and $qt.$SellOffer.owner.exists then $qt.$SellOffer.owner else null)"/>
              <append_to_list name="$mk4MultiTradeLegs" exact="table[
                $Amount = $qtLogAmount,
                $Ware = if $qt.$Ware? then $qt.$Ware else null,
                $BuyPriceRaw = $qtBuyPriceRaw,
                $SellPriceRaw = $qtSellPriceRaw,
                $BuyStation = $mk4BuyStationObj,
                $SellStation = $mk4SellStationObj
              ]"/>

              <set_value name="$qtSellLegInternal" exact="false"/>
              <do_if value="$qt.$SellStation? and $qt.$SellStation.exists and $qt.$SellStation.isplayerowned">
                <set_value name="$qtSellLegInternal" exact="true"/>
              </do_if>
              <do_elseif value="$qt.$SellOffer? and $qt.$SellOffer.owner? and $qt.$SellOffer.owner.exists and $qt.$SellOffer.owner.isplayerowned">
                <set_value name="$qtSellLegInternal" exact="true"/>
              </do_elseif>
              <do_if value="$qt.$SellOffer? and $qtExecSellAmount gt 0">
                <create_trade_order object="this.ship" tradeoffer="$qt.$SellOffer" amount="$qtExecSellAmount" immediate="true" internal="$qtSellLegInternal"/>
                <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$sellOfferAmountAfterOrder" exact="@$qt.$SellOffer.offeramount.{this.ship}"/>
                  <set_value name="$sellDesiredAfterOrder" exact="@$qt.$SellOffer.desiredamount"/>
                  <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': after create_trade_order SELL (phase=SELL, leg ' + $qidx + '/' + $mk4QueueableTrades.count + ')' +
                    '\n  orderAmount=' + $qtExecSellAmount +
                    '\n  sell offeramount(ship)=' + (if $sellOfferAmountAfterOrder? then $sellOfferAmountAfterOrder else 'null') +
                    '\n  sell desiredamount=' + (if $sellDesiredAfterOrder? then $sellDesiredAfterOrder else 'null')"
                    chance="100"/>
                </do_if>
              </do_if>
            </do_all>

            <!-- BUY-phase anti-zigzag compaction (MK1 parity intent):
                 group buy legs by supplier sector blocks so load execution does not
                 bounce A->B->A. Either A->A->B or B->B->A is acceptable. -->
            <set_value name="$mk4BuyPhaseTrades" exact="$mk4QueueableTrades"/>
            <do_if value="$mk4QueueableTrades.count gt 2">
              <create_list name="$mk4BuySectorOrder"/>
              <do_all exact="$mk4QueueableTrades.count" counter="$bsoi">
                <set_value name="$bst" exact="$mk4QueueableTrades.{$bsoi}"/>
                <set_value name="$bsSector" exact="if $bst.$BuySector? then $bst.$BuySector else (if $bst.$BuyStation? then $bst.$BuyStation.sector else (if $bst.$BuyOffer? and $bst.$BuyOffer.owner? then $bst.$BuyOffer.owner.sector else null))"/>
                <do_if value="$bsSector?">
                  <set_value name="$mk4SeenBuySector" exact="false"/>
                  <do_all exact="$mk4BuySectorOrder.count" counter="$bssj">
                    <do_if value="$mk4BuySectorOrder.{$bssj} == $bsSector">
                      <set_value name="$mk4SeenBuySector" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                  <do_if value="not $mk4SeenBuySector">
                    <append_to_list name="$mk4BuySectorOrder" exact="$bsSector"/>
                  </do_if>
                </do_if>
              </do_all>
              <create_list name="$mk4BuyPhaseCompacted"/>
              <do_all exact="$mk4BuySectorOrder.count" counter="$bsi">
                <set_value name="$buySectorKey" exact="$mk4BuySectorOrder.{$bsi}"/>
                <do_all exact="$mk4QueueableTrades.count" counter="$bci">
                  <set_value name="$bct" exact="$mk4QueueableTrades.{$bci}"/>
                  <set_value name="$bctSector" exact="if $bct.$BuySector? then $bct.$BuySector else (if $bct.$BuyStation? then $bct.$BuyStation.sector else (if $bct.$BuyOffer? and $bct.$BuyOffer.owner? then $bct.$BuyOffer.owner.sector else null))"/>
                  <do_if value="$bctSector? and $bctSector == $buySectorKey">
                    <append_to_list name="$mk4BuyPhaseCompacted" exact="$bct"/>
                  </do_if>
                </do_all>
              </do_all>
              <!-- Keep sell-only/no-buy-sector legs stable after clustered buy legs. -->
              <do_all exact="$mk4QueueableTrades.count" counter="$bni">
                <set_value name="$bnt" exact="$mk4QueueableTrades.{$bni}"/>
                <set_value name="$bntSector" exact="if $bnt.$BuySector? then $bnt.$BuySector else (if $bnt.$BuyStation? then $bnt.$BuyStation.sector else (if $bnt.$BuyOffer? and $bnt.$BuyOffer.owner? then $bnt.$BuyOffer.owner.sector else null))"/>
                <do_if value="not $bntSector?">
                  <append_to_list name="$mk4BuyPhaseCompacted" exact="$bnt"/>
                </do_if>
              </do_all>
              <do_if value="$mk4BuyPhaseCompacted.count == $mk4QueueableTrades.count">
                <set_value name="$mk4BuyPhaseTrades" exact="$mk4BuyPhaseCompacted"/>
              </do_if>
            </do_if>

            <do_all exact="$mk4BuyPhaseTrades.count" counter="$qri2">
              <set_value name="$qidx" exact="$mk4BuyPhaseTrades.count - $qri2 + 1"/>
              <set_value name="$qt" exact="$mk4BuyPhaseTrades.{$qidx}"/>
              <set_value name="$qtIsSellOnlyExec" exact="$qt.$IsSellOnly? and $qt.$IsSellOnly"/>
              <set_value name="$qtExecBuyAmount" exact="if $qt.$QueuedBuyAmount? then $qt.$QueuedBuyAmount else (if $qt.$FinalBuyAmount? then $qt.$FinalBuyAmount else $qt.$Amount)"/>
              <set_value name="$qtBuyLegInternal" exact="false"/>
              <do_if value="$qt.$BuyStation? and $qt.$BuyStation.exists and $qt.$BuyStation.isplayerowned">
                <set_value name="$qtBuyLegInternal" exact="true"/>
              </do_if>
              <do_elseif value="$qt.$BuyOffer? and $qt.$BuyOffer.owner? and $qt.$BuyOffer.owner.exists and $qt.$BuyOffer.owner.isplayerowned">
                <set_value name="$qtBuyLegInternal" exact="true"/>
              </do_elseif>
              <do_if value="not $qtIsSellOnlyExec and $qt.$BuyOffer? and $qtExecBuyAmount gt 0">
                <create_trade_order object="this.ship" tradeoffer="$qt.$BuyOffer" amount="$qtExecBuyAmount" immediate="true" internal="$qtBuyLegInternal"/>
                <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$buyOfferAmountAfterOrder" exact="@$qt.$BuyOffer.offeramount.{this.ship}"/>
                  <set_value name="$buyDesiredAfterOrder" exact="@$qt.$BuyOffer.desiredamount"/>
                  <debug_text text="'[GT-Reserve] ' + this.ship.idcode + ': after create_trade_order BUY (phase=BUY, leg ' + $qidx + '/' + $mk4BuyPhaseTrades.count + ')' +
                    '\n  orderAmount=' + $qtExecBuyAmount +
                    '\n  buy offeramount(ship)=' + (if $buyOfferAmountAfterOrder? then $buyOfferAmountAfterOrder else 'null') +
                    '\n  buy desiredamount=' + (if $buyDesiredAfterOrder? then $buyDesiredAfterOrder else 'null')"
                    chance="100"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>

          <!-- Phase C: runtime illegal-route policy snapshot (cleared on completion/abort). -->
          <do_if value="$effectiveAllowIllegal and $effectiveEnforceRouteIllegalLegality">
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{this.ship}?">
              <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
            </do_if>
            <set_value name="$atpBuySector" exact="if not $isSellOnlyTradeForPending and $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner.sector else null"/>
            <set_value name="$atpSellSector" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.sector else null"/>
            <set_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy" exact="table[
              $AllowIllegal = $effectiveAllowIllegal,
              $EnforceRouteIllegalLegality = $effectiveEnforceRouteIllegalLegality,
              $Ware = $finalRouteWare,
              $BuySector = $atpBuySector,
              $SellSector = $atpSellSector,
              $HomeSector = $searchHomeSector,
              $RouteStart = this.ship.sector,
              $Leg = if $isSellOnlyTradeForPending then 'sell' else 'buy',
              $LogbookEntries = $gt_logbookentries,
              $SetAt = player.age
            ]"/>
          </do_if>
          <do_else>
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
              <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
            </do_if>
          </do_else>

          <!-- Fallback flag follows the source of the CURRENT created trade order. -->
          <do_if value="$searchMethod == 'live_fallback'">
            <do_if value="not global.$GT_FallbackTradeActive?">
              <set_value name="global.$GT_FallbackTradeActive" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_FallbackTradeActive.{this.ship}" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Set [FALLBACK] flag - created trade from live_fallback'" chance="100"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='fallback'
              ]"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <remove_value name="global.$GT_FallbackTradeActive.{this.ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Cleared [FALLBACK] flag - created trade from ' + (if $searchMethod != '' then $searchMethod else 'unknown source') + ' (not live_fallback)'" chance="100"/>
              </do_if>
              <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
                <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                  $Ship=this.ship,
                  $pilot=this.ship.pilot,
                  $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                  $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                  $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                  $nameType='trader'
                ]"/>
              </do_if>
            </do_if>
          </do_else>
          
          <!-- Clear fleet reservation: create_trade_order has been called, X4 native offeramount.{ship}
               now handles capacity coordination. Remove our pre-selection reservation. -->
          <do_if value="this.$activeReservationKey? and global.$GT_Reservations? and global.$GT_Reservations.{this.$activeReservationKey}?">
            <remove_value name="global.$GT_Reservations.{this.$activeReservationKey}"/>
            <do_if value="global.$GT_ReservationStats? and global.$GT_ReservationStats.$Active gt 0">
              <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
            </do_if>
            <do_if value="global.$GT_ReservationStats?">
              <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Fleet reservation CLEARED (trade orders created, native system active)'" chance="100"/>
            </do_if>
          </do_if>
          <remove_value name="this.$activeReservationKey"/>
          
          <!-- Scenario 2: Purge consumed trade from cache so other ships don't pick it -->
          <do_if value="$searchMethod == 'cache'">
            <do_if value="$mk4QueueableTrades? and $mk4QueueableTrades.count gt 0">
              <do_all exact="$mk4QueueableTrades.count" counter="$cpIdx">
                <set_value name="$cpTrade" exact="$mk4QueueableTrades.{$cpIdx}"/>
                <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                  $Ship = this.ship,
                  $BuyOffer = @$cpTrade.$BuyOffer,
                  $SellOffer = @$cpTrade.$SellOffer,
                  $HomeSector = $searchHomeSector,
                  $CachePool = 'mk42',
                  $Reason = 'consumed'
                ]"/>
              </do_all>
            </do_if>
            <do_else>
              <signal_objects object="player.galaxy" param="'GT_Cache_Purge'" param2="table[
                $Ship = this.ship,
                $BuyOffer = @$pendingTrade.$BuyOffer,
                $SellOffer = @$pendingTrade.$SellOffer,
                $HomeSector = $searchHomeSector,
                $CachePool = 'mk42',
                $Reason = 'consumed'
              ]"/>
            </do_else>
          </do_if>
          
          <!-- Purge trades awaiting validation after we successfully queued trade orders.
               Keeping them causes stale execution via old trade data. -->
          <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <!-- Clear interrupt flag when clearing trades awaiting validation (trades successfully processed) -->
          <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>

          <!-- Add state update signal AFTER order creation -->
          <!-- This tests if sending a signal immediately after create_trade_order interferes with TradePerform initialization -->
          <!-- NOTE: No handler exists yet (Phase 3) - signal will be sent but not processed -->
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'Trade_Order_Created',
            $TradeOrderCount = this.ship.tradeorders.count
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PHASE 2: State update signal sent (Trade_Order_Created)'" chance="100"/>
            
            <!-- Handle sell-only trades in debug output -->
              <set_value name="$buyOrderText" exact="if $isSellOnlyTradeForPending then 'N/A (sell-only - ship already has cargo)' else (if $buyStationForPending? then @$buyStationForPending.knownname + ' â†’ ' + (if $wareForPendingTrade? then @$wareForPendingTrade.name else 'Unknown') + ' (x' + $finalBuyAmount + ')' else 'Unknown')"/>
            <set_value name="$sellOrderText" exact="if $sellStationForPending? then @$sellStationForPending.knownname else 'Unknown'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade orders created:' +
              '\n  BUY: ' + $buyOrderText +
              '\n  SELL: ' + $sellOrderText"
              chance="100"/>
          </do_if>
          
          <!-- Send logbook message when ship is escaping from blacklisted sector -->
          <set_value name="$isEscapeTrade" exact="false"/>
          <do_if value="$currentSectorIsBlacklisted">
            <!-- Check if trade leads to a different sector (escape route) -->
            <set_value name="$isEscapeTrade" exact="($buySector != $currentSector) or ($sellSector != $currentSector)"/>
          </do_if>
          
          <do_if value="$isEscapeTrade">
            <!-- Set escape flag for ship naming -->
            <do_if value="global.$GT_Ships?">
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>

            <!-- Build escape route message using translation -->
            <!-- Extract values safely with null checks -->
            <set_value name="$escapeWare" exact="null"/>
            <set_value name="$escapeAmount" exact="0"/>
            <set_value name="$escapeProfit" exact="0"/>
            
            <!-- Extract ware from BuyOffer (more reliable than $Ware property) -->
            <do_if value="$pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware?">
              <set_value name="$escapeWare" exact="$pendingTrade.$BuyOffer.ware.name"/>
            </do_if>
            <do_elseif value="$pendingTrade.$Ware?">
              <set_value name="$escapeWare" exact="$pendingTrade.$Ware.name"/>
            </do_elseif>
            
            <!-- Extract amount -->
            <set_value name="$escapeAmount" exact="if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount"/>
            
            <!-- Extract profit -->
            <do_if value="$pendingTrade.$Profit?">
              <set_value name="$escapeProfit" exact="$pendingTrade.$Profit"/>
            </do_if>
            
            <!-- Safe defaults for missing values -->
            <set_value name="$currentSectorName" exact="'Unknown Sector'"/>
            <do_if value="$currentSector?">
              <set_value name="$currentSectorNameTemp" exact="@$currentSector.knownname"/>
              <do_if value="$currentSectorNameTemp?">
                <set_value name="$currentSectorName" exact="$currentSectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$buyStationName" exact="'Unknown Station'"/>
            <do_if value="$buyStation?">
              <set_value name="$buyStationNameTemp" exact="@$buyStation.knownname"/>
              <do_if value="$buyStationNameTemp?">
                <set_value name="$buyStationName" exact="$buyStationNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$buySectorName" exact="'Unknown Sector'"/>
            <do_if value="$buySector?">
              <set_value name="$buySectorNameTemp" exact="@$buySector.knownname"/>
              <do_if value="$buySectorNameTemp?">
                <set_value name="$buySectorName" exact="$buySectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$sellStationName" exact="'Unknown Station'"/>
            <do_if value="$sellStation?">
              <set_value name="$sellStationNameTemp" exact="@$sellStation.knownname"/>
              <do_if value="$sellStationNameTemp?">
                <set_value name="$sellStationName" exact="$sellStationNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$sellSectorName" exact="'Unknown Sector'"/>
            <do_if value="$sellSector?">
              <set_value name="$sellSectorNameTemp" exact="@$sellSector.knownname"/>
              <do_if value="$sellSectorNameTemp?">
                <set_value name="$sellSectorName" exact="$sellSectorNameTemp"/>
              </do_if>
            </do_if>
            
            <set_value name="$wareInfo" exact="'Unknown Ware'"/>
            <do_if value="$escapeWare?">
              <set_value name="$wareInfo" exact="$escapeWare"/>
            </do_if>
            
            <!-- Build message using translation ID 3210 with 8 parameters -->
            <!-- Parameters: currentSector, buyStation, buySector, sellStation, sellSector, ware, amount, profit -->
            <set_value name="$escapeMessage" exact="{77000,3210}.[$currentSectorName,$buyStationName,$buySectorName,$sellStationName,$sellSectorName,$wareInfo,$escapeAmount,($escapeProfit / 100)]"/>
            
            <!-- Log the message being written -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE ROUTE LOGBOOK DEBUG:' + '\n  Current Sector: ' + $currentSectorName + '\n  Buy: ' + $buyStationName + ' (' + $buySectorName + ')' + '\n  Sell: ' + $sellStationName + ' (' + $sellSectorName + ')' + '\n  Ware: ' + $wareInfo + ' (x' + $escapeAmount + ')' + '\n  Profit: ' + ($escapeProfit / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <!-- Log the full message text that will be written to logbook -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE ROUTE LOGBOOK MESSAGE:' + '\n' + $escapeMessage" chance="100"/>
            </do_if>
            
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3210}.[$currentSectorName,$buyStationName,$buySectorName,$sellStationName,$sellSectorName,$wareInfo,$escapeAmount,($escapeProfit / 100)]"/>
            
            <!-- Write to ship logbook -->
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'general',
              $Title = 'Escape Route: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Escape route logbook entry created'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clear UR state once a valid trade was selected for execution. -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
            <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Log to ship logbook if enabled (moved from MD execution to after validation) -->
          <set_value name="$logbookEnabled" exact="false"/>
          <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK4Supply2' and @this.ship.defaultorder.$logbookentries">
            <set_value name="$logbookEnabled" exact="true"/>
          </do_if>
          <do_elseif value="@this.ship.defaultorder.id == 'Assist' and (((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2') and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
            <set_value name="$logbookEnabled" exact="true"/>
          </do_elseif>

          <!-- Canonical queued trade prices in RAW: use pendingTrade snapshot first (real created-trade values). -->
          <set_value name="$buyPriceRawCanonical" exact="if $pendingTrade.$BuyPrice? then $pendingTrade.$BuyPrice else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.unitprice? then $pendingTrade.$BuyOffer.unitprice else 0)"/>
          <set_value name="$sellPriceRawCanonical" exact="if $pendingTrade.$SellPrice? then $pendingTrade.$SellPrice else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.unitprice? then $pendingTrade.$SellOffer.unitprice else 0)"/>
          <set_value name="$isMultiTradeSignal" exact="$mk4CycleLegCount gt 1"/>
          <set_value name="$uiProfitRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleProfitRaw else (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 0)"/>

          <!-- UI bridge: always publish queued-trade values (independent of per-ship logbook setting). -->
          <set_value name="$uiLogAmount" exact="if $isMultiTradeSignal then $mk4CycleAmountTotal else (if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount)"/>
          <set_value name="$uiBuyPriceRawForSignal" exact="if $isMultiTradeSignal then 0 else $buyPriceRawCanonical"/>
          <set_value name="$uiMoneyRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleMoneyRawTotal else (-$uiLogAmount * $uiBuyPriceRawForSignal)"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$rawBuyOfferUnitPrice" exact="if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.unitprice? then $pendingTrade.$BuyOffer.unitprice else -1"/>
            <set_value name="$rawSellOfferUnitPrice" exact="if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.unitprice? then $pendingTrade.$SellOffer.unitprice else -1"/>
            <set_value name="$rawPendingTradeBuyPrice" exact="if $pendingTrade.$BuyPrice? then $pendingTrade.$BuyPrice else -1"/>
            <set_value name="$rawPendingTradeSellPrice" exact="if $pendingTrade.$SellPrice? then $pendingTrade.$SellPrice else -1"/>
            <set_value name="$rawPendingTradeProfit" exact="$uiProfitRawForSignal"/>
            <set_value name="$rawSignalSum" exact="abs($uiMoneyRawForSignal) + $rawPendingTradeProfit"/>
            <debug_text text="'[GT-AI-UI-DUE] ' + this.ship.idcode +
              '\n  MultiTrade: ' + $isMultiTradeSignal + ' (legs=' + $mk4CycleLegCount + ')' +
              '\n  Amount: ' + $uiLogAmount +
              '\n  BuyOffer.unitprice (RAW): ' + $rawBuyOfferUnitPrice +
              '\n  SellOffer.unitprice (RAW): ' + $rawSellOfferUnitPrice +
              '\n  pendingTrade.BuyPrice (RAW?): ' + $rawPendingTradeBuyPrice +
              '\n  pendingTrade.SellPrice (RAW?): ' + $rawPendingTradeSellPrice +
              '\n  Canonical buy price (RAW): ' + $uiBuyPriceRawForSignal +
              '\n  Canonical sell price (RAW): ' + $sellPriceRawCanonical +
              '\n  MoneyRaw sent: ' + $uiMoneyRawForSignal + ' (' + ($uiMoneyRawForSignal / 100) + ' Cr)' +
              '\n  Profit sent (RAW): ' + $rawPendingTradeProfit + ' (' + ($rawPendingTradeProfit / 100) + ' Cr)' +
              '\n  Expected due sum RAW: ' + $rawSignalSum + ' (' + ($rawSignalSum / 100) + ' Cr)'" chance="100"/>
          </do_if>
          <do_if value="$logbookEnabled">
            <set_value name="$logAmount" exact="if $isMultiTradeSignal then $mk4CycleAmountTotal else (if $isSellOnlyTradeForPending then $finalSellAmount else $finalBuyAmount)"/>
            <set_value name="$logProfitRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleProfitRaw else (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 0)"/>
            <set_value name="$logMoneyRawForSignal" exact="if $isMultiTradeSignal then $mk4CycleMoneyRawTotal else (-$logAmount * $buyPriceRawCanonical)"/>
            
            <!-- PROFIT DEBUG: Log trade data before sending to logbook -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$wareName" exact="if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.ware? then @$pendingTrade.$BuyOffer.ware.name else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.ware? then @$pendingTrade.$SellOffer.ware.name else 'NULL')"/>
              <set_value name="$buyStationName" exact="if $pendingTrade.$BuyStation? then @$pendingTrade.$BuyStation.knownname else (if $pendingTrade.$BuyOffer? and $pendingTrade.$BuyOffer.owner? then @$pendingTrade.$BuyOffer.owner.knownname else 'NULL')"/>
              <set_value name="$sellStationName" exact="if $pendingTrade.$SellStation? then @$pendingTrade.$SellStation.knownname else (if $pendingTrade.$SellOffer? and $pendingTrade.$SellOffer.owner? then @$pendingTrade.$SellOffer.owner.knownname else 'NULL')"/>
              <set_value name="$originalAmount" exact="if $pendingTrade.$Amount? then $pendingTrade.$Amount else 'NULL'"/>
              <!-- Use canonical raw snapshot prices to keep buy/sell/profit consistent. -->
              <set_value name="$buyPrice" exact="$buyPriceRawCanonical"/>
              <set_value name="$sellPrice" exact="$sellPriceRawCanonical"/>
              <debug_text text="'[GT-AI-PROFIT] (' + this.ship.idcode + ') LOGBOOK ENTRY PREPARATION:' + 
                '\n  Ware: ' + $wareName +
                '\n  Buy Station: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr (RAW: ' + $buyPrice + ')' +
                '\n  Sell Station: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr (RAW: ' + $sellPrice + ')' +
                '\n  Original Amount (from trade): ' + $originalAmount + ' units' +
                '\n  Final Buy Amount (clamped): ' + $finalBuyAmount + ' units' +
                '\n  Final Sell Amount (clamped): ' + $finalSellAmount + ' units' +
                '\n  Log Amount (used for display): ' + $logAmount + ' units' +
                '\n  Profit (RAW): ' + (if $pendingTrade.$Profit? then $pendingTrade.$Profit else 'NULL') + ' = ' + (if $pendingTrade.$Profit? then ($pendingTrade.$Profit/100) + ' Cr' else 'NULL') +
                '\n  Verification with original amount: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $originalAmount + ' = ' + (if $originalAmount != 'NULL' then (($sellPrice - $buyPrice) * $originalAmount / 100) + ' Cr' else 'N/A') +
                '\n  Verification with log amount: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $logAmount + ' = ' + (($sellPrice - $buyPrice) * $logAmount / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <!-- Use canonical raw snapshot prices for queued trade message. -->
            <set_value name="$buyPriceForSignal" exact="if $isMultiTradeSignal then 0 else ($buyPriceRawCanonical / 100)"/>
            <set_value name="$sellPriceForSignal" exact="if $isMultiTradeSignal then 0 else ($sellPriceRawCanonical / 100)"/>
            <set_value name="$buyPriceRawForSignal" exact="if $isMultiTradeSignal then 0 else $buyPriceRawCanonical"/>
            <set_value name="$sellPriceRawForSignal" exact="if $isMultiTradeSignal then 0 else $sellPriceRawCanonical"/>
            
            <!-- Determine search pipeline type for logbook display -->
            <set_value name="$logSearchPipeline" exact="'normal'"/>
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?">
              <set_value name="$logSearchPipeline" exact="'isolated'"/>
            </do_if>
            <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{this.ship}?">
              <set_value name="$logSearchPipeline" exact="'fallback'"/>
            </do_elseif>
            <signal_objects object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'" param2="table[
              $Ship = this.ship,
              $BuyOffer = if $pendingTrade.$BuyOffer? then $pendingTrade.$BuyOffer else null,
              $SellOffer = if $pendingTrade.$SellOffer? then $pendingTrade.$SellOffer else null,
              $BuyStation = if $pendingTrade.$BuyStation? and $pendingTrade.$BuyStation.exists then $pendingTrade.$BuyStation else null,
              $SellStation = if $pendingTrade.$SellStation? and $pendingTrade.$SellStation.exists then $pendingTrade.$SellStation else null,
              $Amount = $logAmount,
              $Profit = $logProfitRawForSignal,
              $BuyPrice = $buyPriceForSignal,
              $SellPrice = $sellPriceForSignal,
              $BuyPriceRaw = $buyPriceRawForSignal,
              $SellPriceRaw = $sellPriceRawForSignal,
              $MoneyRaw = $logMoneyRawForSignal,
              $IsSellOnly = $isSellOnlyTradeForPending,
              $IsMk4Supply = true,
              $PlayerFreeSupplier = if $pendingTrade.$PlayerFreeSupplier? and $pendingTrade.$PlayerFreeSupplier then true else false,
              $IsMultiTrade = $isMultiTradeSignal,
              $MultiTradeLegs = if $isMultiTradeSignal then $mk4MultiTradeLegs else [],
              $MultiTradeSummaryMax = if $isMultiTradeSignal then 6 else 0,
              $SearchPipeline = $logSearchPipeline
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI-LOG-SIGNAL] ' + this.ship.idcode +
                '\n  sell-only: ' + $isSellOnlyTradeForPending + ', multitrade: ' + $isMultiTradeSignal + ' (legs=' + $mk4CycleLegCount + '), pipeline: ' + $logSearchPipeline +
                '\n  Amount sent: ' + $logAmount +
                '\n  BuyPrice sent (Cr): ' + $buyPriceForSignal +
                '\n  SellPrice sent (Cr): ' + $sellPriceForSignal +
                '\n  BuyPrice sent (RAW): ' + $buyPriceRawForSignal +
                '\n  SellPrice sent (RAW): ' + $sellPriceRawForSignal +
                '\n  Profit sent (RAW): ' + $logProfitRawForSignal +
                '\n  MoneyRaw sent: ' + $logMoneyRawForSignal + ' (' + ($logMoneyRawForSignal / 100) + ' Cr)' +
                (if $isMultiTradeSignal then '\n  MultiTradeLegs: ' + $mk4MultiTradeLegs.count else '')" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Full-sweep mode: no chunk continuation needed. -->
          <!-- All trades in list were rejected - check reason -->
          <!-- Use safe access for variables that might not exist -->
          <set_value name="$tradesRejectedPathSafe" exact="if $tradesRejectedPath? then $tradesRejectedPath else 0"/>
          <set_value name="$tradesRejectedDockingSafe" exact="if $tradesRejectedDocking? then $tradesRejectedDocking else 0"/>
          <set_value name="$tradesRejectedOfferInvalidSafe" exact="if $tradesRejectedOfferInvalid? then $tradesRejectedOfferInvalid else 0"/>
          <set_value name="$tradesRejectedDistanceSafe" exact="if $tradesRejectedDistance? then $tradesRejectedDistance else 0"/>
          <set_value name="$tradesRejectedCargoSafe" exact="if $tradesRejectedCargo? then $tradesRejectedCargo else 0"/>
          <set_value name="$tradesRejectedRestrictionSafe" exact="if $tradesRejectedRestriction? then $tradesRejectedRestriction else 0"/>
          <set_value name="$tradesRejectedDemandReservedSafe" exact="if $tradesRejectedDemandReserved? then $tradesRejectedDemandReserved else 0"/>
          <set_value name="$tradesBlacklistedSafe" exact="if $tradesBlacklisted? then $tradesBlacklisted else 0"/>
          <!-- Use safe access for $tradeList.count -->
          <set_value name="$tradeListCountSafe" exact="if $tradeList != null then $tradeList.count else 0"/>
          <!-- UR must mean route-blocked by blacklist/pathing only (not distance-limit rejects). -->
          <set_value name="$unreachableRejectedSafe" exact="$tradesBlacklistedSafe + $tradesRejectedPathSafe"/>
          <set_value name="$isIsolatedMode" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
          <set_value name="$isUnreachableOnly" exact="$tradeListCountSafe gt 0 and $searchMethod == 'live' and $unreachableRejectedSafe == $tradeListCountSafe"/>
          
          <!-- Search method already captured earlier in trade_found label -->
          <!-- (from cache, signal param2, or global storage) -->
          
          <!-- Enhanced logging for cache trade rejections -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$searchSource" exact="if $searchMethod == 'cache' then 'CACHE' else if $searchMethod == 'live' then 'LIVE' else 'UNKNOWN'"/>
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ALL ' + $tradeListCountSafe + ' trades from ' + $searchSource + ' were rejected:' +
              '\n  Path blocked: ' + $tradesRejectedPathSafe +
              '\n  Docking denied: ' + $tradesRejectedDockingSafe +
              '\n  Offer invalid: ' + $tradesRejectedOfferInvalidSafe +
              '\n  Distance unreachable: ' + $tradesRejectedDistanceSafe +
              '\n  Cargo insufficient: ' + $tradesRejectedCargoSafe +
              '\n  Restriction blocked: ' + $tradesRejectedRestrictionSafe +
              '\n  Demand reserved exhausted: ' + $tradesRejectedDemandReservedSafe +
              '\n  Blacklisted: ' + $tradesBlacklistedSafe +
              '\n  Total rejected: ' + $tradeListCountSafe +
              (if $searchMethod == 'cache' then '\n  Cache exhausted: all ' + $tradeListCountSafe + ' cache candidates failed validation (Restriction=' + $tradesRejectedRestrictionSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Path=' + $tradesRejectedPathSafe + ', Blacklist=' + $tradesBlacklistedSafe + ')' else '') +
              ' - entering retry logic'" chance="100"/>
          </do_if>
          
          <!-- CRITICAL:
               If ALL trades were rejected (often because offers changed), we MUST purge trades awaiting validation.
               Otherwise the ship can loop forever on stale global.$GT_TradesAwaitingValidation.{this.ship} and never request fresh trades. -->
          <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
          </do_if>
          <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
            <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
          </do_if>
          <!-- Clear interrupt flag when clearing trades awaiting validation to prevent re-entry loop -->
          <set_value name="this.$tradeFoundViaInterrupt" exact="false"/>
          <!-- Reduce escalating backoff after purging stale results: next retry will start at 10s again -->
          <set_value name="this.$searchFailed" exact="0"/>

          <!-- Isolated mode is current-sector-only. Remove stale UR and do not re-apply it while isolated. -->
          <do_if value="$isIsolatedMode and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$Unreachable?">
            <remove_value name="global.$GT_Ships.{this.ship}.$Unreachable"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
          </do_if>

          <!-- Mark unreachable-routes state when all evaluated live trades are blocked by blacklist/path reachability. -->
          <do_if value="$isUnreachableOnly and not $isIsolatedMode">
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{this.ship}?">
              <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{this.ship}.$Unreachable" exact="true"/>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>

            <!-- Roleplay logbook message (throttled) for blacklist/path unreachable profitable routes. -->
            <do_if value="$gt_logbookentries">
              <set_value name="$lastUnreachableLogbook" exact="0"/>
              <do_if value="this.$lastUnreachableLogbookTime?">
                <set_value name="$lastUnreachableLogbook" exact="this.$lastUnreachableLogbookTime"/>
              </do_if>
              <set_value name="$unreachableSinceLast" exact="player.age - $lastUnreachableLogbook"/>
              <do_if value="$lastUnreachableLogbook == 0 or $unreachableSinceLast ge 300s">
                <set_value name="$urCurrentSectorName" exact="if this.ship.sector? then @this.ship.sector.knownname else 'Unknown Sector'"/>
                <set_value name="$urNormalRange" exact="if this.$effectiveMaxBuy? and this.$effectiveMaxSell? then [this.$effectiveMaxBuy, this.$effectiveMaxSell].max else (if this.$effectiveMaxSell? and this.$effectiveMaxSell gt 0 then this.$effectiveMaxSell else 1)"/>
                <set_value name="$urNearbyRange" exact="[1, ($urNormalRange / 3)i].max"/>
                <set_value name="$urMessage" exact="{77000,3221}.[this.ship.knownname, $urCurrentSectorName, $urNormalRange, $urNearbyRange]"/>
                <set_value name="$redColor" exact="'\033#FFCC0000#'"/>
                <set_value name="$colorReset" exact="'\033X'"/>
                <set_value name="$urTitle" exact="$redColor + 'Unreachable Routes: ' + $colorReset + this.ship.knownname"/>
                <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                  $Message = $urMessage,
                  $Category = 'alerts',
                  $Title = $urTitle,
                  $Object = this.ship,
                  $Interaction = 'showonmap',
                  $CheckGlobalSettings = true
                ]"/>
                <set_value name="this.$lastUnreachableLogbookTime" exact="player.age"/>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Keep UR sticky across unsuccessful search cycles.
                 UR is intentionally cleared only when a valid trade is selected for execution. -->
          </do_else>
          
          <!-- If ALL trades rejected due to cargo space, trigger cargo disposal -->
          <!-- Use safe access for variable check -->
          <do_if value="$tradesRejectedCargoSafe gt 0 and $tradesRejectedCargoSafe == $tradeListCountSafe">
            <set_value name="$hasCargo" exact="this.ship.cargo.free.all lt this.ship.cargo.capacity.all"/>
            <do_if value="$hasCargo">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ':  ALL trades rejected due to insufficient cargo space - triggering cargo disposal'" chance="100"/>
              </do_if>
              <!-- Ship has cargo but not enough space for any trade - find buyer for existing cargo -->
              <signal_objects object="player.galaxy" param="'GT_Find_Sell'" param2="table[
                $Ship = this.ship,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true
              ]"/>
              <!-- CRITICAL: Resume to wait_for_response so ship is ready to receive GT_Search_Go immediately.
                   Resuming to main_loop caused GT_Search_Go to arrive while ship was busy elsewhere (no matching
                   interrupt), leading to missed signals and up-to-60s waits for sell-order discovery. -->
              <resume label="wait_for_response"/>
            </do_if>
          </do_if>

          <!-- ESCAPE FALLBACK (trade list exists but none can move us out safely):
               If we are in a blacklisted sector and we have no non-blacklisted escape trade, force a move toward home.
               Whitelist overrides blacklist (matches GT_IsSectorBlacklisted). -->
          <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
          <set_value name="$validationWhitelist" exact="[]"/>
          <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
            <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
          </do_if>
          <set_value name="$currentSector" exact="this.ship.sector"/>
          <set_value name="$needsEscape" exact="false"/>
          <do_if value="$currentSector? and $currentSector.exists">
            <set_value name="$curWhitelisted" exact="false"/>
            <do_if value="$validationWhitelist.count gt 0">
              <do_all exact="$validationWhitelist.count" counter="$swIdx">
                <do_if value="$validationWhitelist.{$swIdx} == $currentSector">
                  <set_value name="$curWhitelisted" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $curWhitelisted">
              <set_value name="$curActivityBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
              <set_value name="$curTravelBL" exact="@$currentSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
              <set_value name="$needsEscape" exact="$curActivityBL or $curTravelBL"/>
            </do_if>
          </do_if>
          <do_if value="$needsEscape and ($tradeListCountSafe == 0 or $tradesBlacklistedSafe == $tradeListCountSafe)">
            <!-- Set escape flag for ship naming -->
            <do_if value="global.$GT_Ships?">
              <do_if value="not global.$GT_Ships.{this.ship}?">
                <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
            </do_if>
            <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship=this.ship,
                $pilot=this.ship.pilot,
                $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
                $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
                $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
                $nameType='trader'
              ]"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: No valid escape trade found (all trades blacklisted) - moving toward home sector'" chance="100"/>
            </do_if>
            <resume label="escape_from_blacklisted"/>
          </do_if>
          
          <!-- Cache exhausted: retry remaining cache entries before forcing mk4live when rejections
               are transient-only (stale offers / demand saturation) and the home pool is larger. -->
          <do_if value="$searchMethod == 'cache'">
            <set_value name="$cacheHardRejectTotal" exact="$tradesRejectedPathSafe + $tradesRejectedDockingSafe + $tradesRejectedDistanceSafe + $tradesRejectedCargoSafe + $tradesRejectedRestrictionSafe + $tradesBlacklistedSafe"/>
            <set_value name="$cacheTransientRejectTotal" exact="$tradesRejectedOfferInvalidSafe + $tradesRejectedDemandReservedSafe"/>
            <set_value name="$cacheExhaustedTransientOnly" exact="$tradeListCountSafe gt 0 and $cacheHardRejectTotal == 0 and $cacheTransientRejectTotal == $tradeListCountSafe"/>
            <set_value name="$cacheExhaustHomeSector" exact="if this.$lastPriorityWaresHome? and this.$lastPriorityWaresHome.exists then this.$lastPriorityWaresHome else (if this.$effectiveHome? and this.$effectiveHome.isclass.sector then this.$effectiveHome else (if this.$effectiveHome? and this.$effectiveHome.sector? then @this.$effectiveHome.sector else this.ship.sector))"/>
            <set_value name="$cacheExhaustPoolSize" exact="0"/>
            <do_if value="$cacheExhaustHomeSector? and $cacheExhaustHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$cacheExhaustHomeSector}?">
              <set_value name="$cacheExhaustPoolSize" exact="@global.$GT_TradeCacheMK42.{$cacheExhaustHomeSector}.count"/>
            </do_if>
            <do_if value="$cacheExhaustedTransientOnly and $cacheExhaustPoolSize gt $tradeListCountSafe">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache batch exhausted (transient-only) â€” retrying cache before live (' + $tradeListCountSafe + '/' + $cacheExhaustPoolSize + ' entries tried, home=' + (if $cacheExhaustHomeSector.knownname? then @$cacheExhaustHomeSector.knownname else '?') + ')'" chance="100"/>
              </do_if>
              <!-- Stale-offer rejections flag per-ship on entries; clear before retry so other pool rows can match. -->
              <do_if value="$cacheExhaustHomeSector? and $cacheExhaustHomeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$cacheExhaustHomeSector}?">
                <do_all exact="global.$GT_TradeCacheMK42.{$cacheExhaustHomeSector}.count" counter="$cacheRetryFsi">
                  <set_value name="$cacheRetryEntry" exact="global.$GT_TradeCacheMK42.{$cacheExhaustHomeSector}.{$cacheRetryFsi}"/>
                  <do_if value="$cacheRetryEntry? and $cacheRetryEntry.$FailedShips? and $cacheRetryEntry.$FailedShips.count gt 0">
                    <set_value name="$cacheRetryNewFailed" exact="[]"/>
                    <do_all exact="$cacheRetryEntry.$FailedShips.count" counter="$cacheRetryFsi2">
                      <do_if value="$cacheRetryEntry.$FailedShips.{$cacheRetryFsi2} != this.ship">
                        <append_to_list name="$cacheRetryNewFailed" exact="$cacheRetryEntry.$FailedShips.{$cacheRetryFsi2}"/>
                      </do_if>
                    </do_all>
                    <set_value name="$cacheRetryEntry.$FailedShips" exact="$cacheRetryNewFailed"/>
                  </do_if>
                </do_all>
              </do_if>
              <set_value name="$signalMaxBuy" exact="$maxbuy"/>
              <set_value name="$signalMaxSell" exact="$maxsell"/>
              <do_if value="this.$effectiveMaxBuy?">
                <set_value name="$signalMaxBuy" exact="this.$effectiveMaxBuy"/>
              </do_if>
              <do_if value="this.$effectiveMaxSell?">
                <set_value name="$signalMaxSell" exact="this.$effectiveMaxSell"/>
              </do_if>
              <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
                $Ship = this.ship,
                $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
                $MaxBuy = $signalMaxBuy,
                $MaxSell = $signalMaxSell,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
                $SearchPool = 'mk4_supply_v2',
                $SearchDepth = if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30,
                $ForceLiveSearch = false,
                $LiveSearchPriority = false
              ]"/>
              <resume label="wait_for_response"/>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache exhausted â€” all ' + $tradeListCountSafe + ' cache candidates failed validation, triggering LIVE market search' +
                  '\n  Rejection breakdown: Path=' + $tradesRejectedPathSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Distance=' + $tradesRejectedDistanceSafe + ', Cargo=' + $tradesRejectedCargoSafe + ', Restriction=' + $tradesRejectedRestrictionSafe + ', DemandReserved=' + $tradesRejectedDemandReservedSafe + ', Blacklist=' + $tradesBlacklistedSafe +
                  (if $cacheExhaustPoolSize gt 0 then '\n  Home cache pool size: ' + $cacheExhaustPoolSize else '')" chance="100"/>
              </do_if>
              <!-- Send signal to force live search (bypass cache) -->
              <!-- Include MaxBuy/MaxSell - use effective values if available, otherwise use defaults from order params -->
              <set_value name="$signalMaxBuy" exact="$maxbuy"/>
              <set_value name="$signalMaxSell" exact="$maxsell"/>
              <do_if value="this.$effectiveMaxBuy?">
                <set_value name="$signalMaxBuy" exact="this.$effectiveMaxBuy"/>
              </do_if>
              <do_if value="this.$effectiveMaxSell?">
                <set_value name="$signalMaxSell" exact="this.$effectiveMaxSell"/>
              </do_if>
              <!-- effectiveIgnoreCarrierAux/BuildStorage/TradeRules initialized in <init> -->
              
              <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
                $Ship = this.ship,
                $HomeBase = if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else this.ship.sector),
                $MaxBuy = $signalMaxBuy,
                $MaxSell = $signalMaxSell,
                $IgnoreCarrierAux = @this.$effectiveIgnoreCarrierAux,
                $IgnoreBuildStorage = @this.$effectiveIgnoreBuildStorage,
                $IgnoreTradeRules = @this.$effectiveIgnoreTradeRules,
                $IgnoreMK1Supply = if this.$effectiveIgnoreMK1Supply? then this.$effectiveIgnoreMK1Supply else true,
                $SearchPool = 'mk4_supply_v2',
                $SearchDepth = if this.$effectiveSearchDepth? then this.$effectiveSearchDepth else 30,
                $ForceLiveSearch = true,
                $LiveSearchPriority = true
              ]"/>
              <!-- CRITICAL: Resume to wait_for_response instead of main_loop -->
              <!-- This ensures the ship waits for the live search result instead of sending a duplicate request -->
              <!-- The wait block will catch GT_Trade_Found signal when live search completes -->
              <resume label="wait_for_response"/>
            </do_else>
          </do_if>
          <do_elseif value="$searchMethod == 'live' or $searchMethod == 'live_sell_only' or $searchMethod == 'live_fallback'">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': All live trades rejected - releasing scheduler slot, backing off before fresh live search' +
                '\n  Rejection breakdown: Path=' + $tradesRejectedPathSafe + ', Docking=' + $tradesRejectedDockingSafe + ', OfferInvalid=' + $tradesRejectedOfferInvalidSafe + ', Distance=' + $tradesRejectedDistanceSafe + ', Cargo=' + $tradesRejectedCargoSafe + ', Restriction=' + $tradesRejectedRestrictionSafe + ', DemandReserved=' + $tradesRejectedDemandReservedSafe + ', Blacklist=' + $tradesBlacklistedSafe +
                '\n  All ' + $tradeListCountSafe + ' live trades invalid at validation - skip stale cache on next attempt'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
            <set_value name="this.$forceLiveAfterLiveReject" exact="true"/>
            <resume label="no_trade_retry"/>
          </do_elseif>
          <do_else>
            <!-- Trades came from unknown source - use normal retry -->
            <resume label="no_trade_retry"/>
          </do_else>
        </do_else>
      
      <!-- Stability: vanilla-style micro-yield after creating trade orders -->
      <!-- NOTE: wait must be at top level (not inside any do_if/do_else) -->
      <wait exact="this.$gt_yieldMs * 1ms"/>
      
      <!-- Set ship to trading state -->
      <set_command command="command.trade"/>
      
      <!-- Wait for trade completion or failure signal from diff patch (event-driven, no polling) -->
      <wait max="300s" comment="Wait for trade completion or failure signal">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Completed'"/>
              <event_object_signalled object="this.ship" param="'GT_Trade_Failed'"/>
            </check_any>
          </conditions>
          <actions>
            <!-- Check which signal was received -->
            <do_if value="event.param == 'GT_Trade_Completed'">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] Trade completed signal received for ' + this.ship.idcode" chance="100"/>
              </do_if>
              <set_value name="this.$tradeComplete" exact="true"/>
              
              <!-- Restore XPBlocked if BlockedLevel still exists (training stations may have become available) -->
              <do_if value="this.ship.pilot and global.$GT_Pilots.{this.ship.pilot}?">
                <do_if value="global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel? and not global.$GT_Pilots.{this.ship.pilot}.$XPBlocked? and not (global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
                  <set_value name="global.$GT_Pilots.{this.ship.pilot}.$XPBlocked" exact="true"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-AI] ðŸ”’ Restored XPBlocked for pilot ' + this.ship.pilot.name + ' after trade completion (BlockedLevel: ' + global.$GT_Pilots.{this.ship.pilot}.$BlockedLevel + ')'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
            <do_elseif value="event.param == 'GT_Trade_Failed'">
              <!-- Note: fallback flag is now managed only at trade creation based on search source. -->
              <!-- Isolated flag state will be verified by batch processor on next state check. -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] (' + this.ship.idcode + ') Trade failed - keeping current fallback state until next trade creation; isolation state will be checked by batch processor'" chance="100"/>
              </do_if>
              <!-- Read structured payload (with legacy guard for backward compatibility) -->
              <set_value name="$failurePayload" exact="event.param2"/>
              
              <!-- Handle legacy payloads (string) vs new structured payloads (table) -->
              <set_value name="$isLegacyPayload" exact="false"/>
              <do_if value="typeof $failurePayload == datatype.string">
                <set_value name="$isLegacyPayload" exact="true"/>
                <set_value name="this.$failureReason" exact="$failurePayload"/>
                <set_value name="this.$tradeFailed" exact="true"/>
                <set_value name="this.$tryNextTrade" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-AI] Trade failed (legacy payload) for ' + this.ship.idcode + ': ' + this.$failureReason" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- New structured payload -->
                <!-- Extract properties with safe access, then check if they exist -->
                <set_value name="$reasonTypeValue" exact="@$failurePayload.$ReasonType"/>
                <set_value name="$shouldTryNextValue" exact="@$failurePayload.$ShouldTryNext"/>
                <set_value name="$reasonType" exact="if $reasonTypeValue? then $reasonTypeValue else 'MARKET'"/>
                <set_value name="$shouldTryNext" exact="if $shouldTryNextValue? then $shouldTryNextValue else false"/>
                
                <set_value name="this.$failureReason" exact="$failurePayload.$Reason"/>
                <set_value name="this.$tradeFailed" exact="true"/>
                <set_value name="this.$tryNextTrade" exact="$shouldTryNext"/>
                
                <do_if value="this.$failureReason == 'route_illegal_pre_transit'">
                  <set_value name="this.$lastNoTradeReason" exact="'route_illegal_pre_transit'"/>
                  <do_if value="$gt_logbookentries and global.$GT_Ships? and global.$GT_Ships.{this.ship}.$RouteIllegalAbort?">
                    <set_value name="$ria" exact="global.$GT_Ships.{this.ship}.$RouteIllegalAbort"/>
                    <set_value name="$riaNextSectorName" exact="if $ria.$NextSector? then @$ria.$NextSector.knownname else 'Unknown'"/>
                    <set_value name="$riaWareName" exact="if $ria.$Ware? then @$ria.$Ware.name else 'Unknown'"/>
                    <set_value name="$riaPoliceName" exact="if $ria.$PoliceFaction? then @$ria.$PoliceFaction.knownname else 'Unknown'"/>
                    <set_value name="$logbookMessage" exact="'Commander,\n\nILLEGAL ROUTE BLOCKED\n\nBefore entering sector ' + $riaNextSectorName + ', sector policing now prohibits cargo ware ' + $riaWareName + ' for our owner (police faction: ' + $riaPoliceName + ').\n\nI have aborted the current trade run and will search for an alternative route.\n\nWith vigilance,\nAboard ' + this.ship.knownname"/>
                    <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                      $Message = $logbookMessage,
                      $Category = 'alerts',
                      $Title = 'Illegal Route Blocked: ' + this.ship.knownname,
                      $Object = this.ship,
                      $Interaction = 'showonmap',
                      $Highlighted = false
                    ]"/>
                  </do_if>
                </do_if>
                
                <do_if value="$shouldTryNext">
                  <debug_text text="'[GT-AI] Pathfinding failed for ' + this.ship.idcode + ': ' + this.$failureReason + ' - trying next cached alternative'" chance="100"/>
                </do_if>
                <do_else>
                  <debug_text text="'[GT-AI] Trade failed for ' + this.ship.idcode + ': ' + this.$failureReason + ' - will search for new trade'" chance="100"/>
                </do_else>
              </do_else>
            </do_elseif>
            <resume label="trade_completed"/>
          </actions>
        </interrupt>
      </wait>
      
      <!-- Timeout fallback -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade completion timeout after 300s - resuming anyway'" chance="100"/>
      </do_if>
      
      <label name="trade_completed"/>
      
      <!-- NOTE: Global money cap (global.$GT_MoneyCapActive) auto-clears in the early money gate
           when player.money rises above global.$GT_MoneyCapMoney. No per-ship clearing needed. -->
      
      <!-- Fallback flag is intentionally NOT changed on trade completion.
           It is set/cleared only when a new trade order is created and source is known. -->
      
      <!-- CRITICAL: Clear trades awaiting validation after trade execution completes -->
      <!-- This ensures ships always check cache first on next search, not stale pending trades -->
      <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidation.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_TradesAwaitingValidationTimestamp? and global.$GT_TradesAwaitingValidationTimestamp.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidationTimestamp.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}?">
        <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{this.ship}"/>
      </do_if>
      <!-- Clear active trade tracking -->
      <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{this.ship}?">
        <remove_value name="global.$GT_ActiveTrade.{this.ship}"/>
      </do_if>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
        <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
      </do_if>
      
      <!-- ======================================= -->
      <!-- PILOT CHANGE DETECTION (After Trade)   -->
      <!-- ======================================= -->
      <!-- Check for pilot changes after successful trade completion -->
      <!-- This is a natural restart point where the GT default order reruns -->
      <set_value name="$currentPilot" exact="this.ship.pilot"/>
      <do_if value="this.$trackedPilot? and $currentPilot != this.$trackedPilot">
        <!-- Pilot changed! Send signal to MD system -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': PILOT CHANGE DETECTED after trade completion! Old: ' + @this.$trackedPilot.name + ', New: ' + @$currentPilot.name" chance="100"/>
        </do_if>
        
        <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
          $updateType = 'pilot_change',
          $Ship = this.ship,
          $pilot = $currentPilot,
          $oldPilot = this.$trackedPilot
        ]"/>
      </do_if>
      <!-- Update tracked pilot (always, even if no change) -->
      <set_value name="this.$trackedPilot" exact="$currentPilot"/>
      
      <!-- CRITICAL: Check if pilot is missing (pilot was transferred away) -->
      <!-- If GT order is running but ship has no pilot, cleanup and self-cancel -->
      <do_if value="not $currentPilot">
        <set_value name="$pendingTransferredPilot" exact="false"/>
        <set_value name="$pendingPilotName" exact="'NONE'"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$pk">
            <set_value name="$candidatePilot" exact="$pilotKeys.{$pk}"/>
            <do_if value="$candidatePilot and global.$GT_Pilots.{$candidatePilot}? and global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == this.ship.idcode and global.$GT_Pilots.{$candidatePilot}.$Status? and global.$GT_Pilots.{$candidatePilot}.$Status == 'paused'">
              <set_value name="$pendingTransferredPilot" exact="true"/>
              <set_value name="$pendingPilotName" exact="if $candidatePilot.name? then $candidatePilot.name else 'UNKNOWN'"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$pendingTransferredPilot">
          <do_if value="not this.$pendingPilotTransferSince?">
            <set_value name="this.$pendingPilotTransferSince" exact="player.age"/>
          </do_if>
          <set_value name="$pendingTransferElapsed" exact="player.age - this.$pendingPilotTransferSince"/>
          
          <do_if value="$pendingTransferElapsed lt 15min">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Missing pilot after trade completion but transfer is in progress for ' + $pendingPilotName + ' (elapsed=' + ($pendingTransferElapsed / 1s) + 's) - waiting before cancellation'" chance="100"/>
            </do_if>
            <wait exact="5s"/>
            <return/>
          </do_if>
        </do_if>
        
        <remove_value name="this.$pendingPilotTransferSince"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': MISSING PILOT DETECTED after trade completion - pilot was transferred away, cleaning up and self-canceling GT order'" chance="100"/>
        </do_if>
        
        <!-- Get original ship name from ship registry -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{this.ship}.$OriginalShipName"/>
        </do_if>
        
        <!-- Send cleanup signal (name restoration handled by MD system) -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = null,
          $Reason = 'Pilot transferred away - GT order cannot run without pilot',
          $OriginalName = $originalName
        ]"/>
        
        <!-- Cancel all active orders (trade orders, etc.) -->
        <cancel_all_orders object="this.ship"/>
        
        <!-- Self-cancel GT order -->
        <cancel_order order="this.ship.defaultorder"/>
        <return/>
      </do_if>
      
      <!-- Check if this is a pathfinding retry (try next cached alternative) -->
      <do_if value="this.$tryNextTrade?">
        <remove_value name="this.$tryNextTrade"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Immediately requesting next trade (cache will skip failed trades)'" chance="100"/>
        </do_if>
        <!-- Skip market update wait - immediately try next cached trade -->
        <resume label="main_loop"/>
      </do_if>
      
      <!-- NOTE: Auto-repair check has been moved to MD system (gt_trading_ai.xml TradeCompleted cue) -->
      <!-- This ensures it runs even when the order is aborted/replaced during trade execution -->
      
      <!-- Update market data interval -->
      <wait max="$gt_marketupdatefreq">
        <interrupt>
          <conditions>
            <check_any>
              <event_object_signalled object="this.ship" param="'GT_Trade_Found'" comment="New trade found"/>
              <event_object_signalled object="this.ship" param="'GT_No_Trade_Found'" comment="Wake-up signal"/>
            </check_any>
          </conditions>
          <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Signal received during market update wait - resuming immediately'" chance="100"/>
            </do_if>
          </actions>
        </interrupt>
      </wait>
      <resume label="main_loop"/>
      
      <!-- ========================================= -->
      <!-- NO TRADE FOUND - ESCALATING RETRY LOGIC  -->
      <!-- ========================================= -->
      <label name="escape_from_blacklisted"/>
      
      <!-- Determine home sector -->
      <set_value name="$homeBase" exact="this.$effectiveHome"/>
      <set_value name="$homeSector" exact="null"/>
      <do_if value="$homeBase? and $homeBase.exists">
        <do_if value="$homeBase.isclass.station">
          <set_value name="$homeSector" exact="$homeBase.sector"/>
        </do_if>
        <do_elseif value="$homeBase.isclass.sector">
          <set_value name="$homeSector" exact="$homeBase"/>
        </do_elseif>
      </do_if>
      <do_if value="not $homeSector? or not $homeSector.exists">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: Home sector not available - cannot escape, continuing retry logic'" chance="100"/>
        </do_if>
        <resume label="no_trade_retry"/>
      </do_if>
      
      <set_value name="$currentSector" exact="this.ship.sector"/>
      <do_if value="$currentSector == $homeSector">
        <!-- Already in home sector; just retry normally -->
        <resume label="main_loop"/>
      </do_if>
      
      <!-- Use cached blacklist group from init -->
      <set_value name="$blacklistgroup" exact="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
      
      <!-- Resolve sector whitelist for escape candidate selection (whitelist overrides blacklist) -->
      <set_value name="$validationWhitelist" exact="[]"/>
      <do_if value="$effectiveSectorWhitelist? and $effectiveSectorWhitelist != null and $effectiveSectorWhitelist.count gt 0">
        <set_value name="$validationWhitelist" exact="$effectiveSectorWhitelist"/>
      </do_if>
      
      <!-- Build a jump path to home (ignoring blacklist so we can walk 'toward home') -->
      <get_jump_path component="$jumppath" multiple="true" uselocalhighways="true">
        <start object="this.ship"/>
        <end object="$homeSector"/>
      </get_jump_path>
      
      <!-- Choose the first non-blacklisted sector along the route (or the home sector) -->
      <set_value name="$escapeSector" exact="$homeSector"/>
      <do_all exact="$jumppath.count" counter="$pi">
        <set_value name="$entry" exact="$jumppath.{$pi}"/>
        <do_if value="$entry? and ($entry.isclass.gate or $entry.isclass.highwayentrygate)">
          <set_value name="$candidateSector" exact="$entry.destination.sector"/>
          <set_value name="$candWhitelisted" exact="false"/>
          <do_if value="$validationWhitelist.count gt 0">
            <do_all exact="$validationWhitelist.count" counter="$swIdx">
              <do_if value="$validationWhitelist.{$swIdx} == $candidateSector">
                <set_value name="$candWhitelisted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$candActivityBL" exact="false"/>
          <set_value name="$candTravelBL" exact="false"/>
          <do_if value="not $candWhitelisted">
            <set_value name="$candActivityBL" exact="@$candidateSector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled}"/>
            <set_value name="$candTravelBL" exact="@$candidateSector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}"/>
          </do_if>
          <set_value name="$candBL" exact="$candActivityBL or $candTravelBL"/>
          <do_if value="not $candBL or $candidateSector == $homeSector">
            <set_value name="$escapeSector" exact="$candidateSector"/>
            <break/>
          </do_if>
        </do_if>
      </do_all>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': ESCAPE FALLBACK: Moving toward home sector' +
          '\n  Current: ' + @$currentSector.knownname +
          '\n  Home:    ' + @$homeSector.knownname +
          '\n  Target:  ' + @$escapeSector.knownname" chance="100"/>
      </do_if>
      
      <!-- Logbook: escape fallback (rate-limited, respects per-ship logbook setting) -->
      <set_value name="$logEnabled" exact="false"/>
      <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK4Supply2' and @this.ship.defaultorder.$logbookentries">
        <set_value name="$logEnabled" exact="true"/>
      </do_if>
      <!-- Subordinates inherit logbook setting from commander -->
      <do_elseif value="@this.ship.defaultorder.id == 'Assist' and (((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2') and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
        <set_value name="$logEnabled" exact="true"/>
      </do_elseif>
      
      <do_if value="$logEnabled">
        <set_value name="$lastEscapeLogbookTime" exact="0"/>
        <do_if value="this.$lastEscapeFallbackLogbookEntryTime?">
          <set_value name="$lastEscapeLogbookTime" exact="this.$lastEscapeFallbackLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastEscapeLogbook" exact="player.age - $lastEscapeLogbookTime"/>
        <do_if value="$timeSinceLastEscapeLogbook ge 300s or $lastEscapeLogbookTime == 0">
          <set_value name="$logbookMessage" exact="'Commander,\n\nI am currently in a blacklisted sector and could not find any trade route that safely moves me out.\n\nEscape fallback activated: moving toward my home sector.\n\nCurrent: ' + @$currentSector.knownname + '\nHome: ' + @$homeSector.knownname + '\nTarget: ' + @$escapeSector.knownname + '\n\nStatus: Escaping blacklist lock\n\nAboard ' + this.ship.knownname"/>
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'general',
            $Title = 'Escape Fallback: ' + this.ship.knownname,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          <set_value name="this.$lastEscapeFallbackLogbookEntryTime" exact="player.age"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Escape fallback logbook entry created'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      
      <!-- Create a visible, native navigation order for the player ("Fly and Wait") toward the escape sector.
           Timeout is the post-arrival hold (NOT how long the AI waits â€” the AI resumes immediately because
           of immediate="true" + <resume>). The previous 1s value caused the order to settle within a single
           AI tick after arrival, so the next main_loop pass would re-blacklist and re-fire MoveWait in a
           tight loop. Scale by the planned jump count (one hop minimum) so the ship has a realistic
           settling window before GT re-evaluates. -->
      <set_value name="$escapeTimeout" exact="if $jumppath? and $jumppath.count gt 0 then $jumppath.count * 60s else 60s"/>
      <!-- CRITICAL: Set escape flag RIGHT BEFORE creating order to ensure it's set when ship starts fleeing -->
      <do_if value="global.$GT_Ships?">
        <do_if value="not global.$GT_Ships.{this.ship}?">
          <set_value name="global.$GT_Ships.{this.ship}" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Ships.{this.ship}.$Escaping" exact="true"/>
      </do_if>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship=this.ship,
          $pilot=this.ship.pilot,
          $xp=global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level=global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank=@global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType='trader'
        ]"/>
      </do_if>
      
      <create_order object="this.ship" id="'MoveWait'" immediate="true">
        <param name="destination" value="[$escapeSector, position.[0,0,0]]"/>
        <param name="timeout" value="$escapeTimeout"/>
        <param name="debugchance" value="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </create_order>
      
      <!-- After moving (or attempting to), retry trading immediately -->
      <resume label="main_loop"/>
      
      <label name="no_trade_retry"/>

      <!-- CRITICAL: Initialize retryCooldown with safe default FIRST to prevent property lookup errors -->
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <!-- IMPORTANT (AI script lifetime): local $vars may not persist across <wait/> yields. -->
      <!-- Persist the computed cooldown time on the order instance for any post-wait logic. -->
      <set_value name="this.$retryCooldown" exact="10s"/>

      <!-- SPECIAL CASE: system busy / home refresh in progress (MD queues are saturated OR a home-sector cache refresh is running)
           â†’ fixed retry, do NOT escalate cooldown.
           Smooth gameplay > throughput: wait longer here to reduce request churn and let the scheduler/queues drain.
           TODO: keep hardcoded for now; consider exposing as tuning later. -->
      <set_value name="$noTradeReason" exact="if this.$lastNoTradeReason? then this.$lastNoTradeReason else ''"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': no_trade_retry entered: reason=\'' + $noTradeReason + '\' player.money=' + (player.money / 100) + ' Cr'" chance="100"/>
      </do_if>
      <do_if value="$noTradeReason == 'busy' or $noTradeReason == 'busy_batch' or $noTradeReason == 'home_refresh' or $noTradeReason == 'insufficient_funds'">
        <set_value name="this.$lastNoTradeReason" exact="''"/>
        <!-- NOTE: Global money cap (global.$GT_MoneyCapActive) is set by the authoritative guard
             when blocking. No per-ship state needed here â€” the global flag stops all ships. -->
        <!-- Fixed retry for special reasons (do NOT use escalating cooldown). -->
        <!-- For home_refresh: shorter wait (3s) to allow cache retry while home refresh populates cache -->
        <!-- For busy/busy_batch: longer wait (8-12s) to let queues drain -->
        <!-- For insufficient_funds: long wait (90-150s) - budget exhausted, no point retrying quickly.
             Jitter prevents thundering herd: ships spread across 60s window instead of all waking simultaneously.
             On wake-up, the early money gate and global money cap prevent futile searches. -->
        <set_value name="this.$retryCooldown" exact="if $noTradeReason == 'home_refresh' then 3s else (if $noTradeReason == 'insufficient_funds' then 120s else 10s)"/>
        <!-- JITTER: Compute per-ship min/max wait for <wait> element.
             insufficient_funds: 90s-150s (Â±25%), busy: 8s-12s (Â±20%), home_refresh: 3s (no jitter, needs responsiveness) -->
        <set_value name="this.$retryWaitMin" exact="if $noTradeReason == 'insufficient_funds' then 90s else (if $noTradeReason == 'home_refresh' then 3s else 8s)"/>
        <set_value name="this.$retryWaitMax" exact="if $noTradeReason == 'insufficient_funds' then 150s else (if $noTradeReason == 'home_refresh' then 3s else 12s)"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': System busy/home refresh/insufficient funds - waiting ' + (this.$retryWaitMin/1s) + '-' + (this.$retryWaitMax/1s) + 's then retrying cache (reason: ' + $noTradeReason + ')'" chance="100"/>
        </do_if>
        
        <!-- Record attempt summary (bounded history) -->
        <do_if value="not global.$GT_NoTradeHistory?">
          <set_value name="global.$GT_NoTradeHistory" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_NoTradeHistory.{this.ship}? or global.$GT_NoTradeHistory.{this.ship} == null or typeof global.$GT_NoTradeHistory.{this.ship} != datatype.list">
          <set_value name="global.$GT_NoTradeHistory.{this.ship}" exact="[]"/>
        </do_if>
        <append_to_list name="global.$GT_NoTradeHistory.{this.ship}" exact="table[
          $Time = player.age,
          $Reason = $noTradeReason,
          $Wait = this.$retryCooldown,
          $Sector = @this.ship.sector.knownname,
          $Home = if @this.$effectiveHome != null then @this.$effectiveHome.knownname else (if @this.ship.defaultorder.$home != null then @this.ship.defaultorder.$home.knownname else ''),
          $MaxDistance = if this.$effectiveMaxDistance? then this.$effectiveMaxDistance else null
        ]"/>
        <!-- Keep last 12 entries max -->
        <do_if value="global.$GT_NoTradeHistory.{this.ship}.count gt 12">
          <set_value name="$old" exact="global.$GT_NoTradeHistory.{this.ship}.{1}"/>
          <remove_from_list name="global.$GT_NoTradeHistory.{this.ship}" exact="$old"/>
        </do_if>
        
        <!-- Logbook entry for insufficient funds (throttled: once per 5 minutes per ship) -->
        <do_if value="$noTradeReason == 'insufficient_funds' and $gt_logbookentries">
          <set_value name="$lastInsufficientFundsLogbook" exact="0"/>
          <do_if value="this.$lastInsufficientFundsLogbookTime?">
            <set_value name="$lastInsufficientFundsLogbook" exact="this.$lastInsufficientFundsLogbookTime"/>
          </do_if>
          <set_value name="$timeSinceLastInsufficientFundsLogbook" exact="player.age - $lastInsufficientFundsLogbook"/>
          <do_if value="$timeSinceLastInsufficientFundsLogbook ge 300s or $lastInsufficientFundsLogbook == 0">
            <set_value name="$playerMoneyDisplay" exact="player.money / 100"/>
            <set_value name="$thresholdDisplay" exact="if this.$minPlayerMoney? then this.$minPlayerMoney else 1000"/>
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrading operations paused â€” insufficient funds.\n\nPlayer account: ' + $playerMoneyDisplay + ' Cr\nMinimum required: ' + $thresholdDisplay + ' Cr\n\nI will resume trading automatically once funds are above the threshold.\n\nYou can adjust the minimum in:\nGalaxyTrader Settings &gt; Fleet &gt; Min Player Money\n\nStanding by,\nAboard ' + this.ship.knownname"/>
            <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
              $Message = $logbookMessage,
              $Category = 'alerts',
              $Title = 'Insufficient Funds: ' + this.ship.knownname,
              $Object = this.ship,
              $Interaction = 'showonmap',
              $CheckGlobalSettings = false
            ]"/>
            <set_value name="this.$lastInsufficientFundsLogbookTime" exact="player.age"/>
          </do_if>
        </do_if>

        <set_command command="command.wait"/>
        <set_command_action commandaction="commandaction.standingby"/>
        <!-- JITTER: Use per-ship min/max to spread retries across a time window (prevents thundering herd).
             For insufficient_funds: 90s-150s window. For busy: 8s-12s. For home_refresh: fixed 3s. -->
        <wait min="if @this.$retryWaitMin != null then @this.$retryWaitMin else 10s" max="if @this.$retryWaitMax != null then @this.$retryWaitMax else 10s"/>
        <resume label="main_loop"/>
      </do_if>
      
      <!-- CARGO DISPOSAL: Track cargo disposal failures separately -->
      <set_value name="$isCargoDisposal" exact="false"/>
      <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
        <set_value name="$isCargoDisposal" exact="true"/>
        <!-- Initialize cargo disposal failure counter if not exists -->
        <do_if value="not this.$cargoDisposalFailed?">
          <set_value name="this.$cargoDisposalFailed" exact="0"/>
        </do_if>
        <!-- Increment cargo disposal failure counter -->
        <set_value name="this.$cargoDisposalFailed" exact="this.$cargoDisposalFailed + 1"/>
      </do_if>
      <do_else>
        <!-- Normal trade search failure - increment normal counter -->
        <!-- Increment failure counter -->
        <set_value name="this.$searchFailed" exact="this.$searchFailed + 1"/>
      </do_else>
      
      <!-- Calculate escalating wait time: ~10s, ~20s, ~30s, ~40s, ~50s, ~60s (max) -->
      <!-- Use cargo disposal counter if this is cargo disposal, otherwise use normal counter -->
      <set_value name="$failureCount" exact="if $isCargoDisposal then this.$cargoDisposalFailed else this.$searchFailed"/>
      <!-- Escalating cooldown (cap 60s). This is also required for "no trade found" logbook notifications (they trigger at 60s). -->
      <!-- Purpose B: No-trade retry cooldown (seconds) -->
      <set_value name="this.$retryCooldown" exact="([$failureCount, 6].min) * 10s"/>
      <!-- JITTER: Â±20% around the base cooldown to prevent ships at the same escalation level
           from all retrying in the same frame (thundering herd prevention).
           Example: failureCount=3 â†’ base=30s â†’ min=24s, max=36s -->
      <set_value name="this.$retryCooldownMin" exact="[this.$retryCooldown * 0.8, 5s].max"/>
      <set_value name="this.$retryCooldownMax" exact="this.$retryCooldown * 1.2"/>
      
      <!-- Record attempt summary (bounded history).
           We capture the most recent MD rejection statistics (if available) so the 60s logbook report can show a timeline. -->
      <do_if value="not global.$GT_NoTradeHistory?">
        <set_value name="global.$GT_NoTradeHistory" exact="table[]"/>
      </do_if>
      <do_if value="not global.$GT_NoTradeHistory.{this.ship}? or global.$GT_NoTradeHistory.{this.ship} == null or typeof global.$GT_NoTradeHistory.{this.ship} != datatype.list">
        <set_value name="global.$GT_NoTradeHistory.{this.ship}" exact="[]"/>
      </do_if>
      <set_value name="$lastRejectionStats" exact="null"/>
      <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.$LastRejectionStats? and global.$GT_SearchResult.$LastRejectionStats.{this.ship}?">
        <set_value name="$lastRejectionStats" exact="@global.$GT_SearchResult.$LastRejectionStats.{this.ship}"/>
      </do_if>
      <set_value name="$rsTotal" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Total != null then @$lastRejectionStats.$Total else null"/>
      <set_value name="$rsDock" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Docking != null then @$lastRejectionStats.$Docking else null"/>
      <set_value name="$rsProfit" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Profit != null then @$lastRejectionStats.$Profit else null"/>
      <set_value name="$rsAmount" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Amount != null then @$lastRejectionStats.$Amount else null"/>
      <set_value name="$rsBlacklist" exact="if $lastRejectionStats != null and @$lastRejectionStats.$Blacklist != null then @$lastRejectionStats.$Blacklist else null"/>
      <set_value name="$rsSector" exact="if $lastRejectionStats != null and @$lastRejectionStats.$SectorName != null then @$lastRejectionStats.$SectorName else @this.ship.sector.knownname"/>
      <set_value name="$rsMaxDist" exact="if $lastRejectionStats != null and @$lastRejectionStats.$MaxDistance != null then @$lastRejectionStats.$MaxDistance else null"/>
      <set_value name="$rsMinProfit" exact="if $lastRejectionStats != null and @$lastRejectionStats.$MinAbsoluteProfit != null then @$lastRejectionStats.$MinAbsoluteProfit else null"/>
      <set_value name="$rsDistance" exact="0"/>
      <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{this.ship}? and global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance?">
        <set_value name="$rsDistance" exact="global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance"/>
      </do_if>
      <append_to_list name="global.$GT_NoTradeHistory.{this.ship}" exact="table[
        $Time = player.age,
        $Reason = $noTradeReason,
        $Wait = this.$retryCooldown,
        $Sector = $rsSector,
        $Home = if @this.$effectiveHome != null then @this.$effectiveHome.knownname else (if @this.ship.defaultorder.$home != null then @this.ship.defaultorder.$home.knownname else ''),
        $MaxDistance = $rsMaxDist,
        $MinAbsoluteProfit = $rsMinProfit,
        $Total = $rsTotal,
        $Docking = $rsDock,
        $Profit = $rsProfit,
        $Amount = $rsAmount,
        $Blacklist = $rsBlacklist,
        $Distance = $rsDistance
      ]"/>
      <!-- Keep last 12 entries max -->
      <do_if value="global.$GT_NoTradeHistory.{this.ship}.count gt 12">
        <set_value name="$old" exact="global.$GT_NoTradeHistory.{this.ship}.{1}"/>
        <remove_from_list name="global.$GT_NoTradeHistory.{this.ship}" exact="$old"/>
      </do_if>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No ' + (if $isCargoDisposal then 'cargo buyer' else 'profitable trades') + ' found (attempt ' + $failureCount + ') - waiting ' + (this.$retryCooldown/1s) + 's before retry'" chance="100"/>
      </do_if>
      
      <!-- Set ship to waiting state -->
      <set_command command="command.wait"/>
      <set_command_action commandaction="commandaction.standingby"/>
      
      <!-- Persist $isCargoDisposal and $noTradeReason before wait (local variables lost across wait yields) -->
      <set_value name="this.$isCargoDisposal" exact="$isCargoDisposal"/>
      <set_value name="this.$noTradeReason" exact="$noTradeReason"/>
      
      <!-- Wait with escalating delay -->
      <!-- Track if wait was interrupted (so we don't write logbook if interrupted) -->
      <set_value name="$waitInterrupted" exact="false"/>
      <set_value name="$tradeFoundDuringWait" exact="false"/>
      <set_value name="this.$waitInterrupted" exact="$waitInterrupted"/>
      <set_value name="this.$tradeFoundDuringWait" exact="$tradeFoundDuringWait"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Entering wait for ' + (this.$retryCooldownMin/1s) + '-' + (this.$retryCooldownMax/1s) + 's at game time ' + player.age" chance="100"/>
      </do_if>
      <!-- JITTER: Use min/max range (Â±20%) to spread ships across a time window instead of all waking together -->
      <wait min="if @this.$retryCooldownMin != null then @this.$retryCooldownMin else 8s" max="if @this.$retryCooldownMax != null then @this.$retryCooldownMax else 12s" comment="Jittered escalating wait with interrupt">
        <interrupt>
          <conditions>
            <!-- Only GT_Trade_Found should interrupt retry wait -->
            <!-- GT_No_Trade_Found signals during retry wait are ignored to preserve escalating cooldown -->
            <event_object_signalled object="this.ship" param="'GT_Trade_Found'" comment="MD found a trade"/>
          </conditions>
          <actions>
            <!-- Capture signal payload before resuming so trade_found gets the correct source/list -->
            <set_value name="$intSignalData" exact="event.param2"/>
            <set_value name="$intSignalTradeList" exact="[]"/>
            <set_value name="$intSignalSearchMethod" exact="''"/>
            <do_if value="$intSignalData? and $intSignalData != null">
              <set_value name="$intSignalTradeList" exact="@$intSignalData.$TradeList"/>
              <set_value name="$intSignalSearchMethod" exact="@$intSignalData.$SearchMethod"/>
            </do_if>
            <set_value name="this.$tradeListFromSignal" exact="$intSignalTradeList"/>
            <set_value name="this.$searchMethodFromSignal" exact="if $intSignalSearchMethod != null and $intSignalSearchMethod != '' then $intSignalSearchMethod else ''"/>
            <set_value name="this.$waitInterrupted" exact="true"/>
            <set_value name="this.$tradeFoundDuringWait" exact="true"/>
            <set_value name="$waitInterrupted" exact="true"/>
            <set_value name="$tradeFoundDuringWait" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Trade found during retry wait - stored ' + (if $intSignalTradeList != null then $intSignalTradeList.count else 0) + ' trades from interrupt payload'" chance="100"/>
            </do_if>
            <!-- Resume to trade_found label to process the trade -->
            <resume label="trade_found"/>
          </actions>
        </interrupt>
      </wait>
      <!-- Restore variables after wait (they may have been lost across yield) -->
      <set_value name="$waitInterrupted" exact="this.$waitInterrupted"/>
      <set_value name="$tradeFoundDuringWait" exact="this.$tradeFoundDuringWait"/>
      <set_value name="$isCargoDisposal" exact="this.$isCargoDisposal"/>
      <set_value name="$noTradeReason" exact="if this.$noTradeReason? then this.$noTradeReason else ''"/>
      <!-- Recompute $failureCount from persisted instance variables (local was lost across wait) -->
      <set_value name="$failureCount" exact="if $isCargoDisposal then (if this.$cargoDisposalFailed? then this.$cargoDisposalFailed else 0) else (if this.$searchFailed? then this.$searchFailed else 0)"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Wait completed at game time ' + player.age + ' - continuing retry logic (trade found: ' + this.$tradeFoundDuringWait + ')'" chance="100"/>
      </do_if>
      
      <!-- Write logbook entry only if we've reached max wait (60s) AND wait completed naturally (not interrupted by trade found) -->
      <!-- Also check if we've already written a logbook entry recently to prevent duplicates -->
      <set_value name="$shouldWriteLogbook" exact="false"/>
      <set_value name="$shouldWriteCargoDisposalLogbook" exact="false"/>
      
      <!-- CARGO DISPOSAL: Separate logbook entry for cargo disposal failures -->
      <do_if value="this.$isCargoDisposal and this.$retryCooldown == 60s and not this.$tradeFoundDuringWait">
        <!-- Check if we've already written a cargo disposal failure logbook entry in the last 5 minutes (300s) -->
        <set_value name="$lastCargoDisposalLogbookTime" exact="0"/>
        <do_if value="this.$lastCargoDisposalLogbookEntryTime?">
          <set_value name="$lastCargoDisposalLogbookTime" exact="this.$lastCargoDisposalLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastCargoDisposalLogbook" exact="player.age - $lastCargoDisposalLogbookTime"/>
        <do_if value="$timeSinceLastCargoDisposalLogbook ge 300s or $lastCargoDisposalLogbookTime == 0">
          <!-- Haven't written cargo disposal failure logbook recently (or never) - OK to write -->
          <set_value name="$shouldWriteCargoDisposalLogbook" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- Determine if this is a "critical persistent" reason that should trigger logbook earlier -->
      <!-- Critical reasons: ship is fundamentally unable to trade, not just temporarily busy -->
      <set_value name="$isCriticalReason" exact="$noTradeReason == 'blacklist' or $noTradeReason == 'all_rejected' or $noTradeReason == 'trade_rules_violation'"/>
      
      <!-- Normal trade search logbook entry -->
      <!-- Trigger conditions:
           - Standard: 60s cooldown reached (6th failure)
           - Critical: 2nd consecutive failure with a persistent reason (blacklist/all_rejected/trade_rules) 
           Either way, wait must have completed naturally (not interrupted by trade found) -->
      <do_if value="not $isCargoDisposal and not $tradeFoundDuringWait and (this.$retryCooldown == 60s or ($isCriticalReason and $failureCount ge 2))">
        <!-- Check if we've already written a logbook entry in the last 5 minutes (300s) -->
        <set_value name="$lastLogbookTime" exact="0"/>
        <do_if value="this.$lastLogbookEntryTime?">
          <set_value name="$lastLogbookTime" exact="this.$lastLogbookEntryTime"/>
        </do_if>
        <set_value name="$timeSinceLastLogbook" exact="player.age - $lastLogbookTime"/>
        <do_if value="$timeSinceLastLogbook ge 300s or $lastLogbookTime == 0">
          <!-- Haven't written logbook recently (or never) - OK to write -->
          <set_value name="$shouldWriteLogbook" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- CARGO DISPOSAL: Write separate failure message for cargo disposal -->
      <do_if value="$shouldWriteCargoDisposalLogbook">
        <!-- Check if logbook enabled -->
        <set_value name="$logEnabled" exact="false"/>
        <do_if value="@this.ship.defaultorder.id == 'GalaxyTraderMK4Supply2' and @this.ship.defaultorder.$logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        <!-- Subordinates inherit logbook setting from commander -->
        <do_elseif value="@this.ship.defaultorder.id == 'Assist' and (((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') and @this.ship.commander.defaultorder.$logbookentries) or (@this.ship.commander.defaultorder.id == 'Assist' and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2') and @this.ship.commander.defaultorder.$baseorder.$logbookentries))">
          <set_value name="$logEnabled" exact="true"/>
        </do_elseif>
        
        <do_if value="$logEnabled">
          <!-- Get cargo info for logbook message -->
          <set_value name="$cargoList" exact="this.ship.cargo.list"/>
          <set_value name="$cargoTypes" exact="[]"/>
          <do_all exact="$cargoList.count" counter="$i">
            <set_value name="$ware" exact="$cargoList.{$i}"/>
            <set_value name="$amount" exact="this.ship.cargo.{$ware}.count"/>
            <append_to_list name="$cargoTypes" exact="@$ware.name + ' x' + $amount"/>
          </do_all>
          <set_value name="$cargoDescription" exact="if $cargoTypes.count gt 0 then $cargoTypes.{1} + (if $cargoTypes.count gt 1 then ', ' + $cargoTypes.{2} else '') + (if $cargoTypes.count gt 2 then ', ...' else '') else 'Unknown'"/>
          
          <!-- Write cargo disposal failure logbook entry -->
          <set_value name="$logbookMessage" exact="'Commander,\n\nI have been unable to find a buyer for my cargo after multiple attempts. My cargo hold contains: ' + $cargoDescription + '\n\nI have tried ' + $failureCount + ' times but cannot locate a suitable buyer within my trading range. This may be due to:\n- No stations buying these wares nearby\n- All potential buyers are blacklisted\n- Docking restrictions at available stations\n\nI will continue waiting and retrying periodically. You may want to manually assign a sell order or adjust my trading parameters.\n\nStatus: Waiting for buyer opportunity\n\nWith patience,\nAboard ' + this.ship.knownname"/>
          
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'alerts',
            $Title = 'Cargo Disposal Failed: ' + this.ship.knownname,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          
          <!-- Update last cargo disposal logbook entry time -->
          <set_value name="this.$lastCargoDisposalLogbookEntryTime" exact="player.age"/>
        </do_if>
      </do_if>
      
      <do_if value="$shouldWriteLogbook">
        <!-- Check if logbook enabled -->
        <set_value name="$logEnabled" exact="false"/>
        <!-- Use the already-computed effective logbook flag (matches other GT logbook messages). -->
        <do_if value="$gt_logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        
        <do_if value="$logEnabled">
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               COMMON DATA RETRIEVAL: Gather rejection stats, sector info, etc.
               Used by ALL logbook message templates below.
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          <set_value name="$lastRejectionStats" exact="null"/>
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.$LastRejectionStats? and global.$GT_SearchResult.$LastRejectionStats != null and global.$GT_SearchResult.$LastRejectionStats.{this.ship}?">
            <set_value name="$lastRejectionStats" exact="global.$GT_SearchResult.$LastRejectionStats.{this.ship}"/>
          </do_if>
          <set_value name="$totalRejected" exact="0"/>
          <set_value name="$tradesRejectedDocking" exact="0"/>
          <set_value name="$tradesRejectedProfit" exact="0"/>
          <set_value name="$tradesRejectedAmount" exact="0"/>
          <set_value name="$tradesRejectedBlacklist" exact="0"/>
          <set_value name="$sectorName" exact="''"/>
          <set_value name="$maxDistance" exact="10"/>
          <set_value name="$minAbsoluteProfit" exact="100"/>
          
          <do_if value="$lastRejectionStats != null">
            <set_value name="$tradesRejectedDockingTemp" exact="@$lastRejectionStats.$Docking"/>
            <set_value name="$tradesRejectedDocking" exact="if $tradesRejectedDockingTemp? and $tradesRejectedDockingTemp != null then $tradesRejectedDockingTemp else 0"/>
            <set_value name="$tradesRejectedProfitTemp" exact="@$lastRejectionStats.$Profit"/>
            <set_value name="$tradesRejectedProfit" exact="if $tradesRejectedProfitTemp? and $tradesRejectedProfitTemp != null then $tradesRejectedProfitTemp else 0"/>
            <set_value name="$tradesRejectedAmountTemp" exact="@$lastRejectionStats.$Amount"/>
            <set_value name="$tradesRejectedAmount" exact="if $tradesRejectedAmountTemp? and $tradesRejectedAmountTemp != null then $tradesRejectedAmountTemp else 0"/>
            <set_value name="$tradesRejectedBlacklistTemp" exact="@$lastRejectionStats.$Blacklist"/>
            <set_value name="$tradesRejectedBlacklist" exact="if $tradesRejectedBlacklistTemp? and $tradesRejectedBlacklistTemp != null then $tradesRejectedBlacklistTemp else 0"/>
            <set_value name="$totalRejectedTemp" exact="@$lastRejectionStats.$Total"/>
            <set_value name="$totalRejectedFromStats" exact="if $totalRejectedTemp? and $totalRejectedTemp != null then $totalRejectedTemp else 0"/>
            <set_value name="$sumOfRejections" exact="$tradesRejectedDocking + $tradesRejectedProfit + $tradesRejectedAmount + $tradesRejectedBlacklist"/>
            <set_value name="$totalRejected" exact="if $totalRejectedFromStats gt $sumOfRejections then $totalRejectedFromStats else $sumOfRejections"/>
            
            <set_value name="$sectorNameTemp" exact="@$lastRejectionStats.$SectorName"/>
            <do_if value="$sectorNameTemp? and $sectorNameTemp != null and $sectorNameTemp != ''">
              <set_value name="$sectorName" exact="$sectorNameTemp"/>
            </do_if>
            <do_else>
              <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
            </do_else>
            <set_value name="$maxDistanceTemp" exact="@$lastRejectionStats.$MaxDistance"/>
            <do_if value="$maxDistanceTemp? and $maxDistanceTemp != null">
              <set_value name="$maxDistance" exact="$maxDistanceTemp"/>
            </do_if>
            <set_value name="$minAbsoluteProfitTemp" exact="@$lastRejectionStats.$MinAbsoluteProfit"/>
            <do_if value="$minAbsoluteProfitTemp? and $minAbsoluteProfitTemp != null">
              <set_value name="$minAbsoluteProfit" exact="$minAbsoluteProfitTemp"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
          </do_else>
          
          <!-- Final safety check: Ensure sector name is not null -->
          <do_if value="not $sectorName? or $sectorName == null or $sectorName == ''">
            <set_value name="$sectorName" exact="@this.ship.sector.knownname"/>
            <do_if value="not $sectorName? or $sectorName == null or $sectorName == ''">
              <set_value name="$sectorName" exact="'Unknown Sector'"/>
            </do_if>
          </do_if>
          
          <set_value name="$hasRejectionStats" exact="false"/>
          <do_if value="$lastRejectionStats != null">
            <do_if value="($lastRejectionStats.$Total? and $lastRejectionStats.$Total != null) or ($lastRejectionStats.$Profit? and $lastRejectionStats.$Profit != null) or ($lastRejectionStats.$Docking? and $lastRejectionStats.$Docking != null) or ($lastRejectionStats.$Amount? and $lastRejectionStats.$Amount != null) or ($lastRejectionStats.$Blacklist? and $lastRejectionStats.$Blacklist != null)">
              <set_value name="$hasRejectionStats" exact="true"/>
            </do_if>
          </do_if>
          <set_value name="$totalEvaluated" exact="0"/>
          <do_if value="$hasRejectionStats and $lastRejectionStats.$Total? and $lastRejectionStats.$Total != null">
            <set_value name="$totalEvaluated" exact="$lastRejectionStats.$Total"/>
          </do_if>
          <set_value name="$tradesRejectedDistance" exact="0"/>
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{this.ship}? and global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance?">
            <set_value name="$tradesRejectedDistance" exact="global.$GT_SearchResult.{this.ship}.$TradesRejectedDistance"/>
          </do_if>
          
          <!-- Log the logbook message data before generating -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': LOGBOOK (reason=' + $noTradeReason + ', attempt=' + $failureCount + ', critical=' + $isCriticalReason + ')'" chance="100"/>
          </do_if>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               LOGBOOK TITLE â€” reason-specific for clarity in the logbook list
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          <set_value name="$logbookTitle" exact="'No Trades: ' + this.ship.knownname"/>
          <do_if value="$noTradeReason == 'blacklist'">
            <set_value name="$logbookTitle" exact="'Routes Blocked: ' + this.ship.knownname"/>
          </do_if>
          <do_elseif value="$noTradeReason == 'all_rejected'">
            <set_value name="$logbookTitle" exact="'All Trades Rejected: ' + this.ship.knownname"/>
          </do_elseif>
          <do_elseif value="$noTradeReason == 'trade_rules_violation'">
            <set_value name="$logbookTitle" exact="'Trade Rules Violation: ' + this.ship.knownname"/>
          </do_elseif>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               LOGBOOK MESSAGE â€” reason-specific templates
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          
          <!-- â”€â”€â”€ BLACKLIST: All viable routes pass through blocked sectors â”€â”€â”€ -->
          <do_if value="$noTradeReason == 'blacklist'">
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrading blocked â€” all viable routes pass through blacklisted sectors.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'All trade routes within range are blocked by threat intelligence or blacklist settings. ' +
              'The ship cannot reach any profitable stations safely.\n\n' +
              'Suggestions:\n' +
              '- Review blacklist settings (GalaxyTrader Settings &gt; Trade)\n' +
              '- Increase trading range to find routes around blocked sectors\n' +
              '- Relocate this ship to a sector with better connectivity\n' +
              '- Check if threat levels have changed recently'"/>
          </do_if>
          
          <!-- â”€â”€â”€ ALL_REJECTED: Every trade candidate was filtered out â”€â”€â”€ -->
          <do_elseif value="$noTradeReason == 'all_rejected'">
            <!-- Display strings -->
            <set_value name="$evalDisplay" exact="if $hasRejectionStats then $totalEvaluated else 'â€”'"/>
            <set_value name="$profitDisplay" exact="if $hasRejectionStats then $tradesRejectedProfit else 'â€”'"/>
            <set_value name="$dockDisplay" exact="if $hasRejectionStats then $tradesRejectedDocking else 'â€”'"/>
            <set_value name="$amountDisplay" exact="if $hasRejectionStats then $tradesRejectedAmount else 'â€”'"/>
            <set_value name="$distDisplay" exact="if $hasRejectionStats then $tradesRejectedDistance else 'â€”'"/>
            <set_value name="$blDisplay" exact="if $hasRejectionStats then $tradesRejectedBlacklist else 'â€”'"/>
            
            <set_value name="$logbookMessage" exact="'Commander,\n\nAll trade candidates were rejected after evaluation.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Min profit: ' + ($minAbsoluteProfit/100) + ' Cr\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'Rejection breakdown (evaluated ' + $evalDisplay + '):\n' +
              '  Profit too low: ' + $profitDisplay + '\n' +
              '  Docking restricted: ' + $dockDisplay + '\n' +
              '  Amount too small: ' + $amountDisplay + '\n' +
              '  Out of range: ' + $distDisplay + '\n' +
              '  Blacklisted/path blocked: ' + $blDisplay + '\n'"/>
            
            <!-- Add targeted hint based on dominant rejection reason -->
            <set_value name="$hint" exact="''"/>
            <do_if value="not $hasRejectionStats or $totalEvaluated == 0">
              <set_value name="$hint" exact="'No offers were evaluated. Check if markets are discovered and unblocked.'"/>
            </do_if>
            <do_elseif value="$tradesRejectedProfit gt ($tradesRejectedDocking + $tradesRejectedBlacklist + $tradesRejectedDistance)">
              <set_value name="$hint" exact="'Most candidates failed profit checks. Lower min profit/ROI or increase range.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDocking gt 0 and $tradesRejectedDocking ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates failed docking checks. Check docking restrictions at stations.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedBlacklist gt 0 and $tradesRejectedBlacklist ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Blacklist restrictions filtered many routes. Review threat settings.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDistance gt 0 and $tradesRejectedDistance ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates were out of range. Increase max distance if appropriate.'"/>
            </do_elseif>
            <do_if value="$hint != ''">
              <set_value name="$logbookMessage" exact="$logbookMessage + '\nHint: ' + $hint"/>
            </do_if>
          </do_elseif>
          
          <!-- â”€â”€â”€ TRADE_RULES_VIOLATION: Station trade rules prevent trading â”€â”€â”€ -->
          <do_elseif value="$noTradeReason == 'trade_rules_violation'">
            <set_value name="$logbookMessage" exact="'Commander,\n\nTrade rules violation â€” target stations reject trades from this ship.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Attempts: ' + $failureCount + '\n\n' +
              'This may be caused by:\n' +
              '- Build storage restrictions (station is a build storage)\n' +
              '- Carrier/auxiliary station trading restrictions\n' +
              '- Trade rule changes after search started\n' +
              '- Station ownership or faction restrictions\n\n' +
              'Suggestions:\n' +
              '- Check station trade rule settings\n' +
              '- Review IgnoreCarrierAux / IgnoreBuildStorage in GT Settings\n' +
              '- Increase trading range to find alternative stations'"/>
          </do_elseif>
          
          <!-- â”€â”€â”€ GENERIC: Standard "no profitable trades" with full diagnostics â”€â”€â”€ -->
          <do_else>
            <!-- Display strings (show 'â€”' when stats were not recorded) -->
            <set_value name="$evalDisplay" exact="if $hasRejectionStats then $totalEvaluated else 'â€”'"/>
            <set_value name="$profitDisplay" exact="if $hasRejectionStats then $tradesRejectedProfit else 'â€”'"/>
            <set_value name="$dockDisplay" exact="if $hasRejectionStats then $tradesRejectedDocking else 'â€”'"/>
            <set_value name="$amountDisplay" exact="if $hasRejectionStats then $tradesRejectedAmount else 'â€”'"/>
            <set_value name="$distDisplay" exact="if $hasRejectionStats then $tradesRejectedDistance else 'â€”'"/>
            <set_value name="$blDisplay" exact="if $hasRejectionStats then $tradesRejectedBlacklist else 'â€”'"/>
            
            <!-- Friendly reason string for the generic header -->
            <set_value name="$reasonFriendly" exact="
              if $noTradeReason == 'reserved' then 'all trades reserved by fleet'
              else if $noTradeReason == 'offers_expired' then 'trade offers expired during validation'
              else if $noTradeReason == 'no_trade' then 'no profitable trades found'
              else if $noTradeReason == 'invalid_trade' then 'trade data became invalid'
              else 'no profitable trades found'"/>
            
            <set_value name="$logbookMessage" exact="'Commander,\n\nNo trades available â€” ' + $reasonFriendly + '.\n\n' +
              'Ship: ' + this.ship.knownname + '\n' +
              'Sector: ' + $sectorName + '\n' +
              'Range: ' + $maxDistance + ' jump(s)\n' +
              'Min profit: ' + ($minAbsoluteProfit/100) + ' Cr\n' +
              'Attempts: ' + $failureCount + ' (cooldown reached ' + (this.$retryCooldown/1s) + 's)\n\n' +
              'Latest rejection stats (evaluated ' + $evalDisplay + '):\n' +
              '  Profit too low: ' + $profitDisplay + '\n' +
              '  Docking restricted: ' + $dockDisplay + '\n' +
              '  Amount too small: ' + $amountDisplay + '\n' +
              '  Out of range: ' + $distDisplay + '\n' +
              '  Blacklisted/path blocked: ' + $blDisplay +
              (if not $hasRejectionStats then '\n  (no stats recorded for this attempt)' else '') + '\n\n' +
              'Recent attempts (newest first):'"/>

            <!-- Append up to last 4 history rows (most recent first) -->
            <set_value name="$hist" exact="null"/>
            <do_if value="global.$GT_NoTradeHistory? and global.$GT_NoTradeHistory.{this.ship}?">
              <set_value name="$hist" exact="global.$GT_NoTradeHistory.{this.ship}"/>
            </do_if>
            <set_value name="$histCount" exact="if $hist != null then $hist.count else 0"/>
            <set_value name="$linesToShow" exact="[$histCount, 4].min"/>
            <do_all exact="$linesToShow" counter="$li">
              <!-- Reverse index: last entry is most recent -->
              <set_value name="$idx" exact="$histCount - ($li - 1)"/>
              <set_value name="$h" exact="$hist.{$idx}"/>
              
              <!-- Age formatting: mm:ss ago -->
              <set_value name="$ageSec" exact="0"/>
              <do_if value="$h.$Time? and $h.$Time != null">
                <set_value name="$ageSec" exact="((player.age - $h.$Time) / 1s)i"/>
              </do_if>
              <do_if value="$ageSec lt 0">
                <set_value name="$ageSec" exact="0"/>
              </do_if>
              <set_value name="$ageMin" exact="($ageSec / 60)i"/>
              <set_value name="$ageRem" exact="$ageSec - ($ageMin * 60)"/>
              <set_value name="$ageRemStr" exact="if $ageRem lt 10 then '0' + $ageRem else $ageRem"/>
              <set_value name="$ageStr" exact="$ageMin + ':' + $ageRemStr + ' ago'"/>
              
              <!-- Reason (friendly) -->
              <set_value name="$rRaw" exact="if $h.$Reason? and $h.$Reason != null and $h.$Reason != '' then $h.$Reason else 'none'"/>
              <set_value name="$r" exact="
                if $rRaw == 'busy' then 'busy'
                else if $rRaw == 'busy_batch' then 'busy (batch)'
                else if $rRaw == 'home_refresh' then 'home refresh'
                else if $rRaw == 'reserved' then 'reserved (fleet)'
                else if $rRaw == 'blacklist' then 'BLACKLISTED'
                else if $rRaw == 'all_rejected' then 'all rejected'
                else if $rRaw == 'trade_rules_violation' then 'trade rules'
                else if $rRaw == 'offers_expired' then 'offers expired'
                else if $rRaw == 'insufficient_funds' then 'low funds'
                else if $rRaw == 'invalid_trade' then 'invalid trade'
                else if $rRaw == 'no_trade' then 'no trade'
                else if $rRaw == 'no_cargo' then 'no cargo'
                else if $rRaw == 'no_gt_order' then 'no GT order'
                else if $rRaw == 'forced_sell_failed' then 'sell failed'
                else if $rRaw == 'no_training_stations' then 'no training'
                else $rRaw"/>
              
              <!-- Build compact rejection summary -->
              <set_value name="$p" exact="if $h.$Profit? and $h.$Profit != null then $h.$Profit else 0"/>
              <set_value name="$d" exact="if $h.$Docking? and $h.$Docking != null then $h.$Docking else 0"/>
              <set_value name="$a" exact="if $h.$Amount? and $h.$Amount != null then $h.$Amount else 0"/>
              <set_value name="$bl" exact="if $h.$Blacklist? and $h.$Blacklist != null then $h.$Blacklist else 0"/>
              <set_value name="$dist" exact="if $h.$Distance? and $h.$Distance != null then $h.$Distance else 0"/>
              <set_value name="$w" exact="if $h.$Wait? and $h.$Wait != null then (($h.$Wait / 1s)i) else 0"/>
              
              <set_value name="$rej" exact="''"/>
              <do_if value="$p gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'profit ' + $p"/></do_if>
              <do_if value="$d gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'dock ' + $d"/></do_if>
              <do_if value="$a gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'amount ' + $a"/></do_if>
              <do_if value="$dist gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'dist ' + $dist"/></do_if>
              <do_if value="$bl gt 0"><set_value name="$rej" exact="$rej + (if $rej == '' then '' else ', ') + 'blacklist ' + $bl"/></do_if>
              <do_if value="$rej == ''"><set_value name="$rej" exact="'â€”'"/></do_if>
              
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n  ' + $ageStr + ' | ' + $r + ' | rej: ' + $rej"/>
            </do_all>

            <!-- Quick hints (bounded) -->
            <set_value name="$hint" exact="''"/>
            <do_if value="not $hasRejectionStats">
              <set_value name="$hint" exact="'No rejection stats were recorded yet (likely no evaluation completed for this ship).'" />
            </do_if>
            <do_elseif value="$totalEvaluated == 0">
              <set_value name="$hint" exact="'No offers were evaluated. Consider increasing range or checking if markets are visible/unblocked.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedProfit gt ($tradesRejectedDocking + $tradesRejectedBlacklist + $tradesRejectedDistance)">
              <set_value name="$hint" exact="'Most candidates failed profit checks. Lower min profit/ROI or increase range.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDocking gt 0 and $tradesRejectedDocking ge $tradesRejectedProfit">
              <set_value name="$hint" exact="'Many candidates failed docking checks. Check docking restrictions at stations.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedBlacklist gt 0">
              <set_value name="$hint" exact="'Blacklist/path restrictions filtered many routes. Review blacklists/threat settings.'"/>
            </do_elseif>
            <do_elseif value="$tradesRejectedDistance gt 0">
              <set_value name="$hint" exact="'Many candidates were out of range. Increase max distance (buy/sell) if appropriate.'"/>
            </do_elseif>
            <do_if value="$hint != ''">
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n\nHint: ' + $hint"/>
            </do_if>
          </do_else>
          
          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               SEND LOGBOOK ENTRY (common for all reason-specific templates)
               â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â• -->
          
          <!-- Dump the final logbook message to DebugLog for diagnosis/copy-paste.
               Rate-limited by the existing escalation + 5min per-ship logbook cooldown. -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-LogbookDump] (' + this.ship.idcode + ') reason=' + $noTradeReason + ':\n' + $logbookMessage" chance="100"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $logbookMessage,
            $Category = 'tips',
            $Title = $logbookTitle,
            $Object = this.ship,
            $Interaction = 'showonmap',
            $CheckGlobalSettings = false
          ]"/>
          
          <!-- Log that logbook entry was created -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Logbook entry created (reason=' + $noTradeReason + ', title=' + $logbookTitle + ')'" chance="100"/>
          </do_if>
          
          <!-- Mark that we've written a logbook entry now -->
          <set_value name="this.$lastLogbookEntryTime" exact="player.age"/>
        </do_if>
      </do_if>
      
      <!-- Reset command state and resume search -->
      <do_if value="this.$effectiveIdleParking and not $isCargoDisposal and not $tradeFoundDuringWait and $failureCount ge 6 and this.ship.cargo.count == 0">
        <set_value name="$gtIdleHome" exact="if this.$effectiveHome? and this.$effectiveHome != null and this.$effectiveHome.exists then this.$effectiveHome else null"/>
        <do_if value="$gtIdleHome? and $gtIdleHome != null">
          <run_script name="'lib.gt.idlepark'">
            <param name="handoffMode" value="'trigger'"/>
            <param name="handoffShip" value="this.ship"/>
            <param name="home" value="$gtIdleHome"/>
            <param name="debugchance" value="this.$debugchance"/>
          </run_script>
        </do_if>
      </do_if>
      <set_command command="command.searchtrades"/>
      <set_command_action commandaction="commandaction.searchingtrades"/>
      
      <!-- Resume main trading loop -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Resuming main_loop label'" chance="100"/>
      </do_if>
      <resume label="main_loop"/>
      
      <!-- ========================================================================= -->
      <!-- CARGO SAFETY HANDLERS (In-Parallel Monitoring)                           -->
      <!-- These run in parallel with main trading loop via interrupt-based waits   -->
      <!-- ========================================================================= -->
      
      <!-- ========================================================================= -->
      <!-- DEAD CODE REMOVED: Emergency/Alternative Cargo & Threat Handlers         -->
      <!-- These complex systems were replaced with simple inline cargo check        -->
      <!-- Current implementation: Cargo check at line ~844 sends GT_Find_Sell      -->
      <!-- Threat handler now in interrupt section at lines ~917-941                -->
      <!-- ========================================================================= -->
      
      <!-- ========================================= -->
      <!-- WORK UNIT PROCESSING                      -->
      <!-- ========================================= -->
      
      <!-- Process cache search work unit -->
      <label name="process_cache_workunit"/>
      
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': STARTING cache_search work unit processing'" chance="100"/>
      
      <!-- Extract parameters -->
      <set_value name="$homeSector" exact="@$workUnit.$HomeSector"/>
      <set_value name="$maxDistance" exact="@$workUnit.$MaxDistance"/>
      <set_value name="$minROI" exact="0"/>
      <set_value name="$minAbsoluteProfit" exact="0"/>
      <set_value name="$wareBasket" exact="if $workUnit.$WareBasket? then $workUnit.$WareBasket else $warebasket"/>
      <set_value name="$ignoreBuildStorage" exact="if $workUnit.$IgnoreBuildStorage? then $workUnit.$IgnoreBuildStorage else false"/>
      <set_value name="$ignoreCarrierAux" exact="if $workUnit.$IgnoreCarrierAux? then $workUnit.$IgnoreCarrierAux else false"/>
      
      <!-- Get ship settings for filtering -->
      <!-- Use safe access with defaults in case effective variables aren't initialized in this code path -->
      <set_value name="$allowIllegal" exact="if $workUnit.$AllowIllegal? then $workUnit.$AllowIllegal else (if $effectiveAllowIllegal? then @$effectiveAllowIllegal else false)"/>
      <set_value name="$enforceRouteIllegalLegality" exact="if $workUnit.$EnforceRouteIllegalLegality? then $workUnit.$EnforceRouteIllegalLegality else (if $effectiveEnforceRouteIllegalLegality? then @$effectiveEnforceRouteIllegalLegality else false)"/>
      <set_value name="$ignoreTradeRules" exact="if $workUnit.$IgnoreTradeRules? then $workUnit.$IgnoreTradeRules else (if $effectiveIgnoreTradeRules? then @$effectiveIgnoreTradeRules else false)"/>
      <set_value name="$ignoreMK1Supply" exact="if $workUnit.$IgnoreMK1Supply? then $workUnit.$IgnoreMK1Supply else (if $effectiveIgnoreMK1Supply? then @$effectiveIgnoreMK1Supply else true)"/>
      <set_value name="$shipDockSize" exact="this.ship.docksize"/>
      <set_value name="$isIsolatedForCargoFilter" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{this.ship}?"/>
      <set_value name="$useMinCargoThresholdFilter" exact="if $workUnit.$UseMinCargoThreshold? then $workUnit.$UseMinCargoThreshold else (if $gt_useMinCargoThreshold? then $gt_useMinCargoThreshold else (if this.$effectiveUseMinCargoThresholdFilter? then this.$effectiveUseMinCargoThresholdFilter else false))"/>
      <set_value name="$cacheMinCargoUtilPct" exact="if $gt_cargotarget? then $gt_cargotarget else (if this.$effectiveCargoTarget? then this.$effectiveCargoTarget else 10)"/>
      <set_value name="$cargoUtilThresholdPct" exact="[10,[$cacheMinCargoUtilPct,100].min].max"/>
      
      <!-- Get cache list -->
      <set_value name="$rawCacheList" exact="[]"/>
      <do_if value="global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$homeSector}?">
        <set_value name="$rawCacheList" exact="global.$GT_TradeCacheMK42.{$homeSector}"/>
      </do_if>
      
      <!-- Per-entry distance limits apply in lib.gt.mk42.cache.search; do not reject the whole pool on metadata alone. -->
      <!-- CRITICAL: Load GT_FailedSectorPairs for ship's current sector (prefilter failed sector pairs) -->
      <!-- This prevents revalidating entries that previously failed due to blacklisted routes -->
      <!-- Ships in the same sector share failed sector pairs (same connectivity/blacklist context) -->
      <!-- Ships in different sectors may still try (different path might exist) -->
      <set_value name="$currentSector" exact="this.ship.sector"/>
      <set_value name="$failedTrades" exact="table[]"/>
      <do_if value="$currentSector? and $currentSector.exists and global.$GT_FailedSectorPairs? and global.$GT_FailedSectorPairs.{$currentSector}?">
        <set_value name="$failedTradesRaw" exact="global.$GT_FailedSectorPairs.{$currentSector}"/>
        <set_value name="$expirationTime" exact="1800s"/> <!-- 30 minutes -->
        <run_script name="'lib.gt.failed_sector_pairs'" result="$failedTrades">
          <param name="rawEntry" value="$failedTradesRaw"/>
          <param name="expirationTime" value="$expirationTime"/>
        </run_script>
        <set_value name="$keptCount" exact="0"/>
        <set_value name="$fspBuyKeysNorm" exact="$failedTrades.keys"/>
        <do_all exact="$fspBuyKeysNorm.count" counter="$fspBkci">
          <set_value name="$fspBk" exact="$fspBuyKeysNorm.{$fspBkci}"/>
          <do_if value="$failedTrades.{$fspBk}?">
            <set_value name="$keptCount" exact="$keptCount + $failedTrades.{$fspBk}.keys.count"/>
          </do_if>
        </do_all>
        <do_if value="$keptCount == 0">
          <remove_value name="global.$GT_FailedSectorPairs.{$currentSector}"/>
        </do_if>
        <do_else>
          <set_value name="$fspRoot" exact="table[]"/>
          <do_if value="global.$GT_FailedSectorPairs? and typeof global.$GT_FailedSectorPairs == datatype.table">
            <set_value name="$fspRoot" exact="global.$GT_FailedSectorPairs"/>
          </do_if>
          <set_value name="$fspRoot.{$currentSector}" exact="$failedTrades"/>
          <set_value name="global.$GT_FailedSectorPairs" exact="$fspRoot"/>
        </do_else>
      </do_if>
      
      <!-- NOTE: Removed redundant cache pre-filter money check.
           The Early Money Gate and Fast Money Check already prevent reaching this point
           when player money is below threshold. The old check also had a unit bug
           (compared cents to credits). -->
      
      <!-- ==================================================================================== -->
      <!-- CRITICAL: Pre-filter cache entries by ALL cheap restrictions BEFORE processing -->
      <!-- This prevents validating entries that will never pass these checks -->
      <!-- ==================================================================================== -->
      <set_value name="$mk3BlacklistOwner" exact="this.ship"/>
      <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
        <set_value name="$mk3BlacklistOwner" exact="this.ship.commander"/>
      </do_if>
      <set_value name="$mk3FactionBlacklist" exact="table[]"/>
      <do_if value="global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}?">
        <set_value name="$mk3FactionBlacklist" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}"/>
      </do_if>
      <set_value name="$cacheList" exact="[]"/>
      <set_value name="$rawCount" exact="$rawCacheList.count"/>
      <set_value name="$filterRejectCount" exact="table[
        $Distance = 0,
        $WareBasket = 0,
        $IllegalWare = 0,
        $IncompatibleCargo = 0,
        $RouteIllegal = 0,
        $FactionBlacklist = 0,
        $TradeRules = 0,
        $FailedSectorPairs = 0,
        $FailedShips = 0,
        $TargetType = 0,
        $MinCargoUtil = 0,
        $Mk4PlayerDelivery = 0,
        $Mk4SupplierPolicy = 0,
        $Mk4DedicatedHome = 0,
        $Mk4BuildStorageOnly = 0
      ]"/>
      <!-- Chunked pre-filter: process 50 entries per chunk with cooperative yielding to prevent frame spikes -->
      <set_value name="this.$pfProcessed" exact="0"/>
      <set_value name="this.$pfRouteMemoHits" exact="0"/>
      <label name="prefilter_work_loop"/>
      <set_value name="$pfChunkStart" exact="this.$pfProcessed + 1"/>
      <set_value name="$pfChunkEnd" exact="[this.$pfProcessed + 50, $rawCount].min"/>
      <!-- Chunk-local route-legality memo: skips repeated lib.gt.pathfinding run_script calls
           when multiple rows in this chunk share the same (buySector, sellSector, ware) triple.
           lib.gt.pathfinding already maintains a persistent global cache keyed on
           (home,buy,sell,ware) with $BlacklistEpoch invalidation, so the per-chunk memo only
           saves run_script interpreter overhead, not the underlying legality computation.
           Memo is locals-scoped so it is naturally freed at the cooperative yield, and we keep
           a running total on this.$pfRouteMemoHits so the post-chunk summary debug can report it.
           See DOCS/MK3_PIPELINE_REFACTOR.md Â§3.9. -->
      <set_value name="$pfRouteMemo" exact="table[]"/>
      
      <do_if value="$pfChunkStart le $rawCount">
        <do_all exact="($pfChunkEnd - $pfChunkStart + 1)" counter="$pfIdx">
          <set_value name="$rawIdx" exact="$pfChunkStart + $pfIdx - 1"/>
          <!-- Safe access: global cache list may shrink during cooperative yield between chunks -->
          <set_value name="$rawEntry" exact="@$rawCacheList.{$rawIdx}"/>
          <do_if value="$rawEntry?">
            <set_value name="$entryPassesFilters" exact="true"/>
            
            <!-- 1. Distance filter (using precomputed values from cache entry) -->
            <do_if value="$entryPassesFilters">
              <set_value name="$entryHomeToBuy" exact="@$rawEntry.$HomeToBuyDistance"/>
              <set_value name="$entryHomeToSell" exact="@$rawEntry.$HomeToSellDistance"/>
              <do_if value="$entryHomeToBuy? and $entryHomeToSell?">
                <set_value name="$entryMaxDist" exact="[$entryHomeToBuy, $entryHomeToSell].max"/>
                <do_if value="$entryHomeToBuy lt 0 or $entryHomeToSell lt 0 or $entryMaxDist gt $maxDistance">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Distance" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and ($filterRejectCount.$Distance le 20 or ($entryMaxDist le $maxDistance + 1 and $filterRejectCount.$Distance le 50))">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-filter REJECTED (distance): entryMaxDist=' + $entryMaxDist + ', allowed=' + $maxDistance + ', homeToBuy=' + $entryHomeToBuy + ', homeToSell=' + $entryHomeToSell + ', rawIdx=' + $rawIdx" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $rawIdx le 5">
                    <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-filter PASSED (distance): entryMaxDist=' + $entryMaxDist + ', allowed=' + $maxDistance + ', homeToBuy=' + $entryHomeToBuy + ', homeToSell=' + $entryHomeToSell + ', rawIdx=' + $rawIdx" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and ($rawIdx le 3)">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Pre-filter WARNING: distances not cached for entry (will validate later)'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            
            <!-- 1b. Ware basket filter (manual basket active). -->
            <do_if value="$entryPassesFilters and $wareBasket.count gt 0">
              <set_value name="$entryWare" exact="if $rawEntry.$Ware? then $rawEntry.$Ware else null"/>
              <do_if value="$entryWare == null">
                <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
                <do_if value="$buyOffer? and $buyOffer.exists and $buyOffer.ware?">
                  <set_value name="$entryWare" exact="@$buyOffer.ware"/>
                </do_if>
              </do_if>
              <set_value name="$wareAllowed" exact="false"/>
              <do_if value="$entryWare?">
                <do_all exact="$wareBasket.count" counter="$wbi">
                  <do_if value="$wareBasket.{$wbi} == $entryWare">
                    <set_value name="$wareAllowed" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $wareAllowed">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$WareBasket" operation="add"/>
              </do_if>
            </do_if>

            <!-- 2. Illegal ware filter (if ship doesn't allow illegal) -->
            <do_if value="$entryPassesFilters and not $allowIllegal">
              <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
              <do_if value="$buyOffer? and $buyOffer.exists">
                <set_value name="$ware" exact="@$buyOffer.ware"/>
                <set_value name="$illegalExplicitlyAllowed" exact="false"/>
                <do_if value="$wareBasket.count gt 0 and $ware?">
                  <do_all exact="$wareBasket.count" counter="$ewi">
                    <do_if value="$wareBasket.{$ewi} == $ware">
                      <set_value name="$illegalExplicitlyAllowed" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$ware != null and @$ware.illegal gt 0 and not $illegalExplicitlyAllowed">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$IllegalWare" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 2a. Cargo bay compatibility (solid vs container; shared MK4 pool is ship-agnostic). -->
            <do_if value="$entryPassesFilters and not $rawEntry.$IsSellOnly?">
              <set_value name="$cargoCompatWare" exact="if $rawEntry.$Ware? then $rawEntry.$Ware else null"/>
              <do_if value="$cargoCompatWare == null">
                <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
                <do_if value="$buyOffer? and $buyOffer.exists and $buyOffer.ware?">
                  <set_value name="$cargoCompatWare" exact="@$buyOffer.ware"/>
                </do_if>
              </do_if>
              <set_value name="$cargoCompatTransport" exact="if $rawEntry.$CargoWareTransport? then @$rawEntry.$CargoWareTransport else (if $cargoCompatWare? then @$cargoCompatWare.waretransport else null)"/>
              <set_value name="$cargoCompatOk" exact="false"/>
              <do_if value="$cargoCompatWare? and this.ship.cargo.{$cargoCompatWare}.max gt 0">
                <set_value name="$cargoCompatOk" exact="true"/>
              </do_if>
              <do_elseif value="$cargoCompatTransport? and this.ship.waretransport.indexof.{$cargoCompatTransport}">
                <set_value name="$cargoCompatOk" exact="true"/>
              </do_elseif>
              <do_if value="not $cargoCompatOk">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$IncompatibleCargo" operation="add"/>
              </do_if>
            </do_if>

            <!-- 2b. Illegal route filter â€” contraband only -->
            <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
            <set_value name="$sellOffer" exact="@$rawEntry.$SellOffer"/>
            <set_value name="$ware" exact="if $buyOffer? and $buyOffer.ware? then @$buyOffer.ware else null"/>
            <do_if value="$entryPassesFilters and $allowIllegal and $enforceRouteIllegalLegality and @$ware.illegal gt 0">
              <set_value name="$entryBuySector" exact="if $buyOffer? and $buyOffer.owner? then @$buyOffer.owner.sector else null"/>
              <set_value name="$entrySellSector" exact="if $sellOffer? and $sellOffer.owner? then @$sellOffer.owner.sector else null"/>
              <!-- Chunk-local memo lookup before falling through to run_script. -->
              <set_value name="$routeLegality" exact="null"/>
              <do_if value="$entryBuySector? and $entrySellSector? and $ware? and $pfRouteMemo.{$entryBuySector}? and $pfRouteMemo.{$entryBuySector}.{$entrySellSector}? and $pfRouteMemo.{$entryBuySector}.{$entrySellSector}.{$ware}?">
                <set_value name="$routeLegality" exact="$pfRouteMemo.{$entryBuySector}.{$entrySellSector}.{$ware}"/>
                <set_value name="this.$pfRouteMemoHits" exact="this.$pfRouteMemoHits + 1"/>
              </do_if>
              <do_if value="$routeLegality == null">
                <run_script name="'lib.gt.pathfinding'" result="$routeLegality">
                  <param name="mode" value="'route_legality'"/>
                  <param name="ship" value="this.ship"/>
                  <param name="homeSector" value="$homeSector"/>
                  <param name="blacklistGroup" value="if this.$blacklistgroup? then this.$blacklistgroup else blacklistgroup.civilian"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                  <param name="startSector" value="this.ship.sector"/>
                  <param name="buySector" value="$entryBuySector"/>
                  <param name="sellSector" value="$entrySellSector"/>
                  <param name="ware" value="$ware"/>
                </run_script>
                <do_if value="$entryBuySector? and $entrySellSector? and $ware?">
                  <do_if value="not $pfRouteMemo.{$entryBuySector}?">
                    <set_value name="$pfRouteMemo.{$entryBuySector}" exact="table[]"/>
                  </do_if>
                  <do_if value="not $pfRouteMemo.{$entryBuySector}.{$entrySellSector}?">
                    <set_value name="$pfRouteMemo.{$entryBuySector}.{$entrySellSector}" exact="table[]"/>
                  </do_if>
                  <set_value name="$pfRouteMemo.{$entryBuySector}.{$entrySellSector}.{$ware}" exact="$routeLegality"/>
                </do_if>
              </do_if>
              <do_if value="not $routeLegality.$IsLegal">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$RouteIllegal" operation="add"/>
              </do_if>
            </do_if>
            
            <!-- 3. MK3 faction blacklist filter (per-ship, test feature) -->
            <do_if value="$entryPassesFilters and $mk3FactionBlacklist.keys.count gt 0">
              <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
              <set_value name="$sellOffer" exact="@$rawEntry.$SellOffer"/>
              <do_if value="$buyOffer? and $buyOffer.exists and $buyOffer.owner?">
                <set_value name="$pfBuyOwnerContainer" exact="$buyOffer.owner"/>
                <set_value name="$pfBuyFaction" exact="null"/>
                <do_if value="$pfBuyOwnerContainer.owner?">
                  <set_value name="$pfBuyFaction" exact="$pfBuyOwnerContainer.owner"/>
                </do_if>
                <do_else>
                  <set_value name="$pfBuyFaction" exact="$pfBuyOwnerContainer"/>
                </do_else>
                <do_if value="$pfBuyFaction? and $mk3FactionBlacklist.{$pfBuyFaction}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$FactionBlacklist" operation="add"/>
                </do_if>
              </do_if>
              <do_if value="$entryPassesFilters and $sellOffer? and $sellOffer.exists and $sellOffer.owner?">
                <set_value name="$pfSellOwnerContainer" exact="$sellOffer.owner"/>
                <set_value name="$pfSellFaction" exact="null"/>
                <do_if value="$pfSellOwnerContainer.owner?">
                  <set_value name="$pfSellFaction" exact="$pfSellOwnerContainer.owner"/>
                </do_if>
                <do_else>
                  <set_value name="$pfSellFaction" exact="$pfSellOwnerContainer"/>
                </do_else>
                <do_if value="$pfSellFaction? and $mk3FactionBlacklist.{$pfSellFaction}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$FactionBlacklist" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 4. Trade rules filter (if ship requires trade rules) -->
            <do_if value="$entryPassesFilters and not $ignoreTradeRules">
              <set_value name="$tradeRulesRespected" exact="if $rawEntry.$TradeRulesRespected? then $rawEntry.$TradeRulesRespected else false"/>
              <do_if value="not $tradeRulesRespected">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$TradeRules" operation="add"/>
              </do_if>
            </do_if>
            
            <!-- 5. Failed sector pairs filter â€” O(1) nested table lookup (matching B2 pattern) -->
            <do_if value="$entryPassesFilters and $failedTrades.keys.count gt 0">
              <set_value name="$buyOffer" exact="@$rawEntry.$BuyOffer"/>
              <set_value name="$sellOffer" exact="@$rawEntry.$SellOffer"/>
              <do_if value="$buyOffer? and $buyOffer.exists and $sellOffer? and $sellOffer.exists">
                <set_value name="$entryBuySector" exact="$buyOffer.owner.sector"/>
                <set_value name="$entrySellSector" exact="$sellOffer.owner.sector"/>
                <do_if value="$failedTrades.{$entryBuySector}? and $failedTrades.{$entryBuySector}.{$entrySellSector}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$FailedSectorPairs" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 6. Ship already failed filter (check FailedShips list in cache entry) -->
            <do_if value="$entryPassesFilters">
              <set_value name="$failedShips" exact="@$rawEntry.$FailedShips"/>
              <do_if value="$failedShips != null and $failedShips.count gt 0">
                <do_all exact="$failedShips.count" counter="$f">
                  <do_if value="$failedShips.{$f} == this.ship">
                    <set_value name="$entryPassesFilters" exact="false"/>
                    <set_value name="$filterRejectCount.$FailedShips" operation="add"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
            
            <!-- 7. Target type filters (build storage, carrier/aux) -->
            <do_if value="$entryPassesFilters and ($ignoreBuildStorage or $ignoreCarrierAux)">
              <set_value name="$buyType" exact="@$rawEntry.$BuyTargetType"/>
              <set_value name="$sellType" exact="@$rawEntry.$SellTargetType"/>
              <do_if value="$ignoreBuildStorage and ($buyType == 'Buildstorage' or $sellType == 'Buildstorage')">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$TargetType" operation="add"/>
              </do_if>
              <do_elseif value="$ignoreCarrierAux and (($buyType == 'Aux' or $buyType == 'Carrier') or ($sellType == 'Aux' or $sellType == 'Carrier'))">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$TargetType" operation="add"/>
              </do_elseif>
            </do_if>
            
            <!-- 8. Hard minimum cargo utilization pre-filter (excluded in isolated mode) -->
            <do_if value="$entryPassesFilters and $useMinCargoThresholdFilter and not $isIsolatedForCargoFilter and not $rawEntry.$IsSellOnly?">
              <set_value name="$pfVolumePerUnit" exact="1"/>
              <do_if value="$rawEntry.$Ware? and $rawEntry.$Ware.volume?">
                <set_value name="$pfVolumePerUnit" exact="$rawEntry.$Ware.volume"/>
              </do_if>
              <set_value name="$pfOfferBuyAmount" exact="if $rawEntry.$BuyOffer? and @$rawEntry.$BuyOffer.exists then @$rawEntry.$BuyOffer.offeramount.{this.ship} else 0"/>
              <set_value name="$pfOfferSellAmount" exact="if $rawEntry.$SellOffer? and @$rawEntry.$SellOffer.exists then @$rawEntry.$SellOffer.offeramount.{this.ship} else 0"/>
              <set_value name="$pfAmountLimit" exact="[$pfOfferBuyAmount, $pfOfferSellAmount].min"/>
              <set_value name="$pfTradeVolume" exact="$pfAmountLimit * $pfVolumePerUnit"/>
              <set_value name="$pfRequiredVolume" exact="(this.ship.cargo.capacity.all * $cargoUtilThresholdPct) / 100.0"/>
              <do_if value="$pfTradeVolume lt $pfRequiredVolume">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$MinCargoUtil" operation="add"/>
              </do_if>
            </do_if>
            
            <!-- 9. MK4: delivery station must be player-owned (prefer buyer on cached SellOffer). -->
            <do_if value="$entryPassesFilters">
              <set_value name="$pfDeliveryStation" exact="if $rawEntry.$SellStation? then @$rawEntry.$SellStation else null"/>
              <do_if value="not $pfDeliveryStation? and $rawEntry.$SellOffer?">
                <do_if value="$rawEntry.$SellOffer.buyer? and @$rawEntry.$SellOffer.buyer.exists">
                  <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.buyer"/>
                </do_if>
                <do_elseif value="$rawEntry.$SellOffer.owner?">
                  <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.owner"/>
                </do_elseif>
              </do_if>
              <set_value name="$pfMk4PlayerDeliveryOk" exact="false"/>
              <do_if value="$pfDeliveryStation? and @$pfDeliveryStation.exists">
                <do_if value="@$pfDeliveryStation.isplayerowned">
                  <set_value name="$pfMk4PlayerDeliveryOk" exact="true"/>
                </do_if>
                <do_elseif value="$pfDeliveryStation.isclass.buildstorage and $pfDeliveryStation.base? and @$pfDeliveryStation.base.isplayerowned">
                  <set_value name="$pfMk4PlayerDeliveryOk" exact="true"/>
                </do_elseif>
              </do_if>
              <do_if value="not $pfMk4PlayerDeliveryOk">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4PlayerDelivery" operation="add"/>
              </do_if>
            </do_if>

            <!-- 9a. MK4 home-anchor scope (serveHomeOnly and/or build-storage-only mode). -->
            <do_if value="$entryPassesFilters and (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false)">
              <set_value name="$pfServeHomeAnchor" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null)"/>
              <set_value name="$pfServeHomeSector" exact="if $pfServeHomeAnchor? and $pfServeHomeAnchor.isclass.sector then $pfServeHomeAnchor else (if $pfServeHomeAnchor? and $pfServeHomeAnchor.sector? then @$pfServeHomeAnchor.sector else $homeSector)"/>
              <do_if value="not $pfDeliveryStation?">
                <set_value name="$pfDeliveryStation" exact="if $rawEntry.$SellStation? then @$rawEntry.$SellStation else null"/>
                <do_if value="not $pfDeliveryStation? and $rawEntry.$SellOffer?">
                  <do_if value="$rawEntry.$SellOffer.buyer? and @$rawEntry.$SellOffer.buyer.exists">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.buyer"/>
                  </do_if>
                  <do_elseif value="$rawEntry.$SellOffer.owner?">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_if>
              <set_value name="$pfSuppStationBso" exact="null"/>
              <do_if value="$rawEntry.$BuyOffer? and @$rawEntry.$BuyOffer.exists">
                <do_if value="$rawEntry.$BuyOffer.seller? and @$rawEntry.$BuyOffer.seller.exists">
                  <set_value name="$pfSuppStationBso" exact="@$rawEntry.$BuyOffer.seller"/>
                </do_if>
              </do_if>
              <do_if value="not $pfSuppStationBso? and $rawEntry.$BuyStation?">
                <set_value name="$pfSuppStationBso" exact="@$rawEntry.$BuyStation"/>
              </do_if>
              <do_if value="$pfSuppStationBso? and @$pfSuppStationBso.isclass.buildstorage">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4BuildStorageOnly" operation="add"/>
              </do_if>
              <do_if value="$entryPassesFilters and (not $pfDeliveryStation? or not @$pfDeliveryStation.isclass.buildstorage)">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4BuildStorageOnly" operation="add"/>
              </do_if>
              <do_if value="$entryPassesFilters">
                <set_value name="$pfBsoDist" exact="if $homeSector? and $pfDeliveryStation? and $pfDeliveryStation.sector? then $homeSector.gatedistance.{$pfDeliveryStation.sector} else -1"/>
                <set_value name="$pfBsoCoverageMax" exact="if this.$effectiveMaxSell? then this.$effectiveMaxSell else $maxDistance"/>
                <do_if value="$pfBsoDist lt 0 or ($pfBsoCoverageMax gt 0 and $pfBsoDist gt $pfBsoCoverageMax)">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4BuildStorageOnly" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$entryPassesFilters and not (if this.$mk4BuildStorageOnlyMode? then this.$mk4BuildStorageOnlyMode else false) and (if this.$mk4DedicatedServe? then this.$mk4DedicatedServe else false)">
              <set_value name="$pfServeHomeAnchor" exact="if this.$effectiveHome? then this.$effectiveHome else (if this.ship.defaultorder and this.ship.defaultorder.$home? then @this.ship.defaultorder.$home else null)"/>
              <set_value name="$pfServeHomeSector" exact="if $pfServeHomeAnchor? and $pfServeHomeAnchor.isclass.sector then $pfServeHomeAnchor else (if $pfServeHomeAnchor? and $pfServeHomeAnchor.sector? then @$pfServeHomeAnchor.sector else $homeSector)"/>
              <do_if value="not $pfDeliveryStation?">
                <set_value name="$pfDeliveryStation" exact="if $rawEntry.$SellStation? then @$rawEntry.$SellStation else null"/>
                <do_if value="not $pfDeliveryStation? and $rawEntry.$SellOffer?">
                  <do_if value="$rawEntry.$SellOffer.buyer? and @$rawEntry.$SellOffer.buyer.exists">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.buyer"/>
                  </do_if>
                  <do_elseif value="$rawEntry.$SellOffer.owner?">
                    <set_value name="$pfDeliveryStation" exact="@$rawEntry.$SellOffer.owner"/>
                  </do_elseif>
                </do_if>
              </do_if>
              <do_if value="$pfServeHomeAnchor? and $pfServeHomeAnchor.isclass.station">
                <set_value name="$pfServeHomeMatch" exact="false"/>
                <do_if value="$pfDeliveryStation? and $pfDeliveryStation.exists and $pfServeHomeAnchor.exists">
                  <do_if value="$pfDeliveryStation == $pfServeHomeAnchor">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_if>
                  <do_elseif value="$pfServeHomeAnchor.buildstorage? and $pfServeHomeAnchor.buildstorage.exists and $pfDeliveryStation == $pfServeHomeAnchor.buildstorage">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$pfDeliveryStation.isclass.buildstorage and $pfDeliveryStation.base? and $pfDeliveryStation.base.exists and $pfDeliveryStation.base == $pfServeHomeAnchor">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$pfDeliveryStation.hascontext.{$pfServeHomeAnchor}">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$pfServeHomeAnchor.hascontext.{$pfDeliveryStation}">
                    <set_value name="$pfServeHomeMatch" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="not $pfServeHomeMatch">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4DedicatedHome" operation="add"/>
                </do_if>
              </do_if>
              <do_elseif value="$pfServeHomeSector? and $pfServeHomeSector.exists">
                <do_if value="not $pfDeliveryStation? or not $pfDeliveryStation.sector? or @$pfDeliveryStation.sector != $pfServeHomeSector">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4DedicatedHome" operation="add"/>
                </do_if>
              </do_elseif>
            </do_if>
            
            <!-- 9b. MK4: supplier ($BuyOffer = game sell offer; ship buys here) vs allowAiSuppliers / allowPlayerSuppliers -->
            <do_if value="$entryPassesFilters">
              <set_value name="$pfSuppStation" exact="null"/>
              <do_if value="$rawEntry.$BuyOffer? and @$rawEntry.$BuyOffer.exists">
                <do_if value="$rawEntry.$BuyOffer.seller? and @$rawEntry.$BuyOffer.seller.exists">
                  <set_value name="$pfSuppStation" exact="@$rawEntry.$BuyOffer.seller"/>
                </do_if>
              </do_if>
              <do_if value="not $pfSuppStation? and $rawEntry.$BuyStation?">
                <set_value name="$pfSuppStation" exact="@$rawEntry.$BuyStation"/>
              </do_if>
              <set_value name="$pfMk4AISup" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
              <set_value name="$pfMk4PlSup" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
              <do_if value="not $pfMk4PlSup and $pfSuppStation? and @$pfSuppStation.isplayerowned">
                <set_value name="$entryPassesFilters" exact="false"/>
                <set_value name="$filterRejectCount.$Mk4SupplierPolicy" operation="add"/>
              </do_if>
              <do_if value="$entryPassesFilters and not $pfMk4AISup">
                <do_if value="not $pfSuppStation? or not @$pfSuppStation.isplayerowned">
                  <set_value name="$entryPassesFilters" exact="false"/>
                  <set_value name="$filterRejectCount.$Mk4SupplierPolicy" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- 10. MK1-supplied station filter -->
            <do_if value="$entryPassesFilters and $ignoreMK1Supply and global.$GT_MK1SuppliedStations?">
              <do_if value="$rawEntry.$BuyStation?">
                <do_if value="global.$GT_MK1SuppliedStations.{$rawEntry.$BuyStation}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="$entryPassesFilters and $rawEntry.$SellStation?">
                <do_if value="global.$GT_MK1SuppliedStations.{$rawEntry.$SellStation}?">
                  <set_value name="$entryPassesFilters" exact="false"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- Add entry to filtered list if it passed all pre-filters -->
            <do_if value="$entryPassesFilters">
              <append_to_list name="$cacheList" exact="$rawEntry"/>
            </do_if>
          </do_if>
        </do_all>
        
        <set_value name="this.$pfProcessed" exact="$pfChunkEnd"/>
        
        <!-- Cooperative yield between pre-filter chunks -->
        <wait exact="this.$gt_yieldMs * 1ms"/>
        
        <!-- Continue if more entries to process -->
        <do_if value="this.$pfProcessed lt $rawCount">
          <resume label="prefilter_work_loop"/>
        </do_if>
      </do_if>
      
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache search params: homeSector=' + (if $homeSector? then $homeSector.knownname else 'null') + ', maxDistance=' + $maxDistance + ', cacheMaxDistance=' + $cacheMaxDistance + ', minProfit=' + $minAbsoluteProfit + ', minROI=' + $minROI + ', rawEntries=' + $rawCount + ', preFilteredEntries=' + $cacheList.count + ', routeMemoHits=' + (if this.$pfRouteMemoHits? then this.$pfRouteMemoHits else 0) + ', filterRejections: Distance=' + $filterRejectCount.$Distance + ', WareBasket=' + $filterRejectCount.$WareBasket + ', IllegalWare=' + $filterRejectCount.$IllegalWare + ', IncompatibleCargo=' + $filterRejectCount.$IncompatibleCargo + ', RouteIllegal=' + $filterRejectCount.$RouteIllegal + ', FactionBlacklist=' + $filterRejectCount.$FactionBlacklist + ', TradeRules=' + $filterRejectCount.$TradeRules + ', FailedSectorPairs=' + $filterRejectCount.$FailedSectorPairs + ', FailedShips=' + $filterRejectCount.$FailedShips + ', TargetType=' + $filterRejectCount.$TargetType + ', Mk4PlayerDelivery=' + $filterRejectCount.$Mk4PlayerDelivery + ', Mk4SupplierPolicy=' + $filterRejectCount.$Mk4SupplierPolicy + ', Mk4DedicatedHome=' + $filterRejectCount.$Mk4DedicatedHome + ', Mk4BuildStorageOnly=' + $filterRejectCount.$Mk4BuildStorageOnly" chance="100"/>
      <do_if value="this.$pfRouteMemoHits?">
        <remove_value name="this.$pfRouteMemoHits"/>
      </do_if>
      
      <!-- Process cache entries with frame budgeting -->
      <!-- Get chunk size from global settings (default: 20) -->
      <set_value name="$chunkSize" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize?">
        <set_value name="$tmpChunk" exact="@global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize"/>
        <do_if value="$tmpChunk? and $tmpChunk != null and $tmpChunk gt 0">
          <set_value name="$chunkSize" exact="$tmpChunk"/>
        </do_if>
      </do_if>
      <!-- Clamp to reasonable bounds -->
      <do_if value="$chunkSize lt 10">
        <set_value name="$chunkSize" exact="10"/>
      </do_if>
      <do_if value="$chunkSize gt 200">
        <set_value name="$chunkSize" exact="200"/>
      </do_if>
      
      <!-- Get max trades to return from global settings -->
      <set_value name="$maxTradesToReturn" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn?">
        <set_value name="$tmpMax" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn"/>
        <do_if value="$tmpMax? and $tmpMax != null and $tmpMax gt 0">
          <set_value name="$maxTradesToReturn" exact="$tmpMax"/>
        </do_if>
      </do_if>
      
      <!-- Per-ware diversification for cache work-loop results (parity with lib.gt.mk42.cache.search). -->
      <set_value name="$cacheWorkWareBasketCount" exact="if $wareBasket? and typeof $wareBasket == datatype.list then $wareBasket.count else 0"/>
      <set_value name="$cacheWorkFoundPerWare" exact="table[]"/>
      <set_value name="$cacheWorkMaxTradesPerWare" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
        <set_value name="$cacheWorkMaxTradesPerWare" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
      </do_if>
      <do_if value="$cacheWorkMaxTradesPerWare lt 1">
        <set_value name="$cacheWorkMaxTradesPerWare" exact="1"/>
      </do_if>
      <set_value name="$cacheWorkPerWareCap" exact="$cacheWorkMaxTradesPerWare"/>
      <do_if value="$cacheWorkWareBasketCount gt 0">
        <set_value name="$cacheWorkPerWareCapFromBudget" exact="[1, ($maxTradesToReturn / $cacheWorkWareBasketCount)i].max"/>
        <set_value name="$cacheWorkPerWareCap" exact="[$cacheWorkPerWareCapFromBudget, $cacheWorkMaxTradesPerWare].min"/>
      </do_if>
      <do_else>
        <set_value name="$cacheWorkPerWareCap" exact="[2, [$cacheWorkMaxTradesPerWare, 5].min].max"/>
      </do_else>

      <set_value name="this.$processedCount" exact="0"/>
      <set_value name="this.$gt_dockMemo" exact="table[]"/>
      <set_value name="$validTrades" exact="[]"/>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>
      <set_value name="$cachePriorityBoostCount" exact="0"/>
      <set_value name="$bestWasPriority" exact="false"/>
      
      <!-- Debug: log when priority wares will be applied during cache scoring -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0">
          <set_value name="$pwNames" exact="''"/>
          <do_all exact="$effectivePriorityWares.count" counter="$pn">
            <set_value name="$pnw" exact="$effectivePriorityWares.{$pn}"/>
            <set_value name="$pwNames" exact="$pwNames + (if $pn gt 1 then ', ' else '') + (if $pnw? and $pnw != null then @$pnw.name else '?')"/>
          </do_all>
          <set_value name="$cacheMultPct" exact="if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 1"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache search: priority wares active (' + $effectivePriorityWares.count + ' wares: [' + $pwNames + '], multiplier=' + $cacheMultPct + '%)'" chance="100"/>
        </do_if>
      </do_if>
      
      <label name="cache_work_loop"/>
      <set_value name="$startTime" exact="player.age"/>
      <set_value name="$chunkStart" exact="this.$processedCount + 1"/>
      <set_value name="$chunkEnd" exact="[this.$processedCount + $chunkSize, $cacheList.count].min"/>
      
      <do_if value="$chunkStart le $cacheList.count">
        <do_all exact="($chunkEnd - $chunkStart + 1)" counter="$i">
          <set_value name="$cacheIndex" exact="$chunkStart + $i - 1"/>
          <set_value name="$cacheEntry" exact="$cacheList.{$cacheIndex}"/>
          
          <!-- Validate cache entry -->
          <do_if value="$cacheEntry?">
            <set_value name="$cacheAge" exact="player.age - $cacheEntry.$Timestamp"/>
            <do_if value="$cacheAge le 600s">
              <!-- Validate cache entry with full filtering (aligned with lib.gt.mk42.cache.search + MD purge/reservation rules) -->
              <!-- Use ship-agnostic fields for validation -->
              <set_value name="$buyOffer" exact="@$cacheEntry.$BuyOffer"/>
              <set_value name="$sellOffer" exact="@$cacheEntry.$SellOffer"/>
              
              <!-- Get ship-agnostic fields from cache entry -->
              <set_value name="$offerMaxAmount" exact="@$cacheEntry.$OfferMaxAmount"/>
              <set_value name="$profitPerUnit" exact="@$cacheEntry.$ProfitPerUnit"/>
              <set_value name="$volumePerUnit" exact="@$cacheEntry.$VolumePerUnit"/>
              <set_value name="$buyPrice" exact="@$cacheEntry.$BuyPrice"/>
              <set_value name="$sellPrice" exact="@$cacheEntry.$SellPrice"/>
              
              <!-- Fallback to ship-biased fields for old cache entries (backward compatibility) -->
              <do_if value="not $offerMaxAmount? or $offerMaxAmount == null or $offerMaxAmount le 0">
                <set_value name="$offerMaxAmount" exact="@$cacheEntry.$Amount"/>
              </do_if>
              <do_if value="not $profitPerUnit? or $profitPerUnit == null">
                <set_value name="$cachedProfit" exact="@$cacheEntry.$Profit"/>
                <set_value name="$cachedAmount" exact="@$cacheEntry.$Amount"/>
                <do_if value="$cachedAmount? and $cachedAmount gt 0">
                  <set_value name="$profitPerUnit" exact="$cachedProfit / $cachedAmount"/>
                </do_if>
                <do_else>
                  <set_value name="$profitPerUnit" exact="0"/>
                </do_else>
              </do_if>
              <do_if value="not $volumePerUnit? or $volumePerUnit == null">
                <set_value name="$ware" exact="@$buyOffer.ware"/>
                <set_value name="$volumePerUnit" exact="if $ware? and $ware.volume? then $ware.volume else 1"/>
              </do_if>
              <do_if value="not $buyPrice? or $buyPrice == null">
                <set_value name="$buyPrice" exact="if $buyOffer? and $buyOffer.price? then $buyOffer.price else 0"/>
              </do_if>
              <do_if value="not $sellPrice? or $sellPrice == null">
                <set_value name="$sellPrice" exact="if $sellOffer? and $sellOffer.price? then $sellOffer.price else 0"/>
                <do_if value="$profitPerUnit == 0 and $sellPrice gt 0 and $buyPrice gt 0">
                  <set_value name="$profitPerUnit" exact="$sellPrice - $buyPrice"/>
                </do_if>
              </do_if>
              
              <!-- Track rejection reason for debugging -->
              <set_value name="$rejectReason" exact="''"/>
              <set_value name="$isValid" exact="true"/>
              
              <!-- Basic structure checks -->
              <do_if value="not $buyOffer? or not $buyOffer.exists or not $sellOffer? or not $sellOffer.exists">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$rejectReason" exact="'offers_invalid'"/>
              </do_if>
              <do_elseif value="not @$buyOffer.owner.isoperational or not @$sellOffer.owner.isoperational">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$rejectReason" exact="'station_not_operational'"/>
              </do_elseif>
              
              <!-- Cargo bay compatibility (solid vs container; shared MK4 pool). -->
              <do_if value="$isValid and not $cacheEntry.$IsSellOnly?">
                <set_value name="$cacheWorkCargoWare" exact="if $cacheEntry.$Ware? then $cacheEntry.$Ware else null"/>
                <do_if value="not $cacheWorkCargoWare? and $buyOffer? and $buyOffer.exists and $buyOffer.ware?">
                  <set_value name="$cacheWorkCargoWare" exact="@$buyOffer.ware"/>
                </do_if>
                <do_if value="not $cacheWorkCargoWare? and $sellOffer? and $sellOffer.exists and $sellOffer.ware?">
                  <set_value name="$cacheWorkCargoWare" exact="@$sellOffer.ware"/>
                </do_if>
                <set_value name="$cacheWorkCargoTransport" exact="if $cacheEntry.$CargoWareTransport? then @$cacheEntry.$CargoWareTransport else (if $cacheWorkCargoWare? then @$cacheWorkCargoWare.waretransport else null)"/>
                <set_value name="$cacheWorkCargoOk" exact="false"/>
                <do_if value="$cacheWorkCargoWare? and this.ship.cargo.{$cacheWorkCargoWare}.max gt 0">
                  <set_value name="$cacheWorkCargoOk" exact="true"/>
                </do_if>
                <do_elseif value="$cacheWorkCargoTransport? and this.ship.waretransport.indexof.{$cacheWorkCargoTransport}">
                  <set_value name="$cacheWorkCargoOk" exact="true"/>
                </do_elseif>
                <do_if value="not $cacheWorkCargoOk">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'incompatible_cargo'"/>
                </do_if>
              </do_if>
              
              <!-- MK4 Galaxy-Supply: delivery = cached $SellOffer (game buy offer); prefer buyer (lib.gt.mk42.tradematch). -->
              <do_if value="$isValid">
                <set_value name="$mk4DelivCustomer" exact="null"/>
                <do_if value="$sellOffer.buyer? and @$sellOffer.buyer.exists">
                  <set_value name="$mk4DelivCustomer" exact="@$sellOffer.buyer"/>
                </do_if>
                <do_elseif value="$sellOffer.owner?">
                  <set_value name="$mk4DelivCustomer" exact="@$sellOffer.owner"/>
                </do_elseif>
                <do_if value="not $mk4DelivCustomer? or not @$mk4DelivCustomer.isplayerowned">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk4_delivery_not_player'"/>
                </do_if>
              </do_if>
              
              <!-- MK4: supplier = cached $BuyOffer (game sell offer); prefer seller (lib.gt.mk42.tradematch). -->
              <do_if value="$isValid">
                <set_value name="$mk4SupplierStationVal" exact="null"/>
                <do_if value="$buyOffer.seller? and @$buyOffer.seller.exists">
                  <set_value name="$mk4SupplierStationVal" exact="@$buyOffer.seller"/>
                </do_if>
                <do_elseif value="$buyOffer.owner?">
                  <set_value name="$mk4SupplierStationVal" exact="@$buyOffer.owner"/>
                </do_elseif>
                <set_value name="$valMk4AISup" exact="if this.$mk4AllowAiSuppliers? then this.$mk4AllowAiSuppliers else true"/>
                <set_value name="$valMk4PlSup" exact="if this.$mk4AllowPlayerSuppliers? then this.$mk4AllowPlayerSuppliers else true"/>
                <do_if value="not $valMk4PlSup and $mk4SupplierStationVal? and @$mk4SupplierStationVal.isplayerowned">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk4_player_supplier_disallowed'"/>
                </do_if>
                <do_if value="$isValid and not $valMk4AISup">
                  <do_if value="not $mk4SupplierStationVal? or not @$mk4SupplierStationVal.isplayerowned">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'mk4_ai_supplier_disallowed'"/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- NOTE: Distance, illegal ware, trade rules, failed sector pairs, failed ships,
                   and target type checks are SKIPPED here â€” already verified by the pre-filter
                   loop (prefilter_work_loop). Only time-sensitive and ship-specific expensive
                   checks remain below (docking, dock size, offer availability, profit/ROI). -->
              
              <!-- ==================================================================================== -->
              <!-- EXPENSIVE CHECKS LAST: Property lookups on ship/station objects -->
              <!-- ==================================================================================== -->
              
              <!-- Dock feasibility (ship-specific): trading bays on stations, storage bays on build storage -->
              <do_if value="$isValid">
                <set_value name="$cacheValBuyStation" exact="null"/>
                <do_if value="$buyOffer.seller? and @$buyOffer.seller.exists">
                  <set_value name="$cacheValBuyStation" exact="@$buyOffer.seller"/>
                </do_if>
                <do_elseif value="$buyOffer.owner?">
                  <set_value name="$cacheValBuyStation" exact="@$buyOffer.owner"/>
                </do_elseif>
                <set_value name="$cacheValSellStation" exact="null"/>
                <do_if value="$sellOffer.buyer? and @$sellOffer.buyer.exists">
                  <set_value name="$cacheValSellStation" exact="@$sellOffer.buyer"/>
                </do_if>
                <do_elseif value="$sellOffer.owner?">
                  <set_value name="$cacheValSellStation" exact="@$sellOffer.owner"/>
                </do_elseif>
                <set_value name="$cacheValCanDockBuy" exact="false"/>
                <run_script name="'lib.gt.dockcheck'" result="$cacheValBuyDockResult">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$cacheValBuyStation"/>
                  <param name="purpose" value="'trade'"/>
                  <param name="useMemo" value="true"/>
                </run_script>
                <set_value name="$cacheValCanDockBuy" exact="$cacheValBuyDockResult.$CanDock"/>
                <set_value name="$cacheValCanDockSell" exact="false"/>
                <run_script name="'lib.gt.dockcheck'" result="$cacheValSellDockResult">
                  <param name="ship" value="this.ship"/>
                  <param name="station" value="$cacheValSellStation"/>
                  <param name="purpose" value="'trade'"/>
                  <param name="useMemo" value="true"/>
                </run_script>
                <set_value name="$cacheValCanDockSell" exact="$cacheValSellDockResult.$CanDock"/>
                <do_if value="not $cacheValCanDockBuy or not $cacheValCanDockSell">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'docking_not_allowed'"/>
                </do_if>
              </do_if>
              
              <!-- ==================================================================================== -->
              <!-- SHIP-AGNOSTIC CACHE VALIDATION: Use ship-agnostic fields for prefiltering -->
              <!-- ==================================================================================== -->
              
              <!-- Validate offers are still available -->
              <do_if value="$isValid">
                <set_value name="$buyOfferObj" exact="@$cacheEntry.$BuyOffer"/>
                <set_value name="$sellOfferObj" exact="@$cacheEntry.$SellOffer"/>
                <do_if value="not $buyOfferObj? or $buyOfferObj == null or not $buyOfferObj.exists or not $sellOfferObj? or $sellOfferObj == null or not $sellOfferObj.exists">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'offers_no_longer_exist'"/>
                </do_if>
                <do_else>
                  <set_value name="$buyAvailNow" exact="@$buyOfferObj.available"/>
                  <set_value name="$sellAvailNow" exact="@$sellOfferObj.available"/>
                  <set_value name="$buyAmtNow" exact="@$buyOfferObj.amount"/>
                  <set_value name="$sellAmtNow" exact="@$sellOfferObj.amount"/>
                  <do_if value="$buyAmtNow == null">
                    <set_value name="$buyAmtNow" exact="0"/>
                  </do_if>
                  <do_if value="$sellAmtNow == null">
                    <set_value name="$sellAmtNow" exact="0"/>
                  </do_if>
                  <do_if value="not $buyAvailNow or not $sellAvailNow or $buyAmtNow le 0 or $sellAmtNow le 0">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'offers_insufficient_amount buyAvail=' + $buyAvailNow + ' buyAmt=' + $buyAmtNow + ' sellAvail=' + $sellAvailNow + ' sellAmt=' + $sellAmtNow + ' (both stations must have stock > 0)'"/>
                  </do_if>
                  <do_else>
                    <!-- Update offerMaxAmount with current offer amounts (may have changed since cache creation) -->
                    <set_value name="$currentOfferMaxAmount" exact="[$buyAmtNow, $sellAmtNow].min"/>
                    <do_if value="$currentOfferMaxAmount lt $offerMaxAmount">
                      <set_value name="$offerMaxAmount" exact="$currentOfferMaxAmount"/>
                    </do_if>
                  </do_else>
                </do_else>
              </do_if>
              
              <!-- ==================================================================================== -->
              <!-- SHIP-SPECIFIC PREFILTERING: Calculate max tradeable amount for THIS ship -->
              <!-- ==================================================================================== -->
              
              <!-- Calculate ship's max tradeable amount based on cargo capacity -->
              <do_if value="$isValid">
                <set_value name="$shipMaxByCargo" exact="0"/>
                <do_if value="$volumePerUnit gt 0">
                  <set_value name="$shipCargoCapacity" exact="this.ship.cargo.capacity.all"/>
                  <set_value name="$shipCargoFree" exact="this.ship.cargo.free.all"/>
                  <set_value name="$shipMaxByCargo" exact="$shipCargoFree / $volumePerUnit"/>
                </do_if>
                
                <!-- Calculate ship's max tradeable amount based on money (if applicable) -->
                <set_value name="$shipMaxByMoney" exact="999999999"/>
                <do_if value="$buyPrice gt 0">
                  <set_value name="$playerMoney" exact="player.money"/>
                  <set_value name="$shipMaxByMoney" exact="$playerMoney / $buyPrice"/>
                </do_if>
                
                <!-- Calculate ship's actual max tradeable amount -->
                <set_value name="$shipMaxAmount" exact="[$offerMaxAmount, $shipMaxByCargo, $shipMaxByMoney].min"/>
                
                <!-- Early rejection: ship cannot trade any amount -->
                <do_if value="$shipMaxAmount le 0">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'ship_cannot_carry_amount cargoMax=' + $shipMaxByCargo + ' moneyMax=' + $shipMaxByMoney + ' offerMax=' + $offerMaxAmount"/>
                </do_if>
                <do_else>
                  <!-- Hard minimum cargo utilization filter (excluded in isolated mode) -->
                  <do_if value="$useMinCargoThresholdFilter and not $isIsolatedForCargoFilter and not $cacheEntry.$IsSellOnly?">
                    <set_value name="$cacheTradeVolume" exact="$shipMaxAmount * $volumePerUnit"/>
                    <set_value name="$cacheRequiredVolume" exact="(this.ship.cargo.capacity.all * $cargoUtilThresholdPct) / 100.0"/>
                    <do_if value="$cacheTradeVolume lt $cacheRequiredVolume">
                      <set_value name="$isValid" exact="false"/>
                      <set_value name="$rejectReason" exact="'cargo_utilization_below_min actualVol=' + $cacheTradeVolume + ' requiredVol=' + $cacheRequiredVolume + ' threshold=' + $cargoUtilThresholdPct + '%'"/>
                    </do_if>
                  </do_if>

                  <do_if value="$isValid">
                    <!-- MK4 supply price-cap check:
                         allow equal price; reject only if source price is above customer buy price. -->
                    <do_if value="$sellPrice lt $buyPrice">
                      <set_value name="$isValid" exact="false"/>
                      <set_value name="$rejectReason" exact="'mk4_price_cap_exceeded source=' + $buyPrice + ' customer=' + $sellPrice"/>
                    </do_if>
                  </do_if>
                </do_else>
              </do_if>
              
              <!-- CRITICAL: Re-validate offers with tradepartner to ensure trade rules are respected -->
              <do_if value="$isValid and not $ignoreTradeRules">
                <set_value name="$buyStation" exact="null"/>
                <do_if value="$cacheEntry.$BuyOffer.seller? and @$cacheEntry.$BuyOffer.seller.exists">
                  <set_value name="$buyStation" exact="@$cacheEntry.$BuyOffer.seller"/>
                </do_if>
                <do_elseif value="$cacheEntry.$BuyOffer.owner?">
                  <set_value name="$buyStation" exact="@$cacheEntry.$BuyOffer.owner"/>
                </do_elseif>
                <set_value name="$buyWare" exact="@$cacheEntry.$BuyOffer.ware"/>
                <set_value name="$sellStation" exact="null"/>
                <do_if value="$cacheEntry.$SellOffer.buyer? and @$cacheEntry.$SellOffer.buyer.exists">
                  <set_value name="$sellStation" exact="@$cacheEntry.$SellOffer.buyer"/>
                </do_if>
                <do_elseif value="$cacheEntry.$SellOffer.owner?">
                  <set_value name="$sellStation" exact="@$cacheEntry.$SellOffer.owner"/>
                </do_elseif>
                <set_value name="$sellWare" exact="@$cacheEntry.$SellOffer.ware"/>
                
                <do_if value="$buyStation? and $buyStation.exists and $buyWare != null">
                  <find_sell_offer seller="$buyStation" wares="$buyWare" tradepartner="this.ship" result="$validatedBuyOffer"/>
                  <do_if value="not $validatedBuyOffer.available">
                    <set_value name="$isValid" exact="false"/>
                    <set_value name="$rejectReason" exact="'trade_rules_buy_violation'"/>
                  </do_if>
                </do_if>
                
                <do_if value="$isValid and $sellStation? and $sellStation.exists and $sellWare != null">
                  <!-- Build-storage buy offers are "empty" (.available stays false while a cargo deficit
                       exists), so fetch with excludeempty/usereservations=false and accept a resolvable
                       offer rather than requiring .available (which would reject every build storage). -->
                  <do_if value="@$sellStation.isclass.buildstorage">
                    <find_buy_offer buyer="$sellStation" wares="$sellWare" tradepartner="this.ship" result="$validatedSellOffer" excludeempty="false" usereservations="false"/>
                    <do_if value="not $validatedSellOffer? or not @$validatedSellOffer.exists">
                      <set_value name="$isValid" exact="false"/>
                      <set_value name="$rejectReason" exact="'trade_rules_sell_violation'"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <find_buy_offer buyer="$sellStation" wares="$sellWare" tradepartner="this.ship" result="$validatedSellOffer"/>
                    <do_if value="not $validatedSellOffer.available">
                      <set_value name="$isValid" exact="false"/>
                      <set_value name="$rejectReason" exact="'trade_rules_sell_violation'"/>
                    </do_if>
                  </do_else>
                </do_if>
              </do_if>
              
              <!-- MK3 faction blacklist safety net -->
              <do_if value="$isValid and $mk3FactionBlacklist.keys.count gt 0">
                <set_value name="$cacheBuyFaction" exact="null"/>
                <set_value name="$cacheSellFaction" exact="null"/>
                <do_if value="$cacheEntry.$BuyOffer? and $cacheEntry.$BuyOffer.owner?">
                  <set_value name="$cacheBuyOwnerContainer" exact="@$cacheEntry.$BuyOffer.owner"/>
                  <do_if value="$cacheBuyOwnerContainer.owner?">
                    <set_value name="$cacheBuyFaction" exact="$cacheBuyOwnerContainer.owner"/>
                  </do_if>
                  <do_else>
                    <set_value name="$cacheBuyFaction" exact="$cacheBuyOwnerContainer"/>
                  </do_else>
                </do_if>
                <do_if value="$cacheEntry.$SellOffer? and $cacheEntry.$SellOffer.owner?">
                  <set_value name="$cacheSellOwnerContainer" exact="@$cacheEntry.$SellOffer.owner"/>
                  <do_if value="$cacheSellOwnerContainer.owner?">
                    <set_value name="$cacheSellFaction" exact="$cacheSellOwnerContainer.owner"/>
                  </do_if>
                  <do_else>
                    <set_value name="$cacheSellFaction" exact="$cacheSellOwnerContainer"/>
                  </do_else>
                </do_if>
                <do_if value="$cacheBuyFaction? and $mk3FactionBlacklist.{$cacheBuyFaction}?">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk3_faction_blacklist_buy'"/>
                </do_if>
                <do_if value="$isValid and $cacheSellFaction? and $mk3FactionBlacklist.{$cacheSellFaction}?">
                  <set_value name="$isValid" exact="false"/>
                  <set_value name="$rejectReason" exact="'mk3_faction_blacklist_sell'"/>
                </do_if>
              </do_if>
              
              <!-- Debug first few entries -->
              <do_if value="this.$processedCount + $i le 3">
                <!-- Log cache entry with distance information for debugging -->
                <set_value name="$entryHomeToBuy" exact="@$cacheEntry.$HomeToBuyDistance"/>
                <set_value name="$entryHomeToSell" exact="@$cacheEntry.$HomeToSellDistance"/>
                <set_value name="$entryMaxDist" exact="if ($entryHomeToBuy? and $entryHomeToSell? and $entryHomeToBuy ge 0 and $entryHomeToSell ge 0) then [$entryHomeToBuy, $entryHomeToSell].max else -1"/>
                <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache entry ' + (this.$processedCount + $i) + ': profit=' + (if $shipMaxProfit? then $shipMaxProfit else 'null') + ', minProfit=' + $minAbsoluteProfit + ', roi=' + (if $shipROI? then $shipROI else 'null') + ', minROI=' + $minROI + ', shipMaxAmount=' + (if $shipMaxAmount? then $shipMaxAmount else 'null') + ', homeToBuy=' + (if $entryHomeToBuy? then $entryHomeToBuy else 'null') + ', homeToSell=' + (if $entryHomeToSell? then $entryHomeToSell else 'null') + ', maxDist=' + $entryMaxDist + ', allowed=' + $maxDistance + ', valid=' + $isValid + (if not $isValid then ' reason=' + $rejectReason else '')" chance="100"/>
              </do_if>
              
              <!-- Add to valid trades if all checks passed -->
              <do_if value="$isValid">
                <set_value name="$cacheWorkQuotaWare" exact="if $cacheEntry.$Ware? then $cacheEntry.$Ware else null"/>
                <do_if value="not $cacheWorkQuotaWare? and $cacheEntry.$BuyOffer? and @$cacheEntry.$BuyOffer.ware != null">
                  <set_value name="$cacheWorkQuotaWare" exact="@$cacheEntry.$BuyOffer.ware"/>
                </do_if>
                <do_if value="not $cacheWorkQuotaWare? and $cacheEntry.$SellOffer? and @$cacheEntry.$SellOffer.ware != null">
                  <set_value name="$cacheWorkQuotaWare" exact="@$cacheEntry.$SellOffer.ware"/>
                </do_if>
                <set_value name="$cacheWorkQuotaSkip" exact="false"/>
                <do_if value="$cacheWorkQuotaWare?">
                  <set_value name="$cacheWorkQuotaWareCount" exact="if $cacheWorkFoundPerWare.{$cacheWorkQuotaWare}? then $cacheWorkFoundPerWare.{$cacheWorkQuotaWare} else 0"/>
                  <do_if value="$cacheWorkQuotaWareCount ge $cacheWorkPerWareCap">
                    <set_value name="$cacheWorkQuotaSkip" exact="true"/>
                  </do_if>
                </do_if>
                <do_if value="not $cacheWorkQuotaSkip and $validTrades.count lt $maxTradesToReturn">
                  <append_to_list name="$validTrades" exact="$cacheEntry"/>
                  <do_if value="$cacheWorkQuotaWare?">
                    <set_value name="$cacheWorkFoundPerWare.{$cacheWorkQuotaWare}" exact="if $cacheWorkFoundPerWare.{$cacheWorkQuotaWare}? then ($cacheWorkFoundPerWare.{$cacheWorkQuotaWare} + 1) else 1"/>
                  </do_if>
                  <set_value name="$entryScore" exact="if $cacheEntry.$Score? then $cacheEntry.$Score else (if $shipMaxProfit? then $shipMaxProfit else 0)"/>
                  <!-- Reset per-iteration to avoid carry-over from prior entries (otherwise $bestWasPriority stays true after a non-priority best). -->
                  <set_value name="$cacheIsPriority" exact="false"/>
                  <!-- Apply priority ware score multiplier LAST (same as lib.gt.mk42.score.trades) -->
                  <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0 and $cacheEntry.$Ware?">
                    <do_all exact="$effectivePriorityWares.count" counter="$pw">
                      <do_if value="$effectivePriorityWares.{$pw} == $cacheEntry.$Ware">
                        <set_value name="$cacheIsPriority" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                    <do_if value="$cacheIsPriority">
                      <set_value name="$cacheMult" exact="[1, if $effectivePriorityScoreMultiplier? then $effectivePriorityScoreMultiplier else 1].max"/>
                      <do_if value="$cacheMult gt 300"><set_value name="$cacheMult" exact="300"/></do_if>
                      <set_value name="$cacheBaseScore" exact="$entryScore"/>
                      <set_value name="$entryScore" exact="$entryScore * ($cacheMult / 100.0)"/>
                      <set_value name="$cachePriorityBoostCount" operation="add"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache priority: ware ' + (if $cacheEntry.$Ware? and $cacheEntry.$Ware != null then @$cacheEntry.$Ware.name else '?') + ' baseScore=' + $cacheBaseScore + ' -> boostedScore=' + $entryScore + ' (mult=' + $cacheMult + '%)'" chance="100"/>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_if value="$entryScore gt $bestScore">
                    <set_value name="$bestTrade" exact="$cacheEntry"/>
                    <set_value name="$bestScore" exact="$entryScore"/>
                    <set_value name="$bestWasPriority" exact="$cacheIsPriority"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <!-- Log rejection reason for first few rejected entries -->
                <do_if value="this.$processedCount + $i le 5 and $rejectReason != ''">
                  <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache entry ' + (this.$processedCount + $i) + ' REJECTED: ' + $rejectReason" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
          </do_if>
        </do_all>
        
        <!-- Early exit if we have enough trades -->
        <do_if value="$validTrades.count ge $maxTradesToReturn">
          <break/>
        </do_if>
        
        <set_value name="this.$processedCount" exact="$chunkEnd"/>
        
        <!-- BUG C5 FIX: Unconditional cooperative yield (wait must be top-level in AI scripts, not inside do_if) -->
        <wait exact="this.$gt_yieldMs * 1ms"/>
        <set_value name="$startTime" exact="player.age"/>
        
        <!-- Continue if more to process -->
        <do_if value="this.$processedCount lt $cacheList.count">
          <resume label="cache_work_loop"/>
        </do_if>
      </do_if>
      
      <!-- Signal completion -->
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache search complete: processed=' + this.$processedCount + '/' + $cacheList.count + ', validTrades=' + $validTrades.count + ', bestTrade=' + (if $bestTrade != null then 'found' else 'null') + ', bestScore=' + $bestScore" chance="100"/>
      
      <!-- Debug: summary when priority scoring was applied during cache search -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <do_if value="$effectivePriorityWares? and $effectivePriorityWares.count gt 0 and ($cachePriorityBoostCount gt 0 or $bestWasPriority)">
          <set_value name="$bestWareName" exact="if $bestTrade? and $bestTrade.$Ware? and $bestTrade.$Ware != null then @$bestTrade.$Ware.name else '?'"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cache priority summary: priorityBoosted=' + $cachePriorityBoostCount + ' entries, bestTrade ware=' + $bestWareName + ', bestWasPriority=' + $bestWasPriority" chance="100"/>
        </do_if>
      </do_if>
      
      <!-- Legacy work-unit completion removed by AI pipeline migration -->
      <!-- CRITICAL: Go to wait_for_response (NOT main_loop) so the AI is in a wait state
           when the MD sends GT_Trade_Found or GT_No_Trade_Found after processing the results.
           Previously resumed to main_loop, which ran synchronously and missed the delayed signal. -->
      <resume label="wait_for_response"/>
      
      <!-- Process live offers work unit -->
      <label name="process_live_offers_workunit"/>
      
      <!-- Extract parameters -->
      <set_value name="$homeSector" exact="@$workUnit.$HomeSector"/>
      <set_value name="$sectors" exact="@$workUnit.$Sectors"/>
      <set_value name="$wareBasket" exact="if $workUnit.$WareBasket? then $workUnit.$WareBasket else []"/>
      <set_value name="$allowIllegal" exact="if $workUnit.$AllowIllegal? then $workUnit.$AllowIllegal else false"/>
      <set_value name="$mk42PrioritiesLocal" exact="if this.$mk42Priorities? then this.$mk42Priorities else table[]"/>
      <set_value name="$ignoreMK1Supply" exact="if $workUnit.$IgnoreMK1Supply? then $workUnit.$IgnoreMK1Supply else (if $effectiveIgnoreMK1Supply? then @$effectiveIgnoreMK1Supply else true)"/>
      
      <!-- MK4 inline search must also include all reachable offers (no relative-price filtering). -->
      <set_value name="$inlineSellPriceMax" exact="1.0"/>
      <set_value name="$inlineBuyPriceMin" exact="-1.0"/>
      
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Inline PriceRange: SellPriceMax=' + $inlineSellPriceMax + ' BuyPriceMin=' + $inlineBuyPriceMin" chance="@this.$debugchance"/>
      
      <!-- Initialize work state -->
      <!-- Get chunk size from global settings (default: 3 sectors per chunk) -->
      <set_value name="$chunkSize" exact="3"/>
      <!-- Use LiveOfferSliceInterval to determine chunk size (convert ms to sectors) -->
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval?">
        <set_value name="$sliceInterval" exact="@global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval"/>
        <!-- Smaller interval = smaller chunks for smoother performance -->
        <do_if value="$sliceInterval? and $sliceInterval != null">
          <do_if value="$sliceInterval le 100">
            <set_value name="$chunkSize" exact="1"/>
          </do_if>
          <do_elseif value="$sliceInterval le 300">
            <set_value name="$chunkSize" exact="2"/>
          </do_elseif>
          <do_elseif value="$sliceInterval le 500">
            <set_value name="$chunkSize" exact="3"/>
          </do_elseif>
          <do_else>
            <set_value name="$chunkSize" exact="5"/>
          </do_else>
        </do_if>
      </do_if>
      
      <!-- Get max offers per ware from global settings (no fallback â€” missing value = init bug) -->
      <set_value name="$maxOffersPerWare" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
      
      <set_value name="$processedSectors" exact="0"/>
      <set_value name="$sellOffers" exact="[]"/>
      <set_value name="$buyOffers" exact="[]"/>
      
      <!-- Track offers per ware to enforce MaxOffersPerWare limit -->
      <set_value name="$sellOffersPerWare" exact="table[]"/>
      <set_value name="$buyOffersPerWare" exact="table[]"/>
      
      <!-- Process sectors in chunks with frame budgeting -->
      <label name="offers_work_loop"/>
      <set_value name="$startTime" exact="player.age"/>
      <set_value name="$chunkStart" exact="$processedSectors + 1"/>
      <set_value name="$chunkEnd" exact="[$processedSectors + $chunkSize, $sectors.count].min"/>
      
      <do_if value="$chunkStart le $sectors.count">
        <do_all exact="($chunkEnd - $chunkStart + 1)" counter="$i">
          <set_value name="$sectorIndex" exact="$chunkStart + $i - 1"/>
          <set_value name="$sector" exact="$sectors.{$sectorIndex}"/>
          
          <!-- Collect offers from sector -->
          <do_if value="$sector? and $sector.exists">
            <!-- Find sell offers (for buying) -->
            <find_sell_offer tradepartner="this.ship" space="$sector" result="$sectorSellOffers">
              <relativeprice max="$inlineSellPriceMax" tradepartner="if this.ship.isplayerowned then this.ship else null"/>
            </find_sell_offer>
            <do_if value="$sectorSellOffers?">
              <do_all exact="$sectorSellOffers.count" counter="$j">
                <set_value name="$offer" exact="$sectorSellOffers.{$j}"/>
                <set_value name="$isValid" exact="true"/>
                <run_script name="'lib.gt.mk42.offer.filters'" result="$offerFilterResult">
                  <param name="offer" value="$offer"/>
                  <param name="wareBasket" value="$wareBasket"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="ignoreMK1Supply" value="$ignoreMK1Supply"/>
                  <param name="isBuyOffer" value="false"/>
                </run_script>
                <set_value name="$isValid" exact="if $offerFilterResult? and $offerFilterResult.$Pass? then $offerFilterResult.$Pass else false"/>
                <do_if value="$isValid">
                  <!-- Limit offers per ware -->
                  <set_value name="$ware" exact="@$offer.ware"/>
                  <set_value name="$wareOfferCount" exact="if $sellOffersPerWare.{$ware}? then $sellOffersPerWare.{$ware} else 0"/>
                  <do_if value="$wareOfferCount lt $maxOffersPerWare">
                    <append_to_list name="$sellOffers" exact="$offer"/>
                    <set_value name="$sellOffersPerWare.{$ware}" exact="$wareOfferCount + 1"/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
            
            <!-- Find buy offers (for selling) -->
            <find_buy_offer tradepartner="this.ship" space="$sector" result="$sectorBuyOffers">
              <relativeprice min="$inlineBuyPriceMin" tradepartner="if this.ship.isplayerowned then this.ship else null"/>
            </find_buy_offer>
            <do_if value="$sectorBuyOffers?">
              <do_all exact="$sectorBuyOffers.count" counter="$j">
                <set_value name="$offer" exact="$sectorBuyOffers.{$j}"/>
                <set_value name="$isValid" exact="true"/>
                <run_script name="'lib.gt.mk42.offer.filters'" result="$offerFilterResult">
                  <param name="offer" value="$offer"/>
                  <param name="wareBasket" value="$wareBasket"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="ignoreMK1Supply" value="$ignoreMK1Supply"/>
                  <param name="priorities" value="$mk42PrioritiesLocal"/>
                  <param name="isBuyOffer" value="true"/>
                </run_script>
                <set_value name="$isValid" exact="if $offerFilterResult? and $offerFilterResult.$Pass? then $offerFilterResult.$Pass else false"/>
                <do_if value="$isValid">
                  <!-- Limit offers per ware -->
                  <set_value name="$ware" exact="@$offer.ware"/>
                  <set_value name="$wareOfferCount" exact="if $buyOffersPerWare.{$ware}? then $buyOffersPerWare.{$ware} else 0"/>
                  <do_if value="$wareOfferCount lt $maxOffersPerWare">
                    <append_to_list name="$buyOffers" exact="$offer"/>
                    <set_value name="$buyOffersPerWare.{$ware}" exact="$wareOfferCount + 1"/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
        </do_all>
        
        <set_value name="$processedSectors" exact="$chunkEnd"/>
        
        <!-- BUG C5 FIX: Unconditional cooperative yield (wait must be top-level in AI scripts, not inside do_if) -->
        <wait exact="this.$gt_yieldMs * 1ms"/>
        <set_value name="$startTime" exact="player.age"/>
        
        <!-- Continue if more to process -->
        <do_if value="$processedSectors lt $sectors.count">
          <resume label="offers_work_loop"/>
        </do_if>
      </do_if>
      
      <!-- Legacy MD filter roundtrip removed by AI pipeline migration -->
      <set_value name="$filteredResult" exact="table[$SellOffers = $sellOffers, $BuyOffers = $buyOffers]"/>
      <!-- Legacy work-unit completion removed by AI pipeline migration -->
      <!-- CRITICAL: Go to wait_for_response so AI catches MD's GT_Trade_Found/GT_No_Trade_Found -->
      <resume label="wait_for_response"/>
      
      <!-- Process trade matching work unit -->
      <label name="process_trade_matching_workunit"/>
      
      <!-- Extract parameters -->
      <set_value name="$sellOffers" exact="@$workUnit.$SellOffers"/>
      <set_value name="$buyOffers" exact="@$workUnit.$BuyOffers"/>
      <set_value name="$homeSector" exact="@$workUnit.$HomeSector"/>
      <set_value name="$minROI" exact="0"/>
      <set_value name="$minAbsoluteProfit" exact="0"/>
      <set_value name="$distancePenaltyMultiplier" exact="if $workUnit.$DistancePenaltyMultiplier? then $workUnit.$DistancePenaltyMultiplier else 0.5"/>
      
      <!-- Resolve priority wares + multiplier ONCE per workunit so the per-pair scoring below can apply
           the same boost the cache_work_loop already applies. Without this, fleets with priority wares
           configured got priority ordering on cache hits but distance-optimized / priority-blind ordering
           when the live/matching pipeline produced the trade (see DOCS/MK3_PIPELINE_REFACTOR.md Â§3.10). -->
      <run_script name="'lib.gt.priority_wares.resolve'" result="$matchPriorityWares">
        <param name="instanceWares" value="if this.$effectivePriorityWares? then this.$effectivePriorityWares else null"/>
        <param name="ship" value="this.ship"/>
        <param name="validOrderIds" value="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply2']"/>
      </run_script>
      <set_value name="$matchPriorityMult" exact="if this.$effectivePriorityScoreMultiplier? then [1, this.$effectivePriorityScoreMultiplier].max else 1"/>
      <do_if value="$matchPriorityMult gt 300"><set_value name="$matchPriorityMult" exact="300"/></do_if>
      <set_value name="$matchPriorityBoostCount" exact="0"/>
      
      <!-- Initialize work state -->
      <!-- Get chunk size from global settings (default: 10 trade pairs per chunk) -->
      <set_value name="$chunkSize" exact="10"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$BatchChunkSize?">
        <set_value name="$tmpChunk" exact="@global.$GT_GlobalSettings.$Performance.$BatchChunkSize"/>
        <do_if value="$tmpChunk? and $tmpChunk != null and $tmpChunk gt 0">
          <!-- BatchChunkSize is for offers, scale for trade pairs (roughly square) -->
          <set_value name="$chunkSize" exact="$tmpChunk * 2"/>
        </do_if>
      </do_if>
      <!-- Clamp to reasonable bounds -->
      <do_if value="$chunkSize lt 5">
        <set_value name="$chunkSize" exact="5"/>
      </do_if>
      <do_if value="$chunkSize gt 50">
        <set_value name="$chunkSize" exact="50"/>
      </do_if>
      
      <!-- Get max trades per ware from global settings -->
      <set_value name="$maxTradesPerWare" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
        <set_value name="$tmpMax" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
        <do_if value="$tmpMax? and $tmpMax != null and $tmpMax gt 0">
          <set_value name="$maxTradesPerWare" exact="$tmpMax"/>
        </do_if>
      </do_if>
      
      <!-- Get early exit threshold from global settings -->
      <set_value name="$earlyExitThreshold" exact="2000"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold?">
        <set_value name="$tmpThreshold" exact="@global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold"/>
        <do_if value="$tmpThreshold? and $tmpThreshold != null and $tmpThreshold gt 0">
          <set_value name="$earlyExitThreshold" exact="$tmpThreshold"/>
        </do_if>
      </do_if>
      
      <set_value name="$processedPairs" exact="0"/>
      <set_value name="$validTrades" exact="[]"/>
      <set_value name="$bestTrade" exact="null"/>
      <set_value name="$bestScore" exact="0"/>
      
      <!-- Initialize rejection counters for logging -->
      <set_value name="$profitRejectionCount" exact="0"/>
      <set_value name="$roiRejectionCount" exact="0"/>
      
      <!-- Get max offers per ware for matching from global settings -->
      <set_value name="$maxOffersPerWareForMatching" exact="20"/>
      <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching?">
        <set_value name="$tmpMaxOffers" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching"/>
        <do_if value="$tmpMaxOffers? and $tmpMaxOffers != null and $tmpMaxOffers gt 0">
          <set_value name="$maxOffersPerWareForMatching" exact="$tmpMaxOffers"/>
        </do_if>
      </do_if>
      
      <!-- Track trades per ware for limiting -->
      <set_value name="$tradesPerWare" exact="table[]"/>
      
      <!-- Index offers by ware (simplified - no MD library call) -->
      <!-- Limit offers per ware using MaxOffersPerWareForMatching -->
      <!-- FIX: Validate offers are available before indexing (prevents NULL owner/price issues) -->
      <set_value name="$sellOffersByWare" exact="table[]"/>
      <do_all exact="$sellOffers.count" counter="$i">
        <set_value name="$offer" exact="$sellOffers.{$i}"/>
        <!-- Validate offer exists and is available before indexing -->
        <do_if value="$offer? and $offer.available">
          <set_value name="$ware" exact="@$offer.ware"/>
          <do_if value="$ware?">
            <do_if value="not $sellOffersByWare.{$ware}?">
              <set_value name="$sellOffersByWare.{$ware}" exact="[]"/>
            </do_if>
            <!-- Limit offers per ware -->
            <do_if value="$sellOffersByWare.{$ware}.count lt $maxOffersPerWareForMatching">
              <append_to_list name="$sellOffersByWare.{$ware}" exact="$offer"/>
            </do_if>
          </do_if>
        </do_if>
      </do_all>
      
      <set_value name="$buyOffersByWare" exact="table[]"/>
      <do_all exact="$buyOffers.count" counter="$i">
        <set_value name="$offer" exact="$buyOffers.{$i}"/>
        <!-- Validate offer exists and is available before indexing -->
        <do_if value="$offer? and $offer.available">
          <set_value name="$ware" exact="@$offer.ware"/>
          <do_if value="$ware?">
            <do_if value="not $buyOffersByWare.{$ware}?">
              <set_value name="$buyOffersByWare.{$ware}" exact="[]"/>
            </do_if>
            <!-- Limit offers per ware -->
            <do_if value="$buyOffersByWare.{$ware}.count lt $maxOffersPerWareForMatching">
              <append_to_list name="$buyOffersByWare.{$ware}" exact="$offer"/>
            </do_if>
          </do_if>
        </do_if>
      </do_all>
      
      <!-- OPTIMIZATION: Lazy pair generation - generate pairs on-demand instead of upfront -->
      <!-- Get list of wares that have both sell and buy offers -->
      <set_value name="$wareKeys" exact="[]"/>
      <do_all exact="$sellOffersByWare.keys.count" counter="$i">
        <set_value name="$ware" exact="$sellOffersByWare.keys.{$i}"/>
        <do_if value="$buyOffersByWare.{$ware}? and $buyOffersByWare.{$ware}.count gt 0">
          <append_to_list name="$wareKeys" exact="$ware"/>
        </do_if>
      </do_all>
      
      <!-- Initialize lazy generation state -->
      <set_value name="this.$currentWareIndex" exact="0"/>
      <set_value name="this.$currentSellIndex" exact="0"/>
      <set_value name="this.$currentBuyIndex" exact="0"/>
      
      <!-- Process trade pairs in chunks with frame budgeting (lazy generation) -->
      <label name="matching_work_loop"/>
      <set_value name="$startTime" exact="player.age"/>
      <set_value name="$pairsProcessedThisChunk" exact="0"/>
      
      <!-- Generate and process pairs on-demand -->
      <do_if value="$wareKeys.count gt 0">
        <do_while value="$pairsProcessedThisChunk lt $chunkSize and (this.$currentWareIndex lt $wareKeys.count)">
        <!-- Check early exit threshold -->
        <do_if value="$validTrades.count ge $earlyExitThreshold">
          <break/>
        </do_if>
        
        <!-- Get current ware with safe access -->
        <set_value name="$ware" exact="@$wareKeys.{this.$currentWareIndex}"/>
        <do_if value="not $ware?">
          <!-- Invalid ware index, skip to next -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
          <continue/>
        </do_if>
        
        <!-- Validate lists exist and have items before accessing -->
        <set_value name="$listsValid" exact="false"/>
        <do_if value="$sellOffersByWare.{$ware}?">
          <do_if value="$buyOffersByWare.{$ware}?">
            <set_value name="$sellList" exact="$sellOffersByWare.{$ware}"/>
            <set_value name="$buyList" exact="$buyOffersByWare.{$ware}"/>
            <do_if value="$sellList.count gt 0">
              <do_if value="$buyList.count gt 0">
                <set_value name="$listsValid" exact="true"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        
        <do_if value="not $listsValid">
          <!-- Invalid lists, skip to next ware -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
          <continue/>
        </do_if>
        
        <!-- At this point, $sellList and $buyList are guaranteed to be set and valid -->
        
        <!-- Check if current ware is complete (reached MaxTradesPerWare limit) -->
        <set_value name="$wareTradeCount" exact="if $tradesPerWare.{$ware}? then $tradesPerWare.{$ware} else 0"/>
        <do_if value="$wareTradeCount ge $maxTradesPerWare">
          <!-- OPTIMIZATION: Early termination per ware - skip to next ware immediately -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
          <continue/>
        </do_if>
        
        <!-- Generate next pair on-demand -->
        <do_if value="$listsValid and this.$currentSellIndex lt $sellList.count and this.$currentBuyIndex lt $buyList.count">
          <set_value name="$sellOffer" exact="@$sellList.{this.$currentSellIndex}"/>
          <set_value name="$buyOffer" exact="@$buyList.{this.$currentBuyIndex}"/>
          
          <!-- Validate offers exist AND are available (prevents NULL owner/price issues) -->
          <!-- FIX: Check offer.available - offers can exist but not be available, causing NULL owner/price -->
          <do_if value="$sellOffer? and $buyOffer? and $sellOffer.available and $buyOffer.available">
            <!-- OPTIMIZATION: Quick profit pre-filtering before full evaluation -->
            <!-- FIX: Use unitprice (price per unit) instead of price (total price) - price is total for entire offer amount -->
            <set_value name="$buyPrice" exact="@$sellOffer.unitprice"/>
            <set_value name="$sellPrice" exact="@$buyOffer.unitprice"/>
            <set_value name="$profitPerUnit" exact="$sellPrice - $buyPrice"/>
            <set_value name="$amount" exact="[@$sellOffer.amount, @$buyOffer.amount].min"/>
            <set_value name="$quickProfit" exact="$profitPerUnit * $amount"/>
            
            <!-- Increment processed pairs counter -->
            <set_value name="$processedPairs" exact="$processedPairs + 1"/>
            
            <!-- Quick profit check - skip if can't meet minimum -->
            <do_if value="$quickProfit ge $minAbsoluteProfit">
              <!-- Full evaluation -->
              <!-- Calculate ROI -->
              <set_value name="$investment" exact="$buyPrice * $amount"/>
              <set_value name="$roi" exact="if $investment gt 0 then (($quickProfit * 100) / $investment) else 0"/>
              
              <do_if value="$roi ge $minROI">
                <!-- Simplified distance calculation (use sector distance if available) -->
                <set_value name="$buyDistance" exact="0"/>
                <set_value name="$sellDistance" exact="0"/>
                <do_if value="$sellOffer.owner? and $sellOffer.owner.sector? and $homeSector?">
                  <set_value name="$buySector" exact="$sellOffer.owner.sector"/>
                  <do_if value="$buySector != $homeSector">
                    <set_value name="$buyDistance" exact="1"/> <!-- Simplified - assume 1 jump if different sector -->
                  </do_if>
                </do_if>
                <do_if value="$buyOffer.owner? and $buyOffer.owner.sector? and $homeSector?">
                  <set_value name="$sellSector" exact="$buyOffer.owner.sector"/>
                  <do_if value="$sellSector != $homeSector">
                    <set_value name="$sellDistance" exact="1"/> <!-- Simplified - assume 1 jump if different sector -->
                  </do_if>
                </do_if>
                
                <set_value name="$totalDistance" exact="$buyDistance + $sellDistance"/>
                <set_value name="$distancePenalty" exact="$totalDistance * $distancePenaltyMultiplier * 100"/> <!-- Scale penalty -->
                <set_value name="$baseScore" exact="$quickProfit - $distancePenalty"/>
                <!-- Priority-ware boost: mirrors cache_work_loop so cache vs matching pipelines order trades
                     consistently when the user has priority wares configured (see Â§3.10). -->
                <set_value name="$matchIsPriority" exact="false"/>
                <do_if value="$matchPriorityWares? and $matchPriorityWares.count gt 0 and $ware? and $matchPriorityWares.indexof.{$ware}">
                  <set_value name="$matchIsPriority" exact="true"/>
                </do_if>
                <do_if value="$matchIsPriority">
                  <set_value name="$score" exact="$baseScore * ($matchPriorityMult / 100.0)"/>
                  <set_value name="$matchPriorityBoostCount" exact="$matchPriorityBoostCount + 1"/>
                </do_if>
                <do_else>
                  <set_value name="$score" exact="$baseScore"/>
                </do_else>
                
                <!-- Check trades per ware limit -->
                <do_if value="$wareTradeCount lt $maxTradesPerWare">
                  <!-- Create trade entry -->
                  <!-- FIX: Store BuyPrice and SellPrice in trade object for profit recalculation -->
                  <set_value name="$trade" exact="table[
                    $BuyOffer = $sellOffer,
                    $SellOffer = $buyOffer,
                    $BuyPrice = $buyPrice,
                    $SellPrice = $sellPrice,
                    $Profit = $quickProfit,
                    $ROI = $roi,
                    $Amount = $amount,
                    $Score = $score,
                    $Distance = $totalDistance,
                    $IsPriority = $matchIsPriority,
                    $Ware = $ware
                  ]"/>
                  
                  <append_to_list name="$validTrades" exact="$trade"/>
                  <set_value name="$tradesPerWare.{$ware}" exact="$wareTradeCount + 1"/>
                  
                  <!-- Track best trade -->
                  <do_if value="$score gt $bestScore">
                    <set_value name="$bestTrade" exact="$trade"/>
                    <set_value name="$bestScore" exact="$score"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <!-- ROI check failed - log first few rejections -->
                <set_value name="$roiRejectionCount" exact="$roiRejectionCount + 1"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $roiRejectionCount le 10">
                  <set_value name="$wareName" exact="if $ware? then @$ware.name else 'NULL'"/>
                  <set_value name="$buyStationName" exact="if $sellOffer.owner? then @$sellOffer.owner.knownname else 'NULL'"/>
                  <set_value name="$sellStationName" exact="if $buyOffer.owner? then @$buyOffer.owner.knownname else 'NULL'"/>
                  <debug_text text="'[GT-AI-TradeMatching] ' + this.ship.idcode + ': Pair REJECTED (ROI): #' + $roiRejectionCount +
                    '\n  Ware: ' + $wareName +
                    '\n  Buy: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr' +
                    '\n  Sell: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr' +
                    '\n  ProfitPerUnit: ' + ($profitPerUnit/100) + ' Cr' +
                    '\n  Amount: ' + $amount + ' units' +
                    '\n  QuickProfit: ' + ($quickProfit/100) + ' Cr' +
                    '\n  Investment: ' + ($investment/100) + ' Cr' +
                    '\n  ROI: ' + $roi + '%' +
                    '\n  MinROI: ' + $minROI + '%'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <!-- Quick profit check failed - log first few rejections -->
              <set_value name="$profitRejectionCount" exact="$profitRejectionCount + 1"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $profitRejectionCount le 10">
                <set_value name="$wareName" exact="if $ware? then @$ware.name else 'NULL'"/>
                <set_value name="$buyStationName" exact="if $sellOffer.owner? then @$sellOffer.owner.knownname else 'NULL'"/>
                <set_value name="$sellStationName" exact="if $buyOffer.owner? then @$buyOffer.owner.knownname else 'NULL'"/>
                <debug_text text="'[GT-AI-TradeMatching] ' + this.ship.idcode + ': Pair REJECTED (profit): #' + $profitRejectionCount +
                  '\n  Ware: ' + $wareName +
                  '\n  Buy: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr' +
                  '\n  Sell: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr' +
                  '\n  ProfitPerUnit: ' + ($profitPerUnit/100) + ' Cr' +
                  '\n  Amount: ' + $amount + ' units' +
                  '\n  QuickProfit: ' + ($quickProfit/100) + ' Cr' +
                  '\n  MinProfit: ' + ($minAbsoluteProfit/100) + ' Cr'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          
          <!-- Advance to next pair -->
          <set_value name="this.$currentBuyIndex" exact="this.$currentBuyIndex + 1"/>
          <do_if value="this.$currentBuyIndex ge $buyList.count">
            <set_value name="this.$currentBuyIndex" exact="0"/>
            <set_value name="this.$currentSellIndex" exact="this.$currentSellIndex + 1"/>
            <do_if value="this.$currentSellIndex ge $sellList.count">
              <!-- Move to next ware -->
              <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
              <set_value name="this.$currentSellIndex" exact="0"/>
              <set_value name="this.$currentBuyIndex" exact="0"/>
            </do_if>
          </do_if>
          
          <set_value name="$pairsProcessedThisChunk" exact="$pairsProcessedThisChunk + 1"/>
        </do_if>
        <do_else>
          <!-- Current ware exhausted, move to next -->
          <set_value name="this.$currentWareIndex" exact="this.$currentWareIndex + 1"/>
          <set_value name="this.$currentSellIndex" exact="0"/>
          <set_value name="this.$currentBuyIndex" exact="0"/>
        </do_else>
        </do_while>
      </do_if>
      
      <!-- BUG C5 FIX: Unconditional cooperative yield (wait must be top-level in AI scripts, not inside do_if) -->
      <wait exact="this.$gt_yieldMs * 1ms"/>
      <set_value name="$startTime" exact="player.age"/>
      
      <!-- Continue if more to process -->
      <do_if value="this.$currentWareIndex lt $wareKeys.count">
        <resume label="matching_work_loop"/>
      </do_if>
      
      <!-- Signal completion -->
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI-TradeMatching] ' + this.ship.idcode + ': Trade matching complete:' +
          '\n  ProcessedPairs: ' + $processedPairs +
          '\n  ValidTrades: ' + $validTrades.count +
          '\n  BestTrade: ' + (if $bestTrade != null then 'found' else 'null') +
          '\n  BestScore: ' + $bestScore +
          '\n  WareKeys: ' + $wareKeys.count +
          '\n  PriorityBoosts: ' + $matchPriorityBoostCount + ' (mult=' + $matchPriorityMult + '%, sources=' + (if $matchPriorityWares? then $matchPriorityWares.count else 0) + ')' +
          '\n  Rejected (profit): ' + $profitRejectionCount +
          '\n  Rejected (ROI): ' + $roiRejectionCount" chance="100"/>
      </do_if>
      <!-- Legacy work-unit completion removed by AI pipeline migration -->
      <!-- CRITICAL: Go to wait_for_response so AI catches MD's GT_Trade_Found/GT_No_Trade_Found -->
      <resume label="wait_for_response"/>
      
    </actions>
  </attention>
  
  <on_abort>
    <!-- Intentional handoff: idle parking delegates to GTIdlePark for visible queued docking. -->
    <set_value name="$isIdleParkHandoff" exact="false"/>
    <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{this.ship}?">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.order? and @this.ship.order.id == 'DockAndWait' and this.ship.order.$callerid? and @this.ship.order.$callerid.id == 'GTIdlePark'">
      <set_value name="$isIdleParkHandoff" exact="true"/>
    </do_if>
    <do_if value="not $isIdleParkHandoff and this.ship.orders.count gt 0">
      <do_all exact="this.ship.orders.count" counter="$ipoi">
        <set_value name="$ipOrder" exact="this.ship.orders.{$ipoi}"/>
        <do_if value="@$ipOrder.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_if>
        <do_elseif value="@$ipOrder.id == 'DockAndWait' and $ipOrder.$callerid? and @$ipOrder.$callerid.id == 'GTIdlePark'">
          <set_value name="$isIdleParkHandoff" exact="true"/>
          <break/>
        </do_elseif>
      </do_all>
    </do_if>
    <do_if value="$isIdleParkHandoff">
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': on_abort skipped (handoff to GTIdlePark)'" chance="100"/>
      </do_if>
      <return/>
    </do_if>

    <!-- Release new scheduler semaphore slot if this ship aborts mid-search -->
    <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]"/>

    <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}.$ActiveTradePolicy?">
      <remove_value name="global.$GT_Ships.{this.ship}.$ActiveTradePolicy"/>
    </do_if>

    <!-- Release fleet reservation if ship aborts with an active reservation.
         Restored from pre-migration reservation flow: prevents stale reservations blocking fleet. -->
    <do_if value="this.$activeReservationKey? and global.$GT_Reservations? and global.$GT_Reservations.{this.$activeReservationKey}?">
      <remove_value name="global.$GT_Reservations.{this.$activeReservationKey}"/>
      <do_if value="global.$GT_ReservationStats? and global.$GT_ReservationStats.$Active gt 0">
        <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
      </do_if>
      <do_if value="global.$GT_ReservationStats?">
        <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
      </do_if>
    </do_if>

    <!-- Clear stale clearance naming flag on order abort only when cargo is actually empty.
         Keep [CLEARANCE]/CL during active disposal with remaining cargo. -->
    <do_if value="this.ship.cargo.count == 0 and global.$GT_Ships? and global.$GT_Ships.{this.ship}? and global.$GT_Ships.{this.ship}.$CargoDisposal?">
      <remove_value name="global.$GT_Ships.{this.ship}.$CargoDisposal"/>
      <do_if value="@this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
          $Ship = this.ship,
          $pilot = this.ship.pilot,
          $xp = global.$GT_Pilots.{this.ship.pilot}.$XP,
          $level = global.$GT_Pilots.{this.ship.pilot}.$Level,
          $rank = @global.$GT_Pilots.{this.ship.pilot}.$CurrentRank,
          $nameType = 'trader'
        ]"/>
      </do_if>
    </do_if>

    <!-- Enhanced cleanup when order is aborted/replaced -->
    <!-- Preserve pilot XP data when order is manually replaced by player -->
    <!-- Only completely wipe data in genuine cleanup scenarios (ship destroyed, pilot changed, etc.) -->
    <set_value name="$isActivelyTrading" exact="false"/>
    <set_value name="$isTrainingTransition" exact="false"/>
    
    <!-- Clean up resupply tracking if order aborted mid-resupply -->
    <!-- IMPORTANT: Do NOT clear during maintenance transitions (subordinates can be aborted/replaced while resupply order is active) -->
    <do_if value="not this.$maintenance_transition? and global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{this.ship}?">
      <remove_value name="global.$GT_ResupplyOrders.{this.ship}"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Cleaned up resupply tracking on order abort'" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Check if ship has active TradePerform orders -->
    <do_if value="this.ship.orders.count gt 1">
      <do_all exact="this.ship.orders.count" counter="$i">
        <do_if value="this.ship.orders.{$i}.id == 'TradePerform'">
          <set_value name="$isActivelyTrading" exact="true"/>
          <break/>
        </do_if>
      </do_all>
    </do_if>
    
    <!-- Check if a training order was recently created (within last 5 seconds) -->
    <do_if value="this.$training_order_created? and (player.age - this.$training_order_created) lt 5s">
      <set_value name="$isTrainingTransition" exact="true"/>
    </do_if>
    
    <!-- Also check the flag-based detection -->
    <do_if value="this.$training_transition?">
      <set_value name="$isTrainingTransition" exact="true"/>
    </do_if>
    
    <!-- Check if a maintenance order was recently created (repair/resupply) -->
    <set_value name="$isMaintenanceTransition" exact="false"/>
    <do_if value="this.$maintenance_transition?">
      <set_value name="$isMaintenanceTransition" exact="true"/>
    </do_if>
    
    <!-- Ship state and orders at removal detection -->
    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
      <set_value name="$debugShip" exact="this.ship"/>
      <set_value name="$debugDefaultOrder" exact="@$debugShip.defaultorder.id"/>
      <set_value name="$debugCommander" exact="@$debugShip.commander"/>
      <set_value name="$debugCommanderId" exact="if @$debugCommander.exists then @$debugCommander.idcode else 'NONE'"/>
      <set_value name="$debugCommanderOrder" exact="if @$debugCommander.exists and @$debugCommander.defaultorder != null then @$debugCommander.defaultorder.id else 'NONE'"/>
      <set_value name="$debugPilot" exact="@$debugShip.pilot"/>
      <set_value name="$debugPilotName" exact="if $debugPilot != null then @$debugPilot.knownname else 'NONE'"/>
      
      <!-- Build orders list -->
      <set_value name="$debugOrdersList" exact="[]"/>
      <set_value name="$debugOrdersCount" exact="$debugShip.orders.count"/>
      <do_all exact="$debugOrdersCount" counter="$i">
        <set_value name="$orderId" exact="@$debugShip.orders.{$i}.id"/>
        <append_to_list name="$debugOrdersList" exact="if $orderId then $orderId else 'UNKNOWN'"/>
      </do_all>
      <set_value name="$debugOrdersStr" exact="if $debugOrdersList.count gt 0 then $debugOrdersList.{1} + (if $debugOrdersList.count gt 1 then ', ' + $debugOrdersList.{2} else '') + (if $debugOrdersList.count gt 2 then ', ' + $debugOrdersList.{3} else '') + (if $debugOrdersList.count gt 3 then ', ' + $debugOrdersList.{4} else '') + (if $debugOrdersList.count gt 4 then ', ...' else '') else 'NONE'"/>
      
      <!-- Check GT order status -->
      <set_value name="$debugHasDirectGT" exact="false"/>
      <do_if value="$debugDefaultOrder == 'GalaxyTraderMK3' or $debugDefaultOrder == 'GalaxyTraderMK4Supply2'">
        <set_value name="$debugHasDirectGT" exact="true"/>
      </do_if>
      <set_value name="$debugHasGTCommander" exact="false"/>
      <do_if value="@$debugCommander.exists and ($debugCommanderOrder == 'GalaxyTraderMK3' or $debugCommanderOrder == 'GalaxyTraderMK4Supply2')">
        <set_value name="$debugHasGTCommander" exact="true"/>
      </do_if>
      
      <!-- Check if in GT_Ships registry -->
      <set_value name="$debugInRegistry" exact="global.$GT_Ships? and global.$GT_Ships.{$debugShip}?"/>
      
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT-AI] REMOVAL DETECTION DEBUG: ' + $debugShip.idcode + ' - COMPREHENSIVE STATE'" chance="100"/>
        <debug_text text="'[GT-AI]   Ship: ' + $debugShip.idcode + ' (' + (if $debugShip.knownname then $debugShip.knownname else 'UNNAMED') + ')'" chance="100"/>
        <debug_text text="'[GT-AI]   Pilot: ' + $debugPilotName + (if $debugPilot != null then ' (exists)' else ' (NONE)')" chance="100"/>
        <debug_text text="'[GT-AI]   Default Order: ' + (if $debugDefaultOrder then $debugDefaultOrder else 'NONE')" chance="100"/>
        <debug_text text="'[GT-AI]   Active Orders (' + $debugOrdersCount + '): ' + $debugOrdersStr" chance="100"/>
        <debug_text text="'[GT-AI]   Commander: ' + $debugCommanderId + ' (Order: ' + $debugCommanderOrder + ')'" chance="100"/>
        <debug_text text="'[GT-AI]   GT Status: Direct=' + $debugHasDirectGT + ', ViaCommander=' + $debugHasGTCommander + ', InRegistry=' + $debugInRegistry" chance="100"/>
        <debug_text text="'[GT-AI]   Flags: ActivelyTrading=' + $isActivelyTrading + ', TrainingTransition=' + $isTrainingTransition + ', MaintenanceTransition=' + $isMaintenanceTransition" chance="100"/>
      </do_if>
    </do_if>
    
    <!-- Order cancellation detection -->
    <!-- Only send signal if GT default order is actually cancelled -->
    <!-- on_abort can fire when trade orders are cancelled, but GT order might still be active -->
    <!-- Unified GT order status check (inline for AI scripts) -->
    <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
    <set_value name="$hasDirectGTOrder" exact="false"/>
    <set_value name="$hasGTCommander" exact="false"/>
    <set_value name="$isGTControlled" exact="false"/>
    
    <!-- Check direct GT order -->
    <do_if value="$currentDefaultOrder == 'GalaxyTraderMK3' or $currentDefaultOrder == 'GalaxyTraderMK4Supply2'">
      <set_value name="$hasDirectGTOrder" exact="true"/>
      <set_value name="$isGTControlled" exact="true"/>
    </do_if>
    
    <!-- Check commander status -->
    <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
      <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
        <set_value name="$hasGTCommander" exact="true"/>
        <do_if value="$currentDefaultOrder == 'Assist'">
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
      </do_if>
    </do_if>
    
    <set_value name="$isGTOrderCancelled" exact="false"/>
    
    <!-- If GT order is gone, process cleanup REGARDLESS of training/maintenance transitions -->
    <!-- Only skip Phase 7 if GT order is STILL ACTIVE AND there's a training/maintenance transition -->
    <do_if value="not $isGTControlled and $currentDefaultOrder != 'Assist'">
      <!-- GT order is gone - process cleanup even if training/maintenance/disposal orders exist -->
      <!-- Check if GT default order is still active -->
      <!-- If defaultorder.id is null, different, or not GalaxyTraderMK3/GalaxyTraderMK4Supply2, GT order was cancelled -->
      <do_if value="not $currentDefaultOrder">
        <!-- No default order â†’ GT order was cancelled -->
        <set_value name="$isGTOrderCancelled" exact="true"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: NONE)'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'GT_Order_Cancelled'
        ]"/>
        
        <!-- EVENT-DRIVEN: Trigger orphaned ship check -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
          <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = this.ship]"/>
        </do_if>
        
        <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
        <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
        <!-- Use this.$was_subordinate flag or check state manager state -->
        <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
        <do_if value="this.$was_subordinate?">
          <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
          <!-- Check state manager to see if ship was a subordinate -->
          <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship is CURRENTLY subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$isSubordinateOfGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Restore name if:
             1. Ship was NOT a subordinate before cancellation, OR
             2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
        <set_value name="$shouldRestoreName" exact="false"/>
        <do_if value="not $wasSubordinateBeforeCancellation">
          <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
          <do_if value="not $isSubordinateOfGTCommander">
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
          <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_elseif>
        
        <do_if value="$shouldRestoreName and this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'GT order cancelled - restoring original name',
              $OriginalName = $originalName
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="$currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply2'">
        <!-- Different default order â†’ Check if GT order was actually cancelled -->
        <!-- For subordinates with Assist order, trade order termination is NORMAL -->
        <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
        <set_value name="$actualDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <!-- Check if ship has direct GT order -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <do_if value="$actualDefaultOrder == 'GalaxyTraderMK3' or $actualDefaultOrder == 'GalaxyTraderMK4Supply2'">
          <set_value name="$hasDirectGTOrder" exact="true"/>
        </do_if>
        
        <!-- Check if ship is subordinate to GT commander (current commander, not old) -->
        <set_value name="$hasGTCommander" exact="false"/>
        <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$hasGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
        <!-- For subordinates, Assist order termination is handled by Assist order's on_abort -->
        <!-- Trade order termination is NORMAL and should NOT trigger cleanup -->
        <set_value name="$shouldEmitCleanup" exact="false"/>
        <do_if value="not $hasDirectGTOrder and not $hasGTCommander and $currentDefaultOrder != 'Assist'">
          <!-- No direct GT order and no GT commander = GT order truly gone -->
          <set_value name="$shouldEmitCleanup" exact="true"/>
        </do_if>
        
        <!-- Emit cleanup signal if GT order is gone -->
        <do_if value="$shouldEmitCleanup">
          <set_value name="$isGTOrderCancelled" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ')'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI]  PHASE 7: Trade order aborted but GT order still active for ' + this.ship.idcode + ' (default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ') - NOT sending GT_Order_Cancelled'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
        <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
        <!-- Use this.$was_subordinate flag or check state manager state -->
        <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
        <do_if value="this.$was_subordinate?">
          <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
          <!-- Check state manager to see if ship was a subordinate -->
          <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Check if ship is CURRENTLY subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
          <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
            <set_value name="$isSubordinateOfGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Restore name if:
             1. Ship was NOT a subordinate before cancellation, OR
             2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
        <set_value name="$shouldRestoreName" exact="false"/>
        <do_if value="not $wasSubordinateBeforeCancellation">
          <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
          <do_if value="not $isSubordinateOfGTCommander">
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
          <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_elseif>
        
        <do_if value="$shouldRestoreName and this.ship.pilot?">
          <set_value name="$originalName" exact="null"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
          </do_if>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = this.ship,
              $Pilot = this.ship.pilot,
              $Reason = 'GT order cancelled - restoring original name',
              $OriginalName = $originalName
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </do_elseif>
    </do_if>
    <do_elseif value="$hasDirectGTOrder or $hasGTCommander">
      <!-- GT order still active - only skip Phase 7 if there's a training/maintenance transition -->
      <!-- This prevents cleanup when GT order creates training/maintenance orders (normal behavior) -->
      <do_if value="not $isTrainingTransition and not $isMaintenanceTransition">
        <!-- GT order active, no transitions - check if default order changed -->
        <!-- (This is the original Phase 7 logic for when GT order is still active) -->
        <!-- Check if GT default order is still active -->
        <!-- If defaultorder.id is null, different, or not GalaxyTraderMK3/GalaxyTraderMK4Supply2, GT order was cancelled -->
        <do_if value="not $currentDefaultOrder">
          <!-- No default order â†’ GT order was cancelled -->
          <set_value name="$isGTOrderCancelled" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: NONE)'" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
            $Ship = this.ship,
            $UpdateType = 'GT_Order_Cancelled'
          ]"/>
          
          <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
          <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
          <!-- Use this.$was_subordinate flag or check state manager state -->
          <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
          <do_if value="this.$was_subordinate?">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
            <!-- Check state manager to see if ship was a subordinate -->
            <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
            <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
              <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
            </do_if>
          </do_elseif>
          
          <!-- Check if ship is CURRENTLY subordinate to GT commander -->
          <set_value name="$isSubordinateOfGTCommander" exact="false"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
              <set_value name="$isSubordinateOfGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Restore name if:
               1. Ship was NOT a subordinate before cancellation, OR
               2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
          <set_value name="$shouldRestoreName" exact="false"/>
          <do_if value="not $wasSubordinateBeforeCancellation">
            <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
            <do_if value="not $isSubordinateOfGTCommander">
              <set_value name="$shouldRestoreName" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
            <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_elseif>
          
          <do_if value="$shouldRestoreName and this.ship.pilot?">
            <set_value name="$originalName" exact="null"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
            </do_if>
            
            <do_if value="$originalName">
              <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $Reason = 'GT order cancelled - restoring original name',
                $OriginalName = $originalName
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply2'">
          <!-- Different default order â†’ Check if GT order was actually cancelled -->
          <!-- For subordinates with Assist order, trade order termination is NORMAL -->
          <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
          <set_value name="$actualDefaultOrder" exact="@this.ship.defaultorder.id"/>
          
          <!-- Check if ship has direct GT order -->
          <set_value name="$hasDirectGTOrder" exact="false"/>
          <do_if value="$actualDefaultOrder == 'GalaxyTraderMK3' or $actualDefaultOrder == 'GalaxyTraderMK4Supply2'">
            <set_value name="$hasDirectGTOrder" exact="true"/>
          </do_if>
          
          <!-- Check if ship is subordinate to GT commander (current commander, not old) -->
          <set_value name="$hasGTCommander" exact="false"/>
          <do_if value="not $hasDirectGTOrder and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
              <set_value name="$hasGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Only emit cleanup if ship NO LONGER has GT order (direct or via commander) -->
          <!-- For subordinates, Assist order termination is handled by Assist order's on_abort -->
          <!-- Trade order termination is NORMAL and should NOT trigger cleanup -->
          <set_value name="$shouldEmitCleanup" exact="false"/>
          <do_if value="not $hasDirectGTOrder and not $hasGTCommander">
            <!-- No direct GT order and no GT commander = GT order truly gone -->
            <set_value name="$shouldEmitCleanup" exact="true"/>
          </do_if>
          
          <!-- Emit cleanup signal if GT order is gone -->
          <do_if value="$shouldEmitCleanup">
            <set_value name="$isGTOrderCancelled" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] PHASE 7: GT order cancelled for ' + this.ship.idcode + ' (detected in on_abort, default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ')'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI]  PHASE 7: Trade order aborted but GT order still active for ' + this.ship.idcode + ' (default order: ' + $currentDefaultOrder + ', has direct GT: ' + $hasDirectGTOrder + ', has GT commander: ' + $hasGTCommander + ') - NOT sending GT_Order_Cancelled'" chance="100"/>
            </do_if>
          </do_else>
          
          <!-- Restore ship name if not GT-controlled (direct or subordinate) -->
          <!-- Check if ship WAS a subordinate BEFORE GT order was cancelled -->
          <!-- Use this.$was_subordinate flag or check state manager state -->
          <set_value name="$wasSubordinateBeforeCancellation" exact="false"/>
          <do_if value="this.$was_subordinate?">
            <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.ship}?">
            <!-- Check state manager to see if ship was a subordinate -->
            <set_value name="$state" exact="global.$GT_Ship_State.{this.ship}"/>
            <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
              <set_value name="$wasSubordinateBeforeCancellation" exact="true"/>
            </do_if>
          </do_elseif>
          
          <!-- Check if ship is CURRENTLY subordinate to GT commander -->
          <set_value name="$isSubordinateOfGTCommander" exact="false"/>
          <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((@this.ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and (@this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @this.ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
              <set_value name="$isSubordinateOfGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Restore name if:
               1. Ship was NOT a subordinate before cancellation, OR
               2. Ship was a subordinate but is NO LONGER subordinate to GT commander -->
          <set_value name="$shouldRestoreName" exact="false"/>
          <do_if value="not $wasSubordinateBeforeCancellation">
            <!-- Ship was not a subordinate - restore name if not currently subordinate to GT commander -->
            <do_if value="not $isSubordinateOfGTCommander">
              <set_value name="$shouldRestoreName" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$wasSubordinateBeforeCancellation and not $isSubordinateOfGTCommander">
            <!-- Ship WAS a subordinate but is NO LONGER subordinate to GT commander - restore name -->
            <set_value name="$shouldRestoreName" exact="true"/>
          </do_elseif>
          
          <do_if value="$shouldRestoreName and this.ship.pilot?">
            <set_value name="$originalName" exact="null"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
            </do_if>
            
            <do_if value="$originalName">
              <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                $Ship = this.ship,
                $Pilot = this.ship.pilot,
                $Reason = 'GT order cancelled - restoring original name',
                $OriginalName = $originalName
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-AI] PHASE 7: Name restoration signal sent for ' + this.ship.idcode + ' (was subordinate: ' + $wasSubordinateBeforeCancellation + ', currently subordinate: ' + $isSubordinateOfGTCommander + ', original name: ' + $originalName + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_elseif>
        <do_else>
          <!-- GT order still active - this is just trade order cancellation, not GT order cancellation -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + this.ship.idcode + ': on_abort fired but GT order still active (default order: ' + $currentDefaultOrder + ') - skipping Phase 7 (trade order cancellation, not GT order cancellation)'" chance="100"/>
          </do_if>
        </do_else>
      </do_if>
      <do_else>
        <!-- GT order still active AND training/maintenance transition - skip Phase 7 (normal behavior) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order still active with training/maintenance transition - skipping Phase 7 (normal transition, not removal)'" chance="100"/>
        </do_if>
      </do_else>
    </do_elseif>
    
    <!-- Check if subordinate cleanup already sent signal (to avoid duplicate) -->
    <do_if value="this.$subordinate_cleanup_sent?">
      <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate cleanup signal already sent - skipping duplicate'" chance="100"/>
    </do_if>
    <do_else>
      <!-- Check for permanent removal FIRST, regardless of trading state -->
      <!-- When player stops order, we MUST restore name even if TradePerform orders are still active -->
      <!-- Unified GT order status check (inline for AI scripts) -->
      <!-- If GT order is gone (no direct, no commander), it's permanent removal REGARDLESS of trading state -->
      <set_value name="$isPermanentRemoval" exact="not $hasDirectGTOrder and not $hasGTCommander and $currentDefaultOrder != 'Assist'"/>
      
      <do_if value="$isPermanentRemoval">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$debugOrdersCount" exact="this.ship.orders.count"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order removed (no direct GT, no GT commander) â†’ PERMANENT REMOVAL (actively trading: ' + $isActivelyTrading + ', orders count: ' + $debugOrdersCount + ')'" chance="100"/>
        </do_if>
      </do_if>
      <do_else>
        <!-- GT order still active - check other conditions -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': GT order still active (direct: ' + $hasDirectGTOrder + ', commander: ' + $hasGTCommander + ') - checking other removal conditions'" chance="100"/>
        </do_if>
        
        <!-- Additional checks: no default order, different order, or not registered -->
        <do_if value="not $currentDefaultOrder">
          <!-- No default order at all â†’ PERMANENT REMOVAL -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': No default order detected â†’ PERMANENT REMOVAL'" chance="100"/>
        </do_if>
        <do_elseif value="$currentDefaultOrder and $currentDefaultOrder != 'GalaxyTraderMK3' and $currentDefaultOrder != 'GalaxyTraderMK4Supply2' and $currentDefaultOrder != 'Assist'">
          <!-- Ship has a DIFFERENT permanent default order â†’ PERMANENT REMOVAL -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Different default order (' + $currentDefaultOrder + ') detected â†’ PERMANENT REMOVAL'" chance="100"/>
        </do_elseif>
        <do_elseif value="not (global.$GT_Ships? and global.$GT_Ships.{this.ship}?)">
          <!-- Ship was removed from GT (unregistered), definitely restore name -->
          <set_value name="$isPermanentRemoval" exact="true"/>
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship no longer registered in GT_Ships â†’ PERMANENT REMOVAL (even if actively trading)'" chance="100"/>
        </do_elseif>
      </do_else>
      
      <!-- Calculate subordinate status (needed for both permanent removal and pause checks) -->
      <set_value name="$isSubordinate" exact="$currentDefaultOrder == 'Assist' and $hasGTCommander"/>
      
      <!-- Always restore name on permanent removal, even if actively trading -->
      <do_if value="$isPermanentRemoval">
        <!-- Send ABORT signal: Restore ship name and clean up completely -->
        <set_value name="$originalName" exact="null"/>
        <do_if value="this.ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="this.ship.macro?">
          <set_value name="$originalName" exact="@this.ship.macro.name"/>
        </do_elseif>

        <!-- Always emit cleanup signal on permanent removal, even if no stored original name was found.
             MD cleanup will still run and name restoration falls back safely. -->
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Order permanently removed by player',
          $OriginalName = $originalName
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Sending ABORT signal (restore name, preserve XP) - permanent removal detected'" chance="100"/>
        </do_if>
        
        <!-- Clear training and maintenance flags -->
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_order_created"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$maintenance_transition"/>
      </do_if>
      <!-- Only send PAUSE signal if NOT permanently removed AND NOT actively trading AND NOT transitioning -->
      <!-- CRITICAL: Don't pause subordinates with Assist order - they should stay registered -->
      <do_elseif value="not $isActivelyTrading and not $isTrainingTransition and not $isMaintenanceTransition and not $isSubordinate">
        <!-- Send PAUSE signal: Preserve everything (name and XP) for potential resume -->
        <set_value name="$pauseData" exact="table[
          $Ship = this.ship,
          $Pilot = this.ship.pilot,
          $Reason = 'Order temporarily replaced - preserving pilot data',
          $PreserveData = true
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Sending PAUSE signal (preserve everything for resume)'" chance="100"/>
        </do_if>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Paused'" param2="$pauseData"/>
        
        <!-- Clear training and maintenance flags -->
        <remove_value name="this.$training_in_progress"/>
        <remove_value name="this.$training_order_created"/>
        <remove_value name="this.$training_transition"/>
        <remove_value name="this.$maintenance_transition"/>
      </do_elseif>
      <do_elseif value="$isSubordinate">
        <!-- Subordinate with Assist order - don't pause, stay registered -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Subordinate with Assist order - NOT sending PAUSE (staying registered)'" chance="100"/>
        </do_if>
      </do_elseif>
      <do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + this.ship.idcode + ': Ship still actively trading/training/maintenance - NOT sending signals (will handle when orders complete)'" chance="100"/>
        </do_if>
      </do_else>
    </do_else>
  </on_abort>
  
</aiscript> <?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Direct trade completion signalling patch -->
  <!-- This patch adds immediate XP signalling when trades complete successfully -->
  
  <!-- PHASE 0.5: Escape Logic - Allow trades FROM blacklisted sectors (ship's current sector) -->
  <!-- This patches vanilla's blacklist check to add escape exception -->
  <!-- First blacklist check (before docking) -->
  <add sel="//aiscript[@name='order.trade.perform']/attention/actions/include_interrupt_actions[@ref='GetBlacklistgroup']" pos="after">
    
    <!-- ESCAPE LOGIC: Only for GalaxyTrader ships -->
    <!-- Check if ship is in target sector AND sector is blacklisted (escape FROM blacklisted sector) -->
    <set_value name="$allowEscapeTrade" exact="false"/>
    <do_if value="this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
      <!-- Only apply escape logic to GalaxyTrader ships -->
      <set_value name="$shipCurrentSector" exact="@this.assignedcontrolled.sector"/>
      <set_value name="$commanderSector" exact="@this.assignedcontrolled.commander.sector"/>
      <set_value name="$targetSector" exact="@$targetobject.sector"/>
      
      <!-- ESCAPE EXCEPTION: Only allow if ship is in target sector AND sector is actually blacklisted -->
      <!-- OR if target sector is commander's sector (vanilla exception) -->
      <do_if value="$targetSector and $shipCurrentSector and $targetSector == $shipCurrentSector">
        <!-- Check if the sector/object is actually blacklisted before allowing escape -->
        <set_value name="$isBlacklisted" exact="false"/>
        <do_if value="$targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or 
                      @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or 
                      @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}">
          <set_value name="$isBlacklisted" exact="true"/>
        </do_if>
        
        <!-- Only allow escape if sector/object is actually blacklisted -->
        <do_if value="$isBlacklisted">
          <set_value name="$allowEscapeTrade" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradePerform] ESCAPE TRADE ALLOWED: ' + this.ship.idcode + ' in target sector (escape FROM blacklisted sector)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="$targetSector and $commanderSector and $targetSector == $commanderSector">
        <!-- Vanilla exception: Commander's sector (already in vanilla code) -->
        <set_value name="$allowEscapeTrade" exact="true"/>
      </do_elseif>
    </do_if>
    
  </add>
  
  <!-- Replace vanilla's first blacklist check with escape-aware version -->
  <!-- FIX: Use [1] to explicitly target the FIRST occurrence (before docking) -->
  <!-- CRITICAL: Only apply escape logic to GT ships - preserve vanilla behavior for all other ships -->
  <replace sel="//aiscript[@name='order.trade.perform']/attention/actions/do_if[@value='$internalorder and ($targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}) and $targetobject.sector and ($targetobject.sector != @this.assignedcontrolled.commander.sector)'][1]">
    <!-- GT SHIP CHECK: Apply escape logic only to GT ships, preserve vanilla for others -->
    <do_if value="this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
      <!-- GT Ship: Use escape-aware blacklist check -->
      <do_if value="$internalorder and not $allowEscapeTrade and ($targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}) and $targetobject.sector and ($targetobject.sector != @this.assignedcontrolled.commander.sector)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'trade partner: %s %s %s %s is blacklisted. aborting trade.'.[@$targetobject.class, @$targetobject.idcode, @$targetobject.knownname, $targetobject]" chance="$debugchance"/>
        </do_if>
        <!-- this is not an error. trade will fail in this case since we will refuse to trade with this trade partner. -->
        <set_value name="$failreason" exact="'TRADEPARTNER_BLACKLISTED'"/>
        <set_value name="$failuretext" exact="{1045, 124}" comment="Trade partner is blacklisted."/>
        <resume label="finish"/>
      </do_if>
    </do_if>
    <do_else>
      <!-- Non-GT Ship: Use exact vanilla behavior (no escape logic) -->
      <do_if value="$internalorder and ($targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}) and $targetobject.sector and ($targetobject.sector != @this.assignedcontrolled.commander.sector)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'trade partner: %s %s %s %s is blacklisted. aborting trade.'.[@$targetobject.class, @$targetobject.idcode, @$targetobject.knownname, $targetobject]" chance="$debugchance"/>
        </do_if>
        <!-- this is not an error. trade will fail in this case since we will refuse to trade with this trade partner. -->
        <set_value name="$failreason" exact="'TRADEPARTNER_BLACKLISTED'"/>
        <set_value name="$failuretext" exact="{1045, 124}" comment="Trade partner is blacklisted."/>
        <resume label="finish"/>
      </do_if>
    </do_else>
  </replace>
  
  <!-- PHASE 0.6: Escape Logic - Second check after docking (same logic) -->
  <add sel="//aiscript[@name='order.trade.perform']/attention/actions/label[@name='perform_trade']" pos="before">
    
    <!-- ESCAPE LOGIC: Re-check for escape trade after docking (only for GalaxyTrader ships) -->
    <set_value name="$allowEscapeTrade2" exact="false"/>
    <do_if value="this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
      <!-- Only apply escape logic to GalaxyTrader ships -->
      <set_value name="$shipCurrentSector2" exact="@this.assignedcontrolled.sector"/>
      <set_value name="$commanderSector2" exact="@this.assignedcontrolled.commander.sector"/>
      <set_value name="$targetSector2" exact="@$targetobject.sector"/>
      
      <!-- ESCAPE EXCEPTION: Only allow if ship is in target sector AND sector is actually blacklisted -->
      <do_if value="$targetSector2 and $shipCurrentSector2 and $targetSector2 == $shipCurrentSector2">
        <!-- Check if the sector/object is actually blacklisted before allowing escape -->
        <set_value name="$isBlacklisted2" exact="false"/>
        <do_if value="$targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or 
                      @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or 
                      @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}">
          <set_value name="$isBlacklisted2" exact="true"/>
        </do_if>
        
        <!-- Only allow escape if sector/object is actually blacklisted -->
        <do_if value="$isBlacklisted2">
          <set_value name="$allowEscapeTrade2" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradePerform] ESCAPE TRADE ALLOWED (post-dock): ' + this.ship.idcode + ' in target sector (escape FROM blacklisted sector)'" chance="100"/>
          </do_if>
        </do_if>
      </do_if>
      <do_elseif value="$targetSector2 and $commanderSector2 and $targetSector2 == $commanderSector2">
        <!-- Vanilla exception: Commander's sector (already in vanilla code) -->
        <set_value name="$allowEscapeTrade2" exact="true"/>
      </do_elseif>
    </do_if>
    
  </add>
  
  <!-- Replace vanilla's second blacklist check (after docking) with escape-aware version -->
  <!-- FIX: Select the do_if parent of the unique debug_text for the second check -->
  <!-- CRITICAL: Only apply escape logic to GT ships - preserve vanilla behavior for all other ships -->
  <replace sel="//aiscript[@name='order.trade.perform']/attention/actions/do_if/debug_text[@text=&quot;'was about to dock but trade partner: %s %s %s %s is blacklisted. aborting trade.'.[@$targetobject.class, @$targetobject.idcode, @$targetobject.knownname, $targetobject]&quot;]/..">
    <!-- GT SHIP CHECK: Apply escape logic only to GT ships, preserve vanilla for others -->
    <do_if value="this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
      <!-- GT Ship: Use escape-aware blacklist check -->
      <do_if value="$internalorder and not $allowEscapeTrade2 and ($targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}) and $targetobject.sector and ($targetobject.sector != @this.assignedcontrolled.commander.sector)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'was about to dock but trade partner: %s %s %s %s is blacklisted. aborting trade.'.[@$targetobject.class, @$targetobject.idcode, @$targetobject.knownname, $targetobject]" chance="$debugchance"/>
        </do_if>
        <!-- this is not an error. trade will fail in this case since we will refuse to trade with this trade partner. -->
        <set_value name="$failreason" exact="'TRADEPARTNER_BLACKLISTED'"/>
        <set_value name="$failuretext" exact="{1045, 124}" comment="Trade partner is blacklisted."/>
        <resume label="finish"/>
      </do_if>
    </do_if>
    <do_else>
      <!-- Non-GT Ship: Use exact vanilla behavior (no escape logic) -->
      <do_if value="$internalorder and ($targetobject.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{this.assignedcontrolled} or @$targetobject.sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{this.assignedcontrolled}) and $targetobject.sector and ($targetobject.sector != @this.assignedcontrolled.commander.sector)">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'was about to dock but trade partner: %s %s %s %s is blacklisted. aborting trade.'.[@$targetobject.class, @$targetobject.idcode, @$targetobject.knownname, $targetobject]" chance="$debugchance"/>
        </do_if>
        <!-- this is not an error. trade will fail in this case since we will refuse to trade with this trade partner. -->
        <set_value name="$failreason" exact="'TRADEPARTNER_BLACKLISTED'"/>
        <set_value name="$failuretext" exact="{1045, 124}" comment="Trade partner is blacklisted."/>
        <resume label="finish"/>
      </do_if>
    </do_else>
  </replace>
  
  <!-- PHASE 0: Check for Dock Failure Signals -->
  <!-- This runs AFTER dock order completes, BEFORE trade execution -->
  <add sel="//aiscript[@name='order.trade.perform']/attention/actions/label[@name='perform_trade']" pos="after">
    
    <!-- GALAXYTRADER MK3: Check if dock order failed due to pathfinding -->
    <do_if value="global.$GT_DockFailures? and global.$GT_DockFailures.{this.ship}?">
      <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <!-- Dock failed - set trade failure reason -->
        <set_value name="$dockFailure" exact="global.$GT_DockFailures.{this.ship}"/>
        <set_value name="$failreason" exact="$dockFailure.$Reason"/>
        <set_value name="$failuretext" exact="$dockFailure.$FailureText"/>
        
        <!-- Clean up global entry -->
        <remove_value name="global.$GT_DockFailures.{this.ship}"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradePerform] âš  Dock failure detected: ' + $failreason + ' for ' + this.ship.idcode + ' (target: ' + @$targetobject.knownname + ')'" chance="100"/>
        </do_if>
        
        <!-- Abort trade and go to finish label where failure will be queued -->
        <resume label="finish"/>
      </do_if>
      <do_else>
        <!-- Not a GT-managed ship, but clean up anyway -->
        <remove_value name="global.$GT_DockFailures.{this.ship}"/>
      </do_else>
    </do_if>
    
  </add>
  
  <!-- PHASE 1.1: Add Failure Signal Detection -->
  <!-- This runs when resume label="finish" is called (including from vanilla blacklist check) -->
  <add sel="//aiscript[@name='order.trade.perform']/attention/actions/label[@name='finish']" pos="after">
    
    <!-- GALAXYTRADER MK3: Trade failure signalling -->
    <do_if value="$failreason != ''">
      <!-- MK4/MK3 supply: pickup failure leaves paired delivery orders queued (LIFO buy-then-sell
           queueing). Cancel same-ware delivery legs immediately to prevent ERR_NOTHING_TO_SELL. -->
      <do_if value="$failreason == 'ERR_SELLER_NO_CARGO' and $isbuying and $tradedeal.ware? and global.$GT_Ships? and global.$GT_Ships.{this.ship}?">
        <set_value name="$gtOrphanCancelCount" exact="0"/>
        <set_value name="$gtPendingTrades" exact="this.ship.tradeorders"/>
        <do_all exact="$gtPendingTrades.count" counter="$gtcoi">
          <set_value name="$gtPendingOrder" exact="$gtPendingTrades.{$gtcoi}"/>
          <do_if value="$gtPendingOrder? and $gtPendingOrder != this.ship.order and $gtPendingOrder.$tradedeal?">
            <do_if value="not @$gtPendingOrder.$tradedeal.seller.exists and $gtPendingOrder.$tradedeal.ware == $tradedeal.ware">
              <cancel_order order="$gtPendingOrder"/>
              <set_value name="$gtOrphanCancelCount" operation="add"/>
            </do_if>
          </do_if>
        </do_all>
        <do_if value="$gtOrphanCancelCount gt 0 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradePerform] ' + this.ship.idcode + ': cancelled ' + $gtOrphanCancelCount + ' orphaned delivery order(s) for ' + $tradedeal.ware + ' after supplier pickup failure'" chance="100"/>
        </do_if>
      </do_if>
      <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <set_value name="$failure_data" exact="table[
          $Ship = this.ship,
          $pilot = this.ship.pilot,
          $reason = $failreason,
          $failureText = @$failuretext,
          $ware = @$tradedeal.ware,
          $partner = @$targetobject,
          $isBuying = $isbuying,
          $timestamp = player.age
        ]"/>
        
        <do_if value="not global.$GT_TradeFailureQueue?">
          <set_value name="global.$GT_TradeFailureQueue" exact="[]"/>
        </do_if>
        
        <append_to_list name="global.$GT_TradeFailureQueue" exact="$failure_data"/>
        
        <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
        <signal_objects object="player.galaxy" param="'GT_TradeFailure'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradePerform] âš  Trade FAILED: ' + $failreason + ' for ' + this.ship.idcode + ' (partner: ' + @$targetobject.knownname + ')'" chance="100"/>
        </do_if>
      </do_if>
    </do_if>
    
  </add>
  
  <!-- PHASE 1.2: Add Buy Completion Signal (Analytics) -->
  <add sel="//aiscript[@name='order.trade.perform']/attention/actions/label[@name='finish']" pos="after">
    
    <!-- GALAXYTRADER MK3: Buy completion tracking -->
    <do_if value="$failreason == '' and $isbuying">
      <do_if value="$traderesult?">
        <do_if value="$traderesult">
          <!-- PERFORMANCE FIX: Check GT order status FIRST before any processing -->
          <!-- Only process if ship has GT order (direct or via commander) -->
          <set_value name="$isGTControlled" exact="false"/>
          
          <!-- Quick check: Does ship have direct GT order (or Assist baseorder for GT subordinates)? -->
          <do_if value="(this.ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.id}) or (this.ship.defaultorder? and @this.ship.defaultorder.id == 'Assist' and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id})">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
          
          <!-- Fallback check: Is ship subordinate to GT commander? -->
          <do_if value="not $isGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}) or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}))">
              <set_value name="$isGTControlled" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Proceed for any GT-controlled ship; completion routing/logging must not depend on pilot table timing. -->
          <do_if value="$isGTControlled">
        <set_value name="$buy_data" exact="table[
          $Ship = this.ship,
          $ware = $tradedeal.ware,
          $amount = $tradedeal.transferredamount,
          $unitPrice = $tradedeal.unitprice,
          $partner = $targetobject,
          $timestamp = player.age
        ]"/>
        
        <!-- FIX: Defensive check for race condition (initialization might not have completed yet) -->
        <!-- Extract queue first with @ operator, then validate it's actually a list -->
        <set_value name="$buyQueue" exact="@global.$GT_BuyCompleteQueue"/>
        <set_value name="$queueValid" exact="false"/>
        <do_if value="$buyQueue?">
          <!-- Check if it's actually a list (not null) -->
          <set_value name="$queueType" exact="typeof $buyQueue"/>
          <do_if value="$queueType == datatype.list">
            <set_value name="$queueValid" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $queueValid">
          <set_value name="global.$GT_BuyCompleteQueue" exact="[]"/>
        </do_if>
        <append_to_list name="global.$GT_BuyCompleteQueue" exact="$buy_data"/>
        
        <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
        <signal_objects object="player.galaxy" param="'GT_BuyComplete'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradePerform] BUY complete: ' + this.ship.idcode + ' bought ' + $tradedeal.transferredamount + ' ' + $tradedeal.ware" chance="100"/>
        </do_if>
          </do_if>
        </do_if>
      </do_if>
    </do_if>
    
  </add>
  
  <!-- PHASE 1: Sell Completion (Existing XP System) -->
  <add sel="//aiscript[@name='order.trade.perform']/attention/actions/label[@name='finish']" pos="after">
    
    <!-- GALAXYTRADER MK3: Direct trade completion signalling -->
    <!-- CRITICAL FIX: Only award XP on SELL operations (complete trades), not BUY operations -->
    <do_if value="$failreason == '' and this.ship.pilot and not $isbuying">
      <do_if value="$traderesult?">
        <do_if value="$traderesult">
          <!-- PERFORMANCE FIX: Check GT order status FIRST before any processing -->
          <!-- Only process if ship has GT order (direct or via commander) -->
          <set_value name="$isGTControlled" exact="false"/>
          
          <!-- Quick check: Does ship have direct GT order (or Assist baseorder for GT subordinates)? -->
          <do_if value="(this.ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.id}) or (this.ship.defaultorder? and @this.ship.defaultorder.id == 'Assist' and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id})">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
          
          <!-- Fallback check: Is ship subordinate to GT commander? -->
          <do_if value="not $isGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}) or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}))">
              <set_value name="$isGTControlled" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Proceed for any GT-controlled ship; completion routing/logging must not depend on pilot table timing. -->
          <do_if value="$isGTControlled">
        
        <!-- Calculate GalaxyTrader XP (enhanced version of native XP) -->
        <!-- READ FROM SINGLE SOURCE OF TRUTH CONFIGURATION -->
        <set_value name="$gt_base_xp" exact="@global.$GT_Config.$XP.$BaseXPPerTrade"/>
        <set_value name="$gt_value_divisor" exact="@global.$GT_Config.$XP.$ValueDivisor"/>
        <set_value name="$gt_quality_multiplier" exact="@global.$GT_Config.$XP.$QualityMultiplier"/>
        <set_value name="$gt_max_distance" exact="@global.$GT_Config.$XP.$MaxDistanceForBonus"/>
        <set_value name="$gt_distance_divisor" exact="@global.$GT_Config.$XP.$DistanceBonusDivisor"/>
        <set_value name="$gt_min_xp" exact="@global.$GT_Config.$XP.$MinXPPerTrade"/>
        <set_value name="$gt_max_xp" exact="@global.$GT_Config.$XP.$MaxXPPerTrade"/>
        
        <!-- Apply configuration values with fallbacks for safety -->
        <do_if value="not $gt_base_xp?">
          <set_value name="$gt_base_xp" exact="50"/>  <!-- Fallback if config not loaded -->
        </do_if>
        <do_if value="not $gt_value_divisor?">
          <set_value name="$gt_value_divisor" exact="10000"/>
        </do_if>
        <do_if value="not $gt_quality_multiplier?">
          <set_value name="$gt_quality_multiplier" exact="0.5"/>
        </do_if>
        <do_if value="not $gt_max_distance?">
          <set_value name="$gt_max_distance" exact="10"/>
        </do_if>
        <do_if value="not $gt_distance_divisor?">
          <set_value name="$gt_distance_divisor" exact="20.0"/>
        </do_if>
        <do_if value="not $gt_min_xp?">
          <set_value name="$gt_min_xp" exact="10"/>
        </do_if>
        <do_if value="not $gt_max_xp?">
          <set_value name="$gt_max_xp" exact="1000"/>
        </do_if>
        
        <!-- Calculate XP components using configuration values -->
        <set_value name="$gt_value_multiplier" exact="(($tradedeal.unitprice * $tradedeal.transferredamount) / ($gt_value_divisor * 1Cr))f"/>
        <set_value name="$gt_quality_bonus" exact="1.0 + ($tradequality * $gt_quality_multiplier)"/>
        <set_value name="$gt_distance_bonus" exact="1.0"/>  <!-- Will be calculated below -->
        
        <!-- Calculate distance bonus if we can determine trade partner distance -->
        <do_if value="this.ship.sector? and $targetobject.sector?">
          <set_value name="$sector_distance" exact="this.ship.sector.distanceto.{$targetobject.sector}"/>
          <do_if value="$sector_distance gt 0">
            <!-- Distance bonus using configuration values -->
            <set_value name="$gt_distance_bonus" exact="1.0 + ([$sector_distance, $gt_max_distance].min / $gt_distance_divisor)"/>
          </do_if>
        </do_if>
        
        <!-- Final XP calculation -->
        <set_value name="$gt_xp_amount" exact="($gt_base_xp * $gt_value_multiplier * $gt_quality_bonus * $gt_distance_bonus)i"/>
        
        <!-- Apply player-configurable XP multiplier (50-200%, default 100%) -->
        <set_value name="$gt_xp_multiplier" exact="@global.$GT_GlobalSettings.$XP.$XPMultiplier"/>
        <do_if value="not $gt_xp_multiplier? or $gt_xp_multiplier lt 50 or $gt_xp_multiplier gt 200">
          <set_value name="$gt_xp_multiplier" exact="100"/>  <!-- Fallback to 100% if invalid -->
        </do_if>
        <set_value name="$gt_xp_amount" exact="($gt_xp_amount * ($gt_xp_multiplier / 100.0))i"/>
        
        <!-- Cap XP to configured range -->
        <do_if value="$gt_xp_amount lt $gt_min_xp">
          <set_value name="$gt_xp_amount" exact="$gt_min_xp"/>
        </do_if>
        <do_if value="$gt_xp_amount gt $gt_max_xp">
          <set_value name="$gt_xp_amount" exact="$gt_max_xp"/>
        </do_if>
        
        <!-- Calculate actual profit (revenue - purchase cost) -->
        <set_value name="$sellRevenue" exact="$tradedeal.unitprice * $tradedeal.transferredamount"/>
        <set_value name="$purchaseCost" exact="0"/>
        <set_value name="$actualProfit" exact="$sellRevenue"/>
        
        <!-- Look up purchase cost from cargo tracking -->
        <do_if value="global.$GT_CargoCostTracking? and global.$GT_CargoCostTracking.{this.ship}? and 
                      global.$GT_CargoCostTracking.{this.ship}.{$tradedeal.ware}?">
          <set_value name="$cargoTracking" exact="global.$GT_CargoCostTracking.{this.ship}.{$tradedeal.ware}"/>
          
          <!-- Calculate weighted average purchase price -->
          <do_if value="$cargoTracking.$Amount gt 0">
            <set_value name="$avgPurchasePrice" exact="$cargoTracking.$TotalCost / $cargoTracking.$Amount"/>
            <set_value name="$purchaseCost" exact="($avgPurchasePrice * $tradedeal.transferredamount)i"/>
            <set_value name="$actualProfit" exact="$sellRevenue - $purchaseCost"/>
            
            <!-- Update cargo tracking: reduce tracked amount and cost -->
            <set_value name="$remainingAmount" exact="$cargoTracking.$Amount - $tradedeal.transferredamount"/>
            <do_if value="$remainingAmount le 0">
              <!-- All units sold - remove tracking entry -->
              <remove_value name="global.$GT_CargoCostTracking.{this.ship}.{$tradedeal.ware}"/>
            </do_if>
            <do_else>
              <!-- Partial sale - update tracking -->
              <set_value name="global.$GT_CargoCostTracking.{this.ship}.{$tradedeal.ware}.$Amount" 
                          exact="$remainingAmount"/>
              <set_value name="global.$GT_CargoCostTracking.{this.ship}.{$tradedeal.ware}.$TotalCost" 
                          exact="($avgPurchasePrice * $remainingAmount)i"/>
            </do_else>
          </do_if>
        </do_if>
        
        <!-- Store rich trade data for advanced XP processing -->
        <set_value name="$trade_data" exact="table[
            $pilot = this.ship.pilot,
            $Ship = this.ship,
            $xpAmount = $gt_xp_amount,
            $ware = $tradedeal.ware,
            $tradeValue = $actualProfit,
            $sellRevenue = $sellRevenue,
            $purchaseCost = $purchaseCost,
            $transferredAmount = $tradedeal.transferredamount,
            $unitPrice = $tradedeal.unitprice,
            $tradeQuality = $tradequality,
            $partner = $targetobject,
            $partnerSector = $targetobject.sector,
            $shipSector = this.ship.sector,
            $isPlayerOwned = this.ship.isplayerowned,
            $timestamp = player.age,
            $valueMultiplier = $gt_value_multiplier,
            $qualityBonus = $gt_quality_bonus,
            $distanceBonus = $gt_distance_bonus
        ]"/>
        
        <!-- Store trade data in global queue for MD system to process -->
        <do_if value="not global.$GT_DirectTradeQueue?">
          <set_value name="global.$GT_DirectTradeQueue" exact="[]"/>
        </do_if>
        
        <!-- Add trade data to queue -->
        <append_to_list name="global.$GT_DirectTradeQueue" exact="$trade_data"/>
        
        <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
        <signal_objects object="player.galaxy" param="'GT_DirectTrade'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradePerform] DIRECT XP QUEUED (SELL ONLY): Pilot ' + this.ship.pilot.name + ' earned ' + $gt_xp_amount + ' XP for ' + $tradedeal.ware + ' trade' +
                            '\n  Revenue: ' + ($sellRevenue / 100) + ' Cr, Cost: ' + ($purchaseCost / 100) + ' Cr, PROFIT: ' + ($actualProfit / 100) + ' Cr' +
                            '\n  Quality: ' + $tradequality + ', Distance bonus: ' + $gt_distance_bonus" 
                      chance="100"/>
        </do_if>
          </do_if>
        </do_if>
      </do_if>
    </do_if>
    
    <!-- PHASE 4: Add state update signal AFTER trade completion (sell only - complete trades) -->
    <!-- This tests if signaling after trade completion interferes with trade execution -->
    <do_if value="$failreason == '' and this.ship.pilot and not $isbuying">
      <do_if value="$traderesult?">
        <do_if value="$traderesult">
          <!-- PERFORMANCE FIX: Check GT order status FIRST before any processing -->
          <!-- Only process if ship has GT order (direct or via commander) -->
          <set_value name="$isGTControlled" exact="false"/>
          
          <!-- Quick check: Does ship have direct GT order (or Assist baseorder for GT subordinates)? -->
          <do_if value="(this.ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.id}) or (this.ship.defaultorder? and @this.ship.defaultorder.id == 'Assist' and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id})">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
          
          <!-- Fallback check: Is ship subordinate to GT commander? -->
          <do_if value="not $isGTControlled and this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
            <do_if value="this.ship.commander.defaultorder? and ((global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}) or (@this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}))">
              <set_value name="$isGTControlled" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Proceed for any GT-controlled ship; state updates should not be blocked by pilot table timing. -->
          <do_if value="$isGTControlled">
        <!-- Check remaining trade orders -->
        <set_value name="$remainingOrders" exact="0"/>
        <do_if value="this.ship.tradeorders?">
          <set_value name="$remainingOrders" exact="this.ship.tradeorders.count"/>
        </do_if>
        
        <!-- Send state update signal -->
        <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
          $Ship = this.ship,
          $UpdateType = 'Trade_Order_Completed',
          $RemainingOrders = $remainingOrders
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradePerform] PHASE 4: State update signal sent (Trade_Order_Completed, remaining orders: ' + $remainingOrders + ')'" chance="100"/>
        </do_if>
        
        <!-- PHASE 5: Add name restoration check AFTER trade completion -->
        <!-- This tests if name restoration logic interferes with trade execution -->
        <do_if value="$remainingOrders == 0">
          <!-- Check if ship has GT order -->
          <set_value name="$hasGTOrder" exact="false"/>
          <do_if value="this.ship.defaultorder?">
            <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
            <do_if value="$currentDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$currentDefaultOrder}">
              <set_value name="$hasGTOrder" exact="true"/>
            </do_if>
            <do_elseif value="$currentDefaultOrder == 'Assist' and this.ship.defaultorder? and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
              <set_value name="$hasGTOrder" exact="true"/>
            </do_elseif>
          </do_if>
          
          <!-- Only restore name if no GT order and no remaining trade orders -->
          <do_if value="not $hasGTOrder">
            <!-- Restore name if not GT-controlled (direct or subordinate) -->
            <set_value name="$isSubordinateOfGTCommander" exact="false"/>
            <do_if value="this.ship.commander? and this.ship.commander.exists and this.ship.commander != this.ship">
              <do_if value="this.ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.id}">
                <set_value name="$isSubordinateOfGTCommander" exact="true"/>
              </do_if>
              <do_elseif value="this.ship.commander.defaultorder? and @this.ship.commander.defaultorder.id == 'Assist' and this.ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.commander.defaultorder.$baseorder.id}">
                <set_value name="$isSubordinateOfGTCommander" exact="true"/>
              </do_elseif>
            </do_if>
            
            <do_if value="not $isSubordinateOfGTCommander and this.ship.pilot?">
              <set_value name="$originalName" exact="null"/>
              <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}? and global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName"/>
              </do_if>
              
              <do_if value="$originalName">
                <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                  $Ship = this.ship,
                  $Pilot = this.ship.pilot,
                  $Reason = 'Trade orders completed - ship no longer GT-controlled',
                  $OriginalName = $originalName
                ]"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-TradePerform] PHASE 5: Name restoration signal sent (no GT order, not subordinate, trade orders complete, original name: ' + $originalName + ')'" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
      </do_if>
        </do_if>
      </do_if>
    </do_if>
    
  </add>
  
  <!-- PHASE 2: Add on_abort handler to detect order cancellation -->
  <!-- This catches cases where TradePerform orders are cancelled (e.g., player removes all orders) -->
  <!-- Add on_abort handler after the attention block -->
  <add sel="//aiscript[@name='order.trade.perform']/attention" pos="after">
    <on_abort>
      <!-- CRITICAL: Check if ship still has GT order when TradePerform is cancelled -->
      <!-- This catches cases where player removes all orders while TradePerform is active -->
      <!-- NOTE: When player cancels all orders, TradePerform's on_abort fires, but GT order might still exist temporarily -->
      <!-- So we check registration status as primary indicator, with order check as secondary -->
      <do_if value="this.ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{this.ship.pilot}?">
        <!-- PRIMARY CHECK: Is ship still registered in GT_Ships? -->
        <!-- This is the most reliable indicator - if ship was removed from GT, it's definitely not active -->
        <set_value name="$isRegistered" exact="global.$GT_Ships? and global.$GT_Ships.{this.ship}?"/>
        
        <!-- SECONDARY CHECK: Does ship still have an active GT order? -->
        <!-- Note: This might still be true temporarily during cancellation cascade, so it's secondary -->
        <set_value name="$hasGTOrder" exact="false"/>
        <set_value name="$currentDefaultOrder" exact="@this.ship.defaultorder.id"/>
        
        <do_if value="$currentDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$currentDefaultOrder}">
          <set_value name="$hasGTOrder" exact="true"/>
        </do_if>
        <do_elseif value="$currentDefaultOrder == 'Assist' and this.ship.defaultorder? and this.ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.ship.defaultorder.$baseorder.id}">
          <set_value name="$hasGTOrder" exact="true"/>
        </do_elseif>
        
        <!-- CRITICAL LOGIC: Restore name if GT order is missing (cancellation cascade) -->
        <!-- Priority: GT order check FIRST because registration cleanup happens AFTER abort signals -->
        <!-- If GT order is missing, it means cancellation cascade happened, restore name immediately -->
        <do_if value="not $hasGTOrder">
          <!-- GT order missing = cancellation cascade, restore name even if still registered -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradePerform] TradePerform cancelled for ' + this.ship.idcode + ' - GT order MISSING (current: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + '), restoring original name (ship registered: ' + $isRegistered + ')'" chance="100"/>
          </do_if>
          
          <!-- Send signal to restore ship name -->
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'TradePerform cancelled - GT order no longer active (cancellation cascade)',
            $OriginalName = if global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName? then global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName else null
          ]"/>
        </do_if>
        <do_elseif value="not $isRegistered">
          <!-- Ship was removed from GT (already unregistered) - definitely restore name -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradePerform] TradePerform cancelled for ' + this.ship.idcode + ' - ship NO LONGER REGISTERED in GT_Ships, restoring original name'" chance="100"/>
          </do_if>
          
          <!-- Send signal to restore ship name -->
          <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
            $Ship = this.ship,
            $Pilot = this.ship.pilot,
            $Reason = 'TradePerform cancelled - ship unregistered from GT',
            $OriginalName = if global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName? then global.$GT_Pilots.{this.ship.pilot}.$OriginalShipName else null
          ]"/>
        </do_elseif>
        <do_elseif value="$hasGTOrder and $isRegistered">
          <!-- Clear scheduler state so ship can immediately retry cargo disposal search (avoids 60s timeout) -->
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = this.ship]" delay="1ms"/>
          <!-- TradePerform revoked by player but GT order still active - wake GT script so it can retry (find same or next trade).
               Delay ensures signal arrives after GT order resumes (avoids signal loss during order transition). -->
          <signal_objects object="this.assignedcontrolled" param="'GT_Trade_Failed'" param2="table[
            $Reason = 'Order cancelled by player',
            $ReasonType = 'USER_CANCELLED',
            $ShouldTryNext = true
          ]" delay="1ms"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradePerform] TradePerform cancelled for ' + this.ship.idcode + ' - GT still active, sent GT_Search_Abort + GT_Trade_Failed to retry'" chance="100"/>
          </do_if>
        </do_elseif>
      </do_if>
    </on_abort>
  </add>
</diff>
<?xml version="1.0" encoding="utf-8"?>
<diff>
  <!-- GalaxyTrader MK3: Detect GT order removal when Hold Position is assigned -->
  <!-- When GT order is removed, X4 assigns Hold Position (Wait order) as default order -->
  <!-- This patch detects when Hold Position is assigned to a ship that previously had a GT order -->
  
  <!-- PHASE 7: Add GT order detection in init block -->
  <!-- Add detection logic at the start of init block (after set_command) -->
  <add sel="//aiscript[@name='order.wait']/init/set_command_action[@commandaction='commandaction.standingby']" pos="after">
    
    <!-- PHASE 7: Detect GT order removal when Hold Position is assigned -->
    <!-- When GT order is removed, X4 assigns Hold Position as default order -->
    <!-- Check if this ship was previously registered with GT order -->
    <do_if value="global.$GT_Ship_State? and global.$GT_Ship_State.{this.assignedcontrolled}?">
      <set_value name="$state" exact="global.$GT_Ship_State.{this.assignedcontrolled}"/>
      
      <!-- Unified GT order status check (inline for AI scripts) -->
      <set_value name="$currentDefaultOrder" exact="@this.assignedcontrolled.defaultorder.id"/>
      <set_value name="$hasDirectGTOrder" exact="false"/>
      <set_value name="$hasGTCommander" exact="false"/>
      <set_value name="$commanderExists" exact="false"/>
      <set_value name="$isGTControlled" exact="false"/>
      <set_value name="$shouldCleanup" exact="false"/>
      <set_value name="$shouldRestoreName" exact="false"/>
      
      <!-- Check direct GT order (including Assist baseorder variants) -->
      <do_if value="$currentDefaultOrder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$currentDefaultOrder}">
        <set_value name="$hasDirectGTOrder" exact="true"/>
        <set_value name="$isGTControlled" exact="true"/>
      </do_if>
      <do_elseif value="$currentDefaultOrder == 'Assist' and this.assignedcontrolled.defaultorder? and this.assignedcontrolled.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.assignedcontrolled.defaultorder.$baseorder.id}">
        <set_value name="$hasDirectGTOrder" exact="true"/>
        <set_value name="$isGTControlled" exact="true"/>
      </do_elseif>
      
      <!-- Check commander status -->
      <do_if value="not $hasDirectGTOrder and this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists and this.assignedcontrolled.commander != this.assignedcontrolled">
        <set_value name="$commanderExists" exact="true"/>
        <do_if value="this.assignedcontrolled.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.assignedcontrolled.commander.defaultorder.id}">
          <set_value name="$hasGTCommander" exact="true"/>
          <do_if value="$currentDefaultOrder == 'Assist'">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="this.assignedcontrolled.commander.defaultorder? and @this.assignedcontrolled.commander.defaultorder.id == 'Assist' and this.assignedcontrolled.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@this.assignedcontrolled.commander.defaultorder.$baseorder.id}">
          <set_value name="$hasGTCommander" exact="true"/>
          <do_if value="$currentDefaultOrder == 'Assist'">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
        </do_elseif>
      </do_if>
      
      <!-- Check if ship was GT-controlled (in registry or state says so) -->
      <set_value name="$wasGTControlled" exact="false"/>
      <do_if value="(global.$GT_Ships? and global.$GT_Ships.{this.assignedcontrolled}?) or ($state.$HasGTOrder? and $state.$HasGTOrder)">
        <set_value name="$wasGTControlled" exact="true"/>
      </do_if>
      
      <!-- Determine if cleanup needed -->
      <do_if value="$wasGTControlled and not $isGTControlled">
        <set_value name="$shouldCleanup" exact="true"/>
        <do_if value="not $hasDirectGTOrder and not $hasGTCommander and this.assignedcontrolled.pilot?">
          <set_value name="$shouldRestoreName" exact="true"/>
        </do_if>
      </do_if>
      
      <!-- Check for cancellation using the unified "was vs is" outcome.
           This avoids missing cleanup when state flag exists but is false (e.g. stateHasGT=0 while still in registry). -->
      <set_value name="$shouldCheckCleanup" exact="false"/>
      <do_if value="$wasGTControlled and not $isGTControlled">
        <set_value name="$shouldCheckCleanup" exact="true"/>
      </do_if>
      
      <do_if value="$shouldCheckCleanup">
        <!-- CRITICAL: Check if ship has Assist order with GT commander (subordinate indicator) -->
        <!-- If default order is Assist and commander has GT, ship is still GT-controlled -->
        <do_if value="$currentDefaultOrder == 'Assist' and $hasGTCommander">
          <!-- Ship is subordinate with Assist order - still GT-controlled, don't cleanup -->
        </do_if>
        <do_elseif value="$shouldCleanup">
          <!-- FIX: Prevent duplicate signals - only send if we haven't already sent cancellation recently -->
          <!-- Check if cancellation signal was already sent recently (within last 10 seconds) -->
          <set_value name="$lastCancellationTime" exact="0"/>
          <do_if value="$state.$LastCancellationSignalTime?">
            <set_value name="$lastCancellationTime" exact="@$state.$LastCancellationSignalTime"/>
          </do_if>
          
          <set_value name="$timeSinceLastCancellation" exact="player.age - $lastCancellationTime"/>
          <do_if value="$timeSinceLastCancellation gt 10s or $lastCancellationTime == 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + this.assignedcontrolled.idcode + ' - GT order removed (detected in Hold Position order, new default order: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ')'" chance="100"/>
            </do_if>
            
            <!-- Update state to reflect GT order cancellation -->
            <set_value name="$state.$HasGTOrder" exact="false"/>
            <set_value name="$state.$OperationalState" exact="'orphaned'"/>
            <set_value name="$state.$ActiveTradeOrders" exact="0"/>
            
            <!-- Determine subordinate state from unified check -->
            <do_if value="$commanderExists">
              <set_value name="$state.$Commander" exact="this.assignedcontrolled.commander"/>
              <set_value name="$state.$CommanderHasGT" exact="$hasGTCommander"/>
              
              <do_if value="$hasGTCommander">
                <set_value name="$state.$SubordinateState" exact="'subordinate'"/>
              </do_if>
              <do_else>
                <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
              </do_else>
            </do_if>
            <do_else>
              <set_value name="$state.$Commander" exact="null"/>
              <set_value name="$state.$CommanderHasGT" exact="false"/>
              <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            </do_else>
            
            <set_value name="$state.$LastStateUpdate" exact="player.age"/>
            <set_value name="$state.$LastCancellationSignalTime" exact="player.age"/>
            <set_value name="$cleanupTraceId" exact="this.assignedcontrolled.idcode + '|WAIT_INIT|' + (player.age / 1s)i"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Miner-DIAG] WAIT_INIT ship=' + this.assignedcontrolled.idcode + ', default=' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ', current=' + (if this.assignedcontrolled.order? then @this.assignedcontrolled.order.id else 'NONE') + ', wasGT=' + $wasGTControlled + ', commanderExists=' + $commanderExists + ', commanderHasGT=' + $hasGTCommander + ', commander=' + (if $commanderExists and this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists then this.assignedcontrolled.commander.idcode else 'NONE') + ', trace=' + $cleanupTraceId" chance="100"/>
            </do_if>
            <!-- Detach intent latch: commander/default order state can be stale for a few seconds. -->
            <do_if value="not global.$GT_CleanupIntent?">
              <set_value name="global.$GT_CleanupIntent" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_CleanupIntent.{this.assignedcontrolled}" exact="table[
              $Active = true,
              $StartTime = player.age,
              $ExpireTime = player.age + 8s,
              $Source = 'WAIT_INIT',
              $TraceId = $cleanupTraceId,
              $DefaultOrderAtSignal = $currentDefaultOrder,
              $CommanderAtSignal = if $commanderExists and this.assignedcontrolled.commander? and this.assignedcontrolled.commander.exists then this.assignedcontrolled.commander.idcode else 'NONE'
            ]"/>
            
            <!-- MOD REMOVAL: Send GT_Ship_State_Update signal for mod removal system -->
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = this.assignedcontrolled,
              $UpdateType = 'GT_Order_Cancelled',
              $Source = 'WAIT_INIT',
              $TraceId = $cleanupTraceId
            ]"/>
            
            <!-- EVENT-DRIVEN: Always trigger orphaned ship check.
                 CheckShipOrphaned handles registry membership internally. -->
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
              $Ship = this.assignedcontrolled,
              $Source = 'WAIT_INIT',
              $TraceId = $cleanupTraceId
            ]"/>
            <!-- Also schedule delayed verification from WAIT_INIT in case commander/default order is still transitional. -->
            <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
              $Ship = this.assignedcontrolled,
              $CheckTime = player.age,
              $Source = 'WAIT_INIT',
              $TraceId = $cleanupTraceId
            ]"/>
            
            <!-- EVENT-DRIVEN: Also check if this ship has subordinates that might need checking -->
            <!-- When a commander loses GT order, subordinates will detect it via their own checks -->
            <!-- But we also check commander here in case it lost GT order -->
            
            <!-- NAME RESTORATION: Inline name restoration (AI scripts can't call MD library functions) -->
            <do_if value="$shouldRestoreName">
              <set_value name="$originalName" exact="null"/>
              <do_if value="$state.$OriginalShipName?">
                <set_value name="$originalName" exact="$state.$OriginalShipName"/>
              </do_if>
              <do_elseif value="global.$GT_Pilots? and global.$GT_Pilots.{this.assignedcontrolled.pilot}? and global.$GT_Pilots.{this.assignedcontrolled.pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{this.assignedcontrolled.pilot}.$OriginalShipName"/>
              </do_elseif>

              <!-- If detached cleanup was already signalled moments ago, do not emit a second abort signal from WAIT_INIT. -->
              <set_value name="$recentCleanupSignal" exact="false"/>
              <do_if value="global.$GT_CleanupSignalState? and global.$GT_CleanupSignalState.{this.assignedcontrolled}? and global.$GT_CleanupSignalState.{this.assignedcontrolled}.$LastCleanupTime? and (player.age - @global.$GT_CleanupSignalState.{this.assignedcontrolled}.$LastCleanupTime) le 2s">
                <set_value name="$recentCleanupSignal" exact="true"/>
              </do_if>
              
              <!-- Avoid duplicate abort-cleanup signalling:
                   when ship is still in GT registry, orphan-check path will emit the authoritative abort signal. -->
              <do_if value="$originalName and (not global.$GT_Ships? or not global.$GT_Ships.{this.assignedcontrolled}?) and not $recentCleanupSignal">
                <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                  $Ship = this.assignedcontrolled,
                  $Pilot = this.assignedcontrolled.pilot,
                  $Reason = 'GT order removed - restoring original name',
                  $OriginalName = $originalName,
                  $Source = 'WAIT_INIT',
                  $TraceId = $cleanupTraceId
                ]"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=WAIT_INIT cue=order.wait ship=' + this.assignedcontrolled.idcode + ' action=SIGNAL_ABORT_RESTORE_NAME'" chance="100"/>
                  <debug_text text="'[GT-State] Phase 7: Name restoration signal sent for ' + this.assignedcontrolled.idcode" chance="100"/>
                </do_if>
              </do_if>
              <do_elseif value="$recentCleanupSignal and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=WAIT_INIT cue=order.wait ship=' + this.assignedcontrolled.idcode + ' action=SKIP_DIRECT_ABORT_SIGNAL_RECENT_DETACHED_CLEANUP'" chance="100"/>
              </do_elseif>
              <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=WAIT_INIT cue=order.wait ship=' + this.assignedcontrolled.idcode + ' action=SKIP_DIRECT_ABORT_SIGNAL_REGISTRY_PRESENT'" chance="100"/>
              </do_elseif>
            </do_if>
          </do_if>
          <do_else>
            <!-- Duplicate guard blocks repeated cancellation state updates, but verification must still run. -->
            <set_value name="$cleanupTraceId" exact="this.assignedcontrolled.idcode + '|WAIT_INIT_DUP|' + (player.age / 1s)i"/>
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
              $Ship = this.assignedcontrolled,
              $Source = 'WAIT_INIT_DUP',
              $TraceId = $cleanupTraceId
            ]"/>
            <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
              $Ship = this.assignedcontrolled,
              $CheckTime = player.age,
              $Source = 'WAIT_INIT_DUP',
              $TraceId = $cleanupTraceId
            ]"/>
          </do_else>
        </do_elseif>
        <do_else>
        </do_else>
      </do_if>
    </do_if>
    
  </add>
</diff>
<?xml version="1.0" encoding="utf-8"?>
<diff>

  <!-- Prevent undocking for GalaxyTrader dock-wrapper orders -->
  <add sel="//aiscript[@name='orders.base']/attention/actions/do_if[@value='$undock?']" pos="before">
    <do_if value="global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{$object}? and global.$GT_ReturnHomeHoldUntil? and global.$GT_ReturnHomeHoldUntil.{$object}? and player.age ge global.$GT_ReturnHomeHoldUntil.{$object}">
      <remove_value name="global.$GT_ReturnHomeHold.{$object}"/>
      <remove_value name="global.$GT_ReturnHomeHoldUntil.{$object}"/>
    </do_if>
    <do_if value="global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{$object}? and global.$GT_IdleParkingHoldUntil? and global.$GT_IdleParkingHoldUntil.{$object}? and player.age ge global.$GT_IdleParkingHoldUntil.{$object}">
      <remove_value name="global.$GT_IdleParkingHold.{$object}"/>
      <remove_value name="global.$GT_IdleParkingHoldUntil.{$object}"/>
    </do_if>
    <!-- Mirror vanilla DockAt/DockAndWait: hold dock only when already at the wrapper target.
         Blanket blocking prevented undock after trades when academy/training DockAndWait
         needed to leave the trade station and fly to the training station. -->
    <set_value name="$gtHoldUndockForWrapper" exact="false"/>
    <set_value name="$gtWrapperDest" exact="null"/>
    <do_if value="$object.order?">
      <do_if value="$object.order.id == 'DockAndTrain' or $object.order.id == 'DockAndReturnHome' or $object.order.id == 'DockAndPilotExchange'">
        <do_if value="$object.order.$destination?">
          <set_value name="$gtWrapperDest" exact="$object.order.$destination"/>
        </do_if>
      </do_if>
      <do_elseif value="$object.order.id == 'DockAndWait' and $object.order.$callerid?">
        <do_if value="@$object.order.$callerid.id == 'DockAndReturnHome' or @$object.order.$callerid.id == 'DockAndTrain' or @$object.order.$callerid.id == 'DockAndPilotExchange' or @$object.order.$callerid.id == 'GTIdlePark'">
          <do_if value="$object.order.$destination?">
            <set_value name="$gtWrapperDest" exact="$object.order.$destination"/>
          </do_if>
        </do_if>
      </do_elseif>
    </do_if>
    <do_if value="$gtWrapperDest? and @$gtWrapperDest.exists">
      <do_if value="$object.dock? and @$object.dock.container == $gtWrapperDest">
        <set_value name="$gtHoldUndockForWrapper" exact="true"/>
      </do_if>
      <do_elseif value="$object.parkedat? and (($object.parkedat == $gtWrapperDest) or @$object.parkedat.hascontext.{$gtWrapperDest})">
        <set_value name="$gtHoldUndockForWrapper" exact="true"/>
      </do_elseif>
    </do_if>
    <do_if value="@$undock and ((global.$GT_ReturnHomeHold? and global.$GT_ReturnHomeHold.{$object}? and (not global.$GT_ReturnHomeHoldUntil? or not global.$GT_ReturnHomeHoldUntil.{$object}? or player.age lt global.$GT_ReturnHomeHoldUntil.{$object})) or (global.$GT_IdleParkingHold? and global.$GT_IdleParkingHold.{$object}? and (not global.$GT_IdleParkingHoldUntil? or not global.$GT_IdleParkingHoldUntil.{$object}? or player.age lt global.$GT_IdleParkingHoldUntil.{$object})) or $gtHoldUndockForWrapper)">
      <remove_value name="$undock"/>
      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
        <debug_text text="'[GT ORDER PATCH] Preventing undock for GT dock wrapper order on ship: ' + $object.knownname + ' order=' + @$object.order.id" chance="if $object.isplayerowned then 100 else 0"/>
      </do_if>
    </do_if>
  </add>

</diff>
# GalaxyTrader MK3 Order Icon Placeholder
# This should be replaced with a proper DDS texture file
# For now this prevents the "Could not find order icon" error
# 
# To create a proper icon:
# 1. Create a 64x64 pixel image in your preferred graphics editor
# 2. Save as DDS format with DXT5 compression
# 3. Replace this file with the actual DDS file
#
# The icon should represent trading/commerce activities ï»¿GalaxyTrader - Changelog
========================================

Version 0.15.4 (2026-07-03)

MK3 Fleet / cargo utilisation (stage 1):
FEATURE: **Home fleet cargo profile** (`md/gt_home_fleet_profile.xml`, `global.$GT_HomeFleetCargoProfile` in `gt_configuration.xml`) - per home-sector registry storing fleet-min required cargo volume (container / solid / liquid) from the strictest MK3-service ship at that home (smallest hold x effective cargotarget %). Rebuilds on game load (2s defer), `GT_HomeFleetProfile_Update` (order init, standalone home/cargotarget param edits, commander settings sync with old+new home buckets), and `GT_Ship_Order_Aborted`.
CHANGE: `lib.gt.live.search` - new `searchPurpose` (`cache_refresh` vs `direct_live`) and `cargoTargetPercent` params; offer queries use per-ware `totalvolume` min and `mintotalvolume` max. Cache-refresh scans use fleet-min thresholds from the home profile; direct-live scans use this ship's cargotarget % and current free cargo per transport bucket.
CHANGE: MK3 cache-refresh live search passes `searchPurpose=cache_refresh` and ship cargotarget; sell-only legs stay `direct_live`.
CHANGE: `order.trade.galaxytrader` - persists `this.$gt_cargotarget` / `this.$effectiveCargoTarget` across cooperative `<wait>` yields; cargo-util filters read instance vars after cache/live search resume instead of lost locals.
CHANGE: Commander settings sync inherits **cargotarget** from the commander MK3 order (Assist subordinates included).

Search Engine / cache:
CHANGE: Cache entries stamp stable idcode keys at write (`$SellSectorId`, `$SupplierStationId`, `$BuySectorId`; existing `$DeliveryStationId` unchanged) - object refs on offers/stations/sectors die on refresh but idcodes survive.
CHANGE: New MD libraries `GT_ResolveSectorByIdcodeInRange` and `GT_ResolveStationByIdcodeInRange` (`gt_libraries_general.xml`) - scan sectors from home via `find_sector_in_range`, match `sector.idcode` / `station.idcode` (incl. player build-storage base idcode).
CHANGE: `lib.gt.cache.search` - memoized idcode re-resolution for buy (`$SupplierStationId`) and sell (`$DeliveryStationId`) stations; `$reSellSector` from live `$SellSector` or `$SellSectorId`; relaxed `$purgeReResolvable` / write-time stale gate no longer requires live `$SellSector` when idcodes are present. MK4 cache search/write gets the same idcode path and gate.
FIX: `lib.gt.cache.search` idcode resolve memos no longer store `null` table values (X4 rejects them) - failed station/sector/offer lookups use `$stationIdResolveMiss` / `$sectorResolveMiss` and `$Resolved = false` delivery memo rows instead of memoizing null; stops `Failed to set table[]... to value null` spam when stale cache idcodes (e.g. destroyed/moved stations) cannot be re-resolved.
FEATURE: **Per-ship cache read route scoring** (`lib.gt.cache.score_for_ship`) - MK3 cache hits rank by blacklist-aware `shipâ†’buy + buyâ†’sell` (`$ShipScore`) for the requesting ship; shared `global.$GT_TradeCache` rows keep home-based `$Score` only (ephemeral `$ShipScore` / route fields stripped on write).
CHANGE: MK3 `lib.gt.cache.search` - full-pool per-ship filter pass, then ship-route score/sort/truncate (no early break on home-sorted discovery order); threads order `distancePenalty` and `blacklistGroup` into cache search.
CHANGE: MK3 live cache-miss path (`SearchMethod: live_ship_route`) - executable tradematch survivors scored in-process via `score_for_ship`; `lib.gt.score.trades` optional `useShipRouteScore` applies priority-ware boost and diversify on `$SelectionScore` without mutating home `$Score`; fresh-offer re-check and validation unchanged.
CHANGE: MK3 live cache refresh writes **all** executable tradematch survivors into the home pool (not `MaxTradesToReturn` home top-N); `MaxTradesToReturn` still caps the validation list for MK3 and remains used by MK4 orders.
CHANGE: `lib.gt.cache.write` (MK3) - evict over-cap pool rows by oldest `$CachedAt` instead of lowest home `$Score` tail so far-from-home valid rows are not dropped solely for weak home rank.
CHANGE: `lib.gt.score.selection_sort` - when `$ShipRouteScored`, keep priority-adjusted `$SelectionScore` from `score.trades` instead of replacing with raw `$ShipScore` (avoids double proximity penalty on cache/live ship-route paths).

GT Diagnose:
CHANGE: MK3 **Home Fleet Cargo Profile** section - cohort membership, per-ship required/free volume by bucket, profile registry status/age, fleet-min values, and which ship sets the fleet-min for the home sector.
CHANGE: Cache entry sell-station re-resolution uses the same idcode libraries as runtime cache.search when offer/sector refs are stale.

MK3 Trading / paired trades:
FIX: **Buy-completion sell-leg gate** (`md/gt_buy_tracking.xml`) - after each buy leg, inspects the queued sell with `find_buy_offer` + `tradepartner` (never cancel-first). If the buyer offer is universally dead (partner gone or `not .available`), cancels the stale sell `TradePerform`, clears pending trade/UI credits due, and signals `GT_Trade_Failed` so the ship enters cargo disposal immediately instead of flying to a dead destination (`ERR_TRADEOFFER_INVALID`). Transient `offeramount.{ship}==0` with `.available` true is left alone (pending order still holds the reservation).
CHANGE: `order.trade.galaxytrader` - trade failed with cargo aboard skips the post-trade market-update wait and resumes `main_loop` for clearance/disposal.

MK3 Cargo clearance:
FIX: Cargo disposal (`sell_only`) is **live-only** - scheduler enqueues clearance straight to the live pool (`ForceLiveSearch`); MK3 AI skips cache read/write on clearance (one ware, stale cache not used).
FIX: `lib.gt.live.search` sell_only scans bound volume by **cargo on board** (not free hold) so full holds after a failed paired sell still return buy offers.

Galaxy Miner:
FIX: **Primary-station cargo sell** (`order.mining.routine.gt` sellwares) - demand-first delivery (`overflow=0`) now queries each `primaryTargetStations` buyer directly (vanilla `find_buy_offer` + tradepartner, same loose scan GT Diagnose uses) and merges those offers before the capped sector-wide live search (`maxOffersPerWare=20`). Fixes full holds stuck on `FAIL_NO_BUYER` with `skipPolicy=N` when only NPC buyers filled the live-search cap and the home shipyard never entered the candidate set. Primary policy match also resolves `buyer` and build-storage `base` for shipyard offers.

GalaxyTrader MK4-2:
FIX: Fleet subordinates woken after a commander live-search cache fill now retry **cache** first instead of re-entering live search - `HandleMK42CacheUpdated` marks waiters with `$LiveWaiterWakePending`; scheduler forces cache phase on wake (clears `$ForceLiveSearch`); `GT_TradeSearch_Reset` clears stale `mk42PolicyNeedsLiveSearch` from earlier ST-only cache misses.
CHANGE: Trade validation respects class slider priority when **Stations** dominates **Build Storage** - build-storage-first reorder and strict build-storage-first validation run only in BS-dominant mode (same rule as the ST-only cache gate), so live scoring order is preserved when ST slider is higher.
CHANGE: **Buy from Player** / **Buy from Faction** slider = 0 now excludes that supplier type during MK4-2 live search collection (`includePlayerSellOffers` / `includeNpcSellOffers` on `lib.gt.mk42.live.search`) - engine-level `match_seller` owner filters skip NPC or player supplier sector scans instead of collecting offers and dropping them at tradematch/validation.
CHANGE: **Strict class-tier scoring** (`lib.gt.mk42.score.trades`) - when max/min class slider ratio is >= 5 (e.g. BS=10 ST=1), class priority is enforced via a tier gap so high-urgency ST offers cannot beat weak BS offers on fine score alone; close ratios (e.g. BS=5 ST=4) still use fine score only so demand can tip.
CHANGE: **Player-station live search** (`lib.gt.mk42.player.stations`, `lib.gt.mk42.live.search`) - MK4-2 delivery/supplier discovery uses one `find_station_by_true_owner` (+ standalone build storage) filtered by gate distance from home (`jumpDistanceBuy` / `jumpDistanceCoverage`); per-buyer `find_buy_offer` and per-station `find_sell_offer` replace sector-by-sector scans; SF=0 skips NPC supplier sector discovery entirely.
FIX: **Scheduler cache HIT path** (`order.trade.galaxytradermk42` `trade_found`) - subs and cache-first ships re-score with MK4-2 priorities before selection sort / completion-first reorder; strict-tier ST-only cache rows force live search instead of validating stale ST-first cache order.
FIX: **Gate-crossing debug error** (`interrupt.changedsector`) - GT override removes duplicate `chance` rolls on `$changedsector_previoussector` that caused `Property lookup failed` with MK4-2 debug level 1 (`debugchance=50`).

Developer tooling:
FEATURE: `scripts/analyze_mk42_scoring.py` - log analyzer for MK4-2 tradematch / score-trades / validation pipeline samples (per ship, search session, ware, and delivery class); strict-tier final-score estimation aligned with live `lib.gt.mk42.score.trades`.

Version 0.15.3 (2026-07-01)

MK1 Station Trader:
CHANGE: Buyer/supplier price filtering decoupled from global MK3 Trading Price Ranges - new per-order **Buyer Price Range** slider on the GalaxyTrader MK1 default order (UI 0-200, default 90 = slightly below average / normalized -0.1, 100 = average / 0.0, maps to -1.0..+1.0). Sell search uses `buyPriceMin`; supply search uses inverted `sellPriceMax`. Param propagates via Assist inheritance and promotion recovery.
CHANGE: Queue-time logbook messages split by role - export sells use station-trader export wording (3103 single leg, 3113 multitrade) with NPC buyer as `Sector - Stationname(IDCODE)`; supply runs use fill-% fallback (3102), NPC sourcing under home buy cap (3110), or player-owned source route-only (3111).
CHANGE: MK1 NPC supply queue messages report home-station buy cap vs source price (3110 under-cap savings per unit and total) instead of trader profit; price snapshots pass from tradematch even when delivery offer handles are stale at queue time.
FIX: Supply home-station buy offers no longer rejected when raw offer `.amount` is 0 but the station still has demand - delivery leg resolves via `mk2_player_offer` (tradepartner + ignore-rules fallbacks) and accepts `offeramount.{ship}` instead of `.amount`, matching vanilla/MK2 (player-faction-only trade rules and configured buy prices).
FIX: Supply queue logging no longer falls through to cargo-sale template 3100 when delivery offer handles are invalid - `$IsMk1Supply` is evaluated before `$buyOfferValid`.
FIX: MK1 supply queue messages use explicit `$BuyStation` (source) / `$SellStation` (receiving home) for station labels - remapped offer handles had source and destination swapped in 3110/3111/3102 text.
FIX: MK1 export-trade dock preflight no longer errors after `lib.gt.dockcheck` yields - sequential buy/sell station checks replace list loops that lost locals across `run_script`.
FIX: MK1 sell-phase pathfinding and `lib.gt.live.search` inputs guard missing/null `$SellSpaces`; live search normalizes sell/buy space lists to `[]` and avoids non-short-circuiting null `.count` checks after resume.

Galaxy Miner:
CHANGE: Check Demand First OFF (stockpile mode) now runs a cargo-first willing-buyer scan before full-bay standby - when carried minable wares have a primary station below the overflow threshold, the miner delivers first instead of standing by with a full hold.
CHANGE: Demand-off full-bay standby is limited to cases with no willing primary buyer and overflow sell disabled; overflow-wait and overflow-no-opportunity standby paths publish `GT_Miner_Diag_Update` snapshots (`demand_off_full_bay`, `overflow_wait`, `overflow_no_opportunities`) for live diagnose.

GT Diagnose:
CHANGE: MK1 section uses the order **Buyer Price Range** slider (not global MK3 price ranges), reports raw vs policy buyer counts, and lists MK1 Export Pairs with per-pair rejection reasons.
CHANGE: Miner policy and verdict logic now mirror runtime demand-station auto-discovery (sell-range scan from home anchor when `stationList` is empty) - Configured Target Stations vs Runtime Demand Stations, so empty `stationList` setups no longer show misleading `Target Stations: 0` / false `POLICY BLOCKING`.
CHANGE: Miner section adds Cargo-first Willing Buyer, Live Stall Reason (snapshot), and a demand-off note explaining Check Demand First scope (mining gate vs sell policy).
CHANGE: Verdicts for demand-off full-bay stall and demand-off deliver-before-mine cases; overflow-wait stall scoring applies only in demand-first mode; coordination Intent Phase appends live `stall:` reason from miner snapshots.

Global Settings / Cheats (testing):
FEATURE: New **Cheats** section at the bottom of Global Settings (after state abbreviations) - developer testing tools with a deliberately discouraging section title and tooltip.
FEATURE: **GT ships invulnerable** / **All player ships invulnerable** - mutually exclusive toggles via `set_object_min_hull` / `set_object_min_shield` at 100%; GT mode scoped to `GLX_ShipIsInGTService` ships; stations never affected; reconciles on game load and every 60s while active.
FEATURE: **Reveal universe for GT testing** - one-shot fog-of-war clear, all stations known, faction trade-subscription licences, and galaxy-wide trade subscriptions (vanilla Test_Trade pattern).
FEATURE: **Max registered GT pilot XP** - sets every `global.$GT_Pilots` entry to level 15 with max XP, marks all training gates complete, clears blocks, and refreshes ship names; skipped when **Use Vanilla XP Only** is enabled.
CHANGE: **Cache Query Max Entries** slider restored in Global Settings â†’ Performance (after AI Yield Interval, 1-200, default 50) - caps the per-home-sector cache pool on write trim and read scan; tooltip updated to match runtime behavior.

MK3 Fleet / Assist:
FIX: Promotion Fix no longer assigns GalaxyTraderMK3 to non-GT fleets (e.g. TaterTrader) during commander promotion or order gaps - skips restore when the inherit target is not a protected GT order; removed sector-default MK3 invention fallbacks; cache/AI fallbacks require live GT context (orderdef, Assist baseorder, or commander `$IsGTActive`).

GalaxyTrader MK2:
FIX: Destroyed source/target stations no longer spuriously idle the trader or spam notifications - removed stale pre-refresh `this.$sourceStation` gate that blocked `defaultorder` sync and survivor recovery when the cursor source was destroyed but other stations remained.
FIX: Invalid stations are pruned from `sourceList` / `destList` on detection (`edit_order_param` on the MK2 default order, including commander order for Assist subordinates); legacy `sourceStation` param cleared or repointed to the first survivor.
FIX: Station-destruction notifications respect MK2 notification verbosity, fire once per event (partial removal vs all-invalid standing by), and only on the ship that owns the MK2 order (no duplicate alerts from subordinates).
CHANGE: Text IDs 20203/20204 now report all-invalid standing by (not order cancelled); new 20205/20206 for partial source/destination removal from the distribution order.

Search Engine / cache:
CHANGE: Per-ship cache scan rotation (`cacheReadOffset` plus post-sort fleet spread) so co-located MK3 ships no longer all validate the same top cache row first.
CHANGE: Read-time cache purge on zero-hit scans removes globally dead rows, per-ship average-price band failures, and min-cargo-util failures that diagnose "Cache Runtime Readable" does not check - shrinks stale pools without waiting for TTL cleanup.
CHANGE: Cache-waiter coordination for shared home sectors - `CacheWaiterFirstParkedAt` accumulates wait time across scheduler wake cycles; stale waiters escalate to one live refresh per home (`CacheLiveRefreshPendingByHome`, single ship promoted via `ForceLiveSearch`) instead of mass live-queue promotion.
CHANGE: Cache search done signals carry `$PoolSizeAfter` so scheduler miss handling and FailedShips clear use the post-purge pool count.
FIX: `lib.gt.cache.search` MK4 sector-key reconciliation no longer errors when `global.$GT_TradeCacheMK4.keys` is null - count is read inside a guarded `do_if` (X4 does not short-circuit `and`; `$mk4CacheKeys? and $mk4CacheKeys.count gt 0` threw `Property lookup failed` on empty MK4 pools).

Version 0.15.2 (2026-06-30)

Training / Trading Academy:
FIX: `[BL]` ship prefix no longer sticks after academy or natural training completes - `GT_ClearTrainingBlocked` now clears stale `$PausedWithTrainingNeeded` / `$PausedBlockedLevel` placeholders saved when the GT order was paused for `DockAndTrain`; `RestorePausedTrainingStateIfNeeded` skips restore when that level is already in `$TrainingCompleted`; `Initialize_Pilot_Data` uses the shared restore library.
FIX: `HandleAbortTraining` no longer errors on `Property lookup failed: $BlockedLevel` when `HandleStartTraining` already handled `AcademyFundsAborted` (upstream unblock + rename + abort echo) - duplicate abort is ignored; remaining paths use safe `@` read for `$BlockedLevel`.
FIX: Academy/natural training course timer now waits the full advertised duration at dock - `order.dock.train` yields 1ms after `GT_Start_Training`, rebuilds wait time via `(duration / 1s) * 1s`, uses matching `min`/`max` on the wait (registry time values were completing in ~1/12 of the promised seconds), and only applies save/load resume when elapsed gt 1s.
FIX: `DockAndTrain` ships can undock from a trade station after a queued trade leg and fly to the academy station - `orders.base` undock guard now blocks only when already docked at the training order destination (matches vanilla `DockAndWait` caller-id behavior).
FIX: Commander bonus XP no longer bypasses mandatory training gates - subordinate trade XP that pushes a fleet commander's total past a `RequiredLevels` threshold (e.g. 248 -> 250 for Lv.3) now runs the same level-up gate as direct trade XP (`GT_ProcessLevelUpTrainingGate` in `gt_libraries_general.xml`; shared by direct awards and commander bonus in `ProcessSingleXPEvent`).
FIX: `DockAndTrain` no longer logs a false "Training order was aborted" / fires `GT_Abort_Training` while the ship is still flying to the station - spawning child `DockAndWait` pauses the parent script; `on_abort` now detects that transit handoff (same pattern as `GTIdlePark`) and skips abort signals until the dock leg finishes or the order is genuinely cancelled.

Version 0.15.1 (2026-06-29)

Threat Avoidance / Blacklist:
FIX: Dynamic blacklist fleet apply no longer crashes when exactly one operational non-subordinate GT ship is registered - MD now stringifies the ship list before `GT_Blacklist.ApplyToFleet`; Lua accepts a single numeric component id as well as comma-separated ids.
FIX: Threat blacklist lifecycle - sectors clear when tracked enemies leave, are destroyed, or player defenses outmatch hostiles; defense-station build clears via shared re-evaluation; `move.generic` covers sector-change and destroy paths plus combat-fleet arrival re-check.
FIX: Manual **Clear All Blacklisted Sectors** no longer leaves stale Lua `blacklisted_sectors` entries that `CleanupExpired` could resurrect into the vanilla blacklist without a new logbook message; wipe now resets MD threat table, tracked-enemy group, epoch snapshot, and pushes an empty Lua payload.
FIX: `UpdateBlacklistOnThreat` always syncs Lua (including empty payload when the threat table is cleared).
FIX: `TrackEnemyShipDestruction` no longer errors on missing `global.$GT_TrackedEnemyShipsGroup` at load - group is created at MD script start; destroy listener filters tracked ships in actions instead of `group=` in cue conditions.
CHANGE: Only combat ships (`purpose.fight`) may trigger sector blacklisting - civilian GT ships detecting hostiles no longer add sectors to the dynamic blacklist (fleet warnings unchanged).

GT Diagnose:
FEATURE: Mod version shown in Ship State (below VERDICT) - reads `global.$GT_ModVersion` and `global.$GT_ModContentVersion` set at load in `gt_global_settings.xml`.


Version 0.15.0 (2026-06-28)

Training:
CHANGE: Station search for auto-training, manual training, and Trading Academy no longer caps candidates by pilot-tier jump distance â€” ships dispatch to the nearest reachable trading station (reachability, blacklist, and dock preflight unchanged). Trading order jump-distance limits are unaffected.
FIX: DockAndTrain no longer tight-loops when the saved destination ref is invalid (component.{0x0L}) - `order.dock.train` validates `$destination.exists` (init + attention), cancels the order on invalid destination or docking failure, and load recovery cancels stale DockAndTrain orders then re-dispatches station search.

Docking (unified preflight):
FEATURE: Shared dock preflight libraries â€” AI `lib.gt.dockcheck` and MD `GT_CanDock` (`purpose`: `trade`, `service` / `service_ai`, `dual`, `permission_only`) return `$CanDock` + `$Reason`; `GT_CanDockForTrade` is now a thin `trade` wrapper.
CHANGE: Trade-leg validation uses **trading dock probe** (`find_dockingbay` + `trading="true"` + not-enemy), aligned across MK3/MK4, cache validation, idle park, and return-home â€” replaces MK3 early `dockingallowed`-only path and scattered inline `find_dockingbay` blocks.
CHANGE: **Capital parking preflight** inside `purpose=trade` â€” capital ships at carrier/resupplier (not enemy, not highway) when no trading bay matches vanilla `order.dock` park fallback.
CHANGE: Maintenance, training, and redistribute station filters use `purpose=dual` (service bay + docking permission + resupplier bypass) via `GT_CanDock`.
CHANGE: Idle park, return-home, and matching `DockAndWait` paths pass `allowPlayerOnly=true` on trade preflight.
PERF: Optional per-search **dock memo** (`this.$gt_dockMemo`, `useMemo=true`) on MK2/MK3/MK4 hot paths â€” skips redundant probes for the same station within one search pass; MK2 init once per scoring pass; `lib.gt.tradematch` supply mode shares the same memo.
REMOVED: `mk2_can_dock` mode from `lib.gt.tradematch` â€” all callers use `lib.gt.dockcheck` directly.
REMOVED: Dead `GT_BuildDockingCache` and cache `BuyDockCaps` / `SellDockCaps` validation (caps were never written; per-ship trading dock probe replaces them).

MK4:
completely rewritten as a new defaultorder MK4-2. old MK4 marked as deprecated to keep old saves running
will be entirely removed/replaced in future updates

MK2 Trader:
FIX: Blacklist parity with MK3/MK4 - station-pair evaluation and pre-queue validation use shared `lib.gt.blacklist.validate_lane` (map blacklists, GT threat sectors, whitelist, escape-aware sell rules, optional blacklist-aware path). Stops instant `TRADEPARTNER_BLACKLISTED` dock/trade abort loops on configured lanes in blacklisted sectors (e.g. Eighteen Billion, Bright Promise). Order-completion wait listens for `GT_Trade_Failed` so failed legs no longer count as a successful cycle.
FIX: Cargo clearance (pre-cycle hold dump) â€” each configured buyer is preflighted with `lib.gt.blacklist.validate_lane` (`sellOnly`: object/sector/threat blacklists, escape-aware sell rules, shipâ†’buyer path) and `lib.gt.dockcheck` before `create_trade_order`; blacklisted or unreachable partners are skipped instead of doomed `TRADEPARTNER_BLACKLISTED` / no-path dock failures. Also tags `global.$GT_Ships.$CargoDisposal`, `[CLEARANCE]` naming like MK3/MK4, `internal=true` for player-owned buyers; flag cleared when cargo empties or on order abort.
FIX: Optional home sector â€” when `homeStation` and `homeSector` are both unset, MK2 snapshots `ship.sector` at order apply into `homeSector` (persisted via `edit_order_param`) and `GT_AIParameters.$HomeBase` so `GT_GetHomeSector` and ship naming work without error spam.
FIX: Storage threshold clamping no longer forces `min < static < max` on unidirectional routes â€” each threshold is range-clamped only (e.g. 98/0/0 stays 98/0/0 instead of being rewritten to 98/99/100 at init, which froze traders that should drain sources fully). The ordering ladder is re-applied **only in bidirectional mode** (prevents ping-pong when every station can supply and receive). Per-cycle `main_loop` normalization plus v7 `<patch>` migrates saves that persisted the old clamped values.
FIX: `lib.gt.score.trades` now selects the highest-scoring candidate even when the score is `<= 0` â€” candidates are already fully validated upstream (profit/ROI/offers/amount); the score is ranking-only. A `0`-init floor with `gt 0` dropped every non-positive candidate and reported "no trade selected" despite a non-empty candidate list (common on large-hold ships moving small station amounts or under fleet usage penalty).

GT Diagnose:
FIX: MK2 verdict uses the **station-pair eval** (`$mk2PairPass` / configured source-dest/ware mesh) instead of the sector-wide Search Summary â€” MK2 never runs a range-wide offer scan, so a generic "791 pairs available" verdict (often naming stations outside the MK2 config) was misleading.
CHANGE: MK2 pair evaluation models bidirectional supplier/customer unions, ware-exchange (`ignoreoffersettings`) storage discovery on offer gates, and the same conditional threshold normalization as runtime (independent thresholds vs bidirectional ladder). Storage-threshold display notes which mode applies.

Trade scoring:
FIX: `lib.gt.score.trades` â€” see MK2 Trader (shared library; also affects MK3/MK4 diversify path consistency).
FIX: `lib.gt.tradematch` fast-return modes (`mk2_player_offer`, `mk2_storage_pair_score`, offerdiag, ware fairness, etc.) cooperative-yield before return â€” fixes AIDirector infinite wake-request loop when MK2 scoring runs many nested `run_script` calls per cycle.

Search Engine / cache:
FIX: `lib.gt.cache.search` / `lib.gt.cache.write` / `lib.gt.mk42.cache.search` read-time and write-time purge loops guard `remove_value` with live list bounds â€” stale-count snapshot can exceed current pool size when cooperative yields let MD or parallel ships shrink the list first (`Failed to remove ... .{2949}` on large home-sector pools).

Threat avoidance / dynamic blacklist:
FIX: Lua blacklist init race on save load â€” `gt_blacklist_manager` fired `Ready` at the start menu before MD was listening, so `GT_Blacklist.Initialize` never ran and every `Update` was silently dropped (`initialized=false`). MD now bootstraps via `BootstrapBlacklistLuaIntegration` on `event_game_loaded` / `event_player_created` / `event_game_started` (Lua `Ready` kept as secondary path without fleet assign).
FIX: `GT_ThreatAvoid_Fleet` is auto-assigned to operational GT commanders/solo ships on session start and on new ship registration when **Use Dynamic Blacklist** is enabled (manual settings button still available for refresh).
FIX: **Sector Blacklisted** logbook (`{77000,3222}`) is written only when a sector is newly added to the blacklist â€” repeat threat warnings for an already-blacklisted sector no longer spam duplicate entries.
CHANGE: `gt_blacklist_manager.lua` optional operational trace (`CONFIG.DEBUG_MODE` in file; set `true` for init/update/FFI diagnostics). Errors and warnings still log when disabled.

XP / fallback instrumentation:
FIX: `HandleUpdatePilotXP` no longer errors on `global.$GT_FallbackActivations` counter updates â€” MD cannot mutate `global.$Table.{key}` in place (even with split read/write); `GT_IncrementFallbackActivation` copies to a local table, increments, then assigns the whole global back (`gt_xp_training.xml`, `gt_order_monitor_bridge.xml`).

Trade failure routing:
FIX: `GT_FailedSectorPairs` writers unified â€” `gt_trading_ai.xml` (legacy list + `append_to_list`) and `gt_trading_signals.xml` (nested table in-place writes) both used the same global with incompatible shapes, causing `Failed to set [list].{sector}` / `Property lookup failed` when `ProcessTradeFailureQueue` recorded `ROUTE_PATH_CHANGED` after `TRADEPARTNER_BLACKLISTED` list entries. Shared `GT_RecordFailedSectorPair` / `GT_NormalizeFailedSectorPairsSectorEntry` (copy-mutate-writeback) plus AI `lib.gt.failed_sector_pairs` for MK3/MK4 cache prefilter; legacy list entries migrate on read/write.

Version 0.14.15 (2026-06-25)

GT Maintenance:
CHANGE: S/M traders (no unit bay) now restock laser towers via deployable ammo storage when **Restock Laser Towers** and defensive equipment are enabled â€” tower target follows the Balance Profile % of deployable capacity with the same unified threshold as L/XL unit-bay towers; existing deployables are preserved on every equip trip so CM-only resupply does not clear towers.

MK1 Trader:
FIX: Return-home and normal trade orders no longer tight-loop failed dock attempts when the home station has no operational trading dock (e.g. under construction or last dock destroyed) â€” uses shared `lib.gt.tradematch` `mk2_can_dock` (operational trading bay, ship size, non-enemy).
FIX: **Return Home Between Cycles** pre-checks home dock feasibility before queueing `DockAndReturnHome`; failed dock clears `$GT_ReturnHomeHold` and surfaces `orderfailed` instead of instant `DockAndWait` retry storms (including while paused).
FIX: Export, supply, and queue-build paths gate on home dock availability each main-loop pass (`waitTimeNoTrades` backoff when undockable); matched export legs and supply sources also verify buyer/seller docking before `create_trade_order`.

Idle Parking:
FIX: `GTIdlePark` and `lib.gt.idlepark` `trigger` use the same `mk2_can_dock` checks (replacing weaker `find_dockingbay` without `trading="true"` / relation match); idle parking is not queued when no dockable station exists in home/sector fallback.
CHANGE: Shared `resolve_park_station` helper in `lib.gt.idlepark` â€” home station first, then player-owned sector stations, then friendly NPC stations.

Galaxy Miner:
FIX: Demand-first ware selection now requires a **discovered** mineable asteroid (per-sector `find_closest_resource` probe during scoring) before a ware can win â€” `sector.resources.exists` alone no longer counts as reachable. Undiscovered high-demand wares (e.g. Nividium) are skipped so the miner picks the next mineable demand ware (e.g. Ore) instead of standing by on a dead selection.
FIX: Downstream `$wareReachable` / CARGO-FIRST / overflow / physical-storage alt-ware gates use the same mineable definition (parity with diagnose **Would Select**). Locate failure clears the failed wareâ€™s mineable flag before re-score.

Version 0.14.14 (2026-06-25)

MK1 Trader:
FEATURE: Multitrade minimum leg volume gate â€” secondary and tertiary sell legs must carry at least one-third of the configured selltarget fill (max feasible volume before buyer cap); blocks token padding runs (e.g. 100 units on a near-full hold). Selection still picks the highest planned volume among admitted candidates; admitted legs load max feasible amount (buyer-capped). Multitrade expansion skipped when selltarget is 0.

Galaxy Miner:
PERF: Unified resource locate (`lib.gt.miner_find_target`) â€” single gather-sector pass with early break, optional per-sector resource-probe branch when a probe is present, relaxed second pass (`minrating=1`), and hostile-sector fallback; replaces routine probe pre-scan + wareÃ—sector `do_all` loops + legacy old-method fallback.
PERF: Outer GalaxyMiner scoring ranks wares via `sector.resources.{ware}.exists` only (no per-ware `find_closest_resource` during the scoring loop); one locate runs after `$selectedWare` is chosen. Gather-sector list is built once and reused for locate + `order.mining.routine.gt` via `precomputedgatherspaces`.
PERF: Cooperative frame yields after each miner `find_closest_resource` / `find_resource` â€” `global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs` (default 15; clamp 1â€“100). Reduces frame spikes when many miners search probe-less sectors.
FIX: Fleet locate/search desync uses `<wait min="1ms" max="19ms"/>` instead of `this.ship.id % N` â€” ship components have no numeric `.id` (runtime Property lookup failed).
FEATURE: In-routine physical storage gate (level 6+ pilots) â€” new advanced order slider **Physical storage abort %** (`physicalStorageAbortPercent`, default 20; 0 = disabled). Before each collect, compares station physical stock plus live bay cargo from relevant fleet miners against current physical stock Ã— (1 + headroom%); stops mining the slice ware when projected fill would exceed that threshold, sells existing cargo or returns to outer scoring to switch ware/wait. Independent of overflow threshold; uses real cargo counts (not intent estimates). Skipped in stockpile mode (`checkDemandFirst=false`). Shared logic in `lib.gt.miner_physical_storage_gate`; gate runs at routine loop entry, before `MiningCollect`, and at outer slice entry before `run_script`.
FIX: Physical storage gate abort threshold uses integer-safe `(physical Ã— (100 + headroom%)) / 100` â€” expression `1 + (headroom% / 100)` truncates to 1 for typical slider values, collapsing headroom to zero.
FIX: Save-loaded GalaxyMiner orders backfill `physicalStorageAbortPercent` / `this.$physicalStorageAbortPercent` via script v10 `<patch>` plus lazy `main_loop` guard â€” `<init>` does not re-run on load, so running orders without the patch threw `Property lookup failed` on first gate evaluation.
FIX: `lib.gt.miner_same_fleet` is now a non-blocking interrupt library (`MinerSameFleetMatch`); physical storage gate and `order.trade.galaxyminer` use `include_interrupt_actions` instead of `run_script` in fleet-cargo tally and alt-ware scan loops â€” fixes AIDirector infinite wake-request loop on `lib.gt.miner_same_fleet` / `lib.gt.miner_physical_storage_gate`.
REMOVED: Auto-deploy resource probes â€” order settings **Auto Deploy Resource Probes** and **Probe Stock Target** removed along with active-scout fallback, post-slice probe DEPLOY/RECOVER/BUY lifecycle, maintenance probe restock, and probe param forwarding in `order.assist` / ghost-order restart (`gt_core_system`). Collector-drone restock (`maxCollectorDronesToBuy`) unchanged. Legacy saves: stale probe instance vars, scout state, and `global.$GT_AIParameters` probe keys cleared once on first `main_loop` pass; manually deployed probes still work for engine yield scans and diagnose listing.

GT Diagnose:
CHANGE: Galaxy Miner diagnose adds **Primary Station Cargo** rows (physical units, storage target, % vs overflow threshold), **Physical Storage Gate** status (slider %, active/inactive reason), plus per-reason **Policy Rejection Breakdown** and sample rejected buyer offers in the sell-offer section.
FIX: Miner resource-scan candidate wares use a fleet-stable offer pool (commander primary-station buy offers + snapshot ware + cargo) so commander and subordinate diagnose reports match regardless of momentary bay contents.
FIX: Miner sell-offer and **Clearance** scans use per-ware overflow mode (`diagMinerWareHasPrimaryCapacity`) instead of the ship-level overflow snapshot â€” a full primary (e.g. Ice at 94%) no longer mis-applies primary-only rejection to other wares or falsely reports zero viable clearance buyers when overflow sell-to-others is enabled.
FIX: Miner verdict priority â€” `MINER OPERATIONAL` when demand ranking selects a ware with primary capacity takes precedence over global `POLICY BLOCKING` driven by another ware's rejected offers.
FEATURE: Miner cargo-bay verdicts â€” `MINER STUCK (full bay)` when every carried minable ware has zero policy-passing buyers; `MINER BLOCKED (full bay)` when the bay is full but at least one carried ware can be sold (notes unsellable dead cargo that will remain); `MINER OPERATIONAL (suboptimal)` when unsellable cargo wastes bay capacity but mining can continue (per-ware bay-% in verdict text).

MK2 Trader:
FIX: Fleet subordinates already assigned under Hold Position (Assist) now inherit GalaxyTraderMK2 when the commander receives that default order â€” `ProcessCommanderGTReactivation` restarts Assist with the commander `baseorder` instead of only re-registering pilots, so manual reassignment is no longer required.
EXPERIMENTAL FEATURE: Internal storage transfers (e.g. research-facility buffer â†’ trading station) can run via vanilla ware exchange when **Ignore Offer Settings** is enabled â€” `GetWareExchangeTradeList` resolves the deal and `AddTradeToShipQueue` queues pickup then delivery legs (buy then sell), avoiding synthetic `TradePerform` orders on invalid offers. **Ignore Trade Rules** and **Ignore Offer Settings** are independent: ware exchange follows offer settings; station trade-rule bypass follows ignore rules only.
FEATURE: New order setting **Ignore Offer Settings** (`ignoreoffersettings`) on GalaxyTraderMK2 â€” inherited by Assist subordinates with other MK2 params.
FIX: Fleet subordinates on the ware-exchange path use physical storage fill ratio for source/destination discovery so commander in-flight reservations no longer block eligible buffer pickups.
FIX: Ware-exchange trades now verify docking (trading dock, or storage dock for player-owned internal legs) before queueing â€” skips pairs/stations the ship cannot dock at instead of reserving wares on unreachable stations.
FIX: **Bidirectional Mode** now evaluates trades in both directions â€” any assigned station can supply or receive (deduped station union, pair-mesh autowares, role-agnostic pair loop). Previously the flag only boosted same-ware return scoring and queued a post-delivery return leg; reverse-direction wares were never searched.
FEATURE: **Lane continuity** scoring prefers picking up at the station the ship just delivered to (`lastTradeDestination`) â€” medium soft bias via `routeLaneBonus`, pilot-scaled remote penalty, and extra gate cost for flying elsewhere. Works with bidirectional off when the same station is listed as both source and destination; not tied to fleet coordination.
CHANGE: `lastTradeSource`, `lastTradeDestination`, and `lastTradeWare` are always recorded after each completed trade (fleet coordination still gates reservations only).
CHANGE: Removed redundant post-delivery same-ware return-trip block and the forward `$returnBonus` heuristic â€” reverse hauls are handled by the main search loop plus lane continuity.
CHANGE: MK2 queue-time trade logbook uses supply-only message (text 3102: amount, ware, source and destination as `Sector - Station(ID)` with ware fill at source/destination, e.g. *at 87%* / *at 23%*) â€” no profit, money, or bonus fields; applies to offer-based and ware-exchange legs. Removed post-run upkeep message (20200) that duplicated this after order completion.
FIX: `GT_TradeLogging.LogTradeOrder` no longer errors when MK2 distribution signals omit `$Profit` / `$BuyPrice` / `$SellPrice` â€” optional params default to zero instead of unguarded property lookup.
FIX: **Anti-ping-pong** guard blocks the exact reverse of the previous leg (same ware, swapped source/destination) unless the receiver is bucket-A critical (â‰¤5% fill) â€” prevents Aâ†’Bâ†’Aâ†’B shuttling while still allowing Bâ†’A with a different ware or emergency reverse runs.

MK4 Trader:
CHANGE: Dedicated MK4 trade cache pool (`global.$GT_TradeCacheMK4` per home sector, with `GT_TradeCacheMK4MaxDistance` / `GT_TradeCacheMK4ByWare`) â€” MK4 search reads and writes only the MK4 pool via `cachePool='mk4'` on `lib.gt.cache.search` / `lib.gt.cache.write`; MK3 ships keep `global.$GT_TradeCache`. MK4 policy invalidation and offer-pair purge no longer wipe MK3 cache entries for the same home sector. Diagnose shows MK3 vs MK4 pool counts; fleet cache stats, settings clear-cache, TTL/event cleanup, and purge/flag handlers operate on both pools.

Search Engine Performance:
PERF: `lib.gt.tradematch` ware-indexed offer pairing â€” inner match loop pairs each sell offer only against buy offers for the same ware (all modes when both sides are non-empty), replacing O(sellÃ—buy) scans that skipped mismatched wares with `continue`.
PERF: MK4 live search demand-led supplier collection (`demandLedSupplierScan`) â€” buy offers collected first, then sell-offer sector scan limited to demand wares instead of full auto-ware galaxy scan.
FIX: MK3 cache validation rejects trade-rule violations per candidate in the validation loop (parity with MK4) and flags ship-scoped cache failure (`GT_Cache_Flag_Ship` / `trade_rules_failed`) instead of only at final order creation â€” no fleet-wide cache purge.
FIX: `lib.gt.cache.search` fast path skips entries where the requesting ship is in `$FailedShips` and enforces MK4 `serveHomeOnly` / `mk4AnchorHome` delivery scope (parity with cache work-loop prefilter).
CHANGE: Debug logs distinguish **cache exhausted** (all cache candidates failed validation â†’ live escalation) from TTL/offer staleness â€” replaces misleading `CACHE STALE` wording on MK3/MK4 validation reject-all paths.

Version 0.14.13 (2026-06-23)

Mod Requirements:
CHANGE: content.xml requires X4 Foundations 9.00 (dependency version 900)

Trade Scoring:
CHANGE: MK3/MK4 trade rank distance is now homeâ†’buy + buyâ†’sell (route-aware) instead of max(homeâ†’buy, homeâ†’sell) â€” territorial maxbuy/maxsell gates unchanged; order distancepenalty applies to the summed score distance.
CHANGE: Validation sort applies Selection score (adjusted score / (1 + shipâ†’buy Ã— weight)) after priority-ware boost â€” ship position is not baked into cache $Score.
FEATURE: global.$GT_GlobalSettings.$Trading.$ShipProximityWeight (default 0.04; 0=off) controls the validation ship-proximity nudge; adjustable in Global Settings â†’ Trading Price Ranges (slider 0-100, value Ã· 100 = weight).
CHANGE: Cache trade entries now store $HomeToBuyDistance, $HomeToSellDistance, $RouteDistance, and $Distance (score-distance sum).

Trade Matching:
FIX: `lib.gt.tradematch` no longer throws `Property lookup failed` on route-leg gatedistance when `blacklistGroup` is null (MK1/MK2 paths that omit the param) â€” falls back to plain 2-arg gatedistance instead of passing null into the blacklist-aware form.

Pilot Registry:
FEATURE: GT pilots now enter `$Status = ejected` when their ship is destroyed â€” XP and registry data are preserved; `(T:Level)` tag is restored via a bounded post-eject retag burst (~1s / ~3s / ~5s) while adrift in sector.
FEATURE: Rescue rebind runs when an ejected pilot is assigned to any player ship (GT or vanilla) â€” pilot tag is restored immediately; `$Status` becomes `paused` until a Galaxy Trader order is active on that ship.
CHANGE: Single `Rebind_Pilot_Registry` path and `global.$GT_PilotsByStable` index consolidate pilot identity recovery (eject, rescue, vanilla assignment, register); bounded tag refresh replaces one-shot deferred retag for all paths.

GT Diagnose:
CHANGE: Pair evaluation scoring mirrors route-aware distance (homeâ†’buy + buyâ†’sell), homeâ†’sell territorial gate, MK3/MK4 selection score, and Ship Proximity Weight; Pair Details shows route jump breakdown and Score Â· Sel; cache sample rows include score/distance metadata.
FIX: MK4 sell-offer scan now mirrors runtime live search (`includePlayerSellOffers`) â€” the generic NPC-only scan (`negateownerfilter`) omitted player suppliers, so buy-from-player-only orders evaluated only doomed NPCÃ—player pairs, hit the pair-eval cap on `mk4_supplier_policy_blocked`, and showed zero Pair Details rows.
FIX: MK4 supplier-policy prefilter at sell-offer collection drops disallowed player/faction suppliers before pair evaluation (parity with `lib.gt.live.search` owner filter), preventing eval-cap starvation when one supplier side is disabled.
FIX: MK4 executable-only Pair Details no longer renders an empty section when every pair fails â€” rows are collected during the scan and PASS-only filtering applies only when at least one pair passes; otherwise the top rejected pairs with failure reasons are shown (`no PASS â€” top rejected shown`).

Illegal Route Filter:
PERF: Pre-trade `route_legality` checks run only for contraband (`@$ware.illegal gt 0`) â€” central skip in `lib.gt.pathfinding` (parity with `GT_CheckRouteLegality`) and caller guards in `lib.gt.tradematch`, MK3/MK4 cache validation, MK1/MK2/MK4 final pre-order safety nets, and miner sell routing. Legal-only baskets no longer build jump paths on every pair; runtime pre-transit enforcement unchanged.

Galaxy Miner:
CHANGE: Resource Probe Sector Scan Wait (`$ScaleResourceProbeScanByPilotLevel`) now gates the full `resourceprobescantime` wait â€” OFF (default) matches vanilla (no delay; vanilla never applies the engine wait). ON applies the sector probe-count penalty (+5s per faction probe above one), with GT pilot level scaling unchanged (level 1 = full wait, level 15 = 5s; GT XP mode only when wait exceeds 5s).

MK2 Trader:
FIX: Fleet coordination no longer double-subtracts destination incoming reservations after `lib.gt.tradematch` â€” post-match fairness had re-applied `get_ware_reservation` on amounts already netted by tradematch, falsely zeroing effective need (`reserved=1`) when one in-flight delivery existed but the destination still had a large storage deficit (e.g. MK2 idle at a critical wharf while another ship was en route).

MK1 Trader:
FIX: Save-loaded MK1 orders no longer throw `Property lookup failed: this.$mk1_opportunisticSupplyTried` on the opportunistic-supply branch â€” lazy flag read is guarded with `?` before first use (same pattern as `this.$mk1_returnhomeReleased`).

Trade Logging:
CHANGE: Queued trade logbook messages now include buy/sell stations in `Sector - Stationname(IDCODE)` format â€” single-trade queue entries (MK1/MK2/MK3/MK4), MK1/MK4 multitrade leg summaries, cargo sell-only, and player-supplier queue entries. Station labels are formatted centrally in MD (`GT_FormatStationLocation`); MK1/MK4 pass structured multitrade leg data and the summary is built at log time.

Idle Parking:
FIX: Assist subordinates (mimic commander) no longer loop dock/abort when idle parking triggers â€” Assist "redirect to init" no longer restarts the trader script during active `GTIdlePark` / `DockAndWait` handoff, and `DockAndWait` callerid is the finite `GTIdlePark` order (not the infinite `Assist` default order).
FIX: Idle-parked ships continue trade search while docked â€” `GTIdlePark` docks and completes like MK1 `DockAndReturnHome`; `$GT_IdleParkingHold` and timed release are handled in GalaxyTrader `main_loop` via `lib.gt.idlepark`.
FIX: Idle Parking Release Minutes global setting persists `0` (stay docked until a trade is found) â€” settings menu read/validate no longer treats `0` as missing and resets to `1`.
FIX: `GTIdlePark` sets `$GT_IdleParkingReleased` when the dock attempt fails so the parent trader resumes search instead of re-arming parking every loop.
FIX: `orders.base` undock guard covers idle-park hold (`$GT_IdleParkingHold`) so docked idle-parked ships are not auto-undocked between order transitions.
CHANGE: Idle-park active check, trigger, and timed release consolidated in `lib.gt.idlepark`; MK2/MK3/MK4 and Galaxy Miner share the same paths; trader `on_abort` skips `GT_Search_Abort` during idle-park handoff (parity with MK1 return-home guard).
CHANGE: `GTIdlePark` is a player-cancellable navigation order (`canplayercancel`) queued after repeated search failures; player cancel clears hold and undocks.

Assist:
FIX: `on_abort` handoff guard extended from `DockAndReturnHome` only to all GT navigation handoffs (`GTIdlePark` and related `DockAndWait` caller orders).

Version 0.14.12 (2026-06-21)

Trade Matching:
FIX: `lib.gt.tradematch` v8 â€” post-yield `resume` at `tm_ensure_state` runs only when offer scratch is lost after save/load, not on every cooperative wait (fixes live search appearing hung after large buyer/seller scans).

MK3 Trader:
FIX: Live search no longer stalls indefinitely after offer collection â€” shared `lib.gt.tradematch` v8; sell-loop cooperative yields no longer restart the outer scan from `$si=1` every 1ms.

MK4 Trader:
FIX: Live search path on cache miss uses the same `lib.gt.tradematch` v8 fix â€” cache-hit fleets were unaffected; forced live or empty cache no longer hang in tradematch after buy-offer collection.

Version 0.14.11 (2026-06-21)

GT Cache Search:
FIX: Stale cache entries with destroyed supplier/delivery stations no longer abort the cache scan with `Property lookup failed` on `.gatedistance` / `.tradewares` â€” dead component refs are skipped (with live offer seller/buyer fallback) before distance and MK4 ware-type filters run.

MK4 Trader:
FIX: Cache and live trades no longer fail pre-validate with `sell_not_available` on stale embedded `$SellOffer` handles â€” delivery offers are re-resolved via `find_buy_offer` (tradepartner) in the fresh-offer filter and `trade_found` loop before amount checks; Build Storage / internal delivery uses cargo target-count demand fallback when `offeramount` is zero (parity with `lib.gt.tradematch`).
FIX: Final order validation uses effective delivery amount (fresh offer â†’ `.amount` â†’ cargo demand fallback) instead of rejecting solely on `.available`, so Build Storage legs that pass pre-validate are not blocked again at order creation.

MK1 Trader:
FIX: Export no longer selects MK3-style NPC buyâ†’NPC sell arbitrage when Supply is off â€” `lib.gt.tradematch` now resets match accumulators on each fresh `run_script` entry so stale `$TradeList` rows from prior sector scans on the same ship cannot score ahead of home-station export pairs.

Trade Matching:
FIX: `lib.gt.tradematch` v7 â€” fresh-match reset of `this.$tm_tradeList` and related counters on each new `run_script` entry (fixes stale MK3 trades leaking into MK1 export).

Version 0.14.10 (2026-06-21)

Trading Academy:
FIX: Academy fee is now debited only after the ship successfully docks at the training station, not when the DockAndTrain order starts or the course is selected in the submenu.
FIX: Save/load no longer strands paid academy enrollments â€” load recovery re-dispatches DockAndTrain when $AcademyEnrollment persists but the training order is missing; $CostPaid prevents duplicate charges on retry.
FIX: Academy enrollments can re-dispatch without auto-training enabled ($AcademyEnrollment gate in HandleTrainingNeeded and trader AI retry paths).
FIX: Enrollment logbook entry no longer shows a money debit at course selection (payment is recorded at dock).
FIX: Load-time retroactive XP-block cleanup no longer strips academy, manual-training, or in-flight session blocks when $BlockedLevel exceeds the pilot's current XP tier â€” prevents dock-then-instant-undock ("No training required") after reload.
FIX: order.dock.train treats pending $AcademyEnrollment / $ManualTrainingRequested as training required even if $XPBlocked was cleared.
FIX: Save/load mid-training restores registry timer state ($TrainingStarted / training_in_progress); HandleStartTraining resumes without duplicate payment when $CostPaid is set.

Galaxy Miner:
FIX: Assist subordinates no longer abort DockAndTrain ~1ms after dispatch â€” natural ladder training uses MD immediate=false dispatch (same as academy) instead of inherited-AI immediate=true create_order.
FIX: Main loop holds while DockAndTrain or training_in_progress is active; periodic GT_Training_Needed is suppressed during an in-flight session.

MK1 / MK2 Trader:
FIX: Assist subordinates use immediate=false DockAndTrain dispatch (MD path or handler guard) â€” same inherited-context abort fix as Galaxy Miner.
FIX: Main loop holds while DockAndTrain or training_in_progress is active; periodic GT_Training_Needed is suppressed during an in-flight session.

MK4 Trader:
FIX: Multitrade no longer over-commits the same supplier buy offer across legs (e.g. three Build Storage deliveries from one factory). Cumulative supplier budget per BuyOffer caps queued pickup amounts by effective physical stock minus outgoing reservations and fleet reservations; secondary legs decrement the shared budget at queue time.
FIX: Cargo clearance (sell-only) no longer queues multiple sell legs for one hold load â€” top sell-only candidate forces single-leg multitrade so empty-cargo ERR_NOTHING_TO_SELL follow-ups cannot remain queued after a successful clearance sell.
FIX: Sell-only multitrade legs also respect per-ware ship cargo budget so stacked clearance sells cannot exceed on-board stock.
CHANGE: Supply scoring is demand-based (`tradeAmount / distance`) â€” unit price no longer ranks MK4 deliveries, so low-price wares (e.g. Food Rations) are not permanently buried behind high-volume Energy Cell routes.
CHANGE: Live supply search always round-robins one candidate per ware (`diversifyByWare`, including manual ware basket); priority wares lead each round-robin round and still receive the priority score multiplier for within-ware route choice.
CHANGE: Search-depth cap expands to at least one validated candidate per distinct ware so auto-ware fleets with 30+ active demands no longer drop niche wares at the default breadth limit.
FIX: Save/load no longer throws `Property lookup failed: $waitResponseRemaining` when MK4 orders resume mid-wait for MD response â€” wait timeout is derived from persisted `this.$waitForResponseStartedAt` instead of a local variable that does not survive wait yields.
FIX: Save/load training-in-progress parity with MK3 â€” restores this.$training_in_progress, waits on active DockAndTrain, ignores spurious GT_Training_Complete while academy/timer is active; Assist subordinates use immediate=false DockAndTrain when the signal handler path still fires.

Trade Matching:
FIX: Supply-mode tradematch caps supplier sell amount by station physical stock minus outgoing buy reservations (MK2 parity), reducing matches against suppliers already depleted or fully reserved.
FIX: Clamp preview at match time uses `this.assignedcontrolled` as trade partner (parity with trade_found validation).

GT Trade Perform:
FIX: On ERR_SELLER_NO_CARGO during a buy leg, GT ships immediately cancel orphaned same-ware delivery orders still queued â€” prevents LIFO sell-first multitrade batches from cascading into ERR_NOTHING_TO_SELL after a failed pickup.

GT Diagnose:
FIX: Pilot jump-distance cap now uses GT registry `$Level` (same as runtime order script), not vanilla `pilot.skill.management` â€” subordinate diagnose no longer shows a wider search radius than the ship can actually use (e.g. Lv.2 pilot: 1j cap vs order max 3j).
CHANGE: MK4 supply pair score mirror matches runtime demand-based formula (no unit-price factor in supply-mode score column).

MK3 Trader:
FIX: Normal live search no longer fills the match list with trading-station broker phantoms that pass price/offeramount but fail at execution (`seller_cargo=0`). Sell offers are clamp-filtered at collection time; executable pre-score filter (clamp, cargo util, profit recalc) runs before scoring; tradematch clamp preview uses `this.assignedcontrolled`. Build Storage suppliers are no longer crowded out of the per-ware cap â€” ships should trade at normal price bands without spurious fallback.
FIX: Save/load no longer throws `Property lookup failed: $waitResponseRemaining` when GT orders resume mid-wait for MD response â€” wait timeout is derived from persisted `this.$waitForResponseStartedAt` instead of a local variable that does not survive wait yields.
FIX: Save/load restores this.$training_in_progress from registry or active DockAndTrain; mandatory-training path waits on an active session instead of re-dispatching; spurious GT_Training_Complete resume is ignored while academy/timer is still active.
FIX: Assist subordinates use immediate=false DockAndTrain dispatch when the signal handler path still fires.

GT Live Search:
FIX: Sell-offer collection rejects broker phantoms via `clamp_trade_amount` (seller resolution matches trade_found). Build-storage sell suppliers retain a reserved per-ware slot budget so HQ supply is not displaced when NPC/trading-station offers fill the base cap.

Version 0.14.9 (2026-06-21)

MK4 Trader:
FIX: Global fleet money cap no longer activates on non-money queue failures (destination capacity zero, no queueable legs, etc.). Cap is set only when the primary leg genuinely cannot afford one unit above MinPlayerMoney; other failures retry as no_trade without freezing the fleet.
FIX: Early money gate and trade_found fast check self-heal when player funds are above the gate threshold instead of staying blocked until wealth exceeds a stale snapshot set by another ship.

MK1 Trader:
CHANGE: Export sell-phase live search now resolves home-station sell offers first and passes them to `lib.gt.live.search` with score-aware buy cap enabled. NPC buyer collection keeps the top-N offers per ware by estimated sell profit (home sell vs buyer price, tradeable amount, distance penalty matching tradematch) across the full `maxsell` scan instead of the first offers seen in sector order â€” better buyer choice for multi-ware export and fewer weak or half-load routes when several buyers exist for the same ware.

MK3 Trader:
FIX: Early money gate and trade_found fast check use the same self-heal as MK4 â€” stale global money-cap flags clear once the player is solvent past the gate threshold.

GT Diagnose:
FIX: Fleet money cap verdict no longer fires on a stale flag alone; requires a truthy active cap. When funds are healthy, cap status is informational and notes that MK1/MK2 ignore the fleet cap.
CHANGE: MK1 diagnose uses a dedicated home-station export path (effective wares, export gate, station sell offers, NPC buyers in maxsell range) instead of the generic sector-wide sellÃ—buy scan â€” large MK1 reports generate much faster with capped pair-detail rows.
CHANGE: Generic trader pair evaluation is capped (1000 pairs evaluated, 80 rows shown, 160 full path checks) to keep MK3/MK4 diagnose responsive on wide search radii.
ADD: MK1 diagnose verdict branches for missing home station and export-gate idle (Min Product Storage %); live WARE_SNAPSHOT / SELL_STORAGE_GATE / SELL_OFFER_SNAPSHOT rows refresh during diagnose.

Version 0.14.8 (2026-06-20)

MK4 Trader:
FIX: Auto-wares supply fleet no longer leaves player stations stuck on small remainder deliveries (e.g. Quantum Tubes to Headquarters). Live search completion pass, completion-first validation ordering, completion scoring without expensive-ware price penalty, per-ware round-robin ranking (`diversifyByWare`), cache player-demand fallback, and cache-radius miss when metadata is narrower than the ship's jump range â€” niche remainder trades now surface and validate before dominant Claytronics/Spices routes.

MK1 Trader:
FIX: Single-full-cargo scan, selltarget planning, queue build, and supply trade paths no longer crash when a matched sell/buy offer becomes invalid between tradematch and order queueing. Stale offers are skipped via `.exists` guards and safe `@offeramount` reads (MK3 parity).

Galaxy Miner:
FIX: When "Use Vanilla XP Only" is enabled, gather/sell jump distances no longer stay clamped to the GT pilot tier cap during demand scan, station filtering, and ware scoring. Distance recalc now runs at main loop start (order params only; no GT level cap), matching MK1/trader vanilla-XP behavior. Init no longer applies the GT cap in vanilla mode; miner delivery XP payload is skipped; GT Diagnose gather range mirrors the same rule.

Version 0.14.7 (2026-06-19)
Illegal Route Filter:
ADD: Runtime enforcement for the "Illegal Route Filter" order setting (`enforceRouteIllegalLegality`). When Allow Illegal Wares and Illegal Route Filter are both enabled, GT now re-checks contraband legality immediately before each inter-sector crossing in `move.generic` (capital gate hops and non-capital `move_to` steps). If any illegal ware in the hold would become illegal to the next sector's police faction, the ship aborts the current trade leg, clears the in-flight policy snapshot, busts the route-legality cache for that active ware when applicable, and returns control to the parent GT order for a fresh search (`route_illegal_pre_transit`).
ADD: In-flight trade policy snapshot (`ActiveTradePolicy`) on `global.$GT_Ships.{ship}` when a route-filtered trade is committed; cleared on trade completion, abort, or order exit so mid-flight order edits do not retroactively change enforcement.
CHANGE: Pre-trade `route_legality` path checks now use the same highway flag as actual movement (`uselocalhighways` off for capital ships), reducing false accepts/rejects vs. vanilla travel.
ADD: GT Diagnose Section 3 rows for Illegal Route Filter on/off, Active Trade Policy snapshot, and Last Route Illegal Abort (sector, ware, police faction, age).

MK1 Trader:
ADD: "Illegal Route Filter" order checkbox (same text IDs as MK3/MK4). When enabled with Allow Illegal Wares, MK1 supply and station-trader candidate selection runs pre-trade route legality before queueing trades; committed trades participate in runtime enforcement.

MK2 Trader:
ADD: "Illegal Route Filter" order checkbox with pre-trade route legality in pair selection before `create_trade_order`, Active Trade Policy on commit, and runtime enforcement parity with MK3/MK4.

MK3 / MK4 Trader:
CHANGE: Committed trades under Illegal Route Filter now register Active Trade Policy and use runtime pre-transit enforcement in addition to the existing pre-trade route legality gate.

Galaxy Miner:
ADD: Allow Illegal Wares + Illegal Route Filter order settings with Assist propagation, pre-trade route legality on sell-path selection, Active Trade Policy on overflow sell commits, and the same runtime pre-transit guard as traders.
CHANGE: Overflow live search respects the ship's Allow Illegal Wares setting instead of always permitting illegal goods.
ADD: New "Check Demand First" order checkbox (default on). When disabled, the miner mines from the Resource Basket without demand scoring or primary-capacity gating, stockpiles cargo until a buyer is available, and enters full-bay standby with notification when the hold is full and overflow sell is off. Recommended for dedicated single-resource fleets where primary buyers are temporarily full.
ADD: Demand-off ware selection uses a single shuffle-per-slice pick from reachable basket wares instead of urgency scoring; empty Resource Basket falls back to configured resources on in-range target stations (vanilla-style station resources/supply/tradewares), then the ship mineable ware list if still empty.
ADD: Translations for Check Demand First label and tooltip (`77000,31031` / `77000,31131`) in all 16 supported locales.
ADD: GT Diagnose row for Check Demand First on/off (demand-first vs demand-off / stockpile).
CHANGE: Galaxy Miner order script version 9; existing saves backfill `checkDemandFirst=true`.
ADD: Global Settings toggle "Scale Resource Probe Scan by Pilot Level" (`$Miner.$ScaleResourceProbeScanByPilotLevel`, default off). When enabled in GT XP mode, resource probe scan wait scales linearly with GT pilot level (level 1 = engine `resourceprobescantime`, level 15 = 5s). Unchanged when Use Vanilla XP Only is on, the toggle is off, or base wait is already 5s or less. Galaxy Miner settings block is hidden under Use Vanilla XP Only; toggle is forced off when vanilla XP mode is enabled.
ADD: Translations for the global setting section, label, and tooltip (`77000,9310` / `77000,9311` / `77000,9411`) in all 16 supported locales.
CHANGE: Resource probe scan scaling is opt-in via global settings instead of always active in GT XP mode (mining routine v32+).

Assist / Subordinates:
ADD: Ship-subordinates under MK1, MK2, and Galaxy Miner commanders inherit commander `allowillegal` and `enforceRouteIllegalLegality` through `order.assist.xml`, matching existing MK3/MK4 propagation.
ADD: Galaxy Miner subordinates inherit commander `checkDemandFirst` through Assist (create_order, run_script, and commander-restore paths).

MK3 Trader:
FIX: Ignore Player Pricing (IPP) no longer blocks player-supplier trades at MinPlayerMoney gates. Tradematch already scores player supply as free (`$PlayerFreeSupplier`); the authoritative budget clamp, global money-cap short-circuit, and fast money check at `trade_found` now skip IPP player-supplier candidates instead of rejecting routes the scorer would pick.

GT Diagnose:
ADD: "Copy Report" button in the diagnostic popup â€” exports the full plain-text report (all sections) to the system clipboard.
CHANGE: MK3 Ignore Player Pricing parity â€” Configuration policy snapshot, supplier/buyer pool stats, pair evaluation mirrors runtime (MinPlayerMoney skip, profit/ROI bypass, gross-income scoring), `[IPP]` / `[player]` vs `[NPC]` Pair Details tags, and best IPP vs best NPC supplier summary with score comparison warning.
FIX: MK1-supply exclusion in pair evaluation now checks both supplier and customer legs (was customer-only), matching runtime rejection behavior.
ADD: IPP-specific verdict suggestions (NPC supplier outscores player plant, MK1-supply blocks, no player suppliers in scan).

MK4 Trader:
FIX: Supply multitrade now tracks a per-destination delivery budget across queued legs. Secondary buys from another supplier no longer queue extra sell amounts to the same customer buy offer once remaining destination capacity is exhausted (prevents overflow when the MK4 freighter is larger than the destination cargo hold).
FIX: serveHomeOnly now treats the home station's build storage as part of the home anchor (vanilla `station.buildstorage` / `buildstorage.base`). MK4 supply ships with a station home no longer reject HQ build-storage delivery pairs when serveHomeOnly is enabled.
FIX: Jump distance order params are no longer clamped to the GT pilot tier cap when "Use Vanilla XP Only" is enabled; effective search radius follows the order sliders (MK4 order init and GT Diagnose).
FIX: MK4 pair validation, serveHomeOnly filtering, and GT Diagnose resolve delivery stations from buy-offer buyer first (then owner), matching vanilla build-storage trade structure.

Version 0.14.6 (2026-06-18)
Ship Naming:
ADD: New "Pattern" naming mode in Global Settings (Ship Naming). Players can define a custom ship name format using `{TOKEN}` placeholders (e.g. `{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})`) instead of the legacy prefix/suffix toggles. Pattern mode requires GalaxyTrader XP (`Use Vanilla XP Only` off); saves with pattern mode active are migrated back to Legacy when vanilla XP is enabled.
ADD: "Name Pattern" edit box with default pattern restore when cleared, plus an in-menu placeholder legend (ship, GT XP, home, crew, stats, and status-token rows) shown only in Pattern mode.
ADD: Optional "Display Home Sector" setting with Prefix/Suffix position; home sector is resolved from the ship's GT order and refreshes when home changes.
ADD: Unified ship-name refresh pipeline (`lib.gt.attention.refresh_ship_name` -> MD `RefreshShipName` handler) wired into MK1, MK2, MK3, MK4 Supply, and Galaxy Miner main loops. Names are rebuilt through one MD resolver with content dedupe via `$LastResolvedShipName`.
CHANGE: Bulk rename (`UpdateAllShipNames`) and the settings-menu refresh path now use the same handler as runtime order refreshes instead of duplicating legacy-only name logic.

Jump Distance:
ADD: New optional "Autoscale" order checkbox on MK1, MK2, MK3, MK4 Supply, and Galaxy Miner. When enabled, stored jump-distance sliders are raised to the pilot's tier maximum after mandatory training or Trading Academy completion (not on passive trade/miner XP). Turning the checkbox on or swapping pilots while Autoscale is active also snaps distances to the new pilot's current tier cap. MK4 sets both coverage and buy sliders; miners replace a 0 gather/sell distance with tier max. Disabled by default on new and migrated orders.
ADD: Translations for Autoscale label and tooltip (`77000,1098` / `77000,1099`) in all 16 supported locales.
ADD: GT Diagnose rows for Autoscale on/off and stored jump params vs pilot tier max (commander/standalone GT orders only).

MK1 Trader:
ADD: New order slider "Min Product Storage %" (`minsellstorage`, default 0 = disabled). When above 0, each product/tradeware must reach that % of its configured station storage max (reservation-aware) before MK1 will include it in the sell basket; wares below the threshold are skipped for that cycle. Supply mode and leftover-cargo clearance are unchanged.
ADD: GT Diagnose rows for configured Min Product Storage % and per-cycle `SELL_STORAGE_GATE` snapshot (pre/post ware counts and per-ware keep/drop at verbose debug).
ADD: Translations for Min Product Storage % label and tooltip (`77000,30027` / `77000,30127`) in all 16 supported locales.
CHANGE: Cargo/Profit mode no longer applies soft station-fill preference via Sell Cargo Fill Target when Min Product Storage % is enabled; export gate survivors are tie-broken by highest station fill then profit only.

XP / Training:
FIX: Level-up notifications and GT XP awards no longer run when "Use Vanilla XP Only" is enabled. Trade success, miner delivery, and legacy XP signals all route through `ProcessSingleXPEvent`; that cue now exits immediately in vanilla XP mode so GT does not add registry XP, sync management/piloting skills, or show the level-up popup.

MK2 Distribution:
FIX: Bidirectional return-trip logbook and post-cycle logic no longer crash after order-completion waits. Trade-cycle locals (`$denyTrade`, `$bestTrade`, return amounts) are persisted to `this.$` before `<wait>` yields, matching the standard AI-script lifetime rule.

Threat Avoidance:
FIX: Dynamic threat blacklist manager now loads via ui.xml instead of SirNuke Lua Loader. Lua Loader only reads loose lua files and failed silently on packed Steam/cat installs, so threat blacklisting never initialized while the rest of GT kept working. MD init now listens for `gt_blacklist_manager` Ready (same packed-safe pattern as mod removal and context-menu Lua).

MK4 Trader:
FIX: Galaxy-Supply now sets `internal="true"` per trade leg when the counterparty is player-owned (MK2 / spec Â§1.4.1 parity). Deliveries to player stations and build storage no longer require credits on the destination account; buys from player suppliers no longer debit the player wallet. Multitrade budget planning skips purchase-cost deduction for player-supplier legs. Foreign NPC supplier legs stay external (normal payment).

Version 0.14.5 (2026-06-18)
Galaxy Miner:
CHANGE: The "no mineable wares available" player notification now uses localized text (ID 31200) and includes the ship name, ship ID code, and fleet name (top-level fleet when the miner is a subordinate; "-" when not in a fleet).
CHANGE: The "set Home Station or Home Position" notification now uses localized text (ID 31201) instead of a hardcoded English string.
ADD: Translations for both miner runtime notifications (31200, 31201) in all 16 supported locales.
FIX: fixed a code syntax error for the cargo  calculation

Version 0.14.4 (2026-06-17)
Galaxy Miner:
ADD: New "Mining Drones to Buy" order setting. Sets how many collector (mining) drones a miner buys when it has run out of the needed type (solid ore / liquid gas), capped by the ship's unit-bay capacity. Set to 0 to disable automatic collector-drone purchases and manage drones manually (default 5 = a full drone set).
CHANGE: Collector drones are now replenished only when the ship has zero collectors of the required type. A miner that still carries at least one collector is never topped up or re-bought, so existing drones are kept. Purchases are routed through GT Maintenance (slider-driven) instead of the vanilla bundled resupply, and existing collectors are preserved during probe-only restock trips so they can no longer be wiped and re-bought.
FIX: Removed the invalid `useundiscovered` attribute from every mining resource-finding call (`find_closest_resource` / `find_resource`) in the Galaxy Miner order and its mining routine. The attribute does not exist on these elements in the X4 script schema, so the engine ignored it while logging script errors; the calls now match vanilla, which passes no resource-detection filter and lets the engine apply faction-appropriate discovery by default. Resource probes stay an optional yield/targeting optimization and are never a prerequisite for mining.

GT Diagnose:
FIX: Removed the same invalid `useundiscovered` attribute from the Miner Resource Scan discovery probes, so the diagnostic's engine calls are schema-valid and stay consistent with the miner's own scoring path.

MK1 Trader:
FIX: Supply Station now respects home-station trade rules when "Ignore Trade Rules" is off. Supply candidates are filtered with the same `cantradewith` checks used in the sell phase, so MK1 traders no longer buy from NPC sellers that the home station's trade rules would block from fulfilling the delivery order.

MK4 Trader:
FIX: Galaxy-Supply now enforces customer-station trade rules against the NPC source faction when "Ignore Trade Rules" is off. The `cantradewith` cross-checks run in the main validation loop for every candidate (not only at order creation on a small fallback window), and violating cache entries are flagged in one pass. MK4 no longer retries the same top-scored non-compliant cached trades in a loop; when the whole cache batch fails trade rules it escalates immediately to a live search so other valid targets (including build storage) can be found.
FIX: Build-storage supply deliveries are no longer crowded out by cheaper factory demand in the score-sorted trade cache. Expensive construction wares produced tiny supply scores, so build-storage entries sank to the back and were truncated by the cache `maxEntries` limit while ordinary HQ/factory demand dominated every cache hit. Build-storage deliveries now receive a dedicated scoring priority tier so they sort to the front and survive cache read/write and selection.

Version 0.14.3 (2026-05-09)
Galaxy Miner:
FIX: Galaxy Miner now refreshes its runtime Resource Basket from the current default order before building mining candidates, so order-panel Resource Basket edits are applied on the next main-loop pass instead of leaving miners on an init-time snapshot.
FIX: Galaxy Miner Resource Basket now remains authoritative during station buy-offer candidate discovery, so station demand can no longer re-add Ore or other off-basket wares after the player restricts mining to specific resources.

MK4 Trader:
FIX: Secondary multitrade budget skipping now tracks blocked candidates by prepared-list index instead of using the whole trade table as a table key, preventing `Failed to set table[]...` AI-script errors when a candidate is unaffordable.

Version 0.14.2 (2026-05-08)
Idle Safe Parking:
ADD: New optional "Idle Parking" order setting for MK2, MK3, MK4 Supply, and Miner ships. When enabled, ships that repeatedly fail to find work after the normal retry escalation park at their configured home station or home sector instead of reacting to a single failed search.
ADD: Shared GT idle parking order docks at the home station when available, otherwise searches the home sector for a dockable station with player-owned stations preferred before friendly non-player stations. If no valid dock exists, the ship flies to the home sector and waits there.
ADD: Idle-parked ships undock after 60 seconds when no new task arrives, matching the MK1 return-home port-clearing behavior without changing MK1's existing setting.
ADD: MK2 gains an optional "Home Sector" order setting so sector-only idle parking works when no home station is configured.

Galaxy Miner:
ADD: Galaxy Miner now has the same "Logbook Entries" boolean order setting as MK3, using the existing MK3 translation. Disabling it suppresses miner queue-time cargo sale/delivery logbook entries while leaving XP transfer handling unchanged.
FIX: Resource Basket is now authoritative for Galaxy Miner mining selection even when the ship already carries other minable cargo. Cargo-first delivery helpers no longer inject or select off-basket wares, preventing Methane-only gas miners from switching to Helium just because Helium is already in the hold.
FIX: Resource reachability scoring no longer treats `sector.yieldrating == 0` as a hard blocker before the vanilla-style `find_closest_resource` check. Miners now keep using the engine routing probe to find valid discovered fields even when existing resource probes report `probeYield=0` / `sectorYield=0`, so auto-deployed probes do not prevent normal resource searching.
FIX: Home Station now defines the Galaxy Miner operating anchor when set. If both Home Station and Home Sector are configured, gather and sell range checks are measured from the home station sector; Home Sector is only used as the fallback for stationless miners. This keeps runtime behavior aligned with GT Diagnose and prevents miners from using a separate home sector to reach asteroid fields outside the station-centered range.
FIX: Galaxy Miner mimic subordinates now inherit the commander's Home Position setting through the Assist order path, so ships set to mimic a Galaxy Miner commander use the same operating anchor as direct Galaxy Miner orders instead of failing with incomplete home configuration.

GT Diagnose:
FIX: Miner Resource Scan now mirrors the updated miner reachability rule: `sector.resources.{ware}.exists` is the pre-check, while `sectorYield` / `probeYield` are informational. The probe table now also reports reachable-sector `0/0` probe rows so players can distinguish "yield currently reads 0" from "engine found no routable discovered asteroid".


Version 0.14.1 (2026-04-27)
MK3 Trader:
ADD: Order setup now has a "Blocked Stations" station selector. Selected stations are excluded from MK3 buy and sell trades.
Miner:
ADD: Order setup now has a "Blocked Stations" station selector. Selected stations are excluded from Miner sell trades.

FIX: repaired corrupted translation files

Version 0.14.0 (2026-04-20)
Trading Academy (Fleet Academy):
New "Trading Academy" entry on the right-click context menu of player-owned GT-service ships. Opens a custom MapMenu submenu with three on-demand training courses (Apprentice / Trader / Master Trader, target levels 4 / 7 / 13) that promote the pilot to the chosen rank without waiting for natural XP progression. Backed by the existing training pipeline (HandleTrainingNeeded -> HandleStartTraining -> order.dock.train) so the pilot still flies to a real trading station, docks, and waits out the training timer.
Per-pilot pricing - the listed "headline" cost (500 K / 1.5 M / 3 M Cr) is paid by a level-1 pilot. Players with already-progressed pilots pay a fraction calculated from the level gap with `((target - current) / (target - 1))^1.5`, floored at 5 % of the listed price. Duration scales linearly with the same gap, floored at 5 minutes. The duration shown on the course button is the duration the ship actually waits at the dock (no hidden ladder rewrite).
Pilot's stored level only rises when the course completes - sending the ship to academy keeps the visible "Lv.X" rank at the pilot's pre-course XP-derived level for the entire training run, then cements the new rank on undock (XP is topped up to the new level threshold so subsequent recalculations cannot roll the rank back down).
Academy `DockAndTrain` is queued onto the ship's existing order list (not interrupted as an immediate order), so subordinates finish the in-flight task and head to the academy as soon as it completes; works equally for direct GT-service ships and for miners/traders running under a fleet commander.
Academy fee is debited only when the ship arrives at the academy dock, not at submenu click. If the player has spent the credits between enrollment and arrival the course is canceled outright: no money is deducted, every academy marker is wiped, the ship undocks and resumes its previous order, and the player is notified ({77000,9924}).
New `global.$GT_Config.$Academy` config block (`$Enabled`, `$MinCostPercent`, `$MinDuration`, `$CostExponent`, `$Courses` list) - tweakable via `gt_configuration.xml`.

MK2 Trader:
FIX: Autoware selection now unions destination `resources + tradewares` (was resources only), so Trading Posts and similar buy-only stations are picked up as valid destinations.
FEATURE: AUTOWARES debug trace dumps per-source sellable and per-destination acceptable ware lists (and the resulting intersection) whenever the resolved basket changes.

GT Diagnose:
ADD: MK3 now also shows the Scoring for Tradepairs
FIX: MK2 no longer flagged "CRITICAL: No home sector" - homeStation is optional for MK2; row is now INFO and the verdict is gated to non-MK2 orders.
FIX: Search Sectors aggregate anchors from MK2 source/destination station sectors when no home sector is set, so distance scans cover the actual MK2 footprint.
FEATURE: New MK2 verdicts "MK2 IDLE (source below static reserve)" and "MK2 IDLE (source has no storage allocated)" surface the runtime srcBelowStatic / srcNoTarget skips with player-actionable suggestions.
FEATURE: MK2 Specific section reports the configured min/static/max storage thresholds and a per source-ware reserve table (PASS/BLOCK vs staticStorage) with a summary row.
FEATURE: Pair Details rebuilt for MK2 from the order config (source x destination x ware), walking the runtime gates 1:1 (illegal/cargo, noSrcOffer, srcNoTarget, srcBelowStatic, self, distance, noDstOffer, noNeed, minTrade) with one reasoning string per row plus a Skip Breakdown summary.


Version 0.13.3 (2026-04-19)
MK3 + MK4 trader pipeline:
FIX: Priority-ware multiplier now also applied in `matching_work_loop` (live pipeline), not only `cache_work_loop`. Fleets with `$prioritywares` configured no longer lose priority ordering whenever the trade comes from the live/matching path instead of a cache hit.
FIX: `start_trading` registration wait is bounded (10s spin -> re-emit `GT_Register_Ship` -> 5s grace -> warn + resume) instead of pinning the AI block forever on a queue stall / lost signal.
FIX: `escape_from_blacklisted` MoveWait timeout grew from 1s to `jumppath.count * 60s` (or 60s), giving the ship a real settling window before re-blacklist re-fires in a tight loop.
FIX: `cache_work_loop` resets `$cacheIsPriority` per cache-entry iteration, so non-priority winners are no longer flagged as priority in the post-search summary.
PERF: Route-legality probing (`run_script lib.gt.pathfinding mode=route_legality`) is memoized per chunk on the `(buySector, sellSector, ware)` triple, eliminating duplicate child-script calls when the same triple appears repeatedly within a chunk.
PERF: `[GT-LogbookDump]` and `Signal received during market update wait` debug_text lines wrapped in the global `EnableDebugLogging` toggle, eliminating the highest-volume unconditional log spam.
REFACTOR: Extracted shared library helpers `lib.gt.attention.{min_player_money, is_gt_commander, restore_original_name, emit_gt_state_changed}` and `lib.gt.priority_wares.resolve` to dedupe ~30 inline blocks across MK3 and MK4 init / main_loop / phase 6+7 sites.
REFACTOR: Removed dead `start_repair` label and `global.$GT_AutoRepair` dispatch (global was never written), orphan `signal_objects param='GT_UICreditsDue_TradeOrder'` emits (no listeners), and unused `$maxDistance = $workUnit.$MaxDistance` extraction in `process_*_workunit`.

GT Diagnose:
FIX: `$minPlayerMoney` source aligned with the AI helper. Was reading `global.$GT_AIParameters.{$ship}.$MinPlayerMoney` (a table that never carries this field), so the gate threshold defaulted to 100000 Cr regardless of fleet config and produced misleading "Money gate" verdicts. Now reads `global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney` with the same fallback chain as the AI.
HARDENING: Report serializer + debug-log dumper now skip null rows defensively. A single broken section row no longer takes down both consumers and the entire log dump with `[null] null: null` cascades.
FEATURE: New "Miner Resource Scan" section runs an independent scan of mineable resources within gather range and reports per-ware best yield, reachable sector count, and active-ware marker. Mirrors the miner AI's own anchor-source chain (homeStation.sector -> homeSector -> defaultorder -> order -> commander.sector), pilot-skill jump cap (`$GT_Pilots[pilot].$Level` mapping), A4 safety pre-filter (hostile-owner / hazardous / contested / sectoractivity blacklist), and 3-level ware fallback (warebasket -> cargo.list -> miner-offer pool). Player-facing labels throughout â€” no internal variable names / filter codes leak into the report. Lua side gains an `isMinerScan` layout case for the new column headers.
FIX: Search Summary uses miner-facing labels for `GalaxyMiner` ships â€” `Search Summary (Buyer Side)` heading, `Stations Buying Your Ore` row, `<sector>: N buyer offer(s)` per-sector text rows. Eliminates the misleading "Total Sell Offers: 0" / `0 | N | N` Sell|Buy|Total triplet that read as "no sell opportunities" even though miners only consume buy offers (the sell-search is hard-skipped at `$secSellOffers=[]`).
FIX: Miner buyer-offer detection no longer reports "0 buyer offers" while the miner is actively selling (player-reported). Two root causes:
  - The diag's `find_buy_offer` (Section 8 + Clearance) added 5 extra match clauses the miner AI never applies (`match_buyer tradesknownto`, `dock`, `enemy not`, `offeramount min`, `relativeprice min`), silently dropping offers whose per-ship offeramount was momentarily 0 (reservation-saturated). Miner path now mirrors `order.mining.routine.gt.xml:824`: just `tradepartner` + (optional) `wares` + `space`.
  - The `wares="$diagMinerOfferWares"` filter restricted scans to wares derived from primary-station buy offers only, missing wares the miner discovers from non-primary demand stations. Miner path now uses `$ship.warebasket.list` when set, otherwise omits the wares filter and post-filters on minable + cargo-fit (now applied to ALL miners, not only the `$diagMinerAnyBuyerMode` branch).
FIX: Search Summary now surfaces RAW vs POLICY-PASSING buyer-offer counts as separate rows, with per-sector `P / R` breakdown and a new `POLICY BLOCKING` verdict branch that names the gates responsible (primary stations / overflow / playerStationsOnly) when raw>0 / policy=0 â€” players can now distinguish "no buyers exist" from "buyers exist but config rejects them all".
FIX: `Property lookup failed: $rscDiscMap.keys` on miners with empty `$DiscoverableWares`. Replaced `.keys.count gt 0` with raw presence check (`$rscDiscMap?`).

Galaxy Miner
FIX: Ware selection no longer locks in on the first ware that wins an early cycle. The selection block now picks the highest-scoring ware each slice (`$selectedWare = $bestWare`) instead of gating switches on `cargoCommitPercent < threshold` (a precondition that was effectively never true at decision time â€” the slice that just completed produced a full cargo, so the lock-in held forever after a small early lead). Per-slice granularity is still preserved by `run_script` so wares don't churn mid-cargo. Order params `criticalDemandDelta` / `hardEmergencyDelta` / `minSwitchCooldown` / `minCargoCommitPercent` remain declared for save-game compat but are no longer read.
FIX: Subordinates running `Assist` no longer crash with `Order Assist has no parameter 'homePosition'`. All `<edit_order_param order="this.ship.order">` call sites now require `@this.ship.order.id == 'GalaxyMiner'`; `defaultorder` writes are unaffected and remain the persistent storage path.
FIX: Candidate-ware discovery no longer drops wares the destination station only buys via offers. The buy-offer pass is now always-on instead of `cargo.list.count == 0` fallback â€” fixes refineries where Ore was permanently invisible because Silicon was the only `cargo.list` candidate.
FIX: Removed two `set_value name="global.$GT_FallbackActivations.{'â€¦'}"` increments from `order.trade.galaxyminer.xml` (the AI script expression evaluator resolves `set_value name="global.$X.{'key'}"` against a value-snapshot of `$X` rather than real storage and aborts the slice). The same pattern remains valid MD-side, so MD-side counters in `gt_order_monitor_bridge.xml` / `gt_xp_training.xml` are unaffected.
FIX: `maxGatherDistance` / `maxSellDistance` order param sliders now expose `0` as the actual minimum (was `min="1"` / `startvalue="1"` while `0` was the persisted "Stay At Home" value, so the UI showed 1 while the diag tool showed 0). UI and storage now agree.
FEATURE: New "Probe Stock Target" slider (`maxResourceProbesToBuy`, range `[0, ammostorage.deployable.capacity]`) replaces the hard-coded 1-probe restock; consumed by both the routine BUY block and `gt_maintenance.xml`'s ammotable build (clamped against bay capacity).
FEATURE: Probe lifecycle in `order.mining.routine.gt.xml` is now a v8-style DEPLOY -> RECOVER -> BUY block: drop a probe in the just-mined sector when none is nearby (64km), `CollectDeployables` for stale probes (every basket ware depleted in the sector), and `GT_DoMaintenance` BUY when the bay hits zero (5min throttle). Acts on at most one probe per slice.
FEATURE: Active-Scout Fallback in the "no selected ware" branch (gated on `autoDeployResourceProbes` + not `stayAtHome`): flies to the closest UNDISCOVERED candidate-ware sector (gate-distance / hostile-owner / hazardous / contested filtered) and `launch_resourceprobe` on arrival. Deferred-recycle of the previous scout probe via `CollectDeployables` if it didn't lead to a mineable target. Adaptive throttle: 15s after a successful attempt, otherwise `$demandRecheckInterval`.
FIX: `autoDeployResourceProbes` no longer turns the miner into a scout-only â€” was being forwarded as `$resourcescout` to the vanilla mining routine, which inherits the scout-only branch and skips `MiningCollect` entirely. Routine `$resourcescout` is now hard-wired to `false` and the user's intent is forwarded on a separate `autoDeployProbes` param.
FIX: Probe restock no longer routes through vanilla `'resupply'` / `interrupt.restock` (miner-class ships have no loadout entry for `deployablecategory.resourceprobe`, so vanilla restock silently dropped probes). Routine now signals GT's own `GT_DoMaintenance` pipeline.
FIX: Maintenance probe-need check lifted OUT of the `pilotLevel >= 15` defensive-equipment gate so low-skill miners can also restock probes. Probe quantity reads from `global.$GT_AIParameters.{ship}.$MaxResourceProbesToBuy` (with `$ship.defaultorder.$maxResourceProbesToBuy` fallback) and is clamped to the deployable bay.
FIX: Galaxy Miner gains the missing RESUPPLY EXECUTOR block in `main_loop`. Maintenance was building the shopping list and stashing it on `global.$GT_ResupplyOrders.{$ship}` but no AI script consumed it for miners â€” the ship never undocked. Mirrors the trader pattern: `find_dockingbay match_dock` -> `add_build_to_modify_ship` -> `GT_Maintenance_Complete` interrupt or 5min cooldown on failure.
FIX: Discovery probe (`find_closest_resource useundiscovered="false"`) now anchors per safe gather sector instead of `refobject="this.ship"`. Ship-anchored calls fold the ship's local sensor view into the resolution, so sibling player-owned miners at the same tick disagreed on whether a ware was discovered (one ship saw Silicon as discovered, another did not) and the live miner forced urgency=0 on actually-mineable wares. Mirrors vanilla `order.mining.routine.xml` and the diag tool.
FIX: Capital miners without `orecollector`/`gascollector` units no longer enter a `set_order_failed` UI-freezing loop. A pre-check before issuing the mining order parks the ship on `commandaction.standingby` and signals `GT_DoMaintenance` to restock the missing collector drones.
FIX: Subordinate miners now contribute to scouting via fleet-level claims (`global.$GT_ScoutClaims.{ware}`), so multiple ships do not stampede the same undiscovered ware while the commander is also flagged for that ware.
FIX: Scout iteration skips wares already marked `$wareReachable` (commanders no longer fly to "discover" Ore that is already discovered in the home sector), and skips entirely for ships whose cargo is full (`commandaction.standingby` instead of "searching for resources").
FIX: CARGO-FIRST handling, two stages: (1) pre-scoring INJECTION appends cargo wares with willing primary buyers into the candidate set so a ship with deliverable cargo never hits the "no candidate wares" early-return; (2) post-scoring OVERRIDE forces delivery only when the ship cannot productively mine (no scoring winner, selected ware unreachable, or cargo full). Productive mining cycles are not interrupted just because cargo is non-empty.
FIX: `FAIL_NO_BUYER` diagnostic in `order.mining.routine.gt.xml:1824` no longer crashes with `Property lookup failed: $miningbasket` when the sell-only path is reached on cargo-on-arrival cycles (gathering branch skipped, basket never built). All three scope-fragile vars (`$buyoffers`, `$sellspaces`, `$miningbasket`) are now coalesced.
PERF: Per-ware reachability + discovery probe fused into a single loop with cheap MD checks (sector validity + `resources.{ware}.exists` + `yieldrating`) before the expensive `find_closest_resource` engine call, with proper early exit. Old code did two passes over gather sectors with `<do_all>`+`<break/>` (silently broken in MD â€” `break` only works in `do_for_each`/`do_while`/`do_each`) and called the engine on every sector regardless of whether asteroids existed there. Typical reduction: ~80% fewer engine calls per scoring cycle.

GT Diagnose
FEATURE: New "Resource Probes" section enumerates every player-owned `class.resourceprobe` in the galaxy via `find_sector space="player.galaxy"` + per-sector `find_object owner="faction.player"` (`find_object` does not support galaxy-space directly, which silently returned an empty list before). Reports sector, deployer, and discovered yields per probe; categorises as in-range / out-of-range relative to the diagnosed miner.
FIX: Discovery probe now anchors per safe gather sector (same fix as the miner) so the diag's "Discovered: yes/no" matches the miner's own scoring path by construction. Adds an Engine-Knows layer (`useundiscovered="true"`) and a probe-in-known-sector flag to disambiguate "asteroid not discovered" from "no asteroid known to engine".
FIX: `Property lookup failed: $fspData.keys` resolved by typeof-guarding `$fspData` (table-vs-list) before `.keys` access.
FIX: "Would Select" no longer prints `null` â€” explicit `!= null` checks replace bare `?` shortcuts (which return true even for declared-but-null values).
FIX: Em dashes (`â€”`) replaced with ASCII hyphens throughout â€” the em-dash glyph does not render in the in-game UI.
IMPROVEMENT: Per-ware report now lists up to the top 3 sectors with yield, not just the best one.
IMPROVEMENT: Candidate-ware set is the union of `ship.warebasket.list` + `ship.cargo.list` + `$diagMinerOfferWares`, so commander and subordinate diags show the same wares (was a fallback chain that hid divergent wares between fleet members).

GT Maintenance:
FEATURE: Capital miners now restock collector drones (`orecollector` / `gascollector`, target 5, mirrors vanilla `upkeep_management.xml`). Detection folds into the existing `needsEquipment` trigger; per-station eval requires the collector ware to be in stock; shopping-list build trims non-collector unit categories (defense -> tower -> cargo -> repair) to fit the target within the ship's `maxcount`. Insertion runs AFTER the existing-units preservation block so the collector entry is not silently undone.
FIX: Global table persistence for `$GT_ResupplyOrders.{$ship}` switched from chained `set_value name="...subkey"` writes to a single inline `table[...]` literal â€” the chained pattern was unreliable for table-typed values across cue boundaries and produced `Ammo types=null, Unit types=null` shopping lists when the AI script later read the entry. All values pre-coalesced to non-null sentinels; STORAGE VERIFY debug line confirms immediate persistence.

Assist / Fleet:
FIX: GT-controlled subordinates no longer get torn out of the player's fleet when the player strips orders + assignments from a GT commander. Vanilla `order.assist.xml` (lines 100-107) hard-cancels the subordinate's Assist default order whenever `commander.defaultorder == null AND commander.orders.count == 0`, which detached every subordinate that wasn't actively running an inherited child order at that exact tick (typical for ships in scout / searching-resources / standing-by states). Logs showed dozens of `commander: ... does not use orders` errors followed by mass `DETACHED_CLEANUP_REQUIRED` cleanups across the whole fleet on a single player intervention. New `<replace>` patch intercepts that exact `do_if`: for player-owned subordinates that were GT-controlled and whose commander is still a player ship, suppress the cancel and `wait 10-20s` + `<resume label="init"/>` to retry inheritance. Vanilla's existing interrupt handlers (`event_object_order_ready`, `event_object_commander_set`, `event_object_destroyed`, `event_object_abandoned`) keep the loop self-recovering â€” when the commander gets a new order the inherit picks up immediately, and if the commander goes away the abort path fires normally. Non-GT subordinates fall through to vanilla behaviour unchanged.


Version 0.13.2 (2026-04-16)
FIX: MK2 source-station invalid handling now guards `this.$sourceStation` against null object handles before reading `.knownname`/`.idcode` (notification + diagnostics), preventing `Property lookup failed: this.$sourceStation.knownname` spam when a previously selected source station no longer exists.
FIX: Galaxy Miner station-cargo candidate scan now requires `hastag.minable`, preventing non-mineable solids/liquids (e.g. food, hull parts) from entering the ware pool when the ship's warebasket is empty.
FIX: Galaxy Miner reachability pre-filter relaxed (`$minReachableYieldRating` 3 -> 1); low-yield-but-actually-mineable wares are no longer silently dropped before scoring, fixing low-pilot/single-sector miners that stalled on "No mineable wares".
FIX: Galaxy Miner user-supplied `$stationList` no longer silently drops stations outside `$homeSector`; entries are now gated by `$maxSellDistance` (gatedistance from homeSector or current sector), respecting the user's explicit station picks.
FIX: Galaxy Miner intent ETA refresh after each mining slice now uses `player.age + $demandRecheckInterval` (or removes the entry entirely once phase reaches `delivering`), instead of perpetually resetting to `+15s` and inflating `$projectedIncoming` for every coordinated miner.
FIX: Galaxy Miner global intent/assignment tables (`$GT_MinerIntents`, `$GT_MinerStationAssignments`) are now event-cleaned in `UnregisterShip` when a ship is destroyed, preventing stale rows from inflating supplier counts when a miner dies before `on_abort` completes.
FIX: Galaxy Miner `on_abort` now nulls all chunked-loop scratch vars (`this.$minerScore*`, `this.$minerOverflow*`, `this.$minerPrimary*`, `this.$minerAssign*`, `this.$minerIntentBuild*`, `this.$minerDiag*`, `this.$minerPrev*`, etc.) so abort mid-scan no longer leaks ship-blackboard state.
FIX: Galaxy Miner chunked-loop `do_while` / `do_if` conditions are now existence-guarded (`this.$minerXxxIndex? and this.$minerXxxList? and ...`); savegame-resume landing inside a chunk's `<wait>` after a script line shift no longer cascades `Property lookup failed: this.$minerPrevStationIndex / DemandStations / SelectedWare` errors through `prev-station`, `score`, `primary`, `assign`, `intent-build`, `diag`, `cleanup`, `gather-filter`, `candidate-scan`, `buy-offer-scan`, and `demand-sectors-scan` loops (entity 0x3875b log spam at line 1269/1270/1271/1272/1273/1274/1277).
FIX: Galaxy Trader priority-ware reorder/scoring guards now distinguish "missing key" from "exists-but-null"; `this.$effectivePriorityWares?` returns true when the property exists with a null value, so the follow-up `.count gt 0` would crash. Added `!= null` co-guards on `this.$effectivePriorityWares`, `$effectivePriorityWares`, `$pwForReorder`, and the commander/baseorder `.$prioritywares` chain in `order.trade.galaxytrader.xml` (lines 3821 / 3823 / 3827 / 3884 and cache-scoring sites at 7928 / 8218 / 8282), eliminating `Property lookup failed: this.$effectivePriorityWares.count` / `$effectivePriorityWares.count` / `this.ship.commander.defaultorder.$prioritywares.count` spam.
IMPROVEMENT: Galaxy Miner now pre-filters gather sectors for hostile-owner / hazardous (when `takesregiondamage`) / contested-by-attackers / `sectoractivity` blacklist before scoring (mirrors the mining routine's own checks), so wares whose only reachable sector is unsafe are no longer promoted to "reachable" and the miner stops looping on them.
IMPROVEMENT: Galaxy Miner ware-switching now permits a hard-emergency override (`$switchDelta >= $hardEmergencyDelta`) for pilots below level 9; previously these pilots were locked to their first ware and could not respond to crisis-level demand changes.
IMPROVEMENT: Galaxy Miner cooperative chunk sizes raised for cheap iteration loops (ware scoring 4 -> 10, candidate scan 5 -> 10, primary/assign/intent-build 6 -> 10, demand-sectors 3 -> 5), reducing yield count while leaving heavy live-search and buy-offer loops at their conservative widths.


Version 0.13.1 (2026-04-16)
FIX: Galaxy Miner chunked-loop index math corrected to stable 1-based list indexing (`start + offset - 1`), removing `{count+1}` overrun lookups and related demand/assignment/runtime property errors.
FIX: Galaxy Miner ware-scoring hardening against null wares (candidate normalization + guarded reachability/scoring writes), preventing `{null}` table-key writes and `resources.{null}` lookup crashes.
CHANGE: MK3 clearance mode (`sell_only` / CL) now always uses fallback trading price thresholds (`FallbackSellPriceMax` / `FallbackBuyPriceMin`) for cargo liquidation searches.
CHANGE: DISABLED XP-blocked logbook message
FIX: Diagnose tool miner verdict logic is now order-aware: `GalaxyMiner` no longer reports false "No sell offers" when buyer offers exist (miner path evaluates sell opportunities via buy offers).
FIX: Diagnose tool miner snapshot handling now guards null selected ware access, preventing `$diagMinerSelectedWare.hastag` property lookup failures.
FIX: MK4 Supply `serveHomeOnly` now preserves station-home scope for station-assigned ships (no unintended commander-home override), so dedicated suppliers remain restricted to their configured home station while sector-home ships keep sector-wide scope.


Version 0.13.0 (2026-04-15)
REFACTOR: Removed unreachable legacy `ExecuteTrade` scaffold in `gt_trading_execution.xml` (bridge-only cue retained for stale callers), reducing dead code and simplifying maintenance.
FIX: Reservation-aware demand subtraction is now applied in `lib.gt.tradematch` for all trade modes (including MK3), not only MK4 supply mode.
FIX: Effective destination demand now subtracts both vanilla incoming reservations (`get_ware_reservation`) and GT in-flight reservations before trade acceptance, preventing storage overfill selection paths.



Version 0.12.10 (2026-04-13)
FIX: Ship modifications now reconcile for fleet commanders when the ship still has a direct GT default order but GT order-status briefly reported non-GT (subordinates were unaffected).
FIX: Save-load ghost Galaxy Miner state now self-heals for legacy saves (ships stuck with `default/current=GalaxyMiner` but no active orders are restarted once on load).
FIX: MK1 and MK2 `on_abort` cleanup bridge now suppresses `GT_Order_Cancelled` when GT control is still active (direct order or GT commander), preventing false orphan cleanup.
FIX: `order.wait` cleanup bridge now suppresses duplicate direct-abort signaling when detached cleanup was already emitted moments earlier.
FIX: `HandleShipOrderAborted` now resolves pilot from the current ship when signal payload omits `$Pilot`, preventing false missing-pilot cleanup paths.


Version 0.12.9 (2026-04-12)
FIX: Pilot transfer/reassignment reliability improved; MK3 and MK4 no longer cancel too early during temporary missing-pilot transfer states.
FIX: Promote command now auto-preserves station attachment for station-assigned fleets (e.g. MK1); promoted commander inherits old commander parent assignment immediately and old commander is reattached with the promoted ship's former subordinate role.
FIX: When a fleet commander is destroyed and a subordinate is promoted (vanilla takeover), GT default-order continuity is now preserved so the promoted commander resumes a valid GT order and remaining subordinates keep GT functionality.
IMPROVEMENT: MK4 trade search now evaluates all candidates each cycle and no longer stops early on truncated validation windows.
IMPROVEMENT: MK4 multitrade planning and execution now follow MK1 behavior more closely, including single-trade preference, better route grouping, and reduced zig-zag buying.
IMPROVEMENT: MK4 scheduler stability was improved (stale live-slot self-heal, better queue handling, higher concurrency), reducing stuck/timeout no-trade cycles.
IMPROVEMENT: MK4 queued trade reporting/logging and diagnostics now better reflect real multitrade runtime behavior.
FIX: Player Info -> Personnel tagged-name updates are now page-scoped (visible page only) instead of processing the full personnel list, reducing UI stutter with large pilot rosters.
FIX: Pilot name/tag rendering in UI now strictly respects `ShipNaming.$PilotRenamingEnabled`; when disabled, Personnel and crew highlight overrides no longer apply GT rename tags.
CHANGE: Settings toggle now triggers immediate MD->Lua pilot config sync so `PilotRenamingEnabled` changes take effect without delayed refresh.


Version 0.12.8 (2026-04-11)
CHANGE: MK1 return-home behavior now uses a persistent per-ship undocked state between trade cycles.
FIX: With "Return Home Between Cycles" enabled, ships dock at home, undock after 60s without valid trades, and remain undocked until trades are found.
FIX: Return-home/no-trade retry flow is now consistent across Assist/MK1 handoffs and restarts, preventing unwanted immediate re-docking loops.
IMPROVEMENT: Hard selltarget fallback now follows the same return-home state flow as other no-trade outcomes.
FIX: MK1 queued trade amount is now hard-clamped by real cargo-volume capacity at final queue build, preventing queue/log amounts from exceeding ship capacity.
CHANGE: MK1 queue logbook output now uses single-entry mode per cycle: single-trade cycles keep the existing per-trade queue message, while multi-trade cycles write one dedicated multitrade queue summary with aggregated expected profit and transaction footer.
CHANGE: Trade completed logbook entries are disabled; queued trade entries remain active.


Version 0.12.7 (2026-04-11)
FIX: MK3 detached/orphaned subordinate cleanup now always cancels active/default orders for `DETACHED_CLEANUP_REQUIRED`, preventing stale native order state from surviving cleanup.
FIX: MK3 trade-search scheduler now self-heals stale per-ship live-active state (`LiveActiveShips` / `PhaseStateByShip`) before dedup checks, preventing ships from getting stuck as permanently active/not-queued.
FIX: MK3 `GT_ClearPendingTradeData` now always aborts scheduler state via `GT_Search_Abort` before request-registry release; deep registry cleanup also runs for `ship_destroyed` paths.
FIX: MK3 buy clamp now uses `buyer="this.assignedcontrolled"` (vanilla parity) to avoid invalid buyer context during amount clamping.
FIX: MK3 stale temporary ship accounts are now auto-cleared (vanilla parity) at init and during runtime pre-search self-heal when no active tradeorders exist, allowing affected ships to recover without remove/reattach.
CHANGE: MK1 sell policy now allows zero-profit fulfillment: trades are valid up to the station buy-price cap (e.g. station price 12 Cr allows sell price 12 Cr), while negative-profit trades remain rejected.
FIX: Galaxy Miner home anchor UI now uses a position selector (`homePosition`, class.sector) and derives `homeSector` from it, avoiding sector-selector UI issues for affected players.
CHANGE: Legacy Galaxy Miner orders/saves with `homeSector` are auto-migrated to `homePosition` at runtime while preserving backward compatibility.
FIX: MK1 multi-trade logbook output now reports each queued trip/leg with per-leg buy/sell price and per-leg profit instead of effectively showing only the first leg.
FIX: MK1 queued trade logging now uses trade-match snapshot prices (`$BuyPrice`/`$SellPrice`) for per-leg P/L payloads, preventing drift/negative artifacts from late live-offer price changes.
IMPROVEMENT: MK1 multi-trade cycles now write an aggregate route summary entry with trip count and total cycle profit.


Version 0.12.6 (2026-04-10)
FIX: Galaxy Miner ware selection now filters unreachable wares before scoring; wares without any reachable resource sector in current gather range are skipped instead of causing "No resources found in range" order failures.
CHANGE: Galaxy Miner tie handling for equal urgency wares is now randomized among top candidates (`$bestWares.random`) to avoid deterministic first-ware bias and reduce persistent ore-only lock-in when demand is equal.
IMPROVEMENT: Miner demand scoring now includes vanilla real incoming reservations (`get_ware_reservation`, type sell, virtual=false/default) so wares with already incoming deliveries are deprioritized against equally empty wares without incoming flow.
CHANGE: Incoming forecast merge for miner scoring/station choice/intent sizing now uses `max(GT intents, vanilla reserved incoming)` to prevent double-counting overlapping in-flight supply.
FIX: Galaxy Miner pilot jump-cap derivation is now computed inline from pilot level (MK3/MK4 parity), removing fragile dependency on external return values and preventing `did not provide a return value` failures in distance-cap setup.
FIX: Galaxy Miner lifecycle diagnostics (`Init complete`, `Entered main loop`, `on_abort cleanup`) now respect the global debug toggle via `this.$debugchance` instead of unconditional logging.
CHANGE: MK1 multi-trade now allows any ware combination in one route (including repeated wares), instead of forcing distinct-ware-only chaining.
CHANGE: MK1 route expansion is now strictly "up to 3 trades" and stops early as soon as selltarget is reached (1/2/3 trades as needed).
FIX: MK1 multi-trade destination ordering is normalized by sell-destination sector before queueing, preventing sector zig-zag execution patterns (A->B->A) while preserving selected trade set.
FIX: MK1 no-backtrack and route diagnostics now use sell-destination semantics (`$SellStation`/`$SellSector`) to match actual execution path.
FIX: MK1 trade filtering now drops invalid/expired matched offers before trade-rule `cantradewith` checks, preventing `Property lookup failed` on stale `$SellOffer`/`$BuyOffer` handles.
FIX: MK1 debug output now consistently respects the global debug toggle (`EnableDebugLogging`); verbose diagnostics (`WARE_SNAPSHOT*`, `SELL_OFFER_SNAPSHOT`, `SINGLE_FULL_SCAN`, `ROUTE_PLAN`) no longer log when global debug is disabled.
IMPROVEMENT: In-game Diagnose tool (MK1 section) now shows persisted runtime snapshots for `WARE_SNAPSHOT*`, `SELL_OFFER_SNAPSHOT`, and `ROUTE_PLAN` (including pending/fallback states when no cycle snapshot exists yet).
FEATURE: MK2 same-lane multi-ware batching (up to 3 wares per cycle) now combines low-volume + high-volume deliveries for one source->destination pair instead of forcing single-ware runs.
FIX: `order.assist` MK4 inheritance now uses canonical MK4 Supply parameters (`home`/`assignHome`/`allowBuildstorage` etc.) with guarded legacy fallbacks, preventing `Property lookup failed` errors on stale fields like `$homeStation`, `$homeSector`, `$buildStationsOnly`, `$allowProducts`.


Version 0.12.5 (2026-04-08)
FIX: GT Info Menu pilot-data refresh now filters invalid/stale ship registry keys before idcode sorting (`md.GT_InfoMenu_Loader.SendPilotData`), preventing `Property lookup failed: loop.element.idcode` during transient cleanup races.
FIX: MK4 supply matching (`lib.gt.tradematch`) is reservation-aware for player destinations: subtracts vanilla `get_ware_reservation` (type sell on buyer) from effective demand before scoring, so wares with no remaining need after reservations are skipped early (e.g. Energy Cells when build storage is effectively full).
IMPROVEMENT: MK4 validation diversifies the first top-N chunk by ware before checks, reducing repeated same-ware candidates monopolizing `maxTrades`.
IMPROVEMENT: When that validation chunk rejects all trades but more candidates remain, MK4 immediately continues with the next chunk (`resume trade_found`) instead of entering retry cooldown first.
CHANGE: MK4 validation budget switched to Option A round-robin composition by delivery target with strict Build Storage first, keeping global `maxTrades` cap while improving target fairness.
IMPROVEMENT: Build Storage target ordering now prioritizes smallest absolute remaining demand first, helping finish near-complete construction bottlenecks sooner.
CHANGE: MK4 profit policy now enforces only price-cap semantics (`sourcePrice <= playerBuyPrice`); zero-profit fulfillment is valid, buying above allowed station buy price is rejected.
CHANGE: `ignoreTradeRules` scope for MK4 is limited to faction-access bypass only; it no longer bypasses player-customer policy, reservation-aware demand gate, price cap, legality, path, or docking checks.
FIX: MK4 demand gate now subtracts both vanilla incoming reservations and GT in-flight reservations (global) from destination demand before scoring/filtering.
FIX: `lib.gt.live.search` now guarantees a per-ware reserve slice for player Build Storage buy offers so valid Build Storage demand is not crowded out by generic per-ware caps.
FIX: `lib.gt.live.search` seller search now honors `includePlayerSellOffers=true`; player-owned suppliers (e.g. Headquarters/intermediate stock) are no longer excluded from supplier candidates.


Version 0.12.4 (2026-04-04)
FEATURE: MK1 new order parameter "Cargo/Profit" (`sellselectionmode`) to switch between profit-first and cargo-fill-first sell selection.
CHANGE: MK1 cargo mode now prioritizes highest station ware fill for primary and secondary ware selection (score tie-break).
CHANGE: MK1 cargo mode fill % is reservation-aware (`get_ware_reservation` type buy on home station): effective count excludes other ships' reservations so heavily reserved wares are deprioritized vs. equally full but unreserved stock.
CHANGE: MK1 now prefers a single full-cargo trade run over multi-ware chaining when a valid single run can satisfy selltarget.
FIX: MK1 multi-ware selection now enforces one shared remaining cargo-volume budget across secondary wares.
FIX: MK1 queued trade creation switched to phased queueing to avoid alternating buy/sell mini-runs while preserving load-before-sell execution safety.
FIX: MK1 single full-cargo preference uses queueable clamped amounts (offer/capacity-aware), preventing over-100% fill mis-selection.
FIX: Ship status labels keep `TR` during active training; blocked label logic remains separate.
FIX: Pilot redistribution excludes blocked pilots and ships already in active/queued pilot-exchange orders.
FIX: Pilot exchange is now session-driven and save/load persistent (`global.$GT_PilotExchangeSessions` / `...ByShip`) with reliable swap trigger and cleanup.
FIX: Captain swap execution resolves ships by authoritative idcode/UID and applies idempotent pair execution.
FIX: Abort/fail/release handling is race-hardened with delayed aborted-session recheck before terminal cleanup.
FIX: Ship mod reconciliation keeps already-correct GT mods in place (no unnecessary dismantle/reinstall).
REFACTOR: Removed legacy swap-tracker scaffolding; kept one authoritative MD session pipeline.
REFACTOR: Centralized PE state checks/name-refresh triggers in `md.GT_Ship_State_Utilities`.
CHANGE: Fleet commander swaps only when receiving a same-class pilot from a higher penalty tier.


Version 0.12.3 (2026-04-01)
IMPROVEMENT: Persistent pilot identity ($StableIdentity: seed/idcode) for XP recovery on ship transfer and vanilla crew swaps
FIX: Crew highlight reliability overhaul via PilotIdMap hardening (removed non-unique `npctemplate`, robust alias lookup, bridge-first matching)
FIX: PilotIdMap update handling made safe (empty updates ignored, partial snapshots merged, no Lua map wipes)
FIX: 64-bit NPC seed bridge corrected end-to-end (`u64p:hi32:lo32`, signed hi/lo support, canonical uint64 decode) to prevent missed highlights on large seeds
IMPROVEMENT: PilotIdMap diagnostics cleaned up (map-health counters + throttled miss logging)
ADD: Logbookmessages for miners
IMPROVEMENT: Miner sets the current sector as base if none selected
FIX: MK1 supply had missing cargo compatibility check (liquid/solids)
ADD: tradequeue logbookmessage MK1
FIX: Shiprenaming toggle hardening
FIX: lib.gt.cache.write â€” sector cache can be removed mid-write (e.g. priority-ware cache clear); re-ensure list per trade and null-safe counts to avoid Property lookup failed / append_to_list on null
CHANGE: Trade cache invalidation (priority wares + MK4 policy) only on real order-setup deltas â€” baseline init no longer clears cache; MK3/MK4 search pipeline stores signature every run


Version 0.12.2 (2026-03-30)
IMPROVEMENT: MK4 buildstorage priority (if buildstorage allowed it gets priority over all other demands)
CHANGE: MK4 trade search uses full buy/sell price range (not limited by global min/max settings)
CHANGE: MK4 â€œserve home onlyâ€ strictly targets the home station or home sector (build storage still follows allowBuildstorage rules)
ADD: MK4 option to disable minimum cargo utilization threshold (default: threshold on)
IMPROVEMENT: In-game diagnose tool covers MK4 (params, queue/cache, filters)
FIX: MK4 supplemental build-storage scan respects manual ware basket
IMPROVEMENT: free miner logic
FIX: Keep GT pilot registration/XP when a trader ship is destroyed and the pilot survives (rescue/reassignment case)
CHANGE: 9.0 BETA 3 changes adapted


Version 0.12.1 (2026-03-28)
FIX: MK4 XP gain
FIX: MK4 renaming
FIX: MK4 tradequeue messages
FIX: Crewmember highlighting fur duplicate names
FIX: Mining  sell behaviour


Version 0.12.0 (2026-03-22)
FEATURE: MK4 supply trader
FEATURE: Vanilla Mode
IMPROVEMENT: Diagnose lists training station candidates when pilot is XP/training blocked.
CHANGE: Miner XP calculation
FIX: subordinate level up range refresh
FIX: Reservation cleanup uses default order / commander chain (not script-name-only).
REFACTOR: MD split into `glx_lib_orders`, `glx_lib_trading_log`, `glx_lib_reservations`, `glx_lib_cache`, `glx_lib_settings_menu`; GT order checks via `$GT_ProtectedOrderIDs`; libraries renamed `GLX_*`; unused MD cache helpers removed.
smaller fixes and cleanup


Version 0.11.4 (2026-03-20)
CRITICAL: Standardized ship payload key to $Ship across GT queues/signals (removed ship/Ship mismatch errors)
CRITICAL: Trade success/failure queue payloads now consistently write/read $Ship (prevents null property lookup in MD cues)


Version 0.11.3 (2026-03-17)
IMPROVEMENT: ingame diagnose tool
ADD: new shared lib for warefiltering
IMPROVEMENT: search pipeline code refactoring to use single source warefilter
FEATURE: MK3 new order option "Illegal Route Filter". avoids intermediate sectors for illegal wares
CHANGE: Added route-signature/epoch-aware legality cache to avoid stale legality decisions when topology changes
IMPROVEMENT: Route legality gate now runs in cache prefilter, live tradematch, and final pre-order safeguard


Version 0.11.2 (2026-03-15)
FIX: MK1 supply illegal ware flag not passed
ADD: Priority Warefilter


Version 0.11.1 (2026-03-14)
FIX: Miner sell to player stations only

Version 0.11.0 (2026-03-13)
UPDATE: Gameversion 9-BETA


Version 0.10.11 (2026-03-13)
FIX: GT_Config settings (Notifications, Defense, Fleet, Market, WareFilter, Debug) now persist across save/load â€” ConfigInitV3 now re-applies saved values instead of overwriting with defaults
FIX: Galaxyminer sell routine
fix:  notification setting persistence across saves


Version 0.10.10 (2026-03-13)
ADD: All notification settings exposed to global settings menu (Notifications section): Level-Up Popup, Training Required Alerts, Training Completed, Profit Reports, Market Alerts, Fleet Updates â€” each with enable/disable toggle
CHANGE: Combined redundant training notifications into single green message (level-up + XP unlocked)
FIX: Register_Ship missing required parameters (config, pilot) when called from Update_Ship_Performance_Display â€” fixes "Required library parameter 'config'/'pilot' for Register_Ship was not provided" errors


Version 0.10.9 (2026-03-09)
IMPROVEMENT: Cache search (lib.gt.cache.search) now supports sell-only mode for cargo disposal â€” filters by searchMode and ship wareBasket so disposal ships get correct cache hits
FIX: Sell-only cache now filters by ship cargo â€” cache hits only return trades for wares the ship actually carries (fixes "all 50 trades rejected" when cargo disposal got wrong-ware cache hits)
FIX: Credits due and trade reservations now cleared when fleet commander GT order revoked
FIX: Periodic cleanup (every 5 min) for orphan credits due/reservations when cleanup was missed (save/load, edge cases)
FIX: Clear ALL reservations at game load - stale reservations from prev session were blocking new GT ships from finding trades
FIX: Subordinates: clear credits due/reservations on commander lost GT (was skipped by design)
FIX: Subordinates: clear credits due/reservations when TradePerform cancelled (main branch no longer skips subordinates)
FIX: Pilotexchange: in some cases swapped higher lvl pilots in lower classes
FIX: minor adjustments and fixes


Version 0.10.8 (2026-03-08)
CHANGE: MK1/MK2/MINER  make use of GT  level instead of Vanilla
FIX: Ship mods not reconciled after pilot exchange
FIX: Pilotexchange fixed raceconditions
IMPROVEMENT: Shipstate improvements and Shipmod installations are now faster and do not rely on order recycle


Version 0.10.7 (2026-03-07)
IMPROVEMENT: Ship mods install immediately when enabling in settings (no order recycle needed) â€” uses toggle value from signal for GT registered ships
FIX: MK1 Supply orders queued in wrong order
FIX: Pilotdata not updated after Pilotexchange causes missing ship-modifications


Version 0.10.6 (2026-03-06)
CRITICAL: DismantleMod now validates installed mod is GT before dismantling â€” prevents player-installed mods from being removed when ship mods are disabled
CHANGE: Pilot Redistribution Rule update
FIX: some minor fixes to logging
IMPROVEMENT: ingame diagnostic tool improvements


Version 0.10.5 (2026-03-05)
FEATURE: MK3 Factionfilter (context menue)
FIX: Miner max gather distance was not respected
FIX: Station => Commander => Subordinate  got no mods installed 
FIX: Pilotexchange Dockingcheck
FIX: Station Traderules not respected
IMPROVEMENT: MK1 trader search prefilter relaxed
ADD: Global setting to enable/disable level-up notifications
CHANGE: level-up notifications color changed to green


Version 0.10.4 (2026-03-05)
FIX: Miner routine fixed
FIX: Vanilla Pilotexchange tracking


Version 0.10.3 (2026-03-04)
CHANGE: Making MK1 Cargo threshold a hard rule
CHANGE: Shipmodification level requirement
FIX: Pilotexchange dockingcheck
CHANGE: Blacklist assignment is now done manually in global settings
FIX: some minor fixes


Version 0.10.2 (2026-03-03)
FEATURE: Rename GT Pilots for easier assignment adds a prefix (T:[Level])
T stands for Trading. Future updates will also Include F for Fighting
FEATURE: Pilot redistribution automatically reassigns pilots to higher shipclasses by level
FEATURE: Promote automatically assigns a subordinate to the new fleetcommander
FIX: MK1 was broken


Version 0.10.1 (2026-03-03)
FIX: Tradesearch Homesector origin had do be within  max gatedistance from ships current position.
FIX: fallback center logic if ship is to far away from homesector


Version 0.10.0 (2026-03-01)
FEATURE: Miner Routine added (ALPHA release not tested yet)
FIX: Buy/Sell Price setting not persistent across Saves
FIX: Shipmodifications were dismantled on savegame load and reinstalled on next cycle
FIX: Tradequeuemessage used a stored value instead of the current value which caused in rare cases sell < buy prices but positiv profit (display issue only)
FIX: Fallback flag not cleared properly (display issue only)
IMPROVEMENT: ingame Diagnostic tool


Version 0.9.4 (2026-02-24)
FIX: Shipmodifications MK1/MK2 not updating after lvl up
FIX: GT_Trade_Failed guarded to prevent NULL value spam
IMPROVEMENT: Game-Startup repair Script re-registering GT ships correctly if stale from previous saves
IMPROVEMENT: Shipmod Ware detection
FIX: few smaller fixes


Version 0.9.3 (2026-02-22)
FIX: MK1 and MK2 was missing a Training Signal
IMPROVEMENT: Shipmod reconcile to fix broken shipmods from previous versions


Version 0.9.2 (2026-02-21)

MK2:
ADD: pre-queue availability recheck
CHANGE: Offer selection behaviour in  rare cases caused  no trades
FIX: racecondition on tradeverification level
FIX: Ship state cleanup when assignment for subordinated  was removed


Version 0.9.1

IMPROVEMENT: added intelligence to MK2 routeplanning
FIX: some smaller fixes and  optimizations


Version 0.9.0

FEATURE: MK2 implemented
ADD: Galaxy-Trader due to trades Amount
IMPROVEMENT: XP Training-System refactor and optimization (hardening against possible race conditions)
CHANGE: favor playerstations for repair/maintenance/resupply


Version 0.8.1

FIX: MK1 Global Settings show  in development message
IMPROVEMENT: Reroute detection  improvement
IMPROVEMENT: two Phase Scheduler
IMPROVEMENT: queue fairness across fleets/home sectors
IMPROVEMENT: Universal Cache improvement
IMPROVEMENT: Cache search now respects minimum cargo utilization threshold (isolated mode excluded)
IMPROVEMENT: further Savegame compatibility
IMPROVEMENT: ingame Diagnostic tool
FIX: ingame Diagnostic tool didn't take Blacklists into account
FIX: Pilot behavior now uses GT XP/Level only (no vanilla-skill behavior dependency)
CHANGE: Vanilla management skill sync is raise-only (never lowered/reset)
ADD: Unreachable Flag and Logbookmessage if Profitable trades blocked by Blacklist
-
Planned for 0.8.2
Station cap
Failiure Tracking/Reasoning
Maintenance/Repair favor Playerstations setting

Planned for 0.9.0
MK2 Distribution Trader
Global Settings Shared,MK1,MK2,MK3 specific

Version 0.8.0

FIX: Trannslation files for Global-Settings
FIX: Slider values in Global-Settings
IMPROVEMENT: save game compatibility from older versions <= 7.x
CHANGE: removed Cachesetting Profit Threshold (already handled by Profit filtering)
CHANGE: default values for Price-Ranges
FIX: offeramount parameter in the search pipeline caused pricerange not to work
FIX: brought back the Fallback-Search (was lost during migration)
ADD: used Searchpipeline to Logbookmessages
a little bit of this and that codecleanup and smaller changes


Version 0.8.0-RC-1

FIX: REPAIR and MAINTENANCE station search  was broken
FIX: Shipmodification check on  current Playerresearch was broken
other small fixes


Version 0.8.0-BETA-3.1

FIX. deployment script corrupted xml files. release BETA-3 was broken
FEATURE: added MK1 Traderoutine
FEATURE: added Subordinate Order Access when ships assigned to stations
FEATURE: MK1 Multiware trading up to 3 wares
FEATURE: MK3 ignore MK1 Stations
CHANGE: migrated trade pipeline from MD to AI

Version 0.8.0-BETA-3

FIX: Safe queue and property access to prevent logging errors
IMPROVEMENTS: multiple, no specifics
FEATURE: added Minimal Player Money. Below this value ships will not  creating trades
FEATURE: add Diagnostics accessable via context menue


Version 0.8.0-BETA-2

FIX: illegal ware check took owner faction into account. now illegal wares are blocked entirely if  not allowed
IMPROVEMENT: make cache more ship agnostic
FIX: Translation for performanmce section was messed up
IMPROVEMENT: change cache sorting to score
IMPROVEMENT: Force frame delay after each ship


Version 0.8.0-BETA-1

FIX: Cache revalidation.
FIX: Gravidar Enemy Detection  lvl requirement (6+)
FIX: Money Field in trade queue messages (was double devided by 100)
FIX: add lastFinished timestamp for proper wakeUpCalls after a liveSearch  has completed
IMPROVEMENT: delete pending trades fallback => Faster traderesponse for ships
IMPROVEMENT: Cache distance calculation 
IMPROVEMENT: LiveSearch distance calculation 
IMPROVEMENT: relaxe Clamping

Version 0.8.0-BETA

FEATURE: Hybrid implementation of the search engine
FIX: Clamping calculation fix which prevented certain trades to be available (mostly good ones :-/)
FIX: renaming mechanism
FIX: Isolated Searchmode and Fallback-Searchmode logical flow
ï»¿<?xml version="1.0" encoding="utf-8"?>
<content id="GalaxyTraderMK3" name="GalaxyTrader MK3" description="Advanced Trading AI with XP Progression System" author="GoAhead" version="01504" date="2026-07-03" save="0" enabled="1">
  <text language="44" name="GalaxyTrader MK3" description="Advanced Trading AI with XP Progression System" author="GoAhead" />
  <text language="49" name="GalaxyTrader MK3" description="Advanced Trading AI with XP Progression System" author="GoAhead" />
  <text language="55" name="GalaxyTrader MK3" description="IA de ComÃ©rcio AvanÃ§ada com Sistema de ProgressÃ£o de XP" author="GoAhead" />
  <!-- Dependencies -->
  <dependency version="900" optional="false" name="X4: Foundations 9.00" />
  <dependency id="ws_2042901274" optional="false" name="SirNukes Mod Support APIs" />
  <dependency id="kuerteeUIExtensionsAndHUD" optional="false" name="kuertee UI Extensions and HUD" />
  <dependency id="ego_dlc_boron" optional="true" name="Boron DLC" />
  <dependency id="ego_dlc_split" optional="true" name="Split DLC" />
  <dependency id="ego_dlc_terran" optional="true" name="Terran DLC" />
  <!-- Libraries -->
  <libraries>
    <library path="libraries/wares.xml" />
    <library path="libraries/equipmentmods.xml" />
  </libraries>
</content><?xml version="1.0" encoding="utf-8"?>
<diff xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <!-- GT Ship Modifications - Ship Mods (Agility Focus) -->
  <add sel="/equipmentmods/ship">
    <!-- Level 1: -5% mass, +10% radar range (Lowest Quality) -->
    <maxhull ware="mod_ship_gt_level1" quality="1" min="1.0" max="1.0">
      <bonus chance="1.0" max="2">
        <mass min="0.95" max="0.95" weight="1"/>
        <radarrange min="1.10" max="1.10" weight="1"/>
      </bonus>
    </maxhull>
    
    <!-- Level 2: -10% mass, +20% radar range (Rare Quality) -->
    <maxhull ware="mod_ship_gt_level2" quality="2" min="1.0" max="1.0">
      <bonus chance="1.0" max="2">
        <mass min="0.90" max="0.90" weight="1"/>
        <radarrange min="1.20" max="1.20" weight="1"/>
      </bonus>
    </maxhull>
    
    <!-- Level 3: -25% mass, +40% radar range (Highest Quality) -->
    <maxhull ware="mod_ship_gt_level3" quality="3" min="1.0" max="1.0">
      <bonus chance="1.0" max="2">
        <mass min="0.75" max="0.75" weight="1"/>
        <radarrange min="1.40" max="1.40" weight="1"/>
      </bonus>
    </maxhull>
  </add>

  <!-- GT Ship Modifications - Engine Mods (Agility Focus) -->
  <add sel="/equipmentmods/engine">
    <!-- Level 1: +20% rotationthrust, +10% strafethrust (Lowest Quality) -->
    <forwardthrust ware="mod_engine_gt_level1" quality="1" min="1.0" max="1.0">
      <bonus chance="1.0" max="2">
        <rotationthrust min="1.20" max="1.20"/>
        <strafethrust min="1.10" max="1.10"/>
      </bonus>
    </forwardthrust>
    
    <!-- Level 2: +50% rotationthrust, +25% strafethrust (Rare Quality) -->
    <forwardthrust ware="mod_engine_gt_level2" quality="2" min="1.0" max="1.0">
      <bonus chance="1.0" max="2">
        <rotationthrust min="1.50" max="1.50"/>
        <strafethrust min="1.25" max="1.25"/>
      </bonus>
    </forwardthrust>
    
    <!-- Level 3: +120% rotationthrust, +60% strafethrust (Highest Quality) -->
    <forwardthrust ware="mod_engine_gt_level3" quality="3" min="1.0" max="1.0">
      <bonus chance="1.0" max="2">
        <rotationthrust min="2.20" max="2.20"/>
        <strafethrust min="1.60" max="1.60"/>
      </bonus>
    </forwardthrust>
  </add>

  <!-- GT Penalty Modifications - Ship Mods (Skill Limitation Penalties) -->
  <!-- NOTE: Ship mods only affect ship properties (mass, radarrange, etc.), not engine properties -->
  <!-- Separate wares for ship and engine mods (X4 doesn't allow same ware for both types) -->
  <add sel="/equipmentmods/ship">
    <!-- Severe Penalty: +90% mass -->
    <maxhull ware="mod_penalty_ship_severe" quality="1" min="1.0" max="1.0">
      <bonus chance="1.0" max="1">
        <mass min="1.90" max="1.90" weight="1"/>
      </bonus>
    </maxhull>
    
    <!-- Moderate Penalty: +50% mass -->
    <maxhull ware="mod_penalty_ship_moderate" quality="1" min="1.0" max="1.0">
      <bonus chance="1.0" max="1">
        <mass min="1.50" max="1.50" weight="1"/>
      </bonus>
    </maxhull>
    
    <!-- Light Penalty: +20% mass -->
    <maxhull ware="mod_penalty_ship_light" quality="1" min="1.0" max="1.0">
      <bonus chance="1.0" max="1">
        <mass min="1.20" max="1.20" weight="1"/>
      </bonus>
    </maxhull>
  </add>

  <!-- GT Penalty Modifications - Engine Mods (Skill Limitation Penalties) -->
  <!-- NOTE: Cannot use forwardthrust as both main property and bonus property -->
  <!-- Main property affects forwardthrust, bonus properties affect rotationthrust and strafethrust -->
  <!-- Separate wares for ship and engine mods (X4 doesn't allow same ware for both types) -->
  <add sel="/equipmentmods/engine">
    <!-- Severe Penalty: -90% forwardthrust (main), -90% rotationthrust (bonus) -->
    <forwardthrust ware="mod_penalty_engine_severe" quality="1" min="0.10" max="0.10">
      <bonus chance="1.0" max="1">
        <rotationthrust min="0.10" max="0.10"/>
      </bonus>
    </forwardthrust>
    
    <!-- Moderate Penalty: -50% forwardthrust (main), -50% rotationthrust (bonus) -->
    <forwardthrust ware="mod_penalty_engine_moderate" quality="1" min="0.50" max="0.50">
      <bonus chance="1.0" max="1">
        <rotationthrust min="0.50" max="0.50"/>
      </bonus>
    </forwardthrust>
    
    <!-- Light Penalty: -20% forwardthrust (main), -20% rotationthrust (bonus) -->
    <forwardthrust ware="mod_penalty_engine_light" quality="1" min="0.80" max="0.80">
      <bonus chance="1.0" max="1">
        <rotationthrust min="0.80" max="0.80"/>
      </bonus>
    </forwardthrust>
  </add>

</diff>
<?xml version="1.0" encoding="UTF-8"?>
<diff>
	<add sel="/icons">
		<icon name="order_galaxytradermk3" texture="assets\textures\ui\order\order_traderoutine.tga" height="32" width="32"/>
		<icon name="order_galaxytradermk1" texture="assets\textures\ui\order\order_traderoutine.tga" height="32" width="32"/>
		<icon name="order_galaxytradermk2" texture="assets\textures\ui\order\order_traderoutine.tga" height="32" width="32"/>
		<icon name="order_galaxytradermk4supply" texture="assets\textures\ui\order\order_traderoutine.tga" height="32" width="32"/>
		<icon name="order_galaxytradermk4supply2" texture="assets\textures\ui\order\order_traderoutine.tga" height="32" width="32"/>
		<icon name="order_trainingsession" texture="assets\textures\ui\order\order_dockat.tga" height="32" width="32"/>
		<icon name="order_trainperform" texture="assets\textures\ui\order\order_dockat.tga" height="32" width="32"/>
		<icon name="order_dockandtrain" texture="assets\textures\ui\order\order_dockat.tga" height="32" width="32"/>
		<icon name="order_dockandpilotexchange" texture="assets\textures\ui\order\order_dockat.tga" height="32" width="32"/>
		<icon name="order_dockandreturnhome" texture="assets\textures\ui\order\order_dockat.tga" height="32" width="32"/>
		<icon name="order_gtidlepark" texture="assets\textures\ui\order\order_dockandwait.tga" height="32" width="32"/>
		<icon name="mapst_galaxytrader" texture="assets\textures\ui\order\order_traderoutine.tga" height="32" width="32"/>
	</add>
</diff> <?xml version="1.0" encoding="utf-8"?>
<diff xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <add sel="/wares">
    <!-- GT Ship Modifications - Level 1 -->
    <!-- NOTE: These modifications are GT-only and automatically installed by the GalaxyTrader system. -->
    <!-- They are not available for purchase, crafting, or manual installation by players. -->
    <ware id="mod_ship_gt_level1" name="Consortium Standard Refinement" description="Trade Consortium Standard Refinement - A basic structural enhancement that reduces hull mass and improves sensor range. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="5000" average="7500" max="10000" />
    </ware>
    <ware id="mod_engine_gt_level1" name="Consortium Standard Maneuverability" description="Trade Consortium Standard Maneuverability - A standard thruster upgrade package that enhances ship rotation and strafing capabilities. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="5000" average="7500" max="10000" />
    </ware>
    
    <!-- GT Ship Modifications - Level 2 -->
    <ware id="mod_ship_gt_level2" name="Consortium Rare Enhancement" description="Trade Consortium Rare Enhancement - An advanced structural modification that significantly reduces hull mass and dramatically improves sensor range. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="10000" average="15000" max="20000" />
    </ware>
    <ware id="mod_engine_gt_level2" name="Consortium Rare Thruster System" description="Trade Consortium Rare Thruster System - A rare thruster enhancement that provides exceptional rotation and strafing performance. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="10000" average="15000" max="20000" />
    </ware>
    
    <!-- GT Ship Modifications - Level 3 -->
    <ware id="mod_ship_gt_level3" name="Consortium Lost Technology" description="Trade Consortium Lost Technology - Legendary structural refinement recovered from the lost Consortium ship. Provides exceptional mass reduction and sensor range improvements. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="20000" average="30000" max="40000" />
    </ware>
    <ware id="mod_engine_gt_level3" name="Consortium Lost Propulsion Technology" description="Trade Consortium Lost Propulsion Technology - Legendary thruster system recovered from the lost Consortium ship. Provides unmatched rotation and strafing capabilities. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="20000" average="30000" max="40000" />
    </ware>
    
    <!-- GT Penalty Modifications - Skill Limitation Penalties -->
    <!-- NOTE: These penalty modifications are GT-only and automatically installed by the GalaxyTrader system. -->
    <!-- They represent pilot skill limitations and are not available for purchase, crafting, or manual installation by players. -->
    <!-- Penalty mods do NOT require research - they are always available (unlike bonus mods). -->
    <!-- Separate wares for ship and engine mods (X4 doesn't allow same ware for both types) -->
    
    <!-- Ship Penalty Mods -->
    <ware id="mod_penalty_ship_severe" name="Severe Skill Limitation (Ship)" description="Severe Skill Limitation (Ship) - Represents severe performance penalties due to pilot inexperience with large vessels. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Increases ship mass. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="1" average="1" max="1" />
    </ware>
    <ware id="mod_penalty_ship_moderate" name="Moderate Skill Limitation (Ship)" description="Moderate Skill Limitation (Ship) - Represents moderate performance penalties as pilot adapts to vessel complexity. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Increases ship mass. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="1" average="1" max="1" />
    </ware>
    <ware id="mod_penalty_ship_light" name="Light Skill Limitation (Ship)" description="Light Skill Limitation (Ship) - Represents minor performance penalties during pilot skill development. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Increases ship mass. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="1" average="1" max="1" />
    </ware>
    
    <!-- Engine Penalty Mods -->
    <ware id="mod_penalty_engine_severe" name="Severe Skill Limitation (Engine)" description="Severe Skill Limitation (Engine) - Represents severe performance penalties due to pilot inexperience with large vessels. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Reduces engine thrust and rotation. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="1" average="1" max="1" />
    </ware>
    <ware id="mod_penalty_engine_moderate" name="Moderate Skill Limitation (Engine)" description="Moderate Skill Limitation (Engine) - Represents moderate performance penalties as pilot adapts to vessel complexity. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Reduces engine thrust and rotation. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="1" average="1" max="1" />
    </ware>
    <ware id="mod_penalty_engine_light" name="Light Skill Limitation (Engine)" description="Light Skill Limitation (Engine) - Represents minor performance penalties during pilot skill development. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Reduces engine thrust and rotation. (GT System Only - Not Available for Manual Installation)" transport="inventory" volume="1" tags="equipmentmod noplayerblueprint">
      <price min="1" average="1" max="1" />
    </ware>
  </add>
</diff>
# MIT License

Copyright (c) 2024 GoAhead

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

## Additional Terms for GalaxyTrader MK3

This mod is created for X4: Foundations by Egosoft and requires a legitimate
copy of the game to function. The mod author claims no ownership of X4: Foundations
or any of its assets.

### Attribution
While not required by the license, attribution is appreciated when using substantial
portions of this mod's code in derivative works.

### Compatibility
This mod is designed to be compatible with other X4 mods. Mod authors are encouraged
to maintain compatibility when creating derivative works. <?xml version="1.0" encoding="utf-8"?>
<mdscript name="GLX_Lib_Cache" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Per-home trade cache: total count + cross-home purge (split from gt_libraries_general). AI reads global.$GT_TradeCache directly. -->

    <!-- ========================================= -->
    <!-- CACHE UTILITIES -->
    <!-- ========================================= -->
    
    <!-- Calculate Total Cache Count (MK3 + MK4 pools combined) -->
    <library name="GLX_CalculateTotalCacheCount" purpose="run_actions">
      <params>
      </params>
      <actions>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CalculateCacheCountForPool" result="$mk3Count">
          <param name="cachePool" value="'mk3'"/>
        </run_actions>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CalculateCacheCountForPool" result="$mk4Count">
          <param name="cachePool" value="'mk4'"/>
        </run_actions>
        <return value="$mk3Count + $mk4Count"/>
      </actions>
    </library>

    <!-- Calculate total cache count for a single pool (mk3 or mk4). -->
    <library name="GLX_CalculateCacheCountForPool" purpose="run_actions">
      <params>
        <param name="cachePool" default="'mk3'"/>
      </params>
      <actions>
        <set_value name="$totalCount" exact="0"/>
        <set_value name="$isMk4Pool" exact="$cachePool == 'mk4'"/>
        <set_value name="$cacheTable" exact="null"/>
        <do_if value="$isMk4Pool">
          <set_value name="$cacheTable" exact="@global.$GT_TradeCacheMK4"/>
        </do_if>
        <do_else>
          <set_value name="$cacheTable" exact="@global.$GT_TradeCache"/>
        </do_else>
        <do_if value="$cacheTable?">
          <set_value name="$homes" exact="[]"/>
          <set_value name="$usedRegistry" exact="false"/>
          <do_if value="not $isMk4Pool and global.$GT_TradeCacheHomes? and global.$GT_TradeCacheHomes != null and typeof global.$GT_TradeCacheHomes == datatype.list and global.$GT_TradeCacheHomes.count gt 0">
            <set_value name="$homes" exact="@global.$GT_TradeCacheHomes"/>
            <set_value name="$usedRegistry" exact="true"/>
          </do_if>
          <do_else>
            <set_value name="$homes" exact="@$cacheTable.keys"/>
            <do_if value="$homes == null">
              <set_value name="$homes" exact="[]"/>
            </do_if>
          </do_else>

          <do_if value="not $isMk4Pool and not $usedRegistry and global.$GT_TradeCacheHomes? and (global.$GT_TradeCacheHomes == null or typeof global.$GT_TradeCacheHomes != datatype.list or global.$GT_TradeCacheHomes.count == 0) and $homes.count gt 0">
            <set_value name="global.$GT_TradeCacheHomes" exact="$homes"/>
          </do_if>

          <do_all exact="$homes.count" counter="$sectorIdx">
            <set_value name="$home" exact="$homes.{$sectorIdx}"/>
            <set_value name="$sectorCache" exact="null"/>
            <do_if value="$isMk4Pool">
              <set_value name="$sectorCache" exact="@global.$GT_TradeCacheMK4.{$home}"/>
            </do_if>
            <do_else>
              <set_value name="$sectorCache" exact="@global.$GT_TradeCache.{$home}"/>
            </do_else>
            <do_if value="$sectorCache != null">
              <set_value name="$totalCount" exact="$totalCount + $sectorCache.count"/>
            </do_if>
          </do_all>
        </do_if>
        <return value="$totalCount"/>
      </actions>
    </library>

    <!-- Event-driven TTL cleanup for one cache pool. -->
    <library name="GLX_CachePool_EventCleanup" purpose="run_actions">
      <params>
        <param name="cachePool" default="'mk3'"/>
        <param name="cacheMaxAge" default="300s"/>
      </params>
      <actions>
        <set_value name="$cleanedEntries" exact="0"/>
        <set_value name="$isMk4Pool" exact="$cachePool == 'mk4'"/>
        <set_value name="$cacheExists" exact="false"/>
        <do_if value="$isMk4Pool">
          <set_value name="$cacheExists" exact="global.$GT_TradeCacheMK4?"/>
        </do_if>
        <do_else>
          <set_value name="$cacheExists" exact="global.$GT_TradeCache?"/>
        </do_else>
        <do_if value="$cacheExists">
          <set_value name="$cacheKeys" exact="[]"/>
          <do_if value="$isMk4Pool">
            <set_value name="$cacheKeys" exact="@global.$GT_TradeCacheMK4.keys"/>
          </do_if>
          <do_else>
            <set_value name="$cacheKeys" exact="@global.$GT_TradeCache.keys"/>
          </do_else>
          <set_value name="$cacheKeysCount" exact="@$cacheKeys.count"/>
          <do_if value="$cacheKeysCount == null">
            <set_value name="$cacheKeysCount" exact="0"/>
          </do_if>
          <do_if value="$cacheKeysCount gt 0">
            <do_all exact="$cacheKeysCount" counter="$sectorIdx">
              <set_value name="$homeSector" exact="@$cacheKeys.{$sectorIdx}"/>
              <do_if value="$homeSector != null">
                <set_value name="$sectorCache" exact="[]"/>
                <do_if value="$isMk4Pool">
                  <set_value name="$sectorCache" exact="@global.$GT_TradeCacheMK4.{$homeSector}"/>
                </do_if>
                <do_else>
                  <set_value name="$sectorCache" exact="@global.$GT_TradeCache.{$homeSector}"/>
                </do_else>
                <do_if value="$sectorCache == null">
                  <set_value name="$sectorCache" exact="[]"/>
                </do_if>
                <do_if value="$sectorCache.count gt 0">
                  <set_value name="$cleanSectorCache" exact="[]"/>
                  <do_all exact="$sectorCache.count" counter="$i">
                    <set_value name="$entry" exact="$sectorCache.{$i}"/>
                    <set_value name="$isExpired" exact="false"/>
                    <set_value name="$entryTimestamp" exact="@$entry.$CachedAt"/>
                    <do_if value="$entryTimestamp == null">
                      <set_value name="$entryTimestamp" exact="@$entry.$Timestamp"/>
                    </do_if>
                    <do_if value="$entryTimestamp != null">
                      <do_if value="(player.age - $entryTimestamp) gt $cacheMaxAge">
                        <set_value name="$isExpired" exact="true"/>
                        <set_value name="$cleanedEntries" operation="add"/>
                      </do_if>
                    </do_if>
                    <do_if value="not $isExpired and @$entry.$BuyOffer != null and @$entry.$SellOffer != null">
                      <do_if value="@$entry.$BuyOffer.exists and @$entry.$SellOffer.exists">
                        <append_to_list name="$cleanSectorCache" exact="$entry"/>
                      </do_if>
                      <do_else>
                        <set_value name="$cleanedEntries" operation="add"/>
                      </do_else>
                    </do_if>
                  </do_all>
                  <do_if value="$isMk4Pool">
                    <set_value name="global.$GT_TradeCacheMK4.{$homeSector}" exact="$cleanSectorCache"/>
                    <do_if value="$cleanSectorCache.count == 0">
                      <remove_value name="global.$GT_TradeCacheMK4.{$homeSector}"/>
                      <do_if value="global.$GT_TradeCacheMK4ByWare? and global.$GT_TradeCacheMK4ByWare.{$homeSector}?">
                        <remove_value name="global.$GT_TradeCacheMK4ByWare.{$homeSector}"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="not global.$GT_TradeCacheMK4ByWare?">
                        <set_value name="global.$GT_TradeCacheMK4ByWare" exact="table[]"/>
                      </do_if>
                      <set_value name="global.$GT_TradeCacheMK4ByWare.{$homeSector}" exact="table[]"/>
                      <do_all exact="$cleanSectorCache.count" counter="$i">
                        <set_value name="$entry" exact="$cleanSectorCache.{$i}"/>
                        <set_value name="$entryWare" exact="@$entry.$BuyOffer.ware"/>
                        <do_if value="$entryWare?">
                          <do_if value="not global.$GT_TradeCacheMK4ByWare.{$homeSector}.{$entryWare}?">
                            <set_value name="global.$GT_TradeCacheMK4ByWare.{$homeSector}.{$entryWare}" exact="[]"/>
                          </do_if>
                          <append_to_list name="global.$GT_TradeCacheMK4ByWare.{$homeSector}.{$entryWare}" exact="$entry"/>
                        </do_if>
                      </do_all>
                    </do_else>
                  </do_if>
                  <do_else>
                    <set_value name="global.$GT_TradeCache.{$homeSector}" exact="$cleanSectorCache"/>
                    <do_if value="$cleanSectorCache.count == 0">
                      <remove_value name="global.$GT_TradeCache.{$homeSector}"/>
                      <do_if value="global.$GT_TradeCacheByWare? and global.$GT_TradeCacheByWare.{$homeSector}?">
                        <remove_value name="global.$GT_TradeCacheByWare.{$homeSector}"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <do_if value="not global.$GT_TradeCacheByWare?">
                        <set_value name="global.$GT_TradeCacheByWare" exact="table[]"/>
                      </do_if>
                      <set_value name="global.$GT_TradeCacheByWare.{$homeSector}" exact="table[]"/>
                      <do_all exact="$cleanSectorCache.count" counter="$i">
                        <set_value name="$entry" exact="$cleanSectorCache.{$i}"/>
                        <set_value name="$entryWare" exact="@$entry.$BuyOffer.ware"/>
                        <do_if value="$entryWare?">
                          <do_if value="not global.$GT_TradeCacheByWare.{$homeSector}.{$entryWare}?">
                            <set_value name="global.$GT_TradeCacheByWare.{$homeSector}.{$entryWare}" exact="[]"/>
                          </do_if>
                          <append_to_list name="global.$GT_TradeCacheByWare.{$homeSector}.{$entryWare}" exact="$entry"/>
                        </do_if>
                      </do_all>
                    </do_else>
                  </do_else>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <return value="$cleanedEntries"/>
      </actions>
    </library>
    

    <!-- Accumulate fleet cache statistics for one pool. -->
    <library name="GLX_CachePool_AccumulateFleetStats" purpose="run_actions">
      <params>
        <param name="cachePool" default="'mk3'"/>
      </params>
      <actions>
        <set_value name="$poolStats" exact="table[
          $TotalWares = 0,
          $TotalRoutes = 0,
          $OldestEntry = player.age,
          $NewestEntry = 0,
          $TotalAge = 0
        ]"/>
        <set_value name="$isMk4Pool" exact="$cachePool == 'mk4'"/>
        <set_value name="$cacheExists" exact="false"/>
        <do_if value="$isMk4Pool">
          <set_value name="$cacheExists" exact="global.$GT_TradeCacheMK4?"/>
        </do_if>
        <do_else>
          <set_value name="$cacheExists" exact="global.$GT_TradeCache?"/>
        </do_else>
        <do_if value="$cacheExists">
          <set_value name="$uniqueWares" exact="[]"/>
          <set_value name="$keys" exact="[]"/>
          <do_if value="$isMk4Pool">
            <set_value name="$keys" exact="@global.$GT_TradeCacheMK4.keys"/>
          </do_if>
          <do_else>
            <set_value name="$keys" exact="@global.$GT_TradeCache.keys"/>
          </do_else>
          <set_value name="$keysCount" exact="@$keys.count"/>
          <do_if value="$keysCount? and $keysCount gt 0">
            <do_all exact="$keysCount" counter="$sectorIdx">
              <set_value name="$homeSector" exact="@$keys.{$sectorIdx}"/>
              <do_if value="$homeSector?">
                <set_value name="$sectorCache" exact="null"/>
                <do_if value="$isMk4Pool">
                  <set_value name="$sectorCache" exact="@global.$GT_TradeCacheMK4.{$homeSector}"/>
                </do_if>
                <do_else>
                  <set_value name="$sectorCache" exact="@global.$GT_TradeCache.{$homeSector}"/>
                </do_else>
                <do_if value="$sectorCache?">
                  <set_value name="$sectorCacheCount" exact="@$sectorCache.count"/>
                  <do_if value="$sectorCacheCount? and $sectorCacheCount gt 0">
                    <do_all exact="$sectorCacheCount" counter="$i">
                      <set_value name="$entry" exact="@$sectorCache.{$i}"/>
                      <do_if value="$entry?">
                        <set_value name="$entryTimestamp" exact="@$entry.$Timestamp"/>
                        <do_if value="$entryTimestamp == null">
                          <set_value name="$entryTimestamp" exact="@$entry.$CachedAt"/>
                        </do_if>
                        <do_if value="$entryTimestamp?">
                          <set_value name="$age" exact="player.age - $entryTimestamp"/>
                          <set_value name="$poolStats.$TotalAge" exact="$poolStats.$TotalAge + $age"/>
                          <set_value name="$poolStats.$TotalRoutes" operation="add"/>
                          <do_if value="$entryTimestamp lt $poolStats.$OldestEntry">
                            <set_value name="$poolStats.$OldestEntry" exact="$entryTimestamp"/>
                          </do_if>
                          <do_if value="$entryTimestamp gt $poolStats.$NewestEntry">
                            <set_value name="$poolStats.$NewestEntry" exact="$entryTimestamp"/>
                          </do_if>
                        </do_if>
                        <set_value name="$wareId" exact="@$entry.$WareId"/>
                        <do_if value="$wareId?">
                          <set_value name="$wareExists" exact="false"/>
                          <do_all exact="$uniqueWares.count" counter="$j">
                            <do_if value="$uniqueWares.{$j} == $wareId">
                              <set_value name="$wareExists" exact="true"/>
                              <break/>
                            </do_if>
                          </do_all>
                          <do_if value="not $wareExists">
                            <append_to_list name="$uniqueWares" exact="$wareId"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$poolStats.$TotalWares" exact="$uniqueWares.count"/>
        </do_if>
        <return value="$poolStats"/>
      </actions>
    </library>


    <!-- Purge cache entries by offer-pair across ALL home-sector caches -->
    <!-- Motivation:
         With per-home-sector caching, the same BuyOffer/SellOffer pair can be cached under multiple home sectors.
         If we only remove from the executing ship's home sector, other home caches retain stale entries and ships revalidate "ghost" trades.
         This helper removes matching entries from:
           - global.$GT_TradeCache.{home}
           - global.$GT_TradeCacheByWare.{home}.{wareKey} (best-effort for both ware object key and ware.id string key) -->
    <library name="GLX_PurgeCacheOfferPair_AllHomes" purpose="run_actions">
      <params>
        <param name="cachePool" default="'mk3'" comment="Trade cache pool: mk3 or mk4"/>
        <param name="ship" default="null" comment="Ship for logging context (optional)"/>
        <param name="buyOffer" default="null" comment="Buy offer object (may be null for sell-only)"/>
        <param name="sellOffer" comment="Sell offer object (required)"/>
        <param name="reason" default="'unknown'" comment="Reason for purge (debug)"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <set_value name="$removedTotal" exact="0"/>
        <set_value name="$isMk4Pool" exact="$cachePool == 'mk4'"/>

        <!-- Validate required offer handle -->
        <do_if value="$sellOffer == null">
          <return value="table[$Removed = 0, $Homes = 0, $UsedIndex = false]"/>
        </do_if>

        <!-- PHASE 1: Use index-based lookup (O(1)) - ERROR if index missing -->
        <set_value name="$usedIndex" exact="false"/>
        <set_value name="$homes" exact="[]"/>
        
        <!-- Generate trade key -->
        <!-- CRITICAL: Validate sellOffer has valid ID before generating trade key -->
        <set_value name="$tradeKey" exact="''"/>
        <set_value name="$sellOfferIdValid" exact="false"/>
        
        <!-- Validate sellOffer exists and has valid ID -->
        <do_if value="$sellOffer? and $sellOffer != null and $sellOffer.exists">
          <set_value name="$tempSellId" exact="@$sellOffer.id"/>
          <do_if value="$tempSellId? and $tempSellId != null">
            <set_value name="$sellOfferIdValid" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Only generate trade key if sellOffer has valid ID -->
        <do_if value="$sellOfferIdValid">
          <run_actions ref="md.GLX_Lib_Reservations.GLX_GenerateTradeKey" result="$tradeKey">
            <param name="buyOffer" value="$buyOffer"/>
            <param name="sellOffer" value="$sellOffer"/>
            <param name="traceId" value="$traceId"/>
          </run_actions>
        </do_if>
        
        <!-- Validate trade key was generated -->
        <!-- CRITICAL FIX: This is expected behavior when offers become invalid - log as INFO, not ERROR -->
        <do_if value="$tradeKey == ''">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheInvalidate'"/>
              <param name="action" value="'Info'"/>
              <param name="details" value="'reason=invalid_tradeKey reason=' + $reason + ' note=expected_when_offers_become_invalid'"/>
              <param name="logLevel" value="2"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-INFO] GLX_PurgeCacheOfferPair_AllHomes: Failed to generate trade key - cannot invalidate cache (offer may have been removed, trade executed but cache purge skipped)'" chance="100"/>
          </do_else>
          <return value="table[$Removed = 0, $Homes = 0, $UsedIndex = false]"/>
        </do_if>
        
        <!-- Validate index exists -->
        <do_if value="not global.$GT_TradeIndex?">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheInvalidate'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=index_not_initialized trade=' + $tradeKey + ' reason=' + $reason"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_PurgeCacheOfferPair_AllHomes: Trade index not initialized - tradeKey=' + $tradeKey" chance="100"/>
          </do_else>
          <return value="table[$Removed = 0, $Homes = 0, $UsedIndex = false]"/>
        </do_if>
        
        <!-- Look up homes from index -->
        <run_actions ref="md.GLX_Lib_Reservations.GLX_GetTradeIndexHomes" result="$indexHomes">
          <param name="tradeKey" value="$tradeKey"/>
        </run_actions>
        
        <!-- Validate index lookup returned valid result -->
        <do_if value="not $indexHomes?">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheInvalidate'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=index_lookup_failed trade=' + $tradeKey + ' reason=' + $reason"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_PurgeCacheOfferPair_AllHomes: Index lookup returned null - tradeKey=' + $tradeKey" chance="100"/>
          </do_else>
          <return value="table[$Removed = 0, $Homes = 0, $UsedIndex = false]"/>
        </do_if>
        
        <!-- Use index homes -->
        <set_value name="$homes" exact="$indexHomes"/>
        <set_value name="$usedIndex" exact="true"/>
        
        <!-- Log index-based invalidation -->
        <do_if value="$traceId != ''">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
            <param name="traceId" value="$traceId"/>
            <param name="stage" value="'CacheInvalidate'"/>
            <param name="action" value="'IndexLookup'"/>
            <param name="details" value="'trade=' + $tradeKey + ' homes=' + $homes.count + ' reason=' + $reason"/>
            <param name="logLevel" value="1"/>
          </run_actions>
        </do_if>
        
        <!-- ERROR if index lookup returned empty list but trade should exist -->
        <do_if value="$homes.count == 0">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheInvalidate'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=index_entry_not_found trade=' + $tradeKey + ' reason=' + $reason"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_PurgeCacheOfferPair_AllHomes: Trade not found in index - tradeKey=' + $tradeKey + ' (trade may not be cached or index incomplete)'" chance="100"/>
          </do_else>
          <!-- Continue with empty homes list - will result in 0 removals, which is correct -->
        </do_if>

        <do_all exact="$homes.count" counter="$hi">
          <set_value name="$home" exact="$homes.{$hi}"/>
          <set_value name="$homeHasCache" exact="false"/>
          <do_if value="$isMk4Pool">
            <set_value name="$homeHasCache" exact="$home? and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$home}?"/>
          </do_if>
          <do_else>
            <set_value name="$homeHasCache" exact="$home? and global.$GT_TradeCache? and global.$GT_TradeCache.{$home}?"/>
          </do_else>
          <do_if value="$homeHasCache">
            <set_value name="$sectorCache" exact="[]"/>
            <do_if value="$isMk4Pool">
              <set_value name="$sectorCache" exact="global.$GT_TradeCacheMK4.{$home}"/>
            </do_if>
            <do_else>
              <set_value name="$sectorCache" exact="global.$GT_TradeCache.{$home}"/>
            </do_else>
            <do_all exact="$sectorCache.count" counter="$i" reverse="true">
              <set_value name="$entry" exact="$sectorCache.{$i}"/>
              <do_if value="$entry != null">
                <set_value name="$buyOfferMatches" exact="false"/>
                <set_value name="$sellOfferMatches" exact="false"/>

                <!-- Sell-only match: buyOffer is null => only match sell offer -->
                <do_if value="$buyOffer == null">
                  <set_value name="$buyOfferMatches" exact="true"/>
                  <do_if value="$entry.$SellOffer? and $entry.$SellOffer == $sellOffer">
                    <set_value name="$sellOfferMatches" exact="true"/>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="$entry.$BuyOffer? and $entry.$BuyOffer == $buyOffer">
                    <set_value name="$buyOfferMatches" exact="true"/>
                  </do_if>
                  <do_if value="$entry.$SellOffer? and $entry.$SellOffer == $sellOffer">
                    <set_value name="$sellOfferMatches" exact="true"/>
                  </do_if>
                </do_else>

                <do_if value="$buyOfferMatches and $sellOfferMatches">
                  <!-- Remove from main cache -->
                  <do_if value="$isMk4Pool">
                    <remove_value name="global.$GT_TradeCacheMK4.{$home}.{$i}"/>
                  </do_if>
                  <do_else>
                    <remove_value name="global.$GT_TradeCache.{$home}.{$i}"/>
                  </do_else>
                  <set_value name="$removedTotal" operation="add"/>

                  <!-- Best-effort: remove from per-ware index -->
                  <do_if value="$isMk4Pool">
                    <do_if value="global.$GT_TradeCacheMK4ByWare? and global.$GT_TradeCacheMK4ByWare.{$home}?">
                      <set_value name="$wareObj" exact="null"/>
                      <set_value name="$wareIdKey" exact="null"/>
                      <do_if value="$entry.$BuyOffer?">
                        <set_value name="$wareObj" exact="@$entry.$BuyOffer.ware"/>
                        <do_if value="$wareObj?">
                          <set_value name="$wareIdKey" exact="@$wareObj.id"/>
                        </do_if>
                      </do_if>
                      <do_elseif value="$entry.$WareId?">
                        <set_value name="$wareIdKey" exact="@$entry.$WareId"/>
                      </do_elseif>
                      <do_if value="$wareObj? and global.$GT_TradeCacheMK4ByWare.{$home}.{$wareObj}?">
                        <remove_from_list name="global.$GT_TradeCacheMK4ByWare.{$home}.{$wareObj}" exact="$entry"/>
                      </do_if>
                      <do_if value="$wareIdKey? and global.$GT_TradeCacheMK4ByWare.{$home}.{$wareIdKey}?">
                        <remove_from_list name="global.$GT_TradeCacheMK4ByWare.{$home}.{$wareIdKey}" exact="$entry"/>
                      </do_if>
                    </do_if>
                  </do_if>
                  <do_else>
                    <do_if value="global.$GT_TradeCacheByWare? and global.$GT_TradeCacheByWare.{$home}?">
                    <set_value name="$wareObj" exact="null"/>
                    <set_value name="$wareIdKey" exact="null"/>
                    <do_if value="$entry.$BuyOffer?">
                      <set_value name="$wareObj" exact="@$entry.$BuyOffer.ware"/>
                      <do_if value="$wareObj?">
                        <set_value name="$wareIdKey" exact="@$wareObj.id"/>
                      </do_if>
                    </do_if>
                    <do_elseif value="$entry.$WareId?">
                      <set_value name="$wareIdKey" exact="@$entry.$WareId"/>
                    </do_elseif>

                    <!-- Remove by ware object key -->
                    <do_if value="$wareObj? and global.$GT_TradeCacheByWare.{$home}.{$wareObj}?">
                      <remove_from_list name="global.$GT_TradeCacheByWare.{$home}.{$wareObj}" exact="$entry"/>
                    </do_if>
                    <!-- Remove by ware id key (legacy / mixed saves) -->
                    <do_if value="$wareIdKey? and global.$GT_TradeCacheByWare.{$home}.{$wareIdKey}?">
                      <remove_from_list name="global.$GT_TradeCacheByWare.{$home}.{$wareIdKey}" exact="$entry"/>
                    </do_if>
                  </do_if>
                  </do_else>
                </do_if>
              </do_if>
            </do_all>

            <!-- Clean up empty home cache lists -->
            <do_if value="$isMk4Pool">
              <do_if value="global.$GT_TradeCacheMK4.{$home}? and global.$GT_TradeCacheMK4.{$home}.count == 0">
                <remove_value name="global.$GT_TradeCacheMK4.{$home}"/>
                <do_if value="global.$GT_TradeCacheMK4ByWare? and global.$GT_TradeCacheMK4ByWare.{$home}?">
                  <remove_value name="global.$GT_TradeCacheMK4ByWare.{$home}"/>
                </do_if>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="global.$GT_TradeCache.{$home}? and global.$GT_TradeCache.{$home}.count == 0">
                <remove_value name="global.$GT_TradeCache.{$home}"/>
                <do_if value="global.$GT_TradeCacheByWare? and global.$GT_TradeCacheByWare.{$home}?">
                  <remove_value name="global.$GT_TradeCacheByWare.{$home}"/>
                </do_if>
              </do_if>
            </do_else>
          </do_if>
        </do_all>

        <!-- PHASE 1: Remove from index after invalidation -->
        <do_if value="$tradeKey != '' and $removedTotal gt 0">
          <run_actions ref="md.GLX_Lib_Reservations.GLX_RemoveTradeFromIndex">
            <param name="tradeKey" value="$tradeKey"/>
            <param name="homeSector" value="null"/>
            <param name="traceId" value="$traceId"/>
          </run_actions>
        </do_if>
        
        <!-- Log invalidation completion -->
        <do_if value="$traceId != ''">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
            <param name="traceId" value="$traceId"/>
            <param name="stage" value="'CacheInvalidate'"/>
            <param name="action" value="'Complete'"/>
            <param name="details" value="'trade=' + (if $tradeKey != '' then $tradeKey else 'unknown') + ' removed=' + $removedTotal + ' homes=' + $homes.count + ' usedIndex=' + (if $usedIndex then 'true' else 'false') + ' reason=' + $reason"/>
            <param name="logLevel" value="1"/>
          </run_actions>
        </do_if>
        
        <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$shipId" exact="if $ship != null then $ship.idcode else 'N/A'"/>
          <debug_text text="'[GT-Cache] Purged offer-pair across homes: removed=' + $removedTotal + ', homes=' + $homes.count + ', ship=' + $shipId + ', reason=' + $reason + ', usedIndex=' + $usedIndex" chance="100"/>
        </do_if>

        <return value="table[$Removed = $removedTotal, $Homes = $homes.count, $UsedIndex = $usedIndex]"/>
      </actions>
    </library>


  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GLX_Lib_Orders" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Centralized checks against global.$GT_ProtectedOrderIDs (see gt_core_system.xml). -->
    <!-- Use md.GLX_Lib_Orders.GLX_ShipIsInGTService from run_actions, or inline indexof in hot do_if conditions. -->

    <!-- True if ship's default order is a protected GT id, OR Assist under a GT commander. -->
    <library name="GLX_ShipIsInGTService" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to test"/>
      </params>
      <actions>
        <do_if value="$ship? and $ship.exists and global.$GT_ProtectedOrderIDs? and $ship.defaultorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}">
          <return value="true"/>
        </do_if>
        <do_if value="$ship? and $ship.exists and $ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.exists and $ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id}">
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GLX_Lib_Reservations" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Trade key, index, failure reasons, reservations, orphaned credits cleanup (split from gt_libraries_general). -->

    <!-- Generate Trade Key (Option A: BuyOffer.id + SellOffer.id) -->
    <!-- Simple approach: uses offer IDs which are unique per offer instance -->
    <!-- Trade key format: "buyOfferId_sellOfferId" or "null_sellOfferId" for sell-only -->
    <library name="GLX_GenerateTradeKey" purpose="run_actions">
      <params>
        <param name="buyOffer" default="null" comment="Buy offer object (may be null for sell-only trades)"/>
        <param name="sellOffer" comment="Sell offer object (required)"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <set_value name="$tradeKey" exact="''"/>
        
        <!-- Validate sell offer - ERROR if missing -->
        <do_if value="not $sellOffer? or not $sellOffer.exists">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=missing_sellOffer'"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_GenerateTradeKey: sellOffer is null or missing - cannot generate trade key'" chance="100"/>
          </do_else>
          <return value="''"/>
        </do_if>
        
        <!-- Get offer IDs -->
        <set_value name="$buyOfferId" exact="'null'"/>
        <set_value name="$sellOfferId" exact="''"/>
        
        <do_if value="$buyOffer? and $buyOffer.exists">
          <set_value name="$tempBuyId" exact="@$buyOffer.id"/>
          <do_if value="$tempBuyId? and $tempBuyId != null">
            <set_value name="$buyOfferId" exact="'' + $tempBuyId"/>
          </do_if>
        </do_if>
        
        <!-- Validate sellOffer has valid ID before generating key -->
        <!-- CRITICAL: Check if sellOffer.id exists and is not null before converting to string -->
        <set_value name="$tempSellId" exact="@$sellOffer.id"/>
        <do_if value="$tempSellId? and $tempSellId != null and typeof $tempSellId != datatype.null">
          <!-- Valid ID - convert to string -->
          <set_value name="$sellOfferId" exact="'' + $tempSellId"/>
          <!-- Double-check: ensure sellOfferId is not empty or 'null' string -->
          <do_if value="$sellOfferId == '' or $sellOfferId == 'null'">
            <!-- ID conversion failed - log error and return empty key -->
            <do_if value="$traceId != ''">
              <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
                <param name="traceId" value="$traceId"/>
                <param name="stage" value="'CacheIndex'"/>
                <param name="action" value="'Error'"/>
                <param name="details" value="'reason=invalid_sellOffer_id_conversion tempSellId=' + (if $tempSellId? then $tempSellId else 'null') + ' sellOfferId=' + $sellOfferId"/>
                <param name="logLevel" value="0"/>
              </run_actions>
            </do_if>
            <do_else>
              <debug_text text="'[GT-ERROR] GLX_GenerateTradeKey: sellOffer.id conversion failed - tempSellId=' + (if $tempSellId? then $tempSellId else 'null') + ', sellOfferId=' + $sellOfferId" chance="100"/>
            </do_else>
            <return value="''"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Fallback (Method B): offer.id is not available in many X4 trade-offer objects.
               Use the SELL offer object itself as the reservation key.
               This restores reservation behavior under fleet load and prevents mass cache collisions. -->
          <set_value name="$tradeKey" exact="$sellOffer"/>
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'KeyGenerated'"/>
              <param name="details" value="'trade=SellOfferObj method=B buyOffer=' + (if $buyOffer? then 'valid' else 'null') + ' sellOffer=valid'"/>
              <param name="logLevel" value="2"/>
            </run_actions>
          </do_if>
          <return value="$tradeKey"/>
        </do_else>
        
        <!-- Generate key: "buyOfferId_sellOfferId" -->
        <!-- CRITICAL: Validate sellOfferId is not empty before generating key -->
        <do_if value="$sellOfferId == ''">
          <!-- sellOfferId is empty - this should have been caught earlier, but double-check -->
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=empty_sellOfferId buyOfferId=' + $buyOfferId"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_GenerateTradeKey: sellOfferId is empty - cannot generate trade key'" chance="100"/>
          </do_else>
          <return value="''"/>
        </do_if>
        
        <set_value name="$tradeKey" exact="$buyOfferId + '_' + $sellOfferId"/>
        
        <!-- Validate generated key is not null_null (indicates invalid offer IDs) -->
        <do_if value="$tradeKey == 'null_null'">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=invalid_offer_ids buyOfferId=' + $buyOfferId + ' sellOfferId=' + $sellOfferId"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_GenerateTradeKey: Generated invalid trade key null_null - buyOfferId=' + $buyOfferId + ', sellOfferId=' + $sellOfferId" chance="100"/>
          </do_else>
          <return value="''"/>
        </do_if>
        
        <!-- Log key generation -->
        <do_if value="$traceId != ''">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
            <param name="traceId" value="$traceId"/>
            <param name="stage" value="'CacheIndex'"/>
            <param name="action" value="'KeyGenerated'"/>
            <param name="details" value="'trade=' + $tradeKey + ' method=A buyOffer=' + (if $buyOffer? then 'valid' else 'null') + ' sellOffer=valid'"/>
            <param name="logLevel" value="3"/>
          </run_actions>
        </do_if>
        
        <return value="$tradeKey"/>
      </actions>
    </library>
    
    <!-- Initialize Trade Index Structure -->
    <library name="GLX_InitializeTradeIndex" purpose="run_actions">
      <actions>
        <do_if value="not global.$GT_TradeIndex?">
          <set_value name="global.$GT_TradeIndex" exact="table[]"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Add Trade to Index -->
    <!-- Called when writing to cache: adds home sector to index entry -->
    <library name="GLX_AddTradeToIndex" purpose="run_actions">
      <params>
        <param name="tradeKey" comment="Trade key (from GLX_GenerateTradeKey)"/>
        <param name="homeSector" comment="Home sector where this trade is cached"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- Initialize index if needed -->
        <run_actions ref="md.GLX_Lib_Reservations.GLX_InitializeTradeIndex"/>
        
        <!-- Validate inputs - ERROR if missing or invalid (null_null indicates invalid offers) -->
        <do_if value="$tradeKey == '' or $tradeKey == 'null_null'">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=' + (if $tradeKey == 'null_null' then 'invalid_tradeKey_null_null' else 'empty_tradeKey')"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_AddTradeToIndex: tradeKey is empty or invalid (' + $tradeKey + ') - cannot add to index'" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        <do_if value="not $homeSector? or not $homeSector.exists">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=invalid_homeSector tradeKey=' + $tradeKey"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_AddTradeToIndex: homeSector is null or invalid - tradeKey=' + $tradeKey" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <!-- Get or create index entry -->
        <set_value name="$indexEntry" exact="null"/>
        <do_if value="global.$GT_TradeIndex.{$tradeKey}?">
          <set_value name="$indexEntry" exact="global.$GT_TradeIndex.{$tradeKey}"/>
        </do_if>
        <do_else>
          <set_value name="$indexEntry" exact="table[
            $Homes = [],
            $ReservedBy = null,
            $ReservedUntil = null
          ]"/>
          <set_value name="global.$GT_TradeIndex.{$tradeKey}" exact="$indexEntry"/>
        </do_else>
        
        <!-- Add home sector to list if not already present -->
        <set_value name="$homeExists" exact="false"/>
        <do_if value="$indexEntry.$Homes?">
          <do_all exact="$indexEntry.$Homes.count" counter="$i">
            <do_if value="$indexEntry.$Homes.{$i} == $homeSector">
              <set_value name="$homeExists" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="not $homeExists">
          <append_to_list name="global.$GT_TradeIndex.{$tradeKey}.$Homes" exact="$homeSector"/>
          
          <!-- Log index update -->
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Added'"/>
              <param name="details" value="'trade=' + $tradeKey + ' home=' + (if $homeSector? then @$homeSector.knownname else 'null') + ' homes=' + global.$GT_TradeIndex.{$tradeKey}.$Homes.count"/>
              <param name="logLevel" value="2"/>
            </run_actions>
          </do_if>
        </do_if>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Remove Trade from Index -->
    <!-- Called when invalidating: removes home sector from index entry, removes entry if empty -->
    <library name="GLX_RemoveTradeFromIndex" purpose="run_actions">
      <params>
        <param name="tradeKey" comment="Trade key (from GLX_GenerateTradeKey)"/>
        <param name="homeSector" comment="Home sector to remove (null to remove all)"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- Validate index exists - ERROR if missing -->
        <do_if value="not global.$GT_TradeIndex?">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=index_not_initialized trade=' + $tradeKey"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_RemoveTradeFromIndex: Trade index not initialized - tradeKey=' + $tradeKey" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <!-- Validate trade key entry exists -->
        <do_if value="not global.$GT_TradeIndex.{$tradeKey}?">
          <!-- This is expected if trade was never cached - log but don't error -->
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Warning'"/>
              <param name="details" value="'reason=entry_not_found trade=' + $tradeKey"/>
              <param name="logLevel" value="2"/>
            </run_actions>
          </do_if>
          <return value="false"/>
        </do_if>
        
        <set_value name="$indexEntry" exact="global.$GT_TradeIndex.{$tradeKey}"/>
        
        <!-- Remove specific home sector or all -->
        <do_if value="$homeSector? and $homeSector.exists">
          <!-- Remove specific home sector -->
          <do_if value="$indexEntry.$Homes?">
            <remove_from_list name="global.$GT_TradeIndex.{$tradeKey}.$Homes" exact="$homeSector"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Remove all home sectors (trade fully consumed) -->
          <set_value name="global.$GT_TradeIndex.{$tradeKey}.$Homes" exact="[]"/>
        </do_else>
        
        <!-- Remove index entry if no homes remain -->
        <do_if value="not global.$GT_TradeIndex.{$tradeKey}.$Homes? or global.$GT_TradeIndex.{$tradeKey}.$Homes.count == 0">
          <remove_value name="global.$GT_TradeIndex.{$tradeKey}"/>
          
          <!-- Log index removal -->
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Removed'"/>
              <param name="details" value="'trade=' + $tradeKey + ' reason=no_homes'"/>
              <param name="logLevel" value="2"/>
            </run_actions>
          </do_if>
        </do_if>
        <do_else>
          <!-- Log partial removal -->
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'CacheIndex'"/>
              <param name="action" value="'Updated'"/>
              <param name="details" value="'trade=' + $tradeKey + ' homes=' + global.$GT_TradeIndex.{$tradeKey}.$Homes.count"/>
              <param name="logLevel" value="3"/>
            </run_actions>
          </do_if>
        </do_else>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Get Home Sectors for Trade Key -->
    <!-- Returns list of home sectors where this trade is cached -->
    <!-- ERROR if index not initialized or entry missing -->
    <library name="GLX_GetTradeIndexHomes" purpose="run_actions">
      <params>
        <param name="tradeKey" comment="Trade key (from GLX_GenerateTradeKey)"/>
      </params>
      <actions>
        <set_value name="$homes" exact="[]"/>
        
        <!-- Validate index exists -->
        <do_if value="not global.$GT_TradeIndex?">
          <debug_text text="'[GT-ERROR] GLX_GetTradeIndexHomes: Trade index not initialized - tradeKey=' + $tradeKey" chance="100"/>
          <return value="$homes"/>
        </do_if>
        
        <!-- Validate trade key entry exists -->
        <do_if value="not global.$GT_TradeIndex.{$tradeKey}?">
          <!-- This is expected if trade was never cached - return empty list -->
          <return value="$homes"/>
        </do_if>
        
        <!-- Validate Homes list exists -->
        <do_if value="not global.$GT_TradeIndex.{$tradeKey}.$Homes?">
          <debug_text text="'[GT-ERROR] GLX_GetTradeIndexHomes: Index entry missing $Homes property - tradeKey=' + $tradeKey" chance="100"/>
          <return value="$homes"/>
        </do_if>
        
        <set_value name="$homes" exact="global.$GT_TradeIndex.{$tradeKey}.$Homes"/>
        
        <return value="$homes"/>
      </actions>
    </library>
    
    <!-- Failure Reason Constants -->
    <!-- Standardized failure reasons for trade search pipeline -->
    <library name="GLX_GetFailureReason" purpose="run_actions">
      <params>
        <param name="reason" comment="Failure reason code"/>
      </params>
      <actions>
        <!-- Initialize failure reason constants if not exists -->
        <do_if value="not global.$GT_FailureReasons?">
          <set_value name="global.$GT_FailureReasons" exact="table[
            $NoSectors = 'no_sectors',
            $NoOffers = 'no_offers',
            $NoProfitableMatches = 'no_profitable_matches',
            $DockingBlocked = 'docking_blocked',
            $IllegalBlocked = 'illegal_blocked',
            $BlacklistBlocked = 'blacklist_blocked',
            $PathBlocked = 'path_blocked',
            $ReservedConflict = 'reserved_conflict',
            $CacheMiss = 'cache_miss',
            $CacheEmpty = 'cache_empty',
            $CacheNoValidTrades = 'cache_no_valid_trades',
            $ShipDestroyed = 'ship_destroyed',
            $NoGTOrder = 'no_gt_order',
            $ShipBusy = 'ship_busy',
            $InvalidParams = 'invalid_params',
            $StaleState = 'stale_state',
            $BatchStall = 'batch_stall',
            $Timeout = 'timeout',
            $StateCorruption = 'state_corruption',
            $Unknown = 'unknown'
          ]"/>
        </do_if>
        
        <!-- Return failure reason string -->
        <set_value name="$reasonStr" exact="'unknown'"/>
        <do_if value="global.$GT_FailureReasons.{$reason}?">
          <set_value name="$reasonStr" exact="global.$GT_FailureReasons.{$reason}"/>
        </do_if>
        <return value="$reasonStr"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- RESERVATION SYSTEM (Phase 3) -->
    <!-- Trade-search logging: see glx_lib_trading_log.xml (GLX_Lib_TradingLog) -->
    <!-- ========================================= -->
    
    <!-- Reserve Trade -->
    <!-- Creates a reservation for a trade key, preventing other ships from selecting it -->
    <library name="GLX_ReserveTrade" purpose="run_actions">
      <params>
        <param name="tradeKey" comment="Trade key (from GLX_GenerateTradeKey)"/>
        <param name="ship" comment="Ship reserving the trade"/>
        <param name="ttl" default="10s" comment="Time-to-live for reservation (default: 10 seconds)"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- Validate inputs - ERROR if missing -->
        <do_if value="$tradeKey == ''">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Reservation'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=empty_tradeKey'"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_ReserveTrade: tradeKey is empty - cannot reserve'" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <do_if value="not $ship? or not $ship.exists">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Reservation'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=invalid_ship tradeKey=' + $tradeKey"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_ReserveTrade: ship is null or invalid - tradeKey=' + $tradeKey" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <!-- Initialize reservations if needed -->
        <do_if value="not global.$GT_Reservations?">
          <set_value name="global.$GT_Reservations" exact="table[]"/>
        </do_if>
        
        <!-- Check if already reserved -->
        <set_value name="$alreadyReserved" exact="false"/>
        <set_value name="$existingReservation" exact="null"/>
        <do_if value="global.$GT_Reservations.{$tradeKey}?">
          <set_value name="$existingReservation" exact="global.$GT_Reservations.{$tradeKey}"/>
          <set_value name="$reservedUntil" exact="@$existingReservation.$Until"/>
          <do_if value="$reservedUntil? and player.age lt $reservedUntil">
            <set_value name="$alreadyReserved" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- If already reserved by another ship, log conflict -->
        <do_if value="$alreadyReserved">
          <set_value name="$reservedBy" exact="@$existingReservation.$Ship"/>
          <do_if value="$reservedBy? and $reservedBy != $ship">
            <do_if value="not global.$GT_ReservationStats?">
              <set_value name="global.$GT_ReservationStats" exact="table[$Active = 0, $Expired = 0, $Conflicts = 0, $Created = 0, $Cleared = 0]"/>
            </do_if>
            <set_value name="global.$GT_ReservationStats.$Conflicts" operation="add"/>
            
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Reservation'"/>
              <param name="action" value="'Conflict'"/>
              <param name="details" value="'trade=' + $tradeKey + ' ship=' + $ship.idcode + ' reservedBy=' + $reservedBy.idcode + ' until=' + ($reservedUntil / 1s) + 's'"/>
              <param name="logLevel" value="1"/>
            </run_actions>
            <return value="false"/>
          </do_if>
        </do_if>
        
        <!-- Create or update reservation -->
        <set_value name="$reservationUntil" exact="player.age + $ttl"/>
        <set_value name="global.$GT_Reservations.{$tradeKey}" exact="table[
          $Ship = $ship,
          $Until = $reservationUntil
        ]"/>
        
        <!-- Update statistics -->
        <do_if value="not global.$GT_ReservationStats?">
          <set_value name="global.$GT_ReservationStats" exact="table[$Active = 0, $Expired = 0, $Conflicts = 0, $Created = 0, $Cleared = 0]"/>
        </do_if>
        <set_value name="global.$GT_ReservationStats.$Created" operation="add"/>
        <set_value name="global.$GT_ReservationStats.$Active" operation="add"/>
        
        <!-- Update trade index reservation fields (if index entry exists) -->
        <do_if value="global.$GT_TradeIndex? and global.$GT_TradeIndex.{$tradeKey}?">
          <set_value name="global.$GT_TradeIndex.{$tradeKey}.$ReservedBy" exact="$ship"/>
          <set_value name="global.$GT_TradeIndex.{$tradeKey}.$ReservedUntil" exact="$reservationUntil"/>
        </do_if>
        
        <!-- Log reservation creation -->
        <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
          <param name="traceId" value="$traceId"/>
          <param name="stage" value="'Reservation'"/>
          <param name="action" value="'Create'"/>
          <param name="details" value="'trade=' + $tradeKey + ' ship=' + $ship.idcode + ' ttl=' + ($ttl / 1s) + 's'"/>
          <param name="logLevel" value="1"/>
        </run_actions>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Release Trade Reservation -->
    <!-- Removes a reservation for a trade key -->
    <library name="GLX_ReleaseTrade" purpose="run_actions">
      <params>
        <param name="tradeKey" comment="Trade key (from GLX_GenerateTradeKey)"/>
        <param name="reason" default="'consumed'" comment="Reason for release (consumed, invalidated, expired, etc.)"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- Validate trade key - ERROR if empty -->
        <do_if value="$tradeKey == ''">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Reservation'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=empty_tradeKey'"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GLX_ReleaseTrade: tradeKey is empty - cannot release'" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <!-- Check if reservation exists -->
        <do_if value="not global.$GT_Reservations? or not global.$GT_Reservations.{$tradeKey}?">
          <!-- No reservation exists - this is OK, just log and return -->
          <return value="true"/>
        </do_if>
        
        <!-- Remove reservation -->
        <remove_value name="global.$GT_Reservations.{$tradeKey}"/>
        
        <!-- Update statistics -->
        <do_if value="global.$GT_ReservationStats?">
          <set_value name="global.$GT_ReservationStats.$Cleared" operation="add"/>
          <do_if value="global.$GT_ReservationStats.$Active gt 0">
            <set_value name="global.$GT_ReservationStats.$Active" operation="subtract"/>
          </do_if>
        </do_if>
        
        <!-- Clear trade index reservation fields -->
        <do_if value="global.$GT_TradeIndex? and global.$GT_TradeIndex.{$tradeKey}?">
          <set_value name="global.$GT_TradeIndex.{$tradeKey}.$ReservedBy" exact="null"/>
          <set_value name="global.$GT_TradeIndex.{$tradeKey}.$ReservedUntil" exact="null"/>
        </do_if>
        
        <!-- Log reservation release -->
        <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
          <param name="traceId" value="$traceId"/>
          <param name="stage" value="'Reservation'"/>
          <param name="action" value="'Clear'"/>
          <param name="details" value="'trade=' + $tradeKey + ' reason=' + $reason"/>
          <param name="logLevel" value="1"/>
        </run_actions>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Check if Trade is Reserved -->
    <!-- Returns true if trade is reserved by another ship, false otherwise -->
    <library name="GLX_IsTradeReserved" purpose="run_actions">
      <params>
        <param name="tradeKey" comment="Trade key (from GLX_GenerateTradeKey)"/>
        <param name="ship" default="null" comment="Ship checking reservation (if null, checks if reserved by any ship)"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- Validate trade key - ERROR if empty -->
        <do_if value="$tradeKey == ''">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Reservation'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=empty_tradeKey'"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <return value="false"/>
        </do_if>
        
        <!-- Check if reservation exists -->
        <set_value name="$isReserved" exact="false"/>
        <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$tradeKey}?">
          <set_value name="$reservation" exact="global.$GT_Reservations.{$tradeKey}"/>
          <set_value name="$reservedUntil" exact="@$reservation.$Until"/>
          <set_value name="$reservedBy" exact="@$reservation.$Ship"/>
          
          <!-- Check if reservation is still valid (not expired) -->
          <do_if value="$reservedUntil? and player.age lt $reservedUntil">
            <!-- Check if reserved by different ship -->
            <do_if value="$ship == null or ($reservedBy? and $reservedBy != $ship)">
              <set_value name="$isReserved" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Log reservation check -->
        <do_if value="$traceId != ''">
          <set_value name="$logDetails" exact="'trade=' + $tradeKey + ' reserved=' + $isReserved"/>
          <do_if value="$isReserved and $reservedBy?">
            <set_value name="$logDetails" exact="$logDetails + ' reservedBy=' + $reservedBy.idcode"/>
          </do_if>
          <do_if value="$ship?">
            <set_value name="$logDetails" exact="$logDetails + ' ship=' + $ship.idcode"/>
          </do_if>
          
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
            <param name="traceId" value="$traceId"/>
            <param name="stage" value="'Reservation'"/>
            <param name="action" value="'Check'"/>
            <param name="details" value="$logDetails"/>
            <param name="logLevel" value="3"/>
          </run_actions>
        </do_if>
        
        <return value="$isReserved"/>
      </actions>
    </library>
    
    <!-- Cleanup Expired Reservations -->
    <!-- Called periodically to remove expired reservations and clean up invalid ones -->
    <library name="GLX_CleanupExpiredReservations" purpose="run_actions">
      <params>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- Ensure reservations table exists and is a table (savegame compatibility / corruption guard) -->
        <do_if value="not global.$GT_Reservations? or typeof global.$GT_Reservations != datatype.table">
          <set_value name="global.$GT_Reservations" exact="table[]"/>
          <return value="table[$Expired = 0, $Cleared = 0]"/>
        </do_if>
        
        <set_value name="$expiredCount" exact="0"/>
        <set_value name="$clearedCount" exact="0"/>
        <set_value name="$keysToRemove" exact="[]"/>
        
        <!-- Check all reservations -->
        <set_value name="$reservationKeysCount" exact="@global.$GT_Reservations.keys.count"/>
        <do_if value="$reservationKeysCount != null and $reservationKeysCount gt 0">
          <do_all exact="$reservationKeysCount" counter="$i">
            <set_value name="$tradeKey" exact="global.$GT_Reservations.keys.{$i}"/>
            <set_value name="$reservation" exact="global.$GT_Reservations.{$tradeKey}"/>
            <set_value name="$shouldRemove" exact="false"/>
            <set_value name="$removeReason" exact="'unknown'"/>
            
            <!-- Check expiration -->
            <set_value name="$reservedUntil" exact="@$reservation.$Until"/>
            <do_if value="not $reservedUntil? or player.age ge $reservedUntil">
              <set_value name="$shouldRemove" exact="true"/>
              <set_value name="$removeReason" exact="'ttl_expired'"/>
            </do_if>
            
            <!-- Check if ship still exists -->
            <set_value name="$reservedShip" exact="@$reservation.$Ship"/>
            <do_if value="not $reservedShip? or not $reservedShip.exists">
              <set_value name="$shouldRemove" exact="true"/>
              <set_value name="$removeReason" exact="'ship_destroyed'"/>
            </do_if>
            
            <!-- Check if ship still has GT order (default order id or Assist under GT commander; matches all MK1/MK2/MK3/Miner) -->
            <do_if value="$reservedShip? and $reservedShip.exists">
              <run_actions ref="md.GLX_Lib_Orders.GLX_ShipIsInGTService" result="$hasGTOrder">
                <param name="ship" value="$reservedShip"/>
              </run_actions>
              <do_if value="not $hasGTOrder">
                <set_value name="$shouldRemove" exact="true"/>
                <set_value name="$removeReason" exact="'no_gt_order'"/>
              </do_if>
            </do_if>
            
            <!-- Remove if needed -->
            <do_if value="$shouldRemove">
              <append_to_list name="$keysToRemove" exact="$tradeKey"/>
              <set_value name="$expiredCount" operation="add"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Remove expired reservations -->
        <do_all exact="$keysToRemove.count" counter="$j">
          <set_value name="$tradeKey" exact="$keysToRemove.{$j}"/>
          <run_actions ref="md.GLX_Lib_Reservations.GLX_ReleaseTrade">
            <param name="tradeKey" value="$tradeKey"/>
            <param name="reason" value="if $removeReason == 'ttl_expired' then 'expired' else $removeReason"/>
            <param name="traceId" value="$traceId"/>
          </run_actions>
          <set_value name="$clearedCount" operation="add"/>
          
          <!-- Update statistics -->
          <do_if value="global.$GT_ReservationStats?">
            <set_value name="global.$GT_ReservationStats.$Expired" operation="add"/>
          </do_if>
        </do_all>
        
        <!-- Log cleanup results -->
        <do_if value="$expiredCount gt 0 and $traceId != ''">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
            <param name="traceId" value="$traceId"/>
            <param name="stage" value="'Reservation'"/>
            <param name="action" value="'Expire'"/>
            <param name="details" value="'count=' + $expiredCount + ' cleared=' + $clearedCount"/>
            <param name="logLevel" value="2"/>
          </run_actions>
        </do_if>
        
        <return value="table[$Expired = $expiredCount, $Cleared = $clearedCount]"/>
      </actions>
    </library>
    
    <!-- Cleanup Orphaned Credits Due and Reservations -->
    <!-- Safety net: clears credits due and reservations for ships no longer in GT_Ships registry.
         Addresses edge cases where cleanup was not done correctly (save/load, commander revoke, etc.). -->
    <library name="GLX_CleanupOrphanedCreditsDueAndReservations" purpose="run_actions">
      <params>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <set_value name="$cleanedCount" exact="0"/>
        <set_value name="$candidateShips" exact="table[]"/>
        
        <!-- Collect ships from UICreditsDueByShip -->
        <do_if value="global.$GT_UICreditsDueByShip? and typeof global.$GT_UICreditsDueByShip == datatype.table and global.$GT_UICreditsDueByShip.keys.count gt 0">
          <do_all exact="global.$GT_UICreditsDueByShip.keys.count" counter="$i">
            <set_value name="$ship" exact="global.$GT_UICreditsDueByShip.keys.{$i}"/>
            <set_value name="$candidateShips.{$ship}" exact="true"/>
          </do_all>
        </do_if>
        
        <!-- Collect ships from Reservations -->
        <do_if value="global.$GT_Reservations? and typeof global.$GT_Reservations == datatype.table and global.$GT_Reservations.keys.count gt 0">
          <do_all exact="global.$GT_Reservations.keys.count" counter="$j">
            <set_value name="$tradeKey" exact="global.$GT_Reservations.keys.{$j}"/>
            <set_value name="$reservation" exact="global.$GT_Reservations.{$tradeKey}"/>
            <do_if value="$reservation? and $reservation.$Ship?">
              <set_value name="$resShip" exact="$reservation.$Ship"/>
              <set_value name="$candidateShips.{$resShip}" exact="true"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- For each candidate: if orphan (not in GT_Ships or destroyed), run cleanup -->
        <do_if value="$candidateShips.keys.count gt 0">
          <set_value name="$shipList" exact="$candidateShips.keys.list"/>
          <do_all exact="$shipList.count" counter="$k">
            <set_value name="$ship" exact="$shipList.{$k}"/>
            <set_value name="$isOrphan" exact="false"/>
            <do_if value="not $ship?">
              <set_value name="$isOrphan" exact="true"/>
            </do_if>
            <do_elseif value="not $ship.exists">
              <set_value name="$isOrphan" exact="true"/>
            </do_elseif>
            <do_elseif value="not global.$GT_Ships?">
              <set_value name="$isOrphan" exact="true"/>
            </do_elseif>
            <do_elseif value="not global.$GT_Ships.{$ship}?">
              <set_value name="$isOrphan" exact="true"/>
            </do_elseif>
            <do_if value="$isOrphan and $ship?">
              <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
                <param name="ship" value="$ship"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
                <param name="ship" value="$ship"/>
              </run_actions>
              <set_value name="$cleanedCount" operation="add"/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$cleanedCount gt 0 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-OrphanCleanup] Removed stale credits/reservations for ' + $cleanedCount + ' orphan ship(s)'" chance="100"/>
          </do_if>
        </do_if>
        
        <return value="table[$Cleaned = $cleanedCount]"/>
      </actions>
    </library>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GLX_Lib_Settings_Menu" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>

    <!-- Simple Menu API Integration -->
    <!-- Follow Simple_Menu_API documentation pattern: instantiate="true", ONLY listen to Reloaded -->
    <!-- Renamed from RegisterOptionsMenu to GT_MenuRegistration to avoid "Cannot change parent cue" with existing saves -->
    <cue name="GT_MenuRegistration" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Simple_Menu_API.Reloaded"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] GT_MenuRegistration cue fired!'" chance="100"/>
        </do_if>
        
        <!-- Ensure all settings are initialized before registering menu -->
        <do_if value="not global.$GT_GlobalSettings?">
          <set_value name="global.$GT_GlobalSettings" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment?">
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold" exact="50"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold" exact="70"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile" exact="2"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockCountermeasures" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Initialized missing DefensiveEquipment settings'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$Cheats?">
          <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="'off'"/>
          <set_value name="global.$GT_GlobalSettings.$Cheats.$UniverseRevealed" exact="false"/>
          <set_value name="global.$GT_GlobalSettings.$Cheats.$PilotsMaxed" exact="false"/>
        </do_if>
        
        <!-- Pre-load title text -->
        <set_value name="$menuTitle" exact="{77000,9000}"/>
        
        <!-- Register GalaxyTrader options menu -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Register_Options_Menu" param="table[
          $id = 'gt_global_settings_menu',
          $columns = 8,
          $title = $menuTitle, 
          $onOpen = GT_SettingsMenu,
          $defaultFocus = false
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader] Global settings menu registered with Simple Menu API'" chance="100"/>
        </do_if>
      </actions>
    </cue>
        
    <!-- Global Settings Menu Builder -->
    <cue name="GT_SettingsMenu" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Define color variables for UI -->
            <set_value name="$TextGreen" exact="'Color.text_success'"/>
            <set_value name="$TextRed" exact="'Color.text_failure'"/>
            <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
            
            <!-- XP and Training Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9010},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9516},
              $mouseOverText = {77000,9616}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if $useVanillaXPOnly then {1001,4825} else {1001,8942},
                $color = if $useVanillaXPOnly then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$XP', '$UseVanillaXPOnly', $useVanillaXPOnly]
            ]"/>
            
            <do_if value="not $useVanillaXPOnly">
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
                      $text = {77000,9012},
        $mouseOverText = {77000,9112}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$XP.$AutoTraining then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$XP.$AutoTraining then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$XP', '$AutoTraining', global.$GT_GlobalSettings.$XP.$AutoTraining]
            ]"/>
            
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
                      $text = {77000,9013},
        $mouseOverText = {77000,9113}
            ]"/>
            <!-- Validate slider value is within range (50-200%) -->
            <do_if value="global.$GT_GlobalSettings.$XP.$XPMultiplier lt 50">
              <set_value name="global.$GT_GlobalSettings.$XP.$XPMultiplier" exact="100"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$XP.$XPMultiplier gt 200">
              <set_value name="global.$GT_GlobalSettings.$XP.$XPMultiplier" exact="100"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 50,
              $max = 200,
              $start = global.$GT_GlobalSettings.$XP.$XPMultiplier,
              $step = 10,
              $suffix = '%',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$XP', $setting = '$XPMultiplier']
            ]"/>
            
            <!-- Commander Bonus Percent -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9015},
              $mouseOverText = {77000,9115}
            ]"/>
            <!-- Validate slider value is within range (0-50%) -->
            <do_if value="not global.$GT_GlobalSettings.$XP.$CommanderBonusPercent?">
              <set_value name="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" exact="10"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent lt 0">
              <set_value name="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" exact="0"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent gt 50">
              <set_value name="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" exact="50"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 0,
              $max = 50,
              $start = global.$GT_GlobalSettings.$XP.$CommanderBonusPercent,
              $step = 1,
              $suffix = '%',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$XP', $setting = '$CommanderBonusPercent']
            ]"/>
            
            <!-- Galaxy Miner Section (GT XP mode only) -->
            <do_if value="not global.$GT_GlobalSettings.$Miner?">
              <set_value name="global.$GT_GlobalSettings.$Miner" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel?">
              <set_value name="global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel" exact="false"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9310},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9311},
              $mouseOverText = {77000,9411}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$Miner', '$ScaleResourceProbeScanByPilotLevel', global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel]
            ]"/>
            </do_if>
            
            <!-- Trading Price Range Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9004},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Profit Threshold Base (affects MinAbsoluteProfit calculation) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9016},
              $mouseOverText = {77000,9116}
            ]"/>
            <!-- Validate base profit (0-500 Cr) stored in RAW centicredits -->
            <set_value name="$profitBaseRaw" exact="10000"/> <!-- Default: 100 Cr -->
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$MinAbsoluteProfit?">
              <set_value name="$profitBaseRaw" exact="@global.$GT_Config.$Trading.$MinAbsoluteProfit"/>
            </do_if>
            <do_if value="not $profitBaseRaw? or $profitBaseRaw == null or $profitBaseRaw lt 0 or $profitBaseRaw gt 50000">
              <set_value name="$profitBaseRaw" exact="10000"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Settings] WARNING: Invalid Trading.MinAbsoluteProfit base, reset to 100Cr (10000 RAW)'" chance="100"/>
              </do_if>
              <do_if value="not global.$GT_Config?">
                <set_value name="global.$GT_Config" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Config.$Trading?">
                <set_value name="global.$GT_Config.$Trading" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Config.$Trading.$MinAbsoluteProfit" exact="$profitBaseRaw"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 0,
              $max = 500,
              $start = ($profitBaseRaw / 100),
              $step = 10,
              $suffix = ' Cr',
              $onSliderCellChanged = GT_MinProfitBase_Update,
              $echo = table[$section = '$Trading', $setting = '$MinAbsoluteProfit', $isConfig = true]
            ]"/>

            <!-- Min Player Money (Performance: skip trade search when player is broke) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9025},
              $mouseOverText = 'Minimum player money required before ships search for trades. Range: 1,000 - 100,000 Cr.'
            ]"/>
            <!-- Validate slider value is within range (1000-100000 Cr) -->
            <set_value name="$minPlayerMoney" exact="1000"/>
            <do_if value="global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney?">
              <set_value name="$minPlayerMoney" exact="@global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney"/>
            </do_if>
            <do_if value="not $minPlayerMoney? or $minPlayerMoney == null or $minPlayerMoney lt 1000 or $minPlayerMoney gt 100000">
              <set_value name="$minPlayerMoney" exact="1000"/>
              <set_value name="global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney" exact="1000"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1000,
              $max = 100000,
              $start = $minPlayerMoney,
              $step = 1000,
              $suffix = ' Cr',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Fleet', $setting = '$MinPlayerMoney']
            ]"/>

            <!-- Sell Price Max (Normal Trading) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9005},
              $mouseOverText = {77000,9104}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$sellPriceMax" exact="1.0"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$SellPriceMax?">
              <set_value name="$sellPriceMax" exact="@global.$GT_Config.$Trading.$SellPriceMax"/>
            </do_if>
            <do_if value="$sellPriceMax lt -1.0 or $sellPriceMax gt 1.0">
              <set_value name="$sellPriceMax" exact="1.0"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 100,
              $start = ($sellPriceMax * 100),
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_PriceRange_Update,
              $echo = table[$section = '$Trading', $setting = '$SellPriceMax', $isConfig = true]
            ]"/>
            
            <!-- Buy Price Min (Normal Trading) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9006},
              $mouseOverText = {77000,9105}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$buyPriceMin" exact="-1.0"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$BuyPriceMin?">
              <set_value name="$buyPriceMin" exact="@global.$GT_Config.$Trading.$BuyPriceMin"/>
            </do_if>
            <do_if value="$buyPriceMin lt -1.0 or $buyPriceMin gt 1.0">
              <set_value name="$buyPriceMin" exact="-1.0"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 100,
              $start = ($buyPriceMin * 100),
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_PriceRange_Update,
              $echo = table[$section = '$Trading', $setting = '$BuyPriceMin', $isConfig = true]
            ]"/>
            
            <!-- Isolated Sell Price Max -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9007},
              $mouseOverText = {77000,9106}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$isolatedSellPriceMax" exact="1.0"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$IsolatedSellPriceMax?">
              <set_value name="$isolatedSellPriceMax" exact="@global.$GT_Config.$Trading.$IsolatedSellPriceMax"/>
            </do_if>
            <do_if value="$isolatedSellPriceMax lt -1.0 or $isolatedSellPriceMax gt 1.0">
              <set_value name="$isolatedSellPriceMax" exact="1.0"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 100,
              $start = ($isolatedSellPriceMax * 100),
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_PriceRange_Update,
              $echo = table[$section = '$Trading', $setting = '$IsolatedSellPriceMax', $isConfig = true]
            ]"/>
            
            <!-- Isolated Buy Price Min -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9008},
              $mouseOverText = {77000,9107}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$isolatedBuyPriceMin" exact="-1.0"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$IsolatedBuyPriceMin?">
              <set_value name="$isolatedBuyPriceMin" exact="@global.$GT_Config.$Trading.$IsolatedBuyPriceMin"/>
            </do_if>
            <do_if value="$isolatedBuyPriceMin lt -1.0 or $isolatedBuyPriceMin gt 1.0">
              <set_value name="$isolatedBuyPriceMin" exact="-1.0"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 100,
              $start = ($isolatedBuyPriceMin * 100),
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_PriceRange_Update,
              $echo = table[$section = '$Trading', $setting = '$IsolatedBuyPriceMin', $isConfig = true]
            ]"/>
            
            <!-- Fallback Sell Price Max -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9009},
              $mouseOverText = {77000,9108}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$fallbackSellPriceMax" exact="1.0"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$FallbackSellPriceMax?">
              <set_value name="$fallbackSellPriceMax" exact="@global.$GT_Config.$Trading.$FallbackSellPriceMax"/>
            </do_if>
            <do_if value="$fallbackSellPriceMax lt -1.0 or $fallbackSellPriceMax gt 1.0">
              <set_value name="$fallbackSellPriceMax" exact="1.0"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 100,
              $start = ($fallbackSellPriceMax * 100),
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_PriceRange_Update,
              $echo = table[$section = '$Trading', $setting = '$FallbackSellPriceMax', $isConfig = true]
            ]"/>
            
            <!-- Fallback Buy Price Min -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9014},
              $mouseOverText = {77000,9109}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$fallbackBuyPriceMin" exact="-1.0"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$Trading? and global.$GT_Config.$Trading.$FallbackBuyPriceMin?">
              <set_value name="$fallbackBuyPriceMin" exact="@global.$GT_Config.$Trading.$FallbackBuyPriceMin"/>
            </do_if>
            <do_if value="$fallbackBuyPriceMin lt -1.0 or $fallbackBuyPriceMin gt 1.0">
              <set_value name="$fallbackBuyPriceMin" exact="-1.0"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 100,
              $start = ($fallbackBuyPriceMin * 100),
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_PriceRange_Update,
              $echo = table[$section = '$Trading', $setting = '$FallbackBuyPriceMin', $isConfig = true]
            ]"/>

            <!-- Ship proximity weight (MK3/MK4 validation sort â€” global.$GT_GlobalSettings.$Trading) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9312},
              $mouseOverText = {77000,9412}
            ]"/>
            <do_if value="not global.$GT_GlobalSettings.$Trading?">
              <set_value name="global.$GT_GlobalSettings.$Trading" exact="table[]"/>
            </do_if>
            <set_value name="$shipProxSlider" exact="4"/>
            <do_if value="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight?">
              <set_value name="$shipProxSlider" exact="(global.$GT_GlobalSettings.$Trading.$ShipProximityWeight * 100)i"/>
            </do_if>
            <do_if value="$shipProxSlider lt 0">
              <set_value name="$shipProxSlider" exact="0"/>
              <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="0"/>
            </do_if>
            <do_if value="$shipProxSlider gt 100">
              <set_value name="$shipProxSlider" exact="100"/>
              <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="1"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 0,
              $max = 100,
              $start = $shipProxSlider,
              $step = 1,
              $suffix = '',
              $onSliderCellChanged = GT_ShipProximityWeight_Update,
              $echo = table[$section = '$Trading', $setting = '$ShipProximityWeight']
            ]"/>

            <!-- Fleet Coordination Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9020},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
                      $text = {77000,9021},
        $mouseOverText = {77000,9121}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$Fleet', '$EnableFleetCoordination', global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination]
            ]"/>
            
            <!-- Cache Dropoff Tolerance -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9024},
              $mouseOverText = {77000,9124}
            ]"/>
            <!-- Validate slider value is within range -->
            <do_if value="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance lt 0">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance" exact="15"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance gt 50">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance" exact="15"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 0,
              $max = 50,
              $start = global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance,
              $step = 1,
              $suffix = '%',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Fleet', $setting = '$CacheDropoffTolerance']
            ]"/>

            <!-- Idle Parking Release Time -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9026},
              $mouseOverText = {77000,9126}
            ]"/>
            <!-- Key-existence via .keys â€” @/typeof fail for stored 0; never clobber on menu open -->
            <do_if value="not global.$GT_GlobalSettings.$Fleet?">
              <set_value name="global.$GT_GlobalSettings.$Fleet" exact="table[]"/>
            </do_if>
            <set_value name="$idleParkingReleaseMinutes" exact="1"/>
            <set_value name="$hasIdleParkingKey" exact="false"/>
            <do_all exact="global.$GT_GlobalSettings.$Fleet.keys.count" counter="$fki">
              <set_value name="$fleetKey" exact="global.$GT_GlobalSettings.$Fleet.keys.{$fki}"/>
              <do_if value="$fleetKey == '$IdleParkingReleaseMinutes'">
                <set_value name="$hasIdleParkingKey" exact="true"/>
                <set_value name="$idleParkingReleaseMinutes" exact="global.$GT_GlobalSettings.$Fleet.{$fleetKey}"/>
              </do_if>
            </do_all>
            <do_if value="not $hasIdleParkingKey">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="1"/>
            </do_if>
            <do_elseif value="$idleParkingReleaseMinutes lt 0">
              <set_value name="$idleParkingReleaseMinutes" exact="0"/>
              <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="0"/>
            </do_elseif>
            <do_elseif value="$idleParkingReleaseMinutes gt 60">
              <set_value name="$idleParkingReleaseMinutes" exact="60"/>
              <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="60"/>
            </do_elseif>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 0,
              $max = 60,
              $start = $idleParkingReleaseMinutes,
              $step = 1,
              $suffix = ' min',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Fleet', $setting = '$IdleParkingReleaseMinutes']
            ]"/>
            
            <do_if value="not $useVanillaXPOnly">
            <!-- Threat Avoidance Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9050},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Enable Threat Avoidance -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9051},
              $mouseOverText = {77000,9151}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ThreatAvoidance', '$Enabled', global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled]
            ]"/>
            
            <!-- Hostile Relation Threshold -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9052},
              $mouseOverText = {77000,9152}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$tempThreshold" exact="(global.$GT_GlobalSettings.$ThreatAvoidance.$HostileRelationThreshold * 100)"/>
            <do_if value="$tempThreshold lt -100">
              <set_value name="$tempThreshold" exact="-30"/>
            </do_if>
            <do_if value="$tempThreshold gt 0">
              <set_value name="$tempThreshold" exact="-30"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = -100,
              $max = 0,
              $start = $tempThreshold,
              $step = 1,
              $suffix = '%',
              $onSliderCellChanged = GT_Relation_Update,
              $echo = table[$section = '$ThreatAvoidance', $setting = '$HostileRelationThreshold']
            ]"/>
            
            <!-- Use Dynamic Blacklist -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9053},
              $mouseOverText = {77000,9153}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ThreatAvoidance', '$UseDynamicBlacklist', global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist]
            ]"/>
            
            <!-- Block Enemy Factions -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9054},
              $mouseOverText = {77000,9154}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ThreatAvoidance', '$BlockEnemyFactions', global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions]
            ]"/>
            
            <!-- Blacklist Threat Threshold -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9055},
              $mouseOverText = {77000,9155}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 5,
              $start = global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold,
              $step = 1,
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$ThreatAvoidance', $setting = '$BlacklistThreshold']
            ]"/>
            
            <!-- Recreate Blacklist Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 5,
              $text = {77000,9056},
              $mouseOverText = {77000,9156}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 6,
              $colSpan = 3,
              $text = table[
                $text = {77000,9057},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_RecreateBlacklist,
              $onRightClick = GT_RecreateBlacklist
            ]"/>

            <!-- Assign Current Blacklist To GT Fleet Commanders -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 5,
              $text = {77000,9058},
              $mouseOverText = {77000,9157}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 6,
              $colSpan = 3,
              $text = table[
                $text = {77000,9059},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_AssignBlacklistToGTShips,
              $onRightClick = GT_AssignBlacklistToGTShips
            ]"/>
            
            <!-- Note: Risk Tolerance is now configured per-ship in the command behavior settings -->
            </do_if>
            
            <!-- Auto-Repair Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9040},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Enable Auto-Repair -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9041},
              $mouseOverText = {77000,9141}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$AutoRepair.$Enabled then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$AutoRepair.$Enabled then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$AutoRepair', '$Enabled', global.$GT_GlobalSettings.$AutoRepair.$Enabled]
            ]"/>
            
            <!-- Hull Threshold Slider -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9042},
              $mouseOverText = {77000,9142}
            ]"/>
            <!-- Validate slider value is within range -->
            <do_if value="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold lt 50">
              <set_value name="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold" exact="80"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold gt 99">
              <set_value name="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold" exact="80"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 50,
              $max = 99,
              $start = global.$GT_GlobalSettings.$AutoRepair.$HullThreshold,
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$AutoRepair', $setting = '$HullThreshold']
            ]"/>
            
            <!-- Note: Minimum pilot level for auto-repair is hardcoded to Level 12+ -->
            
            <!-- Notifications Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9030},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>

            <!-- Level-Up Popup Notifications (GT_Config-backed toggle used by XP system) -->
            <do_if value="not global.$GT_Config?">
              <set_value name="global.$GT_Config" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications?">
              <set_value name="global.$GT_Config.$Notifications" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications.$LevelUp?">
              <set_value name="global.$GT_Config.$Notifications.$LevelUp" exact="true"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications.$TrainingRequired?">
              <set_value name="global.$GT_Config.$Notifications.$TrainingRequired" exact="true"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications.$TrainingCompleted?">
              <set_value name="global.$GT_Config.$Notifications.$TrainingCompleted" exact="true"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications.$ProfitReports?">
              <set_value name="global.$GT_Config.$Notifications.$ProfitReports" exact="true"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications.$MarketAlerts?">
              <set_value name="global.$GT_Config.$Notifications.$MarketAlerts" exact="true"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Notifications.$FleetUpdates?">
              <set_value name="global.$GT_Config.$Notifications.$FleetUpdates" exact="false"/>
            </do_if>
            <do_if value="not $useVanillaXPOnly">
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9510},
              $mouseOverText = {77000,9610}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_Config.$Notifications.$LevelUp then {1001,4825} else {1001,8942},
                $color = if global.$GT_Config.$Notifications.$LevelUp then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Config_Setting_Toggle,
              $onRightClick = GT_Config_Setting_Toggle,
              $echo = table[$section = '$Notifications', $setting = '$LevelUp', $current = global.$GT_Config.$Notifications.$LevelUp]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9511},
              $mouseOverText = {77000,9611}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_Config.$Notifications.$TrainingRequired then {1001,4825} else {1001,8942},
                $color = if global.$GT_Config.$Notifications.$TrainingRequired then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Config_Setting_Toggle,
              $onRightClick = GT_Config_Setting_Toggle,
              $echo = table[$section = '$Notifications', $setting = '$TrainingRequired', $current = global.$GT_Config.$Notifications.$TrainingRequired]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9512},
              $mouseOverText = {77000,9612}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_Config.$Notifications.$TrainingCompleted then {1001,4825} else {1001,8942},
                $color = if global.$GT_Config.$Notifications.$TrainingCompleted then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Config_Setting_Toggle,
              $onRightClick = GT_Config_Setting_Toggle,
              $echo = table[$section = '$Notifications', $setting = '$TrainingCompleted', $current = global.$GT_Config.$Notifications.$TrainingCompleted]
            ]"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9513},
              $mouseOverText = {77000,9613}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_Config.$Notifications.$ProfitReports then {1001,4825} else {1001,8942},
                $color = if global.$GT_Config.$Notifications.$ProfitReports then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Config_Setting_Toggle,
              $onRightClick = GT_Config_Setting_Toggle,
              $echo = table[$section = '$Notifications', $setting = '$ProfitReports', $current = global.$GT_Config.$Notifications.$ProfitReports]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9514},
              $mouseOverText = {77000,9614}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_Config.$Notifications.$MarketAlerts then {1001,4825} else {1001,8942},
                $color = if global.$GT_Config.$Notifications.$MarketAlerts then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Config_Setting_Toggle,
              $onRightClick = GT_Config_Setting_Toggle,
              $echo = table[$section = '$Notifications', $setting = '$MarketAlerts', $current = global.$GT_Config.$Notifications.$MarketAlerts]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9515},
              $mouseOverText = {77000,9615}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_Config.$Notifications.$FleetUpdates then {1001,4825} else {1001,8942},
                $color = if global.$GT_Config.$Notifications.$FleetUpdates then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Config_Setting_Toggle,
              $onRightClick = GT_Config_Setting_Toggle,
              $echo = table[$section = '$Notifications', $setting = '$FleetUpdates', $current = global.$GT_Config.$Notifications.$FleetUpdates]
            ]"/>
            
            <!-- Simple Report Frequency -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9246},
              $mouseOverText = {77000,9346}
            ]"/>
            <!-- Validate slider value is within range -->
            <do_if value="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency lt 1">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency" exact="1"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency gt 30">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency" exact="1"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 30,
              $start = global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency,
              $step = 1,
              $suffix = ' min',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Notifications', $setting = '$SimpleReportFrequency']
            ]"/>
            
            <!-- Comprehensive Report Frequency -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9247},
              $mouseOverText = {77000,9347}
            ]"/>
            <!-- Validate slider value is within range -->
            <do_if value="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency lt 1">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" exact="30"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency gt 60">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" exact="30"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 60,
              $start = global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency,
              $step = 1,
              $suffix = ' min',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Notifications', $setting = '$ComprehensiveReportFrequency']
            ]"/>
            
            <do_if value="not $useVanillaXPOnly">
            <!-- Ship Modifications Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9090},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Enable Ship Modifications -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9091},
              $mouseOverText = {77000,9191}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$Modifications.$Enabled then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$Modifications.$Enabled then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$Modifications', '$Enabled', global.$GT_GlobalSettings.$Modifications.$Enabled]
            ]"/>
            </do_if>
            
            <!-- Defensive Equipment Section (Level 15 Feature) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9060},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Enable Defensive Equipment -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9061},
              $mouseOverText = {77000,9161}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$DefensiveEquipment', '$Enabled', global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled]
            ]"/>
            
            <!-- Restock Countermeasures -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9062},
              $mouseOverText = {77000,9162}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockCountermeasures then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockCountermeasures then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$DefensiveEquipment', '$RestockCountermeasures', global.$GT_GlobalSettings.$DefensiveEquipment.$RestockCountermeasures]
            ]"/>
            
            <!-- Restock Defense Drones -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9063},
              $mouseOverText = {77000,9163}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$DefensiveEquipment', '$RestockDefenseDrones', global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones]
            ]"/>
            
            <!-- Restock Trade Drones -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9064},
              $mouseOverText = {77000,9164}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$DefensiveEquipment', '$RestockTradeDrones', global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones]
            ]"/>
            
            <!-- Restock Laser Towers -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9065},
              $mouseOverText = {77000,9165}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$DefensiveEquipment', '$RestockLaserTowers', global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers]
            ]"/>
            
            <!-- Restock Repair Drones -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9066},
              $mouseOverText = {77000,9166}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$DefensiveEquipment', '$RestockRepairDrones', global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones]
            ]"/>
            
            <!-- Countermeasure Threshold -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9067},
              $mouseOverText = {77000,9167}
            ]"/>
            <!-- Validate slider value is within range -->
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold lt 10">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold" exact="50"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold gt 100">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold" exact="50"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 10,
              $max = 100,
              $start = global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold,
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$DefensiveEquipment', $setting = '$CountermeasureThreshold']
            ]"/>
            
            <!-- Unified Capacity Threshold -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9068},
              $mouseOverText = {77000,9168}
            ]"/>
            <!-- Validate slider value is within range -->
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold lt 10">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold" exact="70"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold gt 100">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold" exact="70"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 10,
              $max = 100,
              $start = global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold,
              $step = 5,
              $suffix = '%',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$DefensiveEquipment', $setting = '$UnifiedThreshold']
            ]"/>
            
            <!-- Balance Profile Cycling Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9069},
              $mouseOverText = {77000,9169}
            ]"/>
            <!-- Validate profile value is within range -->
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile lt 0">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile" exact="2"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile gt 4">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile" exact="2"/>
            </do_if>
            <!-- Get profile name for display using translation IDs -->
            <!-- Set profile name using conditional logic (translation IDs must be literals) -->
            <set_value name="$profileName" exact="{77000,6103}"/>  <!-- Default: Trading-Focused -->
            <do_if value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile == 0">
              <set_value name="$profileName" exact="{77000,6101}"/>  <!-- Balanced -->
            </do_if>
            <do_elseif value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile == 1">
              <set_value name="$profileName" exact="{77000,6102}"/>  <!-- Defensive -->
            </do_elseif>
            <do_elseif value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile == 2">
              <set_value name="$profileName" exact="{77000,6103}"/>  <!-- Trading-Focused -->
            </do_elseif>
            <do_elseif value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile == 3">
              <set_value name="$profileName" exact="{77000,6104}"/>  <!-- Heavy Defense -->
            </do_elseif>
            <do_elseif value="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile == 4">
              <set_value name="$profileName" exact="{77000,6105}"/>  <!-- Tower Support -->
            </do_elseif>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 4,
              $text = table[
                $text = $profileName,
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Profile_Cycle,
              $onRightClick = GT_Profile_Cycle,
              $echo = ['$DefensiveEquipment', '$BalanceProfile', global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile]
            ]"/>
            
            <!-- Ship Naming Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9070},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>

            <set_value name="$namingMode" exact="'legacy'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$NamingMode?">
              <set_value name="$namingMode" exact="@global.$GT_GlobalSettings.$ShipNaming.$NamingMode"/>
            </do_if>
            <set_value name="$shipNamingLegacyMode" exact="true"/>
            <do_if value="$namingMode == 'pattern' and not $useVanillaXPOnly">
              <set_value name="$shipNamingLegacyMode" exact="false"/>
            </do_if>
            
            <!-- Master Enable/Disable Toggle -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9075},
              $mouseOverText = {77000,9175}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$Enabled then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$Enabled then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$Enabled', global.$GT_GlobalSettings.$ShipNaming.$Enabled]
            ]"/>

            <do_if value="not $useVanillaXPOnly">
            <!-- Naming Mode: Legacy vs Pattern -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9085},
              $mouseOverText = {77000,9184}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 4,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$NamingMode == 'pattern' then {77000,9087} else {77000,9086},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_NamingMode_Cycle,
              $onRightClick = GT_NamingMode_Cycle,
              $echo = ['$ShipNaming', '$NamingMode', global.$GT_GlobalSettings.$ShipNaming.$NamingMode]
            ]"/>
            </do_if>

            <do_if value="not $useVanillaXPOnly">
            <!-- Pilot Renaming Toggle -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = 'Pilot renaming (GT)',
              $mouseOverText = 'Toggle GT pilot tags: (T:Level) PilotName'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$PilotRenamingEnabled', global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled]
            ]"/>
            </do_if>

            <do_if value="$shipNamingLegacyMode">
            <do_if value="not $useVanillaXPOnly">
            <!-- Display XP Setting -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9071},
              $mouseOverText = {77000,9171}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DisplayXP then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$DisplayXP then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$DisplayXP', global.$GT_GlobalSettings.$ShipNaming.$DisplayXP]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$XPPosition == 'prefix' then {77000,9076} else {77000,9077},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Position_Toggle,
              $onRightClick = GT_Position_Toggle,
              $echo = ['$ShipNaming', '$XPPosition', global.$GT_GlobalSettings.$ShipNaming.$XPPosition]
            ]"/>
            
            <!-- Display Rank Setting -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9072},
              $mouseOverText = {77000,9172}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DisplayRank then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$DisplayRank then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$DisplayRank', global.$GT_GlobalSettings.$ShipNaming.$DisplayRank]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$RankPosition == 'prefix' then {77000,9076} else {77000,9077},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Position_Toggle,
              $onRightClick = GT_Position_Toggle,
              $echo = ['$ShipNaming', '$RankPosition', global.$GT_GlobalSettings.$ShipNaming.$RankPosition]
            ]"/>
            
            <!-- Display Level Setting -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9073},
              $mouseOverText = {77000,9173}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$DisplayLevel', global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$LevelPosition == 'prefix' then {77000,9076} else {77000,9077},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Position_Toggle,
              $onRightClick = GT_Position_Toggle,
              $echo = ['$ShipNaming', '$LevelPosition', global.$GT_GlobalSettings.$ShipNaming.$LevelPosition]
            ]"/>
            </do_if>
            
            <!-- Display Ship Class Setting -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9082},
              $mouseOverText = {77000,9182}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$DisplayShipClass', global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition == 'prefix' then {77000,9076} else {77000,9077},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Position_Toggle,
              $onRightClick = GT_Position_Toggle,
              $echo = ['$ShipNaming', '$ShipClassPosition', global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition]
            ]"/>
            
            <!-- Display Status Setting -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9074},
              $mouseOverText = {77000,9174}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$DisplayStatus', global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$StatusPosition == 'prefix' then {77000,9076} else {77000,9077},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Position_Toggle,
              $onRightClick = GT_Position_Toggle,
              $echo = ['$ShipNaming', '$StatusPosition', global.$GT_GlobalSettings.$ShipNaming.$StatusPosition]
            ]"/>

            <!-- Display Home Sector (legacy layout) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9084},
              $mouseOverText = {77000,9183}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$ShipNaming', '$DisplayHomeSector', global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector]
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition == 'prefix' then {77000,9076} else {77000,9077},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Position_Toggle,
              $onRightClick = GT_Position_Toggle,
              $echo = ['$ShipNaming', '$HomeSectorPosition', global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition]
            ]"/>
            
            <!-- Default Name Source Setting -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9078},
              $mouseOverText = {77000,9178}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 4,
              $text = table[
                $text = if global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource == 'macro.name' then {77000,9079} else if global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource == 'typename' then {77000,9080} else if global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource == 'macro.name.base' then {77000,9081} else {77000,9083},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_NameSource_Cycle,
              $onRightClick = GT_NameSource_Cycle,
              $echo = ['$ShipNaming', '$DefaultNameSource', global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource]
            ]"/>
            </do_if>

            <do_if value="not $shipNamingLegacyMode and not $useVanillaXPOnly">
            <!-- Custom name pattern (pattern mode) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9088},
              $mouseOverText = {77000,9089}
            ]"/>
            <set_value name="$namePatternDefault" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
            <set_value name="$namePatternText" exact="$namePatternDefault"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$NamePattern? and global.$GT_GlobalSettings.$ShipNaming.$NamePattern != ''">
              <set_value name="$namePatternText" exact="global.$GT_GlobalSettings.$ShipNaming.$NamePattern"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $namePatternText,
              $maxChars = 128,
              $onEditBoxDeactivated = GT_NamePattern_Update,
              $echo = table[$setting = '$NamePattern']
            ]"/>
            </do_if>

            <do_if value="not $shipNamingLegacyMode and not $useVanillaXPOnly">
            <!-- Pattern placeholder legend -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9092},
              $halign = 'center',
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9093},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9094},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9095},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9096},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9097},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9098},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9099},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9100},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9101},
              $color = 'Color.text_normal'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9102},
              $color = 'Color.text_normal',
              $mouseOverText = {77000,9089}
            ]"/>
            </do_if>
            
            <!-- Performance Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9230},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Max Concurrent Cache Searches -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9248},
              $mouseOverText = {77000,9348}
            ]"/>
            <set_value name="$maxConcurrentCache" exact="5"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches?">
              <set_value name="$maxConcurrentCache" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches"/>
            </do_if>
            <do_if value="$maxConcurrentCache lt 1 or $maxConcurrentCache gt 10">
              <set_value name="$maxConcurrentCache" exact="5"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 10,
              $start = $maxConcurrentCache,
              $step = 1,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxConcurrentCacheSearches']
            ]"/>

            <!-- Max Concurrent Live Searches -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9249},
              $mouseOverText = {77000,9349}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$maxConcurrentLive" exact="1"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches?">
              <set_value name="$maxConcurrentLive" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches"/>
            </do_if>
            <do_if value="$maxConcurrentLive lt 1 or $maxConcurrentLive gt 10">
              <set_value name="$maxConcurrentLive" exact="1"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 10,
              $start = $maxConcurrentLive,
              $step = 1,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxConcurrentLiveSearches']
            ]"/>

            <!-- Max Concurrent Fallback Searches -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9386},
              $mouseOverText = {77000,9485}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$maxConcurrentFallback" exact="1"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches?">
              <set_value name="$maxConcurrentFallback" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches"/>
            </do_if>
            <do_if value="$maxConcurrentFallback lt 1 or $maxConcurrentFallback gt 10">
              <set_value name="$maxConcurrentFallback" exact="1"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 10,
              $start = $maxConcurrentFallback,
              $step = 1,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxConcurrentFallbackSearches']
            ]"/>
            
            <!-- Max Trades To Return -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9234},
              $mouseOverText = {77000,9334}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$maxTrades" exact="20"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn?">
              <set_value name="$maxTrades" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn"/>
            </do_if>
            <do_if value="$maxTrades lt 1 or $maxTrades gt 100">
              <set_value name="$maxTrades" exact="20"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 100,
              $start = $maxTrades,
              $step = 1,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxTradesToReturn']
            ]"/>
            
            <!-- Max Offers Per Ware -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9235},
              $mouseOverText = {77000,9335}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$maxOffers" exact="20"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare?">
              <set_value name="$maxOffers" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare"/>
            </do_if>
            <do_if value="$maxOffers lt 5 or $maxOffers gt 100">
              <set_value name="$maxOffers" exact="20"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 5,
              $max = 100,
              $start = $maxOffers,
              $step = 5,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxOffersPerWare']
            ]"/>
            
            <!-- Max Trades Per Ware -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9236},
              $mouseOverText = {77000,9336}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$maxTradesPerWare" exact="20"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
              <set_value name="$maxTradesPerWare" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
            </do_if>
            <do_if value="$maxTradesPerWare lt 5 or $maxTradesPerWare gt 100">
              <set_value name="$maxTradesPerWare" exact="20"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 5,
              $max = 100,
              $start = $maxTradesPerWare,
              $step = 5,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxTradesPerWare']
            ]"/>
            
            <!-- Max Offers Per Ware For Matching -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9237},
              $mouseOverText = {77000,9337}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$maxOffersForMatching" exact="20"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching?">
              <set_value name="$maxOffersForMatching" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching"/>
            </do_if>
            <do_if value="$maxOffersForMatching lt 5 or $maxOffersForMatching gt 100">
              <set_value name="$maxOffersForMatching" exact="20"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 5,
              $max = 100,
              $start = $maxOffersForMatching,
              $step = 5,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxOffersPerWareForMatching']
            ]"/>
            
            <!-- Early Exit Threshold -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9238},
              $mouseOverText = {77000,9338}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$earlyExitThreshold" exact="2000"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold?">
              <set_value name="$earlyExitThreshold" exact="@global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold"/>
            </do_if>
            <do_if value="$earlyExitThreshold lt 100 or $earlyExitThreshold gt 10000">
              <set_value name="$earlyExitThreshold" exact="2000"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 100,
              $max = 10000,
              $start = $earlyExitThreshold,
              $step = 100,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$EarlyExitThreshold']
            ]"/>
            
            <!-- Live Offer Slice Interval -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9241},
              $mouseOverText = {77000,9341}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$liveOfferSliceInterval" exact="100"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval?">
              <set_value name="$liveOfferSliceInterval" exact="@global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval"/>
            </do_if>
            <do_if value="$liveOfferSliceInterval lt 5 or $liveOfferSliceInterval gt 2000">
              <set_value name="$liveOfferSliceInterval" exact="100"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 5,
              $max = 2000,
              $start = $liveOfferSliceInterval,
              $step = 25,
              $suffix = 'ms',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$LiveOfferSliceInterval']
            ]"/>

            <!-- Search Lock TTL (self-heal for old saves) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9266},
              $mouseOverText = {77000,9366}
            ]"/>
            <set_value name="$searchLockTtl" exact="600"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$SearchLockTTL?">
              <set_value name="$searchLockTtl" exact="@global.$GT_GlobalSettings.$Performance.$SearchLockTTL"/>
            </do_if>
            <do_if value="$searchLockTtl lt 60 or $searchLockTtl gt 7200">
              <set_value name="$searchLockTtl" exact="600"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 60,
              $max = 7200,
              $start = $searchLockTtl,
              $step = 60,
              $suffix = 's',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$SearchLockTTL']
            ]"/>

            <!-- Max Offers Per Search (total offer cap for lib.gt.live.search) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9265},
              $mouseOverText = {77000,9365}
            ]"/>
            <set_value name="$maxOffersPerSearch" exact="200"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch?">
              <set_value name="$maxOffersPerSearch" exact="@global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch"/>
            </do_if>
            <do_if value="$maxOffersPerSearch lt 50 or $maxOffersPerSearch gt 2000">
              <set_value name="$maxOffersPerSearch" exact="200"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 50,
              $max = 2000,
              $start = $maxOffersPerSearch,
              $step = 50,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$MaxOffersPerSearch']
            ]"/>
            
            <!-- Batch Chunk Size -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9263},
              $mouseOverText = {77000,9363}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$batchChunkSize" exact="5"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$BatchChunkSize?">
              <set_value name="$batchChunkSize" exact="@global.$GT_GlobalSettings.$Performance.$BatchChunkSize"/>
            </do_if>
            <do_if value="$batchChunkSize lt 5 or $batchChunkSize gt 20">
              <set_value name="$batchChunkSize" exact="5"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 5,
              $max = 20,
              $start = $batchChunkSize,
              $step = 1,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$BatchChunkSize']
            ]"/>
            
            <!-- Legacy sliders removed in AI migration:
                 BatchProcessingDelay, BatchBackpressureSoft/Hard,
                 SectorsPerSlice, HomeRefreshCooldown, CacheMissCooldownBase, SchedulerTickInterval,
                 Per-tick limits, QueueStaleThreshold, FailedTradeExpiration -->
            
            <!-- Trade Found Signal Delay -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9490},
              $mouseOverText = {77000,9590}
            ]"/>
            <set_value name="$tradeFoundSignalDelay" exact="10"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay?">
              <set_value name="$tradeFoundSignalDelay" exact="@global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay"/>
            </do_if>
            <do_if value="$tradeFoundSignalDelay lt 10 or $tradeFoundSignalDelay gt 1000">
              <set_value name="$tradeFoundSignalDelay" exact="10"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 10,
              $max = 1000,
              $start = $tradeFoundSignalDelay,
              $step = 10,
              $suffix = 'ms',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$TradeFoundSignalDelay']
            ]"/>
            
            <!-- AI Yield Interval -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = 'AI Yield Interval',
              $mouseOverText = 'CPU yield between heavy loop iterations in AI scripts (ms). Higher values reduce CPU load but slow down trade searches. Default: 1ms. Increase to 5-10ms on weaker systems.'
            ]"/>
            <set_value name="$aiYieldInterval" exact="1"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
              <set_value name="$aiYieldInterval" exact="@global.$GT_GlobalSettings.$Performance.$AIYieldInterval"/>
            </do_if>
            <do_if value="$aiYieldInterval lt 1 or $aiYieldInterval gt 50">
              <set_value name="$aiYieldInterval" exact="1"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 50,
              $start = $aiYieldInterval,
              $step = 1,
              $suffix = 'ms',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$AIYieldInterval']
            ]"/>

            <!-- Cache Query Max Entries -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9381},
              $mouseOverText = {77000,9481}
            ]"/>
            <set_value name="$cacheQueryMaxEntries" exact="50"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries?">
              <set_value name="$cacheQueryMaxEntries" exact="@global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries"/>
            </do_if>
            <do_if value="$cacheQueryMaxEntries lt 1 or $cacheQueryMaxEntries gt 200">
              <set_value name="$cacheQueryMaxEntries" exact="50"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 200,
              $start = $cacheQueryMaxEntries,
              $step = 1,
              $suffix = ' entries',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$CacheQueryMaxEntries']
            ]"/>

            <!-- Cache Write Batch Size -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = 'Cache Write Batch Size',
              $mouseOverText = 'Number of sorted insertions between CPU yields during cache writing (1-20). Higher = faster cache updates but slightly higher per-frame CPU cost. Default: 1. Increase to 5-10 on powerful systems.'
            ]"/>
            <set_value name="$cacheWriteBatch" exact="1"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize?">
              <set_value name="$cacheWriteBatch" exact="@global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize"/>
            </do_if>
            <do_if value="$cacheWriteBatch lt 1 or $cacheWriteBatch gt 20">
              <set_value name="$cacheWriteBatch" exact="1"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1,
              $max = 20,
              $start = $cacheWriteBatch,
              $step = 1,
              $suffix = ' entries',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$CacheWriteBatchSize']
            ]"/>

            <!-- Cache Cleanup Batch Size -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = 'Cache Cleanup Batch Size',
              $mouseOverText = 'Number of cache entries processed between CPU yields during write-time cleanup (10-200). Higher = faster cleanup but slightly higher per-frame CPU cost. Default: 50.'
            ]"/>
            <set_value name="$cacheCleanupBatch" exact="50"/>
            <do_if value="global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize?">
              <set_value name="$cacheCleanupBatch" exact="@global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize"/>
            </do_if>
            <do_if value="$cacheCleanupBatch lt 10 or $cacheCleanupBatch gt 200">
              <set_value name="$cacheCleanupBatch" exact="50"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 10,
              $max = 200,
              $start = $cacheCleanupBatch,
              $step = 10,
              $suffix = ' entries',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$Performance', $setting = '$CacheCleanupBatchSize']
            ]"/>

            <!-- All legacy per-tick / scheduler / queue settings fully removed in AI migration -->
            
            <!-- Number Format Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9239},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Number Format Style -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9240},
              $mouseOverText = {77000,9340}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 5,
              $colSpan = 4,
              $text = table[
                $text = if global.$GT_GlobalSettings.$NumberFormat.$Format == 'german' then {77000,9244} else {77000,9245},
                $color = 'Color.text_normal',
                $halign = 'center'
              ],
              $onClick = GT_Format_Cycle,
              $onRightClick = GT_Format_Cycle,
              $echo = ['$NumberFormat', '$Format', global.$GT_GlobalSettings.$NumberFormat.$Format]
            ]"/>
            
            <!-- Use M Suffix -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9242},
              $mouseOverText = {77000,9342}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$NumberFormat', '$UseMSuffix', global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix]
            ]"/>
            
            <!-- M Suffix Threshold -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9243},
              $mouseOverText = {77000,9343}
            ]"/>
            <!-- Validate slider value is within range -->
            <set_value name="$mThreshold" exact="999999"/>
            <do_if value="global.$GT_GlobalSettings.$NumberFormat? and global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold?">
              <set_value name="$mThreshold" exact="@global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold"/>
            </do_if>
            <do_if value="$mThreshold lt 1000 or $mThreshold gt 999999999">
              <set_value name="$mThreshold" exact="999999"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
              $col = 5,
              $colSpan = 4,
              $min = 1000,
              $max = 999999999,
              $start = $mThreshold,
              $step = 100000,
              $suffix = '',
              $onSliderCellChanged = GT_Slider_Update,
              $echo = table[$section = '$NumberFormat', $setting = '$MSuffixThreshold']
            ]"/>

            <!-- Credits Due UI Override -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9398},
              $mouseOverText = {77000,9399}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$UI', '$UseGTCreditsDueOverride', global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride]
            ]"/>

            <!-- Maintenance & Diagnostics Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9220},
              $halign = 'center',
              $color = 'Color.text_positive'
            ]"/>
            
            <!-- Enable Debug Logging -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9201},
              $mouseOverText = {77000,9202}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then {1001,4825} else {1001,8942},
                $color = if global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Setting_Toggle,
              $onRightClick = GT_Setting_Toggle,
              $echo = ['$Debug', '$EnableDebugLogging', global.$GT_GlobalSettings.$Debug.$EnableDebugLogging]
            ]"/>

            <!-- Clear Pilot Renaming Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = 'Clear pilot renaming',
              $mouseOverText = 'Restore all GT pilot names to their stored vanilla names'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = 'CLEAR',
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_ClearPilotRenaming,
              $onRightClick = GT_ClearPilotRenaming
            ]"/>
            
            <!-- Reset Profit Statistics Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9221},
              $mouseOverText = {77000,9321}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9222},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_ResetProfitStats,
              $onRightClick = GT_ResetProfitStats
            ]"/>
            
            <!-- Clear All Blacklisted Sectors Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9223},
              $mouseOverText = {77000,9323}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9224},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_ClearAllBlacklistedSectors,
              $onRightClick = GT_ClearAllBlacklistedSectors
            ]"/>
            
            <!-- Reset All Settings to Defaults Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9225},
              $mouseOverText = {77000,9325}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9226},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_ResetAllSettings,
              $onRightClick = GT_ResetAllSettings
            ]"/>
            
            <!-- Clear Trade Cache for All Home Sectors Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9227},
              $mouseOverText = {77000,9327}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9228},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_ClearTradeCache,
              $onRightClick = GT_ClearTradeCache
            ]"/>

            <!-- Dump Trade Cache (FULL; heavy) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9292},
              $mouseOverText = {77000,9392}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9293},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_DumpTradeCache,
              $onRightClick = GT_DumpTradeCache
            ]"/>

            <!-- Release All Search Locks Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 1,
              $colSpan = 8,
              $text = table[
                $text = {77000,9229},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $mouseOverText = {77000,9329},
              $onClick = GT_ReleaseAllLocks,
              $onRightClick = GT_ReleaseAllLocks
            ]"/>

            <!-- Clear Fleet Reservations Button -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9294},
              $mouseOverText = {77000,9394}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9295},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_ClearReservations,
              $onRightClick = GT_ClearReservations
            ]"/>

            <!-- Dump Trade Hub Status (on-demand debug snapshot) -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9290},
              $mouseOverText = {77000,9390}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = {77000,9291},
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_DumpTradeHubStatus,
              $onRightClick = GT_DumpTradeHubStatus
            ]"/>

            <!-- Dump fallback activation counters -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = 'Fallback activations',
              $mouseOverText = 'Dump global.$GT_FallbackActivations counters to notification + log'
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = 'Dump',
                $color = 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_DumpFallbackActivations,
              $onRightClick = GT_DumpFallbackActivations
            ]"/>
            
            <!-- Ship State Naming Section -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9250},
              $halign = 'center',
              $color = 'Color.text_positive',
              $mouseOverText = {77000,9350}
            ]"/>
            
            <!-- Resupply State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9251},
              $mouseOverText = {77000,9351}
            ]"/>
            <set_value name="$resupplyAbbr" exact="'RS'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Resupply?">
              <set_value name="$resupplyAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Resupply"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $resupplyAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Resupply', $setting = '$Resupply']
            ]"/>
            
            <!-- Repair State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9252},
              $mouseOverText = {77000,9352}
            ]"/>
            <set_value name="$repairAbbr" exact="'RP'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Repair?">
              <set_value name="$repairAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Repair"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $repairAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Repair', $setting = '$Repair']
            ]"/>
            
            <!-- Maintenance State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9253},
              $mouseOverText = {77000,9353}
            ]"/>
            <set_value name="$maintenanceAbbr" exact="'MT'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Maintenance?">
              <set_value name="$maintenanceAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Maintenance"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $maintenanceAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Maintenance', $setting = '$Maintenance']
            ]"/>
            
            <!-- Training State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9254},
              $mouseOverText = {77000,9354}
            ]"/>
            <set_value name="$trainingAbbr" exact="'TR'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Training?">
              <set_value name="$trainingAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Training"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $trainingAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Training', $setting = '$Training']
            ]"/>
            
            <!-- Escape State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9262},
              $mouseOverText = {77000,9362}
            ]"/>
            <set_value name="$escapeAbbr" exact="'ES'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Escape?">
              <set_value name="$escapeAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Escape"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $escapeAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Escape', $setting = '$Escape']
            ]"/>
            
            <!-- Reroute State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9255},
              $mouseOverText = {77000,9355}
            ]"/>
            <set_value name="$rerouteAbbr" exact="'RR'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Reroute?">
              <set_value name="$rerouteAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Reroute"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $rerouteAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Reroute', $setting = '$Reroute']
            ]"/>
            
            <!-- Clearance State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9256},
              $mouseOverText = {77000,9356}
            ]"/>
            <set_value name="$clearanceAbbr" exact="'CL'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Clearance?">
              <set_value name="$clearanceAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Clearance"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $clearanceAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Clearance', $setting = '$Clearance']
            ]"/>

            <!-- Unreachable State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9268},
              $mouseOverText = {77000,9367}
            ]"/>
            <set_value name="$unreachableAbbr" exact="'UR'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Unreachable?">
              <set_value name="$unreachableAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Unreachable"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $unreachableAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Unreachable', $setting = '$Unreachable']
            ]"/>

            <!-- Pilot Exchange State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9269},
              $mouseOverText = {77000,9368}
            ]"/>
            <set_value name="$pilotExchangeAbbr" exact="'PE'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$PilotExchange?">
              <set_value name="$pilotExchangeAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$PilotExchange"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $pilotExchangeAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'PilotExchange', $setting = '$PilotExchange']
            ]"/>
            
            <!-- Blocked State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9257},
              $mouseOverText = {77000,9357}
            ]"/>
            <set_value name="$blockedAbbr" exact="'BL'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Blocked?">
              <set_value name="$blockedAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Blocked"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $blockedAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Blocked', $setting = '$Blocked']
            ]"/>

            <!-- Custom Blacklist State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9270},
              $mouseOverText = {77000,9369}
            ]"/>
            <set_value name="$customBlacklistAbbr" exact="'CB'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$CustomBlacklist?">
              <set_value name="$customBlacklistAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$CustomBlacklist"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $customBlacklistAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'CustomBlacklist', $setting = '$CustomBlacklist']
            ]"/>
            
            <!-- Fallback State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9258},
              $mouseOverText = {77000,9358}
            ]"/>
            <set_value name="$fallbackAbbr" exact="'FB'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Fallback?">
              <set_value name="$fallbackAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Fallback"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $fallbackAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Fallback', $setting = '$Fallback']
            ]"/>
            
            <!-- Isolated State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9259},
              $mouseOverText = {77000,9359}
            ]"/>
            <set_value name="$isolatedAbbr" exact="'IS'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Isolated?">
              <set_value name="$isolatedAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Isolated"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $isolatedAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Isolated', $setting = '$Isolated']
            ]"/>
            
            <!-- Trading State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9260},
              $mouseOverText = {77000,9360}
            ]"/>
            <set_value name="$tradingAbbr" exact="'TD'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Trading?">
              <set_value name="$tradingAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Trading"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $tradingAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Trading', $setting = '$Trading']
            ]"/>
            
            <!-- Idle State Abbreviation -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 4,
              $text = {77000,9261},
              $mouseOverText = {77000,9361}
            ]"/>
            <set_value name="$idleAbbr" exact="'ID'"/>
            <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Idle?">
              <set_value name="$idleAbbr" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Idle"/>
            </do_if>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_EditBox" param="table[
              $col = 5,
              $colSpan = 4,
              $defaultText = $idleAbbr,
              $maxChars = 12,
              $onEditBoxDeactivated = GT_StateAbbreviation_Update,
              $echo = table[$state = 'Idle', $setting = '$Idle']
            ]"/>

            <!-- Cheats Section -->
            <set_value name="$cheatScope" exact="'off'"/>
            <do_if value="global.$GT_GlobalSettings.$Cheats? and global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope?">
              <set_value name="$cheatScope" exact="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope"/>
            </do_if>
            <do_if value="$cheatScope != 'off' and $cheatScope != 'gt' and $cheatScope != 'all'">
              <set_value name="$cheatScope" exact="'off'"/>
            </do_if>

            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 8,
              $text = {77000,9700},
              $halign = 'center',
              $color = 'Color.text_warning',
              $mouseOverText = {77000,9800}
            ]"/>

            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9701},
              $mouseOverText = {77000,9801}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if $cheatScope == 'gt' then {1001,4825} else {1001,8942},
                $color = if $cheatScope == 'gt' then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Cheat_SetInvulnerabilityScope,
              $onRightClick = GT_Cheat_SetInvulnerabilityScope,
              $echo = 'gt'
            ]"/>

            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9702},
              $mouseOverText = {77000,9802}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if $cheatScope == 'all' then {1001,4825} else {1001,8942},
                $color = if $cheatScope == 'all' then $TextGreen else $TextRed,
                $halign = 'center'
              ],
              $onClick = GT_Cheat_SetInvulnerabilityScope,
              $onRightClick = GT_Cheat_SetInvulnerabilityScope,
              $echo = 'all'
            ]"/>

            <set_value name="$universeRevealed" exact="false"/>
            <do_if value="global.$GT_GlobalSettings.$Cheats? and global.$GT_GlobalSettings.$Cheats.$UniverseRevealed? and global.$GT_GlobalSettings.$Cheats.$UniverseRevealed">
              <set_value name="$universeRevealed" exact="true"/>
            </do_if>

            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9703},
              $mouseOverText = {77000,9803}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if $universeRevealed then {77000,9704} else {77000,9705},
                $color = if $universeRevealed then $TextGreen else 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_Cheat_RevealUniverse_Button,
              $onRightClick = GT_Cheat_RevealUniverse_Button
            ]"/>

            <set_value name="$pilotsMaxed" exact="false"/>
            <do_if value="global.$GT_GlobalSettings.$Cheats? and global.$GT_GlobalSettings.$Cheats.$PilotsMaxed? and global.$GT_GlobalSettings.$Cheats.$PilotsMaxed">
              <set_value name="$pilotsMaxed" exact="true"/>
            </do_if>

            <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
              $col = 1,
              $colSpan = 6,
              $text = {77000,9706},
              $mouseOverText = {77000,9804}
            ]"/>
            <signal_cue_instantly cue="md.Simple_Menu_API.Make_Button" param="table[
              $col = 7,
              $colSpan = 2,
              $text = table[
                $text = if $pilotsMaxed then {77000,9707} else {77000,9708},
                $color = if $pilotsMaxed then $TextGreen else 'Color.text_warning',
                $halign = 'center'
              ],
              $onClick = GT_Cheat_MaxPilotXP_Button,
              $onRightClick = GT_Cheat_MaxPilotXP_Button
            ]"/>
      </actions>
        </cue>
        
    <!-- Setting Toggle Handler -->
    <cue name="GT_Setting_Toggle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Debug: Show the full parameter structure -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] ToggleSetting called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Extract parameters from the echo array -->
            <set_value name="$section" exact="event.param.$echo.{1}"/>
            <set_value name="$setting" exact="event.param.$echo.{2}"/>
            <set_value name="$currentValue" exact="event.param.$echo.{3}"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Extracted parameters - Section: ' + $section + ', Setting: ' + $setting + ', CurrentValue: ' + $currentValue" chance="100"/>
            </do_if>
            
            <!-- Toggle the setting -->
            <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="not $currentValue"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Global setting toggled: ' + $section + '.' + $setting + ' = ' + global.$GT_GlobalSettings.{$section}.{$setting}" chance="100"/>
            </do_if>
            
        <!-- If this is a ship naming setting, update all ship names -->
        <!-- EXCEPTION: PilotRenamingEnabled is pilot-only and must not touch ship names -->
            <do_if value="$section == '$ShipNaming' and $setting != '$PilotRenamingEnabled'">
              <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
            </do_if>
        <!-- Pilot renaming toggle has immediate fleet-wide effect -->
        <do_if value="$section == '$ShipNaming' and $setting == '$PilotRenamingEnabled'">
          <do_if value="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled">
            <signal_cue_instantly cue="GT_ApplyPilotRenamingAll"/>
          </do_if>
          <do_else>
            <signal_cue_instantly cue="GT_ClearPilotRenaming"/>
          </do_else>
        </do_if>
            
            <!-- Auto-repair off: clear stale NeedsRepair / repair-order tracking fleet-wide -->
            <do_if value="$section == '$AutoRepair' and $setting == '$Enabled'">
              <do_if value="not global.$GT_GlobalSettings.$AutoRepair.$Enabled">
                <signal_cue_instantly cue="md.GT_Maintenance.ClearAutoRepairStateAll"/>
              </do_if>
            </do_if>
            
            <!-- If Ship Modifications were toggled, trigger immediate reconciliation -->
            <do_if value="$section == '$Modifications' and $setting == '$Enabled'">
              <signal_objects object="player.galaxy" param="'GT_Modifications_Settings_Changed'" param2="table[
                $Enabled = global.$GT_GlobalSettings.{$section}.{$setting}
              ]"/>
            </do_if>
            <!-- Vanilla XP mode toggle: force-refresh dependent systems immediately -->
            <do_if value="$section == '$XP' and $setting == '$UseVanillaXPOnly'">
              <!-- Reconcile GT modifications state under the new mode -->
              <signal_objects object="player.galaxy" param="'GT_Modifications_Settings_Changed'" param2="table[
                $Enabled = if global.$GT_GlobalSettings.$Modifications? and global.$GT_GlobalSettings.$Modifications.$Enabled? then global.$GT_GlobalSettings.$Modifications.$Enabled else false
              ]"/>
              <!-- Refresh ship names/tags after mode switch -->
              <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
              <do_if value="global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly">
                <do_if value="not global.$GT_GlobalSettings.$Miner?">
                  <set_value name="global.$GT_GlobalSettings.$Miner" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel" exact="false"/>
                <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled">
                  <set_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabledBeforeVanilla" exact="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled"/>
                </do_if>
                <set_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled" exact="false"/>
                <do_if value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$NamingMode? and global.$GT_GlobalSettings.$ShipNaming.$NamingMode == 'pattern'">
                  <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamingMode" exact="'legacy'"/>
                </do_if>
                <signal_cue_instantly cue="GT_ClearPilotRenaming"/>
                <!-- Clear active GT training blocks while preserving stored GT XP data for reversibility -->
                <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
                  <do_all exact="global.$GT_Pilots.keys.count" counter="$pilotIndex">
                    <set_value name="$pilotRef" exact="global.$GT_Pilots.keys.{$pilotIndex}"/>
                    <do_if value="$pilotRef? and global.$GT_Pilots.{$pilotRef}?">
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$XPBlocked"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$BlockedLevel"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$BlockedXPPending"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$PendingSkillLevel"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$PausedWithTrainingNeeded"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$PausedBlockedLevel"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$TrainingStarted"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$TrainingDuration"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$TrainingStation"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$TrainingState"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$ManualTrainingRequested"/>
                      <remove_value name="global.$GT_Pilots.{$pilotRef}.$NextTrainingRetryAt"/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
              <do_elseif value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabledBeforeVanilla? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabledBeforeVanilla">
                <set_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled" exact="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabledBeforeVanilla"/>
                <remove_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabledBeforeVanilla"/>
                <signal_cue_instantly cue="GT_ApplyPilotRenamingAll"/>
              </do_elseif>
              <do_elseif value="global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled">
                <signal_cue_instantly cue="GT_ApplyPilotRenamingAll"/>
              </do_elseif>
            </do_if>
            
            <!-- Keep Lua bridge settings in sync after any settings change. -->
            <signal_cue_instantly cue="md.GT_InfoMenu_Loader.SendPilotData"/>

            <signal_cue_instantly cue="GT_SyncUICreditsDueState"/>
            
            <!-- Refresh the menu -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
        </cue>

    <!-- Cheat invulnerability scope handler (off / gt / all) -->
    <cue name="GT_Cheat_SetInvulnerabilityScope" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_GlobalSettings.$Cheats?">
          <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
        </do_if>
        <set_value name="$requestedScope" exact="event.param.$echo"/>
        <set_value name="$currentScope" exact="'off'"/>
        <do_if value="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope?">
          <set_value name="$currentScope" exact="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope"/>
        </do_if>
        <do_if value="$requestedScope != 'gt' and $requestedScope != 'all'">
          <set_value name="$requestedScope" exact="'off'"/>
        </do_if>
        <do_if value="$currentScope == $requestedScope">
          <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="'off'"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="$requestedScope"/>
        </do_else>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Cheats] Invulnerability scope set to ' + global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" chance="100"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_Cheats.GT_Cheat_Reconcile"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <cue name="GT_Cheat_RevealUniverse_Button" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <signal_cue_instantly cue="md.GT_Cheats.GT_Cheat_RevealUniverse"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <cue name="GT_Cheat_MaxPilotXP_Button" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <signal_cue_instantly cue="md.GT_Cheats.GT_Cheat_MaxPilotXP"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <cue name="GT_Position_Toggle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Debug: Show the full parameter structure -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] TogglePosition called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Extract parameters from the echo array -->
            <set_value name="$section" exact="event.param.$echo.{1}"/>
            <set_value name="$setting" exact="event.param.$echo.{2}"/>
            <set_value name="$currentValue" exact="event.param.$echo.{3}"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Extracted parameters - Section: ' + $section + ', Setting: ' + $setting + ', CurrentValue: ' + $currentValue" chance="100"/>
            </do_if>
            
            <!-- Toggle between 'prefix' and 'suffix' -->
            <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="if $currentValue == 'prefix' then 'suffix' else 'prefix'"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Position setting toggled: ' + $section + '.' + $setting + ' = ' + global.$GT_GlobalSettings.{$section}.{$setting}" chance="100"/>
            </do_if>
            
            <!-- Update all ship names when position changes -->
            <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
            
            <!-- Refresh the menu -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
        </cue>
        
    <!-- Name Source Cycle Handler -->
    <cue name="GT_NameSource_Cycle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Extract parameters from the echo array -->
            <set_value name="$section" exact="event.param.$echo.{1}"/>
            <set_value name="$setting" exact="event.param.$echo.{2}"/>
            <set_value name="$currentValue" exact="event.param.$echo.{3}"/>
            
            <!-- Cycle through options: 'macro.name' -> 'typename' -> 'macro.name.base' -> 'basename' -> 'macro.name' -->
            <set_value name="$newValue" exact="'macro.name'"/>
            <do_if value="$currentValue == 'macro.name'">
              <set_value name="$newValue" exact="'typename'"/>
            </do_if>
            <do_elseif value="$currentValue == 'typename'">
              <set_value name="$newValue" exact="'macro.name.base'"/>
            </do_elseif>
            <do_elseif value="$currentValue == 'macro.name.base'">
              <set_value name="$newValue" exact="'basename'"/>
            </do_elseif>
            <do_else>
              <set_value name="$newValue" exact="'macro.name'"/>
            </do_else>
            
            <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="$newValue"/>
            
            <!-- Update all ship names when name source changes -->
            <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
            
            <!-- Refresh the menu -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
        </cue>

    <!-- Naming Mode Cycle Handler (legacy â†” pattern) -->
    <cue name="GT_NamingMode_Cycle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$section" exact="event.param.$echo.{1}"/>
        <set_value name="$setting" exact="event.param.$echo.{2}"/>
        <set_value name="$currentValue" exact="event.param.$echo.{3}"/>
        <set_value name="$newValue" exact="'pattern'"/>
        <do_if value="$currentValue == 'pattern'">
          <set_value name="$newValue" exact="'legacy'"/>
        </do_if>
        <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="$newValue"/>
        <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>
    
    <!-- Number Format Cycle Handler -->
    <cue name="GT_Format_Cycle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Extract parameters from the echo array -->
            <set_value name="$section" exact="event.param.$echo.{1}"/>
            <set_value name="$setting" exact="event.param.$echo.{2}"/>
            <set_value name="$currentValue" exact="event.param.$echo.{3}"/>
            
            <!-- Cycle between 'german' and 'english' -->
            <set_value name="$newValue" exact="'german'"/>
            <do_if value="$currentValue == 'german'">
              <set_value name="$newValue" exact="'english'"/>
            </do_if>
            <do_else>
              <set_value name="$newValue" exact="'german'"/>
            </do_else>
            
            <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="$newValue"/>
            <signal_cue_instantly cue="GT_SyncUICreditsDueState"/>
            
            <!-- Refresh the menu -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <cue name="GT_Config_Setting_Toggle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$section" exact="if event.param.$echo? and event.param.$echo.$section? then event.param.$echo.$section else null"/>
        <set_value name="$setting" exact="if event.param.$echo? and event.param.$echo.$setting? then event.param.$echo.$setting else null"/>
        <set_value name="$currentValue" exact="if event.param.$echo? and event.param.$echo.$current? then event.param.$echo.$current else false"/>
        <do_if value="$section? and $setting?">
          <do_if value="not global.$GT_Config?">
            <set_value name="global.$GT_Config" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Config.{$section}?">
            <set_value name="global.$GT_Config.{$section}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Config.{$section}.{$setting}" exact="not $currentValue"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Config setting toggled: GT_Config.' + $section + '.' + $setting + ' = ' + global.$GT_Config.{$section}.{$setting}" chance="100"/>
          </do_if>
        </do_if>
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>
    
    <!-- Pushes UI override settings + projected value to player.entity for Lua UI hook -->
    <cue name="GT_SyncUICreditsDueState" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_GlobalSettings.$UI?">
          <set_value name="global.$GT_GlobalSettings.$UI" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride?">
          <set_value name="global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride" exact="false"/>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$NumberFormat?">
          <set_value name="global.$GT_GlobalSettings.$NumberFormat" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$NumberFormat.$Format?">
          <set_value name="global.$GT_GlobalSettings.$NumberFormat.$Format" exact="'german'"/>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix?">
          <set_value name="global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix" exact="true"/>
        </do_if>
        <do_if value="not global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold?">
          <set_value name="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" exact="999999"/>
        </do_if>
        
        <set_value name="player.entity.$GT_UI_UseCreditsDueOverride" exact="global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride"/>
        <set_value name="player.entity.$GT_UI_NumberFormat" exact="global.$GT_GlobalSettings.$NumberFormat.$Format"/>
        <set_value name="player.entity.$GT_UI_UseMSuffix" exact="global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix"/>
        <set_value name="player.entity.$GT_UI_MSuffixThreshold" exact="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold"/>
        
        <set_value name="$uiProjectedRaw" exact="0"/>
        <do_if value="global.$GT_UICreditsDueProjectedRaw?">
          <set_value name="$uiProjectedRaw" exact="global.$GT_UICreditsDueProjectedRaw"/>
        </do_if>
        <set_value name="player.entity.$GT_UI_CreditsDueProjectedRaw" exact="$uiProjectedRaw"/>
        <set_value name="player.entity.$GT_UI_CreditsDueProjectedCr" exact="$uiProjectedRaw / 100"/>
      </actions>
    </cue>
        
    <!-- Balance Profile Cycle Handler -->
    <cue name="GT_Profile_Cycle" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Debug: Show the full parameter structure -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] ProfileCycle called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Extract parameters from the echo array -->
            <set_value name="$section" exact="event.param.$echo.{1}"/>
            <set_value name="$setting" exact="event.param.$echo.{2}"/>
            <set_value name="$currentValue" exact="event.param.$echo.{3}"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Extracted parameters - Section: ' + $section + ', Setting: ' + $setting + ', CurrentValue: ' + $currentValue" chance="100"/>
            </do_if>
            
            <!-- Cycle through profiles: 0=Balanced, 1=Defensive, 2=Trading-Focused, 3=Heavy Defense, 4=Tower Support -->
            <set_value name="$newValue" exact="($currentValue + 1) % 5"/>
            <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="$newValue"/>
            
            <!-- Get profile name for debug -->
            <set_value name="$profileName" exact="'Trading-Focused'"/>
            <do_if value="$newValue == 0">
              <set_value name="$profileName" exact="'Balanced'"/>
            </do_if>
            <do_elseif value="$newValue == 1">
              <set_value name="$profileName" exact="'Defensive'"/>
            </do_elseif>
            <do_elseif value="$newValue == 2">
              <set_value name="$profileName" exact="'Trading-Focused'"/>
            </do_elseif>
            <do_elseif value="$newValue == 3">
              <set_value name="$profileName" exact="'Heavy Defense'"/>
            </do_elseif>
            <do_elseif value="$newValue == 4">
              <set_value name="$profileName" exact="'Tower Support'"/>
            </do_elseif>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Profile cycled: ' + $section + '.' + $setting + ' = ' + $newValue + ' (' + $profileName + ')'" chance="100"/>
            </do_if>
            
        <!-- Refresh the menu -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>
    
    <!-- Clear Trade Cache for All Home Sectors Button Handler -->
    <cue name="GT_ClearTradeCache" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Clear Trade Cache button clicked'" chance="100"/>
        </do_if>
        
        <!-- Clear trade cache for all home sectors -->
        <set_value name="$clearedCount" exact="0"/>
        
        <!-- Clear MK3 trade cache -->
        <do_if value="global.$GT_TradeCache?">
          <set_value name="$cacheKeys" exact="@global.$GT_TradeCache.keys"/>
          <do_if value="$cacheKeys?">
            <set_value name="$cacheKeysCount" exact="@$cacheKeys.count"/>
            <do_if value="$cacheKeysCount? and $cacheKeysCount gt 0">
              <set_value name="$clearedCount" exact="$clearedCount + $cacheKeysCount"/>
            </do_if>
          </do_if>
          <set_value name="global.$GT_TradeCache" exact="table[]"/>
        </do_if>

        <!-- Clear MK4 trade cache -->
        <do_if value="global.$GT_TradeCacheMK4?">
          <set_value name="$mk4CacheKeys" exact="@global.$GT_TradeCacheMK4.keys"/>
          <do_if value="$mk4CacheKeys?">
            <set_value name="$mk4CacheKeysCount" exact="@$mk4CacheKeys.count"/>
            <do_if value="$mk4CacheKeysCount? and $mk4CacheKeysCount gt 0">
              <set_value name="$clearedCount" exact="$clearedCount + $mk4CacheKeysCount"/>
            </do_if>
          </do_if>
          <set_value name="global.$GT_TradeCacheMK4" exact="table[]"/>
        </do_if>
        
        <!-- Clear trade cache homes registry -->
        <do_if value="global.$GT_TradeCacheHomes?">
          <set_value name="global.$GT_TradeCacheHomes" exact="[]"/>
        </do_if>
        
        <!-- Clear trade cache by ware index (MK3) -->
        <do_if value="global.$GT_TradeCacheByWare?">
          <set_value name="global.$GT_TradeCacheByWare" exact="table[]"/>
        </do_if>

        <!-- Clear trade cache by ware index (MK4) -->
        <do_if value="global.$GT_TradeCacheMK4ByWare?">
          <set_value name="global.$GT_TradeCacheMK4ByWare" exact="table[]"/>
        </do_if>

        <!-- Clear cache max distance tracking (MK3) -->
        <do_if value="global.$GT_TradeCacheMaxDistance?">
          <set_value name="global.$GT_TradeCacheMaxDistance" exact="table[]"/>
        </do_if>

        <!-- Clear cache max distance tracking (MK4) -->
        <do_if value="global.$GT_TradeCacheMK4MaxDistance?">
          <set_value name="global.$GT_TradeCacheMK4MaxDistance" exact="table[]"/>
        </do_if>
        
        <!-- Log result -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Trade cache cleared for ' + $clearedCount + ' home sector(s)'" chance="100"/>
        </do_if>
        
        <!-- Refresh the menu -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <!-- Dump Trade Cache (FULL) Button Handler -->
    <!-- NOTE: This is intentionally heavy; it is chunked across frames to reduce spikes. -->
    <cue name="GT_DumpTradeCache" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Always show immediate feedback so the user knows the click was received -->
        <show_notification text="'[GT] Cache dump requested. Output goes to DebugLog. Click again to cancel.'" timeout="6s" priority="5"/>

        <!-- If debug logging is disabled, still allow the dump (explicit user action), but warn. -->
        <do_if value="not global.$GT_GlobalSettings? or not global.$GT_GlobalSettings.$Debug? or not global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <show_notification text="'[GT] Note: Debug Logging is OFF. Dump will still run (explicit) and write to log.'" timeout="6s"/>
        </do_if>

        <do_if value="not global.$GT_CacheDumpState? or global.$GT_CacheDumpState == null">
          <set_value name="global.$GT_CacheDumpState" exact="table[]"/>
        </do_if>

        <!-- Toggle behavior: if already dumping, cancel -->
        <do_if value="global.$GT_CacheDumpState.$Active? and global.$GT_CacheDumpState.$Active">
          <set_value name="global.$GT_CacheDumpState.$Cancel" exact="true"/>
          <show_notification text="'[GT] Cache dump: cancel requested (will stop shortly).'" timeout="4s"/>
          <debug_text text="'[GT-Cache-Dump] CANCEL requested'" chance="100"/>
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>

        <set_value name="$total" exact="0"/>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CalculateTotalCacheCount" result="$total"/>

        <!-- Detect cache shape and build home list -->
        <set_value name="$isLegacyList" exact="false"/>
        <do_if value="global.$GT_TradeCache? and typeof global.$GT_TradeCache == datatype.list">
          <set_value name="$isLegacyList" exact="true"/>
        </do_if>

        <set_value name="$homeKeys" exact="[]"/>
        <do_if value="not $isLegacyList">
          <!-- Prefer homes registry only if it exists AND is non-empty; otherwise fall back to GT_TradeCache.keys.
               Some saves can end up with cache keys but an empty registry, which made dumps show total=0 incorrectly. -->
          <do_if value="global.$GT_TradeCacheHomes? and global.$GT_TradeCacheHomes != null and typeof global.$GT_TradeCacheHomes == datatype.list and global.$GT_TradeCacheHomes.count gt 0">
            <set_value name="$homeKeys" exact="@global.$GT_TradeCacheHomes"/>
          </do_if>
          <do_else>
            <set_value name="$cacheObj" exact="@global.$GT_TradeCache"/>
            <set_value name="$homeKeys" exact="@$cacheObj.keys"/>
            <do_if value="$homeKeys == null">
              <set_value name="$homeKeys" exact="[]"/>
            </do_if>
          </do_else>
        </do_if>

        <set_value name="global.$GT_CacheDumpState" exact="table[
          $Active = true,
          $Cancel = false,
          $StartedAt = player.age,
          $LegacyList = $isLegacyList,
          $HomeKeys = $homeKeys,
          $HomeIndex = 1,
          $EntryIndex = 1,
          $Total = $total,
          $Lines = 0,
          $CurrentHomeHeaderPrinted = false,
          $DockShip = if global.$GT_LastTradeRequestShip? and global.$GT_LastTradeRequestShip.exists then global.$GT_LastTradeRequestShip else null
        ]"/>

        <debug_text text="'[GT-Cache-Dump] BEGIN t=' + (player.age / 1) + 's total=' + $total + ' legacyList=' + $isLegacyList + ' homeKeys=' + $homeKeys.count" chance="100"/>

        <signal_cue_instantly cue="GT_DumpTradeCache_Process"/>
        </do_else>
      </actions>
    </cue>

    <!-- Cache dump worker (chunked across frames) -->
    <cue name="GT_DumpTradeCache_Process" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay min="10ms" max="40ms"/>
      <actions>
        <set_value name="$proceed" exact="true"/>
        <do_if value="not global.$GT_CacheDumpState? or not global.$GT_CacheDumpState.$Active? or not global.$GT_CacheDumpState.$Active">
          <set_value name="$proceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>

        <do_if value="$proceed and global.$GT_CacheDumpState.$Cancel">
          <set_value name="global.$GT_CacheDumpState.$Active" exact="false"/>
          <debug_text text="'[GT-Cache-Dump] CANCELLED after lines=' + global.$GT_CacheDumpState.$Lines" chance="100"/>
          <show_notification text="'[GT] Cache dump cancelled.'" timeout="4s"/>
          <set_value name="$proceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>

        <do_if value="$proceed">
        <set_value name="$maxLinesPerTick" exact="40"/>
        <set_value name="$emitted" exact="0"/>

        <do_while value="$emitted lt $maxLinesPerTick and global.$GT_CacheDumpState.$Active">
          <do_if value="global.$GT_CacheDumpState.$LegacyList">
            <!-- Legacy list-shaped cache -->
            <set_value name="$sectorCache" exact="@global.$GT_TradeCache"/>
            <do_if value="not $sectorCache? or $sectorCache == null or not $sectorCache.count?">
              <set_value name="global.$GT_CacheDumpState.$Active" exact="false"/>
              <break/>
            </do_if>

            <do_if value="not global.$GT_CacheDumpState.$CurrentHomeHeaderPrinted">
              <debug_text text="'[GT-Cache-Dump] HOME [GT_TradeCache legacy list] entries=' + $sectorCache.count" chance="100"/>
              <set_value name="global.$GT_CacheDumpState.$Lines" operation="add"/>
              <set_value name="global.$GT_CacheDumpState.$CurrentHomeHeaderPrinted" exact="true"/>
              <set_value name="$emitted" operation="add"/>
            </do_if>

            <set_value name="$i" exact="global.$GT_CacheDumpState.$EntryIndex"/>
            <do_if value="$i gt $sectorCache.count">
              <set_value name="global.$GT_CacheDumpState.$Active" exact="false"/>
              <break/>
            </do_if>

            <set_value name="$e" exact="$sectorCache.{$i}"/>
            <set_value name="global.$GT_CacheDumpState.$EntryIndex" operation="add"/>
          </do_if>
          <do_else>
            <!-- Normal shape: per-home-sector lists -->
            <set_value name="$homeKeys" exact="@global.$GT_CacheDumpState.$HomeKeys"/>
            <set_value name="$hi" exact="global.$GT_CacheDumpState.$HomeIndex"/>

            <do_if value="not $homeKeys? or $homeKeys == null or $hi gt $homeKeys.count">
              <set_value name="global.$GT_CacheDumpState.$Active" exact="false"/>
              <break/>
            </do_if>

            <set_value name="$home" exact="$homeKeys.{$hi}"/>
            <set_value name="$sectorCache" exact="@global.$GT_TradeCache.{$home}"/>
            <do_if value="$sectorCache == null or not $sectorCache.count? or $sectorCache.count le 0">
              <!-- Move to next home -->
              <set_value name="global.$GT_CacheDumpState.$HomeIndex" operation="add"/>
              <set_value name="global.$GT_CacheDumpState.$EntryIndex" exact="1"/>
              <set_value name="global.$GT_CacheDumpState.$CurrentHomeHeaderPrinted" exact="false"/>
              <continue/>
            </do_if>

            <do_if value="not global.$GT_CacheDumpState.$CurrentHomeHeaderPrinted">
              <set_value name="$homeName" exact="@$home.knownname"/>
              <do_if value="not $homeName?">
                <set_value name="$homeName" exact="'[unknown home sector]'"/>
              </do_if>
              <debug_text text="'[GT-Cache-Dump] HOME ' + $homeName + ' entries=' + $sectorCache.count" chance="100"/>
              <set_value name="global.$GT_CacheDumpState.$Lines" operation="add"/>
              <set_value name="global.$GT_CacheDumpState.$CurrentHomeHeaderPrinted" exact="true"/>
              <set_value name="$emitted" operation="add"/>
            </do_if>

            <set_value name="$i" exact="global.$GT_CacheDumpState.$EntryIndex"/>
            <do_if value="$i gt $sectorCache.count">
              <!-- Next home -->
              <set_value name="global.$GT_CacheDumpState.$HomeIndex" operation="add"/>
              <set_value name="global.$GT_CacheDumpState.$EntryIndex" exact="1"/>
              <set_value name="global.$GT_CacheDumpState.$CurrentHomeHeaderPrinted" exact="false"/>
              <continue/>
            </do_if>

            <set_value name="$e" exact="$sectorCache.{$i}"/>
            <set_value name="global.$GT_CacheDumpState.$EntryIndex" operation="add"/>
          </do_else>

          <!-- Dump entry (best-effort safe reads) -->
          <do_if value="$e != null">
            <set_value name="$buyOffer" exact="@$e.$BuyOffer"/>
            <set_value name="$sellOffer" exact="@$e.$SellOffer"/>
            <set_value name="$amount" exact="@$e.$Amount"/>
            <do_if value="$amount == null">
              <set_value name="$amount" exact="0"/>
            </do_if>

            <set_value name="$buyPriceRaw" exact="@$e.$BuyPrice"/>
            <do_if value="$buyPriceRaw == null">
              <set_value name="$buyPriceRaw" exact="0"/>
            </do_if>
            <set_value name="$sellPriceRaw" exact="@$e.$SellPrice"/>
            <do_if value="$sellPriceRaw == null">
              <set_value name="$sellPriceRaw" exact="0"/>
            </do_if>
            <set_value name="$score" exact="@$e.$Score"/>
            <do_if value="$score == null">
              <set_value name="$score" exact="0"/>
            </do_if>

            <set_value name="$failCount" exact="@$e.$FailCount"/>
            <do_if value="$failCount == null">
              <set_value name="$failCount" exact="0"/>
            </do_if>
            <set_value name="$failedShips" exact="@$e.$FailedShips"/>
            <set_value name="$failedShipsCount" exact="0"/>
            <do_if value="$failedShips != null and $failedShips.count?">
              <set_value name="$failedShipsCount" exact="$failedShips.count"/>
            </do_if>

            <set_value name="$dockShip" exact="@global.$GT_CacheDumpState.$DockShip"/>
            <set_value name="$buyDockOk" exact="null"/>
            <set_value name="$sellDockOk" exact="null"/>
            <do_if value="$dockShip? and $dockShip != null and $dockShip.exists and $buyOffer != null and $sellOffer != null">
              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$buyDockCheck">
                <param name="station" value="$buyOffer.owner"/>
                <param name="ship" value="$dockShip"/>
                <param name="purpose" value="'trade'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$sellDockCheck">
                <param name="station" value="$sellOffer.owner"/>
                <param name="ship" value="$dockShip"/>
                <param name="purpose" value="'trade'"/>
              </run_actions>
              <set_value name="$buyDockOk" exact="$buyDockCheck.$CanDock"/>
              <set_value name="$sellDockOk" exact="$sellDockCheck.$CanDock"/>
            </do_if>

            <set_value name="$wareObj" exact="@$buyOffer.ware"/>
            <set_value name="$wareName" exact="if $e.$WareName? then $e.$WareName else @$wareObj.name"/>
            <do_if value="not $wareName?">
              <set_value name="$wareName" exact="'[unknown ware]'"/>
            </do_if>

            <set_value name="$roi" exact="@$e.$ROI"/>
            <do_if value="$roi == null">
              <set_value name="$roi" exact="-1"/>
            </do_if>

            <set_value name="$profit" exact="@$e.$Profit"/>
            <do_if value="$profit == null">
              <set_value name="$profit" exact="0"/>
            </do_if>

            <set_value name="$dist" exact="@$e.$Distance"/>
            <do_if value="$dist == null">
              <set_value name="$dist" exact="-1"/>
            </do_if>

            <set_value name="$age" exact="-1"/>
            <do_if value="$e.$Timestamp? and $e.$Timestamp != null">
              <set_value name="$age" exact="(player.age - $e.$Timestamp) / 1"/>
            </do_if>

            <set_value name="$buyName" exact="@$buyOffer.owner.knownname"/>
            <do_if value="not $buyName?">
              <set_value name="$buyName" exact="'[unknown buy]'"/>
            </do_if>
            <set_value name="$sellName" exact="@$sellOffer.owner.knownname"/>
            <do_if value="not $sellName?">
              <set_value name="$sellName" exact="'[unknown sell]'"/>
            </do_if>

            <debug_text text="'[GT-Cache-Dump]  ' + ($i / 1) +
              ' ware=' + $wareName +
              ' amount=' + $amount +
              ' buyP=' + ($buyPriceRaw / 100) + 'Cr' +
              ' sellP=' + ($sellPriceRaw / 100) + 'Cr' +
              ' roi=' + ($roi / 1) + '%' +
              ' profit=' + ($profit / 100) + 'Cr' +
              ' score=' + $score +
              ' dist=' + $dist +
              ' age=' + $age + 's' +
              ' fail=' + $failCount +
              ' failedShips=' + $failedShipsCount +
              ' dock=' + (if $buyDockOk? then $buyDockOk else 'n/a') + '/' + (if $sellDockOk? then $sellDockOk else 'n/a') +
              ' buy=' + $buyName +
              ' sell=' + $sellName" chance="100"/>
            <set_value name="global.$GT_CacheDumpState.$Lines" operation="add"/>
            <set_value name="$emitted" operation="add"/>
          </do_if>
        </do_while>

        <do_if value="not global.$GT_CacheDumpState.$Active">
          <set_value name="$dur" exact="player.age - global.$GT_CacheDumpState.$StartedAt"/>
          <debug_text text="'[GT-Cache-Dump] END lines=' + global.$GT_CacheDumpState.$Lines + ' durationMs=' + ($dur / 1ms)" chance="100"/>
          <show_notification text="'[GT] Cache dump finished. (lines=' + global.$GT_CacheDumpState.$Lines + ')'" timeout="6s" priority="5"/>
          <cancel_cue cue="this"/>
        </do_if>

        <!-- Continue next chunk -->
        <do_if value="global.$GT_CacheDumpState? and global.$GT_CacheDumpState.$Active? and global.$GT_CacheDumpState.$Active">
          <signal_cue_instantly cue="GT_DumpTradeCache_Process"/>
        </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Release All Search Locks Button Handler -->
    <cue name="GT_ReleaseAllLocks" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Release All Locks button clicked'" chance="100"/>
        </do_if>

        <set_value name="$released" exact="0"/>
        <do_if value="global.$GT_SearchLocks? and global.$GT_SearchLocks.keys.count gt 0">
          <!-- Snapshot keys list; releasing locks mutates the table -->
          <set_value name="$lockKeys" exact="global.$GT_SearchLocks.keys.list"/>
          <do_all exact="$lockKeys.count" counter="$i">
            <set_value name="$ship" exact="$lockKeys.{$i}"/>
            <!-- stale_lock_cleanup triggers deep cleanup in GT_RequestRegistry_Release (live/batch queues, slice state, cooldowns) -->
            <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'stale_lock_cleanup'"/>
            </run_actions>

            <!-- Also clear scheduler active marker for this ship, if present -->
            <do_if value="global.$GT_Scheduler? and global.$GT_Scheduler.$ActiveWork? and global.$GT_Scheduler.$ActiveWork.{$ship}?">
              <remove_value name="global.$GT_Scheduler.$ActiveWork.{$ship}"/>
            </do_if>

            <set_value name="$released" operation="add"/>
          </do_all>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Release All Locks complete: released=' + $released" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- Clear Fleet Reservations Button Handler -->
    <cue name="GT_ClearReservations" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$cleared" exact="0"/>
        
        <do_if value="global.$GT_Reservations? and typeof global.$GT_Reservations == datatype.table">
          <set_value name="$cleared" exact="global.$GT_Reservations.keys.count"/>
          <set_value name="global.$GT_Reservations" exact="table[]"/>
        </do_if>
        
        <!-- Reset reservation stats -->
        <do_if value="global.$GT_ReservationStats?">
          <set_value name="global.$GT_ReservationStats.$Active" exact="0"/>
          <set_value name="global.$GT_ReservationStats.$Cleared" operation="add" exact="$cleared"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Clear Reservations: removed ' + $cleared + ' fleet trade reservations'" chance="100"/>
        </do_if>
        
        <show_notification text="'[GT] Cleared ' + $cleared + ' fleet trade reservations'" timeout="5s" priority="5"/>
      </actions>
    </cue>

    <!-- Dump Trade Hub Status Button Handler -->
    <!-- On-demand snapshot: scheduler queue/work + per-ship hub request status (and last requester) -->
    <cue name="GT_DumpTradeHubStatus" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$cacheQueue" exact="if global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$CacheQueue? then global.$GT_SearchSemaphore.$CacheQueue.count else 0"/>
        <set_value name="$liveQueue" exact="if global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveQueued? then global.$GT_SearchSemaphore.$LiveQueued.keys.count else 0"/>
        <set_value name="$tsQueue" exact="$cacheQueue + $liveQueue"/>
        <set_value name="$workQueue" exact="if global.$GT_Scheduler? and global.$GT_Scheduler.$WorkQueue? then global.$GT_Scheduler.$WorkQueue.count else 0"/>
        <set_value name="$activeWork" exact="if global.$GT_Scheduler? and global.$GT_Scheduler.$ActiveWork? then global.$GT_Scheduler.$ActiveWork.keys.count else 0"/>
        <set_value name="$statusCount" exact="if global.$GT_RequestStatus? then global.$GT_RequestStatus.keys.count else 0"/>

        <!-- Build a compact summary and show to player -->
        <set_value name="$msg" exact="'[GT] Trade Hub Snapshot\n'"/>
        <set_value name="$msg" exact="$msg + 'Queue: cache=' + $cacheQueue + ' live=' + $liveQueue + ' total=' + $tsQueue + ' | WorkQueue: ' + $workQueue + ' | ActiveWork: ' + $activeWork + '\n'"/>
        <set_value name="$msg" exact="$msg + 'RequestStatus entries: ' + $statusCount + '\n'"/>

        <!-- Cache coverage summary (matchable wares coverage).
             Goal: quickly validate that the cache is being filled broadly (many wares) and deeply (enough entries/ware),
             without flooding the log like the full cache dump. -->
        <set_value name="$cacheTotal" exact="0"/>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CalculateTotalCacheCount" result="$cacheTotal"/>
        <set_value name="$cacheHomes" exact="0"/>
        <set_value name="$homeKeys" exact="[]"/>
        <!-- Prefer homes registry only if it exists AND is non-empty; otherwise fall back to GT_TradeCache.keys. -->
        <do_if value="global.$GT_TradeCacheHomes? and global.$GT_TradeCacheHomes != null and typeof global.$GT_TradeCacheHomes == datatype.list and global.$GT_TradeCacheHomes.count gt 0">
          <set_value name="$homeKeys" exact="@global.$GT_TradeCacheHomes"/>
        </do_if>
        <do_else>
          <do_if value="global.$GT_TradeCache?">
            <set_value name="$cacheObj" exact="@global.$GT_TradeCache"/>
            <set_value name="$homeKeys" exact="@$cacheObj.keys"/>
            <do_if value="$homeKeys == null">
              <set_value name="$homeKeys" exact="[]"/>
            </do_if>
          </do_if>
        </do_else>
        <set_value name="$cacheHomes" exact="$homeKeys.count"/>

        <set_value name="$targetPerWare" exact="20"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
          <set_value name="$targetPerWare" exact="@global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare"/>
        </do_if>
        <do_if value="$targetPerWare lt 1">
          <set_value name="$targetPerWare" exact="1"/>
        </do_if>

        <set_value name="$msg" exact="$msg + 'Cache: total=' + $cacheTotal + ' homes=' + $cacheHomes + ' targetPerWare=' + $targetPerWare + '\n'"/>

        <do_if value="$cacheHomes gt 0 and global.$GT_TradeCache?">
          <set_value name="$maxHomesToShow" exact="5"/>
          <set_value name="$homesShown" exact="0"/>
          <do_all exact="$homeKeys.count" counter="$hk">
            <do_if value="$homesShown ge $maxHomesToShow">
              <break/>
            </do_if>
            <set_value name="$home" exact="$homeKeys.{$hk}"/>
            <set_value name="$sectorCache" exact="@global.$GT_TradeCache.{$home}"/>
            <do_if value="$sectorCache == null or not $sectorCache.count?">
              <continue/>
            </do_if>
            <set_value name="$homesShown" operation="add"/>

            <set_value name="$homeName" exact="@$home.knownname"/>
            <do_if value="not $homeName?">
              <set_value name="$homeName" exact="'[unknown home]'"/>
            </do_if>

            <!-- Build per-ware counts (by ware name) -->
            <set_value name="$wareSummary" exact="[]"/>
            <set_value name="$scanLimit" exact="2000"/>
            <set_value name="$scanCount" exact="[$sectorCache.count, $scanLimit].min"/>
            <do_all exact="$scanCount" counter="$ci">
              <set_value name="$e" exact="$sectorCache.{$ci}"/>
              <do_if value="$e == null">
                <continue/>
              </do_if>
              <set_value name="$wareObj" exact="@$e.$BuyOffer.ware"/>
              <set_value name="$wareName" exact="if $e.$WareName? then $e.$WareName else @$wareObj.name"/>
              <do_if value="not $wareName?">
                <set_value name="$wareName" exact="'[unknown ware]'"/>
              </do_if>
              <set_value name="$found" exact="false"/>
              <do_all exact="$wareSummary.count" counter="$wi">
                <do_if value="$wareSummary.{$wi}.$WareName == $wareName">
                  <set_value name="$wareSummary.{$wi}.$Count" exact="$wareSummary.{$wi}.$Count + 1"/>
                  <set_value name="$found" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="not $found">
                <append_to_list name="$wareSummary" exact="table[$WareName = $wareName, $Count = 1]"/>
              </do_if>
            </do_all>

            <set_value name="$distinctWares" exact="$wareSummary.count"/>
            <set_value name="$underfilled" exact="0"/>
            <set_value name="$underList" exact="''"/>
            <set_value name="$underShown" exact="0"/>
            <do_all exact="$wareSummary.count" counter="$wi">
              <set_value name="$row" exact="$wareSummary.{$wi}"/>
              <set_value name="$c" exact="if $row.$Count? then $row.$Count else 0"/>
              <do_if value="$c lt $targetPerWare">
                <set_value name="$underfilled" exact="$underfilled + 1"/>
                <do_if value="$underShown lt 8">
                  <set_value name="$underList" exact="$underList + (if $row.$WareName? then $row.$WareName else 'unknown') + '(' + $c + ') '"/>
                  <set_value name="$underShown" operation="add"/>
                </do_if>
              </do_if>
            </do_all>

            <set_value name="$msg" exact="$msg + '  HOME ' + $homeName + ': entries=' + $sectorCache.count + ' distinctWares=' + $distinctWares + ' underfilled=' + $underfilled"/>
            <do_if value="$underfilled gt 0">
              <set_value name="$msg" exact="$msg + ' sample=' + $underList"/>
            </do_if>
            <set_value name="$msg" exact="$msg + '\n'"/>
          </do_all>
        </do_if>

        <!-- Stage histogram (on-demand only).
             IMPORTANT: MD does not support dynamic table keys in set_value name="$table.{$key}".
             Use a list of rows ([$Stage,$Count]) instead. -->
        <set_value name="$stageCounts" exact="[]"/>
        <do_if value="global.$GT_RequestStatus? and global.$GT_RequestStatus.keys.count gt 0">
          <set_value name="$keys" exact="global.$GT_RequestStatus.keys.list"/>
          <set_value name="$maxScan" exact="200"/>
          <set_value name="$scan" exact="[$keys.count, $maxScan].min"/>
          <do_all exact="$scan" counter="$i">
            <set_value name="$ship" exact="$keys.{$i}"/>
            <set_value name="$st" exact="if global.$GT_RequestStatus.{$ship}? and global.$GT_RequestStatus.{$ship}.$Stage? then global.$GT_RequestStatus.{$ship}.$Stage else 'unknown'"/>
            <set_value name="$foundStage" exact="false"/>
            <do_all exact="$stageCounts.count" counter="$si">
              <do_if value="$stageCounts.{$si}? and $stageCounts.{$si}.$Stage? and $stageCounts.{$si}.$Stage == $st">
                <set_value name="$stageCounts.{$si}.$Count" exact="if $stageCounts.{$si}.$Count? then ($stageCounts.{$si}.$Count + 1) else 1"/>
                <set_value name="$foundStage" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $foundStage">
              <append_to_list name="$stageCounts" exact="table[$Stage = $st, $Count = 1]"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$stageCounts.count gt 0">
          <set_value name="$msg" exact="$msg + 'Stages (sample up to 200): '"/>
          <set_value name="$shown" exact="0"/>
          <do_all exact="$stageCounts.count" counter="$k">
            <do_if value="$shown lt 8">
              <set_value name="$row" exact="$stageCounts.{$k}"/>
              <set_value name="$msg" exact="$msg + (if $row.$Stage? then $row.$Stage else 'unknown') + '=' + (if $row.$Count? then $row.$Count else 0) + ' '"/>
              <set_value name="$shown" operation="add"/>
            </do_if>
          </do_all>
          <set_value name="$msg" exact="$msg + '\n'"/>
        </do_if>

        <!-- Last requester details (if available) -->
        <set_value name="$lastShip" exact="@global.$GT_LastTradeRequestShip"/>
        <do_if value="$lastShip? and $lastShip.exists">
          <set_value name="$msg" exact="$msg + 'LastRequest: ' + $lastShip.idcode + ' @ ' + (if global.$GT_LastTradeRequestTime? then global.$GT_LastTradeRequestTime else 0) + '\n'"/>
          <do_if value="global.$GT_RequestStatus? and global.$GT_RequestStatus.{$lastShip}?">
            <set_value name="$st" exact="if global.$GT_RequestStatus.{$lastShip}.$Stage? then global.$GT_RequestStatus.{$lastShip}.$Stage else 'unknown'"/>
            <set_value name="$state" exact="if global.$GT_RequestStatus.{$lastShip}.$State? then global.$GT_RequestStatus.{$lastShip}.$State else 'unknown'"/>
            <set_value name="$reason" exact="if global.$GT_RequestStatus.{$lastShip}.$Reason? then global.$GT_RequestStatus.{$lastShip}.$Reason else ''"/>
            <set_value name="$trace" exact="if global.$GT_RequestStatus.{$lastShip}.$TraceId? then global.$GT_RequestStatus.{$lastShip}.$TraceId else ''"/>
            <set_value name="$msg" exact="$msg + '  Status: ' + $st + '/' + $state + ' reason=' + $reason + ' trace=' + $trace + '\n'"/>
          </do_if>
          <do_else>
            <set_value name="$msg" exact="$msg + '  Status: (no GT_RequestStatus entry)\n'"/>
          </do_else>
          <do_if value="global.$GT_SearchSemaphore? and ((global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$lastShip}?) or (global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$lastShip}?))">
            <set_value name="$msg" exact="$msg + '  SchedulerQueue: queued=true\n'"/>
          </do_if>
        </do_if>

        <show_notification text="$msg" timeout="10s" priority="5"/>

        <!-- Always print to debug log for on-demand diagnostics (button-triggered, not periodic). -->
        <debug_text text="$msg" chance="100"/>
      </actions>
    </cue>

    <!-- Dump fallback activation counters -->
    <cue name="GT_DumpFallbackActivations" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$msg" exact="'[GT] Fallback activations:\n'"/>
        <set_value name="$total" exact="0"/>
        <set_value name="$keys" exact="[]"/>
        <set_value name="$shown" exact="0"/>
        <set_value name="$maxShown" exact="12"/>

        <do_if value="global.$GT_FallbackActivations? and typeof global.$GT_FallbackActivations == datatype.table">
          <set_value name="$faObj" exact="@global.$GT_FallbackActivations"/>
          <set_value name="$keys" exact="@$faObj.keys"/>
          <do_if value="$keys == null">
            <set_value name="$keys" exact="[]"/>
          </do_if>
        </do_if>

        <do_if value="$keys.count gt 0">
          <do_all exact="$keys.count" counter="$i">
            <set_value name="$k" exact="$keys.{$i}"/>
            <set_value name="$v" exact="if global.$GT_FallbackActivations.{$k}? then global.$GT_FallbackActivations.{$k} else 0"/>
            <set_value name="$total" exact="$total + $v"/>
            <do_if value="$shown lt $maxShown">
              <set_value name="$msg" exact="$msg + '  ' + $k + ' = ' + $v + '\n'"/>
              <set_value name="$shown" operation="add"/>
            </do_if>
          </do_all>
          <do_if value="$keys.count gt $maxShown">
            <set_value name="$msg" exact="$msg + '  ... +' + ($keys.count - $maxShown) + ' more keys (see log)\n'"/>
          </do_if>
          <set_value name="$msg" exact="$msg + 'keys=' + $keys.count + ' total=' + $total"/>
        </do_if>
        <do_else>
          <set_value name="$msg" exact="$msg + '  none\nkeys=0 total=0'"/>
        </do_else>

        <show_notification text="$msg" timeout="10s" priority="5"/>
        <debug_text text="$msg" chance="100"/>
      </actions>
    </cue>
    
    <!-- Price Range Update Handler (converts percentage to normalized value for GT_Config) -->
    <cue name="GT_PriceRange_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] PriceRangeUpdate called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Simple Menu API passes a table with $value (percentage -100 to +100) and $echo -->
            <set_value name="$percentageValue" exact="null"/>
            <set_value name="$section" exact="null"/>
            <set_value name="$setting" exact="null"/>
            
            <!-- Get the percentage value from $value -->
            <do_if value="event.param.$value?">
              <set_value name="$percentageValue" exact="event.param.$value"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Price range percentage value: ' + $percentageValue + '%'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Get the echo data from $echo -->
            <do_if value="event.param.$echo? and event.param.$echo.$section? and event.param.$echo.$setting?">
              <set_value name="$section" exact="event.param.$echo.$section"/>
              <set_value name="$setting" exact="event.param.$echo.$setting"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Echo data - Section: ' + $section + ', Setting: ' + $setting" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Convert percentage to normalized value and update GT_Config -->
            <do_if value="$percentageValue? and $section and $setting">
              <!-- Convert percentage (-100 to +100) to normalized (-1.0 to +1.0) -->
              <set_value name="$normalizedValue" exact="$percentageValue / 100"/>
              
              <!-- Ensure GT_Config.$Trading exists -->
              <do_if value="not global.$GT_Config?">
                <set_value name="global.$GT_Config" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Config.$Trading?">
                <set_value name="global.$GT_Config.$Trading" exact="table[]"/>
              </do_if>
              
              <!-- Update the setting in GT_Config.$Trading -->
              <set_value name="global.$GT_Config.$Trading.{$setting}" exact="$normalizedValue"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Price range updated: GT_Config.$Trading.' + $setting + ' = ' + $normalizedValue + ' (' + $percentageValue + '%)'" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] ERROR: Missing required parameters for price range update'" chance="100"/>
              </do_if>
            </do_else>
      </actions>
    </cue>

    <!-- Trading MinAbsoluteProfit Base Update Handler (Cr slider -> RAW centicredits in GT_Config) -->
    <cue name="GT_MinProfitBase_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$newValue" exact="null"/>
        <set_value name="$section" exact="null"/>
        <set_value name="$setting" exact="null"/>
        <do_if value="event.param.$value?">
          <set_value name="$newValue" exact="event.param.$value"/>
        </do_if>
        <do_if value="event.param.$echo? and event.param.$echo.$section? and event.param.$echo.$setting?">
          <set_value name="$section" exact="event.param.$echo.$section"/>
          <set_value name="$setting" exact="event.param.$echo.$setting"/>
        </do_if>

        <!-- Slider value is in Cr, range 0..500; store in RAW centicredits -->
        <do_if value="$newValue? and $newValue != null and $section == '$Trading' and $setting == '$MinAbsoluteProfit'">
          <set_value name="$clamped" exact="[$newValue, 0].max"/>
          <set_value name="$clamped" exact="[$clamped, 500].min"/>
          <set_value name="$raw" exact="$clamped * 100"/>

          <do_if value="not global.$GT_Config?">
            <set_value name="global.$GT_Config" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Config.$Trading?">
            <set_value name="global.$GT_Config.$Trading" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Config.$Trading.$MinAbsoluteProfit" exact="$raw"/>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Settings] Updated GT_Config.$Trading.$MinAbsoluteProfit base = ' + $clamped + ' Cr (' + $raw + ' RAW)'" chance="100"/>
          </do_if>

          <!-- NOTE: Do NOT call Refresh_Menu here â€” it destroys and recreates the slider mid-interaction,
               causing widget_fullscreen.lua to access a destroyed slidercellElement (nil crash).
               The slider already displays the correct value; no refresh needed (consistent with GT_PriceRange_Update). -->
        </do_if>
      </actions>
    </cue>

    <!-- Ship Proximity Weight Update Handler (slider 0-100 -> weight 0.0-1.0 in GT_GlobalSettings.$Trading) -->
    <cue name="GT_ShipProximityWeight_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$newValue" exact="null"/>
        <set_value name="$section" exact="null"/>
        <set_value name="$setting" exact="null"/>
        <do_if value="event.param.$value?">
          <set_value name="$newValue" exact="event.param.$value"/>
        </do_if>
        <do_if value="event.param.$echo? and event.param.$echo.$section? and event.param.$echo.$setting?">
          <set_value name="$section" exact="event.param.$echo.$section"/>
          <set_value name="$setting" exact="event.param.$echo.$setting"/>
        </do_if>
        <do_if value="$newValue? and $newValue != null and $section == '$Trading' and $setting == '$ShipProximityWeight'">
          <set_value name="$clamped" exact="[$newValue, 0].max"/>
          <set_value name="$clamped" exact="[$clamped, 100].min"/>
          <set_value name="$weight" exact="$clamped / 100.0"/>
          <do_if value="not global.$GT_GlobalSettings.$Trading?">
            <set_value name="global.$GT_GlobalSettings.$Trading" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="$weight"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Settings] Updated GT_GlobalSettings.$Trading.$ShipProximityWeight = ' + $weight + ' (slider ' + $clamped + ')'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Clear Pilot Renaming Button Handler -->
    <cue name="GT_ClearPilotRenaming" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$restoredCount" exact="0"/>
        <set_value name="$pilotsProcessed" exact="0"/>

        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$i">
            <set_value name="$pilot" exact="$pilotKeys.{$i}"/>
            <set_value name="$pilotsProcessed" operation="add"/>
            <do_if value="$pilot? and $pilot.exists">
              <set_value name="$restoreName" exact="null"/>
              <do_if value="global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalPilotName? and global.$GT_Pilots.{$pilot}.$OriginalPilotName != ''">
                <set_value name="$restoreName" exact="global.$GT_Pilots.{$pilot}.$OriginalPilotName"/>
              </do_if>
              <do_elseif value="global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$PilotName? and global.$GT_Pilots.{$pilot}.$PilotName != ''">
                <set_value name="$restoreName" exact="global.$GT_Pilots.{$pilot}.$PilotName"/>
              </do_elseif>
              <do_else>
                <set_value name="$restoreName" exact="$pilot.name"/>
              </do_else>

              <do_if value="$restoreName? and $restoreName != ''">
                <set_object_name object="$pilot" name="$restoreName"/>
                <set_value name="$restoredCount" operation="add"/>
                <!-- Keep both registry names aligned to plain vanilla baseline -->
                <do_if value="global.$GT_Pilots.{$pilot}?">
                  <set_value name="global.$GT_Pilots.{$pilot}.$PilotName" exact="$restoreName"/>
                  <set_value name="global.$GT_Pilots.{$pilot}.$OriginalPilotName" exact="$restoreName"/>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Clear Pilot Renaming: restored=' + $restoredCount + ' processed=' + $pilotsProcessed" chance="100"/>
        </do_if>
        <show_notification text="'[GT] Restored pilot names: ' + $restoredCount" timeout="5s" priority="5"/>
      </actions>
    </cue>

    <!-- Apply Pilot Renaming to all registered GT pilots (instant toggle-on effect) -->
    <cue name="GT_ApplyPilotRenamingAll" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$updatedCount" exact="0"/>
        <set_value name="$pilotsProcessed" exact="0"/>

        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$i">
            <set_value name="$pilot" exact="$pilotKeys.{$i}"/>
            <set_value name="$pilotsProcessed" operation="add"/>
            <do_if value="$pilot? and $pilot.exists">
              <run_actions ref="md.GT_Ship_Management.Update_Pilot_Name_Tag" result="$tagResult">
                <param name="pilot" value="$pilot"/>
              </run_actions>
              <do_if value="$tagResult">
                <set_value name="$updatedCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Apply Pilot Renaming: updated=' + $updatedCount + ' processed=' + $pilotsProcessed" chance="100"/>
        </do_if>
        <show_notification text="'[GT] Pilot renaming applied: ' + $updatedCount" timeout="5s" priority="5"/>
      </actions>
    </cue>
    
    <!-- Slider Value Update Handler -->
    <!-- Reset Profit Statistics Button Handler -->
    <cue name="GT_ResetProfitStats" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Reset Profit Statistics button clicked - triggering migration'" chance="100"/>
        </do_if>
        
        <!-- Trigger the profit statistics reset -->
        <signal_cue_instantly cue="md.GT_Profit_Migration.ResetInflatedProfitStats"/>
        
        <!-- Refresh the menu -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>
    
    <!-- Clear All Blacklisted Sectors Button Handler -->
    <cue name="GT_ClearAllBlacklistedSectors" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Clear All Blacklisted Sectors button clicked'" chance="100"/>
        </do_if>
        
        <run_actions ref="md.GT_ThreatIntelligence.ClearAllThreatBlacklistData" result="$clearResult">
          <param name="Reason" value="'settings_menu'"/>
          <param name="RefreshFleetBlacklist" value="true"/>
          <param name="DebugChance" value="100"/>
        </run_actions>
        <set_value name="$sectorCount" exact="$clearResult.$ClearedCount"/>
        
        <!-- Show notification to player -->
        <do_if value="$sectorCount gt 0">
          <show_notification text="'Cleared ' + $sectorCount + ' blacklisted sectors'" timeout="5s"/>
        </do_if>
        <do_else>
          <show_notification text="'No blacklisted sectors to clear'" timeout="3s"/>
        </do_else>
        
        <!-- Refresh the menu -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>
    
    <!-- Reset All Settings to Defaults Button Handler -->
    <cue name="GT_ResetAllSettings" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Reset All Settings to Defaults button clicked'" chance="100"/>
        </do_if>
        
        <!-- Reset all global settings to defaults by re-running initialization logic -->
        <!-- XP and Training Settings -->
        <set_value name="global.$GT_GlobalSettings.$XP" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$AutoTraining" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$XPMultiplier" exact="100"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$MinTrainingDistance" exact="5"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$TrainingCooldown" exact="600s"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" exact="10"/>
        <set_value name="global.$GT_GlobalSettings.$XP.$HardForceTraining" exact="true"/>
        
        <!-- Fleet Coordination Settings -->
        <set_value name="global.$GT_GlobalSettings.$Fleet" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance" exact="15"/>
        <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheTTL" exact="300s"/>
        <set_value name="global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney" exact="1000"/>
        <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="1"/>
        
        <!-- Notification Settings -->
        <set_value name="global.$GT_GlobalSettings.$Notifications" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Notifications.$ShowXPGains" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$Notifications.$ShowTradeResults" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$Notifications.$ShowFleetStatus" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency" exact="1"/>
        <set_value name="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" exact="30"/>
        <do_if value="not global.$GT_Config?">
          <set_value name="global.$GT_Config" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Config.$Notifications?">
          <set_value name="global.$GT_Config.$Notifications" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Config.$Notifications.$LevelUp" exact="true"/>
        <set_value name="global.$GT_Config.$Notifications.$TrainingRequired" exact="true"/>
        <set_value name="global.$GT_Config.$Notifications.$TrainingCompleted" exact="true"/>
        <set_value name="global.$GT_Config.$Notifications.$ProfitReports" exact="true"/>
        <set_value name="global.$GT_Config.$Notifications.$MarketAlerts" exact="true"/>
        <set_value name="global.$GT_Config.$Notifications.$FleetUpdates" exact="false"/>
        
        <!-- Mobile Satellite Intelligence Settings -->
        <set_value name="global.$GT_GlobalSettings.$MobileIntel" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$MobileIntel.$Enable" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration" exact="10min"/>
        <set_value name="global.$GT_GlobalSettings.$MobileIntel.$StationCooldown" exact="60s"/>
        
        <!-- Threat Avoidance Settings -->
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$ScanInterval" exact="5s"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry" exact="600s"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$HostileRelationThreshold" exact="-0.20"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold" exact="3"/>
        
        <!-- Debug Settings (reset to false by default) -->
        <set_value name="global.$GT_GlobalSettings.$Debug" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$Debug.$DebugLevel" exact="1"/>
        <set_value name="global.$GT_GlobalSettings.$Debug.$TradeEvaluation" exact="false"/>
        
        <!-- Ship Naming Settings -->
        <set_value name="global.$GT_GlobalSettings.$ShipNaming" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$Enabled" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayXP" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$XPPosition" exact="'suffix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayRank" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$RankPosition" exact="'suffix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$LevelPosition" exact="'suffix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StatusPosition" exact="'prefix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayOperationalState" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$OperationalStatePosition" exact="'prefix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition" exact="'suffix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource" exact="'macro.name'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamingMode" exact="'legacy'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamePattern" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition" exact="'prefix'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Resupply" exact="'RS'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Repair" exact="'RP'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Maintenance" exact="'MT'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Training" exact="'TR'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Escape" exact="'ES'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Reroute" exact="'RR'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Clearance" exact="'CL'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Unreachable" exact="'UR'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$PilotExchange" exact="'PE'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Blocked" exact="'BL'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$CustomBlacklist" exact="'CB'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Fallback" exact="'FB'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Isolated" exact="'IS'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Trading" exact="'TD'"/>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Idle" exact="'ID'"/>
        
        <!-- Auto-Repair Settings -->
        <set_value name="global.$GT_GlobalSettings.$AutoRepair" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$AutoRepair.$Enabled" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold" exact="95"/>
        <set_value name="global.$GT_GlobalSettings.$AutoRepair.$MinPilotLevel" exact="12"/>
        
        <!-- Galaxy Miner Settings -->
        <set_value name="global.$GT_GlobalSettings.$Miner" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel" exact="false"/>

        <!-- Trading global settings -->
        <set_value name="global.$GT_GlobalSettings.$Trading" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="0.04"/>
        
        <!-- Ship Modifications Settings -->
        <set_value name="global.$GT_GlobalSettings.$Modifications" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Modifications.$Enabled" exact="false"/>
        <signal_objects object="player.galaxy" param="'GT_Modifications_Settings_Changed'" param2="table[
          $Enabled = false
        ]"/>
        
        <!-- Performance Settings (post AI-migration) -->
        <set_value name="global.$GT_GlobalSettings.$Performance" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches" exact="5"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches" exact="1"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches" exact="1"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn" exact="20"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize" exact="10"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries" exact="50"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare" exact="20"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch" exact="200"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare" exact="20"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching" exact="20"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold" exact="2000"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$SearchLockTTL" exact="600"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval" exact="500"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$BatchChunkSize" exact="5"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay" exact="10"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$AIYieldInterval" exact="1"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize" exact="1"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize" exact="50"/>
        <set_value name="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds" exact="120"/>
        
        <!-- Number Formatting Settings -->
        <set_value name="global.$GT_GlobalSettings.$NumberFormat" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$NumberFormat.$Format" exact="'german'"/>
        <set_value name="global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix" exact="true"/>
        <set_value name="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" exact="999999"/>
        
        <!-- UI Settings -->
        <set_value name="global.$GT_GlobalSettings.$UI" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride" exact="false"/>

        <!-- Cheat Settings -->
        <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
        <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="'off'"/>
        <set_value name="global.$GT_GlobalSettings.$Cheats.$UniverseRevealed" exact="false"/>
        <set_value name="global.$GT_GlobalSettings.$Cheats.$PilotsMaxed" exact="false"/>
        <signal_cue_instantly cue="md.GT_Cheats.GT_Cheat_Reconcile"/>
        
        <!-- Trading Price Range Settings (stored in GT_Config.$Trading) -->
        <do_if value="not global.$GT_Config?">
          <set_value name="global.$GT_Config" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Config.$Trading?">
          <set_value name="global.$GT_Config.$Trading" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Config.$Trading.$MinAbsoluteProfit" exact="10000"/> <!-- 100 Cr in raw centicredits -->
        <set_value name="global.$GT_Config.$Trading.$SellPriceMax" exact="-0.2"/> <!-- Normal: buy below -20% (cheap) -->
        <set_value name="global.$GT_Config.$Trading.$BuyPriceMin" exact="0.2"/> <!-- Normal: sell above +20% (expensive) -->
        <set_value name="global.$GT_Config.$Trading.$IsolatedSellPriceMax" exact="1.0"/> <!-- Isolated: no filter (+100%) -->
        <set_value name="global.$GT_Config.$Trading.$IsolatedBuyPriceMin" exact="-1.0"/> <!-- Isolated: no filter (-100%) -->
        <set_value name="global.$GT_Config.$Trading.$FallbackSellPriceMax" exact="0.2"/> <!-- Fallback: buy up to +20% -->
        <set_value name="global.$GT_Config.$Trading.$FallbackBuyPriceMin" exact="-0.2"/> <!-- Fallback: sell down to -20% -->
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] All global settings reset to defaults'" chance="100"/>
        </do_if>
        
        <signal_cue_instantly cue="GT_SyncUICreditsDueState"/>
        
        <!-- Refresh the menu -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
        
        <!-- Deferred re-apply: Refresh_Menu destruction of old sliders queues stale
             onSliderCellChanged events that overwrite the defaults we just set.
             Re-apply all GT_Config.$Trading values after 1ms so they survive the stale storm. -->
        <signal_cue_instantly cue="GT_ReapplyTradingDefaults"/>
      </actions>
    </cue>
    
    <!-- Deferred re-apply of trading price range defaults after reset.
         Stale slider callbacks from Refresh_Menu fire in the same tick and overwrite
         GT_Config.$Trading values. This cue waits 1ms then forcefully re-sets them. -->
    <cue name="GT_ReapplyTradingDefaults" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <do_if value="not global.$GT_Config?">
          <set_value name="global.$GT_Config" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Config.$Trading?">
          <set_value name="global.$GT_Config.$Trading" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_Config.$Trading.$MinAbsoluteProfit" exact="10000"/>
        <set_value name="global.$GT_Config.$Trading.$SellPriceMax" exact="-0.2"/>
        <set_value name="global.$GT_Config.$Trading.$BuyPriceMin" exact="0.2"/>
        <set_value name="global.$GT_Config.$Trading.$IsolatedSellPriceMax" exact="1.0"/>
        <set_value name="global.$GT_Config.$Trading.$IsolatedBuyPriceMin" exact="-1.0"/>
        <set_value name="global.$GT_Config.$Trading.$FallbackSellPriceMax" exact="0.2"/>
        <set_value name="global.$GT_Config.$Trading.$FallbackBuyPriceMin" exact="-0.2"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Settings] Trading price range defaults re-applied after Refresh_Menu'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Recreate Blacklist Button Handler -->
    <cue name="GT_RecreateBlacklist" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] Manual blacklist recreation requested via menu button'" chance="100"/>
        </do_if>
        
        <!-- Keep track of the old ID (don't clear it until we have a new one) -->
        <set_value name="$oldID" exact="@global.$GT_BlacklistID"/>
        
        <do_if value="$oldID?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] Current stored ID: ' + $oldID + ' (will attempt to recreate)'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] No stored ID found - will create fresh blacklist'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Trigger blacklist recreation by calling dedicated Recreate event -->
        <!-- Only pass relation threshold if BlockEnemyFactions is enabled (default: true) -->
        <set_value name="$blockEnemyFactions" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions"/>
        <do_if value="not $blockEnemyFactions?">
          <set_value name="$blockEnemyFactions" exact="true"/> <!-- Default: enabled -->
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] Recreate: BlockEnemyFactions setting: ' + $blockEnemyFactions" chance="100"/>
        </do_if>
        
        <set_value name="$relationValue" exact="''"/>
        <do_if value="$blockEnemyFactions">
          <set_value name="$relationValue" exact="'enemy'"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] Recreate: Enemy faction blocking ENABLED (X4 relation field = &quot;enemy&quot;)'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] Recreate: Enemy faction blocking DISABLED (X4 relation field = &quot;&quot;)'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Pass relation|0 to force recreation (Lua will reset initialized flag and recreate) -->
        <set_value name="$initData" exact="$relationValue + '|0'"/>
        <raise_lua_event name="'GT_Blacklist.Recreate'" param="$initData"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] Blacklist recreation triggered - StoreBlacklistID cue will update ID when Lua responds'" chance="100"/>
        </do_if>
        
        <!-- Reload existing threats into the newly recreated blacklist -->
        <signal_cue_instantly cue="md.GT_ThreatIntelligence.UpdateBlacklistOnThreat"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] Reloading existing threat data into recreated blacklist'" chance="100"/>
        </do_if>
        
        <!-- Refresh the menu to show any changes -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <!-- Assign blacklist to all GT fleet commanders (manual action) -->
    <cue name="GT_AssignBlacklistToGTShips" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist">
          <!-- One-shot guard consumed by ApplyBlacklistToFleet -->
          <set_value name="global.$GT_ManualBlacklistAssignRequested" exact="true"/>
          <!-- Rebuild current blacklist payload before applying to fleet -->
          <signal_cue_instantly cue="md.GT_ThreatIntelligence.UpdateBlacklistOnThreat"/>
          <signal_cue_instantly cue="md.GT_ThreatIntelligence.ApplyBlacklistToFleet"/>
          <show_notification text="'Assigned dynamic blacklist to GT fleet commanders'" timeout="4s"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_ManualBlacklistAssignRequested" exact="false"/>
          <show_notification text="'Enable Use Dynamic Blacklist first'" timeout="4s"/>
        </do_else>

        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>
    
    <cue name="GT_Slider_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <!-- Debug: Print the entire event parameter structure -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] UpdateSliderValue called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Simple Menu API passes a table with $value and $echo -->
            <set_value name="$newValue" exact="null"/>
            <set_value name="$section" exact="null"/>
            <set_value name="$setting" exact="null"/>
            
            <!-- Get the new slider value â€” X4 treats 0 as null/falsy; gate on callback event, not value truthiness -->
            <set_value name="$sliderEvent" exact="false"/>
            <do_if value="event.param.$event == 'onSliderCellChanged'">
              <set_value name="$sliderEvent" exact="true"/>
              <set_value name="$newValue" exact="event.param.$value"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Slider new value: ' + $newValue" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Get the echo data from $echo -->
            <do_if value="event.param.$echo? and event.param.$echo.$section? and event.param.$echo.$setting?">
              <set_value name="$section" exact="event.param.$echo.$section"/>
              <set_value name="$setting" exact="event.param.$echo.$setting"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Echo data - Section: ' + $section + ', Setting: ' + $setting" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Update the setting if we have all required data -->
            <!-- Gate on slider callback event â€” 0 is valid but falsy for ? and equals null in comparisons -->
            <do_if value="$sliderEvent and $section != null and $setting != null">
              <!-- Use the section and setting names directly as they come from the echo parameter -->
              <!-- The global settings structure uses these exact names with dollar signs -->
              <set_value name="$cleanSection" exact="$section"/>
              <set_value name="$cleanSetting" exact="$setting"/>
              
              <!-- Update the setting -->
              <set_value name="global.$GT_GlobalSettings.{$cleanSection}.{$cleanSetting}" exact="$newValue"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Global setting updated: ' + $cleanSection + '.' + $cleanSetting + ' = ' + $newValue" chance="100"/>
              </do_if>
              
              <!-- If cache/live concurrency changed, update in-flight queues so changes apply immediately -->
              <do_if value="$cleanSection == '$Performance' and $cleanSetting == '$MaxConcurrentCacheSearches'">
                <do_if value="global.$GT_SearchSemaphore?">
                  <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentCache" exact="$newValue"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] Search semaphore cache MaxConcurrent updated to: ' + $newValue" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_elseif value="$cleanSection == '$Performance' and $cleanSetting == '$MaxConcurrentLiveSearches'">
                <do_if value="global.$GT_SearchSemaphore?">
                  <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentLive" exact="$newValue"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] Search semaphore live MaxConcurrent updated to: ' + $newValue" chance="100"/>
                  </do_if>
                </do_if>
              </do_elseif>
              
              <signal_cue_instantly cue="GT_SyncUICreditsDueState"/>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] ERROR: Missing required parameters - Value: ' + $newValue + ', Section: ' + $section + ', Setting: ' + $setting" chance="100"/>
              </do_if>
            </do_else>
      </actions>
        </cue>
        
    <!-- Relation Threshold Update Handler (converts percentage to normalized value) -->
    <cue name="GT_Relation_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] UpdateRelationThreshold called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Simple Menu API passes a table with $value (percentage -100 to 0) and $echo -->
            <set_value name="$percentageValue" exact="null"/>
            <set_value name="$section" exact="null"/>
            <set_value name="$setting" exact="null"/>
            
            <!-- Get the percentage value from $value -->
            <do_if value="event.param.$value?">
              <set_value name="$percentageValue" exact="event.param.$value"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Relation threshold percentage value: ' + $percentageValue + '%'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Get the echo data from $echo -->
            <do_if value="event.param.$echo? and event.param.$echo.$section? and event.param.$echo.$setting?">
              <set_value name="$section" exact="event.param.$echo.$section"/>
              <set_value name="$setting" exact="event.param.$echo.$setting"/>
            </do_if>
            
            <!-- Convert percentage to normalized value and update setting -->
            <!-- Use explicit existence + null checks (vanilla pattern) -->
            <do_if value="$percentageValue? and $percentageValue != null and $section? and $section != null and $setting? and $setting != null">
              <!-- Convert percentage (-100 to 0) to normalized (-1.0 to 0.0) -->
              <set_value name="$normalizedValue" exact="$percentageValue / 100"/>
              
              <!-- Update the setting -->
              <set_value name="global.$GT_GlobalSettings.{$section}.{$setting}" exact="$normalizedValue"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Relation threshold updated: ' + $section + '.' + $setting + ' = ' + $normalizedValue + ' (' + $percentageValue + '%)'" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] ERROR: Missing required parameters for relation threshold update'" chance="100"/>
              </do_if>
            </do_else>
      </actions>
    </cue>
    
    <!-- State Abbreviation Update Handler -->
    <cue name="GT_StateAbbreviation_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] GT_StateAbbreviation_Update called with event.param: ' + event.param" chance="100"/>
            </do_if>
            
            <!-- Extract text and echo data -->
            <set_value name="$text" exact="''"/>
            <do_if value="event.param.$text?">
              <set_value name="$text" exact="event.param.$text"/>
            </do_if>
            <set_value name="$state" exact="event.param.$echo.$state"/>
            <set_value name="$setting" exact="event.param.$echo.$setting"/>
            
            <!-- Initialize structure if needed -->
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations" exact="table[]"/>
            </do_if>
            
            <!-- Store custom abbreviation (trim whitespace and limit length) -->
            <set_value name="$cleanText" exact="$text"/>
            <!-- Trim leading/trailing whitespace (basic approach - X4 doesn't have trim function) -->
            <do_if value="$cleanText? and $cleanText != ''">
              <!-- Limit to 12 characters max -->
              <do_if value="$cleanText.length gt 12">
                <set_value name="$cleanText" exact="$cleanText.[1,12]"/>
              </do_if>
              <!-- Store the abbreviation -->
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.{$setting}" exact="$cleanText"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] State abbreviation updated: ' + $state + ' (' + $setting + ') = ' + $cleanText" chance="100"/>
              </do_if>
              
              <!-- Update all ship names when abbreviation changes -->
              <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
            </do_if>
            <do_else>
              <!-- Empty text - restore default -->
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$defaultAbbr">
                <param name="stateType" value="$state"/>
              </run_actions>
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.{$setting}" exact="$defaultAbbr"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] State abbreviation reset to default: ' + $state + ' (' + $setting + ') = ' + $defaultAbbr" chance="100"/>
              </do_if>
              
              <!-- Update all ship names -->
              <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
            </do_else>
            
            <!-- Refresh the menu to show updated value -->
            <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

    <!-- Name pattern EditBox handler (pattern mode) -->
    <cue name="GT_NamePattern_Update" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_GlobalSettings.$ShipNaming?">
          <set_value name="global.$GT_GlobalSettings.$ShipNaming" exact="table[]"/>
        </do_if>
        <set_value name="$defaultPattern" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
        <set_value name="$text" exact="''"/>
        <do_if value="event.param.$text?">
          <set_value name="$text" exact="event.param.$text"/>
        </do_if>
        <set_value name="$cleanText" exact="$text"/>
        <set_value name="$patternToStore" exact="$defaultPattern"/>
        <do_if value="$cleanText? and $cleanText != ''">
          <set_value name="$stripped" exact="$cleanText"/>
          <do_all exact="64" counter="$sp">
            <substitute_text source="$stripped" text="$stripped">
              <replace string="' '" with="''"/>
            </substitute_text>
          </do_all>
          <do_if value="$stripped != ''">
            <set_value name="$patternToStore" exact="$cleanText"/>
            <do_if value="$patternToStore.length gt 128">
              <set_value name="$patternToStore" exact="$patternToStore.[1,128]"/>
            </do_if>
          </do_if>
        </do_if>
        <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamePattern" exact="$patternToStore"/>
        <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Refresh_Menu"/>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GLX_Lib_TradingLog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Trade-search trace logging + pipeline counters (split from gt_libraries_general for maintainability). -->

    <!-- Log Trade Search Event (Simple Format) -->
    <library name="GLX_LogTradeSearch" purpose="run_actions">
      <params>
        <param name="traceId" default="0" comment="Trace ID for request correlation"/>
        <param name="stage" default="'Unknown'" comment="Stage name (Request, CacheQuery, HomeSearch, OfferCollect, Match, Finalize, Scheduler, Reservation, Cache, Error)"/>
        <param name="action" default="'Event'" comment="Action name (Start, End, Hit, Miss, Error, etc.)"/>
        <param name="details" default="''" comment="Details string (key=value pairs)"/>
        <param name="chance" default="100" comment="Log chance (0-100)"/>
        <param name="logLevel" default="1" comment="Log level (0=error/critical, 1=important, 2=info, 3=debug) - maps to chance if chance not provided"/>
      </params>
      <actions>
        <!-- Map logLevel to chance if chance not explicitly provided (default 100) -->
        <set_value name="$logChance" exact="$chance"/>
        <do_if value="$chance == 100 and $logLevel != 1">
          <!-- logLevel 0,1,2 = always log (100), logLevel 3 = debug (100 for now, user said "log all") -->
          <set_value name="$logChance" exact="100"/>
        </do_if>
        
        <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$timestamp" exact="player.age"/>
          <set_value name="$logMsg" exact="'[GT-TS] ' + $timestamp + ' ' + $traceId + ' ' + $stage + ' ' + $action + ' ' + $details"/>
          <debug_text text="$logMsg" chance="$logChance"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Log Trade Search Event (Structured Format for PS Scripts) -->
    <library name="GLX_LogTradeSearchStructured" purpose="run_actions">
      <params>
        <param name="traceId" default="0" comment="Trace ID for request correlation"/>
        <param name="stage" default="'Unknown'" comment="Stage name"/>
        <param name="action" default="'Event'" comment="Action name"/>
        <param name="fields" default="table[]" comment="Key-value pairs table for structured logging"/>
      </params>
      <actions>
        <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$timestamp" exact="player.age"/>
          <set_value name="$detailStr" exact="''"/>
          <do_if value="$fields? and $fields.keys?">
            <do_all exact="$fields.keys.count" counter="$i">
              <set_value name="$key" exact="$fields.keys.{$i}"/>
              <set_value name="$value" exact="@$fields.{$key}"/>
              <set_value name="$separator" exact="if $i lt $fields.keys.count then ' ' else ''"/>
              <set_value name="$detailStr" exact="$detailStr + $key + '=' + $value + $separator"/>
            </do_all>
          </do_if>
          <set_value name="$logMsg" exact="'[GT-TS] ' + $timestamp + ' ' + $traceId + ' ' + $stage + ' ' + $action + ' ' + $detailStr"/>
          <debug_text text="$logMsg" chance="100"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Generate Next Trace ID -->
    <library name="GLX_GenerateTraceId" purpose="run_actions">
      <params>
      </params>
      <actions>
        <!-- Initialize trace ID counter if missing -->
        <do_if value="not global.$GT_TraceIdCounter?">
          <set_value name="global.$GT_TraceIdCounter" exact="1"/>
        </do_if>
        
        <!-- Get current trace ID and increment -->
        <set_value name="$traceId" exact="global.$GT_TraceIdCounter"/>
        <set_value name="global.$GT_TraceIdCounter" operation="add"/>
        
        <!-- Return trace ID -->
        <return value="$traceId"/>
      </actions>
    </library>
    
    <!-- Update Pipeline Counter -->
    <library name="GLX_UpdatePipelineCounter" purpose="run_actions">
      <params>
        <param name="counterName" comment="Counter name (Queued, Active, Completed, Failed)"/>
        <param name="delta" default="1" comment="Delta value (positive to increment, negative to decrement)"/>
      </params>
      <actions>
        <!-- Initialize counters structure if missing -->
        <do_if value="not global.$GT_PipelineCounters?">
          <set_value name="global.$GT_PipelineCounters" exact="table[
            $Queued = 0,
            $Active = 0,
            $Completed = 0,
            $Failed = 0
          ]"/>
        </do_if>
        
        <!-- Update counter -->
        <do_if value="global.$GT_PipelineCounters.{$counterName}?">
          <do_if value="$delta gt 0">
            <do_all exact="$delta" counter="$i">
              <set_value name="global.$GT_PipelineCounters.{$counterName}" operation="add"/>
            </do_all>
          </do_if>
          <do_elseif value="$delta lt 0">
            <set_value name="$absDelta" exact="-$delta"/>
            <do_all exact="$absDelta" counter="$i">
              <set_value name="global.$GT_PipelineCounters.{$counterName}" operation="subtract"/>
            </do_all>
          </do_elseif>
          <!-- Clamp to zero (never negative) -->
          <do_if value="global.$GT_PipelineCounters.{$counterName} lt 0">
            <set_value name="global.$GT_PipelineCounters.{$counterName}" exact="0"/>
          </do_if>
        </do_if>
      </actions>
    </library>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Blacklist_Loader" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  
  <cues>
    <!-- Legacy loader stub: gt_blacklist_manager.lua is loaded via ui.xml (works in packed cat/dat).
         Active loader logic lives in gt_libraries_blacklist.xml comment; init in gt_threat_intelligence.xml. -->
  </cues>
  
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Buy_Tracking" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - BUY TRACKING SYSTEM
         Tracks purchase costs for profit calculation
         ======================================== -->
    
    <!-- Initialize cargo cost tracking on game load (NO DELAY - must be immediate) -->
    <cue name="InitializeCargoCostTracking" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
      </actions>
    </cue>
    
    <!-- Process Buy Completion Queue -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessBuyCompletion" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_BuyComplete'"/>
        <!-- Only process if initialization has completed (table exists) -->
        <check_value value="global.$GT_CargoCostTracking?"/>
      </conditions>
      <actions>
        <!-- Ensure table exists before processing (handles cue instances created before initialization) -->
        <do_if value="not global.$GT_CargoCostTracking?">
          <set_value name="global.$GT_CargoCostTracking" exact="table[]"/>
        </do_if>
        
        <do_if value="global.$GT_BuyCompleteQueue? and global.$GT_BuyCompleteQueue.count gt 0">
          <do_while value="global.$GT_BuyCompleteQueue.count gt 0">
            <set_value name="$data" exact="global.$GT_BuyCompleteQueue.{1}"/>
            <remove_from_list name="global.$GT_BuyCompleteQueue" exact="$data"/>
            <set_value name="$ship" exact="@$data.$Ship"/>
            
            <do_if value="not $ship? or $ship == null">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-BuyTracking] Skipping queue entry with missing ship payload'" chance="100"/>
              </do_if>
              <continue/>
            </do_if>
            
            <!-- Skip if ship no longer registered -->
            <do_if value="not global.$GT_Ships.{$ship}?">
              <!-- <debug_text text="'[GT-BuyTracking] âš  Skipping buy tracking for unregistered ship: ' + $ship.idcode" chance="100"/> -->
              <continue/>
            </do_if>
            
            <!-- Initialize ship's cargo cost tracking if not exists -->
            <do_if value="not global.$GT_CargoCostTracking.{$ship}?">
              <set_value name="global.$GT_CargoCostTracking.{$ship}" exact="table[]"/>
            </do_if>
            
            <!-- Calculate total purchase cost for this buy -->
            <set_value name="$ware" exact="$data.$ware"/>
            <set_value name="$amount" exact="$data.$amount"/>
            <set_value name="$unitPrice" exact="$data.$unitPrice"/>
            <set_value name="$totalCost" exact="$unitPrice * $amount"/>
            
            <!-- Track or update cargo cost for this ware -->
            <do_if value="not global.$GT_CargoCostTracking.{$ship}.{$ware}?">
              <!-- First purchase of this ware -->
              <set_value name="global.$GT_CargoCostTracking.{$ship}.{$ware}" exact="table[
                $Amount = $amount,
                $TotalCost = $totalCost,
                $LastUpdate = player.age
              ]"/>
            </do_if>
            <do_else>
              <!-- Additional purchase - add to existing (weighted average handled automatically) -->
              <set_value name="global.$GT_CargoCostTracking.{$ship}.{$ware}.$Amount" 
                          exact="global.$GT_CargoCostTracking.{$ship}.{$ware}.$Amount + $amount"/>
              <set_value name="global.$GT_CargoCostTracking.{$ship}.{$ware}.$TotalCost" 
                          exact="global.$GT_CargoCostTracking.{$ship}.{$ware}.$TotalCost + $totalCost"/>
              <set_value name="global.$GT_CargoCostTracking.{$ship}.{$ware}.$LastUpdate" exact="player.age"/>
            </do_else>
            
            <!-- Use safe operators for debug text to prevent errors if table structure is invalid -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$trackedAmount" exact="@global.$GT_CargoCostTracking.{$ship}.{$ware}.$Amount"/>
              <set_value name="$trackedCost" exact="@global.$GT_CargoCostTracking.{$ship}.{$ware}.$TotalCost"/>
              <debug_text text="'[GT-BuyTracking] BUY tracked: ' + $ship.idcode + ' bought ' + $amount + ' ' + $ware.name + 
                                ' for ' + ($totalCost / 100) + ' Cr (Total tracked: ' + 
                                (if $trackedAmount? then $trackedAmount else 0) + ' units, ' + 
                                (if $trackedCost? then ($trackedCost / 100) else 0) + ' Cr)'" 
                          chance="100"/>
            </do_if>

            <!-- Buy-completion sell-leg gate: inspect the queued sell WITHOUT cancelling first.
                 Cancel and route to disposal only when the buyer offer is universally dead (.available false
                 or partner gone). Never cancel for offeramount.{ship}==0 while .available is true - that is
                 transient fleet saturation and our pending TradePerform still holds the reservation. -->
            <set_value name="$gateHasPendingSell" exact="false"/>
            <do_if value="$ship.tradeorders? and $ship.tradeorders.count gt 0">
              <do_all exact="$ship.tradeorders.count" counter="$gpi">
                <set_value name="$gateOrder" exact="$ship.tradeorders.{$gpi}"/>
                <do_if value="$gateOrder? and $gateOrder != $ship.order and $gateOrder.$tradedeal?">
                  <do_if value="not @$gateOrder.$tradedeal.seller.exists and $gateOrder.$tradedeal.ware == $ware">
                    <set_value name="$gateHasPendingSell" exact="true"/>
                    <break/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>

            <do_if value="$gateHasPendingSell">
              <set_value name="$gateSellStation" exact="null"/>
              <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{$ship}? and global.$GT_ActiveTrade.{$ship}.$SellStation?">
                <set_value name="$gateSellStation" exact="global.$GT_ActiveTrade.{$ship}.$SellStation"/>
              </do_if>
              <do_if value="not $gateSellStation? or not $gateSellStation.exists">
                <do_if value="$ship.tradeorders? and $ship.tradeorders.count gt 0">
                  <do_all exact="$ship.tradeorders.count" counter="$gpsi">
                    <set_value name="$gatePendingOrder" exact="$ship.tradeorders.{$gpsi}"/>
                    <do_if value="$gatePendingOrder? and $gatePendingOrder.$tradedeal? and not @$gatePendingOrder.$tradedeal.seller.exists and $gatePendingOrder.$tradedeal.ware == $ware">
                      <do_if value="$gatePendingOrder.$tradedeal.owner? and $gatePendingOrder.$tradedeal.owner.exists">
                        <set_value name="$gateSellStation" exact="$gatePendingOrder.$tradedeal.owner"/>
                      </do_if>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>

              <set_value name="$gateSellDead" exact="false"/>
              <set_value name="$gateSellStationName" exact="if $gateSellStation? then @$gateSellStation.knownname else 'Unknown'"/>
              <do_if value="not $gateSellStation? or not $gateSellStation.exists or not $gateSellStation.isoperational">
                <set_value name="$gateSellDead" exact="true"/>
              </do_if>
              <do_else>
                <find_buy_offer buyer="$gateSellStation" wares="$ware" tradepartner="$ship" result="$gateSellOffer"/>
                <do_if value="not $gateSellOffer.available">
                  <set_value name="$gateSellDead" exact="true"/>
                </do_if>
                <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$gateOfferAmt" exact="@$gateSellOffer.offeramount.{$ship}"/>
                  <debug_text text="'[GT-SellGate] ' + $ship.idcode + ': queued sell leg still valid after buy (' + $ware.name + ' to ' + $gateSellStationName + ', offeramount.ship=' + (if $gateOfferAmt? then $gateOfferAmt else 'null') + ')'" chance="100"/>
                </do_elseif>
              </do_else>

              <do_if value="$gateSellDead">
                <set_value name="$gateCancelled" exact="0"/>
                <do_if value="$ship.tradeorders? and $ship.tradeorders.count gt 0">
                  <do_all exact="$ship.tradeorders.count" counter="$gci">
                    <set_value name="$gateCancelOrder" exact="$ship.tradeorders.{$gci}"/>
                    <do_if value="$gateCancelOrder? and $gateCancelOrder != $ship.order and $gateCancelOrder.$tradedeal?">
                      <do_if value="not @$gateCancelOrder.$tradedeal.seller.exists and $gateCancelOrder.$tradedeal.ware == $ware">
                        <cancel_order order="$gateCancelOrder"/>
                        <set_value name="$gateCancelled" operation="add"/>
                      </do_if>
                    </do_if>
                  </do_all>
                </do_if>

                <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
                  <param name="ship" value="$ship"/>
                </run_actions>

                <signal_objects object="$ship" param="'GT_Trade_Failed'" param2="table[
                  $Ship = $ship,
                  $Reason = 'ERR_TRADEOFFER_INVALID',
                  $FailureText = null,
                  $Partner = $gateSellStation,
                  $IsBuying = false,
                  $ReasonType = 'MARKET',
                  $PathBlocked = false,
                  $ShouldTryNext = false,
                  $Timestamp = player.age
                ]" delay="1ms"/>

                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-SellGate] ' + $ship.idcode + ': sell leg dead after buy - cancelled ' + $gateCancelled + ' queued sell order(s) for ' + $ware.name + ' (partner: ' + $gateSellStationName + ') - routing to cargo disposal'" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- Event-driven cleanup: Ship destroyed -->
    <cue name="CleanupOnShipDestroyed" instantiate="true">
      <conditions>
        <event_object_destroyed object="player.entity"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <!-- Only cleanup if this was a registered GT ship with cargo tracking -->
        <do_if value="global.$GT_CargoCostTracking? and global.$GT_CargoCostTracking.{$ship}?">
          <remove_value name="global.$GT_CargoCostTracking.{$ship}"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-BuyTracking] Ship destroyed - cleared cargo tracking: ' + $ship.idcode + ' (Pilot may have survived via ejection - pilot data preserved)'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Cheats" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>

    <library name="GT_Cheat_GetScope" purpose="run_actions">
      <actions>
        <set_value name="$scope" exact="'off'"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Cheats? and global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope?">
          <set_value name="$scope" exact="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope"/>
        </do_if>
        <do_if value="$scope != 'off' and $scope != 'gt' and $scope != 'all'">
          <set_value name="$scope" exact="'off'"/>
        </do_if>
        <return value="$scope"/>
      </actions>
    </library>

    <library name="GT_Cheat_ApplyShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to protect"/>
      </params>
      <actions>
        <do_if value="$ship? and $ship.exists and $ship.isclass.{class.ship}">
          <set_object_min_hull object="$ship" exact="100"/>
          <set_object_min_shield object="$ship" exact="100"/>
        </do_if>
      </actions>
    </library>

    <library name="GT_Cheat_ClearShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to restore normal damage rules"/>
      </params>
      <actions>
        <do_if value="$ship? and $ship.exists and $ship.isclass.{class.ship}">
          <set_object_min_hull object="$ship" exact="0"/>
          <set_object_min_shield object="$ship" exact="0"/>
        </do_if>
      </actions>
    </library>

    <cue name="Init" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <do_if value="not global.$GT_CheatProtectedShips?">
          <set_value name="global.$GT_CheatProtectedShips" exact="[]"/>
        </do_if>
        <signal_cue_instantly cue="GT_Cheat_Reconcile"/>
      </actions>
    </cue>

    <cue name="PeriodicRefresh" instantiate="true" checktime="player.age + 5s" checkinterval="60s">
      <actions>
        <run_actions ref="GT_Cheat_GetScope" result="$scope"/>
        <do_if value="$scope != 'off'">
          <signal_cue_instantly cue="GT_Cheat_Reconcile"/>
        </do_if>
      </actions>
    </cue>

    <cue name="GT_Cheat_Reconcile" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <run_actions ref="GT_Cheat_GetScope" result="$scope"/>
        <do_if value="not global.$GT_CheatProtectedShips?">
          <set_value name="global.$GT_CheatProtectedShips" exact="[]"/>
        </do_if>

        <set_value name="$targetTable" exact="table[]"/>

        <do_if value="$scope == 'gt'">
          <do_if value="global.$GT_Ships?">
            <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
            <do_all exact="$shipKeys.count" counter="$sk">
              <set_value name="$ship" exact="$shipKeys.{$sk}"/>
              <do_if value="$ship? and $ship.exists and $ship.isclass.{class.ship}">
                <run_actions ref="md.GLX_Lib_Orders.GLX_ShipIsInGTService" result="$isGTService">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <do_if value="$isGTService">
                  <set_value name="$targetTable.{$ship}" exact="true"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <do_elseif value="$scope == 'all'">
          <find_ship_by_true_owner name="$allShips" faction="faction.player" space="player.galaxy" multiple="true" unit="false"/>
          <do_all exact="$allShips.count" counter="$as">
            <set_value name="$ship" exact="$allShips.{$as}"/>
            <do_if value="$ship? and $ship.exists and $ship.isclass.{class.ship}">
              <set_value name="$targetTable.{$ship}" exact="true"/>
            </do_if>
          </do_all>
        </do_elseif>

        <set_value name="$newProtected" exact="[]"/>
        <do_all exact="global.$GT_CheatProtectedShips.count" counter="$pi">
          <set_value name="$ship" exact="global.$GT_CheatProtectedShips.{$pi}"/>
          <do_if value="$ship? and $ship.exists">
            <do_if value="$scope == 'off' or not $targetTable.{$ship}?">
              <run_actions ref="GT_Cheat_ClearShip">
                <param name="ship" value="$ship"/>
              </run_actions>
            </do_if>
            <do_else>
              <append_to_list name="$newProtected" exact="$ship"/>
            </do_else>
          </do_if>
        </do_all>

        <set_value name="$targetKeys" exact="$targetTable.keys.list"/>
        <do_all exact="$targetKeys.count" counter="$ti">
          <set_value name="$ship" exact="$targetKeys.{$ti}"/>
          <do_if value="$ship? and $ship.exists">
            <set_value name="$alreadyListed" exact="false"/>
            <do_all exact="$newProtected.count" counter="$np">
              <do_if value="$newProtected.{$np} == $ship">
                <set_value name="$alreadyListed" exact="true"/>
              </do_if>
            </do_all>
            <run_actions ref="GT_Cheat_ApplyShip">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="not $alreadyListed">
              <append_to_list name="$newProtected" exact="$ship"/>
            </do_if>
          </do_if>
        </do_all>

        <set_value name="global.$GT_CheatProtectedShips" exact="$newProtected"/>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Cheats] Reconcile scope=' + $scope + ' protected=' + global.$GT_CheatProtectedShips.count" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- One-shot: reveal fog of war, stations, and faction trade subscriptions (vanilla Test_Trade pattern). -->
    <cue name="GT_Cheat_RevealUniverse" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_GlobalSettings.$Cheats?">
          <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
        </do_if>

        <do_for_each name="$faction" in="lookup.faction.list">
          <!-- Visitor factions have no md.$FactionData entry; relation bumps trigger vanilla PromotionInstant errors. -->
          <do_if value="$faction.isactive and $faction != faction.player and $faction != faction.ownerless and not $faction.isvisitor and md.$FactionData.{$faction}?">
            <set_faction_known faction="$faction" known="true"/>
            <do_if value="@$faction.relationto.{faction.player} lt 0.32">
              <set_faction_relation faction="$faction" otherfaction="faction.player" value="0.32"/>
            </do_if>
            <do_all exact="$faction.licences.count" counter="$li">
              <set_value name="$licence" exact="$faction.licences.{$li}"/>
              <do_if value="$licence.type == 'tradesubscription' and not faction.player.haslicence.{$licence}">
                <add_licence licence="$licence"/>
              </do_if>
            </do_all>
          </do_if>
        </do_for_each>

        <find_cluster name="$clusters" multiple="true"/>
        <do_all exact="$clusters.count" counter="$ci">
          <set_value name="$cluster" exact="$clusters.{$ci}"/>
          <set_known object="$cluster" known="true"/>
          <find_sector name="$sectors" space="$cluster" multiple="true"/>
          <do_all exact="$sectors.count" counter="$si">
            <set_value name="$sector" exact="$sectors.{$si}"/>
            <set_known object="$sector" known="true"/>
            <clear_fog_of_war sector="$sector" range="2500km">
              <position x="0" y="0" z="0"/>
            </clear_fog_of_war>
            <find_object name="$gates" class="class.gate" space="$sector" multiple="true"/>
            <do_for_each name="$gate" in="$gates">
              <set_known object="$gate" known="true"/>
            </do_for_each>
            <find_station name="$stations" space="$sector" multiple="true"/>
            <do_all exact="$stations.count" counter="$sti">
              <set_value name="$station" exact="$stations.{$sti}"/>
              <set_known object="$station" known="true" updatesnapshot="true"/>
              <do_if value="not @$station.haspermanenttradesubscription">
                <add_trade_subscription object="$station"/>
              </do_if>
            </do_all>
          </do_all>
        </do_all>

        <set_value name="global.$GT_GlobalSettings.$Cheats.$UniverseRevealed" exact="true"/>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Cheats] Universe reveal applied (' + $clusters.count + ' clusters)'" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- One-shot: max XP and level 15 for every registered GT pilot (no training). -->
    <cue name="GT_Cheat_MaxPilotXP" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_GlobalSettings.$Cheats?">
          <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
        </do_if>

        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$maxLevel" exact="15"/>
        <set_value name="$maxXP" exact="6000"/>
        <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$SkillThresholds? and global.$GT_Config.$XP.$SkillThresholds.{$maxLevel}?">
          <set_value name="$maxXP" exact="global.$GT_Config.$XP.$SkillThresholds.{$maxLevel}"/>
        </do_if>

        <set_value name="$processed" exact="0"/>
        <do_if value="not $useVanillaXPOnly and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$pi">
            <set_value name="$pilot" exact="global.$GT_Pilots.keys.{$pi}"/>
            <do_if value="$pilot? and $pilot.exists and global.$GT_Pilots.{$pilot}?">
              <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="$maxXP"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$maxLevel"/>

              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="[]"/>
              <do_if value="global.$GT_Config? and global.$GT_Config.$Training? and global.$GT_Config.$Training.$RequiredLevels?">
                <do_for_each name="$reqLevel" in="global.$GT_Config.$Training.$RequiredLevels">
                  <append_to_list name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="$reqLevel"/>
                </do_for_each>
              </do_if>
              <do_else>
                <append_to_list name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="3"/>
                <append_to_list name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="6"/>
                <append_to_list name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="9"/>
                <append_to_list name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="12"/>
              </do_else>

              <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
                <param name="pilot" value="$pilot"/>
              </run_actions>
              <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedXPPending"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment"/>

              <set_skill entity="$pilot" type="skilltype.management" exact="$maxLevel"/>
              <set_skill entity="$pilot" type="skilltype.piloting" exact="9"/>

              <do_if value="global.$GT_Pilots.{$pilot}.$Ship? and global.$GT_Pilots.{$pilot}.$Ship.exists">
                <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
                  <param name="pilot" value="$pilot"/>
                  <param name="ship" value="global.$GT_Pilots.{$pilot}.$Ship"/>
                </run_actions>
              </do_if>

              <set_value name="$processed" operation="add"/>
            </do_if>
          </do_all>
        </do_if>

        <set_value name="global.$GT_GlobalSettings.$Cheats.$PilotsMaxed" exact="true"/>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Cheats] Max pilot XP applied to ' + $processed + ' registered pilots (vanilla XP only=' + $useVanillaXPOnly + ')'" chance="100"/>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- SINGLE SOURCE OF TRUTH: All configuration settings are managed here -->
    <!-- NO configuration should exist anywhere else in the mod -->
    <cue name="ConfigInitV3" instantiate="true" version="1" comment="Renamed: old non-instantiate ConfigInit stuck as complete in saves">
      <conditions>
        <check_any>
          <event_player_created/>
          <event_game_loaded/>
        </check_any>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Initializing configuration system...'" chance="100"/>
        </do_if>
        
        <!-- Ensure all global table structures are valid -->
        <!-- This runs once on game start/load and guarantees all tables exist with proper structure -->
        <!-- This eliminates the need for repetitive checks throughout the codebase -->
        <run_actions ref="md.GT_Configuration.GT_InitializeGlobalTables"/>
        
        <!-- Preserve persisted config across savegame loads.
             ConfigInit sets defaults below; we re-apply existing saved keys afterwards. -->
        <set_value name="$existingTradingConfig" exact="if global.$GT_Config? and global.$GT_Config.$Trading? then global.$GT_Config.$Trading else table[]"/>
        <set_value name="$existingNotificationsConfig" exact="if global.$GT_Config? and global.$GT_Config.$Notifications? then global.$GT_Config.$Notifications else table[]"/>
        <set_value name="$existingDefenseConfig" exact="if global.$GT_Config? and global.$GT_Config.$Defense? then global.$GT_Config.$Defense else table[]"/>
        <set_value name="$existingFleetConfig" exact="if global.$GT_Config? and global.$GT_Config.$Fleet? then global.$GT_Config.$Fleet else table[]"/>
        <set_value name="$existingMarketConfig" exact="if global.$GT_Config? and global.$GT_Config.$Market? then global.$GT_Config.$Market else table[]"/>
        <set_value name="$existingWareFilterConfig" exact="if global.$GT_Config? and global.$GT_Config.$WareFilter? then global.$GT_Config.$WareFilter else table[]"/>
        <set_value name="$existingDebugConfig" exact="if global.$GT_Config? and global.$GT_Config.$Debug? then global.$GT_Config.$Debug else table[]"/>
        
        <!-- Trading Configuration -->
        <set_value name="global.$GT_Config" exact="table[]"/>
        <set_value name="global.$GT_Config.$Trading" exact="table[]"/>
        <set_value name="global.$GT_Config.$Trading.$MinROI" exact="0.10" comment="Minimum ROI percentage (10% = 0.10)"/>
        <set_value name="global.$GT_Config.$Trading.$MinAbsoluteProfit" exact="10000" comment="Absolute minimum profit (100 Cr in RAW format)"/>
        <set_value name="global.$GT_Config.$Trading.$CacheThresholdROI" exact="0.20" comment="Minimum ROI for caching trades (20% = 0.20)"/>
        <set_value name="global.$GT_Config.$Trading.$MaxTradeDistance" exact="5" comment="Maximum jump distance for trades"/>
        <set_value name="global.$GT_Config.$Trading.$RiskTolerance" exact="0.5" comment="0=safe only, 1=accept all risks"/>
        <set_value name="global.$GT_Config.$Trading.$CargoUtilization" exact="0.9" comment="Target cargo fill percentage"/>
        <set_value name="global.$GT_Config.$Trading.$UpdateInterval" exact="30s" comment="Market data refresh interval"/>
        <set_value name="global.$GT_Config.$Trading.$FactionPriority" exact="0" comment="0=Equal priority, 1=Boost player-owned station trades"/>
        
        <!-- Price Range Configuration (for trade offer collection) -->
        <!-- relativeprice ranges: -1.0 to +1.0, where negative = below average, positive = above average -->
        <set_value name="global.$GT_Config.$Trading.$SellPriceMax" exact="-0.2" comment="Normal: buy below -20% (only cheap offers). Range -1.0 to 1.0"/>
        <set_value name="global.$GT_Config.$Trading.$BuyPriceMin" exact="0.2" comment="Normal: sell above +20% (only expensive buyers). Range -1.0 to 1.0"/>
        <set_value name="global.$GT_Config.$Trading.$IsolatedSellPriceMax" exact="1.0" comment="Isolated: no filter (+100%). Accept any trade when stuck in single sector"/>
        <set_value name="global.$GT_Config.$Trading.$IsolatedBuyPriceMin" exact="-1.0" comment="Isolated: no filter (-100%). Accept any trade when stuck in single sector"/>
        <set_value name="global.$GT_Config.$Trading.$FallbackSellPriceMax" exact="0.2" comment="Fallback: buy up to +20% above average. Relaxed filter when normal search fails"/>
        <set_value name="global.$GT_Config.$Trading.$FallbackBuyPriceMin" exact="-0.2" comment="Fallback: sell down to -20% below average. Relaxed filter when normal search fails"/>
        
        <!-- Re-apply persisted trading keys from save if present -->
        <do_if value="$existingTradingConfig?">
          <do_all exact="$existingTradingConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingTradingConfig.keys.{$k}"/>
            <do_if value="$key? and $existingTradingConfig.{$key}?">
              <set_value name="global.$GT_Config.$Trading.{$key}" exact="$existingTradingConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- XP and Training Configuration -->
        <set_value name="global.$GT_Config.$XP" exact="table[]"/>
        <!-- DIFF PATCH XP CALCULATION PARAMETERS (Single Source of Truth) -->
        <!-- BALANCED FOR: ~500 trades to reach Level 15 (6000 XP) = ~12 XP average per trade -->
        <set_value name="global.$GT_Config.$XP.$BaseXPPerTrade" exact="8" comment="Base XP awarded per successful trade (diff patch system)"/>
        <set_value name="global.$GT_Config.$XP.$ValueDivisor" exact="100000" comment="Trade value divisor for value multiplier calculation"/>
        <set_value name="global.$GT_Config.$XP.$MinerValueDivisor" exact="200000" comment="Miner delivery value divisor for XP scaling (amount * ware average price)"/>
        <set_value name="global.$GT_Config.$XP.$QualityMultiplier" exact="0.15" comment="Quality bonus multiplier (X4 quality * this value)"/>
        <set_value name="global.$GT_Config.$XP.$MaxDistanceForBonus" exact="10" comment="Maximum sector distance for distance bonus"/>
        <set_value name="global.$GT_Config.$XP.$DistanceBonusDivisor" exact="50.0" comment="Distance bonus calculation divisor"/>
        <set_value name="global.$GT_Config.$XP.$MinXPPerTrade" exact="5" comment="Minimum XP per trade (floor)"/>
        <set_value name="global.$GT_Config.$XP.$MaxXPPerTrade" exact="50" comment="Maximum XP per trade (ceiling)"/>
        
        <!-- Legacy parameters removed - event-driven system replaces polling -->
        
        <!-- XP Level Requirements (deprecated - kept for compatibility) -->
        <set_value name="global.$GT_Config.$XP.$LevelRequirements" exact="table[]"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{1}" exact="0" comment="Level 1 (starting)"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{2}" exact="500" comment="Level 2 (20-30 trades)"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{3}" exact="1500" comment="Level 3"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{4}" exact="3000" comment="Level 4"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{5}" exact="5000" comment="Level 5 - Basic Training Required"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{6}" exact="8000" comment="Level 6"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{7}" exact="12000" comment="Level 7"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{8}" exact="17000" comment="Level 8"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{9}" exact="24000" comment="Level 9"/>
        <set_value name="global.$GT_Config.$XP.$LevelRequirements.{10}" exact="35000" comment="Level 10 - Advanced Training Required"/>
        
        <!-- XP to X4 Skill Level Mapping (1-15 skill levels, 3 per star) -->
        <set_value name="global.$GT_Config.$XP.$SkillThresholds" exact="table[]"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{1}" exact="0" comment="Skill 1 - * (starting)"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{2}" exact="100" comment="Skill 2 - *"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{3}" exact="250" comment="Skill 3 - *"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{4}" exact="450" comment="Skill 4 - **"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{5}" exact="700" comment="Skill 5 - **"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{6}" exact="1000" comment="Skill 6 - **"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{7}" exact="1350" comment="Skill 7 - ***"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{8}" exact="1750" comment="Skill 8 - ***"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{9}" exact="2200" comment="Skill 9 - ***"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{10}" exact="2700" comment="Skill 10 - ****"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{11}" exact="3250" comment="Skill 11 - ****"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{12}" exact="3850" comment="Skill 12 - ****"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{13}" exact="4500" comment="Skill 13 - *****"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{14}" exact="5200" comment="Skill 14 - *****"/>
        <set_value name="global.$GT_Config.$XP.$SkillThresholds.{15}" exact="6000" comment="Skill 15 - ***** (max)"/>
        
        <!-- Trader Rank Titles for Ship Names (Translation IDs) -->
        <set_value name="global.$GT_Config.$XP.$TraderTitles" exact="table[]"/>
        <set_value name="global.$GT_Config.$XP.$TraderTitles.{1}" exact="{77000,6001}" comment="0-1 stars (skill 1-5) - Apprentice"/>
        <set_value name="global.$GT_Config.$XP.$TraderTitles.{2}" exact="{77000,6002}" comment="2 stars (skill 6-8) - Courier"/>
        <set_value name="global.$GT_Config.$XP.$TraderTitles.{3}" exact="{77000,6003}" comment="3 stars (skill 9-11) - Supplier"/>
        <set_value name="global.$GT_Config.$XP.$TraderTitles.{4}" exact="{77000,6004}" comment="4 stars (skill 12-14) - Trader"/>
        <set_value name="global.$GT_Config.$XP.$TraderTitles.{5}" exact="{77000,6005}" comment="5 stars (skill 15) - Merchant"/>
        <set_value name="global.$GT_Config.$XP.$TraderTitles.{6}" exact="{77000,6006}" comment="5 stars MAX (skill 15+) - Long-distance Merchant"/>
        
        <!-- Training Configuration -->
        <set_value name="global.$GT_Config.$Training" exact="table[]"/>
        <set_value name="global.$GT_Config.$Training.$RequiredLevels" exact="[3, 6, 9, 12]" comment="Levels that require training (every 3rd skill level for rank progression)"/>
        <set_value name="global.$GT_Config.$Training.$DurationMode" exact="'skill_based'" comment="skill_based, fixed, or progressive"/>
        <set_value name="global.$GT_Config.$Training.$BaseDuration" exact="600s" comment="Base training duration (10 minutes)"/>
        <set_value name="global.$GT_Config.$Training.$SkillMultiplier" exact="60s" comment="Additional time per skill level (skill_based mode)"/>
        <set_value name="global.$GT_Config.$Training.$ProgressiveIncrement" exact="30s" comment="Time increase per level (progressive mode)"/>
        <set_value name="global.$GT_Config.$Training.$RequireStation" exact="true" comment="Must be docked at valid station"/>
        <set_value name="global.$GT_Config.$Training.$ValidStationTypes" exact="['shipyard', 'wharf', 'tradestation', 'equipmentdock']"/>
        
        <!-- =============================================================== -->
        <!-- Trading Academy (Fleet Academy) Configuration                    -->
        <!-- See DOCS/Spec/FEATURE_FLEET_ACADEMY.md                           -->
        <!--                                                                   -->
        <!-- $ListedCost / $ListedDuration are the "headline" price/time      -->
        <!-- shown in marketing material, paid by a level-1 pilot. Players    -->
        <!-- with already-progressed pilots pay a fraction:                    -->
        <!--   ratio        = (TargetLevel - currentLevel) / (TargetLevel - 1)-->
        <!--   costScale    = max(MinCostPercent, ratio ^ CostExponent)        -->
        <!--   durationScale= max(MinDuration,    ListedDuration * ratio)      -->
        <!-- The math is performed on the Lua side (gt_context_academy.lua)   -->
        <!-- and the locked-in values are passed back to MD via the player    -->
        <!-- NPC blackboard.                                                  -->
        <!-- =============================================================== -->
        <set_value name="global.$GT_Config.$Academy" exact="table[]"/>
        <set_value name="global.$GT_Config.$Academy.$Enabled"        exact="true"     comment="Master toggle for the Trading Academy context-menu entry"/>
        <set_value name="global.$GT_Config.$Academy.$MinCostPercent" exact="0.05"     comment="Minimum cost as fraction of listed price (5% floor)"/>
        <set_value name="global.$GT_Config.$Academy.$MinDuration"    exact="300"      comment="Minimum training duration in seconds (5 min floor; raw int, Lua attaches the unit)"/>
        <set_value name="global.$GT_Config.$Academy.$CostExponent"   exact="1.5"      comment="Quadratic-ish curve exponent for cost scaling"/>
        <!-- Build the course list incrementally with create_list / append_to_list.
             Stock uses inline "[ table[...], table[...] ]" literals for fixed
             fleets (story_paranid.xml, story_criminal.xml), but the MD parser
             reproducibly rejects ours with "Operator expected" at the second row
             (gt_configuration.xml(152)). The incremental form below uses only
             the canonical empty-list constructor + append_to_list, which is the
             documented bullet-proof pattern and matches how the rest of this
             cue builds tables. -->
        <set_value name="global.$GT_Config.$Academy.$Courses" exact="[]"/>
        <append_to_list name="global.$GT_Config.$Academy.$Courses" exact="table[ $TargetLevel = 4,  $ListedCost = 500000Cr,  $ListedDuration = 600s,  $TextId = 9911 ]"/>
        <append_to_list name="global.$GT_Config.$Academy.$Courses" exact="table[ $TargetLevel = 7,  $ListedCost = 1500000Cr, $ListedDuration = 1200s, $TextId = 9912 ]"/>
        <append_to_list name="global.$GT_Config.$Academy.$Courses" exact="table[ $TargetLevel = 13, $ListedCost = 3000000Cr, $ListedDuration = 1800s, $TextId = 9913 ]"/>
        
        <!-- Fleet Coordination Configuration -->
        <set_value name="global.$GT_Config.$Fleet" exact="table[]"/>
        <set_value name="global.$GT_Config.$Fleet.$Enabled" exact="true" comment="Enable fleet coordination"/>
        <set_value name="global.$GT_Config.$Fleet.$MaxShipsPerRoute" exact="2" comment="Maximum ships on same trade route"/>
        <set_value name="global.$GT_Config.$Fleet.$RouteReservationTime" exact="300s" comment="Route exclusive reservation duration"/>
        <set_value name="global.$GT_Config.$Fleet.$TerritoryManagement" exact="true" comment="Enable sector specialization"/>
        <set_value name="global.$GT_Config.$Fleet.$LoadBalancing" exact="true" comment="Dynamic workload distribution"/>
        
        <!-- Re-apply persisted fleet keys from save if present -->
        <do_if value="$existingFleetConfig?">
          <do_all exact="$existingFleetConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingFleetConfig.keys.{$k}"/>
            <do_if value="$key? and $existingFleetConfig.{$key}?">
              <set_value name="global.$GT_Config.$Fleet.{$key}" exact="$existingFleetConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Market Intelligence Configuration -->
        <set_value name="global.$GT_Config.$Market" exact="table[]"/>
        <set_value name="global.$GT_Config.$Market.$PriceHistorySize" exact="10" comment="Number of price points to track"/>
        <set_value name="global.$GT_Config.$Market.$TrendAnalysis" exact="true" comment="Enable market trend prediction"/>
        <set_value name="global.$GT_Config.$Market.$CompetitorTracking" exact="true" comment="Monitor other traders"/>
        <set_value name="global.$GT_Config.$Market.$UpdateFrequency" exact="60s" comment="Market analysis update interval"/>
        
        <!-- Re-apply persisted market keys from save if present -->
        <do_if value="$existingMarketConfig?">
          <do_all exact="$existingMarketConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingMarketConfig.keys.{$k}"/>
            <do_if value="$key? and $existingMarketConfig.{$key}?">
              <set_value name="global.$GT_Config.$Market.{$key}" exact="$existingMarketConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Notification Configuration -->
        <set_value name="global.$GT_Config.$Notifications" exact="table[]"/>
        <set_value name="global.$GT_Config.$Notifications.$LevelUp" exact="true" comment="Notify on level advancement"/>
        <set_value name="global.$GT_Config.$Notifications.$TrainingRequired" exact="true" comment="Alert when training needed"/>
        <set_value name="global.$GT_Config.$Notifications.$TrainingCompleted" exact="true" comment="Notify when training completes"/>
        <set_value name="global.$GT_Config.$Notifications.$ProfitReports" exact="true" comment="Periodic profit summaries"/>
        <set_value name="global.$GT_Config.$Notifications.$MarketAlerts" exact="true" comment="Exceptional market opportunities"/>
        <set_value name="global.$GT_Config.$Notifications.$FleetUpdates" exact="false" comment="Fleet coordination messages"/>
        
        <!-- Re-apply persisted notification keys from save if present -->
        <do_if value="$existingNotificationsConfig?">
          <do_all exact="$existingNotificationsConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingNotificationsConfig.keys.{$k}"/>
            <do_if value="$key? and $existingNotificationsConfig.{$key}?">
              <set_value name="global.$GT_Config.$Notifications.{$key}" exact="$existingNotificationsConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Ware Filter Configuration -->
        <set_value name="global.$GT_Config.$WareFilter" exact="table[]"/>
        <set_value name="global.$GT_Config.$WareFilter.$BlacklistedWares" exact="[]" comment="List of wares to exclude from trading (populated dynamically)"/>
        <set_value name="global.$GT_Config.$WareFilter.$WhitelistedWares" exact="[]" comment="List of allowed wares (empty = all except blacklisted)"/>
        <set_value name="global.$GT_Config.$WareFilter.$DangerousWareHandling" exact="'avoid'" comment="avoid, allow, or priority"/>
        <set_value name="global.$GT_Config.$WareFilter.$RestrictedFactions" exact="[]" comment="Factions to avoid trading with"/>
        <set_value name="global.$GT_Config.$WareFilter.$MinWareValue" exact="0Cr" comment="Minimum value per unit to consider"/>
        <set_value name="global.$GT_Config.$WareFilter.$MaxWareValue" exact="0Cr" comment="Maximum value per unit (0 = no limit)"/>
        
        <!-- Dynamic Ware Categorization Settings -->
        <set_value name="global.$GT_Config.$WareFilter.$AutoCategorizeLowValue" exact="true" comment="Automatically blacklist low-value wares"/>
        <set_value name="global.$GT_Config.$WareFilter.$AutoCategorizeDangerous" exact="true" comment="Automatically handle illegal wares"/>
        <set_value name="global.$GT_Config.$WareFilter.$LowValueThreshold" exact="50Cr" comment="Price threshold for low-value classification"/>
        <set_value name="global.$GT_Config.$WareFilter.$HighValueThreshold" exact="100000" comment="Price threshold for high-value classification (1000 Cr in RAW format)"/>
        <set_value name="global.$GT_Config.$WareFilter.$RefreshInterval" exact="3600s" comment="How often to refresh ware categories"/>
        
        <!-- Re-apply persisted ware filter keys from save if present -->
        <do_if value="$existingWareFilterConfig?">
          <do_all exact="$existingWareFilterConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingWareFilterConfig.keys.{$k}"/>
            <do_if value="$key? and $existingWareFilterConfig.{$key}?">
              <set_value name="global.$GT_Config.$WareFilter.{$key}" exact="$existingWareFilterConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Defensive Equipment Configuration (Level 15 Feature) -->
        <set_value name="global.$GT_Config.$Defense" exact="table[]"/>
        <set_value name="global.$GT_Config.$Defense.$Enabled" exact="true" comment="Enable auto-replenishment for Level 15 pilots"/>
        
        <!-- Individual equipment type toggles -->
        <set_value name="global.$GT_Config.$Defense.$RestockCountermeasures" exact="true" comment="Enable countermeasure restocking (all ships)"/>
        <set_value name="global.$GT_Config.$Defense.$RestockDefenseDrones" exact="true" comment="Enable defense drone restocking (L/XL ships)"/>
        <set_value name="global.$GT_Config.$Defense.$RestockTradeDrones" exact="true" comment="Enable trade drone restocking (L/XL ships)"/>
        <set_value name="global.$GT_Config.$Defense.$RestockLaserTowers" exact="true" comment="Enable laser tower restocking (all ships)"/>
        <set_value name="global.$GT_Config.$Defense.$RestockRepairDrones" exact="true" comment="Enable repair drone restocking (L/XL ships)"/>
        
        <!-- Capacity thresholds -->
        <set_value name="global.$GT_Config.$Defense.$CountermeasureThreshold" exact="50" comment="Restock countermeasures when below 50% capacity"/>
        <set_value name="global.$GT_Config.$Defense.$UnifiedThreshold" exact="70" comment="Restock unified capacity when below 70% total usage"/>
        
        <!-- Balance profile: 0=Balanced, 1=Defensive, 2=Trading-Focused, 3=Heavy Defense, 4=Tower Support -->
        <set_value name="global.$GT_Config.$Defense.$BalanceProfile" exact="2" comment="2=Trading-Focused (20/50/20/10) - DEFAULT for traders"/>
        
        <!-- Re-apply persisted defense keys from save if present -->
        <do_if value="$existingDefenseConfig?">
          <do_all exact="$existingDefenseConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingDefenseConfig.keys.{$k}"/>
            <do_if value="$key? and $existingDefenseConfig.{$key}?">
              <set_value name="global.$GT_Config.$Defense.{$key}" exact="$existingDefenseConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Debug Configuration -->
        <set_value name="global.$GT_Config.$Debug" exact="table[]"/>
        <set_value name="global.$GT_Config.$Debug.$Enabled" exact="true" comment="Enable debug logging"/>
        <set_value name="global.$GT_Config.$Debug.$LogLevel" exact="2" comment="0=errors only, 1=info, 2=verbose"/>
        <set_value name="global.$GT_Config.$Debug.$PerformanceMetrics" exact="true" comment="Track performance data"/>
        <set_value name="global.$GT_Config.$Debug.$TradeSearch" exact="true" comment="Enable detailed trade search logging"/>
        <set_value name="global.$GT_Config.$Debug.$MarketData" exact="true" comment="Log market analysis details"/>
        <set_value name="global.$GT_Config.$Debug.$RouteCalculation" exact="true" comment="Log route calculation steps"/>
        <set_value name="global.$GT_Config.$Debug.$DiagnosticQueries" exact="false" comment="Enable diagnostic queries (4 galaxy-wide scans per cache miss - expensive!)"/>
        
        <!-- Re-apply persisted debug keys from save if present -->
        <do_if value="$existingDebugConfig?">
          <do_all exact="$existingDebugConfig.keys.count" counter="$k">
            <set_value name="$key" exact="$existingDebugConfig.keys.{$k}"/>
            <do_if value="$key? and $existingDebugConfig.{$key}?">
              <set_value name="global.$GT_Config.$Debug.{$key}" exact="$existingDebugConfig.{$key}"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Mod version â€” update on each release (content.xml version is not accessible from MD scripts) -->
        <set_value name="global.$GT_ModVersion" exact="'0.15.4'"/>
        <set_value name="global.$GT_ModContentVersion" exact="'01504'"/>
        <set_value name="global.$GT_Config.$Version" exact="global.$GT_ModVersion"/>
        <set_value name="global.$GT_Config.$ConfigVersion" exact="2" comment="Configuration schema version (v2 = fixed training levels)"/>
        
        <!-- Always log version info so diagnostic tools can extract it from the log file -->
        <debug_text text="'[GalaxyTrader MK3] INIT: Version=' + global.$GT_ModVersion + ' ContentVersion=' + global.$GT_ModContentVersion + ' ConfigSchema=' + global.$GT_Config.$ConfigVersion" chance="100"/>
        
        <!-- Clear incorrectly blocked pilots from old configuration -->
        <do_if value="global.$GT_Pilots?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Checking for pilots incorrectly blocked under old training system...'" chance="100"/>
          </do_if>
          <set_value name="$fixedPilots" exact="0"/>
          
          <!-- Use @ operator to safely access keys.count -->
          <set_value name="$pilotKeysCount" exact="@global.$GT_Pilots.keys.count"/>
          <do_if value="$pilotKeysCount? and $pilotKeysCount gt 0">
            <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
            <do_all exact="$pilotKeysCount" counter="$i">
              <set_value name="$pilot" exact="$pilotKeys.{$i}"/>
              
              <!-- Check if pilot is blocked -->
              <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
                <!-- Never clear academy/manual blocks or in-flight training sessions -->
                <set_value name="$skipRetroactiveClear" exact="false"/>
                <do_if value="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?">
                  <set_value name="$skipRetroactiveClear" exact="true"/>
                </do_if>
                <do_if value="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested?">
                  <set_value name="$skipRetroactiveClear" exact="true"/>
                </do_if>
                <do_if value="global.$GT_Pilots.{$pilot}.$TrainingState? and (global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress' or global.$GT_Pilots.{$pilot}.$TrainingState == 'manual_training_queued')">
                  <set_value name="$skipRetroactiveClear" exact="true"/>
                </do_if>

                <!-- Calculate current skill level from XP -->
                <set_value name="$currentSkillLevel" exact="1"/>
                <do_all exact="15" counter="$skillLevel">
                  <do_if value="global.$GT_Pilots.{$pilot}.$XP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                    <set_value name="$currentSkillLevel" exact="$skillLevel"/>
                  </do_if>
                </do_all>

                <set_value name="$shouldBeBlocked" exact="false"/>
                <do_if value="not $skipRetroactiveClear">
                  <!-- Validate against BlockedLevel when set (academy jump targets exceed current XP tier) -->
                  <set_value name="$levelToValidate" exact="$currentSkillLevel"/>
                  <do_if value="global.$GT_Pilots.{$pilot}.$BlockedLevel? and global.$GT_Pilots.{$pilot}.$BlockedLevel gt 0">
                    <set_value name="$levelToValidate" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                  </do_if>

                  <!-- Check if this skill level should actually be blocked -->
                  <set_value name="$requiresTraining" exact="false"/>
                  <do_if value="global.$GT_Config.$Training.$RequiredLevels?">
                    <do_all exact="global.$GT_Config.$Training.$RequiredLevels.count" counter="$i">
                      <do_if value="global.$GT_Config.$Training.$RequiredLevels.{$i} == $levelToValidate">
                        <set_value name="$requiresTraining" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  
                  <do_if value="$requiresTraining">
                    <!-- Check if training is completed using explicit loop (indexof unreliable for lists) -->
                    <set_value name="$hasCompletedTraining" exact="false"/>
                    <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
                      <do_all exact="global.$GT_Pilots.{$pilot}.$TrainingCompleted.count" counter="$j">
                        <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted.{$j} == $levelToValidate">
                          <set_value name="$hasCompletedTraining" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    
                    <do_if value="not $hasCompletedTraining">
                      <set_value name="$shouldBeBlocked" exact="true"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_else>
                  <set_value name="$shouldBeBlocked" exact="true"/>
                </do_else>
                
                <!-- Fix incorrectly blocked pilots -->
                <do_if value="not $shouldBeBlocked">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] RETROACTIVE FIX: Clearing incorrect XP block for pilot ' + $pilot.name + ' (skill level ' + $currentSkillLevel + ', XP: ' + global.$GT_Pilots.{$pilot}.$XP + ')'" chance="100"/>
                  </do_if>
                  <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
                  <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                  <set_value name="$fixedPilots" exact="$fixedPilots + 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="$fixedPilots gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] RETROACTIVE FIX COMPLETE: Cleared XP blocks for ' + $fixedPilots + ' pilots'" chance="100"/>
            </do_if>
            <show_notification text="'GalaxyTrader MK3: Fixed XP progression for ' + $fixedPilots + ' pilots!'" timeout="8s" priority="7"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] No incorrectly blocked pilots found'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Configuration system initialized successfully'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- PHASE 2 IMPROVEMENT: Event-Driven Configuration System -->
    <!-- Initialize configuration event system -->
    <cue name="InitConfigurationEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="ConfigInitV3"/>
      </conditions>
      <actions>
        <!-- Initialize configuration event queue -->
        <set_value name="global.$GT_ConfigEventQueue" exact="[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] âš¡ Configuration event system initialized (event-driven)'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Event-Driven Configuration Processing -->
    <!-- Listen for signal instead of polling -->
    <!-- NOTE: Currently unused, but ready for future event-driven config updates -->
    <cue name="ProcessConfigurationEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Configuration.ProcessConfigurationEvents"/>
      </conditions>
      <actions>
        
        <!-- Process all queued configuration events -->
        <do_if value="global.$GT_ConfigEventQueue? and global.$GT_ConfigEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] âš¡ Processing ' + global.$GT_ConfigEventQueue.count + ' config events instantly'" chance="100"/>
          </do_if>
          
          <do_while value="global.$GT_ConfigEventQueue.count gt 0">
            <!-- Get next event -->
            <set_value name="$event" exact="global.$GT_ConfigEventQueue.{1}"/>
            <remove_from_list name="global.$GT_ConfigEventQueue" exact="$event"/>
            
            <!-- Process based on event type -->
            <do_if value="$event.$eventType == 'config_update'">
              <signal_cue_instantly cue="HandleConfigUpdate" param="$event"/>
            </do_if>
            <do_elseif value="$event.$eventType == 'validation_request'">
              <signal_cue_instantly cue="HandleConfigValidation" param="$event"/>
            </do_elseif>
            <do_elseif value="$event.$eventType == 'reload_request'">
              <signal_cue_instantly cue="HandleConfigReload" param="$event"/>
            </do_elseif>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle Configuration Updates -->
    <cue name="HandleConfigUpdate" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$section" exact="$event.$section"/>
        <set_value name="$key" exact="$event.$key"/>
        <set_value name="$value" exact="$event.$value"/>
        <set_value name="$source" exact="$event.$source"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Config update event: ' + $section + '.' + $key + ' = ' + $value + ' (source: ' + $source + ')'" chance="100"/>
        </do_if>
        
        <!-- Apply the configuration change -->
        <do_if value="$section == 'Trading'">
          <set_value name="global.$GT_Config.$Trading.{$key}" exact="$value"/>
        </do_if>
        <do_elseif value="$section == 'XP'">
          <set_value name="global.$GT_Config.$XP.{$key}" exact="$value"/>
        </do_elseif>
        <do_elseif value="$section == 'Fleet'">
          <set_value name="global.$GT_Config.$Fleet.{$key}" exact="$value"/>
        </do_elseif>
        <do_elseif value="$section == 'Debug'">
          <set_value name="global.$GT_Config.$Debug.{$key}" exact="$value"/>
        </do_elseif>
        
        <!-- Trigger validation -->
        <signal_cue_instantly cue="ValidateConfigChange" param="table[$section = $section, $key = $key, $value = $value]"/>
        
        <!-- Notify other systems -->
        <signal_cue_instantly cue="md.GT_FleetCoordination.OnConfigurationChanged" param="table[$section = $section, $key = $key, $value = $value]"/>
        <signal_cue_instantly cue="md.GT_TradingAI.OnConfigurationChanged" param="table[$section = $section, $key = $key, $value = $value]"/>
      </actions>
    </cue>
    
    <!-- Validate Configuration Changes -->
    <cue name="ValidateConfigChange" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param"/>
        <set_value name="$section" exact="$params.$section"/>
        <set_value name="$key" exact="$params.$key"/>
        <set_value name="$value" exact="$params.$value"/>
        
        <!-- Validate based on section and key -->
        <set_value name="$isValid" exact="true"/>
        <set_value name="$message" exact="''"/>
        
        <do_if value="$section == 'Trading'">
          <do_if value="$key == 'MinROI'">
            <do_if value="$value lt 0 or $value gt 2.0">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$message" exact="'MinROI must be between 0.0 and 2.0 (200%)'"/>
            </do_if>
          </do_if>
          <do_elseif value="$key == 'MinAbsoluteProfit'">
            <do_if value="$value le 0">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$message" exact="'MinAbsoluteProfit must be positive'"/>
            </do_if>
          </do_elseif>
          <do_elseif value="$key == 'RiskTolerance'">
            <do_if value="$value lt 0 or $value gt 1">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$message" exact="'RiskTolerance must be between 0.0 and 1.0'"/>
            </do_if>
          </do_elseif>
          <do_elseif value="$key == 'FactionPriority'">
            <do_if value="$value lt 0 or $value gt 1">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$message" exact="'FactionPriority must be 0 (equal) or 1 (player station boost)'"/>
            </do_if>
          </do_elseif>
        </do_if>
        <do_elseif value="$section == 'Fleet'">
          <do_if value="$key == 'MaxShipsPerRoute'">
            <do_if value="$value le 0">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$message" exact="'MaxShipsPerRoute must be positive'"/>
            </do_if>
          </do_if>
        </do_elseif>
        
        <do_if value="not $isValid">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Invalid configuration: ' + $message" chance="100"/>
          </do_if>
          <show_notification text="'GalaxyTrader MK3: Invalid config - ' + $message" timeout="5s" priority="6"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Configuration validated: ' + $section + '.' + $key" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>

    <!-- Configuration Hot Reload Detection removed - pure event-driven system -->
    
    <!-- Configuration Validation -->
    <cue name="ConfigValidation" instantiate="true">
      <conditions>
        <event_cue_signalled cue="ConfigInitV3"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Validating configuration...'" chance="100"/>
        </do_if>
        
        <!-- Validate critical settings -->
        <do_if value="global.$GT_Config.$Trading.$MinROI lt 0 or global.$GT_Config.$Trading.$MinROI gt 2.0">
          <set_value name="global.$GT_Config.$Trading.$MinROI" exact="0.10"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid MinROI, reset to 10%'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="global.$GT_Config.$Trading.$MinAbsoluteProfit le 0">
          <set_value name="global.$GT_Config.$Trading.$MinAbsoluteProfit" exact="10000"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid MinAbsoluteProfit, reset to 100Cr (10000 RAW)'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="global.$GT_Config.$Trading.$RiskTolerance lt 0 or global.$GT_Config.$Trading.$RiskTolerance gt 1">
          <set_value name="global.$GT_Config.$Trading.$RiskTolerance" exact="0.5"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid RiskTolerance, reset to default'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="global.$GT_Config.$Trading.$FactionPriority? and (global.$GT_Config.$Trading.$FactionPriority lt 0 or global.$GT_Config.$Trading.$FactionPriority gt 1)">
          <set_value name="global.$GT_Config.$Trading.$FactionPriority" exact="0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid FactionPriority, reset to 0 (equal)'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Validate price range settings (relativeprice: -1.0 to +1.0) -->
        <do_if value="global.$GT_Config.$Trading.$SellPriceMax? and (global.$GT_Config.$Trading.$SellPriceMax lt -1.0 or global.$GT_Config.$Trading.$SellPriceMax gt 1.0)">
          <set_value name="global.$GT_Config.$Trading.$SellPriceMax" exact="-0.2"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid SellPriceMax, reset to -0.2 (-20%)'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_Config.$Trading.$BuyPriceMin? and (global.$GT_Config.$Trading.$BuyPriceMin lt -1.0 or global.$GT_Config.$Trading.$BuyPriceMin gt 1.0)">
          <set_value name="global.$GT_Config.$Trading.$BuyPriceMin" exact="0.2"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid BuyPriceMin, reset to 0.2 (+20%)'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_Config.$Trading.$IsolatedSellPriceMax? and (global.$GT_Config.$Trading.$IsolatedSellPriceMax lt -1.0 or global.$GT_Config.$Trading.$IsolatedSellPriceMax gt 1.0)">
          <set_value name="global.$GT_Config.$Trading.$IsolatedSellPriceMax" exact="1.0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid IsolatedSellPriceMax, reset to 1.0'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_Config.$Trading.$IsolatedBuyPriceMin? and (global.$GT_Config.$Trading.$IsolatedBuyPriceMin lt -1.0 or global.$GT_Config.$Trading.$IsolatedBuyPriceMin gt 1.0)">
          <set_value name="global.$GT_Config.$Trading.$IsolatedBuyPriceMin" exact="-1.0"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid IsolatedBuyPriceMin, reset to -1.0'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_Config.$Trading.$FallbackSellPriceMax? and (global.$GT_Config.$Trading.$FallbackSellPriceMax lt -1.0 or global.$GT_Config.$Trading.$FallbackSellPriceMax gt 1.0)">
          <set_value name="global.$GT_Config.$Trading.$FallbackSellPriceMax" exact="0.2"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid FallbackSellPriceMax, reset to 0.2'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_Config.$Trading.$FallbackBuyPriceMin? and (global.$GT_Config.$Trading.$FallbackBuyPriceMin lt -1.0 or global.$GT_Config.$Trading.$FallbackBuyPriceMin gt 1.0)">
          <set_value name="global.$GT_Config.$Trading.$FallbackBuyPriceMin" exact="-0.2"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid FallbackBuyPriceMin, reset to -0.2'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="global.$GT_Config.$XP.$LevelRequirements.count lt 10">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] ERROR: Invalid level requirements table'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Validate ware filter settings -->
        <do_if value="not global.$GT_Config.$WareFilter.$BlacklistedWares?">
          <set_value name="global.$GT_Config.$WareFilter.$BlacklistedWares" exact="[]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid BlacklistedWares, reset to empty'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="global.$GT_Config.$WareFilter.$DangerousWareHandling != 'avoid' and global.$GT_Config.$WareFilter.$DangerousWareHandling != 'allow' and global.$GT_Config.$WareFilter.$DangerousWareHandling != 'priority'">
          <set_value name="global.$GT_Config.$WareFilter.$DangerousWareHandling" exact="'avoid'"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] WARNING: Invalid DangerousWareHandling, reset to avoid'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Configuration validation complete'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Manual Cleanup Trigger for Development/Testing -->
    <cue name="ManualCleanup" instantiate="true" checkinterval="1s">
      <conditions>
        <check_value value="global.$GT_ForceCleanup?"/>
      </conditions>
      <actions>
        <remove_value name="global.$GT_ForceCleanup"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] MANUAL CLEANUP: Forcing immediate pilot block cleanup...'" chance="100"/>
        </do_if>
        
        <do_if value="global.$GT_Pilots?">
          <set_value name="$fixedPilots" exact="0"/>
          
          <!-- Use @ operator to safely access keys.count -->
          <set_value name="$pilotKeysCount" exact="@global.$GT_Pilots.keys.count"/>
          <do_if value="$pilotKeysCount? and $pilotKeysCount gt 0">
            <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
            <do_all exact="$pilotKeysCount" counter="$i">
              <set_value name="$pilot" exact="$pilotKeys.{$i}"/>
              
              <!-- Check if pilot is blocked -->
              <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
                <set_value name="$skipRetroactiveClear" exact="false"/>
                <do_if value="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?">
                  <set_value name="$skipRetroactiveClear" exact="true"/>
                </do_if>
                <do_if value="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested?">
                  <set_value name="$skipRetroactiveClear" exact="true"/>
                </do_if>
                <do_if value="global.$GT_Pilots.{$pilot}.$TrainingState? and (global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress' or global.$GT_Pilots.{$pilot}.$TrainingState == 'manual_training_queued')">
                  <set_value name="$skipRetroactiveClear" exact="true"/>
                </do_if>

                <!-- Calculate current skill level from XP -->
                <set_value name="$currentSkillLevel" exact="1"/>
                <do_all exact="15" counter="$skillLevel">
                  <do_if value="global.$GT_Pilots.{$pilot}.$XP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                    <set_value name="$currentSkillLevel" exact="$skillLevel"/>
                  </do_if>
                </do_all>
                
                <set_value name="$shouldBeBlocked" exact="false"/>
                <do_if value="not $skipRetroactiveClear">
                  <set_value name="$levelToValidate" exact="$currentSkillLevel"/>
                  <do_if value="global.$GT_Pilots.{$pilot}.$BlockedLevel? and global.$GT_Pilots.{$pilot}.$BlockedLevel gt 0">
                    <set_value name="$levelToValidate" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                  </do_if>

                  <set_value name="$requiresTraining" exact="false"/>
                  <do_if value="global.$GT_Config.$Training.$RequiredLevels?">
                    <do_all exact="global.$GT_Config.$Training.$RequiredLevels.count" counter="$k">
                      <do_if value="global.$GT_Config.$Training.$RequiredLevels.{$k} == $levelToValidate">
                        <set_value name="$requiresTraining" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  
                  <do_if value="$requiresTraining">
                    <set_value name="$hasCompletedTraining" exact="false"/>
                    <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
                      <do_all exact="global.$GT_Pilots.{$pilot}.$TrainingCompleted.count" counter="$m">
                        <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted.{$m} == $levelToValidate">
                          <set_value name="$hasCompletedTraining" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                    </do_if>
                    
                    <do_if value="not $hasCompletedTraining">
                      <set_value name="$shouldBeBlocked" exact="true"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_else>
                  <set_value name="$shouldBeBlocked" exact="true"/>
                </do_else>
                
                <!-- Debug the decision -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Pilot ' + $pilot.name + ': skill=' + $currentSkillLevel + ', in training list=' + global.$GT_Config.$Training.$RequiredLevels.indexof.{$currentSkillLevel} + ', should be blocked=' + $shouldBeBlocked" chance="100"/>
                </do_if>
                
                <!-- Fix incorrectly blocked pilots -->
                <do_if value="not $shouldBeBlocked">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] MANUAL CLEANUP: Clearing incorrect XP block for pilot ' + $pilot.name + ' (skill level ' + $currentSkillLevel + ', XP: ' + global.$GT_Pilots.{$pilot}.$XP + ')'" chance="100"/>
                  </do_if>
                  <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
                  <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                  <set_value name="$fixedPilots" exact="$fixedPilots + 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] MANUAL CLEANUP COMPLETE: Fixed ' + $fixedPilots + ' pilots'" chance="100"/>
          </do_if>
          <show_notification text="'GalaxyTrader MK3: Manual cleanup fixed ' + $fixedPilots + ' pilots!'" timeout="8s" priority="7"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- ========================================
         GLOBAL TABLES INITIALIZATION
         One-time initialization of all global table structures
         Runs on game start/load to ensure save game compatibility
         ======================================== -->
    <library name="GT_InitializeGlobalTables" purpose="run_actions">
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Init] Initializing global table structures...'" chance="100"/>
        </do_if>
        
        <!-- Initialize global.$GT_SearchResult structure -->
        <!-- Per-ship storage: global.$GT_SearchResult.{$ship} contains search results for each ship -->
        <!-- Shared state: global.$GT_SearchResult.$LastRejectionStats contains shared rejection statistics -->
        <set_value name="$initCount" exact="0"/>
        <!-- Extract existing $LastRejectionStats if valid (preserve shared state) -->
        <set_value name="$existingSearchResult" exact="@global.$GT_SearchResult"/>
        <set_value name="$existingLastRejectionStats" exact="null"/>
        <do_if value="$existingSearchResult?">
          <set_value name="$tempStats" exact="@$existingSearchResult.$LastRejectionStats"/>
          <do_if value="$tempStats?">
            <set_value name="$tempStatsKeysCount" exact="@$tempStats.keys.count"/>
            <do_if value="$tempStatsKeysCount? and $tempStatsKeysCount ge 0">
              <set_value name="$existingLastRejectionStats" exact="$tempStats"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Build new structure atomically: preserve existing $LastRejectionStats if valid, otherwise create empty -->
        <set_value name="$newLastRejectionStats" exact="table[]"/>
        <do_if value="$existingLastRejectionStats?">
          <set_value name="$newLastRejectionStats" exact="$existingLastRejectionStats"/>
        </do_if>
        <!-- Initialize as container table with shared $LastRejectionStats -->
        <!-- Per-ship entries (global.$GT_SearchResult.{$ship}) will be created on-demand during searches -->
        <set_value name="$newSearchResultTable" exact="table[$LastRejectionStats = $newLastRejectionStats]"/>
        <!-- Set atomically - this guarantees structure is always valid -->
        <set_value name="global.$GT_SearchResult" exact="$newSearchResultTable"/>
        <set_value name="$initCount" exact="$initCount + 1"/>
        
        <!-- Initialize global.$GT_TradeLogging structure -->
        <!-- Check if global.$GT_TradeLogging exists AND is a valid table (not null) -->
        <set_value name="$tradeLoggingValid" exact="false"/>
        <do_if value="global.$GT_TradeLogging?">
          <set_value name="$tradeLoggingKeysCount" exact="@global.$GT_TradeLogging.keys.count"/>
          <do_if value="$tradeLoggingKeysCount? and $tradeLoggingKeysCount ge 0">
            <set_value name="$tradeLoggingValid" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $tradeLoggingValid">
          <set_value name="global.$GT_TradeLogging" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <set_value name="$checkLifetime" exact="@global.$GT_TradeLogging.$LifetimeProfit"/>
        <set_value name="$lifetimeValid" exact="false"/>
        <do_if value="$checkLifetime?">
          <set_value name="$lifetimeKeysCount" exact="@$checkLifetime.keys.count"/>
          <do_if value="$lifetimeKeysCount? and $lifetimeKeysCount ge 0">
            <set_value name="$lifetimeValid" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $lifetimeValid">
          <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Legacy global.$GT_SearchQueue removed in AI migration -->
        
        <!-- Initialize global.$GT_FallbackAttempted structure -->
        <do_if value="not global.$GT_FallbackAttempted?">
          <set_value name="global.$GT_FallbackAttempted" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Legacy batch globals removed in AI migration -->
        
        <!-- Initialize global.$GT_TradeCache structure (used for trade caching) -->
        <!-- Per-home-sector cache structure -->
        <do_if value="not global.$GT_TradeCache?">
          <set_value name="global.$GT_TradeCache" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <do_if value="not global.$GT_HomeFleetCargoProfile?">
          <set_value name="global.$GT_HomeFleetCargoProfile" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <do_if value="global.$GT_HomeFleetCargoProfile? and typeof global.$GT_HomeFleetCargoProfile != datatype.table">
          <set_value name="global.$GT_HomeFleetCargoProfile" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <do_if value="not global.$GT_TradeCacheMK4?">
          <set_value name="global.$GT_TradeCacheMK4" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <do_if value="not global.$GT_TradeCacheMK42?">
          <set_value name="global.$GT_TradeCacheMK42" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <do_if value="global.$GT_TradeCache? and typeof global.$GT_TradeCache != datatype.table">
          <debug_text text="'[GT-Init] WARNING: global.$GT_TradeCache has invalid type (' + typeof global.$GT_TradeCache + ') - resetting to table[] (old save migration)'" chance="100"/>
          <set_value name="global.$GT_TradeCache" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <do_if value="global.$GT_TradeCacheMK4? and typeof global.$GT_TradeCacheMK4 != datatype.table">
          <debug_text text="'[GT-Init] WARNING: global.$GT_TradeCacheMK4 has invalid type (' + typeof global.$GT_TradeCacheMK4 + ') - resetting to table[] (old save migration)'" chance="100"/>
          <set_value name="global.$GT_TradeCacheMK4" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <!-- Ensure cache version is set -->
        <do_if value="not global.$GT_TradeCacheVersion?">
          <set_value name="global.$GT_TradeCacheVersion" exact="6"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- GT_TradeCacheIndex no longer needed (cache is already indexed by home sector) -->
        <!-- Old index structure was for flat list - new structure is table indexed by home sector -->
        
        <!-- Initialize global.$GT_FilterState structure (used for filtering state) -->
        <do_if value="not global.$GT_FilterState?">
          <set_value name="global.$GT_FilterState" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_CacheMissCooldowns structure (used for cooldown tracking) -->
        <!-- Handle both non-existent and null values (save game compatibility) -->
        <!-- Pattern: Check if global exists first, then extract and validate keys.count inside the check -->
        <set_value name="$cacheMissCooldownsValid" exact="false"/>
        <do_if value="global.$GT_CacheMissCooldowns?">
          <set_value name="$cacheMissCooldownsKeysCount" exact="@global.$GT_CacheMissCooldowns.keys.count"/>
          <do_if value="$cacheMissCooldownsKeysCount? and $cacheMissCooldownsKeysCount ge 0">
            <set_value name="$cacheMissCooldownsValid" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $cacheMissCooldownsValid">
          <set_value name="global.$GT_CacheMissCooldowns" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_ActiveTradeReservations structure (used for fleet coordination) -->
        <do_if value="not global.$GT_ActiveTradeReservations?">
          <set_value name="global.$GT_ActiveTradeReservations" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_MaintenanceFailedResupply structure (used for resupply cooldowns) -->
        <do_if value="not global.$GT_MaintenanceFailedResupply?">
          <set_value name="global.$GT_MaintenanceFailedResupply" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TradesAwaitingValidation structure (used for trade tracking) -->
        <do_if value="not global.$GT_TradesAwaitingValidation?">
          <set_value name="global.$GT_TradesAwaitingValidation" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TradeStats structure (used for trade statistics) -->
        <do_if value="not global.$GT_TradeStats?">
          <set_value name="global.$GT_TradeStats" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <!-- Ensure TradeStats has default properties -->
        <do_if value="not global.$GT_TradeStats.$TotalTrades?">
          <set_value name="global.$GT_TradeStats.$TotalTrades" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_TradeStats.$TotalProfit?">
          <set_value name="global.$GT_TradeStats.$TotalProfit" exact="0"/>
        </do_if>
        
        <!-- Initialize global.$GT_RepairOrders structure (used for repair orders) -->
        <do_if value="not global.$GT_RepairOrders?">
          <set_value name="global.$GT_RepairOrders" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_ResupplyOrders structure (used for resupply orders) -->
        <do_if value="not global.$GT_ResupplyOrders?">
          <set_value name="global.$GT_ResupplyOrders" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_LastResupplyTime structure (used for resupply timing) -->
        <do_if value="not global.$GT_LastResupplyTime?">
          <set_value name="global.$GT_LastResupplyTime" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_MaintenanceOrders structure (used for maintenance orders) -->
        <do_if value="not global.$GT_MaintenanceOrders?">
          <set_value name="global.$GT_MaintenanceOrders" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_Pilots structure (core pilot registry - used throughout mod) -->
        <do_if value="not global.$GT_Pilots?">
          <set_value name="global.$GT_Pilots" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Stable-key index for pilot identity recovery (eject/rescue/rebind). -->
        <do_if value="not global.$GT_PilotsByStable?">
          <set_value name="global.$GT_PilotsByStable" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_Ships structure (core ship registry - used throughout mod) -->
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_FleetData structure (fleet coordination data) -->
        <do_if value="not global.$GT_FleetData?">
          <set_value name="global.$GT_FleetData" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_MarketData structure (market intelligence cache) -->
        <do_if value="not global.$GT_MarketData?">
          <set_value name="global.$GT_MarketData" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TerritoryData structure (territory management data) -->
        <do_if value="not global.$GT_TerritoryData?">
          <set_value name="global.$GT_TerritoryData" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_SessionStats structure (current session statistics) -->
        <do_if value="not global.$GT_SessionStats?">
          <set_value name="global.$GT_SessionStats" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_XPEventQueue structure (event queue for instant XP processing) -->
        <do_if value="not global.$GT_XPEventQueue?">
          <set_value name="global.$GT_XPEventQueue" exact="[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TrainingEventQueue structure (event queue for instant training processing) -->
        <do_if value="not global.$GT_TrainingEventQueue?">
          <set_value name="global.$GT_TrainingEventQueue" exact="[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_FleetEventQueue structure (event queue for instant fleet coordination) -->
        <do_if value="not global.$GT_FleetEventQueue?">
          <set_value name="global.$GT_FleetEventQueue" exact="[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_MarketEventQueue structure (event queue for instant market intelligence) -->
        <do_if value="not global.$GT_MarketEventQueue?">
          <set_value name="global.$GT_MarketEventQueue" exact="[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_ConfigEventQueue structure (configuration event queue) -->
        <do_if value="not global.$GT_ConfigEventQueue?">
          <set_value name="global.$GT_ConfigEventQueue" exact="[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_Reports structure (reporting system) -->
        <do_if value="not global.$GT_Reports?">
          <set_value name="global.$GT_Reports" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_ThreatIntelligence structure (threat intelligence system) -->
        <do_if value="not global.$GT_ThreatIntelligence?">
          <set_value name="global.$GT_ThreatIntelligence" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_ThreatCleanupTime structure (threat cleanup timing) -->
        <do_if value="not global.$GT_ThreatCleanupTime?">
          <set_value name="global.$GT_ThreatCleanupTime" exact="0"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_FailedSectorPairs structure (failed sector pairs tracking, per-sector) -->
        <do_if value="not global.$GT_FailedSectorPairs?">
          <set_value name="global.$GT_FailedSectorPairs" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_SearchLocks structure (search locking system) -->
        <do_if value="not global.$GT_SearchLocks?">
          <set_value name="global.$GT_SearchLocks" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_AIParameters structure (AI parameters per ship) -->
        <do_if value="not global.$GT_AIParameters?">
          <set_value name="global.$GT_AIParameters" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_SearchSemaphore structure (new scheduler queue) -->
        <do_if value="not global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TradesAwaitingValidationSearchMethod structure (trades awaiting validation search method tracking) -->
        <do_if value="not global.$GT_TradesAwaitingValidationSearchMethod?">
          <set_value name="global.$GT_TradesAwaitingValidationSearchMethod" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TS_OutputQueue structure (trade signal output queue) -->
        <do_if value="not global.$GT_TS_OutputQueue?">
          <set_value name="global.$GT_TS_OutputQueue" exact="table[
            $TradeFoundQueue = [],
            $TradeFoundQueued = table[],
            $TradeFoundProcessing = false
          ]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        <!-- Ensure nested structures exist -->
        <do_if value="not global.$GT_TS_OutputQueue.$TradeFoundQueue?">
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundQueue" exact="[]"/>
        </do_if>
        <do_if value="not global.$GT_TS_OutputQueue.$TradeFoundQueued?">
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundQueued" exact="table[]"/>
        </do_if>
        <!-- Reset processing flag if stuck (safeguard for crash/reload scenarios) -->
        <do_if value="global.$GT_TS_OutputQueue.$TradeFoundProcessing? and global.$GT_TS_OutputQueue.$TradeFoundProcessing">
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundProcessing" exact="false"/>
        </do_if>
        
        <!-- Initialize global.$GT_CargoCostTracking structure (cargo cost tracking) -->
        <do_if value="not global.$GT_CargoCostTracking?">
          <set_value name="global.$GT_CargoCostTracking" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_BuyCompleteQueue structure (buy completion queue) -->
        <do_if value="not global.$GT_BuyCompleteQueue?">
          <set_value name="global.$GT_BuyCompleteQueue" exact="[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_LastTradeScan structure (last trade scan timing) -->
        <do_if value="not global.$GT_LastTradeScan?">
          <set_value name="global.$GT_LastTradeScan" exact="0"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_CompetitorData structure (competitor data tracking) -->
        <do_if value="not global.$GT_CompetitorData?">
          <set_value name="global.$GT_CompetitorData" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_SectorAnalysis structure (sector analysis data) -->
        <do_if value="not global.$GT_SectorAnalysis?">
          <set_value name="global.$GT_SectorAnalysis" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_Territories structure (territories tracking) -->
        <do_if value="not global.$GT_Territories?">
          <set_value name="global.$GT_Territories" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_SectorExpertise structure (sector expertise tracking) -->
        <do_if value="not global.$GT_SectorExpertise?">
          <set_value name="global.$GT_SectorExpertise" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TradeCacheVersion structure (trade cache version tracking) -->
        <do_if value="not global.$GT_TradeCacheVersion?">
          <set_value name="global.$GT_TradeCacheVersion" exact="6"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Initialize global.$GT_TradeCacheLastCleanup structure (trade cache cleanup timing) -->
        <do_if value="not global.$GT_TradeCacheLastCleanup?">
          <set_value name="global.$GT_TradeCacheLastCleanup" exact="0"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Legacy batch migration marker removed in AI migration -->
        
        <!-- Initialize global.$GT_Applied_Mods structure (applied modifications tracking) -->
        <do_if value="not global.$GT_Applied_Mods?">
          <set_value name="global.$GT_Applied_Mods" exact="table[]"/>
          <set_value name="$initCount" exact="$initCount + 1"/>
        </do_if>
        
        <!-- Log initialization results -->
        <do_if value="$initCount gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Init] Initialized ' + $initCount + ' global table structure(s)'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Init] All global table structures already valid'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- CONFIGURATION MANAGEMENT -->
    <!-- Consolidated from: gt_configuration_manager.xml -->
    <!-- ========================================= -->
    
    <!-- Initialize Ship Configuration from Order Parameters -->
    <library name="Create_Ship_Config" purpose="run_actions">
      <params>
        <param name="order_params" comment="Order parameters from AI script"/>
        <param name="ship" comment="Ship to configure"/>
      </params>
      <actions>
        <set_value name="$config" exact="table[]"/>
        
        <!-- Extract and validate basic trading parameters -->
        <set_value name="$config.$Home" exact="$order_params.$home"/>
        <set_value name="$config.$MaxBuy" exact="$order_params.$maxbuy"/>
        <set_value name="$config.$MaxSell" exact="$order_params.$maxsell"/>
        <set_value name="$config.$AllowIllegal" exact="$order_params.$allowillegal"/>
        <set_value name="$config.$EnforceRouteIllegalLegality" exact="if $order_params.$enforceRouteIllegalLegality? then $order_params.$enforceRouteIllegalLegality else false"/>
        <set_value name="$config.$DistancePenalty" exact="$order_params.$distancepenalty"/>
        <set_value name="$config.$CargoTarget" exact="$order_params.$cargotarget"/>
        <set_value name="$config.$MarketUpdateFreq" exact="$order_params.$marketupdatefreq"/>
        <set_value name="$config.$AutoWares" exact="$order_params.$autowares"/>
        <set_value name="$config.$WareBasket" exact="$order_params.$warebasket"/>
        <set_value name="$config.$PriorityWares" exact="if $order_params.$prioritywares? then $order_params.$prioritywares else []"/>
        <set_value name="$config.$PriorityScoreMultiplier" exact="if $order_params.$priorityscoremultiplier? then $order_params.$priorityscoremultiplier else 125"/>
        <set_value name="$config.$Notifications" exact="$order_params.$notifications"/>
        <set_value name="$config.$DebugLevel" exact="$order_params.$debuglevel"/>
        <set_value name="$config.$TradeEval" exact="$order_params.$tradeeval"/>
        
        <!-- Apply global settings with fallbacks -->
        <run_actions ref="md.GT_Configuration.Apply_Global_Settings">
          <param name="config" value="$config"/>
        </run_actions>
        
        <!-- Calculate skill-based parameters -->
        <run_actions ref="md.GT_Configuration.Apply_Skill_Based_Config">
          <param name="config" value="$config"/>
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Generate ware list if auto-wares enabled (use all compatible wares) -->
        <do_if value="$config.$AutoWares">
          <!-- Auto-wares: Use empty list = trade all compatible wares -->
          <set_value name="$config.$WareBasket" exact="[]"/>
        </do_if>
        
        <!-- Validate configuration -->
        <run_actions ref="md.GT_Configuration.Validate_Ship_Config">
          <param name="config" value="$config"/>
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Log configuration summary for debugging -->
        <run_actions ref="md.GT_Libraries_General.Log_Configuration_Summary">
          <param name="ship" value="$ship"/>
          <param name="config" value="$config"/>
          <param name="debug_level" value="1"/>
        </run_actions>
        
        <set_value name="this.$result" exact="$config"/>
      </actions>
    </library>
    
    <!-- Apply Global Settings to Ship Configuration -->
    <library name="Apply_Global_Settings">
      <params>
        <param name="config" comment="Ship configuration to update"/>
      </params>
      <actions>
        <!-- XP System Settings -->
        <set_value name="$config.$AutoTraining" exact="@global.$GT_GlobalSettings.$XP.$AutoTraining"/>
        <do_if value="not $config.$AutoTraining?">
          <set_value name="$config.$AutoTraining" exact="true"/>
        </do_if>
        
        <!-- Fleet Coordination Settings -->
        <set_value name="$config.$FleetCoordination" exact="@global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination"/>
        <do_if value="not $config.$FleetCoordination?">
          <set_value name="$config.$FleetCoordination" exact="true"/>
        </do_if>
        
        <!-- Cache settings are read directly from global.$GT_GlobalSettings.$Fleet by AI scripts -->
        
        <!-- Debug Settings Override -->
        <set_value name="$globalDebugLevel" exact="@global.$GT_GlobalSettings.$Debug.$DebugLevel"/>
        <do_if value="$globalDebugLevel?">
          <set_value name="$config.$DebugLevel" exact="$globalDebugLevel"/>
        </do_if>
        
        <set_value name="this.$result" exact="true"/>
      </actions>
    </library>
    
    <!-- Apply Skill-Based Configuration -->
    <library name="Apply_Skill_Based_Config">
      <params>
        <param name="config" comment="Ship configuration to update"/>
        <param name="ship" comment="Ship to analyze"/>
      </params>
      <actions>
        <!-- Calculate skill level -->
        <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level" result="$skillInfo">
          <param name="ship" value="$ship"/>
          <param name="use_md_system" value="true"/>
        </run_actions>
        
        <!-- Calculate jump distance based on skill -->
        <run_actions ref="md.GT_Ship_Management.Calculate_Jump_Distance" result="$jumpDistance">
          <param name="skill_level" value="$skillInfo.$Level"/>
        </run_actions>
        
        <!-- Apply skill-based limits -->
        <set_value name="$config.$SkillLevel" exact="$skillInfo.$Level"/>
        <set_value name="$config.$MaxBuyDistance" exact="[$config.$MaxBuy, $jumpDistance].min"/>
        <set_value name="$config.$MaxSellDistance" exact="[$config.$MaxSell, $jumpDistance].min"/>
        <set_value name="$config.$SkillBasedJumpLimit" exact="$jumpDistance"/>
        <set_value name="$config.$UsingMDSkill" exact="$skillInfo.$UsingMDSystem"/>
        
        <!-- Store skill information for debugging -->
        <set_value name="$config.$SkillInfo" exact="$skillInfo"/>
        
        <set_value name="this.$result" exact="true"/>
      </actions>
    </library>
    
    <!-- Validate Ship Configuration -->
    <library name="Validate_Ship_Config">
      <params>
        <param name="config" comment="Ship configuration to validate"/>
        <param name="ship" comment="Ship to validate for"/>
      </params>
      <actions>
        <set_value name="$errors" exact="[]"/>
        <set_value name="$warnings" exact="[]"/>
        
        <!-- Validate jump distances -->
        <do_if value="$config.$MaxBuyDistance le 0">
          <append_to_list name="$errors" exact="'MaxBuyDistance must be greater than 0'"/>
        </do_if>
        
        <do_if value="$config.$MaxSellDistance le 0">
          <append_to_list name="$errors" exact="'MaxSellDistance must be greater than 0'"/>
        </do_if>
        
        <!-- Validate ware basket -->
        <do_if value="$config.$WareBasket.count == 0">
          <append_to_list name="$warnings" exact="'No compatible wares found for this ship'"/>
        </do_if>
        
        <!-- Validate risk tolerance -->
        <do_if value="$config.$RiskTolerance lt 0 or $config.$RiskTolerance gt 100">
          <append_to_list name="$errors" exact="'RiskTolerance must be between 0 and 100'"/>
        </do_if>
        
        <!-- Store validation results -->
        <set_value name="$config.$ValidationErrors" exact="$errors"/>
        <set_value name="$config.$ValidationWarnings" exact="$warnings"/>
        <set_value name="$config.$IsValid" exact="$errors.count == 0"/>
        
        <set_value name="this.$result" exact="$config.$IsValid"/>
      </actions>
    </library>
    
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Context_Academy" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <!--
    Fleet Academy context-menu integration.
    Spec: DOCS/Spec/FEATURE_FLEET_ACADEMY.md

    Flow:
      1. AddAcademyAction listens to Interact_Menu_API.Get_Actions and adds
         the top-level "Trading Academy" entry on player-owned GT-service ships
         whose pilot is below the highest course's target level.
      2. GT_AcademyAction publishes pilot/player context to the player NPC
         blackboard and raises gt.openAcademyContext for the Lua submenu.
      3. The Lua submenu computes personalized cost/duration with the
         quadratic curve + floors and signals back via
         gt_academy_course_chosen with locked-in numeric values.
      4. HandleAcademyCourseChosen overrides any in-flight training, stores
         $AcademyEnrollment, and queues manual training. The existing
         HandleTrainingNeeded pipeline finds a station and dispatches the
         DockAndTrain order; HandleStartTraining (and InitiateTraining for
         player-piloted ships) consumes $AcademyEnrollment to apply the
         locked-in cost and duration when the ship reaches the dock.
  -->
  <cues>

    <!-- ============================================================== -->
    <!-- Add "Trading Academy" entry to the right-click context menu     -->
    <!-- ============================================================== -->
    <cue name="AddAcademyAction" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Interact_Menu_API.Get_Actions"/>
      </conditions>
      <actions>
        <set_value name="$target" exact="event.param.$object"/>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>

        <!-- Early exit for non-player ships / vanilla XP mode (matches AddRenameAction pattern) -->
        <do_if value="$target.isclass.{class.ship} and $target.isplayerowned and not $useVanillaXPOnly and global.$GT_Config? and global.$GT_Config.$Academy? and global.$GT_Config.$Academy.$Enabled">
          <run_actions ref="md.GLX_Lib_Orders.GLX_ShipIsInGTService" result="$isGTService">
            <param name="ship" value="$target"/>
          </run_actions>
          <do_if value="$isGTService and $target.pilot?">
            <set_value name="$pilot" exact="$target.pilot"/>
            <set_value name="$pilotLevel" exact="1"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Level?">
              <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
            </do_if>

            <!-- Find the highest target level across all configured courses.
                 Hide the entire menu entry if the pilot already meets/exceeds it
                 (no point showing a menu where every course is filtered out). -->
            <set_value name="$maxCourseLevel" exact="0"/>
            <do_all exact="global.$GT_Config.$Academy.$Courses.count" counter="$i">
              <do_if value="global.$GT_Config.$Academy.$Courses.{$i}.$TargetLevel gt $maxCourseLevel">
                <set_value name="$maxCourseLevel" exact="global.$GT_Config.$Academy.$Courses.{$i}.$TargetLevel"/>
              </do_if>
            </do_all>

            <do_if value="$pilotLevel lt $maxCourseLevel">
              <signal_cue_instantly
                cue="md.Interact_Menu_API.Add_Action"
                param="table[
                  $id       = 'gt_mk3_academy',
                  $text     = {77000,9910},
                  $section  = 'gt_actions',
                  $callback = GT_AcademyAction
                ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT Academy] Added context entry for ship ' + $target.idcode + ' (pilot lvl ' + $pilotLevel + ', max course lvl ' + $maxCourseLevel + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- ============================================================== -->
    <!-- Player clicked "Trading Academy" - publish context, open Lua    -->
    <!-- ============================================================== -->
    <cue name="GT_AcademyAction" instantiate="true" namespace="this">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$component" exact="event.param.$object"/>
        <!-- MD requires <return/> at top level of <actions>; use do_if/do_else to early-out. -->
        <do_if value="not $component? or not $component.pilot?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Academy] GT_AcademyAction aborted: missing component or pilot'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <set_value name="$pilot" exact="$component.pilot"/>
          <set_value name="$pilotLevel" exact="1"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Level?">
            <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
          </do_if>

          <!-- Stash everything Lua needs on the player NPC blackboard -->
          <set_value name="player.entity.$GT_Academy_PilotLevel"  exact="$pilotLevel"/>
          <set_value name="player.entity.$GT_Academy_PlayerMoney" exact="player.money"/>
          <set_value name="player.entity.$GT_Academy_PilotName"   exact="$pilot.name"/>
          <set_value name="player.entity.$GT_Academy_ShipName"    exact="$component.knownname"/>

          <!-- Build a serializable course list (Lua-friendly: no nested tables of objects) -->
          <create_list name="$courseList"/>
          <do_all exact="global.$GT_Config.$Academy.$Courses.count" counter="$i">
            <set_value name="$course" exact="global.$GT_Config.$Academy.$Courses.{$i}"/>
            <append_to_list name="$courseList" exact="table[
              $Index          = $i,
              $TargetLevel    = $course.$TargetLevel,
              $ListedCost     = $course.$ListedCost,
              $ListedDuration = $course.$ListedDuration,
              $TextId         = $course.$TextId
            ]"/>
          </do_all>
          <set_value name="player.entity.$GT_Academy_Courses" exact="$courseList"/>
          <set_value name="player.entity.$GT_Academy_MinCostPercent" exact="global.$GT_Config.$Academy.$MinCostPercent"/>
          <set_value name="player.entity.$GT_Academy_MinDuration"    exact="global.$GT_Config.$Academy.$MinDuration"/>
          <set_value name="player.entity.$GT_Academy_CostExponent"   exact="global.$GT_Config.$Academy.$CostExponent"/>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Academy] Opening academy submenu for pilot ' + $pilot.name + ' (lvl ' + $pilotLevel + ', courses=' + $courseList.count + ')'" chance="100"/>
          </do_if>

          <raise_lua_event name="'gt.openAcademyContext'" param="$component"/>
        </do_else>
      </actions>
    </cue>

    <!-- ============================================================== -->
    <!-- Lua signals back the chosen course - process the enrollment.    -->
    <!-- ============================================================== -->
    <!-- The Lua side writes the selection to the player NPC blackboard:   -->
    <!--   $GT_Academy_ChosenIndex     = course index in $GT_Config.$Academy.$Courses -->
    <!--   $GT_Academy_ChosenLevel     = target level                       -->
    <!--   $GT_Academy_ChosenCost      = locked-in cost (Cr in raw units)   -->
    <!--   $GT_Academy_ChosenDuration  = locked-in duration in seconds      -->
    <!-- and signals 'gt_academy_course_chosen' with the ship as event.param2. -->
    <cue name="HandleAcademyCourseChosen" instantiate="true">
      <conditions>
        <event_object_signalled object="player.entity" param="'gt_academy_course_chosen'"/>
      </conditions>
      <actions>
        <!-- MD requires <return/> at top level of <actions>; we use a $abort flag
             (set inside guards) and gate every subsequent step on "not $abort"
             so failed validations short-circuit cleanly without nested <return/>s. -->
        <set_value name="$ship" exact="event.param2"/>
        <set_value name="$abort" exact="false"/>

        <do_if value="not $ship? or not $ship.pilot?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Academy] HandleAcademyCourseChosen aborted: missing ship or pilot'" chance="100"/>
          </do_if>
          <set_value name="$abort" exact="true"/>
        </do_if>

        <do_if value="not $abort">
          <set_value name="$pilot"          exact="$ship.pilot"/>
          <set_value name="$targetLevel"    exact="player.entity.$GT_Academy_ChosenLevel"/>
          <set_value name="$lockedCost"     exact="player.entity.$GT_Academy_ChosenCost"/>
          <set_value name="$lockedDuration" exact="player.entity.$GT_Academy_ChosenDuration"/>

          <!-- Defensive validation: verify the ship is still a GT service candidate -->
          <run_actions ref="md.GLX_Lib_Orders.GLX_ShipIsInGTService" result="$isGTService">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="not $isGTService">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Academy] Enrollment rejected: ship ' + $ship.idcode + ' is no longer in GT service'" chance="100"/>
            </do_if>
            <set_value name="$abort" exact="true"/>
          </do_if>
        </do_if>

        <do_if value="not $abort">
          <!-- Make sure the pilot has a registry entry; create one if missing -->
          <do_if value="not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}?">
            <run_actions ref="md.GT_Ship_Management.Register_Pilot">
              <param name="pilot" value="$pilot"/>
              <param name="ship"  value="$ship"/>
            </run_actions>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}?">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Academy] Enrollment aborted: pilot registry missing for ' + $pilot.name + ' even after register call'" chance="100"/>
            </do_if>
            <set_value name="$abort" exact="true"/>
          </do_if>
        </do_if>

        <do_if value="not $abort">
          <!-- Validate target-level vs current level (defense in depth; Lua already filters) -->
          <set_value name="$pilotLevel" exact="1"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$Level?">
            <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
          </do_if>
          <do_if value="$targetLevel le $pilotLevel">
            <show_notification text="{77000,9922}.[$pilot.name]" timeout="6s" priority="6"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Academy] Enrollment rejected: target lvl ' + $targetLevel + ' le pilot lvl ' + $pilotLevel" chance="100"/>
            </do_if>
            <set_value name="$abort" exact="true"/>
          </do_if>
        </do_if>

        <do_if value="not $abort">
          <!-- Validate funds (player may have spent credits between menu open and click) -->
          <do_if value="player.money lt $lockedCost">
            <show_notification text="{77000,9921}.[$lockedCost / 100, player.money / 100]" timeout="6s" priority="7"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Academy] Enrollment rejected: insufficient funds (need ' + ($lockedCost / 100) + ' Cr, have ' + (player.money / 100) + ' Cr)'" chance="100"/>
            </do_if>
            <set_value name="$abort" exact="true"/>
          </do_if>
        </do_if>

        <do_if value="not $abort">
          <!-- Override any in-flight training (override-policy choice) -->
          <do_if value="global.$GT_Pilots.{$pilot}.$TrainingState? and global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress'">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Academy] Overriding in-flight training for pilot ' + $pilot.name" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Abort_Training'" param2="table[
              $Pilot  = $pilot,
              $Ship   = $ship,
              $Reason = 'academy_override'
            ]"/>
          </do_if>

          <!-- Stamp academy markers so HandleStartTraining (canonical path
               via the AI script's GT_Start_Training signal) and the legacy
               InitiateTraining cue (player-avatar dock) both consume the
               locked-in cost/duration instead of the natural ladder. -->
          <set_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment" exact="table[
            $Level    = $targetLevel,
            $Cost     = $lockedCost,
            $Duration = $lockedDuration,
            $StartedAt = player.age
          ]"/>

          <!-- The completion handler reads $PendingSkillLevel to actually apply
               the new skill rank (see HandleCompleteTraining / ProcessTrainingEvents). -->
          <set_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel" exact="$targetLevel"/>

          <!-- Mark the pilot as needing training at the academy target level
               (this is what the existing pipeline reads to know what to do). -->
          <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
            <param name="pilot"         value="$pilot"/>
            <param name="level"         value="$targetLevel"/>
            <param name="set_xpblocked" value="true"/>
          </run_actions>

          <set_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested" exact="true"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'manual_training_queued'"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt"/>

          <!-- User-facing notification + logbook -->
          <show_notification text="{77000,9920}.[$pilot.name, $targetLevel]" timeout="8s" priority="7"/>

          <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$logbookEnabled">
            <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
              <param name="Message"     value="{77000,9923}.[$pilot.name, $targetLevel, $lockedCost / 100, $lockedDuration / 60s, $ship.knownname]"/>
              <param name="Category"    value="'upkeep'"/>
              <param name="Title"       value="'Trading Academy: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
              <param name="Object"      value="$ship"/>
              <param name="Interaction" value="'showonmap'"/>
              <param name="CheckGlobalSettings" value="false"/>
            </run_actions>
          </do_if>

          <!-- Kick the existing training-needed pipeline immediately rather than
               waiting for the next monitoring loop iteration. -->
          <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
            $Ship  = $ship,
            $Pilot = $pilot
          ]" delay="500ms"/>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Academy] Enrolled pilot ' + $pilot.name + ' (ship ' + $ship.idcode + ') in lvl ' + $targetLevel + ' course (cost: ' + ($lockedCost / 100) + ' Cr, duration: ' + ($lockedDuration / 60s) + ' min)'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Context_Diagnose" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ============================================================ -->
    <!-- GT DIAGNOSE - Context Menu Integration                        -->
    <!-- Registers "GT Diagnose" on player ships with GT order.       -->
    <!-- When clicked, runs an exhaustive diagnostic and sends the    -->
    <!-- result to Lua for display in a scrollable report.            -->
    <!-- ============================================================ -->

    <!-- Register custom action group "GalaxyTrader" in the interact menu -->
    <!-- This creates a separate section for all GT actions, keeping them out of vanilla -->
    <cue name="RegisterGTActionGroup" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'Interact_Menu_API'" control="'reloaded'"/>
      </conditions>
      <actions>
        <raise_lua_event name="'Interact_Menu_API.Add_Custom_Actions_Group_Id'" param="'gt_actions'"/>
        <raise_lua_event name="'Interact_Menu_API.Add_Custom_Actions_Group_Text'" param="'GalaxyTrader'"/>
      </actions>
    </cue>

    <!-- Register "GT Diagnose" in the interact menu -->
    <cue name="AddDiagnoseAction" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Interact_Menu_API.Get_Actions"/>
      </conditions>
      <actions>
        <set_value name="$target" exact="event.param.$object"/>
        <!-- Only for player-owned ships with GT order -->
        <do_if value="$target.isclass.{class.ship} and $target.isplayerowned">
          <!-- Check if this ship has GT order -->
          <set_value name="$hasGTOrder" exact="false"/>
          <do_if value="global.$GT_ProtectedOrderIDs? and $target.defaultorder? and (global.$GT_ProtectedOrderIDs.indexof.{@$target.defaultorder.id} or (@$target.defaultorder.id == 'Assist' and $target.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$target.defaultorder.$baseorder.id}))">
            <set_value name="$hasGTOrder" exact="true"/>
          </do_if>
          <do_elseif value="$target.commander? and $target.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$target.commander.defaultorder.id} or (@$target.commander.defaultorder.id == 'Assist' and $target.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$target.commander.defaultorder.$baseorder.id}))">
            <set_value name="$hasGTOrder" exact="true"/>
          </do_elseif>
          
          <do_if value="$hasGTOrder">
            <signal_cue_instantly
              cue="md.Interact_Menu_API.Add_Action"
              param="table[
                $id         = 'gt_mk3_diagnose',
                $text       = 'GT Diagnose',
                $section    = 'gt_actions',
                $callback   = GT_DiagnoseAction,
              ]"/>

            <!-- Add Redistribute Pilots action for GT fleet commanders -->
            <do_if value="$target.allsubordinates? and @$target.allsubordinates.count gt 0 and $target.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$target.defaultorder.id} or (@$target.defaultorder.id == 'Assist' and $target.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$target.defaultorder.$baseorder.id}))">
              <signal_cue_instantly
                cue="md.Interact_Menu_API.Add_Action"
                param="table[
                  $id         = 'gt_mk3_redistribute_pilots',
                  $text       = 'Redistribute Pilots',
                  $section    = 'gt_actions',
                  $callback   = GT_RedistributePilotsAction,
                ]"/>
            </do_if>

            <!-- Add Promote action for GT subordinates -->
            <do_if value="$target.commander? and $target.commander.exists and $target.commander != $target">
              <set_value name="$isGTSubordinate" exact="false"/>
              <do_if value="$target.defaultorder? and @$target.defaultorder.id == 'Assist' and $target.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$target.commander.defaultorder.id} or (@$target.commander.defaultorder.id == 'Assist' and $target.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$target.commander.defaultorder.$baseorder.id}))">
                <set_value name="$isGTSubordinate" exact="true"/>
              </do_if>
              <do_elseif value="global.$GT_Ships? and global.$GT_Ships.{$target}? and global.$GT_Ships.{$target.commander}? and $target.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$target.commander.defaultorder.id} or (@$target.commander.defaultorder.id == 'Assist' and $target.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$target.commander.defaultorder.$baseorder.id}))">
                <set_value name="$isGTSubordinate" exact="true"/>
              </do_elseif>

              <do_if value="$isGTSubordinate">
                <signal_cue_instantly
                  cue="md.Interact_Menu_API.Add_Action"
                  param="table[
                    $id         = 'gt_mk3_promote_subordinate',
                    $text       = 'Promote',
                    $section    = 'gt_actions',
                    $callback   = GT_PromoteSubordinateAction,
                  ]"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Handle fleet pilot redistribution request from commander context menu -->
    <cue name="GT_RedistributePilotsAction" instantiate="true" namespace="this">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$commander" exact="event.param.$object"/>
        <set_value name="$canRun" exact="true"/>
        <do_if value="not $commander? or not $commander.exists or not $commander.allsubordinates? or @$commander.allsubordinates.count lt 1">
          <show_notification text="'[GT] Redistribute Pilots unavailable: no eligible subordinates found.'" timeout="5s" priority="6"/>
          <set_value name="$canRun" exact="false"/>
        </do_if>

        <do_if value="$canRun">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Redistribute] Requested for commander ' + $commander.idcode + ' with ' + @$commander.allsubordinates.count + ' subordinates'" chance="100"/>
          </do_if>

          <raise_lua_event name="'gt.redistributePilots'" param="$commander"/>
        </do_if>
      </actions>
    </cue>

    <!-- Receive lightweight miner diagnostics snapshots from GalaxyMiner AI -->
    <cue name="HandleMinerDiagUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Miner_Diag_Update'"/>
      </conditions>
      <actions>
        <set_value name="$diagData" exact="event.param2"/>
        <do_if value="$diagData? and $diagData.$Ship?">
          <do_if value="not global.$GT_MinerDiag?">
            <set_value name="global.$GT_MinerDiag" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_MinerDiag.{$diagData.$Ship}" exact="$diagData"/>
        </do_if>
      </actions>
    </cue>

    <!-- Handle when user clicks "GT Diagnose" -->
    <cue name="GT_DiagnoseAction" instantiate="true" namespace="this">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param.$object"/>
        <debug_text text="'[GT Diagnose] === DIAGNOSTIC STARTED for ship ' + $ship.idcode + ' ==='" chance="100"/>

        <!-- Notify player that diagnosis is running -->
        <show_notification text="'GT Diagnose: Generating report for ' + $ship.knownname + '...'" timeout="5s"/>

        <!-- ======================================================== -->
        <!-- SECTION 1: Ship State Summary                            -->
        <!-- ======================================================== -->
        <set_value name="$report" exact="table[]"/>
        <set_value name="$report.$Timestamp" exact="player.age"/>
        <set_value name="$report.$ShipId" exact="$ship.idcode"/>
        <set_value name="$report.$ShipName" exact="$ship.knownname"/>
        <set_value name="$report.$Sections" exact="[]"/>

        <set_value name="$sec1" exact="table[]"/>
        <set_value name="$sec1.$Name" exact="'Ship State'"/>
        <set_value name="$sec1.$Rows" exact="[]"/>

        <!-- Mod version (global set at load in gt_configuration ConfigInitV3; appears below VERDICT rows) -->
        <set_value name="$modVersionDetail" exact="'unknown'"/>
        <do_if value="global.$GT_ModVersion?">
          <set_value name="$modVersionDetail" exact="global.$GT_ModVersion"/>
          <do_if value="global.$GT_ModContentVersion?">
            <set_value name="$modVersionDetail" exact="$modVersionDetail + ' (content.xml: ' + global.$GT_ModContentVersion + ')'"/>
          </do_if>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Mod Version', $Status = 'INFO', $Detail = $modVersionDetail]"/>

        <!-- Ship basics -->
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Ship ID', $Status = 'INFO', $Detail = $ship.idcode]"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Ship Name', $Status = 'INFO', $Detail = $ship.knownname]"/>
        
        <!-- Pilot -->
        <set_value name="$pilotName" exact="'No Pilot'"/>
        <set_value name="$skillLevel" exact="1"/>
        <do_if value="$ship.pilot?">
          <set_value name="$pilotName" exact="$ship.pilot.name"/>
          <do_if value="global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
            <set_value name="$skillLevel" exact="global.$GT_Pilots.{$ship.pilot}.$Level"/>
          </do_if>
          <do_else>
            <do_if value="$ship.pilot.skill.management?">
              <set_value name="$skillLevel" exact="$ship.pilot.skill.management"/>
            </do_if>
          </do_else>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Pilot', $Status = 'INFO', $Detail = $pilotName]"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Skill Level', $Status = 'INFO', $Detail = '' + $skillLevel]"/>

        <!-- GT Order -->
        <set_value name="$orderStatus" exact="'MISSING'"/>
        <set_value name="$orderResult" exact="'FAIL'"/>
        <do_if value="global.$GT_ProtectedOrderIDs? and $ship.defaultorder? and (global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id} or (@$ship.defaultorder.id == 'Assist' and $ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.$baseorder.id}))">
          <set_value name="$orderStatus" exact="'Active (direct)'"/>
          <set_value name="$orderResult" exact="'PASS'"/>
        </do_if>
        <do_elseif value="$ship.commander? and $ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id} or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.$baseorder.id}))">
          <set_value name="$orderStatus" exact="'Active (via commander ' + $ship.commander.knownname + ')'"/>
          <set_value name="$orderResult" exact="'PASS'"/>
        </do_elseif>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'GT Order', $Status = $orderResult, $Detail = $orderStatus]"/>

        <!-- MK3/MK4 Custom Faction Blacklist (commander + subordinate inheritance) -->
        <set_value name="$mk3BlacklistApplies" exact="false"/>
        <set_value name="$mk3BlacklistOwner" exact="null"/>
        <set_value name="$mk3BlacklistOwnerDetail" exact="'N/A (MK3/MK4 only)'"/>
        <do_if value="$ship.defaultorder? and (@$ship.defaultorder.id == 'GalaxyTraderMK3' or @$ship.defaultorder.id == 'GalaxyTraderMK4Supply' or @$ship.defaultorder.id == 'GalaxyTraderMK4Supply2')">
          <set_value name="$mk3BlacklistApplies" exact="true"/>
          <set_value name="$mk3BlacklistOwner" exact="$ship"/>
          <set_value name="$mk3BlacklistOwnerDetail" exact="'Self (' + $ship.idcode + ')'"/>
        </do_if>
        <do_elseif value="$ship.commander? and $ship.commander.exists and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK3' or @$ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply' or @$ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and (@$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2')))">
          <set_value name="$mk3BlacklistApplies" exact="true"/>
          <set_value name="$mk3BlacklistOwner" exact="$ship.commander"/>
          <set_value name="$mk3BlacklistOwnerDetail" exact="'Commander ' + $ship.commander.idcode"/>
        </do_elseif>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Custom Blacklist Owner', $Status = if $mk3BlacklistApplies then 'INFO' else 'WARN', $Detail = $mk3BlacklistOwnerDetail]"/>

        <set_value name="$mk3BlockedCount" exact="0"/>
        <set_value name="$mk3BlacklistActive" exact="false"/>
        <set_value name="$mk3BlockedListText" exact="''"/>
        <do_if value="$mk3BlacklistApplies and $mk3BlacklistOwner? and global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}?">
          <set_value name="$mk3BlockedFactions" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}.keys.list"/>
          <set_value name="$mk3BlockedCount" exact="$mk3BlockedFactions.count"/>
          <set_value name="$mk3BlacklistActive" exact="$mk3BlockedCount gt 0"/>
          <do_if value="$mk3BlockedCount gt 0">
            <do_all exact="$mk3BlockedFactions.count" counter="$fbli">
              <set_value name="$bf" exact="$mk3BlockedFactions.{$fbli}"/>
              <set_value name="$bfName" exact="if $bf? and $bf.name? and $bf.name != '' then $bf.name else 'Unknown Faction'"/>
              <set_value name="$bfShort" exact="if $bf? and $bf.shortname? and $bf.shortname != '' then $bf.shortname else (if $bf? and $bf.id? and $bf.id != '' then $bf.id else '')"/>
              <set_value name="$bfDisplay" exact="if $bfShort != '' then ($bfShort + ' - ' + $bfName) else $bfName"/>
              <do_if value="$mk3BlockedListText == ''">
                <set_value name="$mk3BlockedListText" exact="$bfDisplay"/>
              </do_if>
              <do_else>
                <set_value name="$mk3BlockedListText" exact="$mk3BlockedListText + ', ' + $bfDisplay"/>
              </do_else>
            </do_all>
          </do_if>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Custom Blacklist Active', $Status = if not $mk3BlacklistApplies then 'INFO' else if $mk3BlacklistActive then 'WARN' else 'PASS', $Detail = if not $mk3BlacklistApplies then 'No (not an MK3/MK4 ship)' else if $mk3BlacklistActive then ('Yes (' + $mk3BlockedCount + ' factions blocked)') else 'No']"/>
        <do_if value="$mk3BlacklistApplies and $mk3BlacklistActive">
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Blocked Factions', $Status = 'INFO', $Detail = $mk3BlockedListText]"/>
        </do_if>

        <!-- Ship class / dock size -->
        <set_value name="$dockSize" exact="'Unknown'"/>
        <do_if value="$ship.islasertower">
          <set_value name="$dockSize" exact="'Laser Tower (no docking)'"/>
        </do_if>
        <do_elseif value="$ship.isclass.{class.ship_xs}">
          <set_value name="$dockSize" exact="'XS'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.{class.ship_s}">
          <set_value name="$dockSize" exact="'S'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.{class.ship_m}">
          <set_value name="$dockSize" exact="'M'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.{class.ship_l}">
          <set_value name="$dockSize" exact="'L'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.{class.ship_xl}">
          <set_value name="$dockSize" exact="'XL'"/>
        </do_elseif>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Dock Size', $Status = 'INFO', $Detail = $dockSize]"/>

        <!-- Current sector -->
        <set_value name="$currentSectorName" exact="'Unknown'"/>
        <do_if value="$ship.sector?">
          <set_value name="$currentSectorName" exact="$ship.sector.knownname"/>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Current Sector', $Status = 'INFO', $Detail = $currentSectorName]"/>

        <!-- Early order id probe (the authoritative $orderId is resolved later in section 3,
             but the home-sector display + verdict need to know whether home is mandatory for
             this order type; MK2 routes via explicit source/dest station lists and therefore
             treats homeStation as optional). Mirrors the lightweight probe used at line ~502
             for the price-range section. -->
        <set_value name="$diagOrderId" exact="'Unknown'"/>
        <do_if value="$ship.defaultorder? and $ship.defaultorder.id?">
          <set_value name="$diagOrderId" exact="$ship.defaultorder.id"/>
        </do_if>
        <do_elseif value="$ship.commander? and $ship.commander.exists and $ship.commander.defaultorder? and $ship.commander.defaultorder.id?">
          <set_value name="$diagOrderId" exact="$ship.commander.defaultorder.id"/>
        </do_elseif>
        <set_value name="$homeSectorOptional" exact="$diagOrderId == 'GalaxyTraderMK2'"/>

        <!-- Home sector -->
        <set_value name="$homeSector" exact="null"/>
        <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$homeSector">
          <param name="ship" value="$ship"/>
        </run_actions>
        <set_value name="$homeSectorName" exact="'NONE'"/>
        <set_value name="$homeSectorResult" exact="'FAIL'"/>
        <do_if value="$homeSector? and $homeSector.exists">
          <set_value name="$homeSectorName" exact="$homeSector.knownname"/>
          <set_value name="$homeSectorResult" exact="'PASS'"/>
        </do_if>
        <do_elseif value="$homeSectorOptional">
          <!-- MK2 routes per source/dest station lists; missing homeStation is supported
               (param default is null) and must not be flagged as a failure. -->
          <set_value name="$homeSectorName" exact="'NONE (optional for MK2 - routed via source/destination lists)'"/>
          <set_value name="$homeSectorResult" exact="'INFO'"/>
        </do_elseif>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Home Sector', $Status = $homeSectorResult, $Detail = $homeSectorName]"/>

        <!-- Cargo -->
        <set_value name="$cargoFree" exact="$ship.cargo.free.all"/>
        <set_value name="$cargoCap" exact="$ship.cargo.capacity.all"/>
        <set_value name="$cargoUsed" exact="$cargoCap - $cargoFree"/>
        <set_value name="$cargoDetail" exact="$cargoUsed + ' / ' + $cargoCap + ' (Free: ' + $cargoFree + ')'"/>
        <set_value name="$cargoResult" exact="if $cargoFree gt 0 then 'PASS' else 'WARN'"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cargo', $Status = $cargoResult, $Detail = $cargoDetail]"/>

        <!-- Cargo hold transport types (container / solid / liquid) â€” determines which wares ship.cargo.{ware}.max allows -->
        <set_value name="$diagHoldTypes" exact="''"/>
        <do_if value="$ship.waretransport.indexof.{waretransport.container}">
          <set_value name="$diagHoldTypes" exact="if $diagHoldTypes != '' then $diagHoldTypes + ', container' else 'container'"/>
        </do_if>
        <do_if value="$ship.waretransport.indexof.{waretransport.solid}">
          <set_value name="$diagHoldTypes" exact="if $diagHoldTypes != '' then $diagHoldTypes + ', solid' else 'solid'"/>
        </do_if>
        <do_if value="$ship.waretransport.indexof.{waretransport.liquid}">
          <set_value name="$diagHoldTypes" exact="if $diagHoldTypes != '' then $diagHoldTypes + ', liquid' else 'liquid'"/>
        </do_if>
        <do_if value="$diagHoldTypes == ''">
          <set_value name="$diagHoldTypes" exact="'unknown (no waretransport flags)'"/>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cargo Hold Types', $Status = 'INFO', $Detail = $diagHoldTypes + ' â€” cache/live filters use ship.cargo.{ware}.max gt 0 per ware']"/>

        <!-- Registration -->
        <set_value name="$regResult" exact="'FAIL'"/>
        <set_value name="$regDetail" exact="'Ship NOT registered in global.$GT_Ships'"/>
        <do_if value="global.$GT_Ships.{$ship}?">
          <set_value name="$regResult" exact="'PASS'"/>
          <set_value name="$regDetail" exact="'Registered'"/>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Ship Registration', $Status = $regResult, $Detail = $regDetail]"/>

        <!-- Current Activity State (comprehensive GT state detection) -->
        <set_value name="$activityState" exact="'Unknown'"/>
        <set_value name="$activityDesc" exact="'Could not determine ship activity'"/>
        <set_value name="$activityStatus" exact="'INFO'"/>

        <!-- Check GT-specific state flags (priority order: most specific first) -->
        <set_value name="$shipData" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
        </do_if>

        <!-- Priority 1: Escaping (actively fleeing dangerous/blacklisted sector) -->
        <do_if value="$shipData? and $shipData.$Escaping? and $shipData.$Escaping">
          <set_value name="$activityState" exact="'ESCAPE'"/>
          <set_value name="$activityDesc" exact="'Ship is in a blacklisted or dangerous sector and is actively trying to leave. No trades will be searched until the ship reaches a safe sector.'"/>
          <set_value name="$activityStatus" exact="'WARN'"/>
        </do_if>

        <!-- Priority 2: Rerouting (destination threatened/blacklisted, finding alternative) -->
        <do_elseif value="$shipData? and $shipData.$Rerouting? and $shipData.$Rerouting">
          <set_value name="$activityState" exact="'REROUTE'"/>
          <set_value name="$activityDesc" exact="'Ship trade destination was threatened or blacklisted. Ship is searching for an alternative route or cancelling the current trade.'"/>
          <set_value name="$activityStatus" exact="'WARN'"/>
        </do_elseif>

        <!-- Priority 3: Clearance (selling existing cargo before normal trading) -->
        <do_elseif value="$shipData? and $shipData.$CargoDisposal? and $shipData.$CargoDisposal">
          <set_value name="$activityState" exact="'CLEARANCE'"/>
          <set_value name="$activityDesc" exact="'Ship has cargo from a previous session or order. It must sell all existing cargo before it can search for new buy trades. The ship is looking for the best buyer for its current cargo.'"/>
          <set_value name="$activityStatus" exact="'WARN'"/>
        </do_elseif>

        <!-- Priority 4: Needs Repair -->
        <do_elseif value="$shipData? and $shipData.$NeedsRepair? and $shipData.$NeedsRepair">
          <set_value name="$activityState" exact="'REPAIR'"/>
          <set_value name="$activityDesc" exact="'Ship is damaged and heading to a shipyard or equipment dock for repairs. Trading is paused until repairs are complete.'"/>
          <set_value name="$activityStatus" exact="'WARN'"/>
        </do_elseif>

        <!-- Priority 5: Check current active order for more context -->
        <do_else>
          <set_value name="$activeOrderId" exact="@$ship.order.id"/>
          <do_if value="global.$GT_ProtectedOrderIDs? and $activeOrderId? and global.$GT_ProtectedOrderIDs.indexof.{$activeOrderId}">
            <set_value name="$activityState" exact="'TRADING (GT Order Active)'"/>
            <set_value name="$activityDesc" exact="'Ship is actively running the GalaxyTrader order. It is either searching for trades, executing a trade (buying/selling), or waiting for a work unit from the scheduler.'"/>
            <set_value name="$activityStatus" exact="'PASS'"/>
          </do_if>
          <do_elseif value="$activeOrderId == 'TradePerform'">
            <set_value name="$activityState" exact="'EXECUTING TRADE'"/>
            <set_value name="$activityDesc" exact="'Ship is currently executing a trade order (buying or selling at a station). This is a sub-order created by GalaxyTrader.'"/>
            <set_value name="$activityStatus" exact="'PASS'"/>
          </do_elseif>
          <do_elseif value="$cargoUsed gt 0 and ($activeOrderId == 'TradeSell' or $activeOrderId == 'DockAt' or $activeOrderId == 'DockAndWait')">
            <set_value name="$activityMinerDelivering" exact="false"/>
            <do_if value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyMiner'">
              <set_value name="$activityMinerDelivering" exact="true"/>
            </do_if>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.exists and $ship.commander.defaultorder? and @$ship.commander.defaultorder.id == 'GalaxyMiner'">
              <set_value name="$activityMinerDelivering" exact="true"/>
            </do_elseif>
            <do_if value="$activityMinerDelivering">
              <set_value name="$activityState" exact="'DELIVERING CARGO'"/>
              <set_value name="$activityDesc" exact="'Galaxy Miner is executing a sell leg (' + $activeOrderId + ') with cargo on board â€” docking or trading at the buyer station.'"/>
              <set_value name="$activityStatus" exact="'PASS'"/>
            </do_if>
            <do_else>
              <set_value name="$activityState" exact="'OTHER ORDER: ' + $activeOrderId"/>
              <set_value name="$activityDesc" exact="'Ship is executing a non-GT order (' + $activeOrderId + '). This order may have been queued externally or by another mod.'"/>
              <set_value name="$activityStatus" exact="'INFO'"/>
            </do_else>
          </do_elseif>
          <do_elseif value="$activeOrderId == 'Equip' or $activeOrderId == 'Resupply'">
            <set_value name="$activityState" exact="'RESUPPLY'"/>
            <set_value name="$activityDesc" exact="'Ship is resupplying (ammunition, deployables, etc.) at a station. Trading resumes after resupply is complete.'"/>
            <set_value name="$activityStatus" exact="'INFO'"/>
          </do_elseif>
          <do_elseif value="$activeOrderId == 'Repair'">
            <set_value name="$activityState" exact="'REPAIR (Order)'"/>
            <set_value name="$activityDesc" exact="'Ship has an active repair order. It is heading to or being repaired at a shipyard/equipment dock.'"/>
            <set_value name="$activityStatus" exact="'WARN'"/>
          </do_elseif>
          <do_elseif value="$activeOrderId == 'DockAndWait'">
            <set_value name="$activityState" exact="'DOCKED / WAITING'"/>
            <set_value name="$activityDesc" exact="'Ship is docked at a station or waiting. This may indicate it is waiting for docking clearance or between trade cycles.'"/>
            <set_value name="$activityStatus" exact="'INFO'"/>
          </do_elseif>
          <do_elseif value="$activeOrderId == 'MoveToZone' or $activeOrderId == 'FlyToZone'">
            <set_value name="$activityState" exact="'IN TRANSIT'"/>
            <set_value name="$activityDesc" exact="'Ship is flying to a destination zone. It may be heading to a buy or sell station.'"/>
            <set_value name="$activityStatus" exact="'INFO'"/>
          </do_elseif>
          <do_elseif value="$activeOrderId?">
            <set_value name="$activityState" exact="'OTHER ORDER: ' + $activeOrderId"/>
            <set_value name="$activityDesc" exact="'Ship is executing a non-GT order (' + $activeOrderId + '). This order may have been queued externally or by another mod.'"/>
            <set_value name="$activityStatus" exact="'INFO'"/>
          </do_elseif>
          <do_else>
            <set_value name="$activityState" exact="'IDLE (No Active Order)'"/>
            <set_value name="$activityDesc" exact="'Ship has no active order. It may be waiting for the default order to kick in, or the GT order may not be properly assigned.'"/>
            <set_value name="$activityStatus" exact="'WARN'"/>
          </do_else>
        </do_else>

        <!-- Set clearance mode flag for dynamic tab display -->
        <set_value name="$isClearanceMode" exact="$activityState == 'CLEARANCE'"/>

        <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Current Activity ---', $Status = 'INFO', $Detail = '']"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Activity State', $Status = $activityStatus, $Detail = $activityState]"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Description', $Status = 'INFO', $Detail = $activityDesc]"/>

        <!-- Active order details -->
        <set_value name="$activeOrderDetail" exact="'None'"/>
        <do_if value="$ship.order?">
          <set_value name="$activeOrderDetail" exact="@$ship.order.id"/>
          <do_if value="$ship.order.state?">
            <set_value name="$activeOrderDetail" exact="$activeOrderDetail + ' (state: ' + $ship.order.state + ')'"/>
          </do_if>
        </do_if>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Active Order', $Status = 'INFO', $Detail = $activeOrderDetail]"/>

        <!-- Current cargo wares (relevant for clearance state) -->
        <do_if value="$cargoUsed gt 0">
          <set_value name="$cargoWareList" exact="''"/>
          <set_value name="$cargoWareCount" exact="0"/>
          <do_all exact="$ship.cargo.list.count" counter="$cwi">
            <set_value name="$cWare" exact="$ship.cargo.list.{$cwi}"/>
            <do_if value="$cWare? and $ship.cargo.{$cWare}.count gt 0">
              <set_value name="$cargoWareCount" operation="add"/>
              <do_if value="$cargoWareList != ''">
                <set_value name="$cargoWareList" exact="$cargoWareList + ', '"/>
              </do_if>
              <set_value name="$cargoWareList" exact="$cargoWareList + $cWare.name + ' x' + $ship.cargo.{$cWare}.count"/>
            </do_if>
          </do_all>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cargo Contents', $Status = 'INFO', $Detail = $cargoWareList]"/>
        </do_if>

        <!-- GT Status from registry -->
        <do_if value="$shipData? and $shipData.$Status?">
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'GT Registry Status', $Status = 'INFO', $Detail = '' + $shipData.$Status]"/>
        </do_if>

        <!-- Search Pipeline State (Fallback / Isolated flags) -->
        <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Search Pipeline ---', $Status = 'INFO', $Detail = '']"/>
        <set_value name="$pipelineState" exact="'Normal'"/>
        <set_value name="$pipelineResult" exact="'PASS'"/>
        <set_value name="$pipelineDesc" exact="'Ship is using the normal search pipeline with standard price ranges and full search radius.'"/>
        <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
          <set_value name="$pipelineState" exact="'ISOLATED'"/>
          <set_value name="$pipelineResult" exact="'WARN'"/>
          <set_value name="$pipelineDesc" exact="'Ship is isolated (all connected sectors blacklisted or unreachable). Using isolated price ranges (no filter) and searching only within current sector.'"/>
        </do_if>
        <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{$ship}?">
          <set_value name="$pipelineState" exact="'FALLBACK'"/>
          <set_value name="$pipelineResult" exact="'WARN'"/>
          <set_value name="$pipelineDesc" exact="'Normal search found no trades. Fallback active: searching near ship position with reduced radius (1/3 of normal), relaxed profit thresholds (ROI halved, min 100 Cr), and fallback price ranges. Trades still limited to home sector max distance.'"/>
        </do_elseif>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Search Pipeline', $Status = $pipelineResult, $Detail = $pipelineState]"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Pipeline Detail', $Status = 'INFO', $Detail = $pipelineDesc]"/>

        <!-- Training Gate Status (separate from pipeline state) -->
        <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Training Gate ---', $Status = 'INFO', $Detail = '']"/>
        <set_value name="$diagTrainingGateDetail" exact="'No pilot assigned'"/>
        <set_value name="$diagTrainingGateStatus" exact="'INFO'"/>
        <set_value name="$diagMustTrain" exact="false"/>
        <set_value name="$diagXPBlocked" exact="false"/>
        <set_value name="$diagBlockedLevel" exact="0"/>
        <do_if value="$ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
          <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$diagTrainingGate">
            <param name="pilot" value="$ship.pilot"/>
            <param name="ship" value="$ship"/>
            <param name="respect_hard_force" value="true"/>
          </run_actions>
          <set_value name="$diagMustTrain" exact="if $diagTrainingGate.$MustTrainNow? then $diagTrainingGate.$MustTrainNow else false"/>
          <set_value name="$diagXPBlocked" exact="if $diagTrainingGate.$XPBlocked? then $diagTrainingGate.$XPBlocked else false"/>
          <set_value name="$diagBlockedLevel" exact="if $diagTrainingGate.$BlockedLevel? then $diagTrainingGate.$BlockedLevel else 0"/>
          <set_value name="$diagHardForce" exact="if $diagTrainingGate.$HardForce? then $diagTrainingGate.$HardForce else false"/>
          <set_value name="$diagReason" exact="if $diagTrainingGate.$Reason? then $diagTrainingGate.$Reason else 'none'"/>
          <set_value name="$diagTrainingGateDetail" exact="'MustTrainNow=' + $diagMustTrain + ', XPBlocked=' + $diagXPBlocked + ', BlockedLevel=' + $diagBlockedLevel + ', HardForce=' + $diagHardForce + ', Reason=' + $diagReason"/>
          <do_if value="$diagMustTrain">
            <set_value name="$diagTrainingGateStatus" exact="'WARN'"/>
          </do_if>
          <do_elseif value="$diagBlockedLevel gt 1">
            <set_value name="$diagTrainingGateStatus" exact="'WARN'"/>
          </do_elseif>
          <do_elseif value="$diagXPBlocked">
            <set_value name="$diagTrainingGateStatus" exact="'WARN'"/>
          </do_elseif>
          <do_else>
            <set_value name="$diagTrainingGateStatus" exact="'PASS'"/>
          </do_else>
        </do_if>
        <do_elseif value="$ship.pilot">
          <set_value name="$diagTrainingGateDetail" exact="'Pilot is not in GT registry'"/>
          <set_value name="$diagTrainingGateStatus" exact="'WARN'"/>
        </do_elseif>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Training Block State', $Status = $diagTrainingGateStatus, $Detail = $diagTrainingGateDetail]"/>

        <!-- Training station candidates (same search as auto-training) when XP/training gate active -->
        <do_if value="$ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and ($diagXPBlocked or $diagMustTrain or ($diagBlockedLevel gt 1))">
          <run_actions ref="md.GT_Libraries_General.GT_DiagnoseTrainingStationCandidates" result="$diagTrainingStationReport">
            <param name="ship" value="$ship"/>
            <param name="maxFailureRows" value="30"/>
          </run_actions>
          <do_if value="$diagTrainingStationReport.$Rows? and $diagTrainingStationReport.$Rows.count gt 0">
            <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Training stations (auto search) ---', $Status = 'INFO', $Detail = '']"/>
            <do_all exact="$diagTrainingStationReport.$Rows.count" counter="$tsi">
              <append_to_list name="$sec1.$Rows" exact="$diagTrainingStationReport.$Rows.{$tsi}"/>
            </do_all>
          </do_if>
        </do_if>

        <!-- Show configured price ranges for the active pipeline -->
        <!-- Defaults: no filter (1.0 = max price, -1.0 = min price) - must be numeric for relativeprice filter -->
        <set_value name="$activeSellPriceMax" exact="1.0"/>
        <set_value name="$activeBuyPriceMin" exact="-1.0"/>
        <do_if value="global.$GT_Config? and global.$GT_Config.$Trading?">
          <do_if value="$pipelineState == 'ISOLATED'">
            <set_value name="$activeSellPriceMax" exact="if global.$GT_Config.$Trading.$IsolatedSellPriceMax? then @global.$GT_Config.$Trading.$IsolatedSellPriceMax else 1.0"/>
            <set_value name="$activeBuyPriceMin" exact="if global.$GT_Config.$Trading.$IsolatedBuyPriceMin? then @global.$GT_Config.$Trading.$IsolatedBuyPriceMin else -1.0"/>
          </do_if>
          <do_elseif value="$pipelineState == 'FALLBACK'">
            <set_value name="$activeSellPriceMax" exact="if global.$GT_Config.$Trading.$FallbackSellPriceMax? then @global.$GT_Config.$Trading.$FallbackSellPriceMax else 0.2"/>
            <set_value name="$activeBuyPriceMin" exact="if global.$GT_Config.$Trading.$FallbackBuyPriceMin? then @global.$GT_Config.$Trading.$FallbackBuyPriceMin else -0.2"/>
          </do_elseif>
          <do_else>
            <set_value name="$activeSellPriceMax" exact="if global.$GT_Config.$Trading.$SellPriceMax? then @global.$GT_Config.$Trading.$SellPriceMax else 1.0"/>
            <set_value name="$activeBuyPriceMin" exact="if global.$GT_Config.$Trading.$BuyPriceMin? then @global.$GT_Config.$Trading.$BuyPriceMin else -1.0"/>
          </do_else>
        </do_if>
        <!-- Resolve order id locally for this section (global $orderId is initialized later).
             Subordinates on Assist must unwrap $baseorder / commander GT order â€” same as sec3. -->
        <set_value name="$priceRangeOrderId" exact="'Unknown'"/>
        <set_value name="$priceRangeGtOrder" exact="@$ship.defaultorder"/>
        <do_if value="$ship.commander? and $ship.commander.exists">
          <do_if value="global.$GT_ProtectedOrderIDs? and $ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id} or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.$baseorder.id}))">
            <set_value name="$priceRangeGtOrder" exact="if @$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? then $ship.commander.defaultorder.$baseorder else $ship.commander.defaultorder"/>
          </do_if>
        </do_if>
        <do_if value="$priceRangeGtOrder? and $priceRangeGtOrder.id?">
          <set_value name="$priceRangeOrderId" exact="$priceRangeGtOrder.id"/>
        </do_if>
        <!-- MK4 runtime override: live search always uses full relative-price range. -->
        <do_if value="$priceRangeOrderId == 'GalaxyTraderMK4Supply' or $priceRangeOrderId == 'GalaxyTraderMK4Supply2'">
          <set_value name="$activeSellPriceMax" exact="1.0"/>
          <set_value name="$activeBuyPriceMin" exact="-1.0"/>
        </do_if>
        <!-- MK1 uses per-order Buyer Price Range slider (0-200 offset, 100 = neutral), not global MK3 settings. -->
        <set_value name="$mk1DiagPriceOffset" exact="90"/>
        <set_value name="$mk1DiagPriceNorm" exact="0"/>
        <do_if value="$priceRangeOrderId == 'GalaxyTraderMK1'">
          <do_if value="$priceRangeGtOrder? and $priceRangeGtOrder.$pricerange?">
            <do_if value="$priceRangeGtOrder.$pricerange ge 0 and $priceRangeGtOrder.$pricerange le 200">
              <set_value name="$mk1DiagPriceOffset" exact="$priceRangeGtOrder.$pricerange"/>
            </do_if>
            <do_elseif value="$priceRangeGtOrder.$pricerange ge -100 and $priceRangeGtOrder.$pricerange lt 0">
              <set_value name="$mk1DiagPriceOffset" exact="$priceRangeGtOrder.$pricerange + 100"/>
            </do_elseif>
          </do_if>
          <set_value name="$mk1DiagPriceOffset" exact="[$mk1DiagPriceOffset, 0].max"/>
          <set_value name="$mk1DiagPriceOffset" exact="[$mk1DiagPriceOffset, 200].min"/>
          <set_value name="$mk1DiagPriceNorm" exact="($mk1DiagPriceOffset - 100) / 100"/>
          <set_value name="$activeBuyPriceMin" exact="$mk1DiagPriceNorm"/>
          <set_value name="$activeSellPriceMax" exact="0 - $mk1DiagPriceNorm"/>
        </do_if>
        <do_if value="$priceRangeOrderId == 'GalaxyTraderMK1'">
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Active Price Range', $Status = 'INFO', $Detail = 'MK1 order slider ' + $mk1DiagPriceOffset + '/200 (100=neutral): buy min ' + ($mk1DiagPriceNorm * 100) + '%, supply sell max ' + ((0 - $mk1DiagPriceNorm) * 100) + '%']"/>
        </do_if>
        <do_else>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Active Price Range', $Status = 'INFO', $Detail = 'Sell max: ' + ($activeSellPriceMax * 100) + '%, Buy min: ' + ($activeBuyPriceMin * 100) + '%']"/>
        </do_else>

        <!-- ================================================ -->
        <!-- Blacklist Status                                  -->
        <!-- ================================================ -->
        <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Blacklist Status ---', $Status = 'INFO', $Detail = '']"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Note', $Status = 'INFO', $Detail = 'Sectors on Sector Whitelist (Config) are exempt from blacklist and show as Not blacklisted.']"/>

        <!-- Get blacklist group for this ship -->
        <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$diagBlacklistGroup">
          <param name="ship" value="$ship"/>
        </run_actions>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Blacklist Group', $Status = 'INFO', $Detail = '' + $diagBlacklistGroup]"/>

        <!-- Route cache (stored jump path sectors for reroute diagnostics) -->
        <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Route Cache ---', $Status = 'INFO', $Detail = '']"/>
        <set_value name="$globalBlacklistEpoch" exact="if global.$GT_BlacklistEpoch? then global.$GT_BlacklistEpoch else 0"/>
        <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Global Blacklist Epoch', $Status = 'INFO', $Detail = '' + $globalBlacklistEpoch]"/>
        <set_value name="$routeCacheExists" exact="false"/>
        <set_value name="$routeCache" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$RoutePathCache?">
          <set_value name="$routeCacheExists" exact="true"/>
          <set_value name="$routeCache" exact="global.$GT_Ships.{$ship}.$RoutePathCache"/>
        </do_if>
        <do_if value="$routeCacheExists and $routeCache?">
          <set_value name="$cacheEpoch" exact="if $routeCache.$BlacklistEpoch? then $routeCache.$BlacklistEpoch else 0"/>
          <set_value name="$cacheGroup" exact="if $routeCache.$BlacklistGroup? then '' + $routeCache.$BlacklistGroup else 'N/A'"/>
          <set_value name="$cacheDestName" exact="'Unknown'"/>
          <do_if value="$routeCache.$DestinationSector? and @$routeCache.$DestinationSector.knownname != null">
            <set_value name="$cacheDestName" exact="@$routeCache.$DestinationSector.knownname"/>
          </do_if>
          <set_value name="$remainingCount" exact="0"/>
          <do_if value="$routeCache.$RemainingSectors?">
            <set_value name="$remainingCount" exact="$routeCache.$RemainingSectors.count"/>
          </do_if>

          <set_value name="$routeSectorChain" exact="''"/>
          <do_if value="$remainingCount gt 0">
            <set_value name="$routeLimit" exact="[$remainingCount, 20].min"/>
            <do_all exact="$routeLimit" counter="$rci">
              <set_value name="$rcSector" exact="$routeCache.$RemainingSectors.{$rci}"/>
              <set_value name="$rcSectorName" exact="'Unknown'"/>
              <do_if value="$rcSector? and @$rcSector.knownname != null">
                <set_value name="$rcSectorName" exact="@$rcSector.knownname"/>
              </do_if>
              <do_if value="$routeSectorChain == ''">
                <set_value name="$routeSectorChain" exact="$rcSectorName"/>
              </do_if>
              <do_else>
                <set_value name="$routeSectorChain" exact="$routeSectorChain + ' -> ' + $rcSectorName"/>
              </do_else>
            </do_all>
            <do_if value="$remainingCount gt 20">
              <set_value name="$routeSectorChain" exact="$routeSectorChain + ' -> ... (+' + ($remainingCount - 20) + ')'"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$routeSectorChain" exact="'(empty)'"/>
          </do_else>

          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cache Epoch (Ship)', $Status = if $cacheEpoch == $globalBlacklistEpoch then 'PASS' else 'WARN', $Detail = '' + $cacheEpoch + ' (global: ' + $globalBlacklistEpoch + ')']"/>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cache Blacklist Group', $Status = 'INFO', $Detail = $cacheGroup]"/>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cache Destination', $Status = 'INFO', $Detail = $cacheDestName]"/>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cache Remaining Sectors', $Status = if $remainingCount gt 0 then 'INFO' else 'WARN', $Detail = '' + $remainingCount]"/>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Cached Jump Path', $Status = 'INFO', $Detail = $routeSectorChain]"/>
        </do_if>
        <do_else>
          <!-- Route cache is only built by move.generic sector-change logic when:
               - pilot level >= 12
               - threat avoidance + dynamic blacklist are enabled -->
          <set_value name="$routeCachePilotLevel" exact="0"/>
          <set_value name="$routeCacheTAEnabled" exact="false"/>
          <set_value name="$routeCacheDynBL" exact="false"/>
          <set_value name="$routeCacheEligiblePilot" exact="false"/>
          <set_value name="$routeCacheExpected" exact="false"/>
          <set_value name="$routeCacheReason" exact="'Route cache is not available yet'"/>

          <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
            <set_value name="$routeCachePilotLevel" exact="@global.$GT_Pilots.{$ship.pilot}.$Level"/>
          </do_if>
          <set_value name="$routeCacheEligiblePilot" exact="$routeCachePilotLevel ge 12"/>

          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ThreatAvoidance?">
            <set_value name="$routeCacheTAEnabled" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled"/>
            <set_value name="$routeCacheDynBL" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>
          </do_if>

          <set_value name="$routeCacheExpected" exact="$routeCacheEligiblePilot and $routeCacheTAEnabled and $routeCacheDynBL"/>
          <do_if value="not $routeCacheEligiblePilot">
            <set_value name="$routeCacheReason" exact="'No stored jump path cache (pilot level ' + $routeCachePilotLevel + ' &lt; 12; cache logic inactive)'"/>
          </do_if>
          <do_elseif value="not $routeCacheTAEnabled or not $routeCacheDynBL">
            <set_value name="$routeCacheReason" exact="'No stored jump path cache (ThreatAvoidance=' + $routeCacheTAEnabled + ', DynamicBlacklist=' + $routeCacheDynBL + ')'"/>
          </do_elseif>
          <do_else>
            <set_value name="$routeCacheReason" exact="'No stored jump path cache yet (eligible; cache populates on sector-change route evaluation)'"/>
          </do_else>

          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Route Cache', $Status = if $routeCacheExpected then 'WARN' else 'INFO', $Detail = $routeCacheReason]"/>
        </do_else>

        <!-- Check current sector blacklist status -->
        <do_if value="$ship.sector? and $diagBlacklistGroup?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$currentSectorBL">
            <param name="sector" value="$ship.sector"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$diagBlacklistGroup"/>
            <param name="returnDetails" value="true"/>
          </run_actions>
          <set_value name="$currentBLStatus" exact="'Not blacklisted'"/>
          <set_value name="$currentBLResult" exact="'PASS'"/>
          <do_if value="$currentSectorBL? and $currentSectorBL.$IsBlacklisted">
            <set_value name="$currentBLResult" exact="'FAIL'"/>
            <do_if value="$currentSectorBL.$ActivityBlacklisted and $currentSectorBL.$TravelBlacklisted">
              <set_value name="$currentBLStatus" exact="'BLACKLISTED (activity + travel) - ship cannot trade here and should not travel through this sector'"/>
            </do_if>
            <do_elseif value="$currentSectorBL.$ActivityBlacklisted">
              <set_value name="$currentBLStatus" exact="'BLACKLISTED (activity only) - ship cannot trade here but may travel through'"/>
            </do_elseif>
            <do_elseif value="$currentSectorBL.$TravelBlacklisted">
              <set_value name="$currentBLStatus" exact="'BLACKLISTED (travel only) - ship should not travel through this sector'"/>
            </do_elseif>
            <do_else>
              <set_value name="$currentBLStatus" exact="'BLACKLISTED (unknown type)'"/>
            </do_else>
          </do_if>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Current Sector', $Status = $currentBLResult, $Detail = $ship.sector.knownname + ': ' + $currentBLStatus]"/>
        </do_if>

        <!-- Check home sector blacklist status -->
        <do_if value="$homeSector? and $homeSector.exists and $diagBlacklistGroup?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$homeSectorBL">
            <param name="sector" value="$homeSector"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$diagBlacklistGroup"/>
            <param name="returnDetails" value="true"/>
          </run_actions>
          <set_value name="$homeBLStatus" exact="'Not blacklisted'"/>
          <set_value name="$homeBLResult" exact="'PASS'"/>
          <do_if value="$homeSectorBL? and $homeSectorBL.$IsBlacklisted">
            <set_value name="$homeBLResult" exact="'WARN'"/>
            <do_if value="$homeSectorBL.$ActivityBlacklisted and $homeSectorBL.$TravelBlacklisted">
              <set_value name="$homeBLStatus" exact="'BLACKLISTED (activity + travel) - trade search from home sector is severely limited'"/>
            </do_if>
            <do_elseif value="$homeSectorBL.$ActivityBlacklisted">
              <set_value name="$homeBLStatus" exact="'BLACKLISTED (activity) - no trades will originate from home sector stations'"/>
            </do_elseif>
            <do_elseif value="$homeSectorBL.$TravelBlacklisted">
              <set_value name="$homeBLStatus" exact="'BLACKLISTED (travel) - ships may not route through home sector'"/>
            </do_elseif>
            <do_else>
              <set_value name="$homeBLStatus" exact="'BLACKLISTED'"/>
            </do_else>
          </do_if>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Home Sector', $Status = $homeBLResult, $Detail = $homeSector.knownname + ': ' + $homeBLStatus]"/>
        </do_if>

        <!-- Check connected sectors - isolation detection -->
        <do_if value="$ship.sector? and $diagBlacklistGroup?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_CheckConnectedSectorsBlacklisted" result="$isolationResult">
            <param name="sector" value="$ship.sector"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$diagBlacklistGroup"/>
            <param name="returnDetails" value="true"/>
          </run_actions>

          <set_value name="$connectedCount" exact="@$isolationResult.$ConnectedSectorsCount"/>
          <set_value name="$blNeighborCount" exact="@$isolationResult.$BlacklistedSectorsCount"/>
          <set_value name="$okNeighborCount" exact="@$isolationResult.$NonBlacklistedSectorsCount"/>
          <do_if value="not $connectedCount?">
            <set_value name="$connectedCount" exact="0"/>
          </do_if>
          <do_if value="not $blNeighborCount?">
            <set_value name="$blNeighborCount" exact="0"/>
          </do_if>
          <do_if value="not $okNeighborCount?">
            <set_value name="$okNeighborCount" exact="0"/>
          </do_if>

          <set_value name="$isolatedResult" exact="'PASS'"/>
          <set_value name="$isolatedDesc" exact="'' + $connectedCount + ' connected sectors (' + $okNeighborCount + ' accessible, ' + $blNeighborCount + ' blacklisted)'"/>
          <do_if value="$isolationResult? and $isolationResult.$IsIsolated">
            <set_value name="$isolatedResult" exact="'FAIL'"/>
            <set_value name="$isolatedDesc" exact="'ISOLATED - All ' + $connectedCount + ' connected sectors are blacklisted. Ship can only trade within its current sector.'"/>
          </do_if>
          <do_elseif value="$blNeighborCount gt 0">
            <set_value name="$isolatedResult" exact="'WARN'"/>
          </do_elseif>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Sector Isolation', $Status = $isolatedResult, $Detail = $isolatedDesc]"/>

          <!-- List blacklisted neighboring sectors -->
          <do_if value="$isolationResult.$BlacklistedSectors? and $isolationResult.$BlacklistedSectors.count gt 0">
            <set_value name="$blSectorNames" exact="''"/>
            <do_all exact="[$isolationResult.$BlacklistedSectors.count, 10].min" counter="$bli">
              <set_value name="$blSec" exact="$isolationResult.$BlacklistedSectors.{$bli}"/>
              <do_if value="$blSec? and $blSec.exists">
                <do_if value="$blSectorNames != ''">
                  <set_value name="$blSectorNames" exact="$blSectorNames + ', '"/>
                </do_if>
                <set_value name="$blSectorNames" exact="$blSectorNames + $blSec.knownname"/>
              </do_if>
            </do_all>
            <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Blacklisted Neighbors', $Status = 'WARN', $Detail = $blSectorNames]"/>
          </do_if>

          <!-- List accessible neighboring sectors -->
          <do_if value="$isolationResult.$NonBlacklistedSectors? and $isolationResult.$NonBlacklistedSectors.count gt 0">
            <set_value name="$okSectorNames" exact="''"/>
            <do_all exact="[$isolationResult.$NonBlacklistedSectors.count, 10].min" counter="$oki">
              <set_value name="$okSec" exact="$isolationResult.$NonBlacklistedSectors.{$oki}"/>
              <do_if value="$okSec? and $okSec.exists">
                <do_if value="$okSectorNames != ''">
                  <set_value name="$okSectorNames" exact="$okSectorNames + ', '"/>
                </do_if>
                <set_value name="$okSectorNames" exact="$okSectorNames + $okSec.knownname"/>
              </do_if>
            </do_all>
            <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Accessible Neighbors', $Status = 'PASS', $Detail = $okSectorNames]"/>
          </do_if>
        </do_if>

        <append_to_list name="$report.$Sections" exact="$sec1"/>

        <!-- ======================================================== -->
        <!-- SECTION 2: Miner Coordination Snapshot                    -->
        <!-- ======================================================== -->
        <set_value name="$isMinerContext" exact="false"/>
        <do_if value="@$ship.defaultorder.id == 'GalaxyMiner'">
          <set_value name="$isMinerContext" exact="true"/>
        </do_if>
        <do_elseif value="$ship.commander? and @$ship.commander.defaultorder.id == 'GalaxyMiner'">
          <set_value name="$isMinerContext" exact="true"/>
        </do_elseif>
        <do_elseif value="global.$GT_MinerDiag? and global.$GT_MinerDiag.{$ship}?">
          <set_value name="$isMinerContext" exact="true"/>
        </do_elseif>

        <do_if value="$isMinerContext">
          <set_value name="$sec2" exact="table[]"/>
          <set_value name="$sec2.$Name" exact="'Miner Coordination'"/>
          <set_value name="$sec2.$Rows" exact="[]"/>

          <set_value name="$minerDiag" exact="null"/>
          <do_if value="global.$GT_MinerDiag? and global.$GT_MinerDiag.{$ship}?">
            <set_value name="$minerDiag" exact="global.$GT_MinerDiag.{$ship}"/>
          </do_if>

          <!-- "Selected Ware" copy resolution.
               UNKNOWN is reserved for the genuinely opaque case (no snapshot at all). When the
               snapshot is present but $SelectedWare is null, the miner is between mining slices
               (post-Sell, pre-Score) - surface that explicitly. When no warebasket is configured
               and no snapshot has arrived yet, "All minable wares" is the truthful description
               of the miner's actual scoring pool (it falls back to cargo.list / station buy-offers
               -> see order.trade.galaxyminer.xml ~493-559). -->
          <set_value name="$shipHasBasket" exact="$ship.warebasket? and $ship.warebasket.list? and $ship.warebasket.list.count gt 0"/>
          <set_value name="$selectedWareText" exact="if $shipHasBasket then 'UNKNOWN' else 'All minable wares (no basket configured)'"/>
          <set_value name="$urgencyText" exact="'0'"/>
          <set_value name="$overflowText" exact="'false'"/>
          <set_value name="$targetsText" exact="'0'"/>
          <set_value name="$supplierCountText" exact="'0'"/>
          <set_value name="$intentCountText" exact="'0'"/>
          <set_value name="$intentPhaseText" exact="'unknown'"/>
          <set_value name="$primaryCapacityText" exact="'unknown'"/>
          <set_value name="$overflowFallbackText" exact="'unknown'"/>
          <set_value name="$primaryDeliveryStationText" exact="'n/a'"/>
          <set_value name="$overflowDetachedText" exact="'false'"/>
          <set_value name="$lastUpdateText" exact="'n/a'"/>
          <set_value name="$diagStatus" exact="'WARN'"/>
          <set_value name="$coordEntriesStatus" exact="'INFO'"/>
          <set_value name="$coordEntriesDetail" exact="'Assignments: 0, Intents: 0'"/>

          <do_if value="$minerDiag?">
            <set_value name="$diagStatus" exact="'PASS'"/>
            <set_value name="$selectedWareText" exact="if $minerDiag.$SelectedWare? then '' + $minerDiag.$SelectedWare else (if $shipHasBasket then 'Pending (between mining slices)' else 'All minable wares (no basket configured)')"/>
            <set_value name="$urgencyText" exact="if $minerDiag.$Urgency? then '' + $minerDiag.$Urgency else '0'"/>
            <set_value name="$overflowText" exact="if $minerDiag.$OverflowMode? then 'true' else 'false'"/>
            <set_value name="$targetsText" exact="if $minerDiag.$TargetStationCount? then '' + $minerDiag.$TargetStationCount else '0'"/>
            <set_value name="$supplierCountText" exact="if $minerDiag.$SupplierCount? then '' + $minerDiag.$SupplierCount else '0'"/>
            <set_value name="$intentCountText" exact="if $minerDiag.$IntentCount? then '' + $minerDiag.$IntentCount else '0'"/>
            <set_value name="$intentPhaseText" exact="if $minerDiag.$IntentPhase? then '' + $minerDiag.$IntentPhase else 'unknown'"/>
            <set_value name="$primaryCapacityText" exact="if $minerDiag.$PrimaryCapacityAvailable? then (if $minerDiag.$PrimaryCapacityAvailable then 'true' else 'false') else 'unknown'"/>
            <set_value name="$overflowFallbackText" exact="if $minerDiag.$OverflowFallbackAllowed? then (if $minerDiag.$OverflowFallbackAllowed then 'true' else 'false') else 'unknown'"/>
            <set_value name="$primaryDeliveryStationText" exact="if $minerDiag.$PrimaryDeliveryStation? and $minerDiag.$PrimaryDeliveryStation.exists then $minerDiag.$PrimaryDeliveryStation.knownname else 'n/a'"/>
            <set_value name="$overflowDetachedText" exact="if $minerDiag.$OverflowDetachedCommander? and $minerDiag.$OverflowDetachedCommander then 'true' else 'false'"/>
            <do_if value="$minerDiag.$Timestamp?">
              <set_value name="$lastUpdateText" exact="'' + ((player.age - $minerDiag.$Timestamp) / 1s)i + 's ago'"/>
            </do_if>
            <do_if value="$minerDiag.$StallReason?">
              <set_value name="$intentPhaseText" exact="'' + $intentPhaseText + ' | stall: ' + $minerDiag.$StallReason"/>
            </do_if>
          </do_if>

          <!-- Detect live/stale coordination entries for this ship -->
          <set_value name="$assignmentEntryCount" exact="0"/>
          <set_value name="$intentEntryCount" exact="0"/>
          <do_if value="global.$GT_MinerStationAssignments? and global.$GT_MinerStationAssignments.keys.count gt 0">
            <set_value name="$assignStations" exact="global.$GT_MinerStationAssignments.keys.list"/>
            <do_all exact="$assignStations.count" counter="$asi">
              <set_value name="$assignStation" exact="$assignStations.{$asi}"/>
              <do_if value="global.$GT_MinerStationAssignments.{$assignStation}?">
                <set_value name="$assignWares" exact="global.$GT_MinerStationAssignments.{$assignStation}.keys.list"/>
                <do_all exact="$assignWares.count" counter="$awi">
                  <set_value name="$assignWare" exact="$assignWares.{$awi}"/>
                  <do_if value="global.$GT_MinerStationAssignments.{$assignStation}.{$assignWare}? and global.$GT_MinerStationAssignments.{$assignStation}.{$assignWare}.{$ship}?">
                    <set_value name="$assignmentEntryCount" exact="$assignmentEntryCount + 1"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_MinerIntents? and global.$GT_MinerIntents.keys.count gt 0">
            <set_value name="$intentStations" exact="global.$GT_MinerIntents.keys.list"/>
            <do_all exact="$intentStations.count" counter="$isi">
              <set_value name="$intentStation" exact="$intentStations.{$isi}"/>
              <do_if value="global.$GT_MinerIntents.{$intentStation}?">
                <set_value name="$intentWares" exact="global.$GT_MinerIntents.{$intentStation}.keys.list"/>
                <do_all exact="$intentWares.count" counter="$iwi">
                  <set_value name="$intentWare" exact="$intentWares.{$iwi}"/>
                  <do_if value="global.$GT_MinerIntents.{$intentStation}.{$intentWare}? and global.$GT_MinerIntents.{$intentStation}.{$intentWare}.{$ship}?">
                    <set_value name="$intentEntryCount" exact="$intentEntryCount + 1"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$coordEntriesDetail" exact="'Assignments: ' + $assignmentEntryCount + ', Intents: ' + $intentEntryCount"/>
          <set_value name="$coordEntriesStatus" exact="'PASS'"/>
          <do_if value="$assignmentEntryCount == 0 and $intentEntryCount == 0">
            <set_value name="$coordEntriesStatus" exact="'WARN'"/>
          </do_if>
          <do_if value="not $ship.defaultorder? or @$ship.defaultorder.id != 'GalaxyMiner'">
            <do_if value="$assignmentEntryCount gt 0 or $intentEntryCount gt 0">
              <set_value name="$coordEntriesStatus" exact="'FAIL'"/>
              <set_value name="$coordEntriesDetail" exact="$coordEntriesDetail + ' (stale entries on non-miner order)'"/>
            </do_if>
          </do_if>

          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Snapshot', $Status = $diagStatus, $Detail = if $diagStatus == 'PASS' then 'Available' else 'No live miner snapshot received yet']"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Selected Ware', $Status = 'INFO', $Detail = $selectedWareText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Urgency', $Status = 'INFO', $Detail = $urgencyText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Overflow Mode', $Status = 'INFO', $Detail = $overflowText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Primary Capacity Available', $Status = 'INFO', $Detail = $primaryCapacityText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Overflow Fallback Allowed', $Status = 'INFO', $Detail = $overflowFallbackText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Primary Delivery Station', $Status = 'INFO', $Detail = $primaryDeliveryStationText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Overflow Commander Detached', $Status = 'INFO', $Detail = $overflowDetachedText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Target Stations', $Status = 'INFO', $Detail = $targetsText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Suppliers (selected ware)', $Status = 'INFO', $Detail = $supplierCountText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Active Intents (selected ware)', $Status = 'INFO', $Detail = $intentCountText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Intent Phase (this ship)', $Status = 'INFO', $Detail = $intentPhaseText]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Coordination Entries (this ship)', $Status = $coordEntriesStatus, $Detail = $coordEntriesDetail]"/>
          <append_to_list name="$sec2.$Rows" exact="table[$Check = 'Last Snapshot Update', $Status = 'INFO', $Detail = $lastUpdateText]"/>

          <append_to_list name="$report.$Sections" exact="$sec2"/>
        </do_if>

        <!-- Player economy variables (needed for pair evaluation + VERDICT).
             Mirror the read order used by the AI-side helper lib.gt.attention.min_player_money:
               1) global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney (when present and gt 0)
               2) Fallback to 1000 (historical default if settings have not populated yet)
             Previously read from global.$GT_AIParameters.{ship}.$MinPlayerMoney, which was never
             populated for MK3/MK4/Miner - only $IgnoreBuildStorage / $IgnoreCarrierAux / $HomeBase
             / $TraceId / $DistancePenalty / $MaxDistance keys are written
             into $GT_AIParameters by GT_RequestRegistry_Acquire - so the gate threshold defaulted
             to 100000 Cr regardless of the user's actual fleet setting and made the "money gate"
             verdict misleading. The legacy read is kept as an upper-bound fallback for the rare
             case a future writer puts a per-ship override there. -->
        <set_value name="$playerMoney" exact="player.money"/>
        <set_value name="$minPlayerMoney" exact="1000"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney?">
          <set_value name="$tmpMinMoney" exact="@global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney"/>
          <do_if value="$tmpMinMoney? and $tmpMinMoney != null and $tmpMinMoney gt 0">
            <set_value name="$minPlayerMoney" exact="$tmpMinMoney"/>
          </do_if>
        </do_if>
        <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$MinPlayerMoney? and global.$GT_AIParameters.{$ship}.$MinPlayerMoney gt $minPlayerMoney">
          <set_value name="$minPlayerMoney" exact="global.$GT_AIParameters.{$ship}.$MinPlayerMoney"/>
        </do_if>
        <set_value name="$moneyGateThreshold" exact="$minPlayerMoney + 100000"/>

        <!-- ======================================================== -->
        <!-- SECTION 3: Configuration Snapshot                        -->
        <!-- ======================================================== -->
        <set_value name="$sec3" exact="table[]"/>
        <set_value name="$sec3.$Name" exact="'Configuration'"/>
        <set_value name="$sec3.$Rows" exact="[]"/>

        <!-- Determine the authoritative order source (ship or commander for subordinates) -->
        <set_value name="$orderSource" exact="$ship"/>
        <set_value name="$orderSourceLabel" exact="'direct'"/>
        <set_value name="$gtOrder" exact="@$ship.defaultorder"/>
        <do_if value="$ship.commander? and $ship.commander.exists">
          <do_if value="global.$GT_ProtectedOrderIDs? and $ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id} or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.$baseorder.id}))">
            <set_value name="$orderSource" exact="$ship.commander"/>
            <set_value name="$orderSourceLabel" exact="'commander (' + $ship.commander.idcode + ')'"/>
            <set_value name="$gtOrder" exact="if @$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? then $ship.commander.defaultorder.$baseorder else $ship.commander.defaultorder"/>
          </do_if>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Order Source', $Status = 'INFO', $Detail = $orderSourceLabel]"/>

        <!-- Order type (MK1/MK2/MK3/Miner) for conditional display -->
        <set_value name="$orderId" exact="'Unknown'"/>
        <do_if value="$gtOrder? and $gtOrder.id?">
          <set_value name="$orderId" exact="$gtOrder.id"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Order Type', $Status = 'INFO', $Detail = $orderId]"/>

        <!-- Min Player Money (global gate - ships wait below this) -->
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Min Player Money', $Status = 'INFO', $Detail = '' + ($minPlayerMoney / 100) + ' Cr (ships idle below this)']"/>

        <!-- Max distance (maxbuy / maxsell from order params) -->
        <!-- IMPORTANT: order param default expressions use this.ship which doesn't resolve in MD context.
             Reading defaultorder.$maxbuy in MD can return 25 (the fallback maximum) instead of the
             skill-based default. We must compute the pilot skill cap independently and apply it. -->
        <set_value name="$rawMaxBuy" exact="0"/>
        <set_value name="$rawMaxSell" exact="0"/>
        <do_if value="$orderId == 'GalaxyTraderMK2' and $gtOrder? and $gtOrder.$maxDistance?">
          <set_value name="$rawMaxBuy" exact="$gtOrder.$maxDistance"/>
          <set_value name="$rawMaxSell" exact="$gtOrder.$maxDistance"/>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyMiner' and $gtOrder?">
          <do_if value="$gtOrder.$maxGatherDistance?">
            <set_value name="$rawMaxBuy" exact="$gtOrder.$maxGatherDistance"/>
          </do_if>
          <do_if value="$gtOrder.$maxSellDistance?">
            <set_value name="$rawMaxSell" exact="$gtOrder.$maxSellDistance"/>
          </do_if>
        </do_elseif>
        <do_elseif value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $gtOrder?">
          <do_if value="$gtOrder.$jumpDistanceBuy?">
            <set_value name="$rawMaxBuy" exact="$gtOrder.$jumpDistanceBuy"/>
          </do_if>
          <do_elseif value="$gtOrder.$maxbuy?">
            <set_value name="$rawMaxBuy" exact="$gtOrder.$maxbuy"/>
          </do_elseif>
          <do_if value="$gtOrder.$jumpDistanceCoverage?">
            <set_value name="$rawMaxSell" exact="$gtOrder.$jumpDistanceCoverage"/>
          </do_if>
          <do_elseif value="$gtOrder.$maxsell?">
            <set_value name="$rawMaxSell" exact="$gtOrder.$maxsell"/>
          </do_elseif>
        </do_elseif>
        <do_else>
          <do_if value="$gtOrder? and $gtOrder.$maxbuy?">
            <set_value name="$rawMaxBuy" exact="$gtOrder.$maxbuy"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$maxsell?">
            <set_value name="$rawMaxSell" exact="$gtOrder.$maxsell"/>
          </do_if>
        </do_else>

        <!-- Compute pilot skill cap (mirrors order.trade.galaxytrader.xml: GT registry level, not vanilla management skill) -->
        <set_value name="$pilotMaxJumps" exact="25"/>
        <set_value name="$diagUseVanillaXPOnlyForCap" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$diagPilotSkill" exact="null"/>
        <do_if value="$diagUseVanillaXPOnlyForCap">
          <do_if value="$ship.pilot? and $ship.pilot.skill.piloting?">
            <set_value name="$diagPilotSkill" exact="$ship.pilot.skill.piloting"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
            <set_value name="$diagPilotSkill" exact="global.$GT_Pilots.{$ship.pilot}.$Level"/>
          </do_if>
        </do_else>
        <do_if value="$diagPilotSkill != null">
          <do_if value="$diagPilotSkill le 2">
            <set_value name="$pilotMaxJumps" exact="1"/>
          </do_if>
          <do_elseif value="$diagPilotSkill le 5">
            <set_value name="$pilotMaxJumps" exact="3"/>
          </do_elseif>
          <do_elseif value="$diagPilotSkill le 8">
            <set_value name="$pilotMaxJumps" exact="5"/>
          </do_elseif>
          <do_elseif value="$diagPilotSkill le 11">
            <set_value name="$pilotMaxJumps" exact="10"/>
          </do_elseif>
          <do_elseif value="$diagPilotSkill le 13">
            <set_value name="$pilotMaxJumps" exact="15"/>
          </do_elseif>
          <do_else>
            <set_value name="$pilotMaxJumps" exact="25"/>
          </do_else>
        </do_if>

        <!-- Apply pilot skill cap: effective = min(order value, pilot capability); disabled in vanilla XP mode. -->
        <set_value name="$diagUseVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$diagPilotCapDetail" exact="'' + $pilotMaxJumps"/>
        <do_if value="$diagUseVanillaXPOnly">
          <set_value name="$maxBuy" exact="$rawMaxBuy"/>
          <set_value name="$maxSell" exact="$rawMaxSell"/>
          <set_value name="$diagPilotCapDetail" exact="'disabled (vanilla XP mode)'"/>
        </do_if>
        <do_else>
          <set_value name="$maxBuy" exact="[$rawMaxBuy, $pilotMaxJumps].min"/>
          <set_value name="$maxSell" exact="[$rawMaxSell, $pilotMaxJumps].min"/>
        </do_else>
        <set_value name="$maxDistance" exact="[$maxBuy, $maxSell].max"/>
        <set_value name="$diagSearchDistance" exact="$maxDistance"/>
        <do_if value="$orderId == 'GalaxyMiner'">
          <!-- Miner diagnose should use sell radius (not max of buy/sell). -->
          <set_value name="$diagSearchDistance" exact="$maxSell"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Max Buy Distance', $Status = 'INFO', $Detail = '' + $maxBuy + ' jumps (order: ' + $rawMaxBuy + ', pilot cap: ' + $diagPilotCapDetail + ')']"/>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Max Sell Distance', $Status = 'INFO', $Detail = '' + $maxSell + ' jumps (order: ' + $rawMaxSell + ', pilot cap: ' + $diagPilotCapDetail + ')']"/>

        <!-- Autoscale jump distance (commander/standalone GT orders only) -->
        <do_if value="$ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}">
          <set_value name="$autoJumpOn" exact="if $ship.defaultorder.$autoJumpDistanceByLevel? and $ship.defaultorder.$autoJumpDistanceByLevel then true else false"/>
          <set_value name="$gtTierMax" exact="$pilotMaxJumps"/>
          <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
            <run_actions ref="md.GT_Ship_Management.Calculate_Jump_Distance" result="$gtTierMax">
              <param name="skill_level" value="global.$GT_Pilots.{$ship.pilot}.$Level"/>
            </run_actions>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Autoscale', $Status = 'INFO', $Detail = if $autoJumpOn then 'on' else 'off']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Stored vs Tier Max', $Status = 'INFO', $Detail = 'buy/sell order ' + $rawMaxBuy + '/' + $rawMaxSell + ' vs tier max ' + $gtTierMax]"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Effective Max Distance', $Status = if $maxDistance gt 0 then 'PASS' else 'FAIL', $Detail = '' + $maxDistance + ' jumps (max of buy/sell)']"/>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Diagnose Search Distance', $Status = 'INFO', $Detail = '' + $diagSearchDistance + ' jumps' + (if $orderId == 'GalaxyMiner' then ' (miner sell range)' else '')]"/>

        <!-- Minimum cargo utilization (hard filter) -->
        <set_value name="$rawCargoTarget" exact="90"/>
        <do_if value="$orderId == 'GalaxyTraderMK1' and $gtOrder?">
          <do_if value="$gtOrder.$selltarget?">
            <set_value name="$rawCargoTarget" exact="$gtOrder.$selltarget"/>
          </do_if>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK2' and $gtOrder?">
          <do_if value="$gtOrder.$maxStorage?">
            <set_value name="$rawCargoTarget" exact="$gtOrder.$maxStorage"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyMiner' and $gtOrder?">
          <do_if value="$gtOrder.$overflowThreshold?">
            <set_value name="$rawCargoTarget" exact="$gtOrder.$overflowThreshold"/>
          </do_if>
        </do_elseif>
        <do_elseif value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $gtOrder?">
          <do_if value="$gtOrder.$minCargoUsed?">
            <set_value name="$rawCargoTarget" exact="$gtOrder.$minCargoUsed"/>
          </do_if>
          <do_elseif value="$gtOrder.$cargotarget?">
            <set_value name="$rawCargoTarget" exact="$gtOrder.$cargotarget"/>
          </do_elseif>
        </do_elseif>
        <do_else>
          <do_if value="$gtOrder? and $gtOrder.$cargotarget?">
            <set_value name="$rawCargoTarget" exact="$gtOrder.$cargotarget"/>
          </do_if>
        </do_else>
        <set_value name="$effectiveCargoTarget" exact="[10,[$rawCargoTarget,100].min].max"/>
        <set_value name="$useMinCargoThreshold" exact="true"/>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
          <set_value name="$useMinCargoThreshold" exact="false"/>
          <do_if value="$gtOrder? and $gtOrder.$useMinCargoThreshold?">
            <set_value name="$useMinCargoThreshold" exact="$gtOrder.$useMinCargoThreshold"/>
          </do_if>
        </do_if>
        <set_value name="$cargoFilterMode" exact="'ACTIVE (live/cache/fallback)'"/>
        <set_value name="$cargoFilterStatus" exact="'PASS'"/>
        <do_if value="not $useMinCargoThreshold">
          <set_value name="$cargoFilterMode" exact="'DISABLED (order toggle)'"/>
          <set_value name="$cargoFilterStatus" exact="'WARN'"/>
        </do_if>
        <do_if value="$useMinCargoThreshold and global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
          <set_value name="$cargoFilterMode" exact="'DISABLED (isolated mode)'"/>
          <set_value name="$cargoFilterStatus" exact="'WARN'"/>
        </do_if>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Use Min Cargo Threshold', $Status = 'INFO', $Detail = if $useMinCargoThreshold then 'true' else 'false']"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Min Cargo Utilization', $Status = 'INFO', $Detail = '' + $effectiveCargoTarget + '% (order: ' + $rawCargoTarget + ')']"/>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Cargo Util Filter Mode', $Status = $cargoFilterStatus, $Detail = $cargoFilterMode]"/>

        <!-- Allow illegal (from order params, with explicit true/false) -->
        <set_value name="$allowIllegal" exact="false"/>
        <do_if value="$gtOrder? and $gtOrder.$allowillegal?">
          <set_value name="$allowIllegal" exact="$gtOrder.$allowillegal"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Allow Illegal', $Status = 'INFO', $Detail = if $allowIllegal then 'true' else 'false']"/>

        <!-- Illegal Route Filter (MK1/MK2/MK3/MK4/Miner - from order params) -->
        <do_if value="$orderId == 'GalaxyTraderMK1' or $orderId == 'GalaxyTraderMK2' or $orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyMiner'">
          <set_value name="$enforceRouteIllegalLegality" exact="false"/>
          <do_if value="$gtOrder? and $gtOrder.$enforceRouteIllegalLegality?">
            <set_value name="$enforceRouteIllegalLegality" exact="$gtOrder.$enforceRouteIllegalLegality"/>
          </do_if>
          <set_value name="$routeFilterStatus" exact="'INFO'"/>
          <set_value name="$routeFilterDetail" exact="if $enforceRouteIllegalLegality then 'true' else 'false'"/>
          <do_if value="$enforceRouteIllegalLegality and not $allowIllegal">
            <set_value name="$routeFilterStatus" exact="'WARN'"/>
            <set_value name="$routeFilterDetail" exact="'true (inactive: Allow Illegal is off)'"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Illegal Route Filter', $Status = $routeFilterStatus, $Detail = $routeFilterDetail]"/>
        </do_if>

        <!-- Runtime illegal-route enforcement (ActiveTradePolicy + last abort record) -->
        <append_to_list name="$sec3.$Rows" exact="table[$Check = '--- Illegal Route Enforcement ---', $Status = 'INFO', $Detail = '']"/>
        <set_value name="$activeTradePolicy" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$ActiveTradePolicy?">
          <set_value name="$activeTradePolicy" exact="global.$GT_Ships.{$ship}.$ActiveTradePolicy"/>
        </do_if>
        <do_if value="$activeTradePolicy?">
          <set_value name="$atpWareName" exact="'none'"/>
          <do_if value="$activeTradePolicy.$Ware?">
            <set_value name="$atpWareName" exact="$activeTradePolicy.$Ware.name"/>
          </do_if>
          <set_value name="$atpLeg" exact="if $activeTradePolicy.$Leg? then $activeTradePolicy.$Leg else 'unknown'"/>
          <set_value name="$atpBuySectorName" exact="'unknown'"/>
          <do_if value="$activeTradePolicy.$BuySector? and @$activeTradePolicy.$BuySector.knownname != null">
            <set_value name="$atpBuySectorName" exact="@$activeTradePolicy.$BuySector.knownname"/>
          </do_if>
          <set_value name="$atpSellSectorName" exact="'unknown'"/>
          <do_if value="$activeTradePolicy.$SellSector? and @$activeTradePolicy.$SellSector.knownname != null">
            <set_value name="$atpSellSectorName" exact="@$activeTradePolicy.$SellSector.knownname"/>
          </do_if>
          <set_value name="$atpRouteStartName" exact="'unknown'"/>
          <do_if value="$activeTradePolicy.$RouteStart? and @$activeTradePolicy.$RouteStart.knownname != null">
            <set_value name="$atpRouteStartName" exact="@$activeTradePolicy.$RouteStart.knownname"/>
          </do_if>
          <set_value name="$atpSetAt" exact="if $activeTradePolicy.$SetAt? then $activeTradePolicy.$SetAt else 0"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Active Trade Policy', $Status = 'PASS', $Detail = 'leg=' + $atpLeg + ', ware=' + $atpWareName + ', buy=' + $atpBuySectorName + ', sell=' + $atpSellSectorName + ', routeStart=' + $atpRouteStartName + ', setAt=' + $atpSetAt]"/>
        </do_if>
        <do_else>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Active Trade Policy', $Status = 'INFO', $Detail = 'none (no committed trade under route enforcement)']"/>
        </do_else>
        <set_value name="$routeIllegalAbort" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$RouteIllegalAbort?">
          <set_value name="$routeIllegalAbort" exact="global.$GT_Ships.{$ship}.$RouteIllegalAbort"/>
        </do_if>
        <!-- Require a populated abort record (Reason or Timestamp). An empty table key alone is not enough. -->
        <set_value name="$riaHasRecord" exact="false"/>
        <do_if value="$routeIllegalAbort? and ($routeIllegalAbort.$Reason? or ($routeIllegalAbort.$Timestamp? and $routeIllegalAbort.$Timestamp gt 0))">
          <set_value name="$riaHasRecord" exact="true"/>
        </do_if>
        <do_if value="$riaHasRecord">
          <set_value name="$riaReason" exact="if $routeIllegalAbort.$Reason? then $routeIllegalAbort.$Reason else 'route_illegal_pre_transit'"/>
          <set_value name="$riaNextSectorName" exact="if $routeIllegalAbort.$NextSectorName? then $routeIllegalAbort.$NextSectorName else 'Unknown'"/>
          <do_if value="$riaNextSectorName == 'Unknown' and $routeIllegalAbort.$NextSector? and $routeIllegalAbort.$NextSector.exists">
            <set_value name="$riaNextSectorName" exact="@$routeIllegalAbort.$NextSector.knownname"/>
          </do_if>
          <set_value name="$riaWareName" exact="if $routeIllegalAbort.$WareName? then $routeIllegalAbort.$WareName else 'Unknown'"/>
          <do_if value="$riaWareName == 'Unknown' and $routeIllegalAbort.$Ware?">
            <set_value name="$riaWareName" exact="@$routeIllegalAbort.$Ware.name"/>
          </do_if>
          <set_value name="$riaActiveWareName" exact="if $routeIllegalAbort.$ActiveWareName? then $routeIllegalAbort.$ActiveWareName else 'none'"/>
          <do_if value="$riaActiveWareName == 'none' and $routeIllegalAbort.$ActiveWare?">
            <set_value name="$riaActiveWareName" exact="@$routeIllegalAbort.$ActiveWare.name"/>
          </do_if>
          <set_value name="$riaPoliceName" exact="if $routeIllegalAbort.$PoliceFactionName? then $routeIllegalAbort.$PoliceFactionName else 'Unknown'"/>
          <do_if value="$riaPoliceName == 'Unknown' and $routeIllegalAbort.$PoliceFaction?">
            <set_value name="$riaPoliceName" exact="@$routeIllegalAbort.$PoliceFaction.knownname"/>
          </do_if>
          <set_value name="$riaPoliceId" exact="if $routeIllegalAbort.$PoliceFactionId? then $routeIllegalAbort.$PoliceFactionId else 'none'"/>
          <do_if value="$riaPoliceId == 'none' and $routeIllegalAbort.$PoliceFaction? and $routeIllegalAbort.$PoliceFaction.id?">
            <set_value name="$riaPoliceId" exact="$routeIllegalAbort.$PoliceFaction.id"/>
          </do_if>
          <set_value name="$riaTimestamp" exact="if $routeIllegalAbort.$Timestamp? then $routeIllegalAbort.$Timestamp else 0"/>
          <set_value name="$riaAgeText" exact="if $riaTimestamp gt 0 then '' + ((player.age - $riaTimestamp) / 1s)i + 's ago' else 'unknown age'"/>
          <!-- Historical runtime abort: WARN (not FAIL â€” ship may already be searching again). -->
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Last Route Illegal Abort', $Status = 'WARN', $Detail = 'reason=' + $riaReason + ', next=' + $riaNextSectorName + ', ware=' + $riaWareName + ', activeWare=' + $riaActiveWareName + ', police=' + $riaPoliceName + ' (' + $riaPoliceId + '), ' + $riaAgeText]"/>
        </do_if>
        <do_elseif value="$routeIllegalAbort?">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Last Route Illegal Abort', $Status = 'WARN', $Detail = 'stale/incomplete record on ship registry (no Reason/Timestamp) â€” will refresh on next runtime abort']"/>
        </do_elseif>
        <do_else>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Last Route Illegal Abort', $Status = 'PASS', $Detail = 'none recorded']"/>
        </do_else>

        <!-- Ignore trade rules (from order params) -->
        <set_value name="$ignoreTradeRules" exact="false"/>
        <do_if value="$gtOrder? and $gtOrder.$ignoretraderules?">
          <set_value name="$ignoreTradeRules" exact="$gtOrder.$ignoretraderules"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ignore Trade Rules', $Status = 'INFO', $Detail = if $ignoreTradeRules then 'true' else 'false']"/>

        <!-- Ignore MK1-supplied stations (from order params) -->
        <set_value name="$ignoreMK1Supply" exact="true"/>
        <do_if value="$gtOrder? and $gtOrder.$ignoremk1supply?">
          <set_value name="$ignoreMK1Supply" exact="$gtOrder.$ignoremk1supply"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ignore MK1 Supply', $Status = 'INFO', $Detail = if $ignoreMK1Supply then 'true' else 'false']"/>

        <!-- Ignore build storage (from order params) -->
        <set_value name="$ignoreBuildStorage" exact="false"/>
        <do_if value="$gtOrder? and $gtOrder.$ignorebuildstorage?">
          <set_value name="$ignoreBuildStorage" exact="$gtOrder.$ignorebuildstorage"/>
        </do_if>
        <do_if value="not ($gtOrder? and $gtOrder.$ignorebuildstorage?) and $orderId == 'GalaxyTraderMK4Supply' and $gtOrder? and $gtOrder.$allowBuildstorage?">
          <set_value name="$ignoreBuildStorage" exact="not $gtOrder.$allowBuildstorage"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ignore Build Storage', $Status = 'INFO', $Detail = if $ignoreBuildStorage then 'true' else 'false']"/>

        <!-- Ignore carrier/aux (from order params) -->
        <set_value name="$ignoreCarrierAux" exact="false"/>
        <do_if value="$gtOrder? and $gtOrder.$ignorecarrieraux?">
          <set_value name="$ignoreCarrierAux" exact="$gtOrder.$ignorecarrieraux"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ignore Carrier/Aux', $Status = 'INFO', $Detail = if $ignoreCarrierAux then 'true' else 'false']"/>

        <!-- MK3 'Ignore Player Pricing' (mirrors order.trade.galaxytrader.xml param + runtime semantics):
             When ON, the supplier scan accepts player-owned sell offers regardless of relativeprice,
             player-owned buyers are excluded from the buyer scan, and player-supplier pairs bypass
             the no-profit / profit-threshold / ROI rejection gates because the player's production
             cost for those wares is treated as zero (the buy-leg credits flow within the player's
             own economy). MK3-only param; ignored for MK1/MK2/MK4/Miner. -->
        <set_value name="$ignorePlayerPricing" exact="false"/>
        <do_if value="$orderId == 'GalaxyTraderMK3' and $gtOrder? and $gtOrder.$ignoreplayerpricing?">
          <set_value name="$ignorePlayerPricing" exact="$gtOrder.$ignoreplayerpricing"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ignore Player Pricing', $Status = 'INFO', $Detail = if $ignorePlayerPricing then 'true (MK3 buys from player at any price, sells only to NPCs)' else 'false']"/>
        <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'IPP Policy Snapshot', $Status = 'INFO', $Detail = 'Player suppliers: any sell price (supplemental scan). Buyers: NPC only. Score/profit: supplier cost treated as zero.']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'IPP Runtime Note', $Status = 'INFO', $Detail = 'NPC suppliers still compete on score. MinPlayerMoney purchase gate skipped for player-supplier pairs (internal economy). Vanilla buy leg may still move credits at execution.']"/>
        </do_if>
        <!-- IPP scan stats are appended to Sec8 after the supplier/buyer loops below populate
             the counters. The scan loop sets $diagIppPlayerSuppliersAdded / $diagIppPlayerBuyersRejected. -->

        <!-- MK4-specific policy snapshot (must mirror runtime order.trade.galaxytradermk4) -->
        <set_value name="$diagMk4CustomerMustBePlayer" exact="false"/>
        <set_value name="$diagMk4AllowPlayerSuppliers" exact="true"/>
        <set_value name="$diagMk4AllowAiSuppliers" exact="true"/>
        <set_value name="$diagMk4DedicatedServe" exact="false"/>
        <set_value name="$diagMk4AllowResources" exact="true"/>
        <set_value name="$diagMk4AllowIntermediates" exact="true"/>
        <set_value name="$diagMk4AllowTradewares" exact="true"/>
        <set_value name="$diagMk4BuildStorageOnlyMode" exact="false"/>
        <set_value name="$diagMk4HomeAnchor" exact="$homeSector"/>
        <set_value name="$diagMk4HomeSector" exact="$homeSector"/>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply'">
          <set_value name="$diagMk4CustomerMustBePlayer" exact="true"/>
          <do_if value="$gtOrder? and $gtOrder.$buyFromPlayer?">
            <set_value name="$diagMk4AllowPlayerSuppliers" exact="$gtOrder.$buyFromPlayer"/>
          </do_if>
          <do_elseif value="$gtOrder? and $gtOrder.$allowPlayerSuppliers?">
            <set_value name="$diagMk4AllowPlayerSuppliers" exact="$gtOrder.$allowPlayerSuppliers"/>
          </do_elseif>
          <do_if value="$gtOrder? and $gtOrder.$buyFromFaction?">
            <set_value name="$diagMk4AllowAiSuppliers" exact="$gtOrder.$buyFromFaction"/>
          </do_if>
          <do_elseif value="$gtOrder? and $gtOrder.$allowAiSuppliers?">
            <set_value name="$diagMk4AllowAiSuppliers" exact="$gtOrder.$allowAiSuppliers"/>
          </do_elseif>
          <do_if value="$gtOrder? and $gtOrder.$allowResources?">
            <set_value name="$diagMk4AllowResources" exact="$gtOrder.$allowResources"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$allowIntermediates?">
            <set_value name="$diagMk4AllowIntermediates" exact="$gtOrder.$allowIntermediates"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$allowTradewares?">
            <set_value name="$diagMk4AllowTradewares" exact="$gtOrder.$allowTradewares"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$serveHomeOnly?">
            <set_value name="$diagMk4DedicatedServe" exact="$gtOrder.$serveHomeOnly"/>
          </do_if>
          <do_elseif value="$gtOrder? and $gtOrder.$dedicatedServe?">
            <set_value name="$diagMk4DedicatedServe" exact="$gtOrder.$dedicatedServe"/>
          </do_elseif>
          <do_if value="$gtOrder? and $gtOrder.$home? and $gtOrder.$home.exists">
            <set_value name="$diagMk4HomeAnchor" exact="$gtOrder.$home"/>
          </do_if>
          <set_value name="$diagMk4HomeSector" exact="if $diagMk4HomeAnchor? and $diagMk4HomeAnchor.isclass.sector then $diagMk4HomeAnchor else (if $diagMk4HomeAnchor? and $diagMk4HomeAnchor.sector? then @$diagMk4HomeAnchor.sector else $homeSector)"/>
          <set_value name="$diagMk4BuildStorageOnlyMode" exact="false"/>
          <do_if value="not $ignoreBuildStorage and not $diagMk4AllowResources and not $diagMk4AllowIntermediates and not $diagMk4AllowTradewares">
            <set_value name="$diagMk4BuildStorageOnlyMode" exact="true"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4 Customer Must Be Player', $Status = 'INFO', $Detail = if $diagMk4CustomerMustBePlayer then 'true' else 'false']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4 Supplier Policy', $Status = 'INFO', $Detail = 'player=' + (if $diagMk4AllowPlayerSuppliers then 'on' else 'off') + ', faction=' + (if $diagMk4AllowAiSuppliers then 'on' else 'off')]"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4 Ware Categories', $Status = 'INFO', $Detail = 'res/int/tw=' + (if $diagMk4AllowResources then 'on' else 'off') + '/' + (if $diagMk4AllowIntermediates then 'on' else 'off') + '/' + (if $diagMk4AllowTradewares then 'on' else 'off')]"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4 Build Storage Only Mode', $Status = if $diagMk4BuildStorageOnlyMode then 'PASS' else 'INFO', $Detail = if $diagMk4BuildStorageOnlyMode then ('active (BS on, all ware categories off; home=' + (if $diagMk4HomeAnchor? and $diagMk4HomeAnchor.exists then @$diagMk4HomeAnchor.knownname else 'unknown') + ')') else 'false']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4 Serve Home Only', $Status = 'INFO', $Detail = if $diagMk4DedicatedServe then ('true (home=' + (if $diagMk4HomeAnchor? and $diagMk4HomeAnchor.exists then @$diagMk4HomeAnchor.knownname else 'unknown') + ')') else 'false']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4 Execution Policy Snapshot', $Status = 'INFO', $Detail = 'pairView=all (PASS+FAIL with reason), priceCap=source&lt;=customer, demandGate=vanillaRes+gtInFlight(global), ignoreTradeRules=faction-access-only' + (if $diagMk4BuildStorageOnlyMode then ', buildStorageOnly=delivery to player BS within jumpDistanceCoverage' else '')]"/>
        </do_if>

        <!-- MK4-2 policy snapshot (class sliders â€” mirrors order.trade.galaxytradermk42) -->
        <set_value name="$diagMk42PrioBs" exact="10"/>
        <set_value name="$diagMk42PrioSt" exact="8"/>
        <set_value name="$diagMk42PrioAx" exact="0"/>
        <set_value name="$diagMk42PrioCr" exact="0"/>
        <set_value name="$diagMk42PrioWareMult" exact="1"/>
        <set_value name="$diagMk42AllowPlayerSuppliers" exact="true"/>
        <set_value name="$diagMk42AllowAiSuppliers" exact="true"/>
        <set_value name="$diagMk42DedicatedServe" exact="false"/>
        <set_value name="$diagMk42HomeAnchor" exact="$homeSector"/>
        <set_value name="$diagMk42BuildStorageOnlyMode" exact="false"/>
        <set_value name="$diagMk42NoDeliveryTargets" exact="false"/>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply2'">
          <set_value name="$diagMk42PrioBs" exact="if $gtOrder? and $gtOrder.$priorityBuildstorage? then $gtOrder.$priorityBuildstorage else 10"/>
          <set_value name="$diagMk42PrioSt" exact="if $gtOrder? and $gtOrder.$priorityStations? then $gtOrder.$priorityStations else 8"/>
          <set_value name="$diagMk42PrioAx" exact="if $gtOrder? and $gtOrder.$priorityAux? then $gtOrder.$priorityAux else 0"/>
          <set_value name="$diagMk42PrioCr" exact="if $gtOrder? and $gtOrder.$priorityCarrier? then $gtOrder.$priorityCarrier else 0"/>
          <set_value name="$diagMk42PrioWareMult" exact="if $gtOrder? and $gtOrder.$priorityscoremultiplier? then $gtOrder.$priorityscoremultiplier else 1"/>
          <do_if value="$gtOrder? and $gtOrder.$buyFromPlayer?">
            <set_value name="$diagMk42AllowPlayerSuppliers" exact="$gtOrder.$buyFromPlayer"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$buyFromFaction?">
            <set_value name="$diagMk42AllowAiSuppliers" exact="$gtOrder.$buyFromFaction"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$serveHomeOnly?">
            <set_value name="$diagMk42DedicatedServe" exact="$gtOrder.$serveHomeOnly"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$home? and $gtOrder.$home.exists">
            <set_value name="$diagMk42HomeAnchor" exact="$gtOrder.$home"/>
          </do_if>
          <set_value name="$diagMk42BuildStorageOnlyMode" exact="$diagMk42PrioBs gt 0 and $diagMk42PrioSt == 0 and $diagMk42PrioAx == 0 and $diagMk42PrioCr == 0"/>
          <set_value name="$diagMk42NoDeliveryTargets" exact="$diagMk42PrioBs == 0 and $diagMk42PrioSt == 0 and $diagMk42PrioAx == 0 and $diagMk42PrioCr == 0"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Class Priorities', $Status = if $diagMk42NoDeliveryTargets then 'WARN' else 'INFO', $Detail = 'BS=' + $diagMk42PrioBs + ' ST=' + $diagMk42PrioSt + ' AX=' + $diagMk42PrioAx + ' CR=' + $diagMk42PrioCr + ' (0=off, 1-10=score multiplier only)']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Priority Ware Bonus', $Status = 'INFO', $Detail = 'multiplier=' + $diagMk42PrioWareMult + ' (1=no bonus, 2-10=additive on base score)']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Supplier Policy', $Status = 'INFO', $Detail = 'player=' + (if $diagMk42AllowPlayerSuppliers then 'on' else 'off') + ', faction=' + (if $diagMk42AllowAiSuppliers then 'on' else 'off') + ' (score bias only; both sources stay in pool when on)']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Dual-Axis Buckets', $Status = 'INFO', $Detail = 'tradematch: delivery class (BS/ST/AX/CR) x supplier source (Player/Npc), top-K merge before score.trades']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Build-Storage-Only Mode', $Status = if $diagMk42BuildStorageOnlyMode then 'PASS' else 'INFO', $Detail = if $diagMk42BuildStorageOnlyMode then ('derived from sliders (home=' + (if $diagMk42HomeAnchor? and $diagMk42HomeAnchor.exists then @$diagMk42HomeAnchor.knownname else 'unknown') + ')') else 'false']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Serve Home Only', $Status = 'INFO', $Detail = if $diagMk42DedicatedServe then ('true (home=' + (if $diagMk42HomeAnchor? and $diagMk42HomeAnchor.exists then @$diagMk42HomeAnchor.knownname else 'unknown') + ')') else 'false']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 No Delivery Targets', $Status = if $diagMk42NoDeliveryTargets then 'WARN' else 'PASS', $Detail = if $diagMk42NoDeliveryTargets then 'All class sliders are 0 â€” ship idles (no search)' else 'false']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'MK4-2 Execution Policy Snapshot', $Status = 'INFO', $Detail = 'dual-axis buckets, score.trades normBase x slider, validation order=finalScore (no class-first reorder), mk4_supply_v2 pool, cache=GT_TradeCacheMK42']"/>
          <!-- Mirror MK4 diag flags so Sec8 pair-scan reuses the same supply-order policy gates. -->
          <set_value name="$diagMk4CustomerMustBePlayer" exact="true"/>
          <set_value name="$diagMk4AllowPlayerSuppliers" exact="$diagMk42AllowPlayerSuppliers"/>
          <set_value name="$diagMk4AllowAiSuppliers" exact="$diagMk42AllowAiSuppliers"/>
          <set_value name="$diagMk4BuildStorageOnlyMode" exact="$diagMk42BuildStorageOnlyMode"/>
          <set_value name="$diagMk4DedicatedServe" exact="$diagMk42DedicatedServe"/>
          <set_value name="$diagMk4HomeAnchor" exact="if $diagMk42HomeAnchor? then $diagMk42HomeAnchor else null"/>
          <set_value name="$diagMk4HomeSector" exact="if $diagMk42HomeAnchor? and $diagMk42HomeAnchor.exists then (if $diagMk42HomeAnchor.isclass.sector then $diagMk42HomeAnchor else @$diagMk42HomeAnchor.sector) else $homeSector"/>
        </do_if>

        <!-- Auto Wares (MK2/MK3/MK4 - when off, Ware Basket is used) -->
        <set_value name="$autoWares" exact="true"/>
        <do_if value="$gtOrder? and $gtOrder.$autowares?">
          <set_value name="$autoWares" exact="$gtOrder.$autowares"/>
        </do_if>
        <set_value name="$autoWaresDetail" exact="if $autoWares then 'On (auto-select)' else 'Off (manual Ware Basket)'"/>
        <do_if value="$orderId == 'GalaxyTraderMK1'">
          <set_value name="$autoWaresDetail" exact="'N/A (MK1 uses station products)'"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Auto Wares', $Status = 'INFO', $Detail = $autoWaresDetail]"/>

        <!-- Ware basket (or MK1 Ware Filter) -->
        <set_value name="$wareBasket" exact="[]"/>
        <do_if value="$gtOrder? and $gtOrder.$warebasket? and $gtOrder.$warebasket.count gt 0">
          <set_value name="$wareBasket" exact="$gtOrder.$warebasket"/>
        </do_if>
        <set_value name="$wareBasketDetail" exact="'All wares (no restriction)'"/>
        <do_if value="$wareBasket.count gt 0">
          <set_value name="$wareBasketNames" exact="''"/>
          <do_all exact="[$wareBasket.count, 15].min" counter="$wbi">
            <set_value name="$wbWare" exact="$wareBasket.{$wbi}"/>
            <do_if value="$wbWare?">
              <set_value name="$wbName" exact="if $wbWare.name? then $wbWare.name else '?'"/>
              <do_if value="$wareBasketNames != ''">
                <set_value name="$wareBasketNames" exact="$wareBasketNames + ', '"/>
              </do_if>
              <set_value name="$wareBasketNames" exact="$wareBasketNames + $wbName"/>
            </do_if>
          </do_all>
          <do_if value="$wareBasket.count gt 15">
            <set_value name="$wareBasketDetail" exact="'' + $wareBasket.count + ' wares: ' + $wareBasketNames + ', ...'"/>
          </do_if>
          <do_else>
            <set_value name="$wareBasketDetail" exact="'' + $wareBasket.count + ' wares: ' + $wareBasketNames"/>
          </do_else>
        </do_if>
        <set_value name="$wareBasketCheckName" exact="'Ware Basket'"/>
        <do_if value="$orderId == 'GalaxyTraderMK1' and $wareBasket.count gt 0">
          <set_value name="$wareBasketCheckName" exact="'Ware Filter (MK1 sell restriction)'"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = $wareBasketCheckName, $Status = 'INFO', $Detail = $wareBasketDetail]"/>
        <do_if value="$autoWares and ($orderId == 'GalaxyTraderMK2' or $orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $wareBasket.count gt 0">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Manual Basket Active', $Status = 'WARN', $Detail = 'No (Auto Wares is ON; manual basket is ignored at runtime)']"/>
        </do_if>
        <!-- Runtime-parity active pair filter:
             MK2/MK3/MK4 only use manual ware basket when Auto Wares is disabled.
             MK1/miner have dedicated diagnose paths and are excluded here. -->
        <set_value name="$diagPairWareFilter" exact="[]"/>
        <set_value name="$diagPairWareFilterActive" exact="false"/>
        <do_if value="($orderId == 'GalaxyTraderMK2' or $orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and (not $autoWares) and $wareBasket.count gt 0">
          <set_value name="$diagPairWareFilter" exact="$wareBasket"/>
          <set_value name="$diagPairWareFilterActive" exact="true"/>
        </do_if>

        <!-- Priority wares (MK3 only) -->
        <set_value name="$priorityWares" exact="[]"/>
        <do_if value="$gtOrder? and $gtOrder.$prioritywares? and $gtOrder.$prioritywares.count gt 0">
          <set_value name="$priorityWares" exact="$gtOrder.$prioritywares"/>
        </do_if>
        <set_value name="$priorityWaresDetail" exact="'None (no priority override)'"/>
        <do_if value="$priorityWares.count gt 0">
          <set_value name="$priorityWaresNames" exact="''"/>
          <do_all exact="[$priorityWares.count, 15].min" counter="$pwi">
            <set_value name="$pwWare" exact="$priorityWares.{$pwi}"/>
            <do_if value="$pwWare?">
              <set_value name="$pwName" exact="if $pwWare.name? then $pwWare.name else '?'"/>
              <do_if value="$priorityWaresNames != ''">
                <set_value name="$priorityWaresNames" exact="$priorityWaresNames + ', '"/>
              </do_if>
              <set_value name="$priorityWaresNames" exact="$priorityWaresNames + $pwName"/>
            </do_if>
          </do_all>
          <do_if value="$priorityWares.count gt 15">
            <set_value name="$priorityWaresDetail" exact="'' + $priorityWares.count + ' wares: ' + $priorityWaresNames + ', ...'"/>
          </do_if>
          <do_else>
            <set_value name="$priorityWaresDetail" exact="'' + $priorityWares.count + ' wares: ' + $priorityWaresNames"/>
          </do_else>
        </do_if>
        <do_if value="$orderId == 'GalaxyTraderMK1' or $orderId == 'GalaxyTraderMK2' or $orderId == 'GalaxyMiner'">
          <set_value name="$priorityWaresDetail" exact="'N/A'"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Priority Wares', $Status = 'INFO', $Detail = $priorityWaresDetail]"/>

        <!-- Faction Priority (MK3 only - 10% score bonus for own stations) -->
        <set_value name="$factionPriority" exact="false"/>
        <do_if value="$gtOrder? and $gtOrder.$factionpriority?">
          <set_value name="$factionPriority" exact="$gtOrder.$factionpriority"/>
        </do_if>
        <set_value name="$factionPriorityDetail" exact="if $factionPriority then 'On (+10% own stations)' else 'Off'"/>
        <do_if value="$orderId == 'GalaxyTraderMK1' or $orderId == 'GalaxyTraderMK2' or $orderId == 'GalaxyMiner'">
          <set_value name="$factionPriorityDetail" exact="'N/A'"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Faction Priority', $Status = 'INFO', $Detail = $factionPriorityDetail]"/>

        <!-- Distance Penalty (MK3/MK2 - % impact on trade scoring) -->
        <set_value name="$distancePenalty" exact="50"/>
        <do_if value="$gtOrder? and $gtOrder.$distancepenalty?">
          <set_value name="$distancePenalty" exact="$gtOrder.$distancepenalty"/>
        </do_if>
        <set_value name="$distancePenaltyDetail" exact="'' + $distancePenalty + '% (0=ignore dist, 100=strongly prefer close)'"/>
        <do_if value="$orderId == 'GalaxyTraderMK1' or $orderId == 'GalaxyMiner'">
          <set_value name="$distancePenaltyDetail" exact="'N/A'"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Distance Penalty', $Status = 'INFO', $Detail = $distancePenaltyDetail]"/>

        <!-- Ship proximity nudge at validation (MK3/MK4 â€” global only, mirrors lib.gt.score.selection_sort). -->
        <set_value name="$diagShipProxWeight" exact="0.04"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Trading? and global.$GT_GlobalSettings.$Trading.$ShipProximityWeight?">
          <set_value name="$diagShipProxWeight" exact="@global.$GT_GlobalSettings.$Trading.$ShipProximityWeight"/>
        </do_if>
        <set_value name="$shipProxDetail" exact="'' + $diagShipProxWeight + ' (validation sort: score / (1 + shipâ†’buy Ã— weight); 0=off)'"/>
        <do_if value="$orderId == 'GalaxyTraderMK1' or $orderId == 'GalaxyTraderMK2' or $orderId == 'GalaxyMiner'">
          <set_value name="$shipProxDetail" exact="'N/A'"/>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ship Proximity Weight', $Status = 'INFO', $Detail = $shipProxDetail]"/>

        <!-- Sector Whitelist (sectors exempt from threat blacklist) -->
        <run_actions ref="md.GT_Libraries_Blacklist.GT_GetSectorWhitelist" result="$sectorWhitelist">
          <param name="ship" value="$ship"/>
        </run_actions>
        <set_value name="$sectorWhitelistDetail" exact="'None'"/>
        <set_value name="$swCount" exact="0"/>
        <do_if value="$sectorWhitelist? and $sectorWhitelist.count?">
          <set_value name="$swCount" exact="$sectorWhitelist.count"/>
          <do_if value="$swCount gt 0">
            <set_value name="$swNames" exact="''"/>
            <do_all exact="[$swCount, 8].min" counter="$swi">
              <set_value name="$swSec" exact="$sectorWhitelist.{$swi}"/>
              <do_if value="$swSec? and $swSec.knownname?">
                <do_if value="$swNames != ''">
                  <set_value name="$swNames" exact="$swNames + ', '"/>
                </do_if>
                <set_value name="$swNames" exact="$swNames + $swSec.knownname"/>
              </do_if>
            </do_all>
            <set_value name="$sectorWhitelistDetail" exact="'' + $swCount + ' sectors exempt' + (if $swNames != '' then ': ' + $swNames + (if $swCount gt 8 then ', ...' else '') else '')"/>
          </do_if>
        </do_if>
        <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Sector Whitelist', $Status = 'INFO', $Detail = $sectorWhitelistDetail]"/>

        <!-- MK1-specific: Home Station, Supply Mode -->
        <do_if value="$orderId == 'GalaxyTraderMK1'">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = '--- MK1 Specific ---', $Status = 'INFO', $Detail = '']"/>
          <set_value name="$mk1HomeStation" exact="'Not set'"/>
          <do_if value="$gtOrder? and $gtOrder.$homeStation? and $gtOrder.$homeStation.exists">
            <set_value name="$mk1HomeStation" exact="$gtOrder.$homeStation.knownname"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Home Station', $Status = if $mk1HomeStation == 'Not set' then 'FAIL' else 'PASS', $Detail = $mk1HomeStation]"/>
          <set_value name="$mk1Supply" exact="false"/>
          <do_if value="$gtOrder? and $gtOrder.$supply?">
            <set_value name="$mk1Supply" exact="$gtOrder.$supply"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Supply Mode', $Status = 'INFO', $Detail = if $mk1Supply then 'On (also buys resources)' else 'Off']"/>
          <set_value name="$mk1MinSellStorage" exact="0"/>
          <do_if value="$gtOrder? and $gtOrder.$minsellstorage?">
            <set_value name="$mk1MinSellStorage" exact="[0, [$gtOrder.$minsellstorage, 100].min].max"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Min Product Storage %', $Status = 'INFO', $Detail = if $mk1MinSellStorage gt 0 then '' + $mk1MinSellStorage + '% (export gate active)' else '0 (disabled)']"/>
          <!-- Order-param price range (slider 0-200, 100 = neutral -> norm -1.0..+1.0); mirrors runtime MK1 search. -->
          <set_value name="$mk1DiagPriceOffset" exact="90"/>
          <do_if value="$gtOrder? and $gtOrder.$pricerange?">
            <do_if value="$gtOrder.$pricerange ge 0 and $gtOrder.$pricerange le 200">
              <set_value name="$mk1DiagPriceOffset" exact="$gtOrder.$pricerange"/>
            </do_if>
            <do_elseif value="$gtOrder.$pricerange ge -100 and $gtOrder.$pricerange lt 0">
              <set_value name="$mk1DiagPriceOffset" exact="$gtOrder.$pricerange + 100"/>
            </do_elseif>
          </do_if>
          <set_value name="$mk1DiagPriceOffset" exact="[$mk1DiagPriceOffset, 0].max"/>
          <set_value name="$mk1DiagPriceOffset" exact="[$mk1DiagPriceOffset, 200].min"/>
          <set_value name="$mk1DiagPriceNorm" exact="($mk1DiagPriceOffset - 100) / 100"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Buyer Price Range', $Status = 'INFO', $Detail = 'slider ' + $mk1DiagPriceOffset + '/200 (100=neutral, norm ' + $mk1DiagPriceNorm + ') -> buy min ' + $mk1DiagPriceNorm + ', supply sell max ' + (0 - $mk1DiagPriceNorm)]"/>

          <!-- MK1 diagnostics mirrored from order.trade.galaxytradermk1.xml -->
          <set_value name="$mk1WareSnapshotSig" exact="'pending (no MK1 cycle snapshot yet)'"/>
          <do_if value="$gtOrder? and $gtOrder.$mk1_lastWaresSnapshotSig? and $gtOrder.$mk1_lastWaresSnapshotSig != ''">
            <set_value name="$mk1WareSnapshotSig" exact="$gtOrder.$mk1_lastWaresSnapshotSig"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'WARE_SNAPSHOT*', $Status = if $mk1WareSnapshotSig == 'pending (no MK1 cycle snapshot yet)' then 'WARN' else 'INFO', $Detail = $mk1WareSnapshotSig]"/>

          <set_value name="$mk1SellStorageGateSig" exact="'pending (no MK1 export gate snapshot yet)'"/>
          <do_if value="$gtOrder? and $gtOrder.$mk1_lastSellStorageGateSig? and $gtOrder.$mk1_lastSellStorageGateSig != ''">
            <set_value name="$mk1SellStorageGateSig" exact="$gtOrder.$mk1_lastSellStorageGateSig"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'SELL_STORAGE_GATE', $Status = if $mk1SellStorageGateSig == 'pending (no MK1 export gate snapshot yet)' then 'WARN' else 'INFO', $Detail = $mk1SellStorageGateSig]"/>

          <set_value name="$mk1SellOfferSnapshotSig" exact="'pending (no MK1 cycle snapshot yet)'"/>
          <do_if value="$gtOrder? and $gtOrder.$mk1_lastSellOffersSnapshotSig? and $gtOrder.$mk1_lastSellOffersSnapshotSig != ''">
            <set_value name="$mk1SellOfferSnapshotSig" exact="$gtOrder.$mk1_lastSellOffersSnapshotSig"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'SELL_OFFER_SNAPSHOT', $Status = if $mk1SellOfferSnapshotSig == 'pending (no MK1 cycle snapshot yet)' then 'WARN' else 'INFO', $Detail = $mk1SellOfferSnapshotSig]"/>

          <set_value name="$mk1RoutePlanSnapshotSig" exact="'pending (no MK1 route plan snapshot yet)'"/>
          <do_if value="$gtOrder? and $gtOrder.$mk1_lastRoutePlanSig? and $gtOrder.$mk1_lastRoutePlanSig != ''">
            <set_value name="$mk1RoutePlanSnapshotSig" exact="$gtOrder.$mk1_lastRoutePlanSig"/>
          </do_if>
          <do_elseif value="$ship.tradeorders? and $ship.tradeorders.count gt 0">
            <set_value name="$mk1RoutePlanFallback" exact="''"/>
            <set_value name="$mk1RoutePlanFallbackMax" exact="10"/>
            <do_all exact="$ship.tradeorders.count" counter="$mk1rti">
              <do_if value="$mk1rti gt $mk1RoutePlanFallbackMax">
                <set_value name="$mk1RoutePlanFallback" exact="$mk1RoutePlanFallback + ' | ...+' + ($ship.tradeorders.count - $mk1RoutePlanFallbackMax)"/>
                <break/>
              </do_if>
              <set_value name="$mk1rt" exact="$ship.tradeorders.{$mk1rti}"/>
              <set_value name="$mk1rtWareName" exact="if $mk1rt? and $mk1rt.ware? and $mk1rt.ware.name? then @$mk1rt.ware.name else '?'"/>
              <set_value name="$mk1rtDestName" exact="if $mk1rt? and $mk1rt.buyer? and $mk1rt.buyer.exists and $mk1rt.buyer.knownname? then @$mk1rt.buyer.knownname else '?'"/>
              <set_value name="$mk1rtAmount" exact="if $mk1rt? and $mk1rt.amount? then $mk1rt.amount else 0"/>
              <set_value name="$mk1RoutePlanFallback" exact="$mk1RoutePlanFallback + (if $mk1rti gt 1 then ' | ' else '') + $mk1rtWareName + '->' + $mk1rtDestName + '(' + $mk1rtAmount + ')'"/>
            </do_all>
            <set_value name="$mk1RoutePlanSnapshotSig" exact="'tradeorders=' + $ship.tradeorders.count + ' [' + $mk1RoutePlanFallback + ']'"/>
          </do_elseif>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'ROUTE_PLAN', $Status = if $mk1RoutePlanSnapshotSig == 'pending (no MK1 route plan snapshot yet)' then 'WARN' else 'INFO', $Detail = $mk1RoutePlanSnapshotSig]"/>
        </do_if>

        <!-- MK2-specific: Source/Destination lists.
             $mk2SourceCount / $mk2DestCount are pre-initialized outside the order-id gate
             because the verdict block (much later) reads them for any order id when picking
             priority 1a/1b - reading an undefined var would raise "Property lookup failed".
             For non-MK2 orders the counts stay at 0 and are never displayed.
             The MK2 storage-gate fields ($mk2*Storage*, $mk2SourceWares*, $mk2WorstSource*)
             are initialized here for the same reason - the verdict's MK2-storage branch
             reads them unconditionally and must not crash on non-MK2 orders. -->
        <set_value name="$mk2SourceCount" exact="0"/>
        <set_value name="$mk2DestCount" exact="0"/>
        <set_value name="$mk2MinStorage" exact="20"/>
        <set_value name="$mk2StaticStorage" exact="40"/>
        <set_value name="$mk2MaxStorage" exact="70"/>
        <set_value name="$mk2SourceWaresEvaluated" exact="0"/>
        <set_value name="$mk2SourceWaresBelowStatic" exact="0"/>
        <set_value name="$mk2SourceWaresMissingTarget" exact="0"/>
        <set_value name="$mk2WorstSourceRatio" exact="-1"/>
        <set_value name="$mk2WorstSourceDetail" exact="''"/>
        <set_value name="$mk2BestSourceRatio" exact="-1"/>
        <set_value name="$mk2BestSourceDetail" exact="''"/>
        <!-- bidirectional / ware-exchange awareness (read once, reused by the MK2 reserve
             eval AND the pair-evaluation section far below). Default to the unidirectional /
             offer-based model so non-MK2 orders and older saves behave exactly as before. -->
        <set_value name="$mk2OrderBidirectional" exact="false"/>
        <set_value name="$mk2OrderIgnoreOffers" exact="false"/>
        <set_value name="$mk2SupplierList" exact="[]"/>
        <set_value name="$mk2CustomerList" exact="[]"/>
        <do_if value="$orderId == 'GalaxyTraderMK2'">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = '--- MK2 Specific ---', $Status = 'INFO', $Detail = '']"/>
          <do_if value="$gtOrder? and $gtOrder.$sourceList? and $gtOrder.$sourceList.count?">
            <set_value name="$mk2SourceCount" exact="$gtOrder.$sourceList.count"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$destList? and $gtOrder.$destList.count?">
            <set_value name="$mk2DestCount" exact="$gtOrder.$destList.count"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Source Stations', $Status = if $mk2SourceCount gt 0 then 'PASS' else 'FAIL', $Detail = '' + $mk2SourceCount + ' stations']"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Destination Stations', $Status = if $mk2DestCount gt 0 then 'PASS' else 'FAIL', $Detail = '' + $mk2DestCount + ' stations']"/>

          <!-- Read bidirectional + ignoreoffersettings and build the supplier/customer role
               lists exactly like the runtime does (order.trade.galaxytraderMK2.xml lines
               1212-1227). In bidirectional mode every participating station can both supply
               and receive, so suppliers == customers == dedup union of source + dest lists.
               Otherwise suppliers = source list, customers = destination list. These lists
               are reused by the MK2 reserve eval below AND the pair-evaluation section. -->
          <set_value name="$mk2OrderBidirectional" exact="if $gtOrder.$bidirectional? then $gtOrder.$bidirectional else false"/>
          <set_value name="$mk2OrderIgnoreOffers" exact="if $gtOrder.$ignoreoffersettings? then $gtOrder.$ignoreoffersettings else false"/>
          <do_if value="$mk2OrderBidirectional">
            <set_value name="$mk2Union" exact="[]"/>
            <do_if value="$gtOrder.$sourceList?">
              <do_all exact="$gtOrder.$sourceList.count" counter="$mk2ui">
                <set_value name="$mk2us" exact="$gtOrder.$sourceList.{$mk2ui}"/>
                <set_value name="$mk2udup" exact="false"/>
                <do_all exact="$mk2Union.count" counter="$mk2udi">
                  <do_if value="$mk2Union.{$mk2udi} == $mk2us">
                    <set_value name="$mk2udup" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="not $mk2udup">
                  <append_to_list name="$mk2Union" exact="$mk2us"/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="$gtOrder.$destList?">
              <do_all exact="$gtOrder.$destList.count" counter="$mk2ui2">
                <set_value name="$mk2us2" exact="$gtOrder.$destList.{$mk2ui2}"/>
                <set_value name="$mk2udup2" exact="false"/>
                <do_all exact="$mk2Union.count" counter="$mk2udi2">
                  <do_if value="$mk2Union.{$mk2udi2} == $mk2us2">
                    <set_value name="$mk2udup2" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="not $mk2udup2">
                  <append_to_list name="$mk2Union" exact="$mk2us2"/>
                </do_if>
              </do_all>
            </do_if>
            <set_value name="$mk2SupplierList" exact="$mk2Union"/>
            <set_value name="$mk2CustomerList" exact="$mk2Union"/>
            <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Direction', $Status = 'INFO', $Detail = 'BIDIRECTIONAL - every station can supply or receive (' + $mk2Union.count + ' participating stations, both directions evaluated)']"/>
          </do_if>
          <do_else>
            <set_value name="$mk2SupplierList" exact="if $gtOrder.$sourceList? then $gtOrder.$sourceList else []"/>
            <set_value name="$mk2CustomerList" exact="if $gtOrder.$destList? then $gtOrder.$destList else []"/>
          </do_else>
          <do_if value="$mk2OrderIgnoreOffers">
            <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Ware Exchange', $Status = 'INFO', $Detail = 'ON (ignoreoffersettings) - player-owned stations trade via storage discovery; a formal sell/buy offer is NOT required']"/>
          </do_if>

          <!-- Read the configured storage thresholds and mirror the runtime normalization
               (order.trade.galaxytraderMK2.xml init + main_loop): range-clamp each band,
               then enforce the min&lt;static&lt;max ladder ONLY in bidirectional mode. In
               unidirectional mode the three thresholds are independent (e.g. 98/0/0 = "fill
               destinations to 98%, drain sources fully"), so we must NOT bump static up to
               min+1 there - doing so previously made the diag report a frozen trader (static
               clamped to 99%) when the runtime was actually trading. -->
          <do_if value="$gtOrder.$minStorage?">
            <set_value name="$mk2MinStorage" exact="[0, [$gtOrder.$minStorage, 98].min].max"/>
          </do_if>
          <do_if value="$gtOrder.$staticStorage?">
            <set_value name="$mk2StaticStorage" exact="[0, [$gtOrder.$staticStorage, 99].min].max"/>
          </do_if>
          <do_if value="$gtOrder.$maxStorage?">
            <set_value name="$mk2MaxStorage" exact="[0, [$gtOrder.$maxStorage, 100].min].max"/>
          </do_if>
          <do_if value="$mk2OrderBidirectional">
            <do_if value="$mk2StaticStorage le $mk2MinStorage">
              <set_value name="$mk2StaticStorage" exact="[99, $mk2MinStorage + 1].min"/>
            </do_if>
            <do_if value="$mk2MaxStorage le $mk2StaticStorage">
              <set_value name="$mk2MaxStorage" exact="[100, $mk2StaticStorage + 1].min"/>
            </do_if>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Storage Thresholds (min/static/max)', $Status = 'INFO', $Detail = '' + $mk2MinStorage + '% / ' + $mk2StaticStorage + '% / ' + $mk2MaxStorage + '% (source must be ABOVE static; dest must be AT OR BELOW min' + (if $mk2OrderBidirectional then '; bidirectional ladder enforced' else '; independent thresholds') + ')']"/>

          <!-- Per-source / per-ware static-storage gate evaluation.
               Mirrors the runtime gate at order.trade.galaxytraderMK2.xml line 1410:
                 sourceRatio = (cargo.{ware}.count * 100) / cargo.{ware}.target
                 if sourceRatio &lt;= staticStorage  -> skipSourceBelowStatic (no trade)
               We omit the get_ware_reservation correction (in-flight buy reservations) because
               that is a small overstatement only and the diag is meant to surface the
               player-actionable threshold, not produce byte-exact numbers. Capped at 12 rows
               to avoid swamping the report when many wares are involved. -->
          <do_if value="$mk2SupplierList.count gt 0">
            <set_value name="$mk2SrcRowCap" exact="12"/>
            <set_value name="$mk2SrcRowsAdded" exact="0"/>
            <do_all exact="$mk2SupplierList.count" counter="$mk2si">
              <set_value name="$mk2SrcStation" exact="$mk2SupplierList.{$mk2si}"/>
              <do_if value="$mk2SrcStation? and $mk2SrcStation.exists">
                <set_value name="$mk2SrcProducts" exact="$mk2SrcStation.products.list"/>
                <set_value name="$mk2SrcTradewares" exact="$mk2SrcStation.tradewares.list"/>
                <create_list name="$mk2SrcSellable"/>
                <do_all exact="$mk2SrcProducts.count" counter="$mk2spi">
                  <append_to_list name="$mk2SrcSellable" exact="$mk2SrcProducts.{$mk2spi}"/>
                </do_all>
                <do_all exact="$mk2SrcTradewares.count" counter="$mk2sti">
                  <set_value name="$mk2stw" exact="$mk2SrcTradewares.{$mk2sti}"/>
                  <set_value name="$dup" exact="false"/>
                  <do_all exact="$mk2SrcSellable.count" counter="$mk2sdi">
                    <do_if value="$mk2SrcSellable.{$mk2sdi} == $mk2stw">
                      <set_value name="$dup" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                  <do_if value="not $dup">
                    <append_to_list name="$mk2SrcSellable" exact="$mk2stw"/>
                  </do_if>
                </do_all>
                <do_all exact="$mk2SrcSellable.count" counter="$mk2swi">
                  <set_value name="$mk2sw" exact="$mk2SrcSellable.{$mk2swi}"/>
                  <set_value name="$mk2swCount" exact="$mk2SrcStation.cargo.{$mk2sw}.count"/>
                  <set_value name="$mk2swTarget" exact="$mk2SrcStation.cargo.{$mk2sw}.target"/>
                  <do_if value="$mk2swTarget le 0">
                    <!-- Runtime treats target&lt;=0 as srcNoTarget (continue, no skip), so do
                         not count it as a static-reserve violation; record separately. -->
                    <set_value name="$mk2SourceWaresMissingTarget" operation="add"/>
                    <do_if value="$mk2SrcRowsAdded lt $mk2SrcRowCap">
                      <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Source Reserve: ' + @$mk2SrcStation.knownname + ' / ' + $mk2sw, $Status = 'WARN', $Detail = 'cargo target = 0 (station has no allocated storage for this ware - runtime skips silently)']"/>
                      <set_value name="$mk2SrcRowsAdded" operation="add"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <set_value name="$mk2swRatio" exact="($mk2swCount * 100) / $mk2swTarget"/>
                    <set_value name="$mk2SourceWaresEvaluated" operation="add"/>
                    <set_value name="$mk2swPasses" exact="$mk2swRatio gt $mk2StaticStorage"/>
                    <do_if value="not $mk2swPasses">
                      <set_value name="$mk2SourceWaresBelowStatic" operation="add"/>
                    </do_if>
                    <!-- Track best (highest) and worst (lowest) ratios for the verdict line. -->
                    <do_if value="$mk2WorstSourceRatio lt 0 or $mk2swRatio lt $mk2WorstSourceRatio">
                      <set_value name="$mk2WorstSourceRatio" exact="$mk2swRatio"/>
                      <set_value name="$mk2WorstSourceDetail" exact="@$mk2SrcStation.knownname + ' [' + @$mk2SrcStation.idcode + '] ' + $mk2sw + ' = ' + $mk2swCount + ' / ' + $mk2swTarget + ' (' + $mk2swRatio + '%)'"/>
                    </do_if>
                    <do_if value="$mk2swRatio gt $mk2BestSourceRatio">
                      <set_value name="$mk2BestSourceRatio" exact="$mk2swRatio"/>
                      <set_value name="$mk2BestSourceDetail" exact="@$mk2SrcStation.knownname + ' [' + @$mk2SrcStation.idcode + '] ' + $mk2sw + ' = ' + $mk2swCount + ' / ' + $mk2swTarget + ' (' + $mk2swRatio + '%)'"/>
                    </do_if>
                    <do_if value="$mk2SrcRowsAdded lt $mk2SrcRowCap">
                      <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Source Reserve: ' + @$mk2SrcStation.knownname + ' / ' + $mk2sw, $Status = if $mk2swPasses then 'PASS' else 'BLOCK', $Detail = '' + $mk2swCount + ' / ' + $mk2swTarget + ' = ' + $mk2swRatio + '% ' + (if $mk2swPasses then '&gt; ' else '&lt;= ') + $mk2StaticStorage + '% staticStorage' + (if $mk2swPasses then ' (eligible to ship)' else ' (BELOW reserve - runtime refuses to drain)')]"/>
                      <set_value name="$mk2SrcRowsAdded" operation="add"/>
                    </do_if>
                  </do_else>
                </do_all>
              </do_if>
            </do_all>
            <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Source Reserve Summary', $Status = if $mk2SourceWaresEvaluated == 0 then 'WARN' else (if $mk2SourceWaresBelowStatic == $mk2SourceWaresEvaluated then 'BLOCK' else (if $mk2SourceWaresBelowStatic gt 0 then 'WARN' else 'PASS')), $Detail = '' + ($mk2SourceWaresEvaluated - $mk2SourceWaresBelowStatic) + ' / ' + $mk2SourceWaresEvaluated + ' source-ware combinations are above the static reserve' + (if $mk2SourceWaresMissingTarget gt 0 then ' (' + $mk2SourceWaresMissingTarget + ' have no storage allocated)' else '')]"/>
          </do_if>
        </do_if>

        <!-- Miner-specific: Home Anchor, Target Stations, Overflow -->
        <do_if value="$orderId == 'GalaxyMiner'">
          <append_to_list name="$sec3.$Rows" exact="table[$Check = '--- Miner Specific ---', $Status = 'INFO', $Detail = '']"/>
          <set_value name="$minerHome" exact="'Not set'"/>
          <do_if value="$gtOrder?">
            <do_if value="$gtOrder.$homeStation? and $gtOrder.$homeStation.exists">
              <set_value name="$minerHome" exact="'Station: ' + $gtOrder.$homeStation.knownname"/>
            </do_if>
            <do_elseif value="$gtOrder.$homeSector? and $gtOrder.$homeSector.exists">
              <set_value name="$minerHome" exact="'Sector: ' + $gtOrder.$homeSector.knownname"/>
            </do_elseif>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Home Anchor', $Status = if $minerHome == 'Not set' then 'FAIL' else 'PASS', $Detail = $minerHome]"/>
          
          <set_value name="$diagMinerConfiguredTargetCount" exact="0"/>
          <do_if value="$gtOrder? and $gtOrder.$stationList? and $gtOrder.$stationList.count?">
            <set_value name="$diagMinerConfiguredTargetCount" exact="$gtOrder.$stationList.count"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Configured Target Stations', $Status = if $diagMinerConfiguredTargetCount gt 0 then 'PASS' else 'INFO', $Detail = '' + $diagMinerConfiguredTargetCount + ' in stationList (empty = miner auto-discovers demand stations at runtime)']"/>
          
          <set_value name="$minerOverflow" exact="false"/>
          <do_if value="$gtOrder? and $gtOrder.$allowOverflowSellToOthers?">
            <set_value name="$minerOverflow" exact="$gtOrder.$allowOverflowSellToOthers"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Overflow Sell', $Status = 'INFO', $Detail = if $minerOverflow then 'Enabled' else 'Disabled']"/>
          <set_value name="$minerPlayerOnly" exact="false"/>
          <do_if value="$gtOrder? and $gtOrder.$playerStationsOnly?">
            <set_value name="$minerPlayerOnly" exact="$gtOrder.$playerStationsOnly"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Player Stations Only', $Status = 'INFO', $Detail = if $minerPlayerOnly then 'true' else 'false']"/>
          <set_value name="$diagMinerCheckDemandFirst" exact="true"/>
          <do_if value="$gtOrder? and $gtOrder.$checkDemandFirst?">
            <set_value name="$diagMinerCheckDemandFirst" exact="$gtOrder.$checkDemandFirst"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Check Demand First', $Status = if $diagMinerCheckDemandFirst then 'INFO' else 'WARN', $Detail = if $diagMinerCheckDemandFirst then 'true (demand-first) - checks station demand before starting to mine' else 'false (demand-off / stockpile) - mines proactively; selling still uses primary stations below overflow threshold or Overflow sell']"/>
          <do_if value="not $diagMinerCheckDemandFirst">
            <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Demand-off Note', $Status = 'INFO', $Detail = 'Toggle OFF bypasses the mining demand gate only. Full bay with no willing buyer enters standby until capacity opens or overflow sell is enabled.']"/>
          </do_if>
          <set_value name="$minerOverflowThreshold" exact="90"/>
          <do_if value="$gtOrder? and $gtOrder.$overflowThreshold?">
            <set_value name="$minerOverflowThreshold" exact="[70, [100, $gtOrder.$overflowThreshold].min].max"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Overflow Threshold', $Status = 'INFO', $Detail = '' + $minerOverflowThreshold + '%']"/>
        </do_if>

        <!-- Miner diagnose ware scope: only mineable wares currently in cargo or actively mined now. -->
        <set_value name="$diagMinerOfferWares" exact="[]"/>
        <set_value name="$diagMinerOfferWaresDetail" exact="'N/A (non-miner order)'"/>
        <set_value name="$diagMinerPlayerStationsOnly" exact="false"/>
        <set_value name="$diagMinerOverflowThreshold" exact="90"/>
        <set_value name="$diagMinerAllowOverflowSellToOthers" exact="false"/>
        <set_value name="$diagMinerOverflowMode" exact="false"/>
        <set_value name="$diagMinerPrimaryStations" exact="[]"/>
        <set_value name="$diagMinerPolicySummary" exact="'N/A (non-miner order)'"/>
        <set_value name="$diagMinerRejectPlayerOnly" exact="0"/>
        <set_value name="$diagMinerRejectNotPrimary" exact="0"/>
        <set_value name="$diagMinerRejectOverflow" exact="0"/>
        <set_value name="$diagMinerRejectTargetZero" exact="0"/>
        <set_value name="$diagMinerRejectOverflowNoFallback" exact="0"/>
        <set_value name="$diagMinerRejectOverflowPrimaryExcluded" exact="0"/>
        <set_value name="$diagMinerPolicyRejectedSamples" exact="[]"/>
        <set_value name="$diagMinerPolicyBreakdown" exact="''"/>
        <set_value name="$diagMinerWareHasPrimaryCapacity" exact="table[]"/>
        <set_value name="$diagMinerWareViableBuyers" exact="table[]"/>
        <set_value name="$diagMinerCargoBlocksMining" exact="false"/>
        <set_value name="$diagMinerCargoBlockDetail" exact="''"/>
        <set_value name="$diagMinerFullBayNeedsClearance" exact="false"/>
        <set_value name="$diagMinerHasUnsellableCargo" exact="false"/>
        <set_value name="$diagMinerUnsellableCargoDetail" exact="''"/>
        <set_value name="$diagMinerOnSellRun" exact="false"/>
        <set_value name="$diagMinerSellRunDetail" exact="''"/>
        <set_value name="$diagMinerConfiguredTargetCount" exact="0"/>
        <set_value name="$diagMinerRuntimeDemandAdded" exact="0"/>
        <set_value name="$diagMinerCargoHasWillingBuyer" exact="false"/>
        <set_value name="$diagMinerDemandOffFullBayStall" exact="false"/>
        <set_value name="$diagMinerSnapshotStallReason" exact="''"/>
        <do_if value="$orderId == 'GalaxyMiner'">
          <set_value name="$diagMinerCheckDemandFirst" exact="true"/>
          <do_if value="$gtOrder? and $gtOrder.$checkDemandFirst?">
            <set_value name="$diagMinerCheckDemandFirst" exact="$gtOrder.$checkDemandFirst"/>
          </do_if>
          <set_value name="$diagMinerOfferWaresDetail" exact="'none (no mineable cargo and no active mining ware snapshot)'"/>
          <do_if value="$gtOrder? and $gtOrder.$playerStationsOnly?">
            <set_value name="$diagMinerPlayerStationsOnly" exact="$gtOrder.$playerStationsOnly"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$overflowThreshold?">
            <set_value name="$diagMinerOverflowThreshold" exact="[70, [100, $gtOrder.$overflowThreshold].min].max"/>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$allowOverflowSellToOthers?">
            <set_value name="$diagMinerAllowOverflowSellToOthers" exact="$gtOrder.$allowOverflowSellToOthers"/>
          </do_if>
          <do_if value="$minerDiag? and $minerDiag.$OverflowMode? and $minerDiag.$OverflowMode">
            <set_value name="$diagMinerOverflowMode" exact="true"/>
          </do_if>
          <!-- Rebuild primary station list from miner settings for policy-accurate diagnose filtering. -->
          <do_if value="$gtOrder? and $gtOrder.$stationList? and $gtOrder.$stationList.count gt 0">
            <do_all exact="$gtOrder.$stationList.count" counter="$dsti">
              <set_value name="$diagStationCandidate" exact="$gtOrder.$stationList.{$dsti}"/>
              <do_if value="$diagStationCandidate? and $diagStationCandidate.exists and $diagStationCandidate.isclass.station and $diagStationCandidate.isoperational">
                <set_value name="$diagAllowStation" exact="true"/>
                <do_if value="$diagMinerPlayerStationsOnly and $diagStationCandidate.owner != $ship.owner">
                  <set_value name="$diagAllowStation" exact="false"/>
                </do_if>
                <do_if value="$gtOrder.$homeSector? and $gtOrder.$homeSector.exists and $diagStationCandidate.sector != $gtOrder.$homeSector">
                  <set_value name="$diagAllowStation" exact="false"/>
                </do_if>
                <do_if value="$diagAllowStation and not $diagMinerPrimaryStations.indexof.{$diagStationCandidate}">
                  <append_to_list name="$diagMinerPrimaryStations" exact="$diagStationCandidate"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$gtOrder? and $gtOrder.$homeStation? and $gtOrder.$homeStation.exists and $gtOrder.$homeStation.isoperational and ((not $diagMinerPlayerStationsOnly) or ($gtOrder.$homeStation.owner == $ship.owner)) and ((not $gtOrder.$homeSector?) or (not $gtOrder.$homeSector.exists) or ($gtOrder.$homeStation.sector == $gtOrder.$homeSector)) and not $diagMinerPrimaryStations.indexof.{$gtOrder.$homeStation}">
            <append_to_list name="$diagMinerPrimaryStations" exact="$gtOrder.$homeStation"/>
          </do_if>
          <!-- Mirror order.trade.galaxyminer.xml demand-station auto-discovery when stationList is empty
               and no home station is set (home sector anchor -> all operational stations in sell range). -->
          <do_if value="not ($gtOrder? and $gtOrder.$stationList? and $gtOrder.$stationList.count gt 0)">
            <do_if value="not ($gtOrder? and $gtOrder.$homeStation? and $gtOrder.$homeStation.exists and $gtOrder.$homeStation.isoperational)">
              <set_value name="$diagMinerDemandRefSector" exact="null"/>
              <do_if value="$gtOrder? and $gtOrder.$homeSector? and $gtOrder.$homeSector.exists">
                <set_value name="$diagMinerDemandRefSector" exact="$gtOrder.$homeSector"/>
              </do_if>
              <do_elseif value="$homeSector? and $homeSector.exists">
                <set_value name="$diagMinerDemandRefSector" exact="$homeSector"/>
              </do_elseif>
              <do_else>
                <set_value name="$diagMinerDemandRefSector" exact="$ship.sector"/>
              </do_else>
              <do_if value="$diagMinerDemandRefSector? and $diagMinerDemandRefSector.exists">
                <set_value name="$diagMinerDemandSectors" exact="[]"/>
                <append_to_list name="$diagMinerDemandSectors" exact="$diagMinerDemandRefSector"/>
                <do_if value="$maxSell gt 0">
                  <find_sector name="$diagMinerDemandNearby" space="player.galaxy" multiple="true">
                    <match_gate_distance object="$diagMinerDemandRefSector" min="0" max="$maxSell"/>
                  </find_sector>
                  <do_if value="$diagMinerDemandNearby? and $diagMinerDemandNearby.count gt 0">
                    <do_all exact="$diagMinerDemandNearby.count" counter="$ddsi">
                      <set_value name="$diagMinerDemandSector" exact="$diagMinerDemandNearby.{$ddsi}"/>
                      <do_if value="$diagMinerDemandSector? and $diagMinerDemandSector.exists and not $diagMinerDemandSectors.indexof.{$diagMinerDemandSector}">
                        <append_to_list name="$diagMinerDemandSectors" exact="$diagMinerDemandSector"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_if>
                <do_all exact="$diagMinerDemandSectors.count" counter="$ddsi2">
                  <set_value name="$diagMinerDemandSector" exact="$diagMinerDemandSectors.{$ddsi2}"/>
                  <find_station name="$diagMinerSectorStations" space="$diagMinerDemandSector" checkoperational="true" multiple="true"/>
                  <do_if value="$diagMinerSectorStations? and $diagMinerSectorStations.count gt 0">
                    <do_all exact="$diagMinerSectorStations.count" counter="$dssi">
                      <set_value name="$diagMinerSectorStation" exact="$diagMinerSectorStations.{$dssi}"/>
                      <do_if value="$diagMinerSectorStation? and $diagMinerSectorStation.exists and $diagMinerSectorStation.isclass.station and $diagMinerSectorStation.isoperational and ((not $diagMinerPlayerStationsOnly) or ($diagMinerSectorStation.owner == $ship.owner)) and not $diagMinerPrimaryStations.indexof.{$diagMinerSectorStation}">
                        <append_to_list name="$diagMinerPrimaryStations" exact="$diagMinerSectorStation"/>
                        <set_value name="$diagMinerRuntimeDemandAdded" operation="add"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_all>
              </do_if>
              <do_elseif value="$ship.sector? and $ship.sector.exists">
                <find_station name="$diagMinerSectorStations" space="$ship.sector" checkoperational="true" multiple="true"/>
                <do_if value="$diagMinerSectorStations? and $diagMinerSectorStations.count gt 0">
                  <do_all exact="$diagMinerSectorStations.count" counter="$dssi">
                    <set_value name="$diagMinerSectorStation" exact="$diagMinerSectorStations.{$dssi}"/>
                    <do_if value="$diagMinerSectorStation? and $diagMinerSectorStation.exists and $diagMinerSectorStation.isclass.station and $diagMinerSectorStation.isoperational and ((not $diagMinerPlayerStationsOnly) or ($diagMinerSectorStation.owner == $ship.owner)) and not $diagMinerPrimaryStations.indexof.{$diagMinerSectorStation}">
                      <append_to_list name="$diagMinerPrimaryStations" exact="$diagMinerSectorStation"/>
                      <set_value name="$diagMinerRuntimeDemandAdded" operation="add"/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_elseif>
            </do_if>
          </do_if>
          <set_value name="$diagMinerPolicySummary" exact="'Per-ware: deliver to primary stations below ' + $diagMinerOverflowThreshold + '% fill; wares at/above threshold use overflow sell rules when enabled'"/>
          <set_value name="$diagMinerPhysicalStorageAbortPct" exact="20"/>
          <do_if value="$gtOrder? and $gtOrder.$physicalStorageAbortPercent?">
            <set_value name="$diagMinerPhysicalStorageAbortPct" exact="[0, [100, $gtOrder.$physicalStorageAbortPercent].min].max"/>
          </do_if>
          <set_value name="$diagMinerPhysicalGateDetail" exact="'inactive (slider 0)'"/>
          <set_value name="$diagMinerPhysicalGateActive" exact="false"/>
          <do_if value="$diagMinerPhysicalStorageAbortPct gt 0">
            <set_value name="$diagMinerPhysicalGateDetail" exact="'inactive (check demand first disabled)'"/>
            <do_if value="not $gtOrder? or not $gtOrder.$checkDemandFirst? or $gtOrder.$checkDemandFirst">
              <set_value name="$diagMinerPilotLevel" exact="0"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly">
                <do_if value="$ship.pilot? and $ship.pilot.skill.piloting?">
                  <set_value name="$diagMinerPilotLevel" exact="$ship.pilot.skill.piloting"/>
                </do_if>
              </do_if>
              <do_elseif value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
                <set_value name="$diagMinerPilotLevel" exact="global.$GT_Pilots.{$ship.pilot}.$Level"/>
              </do_elseif>
              <do_if value="$diagMinerPilotLevel ge 6">
                <set_value name="$diagMinerPhysicalGateActive" exact="true"/>
                <set_value name="$diagMinerPhysicalGateDetail" exact="'ACTIVE headroom ' + $diagMinerPhysicalStorageAbortPct + '% (pilot level ' + $diagMinerPilotLevel + ', live cargo formula)'"/>
              </do_if>
              <do_else>
                <set_value name="$diagMinerPhysicalGateDetail" exact="'inactive (pilot level ' + $diagMinerPilotLevel + ' lt 6, headroom slider ' + $diagMinerPhysicalStorageAbortPct + '%)'"/>
              </do_else>
            </do_if>
          </do_if>
          <do_if value="$diagMinerOverflowMode">
            <do_if value="not $diagMinerAllowOverflowSellToOthers">
              <set_value name="$diagMinerPolicySummary" exact="'Overflow mode: fallback disabled, no additional sell targets allowed'"/>
            </do_if>
            <do_elseif value="$diagMinerPlayerStationsOnly">
              <set_value name="$diagMinerPolicySummary" exact="'Overflow mode: only other player stations (non-primary)'" />
            </do_elseif>
            <do_else>
              <set_value name="$diagMinerPolicySummary" exact="'Overflow mode: any faction allowed'" />
            </do_else>
          </do_if>
          <set_value name="$diagMinerSelectedWare" exact="null"/>
          <set_value name="$diagMinerAnyBuyerMode" exact="false"/>
          <do_if value="global.$GT_MinerDiag? and global.$GT_MinerDiag.{$ship}? and global.$GT_MinerDiag.{$ship}.$SelectedWare?">
            <set_value name="$diagMinerSelectedWare" exact="global.$GT_MinerDiag.{$ship}.$SelectedWare"/>
          </do_if>
          <do_if value="$diagMinerSelectedWare? and $diagMinerSelectedWare != null">
            <do_if value="$diagMinerSelectedWare.hastag.minable and $ship.cargo.{$diagMinerSelectedWare}.max gt 0 and not $diagMinerOfferWares.indexof.{$diagMinerSelectedWare}">
              <append_to_list name="$diagMinerOfferWares" exact="$diagMinerSelectedWare"/>
            </do_if>
          </do_if>
          <!-- Fallback for MiningCollect / stale snapshot states:
               derive candidate wares from primary stations' buy offers so diagnose
               can still evaluate miner sell opportunities even with empty cargo. -->
          <do_if value="$diagMinerOfferWares.count == 0 and $diagMinerPrimaryStations.count gt 0">
            <do_all exact="$diagMinerPrimaryStations.count" counter="$dpswi">
              <set_value name="$diagPrimaryStation" exact="$diagMinerPrimaryStations.{$dpswi}"/>
              <do_if value="$diagPrimaryStation? and $diagPrimaryStation.exists">
                <find_buy_offer buyer="$diagPrimaryStation" tradepartner="$ship" result="$diagPrimaryBuyOffers" multiple="true"/>
                <do_if value="$diagPrimaryBuyOffers? and $diagPrimaryBuyOffers.count gt 0">
                  <do_all exact="$diagPrimaryBuyOffers.count" counter="$dpboi">
                    <set_value name="$diagPrimaryOffer" exact="$diagPrimaryBuyOffers.{$dpboi}"/>
                    <set_value name="$diagPrimaryWare" exact="if $diagPrimaryOffer? and $diagPrimaryOffer.ware? then $diagPrimaryOffer.ware else null"/>
                    <do_if value="$diagPrimaryWare? and $diagPrimaryWare.hastag.minable and $ship.cargo.{$diagPrimaryWare}.max gt 0 and not $diagMinerOfferWares.indexof.{$diagPrimaryWare}">
                      <append_to_list name="$diagMinerOfferWares" exact="$diagPrimaryWare"/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          <do_all exact="$ship.cargo.list.count" counter="$mwi">
            <set_value name="$mWare" exact="$ship.cargo.list.{$mwi}"/>
            <do_if value="$mWare? and $mWare.hastag.minable and $ship.cargo.{$mWare}.count gt 0 and $ship.cargo.{$mWare}.max gt 0 and not $diagMinerOfferWares.indexof.{$mWare}">
              <append_to_list name="$diagMinerOfferWares" exact="$mWare"/>
            </do_if>
          </do_all>
          <do_if value="$diagMinerOfferWares.count == 0">
            <set_value name="$diagMinerAnyBuyerMode" exact="true"/>
          </do_if>
          <do_if value="$diagMinerOfferWares.count gt 0">
            <set_value name="$diagMinerOfferWaresNames" exact="''"/>
            <do_all exact="$diagMinerOfferWares.count" counter="$mwni">
              <set_value name="$mWareName" exact="if $diagMinerOfferWares.{$mwni}.name? then $diagMinerOfferWares.{$mwni}.name else '?'"/>
              <do_if value="$diagMinerOfferWaresNames != ''">
                <set_value name="$diagMinerOfferWaresNames" exact="$diagMinerOfferWaresNames + ', '"/>
              </do_if>
              <set_value name="$diagMinerOfferWaresNames" exact="$diagMinerOfferWaresNames + $mWareName"/>
            </do_all>
            <set_value name="$diagMinerOfferWaresDetail" exact="'' + $diagMinerOfferWares.count + ' wares: ' + $diagMinerOfferWaresNames"/>
          </do_if>
          <do_else>
            <set_value name="$diagMinerOfferWaresDetail" exact="'auto-scope mode: all minable buyer offers (no selected/cargo ware available)'"/>
          </do_else>
          <!-- Per-ware primary capacity (mirrors order.trade.galaxyminer $wareHasPrimaryCapacity). -->
          <do_if value="$diagMinerOfferWares.count gt 0 and $diagMinerPrimaryStations.count gt 0">
            <do_all exact="$diagMinerOfferWares.count" counter="$dwci">
              <set_value name="$dwWare" exact="$diagMinerOfferWares.{$dwci}"/>
              <set_value name="$dwHasCap" exact="false"/>
              <do_all exact="$diagMinerPrimaryStations.count" counter="$dwsi">
                <set_value name="$dwStation" exact="$diagMinerPrimaryStations.{$dwsi}"/>
                <do_if value="$dwStation? and $dwStation.exists">
                  <set_value name="$dwTarget" exact="@$dwStation.cargo.{$dwWare}.target"/>
                  <do_if value="$dwTarget? and $dwTarget gt 0">
                    <set_value name="$dwPhysical" exact="@$dwStation.cargo.{$dwWare}.count"/>
                    <do_if value="not $dwPhysical?">
                      <set_value name="$dwPhysical" exact="0"/>
                    </do_if>
                    <set_value name="$dwFillPct" exact="($dwPhysical * 100) / [$dwTarget, 1].max"/>
                    <do_if value="$dwFillPct lt $diagMinerOverflowThreshold">
                      <set_value name="$dwHasCap" exact="true"/>
                    </do_if>
                  </do_if>
                </do_if>
              </do_all>
              <set_value name="$diagMinerWareHasPrimaryCapacity.{$dwWare}" exact="$dwHasCap"/>
            </do_all>
          </do_if>
          <do_if value="$ship.cargo.list? and $ship.cargo.list.count gt 0 and $diagMinerPrimaryStations.count gt 0">
            <do_all exact="$ship.cargo.list.count" counter="$dcfwi">
              <set_value name="$dcfwWare" exact="$ship.cargo.list.{$dcfwi}"/>
              <do_if value="not $diagMinerCargoHasWillingBuyer and $dcfwWare? and $dcfwWare.hastag.minable and $ship.cargo.{$dcfwWare}.count gt 0 and $ship.cargo.{$dcfwWare}.max gt 0">
                <do_all exact="$diagMinerPrimaryStations.count" counter="$dcfws">
                  <do_if value="$diagMinerCargoHasWillingBuyer">
                    <break/>
                  </do_if>
                  <set_value name="$dcfwStation" exact="$diagMinerPrimaryStations.{$dcfws}"/>
                  <do_if value="$dcfwStation? and $dcfwStation.exists">
                    <set_value name="$dcfwTarget" exact="@$dcfwStation.cargo.{$dcfwWare}.target"/>
                    <do_if value="$dcfwTarget? and $dcfwTarget gt 0">
                      <set_value name="$dcfwPhysical" exact="@$dcfwStation.cargo.{$dcfwWare}.count"/>
                      <do_if value="not $dcfwPhysical?">
                        <set_value name="$dcfwPhysical" exact="0"/>
                      </do_if>
                      <set_value name="$dcfwFillPct" exact="($dcfwPhysical * 100) / [$dcfwTarget, 1].max"/>
                      <do_if value="$dcfwFillPct lt $diagMinerOverflowThreshold">
                        <set_value name="$diagMinerCargoHasWillingBuyer" exact="true"/>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$cargoCap gt 0 and $cargoFree le 0 and not $diagMinerAllowOverflowSellToOthers and not $diagMinerCargoHasWillingBuyer and not $diagMinerCheckDemandFirst">
            <set_value name="$diagMinerDemandOffFullBayStall" exact="true"/>
          </do_if>
          <do_if value="global.$GT_MinerDiag? and global.$GT_MinerDiag.{$ship}? and global.$GT_MinerDiag.{$ship}.$StallReason?">
            <set_value name="$diagMinerSnapshotStallReason" exact="'' + global.$GT_MinerDiag.{$ship}.$StallReason"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Diagnose Sell Wares', $Status = if $diagMinerOfferWares.count gt 0 then 'PASS' else 'WARN', $Detail = $diagMinerOfferWaresDetail]"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Diagnose Miner Policy', $Status = 'INFO', $Detail = $diagMinerPolicySummary]"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Physical Storage Gate', $Status = if $diagMinerPhysicalGateActive then 'PASS' else 'INFO', $Detail = $diagMinerPhysicalGateDetail]"/>
          <set_value name="$diagMinerRuntimeDemandDetail" exact="'' + $diagMinerPrimaryStations.count + ' stations'"/>
          <do_if value="$diagMinerRuntimeDemandAdded gt 0">
            <set_value name="$diagMinerRuntimeDemandDetail" exact="$diagMinerRuntimeDemandDetail + ' (' + $diagMinerRuntimeDemandAdded + ' auto-discovered within ' + $maxSell + ' sell jumps of home anchor - mirrors live miner)'"/>
          </do_if>
          <do_elseif value="$diagMinerConfiguredTargetCount gt 0">
            <set_value name="$diagMinerRuntimeDemandDetail" exact="$diagMinerRuntimeDemandDetail + ' (from configured stationList)'"/>
          </do_elseif>
          <do_elseif value="$gtOrder? and $gtOrder.$homeStation? and $gtOrder.$homeStation.exists">
            <set_value name="$diagMinerRuntimeDemandDetail" exact="$diagMinerRuntimeDemandDetail + ' (home station only)'"/>
          </do_elseif>
          <do_if value="$diagMinerPrimaryStations.count == 0">
            <set_value name="$diagMinerRuntimeDemandDetail" exact="'0 stations - no stationList, home station, or sell-range scan found any demand targets'"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Runtime Demand Stations', $Status = if $diagMinerPrimaryStations.count gt 0 then 'PASS' else 'WARN', $Detail = $diagMinerRuntimeDemandDetail]"/>
          <set_value name="$diagMinerCargoBuyerStatus" exact="if $diagMinerCargoHasWillingBuyer then 'PASS' else (if $cargoUsed gt 0 then 'WARN' else 'INFO')"/>
          <set_value name="$diagMinerCargoBuyerDetail" exact="if $diagMinerCargoHasWillingBuyer then 'At least one carried minable ware has a primary station below the overflow threshold - miner should deliver' else (if $cargoUsed gt 0 then 'No primary station below overflow threshold for cargo on board - full bay cannot clear via primary delivery' else 'no cargo on board')"/>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Cargo-first Willing Buyer', $Status = $diagMinerCargoBuyerStatus, $Detail = $diagMinerCargoBuyerDetail]"/>
          <do_if value="$diagMinerSnapshotStallReason != ''">
            <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Live Stall Reason (snapshot)', $Status = 'WARN', $Detail = $diagMinerSnapshotStallReason]"/>
          </do_if>
          <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Diagnose Primary Stations', $Status = if $diagMinerPrimaryStations.count gt 0 then 'PASS' else 'WARN', $Detail = '' + $diagMinerPrimaryStations.count + ' stations used for policy/clearance scans']"/>
          <do_if value="$diagMinerPrimaryStations.count gt 0">
            <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Primary Station Cargo', $Status = 'INFO', $Detail = 'Physical stock / storage target per ware (miner rejects primary delivery at or above ' + $diagMinerOverflowThreshold + '% of target)']"/>
            <do_all exact="$diagMinerPrimaryStations.count" counter="$pssi">
              <set_value name="$pssStation" exact="$diagMinerPrimaryStations.{$pssi}"/>
              <do_if value="$pssStation? and $pssStation.exists">
                <set_value name="$pssStationLabel" exact="$pssStation.idcode + ' ' + $pssStation.knownname"/>
                <set_value name="$pssWares" exact="[]"/>
                <do_if value="$diagMinerOfferWares? and $diagMinerOfferWares.count gt 0">
                  <set_value name="$pssWares" exact="$diagMinerOfferWares.clone"/>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$pssStation" tradepartner="$ship" result="$pssBuyOffers" multiple="true"/>
                  <do_if value="$pssBuyOffers? and $pssBuyOffers.count gt 0">
                    <do_all exact="$pssBuyOffers.count" counter="$pssboi">
                      <set_value name="$pssOffer" exact="$pssBuyOffers.{$pssboi}"/>
                      <do_if value="$pssOffer? and $pssOffer.ware? and $pssOffer.ware.hastag.minable and $ship.cargo.{$pssOffer.ware}.max gt 0 and not $pssWares.indexof.{$pssOffer.ware}">
                        <append_to_list name="$pssWares" exact="$pssOffer.ware"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_else>
                <do_if value="$pssWares.count gt 0">
                  <do_all exact="$pssWares.count" counter="$psswi">
                    <set_value name="$pssWare" exact="$pssWares.{$psswi}"/>
                    <set_value name="$pssTarget" exact="@$pssStation.cargo.{$pssWare}.target"/>
                    <set_value name="$pssPhysical" exact="@$pssStation.cargo.{$pssWare}.count"/>
                    <do_if value="not $pssPhysical?">
                      <set_value name="$pssPhysical" exact="0"/>
                    </do_if>
                    <do_if value="not $pssTarget?">
                      <set_value name="$pssTarget" exact="0"/>
                    </do_if>
                    <set_value name="$pssFillPct" exact="if $pssTarget gt 0 then (($pssPhysical * 100) / $pssTarget) else 0"/>
                    <set_value name="$pssStatus" exact="'WARN'"/>
                    <set_value name="$pssDetail" exact="''"/>
                    <do_if value="$pssTarget le 0">
                      <set_value name="$pssDetail" exact="$pssStationLabel + ' | ' + $pssWare.name + ': target=0 (station does not use this ware â€” miner will not deliver here)'"/>
                    </do_if>
                    <do_elseif value="$pssFillPct ge $diagMinerOverflowThreshold">
                      <set_value name="$pssStatus" exact="'FAIL'"/>
                      <set_value name="$pssDetail" exact="$pssStationLabel + ' | ' + $pssWare.name + ': ' + $pssPhysical + '/' + $pssTarget + ' (' + $pssFillPct + '% of target) â€” AT/ABOVE overflow threshold ' + $diagMinerOverflowThreshold + '%'"/>
                    </do_elseif>
                    <do_else>
                      <set_value name="$pssStatus" exact="'PASS'"/>
                      <set_value name="$pssDetail" exact="$pssStationLabel + ' | ' + $pssWare.name + ': ' + $pssPhysical + '/' + $pssTarget + ' (' + $pssFillPct + '% of target) â€” has capacity below ' + $diagMinerOverflowThreshold + '% threshold'"/>
                    </do_else>
                    <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Cargo', $Status = $pssStatus, $Detail = $pssDetail]"/>
                  </do_all>
                </do_if>
                <do_else>
                  <append_to_list name="$sec3.$Rows" exact="table[$Check = 'Cargo', $Status = 'WARN', $Detail = $pssStationLabel + ' â€” no minable diagnose wares to evaluate (no cargo / no active ware snapshot / no buy offers on station)']"/>
                </do_else>
              </do_if>
            </do_all>
          </do_if>
        </do_if>

        <append_to_list name="$report.$Sections" exact="$sec3"/>

        <!-- ======================================================== -->
        <!-- SECTION 3b: Miner Resource Scan (DEDICATED SELF-SCAN)    -->
        <!-- The diagnostic runs its own scan independent of the      -->
        <!-- miner AI snapshot, so it works even when the ship is in  -->
        <!-- MiningCollect / Sell / FindResource / wait phases or has -->
        <!-- never emitted GT_Miner_Diag_Update yet.                  -->
        <!--                                                          -->
        <!-- For the ship's gather range (gtOrder.$maxGatherDistance, -->
        <!-- 0 if stayAtHome), enumerate sectors via find_sector +    -->
        <!-- match_gate_distance, then for each minable ware in the   -->
        <!-- ship cargo basket query sector.resources.{ware}.exists   -->
        <!-- as the reachability pre-check and keep yieldrating as    -->
        <!-- informational only. Apply the                            -->
        <!-- same A4 safety pre-filter (hostile / hazardous /         -->
        <!-- contested / sector-blacklisted) so the diagnostic        -->
        <!-- mirrors the miner's reachability decision exactly.       -->
        <!-- ======================================================== -->
        <do_if value="$orderId == 'GalaxyMiner'">
          <set_value name="$sec3b" exact="table[]"/>
          <set_value name="$sec3b.$Name" exact="'Miner Resource Scan'"/>
          <set_value name="$sec3b.$Rows" exact="[]"/>

          <!-- Step 0: effective gather distance.
               Mirrors the miner's full clamp chain so the diagnostic reflects what the SHIP
               actually scans, not just the raw order param:
                 1. Read order param  ($gtOrder.$maxGatherDistance, default 0)
                 2. Apply pilot cap   (order.trade.galaxyminer.xml main_loop start; skipped when
                                      UseVanillaXPOnly): level<=2 -> 1, <=5 -> 3, <=8 -> 5,
                                      <=11 -> 10, <=13 -> 15, else 25 (GT_Pilots.$Level).
                 3. Apply stayAtHome  (force 0 when enabled - miner is locked to home sector).
               The pilot cap is the key fix for "miner with maxGatherDistance=5 only scans 1
               sector": a low-skill pilot silently clamps to 1 jump at runtime, so the
               diagnostic must show the same effective number of sectors. -->
          <set_value name="$rscStayAtHome" exact="false"/>
          <do_if value="$gtOrder? and $gtOrder.$stayAtHome?">
            <set_value name="$rscStayAtHome" exact="$gtOrder.$stayAtHome"/>
          </do_if>
          <set_value name="$rscMaxGatherRaw" exact="0"/>
          <do_if value="$gtOrder? and $gtOrder.$maxGatherDistance?">
            <set_value name="$rscMaxGatherRaw" exact="$gtOrder.$maxGatherDistance"/>
          </do_if>
          <set_value name="$rscUseVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
          <set_value name="$rscPilotCap" exact="25"/>
          <do_if value="$rscUseVanillaXPOnly">
            <set_value name="$rscMaxGather" exact="$rscMaxGatherRaw"/>
          </do_if>
          <do_else>
            <set_value name="$rscPilotLevel" exact="1"/>
            <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$Level?">
              <set_value name="$rscPilotLevel" exact="global.$GT_Pilots.{$ship.pilot}.$Level"/>
            </do_if>
            <set_value name="$rscPilotCap" exact="1"/>
            <do_if value="$rscPilotLevel le 2">
              <set_value name="$rscPilotCap" exact="1"/>
            </do_if>
            <do_elseif value="$rscPilotLevel le 5">
              <set_value name="$rscPilotCap" exact="3"/>
            </do_elseif>
            <do_elseif value="$rscPilotLevel le 8">
              <set_value name="$rscPilotCap" exact="5"/>
            </do_elseif>
            <do_elseif value="$rscPilotLevel le 11">
              <set_value name="$rscPilotCap" exact="10"/>
            </do_elseif>
            <do_elseif value="$rscPilotLevel le 13">
              <set_value name="$rscPilotCap" exact="15"/>
            </do_elseif>
            <do_else>
              <set_value name="$rscPilotCap" exact="25"/>
            </do_else>
            <set_value name="$rscMaxGather" exact="[$rscMaxGatherRaw, $rscPilotCap].min"/>
          </do_else>
          <set_value name="$rscEffectiveRange" exact="if $rscStayAtHome then 0 else $rscMaxGather"/>

          <!-- Reference sector resolution.
               The miner AI ALWAYS has a home anchor by the time it runs: order.trade.galaxyminer.xml
               init (lines ~150-162) auto-sets $homeSector to the ship's current sector and persists it
               via edit_order_param if neither $homeStation nor $homeSector were configured. The
               diagnostic must therefore look at every source the miner uses, in priority order, and
               only fall back to "current ship sector (no home anchor configured)" when the persisted
               anchor is genuinely missing - which should only happen for a brand-new miner whose init
               has not run yet, or in pathological savegame states.

               Resolution order (matches the miner's own preference):
                 1. $gtOrder.$homeStation       (Assist-resolved order, station handle)
                 2. $gtOrder.$homeSector        (Assist-resolved order, sector handle)
                 3. $ship.defaultorder.$homeStation / .$homeSector  (own defaultorder; bypasses Assist)
                 4. $ship.order.$homeStation / .$homeSector         (currently running order)
                 5. $ship.commander.sector      (if commander is a station, that sector IS the anchor)
                 6. $ship.sector                (fallback: same sector the miner AI would auto-anchor to)
               Stations carry no .sector by themselves in some hierarchies, so we always read
               .sector with a guard before using it as the reference. -->
          <set_value name="$rscRefSector" exact="null"/>
          <set_value name="$rscRefIsHome" exact="false"/>
          <set_value name="$rscRefSourceLabel" exact="''"/>

          <do_if value="$gtOrder? and $gtOrder.$homeStation? and $gtOrder.$homeStation.exists and $gtOrder.$homeStation.sector?">
            <set_value name="$rscRefSector" exact="@$gtOrder.$homeStation.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home base: ' + (if $gtOrder.$homeStation.knownname? then @$gtOrder.$homeStation.knownname else 'station') + ')'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $gtOrder? and $gtOrder.$homeSector? and $gtOrder.$homeSector.exists">
            <set_value name="$rscRefSector" exact="$gtOrder.$homeSector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home sector)'"/>
          </do_if>
          <!-- Galaxy Miner UI flow: player clicks a sector position -> only $homePosition is set on
               the order. The order's own init resolves homePosition.{1} into $homeSector and persists
               via edit_order_param, but the diagnose tool may run before the resolver has completed
               (freshly assigned order, mid-init savegame state). Probe homePosition.{1} directly so
               the diagnostic does not fall through to "current ship sector" for the most natural
               UI setup. Two branches handle "position is a sector handle" vs "position is on an
               object that has a .sector accessor". -->
          <do_if value="not $rscRefIsHome and $gtOrder? and $gtOrder.$homePosition? and $gtOrder.$homePosition.{1}? and $gtOrder.$homePosition.{1}.exists and $gtOrder.$homePosition.{1}.isclass.sector">
            <set_value name="$rscRefSector" exact="$gtOrder.$homePosition.{1}"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home position)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $gtOrder? and $gtOrder.$homePosition? and $gtOrder.$homePosition.{1}? and $gtOrder.$homePosition.{1}.sector? and $gtOrder.$homePosition.{1}.sector.exists">
            <set_value name="$rscRefSector" exact="$gtOrder.$homePosition.{1}.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home position)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.defaultorder? and $ship.defaultorder.$homeStation? and $ship.defaultorder.$homeStation.exists and $ship.defaultorder.$homeStation.sector?">
            <set_value name="$rscRefSector" exact="@$ship.defaultorder.$homeStation.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home base: ' + (if $ship.defaultorder.$homeStation.knownname? then @$ship.defaultorder.$homeStation.knownname else 'station') + ')'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.defaultorder? and $ship.defaultorder.$homeSector? and $ship.defaultorder.$homeSector.exists">
            <set_value name="$rscRefSector" exact="$ship.defaultorder.$homeSector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home sector)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.defaultorder? and $ship.defaultorder.$homePosition? and $ship.defaultorder.$homePosition.{1}? and $ship.defaultorder.$homePosition.{1}.exists and $ship.defaultorder.$homePosition.{1}.isclass.sector">
            <set_value name="$rscRefSector" exact="$ship.defaultorder.$homePosition.{1}"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home position)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.defaultorder? and $ship.defaultorder.$homePosition? and $ship.defaultorder.$homePosition.{1}? and $ship.defaultorder.$homePosition.{1}.sector? and $ship.defaultorder.$homePosition.{1}.sector.exists">
            <set_value name="$rscRefSector" exact="$ship.defaultorder.$homePosition.{1}.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home position)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.order? and $ship.order.$homeStation? and $ship.order.$homeStation.exists and $ship.order.$homeStation.sector?">
            <set_value name="$rscRefSector" exact="@$ship.order.$homeStation.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home base: ' + (if $ship.order.$homeStation.knownname? then @$ship.order.$homeStation.knownname else 'station') + ')'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.order? and $ship.order.$homeSector? and $ship.order.$homeSector.exists">
            <set_value name="$rscRefSector" exact="$ship.order.$homeSector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home sector)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.order? and $ship.order.$homePosition? and $ship.order.$homePosition.{1}? and $ship.order.$homePosition.{1}.exists and $ship.order.$homePosition.{1}.isclass.sector">
            <set_value name="$rscRefSector" exact="$ship.order.$homePosition.{1}"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home position)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.order? and $ship.order.$homePosition? and $ship.order.$homePosition.{1}? and $ship.order.$homePosition.{1}.sector? and $ship.order.$homePosition.{1}.sector.exists">
            <set_value name="$rscRefSector" exact="$ship.order.$homePosition.{1}.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home position)'"/>
          </do_if>
          <do_if value="not $rscRefIsHome and $ship.commander? and $ship.commander.exists and $ship.commander.isclass.station and $ship.commander.sector?">
            <set_value name="$rscRefSector" exact="@$ship.commander.sector"/>
            <set_value name="$rscRefIsHome" exact="true"/>
            <set_value name="$rscRefSourceLabel" exact="' (home base: ' + (if $ship.commander.knownname? then @$ship.commander.knownname else 'commander station') + ')'"/>
          </do_if>

          <!-- Final fallback: current ship sector. Super-highway-aware so a ship in transit
               reports the sector it is heading to, not the highway zone itself. -->
          <do_if value="not $rscRefIsHome">
            <set_value name="$rscRefSector" exact="$ship.sector"/>
            <do_if value="@$ship.zone.issuperhighway">
              <set_value name="$rscRefSector" exact="@$ship.zone.destination.sector"/>
            </do_if>
            <set_value name="$rscRefSourceLabel" exact="' (current ship sector)'"/>
          </do_if>

          <!-- Step 1: enumerate sectors within gather range (always include refSector). -->
          <set_value name="$rscRawSectors" exact="[]"/>
          <do_if value="$rscRefSector? and $rscRefSector.exists">
            <append_to_list name="$rscRawSectors" exact="$rscRefSector"/>
            <do_if value="$rscEffectiveRange gt 0">
              <find_sector name="$rscNearby" space="player.galaxy" multiple="true">
                <match_gate_distance object="$rscRefSector" min="0" max="$rscEffectiveRange"/>
              </find_sector>
              <do_if value="$rscNearby? and $rscNearby.count gt 0">
                <do_all exact="$rscNearby.count" counter="$rsi">
                  <set_value name="$rscNs" exact="$rscNearby.{$rsi}"/>
                  <do_if value="$rscNs != $rscRefSector and not $rscRawSectors.indexof.{$rscNs}">
                    <append_to_list name="$rscRawSectors" exact="$rscNs"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
          </do_if>

          <!-- Step 2: A4 safety pre-filter (mirrors order.trade.galaxyminer.xml ~654-680).
               Always keep current ship sector and commander sector. Drop hostile-owner /
               hazardous-when-takesregiondamage / contested-by-attackers / sectoractivity-blacklisted. -->
          <set_value name="$rscBlGroup" exact="$diagBlacklistGroup"/>
          <set_value name="$rscCommanderSector" exact="null"/>
          <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander.sector?">
            <set_value name="$rscCommanderSector" exact="@$ship.commander.sector"/>
          </do_if>
          <set_value name="$rscShipSector" exact="$ship.sector"/>
          <set_value name="$rscShipOwner" exact="if $ship.owner? then @$ship.owner else null"/>
          <set_value name="$rscKeptSectors" exact="[]"/>
          <set_value name="$rscDroppedCount" exact="0"/>
          <do_all exact="$rscRawSectors.count" counter="$rfi">
            <set_value name="$rscSec" exact="$rscRawSectors.{$rfi}"/>
            <set_value name="$rscKeep" exact="true"/>
            <do_if value="$rscSec? and $rscSec.exists and $rscSec.isclass.sector">
              <do_if value="$rscSec == $rscShipSector or ($rscCommanderSector? and $rscSec == $rscCommanderSector)">
                <!-- always keep current/commander sector -->
              </do_if>
              <do_else>
                <do_if value="$rscSec.owner? and $rscShipOwner? and @$rscShipOwner.hasrelation.enemy.{$rscSec.owner}">
                  <set_value name="$rscKeep" exact="false"/>
                </do_if>
                <do_if value="$rscKeep and $rscSec.hashazardousregion and not $rscSec.containsthewave and $ship.takesregiondamage">
                  <set_value name="$rscKeep" exact="false"/>
                </do_if>
                <do_if value="$rscKeep and $rscSec.iscontested and not $rscSec.contestingfactions.indexof.{$rscShipOwner}">
                  <do_for_each name="$rscCFac" in="$rscSec.contestingfactions">
                    <do_if value="$rscCFac.mayattack.{$ship}">
                      <set_value name="$rscKeep" exact="false"/>
                      <break/>
                    </do_if>
                  </do_for_each>
                </do_if>
                <do_if value="$rscKeep and $ship.isplayerowned and $rscBlGroup? and $rscBlGroup != null and $ship.hasblacklist.{blacklisttype.sectoractivity}.{$rscBlGroup} and $rscSec.isblacklisted.{blacklisttype.sectoractivity}.{$rscBlGroup}.{$ship}">
                  <set_value name="$rscKeep" exact="false"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <set_value name="$rscKeep" exact="false"/>
            </do_else>
            <do_if value="$rscKeep">
              <append_to_list name="$rscKeptSectors" exact="$rscSec"/>
            </do_if>
            <do_else>
              <set_value name="$rscDroppedCount" exact="$rscDroppedCount + 1"/>
            </do_else>
          </do_all>

          <!-- Step 3: candidate wares - same gating the miner uses (hastag.minable +
               solid/liquid waretransport + cargo capacity). UNION of three sources so the
               result is deterministic across fleet members regardless of momentary cargo
               state (a commander parked at a wharf with only Ore in cargo must produce
               the same candidate set as a subordinate at home with Ore + Silicon + Ice in
               cargo - both share the same basket and primary stations):
                 1) ship.warebasket.list      (the player-configured basket)
                 2) ship.cargo.list           (wares already on board)
                 3) $diagMinerOfferWares      (computed earlier in section 3 from the
                                              commander's primary-station buy offers +
                                              snapshot selected ware + cargo - this is the
                                              fleet-stable signal: every miner under the
                                              same commander gets the same offer pool)
               Tier 4 (sector resources in range) stays as a fallback only when 1-3 are
               all empty, otherwise it would flood the candidate set with every minable
               resource that exists in range. Reports every contributing source so the
               player can see why a ware is or isn't in the set. -->
          <set_value name="$rscCandWares" exact="[]"/>
          <set_value name="$rscWareSourceList" exact="[]"/>
          <do_if value="$ship.warebasket? and $ship.warebasket.list? and $ship.warebasket.list.count gt 0">
            <set_value name="$rscBasketAdded" exact="0"/>
            <do_all exact="$ship.warebasket.list.count" counter="$rwi">
              <set_value name="$rscW" exact="$ship.warebasket.list.{$rwi}"/>
              <do_if value="$rscW? and $rscW.hastag.minable and ($rscW.waretransport == waretransport.solid or $rscW.waretransport == waretransport.liquid) and $ship.cargo.{$rscW}.max gt 0 and not $rscCandWares.indexof.{$rscW}">
                <append_to_list name="$rscCandWares" exact="$rscW"/>
                <set_value name="$rscBasketAdded" exact="$rscBasketAdded + 1"/>
              </do_if>
            </do_all>
            <do_if value="$rscBasketAdded gt 0">
              <append_to_list name="$rscWareSourceList" exact="'ware basket'"/>
            </do_if>
          </do_if>
          <do_if value="$ship.cargo.list? and $ship.cargo.list.count gt 0">
            <set_value name="$rscCargoAdded" exact="0"/>
            <do_all exact="$ship.cargo.list.count" counter="$rwii">
              <set_value name="$rscW2" exact="$ship.cargo.list.{$rwii}"/>
              <do_if value="$rscW2? and $rscW2.hastag.minable and ($rscW2.waretransport == waretransport.solid or $rscW2.waretransport == waretransport.liquid) and $ship.cargo.{$rscW2}.max gt 0 and not $rscCandWares.indexof.{$rscW2}">
                <append_to_list name="$rscCandWares" exact="$rscW2"/>
                <set_value name="$rscCargoAdded" exact="$rscCargoAdded + 1"/>
              </do_if>
            </do_all>
            <do_if value="$rscCargoAdded gt 0">
              <append_to_list name="$rscWareSourceList" exact="'current cargo'"/>
            </do_if>
          </do_if>
          <do_if value="$diagMinerOfferWares? and $diagMinerOfferWares.count gt 0">
            <set_value name="$rscOfferAdded" exact="0"/>
            <do_all exact="$diagMinerOfferWares.count" counter="$rwiii">
              <set_value name="$rscW3" exact="$diagMinerOfferWares.{$rwiii}"/>
              <do_if value="$rscW3? and $rscW3.hastag.minable and ($rscW3.waretransport == waretransport.solid or $rscW3.waretransport == waretransport.liquid) and $ship.cargo.{$rscW3}.max gt 0 and not $rscCandWares.indexof.{$rscW3}">
                <append_to_list name="$rscCandWares" exact="$rscW3"/>
                <set_value name="$rscOfferAdded" exact="$rscOfferAdded + 1"/>
              </do_if>
            </do_all>
            <do_if value="$rscOfferAdded gt 0">
              <append_to_list name="$rscWareSourceList" exact="'primary station buy offers'"/>
            </do_if>
          </do_if>
          <set_value name="$rscWareSource" exact="if $rscWareSourceList.count == 0 then 'none' else if $rscWareSourceList.count == 1 then $rscWareSourceList.{1} else if $rscWareSourceList.count == 2 then $rscWareSourceList.{1} + ' + ' + $rscWareSourceList.{2} else $rscWareSourceList.{1} + ' + ' + $rscWareSourceList.{2} + ' + ' + $rscWareSourceList.{3}"/>
          <!-- Tier 4: ship has no basket, no minable cargo, and no station buy-offers for minable
               wares (most common after a fresh ship assignment in a sector with no GT-served
               stations). Without this tier the diagnostic reports "0 of 0 wares can be mined" with
               no actionable info. Enumerate sector.resources.list across the kept gather sectors
               and surface every minable ware the ship's cargo bay can hold - this is what the
               miner would consider once a station with demand becomes available, so the player
               can see whether the asteroids exist before assigning a buyer. Source label spells
               out the limitation so the player understands why no station-driven scoring happened. -->
          <do_if value="$rscCandWares.count == 0 and $rscKeptSectors? and $rscKeptSectors.count gt 0">
            <set_value name="$rscWareSource" exact="'sector resources in range (no basket, cargo, or station buy-offer pool)'"/>
            <do_all exact="$rscKeptSectors.count" counter="$rwiv">
              <set_value name="$rscSecRes" exact="$rscKeptSectors.{$rwiv}"/>
              <do_if value="$rscSecRes? and $rscSecRes.exists and $rscSecRes.isclass.sector and $rscSecRes.resources? and $rscSecRes.resources.list?">
                <do_all exact="$rscSecRes.resources.list.count" counter="$rwivW">
                  <set_value name="$rscW4" exact="$rscSecRes.resources.list.{$rwivW}"/>
                  <do_if value="$rscW4? and $rscW4.hastag.minable and ($rscW4.waretransport == waretransport.solid or $rscW4.waretransport == waretransport.liquid) and $ship.cargo.{$rscW4}.max gt 0 and not $rscCandWares.indexof.{$rscW4}">
                    <append_to_list name="$rscCandWares" exact="$rscW4"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>

          <!-- Active mining ware (from miner snapshot) - pure overlay marker only. -->
          <set_value name="$rscActiveWare" exact="null"/>
          <do_if value="$minerDiag? and $minerDiag.$SelectedWare?">
            <set_value name="$rscActiveWare" exact="$minerDiag.$SelectedWare"/>
          </do_if>

          <!-- Step 4: per-ware reachability + best-yield scan across $rscKeptSectors.
               Vanilla-aligned predicates (mirrors order.mining.routine.xml ~1086-1141
               and order.trade.galaxyminer.xml's pre-score):
                 - sector.resources.{ware}.exists is the reachability pre-check.
                 - yieldrating is read with @ (no '?' guard) for display/ranking only; a zero
                   yield must NOT suppress the route-discovery probe.
                 - $rscBestSecName / $rscBestYield are seeded from the FIRST resource sector
                   (regardless of its yield value) instead of using strict 'gt running max' on a
                   zero-init max - otherwise a first sector with yield 0 would leave the name empty
                   and the row would render as "best in: ". After the first match, comparisons
                   switch to strict gt as expected. -->
          <set_value name="$rscWareRows" exact="[]"/>
          <!-- Counts split by discovery state so the header row can give the player an
               accurate "X mineable, Y undiscovered" breakdown. The diag now probes
               discovery synchronously per ware (no snapshot wait), so there is no
               'pending' bucket to track. -->
          <set_value name="$rscHasAsteroidsCount" exact="0"/>
          <set_value name="$rscDiscoveredCount" exact="0"/>
          <set_value name="$rscUndiscoveredCount" exact="0"/>
          <!-- Diag-internal discoverability probe (NO snapshot dependency).
               The previous design read $minerDiag.$DiscoverableWares, but the miner only publishes
               that snapshot AFTER the overflow-wait gate at order.trade.galaxyminer.xml:1309-1313.
               Stuck miners (selected ware capped + overflow disabled) loop back to main_loop
               BEFORE the publish at :1595 and never emit a snapshot - so the diag's "pending"
               branch was permanent for exactly the population that needs diagnosing. The diag now
               runs the same engine probe (find_closest_resource useundiscovered="false") itself
               at click time, which is the authoritative answer the miner would get on its next
               scoring pass. NPC ships skip the probe and read as discoverable, matching vanilla
               useundiscovered="not this.isplayerowned" at :927. -->
          <set_value name="$rscIsPlayerShip" exact="$ship.isplayerowned"/>
          <do_all exact="$rscCandWares.count" counter="$rci">
            <set_value name="$rscWare" exact="$rscCandWares.{$rci}"/>
            <set_value name="$rscBestYield" exact="0"/>
            <set_value name="$rscBestSecName" exact="''"/>
            <set_value name="$rscBestSeeded" exact="false"/>
            <set_value name="$rscWareSectorCount" exact="0"/>
            <!-- Per-sector record list for this ware. Used to render the top-3 sectors per
                 ware in the Wares table (player request: see ALL relevant sectors, not just
                 the single best). $BestSector / $BestYield are still maintained for the
                 downstream Selectability + Demand Ranking + Discovery Coverage consumers
                 that only need the headline value. -->
            <set_value name="$rscWareSectorsList" exact="[]"/>
            <do_all exact="$rscKeptSectors.count" counter="$rsj">
              <set_value name="$rscSecEval" exact="$rscKeptSectors.{$rsj}"/>
              <do_if value="$rscSecEval? and $rscSecEval.exists and $rscSecEval.isclass.sector and $rscSecEval.resources.{$rscWare}.exists">
                <set_value name="$rscSecYield" exact="@$rscSecEval.yieldrating.{$rscWare}"/>
                <set_value name="$rscWareSectorCount" exact="$rscWareSectorCount + 1"/>
                <set_value name="$rscSecName" exact="if $rscSecEval.knownname? then @$rscSecEval.knownname else 'unknown'"/>
                <append_to_list name="$rscWareSectorsList" exact="table[$Name = $rscSecName, $Yield = $rscSecYield]"/>
                <do_if value="not $rscBestSeeded or $rscSecYield gt $rscBestYield">
                  <set_value name="$rscBestYield" exact="$rscSecYield"/>
                  <set_value name="$rscBestSecName" exact="$rscSecName"/>
                  <set_value name="$rscBestSeeded" exact="true"/>
                </do_if>
              </do_if>
            </do_all>
            <set_value name="$rscHasAsteroids" exact="$rscWareSectorCount gt 0"/>
            <!-- Top-3 sectors text built via the same selection-sort pattern used elsewhere
                 in this file (no insert_in_list in MD). Format: "SectorA (yield Ya),
                 SectorB (yield Yb), SectorC (yield Yc) (+N more)". Empty string when the
                 ware has no qualifying sectors. -->
            <set_value name="$rscTopSectorsText" exact="''"/>
            <do_if value="$rscWareSectorsList.count gt 0">
              <set_value name="$rscTopCap" exact="[$rscWareSectorsList.count, 3].min"/>
              <set_value name="$rscTopClaimed" exact="[]"/>
              <do_all exact="$rscWareSectorsList.count" counter="$rsti">
                <append_to_list name="$rscTopClaimed" exact="false"/>
              </do_all>
              <do_all exact="$rscTopCap" counter="$rstr">
                <set_value name="$rscTopBestIdx" exact="0"/>
                <set_value name="$rscTopBestY" exact="-1"/>
                <do_all exact="$rscWareSectorsList.count" counter="$rstk">
                  <do_if value="not $rscTopClaimed.{$rstk}">
                    <set_value name="$rscTopCand" exact="$rscWareSectorsList.{$rstk}"/>
                    <do_if value="$rscTopCand.$Yield gt $rscTopBestY">
                      <set_value name="$rscTopBestY" exact="$rscTopCand.$Yield"/>
                      <set_value name="$rscTopBestIdx" exact="$rstk"/>
                    </do_if>
                  </do_if>
                </do_all>
                <do_if value="$rscTopBestIdx gt 0">
                  <set_value name="$rscTopClaimed.{$rscTopBestIdx}" exact="true"/>
                  <set_value name="$rscTopRow" exact="$rscWareSectorsList.{$rscTopBestIdx}"/>
                  <do_if value="$rscTopSectorsText != ''">
                    <set_value name="$rscTopSectorsText" exact="$rscTopSectorsText + ', '"/>
                  </do_if>
                  <set_value name="$rscTopSectorsText" exact="$rscTopSectorsText + $rscTopRow.$Name + ' (yield ' + $rscTopRow.$Yield + ')'"/>
                </do_if>
              </do_all>
              <do_if value="$rscWareSectorsList.count gt $rscTopCap">
                <set_value name="$rscTopSectorsText" exact="$rscTopSectorsText + ' (+' + ($rscWareSectorsList.count - $rscTopCap) + ' more)'"/>
              </do_if>
            </do_if>
            <!-- Discovery state machine for this ware (diag-internal probe, no snapshot):
                   'na'           -> NPC ship, vanilla never gates on discovery for them; OR
                                     no asteroids exist in any safe in-range sector at all
                                     (discovery is moot when the ware can't even be reached).
                   'discovered'   -> the engine probe (find_closest_resource useundiscovered="false",
                                     refobject=$ship) hits an asteroid the player has discovered.
                                     Match exactly what order.trade.galaxyminer.xml:931 does so the
                                     diag and the miner agree by construction.
                   'undiscovered' -> probe returns no sector; vanilla mining for player ships will
                                     refuse to route to undiscovered asteroids, so the ware is not
                                     actually mineable even though resources.exists is true. -->
            <set_value name="$rscDiscState" exact="'na'"/>
            <set_value name="$rscEngineKnowsSectorName" exact="''"/>
            <set_value name="$rscProbeInEngineKnownSector" exact="false"/>
            <do_if value="$rscIsPlayerShip and $rscHasAsteroids">
              <!-- Per-safe-sector anchoring (sector refobject + per-call retry).
                   We previously used a single galaxy-wide call with refobject=$ship. That
                   produced INCONSISTENT results between sibling player-owned miners at the
                   exact same wall-clock tick (one ship saw Silicon as discovered in Watchful
                   Gaze, another ship at the same time saw it as undiscovered). Discovery is
                   faction-wide for the player, so the disagreement was purely a refobject
                   side-effect: a ship-anchored find_closest_resource appears to fold the
                   ship's current position / accessibility into the resolution, and a ship in
                   transit / docked / in another cluster can be effectively blind to a
                   sector that another ship in the same fleet sees fine.
                   Vanilla order.mining.routine.gt.xml NEVER calls find_closest_resource with
                   refobject=this.ship - it always anchors on a sector (gather-space) with a
                   <refposition>. We mirror that here. We iterate the same $rscKeptSectors
                   list the rest of the diag uses (already filtered for safety / blacklist /
                   range), and accept the first probe hit. A hit anywhere in the safe set
                   means the ware is reachable+discovered for player-ship routing - exactly
                   the question the player is asking. -->
              <set_value name="$rscDiscProbedSector" exact="null"/>
              <set_value name="$rscDiscProbedPos" exact="null"/>
              <do_for_each name="$rscDiscAnchor" in="$rscKeptSectors">
                <do_if value="not ($rscDiscProbedSector? and @$rscDiscProbedSector.exists)">
                  <set_value name="$rscDiscTrySec" exact="null"/>
                  <set_value name="$rscDiscTryPos" exact="null"/>
                  <do_if value="$rscDiscAnchor? and $rscDiscAnchor.exists and $rscDiscAnchor.isclass.sector and $rscDiscAnchor.resources.{$rscWare}.exists">
                    <find_closest_resource sector="$rscDiscTrySec" position="$rscDiscTryPos" ware="$rscWare" refobject="$rscDiscAnchor" minamount="1"/>
                    <do_if value="$rscDiscTrySec? and @$rscDiscTrySec.exists">
                      <set_value name="$rscDiscProbedSector" exact="$rscDiscTrySec"/>
                      <set_value name="$rscDiscProbedPos" exact="$rscDiscTryPos"/>
                    </do_if>
                  </do_if>
                  <do_if value="$rscDiscTrySec?"><remove_value name="$rscDiscTrySec"/></do_if>
                  <do_if value="$rscDiscTryPos?"><remove_value name="$rscDiscTryPos"/></do_if>
                </do_if>
              </do_for_each>
              <set_value name="$rscDiscState" exact="if $rscDiscProbedSector? and @$rscDiscProbedSector.exists then 'discovered' else 'undiscovered'"/>
              <!-- Parallel probe to disambiguate the player's mental model from the engine's
                   routing model. Layers in play:
                     1. sector.resources.{ware}.exists (resource type exists in the sector) -
                        already captured by $rscHasAsteroids above. sector.yieldrating is only
                        a statistical display/ranking value and may legitimately read 0.
                     2. find_closest_resource useundiscovered="false" (asteroid-level discovery
                        the engine accepts for player-ship routing) - the per-safe-sector loop
                        above.
                     3. find_closest_resource useundiscovered="true" (the closest match counting
                        ALL asteroids the engine even knows exist, discovered or not) - the
                        per-safe-sector loop below.
                   Layer 3 lets the diag report "engine knows the asteroid is in sector X" so
                   the player can see the engine's view even when layer 2 misses. We also check
                   if a player resource probe is sitting in that sector so we can flag the
                   "probe deployed but engine still says undiscovered" case explicitly. Same
                   per-safe-sector anchoring as layer 2 to keep the result consistent across
                   sibling ships. -->
              <do_if value="$rscDiscState == 'undiscovered'">
                <set_value name="$rscExistsProbedSector" exact="null"/>
                <set_value name="$rscExistsProbedPos" exact="null"/>
                <do_for_each name="$rscExistsAnchor" in="$rscKeptSectors">
                  <do_if value="not ($rscExistsProbedSector? and @$rscExistsProbedSector.exists)">
                    <set_value name="$rscExistsTrySec" exact="null"/>
                    <set_value name="$rscExistsTryPos" exact="null"/>
                    <do_if value="$rscExistsAnchor? and $rscExistsAnchor.exists and $rscExistsAnchor.isclass.sector and $rscExistsAnchor.resources.{$rscWare}.exists">
                      <find_closest_resource sector="$rscExistsTrySec" position="$rscExistsTryPos" ware="$rscWare" refobject="$rscExistsAnchor" minamount="1"/>
                      <do_if value="$rscExistsTrySec? and @$rscExistsTrySec.exists">
                        <set_value name="$rscExistsProbedSector" exact="$rscExistsTrySec"/>
                        <set_value name="$rscExistsProbedPos" exact="$rscExistsTryPos"/>
                      </do_if>
                    </do_if>
                    <do_if value="$rscExistsTrySec?"><remove_value name="$rscExistsTrySec"/></do_if>
                    <do_if value="$rscExistsTryPos?"><remove_value name="$rscExistsTryPos"/></do_if>
                  </do_if>
                </do_for_each>
                <do_if value="$rscExistsProbedSector? and @$rscExistsProbedSector.exists">
                  <set_value name="$rscEngineKnowsSectorName" exact="if $rscExistsProbedSector.knownname? then @$rscExistsProbedSector.knownname else 'unknown sector'"/>
                  <find_object name="$rscProbeInSec" space="$rscExistsProbedSector" trueowner="player.faction" deployablecategory="deployablecategory.resourceprobe"/>
                  <do_if value="$rscProbeInSec? and @$rscProbeInSec.exists">
                    <set_value name="$rscProbeInEngineKnownSector" exact="true"/>
                  </do_if>
                  <do_if value="$rscProbeInSec?">
                    <remove_value name="$rscProbeInSec"/>
                  </do_if>
                </do_if>
                <do_if value="$rscExistsProbedSector?">
                  <remove_value name="$rscExistsProbedSector"/>
                </do_if>
                <do_if value="$rscExistsProbedPos?">
                  <remove_value name="$rscExistsProbedPos"/>
                </do_if>
              </do_if>
            </do_if>
            <set_value name="$rscMineable" exact="$rscHasAsteroids and ($rscDiscState == 'discovered' or $rscDiscState == 'na')"/>
            <do_if value="$rscHasAsteroids">
              <set_value name="$rscHasAsteroidsCount" exact="$rscHasAsteroidsCount + 1"/>
            </do_if>
            <do_if value="$rscDiscState == 'discovered'">
              <set_value name="$rscDiscoveredCount" exact="$rscDiscoveredCount + 1"/>
            </do_if>
            <do_if value="$rscDiscState == 'undiscovered'">
              <set_value name="$rscUndiscoveredCount" exact="$rscUndiscoveredCount + 1"/>
            </do_if>
            <set_value name="$rscIsActive" exact="$rscActiveWare? and $rscActiveWare != null and $rscActiveWare == $rscWare"/>
            <append_to_list name="$rscWareRows" exact="table[
              $WareName = if $rscWare.name? then $rscWare.name else '?',
              $IsActive = $rscIsActive,
              $HasAsteroids = $rscHasAsteroids,
              $DiscState = $rscDiscState,
              $Mineable = $rscMineable,
              $BestYield = $rscBestYield,
              $SectorCount = $rscWareSectorCount,
              $BestSector = $rscBestSecName,
              $TopSectors = $rscTopSectorsText,
              $EngineKnowsSectorName = $rscEngineKnowsSectorName,
              $ProbeInEngineKnownSector = $rscProbeInEngineKnownSector
            ]"/>
          </do_all>

          <!-- Step 5: header context rows.
               Player-facing copy ONLY: do not surface internal variable names, action names,
               filter codes, or "*-snapshot" mentions. The user does not care that the section
               uses find_sector, that the safety pre-filter is internally called "A4", or that
               the gather range comes from $gtOrder.$maxGatherDistance - they care about the
               sector, the range, and which sectors are safe to mine in. -->
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = '--- Scan Context ---', $Status = 'INFO', $Detail = '']"/>
          <set_value name="$rscRefSectorName" exact="'no sector available'"/>
          <do_if value="$rscRefSector? and $rscRefSector.exists">
            <set_value name="$rscRefSectorName" exact="if $rscRefSector.knownname? then @$rscRefSector.knownname else 'unknown'"/>
            <set_value name="$rscRefSectorName" exact="$rscRefSectorName + $rscRefSourceLabel"/>
          </do_if>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Reference Sector', $Status = if $rscRefSector? and $rscRefSector.exists then 'PASS' else 'FAIL', $Detail = $rscRefSectorName]"/>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Gather Range', $Status = 'INFO', $Detail = '' + $rscEffectiveRange + ' jumps' + (if $rscStayAtHome then ' (Stay At Home enabled, mining limited to home sector)' else if $rscMaxGather lt $rscMaxGatherRaw then (' (your setting: ' + $rscMaxGatherRaw + ', limited by pilot skill to ' + $rscPilotCap + ')') else (if $rscMaxGatherRaw gt 0 then '' else ' (your setting: 0)'))]"/>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Sectors In Range', $Status = if $rscRawSectors.count gt 0 then 'PASS' else 'FAIL', $Detail = '' + $rscRawSectors.count + ' sectors reachable from the reference sector']"/>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Safe Sectors', $Status = if $rscKeptSectors.count gt 0 then 'PASS' else 'FAIL', $Detail = '' + $rscKeptSectors.count + ' usable / ' + $rscDroppedCount + ' excluded (hostile, hazardous, contested, or on your sector blacklist)']"/>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Sector Blacklist Group', $Status = 'INFO', $Detail = if $rscBlGroup? and $rscBlGroup != null then '' + $rscBlGroup else 'None']"/>
          <set_value name="$rscKeptNamesText" exact="''"/>
          <set_value name="$rscNamesCap" exact="[$rscKeptSectors.count, 8].min"/>
          <do_all exact="$rscNamesCap" counter="$rkni">
            <set_value name="$rscKeptSec" exact="$rscKeptSectors.{$rkni}"/>
            <set_value name="$rscKeptName" exact="if $rscKeptSec.knownname? then @$rscKeptSec.knownname else 'unknown'"/>
            <do_if value="$rscKeptNamesText != ''">
              <set_value name="$rscKeptNamesText" exact="$rscKeptNamesText + ', '"/>
            </do_if>
            <set_value name="$rscKeptNamesText" exact="$rscKeptNamesText + $rscKeptName"/>
          </do_all>
          <do_if value="$rscKeptNamesText == ''">
            <set_value name="$rscKeptNamesText" exact="'(none)'"/>
          </do_if>
          <do_if value="$rscKeptSectors.count gt $rscNamesCap">
            <set_value name="$rscKeptNamesText" exact="$rscKeptNamesText + ' (+' + ($rscKeptSectors.count - $rscNamesCap) + ' more)'"/>
          </do_if>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Safe Sector Names', $Status = 'INFO', $Detail = $rscKeptNamesText]"/>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Yield Handling', $Status = 'INFO', $Detail = 'sectorYield is informational only; sectors are not ignored just because yield reads 0']"/>
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Candidate Wares', $Status = if $rscCandWares.count gt 0 then 'PASS' else 'WARN', $Detail = '' + $rscCandWares.count + ' minable wares (taken from: ' + $rscWareSource + ')']"/>
          <!-- "Reachable" here means "asteroid resource type exists in a safe sector".
               This is the engine-level resources.exists check; it does NOT yet account for whether the
               player has actually discovered the asteroid (see Discovery Coverage row below). -->
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Reachable Wares', $Status = if $rscHasAsteroidsCount gt 0 then 'PASS' else 'FAIL', $Detail = '' + $rscHasAsteroidsCount + ' of ' + $rscCandWares.count + ' wares have asteroids in a safe sector in range (resource exists in sector; yield may be 0)']"/>
          <do_if value="$rscIsPlayerShip">
            <!-- Discovery Coverage runs the authoritative engine probe at click time
                 (find_closest_resource useundiscovered="false", refobject=$ship), independent of
                 any miner snapshot. Vanilla mining for player-owned ships REQUIRES a discovered
                 asteroid: even if resources.exists is true, the engine will refuse to route the
                 ship to an undiscovered asteroid. The player has to actually scout the asteroid
                 (deploy a resource probe in the sector, fly close enough to spot it visually, or
                 have a satellite see it). -->
            <set_value name="$rscMineableCount" exact="$rscDiscoveredCount"/>
            <do_if value="$rscHasAsteroidsCount == 0">
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Check = 'Discovery Coverage',
                $Status = 'INFO',
                $Detail = 'no asteroids in range to evaluate discovery for'
              ]"/>
            </do_if>
            <do_else>
              <set_value name="$rscDiscDetail" exact="'' + $rscMineableCount + ' of ' + $rscHasAsteroidsCount + ' reachable wares are confirmed discovered and ACTUALLY mineable for this player ship'"/>
              <do_if value="$rscUndiscoveredCount gt 0">
                <!-- The summary row is intentionally generic; the per-ware Wares table below
                     differentiates "no probe yet" vs "probe already deployed but asteroid still
                     needs visual/satellite scout" so the player gets the actionable detail
                     without this one-liner contradicting it when probes are already down. -->
                <set_value name="$rscDiscDetail" exact="$rscDiscDetail + '; ' + $rscUndiscoveredCount + ' undiscovered for player-ship routing (engine refuses to route to an asteroid until it is asteroid-level discovered; resource probes reveal YIELD only - see the per-ware Wares table for the exact remediation per ware)'"/>
              </do_if>
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Check = 'Discovery Coverage',
                $Status = if $rscUndiscoveredCount gt 0 then 'WARN' else 'PASS',
                $Detail = $rscDiscDetail
              ]"/>
            </do_else>
          </do_if>

          <!-- Step 6: render top-N rows sorted by best yield desc (reachable first, unreachable last).
               X4 MD has no insert_in_list, so use the same selection-sort pattern as elsewhere in
               this file: walk the source list once per output row, picking the highest-key entry
               that has not been claimed yet. A boolean parallel list $rscClaimed marks emitted rows. -->
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = '--- Wares (best yield first, top 12) ---', $Status = 'INFO', $Detail = '']"/>
          <do_if value="$rscWareRows.count == 0">
            <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'No data', $Status = 'WARN', $Detail = 'No minable wares are available to this miner. Add a minable ware to the ship ware basket, give the ship a solid or liquid cargo bay, or assign a station that buys a minable ware (see Sell Wares above).']"/>
          </do_if>
          <do_if value="$rscWareRows.count gt 0">
            <set_value name="$rscRenderCap" exact="[$rscWareRows.count, 12].min"/>
            <set_value name="$rscClaimed" exact="[]"/>
            <do_all exact="$rscWareRows.count" counter="$rsii">
              <append_to_list name="$rscClaimed" exact="false"/>
            </do_all>
            <set_value name="$rscSorted" exact="[]"/>
            <do_all exact="$rscRenderCap" counter="$rsj2">
              <set_value name="$rscBestIdx" exact="0"/>
              <set_value name="$rscBestVal" exact="-1000000"/>
              <do_all exact="$rscWareRows.count" counter="$rsk">
                <do_if value="not $rscClaimed.{$rsk}">
                  <set_value name="$rscRow" exact="$rscWareRows.{$rsk}"/>
                  <!-- Sort key: mineable wares first (ranked by yield), then asteroids-but-not-mineable
                       (ranked by yield), then no-asteroids last. -->
                  <set_value name="$rscKey" exact="if $rscRow.$Mineable then $rscRow.$BestYield else (if $rscRow.$HasAsteroids then -10000 + $rscRow.$BestYield else -1000000)"/>
                  <do_if value="$rscKey gt $rscBestVal">
                    <set_value name="$rscBestVal" exact="$rscKey"/>
                    <set_value name="$rscBestIdx" exact="$rsk"/>
                  </do_if>
                </do_if>
              </do_all>
              <do_if value="$rscBestIdx gt 0">
                <append_to_list name="$rscSorted" exact="$rscWareRows.{$rscBestIdx}"/>
                <set_value name="$rscClaimed.{$rscBestIdx}" exact="true"/>
              </do_if>
            </do_all>
            <do_all exact="$rscSorted.count" counter="$rro">
              <set_value name="$rscOut" exact="$rscSorted.{$rro}"/>
              <!-- Tri-state row status drives the colour. The status hierarchy mirrors the player's
                   actionability:
                     - mineable + active     -> PASS (current ware)
                     - mineable inactive     -> INFO (alternative)
                     - undiscovered          -> WARN (player must scout / deploy probe)
                     - no asteroids in range -> WARN (no ore here at all) -->
              <set_value name="$rscWStatus" exact="if $rscOut.$Mineable then (if $rscOut.$IsActive then 'PASS' else 'INFO') else 'WARN'"/>
              <set_value name="$rscWLabel" exact="if $rscOut.$IsActive then '* ' + $rscOut.$WareName else $rscOut.$WareName"/>
              <!-- Tri-state reachability column: yes / undiscovered / no.
                     yes          -> the engine confirms a discovered asteroid for this player ship (or NPC ship)
                     undiscovered -> asteroids exist but the player has not discovered one (vanilla mining will refuse)
                     no           -> no asteroid resource in any safe sector in range -->
              <set_value name="$rscWReach" exact="if $rscOut.$Mineable then 'yes' else (if $rscOut.$DiscState == 'undiscovered' then 'undiscovered' else 'no')"/>
              <set_value name="$rscWBest" exact="if $rscOut.$HasAsteroids then '' + $rscOut.$BestYield else '-'"/>
              <set_value name="$rscWCount" exact="'' + $rscOut.$SectorCount"/>
              <!-- Note text builder. The undiscovered branch now distinguishes three sub-cases
                   so the player gets actionable advice instead of "deploy a probe" boilerplate
                   when they already have a probe down:
                     a) engine knows the asteroid is in a sector AND the player has a resource
                        probe in that sector  -> the probe revealed YIELDS (statistical) but
                        vanilla mining still needs asteroid-level discovery; instruct visual /
                        satellite scout, NOT another probe.
                     b) engine knows the asteroid is in a sector but no probe is in it -> the
                        usual "deploy a probe in <sector>" advice, but with the specific sector
                        named instead of "one of the safe sectors".
                     c) engine has no asteroid for this ware anywhere reachable -> generic
                        "deploy/scout" advice referencing the top yield sectors. -->
              <set_value name="$rscWNote" exact="if $rscOut.$Mineable then ('top: ' + $rscOut.$TopSectors) else (if $rscOut.$DiscState == 'undiscovered' then (if $rscOut.$EngineKnowsSectorName? and $rscOut.$EngineKnowsSectorName != '' then (if $rscOut.$ProbeInEngineKnownSector then ('engine knows the asteroid is in ' + $rscOut.$EngineKnowsSectorName + ' and your resource probe IS already in that sector - the probe reveals YIELD only, vanilla mining still needs asteroid-level discovery for player ships; fly a ship close to the asteroid to scout it visually OR drop a satellite within line-of-sight (top: ' + $rscOut.$TopSectors + ')') else ('engine knows the asteroid is in ' + $rscOut.$EngineKnowsSectorName + ' but no player resource probe is there - drop a probe in ' + $rscOut.$EngineKnowsSectorName + ', scout the sector with a satellite, or fly close enough to spot the asteroid visually (top: ' + $rscOut.$TopSectors + ')')) else ('asteroids exist in ' + $rscOut.$TopSectors + ' but the engine has not asteroid-discovered any - deploy a resource probe in one of these sectors, scout with a satellite, or fly close enough to spot it visually')) else 'no safe sector in range has this resource type')"/>
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Status = $rscWStatus,
                $Check = $rscWLabel,
                $Detail = $rscWBest,
                $Col4 = $rscWReach,
                $Col5 = $rscWCount,
                $Col6 = $rscWNote
              ]"/>
            </do_all>
            <do_if value="$rscWareRows.count gt $rscRenderCap">
              <append_to_list name="$sec3b.$Rows" exact="table[$Check = '... (' + ($rscWareRows.count - $rscRenderCap) + ' more wares not shown)', $Status = 'INFO', $Detail = '']"/>
            </do_if>
          </do_if>

          <!-- ============================================================================ -->
          <!-- Resource Probes (player faction, GALAXY-WIDE)                                -->
          <!--                                                                              -->
          <!-- Player report (galaxy_trader_v9 thread): commander BSD set to autoprobe,    -->
          <!-- subordinate MVE-562 had a probe, headed to a resource field, the probe      -->
          <!-- discovered Ice + Silicon, MVE started mining Silicon successfully - but     -->
          <!-- diag on the commander reported "No probes". That's wrong: MVE's deployed    -->
          <!-- probe physically exists and is feeding the engine yield data, the diag      -->
          <!-- just couldn't see it because the previous implementation iterated only      -->
          <!-- $rscKeptSectors (the diagnosed ship's safe-filtered set). MVE may legally   -->
          <!-- be mining in a sector that the COMMANDER's safety filter dropped (different -->
          <!-- gate distance from BSD, hostile-owner relative to BSD, hazard tolerance,    -->
          <!-- contested-by-attackers, sectoractivity blacklist), or even outside BSD's   -->
          <!-- raw gather radius entirely.                                                  -->
          <!--                                                                              -->
          <!-- Fix: enumerate every player-faction resource probe in the GALAXY (the same  -->
          <!-- find_object pattern vanilla MiningRoutine uses at line 969), then bucket    -->
          <!-- each probe by where its sector falls relative to the diagnosed ship's       -->
          <!-- reachable sets:                                                              -->
          <!--   A) IN $rscKeptSectors           -> the diagnosed ship CAN route here      -->
          <!--   B) IN $rscRawSectors but filtered out -> in range but the safety filter    -->
          <!--      dropped the sector (hostile / hazard / contested / blacklisted) - the  -->
          <!--      probe is useful to other fleet members but NOT to this ship           -->
          <!--   C) Outside $rscRawSectors        -> out of range entirely (>N gates from  -->
          <!--      this ship's reference sector); the probe is useful to fleet members    -->
          <!--      based closer to it but cannot help this ship pick a target             -->
          <!--                                                                              -->
          <!-- Per probe per candidate ware report:                                         -->
          <!--   - probe.bestyieldrating.{ware} (engine reading from this specific probe)  -->
          <!--   - sector.yieldrating.{ware}    (sector aggregate the miner ranks on)      -->
          <!--   - find_closest_resource useundiscovered="false" anchored on probe.sector  -->
          <!--     (the SAME call vanilla mining uses to gate routing for player ships)    -->
          <!-- If probeYield > 0 AND routingDiscovered=no -> X4 mechanic (probe shows      -->
          <!-- yield, asteroid still needs visual/satellite scout). If probeYield > 0 AND  -->
          <!-- routingDiscovered=yes -> ware should be mineable for any ship that can      -->
          <!-- safely reach the bucket-A or bucket-B sector.                                -->
          <!--                                                                              -->
          <!-- ENUMERATION FIX (live log: 851900.81 reported "0 player-faction resource    -->
          <!-- probe(s) found in the entire galaxy" while JSL-221 had a deployed probe in   -->
          <!-- Watchful Gaze): find_object DOES NOT support space="player.galaxy" - the    -->
          <!-- engine silently returns an empty list. Vanilla never calls it that way;     -->
          <!-- every stock callsite (order.mining.routine.xml:314,1077, scenario_tutorials  -->
          <!-- :15445, lib.calculate.miningefficiency.xml:20) uses a SECTOR-scoped space.  -->
          <!-- The galaxy-wide enumeration pattern in stock (fleet_reconstitution.xml:197) -->
          <!-- uses find_sector(space="player.galaxy") to get every sector first, then     -->
          <!-- iterates them. We mirror that here.                                          -->
          <!--                                                                              -->
          <!-- Owner filter: use owner="faction.player" matching                            -->
          <!-- scenario_tutorials.xml:15445 (the only stock callsite that explicitly       -->
          <!-- targets player-deployed probes). The previous trueowner="player.faction"     -->
          <!-- form is a separate property and may not match for player-deployed probes    -->
          <!-- depending on how the engine tracks deployable ownership.                     -->
          <!--                                                                              -->
          <!-- NPC ships are skipped because vanilla mining ignores discovery for them.    -->
          <!-- ============================================================================ -->
          <append_to_list name="$sec3b.$Rows" exact="table[$Check = '--- Resource Probes (player faction, galaxy-wide) ---', $Status = 'INFO', $Detail = '']"/>
          <do_if value="not $rscIsPlayerShip">
            <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'NPC ship', $Status = 'INFO', $Detail = 'discovery is not gated for NPC ships - probe enumeration skipped']"/>
          </do_if>
          <do_else>
            <!-- Build the probe list by iterating every galaxy sector. find_sector with
                 space="player.galaxy" is the canonical "give me every sector" call (see
                 fleet_reconstitution.xml:197). For each sector, find every player-faction
                 resource probe inside it and accumulate. -->
            <set_value name="$rscProbeAll" exact="[]"/>
            <find_sector name="$rscProbeSectors" space="player.galaxy" multiple="true"/>
            <do_if value="$rscProbeSectors? and $rscProbeSectors.count">
              <do_for_each name="$rscProbeScanSec" in="$rscProbeSectors">
                <find_object name="$rscProbeInSec" class="class.resourceprobe" owner="faction.player" space="$rscProbeScanSec" multiple="true"/>
                <do_if value="$rscProbeInSec? and $rscProbeInSec.count">
                  <do_for_each name="$rscProbePush" in="$rscProbeInSec">
                    <append_to_list name="$rscProbeAll" exact="$rscProbePush"/>
                  </do_for_each>
                </do_if>
                <do_if value="$rscProbeInSec?"><remove_value name="$rscProbeInSec"/></do_if>
              </do_for_each>
            </do_if>
            <do_if value="$rscProbeSectors?"><remove_value name="$rscProbeSectors"/></do_if>
            <do_if value="$rscProbeScanSec?"><remove_value name="$rscProbeScanSec"/></do_if>
            <do_if value="$rscProbePush?"><remove_value name="$rscProbePush"/></do_if>
            <set_value name="$rscProbeTotal" exact="if $rscProbeAll? then $rscProbeAll.count else 0"/>
            <set_value name="$rscProbeBucketKept" exact="0"/>
            <set_value name="$rscProbeBucketRaw" exact="0"/>
            <set_value name="$rscProbeBucketOut" exact="0"/>
            <append_to_list name="$sec3b.$Rows" exact="table[$Check = 'Probes (galaxy-wide)', $Status = if $rscProbeTotal gt 0 then 'INFO' else 'WARN', $Detail = '' + $rscProbeTotal + ' player-faction resource probe(s) found in the entire galaxy']"/>
            <do_if value="$rscProbeTotal gt 0">
              <do_for_each name="$rscProbeObj" in="$rscProbeAll">
                <do_if value="$rscProbeObj? and $rscProbeObj.exists">
                  <set_value name="$rscProbeSec" exact="if $rscProbeObj.sector? then @$rscProbeObj.sector else null"/>
                  <set_value name="$rscProbeInKept" exact="$rscProbeSec? and $rscProbeSec != null and $rscKeptSectors.indexof.{$rscProbeSec}"/>
                  <set_value name="$rscProbeInRaw" exact="$rscProbeSec? and $rscProbeSec != null and $rscRawSectors.indexof.{$rscProbeSec}"/>
                  <set_value name="$rscProbeBucket" exact="if $rscProbeInKept then 'A-reachable' else (if $rscProbeInRaw then 'B-in-range-but-filtered' else 'C-out-of-range')"/>
                  <do_if value="$rscProbeInKept">
                    <set_value name="$rscProbeBucketKept" exact="$rscProbeBucketKept + 1"/>
                  </do_if>
                  <do_else>
                    <do_if value="$rscProbeInRaw">
                      <set_value name="$rscProbeBucketRaw" exact="$rscProbeBucketRaw + 1"/>
                    </do_if>
                    <do_else>
                      <set_value name="$rscProbeBucketOut" exact="$rscProbeBucketOut + 1"/>
                    </do_else>
                  </do_else>
                  <set_value name="$rscProbeSecName" exact="if $rscProbeSec? and $rscProbeSec != null and $rscProbeSec.knownname? then @$rscProbeSec.knownname else 'unknown sector'"/>
                  <set_value name="$rscProbeOpr" exact="if $rscProbeObj.isoperational then 'operational' else 'not operational'"/>
                  <set_value name="$rscProbeIdc" exact="if $rscProbeObj.idcode? then @$rscProbeObj.idcode else 'no-idcode'"/>
                  <set_value name="$rscProbeStatus" exact="if not $rscProbeObj.isoperational then 'WARN' else (if $rscProbeInKept then 'PASS' else 'WARN')"/>
                  <set_value name="$rscProbeBucketNote" exact="if $rscProbeInKept then 'in this ship safe set' else (if $rscProbeInRaw then 'in range but FILTERED OUT of this ship safe set (hostile / hazard / contested / blacklist - useful to other fleet members only)' else 'OUT OF RANGE for this ship (>' + $rscEffectiveRange + ' gates from reference sector - useful to fleet members based closer)')"/>
                  <append_to_list name="$sec3b.$Rows" exact="table[
                    $Check = 'Probe ' + $rscProbeIdc,
                    $Status = $rscProbeStatus,
                    $Detail = '[' + $rscProbeBucket + '] ' + $rscProbeSecName + ' (' + $rscProbeOpr + ') - ' + $rscProbeBucketNote
                  ]"/>
                  <!-- Per candidate ware. Run the routing-discovery probe even for bucket B/C
                       sectors so the player can see whether any fleet member could mine here. -->
                  <do_for_each name="$rscProbeWare" in="$rscCandWares">
                    <set_value name="$rscProbeY" exact="if @$rscProbeObj.bestyieldrating.{$rscProbeWare} then @$rscProbeObj.bestyieldrating.{$rscProbeWare} else 0"/>
                    <set_value name="$rscProbeSY" exact="if $rscProbeSec? and $rscProbeSec != null and @$rscProbeSec.yieldrating.{$rscProbeWare} then @$rscProbeSec.yieldrating.{$rscProbeWare} else 0"/>
                    <set_value name="$rscProbeRouteSec" exact="null"/>
                    <set_value name="$rscProbeRoutePos" exact="null"/>
                    <do_if value="$rscProbeSec? and $rscProbeSec != null">
                      <find_closest_resource sector="$rscProbeRouteSec" position="$rscProbeRoutePos" ware="$rscProbeWare" refobject="$rscProbeSec" minamount="1"/>
                    </do_if>
                    <set_value name="$rscProbeRouteOK" exact="$rscProbeRouteSec? and @$rscProbeRouteSec.exists"/>
                    <set_value name="$rscProbeRouteSecName" exact="if $rscProbeRouteOK and $rscProbeRouteSec.knownname? then @$rscProbeRouteSec.knownname else 'NONE'"/>
                    <do_if value="$rscProbeInKept or $rscProbeY gt 0 or $rscProbeSY gt 0 or $rscProbeRouteOK">
                      <set_value name="$rscProbeWareStatus" exact="if $rscProbeRouteOK and $rscProbeInKept then 'PASS' else (if $rscProbeY gt 0 or $rscProbeSY gt 0 then 'WARN' else 'INFO')"/>
                      <set_value name="$rscProbeWareDetail" exact="'probeYield=' + $rscProbeY + ', sectorYield=' + $rscProbeSY + ', routingDiscovered=' + (if $rscProbeRouteOK then ('yes -> ' + $rscProbeRouteSecName + ' (yield values are informational only)') else 'no (yield 0 is not a blocker by itself; engine found no discovered routable asteroid for this player ship)')"/>
                      <append_to_list name="$sec3b.$Rows" exact="table[
                        $Check = '  ' + $rscProbeWare.name,
                        $Status = $rscProbeWareStatus,
                        $Detail = $rscProbeWareDetail
                      ]"/>
                      <remove_value name="$rscProbeWareStatus"/>
                      <remove_value name="$rscProbeWareDetail"/>
                    </do_if>
                    <do_if value="$rscProbeRouteSec?"><remove_value name="$rscProbeRouteSec"/></do_if>
                    <do_if value="$rscProbeRoutePos?"><remove_value name="$rscProbeRoutePos"/></do_if>
                    <remove_value name="$rscProbeY"/>
                    <remove_value name="$rscProbeSY"/>
                    <remove_value name="$rscProbeRouteOK"/>
                    <remove_value name="$rscProbeRouteSecName"/>
                  </do_for_each>
                  <do_if value="$rscProbeSec?"><remove_value name="$rscProbeSec"/></do_if>
                  <remove_value name="$rscProbeInKept"/>
                  <remove_value name="$rscProbeInRaw"/>
                  <remove_value name="$rscProbeBucket"/>
                  <remove_value name="$rscProbeSecName"/>
                  <remove_value name="$rscProbeOpr"/>
                  <remove_value name="$rscProbeIdc"/>
                  <remove_value name="$rscProbeStatus"/>
                  <remove_value name="$rscProbeBucketNote"/>
                </do_if>
              </do_for_each>
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Check = 'Probe Buckets',
                $Status = if $rscProbeBucketKept gt 0 then 'PASS' else 'WARN',
                $Detail = 'A-reachable for this ship: ' + $rscProbeBucketKept + ' | B-in-range-but-filtered: ' + $rscProbeBucketRaw + ' | C-out-of-range: ' + $rscProbeBucketOut
              ]"/>
              <do_if value="$rscProbeBucketKept == 0 and ($rscProbeBucketRaw gt 0 or $rscProbeBucketOut gt 0)">
                <append_to_list name="$sec3b.$Rows" exact="table[
                  $Check = 'Probe Diagnosis',
                  $Status = 'WARN',
                  $Detail = 'Other fleet members have probes deployed (B/C buckets) but NONE land in this ship safe-and-in-range set. This ship cannot benefit from those probes for ware selection. Either move this ship closer to a probe-covered sector, lift the safety filter that excluded the bucket-B sectors (raise gate distance / clear hostile-owner blacklist / accept hazardous regions), or have this ship deploy its own probe in a sector inside its safe set.'
                ]"/>
              </do_if>
            </do_if>
            <do_if value="$rscProbeAll?"><remove_value name="$rscProbeAll"/></do_if>
            <remove_value name="$rscProbeTotal"/>
            <remove_value name="$rscProbeBucketKept"/>
            <remove_value name="$rscProbeBucketRaw"/>
            <remove_value name="$rscProbeBucketOut"/>
          </do_else>

          <!-- ============================================================================ -->
          <!-- Selectability / Stall Cause                                                  -->
          <!--                                                                              -->
          <!-- Mirror of order.trade.galaxyminer.xml:945-1020 (urgency + primary-capacity   -->
          <!-- formula). The miner publishes its $SelectedWare snapshot AFTER the           -->
          <!-- overflow-wait gate at :1309-1313, so when a miner is stuck (selected ware    -->
          <!-- capped + overflow disabled), the snapshot is permanently stale and the diag  -->
          <!-- has no way to surface the actual stall cause from external state. Compute    -->
          <!-- the same selection synchronously here against $diagMinerPrimaryStations so   -->
          <!-- the verdict can name the failing ware, the cap %, and the higher-urgency     -->
          <!-- alternatives the miner would prefer if they were discovered.                 -->
          <!--                                                                              -->
          <!-- Best-effort approximation: omits the live $GT_MinerIntents fleet-balancing   -->
          <!-- subtraction, which only matters for multi-miner squads in flight. For the    -->
          <!-- single stalled-miner diagnose case this match is exact.                      -->
          <!-- ============================================================================ -->
          <set_value name="$selWBest" exact="null"/>
          <set_value name="$selWBestUrgency" exact="0"/>
          <set_value name="$selWBestCap" exact="false"/>
          <set_value name="$selWBestStorageMax" exact="0"/>
          <set_value name="$selWStallCandidate" exact="null"/>
          <set_value name="$selWStallUrgency" exact="0"/>
          <set_value name="$selWStallStorageMax" exact="0"/>
          <set_value name="$selWUndiscoveredAlts" exact="[]"/>
          <!-- Full ranked list of every candidate ware with positive urgency, regardless of
               whether it's currently mineable. Used to render a "Demand Ranking" table that
               shows the priority order the miner would walk (urgency desc) plus the exact
               blocker for each ware that can't be picked. This is the user-facing answer to
               "what would the miner pick, and why can't it pick the higher-urgency ones?". -->
          <set_value name="$selWAllScored" exact="[]"/>
          <set_value name="$selWHasStations" exact="$diagMinerPrimaryStations? and $diagMinerPrimaryStations.count gt 0"/>
          <do_if value="$selWHasStations and $rscWareRows.count gt 0">
            <do_all exact="$rscWareRows.count" counter="$selWi">
              <set_value name="$selWRow" exact="$rscWareRows.{$selWi}"/>
              <set_value name="$selWWareName" exact="if @$selWRow.$WareName then $selWRow.$WareName else '?'"/>
              <!-- Resolve ware reference back from rscCandWares (parallel index by name match,
                   since $rscWareRows only stores the display name, not the ware ref). -->
              <set_value name="$selWWare" exact="null"/>
              <do_all exact="$rscCandWares.count" counter="$selWj">
                <set_value name="$selWWareCand" exact="$rscCandWares.{$selWj}"/>
                <do_if value="$selWWareCand? and @$selWWareCand.name == $selWWareName and $selWWare == null">
                  <set_value name="$selWWare" exact="$selWWareCand"/>
                </do_if>
              </do_all>
              <set_value name="$selWUrgency" exact="0"/>
              <set_value name="$selWHasCap" exact="false"/>
              <set_value name="$selWStorageMax" exact="0"/>
              <do_if value="$selWWare != null">
                <do_all exact="$diagMinerPrimaryStations.count" counter="$selWk">
                  <set_value name="$selWStation" exact="$diagMinerPrimaryStations.{$selWk}"/>
                  <do_if value="$selWStation? and $selWStation.exists">
                    <set_value name="$selWTarget" exact="@$selWStation.cargo.{$selWWare}.target"/>
                    <do_if value="$selWTarget? and $selWTarget gt 0">
                      <set_value name="$selWCurrent" exact="@$selWStation.cargo.{$selWWare}.count"/>
                      <set_value name="$selWDeficit" exact="[0, $selWTarget - $selWCurrent].max"/>
                      <set_value name="$selWUrgency" exact="$selWUrgency + (($selWDeficit * 100) / [$selWTarget, 1].max)"/>
                      <set_value name="$selWStoragePct" exact="($selWCurrent * 100) / [$selWTarget, 1].max"/>
                      <do_if value="$selWStoragePct gt $selWStorageMax">
                        <set_value name="$selWStorageMax" exact="$selWStoragePct"/>
                      </do_if>
                      <do_if value="$selWStoragePct lt $diagMinerOverflowThreshold">
                        <set_value name="$selWHasCap" exact="true"/>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_all>
              </do_if>
              <!-- Categorise this ware against the miner's decision tree:
                     mineable + has primary capacity -> would actually be selected (best urgency wins)
                     mineable + capped               -> stall candidate (urgency exists but no sink)
                     undiscovered + has urgency      -> alternative the player should scout -->
              <do_if value="$selWRow.$Mineable and $selWHasCap and $selWUrgency gt $selWBestUrgency">
                <set_value name="$selWBest" exact="$selWWareName"/>
                <set_value name="$selWBestUrgency" exact="$selWUrgency"/>
                <set_value name="$selWBestCap" exact="true"/>
                <set_value name="$selWBestStorageMax" exact="$selWStorageMax"/>
              </do_if>
              <do_if value="$selWRow.$Mineable and not $selWHasCap and $selWUrgency gt $selWStallUrgency">
                <set_value name="$selWStallCandidate" exact="$selWWareName"/>
                <set_value name="$selWStallUrgency" exact="$selWUrgency"/>
                <set_value name="$selWStallStorageMax" exact="$selWStorageMax"/>
              </do_if>
              <do_if value="$selWRow.$DiscState == 'undiscovered' and $selWUrgency gt 0">
                <!-- Carry the parallel-probe results forward so the verdict suggestion can
                     differentiate "drop a probe in <sector>" from "you already have a probe
                     there, the asteroid still needs visual / satellite scout". $EngineKnowsSector
                     is the sector the engine reports the closest (still-undiscovered) asteroid
                     for this ware lives in, and $ProbeInSector is whether one of the player's
                     resource probes is already in that sector. -->
                <append_to_list name="$selWUndiscoveredAlts" exact="table[$Name = $selWWareName, $Urgency = $selWUrgency, $Sector = $selWRow.$BestSector, $EngineKnowsSector = $selWRow.$EngineKnowsSectorName, $ProbeInSector = $selWRow.$ProbeInEngineKnownSector]"/>
              </do_if>
              <!-- Per-ware blocker classification for the Demand Ranking table.
                   Branch order matters - most-disqualifying reason wins so a ware with no
                   asteroids in range never gets mis-flagged as "undiscovered" or "capped".
                   Status is the row colour the renderer maps:
                     PASS -> currently active mineable selection
                     INFO -> selectable but not currently the active pick
                     WARN -> blocked by a recoverable issue (overflow ok / undiscovered / no asteroid)
                     FAIL -> the exact stall pattern that produces the wait at galaxyminer.xml:1309. -->
              <do_if value="$selWUrgency gt 0">
                <set_value name="$selWBlockerStatus" exact="'INFO'"/>
                <set_value name="$selWBlockerDetail" exact="''"/>
                <do_if value="not $selWRow.$HasAsteroids">
                  <set_value name="$selWBlockerStatus" exact="'WARN'"/>
                  <set_value name="$selWBlockerDetail" exact="'no asteroid resource in any safe sector in range'"/>
                </do_if>
                <do_elseif value="$selWRow.$DiscState == 'undiscovered'">
                  <set_value name="$selWBlockerStatus" exact="'WARN'"/>
                  <set_value name="$selWBlockerDetail" exact="'undiscovered: asteroids exist in ' + $selWRow.$BestSector + ' but the player has not discovered them - deploy a resource probe in the sector, scout it with a satellite, or fly close enough to spot it visually'"/>
                </do_elseif>
                <do_elseif value="$selWRow.$Mineable and not $selWHasCap">
                  <do_if value="not $diagMinerAllowOverflowSellToOthers">
                    <set_value name="$selWBlockerStatus" exact="'FAIL'"/>
                    <set_value name="$selWBlockerDetail" exact="'primary stations at ' + $selWStorageMax + '% ge ' + $diagMinerOverflowThreshold + '% overflow threshold AND overflow sell to other stations is DISABLED - miner stuck waiting at galaxyminer.xml:1309'"/>
                  </do_if>
                  <do_else>
                    <set_value name="$selWBlockerStatus" exact="'WARN'"/>
                    <set_value name="$selWBlockerDetail" exact="'primary stations at ' + $selWStorageMax + '% ge ' + $diagMinerOverflowThreshold + '% overflow threshold; overflow sell to other stations is enabled, so the miner will deliver to a non-primary buyer'"/>
                  </do_else>
                </do_elseif>
                <do_elseif value="$selWRow.$Mineable and $selWHasCap">
                  <set_value name="$selWBlockerStatus" exact="if @$selWRow.$IsActive then 'PASS' else 'INFO'"/>
                  <set_value name="$selWBlockerDetail" exact="'SELECTABLE - primary fill ' + $selWStorageMax + '% lt ' + $diagMinerOverflowThreshold + '% threshold' + (if @$selWRow.$IsActive then ' (currently the active mining target)' else '')"/>
                </do_elseif>
                <do_else>
                  <!-- Defensive: shouldn't happen because the four arms above are exhaustive
                       given urgency>0 and the mineable/discovery state machine. Keep a
                       neutral row so we never silently drop a candidate. -->
                  <set_value name="$selWBlockerStatus" exact="'WARN'"/>
                  <set_value name="$selWBlockerDetail" exact="'unclassified blocker (mineable=' + $selWRow.$Mineable + ', discState=' + $selWRow.$DiscState + ', hasCap=' + $selWHasCap + ')'"/>
                </do_else>
                <append_to_list name="$selWAllScored" exact="table[
                  $Name = $selWWareName,
                  $Urgency = $selWUrgency,
                  $Status = $selWBlockerStatus,
                  $Detail = $selWBlockerDetail
                ]"/>
              </do_if>
            </do_all>
          </do_if>
          <!-- Stall is real iff:
                 - no mineable+capacity ware exists (nothing the miner can actually deliver), AND
                 - a mineable-but-capped ware DOES exist (so the miner picks it and waits), AND
                 - overflow sell to other stations is disabled (no escape valve).
               Mirrors the gate in order.trade.galaxyminer.xml:1309-1313 exactly.
               NOTE on null checks: in X4 MD, `$var?` returns true whenever the variable was
               set, even if it was set to `null` - so `$selWBest?` is true after the initial
               `set_value name="$selWBest" exact="null"`. Use explicit `!= null` here. -->
          <set_value name="$selWStalled" exact="$diagMinerCheckDemandFirst and $selWBest == null and $selWStallCandidate != null and (not $diagMinerAllowOverflowSellToOthers)"/>
          <do_if value="$selWHasStations and $rscWareRows.count gt 0">
            <append_to_list name="$sec3b.$Rows" exact="table[$Check = '--- Selectability (what the miner would pick now) ---', $Status = 'INFO', $Detail = if $diagMinerCheckDemandFirst then 'Demand-first mode: urgency scoring over primary stations' else 'Demand-off mode: fixed Resource Basket / slice-committed pick (urgency scoring skipped for mining gate)']"/>
            <do_if value="$selWBest != null">
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Check = 'Would Select',
                $Status = 'PASS',
                $Detail = $selWBest + ' (urgency ' + $selWBestUrgency + ', primary fill ' + $selWBestStorageMax + '% lt ' + $diagMinerOverflowThreshold + '% threshold)'
              ]"/>
            </do_if>
            <do_elseif value="$selWStallCandidate != null">
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Check = 'Would Select',
                $Status = if $selWStalled then 'FAIL' else 'WARN',
                $Detail = $selWStallCandidate + ' (urgency ' + $selWStallUrgency + ') - but primary fill ' + $selWStallStorageMax + '% is at or above the ' + $diagMinerOverflowThreshold + '% overflow threshold' + (if $diagMinerAllowOverflowSellToOthers then '; overflow sell to other stations is enabled, so the miner can still deliver elsewhere' else '; overflow sell to other stations is DISABLED, so the miner is stuck waiting (see verdict)')
              ]"/>
            </do_elseif>
            <do_else>
              <append_to_list name="$sec3b.$Rows" exact="table[
                $Check = 'Would Select',
                $Status = 'WARN',
                $Detail = 'no mineable ware has any primary-station demand right now (no deficit at any primary station for any reachable+discovered ware)'
              ]"/>
            </do_else>
            <!-- Demand Ranking: every ware with positive urgency, sorted desc by urgency,
                 each with the exact blocker that prevents (or doesn't prevent) it from being
                 picked. The renderer caps at 8 rows so the section stays readable on miners
                 with very wide ware baskets. Selection sort matches the pattern used elsewhere
                 in this file (no insert_in_list in MD); we emit the highest-urgency unclaimed
                 row each pass. -->
            <do_if value="$selWAllScored.count gt 0">
              <append_to_list name="$sec3b.$Rows" exact="table[$Check = '--- Demand Ranking (highest urgency first, with blocker reasons) ---', $Status = 'INFO', $Detail = '']"/>
              <set_value name="$selWRankCap" exact="[$selWAllScored.count, 8].min"/>
              <set_value name="$selWClaimed" exact="[]"/>
              <do_all exact="$selWAllScored.count" counter="$selWci">
                <append_to_list name="$selWClaimed" exact="false"/>
              </do_all>
              <do_all exact="$selWRankCap" counter="$selWri">
                <set_value name="$selWRankBestIdx" exact="0"/>
                <set_value name="$selWRankBestUrgency" exact="-1"/>
                <do_all exact="$selWAllScored.count" counter="$selWrk">
                  <do_if value="not $selWClaimed.{$selWrk}">
                    <set_value name="$selWRankCand" exact="$selWAllScored.{$selWrk}"/>
                    <do_if value="$selWRankCand.$Urgency gt $selWRankBestUrgency">
                      <set_value name="$selWRankBestUrgency" exact="$selWRankCand.$Urgency"/>
                      <set_value name="$selWRankBestIdx" exact="$selWrk"/>
                    </do_if>
                  </do_if>
                </do_all>
                <do_if value="$selWRankBestIdx gt 0">
                  <set_value name="$selWClaimed.{$selWRankBestIdx}" exact="true"/>
                  <set_value name="$selWRankRow" exact="$selWAllScored.{$selWRankBestIdx}"/>
                  <append_to_list name="$sec3b.$Rows" exact="table[
                    $Check = '#' + $selWri + ' ' + $selWRankRow.$Name,
                    $Status = $selWRankRow.$Status,
                    $Detail = 'urgency ' + $selWRankRow.$Urgency + ' - ' + $selWRankRow.$Detail
                  ]"/>
                </do_if>
              </do_all>
              <do_if value="$selWAllScored.count gt $selWRankCap">
                <append_to_list name="$sec3b.$Rows" exact="table[
                  $Check = '... (' + ($selWAllScored.count - $selWRankCap) + ' more wares with positive urgency not shown)',
                  $Status = 'INFO',
                  $Detail = ''
                ]"/>
              </do_if>
            </do_if>
          </do_if>

          <append_to_list name="$report.$Sections" exact="$sec3b"/>
        </do_if>

        <!-- ======================================================== -->
        <!-- Profit Threshold (merged into Ship State sec1)           -->
        <!-- SKIPPED in clearance mode (clearance sells at any price) -->
        <!-- ======================================================== -->
        <do_if value="not $isClearanceMode and $orderId != 'GalaxyTraderMK4Supply' and $orderId != 'GalaxyTraderMK4Supply2' and $orderId != 'GalaxyTraderMK4Supply2'">
          <append_to_list name="$sec1.$Rows" exact="table[$Check = '--- Profit Threshold ---', $Status = 'INFO', $Detail = '']"/>

          <!-- Config base profit -->
          <set_value name="$configBaseProfit" exact="10000"/>
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$ConfigBaseProfit?">
            <set_value name="$configBaseProfit" exact="global.$GT_AIParameters.{$ship}.$ConfigBaseProfit"/>
          </do_if>

          <!-- Skill scaling -->
          <set_value name="$skillNumerator" exact="($skillLevel - 1) * ($skillLevel - 1) * $configBaseProfit"/>
          <set_value name="$baseThreshold" exact="$skillNumerator / 196"/>

          <!-- Cargo scaling -->
          <set_value name="$referenceCargo" exact="8200"/>
          <set_value name="$shipCargoCap" exact="$ship.cargo.capacity.all"/>
          <set_value name="$scalingFactor" exact="($shipCargoCap * 100) / $referenceCargo"/>
          <set_value name="$scaledThreshold" exact="($baseThreshold * $scalingFactor) / 100"/>
          <set_value name="$minFloor" exact="($baseThreshold * 25) / 100"/>
          <set_value name="$finalProfitThreshold" exact="[$scaledThreshold, $minFloor].max"/>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Profit Threshold', $Status = 'INFO', $Detail = '' + ($finalProfitThreshold / 100) + ' Cr']"/>

          <!-- ROI threshold -->
          <set_value name="$minROI" exact="5"/>
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$MinROI?">
            <set_value name="$minROI" exact="global.$GT_AIParameters.{$ship}.$MinROI"/>
          </do_if>
          <!-- Apply skill multiplier to ROI -->
          <run_actions ref="md.GT_Libraries_General.GT_GetSkillMultiplier" result="$roiMultiplier">
            <param name="skillLevel" value="$skillLevel"/>
          </run_actions>
          <set_value name="$effectiveROI" exact="$minROI * $roiMultiplier"/>
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Min ROI', $Status = 'INFO', $Detail = '' + $effectiveROI + '%']"/>
        </do_if>
        <do_if value="not $isClearanceMode and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2')">
          <append_to_list name="$sec1.$Rows" exact="table[$Check = 'Trade Gate', $Status = 'INFO', $Detail = 'Supply score + price profile (no ROI/profit floor)']"/>
        </do_if>

        <!-- ======================================================== -->
        <!-- SECTION 6: Scheduler State                               -->
        <!-- ======================================================== -->
        <set_value name="$sec6" exact="table[]"/>
        <set_value name="$sec6.$Name" exact="'Scheduler State'"/>
        <set_value name="$sec6.$Rows" exact="[]"/>

        <!-- Queue status -->
        <set_value name="$queueResult" exact="'INFO'"/>
        <do_if value="$orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
          <set_value name="$queueDetail" exact="'Not queued'"/>
        </do_if>
        <do_else>
          <set_value name="$queueDetail" exact="'N/A (MK3/MK4 only)'"/>
        </do_else>
        <do_if value="($orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and global.$GT_SearchSemaphore?">
          <do_if value="global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
            <set_value name="$queueDetail" exact="'In cache queue'"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
            <set_value name="$queueDetail" exact="'Cache search active'"/>
            <set_value name="$queueResult" exact="'OK'"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
            <set_value name="$queueDetail" exact="'In live queue'"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
            <set_value name="$queueDetail" exact="'Live search active'"/>
            <set_value name="$queueResult" exact="'OK'"/>
          </do_if>
          <do_if value="$orderId == 'GalaxyTraderMK4Supply' and global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
            <set_value name="$queueDetail" exact="'In MK4 live queue'"/>
          </do_if>
          <do_if value="$orderId == 'GalaxyTraderMK4Supply' and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
            <set_value name="$queueDetail" exact="'MK4 live search active'"/>
            <set_value name="$queueResult" exact="'OK'"/>
          </do_if>
          <do_if value="$orderId == 'GalaxyTraderMK4Supply2' and global.$GT_SearchSemaphore.$MK42LiveQueued? and global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}?">
            <set_value name="$queueDetail" exact="'In MK4-2 live queue'"/>
          </do_if>
          <do_if value="$orderId == 'GalaxyTraderMK4Supply2' and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}?">
            <set_value name="$queueDetail" exact="'MK4-2 live search active'"/>
            <set_value name="$queueResult" exact="'OK'"/>
          </do_if>
        </do_if>
        <append_to_list name="$sec6.$Rows" exact="table[$Check = 'Queue Status', $Status = $queueResult, $Detail = $queueDetail]"/>

        <!-- Scheduler pool usage -->
        <set_value name="$procLockDetail" exact="'No active searches'"/>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="$cacheActive" exact="if global.$GT_SearchSemaphore.$CacheActive? then global.$GT_SearchSemaphore.$CacheActive else 0"/>
          <set_value name="$cacheMax" exact="if global.$GT_SearchSemaphore.$MaxConcurrentCache? then global.$GT_SearchSemaphore.$MaxConcurrentCache else 0"/>
          <set_value name="$liveActive" exact="if global.$GT_SearchSemaphore.$LiveActive? then global.$GT_SearchSemaphore.$LiveActive else 0"/>
          <set_value name="$liveMax" exact="if global.$GT_SearchSemaphore.$MaxConcurrentLive? then global.$GT_SearchSemaphore.$MaxConcurrentLive else 0"/>
          <set_value name="$mk4LiveActive" exact="if global.$GT_SearchSemaphore.$MK4LiveActive? then global.$GT_SearchSemaphore.$MK4LiveActive else 0"/>
          <set_value name="$mk4LiveMax" exact="if global.$GT_SearchSemaphore.$MaxConcurrentMK4Live? then global.$GT_SearchSemaphore.$MaxConcurrentMK4Live else 0"/>
          <set_value name="$mk42LiveActive" exact="if global.$GT_SearchSemaphore.$MK42LiveActive? then global.$GT_SearchSemaphore.$MK42LiveActive else 0"/>
          <set_value name="$mk42LiveMax" exact="if global.$GT_SearchSemaphore.$MaxConcurrentMK42Live? then global.$GT_SearchSemaphore.$MaxConcurrentMK42Live else 0"/>
          <set_value name="$procLockDetail" exact="'Cache active: ' + $cacheActive + '/' + $cacheMax + ' | Live active: ' + $liveActive + '/' + $liveMax + ' | MK4 live active: ' + $mk4LiveActive + '/' + $mk4LiveMax + ' | MK4-2 live active: ' + $mk42LiveActive + '/' + $mk42LiveMax"/>
        </do_if>
        <append_to_list name="$sec6.$Rows" exact="table[$Check = 'Scheduler Slots', $Status = 'INFO', $Detail = $procLockDetail]"/>

        <!-- Home sector refresh lock -->
        <set_value name="$refreshLockDetail" exact="'Not locked'"/>
        <do_if value="$homeSector? and $homeSector.exists and global.$GT_TS_LiveRefreshBySector? and global.$GT_TS_LiveRefreshBySector.{$homeSector}? and global.$GT_TS_LiveRefreshBySector.{$homeSector}.$Active?">
          <set_value name="$lockInitiator" exact="@global.$GT_TS_LiveRefreshBySector.{$homeSector}.$Initiator"/>
          <set_value name="$refreshLockDetail" exact="'LOCKED by ' + (if $lockInitiator? then $lockInitiator.idcode else 'unknown')"/>
          <do_if value="$lockInitiator? and $lockInitiator == $ship">
            <set_value name="$refreshLockDetail" exact="'LOCKED by THIS ship (self)'"/>
          </do_if>
        </do_if>
        <append_to_list name="$sec6.$Rows" exact="table[$Check = 'Home Sector Refresh Lock', $Status = 'INFO', $Detail = $refreshLockDetail]"/>

        <!-- Live search cooldown -->
        <set_value name="$cooldownDetail" exact="'No cooldown'"/>
        <do_if value="global.$GT_CacheMissCooldowns? and global.$GT_CacheMissCooldowns.{$ship}?">
          <set_value name="$cooldownExpiry" exact="@global.$GT_CacheMissCooldowns.{$ship}.$Expiry"/>
          <do_if value="$cooldownExpiry? and player.age lt $cooldownExpiry">
            <set_value name="$cooldownRemaining" exact="$cooldownExpiry - player.age"/>
            <set_value name="$cooldownDetail" exact="'Active - ' + $cooldownRemaining + 's remaining'"/>
          </do_if>
          <do_else>
            <set_value name="$cooldownDetail" exact="'Expired'"/>
          </do_else>
        </do_if>
        <append_to_list name="$sec6.$Rows" exact="table[$Check = 'Live Search Cooldown', $Status = 'INFO', $Detail = $cooldownDetail]"/>

        <append_to_list name="$report.$Sections" exact="$sec6"/>

        <!-- ======================================================== -->
        <!-- SECTION 7: Cache State Dump                              -->
        <!-- SKIPPED in clearance mode (clearance doesn't use cache)  -->
        <!-- SKIPPED for MK1/MK2/Miner (they don't use cache)         -->
        <!-- ======================================================== -->
        <do_if value="not $isClearanceMode and ($orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2')">
        <set_value name="$sec7" exact="table[]"/>
        <set_value name="$sec7.$Name" exact="'Cache State'"/>
        <set_value name="$sec7.$Rows" exact="[]"/>

        <set_value name="$cacheExists" exact="false"/>
        <set_value name="$cacheEntryCount" exact="0"/>
        <set_value name="$cargoCompatCount" exact="0"/>
        <set_value name="$cargoIncompatCount" exact="0"/>
        <set_value name="$cacheRuntimeReadableCount" exact="0"/>
        <set_value name="$cacheRejectNoSellStation" exact="0"/>
        <set_value name="$cacheRejectNoBuyStation" exact="0"/>
        <set_value name="$cacheRejectOfferAmount" exact="0"/>
        <set_value name="$cacheRejectTradeRules" exact="0"/>
        <set_value name="$diagCachePoolLabel" exact="if $orderId == 'GalaxyTraderMK4Supply2' then 'MK4-2' else (if $orderId == 'GalaxyTraderMK4Supply' then 'MK4' else 'MK3')"/>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply2'">
          <do_if value="$homeSector? and $homeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$homeSector}?">
            <set_value name="$cacheExists" exact="true"/>
            <set_value name="$cacheList" exact="global.$GT_TradeCacheMK42.{$homeSector}"/>
            <do_if value="$cacheList.count?">
              <set_value name="$cacheEntryCount" exact="$cacheList.count"/>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK4Supply'">
          <do_if value="$homeSector? and $homeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}?">
            <set_value name="$cacheExists" exact="true"/>
            <set_value name="$cacheList" exact="global.$GT_TradeCacheMK4.{$homeSector}"/>
            <do_if value="$cacheList.count?">
              <set_value name="$cacheEntryCount" exact="$cacheList.count"/>
            </do_if>
          </do_if>
        </do_elseif>
        <do_else>
          <do_if value="$homeSector? and $homeSector.exists and global.$GT_TradeCache? and global.$GT_TradeCache.{$homeSector}?">
            <set_value name="$cacheExists" exact="true"/>
            <set_value name="$cacheList" exact="global.$GT_TradeCache.{$homeSector}"/>
            <do_if value="$cacheList.count?">
              <set_value name="$cacheEntryCount" exact="$cacheList.count"/>
            </do_if>
          </do_if>
        </do_else>
        <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Cache Exists', $Status = if $cacheExists then 'PASS' else 'FAIL', $Detail = $diagCachePoolLabel + ' pool: ' + $cacheEntryCount + ' entries']"/>

        <!-- Cache max distance (cache metadata only, not ship order distance) -->
        <set_value name="$cacheMaxDist" exact="-1"/>
        <set_value name="$cacheDistResult" exact="'INFO'"/>
        <set_value name="$cacheDistDetail" exact="'N/A (no cache max-distance metadata yet) - ship needs: ' + $maxDistance + ' jumps'"/>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply2'">
          <do_if value="$homeSector? and global.$GT_TradeCacheMK42MaxDistance? and global.$GT_TradeCacheMK42MaxDistance.{$homeSector}?">
            <set_value name="$cacheMaxDist" exact="global.$GT_TradeCacheMK42MaxDistance.{$homeSector}"/>
            <set_value name="$cacheDistResult" exact="if $cacheMaxDist ge $maxDistance then 'PASS' else 'WARN'"/>
            <set_value name="$cacheDistDetail" exact="'MK4-2 cache max distance metadata: ' + $cacheMaxDist + ' jumps; ship needs ' + $maxDistance + ' jumps'"/>
          </do_if>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK4Supply'">
          <do_if value="$homeSector? and global.$GT_TradeCacheMK4MaxDistance? and global.$GT_TradeCacheMK4MaxDistance.{$homeSector}?">
            <set_value name="$cacheMaxDist" exact="global.$GT_TradeCacheMK4MaxDistance.{$homeSector}"/>
            <set_value name="$cacheDistResult" exact="if $cacheMaxDist ge $maxDistance then 'PASS' else 'WARN'"/>
            <set_value name="$cacheDistDetail" exact="'MK4 cache max distance metadata: ' + $cacheMaxDist + ' jumps; ship needs ' + $maxDistance + ' jumps'"/>
          </do_if>
        </do_elseif>
        <do_else>
          <do_if value="$homeSector? and global.$GT_TradeCacheMaxDistance? and global.$GT_TradeCacheMaxDistance.{$homeSector}?">
            <set_value name="$cacheMaxDist" exact="global.$GT_TradeCacheMaxDistance.{$homeSector}"/>
            <set_value name="$cacheDistResult" exact="if $cacheMaxDist ge $maxDistance then 'PASS' else 'WARN'"/>
            <set_value name="$cacheDistDetail" exact="'MK3 cache max distance metadata: ' + $cacheMaxDist + ' jumps; ship needs ' + $maxDistance + ' jumps'"/>
          </do_if>
        </do_else>
        <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Cache Max Distance', $Status = $cacheDistResult, $Detail = $cacheDistDetail]"/>

        <!-- MK3 home fleet cargo profile (cache-refresh totalvolume fleet-min; F7 diagnose) -->
        <do_if value="$orderId == 'GalaxyTraderMK3'">
          <append_to_list name="$sec7.$Rows" exact="table[$Check = '--- Home Fleet Cargo Profile ---', $Status = 'INFO', $Detail = 'Cache-refresh live search uses fleet-min; cache read and execution use per-ship cargotarget']"/>
          <run_actions ref="md.GT_HomeFleetProfile.GT_ShipIsMK3Service" result="$diagMk3Service">
            <param name="ship" value="$ship"/>
          </run_actions>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'MK3 Cache Cohort', $Status = if $diagMk3Service then 'PASS' else 'WARN', $Detail = if $diagMk3Service then 'Ship is in MK3 cache-sharing cohort' else 'Ship is not in MK3 service (profile N/A)']"/>
          <run_actions ref="md.GT_HomeFleetProfile.GT_GetMK3EffectiveCargoTarget" result="$diagFleetCargoPct">
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="$diagShipReqContainer" exact="(($ship.cargo.capacity.container + $ship.cargo.capacity.universal) * $diagFleetCargoPct / 100)i"/>
          <set_value name="$diagShipReqSolid" exact="(($ship.cargo.capacity.solid + $ship.cargo.capacity.universal) * $diagFleetCargoPct / 100)i"/>
          <set_value name="$diagShipReqLiquid" exact="(($ship.cargo.capacity.liquid + $ship.cargo.capacity.universal) * $diagFleetCargoPct / 100)i"/>
          <set_value name="$diagShipFreeContainer" exact="$ship.cargo.free.container + $ship.cargo.free.universal"/>
          <set_value name="$diagShipFreeSolid" exact="$ship.cargo.free.solid + $ship.cargo.free.universal"/>
          <set_value name="$diagShipFreeLiquid" exact="$ship.cargo.free.liquid + $ship.cargo.free.universal"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'This Ship Required Vol', $Status = 'INFO', $Detail = 'container=' + $diagShipReqContainer + ', solid=' + $diagShipReqSolid + ', liquid=' + $diagShipReqLiquid + ' (' + $diagFleetCargoPct + '% cargotarget)']"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'This Ship Free Cargo', $Status = 'INFO', $Detail = 'container=' + $diagShipFreeContainer + ', solid=' + $diagShipFreeSolid + ', liquid=' + $diagShipFreeLiquid + ' (direct-live mintotalvolume max)']"/>
          <set_value name="$diagFleetProfile" exact="null"/>
          <set_value name="$diagFleetProfileStatus" exact="'WARN'"/>
          <set_value name="$diagFleetProfileDetail" exact="'No profile (cache-refresh live search falls back to totalvolume min=1 until next fleet rebuild)'"/>
          <do_if value="$homeSector? and $homeSector.exists and global.$GT_HomeFleetCargoProfile? and global.$GT_HomeFleetCargoProfile.{$homeSector}?">
            <set_value name="$diagFleetProfile" exact="global.$GT_HomeFleetCargoProfile.{$homeSector}"/>
          </do_if>
          <do_if value="$diagFleetProfile?">
            <set_value name="$diagFleetShipCount" exact="if $diagFleetProfile.$ShipCount? then $diagFleetProfile.$ShipCount else 0"/>
            <set_value name="$diagFleetProfileStatus" exact="if $diagFleetShipCount gt 0 then 'PASS' else 'WARN'"/>
            <set_value name="$diagFleetProfileDetail" exact="if $diagFleetShipCount gt 0 then ('Cohort at ' + $homeSectorName + ': ' + $diagFleetShipCount + ' MK3-service ships') else 'Empty cohort entry (fallback totalvolume min=1)'"/>
          </do_if>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Profile Registry', $Status = $diagFleetProfileStatus, $Detail = $diagFleetProfileDetail]"/>
          <set_value name="$diagFleetMinContainer" exact="1"/>
          <set_value name="$diagFleetMinSolid" exact="1"/>
          <set_value name="$diagFleetMinLiquid" exact="1"/>
          <set_value name="$diagFleetProfileAge" exact="'N/A'"/>
          <do_if value="$diagFleetProfile? and $diagFleetProfile.$MinRequired?">
            <do_if value="$diagFleetProfile.$MinRequired.$container?">
              <set_value name="$diagFleetMinContainer" exact="$diagFleetProfile.$MinRequired.$container"/>
            </do_if>
            <do_if value="$diagFleetProfile.$MinRequired.$solid?">
              <set_value name="$diagFleetMinSolid" exact="$diagFleetProfile.$MinRequired.$solid"/>
            </do_if>
            <do_if value="$diagFleetProfile.$MinRequired.$liquid?">
              <set_value name="$diagFleetMinLiquid" exact="$diagFleetProfile.$MinRequired.$liquid"/>
            </do_if>
          </do_if>
          <do_if value="$diagFleetProfile? and $diagFleetProfile.$UpdatedAt?">
            <set_value name="$diagFleetProfileAge" exact="'' + ((player.age - $diagFleetProfile.$UpdatedAt) / 1s)i + 's ago'"/>
          </do_if>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Profile Age', $Status = 'INFO', $Detail = $diagFleetProfileAge]"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Fleet-Min Required Vol', $Status = 'INFO', $Detail = 'container=' + $diagFleetMinContainer + ', solid=' + $diagFleetMinSolid + ', liquid=' + $diagFleetMinLiquid + ' (cache-refresh totalvolume min)']"/>
          <set_value name="$diagFleetLimitBuckets" exact="''"/>
          <do_if value="$diagFleetProfile? and $diagFleetShipCount? and $diagFleetShipCount gt 0">
            <do_if value="$diagShipReqContainer == $diagFleetMinContainer">
              <set_value name="$diagFleetLimitBuckets" exact="'container'"/>
            </do_if>
            <do_if value="$diagShipReqSolid == $diagFleetMinSolid">
              <set_value name="$diagFleetLimitBuckets" exact="if $diagFleetLimitBuckets == '' then 'solid' else $diagFleetLimitBuckets + ', solid'"/>
            </do_if>
            <do_if value="$diagShipReqLiquid == $diagFleetMinLiquid">
              <set_value name="$diagFleetLimitBuckets" exact="if $diagFleetLimitBuckets == '' then 'liquid' else $diagFleetLimitBuckets + ', liquid'"/>
            </do_if>
          </do_if>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'This Ship Sets Fleet-Min', $Status = if $diagFleetLimitBuckets != '' then 'INFO' else 'PASS', $Detail = if not $diagFleetProfile? then 'N/A (no profile yet)' else if $diagFleetLimitBuckets != '' then ('Limiting bucket(s): ' + $diagFleetLimitBuckets) else 'No (another fleet member has stricter cargotarget or smaller hold)']"/>
        </do_if>

        <!-- Cache age analysis + per-entry dump (top 20 by ROI) -->
        <do_if value="$cacheExists and $cacheEntryCount gt 0">
          <set_value name="$diagCacheBucketDetail" exact="'N/A'"/>
          <set_value name="$diagCacheBsP" exact="0"/>
          <set_value name="$diagCacheBsN" exact="0"/>
          <set_value name="$diagCacheStP" exact="0"/>
          <set_value name="$diagCacheStN" exact="0"/>
          <set_value name="$diagCacheAxP" exact="0"/>
          <set_value name="$diagCacheAxN" exact="0"/>
          <set_value name="$diagCacheCrP" exact="0"/>
          <set_value name="$diagCacheCrN" exact="0"/>
          <set_value name="$failedShipCount" exact="0"/>
          <set_value name="$oldestAge" exact="0"/>
          <set_value name="$newestAge" exact="999999"/>
          <set_value name="$expiredCount" exact="0"/>
          <set_value name="$uniqueWares" exact="table[]"/>
          <set_value name="$cacheDetails" exact="[]"/>
          <set_value name="$cacheIdx" exact="0"/>
          <set_value name="$diagCacheTTL" exact="300s"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL?">
            <set_value name="$diagCacheTTL" exact="@global.$GT_GlobalSettings.$Fleet.$CacheTTL"/>
          </do_if>

          <!-- Count unique wares + cargo compatibility across ALL cache entries (mirrors lib.gt.cache.search). -->
          <!-- NOTE: Must NOT combine @ and ? operators (X4 rule: @$x? is invalid) -->
          <do_all exact="$cacheEntryCount" counter="$wi">
            <set_value name="$wareEntry" exact="@$cacheList.{$wi}"/>
            <do_if value="$wareEntry?">
              <set_value name="$tempWare" exact="@$wareEntry.$Ware"/>
              <do_if value="not $tempWare? and $wareEntry.$BuyOffer? and @$wareEntry.$BuyOffer.exists and @$wareEntry.$BuyOffer.ware != null">
                <set_value name="$tempWare" exact="@$wareEntry.$BuyOffer.ware"/>
              </do_if>
              <do_if value="not $tempWare? and $wareEntry.$SellOffer? and @$wareEntry.$SellOffer.exists and @$wareEntry.$SellOffer.ware != null">
                <set_value name="$tempWare" exact="@$wareEntry.$SellOffer.ware"/>
              </do_if>
              <set_value name="$tempTransport" exact="null"/>
              <do_if value="$wareEntry.$CargoWareTransport?">
                <set_value name="$tempTransport" exact="@$wareEntry.$CargoWareTransport"/>
              </do_if>
              <do_elseif value="$tempWare?">
                <set_value name="$tempTransport" exact="@$tempWare.waretransport"/>
              </do_elseif>
              <set_value name="$tempCargoOk" exact="false"/>
              <do_if value="$tempWare? and $ship.cargo.{$tempWare}.max gt 0">
                <set_value name="$tempCargoOk" exact="true"/>
              </do_if>
              <do_elseif value="$tempTransport? and $ship.waretransport.indexof.{$tempTransport}">
                <set_value name="$tempCargoOk" exact="true"/>
              </do_elseif>
              <do_if value="$tempWare?">
                <set_value name="$uniqueWares.{$tempWare}" exact="true"/>
              </do_if>
              <do_if value="$tempCargoOk">
                <set_value name="$cargoCompatCount" operation="add"/>
              </do_if>

              <!-- Runtime cache readability (mirrors lib.gt.cache.search gates for buy_and_sell). -->
              <set_value name="$tempBuyStation" exact="null"/>
              <do_if value="$wareEntry.$BuyStation? and @$wareEntry.$BuyStation.exists">
                <set_value name="$tempBuyStation" exact="$wareEntry.$BuyStation"/>
              </do_if>
              <do_if value="not $tempBuyStation? and $wareEntry.$BuyOffer? and @$wareEntry.$BuyOffer.exists">
                <do_if value="$wareEntry.$BuyOffer.seller? and @$wareEntry.$BuyOffer.seller.exists">
                  <set_value name="$tempBuyStation" exact="@$wareEntry.$BuyOffer.seller"/>
                </do_if>
                <do_elseif value="$wareEntry.$BuyOffer.owner? and @$wareEntry.$BuyOffer.owner.exists">
                  <set_value name="$tempBuyStation" exact="@$wareEntry.$BuyOffer.owner"/>
                </do_elseif>
              </do_if>
              <!-- MK4-2 cache bucket breakdown (delivery class x supplier source). -->
              <do_if value="$orderId == 'GalaxyTraderMK4Supply2'">
                <set_value name="$diagCacheClassTag" exact="if $wareEntry.$CustomerClass? then @$wareEntry.$CustomerClass else 'None'"/>
                <set_value name="$diagCacheSrcTag" exact="'Npc'"/>
                <do_if value="$wareEntry.$SupplierSource? and $wareEntry.$SupplierSource != 'Any'">
                  <set_value name="$diagCacheSrcTag" exact="@$wareEntry.$SupplierSource"/>
                </do_if>
                <do_elseif value="$tempBuyStation? and @$tempBuyStation.isplayerowned">
                  <set_value name="$diagCacheSrcTag" exact="'Player'"/>
                </do_elseif>
                <do_if value="$diagCacheClassTag == 'Buildstorage' and $diagCacheSrcTag == 'Player'">
                  <set_value name="$diagCacheBsP" operation="add"/>
                </do_if>
                <do_elseif value="$diagCacheClassTag == 'Buildstorage' and $diagCacheSrcTag == 'Npc'">
                  <set_value name="$diagCacheBsN" operation="add"/>
                </do_elseif>
                <do_elseif value="$diagCacheClassTag == 'Stations' and $diagCacheSrcTag == 'Player'">
                  <set_value name="$diagCacheStP" operation="add"/>
                </do_elseif>
                <do_elseif value="$diagCacheClassTag == 'Stations' and $diagCacheSrcTag == 'Npc'">
                  <set_value name="$diagCacheStN" operation="add"/>
                </do_elseif>
                <do_elseif value="$diagCacheClassTag == 'Aux' and $diagCacheSrcTag == 'Player'">
                  <set_value name="$diagCacheAxP" operation="add"/>
                </do_elseif>
                <do_elseif value="$diagCacheClassTag == 'Aux' and $diagCacheSrcTag == 'Npc'">
                  <set_value name="$diagCacheAxN" operation="add"/>
                </do_elseif>
                <do_elseif value="$diagCacheClassTag == 'Carrier' and $diagCacheSrcTag == 'Player'">
                  <set_value name="$diagCacheCrP" operation="add"/>
                </do_elseif>
                <do_elseif value="$diagCacheClassTag == 'Carrier' and $diagCacheSrcTag == 'Npc'">
                  <set_value name="$diagCacheCrN" operation="add"/>
                </do_elseif>
              </do_if>
              <set_value name="$tempSellStationFromBuyer" exact="null"/>
              <do_if value="$wareEntry.$SellOffer? and @$wareEntry.$SellOffer.exists and $wareEntry.$SellOffer.buyer? and @$wareEntry.$SellOffer.buyer.exists">
                <set_value name="$tempSellStationFromBuyer" exact="@$wareEntry.$SellOffer.buyer"/>
              </do_if>
              <set_value name="$tempSellStation" exact="null"/>
              <do_if value="$diagMk4BuildStorageOnlyMode and $tempSellStationFromBuyer? and @$tempSellStationFromBuyer.exists">
                <set_value name="$tempSellStation" exact="$tempSellStationFromBuyer"/>
              </do_if>
              <do_if value="not $tempSellStation? and $wareEntry.$SellStation? and @$wareEntry.$SellStation.exists">
                <set_value name="$tempSellStation" exact="$wareEntry.$SellStation"/>
              </do_if>
              <do_if value="$tempSellStation? and @$tempSellStation.exists and not @$tempSellStation.isclass.buildstorage and $tempSellStationFromBuyer? and @$tempSellStationFromBuyer.isclass.buildstorage">
                <set_value name="$tempSellStation" exact="$tempSellStationFromBuyer"/>
              </do_if>
              <do_if value="not $tempSellStation? and $tempSellStationFromBuyer?">
                <set_value name="$tempSellStation" exact="$tempSellStationFromBuyer"/>
              </do_if>
              <do_if value="not $tempSellStation? and $wareEntry.$SellOffer? and @$wareEntry.$SellOffer.exists and $wareEntry.$SellOffer.owner? and @$wareEntry.$SellOffer.owner.exists">
                <set_value name="$tempSellStation" exact="@$wareEntry.$SellOffer.owner"/>
              </do_if>
              <!-- Delivery refs die when buy offers refresh; re-discover from permanent keys (mirrors lib.gt.cache.search). -->
              <do_if value="not ($tempSellStation? and @$tempSellStation.exists) and $wareEntry.$SellStationBase? and @$wareEntry.$SellStationBase.exists and @$wareEntry.$SellStationBase.buildstorage and @$wareEntry.$SellStationBase.buildstorage.exists">
                <set_value name="$tempSellStation" exact="@$wareEntry.$SellStationBase.buildstorage"/>
              </do_if>
              <set_value name="$tempReWare" exact="if $tempWare? then $tempWare else null"/>
              <do_if value="$tempReWare == null and $wareEntry.$BuyOffer? and @$wareEntry.$BuyOffer.exists and @$wareEntry.$BuyOffer.ware != null">
                <set_value name="$tempReWare" exact="@$wareEntry.$BuyOffer.ware"/>
              </do_if>
              <do_if value="$tempReWare == null and $wareEntry.$SellOffer? and @$wareEntry.$SellOffer.exists and @$wareEntry.$SellOffer.ware != null">
                <set_value name="$tempReWare" exact="@$wareEntry.$SellOffer.ware"/>
              </do_if>
              <do_if value="not ($tempSellStation? and @$tempSellStation.exists) and $wareEntry.$DeliveryStationId? and $homeSector? and @$homeSector.exists">
                <run_actions ref="md.GT_Libraries_General.GT_ResolveStationByIdcodeInRange" result="$tempSellStation">
                  <param name="homeSector" value="$homeSector"/>
                  <param name="maxScanDistance" value="$diagSearchDistance + 2"/>
                  <param name="stationIdcode" value="$wareEntry.$DeliveryStationId"/>
                </run_actions>
              </do_if>
              <set_value name="$tempReSellSector" exact="null"/>
              <do_if value="$wareEntry.$SellSector? and @$wareEntry.$SellSector.exists">
                <set_value name="$tempReSellSector" exact="$wareEntry.$SellSector"/>
              </do_if>
              <do_elseif value="$wareEntry.$SellSectorId? and $homeSector? and @$homeSector.exists">
                <run_actions ref="md.GT_Libraries_General.GT_ResolveSectorByIdcodeInRange" result="$tempReSellSector">
                  <param name="homeSector" value="$homeSector"/>
                  <param name="maxScanDistance" value="$diagSearchDistance + 2"/>
                  <param name="sectorIdcode" value="$wareEntry.$SellSectorId"/>
                </run_actions>
              </do_elseif>
              <do_if value="not ($tempSellStation? and @$tempSellStation.exists) and $tempReSellSector? and @$tempReSellSector.exists and $tempReWare?">
                <do_if value="$wareEntry.$DeliveryStationId?">
                  <find_buy_offer wares="$tempReWare" tradepartner="$ship" space="$tempReSellSector" result="$tempReOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$ship"/>
                  </find_buy_offer>
                  <do_if value="$tempReOffers? and $tempReOffers.count gt 0">
                    <do_for_each name="$tempReO" in="$tempReOffers">
                      <do_if value="not ($tempSellStation? and @$tempSellStation.exists) and $tempReO? and @$tempReO.exists">
                        <set_value name="$tempReCand" exact="null"/>
                        <do_if value="$tempReO.buyer? and @$tempReO.buyer.exists">
                          <set_value name="$tempReCand" exact="@$tempReO.buyer"/>
                        </do_if>
                        <do_elseif value="$tempReO.owner? and @$tempReO.owner.exists">
                          <set_value name="$tempReCand" exact="@$tempReO.owner"/>
                        </do_elseif>
                        <do_if value="$tempReCand? and @$tempReCand.exists">
                          <set_value name="$tempReCandId" exact="if @$tempReCand.isclass.buildstorage and $tempReCand.base? and @$tempReCand.base.exists then @$tempReCand.base.idcode else @$tempReCand.idcode"/>
                          <do_if value="$tempReCandId == $wareEntry.$DeliveryStationId">
                            <set_value name="$tempSellStation" exact="$tempReCand"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_for_each>
                  </do_if>
                  <do_if value="not ($tempSellStation? and @$tempSellStation.exists)">
                    <find_object name="$tempBsObjs" class="class.buildstorage" space="$tempReSellSector" owner="faction.player" multiple="true"/>
                    <do_if value="$tempBsObjs? and $tempBsObjs.count gt 0">
                      <do_for_each name="$tempBsCand" in="$tempBsObjs">
                        <do_if value="not ($tempSellStation? and @$tempSellStation.exists) and $tempBsCand? and @$tempBsCand.exists and $tempBsCand.base? and @$tempBsCand.base.exists and @$tempBsCand.base.idcode == $wareEntry.$DeliveryStationId">
                          <set_value name="$tempSellStation" exact="$tempBsCand"/>
                        </do_if>
                      </do_for_each>
                    </do_if>
                  </do_if>
                </do_if>
                <do_elseif value="$wareEntry.$DeliveryStationName?">
                  <find_buy_offer wares="$tempReWare" tradepartner="$ship" space="$tempReSellSector" result="$tempNameOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$ship"/>
                  </find_buy_offer>
                  <do_if value="$tempNameOffers? and $tempNameOffers.count gt 0">
                    <do_for_each name="$tempNameO" in="$tempNameOffers">
                      <do_if value="not ($tempSellStation? and @$tempSellStation.exists) and $tempNameO? and @$tempNameO.exists">
                        <set_value name="$tempNameCand" exact="null"/>
                        <do_if value="$tempNameO.buyer? and @$tempNameO.buyer.exists">
                          <set_value name="$tempNameCand" exact="@$tempNameO.buyer"/>
                        </do_if>
                        <do_elseif value="$tempNameO.owner? and @$tempNameO.owner.exists">
                          <set_value name="$tempNameCand" exact="@$tempNameO.owner"/>
                        </do_elseif>
                        <do_if value="$tempNameCand? and @$tempNameCand.exists and $tempNameCand.knownname? and @$tempNameCand.knownname == $wareEntry.$DeliveryStationName">
                          <set_value name="$tempSellStation" exact="$tempNameCand"/>
                        </do_if>
                      </do_if>
                    </do_for_each>
                  </do_if>
                </do_elseif>
              </do_if>
              <set_value name="$tempBuyStationOk" exact="$tempBuyStation? and $tempBuyStation.exists"/>
              <set_value name="$tempSellStationOk" exact="$tempSellStation? and $tempSellStation.exists"/>
              <do_if value="not $wareEntry.$IsSellOnly? and not $tempBuyStationOk">
                <set_value name="$cacheRejectNoBuyStation" operation="add"/>
              </do_if>
              <do_if value="not $tempSellStationOk">
                <set_value name="$cacheRejectNoSellStation" operation="add"/>
              </do_if>

              <set_value name="$tempRuntimeOk" exact="true"/>
              <do_if value="not $wareEntry.$Score? or $wareEntry.$Score le 0">
                <set_value name="$tempRuntimeOk" exact="false"/>
              </do_if>
              <do_if value="$wareEntry.$IsSellOnly? and $wareEntry.$IsSellOnly">
                <set_value name="$tempRuntimeOk" exact="false"/>
              </do_if>
              <do_if value="not $tempCargoOk">
                <set_value name="$tempRuntimeOk" exact="false"/>
              </do_if>
              <set_value name="$cacheEntryTs" exact="if $wareEntry.$CachedAt? then @$wareEntry.$CachedAt else (if $wareEntry.$Timestamp? then @$wareEntry.$Timestamp else null)"/>
              <do_if value="$cacheEntryTs? and (player.age - $cacheEntryTs) gt $diagCacheTTL">
                <set_value name="$tempRuntimeOk" exact="false"/>
              </do_if>
              <do_if value="$wareEntry.$FailedShips? and $wareEntry.$FailedShips.count gt 0">
                <do_all exact="$wareEntry.$FailedShips.count" counter="$cacheFsIdx">
                  <do_if value="$wareEntry.$FailedShips.{$cacheFsIdx} == $ship">
                    <set_value name="$tempRuntimeOk" exact="false"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $wareEntry.$IsSellOnly? and not $tempBuyStationOk">
                <set_value name="$tempRuntimeOk" exact="false"/>
              </do_if>
              <do_if value="not $tempSellStationOk">
                <set_value name="$tempRuntimeOk" exact="false"/>
              </do_if>
              <do_if value="$tempRuntimeOk and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4CustomerMustBePlayer">
                <set_value name="$tempMk4DeliveryPlayerOk" exact="false"/>
                <do_if value="$tempSellStationOk and @$tempSellStation.isplayerowned">
                  <set_value name="$tempMk4DeliveryPlayerOk" exact="true"/>
                </do_if>
                <do_elseif value="$tempSellStationOk and $tempSellStation.isclass.buildstorage and $tempSellStation.base? and @$tempSellStation.base.isplayerowned">
                  <set_value name="$tempMk4DeliveryPlayerOk" exact="true"/>
                </do_elseif>
                <do_if value="not $tempMk4DeliveryPlayerOk">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="$tempRuntimeOk and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and not $wareEntry.$IsSellOnly?">
                <do_if value="not $diagMk4AllowAiSuppliers and (not $tempBuyStationOk or not @$tempBuyStation.isplayerowned)">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                </do_if>
                <do_if value="not $diagMk4AllowPlayerSuppliers and $tempBuyStationOk and @$tempBuyStation.isplayerowned">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="$tempRuntimeOk and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4BuildStorageOnlyMode and not $wareEntry.$IsSellOnly?">
                <do_if value="$tempBuyStationOk and @$tempBuyStation.isclass.buildstorage">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                </do_if>
                <do_if value="not $tempSellStationOk or not @$tempSellStation.isclass.buildstorage">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                </do_if>
                <set_value name="$tempMk4BsoInScope" exact="false"/>
                <!-- Component-based gatedistance (build storage often has no .sector); mirror of fixed cache.search. -->
                <set_value name="$tempMk4BsoDist" exact="if $homeSector? and $tempSellStationOk then $homeSector.gatedistance.{$tempSellStation} else -1"/>
                <do_if value="$tempMk4BsoDist ge 0 and ($maxSell le 0 or $tempMk4BsoDist le $maxSell)">
                  <set_value name="$tempMk4BsoInScope" exact="true"/>
                </do_if>
                <do_if value="not $tempMk4BsoInScope">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                </do_if>
              </do_if>
              <!-- Distance: pass the station COMPONENT to gatedistance (mirror of fixed
                   lib.gt.mk42.cache.search). Build storages often have no .sector accessor, so the
                   old '.sector?'-guarded form silently skipped the check and reported entries as
                   readable while the real cache rejected them on distance = -1. -->
              <do_if value="$tempRuntimeOk and $homeSector? and $homeSector.exists and not $wareEntry.$IsSellOnly?">
                <do_if value="$maxBuy gt 0 and $tempBuyStationOk">
                  <set_value name="$tempDistBuy" exact="$homeSector.gatedistance.{$tempBuyStation}"/>
                  <do_if value="$tempDistBuy lt 0 or $tempDistBuy gt $maxBuy">
                    <set_value name="$tempRuntimeOk" exact="false"/>
                  </do_if>
                </do_if>
                <do_if value="$maxSell gt 0 and $tempSellStationOk">
                  <set_value name="$tempDistSell" exact="$homeSector.gatedistance.{$tempSellStation}"/>
                  <do_if value="$tempDistSell lt 0 or $tempDistSell gt $maxSell">
                    <set_value name="$tempRuntimeOk" exact="false"/>
                  </do_if>
                </do_if>
              </do_if>
              <!-- Trade rules: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
              <do_if value="$tempRuntimeOk and not $ignoreTradeRules and not $wareEntry.$IsSellOnly?">
                <set_value name="$tempTradeRulesApply" exact="false"/>
                <do_if value="$tempBuyStationOk and $tempBuyStation? and @$tempBuyStation.exists">
                  <do_if value="@$tempBuyStation.isplayerowned">
                    <set_value name="$tempTradeRulesApply" exact="true"/>
                  </do_if>
                  <do_elseif value="@$tempBuyStation.isclass.buildstorage and $tempBuyStation.base? and @$tempBuyStation.base.exists and @$tempBuyStation.base.isplayerowned">
                    <set_value name="$tempTradeRulesApply" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="not $tempTradeRulesApply and $tempSellStationOk and $tempSellStation? and @$tempSellStation.exists">
                  <do_if value="@$tempSellStation.isplayerowned">
                    <set_value name="$tempTradeRulesApply" exact="true"/>
                  </do_if>
                  <do_elseif value="@$tempSellStation.isclass.buildstorage and $tempSellStation.base? and @$tempSellStation.base.exists and @$tempSellStation.base.isplayerowned">
                    <set_value name="$tempTradeRulesApply" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="$tempTradeRulesApply">
                  <do_if value="$wareEntry.$SellOffer? and @$wareEntry.$SellOffer.exists and $tempBuyStationOk and not $wareEntry.$SellOffer.cantradewith.{$tempBuyStation}">
                    <set_value name="$tempRuntimeOk" exact="false"/>
                    <set_value name="$cacheRejectTradeRules" operation="add"/>
                  </do_if>
                  <do_elseif value="$wareEntry.$BuyOffer? and @$wareEntry.$BuyOffer.exists and $tempSellStationOk and not $wareEntry.$BuyOffer.cantradewith.{$tempSellStation}">
                    <set_value name="$tempRuntimeOk" exact="false"/>
                    <set_value name="$cacheRejectTradeRules" operation="add"/>
                  </do_elseif>
                </do_if>
              </do_if>
              <do_if value="$tempRuntimeOk and not $wareEntry.$IsSellOnly? and $wareEntry.$BuyOffer? and @$wareEntry.$BuyOffer.exists">
                <set_value name="$tempPreBuyAmt" exact="@$wareEntry.$BuyOffer.offeramount.{$ship}"/>
                <do_if value="(not $tempPreBuyAmt? or $tempPreBuyAmt le 0) and @$wareEntry.$BuyOffer.amount gt 0">
                  <set_value name="$tempPreBuyAmt" exact="@$wareEntry.$BuyOffer.amount"/>
                </do_if>
                <do_if value="(not $tempPreBuyAmt? or $tempPreBuyAmt le 0) and $tempSellStationOk and $tempWare?">
                  <set_value name="$tempPreBuyAmt" exact="[0, $tempSellStation.cargo.{$tempWare}.target - $tempSellStation.cargo.{$tempWare}.count].max"/>
                </do_if>
                <do_if value="not $tempPreBuyAmt? or $tempPreBuyAmt le 0">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                  <set_value name="$cacheRejectOfferAmount" operation="add"/>
                </do_if>
              </do_if>
              <do_if value="$tempRuntimeOk and $wareEntry.$SellOffer? and @$wareEntry.$SellOffer.exists">
                <set_value name="$tempPreSellAmt" exact="@$wareEntry.$SellOffer.offeramount.{$ship}"/>
                <do_if value="(not $tempPreSellAmt? or $tempPreSellAmt le 0) and @$wareEntry.$SellOffer.amount gt 0">
                  <set_value name="$tempPreSellAmt" exact="@$wareEntry.$SellOffer.amount"/>
                </do_if>
                <do_if value="(not $tempPreSellAmt? or $tempPreSellAmt le 0) and $tempSellStationOk and $tempWare?">
                  <set_value name="$tempPreSellAmt" exact="[0, $tempSellStation.cargo.{$tempWare}.target - $tempSellStation.cargo.{$tempWare}.count].max"/>
                </do_if>
                <do_if value="not $tempPreSellAmt? or $tempPreSellAmt le 0">
                  <set_value name="$tempRuntimeOk" exact="false"/>
                  <set_value name="$cacheRejectOfferAmount" operation="add"/>
                </do_if>
              </do_if>
              <do_if value="$tempRuntimeOk">
                <set_value name="$cacheRuntimeReadableCount" operation="add"/>
              </do_if>
              <do_if value="not $tempCargoOk and ($tempWare? or $tempTransport?)">
                <set_value name="$cargoIncompatCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>

          <!-- Detail dump: top 20 entries by score (cache is sorted descending) -->
          <do_all exact="[20, $cacheEntryCount].min" counter="$ci">
            <set_value name="$entry" exact="@$cacheList.{$ci}"/>
            <do_if value="$entry?">
              <set_value name="$entryAge" exact="0"/>
              <do_if value="$entry.$Timestamp?">
                <set_value name="$entryAge" exact="player.age - $entry.$Timestamp"/>
              </do_if>
              <do_if value="$entryAge gt $oldestAge">
                <set_value name="$oldestAge" exact="$entryAge"/>
              </do_if>
              <do_if value="$entryAge lt $newestAge">
                <set_value name="$newestAge" exact="$entryAge"/>
              </do_if>
              <do_if value="$entryAge gt 600">
                <set_value name="$expiredCount" operation="add"/>
              </do_if>

              <set_value name="$entryWare" exact="@$entry.$Ware"/>
              <do_if value="not $entryWare? and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
                <set_value name="$entryWare" exact="@$entry.$BuyOffer.ware"/>
              </do_if>
              <do_if value="not $entryWare? and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
                <set_value name="$entryWare" exact="@$entry.$SellOffer.ware"/>
              </do_if>
              <set_value name="$entryCargoOk" exact="false"/>
              <set_value name="$entryTransport" exact="null"/>
              <do_if value="$entry.$CargoWareTransport?">
                <set_value name="$entryTransport" exact="@$entry.$CargoWareTransport"/>
              </do_if>
              <do_elseif value="$entryWare?">
                <set_value name="$entryTransport" exact="@$entryWare.waretransport"/>
              </do_elseif>
              <do_if value="$entryWare? and $ship.cargo.{$entryWare}.max gt 0">
                <set_value name="$entryCargoOk" exact="true"/>
              </do_if>
              <do_elseif value="$entryTransport? and $ship.waretransport.indexof.{$entryTransport}">
                <set_value name="$entryCargoOk" exact="true"/>
              </do_elseif>

              <!-- Failed ships check ($FailedShips list is runtime field; not $FailedShipSet) -->
              <set_value name="$shipFailed" exact="'No'"/>
              <do_if value="$entry.$FailedShips? and $entry.$FailedShips.count gt 0">
                <do_all exact="$entry.$FailedShips.count" counter="$fsDiagIdx">
                  <do_if value="$entry.$FailedShips.{$fsDiagIdx} == $ship">
                    <set_value name="$shipFailed" exact="'YES'"/>
                    <set_value name="$failedShipCount" operation="add"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>

              <!-- Build detail string (MK4: BuyOffer=supplier sell offer, SellOffer=customer buy offer; use $BuyStation/$SellStation first). -->
              <set_value name="$entryBuyStationObj" exact="null"/>
              <do_if value="$entry.$BuyStation? and @$entry.$BuyStation.exists">
                <set_value name="$entryBuyStationObj" exact="$entry.$BuyStation"/>
              </do_if>
              <do_elseif value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists">
                <do_if value="$entry.$BuyOffer.seller? and @$entry.$BuyOffer.seller.exists">
                  <set_value name="$entryBuyStationObj" exact="@$entry.$BuyOffer.seller"/>
                </do_if>
                <do_elseif value="$entry.$BuyOffer.owner? and @$entry.$BuyOffer.owner.exists">
                  <set_value name="$entryBuyStationObj" exact="@$entry.$BuyOffer.owner"/>
                </do_elseif>
              </do_elseif>
              <set_value name="$entryBuyStation" exact="'???'"/>
              <do_if value="$entryBuyStationObj? and $entryBuyStationObj.exists and $entryBuyStationObj.knownname?">
                <set_value name="$entryBuyStation" exact="$entryBuyStationObj.knownname"/>
              </do_if>
              <set_value name="$entryBuyStationOk" exact="$entryBuyStationObj? and $entryBuyStationObj.exists"/>

              <set_value name="$entrySellStationObj" exact="null"/>
              <set_value name="$entrySellFromBuyer" exact="null"/>
              <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.buyer? and @$entry.$SellOffer.buyer.exists">
                <set_value name="$entrySellFromBuyer" exact="@$entry.$SellOffer.buyer"/>
              </do_if>
              <do_if value="$diagMk4BuildStorageOnlyMode and $entrySellFromBuyer? and @$entrySellFromBuyer.exists">
                <set_value name="$entrySellStationObj" exact="$entrySellFromBuyer"/>
              </do_if>
              <do_if value="not $entrySellStationObj? and $entry.$SellStation? and @$entry.$SellStation.exists">
                <set_value name="$entrySellStationObj" exact="$entry.$SellStation"/>
              </do_if>
              <do_if value="$entrySellStationObj? and @$entrySellStationObj.exists and not @$entrySellStationObj.isclass.buildstorage and $entrySellFromBuyer? and @$entrySellFromBuyer.isclass.buildstorage">
                <set_value name="$entrySellStationObj" exact="$entrySellFromBuyer"/>
              </do_if>
              <do_if value="not $entrySellStationObj? and $entrySellFromBuyer?">
                <set_value name="$entrySellStationObj" exact="$entrySellFromBuyer"/>
              </do_if>
              <do_if value="not $entrySellStationObj? and $entry.$SellOffer? and @$entry.$SellOffer.exists and $entry.$SellOffer.owner? and @$entry.$SellOffer.owner.exists">
                <set_value name="$entrySellStationObj" exact="@$entry.$SellOffer.owner"/>
              </do_if>
              <!-- Delivery refs die when buy offers refresh; re-discover from permanent keys (mirrors lib.gt.cache.search). -->
              <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists) and $entry.$SellStationBase? and @$entry.$SellStationBase.exists and @$entry.$SellStationBase.buildstorage and @$entry.$SellStationBase.buildstorage.exists">
                <set_value name="$entrySellStationObj" exact="@$entry.$SellStationBase.buildstorage"/>
              </do_if>
              <set_value name="$entryReWare" exact="if $entryWare? then $entryWare else null"/>
              <do_if value="$entryReWare == null and $entry.$BuyOffer? and @$entry.$BuyOffer.exists and @$entry.$BuyOffer.ware != null">
                <set_value name="$entryReWare" exact="@$entry.$BuyOffer.ware"/>
              </do_if>
              <do_if value="$entryReWare == null and $entry.$SellOffer? and @$entry.$SellOffer.exists and @$entry.$SellOffer.ware != null">
                <set_value name="$entryReWare" exact="@$entry.$SellOffer.ware"/>
              </do_if>
              <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists) and $entry.$DeliveryStationId? and $homeSector? and @$homeSector.exists">
                <run_actions ref="md.GT_Libraries_General.GT_ResolveStationByIdcodeInRange" result="$entrySellStationObj">
                  <param name="homeSector" value="$homeSector"/>
                  <param name="maxScanDistance" value="$diagSearchDistance + 2"/>
                  <param name="stationIdcode" value="$entry.$DeliveryStationId"/>
                </run_actions>
              </do_if>
              <set_value name="$entryReSellSector" exact="null"/>
              <do_if value="$entry.$SellSector? and @$entry.$SellSector.exists">
                <set_value name="$entryReSellSector" exact="$entry.$SellSector"/>
              </do_if>
              <do_elseif value="$entry.$SellSectorId? and $homeSector? and @$homeSector.exists">
                <run_actions ref="md.GT_Libraries_General.GT_ResolveSectorByIdcodeInRange" result="$entryReSellSector">
                  <param name="homeSector" value="$homeSector"/>
                  <param name="maxScanDistance" value="$diagSearchDistance + 2"/>
                  <param name="sectorIdcode" value="$entry.$SellSectorId"/>
                </run_actions>
              </do_elseif>
              <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists) and $entryReSellSector? and @$entryReSellSector.exists and $entryReWare?">
                <do_if value="$entry.$DeliveryStationId?">
                  <find_buy_offer wares="$entryReWare" tradepartner="$ship" space="$entryReSellSector" result="$entryReOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$ship"/>
                  </find_buy_offer>
                  <do_if value="$entryReOffers? and $entryReOffers.count gt 0">
                    <do_for_each name="$entryReO" in="$entryReOffers">
                      <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists) and $entryReO? and @$entryReO.exists">
                        <set_value name="$entryReCand" exact="null"/>
                        <do_if value="$entryReO.buyer? and @$entryReO.buyer.exists">
                          <set_value name="$entryReCand" exact="@$entryReO.buyer"/>
                        </do_if>
                        <do_elseif value="$entryReO.owner? and @$entryReO.owner.exists">
                          <set_value name="$entryReCand" exact="@$entryReO.owner"/>
                        </do_elseif>
                        <do_if value="$entryReCand? and @$entryReCand.exists">
                          <set_value name="$entryReCandId" exact="if @$entryReCand.isclass.buildstorage and $entryReCand.base? and @$entryReCand.base.exists then @$entryReCand.base.idcode else @$entryReCand.idcode"/>
                          <do_if value="$entryReCandId == $entry.$DeliveryStationId">
                            <set_value name="$entrySellStationObj" exact="$entryReCand"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_for_each>
                  </do_if>
                  <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists)">
                    <find_object name="$entryBsObjs" class="class.buildstorage" space="$entryReSellSector" owner="faction.player" multiple="true"/>
                    <do_if value="$entryBsObjs? and $entryBsObjs.count gt 0">
                      <do_for_each name="$entryBsCand" in="$entryBsObjs">
                        <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists) and $entryBsCand? and @$entryBsCand.exists and $entryBsCand.base? and @$entryBsCand.base.exists and @$entryBsCand.base.idcode == $entry.$DeliveryStationId">
                          <set_value name="$entrySellStationObj" exact="$entryBsCand"/>
                        </do_if>
                      </do_for_each>
                    </do_if>
                  </do_if>
                </do_if>
                <do_elseif value="$entry.$DeliveryStationName?">
                  <find_buy_offer wares="$entryReWare" tradepartner="$ship" space="$entryReSellSector" result="$entryNameOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$ship"/>
                  </find_buy_offer>
                  <do_if value="$entryNameOffers? and $entryNameOffers.count gt 0">
                    <do_for_each name="$entryNameO" in="$entryNameOffers">
                      <do_if value="not ($entrySellStationObj? and @$entrySellStationObj.exists) and $entryNameO? and @$entryNameO.exists">
                        <set_value name="$entryNameCand" exact="null"/>
                        <do_if value="$entryNameO.buyer? and @$entryNameO.buyer.exists">
                          <set_value name="$entryNameCand" exact="@$entryNameO.buyer"/>
                        </do_if>
                        <do_elseif value="$entryNameO.owner? and @$entryNameO.owner.exists">
                          <set_value name="$entryNameCand" exact="@$entryNameO.owner"/>
                        </do_elseif>
                        <do_if value="$entryNameCand? and @$entryNameCand.exists and $entryNameCand.knownname? and @$entryNameCand.knownname == $entry.$DeliveryStationName">
                          <set_value name="$entrySellStationObj" exact="$entryNameCand"/>
                        </do_if>
                      </do_if>
                    </do_for_each>
                  </do_if>
                </do_elseif>
              </do_if>
              <set_value name="$entrySellStation" exact="'???'"/>
              <do_if value="$entrySellStationObj? and $entrySellStationObj.exists and $entrySellStationObj.knownname?">
                <!-- For build storages, surface the parent base station + sector (the bare build storage
                     name carries no location). -->
                <set_value name="$entrySellBaseObj" exact="if $entrySellStationObj.isclass.buildstorage and $entrySellStationObj.base? then @$entrySellStationObj.base else $entrySellStationObj"/>
                <set_value name="$entrySellSecObj" exact="if $entrySellBaseObj? and $entrySellBaseObj.sector? then @$entrySellBaseObj.sector else null"/>
                <set_value name="$entrySellSecName" exact="if $entrySellSecObj? and $entrySellSecObj.knownname? then @$entrySellSecObj.knownname else 'unknown sector'"/>
                <do_if value="$entrySellStationObj.isclass.buildstorage">
                  <set_value name="$entrySellStation" exact="$entrySellStationObj.knownname + ' @ ' + (if $entrySellBaseObj.knownname? then @$entrySellBaseObj.knownname else 'base') + ' (' + $entrySellSecName + ')'"/>
                </do_if>
                <do_else>
                  <set_value name="$entrySellStation" exact="$entrySellStationObj.knownname + ' (' + $entrySellSecName + ')'"/>
                </do_else>
              </do_if>
              <do_elseif value="$entry.$DeliveryStationName?">
                <set_value name="$entrySellStation" exact="$entry.$DeliveryStationName + ' [stale]'"/>
              </do_elseif>
              <do_elseif value="$entry.$SellSector? and @$entry.$SellSector.exists and @$entry.$SellSector.knownname">
                <set_value name="$entrySellStation" exact="@$entry.$SellSector.knownname + ' (delivery sector)'"/>
              </do_elseif>
              <do_elseif value="$entry.$SellStation? and @$entry.$SellStation.knownname">
                <set_value name="$entrySellStation" exact="@$entry.$SellStation.knownname + ' [dead ref]'"/>
              </do_elseif>
              <do_elseif value="$entry.$HomeToSellDistance?">
                <set_value name="$entrySellStation" exact="'(delivery ref dead, Hâ†’S ' + $entry.$HomeToSellDistance + 'j)'"/>
              </do_elseif>
              <do_else>
                <set_value name="$entrySellStation" exact="'(no delivery station)'"/>
              </do_else>
              <set_value name="$entrySellStationOk" exact="$entrySellStationObj? and $entrySellStationObj.exists"/>
              <set_value name="$entryWareName" exact="'???'"/>
              <do_if value="$entryWare?">
                <set_value name="$entryWareName" exact="$entryWare.name"/>
              </do_if>
              <set_value name="$entryTransportLabel" exact="''"/>
              <do_if value="$entryTransport?">
                <do_if value="$entryTransport == waretransport.container">
                  <set_value name="$entryTransportLabel" exact="' [container]'"/>
                </do_if>
                <do_elseif value="$entryTransport == waretransport.solid">
                  <set_value name="$entryTransportLabel" exact="' [solid]'"/>
                </do_elseif>
                <do_elseif value="$entryTransport == waretransport.liquid">
                  <set_value name="$entryTransportLabel" exact="' [liquid]'"/>
                </do_elseif>
              </do_if>
              <!-- ROI is not stored in cache entries - compute from UnitProfit / BuyPrice -->
              <set_value name="$entryBuyPrice" exact="@$entry.$BuyPrice"/>
              <set_value name="$entryUnitProfit" exact="@$entry.$UnitProfit"/>
              <set_value name="$entryROI" exact="0"/>
              <do_if value="$entryBuyPrice? and $entryBuyPrice gt 0 and $entryUnitProfit?">
                <set_value name="$entryROI" exact="($entryUnitProfit * 100) / $entryBuyPrice"/>
              </do_if>
              <set_value name="$entryFailCount" exact="@$entry.$FailCount"/>
              <do_if value="not $entryFailCount?">
                <set_value name="$entryFailCount" exact="0"/>
              </do_if>

              <set_value name="$entryScore" exact="@$entry.$Score"/>
              <do_if value="not $entryScore?">
                <set_value name="$entryScore" exact="0"/>
              </do_if>
              <set_value name="$entryProfit" exact="@$entry.$Profit"/>
              <do_if value="not $entryProfit?">
                <set_value name="$entryProfit" exact="0"/>
              </do_if>
              <set_value name="$entryDistDetail" exact="''"/>
              <do_if value="$entry.$HomeToBuyDistance? and $entry.$RouteDistance?">
                <set_value name="$entryDistDetail" exact="' | Dist Hâ†’B ' + $entry.$HomeToBuyDistance + ' + route ' + $entry.$RouteDistance"/>
                <do_if value="$entry.$Distance?">
                  <set_value name="$entryDistDetail" exact="$entryDistDetail + ' = ' + $entry.$Distance + 'j'"/>
                </do_if>
              </do_if>
              <do_elseif value="$entry.$Distance?">
                <set_value name="$entryDistDetail" exact="' | Dist ' + $entry.$Distance + 'j'"/>
              </do_elseif>
              <set_value name="$detailStr" exact="$entryWareName + $entryTransportLabel + ' | ' + $entryBuyStation + ' -> ' + $entrySellStation + ' | ' + ($entryProfit / 100) + 'Cr | ROI ' + $entryROI + '% | Score ' + ($entryScore)i + $entryDistDetail + ' | ' + $entryAge + 's'"/>
              <do_if value="not $entryCargoOk">
                <set_value name="$detailStr" exact="$detailStr + ' | CARGO-INCOMPAT'"/>
              </do_if>
              <do_if value="not $entry.$IsSellOnly? and not $entryBuyStationOk">
                <set_value name="$detailStr" exact="$detailStr + ' | NO-BUY-STATION'"/>
              </do_if>
              <do_if value="not $entrySellStationOk">
                <set_value name="$detailStr" exact="$detailStr + ' | NO-SELL-STATION'"/>
              </do_if>
              <do_if value="$shipFailed == 'YES'">
                <set_value name="$detailStr" exact="$detailStr + ' | FAILED'"/>
              </do_if>
              <!-- Trade rules: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
              <set_value name="$entryTradeRuleFail" exact="false"/>
              <do_if value="not $ignoreTradeRules and not $entry.$IsSellOnly?">
                <set_value name="$entryTradeRulesApply" exact="false"/>
                <do_if value="$entryBuyStationOk and $entryBuyStationObj? and @$entryBuyStationObj.exists">
                  <do_if value="@$entryBuyStationObj.isplayerowned">
                    <set_value name="$entryTradeRulesApply" exact="true"/>
                  </do_if>
                  <do_elseif value="@$entryBuyStationObj.isclass.buildstorage and $entryBuyStationObj.base? and @$entryBuyStationObj.base.exists and @$entryBuyStationObj.base.isplayerowned">
                    <set_value name="$entryTradeRulesApply" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="not $entryTradeRulesApply and $entrySellStationOk and $entrySellStationObj? and @$entrySellStationObj.exists">
                  <do_if value="@$entrySellStationObj.isplayerowned">
                    <set_value name="$entryTradeRulesApply" exact="true"/>
                  </do_if>
                  <do_elseif value="@$entrySellStationObj.isclass.buildstorage and $entrySellStationObj.base? and @$entrySellStationObj.base.exists and @$entrySellStationObj.base.isplayerowned">
                    <set_value name="$entryTradeRulesApply" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="$entryTradeRulesApply">
                  <do_if value="$entry.$SellOffer? and @$entry.$SellOffer.exists and $entryBuyStationOk and not $entry.$SellOffer.cantradewith.{$entryBuyStationObj}">
                    <set_value name="$entryTradeRuleFail" exact="true"/>
                    <set_value name="$detailStr" exact="$detailStr + ' | TRADE-RULES: player customer disallows source'"/>
                  </do_if>
                  <do_elseif value="$entry.$BuyOffer? and @$entry.$BuyOffer.exists and $entrySellStationOk and not $entry.$BuyOffer.cantradewith.{$entrySellStationObj}">
                    <set_value name="$entryTradeRuleFail" exact="true"/>
                    <set_value name="$detailStr" exact="$detailStr + ' | TRADE-RULES: player source disallows delivery'"/>
                  </do_elseif>
                </do_if>
              </do_if>
              <set_value name="$entryRowStatus" exact="'INFO'"/>
              <do_if value="not $entryCargoOk or not $entrySellStationOk or (not $entry.$IsSellOnly? and not $entryBuyStationOk) or $shipFailed == 'YES'">
                <set_value name="$entryRowStatus" exact="'WARN'"/>
              </do_if>
              <do_if value="$entryTradeRuleFail">
                <set_value name="$entryRowStatus" exact="'FAIL'"/>
              </do_if>
              <append_to_list name="$sec7.$Rows" exact="table[$Check = '#' + $ci, $Status = $entryRowStatus, $Detail = $detailStr]"/>
            </do_if>
          </do_all>

          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Unique Wares In Cache', $Status = 'INFO', $Detail = '' + $uniqueWares.keys.count + ' wares']"/>
          <do_if value="$orderId == 'GalaxyTraderMK4Supply2'">
            <set_value name="$diagCacheBucketDetail" exact="'BS_P=' + $diagCacheBsP + '/BS_N=' + $diagCacheBsN + '/ST_P=' + $diagCacheStP + '/ST_N=' + $diagCacheStN + '/AX_P=' + $diagCacheAxP + '/AX_N=' + $diagCacheAxN + '/CR_P=' + $diagCacheCrP + '/CR_N=' + $diagCacheCrN"/>
            <append_to_list name="$sec7.$Rows" exact="table[$Check = 'MK4-2 Cache Bucket Mix', $Status = 'INFO', $Detail = $diagCacheBucketDetail + ' (delivery class x supplier source; legacy entries infer source from BuyStation)']"/>
          </do_if>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Cargo-Compatible Entries', $Status = if $cargoCompatCount gt 0 then 'PASS' else (if $cacheEntryCount gt 0 then 'WARN' else 'INFO'), $Detail = '' + $cargoCompatCount + ' / ' + $cacheEntryCount + ' (cargo.max or $CargoWareTransport)']"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Cargo-Incompatible Entries', $Status = if $cargoIncompatCount gt 0 then 'WARN' else 'PASS', $Detail = '' + $cargoIncompatCount + ' entries for other hold types']"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Missing Sell Station (stale cache)', $Status = if $cacheRejectNoSellStation gt 0 then 'WARN' else 'PASS', $Detail = '' + $cacheRejectNoSellStation + ' / ' + $cacheEntryCount + ' entries have no resolvable $SellStation / $SellOffer.buyer (lib.gt.cache.search skips these)']"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Missing Buy Station (stale cache)', $Status = if $cacheRejectNoBuyStation gt 0 then 'WARN' else 'PASS', $Detail = '' + $cacheRejectNoBuyStation + ' / ' + $cacheEntryCount + ' entries have no resolvable $BuyStation / $BuyOffer.seller']"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Cache Runtime Readable', $Status = if $cacheRuntimeReadableCount gt 0 then 'PASS' else (if $cacheEntryCount gt 0 then 'WARN' else 'INFO'), $Detail = '' + $cacheRuntimeReadableCount + ' / ' + $cacheEntryCount + ' would be returned by lib.gt.cache.search for this ship (cargo+stations+MK4 policy+distance+offeramount+TTL+FailedShips; TTL=' + (($diagCacheTTL / 1s)i) + 's)']"/>
          <do_if value="$cacheRejectOfferAmount gt 0">
            <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Rejected: Zero Offer Amount', $Status = 'WARN', $Detail = '' + $cacheRejectOfferAmount + ' entries failed per-ship offeramount/demand fallback (saturation or stale offers)']"/>
          </do_if>
          <do_if value="$cacheRejectTradeRules gt 0">
            <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Rejected: Trade Rules', $Status = 'FAIL', $Detail = '' + $cacheRejectTradeRules + ' / ' + $cacheEntryCount + ' entries blocked by player-station trade rules (Ignore Trade Rules is off). NPCÃ—NPC pairs are not checked.']"/>
          </do_if>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'Expired Entries (>600s)', $Status = if $expiredCount gt 0 then 'WARN' else 'PASS', $Detail = '' + $expiredCount + ' / ' + [20, $cacheEntryCount].min]"/>
          <append_to_list name="$sec7.$Rows" exact="table[$Check = 'This Ship In FailedShips', $Status = if $failedShipCount gt 0 then 'WARN' else 'PASS', $Detail = '' + $failedShipCount + ' entries have this ship in FailedShips']"/>
        </do_if>

        <append_to_list name="$report.$Sections" exact="$sec7"/>
        </do_if>

        <!-- ======================================================== -->
        <!-- Compute search sectors (needed by both live search and   -->
        <!-- clearance analysis)                                       -->
        <!-- ======================================================== -->
        <set_value name="$searchSectors" exact="[]"/>
        <!-- MK2 routes per explicit source/dest station lists rather than via a home sector,
             so derive search anchors from those stations when no home sector is configured.
             Without this, MK2 ships without homeStation would scan zero sectors and produce
             a misleading "no offers in 0 sectors" verdict. -->
        <set_value name="$mk2AnchorSectors" exact="[]"/>
        <do_if value="$orderId == 'GalaxyTraderMK2' and $gtOrder?">
          <do_if value="$gtOrder.$sourceList? and $gtOrder.$sourceList.count gt 0">
            <do_all exact="$gtOrder.$sourceList.count" counter="$mk2si">
              <set_value name="$mk2sStation" exact="$gtOrder.$sourceList.{$mk2si}"/>
              <do_if value="$mk2sStation? and $mk2sStation.exists and $mk2sStation.sector? and $mk2sStation.sector.exists and not $mk2AnchorSectors.indexof.{$mk2sStation.sector}">
                <append_to_list name="$mk2AnchorSectors" exact="$mk2sStation.sector"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$gtOrder.$destList? and $gtOrder.$destList.count gt 0">
            <do_all exact="$gtOrder.$destList.count" counter="$mk2di">
              <set_value name="$mk2dStation" exact="$gtOrder.$destList.{$mk2di}"/>
              <do_if value="$mk2dStation? and $mk2dStation.exists and $mk2dStation.sector? and $mk2dStation.sector.exists and not $mk2AnchorSectors.indexof.{$mk2dStation.sector}">
                <append_to_list name="$mk2AnchorSectors" exact="$mk2dStation.sector"/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <!-- Build the union of all anchor sectors (home sector + MK2 station sectors). -->
        <set_value name="$searchAnchors" exact="[]"/>
        <do_if value="$homeSector? and $homeSector.exists">
          <append_to_list name="$searchAnchors" exact="$homeSector"/>
        </do_if>
        <do_all exact="$mk2AnchorSectors.count" counter="$mk2ai">
          <set_value name="$mk2aSec" exact="$mk2AnchorSectors.{$mk2ai}"/>
          <do_if value="not $searchAnchors.indexof.{$mk2aSec}">
            <append_to_list name="$searchAnchors" exact="$mk2aSec"/>
          </do_if>
        </do_all>
        <do_if value="$searchAnchors.count gt 0">
          <!-- Always include the anchor sectors themselves -->
          <do_all exact="$searchAnchors.count" counter="$anchi">
            <set_value name="$anchSec" exact="$searchAnchors.{$anchi}"/>
            <do_if value="not $searchSectors.indexof.{$anchSec}">
              <append_to_list name="$searchSectors" exact="$anchSec"/>
            </do_if>
          </do_all>
          <!-- Add neighboring sectors within diagnose search distance from any anchor.
               For MK2 this expands coverage from each station's local sector outward; for
               other orders the loop runs once with $homeSector as the sole anchor. -->
          <do_if value="$diagSearchDistance gt 0">
            <do_all exact="$searchAnchors.count" counter="$anchExpandIdx">
              <set_value name="$anchExpandSec" exact="$searchAnchors.{$anchExpandIdx}"/>
              <find_sector name="$nearbySectors" space="player.galaxy" multiple="true">
                <match_gate_distance object="$anchExpandSec" min="0" max="$diagSearchDistance"/>
              </find_sector>
              <do_if value="$nearbySectors? and $nearbySectors.count gt 0">
                <do_all exact="$nearbySectors.count" counter="$si">
                  <set_value name="$nearbySec" exact="$nearbySectors.{$si}"/>
                  <do_if value="$nearbySec != $anchExpandSec and not $searchSectors.indexof.{$nearbySec}">
                    <!-- Diagnose parity fix: only include sectors reachable with blacklist-aware pathing. -->
                    <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$diagSecDist">
                      <param name="ship" value="$ship"/>
                      <param name="fromSector" value="$anchExpandSec"/>
                      <param name="toSector" value="$nearbySec"/>
                      <param name="blacklistgroup" value="$diagBlacklistGroup"/>
                      <param name="useEscapeMode" value="false"/>
                    </run_actions>
                    <do_if value="$diagSecDist ge 0 and $diagSecDist le $diagSearchDistance">
                      <append_to_list name="$searchSectors" exact="$nearbySec"/>
                    </do_if>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
        </do_if>

        <!-- ======================================================== -->
        <!-- SECTION 8: Live Search (EXPLICIT)                        -->
        <!-- Runs find_sell_offer / find_buy_offer for all sectors     -->
        <!-- MK1 uses dedicated home-station export path (see below).  -->
        <!-- SKIPPED in clearance mode (ship is selling, not searching)-->
        <!-- ======================================================== -->
        <do_if value="not $isClearanceMode">
        <set_value name="$sec8" exact="table[]"/>
        <!-- Miner section uses a different display name so the Lua falls through to the
             generic 3-col layout (Status | Check | Detail) instead of the trader 6-col
             layout with Sell|Buy|Total column headers. The miner path has no Sell-Offer
             data to fill the Sell column with, and surfacing those headers above
             buyer-only rows reads as "the diag couldn't find any sell offers". -->
        <set_value name="$sec8.$Name" exact="if $orderId == 'GalaxyMiner' then 'Search Summary (Buyer Side)' else 'Search Summary'"/>
        <set_value name="$sec8.$Rows" exact="[]"/>
        <!-- Miner runtime parity: mining-routine sell search uses lib.gt.live.search
             with default buyPriceMin (-1.0), i.e. no relative-price floor. -->
        <set_value name="$diagBuyPriceMinForSearch" exact="$activeBuyPriceMin"/>
        <do_if value="$orderId == 'GalaxyMiner'">
          <set_value name="$diagBuyPriceMinForSearch" exact="-1.0"/>
        </do_if>

        <do_if value="$orderId == 'GalaxyTraderMK1'">
          <!-- Sec3 already resolved mk1DiagPriceNorm; keep activeBuyPriceMin in sync for sec8 scans. -->
          <set_value name="$activeBuyPriceMin" exact="$mk1DiagPriceNorm"/>
          <set_value name="$activeSellPriceMax" exact="0 - $mk1DiagPriceNorm"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Search Pipeline', $Status = 'INFO', $Detail = 'MK1 export buyer scan (order slider ' + $mk1DiagPriceOffset + '/200, buy min ' + ($mk1DiagPriceNorm * 100) + '%, norm ' + $mk1DiagPriceNorm + ')']"/>
        </do_if>
        <do_else>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Search Pipeline', $Status = 'INFO', $Detail = $pipelineState + ' (Sell max: ' + ($activeSellPriceMax * 100) + '%, Buy min: ' + ($activeBuyPriceMin * 100) + '%)']"/>
        </do_else>
        <set_value name="$diagOfferScanModeDetail" exact="'tradepartner + per-ship offeramount (mirrors lib.gt.live.search.xml; pair gates mirror trade_found validation)'"/>
        <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4BuildStorageOnlyMode">
          <set_value name="$diagOfferScanModeDetail" exact="'BS buyer-targeted + player buy-offer supplemental (mirrors lib.gt.live.search MK4 completion pass; post-filter buyer=buildstorage + coverage)'"/>
        </do_if>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Offer Scan Mode', $Status = 'INFO', $Detail = $diagOfferScanModeDetail]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Sectors In Range', $Status = 'INFO', $Detail = '' + $searchSectors.count + ' sectors (distance=' + $diagSearchDistance + ')']"/>
        <do_if value="$orderId == 'GalaxyMiner'">
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Miner Offer Ware Scope', $Status = if $diagMinerOfferWares.count gt 0 then 'PASS' else 'WARN', $Detail = $diagMinerOfferWaresDetail]"/>
        </do_if>

        <!-- Collect sell offers and buy offers from all sectors -->
        <set_value name="$allSellOffers" exact="[]"/>
        <set_value name="$allBuyOffers" exact="[]"/>
        <set_value name="$sectorBreakdown" exact="[]"/>
        <!-- Player-report fix: track miner buyer offers BEFORE policy filter (= what the miner
             AI's find_buy_offer would actually return) separately from offers that survive the
             primary-stations / overflow / playerStationsOnly policy gate. Otherwise a 0 verdict
             collapses two very different states ("no buyers exist" vs "buyers exist but your
             config rejects them all") and players whose miners happily sell see a misleading
             "no offers found" report. Raw = engine returned + minable + ship can carry.
             Policy = also matches the configured primary/overflow gates. -->
        <set_value name="$diagMinerRawBuyOffers" exact="[]"/>
        <set_value name="$diagMinerRawBuyOfferCount" exact="0"/>
        <!-- MK3 'Ignore Player Pricing': count buyer offers excluded because the buyer is a
             player-owned station (mirrors lib.gt.live.search excludePlayerBuyers + tradematch
             rejection). Surfaced in the Sec3 settings table below for observability. -->
        <set_value name="$diagIppPlayerBuyersRejected" exact="0"/>
        <set_value name="$diagIppPlayerSuppliersAdded" exact="0"/>

        <do_if value="$orderId != 'GalaxyTraderMK1'">
        <do_all exact="$searchSectors.count" counter="$si">
          <set_value name="$searchSec" exact="$searchSectors.{$si}"/>

          <!-- For miners we only diagnose sell opportunities (buyers), not buy opportunities. -->
          <do_if value="$orderId == 'GalaxyMiner'">
            <set_value name="$secSellOffers" exact="[]"/>
          </do_if>
          <do_elseif value="$ignoreTradeRules">
            <find_sell_offer tradepartner="$ship" space="$searchSec" result="$secSellOffers" multiple="true">
              <match_seller tradesknownto="$ship.owner">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_seller>
              <amount min="1"/>
              <relativeprice max="$activeSellPriceMax" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_sell_offer>
          </do_elseif>
          <do_elseif value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
            <find_sell_offer tradepartner="$ship" space="$searchSec" result="$secSellOffers" multiple="true">
              <match_seller tradesknownto="$ship.owner">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_seller>
              <amount min="1"/>
              <relativeprice max="$activeSellPriceMax" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_sell_offer>
          </do_elseif>
          <!-- MK4 runtime always passes includePlayerSellOffers=true (lib.gt.live.search).
               The generic NPC-only scan (negateownerfilter) omits player suppliers, so
               buyFromPlayer-only orders evaluate only doomed NPCÃ—player pairs and hit the
               pair-eval cap with mk4_supplier_policy_blocked before any player supplier
               is considered. -->
          <do_elseif value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2')">
            <find_sell_offer tradepartner="$ship" space="$searchSec" result="$secSellOffers" multiple="true">
              <match_seller tradesknownto="$ship.owner">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_seller>
              <amount min="1"/>
              <relativeprice max="$activeSellPriceMax" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_sell_offer>
          </do_elseif>
          <do_else>
            <find_sell_offer tradepartner="$ship" space="$searchSec" result="$secSellOffers" multiple="true">
              <match_seller tradesknownto="$ship.owner" owner="faction.player" negateownerfilter="true">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_seller>
              <amount min="1"/>
              <relativeprice max="$activeSellPriceMax" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_sell_offer>
          </do_else>
          <set_value name="$secSellCount" exact="0"/>
          <do_if value="$secSellOffers? and $secSellOffers.count?">
            <do_all exact="$secSellOffers.count" counter="$soi">
              <set_value name="$diagSellOffer" exact="$secSellOffers.{$soi}"/>
              <!-- MK4 supplier-policy prefilter at collection (mirrors pair gate + live.search
                   ownerFilter semantics). Prevents eval-cap starvation when one supplier side
                   is disabled â€” e.g. buyFromPlayer-only with hundreds of NPC sell offers. -->
              <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
                <set_value name="$diagSellOwner" exact="if $diagSellOffer.owner? then $diagSellOffer.owner else null"/>
                <set_value name="$diagSellIsPlayer" exact="false"/>
                <do_if value="$diagSellOwner? and $diagSellOwner.exists and @$diagSellOwner.isplayerowned">
                  <set_value name="$diagSellIsPlayer" exact="true"/>
                </do_if>
                <do_if value="($diagSellIsPlayer and not $diagMk4AllowPlayerSuppliers) or (not $diagSellIsPlayer and not $diagMk4AllowAiSuppliers)">
                  <continue/>
                </do_if>
                <do_if value="$diagMk4BuildStorageOnlyMode and $diagSellOwner? and @$diagSellOwner.isclass.buildstorage">
                  <continue/>
                </do_if>
              </do_if>
              <!-- Cargo hold filter at collection (mirrors lib.gt.cache.search + trade_found validation). -->
              <do_if value="$diagSellOffer.ware? and $ship.cargo.{$diagSellOffer.ware}.max le 0">
                <continue/>
              </do_if>
              <append_to_list name="$allSellOffers" exact="$diagSellOffer"/>
              <set_value name="$secSellCount" operation="add"/>
            </do_all>
          </do_if>

          <!-- â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•
               MK3 'Ignore Player Pricing' supplemental supplier scan (mirrors
               lib.gt.live.search.xml lines 196-282): collect player-owned sell
               offers WITHOUT the relativeprice cap so the simulation can see
               player suppliers above the configured price band â€” matching what
               the runtime ship will actually consider. Dedupe against the main
               scan to avoid double-counting any player offers that already
               passed the price cap. Only runs for MK3 with IPP enabled. -->
          <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
            <find_sell_offer space="$searchSec" result="$secPlayerSellOffers" multiple="true">
              <match_seller tradesknownto="$ship.owner" owner="faction.player">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
              </match_seller>
              <amount min="1"/>
            </find_sell_offer>
            <do_if value="$secPlayerSellOffers? and $secPlayerSellOffers.count gt 0">
              <set_value name="$secPlayerSellAdded" exact="0"/>
              <do_all exact="$secPlayerSellOffers.count" counter="$bpsoi">
                <set_value name="$bpsOffer" exact="$secPlayerSellOffers.{$bpsoi}"/>
                <do_if value="not $bpsOffer? or not $bpsOffer.owner? or not @$bpsOffer.owner.isplayerowned">
                  <continue/>
                </do_if>
                <set_value name="$bpsDuplicate" exact="false"/>
                <do_all exact="$allSellOffers.count" counter="$bpsdi">
                  <do_if value="$allSellOffers.{$bpsdi} == $bpsOffer">
                    <set_value name="$bpsDuplicate" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="$bpsDuplicate">
                  <continue/>
                </do_if>
                <do_if value="$bpsOffer.ware? and $ship.cargo.{$bpsOffer.ware}.max le 0">
                  <continue/>
                </do_if>
                <append_to_list name="$allSellOffers" exact="$bpsOffer"/>
                <set_value name="$secPlayerSellAdded" operation="add"/>
                <set_value name="$secSellCount" operation="add"/>
                <set_value name="$diagIppPlayerSuppliersAdded" operation="add"/>
              </do_all>
            </do_if>
          </do_if>

          <!-- Find buy offers (ship sells to station).
               MINER PATH: Mirror the actual miner AI signature from
               order.mining.routine.gt.xml:824 - `tradepartner` + (optional) `wares` + `space`.
               The miner AI applies NO match_buyer / offeramount / relativeprice clauses; per-ship
               offeramount is resolved at trade-execution time, dock relation is checked lazily,
               and "tradesknownto" is irrelevant for owned ships. The previous diag scan replicated
               the trader-side over-filter pattern, which silently dropped offers whose per-ship
               offeramount was 0 right now (reservation-saturated) or whose buyer relation was
               below `dock` from the strict trader perspective - producing false-negative
               "0 buyer offers" reports while the miner AI was happily selling.
               WARES filter: use the ship's configured warebasket (matches AI `$warebasket`) when
               present; otherwise omit entirely so non-minable wares are filtered post-loop. -->
          <do_if value="$orderId == 'GalaxyMiner'">
            <do_if value="$ship.warebasket? and $ship.warebasket.list? and $ship.warebasket.list.count gt 0">
              <find_buy_offer wares="$ship.warebasket.list" tradepartner="$ship" space="$searchSec" result="$secBuyOffers" multiple="true"/>
            </do_if>
            <do_else>
              <find_buy_offer tradepartner="$ship" space="$searchSec" result="$secBuyOffers" multiple="true"/>
            </do_else>
          </do_if>
          <do_elseif value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4BuildStorageOnlyMode">
            <create_list name="$secBuyOffers"/>
            <set_value name="$diagBsoSeenBuyers" exact="table[]"/>
            <find_station name="$diagBsoStations" space="$searchSec" checkoperational="true" multiple="true"/>
            <do_if value="$diagBsoStations? and $diagBsoStations.count gt 0">
              <do_all exact="$diagBsoStations.count" counter="$diagBsoSti">
                <set_value name="$diagBsoStation" exact="$diagBsoStations.{$diagBsoSti}"/>
                <do_if value="not $diagBsoStation? or not @$diagBsoStation.exists or not @$diagBsoStation.isplayerowned">
                  <continue/>
                </do_if>
                <set_value name="$diagBsoBuyer" exact="null"/>
                <do_if value="$diagBsoStation.buildstorage? and $diagBsoStation.buildstorage.exists">
                  <set_value name="$diagBsoBuyer" exact="$diagBsoStation.buildstorage"/>
                </do_if>
                <do_elseif value="@$diagBsoStation.isclass.buildstorage">
                  <set_value name="$diagBsoBuyer" exact="$diagBsoStation"/>
                </do_elseif>
                <do_if value="not $diagBsoBuyer? or not @$diagBsoBuyer.exists or $diagBsoSeenBuyers.{$diagBsoBuyer}?">
                  <continue/>
                </do_if>
                <set_value name="$diagBsoSeenBuyers.{$diagBsoBuyer}" exact="true"/>
                <do_if value="$ignoreTradeRules">
                  <find_buy_offer buyer="$diagBsoBuyer" tradepartner="$ship" space="$searchSec" result="$diagBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <amount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$diagBsoBuyer" tradepartner="$ship" space="$searchSec" result="$diagBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1" tradepartner="$ship"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$diagBsoOffers? and $diagBsoOffers.count gt 0">
                  <do_all exact="$diagBsoOffers.count" counter="$diagBsoBi">
                    <append_to_list name="$secBuyOffers" exact="$diagBsoOffers.{$diagBsoBi}"/>
                  </do_all>
                </do_if>
              </do_all>
            </do_if>
            <find_object name="$diagBsoObjects" class="class.buildstorage" space="$searchSec" owner="faction.player" multiple="true"/>
            <do_if value="$diagBsoObjects? and $diagBsoObjects.count gt 0">
              <do_all exact="$diagBsoObjects.count" counter="$diagBsoOi">
                <set_value name="$diagBsoBuyer" exact="$diagBsoObjects.{$diagBsoOi}"/>
                <do_if value="not $diagBsoBuyer? or not @$diagBsoBuyer.exists or $diagBsoSeenBuyers.{$diagBsoBuyer}?">
                  <continue/>
                </do_if>
                <set_value name="$diagBsoSeenBuyers.{$diagBsoBuyer}" exact="true"/>
                <do_if value="$ignoreTradeRules">
                  <find_buy_offer buyer="$diagBsoBuyer" tradepartner="$ship" space="$searchSec" result="$diagBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <amount min="1"/>
                  </find_buy_offer>
                </do_if>
                <do_else>
                  <find_buy_offer buyer="$diagBsoBuyer" tradepartner="$ship" space="$searchSec" result="$diagBsoOffers" multiple="true" excludeempty="false" usereservations="false">
                    <offeramount min="1" tradepartner="$ship"/>
                  </find_buy_offer>
                </do_else>
                <do_if value="$diagBsoOffers? and $diagBsoOffers.count gt 0">
                  <do_all exact="$diagBsoOffers.count" counter="$diagBsoBi">
                    <append_to_list name="$secBuyOffers" exact="$diagBsoOffers.{$diagBsoBi}"/>
                  </do_all>
                </do_if>
              </do_all>
            </do_if>
            <!-- Supplemental: generic player buy-offer scan (mirrors lib.gt.live.search completion pass).
                 BS construction demand often appears only on offers with owner=station, buyer=buildstorage;
                 buyer-targeted queries can return 0 even when this path finds offers. -->
            <find_buy_offer tradepartner="$ship" space="$searchSec" result="$diagBsoSuppTp" multiple="true">
              <match_buyer tradesknownto="$ship.owner">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1" tradepartner="$ship"/>
              <relativeprice min="$activeBuyPriceMin" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_buy_offer>
            <!-- Mirrors lib.gt.live.search MK4 completion pass (player buy offers, amount min=1). -->
            <find_buy_offer space="$searchSec" result="$diagBsoSuppPlayer" multiple="true">
              <match_buyer tradesknownto="$ship.owner" owner="faction.player">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <amount min="1"/>
            </find_buy_offer>
            <do_if value="$diagBsoSuppPlayer? and $diagBsoSuppPlayer.count gt 0">
              <do_if value="not $diagBsoSuppTp?">
                <create_list name="$diagBsoSuppTp"/>
              </do_if>
              <do_all exact="$diagBsoSuppPlayer.count" counter="$diagBsoSi">
                <append_to_list name="$diagBsoSuppTp" exact="$diagBsoSuppPlayer.{$diagBsoSi}"/>
              </do_all>
            </do_if>
            <do_if value="$ignoreTradeRules">
              <find_buy_offer space="$searchSec" result="$diagBsoSuppIgnore" multiple="true">
                <match_buyer tradesknownto="$ship.owner" owner="faction.player">
                  <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <amount min="1"/>
              </find_buy_offer>
              <do_if value="$diagBsoSuppIgnore? and $diagBsoSuppIgnore.count gt 0">
                <do_if value="not $diagBsoSuppTp?">
                  <create_list name="$diagBsoSuppTp"/>
                </do_if>
                <do_all exact="$diagBsoSuppIgnore.count" counter="$diagBsoSi">
                  <append_to_list name="$diagBsoSuppTp" exact="$diagBsoSuppIgnore.{$diagBsoSi}"/>
                </do_all>
              </do_if>
            </do_if>
            <do_if value="$diagBsoSuppTp? and $diagBsoSuppTp.count gt 0">
              <set_value name="$diagBsoSeenOffers" exact="table[]"/>
              <do_all exact="$secBuyOffers.count" counter="$diagBsoSi">
                <set_value name="$diagBsoSeenOffers.{$secBuyOffers.{$diagBsoSi}}" exact="true"/>
              </do_all>
              <do_all exact="$diagBsoSuppTp.count" counter="$diagBsoSi">
                <set_value name="$diagBsoSuppOffer" exact="$diagBsoSuppTp.{$diagBsoSi}"/>
                <do_if value="$diagBsoSeenOffers.{$diagBsoSuppOffer}?">
                  <continue/>
                </do_if>
                <set_value name="$diagBsoSeenOffers.{$diagBsoSuppOffer}" exact="true"/>
                <append_to_list name="$secBuyOffers" exact="$diagBsoSuppOffer"/>
              </do_all>
            </do_if>
          </do_elseif>
          <do_elseif value="$ignoreTradeRules">
            <find_buy_offer tradepartner="$ship" space="$searchSec" result="$secBuyOffers" multiple="true">
              <match_buyer tradesknownto="$ship.owner">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1" tradepartner="$ship"/>
              <relativeprice min="$activeBuyPriceMin" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_buy_offer>
            <find_buy_offer space="$searchSec" result="$diagIgnoreRulesBuyOffers" multiple="true">
              <match_buyer tradesknownto="$ship.owner" owner="faction.player">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <amount min="1"/>
            </find_buy_offer>
            <do_if value="$diagIgnoreRulesBuyOffers? and $diagIgnoreRulesBuyOffers.count gt 0">
              <do_if value="not $secBuyOffers?">
                <create_list name="$secBuyOffers"/>
              </do_if>
              <do_all exact="$diagIgnoreRulesBuyOffers.count" counter="$diri">
                <append_to_list name="$secBuyOffers" exact="$diagIgnoreRulesBuyOffers.{$diri}"/>
              </do_all>
            </do_if>
          </do_elseif>
          <do_else>
            <find_buy_offer tradepartner="$ship" space="$searchSec" result="$secBuyOffers" multiple="true">
              <match_buyer tradesknownto="$ship.owner">
                <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
              </match_buyer>
              <offeramount min="1" tradepartner="$ship"/>
              <relativeprice min="$activeBuyPriceMin" tradepartner="if $ship.isplayerowned then $ship else null"/>
            </find_buy_offer>
          </do_else>
          <set_value name="$secBuyCount" exact="0"/>
          <set_value name="$secRawBuyCount" exact="0"/>
          <do_if value="$secBuyOffers? and $secBuyOffers.count?">
            <do_all exact="$secBuyOffers.count" counter="$boi">
              <set_value name="$boffer" exact="$secBuyOffers.{$boi}"/>
              <set_value name="$diagOfferAllowed" exact="true"/>
              <set_value name="$diagOfferStation" exact="if $boffer? and $boffer.owner? then $boffer.owner else null"/>
              <set_value name="$diagOfferWare" exact="if $boffer? and $boffer.ware? then $boffer.ware else null"/>
              <!-- MK3 'Ignore Player Pricing': exclude player-owned buyers entirely so the
                   diag mirrors the runtime (live.search.excludePlayerBuyers + tradematch
                   rejection). MK3-only; counts skips for the settings observability row. -->
              <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' and $diagOfferStation? and $diagOfferStation.exists and @$diagOfferStation.isplayerowned">
                <set_value name="$diagIppPlayerBuyersRejected" operation="add"/>
                <continue/>
              </do_if>
              <!-- Miner relevance filter: drop non-minable wares and wares the ship can't carry.
                   Now that the engine pre-filter is no longer applying a wares restriction (when
                   no warebasket is configured), this post-filter prevents non-minable buy offers
                   from polluting the miner buyer count. Applies to ALL miners, not only the
                   $diagMinerAnyBuyerMode branch. -->
              <do_if value="$orderId == 'GalaxyMiner' and (not $diagOfferWare? or not $diagOfferWare.hastag.minable or $ship.cargo.{$diagOfferWare}.max le 0)">
                <set_value name="$diagOfferAllowed" exact="false"/>
              </do_if>
              <!-- Track RAW miner buyer count (after engine + minable/cargo-fit filter, BEFORE
                   primary-stations / overflow / playerStationsOnly policy gate). -->
              <do_if value="$diagOfferAllowed and $orderId == 'GalaxyMiner'">
                <set_value name="$secRawBuyCount" operation="add"/>
                <set_value name="$diagMinerRawBuyOfferCount" operation="add"/>
                <append_to_list name="$diagMinerRawBuyOffers" exact="$boffer"/>
              </do_if>
              <set_value name="$diagOfferIsPrimary" exact="false"/>
              <do_if value="$orderId == 'GalaxyMiner' and $diagOfferStation? and $diagOfferStation.exists and $diagMinerPrimaryStations.count gt 0">
                <do_all exact="$diagMinerPrimaryStations.count" counter="$dpsi">
                  <do_if value="$diagMinerPrimaryStations.{$dpsi}? and $diagMinerPrimaryStations.{$dpsi}.exists and $diagMinerPrimaryStations.{$dpsi} == $diagOfferStation">
                    <set_value name="$diagOfferIsPrimary" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$orderId == 'GalaxyMiner' and not $diagMinerAnyBuyerMode">
                <set_value name="$diagOfferRejectReason" exact="''"/>
                <set_value name="$diagOfferWareOverflowMode" exact="false"/>
                <do_if value="$diagOfferWare? and $diagMinerWareHasPrimaryCapacity? and $diagMinerWareHasPrimaryCapacity.{$diagOfferWare}?">
                  <do_if value="not $diagMinerWareHasPrimaryCapacity.{$diagOfferWare}">
                    <set_value name="$diagOfferWareOverflowMode" exact="true"/>
                  </do_if>
                </do_if>
                <do_if value="$diagMinerPlayerStationsOnly and (not $diagOfferStation? or not $diagOfferStation.exists or not $diagOfferStation.isplayerowned)">
                  <set_value name="$diagOfferAllowed" exact="false"/>
                  <set_value name="$diagOfferRejectReason" exact="'playerStationsOnly'"/>
                  <set_value name="$diagMinerRejectPlayerOnly" operation="add"/>
                </do_if>
                <!-- Primary delivery path (ware still has capacity at a primary station). -->
                <do_if value="$diagOfferAllowed and not $diagOfferWareOverflowMode">
                  <do_if value="not $diagOfferIsPrimary">
                    <set_value name="$diagOfferAllowed" exact="false"/>
                    <set_value name="$diagOfferRejectReason" exact="'not in primary target stations'"/>
                    <set_value name="$diagMinerRejectNotPrimary" operation="add"/>
                  </do_if>
                  <do_else>
                    <set_value name="$diagPrimaryTargetAmount" exact="$diagOfferStation.cargo.{$diagOfferWare}.target"/>
                    <do_if value="$diagPrimaryTargetAmount le 0">
                      <set_value name="$diagOfferAllowed" exact="false"/>
                      <set_value name="$diagOfferRejectReason" exact="'primary station target=0 for ware'"/>
                      <set_value name="$diagMinerRejectTargetZero" operation="add"/>
                    </do_if>
                    <do_else>
                      <set_value name="$diagPrimaryPhysical" exact="$diagOfferStation.cargo.{$diagOfferWare}.count"/>
                      <set_value name="$diagPrimaryStoragePercent" exact="($diagPrimaryPhysical * 100) / [$diagPrimaryTargetAmount, 1].max"/>
                      <do_if value="$diagPrimaryStoragePercent ge $diagMinerOverflowThreshold">
                        <set_value name="$diagOfferAllowed" exact="false"/>
                        <set_value name="$diagOfferRejectReason" exact="'overflow threshold (' + $diagPrimaryPhysical + '/' + $diagPrimaryTargetAmount + ' = ' + $diagPrimaryStoragePercent + '% ge ' + $diagMinerOverflowThreshold + '%)'"/>
                        <set_value name="$diagMinerRejectOverflow" operation="add"/>
                      </do_if>
                    </do_else>
                  </do_else>
                </do_if>
                <!-- Overflow sell path (mirrors order.mining.routine.gt sellwares policy). -->
                <do_elseif value="$diagOfferAllowed and $diagOfferWareOverflowMode">
                  <do_if value="not $diagMinerAllowOverflowSellToOthers">
                    <set_value name="$diagOfferAllowed" exact="false"/>
                    <set_value name="$diagOfferRejectReason" exact="'overflow at primary but sell-to-others disabled'"/>
                    <set_value name="$diagMinerRejectOverflowNoFallback" operation="add"/>
                  </do_if>
                  <do_elseif value="$diagMinerPlayerStationsOnly">
                    <do_if value="not $diagOfferStation? or not $diagOfferStation.exists or not $diagOfferStation.isplayerowned or $diagOfferIsPrimary">
                      <set_value name="$diagOfferAllowed" exact="false"/>
                      <set_value name="$diagOfferRejectReason" exact="'overflow player-only requires non-primary player station'"/>
                      <set_value name="$diagMinerRejectOverflowPrimaryExcluded" operation="add"/>
                    </do_if>
                  </do_elseif>
                </do_elseif>
                <do_if value="not $diagOfferAllowed and $diagOfferRejectReason != '' and $diagMinerPolicyRejectedSamples.count lt 12">
                  <set_value name="$diagRejectStationText" exact="if $diagOfferStation? and $diagOfferStation.exists then ($diagOfferStation.idcode + ' ' + $diagOfferStation.knownname) else 'UNKNOWN'"/>
                  <set_value name="$diagRejectWareText" exact="if $diagOfferWare? then $diagOfferWare.name else '?'"/>
                  <set_value name="$diagRejectSampleStatus" exact="'FAIL'"/>
                  <do_if value="$diagOfferRejectReason == 'not in primary target stations'">
                    <set_value name="$diagRejectSampleStatus" exact="'INFO'"/>
                  </do_if>
                  <append_to_list name="$diagMinerPolicyRejectedSamples" exact="table[$Check = $diagRejectWareText, $Status = $diagRejectSampleStatus, $Detail = $diagRejectStationText, $Col6 = $diagOfferRejectReason]"/>
                  <remove_value name="$diagRejectSampleStatus"/>
                </do_if>
              </do_if>
              <do_if value="not $diagOfferAllowed">
                <continue/>
              </do_if>
              <do_if value="$ignoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$boffer.owner}?">
                <continue/>
              </do_if>
              <!-- MK4 runtime only pairs player-owned customers; omit foreign buyers from the scan set. -->
              <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4CustomerMustBePlayer">
                <set_value name="$diagMk4PlayerBuyerOk" exact="false"/>
                <set_value name="$diagMk4BuyerObj" exact="if $boffer? and $boffer.buyer? and @$boffer.buyer.exists then @$boffer.buyer else $diagOfferStation"/>
                <do_if value="$diagMk4BuyerObj? and @$diagMk4BuyerObj.exists">
                  <do_if value="@$diagMk4BuyerObj.isplayerowned">
                    <set_value name="$diagMk4PlayerBuyerOk" exact="true"/>
                  </do_if>
                  <do_elseif value="$diagMk4BuyerObj.isclass.buildstorage and $diagMk4BuyerObj.base? and @$diagMk4BuyerObj.base.isplayerowned">
                    <set_value name="$diagMk4PlayerBuyerOk" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="not $diagMk4PlayerBuyerOk">
                  <continue/>
                </do_if>
              </do_if>
              <!-- MK4 build-storage-only: collect in-scope build storage buy offers only. -->
              <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4BuildStorageOnlyMode">
                <set_value name="$diagBuyCustomer" exact="$diagOfferStation"/>
                <do_if value="$boffer? and $boffer.buyer? and @$boffer.buyer.exists">
                  <set_value name="$diagBuyCustomer" exact="@$boffer.buyer"/>
                </do_if>
                <do_if value="not $diagBuyCustomer? or not @$diagBuyCustomer.isclass.buildstorage">
                  <continue/>
                </do_if>
                <set_value name="$diagBsoInScope" exact="false"/>
                <set_value name="$diagBsoDist" exact="if $diagMk4HomeSector? and $diagMk4HomeSector.exists and $diagBuyCustomer.sector? then $diagMk4HomeSector.gatedistance.{$diagBuyCustomer.sector} else -1"/>
                <do_if value="$diagBsoDist ge 0 and ($maxSell le 0 or $diagBsoDist le $maxSell)">
                  <set_value name="$diagBsoInScope" exact="true"/>
                </do_if>
                <do_if value="not $diagBsoInScope">
                  <continue/>
                </do_if>
              </do_if>
              <do_if value="$boffer.ware? and $ship.cargo.{$boffer.ware}.max le 0">
                <continue/>
              </do_if>
              <append_to_list name="$allBuyOffers" exact="$boffer"/>
              <set_value name="$secBuyCount" operation="add"/>
            </do_all>
          </do_if>

          <!-- Store per-sector breakdown with structured columns.
               Miner path only resolves buyer offers (a miner sells ore to stations; the
               vanilla "Sell Offer" search is hard-skipped above at $secSellOffers=[]).
               Surfacing a `0 | N | N` Sell|Buy|Total triplet for miners reads as "the diag
               found no sell opportunities" even though the buyer side is populated, so we
               render miner per-sector rows as 3-col text ("X buyer offer(s)") and let the
               Lua row-spanner take over. -->
          <do_if value="$orderId == 'GalaxyMiner'">
            <!-- Show BOTH raw and policy-passing per-sector counts so a 0/N gap is visible.
                 raw = engine-returned + minable + ship can carry (what the miner AI sees).
                 pol = also matches your primary-stations / overflow / playerStationsOnly config. -->
            <set_value name="$sectorOfferStatus" exact="if $secRawBuyCount gt 0 then 'INFO' else 'WARN'"/>
            <set_value name="$secMinerDetail" exact="'' + $secBuyCount + ' / ' + $secRawBuyCount + ' buyer offer' + (if $secRawBuyCount == 1 then '' else 's') + ' (policy / raw)'"/>
            <append_to_list name="$sectorBreakdown" exact="table[$Check = $searchSec.knownname, $Status = $sectorOfferStatus, $Detail = $secMinerDetail]"/>
          </do_if>
          <do_else>
            <set_value name="$sectorOfferStatus" exact="if ($secSellCount + $secBuyCount) gt 0 then 'INFO' else 'WARN'"/>
            <append_to_list name="$sectorBreakdown" exact="table[$Check = $searchSec.knownname, $Status = $sectorOfferStatus, $Detail = '' + $secSellCount, $Col4 = '' + $secBuyCount, $Col5 = '' + ($secSellCount + $secBuyCount), $Col6 = '']"/>
          </do_else>
        </do_all>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK1'">
          <!-- MK1 export model: home-station sell offers + buyers in maxsell range only.
               The generic sector-wide sellÃ—buy scan is the wrong model and scales O(sellsÃ—buys). -->
          <set_value name="$mk1DiagHome" exact="null"/>
          <do_if value="$gtOrder? and $gtOrder.$homeStation? and $gtOrder.$homeStation.exists">
            <set_value name="$mk1DiagHome" exact="$gtOrder.$homeStation"/>
          </do_if>
          <set_value name="$mk1DiagEffectiveWares" exact="[]"/>
          <set_value name="$mk1DiagCandidateWares" exact="[]"/>
          <set_value name="$mk1DiagPreGateCount" exact="0"/>
          <set_value name="$mk1DiagMinSellStorage" exact="0"/>
          <do_if value="$gtOrder? and $gtOrder.$minsellstorage?">
            <set_value name="$mk1DiagMinSellStorage" exact="[0, [$gtOrder.$minsellstorage, 100].min].max"/>
          </do_if>
          <do_if value="$mk1DiagHome? and $mk1DiagHome.exists">
            <do_if value="$wareBasket.count gt 0">
              <set_value name="$mk1DiagCandidateWares" exact="$wareBasket"/>
            </do_if>
            <do_else>
              <set_value name="$mk1DiagProducts" exact="$mk1DiagHome.products.list"/>
              <set_value name="$mk1DiagTradewares" exact="$mk1DiagHome.tradewares.list"/>
              <do_all exact="$mk1DiagProducts.count" counter="$m1pi">
                <append_to_list name="$mk1DiagCandidateWares" exact="$mk1DiagProducts.{$m1pi}"/>
              </do_all>
              <do_all exact="$mk1DiagTradewares.count" counter="$m1ti">
                <set_value name="$m1tw" exact="$mk1DiagTradewares.{$m1ti}"/>
                <set_value name="$m1dup" exact="false"/>
                <do_all exact="$mk1DiagCandidateWares.count" counter="$m1di">
                  <do_if value="$mk1DiagCandidateWares.{$m1di} == $m1tw">
                    <set_value name="$m1dup" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                <do_if value="not $m1dup">
                  <append_to_list name="$mk1DiagCandidateWares" exact="$m1tw"/>
                </do_if>
              </do_all>
            </do_else>
            <do_all exact="$mk1DiagCandidateWares.count" counter="$m1fi">
              <set_value name="$m1fw" exact="$mk1DiagCandidateWares.{$m1fi}"/>
              <do_if value="$ship.cargo.{$m1fw}.max le 0">
                <continue/>
              </do_if>
              <do_if value="$m1fw.isprocessed">
                <continue/>
              </do_if>
              <do_if value="not $allowIllegal and $m1fw.illegal">
                <continue/>
              </do_if>
              <append_to_list name="$mk1DiagEffectiveWares" exact="$m1fw"/>
            </do_all>
            <set_value name="$mk1DiagPreGateCount" exact="$mk1DiagEffectiveWares.count"/>
            <do_if value="$mk1DiagMinSellStorage gt 0 and $mk1DiagEffectiveWares.count gt 0">
              <create_list name="$mk1DiagGatedWares"/>
              <do_all exact="$mk1DiagEffectiveWares.count" counter="$m1gi">
                <set_value name="$m1gw" exact="$mk1DiagEffectiveWares.{$m1gi}"/>
                <set_value name="$m1gMax" exact="$mk1DiagHome.cargo.{$m1gw}.target"/>
                <do_if value="$m1gMax le 0">
                  <continue/>
                </do_if>
                <set_value name="$m1gCount" exact="$mk1DiagHome.cargo.{$m1gw}.count"/>
                <get_ware_reservation object="$mk1DiagHome" ware="$m1gw" type="buy" virtual="false" result="$m1gResTotal"/>
                <get_ware_reservation object="$mk1DiagHome" ware="$m1gw" type="buy" reserver="$ship" virtual="false" result="$m1gResSelf"/>
                <set_value name="$m1gResOther" exact="[($m1gResTotal - $m1gResSelf), 0].max"/>
                <set_value name="$m1gEffCount" exact="[($m1gCount - $m1gResOther), 0].max"/>
                <set_value name="$m1gFillPct" exact="($m1gEffCount * 100) / $m1gMax"/>
                <do_if value="$m1gFillPct ge $mk1DiagMinSellStorage">
                  <append_to_list name="$mk1DiagGatedWares" exact="$m1gw"/>
                </do_if>
              </do_all>
              <set_value name="$mk1DiagEffectiveWares" exact="$mk1DiagGatedWares"/>
            </do_if>
            <set_value name="$mk1SellStorageGateSig" exact="'min=' + $mk1DiagMinSellStorage + '|pre=' + $mk1DiagPreGateCount + '|post=' + $mk1DiagEffectiveWares.count"/>
            <set_value name="$mk1WareSnapshotSig" exact="'effective=' + $mk1DiagEffectiveWares.count + ' candidates=' + $mk1DiagCandidateWares.count"/>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
              <param name="ship" value="$ship"/>
            </run_actions>
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_BuildTradeSectorLists" result="$mk1DiagSectorLists">
              <param name="ship" value="$ship"/>
              <param name="homeSector" value="$mk1DiagHome.sector"/>
              <param name="maxDistance" value="$maxSell"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <set_value name="$mk1DiagSellSpaces" exact="if $mk1DiagSectorLists.$SellSpaces? then $mk1DiagSectorLists.$SellSpaces else []"/>
            <set_value name="$mk1DiagRawBuyOfferCount" exact="0"/>
            <set_value name="$mk1DiagRawBuyOffers" exact="[]"/>
            <set_value name="$mk1DiagEngineBuyOfferCount" exact="0"/>
            <set_value name="$mk1DiagEngineBuyOfferSet" exact="table[]"/>
            <set_value name="$mk1DiagPlayerBuyersExcluded" exact="0"/>
            <set_value name="$mk1DiagRejectOfferAmount" exact="0"/>
            <set_value name="$mk1DiagRejectEngineMatch" exact="0"/>
            <set_value name="$mk1DiagSeenRawOffers" exact="table[]"/>
            <set_value name="$mk1DiagSeenPolicyOffers" exact="table[]"/>
            <do_all exact="$mk1DiagEffectiveWares.count" counter="$m1ewi">
              <set_value name="$m1ew" exact="$mk1DiagEffectiveWares.{$m1ewi}"/>
              <do_if value="$ignoreTradeRules">
                <find_sell_offer seller="$mk1DiagHome" wares="$m1ew" result="$m1StationSellOffer"/>
              </do_if>
              <do_else>
                <find_sell_offer seller="$mk1DiagHome" wares="$m1ew" tradepartner="$ship" result="$m1StationSellOffer"/>
              </do_else>
              <do_if value="$m1StationSellOffer? and $m1StationSellOffer.available and $m1StationSellOffer.amount gt 0">
                <append_to_list name="$allSellOffers" exact="$m1StationSellOffer"/>
              </do_if>
            </do_all>
            <do_all exact="$mk1DiagSellSpaces.count" counter="$m1si">
              <set_value name="$m1SearchSec" exact="$mk1DiagSellSpaces.{$m1si}"/>
              <set_value name="$m1SecRawCount" exact="0"/>
              <set_value name="$m1SecPassCount" exact="0"/>
              <!-- Per-ware scan mirrors lib.gt.live.search.xml (not a batched wares list). -->
              <do_all exact="$mk1DiagEffectiveWares.count" counter="$m1ewi">
                <set_value name="$m1ew" exact="$mk1DiagEffectiveWares.{$m1ewi}"/>
                <!-- RAW: tradepartner + ware + space (engine visibility without offeramount/relativeprice). -->
                <find_buy_offer wares="$m1ew" tradepartner="$ship" space="$m1SearchSec" result="$m1RawBuyOffers" multiple="true"/>
                <do_if value="$m1RawBuyOffers? and $m1RawBuyOffers.count?">
                  <do_all exact="$m1RawBuyOffers.count" counter="$m1ri">
                    <set_value name="$m1rOffer" exact="$m1RawBuyOffers.{$m1ri}"/>
                    <do_if value="not $m1rOffer? or not $m1rOffer.exists or not $m1rOffer.ware? or $m1rOffer.ware != $m1ew">
                      <continue/>
                    </do_if>
                    <do_if value="not $allowIllegal and $m1ew.illegal">
                      <continue/>
                    </do_if>
                    <do_if value="$mk1DiagSeenRawOffers.{$m1rOffer}?">
                      <continue/>
                    </do_if>
                    <set_value name="$mk1DiagSeenRawOffers.{$m1rOffer}" exact="true"/>
                    <set_value name="$m1SecRawCount" operation="add"/>
                    <set_value name="$mk1DiagRawBuyOfferCount" operation="add"/>
                    <append_to_list name="$mk1DiagRawBuyOffers" exact="$m1rOffer"/>
                    <do_if value="$m1rOffer.owner? and $m1rOffer.owner.isplayerowned">
                      <set_value name="$mk1DiagPlayerBuyersExcluded" operation="add"/>
                    </do_if>
                  </do_all>
                </do_if>
                <!-- ENGINE: match_buyer + relativeprice + amount. Per-ship offeramount is checked below
                     (mirrors miner diag fix - offeramount in find_buy_offer pre-filter hides visible buyers). -->
                <find_buy_offer wares="$m1ew" tradepartner="$ship" space="$m1SearchSec" result="$m1FoundBuyOffers" multiple="true">
                  <match_buyer tradesknownto="$ship.owner">
                    <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                    <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                  </match_buyer>
                  <amount min="1"/>
                  <relativeprice min="$activeBuyPriceMin" tradepartner="if $ship.isplayerowned then $ship else null"/>
                </find_buy_offer>
                <do_if value="$ignoreTradeRules">
                  <find_buy_offer wares="$m1ew" space="$m1SearchSec" result="$m1IgnoreRulesBuyOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner" owner="faction.player">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <amount min="1"/>
                  </find_buy_offer>
                  <do_if value="not $m1FoundBuyOffers?">
                    <create_list name="$m1FoundBuyOffers"/>
                  </do_if>
                  <do_if value="$m1IgnoreRulesBuyOffers? and $m1IgnoreRulesBuyOffers.count gt 0">
                    <do_all exact="$m1IgnoreRulesBuyOffers.count" counter="$m1iri">
                      <append_to_list name="$m1FoundBuyOffers" exact="$m1IgnoreRulesBuyOffers.{$m1iri}"/>
                    </do_all>
                  </do_if>
                </do_if>
                <do_if value="$m1FoundBuyOffers? and $m1FoundBuyOffers.count?">
                  <do_all exact="$m1FoundBuyOffers.count" counter="$m1boi">
                    <set_value name="$m1bOffer" exact="$m1FoundBuyOffers.{$m1boi}"/>
                    <do_if value="not $m1bOffer? or not $m1bOffer.exists or not $m1bOffer.ware? or $m1bOffer.ware != $m1ew">
                      <continue/>
                    </do_if>
                    <do_if value="not $mk1DiagEngineBuyOfferSet.{$m1bOffer}?">
                      <set_value name="$mk1DiagEngineBuyOfferSet.{$m1bOffer}" exact="true"/>
                      <set_value name="$mk1DiagEngineBuyOfferCount" operation="add"/>
                    </do_if>
                    <do_if value="$m1bOffer.owner.isplayerowned">
                      <continue/>
                    </do_if>
                    <set_value name="$m1PerShipAmt" exact="if $m1bOffer.offeramount.{$ship}? then $m1bOffer.offeramount.{$ship} else 0"/>
                    <do_if value="$m1PerShipAmt lt 1">
                      <set_value name="$mk1DiagRejectOfferAmount" operation="add"/>
                      <continue/>
                    </do_if>
                    <do_if value="not $ignoreTradeRules and not $m1bOffer.cantradewith.{$mk1DiagHome}">
                      <continue/>
                    </do_if>
                    <do_if value="$mk1DiagSeenPolicyOffers.{$m1bOffer}?">
                      <continue/>
                    </do_if>
                    <set_value name="$mk1DiagSeenPolicyOffers.{$m1bOffer}" exact="true"/>
                    <append_to_list name="$allBuyOffers" exact="$m1bOffer"/>
                    <set_value name="$m1SecPassCount" operation="add"/>
                  </do_all>
                </do_if>
              </do_all>
              <append_to_list name="$sectorBreakdown" exact="table[$Check = $m1SearchSec.knownname, $Status = if $m1SecPassCount gt 0 then 'INFO' else 'WARN', $Detail = '' + $m1SecPassCount + ' / ' + $m1SecRawCount + ' buyer offer' + (if $m1SecRawCount == 1 then '' else 's') + ' (policy / raw)']"/>
            </do_all>
            <set_value name="$mk1DiagRejectEngineMatch" exact="0"/>
            <do_all exact="$mk1DiagRawBuyOffers.count" counter="$m1rbi">
              <set_value name="$m1rbo" exact="$mk1DiagRawBuyOffers.{$m1rbi}"/>
              <do_if value="$m1rbo.owner? and $m1rbo.owner.isplayerowned">
                <continue/>
              </do_if>
              <do_if value="not $mk1DiagEngineBuyOfferSet.{$m1rbo}?">
                <set_value name="$mk1DiagRejectEngineMatch" operation="add"/>
              </do_if>
            </do_all>
            <set_value name="$mk1DiagPolicyBreakdown" exact="'engine_match_or_relativeprice=' + $mk1DiagRejectEngineMatch + ', per_ship_offeramount=' + $mk1DiagRejectOfferAmount + ', player_buyers=' + $mk1DiagPlayerBuyersExcluded"/>
            <set_value name="$mk1SellOfferSnapshotSig" exact="'stationSellOffers=' + $allSellOffers.count + ' buyerOffers=' + $allBuyOffers.count"/>
          </do_if>
          <do_else>
            <set_value name="$mk1SellStorageGateSig" exact="'no home station'"/>
            <set_value name="$mk1WareSnapshotSig" exact="'no home station'"/>
            <set_value name="$mk1SellOfferSnapshotSig" exact="'no home station'"/>
            <set_value name="$mk1DiagEffectiveWares" exact="[]"/>
            <set_value name="$mk1DiagSellSpaces" exact="[]"/>
            <set_value name="$mk1DiagRawBuyOfferCount" exact="0"/>
            <set_value name="$mk1DiagRawBuyOffers" exact="[]"/>
            <set_value name="$mk1DiagEngineBuyOfferCount" exact="0"/>
            <set_value name="$mk1DiagEngineBuyOfferSet" exact="table[]"/>
            <set_value name="$mk1DiagPlayerBuyersExcluded" exact="0"/>
            <set_value name="$mk1DiagRejectOfferAmount" exact="0"/>
            <set_value name="$mk1DiagRejectEngineMatch" exact="0"/>
            <set_value name="$mk1DiagPolicyBreakdown" exact="''"/>
          </do_else>
        </do_elseif>

        <!-- Miners never search Sell Offers (see $secSellOffers=[] hard-skip above), so the
             "Total Sell Offers: 0" row is misleading for the miner workflow ("the miner is
             selling to stations, why does the diag say no sell offers?"). Suppress it for
             miners and re-label the buyer-side row with the player-facing semantics. -->
        <do_if value="$orderId == 'GalaxyMiner'">
          <!-- Two rows for miners: raw discovery (what the miner AI's find_buy_offer would see)
               vs policy-passing (subset that matches the player's primary/overflow config).
               When raw > 0 but policy = 0, the player's miner is finding buyers but the
               diag's policy gate is rejecting them all - strongly indicates a config mismatch
               (e.g. primary-station list missing the actual sell target, overflow disabled
               with primaries full, playerStationsOnly excluding NPC buyers, etc.). -->
          <set_value name="$diagMinerRawStatus" exact="if $diagMinerRawBuyOfferCount gt 0 then 'PASS' else 'FAIL'"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Buyer Offers In Range (raw)', $Status = $diagMinerRawStatus, $Detail = '' + $diagMinerRawBuyOfferCount + ' buyer offer' + (if $diagMinerRawBuyOfferCount == 1 then '' else 's') + ' (engine + minable + cargo-fit; what the miner AI sees)']"/>
          <set_value name="$diagMinerPolicyStatus" exact="if $allBuyOffers.count gt 0 then 'PASS' else (if $diagMinerRawBuyOfferCount gt 0 then 'WARN' else 'FAIL')"/>
          <set_value name="$diagMinerPolicyDetail" exact="'' + $allBuyOffers.count + ' of ' + $diagMinerRawBuyOfferCount + ' buyer offer' + (if $diagMinerRawBuyOfferCount == 1 then '' else 's') + ' pass primary/overflow policy'"/>
          <do_if value="$diagMinerRawBuyOfferCount gt 0 and $allBuyOffers.count == 0">
            <set_value name="$diagMinerPolicyDetail" exact="$diagMinerPolicyDetail + ' - buyers exist but your config rejects them all'"/>
            <set_value name="$diagMinerPolicyBreakdown" exact="'not-primary=' + $diagMinerRejectNotPrimary + ', overflow-fill=' + $diagMinerRejectOverflow + ', player-only=' + $diagMinerRejectPlayerOnly + ', target-zero=' + $diagMinerRejectTargetZero + ', overflow-no-fallback=' + $diagMinerRejectOverflowNoFallback + ', overflow-primary-excluded=' + $diagMinerRejectOverflowPrimaryExcluded"/>
          </do_if>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Stations Buying Your Ore (policy-passing)', $Status = $diagMinerPolicyStatus, $Detail = $diagMinerPolicyDetail]"/>
          <do_if value="$diagMinerPolicyBreakdown != ''">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Policy Rejection Breakdown', $Status = 'WARN', $Detail = $diagMinerPolicyBreakdown]"/>
          </do_if>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK1'">
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Home Station Sell Offers', $Status = if $allSellOffers.count gt 0 then 'PASS' else 'FAIL', $Detail = '' + $allSellOffers.count + ' export offer' + (if $allSellOffers.count == 1 then '' else 's') + ' (after export gate: ' + (if $mk1DiagEffectiveWares? then $mk1DiagEffectiveWares.count else 0) + ' wares)']"/>
          <set_value name="$mk1DiagRawStatus" exact="if $mk1DiagRawBuyOfferCount gt 0 then 'PASS' else 'FAIL'"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Buyer Offers In Range (raw)', $Status = $mk1DiagRawStatus, $Detail = '' + $mk1DiagRawBuyOfferCount + ' buyer offer' + (if $mk1DiagRawBuyOfferCount == 1 then '' else 's') + ' (tradepartner + ware + space; what exists in range)']"/>
          <set_value name="$mk1DiagEngineStatus" exact="if $mk1DiagEngineBuyOfferCount gt 0 then 'PASS' else (if $mk1DiagRawBuyOfferCount gt 0 then 'WARN' else 'FAIL')"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Buyer Offers (engine match)', $Status = $mk1DiagEngineStatus, $Detail = '' + $mk1DiagEngineBuyOfferCount + ' buyer offer' + (if $mk1DiagEngineBuyOfferCount == 1 then '' else 's') + ' (match_buyer + relativeprice min ' + $mk1DiagPriceNorm + ', amount min 1)']"/>
          <set_value name="$mk1DiagPolicyStatus" exact="if $allBuyOffers.count gt 0 then 'PASS' else (if $mk1DiagRawBuyOfferCount gt 0 then 'WARN' else 'FAIL')"/>
          <set_value name="$mk1DiagPolicyDetail" exact="'' + $allBuyOffers.count + ' NPC buyer offer' + (if $allBuyOffers.count == 1 then '' else 's') + ' pass runtime export policy (npc_only + per-ship offeramount ge 1)'"/>
          <do_if value="$mk1DiagRawBuyOfferCount gt 0 and $allBuyOffers.count == 0">
            <set_value name="$mk1DiagPolicyDetail" exact="$mk1DiagPolicyDetail + ' - buyers visible in raw scan but runtime pre-filters reject them all'"/>
          </do_if>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Buyer Offers In Range (NPC policy)', $Status = $mk1DiagPolicyStatus, $Detail = $mk1DiagPolicyDetail]"/>
          <do_if value="$mk1DiagPolicyBreakdown? and $mk1DiagPolicyBreakdown != ''">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK1 Policy Rejection Breakdown', $Status = 'WARN', $Detail = $mk1DiagPolicyBreakdown]"/>
          </do_if>
          <do_if value="$mk1DiagPlayerBuyersExcluded gt 0">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Player Buyers Excluded (MK1 npc_only)', $Status = 'INFO', $Detail = '' + $mk1DiagPlayerBuyersExcluded + ' player buy offer' + (if $mk1DiagPlayerBuyersExcluded == 1 then '' else 's') + ' found but MK1 export only sells to NPC stations']"/>
          </do_if>
        </do_elseif>
        <do_else>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Total Sell Offers', $Status = 'INFO', $Detail = '' + $allSellOffers.count]"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Total Buy Offers', $Status = 'INFO', $Detail = '' + $allBuyOffers.count]"/>
          <!-- MK3 IPP impact summary on the supplier/buyer pools (only when meaningful). -->
          <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'IPP: Player Suppliers Added', $Status = if $diagIppPlayerSuppliersAdded gt 0 then 'INFO' else 'WARN', $Detail = '' + $diagIppPlayerSuppliersAdded + ' player sell offer' + (if $diagIppPlayerSuppliersAdded == 1 then '' else 's') + ' admitted past relativeprice cap']"/>
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'IPP: Player Buyers Excluded', $Status = 'INFO', $Detail = '' + $diagIppPlayerBuyersRejected + ' player buy offer' + (if $diagIppPlayerBuyersRejected == 1 then '' else 's') + ' filtered (sell only to NPCs)']"/>
          </do_if>
        </do_else>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = '--- Per Sector ---', $Status = 'INFO', $Detail = '']"/>
        <do_all exact="$sectorBreakdown.count" counter="$sbi">
          <append_to_list name="$sec8.$Rows" exact="$sectorBreakdown.{$sbi}"/>
        </do_all>

        <!-- NOTE: No cooperative yield in MD scripts (<wait> is AI-script only) -->
        <!-- This diagnostic runs synchronously - acceptable for manual trigger -->

        <!-- ======================================================== -->
        <!-- SECTION 8b: Pair Evaluation                              -->
        <!-- Generic traders: capped pair scan; MK1/MK2 use dedicated paths. -->
        <!-- ======================================================== -->
        <set_value name="$pairCount" exact="0"/>
        <set_value name="$passCount" exact="0"/>
        <set_value name="$rejectNoProfit" exact="0"/>
        <set_value name="$rejectBelowThreshold" exact="0"/>
        <set_value name="$rejectBelowROI" exact="0"/>
        <set_value name="$rejectDocking" exact="0"/>
        <set_value name="$rejectDockSize" exact="0"/>
        <set_value name="$rejectNotOperational" exact="0"/>
        <set_value name="$rejectZeroAmount" exact="0"/>
        <set_value name="$rejectCantAfford" exact="0"/>
        <set_value name="$rejectDistance" exact="0"/>
        <set_value name="$rejectPathBlocked" exact="0"/>
        <set_value name="$rejectIllegal" exact="0"/>
        <set_value name="$rejectBlacklist" exact="0"/>
        <set_value name="$rejectMK1Supply" exact="0"/>
        <set_value name="$rejectBuildStorage" exact="0"/>
        <set_value name="$rejectCarrierAux" exact="0"/>
        <set_value name="$rejectMK4ForeignCustomer" exact="0"/>
        <set_value name="$rejectMK4SupplierPolicy" exact="0"/>
        <set_value name="$rejectMK4TradeRules" exact="0"/>
        <set_value name="$rejectMK4ServeHomeScope" exact="0"/>
        <set_value name="$rejectMK4BuildStorageOnly" exact="0"/>
        <set_value name="$rejectMK4DemandReservedExhausted" exact="0"/>
        <set_value name="$rejectSameStation" exact="0"/>
        <set_value name="$rejectWareBasket" exact="0"/>
        <set_value name="$rejectCargoType" exact="0"/>
        <set_value name="$rejectCargoUtil" exact="0"/>
        <set_value name="$rejectOfferInvalid" exact="0"/>
        <set_value name="$rejectProfitRecalc" exact="0"/>
        <set_value name="$rejectSupplierClamp" exact="0"/>
        <set_value name="$rejectMK3Faction" exact="0"/>
        <set_value name="$rejectRouteIllegal" exact="0"/>
        <set_value name="$diagRuntimePassPairs" exact="[]"/>
        <set_value name="$diagRuntimeDispatchCount" exact="0"/>
        <set_value name="$diagRuntimeBestDispatch" exact="'none'"/>
        <set_value name="$diagRuntimeBatchPreview" exact="'none'"/>
        <set_value name="$diagRouteFilterActive" exact="$allowIllegal and $enforceRouteIllegalLegality"/>
        <set_value name="$diagUseSelectionSort" exact="false"/>
        <do_if value="$orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
          <set_value name="$diagUseSelectionSort" exact="true"/>
        </do_if>
        <set_value name="$diagPriorityMultPct" exact="125"/>
        <do_if value="$gtOrder? and $gtOrder.$priorityscoremultiplier?">
          <set_value name="$diagPriorityMultPct" exact="[$gtOrder.$priorityscoremultiplier, 125].max"/>
        </do_if>
        <do_if value="$diagPriorityMultPct gt 300">
          <set_value name="$diagPriorityMultPct" exact="300"/>
        </do_if>
        <!-- Performance caps for generic trader pair scan (MK1 uses dedicated export path above). -->
        <set_value name="$diagPairEvalCap" exact="1000"/>
        <set_value name="$diagPairDisplayCap" exact="80"/>
        <set_value name="$diagPathfindBudget" exact="160"/>
        <set_value name="$diagHitEvalCap" exact="false"/>
        <set_value name="$pairDetails" exact="[]"/>
        <!-- Diagnostics show EVERY evaluated pair with its verdict + reason (FAIL rows are the whole
             point of a ship-specific search-state diagnosis), instead of silently dropping
             trade-rule / policy rejections. -->

        <set_value name="$bestDiagProfit" exact="0"/>
        <set_value name="$bestDiagPairDesc" exact="'none'"/>
        <set_value name="$bestIppPairScore" exact="0"/>
        <set_value name="$bestIppPairDesc" exact="'none'"/>
        <set_value name="$bestNpcSupplierPairScore" exact="0"/>
        <set_value name="$bestNpcSupplierPairDesc" exact="'none'"/>
        <set_value name="$diagIsolatedForCargoFilter" exact="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?"/>

        <!-- Blacklist group for distance checks -->
        <do_if value="not $blacklistgroup?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>

        <do_if value="$orderId == 'GalaxyTraderMK1'">
          <!-- MK1 pair evaluation: home-station sell offer Ã— buyer offer per ware (mirrors runtime tradematch sell phase). -->
          <set_value name="$mk1RowCap" exact="40"/>
          <set_value name="$mk1SellByWare" exact="table[]"/>
          <do_all exact="$allSellOffers.count" counter="$m1soi">
            <set_value name="$m1so" exact="$allSellOffers.{$m1soi}"/>
            <do_if value="$m1so.exists and $m1so.ware?">
              <set_value name="$m1sw" exact="$m1so.ware"/>
              <do_if value="not $mk1SellByWare.{$m1sw}?">
                <set_value name="$mk1SellByWare.{$m1sw}" exact="$m1so"/>
              </do_if>
            </do_if>
          </do_all>
          <do_all exact="$mk1DiagRawBuyOffers.count" counter="$m1boi">
            <do_if value="$diagHitEvalCap">
              <break/>
            </do_if>
            <set_value name="$m1BuyOffer" exact="$mk1DiagRawBuyOffers.{$m1boi}"/>
            <do_if value="not $m1BuyOffer.exists or not $m1BuyOffer.ware?">
              <continue/>
            </do_if>
            <set_value name="$m1Ware" exact="$m1BuyOffer.ware"/>
            <do_if value="not $mk1SellByWare.{$m1Ware}?">
              <continue/>
            </do_if>
            <set_value name="$sellOffer" exact="$mk1SellByWare.{$m1Ware}"/>
            <set_value name="$buyOffer" exact="$m1BuyOffer"/>
            <set_value name="$pairCount" operation="add"/>
            <do_if value="$pairCount ge $diagPairEvalCap">
              <set_value name="$diagHitEvalCap" exact="true"/>
              <break/>
            </do_if>
            <set_value name="$pairVerdict" exact="'PASS'"/>
            <set_value name="$pairReason" exact="''"/>
            <set_value name="$pairScore" exact="0"/>
            <set_value name="$pairHasDistances" exact="false"/>
            <set_value name="$buyStation" exact="$mk1DiagHome"/>
            <set_value name="$sellStation" exact="if $m1BuyOffer.buyer? and @$m1BuyOffer.buyer.exists then @$m1BuyOffer.buyer else @$m1BuyOffer.owner"/>
            <!-- Build storages have no location in their bare name; label with base station + sector. -->
            <set_value name="$sellStationLabel" exact="if $sellStation? and $sellStation.exists then @$sellStation.knownname else 'customer'"/>
            <do_if value="$sellStation? and $sellStation.exists and $sellStation.isclass.buildstorage">
              <set_value name="$sellLabelBase" exact="if $sellStation.base? then @$sellStation.base else null"/>
              <set_value name="$sellLabelSec" exact="if $sellLabelBase? and $sellLabelBase.sector? then @$sellLabelBase.sector else (if $sellStation.sector? then @$sellStation.sector else null)"/>
              <set_value name="$sellStationLabel" exact="@$sellStation.knownname + ' @ ' + (if $sellLabelBase? and $sellLabelBase.knownname? then @$sellLabelBase.knownname else 'base') + ' (' + (if $sellLabelSec? and $sellLabelSec.knownname? then @$sellLabelSec.knownname else 'unknown sector') + ')'"/>
            </do_if>
            <do_if value="$m1BuyOffer.owner? and $m1BuyOffer.owner.isplayerowned">
              <set_value name="$pairVerdict" exact="'FAIL'"/>
              <set_value name="$pairReason" exact="'mk1_npc_only_player_buyer'"/>
            </do_if>
            <do_elseif value="not $mk1DiagEngineBuyOfferSet.{$m1BuyOffer}?">
              <set_value name="$pairVerdict" exact="'FAIL'"/>
              <set_value name="$pairReason" exact="'engine_match_buyer_or_relativeprice'"/>
            </do_elseif>
            <do_else>
              <set_value name="$m1PairPerShipAmt" exact="if $m1BuyOffer.offeramount.{$ship}? then $m1BuyOffer.offeramount.{$ship} else 0"/>
              <do_if value="$m1PairPerShipAmt lt 1">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'per_ship_offeramount_zero'"/>
              </do_if>
            </do_else>
            <set_value name="$buyPrice" exact="$sellOffer.unitprice"/>
            <set_value name="$sellPrice" exact="$m1BuyOffer.unitprice"/>
            <set_value name="$sellOfferAmount" exact="if $sellOffer.offeramount.{$ship}? then $sellOffer.offeramount.{$ship} else $sellOffer.amount"/>
            <set_value name="$buyOfferAmount" exact="if $m1BuyOffer.offeramount.{$ship}? then $m1BuyOffer.offeramount.{$ship} else $m1BuyOffer.amount"/>
            <do_if value="$buyOfferAmount le 0 and $sellStation? and $sellStation.exists">
              <set_value name="$buyOfferAmount" exact="[0, $sellStation.cargo.{$m1Ware}.target - $sellStation.cargo.{$m1Ware}.count].max"/>
            </do_if>
            <set_value name="$profitPerUnit" exact="$sellPrice - $buyPrice"/>
            <set_value name="$volumePerUnit" exact="if $m1Ware.volume gt 0 then $m1Ware.volume else 1"/>
            <set_value name="$maxByCargo" exact="$cargoFree / $volumePerUnit"/>
            <set_value name="$tradeAmount" exact="[$maxByCargo, $sellOfferAmount, $buyOfferAmount].min"/>
            <set_value name="$totalProfit" exact="$profitPerUnit * $tradeAmount"/>
            <set_value name="$roi" exact="if $buyPrice gt 0 then (($profitPerUnit * 100) / $buyPrice) else 0"/>
            <do_if value="$pairVerdict == 'PASS' and not $allowIllegal and $m1Ware.illegal">
              <set_value name="$pairVerdict" exact="'FAIL'"/>
              <set_value name="$pairReason" exact="'ware_illegal'"/>
              <set_value name="$rejectIllegal" operation="add"/>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and not $buyStation.isoperational">
              <set_value name="$pairVerdict" exact="'FAIL'"/>
              <set_value name="$pairReason" exact="'buy_station_not_operational'"/>
              <set_value name="$rejectNotOperational" operation="add"/>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and not $sellStation.isoperational">
              <set_value name="$pairVerdict" exact="'FAIL'"/>
              <set_value name="$pairReason" exact="'sell_station_not_operational'"/>
              <set_value name="$rejectNotOperational" operation="add"/>
            </do_if>
            <do_if value="$pairVerdict == 'PASS'">
              <run_actions ref="md.GT_Libraries_General.GT_CanDockForTrade" result="$m1DiagBuyDock">
                <param name="station" value="$buyStation"/>
                <param name="ship" value="$ship"/>
                <param name="allowStorageDock" value="false"/>
              </run_actions>
              <do_if value="not $m1DiagBuyDock.$CanDock">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'docking_denied_home'"/>
                <set_value name="$rejectDocking" operation="add"/>
              </do_if>
              <do_else>
                <run_actions ref="md.GT_Libraries_General.GT_CanDockForTrade" result="$m1DiagSellDock">
                  <param name="station" value="$sellStation"/>
                  <param name="ship" value="$ship"/>
                  <param name="allowStorageDock" value="false"/>
                </run_actions>
                <do_if value="not $m1DiagSellDock.$CanDock">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'docking_denied_buyer'"/>
                  <set_value name="$rejectDocking" operation="add"/>
                </do_if>
              </do_else>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and $tradeAmount le 0">
              <set_value name="$pairVerdict" exact="'FAIL'"/>
              <set_value name="$pairReason" exact="'zero_amount'"/>
              <set_value name="$rejectZeroAmount" operation="add"/>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and not $ignoreTradeRules">
              <do_if value="not $m1BuyOffer.cantradewith.{$buyStation}">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'trade_rules_buyer_blocks_home'"/>
              </do_if>
              <do_elseif value="not $sellOffer.cantradewith.{$sellStation}">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'trade_rules_home_blocks_buyer'"/>
              </do_elseif>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and $maxSell gt 0">
              <set_value name="$m1Dist" exact="$mk1DiagHome.sector.gatedistance.{$sellStation.sector}"/>
              <do_if value="$m1Dist lt 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'path_blocked (no gate route to buyer)'"/>
                <set_value name="$rejectPathBlocked" operation="add"/>
              </do_if>
              <do_elseif value="$m1Dist gt $maxSell">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'distance_exceeded (' + $m1Dist + ' gt ' + $maxSell + ')'"/>
                <set_value name="$rejectDistance" operation="add"/>
              </do_elseif>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and $diagRouteFilterActive and @$m1Ware.illegal gt 0 and $diagPathfindBudget gt 0">
              <set_value name="$diagPathfindBudget" operation="subtract" exact="1"/>
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CheckRouteLegality" result="$m1RouteLegality">
                <param name="ship" value="$ship"/>
                <param name="homeSector" value="$mk1DiagHome.sector"/>
                <param name="buySector" value="$mk1DiagHome.sector"/>
                <param name="sellSector" value="$sellStation.sector"/>
                <param name="ware" value="$m1Ware"/>
                <param name="allowIllegal" value="$allowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="startSector" value="$ship.sector"/>
              </run_actions>
              <do_if value="not $m1RouteLegality.$IsLegal">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'route_illegal'"/>
                <set_value name="$rejectRouteIllegal" operation="add"/>
              </do_if>
            </do_if>
            <do_if value="$pairVerdict == 'PASS'">
              <set_value name="$m1DistScore" exact="if $maxSell gt 0 then $mk1DiagHome.sector.gatedistance.{$sellStation.sector} else 0"/>
              <do_if value="$m1DistScore lt 0">
                <set_value name="$m1DistScore" exact="0"/>
              </do_if>
              <set_value name="$scoreDistanceFactor" exact="1.0 + ($m1DistScore * ($distancePenalty / 50.0))"/>
              <set_value name="$scoreGrossCr" exact="($totalProfit / 1Cr)i"/>
              <set_value name="$pairScore" exact="$scoreGrossCr / $scoreDistanceFactor"/>
              <set_value name="$pairHasDistances" exact="true"/>
              <set_value name="$passCount" operation="add"/>
              <set_value name="$drPassDesc" exact="$m1Ware.name + ': ' + $buyStation.knownname + ' -> ' + $sellStationLabel + ' (Score ' + ($pairScore)i + ', ' + ($totalProfit / 100) + ' Cr)'"/>
              <append_to_list name="$diagRuntimePassPairs" exact="table[$Score = $pairScore, $SellOffer = $sellOffer, $BuyOffer = $buyOffer, $Ware = $m1Ware, $Desc = $drPassDesc]"/>
              <do_if value="$pairScore gt $bestDiagProfit">
                <set_value name="$bestDiagProfit" exact="$pairScore"/>
                <set_value name="$bestDiagPairDesc" exact="$m1Ware.name + ': ' + $buyStation.knownname + ' -> ' + $sellStationLabel + ' (' + ($totalProfit / 100) + ' Cr, ROI ' + $roi + '%, Score ' + ($pairScore)i + ')'"/>
              </do_if>
            </do_if>
            <do_if value="$pairDetails.count lt $mk1RowCap">
              <set_value name="$pdRoute" exact="$buyStation.knownname + ' -> ' + $sellStationLabel"/>
              <set_value name="$pdProfitStr" exact="($totalProfit / 100) + 'Cr &#183; ROI ' + $roi + '%'"/>
              <set_value name="$pdScoreStr" exact="if $pairHasDistances then ('' + ($pairScore)i) else '-'"/>
              <append_to_list name="$pairDetails" exact="table[$Check = $m1Ware.name, $Status = $pairVerdict, $Detail = $pdRoute, $Col4 = $pdProfitStr, $Col5 = $pdScoreStr, $Col6 = $pairReason, $SortKey = $pairScore]"/>
            </do_if>
          </do_all>
        </do_if>
        <do_else>
        <!-- Sell-driven pairing (mirrors lib.gt.tradematch.xml outer sell loop). -->
        <do_all exact="$allSellOffers.count" counter="$soi">
          <do_if value="$diagHitEvalCap">
            <break/>
          </do_if>
          <set_value name="$sellOffer" exact="$allSellOffers.{$soi}"/>
          <do_if value="not $sellOffer.exists or not $sellOffer.ware?">
            <continue/>
          </do_if>
          <set_value name="$pairWare" exact="$sellOffer.ware"/>
          <!-- Manual ware-basket gate parity (check on supplier ware). -->
          <do_if value="$diagPairWareFilterActive">
            <set_value name="$diagPairWareAllowed" exact="false"/>
            <do_all exact="$diagPairWareFilter.count" counter="$fwi">
              <do_if value="$diagPairWareFilter.{$fwi} == $pairWare">
                <set_value name="$diagPairWareAllowed" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $diagPairWareAllowed and ($orderId == 'GalaxyTraderMK3' or $orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $priorityWares.count gt 0">
              <do_all exact="$priorityWares.count" counter="$pwi">
                <do_if value="$priorityWares.{$pwi} == $pairWare">
                  <set_value name="$diagPairWareAllowed" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $diagPairWareAllowed">
              <set_value name="$rejectWareBasket" operation="add"/>
              <continue/>
            </do_if>
          </do_if>

          <do_all exact="$allBuyOffers.count" counter="$boi">
            <do_if value="$diagHitEvalCap">
              <break/>
            </do_if>
            <set_value name="$buyOffer" exact="$allBuyOffers.{$boi}"/>
            <do_if value="not $buyOffer.exists or not $buyOffer.ware?">
              <continue/>
            </do_if>
            <do_if value="$buyOffer.ware != $pairWare">
              <continue/>
            </do_if>

            <!-- Skip same station -->
            <do_if value="$buyOffer.owner == $sellOffer.owner">
              <set_value name="$rejectSameStation" operation="add"/>
              <continue/>
            </do_if>

            <set_value name="$pairCount" operation="add"/>
            <do_if value="$pairCount ge $diagPairEvalCap">
              <set_value name="$diagHitEvalCap" exact="true"/>
              <break/>
            </do_if>

            <!-- === Evaluate this pair === -->
            <set_value name="$pairVerdict" exact="'PASS'"/>
            <set_value name="$pairReason" exact="''"/>
            <!-- Score state (mirrors lib.gt.tradematch.xml score formula). Initialised per pair
                 because locals leak across iterations otherwise; pairs that bail before the
                 path checks fire keep $pairScore = 0 and naturally sort to the bottom of the
                 score-ranked Pair Details table. -->
            <set_value name="$pairScore" exact="0"/>
            <set_value name="$pairSelectionScore" exact="0"/>
            <set_value name="$pdSortKey" exact="0"/>
            <set_value name="$pairHasDistances" exact="false"/>
            <set_value name="$buyDist" exact="-1"/>
            <set_value name="$sellDist" exact="-1"/>
            <set_value name="$homeToSellDist" exact="-1"/>
            <set_value name="$scoreDistance" exact="-1"/>

            <set_value name="$buyStation" exact="null"/>
            <do_if value="$sellOffer?">
              <do_if value="$sellOffer.seller? and @$sellOffer.seller.exists">
                <set_value name="$buyStation" exact="@$sellOffer.seller"/>
              </do_if>
              <do_elseif value="$sellOffer.owner?">
                <set_value name="$buyStation" exact="@$sellOffer.owner"/>
              </do_elseif>
            </do_if>
            <set_value name="$sellStation" exact="null"/>
            <do_if value="$buyOffer?">
              <do_if value="$buyOffer.buyer? and @$buyOffer.buyer.exists">
                <set_value name="$sellStation" exact="@$buyOffer.buyer"/>
              </do_if>
              <do_elseif value="$buyOffer.owner?">
                <set_value name="$sellStation" exact="@$buyOffer.owner"/>
              </do_elseif>
            </do_if>
            <!-- Build storages have no location in their bare name; label with base station + sector. -->
            <set_value name="$sellStationLabel" exact="if $sellStation? and $sellStation.exists then @$sellStation.knownname else 'customer'"/>
            <do_if value="$sellStation? and $sellStation.exists and $sellStation.isclass.buildstorage">
              <set_value name="$sellLabelBase" exact="if $sellStation.base? then @$sellStation.base else null"/>
              <set_value name="$sellLabelSec" exact="if $sellLabelBase? and $sellLabelBase.sector? then @$sellLabelBase.sector else (if $sellStation.sector? then @$sellStation.sector else null)"/>
              <set_value name="$sellStationLabel" exact="@$sellStation.knownname + ' @ ' + (if $sellLabelBase? and $sellLabelBase.knownname? then @$sellLabelBase.knownname else 'base') + ' (' + (if $sellLabelSec? and $sellLabelSec.knownname? then @$sellLabelSec.knownname else 'unknown sector') + ')'"/>
            </do_if>
            <set_value name="$buyPrice" exact="$sellOffer.unitprice"/>
            <set_value name="$sellPrice" exact="$buyOffer.unitprice"/>
            <!-- $mk4SupplierIsPlayerOwned is a generic 'supplier-station-is-player' flag despite
                 the legacy name; reused by MK3 IPP logic below. Renaming would touch unrelated
                 MK4 paths, so the name is preserved for diff-clarity. -->
            <set_value name="$mk4SupplierIsPlayerOwned" exact="false"/>
            <do_if value="$buyStation? and $buyStation.exists and $buyStation.isplayerowned">
              <set_value name="$mk4SupplierIsPlayerOwned" exact="true"/>
            </do_if>
            <!-- MK3 'Ignore Player Pricing' pair flag: when ON and the supplier is player-owned,
                 the runtime (lib.gt.tradematch.xml playerSupplierFreeProduction) treats the buy
                 cost as zero, bypasses no_profit/below_profit_threshold/below_roi gates and
                 reports gross sell income as profit. Mirror that here so the diag verdict and
                 reported numbers match what the runtime ship will actually do. -->
            <set_value name="$diagPairPlayerFreeSupplier" exact="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' and $mk4SupplierIsPlayerOwned"/>
            <set_value name="$sellOfferAmount" exact="$sellOffer.offeramount.{$ship}"/>
            <do_if value="$sellOfferAmount == null">
              <set_value name="$sellOfferAmount" exact="$sellOffer.amount"/>
            </do_if>
            <do_if value="$sellOfferAmount le 0 and $sellOffer.amount? and $sellOffer.amount gt 0">
              <set_value name="$sellOfferAmount" exact="$sellOffer.amount"/>
            </do_if>
            <do_if value="$sellOfferAmount == null">
              <set_value name="$sellOfferAmount" exact="0"/>
            </do_if>
            <set_value name="$buyOfferAmount" exact="$buyOffer.offeramount.{$ship}"/>
            <do_if value="$buyOfferAmount == null">
              <set_value name="$buyOfferAmount" exact="$buyOffer.amount"/>
            </do_if>
            <do_if value="$buyOfferAmount le 0 and $buyOffer.amount? and $buyOffer.amount gt 0">
              <set_value name="$buyOfferAmount" exact="$buyOffer.amount"/>
            </do_if>
            <do_if value="$buyOfferAmount == null">
              <set_value name="$buyOfferAmount" exact="0"/>
            </do_if>
            <!-- Mirror runtime supply fallback:
                 if offeramount is unresolved/zero, derive destination demand from target-count. -->
            <do_if value="$buyOfferAmount le 0 and $buyOffer? and $sellStation? and $sellStation.exists and $pairWare?">
              <set_value name="$diagBuyOfferDemandFallback" exact="[0, $sellStation.cargo.{$pairWare}.target - $sellStation.cargo.{$pairWare}.count].max"/>
              <do_if value="$diagBuyOfferDemandFallback gt 0">
                <set_value name="$buyOfferAmount" exact="$diagBuyOfferDemandFallback"/>
              </do_if>
            </do_if>

            <!-- Compute financials upfront so ALL pairs have price/profit/ROI info -->
            <set_value name="$profitPerUnit" exact="$sellPrice - $buyPrice"/>
            <set_value name="$volumePerUnit" exact="$pairWare.volume"/>
            <do_if value="$volumePerUnit le 0">
              <set_value name="$volumePerUnit" exact="1"/>
            </do_if>
            <set_value name="$maxByCargo" exact="$cargoFree / $volumePerUnit"/>
            <!-- IPP player-supplier: mirror runtime MinPlayerMoney skip (order.trade.galaxytrader.xml). -->
            <set_value name="$maxByMoney" exact="999999"/>
            <do_if value="not $diagPairPlayerFreeSupplier and $buyPrice gt 0">
              <set_value name="$maxByMoney" exact="$playerMoney / $buyPrice"/>
            </do_if>
            <set_value name="$maxByOffer" exact="[$sellOfferAmount, $buyOfferAmount].min"/>
            <set_value name="$maxAmount" exact="[$maxByCargo, $maxByMoney, $maxByOffer].min"/>
            <do_if value="$maxAmount lt 0">
              <set_value name="$maxAmount" exact="0"/>
            </do_if>
            <set_value name="$totalProfit" exact="$profitPerUnit * $maxAmount"/>
            <set_value name="$roi" exact="0"/>
            <do_if value="$buyPrice gt 0">
              <set_value name="$roi" exact="($profitPerUnit * 100) / $buyPrice"/>
            </do_if>
            <!-- IPP override: replicate lib.gt.tradematch.xml ($playerFreeSupplier branch).
                 unitProfit becomes the full sell price, totalProfit becomes gross sell income,
                 ROI is conceptually infinite (player paid 0) - rendered as 'n/a (free)' below. -->
            <do_if value="$diagPairPlayerFreeSupplier">
              <set_value name="$profitPerUnit" exact="$sellPrice"/>
              <set_value name="$totalProfit" exact="$sellPrice * $maxAmount"/>
              <set_value name="$roi" exact="0"/>
            </do_if>

            <!-- MK4 policy checks (must mirror runtime behavior):
                 1) customer must be player-owned
                 2) supplier side must match buyFromPlayer/buyFromFaction flags
                 3) serveHomeOnly must restrict delivery to home anchor -->
            <do_if value="$pairVerdict == 'PASS' and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4CustomerMustBePlayer">
              <do_if value="not $sellStation? or not $sellStation.exists or not $sellStation.isplayerowned">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk4_customer_not_player_owned'"/>
                <set_value name="$rejectMK4ForeignCustomer" operation="add"/>
              </do_if>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2')">
              <do_if value="not $diagMk4AllowPlayerSuppliers and $mk4SupplierIsPlayerOwned">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk4_supplier_policy: player suppliers disabled'"/>
                <set_value name="$rejectMK4SupplierPolicy" operation="add"/>
              </do_if>
              <do_elseif value="not $diagMk4AllowAiSuppliers and not $mk4SupplierIsPlayerOwned">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk4_supplier_policy: faction suppliers disabled'"/>
                <set_value name="$rejectMK4SupplierPolicy" operation="add"/>
              </do_elseif>
            </do_if>
            <!-- Trade rules: player-owned stations only (NPCÃ—NPC ignores cantradewith). -->
            <do_if value="$pairVerdict == 'PASS' and not $ignoreTradeRules and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2')">
              <set_value name="$diagPairTradeRulesApply" exact="false"/>
              <do_if value="$buyStation? and $buyStation.exists">
                <do_if value="@$buyStation.isplayerowned">
                  <set_value name="$diagPairTradeRulesApply" exact="true"/>
                </do_if>
                <do_elseif value="@$buyStation.isclass.buildstorage and $buyStation.base? and @$buyStation.base.exists and @$buyStation.base.isplayerowned">
                  <set_value name="$diagPairTradeRulesApply" exact="true"/>
                </do_elseif>
              </do_if>
              <do_if value="not $diagPairTradeRulesApply and $sellStation? and $sellStation.exists">
                <do_if value="@$sellStation.isplayerowned">
                  <set_value name="$diagPairTradeRulesApply" exact="true"/>
                </do_if>
                <do_elseif value="@$sellStation.isclass.buildstorage and $sellStation.base? and @$sellStation.base.exists and @$sellStation.base.isplayerowned">
                  <set_value name="$diagPairTradeRulesApply" exact="true"/>
                </do_elseif>
              </do_if>
              <do_if value="$diagPairTradeRulesApply">
                <do_if value="$buyOffer? and $buyStation? and $buyStation.exists and not $buyOffer.cantradewith.{$buyStation}">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk4_trade_rules: customer ' + (if $sellStation? and $sellStation.exists then $sellStation.knownname else 'customer') + ' disallows source ' + (if $buyStation? and $buyStation.exists then $buyStation.knownname else 'source')"/>
                  <set_value name="$rejectMK4TradeRules" operation="add"/>
                </do_if>
                <do_elseif value="$sellOffer? and $sellStation? and $sellStation.exists and not $sellOffer.cantradewith.{$sellStation}">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk4_trade_rules: source ' + (if $buyStation? and $buyStation.exists then $buyStation.knownname else 'source') + ' disallows delivery to ' + (if $sellStation? and $sellStation.exists then $sellStation.knownname else 'customer')"/>
                  <set_value name="$rejectMK4TradeRules" operation="add"/>
                </do_elseif>
              </do_if>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4BuildStorageOnlyMode">
              <do_if value="$buyStation? and @$buyStation.isclass.buildstorage">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk4_buildstorage_only: BS supplier leg blocked'"/>
                <set_value name="$rejectMK4BuildStorageOnly" operation="add"/>
              </do_if>
              <do_if value="$pairVerdict == 'PASS' and (not $sellStation? or not @$sellStation.isclass.buildstorage)">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk4_buildstorage_only: delivery must be build storage'"/>
                <set_value name="$rejectMK4BuildStorageOnly" operation="add"/>
              </do_if>
              <do_if value="$pairVerdict == 'PASS'">
                <set_value name="$diagBsoDist" exact="if $diagMk4HomeSector? and $diagMk4HomeSector.exists and $sellStation? and $sellStation.sector? then $diagMk4HomeSector.gatedistance.{$sellStation.sector} else -1"/>
                <do_if value="$diagBsoDist lt 0 or ($maxSell gt 0 and $diagBsoDist gt $maxSell)">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk4_buildstorage_only: delivery outside jumpDistanceCoverage'"/>
                  <set_value name="$rejectMK4BuildStorageOnly" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="$pairVerdict == 'PASS' and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $diagMk4DedicatedServe and not $diagMk4BuildStorageOnlyMode and $diagMk4HomeAnchor?">
              <do_if value="$diagMk4HomeAnchor.isclass.station">
                <set_value name="$diagServeHomeMatch" exact="false"/>
                <do_if value="$sellStation? and $sellStation.exists and $diagMk4HomeAnchor.exists">
                  <do_if value="$sellStation == $diagMk4HomeAnchor">
                    <set_value name="$diagServeHomeMatch" exact="true"/>
                  </do_if>
                  <do_elseif value="$diagMk4HomeAnchor.buildstorage? and $diagMk4HomeAnchor.buildstorage.exists and $sellStation == $diagMk4HomeAnchor.buildstorage">
                    <set_value name="$diagServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$sellStation.isclass.buildstorage and $sellStation.base? and $sellStation.base.exists and $sellStation.base == $diagMk4HomeAnchor">
                    <set_value name="$diagServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$sellStation.hascontext.{$diagMk4HomeAnchor}">
                    <set_value name="$diagServeHomeMatch" exact="true"/>
                  </do_elseif>
                  <do_elseif value="$diagMk4HomeAnchor.hascontext.{$sellStation}">
                    <set_value name="$diagServeHomeMatch" exact="true"/>
                  </do_elseif>
                </do_if>
                <do_if value="not $diagServeHomeMatch">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk4_servehome_station_mismatch (delivery must be home station or its build storage)'"/>
                  <set_value name="$rejectMK4ServeHomeScope" operation="add"/>
                </do_if>
              </do_if>
              <do_elseif value="$diagMk4HomeSector? and $diagMk4HomeSector.exists">
                <do_if value="not $sellStation.sector? or @$sellStation.sector != $diagMk4HomeSector">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk4_servehome_sector_mismatch (delivery outside home sector)'"/>
                  <set_value name="$rejectMK4ServeHomeScope" operation="add"/>
                </do_if>
              </do_elseif>
            </do_if>

            <!-- MK4 reservation-aware demand gate:
                 skip pairs whose destination demand is already covered by vanilla incoming
                 reservations plus GT in-flight reservations from other ships.
                 Baseline uses max(per-ship offeramount, raw offer.amount, cargo deficit) because
                 offer slices understate build-storage need while reservations are station-wide. -->
            <do_if value="$pairVerdict == 'PASS' and ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $buyOffer? and $sellStation? and $sellStation.exists and $pairWare?">
              <set_value name="$diagDemandBaseline" exact="$buyOfferAmount"/>
              <do_if value="$buyOffer.amount? and $buyOffer.amount gt $diagDemandBaseline">
                <set_value name="$diagDemandBaseline" exact="$buyOffer.amount"/>
              </do_if>
              <set_value name="$diagCargoDeficit" exact="[0, $sellStation.cargo.{$pairWare}.target - $sellStation.cargo.{$pairWare}.count].max"/>
              <do_if value="$diagCargoDeficit gt $diagDemandBaseline">
                <set_value name="$diagDemandBaseline" exact="$diagCargoDeficit"/>
              </do_if>
              <set_value name="$diagIncomingReservedAmount" exact="0"/>
              <get_ware_reservation object="$sellStation" ware="$pairWare" type="sell" virtual="false" result="$diagIncomingReservedAmount"/>
              <set_value name="$diagGTIncomingReservedAmount" exact="0"/>
              <do_if value="global.$GT_Reservations? and global.$GT_Reservations.{$buyOffer}?">
                <set_value name="$diagGTResData" exact="global.$GT_Reservations.{$buyOffer}"/>
                <do_if value="$diagGTResData.$Until? and player.age lt @$diagGTResData.$Until">
                  <do_if value="not $diagGTResData.$Ship? or @$diagGTResData.$Ship != $ship">
                    <set_value name="$diagGTResAmount" exact="0"/>
                    <do_if value="$diagGTResData.$Amount? and @$diagGTResData.$Amount gt 0">
                      <set_value name="$diagGTResAmount" exact="$diagGTResData.$Amount"/>
                    </do_if>
                    <do_else>
                      <set_value name="$diagGTResAmount" exact="1"/>
                    </do_else>
                    <set_value name="$diagGTIncomingReservedAmount" exact="$diagGTIncomingReservedAmount + $diagGTResAmount"/>
                  </do_if>
                </do_if>
              </do_if>
              <set_value name="$diagEffectiveNeedAmount" exact="[$diagDemandBaseline - $diagIncomingReservedAmount - $diagGTIncomingReservedAmount, 0].max"/>
              <do_if value="$diagEffectiveNeedAmount le 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk4_demand_reserved_exhausted (need=' + $diagDemandBaseline + ', offerAmt=' + $buyOfferAmount + ', vanillaRes=' + $diagIncomingReservedAmount + ', gtRes=' + $diagGTIncomingReservedAmount + ')'"/>
                <set_value name="$rejectMK4DemandReservedExhausted" operation="add"/>
              </do_if>
            </do_if>

            <!-- Check 1: price validity -->
            <do_if value="$pairVerdict == 'PASS'">
              <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
                <do_if value="$sellPrice lt $buyPrice">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk4_price_cap_exceeded (customer=' + ($sellPrice / 100) + ' lt source=' + ($buyPrice / 100) + ')'"/>
                  <set_value name="$rejectNoProfit" operation="add"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- IPP bypass: skip no_profit gate when supplier is player-owned and IPP is on
                     (player's production cost is treated as zero - any sale is profitable). -->
                <do_if value="$sellPrice le $buyPrice and not $diagPairPlayerFreeSupplier">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'no_profit (sell=' + ($sellPrice / 100) + ' le buy=' + ($buyPrice / 100) + ')'"/>
                  <set_value name="$rejectNoProfit" operation="add"/>
                </do_if>
              </do_else>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 2: Operational -->
              <do_if value="not $buyStation.isoperational">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'buy_station_not_operational'"/>
                <set_value name="$rejectNotOperational" operation="add"/>
              </do_if>
              <do_elseif value="not $sellStation.isoperational">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'sell_station_not_operational'"/>
                <set_value name="$rejectNotOperational" operation="add"/>
              </do_elseif>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 3: Dock feasibility (trading bays on stations, storage bays on build storage) -->
              <run_actions ref="md.GT_Libraries_General.GT_CanDockForTrade" result="$diagBuyDockResult">
                <param name="station" value="$buyStation"/>
                <param name="ship" value="$ship"/>
                <param name="allowStorageDock" value="false"/>
              </run_actions>
              <do_if value="not $diagBuyDockResult.$CanDock">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'dock_incompatible_buy (' + $buyStation.knownname + ', size=' + $ship.docksize + ')'"/>
                <set_value name="$rejectDocking" operation="add"/>
              </do_if>
              <do_else>
                <run_actions ref="md.GT_Libraries_General.GT_CanDockForTrade" result="$diagSellDockResult">
                  <param name="station" value="$sellStation"/>
                  <param name="ship" value="$ship"/>
                  <param name="allowStorageDock" value="false"/>
                </run_actions>
                <do_if value="not $diagSellDockResult.$CanDock">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'dock_incompatible_sell (' + $sellStation.knownname + ', size=' + $ship.docksize + ')'"/>
                  <set_value name="$rejectDockSize" operation="add"/>
                </do_if>
              </do_else>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 4: Runtime station-class exclusions -->
              <do_if value="$ignoreBuildStorage and ($buyStation.isbuildstorage or $sellStation.isbuildstorage)">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'build_storage_excluded'"/>
                <set_value name="$rejectBuildStorage" operation="add"/>
              </do_if>
              <do_elseif value="$ignoreCarrierAux and (($buyStation.isclass.ship and ($buyStation.type == shiptype.carrier or $buyStation.type == shiptype.resupplier)) or ($sellStation.isclass.ship and ($sellStation.type == shiptype.carrier or $sellStation.type == shiptype.resupplier)))">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'carrier_aux_excluded'"/>
                <set_value name="$rejectCarrierAux" operation="add"/>
              </do_elseif>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 5: MK1 supply exclusion (mirrors runtime: either leg may be MK1-supplied). -->
              <do_if value="$ignoreMK1Supply and global.$GT_MK1SuppliedStations?">
                <do_if value="$buyStation? and global.$GT_MK1SuppliedStations.{$buyStation}?">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk1_supply_excluded (supplier: ' + $buyStation.knownname + ')'"/>
                  <set_value name="$rejectMK1Supply" operation="add"/>
                </do_if>
                <do_elseif value="$sellStation? and global.$GT_MK1SuppliedStations.{$sellStation}?">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'mk1_supply_excluded (customer: ' + $sellStation.knownname + ')'"/>
                  <set_value name="$rejectMK1Supply" operation="add"/>
                </do_elseif>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 6: Illegal ware -->
              <do_if value="not $allowIllegal and @$pairWare.illegal gt 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'ware_illegal (' + $pairWare.name + ')'"/>
                <set_value name="$rejectIllegal" operation="add"/>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 7: Ship can carry ware type -->
              <do_if value="$ship.cargo.{$pairWare}.max le 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'cargo_incompatible (' + $pairWare.name + ')'"/>
                <set_value name="$rejectCargoType" operation="add"/>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 8: Amount / affordability (values pre-computed above) -->
              <do_if value="$maxAmount le 0">
                <do_if value="$maxByMoney le 0">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'cant_afford (need ' + ($buyPrice / 100) + ' Cr/unit, have ' + ($playerMoney / 100) + ' Cr)'"/>
                  <set_value name="$rejectCantAfford" operation="add"/>
                </do_if>
                <do_else>
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'zero_amount (cargo=' + $maxByCargo + ', money=' + $maxByMoney + ', offer=' + $maxByOffer + ')'"/>
                  <set_value name="$rejectZeroAmount" operation="add"/>
                </do_else>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS' and $orderId != 'GalaxyTraderMK4Supply' and $orderId != 'GalaxyTraderMK4Supply2' and not $diagPairPlayerFreeSupplier">
              <!-- Check 9: Profit threshold (pre-path screen; re-validated after trade_found parity gates below). -->
              <do_if value="$totalProfit lt $finalProfitThreshold">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'below_profit_threshold (' + ($totalProfit / 100) + ' Cr lt ' + ($finalProfitThreshold / 100) + ' Cr)'"/>
                <set_value name="$rejectBelowThreshold" operation="add"/>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS' and $orderId != 'GalaxyTraderMK4Supply' and $orderId != 'GalaxyTraderMK4Supply2' and not $diagPairPlayerFreeSupplier">
              <!-- Check 10: ROI threshold -->
              <do_if value="$roi lt $effectiveROI">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'below_roi (' + $roi + '% lt ' + $effectiveROI + '%)'"/>
                <set_value name="$rejectBelowROI" operation="add"/>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 11: Blacklist (explicit object/sector activity checks) -->
              <do_if value="$blacklistgroup? and (@$buyStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship} or @$buyStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{$ship})">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'blacklisted_buy (' + $buyStation.knownname + ')'"/>
                <set_value name="$rejectBlacklist" operation="add"/>
              </do_if>
              <do_elseif value="$blacklistgroup? and (@$sellStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship} or @$sellStation.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{$ship})">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'blacklisted_sell (' + $sellStation.knownname + ')'"/>
                <set_value name="$rejectBlacklist" operation="add"/>
              </do_elseif>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <!-- Check 12: Path reachability on both trade legs (ship->buy and buy->sell).
                   Budget-limited: only the first $diagPathfindBudget passing pairs get full path checks. -->
              <do_if value="$diagPathfindBudget gt 0">
                <set_value name="$diagPathfindBudget" operation="subtract" exact="1"/>
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$buyDist">
                <param name="ship" value="$ship"/>
                <param name="fromSector" value="if $homeSector? and $homeSector.exists then $homeSector else $ship.sector"/>
                <param name="toSector" value="$buyStation.sector"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="useEscapeMode" value="false"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$sellDist">
                <param name="ship" value="$ship"/>
                <param name="fromSector" value="$buyStation.sector"/>
                <param name="toSector" value="$sellStation.sector"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="useEscapeMode" value="false"/>
              </run_actions>
              <set_value name="$pairHasDistances" exact="true"/>
              <set_value name="$diagHomeForDist" exact="if $homeSector? and $homeSector.exists then $homeSector else $ship.sector"/>
              <set_value name="$homeToSellDist" exact="$diagHomeForDist.gatedistance.{$sellStation}"/>

              <do_if value="$buyDist lt 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'path_blocked_buy (unreachable: ' + $buyStation.knownname + ')'"/>
                <set_value name="$rejectPathBlocked" operation="add"/>
              </do_if>
              <do_elseif value="$sellDist lt 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'path_blocked_sell (unreachable: ' + $sellStation.knownname + ')'"/>
                <set_value name="$rejectPathBlocked" operation="add"/>
              </do_elseif>
              </do_if>
            </do_if>

            <!-- Check 12b: Illegal Route Filter (pre-trade route_legality parity) -->
            <do_if value="$pairVerdict == 'PASS' and $diagRouteFilterActive and @$pairWare.illegal gt 0">
              <set_value name="$diagRouteHome" exact="if $homeSector? and $homeSector.exists then $homeSector else $buyStation.sector"/>
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CheckRouteLegality" result="$diagRouteLegality">
                <param name="ship" value="$ship"/>
                <param name="homeSector" value="$diagRouteHome"/>
                <param name="buySector" value="$buyStation.sector"/>
                <param name="sellSector" value="$sellStation.sector"/>
                <param name="ware" value="$pairWare"/>
                <param name="allowIllegal" value="$allowIllegal"/>
                <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="startSector" value="$ship.sector"/>
              </run_actions>
              <do_if value="not $diagRouteLegality.$IsLegal">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$diagRlBlockedSector" exact="if $diagRouteLegality.$BlockedSectorName? and $diagRouteLegality.$BlockedSectorName != '' then $diagRouteLegality.$BlockedSectorName else 'unknown sector'"/>
                <set_value name="$diagRlBlockedPolice" exact="if $diagRouteLegality.$BlockedPoliceName? and $diagRouteLegality.$BlockedPoliceName != '' then $diagRouteLegality.$BlockedPoliceName else 'unknown police'"/>
                <set_value name="$pairReason" exact="'route_illegal (' + $pairWare.name + ' illegal in ' + $diagRlBlockedSector + ', police=' + $diagRlBlockedPolice + ')'"/>
                <set_value name="$rejectRouteIllegal" operation="add"/>
              </do_if>
            </do_if>

            <!-- Check 12c: clamp_trade_amount preview (mirrors lib.gt.tradematch + trade_found). -->
            <do_if value="$pairVerdict == 'PASS' and $orderId != 'GalaxyMiner'">
              <set_value name="$diagClampAmount" exact="$maxAmount"/>
              <set_value name="$diagClampBuySeller" exact="null"/>
              <do_if value="$sellOffer.seller?">
                <set_value name="$diagClampBuySeller" exact="@$sellOffer.seller"/>
              </do_if>
              <do_if value="$diagClampBuySeller == null and $sellOffer.owner?">
                <set_value name="$diagClampBuySeller" exact="@$sellOffer.owner"/>
              </do_if>
              <do_if value="$diagClampBuySeller != null">
                <set_value name="$diagClampReason" exact="null"/>
                <clamp_trade_amount trade="$sellOffer" amount="$diagClampAmount" buyer="$ship" seller="$diagClampBuySeller" result="$diagClampAmount" reason="$diagClampReason"/>
                <do_if value="not $diagClampAmount? or $diagClampAmount le 0">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'supplier_clamp_zero (' + (if $diagClampReason? then $diagClampReason else 'seller_cargo') + ')'"/>
                  <set_value name="$rejectSupplierClamp" operation="add"/>
                </do_if>
              </do_if>
              <do_elseif value="$pairVerdict == 'PASS'">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'supplier_clamp_zero (seller_missing)'"/>
                <set_value name="$rejectSupplierClamp" operation="add"/>
              </do_elseif>
              <do_if value="$pairVerdict == 'PASS'">
                <set_value name="$diagClampSellBuyer" exact="null"/>
                <do_if value="$buyOffer.buyer?">
                  <set_value name="$diagClampSellBuyer" exact="@$buyOffer.buyer"/>
                </do_if>
                <do_if value="$diagClampSellBuyer == null and $buyOffer.owner?">
                  <set_value name="$diagClampSellBuyer" exact="@$buyOffer.owner"/>
                </do_if>
                <do_if value="$diagClampSellBuyer != null">
                  <set_value name="$diagSellClampReason" exact="null"/>
                  <clamp_trade_amount trade="$buyOffer" amount="$diagClampAmount" buyer="$diagClampSellBuyer" result="$diagClampAmount" reason="$diagSellClampReason"/>
                  <do_if value="not $diagClampAmount? or $diagClampAmount le 0">
                    <set_value name="$pairVerdict" exact="'FAIL'"/>
                    <set_value name="$pairReason" exact="'destination_clamp_zero (' + (if $diagSellClampReason? then $diagSellClampReason else 'buyer_cargo') + ')'"/>
                    <set_value name="$rejectSupplierClamp" operation="add"/>
                  </do_if>
                </do_if>
                <do_elseif value="$pairVerdict == 'PASS'">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'destination_clamp_zero (buyer_missing)'"/>
                  <set_value name="$rejectSupplierClamp" operation="add"/>
                </do_elseif>
              </do_if>
              <do_if value="$pairVerdict == 'PASS'">
                <set_value name="$maxAmount" exact="$diagClampAmount"/>
                <set_value name="$totalProfit" exact="$profitPerUnit * $maxAmount"/>
                <do_if value="$diagPairPlayerFreeSupplier">
                  <set_value name="$totalProfit" exact="$sellPrice * $maxAmount"/>
                </do_if>
                <do_if value="$buyPrice gt 0">
                  <set_value name="$roi" exact="($profitPerUnit * 100) / $buyPrice"/>
                </do_if>
              </do_if>
            </do_if>

            <!-- Check 13: trade_found validation parity (offer validity, home distance, post-clamp cargo, profit recalc, MK3 blacklist, dock size). -->
            <do_if value="$pairVerdict == 'PASS'">
              <do_if value="not $sellOffer.available or not $buyOffer.available">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'offer_not_available (buy=' + $sellOffer.available + ', sell=' + $buyOffer.available + ')'"/>
                <set_value name="$rejectOfferInvalid" operation="add"/>
              </do_if>
              <do_elseif value="not $sellOffer.offeramount.{$ship}? or $sellOffer.offeramount.{$ship} le 0 or not $buyOffer.offeramount.{$ship}? or $buyOffer.offeramount.{$ship} le 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'offeramount_for_ship_zero (buy=' + (if $sellOffer.offeramount.{$ship}? then $sellOffer.offeramount.{$ship} else 'null') + ', sell=' + (if $buyOffer.offeramount.{$ship}? then $buyOffer.offeramount.{$ship} else 'null') + ')'"/>
                <set_value name="$rejectOfferInvalid" operation="add"/>
              </do_elseif>
            </do_if>

            <do_if value="$pairVerdict == 'PASS' and $pairHasDistances">
              <do_if value="$buyDist gt $maxBuy">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'buy_distance_exceeded (' + $buyDist + ' gt ' + $maxBuy + ' from home)'"/>
                <set_value name="$rejectDistance" operation="add"/>
              </do_if>
              <do_elseif value="$homeToSellDist lt 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'sell_distance_unreachable (homeâ†’sell blocked)'"/>
                <set_value name="$rejectDistance" operation="add"/>
              </do_elseif>
              <do_elseif value="$homeToSellDist gt $maxSell">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'sell_distance_exceeded (' + $homeToSellDist + ' gt ' + $maxSell + ' from home)'"/>
                <set_value name="$rejectDistance" operation="add"/>
              </do_elseif>
            </do_if>

            <do_if value="$pairVerdict == 'PASS'">
              <set_value name="$diagFinalAmount" exact="$maxAmount"/>
              <set_value name="$diagSyncedProfit" exact="$profitPerUnit * $diagFinalAmount"/>
              <do_if value="$diagPairPlayerFreeSupplier">
                <set_value name="$diagSyncedProfit" exact="$sellPrice * $diagFinalAmount"/>
              </do_if>
              <set_value name="$totalProfit" exact="$diagSyncedProfit"/>
              <do_if value="$buyPrice gt 0">
                <set_value name="$roi" exact="(($sellPrice - $buyPrice) * 100) / $buyPrice"/>
              </do_if>
              <do_if value="$diagPairPlayerFreeSupplier">
                <set_value name="$roi" exact="0"/>
              </do_if>

              <do_if value="$useMinCargoThreshold and not $diagIsolatedForCargoFilter and $orderId != 'GalaxyTraderMK4Supply'">
                <set_value name="$diagTradeVolume" exact="$diagFinalAmount * $volumePerUnit"/>
                <set_value name="$diagRequiredVolume" exact="($ship.cargo.capacity.all * $effectiveCargoTarget) / 100.0"/>
                <set_value name="$diagUtilPct" exact="if $ship.cargo.capacity.all gt 0 then ($diagTradeVolume * 100.0) / $ship.cargo.capacity.all else 0"/>
                <do_if value="$diagTradeVolume lt $diagRequiredVolume">
                  <set_value name="$pairVerdict" exact="'FAIL'"/>
                  <set_value name="$pairReason" exact="'cargo_utilization_below_min (' + $diagUtilPct + '% lt ' + $effectiveCargoTarget + '% after amount sync)'"/>
                  <set_value name="$rejectCargoUtil" operation="add"/>
                </do_if>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS' and not $diagPairPlayerFreeSupplier">
              <do_if value="$totalProfit le 0">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'profit_recalc_nonpositive (' + ($totalProfit / 100) + ' Cr)'"/>
                <set_value name="$rejectProfitRecalc" operation="add"/>
              </do_if>
            </do_if>

            <do_if value="$pairVerdict == 'PASS' and $orderId != 'GalaxyTraderMK4Supply' and $orderId != 'GalaxyTraderMK4Supply2' and not $diagPairPlayerFreeSupplier">
              <do_if value="$totalProfit lt $finalProfitThreshold">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'below_profit_threshold_after_sync (' + ($totalProfit / 100) + ' Cr lt ' + ($finalProfitThreshold / 100) + ' Cr)'"/>
                <set_value name="$rejectBelowThreshold" operation="add"/>
              </do_if>
              <do_elseif value="$roi lt $effectiveROI">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'below_roi_after_sync (' + $roi + '% lt ' + $effectiveROI + '%)'"/>
                <set_value name="$rejectBelowROI" operation="add"/>
              </do_elseif>
            </do_if>

            <do_if value="$pairVerdict == 'PASS' and $mk3BlacklistApplies and $mk3BlacklistOwner? and global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}?">
              <set_value name="$diagMk3Blacklist" exact="global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwner}"/>
              <set_value name="$diagBuyFaction" exact="null"/>
              <set_value name="$diagSellFaction" exact="null"/>
              <do_if value="$buyStation.owner?">
                <set_value name="$diagBuyOwnerContainer" exact="@$buyStation.owner"/>
                <do_if value="$diagBuyOwnerContainer.owner?">
                  <set_value name="$diagBuyFaction" exact="$diagBuyOwnerContainer.owner"/>
                </do_if>
                <do_else>
                  <set_value name="$diagBuyFaction" exact="$diagBuyOwnerContainer"/>
                </do_else>
              </do_if>
              <do_if value="$sellStation.owner?">
                <set_value name="$diagSellOwnerContainer" exact="@$sellStation.owner"/>
                <do_if value="$diagSellOwnerContainer.owner?">
                  <set_value name="$diagSellFaction" exact="$diagSellOwnerContainer.owner"/>
                </do_if>
                <do_else>
                  <set_value name="$diagSellFaction" exact="$diagSellOwnerContainer"/>
                </do_else>
              </do_if>
              <do_if value="$diagBuyFaction? and $diagMk3Blacklist.{$diagBuyFaction}?">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk3_faction_blacklist_buy (' + $diagBuyFaction.name + ')'"/>
                <set_value name="$rejectMK3Faction" operation="add"/>
              </do_if>
              <do_elseif value="$diagSellFaction? and $diagMk3Blacklist.{$diagSellFaction}?">
                <set_value name="$pairVerdict" exact="'FAIL'"/>
                <set_value name="$pairReason" exact="'mk3_faction_blacklist_sell (' + $diagSellFaction.name + ')'"/>
                <set_value name="$rejectMK3Faction" operation="add"/>
              </do_elseif>
            </do_if>

            <!-- Dock size check merged into Check 3 (GT_CanDockForTrade) â€” build storage uses storage bays. -->

            <!-- ==============================================================================
                 SCORE COMPUTATION (mirrors lib.gt.tradematch.xml score formula).
                 Computed for ALL pairs that reached Check 12 (so distances are known) regardless
                 of final pass/fail verdict. This means FAIL pairs that lost on a late check
                 (path_blocked, blacklist) still get a meaningful score for sort ordering, while
                 pairs that bailed early (no_profit, illegal, cargo_incompatible) keep the
                 default $pairScore = 0 and cluster at the bottom of the score-ranked list.

                 Sell-mode (MK1/MK2/MK3, default trader):
                   homeToBuy      = homeâ†’buy station (path distance)
                   routeLeg       = buyâ†’sell sector (path distance; 0 when same sector)
                   scoreDistance  = homeToBuy + routeLeg              [route-aware sum]
                   gt_distpenalty = order.distancepenalty / 50.0          [runtime conversion]
                   distanceFactor = 1.0 + scoreDistance * gt_distpenalty
                   grossProfitCr  = (totalProfit / 1Cr)i   (Cr units, integer â€” avoids money/float mix)
                   score          = grossProfitCr / distanceFactor
                   factionBonus   = 1.1 if factionPriority and either station player-owned
                                  = 1.0 otherwise
                   score          = score * factionBonus

                 Supply-mode (MK4Supply only):
                   score          = tradeAmount / distanceFactor
                   (demand-based; unit price does not affect supply ranking)

                 Player-free-supplier (IPP) reuses sell-mode but $totalProfit is already the
                 gross sell income, so the formula picks it up automatically.

                 MK3/MK4 validation sort: selectionScore = adjustedScore / (1 + shipâ†’buy Ã— weight)
                 after optional priority-ware multiplier (mirrors lib.gt.score.trades + selection_sort). -->
            <do_if value="$pairHasDistances and $buyDist ge 0 and $sellDist ge 0">
              <set_value name="$routeLeg" exact="if $buyStation.sector == $sellStation.sector then 0 else $sellDist"/>
              <do_if value="$routeLeg lt 0">
                <set_value name="$routeLeg" exact="0"/>
              </do_if>
              <set_value name="$scoreDistance" exact="$buyDist + $routeLeg"/>
              <set_value name="$gtDistPenalty" exact="$distancePenalty / 50.0"/>
              <set_value name="$scoreDistanceFactor" exact="1.0 + ($scoreDistance * $gtDistPenalty)"/>
              <do_if value="$scoreDistanceFactor le 0">
                <set_value name="$scoreDistanceFactor" exact="1.0"/>
              </do_if>
              <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
                <set_value name="$pairScore" exact="$maxAmount / $scoreDistanceFactor"/>
                <!-- Single-trip completion scoring (mirrors lib.gt.tradematch v5):
                     target/(distance*deficit) without priceFactor when deficit fits one load. -->
                <do_if value="$sellStation.isplayerowned and not $sellStation.isclass.buildstorage and $pairWare?">
                  <set_value name="$diagCfTarget" exact="$sellStation.cargo.{$pairWare}.target"/>
                  <do_if value="$diagCfTarget gt 0">
                    <set_value name="$diagCfDeficit" exact="[$diagCfTarget - $sellStation.cargo.{$pairWare}.count, 0].max"/>
                    <set_value name="$diagCfVolPerUnit" exact="if $pairWare.volume? and $pairWare.volume gt 0 then $pairWare.volume else 1"/>
                    <set_value name="$diagCfOneTripUnits" exact="($ship.cargo.free.all / $diagCfVolPerUnit)i"/>
                    <do_if value="$diagCfDeficit gt 0 and $diagCfOneTripUnits gt 0 and $diagCfDeficit le $diagCfOneTripUnits">
                      <set_value name="$pairScore" exact="$diagCfTarget / ($scoreDistanceFactor * $diagCfDeficit)"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_if value="$sellStation.isclass.buildstorage">
                  <set_value name="$pairScore" exact="$pairScore + 1000000"/>
                </do_if>
              </do_if>
              <do_else>
                <set_value name="$scoreGrossCr" exact="($totalProfit / 1Cr)i"/>
                <set_value name="$pairScore" exact="$scoreGrossCr / $scoreDistanceFactor"/>
                <do_if value="$factionPriority and ($buyStation.isplayerowned or $sellStation.isplayerowned)">
                  <set_value name="$pairScore" exact="$pairScore * 1.1"/>
                </do_if>
              </do_else>
            </do_if>

            <!-- Priority-ware boost then validation selection score (MK3/MK4 â€” mirrors score.trades + selection_sort). -->
            <set_value name="$pairAdjustedScore" exact="$pairScore"/>
            <set_value name="$pairSelectionScore" exact="$pairScore"/>
            <set_value name="$pdSortKey" exact="$pairScore"/>
            <do_if value="$diagUseSelectionSort and $pairScore gt 0">
              <do_if value="$priorityWares.count gt 0 and $pairWare?">
                <do_all exact="$priorityWares.count" counter="$diagPwIdx">
                  <do_if value="$priorityWares.{$diagPwIdx} == $pairWare">
                    <set_value name="$pairAdjustedScore" exact="$pairScore * ($diagPriorityMultPct / 100.0)"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <set_value name="$pairSelectionScore" exact="$pairAdjustedScore"/>
              <do_if value="$diagShipProxWeight gt 0 and $buyStation? and $buyStation.sector? and $ship? and $ship.sector?">
                <set_value name="$diagShipToBuy" exact="-1"/>
                <do_if value="$buyStation.sector == $ship.sector">
                  <set_value name="$diagShipToBuy" exact="0"/>
                </do_if>
                <do_elseif value="$blacklistgroup? and $blacklistgroup != null">
                  <set_value name="$diagShipToBuy" exact="$ship.gatedistance.{$buyStation.sector}.{$blacklistgroup}.{$ship}"/>
                </do_elseif>
                <do_else>
                  <set_value name="$diagShipToBuy" exact="$ship.gatedistance.{$buyStation.sector}"/>
                </do_else>
                <do_if value="$diagShipToBuy ge 0">
                  <set_value name="$diagProxFactor" exact="1.0 + ($diagShipToBuy * $diagShipProxWeight)"/>
                  <do_if value="$diagProxFactor gt 0">
                    <set_value name="$pairSelectionScore" exact="$pairAdjustedScore / $diagProxFactor"/>
                  </do_if>
                </do_if>
              </do_if>
              <set_value name="$pdSortKey" exact="$pairSelectionScore"/>
            </do_if>
            <set_value name="$pairShowSel" exact="false"/>
            <do_if value="$diagUseSelectionSort and $pairSelectionScore != $pairScore">
              <set_value name="$pairShowSel" exact="true"/>
            </do_if>

            <!-- Record pass / track best (sort key matches runtime validation order on MK3/MK4). -->
            <do_if value="$pairVerdict == 'PASS'">
              <set_value name="$passCount" operation="add"/>
              <set_value name="$drPassDesc" exact="$pairWare.name + ': ' + $buyStation.knownname + ' -> ' + $sellStationLabel + ' (Score ' + ($pairScore)i + (if $pairShowSel then (' Â· sel ' + ($pairSelectionScore)i) else '') + ', ' + ($totalProfit / 100) + ' Cr)'"/>
              <append_to_list name="$diagRuntimePassPairs" exact="table[$Score = $pairScore, $SelectionScore = $pairSelectionScore, $SortKey = $pdSortKey, $SellOffer = $sellOffer, $BuyOffer = $buyOffer, $Ware = $pairWare, $Desc = $drPassDesc]"/>
              <do_if value="$pdSortKey gt $bestDiagProfit">
                <set_value name="$bestDiagProfit" exact="$pdSortKey"/>
                <!-- IPP best-pair description: tag the route as a player-free-supplier sale and
                     show 'free' in place of an arithmetic ROI (which would otherwise read as 0). -->
                <set_value name="$bestDiagPairDesc" exact="$pairWare.name + ': ' + $buyStation.knownname + ' -> ' + $sellStationLabel + ' (' + ($totalProfit / 100) + ' Cr, ROI ' + (if $diagPairPlayerFreeSupplier then 'n/a (free)' else ('' + $roi + '%')) + (if $diagPairPlayerFreeSupplier then ' [IPP gross]' else '') + ', Score ' + ($pairScore)i + (if $pairShowSel then (' Â· sel ' + ($pairSelectionScore)i) else '') + ')'"/>
              </do_if>
              <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' and $diagPairPlayerFreeSupplier">
                <do_if value="$pdSortKey gt $bestIppPairScore">
                  <set_value name="$bestIppPairScore" exact="$pdSortKey"/>
                  <set_value name="$bestIppPairDesc" exact="$pairWare.name + ': ' + $buyStation.knownname + ' -> ' + $sellStation.knownname + ' (Score ' + ($pairScore)i + (if $pairShowSel then (' Â· sel ' + ($pairSelectionScore)i) else '') + ', ~' + ($totalProfit / 100) + ' Cr gross)'"/>
                </do_if>
              </do_if>
              <do_elseif value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' and not $mk4SupplierIsPlayerOwned">
                <do_if value="$pdSortKey gt $bestNpcSupplierPairScore">
                  <set_value name="$bestNpcSupplierPairScore" exact="$pdSortKey"/>
                  <set_value name="$bestNpcSupplierPairDesc" exact="$pairWare.name + ': ' + $buyStation.knownname + ' -> ' + $sellStation.knownname + ' (Score ' + ($pairScore)i + (if $pairShowSel then (' Â· sel ' + ($pairSelectionScore)i) else '') + ', ' + ($totalProfit / 100) + ' Cr profit)'"/>
                </do_if>
              </do_elseif>
            </do_if>

            <!-- Record pair details: Ware | Route | Profit (incl. ROI) | Score/Sel | Reason. -->
            <set_value name="$pdRoute" exact="$buyStation.knownname + (if $mk4SupplierIsPlayerOwned then ' [player]' else ' [NPC]') + ' -> ' + $sellStationLabel"/>
            <do_if value="$pairHasDistances and $scoreDistance ge 0">
              <set_value name="$pdRouteLeg" exact="if $routeLeg? then $routeLeg else $sellDist"/>
              <set_value name="$pdRoute" exact="$pdRoute + ' [Hâ†’B ' + $buyDist + '+route ' + $pdRouteLeg + '=' + $scoreDistance + 'j]'"/>
            </do_if>
            <set_value name="$pdROIPart" exact="if $diagPairPlayerFreeSupplier then 'IPP gross' else ('ROI ' + $roi + '%')"/>
            <set_value name="$pdProfitStr" exact="(if $diagPairPlayerFreeSupplier then ('buy ' + ($buyPrice / 100) + 'Cr/u eff 0 Â· ~') else '') + ($totalProfit / 100) + 'Cr' + ' &#183; ' + $pdROIPart"/>
            <set_value name="$pdScoreStr" exact="if not $pairHasDistances then '-' else ('' + ($pairScore)i + (if $pairShowSel then (' Â· sel ' + ($pairSelectionScore)i) else ''))"/>
            <set_value name="$pdStatus" exact="$pairVerdict"/>
            <do_if value="$diagPairPlayerFreeSupplier">
              <set_value name="$pdStatus" exact="$pairVerdict + ' [IPP]'"/>
            </do_if>
            <set_value name="$pdReason" exact="''"/>
            <do_if value="$pairVerdict != 'PASS'">
              <set_value name="$pdReason" exact="$pairReason"/>
            </do_if>
            <do_elseif value="$diagPairPlayerFreeSupplier">
              <set_value name="$pdReason" exact="'IPP: gross sell income; profit/ROI/money gates bypassed'"/>
            </do_elseif>
            <!-- Always capture PASS rows (executable trades for this ship); cap only the FAIL rows so a
                 flood of trade-rule rejections cannot crowd the executable pairs out of the display. -->
            <do_if value="$pairVerdict == 'PASS' or $pairDetails.count lt $diagPairDisplayCap">
              <append_to_list name="$pairDetails" exact="table[$Check = $pairWare.name, $Status = $pdStatus, $Detail = $pdRoute, $Col4 = $pdProfitStr, $Col5 = $pdScoreStr, $Col6 = $pdReason, $SortKey = $pdSortKey]"/>
            </do_if>
          </do_all>
        </do_all>
        </do_else>

        <!-- ==============================================================================
             SORT $pairDetails BY $SortKey DESCENDING (selection-sort pattern, mirrors the
             $rscWareRows sort earlier in this file). MD has no insert_in_list / list.sort,
             so we walk the source list once per output row, picking the highest-key entry
             that has not been claimed yet. A boolean parallel list $pdClaimed marks emitted
             rows. Sort key is tradematch score on MK1/MK2; on MK3/MK4 it is validation selection
             score (after priority-ware boost and ship-proximity nudge). -->
        <do_if value="$pairDetails.count gt 1">
          <set_value name="$pdClaimed" exact="[]"/>
          <do_all exact="$pairDetails.count" counter="$pdci">
            <append_to_list name="$pdClaimed" exact="false"/>
          </do_all>
          <set_value name="$pairDetailsSorted" exact="[]"/>
          <do_all exact="$pairDetails.count" counter="$pdsi">
            <set_value name="$pdBestIdx" exact="0"/>
            <set_value name="$pdBestKey" exact="-1000000000.0"/>
            <do_all exact="$pairDetails.count" counter="$pdsk">
              <do_if value="not $pdClaimed.{$pdsk}">
                <set_value name="$pdRow" exact="$pairDetails.{$pdsk}"/>
                <set_value name="$pdRowKey" exact="if $pdRow.$SortKey? then $pdRow.$SortKey else 0"/>
                <do_if value="$pdRowKey gt $pdBestKey">
                  <set_value name="$pdBestKey" exact="$pdRowKey"/>
                  <set_value name="$pdBestIdx" exact="$pdsk"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$pdBestIdx gt 0">
              <append_to_list name="$pairDetailsSorted" exact="$pairDetails.{$pdBestIdx}"/>
              <set_value name="$pdClaimed.{$pdBestIdx}" exact="true"/>
            </do_if>
          </do_all>
          <set_value name="$pairDetails" exact="$pairDetailsSorted"/>
        </do_if>
        <!-- Runtime dispatch preview: score-sort passing pairs, then fresh-offer filter (mirrors live pipeline). -->
        <do_if value="$orderId != 'GalaxyMiner' and $diagRuntimePassPairs.count gt 0">
          <set_value name="$diagRuntimeSorted" exact="$diagRuntimePassPairs"/>
          <do_if value="$diagRuntimePassPairs.count gt 1">
            <set_value name="$drClaimed" exact="[]"/>
            <do_all exact="$diagRuntimePassPairs.count" counter="$drci">
              <append_to_list name="$drClaimed" exact="false"/>
            </do_all>
            <set_value name="$diagRuntimeSorted" exact="[]"/>
            <do_all exact="$diagRuntimePassPairs.count" counter="$drsi">
              <set_value name="$drBestIdx" exact="0"/>
              <set_value name="$drBestScore" exact="-1000000000.0"/>
              <do_all exact="$diagRuntimePassPairs.count" counter="$drsk">
                <do_if value="not $drClaimed.{$drsk}">
                  <set_value name="$drRow" exact="$diagRuntimePassPairs.{$drsk}"/>
                  <set_value name="$drRowScore" exact="if $drRow.$SortKey? then $drRow.$SortKey else (if $drRow.$Score? then $drRow.$Score else 0)"/>
                  <do_if value="$drRowScore gt $drBestScore">
                    <set_value name="$drBestScore" exact="$drRowScore"/>
                    <set_value name="$drBestIdx" exact="$drsk"/>
                  </do_if>
                </do_if>
              </do_all>
              <do_if value="$drBestIdx gt 0">
                <append_to_list name="$diagRuntimeSorted" exact="$diagRuntimePassPairs.{$drBestIdx}"/>
                <set_value name="$drClaimed.{$drBestIdx}" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
          <set_value name="$diagRuntimeFreshList" exact="[]"/>
          <set_value name="$diagRuntimePreviewParts" exact="[]"/>
          <set_value name="$diagRuntimePreviewCap" exact="5"/>
          <do_all exact="$diagRuntimeSorted.count" counter="$drpi">
            <set_value name="$drPair" exact="$diagRuntimeSorted.{$drpi}"/>
            <set_value name="$drFreshKeep" exact="false"/>
            <do_if value="$drPair? and $drPair.$SellOffer? and $drPair.$BuyOffer?">
              <set_value name="$drFreshBuyAmt" exact="@$drPair.$BuyOffer.offeramount.{$ship}"/>
              <do_if value="(not $drFreshBuyAmt? or $drFreshBuyAmt le 0) and @$drPair.$BuyOffer.amount gt 0">
                <set_value name="$drFreshBuyAmt" exact="@$drPair.$BuyOffer.amount"/>
              </do_if>
              <do_if value="(not $drFreshBuyAmt? or $drFreshBuyAmt le 0) and $drPair.$SellOffer.owner? and @$drPair.$SellOffer.owner.exists and $drPair.$Ware?">
                <set_value name="$drFreshBuyAmt" exact="[0, $drPair.$SellOffer.owner.cargo.{$drPair.$Ware}.target - $drPair.$SellOffer.owner.cargo.{$drPair.$Ware}.count].max"/>
              </do_if>
              <set_value name="$drFreshSellAmt" exact="@$drPair.$SellOffer.offeramount.{$ship}"/>
              <do_if value="(not $drFreshSellAmt? or $drFreshSellAmt le 0) and @$drPair.$SellOffer.amount gt 0">
                <set_value name="$drFreshSellAmt" exact="@$drPair.$SellOffer.amount"/>
              </do_if>
              <do_if value="$drFreshBuyAmt? and $drFreshBuyAmt gt 0 and $drFreshSellAmt? and $drFreshSellAmt gt 0">
                <set_value name="$drFreshKeep" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="$drFreshKeep">
              <append_to_list name="$diagRuntimeFreshList" exact="$drPair"/>
              <do_if value="$diagRuntimePreviewParts.count lt $diagRuntimePreviewCap">
                <append_to_list name="$diagRuntimePreviewParts" exact="$drPair.$Desc"/>
              </do_if>
            </do_if>
          </do_all>
          <set_value name="$diagRuntimeDispatchCount" exact="$diagRuntimeFreshList.count"/>
          <do_if value="$diagRuntimeFreshList.count gt 0">
            <set_value name="$diagRuntimeBestDispatch" exact="$diagRuntimeFreshList.{1}.$Desc"/>
          </do_if>
          <set_value name="$diagRuntimeBatchPreview" exact="''"/>
          <do_all exact="$diagRuntimePreviewParts.count" counter="$drpp">
            <do_if value="$drpp gt 1">
              <set_value name="$diagRuntimeBatchPreview" exact="$diagRuntimeBatchPreview + ' | '"/>
            </do_if>
            <set_value name="$diagRuntimeBatchPreview" exact="$diagRuntimeBatchPreview + $diagRuntimePreviewParts.{$drpp}"/>
          </do_all>
          <do_if value="$diagRuntimeBatchPreview == ''">
            <set_value name="$diagRuntimeBatchPreview" exact="'none (fresh-offer filter removed all ' + $diagRuntimePassPairs.count + ' passing pairs)'"/>
          </do_if>
        </do_if>

        <!-- Add pair evaluation summary -->
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Scoring Model', $Status = 'INFO', $Detail = 'Score distance = homeâ†’buy + buyâ†’sell (route-aware)' + (if $diagUseSelectionSort then ('; validation sort = score / (1 + shipâ†’buy Ã— ' + $diagShipProxWeight + ') after priority boost') else '')]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Total Pairs Evaluated', $Status = 'INFO', $Detail = '' + $pairCount + (if $diagHitEvalCap then (' (cap ' + $diagPairEvalCap + ' reached â€” counts may be truncated)') else '')]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Pairs Passing All Checks', $Status = if $passCount gt 0 then 'PASS' else 'FAIL', $Detail = '' + $passCount + ' / ' + $pairCount + ' (executable parity â€” mirrors trade_found validation)']"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Runtime Dispatch (fresh-offer filter)', $Status = if $diagRuntimeDispatchCount gt 0 then 'PASS' else (if $passCount gt 0 then 'WARN' else 'FAIL'), $Detail = '' + $diagRuntimeDispatchCount + ' / ' + $passCount + ' passing pairs would reach validation (mirrors live pipeline)']"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Runtime Dispatch Preview', $Status = if $diagRuntimeDispatchCount gt 0 then 'PASS' else 'INFO', $Detail = if $diagRuntimeDispatchCount gt 0 then ('Best: ' + $diagRuntimeBestDispatch + ' | Top: ' + $diagRuntimeBatchPreview) else $diagRuntimeBatchPreview]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Best Passing Pair', $Status = if $passCount gt 0 then 'PASS' else 'FAIL', $Detail = $bestDiagPairDesc]"/>
        <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Best IPP Pair (player supplier)', $Status = if $bestIppPairScore gt 0 then 'PASS' else 'WARN', $Detail = $bestIppPairDesc]"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Best NPC Supplier Pair', $Status = if $bestNpcSupplierPairScore gt 0 then 'INFO' else 'INFO', $Detail = $bestNpcSupplierPairDesc]"/>
          <do_if value="$bestNpcSupplierPairScore gt $bestIppPairScore and $bestIppPairScore gt 0">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'IPP vs NPC Score', $Status = 'WARN', $Detail = 'Runtime picks highest score: NPC supplier (' + ($bestNpcSupplierPairScore)i + ') beats player supplier (' + ($bestIppPairScore)i + '). IPP does not disable NPC suppliers.']"/>
          </do_if>
          <do_elseif value="$bestIppPairScore gt 0 and $bestNpcSupplierPairScore le 0">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'IPP vs NPC Score', $Status = 'INFO', $Detail = 'Only player-supplier routes pass filters; no competing NPC-supplier pair in the passing set.']"/>
          </do_elseif>
          <do_elseif value="$bestIppPairScore le 0 and $bestNpcSupplierPairScore gt 0">
            <append_to_list name="$sec8.$Rows" exact="table[$Check = 'IPP vs NPC Score', $Status = 'WARN', $Detail = 'No passing player-supplier pair. Runtime will use NPC supplier routes only despite IPP being enabled.']"/>
          </do_elseif>
        </do_if>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = '--- Rejection Breakdown ---', $Status = 'INFO', $Detail = '']"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = if ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') then 'MK4 Price Cap Exceeded (source gt customer buy)' else 'No Profit (sell le buy)', $Status = if $rejectNoProfit gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectNoProfit]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Below Profit Threshold', $Status = if $rejectBelowThreshold gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectBelowThreshold]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Below ROI Threshold', $Status = if $rejectBelowROI gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectBelowROI]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Not Operational', $Status = if $rejectNotOperational gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectNotOperational]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Offer Invalid (unavailable/zero per-ship amount)', $Status = if $rejectOfferInvalid gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectOfferInvalid]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Supplier Clamp Zero (seller_cargo / destination)', $Status = if $rejectSupplierClamp gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectSupplierClamp + ' (clamp_trade_amount preview â€” mirrors lib.gt.tradematch + trade_found)']"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Profit Recalc Non-Positive', $Status = if $rejectProfitRecalc gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectProfitRecalc]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK3 Faction Blacklist', $Status = if $rejectMK3Faction gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK3Faction]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Docking Denied', $Status = if $rejectDocking gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectDocking]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Dock Size Incompatible', $Status = if $rejectDockSize gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectDockSize]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Zero Amount', $Status = if $rejectZeroAmount gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectZeroAmount]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Cant Afford', $Status = if $rejectCantAfford gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectCantAfford + (if $ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' then ' (IPP player-supplier pairs exempt)' else '')]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Path Blocked', $Status = if $rejectPathBlocked gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectPathBlocked]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Blacklisted (station/sector)', $Status = if $rejectBlacklist gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectBlacklist]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK1 Supply Excluded', $Status = if $rejectMK1Supply gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK1Supply + (if $ignoreMK1Supply then ' (supplier or customer leg in global.$GT_MK1SuppliedStations)' else '')]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Ware Basket Excluded', $Status = if $rejectWareBasket gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectWareBasket + (if $diagPairWareFilterActive then ' (manual basket active)' else '')]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Build Storage Excluded', $Status = if $rejectBuildStorage gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectBuildStorage]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Carrier/Aux Excluded', $Status = if $rejectCarrierAux gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectCarrierAux]"/>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK4 Foreign Customer Blocked', $Status = if $rejectMK4ForeignCustomer gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK4ForeignCustomer]"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK4 Supplier Policy Blocked', $Status = if $rejectMK4SupplierPolicy gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK4SupplierPolicy]"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK4 Trade Rules Blocked (customer/source faction)', $Status = if $rejectMK4TradeRules gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK4TradeRules + ' (build storage trade rule disallows the source faction; enforced when Ignore Trade Rules is off)']"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK4 Serve-Home Scope Blocked', $Status = if $rejectMK4ServeHomeScope gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK4ServeHomeScope]"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK4 Build Storage Only Blocked', $Status = if $rejectMK4BuildStorageOnly gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK4BuildStorageOnly]"/>
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'MK4 Demand Reserved Exhausted', $Status = if $rejectMK4DemandReservedExhausted gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectMK4DemandReservedExhausted]"/>
        </do_if>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Illegal Ware', $Status = if $rejectIllegal gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectIllegal + ' (Allow Illegal off â€” blocks all illegal wares)']"/>
        <do_if value="$diagRouteFilterActive">
          <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Illegal Route (jump path)', $Status = if $rejectRouteIllegal gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectRouteIllegal + ' (Illegal Route Filter on â€” illegal wares must stay legal on full path)']"/>
        </do_if>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Cargo Incompatible', $Status = if $rejectCargoType gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectCargoType]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Cargo Utilization Below Min', $Status = if $rejectCargoUtil gt 0 then 'WARN' else 'INFO', $Detail = '' + $rejectCargoUtil + (if not $useMinCargoThreshold then ' (filter disabled on order)' else if $diagIsolatedForCargoFilter then ' (ignored in isolated mode)' else '')]"/>
        <append_to_list name="$sec8.$Rows" exact="table[$Check = 'Same Station (skipped)', $Status = 'INFO', $Detail = '' + $rejectSameStation]"/>

        <append_to_list name="$report.$Sections" exact="$sec8"/>

        <!-- ======================================================== -->
        <!-- SECTION: Trade Pair Details / Miner Sell Offer Details    -->
        <!-- ======================================================== -->
        <set_value name="$sec8b" exact="table[]"/>
        <set_value name="$sec8b.$Name" exact="if $orderId == 'GalaxyMiner' then 'Miner Sell Offer Details' else 'Pair Details'"/>
        <set_value name="$sec8b.$Rows" exact="[]"/>
        <do_if value="$orderId == 'GalaxyMiner'">
          <do_if value="$diagRouteFilterActive">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Illegal Route Filter', $Status = 'INFO', $Detail = 'active â€” sell offers checked against jump path (ship sector -> buyer sector) for illegal wares']"/>
          </do_if>
          <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Sell Offers Passing Policy', $Status = if $allBuyOffers.count gt 0 then 'PASS' else 'FAIL', $Detail = '' + $allBuyOffers.count + ' offers']"/>
          <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Search Sectors', $Status = if $searchSectors.count gt 0 then 'INFO' else 'FAIL', $Detail = '' + $searchSectors.count + ' sectors']"/>
          <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Diagnose Wares', $Status = if $diagMinerOfferWares.count gt 0 then 'INFO' else 'WARN', $Detail = $diagMinerOfferWaresDetail]"/>
          <do_if value="$allBuyOffers.count gt 0">
            <do_all exact="$allBuyOffers.count" counter="$mbi">
              <set_value name="$mOffer" exact="$allBuyOffers.{$mbi}"/>
              <set_value name="$mStation" exact="if $mOffer? and $mOffer.owner? then $mOffer.owner else null"/>
              <set_value name="$mStationText" exact="if $mStation? and $mStation.exists then ($mStation.knownname + ' (' + $mStation.sector.knownname + ')') else 'UNKNOWN'"/>
              <set_value name="$mAmount" exact="if $mOffer? and $mOffer.offeramount? and $mOffer.offeramount.{$ship}? then $mOffer.offeramount.{$ship} else (if $mOffer? and $mOffer.amount? then $mOffer.amount else 0)"/>
              <set_value name="$mStatus" exact="'PASS'"/>
              <set_value name="$mReason" exact="''"/>
              <do_if value="$diagRouteFilterActive and $mOffer? and $mOffer.ware? and @$mOffer.ware.illegal gt 0 and $mStation? and $mStation.exists and $mStation.sector?">
                <set_value name="$mRouteHome" exact="if $homeSector? and $homeSector.exists then $homeSector else $ship.sector"/>
                <run_actions ref="md.GT_Libraries_Pathfinding.GT_CheckRouteLegality" result="$mRouteLegality">
                  <param name="ship" value="$ship"/>
                  <param name="homeSector" value="$mRouteHome"/>
                  <param name="buySector" value="$ship.sector"/>
                  <param name="sellSector" value="$mStation.sector"/>
                  <param name="ware" value="$mOffer.ware"/>
                  <param name="allowIllegal" value="$allowIllegal"/>
                  <param name="enforceRouteIllegalLegality" value="$enforceRouteIllegalLegality"/>
                  <param name="blacklistgroup" value="$blacklistgroup"/>
                  <param name="startSector" value="$ship.sector"/>
                </run_actions>
                <do_if value="not $mRouteLegality.$IsLegal">
                  <set_value name="$mStatus" exact="'FAIL'"/>
                  <set_value name="$mBlockedSector" exact="if $mRouteLegality.$BlockedSectorName? and $mRouteLegality.$BlockedSectorName != '' then $mRouteLegality.$BlockedSectorName else 'unknown sector'"/>
                  <set_value name="$mBlockedPolice" exact="if $mRouteLegality.$BlockedPoliceName? and $mRouteLegality.$BlockedPoliceName != '' then $mRouteLegality.$BlockedPoliceName else 'unknown police'"/>
                  <set_value name="$mReason" exact="'route_illegal (illegal in ' + $mBlockedSector + ', police=' + $mBlockedPolice + ')'"/>
                </do_if>
              </do_if>
              <append_to_list name="$sec8b.$Rows" exact="table[$Check = if $mOffer? and $mOffer.ware? then $mOffer.ware.name else 'UNKNOWN', $Status = $mStatus, $Detail = $mStationText, $Col4 = '' + (if $mOffer? and $mOffer.unitprice? then ($mOffer.unitprice / 100) else 0) + 'Cr', $Col5 = '' + $mAmount + ' units', $Col6 = $mReason]"/>
            </do_all>
          </do_if>
          <do_else>
            <set_value name="$mNoOfferReason" exact="'No sell opportunities found with current miner policy.'"/>
            <do_if value="$searchSectors.count == 0">
              <set_value name="$mNoOfferReason" exact="'No search sectors resolved (home sector/anchor unavailable for diagnose).'"/>
            </do_if>
            <do_elseif value="$diagMinerOfferWares.count == 0">
              <set_value name="$mNoOfferReason" exact="'No diagnose wares available (no mineable cargo and no active miner ware snapshot).'"/>
            </do_elseif>
            <do_elseif value="$diagMinerRawBuyOfferCount gt 0">
              <set_value name="$mNoOfferReason" exact="'All ' + $diagMinerRawBuyOfferCount + ' raw buyer offer(s) rejected by miner policy.'"/>
            </do_elseif>
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Reason', $Status = 'FAIL', $Detail = $mNoOfferReason]"/>
            <do_if value="$diagMinerPolicyBreakdown != ''">
              <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Policy Rejection Breakdown', $Status = 'WARN', $Detail = $diagMinerPolicyBreakdown]"/>
            </do_if>
            <do_if value="$diagMinerPolicyRejectedSamples.count gt 0">
              <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Rejected Offer Samples', $Status = 'INFO', $Detail = 'First ' + $diagMinerPolicyRejectedSamples.count + ' policy-blocked buyer offer(s) â€” see Primary Station Cargo in section 3 for home-station fill']"/>
              <do_all exact="$diagMinerPolicyRejectedSamples.count" counter="$mrsi">
                <append_to_list name="$sec8b.$Rows" exact="$diagMinerPolicyRejectedSamples.{$mrsi}"/>
              </do_all>
            </do_if>
            <do_else>
              <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Hint', $Status = 'INFO', $Detail = 'See Clearance section for per-station rejection details when the ship is carrying cargo.' ]"/>
            </do_else>
          </do_else>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK2'">
          <!-- MK2 pair details rebuilt from the actual order configuration.
               The generic pair table above is built from sector-wide find_sell_offer/
               find_buy_offer scans, which is the correct model for MK1/MK3/MK4 (those
               orders search the sector for opportunities). MK2 instead trades exclusively
               between the explicit $sourceList and $destList, so the only meaningful pair
               table is one that iterates supplier x customer x ware and walks the same
               gates the runtime applies in order.trade.galaxytraderMK2.xml lines 1212-1956.
               When bidirectional is on, suppliers/customers are the participating-station
               union so both trade directions are evaluated (runtime lines 1212-1227).
               When ignoreoffersettings (ware exchange) is on, player-owned stations trade
               via storage discovery without a formal offer (runtime lines 1313 / 1459).
               We mirror those gates 1:1 here so each row carries a verdict + reasoning
               line that maps directly to a runtime skip counter (illegal/cargo, noSrcOffer,
               srcNoTarget, srcBelowStatic, self, distance, noDstOffer, noNeed, minTrade).
               Reservations (skipReserved) are intentionally NOT modelled - they require
               get_ware_reservation which can mutate engine state in unpredictable ways
               from an MD diagnostic context, and the player-actionable signal is already
               captured by the other gates. -->
          <set_value name="$mk2PairCount" exact="0"/>
          <set_value name="$mk2PairPass" exact="0"/>
          <set_value name="$mk2FirstPassPair" exact="''"/>
          <set_value name="$mk2PairSkipIllegal" exact="0"/>
          <set_value name="$mk2PairSkipNoSrc" exact="0"/>
          <set_value name="$mk2PairSkipSrcNoTarget" exact="0"/>
          <set_value name="$mk2PairSkipBelowStatic" exact="0"/>
          <set_value name="$mk2PairSkipSelf" exact="0"/>
          <set_value name="$mk2PairSkipDistance" exact="0"/>
          <set_value name="$mk2PairSkipNoDst" exact="0"/>
          <set_value name="$mk2PairSkipNoNeed" exact="0"/>
          <set_value name="$mk2PairSkipMinTrade" exact="0"/>
          <set_value name="$mk2PairSkipRouteIllegal" exact="0"/>
          <set_value name="$mk2PairRows" exact="[]"/>
          <set_value name="$mk2NoBasketWares" exact="$mk2SourceCount le 0 or $mk2DestCount le 0"/>
          <do_if value="not $mk2NoBasketWares">
            <set_value name="$mk2OrderAutowares" exact="if $gtOrder.$autowares? then $gtOrder.$autowares else true"/>
            <set_value name="$mk2OrderManualBasket" exact="if $gtOrder.$warebasket? then $gtOrder.$warebasket else []"/>
            <set_value name="$mk2OrderIgnoreRules" exact="if $gtOrder.$ignoretraderules? then $gtOrder.$ignoretraderules else false"/>
            <set_value name="$mk2OrderAllowIllegal" exact="if $gtOrder.$allowillegal? then $gtOrder.$allowillegal else false"/>
            <set_value name="$mk2OrderEnforceRouteIllegal" exact="if $gtOrder.$enforceRouteIllegalLegality? then $gtOrder.$enforceRouteIllegalLegality else false"/>
            <set_value name="$mk2OrderMaxDist" exact="if $gtOrder.$maxDistance? then $gtOrder.$maxDistance else 0"/>
            <set_value name="$mk2OrderMinFill" exact="0"/>
            <do_if value="this.$debug? and false">
              <!-- minCargoFillPercent is read from the live trader instance (this.$minCargoFillPercent)
                   and is not exposed on the order object; we approximate using the order's
                   minimum-trade derivation - see runtime line 1398. The diag uses 1 as a
                   safe lower bound, matching the [1, ...].max guard. -->
            </do_if>
            <set_value name="$mk2RowCap" exact="40"/>
            <do_all exact="$mk2SupplierList.count" counter="$pmsi">
              <set_value name="$pmSrc" exact="$mk2SupplierList.{$pmsi}"/>
              <do_if value="not $pmSrc? or not $pmSrc.exists">
                <continue/>
              </do_if>
              <!-- Build the source's effective ware list: manual basket if autowares=false,
                   otherwise products union tradewares. Mirrors runtime lines 1231-1284.
                   Ware-exchange (ignoreoffersettings) additionally lets a player-owned source
                   sell anything it physically holds (target>0, count>0), so mirror the runtime
                   cargo-ware augmentation (lines 1257-1274) here too. -->
              <create_list name="$pmSrcWares"/>
              <do_if value="not $mk2OrderAutowares">
                <do_all exact="$mk2OrderManualBasket.count" counter="$pmmwi">
                  <append_to_list name="$pmSrcWares" exact="$mk2OrderManualBasket.{$pmmwi}"/>
                </do_all>
              </do_if>
              <do_else>
                <set_value name="$pmSrcProducts" exact="$pmSrc.products.list"/>
                <set_value name="$pmSrcTradewares" exact="$pmSrc.tradewares.list"/>
                <do_all exact="$pmSrcProducts.count" counter="$pmspi">
                  <append_to_list name="$pmSrcWares" exact="$pmSrcProducts.{$pmspi}"/>
                </do_all>
                <do_all exact="$pmSrcTradewares.count" counter="$pmsti">
                  <set_value name="$pmstw" exact="$pmSrcTradewares.{$pmsti}"/>
                  <set_value name="$dup" exact="false"/>
                  <do_all exact="$pmSrcWares.count" counter="$pmsdi">
                    <do_if value="$pmSrcWares.{$pmsdi} == $pmstw">
                      <set_value name="$dup" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                  <do_if value="not $dup">
                    <append_to_list name="$pmSrcWares" exact="$pmstw"/>
                  </do_if>
                </do_all>
                <do_if value="$mk2OrderIgnoreOffers and $pmSrc.isplayerowned">
                  <set_value name="$pmSrcCargoWares" exact="$pmSrc.cargo.list"/>
                  <do_all exact="$pmSrcCargoWares.count" counter="$pmscwi">
                    <set_value name="$pmscw" exact="$pmSrcCargoWares.{$pmscwi}"/>
                    <do_if value="$pmSrc.cargo.{$pmscw}.target gt 0 and $pmSrc.cargo.{$pmscw}.count gt 0">
                      <set_value name="$dup" exact="false"/>
                      <do_all exact="$pmSrcWares.count" counter="$pmscdi">
                        <do_if value="$pmSrcWares.{$pmscdi} == $pmscw">
                          <set_value name="$dup" exact="true"/>
                          <break/>
                        </do_if>
                      </do_all>
                      <do_if value="not $dup">
                        <append_to_list name="$pmSrcWares" exact="$pmscw"/>
                      </do_if>
                    </do_if>
                  </do_all>
                </do_if>
              </do_else>

              <do_all exact="$pmSrcWares.count" counter="$pmwi">
                <set_value name="$pmWare" exact="$pmSrcWares.{$pmwi}"/>
                <set_value name="$pmRoute" exact="@$pmSrc.knownname + ' [' + @$pmSrc.idcode + '] -&gt; (any dst)'"/>
                <set_value name="$pmStatus" exact="'PASS'"/>
                <set_value name="$pmReason" exact="''"/>

                <!-- Gate 1: illegal / cargo capacity (skipIllegalOrNoCargo, runtime line 1289) -->
                <set_value name="$pmShipCargoMax" exact="$ship.cargo.{$pmWare}.max"/>
                <do_if value="$pmShipCargoMax le 0">
                  <set_value name="$pmStatus" exact="'BLOCK'"/>
                  <set_value name="$pmReason" exact="'illegal/cargo: ship cannot carry ' + $pmWare + ' (cargo.max=0 - hold size or container type)'"/>
                  <set_value name="$mk2PairSkipIllegal" operation="add"/>
                </do_if>
                <do_elseif value="not $mk2OrderAllowIllegal and $pmWare.illegal">
                  <set_value name="$pmStatus" exact="'BLOCK'"/>
                  <set_value name="$pmReason" exact="'illegal/cargo: ' + $pmWare + ' is illegal here and Allow Illegal is OFF'"/>
                  <set_value name="$mk2PairSkipIllegal" operation="add"/>
                </do_elseif>

                <!-- Gate 2: source has a sell offer (skipNoSourceOffer, runtime line 1317).
                     Ware-exchange (ignoreoffersettings) storage discovery: a player-owned
                     source with allocated storage (target>0), stock on hand (count>0) and
                     fill at or above static reserve trades WITHOUT a formal sell offer
                     (runtime line 1313). When that applies we must not raise noSrcOffer. -->
                <set_value name="$pmSrcStorageDiscovery" exact="false"/>
                <do_if value="$pmStatus == 'PASS'">
                  <set_value name="$pmSrcSdTarget" exact="$pmSrc.cargo.{$pmWare}.target"/>
                  <set_value name="$pmSrcSdCount" exact="$pmSrc.cargo.{$pmWare}.count"/>
                  <set_value name="$pmSrcSdFill" exact="if $pmSrcSdTarget gt 0 then (($pmSrcSdCount * 100) / $pmSrcSdTarget) else 0"/>
                  <do_if value="$mk2OrderIgnoreOffers and $pmSrc.isplayerowned and $pmSrcSdTarget gt 0 and $pmSrcSdCount gt 0 and $pmSrcSdFill ge $mk2StaticStorage">
                    <set_value name="$pmSrcStorageDiscovery" exact="true"/>
                  </do_if>
                  <do_if value="$mk2OrderIgnoreRules and $pmSrc.isplayerowned">
                    <find_sell_offer seller="$pmSrc" wares="$pmWare" result="$pmSrcOffer"/>
                  </do_if>
                  <do_else>
                    <find_sell_offer tradepartner="$ship" seller="$pmSrc" wares="$pmWare" result="$pmSrcOffer"/>
                  </do_else>
                  <do_if value="$pmSrcOffer == null and $mk2OrderIgnoreRules and $pmSrc.isplayerowned">
                    <find_sell_offer tradepartner="$ship" seller="$pmSrc" wares="$pmWare" result="$pmSrcOffer"/>
                  </do_if>
                  <set_value name="$pmSrcOfferAmount" exact="0"/>
                  <set_value name="$pmSrcOfferAvail" exact="false"/>
                  <do_if value="$pmSrcOffer? and $pmSrcOffer.exists">
                    <set_value name="$pmSrcOfferAvail" exact="$pmSrcOffer.available"/>
                    <set_value name="$pmSrcOfferAmount" exact="if $pmSrcOffer.offeramount.{$ship}? then $pmSrcOffer.offeramount.{$ship} else 0"/>
                    <do_if value="$pmSrcOfferAmount le 0 and $mk2OrderIgnoreRules and $pmSrc.isplayerowned">
                      <set_value name="$pmSrcOfferAmount" exact="[$pmSrc.cargo.{$pmWare}.count, $pmShipCargoMax].min"/>
                    </do_if>
                  </do_if>
                  <do_if value="$pmSrcStorageDiscovery">
                    <!-- Storage discovery supplies the sell side from cargo on hand. -->
                    <set_value name="$pmSrcOfferAmount" exact="[$pmSrcSdCount, $pmShipCargoMax].min"/>
                    <set_value name="$pmSrcOfferAvail" exact="true"/>
                  </do_if>
                  <do_if value="not $pmSrcStorageDiscovery and $pmSrcOffer == null">
                    <set_value name="$pmStatus" exact="'BLOCK'"/>
                    <set_value name="$pmReason" exact="'noSrcOffer: source has no sell offer for ' + $pmWare + ' (typically: not a sellable ware here, station policy, or relation rules block ' + (if $ship.owner? then @$ship.owner.name else 'this faction') + ')'"/>
                    <set_value name="$mk2PairSkipNoSrc" operation="add"/>
                  </do_if>
                  <do_elseif value="not $pmSrcStorageDiscovery and (not $pmSrcOfferAvail or $pmSrcOfferAmount le 0)">
                    <set_value name="$pmStatus" exact="'BLOCK'"/>
                    <set_value name="$pmReason" exact="'noSrcOffer: source offer present but ' + (if not $pmSrcOfferAvail then 'flagged unavailable' else 'amount=0 (station has no stock to sell right now)')"/>
                    <set_value name="$mk2PairSkipNoSrc" operation="add"/>
                  </do_elseif>
                </do_if>

                <!-- Gate 3: source.cargo.{ware}.target > 0 (skipSourceNoTarget, runtime line 1407) -->
                <set_value name="$pmSrcTarget" exact="$pmSrc.cargo.{$pmWare}.target"/>
                <do_if value="$pmStatus == 'PASS' and $pmSrcTarget le 0">
                  <set_value name="$pmStatus" exact="'BLOCK'"/>
                  <set_value name="$pmReason" exact="'srcNoTarget: source has no allocated cargo target for ' + $pmWare + ' (cargo.target=0 - station manager has not assigned storage)'"/>
                  <set_value name="$mk2PairSkipSrcNoTarget" operation="add"/>
                </do_if>

                <!-- Gate 4: source ratio above static reserve (skipSourceBelowStatic, runtime line 1410) -->
                <set_value name="$pmSrcCount" exact="$pmSrc.cargo.{$pmWare}.count"/>
                <set_value name="$pmSrcRatio" exact="-1"/>
                <do_if value="$pmStatus == 'PASS' and $pmSrcTarget gt 0">
                  <set_value name="$pmSrcRatio" exact="($pmSrcCount * 100) / $pmSrcTarget"/>
                  <do_if value="$pmSrcRatio le $mk2StaticStorage">
                    <set_value name="$pmStatus" exact="'BLOCK'"/>
                    <set_value name="$pmReason" exact="'srcBelowStatic: source has ' + $pmSrcCount + '/' + $pmSrcTarget + ' = ' + $pmSrcRatio + '% &lt;= ' + $mk2StaticStorage + '% staticStorage reserve (runtime refuses to drain a source below this floor)'"/>
                    <set_value name="$mk2PairSkipBelowStatic" operation="add"/>
                  </do_if>
                </do_if>

                <!-- For source-side blockers we record a single "any dst" row and skip the
                     destination loop entirely, exactly like the runtime continues out of
                     the source loop without iterating destinations. -->
                <do_if value="$pmStatus != 'PASS'">
                  <set_value name="$mk2PairCount" operation="add"/>
                  <do_if value="$mk2PairRows.count lt $mk2RowCap">
                    <append_to_list name="$mk2PairRows" exact="table[$Check = $pmWare.name, $Status = $pmStatus, $Detail = $pmRoute, $Col4 = '' + (if $pmSrcRatio ge 0 then ('src ' + $pmSrcRatio + '%') else 'src n/a'), $Col5 = '', $Col6 = $pmReason]"/>
                  </do_if>
                  <continue/>
                </do_if>

                <!-- Per-destination evaluation. In bidirectional mode the customer list is
                     the participating-station union, so this also covers reverse-direction
                     (former destination selling back to a former source) pairs. -->
                <do_all exact="$mk2CustomerList.count" counter="$pmdi">
                  <set_value name="$pmDst" exact="$mk2CustomerList.{$pmdi}"/>
                  <do_if value="not $pmDst? or not $pmDst.exists">
                    <continue/>
                  </do_if>
                  <set_value name="$pmRoute2" exact="@$pmSrc.knownname + ' [' + @$pmSrc.idcode + '] -&gt; ' + @$pmDst.knownname + ' [' + @$pmDst.idcode + ']'"/>
                  <set_value name="$pmStatus2" exact="'PASS'"/>
                  <set_value name="$pmReason2" exact="''"/>
                  <set_value name="$pmDist" exact="-1"/>

                  <!-- Gate 5: same station (skipSelfTarget, runtime line 1433) -->
                  <do_if value="$pmDst == $pmSrc">
                    <set_value name="$pmStatus2" exact="'BLOCK'"/>
                    <set_value name="$pmReason2" exact="'self: source and destination are the same station'"/>
                    <set_value name="$mk2PairSkipSelf" operation="add"/>
                  </do_if>

                  <!-- Gate 6: distance (skipDistance, runtime line 1437-1439) -->
                  <do_if value="$pmStatus2 == 'PASS' and $mk2OrderMaxDist gt 0">
                    <set_value name="$pmDist" exact="$pmSrc.gatedistance.{$pmDst}"/>
                    <do_if value="$pmDist lt 0">
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmReason2" exact="'distance: no gate path from source to destination (gatedistance=-1, sectors not connected)'"/>
                      <set_value name="$mk2PairSkipDistance" operation="add"/>
                    </do_if>
                    <do_elseif value="$pmDist gt $mk2OrderMaxDist">
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmReason2" exact="'distance: ' + $pmDist + ' gates &gt; ' + $mk2OrderMaxDist + ' maxDistance (raise pilot level or maxDistance)'"/>
                      <set_value name="$mk2PairSkipDistance" operation="add"/>
                    </do_elseif>
                  </do_if>

                  <!-- Gate 7: dest has a buy offer (skipNoDestOffer, runtime line 1468).
                       Ware-exchange (ignoreoffersettings) storage discovery: a player-owned
                       destination with free room (target-count gap > 0) accepts the ware
                       WITHOUT a formal buy offer (runtime line 1459). -->
                  <set_value name="$pmDstOfferAmount" exact="0"/>
                  <set_value name="$pmDstOfferAvail" exact="false"/>
                  <set_value name="$pmDstStorageDiscovery" exact="false"/>
                  <do_if value="$pmStatus2 == 'PASS'">
                    <set_value name="$pmDstSdGap" exact="[0, $pmDst.cargo.{$pmWare}.target - $pmDst.cargo.{$pmWare}.count].max"/>
                    <do_if value="$mk2OrderIgnoreOffers and $pmDst.isplayerowned and $pmDstSdGap gt 0">
                      <set_value name="$pmDstStorageDiscovery" exact="true"/>
                    </do_if>
                    <do_if value="$mk2OrderIgnoreRules and $pmDst.isplayerowned">
                      <find_buy_offer buyer="$pmDst" wares="$pmWare" result="$pmDstOffer"/>
                    </do_if>
                    <do_else>
                      <find_buy_offer tradepartner="$ship" buyer="$pmDst" wares="$pmWare" result="$pmDstOffer"/>
                    </do_else>
                    <do_if value="$pmDstOffer == null and $mk2OrderIgnoreRules and $pmDst.isplayerowned">
                      <find_buy_offer tradepartner="$ship" buyer="$pmDst" wares="$pmWare" result="$pmDstOffer"/>
                    </do_if>
                    <do_if value="$pmDstOffer? and $pmDstOffer.exists">
                      <set_value name="$pmDstOfferAvail" exact="$pmDstOffer.available"/>
                      <set_value name="$pmDstOfferAmount" exact="if $pmDstOffer.offeramount.{$ship}? then $pmDstOffer.offeramount.{$ship} else 0"/>
                      <do_if value="$pmDstOfferAmount le 0 and $mk2OrderIgnoreRules and $pmDst.isplayerowned">
                        <set_value name="$pmDstOfferAmount" exact="[0, $pmDst.cargo.{$pmWare}.target - $pmDst.cargo.{$pmWare}.count].max"/>
                      </do_if>
                    </do_if>
                    <do_if value="$pmDstStorageDiscovery">
                      <set_value name="$pmDstOfferAmount" exact="$pmDstSdGap"/>
                      <set_value name="$pmDstOfferAvail" exact="true"/>
                    </do_if>
                    <do_if value="not $pmDstStorageDiscovery and $pmDstOffer == null">
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmReason2" exact="'noDstOffer: destination does not buy ' + $pmWare + ' (not a resource, not a tradeware, or station/relation policy blocks)'"/>
                      <set_value name="$mk2PairSkipNoDst" operation="add"/>
                    </do_if>
                    <do_elseif value="not $pmDstStorageDiscovery and (not $pmDstOfferAvail or $pmDstOfferAmount le 0)">
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmReason2" exact="'noDstOffer: dest offer present but ' + (if not $pmDstOfferAvail then 'flagged unavailable' else 'demand=0 (cargo at or above target - no room)')"/>
                      <set_value name="$mk2PairSkipNoDst" operation="add"/>
                    </do_elseif>
                  </do_if>

                  <!-- Gate 8: bucket / need check (skipNoNeed, runtime line 1726-1778).
                       Simplified to the L4+ profile (the diag does not know pilot level
                       at order params time); uses the same thresholds. -->
                  <set_value name="$pmDstCount" exact="$pmDst.cargo.{$pmWare}.count"/>
                  <set_value name="$pmDstTarget" exact="[$pmDst.cargo.{$pmWare}.target, 1].max"/>
                  <set_value name="$pmDstRatio" exact="($pmDstCount * 100) / $pmDstTarget"/>
                  <set_value name="$pmBucket" exact="'none'"/>
                  <do_if value="$pmStatus2 == 'PASS'">
                    <do_if value="$pmDstRatio le 5">
                      <set_value name="$pmBucket" exact="'A (critical &lt;=5%)'"/>
                    </do_if>
                    <do_elseif value="$pmDstRatio le 20">
                      <set_value name="$pmBucket" exact="'B (urgent &lt;=20%)'"/>
                    </do_elseif>
                    <do_elseif value="$pmDstRatio le $mk2MinStorage">
                      <set_value name="$pmBucket" exact="'C (need &lt;=' + $mk2MinStorage + '% minStorage)'"/>
                    </do_elseif>
                    <do_elseif value="$pmSrcRatio gt $mk2MaxStorage and $pmSrcRatio gt ($pmDstRatio + 10)">
                      <set_value name="$pmBucket" exact="'D (rebalance: src ' + $pmSrcRatio + '% &gt; ' + $mk2MaxStorage + '% max and gt dst ' + $pmDstRatio + '% +10)'"/>
                    </do_elseif>
                    <do_else>
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmReason2" exact="'noNeed: dst ' + $pmDstCount + '/' + $pmDstTarget + ' = ' + $pmDstRatio + '% is above ' + $mk2MinStorage + '% minStorage and src ' + $pmSrcRatio + '% does not trigger the rebalance bucket (src must be &gt;' + $mk2MaxStorage + '% maxStorage AND &gt;dst+10)'"/>
                      <set_value name="$mk2PairSkipNoNeed" operation="add"/>
                    </do_else>
                  </do_if>

                  <!-- Gate 9: minimum trade amount (skipMinTrade, runtime line 1659).
                       Use a 1-unit floor here - the diag does not have access to
                       this.$minCargoFillPercent or low-volume profile, so we report PASS
                       whenever the engine could move at least 1 unit. The runtime check
                       is added to the reason string when the trade would be tiny. -->
                  <set_value name="$pmTradeAmount" exact="0"/>
                  <do_if value="$pmStatus2 == 'PASS'">
                    <set_value name="$pmTradeAmount" exact="[$pmShipCargoMax, $pmSrcOfferAmount, $pmDstOfferAmount].min"/>
                    <do_if value="$pmTradeAmount le 0">
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmReason2" exact="'minTrade: computed trade amount is 0 (cargo room ' + $pmShipCargoMax + ', src offer ' + $pmSrcOfferAmount + ', dst demand ' + $pmDstOfferAmount + ')'"/>
                      <set_value name="$mk2PairSkipMinTrade" operation="add"/>
                    </do_if>
                  </do_if>

                  <!-- Gate 10: Illegal Route Filter (route_legality parity, runtime queue gate) -->
                  <do_if value="$pmStatus2 == 'PASS' and $mk2OrderAllowIllegal and $mk2OrderEnforceRouteIllegal and @$pmWare.illegal gt 0">
                    <set_value name="$mk2RouteHome" exact="if $homeSector? and $homeSector.exists then $homeSector else $pmSrc.sector"/>
                    <run_actions ref="md.GT_Libraries_Pathfinding.GT_CheckRouteLegality" result="$pmRouteLegality">
                      <param name="ship" value="$ship"/>
                      <param name="homeSector" value="$mk2RouteHome"/>
                      <param name="buySector" value="$pmSrc.sector"/>
                      <param name="sellSector" value="$pmDst.sector"/>
                      <param name="ware" value="$pmWare"/>
                      <param name="allowIllegal" value="$mk2OrderAllowIllegal"/>
                      <param name="enforceRouteIllegalLegality" value="$mk2OrderEnforceRouteIllegal"/>
                      <param name="blacklistgroup" value="$blacklistgroup"/>
                      <param name="startSector" value="$ship.sector"/>
                    </run_actions>
                    <do_if value="not $pmRouteLegality.$IsLegal">
                      <set_value name="$pmStatus2" exact="'BLOCK'"/>
                      <set_value name="$pmRlSector" exact="if $pmRouteLegality.$BlockedSectorName? and $pmRouteLegality.$BlockedSectorName != '' then $pmRouteLegality.$BlockedSectorName else 'unknown sector'"/>
                      <set_value name="$pmRlPolice" exact="if $pmRouteLegality.$BlockedPoliceName? and $pmRouteLegality.$BlockedPoliceName != '' then $pmRouteLegality.$BlockedPoliceName else 'unknown police'"/>
                      <set_value name="$pmReason2" exact="'route_illegal: ' + $pmWare.name + ' illegal in ' + $pmRlSector + ' (police=' + $pmRlPolice + ')'"/>
                      <set_value name="$mk2PairSkipRouteIllegal" operation="add"/>
                    </do_if>
                  </do_if>

                  <do_if value="$pmStatus2 == 'PASS'">
                    <set_value name="$pmReason2" exact="'eligible: bucket=' + $pmBucket + ' src=' + $pmSrcRatio + '% dst=' + $pmDstRatio + '% trade=' + $pmTradeAmount + ' units (final amount may be lower after fairness/reservation)'"/>
                    <set_value name="$mk2PairPass" operation="add"/>
                    <do_if value="$mk2FirstPassPair == ''">
                      <set_value name="$mk2FirstPassPair" exact="$pmWare.name + ': ' + $pmRoute2"/>
                    </do_if>
                  </do_if>

                  <set_value name="$mk2PairCount" operation="add"/>
                  <do_if value="$mk2PairRows.count lt $mk2RowCap">
                    <append_to_list name="$mk2PairRows" exact="table[$Check = $pmWare.name, $Status = $pmStatus2, $Detail = $pmRoute2, $Col4 = 'src ' + $pmSrcRatio + '% / dst ' + $pmDstRatio + '%', $Col5 = (if $pmDist ge 0 then ('' + $pmDist + ' gates') else ''), $Col6 = $pmReason2]"/>
                  </do_if>
                </do_all>
              </do_all>
            </do_all>
          </do_if>

          <!-- Header row + skip summary so the player can read the picture at a glance. -->
          <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'MK2 Pairs Evaluated', $Status = if $mk2PairPass gt 0 then 'PASS' else (if $mk2PairCount == 0 then 'WARN' else 'FAIL'), $Detail = '' + $mk2PairCount + ' src*dst*ware combinations checked, ' + $mk2PairPass + ' PASS, ' + ($mk2PairCount - $mk2PairPass) + ' BLOCK (showing first ' + $mk2PairRows.count + ')']"/>
          <do_if value="$mk2NoBasketWares">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'No Pairs', $Status = 'WARN', $Detail = 'No source/destination stations configured (see MK2 Specific section)']"/>
          </do_if>
          <do_if value="$mk2PairCount gt 0">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Skip Breakdown', $Status = 'INFO', $Detail = 'illegal/cargo=' + $mk2PairSkipIllegal + ', routeIllegal=' + $mk2PairSkipRouteIllegal + ', noSrcOffer=' + $mk2PairSkipNoSrc + ', srcNoTarget=' + $mk2PairSkipSrcNoTarget + ', srcBelowStatic=' + $mk2PairSkipBelowStatic + ', self=' + $mk2PairSkipSelf + ', distance=' + $mk2PairSkipDistance + ', noDstOffer=' + $mk2PairSkipNoDst + ', noNeed=' + $mk2PairSkipNoNeed + ', minTrade=' + $mk2PairSkipMinTrade]"/>
          </do_if>
          <do_all exact="$mk2PairRows.count" counter="$pmri">
            <append_to_list name="$sec8b.$Rows" exact="$mk2PairRows.{$pmri}"/>
          </do_all>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyTraderMK1'">
          <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'MK1 Export Pairs', $Status = if $passCount gt 0 then 'PASS' else (if $pairCount == 0 then 'WARN' else 'FAIL'), $Detail = '' + $pairCount + ' home-station export Ã— buyer pairs checked, ' + $passCount + ' PASS (showing first ' + $pairDetails.count + ' rows)']"/>
          <do_if value="not $mk1DiagHome? or not $mk1DiagHome.exists">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'No Home Station', $Status = 'FAIL', $Detail = 'MK1 requires a home station â€” assign one on the order']"/>
          </do_if>
          <do_elseif value="$mk1DiagEffectiveWares? and $mk1DiagEffectiveWares.count == 0">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'No Export Wares', $Status = 'FAIL', $Detail = 'No wares pass cargo/illegal filters and export storage gate (Min Product Storage % = ' + $mk1DiagMinSellStorage + ')']"/>
          </do_elseif>
          <do_all exact="$pairDetails.count" counter="$m1pi">
            <append_to_list name="$sec8b.$Rows" exact="$pairDetails.{$m1pi}"/>
          </do_all>
        </do_elseif>
        <do_else>
          <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'Pairs Evaluated', $Status = 'INFO', $Detail = '' + $pairCount + ' scanned, ' + $pairDetails.count + ' shown (' + $passCount + ' PASS, ' + ($pairCount - $passCount) + ' FAIL â€” verdict + reason shown per row)']"/>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2')">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'MK4 Pair Legend', $Status = 'INFO', $Detail = 'Every evaluated supply pair is listed with the per-ship verdict + reason. PASS = executable now; FAIL = rejected (e.g. mk4_trade_rules = customer build storage disallows the source faction). [player]/[NPC] = supplier ownership.']"/>
          </do_if>
          <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
            <append_to_list name="$sec8b.$Rows" exact="table[$Check = 'IPP Pair Legend', $Status = 'INFO', $Detail = '[IPP] = player-owned supplier; buy cost scored as zero; profit/ROI/money gates bypassed. [NPC] = non-player supplier. Runtime still picks highest score overall.']"/>
          </do_if>
          <do_all exact="$pairDetails.count" counter="$pi">
            <append_to_list name="$sec8b.$Rows" exact="$pairDetails.{$pi}"/>
          </do_all>
        </do_else>
        <append_to_list name="$report.$Sections" exact="$sec8b"/>
        </do_if>

        <!-- ======================================================== -->
        <!-- SECTION: Clearance Analysis                               -->
        <!-- When the ship has cargo, evaluates ALL potential buyers    -->
        <!-- for each ware the ship is carrying, with per-station      -->
        <!-- rejection reasons. This is what the ship sees when it     -->
        <!-- tries to sell its current cargo in clearance mode.         -->
        <!-- ======================================================== -->
        <!-- Initialize clearance totals (safe defaults for VERDICT) -->
        <set_value name="$clTotalBuyers" exact="0"/>
        <set_value name="$clTotalPass" exact="0"/>
        <set_value name="$clTotalIllegal" exact="0"/>
        <do_if value="$cargoUsed gt 0">
          <set_value name="$secCL" exact="table[]"/>
          <set_value name="$secCL.$Name" exact="'Clearance'"/>
          <set_value name="$secCL.$Rows" exact="[]"/>

          <append_to_list name="$secCL.$Rows" exact="table[$Check = 'Mode', $Status = 'WARN', $Detail = 'Ship has cargo (' + $cargoUsed + '/' + $cargoCap + ' used). In clearance mode, the ship must sell ALL existing cargo before it can search for new buy trades.']"/>

          <!-- Iterate each ware the ship is carrying -->
          <do_all exact="$ship.cargo.list.count" counter="$clwi">
            <set_value name="$clWare" exact="$ship.cargo.list.{$clwi}"/>
            <do_if value="$clWare? and $ship.cargo.{$clWare}.count gt 0 and (($orderId != 'GalaxyMiner') or $clWare.hastag.minable)">
              <set_value name="$clWareAmount" exact="$ship.cargo.{$clWare}.count"/>
              <append_to_list name="$secCL.$Rows" exact="table[$Check = '--- ' + $clWare.name + ' ---', $Status = 'INFO', $Detail = 'Carrying ' + $clWareAmount + ' units (volume: ' + $clWare.volume + '/unit)']"/>

              <!-- Find all buy offers for this ware in search sectors -->
              <set_value name="$clBuyerCount" exact="0"/>
              <set_value name="$clPassCount" exact="0"/>

              <do_all exact="$searchSectors.count" counter="$clsi">
                <set_value name="$clSector" exact="$searchSectors.{$clsi}"/>

                <!-- Find buy offers for this specific ware (with price range filter).
                     MINER PATH: drop the over-restrictive engine matchers (match_buyer/
                     offeramount/relativeprice) that the actual miner AI's find_buy_offer
                     never applies - see gt_context_diagnose.xml section 8 fix and
                     order.mining.routine.gt.xml:824 for rationale. The per-station
                     evaluation below already enforces the relevant gates (player-only,
                     primary, overflow threshold, dock size, blacklist) with explicit
                     verdict + reason strings, so dropping the engine pre-filter does NOT
                     hide rejection causes - it surfaces them. -->
                <do_if value="$orderId == 'GalaxyMiner'">
                  <find_buy_offer wares="[$clWare]" tradepartner="$ship" space="$clSector" result="$clBuyOffers" multiple="true"/>
                </do_if>
                <do_elseif value="$ignoreTradeRules">
                  <find_buy_offer wares="[$clWare]" tradepartner="$ship" space="$clSector" result="$clBuyOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$ship"/>
                    <relativeprice min="$activeBuyPriceMin" tradepartner="if $ship.isplayerowned then $ship else null"/>
                  </find_buy_offer>
                </do_elseif>
                <do_else>
                  <find_buy_offer wares="[$clWare]" tradepartner="$ship" space="$clSector" result="$clBuyOffers" multiple="true">
                    <match_buyer tradesknownto="$ship.owner">
                      <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                      <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                    </match_buyer>
                    <offeramount min="1" tradepartner="$ship"/>
                    <relativeprice min="$activeBuyPriceMin" tradepartner="if $ship.isplayerowned then $ship else null"/>
                  </find_buy_offer>
                </do_else>

                <do_if value="$clBuyOffers? and $clBuyOffers.count?">
                  <do_all exact="$clBuyOffers.count" counter="$clbi">
                    <set_value name="$clOffer" exact="$clBuyOffers.{$clbi}"/>
                    <do_if value="not $clOffer.exists">
                      <continue/>
                    </do_if>
                    <set_value name="$clBuyerCount" operation="add"/>
                    <set_value name="$clTotalBuyers" operation="add"/>
                    <set_value name="$clStation" exact="$clOffer.owner"/>
                    <set_value name="$clStationName" exact="@$clStation.knownname"/>
                    <do_if value="not $clStationName?">
                      <set_value name="$clStationName" exact="'???'"/>
                    </do_if>

                    <!-- Evaluate this buyer -->
                    <set_value name="$clVerdict" exact="'PASS'"/>
                    <set_value name="$clReason" exact="''"/>
                    <set_value name="$clPrice" exact="$clOffer.unitprice"/>
                    <set_value name="$clDemand" exact="$clOffer.offeramount.{$ship}"/>
                    <do_if value="$clDemand == null">
                      <set_value name="$clDemand" exact="$clOffer.amount"/>
                    </do_if>
                    <do_if value="$clDemand == null">
                      <set_value name="$clDemand" exact="0"/>
                    </do_if>
                    <set_value name="$clTradeAmount" exact="[$clWareAmount, $clDemand].min"/>

                    <!-- Miner policy checks (player-only, primary targets, overflow threshold) -->
                    <do_if value="$clVerdict == 'PASS' and $orderId == 'GalaxyMiner'">
                      <set_value name="$clIsPrimary" exact="false"/>
                      <do_if value="$diagMinerPrimaryStations.count gt 0">
                        <do_all exact="$diagMinerPrimaryStations.count" counter="$dpsi">
                          <do_if value="$diagMinerPrimaryStations.{$dpsi}? and $diagMinerPrimaryStations.{$dpsi}.exists and $diagMinerPrimaryStations.{$dpsi} == $clStation">
                            <set_value name="$clIsPrimary" exact="true"/>
                            <break/>
                          </do_if>
                        </do_all>
                      </do_if>
                      <do_if value="$diagMinerPlayerStationsOnly and not $clStation.isplayerowned">
                        <set_value name="$clVerdict" exact="'FAIL'"/>
                        <set_value name="$clReason" exact="'playerStationsOnly: non-player station excluded'"/>
                      </do_if>
                      <set_value name="$clWareOverflowMode" exact="false"/>
                      <do_if value="$diagMinerWareHasPrimaryCapacity? and $diagMinerWareHasPrimaryCapacity.{$clWare}?">
                        <do_if value="not $diagMinerWareHasPrimaryCapacity.{$clWare}">
                          <set_value name="$clWareOverflowMode" exact="true"/>
                        </do_if>
                      </do_if>
                      <!-- Primary delivery path (ware still has capacity at a primary station). -->
                      <do_if value="$clVerdict == 'PASS' and not $clWareOverflowMode">
                        <do_if value="not $clIsPrimary">
                          <set_value name="$clVerdict" exact="'FAIL'"/>
                          <set_value name="$clReason" exact="'not in primary target stations'"/>
                        </do_if>
                        <do_else>
                          <set_value name="$clTargetAmount" exact="$clStation.cargo.{$clWare}.target"/>
                          <do_if value="$clTargetAmount le 0">
                            <set_value name="$clVerdict" exact="'FAIL'"/>
                            <set_value name="$clReason" exact="'station target amount is 0 for ware'"/>
                          </do_if>
                          <do_else>
                            <set_value name="$clStoragePercent" exact="($clStation.cargo.{$clWare}.count * 100) / [$clTargetAmount, 1].max"/>
                            <do_if value="$clStoragePercent ge $diagMinerOverflowThreshold">
                              <set_value name="$clVerdict" exact="'FAIL'"/>
                              <set_value name="$clReason" exact="'at/above overflow threshold (' + $clStoragePercent + '% >= ' + $diagMinerOverflowThreshold + '%)'"/>
                            </do_if>
                          </do_else>
                        </do_else>
                      </do_if>
                      <!-- Overflow sell path (mirrors offer scan / runtime sellwares policy). -->
                      <do_elseif value="$clVerdict == 'PASS' and $clWareOverflowMode">
                        <do_if value="not $diagMinerAllowOverflowSellToOthers">
                          <set_value name="$clVerdict" exact="'FAIL'"/>
                          <set_value name="$clReason" exact="'overflow at primary but sell-to-others disabled'"/>
                        </do_if>
                        <do_elseif value="$diagMinerPlayerStationsOnly">
                          <do_if value="not $clStation.isplayerowned or $clIsPrimary">
                            <set_value name="$clVerdict" exact="'FAIL'"/>
                            <set_value name="$clReason" exact="'overflow player-only requires non-primary player station'"/>
                          </do_if>
                        </do_elseif>
                      </do_elseif>
                    </do_if>

                    <!-- Check 1: Station operational -->
                    <do_if value="not $clStation.isoperational">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'station not operational'"/>
                    </do_if>

                    <!-- Check 2: Dock feasibility -->
                    <do_if value="$clVerdict == 'PASS'">
                      <run_actions ref="md.GT_Libraries_General.GT_CanDockForTrade" result="$clDockResult">
                        <param name="station" value="$clStation"/>
                        <param name="ship" value="$ship"/>
                        <param name="allowStorageDock" value="false"/>
                      </run_actions>
                      <do_if value="not $clDockResult.$CanDock">
                        <set_value name="$clVerdict" exact="'FAIL'"/>
                        <set_value name="$clReason" exact="'no compatible dock for ship size ' + $ship.docksize"/>
                      </do_if>
                    </do_if>

                    <!-- Check 3: Runtime station-class exclusions -->
                    <do_if value="$clVerdict == 'PASS' and $ignoreBuildStorage and $clStation.isbuildstorage">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'build storage excluded'"/>
                    </do_if>
                    <do_if value="$clVerdict == 'PASS' and $ignoreCarrierAux and $clStation.isclass.ship and ($clStation.type == shiptype.carrier or $clStation.type == shiptype.resupplier)">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'carrier/aux excluded'"/>
                    </do_if>
                    <do_if value="$clVerdict == 'PASS' and $ignoreMK1Supply and global.$GT_MK1SuppliedStations? and global.$GT_MK1SuppliedStations.{$clStation}?">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'already supplied by MK1 (excluded)'"/>
                    </do_if>

                    <!-- Check 4: Distance -->
                    <do_if value="$clVerdict == 'PASS'">
                      <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$clDist">
                        <param name="ship" value="$ship"/>
                        <param name="fromSector" value="if $homeSector? and $homeSector.exists then $homeSector else $ship.sector"/>
                        <param name="toSector" value="$clStation.sector"/>
                        <param name="blacklistgroup" value="$diagBlacklistGroup"/>
                        <param name="useEscapeMode" value="false"/>
                      </run_actions>
                      <do_if value="$clDist lt 0">
                        <set_value name="$clVerdict" exact="'FAIL'"/>
                        <set_value name="$clReason" exact="'unreachable (no path or blocked by blacklist)'"/>
                      </do_if>
                      <do_elseif value="$maxSell gt 0 and $clDist gt $maxSell">
                        <set_value name="$clVerdict" exact="'FAIL'"/>
                        <set_value name="$clReason" exact="'too far (' + $clDist + ' jumps, max sell distance: ' + $maxSell + ')'"/>
                      </do_elseif>
                    </do_if>

                    <!-- Check 5: Blacklist (sector) -->
                    <do_if value="$clVerdict == 'PASS' and $diagBlacklistGroup?">
                      <set_value name="$clSectorBL" exact="@$clStation.sector.isblacklisted.{blacklisttype.sectoractivity}.{$diagBlacklistGroup}.{$ship}"/>
                      <do_if value="$clSectorBL">
                        <set_value name="$clVerdict" exact="'FAIL'"/>
                        <set_value name="$clReason" exact="'station sector blacklisted (activity)'"/>
                      </do_if>
                    </do_if>

                    <!-- Check 6: Blacklist (station) -->
                    <do_if value="$clVerdict == 'PASS' and $diagBlacklistGroup?">
                      <set_value name="$clStationBL" exact="@$clStation.isblacklisted.{blacklisttype.objectactivity}.{$diagBlacklistGroup}.{$ship}"/>
                      <do_if value="$clStationBL">
                        <set_value name="$clVerdict" exact="'FAIL'"/>
                        <set_value name="$clReason" exact="'station itself is blacklisted'"/>
                      </do_if>
                    </do_if>

                    <!-- Check 7: Demand amount -->
                    <do_if value="$clVerdict == 'PASS' and $clDemand le 0">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'station has no demand (0 units wanted)'"/>
                    </do_if>

                    <!-- Check 8: Price sanity -->
                    <do_if value="$clVerdict == 'PASS' and $clPrice le 0">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'station offers 0 Cr per unit'"/>
                    </do_if>

                    <!-- Check 9: Illegal ware (matches execution-time check in gt_trading_execution.xml) -->
                    <do_if value="$clVerdict == 'PASS' and not $allowIllegal and @$clWare.illegal gt 0">
                      <set_value name="$clVerdict" exact="'FAIL'"/>
                      <set_value name="$clReason" exact="'ware is illegal to a faction (AllowIllegal: false)'"/>
                      <set_value name="$clTotalIllegal" operation="add"/>
                    </do_if>

                    <!-- Build structured multi-column data for buyer -->
                    <!-- Fields: Status || Ware || Station (Sector) || Price/Demand || Revenue/Dist || Reason -->
                    <do_if value="$clVerdict == 'PASS'">
                      <set_value name="$clPassCount" operation="add"/>
                      <set_value name="$clTotalPass" operation="add"/>
                      <set_value name="$clRevenue" exact="$clPrice * $clTradeAmount"/>
                      <set_value name="$clDistStr" exact="''"/>
                      <do_if value="$clDist?">
                        <set_value name="$clDistStr" exact="' (' + $clDist + 'j)'"/>
                      </do_if>
                    </do_if>
                    <do_else>
                      <set_value name="$clRevenue" exact="0"/>
                      <set_value name="$clDistStr" exact="''"/>
                    </do_else>
                    <set_value name="$clStationFull" exact="$clStationName + ' (' + $clSector.knownname + ')'"/>
                    <set_value name="$clPriceDemand" exact="($clPrice / 100) + 'Cr x' + $clDemand"/>
                    <set_value name="$clRevenueStr" exact="($clRevenue / 100) + 'Cr' + $clDistStr"/>
                    <set_value name="$clReasonStr" exact="''"/>
                    <do_if value="$clVerdict != 'PASS'">
                      <set_value name="$clReasonStr" exact="$clReason"/>
                    </do_if>
                    <append_to_list name="$secCL.$Rows" exact="table[$Check = $clWare.name, $Status = $clVerdict, $Detail = $clStationFull, $Col4 = $clPriceDemand, $Col5 = $clRevenueStr, $Col6 = $clReasonStr]"/>
                  </do_all>
                </do_if>
                <do_else>
                  <append_to_list name="$secCL.$Rows" exact="table[$Check = $clWare.name, $Status = 'WARN', $Detail = 'Sector: ' + $clSector.knownname, $Col4 = '-', $Col5 = '-', $Col6 = 'No buy offers found in this sector for this ware (after current filters).']"/>
                </do_else>
              </do_all>

              <!-- Summary for this ware -->
              <set_value name="$clWareResult" exact="if $clPassCount gt 0 then 'PASS' else 'FAIL'"/>
              <append_to_list name="$secCL.$Rows" exact="table[$Check = $clWare.name + ' Summary', $Status = $clWareResult, $Detail = '' + $clPassCount + ' viable buyers out of ' + $clBuyerCount + ' total offers found']"/>
              <do_if value="$orderId == 'GalaxyMiner'">
                <set_value name="$diagMinerWareViableBuyers.{$clWare}" exact="$clPassCount"/>
              </do_if>
            </do_if>
          </do_all>

          <!-- Miner cargo sellability (all fill levels): track unsellable dead weight vs sellable cargo. -->
          <do_if value="$orderId == 'GalaxyMiner' and $cargoUsed gt 0">
            <set_value name="$diagMinerUnsellableParts" exact="''"/>
            <set_value name="$diagMinerCargoWareCount" exact="0"/>
            <set_value name="$diagMinerCargoSellableWareCount" exact="0"/>
            <do_all exact="$ship.cargo.list.count" counter="$mcwi">
              <set_value name="$mcWare" exact="$ship.cargo.list.{$mcwi}"/>
              <do_if value="$mcWare? and $mcWare.hastag.minable and $ship.cargo.{$mcWare}.count gt 0">
                <set_value name="$diagMinerCargoWareCount" operation="add"/>
                <set_value name="$mcViable" exact="0"/>
                <do_if value="$diagMinerWareViableBuyers.{$mcWare}?">
                  <set_value name="$mcViable" exact="$diagMinerWareViableBuyers.{$mcWare}"/>
                </do_if>
                <set_value name="$mcVolumeUsed" exact="$ship.cargo.{$mcWare}.count * $mcWare.volume"/>
                <set_value name="$mcBayPct" exact="($mcVolumeUsed * 100) / [$cargoCap, 1].max"/>
                <set_value name="$mcCargoLabel" exact="$mcWare.name + ' x' + $ship.cargo.{$mcWare}.count + ' (~' + $mcBayPct + '% bay)'"/>
                <do_if value="$mcViable gt 0">
                  <set_value name="$diagMinerCargoSellableWareCount" operation="add"/>
                </do_if>
                <do_else>
                  <do_if value="$diagMinerUnsellableParts != ''">
                    <set_value name="$diagMinerUnsellableParts" exact="$diagMinerUnsellableParts + ', '"/>
                  </do_if>
                  <set_value name="$diagMinerUnsellableParts" exact="$diagMinerUnsellableParts + $mcCargoLabel"/>
                </do_else>
              </do_if>
            </do_all>
            <do_if value="$diagMinerUnsellableParts != ''">
              <set_value name="$diagMinerHasUnsellableCargo" exact="true"/>
              <set_value name="$diagMinerUnsellableCargoDetail" exact="$diagMinerUnsellableParts"/>
            </do_if>
            <do_if value="$cargoCap gt 0 and $cargoFree le 0 and $diagMinerCargoWareCount gt 0">
              <set_value name="$diagMinerFullBayNeedsClearance" exact="true"/>
              <do_if value="$diagMinerCargoSellableWareCount == 0">
                <set_value name="$diagMinerCargoBlocksMining" exact="true"/>
                <set_value name="$diagMinerCargoBlockDetail" exact="$diagMinerUnsellableCargoDetail"/>
              </do_if>
            </do_if>
          </do_if>

          <!-- Active sell/delivery leg: runtime may already have queued a trade or be
               docking/in transit while static clearance scans still show 0 policy matches. -->
          <do_if value="$orderId == 'GalaxyMiner' and $cargoUsed gt 0">
            <set_value name="$diagMinerImmOrder" exact="if $ship.order? then @$ship.order.id else null"/>
            <do_if value="$ship.tradeorders? and $ship.tradeorders.count gt 0">
              <set_value name="$diagMinerOnSellRun" exact="true"/>
              <set_value name="$diagTo0" exact="$ship.tradeorders.{1}"/>
              <set_value name="$diagMinerSellRunDetail" exact="'queued trade: ' + (if $diagTo0? and $diagTo0.ware? and $diagTo0.ware.name? then @$diagTo0.ware.name else '?') + ' x' + (if $diagTo0? and $diagTo0.amount? then $diagTo0.amount else '?') + ' -> ' + (if $diagTo0? and $diagTo0.buyer? and $diagTo0.buyer.exists then @$diagTo0.buyer.knownname else '?')"/>
            </do_if>
            <do_if value="not $diagMinerOnSellRun and $diagMinerImmOrder?">
              <do_if value="$diagMinerImmOrder == 'TradePerform' or $diagMinerImmOrder == 'TradeSell' or $diagMinerImmOrder == 'DockAt' or $diagMinerImmOrder == 'DockAndWait'">
                <set_value name="$diagMinerOnSellRun" exact="true"/>
                <set_value name="$diagMinerSellRunDetail" exact="'immediate order: ' + $diagMinerImmOrder"/>
              </do_if>
              <do_elseif value="$cargoFree le 0 and ($diagMinerImmOrder == 'MoveToZone' or $diagMinerImmOrder == 'FlyToZone' or $diagMinerImmOrder == 'MoveWait' or $diagMinerImmOrder == 'Jump' or $diagMinerImmOrder == 'UseElevator' or $diagMinerImmOrder == 'MoveToObject')">
                <set_value name="$diagMinerOnSellRun" exact="true"/>
                <set_value name="$diagMinerSellRunDetail" exact="'in transit (full bay): ' + $diagMinerImmOrder"/>
              </do_elseif>
            </do_if>
            <do_if value="not $diagMinerOnSellRun and global.$GT_MinerIntents? and global.$GT_MinerIntents.keys.count gt 0">
              <do_all exact="global.$GT_MinerIntents.keys.count" counter="$msellsi">
                <do_if value="not $diagMinerOnSellRun">
                  <set_value name="$msellStation" exact="global.$GT_MinerIntents.keys.{$msellsi}"/>
                  <do_if value="global.$GT_MinerIntents.{$msellStation}? and global.$GT_MinerIntents.{$msellStation}.keys.count gt 0">
                    <do_all exact="global.$GT_MinerIntents.{$msellStation}.keys.count" counter="$msellwi">
                      <do_if value="not $diagMinerOnSellRun">
                        <set_value name="$msellWare" exact="global.$GT_MinerIntents.{$msellStation}.keys.{$msellwi}"/>
                        <do_if value="global.$GT_MinerIntents.{$msellStation}.{$msellWare}? and global.$GT_MinerIntents.{$msellStation}.{$msellWare}.{$ship}?">
                          <set_value name="$msellIntent" exact="global.$GT_MinerIntents.{$msellStation}.{$msellWare}.{$ship}"/>
                          <do_if value="$msellIntent? and $msellIntent.$phase? and ($msellIntent.$phase == 'delivering' or ($msellIntent.$phase == 'hauling' and $cargoFree le 0))">
                            <set_value name="$diagMinerOnSellRun" exact="true"/>
                            <set_value name="$diagMinerSellRunDetail" exact="'fleet intent phase: ' + $msellIntent.$phase + ' -> ' + (if $msellStation? and $msellStation.exists then @$msellStation.knownname else '?')"/>
                          </do_if>
                        </do_if>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $diagMinerOnSellRun and global.$GT_MinerDiag? and global.$GT_MinerDiag.{$ship}? and global.$GT_MinerDiag.{$ship}.$IntentPhase?">
              <set_value name="$diagMinerSnapPhase" exact="'' + global.$GT_MinerDiag.{$ship}.$IntentPhase"/>
              <do_if value="$diagMinerSnapPhase == 'delivering' or ($diagMinerSnapPhase == 'hauling' and $cargoFree le 0)">
                <set_value name="$diagMinerOnSellRun" exact="true"/>
                <set_value name="$diagMinerSellRunDetail" exact="'snapshot intent phase: ' + $diagMinerSnapPhase"/>
              </do_if>
            </do_if>
          </do_if>

          <append_to_list name="$report.$Sections" exact="$secCL"/>
        </do_if>

        <!-- ======================================================== -->
        <!-- SECTION 9: Reservations & Route Conflicts                -->
        <!-- ======================================================== -->
        <set_value name="$sec9" exact="table[]"/>
        <set_value name="$sec9.$Name" exact="'Reservations and Fleet'"/>
        <set_value name="$sec9.$Rows" exact="[]"/>

        <!-- Active reservations dump -->
        <set_value name="$totalReservations" exact="0"/>
        <do_if value="global.$GT_Reservations?">
          <set_value name="$resKeys" exact="global.$GT_Reservations.keys.list"/>
          <set_value name="$totalReservations" exact="$resKeys.count"/>
          <set_value name="$activeRes" exact="0"/>
          <do_all exact="$totalReservations" counter="$ri">
            <set_value name="$resKey" exact="$resKeys.{$ri}"/>
            <set_value name="$resData" exact="@global.$GT_Reservations.{$resKey}"/>
            <do_if value="$resData?">
              <set_value name="$resExpiry" exact="@$resData.$Until"/>
              <set_value name="$resShip" exact="@$resData.$Ship"/>
              <set_value name="$resActive" exact="$resExpiry? and player.age lt $resExpiry"/>
              <do_if value="$resActive">
                <set_value name="$activeRes" operation="add"/>
                <set_value name="$resShipName" exact="if $resShip? and $resShip.exists then ($resShip.idcode + ' (' + $resShip.knownname + ')') else '???'"/>
                <set_value name="$resTTL" exact="$resExpiry - player.age"/>
                <set_value name="$resWareName" exact="'Unknown'"/>
                <do_if value="$resKey? and @$resKey.ware != null and @$resKey.ware.name != null">
                  <set_value name="$resWareName" exact="@$resKey.ware.name"/>
                </do_if>
                <append_to_list name="$sec9.$Rows" exact="table[
                  $Check = 'Reservation #' + $ri,
                  $Status = if $resShip == $ship then 'PASS' else 'INFO',
                  $Detail = $resShipName + (if $resShip == $ship then ' (THIS SHIP)' else ''),
                  $Col4 = $resWareName,
                  $Col5 = 'TTL=' + $resTTL + 's',
                  $Col6 = 'Key=' + $resKey
                ]"/>
              </do_if>
            </do_if>
          </do_all>
          <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Total Reservations', $Status = 'INFO', $Detail = '' + $totalReservations + ' total, ' + $activeRes + ' active']"/>
        </do_if>
        <do_else>
          <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Reservations', $Status = 'INFO', $Detail = 'No reservation system initialized']"/>
        </do_else>

        <!-- Cumulative reservation statistics (shows lifetime activity even when table is currently empty).
             Reservations have a 10s TTL and are cleared immediately after create_trade_order,
             so the table is almost always empty. These stats prove the system is working. -->
        <do_if value="global.$GT_ReservationStats?">
          <set_value name="$rsCreated"  exact="@global.$GT_ReservationStats.$Created"/>
          <set_value name="$rsCleared"  exact="@global.$GT_ReservationStats.$Cleared"/>
          <set_value name="$rsExpired"  exact="@global.$GT_ReservationStats.$Expired"/>
          <set_value name="$rsConflicts" exact="@global.$GT_ReservationStats.$Conflicts"/>
          <append_to_list name="$sec9.$Rows" exact="table[
            $Check = 'Reservation Stats (Lifetime)',
            $Status = if ($rsCreated? and $rsCreated gt 0) then 'PASS' else 'WARN',
            $Detail = 'Created: ' + (if $rsCreated? then $rsCreated else 0) + ' | Cleared: ' + (if $rsCleared? then $rsCleared else 0) + ' | Expired: ' + (if $rsExpired? then $rsExpired else 0) + ' | Conflicts: ' + (if $rsConflicts? then $rsConflicts else 0)
          ]"/>
        </do_if>
        <do_else>
          <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Reservation Stats', $Status = 'WARN', $Detail = 'No stats available (system may not have initialized)']"/>
        </do_else>

        <!-- Active trades (authoritative runtime source).
             global.$GT_ActiveTrade is written by MK3 AI right before native trade order creation
             and cleared when the order exits. -->
        <set_value name="$activeTradingShips" exact="[]"/>
        <set_value name="$activeTradeSourceInfo" exact="'none'"/>
        <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.keys.count gt 0">
          <set_value name="$activeTradeSourceInfo" exact="'global.$GT_ActiveTrade (' + global.$GT_ActiveTrade.keys.count + ' keys)'"/>
          <set_value name="$atrKeys" exact="global.$GT_ActiveTrade.keys.list"/>
          <do_all exact="$atrKeys.count" counter="$ai">
            <set_value name="$atrShip" exact="$atrKeys.{$ai}"/>
            <do_if value="$atrShip? and $atrShip.exists and $atrShip.isoperational">
              <set_value name="$atrData" exact="@global.$GT_ActiveTrade.{$atrShip}"/>
              <set_value name="$tradeSource" exact="'active trade pipeline'"/>
              <set_value name="$tradeWareName" exact="'Unknown'"/>
              <do_if value="$atrData? and $atrData.$Ware?">
                <set_value name="$tradeWareName" exact="$atrData.$Ware.name"/>
                <set_value name="$tradeSource" exact="$tradeSource + ' | Ware=' + $atrData.$Ware.name"/>
              </do_if>
              <append_to_list name="$activeTradingShips" exact="table[$Ship = $atrShip, $Source = $tradeSource, $Ware = $tradeWareName]"/>
            </do_if>
          </do_all>
        </do_if>
        <do_elseif value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <!-- Fallback for older saves/mod versions where $GT_ActiveTrade may not be initialized yet -->
          <set_value name="$activeTradeSourceInfo" exact="'fallback: current trade orders via global.$GT_Ships (' + global.$GT_Ships.keys.count + ' ships)'"/>
          <set_value name="$atrKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$atrKeys.count" counter="$ai">
            <set_value name="$atrShip" exact="$atrKeys.{$ai}"/>
            <do_if value="$atrShip? and $atrShip.exists and $atrShip.isoperational and $atrShip.order? and (@$atrShip.order.id == 'TradePerform' or @$atrShip.order.id == 'TradeBuy' or @$atrShip.order.id == 'TradeSell')">
              <append_to_list name="$activeTradingShips" exact="table[$Ship = $atrShip, $Source = 'fallback current order: ' + @$atrShip.order.id, $Ware = 'Unknown (fallback)']"/>
            </do_if>
          </do_all>
        </do_elseif>
        <set_value name="$atrCount" exact="$activeTradingShips.count"/>
        <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Ships With Active Trades', $Status = if $atrCount gt 0 then 'PASS' else 'WARN', $Detail = '' + $atrCount]"/>
        <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Active Trade Source', $Status = 'INFO', $Detail = $activeTradeSourceInfo]"/>
        <do_all exact="$atrCount" counter="$ai">
          <set_value name="$atrEntry" exact="$activeTradingShips.{$ai}"/>
          <do_if value="$atrEntry? and $atrEntry.$Ship? and $atrEntry.$Ship.exists">
            <set_value name="$atrDetail" exact="$atrEntry.$Ship.idcode + ' (' + $atrEntry.$Ship.knownname + ')'"/>
            <set_value name="$atrWareName" exact="if $atrEntry.$Ware? then $atrEntry.$Ware else 'Unknown'"/>
            <append_to_list name="$sec9.$Rows" exact="table[
              $Check = 'Active Trade #' + $ai,
              $Status = if $atrEntry.$Ship == $ship then 'PASS' else 'INFO',
              $Detail = $atrDetail,
              $Col4 = $atrWareName,
              $Col5 = $atrEntry.$Source,
              $Col6 = if $atrEntry.$Ship == $ship then 'THIS SHIP' else ''
            ]"/>
          </do_if>
        </do_all>

        <!-- Fleet summary (GT ships in same home sector) -->
        <set_value name="$totalGTShips" exact="0"/>
        <set_value name="$sameHomeCount" exact="0"/>
        <do_if value="global.$GT_Ships?">
          <set_value name="$gtShipKeys" exact="global.$GT_Ships.keys.list"/>
          <set_value name="$totalGTShips" exact="$gtShipKeys.count"/>
          <do_all exact="$gtShipKeys.count" counter="$gsi">
            <set_value name="$gtShipRef" exact="$gtShipKeys.{$gsi}"/>
            <do_if value="$gtShipRef? and $gtShipRef.exists and $gtShipRef != $ship">
              <set_value name="$otherHome" exact="null"/>
              <do_if value="global.$GT_Ships.{$gtShipRef}.$HomeSector?">
                <set_value name="$otherHome" exact="global.$GT_Ships.{$gtShipRef}.$HomeSector"/>
              </do_if>
              <do_if value="$otherHome? and $homeSector? and $otherHome == $homeSector">
                <set_value name="$sameHomeCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Total GT Ships', $Status = 'INFO', $Detail = '' + $totalGTShips]"/>
        <append_to_list name="$sec9.$Rows" exact="table[$Check = 'Ships In Same Home Sector', $Status = if $sameHomeCount gt 5 then 'WARN' else 'INFO', $Detail = '' + $sameHomeCount + ' (excl. this ship)']"/>

        <append_to_list name="$report.$Sections" exact="$sec9"/>

        <!-- ======================================================== -->
        <!-- SECTION 10: Failed Sector Pairs                          -->
        <!-- ======================================================== -->
        <!-- ======================================================== -->
        <!-- SECTION 10: Failed Sector Pairs                          -->
        <!-- SKIPPED in clearance mode (not relevant for selling)     -->
        <!-- ======================================================== -->
        <do_if value="not $isClearanceMode">
        <set_value name="$sec10" exact="table[]"/>
        <set_value name="$sec10.$Name" exact="'Failed Sector Pairs'"/>
        <set_value name="$sec10.$Rows" exact="[]"/>

        <set_value name="$failedPairsCount" exact="0"/>
        <do_if value="$ship.sector? and global.$GT_FailedSectorPairs? and global.$GT_FailedSectorPairs.{$ship.sector}?">
          <set_value name="$fspData" exact="global.$GT_FailedSectorPairs.{$ship.sector}"/>
          <!-- Savegame compatibility: sector entry can be a nested table (new format,    -->
          <!-- written by gt_trading_signals.xml + order.trade.galaxytrader*.xml) OR a    -->
          <!-- flat list of records (legacy format, still written by gt_trading_ai.xml).  -->
          <!-- Lists have no .keys, so the old code crashed on legacy-format savegames.   -->
          <do_if value="typeof $fspData == datatype.table">
            <set_value name="$fspBuySectors" exact="$fspData.keys.list"/>
            <do_all exact="[$fspBuySectors.count, 10].min" counter="$fbi">
              <set_value name="$fspBuySec" exact="$fspBuySectors.{$fbi}"/>
              <do_if value="$fspData.{$fspBuySec}? and typeof $fspData.{$fspBuySec} == datatype.table">
                <set_value name="$fspSellSectors" exact="$fspData.{$fspBuySec}.keys.list"/>
                <do_all exact="[$fspSellSectors.count, 5].min" counter="$fsi">
                  <set_value name="$fspSellSec" exact="$fspSellSectors.{$fsi}"/>
                  <set_value name="$failedPairsCount" operation="add"/>
                  <set_value name="$fspAge" exact="0"/>
                  <do_if value="$fspData.{$fspBuySec}.{$fspSellSec}? and @$fspData.{$fspBuySec}.{$fspSellSec}.$Timestamp">
                    <set_value name="$fspAge" exact="player.age - $fspData.{$fspBuySec}.{$fspSellSec}.$Timestamp"/>
                  </do_if>
                  <set_value name="$fspDetail" exact="$fspBuySec.knownname + ' -> ' + $fspSellSec.knownname + ' (age: ' + $fspAge + 's)'"/>
                  <append_to_list name="$sec10.$Rows" exact="table[$Check = 'Failed Pair #' + $failedPairsCount, $Status = 'WARN', $Detail = $fspDetail]"/>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_elseif value="typeof $fspData == datatype.list">
            <do_all exact="[$fspData.count, 10].min" counter="$fbi">
              <set_value name="$fspRecord" exact="$fspData.{$fbi}"/>
              <do_if value="$fspRecord? and @$fspRecord.$BuySector and @$fspRecord.$SellSector">
                <set_value name="$failedPairsCount" operation="add"/>
                <set_value name="$fspAge" exact="if @$fspRecord.$Timestamp then player.age - $fspRecord.$Timestamp else 0"/>
                <set_value name="$fspDetail" exact="$fspRecord.$BuySector.knownname + ' -> ' + $fspRecord.$SellSector.knownname + ' (age: ' + $fspAge + 's)'"/>
                <append_to_list name="$sec10.$Rows" exact="table[$Check = 'Failed Pair #' + $failedPairsCount, $Status = 'WARN', $Detail = $fspDetail]"/>
              </do_if>
            </do_all>
          </do_elseif>
        </do_if>
        <append_to_list name="$sec10.$Rows" exact="table[$Check = 'Total Failed Sector Pairs', $Status = if $failedPairsCount gt 0 then 'WARN' else 'PASS', $Detail = '' + $failedPairsCount + ' (for current sector)']"/>

        <append_to_list name="$report.$Sections" exact="$sec10"/>
        </do_if>

        <!-- ======================================================== -->
        <!-- SECTION 11: Verdict & Recommendations                    -->
        <!-- ======================================================== -->
        <!-- ======================================================== -->
        <!-- VERDICT: Inserted at top of Ship State (sec1)             -->
        <!-- ======================================================== -->
        <set_value name="$verdictRows" exact="[]"/>

        <!-- Determine root cause -->
        <set_value name="$verdict" exact="'Unknown - no clear root cause identified'"/>
        <set_value name="$suggestions" exact="[]"/>

        <!-- ====== CLEARANCE MODE VERDICT ====== -->
        <do_if value="$isClearanceMode">
          <do_if value="$cargoUsed le 0">
            <set_value name="$verdict" exact="'CLEARANCE: Ship is in clearance mode but has no cargo. This should not happen.'"/>
            <append_to_list name="$suggestions" exact="'This may be a state inconsistency - try reassigning the GT order.'"/>
          </do_if>
          <do_elseif value="$clTotalIllegal gt 0 and $clTotalPass == 0">
            <set_value name="$verdict" exact="'STUCK (ILLEGAL CARGO): All ' + $clTotalBuyers + ' potential buyers blocked because ware is illegal to a faction and AllowIllegal is disabled. Ship cannot sell its cargo and is stuck in an infinite retry loop.'"/>
            <append_to_list name="$suggestions" exact="'Enable AllowIllegal on this ship/commander to allow selling the cargo.'"/>
            <append_to_list name="$suggestions" exact="'Or: manually sell the cargo, then reassign the GT order.'"/>
          </do_elseif>
          <do_elseif value="$clTotalPass == 0 and $clTotalBuyers gt 0">
            <set_value name="$verdict" exact="'STUCK (NO VIABLE BUYER): ' + $clTotalBuyers + ' potential buyers found but all rejected. Ship cannot sell its cargo.'"/>
            <append_to_list name="$suggestions" exact="'Check the Clearance tab for specific rejection reasons per station.'"/>
            <append_to_list name="$suggestions" exact="'Increase max sell distance or review blacklist settings.'"/>
          </do_elseif>
          <do_elseif value="$clTotalPass == 0 and $clTotalBuyers == 0">
            <set_value name="$verdict" exact="'STUCK (NO BUYERS): No buy offers found for current cargo in ' + $searchSectors.count + ' sectors within range.'"/>
            <append_to_list name="$suggestions" exact="'Increase max sell distance to expand search radius.'"/>
            <append_to_list name="$suggestions" exact="'Check if any stations in range buy these wares.'"/>
          </do_elseif>
          <do_elseif value="$clTotalPass gt 0">
            <set_value name="$verdict" exact="'CLEARANCE OK: ' + $clTotalPass + ' viable buyers found out of ' + $clTotalBuyers + ' total. Ship should be able to sell its cargo.'"/>
            <append_to_list name="$suggestions" exact="'If the ship is not selling, check scheduler state and queue.'"/>
          </do_elseif>
        </do_if>
        <!-- ====== NORMAL TRADING VERDICT ====== -->
        <do_else>
        <!-- Priority 1a: MK2 routes via explicit source/destination station lists.
             A missing home sector is allowed (the order's homeStation param is optional,
             default null). The genuine MK2-critical state is "no source stations" or
             "no destination stations" - both lists are mandatory for MK2 to plan a trade.
             These three branches are flattened into the parent do_if/do_elseif chain so
             that an MK2 ship with both lists populated falls through to the regular
             priority gates (money, offers, pair filters) instead of swallowing them. -->
        <do_if value="$orderId == 'GalaxyTraderMK2' and $mk2SourceCount le 0 and $mk2DestCount le 0">
          <set_value name="$verdict" exact="'CRITICAL: MK2 has no source and no destination stations configured - cannot plan trades'"/>
          <append_to_list name="$suggestions" exact="'Reconfigure this MK2 trade order on the ship and assign at least one source station and one destination station via the order params.'"/>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK2' and $mk2SourceCount le 0">
          <set_value name="$verdict" exact="'CRITICAL: MK2 has no source stations configured - cannot plan trades'"/>
          <append_to_list name="$suggestions" exact="'Reconfigure this MK2 trade order on the ship and assign at least one source station via the order params.'"/>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyTraderMK2' and $mk2DestCount le 0">
          <set_value name="$verdict" exact="'CRITICAL: MK2 has no destination stations configured - cannot plan trades'"/>
          <append_to_list name="$suggestions" exact="'Reconfigure this MK2 trade order on the ship and assign at least one destination station via the order params.'"/>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyTraderMK1' and (not $mk1DiagHome? or not $mk1DiagHome.exists)">
          <set_value name="$verdict" exact="'CRITICAL: MK1 has no home station configured - cannot export products'"/>
          <append_to_list name="$suggestions" exact="'Assign a home station on this MK1 Heron/trader order (the station whose products it should haul).'"/>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyTraderMK1' and $mk1DiagEffectiveWares? and $mk1DiagEffectiveWares.count == 0 and $mk1DiagHome? and $mk1DiagHome.exists">
          <set_value name="$verdict" exact="'MK1 IDLE (export gate): no wares above Min Product Storage % (' + $mk1DiagMinSellStorage + ') â€” station products not ready to export'"/>
          <append_to_list name="$suggestions" exact="'Wait for home station storage to fill above the export threshold, or lower Min Product Storage % on the order.'"/>
        </do_elseif>
        <!-- Priority 1c: MK2 source stations exist but every sellable ware is at or below
             the static-reserve threshold. This is the player-actionable equivalent of the
             runtime "srcBelowStatic" skip (order.trade.galaxytraderMK2.xml line 1410) and
             surfaces what would otherwise show up only as a cryptic debug log line. We
             require at least one ware was actually evaluated - if none were, the source has
             no allocated storage and a separate diagnosis is more appropriate. -->
        <do_elseif value="$orderId == 'GalaxyTraderMK2' and $mk2SourceWaresEvaluated gt 0 and $mk2SourceWaresBelowStatic == $mk2SourceWaresEvaluated">
          <set_value name="$verdict" exact="'MK2 IDLE (source below static reserve): every sellable ware on the configured ' + (if $mk2OrderBidirectional then 'participating station(s) [bidirectional]' else 'source station(s)') + ' is at or below the static-storage reserve of ' + $mk2StaticStorage + '%. The runtime refuses to drain a source until it climbs ABOVE this threshold. Worst case: ' + $mk2WorstSourceDetail + ' . Highest fill seen: ' + $mk2BestSourceDetail + ' .'"/>
          <append_to_list name="$suggestions" exact="'Wait for the source station to produce more stock (the static reserve is intentional - it prevents the trader from emptying a production line below operating margins).'"/>
          <append_to_list name="$suggestions" exact="'OR lower the trader Static Storage % in its order params (current ' + $mk2StaticStorage + '%) so it ships earlier - e.g. set it to a value below the highest source fill (' + $mk2BestSourceRatio + '%).'"/>
        </do_elseif>
        <!-- Priority 1d: MK2 source stations exist but no source ware has any allocated
             storage (cargo.{ware}.target == 0 for all wares). The runtime treats this as
             srcNoTarget (silent continue) and the trader will never trade. -->
        <do_elseif value="$orderId == 'GalaxyTraderMK2' and $mk2SourceCount gt 0 and $mk2SourceWaresEvaluated == 0 and $mk2SourceWaresMissingTarget gt 0">
          <set_value name="$verdict" exact="'MK2 IDLE (source has no storage allocated): the configured source station(s) have no cargo storage allocated for any of their sellable wares. The runtime cannot read a fill ratio and skips the pair silently.'"/>
          <append_to_list name="$suggestions" exact="'Wait for the station manager to assign storage to the produced wares, or pick a different source station.'"/>
        </do_elseif>
        <!-- Priority 1b: No home sector (non-MK2 orders only - MK2 does not require one). -->
        <do_elseif value="$orderId != 'GalaxyTraderMK2' and (not $homeSector? or not $homeSector.exists)">
          <set_value name="$verdict" exact="'CRITICAL: No home sector - ship cannot search for trades'"/>
          <append_to_list name="$suggestions" exact="'Assign ship to a commander or set a home sector'"/>
        </do_elseif>
        <!-- Priority 2: Money gate -->
        <do_elseif value="$playerMoney le $moneyGateThreshold">
          <set_value name="$verdict" exact="'BLOCKED: Money gate - player funds too low (' + ($playerMoney / 100) + ' Cr lt ' + ($moneyGateThreshold / 100) + ' Cr threshold)'"/>
          <append_to_list name="$suggestions" exact="'Increase player funds or lower MinPlayerMoney setting'"/>
        </do_elseif>
        <!-- Priority 2b: MK2 verdict from the station-pair eval, NOT the sector-wide scan.
             MK2 only trades its configured source/destination lists, so the generic Search
             Summary / Rejection Breakdown / Runtime Dispatch counts (which scan every offer in
             range) describe trades this order will never execute - e.g. a 791-pair "available"
             count whose best pair is between two stations not even in the MK2 config. The
             authoritative picture is the MK2 pair eval ($mk2PairPass / $mk2PairCount). This
             branch must sit before the generic Priority 3-7 verdicts so MK2 never falls through
             to them. -->
        <do_elseif value="$orderId == 'GalaxyTraderMK2' and $mk2PairCount gt 0">
          <do_if value="$mk2PairPass gt 0">
            <set_value name="$verdict" exact="'TRADES AVAILABLE (MK2): ' + $mk2PairPass + ' of ' + $mk2PairCount + ' configured source/dest/ware combination(s) are eligible' + (if $mk2FirstPassPair != '' then ' (e.g. ' + $mk2FirstPassPair + ')' else '') + '. MK2 trades ONLY its assigned source/destination lists - the sector-wide Search Summary above does not apply to this order.'"/>
            <append_to_list name="$suggestions" exact="'Eligible pairs exist, so a not-trading ship is limited by a runtime factor this diagnostic does not model: in-flight reservations and fleet fairness (sibling traders may have already claimed the destination intake), search cadence, or the ship currently running another order (e.g. Assist while a fleet subordinate) before it re-enters the MK2 loop. Reservations are intentionally not simulated here (see MK2 pair-eval note).'"/>
          </do_if>
          <do_else>
            <set_value name="$verdict" exact="'MK2 NO ELIGIBLE PAIRS: all ' + $mk2PairCount + ' configured source/dest/ware combination(s) are currently blocked - see the MK2 Skip Breakdown and Pair Details for the per-gate reasons (typically noDstOffer / noNeed / noSrcOffer).'"/>
            <append_to_list name="$suggestions" exact="'Confirm destination stations actually buy the source wares (noDstOffer), that destinations are below minStorage so they still need stock (noNeed), and that sources publish sell offers (noSrcOffer).'"/>
          </do_else>
        </do_elseif>
        <!-- Priority 3: Money cap active.
             Reaching here means Priority 2 already passed, i.e. player funds are above the money
             gate threshold (the fleet is solvent). The fleet money cap is a wealth snapshot left
             by a ship that recently could not afford a trade above MinPlayerMoney; MK3/MK4 ships
             self-clear it on their next search now that funds are healthy, and MK1/MK2 never use
             it. So this is informational, not a hard block. Check the value (not just key
             existence) so a cleared cap (value=false) does not report as active. -->
        <do_elseif value="global.$GT_MoneyCapActive? and global.$GT_MoneyCapActive">
          <set_value name="$verdict" exact="'INFO: Fleet money cap flag is set (snapshot ' + (if global.$GT_MoneyCapMoney? then (global.$GT_MoneyCapMoney / 100) else 0) + ' Cr), but player funds (' + ($playerMoney / 100) + ' Cr) are above the gate threshold (' + ($moneyGateThreshold / 100) + ' Cr). MK3/MK4 ships clear this cap on their next search; MK1/MK2 ignore it. This is not blocking this ship.'"/>
          <append_to_list name="$suggestions" exact="'No action needed if funds are healthy - the cap self-clears once any solvent MK3/MK4 ship searches. If trades still never start, run diagnose again after a few seconds.'"/>
        </do_elseif>
        <!-- Priority 4: No offers at all (order-aware)
             Miner diagnose only searches buyer offers (ship sells to station),
             so a missing seller side must not trigger a false "No sell offers" verdict. -->
        <do_elseif value="($orderId == 'GalaxyMiner' and $allBuyOffers.count == 0 and $selWBest == null and (not $selWStalled? or not $selWStalled)) or ($orderId != 'GalaxyMiner' and ($allSellOffers.count == 0 or $allBuyOffers.count == 0))">
          <!-- Miner-specific: distinguish "no buyers exist" (raw=0) from "buyers exist but
               policy rejects them" (raw>0, policy=0). The latter is a CONFIG bug, not a
               discovery bug, and the player needs a different fix path. -->
          <do_if value="$orderId == 'GalaxyTraderMK1' and $mk1DiagRawBuyOfferCount gt 0 and $allBuyOffers.count == 0">
            <set_value name="$mk1VerdictSectorCount" exact="if $mk1DiagSellSpaces? then $mk1DiagSellSpaces.count else $searchSectors.count"/>
            <set_value name="$verdict" exact="'POLICY BLOCKING (MK1 export): ' + $mk1DiagRawBuyOfferCount + ' buyer offer(s) visible in range across ' + $mk1VerdictSectorCount + ' sectors, but none pass runtime export policy.'"/>
            <do_if value="$mk1DiagPolicyBreakdown? and $mk1DiagPolicyBreakdown != ''">
              <set_value name="$verdict" exact="$verdict + ' Breakdown: ' + $mk1DiagPolicyBreakdown + '.'"/>
            </do_if>
            <do_if value="$mk1DiagPlayerBuyersExcluded gt 0 and $mk1DiagPlayerBuyersExcluded == $mk1DiagRawBuyOfferCount">
              <set_value name="$verdict" exact="$verdict + ' All visible buyers are player-owned; MK1 export only sells to NPC stations (ownerFilter=npc_only).'"/>
            </do_if>
            <do_if value="$mk1DiagRejectEngineMatch gt 0">
              <append_to_list name="$suggestions" exact="'See MK1 Export Pairs for per-buyer FAIL reasons. engine_match_buyer_or_relativeprice means the station fails match_buyer/relativeprice (not the price slider alone).'"/>
            </do_if>
            <do_if value="$mk1DiagRejectOfferAmount gt 0">
              <append_to_list name="$suggestions" exact="'per_ship_offeramount_zero: station has demand but offeramount for this ship is 0 right now (reservations, faction rules, or docking). The ship cannot execute that trade yet.'"/>
            </do_if>
            <append_to_list name="$suggestions" exact="'MK1 only pairs with NPC buyers. Player station buy orders appear in raw counts but cannot be export targets.'"/>
            <do_if value="$mk1DiagRejectEngineMatch == 0 and $mk1DiagRejectOfferAmount == 0 and $mk1DiagPlayerBuyersExcluded lt $mk1DiagRawBuyOfferCount">
              <append_to_list name="$suggestions" exact="'Buyer Price Range slider only affects relativeprice filtering - if engine_match count is 0 at slider 100 (neutral), widening the slider will not help.'"/>
            </do_if>
          </do_if>
          <do_elseif value="$orderId == 'GalaxyMiner' and $diagMinerRawBuyOfferCount gt 0">
            <set_value name="$verdict" exact="'POLICY BLOCKING (sell path): ' + $diagMinerRawBuyOfferCount + ' buyer offer(s) found in ' + $searchSectors.count + ' sectors but none pass per-ware sell policy for the wares in scope.'"/>
            <do_if value="$diagMinerPolicyBreakdown != ''">
              <set_value name="$verdict" exact="$verdict + ' Rejection breakdown: ' + $diagMinerPolicyBreakdown + '.'"/>
            </do_if>
            <do_if value="$diagMinerRejectOverflow gt 0">
              <set_value name="$verdict" exact="$verdict + ' At least one ware is at/above the overflow threshold on a primary station â€” see Primary Station Cargo rows.'"/>
            </do_if>
            <do_elseif value="$diagMinerRejectOverflowNoFallback gt 0">
              <set_value name="$verdict" exact="$verdict + ' Overflow wares cannot sell elsewhere because Overflow â†’ Sell To Other Stations is disabled.'"/>
            </do_elseif>
            <append_to_list name="$suggestions" exact="'See Primary Station Cargo (section 3) for each primary station ware fill: physical units, target, and % vs overflow threshold ' + $diagMinerOverflowThreshold + '%.'"/>
            <append_to_list name="$suggestions" exact="'See Miner Sell Offer Details for sample rejected offers with explicit policy reasons.'"/>
            <append_to_list name="$suggestions" exact="'For overflow wares (e.g. Ice full at home): enable Overflow â†’ Sell To Other Stations or wait for primary demand to drain.'"/>
            <do_if value="not $diagMinerCheckDemandFirst">
              <append_to_list name="$suggestions" exact="'Check Demand First is OFF: POLICY BLOCKING here affects selling carried cargo, not permission to mine. See Runtime Demand Stations for the station set the live miner actually uses.'"/>
            </do_if>
          </do_elseif>
          <do_else>
            <set_value name="$diagVerdictSectorCount" exact="if $orderId == 'GalaxyTraderMK1' and $mk1DiagSellSpaces? then $mk1DiagSellSpaces.count else $searchSectors.count"/>
            <set_value name="$verdict" exact="'NO OFFERS: ' + (if $orderId == 'GalaxyMiner' then 'No buy offers' else (if $allSellOffers.count == 0 then 'No sell offers' else 'No buy offers')) + ' found in ' + $diagVerdictSectorCount + ' sectors'"/>
            <append_to_list name="$suggestions" exact="'Increase max distance to expand search radius'"/>
            <append_to_list name="$suggestions" exact="'Check if sectors have operational stations'"/>
          </do_else>
        </do_elseif>
        <!-- Priority 4a-min: Demand-off full bay with no willing primary buyer (stockpile standby). -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $diagMinerDemandOffFullBayStall and not $diagMinerOnSellRun">
          <set_value name="$verdict" exact="'MINER STALLED (demand-off full-bay): cargo bay full (' + $cargoUsed + '/' + $cargoCap + '). Check Demand First is OFF (stockpile mode) but no primary station is below the ' + $diagMinerOverflowThreshold + '% overflow threshold for cargo on board, and Overflow â†’ Sell To Other Stations is disabled. The miner is in full-bay standby until a buyer opens or you intervene.'"/>
          <do_if value="$diagMinerSnapshotStallReason != ''">
            <set_value name="$verdict" exact="$verdict + ' Live snapshot stall reason: ' + $diagMinerSnapshotStallReason + '.'"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'Enable Overflow â†’ Sell To Other Stations so full cargo can sell to non-primary buyers.'"/>
          <append_to_list name="$suggestions" exact="'Add stations to Target Stations (stationList) or wait for primary demand to drain below ' + $diagMinerOverflowThreshold + '%.'"/>
          <append_to_list name="$suggestions" exact="'Demand-off only bypasses the mining demand gate - it does not remove sell policy. See Runtime Demand Stations vs Configured Target Stations in section 3.'"/>
        </do_elseif>
        <!-- Priority 4a0: Miner is actively executing a sell/delivery leg (not stuck). -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $diagMinerOnSellRun? and $diagMinerOnSellRun">
          <set_value name="$verdict" exact="'MINER DELIVERING: cargo on board (' + $cargoUsed + '/' + $cargoCap + '). Ship is actively executing a sell leg (' + $diagMinerSellRunDetail + ') â€” not stuck. Clearance/policy rows in this report are a static re-scan and may show 0 matches even while the runtime sell pipeline already selected a buyer.'"/>
          <do_if value="$selWBest != null">
            <set_value name="$verdict" exact="$verdict + ' After delivery, would mine ' + $selWBest + ' (urgency ' + $selWBestUrgency + ').'"/>
          </do_if>
        </do_elseif>
        <!-- Priority 4a-deliver: Demand-off full bay but a willing primary buyer exists - should deliver, not mine. -->
        <do_elseif value="$orderId == 'GalaxyMiner' and not $diagMinerCheckDemandFirst and $diagMinerFullBayNeedsClearance and $diagMinerCargoHasWillingBuyer and not $diagMinerOnSellRun">
          <set_value name="$verdict" exact="'MINER BLOCKED (demand-off deliver): cargo bay full (' + $cargoUsed + '/' + $cargoCap + ') but a primary buyer has capacity below the overflow threshold. The miner should run a delivery slice before mining more. If it is still standing by, reload the order or check for a stuck immediate order.'"/>
          <append_to_list name="$suggestions" exact="'See Cargo-first Willing Buyer in section 3 - if PASS, the runtime should deliver on the next mining slice.'"/>
          <append_to_list name="$suggestions" exact="'Compare Live Stall Reason (snapshot) in section 3 - demand_off_full_bay here means the previous cycle blocked delivery (fixed in current build).'"/>
        </do_elseif>
        <!-- Priority 4a: Miner has selectable demand but is stuck (overflow wait). -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $selWStalled? and $selWStalled">
          <set_value name="$verdict" exact="'MINER STALLED (overflow wait): ' + $selWStallCandidate + ' is the highest-urgency reachable ware (urgency ' + $selWStallUrgency + '), but every primary station is at or above the overflow threshold for it (worst fill ' + $selWStallStorageMax + '% ge ' + $diagMinerOverflowThreshold + '%) and Overflow â†’ Sell To Other Stations is DISABLED. The miner is looping in the demand-recheck wait at order.trade.galaxyminer.xml:1309 and will not deliver until something below changes.'"/>
          <do_if value="$selWUndiscoveredAlts? and $selWUndiscoveredAlts.count gt 0">
            <set_value name="$selWVerdictAltText" exact="''"/>
            <set_value name="$selWVerdictAltCap" exact="[$selWUndiscoveredAlts.count, 3].min"/>
            <!-- Track whether any of the listed alternatives already has one of the player's
                 resource probes in the engine-known sector. If even one does, the generic
                 "deploy a resource probe in each sector" suggestion is misleading - the player
                 already did that and is hitting the asteroid-discovery layer (probe reveals
                 yield only). Annotate the per-alt entry with the engine-known sector when it
                 differs from $BestSector and add a clarifying tail to the suggestion text. -->
            <set_value name="$selWAnyProbed" exact="false"/>
            <do_all exact="$selWVerdictAltCap" counter="$selWvai">
              <set_value name="$selWVerdictAlt" exact="$selWUndiscoveredAlts.{$selWvai}"/>
              <do_if value="$selWVerdictAltText != ''">
                <set_value name="$selWVerdictAltText" exact="$selWVerdictAltText + ', '"/>
              </do_if>
              <set_value name="$selWVerdictAltSector" exact="if $selWVerdictAlt.$EngineKnowsSector? and $selWVerdictAlt.$EngineKnowsSector != '' then $selWVerdictAlt.$EngineKnowsSector else $selWVerdictAlt.$Sector"/>
              <set_value name="$selWVerdictAltText" exact="$selWVerdictAltText + $selWVerdictAlt.$Name + ' in ' + $selWVerdictAltSector + (if $selWVerdictAlt.$ProbeInSector? and $selWVerdictAlt.$ProbeInSector then ' (probe already deployed - asteroid still needs visual/satellite scout)' else '')"/>
              <do_if value="$selWVerdictAlt.$ProbeInSector? and $selWVerdictAlt.$ProbeInSector">
                <set_value name="$selWAnyProbed" exact="true"/>
              </do_if>
            </do_all>
            <append_to_list name="$suggestions" exact="'Scout these higher-priority alternatives (asteroids exist but are undiscovered, so vanilla mining refuses to route player ships there): ' + $selWVerdictAltText + (if $selWUndiscoveredAlts.count gt $selWVerdictAltCap then ' (+' + ($selWUndiscoveredAlts.count - $selWVerdictAltCap) + ' more)' else '') + '. ' + (if $selWAnyProbed then 'For sectors marked (probe already deployed) the resource probe reveals yield only - the engine still needs asteroid-level discovery for player-ship routing; fly a ship close to an asteroid OR drop a satellite within line-of-sight. For the others: deploy a resource probe in the sector, scout with a satellite, or fly close enough to spot the asteroid visually.' else 'Deploy a resource probe in each sector, fly close enough to spot the asteroid visually, or have a satellite see it.')"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'Enable Overflow â†’ Sell To Other Stations on this miner so it can deliver ' + $selWStallCandidate + ' to a non-primary buyer instead of waiting.'"/>
          <append_to_list name="$suggestions" exact="'Lower the Overflow Threshold below ' + $selWStallStorageMax + '% (current threshold: ' + $diagMinerOverflowThreshold + '%) so the primary stations stop counting as full.'"/>
          <append_to_list name="$suggestions" exact="'Add another primary station that buys ' + $selWStallCandidate + ' so this miner has a sink with real capacity.'"/>
        </do_elseif>
        <!-- Priority 4a2: Miner bay full and carried minable cargo has no policy-passing buyer. -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $diagMinerCargoBlocksMining">
          <set_value name="$verdict" exact="'MINER STUCK (full bay): cargo bay full (' + $cargoUsed + '/' + $cargoCap + '). Carrying ' + $diagMinerCargoBlockDetail + ' but 0 policy-passing buyers in sell range â€” cannot mine until cargo is cleared. See Clearance for per-station rejection reasons.'"/>
          <do_if value="$selWBest != null">
            <set_value name="$verdict" exact="$verdict + ' Would otherwise mine ' + $selWBest + ' (urgency ' + $selWBestUrgency + ') if the bay had free space.'"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'See Clearance tab: fix overflow policy (enable Overflow â†’ Sell To Other Stations, add primary capacity, or lower overflow threshold) so the carried ware can be sold.'"/>
          <append_to_list name="$suggestions" exact="'Increase max sell distance or review blacklist if buyers exist but fail distance/path checks.'"/>
          <do_if value="not $diagMinerAllowOverflowSellToOthers">
            <append_to_list name="$suggestions" exact="'Overflow â†’ Sell To Other Stations is DISABLED â€” overflow wares like Ice at 94% primary fill cannot sell to non-primary buyers.'"/>
          </do_if>
        </do_elseif>
        <!-- Priority 4a3: Miner bay full but at least one carried ware can be sold â€” sell path exists. -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $diagMinerFullBayNeedsClearance and not $diagMinerCargoBlocksMining">
          <set_value name="$verdict" exact="'MINER BLOCKED (full bay): cargo bay full (' + $cargoUsed + '/' + $cargoCap + '). Must sell sellable cargo before mining. Clearance: ' + $clTotalPass + ' viable buyer(s) out of ' + $clTotalBuyers + ' for carried minable wares.'"/>
          <do_if value="$diagMinerHasUnsellableCargo">
            <set_value name="$verdict" exact="$verdict + ' Unsellable dead cargo will remain after sellable wares are cleared: ' + $diagMinerUnsellableCargoDetail + '.'"/>
          </do_if>
          <do_if value="$selWBest != null">
            <set_value name="$verdict" exact="$verdict + ' Would mine ' + $selWBest + ' once sellable cargo is cleared and bay has space.'"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'If the ship is not selling, check runtime sellwares / physical-storage gate and scheduler state.'"/>
          <append_to_list name="$suggestions" exact="'See Clearance tab for which stations would accept each carried ware.'"/>
          <do_if value="$diagMinerHasUnsellableCargo">
            <append_to_list name="$suggestions" exact="'Unsellable cargo wastes bay capacity â€” fix overflow policy for those wares (see Clearance rejection reasons) or wait for primary demand to drain.'"/>
          </do_if>
        </do_elseif>
        <!-- Priority 4b: Miner would select a ware with primary capacity â€” mining path is healthy. -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $selWBest != null">
          <set_value name="$verdict" exact="'MINER OPERATIONAL' + (if $diagMinerHasUnsellableCargo then ' (suboptimal)' else '') + ': would mine ' + $selWBest + ' (urgency ' + $selWBestUrgency + ', primary fill ' + $selWBestStorageMax + '% lt ' + $diagMinerOverflowThreshold + '%).'"/>
          <do_if value="$diagMinerHasUnsellableCargo">
            <set_value name="$verdict" exact="$verdict + ' Carrying unsellable dead cargo: ' + $diagMinerUnsellableCargoDetail + ' â€” reduces effective bay capacity; see Clearance for why those wares have no policy-passing buyers.'"/>
          </do_if>
          <do_else>
            <set_value name="$verdict" exact="$verdict + ' Demand-first selection matches runtime.'"/>
          </do_else>
          <append_to_list name="$suggestions" exact="'Primary Station Cargo (section 3) shows which wares are at/above the overflow threshold on your home station.'"/>
          <do_if value="$diagMinerHasUnsellableCargo">
            <append_to_list name="$suggestions" exact="'For unsellable overflow wares: enable Overflow â†’ Sell To Other Stations, lower overflow threshold, or add primary capacity so dead cargo can eventually be sold.'"/>
          </do_if>
          <do_if value="$diagMinerRawBuyOfferCount gt $allBuyOffers.count">
            <append_to_list name="$suggestions" exact="'Sell-offer policy scan rejected ' + ($diagMinerRawBuyOfferCount - $allBuyOffers.count) + ' distant buyer offer(s) by design (non-primary stations are ignored for wares that still have primary capacity).'"/>
          </do_if>
        </do_elseif>
        <!-- Priority 5: Miner buyer offers found (single-side miner flow) -->
        <do_elseif value="$orderId == 'GalaxyMiner' and $allBuyOffers.count gt 0">
          <set_value name="$verdict" exact="'MINER BUYERS AVAILABLE: ' + $allBuyOffers.count + ' of ' + $diagMinerRawBuyOfferCount + ' buyer offer(s) pass policy in ' + $searchSectors.count + ' sectors' + (if $diagMinerAnyBuyerMode then ' (auto-scope: all minable wares)' else ' (policy-scoped)')"/>
          <append_to_list name="$suggestions" exact="'See Miner Sell Offer Details for station/ware list and demand amounts.'"/>
          <do_if value="$diagMinerRawBuyOfferCount gt $allBuyOffers.count">
            <append_to_list name="$suggestions" exact="'NOTE: ' + ($diagMinerRawBuyOfferCount - $allBuyOffers.count) + ' additional buyer offer(s) were rejected by your primary/overflow/playerStationsOnly policy - review the Clearance section if your miner is selling to stations not listed here.'"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'If execution still stalls, compare against live order state (collecting/transfer/sell) and scheduler queue.'"/>
        </do_elseif>
        <!-- Priority 5: Offers exist, but no valid pair candidates were formed -->
        <do_elseif value="$pairCount == 0 and ($allSellOffers.count gt 0 and $allBuyOffers.count gt 0)">
          <set_value name="$verdict" exact="'NO MATCHING PAIRS: Offers exist on both sides, but no tradable sell-buy pairs could be formed'"/>
          <do_if value="$rejectSameStation gt 0">
            <append_to_list name="$suggestions" exact="'Most matches were same-station loops (' + $rejectSameStation + ' skipped) - this is intentionally ignored.'"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'Check ware overlap between sell and buy offers in Pair Details.'"/>
          <append_to_list name="$suggestions" exact="'Increase max distance or review blacklist constraints to expose more counterpart stations.'"/>
        </do_elseif>
        <!-- Priority 6: All evaluated pairs fail -->
        <do_elseif value="$passCount == 0 and $pairCount gt 0">
          <!-- Find dominant rejection reason -->
          <set_value name="$maxReject" exact="0"/>
          <set_value name="$maxRejectName" exact="'unknown'"/>
          <do_if value="$rejectNoProfit gt $maxReject">
            <set_value name="$maxReject" exact="$rejectNoProfit"/>
            <set_value name="$maxRejectName" exact="if ($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') then 'mk4_price_cap_exceeded (source price gt customer buy price)' else 'no_profit (sell price le buy price)'"/>
          </do_if>
          <do_if value="$rejectBelowThreshold gt $maxReject">
            <set_value name="$maxReject" exact="$rejectBelowThreshold"/>
            <set_value name="$maxRejectName" exact="'below_profit_threshold (threshold: ' + ($finalProfitThreshold / 100) + ' Cr)'"/>
          </do_if>
          <do_if value="$rejectBelowROI gt $maxReject">
            <set_value name="$maxReject" exact="$rejectBelowROI"/>
            <set_value name="$maxRejectName" exact="'below_roi_threshold (threshold: ' + $effectiveROI + '%)'"/>
          </do_if>
          <do_if value="$rejectNotOperational gt $maxReject">
            <set_value name="$maxReject" exact="$rejectNotOperational"/>
            <set_value name="$maxRejectName" exact="'station_not_operational'"/>
          </do_if>
          <do_if value="$rejectDocking gt $maxReject">
            <set_value name="$maxReject" exact="$rejectDocking"/>
            <set_value name="$maxRejectName" exact="'docking_denied'"/>
          </do_if>
          <do_if value="$rejectDockSize gt $maxReject">
            <set_value name="$maxReject" exact="$rejectDockSize"/>
            <set_value name="$maxRejectName" exact="'dock_size_incompatible'"/>
          </do_if>
          <do_if value="$rejectIllegal gt $maxReject">
            <set_value name="$maxReject" exact="$rejectIllegal"/>
            <set_value name="$maxRejectName" exact="'ware_illegal (AllowIllegal=false)'"/>
          </do_if>
          <do_if value="$rejectRouteIllegal gt $maxReject">
            <set_value name="$maxReject" exact="$rejectRouteIllegal"/>
            <set_value name="$maxRejectName" exact="'route_illegal (Illegal Route Filter â€” contraband illegal on jump path)'"/>
          </do_if>
          <do_if value="$rejectCargoType gt $maxReject">
            <set_value name="$maxReject" exact="$rejectCargoType"/>
            <set_value name="$maxRejectName" exact="'cargo_incompatible'"/>
          </do_if>
          <do_if value="$rejectCargoUtil gt $maxReject">
            <set_value name="$maxReject" exact="$rejectCargoUtil"/>
            <set_value name="$maxRejectName" exact="'cargo_utilization_below_min (threshold: ' + $effectiveCargoTarget + '%)'"/>
          </do_if>
          <do_if value="$rejectZeroAmount gt $maxReject">
            <set_value name="$maxReject" exact="$rejectZeroAmount"/>
            <set_value name="$maxRejectName" exact="'zero_amount (cargo/money/offer limits)'"/>
          </do_if>
          <do_if value="$rejectOfferInvalid gt $maxReject">
            <set_value name="$maxReject" exact="$rejectOfferInvalid"/>
            <set_value name="$maxRejectName" exact="'offer_invalid (unavailable or zero per-ship amount)'"/>
          </do_if>
          <do_if value="$rejectSupplierClamp gt $maxReject">
            <set_value name="$maxReject" exact="$rejectSupplierClamp"/>
            <set_value name="$maxRejectName" exact="'supplier_clamp_zero (trading-station broker has no exportable stock)'"/>
          </do_if>
          <do_if value="$rejectProfitRecalc gt $maxReject">
            <set_value name="$maxReject" exact="$rejectProfitRecalc"/>
            <set_value name="$maxRejectName" exact="'profit_recalc_non_positive'"/>
          </do_if>
          <do_if value="$rejectPathBlocked gt $maxReject">
            <set_value name="$maxReject" exact="$rejectPathBlocked"/>
            <set_value name="$maxRejectName" exact="'path_blocked (blacklisted or unreachable)'"/>
          </do_if>
          <do_if value="$rejectCantAfford gt $maxReject">
            <set_value name="$maxReject" exact="$rejectCantAfford"/>
            <set_value name="$maxRejectName" exact="'cant_afford'"/>
          </do_if>
          <do_if value="$rejectDistance gt $maxReject">
            <set_value name="$maxReject" exact="$rejectDistance"/>
            <set_value name="$maxRejectName" exact="'distance_exceeded (maxDistance=' + $maxDistance + ')'"/>
          </do_if>
          <do_if value="$rejectBlacklist gt $maxReject">
            <set_value name="$maxReject" exact="$rejectBlacklist"/>
            <set_value name="$maxRejectName" exact="'blacklisted_station_or_sector'"/>
          </do_if>
          <do_if value="$rejectMK1Supply gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK1Supply"/>
            <set_value name="$maxRejectName" exact="'mk1_supply_excluded'"/>
          </do_if>
          <do_if value="$rejectWareBasket gt $maxReject">
            <set_value name="$maxReject" exact="$rejectWareBasket"/>
            <set_value name="$maxRejectName" exact="'ware_not_in_manual_basket'"/>
          </do_if>
          <do_if value="$rejectBuildStorage gt $maxReject">
            <set_value name="$maxReject" exact="$rejectBuildStorage"/>
            <set_value name="$maxRejectName" exact="'build_storage_excluded'"/>
          </do_if>
          <do_if value="$rejectCarrierAux gt $maxReject">
            <set_value name="$maxReject" exact="$rejectCarrierAux"/>
            <set_value name="$maxRejectName" exact="'carrier_or_aux_excluded'"/>
          </do_if>
          <do_if value="$rejectMK4ForeignCustomer gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK4ForeignCustomer"/>
            <set_value name="$maxRejectName" exact="'mk4_customer_not_player_owned'"/>
          </do_if>
          <do_if value="$rejectMK4SupplierPolicy gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK4SupplierPolicy"/>
            <set_value name="$maxRejectName" exact="'mk4_supplier_policy_blocked'"/>
          </do_if>
          <do_if value="$rejectMK4TradeRules gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK4TradeRules"/>
            <set_value name="$maxRejectName" exact="'mk4_trade_rules_blocked (build storage disallows source faction)'"/>
          </do_if>
          <do_if value="$rejectMK4ServeHomeScope gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK4ServeHomeScope"/>
            <set_value name="$maxRejectName" exact="'mk4_serve_home_scope_blocked'"/>
          </do_if>
          <do_if value="$rejectMK4BuildStorageOnly gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK4BuildStorageOnly"/>
            <set_value name="$maxRejectName" exact="'mk4_buildstorage_only_blocked'"/>
          </do_if>
          <do_if value="$rejectMK4DemandReservedExhausted gt $maxReject">
            <set_value name="$maxReject" exact="$rejectMK4DemandReservedExhausted"/>
            <set_value name="$maxRejectName" exact="'mk4_demand_reserved_exhausted'"/>
          </do_if>
          <do_if value="$maxReject == 0">
            <set_value name="$maxRejectName" exact="'mixed_or_unclassified_rejections (see Pair Details)'"/>
          </do_if>

          <set_value name="$verdict" exact="'ALL REJECTED: 0/' + $pairCount + ' pairs passed. Dominant reason: ' + $maxRejectName + ' (' + $maxReject + ' pairs)'"/>

          <do_if value="$rejectBelowThreshold gt 0">
            <append_to_list name="$suggestions" exact="'Lower profit threshold base (current effective: ' + ($finalProfitThreshold / 100) + ' Cr)'"/>
          </do_if>
          <do_if value="$rejectBelowROI gt 0">
            <append_to_list name="$suggestions" exact="'Lower minimum ROI setting (current effective: ' + $effectiveROI + '%)'"/>
          </do_if>
          <do_if value="$rejectDocking gt 0">
            <append_to_list name="$suggestions" exact="'Check dock size compatibility - ship is ' + $dockSize + '-class'"/>
          </do_if>
          <do_if value="$rejectNotOperational gt 0">
            <append_to_list name="$suggestions" exact="'Some stations are not operational. Wait for production/storage recovery or pick other sectors.'"/>
          </do_if>
          <do_if value="$rejectIllegal gt 0">
            <append_to_list name="$suggestions" exact="'Enable AllowIllegal if you want to include illegal wares.'"/>
          </do_if>
          <do_if value="$rejectRouteIllegal gt 0">
            <append_to_list name="$suggestions" exact="'Illegal Route Filter blocked pairs where contraband would be illegal on the jump path. See Pair Details route_illegal rows for sector/police, or disable the filter / choose different routes.'"/>
          </do_if>
          <do_if value="$rejectCargoType gt 0">
            <append_to_list name="$suggestions" exact="'Ship cargo hold cannot carry ' + $rejectCargoType + ' pair(s) (solid/liquid vs container). Other fleet members may still cache those wares â€” see Cache State cargo-compatible count.'"/>
          </do_if>
          <do_if value="$rejectCargoUtil gt 0 and $useMinCargoThreshold and not $diagIsolatedForCargoFilter">
            <append_to_list name="$suggestions" exact="'Lower minimum cargo utilization target (current: ' + $effectiveCargoTarget + '%) or increase trade volume options (distance/wares).'"/>
          </do_if>
          <do_if value="$rejectZeroAmount gt 0">
            <append_to_list name="$suggestions" exact="'Offer amount/cargo free/money limits reduce tradable amount to zero for many pairs.'"/>
          </do_if>
          <do_if value="$rejectSupplierClamp gt 0">
            <append_to_list name="$suggestions" exact="'Trading-station broker offers show amount but have no exportable stock (seller_cargo clamp). These are rejected at match time â€” factory/refinery routes should rank instead.'"/>
          </do_if>
          <do_if value="$rejectPathBlocked gt 0">
            <append_to_list name="$suggestions" exact="'Review blacklist settings - some routes may be blocked'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $rejectMK4ForeignCustomer gt 0">
            <append_to_list name="$suggestions" exact="'MK4 delivers only to player-owned customers. Foreign-customer pairs are listed as FAIL (mk4_customer_not_player_owned) in Pair Details.'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $rejectMK4TradeRules gt 0">
            <append_to_list name="$suggestions" exact="'Trade rules block ' + $rejectMK4TradeRules + ' pair(s): the customer build storage only accepts its own faction, so foreign sources cannot supply it (mk4_trade_rules rows). Enable Ignore Trade Rules on the order, or widen the build storage trade rules, to allow foreign suppliers.'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $rejectMK4SupplierPolicy gt 0">
            <append_to_list name="$suggestions" exact="'Review MK4 supplier policy (buyFromPlayer / buyFromFaction). Current policy excludes many suppliers.'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $rejectMK4ServeHomeScope gt 0">
            <append_to_list name="$suggestions" exact="'serveHomeOnly is active: delivery must match home anchor (home station, its build storage, or home sector).'" />
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $rejectMK4BuildStorageOnly gt 0">
            <append_to_list name="$suggestions" exact="'Build storage only mode is active (Include Build Storage on, all ware categories off): only in-scope build storage buyers; no BS supplier legs or normal-station deliveries.'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2') and $rejectMK4DemandReservedExhausted gt 0">
            <append_to_list name="$suggestions" exact="'Demand is already covered by incoming reservations (vanilla + GT in-flight). Wait for execution/expiry or target different wares/stations.'"/>
          </do_if>
          <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' and $rejectMK1Supply gt 0 and $ignoreMK1Supply">
            <append_to_list name="$suggestions" exact="'Ignore MK1-Supplied Stations is blocking routes touching MK1-fed stations (supplier or customer leg). Disable it or remove the player station from global.$GT_MK1SuppliedStations if you want IPP trades through it.'"/>
          </do_if>
          <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3' and $diagIppPlayerSuppliersAdded == 0">
            <append_to_list name="$suggestions" exact="'IPP is on but no player sell offers passed the supplier scan. Check home sector range, ware basket, station operational state, and blacklist.'"/>
          </do_if>
        </do_elseif>
        <!-- Priority 6b: Pairs pass gates but runtime dispatch batch is empty -->
        <do_elseif value="$passCount gt 0 and $diagRuntimeDispatchCount == 0 and $orderId != 'GalaxyMiner'">
          <set_value name="$verdict" exact="'PAIRS PASS GATES BUT RUNTIME BATCH EMPTY: ' + $passCount + ' pairs passed validation parity, but 0 survive fresh-offer filter (mirrors live pipeline before trade_found)'"/>
          <append_to_list name="$suggestions" exact="'Offers may have been reserved or exhausted between scan and dispatch. Retry diagnose or wait for offer refresh.'"/>
          <do_if value="$rejectSupplierClamp gt 0">
            <append_to_list name="$suggestions" exact="'Many pairs failed supplier_clamp_zero â€” trading-station brokers without exportable stock. Runtime now rejects these at match time (lib.gt.tradematch v6+).'"/>
          </do_if>
        </do_elseif>
        <!-- Priority 7: Trades found (runtime dispatch count is authoritative) -->
        <do_elseif value="$diagRuntimeDispatchCount gt 0">
          <set_value name="$verdict" exact="'TRADES AVAILABLE: ' + $diagRuntimeDispatchCount + ' pairs would reach validation. Best: ' + $diagRuntimeBestDispatch"/>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyTraderMK3') and $cacheExists and $cacheEntryCount gt 0 and $cacheRuntimeReadableCount == 0">
            <set_value name="$verdict" exact="'LIVE ONLY (cache not runtime-ready): ' + $diagRuntimeDispatchCount + ' pairs via live search; 0 / ' + $cacheEntryCount + ' cache rows readable for this ship. Best: ' + $diagRuntimeBestDispatch"/>
          </do_if>
          <append_to_list name="$suggestions" exact="'Ship should be able to find trades. If it is not trading, check scheduler state and queue.'"/>
          <do_if value="$passCount gt $diagRuntimeDispatchCount">
            <append_to_list name="$suggestions" exact="'Note: ' + ($passCount - $diagRuntimeDispatchCount) + ' passing pair(s) dropped by fresh-offer filter since scan (offeramount/amount stale).'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyTraderMK3') and $cacheExists and $cacheEntryCount gt 0 and $cargoIncompatCount gt 0 and $cacheRuntimeReadableCount == 0 and $cacheRejectNoSellStation == 0 and $diagRuntimeDispatchCount gt 0">
            <append_to_list name="$suggestions" exact="'Cache pool has ' + $cacheEntryCount + ' entries but 0 are runtime-readable for this ship (' + $cargoIncompatCount + ' wrong hold type). Live search finds trades; cache read skips them.'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyTraderMK3') and $cacheExists and $cacheEntryCount gt 0 and $cacheRuntimeReadableCount == 0 and $diagRuntimeDispatchCount gt 0 and $cacheRejectNoSellStation gt 0">
            <append_to_list name="$suggestions" exact="'CACHE POISONED: ' + $cacheRejectNoSellStation + ' / ' + $cacheEntryCount + ' entries lack a resolvable delivery station ($SellStation / $SellOffer.buyer dead). Runtime logs Cache MISS (pool=' + $cacheEntryCount + ', trades=0) while live finds ' + $diagRuntimeDispatchCount + ' pairs. Stale entries inflate pool size without helping this ship.'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyTraderMK3') and $cacheExists and $cacheRuntimeReadableCount gt 0 and $cacheRuntimeReadableCount lt $cacheEntryCount">
            <append_to_list name="$suggestions" exact="'Only ' + $cacheRuntimeReadableCount + ' / ' + $cacheEntryCount + ' cache entries are runtime-readable for this ship (see Cache State: Missing Sell/Buy Station, Cache Runtime Readable).'"/>
          </do_if>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyTraderMK3') and $cacheExists and $cacheEntryCount gt 0 and $cacheRuntimeReadableCount == 0 and $diagRuntimeDispatchCount gt 0">
            <append_to_list name="$suggestions" exact="'Ship will miss cache and queue for mk4live/live search. Check Scheduler State (MK4 live waiters / home refresh lock) if search is slow.'"/>
          </do_if>
          <do_if value="$ignorePlayerPricing and $orderId == 'GalaxyTraderMK3'">
            <do_if value="$bestNpcSupplierPairScore gt $bestIppPairScore and $bestIppPairScore gt 0">
              <append_to_list name="$suggestions" exact="'IPP enabled but an NPC-supplier route scores higher (' + ($bestNpcSupplierPairScore)i + ' vs ' + ($bestIppPairScore)i + '). Runtime will prefer the NPC route unless you block it (blacklist, MK1-supply filter, etc.).'"/>
            </do_if>
            <do_if value="$bestIppPairScore le 0 and $bestNpcSupplierPairScore gt 0">
              <append_to_list name="$suggestions" exact="'No passing player-supplier pair despite IPP. Check MK1-supply exclusion, ware basket, and whether your player station has sell offers in range.'"/>
            </do_if>
            <do_if value="$rejectMK1Supply gt 0 and $ignoreMK1Supply">
              <append_to_list name="$suggestions" exact="'Some player routes may be blocked by Ignore MK1-Supplied Stations (checks both supplier and customer legs). See mk1_supply_excluded rows in Pair Details.'"/>
            </do_if>
          </do_if>
        </do_elseif>
        </do_else>

        <set_value name="$verdictStatus" exact="'FAIL'"/>
        <do_if value="$isClearanceMode and $clTotalPass gt 0">
          <set_value name="$verdictStatus" exact="'PASS'"/>
        </do_if>
        <do_elseif value="not $isClearanceMode and $diagRuntimeDispatchCount gt 0">
          <set_value name="$verdictStatus" exact="'PASS'"/>
          <do_if value="($orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2' or $orderId == 'GalaxyTraderMK3') and $cacheExists and $cacheEntryCount gt 0 and $cacheRuntimeReadableCount == 0">
            <set_value name="$verdictStatus" exact="'WARN'"/>
          </do_if>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $passCount gt 0 and $orderId == 'GalaxyMiner'">
          <set_value name="$verdictStatus" exact="'PASS'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $diagMinerOnSellRun? and $diagMinerOnSellRun">
          <set_value name="$verdictStatus" exact="'PASS'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $diagMinerDemandOffFullBayStall and not $diagMinerOnSellRun">
          <set_value name="$verdictStatus" exact="'FAIL'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and not $diagMinerCheckDemandFirst and $diagMinerFullBayNeedsClearance and $diagMinerCargoHasWillingBuyer and not $diagMinerOnSellRun">
          <set_value name="$verdictStatus" exact="'WARN'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $diagMinerCargoBlocksMining">
          <set_value name="$verdictStatus" exact="'FAIL'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $diagMinerFullBayNeedsClearance and not $diagMinerCargoBlocksMining">
          <set_value name="$verdictStatus" exact="'WARN'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $selWBest != null and $diagMinerHasUnsellableCargo">
          <set_value name="$verdictStatus" exact="'WARN'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $selWBest != null">
          <set_value name="$verdictStatus" exact="'PASS'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $selWStalled? and $selWStalled">
          <set_value name="$verdictStatus" exact="'FAIL'"/>
        </do_elseif>
        <do_elseif value="not $isClearanceMode and $orderId == 'GalaxyMiner' and $allBuyOffers.count gt 0">
          <set_value name="$verdictStatus" exact="'PASS'"/>
        </do_elseif>
        <!-- Build verdict rows -->
        <append_to_list name="$verdictRows" exact="table[$Check = 'VERDICT', $Status = $verdictStatus, $Detail = $verdict]"/>
        <do_if value="$orderId == 'GalaxyMiner' and $diagMinerRawBuyOfferCount gt 0 and $allBuyOffers.count == 0">
          <do_if value="$diagMinerPolicyBreakdown != ''">
            <append_to_list name="$verdictRows" exact="table[$Check = 'Policy Rejection Breakdown', $Status = 'WARN', $Detail = $diagMinerPolicyBreakdown]"/>
          </do_if>
          <do_if value="$diagMinerPolicyRejectedSamples.count gt 0">
            <append_to_list name="$verdictRows" exact="table[$Check = 'Rejected Offer Samples', $Status = 'INFO', $Detail = 'First ' + [$diagMinerPolicyRejectedSamples.count, 6].min + ' policy-blocked buyer offer(s)']"/>
            <set_value name="$verdictSampleCap" exact="[$diagMinerPolicyRejectedSamples.count, 6].min"/>
            <do_all exact="$verdictSampleCap" counter="$vsi">
              <append_to_list name="$verdictRows" exact="$diagMinerPolicyRejectedSamples.{$vsi}"/>
            </do_all>
          </do_if>
        </do_if>
        <do_if value="$orderId == 'GalaxyTraderMK4Supply' or $orderId == 'GalaxyTraderMK4Supply2'">
          <append_to_list name="$verdictRows" exact="table[$Check = 'MK4 Policy', $Status = 'INFO', $Detail = 'exec-only pairs, priceCap source&lt;=customer, demandGate vanillaRes+gtInFlight(global), ignoreTradeRules=faction-access-only']"/>
        </do_if>
        <do_all exact="$suggestions.count" counter="$si">
          <append_to_list name="$verdictRows" exact="table[$Check = 'Suggestion #' + $si, $Status = 'INFO', $Detail = $suggestions.{$si}]"/>
        </do_all>
        <append_to_list name="$verdictRows" exact="table[$Check = '---', $Status = 'INFO', $Detail = '']"/>

        <!-- Insert verdict rows at the TOP of sec1 (Ship State) -->
        <!-- Build a new rows list: verdict first, then original sec1 rows -->
        <set_value name="$originalSec1Rows" exact="$sec1.$Rows"/>
        <set_value name="$sec1.$Rows" exact="[]"/>
        <do_all exact="$verdictRows.count" counter="$vri">
          <append_to_list name="$sec1.$Rows" exact="$verdictRows.{$vri}"/>
        </do_all>
        <do_all exact="$originalSec1Rows.count" counter="$ori">
          <append_to_list name="$sec1.$Rows" exact="$originalSec1Rows.{$ori}"/>
        </do_all>

        <!-- ======================================================== -->
        <!-- Serialize report to delimited string for Lua transfer    -->
        <!-- Format: sections separated by "@@", rows by ";;",       -->
        <!--         fields by "||" (SectionName;;Status||Check||Detail;;...) -->
        <!-- GetNPCBlackboard cannot read complex tables, so we      -->
        <!-- serialize everything as a flat string.                   -->
        <!-- ======================================================== -->
        <set_value name="$serialized" exact="''"/>
        <do_all exact="$report.$Sections.count" counter="$secIdx">
          <set_value name="$sec" exact="$report.$Sections.{$secIdx}"/>
          <do_if value="$secIdx gt 1">
            <set_value name="$serialized" exact="$serialized + '@@'"/>
          </do_if>
          <set_value name="$serialized" exact="$serialized + $sec.$Name"/>
          <do_all exact="$sec.$Rows.count" counter="$rowIdx">
            <set_value name="$row" exact="$sec.$Rows.{$rowIdx}"/>
            <!-- Defensive: if a section builder produced a null row (e.g. a parser error in
                 a `table[...]` literal made `append_to_list exact=` evaluate to null), skip it
                 instead of letting the property lookup take down the whole serializer. -->
            <do_if value="$row?">
              <set_value name="$serialized" exact="$serialized + ';;' + $row.$Status + '||' + $row.$Check + '||' + $row.$Detail"/>
              <!-- Append extra columns if present (for structured multi-column sections) -->
              <do_if value="$row.$Col4?">
                <set_value name="$serialized" exact="$serialized + '||' + $row.$Col4"/>
              </do_if>
              <do_if value="$row.$Col5?">
                <set_value name="$serialized" exact="$serialized + '||' + $row.$Col5"/>
              </do_if>
              <do_if value="$row.$Col6?">
                <set_value name="$serialized" exact="$serialized + '||' + $row.$Col6"/>
              </do_if>
            </do_if>
          </do_all>
        </do_all>

        <!-- Store serialized report + metadata on player entity -->
        <set_value name="player.entity.$GT_DiagReport" exact="$serialized"/>
        <set_value name="player.entity.$GT_DiagShipId" exact="$ship.idcode"/>
        <set_value name="player.entity.$GT_DiagShipName" exact="$ship.knownname"/>
        <set_value name="player.entity.$GT_DiagTimestamp" exact="player.age"/>

        <!-- Log full diagnostic report to debug log -->
        <debug_text text="'[GT Diagnose] ================================================================'" chance="100"/>
        <debug_text text="'[GT Diagnose] DIAGNOSTIC REPORT for ' + $ship.idcode + ' (' + $ship.knownname + ')'" chance="100"/>
        <debug_text text="'[GT Diagnose] ================================================================'" chance="100"/>
        <do_all exact="$report.$Sections.count" counter="$logSecIdx">
          <set_value name="$logSec" exact="$report.$Sections.{$logSecIdx}"/>
          <debug_text text="'[GT Diagnose] --- ' + $logSec.$Name + ' ---'" chance="100"/>
          <do_all exact="$logSec.$Rows.count" counter="$logRowIdx">
            <set_value name="$logRow" exact="$logSec.$Rows.{$logRowIdx}"/>
            <!-- Defensive: skip null rows (matches the serializer guard above). -->
            <do_if value="$logRow?">
              <set_value name="$logLine" exact="'[GT Diagnose]   [' + $logRow.$Status + '] ' + $logRow.$Check + ': ' + $logRow.$Detail"/>
              <do_if value="$logRow.$Col4?">
                <set_value name="$logCol4" exact="$logRow.$Col4"/>
                <do_if value="$logCol4 != ''">
                  <set_value name="$logLine" exact="$logLine + ' | ' + $logCol4"/>
                </do_if>
              </do_if>
              <do_if value="$logRow.$Col5?">
                <set_value name="$logCol5" exact="$logRow.$Col5"/>
                <do_if value="$logCol5 != ''">
                  <set_value name="$logLine" exact="$logLine + ' | ' + $logCol5"/>
                </do_if>
              </do_if>
              <do_if value="$logRow.$Col6?">
                <set_value name="$logCol6" exact="$logRow.$Col6"/>
                <do_if value="$logCol6 != ''">
                  <set_value name="$logLine" exact="$logLine + ' | ' + $logCol6"/>
                </do_if>
              </do_if>
              <debug_text text="$logLine" chance="100"/>
            </do_if>
          </do_all>
        </do_all>
        <debug_text text="'[GT Diagnose] ================================================================'" chance="100"/>
        <debug_text text="'[GT Diagnose] VERDICT: ' + $verdict" chance="100"/>
        <debug_text text="'[GT Diagnose] ================================================================'" chance="100"/>

        <!-- Signal Lua to display report -->
        <raise_lua_event name="'gt.openDiagnoseReport'" param="$ship"/>
      </actions>
    </cue>

    <!-- Handle when user clicks "Promote" on a GT subordinate -->
    <cue name="GT_PromoteSubordinateAction" instantiate="true" namespace="this">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param.$object"/>
        <set_value name="$canRun" exact="true"/>
        <do_if value="not $ship? or not $ship.exists or not $ship.commander? or not $ship.commander.exists">
          <show_notification text="'[GT] Promote unavailable: no valid commander found.'" timeout="5s" priority="6"/>
          <set_value name="$canRun" exact="false"/>
        </do_if>

        <do_if value="$canRun and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Promote] Requested for subordinate ' + $ship.idcode + ' under commander ' + $ship.commander.idcode" chance="100"/>
        </do_if>

        <do_if value="$canRun">
          <!-- Lua promotes subordinate to commander -->
          <raise_lua_event name="'gt.openPromoteContext'" param="$ship"/>
        </do_if>
      </actions>
    </cue>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Context_Redistribute" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Handle logbook messages emitted by UI pilot redistribution flow -->
    <cue name="GT_RedistributeLogbookBridge" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_Redistribute'" control="'Logbook'"/>
      </conditions>
      <actions>
        <set_value name="$p" exact="event.param3"/>
        <do_if value="$p? and $p.$title? and $p.$message?">
          <debug_text text="'[GT Redistribute] LogbookBridge received title=' + $p.$title" chance="100"/>
          <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
            $Message = $p.$message,
            $Category = 'general',
            $Title = $p.$title,
            $CheckGlobalSettings = false
          ]"/>
        </do_if>
      </actions>
    </cue>

    <!-- Helper: close and remove a pilot-exchange session by key. -->
    <library name="GT_ClosePilotExchangeSession" purpose="run_actions">
      <params>
        <param name="sessionKey"/>
        <param name="reason" default="''"/>
      </params>
      <actions>
        <do_if value="$sessionKey? and $sessionKey != '' and global.$GT_PilotExchangeSessions? and global.$GT_PilotExchangeSessions.{'$' + $sessionKey}?">
          <set_value name="$sessionLeftId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$left"/>
          <set_value name="$sessionRightId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$right"/>
          <remove_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}"/>
          <do_if value="global.$GT_PilotExchangeSessionByShip?">
            <do_if value="$sessionLeftId? and $sessionLeftId != ''">
              <remove_value name="global.$GT_PilotExchangeSessionByShip.{'$' + $sessionLeftId}"/>
            </do_if>
            <do_if value="$sessionRightId? and $sessionRightId != ''">
              <remove_value name="global.$GT_PilotExchangeSessionByShip.{'$' + $sessionRightId}"/>
            </do_if>
          </do_if>
          <debug_text text="'[GT Redistribute] PE session closed key=' + $sessionKey + ' reason=' + (if $reason != '' then $reason else 'none')" chance="100"/>
        </do_if>
      </actions>
    </library>
    
    <!-- MD-native DockAndWait assignment (MD decides/validates station, then issues orders) -->
    <cue name="GT_RedistributeAssignDockOrdersBridge" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_Redistribute'" control="'AssignDockOrders'"/>
      </conditions>
      <actions>
        <set_value name="$p" exact="event.param3"/>
        <do_if value="$p? and $p.$leftObj? and $p.$rightObj?">
          <set_value name="$leftShip" exact="$p.$leftObj"/>
          <set_value name="$rightShip" exact="$p.$rightObj"/>
          <set_value name="$station" exact="null"/>
          <do_if value="$p.$stationObj? and $p.$stationObj.exists">
            <set_value name="$station" exact="$p.$stationObj"/>
          </do_if>
          <set_value name="$immediate" exact="true"/>
          <do_if value="$p.$immediate?">
            <set_value name="$immediate" exact="$p.$immediate"/>
          </do_if>

          <do_if value="not global.$GT_RedistributePendingDockByShip?">
            <set_value name="global.$GT_RedistributePendingDockByShip" exact="table[]"/>
          </do_if>

          <do_if value="$leftShip.exists and $rightShip.exists">
            <set_value name="$leftId" exact="$leftShip.idcode"/>
            <set_value name="$rightId" exact="$rightShip.idcode"/>
            <set_value name="$stationId" exact="''"/>

            <!-- If station was not preselected by caller, select one in MD with full checks for both ships -->
            <do_if value="not $station? or not $station.exists">
              <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$leftBlacklistGroup">
                <param name="ship" value="$leftShip"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$rightBlacklistGroup">
                <param name="ship" value="$rightShip"/>
              </run_actions>

              <find_station name="$candidateStations" space="player.galaxy" multiple="true" tradesknownto="faction.player" sortbydistanceto="$leftShip">
                <match class="[class.station]"/>
                <match owner="[faction.xenon, faction.khaak, faction.yaki]" negate="true"/>
                <match_relation_to object="$leftShip" relation="dock" comparison="ge"/>
                <match_relation_to object="$rightShip" relation="dock" comparison="ge"/>
              </find_station>

              <set_value name="$bestStation" exact="null"/>
              <set_value name="$bestScore" exact="999999999"/>
              <do_all exact="$candidateStations.count" counter="$i">
                <set_value name="$candidate" exact="$candidateStations.{$i}"/>
                <set_value name="$isValid" exact="$candidate.exists and $candidate.isoperational"/>

                <do_if value="$isValid">
                  <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$leftDockResult">
                    <param name="station" value="$candidate"/>
                    <param name="ship" value="$leftShip"/>
                    <param name="purpose" value="'dual'"/>
                  </run_actions>
                  <do_if value="not $leftDockResult.$CanDock">
                    <set_value name="$isValid" exact="false"/>
                  </do_if>
                </do_if>
                <do_if value="$isValid">
                  <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$rightDockResult">
                    <param name="station" value="$candidate"/>
                    <param name="ship" value="$rightShip"/>
                    <param name="purpose" value="'dual'"/>
                  </run_actions>
                  <do_if value="not $rightDockResult.$CanDock">
                    <set_value name="$isValid" exact="false"/>
                  </do_if>
                </do_if>

                <do_if value="$isValid">
                  <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$leftReachable">
                    <param name="ship" value="$leftShip"/>
                    <param name="station" value="$candidate"/>
                    <param name="blacklistgroup" value="$leftBlacklistGroup"/>
                    <param name="returnDetails" value="false"/>
                  </run_actions>
                  <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$rightReachable">
                    <param name="ship" value="$rightShip"/>
                    <param name="station" value="$candidate"/>
                    <param name="blacklistgroup" value="$rightBlacklistGroup"/>
                    <param name="returnDetails" value="false"/>
                  </run_actions>
                  <do_if value="not $leftReachable or not $rightReachable">
                    <set_value name="$isValid" exact="false"/>
                  </do_if>
                </do_if>

                <do_if value="$isValid">
                  <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$leftDist">
                    <param name="ship" value="$leftShip"/>
                    <param name="fromSector" value="$leftShip.sector"/>
                    <param name="toSector" value="$candidate.sector"/>
                    <param name="blacklistgroup" value="$leftBlacklistGroup"/>
                    <param name="useEscapeMode" value="false"/>
                  </run_actions>
                  <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$rightDist">
                    <param name="ship" value="$rightShip"/>
                    <param name="fromSector" value="$rightShip.sector"/>
                    <param name="toSector" value="$candidate.sector"/>
                    <param name="blacklistgroup" value="$rightBlacklistGroup"/>
                    <param name="useEscapeMode" value="false"/>
                  </run_actions>
                  <do_if value="$leftDist lt 0 or $rightDist lt 0">
                    <set_value name="$isValid" exact="false"/>
                  </do_if>
                  <do_if value="$isValid">
                    <set_value name="$score" exact="$leftDist + $rightDist"/>
                    <do_if value="$score lt $bestScore">
                      <set_value name="$bestScore" exact="$score"/>
                      <set_value name="$bestStation" exact="$candidate"/>
                    </do_if>
                  </do_if>
                </do_if>
              </do_all>

              <set_value name="$station" exact="$bestStation"/>
            </do_if>

            <do_if value="$station? and $station.exists">
              <set_value name="$stationId" exact="$station.idcode"/>
              <debug_text text="'[GT Redistribute] AssignDockOrders left=' + $leftId + ' right=' + $rightId + ' station=' + $stationId + ' immediate=' + $immediate" chance="100"/>

              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$leftDockResult">
                <param name="station" value="$station"/>
                <param name="ship" value="$leftShip"/>
                <param name="purpose" value="'dual'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$rightDockResult">
                <param name="station" value="$station"/>
                <param name="ship" value="$rightShip"/>
                <param name="purpose" value="'dual'"/>
              </run_actions>
              <do_if value="$leftDockResult.$CanDock and $rightDockResult.$CanDock">
                <!-- Set PE state at source of truth (MD assignment path) to avoid UI event timing gaps. -->
                <do_if value="not global.$GT_Ships?">
                  <set_value name="global.$GT_Ships" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_RedistributePendingDockByShip?">
                  <set_value name="global.$GT_RedistributePendingDockByShip" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_RedistributePendingDockSinceByShip?">
                  <set_value name="global.$GT_RedistributePendingDockSinceByShip" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_Ships.{$leftShip}?">
                  <set_value name="global.$GT_Ships.{$leftShip}" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_Ships.{$rightShip}?">
                  <set_value name="global.$GT_Ships.{$rightShip}" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_Ships.{$leftShip}.$PilotExchange" exact="true"/>
                <set_value name="global.$GT_Ships.{$rightShip}.$PilotExchange" exact="true"/>
                <!-- Force immediate PE label update on assignment (authoritative MD path). -->
                <do_if value="$leftShip.pilot?">
                  <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
                    <param name="ship" value="$leftShip"/>
                    <param name="pilot" value="$leftShip.pilot"/>
                    <param name="reason" value="'redistribute_assign_pe_activate_left'"/>
                  </run_actions>
                </do_if>
                <do_if value="$rightShip.pilot?">
                  <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
                    <param name="ship" value="$rightShip"/>
                    <param name="pilot" value="$rightShip.pilot"/>
                    <param name="reason" value="'redistribute_assign_pe_activate_right'"/>
                  </run_actions>
                </do_if>
                <!-- Authoritative PE session state (save/load persistent, pair-scoped). -->
                <set_value name="$sessionLeftId" exact="$leftId"/>
                <set_value name="$sessionRightId" exact="$rightId"/>
                <set_value name="$sessionLeftShip" exact="$leftShip"/>
                <set_value name="$sessionRightShip" exact="$rightShip"/>
                <set_value name="$sessionKey" exact="$sessionLeftId + '|' + $sessionRightId"/>
                <do_if value="not global.$GT_PilotExchangeSessions?">
                  <set_value name="global.$GT_PilotExchangeSessions" exact="table[]"/>
                </do_if>
                <do_if value="not global.$GT_PilotExchangeSessionByShip?">
                  <set_value name="global.$GT_PilotExchangeSessionByShip" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}" exact="table[]"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$left" exact="$sessionLeftId"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$right" exact="$sessionRightId"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$station" exact="$stationId"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftObj" exact="$sessionLeftShip"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightObj" exact="$sessionRightShip"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftUid" exact="'' + $sessionLeftShip"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightUid" exact="'' + $sessionRightShip"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftArrived" exact="false"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightArrived" exact="false"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$swapAttempted" exact="false"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$swapCompleted" exact="false"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$releaseSent" exact="false"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$createdAt" exact="player.age"/>
                <set_value name="global.$GT_PilotExchangeSessionByShip.{'$' + $leftId}" exact="$sessionKey"/>
                <set_value name="global.$GT_PilotExchangeSessionByShip.{'$' + $rightId}" exact="$sessionKey"/>
                <debug_text text="'[GT Redistribute] PE session created key=' + $sessionKey + ' station=' + $stationId" chance="100"/>

                <!-- Dedupe repeated requests for same ship->station pair -->
                <set_value name="$leftNeedsOrder" exact="true"/>
                <set_value name="$rightNeedsOrder" exact="true"/>
                <do_if value="global.$GT_RedistributePendingDockByShip.{'$' + $leftId}? and global.$GT_RedistributePendingDockByShip.{'$' + $leftId} == $stationId">
                  <set_value name="$leftNeedsOrder" exact="false"/>
                </do_if>
                <do_if value="global.$GT_RedistributePendingDockByShip.{'$' + $rightId}? and global.$GT_RedistributePendingDockByShip.{'$' + $rightId} == $stationId">
                  <set_value name="$rightNeedsOrder" exact="false"/>
                </do_if>

                <do_if value="$leftNeedsOrder">
                  <create_order object="$leftShip" id="'DockAndPilotExchange'" immediate="$immediate">
                    <param name="destination" value="$station"/>
                    <param name="partner" value="$rightShip"/>
                  </create_order>
                  <debug_text text="'[GT Redistribute] Assigned DockAndPilotExchange ship=' + $leftId + ' partner=' + $rightId + ' station=' + $stationId" chance="100"/>
                  <set_value name="global.$GT_RedistributePendingDockByShip.{'$' + $leftId}" exact="$stationId"/>
                  <set_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $leftId}" exact="player.age"/>
                </do_if>
                <do_if value="$rightNeedsOrder">
                  <create_order object="$rightShip" id="'DockAndPilotExchange'" immediate="$immediate">
                    <param name="destination" value="$station"/>
                    <param name="partner" value="$leftShip"/>
                  </create_order>
                  <debug_text text="'[GT Redistribute] Assigned DockAndPilotExchange ship=' + $rightId + ' partner=' + $leftId + ' station=' + $stationId" chance="100"/>
                  <set_value name="global.$GT_RedistributePendingDockByShip.{'$' + $rightId}" exact="$stationId"/>
                  <set_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $rightId}" exact="player.age"/>
                </do_if>
                <do_if value="not $leftNeedsOrder">
                  <set_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $leftId}" exact="player.age"/>
                </do_if>
                <do_if value="not $rightNeedsOrder">
                  <set_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $rightId}" exact="player.age"/>
                </do_if>
                <raise_lua_event name="'gt.redistributeDockAssignResult'" param="'ok|' + $leftId + '|' + $rightId + '|' + $stationId"/>
              </do_if>
              <do_else>
                <debug_text text="'[GT Redistribute] AssignDockOrders skipped: docking disallowed at station=' + $stationId + ' left=' + $leftId + ' right=' + $rightId + ' leftAllowed=' + $leftDockAllowed + ' rightAllowed=' + $rightDockAllowed" chance="100"/>
                <raise_lua_event name="'gt.redistributeDockAssignResult'" param="'fail|' + $leftId + '|' + $rightId + '|docking_denied'"/>
              </do_else>
            </do_if>
            <do_else>
              <debug_text text="'[GT Redistribute] AssignDockOrders failed: no valid rendezvous station for left=' + $leftId + ' right=' + $rightId" chance="100"/>
              <raise_lua_event name="'gt.redistributeDockAssignResult'" param="'fail|' + $leftId + '|' + $rightId + '|no_station'"/>
            </do_else>
          </do_if>
          <do_else>
            <set_value name="$leftFallback" exact="if $p.$left? then $p.$left else 'UNKNOWN'"/>
            <set_value name="$rightFallback" exact="if $p.$right? then $p.$right else 'UNKNOWN'"/>
            <debug_text text="'[GT Redistribute] AssignDockOrders failed: ship object missing left=' + $leftFallback + ' right=' + $rightFallback" chance="100"/>
            <raise_lua_event name="'gt.redistributeDockAssignResult'" param="'fail|' + $leftFallback + '|' + $rightFallback + '|missing_ship'"/>
          </do_else>
        </do_if>
      </actions>
    </cue>

    <!-- Consume explicit pilot-exchange order states for dedupe cleanup and diagnostics -->
    <cue name="GT_RedistributePilotExchangeOrderStateBridge" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_PilotExchange_OrderState'"/>
      </conditions>
      <actions>
        <set_value name="$s" exact="event.param2"/>
        <do_if value="$s? and $s.$ShipID? and $s.$State?">
          <debug_text text="'[GT Redistribute] PilotExchangeOrderState ship=' + $s.$ShipID + ' state=' + $s.$State + ' station=' + (if $s.$StationID? then $s.$StationID else '')" chance="100"/>
          <set_value name="$sessionKey" exact="''"/>
          <do_if value="global.$GT_PilotExchangeSessionByShip? and global.$GT_PilotExchangeSessionByShip.{'$' + $s.$ShipID}?">
            <set_value name="$sessionKey" exact="global.$GT_PilotExchangeSessionByShip.{'$' + $s.$ShipID}"/>
          </do_if>
          <do_if value="$sessionKey != '' and global.$GT_PilotExchangeSessions? and global.$GT_PilotExchangeSessions.{'$' + $sessionKey}?">
            <set_value name="$sessionLeftId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$left"/>
            <set_value name="$sessionRightId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$right"/>
            <set_value name="$sessionStationId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$station"/>
            <do_if value="$s.$Ship? and $s.$Ship.exists">
              <do_if value="$s.$ShipID == $sessionLeftId">
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftObj" exact="$s.$Ship"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftUid" exact="'' + $s.$Ship"/>
              </do_if>
              <do_if value="$s.$ShipID == $sessionRightId">
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightObj" exact="$s.$Ship"/>
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightUid" exact="'' + $s.$Ship"/>
              </do_if>
            </do_if>
            <do_if value="$s.$State == 'arrived' and $s.$StationID? and $s.$StationID == $sessionStationId">
              <do_if value="$s.$ShipID == $sessionLeftId">
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftArrived" exact="true"/>
              </do_if>
              <do_if value="$s.$ShipID == $sessionRightId">
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightArrived" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="$s.$State == 'failed' or $s.$State == 'aborted'">
              <do_if value="$s.$ShipID == $sessionLeftId">
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftArrived" exact="false"/>
              </do_if>
              <do_if value="$s.$ShipID == $sessionRightId">
                <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightArrived" exact="false"/>
              </do_if>
            </do_if>
            <do_if value="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftArrived and global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightArrived and (not global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$swapAttempted)">
              <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$swapAttempted" exact="true"/>
              <set_value name="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$swapAttemptedAt" exact="player.age"/>
              <raise_lua_event name="'gt.executePilotSwap'" param="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$left + '|' + global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$right + '|' + (if global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftUid? then global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftUid else '') + '|' + (if global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightUid? then global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightUid else '')"/>
              <debug_text text="'[GT Redistribute] PE session trigger key=' + $sessionKey + ' left=' + global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$left + ' right=' + global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$right + ' station=' + $sessionStationId" chance="100"/>
            </do_if>
          </do_if>
          <do_if value="$s.$State == 'started'">
            <!-- Authoritative active-state assertion: if exchange order starts, PE must be true. -->
            <set_value name="$activeShip" exact="if $s.$Ship? then $s.$Ship else null"/>
            <do_if value="global.$GT_RedistributePendingDockByShip?">
              <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $s.$ShipID}"/>
            </do_if>
            <do_if value="global.$GT_RedistributePendingDockSinceByShip?">
              <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $s.$ShipID}"/>
            </do_if>
            <do_if value="$activeShip? and $activeShip.exists">
              <do_if value="not global.$GT_Ships?">
                <set_value name="global.$GT_Ships" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Ships.{$activeShip}?">
                <set_value name="global.$GT_Ships.{$activeShip}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{$activeShip}.$PilotExchange" exact="true"/>
              <do_if value="$activeShip.pilot?">
                <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
                  <param name="ship" value="$activeShip"/>
                  <param name="pilot" value="$activeShip.pilot"/>
                  <param name="reason" value="'redistribute_orderstate_started'"/>
                </run_actions>
              </do_if>
            </do_if>
          </do_if>
          <do_if value="$s.$State == 'failed' or $s.$State == 'released'">
            <do_if value="global.$GT_RedistributePendingDockByShip?">
              <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $s.$ShipID}"/>
            </do_if>
            <do_if value="global.$GT_RedistributePendingDockSinceByShip?">
              <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $s.$ShipID}"/>
            </do_if>
            <!-- Ensure PE flag is reset using authoritative ship object emitted by DockAndPilotExchange order state. -->
            <set_value name="$cancelShip" exact="if $s.$Ship? then $s.$Ship else null"/>
            <do_if value="$cancelShip? and $cancelShip.exists">
              <do_if value="not global.$GT_Ships?">
                <set_value name="global.$GT_Ships" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Ships.{$cancelShip}?">
                <set_value name="global.$GT_Ships.{$cancelShip}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{$cancelShip}.$PilotExchange" exact="false"/>
              <do_if value="$cancelShip.pilot?">
                <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
                  <param name="ship" value="$cancelShip"/>
                  <param name="pilot" value="$cancelShip.pilot"/>
                  <param name="reason" value="'redistribute_orderstate_failed_or_released'"/>
                </run_actions>
              </do_if>
            </do_if>
            <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Redistribute] PilotExchangeOrderState missing ship object for PE clear id=' + $s.$ShipID + ' state=' + $s.$State" chance="100"/>
            </do_elseif>
            <run_actions ref="md.GT_Context_Redistribute.GT_ClosePilotExchangeSession">
              <param name="sessionKey" value="$sessionKey"/>
              <param name="reason" value="'order_state:' + $s.$State"/>
            </run_actions>
            <raise_lua_event name="'gt.redistributeOrderCancelled'" param="$s.$ShipID"/>
          </do_if>
          <do_if value="$s.$State == 'aborted' and $sessionKey != ''">
            <!-- Delay abort handling to avoid same-frame races during DockAndPilotExchange -> DockAndWait handoff. -->
            <signal_cue_instantly cue="md.GT_Context_Redistribute.GT_RedistributeFinalizeAbortedSessionCheck" param="table[
              $sessionKey = $sessionKey,
              $shipId = $s.$ShipID
            ]"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <cue name="GT_RedistributeFinalizeAbortedSessionCheck" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="200ms"/>
      <actions>
        <set_value name="$p" exact="event.param"/>
        <do_if value="$p? and $p.$sessionKey? and $p.$sessionKey != '' and global.$GT_PilotExchangeSessions? and global.$GT_PilotExchangeSessions.{'$' + $p.$sessionKey}?">
          <set_value name="$sessionKey" exact="$p.$sessionKey"/>
          <set_value name="$leftId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$left"/>
          <set_value name="$rightId" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$right"/>
          <set_value name="$leftShip" exact="null"/>
          <set_value name="$rightShip" exact="null"/>
          <set_value name="$leftKeepPE" exact="false"/>
          <set_value name="$rightKeepPE" exact="false"/>

          <do_if value="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftObj? and global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftObj.exists">
            <set_value name="$leftShip" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$leftObj"/>
          </do_if>
          <do_if value="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightObj? and global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightObj.exists">
            <set_value name="$rightShip" exact="global.$GT_PilotExchangeSessions.{'$' + $sessionKey}.$rightObj"/>
          </do_if>
          <do_if value="(not $leftShip? or not $leftShip.exists) and global.$GT_ShipIDCodeMap? and $leftId? and global.$GT_ShipIDCodeMap.{'$' + $leftId}?">
            <set_value name="$leftShip" exact="global.$GT_ShipIDCodeMap.{'$' + $leftId}"/>
          </do_if>
          <do_if value="(not $rightShip? or not $rightShip.exists) and global.$GT_ShipIDCodeMap? and $rightId? and global.$GT_ShipIDCodeMap.{'$' + $rightId}?">
            <set_value name="$rightShip" exact="global.$GT_ShipIDCodeMap.{'$' + $rightId}"/>
          </do_if>

          <do_if value="$leftShip? and $leftShip.exists and md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$leftPEStatus">
              <param name="ship" value="$leftShip"/>
            </run_actions>
            <set_value name="$leftKeepPE" exact="$leftPEStatus.$ShouldKeepPE"/>
          </do_if>
          <do_if value="$rightShip? and $rightShip.exists and md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$rightPEStatus">
              <param name="ship" value="$rightShip"/>
            </run_actions>
            <set_value name="$rightKeepPE" exact="$rightPEStatus.$ShouldKeepPE"/>
          </do_if>

          <do_if value="not $leftKeepPE and not $rightKeepPE">
            <do_if value="$leftShip? and $leftShip.exists and global.$GT_Ships? and global.$GT_Ships.{$leftShip}?">
              <set_value name="global.$GT_Ships.{$leftShip}.$PilotExchange" exact="false"/>
              <do_if value="$leftShip.pilot?">
                <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
                  <param name="ship" value="$leftShip"/>
                  <param name="pilot" value="$leftShip.pilot"/>
                  <param name="reason" value="'redistribute_abort_recheck_clear_left'"/>
                </run_actions>
              </do_if>
            </do_if>
            <do_if value="$rightShip? and $rightShip.exists and global.$GT_Ships? and global.$GT_Ships.{$rightShip}?">
              <set_value name="global.$GT_Ships.{$rightShip}.$PilotExchange" exact="false"/>
              <do_if value="$rightShip.pilot?">
                <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
                  <param name="ship" value="$rightShip"/>
                  <param name="pilot" value="$rightShip.pilot"/>
                  <param name="reason" value="'redistribute_abort_recheck_clear_right'"/>
                </run_actions>
              </do_if>
            </do_if>
            <do_if value="global.$GT_RedistributePendingDockByShip? and $leftId? and $leftId != ''">
              <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $leftId}"/>
            </do_if>
            <do_if value="global.$GT_RedistributePendingDockByShip? and $rightId? and $rightId != ''">
              <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $rightId}"/>
            </do_if>
            <do_if value="global.$GT_RedistributePendingDockSinceByShip? and $leftId? and $leftId != ''">
              <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $leftId}"/>
            </do_if>
            <do_if value="global.$GT_RedistributePendingDockSinceByShip? and $rightId? and $rightId != ''">
              <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $rightId}"/>
            </do_if>
            <run_actions ref="md.GT_Context_Redistribute.GT_ClosePilotExchangeSession">
              <param name="sessionKey" value="$sessionKey"/>
              <param name="reason" value="'order_state:aborted_recheck'"/>
            </run_actions>
            <do_if value="$leftId? and $leftId != ''">
              <raise_lua_event name="'gt.redistributeOrderCancelled'" param="$leftId"/>
            </do_if>
            <do_if value="$rightId? and $rightId != ''">
              <raise_lua_event name="'gt.redistributeOrderCancelled'" param="$rightId"/>
            </do_if>
          </do_if>
          <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Redistribute] Aborted recheck retained session key=' + $sessionKey + ' leftKeep=' + $leftKeepPE + ' rightKeep=' + $rightKeepPE" chance="100"/>
          </do_elseif>
        </do_if>
      </actions>
    </cue>
    
    <!-- Reconcile PE when a ship transitions to a new current order. -->
    <cue name="GT_RedistributePilotExchangeOrderReadyReconcile" instantiate="true">
      <conditions>
        <event_object_order_ready object="player.galaxy"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <do_if value="$ship? and $ship.exists and $ship.isclass.ship and $ship.owner == faction.player and md.GT_Ship_State_Utilities.GT_ReconcilePilotExchangeState? and ((global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$PilotExchange? and global.$GT_Ships.{$ship}.$PilotExchange) or (global.$GT_RedistributePendingDockByShip? and $ship.idcode? and global.$GT_RedistributePendingDockByShip.{'$' + $ship.idcode}?))">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_ReconcilePilotExchangeState">
            <param name="ship" value="$ship"/>
            <param name="reason" value="'order_ready'"/>
          </run_actions>
        </do_if>
      </actions>
    </cue>
    
    <!-- Reconcile PE when any current order is cancelled (including manual remove-all-orders). -->
    <cue name="GT_RedistributePilotExchangeOrderCancelledReconcile" instantiate="true">
      <conditions>
        <event_object_order_cancelled object="player.galaxy"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <do_if value="$ship? and $ship.exists and $ship.isclass.ship and $ship.owner == faction.player and md.GT_Ship_State_Utilities.GT_ReconcilePilotExchangeState? and ((global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$PilotExchange? and global.$GT_Ships.{$ship}.$PilotExchange) or (global.$GT_RedistributePendingDockByShip? and $ship.idcode? and global.$GT_RedistributePendingDockByShip.{'$' + $ship.idcode}?))">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_ReconcilePilotExchangeState">
            <param name="ship" value="$ship"/>
            <param name="reason" value="'order_cancelled'"/>
          </run_actions>
        </do_if>
      </actions>
    </cue>

    <!-- Release DockAndPilotExchange hold after swap completes/fails -->
    <cue name="GT_RedistributeReleaseDockHoldBridge" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_Redistribute'" control="'ReleaseDockHold'"/>
      </conditions>
      <actions>
        <set_value name="$p" exact="event.param3"/>
        <do_if value="$p? and $p.$left? and $p.$right?">
          <debug_text text="'[GT Redistribute] ReleaseDockHold received left=' + $p.$left + ' right=' + $p.$right" chance="100"/>
          <signal_cue_instantly cue="md.GT_Context_Redistribute.GT_RedistributeReleaseDockHoldApply" param="$p"/>
          <signal_cue_instantly cue="md.GT_Context_Redistribute.GT_RedistributeReleaseDockHoldRetry2s" param="$p"/>
          <signal_cue_instantly cue="md.GT_Context_Redistribute.GT_RedistributeReleaseDockHoldRetry4s" param="$p"/>
        </do_if>
      </actions>
    </cue>

    <cue name="GT_RedistributeReleaseDockHoldRetry2s" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="2s"/>
      <actions>
        <signal_cue_instantly cue="md.GT_Context_Redistribute.GT_RedistributeReleaseDockHoldApply" param="event.param"/>
      </actions>
    </cue>

    <cue name="GT_RedistributeReleaseDockHoldRetry4s" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="4s"/>
      <actions>
        <signal_cue_instantly cue="md.GT_Context_Redistribute.GT_RedistributeReleaseDockHoldApply" param="event.param"/>
      </actions>
    </cue>

    <cue name="GT_RedistributeReleaseDockHoldApply" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$p" exact="event.param"/>
        <set_value name="$sessionKey" exact="''"/>
        <do_if value="$p.$left? and global.$GT_PilotExchangeSessionByShip? and global.$GT_PilotExchangeSessionByShip.{'$' + $p.$left}?">
          <set_value name="$sessionKey" exact="global.$GT_PilotExchangeSessionByShip.{'$' + $p.$left}"/>
        </do_if>
        <do_if value="$sessionKey == '' and $p.$right? and global.$GT_PilotExchangeSessionByShip? and global.$GT_PilotExchangeSessionByShip.{'$' + $p.$right}?">
          <set_value name="$sessionKey" exact="global.$GT_PilotExchangeSessionByShip.{'$' + $p.$right}"/>
        </do_if>
        <run_actions ref="md.GT_Context_Redistribute.GT_ClosePilotExchangeSession">
          <param name="sessionKey" value="$sessionKey"/>
          <param name="reason" value="'release_hold'"/>
        </run_actions>
        <set_value name="$leftShip" exact="null"/>
        <set_value name="$rightShip" exact="null"/>
        <!-- Resolve ships authoritatively by idcode first (stable across reload/UI marshalling). -->
        <do_if value="$p.$left? and global.$GT_ShipIDCodeMap? and global.$GT_ShipIDCodeMap.{'$' + $p.$left}?">
          <set_value name="$leftShip" exact="global.$GT_ShipIDCodeMap.{'$' + $p.$left}"/>
        </do_if>
        <do_if value="$p.$right? and global.$GT_ShipIDCodeMap? and global.$GT_ShipIDCodeMap.{'$' + $p.$right}?">
          <set_value name="$rightShip" exact="global.$GT_ShipIDCodeMap.{'$' + $p.$right}"/>
        </do_if>
        <do_if value="$p.$leftObj? and $p.$leftObj.exists and ($p.$leftObj.isclass.ship_s or $p.$leftObj.isclass.ship_m or $p.$leftObj.isclass.ship_l or $p.$leftObj.isclass.ship_xl)">
          <set_value name="$leftShip" exact="$p.$leftObj"/>
        </do_if>
        <do_if value="$p.$rightObj? and $p.$rightObj.exists and ($p.$rightObj.isclass.ship_s or $p.$rightObj.isclass.ship_m or $p.$rightObj.isclass.ship_l or $p.$rightObj.isclass.ship_xl)">
          <set_value name="$rightShip" exact="$p.$rightObj"/>
        </do_if>
        <do_if value="not $leftShip? or not $rightShip?">
          <debug_text text="'[GT Redistribute] ReleaseDockHold hard-fail: missing ship object(s) leftObj=' + (if $p.$leftObj? then 'yes' else 'no') + ' rightObj=' + (if $p.$rightObj? then 'yes' else 'no') + ' left=' + (if $p.$left? then $p.$left else 'NONE') + ' right=' + (if $p.$right? then $p.$right else 'NONE')" chance="100"/>
        </do_if>
        <do_if value="$leftShip? and $leftShip.exists">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{$leftShip}?">
            <set_value name="global.$GT_Ships.{$leftShip}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{$leftShip}.$PilotExchange" exact="false"/>
          <do_if value="global.$GT_RedistributePendingDockByShip? and $leftShip.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $leftShip.idcode}"/>
          </do_if>
          <do_if value="global.$GT_RedistributePendingDockSinceByShip? and $leftShip.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $leftShip.idcode}"/>
          </do_if>
          <signal_objects object="$leftShip" param="'GT_PilotExchange_Release'"/>
          <do_if value="$leftShip.order? and (@$leftShip.order.id == 'DockAndPilotExchange' or (@$leftShip.order.id == 'DockAndWait' and @$leftShip.order.$callerid.id == 'DockAndPilotExchange'))">
            <debug_text text="'[GT Redistribute] ReleaseDockHold cancelling lingering order on ' + $leftShip.idcode + ' current=' + @$leftShip.order.id" chance="100"/>
            <cancel_order order="$leftShip.order"/>
          </do_if>
          <do_if value="$leftShip.pilot?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
              <param name="ship" value="$leftShip"/>
              <param name="pilot" value="$leftShip.pilot"/>
              <param name="reason" value="'redistribute_release_hold_left'"/>
            </run_actions>
          </do_if>
        </do_if>
        <do_if value="$rightShip? and $rightShip.exists">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{$rightShip}?">
            <set_value name="global.$GT_Ships.{$rightShip}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{$rightShip}.$PilotExchange" exact="false"/>
          <do_if value="global.$GT_RedistributePendingDockByShip? and $rightShip.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $rightShip.idcode}"/>
          </do_if>
          <do_if value="global.$GT_RedistributePendingDockSinceByShip? and $rightShip.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $rightShip.idcode}"/>
          </do_if>
          <signal_objects object="$rightShip" param="'GT_PilotExchange_Release'"/>
          <do_if value="$rightShip.order? and (@$rightShip.order.id == 'DockAndPilotExchange' or (@$rightShip.order.id == 'DockAndWait' and @$rightShip.order.$callerid.id == 'DockAndPilotExchange'))">
            <debug_text text="'[GT Redistribute] ReleaseDockHold cancelling lingering order on ' + $rightShip.idcode + ' current=' + @$rightShip.order.id" chance="100"/>
            <cancel_order order="$rightShip.order"/>
          </do_if>
          <do_if value="$rightShip.pilot?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
              <param name="ship" value="$rightShip"/>
              <param name="pilot" value="$rightShip.pilot"/>
              <param name="reason" value="'redistribute_release_hold_right'"/>
            </run_actions>
          </do_if>
        </do_if>
        <debug_text text="'[GT Redistribute] ReleaseDockHold left=' + $p.$left + ' right=' + $p.$right + ' leftResolved=' + (if $leftShip? then 'yes' else 'no') + ' rightResolved=' + (if $rightShip? then 'yes' else 'no')" chance="100"/>
      </actions>
    </cue>

    <!-- After captain swap, re-bind GT pilot data to the new ship assignments and force name refresh -->
    <cue name="GT_RedistributePostSwapNameRefreshBridge" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_Redistribute'" control="'PostSwapNameRefresh'"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$p" exact="event.param3"/>
        <set_value name="$attempt" exact="if $p? and $p.$attempt? then $p.$attempt else 1"/>
        <do_if value="$p? and $p.$left? and $p.$right?">
          <debug_text text="'[GT Redistribute] PostSwapNameRefresh received left=' + $p.$left + ' right=' + $p.$right + ' attempt=' + $attempt" chance="100"/>
          <set_value name="$leftShip" exact="null"/>
          <set_value name="$rightShip" exact="null"/>
          <!-- Resolve ships authoritatively by idcode first (stable across reload/UI marshalling). -->
          <do_if value="global.$GT_ShipIDCodeMap? and global.$GT_ShipIDCodeMap.{'$' + $p.$left}?">
            <set_value name="$leftShip" exact="global.$GT_ShipIDCodeMap.{'$' + $p.$left}"/>
          </do_if>
          <do_if value="global.$GT_ShipIDCodeMap? and global.$GT_ShipIDCodeMap.{'$' + $p.$right}?">
            <set_value name="$rightShip" exact="global.$GT_ShipIDCodeMap.{'$' + $p.$right}"/>
          </do_if>
          <do_if value="$p.$leftObj? and $p.$leftObj.exists and ($p.$leftObj.isclass.ship_s or $p.$leftObj.isclass.ship_m or $p.$leftObj.isclass.ship_l or $p.$leftObj.isclass.ship_xl)">
            <set_value name="$leftShip" exact="$p.$leftObj"/>
          </do_if>
          <do_if value="$p.$rightObj? and $p.$rightObj.exists and ($p.$rightObj.isclass.ship_s or $p.$rightObj.isclass.ship_m or $p.$rightObj.isclass.ship_l or $p.$rightObj.isclass.ship_xl)">
            <set_value name="$rightShip" exact="$p.$rightObj"/>
          </do_if>
          <do_if value="not $leftShip? or not $rightShip?">
            <debug_text text="'[GT Redistribute] PostSwapNameRefresh hard-fail: missing ship object(s) leftObj=' + (if $p.$leftObj? then 'yes' else 'no') + ' rightObj=' + (if $p.$rightObj? then 'yes' else 'no') + ' left=' + (if $p.$left? then $p.$left else 'NONE') + ' right=' + (if $p.$right? then $p.$right else 'NONE')" chance="100"/>
          </do_if>
          <debug_text text="'[GT Redistribute] PostSwapNameRefresh resolved left=' + (if $leftShip? then 'yes' else 'no') + ' right=' + (if $rightShip? then 'yes' else 'no')" chance="100"/>

          <set_value name="$leftPilot" exact="if $leftShip? and $leftShip.exists and $leftShip.pilot? and $leftShip.pilot.exists then $leftShip.pilot else null"/>
          <set_value name="$rightPilot" exact="if $rightShip? and $rightShip.exists and $rightShip.pilot? and $rightShip.pilot.exists then $rightShip.pilot else null"/>
          <set_value name="$leftPilotNameDbg" exact="if $leftPilot and $leftPilot.exists and $leftPilot.name? then $leftPilot.name else 'NONE'"/>
          <set_value name="$leftPilotIdDbg" exact="if $leftPilot and $leftPilot.exists and $leftPilot.idcode? then $leftPilot.idcode else 'NONE'"/>
          <set_value name="$rightPilotNameDbg" exact="if $rightPilot and $rightPilot.exists and $rightPilot.name? then $rightPilot.name else 'NONE'"/>
          <set_value name="$rightPilotIdDbg" exact="if $rightPilot and $rightPilot.exists and $rightPilot.idcode? then $rightPilot.idcode else 'NONE'"/>

          <do_if value="$leftShip? and $leftShip.exists and not ($leftPilot and $leftPilot.exists)">
            <debug_text text="'[GT Redistribute] PostSwap LEFT missing pilot ship=' + $leftShip.idcode + ' attempt=' + $attempt + ' default=' + (if $leftShip.defaultorder? then @$leftShip.defaultorder.id else 'NONE') + ' current=' + (if $leftShip.order? then @$leftShip.order.id else 'NONE')" chance="100"/>
            <signal_cue_instantly cue="md.GT_CoreSystem.FinalizeVanillaPilotAssignmentForGT" param="table[
              $Ship = $leftShip,
              $source = 'redistribute_post_swap',
              $attempt = 1
            ]"/>
          </do_if>
          <do_if value="$rightShip? and $rightShip.exists and not ($rightPilot and $rightPilot.exists)">
            <debug_text text="'[GT Redistribute] PostSwap RIGHT missing pilot ship=' + $rightShip.idcode + ' attempt=' + $attempt + ' default=' + (if $rightShip.defaultorder? then @$rightShip.defaultorder.id else 'NONE') + ' current=' + (if $rightShip.order? then @$rightShip.order.id else 'NONE')" chance="100"/>
            <signal_cue_instantly cue="md.GT_CoreSystem.FinalizeVanillaPilotAssignmentForGT" param="table[
              $Ship = $rightShip,
              $source = 'redistribute_post_swap',
              $attempt = 1
            ]"/>
          </do_if>

          <do_if value="$leftShip? and $leftShip.exists and $leftPilot and $leftPilot.exists">
            <debug_text text="'[GT Redistribute] PostSwap LEFT before sync ship=' + $leftShip.idcode + ' pilot=' + $leftPilotNameDbg + ' pilotId=' + $leftPilotIdDbg + ' default=' + (if $leftShip.defaultorder? then @$leftShip.defaultorder.id else 'NONE') + ' current=' + (if $leftShip.order? then @$leftShip.order.id else 'NONE')" chance="100"/>
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{$leftShip}?">
              <set_value name="global.$GT_Ships.{$leftShip}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{$leftShip}.$Pilot" exact="$leftPilot"/>
            <set_value name="global.$GT_Ships.{$leftShip}.$LastUpdate" exact="player.age"/>
            <!-- Force full pilot-change sync after swap so pilot registry, ship links and mods are all updated. -->
            <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
              $updateType = 'pilot_change',
              $Ship = $leftShip,
              $pilot = $leftPilot,
              $oldPilot = null
            ]"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$leftPilot}?">
              <set_value name="global.$GT_Pilots.{$leftPilot}.$AssociatedShip" exact="$leftShip"/>
              <set_value name="global.$GT_Pilots.{$leftPilot}.$Ship" exact="$leftShip"/>
              <set_value name="global.$GT_Pilots.{$leftPilot}.$ShipID" exact="$leftShip.idcode"/>
              <set_value name="global.$GT_Pilots.{$leftPilot}.$Status" exact="'active'"/>
              <set_value name="global.$GT_Pilots.{$leftPilot}.$ResumedTime" exact="player.age"/>
            </do_if>
            <do_else>
              <do_if value="md.GT_Ship_Management.Register_Pilot?">
                <run_actions ref="md.GT_Ship_Management.Register_Pilot">
                  <param name="pilot" value="$leftPilot"/>
                  <param name="ship" value="$leftShip"/>
                </run_actions>
              </do_if>
              <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$leftPilot}?">
                <set_value name="global.$GT_Pilots.{$leftPilot}.$AssociatedShip" exact="$leftShip"/>
                <set_value name="global.$GT_Pilots.{$leftPilot}.$Ship" exact="$leftShip"/>
                <set_value name="global.$GT_Pilots.{$leftPilot}.$ShipID" exact="$leftShip.idcode"/>
                <set_value name="global.$GT_Pilots.{$leftPilot}.$Status" exact="'active'"/>
                <set_value name="global.$GT_Pilots.{$leftPilot}.$ResumedTime" exact="player.age"/>
              </do_if>
              <do_else>
                <debug_text text="'[GT Redistribute] PostSwapNameRefresh hard-fail: left pilot missing in GT registry after forced sync pilot=' + $leftPilotNameDbg + ' ship=' + $leftShip.idcode" chance="100"/>
              </do_else>
            </do_else>
            <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
              <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
                <param name="ship" value="$leftShip"/>
                <param name="new_pilot" value="$leftPilot"/>
                <param name="old_pilot" value="$leftPilot"/>
              </run_actions>
            </do_if>
            <debug_text text="'[GT Redistribute] PostSwap LEFT after sync ship=' + $leftShip.idcode + ' pilot=' + $leftPilotNameDbg + ' pilotId=' + $leftPilotIdDbg + ' gtPilotRegistered=' + (if global.$GT_Pilots? and global.$GT_Pilots.{$leftPilot}? then 'yes' else 'no') + ' gtShipRegistered=' + (if global.$GT_Ships? and global.$GT_Ships.{$leftShip}? then 'yes' else 'no') + ' pilotExchange=' + (if global.$GT_Ships? and global.$GT_Ships.{$leftShip}? and global.$GT_Ships.{$leftShip}.$PilotExchange? then global.$GT_Ships.{$leftShip}.$PilotExchange else 'NONE')" chance="100"/>
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
              <param name="ship" value="$leftShip"/>
              <param name="pilot" value="$leftPilot"/>
              <param name="reason" value="'redistribute_postswap_refresh_left'"/>
            </run_actions>
          </do_if>

          <do_if value="$rightShip? and $rightShip.exists and $rightPilot and $rightPilot.exists">
            <debug_text text="'[GT Redistribute] PostSwap RIGHT before sync ship=' + $rightShip.idcode + ' pilot=' + $rightPilotNameDbg + ' pilotId=' + $rightPilotIdDbg + ' default=' + (if $rightShip.defaultorder? then @$rightShip.defaultorder.id else 'NONE') + ' current=' + (if $rightShip.order? then @$rightShip.order.id else 'NONE')" chance="100"/>
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{$rightShip}?">
              <set_value name="global.$GT_Ships.{$rightShip}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{$rightShip}.$Pilot" exact="$rightPilot"/>
            <set_value name="global.$GT_Ships.{$rightShip}.$LastUpdate" exact="player.age"/>
            <!-- Force full pilot-change sync after swap so pilot registry, ship links and mods are all updated. -->
            <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
              $updateType = 'pilot_change',
              $Ship = $rightShip,
              $pilot = $rightPilot,
              $oldPilot = null
            ]"/>
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$rightPilot}?">
              <set_value name="global.$GT_Pilots.{$rightPilot}.$AssociatedShip" exact="$rightShip"/>
              <set_value name="global.$GT_Pilots.{$rightPilot}.$Ship" exact="$rightShip"/>
              <set_value name="global.$GT_Pilots.{$rightPilot}.$ShipID" exact="$rightShip.idcode"/>
              <set_value name="global.$GT_Pilots.{$rightPilot}.$Status" exact="'active'"/>
              <set_value name="global.$GT_Pilots.{$rightPilot}.$ResumedTime" exact="player.age"/>
            </do_if>
            <do_else>
              <do_if value="md.GT_Ship_Management.Register_Pilot?">
                <run_actions ref="md.GT_Ship_Management.Register_Pilot">
                  <param name="pilot" value="$rightPilot"/>
                  <param name="ship" value="$rightShip"/>
                </run_actions>
              </do_if>
              <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$rightPilot}?">
                <set_value name="global.$GT_Pilots.{$rightPilot}.$AssociatedShip" exact="$rightShip"/>
                <set_value name="global.$GT_Pilots.{$rightPilot}.$Ship" exact="$rightShip"/>
                <set_value name="global.$GT_Pilots.{$rightPilot}.$ShipID" exact="$rightShip.idcode"/>
                <set_value name="global.$GT_Pilots.{$rightPilot}.$Status" exact="'active'"/>
                <set_value name="global.$GT_Pilots.{$rightPilot}.$ResumedTime" exact="player.age"/>
              </do_if>
              <do_else>
                <debug_text text="'[GT Redistribute] PostSwapNameRefresh hard-fail: right pilot missing in GT registry after forced sync pilot=' + $rightPilotNameDbg + ' ship=' + $rightShip.idcode" chance="100"/>
              </do_else>
            </do_else>
            <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
              <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
                <param name="ship" value="$rightShip"/>
                <param name="new_pilot" value="$rightPilot"/>
                <param name="old_pilot" value="$rightPilot"/>
              </run_actions>
            </do_if>
            <debug_text text="'[GT Redistribute] PostSwap RIGHT after sync ship=' + $rightShip.idcode + ' pilot=' + $rightPilotNameDbg + ' pilotId=' + $rightPilotIdDbg + ' gtPilotRegistered=' + (if global.$GT_Pilots? and global.$GT_Pilots.{$rightPilot}? then 'yes' else 'no') + ' gtShipRegistered=' + (if global.$GT_Ships? and global.$GT_Ships.{$rightShip}? then 'yes' else 'no') + ' pilotExchange=' + (if global.$GT_Ships? and global.$GT_Ships.{$rightShip}? and global.$GT_Ships.{$rightShip}.$PilotExchange? then global.$GT_Ships.{$rightShip}.$PilotExchange else 'NONE')" chance="100"/>
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
              <param name="ship" value="$rightShip"/>
              <param name="pilot" value="$rightPilot"/>
              <param name="reason" value="'redistribute_postswap_refresh_right'"/>
            </run_actions>
          </do_if>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Context_Rename" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Listen for Interact_Menu_API.Get_Actions to add our "GT Rename" entry -->
    <cue name="AddRenameAction" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Interact_Menu_API.Get_Actions"/>
      </conditions>
      <actions>
        <set_value name="$target" exact="event.param.$object"/>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        
        <!-- PERFORMANCE FIX: Early exit for non-player ships - skip all processing and logging -->
        <!-- Only process if it's actually a player-owned ship -->
        <do_if value="$target.isclass.{class.ship} and $target.isplayerowned and not $useVanillaXPOnly">
          <run_actions ref="md.GLX_Lib_Orders.GLX_ShipIsInGTService" result="$isGTService">
            <param name="ship" value="$target"/>
          </run_actions>
          <do_if value="$isGTService">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] MD: Adding GT Rename action for ship (ID: ' + $target.idcode + ')'" chance="100"/>
          </do_if>
          <set_value name="$renameActionText" exact="{77000,9001}"/>
          <!-- Omit $icon parameter instead of using empty string to avoid icon lookup errors -->
          <signal_cue_instantly
            cue="md.Interact_Menu_API.Add_Action"
            param="table[
              $id         = 'gt_mk3_rename',
              $text       = $renameActionText,
              $section    = 'gt_actions',
              $callback   = GT_RenameAction,
            ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] MD: Action added successfully for ship (ID: ' + $target.idcode + ')'" chance="100"/>
          </do_if>
          
          <!-- Add manual training action only when AutoTraining is disabled and pilot is blocked -->
          <set_value name="$autoTrainingEnabled" exact="true"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$AutoTraining?">
            <set_value name="$autoTrainingEnabled" exact="global.$GT_GlobalSettings.$XP.$AutoTraining"/>
          </do_if>
          
          <set_value name="$pilot" exact="null"/>
          <set_value name="$blockedLevel" exact="0"/>
          <do_if value="$target.pilot?">
            <set_value name="$pilot" exact="$target.pilot"/>
            <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$BlockedLevel?">
              <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
            </do_if>
          </do_if>
          
          <do_if value="not $autoTrainingEnabled and $pilot and $blockedLevel gt 1">
            <set_value name="$manualTrainingActionText" exact="{77000,9902}"/>
            <signal_cue_instantly
              cue="md.Interact_Menu_API.Add_Action"
              param="table[
                $id         = 'gt_mk3_manual_training',
                $text       = $manualTrainingActionText,
                $section    = 'gt_actions',
                $callback   = GT_QueueManualTrainingAction,
              ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] MD: Added manual training action for ship (ID: ' + $target.idcode + ', blocked level ' + $blockedLevel + ')'" chance="100"/>
            </do_if>
          </do_if>
          </do_if>
        </do_if>
        <!-- PERFORMANCE FIX: Removed else block - early exit above prevents unnecessary processing -->
      </actions>
    </cue>
    
    <!-- Handle manual training request from context menu -->
    <cue name="GT_QueueManualTrainingAction" instantiate="true" namespace="this">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$component" exact="event.param.$object"/>
        <set_value name="$pilot" exact="null"/>
        <set_value name="$blockedLevel" exact="0"/>
        
        <do_if value="$component.pilot?">
          <set_value name="$pilot" exact="$component.pilot"/>
        </do_if>
        
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <do_if value="global.$GT_Pilots.{$pilot}.$BlockedLevel?">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          </do_if>
          
          <do_if value="$blockedLevel gt 1">
            <!-- Queue manual training request; AI processes it after current cycle -->
            <set_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested" exact="true"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'manual_training_queued'"/>
            
            <show_notification text="{77000,9903}.[$pilot.name]" timeout="6s" priority="7"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] Manual training queued for ' + $pilot.name + ' on ship ' + $component.idcode + ' (blocked level ' + $blockedLevel + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] Manual training requested but blocked level invalid for ship ' + $component.idcode" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle when user clicks "GT Rename" -->
    <cue name="GT_RenameAction" instantiate="true" namespace="this">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] MD: GT_RenameAction triggered'" chance="100"/>
        </do_if>
        <set_value name="$component" exact="event.param.$object"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] MD: Component = ' + $component" chance="100"/>
        </do_if>
        
        <!-- Get GT original name.
             Priority: ship registry (authoritative) -> pilot registry (legacy fallback). -->
        <set_value name="$originalName" exact="null"/>
        <set_value name="$pilot" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$component}? and global.$GT_Ships.{$component}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{$component}.$OriginalShipName"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] MD: Found original name in ship registry: ' + $originalName" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="$component.pilot?">
          <set_value name="$pilot" exact="$component.pilot"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] MD: Pilot found: ' + $pilot.name" chance="100"/>
          </do_if>
          <do_if value="$originalName == '' or not $originalName?">
            <do_if value="global.$GT_Pilots.{$pilot}?">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT Context Rename] MD: Pilot exists in GT_Pilots registry'" chance="100"/>
              </do_if>
              <do_if value="global.$GT_Pilots.{$pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT Context Rename] MD: Found original name in pilot registry: ' + $originalName" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT Context Rename] MD: Pilot exists but $OriginalShipName field is missing'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT Context Rename] MD: Pilot NOT found in GT_Pilots registry'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] MD: Ship has no pilot'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- If still unresolved, prefill with current ship name (better UX than empty field). -->
        <do_if value="not $originalName? or $originalName == ''">
          <set_value name="$originalName" exact="$component.knownname"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] MD: No stored GT original name found - using current ship name: ' + $originalName" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Store original name in NPCBlackboard for Lua to read -->
        <set_value name="player.entity.$GT_ContextRename_OriginalName" exact="$originalName"/>
        
        <!-- Trigger Lua event to open rename dialog -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] MD: Raising Lua event gt.openRenameContext with originalName: ' + $originalName" chance="100"/>
        </do_if>
        <raise_lua_event name="'gt.openRenameContext'" param="$component"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] MD: Lua event raised'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle rename confirmation from Lua - set GT original name -->
    <!-- Event-driven: triggered when Lua signals the rename confirmation -->
    <cue name="HandleRenameConfirmation" instantiate="true">
      <conditions>
        <event_object_signalled object="player.entity" param="'gt_context_rename_confirmed'"/>
      </conditions>
      <actions>
        <!-- Get component from event parameter (SignalObject third param becomes event.param2) -->
        <set_value name="$component" exact="event.param2"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Received signal for component = ' + $component" chance="100"/>
        </do_if>
        
        <!-- Get newName from NPCBlackboard (stored separately to avoid table access issues) -->
        <set_value name="$newName" exact="player.entity.$GT_ContextRename_NewName"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] HandleRenameConfirmation: newName from blackboard = ' + $newName" chance="100"/>
        </do_if>
        
        <!-- event.param2 should be a component object (like in vanilla orders.xml) -->
        <!-- Use component from event.param2 directly as the ship -->
        <set_value name="$ship" exact="event.param2"/>
        <run_actions ref="md.GLX_Lib_Orders.GLX_ShipIsInGTService" result="$isGTService">
          <param name="ship" value="$ship"/>
        </run_actions>
        <do_if value="not $isGTService">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] HandleRenameConfirmation: skipping rename - ship not in GT service (ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Processing rename - ship = ' + $ship + ', newName = ' + $newName" chance="100"/>
          </do_if>
        
        <!-- Keep rename text available for potential multi-ship batch signals from Lua.
             The value is overwritten on every new confirmation. -->
        
        <!-- Get pilot from ship -->
        <set_value name="$pilot" exact="null"/>
        <do_if value="$ship.pilot?">
          <set_value name="$pilot" exact="$ship.pilot"/>
        </do_if>
        
        <!-- Store original name in GT_Pilots registry -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Context Rename] HandleRenameConfirmation: ship = ' + $ship + ', newName = ' + $newName" chance="100"/>
          <debug_text text="'[GT Context Rename] HandleRenameConfirmation: pilot = ' + (if $pilot != null then @$pilot.name else 'null')" chance="100"/>
        </do_if>
        
        <do_if value="$pilot?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Checking if pilot exists in GT_Pilots registry'" chance="100"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{$pilot}?">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Pilot found in registry, setting $OriginalShipName'" chance="100"/>
            </do_if>
            <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$newName"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Set global.$GT_Pilots.{' + $pilot.name + '}.$OriginalShipName = ' + $newName" chance="100"/>
            </do_if>
            
            <!-- CRITICAL FIX: Also update ship registry so custom name takes priority -->
            <!-- The UpdateShipName cue checks ship registry first, then pilot registry -->
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{$ship}?">
              <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$newName"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Also updated global.$GT_Ships.{' + $ship.idcode + '}.$OriginalShipName = ' + $newName" chance="100"/>
            </do_if>
            
            <!-- Trigger GT ship name update to apply the new original name -->
            <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
              <param name="pilot" value="$pilot"/>
              <param name="ship" value="$ship"/>
              <param name="forceUpdate" value="true"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] Set original name for pilot ' + $pilot.name + ' to: ' + $newName + ' and triggered name update'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Pilot not registered yet - register them first so we can store the original name -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Pilot ' + $pilot.name + ' NOT found in GT_Pilots registry - registering pilot first'" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_Ship_Management.Register_Pilot">
              <param name="pilot" value="$pilot"/>
              <param name="ship" value="$ship"/>
            </run_actions>
            
            <!-- Now set the original name -->
            <do_if value="global.$GT_Pilots.{$pilot}?">
              <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$newName"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Registered pilot and set $OriginalShipName = ' + $newName" chance="100"/>
              </do_if>
              
              <!-- CRITICAL FIX: Also update ship registry so custom name takes priority -->
              <!-- The UpdateShipName cue checks ship registry first, then pilot registry -->
              <do_if value="not global.$GT_Ships?">
                <set_value name="global.$GT_Ships" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_Ships.{$ship}?">
                <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$newName"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT Context Rename] HandleRenameConfirmation: Also updated global.$GT_Ships.{' + $ship.idcode + '}.$OriginalShipName = ' + $newName" chance="100"/>
              </do_if>
              
              <!-- Trigger GT ship name update to apply the new original name -->
              <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
                <param name="pilot" value="$pilot"/>
                <param name="ship" value="$ship"/>
                <param name="forceUpdate" value="true"/>
              </run_actions>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT Context Rename] Set original name for newly registered pilot ' + $pilot.name + ' to: ' + $newName + ' and triggered name update'" chance="100"/>
              </do_if>
            </do_if>
          </do_else>
        </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT Context Rename] WARNING: Ship has no pilot - cannot save original name'" chance="100"/>
            </do_if>
          </do_else>
        </do_else>
      </actions>
    </cue>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_CoreSystem" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Core System Initialization -->
    <cue name="SystemInit" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_player_created/>
          <event_game_loaded/>
        </check_any>
        <check_value value="not global.$GT_Initialized? or not global.$GT_Initialized"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Core system initializing...'" chance="100"/>
        </do_if>

        <!-- Initialize global data structures -->
        <set_value name="global.$GT_Ships" exact="table[]" comment="Registry of all managed ships"/>
        <set_value name="global.$GT_FleetData" exact="table[]" comment="Fleet coordination data"/>
        <set_value name="global.$GT_MarketData" exact="table[]" comment="Market intelligence cache"/>
        <set_value name="global.$GT_TerritoryData" exact="table[]" comment="Territory management data"/>
        <set_value name="global.$GT_SessionStats" exact="table[]" comment="Current session statistics"/>
        <set_value name="global.$GT_TradesAwaitingValidation" exact="table[]" comment="Trades found by MD, awaiting AI validation"/>
        
        <!-- PHASE 1: Initialize event-driven signaling system -->
        <set_value name="global.$GT_XPEventQueue" exact="[]" comment="Event queue for instant XP processing"/>
        
        <!-- PHASE 2: Initialize training event system -->
        <set_value name="global.$GT_TrainingEventQueue" exact="[]" comment="Event queue for instant training processing"/>
        
        <!-- PHASE 3: Initialize fleet and market event systems -->
        <set_value name="global.$GT_FleetEventQueue" exact="[]" comment="Event queue for instant fleet coordination"/>
        <set_value name="global.$GT_MarketEventQueue" exact="[]" comment="Event queue for instant market intelligence"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Event-driven signaling system initialized (XP + Training + Fleet + Market)'" chance="100"/>
        </do_if>
        
        <!-- Initialize configuration settings for re-enabled features -->
        <do_if value="not global.$GT_Config?">
          <set_value name="global.$GT_Config" exact="table[]"/>
        </do_if>
        
        <do_if value="not global.$GT_Config.$Fleet?">
          <set_value name="global.$GT_Config.$Fleet" exact="table[]"/>
        </do_if>
        
        <do_if value="not global.$GT_Config.$Territory?">
          <set_value name="global.$GT_Config.$Territory" exact="table[]"/>
        </do_if>
        
        <!-- RE-ENABLED FEATURES: Set defaults to enabled since event-driven system is now stable -->
        <!-- Legacy load balancing config removed - pure event-driven system -->
        
        <do_if value="not global.$GT_Config.$Fleet.$EnablePerformanceMonitoring?">
          <set_value name="global.$GT_Config.$Fleet.$EnablePerformanceMonitoring" exact="true" comment="Fleet performance monitoring"/>
        </do_if>
        
        <do_if value="not global.$GT_Config.$Territory.$EnableConflictResolution?">
          <set_value name="global.$GT_Config.$Territory.$EnableConflictResolution" exact="true" comment="Territory conflict resolution"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Previously disabled features have been re-enabled with event-driven architecture'" chance="100"/>
        </do_if>
        
        <!-- Initialize subsystems -->
        <set_value name="global.$GT_SessionStats.$StartTime" exact="player.age"/>
        <set_value name="global.$GT_SessionStats.$TotalProfit" exact="0Cr"/>
        <set_value name="global.$GT_SessionStats.$TradesCompleted" exact="0"/>
        <set_value name="global.$GT_SessionStats.$XPGained" exact="0"/>
        
        <!-- Cleanup: Remove incorrect legacy globals (these were local variables incorrectly saved as globals) -->
        <set_value name="$cleanupCount" exact="0"/>
        <do_if value="global.$gt_AdvancedAnalytics?">
          <remove_value name="global.$gt_AdvancedAnalytics"/>
          <set_value name="$cleanupCount" exact="$cleanupCount + 1"/>
        </do_if>
        <do_if value="global.$gt_FleetCoord?">
          <remove_value name="global.$gt_FleetCoord"/>
          <set_value name="$cleanupCount" exact="$cleanupCount + 1"/>
        </do_if>
        <do_if value="global.$gt_SatelliteIntel?">
          <remove_value name="global.$gt_SatelliteIntel"/>
          <set_value name="$cleanupCount" exact="$cleanupCount + 1"/>
        </do_if>
        <do_if value="global.$gt_ThreatIntel?">
          <remove_value name="global.$gt_ThreatIntel"/>
          <set_value name="$cleanupCount" exact="$cleanupCount + 1"/>
        </do_if>
        <do_if value="$cleanupCount gt 0 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] Cleaned up ' + $cleanupCount + ' incorrect legacy globals (gt_AdvancedAnalytics, gt_FleetCoord, gt_SatelliteIntel, gt_ThreatIntel)'" chance="100"/>
        </do_if>
        
        <!-- Station Subordinate Order Access: Protected order IDs list -->
        <!-- Orders in this list are protected from being replaced by vanilla TradeRoutine -->
        <!-- when the ship is assigned as a station subordinate (lib.request.orders patch) -->
        <set_value name="global.$GT_ProtectedOrderIDs" exact="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply', 'GalaxyTraderMK4Supply2', 'GalaxyTraderMK2', 'GalaxyTraderMK1', 'GalaxyMiner']" comment="Protected GT order IDs"/>
        
        <!-- Set initialization complete flag -->
        <set_value name="global.$GT_Initialized" exact="true"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Core system initialization complete'" chance="100"/>
        </do_if>
        
        <!-- Show welcome notification -->
        <show_notification text="'GalaxyTrader MK3 Activated'" timeout="5s"/>
        <!-- Broadcast initialization signal for dependent modules -->
        <signal_cue cue="md.GT_CoreSystem.SystemInit"/>
        <!-- Legacy registration catch-up: seed original ship names for already-registered pilots -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0 and global.$GT_Pilots?">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <set_value name="$pilot" exact="$ship.pilot"/>
            <do_if value="$pilot and global.$GT_Pilots.{$pilot}? and not global.$GT_Pilots.{$pilot}.$OriginalShipName?">
              <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$cleanedName">
                <param name="shipName" value="$ship.knownname"/>
              </run_actions>
              <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$cleanedName"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] SystemInit: Seeded cleaned original name for pilot ' + $pilot.name + ': ' + $cleanedName + ' (from: ' + $ship.knownname + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </cue>

    <!-- Re-apply protected order ID list on every load/new game. SystemInit skips when GT_Initialized is already
         true in the save, which left stale lists without GalaxyTraderMK4Supply and broke interact-menu GT actions. -->
    <cue name="RefreshGTProtectedOrderIDs" instantiate="true" version="2">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <set_value name="global.$GT_ProtectedOrderIDs" exact="['GalaxyTraderMK3', 'GalaxyTraderMK4Supply', 'GalaxyTraderMK4Supply2', 'GalaxyTraderMK2', 'GalaxyTraderMK1', 'GalaxyMiner']" comment="Protected GT order IDs (canonical; refreshed each session)"/>
      </actions>
    </cue>

    <!-- TEMPORARY COMPATIBILITY RECOVERY (remove after next few releases):
         root cause is fixed; this is only for legacy saves that still carry ghost order state.
         Save-load one-shot recovery for ghost GalaxyMiner state:
         default/current report GalaxyMiner as running, but ship has zero active orders. -->
    <cue name="RecoverGhostRunningGalaxyMinerOnLoad" instantiate="true" version="1">
      <conditions>
        <event_game_loaded/>
      </conditions>
      <delay exact="30s"/>
      <actions>
        <set_value name="$recoveredCount" exact="0"/>
        <find_ship_by_true_owner name="$playerShips" faction="faction.player" space="player.galaxy" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="false"/>
        <do_if value="$playerShips.count gt 0">
          <do_all exact="$playerShips.count" counter="$i">
            <set_value name="$ship" exact="$playerShips.{$i}"/>
            <set_value name="$isGhostMinerState" exact="false"/>
            <do_if value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyMiner' and $ship.order? and @$ship.order.id == 'GalaxyMiner' and $ship.defaultorder.isrunning and $ship.order.isrunning and (($ship.orders? and $ship.orders.count == 0) or not $ship.orders?) and $ship.pilot? and @$ship.pilot.exists and (not global.$GT_CleanupIntent? or not global.$GT_CleanupIntent.{$ship}?) and (not global.$GT_OrphanVerifyPending? or not global.$GT_OrphanVerifyPending.{$ship}?) and (not global.$GT_DelayedVerificationState? or not global.$GT_DelayedVerificationState.{$ship}?)">
              <set_value name="$isGhostMinerState" exact="true"/>
            </do_if>

            <do_if value="$isGhostMinerState">
              <set_value name="$homeStation" exact="if $ship.defaultorder.$homeStation? then $ship.defaultorder.$homeStation else null"/>
              <set_value name="$homeSector" exact="if $ship.defaultorder.$homeSector? then $ship.defaultorder.$homeSector else null"/>
              <set_value name="$resourceBasket" exact="if $ship.defaultorder.$resourceBasket? then $ship.defaultorder.$resourceBasket else []"/>
              <set_value name="$stationList" exact="if $ship.defaultorder.$stationList? then $ship.defaultorder.$stationList else []"/>
              <set_value name="$overflowThreshold" exact="if $ship.defaultorder.$overflowThreshold? then $ship.defaultorder.$overflowThreshold else 0.9"/>
              <set_value name="$allowOverflowSellToOthers" exact="if $ship.defaultorder.$allowOverflowSellToOthers? then $ship.defaultorder.$allowOverflowSellToOthers else false"/>
              <set_value name="$assignToStation" exact="if $ship.defaultorder.$assignToStation? then $ship.defaultorder.$assignToStation else false"/>
              <set_value name="$playerStationsOnly" exact="if $ship.defaultorder.$playerStationsOnly? then $ship.defaultorder.$playerStationsOnly else true"/>
              <set_value name="$checkDemandFirst" exact="if $ship.defaultorder.$checkDemandFirst? then $ship.defaultorder.$checkDemandFirst else true"/>
              <set_value name="$stayAtHome" exact="if $ship.defaultorder.$stayAtHome? then $ship.defaultorder.$stayAtHome else false"/>
              <set_value name="$maxGatherDistance" exact="if $ship.defaultorder.$maxGatherDistance? then $ship.defaultorder.$maxGatherDistance else 3"/>
              <set_value name="$maxSellDistance" exact="if $ship.defaultorder.$maxSellDistance? then $ship.defaultorder.$maxSellDistance else 1"/>
              <set_value name="$fleetBalancing" exact="if $ship.defaultorder.$fleetBalancing? then $ship.defaultorder.$fleetBalancing else true"/>
              <set_value name="$demandRecheckInterval" exact="if $ship.defaultorder.$demandRecheckInterval? then $ship.defaultorder.$demandRecheckInterval else 20s"/>
              <set_value name="$physicalStorageAbortPercent" exact="if $ship.defaultorder.$physicalStorageAbortPercent? then $ship.defaultorder.$physicalStorageAbortPercent else 20"/>
              <set_value name="$criticalDemandDelta" exact="if $ship.defaultorder.$criticalDemandDelta? then $ship.defaultorder.$criticalDemandDelta else 25"/>
              <set_value name="$minSwitchCooldown" exact="if $ship.defaultorder.$minSwitchCooldown? then $ship.defaultorder.$minSwitchCooldown else 60s"/>
              <set_value name="$minCargoCommitPercent" exact="if $ship.defaultorder.$minCargoCommitPercent? then $ship.defaultorder.$minCargoCommitPercent else 30"/>
              <set_value name="$hardEmergencyDelta" exact="if $ship.defaultorder.$hardEmergencyDelta? then $ship.defaultorder.$hardEmergencyDelta else 40"/>
              <set_value name="$notifications" exact="if $ship.defaultorder.$notifications? then $ship.defaultorder.$notifications else true"/>
              <set_value name="$debuglevel" exact="if $ship.defaultorder.$debuglevel? then $ship.defaultorder.$debuglevel else 1"/>

              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-LoadHeal] RESTART_GHOST_GALAXYMINER ship=' + $ship.idcode + ' commander=' + (if $ship.commander? and $ship.commander.exists then $ship.commander.idcode else 'NONE') + ' defaultRunning=1 currentRunning=1 orders=' + (if $ship.orders? then $ship.orders.count else 0)" chance="100"/>
              </do_if>

              <cancel_order order="$ship.defaultorder"/>
              <create_order id="'GalaxyMiner'" object="$ship" default="true">
                <param name="homeStation" value="$homeStation"/>
                <param name="homeSector" value="$homeSector"/>
                <param name="resourceBasket" value="$resourceBasket"/>
                <param name="stationList" value="$stationList"/>
                <param name="overflowThreshold" value="$overflowThreshold"/>
                <param name="allowOverflowSellToOthers" value="$allowOverflowSellToOthers"/>
                <param name="assignToStation" value="$assignToStation"/>
                <param name="playerStationsOnly" value="$playerStationsOnly"/>
                <param name="checkDemandFirst" value="$checkDemandFirst"/>
                <param name="stayAtHome" value="$stayAtHome"/>
                <param name="maxGatherDistance" value="$maxGatherDistance"/>
                <param name="maxSellDistance" value="$maxSellDistance"/>
                <param name="fleetBalancing" value="$fleetBalancing"/>
                <param name="demandRecheckInterval" value="$demandRecheckInterval"/>
                <param name="physicalStorageAbortPercent" value="$physicalStorageAbortPercent"/>
                <param name="criticalDemandDelta" value="$criticalDemandDelta"/>
                <param name="minSwitchCooldown" value="$minSwitchCooldown"/>
                <param name="minCargoCommitPercent" value="$minCargoCommitPercent"/>
                <param name="hardEmergencyDelta" value="$hardEmergencyDelta"/>
                <param name="notifications" value="$notifications"/>
                <param name="debuglevel" value="$debuglevel"/>
              </create_order>
              <set_value name="$recoveredCount" operation="add"/>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-LoadHeal] END_GHOST recovered=' + $recoveredCount + ' age=' + (player.age / 1s)i" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Ship Registration System -->
    <cue name="RegisterShip" instantiate="true">
      <conditions>
        <event_object_order_ready object="player.galaxy" comment="Detect when player-owned ships get order-ready transitions"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <!-- Validate ship -->
        <do_if value="$ship.isplayerowned and $ship.primarypurpose == purpose.trade">
          <run_actions ref="md.GT_CoreSystem.IsShipInRegistry" result="$shipInRegistry">
            <param name="ship" value="$ship"/>
          </run_actions>
          <!-- Check if already registered -->
          <do_if value="not $shipInRegistry">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Registering new trading ship: ' + $ship.knownname" chance="100"/>
            </do_if>
            
            <!-- Create ship data structure -->
            <run_actions ref="md.GT_CoreSystem.EnsureShipRegistryEntry">
              <param name="ship" value="$ship"/>
            </run_actions>
            <set_value name="global.$GT_Ships.{$ship}.$RegisterTime" exact="player.age"/>
            <set_value name="global.$GT_Ships.{$ship}.$Level" exact="1"/>
            <set_value name="global.$GT_Ships.{$ship}.$XP" exact="0"/>
            <set_value name="global.$GT_Ships.{$ship}.$TotalProfit" exact="0Cr"/>
            <set_value name="global.$GT_Ships.{$ship}.$TradesCompleted" exact="0"/>
            <set_value name="global.$GT_Ships.{$ship}.$TotalTrades" exact="0"/>
            <set_value name="global.$GT_Ships.{$ship}.$LastTradeProfit" exact="0Cr"/>
            <set_value name="global.$GT_Ships.{$ship}.$LastMoney" exact="$ship.money"/>
            <set_value name="global.$GT_Ships.{$ship}.$TrainingCompleted" exact="[]"/>
            <set_value name="global.$GT_Ships.{$ship}.$ThreatReports" exact="0"/>
            <set_value name="global.$GT_Ships.{$ship}.$LastThreatTime" exact="0"/>
            <set_value name="global.$GT_Ships.{$ship}.$Territory" exact="null"/>
            <run_actions ref="md.GT_CoreSystem.TouchShipRegistryLastUpdate">
              <param name="ship" value="$ship"/>
            </run_actions>
            
            <!-- Notify player (respect FleetUpdates setting) -->
            <do_if value="global.$GT_Config? and global.$GT_Config.$Notifications? and global.$GT_Config.$Notifications.$FleetUpdates">
              <show_notification text="'GalaxyTrader MK3: ' + $ship.knownname + ' registered for advanced trading'" timeout="3s"/>
            </do_if>
            <!-- Trigger XP system pilot registration for ship renaming -->
            <set_value name="global.$GT_RegisterPilot" exact="$ship.pilot"/>
            <set_value name="global.$GT_RegisterShip" exact="$ship"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] XP registration triggered for pilot ' + $ship.pilot.name + ' on ship ' + $ship.knownname" chance="100"/>
            </do_if>
            <!-- Event-driven registration processing -->
            <signal_cue_instantly cue="md.GT_XP_Training.RegisterPilot" param="table[$Pilot=$ship.pilot, $Ship=$ship]"/>
          </do_if>

        </do_if>
        
      </actions>
    </cue>
    
    <!-- Delayed commander GT reactivation:
         re-registers subordinates and restarts Assist inheritance when commander gains GT. -->
    <cue name="ProcessCommanderGTReactivation" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.ProcessCommanderGTReactivation"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$commander" exact="event.param.$Commander"/>
        <set_value name="$attempt" exact="1"/>
        <do_if value="event.param.$Attempt?">
          <set_value name="$attempt" exact="event.param.$Attempt"/>
        </do_if>
        
        <do_if value="$commander? and $commander.exists and $commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$commander.defaultorder.id})">
          <set_value name="$reactivatedSubs" exact="0"/>
          <set_value name="$lightRefreshedSubs" exact="0"/>
          <set_value name="$fullRefreshedSubs" exact="0"/>
          <set_value name="$assistNudgedSubs" exact="0"/>
          <set_value name="$unresolvedSubs" exact="[]"/>
          <set_value name="$sourceMode" exact="'all'"/>
          <set_value name="$subordinates" exact="[]"/>
          <set_value name="$retryAll" exact="false"/>
          
          <!-- Prefer unresolved subset on retries to avoid fleet-wide full reprocessing. -->
          <do_if value="event.param.$PendingSubs? and typeof event.param.$PendingSubs == datatype.list and event.param.$PendingSubs.count gt 0">
            <set_value name="$sourceMode" exact="'pending'"/>
            <set_value name="$subordinates" exact="event.param.$PendingSubs"/>
          </do_if>
          <do_elseif value="$commander.allsubordinates? and @$commander.allsubordinates.count gt 0">
            <!-- First pass source: commander's subordinate tree -->
            <set_value name="$subordinates" exact="@$commander.allsubordinates"/>
          </do_elseif>
          <do_else>
            <!-- Keep existing settle behavior: hierarchy can be empty briefly on startup. -->
            <set_value name="$retryAll" exact="true"/>
          </do_else>
          
          <do_if value="$subordinates.count gt 0">
            <do_all exact="$subordinates.count" counter="$si">
              <set_value name="$sub" exact="$subordinates.{$si}"/>
              <set_value name="$isCandidate" exact="false"/>
              <set_value name="$needsRetry" exact="false"/>
              
              <do_if value="$sub? and $sub.exists and $sub.isplayerowned and not ($sub.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$sub.defaultorder.id}))">
                <do_if value="$sub.commander? and $sub.commander == $commander or ($sub.toplevelcommander? and $sub.toplevelcommander == $commander)">
                  <set_value name="$isCandidate" exact="true"/>
                </do_if>
                <do_else>
                  <!-- Hierarchy may still be settling; retry this subordinate only. -->
                  <set_value name="$needsRetry" exact="true"/>
                </do_else>
              </do_if>
              
              <do_if value="$isCandidate">
                <do_if value="not $sub.pilot?">
                  <!-- Pilot binding can lag one tick after AI restart. -->
                  <set_value name="$needsRetry" exact="true"/>
                </do_if>
                <do_else>
                  <set_value name="$isUnchanged" exact="false"/>
                  <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$sub.pilot}? and global.$GT_Pilots.{$sub.pilot}.$AssociatedShip? and global.$GT_Pilots.{$sub.pilot}.$AssociatedShip == $sub and global.$GT_Ships? and global.$GT_Ships.{$sub}? and global.$GT_Ships.{$sub}.$Pilot? and global.$GT_Ships.{$sub}.$Pilot == $sub.pilot">
                    <set_value name="$isUnchanged" exact="true"/>
                  </do_if>
                  
                  <!-- Light path: unchanged mapping only needs a name/status sync. -->
                  <do_if value="$isUnchanged and md.GT_Ship_Management.Update_Pilot_Ship_Name?">
                    <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
                      <param name="pilot" value="$sub.pilot"/>
                      <param name="ship" value="$sub"/>
                      <param name="forceUpdate" value="false"/>
                    </run_actions>
                    <set_value name="$lightRefreshedSubs" operation="add"/>
                    <set_value name="$reactivatedSubs" operation="add"/>
                  </do_if>
                  <do_else>
                    <!-- Full path: changed/missing mapping requires full registration + assignment sync. -->
                    <run_actions ref="md.GT_Ship_Management.Register_Pilot">
                      <param name="pilot" value="$sub.pilot"/>
                      <param name="ship" value="$sub"/>
                    </run_actions>
                    <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
                      <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
                        <param name="ship" value="$sub"/>
                        <param name="new_pilot" value="$sub.pilot"/>
                        <param name="old_pilot" value="$sub.pilot"/>
                      </run_actions>
                    </do_if>
                    <set_value name="$fullRefreshedSubs" operation="add"/>
                    <set_value name="$reactivatedSubs" operation="add"/>
                  </do_else>
                  <!-- Existing Assist subordinates may still mimic a prior commander order (e.g. Hold Position).
                       MD signals do not reach Assist while a nested mimic script is active; restart Assist
                       with commander baseorder like a fresh subordinate assignment. -->
                  <do_if value="$sub.defaultorder? and @$sub.defaultorder.id == 'Assist' and $commander.defaultorder?">
                    <cancel_order order="$sub.defaultorder"/>
                    <create_order id="'Assist'" object="$sub" default="true">
                      <param name="baseorder" value="$commander.defaultorder"/>
                      <param name="orderobject" value="$commander"/>
                    </create_order>
                    <set_value name="$assistNudgedSubs" operation="add"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Core] Restarted Assist inheritance for ' + $sub.idcode + ' under commander ' + $commander.idcode + ' (order=' + @$commander.defaultorder.id + ')'" chance="100"/>
                    </do_if>
                  </do_if>
                </do_else>
              </do_if>
              
              <do_if value="$needsRetry and $sub? and $sub.exists">
                <append_to_list name="$unresolvedSubs" exact="$sub"/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] Commander GT reactivation delayed pass #' + $attempt + ': processed ' + $reactivatedSubs + ' subordinate(s) for commander ' + $commander.idcode + ' (source=' + $sourceMode + ', light=' + $lightRefreshedSubs + ', full=' + $fullRefreshedSubs + ', assistRestarted=' + $assistNudgedSubs + ', unresolved=' + $unresolvedSubs.count + ')'" chance="100"/>
          </do_if>
          
          <!-- Retry a few times while relationships/pilot bindings settle. -->
          <do_if value="$unresolvedSubs.count gt 0 and $attempt lt 5">
            <run_actions ref="md.GT_CoreSystem.QueueProcessCommanderGTReactivation">
              <param name="commander" value="$commander"/>
              <param name="attempt" value="$attempt + 1"/>
              <param name="pendingSubs" value="$unresolvedSubs"/>
            </run_actions>
          </do_if>
          <do_elseif value="$retryAll and $attempt lt 5">
            <run_actions ref="md.GT_CoreSystem.QueueProcessCommanderGTReactivation">
              <param name="commander" value="$commander"/>
              <param name="attempt" value="$attempt + 1"/>
            </run_actions>
          </do_elseif>
        </do_if>
      </actions>
    </cue>
    
    <!-- Authoritative commander GT state transition handler.
         Driven by commander AI default-order tracking, not fragile engine order payload timing. -->
    <cue name="HandleCommanderGTStateChanged" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Commander_GT_State_Changed'"/>
      </conditions>
      <actions>
        <set_value name="$payload" exact="event.param2"/>
        <set_value name="$commander" exact="$payload.$Commander"/>
        <set_value name="$isGTActive" exact="false"/>
        <do_if value="$payload.$IsGTActive?">
          <set_value name="$isGTActive" exact="$payload.$IsGTActive"/>
        </do_if>
        <set_value name="$reportedSubCount" exact="0"/>
        <do_if value="$payload.$SubordinateCount?">
          <set_value name="$reportedSubCount" exact="$payload.$SubordinateCount"/>
        </do_if>
        
        <do_if value="$commander? and $commander.exists and $commander.isclass.ship and $commander.isplayerowned">
          <do_if value="not global.$GT_CommanderGTState?">
            <set_value name="global.$GT_CommanderGTState" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_CommanderGTState.{$commander}?">
            <set_value name="global.$GT_CommanderGTState.{$commander}" exact="table[
              $IsGTActive = false,
              $WasCommander = false,
              $LastUpdate = 0s
            ]"/>
          </do_if>
          
          <set_value name="$state" exact="global.$GT_CommanderGTState.{$commander}"/>
          <set_value name="$prevActive" exact="false"/>
          <do_if value="$state.$IsGTActive? and $state.$IsGTActive">
            <set_value name="$prevActive" exact="true"/>
          </do_if>
          
          <!-- Commander role memory avoids missing reassignment transitions when subordinate list
               is temporarily empty at event time. -->
          <set_value name="$isCommanderNow" exact="false"/>
          <do_if value="($commander.allsubordinates? and @$commander.allsubordinates.count gt 0) or ($commander.subordinates? and @$commander.subordinates.count gt 0) or $reportedSubCount gt 0">
            <set_value name="$isCommanderNow" exact="true"/>
            <set_value name="$state.$WasCommander" exact="true"/>
          </do_if>
          
          <set_value name="$wasCommanderKnown" exact="false"/>
          <do_if value="$state.$WasCommander? and $state.$WasCommander">
            <set_value name="$wasCommanderKnown" exact="true"/>
          </do_if>
          
          <!-- Process transitions for known commanders (current or historical). -->
          <do_if value="$isCommanderNow or $wasCommanderKnown">
            <do_if value="$isGTActive and not $prevActive">
              <run_actions ref="md.GT_CoreSystem.QueueProcessCommanderGTReactivation">
                <param name="commander" value="$commander"/>
                <param name="attempt" value="1"/>
              </run_actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] Commander GT state transition: ACTIVE for ' + $commander.idcode + ' (source=' + (if $payload.$Source? then $payload.$Source else 'unknown') + ', subCount=' + $reportedSubCount + ')'" chance="100"/>
              </do_if>
            </do_if>
            <do_elseif value="not $isGTActive and $prevActive">
              <run_actions ref="md.GT_CoreSystem.QueueVerifyCommanderSubordinateCleanup">
                <param name="commander" value="$commander"/>
              </run_actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] Commander GT state transition: INACTIVE for ' + $commander.idcode + ' (source=' + (if $payload.$Source? then $payload.$Source else 'unknown') + ', subCount=' + $reportedSubCount + ')'" chance="100"/>
              </do_if>
            </do_elseif>
          </do_if>
          
          <set_value name="$state.$IsGTActive" exact="$isGTActive"/>
          <set_value name="$state.$LastUpdate" exact="player.age"/>
        </do_if>
      </actions>
    </cue>

    <!-- Shared scheduler for commander GT reactivation processing. -->
    <library name="QueueProcessCommanderGTReactivation" purpose="run_actions">
      <params>
        <param name="commander"/>
        <param name="attempt" default="1"/>
        <param name="pendingSubs" default="null"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.ProcessCommanderGTReactivation" param="table[
          $Commander = $commander,
          $Attempt = $attempt,
          $PendingSubs = $pendingSubs
        ]"/>
      </actions>
    </library>

    <!-- Shared scheduler for delayed commander subordinate cleanup verification. -->
    <library name="QueueVerifyCommanderSubordinateCleanup" purpose="run_actions">
      <params>
        <param name="commander"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.VerifyCommanderSubordinateCleanup" param="table[
          $Commander = $commander
        ]"/>
      </actions>
    </library>

    <!-- Shared GT-control checker for vanilla pilot assignment/finalize flows. -->
    <library name="DeterminePilotAssignmentHasGTOrder" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$hasGTOrder" exact="false"/>
        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
          <param name="ship" value="$ship"/>
          <param name="checkRegistry" value="false"/>
          <param name="checkState" value="false"/>
        </run_actions>
        <do_if value="$gtStatus.$IsGTControlled">
          <set_value name="$hasGTOrder" exact="true"/>
        </do_if>
        <!-- Pilot-exchange flow can be active while defaultorder is not yet a GT order. -->
        <do_if value="not $hasGTOrder and $ship.order? and @$ship.order.id == 'DockAndPilotExchange' and global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$PilotExchange? and global.$GT_Ships.{$ship}.$PilotExchange">
          <set_value name="$hasGTOrder" exact="true"/>
        </do_if>
        <return value="$hasGTOrder"/>
      </actions>
    </library>

    <!-- Guarded pilot-registration helper for call sites that already check availability. -->
    <library name="TryRegisterPilotForShip" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$didRegister" exact="false"/>
        <do_if value="md.GT_Ship_Management.Register_Pilot?">
          <run_actions ref="md.GT_Ship_Management.Register_Pilot">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="$didRegister" exact="true"/>
        </do_if>
        <return value="$didRegister"/>
      </actions>
    </library>

    <!-- Guarded pilot-tag updater (optionally with explicit level override). -->
    <library name="TryUpdatePilotNameTag" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="level" default="null"/>
      </params>
      <actions>
        <set_value name="$tagApplied" exact="false"/>
        <do_if value="md.GT_Ship_Management.Update_Pilot_Name_Tag?">
          <do_if value="$level? and $level != null">
            <run_actions ref="md.GT_Ship_Management.Update_Pilot_Name_Tag" result="$tagApplied">
              <param name="pilot" value="$pilot"/>
              <param name="level" value="$level"/>
            </run_actions>
          </do_if>
          <do_else>
            <run_actions ref="md.GT_Ship_Management.Update_Pilot_Name_Tag" result="$tagApplied">
              <param name="pilot" value="$pilot"/>
            </run_actions>
          </do_else>
        </do_if>
        <return value="$tagApplied"/>
      </actions>
    </library>

    <!-- Shared scheduler for delayed orphan verification checks. -->
    <library name="QueueVerifyShipOrphaned" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'unknown'"/>
        <param name="traceId" default="'NONE'"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.VerifyShipOrphaned" param="table[
          $Ship = $ship,
          $Source = $source,
          $TraceId = $traceId
        ]"/>
      </actions>
    </library>

    <!-- Shared event emitter: request orphan check with basic payload. -->
    <library name="QueueCheckShipOrphaned" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
          $Ship = $ship
        ]"/>
      </actions>
    </library>

    <!-- Shared event emitter: request orphan check with full trace payload. -->
    <library name="QueueCheckShipOrphanedDetailed" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="force" default="true"/>
        <param name="source" default="'unknown'"/>
        <param name="traceId" default="'NONE'"/>
      </params>
      <actions>
        <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
          $Ship = $ship,
          $Force = $force,
          $Source = $source,
          $TraceId = $traceId
        ]"/>
      </actions>
    </library>

    <!-- Build normalized orphan-check context from defaults + optional payload overrides. -->
    <library name="BuildOrphanCheckContext" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="payload" default="null"/>
        <param name="defaultSource" default="'UNKNOWN'"/>
        <param name="defaultTraceTag" default="'CHECK_ORPHANED'"/>
      </params>
      <actions>
        <set_value name="$context" exact="table[
          $Source = $defaultSource,
          $TraceId = if $ship? and $ship.exists then $ship.idcode + '|' + $defaultTraceTag + '|' + (player.age / 1s)i else 'UNKNOWN|' + $defaultTraceTag + '|' + (player.age / 1s)i,
          $Force = false
        ]"/>
        <do_if value="$payload? and $payload.$Force? and $payload.$Force">
          <set_value name="$context.$Force" exact="true"/>
        </do_if>
        <do_if value="$payload? and $payload.$Source?">
          <set_value name="$context.$Source" exact="$payload.$Source"/>
        </do_if>
        <do_if value="$payload? and $payload.$TraceId?">
          <set_value name="$context.$TraceId" exact="$payload.$TraceId"/>
        </do_if>
        <return value="$context"/>
      </actions>
    </library>

    <!-- Shared GT ship-registry membership checker. -->
    <library name="IsShipInRegistry" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$inRegistry" exact="false"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <set_value name="$inRegistry" exact="true"/>
        </do_if>
        <return value="$inRegistry"/>
      </actions>
    </library>

    <!-- Ensure GT ship-registry root + per-ship entry table exist. -->
    <library name="EnsureShipRegistryEntry" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
        </do_if>
      </actions>
    </library>

    <!-- Shared ship-registry timestamp touch helper. -->
    <library name="TouchShipRegistryLastUpdate" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
      </actions>
    </library>

    <!-- Shared wrapper for ship-name refresh scheduling. -->
    <library name="RequestShipNameRefresh" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot"/>
        <param name="reason" default="'unknown'"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="reason" value="$reason"/>
        </run_actions>
      </actions>
    </library>

    <!-- Guarded helper: request ship-name refresh only for known pilot records. -->
    <library name="MaybeRequestShipNameRefreshForPilot" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="reason" default="'unknown'"/>
      </params>
      <actions>
        <do_if value="$ship.pilot and global.$GT_Pilots.{$ship.pilot}? and md.GT_Ship_Management.Update_Pilot_Ship_Name?">
          <run_actions ref="md.GT_CoreSystem.RequestShipNameRefresh">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$ship.pilot"/>
            <param name="reason" value="$reason"/>
          </run_actions>
        </do_if>
      </actions>
    </library>

    <!-- Shared event emit for fleet blacklist application refresh. -->
    <library name="QueueApplyBlacklistToFleet" purpose="run_actions">
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist">
          <set_value name="global.$GT_ManualBlacklistAssignRequested" exact="true"/>
          <signal_cue_instantly cue="md.GT_ThreatIntelligence.ApplyBlacklistToFleet"/>
        </do_if>
      </actions>
    </library>

    <!-- Shared post-registration side-effects for both registration paths. -->
    <library name="FinalizeShipRegistrationSideEffects" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="nameRefreshReason" default="'unknown'"/>
      </params>
      <actions>
        <run_actions ref="md.GT_CoreSystem.MaybeRequestShipNameRefreshForPilot">
          <param name="ship" value="$ship"/>
          <param name="reason" value="$nameRefreshReason"/>
        </run_actions>
        <run_actions ref="md.GT_CoreSystem.QueueApplyBlacklistToFleet"/>
      </actions>
    </library>

    <!-- Restore paused training requirements after temporary pilot pause/resume flows. -->
    <library name="RestorePausedTrainingStateIfNeeded" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="debugLabel" default="'TRAINING STATE RESTORED'"/>
      </params>
      <actions>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded?">
          <set_value name="$pausedLevel" exact="0"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$PausedBlockedLevel?">
            <set_value name="$pausedLevel" exact="global.$GT_Pilots.{$pilot}.$PausedBlockedLevel"/>
          </do_if>
          <set_value name="$alreadyCompleted" exact="false"/>
          <do_if value="$pausedLevel gt 0 and global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
            <do_all exact="global.$GT_Pilots.{$pilot}.$TrainingCompleted.count" counter="$tcIdx">
              <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted.{$tcIdx} == $pausedLevel">
                <set_value name="$alreadyCompleted" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="not $alreadyCompleted and $pausedLevel gt 1">
            <set_value name="global.$GT_Pilots.{$pilot}.$XPBlocked" exact="true"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel" exact="$pausedLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] ' + $debugLabel + ': Pilot ' + $pilot.name + ' still needs level ' + $pausedLevel + ' training'" chance="100"/>
            </do_if>
          </do_if>
          <do_elseif value="$alreadyCompleted">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] ' + $debugLabel + ': Skipping stale paused training restore for ' + $pilot.name + ' (level ' + $pausedLevel + ' already completed)'" chance="100"/>
            </do_if>
          </do_elseif>
          <remove_value name="global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$PausedBlockedLevel"/>
        </do_if>
      </actions>
    </library>

    <!-- Mark orphan verify pending once and queue delayed verification. -->
    <library name="QueueOrphanVerifyIfNotPending" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'unknown'"/>
        <param name="traceId" default="'NONE'"/>
      </params>
      <actions>
        <do_if value="not global.$GT_OrphanVerifyPending?">
          <set_value name="global.$GT_OrphanVerifyPending" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_OrphanVerifyPending.{$ship}?">
          <set_value name="global.$GT_OrphanVerifyPending.{$ship}" exact="player.age"/>
          <run_actions ref="md.GT_CoreSystem.QueueVerifyShipOrphaned">
            <param name="ship" value="$ship"/>
            <param name="source" value="$source"/>
            <param name="traceId" value="$traceId"/>
          </run_actions>
        </do_if>
      </actions>
    </library>

    <!-- Shared original-name resolver for cleanup payloads. -->
    <library name="GetOriginalShipNameForCleanup" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{$ship}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{$ship.pilot}.$OriginalShipName"/>
        </do_elseif>
        <do_elseif value="$ship.macro?">
          <set_value name="$originalName" exact="@$ship.macro.name"/>
        </do_elseif>
        <return value="$originalName"/>
      </actions>
    </library>

    <!-- Return original ship name from ship registry only (no pilot/macro fallback). -->
    <library name="GetShipRegistryOriginalName" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{$ship}.$OriginalShipName"/>
        </do_if>
        <return value="$originalName"/>
      </actions>
    </library>

    <!-- Shared cleanup signal emitter for standard order-aborted payloads. -->
    <library name="EmitShipOrderAborted" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="reason" default="'unknown'"/>
        <param name="originalName" default="null"/>
      </params>
      <actions>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = $ship,
          $Pilot = $pilot,
          $Reason = $reason,
          $OriginalName = $originalName
        ]"/>
      </actions>
    </library>

    <!-- Resolve cleanup original-name chain and emit standard order-aborted payload. -->
    <library name="EmitShipOrderAbortedWithResolvedName" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="reason" default="'unknown'"/>
      </params>
      <actions>
        <run_actions ref="md.GT_CoreSystem.GetOriginalShipNameForCleanup" result="$originalName">
          <param name="ship" value="$ship"/>
        </run_actions>
        <run_actions ref="md.GT_CoreSystem.EmitShipOrderAborted">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="reason" value="$reason"/>
          <param name="originalName" value="$originalName"/>
        </run_actions>
      </actions>
    </library>

    <!-- Shared pilot-link synchronizer for vanilla reassignment/finalize flows.
         clearPausedFields is explicit because some paths intentionally keep pause metadata. -->
    <library name="SyncPilotShipLinkState" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="ship"/>
        <param name="hasGTOrder" default="false"/>
        <param name="clearPausedFields" default="false"/>
      </params>
      <actions>
        <do_if value="$pilot and $ship and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
          <do_if value="$pilot.idcode?">
            <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="$pilot.idcode"/>
          </do_if>
          <do_elseif value="not global.$GT_Pilots.{$pilot}.$PilotID?">
            <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="''"/>
          </do_elseif>
          <do_if value="$hasGTOrder">
            <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'active'"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$ResumedTime" exact="player.age"/>
          </do_if>
          <do_else>
            <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'paused'"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$Ship"/>
          </do_else>
          <do_if value="$clearPausedFields">
            <remove_value name="global.$GT_Pilots.{$pilot}.$PausedTime"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$PausedReason"/>
          </do_if>
        </do_if>
      </actions>
    </library>

    <!-- Shared scheduler for delayed vanilla pilot finalize retries/deferrals. -->
    <library name="QueueFinalizeVanillaPilotAssignment" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'unknown'"/>
        <param name="newPilot" default="null"/>
        <param name="newPilotTemplate" default="null"/>
        <param name="attempt" default="1"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.FinalizeVanillaPilotAssignmentForGT" param="table[
          $Ship = $ship,
          $source = $source,
          $newPilot = $newPilot,
          $newPilotTemplate = $newPilotTemplate,
          $attempt = $attempt
        ]"/>
      </actions>
    </library>

    <!-- Shared bounded retry helper for delayed vanilla pilot finalize. -->
    <library name="MaybeRetryFinalizeVanillaPilotAssignment" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'unknown'"/>
        <param name="newPilot" default="null"/>
        <param name="newPilotTemplate" default="null"/>
        <param name="attempt" default="1"/>
        <param name="maxAttempts" default="5"/>
      </params>
      <actions>
        <do_if value="$attempt lt $maxAttempts">
          <run_actions ref="md.GT_CoreSystem.QueueFinalizeVanillaPilotAssignment">
            <param name="ship" value="$ship"/>
            <param name="source" value="$source"/>
            <param name="newPilot" value="$newPilot"/>
            <param name="newPilotTemplate" value="$newPilotTemplate"/>
            <param name="attempt" value="$attempt + 1"/>
          </run_actions>
        </do_if>
      </actions>
    </library>

    <!-- Bounded pilot-tag refresh scheduler (~1s / +2s / +2s burst). -->
    <library name="QueueBoundedPilotTagRefresh" purpose="run_actions">
      <params>
        <param name="pilot" default="null"/>
        <param name="stableKey" default="''"/>
        <param name="sector" default="null"/>
        <param name="ship" default="null"/>
        <param name="source" default="'unknown'"/>
        <param name="attempt" default="1"/>
        <param name="ejectMode" default="false"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.BoundedPilotTagRefresh" param="table[
          $pilot = $pilot,
          $stableKey = $stableKey,
          $sector = $sector,
          $ship = $ship,
          $source = $source,
          $attempt = $attempt,
          $ejectMode = $ejectMode
        ]"/>
      </actions>
    </library>

    <!-- Back-compat alias (all call sites migrated to bounded scheduler). -->
    <library name="QueueDeferredPilotTagRefresh" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="source" default="'unknown'"/>
      </params>
      <actions>
        <run_actions ref="md.GT_CoreSystem.QueueBoundedPilotTagRefresh">
          <param name="pilot" value="$pilot"/>
          <param name="source" value="$source"/>
          <param name="attempt" value="1"/>
        </run_actions>
      </actions>
    </library>

    <library name="MaybeRetryBoundedPilotTagRefresh" purpose="run_actions">
      <params>
        <param name="pilot" default="null"/>
        <param name="stableKey" default="''"/>
        <param name="sector" default="null"/>
        <param name="ship" default="null"/>
        <param name="source" default="'unknown'"/>
        <param name="attempt" default="1"/>
        <param name="ejectMode" default="false"/>
        <param name="tagApplied" default="false"/>
        <param name="maxAttempts" default="3"/>
      </params>
      <actions>
        <do_if value="not $tagApplied and $attempt lt $maxAttempts">
          <signal_cue_instantly cue="md.GT_CoreSystem.BoundedPilotTagRefreshFollowUp" param="table[
            $pilot = $pilot,
            $stableKey = $stableKey,
            $sector = $sector,
            $ship = $ship,
            $source = $source,
            $attempt = $attempt + 1,
            $ejectMode = $ejectMode
          ]"/>
        </do_if>
      </actions>
    </library>

    <library name="ExecuteBoundedPilotTagRefreshAttempt" purpose="run_actions">
      <params>
        <param name="pilotHint" default="null"/>
        <param name="stableKey" default="''"/>
        <param name="sector" default="null"/>
        <param name="ship" default="null"/>
        <param name="source" default="'unknown'"/>
        <param name="attempt" default="1"/>
        <param name="ejectMode" default="false"/>
      </params>
      <actions>
        <set_value name="$livePilot" exact="$pilotHint"/>
        <do_if value="$ejectMode or not ($livePilot and $livePilot.exists)">
          <run_actions ref="md.GT_Ship_Management.Resolve_Live_Pilot_Tiered" result="$tierRes">
            <param name="livePilotHint" value="$pilotHint"/>
            <param name="stableKey" value="$stableKey"/>
            <param name="sector" value="$sector"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$tierRes.$Pilot? and $tierRes.$Pilot.exists">
            <set_value name="$livePilot" exact="$tierRes.$Pilot"/>
            <run_actions ref="md.GT_Ship_Management.Rebind_Pilot_Registry" result="$rb">
              <param name="livePilot" value="$livePilot"/>
              <param name="registryPilotHint" value="$pilotHint"/>
              <param name="stableKey" value="$stableKey"/>
              <param name="sector" value="$sector"/>
            </run_actions>
            <set_value name="$livePilot" exact="if $rb.$Pilot? then $rb.$Pilot else $livePilot"/>
          </do_if>
        </do_if>

        <set_value name="$tagApplied" exact="false"/>
        <do_if value="$livePilot and $livePilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$livePilot}?">
          <run_actions ref="md.GT_CoreSystem.TryUpdatePilotNameTag" result="$tagApplied">
            <param name="pilot" value="$livePilot"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] BoundedPilotTagRefresh: attempt=' + $attempt + ', pilot=' + $livePilot.name + ', tagApplied=' + $tagApplied + ', source=' + $source + ', ejectMode=' + $ejectMode" chance="100"/>
          </do_if>
        </do_if>

        <!-- Eject logbook is independent of tag refresh â€” registry key may differ from live spacesuit pilot entity. -->
        <do_if value="$ejectMode">
          <run_actions ref="md.GT_CoreSystem.TryWriteTestPilotEjectLogbook">
            <param name="registryPilotHint" value="$pilotHint"/>
            <param name="livePilot" value="$livePilot"/>
            <param name="stableKey" value="$stableKey"/>
            <param name="sector" value="$sector"/>
          </run_actions>
        </do_if>

        <run_actions ref="md.GT_CoreSystem.MaybeRetryBoundedPilotTagRefresh">
          <param name="pilot" value="$livePilot"/>
          <param name="stableKey" value="$stableKey"/>
          <param name="sector" value="$sector"/>
          <param name="ship" value="$ship"/>
          <param name="source" value="$source"/>
          <param name="attempt" value="$attempt"/>
          <param name="ejectMode" value="$ejectMode"/>
          <param name="tagApplied" value="$tagApplied"/>
        </run_actions>
      </actions>
    </library>
    <library name="HandleRescueRebindForEjectedPilot" purpose="run_actions">
      <params>
        <param name="livePilot"/>
        <param name="ship"/>
        <param name="hasGTOrder" default="false"/>
        <param name="source" default="'rescue_rebind'"/>
        <param name="registryPilotHint" default="null"/>
        <param name="spacesuit" default="null"/>
      </params>
      <actions>
        <set_value name="$result" exact="false"/>
        <do_if value="not $ship or not $ship.exists">
          <return value="false"/>
        </do_if>

        <set_value name="$registryKey" exact="null"/>
        <set_value name="$stableKey" exact="''"/>
        <set_value name="$wasEjected" exact="false"/>

        <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}? and global.$GT_Pilots.{$registryPilotHint}.$Status? and global.$GT_Pilots.{$registryPilotHint}.$Status == 'ejected'">
          <set_value name="$registryKey" exact="$registryPilotHint"/>
          <set_value name="$wasEjected" exact="true"/>
          <do_if value="global.$GT_Pilots.{$registryPilotHint}.$StableIdentity?">
            <set_value name="$stableKey" exact="global.$GT_Pilots.{$registryPilotHint}.$StableIdentity"/>
          </do_if>
        </do_if>

        <do_if value="not $wasEjected and $livePilot and $livePilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$livePilot}? and global.$GT_Pilots.{$livePilot}.$Status? and global.$GT_Pilots.{$livePilot}.$Status == 'ejected'">
          <set_value name="$registryKey" exact="$livePilot"/>
          <set_value name="$wasEjected" exact="true"/>
          <do_if value="global.$GT_Pilots.{$livePilot}.$StableIdentity?">
            <set_value name="$stableKey" exact="global.$GT_Pilots.{$livePilot}.$StableIdentity"/>
          </do_if>
        </do_if>

        <do_if value="not $wasEjected and $livePilot and $livePilot.exists">
          <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$liveStableKey">
            <param name="pilot" value="$livePilot"/>
          </run_actions>
          <do_if value="$liveStableKey != ''">
            <set_value name="$stableKey" exact="$liveStableKey"/>
          </do_if>
        </do_if>

        <do_if value="not $wasEjected and $stableKey != '' and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$ei">
            <set_value name="$eKey" exact="global.$GT_Pilots.keys.{$ei}"/>
            <do_if value="global.$GT_Pilots.{$eKey}.$Status? and global.$GT_Pilots.{$eKey}.$Status == 'ejected' and global.$GT_Pilots.{$eKey}.$StableIdentity? and global.$GT_Pilots.{$eKey}.$StableIdentity == $stableKey">
              <set_value name="$registryKey" exact="$eKey"/>
              <set_value name="$wasEjected" exact="true"/>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="not $wasEjected">
          <return value="false"/>
        </do_if>

        <set_value name="$resolvedPilot" exact="if $livePilot and $livePilot.exists then $livePilot else null"/>

        <!-- registryPilotHint must match the live entity â€” never rebind the wrong ejected record. -->
        <do_if value="$registryPilotHint and $livePilot and $livePilot.exists and $stableKey != ''">
          <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$liveStableKey">
            <param name="pilot" value="$livePilot"/>
          </run_actions>
          <do_if value="$liveStableKey != '' and $liveStableKey != $stableKey">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] HandleRescueRebindForEjectedPilot: stable mismatch â€” live=' + $liveStableKey + ', registry=' + $stableKey + ', liveName=' + (if $livePilot.name? then $livePilot.name else 'NONE') + ', source=' + $source" chance="100"/>
            </do_if>
            <return value="false"/>
          </do_if>
          <set_value name="$pilotStillInSpacesuit" exact="$livePilot.ship? and $livePilot.ship.exists and $livePilot.ship.isclass.spacesuit"/>
          <do_if value="not $pilotStillInSpacesuit">
            <run_actions ref="md.GT_Ship_Management.Pilot_Is_On_Ship" result="$liveOnShip">
              <param name="pilot" value="$livePilot"/>
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="not $liveOnShip">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] HandleRescueRebindForEjectedPilot: live pilot not on ship=' + $ship.idcode + ', source=' + $source" chance="100"/>
              </do_if>
              <return value="false"/>
            </do_if>
          </do_if>
          <do_if value="$pilotStillInSpacesuit">
            <set_value name="$resolvedPilot" exact="null"/>
          </do_if>
        </do_if>

        <do_if value="not ($resolvedPilot and $resolvedPilot.exists) or ($resolvedPilot.ship? and $resolvedPilot.ship.isclass.spacesuit)">
          <set_value name="$resolveHint" exact="if $registryKey and global.$GT_Pilots.{$registryKey}.$LastKnownPilotRef? then global.$GT_Pilots.{$registryKey}.$LastKnownPilotRef else null"/>
          <run_actions ref="md.GT_Ship_Management.Resolve_Live_Pilot_Tiered" result="$tierRes">
            <param name="livePilotHint" value="$resolveHint"/>
            <param name="stableKey" value="$stableKey"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$tierRes.$Pilot? and $tierRes.$Pilot.exists">
            <set_value name="$resolvedPilot" exact="$tierRes.$Pilot"/>
          </do_if>
          <do_elseif value="$resolveHint and $resolveHint.exists">
            <set_value name="$resolvedPilot" exact="$resolveHint"/>
          </do_elseif>
        </do_if>

        <do_if value="not ($resolvedPilot and $resolvedPilot.exists)">
          <return value="false"/>
        </do_if>

        <run_actions ref="md.GT_Ship_Management.Rebind_Pilot_Registry" result="$rebindResult">
          <param name="livePilot" value="$resolvedPilot"/>
          <param name="registryPilotHint" value="if $registryKey? then $registryKey else $resolvedPilot"/>
          <param name="stableKey" value="$stableKey"/>
          <param name="ship" value="$ship"/>
        </run_actions>
        <set_value name="$pilot" exact="if $rebindResult.$Pilot? then $rebindResult.$Pilot else $resolvedPilot"/>

        <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
          <param name="pilot" value="$pilot"/>
          <param name="ship" value="$ship"/>
          <param name="hasGTOrder" value="$hasGTOrder"/>
          <param name="clearPausedFields" value="true"/>
        </run_actions>

        <run_actions ref="md.GT_Ship_Management.Clear_Eject_Scratch_State">
          <param name="pilot" value="$pilot"/>
        </run_actions>

        <run_actions ref="md.GT_CoreSystem.QueueBoundedPilotTagRefresh">
          <param name="pilot" value="$pilot"/>
          <param name="stableKey" value="$stableKey"/>
          <param name="ship" value="$ship"/>
          <param name="source" value="$source"/>
        </run_actions>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] HandleRescueRebindForEjectedPilot: pilot=' + (if $pilot.name? then $pilot.name else 'NONE') + ', ship=' + $ship.idcode + ', hasGTOrder=' + $hasGTOrder + ', source=' + $source" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>

    <!-- TEST: one logbook entry per eject, map object = pilot spacesuit (not destroyed hull). -->
    <library name="TryWriteTestPilotEjectLogbook" purpose="run_actions">
      <params>
        <param name="registryPilotHint"/>
        <param name="livePilot" default="null"/>
        <param name="stableKey" default="''"/>
        <param name="sector" default="null"/>
      </params>
      <actions>
        <do_if value="not global.$GT_Pilots?">
          <return value="false"/>
        </do_if>

        <!-- Resolve ejected registry row â€” live spacesuit pilot entity is often a different key than destroy-time hint. -->
        <set_value name="$regKey" exact="null"/>
        <set_value name="$lookupStable" exact="$stableKey"/>
        <do_if value="$registryPilotHint and global.$GT_Pilots.{$registryPilotHint}? and global.$GT_Pilots.{$registryPilotHint}.$Status? and global.$GT_Pilots.{$registryPilotHint}.$Status == 'ejected'">
          <set_value name="$regKey" exact="$registryPilotHint"/>
          <do_if value="$lookupStable == '' and global.$GT_Pilots.{$registryPilotHint}.$StableIdentity?">
            <set_value name="$lookupStable" exact="global.$GT_Pilots.{$registryPilotHint}.$StableIdentity"/>
          </do_if>
        </do_if>
        <do_if value="not $regKey and $livePilot and $livePilot.exists and global.$GT_Pilots.{$livePilot}? and global.$GT_Pilots.{$livePilot}.$Status? and global.$GT_Pilots.{$livePilot}.$Status == 'ejected'">
          <set_value name="$regKey" exact="$livePilot"/>
          <do_if value="$lookupStable == '' and global.$GT_Pilots.{$livePilot}.$StableIdentity?">
            <set_value name="$lookupStable" exact="global.$GT_Pilots.{$livePilot}.$StableIdentity"/>
          </do_if>
        </do_if>
        <do_if value="not $regKey and $lookupStable != '' and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$ri">
            <set_value name="$candKey" exact="global.$GT_Pilots.keys.{$ri}"/>
            <do_if value="global.$GT_Pilots.{$candKey}.$Status? and global.$GT_Pilots.{$candKey}.$Status == 'ejected' and global.$GT_Pilots.{$candKey}.$StableIdentity? and global.$GT_Pilots.{$candKey}.$StableIdentity == $lookupStable">
              <set_value name="$regKey" exact="$candKey"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $regKey">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] TryWriteTestPilotEjectLogbook: no ejected registry row (hint=' + (if $registryPilotHint and $registryPilotHint.name? then $registryPilotHint.name else 'NONE') + ', stable=' + $lookupStable + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        <do_if value="global.$GT_Pilots.{$regKey}.$EjectLogbookWritten? and global.$GT_Pilots.{$regKey}.$EjectLogbookWritten">
          <return value="false"/>
        </do_if>

        <set_value name="$spacesuitPilot" exact="if $livePilot and $livePilot.exists then $livePilot else null"/>
        <do_if value="not ($spacesuitPilot and $spacesuitPilot.exists) and global.$GT_Pilots.{$regKey}.$LastKnownPilotRef? and global.$GT_Pilots.{$regKey}.$LastKnownPilotRef.exists">
          <set_value name="$spacesuitPilot" exact="global.$GT_Pilots.{$regKey}.$LastKnownPilotRef"/>
        </do_if>

        <set_value name="$spacesuit" exact="null"/>
        <do_if value="$spacesuitPilot and $spacesuitPilot.exists and $spacesuitPilot.ship? and $spacesuitPilot.ship.exists and $spacesuitPilot.ship.isclass.spacesuit">
          <set_value name="$spacesuit" exact="$spacesuitPilot.ship"/>
        </do_if>

        <!-- Spacesuit may not exist at hull-destroy time; scan eject sector once pilot entity is bound (Resolve_Live_Pilot_Tiered pattern). -->
        <do_if value="not ($spacesuit? and $spacesuit.exists) and $lookupStable != ''">
          <set_value name="$searchSector" exact="if $sector? then $sector else (if global.$GT_Pilots.{$regKey}.$EjectedSector? then global.$GT_Pilots.{$regKey}.$EjectedSector else null)"/>
          <do_if value="$searchSector? and $searchSector.exists">
            <set_value name="$spacesuits" exact="[]"/>
            <find_ship_by_true_owner name="$spacesuits" class="class.spacesuit" faction="faction.player" space="$searchSector" multiple="true"/>
            <do_all exact="$spacesuits.count" counter="$si">
              <set_value name="$suit" exact="$spacesuits.{$si}"/>
              <do_if value="not ($spacesuit? and $spacesuit.exists) and $suit.pilot? and $suit.pilot.exists">
                <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$suitStable">
                  <param name="pilot" value="$suit.pilot"/>
                </run_actions>
                <do_if value="$suitStable == $lookupStable">
                  <set_value name="$spacesuit" exact="$suit"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
        </do_if>

        <do_if value="not ($spacesuit? and $spacesuit.exists)">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] TryWriteTestPilotEjectLogbook: spacesuit not resolved yet (reg=' + (if $regKey.name? then $regKey.name else 'NONE') + ', stable=' + $lookupStable + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>

        <set_value name="global.$GT_Pilots.{$regKey}.$EjectLogbookWritten" exact="true"/>
        <run_actions ref="md.GT_CoreSystem.RegisterEjectedSpacesuitForDockWatch">
          <param name="spacesuit" value="$spacesuit"/>
          <param name="registryPilotHint" value="$regKey"/>
        </run_actions>
        <set_value name="$pilotName" exact="if $regKey.name? then $regKey.name else 'Unknown Pilot'"/>
        <set_value name="$sectorName" exact="if global.$GT_Pilots.{$regKey}.$EjectedSector? and global.$GT_Pilots.{$regKey}.$EjectedSector.knownname? then global.$GT_Pilots.{$regKey}.$EjectedSector.knownname else 'unknown sector'"/>
        <set_value name="$ejectLogbookMessage" exact="'\033#text_inprogress#' + {77000,3228}.[player.name, $pilotName, $sectorName] + '\033X'"/>
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="$ejectLogbookMessage"/>
          <param name="Category" value="'upkeep'"/>
          <param name="Title" value="'\033#text_inprogress#' + {77000,3227} + '\033X'"/>
          <param name="Object" value="$spacesuit"/>
          <param name="Interaction" value="'showonmap'"/>
          <param name="CheckGlobalSettings" value="false"/>
        </run_actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] TryWriteTestPilotEjectLogbook: wrote eject logbook, reg=' + (if $regKey.name? then $regKey.name else 'NONE') + ', spacesuit=' + (if $spacesuit.idcode? then $spacesuit.idcode else 'NONE')" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>

    <!-- True for direct player ships and Assist subs (isplayerowned is often false on subordinates). -->
    <library name="GT_ShipIsPlayerFleet" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <do_if value="not $ship or not $ship.exists">
          <return value="false"/>
        </do_if>
        <do_if value="$ship.isplayerowned">
          <return value="true"/>
        </do_if>
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander.isplayerowned">
          <return value="true"/>
        </do_if>
        <do_if value="$ship.owner? and $ship.owner == faction.player">
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>

    <!-- Per-spacesuit dock pickup handler (shared by WatchEjectedSpacesuitDock). -->
    <library name="ProcessEjectedSpacesuitDockPickup" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="dockObject"/>
        <param name="registryPilotHint" default="null"/>
        <param name="source" default="'spacesuit_docked'"/>
      </params>
      <actions>
        <set_value name="$rescued" exact="false"/>
        <do_if value="not $spacesuit or not $spacesuit.exists">
          <return value="false"/>
        </do_if>
        <run_actions ref="md.GT_CoreSystem.ResolveRescueShipFromDockObject" result="$rescueShip">
          <param name="dockObject" value="$dockObject"/>
        </run_actions>
        <do_if value="not ($rescueShip and $rescueShip.exists)">
          <return value="false"/>
        </do_if>
        <set_value name="$livePilot" exact="if $spacesuit.pilot? and $spacesuit.pilot.exists then $spacesuit.pilot else null"/>
        <set_value name="$regHint" exact="$registryPilotHint"/>
        <do_if value="not $regHint and $livePilot and $livePilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$livePilot}? and global.$GT_Pilots.{$livePilot}.$Status? and global.$GT_Pilots.{$livePilot}.$Status == 'ejected'">
          <set_value name="$regHint" exact="$livePilot"/>
        </do_if>
        <do_if value="not $regHint and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$ei">
            <set_value name="$eKey" exact="global.$GT_Pilots.keys.{$ei}"/>
            <do_if value="not $regHint and global.$GT_Pilots.{$eKey}.$Status? and global.$GT_Pilots.{$eKey}.$Status == 'ejected'">
              <set_value name="$regHint" exact="$eKey"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$regHint?">
          <run_actions ref="md.GT_CoreSystem.TryRescueEjectedPilotAtPickup" result="$rescued">
            <param name="livePilot" value="$livePilot"/>
            <param name="rescueShip" value="$rescueShip"/>
            <param name="registryPilotHint" value="$regHint"/>
            <param name="spacesuit" value="$spacesuit"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <do_if value="not $rescued">
          <run_actions ref="md.GT_CoreSystem.QueueScanPlayerShipForEjectedPilotRescue">
            <param name="ship" value="$rescueShip"/>
            <param name="source" value="'spacesuit_docked_at_rescue'"/>
            <param name="registryPilotHint" value="$regHint"/>
          </run_actions>
        </do_if>
        <return value="$rescued"/>
      </actions>
    </library>

    <!-- Start a per-spacesuit dock watcher (avoids global group â€” not safe during save-load second pass). -->
    <library name="RegisterEjectedSpacesuitForDockWatch" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="registryPilotHint" default="null"/>
      </params>
      <actions>
        <do_if value="not $spacesuit or not $spacesuit.exists or not $spacesuit.isclass.spacesuit">
          <return value="false"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_CoreSystem.WatchEjectedSpacesuitDock" param="table[
          $Spacesuit = $spacesuit,
          $RegistryPilotHint = $registryPilotHint
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] RegisterEjectedSpacesuitForDockWatch: suit=' + (if $spacesuit.idcode? then $spacesuit.idcode else 'NONE')" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>

    <!-- event_object_docked param is often a dock bay, not the rescue hull â€” walk up to the ship. -->
    <library name="ResolveRescueShipFromDockObject" purpose="run_actions">
      <params>
        <param name="dockObject"/>
      </params>
      <actions>
        <set_value name="$rescueShip" exact="null"/>
        <do_if value="$dockObject? and $dockObject.exists">
          <do_if value="$dockObject.isclass.ship and not $dockObject.isclass.spacesuit">
            <set_value name="$rescueShip" exact="$dockObject"/>
          </do_if>
          <do_elseif value="$dockObject.container? and $dockObject.container.exists and $dockObject.container.isclass.ship and not $dockObject.container.isclass.spacesuit">
            <set_value name="$rescueShip" exact="$dockObject.container"/>
          </do_elseif>
          <do_elseif value="$dockObject.dock? and $dockObject.dock.controllable? and $dockObject.dock.controllable.exists">
            <set_value name="$rescueShip" exact="$dockObject.dock.controllable"/>
          </do_elseif>
        </do_if>
        <return value="$rescueShip"/>
      </actions>
    </library>

    <!-- Resolve rescue hull from a spacesuit at dock/removal time (vanilla often destroys the suit on pickup). -->
    <library name="ResolveRescueShipFromSpacesuitContext" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="sector" default="null"/>
      </params>
      <actions>
        <set_value name="$rescueShip" exact="null"/>
        <do_if value="$spacesuit?">
          <do_if value="$spacesuit.container? and $spacesuit.container.exists and $spacesuit.container.isclass.ship and not $spacesuit.container.isclass.spacesuit">
            <set_value name="$rescueShip" exact="$spacesuit.container"/>
          </do_if>
          <do_if value="not ($rescueShip? and $rescueShip.exists) and $spacesuit.assigneddock? and $spacesuit.assigneddock.controllable? and $spacesuit.assigneddock.controllable.exists">
            <set_value name="$rescueShip" exact="$spacesuit.assigneddock.controllable"/>
          </do_if>
          <do_if value="not ($rescueShip? and $rescueShip.exists) and $spacesuit.order? and @$spacesuit.order.id == 'DockAt' and $spacesuit.order.$destination? and $spacesuit.order.$destination.exists and $spacesuit.order.$destination.isclass.ship and not $spacesuit.order.$destination.isclass.spacesuit">
            <set_value name="$rescueShip" exact="$spacesuit.order.$destination"/>
          </do_if>
        </do_if>
        <do_if value="not ($rescueShip? and $rescueShip.exists)">
          <run_actions ref="md.GT_CoreSystem.FindRescueCandidateShipsNearSpacesuit" result="$candidates">
            <param name="spacesuit" value="$spacesuit"/>
            <param name="sector" value="$sector"/>
          </run_actions>
          <do_if value="$candidates.count gt 0">
            <set_value name="$rescueShip" exact="$candidates.{1}"/>
          </do_if>
        </do_if>
        <return value="$rescueShip"/>
      </actions>
    </library>

    <!-- Rescue pickup: logbook + rebind when a rescue hull is identified. -->
    <library name="TryRescueEjectedPilotAtPickup" purpose="run_actions">
      <params>
        <param name="livePilot"/>
        <param name="rescueShip"/>
        <param name="registryPilotHint"/>
        <param name="spacesuit" default="null"/>
        <param name="source" default="'pilot_pickup'"/>
      </params>
      <actions>
        <set_value name="$rescued" exact="false"/>
        <do_if value="not $rescueShip or not $rescueShip.exists">
          <return value="false"/>
        </do_if>
        <run_actions ref="md.GT_CoreSystem.GT_ShipIsPlayerFleet" result="$isPlayerFleet">
          <param name="ship" value="$rescueShip"/>
        </run_actions>
        <do_if value="not $isPlayerFleet">
          <return value="false"/>
        </do_if>
        <set_value name="$pilotName" exact="if $livePilot and $livePilot.exists and $livePilot.name? then $livePilot.name else (if $registryPilotHint and $registryPilotHint.name? then $registryPilotHint.name else 'NONE')"/>
        <run_actions ref="md.GT_CoreSystem.TryWriteTestPilotRescueLogbook">
          <param name="pilot" value="$livePilot"/>
          <param name="ship" value="$rescueShip"/>
          <param name="registryPilotHint" value="$registryPilotHint"/>
        </run_actions>
        <run_actions ref="md.GT_CoreSystem.DeterminePilotAssignmentHasGTOrder" result="$hasGTOrder">
          <param name="ship" value="$rescueShip"/>
        </run_actions>
        <set_value name="$resolvedPilot" exact="if $livePilot and $livePilot.exists then $livePilot else null"/>
        <do_if value="$resolvedPilot and $resolvedPilot.exists">
          <run_actions ref="md.GT_CoreSystem.HandleRescueRebindForEjectedPilot" result="$rescued">
            <param name="livePilot" value="$resolvedPilot"/>
            <param name="ship" value="$rescueShip"/>
            <param name="hasGTOrder" value="$hasGTOrder"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="spacesuit" value="$spacesuit"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <do_if value="not $rescued">
          <run_actions ref="md.GT_CoreSystem.ScanPlayerShipForEjectedPilotRescue" result="$rescued">
            <param name="ship" value="$rescueShip"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <return value="$rescued"/>
      </actions>
    </library>

    <!-- Scan every player-fleet ship in sector for an ejected pilot already transferred as crew. -->
    <library name="ScanPlayerFleetInSectorForEjectedPilot" purpose="run_actions">
      <params>
        <param name="sector"/>
        <param name="registryPilotHint"/>
        <param name="source" default="'sector_fleet_rescue_scan'"/>
      </params>
      <actions>
        <set_value name="$rescued" exact="false"/>
        <do_if value="not $registryPilotHint or not global.$GT_Pilots? or not global.$GT_Pilots.{$registryPilotHint}? or not global.$GT_Pilots.{$registryPilotHint}.$Status? or global.$GT_Pilots.{$registryPilotHint}.$Status != 'ejected'">
          <return value="false"/>
        </do_if>
        <set_value name="$searchSpace" exact="if $sector? and $sector.exists then $sector else player.sector"/>
        <find_ship_by_true_owner name="$ships" space="$searchSpace" faction="faction.player" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="true"/>
        <do_all exact="$ships.count" counter="$si">
          <do_if value="not $rescued">
            <set_value name="$scanShip" exact="$ships.{$si}"/>
            <run_actions ref="md.GT_CoreSystem.ScanPlayerShipForEjectedPilotRescue" result="$rescued">
              <param name="ship" value="$scanShip"/>
              <param name="registryPilotHint" value="$registryPilotHint"/>
              <param name="source" value="$source"/>
            </run_actions>
          </do_if>
        </do_all>
        <return value="$rescued"/>
      </actions>
    </library>

    <!-- One logbook entry per rescue; map marker on the rescue ship (vanilla player logbook + object= pattern). -->
    <library name="TryWriteTestPilotRescueLogbook" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="ship"/>
        <param name="registryPilotHint" default="null"/>
      </params>
      <actions>
        <set_value name="$regKey" exact="if $registryPilotHint? then $registryPilotHint else (if $pilot? then $pilot else null)"/>
        <set_value name="$alreadyWritten" exact="false"/>
        <do_if value="$regKey and global.$GT_Pilots? and global.$GT_Pilots.{$regKey}? and global.$GT_Pilots.{$regKey}.$RescueLogbookWritten? and global.$GT_Pilots.{$regKey}.$RescueLogbookWritten">
          <set_value name="$alreadyWritten" exact="true"/>
        </do_if>
        <do_if value="not $alreadyWritten and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$dedupeStable" exact="''"/>
          <do_if value="$regKey and global.$GT_Pilots.{$regKey}.$StableIdentity?">
            <set_value name="$dedupeStable" exact="global.$GT_Pilots.{$regKey}.$StableIdentity"/>
          </do_if>
          <do_elseif value="$regKey and $regKey.exists? and $regKey.exists">
            <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$dedupeStable">
              <param name="pilot" value="$regKey"/>
            </run_actions>
          </do_elseif>
          <do_if value="$dedupeStable != ''">
            <do_all exact="global.$GT_Pilots.keys.count" counter="$di">
              <set_value name="$dedupeKey" exact="global.$GT_Pilots.keys.{$di}"/>
              <do_if value="not $alreadyWritten and global.$GT_Pilots.{$dedupeKey}.$StableIdentity? and global.$GT_Pilots.{$dedupeKey}.$StableIdentity == $dedupeStable and global.$GT_Pilots.{$dedupeKey}.$RescueLogbookWritten? and global.$GT_Pilots.{$dedupeKey}.$RescueLogbookWritten">
                <set_value name="$alreadyWritten" exact="true"/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <do_if value="$alreadyWritten">
          <return value="false"/>
        </do_if>
        <do_if value="not $ship or not $ship.exists">
          <return value="false"/>
        </do_if>
        <set_value name="$pilotName" exact="if $pilot and $pilot.exists and $pilot.name? then $pilot.name else (if $regKey and $regKey.name? then $regKey.name else 'Unknown Pilot')"/>
        <set_value name="$shipName" exact="if $ship.knownname? then $ship.knownname else 'Unknown Ship'"/>
        <set_value name="$shipID" exact="if $ship.idcode? then $ship.idcode else 'NONE'"/>
        <set_value name="$rescueLogbookMessage" exact="'\033#text_positive#' + {77000,3230}.[player.name, $pilotName, $shipName, $shipID] + '\033X'"/>
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="$rescueLogbookMessage"/>
          <param name="Category" value="'news'"/>
          <param name="Title" value="'\033#text_positive#' + {77000,3229} + '\033X'"/>
          <param name="Object" value="$ship"/>
          <param name="Interaction" value="'showonmap'"/>
          <param name="CheckGlobalSettings" value="false"/>
        </run_actions>
        <do_if value="$regKey and global.$GT_Pilots? and global.$GT_Pilots.{$regKey}?">
          <set_value name="global.$GT_Pilots.{$regKey}.$RescueLogbookWritten" exact="true"/>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] TryWriteTestPilotRescueLogbook: pilot=' + (if $pilot and $pilot.name? then $pilot.name else 'NONE') + ', ship=' + (if $ship and $ship.idcode? then $ship.idcode else 'NONE')" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>

    <!-- Resolve GT registry pilot for a destroyed player ship/spacesuit. -->
    <library name="ResolveGTPilotForDestroyedShip" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="destroyedShipID" default="''"/>
      </params>
      <actions>
        <set_value name="$pilot" exact="null"/>
        <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
          <set_value name="$pilot" exact="$ship.pilot"/>
        </do_if>
        <do_if value="not $pilot and global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$Pilot? and global.$GT_Pilots? and global.$GT_Pilots.{global.$GT_Ships.{$ship}.$Pilot}?">
          <set_value name="$pilot" exact="global.$GT_Ships.{$ship}.$Pilot"/>
        </do_if>
        <do_if value="not $pilot and $destroyedShipID != '' and global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <do_all exact="global.$GT_Ships.keys.count" counter="$gsi">
            <set_value name="$regShip" exact="global.$GT_Ships.keys.{$gsi}"/>
            <do_if value="not $pilot and $regShip.idcode? and $regShip.idcode == $destroyedShipID and global.$GT_Ships.{$regShip}.$Pilot? and global.$GT_Pilots? and global.$GT_Pilots.{global.$GT_Ships.{$regShip}.$Pilot}?">
              <set_value name="$pilot" exact="global.$GT_Ships.{$regShip}.$Pilot"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $pilot and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$pi">
            <set_value name="$pKey" exact="global.$GT_Pilots.keys.{$pi}"/>
            <do_if value="not $pilot and global.$GT_Pilots.{$pKey}.$Ship? and global.$GT_Pilots.{$pKey}.$Ship == $ship">
              <set_value name="$pilot" exact="$pKey"/>
            </do_if>
            <do_elseif value="not $pilot and global.$GT_Pilots.{$pKey}.$AssociatedShip? and global.$GT_Pilots.{$pKey}.$AssociatedShip == $ship">
              <set_value name="$pilot" exact="$pKey"/>
            </do_elseif>
            <do_elseif value="not $pilot and $destroyedShipID != '' and global.$GT_Pilots.{$pKey}.$ShipID? and global.$GT_Pilots.{$pKey}.$ShipID == $destroyedShipID">
              <set_value name="$pilot" exact="$pKey"/>
            </do_elseif>
          </do_all>
        </do_if>
        <return value="$pilot"/>
      </actions>
    </library>

    <!-- Ship hull destroyed (or spacesuit-only first event): mark ejected, start retag burst. -->
    <library name="ProcessGTPilotEjectOnDestroy" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="destroyedObject"/>
      </params>
      <actions>
        <do_if value="not $pilot or not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}?">
          <return value="false"/>
        </do_if>
        <do_if value="global.$GT_Pilots.{$pilot}.$Status? and global.$GT_Pilots.{$pilot}.$Status == 'ejected'">
          <return value="false"/>
        </do_if>

        <set_value name="$ejectSector" exact="null"/>
        <do_if value="$destroyedObject? and $destroyedObject.sector?">
          <set_value name="$ejectSector" exact="$destroyedObject.sector"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots.{$pilot}.$Ship? and global.$GT_Pilots.{$pilot}.$Ship.sector?">
          <set_value name="$ejectSector" exact="global.$GT_Pilots.{$pilot}.$Ship.sector"/>
        </do_elseif>

        <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'ejected'"/>
        <remove_value name="global.$GT_Pilots.{$pilot}.$RescueLogbookWritten"/>
        <do_if value="$ejectSector?">
          <set_value name="global.$GT_Pilots.{$pilot}.$EjectedSector" exact="$ejectSector"/>
        </do_if>
        <set_value name="global.$GT_Pilots.{$pilot}.$LastKnownPilotRef" exact="$pilot"/>
        <remove_value name="global.$GT_Pilots.{$pilot}.$Ship"/>
        <remove_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip"/>
        <remove_value name="global.$GT_Pilots.{$pilot}.$ShipID"/>

        <run_actions ref="md.GT_Ship_Management.Ensure_Pilot_Fields">
          <param name="pilot" value="$pilot"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$stableKey">
          <param name="pilot" value="$pilot"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Management.Sync_Stable_Identity_Index">
          <param name="pilot" value="$pilot"/>
        </run_actions>

        <run_actions ref="md.GT_CoreSystem.QueueBoundedPilotTagRefresh">
          <param name="pilot" value="$pilot"/>
          <param name="stableKey" value="$stableKey"/>
          <param name="sector" value="$ejectSector"/>
          <param name="source" value="'ship_destroy_eject'"/>
          <param name="ejectMode" value="true"/>
        </run_actions>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] ProcessGTPilotEjectOnDestroy: pilot=' + (if $pilot.name? then $pilot.name else 'NONE') + ', sector=' + (if $ejectSector? then $ejectSector.knownname else 'unknown') + ', stable=' + $stableKey" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>

    <library name="QueueDelayedSpacesuitDestroyRescue" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="registryPilotHint"/>
        <param name="sector"/>
        <param name="source" default="'spacesuit_destroyed_gt_handler'"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.DelayedSpacesuitDestroyRescue" param="table[
          $Spacesuit = $spacesuit,
          $RegistryPilotHint = $registryPilotHint,
          $Sector = $sector,
          $source = $source
        ]"/>
      </actions>
    </library>

    <!-- Scan a player ship for one ejected pilot (strict stable-identity match). -->
    <library name="TryRescueSpecificEjectedPilotOnShip" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="registryPilotHint"/>
        <param name="source" default="'specific_ejected_rescue'"/>
      </params>
      <actions>
        <set_value name="$rescued" exact="false"/>
        <do_if value="not $ship or not $ship.exists">
          <return value="false"/>
        </do_if>
        <run_actions ref="md.GT_CoreSystem.GT_ShipIsPlayerFleet" result="$isPlayerFleet">
          <param name="ship" value="$ship"/>
        </run_actions>
        <do_if value="not $isPlayerFleet">
          <return value="false"/>
        </do_if>
        <do_if value="not $registryPilotHint or not global.$GT_Pilots? or not global.$GT_Pilots.{$registryPilotHint}? or not global.$GT_Pilots.{$registryPilotHint}.$Status? or global.$GT_Pilots.{$registryPilotHint}.$Status != 'ejected'">
          <return value="false"/>
        </do_if>

        <run_actions ref="md.GT_CoreSystem.DeterminePilotAssignmentHasGTOrder" result="$hasGTOrder">
          <param name="ship" value="$ship"/>
        </run_actions>

        <set_value name="$regKey" exact="$registryPilotHint"/>
        <set_value name="$stableKey" exact="if global.$GT_Pilots.{$regKey}.$StableIdentity? then global.$GT_Pilots.{$regKey}.$StableIdentity else ''"/>
        <set_value name="$lastKnown" exact="if global.$GT_Pilots.{$regKey}.$LastKnownPilotRef? then global.$GT_Pilots.{$regKey}.$LastKnownPilotRef else null"/>
        <set_value name="$originalName" exact="''"/>
        <do_if value="global.$GT_Pilots.{$regKey}.$OriginalPilotName? and global.$GT_Pilots.{$regKey}.$OriginalPilotName != ''">
          <set_value name="$originalName" exact="global.$GT_Pilots.{$regKey}.$OriginalPilotName"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots.{$regKey}.$PilotName? and global.$GT_Pilots.{$regKey}.$PilotName != ''">
          <set_value name="$originalName" exact="global.$GT_Pilots.{$regKey}.$PilotName"/>
        </do_elseif>
        <set_value name="$taggedPilotName" exact="''"/>
        <do_if value="global.$GT_Pilots.{$regKey}.$PilotName? and global.$GT_Pilots.{$regKey}.$PilotName != ''">
          <set_value name="$taggedPilotName" exact="global.$GT_Pilots.{$regKey}.$PilotName"/>
        </do_if>
        <do_elseif value="$regKey and $regKey.exists? and $regKey.exists and $regKey.name? and $regKey.name != ''">
          <set_value name="$taggedPilotName" exact="$regKey.name"/>
        </do_elseif>
        <set_value name="$pilotLevel" exact="null"/>
        <do_if value="global.$GT_Pilots.{$regKey}.$Level? and global.$GT_Pilots.{$regKey}.$Level != null">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$regKey}.$Level"/>
        </do_if>
        <set_value name="$ejectSector" exact="if global.$GT_Pilots.{$regKey}.$EjectedSector? then global.$GT_Pilots.{$regKey}.$EjectedSector else null"/>
        <set_value name="$livePilot" exact="null"/>
        <run_actions ref="md.GT_Ship_Management.Resolve_Live_Pilot_Tiered" result="$tierRes">
          <param name="livePilotHint" value="$lastKnown"/>
          <param name="stableKey" value="$stableKey"/>
          <param name="sector" value="$ejectSector"/>
          <param name="ship" value="$ship"/>
          <param name="originalName" value="$originalName"/>
          <param name="taggedPilotName" value="$taggedPilotName"/>
          <param name="pilotLevel" value="$pilotLevel"/>
        </run_actions>
        <do_if value="$tierRes.$Pilot? and $tierRes.$Pilot.exists and $tierRes.$MatchCount? and $tierRes.$MatchCount == 1">
          <set_value name="$livePilot" exact="$tierRes.$Pilot"/>
        </do_if>
        <do_if value="$livePilot and $livePilot.exists">
          <run_actions ref="md.GT_CoreSystem.TryWriteTestPilotRescueLogbook">
            <param name="pilot" value="$livePilot"/>
            <param name="ship" value="$ship"/>
            <param name="registryPilotHint" value="$regKey"/>
          </run_actions>
          <run_actions ref="md.GT_CoreSystem.HandleRescueRebindForEjectedPilot" result="$rescued">
            <param name="livePilot" value="$livePilot"/>
            <param name="ship" value="$ship"/>
            <param name="hasGTOrder" value="$hasGTOrder"/>
            <param name="registryPilotHint" value="$regKey"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <return value="$rescued"/>
      </actions>
    </library>

    <!-- Scan a player ship for ejected GT pilots via registry stable identity + tiered crew resolve. -->
    <library name="ScanPlayerShipForEjectedPilotRescue" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'crew_rescue_scan'"/>
        <param name="registryPilotHint" default="null"/>
      </params>
      <actions>
        <set_value name="$anyRescued" exact="false"/>
        <run_actions ref="md.GT_CoreSystem.GT_ShipIsPlayerFleet" result="$isPlayerFleet">
          <param name="ship" value="$ship"/>
        </run_actions>
        <do_if value="not $isPlayerFleet">
          <return value="false"/>
        </do_if>

        <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}? and global.$GT_Pilots.{$registryPilotHint}.$Status? and global.$GT_Pilots.{$registryPilotHint}.$Status == 'ejected'">
          <run_actions ref="md.GT_CoreSystem.TryRescueSpecificEjectedPilotOnShip" result="$anyRescued">
            <param name="ship" value="$ship"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="source" value="$source"/>
          </run_actions>
          <return value="$anyRescued"/>
        </do_if>

        <set_value name="$hasEjected" exact="false"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$ej">
            <set_value name="$eKey" exact="global.$GT_Pilots.keys.{$ej}"/>
            <do_if value="global.$GT_Pilots.{$eKey}.$Status? and global.$GT_Pilots.{$eKey}.$Status == 'ejected'">
              <set_value name="$hasEjected" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $hasEjected">
          <return value="false"/>
        </do_if>

        <run_actions ref="md.GT_CoreSystem.DeterminePilotAssignmentHasGTOrder" result="$hasGTOrder">
          <param name="ship" value="$ship"/>
        </run_actions>

        <do_all exact="global.$GT_Pilots.keys.count" counter="$ri">
          <set_value name="$regKey" exact="global.$GT_Pilots.keys.{$ri}"/>
          <do_if value="global.$GT_Pilots.{$regKey}.$Status? and global.$GT_Pilots.{$regKey}.$Status == 'ejected'">
            <set_value name="$stableKey" exact="if global.$GT_Pilots.{$regKey}.$StableIdentity? then global.$GT_Pilots.{$regKey}.$StableIdentity else ''"/>
            <set_value name="$lastKnown" exact="if global.$GT_Pilots.{$regKey}.$LastKnownPilotRef? then global.$GT_Pilots.{$regKey}.$LastKnownPilotRef else null"/>
            <set_value name="$originalName" exact="''"/>
            <do_if value="global.$GT_Pilots.{$regKey}.$OriginalPilotName? and global.$GT_Pilots.{$regKey}.$OriginalPilotName != ''">
              <set_value name="$originalName" exact="global.$GT_Pilots.{$regKey}.$OriginalPilotName"/>
            </do_if>
            <do_elseif value="global.$GT_Pilots.{$regKey}.$PilotName? and global.$GT_Pilots.{$regKey}.$PilotName != ''">
              <set_value name="$originalName" exact="global.$GT_Pilots.{$regKey}.$PilotName"/>
            </do_elseif>
            <set_value name="$taggedPilotName" exact="''"/>
            <do_if value="global.$GT_Pilots.{$regKey}.$PilotName? and global.$GT_Pilots.{$regKey}.$PilotName != ''">
              <set_value name="$taggedPilotName" exact="global.$GT_Pilots.{$regKey}.$PilotName"/>
            </do_if>
            <do_elseif value="$regKey and $regKey.exists? and $regKey.exists and $regKey.name? and $regKey.name != ''">
              <set_value name="$taggedPilotName" exact="$regKey.name"/>
            </do_elseif>
            <set_value name="$pilotLevel" exact="null"/>
            <do_if value="global.$GT_Pilots.{$regKey}.$Level? and global.$GT_Pilots.{$regKey}.$Level != null">
              <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$regKey}.$Level"/>
            </do_if>
            <set_value name="$ejectSector" exact="if global.$GT_Pilots.{$regKey}.$EjectedSector? then global.$GT_Pilots.{$regKey}.$EjectedSector else null"/>
            <set_value name="$livePilot" exact="null"/>
            <run_actions ref="md.GT_Ship_Management.Resolve_Live_Pilot_Tiered" result="$tierRes">
              <param name="livePilotHint" value="$lastKnown"/>
              <param name="stableKey" value="$stableKey"/>
              <param name="sector" value="$ejectSector"/>
              <param name="ship" value="$ship"/>
              <param name="originalName" value="$originalName"/>
              <param name="taggedPilotName" value="$taggedPilotName"/>
              <param name="pilotLevel" value="$pilotLevel"/>
            </run_actions>
            <do_if value="$tierRes.$Pilot? and $tierRes.$Pilot.exists and $tierRes.$MatchCount? and $tierRes.$MatchCount == 1">
              <set_value name="$livePilot" exact="$tierRes.$Pilot"/>
            </do_if>
            <do_if value="$livePilot and $livePilot.exists">
              <run_actions ref="md.GT_CoreSystem.TryWriteTestPilotRescueLogbook">
                <param name="pilot" value="$livePilot"/>
                <param name="ship" value="$ship"/>
                <param name="registryPilotHint" value="$regKey"/>
              </run_actions>
              <run_actions ref="md.GT_CoreSystem.HandleRescueRebindForEjectedPilot" result="$rescued">
                <param name="livePilot" value="$livePilot"/>
                <param name="ship" value="$ship"/>
                <param name="hasGTOrder" value="$hasGTOrder"/>
                <param name="registryPilotHint" value="$regKey"/>
                <param name="source" value="$source"/>
              </run_actions>
              <do_if value="$rescued">
                <set_value name="$anyRescued" exact="true"/>
                <break/>
              </do_if>
            </do_if>
          </do_if>
        </do_all>

        <do_if value="$anyRescued and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] ScanPlayerShipForEjectedPilotRescue: rescued ejected pilot on ship=' + $ship.idcode + ', source=' + $source" chance="100"/>
        </do_if>
        <do_elseif value="not $anyRescued and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] ScanPlayerShipForEjectedPilotRescue: no ejected pilot resolved on ship=' + $ship.idcode + ', source=' + $source" chance="100"/>
        </do_elseif>
        <return value="$anyRescued"/>
      </actions>
    </library>

    <!-- Rescue candidates: active RescueShip order, else ships nearest the destroyed spacesuit (vanilla HACK path). -->
    <library name="FindRescueCandidateShipsNearSpacesuit" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="sector"/>
        <param name="maxCandidates" default="3"/>
        <param name="maxDistance" default="15km"/>
      </params>
      <actions>
        <set_value name="$candidates" exact="[]"/>
        <set_value name="$searchSpace" exact="if $sector? and $sector.exists then $sector else player.sector"/>
        <find_ship_by_true_owner name="$ships" space="$searchSpace" faction="faction.player" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="true"/>
        <do_all exact="$ships.count" counter="$ri">
          <set_value name="$candidate" exact="$ships.{$ri}"/>
          <do_if value="$candidate? and $candidate.exists and @$candidate.order.id == 'RescueShip' and $candidate.order.$target? and $candidate.order.$target == $spacesuit">
            <append_to_list name="$candidates" exact="$candidate"/>
          </do_if>
        </do_all>
        <do_if value="$candidates.count == 0">
          <set_value name="$sectorRescueCount" exact="0"/>
          <set_value name="$soleRescueShip" exact="null"/>
          <do_all exact="$ships.count" counter="$ri2">
            <set_value name="$candidate" exact="$ships.{$ri2}"/>
            <do_if value="$candidate? and $candidate.exists and @$candidate.order.id == 'RescueShip'">
              <set_value name="$soleRescueShip" exact="$candidate"/>
              <set_value name="$sectorRescueCount" exact="$sectorRescueCount + 1"/>
            </do_if>
          </do_all>
          <do_if value="$sectorRescueCount == 1 and $soleRescueShip? and $soleRescueShip.exists">
            <append_to_list name="$candidates" exact="$soleRescueShip"/>
          </do_if>
        </do_if>
        <do_if value="$candidates.count == 0 and $spacesuit? and $spacesuit.exists">
          <find_ship_by_true_owner name="$nearbyShips" space="$searchSpace" faction="faction.player" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="true" sortbydistanceto="$spacesuit" sortdescending="false" sortlimit="$maxCandidates"/>
          <do_all exact="$nearbyShips.count" counter="$ni">
            <set_value name="$nearShip" exact="$nearbyShips.{$ni}"/>
            <do_if value="$nearShip? and $nearShip.exists and not $nearShip.isclass.spacesuit and $nearShip.bboxdistanceto.{$spacesuit} le $maxDistance">
              <append_to_list name="$candidates" exact="$nearShip"/>
            </do_if>
          </do_all>
        </do_if>
        <do_elseif value="$candidates.count == 0">
          <find_ship_by_true_owner name="$sectorShips" space="$searchSpace" faction="faction.player" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="true"/>
          <set_value name="$sectorScanLimit" exact="if $sectorShips.count lt $maxCandidates then $sectorShips.count else $maxCandidates"/>
          <do_all exact="$sectorScanLimit" counter="$si">
            <append_to_list name="$candidates" exact="$sectorShips.{$si}"/>
          </do_all>
        </do_elseif>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$candidateIds" exact="''"/>
          <do_all exact="$candidates.count" counter="$ci">
            <set_value name="$candidateIds" exact="$candidateIds + (if $ci gt 1 then ', ' else '') + $candidates.{$ci}.idcode"/>
          </do_all>
          <debug_text text="'[GT-Core] FindRescueCandidateShipsNearSpacesuit: count=' + $candidates.count + ', ids=' + (if $candidateIds != '' then $candidateIds else 'NONE') + ', sector=' + (if $searchSpace? then $searchSpace.knownname else 'NONE')" chance="100"/>
        </do_if>
        <return value="$candidates"/>
      </actions>
    </library>

    <!-- Backward-compatible wrapper: first rescue candidate ship, or null. -->
    <library name="FindRescueShipForDestroyedSpacesuit" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="sector"/>
      </params>
      <actions>
        <set_value name="$rescueShip" exact="null"/>
        <run_actions ref="md.GT_CoreSystem.FindRescueCandidateShipsNearSpacesuit" result="$candidates">
          <param name="spacesuit" value="$spacesuit"/>
          <param name="sector" value="$sector"/>
        </run_actions>
        <do_if value="$candidates.count gt 0">
          <set_value name="$rescueShip" exact="$candidates.{1}"/>
        </do_if>
        <return value="$rescueShip"/>
      </actions>
    </library>

    <library name="TryRescueOnCandidateShips" purpose="run_actions">
      <params>
        <param name="candidateShips"/>
        <param name="registryPilotHint"/>
        <param name="source" default="'rescue_candidate_ships'"/>
      </params>
      <actions>
        <set_value name="$rescued" exact="false"/>
        <do_if value="not $registryPilotHint or not global.$GT_Pilots? or not global.$GT_Pilots.{$registryPilotHint}? or not global.$GT_Pilots.{$registryPilotHint}.$Status? or global.$GT_Pilots.{$registryPilotHint}.$Status != 'ejected'">
          <return value="false"/>
        </do_if>
        <do_if value="$candidateShips? and $candidateShips.count gt 0">
          <do_all exact="$candidateShips.count" counter="$ci">
            <set_value name="$scanShip" exact="$candidateShips.{$ci}"/>
            <do_if value="not $rescued and $scanShip and $scanShip.exists and not $scanShip.isclass.spacesuit">
              <run_actions ref="md.GT_CoreSystem.TryRescueSpecificEjectedPilotOnShip" result="$rescued">
                <param name="ship" value="$scanShip"/>
                <param name="registryPilotHint" value="$registryPilotHint"/>
                <param name="source" value="$source"/>
              </run_actions>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] TryRescueOnCandidateShips: rescued=' + $rescued + ', candidates=' + (if $candidateShips? then $candidateShips.count else 0) + ', pilotHint=' + (if global.$GT_Pilots.{$registryPilotHint}.$PilotName? then global.$GT_Pilots.{$registryPilotHint}.$PilotName else 'NONE') + ', source=' + $source" chance="100"/>
        </do_if>
        <return value="$rescued"/>
      </actions>
    </library>

    <!-- Immediate rescue rebind on the RescueShip that just force-transferred the ejected pilot. -->
    <library name="TryImmediateSpacesuitDestroyRescue" purpose="run_actions">
      <params>
        <param name="spacesuit"/>
        <param name="registryPilotHint"/>
        <param name="sector"/>
        <param name="source" default="'spacesuit_destroyed_rescue'"/>
      </params>
      <actions>
        <set_value name="$rescued" exact="false"/>
        <run_actions ref="md.GT_CoreSystem.ResolveRescueShipFromSpacesuitContext" result="$rescueShip">
          <param name="spacesuit" value="$spacesuit"/>
          <param name="sector" value="$sector"/>
        </run_actions>
        <set_value name="$livePilot" exact="if $registryPilotHint and $registryPilotHint.exists then $registryPilotHint else null"/>
        <do_if value="$spacesuit? and $spacesuit.pilot? and $spacesuit.pilot.exists">
          <set_value name="$livePilot" exact="$spacesuit.pilot"/>
        </do_if>
        <do_if value="$rescueShip? and $rescueShip.exists and $registryPilotHint?">
          <run_actions ref="md.GT_CoreSystem.TryRescueEjectedPilotAtPickup" result="$rescued">
            <param name="livePilot" value="$livePilot"/>
            <param name="rescueShip" value="$rescueShip"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="spacesuit" value="$spacesuit"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <do_if value="not $rescued">
          <run_actions ref="md.GT_CoreSystem.FindRescueCandidateShipsNearSpacesuit" result="$candidates">
            <param name="spacesuit" value="$spacesuit"/>
            <param name="sector" value="$sector"/>
          </run_actions>
          <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}? and $candidates.count gt 0">
            <set_value name="global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips" exact="$candidates"/>
          </do_if>
          <run_actions ref="md.GT_CoreSystem.TryRescueOnCandidateShips" result="$rescued">
            <param name="candidateShips" value="$candidates"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <do_if value="not $rescued and $registryPilotHint?">
          <run_actions ref="md.GT_CoreSystem.ScanPlayerFleetInSectorForEjectedPilot" result="$rescued">
            <param name="sector" value="$sector"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="source" value="$source"/>
          </run_actions>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] TryImmediateSpacesuitDestroyRescue: rescued=' + $rescued + ', candidates=' + $candidates.count + ', pilotHint=' + (if $registryPilotHint.name? then $registryPilotHint.name else 'NONE')" chance="100"/>
        </do_if>
        <return value="$rescued"/>
      </actions>
    </library>

    <library name="QueueDelayedEjectedPilotNearbyRescan" purpose="run_actions">
      <params>
        <param name="registryPilotHint"/>
        <param name="source" default="'spacesuit_destroyed_nearby_rescan'"/>
        <param name="attempt" default="1"/>
      </params>
      <actions>
        <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}? and global.$GT_Pilots.{$registryPilotHint}.$Status? and global.$GT_Pilots.{$registryPilotHint}.$Status == 'ejected'">
          <signal_cue_instantly cue="md.GT_CoreSystem.DelayedEjectedPilotNearbyRescan" param="table[
            $RegistryPilotHint = $registryPilotHint,
            $source = $source,
            $attempt = $attempt
          ]"/>
        </do_if>
      </actions>
    </library>

    <library name="MaybeRetryScanPlayerShipForEjectedPilotRescue" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'crew_rescue_scan'"/>
        <param name="attempt" default="1"/>
        <param name="maxAttempts" default="10"/>
      </params>
      <actions>
        <do_if value="$attempt lt $maxAttempts">
          <signal_cue_instantly cue="md.GT_CoreSystem.DelayedScanPlayerShipForEjectedPilotRescue" param="table[
            $Ship = $ship,
            $source = $source,
            $attempt = $attempt + 1
          ]"/>
        </do_if>
      </actions>
    </library>

    <library name="QueueScanPlayerShipForEjectedPilotRescue" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="source" default="'crew_rescue_scan'"/>
        <param name="registryPilotHint" default="null"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.DelayedScanPlayerShipForEjectedPilotRescue" param="table[
          $Ship = $ship,
          $source = $source,
          $attempt = 1,
          $RegistryPilotHint = $registryPilotHint
        ]"/>
      </actions>
    </library>

    <!-- Shared scheduler for stable-key identity resolution cues. -->
    <library name="QueueResolvePilotIdentityByStable" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="stable" default="''"/>
        <param name="template" default="null"/>
        <param name="source" default="'unknown'"/>
        <param name="attempt" default="1"/>
      </params>
      <actions>
        <signal_cue_instantly cue="ResolvePilotIdentityByStable" param="table[
          $Ship = $ship,
          $stable = $stable,
          $template = $template,
          $source = $source,
          $attempt = $attempt
        ]"/>
      </actions>
    </library>

    <!-- Shared scheduler for demoted-pilot identity resolution cues. -->
    <library name="QueueResolveDemotedPilotIdentity" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="oldPilot" default="null"/>
        <param name="baseName" default="''"/>
        <param name="oldStable" default="''"/>
        <param name="oldTemplate" default="null"/>
        <param name="attempt" default="1"/>
      </params>
      <actions>
        <signal_cue_instantly cue="md.GT_CoreSystem.ResolveDemotedPilotIdentity" param="table[
          $Ship = $ship,
          $oldPilot = $oldPilot,
          $baseName = $baseName,
          $oldStable = $oldStable,
          $oldTemplate = $oldTemplate,
          $attempt = $attempt
        ]"/>
      </actions>
    </library>

    <!-- Shared bounded retry helper for ResolveDemotedPilotIdentity. -->
    <library name="MaybeRetryResolveDemotedPilotIdentity" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="oldPilot" default="null"/>
        <param name="baseName" default="''"/>
        <param name="oldStable" default="''"/>
        <param name="oldTemplate" default="null"/>
        <param name="attempt" default="1"/>
        <param name="maxAttempts" default="31"/>
      </params>
      <actions>
        <do_if value="$attempt lt $maxAttempts">
          <run_actions ref="md.GT_CoreSystem.QueueResolveDemotedPilotIdentity">
            <param name="ship" value="$ship"/>
            <param name="oldPilot" value="$oldPilot"/>
            <param name="baseName" value="$baseName"/>
            <param name="oldStable" value="$oldStable"/>
            <param name="oldTemplate" value="$oldTemplate"/>
            <param name="attempt" value="$attempt + 1"/>
          </run_actions>
        </do_if>
      </actions>
    </library>

    <!-- Shared bounded retry helper for ResolvePilotIdentityByStable. -->
    <library name="MaybeRetryResolvePilotIdentityByStable" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="stable" default="''"/>
        <param name="template" default="null"/>
        <param name="source" default="'unknown'"/>
        <param name="attempt" default="1"/>
        <param name="maxAttempts" default="31"/>
      </params>
      <actions>
        <do_if value="$attempt lt $maxAttempts">
          <run_actions ref="md.GT_CoreSystem.QueueResolvePilotIdentityByStable">
            <param name="ship" value="$ship"/>
            <param name="stable" value="$stable"/>
            <param name="template" value="$template"/>
            <param name="source" value="$source"/>
            <param name="attempt" value="$attempt + 1"/>
          </run_actions>
        </do_if>
      </actions>
    </library>
    
    <!-- Global vanilla crew assignment hook.
         Tracks pilot swaps even when no GT order is currently running. -->
    <cue name="HandleVanillaPilotAssignment" instantiate="true">
      <conditions>
        <event_player_assigned_hired_actor/>
      </conditions>
      <actions>
        <set_value name="$newPilotRaw" exact="event.param"/>
        <set_value name="$ship" exact="event.param2"/>
        <set_value name="$assignment" exact="event.param3"/>
        
        <!-- Only process pilot post reassignments on player fleet ships (includes Assist subs). -->
        <run_actions ref="md.GT_CoreSystem.GT_ShipIsPlayerFleet" result="$isPlayerFleet">
          <param name="ship" value="$ship"/>
        </run_actions>
        <do_if value="$assignment == controlpost.aipilot and $ship and $ship.exists and $isPlayerFleet">
          <!-- event.param may be an actor object OR a payload table depending on vanilla path. -->
          <set_value name="$newPilot" exact="null"/>
          <set_value name="$newPilotTemplate" exact="null"/>
          <do_if value="$newPilotRaw and $newPilotRaw.exists? and $newPilotRaw.exists">
            <set_value name="$newPilot" exact="$newPilotRaw"/>
          </do_if>
          <do_elseif value="$newPilotRaw and $newPilotRaw.$actor? and $newPilotRaw.$actor.exists? and $newPilotRaw.$actor.exists">
            <set_value name="$newPilot" exact="$newPilotRaw.$actor"/>
          </do_elseif>
          <do_elseif value="$newPilotRaw and $newPilotRaw.$entity? and $newPilotRaw.$entity.exists? and $newPilotRaw.$entity.exists">
            <set_value name="$newPilot" exact="$newPilotRaw.$entity"/>
          </do_elseif>
          <!-- genericactor can be [context, template] per XSD -->
          <do_elseif value="$newPilotRaw and $newPilotRaw.count? and $newPilotRaw.count ge 2 and $newPilotRaw.{2}?">
            <set_value name="$newPilotTemplate" exact="$newPilotRaw.{2}"/>
            <do_if value="$ship.roleentity? and $ship.roleentity.{$newPilotTemplate}? and $ship.roleentity.{$newPilotTemplate}.exists">
              <set_value name="$newPilot" exact="$ship.roleentity.{$newPilotTemplate}"/>
            </do_if>
          </do_elseif>
          
          <set_value name="$oldPilot" exact="if $ship.pilot? then $ship.pilot else null"/>
          <set_value name="$oldPilotTemplate" exact="if $oldPilot and $oldPilot.npctemplate? then $oldPilot.npctemplate else null"/>
          <set_value name="$oldPilotName" exact="'NONE'"/>
          <do_if value="$oldPilot and $oldPilot.name?">
            <set_value name="$oldPilotName" exact="$oldPilot.name"/>
          </do_if>
          <set_value name="$newPilotName" exact="'NONE'"/>
          <do_if value="$newPilot and $newPilot.name?">
            <set_value name="$newPilotName" exact="$newPilot.name"/>
          </do_if>
          <do_elseif value="$newPilotRaw and $newPilotRaw.name?">
            <set_value name="$newPilotName" exact="$newPilotRaw.name"/>
          </do_elseif>
          
          <run_actions ref="md.GT_CoreSystem.DeterminePilotAssignmentHasGTOrder" result="$hasGTOrder">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] Vanilla pilot assignment detected: ship=' + $ship.idcode + ', old=' + $oldPilotName + (if $oldPilot and $oldPilot.idcode? then ' [' + $oldPilot.idcode + ']' else '') + ', oldTpl=' + (if $oldPilotTemplate? then $oldPilotTemplate else 'NONE') + ', new=' + $newPilotName + (if $newPilot and $newPilot.idcode? then ' [' + $newPilot.idcode + ']' else '') + ', newTpl=' + (if $newPilotTemplate? then $newPilotTemplate else 'NONE') + ', hasGTOrder=' + $hasGTOrder" chance="100"/>
          </do_if>
          
          <!-- Re-check after vanilla settles to reliably capture final promoted pilot entity.
               Run regardless of current GT order so delayed vanilla pilot binding is still reconciled
               before the player assigns a fresh GT order to the ship. -->
          <run_actions ref="md.GT_CoreSystem.QueueFinalizeVanillaPilotAssignment">
            <param name="ship" value="$ship"/>
            <param name="source" value="'vanilla_assignment_event'"/>
            <param name="newPilot" value="$newPilot"/>
            <param name="newPilotTemplate" value="$newPilotTemplate"/>
            <param name="attempt" value="1"/>
          </run_actions>
          
          <!-- Preserve outgoing GT pilot progression even without active GT order. -->
          <do_if value="$oldPilot and $oldPilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$oldPilot}? and $oldPilot != $newPilot">
            <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
              <param name="pilot" value="$oldPilot"/>
              <param name="ship" value="$ship"/>
              <param name="hasGTOrder" value="false"/>
              <param name="clearPausedFields" value="false"/>
            </run_actions>
            <set_value name="global.$GT_Pilots.{$oldPilot}.$PausedTime" exact="player.age"/>
            <set_value name="global.$GT_Pilots.{$oldPilot}.$PausedReason" exact="'Vanilla pilot reassignment - preserving GT XP data'"/>
            <!-- Ensure outgoing GT pilot keeps the (T:xx) prefix after being moved to crew. -->
            <run_actions ref="md.GT_CoreSystem.QueueDeferredPilotTagRefresh">
              <param name="pilot" value="$oldPilot"/>
              <param name="source" value="'vanilla_reassignment_oldpilot'"/>
            </run_actions>
            <!-- Vanilla may rebind demoted pilot to a new crew actor id.
                 Resolve identity to the service-crew actor so UI and GT data stay aligned. -->
            <set_value name="$oldPilotBaseName" exact="if global.$GT_Pilots.{$oldPilot}.$OriginalPilotName? then global.$GT_Pilots.{$oldPilot}.$OriginalPilotName else $oldPilotName"/>
            <set_value name="$oldPilotStable" exact="if global.$GT_Pilots.{$oldPilot}.$StableIdentity? then global.$GT_Pilots.{$oldPilot}.$StableIdentity else ''"/>
            <run_actions ref="md.GT_CoreSystem.QueueResolveDemotedPilotIdentity">
              <param name="ship" value="$ship"/>
              <param name="oldPilot" value="$oldPilot"/>
              <param name="baseName" value="$oldPilotBaseName"/>
              <param name="oldStable" value="$oldPilotStable"/>
              <param name="oldTemplate" value="$oldPilotTemplate"/>
              <param name="attempt" value="1"/>
            </run_actions>
            <do_if value="$oldPilotStable != ''">
              <run_actions ref="md.GT_CoreSystem.QueueResolvePilotIdentityByStable">
                <param name="ship" value="$ship"/>
                <param name="stable" value="$oldPilotStable"/>
                <param name="template" value="$oldPilotTemplate"/>
                <param name="source" value="'vanilla_reassignment_oldpilot_stable'"/>
              </run_actions>
            </do_if>
          </do_if>
          <!-- Fallback: some vanilla sequences report oldPilot as NONE while still exposing a
               replacement template. Rebind paused GT records by stable identity early so tag loss
               windows are minimized. -->
          <do_if value="$hasGTOrder and $newPilotTemplate? and $newPilotTemplate != null">
            <run_actions ref="md.GT_CoreSystem.QueueResolvePilotIdentityByStable">
              <param name="ship" value="$ship"/>
              <param name="stable" value="'s:' + $newPilotTemplate"/>
              <param name="template" value="$newPilotTemplate"/>
              <param name="source" value="'vanilla_assignment_template_only'"/>
            </run_actions>
          </do_if>
          
          <!-- Handle incoming pilot identity:
               - If already registered, keep their GT record linked to this ship.
               - If unregistered (e.g. object id changed), recover from paused/ejected record. -->
          <do_if value="$newPilot and $newPilot.exists? and $newPilot.exists">
            <run_actions ref="md.GT_CoreSystem.HandleRescueRebindForEjectedPilot" result="$rescuedEjected">
              <param name="livePilot" value="$newPilot"/>
              <param name="ship" value="$ship"/>
              <param name="hasGTOrder" value="$hasGTOrder"/>
              <param name="source" value="'vanilla_assignment_rescue'"/>
            </run_actions>
            <do_if value="not $rescuedEjected">
            <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$newPilot}?">
              <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
                <param name="pilot" value="$newPilot"/>
                <param name="ship" value="$ship"/>
                <param name="hasGTOrder" value="$hasGTOrder"/>
                <param name="clearPausedFields" value="false"/>
              </run_actions>
              <!-- Ensure pilot tag is refreshed when vanilla reassignment changes actor identity/state. -->
              <run_actions ref="md.GT_CoreSystem.TryUpdatePilotNameTag">
                <param name="pilot" value="$newPilot"/>
              </run_actions>
            </do_if>
            <do_elseif value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
              <set_value name="$incomingName" exact="$newPilotName"/>
              <set_value name="$incomingPilotID" exact="if $newPilot.idcode? then $newPilot.idcode else ''"/>
              <set_value name="$incomingStable" exact="''"/>
              <do_if value="md.GT_Ship_Management.Compute_Pilot_Stable_Key?">
                <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$incomingStable">
                  <param name="pilot" value="$newPilot"/>
                </run_actions>
              </do_if>
              <set_value name="$keys" exact="global.$GT_Pilots.keys.list"/>
              <set_value name="$bestCandidate" exact="null"/>
              <set_value name="$bestScore" exact="0"/>
              <set_value name="$bestScoreCount" exact="0"/>
              
              <do_all exact="$keys.count" counter="$i">
                <set_value name="$candidate" exact="$keys.{$i}"/>
                <do_if value="$candidate and $candidate != $newPilot and global.$GT_Pilots.{$candidate}? and global.$GT_Pilots.{$candidate}.$Status? and (global.$GT_Pilots.{$candidate}.$Status == 'paused' or global.$GT_Pilots.{$candidate}.$Status == 'ejected')">
                  <set_value name="$score" exact="0"/>
                  
                  <do_if value="$incomingStable != '' and global.$GT_Pilots.{$candidate}.$StableIdentity? and global.$GT_Pilots.{$candidate}.$StableIdentity == $incomingStable">
                    <set_value name="$score" exact="$score + 50"/>
                  </do_if>
                  
                  <do_if value="$incomingPilotID != '' and global.$GT_Pilots.{$candidate}.$PilotID? and global.$GT_Pilots.{$candidate}.$PilotID == $incomingPilotID">
                    <set_value name="$score" exact="$score + 20"/>
                  </do_if>
                  
                  <do_if value="global.$GT_Pilots.{$candidate}.$ShipID? and global.$GT_Pilots.{$candidate}.$ShipID == $ship.idcode">
                    <set_value name="$score" exact="$score + 4"/>
                  </do_if>
                  <do_if value="$incomingPilotID == '' or not global.$GT_Pilots.{$candidate}.$PilotID?">
                    <do_if value="global.$GT_Pilots.{$candidate}.$OriginalPilotName? and global.$GT_Pilots.{$candidate}.$OriginalPilotName == $incomingName">
                      <set_value name="$score" exact="$score + 5"/>
                    </do_if>
                    <do_elseif value="global.$GT_Pilots.{$candidate}.$PilotName? and global.$GT_Pilots.{$candidate}.$PilotName == $incomingName">
                      <set_value name="$score" exact="$score + 4"/>
                    </do_elseif>
                  </do_if>
                  
                  <do_if value="$score gt $bestScore">
                    <set_value name="$bestScore" exact="$score"/>
                    <set_value name="$bestCandidate" exact="$candidate"/>
                    <set_value name="$bestScoreCount" exact="1"/>
                  </do_if>
                  <do_elseif value="$score gt 0 and $score == $bestScore">
                    <set_value name="$bestScoreCount" exact="$bestScoreCount + 1"/>
                  </do_elseif>
                </do_if>
              </do_all>
              
              <do_if value="$bestCandidate and $bestScoreCount == 1 and $bestScore ge 8">
                <set_value name="global.$GT_Pilots.{$newPilot}" exact="global.$GT_Pilots.{$bestCandidate}"/>
                <remove_value name="global.$GT_Pilots.{$bestCandidate}"/>
                <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
                  <param name="pilot" value="$newPilot"/>
                  <param name="ship" value="$ship"/>
                  <param name="hasGTOrder" value="$hasGTOrder"/>
                  <param name="clearPausedFields" value="true"/>
                </run_actions>
                
                <!-- Keep vanilla skill aligned with recovered GT XP so stars are not lost. -->
                <set_value name="$xp" exact="if global.$GT_Pilots.{$newPilot}.$XP? then global.$GT_Pilots.{$newPilot}.$XP else 0"/>
                <set_value name="$level" exact="1"/>
                <do_if value="md.GT_Ship_Management.Calculate_Skill_Level_From_XP?">
                  <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level_From_XP" result="$level">
                    <param name="pilot" value="$newPilot"/>
                    <param name="xp" value="$xp"/>
                  </run_actions>
                </do_if>
                <set_value name="$vanillaMgmt" exact="if $newPilot.skill.management? then $newPilot.skill.management else 0"/>
                <do_if value="$level gt $vanillaMgmt">
                  <set_skill entity="$newPilot" type="skilltype.management" exact="$level"/>
                </do_if>
                <set_value name="global.$GT_Pilots.{$newPilot}.$Level" exact="$level"/>
                <run_actions ref="md.GT_CoreSystem.TryUpdatePilotNameTag">
                  <param name="pilot" value="$newPilot"/>
                  <param name="level" value="$level"/>
                </run_actions>
                <run_actions ref="md.GT_CoreSystem.QueueDeferredPilotTagRefresh">
                  <param name="pilot" value="$newPilot"/>
                  <param name="source" value="'vanilla_reassignment_recovered'"/>
                </run_actions>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Core] Reattached GT pilot after vanilla reassignment: new=' + $newPilot.name + (if $newPilot.idcode? then ' [' + $newPilot.idcode + ']' else '') + ', recoveredFrom=' + $bestCandidate.name + (if $bestCandidate.idcode? then ' [' + $bestCandidate.idcode + ']' else '') + ', XP=' + $xp + ', level=' + $level + ', hasGTOrder=' + $hasGTOrder" chance="100"/>
                </do_if>
              </do_if>
            </do_elseif>
            </do_if>
          </do_if>
        </do_if>

        <!-- Vanilla RescueShip boards ejected pilots as unassigned crew (entityrole), not ship pilot. -->
        <do_elseif value="$ship and $ship.exists and $isPlayerFleet and typeof $assignment == datatype.entityrole">
          <set_value name="$rescuedCrew" exact="false"/>
          <set_value name="$newCrew" exact="null"/>
          <set_value name="$newCrewTemplate" exact="null"/>
          <do_if value="$newPilotRaw and $newPilotRaw.exists? and $newPilotRaw.exists">
            <set_value name="$newCrew" exact="$newPilotRaw"/>
          </do_if>
          <do_elseif value="$newPilotRaw and $newPilotRaw.$actor? and $newPilotRaw.$actor.exists? and $newPilotRaw.$actor.exists">
            <set_value name="$newCrew" exact="$newPilotRaw.$actor"/>
          </do_elseif>
          <do_elseif value="$newPilotRaw and $newPilotRaw.$entity? and $newPilotRaw.$entity.exists? and $newPilotRaw.$entity.exists">
            <set_value name="$newCrew" exact="$newPilotRaw.$entity"/>
          </do_elseif>
          <do_elseif value="$newPilotRaw and $newPilotRaw.count? and $newPilotRaw.count ge 2 and $newPilotRaw.{2}?">
            <set_value name="$newCrewTemplate" exact="$newPilotRaw.{2}"/>
            <do_if value="$ship.roleentity? and $ship.roleentity.{$newCrewTemplate}? and $ship.roleentity.{$newCrewTemplate}.exists">
              <set_value name="$newCrew" exact="$ship.roleentity.{$newCrewTemplate}"/>
            </do_if>
          </do_elseif>
          <set_value name="$newCrewName" exact="'NONE'"/>
          <do_if value="$newCrew and $newCrew.name?">
            <set_value name="$newCrewName" exact="$newCrew.name"/>
          </do_if>
          <do_elseif value="$newPilotRaw and $newPilotRaw.name?">
            <set_value name="$newCrewName" exact="$newPilotRaw.name"/>
          </do_elseif>
          <run_actions ref="md.GT_CoreSystem.DeterminePilotAssignmentHasGTOrder" result="$hasGTOrder">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$newCrew and $newCrew.exists">
            <run_actions ref="md.GT_CoreSystem.HandleRescueRebindForEjectedPilot" result="$rescuedCrew">
              <param name="livePilot" value="$newCrew"/>
              <param name="ship" value="$ship"/>
              <param name="hasGTOrder" value="$hasGTOrder"/>
              <param name="source" value="'vanilla_entityrole_rescue'"/>
            </run_actions>
          </do_if>
          <do_if value="not $rescuedCrew? or not $rescuedCrew">
            <run_actions ref="md.GT_CoreSystem.QueueScanPlayerShipForEjectedPilotRescue">
              <param name="ship" value="$ship"/>
              <param name="source" value="'vanilla_entityrole_assignment'"/>
            </run_actions>
          </do_if>
        </do_elseif>
      </actions>
    </cue>
    
    <!-- Deferred GT registration/update for vanilla pilot assignment changes.
         event.param can be unresolved at assignment time (new=NONE), so re-evaluate ship.pilot after delay. -->
    <cue name="FinalizeVanillaPilotAssignmentForGT" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.FinalizeVanillaPilotAssignmentForGT"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="$data.$Ship"/>
        <set_value name="$source" exact="if $data.$source? then $data.$source else 'unknown'"/>
        <set_value name="$newPilot" exact="if $data.$newPilot? then $data.$newPilot else null"/>
        <set_value name="$newPilotTemplate" exact="if $data.$newPilotTemplate? then $data.$newPilotTemplate else null"/>
        <set_value name="$attempt" exact="if $data.$attempt? then $data.$attempt else 1"/>
        
        <do_if value="$ship and $ship.exists">
          <run_actions ref="md.GT_CoreSystem.GT_ShipIsPlayerFleet" result="$isPlayerFleet">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$isPlayerFleet">
          <run_actions ref="md.GT_CoreSystem.DeterminePilotAssignmentHasGTOrder" result="$hasGTOrder">
            <param name="ship" value="$ship"/>
          </run_actions>

          <!-- Resolve promoted pilot once and reuse for both GT/non-GT branches. -->
          <set_value name="$pilot" exact="null"/>
          <do_if value="$ship.pilot? and $ship.pilot.exists? and $ship.pilot.exists">
            <set_value name="$pilot" exact="$ship.pilot"/>
          </do_if>
          <do_elseif value="$newPilot and $newPilot.exists? and $newPilot.exists">
            <set_value name="$pilot" exact="$newPilot"/>
          </do_elseif>
          <do_elseif value="$newPilotTemplate? and $ship.roleentity? and $ship.roleentity.{$newPilotTemplate}? and $ship.roleentity.{$newPilotTemplate}.exists">
            <set_value name="$pilot" exact="$ship.roleentity.{$newPilotTemplate}"/>
          </do_elseif>
          <do_elseif value="$newPilotTemplate? and $ship.people? and $ship.people.list?">
            <!-- Fallback: resolve by template from full onboard roster if direct lookup is not populated yet. -->
            <set_value name="$crewPool" exact="$ship.people.list"/>
            <do_all exact="$crewPool.count" counter="$i">
              <set_value name="$crew" exact="$crewPool.{$i}"/>
              <do_if value="$crew and (($crew.seed? and $crew.seed == $newPilotTemplate) or $crew == $newPilotTemplate) and $ship.roleentity? and $ship.roleentity.{$crew}? and $ship.roleentity.{$crew}.exists">
                <set_value name="$pilot" exact="$ship.roleentity.{$crew}"/>
              </do_if>
            </do_all>
          </do_elseif>
          
          <do_if value="$pilot and $pilot.exists? and $pilot.exists">
            <run_actions ref="md.GT_CoreSystem.HandleRescueRebindForEjectedPilot" result="$rescuedFinalize">
              <param name="livePilot" value="$pilot"/>
              <param name="ship" value="$ship"/>
              <param name="hasGTOrder" value="$hasGTOrder"/>
              <param name="source" value="'finalize_vanilla_rescue'"/>
            </run_actions>
          </do_if>
          <run_actions ref="md.GT_CoreSystem.ScanPlayerShipForEjectedPilotRescue">
            <param name="ship" value="$ship"/>
            <param name="source" value="'finalize_vanilla_crew_scan'"/>
          </run_actions>
          
          <do_if value="$hasGTOrder">
            <do_if value="$pilot and $pilot.exists? and $pilot.exists">
              <set_value name="$pilotName" exact="if $pilot.name? then $pilot.name else 'NONE'"/>
              
              <do_if value="not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}?">
                <run_actions ref="md.GT_CoreSystem.TryRegisterPilotForShip">
                  <param name="pilot" value="$pilot"/>
                  <param name="ship" value="$ship"/>
                </run_actions>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Core] FinalizeVanillaPilotAssignmentForGT: registered promoted pilot for active GT order: ship=' + $ship.idcode + ', pilot=' + $pilotName + ', source=' + $source + ', attempt=' + $attempt" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
                  <param name="pilot" value="$pilot"/>
                  <param name="ship" value="$ship"/>
                  <param name="hasGTOrder" value="true"/>
                  <param name="clearPausedFields" value="true"/>
                </run_actions>
                <run_actions ref="md.GT_CoreSystem.TryUpdatePilotNameTag">
                  <param name="pilot" value="$pilot"/>
                </run_actions>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Core] FinalizeVanillaPilotAssignmentForGT: refreshed existing GT pilot for active GT order: ship=' + $ship.idcode + ', pilot=' + $pilotName + ', source=' + $source + ', attempt=' + $attempt" chance="100"/>
                </do_if>
              </do_else>
              
              <run_actions ref="md.GT_CoreSystem.EnsureShipRegistryEntry">
                <param name="ship" value="$ship"/>
              </run_actions>
              <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$pilot"/>
              <run_actions ref="md.GT_CoreSystem.TouchShipRegistryLastUpdate">
                <param name="ship" value="$ship"/>
              </run_actions>
              <run_actions ref="md.GT_CoreSystem.RequestShipNameRefresh">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="reason" value="'finalize_vanilla_pilot_assignment'"/>
              </run_actions>
              
              <!-- Re-run ship performance and mod reconciliation immediately after vanilla crew swap settles. -->
              <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
                <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
                  <param name="ship" value="$ship"/>
                  <param name="new_pilot" value="$pilot"/>
                  <param name="old_pilot" value="$pilot"/>
                </run_actions>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$Pilot? and not (global.$GT_Ships.{$ship}.$Pilot.exists? and global.$GT_Ships.{$ship}.$Pilot.exists)">
                <remove_value name="global.$GT_Ships.{$ship}.$Pilot"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] FinalizeVanillaPilotAssignmentForGT: unresolved promoted pilot (ship=' + $ship.idcode + ', source=' + $source + ', tpl=' + (if $newPilotTemplate? then $newPilotTemplate else 'NONE') + ', attempt=' + $attempt + ')'" chance="100"/>
              </do_if>
              <!-- One bounded retry for late vanilla pilot binding. -->
              <run_actions ref="md.GT_CoreSystem.MaybeRetryFinalizeVanillaPilotAssignment">
                <param name="ship" value="$ship"/>
                <param name="source" value="$source"/>
                <param name="newPilot" value="$newPilot"/>
                <param name="newPilotTemplate" value="$newPilotTemplate"/>
                <param name="attempt" value="$attempt"/>
                <param name="maxAttempts" value="5"/>
              </run_actions>
            </do_else>
          </do_if>
          <do_else>
            <!-- No GT order yet: still reconcile pilot identity after delayed vanilla binding so
                 transferred GT pilots are ready for a fresh GT order assignment. -->
            <do_if value="$pilot and $pilot.exists? and $pilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
              <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
                <param name="pilot" value="$pilot"/>
                <param name="ship" value="$ship"/>
                <param name="hasGTOrder" value="false"/>
                <param name="clearPausedFields" value="false"/>
              </run_actions>

              <run_actions ref="md.GT_CoreSystem.QueueDeferredPilotTagRefresh">
                <param name="pilot" value="$pilot"/>
                <param name="source" value="'finalize_vanilla_assignment_no_gt'"/>
              </run_actions>

              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] FinalizeVanillaPilotAssignmentForGT: synchronized GT pilot without active GT order: ship=' + $ship.idcode + ', pilot=' + (if $pilot.name? then $pilot.name else 'NONE') + ', source=' + $source + ', attempt=' + $attempt" chance="100"/>
              </do_if>
            </do_if>
            <do_elseif value="$newPilotTemplate? and $newPilotTemplate != null">
              <run_actions ref="md.GT_CoreSystem.QueueResolvePilotIdentityByStable">
                <param name="ship" value="$ship"/>
                <param name="stable" value="'s:' + $newPilotTemplate"/>
                <param name="template" value="$newPilotTemplate"/>
                <param name="source" value="'finalize_vanilla_assignment_no_gt_template'"/>
              </run_actions>
            </do_elseif>
            <do_else>
              <run_actions ref="md.GT_CoreSystem.MaybeRetryFinalizeVanillaPilotAssignment">
                <param name="ship" value="$ship"/>
                <param name="source" value="$source"/>
                <param name="newPilot" value="$newPilot"/>
                <param name="newPilotTemplate" value="$newPilotTemplate"/>
                <param name="attempt" value="$attempt"/>
                <param name="maxAttempts" value="5"/>
              </run_actions>
            </do_else>
          </do_else>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Resolve demoted GT pilot to the actual service-crew actor after vanilla reassignment.
         This handles cases where vanilla moves the person to a new object id. -->
    <cue name="ResolveDemotedPilotIdentity" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.ResolveDemotedPilotIdentity"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="$data.$Ship"/>
        <set_value name="$oldPilot" exact="$data.$oldPilot"/>
        <set_value name="$baseName" exact="$data.$baseName"/>
        <set_value name="$oldStable" exact="if $data.$oldStable? then $data.$oldStable else ''"/>
        <set_value name="$oldTemplate" exact="$data.$oldTemplate"/>
        <set_value name="$attempt" exact="if $data.$attempt? then $data.$attempt else 1"/>
        
        <do_if value="$ship and $ship.exists and global.$GT_Pilots? and ($oldStable != '' or ($oldPilot and global.$GT_Pilots.{$oldPilot}?))">
          <set_value name="$registryPilot" exact="null"/>
          <do_if value="$oldPilot and global.$GT_Pilots.{$oldPilot}?">
            <set_value name="$registryPilot" exact="$oldPilot"/>
          </do_if>
          <do_elseif value="$oldStable != ''">
            <do_all exact="global.$GT_Pilots.keys.count" counter="$r">
              <set_value name="$candReg" exact="global.$GT_Pilots.keys.{$r}"/>
              <do_if value="global.$GT_Pilots.{$candReg}.$StableIdentity? and global.$GT_Pilots.{$candReg}.$StableIdentity == $oldStable">
                <set_value name="$registryPilot" exact="$candReg"/>
                <break/>
              </do_if>
            </do_all>
          </do_elseif>

          <do_if value="$registryPilot">
          <set_value name="$crewPool" exact="[]"/>
          <do_if value="$ship.people? and $ship.people.list?">
            <set_value name="$crewPool" exact="$ship.people.list"/>
          </do_if>
          <do_elseif value="$ship.people? and $ship.people.{entityrole.service}.list?">
            <set_value name="$crewPool" exact="$ship.people.{entityrole.service}.list"/>
          </do_elseif>
          
          <set_value name="$candidate" exact="null"/>
          <set_value name="$matchCount" exact="0"/>

          <!-- Tier 0 (preferred): StableIdentity match against current service crew actors. -->
          <do_if value="$oldStable != ''">
            <do_all exact="$crewPool.count" counter="$s">
              <set_value name="$crew" exact="$crewPool.{$s}"/>
              <set_value name="$crewEntity" exact="if $crew and $ship.roleentity? and $ship.roleentity.{$crew}? and $ship.roleentity.{$crew}.exists then $ship.roleentity.{$crew} else null"/>
              <do_if value="$crew and $crewEntity and (not $oldPilot or $crewEntity != $oldPilot)">
                <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$crewStable">
                  <param name="pilot" value="$crew"/>
                </run_actions>
                <do_if value="$crewStable != '' and $crewStable == $oldStable">
                  <set_value name="$candidate" exact="$crewEntity"/>
                  <set_value name="$matchCount" exact="$matchCount + 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Prefer deterministic template resolution when available. -->
          <do_if value="not $candidate and $oldTemplate? and $ship.roleentity? and $ship.roleentity.{$oldTemplate}? and (not $oldPilot or $ship.roleentity.{$oldTemplate} != $oldPilot)">
            <set_value name="$candidate" exact="$ship.roleentity.{$oldTemplate}"/>
            <set_value name="$matchCount" exact="1"/>
          </do_if>
          
          <do_if value="not $candidate and $baseName? and $baseName != ''">
            <do_all exact="$crewPool.count" counter="$i">
              <set_value name="$crew" exact="$crewPool.{$i}"/>
              <set_value name="$crewEntity" exact="if $crew and $ship.roleentity? and $ship.roleentity.{$crew}? and $ship.roleentity.{$crew}.exists then $ship.roleentity.{$crew} else null"/>
              <do_if value="$crew and $crewEntity and (not $oldPilot or $crewEntity != $oldPilot) and $crew.name? and $crew.name == $baseName">
                <set_value name="$candidate" exact="$crewEntity"/>
                <set_value name="$matchCount" exact="$matchCount + 1"/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Unique match found: migrate GT record key to new actor id. -->
          <do_if value="$candidate and $matchCount == 1">
            <run_actions ref="md.GT_Ship_Management.Rebind_Pilot_Registry" result="$demotedRebind">
              <param name="livePilot" value="$candidate"/>
              <param name="registryPilotHint" value="$registryPilot"/>
              <param name="stableKey" value="$oldStable"/>
              <param name="ship" value="$ship"/>
              <param name="template" value="$oldTemplate"/>
            </run_actions>
            <set_value name="$candidate" exact="if $demotedRebind.$Pilot? then $demotedRebind.$Pilot else $candidate"/>
            <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
              <param name="pilot" value="$candidate"/>
              <param name="ship" value="$ship"/>
              <param name="hasGTOrder" value="false"/>
              <param name="clearPausedFields" value="false"/>
            </run_actions>
            
            <run_actions ref="md.GT_CoreSystem.QueueBoundedPilotTagRefresh">
              <param name="pilot" value="$candidate"/>
              <param name="stableKey" value="$oldStable"/>
              <param name="ship" value="$ship"/>
              <param name="source" value="'resolve_demoted_identity'"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$oldPilotNameDbg" exact="if $oldPilot and $oldPilot.exists and $oldPilot.name? then $oldPilot.name else 'NONE'"/>
              <set_value name="$registryPilotNameDbg" exact="if $registryPilot and $registryPilot.exists and $registryPilot.name? then $registryPilot.name else 'NONE'"/>
              <debug_text text="'[GT-Core] Resolved demoted GT pilot identity: old=' + $oldPilotNameDbg + ', reg=' + $registryPilotNameDbg + ', oldTpl=' + (if $oldTemplate? then $oldTemplate else 'NONE') + ', stable=' + (if $oldStable != '' then $oldStable else 'NONE') + ', new=' + $candidate.name + (if $candidate.idcode? then ' [' + $candidate.idcode + ']' else '') + ', ship=' + $ship.idcode" chance="100"/>
            </do_if>
          </do_if>
          <do_elseif value="not $candidate">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$oldPilotNameDbg" exact="if $oldPilot and $oldPilot.exists and $oldPilot.name? then $oldPilot.name else 'NONE'"/>
              <debug_text text="'[GT-Core] ResolveDemotedPilotIdentity retry: ship=' + $ship.idcode + ', old=' + $oldPilotNameDbg + ', stable=' + (if $oldStable != '' then $oldStable else 'NONE') + ', attempt=' + $attempt" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_CoreSystem.MaybeRetryResolveDemotedPilotIdentity">
              <param name="ship" value="$ship"/>
              <param name="oldPilot" value="$oldPilot"/>
              <param name="baseName" value="$baseName"/>
              <param name="oldStable" value="$oldStable"/>
              <param name="oldTemplate" value="$oldTemplate"/>
              <param name="attempt" value="$attempt"/>
              <param name="maxAttempts" value="31"/>
            </run_actions>
          </do_elseif>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Resolve/rebind GT pilot identity by stable key when vanilla assignment events do not
         provide oldPilot/newPilot actors reliably (old=NONE/new=NONE with template present). -->
    <cue name="ResolvePilotIdentityByStable" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.ResolvePilotIdentityByStable"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="$data.$Ship"/>
        <set_value name="$stable" exact="if $data.$stable? then $data.$stable else ''"/>
        <set_value name="$template" exact="$data.$template"/>
        <set_value name="$source" exact="if $data.$source? then $data.$source else 'unknown'"/>
        <set_value name="$attempt" exact="if $data.$attempt? then $data.$attempt else 1"/>

        <do_if value="$ship and $ship.exists and $stable != '' and global.$GT_Pilots?">
          <set_value name="$registryPilot" exact="null"/>
          <set_value name="$registryMatchCount" exact="0"/>
          <do_all exact="global.$GT_Pilots.keys.count" counter="$i">
            <set_value name="$cand" exact="global.$GT_Pilots.keys.{$i}"/>
            <do_if value="global.$GT_Pilots.{$cand}.$StableIdentity? and global.$GT_Pilots.{$cand}.$StableIdentity == $stable">
              <set_value name="$registryPilot" exact="$cand"/>
              <set_value name="$registryMatchCount" exact="$registryMatchCount + 1"/>
            </do_if>
          </do_all>

          <set_value name="$crewCandidate" exact="null"/>
          <set_value name="$crewMatchCount" exact="0"/>

          <do_if value="$template? and $template != null and $ship.roleentity? and $ship.roleentity.{$template}?">
            <set_value name="$crewCandidate" exact="$ship.roleentity.{$template}"/>
            <set_value name="$crewMatchCount" exact="1"/>
          </do_if>

          <do_if value="(not $crewCandidate)">
            <set_value name="$crewPool" exact="[]"/>
            <do_if value="$ship.people? and $ship.people.list?">
              <set_value name="$crewPool" exact="$ship.people.list"/>
            </do_if>
            <do_elseif value="$ship.people? and $ship.people.{entityrole.service}.list?">
              <set_value name="$crewPool" exact="$ship.people.{entityrole.service}.list"/>
            </do_elseif>
            <do_all exact="$crewPool.count" counter="$j">
              <set_value name="$crew" exact="$crewPool.{$j}"/>
              <do_if value="$crew">
                <run_actions ref="md.GT_Ship_Management.Compute_Pilot_Stable_Key" result="$crewStable">
                  <param name="pilot" value="$crew"/>
                </run_actions>
                <set_value name="$crewEntity" exact="if $ship.roleentity? and $ship.roleentity.{$crew}? and $ship.roleentity.{$crew}.exists then $ship.roleentity.{$crew} else null"/>
                <do_if value="$crewStable != '' and $crewStable == $stable and $crewEntity">
                  <set_value name="$crewCandidate" exact="$crewEntity"/>
                  <set_value name="$crewMatchCount" exact="$crewMatchCount + 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>

          <do_if value="$crewCandidate and $crewMatchCount == 1">
            <run_actions ref="md.GT_Ship_Management.Rebind_Pilot_Registry" result="$rebindStableResult">
              <param name="livePilot" value="$crewCandidate"/>
              <param name="registryPilotHint" value="$registryPilot"/>
              <param name="stableKey" value="$stable"/>
              <param name="ship" value="$ship"/>
              <param name="template" value="$template"/>
            </run_actions>
            <set_value name="$crewCandidate" exact="if $rebindStableResult.$Pilot? then $rebindStableResult.$Pilot else $crewCandidate"/>
            <run_actions ref="md.GT_CoreSystem.SyncPilotShipLinkState">
              <param name="pilot" value="$crewCandidate"/>
              <param name="ship" value="$ship"/>
              <param name="hasGTOrder" value="false"/>
              <param name="clearPausedFields" value="false"/>
            </run_actions>
            <run_actions ref="md.GT_CoreSystem.QueueBoundedPilotTagRefresh">
              <param name="pilot" value="$crewCandidate"/>
              <param name="stableKey" value="$stable"/>
              <param name="ship" value="$ship"/>
              <param name="source" value="'resolve_stable_' + $source"/>
            </run_actions>
            <do_if value="$rebindStableResult.$Rebound? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$registryPilotNameDbg" exact="if $registryPilot and $registryPilot.exists and $registryPilot.name? then $registryPilot.name else 'NONE'"/>
              <debug_text text="'[GT-Core] ResolvePilotIdentityByStable: rebound pilot stable=' + $stable + ' source=' + $source + ' ship=' + $ship.idcode + ', new=' + $crewCandidate.name + ', old=' + $registryPilotNameDbg" chance="100"/>
            </do_if>
          </do_if>
          <do_elseif value="not $crewCandidate">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] ResolvePilotIdentityByStable retry: ship=' + $ship.idcode + ', stable=' + $stable + ', source=' + $source + ', attempt=' + $attempt" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_CoreSystem.MaybeRetryResolvePilotIdentityByStable">
              <param name="ship" value="$ship"/>
              <param name="stable" value="$stable"/>
              <param name="template" value="$template"/>
              <param name="source" value="$source"/>
              <param name="attempt" value="$attempt"/>
              <param name="maxAttempts" value="31"/>
            </run_actions>
          </do_elseif>
        </do_if>
      </actions>
    </cue>

    <!-- Bounded tag refresh: attempt 1 at ~1s. -->
    <cue name="BoundedPilotTagRefresh" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.BoundedPilotTagRefresh"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <run_actions ref="md.GT_CoreSystem.ExecuteBoundedPilotTagRefreshAttempt">
          <param name="pilotHint" value="if $data.$pilot? then $data.$pilot else null"/>
          <param name="stableKey" value="if $data.$stableKey? then $data.$stableKey else ''"/>
          <param name="sector" value="if $data.$sector? then $data.$sector else null"/>
          <param name="ship" value="if $data.$ship? then $data.$ship else null"/>
          <param name="source" value="if $data.$source? then $data.$source else 'unknown'"/>
          <param name="attempt" value="if $data.$attempt? then $data.$attempt else 1"/>
          <param name="ejectMode" value="if $data.$ejectMode? then $data.$ejectMode else false"/>
        </run_actions>
      </actions>
    </cue>

    <!-- Follow-up attempts 2-3 at +2s each (~3s / ~5s from first signal). -->
    <cue name="BoundedPilotTagRefreshFollowUp" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.BoundedPilotTagRefreshFollowUp"/>
      </conditions>
      <delay exact="2s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <run_actions ref="md.GT_CoreSystem.ExecuteBoundedPilotTagRefreshAttempt">
          <param name="pilotHint" value="if $data.$pilot? then $data.$pilot else null"/>
          <param name="stableKey" value="if $data.$stableKey? then $data.$stableKey else ''"/>
          <param name="sector" value="if $data.$sector? then $data.$sector else null"/>
          <param name="ship" value="if $data.$ship? then $data.$ship else null"/>
          <param name="source" value="if $data.$source? then $data.$source else 'unknown'"/>
          <param name="attempt" value="if $data.$attempt? then $data.$attempt else 2"/>
          <param name="ejectMode" value="if $data.$ejectMode? then $data.$ejectMode else false"/>
        </run_actions>
      </actions>
    </cue>

    <!-- Delayed crew scan after vanilla boarding events settle (RescueShip crew transfer). -->
    <cue name="DelayedSpacesuitDestroyRescue" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.DelayedSpacesuitDestroyRescue"/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$spacesuit" exact="if $data.$Spacesuit? then $data.$Spacesuit else null"/>
        <set_value name="$registryPilotHint" exact="if $data.$RegistryPilotHint? then $data.$RegistryPilotHint else null"/>
        <set_value name="$sector" exact="if $data.$Sector? then $data.$Sector else null"/>
        <set_value name="$source" exact="if $data.$source? then $data.$source else 'spacesuit_destroyed_gt_handler'"/>
        <set_value name="$rescued" exact="false"/>
        <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}? and global.$GT_Pilots.{$registryPilotHint}.$Status? and global.$GT_Pilots.{$registryPilotHint}.$Status == 'ejected'">
          <do_if value="$spacesuit? and $spacesuit.exists and $spacesuit.pilot? and $spacesuit.pilot.exists">
            <set_value name="global.$GT_Pilots.{$registryPilotHint}.$LastKnownPilotRef" exact="$spacesuit.pilot"/>
          </do_if>
          <run_actions ref="md.GT_CoreSystem.TryImmediateSpacesuitDestroyRescue" result="$rescued">
            <param name="spacesuit" value="$spacesuit"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="sector" value="$sector"/>
            <param name="source" value="$source"/>
          </run_actions>
          <do_if value="not $rescued">
            <do_if value="global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips? and global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips.count gt 0">
              <signal_cue_instantly cue="md.GT_CoreSystem.DelayedRescueShipRescan" param="table[
                $Ship = global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips.{1},
                $source = $source,
                $attempt = 1,
                $maxAttempts = 20,
                $RegistryPilotHint = $registryPilotHint
              ]"/>
            </do_if>
            <run_actions ref="md.GT_CoreSystem.QueueDelayedEjectedPilotNearbyRescan">
              <param name="registryPilotHint" value="$registryPilotHint"/>
              <param name="source" value="$source"/>
            </run_actions>
          </do_if>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] DelayedSpacesuitDestroyRescue: pilot=' + (if $registryPilotHint.name? then $registryPilotHint.name else 'NONE') + ', sector=' + (if $sector? then $sector.knownname else 'NONE') + ', rescued=' + $rescued" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <cue name="DelayedEjectedPilotNearbyRescan" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.DelayedEjectedPilotNearbyRescan"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$registryPilotHint" exact="if $data.$RegistryPilotHint? then $data.$RegistryPilotHint else null"/>
        <set_value name="$source" exact="if $data.$source? then $data.$source else 'spacesuit_destroyed_nearby_rescan'"/>
        <set_value name="$attempt" exact="if $data.$attempt? then $data.$attempt else 1"/>
        <set_value name="$maxAttempts" exact="if $data.$maxAttempts? then $data.$maxAttempts else 20"/>
        <set_value name="$stillEjected" exact="false"/>
        <set_value name="$candidates" exact="[]"/>
        <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}? and global.$GT_Pilots.{$registryPilotHint}.$Status? and global.$GT_Pilots.{$registryPilotHint}.$Status == 'ejected'">
          <set_value name="$stillEjected" exact="true"/>
          <do_if value="global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips? and global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips.count gt 0">
            <set_value name="$candidates" exact="global.$GT_Pilots.{$registryPilotHint}.$RescueCandidateShips"/>
          </do_if>
        </do_if>
        <set_value name="$rescued" exact="false"/>
        <do_if value="$stillEjected and $candidates.count gt 0">
          <run_actions ref="md.GT_CoreSystem.TryRescueOnCandidateShips" result="$rescued">
            <param name="candidateShips" value="$candidates"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="source" value="$source + '_try' + $attempt"/>
          </run_actions>
        </do_if>
        <do_if value="not $rescued and $stillEjected and $attempt lt $maxAttempts and $candidates.count gt 0">
          <signal_cue_instantly cue="md.GT_CoreSystem.DelayedEjectedPilotNearbyRescan" param="table[
            $RegistryPilotHint = $registryPilotHint,
            $source = $source,
            $attempt = $attempt + 1,
            $maxAttempts = $maxAttempts
          ]"/>
        </do_if>
        <do_elseif value="not $rescued and $stillEjected and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] DelayedEjectedPilotNearbyRescan: gave up after ' + $attempt + ' attempts, pilot still ejected, candidates=' + $candidates.count" chance="100"/>
        </do_elseif>
      </actions>
    </cue>

    <cue name="DelayedScanPlayerShipForEjectedPilotRescue" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.DelayedScanPlayerShipForEjectedPilotRescue"/>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="if $data.$Ship? then $data.$Ship else null"/>
        <set_value name="$source" exact="if $data.$source? then $data.$source else 'crew_rescue_scan'"/>
        <set_value name="$attempt" exact="if $data.$attempt? then $data.$attempt else 1"/>
        <set_value name="$maxAttempts" exact="if $data.$maxAttempts? then $data.$maxAttempts else 10"/>
        <set_value name="$registryPilotHint" exact="if $data.$RegistryPilotHint? then $data.$RegistryPilotHint else null"/>
        <run_actions ref="md.GT_CoreSystem.ScanPlayerShipForEjectedPilotRescue" result="$rescued">
          <param name="ship" value="$ship"/>
          <param name="source" value="$source + '_try' + $attempt"/>
          <param name="registryPilotHint" value="$registryPilotHint"/>
        </run_actions>
        <do_if value="not $rescued">
          <run_actions ref="md.GT_CoreSystem.MaybeRetryScanPlayerShipForEjectedPilotRescue">
            <param name="ship" value="$ship"/>
            <param name="source" value="$source"/>
            <param name="attempt" value="$attempt"/>
            <param name="maxAttempts" value="$maxAttempts"/>
          </run_actions>
        </do_if>
      </actions>
    </cue>

    <cue name="DelayedRescueShipRescan" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.DelayedRescueShipRescan"/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="if $data.$Ship? then $data.$Ship else null"/>
        <set_value name="$source" exact="if $data.$source? then $data.$source else 'spacesuit_destroyed_rescue'"/>
        <set_value name="$attempt" exact="if $data.$attempt? then $data.$attempt else 1"/>
        <set_value name="$maxAttempts" exact="if $data.$maxAttempts? then $data.$maxAttempts else 20"/>
        <set_value name="$registryPilotHint" exact="if $data.$RegistryPilotHint? then $data.$RegistryPilotHint else null"/>
        <do_if value="$registryPilotHint and $ship? and $ship.exists">
          <run_actions ref="md.GT_CoreSystem.TryRescueSpecificEjectedPilotOnShip" result="$rescued">
            <param name="ship" value="$ship"/>
            <param name="registryPilotHint" value="$registryPilotHint"/>
            <param name="source" value="$source + '_retry' + $attempt"/>
          </run_actions>
        </do_if>
        <do_else>
          <run_actions ref="md.GT_CoreSystem.ScanPlayerShipForEjectedPilotRescue" result="$rescued">
            <param name="ship" value="$ship"/>
            <param name="source" value="$source + '_retry' + $attempt"/>
          </run_actions>
        </do_else>
        <do_if value="not $rescued and $attempt lt $maxAttempts and $ship? and $ship.exists">
          <signal_cue_instantly cue="md.GT_CoreSystem.DelayedRescueShipRescan" param="table[
            $Ship = $ship,
            $source = $source,
            $attempt = $attempt + 1,
            $maxAttempts = $maxAttempts,
            $RegistryPilotHint = $registryPilotHint
          ]"/>
        </do_if>
      </actions>
    </cue>

    <!-- Per-spacesuit dock watcher: event_object_docked object= requires a concrete object, not a global group. -->
    <cue name="WatchEjectedSpacesuitDock" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.WatchEjectedSpacesuitDock"/>
      </conditions>
      <actions>
        <set_value name="this.$spacesuit" exact="event.param.$Spacesuit"/>
        <set_value name="this.$registryPilotHint" exact="if event.param.$RegistryPilotHint? then event.param.$RegistryPilotHint else null"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] WatchEjectedSpacesuitDock: suit=' + (if this.$spacesuit? and this.$spacesuit.idcode? then this.$spacesuit.idcode else 'NONE')" chance="100"/>
        </do_if>
      </actions>
      <cues>
        <cue name="OnSpacesuitDocked" instantiate="true">
          <conditions>
            <event_object_docked object="parent.$spacesuit"/>
          </conditions>
          <actions>
            <run_actions ref="md.GT_CoreSystem.ProcessEjectedSpacesuitDockPickup">
              <param name="spacesuit" value="parent.$spacesuit"/>
              <param name="dockObject" value="event.param"/>
              <param name="registryPilotHint" value="parent.$registryPilotHint"/>
              <param name="source" value="'spacesuit_docked'"/>
            </run_actions>
            <cancel_cue cue="parent"/>
          </actions>
        </cue>
        <cue name="OnSpacesuitDestroyed" instantiate="true">
          <conditions>
            <event_object_destroyed object="parent.$spacesuit"/>
          </conditions>
          <actions>
            <cancel_cue cue="parent"/>
          </actions>
        </cue>
      </cues>
    </cue>

    <!-- GT pilot eject lifecycle: destroy â†’ ejected status â†’ bounded retag burst. -->
    <cue name="HandlePlayerOwnedShipDestroyedForGT" instantiate="true">
      <conditions>
        <event_player_owned_destroyed/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param"/>
        <set_value name="$killer" exact="event.param2"/>
        <set_value name="$killMethod" exact="if event.param3? then event.param3 else 'NONE'"/>

        <!-- TEST DIAG: mark exact vanilla destroy event timing in log + logbook (before any GT guards). -->
        <set_value name="$destroyDiagID" exact="if $ship? and $ship.idcode? then $ship.idcode else 'NONE'"/>
        <set_value name="$destroyedShipID" exact="if $ship? and $ship.idcode? then $ship.idcode else ''"/>
        <set_value name="$destroyedShipName" exact="if $ship? and $ship.knownname? then $ship.knownname else 'NONE'"/>
        <set_value name="$destroyedClass" exact="if $ship? and $ship.isclass.spacesuit then 'spacesuit' else (if $ship? and $ship.isclass.ship then 'ship' else 'other')"/>
        <set_value name="$destroyDefaultOrder" exact="if $ship? and $ship.defaultorder? then @$ship.defaultorder.id else 'NONE'"/>
        <set_value name="$destroyCurrentOrder" exact="if $ship? and $ship.order? then @$ship.order.id else 'NONE'"/>
        <set_value name="$destroyPilotName" exact="if $ship? and $ship.pilot? and $ship.pilot.name? then $ship.pilot.name else 'NONE'"/>
        <set_value name="$destroySectorName" exact="if $ship? and $ship.sector? then $ship.sector.knownname else 'NONE'"/>
        <set_value name="$destroyCommanderID" exact="if $ship? and $ship.commander? and $ship.commander.exists and $ship.commander.idcode? then $ship.commander.idcode else 'NONE'"/>
        <!-- event_player_owned_destroyed includes Assist subordinates where isplayerowned is false â€” do not gate on isplayerowned. -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] event_player_owned_destroyed: id=' + $destroyDiagID + ', name=' + $destroyedShipName + ', class=' + $destroyedClass + ', sector=' + $destroySectorName + ', default=' + $destroyDefaultOrder + ', current=' + $destroyCurrentOrder + ', pilot=' + $destroyPilotName + ', commander=' + $destroyCommanderID + ', killMethod=' + $killMethod + ', isplayerowned=' + (if $ship? and $ship.isplayerowned then '1' else '0')" chance="100"/>
        </do_if>

        <do_if value="$ship and ($ship.isclass.ship or $ship.isclass.spacesuit)">
          <run_actions ref="md.GT_CoreSystem.ResolveGTPilotForDestroyedShip" result="$pilot">
            <param name="ship" value="$ship"/>
            <param name="destroyedShipID" value="$destroyedShipID"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] HandlePlayerOwnedShipDestroyedForGT: ship=' + (if $destroyedShipID != '' then $destroyedShipID else 'NONE') + ', spacesuit=' + $ship.isclass.spacesuit + ', pilot=' + (if $pilot and $pilot.name? then $pilot.name else 'NONE')" chance="100"/>
          </do_if>

          <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
            <!-- Spacesuit follow-up: vanilla removes the suit on pickup (killMethod=removed, current=DockAt). -->
            <do_if value="$ship.isclass.spacesuit and global.$GT_Pilots.{$pilot}.$Status? and global.$GT_Pilots.{$pilot}.$Status == 'ejected'">
              <set_value name="$ejectSector" exact="if $ship.sector? then $ship.sector else null"/>
              <set_value name="$livePilot" exact="if $ship.pilot? and $ship.pilot.exists then $ship.pilot else $pilot"/>
              <set_value name="$rescuedImmediate" exact="false"/>
              <run_actions ref="md.GT_CoreSystem.ResolveRescueShipFromSpacesuitContext" result="$rescueShip">
                <param name="spacesuit" value="$ship"/>
                <param name="sector" value="$ejectSector"/>
              </run_actions>
              <do_if value="$rescueShip? and $rescueShip.exists">
                <run_actions ref="md.GT_CoreSystem.TryRescueEjectedPilotAtPickup" result="$rescuedImmediate">
                  <param name="livePilot" value="$livePilot"/>
                  <param name="rescueShip" value="$rescueShip"/>
                  <param name="registryPilotHint" value="$pilot"/>
                  <param name="spacesuit" value="$ship"/>
                  <param name="source" value="'spacesuit_destroyed_pickup'"/>
                </run_actions>
              </do_if>
              <do_if value="not $rescuedImmediate">
                <run_actions ref="md.GT_CoreSystem.ScanPlayerFleetInSectorForEjectedPilot" result="$rescuedImmediate">
                  <param name="sector" value="$ejectSector"/>
                  <param name="registryPilotHint" value="$pilot"/>
                  <param name="source" value="'spacesuit_destroyed_sector_scan'"/>
                </run_actions>
              </do_if>
              <do_if value="not $rescuedImmediate">
                <run_actions ref="md.GT_CoreSystem.QueueDelayedSpacesuitDestroyRescue">
                  <param name="spacesuit" value="$ship"/>
                  <param name="registryPilotHint" value="$pilot"/>
                  <param name="sector" value="$ejectSector"/>
                  <param name="source" value="'spacesuit_destroyed_gt_handler'"/>
                </run_actions>
              </do_if>
            </do_if>
            <do_elseif value="$ship.isclass.spacesuit">
              <run_actions ref="md.GT_CoreSystem.ProcessGTPilotEjectOnDestroy">
                <param name="pilot" value="$pilot"/>
                <param name="destroyedObject" value="$ship"/>
              </run_actions>
            </do_elseif>
            <do_else>
              <run_actions ref="md.GT_CoreSystem.ProcessGTPilotEjectOnDestroy">
                <param name="pilot" value="$pilot"/>
                <param name="destroyedObject" value="$ship"/>
              </run_actions>
            </do_else>
          </do_if>
          <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] HandlePlayerOwnedShipDestroyedForGT: NO GT pilot resolved for ship=' + (if $destroyDiagID != 'NONE' then $destroyDiagID else 'NONE')" chance="100"/>
          </do_elseif>
        </do_if>
      </actions>
    </cue>
    
    <!-- Ship Unregistration System -->
    <cue name="UnregisterShip" instantiate="true">
      <conditions>
        <event_object_destroyed object="player.entity"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <set_value name="$destroyedShipID" exact="if $ship? and $ship.idcode? then $ship.idcode else ''"/>
        
        <!-- Check if ship was registered -->
        <do_if value="global.$GT_Ships.{$ship}?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Unregistering destroyed ship: ' + $ship.knownname" chance="100"/>
          </do_if>
          
          <!-- OPTIMIZATION: Update cached active trader count incrementally -->
          <!-- Only decrement if ship was operational (matches counting logic) -->
          <do_if value="$ship.exists and $ship.isoperational and global.$GT_ActiveTraderCount? and global.$GT_ActiveTraderCount gt 0">
            <set_value name="global.$GT_ActiveTraderCount" operation="subtract"/>
          </do_if>
          
          <!-- Clean up data -->
          <set_value name="$destroyedShipID" exact="if $ship.idcode? then $ship.idcode else ''"/>
          <remove_value name="global.$GT_Ships.{$ship}"/>
          <remove_value name="global.$GT_FleetData.{$ship}"/>
          <do_if value="global.$GT_Ship_State? and global.$GT_Ship_State.{$ship}?">
            <remove_value name="global.$GT_Ship_State.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_DelayedVerificationState? and global.$GT_DelayedVerificationState.{$ship}?">
            <remove_value name="global.$GT_DelayedVerificationState.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_CleanupIntent? and global.$GT_CleanupIntent.{$ship}?">
            <remove_value name="global.$GT_CleanupIntent.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_CleanupSignalState? and global.$GT_CleanupSignalState.{$ship}?">
            <remove_value name="global.$GT_CleanupSignalState.{$ship}"/>
          </do_if>
          <!-- B6: Drop any leftover Galaxy-Miner intent/assignment entries for this destroyed ship.
               The miner order's on_abort already cleans its own entries when it aborts, but a destroyed
               script cannot guarantee on_abort completes; without this sweep, stale rows in
               $GT_MinerIntents.{station}.{ware}.{ship} keep inflating $projectedIncoming and
               $supplierCount for the surviving fleet. Walk only the keys that actually exist so this
               stays O(active stations * served wares), not O(all stations). -->
          <do_if value="global.$GT_MinerIntents? and global.$GT_MinerIntents.keys.count gt 0">
            <do_all exact="global.$GT_MinerIntents.keys.count" counter="$mintIdx">
              <set_value name="$mintStation" exact="global.$GT_MinerIntents.keys.{$mintIdx}"/>
              <do_if value="global.$GT_MinerIntents.{$mintStation}? and global.$GT_MinerIntents.{$mintStation}.keys.count gt 0">
                <do_all exact="global.$GT_MinerIntents.{$mintStation}.keys.count" counter="$mintWareIdx">
                  <set_value name="$mintWare" exact="global.$GT_MinerIntents.{$mintStation}.keys.{$mintWareIdx}"/>
                  <do_if value="global.$GT_MinerIntents.{$mintStation}.{$mintWare}? and global.$GT_MinerIntents.{$mintStation}.{$mintWare}.{$ship}?">
                    <remove_value name="global.$GT_MinerIntents.{$mintStation}.{$mintWare}.{$ship}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_MinerStationAssignments? and global.$GT_MinerStationAssignments.keys.count gt 0">
            <do_all exact="global.$GT_MinerStationAssignments.keys.count" counter="$massnIdx">
              <set_value name="$massnStation" exact="global.$GT_MinerStationAssignments.keys.{$massnIdx}"/>
              <do_if value="global.$GT_MinerStationAssignments.{$massnStation}? and global.$GT_MinerStationAssignments.{$massnStation}.keys.count gt 0">
                <do_all exact="global.$GT_MinerStationAssignments.{$massnStation}.keys.count" counter="$massnWareIdx">
                  <set_value name="$massnWare" exact="global.$GT_MinerStationAssignments.{$massnStation}.keys.{$massnWareIdx}"/>
                  <do_if value="global.$GT_MinerStationAssignments.{$massnStation}.{$massnWare}? and global.$GT_MinerStationAssignments.{$massnStation}.{$massnWare}.{$ship}?">
                    <remove_value name="global.$GT_MinerStationAssignments.{$massnStation}.{$massnWare}.{$ship}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <!-- Use library function to clear pending trade data -->
          <!-- Phase 3: Enhanced cleanup includes reservations, work items, scheduler state -->
          <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
            <param name="ship" value="$ship"/>
          </run_actions>
          <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Legacy SearchQueue cleanup removed in AI migration -->
          
          <!-- Defer pilot ship-link cleanup so player_owned_destroyed eject handler can resolve pilot first. -->
          <do_if value="$destroyedShipID != ''">
            <signal_cue_instantly cue="md.GT_CoreSystem.DelayedClearDestroyedPilotShipLinks" param="table[
              $Ship = $ship,
              $ShipID = $destroyedShipID
            ]"/>
          </do_if>
          <!-- Preserve pilot registry on ship loss.
               Destroy/eject timing can temporarily report survivors as non-existent,
               so aggressive object-exists cleanup would wipe rescued pilot XP/level data. -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $ship.pilot?">
            <debug_text text="'[GalaxyTrader MK3] Ship destroyed; preserving pilot registry for potential rescue/reassignment: ' + $ship.pilot.name" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <cue name="DelayedClearDestroyedPilotShipLinks" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.DelayedClearDestroyedPilotShipLinks"/>
      </conditions>
      <delay exact="100ms"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="if $data.$Ship? then $data.$Ship else null"/>
        <set_value name="$destroyedShipID" exact="if $data.$ShipID? then $data.$ShipID else ''"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$pilotIdx">
            <set_value name="$pilotKey" exact="global.$GT_Pilots.keys.{$pilotIdx}"/>
            <set_value name="$pilotLinkedToDestroyedShip" exact="false"/>
            <do_if value="$ship and global.$GT_Pilots.{$pilotKey}.$Ship? and global.$GT_Pilots.{$pilotKey}.$Ship == $ship">
              <set_value name="$pilotLinkedToDestroyedShip" exact="true"/>
            </do_if>
            <do_if value="not $pilotLinkedToDestroyedShip and $ship and global.$GT_Pilots.{$pilotKey}.$AssociatedShip? and global.$GT_Pilots.{$pilotKey}.$AssociatedShip == $ship">
              <set_value name="$pilotLinkedToDestroyedShip" exact="true"/>
            </do_if>
            <do_if value="not $pilotLinkedToDestroyedShip and $destroyedShipID != '' and global.$GT_Pilots.{$pilotKey}.$ShipID? and global.$GT_Pilots.{$pilotKey}.$ShipID == $destroyedShipID">
              <set_value name="$pilotLinkedToDestroyedShip" exact="true"/>
            </do_if>
            <do_if value="$pilotLinkedToDestroyedShip">
              <remove_value name="global.$GT_Pilots.{$pilotKey}.$Ship"/>
              <remove_value name="global.$GT_Pilots.{$pilotKey}.$AssociatedShip"/>
              <remove_value name="global.$GT_Pilots.{$pilotKey}.$ShipID"/>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </cue>
    
    <!-- Commander Destruction Handler - Handle Subordinates When Commander is Destroyed -->
    <cue name="HandleCommanderDestroyed" instantiate="true">
      <conditions>
        <event_object_destroyed object="player.entity"/>
      </conditions>
      <actions>
        <set_value name="$destroyedCommander" exact="event.object"/>
        
        <!-- BUG C6 FIX: Don't gate on global.$GT_Ships.{$destroyedCommander} alone.
             UnregisterShip listens on the same event and may run first, removing the
             commander from the registry before we get here.  Instead, collect
             subordinates directly from the ship object and check for GT-registered ones. -->
        
        <!-- Find all subordinates of this commander -->
        <!-- Use safe operator since ship is destroyed and allsubordinates might not be accessible -->
        <set_value name="$subordinates" exact="[]"/>
        <do_if value="$destroyedCommander.allsubordinates?">
          <set_value name="$subordinates" exact="@$destroyedCommander.allsubordinates"/>
        </do_if>
        <do_if value="(if $subordinates != null then $subordinates.count else 0) gt 0">
          <!-- Quick scan: does this commander have any GT subordinates? -->
          <set_value name="$hasGTSubordinates" exact="false"/>
          <do_all exact="$subordinates.count" counter="$chk">
            <do_if value="global.$GT_Ships.{$subordinates.{$chk}}?">
              <set_value name="$hasGTSubordinates" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="$hasGTSubordinates">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] Commander destroyed: ' + @$destroyedCommander.knownname + ' (ID: ' + @$destroyedCommander.idcode + ') - checking ' + $subordinates.count + ' subordinates'" chance="100"/>
            </do_if>
            <!-- First pass: Identify promoted subordinate (if any) -->
            <!-- When X4 promotes a subordinate to commander, it:
                 1. No longer has a commander (or commander is destroyed)
                 2. Gets a GT order directly (not via Assist)
                 3. May have subordinates assigned (but timing can vary) -->
            <set_value name="$promotedSubordinate" exact="null"/>
            <do_all exact="$subordinates.count" counter="$i">
              <set_value name="$subordinate" exact="$subordinates.{$i}"/>
              <do_if value="$subordinate.exists and global.$GT_Ships.{$subordinate}?">
                <!-- Check if this subordinate was promoted -->
                <set_value name="$hasNoCommander" exact="false"/>
                <do_if value="not $subordinate.commander? or not $subordinate.commander.exists or $subordinate.commander == $destroyedCommander">
                  <set_value name="$hasNoCommander" exact="true"/>
                </do_if>
                
                <!-- Check if subordinate has GT order directly (not via Assist) - indicates promotion -->
                <set_value name="$hasDirectGTOrder" exact="false"/>
                <do_if value="$hasNoCommander and $subordinate.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$subordinate.defaultorder.id})">
                  <set_value name="$hasDirectGTOrder" exact="true"/>
                </do_if>
                
                <!-- Also check if subordinate has subordinates (another indicator) -->
                <set_value name="$hasSubordinates" exact="false"/>
                <do_if value="$subordinate.allsubordinates? and @$subordinate.allsubordinates.count gt 0">
                  <set_value name="$hasSubordinates" exact="true"/>
                </do_if>
                
                <!-- If subordinate has no commander AND (has direct GT order OR has subordinates), it was promoted -->
                <do_if value="$hasNoCommander and ($hasDirectGTOrder or $hasSubordinates)">
                  <set_value name="$promotedSubordinate" exact="$subordinate"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Core] Subordinate ' + $subordinate.idcode + ' was promoted to commander (has direct GT order: ' + $hasDirectGTOrder + ', has subordinates: ' + $hasSubordinates + ')'" chance="100"/>
                  </do_if>
                  <break/>
                </do_if>
              </do_if>
            </do_all>
            
            <!-- Second pass: Process all subordinates -->
            <do_all exact="$subordinates.count" counter="$i">
              <set_value name="$subordinate" exact="$subordinates.{$i}"/>
              
              <!-- Check if subordinate is in GT registry -->
              <do_if value="$subordinate.exists and global.$GT_Ships.{$subordinate}?">
                <!-- Skip cleanup if this subordinate was promoted to commander -->
                <do_if value="$promotedSubordinate? and $subordinate == $promotedSubordinate">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Core] Skipping cleanup for promoted subordinate ' + $subordinate.idcode + ' (now commander)'" chance="100"/>
                  </do_if>
                  
                  <!-- Update state to reflect promotion (no longer subordinate, now commander) -->
                  <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
                    $Ship = $subordinate,
                    $UpdateType = 'Promoted_To_Commander',
                    $Commander = null,
                    $CommanderHasGT = false
                  ]"/>
                </do_if>
                <do_else>
                  <!-- Check if X4 automatically assigned a new commander -->
                  <set_value name="$newCommander" exact="null"/>
                  <set_value name="$hasNewCommander" exact="false"/>
                  <do_if value="$subordinate.commander? and $subordinate.commander.exists and $subordinate.commander != $destroyedCommander">
                    <set_value name="$newCommander" exact="$subordinate.commander"/>
                    <set_value name="$hasNewCommander" exact="true"/>
                  </do_if>
                  
                  <!-- If no explicit commander but promoted subordinate exists, check if subordinate should follow promoted one -->
                  <!-- CRITICAL: Check both commander property AND promoted subordinate's subordinates list -->
                  <!-- X4 might not have updated $subordinate.commander yet, but subordinates list is updated immediately -->
                  <do_if value="not $hasNewCommander and @$promotedSubordinate.exists">
                    <!-- Check 1: Is subordinate's commander property updated? -->
                    <do_if value="$subordinate.commander? and $subordinate.commander == $promotedSubordinate">
                      <set_value name="$newCommander" exact="$promotedSubordinate"/>
                      <set_value name="$hasNewCommander" exact="true"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-Core] Subordinate ' + $subordinate.idcode + ' has commander property updated to ' + $promotedSubordinate.idcode" chance="100"/>
                      </do_if>
                    </do_if>
                    <!-- Check 2: Is subordinate in promoted subordinate's subordinates list? (handles timing issues) -->
                    <do_if value="not $hasNewCommander and $promotedSubordinate.allsubordinates?">
                      <set_value name="$promotedSubordinates" exact="@$promotedSubordinate.allsubordinates"/>
                      <do_if value="(if $promotedSubordinates != null then $promotedSubordinates.count else 0) gt 0">
                        <do_all exact="$promotedSubordinates.count" counter="$j">
                          <do_if value="$promotedSubordinates.{$j} == $subordinate">
                            <set_value name="$newCommander" exact="$promotedSubordinate"/>
                            <set_value name="$hasNewCommander" exact="true"/>
                            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                              <debug_text text="'[GT-Core] Subordinate ' + $subordinate.idcode + ' found in promoted commander ' + $promotedSubordinate.idcode + ' subordinates list (timing workaround)'" chance="100"/>
                            </do_if>
                            <break/>
                          </do_if>
                        </do_all>
                      </do_if>
                    </do_if>
                    <!-- Debug: Log if subordinate still not found -->
                    <do_if value="not $hasNewCommander and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <set_value name="$subCommander" exact="null"/>
                      <do_if value="$subordinate.commander?">
                        <set_value name="$subCommander" exact="$subordinate.commander"/>
                      </do_if>
                      <debug_text text="'[GT-Core] Subordinate ' + $subordinate.idcode + ' not reassigned to promoted commander ' + $promotedSubordinate.idcode + ' (commander: ' + $subCommander + ', promoted has ' + (@$promotedSubordinate.allsubordinates.count) + ' subordinates)'" chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Check if new commander has GT order -->
                  <set_value name="$newCommanderHasGT" exact="false"/>
                  <do_if value="$hasNewCommander and $newCommander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$newCommander.defaultorder.id})">
                    <set_value name="$newCommanderHasGT" exact="true"/>
                  </do_if>
                  
                  <do_if value="$hasNewCommander and $newCommanderHasGT">
                    <!-- New commander exists and has GT order - subordinate continues with new commander -->
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Core] Subordinate ' + $subordinate.idcode + ' automatically reassigned to new GT commander ' + $newCommander.idcode + ' (X4 auto-promotion)'" chance="100"/>
                    </do_if>
                    
                    <!-- Update state to reflect new commander -->
                    <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
                      $Ship = $subordinate,
                      $UpdateType = 'Commander_Changed',
                      $Commander = $newCommander,
                      $CommanderHasGT = true
                    ]"/>
                  </do_if>
                  <do_else>
                    <!-- No new commander OR new commander doesn't have GT order - trigger cleanup -->
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Core] Subordinate ' + $subordinate.idcode + ' lost GT commander (destroyed) - triggering cleanup'" chance="100"/>
                    </do_if>
                    
                    <!-- Trigger cleanup -->
                    <run_actions ref="md.GT_CoreSystem.EmitShipOrderAbortedWithResolvedName">
                      <param name="ship" value="$subordinate"/>
                      <param name="pilot" value="$subordinate.pilot"/>
                      <param name="reason" value="'Commander destroyed (no new GT commander)'"/>
                    </run_actions>
                  </do_else>
                </do_else>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Periodic System Maintenance removed: migrated to event-driven triggers -->
    
    <!-- System Shutdown Handler -->
    <cue name="SystemShutdown" instantiate="true">
      <conditions>
        <event_game_saved/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Saving system state...'" chance="100"/>
        </do_if>
        
        <!-- PERFORMANCE: LastUpdate timestamp update removed -->
        <!-- LastUpdate should only be updated when ships actually do something (trade completes, registers, etc.) -->
        <!-- Periodic update made all ships appear "active" even when idle, breaking the active check -->
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] System state saved'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    <!-- Ship Registration Signal Handler - QUEUED VERSION -->
    <!-- Queues registrations to prevent stutter when assigning orders to many ships -->
    <cue name="HandleShipRegistration" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Register_Ship'" comment="Handle ship registration from AI scripts"/>
      </conditions>
      <actions>
        <set_value name="$registrationData" exact="event.param2"/>
        
        <!-- Initialize registration queue if needed -->
        <do_if value="not global.$GT_RegistrationQueue?">
          <set_value name="global.$GT_RegistrationQueue" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_RegistrationQueue.$Ships?">
          <set_value name="global.$GT_RegistrationQueue.$Ships" exact="[]"/>
        </do_if>
        <do_if value="not global.$GT_RegistrationQueue.$Processing?">
          <set_value name="global.$GT_RegistrationQueue.$Processing" exact="false"/>
        </do_if>
        
        <!-- Add to queue -->
        <append_to_list name="global.$GT_RegistrationQueue.$Ships" exact="$registrationData"/>
        
        <!-- Process queue if not already processing -->
        <do_if value="not global.$GT_RegistrationQueue.$Processing">
          <signal_cue_instantly cue="ProcessRegistrationQueue"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Process Registration Queue - Batched with delays to prevent stutter -->
    <cue name="ProcessRegistrationQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Prevent concurrent processing -->
        <do_if value="not global.$GT_RegistrationQueue.$Processing and global.$GT_RegistrationQueue.$Ships.count gt 0">
          <set_value name="global.$GT_RegistrationQueue.$Processing" exact="true"/>
          
          <!-- Process ONE ship at a time to prevent stutter -->
          <set_value name="$registrationData" exact="global.$GT_RegistrationQueue.$Ships.{1}"/>
          <remove_from_list name="global.$GT_RegistrationQueue.$Ships" exact="$registrationData"/>
          
          <set_value name="$ship" exact="$registrationData.$Ship"/>
          <set_value name="$config" exact="$registrationData.$Config"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Processing queued registration for ' + $ship.knownname + ' (queue: ' + global.$GT_RegistrationQueue.$Ships.count + ' remaining)'" chance="100"/>
          </do_if>
          
          <!-- Process this ship -->
          <do_if value="md.GT_Ship_Management.Register_Ship?">
            <run_actions ref="md.GT_Ship_Management.Register_Ship">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$ship.pilot"/>
              <param name="config" value="$config"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Ship registered using GT_Ship_Management library: ' + $ship.knownname" chance="100"/>
            </do_if>

            <!-- Restore paused training state if it was preserved during order replacement -->
            <run_actions ref="md.GT_CoreSystem.RestorePausedTrainingStateIfNeeded">
              <param name="pilot" value="$ship.pilot"/>
              <param name="debugLabel" value="'TRAINING STATE RESTORED (library path)'"/>
            </run_actions>
            
            <!-- Ensure ship name update happens (deferred to prevent stutter during registration) -->
            <!-- Register_Pilot sends GT_Update_Ship_Name signal, but we ensure it happens here too -->
            <run_actions ref="md.GT_CoreSystem.FinalizeShipRegistrationSideEffects">
              <param name="ship" value="$ship"/>
              <param name="nameRefreshReason" value="'register_ship_sync_library_path'"/>
            </run_actions>
          </do_if>
          <do_else>
            <!-- Fallback registration if library not available -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Library not available, using fallback registration for ' + $ship.knownname" chance="100"/>
            </do_if>
            
            <!-- Register ship if not already registered -->
            <run_actions ref="md.GT_CoreSystem.IsShipInRegistry" result="$shipInRegistryFallback">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="not $shipInRegistryFallback">
              <run_actions ref="md.GT_CoreSystem.EnsureShipRegistryEntry">
                <param name="ship" value="$ship"/>
              </run_actions>
              <set_value name="global.$GT_Ships.{$ship}.$RegisterTime" exact="player.age"/>
              <set_value name="global.$GT_Ships.{$ship}.$Config" exact="$config"/>
              <run_actions ref="md.GT_CoreSystem.TouchShipRegistryLastUpdate">
                <param name="ship" value="$ship"/>
              </run_actions>
              <set_value name="global.$GT_Ships.{$ship}.$Status" exact="'active'"/>
              
              <!-- Register pilot if provided and trigger ship renaming -->
              <do_if value="$ship.pilot">
                <!-- Use extracted initialization library -->
              <run_actions ref="md.GT_Ship_Management.Initialize_Pilot_Data" result="$wasNewPilot">
                <param name="pilot" value="$ship.pilot"/>
                <param name="ship" value="$ship"/>
              </run_actions>
              
              <do_if value="$wasNewPilot">
                <!-- NEW PILOT - Ship name update deferred to prevent stutter -->
                <!-- Name update handled by DeferredShipNameUpdate cue -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] XP System: NEW pilot ' + $ship.pilot.name + ' initialized with 0 XP, skill level 1 (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- EXISTING PILOT (including paused pilots) -->
                
                <!-- Check if pilot was paused and restore them -->
                <do_if value="global.$GT_Pilots.{$ship.pilot}.$Status? and global.$GT_Pilots.{$ship.pilot}.$Status == 'paused'">
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] PAUSED PILOT DETECTED: Restoring ' + $ship.pilot.name + ' with XP: ' + global.$GT_Pilots.{$ship.pilot}.$XP + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- RESTORE TRAINING STATE if it was preserved -->
                  <run_actions ref="md.GT_CoreSystem.RestorePausedTrainingStateIfNeeded">
                    <param name="pilot" value="$ship.pilot"/>
                    <param name="debugLabel" value="'TRAINING STATE RESTORED'"/>
                  </run_actions>
                  
                  <!-- Restore pilot to active status -->
                  <set_value name="global.$GT_Pilots.{$ship.pilot}.$Status" exact="'active'"/>
                  <set_value name="global.$GT_Pilots.{$ship.pilot}.$ResumedTime" exact="player.age"/>
                  <remove_value name="global.$GT_Pilots.{$ship.pilot}.$PausedTime"/>
                  <remove_value name="global.$GT_Pilots.{$ship.pilot}.$PausedReason"/>
                  
                  <!-- Update associated ship -->
                  <set_value name="global.$GT_Pilots.{$ship.pilot}.$AssociatedShip" exact="$ship"/>
                </do_if>
                
                <!-- Ensure all fields exist (defensive programming) -->
                <run_actions ref="md.GT_Ship_Management.Ensure_Pilot_Fields">
                  <param name="pilot" value="$ship.pilot"/>
                </run_actions>
                
                <!-- Store original ship name if not already stored (strip any existing GT formatting) -->
                <do_if value="not global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
                  <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$cleanedName">
                    <param name="shipName" value="$ship.knownname"/>
                  </run_actions>
                  <set_value name="global.$GT_Pilots.{$ship.pilot}.$OriginalShipName" exact="$cleanedName"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Core] Stored cleaned original ship name for existing pilot: ' + $cleanedName + ' (from: ' + $ship.knownname + ') (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- Ship name update deferred to prevent stutter -->
                <!-- Name update handled by DeferredShipNameUpdate cue -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] XP System: EXISTING pilot ' + $ship.pilot.name + ' restored with XP: ' + global.$GT_Pilots.{$ship.pilot}.$XP + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Fallback registration complete for ship: ' + $ship.knownname" chance="100"/>
            </do_if>
            
            <!-- Ensure ship name update happens (deferred to prevent stutter during registration) -->
            <run_actions ref="md.GT_CoreSystem.FinalizeShipRegistrationSideEffects">
              <param name="ship" value="$ship"/>
              <param name="nameRefreshReason" value="'register_ship_sync_fallback_path'"/>
            </run_actions>
          </do_else>
        </do_if>
        
        <!-- Signal post-processing delay (yields CPU after processing this ship) -->
        <signal_cue_instantly cue="PostRegistrationDelay"/>
      </actions>
    </cue>
    
    <!-- Post-processing delay - yields CPU after each ship registration -->
    <cue name="PostRegistrationDelay" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- 200ms delay after processing each ship (gives game CPU time to catch up) -->
      <!-- Increased from 100ms to prevent stutter when initializing large fleets -->
      <delay exact="200ms"/>
      <actions>
        <set_value name="global.$GT_RegistrationQueue.$Processing" exact="false"/>
        
        <!-- Continue processing if more ships in queue WITH DELAY to prevent stutter -->
        <do_if value="global.$GT_RegistrationQueue.$Ships.count gt 0">
          <signal_cue_instantly cue="DelayedRegistrationProcessing"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Delayed registration queue processing to prevent stuttering -->
    <cue name="DelayedRegistrationProcessing" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- 300ms delay to spread load and prevent stutter (increased from 200ms) -->
      <!-- Gives game more CPU time between registrations -->
      <!-- Higher delay = smoother but slower registration (acceptable trade-off) -->
      <!-- Total delay per ship: 300ms before + 200ms after = 500ms per ship -->
      <delay exact="300ms"/>
      <actions>
        <signal_cue_instantly cue="ProcessRegistrationQueue"/>
      </actions>
    </cue>
    
    <!-- Deferred Ship Name Update - ensures ship names are updated after registration -->
    <cue name="DeferredShipNameUpdate" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- 100ms delay to spread name update load (increased from 50ms to prevent stutter) -->
      <delay exact="100ms"/>
      <actions>
        <set_value name="$updateData" exact="event.param"/>
        <set_value name="$ship" exact="$updateData.$Ship"/>
        <set_value name="$pilot" exact="$updateData.$pilot"/>
        
        <!-- Update ship name if ship and pilot still exist -->
        <do_if value="$ship.exists and $ship.isoperational and $pilot and global.$GT_Pilots.{$pilot}?">
          <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="forceUpdate" value="true"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Deferred ship name update completed for ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Ship Order Aborted Handler with Name Restoration -->
    <cue name="HandleShipOrderAborted" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_Order_Aborted'" comment="Handle ship order abortion"/>
      </conditions>
      <actions>
        <set_value name="$abortData" exact="event.param2"/>
        <set_value name="$ship" exact="$abortData.$Ship"/>
        <set_value name="$pilot" exact="$abortData.$Pilot"/>
        <run_actions ref="md.GT_CoreSystem.BuildOrphanCheckContext" result="$context">
          <param name="ship" value="$ship"/>
          <param name="payload" value="$abortData"/>
          <param name="defaultSource" value="'UNKNOWN'"/>
          <param name="defaultTraceTag" value="'HANDLE_ABORT'"/>
        </run_actions>
        <set_value name="$cleanupSource" exact="$context.$Source"/>
        <set_value name="$cleanupTraceId" exact="$context.$TraceId"/>
        <!-- Normalize pilot source: some callers omit $Pilot even when ship still has one. -->
        <do_if value="not $pilot and $ship? and $ship.exists and $ship.pilot? and @$ship.pilot.exists">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>

        <!-- Release scheduler slots immediately when ship loses GT control (commander/subordinate revoke) -->
        <!-- Prevents "slot full" with one ship when subordinate had slot and commander was revoked -->
        <do_if value="$ship? and $ship.exists">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = $ship]"/>
        </do_if>
        <!-- Ensure $reason is always a string -->
        <!-- Default to empty string, then set from signal if present -->
        <set_value name="$reason" exact="''"/>
        <do_if value="$abortData.$Reason?">
          <set_value name="$reasonTemp" exact="$abortData.$Reason"/>
          <!-- Force string conversion by concatenating with empty string -->
          <!-- This ensures $reason is always a string type that supports indexof -->
          <do_if value="$reasonTemp?">
            <set_value name="$reason" exact="'' + $reasonTemp"/>
          </do_if>
        </do_if>
        <set_value name="$originalName" exact="$abortData.$OriginalName"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$dbgDefaultOrder" exact="'NONE'"/>
          <do_if value="$ship.defaultorder?">
            <set_value name="$dbgDefaultOrder" exact="@$ship.defaultorder.id"/>
          </do_if>
          <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=HandleShipOrderAborted ship=' + (if $ship? then $ship.idcode else 'NONE') + ' default=' + $dbgDefaultOrder + ' reason=' + $reason" chance="100"/>
        </do_if>
        
        <!-- Check if ship is a subordinate with Assist order -->
        <set_value name="$isSubordinate" exact="false"/>
        <do_if value="$ship.defaultorder?">
          <do_if value="@$ship.defaultorder.id == 'Assist'">
            <set_value name="$isSubordinate" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Check if cleanup reason is commander-related -->
        <set_value name="$isCommanderCleanup" exact="false"/>
        <!-- Check reason string - only check exact known reason strings to avoid indexof errors -->
        <!-- Known reasons that indicate commander cleanup (from various sources): -->
        <do_if value="$reason? and $reason != ''">
          <!-- Check for exact known commander-related reason strings -->
          <do_if value="$reason == 'Commander lost GT order' or $reason == 'Commander removed' or $reason == 'Commander lost GT order (Lua detection)' or $reason == 'Commander cleanup'">
            <set_value name="$isCommanderCleanup" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Handle subordinates differently when commander is cleaned up -->
        <!-- Subordinates get cleaned up (registry removal, name restoration) but keep their active orders -->
        <do_if value="$isSubordinate and $isCommanderCleanup">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Cleaning up subordinate (commander lost GT order): ' + $ship.knownname + ' (ID: ' + $ship.idcode + ') - preserving active orders'" chance="100"/>
          </do_if>
          
          <!-- Skip order cancellation - subordinates keep their active orders (trade orders continue) -->
          <!-- Only do registry cleanup and name restoration -->
          
          <!-- ============================================= -->
          <!-- SHIP NAME RESTORATION                        -->
          <!-- ============================================= -->
          
          <!-- Use extracted library function to restore original ship name -->
          <run_actions ref="md.GT_Ship_Management.Restore_Original_Ship_Name">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="originalName" value="$originalName"/>
          </run_actions>

          <!-- ============================================= -->
          <!-- SHIP MODIFICATION CLEANUP                   -->
          <!-- ============================================= -->
          
          <!-- Remove GT equipment mods BEFORE registry cleanup (needs $GT_Ships data) -->
          <!-- Remove penalty mods -->
          <do_if value="md.GT_Ship_Modifications.Remove_Penalty_Modifications?">
            <run_actions ref="md.GT_Ship_Modifications.Remove_Penalty_Modifications">
              <param name="ship" value="$ship"/>
            </run_actions>
          </do_if>
          
          <!-- Remove bonus mods (check GTInstalledSlots and call Lua) -->
          <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$GTModifications? and global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots?">
            <set_value name="$installedSlots" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots"/>
            <set_value name="$hasShipMod" exact="false"/>
            <set_value name="$hasEngineMod" exact="false"/>
            <do_all exact="$installedSlots.count" counter="$i">
              <do_if value="$installedSlots.{$i} == 'ship'">
                <set_value name="$hasShipMod" exact="true"/>
              </do_if>
              <do_if value="$installedSlots.{$i} == 'engine'">
                <set_value name="$hasEngineMod" exact="true"/>
              </do_if>
            </do_all>
            
            <do_if value="$hasShipMod">
              <set_value name="$shipIdCode" exact="@$ship.idcode"/>
              <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|null'"/>
            </do_if>
            <do_if value="$hasEngineMod">
              <set_value name="$shipIdCode" exact="@$ship.idcode"/>
              <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|null'"/>
            </do_if>
            
            <!-- Clear tracking -->
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="[]"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel" exact="0"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Removed GT equipment mods from ' + $ship.idcode + ' (ship=' + $hasShipMod + ', engine=' + $hasEngineMod + ')'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clean up legacy modification tracking -->
          <do_if value="global.$GT_Applied_Mods? and global.$GT_Applied_Mods.{$ship}?">
            <remove_value name="global.$GT_Applied_Mods.{$ship}"/>
          </do_if>
          
          <!-- ============================================= -->
          <!-- REGISTRY CLEANUP                             -->
          <!-- ============================================= -->
          
          <!-- Remove ship from GT_Ships registry -->
          <do_if value="global.$GT_Ships.{$ship}?">
            <remove_value name="global.$GT_Ships.{$ship}"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Ship removed from GT_Ships registry: ' + $ship.idcode" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- ============================================= -->
          <!-- CREDITS DUE & RESERVATIONS CLEANUP           -->
          <!-- ============================================= -->
          <!-- Always clear when removing ship from GT control â€” prevents stale trade due display
               when commander order revoked or TradePerform orders cancelled. Bookkeeping only;
               does not cancel vanilla orders. -->
          <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
            <param name="ship" value="$ship"/>
          </run_actions>
          <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- ============================================= -->
          <!-- PILOT DATA PRESERVATION (CRITICAL)            -->
          <!-- ============================================= -->
          
          <!-- CRITICAL: DO NOT remove pilot from GT_Pilots registry - preserve XP data -->
          <!-- When commander gets GT order again, subordinates will be re-registered and need their XP -->
          <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
            <!-- Mark pilot as paused/inactive but keep all XP data -->
            <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'paused'"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$PausedTime" exact="player.age"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$PausedReason" exact="'Commander lost GT order'"/>
            
            <!-- PRESERVE TRAINING STATE: Save training requirements if active -->
            <!-- Don't clear training flags - keep them so training requirement is preserved when pilot is reactivated -->
            <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded" exact="true"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$PausedBlockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] TRAINING STATE PRESERVED: Pilot ' + $pilot.name + ' was XP blocked at level ' + global.$GT_Pilots.{$pilot}.$BlockedLevel + ' - will restore training requirement'" chance="100"/>
              </do_if>
              <!-- Keep XPBlocked and BlockedLevel flags - Initialize_Pilot_Data will handle restoration -->
              <!-- Only clear TrainingInProgress since training is paused -->
              <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingInProgress"/>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Pilot marked as paused (XP preserved): ' + $pilot.name + ' - XP: ' + global.$GT_Pilots.{$pilot}.$XP + ' (will be restored when re-registered)'" chance="100"/>
            </do_if>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Ship cleanup completed for ' + $ship.idcode + ' (pilot XP preserved)'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Cleaning up ship: ' + $ship.knownname + ' (ID: ' + $ship.idcode + ') - ' + $reason" chance="100"/>
          </do_if>
          
          <!-- ============================================= -->
          <!-- ORDER CANCELLATION (only if no pilot)        -->
          <!-- ============================================= -->
          
          <!-- Determine if orders should be cancelled -->
          <!-- Trust Lua detection: if reason indicates missing pilot, cancel orders -->
          <!-- Also check if passed pilot is null or ship has no pilot -->
          <set_value name="$shouldCancelOrders" exact="false"/>
          <do_if value="not $pilot">
            <set_value name="$shouldCancelOrders" exact="true"/>
          </do_if>
          <do_elseif value="$reason? and $reason != ''">
            <!-- Root-cause guard: detached orphan cleanup must purge all active/default orders.
                 Leaving orders intact while removing GT registry can leave stale hidden trade/order state. -->
            <do_if value="$reason == 'Orphaned ship detected (decision: DETACHED_CLEANUP_REQUIRED)'">
              <set_value name="$shouldCancelOrders" exact="true"/>
            </do_if>
            <!-- Check if reason indicates missing pilot -->
            <!-- Only check exact known reason strings to avoid indexof errors -->
            <do_elseif value="$reason == 'Missing pilot (Lua detection)' or $reason == 'Missing pilot' or $reason == 'Pilot transferred away - GT order cannot run without pilot' or $reason == 'No pilot assigned'">
              <set_value name="$shouldCancelOrders" exact="true"/>
            </do_elseif>
          </do_elseif>
          <do_else>
            <!-- Double-check ship's current pilot status -->
            <!-- CRITICAL: Check if pilot is actually assigned to THIS ship, not just if pilot exists -->
            <set_value name="$hasPilot" exact="false"/>
            <do_if value="$ship.pilot?">
              <set_value name="$pilotObj" exact="@$ship.pilot"/>
              <do_if value="$pilotObj and $pilotObj.exists">
                <!-- Verify pilot is actually assigned to THIS ship (not transferred to another ship) -->
                <do_if value="$pilotObj.ship? and $pilotObj.ship == $ship">
                  <set_value name="$hasPilot" exact="true"/>
                </do_if>
              </do_if>
            </do_if>
            <do_if value="not $hasPilot">
              <set_value name="$shouldCancelOrders" exact="true"/>
            </do_if>
          </do_else>
          
          <do_if value="$shouldCancelOrders">
            <!-- No pilot => Remove everything (default order and current orders) -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] No pilot detected - cancelling all orders and removing default order: ' + $ship.knownname + ' (ID: ' + $ship.idcode + ')'" chance="100"/>
            </do_if>
            
            <!-- First: Cancel default order (stops order script from creating new orders) -->
            <do_if value="$ship.defaultorder? and @$ship.defaultorder != null">
              <cancel_order order="$ship.defaultorder"/>
            </do_if>
            
            <!-- Then: Cancel all active orders on the ship (including trade orders, etc.) -->
            <cancel_all_orders object="$ship"/>
          </do_if>
          <do_else>
            <!-- Pilot present => Only remove from registry, don't touch orders -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Ship has pilot - removing from registry only, leaving orders intact: ' + $ship.knownname + ' (ID: ' + $ship.idcode + ')'" chance="100"/>
            </do_if>
          </do_else>
          
          <!-- ============================================= -->
          <!-- SHIP NAME RESTORATION                        -->
          <!-- ============================================= -->
          
          <!-- Use extracted library function to restore original ship name -->
          <run_actions ref="md.GT_Ship_Management.Restore_Original_Ship_Name">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="originalName" value="$originalName"/>
          </run_actions>

          <!-- ============================================= -->
          <!-- SHIP MODIFICATION CLEANUP                   -->
          <!-- ============================================= -->
          
          <!-- Remove GT equipment mods BEFORE registry cleanup (needs $GT_Ships data) -->
          <!-- Remove penalty mods -->
          <do_if value="md.GT_Ship_Modifications.Remove_Penalty_Modifications?">
            <run_actions ref="md.GT_Ship_Modifications.Remove_Penalty_Modifications">
              <param name="ship" value="$ship"/>
            </run_actions>
          </do_if>
          
          <!-- Remove bonus mods (check GTInstalledSlots and call Lua) -->
          <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$GTModifications? and global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots?">
            <set_value name="$installedSlots" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots"/>
            <set_value name="$hasShipMod" exact="false"/>
            <set_value name="$hasEngineMod" exact="false"/>
            <do_all exact="$installedSlots.count" counter="$i">
              <do_if value="$installedSlots.{$i} == 'ship'">
                <set_value name="$hasShipMod" exact="true"/>
              </do_if>
              <do_if value="$installedSlots.{$i} == 'engine'">
                <set_value name="$hasEngineMod" exact="true"/>
              </do_if>
            </do_all>
            
            <do_if value="$hasShipMod">
              <set_value name="$shipIdCode" exact="@$ship.idcode"/>
              <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|null'"/>
            </do_if>
            <do_if value="$hasEngineMod">
              <set_value name="$shipIdCode" exact="@$ship.idcode"/>
              <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|null'"/>
            </do_if>
            
            <!-- Clear tracking -->
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="[]"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel" exact="0"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Removed GT equipment mods from ' + $ship.idcode + ' (ship=' + $hasShipMod + ', engine=' + $hasEngineMod + ')'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clean up legacy modification tracking -->
          <do_if value="global.$GT_Applied_Mods? and global.$GT_Applied_Mods.{$ship}?">
            <remove_value name="global.$GT_Applied_Mods.{$ship}"/>
          </do_if>
          
          <!-- ============================================= -->
          <!-- SEARCH STATE CLEANUP                         -->
          <!-- ============================================= -->
          
          <!-- Phase 3: Use comprehensive cleanup function (includes reservations, work items, scheduler state) -->
          <!-- Always clear for all ships being removed from GT control (including subordinates).
               Prevents stale trade due display when commander revoked + trade orders cancelled. -->
          <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
            <param name="ship" value="$ship"/>
          </run_actions>
          <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Remove from pathfinding queue if present -->
          <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$ActiveShips?">
            <do_all exact="global.$GT_PathfindingQueue.$ActiveShips.count" counter="$i" reverse="true">
              <do_if value="global.$GT_PathfindingQueue.$ActiveShips.{$i} == $ship">
                <remove_from_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="$ship"/>
                <!-- Decrement active instances if ship was active -->
                <do_if value="global.$GT_PathfindingQueue.$ActiveInstances? and global.$GT_PathfindingQueue.$ActiveInstances gt 0">
                  <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="subtract"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Remove from pathfinding request queue if present -->
          <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$Requests?">
            <do_all exact="global.$GT_PathfindingQueue.$Requests.count" counter="$i" reverse="true">
              <set_value name="$request" exact="global.$GT_PathfindingQueue.$Requests.{$i}"/>
              <do_if value="$request.$Ship? and $request.$Ship == $ship">
                <remove_from_list name="global.$GT_PathfindingQueue.$Requests" exact="$request"/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Legacy batch processor cleanup removed in AI migration -->
          
          <!-- LiveSearchQueue removed (hub finalization): remove ship from home-refresh waiters if present -->
          <do_if value="global.$GT_TS_LiveRefreshBySector? and global.$GT_TS_LiveRefreshBySector.keys.count gt 0">
            <do_all exact="global.$GT_TS_LiveRefreshBySector.keys.count" counter="$hsIdx">
              <set_value name="$hs" exact="global.$GT_TS_LiveRefreshBySector.keys.{$hsIdx}"/>
              <do_if value="$hs? and global.$GT_TS_LiveRefreshBySector.{$hs}?">
                <do_if value="global.$GT_TS_LiveRefreshBySector.{$hs}.$WaiterQueued? and global.$GT_TS_LiveRefreshBySector.{$hs}.$WaiterQueued.{$ship}?">
                  <remove_value name="global.$GT_TS_LiveRefreshBySector.{$hs}.$WaiterQueued.{$ship}"/>
                </do_if>
                <do_if value="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters? and global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters.count gt 0">
                  <do_all exact="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters.count" counter="$wi" reverse="true">
                    <set_value name="$w" exact="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters.{$wi}"/>
                    <do_if value="$w? and $w.$Ship? and $w.$Ship == $ship">
                      <remove_from_list name="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters" exact="$w"/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Clear search results -->
          <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{$ship}?">
            <remove_value name="global.$GT_SearchResult.{$ship}"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Cleared search results for ' + $ship.idcode" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clear fallback flags -->
          <do_if value="global.$GT_FallbackAttempted? and global.$GT_FallbackAttempted.{$ship}?">
            <remove_value name="global.$GT_FallbackAttempted.{$ship}"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Cleared fallback attempted flag for ' + $ship.idcode" chance="100"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_FallbackLogbookWritten? and global.$GT_FallbackLogbookWritten.{$ship}?">
            <remove_value name="global.$GT_FallbackLogbookWritten.{$ship}"/>
          </do_if>
          
          <!-- ============================================= -->
          <!-- REGISTRY CLEANUP                             -->
          <!-- ============================================= -->
          
          <!-- Remove ship from GT_Ships registry -->
          <do_if value="global.$GT_Ships.{$ship}?">
            <remove_value name="global.$GT_Ships.{$ship}"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Ship removed from GT_Ships registry: ' + $ship.idcode" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- ============================================= -->
          <!-- PILOT DATA PRESERVATION                       -->
          <!-- ============================================= -->
          
          <!-- Preserve pilot XP data - NEVER remove pilots from registry -->
          <!-- Instead, mark them as paused/inactive so they can be reactivated later with their XP intact -->
          <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
            <set_value name="$pilotHasOtherShips" exact="false"/>
            
            <!-- Check if pilot has other active GalaxyTrader ships -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
              <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
              <do_all exact="$shipKeys.count" counter="$i">
                <set_value name="$otherShip" exact="$shipKeys.{$i}"/>
                <do_if value="$otherShip? and $otherShip.exists and $otherShip.pilot == $pilot">
                  <set_value name="$pilotHasOtherShips" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            
            <!-- Mark pilot as paused instead of removing from registry -->
            <!-- This preserves XP, skill level, trades, profit, and all training data -->
            <do_if value="not $pilotHasOtherShips">
              <!-- No other active ships - mark pilot as paused to preserve all data -->
              <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'paused'"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$PausedTime" exact="player.age"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$PausedReason" exact="'Order aborted - preserving XP data for reactivation'"/>
              <!-- Clear ship association since order is aborted -->
              <remove_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$Ship"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Pilot paused (preserving XP data): ' + $pilot.name + ' (XP: ' + global.$GT_Pilots.{$pilot}.$XP + ', Level: ' + (if global.$GT_Pilots.{$pilot}.$Level? then global.$GT_Pilots.{$pilot}.$Level else 1) + ')'" chance="100"/>
              </do_if>
              
              <!-- Send logbook message thanking player for holiday -->
              <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
              <set_value name="$logbookMessage" exact="{77000,3215}.[player.name]"/>
              
              <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                <param name="Message" value="$logbookMessage"/>
                <param name="Category" value="'general'"/>
                <param name="Title" value="'Pilot Status: ' + $pilot.name"/>
                <param name="Object" value="$ship"/>
                <param name="Interaction" value="'showonmap'"/>
              </run_actions>
            </do_if>
            <do_else>
              <!-- Pilot has other active ships - keep them active -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Pilot kept active (has other active ships): ' + $pilot.name" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          
          <!-- Update ship status (legacy compatibility) -->
          <do_if value="md.GT_Ship_Management.Update_Ship_Status?">
            <run_actions ref="md.GT_Ship_Management.Update_Ship_Status">
              <param name="ship" value="$ship"/>
              <param name="status" value="'aborted'"/>
            </run_actions>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Ship cleanup completed for ' + $ship.idcode" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>

    <!-- Ship Order Paused Handler with XP Preservation -->
    <cue name="HandleShipOrderPaused" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_Order_Paused'" comment="Handle ship order pause (preserve XP)"/>
      </conditions>
      <actions>
        <set_value name="$pauseData" exact="event.param2"/>
        <set_value name="$ship" exact="$pauseData.$Ship"/>
        <set_value name="$pilot" exact="$pauseData.$Pilot"/>
        <set_value name="$reason" exact="$pauseData.$Reason"/>
        <set_value name="$preserveData" exact="$pauseData.$PreserveData"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ship order paused for ' + $ship.knownname + ': ' + $reason + ' (preserving XP: ' + $preserveData + ')'" chance="100"/>
        </do_if>
        
        <!-- ============================================= -->
        <!-- SHIP NAME PRESERVATION (DO NOT RESTORE)      -->
        <!-- ============================================= -->
        <!-- NOTE: When pausing (not aborting), we KEEP the current ship name with rank/level/XP.
             Name restoration to original only happens on permanent order removal (HandleShipOrderAborted).
             This preserves the player's view of their pilot's progression even during order changes. -->
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ship name PRESERVED during pause: ' + $ship.knownname + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
        </do_if>
        
        <!-- ============================================= -->
        <!-- SHIP MODIFICATION CLEANUP (PAUSE)           -->
        <!-- ============================================= -->
        
        <!-- Clean up any ship modification tracking -->
        <do_if value="global.$GT_Applied_Mods? and global.$GT_Applied_Mods.{$ship}?">
          <remove_value name="global.$GT_Applied_Mods.{$ship}"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Ship modification tracking cleared for ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- ============================================= -->
        <!-- SELECTIVE REGISTRY CLEANUP (PRESERVE XP)    -->
        <!-- ============================================= -->
        
        <!-- Remove transient ship data but preserve OriginalShipName as stable rename base -->
        <do_if value="global.$GT_Ships.{$ship}?">
          <set_value name="$preservedOriginalShipName" exact="null"/>
          <do_if value="global.$GT_Ships.{$ship}.$OriginalShipName? and global.$GT_Ships.{$ship}.$OriginalShipName != ''">
            <set_value name="$preservedOriginalShipName" exact="global.$GT_Ships.{$ship}.$OriginalShipName"/>
          </do_if>
          <remove_value name="global.$GT_Ships.{$ship}"/>
          <do_if value="$preservedOriginalShipName? and $preservedOriginalShipName != null and $preservedOriginalShipName != ''">
            <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
            <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$preservedOriginalShipName"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Ship registry cleaned for pause: ' + $ship.idcode + ' (preserved OriginalShipName=' + (if $preservedOriginalShipName? and $preservedOriginalShipName != null and $preservedOriginalShipName != '' then 'yes' else 'no') + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- CRITICAL: DO NOT remove pilot from GT_Pilots registry - preserve XP data -->
        <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
          <!-- Mark pilot as temporarily inactive but keep all XP data -->
          <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'paused'"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$PausedTime" exact="player.age"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$PausedReason" exact="$reason"/>
          
          <!-- PRESERVE TRAINING STATE: Save training requirements if active -->
          <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
            <set_value name="global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded" exact="true"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$PausedBlockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] TRAINING STATE PRESERVED: Pilot ' + $pilot.name + ' was XP blocked at level ' + global.$GT_Pilots.{$pilot}.$BlockedLevel + ' - will restore training requirement'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Clear active training flags (but preserve paused state) -->
          <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingInProgress"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Pilot marked as paused (XP preserved): ' + $pilot.name + ' - XP: ' + global.$GT_Pilots.{$pilot}.$XP" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ship pause completed for ' + $ship.idcode + ' (pilot XP data preserved)'" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- Ship Pilot Change Monitor removed -->
    <!-- Polling monitor has been removed. Order removal is now detected instantly via signal from AI script's <on_abort> handler. -->
    <!-- This provides instant response (0ms latency) and zero CPU overhead. Professional code doesn't crash - we trust the signal system. -->

    <!-- Event-Driven Orphaned Ship Check - Checks a single ship when triggered -->
    <!-- This replaces polling-based cleanup with event-driven checks -->
    <!-- Triggered from: GT_Update_Ship (pilot_change), GT_Ship_State_Update (GT_Order_Cancelled), Wait/Assist orders, GT order on_abort -->
    <cue name="CheckShipOrphaned" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Check_Ship_Orphaned'"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <run_actions ref="md.GT_CoreSystem.BuildOrphanCheckContext" result="$context">
          <param name="ship" value="$ship"/>
          <param name="payload" value="event.param2"/>
          <param name="defaultSource" value="'UNKNOWN'"/>
          <param name="defaultTraceTag" value="'CHECK_ORPHANED'"/>
        </run_actions>
        <set_value name="$force" exact="$context.$Force"/>
        <set_value name="$cleanupSource" exact="$context.$Source"/>
        <set_value name="$cleanupTraceId" exact="$context.$TraceId"/>
        
        <!-- Skip if ship doesn't exist -->
        <do_if value="not $ship.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=NONE action=FILTERED_SHIP_NOT_EXISTS'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Check if ship is in registry -->
          <run_actions ref="md.GT_CoreSystem.IsShipInRegistry" result="$shipInRegistry">
            <param name="ship" value="$ship"/>
          </run_actions>
          <!-- Pilot registry link survives some detach races after GT_Ships cleanup. -->
          <set_value name="$pilotRegistryLinked" exact="false"/>
          <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
            <set_value name="$pilotData" exact="global.$GT_Pilots.{$ship.pilot}"/>
            <do_if value="($pilotData.$Ship? and $pilotData.$Ship == $ship) or ($pilotData.$AssociatedShip? and $pilotData.$AssociatedShip == $ship) or ($pilotData.$ShipID? and $pilotData.$ShipID == $ship.idcode)">
              <set_value name="$pilotRegistryLinked" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Active GT order rescue:
               if registry entries are missing but the ship still has an active GT order,
               re-register it instead of filtering out cleanup checks. -->
          <set_value name="$activeGTOrderNoRegistry" exact="false"/>
          <do_if value="$ship.defaultorder? and ((@$ship.defaultorder.id == 'GalaxyTraderMK4Supply' or @$ship.defaultorder.id == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})) or (@$ship.defaultorder.id == 'Assist' and $ship.defaultorder.$baseorder? and (@$ship.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @$ship.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.$baseorder.id}))) )">
            <set_value name="$activeGTOrderNoRegistry" exact="true"/>
          </do_if>
          
          <!-- Only filter cleanup when we have no reliable GT history AND no active GT order. -->
          <do_if value="not $shipInRegistry and not $pilotRegistryLinked and not $activeGTOrderNoRegistry">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=' + $ship.idcode + ' action=FILTERED_NOT_IN_REGISTRY'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="not $shipInRegistry and not $pilotRegistryLinked and $activeGTOrderNoRegistry">
              <signal_objects object="player.galaxy" param="'GT_Register_Ship'" param2="table[
                $Ship = $ship,
                $Config = table[]
              ]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$dbgActiveDefaultOrder" exact="'NONE'"/>
                <do_if value="$ship.defaultorder?">
                  <set_value name="$dbgActiveDefaultOrder" exact="@$ship.defaultorder.id"/>
                </do_if>
                <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=' + $ship.idcode + ' action=RECOVERY_REREGISTER_ACTIVE_GT default=' + $dbgActiveDefaultOrder" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Ship is in registry, pilot-linked, or has active GT order - continue with orphaned check -->
            
            <!-- PROMOTION / TRANSITION GUARD:
                 During commander destruction + promotion, ships can briefly have no default order.
                 Do NOT purge registry on the first observation; schedule a delayed verify once. -->
            <set_value name="$exitEarly" exact="false"/>
            <set_value name="$defaultOrderId" exact="@$ship.defaultorder.id"/>
            <set_value name="$commander" exact="@$ship.commander"/>
            <set_value name="$commanderExists" exact="false"/>
            <set_value name="$commanderDefaultNull" exact="false"/>
            <do_if value="$commander? and $commander.exists and $commander != $ship">
              <set_value name="$commanderExists" exact="true"/>
              <!-- Commander exists but has no default order yet (promotion window) -->
              <do_if value="(not @$commander.defaultorder) or (@$commander.defaultorder == null)">
                <set_value name="$commanderDefaultNull" exact="true"/>
              </do_if>
            </do_if>
            
            <!-- Defer cleanup only for real transition windows:
                 - ship has no default order id yet, OR
                 - commander exists but default order is null (promotion window), OR
                 - ship is still on Assist while commander link is temporarily missing (promotion handoff)
                 A detached ship on Wait with no commander is stable and should be processed. -->
            <do_if value="not $force and ((not $defaultOrderId or $defaultOrderId == null) or $commanderDefaultNull or ($defaultOrderId == 'Assist' and not $commanderExists))">
              <set_value name="$exitEarly" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=' + $ship.idcode + ' action=FILTERED_PROMOTION_WINDOW default=' + (if $defaultOrderId then $defaultOrderId else 'NONE') + ' commanderExists=' + $commanderExists + ' commanderDefaultNull=' + $commanderDefaultNull + ' force=' + $force" chance="100"/>
              </do_if>
              <do_if value="not global.$GT_OrphanVerifyPending? or not global.$GT_OrphanVerifyPending.{$ship}?">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Cleanup] Deferring orphan cleanup (promotion window): ' + $ship.idcode + ' (defaultOrder=' + (if $defaultOrderId then $defaultOrderId else 'null') + ', commanderExists=' + $commanderExists + ', commanderDefaultNull=' + $commanderDefaultNull + ')'" chance="100"/>
                </do_if>
              </do_if>
              <run_actions ref="md.GT_CoreSystem.QueueOrphanVerifyIfNotPending">
                <param name="ship" value="$ship"/>
                <param name="source" value="$cleanupSource"/>
                <param name="traceId" value="$cleanupTraceId"/>
              </run_actions>
            </do_if>
            
            <do_if value="not $exitEarly">
        
        <!-- Unified cleanup decision engine -->
        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
          <param name="ship" value="$ship"/>
          <param name="checkRegistry" value="true"/>
          <param name="checkState" value="true"/>
        </run_actions>
        
        <set_value name="$cleanupDecision" exact="'NO_ACTION'"/>
        <do_if value="$gtStatus.$IsGTControlled">
          <set_value name="$cleanupDecision" exact="'KEEP_GT_CONTROLLED'"/>
        </do_if>
        <do_elseif value="$gtStatus.$ShouldCleanup">
          <set_value name="$cleanupDecision" exact="'DETACHED_CLEANUP_REQUIRED'"/>
        </do_elseif>
        <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist'">
          <set_value name="$cleanupDecision" exact="'TRANSIENT_RECHECK_REQUIRED'"/>
        </do_elseif>
        
        <!-- Detach intent handling:
             producer-side snapshots (on_abort/wait) can be ahead of commander/default-order reflection.
             Keep intent active during grace window, then force detach if still unresolved. -->
        <set_value name="$intentActive" exact="false"/>
        <set_value name="$intentExpired" exact="false"/>
        <set_value name="$intentSource" exact="'NONE'"/>
        <set_value name="$intentTraceId" exact="'NONE'"/>
        <do_if value="global.$GT_CleanupIntent? and global.$GT_CleanupIntent.{$ship}?">
          <set_value name="$intent" exact="global.$GT_CleanupIntent.{$ship}"/>
          <do_if value="$intent.$Active? and $intent.$Active">
            <set_value name="$intentActive" exact="true"/>
          </do_if>
          <do_if value="$intent.$Source?">
            <set_value name="$intentSource" exact="$intent.$Source"/>
          </do_if>
          <do_if value="$intent.$TraceId?">
            <set_value name="$intentTraceId" exact="$intent.$TraceId"/>
          </do_if>
          <do_if value="$intent.$ExpireTime? and player.age ge $intent.$ExpireTime">
            <set_value name="$intentExpired" exact="true"/>
          </do_if>
        </do_if>
        
        <do_if value="$intentActive">
          <!-- Strong re-control signal: direct GT order means intent is obsolete. -->
          <do_if value="$gtStatus.$HasDirectGTOrder">
            <remove_value name="global.$GT_CleanupIntent.{$ship}"/>
            <set_value name="$intentActive" exact="false"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=' + $ship.idcode + ' intent=CLEARED_DIRECT_GT'" chance="100"/>
            </do_if>
          </do_if>
          <do_elseif value="$intentExpired and $cleanupDecision != 'DETACHED_CLEANUP_REQUIRED'">
            <!-- Expired intent:
                 - Force detach only if GT control is truly missing now.
                 - If still subordinate to GT commander (Assist + hasGTCommander), intent was stale/noise -> clear it. -->
            <do_if value="(not $gtStatus.$IsGTControlled) or (not $ship.defaultorder?) or (@$ship.defaultorder.id != 'Assist') or (not $gtStatus.$HasGTCommander)">
              <set_value name="$cleanupDecision" exact="'DETACHED_CLEANUP_REQUIRED'"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_CleanupIntent.{$ship}"/>
              <set_value name="$intentActive" exact="false"/>
              <set_value name="$cleanupDecision" exact="'KEEP_GT_CONTROLLED'"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=' + $ship.idcode + ' intent=EXPIRED_BUT_STILL_SUBORDINATE -> CLEARED'" chance="100"/>
              </do_if>
            </do_else>
          </do_elseif>
          <do_elseif value="$cleanupDecision == 'KEEP_GT_CONTROLLED'">
            <!-- During grace window, treat as transitional and re-check instead of accepting stale keep-controlled state. -->
            <set_value name="$cleanupDecision" exact="'TRANSIENT_RECHECK_REQUIRED'"/>
          </do_elseif>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$dbgCommanderId" exact="'NONE'"/>
          <set_value name="$dbgCommanderOrder" exact="'NONE'"/>
          <do_if value="$gtStatus.$Commander? and $gtStatus.$Commander.exists">
            <set_value name="$dbgCommanderId" exact="@$gtStatus.$Commander.idcode"/>
            <do_if value="$gtStatus.$Commander.defaultorder?">
              <set_value name="$dbgCommanderOrder" exact="@$gtStatus.$Commander.defaultorder.id"/>
            </do_if>
          </do_if>
          <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=CheckShipOrphaned ship=' + $ship.idcode + ' force=' + $force + ' inRegistry=' + $shipInRegistry + ' default=' + @$ship.defaultorder.id + ' commander=' + $dbgCommanderId + ' commanderOrder=' + $dbgCommanderOrder + ' intentActive=' + $intentActive + ' intentExpired=' + $intentExpired + ' intentSource=' + $intentSource + ' intentTrace=' + $intentTraceId" chance="100"/>
          <debug_text text="'[GT-Cleanup] Decision=' + $cleanupDecision + ' ship=' + $ship.idcode + ' default=' + @$ship.defaultorder.id + ' commander=' + $dbgCommanderId + ' commanderOrder=' + $dbgCommanderOrder + ' hasDirect=' + $gtStatus.$HasDirectGTOrder + ' hasGTCommander=' + $gtStatus.$HasGTCommander + ' inRegistry=' + $gtStatus.$InRegistry" chance="100"/>
        </do_if>
        
        <do_if value="$cleanupDecision == 'DETACHED_CLEANUP_REQUIRED'">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Cleaning up detached ship: ' + $ship.knownname + ' (ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
          
          <!-- Get original ship name from shared cleanup resolver. -->
          <run_actions ref="md.GT_CoreSystem.GetOriginalShipNameForCleanup" result="$originalName">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Idempotency guard: suppress duplicate detached-cleanup signals per ship/time bucket -->
          <set_value name="$cleanupSignalType" exact="'DETACHED_CLEANUP_REQUIRED'"/>
          <set_value name="$cleanupTokenBucket" exact="(player.age / 1s)i"/>
          <set_value name="$cleanupToken" exact="$cleanupSignalType + '|' + $cleanupTokenBucket"/>
          <do_if value="not global.$GT_CleanupSignalState?">
            <set_value name="global.$GT_CleanupSignalState" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_CleanupSignalState.{$ship}?">
            <set_value name="global.$GT_CleanupSignalState.{$ship}" exact="table[
              $LastCleanupToken = '',
              $LastCleanupTime = 0s
            ]"/>
          </do_if>
          <set_value name="$signalState" exact="global.$GT_CleanupSignalState.{$ship}"/>
          <do_if value="not $signalState.$LastCleanupToken? or $signalState.$LastCleanupToken != $cleanupToken">
            <set_value name="$signalState.$LastCleanupToken" exact="$cleanupToken"/>
            <set_value name="$signalState.$LastCleanupTime" exact="player.age"/>
            <!-- Send cleanup signal (reuses existing HandleShipOrderAborted logic) -->
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = $ship,
              $Pilot = $ship.pilot,
              $Reason = 'Orphaned ship detected (decision: ' + $cleanupDecision + ')',
              $OriginalName = $originalName,
              $Source = 'CHECK_SHIP_ORPHANED',
              $TraceId = $cleanupTraceId
            ]"/>
            <do_if value="global.$GT_CleanupIntent? and global.$GT_CleanupIntent.{$ship}?">
              <remove_value name="global.$GT_CleanupIntent.{$ship}"/>
            </do_if>
          </do_if>
          <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Duplicate cleanup signal suppressed for ' + $ship.idcode + ' token=' + $cleanupToken" chance="100"/>
          </do_elseif>
        </do_if>
        <do_elseif value="$cleanupDecision == 'TRANSIENT_RECHECK_REQUIRED'">
          <!-- Schedule forced re-check while detach intent is active. -->
          <run_actions ref="md.GT_CoreSystem.QueueOrphanVerifyIfNotPending">
            <param name="ship" value="$ship"/>
            <param name="source" value="$cleanupSource"/>
            <param name="traceId" value="$cleanupTraceId"/>
          </run_actions>
        </do_elseif>
        
        <!-- Check for missing pilot (ship has GT order but no pilot) -->
        <do_elseif value="$gtStatus.$IsGTControlled and not $ship.pilot?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Cleaning up ship without pilot: ' + $ship.knownname + ' (ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
          
          <!-- Set default order to Wait (hold position) before cleanup -->
          <do_if value="$ship.defaultorder?">
            <create_order id="'Wait'" object="$ship" default="true">
              <param name="allowdocked" value="true"/>
              <param name="holdfire" value="false"/>
              <param name="noattackresponse" value="false"/>
            </create_order>
          </do_if>
          
          <!-- Get original ship name from ship registry -->
          <run_actions ref="md.GT_CoreSystem.GetShipRegistryOriginalName" result="$originalName">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Send cleanup signal -->
          <run_actions ref="md.GT_CoreSystem.EmitShipOrderAborted">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="null"/>
            <param name="reason" value="'Pilot transferred away - GT order cannot run without pilot (event-driven check)'"/>
            <param name="originalName" value="$originalName"/>
          </run_actions>
        </do_elseif>
        
            </do_if>
          </do_else>
        </do_else>
      </actions>
    </cue>
    
    <!-- Delayed verify for transient "no default order" states (promotion window). -->
    <cue name="VerifyShipOrphaned" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.VerifyShipOrphaned"/>
      </conditions>
      <delay exact="3s"/>
      <actions>
        <set_value name="$ship" exact="event.param.$Ship"/>
        <run_actions ref="md.GT_CoreSystem.BuildOrphanCheckContext" result="$context">
          <param name="ship" value="$ship"/>
          <param name="payload" value="event.param"/>
          <param name="defaultSource" value="'VERIFY_ORPHANED'"/>
          <param name="defaultTraceTag" value="'VERIFY_ORPHANED'"/>
        </run_actions>
        <set_value name="$cleanupSource" exact="$context.$Source"/>
        <set_value name="$cleanupTraceId" exact="$context.$TraceId"/>
        <do_if value="$ship? and $ship.exists">
          <do_if value="global.$GT_OrphanVerifyPending? and global.$GT_OrphanVerifyPending.{$ship}?">
            <remove_value name="global.$GT_OrphanVerifyPending.{$ship}"/>
          </do_if>
          <run_actions ref="md.GT_CoreSystem.QueueCheckShipOrphanedDetailed">
            <param name="ship" value="$ship"/>
            <param name="force" value="true"/>
            <param name="source" value="$cleanupSource"/>
            <param name="traceId" value="$cleanupTraceId"/>
          </run_actions>
        </do_if>
      </actions>
    </cue>
    
    <!-- Savegame Compatibility: Migrate Original Ship Names from Pilot Registry to Ship Registry -->
    <!-- This migration runs once per savegame to move OriginalShipName from pilot to ship registry -->
    <cue name="MigrateOriginalShipNames" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_player_created/>
          <event_game_loaded/>
        </check_any>
        <check_value value="global.$GT_Initialized and not global.$GT_OriginalShipNamesMigrated?"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] Starting migration: Original ship names from pilot to ship registry...'" chance="100"/>
        </do_if>
        
        <!-- Initialize ship registry if needed -->
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        
        <set_value name="$migratedCount" exact="0"/>
        <set_value name="$skippedCount" exact="0"/>
        
        <!-- Iterate through all pilots -->
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$i">
            <set_value name="$pilot" exact="$pilotKeys.{$i}"/>
            <set_value name="$pilotData" exact="global.$GT_Pilots.{$pilot}"/>
            
            <!-- Check if pilot has OriginalShipName and associated ship -->
            <do_if value="$pilotData.$OriginalShipName? and $pilotData.$Ship? and $pilotData.$Ship.exists">
              <set_value name="$ship" exact="$pilotData.$Ship"/>
              
              <!-- Initialize ship registry entry if needed -->
              <run_actions ref="md.GT_CoreSystem.EnsureShipRegistryEntry">
                <param name="ship" value="$ship"/>
              </run_actions>
              
              <!-- Migrate OriginalShipName to ship registry (only if not already set) -->
              <!-- Note: If pilot was transferred, their OriginalShipName might be for old ship -->
              <!-- But we migrate to current ship - Register_Pilot will handle old ship cleanup -->
              <do_if value="not global.$GT_Ships.{$ship}.$OriginalShipName?">
                <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$pilotData.$OriginalShipName"/>
                <set_value name="$migratedCount" operation="add"/>
                
                <!-- <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Core] Migrated original name for ship ' + $ship.knownname + ' (ID: ' + $ship.idcode + ') from pilot ' + $pilot.name + ': ' + $pilotData.$OriginalShipName" chance="100"/>
                </do_if> -->
              </do_if>
              <do_else>
                <!-- Ship already has OriginalShipName - skip migration -->
                <set_value name="$skippedCount" operation="add"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Core] Skipped migration for ship ' + $ship.knownname + ' - already has OriginalShipName: ' + global.$GT_Ships.{$ship}.$OriginalShipName" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Mark migration as complete -->
        <set_value name="global.$GT_OriginalShipNamesMigrated" exact="true"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] Migration complete: ' + $migratedCount + ' ship names migrated, ' + $skippedCount + ' skipped (already in ship registry)'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Polling-based cleanup removed - now using event-driven checks -->
    <!-- Orphaned ships are checked when:
         - Pilot is transferred (GT_Update_Ship with pilot_change) checks old ship
         - GT order is canceled (GT_Ship_State_Update with GT_Order_Cancelled) checks ship
         - Wait/Assist orders detect GT order removal checks ship
    -->
    
    <!-- Handler for GT_Ship_State_Update - Triggers orphaned check when GT order is cancelled -->
    <cue name="HandleShipStateUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_State_Update'"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$updateType" exact="@$params.$UpdateType"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        
        <!-- Trigger orphaned check when GT order is cancelled -->
        <do_if value="$updateType == 'GT_Order_Cancelled' and $ship.exists">
          <run_actions ref="md.GT_CoreSystem.IsShipInRegistry" result="$shipInRegistry">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$shipInRegistry">
            <run_actions ref="md.GT_CoreSystem.QueueCheckShipOrphaned">
              <param name="ship" value="$ship"/>
            </run_actions>
          </do_if>
          
          <!-- EVENT-DRIVEN: Defer subordinate cleanup verification to avoid transient false positives
               during commander order transitions (e.g. promotion/station-assignment handover). -->
          <run_actions ref="md.GT_CoreSystem.QueueVerifyCommanderSubordinateCleanup">
            <param name="commander" value="$ship"/>
          </run_actions>
        </do_if>
      </actions>
    </cue>

    <!-- Verify commander-lost-GT cleanup after a short delay.
         This prevents subordinate purge when commander order state is transiently inconsistent. -->
    <cue name="VerifyCommanderSubordinateCleanup" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.VerifyCommanderSubordinateCleanup"/>
      </conditions>
      <delay exact="3s"/>
      <actions>
        <set_value name="$commander" exact="event.param.$Commander"/>
        <do_if value="$commander? and $commander.exists">
          <set_value name="$commanderHasGTNow" exact="false"/>
          <set_value name="$commanderDefaultOrderNull" exact="false"/>
          <do_if value="$commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$commander.defaultorder.id})">
            <set_value name="$commanderHasGTNow" exact="true"/>
          </do_if>
          <do_elseif value="(not @$commander.defaultorder) or (@$commander.defaultorder == null)">
            <set_value name="$commanderDefaultOrderNull" exact="true"/>
          </do_elseif>

          <!-- If still GT-controlled (or in null-order transition), skip subordinate cleanup. -->
          <do_if value="$commanderHasGTNow or $commanderDefaultOrderNull">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Skipping subordinate cleanup for commander ' + $commander.idcode + ' after verify (hasGT=' + $commanderHasGTNow + ', defaultOrderNull=' + $commanderDefaultOrderNull + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Engine hierarchy source of truth: walk commander's subordinate tree -->
            <set_value name="$subordinates" exact="[]"/>
            <do_if value="$commander.allsubordinates? and @$commander.allsubordinates.count gt 0">
              <set_value name="$subordinates" exact="@$commander.allsubordinates"/>
            </do_if>
            <do_elseif value="$commander.subordinates? and @$commander.subordinates.count gt 0">
              <set_value name="$subordinates" exact="@$commander.subordinates"/>
            </do_elseif>
            
            <do_all exact="$subordinates.count" counter="$i">
              <set_value name="$potentialSubordinate" exact="$subordinates.{$i}"/>
              <do_if value="$potentialSubordinate? and $potentialSubordinate.exists and $potentialSubordinate.isplayerowned">
                <!-- Safety: do not purge ships that now have direct GT orders. -->
                <set_value name="$subHasDirectGT" exact="false"/>
                <do_if value="$potentialSubordinate.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$potentialSubordinate.defaultorder.id})">
                  <set_value name="$subHasDirectGT" exact="true"/>
                </do_if>
                <do_if value="not $subHasDirectGT">
                  <run_actions ref="md.GT_CoreSystem.EmitShipOrderAbortedWithResolvedName">
                    <param name="ship" value="$potentialSubordinate"/>
                    <param name="pilot" value="$potentialSubordinate.pilot"/>
                    <param name="reason" value="'Commander lost GT order'"/>
                  </run_actions>
                </do_if>
              </do_if>
            </do_all>
          </do_else>
        </do_if>
      </actions>
    </cue>

    <!-- One-Time Legacy Ship Name Fix (for ships active before fixes were applied) -->
    <cue name="LegacyShipNameFix" instantiate="true" version="1">
      <conditions>
        <event_game_loaded/>
        <check_value value="global.$GT_Initialized and not global.$GT_LegacyShipNamesFixed?"/>
      </conditions>
      <actions>
        <!-- Mark as fixed so this only runs once -->
        <set_value name="global.$GT_LegacyShipNamesFixed" exact="true"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Running one-time legacy ship name fix...'" chance="100"/>
        </do_if>
        
        <set_value name="$fixedCount" exact="0"/>
        <set_value name="$skippedCount" exact="0"/>
        
        <!-- Check all registered GT ships -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            
            <!-- Skip if ship no longer exists -->
            <do_if value="not $ship.exists or not $ship.isoperational or not $ship.pilot">
              <continue/>
            </do_if>
            
            <!-- Check if pilot exists in registry -->
            <do_if value="global.$GT_Pilots.{$ship.pilot}?">
              <set_value name="$pilotData" exact="global.$GT_Pilots.{$ship.pilot}"/>
              
              <!-- Check if ship needs name update - ONLY if name is EXACTLY the original base name -->
              <set_value name="$needsUpdate" exact="false"/>
              
              <!-- Ship needs update if it has the exact original name (no rank/level/XP added yet) -->
              <do_if value="$pilotData.$OriginalShipName? and $ship.knownname == $pilotData.$OriginalShipName and $pilotData.$XP? and $pilotData.$XP gt 0">
                <set_value name="$needsUpdate" exact="true"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Legacy] Ship ' + $ship.idcode + ' needs update: name matches original exactly'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <set_value name="$skippedCount" exact="$skippedCount + 1"/>
              </do_else>
              
              <do_if value="$needsUpdate">
                <!-- Store original name if not already stored (strip any existing GT formatting) -->
                <do_if value="not $pilotData.$OriginalShipName?">
                  <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$cleanedName">
                    <param name="shipName" value="$ship.knownname"/>
                  </run_actions>
                  <set_value name="global.$GT_Pilots.{$ship.pilot}.$OriginalShipName" exact="$cleanedName"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Core] Cleanup: Stored cleaned original name: ' + $cleanedName + ' (from: ' + $ship.knownname + ')'" chance="if $cleanedName != $ship.knownname then 100 else 0"/>
                  </do_if>
                </do_if>
                
                <!-- OPTIMIZED: Use extracted libraries for skill level and ship name update -->
                <set_value name="$currentXP" exact="$pilotData.$XP"/>
                <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
                  <param name="pilot" value="$ship.pilot"/>
                  <param name="ship" value="$ship"/>
                </run_actions>
                
                <set_value name="$fixedCount" exact="$fixedCount + 1"/>
                <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
                  <param name="pilot" value="$ship.pilot"/>
                  <param name="xp" value="$currentXP"/>
                </run_actions>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Fixed ship name: ' + $ship.idcode + ' (Pilot: ' + $ship.pilot.name + ', Level: ' + $currentSkillLevel + ', XP: ' + $currentXP + ')'" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Legacy ship name fix complete: ' + $fixedCount + ' ships updated, ' + $skippedCount + ' ships already properly named'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Update All Ship Names Based on Configuration -->
    <cue name="UpdateAllShipNames" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$skipUpdateAllNames" exact="false"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and not @global.$GT_GlobalSettings.$ShipNaming.$Enabled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] UpdateAllShipNames skipped: ship renaming disabled'" chance="100"/>
          </do_if>
          <set_value name="$skipUpdateAllNames" exact="true"/>
        </do_if>
        <do_if value="not $skipUpdateAllNames">
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Updating all ship names based on new naming configuration...'" chance="100"/>
        </do_if>
        
        <set_value name="$updatedCount" exact="0"/>
        
        <!-- Update all registered GT ships -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            
            <!-- Skip if ship no longer exists -->
            <do_if value="not $ship.exists or not $ship.isoperational">
              <continue/>
            </do_if>
            
            <!-- Rename only GT-active ships (direct GT order OR subordinate of GT commander) -->
            <set_value name="$hasGTOrder" exact="false"/>
            <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
              <set_value name="$hasGTOrder" exact="true"/>
            </do_if>
            <do_elseif value="$ship.commander? and $ship.commander.exists and $ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
              <set_value name="$hasGTOrder" exact="true"/>
            </do_elseif>
            <do_if value="not $hasGTOrder">
              <continue/>
            </do_if>

            <!-- Get the pilot -->
            <set_value name="$pilot" exact="$ship.pilot"/>
            <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
              <!-- Get pilot data -->
              <set_value name="$pilotData" exact="global.$GT_Pilots.{$pilot}"/>
              <set_value name="$currentXP" exact="$pilotData.$XP"/>
              
              <!-- OPTIMIZED: Use extracted library for skill level calculation -->
              <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level_From_XP" result="$skillLevel">
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$currentXP"/>
              </run_actions>
              
              <!-- Delegate to unified name builder + content dedupe -->
              <run_actions ref="md.GT_Ship_Management.Calculate_Rank_Title" result="$rankTitle">
                <param name="skillLevel" value="$skillLevel"/>
              </run_actions>
              <run_actions ref="md.GT_Ship_Management.GT_Process_Ship_Name_Refresh" result="$resolvedName">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$currentXP"/>
                <param name="level" value="$skillLevel"/>
                <param name="rank" value="$rankTitle"/>
                <param name="nameType" value="'trader'"/>
              </run_actions>
              <do_if value="$resolvedName? and $resolvedName != false">
                <set_value name="$updatedCount" exact="$updatedCount + 1"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Updated ship name: ' + $ship.idcode + ' -> ' + $resolvedName" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ship name update complete: ' + $updatedCount + ' ships updated'" chance="100"/>
        </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Ship Modification Update Handler (Queue Wrapper) -->
    <!-- PERFORMANCE: Coalesce & spread ship-update work across frames to prevent stutter bursts -->
    <cue name="HandleShipModificationUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Update_Ship'" comment="Handle ship updates from AI scripts"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$ship" exact="$data.$Ship"/>
        <set_value name="$updateType" exact="$data.$updateType"/>

        <!-- Initialize queue state if missing (save/load safe) -->
        <do_if value="not global.$GT_ShipUpdateQueue?">
          <set_value name="global.$GT_ShipUpdateQueue" exact="table[
            $Ships = [],
            $Params = table[],
            $QueuedShips = table[],
            $Processing = false
          ]"/>
        </do_if>
        <do_if value="not global.$GT_ShipUpdateQueue.$Ships? or global.$GT_ShipUpdateQueue.$Ships == null">
          <set_value name="global.$GT_ShipUpdateQueue.$Ships" exact="[]"/>
        </do_if>
        <do_if value="not global.$GT_ShipUpdateQueue.$Params? or global.$GT_ShipUpdateQueue.$Params == null">
          <set_value name="global.$GT_ShipUpdateQueue.$Params" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_ShipUpdateQueue.$QueuedShips? or global.$GT_ShipUpdateQueue.$QueuedShips == null">
          <set_value name="global.$GT_ShipUpdateQueue.$QueuedShips" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_ShipUpdateQueue.$Processing?">
          <set_value name="global.$GT_ShipUpdateQueue.$Processing" exact="false"/>
        </do_if>

        <!-- Always store the latest update for the ship (coalescing by ship) -->
        <set_value name="global.$GT_ShipUpdateQueue.$Params.{$ship}" exact="$data"/>

        <!-- Enqueue ship only once -->
        <do_if value="not global.$GT_ShipUpdateQueue.$QueuedShips.{$ship}?">
          <set_value name="global.$GT_ShipUpdateQueue.$QueuedShips.{$ship}" exact="true"/>
          <append_to_list name="global.$GT_ShipUpdateQueue.$Ships" exact="$ship"/>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] Ship modification update QUEUED: ' + (if $ship? then $ship.knownname else 'NULL') + ' (Type: ' + $updateType + ', queued=' + global.$GT_ShipUpdateQueue.$Ships.count + ')'" chance="100"/>
        </do_if>

        <!-- Kick the queue processor (single-threaded) -->
        <signal_cue_instantly cue="md.GT_CoreSystem.ProcessShipModificationUpdateQueue"/>
      </actions>
    </cue>

    <!-- Ship Modification Update Queue Processor -->
    <cue name="ProcessShipModificationUpdateQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- Yield a little to avoid same-frame stampedes -->
      <delay min="5ms" max="25ms"/>
      <actions>
        <set_value name="$proceed" exact="true"/>
        <do_if value="not global.$GT_ShipUpdateQueue?">
          <set_value name="$proceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>
        <do_if value="global.$GT_ShipUpdateQueue? and global.$GT_ShipUpdateQueue.$Processing">
          <set_value name="$proceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>
        <do_if value="$proceed">
          <set_value name="global.$GT_ShipUpdateQueue.$Processing" exact="true"/>

          <!-- Process ONE ship per invocation (smooth gameplay > speed) -->
          <do_if value="global.$GT_ShipUpdateQueue.$Ships.count gt 0">
            <set_value name="$ship" exact="global.$GT_ShipUpdateQueue.$Ships.{1}"/>
            <remove_from_list name="global.$GT_ShipUpdateQueue.$Ships" exact="$ship"/>
            <do_if value="global.$GT_ShipUpdateQueue.$QueuedShips.{$ship}?">
              <remove_value name="global.$GT_ShipUpdateQueue.$QueuedShips.{$ship}"/>
            </do_if>

            <set_value name="$data" exact="global.$GT_ShipUpdateQueue.$Params.{$ship}"/>
            <do_if value="global.$GT_ShipUpdateQueue.$Params.{$ship}?">
              <remove_value name="global.$GT_ShipUpdateQueue.$Params.{$ship}"/>
            </do_if>

            <do_if value="$data? and $ship? and $ship.exists">
              <signal_cue_instantly cue="md.GT_CoreSystem.HandleShipModificationUpdate_Process" param="$data"/>
            </do_if>
          </do_if>

          <set_value name="global.$GT_ShipUpdateQueue.$Processing" exact="false"/>
        </do_if>

        <!-- Continue draining if needed -->
        <do_if value="$proceed and global.$GT_ShipUpdateQueue? and global.$GT_ShipUpdateQueue.$Ships.count gt 0">
          <signal_cue_instantly cue="md.GT_CoreSystem.ProcessShipModificationUpdateQueue"/>
        </do_if>
      </actions>
    </cue>

    <!-- Ship Modification Update Processor (was HandleShipModificationUpdate) -->
    <cue name="HandleShipModificationUpdate_Process" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param.$Ship"/>
        <set_value name="$pilot" exact="event.param.$pilot"/>
        <set_value name="$updateType" exact="event.param.$updateType"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] Ship modification update requested: ' + $ship.knownname + ' (Type: ' + $updateType + ')'" chance="100"/>
        </do_if>
        
        <!-- DEBUG: Check library availability -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Core] DEBUG: GT_Ship_Management library check result: ' + md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?" chance="100"/>
        </do_if>
        
        <!-- Handle different update types -->
        <do_if value="$updateType == 'training_completion'">
          <!-- Apply modifications after training completion -->
          <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
            <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
              <param name="ship" value="$ship"/>
              <param name="new_pilot" value="$pilot"/>
              <param name="old_pilot" value="$pilot"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] Applied ship modifications after training completion for ' + $pilot.name" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_Ship_Management.GT_Apply_AutoJumpDistance_ForShip">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="reason" value="'training_completion'"/>
            </run_actions>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] GT_Ship_Management library not available - ship modifications skipped'" chance="100"/>
            </do_if>
          </do_else>
          
        </do_if>
        <do_elseif value="$updateType == 'pilot_change'">
          <!-- Handle pilot assignment changes -->
          <set_value name="$oldPilot" exact="event.param.$oldPilot"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Core] Processing pilot change on ' + $ship.knownname + ' - Old: ' + @$oldPilot.name + ', New: ' + @$pilot.name" chance="100"/>
          </do_if>

          <do_if value="not $pilot? or not $pilot.exists">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] Pilot change deferred: ship=' + $ship.idcode + ' has no bound pilot yet - delegating to FinalizeVanillaPilotAssignmentForGT'" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_CoreSystem.QueueFinalizeVanillaPilotAssignment">
              <param name="ship" value="$ship"/>
              <param name="source" value="'pilot_change_missing_pilot'"/>
              <param name="attempt" value="1"/>
            </run_actions>
          </do_if>
          <do_else>
          
          <!-- EVENT-DRIVEN: Check old ship for orphaned status (if old pilot was transferred away) -->
          <!-- CRITICAL: Don't require registry membership - ship might have been cleaned up already, but we should still check -->
          <!-- The CheckShipOrphaned cue will handle registry checks internally -->
          <do_if value="$oldPilot and $oldPilot.exists and $oldPilot.ship? and $oldPilot.ship.exists and $oldPilot.ship != $ship">
            <set_value name="$oldShip" exact="$oldPilot.ship"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <run_actions ref="md.GT_CoreSystem.IsShipInRegistry" result="$oldShipInRegistry">
                <param name="ship" value="$oldShip"/>
              </run_actions>
              <debug_text text="'[GT-Core] Pilot change: Checking old ship ' + $oldShip.idcode + ' (inRegistry=' + (if $oldShipInRegistry then 'YES' else 'NO') + ')'" chance="100"/>
            </do_if>
            <!-- Always trigger check - CheckShipOrphaned will handle registry membership internally -->
            <run_actions ref="md.GT_CoreSystem.QueueCheckShipOrphaned">
              <param name="ship" value="$oldShip"/>
            </run_actions>
          </do_if>
          
          <!-- Check if new pilot is a registered GT pilot -->
          <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
            <!-- New pilot is already registered - update ship name with their XP/rank -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] New pilot ' + $pilot.name + ' is registered GT pilot - updating ship name'" chance="100"/>
            </do_if>
            
            <!-- Register new pilot for this ship -->
            <run_actions ref="md.GT_CoreSystem.TryRegisterPilotForShip">
              <param name="pilot" value="$pilot"/>
              <param name="ship" value="$ship"/>
            </run_actions>
          </do_if>
          <do_elseif value="$pilot">
            <!-- New pilot is NOT registered - restore original ship name and clean up old pilot -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] New pilot ' + $pilot.name + ' is NOT registered GT pilot - restoring original ship name'" chance="100"/>
            </do_if>
            
            <!-- Get original name from ship registry (per ship, not per pilot) -->
            <run_actions ref="md.GT_CoreSystem.GetShipRegistryOriginalName" result="$originalName">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="not $originalName and $ship.knownname?">
              <!-- Fallback: use current name if ship registry doesn't have original name -->
              <set_value name="$originalName" exact="$ship.knownname"/>
            </do_if>
            
            <!-- Restore original ship name -->
            <do_if value="$originalName">
              <set_object_name object="$ship" name="$originalName"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] Ship name restored to: ' + $originalName" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- CRITICAL FIX: Register the new unregistered pilot -->
            <!-- This ensures unregistered pilots get registered when swapped in -->
            <run_actions ref="md.GT_CoreSystem.TryRegisterPilotForShip" result="$didRegisterNewPilot">
              <param name="pilot" value="$pilot"/>
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="$didRegisterNewPilot">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Core] Registered new unregistered pilot: ' + $pilot.name" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Clean up old pilot if no other ships -->
            <do_if value="$oldPilot and global.$GT_Pilots.{$oldPilot}?">
              <!-- CRITICAL FIX: Preserve old pilot's XP data when pilot changes -->
              <!-- Mark old pilot as paused instead of removing, so they can be reactivated later -->
              <set_value name="$oldPilotHasOtherShips" exact="false"/>
              <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
                <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
                <do_all exact="$shipKeys.count" counter="$i">
                  <set_value name="$otherShip" exact="$shipKeys.{$i}"/>
                  <do_if value="$otherShip? and $otherShip.exists and $otherShip.pilot == $oldPilot">
                    <set_value name="$oldPilotHasOtherShips" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              
              <do_if value="not $oldPilotHasOtherShips">
                <!-- Old pilot has no other ships - mark as paused to preserve XP data -->
                <set_value name="global.$GT_Pilots.{$oldPilot}.$Status" exact="'paused'"/>
                <set_value name="global.$GT_Pilots.{$oldPilot}.$PausedTime" exact="player.age"/>
                <set_value name="global.$GT_Pilots.{$oldPilot}.$PausedReason" exact="'Pilot changed on ship - preserving XP data'"/>
                <remove_value name="global.$GT_Pilots.{$oldPilot}.$AssociatedShip"/>
                <remove_value name="global.$GT_Pilots.{$oldPilot}.$Ship"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Core] Old pilot paused (preserving XP): ' + $oldPilot.name + ' (XP: ' + (if global.$GT_Pilots.{$oldPilot}.$XP? then global.$GT_Pilots.{$oldPilot}.$XP else 0) + ')'" chance="100"/>
                </do_if>
                
                <!-- ROLEPLAY: Send logbook message thanking player for holiday -->
                <set_value name="$message" exact="{77000,3215}.[player.name]"/>
                <write_to_logbook 
                  category="general" 
                  title="'Pilot Status: ' + $oldPilot.name" 
                  interaction="showonmap" 
                  object="$ship" 
                  text="$message"/>
              </do_if>
            </do_if>
          </do_elseif>
          
          <!-- Apply performance modifications -->
          <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
            <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
              <param name="ship" value="$ship"/>
              <param name="new_pilot" value="$pilot"/>
              <param name="old_pilot" value="$oldPilot"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] Applied ship modifications after pilot change on ' + $ship.knownname" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_Ship_Management.GT_Apply_AutoJumpDistance_ForShip">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="reason" value="'pilot_change'"/>
            </run_actions>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] GT_Ship_Management library not available - pilot change modifications skipped'" chance="100"/>
            </do_if>
          </do_else>
          </do_else>
          
        </do_elseif>
        <do_elseif value="$updateType == 'level_up'">
          <!-- Handle skill level increases -->
          <do_if value="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment?">
            <run_actions ref="md.GT_Ship_Management.Handle_Pilot_Ship_Assignment">
              <param name="ship" value="$ship"/>
              <param name="new_pilot" value="$pilot"/>
              <param name="old_pilot" value="$pilot"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] Applied ship modifications after level up for ' + $pilot.name" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Core] GT_Ship_Management library not available - level up modifications skipped'" chance="100"/>
            </do_if>
          </do_else>
          
        </do_elseif>
      </actions>
    </cue>

  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Debug" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Debug Commands Initialization -->
    <cue name="DebugInit" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.SystemInit"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3 Debug] Debug system initialized'" chance="100"/>
          <debug_text text="'[GalaxyTrader MK3 Debug] Available commands:'" chance="100"/>
          <debug_text text="'- /gt status - Show mod status'" chance="100"/>
          <debug_text text="'- /gt ship [shipname] - Show ship details'" chance="100"/>
          <debug_text text="'- /gt xp [shipname] [amount] - Award XP to ships pilot'" chance="100"/>
          <debug_text text="'- /gt level [shipname] [level] - Set ship level'" chance="100"/>
          <debug_text text="'- /gt report [type] - Generate report (fleet/market/territory)'" chance="100"/>
          <debug_text text="'- /gt dashboard - Show quick dashboard'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- PERFORMANCE: PeriodicDebugStatus removed -->
    <!-- This cue iterated through all ships every 5 minutes for debug output -->
    <!-- Debug information can be obtained on-demand via ShowStatus cue if needed -->
    
    <!-- Show Status -->
    <cue name="ShowStatus" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$status" exact="'=== GALAXYTRADER MK3 STATUS ===\n\n'"/>
        
        <!-- System status -->
        <set_value name="$status" exact="$status + 'System Status:\n'"/>
        <set_value name="$status" exact="$status + '- Ships Registered: ' + if global.$GT_Ships? then global.$GT_Ships.keys.count else 0 + '\n'"/>
        <set_value name="$status" exact="$status + '- Pilots Registered: ' + if global.$GT_Pilots? then global.$GT_Pilots.keys.count else 0 + '\n'"/>
        <set_value name="$status" exact="$status + '- XP System: Enabled\n'"/>
        <set_value name="$status" exact="$status + '- Fleet Coordination: ' + if global.$GT_Config.$Fleet.$Enabled then 'Enabled' else 'Disabled' + '\n'"/>
        <set_value name="$status" exact="$status + '- Market Intelligence: ' + if global.$GT_Config.$Market.$TrendAnalysis then 'Enabled' else 'Disabled' + '\n'"/>
        <set_value name="$status" exact="$status + '- Territory Management: ' + if global.$GT_Config.$Fleet.$TerritoryManagement then 'Enabled' else 'Disabled' + '\n\n'"/>
        
        <!-- Session stats -->
        <set_value name="$sessionTime" exact="player.age - global.$GT_SessionStats.$StartTime"/>
        <set_value name="$hours" exact="($sessionTime / 3600)i"/>
        <set_value name="$minutes" exact="(($sessionTime - ($hours * 3600)) / 60)i"/>
        
        <set_value name="$status" exact="$status + 'Session Stats:\n'"/>
        <set_value name="$status" exact="$status + '- Session Duration: ' + $hours + 'h ' + $minutes + 'm\n'"/>
        <set_value name="$status" exact="$status + '- Total Session Profit: ' + (global.$GT_SessionStats.$TotalProfit / 100) + ' Cr\n'"/>
        <set_value name="$status" exact="$status + '- Total Trades Completed: ' + global.$GT_SessionStats.$TradesCompleted + '\n'"/>
        
        <show_notification text="$status" timeout="15s" priority="5"/>
      </actions>
    </cue>
    
    <!-- Show Ship Details -->
    <cue name="ShowShipDetails" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$shipname" exact="global.$GT_Debug_ShipName"/>
        
        <!-- Find ship by name -->
        <set_value name="$foundship" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <do_if value="$ship.knownname.{$shipname}?">
              <set_value name="$foundship" exact="$ship"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$foundship">
          <set_value name="$pilot" exact="$foundship.pilot"/>
          <set_value name="$details" exact="'=== SHIP/PILOT DETAILS ===\n\n'"/>
          <set_value name="$details" exact="$details + 'Ship: ' + $foundship.knownname + ' (' + $foundship.idcode + ')\n'"/>
          
          <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
            <set_value name="$pilotdata" exact="global.$GT_Pilots.{$pilot}"/>
            <set_value name="$details" exact="$details + 'Pilot: ' + $pilot.name + '\n'"/>
            <set_value name="$details" exact="$details + 'Level: ' + $pilotdata.$Level + '\n'"/>
            <set_value name="$details" exact="$details + 'XP: ' + $pilotdata.$XP + '/' + if global.$GT_Config.$XP.$LevelRequirements.{$pilotdata.$Level + 1}? then global.$GT_Config.$XP.$LevelRequirements.{$pilotdata.$Level + 1} else 'MAX' + '\n'"/>
            <set_value name="$details" exact="$details + 'Total Trades: ' + $pilotdata.$TotalTrades + '\n'"/>
            <set_value name="$details" exact="$details + 'Last Trade Profit: ' + ($pilotdata.$LastTradeProfit / 100) + ' Cr\n'"/>
            
            <!-- PERFORMANCE INFORMATION DISPLAY -->
            <do_if value="global.$GT_Ships.{$foundship}?">
              <set_value name="$shipData" exact="global.$GT_Ships.{$foundship}"/>
              <do_if value="$shipData.$PerformanceInfo?">
                <set_value name="$details" exact="$details + '\n=== PERFORMANCE BONUSES ===\n'"/>
                <set_value name="$details" exact="$details + $shipData.$PerformanceInfo + '\n'"/>
                <set_value name="$details" exact="$details + 'Performance Modifier: ' + $shipData.$PerformanceModifier + '%\n'"/>
                <set_value name="$details" exact="$details + 'Status: ' + $shipData.$PerformanceStatus + '\n'"/>
                <set_value name="$details" exact="$details + 'Pilot Level: ' + $shipData.$PerformanceLevel + '\n'"/>
              </do_if>
              <do_else>
                <set_value name="$details" exact="$details + '\n=== PERFORMANCE BONUSES ===\n'"/>
                <set_value name="$details" exact="$details + 'Performance data not available\n'"/>
              </do_else>
            </do_if>
            
            <do_if value="$pilotdata.$XPBlocked?">
              <set_value name="$details" exact="$details + '\nStatus: BLOCKED FOR TRAINING (Level ' + $pilotdata.$BlockedLevel + ')\n'"/>
            </do_if>
            <do_elseif value="$pilotdata.$TrainingStarted?">
              <set_value name="$details" exact="$details + '\nStatus: IN TRAINING\n'"/>
            </do_elseif>
            <do_else>
              <set_value name="$details" exact="$details + '\nStatus: ACTIVE\n'"/>
            </do_else>
          </do_if>
          <do_else>
            <set_value name="$details" exact="$details + 'Pilot: NO PILOT or NOT REGISTERED\n'"/>
          </do_else>
          
          <show_notification text="$details" timeout="10s" priority="5"/>
        </do_if>
        <do_else>
          <show_notification text="'Ship not found: ' + $shipname" timeout="5s"/>
        </do_else>
      </actions>
    </cue>
    
    <!-- Award Debug XP -->
    <cue name="AwardDebugXP" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$params" exact="global.$GT_Debug_XPCommand"/>
        
        <!-- Parse parameters (simple split by space) -->
        <set_value name="$spaceindex" exact="1"/>
        <do_if value="$spaceindex gt 0">
          <set_value name="$shipname" exact="$params"/>
          <set_value name="$xpamount" exact="100"/>
          
          <!-- Find ship -->
          <set_value name="$foundship" exact="null"/>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
            <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
            <do_all exact="$shipKeys.count" counter="$i">
              <set_value name="$ship" exact="$shipKeys.{$i}"/>
              <do_if value="$ship.knownname.{$shipname}?">
                <set_value name="$foundship" exact="$ship"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="$foundship">
            <set_value name="$pilot" exact="$foundship.pilot"/>
            <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
              <!-- Award XP to pilot -->
              <set_value name="global.$GT_Pilots.{$pilot}.$PendingXP" exact="$xpamount"/>
                        <!-- PHASE 1 IMPROVEMENT: Use event queue instead of polling -->
          
          <append_to_list name="global.$GT_XPEventQueue" exact="table[
              $pilot = $pilot,
              $ship = $foundship,
              $xpAmount = 100,
              $ware = ware.energycells,
              $timestamp = player.age
          ]"/>
          
          <!-- Signal MD cue directly (no polling needed) -->
          <signal_cue_instantly cue="md.GT_XP_Training.ProcessXPEvents"/>
              
              <show_notification text="'Awarded ' + $xpamount + ' XP to pilot ' + $pilot.name + ' on ' + $foundship.knownname" timeout="5s"/>
            </do_if>
            <do_else>
              <show_notification text="'Ship has no pilot or pilot not registered'" timeout="5s"/>
            </do_else>
          </do_if>
          <do_else>
            <show_notification text="'Ship not found: ' + $shipname" timeout="5s"/>
          </do_else>
        </do_if>
        <do_else>
          <show_notification text="'Invalid XP command format. Use: /gt xp shipname amount'" timeout="5s"/>
        </do_else>
      </actions>
    </cue>
    
    <!-- Set Debug Level -->
    <cue name="SetDebugLevel" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$params" exact="global.$GT_Debug_LevelCommand"/>
        
        <!-- Parse parameters -->
        <set_value name="$spaceindex" exact="1"/>
        <do_if value="$spaceindex gt 0">
          <set_value name="$shipname" exact="$params"/>
          <set_value name="$level" exact="5"/>
          
          <!-- Find ship -->
          <set_value name="$foundship" exact="null"/>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
            <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
            <do_all exact="$shipKeys.count" counter="$i">
              <set_value name="$ship" exact="$shipKeys.{$i}"/>
              <do_if value="$ship.knownname.{$shipname}?">
                <set_value name="$foundship" exact="$ship"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="$foundship and ($level ge 0) and ($level le 10)">
            <set_value name="$pilot" exact="$foundship.pilot"/>
            <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
              <!-- Set level for pilot -->
              <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$level"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="0"/>
              
              <!-- Clear any blocks -->
              <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
              
              <show_notification text="'Set pilot ' + $pilot.name + ' on ' + $foundship.knownname + ' to level ' + $level" timeout="5s"/>
            </do_if>
            <do_else>
              <show_notification text="'Ship has no pilot or pilot not registered'" timeout="5s"/>
            </do_else>
          </do_if>
          <do_else>
            <show_notification text="'Invalid ship or level (0-10)'" timeout="5s"/>
          </do_else>
        </do_if>
        <do_else>
          <show_notification text="'Invalid level command format. Use: /gt level shipname level'" timeout="5s"/>
        </do_else>
      </actions>
    </cue>
    
    <!-- Test Trade Route -->
    <cue name="TestTradeRoute" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3 Debug] Testing trade route for ' + $ship.knownname" chance="100"/>
        </do_if>
        
        <!-- Force a trade calculation -->
        <set_value name="global.$GT_FindTrades_Ship" exact="$ship"/>
        <signal_cue cue="md.GT_TradingAI.FindTrades"/>
        
        <show_notification text="'Testing trade route for ' + $ship.knownname + '...'" timeout="5s"/>
      </actions>
    </cue>
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Fleet_Coordination" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Fleet Management Library - Shared logic for fleet coordination -->
    
    <!-- Register Ship in Fleet -->
    <library name="RegisterShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to register"/>
        <param name="preserveData" default="true" comment="Preserve existing ship data"/>
      </params>
      <actions>
        <!-- Initialize fleet registry if needed -->
        
        <!-- Register ship with data preservation -->
        <do_if value="$preserveData and global.$GT_Ships.{$ship}?">
          <!-- Update only essential fields, preserve statistics -->
          <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
          <do_if value="$ship.pilot?">
            <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$ship.pilot"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- New ship registration -->
          <set_value name="global.$GT_Ships.{$ship}" exact="table[
            $Pilot = $ship.pilot,
            $LastUpdate = player.age,
            $TotalProfit = 0,
            $TradesCompleted = 0,
            $ThreatReports = 0,
            $LastThreatTime = 0,
            $RegistrationTime = player.age
          ]"/>
        </do_else>
        
        <set_value name="this.$result" exact="true"/>
      </actions>
    </library>
    
    <!-- Update Ship Statistics -->
    <library name="UpdateShipStats" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to update"/>
        <param name="profit" default="0" comment="Profit to add"/>
        <param name="tradesCompleted" default="0" comment="Trades to add"/>
      </params>
      <actions>
        <!-- Ensure ship is registered -->
        <do_if value="not global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}" exact="table[
            $Pilot = $ship.pilot,
            $LastUpdate = player.age,
            $TotalProfit = 0,
            $TradesCompleted = 0,
            $ThreatReports = 0,
            $LastThreatTime = 0,
            $RegistrationTime = player.age
          ]"/>
        </do_if>
        
        <!-- Initialize ship statistics if missing (for ships registered before these fields existed) -->
        <do_if value="not global.$GT_Ships.{$ship}.$TotalProfit?">
          <set_value name="global.$GT_Ships.{$ship}.$TotalProfit" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{$ship}.$TradesCompleted?">
          <set_value name="global.$GT_Ships.{$ship}.$TradesCompleted" exact="0"/>
        </do_if>
        
        <!-- Update ship statistics -->
        <set_value name="global.$GT_Ships.{$ship}.$TotalProfit" exact="global.$GT_Ships.{$ship}.$TotalProfit + $profit"/>
        <set_value name="global.$GT_Ships.{$ship}.$TradesCompleted" exact="global.$GT_Ships.{$ship}.$TradesCompleted + $tradesCompleted"/>
        <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
        
        <!-- Also update pilot statistics (so profit follows pilot across ships) -->
        <do_if value="@$ship.pilot and global.$GT_Pilots.{$ship.pilot}?">
          <set_value name="$pilot" exact="$ship.pilot"/>
          
          <!-- Initialize pilot profit if not set -->
          <do_if value="not global.$GT_Pilots.{$pilot}.$TotalProfit?">
            <set_value name="global.$GT_Pilots.{$pilot}.$TotalProfit" exact="0"/>
          </do_if>
          
          <!-- Update pilot profit and trade count -->
          <set_value name="global.$GT_Pilots.{$pilot}.$TotalProfit" exact="global.$GT_Pilots.{$pilot}.$TotalProfit + $profit"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TotalTrades" exact="global.$GT_Pilots.{$pilot}.$TotalTrades + $tradesCompleted"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-FleetCoord] Updated pilot ' + $pilot.name + ': +' + ($profit / 100) + ' Cr (Total: ' + (global.$GT_Pilots.{$pilot}.$TotalProfit / 100) + ' Cr, Trades: ' + global.$GT_Pilots.{$pilot}.$TotalTrades + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <set_value name="this.$result" exact="global.$GT_Ships.{$ship}"/>
      </actions>
    </library>
    
    <!-- Get Fleet Summary -->
    <library name="GetFleetSummary" purpose="run_actions">
      <params>
        <param name="includeInactive" default="false" comment="Include inactive ships"/>
      </params>
      <actions>
        <set_value name="$summary" exact="table[
          $TotalShips = 0,
          $ActiveShips = 0,
          $TotalProfit = 0,
          $TotalTrades = 0,
          $AverageProfit = 0
        ]"/>
        
        <do_if value="global.$GT_Ships?">
          <do_all exact="global.$GT_Ships.keys.count" counter="$i">
            <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
            <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
            
            <!-- Check if ship is active (updated in last 10 minutes) -->
            <set_value name="$isActive" exact="(player.age - $shipData.$LastUpdate) lt 600s"/>
            
            <do_if value="$includeInactive or $isActive">
              <set_value name="$summary.$TotalShips" exact="$summary.$TotalShips + 1"/>
              <set_value name="$summary.$TotalProfit" exact="$summary.$TotalProfit + $shipData.$TotalProfit"/>
              <set_value name="$summary.$TotalTrades" exact="$summary.$TotalTrades + $shipData.$TradesCompleted"/>
              
              <do_if value="$isActive">
                <set_value name="$summary.$ActiveShips" exact="$summary.$ActiveShips + 1"/>
              </do_if>
            </do_if>
          </do_all>
          
          <!-- Calculate average -->
          <do_if value="$summary.$TotalShips gt 0">
            <set_value name="$summary.$AverageProfit" exact="$summary.$TotalProfit / $summary.$TotalShips"/>
          </do_if>
        </do_if>
        
        <set_value name="this.$result" exact="$summary"/>
      </actions>
    </library>
    
    <!-- Get Ship Performance Data -->
    <library name="GetShipPerformance" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to analyze"/>
      </params>
      <actions>
        <set_value name="$performance" exact="null"/>
        
        <do_if value="global.$GT_Ships.{$ship}?">
          <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
          <set_value name="$activeTime" exact="player.age - $shipData.$RegistrationTime"/>
          
          <!-- Calculate performance metrics -->
          <set_value name="$profitPerHour" exact="0"/>
          <set_value name="$tradesPerHour" exact="0"/>
          
          <do_if value="$activeTime gt 0">
            <set_value name="$hoursActive" exact="$activeTime / 3600"/>
            <set_value name="$profitPerHour" exact="$shipData.$TotalProfit / $hoursActive"/>
            <set_value name="$tradesPerHour" exact="$shipData.$TradesCompleted / $hoursActive"/>
          </do_if>
          
          <set_value name="$performance" exact="table[
            $Ship = $ship,
            $TotalProfit = $shipData.$TotalProfit,
            $TradesCompleted = $shipData.$TradesCompleted,
            $ProfitPerHour = $profitPerHour,
            $TradesPerHour = $tradesPerHour,
            $ActiveTime = $activeTime,
            $LastUpdate = $shipData.$LastUpdate,
            $IsActive = (player.age - $shipData.$LastUpdate) lt 600s
          ]"/>
        </do_if>
        
        <set_value name="this.$result" exact="$performance"/>
      </actions>
    </library>
    
    <!-- Clean Up Inactive Ships -->
    <library name="CleanupInactiveShips" purpose="run_actions">
      <params>
        <param name="maxAge" default="3600s" comment="Maximum age for inactive ships"/>
      </params>
      <actions>
        <set_value name="$removedShips" exact="0"/>
        
        <do_if value="global.$GT_Ships?">
          <do_all exact="global.$GT_Ships.keys.count" counter="$i" reverse="true">
            <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
            <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
            
            <!-- Check if ship is too old and no longer exists -->
            <set_value name="$age" exact="player.age - $shipData.$LastUpdate"/>
            <do_if value="$age gt $maxAge and not $ship.exists">
              <remove_value name="global.$GT_Ships.{$ship}"/>
              <set_value name="$removedShips" exact="$removedShips + 1"/>
            </do_if>
          </do_all>
        </do_if>
        
        <set_value name="this.$result" exact="$removedShips"/>
      </actions>
    </library>
    
    <!-- Fleet Cache Statistics -->
    <library name="GetCacheStatistics" purpose="run_actions">
      <actions>
        <set_value name="$stats" exact="table[
          $TotalWares = 0,
          $TotalRoutes = 0,
          $OldestEntry = player.age,
          $NewestEntry = 0,
          $AverageAge = 0
        ]"/>
        
        <run_actions ref="md.GLX_Lib_Cache.GLX_CachePool_AccumulateFleetStats" result="$mk3PoolStats">
          <param name="cachePool" value="'mk3'"/>
        </run_actions>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CachePool_AccumulateFleetStats" result="$mk4PoolStats">
          <param name="cachePool" value="'mk4'"/>
        </run_actions>
        <set_value name="$stats.$TotalRoutes" exact="$mk3PoolStats.$TotalRoutes + $mk4PoolStats.$TotalRoutes"/>
        <set_value name="$stats.$TotalWares" exact="$mk3PoolStats.$TotalWares + $mk4PoolStats.$TotalWares"/>
        <set_value name="$stats.$OldestEntry" exact="[$mk3PoolStats.$OldestEntry, $mk4PoolStats.$OldestEntry].min"/>
        <set_value name="$stats.$NewestEntry" exact="[$mk3PoolStats.$NewestEntry, $mk4PoolStats.$NewestEntry].max"/>
        <set_value name="$totalAge" exact="$mk3PoolStats.$TotalAge + $mk4PoolStats.$TotalAge"/>
        <do_if value="$stats.$TotalRoutes gt 0">
          <set_value name="$stats.$AverageAge" exact="$totalAge / $stats.$TotalRoutes"/>
        </do_if>
        
        <set_value name="this.$result" exact="$stats"/>
      </actions>
    </library>
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_FleetReplacement" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <!--
    Bridges the vanilla fleet reconstitution system into GT-controlled fleets.

    Vanilla raises the 'reconstitute_fleet' signal only from a small set of AI scripts
    (orders.base, order.wait, order.move.follow, order.fight.escort, fight.attack.object.station)
    and only when the firing ship is itself a top-level commander (no commander, no fleetunit).
    GT miners/traders run infinite custom orders and are commonly subordinated to a station,
    so neither condition is met for their fleets and lost subordinate slots never get rebuilt
    by Fleet_Reconstitution.ProcessRequest.

    This script raises 'reconstitute_fleet' from the destruction event of any player-owned
    subordinate. The vanilla cue Fleet_Reconstitution.ProcessRequest then walks up to
    toplevelcommander, picks the closest reachable player shipyard with the right macro and
    loadout equipment, and queues the rebuild; on completion it ships the replacement back
    via MoveToObject(joinfleet=true) and reinstate_fleet_ship slots it into the original
    fleet position. No other glue is needed.

    Composition with existing GT destruction handlers in gt_core_system.xml:
      - UnregisterShip          : cleans GT registries on any destroyed player object.
      - HandleCommanderDestroyed: handles promotion when a commander dies.
      - This cue                : only fires when the destroyed object had a commander
                                  (i.e. was a subordinate), so it never overlaps with
                                  HandleCommanderDestroyed (which acts on top-level deaths).
  -->
  <cues>

    <cue name="Init" version="1" instantiate="true">
      <conditions>
        <check_any>
          <event_player_created/>
          <event_game_loaded/>
        </check_any>
        <check_value value="not global.$GT_LastReconstituteSignal?"/>
      </conditions>
      <actions>
        <set_value name="global.$GT_LastReconstituteSignal" exact="table[]" comment="Per-commander cooldown timestamps (player.age) for the reconstitute_fleet signal"/>
      </actions>
    </cue>

    <cue name="RequestFleetReconstitution" instantiate="true">
      <conditions>
        <event_object_destroyed object="player.entity"/>
        <check_value value="event.object.commander?"/>
      </conditions>
      <delay exact="500ms"/>
      <actions>
        <set_value name="$commander" exact="event.object.commander"/>
        <do_if value="$commander? and $commander.exists and $commander.isoperational and @$commander.fleetunits.count">
          <set_value name="$shouldSignal" exact="false"/>
          <do_if value="not global.$GT_LastReconstituteSignal?">
            <set_value name="global.$GT_LastReconstituteSignal" exact="table[]"/>
            <set_value name="$shouldSignal" exact="true"/>
          </do_if>
          <do_elseif value="not global.$GT_LastReconstituteSignal.{$commander}?">
            <set_value name="$shouldSignal" exact="true"/>
          </do_elseif>
          <do_elseif value="(player.age - global.$GT_LastReconstituteSignal.{$commander}) gt 1s">
            <set_value name="$shouldSignal" exact="true"/>
          </do_elseif>
          <do_if value="$shouldSignal">
            <set_value name="global.$GT_LastReconstituteSignal.{$commander}" exact="player.age"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-FleetReplacement] Requesting fleet reconstitution: commander=' + @$commander.knownname + ' [' + @$commander.idcode + '], tracked slots=' + $commander.fleetunits.count" chance="100"/>
            </do_if>
            <signal_objects object="player.entity" param="'reconstitute_fleet'" param2="$commander" param3="$commander.fleetunits"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_GlobalSettings" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <cue name="Init" instantiate="true" version="3">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <!-- CRITICAL: Only initialize settings if they don't exist (preserve saved settings) -->
        <do_if value="not global.$GT_GlobalSettings?">
          <!-- Initialize global GalaxyTrader MK3 settings -->
          <set_value name="global.$GT_GlobalSettings" exact="table[]"/>
          
          <!-- XP and Training Settings -->
          <set_value name="global.$GT_GlobalSettings.$XP" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly" exact="false"/> <!-- false: use GT XP system, true: use vanilla pilot.skill.piloting -->
          <set_value name="global.$GT_GlobalSettings.$XP.$AutoTraining" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$XP.$XPMultiplier" exact="100"/> <!-- Percentage: 50-200% (100% = normal rate, balanced for ~500 trades) -->
          <set_value name="global.$GT_GlobalSettings.$XP.$MinTrainingDistance" exact="5"/> <!-- Max distance to training stations -->
          <set_value name="global.$GT_GlobalSettings.$XP.$TrainingCooldown" exact="600s"/> <!-- Cooldown between training sessions -->
          <set_value name="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" exact="10"/> <!-- Percentage of subordinate XP awarded to commander (default: 10%) -->
          <set_value name="global.$GT_GlobalSettings.$XP.$HardForceTraining" exact="true"/> <!-- true: no trading while training required; false: allow trading but keep XP blocked -->
          
          <!-- Fleet Coordination Settings -->
          <set_value name="global.$GT_GlobalSettings.$Fleet" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance" exact="15"/> <!-- Percentage -->
          <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheTTL" exact="300s"/> <!-- Time to live -->
          <set_value name="global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney" exact="1000"/> <!-- Minimum player money (credits) before ships stop searching for trades (default: 1000 Cr) -->
          <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="1"/> <!-- Minutes docked before undocking to free port (0-60). 0 = stay docked until work is found. -->
          
          <!-- Notification Settings -->
          <set_value name="global.$GT_GlobalSettings.$Notifications" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Notifications.$ShowXPGains" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$Notifications.$ShowTradeResults" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$Notifications.$ShowFleetStatus" exact="false"/>
          <set_value name="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency" exact="1"/> <!-- Minutes: 1-30 (default: 1 minute) -->
          <set_value name="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" exact="30"/> <!-- Minutes: 1-60 (default: 30 minutes) -->

          <!-- Mobile Satellite Intelligence Settings -->
          <set_value name="global.$GT_GlobalSettings.$MobileIntel" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$MobileIntel.$Enable" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration" exact="10min"/>
          <set_value name="global.$GT_GlobalSettings.$MobileIntel.$StationCooldown" exact="60s"/>
          
          <!-- Threat Avoidance Settings -->
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled" exact="false"/>
          <!-- Note: RiskTolerance removed - now configured per-ship in command behavior (0.0-1.0 scale) -->
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$ScanInterval" exact="5s"/>
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry" exact="600s"/> <!-- 10 minutes -->
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$HostileRelationThreshold" exact="-0.20"/> <!-- Only flag factions with relation <= this value (default: -0.20 = -20%) -->
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist" exact="false"/> <!-- Automatically blacklist dangerous sectors -->
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions" exact="true"/> <!-- Automatically block all sectors owned by enemy factions -->
          <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold" exact="3"/> <!-- Threat level (1-5) required for blacklisting -->
          
          <!-- Debug Settings -->
          <set_value name="global.$GT_GlobalSettings.$Debug" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/> <!-- Master toggle for debug_text output -->
          <set_value name="global.$GT_GlobalSettings.$Debug.$DebugLevel" exact="1"/> <!-- 0=None, 1=Basic, 2=Verbose -->
          <set_value name="global.$GT_GlobalSettings.$Debug.$TradeEvaluation" exact="false"/>
          
          <!-- Ship Naming Settings -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$Enabled" exact="false"/> <!-- Master toggle - default OFF -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled" exact="false"/> <!-- GT pilot name tags: (T:Level) PilotName -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayXP" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$XPPosition" exact="'suffix'"/> <!-- 'prefix' or 'suffix' -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayRank" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$RankPosition" exact="'suffix'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$LevelPosition" exact="'suffix'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StatusPosition" exact="'prefix'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayOperationalState" exact="true"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$OperationalStatePosition" exact="'prefix'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass" exact="false"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition" exact="'suffix'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource" exact="'macro.name'"/> <!-- 'macro.name', 'typename', 'macro.name.base', 'basename' -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamingMode" exact="'legacy'"/> <!-- 'legacy' or 'pattern' (pattern requires GT XP) -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamePattern" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector" exact="false"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition" exact="'prefix'"/> <!-- 'prefix' or 'suffix' (legacy mode only) -->
          
          <!-- Ship State Abbreviations (customizable) -->
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Resupply" exact="'RS'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Repair" exact="'RP'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Maintenance" exact="'MT'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Training" exact="'TR'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Escape" exact="'ES'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Reroute" exact="'RR'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Clearance" exact="'CL'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Unreachable" exact="'UR'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$PilotExchange" exact="'PE'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Blocked" exact="'BL'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$CustomBlacklist" exact="'CB'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Fallback" exact="'FB'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Isolated" exact="'IS'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Trading" exact="'TD'"/>
          <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$Idle" exact="'ID'"/>
          
          <!-- Auto-Repair Settings -->
          <set_value name="global.$GT_GlobalSettings.$AutoRepair" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$AutoRepair.$Enabled" exact="true"/> <!-- Enable/disable auto-repair system -->
          <set_value name="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold" exact="95"/> <!-- Hull percentage threshold (1-99) -->
          <set_value name="global.$GT_GlobalSettings.$AutoRepair.$MinPilotLevel" exact="12"/> <!-- Minimum pilot level required -->
          
          <!-- Galaxy Miner Settings -->
          <set_value name="global.$GT_GlobalSettings.$Miner" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel" exact="false"/> <!-- Off = vanilla (no resourceprobescantime wait). On = engine probe-count wait, scaled by GT pilot level (level 1 = full, level 15 = 5s). -->
          
          <!-- Ship Modifications Settings -->
          <set_value name="global.$GT_GlobalSettings.$Modifications" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Modifications.$Enabled" exact="false"/> <!-- Enable/disable automatic modification installation -->
          
          <!-- Trading Settings -->
          <set_value name="global.$GT_GlobalSettings.$Trading" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="0.04"/> <!-- Selection-score shipâ†’buy nudge at validation (0=off) -->
          
          <!-- Performance Settings (post AI-migration cleanup) -->
          <set_value name="global.$GT_GlobalSettings.$Performance" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches" exact="5"/> <!-- Maximum concurrent cache searches via scheduler (1-10) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches" exact="1"/> <!-- Maximum concurrent live searches via semaphore (1-10) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches" exact="1"/> <!-- Maximum concurrent fallback live searches (1-10) -->
          <!-- Search result limits -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn" exact="20"/> <!-- Maximum trades to return from search (1-100) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize" exact="10"/> <!-- Cache entries validated per chunk (10-200). Smaller = smoother. -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries" exact="50"/> <!-- Maximum cache entries scanned per search (1-200) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare" exact="20"/> <!-- Per-ware offer cap in live search collection (5-100). Ensures ware diversity: every tradeable ware gets up to this many offers. With 50 wares x 20 = ~1000 total offers. Old version used 200 for collection + 20 for matching; combined into single cap. -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch" exact="200"/> <!-- DEPRECATED: No longer used by pipeline (per-ware cap replaced blind total cap). Kept for backward compat. -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare" exact="20"/> <!-- Maximum trades per ware during matching (5-100) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching" exact="20"/> <!-- Maximum offers per ware for matching (5-100) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold" exact="2000"/> <!-- Early exit threshold for matching (100-10000) -->
          <!-- Timing -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$SearchLockTTL" exact="600"/> <!-- Search lock time-to-live in seconds (60-7200). Self-heals stale locks. -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval" exact="100"/> <!-- Live offer slice interval in milliseconds (5-2000) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$BatchChunkSize" exact="5"/> <!-- Matching chunk size (5-20) -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay" exact="10"/> <!-- Delay before GT_Trade_Found signal in ms (10-1000) -->
          <!-- AI script CPU yielding -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$AIYieldInterval" exact="1"/> <!-- Cooperative yield in ms between heavy loop iterations (1-50). Higher = smoother but slower searches. -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs" exact="15"/> <!-- Yield after each miner find_closest_resource / find_resource call (1-100). Higher = smoother frames, slower locate. -->
          <!-- Cache write performance -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize" exact="1"/> <!-- Sorted insertions between yields during cache write (1-20). Higher = faster writes but more per-frame CPU cost. -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize" exact="50"/> <!-- Entries processed between yields during cache cleanup (10-200). Higher = faster cleanup but more per-frame CPU cost. -->
          <!-- Semaphore health -->
          <set_value name="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds" exact="120"/> <!-- Semaphore stale purge age in seconds (60-600) -->
          
          <!-- Number Formatting Settings -->
          <set_value name="global.$GT_GlobalSettings.$NumberFormat" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$NumberFormat.$Format" exact="'german'"/> <!-- 'german' for '.' thousands and ',' decimals (123.456,78), 'english' for ',' thousands and '.' decimals (123,456.78) -->
          <set_value name="global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix" exact="true"/> <!-- Add 'M' suffix for numbers > 999,999 -->
          <set_value name="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" exact="999999"/> <!-- Threshold for M suffix (default: 999,999) -->

          <!-- UI Settings -->
          <set_value name="global.$GT_GlobalSettings.$UI" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride" exact="false"/>

          <!-- Cheat Settings -->
          <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
          <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="'off'"/> <!-- 'off', 'gt', or 'all' -->
          <set_value name="global.$GT_GlobalSettings.$Cheats.$UniverseRevealed" exact="false"/>
          <set_value name="global.$GT_GlobalSettings.$Cheats.$PilotsMaxed" exact="false"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader] Global settings initialized with defaults'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader] Global settings loaded from save'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Signal ValidateSettings to log settings once after restoration completes -->
        <set_value name="global.$GT_SettingsNeedLog" exact="true"/>
        <signal_cue_instantly cue="md.GLX_Lib_Settings_Menu.GT_SyncUICreditsDueState"/>
        
        <!-- Migrate StateHistory for existing ships from old save games -->
        <!-- StateHistory might be null if ship states were created before StateHistory was added -->
        <do_if value="global.$GT_Ship_State?">
          <set_value name="$shipKeys" exact="global.$GT_Ship_State.keys.list"/>
          <set_value name="$migratedCount" exact="0"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
            <do_if value="not $state.$StateHistory? or $state.$StateHistory == null">
              <set_value name="$state.$StateHistory" exact="[]"/>
              <set_value name="$migratedCount" exact="$migratedCount + 1"/>
            </do_if>
          </do_all>
          <do_if value="$migratedCount gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Migrated StateHistory for ' + $migratedCount + ' existing ships'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Text Colors for UI -->
        <set_value name="$TextGreen" exact="'Color.text_success'"/>
        <set_value name="$TextRed" exact="'Color.text_failure'"/>
      </actions>
      
      <cues>
        <!-- Settings Validation and Restoration -->
        <cue name="ValidateSettings" instantiate="true" version="2">
          <conditions>
            <check_any>
              <event_universe_generated/>
              <event_game_loaded/>
              <event_cue_signalled/>
            </check_any>
          </conditions>
          <actions>
            <set_value name="$MissingVarCount" exact="0"/>
            <set_value name="$restored" exact="''"/>
            
            <!-- Validate and restore missing settings -->
            <do_if value="not global.$GT_GlobalSettings?">
              <set_value name="global.$GT_GlobalSettings" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            
            <!-- XP Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$XP?">
              <set_value name="global.$GT_GlobalSettings.$XP" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $XP=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$XP.$AutoTraining?">
              <set_value name="global.$GT_GlobalSettings.$XP.$AutoTraining" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $XP.$AutoTraining=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly?">
              <set_value name="global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $XP.$UseVanillaXPOnly=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$XP.$XPMultiplier?">
              <set_value name="global.$GT_GlobalSettings.$XP.$XPMultiplier" exact="100"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $XP.$XPMultiplier=100'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$XP.$CommanderBonusPercent?">
              <set_value name="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" exact="10"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $XP.$CommanderBonusPercent=10'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$XP.$HardForceTraining?">
              <set_value name="global.$GT_GlobalSettings.$XP.$HardForceTraining" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $XP.$HardForceTraining=true'"/>
            </do_if>
            
            <!-- Fleet Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Fleet?">
              <set_value name="global.$GT_GlobalSettings.$Fleet" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Fleet=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination?">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Fleet.$EnableFleetCoordination=true'"/>
            </do_if>
            <!-- Purge deprecated Fleet settings from old save games -->
            <do_if value="global.$GT_GlobalSettings.$Fleet.$EnableTradeCache?"><remove_value name="global.$GT_GlobalSettings.$Fleet.$EnableTradeCache"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Fleet.$MaxCachedRoutes?"><remove_value name="global.$GT_GlobalSettings.$Fleet.$MaxCachedRoutes"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Fleet.$ZeroTradeCooldown?"><remove_value name="global.$GT_GlobalSettings.$Fleet.$ZeroTradeCooldown"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Fleet.$CacheProfitThreshold?"><remove_value name="global.$GT_GlobalSettings.$Fleet.$CacheProfitThreshold"/></do_if>
            <do_if value="not global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance?">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance" exact="10"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Fleet.$CacheDropoffTolerance=10'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Fleet.$CacheTTL?">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$CacheTTL" exact="300"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Fleet.$CacheTTL=300'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney?">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney" exact="1000"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Fleet.$MinPlayerMoney=1000'"/>
            </do_if>
            <!-- Key-existence via .keys â€” @/typeof fail for stored 0 -->
            <set_value name="$hasIdleParkingKey" exact="false"/>
            <do_all exact="global.$GT_GlobalSettings.$Fleet.keys.count" counter="$fki">
              <set_value name="$fleetKey" exact="global.$GT_GlobalSettings.$Fleet.keys.{$fki}"/>
              <do_if value="$fleetKey == '$IdleParkingReleaseMinutes'">
                <set_value name="$hasIdleParkingKey" exact="true"/>
              </do_if>
            </do_all>
            <do_if value="not $hasIdleParkingKey">
              <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Fleet.$IdleParkingReleaseMinutes=1'"/>
            </do_if>
            <do_else>
              <set_value name="$idleParkingReleaseMinutes" exact="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes"/>
              <do_if value="$idleParkingReleaseMinutes lt 0 or $idleParkingReleaseMinutes gt 60">
                <set_value name="global.$GT_GlobalSettings.$Fleet.$IdleParkingReleaseMinutes" exact="1"/>
              </do_if>
            </do_else>
            
            <!-- Initialize global trade cache system ALWAYS (early initialization to prevent race conditions) -->
            <!-- Even if global fleet coordination is disabled, individual ships may still use cache -->
            <!-- Switch to per-home-sector cache structure -->
            <!-- v6: Trade schema normalization (BuyOffer/SellOffer mapping + price/profit fields) -->
            <do_if value="not global.$GT_TradeCacheVersion? or global.$GT_TradeCacheVersion lt 6">
              <!-- Migrate old cache structure if exists -->
              <do_if value="global.$GT_TradeCache?">
                <!-- Old cache exists - clear it (will be repopulated with new structure) -->
                <remove_value name="global.$GT_TradeCache"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Migrating trade cache to v6 (normalized trade schema)'" chance="100"/>
                </do_if>
              </do_if>
              <!-- Create cache as table indexed by home sector - each home sector has its own list -->
              <set_value name="global.$GT_TradeCache" exact="table[]"/>
              <set_value name="global.$GT_TradeCacheVersion" exact="6"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Trade cache initialized as per-home-sector table (v6 - normalized trade schema)'" chance="100"/>
              </do_if>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <!-- MK4 supply cache: separate pool from MK3 traders (same per-home-sector shape). -->
            <do_if value="not global.$GT_TradeCacheMK4?">
              <set_value name="global.$GT_TradeCacheMK4" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <!-- MK4-2 supply cache: isolated from MK4 v1. -->
            <do_if value="not global.$GT_TradeCacheMK42?">
              <set_value name="global.$GT_TradeCacheMK42" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <!-- GT_TradeCacheIndex removed - no longer needed (cache is already indexed by home sector) -->
            <!-- Old index structure was for flat list - new structure is table indexed by home sector -->
            <!-- Ensure cleanup timestamp always exists -->
            <do_if value="not global.$GT_TradeCacheLastCleanup?">
              <set_value name="global.$GT_TradeCacheLastCleanup" exact="player.age"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            
            <!-- Notification Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Notifications?">
              <set_value name="global.$GT_GlobalSettings.$Notifications" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Notifications=table[]'"/>
            </do_if>
            
            <!-- Remove old notification level setting if it exists (no longer used) -->
            <do_if value="global.$GT_GlobalSettings.$Notifications.$Level?">
              <remove_value name="global.$GT_GlobalSettings.$Notifications.$Level"/>
            </do_if>
            
            <!-- Validate report frequency settings -->
            <do_if value="not global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency?">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Notifications.$SimpleReportFrequency=1'"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency lt 1 or global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency gt 30">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency" exact="1"/>
            </do_if>
            
            <do_if value="not global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency?">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" exact="30"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Notifications.$ComprehensiveReportFrequency=30'"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency lt 1 or global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency gt 60">
              <set_value name="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" exact="30"/>
            </do_if>
            
            <!-- Debug Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Debug?">
              <set_value name="global.$GT_GlobalSettings.$Debug" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Debug=table[]'"/>
            </do_if>
            <!-- Mobile Intel Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$MobileIntel?">
              <set_value name="global.$GT_GlobalSettings.$MobileIntel" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $MobileIntel=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$MobileIntel.$Enable?">
              <set_value name="global.$GT_GlobalSettings.$MobileIntel.$Enable" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $MobileIntel.$Enable=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration?">
              <set_value name="global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration" exact="10min"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $MobileIntel.$SubscriptionDuration=10min'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$MobileIntel.$StationCooldown?">
              <set_value name="global.$GT_GlobalSettings.$MobileIntel.$StationCooldown" exact="60s"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $MobileIntel.$StationCooldown=60s'"/>
            </do_if>
            
            <!-- Threat Avoidance Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$Enabled=false'"/>
            </do_if>
            <!-- Note: RiskTolerance validation removed - now per-ship parameter -->
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$ScanInterval?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$ScanInterval" exact="5s"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$ScanInterval=5s'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry" exact="600s"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$ThreatExpiry=600s'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$HostileRelationThreshold?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$HostileRelationThreshold" exact="-0.20"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$HostileRelationThreshold=-0.20'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$UseDynamicBlacklist=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold" exact="3"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$BlacklistThreshold=3'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions?">
              <set_value name="global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ThreatAvoidance.$BlockEnemyFactions=true'"/>
            </do_if>
            
            <do_if value="not global.$GT_GlobalSettings.$Debug.$EnableDebugLogging?">
              <set_value name="global.$GT_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Debug.$EnableDebugLogging=false'"/>
            </do_if>
            
            <do_if value="not global.$GT_GlobalSettings.$Debug.$DebugLevel?">
              <set_value name="global.$GT_GlobalSettings.$Debug.$DebugLevel" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Debug.$DebugLevel=1'"/>
            </do_if>
            
            <!-- Ship Naming Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$Enabled?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$Enabled" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$Enabled=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$PilotRenamingEnabled=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DisplayXP?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayXP" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DisplayXP=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$XPPosition?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$XPPosition" exact="'suffix'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$XPPosition=suffix'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DisplayRank?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayRank" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DisplayRank=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$RankPosition?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$RankPosition" exact="'suffix'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$RankPosition=suffix'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DisplayLevel=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$LevelPosition?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$LevelPosition" exact="'suffix'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$LevelPosition=suffix'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DisplayStatus=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$StatusPosition?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StatusPosition" exact="'prefix'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$StatusPosition=prefix'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource" exact="'macro.name'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DefaultNameSource=macro.name'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DisplayShipClass=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition" exact="'suffix'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$ShipClassPosition=suffix'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$StateAbbreviations=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$CustomBlacklist?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.$CustomBlacklist" exact="'CB'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$StateAbbreviations.$CustomBlacklist=CB'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$NamingMode?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamingMode" exact="'legacy'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$NamingMode=legacy'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$NamePattern?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamePattern" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$NamePattern=R6-default'"/>
            </do_if>
            <do_elseif value="global.$GT_GlobalSettings.$ShipNaming.$NamePattern == ''">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamePattern" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$NamePattern=blank-to-default'"/>
            </do_elseif>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$DisplayHomeSector=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition?">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition" exact="'prefix'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $ShipNaming.$HomeSectorPosition=prefix'"/>
            </do_if>
            <!-- Vanilla XP: pattern mode is unavailable â€” force legacy -->
            <do_if value="global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly and global.$GT_GlobalSettings.$ShipNaming.$NamingMode == 'pattern'">
              <set_value name="global.$GT_GlobalSettings.$ShipNaming.$NamingMode" exact="'legacy'"/>
            </do_if>
            
            <!-- Auto-Repair Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$AutoRepair?">
              <set_value name="global.$GT_GlobalSettings.$AutoRepair" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $AutoRepair=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$AutoRepair.$Enabled?">
              <set_value name="global.$GT_GlobalSettings.$AutoRepair.$Enabled" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $AutoRepair.$Enabled=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$AutoRepair.$HullThreshold?">
              <set_value name="global.$GT_GlobalSettings.$AutoRepair.$HullThreshold" exact="95"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $AutoRepair.$HullThreshold=95'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$AutoRepair.$MinPilotLevel?">
              <set_value name="global.$GT_GlobalSettings.$AutoRepair.$MinPilotLevel" exact="12"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $AutoRepair.$MinPilotLevel=12'"/>
            </do_if>
            
            <!-- Galaxy Miner Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Miner?">
              <set_value name="global.$GT_GlobalSettings.$Miner" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Miner=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel?">
              <set_value name="global.$GT_GlobalSettings.$Miner.$ScaleResourceProbeScanByPilotLevel" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Miner.$ScaleResourceProbeScanByPilotLevel=false'"/>
            </do_if>
            
            <!-- Ship Modifications Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Modifications?">
              <set_value name="global.$GT_GlobalSettings.$Modifications" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Modifications=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Modifications.$Enabled?">
              <set_value name="global.$GT_GlobalSettings.$Modifications.$Enabled" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Modifications.$Enabled=false'"/>
            </do_if>
            
            <!-- Trading Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Trading?">
              <set_value name="global.$GT_GlobalSettings.$Trading" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Trading=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Trading.$ShipProximityWeight?">
              <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="0.04"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Trading.$ShipProximityWeight=0.04'"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight lt 0">
              <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="0"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight gt 1">
              <set_value name="global.$GT_GlobalSettings.$Trading.$ShipProximityWeight" exact="1"/>
            </do_if>
            
            <!-- Performance Settings Validation (post AI-migration) -->
            <do_if value="not global.$GT_GlobalSettings.$Performance?">
              <set_value name="global.$GT_GlobalSettings.$Performance" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Performance=table[]'"/>
            </do_if>

            <!-- Migration cleanup: remove legacy settings from old saves -->
            <do_if value="global.$GT_GlobalSettings.$Performance.$BatchProcessingDelay?"><remove_value name="global.$GT_GlobalSettings.$Performance.$BatchProcessingDelay"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$ValidationDelay?"><remove_value name="global.$GT_GlobalSettings.$Performance.$ValidationDelay"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxConcurrentSearches?"><remove_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentSearches"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$BatchBackpressureSoftThreshold?"><remove_value name="global.$GT_GlobalSettings.$Performance.$BatchBackpressureSoftThreshold"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$BatchBackpressureHardThreshold?"><remove_value name="global.$GT_GlobalSettings.$Performance.$BatchBackpressureHardThreshold"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$SectorsPerSlice?"><remove_value name="global.$GT_GlobalSettings.$Performance.$SectorsPerSlice"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$HomeRefreshCooldown?"><remove_value name="global.$GT_GlobalSettings.$Performance.$HomeRefreshCooldown"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$CacheMissCooldownBase?"><remove_value name="global.$GT_GlobalSettings.$Performance.$CacheMissCooldownBase"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$SchedulerTickInterval?"><remove_value name="global.$GT_GlobalSettings.$Performance.$SchedulerTickInterval"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxCacheQueriesPerTick?"><remove_value name="global.$GT_GlobalSettings.$Performance.$MaxCacheQueriesPerTick"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxSearchContinuationsPerTick?"><remove_value name="global.$GT_GlobalSettings.$Performance.$MaxSearchContinuationsPerTick"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxShipsPerTick?"><remove_value name="global.$GT_GlobalSettings.$Performance.$MaxShipsPerTick"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxItemsPerTick?"><remove_value name="global.$GT_GlobalSettings.$Performance.$MaxItemsPerTick"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxWakePerTick?"><remove_value name="global.$GT_GlobalSettings.$Performance.$MaxWakePerTick"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$QueueStaleThresholdSeconds?"><remove_value name="global.$GT_GlobalSettings.$Performance.$QueueStaleThresholdSeconds"/></do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$FailedTradeExpirationSeconds?"><remove_value name="global.$GT_GlobalSettings.$Performance.$FailedTradeExpirationSeconds"/></do_if>
            <!-- Migrate LiveOfferAppendChunkSize -> MaxOffersPerSearch -->
            <do_if value="global.$GT_GlobalSettings.$Performance.$LiveOfferAppendChunkSize? and not global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch" exact="global.$GT_GlobalSettings.$Performance.$LiveOfferAppendChunkSize"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$LiveOfferAppendChunkSize?"><remove_value name="global.$GT_GlobalSettings.$Performance.$LiveOfferAppendChunkSize"/></do_if>

            <!-- Concurrency defaults + validation -->
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches" exact="5"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Performance.$MaxConcurrentCacheSearches=5'"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches lt 1 or global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches gt 10">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches" exact="5"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Performance.$MaxConcurrentLiveSearches=1'"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches lt 1 or global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches gt 10">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches" exact="1"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Performance.$MaxConcurrentFallbackSearches=1'"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches lt 1 or global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches gt 10">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches" exact="1"/>
            </do_if>

            <!-- Search result limits defaults + validation -->
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn" exact="20"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn lt 1 or global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn gt 100">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn" exact="20"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize" exact="10"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries" exact="50"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <!-- Migrate legacy default of 5 to 50 -->
            <do_if value="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries? and global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries == 5">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries" exact="50"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries lt 1 or global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries gt 200">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries" exact="50"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare" exact="20"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare lt 5 or global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare gt 100">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare" exact="20"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch" exact="200"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch lt 50 or global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch gt 2000">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch" exact="200"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare" exact="20"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare lt 5 or global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare gt 100">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare" exact="20"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching" exact="20"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching lt 5 or global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching gt 100">
              <set_value name="global.$GT_GlobalSettings.$Performance.$MaxOffersPerWareForMatching" exact="20"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold" exact="2000"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <!-- Migration: old defaults to new -->
            <do_if value="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold == 1000 or global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold == 800">
              <set_value name="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold" exact="2000"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold lt 100 or global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold gt 10000">
              <set_value name="global.$GT_GlobalSettings.$Performance.$EarlyExitThreshold" exact="2000"/>
            </do_if>

            <!-- Timing defaults + validation -->
            <do_if value="not global.$GT_GlobalSettings.$Performance.$SearchLockTTL?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$SearchLockTTL" exact="600"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$SearchLockTTL lt 60 or global.$GT_GlobalSettings.$Performance.$SearchLockTTL gt 7200">
              <set_value name="global.$GT_GlobalSettings.$Performance.$SearchLockTTL" exact="600"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval" exact="100"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval lt 5 or global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval gt 2000">
              <set_value name="global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval" exact="100"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$BatchChunkSize?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$BatchChunkSize" exact="5"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$BatchChunkSize lt 5 or global.$GT_GlobalSettings.$Performance.$BatchChunkSize gt 20">
              <set_value name="global.$GT_GlobalSettings.$Performance.$BatchChunkSize" exact="5"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay" exact="10"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay lt 10 or global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay gt 1000">
              <set_value name="global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay" exact="10"/>
            </do_if>

            <!-- AI script CPU yielding -->
            <do_if value="not global.$GT_GlobalSettings.$Performance.$AIYieldInterval?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$AIYieldInterval" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$AIYieldInterval lt 1 or global.$GT_GlobalSettings.$Performance.$AIYieldInterval gt 50">
              <set_value name="global.$GT_GlobalSettings.$Performance.$AIYieldInterval" exact="1"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs" exact="15"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs lt 1 or global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs gt 100">
              <set_value name="global.$GT_GlobalSettings.$Performance.$ResourceSearchYieldMs" exact="15"/>
            </do_if>

            <!-- Cache write performance -->
            <do_if value="not global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize" exact="1"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize lt 1 or global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize gt 20">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize" exact="1"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize" exact="50"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize lt 10 or global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize gt 200">
              <set_value name="global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize" exact="50"/>
            </do_if>

            <!-- Semaphore health -->
            <do_if value="not global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
              <set_value name="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds" exact="120"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <!-- Migrate old default of 300 to new default of 120 -->
            <do_if value="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds == 300">
              <set_value name="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds" exact="120"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds lt 60 or global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds gt 600">
              <set_value name="global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds" exact="120"/>
            </do_if>
            
            <!-- Number Format Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$NumberFormat?">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $NumberFormat=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$NumberFormat.$Format?">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat.$Format" exact="'german'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $NumberFormat.$Format=german'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix?">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $NumberFormat.$UseMSuffix=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold?">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" exact="999999"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $NumberFormat.$MSuffixThreshold=999999'"/>
            </do_if>
            <!-- Validate format value (must be 'german' or 'english') -->
            <do_if value="global.$GT_GlobalSettings.$NumberFormat.$Format != 'german' and global.$GT_GlobalSettings.$NumberFormat.$Format != 'english'">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat.$Format" exact="'german'"/>
            </do_if>
            <!-- Validate MSuffixThreshold range (1000-999999999) -->
            <do_if value="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold lt 1000">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" exact="999999"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold gt 999999999">
              <set_value name="global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" exact="999999"/>
            </do_if>

            <!-- UI Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$UI?">
              <set_value name="global.$GT_GlobalSettings.$UI" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $UI=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride?">
              <set_value name="global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $UI.$UseGTCreditsDueOverride=false'"/>
            </do_if>

            <!-- Cheat Settings Validation -->
            <do_if value="not global.$GT_GlobalSettings.$Cheats?">
              <set_value name="global.$GT_GlobalSettings.$Cheats" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Cheats=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope?">
              <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="'off'"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Cheats.$InvulnerabilityScope=off'"/>
            </do_if>
            <do_else>
              <set_value name="$cheatScope" exact="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope"/>
              <do_if value="$cheatScope != 'off' and $cheatScope != 'gt' and $cheatScope != 'all'">
                <set_value name="global.$GT_GlobalSettings.$Cheats.$InvulnerabilityScope" exact="'off'"/>
                <set_value name="$MissingVarCount" exact="1" operation="add"/>
                <set_value name="$restored" exact="$restored + ' $Cheats.$InvulnerabilityScope=off(invalid)'"/>
              </do_if>
            </do_else>
            <do_if value="not global.$GT_GlobalSettings.$Cheats.$UniverseRevealed?">
              <set_value name="global.$GT_GlobalSettings.$Cheats.$UniverseRevealed" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Cheats.$UniverseRevealed=false'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$Cheats.$PilotsMaxed?">
              <set_value name="global.$GT_GlobalSettings.$Cheats.$PilotsMaxed" exact="false"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $Cheats.$PilotsMaxed=false'"/>
            </do_if>
            
            <!-- CRITICAL: Validate BOTH config tables exist -->
            <do_if value="not global.$GT_Config.$Defense?">
              <set_value name="global.$GT_Config.$Defense" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            <do_if value="not global.$GT_Config.$Defense.$Enabled?">
              <set_value name="global.$GT_Config.$Defense.$Enabled" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
            </do_if>
            
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment" exact="table[]"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment=table[]'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$Enabled=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold" exact="50"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$CountermeasureThreshold=50'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold" exact="70"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$UnifiedThreshold=70'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile" exact="2"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$BalanceProfile=2'"/>
            </do_if>
            <!-- Individual equipment type toggles -->
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$RestockCountermeasures?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockCountermeasures" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$RestockCountermeasures=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$RestockDefenseDrones=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$RestockTradeDrones=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$RestockLaserTowers=true'"/>
            </do_if>
            <do_if value="not global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones?">
              <set_value name="global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones" exact="true"/>
              <set_value name="$MissingVarCount" exact="1" operation="add"/>
              <set_value name="$restored" exact="$restored + ' $DefensiveEquipment.$RestockRepairDrones=true'"/>
            </do_if>
            
            <do_if value="$MissingVarCount gt 0">
              <debug_text text="'[GalaxyTrader MK3] Restored ' + $MissingVarCount + ' missing global settings:' + $restored" chance="100"/>
            </do_if>
            
            <!-- Log final settings once per game load (multiple ValidateSettings instances fire â€” only the first one logs) -->
            <do_if value="@global.$GT_SettingsNeedLog">
              <set_value name="global.$GT_SettingsNeedLog" exact="false"/>

              <debug_text text="'[GalaxyTrader MK3] SETTINGS.Fleet: Coordination=' + @global.$GT_GlobalSettings.$Fleet.$EnableFleetCoordination + ' CacheDropoffTolerance=' + @global.$GT_GlobalSettings.$Fleet.$CacheDropoffTolerance + ' CacheTTL=' + @global.$GT_GlobalSettings.$Fleet.$CacheTTL + ' MinPlayerMoney=' + @global.$GT_GlobalSettings.$Fleet.$MinPlayerMoney" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.XP: UseVanillaXPOnly=' + @global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly + ' AutoTraining=' + @global.$GT_GlobalSettings.$XP.$AutoTraining + ' HardForceTraining=' + @global.$GT_GlobalSettings.$XP.$HardForceTraining + ' XPMultiplier=' + @global.$GT_GlobalSettings.$XP.$XPMultiplier + ' MinTrainingDistance=' + @global.$GT_GlobalSettings.$XP.$MinTrainingDistance + ' TrainingCooldown=' + @global.$GT_GlobalSettings.$XP.$TrainingCooldown + ' CommanderBonusPercent=' + @global.$GT_GlobalSettings.$XP.$CommanderBonusPercent" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.Performance: MaxConcurrentLive=' + @global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches + ' MaxConcurrentFallback=' + @global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches + ' MaxTradesToReturn=' + @global.$GT_GlobalSettings.$Performance.$MaxTradesToReturn + ' CacheChunkSize=' + @global.$GT_GlobalSettings.$Performance.$CacheQueryChunkSize + ' CacheMaxEntries=' + @global.$GT_GlobalSettings.$Performance.$CacheQueryMaxEntries + ' MaxOffersPerSearch=' + @global.$GT_GlobalSettings.$Performance.$MaxOffersPerSearch" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.Performance2: MaxOffersPerWare=' + @global.$GT_GlobalSettings.$Performance.$MaxOffersPerWare + ' MaxTradesPerWare=' + @global.$GT_GlobalSettings.$Performance.$MaxTradesPerWare + ' BatchChunkSize=' + @global.$GT_GlobalSettings.$Performance.$BatchChunkSize + ' SearchLockTTL=' + @global.$GT_GlobalSettings.$Performance.$SearchLockTTL + ' LiveOfferSliceInterval=' + @global.$GT_GlobalSettings.$Performance.$LiveOfferSliceInterval + ' AIYield=' + @global.$GT_GlobalSettings.$Performance.$AIYieldInterval + 'ms StaleThreshold=' + @global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds + ' TradeFoundDelay=' + @global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay + ' CacheWriteBatch=' + @global.$GT_GlobalSettings.$Performance.$CacheWriteBatchSize + ' CacheCleanupBatch=' + @global.$GT_GlobalSettings.$Performance.$CacheCleanupBatchSize" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.ThreatAvoidance: Enabled=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled + ' ScanInterval=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$ScanInterval + ' ThreatExpiry=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry + ' HostileRelationThreshold=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$HostileRelationThreshold + ' UseDynamicBlacklist=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist + ' BlockEnemyFactions=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions + ' BlacklistThreshold=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.Notifications: ShowXPGains=' + @global.$GT_GlobalSettings.$Notifications.$ShowXPGains + ' ShowTradeResults=' + @global.$GT_GlobalSettings.$Notifications.$ShowTradeResults + ' ShowFleetStatus=' + @global.$GT_GlobalSettings.$Notifications.$ShowFleetStatus + ' SimpleReportFreq=' + @global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency + ' ComprehensiveReportFreq=' + @global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.Debug: EnableDebugLogging=' + @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging + ' DebugLevel=' + @global.$GT_GlobalSettings.$Debug.$DebugLevel + ' TradeEvaluation=' + @global.$GT_GlobalSettings.$Debug.$TradeEvaluation" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.AutoRepair: Enabled=' + @global.$GT_GlobalSettings.$AutoRepair.$Enabled + ' HullThreshold=' + @global.$GT_GlobalSettings.$AutoRepair.$HullThreshold + ' MinPilotLevel=' + @global.$GT_GlobalSettings.$AutoRepair.$MinPilotLevel" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.MobileIntel: Enable=' + @global.$GT_GlobalSettings.$MobileIntel.$Enable + ' SubscriptionDuration=' + @global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration + ' StationCooldown=' + @global.$GT_GlobalSettings.$MobileIntel.$StationCooldown" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.Modifications: Enabled=' + @global.$GT_GlobalSettings.$Modifications.$Enabled" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.ShipNaming: Enabled=' + @global.$GT_GlobalSettings.$ShipNaming.$Enabled + ' NameSource=' + @global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.NumberFormat: Format=' + @global.$GT_GlobalSettings.$NumberFormat.$Format + ' UseMSuffix=' + @global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix + ' MSuffixThreshold=' + @global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold" chance="100"/>
              <debug_text text="'[GalaxyTrader MK3] SETTINGS.UI: UseGTCreditsDueOverride=' + @global.$GT_GlobalSettings.$UI.$UseGTCreditsDueOverride" chance="100"/>

              <!-- Snapshot of currently blacklisted sectors -->
              <do_if value="global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.keys.count gt 0">
                <set_value name="$blSectors" exact="''"/>
                <set_value name="$blCount" exact="global.$GT_ThreatIntelligence.keys.count"/>
                <do_all exact="$blCount" counter="$blIdx">
                  <set_value name="$blSector" exact="global.$GT_ThreatIntelligence.keys.list.{$blIdx}"/>
                  <set_value name="$blThreat" exact="global.$GT_ThreatIntelligence.{$blSector}"/>
                  <set_value name="$blSectors" exact="$blSectors + ' ' + @$blSector.knownname + '(L' + @$blThreat.$ThreatLevel + ')'"/>
                </do_all>
                <debug_text text="'[GalaxyTrader MK3] BLACKLISTED_SECTORS: Count=' + $blCount + ' |' + $blSectors" chance="100"/>
              </do_if>
              <do_else>
                <debug_text text="'[GalaxyTrader MK3] BLACKLISTED_SECTORS: Count=0'" chance="100"/>
              </do_else>
            </do_if>

            <signal_cue_instantly cue="md.GLX_Lib_Settings_Menu.GT_SyncUICreditsDueState"/>
          </actions>
        </cue>
        
      </cues>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_HomeFleetProfile" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Event-driven rebuild for MK3 home-sector fleet-min cargo profiles (cache-refresh totalvolume). -->
    <cue name="HandleProfileUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_HomeFleetProfile_Update'"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <run_actions ref="md.GT_HomeFleetProfile.GT_RebuildHomeFleetCargoProfile">
          <param name="homeSector" value="if $params? and $params.$HomeSector? then @$params.$HomeSector else null"/>
          <param name="alsoHomeSector" value="if $params? and $params.$AlsoHomeSector? then @$params.$AlsoHomeSector else null"/>
        </run_actions>
      </actions>
    </cue>

    <!-- One-shot rebuild after load so profiles match the full MK3 cohort (F13). -->
    <cue name="RebuildAllOnGameLoad" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_player_created/>
          <event_game_loaded/>
        </check_any>
      </conditions>
      <delay exact="2s"/>
      <actions>
        <run_actions ref="md.GT_HomeFleetProfile.GT_RebuildHomeFleetCargoProfile">
          <param name="homeSector" value="null"/>
          <param name="alsoHomeSector" value="null"/>
        </run_actions>
      </actions>
    </cue>

    <cue name="HandleProfileOnOrderAbort" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_Order_Aborted'"/>
      </conditions>
      <actions>
        <set_value name="$abortShip" exact="if event.param2? and event.param2.$Ship? then @event.param2.$Ship else null"/>
        <set_value name="$abortHome" exact="null"/>
        <do_if value="$abortShip? and $abortShip.exists">
          <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$abortHome">
            <param name="ship" value="$abortShip"/>
          </run_actions>
        </do_if>
        <run_actions ref="md.GT_HomeFleetProfile.GT_RebuildHomeFleetCargoProfile">
          <param name="homeSector" value="$abortHome"/>
          <param name="alsoHomeSector" value="null"/>
        </run_actions>
      </actions>
    </cue>

    <library name="GT_ShipIsMK3Service" purpose="run_actions">
    <params>
      <param name="ship"/>
    </params>
    <actions>
      <do_if value="not $ship? or not $ship.exists or not $ship.defaultorder?">
        <return value="false"/>
      </do_if>
      <do_if value="@$ship.defaultorder.id == 'GalaxyTraderMK3'">
        <return value="true"/>
      </do_if>
      <do_if value="@$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.exists and $ship.commander.defaultorder?">
        <do_if value="@$ship.commander.defaultorder.id == 'GalaxyTraderMK3'">
          <return value="true"/>
        </do_if>
        <do_if value="@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'">
          <return value="true"/>
        </do_if>
      </do_if>
      <return value="false"/>
    </actions>
  </library>

  <library name="GT_GetMK3EffectiveCargoTarget" purpose="run_actions">
    <params>
      <param name="ship"/>
    </params>
    <actions>
      <set_value name="$pct" exact="80"/>
      <set_value name="$order" exact="if $ship? and $ship.defaultorder? then $ship.defaultorder else null"/>
      <do_if value="$ship? and $ship.commander? and $ship.commander.exists and $ship.commander != $ship and $ship.commander.defaultorder?">
        <set_value name="$order" exact="$ship.commander.defaultorder"/>
      </do_if>
      <do_if value="$order?">
        <do_if value="@$order.id == 'GalaxyTraderMK3' and $order.$cargotarget?">
          <set_value name="$pct" exact="$order.$cargotarget"/>
        </do_if>
        <do_elseif value="@$order.id == 'Assist' and $order.$baseorder? and @$order.$baseorder.id == 'GalaxyTraderMK3' and $order.$baseorder.$cargotarget?">
          <set_value name="$pct" exact="$order.$baseorder.$cargotarget"/>
        </do_elseif>
        <do_elseif value="@$order.id == 'Assist' and $order.$cargotarget?">
          <set_value name="$pct" exact="$order.$cargotarget"/>
        </do_elseif>
      </do_if>
      <set_value name="$pct" exact="[10, [$pct, 100].min].max"/>
      <return value="$pct"/>
    </actions>
  </library>

  <library name="GT_RebuildHomeFleetCargoProfile" purpose="run_actions">
    <params>
      <param name="homeSector" default="null" comment="Rebuild this home sector only; null = rebuild all cohort homes"/>
      <param name="alsoHomeSector" default="null" comment="Optional second home bucket (e.g. after home change)"/>
    </params>
    <actions>
      <do_if value="not global.$GT_HomeFleetCargoProfile?">
        <set_value name="global.$GT_HomeFleetCargoProfile" exact="table[]"/>
      </do_if>

      <set_value name="$homesToRebuild" exact="[]"/>
      <do_if value="$homeSector? and $homeSector.exists">
        <append_to_list name="$homesToRebuild" exact="$homeSector"/>
      </do_if>
      <do_if value="$alsoHomeSector? and $alsoHomeSector.exists">
        <set_value name="$alsoAlready" exact="false"/>
        <do_all exact="$homesToRebuild.count" counter="$hck">
          <do_if value="$homesToRebuild.{$hck} == $alsoHomeSector">
            <set_value name="$alsoAlready" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        <do_if value="not $alsoAlready">
          <append_to_list name="$homesToRebuild" exact="$alsoHomeSector"/>
        </do_if>
      </do_if>

      <find_ship_by_true_owner name="$fleetShips" faction="faction.player" space="player.galaxy" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="true"/>

      <do_if value="$homesToRebuild.count == 0">
        <set_value name="$homesSeen" exact="table[]"/>
        <do_all exact="$fleetShips.count" counter="$fsi">
          <set_value name="$fs" exact="$fleetShips.{$fsi}"/>
          <run_actions ref="md.GT_HomeFleetProfile.GT_ShipIsMK3Service" result="$fsIsMk3">
            <param name="ship" value="$fs"/>
          </run_actions>
          <do_if value="not $fsIsMk3">
            <continue/>
          </do_if>
          <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$fsHome">
            <param name="ship" value="$fs"/>
          </run_actions>
          <do_if value="$fsHome? and $fsHome.exists and not $homesSeen.{$fsHome}?">
            <set_value name="$homesSeen.{$fsHome}" exact="true"/>
            <append_to_list name="$homesToRebuild" exact="$fsHome"/>
          </do_if>
        </do_all>
      </do_if>

      <do_all exact="$homesToRebuild.count" counter="$hi">
        <set_value name="$h" exact="$homesToRebuild.{$hi}"/>
        <set_value name="$minContainer" exact="null"/>
        <set_value name="$minSolid" exact="null"/>
        <set_value name="$minLiquid" exact="null"/>
        <set_value name="$shipCount" exact="0"/>

        <do_all exact="$fleetShips.count" counter="$si">
          <set_value name="$s" exact="$fleetShips.{$si}"/>
          <run_actions ref="md.GT_HomeFleetProfile.GT_ShipIsMK3Service" result="$isMk3">
            <param name="ship" value="$s"/>
          </run_actions>
          <do_if value="not $isMk3">
            <continue/>
          </do_if>
          <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$sHome">
            <param name="ship" value="$s"/>
          </run_actions>
          <do_if value="not $sHome? or not $sHome.exists or $sHome != $h">
            <continue/>
          </do_if>

          <run_actions ref="md.GT_HomeFleetProfile.GT_GetMK3EffectiveCargoTarget" result="$pct">
            <param name="ship" value="$s"/>
          </run_actions>
          <set_value name="$shipCount" operation="add"/>

          <set_value name="$capContainer" exact="$s.cargo.capacity.container + $s.cargo.capacity.universal"/>
          <set_value name="$reqContainer" exact="($capContainer * $pct / 100)i"/>
          <do_if value="not $minContainer? or $reqContainer lt $minContainer">
            <set_value name="$minContainer" exact="$reqContainer"/>
          </do_if>

          <set_value name="$capSolid" exact="$s.cargo.capacity.solid + $s.cargo.capacity.universal"/>
          <set_value name="$reqSolid" exact="($capSolid * $pct / 100)i"/>
          <do_if value="not $minSolid? or $reqSolid lt $minSolid">
            <set_value name="$minSolid" exact="$reqSolid"/>
          </do_if>

          <set_value name="$capLiquid" exact="$s.cargo.capacity.liquid + $s.cargo.capacity.universal"/>
          <set_value name="$reqLiquid" exact="($capLiquid * $pct / 100)i"/>
          <do_if value="not $minLiquid? or $reqLiquid lt $minLiquid">
            <set_value name="$minLiquid" exact="$reqLiquid"/>
          </do_if>
        </do_all>

        <do_if value="$shipCount gt 0">
          <set_value name="global.$GT_HomeFleetCargoProfile.{$h}" exact="table[
            $MinRequired = table[
              $container = if $minContainer? then $minContainer else 1,
              $solid = if $minSolid? then $minSolid else 1,
              $liquid = if $minLiquid? then $minLiquid else 1
            ],
            $ShipCount = $shipCount,
            $UpdatedAt = player.age
          ]"/>
        </do_if>
        <do_else>
          <do_if value="global.$GT_HomeFleetCargoProfile.{$h}?">
            <remove_value name="global.$GT_HomeFleetCargoProfile.{$h}"/>
          </do_if>
        </do_else>
      </do_all>
    </actions>
  </library>

  </cues>

</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_InfoMenu_Loader" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  
  <cues>
    <!-- PilotIdMap wire key: MD cannot stringify full uint64 NPC seeds &gt;2^53 without FP rounding.
         Split into 32-bit halves (exact small integers), Lua reconstructs decimal for MapMenu match. -->
    <library name="Pilot_Seed_U64Wire_ForPilotIdMap" purpose="run_actions">
      <params>
        <param name="pilot" comment="NPC pilot entity"/>
      </params>
      <actions>
        <set_value name="$result" exact="''"/>
        <do_if value="$pilot? and $pilot.exists and $pilot.seed?">
          <!-- Normalise low 32-bit part to unsigned range first.
               For signed seeds, MD modulo can be negative; without this, hi is off by +1 and decoded u64 shifts by +2^32. -->
          <set_value name="$lo32" exact="$pilot.seed % 4294967296L"/>
          <do_if value="$lo32 lt 0">
            <set_value name="$lo32" exact="$lo32 + 4294967296L"/>
          </do_if>
          <set_value name="$hi32" exact="(($pilot.seed - $lo32) / 4294967296L)i"/>
          <set_value name="$result" exact="'u64p:' + $hi32 + ':' + $lo32"/>
        </do_if>
        <return value="$result"/>
      </actions>
    </library>

    <!-- DISABLED: UI Lua files are disabled, so don't try to load them -->
    <!-- Load Lua file via sn_mod_support_apis Lua Loader -->
    <!-- <cue name="Load_PilotDataBridge" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'Lua_Loader'" control="'Ready'" />
      </conditions>
      <actions>
        <raise_lua_event 
          name="'Lua_Loader.Load'" 
          param="'extensions.galaxy_trader.ui.gt_pilot_data_bridge'"/>
        
        <debug_text text="'[GT Info Menu] Loading pilot data bridge via Lua Loader...'" chance="100"/>
      </actions>
    </cue> -->
    
    <!-- Verify Lua module loaded successfully -->
    <!-- <cue name="Verify_PilotDataBridge" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'Lua_Loader'" 
          control="'Loaded extensions.galaxy_trader.ui.gt_pilot_data_bridge'" />
      </conditions>
      <actions>
        <debug_text text="'[GT Info Menu] Pilot data bridge loaded successfully!'" chance="100"/>
      </actions>
    </cue> -->
    
    <!-- Send pilot data when UI requests it -->
    <cue name="HandlePilotDataRequest" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'gt_pilot_data_bridge'" control="'RequestPilotData'" />
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Info Menu] Received request for pilot data from UI'" chance="100"/>
        </do_if>
        <signal_cue_instantly cue="SendPilotData" />
      </actions>
    </cue>
    
    <!-- Auto-send pilot data when ships are registered -->
    <!-- <cue name="AutoRefreshOnShipRegistration" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Register_Ship'" />
      </conditions>
      <delay exact="100ms"/>
      <actions>
        <debug_text text="'[GT Info Menu] Ship registered - auto-refreshing pilot data'" chance="100"/>
        <signal_cue_instantly cue="SendPilotData" />
      </actions>
    </cue> -->
    
    <!-- Collect and send pilot data to Lua -->
    <cue name="SendPilotData" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$pilotDataString" exact="''"/>
        <set_value name="$pilotCount" exact="0"/>
        <!-- Build ID-based map for UI crew highlighting (strict unique pilot id). -->
        <set_value name="$gtPilotIdMapData" exact="''"/>
        <set_value name="$gtPilotIdMapCount" exact="0"/>
        <set_value name="$gtPilotIdMapFromTemplate" exact="0"/>
        <set_value name="$gtPilotIdMapFromPilotIdcode" exact="0"/>
        <set_value name="$gtPilotIdMapFromPilotRef" exact="0"/>
        <set_value name="$gtPilotIdMapFromStable" exact="0"/>
        
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_Ships and global.$GT_Pilots exist -->
        <!-- FIX: Use @ operator to safely access keys.count -->
        <set_value name="$shipsKeysCount" exact="@global.$GT_Ships.keys.count"/>
        <set_value name="$pilotsKeysCount" exact="@global.$GT_Pilots.keys.count"/>
        <do_if value="not $shipsKeysCount? or not $pilotsKeysCount? or $shipsKeysCount == 0 or $pilotsKeysCount == 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Info Menu] GT systems initialized but no data yet'" chance="100"/>
          </do_if>
          <raise_lua_event name="'GT_PilotData.Update'" param="''"/>
          
          <!-- Still send GT pilot maps so crew highlight works for paused pilots. -->
          <set_value name="$gtNameData" exact="''"/>
          <set_value name="$gtNameMapData" exact="''"/>
          <set_value name="$gtPilotIdMapData" exact="''"/>
          <set_value name="$gtNameCount" exact="0"/>
          <set_value name="$gtPilotIdMapCount" exact="0"/>
          <set_value name="$gtPilotIdMapFromTemplate" exact="0"/>
          <set_value name="$gtPilotIdMapFromPilotIdcode" exact="0"/>
          <set_value name="$gtPilotIdMapFromPilotRef" exact="0"/>
          <set_value name="$gtPilotIdMapFromStable" exact="0"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
            <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
            <do_all exact="$pilotKeys.count" counter="$ni">
              <set_value name="$pilotObj" exact="$pilotKeys.{$ni}"/>
              <set_value name="$nameToAdd" exact="''"/>
              <do_if value="global.$GT_Pilots.{$pilotObj}? and global.$GT_Pilots.{$pilotObj}.$OriginalPilotName? and global.$GT_Pilots.{$pilotObj}.$OriginalPilotName != ''">
                <set_value name="$nameToAdd" exact="global.$GT_Pilots.{$pilotObj}.$OriginalPilotName"/>
              </do_if>
              <do_elseif value="global.$GT_Pilots.{$pilotObj}? and global.$GT_Pilots.{$pilotObj}.$PilotName? and global.$GT_Pilots.{$pilotObj}.$PilotName != ''">
                <set_value name="$nameToAdd" exact="global.$GT_Pilots.{$pilotObj}.$PilotName"/>
              </do_elseif>
              <do_elseif value="$pilotObj and $pilotObj.name?">
                <set_value name="$nameToAdd" exact="$pilotObj.name"/>
              </do_elseif>
              
              <do_if value="$nameToAdd != ''">
                <set_value name="$pilotLevelForTag" exact="if global.$GT_Pilots.{$pilotObj}.$Level? then global.$GT_Pilots.{$pilotObj}.$Level else 1"/>
                <set_value name="$taggedNameToAdd" exact="'(T:' + $pilotLevelForTag + ') ' + $nameToAdd"/>
                <do_if value="$gtNameCount gt 0">
                  <set_value name="$gtNameData" exact="$gtNameData + '||'"/>
                  <set_value name="$gtNameMapData" exact="$gtNameMapData + '||'"/>
                </do_if>
                <set_value name="$gtNameData" exact="$gtNameData + $nameToAdd"/>
                <set_value name="$gtNameMapData" exact="$gtNameMapData + $nameToAdd + '|' + $taggedNameToAdd"/>
                <set_value name="$gtNameCount" operation="add"/>
              </do_if>

              <do_if value="$nameToAdd != '' and global.$GT_Pilots.{$pilotObj}?">
                <set_value name="$pOD0" exact="global.$GT_Pilots.{$pilotObj}"/>
                <do_if value="$pOD0.$StableIdentity? and $pOD0.$StableIdentity != ''">
                  <do_if value="$gtPilotIdMapCount gt 0">
                    <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                  </do_if>
                  <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pOD0.$StableIdentity + '|' + $taggedNameToAdd"/>
                  <set_value name="$gtPilotIdMapCount" operation="add"/>
                  <set_value name="$gtPilotIdMapFromStable" operation="add"/>
                </do_if>
                <do_if value="$pilotObj.seed?">
                  <run_actions ref="Pilot_Seed_U64Wire_ForPilotIdMap" result="$pilotSeedWire">
                    <param name="pilot" value="$pilotObj"/>
                  </run_actions>
                  <do_if value="$pilotSeedWire != ''">
                    <do_if value="$gtPilotIdMapCount gt 0">
                      <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                    </do_if>
                    <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilotSeedWire + '|' + $taggedNameToAdd"/>
                    <set_value name="$gtPilotIdMapCount" operation="add"/>
                    <set_value name="$gtPilotIdMapFromPilotRef" operation="add"/>
                  </do_if>
                </do_if>
                <do_if value="$pilotObj.idcode? and $pilotObj.idcode != ''">
                  <do_if value="$gtPilotIdMapCount gt 0">
                    <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                  </do_if>
                  <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilotObj.idcode + '|' + $taggedNameToAdd"/>
                  <set_value name="$gtPilotIdMapCount" operation="add"/>
                  <set_value name="$gtPilotIdMapFromPilotIdcode" operation="add"/>
                </do_if>
                <!-- npctemplate is NOT unique across pilots â€” do not add to PilotIdMap (collisions overwrote per-seed keys). -->
              </do_if>
            </do_all>
          </do_if>
          <raise_lua_event name="'GT_PilotNameIndex.Update'" param="$gtNameData"/>
          <raise_lua_event name="'GT_PilotNameMap.Update'" param="$gtNameMapData"/>
          <!-- Do not send empty PilotIdMap â€” Lua would wipe cached keys (crew highlight flicker). -->
          <do_if value="$gtPilotIdMapCount gt 0">
            <raise_lua_event name="'GT_PilotIdMap.Update'" param="$gtPilotIdMapData"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Collect config flags for conditional UI controls -->
          <set_value name="$autoTraining" exact="1"/>
          <do_if value="global.$GT_Config? and global.$GT_Config.$Training? and global.$GT_Config.$Training.$AutomaticTraining?">
            <set_value name="$autoTraining" exact="global.$GT_Config.$Training.$AutomaticTraining"/>
          </do_if>
          
          <set_value name="$autoRepair" exact="1"/>
          <do_if value="global.$GT_Config? and global.$GT_Config.$Maintenance? and global.$GT_Config.$Maintenance.$AutoRepair?">
            <set_value name="$autoRepair" exact="global.$GT_Config.$Maintenance.$AutoRepair"/>
          </do_if>
          
          <set_value name="$autoResupply" exact="1"/>
          <do_if value="global.$GT_Config? and global.$GT_Config.$Maintenance? and global.$GT_Config.$Maintenance.$AutoResupply?">
            <set_value name="$autoResupply" exact="global.$GT_Config.$Maintenance.$AutoResupply"/>
          </do_if>
          <set_value name="$pilotRenamingEnabled" exact="0"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled">
            <set_value name="$pilotRenamingEnabled" exact="1"/>
          </do_if>
          
          <!-- Build config string: "CONFIG:autoTraining|autoRepair|autoResupply|pilotRenamingEnabled" -->
          <set_value name="$configString" exact="'CONFIG:' + $autoTraining + '|' + $autoRepair + '|' + $autoResupply + '|' + $pilotRenamingEnabled"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Info Menu] Config flags: AutoTraining=' + $autoTraining + ', AutoRepair=' + $autoRepair + ', AutoResupply=' + $autoResupply + ', PilotRenamingEnabled=' + $pilotRenamingEnabled" chance="100"/>
            <debug_text text="'[GT Info Menu] Found ' + $shipsKeysCount + ' ships in registry'" chance="100"/>
          </do_if>
          
          <!-- Sort ships by idcode for stable, consistent order -->
          <create_list name="$sortedShips"/>
          <do_all exact="$shipsKeysCount" counter="$i">
            <set_value name="$shipKey" exact="global.$GT_Ships.keys.{$i}"/>
            <!-- Guard against stale/null component handles in registry keys. -->
            <do_if value="$shipKey and $shipKey.exists">
              <append_to_list name="$sortedShips" exact="$shipKey"/>
            </do_if>
          </do_all>
          <sort_list list="$sortedShips" sortbyvalue="loop.element.idcode"/>
          
          <!-- Iterate through sorted ship list -->
          <do_all exact="$sortedShips.count" counter="$i">
            <set_value name="$ship" exact="$sortedShips.{$i}"/>
            <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
            
            <!-- <debug_text text="'[GT Info Menu] Ship ' + $i + ': ' + @$ship.knownname + ' (operational: ' + $ship.isoperational + ', has pilot entry: ' + $shipData.$Pilot? + ')'" chance="100"/> -->
            
            <do_if value="$ship.isoperational and $shipData.$Pilot?">
              <set_value name="$pilot" exact="null"/>
              <do_if value="$shipData.$Pilot and $shipData.$Pilot.exists? and $shipData.$Pilot.exists">
                <set_value name="$pilot" exact="$shipData.$Pilot"/>
              </do_if>
              <do_elseif value="$ship.pilot? and $ship.pilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
                <set_value name="$pilot" exact="$ship.pilot"/>
                <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$ship.pilot"/>
              </do_elseif>
              <do_else>
                <remove_value name="global.$GT_Ships.{$ship}.$Pilot"/>
              </do_else>
              
              <do_if value="$pilot and $pilot.exists and global.$GT_Pilots.{$pilot}?">
                <set_value name="$pilotData" exact="global.$GT_Pilots.{$pilot}"/>
                <set_value name="$pilotName" exact="if $pilot.name? then $pilot.name else 'NONE'"/>
                <set_value name="$pilotLevelForTag" exact="if $pilotData.$Level? then $pilotData.$Level else 1"/>
                <set_value name="$taggedNameToAdd" exact="'(T:' + $pilotLevelForTag + ') ' + $pilotName"/>

                <!-- PilotIdMap: multiple keys per pilot â€” StableIdentity + raw seed + idcode + template (names are not unique). -->
                <do_if value="$pilotName != ''">
                  <do_if value="$pilotData.$StableIdentity? and $pilotData.$StableIdentity != ''">
                    <do_if value="$gtPilotIdMapCount gt 0">
                      <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                    </do_if>
                    <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilotData.$StableIdentity + '|' + $taggedNameToAdd"/>
                    <set_value name="$gtPilotIdMapCount" operation="add"/>
                    <set_value name="$gtPilotIdMapFromStable" operation="add"/>
                  </do_if>
                  <do_if value="$pilot.seed?">
                    <run_actions ref="Pilot_Seed_U64Wire_ForPilotIdMap" result="$pilotSeedWire">
                      <param name="pilot" value="$pilot"/>
                    </run_actions>
                    <do_if value="$pilotSeedWire != ''">
                      <do_if value="$gtPilotIdMapCount gt 0">
                        <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                      </do_if>
                      <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilotSeedWire + '|' + $taggedNameToAdd"/>
                      <set_value name="$gtPilotIdMapCount" operation="add"/>
                      <set_value name="$gtPilotIdMapFromPilotRef" operation="add"/>
                    </do_if>
                  </do_if>
                  <do_if value="$pilot.idcode? and $pilot.idcode != ''">
                    <do_if value="$gtPilotIdMapCount gt 0">
                      <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                    </do_if>
                    <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilot.idcode + '|' + $taggedNameToAdd"/>
                    <set_value name="$gtPilotIdMapCount" operation="add"/>
                    <set_value name="$gtPilotIdMapFromPilotIdcode" operation="add"/>
                  </do_if>
                  <!-- npctemplate not unique â€” omitted from PilotIdMap (see paused-pilot branch comment). -->
                </do_if>
                
                <!-- Calculate rank from level -->
                <set_value name="$level" exact="$pilotData.$Level"/>
                <set_value name="$rankIndex" exact="($level / 3)i + 1"/>
                <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
                  <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
                    <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
                  </do_if>
                  <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
                </do_if>
                <do_else>
                  <set_value name="$rankTitle" exact="'Lehrling'"/>
                </do_else>
                
                <!-- Calculate XP to next level -->
                <set_value name="$xpToNext" exact="1000"/>
                <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$SkillThresholds?">
                  <do_if value="$level lt 15 and global.$GT_Config.$XP.$SkillThresholds.{$level + 1}?">
                    <set_value name="$xpToNext" exact="global.$GT_Config.$XP.$SkillThresholds.{$level + 1}"/>
                  </do_if>
                </do_if>
                
                <!-- Build status string from ship data flags -->
                <set_value name="$statusString" exact="''"/>
                <do_if value="$shipData.$Training? and $shipData.$Training">
                  <set_value name="$statusString" exact="$statusString + '[TRAINING] '"/>
                </do_if>
                <do_if value="$shipData.$NeedsRepair? and $shipData.$NeedsRepair">
                  <set_value name="$statusString" exact="$statusString + '[REPAIR] '"/>
                </do_if>
                <do_if value="$shipData.$NeedsResupply? and $shipData.$NeedsResupply">
                  <set_value name="$statusString" exact="$statusString + '[RESUPPLY] '"/>
                </do_if>
                <do_if value="$shipData.$Rerouting? and $shipData.$Rerouting">
                  <set_value name="$statusString" exact="$statusString + '[REROUTE] '"/>
                </do_if>
                <do_if value="$shipData.$Escaping? and $shipData.$Escaping">
                  <set_value name="$statusString" exact="$statusString + '[ESCAPE] '"/>
                </do_if>
                <do_if value="$shipData.$CargoDisposal? and $shipData.$CargoDisposal">
                  <set_value name="$statusString" exact="$statusString + '[CLEARANCE] '"/>
                </do_if>
                
                <!-- If no special status, check if ship is actively trading or idle -->
                <do_if value="$statusString == ''">
                  <do_if value="$ship.order and $ship.order.id == 'TradeAdvance'">
                    <set_value name="$statusString" exact="'[ADVANCE]'"/>
                  </do_if>
                  <do_elseif value="$ship.order and $ship.order.id == 'Trade'">
                    <set_value name="$statusString" exact="'[TRADING]'"/>
                  </do_elseif>
                  <do_else>
                    <set_value name="$statusString" exact="'[ACTIVE]'"/>
                  </do_else>
                </do_if>
                
                <!-- Get profit from PILOT data (follows pilot across ships) -->
                <set_value name="$pilotProfit" exact="0"/>
                <do_if value="$pilotData.$TotalProfit?">
                  <set_value name="$pilotProfit" exact="$pilotData.$TotalProfit"/>
                </do_if>
                
                <!-- Get profit from SHIP data (current ship's earnings) -->
                <set_value name="$shipProfit" exact="0"/>
                <do_if value="$shipData.$TotalProfit?">
                  <set_value name="$shipProfit" exact="$shipData.$TotalProfit"/>
                </do_if>
                
                <!-- Get trade count from PILOT data (follows pilot across ships) -->
                <set_value name="$tradeCount" exact="0"/>
                <do_if value="$pilotData.$TotalTrades?">
                  <set_value name="$tradeCount" exact="$pilotData.$TotalTrades"/>
                </do_if>
                
                <!-- Expose blocked level for context-sensitive control actions -->
                <set_value name="$blockedLevel" exact="0"/>
                <do_if value="$pilotData.$BlockedLevel?">
                  <set_value name="$blockedLevel" exact="$pilotData.$BlockedLevel"/>
                </do_if>
                
                <!-- Build pilot record string -->
                <!-- Format: shipId|pilotName|shipType|status|rank|rankIndex|level|xp|xpNext|pilotProfit|shipProfit|location|tradeCount|blockedLevel -->
                <set_value name="$pilotRecord" exact="
                  $ship.idcode + '|' +
                  $pilotName + '|' +
                  $ship.knownname + '|' +
                  $statusString + '|' +
                  $rankTitle + '|' +
                  $rankIndex + '|' +
                  $level + '|' +
                  $pilotData.$XP + '|' +
                  $xpToNext + '|' +
                  $pilotProfit + '|' +
                  $shipProfit + '|' +
                  @$ship.sector.knownname + '|' +
                  $tradeCount + '|' +
                  $blockedLevel
                "/>
                
                <!-- Add to data string -->
                <do_if value="$pilotCount gt 0">
                  <set_value name="$pilotDataString" exact="$pilotDataString + '||'"/>
                </do_if>
                <set_value name="$pilotDataString" exact="$pilotDataString + $pilotRecord"/>
                <set_value name="$pilotCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Info Menu] Sending data for ' + $pilotCount + ' pilots to Lua UI'" chance="100"/>
        </do_if>
        
        <!-- Send to Lua: config flags + pilot data -->
        <!-- Format: "CONFIG:1|0|1||pilot1data||pilot2data||..." -->
        <set_value name="$fullDataString" exact="$configString + '||' + $pilotDataString"/>
        <raise_lua_event name="'GT_PilotData.Update'" param="$fullDataString"/>
        
        <!-- Append paused/off-ship pilots so map also covers non-active records when PilotID exists. -->
        <set_value name="$gtNameData" exact="''"/>
        <set_value name="$gtNameMapData" exact="''"/>
        <set_value name="$gtNameCount" exact="0"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$pilotKeys" exact="global.$GT_Pilots.keys.list"/>
          <do_all exact="$pilotKeys.count" counter="$ni">
            <set_value name="$pilotObj" exact="$pilotKeys.{$ni}"/>
            <set_value name="$nameToAdd" exact="''"/>
            <do_if value="global.$GT_Pilots.{$pilotObj}? and global.$GT_Pilots.{$pilotObj}.$OriginalPilotName? and global.$GT_Pilots.{$pilotObj}.$OriginalPilotName != ''">
              <set_value name="$nameToAdd" exact="global.$GT_Pilots.{$pilotObj}.$OriginalPilotName"/>
            </do_if>
            <do_elseif value="global.$GT_Pilots.{$pilotObj}? and global.$GT_Pilots.{$pilotObj}.$PilotName? and global.$GT_Pilots.{$pilotObj}.$PilotName != ''">
              <set_value name="$nameToAdd" exact="global.$GT_Pilots.{$pilotObj}.$PilotName"/>
            </do_elseif>
            <do_elseif value="$pilotObj and $pilotObj.name?">
              <set_value name="$nameToAdd" exact="$pilotObj.name"/>
            </do_elseif>
            
            <do_if value="$nameToAdd != ''">
              <set_value name="$pilotLevelForTag" exact="if global.$GT_Pilots.{$pilotObj}.$Level? then global.$GT_Pilots.{$pilotObj}.$Level else 1"/>
              <set_value name="$taggedNameToAdd" exact="'(T:' + $pilotLevelForTag + ') ' + $nameToAdd"/>
              <do_if value="$gtNameCount gt 0">
                <set_value name="$gtNameData" exact="$gtNameData + '||'"/>
                <set_value name="$gtNameMapData" exact="$gtNameMapData + '||'"/>
              </do_if>
              <set_value name="$gtNameData" exact="$gtNameData + $nameToAdd"/>
              <set_value name="$gtNameMapData" exact="$gtNameMapData + $nameToAdd + '|' + $taggedNameToAdd"/>
              <set_value name="$gtNameCount" operation="add"/>
            </do_if>

            <do_if value="$nameToAdd != '' and global.$GT_Pilots.{$pilotObj}?">
              <set_value name="$pOD" exact="global.$GT_Pilots.{$pilotObj}"/>
              <do_if value="$pOD.$StableIdentity? and $pOD.$StableIdentity != ''">
                <do_if value="$gtPilotIdMapCount gt 0">
                  <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                </do_if>
                <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pOD.$StableIdentity + '|' + $taggedNameToAdd"/>
                <set_value name="$gtPilotIdMapCount" operation="add"/>
                <set_value name="$gtPilotIdMapFromStable" operation="add"/>
              </do_if>
              <do_if value="$pilotObj.seed?">
                <run_actions ref="Pilot_Seed_U64Wire_ForPilotIdMap" result="$pilotSeedWire">
                  <param name="pilot" value="$pilotObj"/>
                </run_actions>
                <do_if value="$pilotSeedWire != ''">
                  <do_if value="$gtPilotIdMapCount gt 0">
                    <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                  </do_if>
                  <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilotSeedWire + '|' + $taggedNameToAdd"/>
                  <set_value name="$gtPilotIdMapCount" operation="add"/>
                  <set_value name="$gtPilotIdMapFromPilotRef" operation="add"/>
                </do_if>
              </do_if>
              <do_if value="$pilotObj.idcode? and $pilotObj.idcode != ''">
                <do_if value="$gtPilotIdMapCount gt 0">
                  <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + '||'"/>
                </do_if>
                <set_value name="$gtPilotIdMapData" exact="$gtPilotIdMapData + $pilotObj.idcode + '|' + $taggedNameToAdd"/>
                <set_value name="$gtPilotIdMapCount" operation="add"/>
                <set_value name="$gtPilotIdMapFromPilotIdcode" operation="add"/>
              </do_if>
              <!-- npctemplate not unique â€” omitted from PilotIdMap -->
            </do_if>
          </do_all>
        </do_if>
        <debug_text text="'[GT Info Menu] PilotIdMap entries prepared=' + $gtPilotIdMapCount + ' (stable=' + $gtPilotIdMapFromStable + ', idcode=' + $gtPilotIdMapFromPilotIdcode + ', seed/ref=' + $gtPilotIdMapFromPilotRef + ')'" chance="100"/>
        <raise_lua_event name="'GT_PilotNameIndex.Update'" param="$gtNameData"/>
        <raise_lua_event name="'GT_PilotNameMap.Update'" param="$gtNameMapData"/>
        <do_if value="$gtPilotIdMapCount gt 0">
          <raise_lua_event name="'GT_PilotIdMap.Update'" param="$gtPilotIdMapData"/>
        </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- Queue manual training from GT control UI -->
    <cue name="HandleManualTrainingRequest" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_PilotControl'" control="'Training'" />
      </conditions>
      <actions>
        <set_value name="$shipId" exact="event.param3"/>
        <set_value name="$autoTrainingEnabled" exact="true"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$AutoTraining?">
          <set_value name="$autoTrainingEnabled" exact="global.$GT_GlobalSettings.$XP.$AutoTraining"/>
        </do_if>
        
        <set_value name="$ship" exact="null"/>
        <set_value name="$status" exact="'ok'"/>
        <set_value name="$message" exact="{77000,9904}"/>
        <set_value name="$shipsKeysCount" exact="@global.$GT_Ships.keys.count"/>
        <do_if value="$shipsKeysCount? and $shipsKeysCount gt 0">
          <do_all exact="$shipsKeysCount" counter="$i">
            <set_value name="$candidateShip" exact="global.$GT_Ships.keys.{$i}"/>
            <do_if value="$candidateShip? and $candidateShip.idcode == $shipId">
              <set_value name="$ship" exact="$candidateShip"/>
            </do_if>
          </do_all>
        </do_if>
        
        <set_value name="$pilot" exact="null"/>
        <set_value name="$blockedLevel" exact="0"/>
        
        <do_if value="not $ship? or not $ship.pilot?">
          <set_value name="$status" exact="'error'"/>
          <set_value name="$message" exact="{77000,9905}"/>
        </do_if>
        <do_else>
          <set_value name="$pilot" exact="$ship.pilot"/>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$BlockedLevel?">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          </do_if>
        </do_else>
        
        <do_if value="$status == 'ok' and $autoTrainingEnabled">
          <set_value name="$status" exact="'error'"/>
          <set_value name="$message" exact="{77000,9906}"/>
        </do_if>
        
        <do_if value="$status == 'ok' and $blockedLevel le 1">
          <set_value name="$status" exact="'error'"/>
          <set_value name="$message" exact="{77000,9907}"/>
        </do_if>
        
        <do_if value="$status == 'ok' and $pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested" exact="true"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'manual_training_queued'"/>
          <!-- Trigger pilot data refresh for UI status updates -->
          <signal_cue_instantly cue="SendPilotData"/>
        </do_if>
        
        <raise_lua_event name="'GT_PilotControl.Confirmation'" param="'training|' + $shipId + '|' + $status + '|' + $message"/>
      </actions>
    </cue>
    
  </cues>
  
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Libraries_Blacklist" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================= -->
    <!-- BLACKLIST UTILITIES -->
    <!-- ========================================= -->
    <!-- Consolidated from: gt_blacklist_utilities.xml + gt_blacklist_loader.xml -->
    
    <!-- Get Blacklist Group -->
    <library name="GT_GetBlacklistGroup" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to determine blacklist group for"/>
      </params>
      <actions>
        <set_value name="$blacklistgroup" exact="blacklistgroup.civilian"/>
        <do_if value="(@$ship.primarypurpose == purpose.fight) or (@$ship.primarypurpose == purpose.auxiliary)">
          <set_value name="$blacklistgroup" exact="blacklistgroup.military"/>
        </do_if>
        <return value="$blacklistgroup"/>
      </actions>
    </library>
    
    <!-- Get Sector Whitelist -->
    <library name="GT_GetSectorWhitelist" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to get whitelist for"/>
      </params>
      <actions>
        <set_value name="$whitelist" exact="[]"/>
        
        <!-- Check if ship is a subordinate - inherit commander's whitelist -->
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <do_if value="$ship.commander.defaultorder? and $ship.commander.defaultorder.$sectorwhitelist?">
            <set_value name="$commanderWhitelist" exact="@$ship.commander.defaultorder.$sectorwhitelist"/>
            <!-- Extract count property with @ first, then check if result exists and is valid -->
            <set_value name="$commanderWhitelistCount" exact="@$commanderWhitelist.count"/>
            <do_if value="$commanderWhitelistCount? and $commanderWhitelistCount gt 0">
              <set_value name="$whitelist" exact="$commanderWhitelist"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- For non-subordinates: use ship's own whitelist -->
        <do_if value="not ($ship.commander? and $ship.commander.exists and $ship.commander != $ship)">
          <do_if value="$ship.defaultorder? and $ship.defaultorder.$sectorwhitelist?">
            <set_value name="$shipWhitelist" exact="@$ship.defaultorder.$sectorwhitelist"/>
            <!-- Extract count property with @ first, then check if result exists and is valid -->
            <set_value name="$shipWhitelistCount" exact="@$shipWhitelist.count"/>
            <do_if value="$shipWhitelistCount? and $shipWhitelistCount gt 0">
              <set_value name="$whitelist" exact="$shipWhitelist"/>
            </do_if>
          </do_if>
        </do_if>
        
        <return value="$whitelist"/>
      </actions>
    </library>
    
    <!-- Is Sector Blacklisted -->
    <library name="GT_IsSectorBlacklisted" purpose="run_actions">
      <params>
        <param name="sector" comment="Sector to check"/>
        <param name="ship" comment="Ship for blacklist context"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group (will be auto-determined if null)"/>
        <param name="returnDetails" default="false" comment="If true, returns table with activity/travel flags"/>
        <param name="sectorWhitelist" default="null" comment="List of sectors to exclude from blacklist checks (if null, will be auto-determined from ship's order)"/>
      </params>
      <actions>
        <!-- Get whitelist if not provided -->
        <set_value name="$whitelist" exact="[]"/>
        <do_if value="not $sectorWhitelist? or $sectorWhitelist == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetSectorWhitelist" result="$whitelist">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        <do_else>
          <set_value name="$whitelist" exact="$sectorWhitelist"/>
        </do_else>
        
        <!-- Check whitelist first: if sector is in whitelist, it's not blacklisted -->
        <set_value name="$isWhitelisted" exact="false"/>
        <do_if value="$whitelist.count gt 0">
          <do_all exact="$whitelist.count" counter="$i">
            <do_if value="$whitelist.{$i} == $sector">
              <set_value name="$isWhitelisted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- If whitelisted, return false (not blacklisted) -->
        <do_if value="$isWhitelisted">
          <do_if value="$returnDetails">
            <set_value name="$result" exact="table[]"/>
            <set_value name="$result.$IsBlacklisted" exact="false"/>
            <set_value name="$result.$ActivityBlacklisted" exact="false"/>
            <set_value name="$result.$TravelBlacklisted" exact="false"/>
            <return value="$result"/>
          </do_if>
          <do_else>
            <return value="false"/>
          </do_else>
        </do_if>
        
        <!-- Auto-determine blacklist group if not provided or null (memory:10529400 - ? checks existence, not null) -->
        <do_if value="not $blacklistgroup? or $blacklistgroup == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        
        <set_value name="$activityBlacklisted" exact="@$sector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship}"/>
        <set_value name="$travelBlacklisted" exact="@$sector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{$ship}"/>
        <set_value name="$isBlacklisted" exact="$activityBlacklisted or $travelBlacklisted"/>
        
        <do_if value="$returnDetails">
          <set_value name="$result" exact="table[]"/>
          <set_value name="$result.$IsBlacklisted" exact="$isBlacklisted"/>
          <set_value name="$result.$ActivityBlacklisted" exact="$activityBlacklisted"/>
          <set_value name="$result.$TravelBlacklisted" exact="$travelBlacklisted"/>
          <return value="$result"/>
        </do_if>
        <do_else>
          <return value="$isBlacklisted"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Is Station Blacklisted -->
    <library name="GT_IsStationBlacklisted" purpose="run_actions">
      <params>
        <param name="station" comment="Station to check"/>
        <param name="ship" comment="Ship for blacklist context"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group (auto-determined if null)"/>
      </params>
      <actions>
        <do_if value="not $blacklistgroup?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        <return value="@$station.isblacklisted.{blacklisttype.objectactivity}.{$blacklistgroup}.{$ship}"/>
      </actions>
    </library>
    
    <!-- Check Trade Blacklist -->
    <library name="GT_CheckTradeBlacklist" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship executing trade"/>
        <param name="buyStation" comment="Buy station"/>
        <param name="sellStation" comment="Sell station"/>
        <param name="currentSector" default="null" comment="Ship's current sector (for escape logic)"/>
        <param name="enableEscapeLogic" default="true" comment="Enable escape logic (block buying in blacklisted sectors)"/>
      </params>
      <actions>
        <!-- Initialize result -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$IsBlacklisted" exact="false"/>
        <set_value name="$result.$Reason" exact="''"/>
        
        <!-- Get blacklist group -->
        <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Extract sectors -->
        <set_value name="$buySector" exact="@$buyStation.sector"/>
        <set_value name="$sellSector" exact="@$sellStation.sector"/>
        <set_value name="$currentSector" exact="if $currentSector? then $currentSector else $ship.sector"/>
        
        <!-- Check current sector for intra-sector trades -->
        <run_actions ref="md.GT_Libraries_General.GT_IsIntraSectorTrade" result="$isIntraSector">
          <param name="buySector" value="$buySector"/>
          <param name="sellSector" value="$sellSector"/>
          <param name="currentSector" value="$currentSector"/>
        </run_actions>
        
        <do_if value="$isIntraSector">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$currentSectorBlacklisted">
            <param name="sector" value="$currentSector"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$blacklistgroup"/>
          </run_actions>
          <do_if value="$currentSectorBlacklisted">
            <set_value name="$result.$IsBlacklisted" exact="true"/>
            <set_value name="$result.$Reason" exact="'Intra-sector trade in blacklisted sector'"/>
            <return value="$result"/>
          </do_if>
        </do_if>
        
        <!-- Check stations -->
        <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$buyStationBlacklisted">
          <param name="station" value="$buyStation"/>
          <param name="ship" value="$ship"/>
          <param name="blacklistgroup" value="$blacklistgroup"/>
        </run_actions>
        <do_if value="$buyStationBlacklisted">
          <set_value name="$result.$IsBlacklisted" exact="true"/>
          <set_value name="$result.$Reason" exact="'Buy station blacklisted'"/>
          <return value="$result"/>
        </do_if>
        
        <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$sellStationBlacklisted">
          <param name="station" value="$sellStation"/>
          <param name="ship" value="$ship"/>
          <param name="blacklistgroup" value="$blacklistgroup"/>
        </run_actions>
        <do_if value="$sellStationBlacklisted">
          <set_value name="$result.$IsBlacklisted" exact="true"/>
          <set_value name="$result.$Reason" exact="'Sell station blacklisted'"/>
          <return value="$result"/>
        </do_if>
        
        <!-- Check sectors (with escape logic) -->
        <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$buySectorBlacklisted">
          <param name="sector" value="$buySector"/>
          <param name="ship" value="$ship"/>
          <param name="blacklistgroup" value="$blacklistgroup"/>
        </run_actions>
        <do_if value="$enableEscapeLogic and $buySectorBlacklisted">
          <!-- Escape logic: block buying in blacklisted sector -->
          <set_value name="$result.$IsBlacklisted" exact="true"/>
          <set_value name="$result.$Reason" exact="'Buy sector blacklisted (escape logic)'"/>
          <return value="$result"/>
        </do_if>
        
        <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$sellSectorBlacklisted">
          <param name="sector" value="$sellSector"/>
          <param name="ship" value="$ship"/>
          <param name="blacklistgroup" value="$blacklistgroup"/>
        </run_actions>
        <do_if value="$enableEscapeLogic and $sellSectorBlacklisted and $sellSector != $currentSector">
          <!-- Escape logic: block selling to blacklisted sector (unless already there) -->
          <set_value name="$result.$IsBlacklisted" exact="true"/>
          <set_value name="$result.$Reason" exact="'Sell sector blacklisted (escape logic)'"/>
          <return value="$result"/>
        </do_if>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Check if Ship Needs Escape (is in blacklisted sector) -->
    <library name="GT_CheckNeedsEscape" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
      </params>
      <actions>
        <set_value name="$needsEscape" exact="false"/>
        <set_value name="$currentSector" exact="$ship.sector"/>
        <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
          <param name="ship" value="$ship"/>
        </run_actions>
        <do_if value="$blacklistgroup? and $currentSector?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$needsEscape">
            <param name="sector" value="$currentSector"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$blacklistgroup"/>
          </run_actions>
        </do_if>
        <return value="$needsEscape"/>
      </actions>
    </library>
    
    <!-- Check Connected Sectors Blacklist Status -->
    <!-- Returns information about connected sectors and whether the sector is isolated -->
    <library name="GT_CheckConnectedSectorsBlacklisted" purpose="run_actions">
      <params>
        <param name="sector" comment="Sector to check connected sectors from"/>
        <param name="ship" comment="Ship for blacklist context and reference object"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group (auto-determined if null)"/>
        <param name="returnDetails" default="false" comment="If true, returns detailed table with sector lists"/>
      </params>
      <actions>
        <!-- Initialize result -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$IsIsolated" exact="false"/>
        <set_value name="$result.$ConnectedSectorsCount" exact="0"/>
        <set_value name="$result.$BlacklistedSectorsCount" exact="0"/>
        <set_value name="$result.$NonBlacklistedSectorsCount" exact="0"/>
        
        <!-- Auto-determine blacklist group if not provided -->
        <do_if value="not $blacklistgroup? or $blacklistgroup == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        
        <!-- Validate inputs -->
        <do_if value="not $sector? or not $ship? or not $blacklistgroup?">
          <return value="$result"/>
        </do_if>
        
        <!-- Use ship's effective blacklist context (includes sector whitelist rules) -->

        <!-- Targeted isolation diagnostics (avoid log spam / micro-stutter when debug is enabled) -->
        <!-- To enable detailed logging for ONE ship: set global.$GT_Config.$Debug.$WatchIsolationShipId = 'ABC-123' -->
        <set_value name="$watchShipId" exact="@global.$GT_Config.$Debug.$WatchIsolationShipId"/>
        <set_value name="$doWatch" exact="$watchShipId != null and $watchShipId != '' and $ship.idcode == $watchShipId"/>

        <!-- Shared connectivity cache (per sector): avoids expensive galaxy-wide accelerator/highway fallback scans per ship -->
        <set_value name="$connCacheTtl" exact="300s"/>
        <set_value name="$connCacheKeys" exact="@global.$GT_SectorConnectivityCache.keys.count"/>
        <do_if value="$connCacheKeys == null">
          <set_value name="global.$GT_SectorConnectivityCache" exact="table[]"/>
        </do_if>

        <!-- Short-lived cache to avoid repeated expensive enumeration (and log spam) -->
        <!-- Many callers may request this repeatedly while filtering trades; caching keeps it O(1) per tick. -->
        <set_value name="$cacheHit" exact="false"/>
        <!-- Smoothness > speed: keep results longer; connectivity/blacklist topology rarely changes moment-to-moment -->
        <set_value name="$cacheTtl" exact="30s"/>
        <set_value name="$cachedEntry" exact="null"/>
        <do_if value="$returnDetails">
          <set_value name="$cachedEntry" exact="@global.$GT_IsolationCheckCache.{$ship}.{$sector}.$Details"/>
        </do_if>
        <do_else>
          <set_value name="$cachedEntry" exact="@global.$GT_IsolationCheckCache.{$ship}.{$sector}.$Simple"/>
        </do_else>
        <set_value name="$cachedTime" exact="@$cachedEntry.$Time"/>
        <set_value name="$cachedGroup" exact="@$cachedEntry.$BlacklistGroup"/>
        <set_value name="$cachedResult" exact="@$cachedEntry.$Result"/>
        <do_if value="$cachedTime? and $cachedTime != null and $cachedGroup? and $cachedGroup != null and $cachedResult? and $cachedResult != null">
          <set_value name="$cacheAge" exact="player.age - $cachedTime"/>
          <do_if value="$cacheAge le $cacheTtl and $cachedGroup == $blacklistgroup">
            <set_value name="$cacheHit" exact="true"/>
            <set_value name="$result" exact="$cachedResult"/>
          </do_if>
        </do_if>
        
        <!-- Only compute (and only log) if cache miss -->
        <do_if value="not $cacheHit">
        
        <!-- Find all sectors directly connected via gates and accelerators -->
        <!-- Use find_gate to enumerate all gates and accelerators in the target sector -->
        <set_value name="$validConnectedSectors" exact="[]"/>
        <set_value name="$blacklistedSectors" exact="[]"/>
        <set_value name="$nonBlacklistedSectors" exact="[]"/>
        <set_value name="$foundSectors" exact="table[]"/>
        <set_value name="$skipEnumeration" exact="false"/>

        <!-- Try shared sector connectivity cache (ship-independent) -->
        <set_value name="$connCacheHit" exact="false"/>
        <set_value name="$connEntry" exact="@global.$GT_SectorConnectivityCache.{$sector}"/>
        <set_value name="$connTime" exact="@$connEntry.$Time"/>
        <set_value name="$connSectors" exact="@$connEntry.$Sectors"/>
        <do_if value="$connTime? and $connTime != null and $connSectors? and $connSectors != null">
          <set_value name="$connAge" exact="player.age - $connTime"/>
          <do_if value="$connAge le $connCacheTtl">
            <set_value name="$connCacheHit" exact="true"/>
            <set_value name="$skipEnumeration" exact="true"/>
            <set_value name="$validConnectedSectors" exact="$connSectors"/>
          </do_if>
        </do_if>

        <!-- If connectivity cache hit: classify connected sectors for THIS ship's blacklist context -->
        <do_if value="$connCacheHit">
          <do_all exact="$validConnectedSectors.count" counter="$i">
            <set_value name="$connectedSector" exact="$validConnectedSectors.{$i}"/>
            <set_value name="$isBlacklisted" exact="false"/>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$isBlacklisted">
              <param name="sector" value="$connectedSector"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <do_if value="$isBlacklisted">
              <append_to_list name="$blacklistedSectors" exact="$connectedSector"/>
              <set_value name="$result.$BlacklistedSectorsCount" exact="$result.$BlacklistedSectorsCount + 1"/>
            </do_if>
            <do_else>
              <append_to_list name="$nonBlacklistedSectors" exact="$connectedSector"/>
              <set_value name="$result.$NonBlacklistedSectorsCount" exact="$result.$NonBlacklistedSectorsCount + 1"/>
            </do_else>
          </do_all>
        </do_if>

        <!-- Only enumerate gates/accelerators/highways when we must (connectivity cache miss) -->
        <do_if value="not $skipEnumeration">
        
        <!-- Find all gates in the target sector -->
        <find_gate name="$gates" multiple="true" space="$sector"/>
        <set_value name="$gatesExist" exact="if $gates? then 'YES' else 'NO'"/>
        <set_value name="$gateCount" exact="if $gates != null then @$gates.count else 0"/>
        <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$sectorName" exact="@$sector.knownname"/>
          <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ') ISOLATION CHECK: Gates exist=' + $gatesExist + ', Found ' + $gateCount + ' gates in sector ' + $sectorName" chance="100"/>
        </do_if>
        <do_for_each name="$gate" in="$gates">
          <!-- Log each gate found (even if exit is invalid) -->
          <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$gateExit" exact="@$gate.exit"/>
            <set_value name="$gateExitSector" exact="@$gate.exit.sector"/>
            <set_value name="$gateDestSector" exact="@$gate.destination.sector"/>
            <set_value name="$hasExit" exact="if $gateExit? then 'YES' else 'NO'"/>
            <set_value name="$exitSectorName" exact="if $gateExitSector? then @$gateExitSector.knownname else 'NULL'"/>
            <set_value name="$destSectorName" exact="if $gateDestSector? then @$gateDestSector.knownname else 'NULL'"/>
            <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   GATE found: exit=' + $hasExit + ', exit.sector=' + $exitSectorName + ', destination.sector=' + $destSectorName" chance="100"/>
          </do_if>
          <!-- IMPORTANT: For superhighway gates (highwayentrygate), vanilla uses gate.highway.destination.sector -->
          <set_value name="$connectedSector" exact="@$gate.exit.sector"/>
          <do_if value="$gate.isclass.highwayentrygate">
            <set_value name="$connectedSector" exact="@$gate.highway.destination.sector"/>
          </do_if>
          <do_elseif value="not $connectedSector? or $connectedSector == null">
            <set_value name="$connectedSector" exact="@$gate.destination.sector"/>
          </do_elseif>
          <!-- Check that connectedSector exists AND is not null before using as table key -->
          <!-- The ? operator checks existence, not null - a variable can exist but be null -->
          <!-- We need to verify the sector is valid before using it as a table key -->
          <do_if value="$connectedSector? and $connectedSector != null and $connectedSector != $sector">
            <!-- Gate connects to a different sector - check if we've already seen this sector -->
            <do_if value="not $foundSectors.{$connectedSector}?">
              <set_value name="$foundSectors.{$connectedSector}" exact="true"/>
              <!-- Check blacklist status -->
              <set_value name="$isBlacklisted" exact="false"/>
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$isBlacklisted">
                <param name="sector" value="$connectedSector"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
              </run_actions>
              
              <!-- Log each connected sector -->
              <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$connectedSectorName" exact="@$connectedSector.knownname"/>
                <set_value name="$blacklistStatus" exact="if $isBlacklisted then 'BLACKLISTED' else 'OK'"/>
                <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   GATE ' + $connectedSectorName + ' (' + $blacklistStatus + ')'" chance="100"/>
              </do_if>
              
              <!-- Add to appropriate list -->
              <append_to_list name="$validConnectedSectors" exact="$connectedSector"/>
              <do_if value="$isBlacklisted">
                <append_to_list name="$blacklistedSectors" exact="$connectedSector"/>
                <set_value name="$result.$BlacklistedSectorsCount" exact="$result.$BlacklistedSectorsCount + 1"/>
              </do_if>
              <do_else>
                <append_to_list name="$nonBlacklistedSectors" exact="$connectedSector"/>
                <set_value name="$result.$NonBlacklistedSectorsCount" exact="$result.$NonBlacklistedSectorsCount + 1"/>
              </do_else>
            </do_if>
          </do_if>
        </do_for_each>
        
        <!-- Find all accelerators in the target sector -->
        <!-- Note: Accelerators are bidirectional, so we need to check both:
             1. Accelerators IN this sector (pointing out)
             2. Accelerators pointing TO this sector (from other sectors)
        -->
        <find_gate name="$accelerators" multiple="true" space="$sector" accelerator="true"/>
        <set_value name="$acceleratorsExist" exact="if $accelerators? then 'YES' else 'NO'"/>
        <set_value name="$acceleratorCount" exact="if $accelerators != null then @$accelerators.count else 0"/>
        <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ') ISOLATION CHECK: Accelerators exist=' + $acceleratorsExist + ', Found ' + $acceleratorCount + ' accelerators IN sector ' + $sectorName" chance="100"/>
        </do_if>
        <do_for_each name="$accelerator" in="$accelerators">
          <!-- Log each accelerator found (even if exit is invalid) -->
          <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$acceleratorExit" exact="@$accelerator.exit"/>
            <set_value name="$acceleratorExitSector" exact="@$accelerator.exit.sector"/>
            <set_value name="$hasExit" exact="if $acceleratorExit? then 'YES' else 'NO'"/>
            <set_value name="$exitSectorName" exact="if $acceleratorExitSector? then @$acceleratorExitSector.knownname else 'NULL'"/>
            <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   ACCELERATOR found: exit=' + $hasExit + ', exit.sector=' + $exitSectorName" chance="100"/>
          </do_if>
          <set_value name="$connectedSector" exact="@$accelerator.exit.sector"/>
          <!-- Check that connectedSector exists AND is not null before using as table key -->
          <do_if value="$connectedSector? and $connectedSector != null and $connectedSector != $sector">
            <!-- Accelerator connects to a different sector - check if we've already seen this sector -->
            <do_if value="not $foundSectors.{$connectedSector}?">
              <set_value name="$foundSectors.{$connectedSector}" exact="true"/>
              <!-- Check blacklist status -->
              <set_value name="$isBlacklisted" exact="false"/>
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$isBlacklisted">
                <param name="sector" value="$connectedSector"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
              </run_actions>
              
              <!-- Log each connected sector -->
              <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$connectedSectorName" exact="@$connectedSector.knownname"/>
                <set_value name="$blacklistStatus" exact="if $isBlacklisted then 'BLACKLISTED' else 'OK'"/>
                <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   ACCELERATOR ' + $connectedSectorName + ' (' + $blacklistStatus + ')'" chance="100"/>
              </do_if>
              
              <!-- Add to appropriate list -->
              <append_to_list name="$validConnectedSectors" exact="$connectedSector"/>
              <do_if value="$isBlacklisted">
                <append_to_list name="$blacklistedSectors" exact="$connectedSector"/>
                <set_value name="$result.$BlacklistedSectorsCount" exact="$result.$BlacklistedSectorsCount + 1"/>
              </do_if>
              <do_else>
                <append_to_list name="$nonBlacklistedSectors" exact="$connectedSector"/>
                <set_value name="$result.$NonBlacklistedSectorsCount" exact="$result.$NonBlacklistedSectorsCount + 1"/>
              </do_else>
            </do_if>
          </do_if>
        </do_for_each>
        
        <!-- Also search for accelerators pointing TO this sector (bidirectional check) -->
        <!-- Accelerators are bidirectional but may be defined from either direction -->
        <!-- Search in player.galaxy for all accelerators, then filter by exit.sector == our sector -->
        <!-- This catches accelerators defined from the opposite direction -->
        <do_if value="$acceleratorCount == 0">
          <!-- No accelerators found IN this sector - search for accelerators pointing TO this sector -->
          <find_gate name="$allAccelerators" multiple="true" space="player.galaxy" accelerator="true"/>
          <set_value name="$allAcceleratorCount" exact="if $allAccelerators != null then @$allAccelerators.count else 0"/>
          <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ') FALLBACK: Searching ' + $allAcceleratorCount + ' accelerators in galaxy for ones pointing TO sector ' + $sectorName" chance="100"/>
          </do_if>
          <do_for_each name="$accelerator" in="$allAccelerators">
            <set_value name="$acceleratorExitSector" exact="@$accelerator.exit.sector"/>
            <set_value name="$acceleratorSector" exact="@$accelerator.sector"/>
            <!-- Check if this accelerator points TO our sector -->
            <do_if value="$acceleratorExitSector? and $acceleratorExitSector == $sector">
              <!-- This accelerator points TO our sector - get the source sector (where accelerator is located) -->
              <set_value name="$sourceSector" exact="@$accelerator.sector"/>
              <do_if value="$sourceSector? and $sourceSector != $sector">
                <!-- Source sector is different from our sector - check if we've already seen this sector -->
                <do_if value="not $foundSectors.{$sourceSector}?">
                  <set_value name="$foundSectors.{$sourceSector}" exact="true"/>
                  <!-- Check blacklist status of source sector -->
                  <set_value name="$isBlacklisted" exact="false"/>
                  <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$isBlacklisted">
                    <param name="sector" value="$sourceSector"/>
                    <param name="ship" value="$ship"/>
                    <param name="blacklistgroup" value="$blacklistgroup"/>
                  </run_actions>
                  
                  <!-- Log accelerator found from opposite direction -->
                  <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$sourceSectorName" exact="@$sourceSector.knownname"/>
                    <set_value name="$blacklistStatus" exact="if $isBlacklisted then 'BLACKLISTED' else 'OK'"/>
                    <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   ACCELERATOR (FROM OPPOSITE): ' + $sourceSectorName + ' ' + $sectorName + ' (' + $blacklistStatus + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Add to appropriate list -->
                  <append_to_list name="$validConnectedSectors" exact="$sourceSector"/>
                  <do_if value="$isBlacklisted">
                    <append_to_list name="$blacklistedSectors" exact="$sourceSector"/>
                    <set_value name="$result.$BlacklistedSectorsCount" exact="$result.$BlacklistedSectorsCount + 1"/>
                  </do_if>
                  <do_else>
                    <append_to_list name="$nonBlacklistedSectors" exact="$sourceSector"/>
                    <set_value name="$result.$NonBlacklistedSectorsCount" exact="$result.$NonBlacklistedSectorsCount + 1"/>
                  </do_else>
                </do_if>
              </do_if>
            </do_if>
          </do_for_each>
        </do_if>
        
        <!-- Find all highway entry gates in the target sector -->
        <!-- Highway entry gates connect sectors via superhighways; vanilla uses highway.destination.sector -->
        <find_object name="$highwayEntries" class="class.highwayentrygate" space="$sector" multiple="true"/>
        <set_value name="$highwayEntriesExist" exact="if $highwayEntries? then 'YES' else 'NO'"/>
        <set_value name="$highwayEntryCount" exact="if $highwayEntries != null then @$highwayEntries.count else 0"/>
        <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ') ISOLATION CHECK: Highway entries exist=' + $highwayEntriesExist + ', Found ' + $highwayEntryCount + ' highway entries IN sector ' + $sectorName" chance="100"/>
        </do_if>
        <do_for_each name="$highwayEntry" in="$highwayEntries">
          <!-- Log each highway entry found (even if destination is invalid) -->
          <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$hwDestination" exact="@$highwayEntry.highway.destination"/>
            <set_value name="$hwDestinationSector" exact="@$highwayEntry.highway.destination.sector"/>
            <set_value name="$hasDestination" exact="if $hwDestination? then 'YES' else 'NO'"/>
            <set_value name="$destinationSectorName" exact="if $hwDestinationSector? then @$hwDestinationSector.knownname else 'NULL'"/>
            <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   HIGHWAY ENTRY found: destination=' + $hasDestination + ', destination.sector=' + $destinationSectorName" chance="100"/>
          </do_if>
          <set_value name="$connectedSector" exact="@$highwayEntry.highway.destination.sector"/>
          <!-- Check that connectedSector exists AND is not null before using as table key -->
          <do_if value="$connectedSector? and $connectedSector != null and $connectedSector != $sector">
            <!-- Highway entry connects to a different sector - check if we've already seen this sector -->
            <do_if value="not $foundSectors.{$connectedSector}?">
              <set_value name="$foundSectors.{$connectedSector}" exact="true"/>
              <!-- Check blacklist status -->
              <set_value name="$isBlacklisted" exact="false"/>
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$isBlacklisted">
                <param name="sector" value="$connectedSector"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
              </run_actions>
              
              <!-- Log each connected sector -->
              <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$connectedSectorName" exact="@$connectedSector.knownname"/>
                <set_value name="$blacklistStatus" exact="if $isBlacklisted then 'BLACKLISTED' else 'OK'"/>
                <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   HIGHWAY ' + $connectedSectorName + ' (' + $blacklistStatus + ')'" chance="100"/>
              </do_if>
              
              <!-- Add to appropriate list -->
              <append_to_list name="$validConnectedSectors" exact="$connectedSector"/>
              <do_if value="$isBlacklisted">
                <append_to_list name="$blacklistedSectors" exact="$connectedSector"/>
                <set_value name="$result.$BlacklistedSectorsCount" exact="$result.$BlacklistedSectorsCount + 1"/>
              </do_if>
              <do_else>
                <append_to_list name="$nonBlacklistedSectors" exact="$connectedSector"/>
                <set_value name="$result.$NonBlacklistedSectorsCount" exact="$result.$NonBlacklistedSectorsCount + 1"/>
              </do_else>
            </do_if>
          </do_if>
        </do_for_each>
        
        <!-- Also search for highway entries pointing TO this sector (bidirectional check) -->
        <!-- Highways are bidirectional, so we need to check both directions -->
        <do_if value="$highwayEntryCount == 0">
          <!-- No highway entries found IN this sector - search for highway entries pointing TO this sector -->
          <!-- Vanilla pattern: highwayentrygate.highway.destination.sector -->
          <find_object name="$allHighwayEntries" class="class.highwayentrygate" space="player.galaxy" multiple="true"/>
          <set_value name="$allHighwayEntryCount" exact="if $allHighwayEntries != null then @$allHighwayEntries.count else 0"/>
          <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ') FALLBACK: Searching ' + $allHighwayEntryCount + ' highway entries in galaxy for ones pointing TO sector ' + $sectorName" chance="100"/>
          </do_if>
          <do_for_each name="$highwayEntry" in="$allHighwayEntries">
            <set_value name="$hwDestinationSector" exact="@$highwayEntry.highway.destination.sector"/>
            <set_value name="$hwSourceSector" exact="@$highwayEntry.highway.origin.sector"/>
            <!-- Check if this highway entry points TO our sector -->
            <do_if value="$hwDestinationSector? and $hwDestinationSector == $sector">
              <!-- This highway entry points TO our sector - get the source sector (where highway starts) -->
              <set_value name="$sourceSector" exact="$hwSourceSector"/>
              <do_if value="$sourceSector? and $sourceSector != null and $sourceSector != $sector">
                <!-- Source sector is different from our sector - check if we've already seen this sector -->
                <do_if value="not $foundSectors.{$sourceSector}?">
                  <set_value name="$foundSectors.{$sourceSector}" exact="true"/>
                  <!-- Check blacklist status of source sector -->
                  <set_value name="$isBlacklisted" exact="false"/>
                  <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$isBlacklisted">
                    <param name="sector" value="$sourceSector"/>
                    <param name="ship" value="$ship"/>
                    <param name="blacklistgroup" value="$blacklistgroup"/>
                  </run_actions>
                  
                  <!-- Log highway entry found from opposite direction -->
                  <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$sourceSectorName" exact="@$sourceSector.knownname"/>
                    <set_value name="$blacklistStatus" exact="if $isBlacklisted then 'BLACKLISTED' else 'OK'"/>
                    <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ')   HIGHWAY (FROM OPPOSITE): ' + $sourceSectorName + ' ' + $sectorName + ' (' + $blacklistStatus + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Add to appropriate list -->
                  <append_to_list name="$validConnectedSectors" exact="$sourceSector"/>
                  <do_if value="$isBlacklisted">
                    <append_to_list name="$blacklistedSectors" exact="$sourceSector"/>
                    <set_value name="$result.$BlacklistedSectorsCount" exact="$result.$BlacklistedSectorsCount + 1"/>
                  </do_if>
                  <do_else>
                    <append_to_list name="$nonBlacklistedSectors" exact="$sourceSector"/>
                    <set_value name="$result.$NonBlacklistedSectorsCount" exact="$result.$NonBlacklistedSectorsCount + 1"/>
                  </do_else>
                </do_if>
              </do_if>
            </do_if>
          </do_for_each>
        </do_if>
        
        <!-- Populate shared sector connectivity cache -->
        <set_value name="global.$GT_SectorConnectivityCache.{$sector}" exact="table[$Time = player.age, $Sectors = $validConnectedSectors]"/>

        </do_if>

        <!-- Update result counts -->
        <set_value name="$result.$ConnectedSectorsCount" exact="$validConnectedSectors.count"/>
        
        <!-- Sector is isolated if it has connected sectors AND all of them are blacklisted -->
        <do_if value="$validConnectedSectors.count gt 0">
          <set_value name="$result.$IsIsolated" exact="$result.$NonBlacklistedSectorsCount == 0"/>
        </do_if>
        <do_else>
          <!-- No connected sectors found - might be a dead-end or single-sector zone -->
          <!-- Consider it NOT isolated (can't be isolated if there's nothing to isolate from) -->
          <set_value name="$result.$IsIsolated" exact="false"/>
        </do_else>
        
        <!-- Return detailed information if requested -->
        <do_if value="$returnDetails">
          <set_value name="$result.$ConnectedSectors" exact="$validConnectedSectors"/>
          <set_value name="$result.$BlacklistedSectors" exact="$blacklistedSectors"/>
          <set_value name="$result.$NonBlacklistedSectors" exact="$nonBlacklistedSectors"/>
        </do_if>
        
        <!-- Log final isolation check summary -->
        <do_if value="$doWatch and global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$finalStatus" exact="if $result.$IsIsolated then 'ISOLATED' else 'NOT ISOLATED'"/>
          <set_value name="$sectorName" exact="@$sector.knownname"/>
          <debug_text text="'[GT-Blacklist] (' + $ship.idcode + ') ' + $finalStatus + ': ' + $result.$ConnectedSectorsCount + ' connected sectors (' + $result.$BlacklistedSectorsCount + ' blacklisted, ' + $result.$NonBlacklistedSectorsCount + ' OK) in ' + $sectorName" chance="100"/>
        </do_if>

        <!-- Cache result (short-lived, per ship+sector) -->
        <!-- IMPORTANT: Do NOT use '.simple' as a table member. It is reserved/read-only in MD and causes:
             "Failed to set table[].simple ..."
          -->
        <set_value name="$cacheTime" exact="player.age"/>
        <set_value name="$cacheEntry" exact="table[
          $BlacklistGroup = $blacklistgroup,
          $Result = $result,
          $Time = $cacheTime
        ]"/>
        <!-- Ensure cache root exists and is a valid table -->
        <set_value name="$isolationCacheRootCheck" exact="@global.$GT_IsolationCheckCache.keys.count"/>
        <do_if value="$isolationCacheRootCheck == null">
          <set_value name="global.$GT_IsolationCheckCache" exact="table[]"/>
        </do_if>
        <!-- Ensure ship cache table exists (and is valid) -->
        <set_value name="$isolationCacheShipCheck" exact="@global.$GT_IsolationCheckCache.{$ship}.keys.count"/>
        <do_if value="$isolationCacheShipCheck == null">
          <set_value name="global.$GT_IsolationCheckCache.{$ship}" exact="table[]"/>
        </do_if>
        <!-- Ensure sector cache table exists (and is valid) -->
        <set_value name="$isolationCacheSectorCheck" exact="@global.$GT_IsolationCheckCache.{$ship}.{$sector}.keys.count"/>
        <do_if value="$isolationCacheSectorCheck == null">
          <set_value name="global.$GT_IsolationCheckCache.{$ship}.{$sector}" exact="table[]"/>
        </do_if>
        <!-- Store by mode using $-prefixed keys to avoid reserved members like '.simple' -->
        <do_if value="$returnDetails">
          <set_value name="global.$GT_IsolationCheckCache.{$ship}.{$sector}.$Details" exact="$cacheEntry"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_IsolationCheckCache.{$ship}.{$sector}.$Simple" exact="$cacheEntry"/>
        </do_else>

        </do_if>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Check And Handle Isolation -->
    <!-- Extracted from gt_trading_batch_processor.xml for reusability and maintainability -->
    <!-- This function checks if a ship is isolated, manages state, handles logging, and writes logbook messages -->
    <library name="GT_CheckAndHandleIsolation" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check isolation for"/>
        <param name="state" comment="Batch state table (will be updated and returned)"/>
      </params>
      <actions>
        <set_value name="$shipIsIsolated" exact="false"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Batch] GT_CheckAndHandleIsolation called for ship: ' + $ship.idcode" chance="100"/>
        </do_if>
        <!-- Targeted one-ship isolation diagnostics (high signal, low noise) -->
        <!-- To enable: set global.$GT_Config.$Debug.$WatchIsolationShipId = 'BZK-058' (or any idcode) -->
        <set_value name="$watchShipId" exact="@global.$GT_Config.$Debug.$WatchIsolationShipId"/>
        <set_value name="$doWatch" exact="$watchShipId? and $watchShipId != null and $watchShipId != '' and $ship.idcode == $watchShipId"/>
        
        <!-- Ensure state is valid (save game compatibility) -->
        <!-- If state is null or invalid, initialize as empty table -->
        <!-- Always initialize $updatedState to prevent null property access errors -->
        <set_value name="$updatedState" exact="table[]"/>
        <set_value name="$stateValid" exact="false"/>
        <do_if value="$state?">
          <!-- State variable exists - check if it's actually a valid table (not null) -->
          <!-- Try to access .keys property - if state is null, this will fail safely with @ operator -->
          <set_value name="$stateKeysTest" exact="@$state.keys"/>
          <!-- Check if keys test returned a valid list (not null) -->
          <!-- In X4, if $state is null, @$state.keys returns null, and null? returns true (variable exists) -->
          <!-- So we need to check if the result is actually a valid list by trying to access .count -->
          <set_value name="$stateKeysCountTest" exact="@$stateKeysTest.count"/>
          <!-- Only valid if count test succeeded AND returned a number >= 0 -->
          <!-- If $stateKeysTest was null, then $stateKeysCountTest will be null, and null ge 0 is false -->
          <do_if value="$stateKeysCountTest? and $stateKeysCountTest ge 0">
            <!-- State is valid table - safe to use -->
            <set_value name="$stateValid" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$stateValid">
          <!-- State is valid - use it instead of empty table -->
          <!-- Final safety check - ensure state is still valid before overwriting -->
          <set_value name="$stateFinalKeysCheck" exact="@$state.keys"/>
          <set_value name="$stateFinalCountCheck" exact="@$stateFinalKeysCheck.count"/>
          <do_if value="$stateFinalCountCheck? and $stateFinalCountCheck ge 0">
            <set_value name="$updatedState" exact="$state"/>
          </do_if>
        </do_if>
        <!-- If not valid, $updatedState already initialized to table[] above -->
        
        <!-- Ensure $updatedState is never null before using it -->
        <!-- This must happen BEFORE any property access on $updatedState -->
        <!-- Direct validation - check if $updatedState is a valid table -->
        <set_value name="$updatedStateIsValid" exact="false"/>
        <do_if value="$updatedState?">
          <!-- $updatedState variable exists - verify it's actually a valid table (not null) -->
          <!-- Try accessing .keys property - if $updatedState is null, @ operator returns null safely -->
          <set_value name="$updatedStateKeysTest" exact="@$updatedState.keys"/>
          <!-- If $updatedState is null, $updatedStateKeysTest will be null -->
          <!-- Check if we got a valid list back (not null) by trying to access .count -->
          <set_value name="$updatedStateCountTest" exact="@$updatedStateKeysTest.count"/>
          <!-- Check if count is actually a number (not null) -->
          <!-- If $updatedStateCountTest is null, we can't compare it, so check if it exists AND is >= 0 -->
          <do_if value="$updatedStateCountTest?">
            <!-- Count variable exists - verify it's actually a number by checking it's >= 0 -->
            <!-- If count is null, the comparison will fail or be false -->
            <do_if value="$updatedStateCountTest ge 0">
              <!-- Comparison succeeded - count is >= 0, so it's a valid number and $updatedState is valid table -->
              <set_value name="$updatedStateIsValid" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="not $updatedStateIsValid">
          <!-- $updatedState is null or invalid - reinitialize to empty table -->
          <set_value name="$updatedState" exact="table[]"/>
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist]  $updatedState was null/invalid - reinitialized to empty table (countTest: ' + $updatedStateCountTest + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Ensure $updatedState is still valid before property access -->
        <!-- Double-check that $updatedState hasn't become null somehow -->
        <set_value name="$updatedStateFinalKeysCheck" exact="@$updatedState.keys"/>
        <set_value name="$updatedStateFinalCountCheck" exact="@$updatedStateFinalKeysCheck.count"/>
        <do_if value="not $updatedStateFinalCountCheck? or $updatedStateFinalCountCheck lt 0">
          <!-- $updatedState became invalid - reinitialize to empty table -->
          <set_value name="$updatedState" exact="table[]"/>
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist]  $updatedState became invalid after validation - reinitialized to empty table'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Check if isolation has already been checked for this ship -->
        <!-- Use safe operator @ for property access to prevent null errors -->
        <set_value name="$isolationAlreadyChecked" exact="@$updatedState.$shipIsIsolatedChecked"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Isolation check: alreadyChecked=' + (if $isolationAlreadyChecked? then 'yes' else 'no')" chance="100"/>
        </do_if>
        <do_if value="not $isolationAlreadyChecked?">
          <!-- First time checking isolation for this ship -->
          <set_value name="$currentSector" exact="$ship.sector"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Current sector check: sector=' + (if $currentSector? then 'exists' else 'null')" chance="100"/>
          </do_if>
          <do_if value="$currentSector?">
            <!-- Check if current sector is blacklisted (if yes, not isolated, it's just blacklisted) -->
            <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
              <param name="ship" value="$ship"/>
            </run_actions>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$currentSectorIsBlacklisted">
              <param name="sector" value="$currentSector"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <do_if value="$doWatch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Isolation] (' + $ship.idcode + ') CurrentSector=' + @$currentSector.knownname + ' | CurrentSectorBlacklisted=' + $currentSectorIsBlacklisted + ' | blacklistgroup=' + $blacklistgroup" chance="100"/>
            </do_if>
            <do_if value="not $currentSectorIsBlacklisted">
              <!-- Ship is in non-blacklisted sector - check if all routes are blocked -->
              <run_actions ref="md.GT_Libraries_Blacklist.GT_CheckConnectedSectorsBlacklisted" result="$isolationCheck">
                <param name="sector" value="$currentSector"/>
                <param name="ship" value="$ship"/>
                <param name="returnDetails" value="$doWatch"/>
              </run_actions>
              <set_value name="$isolatedValue" exact="@$isolationCheck.$IsIsolated"/>
              <set_value name="$shipIsIsolated" exact="if $isolatedValue? and ($isolatedValue == true or $isolatedValue == 1) then true else false"/>
              <do_if value="$doWatch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Isolation] (' + $ship.idcode + ') Connected=' + @$isolationCheck.$ConnectedSectorsCount + ' | Blacklisted=' + @$isolationCheck.$BlacklistedSectorsCount + ' | OK=' + @$isolationCheck.$NonBlacklistedSectorsCount + ' | IsIsolated=' + $shipIsIsolated" chance="100"/>
                <!-- When watched, GT_CheckConnectedSectorsBlacklisted returns $ConnectedSectors/$BlacklistedSectors/$NonBlacklistedSectors -->
                <set_value name="$okList" exact="@$isolationCheck.$NonBlacklistedSectors"/>
                <set_value name="$blList" exact="@$isolationCheck.$BlacklistedSectors"/>
                <set_value name="$okCount" exact="if $okList != null then @$okList.count else 0"/>
                <set_value name="$blCount" exact="if $blList != null then @$blList.count else 0"/>
                <set_value name="$okNames" exact="''"/>
                <set_value name="$blNames" exact="''"/>
                <do_all exact="$okCount" counter="$i">
                  <set_value name="$s" exact="$okList.{$i}"/>
                  <do_if value="$okNames != ''">
                    <set_value name="$okNames" exact="$okNames + ', '"/>
                  </do_if>
                  <set_value name="$okNames" exact="$okNames + (if @$s.knownname then @$s.knownname else 'NULL')"/>
                </do_all>
                <do_all exact="$blCount" counter="$j">
                  <set_value name="$s" exact="$blList.{$j}"/>
                  <do_if value="$blNames != ''">
                    <set_value name="$blNames" exact="$blNames + ', '"/>
                  </do_if>
                  <set_value name="$blNames" exact="$blNames + (if @$s.knownname then @$s.knownname else 'NULL')"/>
                </do_all>
                <debug_text text="'[GT-Isolation] (' + $ship.idcode + ') OK connected sectors: ' + (if $okNames != '' then $okNames else '(none)') " chance="100"/>
                <debug_text text="'[GT-Isolation] (' + $ship.idcode + ') BLACKLISTED connected sectors: ' + (if $blNames != '' then $blNames else '(none)') " chance="100"/>
              </do_if>
              <!-- Final safety check before setting properties -->
              <!-- Ensure $updatedState is still valid (not null) before setting properties -->
              <set_value name="$updatedStatePreSetCheck" exact="@$updatedState.keys"/>
              <do_if value="$updatedStatePreSetCheck?">
                <!-- $updatedState is valid - safe to set properties -->
                <set_value name="$updatedState.$shipIsIsolated" exact="if $shipIsIsolated then 1 else 0"/>
                <set_value name="$updatedState.$shipIsIsolatedChecked" exact="1"/>
              </do_if>
              <do_else>
                <!-- $updatedState is null - reinitialize and set properties -->
                <set_value name="$updatedState" exact="table[]"/>
                <set_value name="$updatedState.$shipIsIsolated" exact="if $shipIsIsolated then 1 else 0"/>
                <set_value name="$updatedState.$shipIsIsolatedChecked" exact="1"/>
                <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Blacklist]  $updatedState was null before setting isolation properties - reinitialized'" chance="100"/>
                </do_if>
              </do_else>
              
              <!-- Log isolation status -->
              <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$connectedCount" exact="@$isolationCheck.$ConnectedSectorsCount"/>
                <set_value name="$blacklistedCount" exact="@$isolationCheck.$BlacklistedSectorsCount"/>
                <set_value name="$nonBlacklistedCount" exact="@$isolationCheck.$NonBlacklistedSectorsCount"/>
                <set_value name="$currentSectorName" exact="@$currentSector.knownname"/>
                <do_if value="$shipIsIsolated">
                  <debug_text text="'[GT-Batch] (' + $ship.idcode + ') ISOLATED: All ' + $connectedCount + ' connected sectors are blacklisted (ship in ' + $currentSectorName + ')'" chance="100"/>
                </do_if>
                <do_else>
                  <debug_text text="'[GT-Batch] (' + $ship.idcode + ') NOT ISOLATED: ' + $nonBlacklistedCount + ' of ' + $connectedCount + ' connected sectors are non-blacklisted (ship in ' + $currentSectorName + ')'" chance="100"/>
                </do_else>
              </do_if>
              
              <!-- Set isolated flag and trigger name update if isolated -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Isolation check result: shipIsIsolated=' + $shipIsIsolated + ', isolatedValue=' + $isolatedValue" chance="100"/>
              </do_if>
              
              <do_if value="$shipIsIsolated">
                <!-- Set isolated flag for ship name updates (always set when isolated, not just on first detection) -->
                <do_if value="not global.$GT_IsolatedTradeActive?">
                  <set_value name="global.$GT_IsolatedTradeActive" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_IsolatedTradeActive.{$ship}" exact="true"/>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Batch] (' + $ship.idcode + ') ISOLATION FLAG SET: global.$GT_IsolatedTradeActive.{$ship} = true'" chance="100"/>
                </do_if>
                
                <!-- Check if isolation was already logged (for logbook message only) -->
                <set_value name="$isolationAlreadyLogged" exact="false"/>
                <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$IsolationLogged?">
                  <set_value name="$isolationAlreadyLogged" exact="global.$GT_Ships.{$ship}.$IsolationLogged"/>
                </do_if>
                
                <!-- Log isolation message if not already logged -->
                <do_if value="not $isolationAlreadyLogged">
                  <!-- Initialization guarantees global.$GT_Ships exists -->
                  <do_if value="not global.$GT_Ships.{$ship}?">
                    <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_Ships.{$ship}.$IsolationLogged" exact="true"/>
                  <set_value name="$currentSectorName" exact="@$currentSector.knownname"/>
                  <do_if value="not $currentSectorName?">
                    <set_value name="$currentSectorName" exact="'Unknown Sector'"/>
                  </do_if>
                  <set_value name="$shipName" exact="@$ship.knownname"/>
                  <do_if value="not $shipName?">
                    <set_value name="$shipName" exact="$ship.idcode"/>
                  </do_if>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Batch] (' + $ship.idcode + ') ISOLATION DETECTED: Ship in ' + $currentSectorName + ' (non-blacklisted) but ALL routes to other sectors blocked by blacklist - prioritizing intra-sector trades'" chance="100"/>
                  </do_if>
                  <set_value name="$logbookEnabled" exact="true"/>
                  <do_if value="global.$GT_Ships.{$ship}.$LogbookEntries?">
                    <set_value name="$logbookEnabled" exact="global.$GT_Ships.{$ship}.$LogbookEntries"/>
                  </do_if>
                  <do_if value="$logbookEnabled">
                    <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
                    <set_value name="$logbookMessage" exact="{77000,3211}.[$shipName, $currentSectorName]"/>
                    
                    <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                      <param name="Message" value="$logbookMessage"/>
                      <param name="Category" value="'general'"/>
                      <param name="Title" value="'Isolated Trading: ' + $shipName"/>
                      <param name="Object" value="$ship"/>
                      <param name="Interaction" value="'showonmap'"/>
                      <param name="CheckGlobalSettings" value="false"/>
                    </run_actions>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Batch] (' + $ship.idcode + ') ISOLATION LOGBOOK MESSAGE WRITTEN: Ship ' + $shipName + ' in sector ' + $currentSectorName + ' - forced to intra-sector trades only due to blacklisted hub sectors'" chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- Trigger ship name update to show [ISOLATED] flag (always, not just on first detection) -->
                <!-- Only update if ship has a pilot (required for name update) -->
                <set_value name="$pilot" exact="@$ship.pilot"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Checking pilot for name update: pilot=' + (if $pilot? then 'exists' else 'null') + ', exists=' + (if $pilot.exists then 'yes' else 'no')" chance="100"/>
                </do_if>
                <do_if value="$pilot? and $pilot.exists">
                  <set_value name="$pilotXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
                  <do_if value="not $pilotXP?">
                    <set_value name="$pilotXP" exact="0"/>
                  </do_if>
                  <set_value name="$skillLevel" exact="1"/>
                  <do_all exact="15" counter="$lvl">
                    <do_if value="$pilotXP ge global.$GT_Config.$XP.$SkillThresholds.{$lvl}">
                      <set_value name="$skillLevel" exact="$lvl"/>
                    </do_if>
                  </do_all>
                  <set_value name="$rankTitle" exact="'Lehrling'"/>
                  <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
                    <set_value name="$rankIndex" exact="($skillLevel / 3)i + 1"/>
                    <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
                      <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
                    </do_if>
                    <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
                      <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Signal ship name update with isolated nameType -->
                  <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                    $Ship = $ship,
                    $pilot = $pilot,
                    $xp = $pilotXP,
                    $level = $skillLevel,
                    $rank = $rankTitle,
                    $nameType = 'isolated'
                  ]"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Triggered ship name update for isolated ship'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
            <do_else>
              <!-- Current sector is blacklisted - ship is not isolated, it's just in a blacklisted sector -->
              <set_value name="$shipIsIsolated" exact="false"/>
              <!-- Clear isolated flag if it was previously set -->
              <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
                <remove_value name="global.$GT_IsolatedTradeActive.{$ship}"/>
              </do_if>
              <!-- Final safety check before setting properties -->
              <set_value name="$updatedStatePreSetCheck2" exact="@$updatedState.keys"/>
              <do_if value="$updatedStatePreSetCheck2?">
                <!-- $updatedState is valid - safe to set properties -->
                <set_value name="$updatedState.$shipIsIsolated" exact="0"/>
                <set_value name="$updatedState.$shipIsIsolatedChecked" exact="1"/>
              </do_if>
              <do_else>
                <!-- $updatedState is null - reinitialize and set properties -->
                <set_value name="$updatedState" exact="table[]"/>
                <set_value name="$updatedState.$shipIsIsolated" exact="0"/>
                <set_value name="$updatedState.$shipIsIsolatedChecked" exact="1"/>
                <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Blacklist]  $updatedState was null before setting isolation properties (blacklisted sector) - reinitialized'" chance="100"/>
                </do_if>
              </do_else>
            </do_else>
          </do_if>
        </do_if>
        <do_else>
          <!-- Isolation already checked - retrieve from state -->
          <set_value name="$isolatedStateValue" exact="@$updatedState.$shipIsIsolated"/>
          <set_value name="$shipIsIsolated" exact="if $isolatedStateValue? and ($isolatedStateValue == 1 or $isolatedStateValue == true) then true else false"/>
          
          <!-- CRITICAL: Also check global flag as authoritative source (state might be stale) -->
          <!-- The global flag is set when isolation is detected, so it's the source of truth -->
          <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
            <set_value name="$shipIsIsolated" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Overriding cached isolation state with global flag (state=' + $isolatedStateValue + ', global=true)'" chance="100"/>
            </do_if>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Cached isolation check: stateValue=' + $isolatedStateValue + ', shipIsIsolated=' + $shipIsIsolated + ', globalFlag=' + (if global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}? then 'true' else 'false')" chance="100"/>
          </do_if>
          
          <!-- Set or clear isolated flag based on current state -->
          <do_if value="$shipIsIsolated">
            <!-- Ship is isolated - ensure flag is set -->
            <!-- CRITICAL: Isolated and fallback are mutually exclusive - clear fallback flag when isolated is active -->
            <do_if value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{$ship}?">
              <remove_value name="global.$GT_FallbackTradeActive.{$ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Cleared [FALLBACK] flag - isolated takes precedence'" chance="100"/>
              </do_if>
            </do_if>
            
            <do_if value="not global.$GT_IsolatedTradeActive?">
              <set_value name="global.$GT_IsolatedTradeActive" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_IsolatedTradeActive.{$ship}?">
              <set_value name="global.$GT_IsolatedTradeActive.{$ship}" exact="true"/>
            </do_if>
            
            <!-- Trigger ship name update to show [ISOLATED] flag (always when isolated) -->
            <set_value name="$pilot" exact="@$ship.pilot"/>
            <do_if value="$pilot? and $pilot.exists">
              <set_value name="$pilotXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
              <do_if value="not $pilotXP?">
                <set_value name="$pilotXP" exact="0"/>
              </do_if>
              <set_value name="$skillLevel" exact="1"/>
              <do_all exact="15" counter="$lvl">
                <do_if value="$pilotXP ge global.$GT_Config.$XP.$SkillThresholds.{$lvl}">
                  <set_value name="$skillLevel" exact="$lvl"/>
                </do_if>
              </do_all>
              <set_value name="$rankTitle" exact="'Lehrling'"/>
              <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
                <set_value name="$rankIndex" exact="($skillLevel / 3)i + 1"/>
                <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
                  <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
                </do_if>
                <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
                  <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
                </do_if>
              </do_if>
              
              <!-- Signal ship name update with isolated nameType -->
              <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                $Ship = $ship,
                $pilot = $pilot,
                $xp = $pilotXP,
                $level = $skillLevel,
                $rank = $rankTitle,
                $nameType = 'isolated'
              ]"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Triggered ship name update for isolated ship (from cached state)'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Ship is not isolated - clear flag if it was set -->
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
              <remove_value name="global.$GT_IsolatedTradeActive.{$ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Batch] (' + $ship.idcode + ') Ship no longer isolated - cleared [ISOLATED] flag'" chance="100"/>
              </do_if>
            </do_if>
          </do_else>
        </do_else>
        
        <!-- Return result table -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$IsIsolated" exact="$shipIsIsolated"/>
        <set_value name="$result.$UpdatedState" exact="$updatedState"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Blacklist manager Lua is loaded via ui.xml (packed-safe).
         Initialization is handled by gt_threat_intelligence.xml on gt_blacklist_manager Ready. -->
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Libraries_Distribution" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <library name="GT_CalculateStorageRatio" purpose="run_actions">
      <params>
        <param name="station"/>
        <param name="ware"/>
      </params>
      <actions>
        <set_value name="$target" exact="$station.cargo.{$ware}.target"/>
        <do_if value="$target le 0">
          <return value="0"/>
        </do_if>
        <return value="($station.cargo.{$ware}.count * 100.0) / $target"/>
      </actions>
    </library>

    <library name="GT_EvaluateDistributionNeed" purpose="run_actions">
      <params>
        <param name="sourceRatio"/>
        <param name="targetRatio"/>
        <param name="minStorage"/>
        <param name="staticStorage"/>
        <param name="maxStorage"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[$ShouldDistribute = false, $Priority = 0]"/>
        <do_if value="$sourceRatio le $staticStorage">
          <return value="$result"/>
        </do_if>
        <do_if value="$targetRatio lt $minStorage">
          <set_value name="$result.$ShouldDistribute" exact="true"/>
          <set_value name="$result.$Priority" exact="2"/>
          <return value="$result"/>
        </do_if>
        <do_if value="$sourceRatio gt $maxStorage and $sourceRatio gt ($targetRatio + 10)">
          <set_value name="$result.$ShouldDistribute" exact="true"/>
          <set_value name="$result.$Priority" exact="1"/>
        </do_if>
        <return value="$result"/>
      </actions>
    </library>

    <library name="GT_ScoreDistributionTrade" purpose="run_actions">
      <params>
        <param name="sourceRatio"/>
        <param name="priority"/>
        <param name="tradeAmount"/>
        <param name="cargoCapacity"/>
        <param name="staticStorage"/>
      </params>
      <actions>
        <set_value name="$urgencyMultiplier" exact="if $priority == 2 then 2.0 else 1.0"/>
        <set_value name="$excessFactor" exact="($sourceRatio - $staticStorage) / 100.0"/>
        <set_value name="$fillFactor" exact="$tradeAmount / [$cargoCapacity, 1].max"/>
        <return value="$excessFactor * $urgencyMultiplier * $fillFactor * 1000"/>
      </actions>
    </library>

    <library name="GT_BuildWareBasket" purpose="run_actions">
      <params>
        <param name="sourceStation"/>
        <param name="warebasket"/>
      </params>
      <actions>
        <create_list name="$effectiveWares"/>
        <do_if value="$warebasket? and $warebasket.count gt 0">
          <do_all exact="$warebasket.count" counter="$i">
            <append_to_list name="$effectiveWares" exact="$warebasket.{$i}"/>
          </do_all>
          <return value="$effectiveWares"/>
        </do_if>

        <set_value name="$products" exact="$sourceStation.products.list"/>
        <set_value name="$tradewares" exact="$sourceStation.tradewares.list"/>

        <do_all exact="$products.count" counter="$i">
          <append_to_list name="$effectiveWares" exact="$products.{$i}"/>
        </do_all>
        <do_all exact="$tradewares.count" counter="$i">
          <set_value name="$ware" exact="$tradewares.{$i}"/>
          <set_value name="$exists" exact="false"/>
          <do_all exact="$effectiveWares.count" counter="$j">
            <do_if value="$effectiveWares.{$j} == $ware">
              <set_value name="$exists" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          <do_if value="not $exists">
            <append_to_list name="$effectiveWares" exact="$ware"/>
          </do_if>
        </do_all>
        <return value="$effectiveWares"/>
      </actions>
    </library>

    <!-- Trade finder is implemented in AI script for execution ordering; keep a no-op placeholder for API stability. -->
    <library name="GT_FindBestDistributionTrade" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="sourceStation"/>
        <param name="destList"/>
        <param name="warebasket"/>
        <param name="minStorage"/>
        <param name="staticStorage"/>
        <param name="maxStorage"/>
        <param name="allowillegal"/>
        <param name="fleetcoordination"/>
      </params>
      <actions>
        <return value="table[$BestTrade = null, $SourceOffer = null, $DestOffer = null]"/>
      </actions>
    </library>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Libraries_General" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================= -->
    <!-- GENERAL UTILITIES -->
    <!-- Consolidated from: gt_trade_utilities.xml, gt_data_utilities.xml, gt_utilities.xml, gt_ai_script_utilities.xml, gt_logbook_utilities.xml -->
    <!-- Trade-search trace logging: glx_lib_trading_log.xml (GLX_Lib_TradingLog): GT_LogTradeSearch, GT_LogTradeSearchStructured, GT_GenerateTraceId, GT_UpdatePipelineCounter -->
    <!-- Trade key / reservations: glx_lib_reservations.xml (GLX_Lib_Reservations) -->
    <!-- Per-home cache: glx_lib_cache.xml (GLX_Lib_Cache) -->
    <!-- ========================================= -->
    <!-- ========================================= -->
    <!-- TRADE UTILITIES -->
    <!-- ========================================= -->

    <!-- Ensure global fallback-instrumentation table exists (must be table, not list). -->
    <library name="GT_EnsureFallbackActivationsTable" purpose="run_actions">
      <actions>
        <do_if value="not global.$GT_FallbackActivations? or typeof global.$GT_FallbackActivations != datatype.table">
          <set_value name="global.$GT_FallbackActivations" exact="table[]"/>
        </do_if>
      </actions>
    </library>

    <!-- Increment a keyed fallback counter; returns new count. Mutate a local copy then assign global (in-place global subscript writes abort). -->
    <library name="GT_IncrementFallbackActivation" purpose="run_actions">
      <params>
        <param name="key" comment="String key in global.$GT_FallbackActivations"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Libraries_General.GT_EnsureFallbackActivationsTable"/>
        <set_value name="$fa" exact="table[]"/>
        <do_if value="global.$GT_FallbackActivations? and typeof global.$GT_FallbackActivations == datatype.table">
          <set_value name="$fa" exact="global.$GT_FallbackActivations"/>
        </do_if>
        <set_value name="$prev" exact="0"/>
        <do_if value="$fa.{$key}?">
          <set_value name="$prev" exact="$fa.{$key}"/>
        </do_if>
        <set_value name="$next" exact="$prev + 1"/>
        <set_value name="$fa.{$key}" exact="$next"/>
        <set_value name="global.$GT_FallbackActivations" exact="$fa"/>
        <return value="$next"/>
      </actions>
    </library>

    <!-- Normalize per-sector failed-pair storage to nested table {buySector}->{sellSector}->record.
         Accepts legacy list entries (gt_trading_ai) or nested table (cache prefilter). -->
    <library name="GT_NormalizeFailedSectorPairsSectorEntry" purpose="run_actions">
      <params>
        <param name="rawEntry" default="null"/>
        <param name="expirationTime" default="1800s"/>
      </params>
      <actions>
        <set_value name="$normalized" exact="table[]"/>
        <do_if value="not $rawEntry?">
          <return value="$normalized"/>
        </do_if>
        <do_if value="typeof $rawEntry == datatype.table">
          <set_value name="$buyKeys" exact="$rawEntry.keys"/>
          <do_all exact="$buyKeys.count" counter="$bki">
            <set_value name="$buyKey" exact="$buyKeys.{$bki}"/>
            <do_if value="$rawEntry.{$buyKey}? and typeof $rawEntry.{$buyKey} == datatype.table">
              <set_value name="$innerTable" exact="$rawEntry.{$buyKey}"/>
              <set_value name="$sellKeys" exact="$innerTable.keys"/>
              <do_all exact="$sellKeys.count" counter="$ski">
                <set_value name="$sellKey" exact="$sellKeys.{$ski}"/>
                <set_value name="$record" exact="@$innerTable.{$sellKey}"/>
                <set_value name="$keep" exact="true"/>
                <do_if value="$expirationTime gt 0s and $record? and $record.$Timestamp?">
                  <do_if value="(player.age - $record.$Timestamp) gt $expirationTime">
                    <set_value name="$keep" exact="false"/>
                  </do_if>
                </do_if>
                <do_if value="$keep and $record?">
                  <set_value name="$buyMap" exact="if $normalized.{$buyKey}? then $normalized.{$buyKey} else table[]"/>
                  <set_value name="$buyMap.{$sellKey}" exact="$record"/>
                  <set_value name="$normalized.{$buyKey}" exact="$buyMap"/>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
        </do_if>
        <do_elseif value="typeof $rawEntry == datatype.list">
          <do_all exact="$rawEntry.count" counter="$li">
            <set_value name="$legacyRec" exact="$rawEntry.{$li}"/>
            <do_if value="$legacyRec? and $legacyRec.$BuySector? and $legacyRec.$BuySector.exists and $legacyRec.$SellSector? and $legacyRec.$SellSector.exists">
              <set_value name="$keepLegacy" exact="true"/>
              <do_if value="$expirationTime gt 0s and $legacyRec.$Timestamp?">
                <do_if value="(player.age - $legacyRec.$Timestamp) gt $expirationTime">
                  <set_value name="$keepLegacy" exact="false"/>
                </do_if>
              </do_if>
              <do_if value="$keepLegacy">
                <set_value name="$legacyBuy" exact="$legacyRec.$BuySector"/>
                <set_value name="$legacySell" exact="$legacyRec.$SellSector"/>
                <set_value name="$legacyBuyMap" exact="if $normalized.{$legacyBuy}? then $normalized.{$legacyBuy} else table[]"/>
                <set_value name="$legacyBuyMap.{$legacySell}" exact="table[
                  $Reason = if $legacyRec.$Reason? then $legacyRec.$Reason else '',
                  $Timestamp = if $legacyRec.$Timestamp? then $legacyRec.$Timestamp else player.age
                ]"/>
                <set_value name="$normalized.{$legacyBuy}" exact="$legacyBuyMap"/>
              </do_if>
            </do_if>
          </do_all>
        </do_elseif>
        <return value="$normalized"/>
      </actions>
    </library>

    <!-- Record a failed buy/sell sector pair for ships sharing $currentSector. Returns buy-sector key count. -->
    <library name="GT_RecordFailedSectorPair" purpose="run_actions">
      <params>
        <param name="currentSector" default="null"/>
        <param name="buySector" default="null"/>
        <param name="sellSector" default="null"/>
        <param name="reason" default="''"/>
        <param name="expirationTime" default="1800s"/>
      </params>
      <actions>
        <do_if value="not $currentSector? or not $currentSector.exists or not $buySector? or not $buySector.exists or not $sellSector? or not $sellSector.exists">
          <return value="0"/>
        </do_if>
        <set_value name="$root" exact="table[]"/>
        <do_if value="global.$GT_FailedSectorPairs? and typeof global.$GT_FailedSectorPairs == datatype.table">
          <set_value name="$root" exact="global.$GT_FailedSectorPairs"/>
        </do_if>
        <set_value name="$rawSector" exact="if $root.{$currentSector}? then $root.{$currentSector} else null"/>
        <run_actions ref="md.GT_Libraries_General.GT_NormalizeFailedSectorPairsSectorEntry" result="$sectorMap">
          <param name="rawEntry" value="$rawSector"/>
          <param name="expirationTime" value="$expirationTime"/>
        </run_actions>
        <set_value name="$buyMap" exact="if $sectorMap.{$buySector}? then $sectorMap.{$buySector} else table[]"/>
        <set_value name="$buyMap.{$sellSector}" exact="table[$Reason = $reason, $Timestamp = player.age]"/>
        <set_value name="$sectorMap.{$buySector}" exact="$buyMap"/>
        <set_value name="$root.{$currentSector}" exact="$sectorMap"/>
        <do_if value="$root.keys.count gt 100">
          <set_value name="$root" exact="table[$currentSector = $sectorMap]"/>
        </do_if>
        <set_value name="global.$GT_FailedSectorPairs" exact="$root"/>
        <return value="$sectorMap.keys.count"/>
      </actions>
    </library>
    
    <!-- Is Intra-Sector Trade -->
    <library name="GT_IsIntraSectorTrade" purpose="run_actions">
      <params>
        <param name="buySector" comment="Buy station sector"/>
        <param name="sellSector" comment="Sell station sector"/>
        <param name="currentSector" comment="Ship's current sector"/>
      </params>
      <actions>
        <do_if value="$buySector? and $sellSector? and $currentSector?">
          <do_if value="$buySector == $currentSector and $sellSector == $currentSector">
            <return value="true"/>
          </do_if>
        </do_if>
        <return value="false"/>
      </actions>
    </library>

    <!-- Resolve a sector component from a stable idcode string (survives dead $SellSector refs). -->
    <library name="GT_ResolveSectorByIdcodeInRange" purpose="run_actions">
      <params>
        <param name="homeSector" comment="Anchor for find_sector_in_range scan"/>
        <param name="sectorIdcode" comment="Stable sector.idcode string stamped at cache write"/>
        <param name="maxScanDistance" default="15" comment="Jump radius for sector scan"/>
      </params>
      <actions>
        <set_value name="$resolvedSector" exact="null"/>
        <do_if value="$sectorIdcode? and $homeSector? and @$homeSector.exists">
          <set_value name="$scanDist" exact="if $maxScanDistance? and $maxScanDistance gt 0 then $maxScanDistance else 15"/>
          <find_sector_in_range name="$scanSectors" object="$homeSector" maxdistance="$scanDist" multiple="true"/>
          <do_if value="$scanSectors? and $scanSectors.count gt 0">
            <do_for_each name="$scanSec" in="$scanSectors">
              <do_if value="not $resolvedSector? and $scanSec? and @$scanSec.exists and $scanSec.idcode? and @$scanSec.idcode == $sectorIdcode">
                <set_value name="$resolvedSector" exact="$scanSec"/>
              </do_if>
            </do_for_each>
          </do_if>
        </do_if>
        <return value="$resolvedSector"/>
      </actions>
    </library>

    <!-- Resolve a station/build storage from a stable idcode string (survives dead offer/station refs). -->
    <library name="GT_ResolveStationByIdcodeInRange" purpose="run_actions">
      <params>
        <param name="homeSector" comment="Anchor for find_sector_in_range scan"/>
        <param name="stationIdcode" comment="Stable station.idcode (or build-storage base idcode)"/>
        <param name="maxScanDistance" default="15" comment="Jump radius for sector scan"/>
      </params>
      <actions>
        <set_value name="$resolvedStation" exact="null"/>
        <do_if value="$stationIdcode? and $homeSector? and @$homeSector.exists">
          <set_value name="$scanDist" exact="if $maxScanDistance? and $maxScanDistance gt 0 then $maxScanDistance else 15"/>
          <find_sector_in_range name="$scanSectors" object="$homeSector" maxdistance="$scanDist" multiple="true"/>
          <do_if value="$scanSectors? and $scanSectors.count gt 0">
            <do_for_each name="$scanSec" in="$scanSectors">
              <do_if value="not $resolvedStation? and $scanSec? and @$scanSec.exists">
                <find_station name="$scanStations" space="$scanSec" multiple="true"/>
                <do_if value="$scanStations? and $scanStations.count gt 0">
                  <do_for_each name="$scanSt" in="$scanStations">
                    <do_if value="not $resolvedStation? and $scanSt? and @$scanSt.exists and $scanSt.idcode? and @$scanSt.idcode == $stationIdcode">
                      <set_value name="$resolvedStation" exact="$scanSt"/>
                    </do_if>
                  </do_for_each>
                </do_if>
                <do_if value="not $resolvedStation?">
                  <find_object name="$scanBsObjs" class="class.buildstorage" space="$scanSec" owner="faction.player" multiple="true"/>
                  <do_if value="$scanBsObjs? and $scanBsObjs.count gt 0">
                    <do_for_each name="$scanBsCand" in="$scanBsObjs">
                      <do_if value="not $resolvedStation? and $scanBsCand? and @$scanBsCand.exists and $scanBsCand.base? and @$scanBsCand.base.exists and @$scanBsCand.base.idcode == $stationIdcode">
                        <set_value name="$resolvedStation" exact="$scanBsCand"/>
                      </do_if>
                    </do_for_each>
                  </do_if>
                </do_if>
              </do_if>
            </do_for_each>
          </do_if>
        </do_if>
        <return value="$resolvedStation"/>
      </actions>
    </library>
    
    <!-- Calculate Trade Efficiency -->
    <library name="GT_CalculateTradeEfficiency" purpose="run_actions">
      <params>
        <param name="profit" comment="Trade profit"/>
        <param name="distance" default="0" comment="Trade distance (jumps) - legacy parameter, used as fallback"/>
        <param name="distancePenaltyMultiplier" default="1.0" comment="Distance penalty multiplier (0.0-2.0)"/>
        <param name="factionPriority" default="2" comment="Faction priority (0=Player, 1=Foreign, 2=Equal)"/>
        <param name="buyStationOwner" default="null" comment="Buy station owner faction"/>
        <param name="sellStationOwner" default="null" comment="Sell station owner faction"/>
        <param name="homeSector" default="null" comment="Home sector for path efficiency calculation"/>
        <param name="shipSector" default="null" comment="Ship's current sector"/>
        <param name="buySector" default="null" comment="Buy station sector"/>
        <param name="sellSector" default="null" comment="Sell station sector"/>
        <param name="shipToBuyDistance" default="-1" comment="Distance from ship to buy station (for path efficiency)"/>
        <param name="buyToSellDistance" default="-1" comment="Distance from buy station to sell station"/>
        <param name="homeToBuyDistance" default="-1" comment="Distance from home sector to buy station"/>
        <param name="homeToSellDistance" default="-1" comment="Distance from home sector to sell station"/>
      </params>
      <actions>
        <!-- Multi-factor distance penalty system -->
        <!-- Improved scoring that separately penalizes:
             1. Ship Buy distance (HEAVY weight - ship must travel first)
             2. Buy Sell distance (MODERATE weight - trade route length)
             3. Home distance (LIGHT weight - territorial control)
        -->
        <set_value name="$adjustedDistance" exact="0.0"/>
        
        <!-- Check if we have all required parameters for new multi-factor system -->
        <set_value name="$useMultiFactor" exact="false"/>
        <do_if value="$shipToBuyDistance ge 0 and $buyToSellDistance ge 0 and $homeToBuyDistance ge 0 and $homeToSellDistance ge 0 and $buySector? and $sellSector?">
          <set_value name="$useMultiFactor" exact="true"/>
        </do_if>
        
        <!-- Log which system is being used -->
        <!-- NOTE: This library is called in hot loops (cache scoring). Guard verbose logging behind DiagnosticQueries to avoid CPU/log spikes. -->
        <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_Config.$Debug.$DiagnosticQueries and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Efficiency] Multi-factor=' + $useMultiFactor + ', Ship Buy=' + $shipToBuyDistance + ', Buy Sell=' + $buyToSellDistance + ', Home Buy=' + $homeToBuyDistance + ', Home Sell=' + $homeToSellDistance" chance="100"/>
        </do_if>
        
        <do_if value="$useMultiFactor">
          <!-- Factor 1: Ship to Buy Distance Penalty (HEAVY WEIGHT - ship must travel first) -->
          <!-- This is the most important - ship has to get to buy station first -->
          <!-- Weight: 4.0 (increased from 3.0), Quadratic base: 3.5 (steeper penalty for longer distances) -->
          <!-- Example: 7 jumps = 7 * 4 * (1 + 4) = 140 penalty units (with multiplier=2: 280 units) -->
          <!-- Apply user's distance penalty multiplier setting -->
          <set_value name="$shipToBuyBase" exact="3.5"/>
          <set_value name="$shipToBuyRatio" exact="$shipToBuyDistance / $shipToBuyBase"/>
          <set_value name="$shipToBuyNonLinear" exact="1.0 + ($shipToBuyRatio * $shipToBuyRatio)"/>
          <set_value name="$shipToBuyPenalty" exact="$shipToBuyDistance * 4.0 * $shipToBuyNonLinear * $distancePenaltyMultiplier"/>
          
          <!-- Factor 2: Buy to Sell Distance Penalty (MODERATE WEIGHT - trade route length) -->
          <!-- Encourages shorter trade routes between stations -->
          <!-- Weight: 1.5, Quadratic base: 8.0 (moderate penalty) -->
          <!-- Apply user's distance penalty multiplier setting -->
          <set_value name="$buyToSellBase" exact="8.0"/>
          <set_value name="$buyToSellRatio" exact="$buyToSellDistance / $buyToSellBase"/>
          <set_value name="$buyToSellNonLinear" exact="1.0 + ($buyToSellRatio * $buyToSellRatio)"/>
          <set_value name="$buyToSellPenalty" exact="$buyToSellDistance * 1.5 * $buyToSellNonLinear * $distancePenaltyMultiplier"/>
          
          <!-- Factor 3: Home Distance Penalty (LIGHT WEIGHT - territorial control) -->
          <!-- Penalize trades far from home (both stations) - encourages staying near home base -->
          <!-- Weight: 0.5, Quadratic base: 10.0 (light penalty) -->
          <!-- Apply user's distance penalty multiplier setting -->
          <set_value name="$maxHomeDistance" exact="[$homeToBuyDistance, $homeToSellDistance].max"/>
          <set_value name="$homeDistanceBase" exact="10.0"/>
          <set_value name="$homeDistanceRatio" exact="$maxHomeDistance / $homeDistanceBase"/>
          <set_value name="$homeDistanceNonLinear" exact="1.0 + ($homeDistanceRatio * $homeDistanceRatio)"/>
          <set_value name="$homeDistancePenalty" exact="$maxHomeDistance * 0.5 * $homeDistanceNonLinear * $distancePenaltyMultiplier"/>
          
          <!-- Combined Adjusted Distance -->
          <set_value name="$adjustedDistance" exact="$shipToBuyPenalty + $buyToSellPenalty + $homeDistancePenalty"/>
          
          <!-- Log penalty breakdown -->
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_Config.$Debug.$DiagnosticQueries and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Efficiency] Multi-factor penalties (multiplier=' + $distancePenaltyMultiplier + '): Ship Buy=' + $shipToBuyPenalty + ', Buy Sell=' + $buyToSellPenalty + ', Home=' + $homeDistancePenalty + ', Total=' + $adjustedDistance" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Legacy single-factor distance penalty (for batch processor, etc.) -->
          <!-- Formula: adjustedDistance = distance * multiplier * (1 + (distance / 10)^2) -->
          <!-- This creates quadratic penalty: longer distances get exponentially more penalized -->
          <!-- Examples with multiplier=2.0:
               - Distance 1:  1 * 2 * (1 + 0.01) = 2.02   (minimal penalty)
               - Distance 5:  5 * 2 * (1 + 0.25) = 12.5   (25% extra)
               - Distance 10: 10 * 2 * (1 + 1)   = 40     (100% extra = 2x)
               - Distance 20: 20 * 2 * (1 + 4)   = 200    (400% extra = 5x)
          -->
          <set_value name="$distanceBase" exact="10.0"/>
          <set_value name="$distanceRatio" exact="$distance / $distanceBase"/>
          <set_value name="$nonLinearFactor" exact="1.0 + ($distanceRatio * $distanceRatio)"/>
          <set_value name="$adjustedDistance" exact="$distance * $distancePenaltyMultiplier * $nonLinearFactor"/>
        </do_else>
        
        <!-- Convert money to number before division to avoid "Loss of data while converting floating point" error -->
        <!-- Convert profit (money in cents) to numeric value using f suffix to force float conversion -->
        <!-- Pattern from order.trade.perform.xml:243: (money / 1Cr)f forces float conversion -->
        <!-- Apply non-linear profit scaling to reduce profit dominance in scoring -->
        <!-- Formula: profitNum_scaled = profitNum / (1.0 + profitNum / profitBase) -->
        <!-- This creates diminishing returns: higher profits get scaled down more -->
        <!-- Examples:
             - Profit 10,000 Cr   profitNum = 1,000,000   scaled = 1,000,000 / (1 + 1) = 500,000 (50% reduction)
             - Profit 20,000 Cr   profitNum = 2,000,000   scaled = 2,000,000 / (1 + 2) = 666,667 (67% reduction)
             - Profit 260,090 Cr   profitNum = 26,009,000   scaled = 26,009,000 / (1 + 26) = 962,556 (96% reduction)
        -->
        <!-- This means: 2x profit   ~1.33x score (instead of 2x), significantly reducing profit's overwhelming influence -->
        <set_value name="$efficiency" exact="0.0"/>
        <do_if value="$adjustedDistance gt 0">
          <!-- Convert profit from money (cents) to number by dividing by 1ct, then scale by 100 -->
          <!-- Use f suffix to force float conversion (pattern from order.trade.perform.xml:243) -->
          <set_value name="$profitNum" exact="(($profit / 1ct) * 100)f"/>
          
          <!-- Apply diminishing returns to reduce profit dominance -->
          <!-- profitBase controls where scaling kicks in - lower = more aggressive scaling -->
          <!-- Formula: profitNum_scaled = profitNum / (1.0 + profitNum / profitBase) -->
          <set_value name="$profitBase" exact="1000000.0"/>
          <set_value name="$profitRatio" exact="$profitNum / $profitBase"/>
          <set_value name="$profitScalingFactor" exact="1.0 + $profitRatio"/>
          <set_value name="$profitNumScaled" exact="$profitNum / $profitScalingFactor"/>
          
          <!-- Scale adjustedDistance by 10000 for precision -->
          <set_value name="$scaledDistance" exact="$adjustedDistance * 10000.0"/>
          <!-- Division: number / number = number (efficiency scaled by 10000) -->
          <!-- Note: Efficiency is now scaled by 10000, but all comparisons/scoring work correctly with scaled values -->
          <set_value name="$efficiency" exact="$profitNumScaled / $scaledDistance"/>
        </do_if>
        <do_else>
          <!-- If distance is 0, efficiency equals profit (converted to number) with same scaling -->
          <set_value name="$profitNum" exact="(($profit / 1ct) * 100)f"/>
          <set_value name="$profitBase" exact="1000000.0"/>
          <set_value name="$profitRatio" exact="$profitNum / $profitBase"/>
          <set_value name="$profitScalingFactor" exact="1.0 + $profitRatio"/>
          <set_value name="$profitNumScaled" exact="$profitNum / $profitScalingFactor"/>
          <set_value name="$efficiency" exact="$profitNumScaled"/>
        </do_else>
        
        <!-- Apply faction priority boost -->
        <do_if value="$factionPriority == 0 and ($buyStationOwner == faction.player or $sellStationOwner == faction.player)">
          <set_value name="$boost" exact="$efficiency / 5"/>
          <set_value name="$efficiency" exact="$efficiency + $boost"/>
        </do_if>
        <do_elseif value="$factionPriority == 1 and $buyStationOwner != faction.player and $sellStationOwner != faction.player">
          <set_value name="$boost" exact="$efficiency / 5"/>
          <set_value name="$efficiency" exact="$efficiency + $boost"/>
        </do_elseif>
        
        <!-- Apply "same path" bonus for efficient routing -->
        <!-- Favors trades where stations are "in order" relative to home and ship position -->
        <!-- Example: Home=E, Ship=B, Buy=C, Sell=E   Efficient (moves toward home) -->
        <!-- Example: Home=E, Ship=B, Buy=E, Sell=C   Less efficient (backtracks) -->
        <set_value name="$pathBonus" exact="1.0"/>
        <do_if value="$homeSector? and $shipSector? and $buySector? and $sellSector? and $shipToBuyDistance ge 0">
          <!-- Use passed distance parameters if available, otherwise calculate -->
          <set_value name="$homeToBuy" exact="-1"/>
          <set_value name="$homeToSell" exact="-1"/>
          <do_if value="$homeToBuyDistance ge 0 and $homeToSellDistance ge 0">
            <!-- Use passed parameters (from new multi-factor system) -->
            <set_value name="$homeToBuy" exact="$homeToBuyDistance"/>
            <set_value name="$homeToSell" exact="$homeToSellDistance"/>
          </do_if>
          <do_else>
            <!-- Fallback: Calculate distances (for backward compatibility) -->
            <set_value name="$homeToBuy" exact="$homeSector.gatedistance.{$buySector}"/>
            <set_value name="$homeToSell" exact="$homeSector.gatedistance.{$sellSector}"/>
          </do_else>
          
          <!-- Calculate ship sell distance directly (path might differ from ship buy + buy sell) -->
          <set_value name="$shipToSell" exact="$shipSector.gatedistance.{$sellSector}"/>
          
          <!-- Only apply bonus if all distances are valid (non-negative, paths exist) -->
          <do_if value="$homeToBuy ge 0 and $homeToSell ge 0 and $shipToSell ge 0">
            <!-- Case 1: Buy station is further from home than sell station -->
            <!-- Efficient route: Ship   Buy (further)   Sell (closer)   Home -->
            <!-- This is efficient if ship is closer to buy than sell (ship between buy and sell, or beyond buy) -->
            <do_if value="$homeToBuy gt $homeToSell">
              <!-- Efficient if ship is closer to buy station than sell station -->
              <!-- This means ship can move forward (toward sell/home) without backtracking -->
              <do_if value="$shipToBuyDistance le $shipToSell">
                <!-- Same path bonus: 10% efficiency boost -->
                <set_value name="$pathBonus" exact="1.1"/>
              </do_if>
            </do_if>
            <!-- Case 2: Sell station is further from home than buy station -->
            <!-- Efficient route: Ship   Sell (further)   Buy (closer)   Home -->
            <!-- This is efficient if ship is closer to sell than buy -->
            <do_elseif value="$homeToSell gt $homeToBuy">
              <!-- Efficient if ship is closer to sell station than buy station -->
              <do_if value="$shipToSell le $shipToBuyDistance">
                <!-- Same path bonus: 10% efficiency boost -->
                <set_value name="$pathBonus" exact="1.1"/>
              </do_if>
            </do_elseif>
            <!-- Case 3: Both stations same distance from home (same sector or equidistant) -->
            <!-- Already efficient - smaller bonus -->
            <do_elseif value="$homeToBuy == $homeToSell">
              <set_value name="$pathBonus" exact="1.05"/>
            </do_elseif>
          </do_if>
        </do_if>
        
        <!-- Apply path bonus to efficiency -->
        <set_value name="$efficiency" exact="$efficiency * $pathBonus"/>
        
        <return value="$efficiency"/>
      </actions>
    </library>
    
    <!-- Get Distance Penalty Multiplier -->
    <library name="GT_GetDistancePenaltyMultiplier" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to get distance penalty for"/>
        <param name="defaultMultiplier" default="1.0" comment="Default multiplier (for 50% distance penalty)"/>
      </params>
      <actions>
        <set_value name="$distancePenalty" exact="@global.$GT_AIParameters.{$ship}.$DistancePenalty"/>
        <do_if value="$distancePenalty?">
          <!-- Convert 0-100% to 0.0-2.0: 0%=0.0, 50%=1.0, 100%=2.0 -->
          <return value="$distancePenalty / 50.0"/>
        </do_if>
        <return value="$defaultMultiplier"/>
      </actions>
    </library>
    
    <!-- Get Faction Priority Text -->
    <library name="GT_GetFactionPriorityText" purpose="run_actions">
      <params>
        <param name="factionPriority" comment="Faction priority (0=equal, 1=player station boost)"/>
      </params>
      <actions>
        <return value="if $factionPriority gt 0 then 'Player Priority' else 'Equal'"/>
      </actions>
    </library>
    
    <!-- Calculate ROI from Prices -->
    <library name="GT_CalculateROIFromPrices" purpose="run_actions">
      <params>
        <param name="buyPrice" comment="Price per unit to buy"/>
        <param name="sellPrice" comment="Price per unit to sell"/>
      </params>
      <actions>
        <!-- Calculate ROI as percentage: ((sellPrice - buyPrice) / buyPrice) * 100 -->
        <do_if value="$buyPrice gt 0">
          <return value="(($sellPrice - $buyPrice) * 100) / $buyPrice"/>
        </do_if>
        <return value="0"/>
      </actions>
    </library>
    
    <!-- Request Registry: Acquire Search Lock and Parameters -->
    <!-- Centralizes lock and parameter management to prevent cleanup leaks -->
    <library name="GT_RequestRegistry_Acquire" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship requesting trade search"/>
        <param name="parameters" comment="AI parameters table (must match structure from gt_trading_ai.xml)"/>
      </params>
      <actions>
        <!-- Initialize tables if needed -->
        <do_if value="not global.$GT_SearchLocks?">
          <set_value name="global.$GT_SearchLocks" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_AIParameters?">
          <set_value name="global.$GT_AIParameters" exact="table[]"/>
        </do_if>
        
        <!-- Check if already locked -->
        <set_value name="this.$alreadyLocked" exact="false"/>
        <do_if value="global.$GT_SearchLocks.{$ship}?">
          <set_value name="this.$alreadyLocked" exact="true"/>
          <!-- Log lock already exists -->
          <debug_text text="'[GT-Lock] (' + $ship.idcode + ') LOCK ACQUIRE FAILED - lock already exists (lockTime: ' + global.$GT_SearchLocks.{$ship} + ')'" chance="100"/>
        </do_if>
        
        <!-- Acquire lock and store parameters -->
        <do_if value="not this.$alreadyLocked">
          <set_value name="global.$GT_SearchLocks.{$ship}" exact="player.age"/>
          <set_value name="global.$GT_AIParameters.{$ship}" exact="$parameters"/>
          <set_value name="this.$acquired" exact="true"/>
          <!-- Log successful lock acquisition -->
          <debug_text text="'[GT-Lock] (' + $ship.idcode + ') LOCK ACQUIRED (lockTime: ' + player.age + ')'" chance="100"/>

          <!-- Hub status (lightweight): record request lock acquisition -->
          <set_value name="$traceId" exact="if @$parameters.$TraceId != null then @$parameters.$TraceId else ''"/>
          <run_actions ref="md.GT_Libraries_General.GT_RequestStatus_Update">
            <param name="ship" value="$ship"/>
            <param name="stage" value="'lock_acquired'"/>
            <param name="state" value="'in_progress'"/>
            <param name="reason" value="'acquired'"/>
            <param name="traceId" value="$traceId"/>
          </run_actions>
        </do_if>
        <do_else>
          <set_value name="this.$acquired" exact="false"/>
        </do_else>
      </actions>
    </library>

    <!-- Hub Status: Initialize -->
    <library name="GT_RequestStatus_Init" purpose="run_actions">
      <actions>
        <do_if value="not global.$GT_RequestStatus? or global.$GT_RequestStatus == null">
          <set_value name="global.$GT_RequestStatus" exact="table[]"/>
        </do_if>
      </actions>
    </library>

    <!-- Hub Status: Update per-ship lifecycle state (debug/coordination only; does NOT signal AI) -->
    <library name="GT_RequestStatus_Update" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship object key"/>
        <param name="stage" default="'unknown'" comment="High-level pipeline stage"/>
        <param name="state" default="'unknown'" comment="State within stage"/>
        <param name="reason" default="''" comment="Optional reason code"/>
        <param name="traceId" default="''" comment="Trace ID for correlation"/>
        <param name="homeSector" default="null" comment="Home sector if known"/>
        <param name="extra" default="null" comment="Optional table[] of extra fields"/>
      </params>
      <actions>
        <do_if value="not global.$GT_RequestStatus? or global.$GT_RequestStatus == null">
          <set_value name="global.$GT_RequestStatus" exact="table[]"/>
        </do_if>

        <do_if value="$ship? and $ship.exists">
          <do_if value="not global.$GT_RequestStatus.{$ship}? or global.$GT_RequestStatus.{$ship} == null">
            <set_value name="global.$GT_RequestStatus.{$ship}" exact="table[]"/>
          </do_if>

          <set_value name="global.$GT_RequestStatus.{$ship}.$Stage" exact="$stage"/>
          <set_value name="global.$GT_RequestStatus.{$ship}.$State" exact="$state"/>
          <set_value name="global.$GT_RequestStatus.{$ship}.$Reason" exact="$reason"/>
          <set_value name="global.$GT_RequestStatus.{$ship}.$TraceId" exact="$traceId"/>
          <set_value name="global.$GT_RequestStatus.{$ship}.$UpdatedAt" exact="player.age"/>

          <do_if value="$homeSector? and $homeSector != null">
            <set_value name="global.$GT_RequestStatus.{$ship}.$HomeSector" exact="$homeSector"/>
          </do_if>

          <!-- Best-effort merge of extra fields (tables only) -->
          <do_if value="$extra? and $extra != null and $extra.keys?">
            <do_all exact="$extra.keys.count" counter="$i">
              <set_value name="$k" exact="$extra.keys.{$i}"/>
              <set_value name="global.$GT_RequestStatus.{$ship}.{$k}" exact="$extra.{$k}"/>
            </do_all>
          </do_if>
        </do_if>
      </actions>
    </library>
    
    <!-- Request Registry: Release Search Lock and Parameters -->
    <!-- Centralizes cleanup to prevent leaks and ensure consistent behavior -->
    <!-- FIX: Version-aware cleanup prevents deleting parameters from newer requests -->
    <library name="GT_RequestRegistry_Release" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to release"/>
        <param name="reason" default="'search_complete'" comment="Reason for release (for debugging)"/>
      </params>
      <actions>
        <!-- CRITICAL: Validate ship is valid before accessing any properties (ship may have been destroyed) -->
        <do_if value="not $ship? or not $ship.exists">
          <!-- Ship is invalid (destroyed) - clean up locks/params silently and exit -->
          <do_if value="global.$GT_SearchLocks? and global.$GT_SearchLocks.{$ship}?">
            <remove_value name="global.$GT_SearchLocks.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}?">
            <remove_value name="global.$GT_AIParameters.{$ship}"/>
          </do_if>
          <return value="false"/>
        </do_if>
        
        <!-- PERFORMANCE FIX: Early exit check for non-GT ships -->
        <!-- If ship is not GT-controlled, exit immediately to prevent stutter -->
        <set_value name="$isGTControlled" exact="false"/>
        
        <!-- Quick check: Does ship have direct GT order? -->
        <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
          <set_value name="$isGTControlled" exact="true"/>
        </do_if>
        
        <!-- Fallback check: Is ship subordinate to GT commander? -->
        <do_if value="not $isGTControlled and $ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- EARLY EXIT: If ship is not GT-controlled, still clean up locks/params silently but skip logging -->
        <!-- We still clean up to prevent leaks, but don't log for non-GT ships -->
        <set_value name="$shouldLog" exact="$isGTControlled"/>
        
        <!-- Hub status (lightweight): record release attempt early -->
        <run_actions ref="md.GT_Libraries_General.GT_RequestStatus_Update">
          <param name="ship" value="$ship"/>
          <param name="stage" value="'release'"/>
          <param name="state" value="'released'"/>
          <param name="reason" value="$reason"/>
          <param name="traceId" value="if global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$TraceId? then global.$GT_AIParameters.{$ship}.$TraceId else ''"/>
        </run_actions>

        <!-- Get lock time BEFORE releasing lock (needed for version check) -->
        <set_value name="$lockTime" exact="null"/>
        <do_if value="global.$GT_SearchLocks? and global.$GT_SearchLocks.{$ship}?">
          <set_value name="$lockTime" exact="global.$GT_SearchLocks.{$ship}"/>
        </do_if>
        
        <!-- Release lock -->
        <do_if value="$lockTime != null">
          <remove_value name="global.$GT_SearchLocks.{$ship}"/>
          <!-- Always log lock release with ship ID and reason -->
          <!-- CRITICAL: Validate ship is valid before accessing idcode (ship may have been destroyed or invalidated) -->
          <!-- Use safe operator @ to prevent errors when ship component handle is invalid -->
          <set_value name="$shipIdCode" exact="'INVALID_SHIP'"/>
          <do_if value="$ship? and $ship.exists">
            <set_value name="$tempShipIdCode" exact="@$ship.idcode"/>
            <do_if value="$tempShipIdCode? and $tempShipIdCode != null and $tempShipIdCode != ''">
              <set_value name="$shipIdCode" exact="$tempShipIdCode"/>
            </do_if>
          </do_if>
          <debug_text text="'[GT-Lock] (' + $shipIdCode + ') LOCK RELEASED (reason: ' + $reason + ', lockTime: ' + $lockTime + ', age: ' + (player.age - $lockTime) + ')'" chance="100"/>
        </do_if>
        
        <!-- Clean up parameters ONLY if they belong to this request -->
        <!-- Check RequestTime matches lock time (or lock was null, meaning already released) -->
        <set_value name="$shouldDeleteParams" exact="false"/>
        <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}?">
          <set_value name="$params" exact="global.$GT_AIParameters.{$ship}"/>
          <set_value name="$paramsRequestTime" exact="@$params.$RequestTime"/>
          
          <!-- Delete parameters if:
               1. Lock time matches params RequestTime (same request), OR
               2. Lock was null (already released, but params still exist - stale cleanup) -->
          <do_if value="$lockTime != null and $paramsRequestTime? and $lockTime == $paramsRequestTime">
            <set_value name="$shouldDeleteParams" exact="true"/>
          </do_if>
          <do_elseif value="$lockTime == null and $paramsRequestTime?">
            <!-- Lock already released (by newer request), but params still exist -->
            <!-- Only delete if params are old (older than 1 minute) to avoid deleting active requests -->
            <do_if value="(player.age - $paramsRequestTime) gt 60s">
              <set_value name="$shouldDeleteParams" exact="true"/>
            </do_if>
          </do_elseif>
          
          <do_if value="$shouldDeleteParams">
            <remove_value name="global.$GT_AIParameters.{$ship}"/>
            <do_if value="$shouldLog and global.$GT_Config? and global.$GT_Config.$Debug? and global.$GT_Config.$Debug.$TradeSearch? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <!-- Use safe operator to prevent errors with invalid ship objects -->
              <set_value name="$logShipIdCode" exact="@$ship.idcode"/>
              <set_value name="$safeShipIdCode" exact="if ($logShipIdCode? and $logShipIdCode != null and $logShipIdCode != '') then $logShipIdCode else 'INVALID_SHIP'"/>
              <debug_text text="'[GT-Registry] AI parameters cleaned up for ' + $safeShipIdCode + ' (' + $reason + ', RequestTime: ' + $paramsRequestTime + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Parameters belong to newer request - don't delete -->
            <do_if value="$shouldLog and global.$GT_Config? and global.$GT_Config.$Debug? and global.$GT_Config.$Debug.$TradeSearch? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <!-- Use safe operator to prevent errors with invalid ship objects -->
              <set_value name="$logShipIdCode2" exact="@$ship.idcode"/>
              <set_value name="$safeShipIdCode2" exact="if ($logShipIdCode2? and $logShipIdCode2 != null and $logShipIdCode2 != '') then $logShipIdCode2 else 'INVALID_SHIP'"/>
              <debug_text text="'[GT-Registry] Skipping parameter cleanup for ' + $safeShipIdCode2 + ' - parameters belong to newer request (lock: ' + $lockTime + ', params: ' + $paramsRequestTime + ')'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>

        <!-- IMPORTANT:
             stale_lock_cleanup and hard ship cleanup paths should reset MORE than just registry lock/params.
             Otherwise ships can remain stuck in "live search already in progress (pre-gate)" / batch-wait states
             even after the lock is released, leading to repeat AI timeouts and home-sector refresh blocking. -->
        <set_value name="$doDeepCleanup" exact="false"/>
        <do_if value="$reason == 'stale_lock_cleanup' or $reason == 'ship_destroyed'">
          <set_value name="$doDeepCleanup" exact="true"/>
        </do_if>
        <do_if value="$doDeepCleanup">
          <!-- Hub pipeline: LiveSearchQueue removed. If ship was waiting for a home-sector refresh, remove it from waiter lists. -->
          <do_if value="global.$GT_TS_LiveRefreshBySector? and global.$GT_TS_LiveRefreshBySector.keys.count gt 0">
            <do_all exact="global.$GT_TS_LiveRefreshBySector.keys.count" counter="$hsIdx">
              <set_value name="$hs" exact="global.$GT_TS_LiveRefreshBySector.keys.{$hsIdx}"/>
              <do_if value="$hs? and global.$GT_TS_LiveRefreshBySector.{$hs}?">
                <do_if value="global.$GT_TS_LiveRefreshBySector.{$hs}.$WaiterQueued? and global.$GT_TS_LiveRefreshBySector.{$hs}.$WaiterQueued.{$ship}?">
                  <remove_value name="global.$GT_TS_LiveRefreshBySector.{$hs}.$WaiterQueued.{$ship}"/>
                </do_if>
                <do_if value="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters? and global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters.count gt 0">
                  <do_all exact="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters.count" counter="$wi" reverse="true">
                    <set_value name="$w" exact="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters.{$wi}"/>
                    <do_if value="$w? and $w.$Ship? and $w.$Ship == $ship">
                      <remove_from_list name="global.$GT_TS_LiveRefreshBySector.{$hs}.$Waiters" exact="$w"/>
                    </do_if>
                  </do_all>
                </do_if>
              </do_if>
            </do_all>
          </do_if>

          <!-- 3) Legacy live-slice and batch cleanup removed in AI migration -->

          <!-- 5) If this ship was the home-sector live-refresh initiator, release the marker so other ships aren't blocked.
               IMPORTANT: Do NOT call GT_GetHomeSector here. Some stale-lock cleanup cases involve ships that no longer have
               a valid defaultorder.$home / GT_AIParameters.$HomeBase, which would spam GT_GetHomeSector "THIS SHOULD NEVER HAPPEN"
               errors and trigger ship.sector fallback drift.
               Instead, scan the refresh table for any entry whose $Initiator == this ship. -->
          <do_if value="global.$GT_TS_LiveRefreshBySector? and global.$GT_TS_LiveRefreshBySector.keys.count gt 0">
            <do_all exact="global.$GT_TS_LiveRefreshBySector.keys.count" counter="$hsIdx">
              <set_value name="$hs" exact="global.$GT_TS_LiveRefreshBySector.keys.{$hsIdx}"/>
              <do_if value="$hs? and global.$GT_TS_LiveRefreshBySector.{$hs}?">
                <set_value name="$refreshEntry" exact="global.$GT_TS_LiveRefreshBySector.{$hs}"/>
                <do_if value="$refreshEntry? and $refreshEntry.$Initiator? and $refreshEntry.$Initiator == $ship">
                  <set_value name="global.$GT_TS_LiveRefreshBySector.{$hs}.$Active" exact="false"/>
                  <set_value name="global.$GT_TS_LiveRefreshBySector.{$hs}.$LastFinished" exact="player.age"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>

          <do_if value="$shouldLog and global.$GT_Config? and global.$GT_Config.$Debug? and global.$GT_Config.$Debug.$TradeSearch? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <!-- Use safe operator to prevent errors with invalid ship objects -->
            <set_value name="$logShipIdCode3" exact="@$ship.idcode"/>
            <set_value name="$safeShipIdCode3" exact="if ($logShipIdCode3? and $logShipIdCode3 != null and $logShipIdCode3 != '') then $logShipIdCode3 else 'INVALID_SHIP'"/>
            <debug_text text="'[GT-Registry] deep cleanup (' + $reason + '): reset live/batch state for ' + $safeShipIdCode3" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- M4 FIX: Clean up RequestStatus entry for this ship to prevent unbounded growth -->
        <do_if value="global.$GT_RequestStatus? and global.$GT_RequestStatus.{$ship}?">
          <remove_value name="global.$GT_RequestStatus.{$ship}"/>
        </do_if>
        
        <set_value name="this.$released" exact="true"/>
      </actions>
    </library>
    
    <!-- Get Skill-Based Multiplier -->
    <library name="GT_GetSkillMultiplier" purpose="run_actions">
      <params>
        <param name="skillLevel" comment="Pilot skill level (1-15+)"/>
      </params>
      <actions>
        <!-- Returns multiplier: 0.5 at Lv1   2.0 at Lv15 -->
        <!-- Formula: 0.5 + ((skillLevel - 1) * (1.5 / 14)) -->
        <return value="0.5 + (($skillLevel - 1) * (1.5 / 14))"/>
      </actions>
    </library>
    
    <!-- Get Pilot Level-Based Profit Threshold -->
    <library name="GT_GetPilotLevelProfitThreshold" purpose="run_actions">
      <params>
        <param name="skillLevel" comment="Pilot skill level (1-15+)"/>
        <param name="shipCargoCapacity" comment="Ship's max cargo capacity (for scaling threshold)"/>
        <param name="configBaseProfit" default="10000" comment="Base profit at Level 15 for reference cargo (RAW centicredits). Example: 100Cr = 10000."/>
      </params>
      <actions>
        <!-- Returns profit threshold in raw format (centicredits) based on pilot level:
             Non-linear (quadratic) progression from Level 1 (0 Cr) to Level 15 (configBaseProfit).
             Formula: configBaseProfit * ((skillLevel - 1) / 14)^2
             This creates a quadratic curve that starts at 0 Cr and accelerates to 10000 Cr:
             Level 1: 0 Cr (0 raw)
             Level 15: configBaseProfit (raw)
             
             NEW: Threshold is scaled by ship cargo capacity
             - Reference cargo: 8200 (Merkur - baseline for Level 15 = configBaseProfit)
             - Small ships (2200 cargo) get proportionally lower thresholds
             - Minimum floor: 25% of base threshold (prevents thresholds from being too low)
        -->
        <!-- Level 1-15+: Non-linear (quadratic) progression from 0 Cr to configBaseProfit -->
        <!-- Avoid integer division by rearranging formula:
             Original: configBaseProfit * ((skillLevel - 1) / 14)^2
             Rearranged: ((skillLevel - 1)^2 * configBaseProfit) / 196
        -->
        <!-- This avoids floating-point division issues in MD by doing integer math -->
        <!-- This creates an accelerating curve - lower levels have lower thresholds, -->
        <!-- higher levels require much more profit (more selective traders) -->
        <set_value name="$baseMax" exact="$configBaseProfit"/>
        <do_if value="not $baseMax? or $baseMax == null or $baseMax lt 0">
          <set_value name="$baseMax" exact="10000"/>
        </do_if>
        <set_value name="$numerator" exact="($skillLevel - 1) * ($skillLevel - 1) * $baseMax"/>
        <set_value name="$baseThreshold" exact="$numerator / 196"/>
        
        <!-- Scale threshold by ship cargo capacity -->
        <!-- Reference cargo: 8200 (Merkur - baseline for Level 15 = 10,000 Cr) -->
        <!-- Small ships get proportionally lower thresholds -->
        <set_value name="$referenceCargo" exact="8200"/>
        <do_if value="$shipCargoCapacity? and $shipCargoCapacity gt 0">
          <!-- Calculate scaling factor: shipCargo / referenceCargo -->
          <!-- Use integer math to avoid floating-point issues -->
          <set_value name="$scalingFactor" exact="($shipCargoCapacity * 100) / $referenceCargo"/>
          <set_value name="$scaledThreshold" exact="($baseThreshold * $scalingFactor) / 100"/>
          
          <!-- Apply minimum floor: At least 25% of base threshold -->
          <set_value name="$minFloor" exact="($baseThreshold * 25) / 100"/>
          <set_value name="$result" exact="[$scaledThreshold, $minFloor].max"/>
        </do_if>
        <do_else>
          <!-- Fallback: Use base threshold if cargo capacity not available -->
          <set_value name="$result" exact="$baseThreshold"/>
        </do_else>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Validate Trade -->
    <library name="GT_IsTradeValid" purpose="run_actions">
      <params>
        <param name="trade" comment="Trade object to validate"/>
        <param name="minScore" default="0" comment="Minimum score required (default: 0 = any positive score)"/>
      </params>
      <actions>
        <!-- Validate trade has all required properties -->
        <set_value name="$testBuyOffer" exact="@$trade.$BuyOffer"/>
        <set_value name="$testSellOffer" exact="@$trade.$SellOffer"/>
        <set_value name="$testScore" exact="@$trade.$Score"/>
        <do_if value="$testBuyOffer? and $testSellOffer? and $testScore? and $testScore gt $minScore">
          <set_value name="$testWare" exact="@$testBuyOffer.ware"/>
          <do_if value="$testWare?">
            <return value="true"/>
          </do_if>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Calculate Max Tradeable Amount -->
    <library name="GT_CalculateMaxTradeableAmount" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship for cargo capacity calculation"/>
        <param name="ware" comment="Ware to calculate capacity for"/>
        <param name="buyOfferAmount" comment="Buy offer amount"/>
        <param name="sellOfferAmount" comment="Sell offer amount"/>
        <param name="availableMoney" default="999999Cr" comment="Available money"/>
        <param name="buyPrice" default="0" comment="Buy price per unit"/>
      </params>
      <actions>
        <!-- Calculate max cargo capacity for this ware -->
        <set_value name="$maxCargoCapacity" exact="($ship.cargo.free.all / $ware.volume)i"/>
        <!-- Calculate max affordable based on available money -->
        <set_value name="$maxAffordable" exact="99999"/>
        <do_if value="$buyPrice gt 0">
          <set_value name="$maxAffordable" exact="($availableMoney / $buyPrice)i"/>
        </do_if>
        <!-- Return minimum of offer amounts, cargo capacity, and money limit -->
        <return value="[$buyOfferAmount, $sellOfferAmount, $maxCargoCapacity, $maxAffordable].min"/>
      </actions>
    </library>
    
    <!-- Index Offers By Ware -->
    <library name="GT_IndexOffersByWare" purpose="run_actions">
      <params>
        <param name="offersList" comment="List of trade offers to index"/>
      </params>
      <actions>
        <set_value name="$offersByWare" exact="table[]"/>
        
        <!-- Defensive: list may be null/invalid -->
        <do_if value="not $offersList? or $offersList == null">
          <return value="$offersByWare"/>
        </do_if>
        
        <do_all exact="$offersList.count" counter="$i">
          <set_value name="$offer" exact="$offersList.{$i}"/>
          
          <!-- Null-safety: offer handles can be invalid; ware can be null -->
          <set_value name="$ware" exact="@$offer.ware"/>
          <do_if value="not $ware? or $ware == null">
            <continue/>
          </do_if>
          
          <do_if value="not $offersByWare.{$ware}? or $offersByWare.{$ware} == null">
            <set_value name="$offersByWare.{$ware}" exact="[]"/>
          </do_if>
          <append_to_list name="$offersByWare.{$ware}" exact="$offer"/>
        </do_all>
        <return value="$offersByWare"/>
      </actions>
    </library>
    
    <!-- Filter Offers By Distance -->
    <library name="GT_FilterOffersByDistance" purpose="run_actions">
      <params>
        <param name="offersList" comment="List of offers to filter"/>
        <param name="homeSector" comment="Home/base sector for distance calculation"/>
        <param name="maxDistance" comment="Maximum distance (jumps)"/>
      </params>
      <actions>
        <set_value name="$filteredOffers" exact="[]"/>
        <set_value name="$filteredCount" exact="0"/>
        
        <!-- Defensive: list may be null/invalid -->
        <do_if value="not $offersList? or $offersList == null">
          <set_value name="$result" exact="table[]"/>
          <set_value name="$result.$FilteredOffers" exact="$filteredOffers"/>
          <set_value name="$result.$FilteredCount" exact="$filteredCount"/>
          <return value="$result"/>
        </do_if>
        
        <do_all exact="$offersList.count" counter="$i">
          <set_value name="$offer" exact="$offersList.{$i}"/>
          
          <!-- Null-safety: offer.owner can be invalid -->
          <set_value name="$owner" exact="@$offer.owner"/>
          <set_value name="$targetSector" exact="@$owner.sector"/>
          <do_if value="not $targetSector? or $targetSector == null">
            <set_value name="$filteredCount" exact="$filteredCount + 1"/>
            <continue/>
          </do_if>
          
          <!-- Calculate range-only distance (using library function) -->
          <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculateRangeOnlyDistance" result="$distance">
            <param name="fromSector" value="$homeSector"/>
            <param name="toSector" value="$targetSector"/>
          </run_actions>
          
          <!-- Keep offer if within max distance and path exists (distance >= 0) -->
          <do_if value="$distance ge 0 and $distance le $maxDistance">
            <append_to_list name="$filteredOffers" exact="$offer"/>
          </do_if>
          <do_else>
            <set_value name="$filteredCount" exact="$filteredCount + 1"/>
          </do_else>
        </do_all>
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$FilteredOffers" exact="$filteredOffers"/>
        <set_value name="$result.$FilteredCount" exact="$filteredCount"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Sort and Limit Offers -->
    <library name="GT_SortAndLimitOffers" purpose="run_actions">
      <params>
        <param name="offersList" comment="List of offers to sort and limit"/>
        <param name="maxCount" comment="Maximum number of offers to return"/>
        <param name="sortAscending" default="true" comment="If true, sort ascending (take first N), if false sort descending (take last N)"/>
      </params>
      <actions>
        <set_value name="$offers" exact="$offersList"/>
        <!-- Sort by relativeprice -->
        <sort_trades name="$offers" tradelist="$offers" sorter="relativeprice"/>
        
        <set_value name="$limitedOffers" exact="[]"/>
        <do_if value="$sortAscending">
          <!-- Take first N offers (lowest price for buy offers) -->
          <set_value name="$limitCount" exact="[$offers.count, $maxCount].min"/>
          <do_all exact="$limitCount" counter="$idx">
            <append_to_list name="$limitedOffers" exact="$offers.{$idx}"/>
          </do_all>
        </do_if>
        <do_else>
          <!-- Take last N offers (highest price for sell offers) -->
          <do_if value="$offers.count gt $maxCount">
            <set_value name="$startIndex" exact="$offers.count - $maxCount + 1"/>
            <do_all exact="$maxCount" counter="$idx">
              <set_value name="$actualIndex" exact="$startIndex + $idx - 1"/>
              <append_to_list name="$limitedOffers" exact="$offers.{$actualIndex}"/>
            </do_all>
          </do_if>
          <do_else>
            <!-- Less than limit, take all -->
            <do_all exact="$offers.count" counter="$idx">
              <append_to_list name="$limitedOffers" exact="$offers.{$idx}"/>
            </do_all>
          </do_else>
        </do_else>
        <return value="$limitedOffers"/>
      </actions>
    </library>
    
    <!-- Sort Trades By Score (highest first) -->
    <library name="GT_SortTradesByScore" purpose="run_actions">
      <params>
        <param name="tradeList" comment="List of trades to sort"/>
      </params>
      <actions>
        <!-- Optimize sort for small lists (â‰¤10 items: O(n) vs O(nÂ²)) -->
        <do_if value="(if $tradeList != null then $tradeList.count else 0) gt 1">
          <do_if value="$tradeList.count gt 10">
            <!-- Large list: Full selection sort (necessary for proper ordering) -->
            <set_value name="$sortedTradeList" exact="[]"/>
            <set_value name="$remainingTrades" exact="$tradeList"/>
            <do_all exact="$tradeList.count" counter="$sortIdx">
              <set_value name="$maxScore" exact="-999999999"/>
              <set_value name="$maxIdx" exact="-1"/>
              <do_all exact="$remainingTrades.count" counter="$i">
                <set_value name="$trade" exact="$remainingTrades.{$i}"/>
                <set_value name="$tradeScore" exact="$trade.$Score"/>
                <do_if value="$tradeScore gt $maxScore">
                  <set_value name="$maxScore" exact="$tradeScore"/>
                  <set_value name="$maxIdx" exact="$i"/>
                </do_if>
              </do_all>
              <do_if value="$maxIdx ge 0">
                <append_to_list name="$sortedTradeList" exact="$remainingTrades.{$maxIdx}"/>
                <remove_value name="$remainingTrades.{$maxIdx}"/>
              </do_if>
            </do_all>
            <set_value name="$tradeList" exact="$sortedTradeList"/>
          </do_if>
          <do_elseif value="$tradeList.count gt 1">
            <!-- Small list (2-10): Single pass bubble-like sort (O(nÃ‚Â²) but n is small) -->
            <set_value name="$sortedTradeList" exact="$tradeList"/>
            <!-- Single pass: swap adjacent elements if wrong order (n-1 comparisons) -->
            <do_all exact="$tradeList.count - 1" counter="$pass">
              <set_value name="$swapped" exact="false"/>
              <do_all exact="$tradeList.count - 1 - $pass" counter="$i">
                <set_value name="$currentScore" exact="$sortedTradeList.{$i}.$Score"/>
                <set_value name="$nextScore" exact="$sortedTradeList.{$i + 1}.$Score"/>
                <do_if value="$currentScore lt $nextScore">
                  <!-- Swap -->
                  <set_value name="$temp" exact="$sortedTradeList.{$i}"/>
                  <set_value name="$sortedTradeList.{$i}" exact="$sortedTradeList.{$i + 1}"/>
                  <set_value name="$sortedTradeList.{$i + 1}" exact="$temp"/>
                  <set_value name="$swapped" exact="true"/>
                </do_if>
              </do_all>
              <!-- Early exit if no swaps (already sorted) -->
              <do_if value="not $swapped">
                <break/>
              </do_if>
            </do_all>
            <set_value name="$tradeList" exact="$sortedTradeList"/>
          </do_elseif>
          <!-- Single item or empty: no sort needed -->
        </do_if>
        <return value="$tradeList"/>
      </actions>
    </library>
    
    <!-- Filter Trade For Ship (ware basket, illegal, blacklist, path availability) -->
    <library name="GT_FilterTradeForShip" purpose="run_actions">
      <params>
        <param name="trade" comment="Trade to filter"/>
        <param name="ship" comment="Ship that would execute the trade"/>
        <param name="ware" comment="Ware being traded"/>
        <param name="wareBasket" comment="Allowed ware basket (empty = all wares allowed)"/>
        <param name="allowIllegal" default="false" comment="Whether to allow illegal wares"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group"/>
        <param name="currentSector" comment="Ship's current sector"/>
        <param name="buySector" comment="Buy station sector"/>
        <param name="sellSector" comment="Sell station sector"/>
        <param name="filterStats" default="null" comment="Optional filter statistics table to update"/>
        <param name="isIntraSectorTrade" default="false" comment="Whether this is an intra-sector trade"/>
        <param name="ignoreCarrierAux" default="false" comment="Ignore carrier/auxiliary stations"/>
        <param name="ignoreBuildStorage" default="false" comment="Ignore build storage ships"/>
      </params>
      <actions>
        <!-- Initialize result -->
        <set_value name="$isAllowed" exact="true"/>
        <set_value name="$filterReason" exact="''"/>
        
        <!-- Skip wares ship cannot carry -->
        <!-- Some wares (like Methane/gas, Feststoffe/solids) require special cargo bays -->
        <set_value name="$canCarryWareType" exact="false"/>
        <do_if value="$ware? and $ware != null">
          <!-- Check if ship has cargo bay capacity for this specific ware type -->
          <set_value name="$canCarryWareType" exact="$ship.cargo.{$ware}.max gt 0"/>
        </do_if>
        <do_if value="not $canCarryWareType">
          <set_value name="$isAllowed" exact="false"/>
          <set_value name="$filterReason" exact="'incompatible_cargo'"/>
          <do_if value="$filterStats?">
            <!-- Track in filter stats if provided -->
            <do_if value="not $filterStats.$filteredByIncompatibleCargo?">
              <set_value name="$filterStats.$filteredByIncompatibleCargo" exact="0"/>
            </do_if>
            <set_value name="$filterStats.$filteredByIncompatibleCargo" exact="$filterStats.$filteredByIncompatibleCargo + 1"/>
          </do_if>
          <!-- Return early - ship cannot carry this ware type -->
          <set_value name="$result" exact="table[]"/>
          <set_value name="$result.$IsAllowed" exact="$isAllowed"/>
          <set_value name="$result.$FilterReason" exact="$filterReason"/>
          <return value="$result"/>
        </do_if>
        
        <!-- Cheap checks first (ware basket, illegal) -->
        <!-- Ware basket check -->
        <set_value name="$wareAllowed" exact="true"/>
        <do_if value="$wareBasket? and $wareBasket != null and $wareBasket.count gt 0">
          <run_actions ref="md.GT_Libraries_General.GT_IsWareInBasket" result="$wareAllowed">
            <param name="ware" value="$ware"/>
            <param name="basket" value="$wareBasket"/>
          </run_actions>
          <do_if value="not $wareAllowed">
            <set_value name="$isAllowed" exact="false"/>
            <set_value name="$filterReason" exact="'ware_basket'"/>
            <do_if value="$filterStats?">
              <set_value name="$filterStats.$filteredByWareBasket" exact="$filterStats.$filteredByWareBasket + 1"/>
            </do_if>
            <!-- Early return - skip expensive checks (blacklist, pathfinding) -->
            <set_value name="$result" exact="table[]"/>
            <set_value name="$result.$IsAllowed" exact="$isAllowed"/>
            <set_value name="$result.$FilterReason" exact="$filterReason"/>
            <return value="$result"/>
          </do_if>
        </do_if>
        
        <!-- Illegal ware check -->
        <!-- FIX: Explicit gt 0 check to ensure legal wares (illegal=0) are not filtered. Ice allowed by default (common mined resource). -->
        <do_if value="$wareAllowed and not $allowIllegal and @$ware.illegal gt 0">
          <set_value name="$wareAllowed" exact="false"/>
          <set_value name="$isAllowed" exact="false"/>
          <set_value name="$filterReason" exact="'illegal'"/>
          <do_if value="$filterStats?">
            <set_value name="$filterStats.$filteredByIllegal" exact="$filterStats.$filteredByIllegal + 1"/>
          </do_if>
          <!-- PERFORMANCE OPTIMIZATION: Early return - skip expensive checks (blacklist, pathfinding) -->
          <set_value name="$result" exact="table[]"/>
          <set_value name="$result.$IsAllowed" exact="$isAllowed"/>
          <set_value name="$result.$FilterReason" exact="$filterReason"/>
          <return value="$result"/>
        </do_if>
        
        <!-- PERFORMANCE OPTIMIZATION: Expensive checks only if cheap checks pass -->
        <!-- Blacklist check -->
        <set_value name="$isBlacklisted" exact="false"/>
        <do_if value="$wareAllowed">
          <!-- FIX: Block intra-sector trades in blacklisted sectors (force escape) -->
          <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$currentSectorIsBlacklisted">
            <param name="sector" value="$currentSector"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$blacklistgroup"/>
          </run_actions>
          <do_if value="$currentSectorIsBlacklisted">
            <do_if value="$buySector == $currentSector and $sellSector == $currentSector">
              <!-- Intra-sector trade in blacklisted sector - BLOCK to force escape -->
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'blacklist_intra'"/>
              <do_if value="$filterStats?">
                <set_value name="$filterStats.$filteredByBlacklist" exact="$filterStats.$filteredByBlacklist + 1"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Check buy station blacklist -->
          <do_if value="not $isBlacklisted">
            <set_value name="$buyStation" exact="@$trade.$BuyStation"/>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$buyStationBlacklisted">
              <param name="station" value="$buyStation"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <do_if value="$buyStationBlacklisted">
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'blacklist_buy_station'"/>
              <do_if value="$filterStats?">
                <set_value name="$filterStats.$filteredByBlacklist" exact="$filterStats.$filteredByBlacklist + 1"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Check sell station blacklist -->
          <do_if value="not $isBlacklisted">
            <set_value name="$sellStation" exact="@$trade.$SellStation"/>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$sellStationBlacklisted">
              <param name="station" value="$sellStation"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <do_if value="$sellStationBlacklisted">
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'blacklist_sell_station'"/>
              <do_if value="$filterStats?">
                <set_value name="$filterStats.$filteredByBlacklist" exact="$filterStats.$filteredByBlacklist + 1"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Check carrier/aux exclusion -->
          <!-- Vanilla pattern: carriers = type==shiptype.carrier, aux = primarypurpose==purpose.auxiliary -->
          <!-- Do NOT use purpose.fight â€” that catches wharfs/shipyards (they build combat ships) -->
          <do_if value="not $isBlacklisted and $ignoreCarrierAux">
            <set_value name="$buyStation" exact="@$trade.$BuyStation"/>
            <set_value name="$sellStation" exact="@$trade.$SellStation"/>
            
            <!-- Check buy station: carrier or auxiliary ship -->
            <set_value name="$buyIsCarrierAux" exact="false"/>
            <do_if value="$buyStation?">
              <do_if value="@$buyStation.type == shiptype.carrier or @$buyStation.primarypurpose == purpose.auxiliary">
                <set_value name="$buyIsCarrierAux" exact="true"/>
              </do_if>
            </do_if>
            
            <!-- Check sell station: carrier or auxiliary ship -->
            <set_value name="$sellIsCarrierAux" exact="false"/>
            <do_if value="$sellStation?">
              <do_if value="@$sellStation.type == shiptype.carrier or @$sellStation.primarypurpose == purpose.auxiliary">
                <set_value name="$sellIsCarrierAux" exact="true"/>
              </do_if>
            </do_if>
            
            <do_if value="$buyIsCarrierAux or $sellIsCarrierAux">
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'carrier_aux_excluded'"/>
              <do_if value="$filterStats?">
                <do_if value="not $filterStats.$filteredByCarrierAux?">
                  <set_value name="$filterStats.$filteredByCarrierAux" exact="0"/>
                </do_if>
                <set_value name="$filterStats.$filteredByCarrierAux" exact="$filterStats.$filteredByCarrierAux + 1"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Check build storage exclusion -->
          <do_if value="not $isBlacklisted and $isAllowed and $ignoreBuildStorage">
            <set_value name="$buyStation" exact="@$trade.$BuyStation"/>
            <set_value name="$sellStation" exact="@$trade.$SellStation"/>
            
            <!-- Check buy station: build storage -->
            <set_value name="$buyIsBuildStorage" exact="false"/>
            <do_if value="$buyStation?">
              <set_value name="$buyIsBuildStorage" exact="$buyStation.isclass.buildstorage"/>
            </do_if>
            
            <!-- Check sell station: build storage -->
            <set_value name="$sellIsBuildStorage" exact="false"/>
            <do_if value="$sellStation?">
              <set_value name="$sellIsBuildStorage" exact="$sellStation.isclass.buildstorage"/>
            </do_if>
            
            <do_if value="$buyIsBuildStorage or $sellIsBuildStorage">
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'buildstorage_excluded'"/>
              <do_if value="$filterStats?">
                <do_if value="not $filterStats.$filteredByBuildStorage?">
                  <set_value name="$filterStats.$filteredByBuildStorage" exact="0"/>
                </do_if>
                <set_value name="$filterStats.$filteredByBuildStorage" exact="$filterStats.$filteredByBuildStorage + 1"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Check buy sector blacklist -->
          <do_if value="not $isBlacklisted">
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$buySectorBlacklisted">
              <param name="sector" value="$buySector"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <do_if value="$buySectorBlacklisted">
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'blacklist_buy_sector'"/>
              <do_if value="$filterStats?">
                <set_value name="$filterStats.$filteredByBlacklist" exact="$filterStats.$filteredByBlacklist + 1"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Check sell sector blacklist -->
          <do_if value="not $isBlacklisted">
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$sellSectorBlacklisted">
              <param name="sector" value="$sellSector"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <do_if value="$sellSectorBlacklisted">
              <do_if value="$sellSector != $currentSector">
                <!-- Ship needs to travel TO a blacklisted sector - BLOCK -->
                <set_value name="$isBlacklisted" exact="true"/>
                <set_value name="$isAllowed" exact="false"/>
                <set_value name="$filterReason" exact="'blacklist_sell_sector'"/>
                <do_if value="$filterStats?">
                  <set_value name="$filterStats.$filteredByBlacklist" exact="$filterStats.$filteredByBlacklist + 1"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Path availability check -->
          <do_if value="not $isBlacklisted">
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculateTradePathDistances" result="$pathResult">
              <param name="ship" value="$ship"/>
              <param name="currentSector" value="$currentSector"/>
              <param name="buySector" value="$buySector"/>
              <param name="sellSector" value="$sellSector"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            
            <!-- Debug logging (if enabled) -->
            <!-- FIX: Only log intra-sector trades for isolated ships (they're common for non-isolated ships) -->
            <!-- Always log unreachable paths as they indicate problems -->
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch">
              <set_value name="$shouldLogIntraSector" exact="false"/>
              <do_if value="$pathResult.$IsIntraSectorTrade">
                <!-- Check if ship is isolated - only log intra-sector trades for isolated ships -->
                <do_if value="$currentSector?">
                  <run_actions ref="md.GT_Libraries_Blacklist.GT_CheckConnectedSectorsBlacklisted" result="$isolationCheck">
                    <param name="sector" value="$currentSector"/>
                    <param name="ship" value="$ship"/>
                    <param name="returnDetails" value="false"/>
                  </run_actions>
                  <set_value name="$isolatedValue" exact="@$isolationCheck.$IsIsolated"/>
                  <set_value name="$shouldLogIntraSector" exact="if $isolatedValue? and ($isolatedValue == true or $isolatedValue == 1) then true else false"/>
                </do_if>
              </do_if>
              <do_if value="$shouldLogIntraSector or not $pathResult.$IsReachable">
                <set_value name="$buySectorName" exact="@$buySector.knownname"/>
                <set_value name="$sellSectorName" exact="@$sellSector.knownname"/>
                <set_value name="$currentSectorName" exact="@$currentSector.knownname"/>
                <set_value name="$wareName" exact="@$ware.name"/>
                <set_value name="$tradeType" exact="if $pathResult.$IsIntraSectorTrade then 'INTRA-SECTOR' else 'CROSS-SECTOR'"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Resume] ' + $ship.idcode + ': ' + $tradeType + ' trade (' + $wareName + '):' +
                    '\n  Current sector: ' + $currentSectorName + ' (blacklisted: ' + $pathResult.$CurrentSectorIsBlacklisted + ')' +
                    '\n  Buy sector: ' + $buySectorName + ' (distance: ' + $pathResult.$BuyPathDistance + ', same as current: ' + ($buySector == $currentSector) + ')' +
                    '\n  Sell sector: ' + $sellSectorName + ' (distance: ' + $pathResult.$SellPathDistance + ', same as buy: ' + ($sellSector == $buySector) + ', same as current: ' + ($sellSector == $currentSector) + ')' +
                    (if not $pathResult.$IsReachable then ' [PATH BLOCKED]' else '')"
                    chance="100"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- Block if paths are unreachable -->
            <do_if value="not $pathResult.$IsReachable">
              <set_value name="$isBlacklisted" exact="true"/>
              <set_value name="$isAllowed" exact="false"/>
              <set_value name="$filterReason" exact="'path_blocked'"/>
              <do_if value="$filterStats?">
                <set_value name="$filterStats.$filteredByPathBlocked" exact="$filterStats.$filteredByPathBlocked + 1"/>
              </do_if>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Return result -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$IsAllowed" exact="$isAllowed"/>
        <set_value name="$result.$FilterReason" exact="$filterReason"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Unified dock preflight â€” paired with lib.gt.dockcheck (AI). -->
    <library name="GT_CanDock" purpose="run_actions">
      <params>
        <param name="station" comment="Station, buildstorage, carrier, etc."/>
        <param name="ship" comment="Ship that needs to dock"/>
        <param name="purpose" default="'trade'" comment="trade | service | service_ai | permission_only | dual"/>
        <param name="allowStorageDock" default="false" comment="Player-owned non-BS: try storage bay after trading bay (MK2 ware-exchange)"/>
        <param name="allowPlayerOnly" default="false" comment="Mirror DockAndWait allowplayeronly for trade probe"/>
        <param name="checkOperational" default="true"/>
      </params>
      <actions>
        <set_value name="$canDock" exact="false"/>
        <set_value name="$reason" exact="'invalid_station'"/>
        <set_value name="$usedStorageFallback" exact="false"/>
        <set_value name="$bay" exact="null"/>

        <do_if value="$station? and $station.exists">
          <set_value name="$reason" exact="'no_bay'"/>

          <do_if value="$purpose == 'trade'">
            <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
              <match_dock size="$ship.docksize" trading="true" storage="false" allowplayeronly="$allowPlayerOnly"/>
              <match_relation_to object="$ship" comparison="not" relation="enemy"/>
            </find_dockingbay>
            <do_if value="$bay">
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'ok'"/>
            </do_if>
            <do_elseif value="$allowStorageDock and $station.isplayerowned and not $station.isclass.buildstorage">
              <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
                <match_dock size="$ship.docksize" storage="true"/>
                <match_relation_to object="$ship" comparison="not" relation="enemy"/>
              </find_dockingbay>
              <do_if value="$bay">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
                <set_value name="$usedStorageFallback" exact="true"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'no_trading_bay'"/>
              </do_else>
            </do_elseif>
            <do_else>
              <do_if value="((@$station.type == shiptype.resupplier) or (@$station.type == shiptype.carrier)) and not $ship.hasrelation.enemy.{$station} and $ship.iscapitalship and not $station.zone.isclass.highway">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'capital_park'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'no_trading_bay'"/>
              </do_else>
            </do_else>
          </do_if>

          <do_elseif value="$purpose == 'service' or $purpose == 'service_ai'">
            <do_if value="not $ship.iscapitalship or $station.isclass.station">
              <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
                <match_dock size="$ship.docksize" storage="false"/>
              </find_dockingbay>
              <do_if value="$bay">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'no_service_bay'"/>
              </do_else>
            </do_if>
            <do_else>
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'capital_skip'"/>
            </do_else>
          </do_elseif>

          <do_elseif value="$purpose == 'permission_only'">
            <do_if value="@$station.type == shiptype.resupplier">
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'ok'"/>
            </do_if>
            <do_else>
              <set_value name="$checkPolicy" exact="not $ship.iscapitalship or $station.isclass.station"/>
              <do_if value="not $checkPolicy or $station.dockingallowed.{$ship}">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'docking_denied'"/>
              </do_else>
            </do_else>
          </do_elseif>

          <do_elseif value="$purpose == 'dual'">
            <find_dockingbay name="$bay" object="$station" checkoperational="$checkOperational" multiple="false">
              <match_dock size="$ship.docksize" storage="false"/>
            </find_dockingbay>
            <do_if value="not $bay">
              <set_value name="$reason" exact="'no_service_bay'"/>
            </do_if>
            <do_elseif value="@$station.type == shiptype.resupplier">
              <set_value name="$canDock" exact="true"/>
              <set_value name="$reason" exact="'ok'"/>
            </do_elseif>
            <do_else>
              <set_value name="$checkPolicy" exact="not $ship.iscapitalship or $station.isclass.station"/>
              <do_if value="not $checkPolicy or $station.dockingallowed.{$ship}">
                <set_value name="$canDock" exact="true"/>
                <set_value name="$reason" exact="'ok'"/>
              </do_if>
              <do_else>
                <set_value name="$reason" exact="'docking_denied'"/>
              </do_else>
            </do_else>
          </do_elseif>

          <do_else>
            <set_value name="$reason" exact="'unknown_purpose'"/>
          </do_else>
        </do_if>

        <return value="table[
          $CanDock = $canDock,
          $Reason = $reason,
          $UsedStorageFallback = $usedStorageFallback,
          $Bay = $bay
        ]"/>
      </actions>
    </library>

    <!-- Deprecated wrapper â€” use GT_CanDock with purpose='trade'. -->
    <library name="GT_CanDockForTrade" purpose="run_actions">
      <params>
        <param name="station" comment="Station or buildstorage object to dock at"/>
        <param name="ship" comment="Ship that needs to dock"/>
        <param name="allowStorageDock" default="false" comment="Player-owned non-BS: try storage bay after trading bay (MK2 ware-exchange parity)"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$dockResult">
          <param name="station" value="$station"/>
          <param name="ship" value="$ship"/>
          <param name="purpose" value="'trade'"/>
          <param name="allowStorageDock" value="$allowStorageDock"/>
        </run_actions>
        <return value="$dockResult"/>
      </actions>
    </library>

    <!-- Separate Offers By Sector -->
    <library name="GT_SeparateOffersBySector" purpose="run_actions">
      <params>
        <param name="sellOffers" comment="List of sell offers"/>
        <param name="buyOffers" comment="List of buy offers"/>
        <param name="currentSector" comment="Current sector to compare against"/>
      </params>
      <actions>
        <set_value name="$intraSectorSellOffers" exact="[]"/>
        <set_value name="$intraSectorBuyOffers" exact="[]"/>
        <set_value name="$crossSectorSellOffers" exact="[]"/>
        <set_value name="$crossSectorBuyOffers" exact="[]"/>
        
        <!-- FIX: Validate currentSector is set and not null -->
        <do_if value="not $currentSector?">
          <!-- If currentSector is null, all offers are cross-sector -->
          <set_value name="$crossSectorSellOffers" exact="$sellOffers"/>
          <set_value name="$crossSectorBuyOffers" exact="$buyOffers"/>
        </do_if>
        <do_else>
          <!-- Separate sell offers -->
          <do_all exact="$sellOffers.count" counter="$idx">
            <set_value name="$offer" exact="$sellOffers.{$idx}"/>
            <set_value name="$offerSector" exact="@$offer.owner.sector"/>
            <!-- FIX: Compare sectors directly - == should work for same component reference -->
            <do_if value="$offerSector? and $offerSector == $currentSector">
              <append_to_list name="$intraSectorSellOffers" exact="$offer"/>
            </do_if>
            <do_else>
              <append_to_list name="$crossSectorSellOffers" exact="$offer"/>
            </do_else>
          </do_all>
          
          <!-- Separate buy offers -->
          <do_all exact="$buyOffers.count" counter="$idx">
            <set_value name="$offer" exact="$buyOffers.{$idx}"/>
            <set_value name="$offerSector" exact="@$offer.owner.sector"/>
            <!-- FIX: Compare sectors directly - == should work for same component reference -->
            <do_if value="$offerSector? and $offerSector == $currentSector">
              <append_to_list name="$intraSectorBuyOffers" exact="$offer"/>
            </do_if>
            <do_else>
              <append_to_list name="$crossSectorBuyOffers" exact="$offer"/>
            </do_else>
          </do_all>
        </do_else>
        
        <!-- Return result table -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$IntraSectorSell" exact="$intraSectorSellOffers"/>
        <set_value name="$result.$IntraSectorBuy" exact="$intraSectorBuyOffers"/>
        <set_value name="$result.$CrossSectorSell" exact="$crossSectorSellOffers"/>
        <set_value name="$result.$CrossSectorBuy" exact="$crossSectorBuyOffers"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Calculate Trade Thresholds -->
    <library name="GT_CalculateTradeThresholds" purpose="run_actions">
      <params>
        <param name="minROI" comment="Base minimum ROI"/>
        <param name="minAbsoluteProfit" comment="Base minimum profit"/>
        <param name="useAdvancedAnalytics" default="false" comment="Apply 95% multiplier"/>
        <param name="isIntraSector" default="false" comment="Is intra-sector trade"/>
        <param name="isIsolated" default="false" comment="Is ship isolated"/>
      </params>
      <actions>
        <set_value name="$roiThreshold" exact="$minROI"/>
        <set_value name="$profitThreshold" exact="$minAbsoluteProfit"/>
        
        <!-- Apply advanced analytics adjustment -->
        <!-- FIX: Use integer math to avoid floating-point to money conversion warnings -->
        <!-- CRITICAL: $profitThreshold is already in raw format (centicredits), so don't use Cr suffix -->
        <do_if value="$useAdvancedAnalytics">
          <set_value name="$roiThreshold" exact="$roiThreshold * 0.95"/>
          <set_value name="$profitThreshold" exact="$profitThreshold * 95 / 100"/>
        </do_if>
        
        <!-- Apply intra-sector/isolation adjustments -->
        <!-- FIX: Use integer math to avoid floating-point to money conversion warnings -->
        <!-- CRITICAL: $profitThreshold is already in raw format (centicredits), so divide by 2 (or multiply by 50/100) without Cr suffix -->
        <do_if value="$isIntraSector">
          <do_if value="$isIsolated">
            <!-- Isolated intra-sector: 25% of threshold -->
            <set_value name="$roiThreshold" exact="$roiThreshold * 0.25"/>
            <set_value name="$profitThreshold" exact="$profitThreshold * 25 / 100"/>
          </do_if>
          <do_else>
            <!-- Normal intra-sector: 50% of threshold -->
            <set_value name="$roiThreshold" exact="$roiThreshold * 0.5"/>
            <set_value name="$profitThreshold" exact="$profitThreshold / 2"/>
          </do_else>
        </do_if>
        
        <!-- Return result table -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$ROIThreshold" exact="$roiThreshold"/>
        <set_value name="$result.$ProfitThreshold" exact="$profitThreshold"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Create Trade Object -->
    <library name="GT_CreateTradeObject" purpose="run_actions">
      <params>
        <param name="sellOffer" comment="Sell offer"/>
        <param name="buyOffer" comment="Buy offer"/>
        <param name="sellStation" comment="Sell station"/>
        <param name="buyStation" comment="Buy station"/>
        <param name="amount" comment="Trade amount"/>
        <param name="profit" comment="Trade profit"/>
        <param name="roi" comment="Trade ROI"/>
        <param name="efficiency" comment="Trade efficiency score"/>
        <param name="buyPrice" comment="Buy price"/>
        <param name="sellPrice" comment="Sell price"/>
        <param name="distance" default="0" comment="Route distance"/>
        <param name="risk" default="0" comment="Trade risk"/>
      </params>
      <actions>
        <set_value name="$trade" exact="table[
          $BuyOffer = $sellOffer,
          $SellOffer = $buyOffer,
          $BuyStation = $sellStation,
          $SellStation = $buyStation,
          $Amount = $amount,
          $Profit = $profit,
          $ROI = $roi,
          $Score = $efficiency,
          $BuyPrice = $buyPrice,
          $SellPrice = $sellPrice,
          $Distance = $distance,
          $Risk = $risk
        ]"/>
        
        <!-- PROFIT DEBUG: Log trade object creation details for investigation -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$wareName" exact="if $buyOffer? and $buyOffer.ware? then @$buyOffer.ware.name else (if $sellOffer? and $sellOffer.ware? then @$sellOffer.ware.name else 'NULL')"/>
          <set_value name="$buyStationName" exact="if $sellStation? then @$sellStation.knownname else 'NULL'"/>
          <set_value name="$sellStationName" exact="if $buyStation? then @$buyStation.knownname else 'NULL'"/>
          <debug_text text="'[GT-CreateTrade] TRADE OBJECT CREATED:' + 
            '\n  Ware: ' + $wareName +
            '\n  Buy Station: ' + $buyStationName + ' @ ' + ($buyPrice/100) + ' Cr (RAW: ' + $buyPrice + ')' +
            '\n  Sell Station: ' + $sellStationName + ' @ ' + ($sellPrice/100) + ' Cr (RAW: ' + $sellPrice + ')' +
            '\n  Amount: ' + $amount + ' units' +
            '\n  Profit: ' + $profit + ' RAW (' + ($profit/100) + ' Cr)' +
            '\n  Verification: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $amount + ' = ' + (($sellPrice - $buyPrice) * $amount / 100) + ' Cr'" chance="100"/>
        </do_if>
        
        <return value="$trade"/>
      </actions>
    </library>
    
    <!-- Add Intra-Sector Offers -->
    <library name="GT_AddIntraSectorOffers" purpose="run_actions">
      <params>
        <param name="originalSellOffers" comment="Original sell offers before limiting"/>
        <param name="originalBuyOffers" comment="Original buy offers before limiting"/>
        <param name="limitedSellOffers" comment="Limited sell offers (will be modified)"/>
        <param name="limitedBuyOffers" comment="Limited buy offers (will be modified)"/>
        <param name="currentSector" comment="Current sector"/>
        <param name="currentSectorIsBlacklisted" default="false" comment="Is current sector blacklisted"/>
      </params>
      <actions>
        <set_value name="$addedSellCount" exact="0"/>
        <set_value name="$addedBuyCount" exact="0"/>
        
        <!-- Only add intra-sector offers if current sector is not blacklisted -->
        <do_if value="$currentSector? and not $currentSectorIsBlacklisted">
          <!-- Scan original sell offers for intra-sector ones not in limited list -->
          <do_all exact="$originalSellOffers.count" counter="$idx">
            <set_value name="$offer" exact="$originalSellOffers.{$idx}"/>
            <set_value name="$offerSector" exact="@$offer.owner.sector"/>
            <do_if value="$offerSector? and $offerSector == $currentSector">
              <!-- Check if already in limited list -->
              <set_value name="$alreadyIncluded" exact="false"/>
              <do_all exact="$limitedSellOffers.count" counter="$checkIdx">
                <do_if value="$limitedSellOffers.{$checkIdx} == $offer">
                  <set_value name="$alreadyIncluded" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <!-- Add if not already included -->
              <do_if value="not $alreadyIncluded">
                <append_to_list name="$limitedSellOffers" exact="$offer"/>
                <set_value name="$addedSellCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
          
          <!-- Scan original buy offers for intra-sector ones not in limited list -->
          <do_all exact="$originalBuyOffers.count" counter="$idx">
            <set_value name="$offer" exact="$originalBuyOffers.{$idx}"/>
            <set_value name="$offerSector" exact="@$offer.owner.sector"/>
            <do_if value="$offerSector? and $offerSector == $currentSector">
              <!-- Check if already in limited list -->
              <set_value name="$alreadyIncluded" exact="false"/>
              <do_all exact="$limitedBuyOffers.count" counter="$checkIdx">
                <do_if value="$limitedBuyOffers.{$checkIdx} == $offer">
                  <set_value name="$alreadyIncluded" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <!-- Add if not already included -->
              <do_if value="not $alreadyIncluded">
                <append_to_list name="$limitedBuyOffers" exact="$offer"/>
                <set_value name="$addedBuyCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Return result table -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$UpdatedSellOffers" exact="$limitedSellOffers"/>
        <set_value name="$result.$UpdatedBuyOffers" exact="$limitedBuyOffers"/>
        <set_value name="$result.$AddedSellCount" exact="$addedSellCount"/>
        <set_value name="$result.$AddedBuyCount" exact="$addedBuyCount"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Validate Trade Offer Pair -->
    <library name="GT_ValidateTradeOfferPair" purpose="run_actions">
      <params>
        <param name="sellOffer" comment="Sell offer to validate"/>
        <param name="buyOffer" comment="Buy offer to validate"/>
      </params>
      <actions>
        <!-- Validate sell offer -->
        <set_value name="$sellOfferOwner" exact="@$sellOffer.owner"/>
        <set_value name="$sellOfferPrice" exact="@$sellOffer.unitprice"/>
        <do_if value="not $sellOffer? or not $sellOfferOwner? or not $sellOfferPrice?">
          <return value="false"/>
        </do_if>
        
        <!-- Validate buy offer -->
        <set_value name="$buyOfferOwner" exact="@$buyOffer.owner"/>
        <set_value name="$buyOfferPrice" exact="@$buyOffer.unitprice"/>
        <do_if value="not $buyOffer? or not $buyOfferOwner? or not $buyOfferPrice?">
          <return value="false"/>
        </do_if>
        
        <!-- Different stations only -->
        <do_if value="$sellOfferOwner == $buyOfferOwner">
          <return value="false"/>
        </do_if>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Check Failed Sector Pair -->
    <!-- OPTIMIZATION: O(1) hash-based lookup using nested table (was O(N) linear scan) -->
    <!-- failedTrades format: table[ {buySector} = table[ {sellSector} = table[$Reason, $Timestamp] ] ] -->
    <library name="GT_CheckFailedSectorPair" purpose="run_actions">
      <params>
        <param name="buySector" comment="Buy station sector"/>
        <param name="sellSector" comment="Sell station sector"/>
        <param name="failedTrades" comment="Nested table of failed trades: failedTrades.{buySector}.{sellSector}"/>
      </params>
      <actions>
        <!-- O(1) hash-based lookup: check if buySector key exists, then sellSector sub-key -->
        <do_if value="$failedTrades? and $failedTrades.{$buySector}? and $failedTrades.{$buySector}.{$sellSector}?">
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Check Route Conflict -->
    <library name="GT_CheckRouteConflict" purpose="run_actions">
      <params>
        <param name="sellStation" comment="Sell station"/>
        <param name="buyStation" comment="Buy station"/>
        <param name="ware" comment="Ware being traded"/>
        <param name="reservedRoutes" comment="List of reserved route keys"/>
      </params>
      <actions>
        <set_value name="$isConflicted" exact="false"/>
        <do_if value="$reservedRoutes.count gt 0">
          <set_value name="$tradeCacheKey" exact="$sellStation.idcode + '_' + $buyStation.idcode + '_' + $ware"/>
          <!-- FIX: Use explicit loop instead of unreliable indexof check -->
          <do_all exact="$reservedRoutes.count" counter="$i">
            <do_if value="$reservedRoutes.{$i} == $tradeCacheKey">
              <set_value name="$isConflicted" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <return value="$isConflicted"/>
      </actions>
    </library>
    
    <!-- Update Trade Quota -->
    <library name="GT_UpdateTradeQuota" purpose="run_actions">
      <params>
        <param name="tradesPerWare" comment="Table of trades per ware (may be null or invalid)"/>
        <param name="ware" comment="Ware to update quota for"/>
        <param name="increment" default="1" comment="Amount to increment"/>
      </params>
      <actions>
        <!-- Ensure tradesPerWare is a valid table -->
        <set_value name="$validTable" exact="$tradesPerWare"/>
        <set_value name="$keysCheck" exact="@$validTable.keys"/>
        <set_value name="$countCheck" exact="@$keysCheck.count"/>
        <do_if value="not $countCheck? or $countCheck lt 0">
          <set_value name="$validTable" exact="table[]"/>
        </do_if>
        
        <!-- Get current count for this ware -->
        <set_value name="$currentCount" exact="0"/>
        <do_if value="$validTable.{$ware}?">
          <set_value name="$currentCount" exact="$validTable.{$ware}"/>
        </do_if>
        
        <!-- Update count -->
        <set_value name="$newCount" exact="$currentCount + $increment"/>
        <set_value name="$validTable.{$ware}" exact="$newCount"/>
        
        <!-- Return updated table and new count -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$UpdatedTable" exact="$validTable"/>
        <set_value name="$result.$NewCount" exact="$newCount"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- UI Credits Due Projected Helpers -->
    <!-- Maintains a per-ship projected due table and publishes aggregate to player.entity for Lua UI hook. -->
    <library name="GT_RecalculateUICreditsDueProjected" purpose="run_actions">
      <params>
      </params>
      <actions>
        <do_if value="not global.$GT_UICreditsDueByShip?">
          <set_value name="global.$GT_UICreditsDueByShip" exact="table[]"/>
        </do_if>

        <set_value name="$totalProjected" exact="0"/>
        <set_value name="$shipKeys" exact="@global.$GT_UICreditsDueByShip.keys.list"/>
        <do_if value="$shipKeys? and $shipKeys.count gt 0">
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$shipKey" exact="$shipKeys.{$i}"/>
            <set_value name="$shipProjected" exact="@global.$GT_UICreditsDueByShip.{$shipKey}"/>
            <do_if value="$shipProjected? and $shipProjected != null">
              <set_value name="$totalProjected" exact="$totalProjected + $shipProjected"/>
            </do_if>
          </do_all>
        </do_if>

        <set_value name="global.$GT_UICreditsDueProjectedRaw" exact="$totalProjected"/>
        <set_value name="player.entity.$GT_UI_CreditsDueProjectedRaw" exact="$totalProjected"/>
        <set_value name="player.entity.$GT_UI_CreditsDueProjectedCr" exact="$totalProjected / 100"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-UI-DUE-TOTAL] Recalculated total RAW=' + $totalProjected + ' (' + ($totalProjected / 100) + ' Cr), entries=' + (if $shipKeys? then $shipKeys.count else 0)" chance="100"/>
        </do_if>
      </actions>
    </library>

    <library name="GT_SetUICreditsDueForShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship key/component"/>
        <param name="projectedRaw" comment="Projected amount in RAW centicredits"/>
      </params>
      <actions>
        <do_if value="not global.$GT_UICreditsDueByShip?">
          <set_value name="global.$GT_UICreditsDueByShip" exact="table[]"/>
        </do_if>
        <set_value name="global.$GT_UICreditsDueByShip.{$ship}" exact="$projectedRaw"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-UI-DUE-SET] ' + $ship.idcode + ': projectedRaw=' + $projectedRaw + ' (' + ($projectedRaw / 100) + ' Cr)'" chance="100"/>
        </do_if>
        <run_actions ref="md.GT_Libraries_General.GT_RecalculateUICreditsDueProjected"/>
      </actions>
    </library>

    <library name="GT_AddUICreditsDueForShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship key/component"/>
        <param name="deltaRaw" comment="Amount to add in RAW centicredits"/>
      </params>
      <actions>
        <do_if value="not global.$GT_UICreditsDueByShip?">
          <set_value name="global.$GT_UICreditsDueByShip" exact="table[]"/>
        </do_if>
        <set_value name="$currentRaw" exact="0"/>
        <do_if value="global.$GT_UICreditsDueByShip.{$ship}?">
          <set_value name="$currentRaw" exact="@global.$GT_UICreditsDueByShip.{$ship}"/>
        </do_if>
        <set_value name="global.$GT_UICreditsDueByShip.{$ship}" exact="$currentRaw + $deltaRaw"/>
        <run_actions ref="md.GT_Libraries_General.GT_RecalculateUICreditsDueProjected"/>
      </actions>
    </library>

    <library name="GT_ClearUICreditsDueForShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship key/component"/>
      </params>
      <actions>
        <do_if value="global.$GT_UICreditsDueByShip? and global.$GT_UICreditsDueByShip.{$ship}?">
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$oldProjectedRaw" exact="@global.$GT_UICreditsDueByShip.{$ship}"/>
            <set_value name="$shipId" exact="if $ship? and $ship.exists then $ship.idcode else 'invalid'"/>
            <debug_text text="'[GT-UI-DUE-CLEAR] ' + $shipId + ': removing projectedRaw=' + $oldProjectedRaw + ' (' + ($oldProjectedRaw / 100) + ' Cr)'" chance="100"/>
          </do_if>
          <remove_value name="global.$GT_UICreditsDueByShip.{$ship}"/>
          <run_actions ref="md.GT_Libraries_General.GT_RecalculateUICreditsDueProjected"/>
        </do_if>
      </actions>
    </library>

    <!-- Clear Pending Trade Data -->
    <!-- EXTRACTED: Cleanup function for pending trade data to avoid code duplication -->
    <!-- Phase 3: Enhanced to clean up reservations, work items, and scheduler state -->
    <library name="GT_ClearPendingTradeData" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to clear pending trade data for"/>
      </params>
      <actions>
        <!-- Clear trades awaiting validation -->
        <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{$ship}?">
          <remove_value name="global.$GT_TradesAwaitingValidation.{$ship}"/>
        </do_if>

        <!-- Clear search method tracking -->
        <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{$ship}?">
          <remove_value name="global.$GT_TradesAwaitingValidationSearchMethod.{$ship}"/>
        </do_if>

        <!-- Clear active trade tracking (used for failure route bookkeeping) -->
        <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{$ship}?">
          <remove_value name="global.$GT_ActiveTrade.{$ship}"/>
        </do_if>
        
        <!-- Clear fallback flags (trade completed successfully, reset fallback state) -->
        <do_if value="global.$GT_FallbackAttempted? and global.$GT_FallbackAttempted.{$ship}?">
          <remove_value name="global.$GT_FallbackAttempted.{$ship}"/>
        </do_if>
        <do_if value="global.$GT_FallbackLogbookWritten? and global.$GT_FallbackLogbookWritten.{$ship}?">
          <remove_value name="global.$GT_FallbackLogbookWritten.{$ship}"/>
        </do_if>
        
        <!-- Phase 3: Release all reservations for this ship -->
        <!-- CRITICAL: global.$GT_Reservations can exist but be null or a non-table (savegame compatibility / corruption).
             Never access .keys unless it is a real table. -->
        <do_if value="not global.$GT_Reservations? or typeof global.$GT_Reservations != datatype.table">
          <set_value name="global.$GT_Reservations" exact="table[]"/>
        </do_if>
        <set_value name="$reservationKeysCount" exact="@global.$GT_Reservations.keys.count"/>
        <do_if value="$reservationKeysCount != null and $reservationKeysCount gt 0">
          <set_value name="$reservationsToRemove" exact="[]"/>
          <do_all exact="$reservationKeysCount" counter="$i">
            <set_value name="$tradeKey" exact="global.$GT_Reservations.keys.{$i}"/>
            <set_value name="$reservation" exact="global.$GT_Reservations.{$tradeKey}"/>
            <set_value name="$reservedByShip" exact="@$reservation.$Ship"/>
            <do_if value="$reservedByShip == $ship">
              <append_to_list name="$reservationsToRemove" exact="$tradeKey"/>
            </do_if>
          </do_all>
          <do_for_each name="$tradeKeyToRemove" in="$reservationsToRemove">
            <run_actions ref="md.GLX_Lib_Reservations.GLX_ReleaseTrade">
              <param name="tradeKey" value="$tradeKeyToRemove"/>
              <param name="reason" value="'ship_destroyed'"/>
              <param name="traceId" value="'0'"/>
            </run_actions>
          </do_for_each>
        </do_if>
        
        <!-- Phase 3: Clean up scheduler work items for this ship -->
        <do_if value="global.$GT_Scheduler?">
          <!-- Remove from work queue -->
          <do_if value="global.$GT_Scheduler.$WorkQueue?">
            <set_value name="$workQueue" exact="global.$GT_Scheduler.$WorkQueue"/>
            <set_value name="$filteredQueue" exact="[]"/>
            <do_all exact="$workQueue.count" counter="$i">
              <set_value name="$workItem" exact="$workQueue.{$i}"/>
              <do_if value="$workItem.$Payload?">
                <set_value name="$workShip" exact="@$workItem.$Payload.$Ship"/>
                <do_if value="$workShip != $ship">
                  <append_to_list name="$filteredQueue" exact="$workItem"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- Keep work items without ship payload (shouldn't happen, but be safe) -->
                <append_to_list name="$filteredQueue" exact="$workItem"/>
              </do_else>
            </do_all>
            <set_value name="global.$GT_Scheduler.$WorkQueue" exact="$filteredQueue"/>
          </do_if>
          
          <!-- Remove from active work (keyed by ship, so direct lookup) -->
          <do_if value="global.$GT_Scheduler.$ActiveWork? and global.$GT_Scheduler.$ActiveWork.{$ship}?">
            <set_value name="$workItem" exact="global.$GT_Scheduler.$ActiveWork.{$ship}"/>
            <!-- Mark work item as failed -->
            <run_actions ref="md.GT_Libraries_General.GT_UpdateWorkItemState">
              <param name="key" value="if $workItem.$Key? then $workItem.$Key else 'unknown'"/>
              <param name="newState" value="'failed'"/>
              <param name="traceId" value="if $workItem.$TraceId? then $workItem.$TraceId else '0'"/>
              <param name="reason" value="'ship_destroyed'"/>
              <param name="workItem" value="$workItem"/>
            </run_actions>
            <remove_value name="global.$GT_Scheduler.$ActiveWork.{$ship}"/>
          </do_if>
        </do_if>
        
        <!-- Phase 3: Abort scheduler state first (covers active/queued phase tables), then release request registry lock -->
        <do_if value="$ship? and $ship.exists">
          <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = $ship]"/>
        </do_if>
        <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
          <param name="ship" value="$ship"/>
          <param name="reason" value="'ship_destroyed'"/>
        </run_actions>
        
        <!-- Phase 3: Legacy search/batch state cleanup removed in AI migration -->
        
        <!-- Phase 3: Clear AI parameters -->
        <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}?">
          <remove_value name="global.$GT_AIParameters.{$ship}"/>
        </do_if>
        
        <!-- Phase 4: Clear scheduler entry queue (GT_TS) -->
        <do_if value="global.$GT_TS?">
          <!-- Remove from queue list -->
          <do_if value="global.$GT_TS.$Queue? and global.$GT_TS.$Queue.count gt 0">
            <remove_from_list name="global.$GT_TS.$Queue" exact="$ship"/>
          </do_if>
          <!-- Remove queue markers -->
          <do_if value="global.$GT_TS.$Queued? and global.$GT_TS.$Queued.{$ship}?">
            <remove_value name="global.$GT_TS.$Queued.{$ship}"/>
          </do_if>
          <!-- Remove enqueue timestamp -->
          <do_if value="global.$GT_TS.$EnqueuedAt? and global.$GT_TS.$EnqueuedAt.{$ship}?">
            <remove_value name="global.$GT_TS.$EnqueuedAt.{$ship}"/>
          </do_if>
          <!-- Remove request params -->
          <do_if value="global.$GT_TS.$Requests? and global.$GT_TS.$Requests.{$ship}?">
            <remove_value name="global.$GT_TS.$Requests.{$ship}"/>
          </do_if>
        </do_if>
      </actions>
    </library>
    

    <!-- Cache utilities: glx_lib_cache.xml (GLX_Lib_Cache) -->

    
    <!-- Calculate Fallback Distance -->
    <library name="GT_CalculateFallbackDistance" purpose="run_actions">
      <params>
        <param name="maxDistance" comment="Maximum distance (pilot's maxJumps)"/>
        <param name="skillLevel" comment="Pilot skill level (for capping fallback distance)"/>
      </params>
      <actions>
        <!-- Calculates fallback search distance: max(1, min(pilotMaxJumps, maxDistance / 3)) -->
        <!-- Formula: 1/3 of maxDistance, capped by pilot level capability, minimum 1 jump -->
        <!-- This compensates for lower profit thresholds in fallback search -->
        
        <!-- Calculate pilot's max jump capability based on skill level -->
        <set_value name="$pilotMaxJumps" exact="1"/>
        <do_if value="$skillLevel le 2">
          <set_value name="$pilotMaxJumps" exact="1"/>
        </do_if>
        <do_elseif value="$skillLevel le 5">
          <set_value name="$pilotMaxJumps" exact="3"/>
        </do_elseif>
        <do_elseif value="$skillLevel le 8">
          <set_value name="$pilotMaxJumps" exact="5"/>
        </do_elseif>
        <do_elseif value="$skillLevel le 11">
          <set_value name="$pilotMaxJumps" exact="10"/>
        </do_elseif>
        <do_elseif value="$skillLevel le 13">
          <set_value name="$pilotMaxJumps" exact="15"/>
        </do_elseif>
        <do_else>
          <set_value name="$pilotMaxJumps" exact="25"/>
        </do_else>
        
        <!-- Calculate 1/3 of maxDistance -->
        <set_value name="$calculatedDistance" exact="($maxDistance / 3)"/>
        
        <!-- Cap by pilot capability, then ensure minimum of 1 -->
        <set_value name="$fallbackDistance" exact="[$calculatedDistance, $pilotMaxJumps].min"/>
        <set_value name="$fallbackDistance" exact="[$fallbackDistance, 1].max"/>  <!-- Minimum: 1 jump -->
        
        <return value="$fallbackDistance"/>
      </actions>
    </library>
    
    <!-- Check Batch Status -->
    <library name="GT_CheckBatchStatus" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check batch status for"/>
      </params>
      <actions>
        <!-- Checks if batch processing is in progress and returns status information -->
        <!-- Returns table with: $IsBatchActive, $BatchShip, $ShouldProceed, $IsForThisShip -->
        <set_value name="$waitingForBatch" exact="false"/>
        <set_value name="$batchShip" exact="null"/>
        <do_if value="global.$GT_SearchResult.{$ship}?">
          <set_value name="$shipResults" exact="global.$GT_SearchResult.{$ship}"/>
          <do_if value="$shipResults.$WaitingForBatch? and $shipResults.$WaitingForBatch">
            <set_value name="$waitingForBatch" exact="true"/>
            <do_if value="$shipResults.$Ship?">
              <set_value name="$batchShip" exact="$shipResults.$Ship"/>
            </do_if>
          </do_if>
        </do_if>
        
        <set_value name="$isForThisShip" exact="false"/>
        <do_if value="$waitingForBatch and $batchShip? and $batchShip == $ship">
          <set_value name="$isForThisShip" exact="true"/>
        </do_if>
        
        <set_value name="$shouldProceed" exact="true"/>
        <do_if value="$waitingForBatch and $isForThisShip">
          <set_value name="$shouldProceed" exact="false"/>
        </do_if>
        
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$IsBatchActive" exact="$waitingForBatch"/>
        <set_value name="$result.$BatchShip" exact="$batchShip"/>
        <set_value name="$result.$ShouldProceed" exact="$shouldProceed"/>
        <set_value name="$result.$IsForThisShip" exact="$isForThisShip"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Update Rejection Stats -->
    <library name="GT_UpdateRejectionStats" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to update stats for"/>
        <param name="stats" comment="Rejection statistics table"/>
      </params>
      <actions>
        <!-- Updates LastRejectionStats in global.$GT_SearchResult for a ship -->
        <!-- Preserves existing entries for other ships, updates/adds entry for this ship -->
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_SearchResult exists -->
        <!-- CRITICAL: Validate ship parameter before using it as table key -->
        <do_if value="not $ship?">
          <!-- Ship is null - cannot update stats, exit silently -->
          <return value="null"/>
        </do_if>
        
        <set_value name="$existingLastRejectionStats" exact="null"/>
        <do_if value="global.$GT_SearchResult.$LastRejectionStats?">
          <set_value name="$existingLastRejectionStats" exact="global.$GT_SearchResult.$LastRejectionStats"/>
        </do_if>
        
        <!-- Build new $LastRejectionStats: preserve existing entries, update/add per-ship entry -->
        <set_value name="$newLastRejectionStats" exact="table[]"/>
        <!-- Copy existing entries if valid -->
        <do_if value="$existingLastRejectionStats?">
          <set_value name="$existingStatsKeys" exact="@$existingLastRejectionStats.keys"/>
          <do_if value="$existingStatsKeys?">
            <set_value name="$existingStatsKeysCount" exact="@$existingStatsKeys.count"/>
            <do_if value="$existingStatsKeysCount? and $existingStatsKeysCount gt 0">
              <do_all exact="$existingStatsKeysCount" counter="$k">
                <set_value name="$key" exact="$existingStatsKeys.{$k}"/>
                <do_if value="$key != $ship">
                  <set_value name="$newLastRejectionStats.{$key}" exact="@$existingLastRejectionStats.{$key}"/>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
        </do_if>
        <!-- Add/update per-ship entry -->
        <!-- CRITICAL: $ship is validated above, safe to use as table key -->
        <set_value name="$newLastRejectionStats.{$ship}" exact="$stats"/>
        
        <!-- Build new $searchResultTable: preserve existing properties, set new $LastRejectionStats -->
        <set_value name="$newSearchResultTable" exact="table[$LastRejectionStats = $newLastRejectionStats]"/>
        <!-- Copy other existing properties -->
        <set_value name="$existingSearchResult" exact="global.$GT_SearchResult"/>
        <do_if value="$existingSearchResult?">
          <set_value name="$existingKeys" exact="@$existingSearchResult.keys"/>
          <do_if value="$existingKeys?">
            <set_value name="$existingKeysCount" exact="@$existingKeys.count"/>
            <do_if value="$existingKeysCount? and $existingKeysCount gt 0">
              <do_all exact="$existingKeysCount" counter="$tk">
                <set_value name="$tableKey" exact="$existingKeys.{$tk}"/>
                <do_if value="$tableKey != 'LastRejectionStats'">
                  <set_value name="$newSearchResultTable.{$tableKey}" exact="@$existingSearchResult.{$tableKey}"/>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
        </do_if>
        <!-- Set atomically to global -->
        <set_value name="global.$GT_SearchResult" exact="$newSearchResultTable"/>
      </actions>
    </library>
    
    <!-- Get Price Range -->
    <library name="GT_GetPriceRange" purpose="run_actions">
      <params>
        <param name="shipIsIsolated" default="false" comment="Whether ship is isolated"/>
      </params>
      <actions>
        <!-- Returns price range from config: $sellPriceMax, $buyPriceMin -->
        <!-- For isolated ships, uses isolated-specific price ranges -->
        <set_value name="$sellPriceMax" exact="1.0"/>  <!-- Default fallback: +100% -->
        <set_value name="$buyPriceMin" exact="-1.0"/>  <!-- Default fallback: -100% -->
        <do_if value="global.$GT_Config? and global.$GT_Config.$Trading?">
          <do_if value="$shipIsIsolated">
            <!-- Isolated ships: Use isolated-specific price ranges -->
            <do_if value="global.$GT_Config.$Trading.$IsolatedSellPriceMax?">
              <set_value name="$sellPriceMax" exact="@global.$GT_Config.$Trading.$IsolatedSellPriceMax"/>
            </do_if>
            <do_if value="global.$GT_Config.$Trading.$IsolatedBuyPriceMin?">
              <set_value name="$buyPriceMin" exact="@global.$GT_Config.$Trading.$IsolatedBuyPriceMin"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Normal ships: Use standard price ranges -->
            <do_if value="global.$GT_Config.$Trading.$SellPriceMax?">
              <set_value name="$sellPriceMax" exact="@global.$GT_Config.$Trading.$SellPriceMax"/>
            </do_if>
            <do_if value="global.$GT_Config.$Trading.$BuyPriceMin?">
              <set_value name="$buyPriceMin" exact="@global.$GT_Config.$Trading.$BuyPriceMin"/>
            </do_if>
          </do_else>
        </do_if>
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$SellPriceMax" exact="$sellPriceMax"/>
        <set_value name="$result.$BuyPriceMin" exact="$buyPriceMin"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Sort Trades By Distance -->
    <library name="GT_SortTradesByDistance" purpose="run_actions">
      <params>
        <param name="tradesWithDistance" comment="List of trades with Distance field"/>
      </params>
      <actions>
        <!-- Sorts trades by distance (shortest first) using selection sort -->
        <!-- Input: List of tables with $Trade and $Distance fields -->
        <!-- Output: Sorted list (shortest distance first) -->
        <!-- Uses same pattern as original: check if already sorted to avoid duplicates -->
        <set_value name="$sortedTrades" exact="[]"/>
        <do_all exact="$tradesWithDistance.count" counter="$sortIdx">
          <set_value name="$minDistance" exact="999999999"/>
          <set_value name="$minIdx" exact="-1"/>
          <do_all exact="$tradesWithDistance.count" counter="$i">
            <set_value name="$alreadySorted" exact="false"/>
            <do_all exact="$sortedTrades.count" counter="$j">
              <do_if value="$sortedTrades.{$j}.$Trade == $tradesWithDistance.{$i}.$Trade">
                <set_value name="$alreadySorted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $alreadySorted">
              <set_value name="$tradeDistance" exact="@$tradesWithDistance.{$i}.$Distance"/>
              <do_if value="$tradeDistance? and $tradeDistance lt $minDistance">
                <set_value name="$minDistance" exact="$tradeDistance"/>
                <set_value name="$minIdx" exact="$i"/>
              </do_if>
            </do_if>
          </do_all>
          <do_if value="$minIdx ge 0">
            <append_to_list name="$sortedTrades" exact="$tradesWithDistance.{$minIdx}"/>
          </do_if>
        </do_all>
        <return value="$sortedTrades"/>
      </actions>
    </library>
    
    <!-- Calculate Fallback Trade Distances -->
    <library name="GT_CalculateFallbackTradeDistances" purpose="run_actions">
      <params>
        <param name="wareTrades" comment="List of trades for a specific ware"/>
        <param name="ship" comment="Ship executing the trade"/>
        <param name="homeSector" comment="Home sector for distance calculations"/>
        <param name="currentSector" comment="Current sector (ship's current position)"/>
        <param name="maxDistance" comment="Maximum distance from home sector"/>
        <param name="originalMaxDistance" comment="Original max distance (for fallback search)"/>
        <param name="isFallbackSearch" default="false" comment="Whether this is a fallback search"/>
      </params>
      <actions>
        <!-- Calculates distances for fallback search trades -->
        <!-- For fallback search: Filters by CURRENT LOCATION distance (2 jumps max), calculates home distance for reference -->
        <!-- For normal search: Filters by HOME SECTOR distance, calculates current distance for sorting -->
        <!-- Returns: $tradesWithDistance list, $rejectionStats -->
        <set_value name="$tradesWithDistance" exact="[]"/>
        <set_value name="$rejectedByUnreachable" exact="0"/>
        <set_value name="$rejectedByHomeDistance" exact="0"/>
        <set_value name="$evaluatedCount" exact="0"/>
        
        <!-- Get filterMaxDistance (home sector distance limit) -->
        <set_value name="$filterMaxDistance" exact="$maxDistance"/>  <!-- Default: use maxDistance -->
        <do_if value="$isFallbackSearch and $originalMaxDistance?">
          <set_value name="$filterMaxDistance" exact="$originalMaxDistance"/>  <!-- Fallback: use original pilot maxDistance (respects trading range) -->
        </do_if>
        
        <do_all exact="$wareTrades.count" counter="$i">
          <set_value name="$trade" exact="$wareTrades.{$i}"/>
          <set_value name="$buySector" exact="@$trade.$BuyStation.sector"/>
          <set_value name="$sellSector" exact="@$trade.$SellStation.sector"/>
          <set_value name="$buyStation" exact="@$trade.$BuyStation"/>
          <set_value name="$sellStation" exact="@$trade.$SellStation"/>
          <set_value name="$ware" exact="@$trade.$BuyOffer.ware"/>
          
          <do_if value="$isFallbackSearch">
            <!-- FALLBACK SEARCH: Filter by HOME SECTOR distance (respects pilot's trading range) -->
            <!-- Sector list was built from current location, but trades must still respect home sector range -->
            <set_value name="$buyDistance" exact="-1"/>
            <set_value name="$sellDistance" exact="-1"/>
            
            <do_if value="$buySector == $homeSector">
              <set_value name="$buyDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$buyDistance" exact="$homeSector.gatedistance.{$buySector}"/>
            </do_else>
            
            <do_if value="$sellSector == $homeSector">
              <set_value name="$sellDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="$homeSector.gatedistance.{$sellSector}"/>
            </do_else>
            
            <set_value name="$maxStationDistance" exact="[$buyDistance, $sellDistance].max"/>
            
            <!-- Filter by home sector distance (using originalMaxDistance to respect pilot's trading range) -->
            <do_if value="$buyDistance lt 0 or $sellDistance lt 0">
              <!-- Unreachable from home sector - skip -->
              <set_value name="$rejectedByUnreachable" exact="$rejectedByUnreachable + 1"/>
              <continue/>
            </do_if>
            <do_if value="$maxStationDistance gt $filterMaxDistance">
              <!-- Too far from home sector - skip (respects pilot's trading range) -->
              <set_value name="$rejectedByHomeDistance" exact="$rejectedByHomeDistance + 1"/>
              <continue/>
            </do_if>
            
            <!-- Calculate current location distance for SORTING (prioritize nearby trades) -->
            <set_value name="$currentToBuyDistance" exact="-1"/>
            <set_value name="$currentToSellDistance" exact="-1"/>
            <do_if value="$buySector == $currentSector">
              <set_value name="$currentToBuyDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$currentToBuyDistance" exact="$currentSector.gatedistance.{$buySector}"/>
            </do_else>
            <do_if value="$sellSector == $currentSector">
              <set_value name="$currentToSellDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$currentToSellDistance" exact="$currentSector.gatedistance.{$sellSector}"/>
            </do_else>
            <set_value name="$maxDistanceFromCurrent" exact="[$currentToBuyDistance, $currentToSellDistance].max"/>
            
            <!-- Count trade as evaluated (passed home sector filter) -->
            <set_value name="$evaluatedCount" exact="$evaluatedCount + 1"/>
            
            <!-- Sort by distance from current position (prioritize nearby trades) -->
            <set_value name="$sortDistance" exact="$maxDistanceFromCurrent"/>
          </do_if>
          <do_else>
            <!-- NORMAL SEARCH: Filter by HOME SECTOR distance -->
            <set_value name="$buyDistance" exact="-1"/>
            <set_value name="$sellDistance" exact="-1"/>
            
            <do_if value="$buySector == $homeSector">
              <set_value name="$buyDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$buyDistance" exact="$homeSector.gatedistance.{$buySector}"/>
            </do_else>
            
            <do_if value="$sellSector == $homeSector">
              <set_value name="$sellDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$sellDistance" exact="$homeSector.gatedistance.{$sellSector}"/>
            </do_else>
            
            <!-- Use max distance (farthest station from home) for filtering -->
            <set_value name="$maxStationDistance" exact="[$buyDistance, $sellDistance].max"/>
            
            <!-- Filter by home distance -->
            <do_if value="$buyDistance lt 0 or $sellDistance lt 0">
              <!-- Unreachable from home sector - skip -->
              <set_value name="$rejectedByUnreachable" exact="$rejectedByUnreachable + 1"/>
              <continue/>
            </do_if>
            <do_if value="$maxStationDistance gt $filterMaxDistance">
              <!-- Too far from home sector - skip -->
              <set_value name="$rejectedByHomeDistance" exact="$rejectedByHomeDistance + 1"/>
              <continue/>
            </do_if>
            
            <!-- Trade passed home distance filter - calculate distance from current for SCORING/SORTING -->
            <set_value name="$currentToBuyDistance" exact="-1"/>
            <set_value name="$currentToSellDistance" exact="-1"/>
            <set_value name="$maxDistanceFromCurrent" exact="-1"/>
            <do_if value="$buySector == $currentSector">
              <set_value name="$currentToBuyDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$currentToBuyDistance" exact="$currentSector.gatedistance.{$buySector}"/>
            </do_else>
            <do_if value="$sellSector == $currentSector">
              <set_value name="$currentToSellDistance" exact="0"/>
            </do_if>
            <do_else>
              <set_value name="$currentToSellDistance" exact="$currentSector.gatedistance.{$sellSector}"/>
            </do_else>
            <set_value name="$maxDistanceFromCurrent" exact="[$currentToBuyDistance, $currentToSellDistance].max"/>
            
            <!-- Count trade as evaluated (passed home distance filter) -->
            <set_value name="$evaluatedCount" exact="$evaluatedCount + 1"/>
            
            <!-- Sort by distance from home -->
            <set_value name="$sortDistance" exact="$maxStationDistance"/>
          </do_else>
          
          <append_to_list name="$tradesWithDistance" exact="table[
            $Trade = $trade,
            $Distance = $sortDistance,
            $HomeDistance = $maxStationDistance
          ]"/>
        </do_all>
        
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$TradesWithDistance" exact="$tradesWithDistance"/>
        <set_value name="$result.$RejectedByUnreachable" exact="$rejectedByUnreachable"/>
        <set_value name="$result.$RejectedByHomeDistance" exact="$rejectedByHomeDistance"/>
        <set_value name="$result.$EvaluatedCount" exact="$evaluatedCount"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Select Best Trades With Diversity -->
    <library name="GT_SelectBestTradesWithDiversity" purpose="run_actions">
      <params>
        <param name="sortedTrades" comment="List of trades sorted by distance"/>
        <param name="maxDistance" comment="Maximum distance limit"/>
        <param name="filterMaxDistance" comment="Filter max distance (for fallback search)"/>
        <param name="isFallbackSearch" default="false" comment="Whether this is a fallback search"/>
        <param name="ware" comment="Ware being traded (for logging)"/>
        <param name="ship" comment="Ship executing the trade"/>
      </params>
      <actions>
        <!-- Selects top 5 trades with station pair diversity -->
        <!-- Returns: $topTrades list (up to 5 trades), $skippedDueToDistance -->
        <set_value name="$topTrades" exact="[]"/>
        <set_value name="$skippedDueToDistance" exact="0"/>
        <set_value name="$distanceLimit" exact="$maxDistance"/>  <!-- Default: use maxDistance (home sector) -->
        <do_if value="$isFallbackSearch">
          <set_value name="$distanceLimit" exact="$filterMaxDistance"/>  <!-- Fallback: use home distance limit -->
        </do_if>
        
        <do_all exact="$sortedTrades.count" counter="$i">
          <!-- Early exit: If this trade exceeds distance limit, all subsequent trades are also too far -->
          <do_if value="$sortedTrades.{$i}.$HomeDistance gt $distanceLimit">
            <set_value name="$skippedDueToDistance" exact="$sortedTrades.count - $i"/>
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$distanceType" exact="'home sector'"/>  <!-- Always home sector for distance limit check -->
              <debug_text text="'[GT-Resume] (' + $ship.idcode + ') EARLY EXIT for ware ' + @$ware.name + ': Reached distance limit (' + $distanceLimit + ' jumps from ' + $distanceType + ') at trade ' + $i + '/' + $sortedTrades.count + ' (skipped ' + $skippedDueToDistance + ' trades)'" chance="100"/>
            </do_if>
            <break/>
          </do_if>
          
          <!-- Trade is within distance - select top 5 by Score with STATION PAIR DIVERSITY -->
          <set_value name="$trade" exact="$sortedTrades.{$i}.$Trade"/>
          <set_value name="$buyStation" exact="$trade.$BuyStation"/>
          <set_value name="$sellStation" exact="$trade.$SellStation"/>
          
          <!-- Check if this station pair already exists in topTrades -->
          <set_value name="$stationPairExists" exact="false"/>
          <do_all exact="$topTrades.count" counter="$j">
            <set_value name="$existingBuyStation" exact="$topTrades.{$j}.$BuyStation"/>
            <set_value name="$existingSellStation" exact="$topTrades.{$j}.$SellStation"/>
            <do_if value="$existingBuyStation == $buyStation and $existingSellStation == $sellStation">
              <set_value name="$stationPairExists" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          
          <!-- Skip if station pair already exists (ensure diversity) -->
          <do_if value="not $stationPairExists">
            <set_value name="$shouldAdd" exact="false"/>
            <do_if value="$topTrades.count lt 5">
              <!-- Still building initial top 5 - add unique station pair -->
              <set_value name="$shouldAdd" exact="true"/>
            </do_if>
            <do_else>
              <!-- Top 5 full - check if this trade's Score is better than worst -->
              <set_value name="$worstScore" exact="999999999"/>
              <set_value name="$worstIdx" exact="-1"/>
              <do_all exact="5" counter="$j">
                <do_if value="$topTrades.{$j}.$Score lt $worstScore">
                  <set_value name="$worstScore" exact="$topTrades.{$j}.$Score"/>
                  <set_value name="$worstIdx" exact="$j"/>
                </do_if>
              </do_all>
              <do_if value="$trade.$Score gt $worstScore">
                <!-- Replace worst with this trade (unique station pair) -->
                <set_value name="$shouldAdd" exact="true"/>
              </do_if>
            </do_else>
            <do_if value="$shouldAdd">
              <do_if value="$topTrades.count lt 5">
                <append_to_list name="$topTrades" exact="$trade"/>
              </do_if>
              <do_else>
                <!-- Replace worst trade in top5 -->
                <set_value name="$worstScore" exact="999999999"/>
                <set_value name="$worstIdx" exact="-1"/>
                <do_all exact="5" counter="$j">
                  <do_if value="$topTrades.{$j}.$Score lt $worstScore">
                    <set_value name="$worstScore" exact="$topTrades.{$j}.$Score"/>
                    <set_value name="$worstIdx" exact="$j"/>
                  </do_if>
                </do_all>
                <do_if value="$worstIdx ge 0">
                  <set_value name="$topTrades.{$worstIdx}" exact="$trade"/>
                </do_if>
              </do_else>
            </do_if>
          </do_if>
        </do_all>
        
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$TopTrades" exact="$topTrades"/>
        <set_value name="$result.$SkippedDueToDistance" exact="$skippedDueToDistance"/>
        <return value="$result"/>
      </actions>
    </library>

<!-- Register pilot with the GT system -->
    <library name="Register_Pilot">
      <params>
        <param name="pilot" comment="Pilot to register"/>
        <param name="ship" comment="Ship associated with pilot"/>
        <param name="debuglevel" default="1" comment="Debug output level"/>
      </params>
      <actions>
        <!-- Initialize global pilot registry if needed -->
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_Pilots exists -->
        
        <!-- Check if pilot is new or existing -->
        <do_if value="not global.$GT_Pilots.{$pilot}?">
          <!-- New pilot - initialize data -->
          <set_value name="global.$GT_Pilots.{$pilot}" exact="table[
            $Name = $pilot.name,
            $RegistrationTime = player.age,
            $LastActiveTime = player.age,
            $TotalXP = 0,
            $TradesCompleted = 0,
            $ProfitGenerated = 0Cr,
            $RequiresTraining = false,
            $CurrentlyTraining = false,
            $Ship = $ship
          ]"/>
          
          <do_if value="$debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Data] Registered new pilot: ' + $pilot.name + ' for ship ' + $ship.idcode" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Existing pilot - update activity -->
          <set_value name="global.$GT_Pilots.{$pilot}.$LastActiveTime" exact="player.age"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
          
          <do_if value="$debuglevel ge 2 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Data] Updated existing pilot: ' + $pilot.name + ' for ship ' + $ship.idcode" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </library>
    
    <!-- Register ship with the GT system -->
    <library name="Register_Ship">
      <params>
        <param name="ship" comment="Ship to register"/>
        <param name="debuglevel" default="1" comment="Debug output level"/>
      </params>
      <actions>
        <!-- Initialize global ship registry if needed -->
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_Ships exists -->
        
        <!-- Register or update ship -->
        <do_if value="not global.$GT_Ships.{$ship}?">
          <!-- New ship - initialize data -->
          <set_value name="global.$GT_Ships.{$ship}" exact="table[
            $Name = $ship.knownname,
            $IDCode = $ship.idcode,
            $RegistrationTime = player.age,
            $LastActiveTime = player.age,
            $IsSubordinate = false,
            $Commander = null,
            $FleetPosition = 0,
            $TotalTrades = 0,
            $TotalProfit = 0,
            $LastTradeTime = null
          ]"/>
          
          <!-- Check if ship is subordinate -->
          <do_if value="$ship.commander and $ship.commander != $ship">
            <set_value name="global.$GT_Ships.{$ship}.$IsSubordinate" exact="true"/>
            <set_value name="global.$GT_Ships.{$ship}.$Commander" exact="$ship.commander"/>
            
            <!-- FleetPosition removed: Not used (Get_Fleet_Startup_Delay library not called) -->
            <!-- Trade search queue already prevents simultaneous searches via MaxConcurrent -->
            <!-- FleetPosition calculation caused stutter with many subordinates (O(n) loop) -->
            <!-- FleetPosition remains initialized to 0 (default value) -->
          </do_if>
          
          <!-- OPTIMIZATION: Update cached active trader count incrementally -->
          <!-- Only increment if ship is operational (matches counting logic) -->
          <do_if value="$ship.exists and $ship.isoperational">
            <do_if value="not global.$GT_ActiveTraderCount?">
              <set_value name="global.$GT_ActiveTraderCount" exact="0"/>
            </do_if>
            <set_value name="global.$GT_ActiveTraderCount" operation="add"/>
          </do_if>
          
          <do_if value="$debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Data] Registered new ship: ' + $ship.knownname + ' (' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Existing ship - update activity -->
          <set_value name="global.$GT_Ships.{$ship}.$LastActiveTime" exact="player.age"/>
          
          <do_if value="$debuglevel ge 2 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Data] Updated existing ship: ' + $ship.knownname + ' (' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </library>
    
    <!-- Initialize global systems if needed -->
    <library name="Ensure_Global_Systems">
      <params>
        <param name="debuglevel" default="1" comment="Debug output level"/>
      </params>
      <actions>
        <set_value name="$systemsInitialized" exact="0"/>
        
        <!-- Initialize ThreatIntelligence system -->
        <do_if value="not global.$GT_ThreatIntelligence?">
          <set_value name="global.$GT_ThreatIntelligence" exact="table[]"/>
          <set_value name="$systemsInitialized" exact="$systemsInitialized + 1"/>
        </do_if>
        
        <!-- Trade cache is NOT pre-initialized - X4 locks empty table[] -->
        <!-- It will be created WITH data on first cache write -->
        
        <!-- Initialize global configuration if needed -->
        <do_if value="not global.$GT_GlobalSettings?">
          <set_value name="global.$GT_GlobalSettings" exact="table[
            $XP = table[
              $AutoTraining = true,
              $BaseXPPerTrade = 25,
              $DistanceBonus = 20,
              $RiskBonus = 25
            ],
            $Fleet = table[
              $EnableFleetCoordination = true
            ],
            $Debug = table[
              $DebugLevel = 1,
              $TradeEvaluation = false
            ]
          ]"/>
          <set_value name="$systemsInitialized" exact="$systemsInitialized + 1"/>
        </do_if>
        
        <do_if value="$systemsInitialized gt 0 and $debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Data] Initialized ' + $systemsInitialized + ' global systems'" chance="100"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Clean up pilot data (safe removal) -->
    <library name="Cleanup_Pilot_Data">
      <params>
        <param name="pilot" comment="Pilot to remove data for"/>
        <param name="debuglevel" default="1" comment="Debug output level"/>
      </params>
      <actions>
        <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <remove_value name="global.$GT_Pilots.{$pilot}"/>
          
          <do_if value="$debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Data] Cleaned up data for pilot: ' + $pilot.name" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </library>
    
    <!-- Clean up ship data (safe removal) -->
    <library name="Cleanup_Ship_Data">
      <params>
        <param name="ship" comment="Ship to remove data for"/>
        <param name="debuglevel" default="1" comment="Debug output level"/>
      </params>
      <actions>
        <do_if value="$ship? and global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <!-- OPTIMIZATION: Update cached active trader count incrementally -->
          <!-- Only decrement if ship was operational (matches counting logic) -->
          <do_if value="$ship.exists and $ship.isoperational and global.$GT_ActiveTraderCount? and global.$GT_ActiveTraderCount gt 0">
            <set_value name="global.$GT_ActiveTraderCount" operation="subtract"/>
          </do_if>
          
          <remove_value name="global.$GT_Ships.{$ship}"/>
          
          <do_if value="$debuglevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Data] Cleaned up data for ship: ' + $ship.knownname + ' (' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </library>
    
    <!-- Get fleet coordination delay for subordinate -->
    <library name="Get_Fleet_Startup_Delay" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to calculate delay for"/>
      </params>
      <actions>
        <set_value name="$delay" exact="0"/>
        
        <!-- Check if ship is subordinate -->
        <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$IsSubordinate">
          <set_value name="$fleetPosition" exact="global.$GT_Ships.{$ship}.$FleetPosition"/>
          
          <!-- Calculate staggered startup delay -->
          <set_value name="$delay" exact="$fleetPosition * 30s"/>
          
          <!-- Cap maximum delay -->
          <do_if value="$delay gt 300s">
            <set_value name="$delay" exact="300s"/>
          </do_if>
        </do_if>
        
        <set_value name="this.$result" exact="$delay"/>
      </actions>
    </library>

<!-- ========================================= -->
    <!-- NOTIFICATION SYSTEM -->
    <!-- ========================================= -->
    
    <!-- Show Notification -->
    <library name="GT_ShowNotification" purpose="run_actions">
      <params>
        <param name="text" comment="Notification text"/>
        <param name="category" default="'info'" comment="Notification category"/>
        <param name="timeout" default="5s" comment="Notification timeout"/>
      </params>
      <actions>
        <show_notification text="$text" timeout="$timeout"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- VALIDATION HELPERS -->
    <!-- ========================================= -->
    
    <!-- Validate Ship -->
    <library name="GT_ValidateShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship object to validate"/>
      </params>
      <actions>
        <do_if value="@$ship.exists and @$ship.isoperational and (@$ship.iswreck == false) and (@$ship.pilot != null)">
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Validate Station -->
    <library name="GT_ValidateStation" purpose="run_actions">
      <params>
        <param name="station" comment="Station object to validate"/>
        <param name="ship" default="null" comment="Optional: Ship parameter (reserved for future use)"/>
      </params>
      <actions>
        <!-- 
          DESIGN NOTE: Threat avoidance is now handled by vanilla pathfinding
          - Trade orders created with internal="true" use strictblacklist mode
          - Vanilla pathfinding routes AROUND blacklisted sectors automatically
          - If no route exists, the order fails gracefully and ship requests new trade
          - No need for manual sector filtering here
        -->
        <do_if value="@$station.exists and @$station.isoperational">
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Check if Ware is Allowed -->
    <library name="GT_IsWareAllowed" purpose="run_actions">
      <params>
        <param name="ware" comment="Ware to check"/>
        <param name="allowIllegal" default="true" comment="Whether to allow illegal wares"/>
        <param name="zone" default="null" comment="Optional: Zone context for illegal check"/>
        <param name="shipOwner" default="null" comment="Optional: Ship owner for license check"/>
      </params>
      <actions>
        <!-- Illegal ware check: Always use global check when allowIllegal=false -->
        <!-- CRITICAL: Illegal wares are NEVER allowed if AllowIllegal=false, regardless of faction or licenses -->
        <do_if value="not $allowIllegal">
          <!-- FIX: Use safe operator and explicit gt 0 check to ensure legal wares (illegal=0) are not filtered -->
          <do_if value="@$ware.illegal gt 0">
            <return value="false"/>
          </do_if>
        </do_if>
        
        <!-- Check blacklist -->
        <do_if value="global.$GT_Config.$WareFilter.$BlacklistedWares?">
          <do_all exact="global.$GT_Config.$WareFilter.$BlacklistedWares.count" counter="$i">
            <do_if value="global.$GT_Config.$WareFilter.$BlacklistedWares.{$i} == $ware">
              <return value="false"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Check whitelist if exists -->
        <do_if value="global.$GT_Config.$WareFilter.$WhitelistedWares? and global.$GT_Config.$WareFilter.$WhitelistedWares.count gt 0">
          <do_all exact="global.$GT_Config.$WareFilter.$WhitelistedWares.count" counter="$j">
            <do_if value="global.$GT_Config.$WareFilter.$WhitelistedWares.{$j} == $ware">
              <return value="true"/>
            </do_if>
          </do_all>
          <return value="false"/>
        </do_if>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- XP CALCULATIONS -->
    <!-- ========================================= -->
    
    <!-- Calculate XP Award -->
    <library name="GT_CalculateXP" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship that completed trade"/>
        <param name="profit" comment="Trade profit amount"/>
        <param name="jumps" default="1" comment="Number of jumps"/>
      </params>
      <actions>
        <!-- Get base XP from config -->
        <set_value name="$baseXP" exact="@global.$GT_Config.$XP.$BaseXPPerTrade"/>
        <do_if value="not $baseXP">
          <set_value name="$baseXP" exact="100"/>
        </do_if>
        
        <!-- Calculate distance bonus -->
        <set_value name="$distanceBonusPerJump" exact="@global.$GT_Config.$XP.$DistanceBonus"/>
        <do_if value="not $distanceBonusPerJump">
          <set_value name="$distanceBonusPerJump" exact="20"/>
        </do_if>
        <set_value name="$distanceBonus" exact="$jumps * $distanceBonusPerJump"/>
        
        <!-- Calculate risk bonus -->
        <set_value name="$riskBonus" exact="0"/>
              <!-- Risk bonus calculation disabled - sector security property uncertain -->
      <set_value name="$riskBonus" exact="0"/>
        
        <!-- Return total XP -->
        <return value="$baseXP + $distanceBonus + $riskBonus"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- CONFIGURATION HELPERS -->
    <!-- ========================================= -->
    
    <!-- Get Configuration Value -->
    <library name="GT_GetConfigValue" purpose="run_actions">
      <params>
        <param name="section" comment="Configuration section"/>
        <param name="key" comment="Configuration key"/>
        <param name="default" default="null" comment="Default value if not found"/>
      </params>
      <actions>
        <do_if value="global.$GT_Config? and global.$GT_Config.{$section}? and global.$GT_Config.{$section}.{$key}?">
          <return value="@global.$GT_Config.{$section}.{$key}"/>
        </do_if>
        <return value="$default"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- TRADE FILTERING AND ANALYSIS -->
    <!-- ========================================= -->
    
    <!-- Filter Trade Offer -->
    <library name="GT_FilterTradeOffer" purpose="run_actions">
      <params>
        <param name="offer" comment="Trade offer to filter"/>
        <param name="ship" comment="Ship that would execute the trade"/>
        <param name="allowIllegal" default="true" comment="Whether to allow illegal wares"/>
      </params>
      <actions>
        <!-- Check if ware is allowed (global illegal check) -->
        <run_actions ref="GT_IsWareAllowed" result="$wareAllowed">
          <param name="ware" value="$offer.ware"/>
          <param name="allowIllegal" value="$allowIllegal"/>
        </run_actions>
        <do_if value="not $wareAllowed">
          <return value="false"/>
        </do_if>
        
        <!-- Check if ship can carry this ware -->
        <do_if value="$ship.cargo.{$offer.ware}.max le 0">
          <return value="false"/>
        </do_if>
        
        <!-- Check if offer has sufficient amount -->
        <do_if value="$offer.amount le 0">
          <return value="false"/>
        </do_if>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Calculate Trade Profit -->
    <library name="GT_CalculateProfit" purpose="run_actions">
      <params>
        <param name="buyPrice" comment="Price to buy at"/>
        <param name="sellPrice" comment="Price to sell at"/>
        <param name="amount" comment="Amount to trade"/>
        <param name="expenses" default="0Cr" comment="Additional expenses"/>
      </params>
      <actions>
        <set_value name="$revenue" exact="$sellPrice * $amount"/>
        <set_value name="$cost" exact="$buyPrice * $amount"/>
        
        <!-- PROFIT DEBUG: Log profit calculation details for investigation -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$calculatedProfit" exact="$revenue - $cost - $expenses"/>
          <debug_text text="'[GT-CalcProfit] PROFIT CALCULATION:' + 
            '\n  buyPrice: ' + $buyPrice + ' RAW (' + ($buyPrice/100) + ' Cr)' +
            '\n  sellPrice: ' + $sellPrice + ' RAW (' + ($sellPrice/100) + ' Cr)' +
            '\n  amount: ' + $amount + ' units' +
            '\n  revenue: ' + $revenue + ' RAW (' + ($revenue/100) + ' Cr)' +
            '\n  cost: ' + $cost + ' RAW (' + ($cost/100) + ' Cr)' +
            '\n  expenses: ' + $expenses + ' RAW (' + ($expenses/100) + ' Cr)' +
            '\n  profit: ' + $calculatedProfit + ' RAW (' + ($calculatedProfit/100) + ' Cr)' +
            '\n  Verification: (' + ($sellPrice/100) + ' - ' + ($buyPrice/100) + ') * ' + $amount + ' = ' + (($sellPrice - $buyPrice) * $amount / 100) + ' Cr'" chance="100"/>
        </do_if>
        
        <return value="$revenue - $cost - $expenses"/>
      </actions>
    </library>
    
    <!-- Calculate ROI (Return on Investment) -->
    <library name="GT_CalculateROI" purpose="run_actions">
      <params>
        <param name="investment" comment="Investment amount in credits"/>
        <param name="profit" comment="Profit amount in credits"/>
      </params>
      <actions>
        <!-- Returns ROI as percentage (21 = 21%) to avoid integer division issues -->
        <!-- OLD approach with decimals (0.15 = 15%) failed due to X4 MD integer truncation -->
        <do_if value="$investment gt 0">
          <return value="(($profit * 100) / $investment)"/>
        </do_if>
        <return value="0"/>
      </actions>
    </library>
    
    <!-- Calculate Trade Risk -->
    <library name="GT_CalculateRisk" purpose="run_actions">
      <params>
        <param name="sector" comment="Sector to assess risk for"/>
        <param name="ship" comment="Ship that would travel there"/>
      </params>
      <actions>
              <!-- Calculate security based on faction relations and sector characteristics -->
      <set_value name="$sectorSecurity" exact="0.5"/>
      
      <do_if value="$sector? and $sector.owner?">
                      <set_value name="$relation" exact="faction.player.relationto.{$sector.owner}"/>
        <do_if value="$relation ge 0.1">
          <set_value name="$sectorSecurity" exact="1.0"/>  <!-- Friendly = very safe -->
        </do_if>
        <do_elseif value="$relation ge -0.1">
          <set_value name="$sectorSecurity" exact="0.75"/> <!-- Neutral = safe -->
        </do_elseif>
        <do_elseif value="$relation ge -0.5">
          <set_value name="$sectorSecurity" exact="0.5"/>  <!-- Hostile = moderate -->
        </do_elseif>
        <do_else>
          <set_value name="$sectorSecurity" exact="0.25"/> <!-- Very hostile = dangerous -->
        </do_else>
        
        <!-- Extra danger for Xenon/Kha'ak sectors -->
        <do_if value="$sector.owner.id == 'xenon' or $sector.owner.id == 'khaak'">
          <set_value name="$sectorSecurity" exact="0.1"/>
        </do_if>
      </do_if>
      
      <!-- Base risk from security level -->
      <set_value name="$securityRisk" exact="1.0 - $sectorSecurity"/>
        
        <!-- Distance risk factor -->
        <set_value name="$distance" exact="$ship.distanceto.{$sector}"/>
        <set_value name="$distanceRisk" exact="[$distance / 100000, 0.5].min"/>
        
        <!-- Faction relation risk -->
        <set_value name="$relationRisk" exact="0"/>
        <do_if value="$sector.owner != $ship.owner">
          <set_value name="$relation" exact="$ship.owner.relationto.{$sector.owner}"/>
          <do_if value="$relation lt 0">
            <set_value name="$relationRisk" exact="($relation * -1) / 100"/>
          </do_if>
        </do_if>
        
        <!-- Combined risk (weighted average) -->
        <set_value name="$combinedRisk" exact="($securityRisk * 0.5) + ($distanceRisk * 0.3) + ($relationRisk * 0.2)"/>
        <return value="[$combinedRisk, 1.0].min"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- SHIP/SECTOR UTILITIES -->
    <!-- ========================================= -->
    
    <!-- Get Home Sector -->
    <library name="GT_GetHomeSector" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to get home sector for"/>
      </params>
      <actions>
        <!-- CRITICAL: Subordinates ALWAYS use commander's home sector (not a fallback!) -->
        <set_value name="$homeBase" exact="null"/>
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <!-- Ship is a subordinate - ALWAYS use commander's home sector -->
          <do_if value="$ship.commander.defaultorder?">
            <set_value name="$commanderHome" exact="@$ship.commander.defaultorder.$home"/>
            <do_if value="@$commanderHome.exists">
              <set_value name="$homeBase" exact="$commanderHome"/>
            </do_if>
            <!-- Galaxy Miner compatibility: explicit homeSector/homeStation params -->
            <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.commander.defaultorder.$homeSector? and @$ship.commander.defaultorder.$homeSector.exists">
              <set_value name="$homeBase" exact="$ship.commander.defaultorder.$homeSector"/>
            </do_if>
            <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.commander.defaultorder.$homeStation? and @$ship.commander.defaultorder.$homeStation.exists">
              <set_value name="$homeBase" exact="$ship.commander.defaultorder.$homeStation"/>
            </do_if>
            <!-- Galaxy Miner UI flow: player clicks a sector position -> only $homePosition is set;
                 $homeSector / $homeStation are not populated unless the order's own resolver has run.
                 Probe homePosition.{1} so subordinates of a position-only commander still resolve. -->
            <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.commander.defaultorder.$homePosition? and $ship.commander.defaultorder.$homePosition.{1}? and $ship.commander.defaultorder.$homePosition.{1}.exists and $ship.commander.defaultorder.$homePosition.{1}.isclass.sector">
              <set_value name="$homeBase" exact="$ship.commander.defaultorder.$homePosition.{1}"/>
            </do_if>
            <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.commander.defaultorder.$homePosition? and $ship.commander.defaultorder.$homePosition.{1}? and $ship.commander.defaultorder.$homePosition.{1}.sector? and $ship.commander.defaultorder.$homePosition.{1}.sector.exists">
              <set_value name="$homeBase" exact="$ship.commander.defaultorder.$homePosition.{1}.sector"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- For non-subordinates: Always use defaultorder.$home as PRIMARY source (fixed value in order) -->
        <!-- Home sector is a fixed value in the order settings and should NEVER drift -->
        <do_if value="not $homeBase? or not $homeBase.exists">
          <set_value name="$homeBase" exact="@$ship.defaultorder.$home"/>
        </do_if>
        <!-- Galaxy Miner compatibility: explicit homeSector/homeStation params -->
        <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.defaultorder? and $ship.defaultorder.$homeSector? and @$ship.defaultorder.$homeSector.exists">
          <set_value name="$homeBase" exact="$ship.defaultorder.$homeSector"/>
        </do_if>
        <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.defaultorder? and $ship.defaultorder.$homeStation? and @$ship.defaultorder.$homeStation.exists">
          <set_value name="$homeBase" exact="$ship.defaultorder.$homeStation"/>
        </do_if>
        <!-- Galaxy Miner UI flow (position-only): see commander branch above. The order's own init
             resolves $homePosition.{1} into $homeSector and persists via edit_order_param, but a
             freshly created order may invoke this lib before that resolver has run, and savegame
             states can land mid-init; reading homePosition.{1} directly closes that gap. -->
        <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.defaultorder? and $ship.defaultorder.$homePosition? and $ship.defaultorder.$homePosition.{1}? and $ship.defaultorder.$homePosition.{1}.exists and $ship.defaultorder.$homePosition.{1}.isclass.sector">
          <set_value name="$homeBase" exact="$ship.defaultorder.$homePosition.{1}"/>
        </do_if>
        <do_if value="(not $homeBase? or not $homeBase.exists) and $ship.defaultorder? and $ship.defaultorder.$homePosition? and $ship.defaultorder.$homePosition.{1}? and $ship.defaultorder.$homePosition.{1}.sector? and $ship.defaultorder.$homePosition.{1}.sector.exists">
          <set_value name="$homeBase" exact="$ship.defaultorder.$homePosition.{1}.sector"/>
        </do_if>
        
        <!-- Fallback: Only if defaultorder.$home is not available, check GT_AIParameters -->
        <do_if value="not $homeBase? or not $homeBase.exists">
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$HomeBase?">
            <set_value name="$homeBase" exact="global.$GT_AIParameters.{$ship}.$HomeBase"/>
          </do_if>
        </do_if>
        
        <!-- REMOVED: Never fall back to $ship.sector (causes cascading drift) -->
        <!-- If home is still null, log critical error and return null -->
        <do_if value="not $homeBase? or not $homeBase.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ERROR] Home sector not found for ' + $ship.idcode + ' - defaultorder.$home is null and GT_AIParameters.$HomeBase is null! This should never happen. Returning null to prevent drift.'" chance="100"/>
          </do_if>
          <!-- Return null instead of ship.sector to prevent drift -->
          <return value="null"/>
        </do_if>
        
        <!-- Extract sector from home base (station/sector) -->
        <set_value name="$homeSector" exact="null"/>
        <do_if value="@$homeBase.exists">
          <do_if value="$homeBase.isclass.station">
            <set_value name="$homeSector" exact="$homeBase.sector"/>
          </do_if>
          <do_elseif value="$homeBase.isclass.sector">
            <set_value name="$homeSector" exact="$homeBase"/>
          </do_elseif>
        </do_if>
        
        <!-- Validate final home sector - return null if extraction failed (prevents drift) -->
        <do_if value="not $homeSector? or not $homeSector.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ERROR] Failed to extract home sector from homeBase for ' + $ship.idcode + ' - returning null to prevent drift!'" chance="100"/>
          </do_if>
          <!-- Return null instead of ship.sector to prevent drift -->
          <return value="null"/>
        </do_if>
        
        <return value="$homeSector"/>
      </actions>
    </library>
    
    <!-- Get Sector Name Safe -->
    <library name="GT_GetSectorNameSafe" purpose="run_actions">
      <params>
        <param name="sector" default="null" comment="Sector to get name for (or null to use ship.sector)"/>
        <param name="ship" default="null" comment="Ship to get sector from if sector not provided"/>
      </params>
      <actions>
        <set_value name="$targetSector" exact="$sector"/>
        <do_if value="not $targetSector?">
          <do_if value="$ship?">
            <set_value name="$targetSector" exact="$ship.sector"/>
          </do_if>
        </do_if>
        <set_value name="$sectorName" exact="@$targetSector.knownname"/>
        <do_if value="not $sectorName?">
          <set_value name="$sectorName" exact="'Unknown Sector'"/>
        </do_if>
        <return value="$sectorName"/>
      </actions>
    </library>
    
    <!-- Get Ware Basket Safe (with null-checking pattern) -->
    <library name="GT_GetWareBasketSafe" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to get ware basket for"/>
      </params>
      <actions>
        <!-- CRITICAL: Initialize to safe default FIRST (memory:10529400 - ? checks existence, not null) -->
        <set_value name="$wareBasket" exact="[]"/>
        <!-- Step 2: Check if source exists -->
        <do_if value="global.$GT_AIParameters.{$ship}.$WareBasket?">
          <!-- Step 3: Get value with @ (returns null if missing) -->
          <set_value name="$tempBasket" exact="@global.$GT_AIParameters.{$ship}.$WareBasket"/>
          <!-- Step 4: Extract count property with @ to check if result is valid list -->
          <set_value name="$tempCount" exact="@$tempBasket.count"/>
          <!-- Step 5: Check if COUNT result exists and is valid (>= 0 means it's a list, not null) -->
          <do_if value="$tempCount? and $tempCount ge 0">
            <!-- Step 6: Now safe to use the original temp value -->
            <set_value name="$wareBasket" exact="$tempBasket"/>
          </do_if>
        </do_if>
        <return value="$wareBasket"/>
      </actions>
    </library>
    
    <!-- Check if Ware is in Basket -->
    <library name="GT_IsWareInBasket" purpose="run_actions">
      <params>
        <param name="ware" comment="Ware to check"/>
        <param name="basket" comment="Ware basket list to check against"/>
      </params>
      <actions>
        <!-- Use explicit loop for reliable list membership check (indexof unreliable) -->
        <set_value name="$found" exact="false"/>
        <do_if value="(if $basket != null then $basket.count else 0) gt 0">
          <do_all exact="$basket.count" counter="$i">
            <do_if value="$basket.{$i} == $ware">
              <set_value name="$found" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <return value="$found"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- MARKET ANALYSIS -->
    <!-- ========================================= -->
    
    <!-- Find Best Trade -->
    <library name="GT_FindBestTrade">
      <params>
        <param name="ship" comment="Ship to find trade for"/>
        <param name="warebasket" comment="List of allowed wares"/>
      </params>
      <actions>
        <set_value name="$return" exact="null"/>
        <set_value name="$bestProfit" exact="0"/>
        
        <!-- Find buy offers -->
        <!-- CRITICAL: Include tradepartner to respect trade rules (e.g., "internal only") -->
        <find_buy_offer space="player.galaxy" tradepartner="this.ship" result="$buyoffers" multiple="true">
          <match_buyer tradesknownto="@this.owner"/>
          <match_seller tradesknownto="@this.owner"/>
        </find_buy_offer>
        
        <!-- Evaluate trades -->
        <do_all exact="[$buyoffers.count, 20].min" counter="$i">
          <set_value name="$buyoffer" exact="$buyoffers.{$i}"/>
          
          <!-- Check if ware is in basket using explicit loop (indexof unreliable for lists) -->
          <set_value name="$wareInBasket" exact="false"/>
          <do_all exact="$warebasket.count" counter="$k">
            <do_if value="$warebasket.{$k} == $buyoffer.ware">
              <set_value name="$wareInBasket" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          
          <do_if value="$wareInBasket">
            <!-- Find sell offers -->
            <!-- CRITICAL: Include tradepartner to respect trade rules (e.g., "internal only") -->
            <find_sell_offer buyer="$buyoffer.buyer" wares="$buyoffer.ware" tradepartner="this.ship" result="$selloffer">
              <match_seller tradesknownto="@this.owner"/>
            </find_sell_offer>
            
            <do_if value="$selloffer">
              <!-- Calculate profit -->
              <set_value name="$amount" exact="[this.ship.cargo.{$buyoffer.ware}.free, $buyoffer.amount, $selloffer.amount].min"/>
              <do_if value="$amount gt 0">
                <set_value name="$profit" exact="($selloffer.unitprice - $buyoffer.unitprice) * $amount"/>
                
                <!-- Check ROI and absolute profit thresholds -->
                <set_value name="$minROI" exact="@global.$GT_Config.$Trading.$MinROI"/>
                <do_if value="not $minROI">
                  <set_value name="$minROI" exact="0.10"/>
                </do_if>
                
                <set_value name="$minAbsoluteProfit" exact="@global.$GT_Config.$Trading.$MinAbsoluteProfit"/>
                <do_if value="not $minAbsoluteProfit">
                  <set_value name="$minAbsoluteProfit" exact="10000"/> <!-- 100 Cr in RAW format -->
                </do_if>
                
                <!-- Calculate ROI -->
                <set_value name="$investment" exact="$buyoffer.unitprice * $amount"/>
                <set_value name="$roi" exact="if $investment gt 0 then (($profit * 100.0) / $investment) else 0.0"/>
                
                <do_if value="$roi ge ($minROI * 100) and $profit ge $minAbsoluteProfit and $profit gt $bestProfit">
                  <set_value name="$bestProfit" exact="$profit"/>
                  <set_value name="$return" exact="$buyoffer"/>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_all>
      </actions>
    </library>
    
    <!-- Analyze Route Threat -->
    <library name="GT_AnalyzeRouteThreat" purpose="run_actions">
      <params>
        <param name="buyStation" comment="Station to buy from"/>
        <param name="sellStation" comment="Station to sell to"/>
        <param name="ship" comment="Ship for context"/>
      </params>
      <actions>
        <!-- Initialize return table -->
        <set_value name="$return" exact="table[]"/>
        <set_value name="$return.$MaxThreat" exact="0"/>
        <set_value name="$return.$TotalThreatScore" exact="0"/>
        <set_value name="$return.$ThreatSectors" exact="[]"/>
        <set_value name="$return.$SectorCount" exact="0"/>
        
        <!-- Check if threat avoidance is enabled -->
        <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance? or not global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled">
          <return value="$return"/>
        </do_if>
        
        <!-- Check if dynamic blacklist is enabled (required for blacklist-aware pathfinding) -->
        <set_value name="$useDynamicBlacklist" exact="false"/>
        <do_if value="global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist?">
          <set_value name="$useDynamicBlacklist" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist"/>
        </do_if>
        
        <!-- Get threat expiry time -->
        <set_value name="$threatExpiry" exact="if global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry? then global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry else 600s"/>
        
        <!-- Build list of sectors to check: buy sector and sell sector -->
        <set_value name="$sectorsToCheck" exact="[]"/>
        
        <!-- Add buy station sector -->
        <append_to_list name="$sectorsToCheck" exact="$buyStation.sector"/>
        
        <!-- Add sell station sector if different -->
        <do_if value="$sellStation.sector != $buyStation.sector">
          <append_to_list name="$sectorsToCheck" exact="$sellStation.sector"/>
        </do_if>
        
        <!-- Check if preferred route goes through threatened sectors -->
        <!-- Compare normal vs blacklist-aware gatedistance to detect threats in path (only if dynamic blacklist enabled) -->
        <do_if value="$ship? and $sellStation.sector != $buyStation.sector and $useDynamicBlacklist">
          <!-- Extract sectors before gatedistance calculation (property chains in curly braces can fail) -->
          <set_value name="$sellSector" exact="@$sellStation.sector"/>
          <do_if value="$sellSector?">
            <!-- Calculate distance from ship to sell station WITHOUT blacklist (preferred path) -->
            <set_value name="$normalDistance" exact="$ship.gatedistance.{$sellSector}"/>
            
            <!-- Calculate distance WITH blacklist (avoiding threats) -->
            <!-- Vanilla pattern: order.dock.xml:503 -->
            <set_value name="$blacklistDistance" exact="$ship.gatedistance.{$sellSector}.{blacklistgroup.civilian}.{$ship}"/>
          </do_if>
          <do_else>
            <!-- Sector extraction failed - skip threat check -->
            <set_value name="$normalDistance" exact="-1"/>
            <set_value name="$blacklistDistance" exact="-1"/>
          </do_else>
          
          <!-- If blacklist distance > normal, preferred path goes through threat! -->
          <!-- Apply heavy penalty to discourage this route -->
          <do_if value="($normalDistance ge 0) and ($blacklistDistance gt $normalDistance or $blacklistDistance lt 0)">
            <!-- Route goes through threatened sector(s) - apply heavy threat penalty -->
            <set_value name="$return.$MaxThreat" exact="5"/>
            <set_value name="$return.$TotalThreatScore" exact="10"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Route analysis: Preferred path threatened (normal: %s, blacklist: %s) - heavy penalty applied'.[$normalDistance, $blacklistDistance]" chance="0"/>
            </do_if>
          </do_if>
        </do_if>
        
        <set_value name="$return.$SectorCount" exact="$sectorsToCheck.count"/>
        
        <!-- Check threat level for each sector -->
        <do_all exact="$sectorsToCheck.count" counter="$i">
          <set_value name="$sector" exact="$sectorsToCheck.{$i}"/>
          
          <!-- Check if we have threat data for this sector -->
          <do_if value="global.$GT_ThreatIntelligence.{$sector}?">
            <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$sector}"/>
            
            <!-- Check if threat data is still valid (not expired) -->
            <do_if value="$threatData.$Timestamp?">
              <set_value name="$age" exact="player.age - $threatData.$Timestamp"/>
              
              <do_if value="$age le $threatExpiry">
                <set_value name="$threatLevel" exact="@$threatData.$ThreatLevel"/>
                
                <do_if value="$threatLevel?">
                  <!-- Update max threat -->
                  <do_if value="$threatLevel gt $return.$MaxThreat">
                    <set_value name="$return.$MaxThreat" exact="$threatLevel"/>
                  </do_if>
                  
                  <!-- Add to total threat score -->
                  <set_value name="$return.$TotalThreatScore" exact="$return.$TotalThreatScore + $threatLevel"/>
                  
                  <!-- Add sector to threat list if threat level > 1 -->
                  <do_if value="$threatLevel gt 1">
                    <set_value name="$threatSectorInfo" exact="table[]"/>
                    <set_value name="$threatSectorInfo.$Sector" exact="$sector"/>
                    <set_value name="$threatSectorInfo.$ThreatLevel" exact="$threatLevel"/>
                    <set_value name="$threatSectorInfo.$HostileCount" exact="@$threatData.$HostileCount"/>
                    <append_to_list name="$return.$ThreatSectors" exact="$threatSectorInfo"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
        </do_all>
        
        <!-- Calculate average threat -->
        <set_value name="$return.$AverageThreat" exact="if $return.$SectorCount gt 0 then ($return.$TotalThreatScore / $return.$SectorCount) else 0"/>
        
        <!-- Return threat analysis result -->
        <return value="$return"/>
      </actions>
    </library>
    
    <!-- Validate Table Safe (null-checking pattern) -->
    <library name="GT_ValidateTableSafe" purpose="run_actions">
      <params>
        <param name="table" comment="Table to validate (may be null)"/>
      </params>
      <actions>
        <!-- CRITICAL: X4 MD null-checking pattern -->
        <!-- null? = true, so we check if .keys.count exists and is >= 0 -->
        <set_value name="$keysCheck" exact="@$table.keys"/>
        <set_value name="$countCheck" exact="@$keysCheck.count"/>
        <do_if value="$table? and $keysCheck? and $countCheck? and $countCheck ge 0">
          <return value="$table"/>
        </do_if>
        <!-- Return empty table if invalid -->
        <return value="table[]"/>
      </actions>
    </library>

<!-- Initialize AI Script Configuration -->
    <library name="Initialize_AI_Script">
      <params>
        <param name="ship" comment="Ship being initialized"/>
        <param name="order_params" comment="Order parameters"/>
      </params>
      <actions>
        <!-- Create configuration using the Configuration Manager -->
        <run_actions ref="md.GT_Configuration.Create_Ship_Config" result="$shipConfig">
          <param name="order_params" value="$order_params"/>
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Register ship and pilot -->
        <do_if value="$ship.pilot">
          <run_actions ref="md.GT_Ship_Management.Register_Ship">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$ship.pilot"/>
            <param name="config" value="$shipConfig"/>
          </run_actions>
        </do_if>
        
        <!-- Return the configuration for use in the AI script -->
        <set_value name="this.$result" exact="$shipConfig"/>
      </actions>
    </library>
    
    <!-- Validate Runtime Parameters -->
    <library name="Validate_Runtime_Parameters" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to validate"/>
        <param name="config" comment="Ship configuration"/>
      </params>
      <actions>
        <set_value name="$validationResult" exact="table[]"/>
        <set_value name="$isValid" exact="true"/>
        <create_list name="$warnings"/>
        <create_list name="$corrections"/>
        
        <!-- Get current skill level -->
        <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level" result="$skillInfo">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Calculate skill-based jump distance -->
        <run_actions ref="md.GT_Ship_Management.Calculate_Jump_Distance" result="$skillMaxDistance">
          <param name="skill_level" value="$skillInfo.$Level"/>
        </run_actions>
        
        <!-- Check if pilot is training-gated -->
        <set_value name="$pilotXPBlocked" exact="false"/>
        <do_if value="$ship.pilot and global.$GT_Pilots.{$ship.pilot}?">
          <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$trainingGate">
            <param name="pilot" value="$ship.pilot"/>
            <param name="ship" value="$ship"/>
            <param name="respect_hard_force" value="true"/>
          </run_actions>
          <set_value name="$pilotXPBlocked" exact="$trainingGate.$MustTrainNow"/>
        </do_if>
        
        <!-- Validate and correct MaxBuy distance -->
        <do_if value="not $pilotXPBlocked and $config.$MaxBuy gt $skillMaxDistance">
          <append_to_list name="$warnings" exact="'MaxBuy (' + $config.$MaxBuy + ') exceeds skill limit (' + $skillMaxDistance + ')'"/>
          <append_to_list name="$corrections" exact="'MaxBuy corrected to ' + $skillMaxDistance"/>
          <set_value name="$config.$MaxBuy" exact="$skillMaxDistance"/>
          <set_value name="$config.$MaxBuyDistance" exact="$skillMaxDistance"/>
        </do_if>
        
        <!-- Validate and correct MaxSell distance -->
        <do_if value="not $pilotXPBlocked and $config.$MaxSell gt $skillMaxDistance">
          <append_to_list name="$warnings" exact="'MaxSell (' + $config.$MaxSell + ') exceeds skill limit (' + $skillMaxDistance + ')'"/>
          <append_to_list name="$corrections" exact="'MaxSell corrected to ' + $skillMaxDistance"/>
          <set_value name="$config.$MaxSell" exact="$skillMaxDistance"/>
          <set_value name="$config.$MaxSellDistance" exact="$skillMaxDistance"/>
        </do_if>
        
        <!-- Store validation results -->
        <set_value name="$validationResult.$IsValid" exact="$isValid"/>
        <set_value name="$validationResult.$Warnings" exact="$warnings"/>
        <set_value name="$validationResult.$Corrections" exact="$corrections"/>
        <set_value name="$validationResult.$SkillInfo" exact="$skillInfo"/>
        <set_value name="$validationResult.$SkillMaxDistance" exact="$skillMaxDistance"/>
        <set_value name="$validationResult.$PilotXPBlocked" exact="$pilotXPBlocked"/>
        
        <set_value name="this.$result" exact="$validationResult"/>
      </actions>
    </library>
    
    <!-- Handle Fleet Coordination -->
    <library name="Handle_Fleet_Coordination" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship joining fleet"/>
        <param name="config" comment="Ship configuration"/>
      </params>
      <actions>
        <set_value name="$fleetResult" exact="table[]"/>
        <set_value name="$startupDelay" exact="0"/>
        <set_value name="$isSubordinate" exact="false"/>
        
        <!-- Check if fleet coordination is enabled AND pilot level gate passed (>= 12) -->
        <do_if value="$config.$FleetCoordination">
          <set_value name="$fleetGatePassed" exact="false"/>
          <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level" result="$skillInfo">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$skillInfo? and $skillInfo.$Level? and $skillInfo.$Level ge 12">
            <set_value name="$fleetGatePassed" exact="true"/>
          </do_if>
          
          <!-- Only apply coordination delay if gate passed -->
          <do_if value="$fleetGatePassed">
          <!-- OPTIMIZED: Use cached active trader count instead of expensive O(n) loop -->
          <!-- Cache is maintained incrementally during ship registration/unregistration -->
          <set_value name="$activeTraders" exact="0"/>
          <do_if value="global.$GT_ActiveTraderCount?">
            <set_value name="$activeTraders" exact="global.$GT_ActiveTraderCount"/>
          </do_if>
          <do_else>
            <!-- Fallback: Cache not initialized - count manually (shouldn't happen, but safe) -->
            <set_value name="$activeTraders" exact="0"/>
            <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
              <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
              <do_all exact="$shipKeys.count" counter="$i">
                <set_value name="$existingShip" exact="$shipKeys.{$i}"/>
                <do_if value="$existingShip.exists and $existingShip.isoperational and $existingShip != $ship">
                  <set_value name="$activeTraders" exact="$activeTraders + 1"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- Initialize cache with counted value -->
            <set_value name="global.$GT_ActiveTraderCount" exact="$activeTraders"/>
          </do_else>
          
          <!-- Apply fleet coordination delay -->
          <do_if value="$activeTraders gt 0">
            <set_value name="$startupDelay" exact="[$activeTraders * 5, 30].min"/>
            <set_value name="$isSubordinate" exact="true"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + $ship.idcode + ': Fleet coordination: delaying startup for ' + $startupDelay + 's (found ' + $activeTraders + ' active traders, cached)'" chance="100"/>
            </do_if>
          </do_if>
          </do_if>
          <do_if value="not $fleetGatePassed">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + $ship.idcode + ': Fleet coordination gated by level (requires 12), current=' + (if @$skillInfo.$Level != null then @$skillInfo.$Level else 1)" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Fleet coordination disabled - skip expensive count (Option 2: Skip if disabled) -->
          <set_value name="$activeTraders" exact="0"/>
        </do_else>
        
        <!-- Store results -->
        <set_value name="$fleetResult.$StartupDelay" exact="$startupDelay"/>
        <set_value name="$fleetResult.$IsSubordinate" exact="$isSubordinate"/>
        <set_value name="$fleetResult.$ActiveTraders" exact="$activeTraders"/>
        
        <set_value name="this.$result" exact="$fleetResult"/>
      </actions>
    </library>
    
    <!-- Check Training Requirements -->
    <library name="Check_Training_Requirements" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
        <param name="pilot" comment="Pilot to check"/>
        <param name="config" comment="Ship configuration"/>
      </params>
      <actions>
        <set_value name="$trainingResult" exact="table[]"/>
        <set_value name="$needsTraining" exact="false"/>
        <set_value name="$trainingAction" exact="'none'"/>
        
        <!-- Only check if auto-training is enabled -->
        <do_if value="$config.$AutoTraining and $pilot">
          <!-- Check training requirements using XP system -->
          <set_value name="$trainingStatus" exact="table[$Required = false, $Level = 1, $IsBlocked = false]"/>
          <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
            <set_value name="$currentLevel" exact="@global.$GT_Pilots.{$pilot}.$Level"/>
            <do_if value="not $currentLevel">
              <set_value name="$currentLevel" exact="1"/>
            </do_if>
            
            <!-- Check if training is beneficial (level < 5) -->
            <do_if value="$currentLevel lt 5">
              <set_value name="$trainingStatus.$Required" exact="true"/>
              <set_value name="$trainingStatus.$Level" exact="$currentLevel + 1"/>
            </do_if>
          </do_if>
          
          <set_value name="$needsTraining" exact="$trainingStatus.$Required"/>
          
          <do_if value="$needsTraining">
            <!-- Find training station -->
            <set_value name="$stationResult" exact="table[$Found = false, $Station = null]"/>
            <find_station name="$nearestStation" space="$ship.zone">
              <match class="class.station"/>
            </find_station>
            <do_if value="$nearestStation">
              <set_value name="$stationResult.$Found" exact="true"/>
              <set_value name="$stationResult.$Station" exact="$nearestStation"/>
            </do_if>
            
            <do_if value="$stationResult.$Found">
              <set_value name="$trainingAction" exact="'start_training'"/>
              <set_value name="$trainingResult.$TrainingStation" exact="$stationResult.$Station"/>
              <set_value name="$trainingResult.$RequiredLevel" exact="$trainingStatus.$Level"/>
            </do_if>
            <do_else>
              <set_value name="$trainingAction" exact="'no_station'"/>
            </do_else>
          </do_if>
          <do_elseif value="$trainingStatus.$IsBlocked">
            <!-- Pilot is blocked but no training needed - this shouldn't happen -->
            <set_value name="$trainingAction" exact="'clear_block'"/>
          </do_elseif>
        </do_if>
        
        <!-- Store results -->
        <set_value name="$trainingResult.$NeedsTraining" exact="$needsTraining"/>
        <set_value name="$trainingResult.$Action" exact="$trainingAction"/>
        <set_value name="$trainingResult.$TrainingStatus" exact="@$trainingStatus"/>
        
        <set_value name="this.$result" exact="$trainingResult"/>
      </actions>
    </library>
    
    <!-- Extract Configuration Variables for AI Script Compatibility -->
    <library name="Extract_Config_Variables" purpose="run_actions">
      <params>
        <param name="config" comment="Ship configuration"/>
      </params>
      <actions>
        <!-- Extract all configuration values into individual variables for backward compatibility -->
        <set_value name="$variables" exact="table[]"/>
        
        <!-- Basic trading settings -->
        <set_value name="$variables.$gt_allowillegal" exact="$config.$AllowIllegal"/>
        <set_value name="$variables.$gt_enforceRouteIllegalLegality" exact="if $config.$EnforceRouteIllegalLegality? then $config.$EnforceRouteIllegalLegality else false"/>
        <set_value name="$variables.$gt_distancepenalty" exact="$config.$DistancePenalty"/>
        <set_value name="$variables.$gt_cargotarget" exact="$config.$CargoTarget"/>
        <set_value name="$variables.$gt_marketupdatefreq" exact="$config.$MarketUpdateFreq"/>
        
        <!-- System settings -->
        <set_value name="$variables.$gt_autotraining" exact="$config.$AutoTraining"/>
        <set_value name="$variables.$gt_fleetcoord" exact="$config.$FleetCoordination"/>
        <!-- Cache settings (TradeCache, CacheThreshold, CacheTTL, CacheDropoff) read directly from globals by AI scripts -->
        <set_value name="$variables.$gt_debuglevel" exact="$config.$DebugLevel"/>
        
        <!-- Jump distances -->
        <set_value name="$variables.$maxbuy" exact="$config.$MaxBuyDistance"/>
        <set_value name="$variables.$maxsell" exact="$config.$MaxSellDistance"/>
        
        <!-- Ware settings -->
        <set_value name="$variables.$warebasket" exact="$config.$WareBasket"/>
        <set_value name="$variables.$gt_notifications" exact="$config.$Notifications"/>
        <set_value name="$variables.$gt_tradeeval" exact="$config.$TradeEval"/>
        
        <!-- Debug settings -->
        <set_value name="$variables.$debugchance" exact="100"/>
        
        <set_value name="this.$result" exact="$variables"/>
      </actions>
    </library>
    
    <!-- Log Configuration Summary -->
    <library name="Log_Configuration_Summary">
      <params>
        <param name="ship" comment="Ship being configured"/>
        <param name="config" comment="Ship configuration"/>
        <param name="debug_level" default="1" comment="Minimum debug level to log"/>
      </params>
      <actions>
        <do_if value="$config.$DebugLevel ge $debug_level and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AI] ' + $ship.idcode + ': === CONFIGURATION SUMMARY ==='" chance="100"/>
          <debug_text text="'[GT-AI] ' + $ship.idcode + ': Illegal=' + $config.$AllowIllegal + ', DistancePenalty=' + $config.$DistancePenalty + '%'" chance="100"/>
          <debug_text text="'[GT-AI] ' + $ship.idcode + ': AutoTraining=' + $config.$AutoTraining + ', Fleet=' + $config.$FleetCoordination" chance="100"/>
          <debug_text text="'[GT-AI] ' + $ship.idcode + ': Distance limits: MaxBuy=' + $config.$MaxBuyDistance + ' jumps, MaxSell=' + $config.$MaxSellDistance + ' jumps'" chance="100"/>
          <debug_text text="'[GT-AI] ' + $ship.idcode + ': Ware basket: ' + $config.$WareBasket.count + ' wares configured (AutoWares=' + $config.$AutoWares + ')'" chance="100"/>
          
          <!-- Log skill information if available -->
          <do_if value="$config.$SkillInfo?">
            <debug_text text="'[GT-AI] ' + $ship.idcode + ': Skill Level=' + $config.$SkillInfo.$Level + ', Using MD System=' + $config.$SkillInfo.$UsingMDSystem" chance="100"/>
          </do_if>
        </do_if>
        
        <set_value name="this.$result" exact="true"/>
      </actions>
    </library>
    
    <!-- Handle Order Parameter Updates -->
    <library name="Update_Order_Parameters">
      <params>
        <param name="ship" comment="Ship with order to update"/>
        <param name="config" comment="Current configuration"/>
        <param name="pilot_xp_blocked" default="false" comment="Whether pilot is XP blocked"/>
      </params>
      <actions>
        <!-- Only update order parameters if pilot is not XP blocked to prevent restart loops -->
        <do_if value="not $pilot_xp_blocked and $ship.order?">
          <!-- Update MaxBuy parameter if corrected -->
          <do_if value="$config.$MaxBuy != $config.$MaxBuyDistance">
            <edit_order_param order="$ship.order" param="'maxbuy'" value="$config.$MaxBuyDistance"/>
          </do_if>
          
          <!-- Update MaxSell parameter if corrected -->
          <do_if value="$config.$MaxSell != $config.$MaxSellDistance">
            <edit_order_param order="$ship.order" param="'maxsell'" value="$config.$MaxSellDistance"/>
          </do_if>
        </do_if>
        
        <set_value name="this.$result" exact="true"/>
      </actions>
    </library>
    
    <!-- Clean Up Stale Flags -->
    <library name="Cleanup_Stale_Flags">
      <params>
        <param name="ship" comment="Ship to clean up"/>
      </params>
      <actions>
        <!-- Clear stale predictive training flags -->
        <do_if value="$ship.$TrainingRequiredAfterThisTrade?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-AI] ' + $ship.idcode + ': Clearing stale predictive training flag'" chance="100"/>
          </do_if>
          <remove_value name="$ship.$TrainingRequiredAfterThisTrade"/>
        </do_if>
        
        <!-- Clear stale training in progress flags (older than 5 minutes) -->
        <do_if value="$ship.$TrainingInProgress? and $ship.$TrainingStartTime?">
          <do_if value="(player.age - $ship.$TrainingStartTime) gt 300s">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] ' + $ship.idcode + ': Clearing stale training-in-progress flag (older than 5 minutes)'" chance="100"/>
            </do_if>
            <remove_value name="$ship.$TrainingInProgress"/>
            <remove_value name="$ship.$TrainingStartTime"/>
          </do_if>
        </do_if>
        
        <set_value name="this.$result" exact="true"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- NUMBER FORMATTING UTILITIES -->
    <!-- ========================================= -->
    
    <!-- Format Number with Thousand Separators and M Suffix -->
    <!-- Formats numbers according to global settings: thousand separator, decimal separator, M suffix threshold -->
    <library name="GT_FormatNumber" purpose="run_actions">
      <params>
        <param name="number" comment="Number to format (in credits, not RAW format)"/>
        <param name="suffix" default="' Cr'" comment="Suffix to append (default: ' Cr')"/>
      </params>
      <actions>
        <!-- Get formatting settings from global config -->
        <set_value name="$format" exact="if global.$GT_GlobalSettings.$NumberFormat.$Format? then global.$GT_GlobalSettings.$NumberFormat.$Format else 'german'"/>
        <!-- Set separators based on format choice -->
        <set_value name="$thousandSep" exact="if $format == 'german' then '.' else ','"/>
        <set_value name="$decimalSep" exact="if $format == 'german' then ',' else '.'"/>
        <set_value name="$useMSuffix" exact="if global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix? then global.$GT_GlobalSettings.$NumberFormat.$UseMSuffix else true"/>
        <set_value name="$mThreshold" exact="if global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold? then global.$GT_GlobalSettings.$NumberFormat.$MSuffixThreshold else 999999"/>
        
        <!-- Handle negative numbers -->
        <set_value name="$isNegative" exact="false"/>
        <set_value name="$absNumber" exact="$number"/>
        <do_if value="$number lt 0">
          <set_value name="$isNegative" exact="true"/>
          <set_value name="$absNumber" exact="-$number"/>
        </do_if>
        
        <!-- Check if we should use M suffix -->
        <set_value name="$useM" exact="false"/>
        <do_if value="$useMSuffix and $absNumber gt $mThreshold">
          <set_value name="$useM" exact="true"/>
        </do_if>
        
        <!-- Format the number -->
        <set_value name="$formatted" exact="''"/>
        <do_if value="$useM">
          <!-- Format as M suffix: e.g., "1,0 M" or "1.0 M" -->
          <!-- Use integer arithmetic: calculate value in tenths of millions, then round to nearest tenth -->
          <!-- Example: 1500000 -> 15 tenths -> 1.5 M -->
          <!-- Example: 1550000 -> 15.5 tenths -> round to 16 tenths -> 1.6 M -->
          <!-- Calculate value in hundredths for rounding precision -->
          <set_value name="$mValueTimes100" exact="($absNumber * 100) / 1000000"/>
          <!-- Round to nearest tenth: add 5 hundredths, then divide by 10 to get rounded tenths -->
          <set_value name="$mRoundedTimes10" exact="($mValueTimes100 + 5) / 10"/>
          <!-- Extract integer part (millions) -->
          <set_value name="$mInt" exact="$mRoundedTimes10 / 10"/>
          <!-- Extract decimal part (tenths) -->
          <set_value name="$mDec" exact="$mRoundedTimes10 - ($mInt * 10)"/>
          
          <!-- Build formatted string: "1,0" or "1.0" -->
          <set_value name="$mStr" exact="$mInt + ''"/>
          <do_if value="$mDec gt 0">
            <set_value name="$mStr" exact="$mStr + $decimalSep + $mDec"/>
          </do_if>
          <do_else>
            <!-- Always show at least one decimal: "1,0" or "1.0" -->
            <set_value name="$mStr" exact="$mStr + $decimalSep + '0'"/>
          </do_else>
          
          <set_value name="$formatted" exact="$mStr + ' M'"/>
        </do_if>
        <do_else>
          <!-- Format with thousand separators: e.g., "123.456" or "123,456" -->
          <!-- Use integer arithmetic to extract digits (more reliable than string operations) -->
          <set_value name="$result" exact="''"/>
          <set_value name="$remaining" exact="$absNumber"/>
          <set_value name="$digitCount" exact="0"/>
          
          <!-- Handle zero case -->
          <do_if value="$remaining == 0">
            <set_value name="$formatted" exact="'0'"/>
          </do_if>
          <do_else>
            <!-- Extract digits from right to left using integer arithmetic (no mod operator) -->
            <do_while value="$remaining gt 0">
              <!-- Get last digit using integer arithmetic: remaining - (remaining / 10) * 10 -->
              <set_value name="$digit" exact="$remaining - ($remaining / 10) * 10"/>
              <set_value name="$remaining" exact="$remaining / 10"/>
              
              <!-- Insert thousand separator every 3 digits (but not before first digit) -->
              <!-- Check if digitCount is divisible by 3 using integer arithmetic -->
              <set_value name="$digitCountDiv3" exact="$digitCount / 3"/>
              <set_value name="$digitCountMod3" exact="$digitCount - ($digitCountDiv3 * 3)"/>
              <do_if value="$digitCount gt 0 and $digitCountMod3 == 0">
                <set_value name="$result" exact="$thousandSep + $result"/>
              </do_if>
              
              <!-- Prepend digit to result -->
              <set_value name="$result" exact="$digit + $result"/>
              <set_value name="$digitCount" exact="$digitCount + 1"/>
            </do_while>
            
            <set_value name="$formatted" exact="$result"/>
          </do_else>
        </do_else>
        
        <!-- Add negative sign if needed -->
        <do_if value="$isNegative">
          <set_value name="$formatted" exact="'-' + $formatted"/>
        </do_if>
        
        <!-- Add suffix -->
        <set_value name="$formatted" exact="$formatted + $suffix"/>
        
        <!-- Return formatted string -->
        <return value="$formatted"/>
      </actions>
    </library>

    <!-- Format station as "Sector - Stationname(IDCODE)" for logbook/tradequeue messages -->
    <library name="GT_FormatStationLocation" purpose="run_actions">
      <params>
        <param name="station" comment="Station object to format"/>
      </params>
      <actions>
        <set_value name="$formatted" exact="'Unknown'"/>
        <do_if value="$station? and $station.exists">
          <set_value name="$sectorName" exact="if $station.sector? and $station.sector.exists then @$station.sector.knownname else '?'"/>
          <set_value name="$stationName" exact="if $station.knownname? then @$station.knownname else '?'"/>
          <set_value name="$stationId" exact="if $station.idcode? then @$station.idcode else '?'"/>
          <set_value name="$formatted" exact="$sectorName + ' - ' + $stationName + '(' + $stationId + ')'"/>
        </do_if>
        <return value="$formatted"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- TRAINING GATE UTILITIES -->
    <!-- ========================================= -->
    
    <!-- Unified training/XP gate decision -->
    <library name="GT_GetTrainingGate" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to evaluate"/>
        <param name="ship" default="null" comment="Optional ship (for diagnostics only)"/>
        <param name="respect_hard_force" default="true" comment="Whether BlockedLevel enforces mandatory training"/>
      </params>
      <actions>
        <set_value name="$gate" exact="table[
          $MustTrainNow = false,
          $CanTrade = true,
          $XPGainBlocked = false,
          $XPBlocked = false,
          $BlockedLevel = 0,
          $HardForce = true,
          $Reason = 'none'
        ]"/>
        
        <!-- Default hard-force behavior is enabled unless explicitly disabled -->
        <set_value name="$hardForceTraining" exact="true"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
          <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
        </do_if>
        <do_if value="not $respect_hard_force">
          <set_value name="$hardForceTraining" exact="false"/>
        </do_if>
        <set_value name="$gate.$HardForce" exact="$hardForceTraining"/>
        
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="$isExplorerContext" exact="false"/>
          <do_if value="$ship? and $ship.exists and $ship.defaultorder?">
            <set_value name="$orderId" exact="@$ship.defaultorder.id"/>
            <set_value name="$baseOrderId" exact="if $ship.defaultorder.$baseorder? then @$ship.defaultorder.$baseorder.id else null"/>
            <do_if value="$orderId == 'GalaxyExplorer' or ($orderId == 'Assist' and $baseOrderId == 'GalaxyExplorer')">
              <set_value name="$isExplorerContext" exact="true"/>
            </do_if>
          </do_if>

          <!-- Explorer exemption: no XP blocking and no mandatory training gates. -->
          <do_if value="$isExplorerContext">
            <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'active'"/>

            <set_value name="$gate.$XPBlocked" exact="false"/>
            <set_value name="$gate.$BlockedLevel" exact="0"/>
            <set_value name="$gate.$XPGainBlocked" exact="false"/>
            <set_value name="$gate.$MustTrainNow" exact="false"/>
            <set_value name="$gate.$CanTrade" exact="true"/>
            <set_value name="$gate.$Reason" exact="'explorer_exempt'"/>

            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP-Guard] Explorer exemption applied for pilot ' + $pilot.name + ' on ship ' + (if $ship? and $ship.exists then $ship.idcode else 'UNKNOWN')" chance="100"/>
            </do_if>
            <return value="$gate"/>
          </do_if>

          <set_value name="$xpBlockedFlag" exact="global.$GT_Pilots.{$pilot}.$XPBlocked?"/>
          <set_value name="$pausedWithTrainingNeeded" exact="global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded?"/>
          <set_value name="$blockedLevel" exact="0"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$BlockedLevel?">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          </do_if>
          
          <set_value name="$xpGainBlocked" exact="$xpBlockedFlag or $blockedLevel gt 1"/>
          <set_value name="$mustTrainNow" exact="$pausedWithTrainingNeeded or $xpBlockedFlag or ($hardForceTraining and $blockedLevel gt 1)"/>
          
          <set_value name="$gate.$XPBlocked" exact="$xpBlockedFlag"/>
          <set_value name="$gate.$BlockedLevel" exact="$blockedLevel"/>
          <set_value name="$gate.$XPGainBlocked" exact="$xpGainBlocked"/>
          <set_value name="$gate.$MustTrainNow" exact="$mustTrainNow"/>
          <set_value name="$gate.$CanTrade" exact="not $mustTrainNow"/>
          
          <set_value name="$reason" exact="'none'"/>
          <do_if value="$pausedWithTrainingNeeded">
            <set_value name="$reason" exact="'paused_training_needed'"/>
          </do_if>
          <do_elseif value="$xpBlockedFlag">
            <set_value name="$reason" exact="'xp_blocked'"/>
          </do_elseif>
          <do_elseif value="$hardForceTraining and $blockedLevel gt 1">
            <set_value name="$reason" exact="'hard_force_blocked_level'"/>
          </do_elseif>
          <do_elseif value="$blockedLevel gt 1">
            <set_value name="$reason" exact="'xp_blocked_only_blocked_level'"/>
          </do_elseif>
          <set_value name="$gate.$Reason" exact="$reason"/>
        </do_if>
        <do_else>
          <set_value name="$gate.$Reason" exact="'pilot_missing_or_unregistered'"/>
        </do_else>
        
        <return value="$gate"/>
      </actions>
    </library>
    
    <!-- Diagnose: list training station candidates using the same filters as auto-training (gt_xp_training HandleCheckTrainingRequired). -->
    <library name="GT_DiagnoseTrainingStationCandidates" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship used for path/blacklist/dock checks"/>
        <param name="maxFailureRows" default="30" comment="Max rejected stations to list as samples"/>
      </params>
      <actions>
        <create_list name="$rows"/>
        <create_list name="$eligibleRows"/>
        <create_list name="$failRows"/>
        <set_value name="$eligibleCount" exact="0"/>
        <set_value name="$failureCount" exact="0"/>
        
        <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <set_value name="$candidateCount" exact="0"/>
        <set_value name="$tradingPosts" exact="null"/>
        <do_if value="$ship? and $ship.exists">
          <find_station name="$tradingPosts" space="player.galaxy" multiple="true" tradestation="true" tradesknownto="faction.player">
            <match class="[class.station]"/>
            <match owner="[faction.player]" negate="true"/>
            <match owner="[faction.xenon, faction.khaak, faction.yaki]" negate="true"/>
            <match_relation_to object="$ship" relation="dock" comparison="ge"/>
          </find_station>
          <do_if value="$tradingPosts? and $tradingPosts.count?">
            <set_value name="$candidateCount" exact="$tradingPosts.count"/>
          </do_if>
        </do_if>
        
        <append_to_list name="$rows" exact="table[
          $Check = 'Training search summary',
          $Status = 'INFO',
          $Detail = 'Candidates=' + $candidateCount + '. Filters match auto-training: reachable, blacklist, dock bay, docking permission, ValidStationTypes macro (no pilot jump cap; nearest eligible wins).'
        ]"/>
        
        <do_if value="not $ship? or not $ship.exists or not $ship.sector?">
          <append_to_list name="$rows" exact="table[$Check = 'Training stations', $Status = 'WARN', $Detail = 'Ship or sector invalid; cannot evaluate path.']"/>
        </do_if>
        <do_elseif value="$candidateCount == 0">
          <append_to_list name="$rows" exact="table[$Check = 'Training stations', $Status = 'WARN', $Detail = 'find_station returned 0 trading posts (player trade knowledge, relations, or filters).']"/>
        </do_elseif>
        <do_else>
          <do_all exact="$tradingPosts.count" counter="$i">
            <set_value name="$station" exact="$tradingPosts.{$i}"/>
            <set_value name="$isValid" exact="true"/>
            <set_value name="$failReason" exact="''"/>
            <set_value name="$gateDistance" exact="-1"/>
            
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$isReachable">
              <param name="ship" value="$ship"/>
              <param name="station" value="$station"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="returnDetails" value="false"/>
            </run_actions>
            <do_if value="not $isReachable">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$failReason" exact="'Not reachable (station unknown or no path)'"/>
            </do_if>
            
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$gateDistance">
                <param name="ship" value="$ship"/>
                <param name="fromSector" value="$ship.sector"/>
                <param name="toSector" value="$station.sector"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="useEscapeMode" value="false"/>
              </run_actions>
            </do_if>
            
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$stationBlacklisted">
                <param name="station" value="$station"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$sectorBlacklistDetails">
                <param name="sector" value="$station.sector"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="returnDetails" value="true"/>
              </run_actions>
              <set_value name="$sectorTravelBlacklisted" exact="$sectorBlacklistDetails.$TravelBlacklisted"/>
              <set_value name="$sectorActivityBlacklisted" exact="$sectorBlacklistDetails.$ActivityBlacklisted"/>
              <do_if value="$stationBlacklisted or $sectorTravelBlacklisted or $sectorActivityBlacklisted">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$failReason" exact="'Blacklist: station=' + $stationBlacklisted + ', sector travel=' + $sectorTravelBlacklisted + ', sector activity=' + $sectorActivityBlacklisted"/>
              </do_if>
            </do_if>
            
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$trainListDockResult">
                <param name="station" value="$station"/>
                <param name="ship" value="$ship"/>
                <param name="purpose" value="'dual'"/>
              </run_actions>
              <do_if value="not $trainListDockResult.$CanDock">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$failReason" exact="'Dock preflight failed: ' + $trainListDockResult.$Reason"/>
              </do_if>
            </do_if>
            
            <do_if value="$isValid">
              <set_value name="$validMacro" exact="false"/>
              <do_if value="global.$GT_Config? and global.$GT_Config.$Training? and global.$GT_Config.$Training.$ValidStationTypes?">
                <do_all exact="global.$GT_Config.$Training.$ValidStationTypes.count" counter="$vi">
                  <do_if value="$station.macro.id? and ($station.macro.id.indexof.{global.$GT_Config.$Training.$ValidStationTypes.{$vi}} != -1)">
                    <set_value name="$validMacro" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $validMacro">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$failReason" exact="'Macro not in ValidStationTypes (training will not start on dock)'"/>
              </do_if>
            </do_if>
            
            <set_value name="$stationLabel" exact="@$station.knownname"/>
            <do_if value="$stationLabel == null or $stationLabel == ''">
              <set_value name="$stationLabel" exact="'Unknown station'"/>
            </do_if>
            <set_value name="$stationLabel" exact="$stationLabel + ' (' + $station.idcode + ')'"/>
            
            <do_if value="$isValid">
              <set_value name="$eligibleCount" exact="$eligibleCount + 1"/>
              <set_value name="$secName" exact="'?'"/>
              <do_if value="$station.sector? and @$station.sector.knownname != null">
                <set_value name="$secName" exact="@$station.sector.knownname"/>
              </do_if>
              <append_to_list name="$eligibleRows" exact="table[
                $Check = $stationLabel,
                $Status = 'PASS',
                $Detail = 'Eligible. Jumps: ' + $gateDistance + ', sector: ' + $secName
              ]"/>
            </do_if>
            <do_else>
              <set_value name="$failureCount" exact="$failureCount + 1"/>
              <do_if value="$failRows.count lt $maxFailureRows">
                <append_to_list name="$failRows" exact="table[
                  $Check = $stationLabel,
                  $Status = 'WARN',
                  $Detail = $failReason
                ]"/>
              </do_if>
            </do_else>
          </do_all>
          
          <do_if value="$eligibleCount == 0">
            <append_to_list name="$rows" exact="table[$Check = 'Eligible stations', $Status = 'WARN', $Detail = 'None within max jumps passing all checks.']"/>
          </do_if>
          <do_else>
            <append_to_list name="$rows" exact="table[$Check = 'Eligible stations', $Status = 'PASS', $Detail = 'Count: ' + $eligibleCount + ' (auto-training picks nearest by path distance).']"/>
          </do_else>
          
          <do_all exact="$eligibleRows.count" counter="$er">
            <append_to_list name="$rows" exact="$eligibleRows.{$er}"/>
          </do_all>
          
          <do_if value="$failureCount gt 0">
            <append_to_list name="$rows" exact="table[
              $Check = 'Rejected (sample)',
              $Status = 'INFO',
              $Detail = 'Showing up to ' + $maxFailureRows + ' of ' + $failureCount + ' rejected candidates.'
            ]"/>
            <do_all exact="$failRows.count" counter="$fr">
              <append_to_list name="$rows" exact="$failRows.{$fr}"/>
            </do_all>
          </do_if>
        </do_else>
        
        <return value="table[$Rows = $rows]"/>
      </actions>
    </library>
    
    <!-- Centralized transition to training-blocked state -->
    <library name="GT_SetTrainingBlocked" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to block"/>
        <param name="level" default="1" comment="Required training level"/>
        <param name="set_xpblocked" default="true" comment="Set XPBlocked flag"/>
      </params>
      <actions>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel" exact="$level"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'needs_training'"/>
          <do_if value="$set_xpblocked">
            <set_value name="global.$GT_Pilots.{$pilot}.$XPBlocked" exact="true"/>
          </do_if>
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Centralized transition to unblocked state -->
    <library name="GT_ClearTrainingBlocked" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to unblock"/>
        <param name="clear_blocked_level" default="true" comment="Clear BlockedLevel too"/>
      </params>
      <actions>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
          <do_if value="$clear_blocked_level">
            <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          </do_if>
          <!-- Paused placeholders survive commander-pause cleanup; drop them whenever
               the live block is cleared so reactivation cannot re-apply [BL]. -->
          <remove_value name="global.$GT_Pilots.{$pilot}.$PausedWithTrainingNeeded"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$PausedBlockedLevel"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'active'"/>
          <return value="true"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Apply training gate when XP crosses a new skill threshold (any XP source). -->
    <library name="GT_ProcessLevelUpTrainingGate" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot who gained XP"/>
        <param name="ship" comment="Ship to rename and signal for auto-training"/>
        <param name="currentSkillLevel" comment="Management skill level before XP award"/>
        <param name="newSkillLevel" comment="Management skill level implied by new XP total"/>
        <param name="newXP" comment="Pilot XP total after award"/>
        <param name="ware" default="null" comment="Ware name for level-up notification (optional)"/>
        <param name="logTag" default="'XP'" comment="Debug log prefix"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[$TrainingBlocked = false, $RequiredTrainingLevel = 0]"/>
        <set_value name="$starRating" exact="($newSkillLevel / 3)i"/>
        <do_if value="$starRating gt 5">
          <set_value name="$starRating" exact="5"/>
        </do_if>
        
        <set_value name="$trainingRequired" exact="false"/>
        <set_value name="$requiredTrainingLevel" exact="0"/>
        
        <do_all exact="($newSkillLevel - $currentSkillLevel)" counter="$levelCheck">
          <set_value name="$checkLevel" exact="$currentSkillLevel + $levelCheck"/>
          
          <set_value name="$levelRequiresTraining" exact="false"/>
          <do_if value="global.$GT_Config.$Training.$RequiredLevels?">
            <do_all exact="global.$GT_Config.$Training.$RequiredLevels.count" counter="$i">
              <do_if value="global.$GT_Config.$Training.$RequiredLevels.{$i} == $checkLevel">
                <set_value name="$levelRequiresTraining" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="$levelRequiresTraining">
            <set_value name="$hasCompletedTraining" exact="false"/>
            <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
              <do_all exact="global.$GT_Pilots.{$pilot}.$TrainingCompleted.count" counter="$j">
                <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted.{$j} == $checkLevel">
                  <set_value name="$hasCompletedTraining" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            
            <do_if value="not $hasCompletedTraining">
              <set_value name="$trainingRequired" exact="true"/>
              <set_value name="$requiredTrainingLevel" exact="$checkLevel"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ')   TRAINING BLOCK: Pilot would advance from ' + $currentSkillLevel + ' to ' + $newSkillLevel + ' but needs training at level ' + $checkLevel + ' [' + $logTag + ']'" chance="100"/>
              </do_if>
              <break/>
            </do_if>
          </do_if>
        </do_all>
        
        <do_if value="$trainingRequired">
          <set_value name="$result.$TrainingBlocked" exact="true"/>
          <set_value name="$result.$RequiredTrainingLevel" exact="$requiredTrainingLevel"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ')  ' + $logTag + ': Skill level ' + $requiredTrainingLevel + ' requires training - blocking advancement (would have reached level ' + $newSkillLevel + ')'" chance="100"/>
          </do_if>
          
          <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
          <do_if value="$currentSkillLevel gt $vanillaMgmtLevel">
            <set_skill entity="$pilot" type="skilltype.management" exact="$currentSkillLevel"/>
          </do_if>
          <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$currentSkillLevel"/>
          
          <set_value name="$currentPilotSkill" exact="0"/>
          <do_if value="$pilot.skill.piloting?">
            <set_value name="$currentPilotSkill" exact="@$pilot.skill.piloting"/>
          </do_if>
          <set_value name="$targetPilotLevel" exact="($currentSkillLevel * 9) / 15"/>
          <do_if value="$targetPilotLevel lt 1">
            <set_value name="$targetPilotLevel" exact="1"/>
          </do_if>
          <do_if value="$targetPilotLevel gt 9">
            <set_value name="$targetPilotLevel" exact="9"/>
          </do_if>
          <do_if value="$targetPilotLevel gt $currentPilotSkill">
            <set_skill entity="$pilot" type="skilltype.piloting" exact="$targetPilotLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Pilot skill increased from ' + $currentPilotSkill + ' to ' + $targetPilotLevel + ' (management blocked at: ' + $currentSkillLevel + ')'" chance="100"/>
            </do_if>
          </do_if>
          
          <set_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel" exact="$newSkillLevel"/>
          
          <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
            <param name="pilot" value="$pilot"/>
            <param name="level" value="$requiredTrainingLevel"/>
            <param name="set_xpblocked" value="true"/>
          </run_actions>
          
          <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="xp" value="$newXP"/>
            <param name="level" value="$requiredTrainingLevel"/>
            <param name="nameType" value="'blocked'"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Ship renamed to show blocked state (advancement required for level ' + $requiredTrainingLevel + ')'" chance="100"/>
          </do_if>
          
          <do_if value="global.$GT_Config.$Notifications.$TrainingRequired">
            <set_value name="$message" exact="'Pilot ' + $pilot.name + ' needs training to advance to skill level ' + $requiredTrainingLevel + '! Dock at a training station to unlock further progression.'"/>
            <show_notification text="$message" timeout="8s" priority="7"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <write_to_logbook category="upkeep" title="'Training Required: ' + $pilot.name + ' (' + $ship.knownname + ')'" text="$message" interaction="showonmap" object="$ship" highlighted="true"/>
            </do_if>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Management skill kept at level ' + $currentSkillLevel + ' until level ' + $requiredTrainingLevel + ' training completed'" chance="100"/>
          </do_if>
          
          <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
            $Ship = $ship,
            $Pilot = $pilot,
            $RequiredLevel = $requiredTrainingLevel,
            $CurrentLevel = $currentSkillLevel,
            $TargetLevel = $newSkillLevel,
            $BlockedXP = $newXP
          ]"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') AUTO-TRAINING: Sent training needed signal for pilot ' + $pilot.name + ' (requires level ' + $requiredTrainingLevel + ' training) [' + $logTag + ']'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') ' + $logTag + ': Pilot ' + $pilot.name + ' advanced from skill level ' + $currentSkillLevel + ' to ' + $newSkillLevel + ' (no training required)!'" chance="100"/>
          </do_if>
          
          <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
          <do_if value="$newSkillLevel gt $vanillaMgmtLevel">
            <set_skill entity="$pilot" type="skilltype.management" exact="$newSkillLevel"/>
          </do_if>
          <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$newSkillLevel"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Management skill set to level ' + $newSkillLevel + ' (' + $starRating + ' stars)'" chance="100"/>
          </do_if>
          
          <set_value name="$currentPilotSkill" exact="0"/>
          <do_if value="$pilot.skill.piloting?">
            <set_value name="$currentPilotSkill" exact="@$pilot.skill.piloting"/>
          </do_if>
          <set_value name="$targetPilotLevel" exact="($newSkillLevel * 9) / 15"/>
          <do_if value="$targetPilotLevel lt 1">
            <set_value name="$targetPilotLevel" exact="1"/>
          </do_if>
          <do_if value="$targetPilotLevel gt 9">
            <set_value name="$targetPilotLevel" exact="9"/>
          </do_if>
          <do_if value="$targetPilotLevel gt $currentPilotSkill">
            <set_skill entity="$pilot" type="skilltype.piloting" exact="$targetPilotLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Pilot skill increased from ' + $currentPilotSkill + ' to ' + $targetPilotLevel + ' (management: ' + $newSkillLevel + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Pilot skill unchanged at ' + $currentPilotSkill + ' (already higher than target ' + $targetPilotLevel + ')'" chance="100"/>
            </do_if>
          </do_else>
          
          <do_if value="global.$GT_Config.$Notifications.$LevelUp">
            <set_value name="$wareLabel" exact="if $ware? and $ware != null then $ware else 'trade'"/>
            <set_value name="$message" exact="{77000,2006}.[$pilot.name, $newSkillLevel, $wareLabel]"/>
            <set_value name="$greenColor" exact="'\033#FF00CC00#'"/>
            <set_value name="$colorReset" exact="'\033X'"/>
            <set_value name="$coloredMessage" exact="$greenColor + $message + $colorReset"/>
            <show_notification text="$coloredMessage" timeout="6s"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <write_to_logbook category="news" title="'Level Up: ' + $pilot.name + ' (' + $ship.knownname + ')'" text="$message" interaction="showonmap" object="$ship"/>
            </do_if>
          </do_if>
          
          <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="xp" value="$newXP"/>
            <param name="level" value="$newSkillLevel"/>
            <param name="nameType" value="'trader'"/>
          </run_actions>
        </do_else>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- LOGBOOK UTILITIES -->
    <!-- ========================================= -->
    
    <!-- Is Logbook Enabled -->
    <library name="GT_IsLogbookEnabled" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check logbook setting for"/>
      </params>
      <actions>
        <set_value name="$logEnabled" exact="false"/>
        <do_if value="(global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}) and @$ship.defaultorder.$logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_if>
        <do_elseif value="@$ship.defaultorder.id == 'Assist' and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id}) and @$ship.commander.defaultorder.$logbookentries">
          <set_value name="$logEnabled" exact="true"/>
        </do_elseif>
        <return value="$logEnabled"/>
      </actions>
    </library>
    
    <!-- Write Logbook Message -->
    <!-- Centralized logbook message creation for MD scripts -->
    <!-- IMPORTANT: X4 TextDB doesn't support list variables, so callers must construct message string first -->
    <!-- Use: {77000,ID}.[param1, param2, ...] to create message, then pass as Message parameter -->
    <library name="WriteLogbookMessage" purpose="run_actions">
      <params>
        <param name="Message" comment="Message string (REQUIRED - construct using {77000,ID}.[params] before calling)"/>
        <param name="Category" comment="Logbook category: alerts, upkeep, news, general, tips"/>
        <param name="Title" comment="Logbook entry title"/>
        <param name="Object" default="null" comment="Object to attach message to (ship, station, etc.)"/>
        <param name="Interaction" default="null" comment="Interaction type: 'showonmap' or null"/>
        <param name="Highlighted" default="false" comment="Whether to highlight message (true/false)"/>
        <param name="Money" default="null" comment="Money amount to display (negative for expenses, positive for income)"/>
        <param name="Bonus" default="null" comment="Bonus amount to display (typically profit)"/>
        <param name="CheckGlobalSettings" default="true" comment="Check global logbook settings before writing (default true)"/>
      </params>
      <actions>
        <!-- DEBUG MODE: Check if debug logging is enabled (if CheckGlobalSettings is true) -->
        <!-- Logbook messages now only write when debug is enabled -->
        <set_value name="$shouldWrite" exact="true"/>
        <do_if value="$CheckGlobalSettings">
          <set_value name="$shouldWrite" exact="false"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$shouldWrite" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Write logbook if enabled -->
        <do_if value="$shouldWrite">
          <!-- Message is already constructed by caller using TextDB syntax -->
          <!-- Example: {77000,3218}.[@$newSector.knownname, @$currentDestination.knownname, ...] -->
          <!-- Determine object value -->
          <set_value name="$objectValue" exact="null"/>
          <do_if value="$Object? and $Object != null">
            <set_value name="$objectValue" exact="$Object"/>
          </do_if>
        <set_value name="$hasObject" exact="$objectValue? and $objectValue != null"/>
          
          <!-- Check if interaction is 'showonmap' -->
          <set_value name="$hasInteraction" exact="false"/>
          <do_if value="$Interaction? and $Interaction != null and $Interaction == 'showonmap'">
            <set_value name="$hasInteraction" exact="true"/>
          </do_if>
        <!-- If no object is provided, do not use interaction (vanilla player logbook entries omit object/interaction). -->
        <do_if value="not $hasObject">
          <set_value name="$hasInteraction" exact="false"/>
        </do_if>
          
          <!-- Debug: Log before writing logbook -->
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$msgExists" exact="if $Message? then 'true' else 'false'"/>
            <set_value name="$msgNull" exact="if $Message == null then 'true' else 'false'"/>
            <set_value name="$msgEmpty" exact="if $Message == '' then 'true' else 'false'"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Logbook] WriteLogbookMessage: Category=' + $Category + ', Title=' + $Title" chance="100"/>
              <debug_text text="'[GT-Logbook] Message exists=' + $msgExists + ', null=' + $msgNull + ', empty=' + $msgEmpty" chance="100"/>
            </do_if>
          </do_if>
          
        <!-- Write logbook entry with conditional blocks for: hasObject -> interaction -> category -> money/bonus -->
        <!-- XSD requires literal values for category and interaction attributes -->
        <do_if value="not $hasObject">
          <!-- Player logbook only: omit object attribute entirely (vanilla pattern: write_to_logbook without object=...) -->
          <do_if value="$Category == 'alerts'">
            <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
              <write_to_logbook category="alerts" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
            </do_if>
            <do_elseif value="$Money? and $Money != null">
              <write_to_logbook category="alerts" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money"/>
            </do_elseif>
            <do_elseif value="$Bonus? and $Bonus != null">
              <write_to_logbook category="alerts" title="$Title" text="$Message" highlighted="$Highlighted" bonus="$Bonus"/>
            </do_elseif>
            <do_else>
              <write_to_logbook category="alerts" title="$Title" text="$Message" highlighted="$Highlighted"/>
            </do_else>
          </do_if>
          <do_elseif value="$Category == 'upkeep'">
            <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
              <write_to_logbook category="upkeep" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
            </do_if>
            <do_elseif value="$Money? and $Money != null">
              <write_to_logbook category="upkeep" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money"/>
            </do_elseif>
            <do_elseif value="$Bonus? and $Bonus != null">
              <write_to_logbook category="upkeep" title="$Title" text="$Message" highlighted="$Highlighted" bonus="$Bonus"/>
            </do_elseif>
            <do_else>
              <write_to_logbook category="upkeep" title="$Title" text="$Message" highlighted="$Highlighted"/>
            </do_else>
          </do_elseif>
          <do_elseif value="$Category == 'news'">
            <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
              <write_to_logbook category="news" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
            </do_if>
            <do_elseif value="$Money? and $Money != null">
              <write_to_logbook category="news" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money"/>
            </do_elseif>
            <do_elseif value="$Bonus? and $Bonus != null">
              <write_to_logbook category="news" title="$Title" text="$Message" highlighted="$Highlighted" bonus="$Bonus"/>
            </do_elseif>
            <do_else>
              <write_to_logbook category="news" title="$Title" text="$Message" highlighted="$Highlighted"/>
            </do_else>
          </do_elseif>
          <do_elseif value="$Category == 'general'">
            <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
            </do_if>
            <do_elseif value="$Money? and $Money != null">
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money"/>
            </do_elseif>
            <do_elseif value="$Bonus? and $Bonus != null">
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted" bonus="$Bonus"/>
            </do_elseif>
            <do_else>
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted"/>
            </do_else>
          </do_elseif>
          <do_elseif value="$Category == 'tips'">
            <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
              <write_to_logbook category="tips" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
            </do_if>
            <do_elseif value="$Money? and $Money != null">
              <write_to_logbook category="tips" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money"/>
            </do_elseif>
            <do_elseif value="$Bonus? and $Bonus != null">
              <write_to_logbook category="tips" title="$Title" text="$Message" highlighted="$Highlighted" bonus="$Bonus"/>
            </do_elseif>
            <do_else>
              <write_to_logbook category="tips" title="$Title" text="$Message" highlighted="$Highlighted"/>
            </do_else>
          </do_elseif>
          <do_else>
            <!-- Default to 'general' if category not recognized -->
            <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
            </do_if>
            <do_elseif value="$Money? and $Money != null">
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted" money="$Money"/>
            </do_elseif>
            <do_elseif value="$Bonus? and $Bonus != null">
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted" bonus="$Bonus"/>
            </do_elseif>
            <do_else>
              <write_to_logbook category="general" title="$Title" text="$Message" highlighted="$Highlighted"/>
            </do_else>
          </do_else>
        </do_if>
        <do_elseif value="$hasInteraction">
            <!-- WITH interaction="showonmap" -->
            <do_if value="$Category == 'alerts'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="alerts" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="alerts" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="alerts" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="alerts" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_if>
            <do_elseif value="$Category == 'upkeep'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="upkeep" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="upkeep" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="upkeep" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="upkeep" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$Category == 'news'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="news" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="news" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="news" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="news" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$Category == 'general'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$Category == 'tips'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="tips" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="tips" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="tips" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="tips" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_else>
              <!-- Default to 'general' if category not recognized -->
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="general" title="$Title" text="$Message" interaction="showonmap" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_else>
          </do_elseif>
          <do_else>
            <!-- WITHOUT interaction attribute -->
            <do_if value="$Category == 'alerts'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="alerts" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="alerts" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="alerts" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="alerts" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_if>
            <do_elseif value="$Category == 'upkeep'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="upkeep" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="upkeep" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="upkeep" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="upkeep" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$Category == 'news'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="news" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="news" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="news" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="news" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$Category == 'general'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$Category == 'tips'">
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="tips" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="tips" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="tips" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="tips" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_elseif>
            <do_else>
              <!-- Default to 'general' if category not recognized -->
              <do_if value="$Money? and $Money != null and $Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money" bonus="$Bonus"/>
              </do_if>
              <do_elseif value="$Money? and $Money != null">
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" money="$Money"/>
              </do_elseif>
              <do_elseif value="$Bonus? and $Bonus != null">
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted" bonus="$Bonus"/>
              </do_elseif>
              <do_else>
                <write_to_logbook category="general" title="$Title" text="$Message" object="$objectValue" highlighted="$Highlighted"/>
              </do_else>
            </do_else>
          </do_else>
        </do_if>
      </actions>
    </library>
    
    <!-- Handle Logbook Message from AI Scripts -->
    <!-- AI scripts cannot call MD libraries directly, so they signal this cue -->
    <!-- AI scripts construct messages using TextDB syntax before sending (vanilla pattern) -->
    <cue name="HandleLogbookMessage" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_WriteLogbook'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        
        <!-- Call library with data from signal -->
        <!-- Message is already constructed by AI script using TextDB syntax -->
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="$data.$Message"/>
          <param name="Category" value="$data.$Category"/>
          <param name="Title" value="$data.$Title"/>
          <param name="Object" value="if $data.$Object? then $data.$Object else null"/>
          <param name="Interaction" value="if $data.$Interaction? then $data.$Interaction else null"/>
          <param name="Highlighted" value="if $data.$Highlighted? then $data.$Highlighted else false"/>
          <param name="Money" value="if $data.$Money? then $data.$Money else null"/>
          <param name="Bonus" value="if $data.$Bonus? then $data.$Bonus else null"/>
          <param name="CheckGlobalSettings" value="if $data.$CheckGlobalSettings? then $data.$CheckGlobalSettings else true"/>
        </run_actions>
      </actions>
    </cue>

    <!-- ========================================= -->
    
    <!-- Counter Management Library Functions -->
    <!-- Centralized counter management to prevent leaks and ensure consistency -->
    
    <!-- Increment Counter (with initialization check) -->
    <library name="GT_IncrementCounter" purpose="run_actions">
      <params>
        <param name="counterPath" comment="Path to counter (legacy helper; dynamic access unsupported in MD)"/>
        <param name="initializeIfMissing" default="true" comment="Initialize counter to 0 if it doesn't exist"/>
      </params>
      <actions>
        <!-- Extract counter object and property name -->
        <!-- For now, we'll use a simpler approach: pass the counter object and property name separately -->
        <!-- Actually, MD doesn't support dynamic property access, so we need a different approach -->
        <!-- We'll create specific functions for each counter type -->
      </actions>
    </library>
    
    <!-- Decrement Counter (with negative clamp) -->
    <library name="GT_DecrementCounter" purpose="run_actions">
      <params>
        <param name="counterPath" comment="Path to counter"/>
        <param name="clampToZero" default="true" comment="Clamp counter to 0 if it goes negative"/>
      </params>
      <actions>
        <!-- Similar limitation - MD doesn't support dynamic property access -->
        <!-- We'll create specific functions for each counter type -->
      </actions>
    </library>
    
    <!-- Legacy queue/batch counter helpers removed in AI migration -->
    
    <!-- ========================================= -->
    <!-- TRADE SEARCH PIPELINE LOGGING -->
    <!-- ========================================= -->
    
    <!-- ========================================= -->
    <!-- TRADE INDEX (Cross-Cache Invalidation) -->
    <!-- ========================================= -->
    
    <!-- ========================================= -->
    <!-- CENTRAL SCHEDULER (Phase 2) -->
    <!-- ========================================= -->
    
    <!-- Create Work Item for Scheduler -->
    <!-- Work items represent units of work in the trade search pipeline -->
    <library name="GT_CreateWorkItem" purpose="run_actions">
      <params>
        <param name="type" comment="Work item type: 'Request', 'CacheQuery', 'SearchContinuation', 'HomeSearch', 'OfferCollect', 'Match', 'Finalize'"/>
        <param name="key" comment="Unique key for this work item (typically ship.idcode + '_' + type)"/>
        <param name="traceId" comment="Trace ID for this work item"/>
        <param name="payload" default="table[]" comment="Type-specific payload data"/>
      </params>
      <actions>
        <!-- Validate inputs - ERROR if missing -->
        <do_if value="$type == '' or $key == ''">
          <debug_text text="'[GT-ERROR] GT_CreateWorkItem: type or key is empty - type=' + $type + ' key=' + $key" chance="100"/>
          <return value="null"/>
        </do_if>
        
        <set_value name="$workItem" exact="table[
          $Type = $type,
          $Key = $key,
          $TraceId = $traceId,
          $CreatedAt = player.age,
          $UpdatedAt = player.age,
          $State = 'queued',
          $Payload = $payload
        ]"/>
        
        <return value="$workItem"/>
      </actions>
    </library>
    
    <!-- Enqueue Work Item to Scheduler -->
    <library name="GT_EnqueueWorkItem" purpose="run_actions">
      <params>
        <param name="workItem" comment="Work item to enqueue"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
      </params>
      <actions>
        <!-- CRITICAL: Initialize scheduler if missing (defensive initialization) -->
        <!-- This handles race conditions where work items are enqueued before SystemInit completes -->
        <do_if value="not global.$GT_Scheduler?">
          <!-- Initialize with defaults, will be updated from global settings if available -->
          <set_value name="$defaultFallbackSearches" exact="1"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches?">
            <set_value name="$defaultFallbackSearches" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches"/>
          </do_if>
          <set_value name="global.$GT_Scheduler" exact="table[
            $WorkQueue = [],
            $ActiveWork = table[],
            $Budgets = table[
              $CheapOpsPerTick = 10,
              $OfferOpsPerTick = 5,
              $MatchOpsPerTick = 1,
              $MaxActiveHomeSearches = 1,
              $MaxActiveFallbackSearches = $defaultFallbackSearches
            ],
            $Counters = table[
              $Queued = 0,
              $Active = 0,
              $Completed = 0,
              $Failed = 0
            ],
            $Processing = false,
            $LastStatsLog = player.age
          ]"/>
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Scheduler'"/>
              <param name="action" value="'Initialized'"/>
              <param name="details" value="'reason=auto_init_on_enqueue type=' + (if $workItem? and $workItem.$Type? then $workItem.$Type else 'unknown')"/>
              <param name="logLevel" value="2"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-WARN] GT_EnqueueWorkItem: Scheduler auto-initialized (should have been initialized by SystemInit)'" chance="100"/>
          </do_else>
        </do_if>
        <!-- Ensure required properties exist (defensive check) -->
        <do_if value="not global.$GT_Scheduler.$WorkQueue?">
          <set_value name="global.$GT_Scheduler.$WorkQueue" exact="[]"/>
        </do_if>
        <!-- CRITICAL: Ensure ActiveWork exists - but DON'T fix corruption here -->
        <!-- Corruption detection/fixing is handled by ProcessWorkQueue (authoritative processor) -->
        <!-- This prevents race conditions where multiple places try to fix corruption simultaneously -->
        <do_if value="not global.$GT_Scheduler.$ActiveWork?">
          <set_value name="global.$GT_Scheduler.$ActiveWork" exact="table[]"/>
        </do_if>
        <!-- NOTE: We don't check for corruption here - ProcessWorkQueue handles that -->
        <!-- If ActiveWork is corrupted, ProcessWorkQueue will detect and fix it on its next tick -->
        
        <!-- Validate work item - ERROR if missing -->
        <do_if value="not $workItem? or not $workItem.$Type? or not $workItem.$Key?">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Scheduler'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=invalid_workItem'"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GT_EnqueueWorkItem: Work item is null or missing required fields'" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <!-- Ensure WorkQueue exists -->
        <do_if value="not global.$GT_Scheduler.$WorkQueue?">
          <set_value name="global.$GT_Scheduler.$WorkQueue" exact="[]"/>
        </do_if>
        <!-- NOTE: ActiveWork type check already done above (lines 4788-4800) - no need to check again -->
        <do_if value="not global.$GT_Scheduler.$Processing?">
          <set_value name="global.$GT_Scheduler.$Processing" exact="false"/>
        </do_if>
        
        <!-- Add to queue -->
        <append_to_list name="global.$GT_Scheduler.$WorkQueue" exact="$workItem"/>
        
        <!-- Update counters -->
        <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
          <param name="counterName" value="'Queued'"/>
          <param name="delta" value="1"/>
        </run_actions>
        
        <!-- Log work item queued -->
        <set_value name="$logTraceId" exact="if $traceId != '' then $traceId else (if $workItem.$TraceId? then $workItem.$TraceId else '0')"/>
        <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
          <param name="traceId" value="$logTraceId"/>
          <param name="stage" value="'Scheduler'"/>
          <param name="action" value="'WorkItemQueued'"/>
          <param name="details" value="'type=' + $workItem.$Type + ' key=' + $workItem.$Key + ' queue=' + global.$GT_Scheduler.$WorkQueue.count"/>
          <param name="logLevel" value="2"/>
        </run_actions>
        
        <!-- Trigger scheduler processing if not already running (single signal, no duplicate) -->
        <!-- ROOT CAUSE FIX: Use ProcessWorkQueueDelayed instead of direct signal to prevent stutter -->
        <!-- Direct signal can cause multiple ProcessWorkQueue instances in same frame -->
        <do_if value="not global.$GT_Scheduler.$Processing">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.ProcessWorkQueueDelayed"/>
        </do_if>
        
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Update Work Item State -->
    <library name="GT_UpdateWorkItemState" purpose="run_actions">
      <params>
        <param name="key" comment="Work item key"/>
        <param name="newState" comment="New state: 'queued', 'active', 'completed', 'failed'"/>
        <param name="traceId" default="''" comment="Trace ID for logging"/>
        <param name="reason" default="''" comment="Failure reason (if state='failed')"/>
        <param name="workItem" default="null" comment="Work item object (optional - if provided, skips lookup)"/>
      </params>
      <actions>
        <!-- Validate scheduler exists - ERROR if missing -->
        <do_if value="not global.$GT_Scheduler?">
          <debug_text text="'[GT-ERROR] GT_UpdateWorkItemState: Scheduler not initialized - key=' + $key" chance="100"/>
          <return value="false"/>
        </do_if>
        
        <!-- Use provided work item or find it in WorkQueue -->
        <!-- NOTE: ActiveWork is now keyed by ship, not by string key, so we can't look it up by key -->
        <set_value name="$oldState" exact="'unknown'"/>
        <set_value name="$workShip" exact="null"/>
        
        <do_if value="$workItem != null">
          <!-- Use provided work item -->
          <set_value name="$oldState" exact="if $workItem.$State? then $workItem.$State else 'unknown'"/>
          <!-- Extract ship from payload for ActiveWork operations -->
          <do_if value="$workItem.$Payload?">
            <set_value name="$workShip" exact="@$workItem.$Payload.$Ship"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Find work item in WorkQueue (can't look up ActiveWork by key anymore - it's keyed by ship) -->
          <set_value name="$workItem" exact="null"/>
          
          <!-- Check WorkQueue -->
          <do_if value="global.$GT_Scheduler.$WorkQueue?">
            <do_all exact="global.$GT_Scheduler.$WorkQueue.count" counter="$i">
              <do_if value="global.$GT_Scheduler.$WorkQueue.{$i}.$Key == $key">
                <set_value name="$workItem" exact="global.$GT_Scheduler.$WorkQueue.{$i}"/>
                <set_value name="$oldState" exact="if $workItem.$State? then $workItem.$State else 'unknown'"/>
                <!-- Extract ship from payload -->
                <do_if value="$workItem.$Payload?">
                  <set_value name="$workShip" exact="@$workItem.$Payload.$Ship"/>
                </do_if>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- ERROR if work item not found -->
          <do_if value="not $workItem? or $workItem == null">
            <do_if value="$traceId != ''">
              <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
                <param name="traceId" value="$traceId"/>
                <param name="stage" value="'Scheduler'"/>
                <param name="action" value="'Error'"/>
                <param name="details" value="'reason=workItem_not_found key=' + $key + ' newState=' + $newState"/>
                <param name="logLevel" value="0"/>
              </run_actions>
            </do_if>
            <do_else>
              <debug_text text="'[GT-ERROR] GT_UpdateWorkItemState: Work item not found - key=' + $key" chance="100"/>
            </do_else>
            <return value="false"/>
          </do_if>
        </do_else>
        
        <!-- CRITICAL FIX: Validate workItem is not null before accessing properties -->
        <do_if value="not $workItem? or $workItem == null">
          <do_if value="$traceId != ''">
            <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
              <param name="traceId" value="$traceId"/>
              <param name="stage" value="'Scheduler'"/>
              <param name="action" value="'Error'"/>
              <param name="details" value="'reason=workItem_is_null key=' + $key + ' newState=' + $newState"/>
              <param name="logLevel" value="0"/>
            </run_actions>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ERROR] GT_UpdateWorkItemState: Work item is null - key=' + $key" chance="100"/>
          </do_else>
          <return value="false"/>
        </do_if>
        
        <!-- Update state -->
        <set_value name="$workItem.$State" exact="$newState"/>
        <set_value name="$workItem.$UpdatedAt" exact="player.age"/>
        
        <!-- Update in ActiveWork if present (keyed by ship, not by key) -->
        <do_if value="$workShip? and global.$GT_Scheduler.$ActiveWork? and global.$GT_Scheduler.$ActiveWork.{$workShip}?">
          <set_value name="global.$GT_Scheduler.$ActiveWork.{$workShip}" exact="$workItem"/>
        </do_if>
        
        <!-- Log state transition -->
        <!-- CRITICAL FIX: Use safe property access for logging -->
        <set_value name="$logTraceId" exact="if $traceId != '' then $traceId else (if $workItem? and $workItem.$TraceId? then $workItem.$TraceId else '0')"/>
        <set_value name="$workItemType" exact="if $workItem? and $workItem.$Type? then $workItem.$Type else 'unknown'"/>
        <set_value name="$details" exact="'type=' + $workItemType + ' key=' + $key + ' state=' + $oldState + '->' + $newState"/>
        <do_if value="$newState == 'failed' and $reason != ''">
          <set_value name="$details" exact="$details + ' reason=' + $reason"/>
        </do_if>
        <do_if value="$newState == 'completed'">
          <!-- CRITICAL FIX: Use safe property access -->
          <do_if value="$workItem? and $workItem.$CreatedAt?">
            <set_value name="$duration" exact="player.age - $workItem.$CreatedAt"/>
            <set_value name="$details" exact="$details + ' duration=' + ($duration / 1ms) + 'ms'"/>
          </do_if>
        </do_if>
        
        <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearch">
          <param name="traceId" value="$logTraceId"/>
          <param name="stage" value="'Scheduler'"/>
          <param name="action" value="'WorkItemStateChange'"/>
          <param name="details" value="$details"/>
          <param name="logLevel" value="1"/>
        </run_actions>
        
        <!-- Update counters -->
        <do_if value="$oldState == 'queued' and $newState == 'active'">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Queued'"/>
            <param name="delta" value="-1"/>
          </run_actions>
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Active'"/>
            <param name="delta" value="1"/>
          </run_actions>
        </do_if>
        <do_elseif value="$oldState == 'active' and $newState == 'completed'">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Active'"/>
            <param name="delta" value="-1"/>
          </run_actions>
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Completed'"/>
            <param name="delta" value="1"/>
          </run_actions>
        </do_elseif>
        <do_elseif value="$oldState == 'active' and $newState == 'failed'">
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Active'"/>
            <param name="delta" value="-1"/>
          </run_actions>
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Failed'"/>
            <param name="delta" value="1"/>
          </run_actions>
        </do_elseif>
        
        <return value="true"/>
      </actions>
    </library>
    

    <!-- Trade key, trade index, reservations, orphan cleanup: glx_lib_reservations.xml (GLX_Lib_Reservations) -->

    
    <!-- ========================================= -->
    
    <!-- Build Search Params from Payload -->
    <!-- DRY: Extracts the common $searchParams table construction used by gt_tradesearch_scheduler.xml -->
    <library name="GT_BuildSearchParams" purpose="run_actions">
      <params>
        <param name="payload" comment="Work item payload containing search parameters"/>
      </params>
      <actions>
        <set_value name="$searchParams" exact="table[]"/>
        <do_if value="$payload.$Ship?">
          <set_value name="$searchParams.$Ship" exact="$payload.$Ship"/>
        </do_if>
        <do_if value="$payload.$MaxDistance?">
          <set_value name="$searchParams.$MaxDistance" exact="$payload.$MaxDistance"/>
        </do_if>
        <do_if value="$payload.$OriginalMaxDistance?">
          <set_value name="$searchParams.$OriginalMaxDistance" exact="$payload.$OriginalMaxDistance"/>
        </do_if>
        <do_if value="$payload.$PilotSkillMaxDistance?">
          <set_value name="$searchParams.$PilotSkillMaxDistance" exact="$payload.$PilotSkillMaxDistance"/>
        </do_if>
        <do_if value="$payload.$MinROI?">
          <set_value name="$searchParams.$MinROI" exact="$payload.$MinROI"/>
        </do_if>
        <do_if value="$payload.$MinAbsoluteProfit?">
          <set_value name="$searchParams.$MinAbsoluteProfit" exact="$payload.$MinAbsoluteProfit"/>
        </do_if>
        <do_if value="$payload.$FactionPriority?">
          <set_value name="$searchParams.$FactionPriority" exact="$payload.$FactionPriority"/>
        </do_if>
        <do_if value="$payload.$FactionPriorityText?">
          <set_value name="$searchParams.$FactionPriorityText" exact="$payload.$FactionPriorityText"/>
        </do_if>
        <do_if value="$payload.$DistancePenaltyMultiplier?">
          <set_value name="$searchParams.$DistancePenaltyMultiplier" exact="$payload.$DistancePenaltyMultiplier"/>
        </do_if>
        <do_if value="$payload.$SkillLevel?">
          <set_value name="$searchParams.$SkillLevel" exact="$payload.$SkillLevel"/>
        </do_if>
        <do_if value="$payload.$ThreatIntel?">
          <set_value name="$searchParams.$ThreatIntel" exact="$payload.$ThreatIntel"/>
        </do_if>
        <do_if value="$payload.$FleetCoord?">
          <set_value name="$searchParams.$FleetCoord" exact="$payload.$FleetCoord"/>
        </do_if>
        <do_if value="$payload.$AdvancedAnalytics?">
          <set_value name="$searchParams.$AdvancedAnalytics" exact="$payload.$AdvancedAnalytics"/>
        </do_if>
        <return value="$searchParams"/>
      </actions>
    </library>
    
  </cues>
</mdscript><?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Libraries_Pathfinding" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- PROOF-OF-LOAD:
         Emit a single log line on game start/load so we can confirm this MD script is actually loaded and executing
         in the game instance that produces player.log. -->
    <cue name="Init" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <debug_text text="'[GT-Pathfinding] GT_Libraries_Pathfinding loaded (md/gt_libraries_pathfinding.xml)'" chance="100"/>

        <!-- Initialize global sector distance cache (persists across searches, shared by all ships) -->
        <!-- Gate distances only change when gates are built/destroyed (extremely rare) -->
        <!-- Format: global.$GT_SectorDistanceCache.{fromSector}.{toSector} = distance (integer) -->
        <do_if value="not global.$GT_SectorDistanceCache?">
          <set_value name="global.$GT_SectorDistanceCache" exact="table[]"/>
        </do_if>

        <!-- SAVEGAME COMPAT / CRASH RECOVERY:
             These are transient, in-flight coordination globals. If they persist (crash/refresh/old save),
             they can deadlock ships behind "live search already in progress" forever.
             Reset them on game load. -->
        <set_value name="global.$GT_PathfindingQueue" exact="table[
          $Requests = [],
          $ActiveShips = [],
          $ActiveInstances = 0,
          $MaxConcurrent = 2
        ]"/>
        
        <!-- Debug/proof helpers (safe to reset on load) -->
        <set_value name="global.$GT_Pathfinding_Proof" exact="table[
          $QueueProcessorRan = false,
          $IncrementalRan = false,
          $StartedShips = table[],
          $IncrementalStartedShips = table[],
          $LastQueueBlockedLogTime = 0
        ]"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Pathfinding] Reset transient pathfinding queue state on game load'" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- ========================================= -->
    <!-- PATHFINDING UTILITIES -->
    <!-- ========================================= -->
    <!-- Consolidated from: gt_pathfinding_utilities.xml -->
    
    <!-- Calculate Path Distance -->
    <library name="GT_CalculatePathDistance" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship for pathfinding"/>
        <param name="fromSector" comment="Source sector"/>
        <param name="toSector" comment="Destination sector"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group"/>
        <param name="useEscapeMode" default="false" comment="If true, use non-blacklist-aware for escape"/>
      </params>
      <actions>
        <!-- Same sector = 0 -->
        <do_if value="$fromSector == $toSector">
          <return value="0"/>
        </do_if>
        
        <!-- Escape mode: non-blacklist-aware -->
        <do_if value="$useEscapeMode">
          <return value="$fromSector.gatedistance.{$toSector}"/>
        </do_if>
        
        <!-- Normal mode: blacklist-aware -->
        <!-- Get blacklist group if not provided or null (memory:10529400 - ? checks existence, not null) -->
        <do_if value="not $blacklistgroup? or $blacklistgroup == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        <return value="$fromSector.gatedistance.{$toSector}.{$blacklistgroup}.{$ship}"/>
      </actions>
    </library>

    <!-- Check full jump-path legality for illegal wares (mirrors lib.gt.pathfinding route_legality).
         Used by GT Diagnose pair evaluation; no cache (diagnose is player-triggered, one-shot). -->
    <library name="GT_CheckRouteLegality" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship for pathfinding"/>
        <param name="buySector" comment="Buy/source sector on the trade leg"/>
        <param name="sellSector" comment="Sell/destination sector on the trade leg"/>
        <param name="ware" comment="Ware to evaluate"/>
        <param name="homeSector" default="null" comment="Home sector (cache anchor; fallback for route start)"/>
        <param name="startSector" default="null" comment="Route start sector (defaults to ship.sector)"/>
        <param name="allowIllegal" default="false"/>
        <param name="enforceRouteIllegalLegality" default="false"/>
        <param name="blacklistgroup" default="null"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[
          $IsLegal = true,
          $Reason = 'skipped',
          $BlockedSector = null,
          $BlockedSectorName = '',
          $BlockedPoliceFaction = null,
          $BlockedPoliceName = ''
        ]"/>

        <do_if value="not $allowIllegal or not $enforceRouteIllegalLegality">
          <return value="$result"/>
        </do_if>
        <do_if value="not $ware? or @$ware.illegal le 0">
          <return value="$result"/>
        </do_if>
        <do_if value="$ship == null or not $ship.exists or $buySector == null or not $buySector.exists or $sellSector == null or not $sellSector.exists">
          <set_value name="$result.$IsLegal" exact="false"/>
          <set_value name="$result.$Reason" exact="'invalid_context'"/>
          <return value="$result"/>
        </do_if>

        <set_value name="$shipOwner" exact="$ship.owner"/>
        <do_if value="$shipOwner == null">
          <set_value name="$result.$IsLegal" exact="false"/>
          <set_value name="$result.$Reason" exact="'invalid_owner'"/>
          <return value="$result"/>
        </do_if>

        <do_if value="not $blacklistgroup? or $blacklistgroup == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>

        <set_value name="$routeStart" exact="$startSector"/>
        <do_if value="not $routeStart? or not $routeStart.exists">
          <do_if value="$ship.sector? and $ship.sector.exists">
            <set_value name="$routeStart" exact="$ship.sector"/>
          </do_if>
          <do_else>
            <set_value name="$routeStart" exact="$buySector"/>
          </do_else>
        </do_if>
        <do_if value="not $routeStart? or not $routeStart.exists">
          <do_if value="$homeSector? and $homeSector.exists">
            <set_value name="$routeStart" exact="$homeSector"/>
          </do_if>
        </do_if>

        <set_value name="$useLocalHighways" exact="true"/>
        <do_if value="$ship.isclass.ship_l or $ship.isclass.ship_xl">
          <set_value name="$useLocalHighways" exact="false"/>
        </do_if>

        <set_value name="$routeSectors" exact="[]"/>
        <set_value name="$lastRouteSector" exact="null"/>
        <do_if value="$routeStart? and $routeStart.exists">
          <append_to_list name="$routeSectors" exact="$routeStart"/>
          <set_value name="$lastRouteSector" exact="$routeStart"/>
        </do_if>

        <set_value name="$pathToBuy" exact="[]"/>
        <do_if value="$routeStart != $buySector">
          <get_jump_path component="$pathToBuy" multiple="true" uselocalhighways="$useLocalHighways" useblacklist="$blacklistgroup" refobject="$ship" useknownpath="$ship.isplayerowned">
            <start object="$ship"/>
            <end object="$buySector"/>
          </get_jump_path>
        </do_if>
        <do_all exact="$pathToBuy.count" counter="$rlPi">
          <set_value name="$pathComponent" exact="$pathToBuy.{$rlPi}"/>
          <do_if value="$pathComponent? and @$pathComponent.sector != null">
            <set_value name="$pathSector" exact="@$pathComponent.sector"/>
            <do_if value="$lastRouteSector == null or $pathSector != $lastRouteSector">
              <append_to_list name="$routeSectors" exact="$pathSector"/>
              <set_value name="$lastRouteSector" exact="$pathSector"/>
            </do_if>
          </do_if>
        </do_all>
        <do_if value="$lastRouteSector != $buySector">
          <append_to_list name="$routeSectors" exact="$buySector"/>
          <set_value name="$lastRouteSector" exact="$buySector"/>
        </do_if>

        <set_value name="$pathToSell" exact="[]"/>
        <do_if value="$buySector != $sellSector">
          <get_jump_path component="$pathToSell" multiple="true" uselocalhighways="$useLocalHighways" useblacklist="$blacklistgroup" refobject="$ship" useknownpath="$ship.isplayerowned">
            <start object="$buySector"/>
            <end object="$sellSector"/>
          </get_jump_path>
        </do_if>
        <do_all exact="$pathToSell.count" counter="$rlSi">
          <set_value name="$pathComponent2" exact="$pathToSell.{$rlSi}"/>
          <do_if value="$pathComponent2? and @$pathComponent2.sector != null">
            <set_value name="$pathSector2" exact="@$pathComponent2.sector"/>
            <do_if value="$lastRouteSector == null or $pathSector2 != $lastRouteSector">
              <append_to_list name="$routeSectors" exact="$pathSector2"/>
              <set_value name="$lastRouteSector" exact="$pathSector2"/>
            </do_if>
          </do_if>
        </do_all>
        <do_if value="$lastRouteSector != $sellSector">
          <append_to_list name="$routeSectors" exact="$sellSector"/>
        </do_if>

        <set_value name="$isLegal" exact="true"/>
        <set_value name="$blockedSector" exact="null"/>
        <set_value name="$blockedPolice" exact="null"/>
        <set_value name="$reason" exact="'ok'"/>
        <do_all exact="$routeSectors.count" counter="$rlLi">
          <do_if value="$isLegal">
            <set_value name="$checkSector" exact="$routeSectors.{$rlLi}"/>
            <do_if value="$checkSector? and $checkSector.exists and $checkSector.policefaction and ($checkSector.policefaction != $shipOwner)">
              <do_if value="$ware.illegalto.{$checkSector.policefaction}.{$shipOwner}">
                <set_value name="$isLegal" exact="false"/>
                <set_value name="$blockedSector" exact="$checkSector"/>
                <set_value name="$blockedPolice" exact="$checkSector.policefaction"/>
                <set_value name="$reason" exact="'illegal_on_route'"/>
              </do_if>
            </do_if>
          </do_if>
        </do_all>

        <set_value name="$result.$IsLegal" exact="$isLegal"/>
        <set_value name="$result.$Reason" exact="$reason"/>
        <set_value name="$result.$BlockedSector" exact="$blockedSector"/>
        <set_value name="$result.$BlockedPoliceFaction" exact="$blockedPolice"/>
        <do_if value="$blockedSector? and $blockedSector.exists">
          <set_value name="$result.$BlockedSectorName" exact="@$blockedSector.knownname"/>
        </do_if>
        <do_if value="$blockedPolice?">
          <set_value name="$result.$BlockedPoliceName" exact="@$blockedPolice.knownname"/>
        </do_if>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Calculate Trade Route Distance -->
    <library name="GT_CalculateTradeRouteDistance" purpose="run_actions">
      <params>
        <param name="homeSector" comment="Home/base sector"/>
        <param name="buyStation" comment="Buy station (or buy station sector)"/>
        <param name="sellStation" comment="Sell station (or sell station sector)"/>
      </params>
      <actions>
        <!-- Extract sectors from stations if needed -->
        <set_value name="$buySector" exact="$buyStation"/>
        <do_if value="$buyStation.isclass.station">
          <set_value name="$buySector" exact="$buyStation.sector"/>
        </do_if>
        <set_value name="$sellSector" exact="$sellStation"/>
        <do_if value="$sellStation.isclass.station">
          <set_value name="$sellSector" exact="$sellStation.sector"/>
        </do_if>
        
        <!-- Calculate distance from home to buy station -->
        <set_value name="$buyDistance" exact="0"/>
        <do_if value="$homeSector == $buySector">
          <set_value name="$buyDistance" exact="0"/>
        </do_if>
        <do_else>
          <set_value name="$buyDistance" exact="$homeSector.gatedistance.{$buySector}"/>
        </do_else>
        
        <!-- Calculate distance from buy station to sell station (route distance) -->
        <set_value name="$routeDistance" exact="0"/>
        <do_if value="$buySector == $sellSector">
          <set_value name="$routeDistance" exact="0"/>
        </do_if>
        <do_else>
          <set_value name="$routeDistance" exact="$buySector.gatedistance.{$sellSector}"/>
        </do_else>
        
        <!-- Return total route distance (home buy sell) -->
        <return value="$buyDistance + $routeDistance"/>
      </actions>
    </library>
    
    <!-- Calculate Range-Only Distance (Universal Cache Validation) -->
    <!-- OPTIMIZATION: Uses global sector distance cache to avoid redundant gatedistance API calls -->
    <!-- Gate distances only change when gates are built/destroyed (extremely rare) -->
    <library name="GT_CalculateRangeOnlyDistance" purpose="run_actions">
      <params>
        <param name="fromSector" comment="Source sector (typically home sector)"/>
        <param name="toSector" comment="Destination sector"/>
      </params>
      <actions>
        <!-- UNIVERSAL CACHE: Use range-only distance (NO blacklist params) -->
        <!-- Same sector = 0, otherwise use cached gatedistance -->
        <!-- Defensive: if sectors are missing/null, treat as unreachable -->
        <do_if value="not $fromSector? or $fromSector == null or not $toSector? or $toSector == null">
          <return value="-1"/>
        </do_if>
        <do_if value="$fromSector == $toSector">
          <return value="0"/>
        </do_if>
        <do_else>
          <!-- Check global sector distance cache first -->
          <do_if value="global.$GT_SectorDistanceCache? and global.$GT_SectorDistanceCache.{$fromSector}? and global.$GT_SectorDistanceCache.{$fromSector}.{$toSector}?">
            <return value="global.$GT_SectorDistanceCache.{$fromSector}.{$toSector}"/>
          </do_if>
          <!-- Cache miss: compute and store -->
          <set_value name="$dist" exact="$fromSector.gatedistance.{$toSector}"/>
          <!-- Initialize nested table if needed -->
          <do_if value="not global.$GT_SectorDistanceCache?">
            <set_value name="global.$GT_SectorDistanceCache" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_SectorDistanceCache.{$fromSector}?">
            <set_value name="global.$GT_SectorDistanceCache.{$fromSector}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_SectorDistanceCache.{$fromSector}.{$toSector}" exact="$dist"/>
          <return value="$dist"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Calculate Station Distance Cache -->
    <library name="GT_CalculateStationDistanceCache" purpose="run_actions">
      <params>
        <param name="stations" comment="List of stations to calculate distances for"/>
        <param name="homeSector" comment="Home/base sector for distance calculation"/>
      </params>
      <actions>
        <set_value name="$distanceCache" exact="table[]"/>
        <do_all exact="$stations.count" counter="$i">
          <set_value name="$station" exact="$stations.{$i}"/>
          <do_if value="not $distanceCache.{$station}?">
            <!-- UNIVERSAL CACHE: Use range-only distance (using library function) -->
            <set_value name="$targetSector" exact="$station.sector"/>
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculateRangeOnlyDistance" result="$distanceCache.{$station}">
              <param name="fromSector" value="$homeSector"/>
              <param name="toSector" value="$targetSector"/>
            </run_actions>
          </do_if>
        </do_all>
        <return value="$distanceCache"/>
      </actions>
    </library>
    
    <!-- Calculate Trade Path Distances (with escape logic) -->
    <library name="GT_CalculateTradePathDistances" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship for pathfinding"/>
        <param name="currentSector" comment="Ship's current sector"/>
        <param name="buySector" comment="Buy station sector"/>
        <param name="sellSector" comment="Sell station sector"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group"/>
      </params>
      <actions>
        <!-- FIX: Handle same-sector cases first (ship already there = 0 distance) -->
        <!-- If ship is in blacklisted sector, allow trades where ship stays in same sector OR escapes -->
        <set_value name="$buyPathDistance" exact="-1"/>
        <set_value name="$sellPathDistance" exact="-1"/>
        
        <!-- ESCAPE LOGIC: Buy path calculation with escape support -->
        <!-- Check if current sector is blacklisted for escape logic -->
        <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$currentSectorIsBlacklistedForEscape">
          <param name="sector" value="$currentSector"/>
          <param name="ship" value="$ship"/>
          <param name="blacklistgroup" value="$blacklistgroup"/>
        </run_actions>
        
        <!-- Buy path calculation -->
        <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$buyPathDistance">
          <param name="ship" value="$ship"/>
          <param name="fromSector" value="$currentSector"/>
          <param name="toSector" value="$buySector"/>
          <param name="blacklistgroup" value="$blacklistgroup"/>
          <param name="useEscapeMode" value="$currentSectorIsBlacklistedForEscape"/>
        </run_actions>
        
        <!-- Sell path calculation -->
        <!-- CRITICAL: If ship is in blacklisted sector and buy is same sector, use ship position (not buy sector) -->
        <!-- This allows escape: ship in Lasting Vengeance buy in Lasting Vengeance sell in safe sector -->
        <do_if value="$sellSector == $buySector">
          <!-- Buy and sell in same sector -->
          <set_value name="$sellPathDistance" exact="0"/>
        </do_if>
        <do_elseif value="$sellSector == $currentSector">
          <!-- ISOLATION FIX: Sell sector is current sector (intra-sector trade) - distance is 0 -->
          <set_value name="$sellPathDistance" exact="0"/>
        </do_elseif>
        <do_elseif value="$buySector == $currentSector">
          <!-- Ship is in buy sector (same as current) - check path FROM ship's current position to sell sector -->
          <!-- This handles escape case: ship in blacklisted sector, staying there to buy, then selling in safe sector -->
          <!-- ESCAPE LOGIC: If ship is in blacklisted sector, use NON-blacklist-aware gatedistance to find ANY path -->
          <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$sellPathDistance">
            <param name="ship" value="$ship"/>
            <param name="fromSector" value="$currentSector"/>
            <param name="toSector" value="$sellSector"/>
            <param name="blacklistgroup" value="$blacklistgroup"/>
            <param name="useEscapeMode" value="$currentSectorIsBlacklistedForEscape"/>
          </run_actions>
        </do_elseif>
        <do_else>
          <!-- Normal case: Need to travel from buy to sell sector -->
          <!-- Note: GT_CalculatePathDistance uses ship.gatedistance, but here we need buySector.gatedistance -->
          <!-- For sector-to-sector distance, calculate manually -->
          <do_if value="$buySector == $sellSector">
            <set_value name="$sellPathDistance" exact="0"/>
          </do_if>
          <do_else>
            <set_value name="$sellPathDistance" exact="$buySector.gatedistance.{$sellSector}.{$blacklistgroup}.{$ship}"/>
          </do_else>
        </do_else>
        
        <!-- Check if paths are reachable -->
        <set_value name="$isReachable" exact="($buyPathDistance ge 0 and $sellPathDistance ge 0)"/>
        
        <!-- Check if intra-sector trade -->
        <run_actions ref="md.GT_Libraries_General.GT_IsIntraSectorTrade" result="$isIntraSectorTrade">
          <param name="buySector" value="$buySector"/>
          <param name="sellSector" value="$sellSector"/>
          <param name="currentSector" value="$currentSector"/>
        </run_actions>
        
        <!-- Return result table -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$BuyPathDistance" exact="$buyPathDistance"/>
        <set_value name="$result.$SellPathDistance" exact="$sellPathDistance"/>
        <set_value name="$result.$IsReachable" exact="$isReachable"/>
        <set_value name="$result.$IsIntraSectorTrade" exact="$isIntraSectorTrade"/>
        <set_value name="$result.$CurrentSectorIsBlacklisted" exact="$currentSectorIsBlacklistedForEscape"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Check if Station is Reachable -->
    <library name="GT_IsStationReachable" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship for pathfinding"/>
        <param name="station" comment="Station to check reachability for"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group (will be auto-determined if null)"/>
        <param name="returnDetails" default="false" comment="If true, returns table with detailed results"/>
      </params>
      <actions>
        <!-- Initialize result -->
        <set_value name="$isReachable" exact="false"/>
        <set_value name="$failureReason" exact="''"/>
        
        <!-- Check 1: Station exists -->
        <do_if value="not $station? or not $station.exists">
          <set_value name="$failureReason" exact="'Station does not exist'"/>
          <do_if value="$returnDetails">
            <set_value name="$result" exact="table[]"/>
            <set_value name="$result.$IsReachable" exact="false"/>
            <set_value name="$result.$FailureReason" exact="$failureReason"/>
            <set_value name="$result.$StationKnown" exact="false"/>
            <set_value name="$result.$BasicPathDistance" exact="-1"/>
            <set_value name="$result.$BlacklistAwarePathDistance" exact="-1"/>
            <return value="$result"/>
          </do_if>
          <do_else>
            <return value="false"/>
          </do_else>
        </do_if>
        
        <!-- Check 2: Station is known to player OR ship is in same zone/sector -->
        <!-- FIX: Use correct property syntax - $station.isknown (not player.entity.isknown.{$station}) -->
        <!-- FIX: If ship is in same zone as station, skip "known" check (ship can see it) -->
        <set_value name="$sameZone" exact="$ship.zone == $station.zone"/>
        <set_value name="$sameSector" exact="$ship.sector == $station.sector"/>
        <set_value name="$stationIsKnown" exact="@$station.isknown"/>
        
        <!-- Station is accessible if: known to player OR ship is in same zone/sector -->
        <set_value name="$stationAccessible" exact="$stationIsKnown or $sameZone or $sameSector"/>
        
        <do_if value="not $stationAccessible">
          <set_value name="$failureReason" exact="'Station not known to player and not in same zone/sector'"/>
          <do_if value="$returnDetails">
            <set_value name="$result" exact="table[]"/>
            <set_value name="$result.$IsReachable" exact="false"/>
            <set_value name="$result.$FailureReason" exact="$failureReason"/>
            <set_value name="$result.$StationKnown" exact="$stationIsKnown"/>
            <set_value name="$result.$BasicPathDistance" exact="-1"/>
            <set_value name="$result.$BlacklistAwarePathDistance" exact="-1"/>
            <return value="$result"/>
          </do_if>
          <do_else>
            <return value="false"/>
          </do_else>
        </do_if>
        
        <!-- Check 3: If ship and station are in same zone, they're reachable (no pathfinding needed) -->
        <do_if value="$sameZone">
          <!-- Ship is in same zone as station - can reach directly -->
          <set_value name="$isReachable" exact="true"/>
          <set_value name="$basicPathDistance" exact="0"/>
          <set_value name="$blacklistAwarePathDistance" exact="0"/>
        </do_if>
        <do_else>
          <!-- Different zones - need to check pathfinding -->
          <!-- Get blacklist group if not provided -->
          <do_if value="not $blacklistgroup? or $blacklistgroup == null">
            <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
              <param name="ship" value="$ship"/>
            </run_actions>
          </do_if>
          
          <!-- Check 3a: Basic path (what vanilla's move.generic checks) -->
          <set_value name="$basicPathDistance" exact="$ship.gatedistance.{$station}"/>
          
          <!-- Check 3b: Blacklist-aware path (what we want to use) -->
          <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$blacklistAwarePathDistance">
            <param name="ship" value="$ship"/>
            <param name="fromSector" value="$ship.sector"/>
            <param name="toSector" value="$station.sector"/>
            <param name="blacklistgroup" value="$blacklistgroup"/>
            <param name="useEscapeMode" value="false"/>
          </run_actions>
          
          <!-- Determine if reachable (both paths must exist) -->
          <do_if value="$basicPathDistance lt 0">
            <set_value name="$failureReason" exact="'No basic path exists (distance: ' + $basicPathDistance + ')'"/>
          </do_if>
          <do_elseif value="$blacklistAwarePathDistance lt 0">
            <set_value name="$failureReason" exact="'No blacklist-aware path exists (distance: ' + $blacklistAwarePathDistance + ')'"/>
          </do_elseif>
          <do_else>
            <set_value name="$isReachable" exact="true"/>
          </do_else>
        </do_else>
        
        <!-- Return result -->
        <do_if value="$returnDetails">
          <set_value name="$result" exact="table[]"/>
          <set_value name="$result.$IsReachable" exact="$isReachable"/>
          <set_value name="$result.$FailureReason" exact="$failureReason"/>
          <set_value name="$result.$StationKnown" exact="$stationIsKnown"/>
          <set_value name="$result.$BasicPathDistance" exact="$basicPathDistance"/>
          <set_value name="$result.$BlacklistAwarePathDistance" exact="$blacklistAwarePathDistance"/>
          <return value="$result"/>
        </do_if>
        <do_else>
          <return value="$isReachable"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Find Sectors In Range (Vanilla Pattern) -->
    <!-- Replicates vanilla lib.find.sectors.inrange logic for MD scripts -->
    <!-- Pre-filters sectors by gate distance and blacklist BEFORE native trade queries -->
    <!-- CRITICAL: Vanilla pattern using find_cluster_in_range -->
    <library name="GT_FindSectorsInRange" purpose="run_actions">
      <params>
        <param name="refobject" comment="Reference object (sector/station) from which gate distance is measured"/>
        <param name="mingatedistance" default="0" comment="Minimum gate distance from refobject"/>
        <param name="maxgatedistance" default="1" comment="Maximum gate distance from refobject"/>
        <param name="ship" comment="Ship for blacklist checks"/>
        <param name="blacklistgroup" default="null" comment="Blacklist group (auto-determined if null)"/>
        <param name="applyblacklist" default="true" comment="Apply blacklist filtering"/>
        <param name="sectorWhitelist" default="null" comment="List of sectors to exclude from blacklist checks (if null, will be auto-determined from ship's order)"/>
      </params>
      <actions>
        <!-- Get blacklist group if not provided -->
        <do_if value="not $blacklistgroup? or $blacklistgroup == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        
        <!-- Get whitelist if not provided -->
        <set_value name="$whitelist" exact="[]"/>
        <do_if value="not $sectorWhitelist? or $sectorWhitelist == null">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetSectorWhitelist" result="$whitelist">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        <do_else>
          <set_value name="$whitelist" exact="$sectorWhitelist"/>
        </do_else>
        
        <!-- Extract reference sector from refobject -->
        <set_value name="$refsector" exact="null"/>
        
        <!-- Validate refobject exists and is valid -->
        <do_if value="not $refobject? or not $refobject.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Pathfinding] ERROR: refobject is null or does not exist in GT_FindSectorsInRange'" chance="100"/>
          </do_if>
          <return value="[]"/>
        </do_if>
        
        <!-- Check if refobject is a sector -->
        <do_if value="$refobject.isclass.sector">
          <set_value name="$refsector" exact="$refobject"/>
        </do_if>
        <!-- Check if refobject has a sector property (station, ship, etc.) -->
        <do_elseif value="$refobject.sector?">
          <set_value name="$refsector" exact="$refobject.sector"/>
        </do_elseif>
        <!-- Check if refobject has a zone property - try to get sector from zone -->
        <do_elseif value="$refobject.zone?">
          <set_value name="$refzone" exact="$refobject.zone"/>
          <do_if value="$refzone.sector?">
            <set_value name="$refsector" exact="$refzone.sector"/>
          </do_if>
          <do_elseif value="$refzone.destination? and $refzone.destination.sector?">
            <!-- Highway zone - use destination sector -->
            <set_value name="$refsector" exact="$refzone.destination.sector"/>
          </do_elseif>
        </do_elseif>
        
        <!-- Validate refsector -->
        <do_if value="not $refsector? or not $refsector.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Pathfinding] ERROR: Failed to extract sector from refobject in GT_FindSectorsInRange (refobject type: ' + (if $refobject.isclass? then 'has isclass' else 'no isclass') + ')'" chance="100"/>
          </do_if>
          <return value="[]"/>
        </do_if>
        
        <!-- Get commander sector (ships can always operate in commander's sector regardless of blacklist) -->
        <set_value name="$commandersector" exact="null"/>
        <do_if value="$ship.commander? and $ship.commander.exists">
          <set_value name="$commandersector" exact="@$ship.commander.sector"/>
        </do_if>
        
        <!-- Get ship's current sector (fallback if all sectors blacklisted) -->
        <set_value name="$mysector" exact="$ship.sector"/>
        <do_if value="@$ship.zone.issuperhighway">
          <set_value name="$mysector" exact="@$ship.zone.destination.sector"/>
        </do_if>
        
        <!-- Use native find_cluster_in_range to find sectors within range -->
        <!-- This is the vanilla pattern - uses native C++ pathfinding for performance -->
        <set_value name="$locclusters" exact="table[]"/>
        <find_cluster_in_range distances="$locclusters" multiple="true" object="$refobject" mindistance="$mingatedistance" maxdistance="$maxgatedistance"/>
        
        <!-- Build sector table from clusters -->
        <set_value name="$sectortable" exact="table[]"/>
        <do_for_each name="$loccluster" valuename="$jumpdist" in="$locclusters">
          <find_sector name="$sectorlist" space="$loccluster" multiple="true"/>
          <do_if value="$sectorlist.count == 1">
            <!-- Single-sector cluster -->
            <set_value name="$locsector" exact="$sectorlist.{1}"/>
            <do_if value="not player.entity.isknown.{$locsector}? or @player.entity.isknown.{$locsector}">
              <!-- Check gate distance (for multi-sector clusters with one-way superhighways) -->
              <set_value name="$locgatedist" exact="$refsector.gatedistance.{$locsector}"/>
              <do_if value="($locgatedist ge 0) and ($locgatedist ge $mingatedistance) and ($locgatedist le $maxgatedistance)">
                <!-- Check return path distance -->
                <set_value name="$locreturngatedist" exact="$locsector.gatedistance.{$refsector}"/>
                <do_if value="($locreturngatedist ge 0) and ($locreturngatedist le $maxgatedistance)">
                  <!-- Apply blacklist filtering if enabled -->
                  <set_value name="$sectorValid" exact="true"/>
                  <do_if value="$applyblacklist">
                    <!-- Always allow commander's sector and ship's current sector -->
                    <do_if value="$locsector != $commandersector and $locsector != $mysector">
                      <!-- Check whitelist first: if sector is in whitelist, it's allowed -->
                      <set_value name="$isWhitelisted" exact="false"/>
                      <do_if value="(if $whitelist != null then $whitelist.count else 0) gt 0">
                        <do_all exact="$whitelist.count" counter="$w">
                          <do_if value="$whitelist.{$w} == $locsector">
                            <set_value name="$isWhitelisted" exact="true"/>
                            <break/>
                          </do_if>
                        </do_all>
                      </do_if>
                      
                      <!-- Only check blacklist if not whitelisted -->
                      <do_if value="not $isWhitelisted">
                        <!-- Check blacklist (sectoractivity AND sectortravel) -->
                        <set_value name="$sectorActivityBlacklisted" exact="@$locsector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship}"/>
                        <set_value name="$sectorTravelBlacklisted" exact="@$locsector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{$ship}"/>
                        <do_if value="$sectorActivityBlacklisted or $sectorTravelBlacklisted">
                          <set_value name="$sectorValid" exact="false"/>
                        </do_if>
                      </do_if>
                      <do_else>
                        <!-- Check blacklist-aware path distance (for return path) -->
                        <set_value name="$blacklistAwareDist" exact="$refsector.gatedistance.{$locsector}.{$blacklistgroup}.{$ship}"/>
                        <do_if value="$blacklistAwareDist lt 0">
                          <!-- No blacklist-aware path exists -->
                          <set_value name="$sectorValid" exact="false"/>
                        </do_if>
                        <do_else>
                          <!-- Check return path with blacklist -->
                          <set_value name="$blacklistAwareReturnDist" exact="$locsector.gatedistance.{$refsector}.{$blacklistgroup}.{$ship}"/>
                          <do_if value="$blacklistAwareReturnDist lt 0 or $blacklistAwareReturnDist gt $maxgatedistance">
                            <set_value name="$sectorValid" exact="false"/>
                          </do_if>
                        </do_else>
                      </do_else>
                    </do_if>
                  </do_if>
                  
                  <!-- Add sector if valid -->
                  <do_if value="$sectorValid">
                    <set_value name="$sectortable.{$locsector}" exact="$locgatedist"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Multi-sector cluster -->
            <do_for_each name="$locsector" in="$sectorlist">
              <do_if value="not player.entity.isknown.{$locsector}? or @player.entity.isknown.{$locsector}">
                <!-- Check gate distance -->
                <set_value name="$locgatedist" exact="$refsector.gatedistance.{$locsector}"/>
                <do_if value="($locgatedist ge 0) and ($locgatedist ge $mingatedistance) and ($locgatedist le $maxgatedistance)">
                  <!-- Check return path distance -->
                  <set_value name="$locreturngatedist" exact="$locsector.gatedistance.{$refsector}"/>
                  <do_if value="($locreturngatedist ge 0) and ($locreturngatedist le $maxgatedistance)">
                    <!-- Apply blacklist filtering if enabled -->
                    <set_value name="$sectorValid" exact="true"/>
                    <do_if value="$applyblacklist">
                      <!-- Always allow commander's sector and ship's current sector -->
                      <do_if value="$locsector != $commandersector and $locsector != $mysector">
                        <!-- Check whitelist first: if sector is in whitelist, it's allowed -->
                        <set_value name="$isWhitelisted" exact="false"/>
                        <do_if value="(if $whitelist != null then $whitelist.count else 0) gt 0">
                          <do_all exact="$whitelist.count" counter="$w">
                            <do_if value="$whitelist.{$w} == $locsector">
                              <set_value name="$isWhitelisted" exact="true"/>
                              <break/>
                            </do_if>
                          </do_all>
                        </do_if>
                        
                        <!-- Only check blacklist if not whitelisted -->
                        <do_if value="not $isWhitelisted">
                          <!-- Check blacklist (sectoractivity AND sectortravel) -->
                          <set_value name="$sectorActivityBlacklisted" exact="@$locsector.isblacklisted.{blacklisttype.sectoractivity}.{$blacklistgroup}.{$ship}"/>
                          <set_value name="$sectorTravelBlacklisted" exact="@$locsector.isblacklisted.{blacklisttype.sectortravel}.{$blacklistgroup}.{$ship}"/>
                          <do_if value="$sectorActivityBlacklisted or $sectorTravelBlacklisted">
                            <set_value name="$sectorValid" exact="false"/>
                          </do_if>
                        </do_if>
                        <do_else>
                          <!-- Check blacklist-aware path distance -->
                          <set_value name="$blacklistAwareDist" exact="$refsector.gatedistance.{$locsector}.{$blacklistgroup}.{$ship}"/>
                          <do_if value="$blacklistAwareDist lt 0">
                            <set_value name="$sectorValid" exact="false"/>
                          </do_if>
                          <do_else>
                            <!-- Check return path with blacklist -->
                            <set_value name="$blacklistAwareReturnDist" exact="$locsector.gatedistance.{$refsector}.{$blacklistgroup}.{$ship}"/>
                            <do_if value="$blacklistAwareReturnDist lt 0 or $blacklistAwareReturnDist gt $maxgatedistance">
                              <set_value name="$sectorValid" exact="false"/>
                            </do_if>
                          </do_else>
                        </do_else>
                      </do_if>
                    </do_if>
                    
                    <!-- Add sector if valid -->
                    <do_if value="$sectorValid">
                      <set_value name="$sectortable.{$locsector}" exact="$locgatedist"/>
                    </do_if>
                  </do_if>
                </do_if>
              </do_if>
            </do_for_each>
          </do_else>
        </do_for_each>
        
        <!-- If mingatedistance <= 0, include the refsector itself -->
        <do_if value="($mingatedistance le 0) and not $sectortable.{$refsector}?">
          <set_value name="$sectortable.{$refsector}" exact="0"/>
        </do_if>
        
        <!-- If no valid sectors found (probably due to blacklist), add ship's current sector as fallback -->
        <do_if value="not $sectortable.keys.count">
          <do_if value="@$mysector.exists">
            <set_value name="$sectortable.{$mysector}" exact="0"/>
          </do_if>
        </do_if>
        
        <!-- Sort sectors by gate distance (vanilla pattern) -->
        <set_value name="$spaces" exact="$sectortable.keys.list"/>
        <shuffle_list list="$spaces"/>
        <sort_list list="$spaces" sortbyvalue="$sectortable.{loop.element}"/>
        
        <!-- If mingatedistance <= 0, ensure refsector is first -->
        <do_if value="($mingatedistance le 0) and $refsector?">
          <!-- FIX: Use explicit loop to check if refsector is in spaces -->
          <set_value name="$refSectorInList" exact="false"/>
          <do_all exact="$spaces.count" counter="$i">
            <do_if value="$spaces.{$i} == $refsector">
              <set_value name="$refSectorInList" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          
          <do_if value="not $refSectorInList">
            <set_value name="$spaces.{1}" exact="$refsector" operation="insert"/>
          </do_if>
        </do_if>
        
        <!-- If still no sectors, add ship's current sector -->
        <do_if value="not $spaces.count">
          <do_if value="@$mysector.exists">
            <set_value name="$spaces.{1}" exact="$mysector" operation="insert"/>
          </do_if>
        </do_if>
        
        <!-- Return sorted list of sectors -->
        <return value="$spaces"/>
      </actions>
    </library>
    
    <!-- Build Station Distance Cache from Offers -->
    <library name="GT_BuildStationDistanceCache" purpose="run_actions">
      <params>
        <param name="sellOffers" comment="List of sell offers"/>
        <param name="buyOffers" comment="List of buy offers"/>
        <param name="homeSector" comment="Home/base sector for distance calculation"/>
      </params>
      <actions>
        <!-- Extract unique stations from offers -->
        <set_value name="$sellStations" exact="[]"/>
        <set_value name="$buyStations" exact="[]"/>
        <set_value name="$sellStationsSeen" exact="table[]"/>
        <set_value name="$buyStationsSeen" exact="table[]"/>
        <do_all exact="$sellOffers.count" counter="$i">
          <set_value name="$station" exact="$sellOffers.{$i}.owner"/>
          <do_if value="not $sellStationsSeen.{$station}?">
            <set_value name="$sellStationsSeen.{$station}" exact="true"/>
            <append_to_list name="$sellStations" exact="$station"/>
          </do_if>
        </do_all>
        <do_all exact="$buyOffers.count" counter="$i">
          <set_value name="$station" exact="$buyOffers.{$i}.owner"/>
          <do_if value="not $buyStationsSeen.{$station}?">
            <set_value name="$buyStationsSeen.{$station}" exact="true"/>
            <append_to_list name="$buyStations" exact="$station"/>
          </do_if>
        </do_all>
        <!-- Calculate distance cache for sell stations -->
        <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculateStationDistanceCache" result="$sellDistanceCache">
          <param name="stations" value="$sellStations"/>
          <param name="homeSector" value="$homeSector"/>
        </run_actions>
        <!-- Calculate distance cache for buy stations -->
        <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculateStationDistanceCache" result="$buyDistanceCache">
          <param name="stations" value="$buyStations"/>
          <param name="homeSector" value="$homeSector"/>
        </run_actions>
        <!-- Merge caches -->
        <set_value name="$stationDistanceCache" exact="table[]"/>
        <do_all exact="$sellStations.count" counter="$i">
          <set_value name="$station" exact="$sellStations.{$i}"/>
          <set_value name="$stationDistanceCache.{$station}" exact="$sellDistanceCache.{$station}"/>
        </do_all>
        <do_all exact="$buyStations.count" counter="$i">
          <set_value name="$station" exact="$buyStations.{$i}"/>
          <set_value name="$stationDistanceCache.{$station}" exact="$buyDistanceCache.{$station}"/>
        </do_all>
        <return value="$stationDistanceCache"/>
      </actions>
    </library>
    
    <!-- Build Trade Sector Lists -->
    <!-- CRITICAL: Vanilla pattern using find_cluster_in_range -->
    <library name="GT_BuildTradeSectorLists" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to build sector lists for"/>
        <param name="homeSector" comment="Home sector for distance calculations"/>
        <param name="maxDistance" comment="Maximum gate distance"/>
        <param name="blacklistgroup" comment="Blacklist group for filtering"/>
      </params>
      <actions>
        <!-- Builds sector lists for trade searches with isolation handling -->
        <!-- Returns: $buyspaces, $sellspaces, $shipIsIsolated -->
        <!-- For isolated ships: Uses current sector only -->
        <!-- For normal ships: Uses GT_FindSectorsInRange to build lists -->
        <set_value name="$currentSector" exact="$ship.sector"/>
        <set_value name="$shipIsIsolated" exact="false"/>
        <set_value name="$buyspaces" exact="[]"/>
        <set_value name="$sellspaces" exact="[]"/>
        
        <!-- Check if ship is isolated -->
        <do_if value="$currentSector?">
          <run_actions ref="md.GT_Libraries_Blacklist.GT_CheckConnectedSectorsBlacklisted" result="$isolationCheck">
            <param name="sector" value="$currentSector"/>
            <param name="ship" value="$ship"/>
            <param name="returnDetails" value="false"/>
          </run_actions>
          <set_value name="$isolatedValue" exact="@$isolationCheck.$IsIsolated"/>
          <set_value name="$shipIsIsolated" exact="if $isolatedValue? and ($isolatedValue == true or $isolatedValue == 1) then true else false"/>
          <do_if value="$shipIsIsolated">
            <!-- Ship is isolated - use current sector only -->
            <set_value name="$buyspaces" exact="[$currentSector]"/>
            <set_value name="$sellspaces" exact="[$currentSector]"/>
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$sectorName" exact="@$currentSector.knownname"/>
              <debug_text text="'[GT-Search] (' + $ship.idcode + ') ðŸ”’ ISOLATED: Using current sector only: ' + (if $sectorName? then $sectorName else 'NULL') + ' (price range expanded)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Build sector lists for non-isolated ships -->
        <do_if value="not $shipIsIsolated">
          <!-- Build buy sector list (sectors where ship can buy from) -->
          <run_actions ref="md.GT_Libraries_Pathfinding.GT_FindSectorsInRange" result="$buyspaces">
            <param name="refobject" value="$homeSector"/>
            <param name="mingatedistance" value="0"/>
            <param name="maxgatedistance" value="$maxDistance"/>
            <param name="ship" value="$ship"/>
            <param name="blacklistgroup" value="$blacklistgroup"/>
            <param name="applyblacklist" value="true"/>
          </run_actions>
          
          <!-- Build sell sector list (sectors where ship can sell to) -->
          <!-- For now, use same range as buy (can be optimized later if maxbuy != maxsell) -->
          <set_value name="$sellspaces" exact="$buyspaces"/>
          
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Search] (' + $ship.idcode + ') VANILLA PATTERN: Built sector lists - ' + $buyspaces.count + ' buy sectors, ' + $sellspaces.count + ' sell sectors (max distance: ' + $maxDistance + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$BuySpaces" exact="$buyspaces"/>
        <set_value name="$result.$SellSpaces" exact="$sellspaces"/>
        <set_value name="$result.$ShipIsIsolated" exact="$shipIsIsolated"/>
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- ========================================= -->
    <!-- INCREMENTAL RADIUS SEARCH (Cue-Based) -->
    <!-- ========================================= -->
    
    <!-- Pathfinding Queue Processor -->
    <!-- Manages concurrency for pathfinding instances to prevent CPU spikes -->
    <cue name="ProcessPathfindingQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- CPU YIELDING: Prevent queue-drain avalanches in a single frame when many ships request pathfinding at once -->
      <delay exact="10ms"/>
      <actions>
        <!-- PROOF (once): confirm that the queue processor is actually executing in this game instance -->
        <do_if value="not global.$GT_Pathfinding_Proof?">
          <set_value name="global.$GT_Pathfinding_Proof" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Pathfinding_Proof.$QueueProcessorRan?">
          <set_value name="global.$GT_Pathfinding_Proof.$QueueProcessorRan" exact="true"/>
          <debug_text text="'[GT-Pathfinding] ProcessPathfindingQueue running (requests=' + (if global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$Requests? then global.$GT_PathfindingQueue.$Requests.count else 0) + ')'" chance="100"/>
        </do_if>

        <!-- Initialize queue properties if they don't exist -->
        <do_if value="not global.$GT_PathfindingQueue?">
          <set_value name="global.$GT_PathfindingQueue" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_PathfindingQueue.$Requests? or global.$GT_PathfindingQueue.$Requests == null">
          <set_value name="global.$GT_PathfindingQueue.$Requests" exact="[]"/>
        </do_if>
        <do_if value="not global.$GT_PathfindingQueue.$ActiveInstances? or global.$GT_PathfindingQueue.$ActiveInstances == null">
          <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_PathfindingQueue.$MaxConcurrent? or global.$GT_PathfindingQueue.$MaxConcurrent == null">
          <set_value name="global.$GT_PathfindingQueue.$MaxConcurrent" exact="2"/>
        </do_if>
        <do_if value="not global.$GT_PathfindingQueue.$ActiveShips? or global.$GT_PathfindingQueue.$ActiveShips == null">
          <set_value name="global.$GT_PathfindingQueue.$ActiveShips" exact="[]"/>
        </do_if>

        <!-- SANITY: Prevent stale save/crash state from blocking the queue forever -->
        <do_if value="global.$GT_PathfindingQueue.$ActiveInstances lt 0">
          <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" exact="0"/>
        </do_if>
        <do_if value="global.$GT_PathfindingQueue.$MaxConcurrent le 0">
          <set_value name="global.$GT_PathfindingQueue.$MaxConcurrent" exact="2"/>
        </do_if>
        <!-- If counters got out of sync, trust the ActiveShips list -->
        <do_if value="global.$GT_PathfindingQueue.$ActiveInstances gt global.$GT_PathfindingQueue.$ActiveShips.count">
          <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" exact="global.$GT_PathfindingQueue.$ActiveShips.count"/>
        </do_if>

        <!-- DEBUG (throttled): explain why queue is not starting workers when requests are pending -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and global.$GT_PathfindingQueue.$Requests.count gt 0 and global.$GT_PathfindingQueue.$ActiveInstances ge global.$GT_PathfindingQueue.$MaxConcurrent">
          <do_if value="not global.$GT_Pathfinding_Proof.$LastQueueBlockedLogTime?">
            <set_value name="global.$GT_Pathfinding_Proof.$LastQueueBlockedLogTime" exact="0"/>
          </do_if>
          <do_if value="(player.age - global.$GT_Pathfinding_Proof.$LastQueueBlockedLogTime) ge 5s">
            <set_value name="global.$GT_Pathfinding_Proof.$LastQueueBlockedLogTime" exact="player.age"/>
            <debug_text text="'[GT-Pathfinding] Queue BLOCKED (active=' + global.$GT_PathfindingQueue.$ActiveInstances + '/' + global.$GT_PathfindingQueue.$MaxConcurrent + ', activeShips=' + global.$GT_PathfindingQueue.$ActiveShips.count + ', queued=' + global.$GT_PathfindingQueue.$Requests.count + ')'" chance="100"/>
          </do_if>
        </do_if>

        <!-- Process if below max concurrent and there are requests in the queue -->
        <do_if value="global.$GT_PathfindingQueue.$ActiveInstances lt global.$GT_PathfindingQueue.$MaxConcurrent and global.$GT_PathfindingQueue.$Requests.count gt 0">
          <set_value name="$request" exact="global.$GT_PathfindingQueue.$Requests.{1}"/>
          <remove_from_list name="global.$GT_PathfindingQueue.$Requests" exact="$request"/>
          <!-- Mark request as coming FROM the queue. The queue processor already reserves the concurrency slot,
               so the worker must NOT re-apply concurrency gating and re-queue itself (would stall forever). -->
          <set_value name="$request.$FromQueue" exact="true"/>
          
          <set_value name="$ship" exact="$request.$Ship"/>
          <!-- IMPORTANT:
               NEVER drop queued pathfinding requests based on SearchLiveTrades_State lookups.
               If that lookup fails for any reason (object-key mismatch, transient ordering), dropping the request leaves
               SearchTradeRoutes stuck behind "live search already in progress" forever.
               Instead: always run the incremental radius search; SearchLiveTrades_Resume will safely ignore results if
               the live-search state was already cleaned up. -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Pathfinding-Queue] Processing queued pathfinding for ' + $ship.idcode + ' (active: ' + global.$GT_PathfindingQueue.$ActiveInstances + '/' + global.$GT_PathfindingQueue.$MaxConcurrent + ', queued: ' + global.$GT_PathfindingQueue.$Requests.count + ')'" chance="10"/>
          </do_if>

          <!-- DEBUG (once per ship): record that the queue started pathfinding for this ship -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <do_if value="not global.$GT_Pathfinding_Proof.$StartedShips?">
              <set_value name="global.$GT_Pathfinding_Proof.$StartedShips" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Pathfinding_Proof.$StartedShips.{$ship}?">
              <set_value name="global.$GT_Pathfinding_Proof.$StartedShips.{$ship}" exact="player.age"/>
              <debug_text text="'[GT-Pathfinding] Queue STARTED worker for ' + $ship.idcode + ' (active now=' + (global.$GT_PathfindingQueue.$ActiveInstances + 1) + '/' + global.$GT_PathfindingQueue.$MaxConcurrent + ', queued now=' + global.$GT_PathfindingQueue.$Requests.count + ')'" chance="100"/>
            </do_if>
          </do_if>

          <!-- Increment active instances counter -->
          <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="add"/>
          <append_to_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="$ship"/>

          <!-- Signal the actual pathfinding cue -->
          <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch" param="$request"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Incremental Radius Search Cue -->
    <!-- Cue-based pattern with CPU yielding between radius increments -->
    <!-- Phase 1: Detection only - no runtime behavior changes -->
    <!-- Uses recursive signaling pattern (MD script compatible) -->
    <cue name="GT_IncrementalRadiusSearch" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- CPU YIELDING: Delay before each iteration (including recursive signals) -->
      <!-- This ensures CPU is yielded between radius increments, preventing game stutter -->
      <delay exact="25ms"/>
      <actions>
        <!-- Extract parameters from signal -->
        <set_value name="$params" exact="event.param"/>
        <set_value name="$shouldProceed" exact="true"/>
        <set_value name="$fromQueue" exact="false"/>
        <do_if value="$params.$FromQueue? and $params.$FromQueue == true">
          <set_value name="$fromQueue" exact="true"/>
        </do_if>
        
        <!-- Ship object from request -->
        <set_value name="$ship" exact="$params.$Ship"/>

        <!-- PROOF (once): confirm that GT_IncrementalRadiusSearch is actually starting -->
        <do_if value="not global.$GT_Pathfinding_Proof?">
          <set_value name="global.$GT_Pathfinding_Proof" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Pathfinding_Proof.$IncrementalRan?">
          <set_value name="global.$GT_Pathfinding_Proof.$IncrementalRan" exact="true"/>
          <debug_text text="'[GT-Pathfinding] GT_IncrementalRadiusSearch running (ship=' + (if $ship? then $ship.idcode else 'NULL') + ')'" chance="100"/>
        </do_if>
        
        <!-- DEBUG (once per ship): make sure we always get a line for the ships we care about -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <do_if value="not global.$GT_Pathfinding_Proof.$IncrementalStartedShips?">
            <set_value name="global.$GT_Pathfinding_Proof.$IncrementalStartedShips" exact="table[]"/>
          </do_if>
          <do_if value="$ship? and not global.$GT_Pathfinding_Proof.$IncrementalStartedShips.{$ship}?">
            <set_value name="global.$GT_Pathfinding_Proof.$IncrementalStartedShips.{$ship}" exact="player.age"/>
            <!-- NOTE: $isContinuation is initialized below; keep this log null-safe. -->
            <set_value name="$isContinuationForLog" exact="false"/>
            <do_if value="$params.$IsContinuation? and $params.$IsContinuation == true">
              <set_value name="$isContinuationForLog" exact="true"/>
            </do_if>
            <debug_text text="'[GT-Pathfinding] Incremental START for ' + $ship.idcode + ' (fromQueue=' + (if $fromQueue then 1 else 0) + ', isContinuation=' + (if $isContinuationForLog then 1 else 0) + ')'" chance="100"/>
          </do_if>
        </do_if>

        <!-- IMPORTANT:
             Do NOT drop/abort the incremental radius search based on SearchLiveTrades_State lookups.
             In player.log, ships can get stuck if the request is aborted but SearchTradeRoutes still sees an in-progress
             live-search state. SearchLiveTrades_Resume has its own guards and can ignore results if state is missing. -->
        
        <!-- CONCURRENCY CONTROL: Check if this is a NEW request (not continuation) -->
        <!-- Continuation batches (IsContinuation=true) don't need queuing - they're for the same ship -->
        <set_value name="$isContinuation" exact="false"/>
        <do_if value="$params.$IsContinuation? and $params.$IsContinuation == true">
          <set_value name="$isContinuation" exact="true"/>
        </do_if>
        
        <!-- For NEW requests (not continuation), check concurrency before processing.
             IMPORTANT: Requests coming FROM ProcessPathfindingQueue already reserved the slot, so skip gating. -->
        <do_if value="not $isContinuation and not $fromQueue">
          <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$ActiveInstances? and global.$GT_PathfindingQueue.$MaxConcurrent?">
            <do_if value="global.$GT_PathfindingQueue.$ActiveInstances ge global.$GT_PathfindingQueue.$MaxConcurrent">
              <!-- Max concurrent reached - queue this request -->
              <do_if value="not global.$GT_PathfindingQueue.$Requests?">
                <set_value name="global.$GT_PathfindingQueue.$Requests" exact="[]"/>
              </do_if>
              
              <!-- Mark as queued so it will bypass concurrency gating when ProcessPathfindingQueue starts it -->
              <set_value name="$params.$FromQueue" exact="true"/>
              <append_to_list name="global.$GT_PathfindingQueue.$Requests" exact="$params"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$debugShip" exact="@$params.$Ship"/>
                <debug_text text="'[GT-Pathfinding-Queue] Pathfinding queued for ' + (if $debugShip != null then @$debugShip.idcode else 'NULL') + ' (active: ' + global.$GT_PathfindingQueue.$ActiveInstances + '/' + global.$GT_PathfindingQueue.$MaxConcurrent + ')'" chance="10"/>
              </do_if>
              
              <!-- Signal queue processor -->
              <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.ProcessPathfindingQueue"/>
              
              <!-- Cancel this instance - queue will process it -->
              <set_value name="$shouldProceed" exact="false"/>
              <cancel_cue cue="this"/>
            </do_if>
            <do_else>
              <!-- Below max concurrent - increment counter for NEW requests -->
              <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="add"/>
              <do_if value="not global.$GT_PathfindingQueue.$ActiveShips?">
                <set_value name="global.$GT_PathfindingQueue.$ActiveShips" exact="[]"/>
              </do_if>
              <set_value name="$debugShip" exact="@$params.$Ship"/>
              <append_to_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="$debugShip"/>
            </do_else>
          </do_if>
        </do_if>

        <!-- cancel_cue does NOT stop the current actions block; explicitly gate the rest -->
        <do_if value="$shouldProceed">
          <set_value name="$terminated" exact="false"/>
          <!-- Check if this is initialization or continuation -->
          <do_if value="not this.$initialized?">
          <!-- Check if this is a continuation from a previous instance -->
          <do_if value="$params.$IsContinuation? and $params.$IsContinuation == true">
            <!-- CONTINUATION: Restore state from previous instance -->
            <!-- Note: Continuation batches don't increment active counter (same ship) -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$debugShip" exact="@$params.$Ship"/>
              <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: CONTINUATION - Ship=' + (if $debugShip != null then @$debugShip.idcode else 'NULL') + ', Phase=' + $params.$Phase + ', EscapeRadius=' + $params.$EscapeSearchRadius + ', TradeRadius=' + $params.$TradeSearchRadius + ', BuySpaces=' + (if @$params.$BuySpaces != null then @$params.$BuySpaces.count else 0) + ', SellSpaces=' + (if @$params.$SellSpaces != null then @$params.$SellSpaces.count else 0)" chance="10"/>
            </do_if>
            <set_value name="this.$initialized" exact="true"/>
            <set_value name="this.$ship" exact="$params.$Ship"/>
            <set_value name="this.$homeSector" exact="$params.$HomeSector"/>
            <set_value name="this.$maxDistance" exact="$params.$MaxDistance"/>
            <set_value name="this.$blacklistgroup" exact="$params.$BlacklistGroup"/>
            <set_value name="this.$phase" exact="$params.$Phase"/>
            <set_value name="this.$escapeSearchRadius" exact="$params.$EscapeSearchRadius"/>
            <set_value name="this.$tradeSearchRadius" exact="$params.$TradeSearchRadius"/>
            <set_value name="this.$buyspaces" exact="$params.$BuySpaces"/>
            <set_value name="this.$sellspaces" exact="$params.$SellSpaces"/>
            <set_value name="this.$shipIsIsolated" exact="$params.$ShipIsIsolated"/>
            <set_value name="this.$escapeSector" exact="$params.$EscapeSector"/>
            <set_value name="this.$currentSector" exact="$params.$CurrentSector"/>
            <set_value name="this.$currentSectorIsBlacklisted" exact="$params.$CurrentSectorIsBlacklisted"/>
            <set_value name="this.$escapeMaxRadius" exact="10"/>
          </do_if>
          <do_else>
            <!-- INITIALIZATION: First signal - set up state -->
            <set_value name="$ship" exact="$params.$Ship"/>
            <set_value name="$homeSector" exact="$params.$HomeSector"/>
            <set_value name="$maxDistance" exact="$params.$MaxDistance"/>
            <set_value name="$blacklistgroup" exact="$params.$BlacklistGroup"/>
            
            <!-- Debug logging for initialization -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$homeSectorName" exact="@$homeSector.knownname"/>
              <set_value name="$currentSectorName" exact="@$ship.sector.knownname"/>
              <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: INITIALIZATION - Ship=' + $ship.idcode + ', HomeSector=' + (if $homeSectorName? then $homeSectorName else 'NULL') + ', CurrentSector=' + (if $currentSectorName? then $currentSectorName else 'NULL') + ', MaxDistance=' + $maxDistance" chance="10"/>
            </do_if>
            
            <!-- Initialize state in cue instance variables (persists across delays) -->
            <set_value name="this.$initialized" exact="true"/>
            <set_value name="this.$buyspaces" exact="[]"/>
            <set_value name="this.$sellspaces" exact="[]"/>
            <set_value name="this.$shipIsIsolated" exact="false"/>
            <set_value name="this.$escapeSector" exact="null"/>
            <set_value name="this.$currentSector" exact="$ship.sector"/>
            <set_value name="this.$currentSectorIsBlacklisted" exact="false"/>
            <set_value name="this.$escapeSearchRadius" exact="0"/>
            <set_value name="this.$escapeMaxRadius" exact="10"/>
            <set_value name="this.$tradeSearchRadius" exact="0"/>
            <set_value name="this.$phase" exact="'escape'"/>
            <set_value name="this.$ship" exact="$ship"/>
            <set_value name="this.$homeSector" exact="$homeSector"/>
            <set_value name="this.$maxDistance" exact="$maxDistance"/>
            <set_value name="this.$blacklistgroup" exact="$blacklistgroup"/>
            
            <!-- Check if current sector is blacklisted (for escape detection) -->
            <do_if value="this.$currentSector? and $blacklistgroup?">
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="this.$currentSectorIsBlacklisted">
                <param name="sector" value="this.$currentSector"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
              </run_actions>
            </do_if>
            
            <!-- Start with escape path search if current sector is blacklisted -->
            <do_if value="this.$currentSectorIsBlacklisted">
              <set_value name="this.$phase" exact="'escape'"/>
              <set_value name="this.$escapeSearchRadius" exact="0"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: Starting ESCAPE search (current sector blacklisted) - Ship=' + $ship.idcode" chance="10"/>
              </do_if>
            </do_if>
            <do_else>
              <!-- Skip escape search, go directly to trade search -->
              <set_value name="this.$phase" exact="'trade'"/>
              <set_value name="this.$tradeSearchRadius" exact="0"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: Starting TRADE search (current sector not blacklisted) - Ship=' + $ship.idcode" chance="100"/>
              </do_if>
              
              <!-- ISOLATION CHECK (CRITICAL):
                   A ship can be in a non-blacklisted sector but still be effectively isolated if all directly connected sectors
                   (including superhighway/cluster links) are blacklisted for this ship. In that case we must constrain trade search
                   to the current sector only (otherwise home-centered radius search returns sectors the ship cannot reach). -->
              <do_if value="this.$currentSector? and this.$blacklistgroup?">
                <run_actions ref="md.GT_Libraries_Blacklist.GT_CheckConnectedSectorsBlacklisted" result="$isolationCheck">
                  <param name="sector" value="this.$currentSector"/>
                  <param name="ship" value="this.$ship"/>
                  <param name="blacklistgroup" value="this.$blacklistgroup"/>
                  <param name="returnDetails" value="false"/>
                </run_actions>
                <set_value name="$isolatedValue" exact="@$isolationCheck.$IsIsolated"/>
                <do_if value="$isolatedValue? and ($isolatedValue == true or $isolatedValue == 1)">
                  <set_value name="this.$shipIsIsolated" exact="true"/>
                  <set_value name="this.$buyspaces" exact="[this.$currentSector]"/>
                  <set_value name="this.$sellspaces" exact="[this.$currentSector]"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Search] (' + this.$ship.idcode + ') ðŸ”’ ISOLATED (current sector pocket): All connected sectors are blacklisted - using current sector only (' + (if @this.$currentSector.knownname then @this.$currentSector.knownname else 'NULL') + ')'" chance="100"/>
                  </do_if>
                  <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch_Complete" param="this"/>
                  <set_value name="$terminated" exact="true"/>
                  <cancel_cue cue="this"/>
                </do_if>
              </do_if>
            </do_else>
          </do_else>
          </do_if>
        
        <do_if value="not $terminated">
        <!-- CONTINUATION: Process based on current phase -->
        <!-- Escape Path Search Phase -->
        <do_if value="this.$phase == 'escape'">
          <!-- Check if escape path already found or max radius reached -->
          <do_if value="this.$escapeSector? or this.$escapeSearchRadius gt this.$escapeMaxRadius">
            <!-- Escape search complete - transition to trade search or mark as isolated -->
            <do_if value="not this.$escapeSector?">
              <!-- NO ESCAPE PATH FOUND: Mark ship as isolated (Phase 1: detection only) -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Search] (' + this.$ship.idcode + ') âš ï¸ NO ESCAPE PATH FOUND: Ship in blacklisted sector, no valid escape route within range. Ship marked as isolated (Phase 1: detection only).'" chance="100"/>
              </do_if>
              <set_value name="this.$shipIsIsolated" exact="true"/>
              <set_value name="this.$escapeSector" exact="null"/>
              <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch_Complete" param="this"/>
              <set_value name="$terminated" exact="true"/>
              <cancel_cue cue="this"/>
            </do_if>
            <do_else>
              <!-- Escape path found - transition to trade search -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$escapeSectorName" exact="@this.$escapeSector.knownname"/>
                <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: ESCAPE found, transitioning to TRADE search - Ship=' + this.$ship.idcode + ', EscapeSector=' + (if $escapeSectorName? then $escapeSectorName else 'NULL')" chance="10"/>
              </do_if>
              <set_value name="this.$phase" exact="'trade'"/>
              <set_value name="this.$tradeSearchRadius" exact="0"/>
              <!-- Continue to trade search processing below -->
            </do_else>
          </do_if>
          <do_else>
            <!-- Process current escape search radius -->
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_FindSectorsInRange" result="$escapeRadiusSectors">
              <param name="refobject" value="this.$currentSector"/>
              <param name="mingatedistance" value="this.$escapeSearchRadius"/>
              <param name="maxgatedistance" value="this.$escapeSearchRadius"/>
              <param name="ship" value="this.$ship"/>
              <param name="blacklistgroup" value="this.$blacklistgroup"/>
              <param name="applyblacklist" value="false"/>
            </run_actions>
            
            <!-- Check for fallback vs legitimate sectors -->
            <set_value name="$newSectorsFound" exact="false"/>
            <set_value name="$onlyFallbackSector" exact="false"/>
            <do_if value="(if $escapeRadiusSectors != null then $escapeRadiusSectors.count else 0) gt 0">
              <!-- Radius 0: Current sector is expected, always process it -->
              <do_if value="this.$escapeSearchRadius == 0">
                <set_value name="$newSectorsFound" exact="true"/>
              </do_if>
              <do_else>
                <!-- Radius > 0: Check if only current sector returned (fallback) -->
                <set_value name="$onlyCurrentSector" exact="false"/>
                <do_if value="$escapeRadiusSectors.count == 1">
                  <do_if value="$escapeRadiusSectors.{1} == this.$currentSector">
                    <set_value name="$onlyCurrentSector" exact="true"/>
                  </do_if>
                </do_if>
                <do_if value="$onlyCurrentSector and this.$escapeSearchRadius gt 0">
                  <set_value name="$onlyFallbackSector" exact="true"/>
                </do_if>
                <do_else>
                  <set_value name="$newSectorsFound" exact="true"/>
                </do_else>
              </do_else>
            </do_if>
            
            <!-- Process sectors: Radius 0 always processes, radius > 0 processes if legitimate (not fallback) -->
            <do_if value="$newSectorsFound">
              <do_all exact="$escapeRadiusSectors.count" counter="$i">
                <set_value name="$testSector" exact="$escapeRadiusSectors.{$i}"/>
                <do_if value="$testSector?">
                  <set_value name="$testSectorIsBlacklisted" exact="false"/>
                  <set_value name="$testSectorInRange" exact="false"/>
                  
                  <!-- Check if sector is blacklisted -->
                  <do_if value="$testSector? and this.$blacklistgroup?">
                    <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$testSectorIsBlacklisted">
                      <param name="sector" value="$testSector"/>
                      <param name="ship" value="this.$ship"/>
                      <param name="blacklistgroup" value="this.$blacklistgroup"/>
                    </run_actions>
                  </do_if>
                  
                  <!-- Check if candidate sector is within jump distance from HOME sector -->
                  <do_if value="not $testSectorIsBlacklisted and $testSector? and this.$homeSector?">
                    <!-- Special case: home sector is the escape candidate (distance = 0) -->
                    <do_if value="$testSector == this.$homeSector">
                      <set_value name="$distanceFromHome" exact="0"/>
                    </do_if>
                    <do_else>
                      <!-- Calculate distance from home sector to candidate sector -->
                      <set_value name="$distanceFromHome" exact="this.$homeSector.gatedistance.{$testSector}"/>
                    </do_else>
                    <do_if value="$distanceFromHome ge 0 and $distanceFromHome le this.$maxDistance">
                      <set_value name="$testSectorInRange" exact="true"/>
                      <set_value name="$testSectorDistanceFromHome" exact="$distanceFromHome"/>
                    </do_if>
                  </do_if>
                  
                  <!-- First non-blacklisted sector found (within home sector range) = escape path -->
                  <do_if value="not $testSectorIsBlacklisted and $testSectorInRange">
                    <do_if value="not this.$escapeSector?">
                      <!-- First candidate found -->
                      <set_value name="this.$escapeSector" exact="$testSector"/>
                    </do_if>
                    <do_elseif value="$testSectorDistanceFromHome lt this.$homeSector.gatedistance.{this.$escapeSector}">
                      <!-- New candidate is closer to home sector - prefer this one -->
                      <set_value name="this.$escapeSector" exact="$testSector"/>
                    </do_elseif>
                  </do_if>
                </do_if>
              </do_all>
              
              <!-- If escape path found, transition to trade search -->
              <do_if value="this.$escapeSector?">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$escapeSectorName" exact="@this.$escapeSector.knownname"/>
                  <debug_text text="'[GT-Search] (' + this.$ship.idcode + ') ðŸš€ ESCAPE PATH FOUND: ' + (if $escapeSectorName? then $escapeSectorName else 'UNKNOWN') + ' at radius ' + this.$escapeSearchRadius + ' from current position'" chance="100"/>
                </do_if>
                <!-- Escape path found - transition to trade search -->
                <set_value name="this.$phase" exact="'trade'"/>
                <set_value name="this.$tradeSearchRadius" exact="0"/>
              </do_if>
            </do_if>
            
            <!-- Early termination: Only fallback current sector returned = no new sectors found -->
            <do_if value="$onlyFallbackSector">
              <!-- Only current sector returned (fallback) means no new sectors at this radius -->
              <!-- Further radii will also be empty, so stop searching -->
              <set_value name="this.$shipIsIsolated" exact="true"/>
              <set_value name="this.$escapeSector" exact="null"/>
              
              <!-- CONCURRENCY CONTROL: Decrement counter and process queue on completion -->
              <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$ActiveInstances?">
                <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="subtract"/>
                <do_if value="global.$GT_PathfindingQueue.$ActiveShips?">
                  <remove_from_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="this.$ship"/>
                </do_if>
                <!-- Signal queue processor to process next item -->
                <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.ProcessPathfindingQueue"/>
              </do_if>
              
              <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch_Complete" param="this"/>
              <set_value name="$terminated" exact="true"/>
              <cancel_cue cue="this"/>
            </do_if>
            
            <!-- Increment radius for next iteration (if not found and not terminated) -->
            <do_if value="not this.$escapeSector? and not $onlyFallbackSector">
              <set_value name="this.$escapeSearchRadius" operation="add"/>
            </do_if>
          </do_else>
        </do_if>
        </do_if>
        
        <do_if value="not $terminated">
        <!-- Trade Search Phase -->
        <do_if value="this.$phase == 'trade'">
          <!-- Check if max radius reached -->
          <do_if value="this.$tradeSearchRadius gt this.$maxDistance">
            <!-- Trade search complete - signal completion -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: TRADE search COMPLETE (max radius reached) - Ship=' + this.$ship.idcode + ', BuySpaces=' + this.$buyspaces.count + ', SellSpaces=' + this.$sellspaces.count + ', FinalRadius=' + this.$tradeSearchRadius" chance="10"/>
            </do_if>
            
            <!-- CONCURRENCY CONTROL: Decrement counter and process queue on completion -->
            <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$ActiveInstances?">
              <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="subtract"/>
              <do_if value="global.$GT_PathfindingQueue.$ActiveShips?">
                <remove_from_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="this.$ship"/>
              </do_if>
              <!-- Signal queue processor to process next item -->
              <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.ProcessPathfindingQueue"/>
            </do_if>
            
            <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch_Complete" param="this"/>
            <set_value name="$terminated" exact="true"/>
            <cancel_cue cue="this"/>
          </do_if>
          <do_else>
            <!-- Process current trade search radius -->
            <!-- IMPORTANT: Trade searches must be centered on HOME sector, not the ship's current sector.
                 Otherwise ships far away from home (e.g. 5 jumps away, maxDistance=3 from home) will get EMPTY sector lists
                 because we'd search around current position then filter by home distance. -->
            <set_value name="$tradeRefSector" exact="this.$currentSector"/>
            <do_if value="this.$homeSector?">
              <set_value name="$tradeRefSector" exact="this.$homeSector"/>
            </do_if>
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_FindSectorsInRange" result="$radiusSectors">
              <param name="refobject" value="$tradeRefSector"/>
              <param name="mingatedistance" value="this.$tradeSearchRadius"/>
              <param name="maxgatedistance" value="this.$tradeSearchRadius"/>
              <param name="ship" value="this.$ship"/>
              <param name="blacklistgroup" value="this.$blacklistgroup"/>
              <param name="applyblacklist" value="true"/>
            </run_actions>
            
            <!-- Check for fallback vs legitimate sectors -->
            <set_value name="$newSectorsFound" exact="false"/>
            <set_value name="$onlyFallbackSector" exact="false"/>
            <do_if value="(if $radiusSectors != null then $radiusSectors.count else 0) gt 0">
              <!-- Radius 0: Current sector is expected, always process it -->
              <do_if value="this.$tradeSearchRadius == 0">
                <set_value name="$newSectorsFound" exact="true"/>
              </do_if>
              <do_else>
                <!-- Radius > 0: Check if only current sector returned (fallback) -->
                <set_value name="$onlyCurrentSector" exact="false"/>
                <do_if value="$radiusSectors.count == 1">
                  <do_if value="$radiusSectors.{1} == this.$currentSector">
                    <set_value name="$onlyCurrentSector" exact="true"/>
                  </do_if>
                </do_if>
                <do_if value="$onlyCurrentSector and this.$tradeSearchRadius gt 0">
                  <set_value name="$onlyFallbackSector" exact="true"/>
                </do_if>
                <do_else>
                  <set_value name="$newSectorsFound" exact="true"/>
                </do_else>
              </do_else>
            </do_if>
            
            <!-- ISOLATION DETECTION: If radius 1 returns only fallback current sector, ship is isolated -->
            <do_if value="this.$tradeSearchRadius == 1 and $onlyFallbackSector">
              <set_value name="this.$shipIsIsolated" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Search] (' + this.$ship.idcode + ') ðŸ”’ ISOLATED: Only fallback current sector returned at radius 1 (all connected sectors blacklisted or unreachable)'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Process sectors: Radius 0 always processes, radius > 0 processes if legitimate (not fallback) -->
            <do_if value="$newSectorsFound">
              <!-- Debug logging for sector collection -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: Processing TRADE radius ' + this.$tradeSearchRadius + ' - Found ' + $radiusSectors.count + ' sectors - Ship=' + this.$ship.idcode" chance="10"/>
              </do_if>
              <!-- Collect sectors at this radius for downstream processing -->
              <do_all exact="$radiusSectors.count" counter="$i">
                <set_value name="$sectorToAdd" exact="$radiusSectors.{$i}"/>
                <do_if value="@$sectorToAdd.exists">
                  <!-- CRITICAL: Validate sector is within maxDistance from HOME SECTOR -->
                  <set_value name="$sectorDistanceFromHome" exact="-1"/>
                  <do_if value="@this.$homeSector.exists">
                    <!-- Special case: sector is home sector (distance = 0) -->
                    <do_if value="$sectorToAdd == this.$homeSector">
                      <set_value name="$sectorDistanceFromHome" exact="0"/>
                    </do_if>
                    <do_else>
                      <!-- Calculate distance from home sector to candidate sector -->
                      <set_value name="$sectorDistanceFromHome" exact="this.$homeSector.gatedistance.{$sectorToAdd}"/>
                    </do_else>
                  </do_if>
                  
                  <!-- Only add sector if it's within maxDistance from home sector -->
                  <do_if value="$sectorDistanceFromHome ge 0 and $sectorDistanceFromHome le this.$maxDistance">
                    <!-- Add to buy spaces list -->
                    <append_to_list name="this.$buyspaces" exact="$sectorToAdd"/>
                    <!-- Add to sell spaces list -->
                    <append_to_list name="this.$sellspaces" exact="$sectorToAdd"/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
            
            <!-- Early termination: Only fallback current sector returned = no new sectors found -->
            <do_if value="$onlyFallbackSector">
              <!-- Only current sector returned (fallback) means no new sectors at this radius -->
              <!-- Further radii will also be empty, so stop searching -->
              
              <!-- CONCURRENCY CONTROL: Decrement counter and process queue on completion -->
              <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$ActiveInstances?">
                <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="subtract"/>
                <do_if value="global.$GT_PathfindingQueue.$ActiveShips?">
                  <remove_from_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="this.$ship"/>
                </do_if>
                <!-- Signal queue processor to process next item -->
                <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.ProcessPathfindingQueue"/>
              </do_if>
              
              <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch_Complete" param="this"/>
              <set_value name="$terminated" exact="true"/>
              <cancel_cue cue="this"/>
            </do_if>
            
            <!-- CRITICAL FIX: Check BEFORE incrementing to determine if we should signal next iteration -->
            <!-- We need to signal when current radius <= maxDistance so next iteration can check completion -->
            <do_if value="not $onlyFallbackSector">
              <!-- Check if we should continue (before incrementing) -->
              <set_value name="$shouldContinue" exact="this.$tradeSearchRadius le this.$maxDistance"/>
              
              <!-- Increment radius for next iteration -->
              <set_value name="this.$tradeSearchRadius" operation="add"/>
              
              <!-- Signal next iteration if we should continue -->
              <do_if value="$shouldContinue">
                <!-- Debug logging for recursive signaling -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: Signaling next TRADE iteration - Ship=' + this.$ship.idcode + ', NextRadius=' + this.$tradeSearchRadius + ', BuySpaces=' + this.$buyspaces.count + ', SellSpaces=' + this.$sellspaces.count" chance="10"/>
                </do_if>
                <!-- Signal new instance for next radius iteration with current state -->
                <!-- Note: Continuation batches signal directly (don't go through queue) -->
                <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch" param="table[
                  $Ship = this.$ship,
                  $HomeSector = this.$homeSector,
                  $MaxDistance = this.$maxDistance,
                  $BlacklistGroup = this.$blacklistgroup,
                  $IsContinuation = true,
                  $Phase = this.$phase,
                  $EscapeSearchRadius = this.$escapeSearchRadius,
                  $TradeSearchRadius = this.$tradeSearchRadius,
                  $BuySpaces = this.$buyspaces,
                  $SellSpaces = this.$sellspaces,
                  $ShipIsIsolated = this.$shipIsIsolated,
                  $EscapeSector = this.$escapeSector,
                  $CurrentSector = this.$currentSector,
                  $CurrentSectorIsBlacklisted = this.$currentSectorIsBlacklisted
                ]"/>
              </do_if>
            </do_if>
          </do_else>
        </do_if>
        
        <!-- CPU YIELDING: Signal new instance for next iteration (ESCAPE phase) -->
        <!-- Only signal if we haven't completed (not cancelled) -->
        <!-- Note: Delay happens at cue level (before actions), so each recursive signal gets delayed -->
        <!-- Pass current state via params so new instance can restore it -->
        <do_if value="this.$phase == 'escape' and not this.$escapeSector? and this.$escapeSearchRadius le this.$escapeMaxRadius">
          <!-- Debug logging for recursive signaling -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch: Signaling next ESCAPE iteration - Ship=' + this.$ship.idcode + ', NextRadius=' + (this.$escapeSearchRadius + 1)" chance="10"/>
          </do_if>
          <!-- Signal new instance for next radius iteration with current state -->
          <signal_cue_instantly cue="md.GT_Libraries_Pathfinding.GT_IncrementalRadiusSearch" param="table[
            $Ship = this.$ship,
            $HomeSector = this.$homeSector,
            $MaxDistance = this.$maxDistance,
            $BlacklistGroup = this.$blacklistgroup,
            $IsContinuation = true,
            $Phase = this.$phase,
            $EscapeSearchRadius = this.$escapeSearchRadius,
            $TradeSearchRadius = this.$tradeSearchRadius,
            $BuySpaces = this.$buyspaces,
            $SellSpaces = this.$sellspaces,
            $ShipIsIsolated = this.$shipIsIsolated,
            $EscapeSector = this.$escapeSector,
            $CurrentSector = this.$currentSector,
            $CurrentSectorIsBlacklisted = this.$currentSectorIsBlacklisted
          ]"/>
        </do_if>
        </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Completion Handler -->
    <cue name="GT_IncrementalRadiusSearch_Complete" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Extract state from signaled cue instance -->
        <set_value name="$searchInstance" exact="event.param"/>
        
        <!-- Debug logging -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$debugShip" exact="@$searchInstance.$ship"/>
          <set_value name="$debugBuySpacesCount" exact="0"/>
          <set_value name="$debugSellSpacesCount" exact="0"/>
          <set_value name="$debugBuySpacesCount" exact="if @$searchInstance.$buyspaces != null then @$searchInstance.$buyspaces.count else 0"/>
          <set_value name="$debugSellSpacesCount" exact="if @$searchInstance.$sellspaces != null then @$searchInstance.$sellspaces.count else 0"/>
          <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch_Complete: Ship=' + (if $debugShip != null then @$debugShip.idcode else 'NULL') + ', BuySpaces=' + $debugBuySpacesCount + ', SellSpaces=' + $debugSellSpacesCount + ', Isolated=' + $searchInstance.$shipIsIsolated" chance="10"/>
        </do_if>
        
        <!-- Build result table (matches GT_BuildTradeSectorLists format for drop-in replacement) -->
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$Ship" exact="$searchInstance.$ship"/>
        <set_value name="$result.$BuySpaces" exact="$searchInstance.$buyspaces"/>
        <set_value name="$result.$SellSpaces" exact="$searchInstance.$sellspaces"/>
        <set_value name="$result.$ShipIsIsolated" exact="$searchInstance.$shipIsIsolated"/>
        <set_value name="$result.$EscapeSector" exact="$searchInstance.$escapeSector"/>
        
        <!-- CRITICAL FIX: Check if ship still has GT order before signaling resume -->
        <set_value name="$ship" exact="$searchInstance.$ship"/>
        <set_value name="$hasGTOrder" exact="false"/>
        <do_if value="$ship.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id} or (@$ship.defaultorder.id == 'Assist' and $ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.$baseorder.id}))">
          <set_value name="$hasGTOrder" exact="true"/>
        </do_if>
        <do_else>
          <!-- Check if subordinate to GT commander -->
          <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
            <do_if value="$ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and (global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id} or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.$baseorder.id}))">
              <set_value name="$hasGTOrder" exact="true"/>
            </do_if>
          </do_if>
        </do_else>
        
        <!-- Only signal resume if ship still has GT order -->
        <do_if value="not $hasGTOrder">
          <!-- Clean up from active ships list -->
          <do_if value="global.$GT_PathfindingQueue? and global.$GT_PathfindingQueue.$ActiveShips?">
            <do_all exact="global.$GT_PathfindingQueue.$ActiveShips.count" counter="$i" reverse="true">
              <do_if value="global.$GT_PathfindingQueue.$ActiveShips.{$i} == $ship">
                <remove_from_list name="global.$GT_PathfindingQueue.$ActiveShips" exact="$ship"/>
                <do_if value="global.$GT_PathfindingQueue.$ActiveInstances? and global.$GT_PathfindingQueue.$ActiveInstances gt 0">
                  <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" operation="subtract"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Search] GT_IncrementalRadiusSearch_Complete: Ship ' + $ship.idcode + ' no longer has GT order - cancelling completion signal'" chance="10"/>
          </do_if>
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
          <!-- Legacy SearchLiveTrades resume path removed; fail fast for any stale caller. -->
          <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'legacy_pathfinding_resume_removed'" delay="1ms"/>
        </do_else>
      </actions>
    </cue>
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<!--
  GalaxyTrader MK1 â€” Station Trader Library Functions
  
  Provides reusable library cues for the MK1 Station Trader order:
  - GT_BuildStationWareBasket: Derive effective ware list from station
  - GT_FindBestStationSale: Find best NPC buyer for station wares
  - GT_ValidateStationAssignment: Validate station is valid for MK1
  
  These are called via run_actions from the MK1 AI script.
-->
<mdscript name="GT_Libraries_StationTrader" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>

    <!-- ================================================================ -->
    <!-- GT_ValidateStationAssignment                                     -->
    <!-- Validates that a station is a valid MK1 home station             -->
    <!-- Returns: $valid (bool), $reason (string)                         -->
    <!-- ================================================================ -->
    <library name="GT_ValidateStationAssignment" purpose="run_actions">
      <params>
        <param name="ship" comment="The trading ship"/>
        <param name="homeStation" comment="The station to validate"/>
      </params>
      <actions>
        <set_value name="$valid" exact="false"/>
        <set_value name="$reason" exact="''"/>

        <do_if value="not $homeStation? or not $homeStation.exists">
          <set_value name="$reason" exact="'Station does not exist'"/>
          <return/>
        </do_if>

        <do_if value="not $homeStation.isclass.station">
          <set_value name="$reason" exact="'Object is not a station'"/>
          <return/>
        </do_if>

        <do_if value="not $homeStation.isplayerowned">
          <set_value name="$reason" exact="'Station is not player-owned'"/>
          <return/>
        </do_if>

        <do_if value="not $homeStation.isoperational">
          <set_value name="$reason" exact="'Station is not operational'"/>
          <return/>
        </do_if>

        <set_value name="$valid" exact="true"/>
      </actions>
    </library>

    <!-- ================================================================ -->
    <!-- GT_BuildStationWareBasket                                        -->
    <!-- Builds the effective ware list from station products/tradewares  -->
    <!-- Excludes resources, processed wares, and cargo-incompatible      -->
    <!-- Returns: $effectiveWares (list)                                  -->
    <!-- ================================================================ -->
    <library name="GT_BuildStationWareBasket" purpose="run_actions">
      <params>
        <param name="station" comment="Home station"/>
        <param name="ship" comment="Trading ship (for cargo filtering)"/>
        <param name="warebasket" comment="User-specified ware filter (empty = auto-derive)"/>
        <param name="allowillegal" comment="Allow illegal wares"/>
      </params>
      <actions>
        <create_list name="$effectiveWares"/>
        <create_list name="$candidateWares"/>

        <!-- Step 1: Build candidate list from station -->
        <do_if value="$warebasket? and $warebasket.count gt 0">
          <!-- Manual filter: use only user-specified wares -->
          <do_all exact="$warebasket.count" counter="$i">
            <append_to_list name="$candidateWares" exact="$warebasket.{$i}"/>
          </do_all>
        </do_if>
        <do_else>
          <!-- Auto-derive: station products + tradewares, exclude resources -->
          <set_value name="$products" exact="$station.products.list"/>
          <set_value name="$tradewares" exact="$station.tradewares.list"/>

          <do_all exact="$products.count" counter="$i">
            <set_value name="$ware" exact="$products.{$i}"/>
            <!-- Avoid duplicates -->
            <set_value name="$alreadyAdded" exact="false"/>
            <do_all exact="$candidateWares.count" counter="$j">
              <do_if value="$candidateWares.{$j} == $ware">
                <set_value name="$alreadyAdded" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $alreadyAdded">
              <append_to_list name="$candidateWares" exact="$ware"/>
            </do_if>
          </do_all>

          <do_all exact="$tradewares.count" counter="$i">
            <set_value name="$ware" exact="$tradewares.{$i}"/>
            <set_value name="$alreadyAdded" exact="false"/>
            <do_all exact="$candidateWares.count" counter="$j">
              <do_if value="$candidateWares.{$j} == $ware">
                <set_value name="$alreadyAdded" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            <do_if value="not $alreadyAdded">
              <append_to_list name="$candidateWares" exact="$ware"/>
            </do_if>
          </do_all>
        </do_else>

        <!-- Step 2: Filter candidates -->
        <do_all exact="$candidateWares.count" counter="$i">
          <set_value name="$ware" exact="$candidateWares.{$i}"/>

          <!-- Skip if ship can't carry this ware -->
          <do_if value="$ship.cargo.{$ware}.max le 0">
            <continue/>
          </do_if>

          <!-- Skip processed wares -->
          <do_if value="$ware.isprocessed">
            <continue/>
          </do_if>

          <!-- Skip illegal wares unless allowed -->
          <do_if value="not $allowillegal and $ware.illegal">
            <continue/>
          </do_if>

          <append_to_list name="$effectiveWares" exact="$ware"/>
        </do_all>
      </actions>
    </library>

    <!-- ================================================================ -->
    <!-- GT_FindBestStationSale                                           -->
    <!-- Finds the best NPC buyer(s) for station wares                    -->
    <!-- Returns: $bestTrade (table or null), $allTrades (list)           -->
    <!--                                                                  -->
    <!-- Trade table structure:                                           -->
    <!--   $Ware, $SellOffer, $BuyOffer, $Amount, $Score,                 -->
    <!--   $BuyStation, $BuySector, $Distance, $UnitProfit                -->
    <!-- ================================================================ -->
    <library name="GT_FindBestStationSale" purpose="run_actions">
      <params>
        <param name="ship" comment="Trading ship"/>
        <param name="station" comment="Home station (sell source)"/>
        <param name="effectiveWares" comment="List of wares to sell"/>
        <param name="maxsell" comment="Max gate distance for buyers"/>
        <param name="ignoretraderules" comment="Bypass station trade rules"/>
        <param name="fleetcoordination" comment="Check fleet reservations"/>
      </params>
      <actions>
        <set_value name="$bestTrade" exact="null"/>
        <create_list name="$allTrades"/>
        <set_value name="$bestScore" exact="0"/>

        <!-- Build list of sectors within maxsell range -->
        <create_list name="$searchSectors"/>
        <append_to_list name="$searchSectors" exact="$station.sector"/>
        <do_if value="$maxsell gt 0">
          <find_sector name="$nearbySectors" space="player.galaxy" multiple="true">
            <match_gate_distance object="$station.sector" min="0" max="$maxsell"/>
          </find_sector>
          <do_if value="$nearbySectors? and $nearbySectors.count gt 0">
            <do_all exact="$nearbySectors.count" counter="$si">
              <do_if value="$nearbySectors.{$si} != $station.sector">
                <append_to_list name="$searchSectors" exact="$nearbySectors.{$si}"/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>

        <!-- For each ware, find sell offer from station and matching buy offers -->
        <do_all exact="$effectiveWares.count" counter="$wi">
          <set_value name="$ware" exact="$effectiveWares.{$wi}"/>

          <!-- Get sell offer from home station for this ware -->
          <!-- Station sells -> ship buys from station -->
          <find_sell_offer seller="$station" wares="$ware" result="$stationSellOffer"/>
          <do_if value="not $stationSellOffer.available">
            <continue/>
          </do_if>
          <do_if value="$stationSellOffer.amount le 0">
            <continue/>
          </do_if>

          <!-- Find NPC buyers in each sector within range -->
          <create_list name="$buyOffers"/>
          <do_all exact="$searchSectors.count" counter="$si">
            <set_value name="$searchSec" exact="$searchSectors.{$si}"/>
            <do_if value="$ignoretraderules">
              <!-- Bypass trade rules: find any friendly NPC buyer -->
              <find_buy_offer wares="$ware" space="$searchSec" result="$secBuyOffers" multiple="true">
                <match_buyer tradesknownto="$ship.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <amount min="1"/>
              </find_buy_offer>
            </do_if>
            <do_else>
              <!-- Respect trade rules: use tradepartner for restriction filtering -->
              <find_buy_offer wares="$ware" tradepartner="$ship" space="$searchSec" result="$secBuyOffers" multiple="true">
                <match_buyer tradesknownto="$ship.owner" owner="faction.player" negateownerfilter="true">
                  <match_relation_to object="$ship" relation="dock" comparison="ge"/>
                  <match_relation_to faction="$ship.owner" relation="enemy" comparison="not"/>
                </match_buyer>
                <amount min="1"/>
              </find_buy_offer>
            </do_else>
            <do_if value="$secBuyOffers? and $secBuyOffers.count gt 0">
              <do_all exact="$secBuyOffers.count" counter="$boi">
                <append_to_list name="$buyOffers" exact="$secBuyOffers.{$boi}"/>
              </do_all>
            </do_if>
          </do_all>

          <do_if value="$buyOffers.count == 0">
            <continue/>
          </do_if>

          <!-- Evaluate each buyer -->
          <do_all exact="$buyOffers.count" counter="$bi">
            <set_value name="$buyOffer" exact="$buyOffers.{$bi}"/>

            <!-- Skip if buyer has no demand -->
            <do_if value="$buyOffer.amount le 0">
              <continue/>
            </do_if>

            <!-- Calculate tradeable amount -->
            <set_value name="$tradeAmount" exact="[$stationSellOffer.amount, $buyOffer.amount, $ship.cargo.{$ware}.free].min"/>
            <do_if value="$tradeAmount le 0">
              <continue/>
            </do_if>

            <!-- Calculate profit -->
            <set_value name="$unitProfit" exact="$buyOffer.unitprice - $stationSellOffer.unitprice"/>
            <do_if value="$unitProfit le 0">
              <continue/>
            </do_if>

            <!-- Get buyer station and distance -->
            <set_value name="$buyStation" exact="$buyOffer.owner"/>
            <set_value name="$buySector" exact="$buyStation.sector"/>
            <set_value name="$distance" exact="$station.gatedistance.{$buyStation}"/>
            <do_if value="$distance lt 0">
              <!-- Unreachable -->
              <continue/>
            </do_if>

            <!-- Check fleet reservation (if enabled) -->
            <do_if value="$fleetcoordination and global.$GT_TradeReservations?">
              <set_value name="$tradeKey" exact="'' + $ware + '_' + $buyStation"/>
              <set_value name="$isReserved" exact="false"/>
              <do_if value="global.$GT_TradeReservations.{$tradeKey}? and global.$GT_TradeReservations.{$tradeKey} != $ship">
                <set_value name="$isReserved" exact="true"/>
              </do_if>
              <do_if value="$isReserved">
                <continue/>
              </do_if>
            </do_if>

            <!-- Check blacklist -->
            <do_if value="global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.$BlacklistedSectors?">
              <set_value name="$sectorBlacklisted" exact="false"/>
              <do_all exact="global.$GT_ThreatIntelligence.$BlacklistedSectors.count" counter="$bli">
                <do_if value="global.$GT_ThreatIntelligence.$BlacklistedSectors.{$bli} == $buySector">
                  <set_value name="$sectorBlacklisted" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              <do_if value="$sectorBlacklisted">
                <continue/>
              </do_if>
            </do_if>

            <!-- Score: (unitProfit * amount) / distancePenalty -->
            <set_value name="$distancePenalty" exact="1.0 + ($distance * 0.1)"/>
            <set_value name="$score" exact="($unitProfit * $tradeAmount) / $distancePenalty"/>

            <!-- Build trade entry -->
            <set_value name="$trade" exact="table[
              $Ware = $ware,
              $SellOffer = $stationSellOffer,
              $BuyOffer = $buyOffer,
              $Amount = $tradeAmount,
              $Score = $score,
              $BuyStation = $buyStation,
              $BuySector = $buySector,
              $Distance = $distance,
              $UnitProfit = $unitProfit
            ]"/>

            <append_to_list name="$allTrades" exact="$trade"/>

            <!-- Track best -->
            <do_if value="$score gt $bestScore">
              <set_value name="$bestScore" exact="$score"/>
              <set_value name="$bestTrade" exact="$trade"/>
            </do_if>
          </do_all>
        </do_all>
      </actions>
    </library>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Maintenance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ============================================================================= -->
    <!-- GALAXY TRADER MK3 - UNIFIED MAINTENANCE SYSTEM                                -->
    <!-- Handles ALL ship maintenance (repair + equipment) in one place                -->
    <!-- Pattern: AI script signals MD processes EVERYTHING signals completion    -->
    <!-- ============================================================================= -->
    
    <!-- Main Maintenance Handler -->
    <cue name="DoMaintenance" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_DoMaintenance'"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param2"/>
        <!-- MD cue actions do not allow <return/> (only <library>/<run_actions>-callable lists do),
             so the re-entry guards below set $abortEarly=true and the entire rest of the cue is
             wrapped in <do_if value="not $abortEarly"> at line ~78. -->
        <set_value name="$abortEarly" exact="false"/>
        
        <!-- ===================================================================== -->
        <!-- RE-ENTRY GUARDS                                                       -->
        <!--                                                                       -->
        <!-- 1. In-flight order short-circuit: if we've already issued an          -->
        <!--    add_build_to_modify_ship for this ship and are tracking it in      -->
        <!--    $GT_MaintenanceOrders with WaitingForEquipment/WaitingForRepair    -->
        <!--    set true, ignore further GT_DoMaintenance signals until the order  -->
        <!--    completes (which clears the entry via ProcessResupplyComplete /    -->
        <!--    ProcessRepairComplete). Without this, every miner-order restart    -->
        <!--    (which fires GT_DoMaintenance from order.trade.galaxyminer.xml's   -->
        <!--    init at ~403) would re-run ExecuteMaintenance, re-enumerate all    -->
        <!--    51 equipment stations, rebuild the shopping list, and re-issue     -->
        <!--    add_build_to_modify_ship - which in X4 RESETS the build queue,     -->
        <!--    meaning the ship never sees a stable enough target to undock and  -->
        <!--    travel to a wharf.                                                 -->
        <!--                                                                       -->
        <!-- 2. Signal-rate throttle: even before an order is created, back-to-   -->
        <!--    back GT_DoMaintenance signals (e.g. AI init -> ship modification  -->
        <!--    refresh -> order restart -> AI init again, all within seconds)    -->
        <!--    can pile up multiple ExecuteMaintenance instances racing on the    -->
        <!--    same ship. A 30s minimum gap between accepted signals per ship     -->
        <!--    bounds this without delaying legitimate maintenance (the smallest  -->
        <!--    real-world cycle is "scout fallback every 5min" or "ship docks     -->
        <!--    + completes restock + needs more probes" which is minutes apart).  -->
        <!-- ===================================================================== -->
        <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{$ship}?">
          <set_value name="$inFlightWaitingEquipment" exact="@global.$GT_MaintenanceOrders.{$ship}.$WaitingForEquipment"/>
          <set_value name="$inFlightWaitingRepair" exact="@global.$GT_MaintenanceOrders.{$ship}.$WaitingForRepair"/>
          <do_if value="$inFlightWaitingEquipment or $inFlightWaitingRepair">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' already has maintenance order in flight (WaitingForEquipment=' + $inFlightWaitingEquipment + ', WaitingForRepair=' + $inFlightWaitingRepair + ') - ignoring duplicate GT_DoMaintenance signal'" chance="100"/>
            </do_if>
            <set_value name="$abortEarly" exact="true"/>
          </do_if>
          <do_if value="not $abortEarly">
            <!-- Entry exists but both Waiting flags are false: stale (e.g. order was created but
                 never reached add_build_to_modify_ship, or completion handler missed clearing it).
                 Drop it so this cycle can re-issue cleanly. -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Clearing stale maintenance order tracking for ' + $ship.idcode + ' (no Waiting flag set)'" chance="100"/>
            </do_if>
            <remove_value name="global.$GT_MaintenanceOrders.{$ship}"/>
          </do_if>
        </do_if>
        
        <do_if value="not $abortEarly">
          <do_if value="not global.$GT_MaintenanceLastSignaledAt?">
            <set_value name="global.$GT_MaintenanceLastSignaledAt" exact="table[]"/>
          </do_if>
          <do_if value="global.$GT_MaintenanceLastSignaledAt.{$ship}? and (player.age - @global.$GT_MaintenanceLastSignaledAt.{$ship}) lt 30s">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' GT_DoMaintenance throttled (last signal ' + (player.age - @global.$GT_MaintenanceLastSignaledAt.{$ship}) + 's ago, min 30s) - ignoring'" chance="100"/>
            </do_if>
            <set_value name="$abortEarly" exact="true"/>
          </do_if>
        </do_if>
        
        <do_if value="not $abortEarly">
          <set_value name="global.$GT_MaintenanceLastSignaledAt.{$ship}" exact="player.age"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] Starting maintenance check for ' + $ship.idcode" chance="100"/>
          </do_if>
        
        <!-- Initialize pilot level before use -->
        <set_value name="$pilotLevel" exact="1"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{$ship.pilot}.$Level"/>
        </do_if>
        
        <!-- Clear stale maintenance orders before checks -->
        <!-- Old orders from previous sessions can persist in save files -->
        <!-- Always start fresh to prevent executing obsolete repair/resupply orders -->
        <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{$ship}?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] Clearing stale repair order for ' + $ship.idcode" chance="100"/>
          </do_if>
          <remove_value name="global.$GT_RepairOrders.{$ship}"/>
        </do_if>
        
        <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] Clearing stale resupply order for ' + $ship.idcode" chance="100"/>
          </do_if>
          <remove_value name="global.$GT_ResupplyOrders.{$ship}"/>
        </do_if>
          
        <!-- Flags for what needs to be done -->
        <set_value name="$needsRepair" exact="false"/>
        <set_value name="$needsEquipment" exact="false"/>
        <set_value name="$shipIsGalaxyMiner" exact="false"/>
        <!-- Collector ("mining") drone buy amount. Default 5 preserves the previous hard-coded
             behaviour for any miner whose AI params / order param haven't published a value yet.
             0 = disable automatic collector-drone purchases (player manages drones manually). -->
        <set_value name="$maxCollectorDronesToBuy" exact="5"/>
        
        <do_if value="$ship.defaultorder? and @$ship.defaultorder != null and @$ship.defaultorder.id == 'GalaxyMiner'">
          <set_value name="$shipIsGalaxyMiner" exact="true"/>
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$MaxCollectorDronesToBuy?">
            <set_value name="$maxCollectorDronesToBuy" exact="global.$GT_AIParameters.{$ship}.$MaxCollectorDronesToBuy"/>
          </do_if>
          <do_elseif value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$maxCollectorDronesToBuy?">
            <set_value name="$maxCollectorDronesToBuy" exact="global.$GT_AIParameters.{$ship}.$maxCollectorDronesToBuy"/>
          </do_elseif>
          <do_elseif value="$ship.defaultorder.$maxCollectorDronesToBuy?">
            <set_value name="$maxCollectorDronesToBuy" exact="$ship.defaultorder.$maxCollectorDronesToBuy"/>
          </do_elseif>
        </do_if>
        
        <!-- ========================================================================= -->
        <!-- 1. CHECK REPAIR (Level 12+)                                              -->
        <!-- ========================================================================= -->
        
        <!-- DIAGNOSTIC: Log repair prerequisites -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance] Repair gate: pilotLevel=' + $pilotLevel + ' (need 12+), AutoRepair.Enabled=' + @global.$GT_GlobalSettings.$AutoRepair.$Enabled + ', HullThreshold=' + @global.$GT_GlobalSettings.$AutoRepair.$HullThreshold + '%'" chance="100"/>
        </do_if>
        
        <do_if value="$pilotLevel ge 12 and @global.$GT_GlobalSettings.$AutoRepair.$Enabled">
          <set_value name="$hullPercentage" exact="$ship.hullpercentage"/>
          <set_value name="$repairThreshold" exact="@global.$GT_GlobalSettings.$AutoRepair.$HullThreshold"/>
          
          <do_if value="$hullPercentage lt $repairThreshold">
            <set_value name="$needsRepair" exact="true"/>
            <!-- Set flag for ship name operational state -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
              <set_value name="global.$GT_Ships.{$ship}.$NeedsRepair" exact="true"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' needs repair (hull: ' + $hullPercentage + '%, threshold: ' + $repairThreshold + '%)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="not @global.$GT_GlobalSettings.$AutoRepair.$Enabled">
          <!-- Auto-repair disabled: drop stale repair registry so [RP] / diagnose do not linger -->
          <run_actions ref="ClearAutoRepairStateForShip">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_elseif>
        
        <!-- ========================================================================= -->
        <!-- 2. CHECK EQUIPMENT (Level 15+)                                           -->
        <!-- ========================================================================= -->
        
        <!-- Always read deployable counts up-front (countermeasures / collector drones). -->
        <set_value name="$deployableCapacity" exact="$ship.ammostorage.deployable.capacity"/>
        <set_value name="$currentDeployables" exact="$ship.ammostorage.deployable.count"/>
        <set_value name="$needsCountermeasures" exact="false"/>
        <set_value name="$needsUnits" exact="false"/>
        <set_value name="$needsDeployableLaserTowers" exact="false"/>
        <!-- ============================================================================ -->
        <!-- Collector-drone shortage detection (capital miners only).                    -->
        <!-- Detection mirrors vanilla order.mining.routine.xml lines 467/472 verbatim:   -->
        <!--   waretransport.solid + 0 orecollector  -> needs ore collector               -->
        <!--   waretransport.liquid + 0 gascollector -> needs gas collector               -->
        <!-- (waretransport.indexof on the ship's storage, not the selected ware: this is -->
        <!--  fleet-prep, no ware is locked in yet.) Macro names are vanilla canonical    -->
        <!-- (libraries/loadoutrules.xml lines 12 + 14): the orecollector mk1 macro is    -->
        <!-- ship_gen_s_miningdrone_solid_01_a_macro, gascollector mk1 macro is          -->
        <!-- ship_gen_s_miningdrone_liquid_01_a_macro. Target count = 5, matching         -->
        <!-- upkeep_management.xml line 341/350 (the canonical vanilla restock amount     -->
        <!-- for stations restocking their own miners). Capped below at unitsMaxCount.    -->
        <!-- ============================================================================ -->
        <set_value name="$needsCollectorDrones" exact="false"/>
        <set_value name="$collectorMacro" exact="null"/>
        <set_value name="$collectorMacroLabel" exact="''"/>
        <set_value name="$collectorTargetCount" exact="0"/>
        <!-- Only auto-buy collectors when the player slider allows it (gt 0). The shortage is still
             detected strictly at count==0, so a miner that already has at least one collector of the
             needed type is never topped up or re-bought. Target = slider amount, capped at unit bay. -->
        <do_if value="$ship.iscapitalship and $maxCollectorDronesToBuy gt 0">
          <do_if value="$ship.waretransport.indexof.{waretransport.solid} and not $ship.units.{unitcategory.orecollector}.count">
            <set_value name="$needsCollectorDrones" exact="true"/>
            <set_value name="$collectorMacro" exact="macro.ship_gen_s_miningdrone_solid_01_a_macro"/>
            <set_value name="$collectorMacroLabel" exact="'orecollector'"/>
            <set_value name="$collectorTargetCount" exact="[$maxCollectorDronesToBuy, $ship.units.maxcount].min"/>
          </do_if>
          <do_elseif value="$ship.waretransport.indexof.{waretransport.liquid} and not $ship.units.{unitcategory.gascollector}.count">
            <set_value name="$needsCollectorDrones" exact="true"/>
            <set_value name="$collectorMacro" exact="macro.ship_gen_s_miningdrone_liquid_01_a_macro"/>
            <set_value name="$collectorMacroLabel" exact="'gascollector'"/>
            <set_value name="$collectorTargetCount" exact="[$maxCollectorDronesToBuy, $ship.units.maxcount].min"/>
          </do_elseif>
        </do_if>
        
        <do_if value="$pilotLevel ge 15 and @global.$GT_Config.$Defense.$Enabled and @global.$GT_GlobalSettings.$DefensiveEquipment.$Enabled">
          <!-- Check countermeasures and deployables -->
          <set_value name="$countermeasureCapacity" exact="$ship.ammostorage.countermeasure.capacity"/>
          <set_value name="$currentCountermeasures" exact="$ship.ammostorage.countermeasure.count"/>
          <set_value name="$countermeasurePercentage" exact="if $countermeasureCapacity gt 0 then ($currentCountermeasures * 100) / $countermeasureCapacity else 100"/>
          
          <set_value name="$deployablePercentage" exact="if $deployableCapacity gt 0 then ($currentDeployables * 100) / $deployableCapacity else 100"/>
          
          <!-- Also check UNITS (drones in docking bays) -->
        <set_value name="$unitsCapacity" exact="$ship.units.maxcount"/>
        <set_value name="$currentUnits" exact="$ship.units.count"/>
        <set_value name="$unitsPercentage" exact="if $unitsCapacity gt 0 then ($currentUnits * 100) / $unitsCapacity else 100"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' storage check: CM cap=' + $countermeasureCapacity + ', Deployables cap=' + $deployableCapacity + ', Units maxcount=' + $unitsCapacity" chance="100"/>
          <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' current: CM=' + $currentCountermeasures + ', Deployables=' + $currentDeployables + ', Units=' + $currentUnits" chance="100"/>
        </do_if>
          
          <set_value name="$countermeasureThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold"/>
          <set_value name="$unifiedThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold"/>
          
          <!-- Check if restocking needed -->
          <set_value name="$needsCountermeasures" exact="$countermeasureCapacity gt 0 and $countermeasurePercentage lt $countermeasureThreshold"/>
          <!-- NOTE: Don't check deployables (mines/satellites) here - only restock if ship's loadout explicitly defines them -->
          <set_value name="$needsDeployables" exact="false"/>
          <!-- NOTE: For units, check if below threshold to trigger maintenance -->
          <set_value name="$needsUnits" exact="$unitsCapacity gt 0 and $unitsPercentage lt $unifiedThreshold"/>
          
          <!-- S/M ships store laser towers in deployable bay, not unit docks -->
          <do_if value="$unitsCapacity == 0 and $deployableCapacity gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers">
            <set_value name="$balanceProfile" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile"/>
            <do_if value="not $balanceProfile?">
              <set_value name="$balanceProfile" exact="2"/>
            </do_if>
            <set_value name="$laserTowerPct" exact="20"/>
            <do_if value="$balanceProfile == 4">
              <set_value name="$laserTowerPct" exact="30"/>
            </do_if>
            <set_value name="$deployableLaserTowerTarget" exact="[($deployableCapacity * $laserTowerPct / 100)i, 1].max"/>
            <set_value name="$currentDeployableLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
            <set_value name="$deployableLaserTowerPercentage" exact="if $deployableLaserTowerTarget gt 0 then ($currentDeployableLaserTowers * 100) / $deployableLaserTowerTarget else 100"/>
            <set_value name="$needsDeployableLaserTowers" exact="$deployableLaserTowerTarget gt 0 and $deployableLaserTowerPercentage lt $unifiedThreshold"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]   Deployable Towers: Current=' + $currentDeployableLaserTowers + '/' + $deployableLaserTowerTarget + ' (' + $deployableLaserTowerPercentage + '%), Threshold=' + $unifiedThreshold + '%, Needs=' + $needsDeployableLaserTowers" chance="100"/>
            </do_if>
            <remove_value name="$laserTowerPct"/>
            <remove_value name="$deployableLaserTowerTarget"/>
            <remove_value name="$currentDeployableLaserTowers"/>
            <remove_value name="$deployableLaserTowerPercentage"/>
            <remove_value name="$balanceProfile"/>
          </do_if>
          
          <!-- Track exact values and logic -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] RESUPPLY CHECK DETAILS for ' + $ship.idcode + ':'" chance="100"/>
            <debug_text text="'[GT-Maintenance]   CM: Current=' + $currentCountermeasures + '/' + $countermeasureCapacity + ' (' + $countermeasurePercentage + '%), Threshold=' + $countermeasureThreshold + '%, Needs=' + $needsCountermeasures + ' (capacity&gt;0=' + ($countermeasureCapacity gt 0) + ', percentage&lt;threshold=' + ($countermeasurePercentage lt $countermeasureThreshold) + ')'" chance="100"/>
            <debug_text text="'[GT-Maintenance]   Units: Current=' + $currentUnits + '/' + $unitsCapacity + ' (' + $unitsPercentage + '%), Threshold=' + $unifiedThreshold + '%, Needs=' + $needsUnits + ' (capacity&gt;0=' + ($unitsCapacity gt 0) + ', percentage&lt;threshold=' + ($unitsPercentage lt $unifiedThreshold) + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance]   Collector drones (Miner): NeedsCollectors=' + $needsCollectorDrones + ', Category=' + $collectorMacroLabel + ', Target=' + $collectorTargetCount + ', UnitsMax=' + $ship.units.maxcount + ', CurrentOreCol=' + $ship.units.{unitcategory.orecollector}.count + ', CurrentGasCol=' + $ship.units.{unitcategory.gascollector}.count" chance="100"/>
          <debug_text text="'[GT-Maintenance]   Result: needsCountermeasures=' + $needsCountermeasures + ', needsUnits=' + $needsUnits + ', needsDeployableLaserTowers=' + $needsDeployableLaserTowers + ', needsCollectorDrones=' + $needsCollectorDrones + ', needsEquipment=' + ($needsCountermeasures or $needsUnits or $needsDeployableLaserTowers or $needsCollectorDrones)" chance="100"/>
        </do_if>
        
        <do_if value="$needsCountermeasures or $needsUnits or $needsDeployableLaserTowers or $needsCollectorDrones">
          <set_value name="$needsEquipment" exact="true"/>
          <!-- Build human-readable restock summary as a list join (was if/else chain - exploded to 2^4
               combinations once collectors were added). -->
          <set_value name="$restockComponents" exact="[]"/>
          <do_if value="$needsCountermeasures">
            <append_to_list name="$restockComponents" exact="'CM'"/>
          </do_if>
          <do_if value="$needsUnits">
            <append_to_list name="$restockComponents" exact="'units'"/>
          </do_if>
          <do_if value="$needsDeployableLaserTowers">
            <append_to_list name="$restockComponents" exact="'deployable towers'"/>
          </do_if>
          <do_if value="$needsCollectorDrones">
            <append_to_list name="$restockComponents" exact="$collectorMacroLabel + ' drones'"/>
          </do_if>
          <set_value name="$whatNeedsRestocking" exact="''"/>
          <do_all exact="$restockComponents.count" counter="$_rci">
            <set_value name="$whatNeedsRestocking" exact="$whatNeedsRestocking + (if $_rci gt 1 then ' + ' else '') + $restockComponents.{$_rci}"/>
          </do_all>
          <remove_value name="$restockComponents"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' needs equipment (CollectorTarget: ' + $collectorTargetCount + ' ' + $collectorMacroLabel + ' - will restock ' + $whatNeedsRestocking + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- ========================================================================= -->
        <!-- 3. EXECUTE MAINTENANCE                                                    -->
        <!-- ========================================================================= -->
        
        <do_if value="not $needsRepair and not $needsEquipment">
          <!-- No maintenance needed -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] ' + $ship.idcode + ' no maintenance needed'" chance="100"/>
          </do_if>
          <signal_objects object="$ship" param="'GT_Maintenance_Complete'" delay="1ms"/>
        </do_if>
        <do_else>
          <!-- CRITICAL PERFORMANCE FIX: Queue maintenance execution to prevent CPU spikes -->
          <!-- When many ships need maintenance simultaneously (save load, fleet init), unlimited concurrent instances cause massive spikes -->
          <!-- Initialize queue if needed -->
          <do_if value="not global.$GT_MaintenanceQueue?">
            <set_value name="global.$GT_MaintenanceQueue" exact="table[]"/>
            <set_value name="global.$GT_MaintenanceQueue.$Requests" exact="[]"/>
            <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" exact="0"/>
            <set_value name="global.$GT_MaintenanceQueue.$MaxConcurrent" exact="2"/>
          </do_if>
          
          <!-- Check concurrency limit -->
          <set_value name="$shouldQueue" exact="false"/>
          <do_if value="global.$GT_MaintenanceQueue.$ActiveInstances ge global.$GT_MaintenanceQueue.$MaxConcurrent">
            <set_value name="$shouldQueue" exact="true"/>
          </do_if>
          
          <do_if value="$shouldQueue">
            <!-- At max concurrent - queue request -->
            <append_to_list name="global.$GT_MaintenanceQueue.$Requests" exact="table[
              $Ship = $ship,
              $PilotLevel = $pilotLevel,
              $NeedsRepair = $needsRepair,
              $NeedsEquipment = $needsEquipment,
              $HullPercentage = $hullPercentage,
              $RepairThreshold = $repairThreshold
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Maintenance request QUEUED for ' + $ship.idcode + ' (active: ' + global.$GT_MaintenanceQueue.$ActiveInstances + '/' + global.$GT_MaintenanceQueue.$MaxConcurrent + ', queued: ' + global.$GT_MaintenanceQueue.$Requests.count + ')'" chance="10"/>
            </do_if>
            <!-- Signal queue processor -->
            <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
          </do_if>
          <do_else>
            <!-- Below limit - process immediately -->
            <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" operation="add"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Processing maintenance immediately for ' + $ship.idcode + ' (active: ' + global.$GT_MaintenanceQueue.$ActiveInstances + '/' + global.$GT_MaintenanceQueue.$MaxConcurrent + ')'" chance="10"/>
            </do_if>
            <signal_cue_instantly cue="ExecuteMaintenance" param="table[
              $Ship = $ship,
              $PilotLevel = $pilotLevel,
              $NeedsRepair = $needsRepair,
              $NeedsEquipment = $needsEquipment,
              $HullPercentage = $hullPercentage,
              $RepairThreshold = $repairThreshold
            ]"/>
          </do_else>
        </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Maintenance Queue Processor -->
    <cue name="ProcessMaintenanceQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- CPU YIELDING: Prevent queue-drain avalanches in a single frame when many ships enqueue maintenance at once -->
      <delay exact="10ms"/>
      <actions>
        <!-- Process next request in queue if below concurrency limit -->
        <do_if value="global.$GT_MaintenanceQueue? and global.$GT_MaintenanceQueue.$Requests? and global.$GT_MaintenanceQueue.$Requests.count gt 0">
          <do_if value="global.$GT_MaintenanceQueue.$ActiveInstances lt global.$GT_MaintenanceQueue.$MaxConcurrent">
            <!-- Below limit - process next request -->
            <set_value name="$nextRequest" exact="global.$GT_MaintenanceQueue.$Requests.{1}"/>
            <do_if value="$nextRequest?">
              <remove_from_list name="global.$GT_MaintenanceQueue.$Requests" exact="$nextRequest"/>
              <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" operation="add"/>
              
              <!-- Process request -->
              <signal_cue_instantly cue="md.GT_Maintenance.ExecuteMaintenance" param="$nextRequest"/>
              
              <!-- Continue processing queue -->
              <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
            </do_if>
            <do_else>
              <!-- Invalid request - remove it and continue -->
              <do_if value="global.$GT_MaintenanceQueue.$Requests.count gt 0">
                <remove_from_list name="global.$GT_MaintenanceQueue.$Requests" exact="global.$GT_MaintenanceQueue.$Requests.{1}"/>
              </do_if>
              <!-- Continue processing queue -->
              <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
            </do_else>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Execute Maintenance Orders -->
    <cue name="ExecuteMaintenance" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        <set_value name="$pilotLevel" exact="$params.$PilotLevel"/>
        <set_value name="$needsRepair" exact="$params.$NeedsRepair"/>
        <set_value name="$needsEquipment" exact="$params.$NeedsEquipment"/>
        <set_value name="$hullPercentage" exact="@$params.$HullPercentage"/>
        <set_value name="$repairThreshold" exact="@$params.$RepairThreshold"/>
        <set_value name="$shipIsGalaxyMiner" exact="false"/>
        <set_value name="$maxCollectorDronesToBuy" exact="5"/>
        
        <do_if value="$ship.defaultorder? and @$ship.defaultorder != null and @$ship.defaultorder.id == 'GalaxyMiner'">
          <set_value name="$shipIsGalaxyMiner" exact="true"/>
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$MaxCollectorDronesToBuy?">
            <set_value name="$maxCollectorDronesToBuy" exact="global.$GT_AIParameters.{$ship}.$MaxCollectorDronesToBuy"/>
          </do_if>
          <do_elseif value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$maxCollectorDronesToBuy?">
            <set_value name="$maxCollectorDronesToBuy" exact="global.$GT_AIParameters.{$ship}.$maxCollectorDronesToBuy"/>
          </do_elseif>
          <do_elseif value="$ship.defaultorder.$maxCollectorDronesToBuy?">
            <set_value name="$maxCollectorDronesToBuy" exact="$ship.defaultorder.$maxCollectorDronesToBuy"/>
          </do_elseif>
        </do_if>
        
        <!-- Re-resolve collector-drone shortage in execution context (queue-safe).
             Same logic as DoMaintenance lines ~178-203; can't pass through param table because
             the queued ProcessMaintenanceQueue path drops fields not in its own append_to_list.
             Gated on $maxCollectorDronesToBuy gt 0 and count==0 so an existing collector is never
             re-bought; target = slider amount capped at unit bay. -->
        <set_value name="$needsCollectorDrones" exact="false"/>
        <set_value name="$collectorMacro" exact="null"/>
        <set_value name="$collectorMacroLabel" exact="''"/>
        <set_value name="$collectorTargetCount" exact="0"/>
        <do_if value="$ship.iscapitalship and $maxCollectorDronesToBuy gt 0">
          <do_if value="$ship.waretransport.indexof.{waretransport.solid} and not $ship.units.{unitcategory.orecollector}.count">
            <set_value name="$needsCollectorDrones" exact="true"/>
            <set_value name="$collectorMacro" exact="macro.ship_gen_s_miningdrone_solid_01_a_macro"/>
            <set_value name="$collectorMacroLabel" exact="'orecollector'"/>
            <set_value name="$collectorTargetCount" exact="[$maxCollectorDronesToBuy, $ship.units.maxcount].min"/>
          </do_if>
          <do_elseif value="$ship.waretransport.indexof.{waretransport.liquid} and not $ship.units.{unitcategory.gascollector}.count">
            <set_value name="$needsCollectorDrones" exact="true"/>
            <set_value name="$collectorMacro" exact="macro.ship_gen_s_miningdrone_liquid_01_a_macro"/>
            <set_value name="$collectorMacroLabel" exact="'gascollector'"/>
            <set_value name="$collectorTargetCount" exact="[$maxCollectorDronesToBuy, $ship.units.maxcount].min"/>
          </do_elseif>
        </do_if>
        
        <!-- Get max jump distance -->
        <set_value name="$maxJumpDistance" exact="15"/>
        <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$MaxDistance?">
          <set_value name="$maxJumpDistance" exact="global.$GT_AIParameters.{$ship}.$MaxDistance"/>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance] ExecuteMaintenance for ' + $ship.idcode + ': maxJumpDistance=' + $maxJumpDistance + ', needsRepair=' + $needsRepair + ', needsEquipment=' + $needsEquipment + ', hullPercentage=' + $hullPercentage + ', repairThreshold=' + $repairThreshold" chance="100"/>
        </do_if>
        
        <!-- Track orders created -->
        <set_value name="$repairOrderCreated" exact="false"/>
        <set_value name="$equipmentOrderCreated" exact="false"/>
        
        <!-- ========================================================================= -->
        <!-- REPAIR FIRST (Priority)                                                  -->
        <!-- ========================================================================= -->
        
        <do_if value="$needsRepair">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] Finding repair station for ' + $ship.idcode" chance="100"/>
          </do_if>
          
          <!-- Find repair station -->
          <run_actions ref="FindNearestRepairStation" result="$repairStation">
            <param name="ship" value="$ship"/>
            <param name="maxJumpDistance" value="$maxJumpDistance"/>
          </run_actions>
          
          <do_if value="$repairStation and $repairStation.exists">
            <!-- Final reachability check BEFORE creating order using library function -->
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$reachabilityCheck">
              <param name="ship" value="$ship"/>
              <param name="station" value="$repairStation"/>
              <param name="returnDetails" value="true"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Final reachability check for repair station ' + $repairStation.knownname + ':'" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Station known: ' + $reachabilityCheck.$StationKnown" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Basic path (vanilla check): ' + $reachabilityCheck.$BasicPathDistance + ' jumps'" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Blacklist-aware path: ' + $reachabilityCheck.$BlacklistAwarePathDistance + ' jumps'" chance="100"/>
            </do_if>
            
            <!-- Station is unreachable if check fails -->
            <do_if value="not $reachabilityCheck.$IsReachable">
              <!-- Station is unreachable - log and continue trading -->
              <debug_text text="'[GT-Maintenance]   Repair station ' + $repairStation.knownname + ' is unreachable for ' + $ship.idcode + ' (' + $reachabilityCheck.$FailureReason + ') - will continue with trading'" chance="100"/>
              
              <!-- Write logbook message when repair station unreachable -->
              <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                <param name="ship" value="$ship"/>
              </run_actions>
              <do_if value="$logbookEnabled">
                <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
                <set_value name="$logbookMessage" exact="{77000,3212}.[$hullPercentage,$repairThreshold,$repairStation.knownname,$ship.knownname]"/>
                
                <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                  <param name="Message" value="$logbookMessage"/>
                  <param name="Category" value="'alerts'"/>
                  <param name="Title" value="'Auto-Repair Unreachable: ' + $ship.knownname"/>
                  <param name="Object" value="$ship"/>
                  <param name="Interaction" value="'showonmap'"/>
                  <param name="Highlighted" value="true"/>
                  <param name="CheckGlobalSettings" value="false"/>
                </run_actions>
              </do_if>
              
              <!-- Clear repair station so we don't try to create order -->
              <set_value name="$repairStation" exact="null"/>
            </do_if>
          </do_if>
          
          <do_if value="$repairStation and $repairStation.exists">
            <!-- Final docking check BEFORE creating order (dual probe) -->
            <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$repairDockResult">
              <param name="station" value="$repairStation"/>
              <param name="ship" value="$ship"/>
              <param name="purpose" value="'dual'"/>
            </run_actions>
            <do_if value="not $repairDockResult.$CanDock">
                <!-- Station is not dockable - log and continue trading -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Repair station ' + $repairStation.knownname + ' does not allow docking for ' + $ship.idcode + ' (trade restrictions, relation issues, or docking policy) - will continue with trading'" chance="100"/>
                </do_if>
                
                <!-- Write logbook message when repair station not dockable -->
                <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <do_if value="$logbookEnabled">
                  <!-- Only write logbook when debug is enabled -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$message" exact="{77000,3212}.[$hullPercentage,$repairThreshold,$repairStation.knownname,$ship.knownname]"/>
                    <write_to_logbook 
                      category="alerts" 
                      title="'Auto-Repair Unreachable: ' + $ship.knownname" 
                      text="$message"
                      interaction="showonmap" 
                      object="$ship"
                      highlighted="true"/>
                  </do_if>
                </do_if>
                
                <!-- Clear repair station so we don't try to create order -->
                <set_value name="$repairStation" exact="null"/>
            </do_if>
          </do_if>
          
          <do_if value="$repairStation and $repairStation.exists">
            <!-- Calculate cost -->
            <set_value name="$estimatedCost" exact="$ship.maxhull - $ship.hull"/>
            <set_value name="$playerMoney" exact="player.money"/>
            
            <do_if value="$playerMoney ge $estimatedCost">
              <!-- Prepare repair data for AI script -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Repair data prepared for ' + $ship.idcode + ' at ' + $repairStation.knownname + ' (cost: ' + ($estimatedCost/100) + ' Cr)'" chance="100"/>
              </do_if>
              
              <!-- Ensure table exists before accessing (handles race condition) -->
              <do_if value="not global.$GT_RepairOrders?">
                <set_value name="global.$GT_RepairOrders" exact="table[]"/>
              </do_if>
              
              <set_value name="global.$GT_RepairOrders.{$ship}" exact="table[
                $Station = $repairStation,
                $AcceptedCost = $estimatedCost
              ]"/>
              
              <!-- PERFORMANCE OPTIMIZATION: Defer UI operations (ship renaming, logbook messages) -->
              <!-- These operations don't affect gameplay and can be processed later to reduce spike size -->
              <do_if value="not global.$GT_DeferredUIUpdates?">
                <set_value name="global.$GT_DeferredUIUpdates" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_DeferredUIUpdates.{$ship}" exact="table[
                $Type = 'repair',
                $Ship = $ship,
                $Pilot = @$ship.pilot,
                $LogbookMessage = '{77000,3205}.[' + $hullPercentage + ',' + $repairThreshold + ',' + $pilotLevel + ',' + $repairStation.knownname + ',' + ($estimatedCost/100) + ',' + $ship.knownname + ']',
                $LogbookCategory = 'upkeep',
                $LogbookTitle = 'Auto-Repair: ' + $ship.knownname,
                $LogbookObject = $repairStation,
                $LogbookInteraction = 'showonmap'
              ]"/>
              <signal_cue_instantly cue="md.GT_Maintenance.ProcessDeferredUIUpdates"/>
              
              <set_value name="$repairOrderCreated" exact="true"/>
            </do_if>
            <do_elseif value="$playerMoney ge 5000Cr">
              <!-- Prepare partial repair data -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Partial repair data prepared for ' + $ship.idcode + ' (max: ' + ($playerMoney/100) + ' Cr)'" chance="100"/>
              </do_if>
              
              <!-- Ensure table exists before accessing (handles race condition) -->
              <do_if value="not global.$GT_RepairOrders?">
                <set_value name="global.$GT_RepairOrders" exact="table[]"/>
              </do_if>
              
              <set_value name="global.$GT_RepairOrders.{$ship}" exact="table[
                $Station = $repairStation,
                $AcceptedCost = $playerMoney
              ]"/>
              
              <!-- Write logbook entry about partial repair -->
              <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
              <set_value name="$logbookMessage" exact="{77000,3206}.[$hullPercentage,$repairThreshold,($playerMoney/100),($estimatedCost/100),$repairStation.knownname,$ship.knownname]"/>
              
              <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                <param name="Message" value="$logbookMessage"/>
                <param name="Category" value="'alerts'"/>
                <param name="Title" value="'Auto-Repair (Partial): ' + $ship.knownname"/>
                <param name="Object" value="$repairStation"/>
                <param name="Interaction" value="'showonmap'"/>
                <param name="Highlighted" value="true"/>
                <param name="CheckGlobalSettings" value="false"/>
              </run_actions>
              
              <set_value name="$repairOrderCreated" exact="true"/>
              
              <show_notification text="' ' + $ship.knownname + ' needs repairs but insufficient funds!\nCost: ' + ($estimatedCost/100) + ' Cr, Available: ' + ($playerMoney/100) + ' Cr\nAttempting partial repair.'" timeout="10s" priority="8"/>
            </do_elseif>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Insufficient funds for repair (' + ($playerMoney/100) + ' Cr available, need ' + ($estimatedCost/100) + ' Cr)'" chance="100"/>
              </do_if>
              <show_notification text="'' + $ship.knownname + ' needs repairs but insufficient funds!\nCost: ' + ($estimatedCost/100) + ' Cr, Available: ' + ($playerMoney/100) + ' Cr'" timeout="10s" priority="9"/>
            </do_else>
          </do_if>
          <do_else>
            <debug_text text="'[GT-Maintenance] No repair station found for ' + $ship.idcode" chance="100"/>
          </do_else>
        </do_if>
        
        <!-- ========================================================================= -->
        <!-- EQUIPMENT SECOND                                                          -->
        <!-- ========================================================================= -->
        
        <do_if value="$needsEquipment">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
            <debug_text text="'[GT-Maintenance] EQUIPMENT STATION SEARCH for ' + $ship.idcode" chance="100"/>
            <debug_text text="'[GT-Maintenance] Ship location: ' + @$ship.sector.knownname + ' (ID: ' + $ship.idcode + ')'" chance="100"/>
            <debug_text text="'[GT-Maintenance] Max jump distance: ' + $maxJumpDistance + ' jumps'" chance="100"/>
          </do_if>
          
          <!-- PERFORMANCE OPTIMIZATION: Cache station search results (stations don't change often) -->
          <!-- Cache key: 'equipment_stations' (same for all ships, stations rarely change) -->
          <!-- Cache age: 300 seconds (5 minutes) - stations can be destroyed/built, but rarely -->
          <set_value name="$cacheKey" exact="'equipment_stations'"/>
          <set_value name="$cacheAge" exact="300s"/>
          <set_value name="$useCache" exact="false"/>
          
          <!-- Check if cache exists and is fresh -->
          <!-- CRITICAL: Use {'$' + $cacheKey} pattern for string keys in X4 tables -->
          <set_value name="$cacheKeyWithDollar" exact="'$' + $cacheKey"/>
          <do_if value="global.$GT_MaintenanceStationCache? and global.$GT_MaintenanceStationCache.{$cacheKeyWithDollar}?">
            <set_value name="$cacheEntry" exact="global.$GT_MaintenanceStationCache.{$cacheKeyWithDollar}"/>
            <set_value name="$cacheTime" exact="@$cacheEntry.$Timestamp"/>
            <do_if value="(player.age - $cacheTime) lt $cacheAge">
              <set_value name="$useCache" exact="true"/>
              <!-- Extract cached lists and ensure they're lists (not null) -->
              <!-- CRITICAL: Always initialize as empty lists if cache values are null -->
              <set_value name="$cachedEquipmentDocks" exact="@$cacheEntry.$EquipmentDocks"/>
              <set_value name="$cachedWharfs" exact="@$cacheEntry.$Wharfs"/>
              <set_value name="$cachedShipyards" exact="@$cacheEntry.$Shipyards"/>
              
              <!-- Initialize as empty lists if null -->
              <set_value name="$potentialStations" exact="if $cachedEquipmentDocks? then $cachedEquipmentDocks else []"/>
              <set_value name="$wharfs" exact="if $cachedWharfs? then $cachedWharfs else []"/>
              <set_value name="$shipyards" exact="if $cachedShipyards? then $cachedShipyards else []"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Using cached equipment station search (age: ' + (player.age - $cacheTime) + 's, EquipmentDocks: ' + $potentialStations.count + ', Wharfs: ' + $wharfs.count + ', Shipyards: ' + $shipyards.count + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Only search if cache miss or expired -->
          <do_if value="not $useCache">
            <!-- Use capability-based search instead of station type checks -->
            <!-- Vanilla pattern: Stations can resupply if they can supply the ship's class -->
            <!-- Find stations that can supply equipment, then validate cansupplyclass manually -->
            <!-- Note: find_station doesn't support cansupplyclass filter directly, so we search broadly and validate capability -->
            <find_station name="$potentialStations" 
              space="player.galaxy" 
              multiple="true" 
              knownto="player.entity" 
              checkoperational="true" 
              sortbygatedistanceto="$ship"
              equipmentdock="true">
              <match class="class.station"/>
              <match_relation_to object="$ship" relation="dock" comparison="ge"/>
            </find_station>
            
            <!-- Also search wharfs and shipyards (they can also supply equipment) -->
            <find_station name="$wharfs" 
              space="player.galaxy" 
              multiple="true" 
              knownto="player.entity" 
              checkoperational="true" 
              sortbygatedistanceto="$ship"
              wharf="true">
              <match class="class.station"/>
              <match_relation_to object="$ship" relation="dock" comparison="ge"/>
            </find_station>
            
            <find_station name="$shipyards" 
              space="player.galaxy" 
              multiple="true" 
              knownto="player.entity" 
              checkoperational="true" 
              sortbygatedistanceto="$ship"
              shipyard="true">
              <match class="class.station"/>
              <match_relation_to object="$ship" relation="dock" comparison="ge"/>
            </find_station>
            
            <!-- Store in cache -->
            <!-- CRITICAL: Ensure lists are never null before storing in cache -->
            <do_if value="not global.$GT_MaintenanceStationCache?">
              <set_value name="global.$GT_MaintenanceStationCache" exact="table[]"/>
            </do_if>
            <!-- Ensure all lists are initialized (never null) -->
            <set_value name="$equipmentDocksToCache" exact="if $potentialStations? then $potentialStations else []"/>
            <set_value name="$wharfsToCache" exact="if $wharfs? then $wharfs else []"/>
            <set_value name="$shipyardsToCache" exact="if $shipyards? then $shipyards else []"/>
            <set_value name="global.$GT_MaintenanceStationCache.{$cacheKeyWithDollar}" exact="table[
              $EquipmentDocks = $equipmentDocksToCache,
              $Wharfs = $wharfsToCache,
              $Shipyards = $shipyardsToCache,
              $Timestamp = player.age
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Cached equipment station search results (EquipmentDocks: ' + $potentialStations.count + ', Wharfs: ' + $wharfs.count + ', Shipyards: ' + $shipyards.count + ')'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- PERFORMANCE: Cap candidate station lists before expensive per-station distance/validation work -->
          <!-- find_station results are already sorted by gate distance to ship; we only need "nearby enough" candidates -->
          <set_value name="$maxStationsPerType" exact="30"/>

          <!-- Limit equipment docks list -->
          <set_value name="$limitedEquipmentDocks" exact="[]"/>
          <set_value name="$equipCount" exact="if $potentialStations.count lt $maxStationsPerType then $potentialStations.count else $maxStationsPerType"/>
          <do_all exact="$equipCount" counter="$i">
            <append_to_list name="$limitedEquipmentDocks" exact="$potentialStations.{$i}"/>
          </do_all>
          <set_value name="$potentialStations" exact="$limitedEquipmentDocks"/>

          <!-- Limit wharfs list -->
          <set_value name="$limitedWharfs" exact="[]"/>
          <set_value name="$wharfCount" exact="if $wharfs.count lt $maxStationsPerType then $wharfs.count else $maxStationsPerType"/>
          <do_all exact="$wharfCount" counter="$i">
            <append_to_list name="$limitedWharfs" exact="$wharfs.{$i}"/>
          </do_all>
          <set_value name="$wharfs" exact="$limitedWharfs"/>

          <!-- Limit shipyards list -->
          <set_value name="$limitedShipyards" exact="[]"/>
          <set_value name="$shipyardCount" exact="if $shipyards.count lt $maxStationsPerType then $shipyards.count else $maxStationsPerType"/>
          <do_all exact="$shipyardCount" counter="$i">
            <append_to_list name="$limitedShipyards" exact="$shipyards.{$i}"/>
          </do_all>
          <set_value name="$shipyards" exact="$limitedShipyards"/>

          <!-- Combine all station types into one list (always needed, even with cache) -->
          <do_all exact="$wharfs.count" counter="$i">
            <append_to_list name="$potentialStations" exact="$wharfs.{$i}"/>
          </do_all>
          <do_all exact="$shipyards.count" counter="$i">
            <append_to_list name="$potentialStations" exact="$shipyards.{$i}"/>
          </do_all>
          
          <!-- Re-sort combined list by gate distance (equipment docks + wharfs + shipyards merged). -->
          <!-- v8 compat: standalone <sort_list> in v8 only supports sortbyvalue/sortdescending. The sortbygatedistanceto attribute is v9-only on this element. (It works on <find_station> via the sortresultwithlimit attributeGroup, which is why the find_station calls above keep that attribute unchanged.) Same ordering achieved here via the gatedistance.{$ship} script property. The find_station calls above already drop unreachable stations (sortbygatedistanceto on find_station auto-excludes objects with gatedistance == -1), so $potentialStations contains only reachable entries by this point. -->
          <sort_list list="$potentialStations" sortbyvalue="loop.element.gatedistance.{$ship}"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Found ' + $potentialStations.count + ' potential equipment stations (equipment docks + wharfs + shipyards, sorted by distance)'" chance="100"/>
          </do_if>
          
          <!-- Get blacklist group for pathfinding (needed before distance checks) -->
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Validate each station has resupply capability AND docking capability -->
          <!-- Vanilla check: station must be able to supply this ship class (cansupplyclass.{ship.class}) -->
          <set_value name="$validatedStations" exact="[]"/>
          <do_all exact="$potentialStations.count" counter="$i">
            <set_value name="$station" exact="$potentialStations.{$i}"/>
            <set_value name="$isValid" exact="true"/>
            
            <!-- CHECK 1: Verify resupply capability: can supply this ship class -->
            <set_value name="$canSupply" exact="@$station.cansupplyclass.{$ship.class}"/>
            <do_if value="not $canSupply">
              <set_value name="$isValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   SKIPPED station: ' + $station.knownname + ' - cannot supply ship class ' + $ship.class" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- CHECK 2: Service dual probe (bay + docking permission) -->
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$maintDockResult">
                <param name="station" value="$station"/>
                <param name="ship" value="$ship"/>
                <param name="purpose" value="'dual'"/>
              </run_actions>
              <do_if value="not $maintDockResult.$CanDock">
                <set_value name="$isValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   SKIPPED station: ' + $station.knownname + ' - dock preflight failed (' + $maintDockResult.$Reason + ') for ship size ' + $ship.docksize" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
            
            <do_if value="$isValid">
              <append_to_list name="$validatedStations" exact="$station"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   âœ“ Added station: ' + $station.knownname + ' (can supply class ' + $ship.class + ', docking bay size ' + $ship.docksize + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
          
          <!-- CRITICAL: Use validatedStations directly to avoid list copy issues -->
          <set_value name="$potentialStations" exact="$validatedStations"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Validated ' + $potentialStations.count + ' stations with resupply capability (can supply class ' + $ship.class + ') and docking capability (size ' + $ship.docksize + ')'" chance="100"/>
          </do_if>
          
          <!-- ============================================================= -->
          <!-- Find first station within distance that has STOCK           -->
          <!-- Try stations in order (sorted by distance), skip those      -->
          <!-- with no stock, take first one with ANY stock available      -->
          <!-- ============================================================= -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€'" chance="100"/>
            <debug_text text="'[GT-Maintenance] EVALUATING ' + $potentialStations.count + ' STATIONS...'" chance="100"/>
          </do_if>
          
          <set_value name="$equipmentStation" exact="null"/>
          <set_value name="$playerStationJumpPreference" exact="2"/>
          <set_value name="$nearestPlayerEquipmentStation" exact="null"/>
          <set_value name="$nearestPlayerEquipmentDistance" exact="999999"/>
          <set_value name="$nearestForeignEquipmentStation" exact="null"/>
          <set_value name="$nearestForeignEquipmentDistance" exact="999999"/>
          <set_value name="$stationsChecked" exact="0"/>
          <set_value name="$stationsWithNoStock" exact="0"/>
          <set_value name="$stationsSkippedDistance" exact="0"/>
          <set_value name="$stationsSkippedBlacklist" exact="0"/>
          <set_value name="$stationsSkippedDocking" exact="0"/>
          
          <!-- CRITICAL DEBUG: Verify list before loop -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] DEBUG: About to loop through ' + $potentialStations.count + ' stations, list exists: ' + $potentialStations?" chance="100"/>
            <do_if value="$potentialStations.count gt 0">
              <debug_text text="'[GT-Maintenance] DEBUG: First station: ' + $potentialStations.{1}.knownname" chance="100"/>
              <debug_text text="'[GT-Maintenance] DEBUG: List type check - count: ' + $potentialStations.count + ', validatedStations count: ' + $validatedStations.count" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- CRITICAL: Ensure we have stations to process -->
          <!-- PERFORMANCE: Limit to first 20 closest stations (already sorted by distance) -->
          <!-- This prevents processing hundreds of stations when only a few nearby ones matter -->
          <set_value name="$maxStationsToCheck" exact="20"/>
          <set_value name="$stationsToProcess" exact="if $potentialStations.count lt $maxStationsToCheck then $potentialStations.count else $maxStationsToCheck"/>
          
          <do_if value="$stationsToProcess gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] DEBUG: Processing ' + $stationsToProcess + ' of ' + $potentialStations.count + ' stations (limited to closest ' + $maxStationsToCheck + ')'" chance="100"/>
            </do_if>
            
            <do_all exact="$stationsToProcess" counter="$i">
            <!-- CRITICAL DEBUG: Log loop iteration start -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] DEBUG: Loop iteration ' + $i + ', equipmentStation is null: ' + ($equipmentStation == null)" chance="100"/>
            </do_if>
            
            <!-- CRITICAL: Extract station BEFORE any checks to ensure loop processes items -->
            <set_value name="$station" exact="$potentialStations.{$i}"/>
            
            <!-- CRITICAL DEBUG: Verify station was extracted correctly -->
            <do_if value="not $station?">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] ERROR: Station at index ' + $i + ' is null!'" chance="100"/>
              </do_if>
              <continue/>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€'" chance="100"/>
              <debug_text text="'[GT-Maintenance] Station [' + $i + '/' + $potentialStations.count + ']: ' + $station.knownname" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Owner: ' + @$station.owner.knownname" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Sector: ' + @$station.sector.knownname" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Type: Wharf=' + $station.iswharf + ', Shipyard=' + $station.isshipyard + ', EquipmentDock=' + $station.isequipmentdock" chance="100"/>
            </do_if>
            
            <!-- Determine blacklist group first (needed for pathfinding and blacklist checks) -->
            <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
              <param name="ship" value="$ship"/>
            </run_actions>
            
            <!-- SAFETY CHECK 1: Full reachability check (station known + basic path + blacklist-aware path) -->
            <!-- Check ALL reachability requirements BEFORE evaluating stock -->
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$reachabilityCheck">
              <param name="ship" value="$ship"/>
              <param name="station" value="$station"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="returnDetails" value="true"/>
            </run_actions>
            
            <do_if value="not $reachabilityCheck.$IsReachable">
              <!-- Station is unreachable - skip it -->
              <set_value name="$stationsSkippedDistance" operation="add"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]    SKIPPED - Not reachable (' + $reachabilityCheck.$FailureReason + ')'" chance="100"/>
                <debug_text text="'[GT-Maintenance]      Station known: ' + $reachabilityCheck.$StationKnown + ', Basic path: ' + $reachabilityCheck.$BasicPathDistance + ', Blacklist-aware: ' + $reachabilityCheck.$BlacklistAwarePathDistance" chance="100"/>
              </do_if>
              <continue/>
            </do_if>
            
            <!-- Extract distance from reachability check (use blacklist-aware distance) -->
            <set_value name="$distance" exact="$reachabilityCheck.$BlacklistAwarePathDistance"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]    Reachability check PASSED'" chance="100"/>
              <debug_text text="'[GT-Maintenance]    Distance (blacklist-aware): ' + $distance + ' jumps (max allowed: ' + $maxJumpDistance + ')'" chance="100"/>
            </do_if>
            
            <!-- SAFETY CHECK 2: Blacklist checks (station + sector) -->
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$stationBlacklisted">
              <param name="station" value="$station"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$sectorBlacklistDetails">
              <param name="sector" value="$station.sector"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="returnDetails" value="true"/>
            </run_actions>
            <set_value name="$sectorTravelBlacklisted" exact="$sectorBlacklistDetails.$TravelBlacklisted"/>
            <set_value name="$sectorActivityBlacklisted" exact="$sectorBlacklistDetails.$ActivityBlacklisted"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]    Blacklist: Station=' + $stationBlacklisted + ', SectorTravel=' + $sectorTravelBlacklisted + ', SectorActivity=' + $sectorActivityBlacklisted" chance="100"/>
            </do_if>
            
            <do_if value="$stationBlacklisted or $sectorTravelBlacklisted or $sectorActivityBlacklisted">
              <set_value name="$stationsSkippedBlacklist" operation="add"/>
              <set_value name="$blacklistReason" exact="if $stationBlacklisted then 'station unsafe' else if $sectorTravelBlacklisted then 'sector travel blocked (threat system)' else 'sector activity restricted'"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]    SKIPPED - Blacklisted (' + $blacklistReason + ')'" chance="100"/>
              </do_if>
              <continue/>
            </do_if>
            
            <!-- SAFETY CHECK 3: Skip if distance is too far -->
            <do_if value="$distance gt $maxJumpDistance">
              <set_value name="$stationsSkippedDistance" operation="add"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]    SKIPPED - Beyond max jump distance (' + $distance + ' > ' + $maxJumpDistance + ')'" chance="100"/>
              </do_if>
              <continue/>
            </do_if>
            
            <do_if value="$distance ge 0 and $distance le $maxJumpDistance">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]    Distance check PASSED - evaluating stock...'" chance="100"/>
              </do_if>
              <set_value name="$stationsChecked" operation="add"/>
              
              <!-- Recalculate what equipment is actually needed for stock check -->
              <set_value name="$countermeasureCapacity" exact="$ship.ammostorage.countermeasure.capacity"/>
              <set_value name="$currentCountermeasures" exact="$ship.ammostorage.countermeasure.count"/>
              <set_value name="$countermeasurePercentage" exact="if $countermeasureCapacity gt 0 then ($currentCountermeasures * 100) / $countermeasureCapacity else 100"/>
              
              <set_value name="$deployableCapacity" exact="$ship.ammostorage.deployable.capacity"/>
              <set_value name="$currentDeployables" exact="$ship.ammostorage.deployable.count"/>
              <set_value name="$deployablePercentage" exact="if $deployableCapacity gt 0 then ($currentDeployables * 100) / $deployableCapacity else 100"/>
              
              <set_value name="$countermeasureThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold"/>
              <set_value name="$unifiedThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold"/>
              
              <!-- Recalculate needs inside loop (check units too!) -->
              <set_value name="$unitsCapacity" exact="@$ship.units.maxcount"/>
              <set_value name="$needsCountermeasures" exact="$countermeasureCapacity gt 0 and $countermeasurePercentage lt $countermeasureThreshold"/>
              <!-- Don't check deployables (mines/satellites) for trading ships -->
              <set_value name="$needsDeployables" exact="false"/>
              <!-- For units, always check loadout (ship may have more than loadout wants) -->
              <set_value name="$needsUnits" exact="$unitsCapacity gt 0"/>
              
              <!-- S/M deployable laser towers: check station stock when towers are below threshold -->
              <set_value name="$needsDeployableLaserTowers" exact="false"/>
              <set_value name="$deployableTowerWare" exact="null"/>
              <do_if value="$unitsCapacity == 0 and $deployableCapacity gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers">
                <set_value name="$balanceProfile" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile"/>
                <do_if value="not $balanceProfile?">
                  <set_value name="$balanceProfile" exact="2"/>
                </do_if>
                <set_value name="$laserTowerPct" exact="20"/>
                <do_if value="$balanceProfile == 4">
                  <set_value name="$laserTowerPct" exact="30"/>
                </do_if>
                <set_value name="$deployableLaserTowerTarget" exact="[($deployableCapacity * $laserTowerPct / 100)i, 1].max"/>
                <set_value name="$currentDeployableLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
                <set_value name="$deployableLaserTowerPercentage" exact="if $deployableLaserTowerTarget gt 0 then ($currentDeployableLaserTowers * 100) / $deployableLaserTowerTarget else 100"/>
                <set_value name="$needsDeployableLaserTowers" exact="$deployableLaserTowerTarget gt 0 and $deployableLaserTowerPercentage lt $unifiedThreshold"/>
                <remove_value name="$laserTowerPct"/>
                <remove_value name="$deployableLaserTowerTarget"/>
                <remove_value name="$currentDeployableLaserTowers"/>
                <remove_value name="$deployableLaserTowerPercentage"/>
                <remove_value name="$balanceProfile"/>
              </do_if>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   Ship needs: CM=' + $needsCountermeasures + ', Units=' + $needsUnits + ', DeployableTowers=' + $needsDeployableLaserTowers" chance="100"/>
              </do_if>
              
              <!-- Capability and docking already validated earlier (lines 428-448) -->
              <!-- Now we only need to check stock availability (like vanilla) -->
              <set_value name="$canSupply" exact="false"/>
              
              <!-- Build evaluation tables like vanilla does to check stock -->
              <set_value name="$evalammotable" exact="null"/>
              <set_value name="$evalunittable" exact="null"/>
              
              <!-- Check countermeasures stock -->
              <do_if value="$needsCountermeasures">
                <set_value name="$availableCM" exact="@$station.buildequipment.countermeasures.list"/>
                <do_if value="@$availableCM.count gt 0">
                  <!-- Create evaluation table with quantity=1 for each ware (vanilla pattern) -->
                  <set_value name="$evalammotable" exact="table[]"/>
                  <do_all exact="$availableCM.count" counter="$j">
                    <set_value name="$evalammotable.{$availableCM.{$j}}" exact="1"/>
                  </do_all>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Maintenance]   Eval ammo table has ' + @$evalammotable.keys.count + ' types'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- Miner collector-drone restock check: require the candidate equipment dock to actually
                   stock the matching ore/gas collector macro before letting it qualify. Without this
                   filter we'd happily route the ship to a dock that sells probes + CMs but no collector
                   drones, the dock would silently drop the collector entry from add_build_to_modify_ship,
                   and the ship would return still missing collectors -> mining routine still fails. -->
              <do_if value="$needsCollectorDrones and $collectorMacro != null">
                <do_if value="not $evalunittable">
                  <set_value name="$evalunittable" exact="table[]"/>
                </do_if>
                <set_value name="$evalunittable.{$collectorMacro.ware}" exact="$collectorTargetCount"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Added ' + $collectorMacroLabel + ' requirement to unit eval table (ware=' + $collectorMacro.ware + ', amount=' + $collectorTargetCount + ')'" chance="100"/>
                </do_if>
              </do_if>
              
              <!-- S/M deployable laser tower stock check (only when below threshold) -->
              <do_if value="$needsDeployableLaserTowers">
                <do_if value="$ship.ammostorage.{deployablecategory.lasertower}.count gt 0">
                  <set_value name="$deployableTowerWare" exact="@$ship.ammostorage.{deployablecategory.lasertower}.list.{1}.ware"/>
                </do_if>
                <do_else>
                  <set_value name="$towerMk" exact="2"/>
                  <do_if value="$ship.docksize == tag.dock_xs">
                    <set_value name="$towerMk" exact="1"/>
                  </do_if>
                  <set_value name="$deployableTowerWare" exact="deployablecategory.lasertower.mk.{$towerMk}.list.{1}.ware"/>
                  <remove_value name="$towerMk"/>
                </do_else>
                <do_if value="$deployableTowerWare">
                  <do_if value="not $evalammotable">
                    <set_value name="$evalammotable" exact="table[]"/>
                  </do_if>
                  <set_value name="$evalammotable.{$deployableTowerWare}" exact="1"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Maintenance]   Added deployable lasertower requirement to ammo eval table (ware=' + $deployableTowerWare + ')'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
              
              <!-- NOTE: Mines/satellites are NOT auto-restocked for trading ships -->
              
              <!-- Now check stock using vanilla's exact logic -->
              <!-- Check each category we need, station passes if it has stock for ALL needed categories -->
              <set_value name="$hasAmmoStock" exact="true"/>
              <set_value name="$hasUnitDroneStock" exact="true"/>
              
              <do_if value="($needsCountermeasures or $needsDeployableLaserTowers) and $evalammotable">
                <set_value name="$canBuildAmmo" exact="$station.canbuildequipment.{$evalammotable.keys.list}"/>
                <set_value name="$hasAmmoResources" exact="$station.hasresourcesfor.{$evalammotable}"/>
                <set_value name="$hasAmmoStock" exact="$canBuildAmmo and $hasAmmoResources"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Ammo check: canBuild=' + $canBuildAmmo + ', hasResources=' + $hasAmmoResources + ', result=' + $hasAmmoStock" chance="100"/>
                </do_if>
              </do_if>
              <do_elseif value="($needsCountermeasures or $needsDeployableLaserTowers) and not $evalammotable">
                <!-- Need ammo/deployables but no eval table - fail -->
                <set_value name="$hasAmmoStock" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Ammo check: no eval table, result=false'" chance="100"/>
                </do_if>
              </do_elseif>
              
              <!-- Check for UNITS (defense drones, laser towers, etc.) -->
              <!-- Note: We already validated cansupplyclass earlier, so station can supply this ship class -->
              <do_if value="$needsUnits">
                <!-- For units/drones, check if station can build units (shipyard/wharf) or is equipment dock that can supply -->
                <!-- Vanilla resupply will handle the complex unit selection -->
                <set_value name="$hasUnitDroneStock" exact="$station.isshipyard or $station.iswharf or $station.isequipmentdock"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Units/Drones check: isShipyard=' + $station.isshipyard + ', isWharf=' + $station.iswharf + ', isEquipmentDock=' + $station.isequipmentdock + ', result=' + $hasUnitDroneStock" chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Collector-drone availability check: harden the unit-stock check above when we
                   specifically need a collector. The generic "is wharf/shipyard/equipment dock"
                   gate isn't enough - many equipment docks don't actually stock mining drones
                   (loadoutrules.xml only assigns mining drones to ship_l/ship_xl + purpose=mine,
                   so smaller dockyards skip them entirely). Use canbuildequipment + hasresourcesfor
                   on the collector ware itself, exact same pattern as the ammo check at line 1079. -->
              <do_if value="$needsCollectorDrones and $collectorMacro != null and $hasUnitDroneStock">
                <set_value name="$canBuildCollector" exact="$station.canbuildequipment.{[$collectorMacro.ware]}"/>
                <set_value name="$hasCollectorResources" exact="$station.hasresourcesfor.{table[{$collectorMacro.ware} = $collectorTargetCount]}"/>
                <set_value name="$hasUnitDroneStock" exact="$canBuildCollector and $hasCollectorResources"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Collector check (' + $collectorMacroLabel + '): canBuild=' + $canBuildCollector + ', hasResources=' + $hasCollectorResources + ', result=' + $hasUnitDroneStock" chance="100"/>
                </do_if>
                <remove_value name="$canBuildCollector"/>
                <remove_value name="$hasCollectorResources"/>
              </do_if>
              
              <!-- Station passes if it has stock for ALL needed categories (all must be true) -->
              <set_value name="$canSupply" exact="$hasAmmoStock and $hasUnitDroneStock"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   Final: hasAmmoStock=' + $hasAmmoStock + ', hasUnitDroneStock=' + $hasUnitDroneStock + ', canSupply=' + $canSupply" chance="100"/>
              </do_if>
              
              <do_if value="$canSupply">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Station has stock for required items'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]    Station has no stock for any required items'" chance="100"/>
                </do_if>
              </do_else>
              
              <!-- If this station can supply, track nearest valid player/foreign candidate -->
              <do_if value="$canSupply">
                <do_if value="$station.owner == faction.player">
                  <do_if value="$distance lt $nearestPlayerEquipmentDistance">
                    <set_value name="$nearestPlayerEquipmentStation" exact="$station"/>
                    <set_value name="$nearestPlayerEquipmentDistance" exact="$distance"/>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="$distance lt $nearestForeignEquipmentDistance">
                    <set_value name="$nearestForeignEquipmentStation" exact="$station"/>
                    <set_value name="$nearestForeignEquipmentDistance" exact="$distance"/>
                  </do_if>
                </do_else>
              </do_if>
              <do_else>
                <!-- Station cannot supply, try next one -->
                <set_value name="$stationsWithNoStock" operation="add"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]     SKIPPED - Cannot supply required items'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
          </do_all>
          </do_if>
          
          <!-- Final equipment station selection with player-station preference -->
          <do_if value="$nearestPlayerEquipmentStation and $nearestForeignEquipmentStation">
            <do_if value="$nearestPlayerEquipmentDistance le ($nearestForeignEquipmentDistance + $playerStationJumpPreference)">
              <set_value name="$equipmentStation" exact="$nearestPlayerEquipmentStation"/>
            </do_if>
            <do_else>
              <set_value name="$equipmentStation" exact="$nearestForeignEquipmentStation"/>
            </do_else>
          </do_if>
          <do_elseif value="$nearestPlayerEquipmentStation">
            <set_value name="$equipmentStation" exact="$nearestPlayerEquipmentStation"/>
          </do_elseif>
          <do_elseif value="$nearestForeignEquipmentStation">
            <set_value name="$equipmentStation" exact="$nearestForeignEquipmentStation"/>
          </do_elseif>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $equipmentStation">
            <debug_text text="'[GT-Maintenance] Equipment station preference: selected ' + $equipmentStation.knownname + ' (player dist=' + $nearestPlayerEquipmentDistance + ', foreign dist=' + $nearestForeignEquipmentDistance + ', threshold=' + $playerStationJumpPreference + ')'" chance="100"/>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
            <debug_text text="'[GT-Maintenance] STATION SEARCH SUMMARY:'" chance="100"/>
            <debug_text text="'[GT-Maintenance]    Total found: ' + $potentialStations.count + ' (checked: ' + (if $stationsToProcess? then $stationsToProcess else 0) + ')'" chance="100"/>
            <debug_text text="'[GT-Maintenance]    Skipped (blacklisted): ' + $stationsSkippedBlacklist" chance="100"/>
            <debug_text text="'[GT-Maintenance]    Skipped (distance): ' + $stationsSkippedDistance" chance="100"/>
            <debug_text text="'[GT-Maintenance]    Skipped (no docking rights): ' + $stationsSkippedDocking" chance="100"/>
            <debug_text text="'[GT-Maintenance]    Checked for stock: ' + $stationsChecked" chance="100"/>
            <debug_text text="'[GT-Maintenance]    No stock available: ' + $stationsWithNoStock" chance="100"/>
            <debug_text text="'[GT-Maintenance]    Selected station: ' + if $equipmentStation then $equipmentStation.knownname else 'NONE'" chance="100"/>
            <debug_text text="'[GT-Maintenance] â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•'" chance="100"/>
          </do_if>
          
          <do_if value="$stationsChecked gt 0 and not $equipmentStation">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]  WARNING: Checked ' + $stationsChecked + ' station(s), but NONE can supply equipment - will retry after next trade'" chance="100"/>
            </do_if>
          </do_if>
          
          <do_if value="not $equipmentStation and $potentialStations.count == 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]  WARNING: NO stations found in galaxy - check if player owns any wharfs/equipment docks/shipyards'" chance="100"/>
            </do_if>
          </do_if>
          
          <do_if value="$equipmentStation and $equipmentStation.exists">
            <!-- Final docking check BEFORE creating order -->
            <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$equipDockResult">
              <param name="station" value="$equipmentStation"/>
              <param name="ship" value="$ship"/>
              <param name="purpose" value="'dual'"/>
            </run_actions>
            <do_if value="not $equipDockResult.$CanDock">
                <!-- Station is not dockable - log and continue trading -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   Equipment station ' + $equipmentStation.knownname + ' does not allow docking for ' + $ship.idcode + ' (trade restrictions, relation issues, or docking policy) - will continue with trading'" chance="100"/>
                </do_if>
                
                <!-- Write logbook message when equipment station not dockable -->
                <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <do_if value="$logbookEnabled">
                  <!-- Only write logbook when debug is enabled -->
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$message" exact="{77000,3213}.[$equipmentStation.knownname,$ship.knownname]"/>
                    <write_to_logbook 
                      category="alerts" 
                      title="'Auto-Resupply Unreachable: ' + $ship.knownname" 
                      text="$message"
                      interaction="showonmap" 
                      object="$ship"
                      highlighted="true"/>
                  </do_if>
                </do_if>
                
                <!-- Clear equipment station so we don't try to create order -->
                <set_value name="$equipmentStation" exact="null"/>
            </do_if>
          </do_if>
          
          <do_if value="$equipmentStation and $equipmentStation.exists">
            <!-- Station found - build shopping list using vanilla's pattern -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Building shopping list for ' + $ship.idcode + ' at ' + $equipmentStation.knownname" chance="100"/>
            </do_if>
            
            <!-- Save current equipment levels to compare after resupply -->
            <set_value name="$currentDeployables" exact="$ship.ammostorage.deployable.count"/>
            <set_value name="$currentCM" exact="$ship.ammostorage.countermeasure.count"/>
            <set_value name="$currentUnitsCount" exact="$ship.units.count"/>
            
            <!-- Get counts for each specific unit type BEFORE resupply -->
            <!-- Note: Use macro directly, not macro.ware (vanilla pattern: units.{macro}.count) -->
            <set_value name="$beforeDefenseDrones" exact="$ship.units.{macro.ship_gen_s_fightingdrone_01_a_macro}.count"/>
            <set_value name="$beforeCargoDrones" exact="$ship.units.{macro.ship_gen_xs_cargodrone_empty_01_a_macro}.count"/>
            <do_if value="$ship.units.maxcount == 0">
              <set_value name="$beforeLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
            </do_if>
            <do_else>
              <set_value name="$beforeLaserTowers" exact="$ship.units.{macro.ship_gen_xs_lasertower_01_a_macro}.count"/>
            </do_else>
            <set_value name="$beforeRepairDrones" exact="$ship.units.{macro.ship_gen_xs_repairdrone_01_a_macro}.count"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] EQUIPMENT COUNTS BEFORE RESUPPLY for ' + $ship.idcode + ':'" chance="100"/>
              <debug_text text="'[GT-Maintenance]   Countermeasures: ' + $currentCM + '/' + $countermeasureCapacity" chance="100"/>
              <debug_text text="'[GT-Maintenance]   Defense Drones: ' + $beforeDefenseDrones" chance="100"/>
              <debug_text text="'[GT-Maintenance]   Cargo Drones: ' + $beforeCargoDrones" chance="100"/>
              <debug_text text="'[GT-Maintenance]   Laser Towers: ' + $beforeLaserTowers" chance="100"/>
              <debug_text text="'[GT-Maintenance]   Repair Drones: ' + $beforeRepairDrones" chance="100"/>
              <debug_text text="'[GT-Maintenance]   Total Units: ' + $currentUnitsCount + '/' + $unitsCapacity" chance="100"/>
            </do_if>
            
            <!-- Recalculate what ship needs (for shopping list) -->
            <set_value name="$countermeasureCapacity" exact="$ship.ammostorage.countermeasure.capacity"/>
            <set_value name="$currentCountermeasures" exact="$ship.ammostorage.countermeasure.count"/>
            <set_value name="$countermeasurePercentage" exact="if $countermeasureCapacity gt 0 then ($currentCountermeasures * 100) / $countermeasureCapacity else 100"/>
            
            <set_value name="$deployableCapacity" exact="$ship.ammostorage.deployable.capacity"/>
            <set_value name="$currentDeployablesPercentage" exact="$ship.ammostorage.deployable.count"/>
            <set_value name="$deployablePercentage" exact="if $deployableCapacity gt 0 then ($currentDeployablesPercentage * 100) / $deployableCapacity else 100"/>
            
            <set_value name="$unitsCapacity" exact="$ship.units.maxcount"/>
            <set_value name="$currentUnits" exact="$ship.units.count"/>
            <set_value name="$unitsPercentage" exact="if $unitsCapacity gt 0 then ($currentUnits * 100) / $unitsCapacity else 100"/>
            
            <set_value name="$countermeasureThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold"/>
            <set_value name="$unifiedThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold"/>
            <set_value name="$needsCountermeasures" exact="$countermeasureCapacity gt 0 and $countermeasurePercentage lt $countermeasureThreshold"/>
            <set_value name="$needsDeployables" exact="false"/>
            <!-- Only restock Units if capacity exists AND percentage is below threshold -->
            <set_value name="$needsUnits" exact="$unitsCapacity gt 0 and $unitsPercentage lt $unifiedThreshold"/>
            <set_value name="$needsDeployableLaserTowers" exact="false"/>
            <do_if value="$unitsCapacity == 0 and $deployableCapacity gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers">
              <set_value name="$balanceProfile" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile"/>
              <do_if value="not $balanceProfile?">
                <set_value name="$balanceProfile" exact="2"/>
              </do_if>
              <set_value name="$laserTowerPct" exact="20"/>
              <do_if value="$balanceProfile == 4">
                <set_value name="$laserTowerPct" exact="30"/>
              </do_if>
              <set_value name="$deployableLaserTowerTarget" exact="[($deployableCapacity * $laserTowerPct / 100)i, 1].max"/>
              <set_value name="$currentDeployableLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
              <set_value name="$deployableLaserTowerPercentage" exact="if $deployableLaserTowerTarget gt 0 then ($currentDeployableLaserTowers * 100) / $deployableLaserTowerTarget else 100"/>
              <set_value name="$needsDeployableLaserTowers" exact="$deployableLaserTowerTarget gt 0 and $deployableLaserTowerPercentage lt $unifiedThreshold"/>
              <remove_value name="$laserTowerPct"/>
              <remove_value name="$deployableLaserTowerTarget"/>
              <remove_value name="$currentDeployableLaserTowers"/>
              <remove_value name="$deployableLaserTowerPercentage"/>
              <remove_value name="$balanceProfile"/>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]   Ship needs: CM=' + $needsCountermeasures + ' (' + $countermeasurePercentage + '%), Units=' + $needsUnits + ' (' + $unitsPercentage + '%), DeployableTowers=' + $needsDeployableLaserTowers" chance="100"/>
            </do_if>
            
            <!-- ALWAYS initialize to empty tables (not null) -->
            <!-- If ammotable/unittable are null, add_build_to_modify_ship CLEARS all countermeasures/units! -->
            <!-- Build ammo/unit tables like vanilla does -->
            <set_value name="$ammotable" exact="table[]"/>
            <set_value name="$unittable" exact="table[]"/>
            
            <!-- Get loadout level (determines what equipment to buy) -->
            <set_value name="$loadoutlevel" exact="$ship.loadoutlevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]   Loadout level: ' + $loadoutlevel" chance="100"/>
            </do_if>
            
            <!-- Evaluate what UNITS ship needs (drones/towers) using Balance Profile -->
            <!-- ALWAYS build unit list if ship has unit capacity - this ensures we restock EVERYTHING in one trip -->
            <do_if value="$ship.units.maxcount gt 0">
              <!-- Use Balance Profile to determine unit distribution -->
              <set_value name="$balanceProfile" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile"/>
              <do_if value="not $balanceProfile?">
                <set_value name="$balanceProfile" exact="2"/> <!-- Default: Trading-Focused -->
              </do_if>
              
              <!-- Get distribution percentages from Balance Profile -->
              <set_value name="$distribution" exact="table[
                $DefenseDrones = 20,
                $TradeDrones = 50,
                $LaserTowers = 20,
                $RepairDrones = 10
              ]"/>
              
              <do_if value="$balanceProfile == 0">
                <!-- Balanced -->
                <set_value name="$distribution.$DefenseDrones" exact="35"/>
                <set_value name="$distribution.$TradeDrones" exact="35"/>
                <set_value name="$distribution.$LaserTowers" exact="20"/>
                <set_value name="$distribution.$RepairDrones" exact="10"/>
              </do_if>
              <do_elseif value="$balanceProfile == 1">
                <!-- Defensive -->
                <set_value name="$distribution.$DefenseDrones" exact="50"/>
                <set_value name="$distribution.$TradeDrones" exact="20"/>
                <set_value name="$distribution.$LaserTowers" exact="20"/>
                <set_value name="$distribution.$RepairDrones" exact="10"/>
              </do_elseif>
              <do_elseif value="$balanceProfile == 3">
                <!-- Heavy Defense -->
                <set_value name="$distribution.$DefenseDrones" exact="40"/>
                <set_value name="$distribution.$TradeDrones" exact="30"/>
                <set_value name="$distribution.$LaserTowers" exact="20"/>
                <set_value name="$distribution.$RepairDrones" exact="10"/>
              </do_elseif>
              <do_elseif value="$balanceProfile == 4">
                <!-- Tower Support -->
                <set_value name="$distribution.$DefenseDrones" exact="30"/>
                <set_value name="$distribution.$TradeDrones" exact="30"/>
                <set_value name="$distribution.$LaserTowers" exact="30"/>
                <set_value name="$distribution.$RepairDrones" exact="10"/>
              </do_elseif>
              <!-- Default is already set: Profile 2 = Trading-Focused -->
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   Balance Profile ' + $balanceProfile + ': Defense=' + $distribution.$DefenseDrones + '%, Trade=' + $distribution.$TradeDrones + '%, Towers=' + $distribution.$LaserTowers + '%, Repair=' + $distribution.$RepairDrones + '%'" chance="100"/>
              </do_if>
              
              <!-- Calculate target quantities based on capacity and percentages -->
              <set_value name="$totalCapacity" exact="$ship.units.maxcount"/>
              <set_value name="$targetDefense" exact="(($totalCapacity * $distribution.$DefenseDrones) / 100)i"/>
              <set_value name="$targetTrade" exact="(($totalCapacity * $distribution.$TradeDrones) / 100)i"/>
              <set_value name="$targetTowers" exact="(($totalCapacity * $distribution.$LaserTowers) / 100)i"/>
              <set_value name="$targetRepair" exact="(($totalCapacity * $distribution.$RepairDrones) / 100)i"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   Targets (capacity=' + $totalCapacity + '): Defense=' + $targetDefense + ', Trade=' + $targetTrade + ', Towers=' + $targetTowers + ', Repair=' + $targetRepair" chance="100"/>
              </do_if>
              
              <!-- Build unit shopping list using Balance Profile (like vanilla does in interrupt.restock line 603) -->
              <!-- Initialize unittable BEFORE adding existing units (happens later) -->
              <!-- We set TARGET amounts here, then add EXISTING amounts later to preserve them -->
              <set_value name="$unittable" exact="table[]"/>
              
              <!-- Get current counts BEFORE setting targets (needed for later preservation logic) -->
              <set_value name="$currentDefenseCount" exact="$ship.units.{macro.ship_gen_s_fightingdrone_01_a_macro}.count"/>
              <set_value name="$currentCargoCount" exact="$ship.units.{macro.ship_gen_xs_cargodrone_empty_01_a_macro}.count"/>
              <set_value name="$currentTowerCount" exact="$ship.units.{macro.ship_gen_xs_lasertower_01_a_macro}.count"/>
              <set_value name="$currentRepairCount" exact="$ship.units.{macro.ship_gen_xs_repairdrone_01_a_macro}.count"/>
              
              <!-- Use hardcoded macro references (EXACTLY like vanilla) - macro.XXX.ware works at runtime! -->
              <!-- Set TARGET amounts (will be adjusted by existing amounts later) -->
              <do_if value="$targetDefense gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockDefenseDrones">
                <set_value name="$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware}" exact="$targetDefense"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   - Target Defense Drones: ' + $targetDefense + ' (current: ' + $currentDefenseCount + ')'" chance="100"/>
                </do_if>
              </do_if>
              
              <do_if value="$targetTrade gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockTradeDrones">
                <set_value name="$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware}" exact="$targetTrade"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   - Target Trade Drones: ' + $targetTrade + ' (current: ' + $currentCargoCount + ')'" chance="100"/>
                </do_if>
              </do_if>
              
              <do_if value="$targetTowers gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers">
                <set_value name="$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware}" exact="$targetTowers"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   - Target Laser Towers: ' + $targetTowers + ' (current: ' + $currentTowerCount + ')'" chance="100"/>
                </do_if>
              </do_if>
              
              <do_if value="$targetRepair gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockRepairDrones">
                <set_value name="$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware}" exact="$targetRepair"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   - Target Repair Drones: ' + $targetRepair + ' (current: ' + $currentRepairCount + ')'" chance="100"/>
                </do_if>
              </do_if>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   Shopping list (targets) has ' + @$unittable.keys.count + ' unit types'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- S/M ships: laser towers live in deployable bay (ammostorage), not unit docks.
                 add_build_to_modify_ship SETS deployables - preserve ALL existing deployable ammo
                 on every equip trip, then top up laser towers per Balance Profile when enabled. -->
            <do_if value="$deployableCapacity gt 0">
              <do_for_each name="$deployableMacro" in="$ship.ammostorage.deployable.list">
                <set_value name="$ammotable.{$deployableMacro.ware}" exact="$ship.ammostorage.{$deployableMacro}.count"/>
              </do_for_each>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $ship.ammostorage.deployable.list.count gt 0">
                <debug_text text="'[GT-Maintenance]   - Preserving ' + $ship.ammostorage.deployable.list.count + ' deployable ammo type(s) on ship'" chance="100"/>
              </do_if>
            </do_if>
            
            <do_if value="$ship.units.maxcount == 0 and $deployableCapacity gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers and $needsDeployableLaserTowers">
              <set_value name="$balanceProfile" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile"/>
              <do_if value="not $balanceProfile?">
                <set_value name="$balanceProfile" exact="2"/>
              </do_if>
              <set_value name="$laserTowerPct" exact="20"/>
              <do_if value="$balanceProfile == 4">
                <set_value name="$laserTowerPct" exact="30"/>
              </do_if>
              <set_value name="$deployableLaserTowerTarget" exact="[($deployableCapacity * $laserTowerPct / 100)i, 1].max"/>
              <set_value name="$currentDeployableLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
              <set_value name="$otherDeployableCount" exact="$currentDeployables - $currentDeployableLaserTowers"/>
              <set_value name="$maxDeployableTowers" exact="[$deployableCapacity - $otherDeployableCount, 0].max"/>
              <set_value name="$finalDeployableTowerCount" exact="[$deployableLaserTowerTarget, $maxDeployableTowers].min"/>
              
              <set_value name="$deployableTowerWare" exact="null"/>
              <do_if value="$ship.ammostorage.{deployablecategory.lasertower}.count gt 0">
                <set_value name="$deployableTowerWare" exact="@$ship.ammostorage.{deployablecategory.lasertower}.list.{1}.ware"/>
              </do_if>
              <do_else>
                <set_value name="$towerMk" exact="2"/>
                <do_if value="$ship.docksize == tag.dock_xs">
                  <set_value name="$towerMk" exact="1"/>
                </do_if>
                <set_value name="$deployableTowerWare" exact="deployablecategory.lasertower.mk.{$towerMk}.list.{1}.ware"/>
                <remove_value name="$towerMk"/>
              </do_else>
              <do_if value="$deployableTowerWare and $equipmentStation and not $equipmentStation.canbuildequipment.{[$deployableTowerWare]}">
                <set_value name="$deployableTowerWare" exact="null"/>
                <do_for_each name="$ltWare" in="$equipmentStation.buildequipment.lasertowers.list">
                  <set_value name="$deployableTowerWare" exact="$ltWare"/>
                  <break/>
                </do_for_each>
              </do_if>
              
              <do_if value="$deployableTowerWare and $finalDeployableTowerCount gt 0">
                <set_value name="$ammotable.{$deployableTowerWare}" exact="$finalDeployableTowerCount"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]   - Target Deployable Laser Towers: ' + $finalDeployableTowerCount + ' (profile ' + $laserTowerPct + '%, current: ' + $currentDeployableLaserTowers + ', ware: ' + $deployableTowerWare + ')'" chance="100"/>
                </do_if>
              </do_if>
              <remove_value name="$laserTowerPct"/>
              <remove_value name="$otherDeployableCount"/>
              <remove_value name="$maxDeployableTowers"/>
              <remove_value name="$finalDeployableTowerCount"/>
              <remove_value name="$deployableTowerWare"/>
              <remove_value name="$balanceProfile"/>
            </do_if>
            
            <!-- NOTE: Mines/satellites are only preserved (not auto-restocked) for trading ships -->
            
            <!-- NOTE: Countermeasure preservation happens AFTER this section (see lines ~1000+) -->
            <!-- We preserve CM up to capacity there, so we don't need to build CM shopping list here -->
            <!-- The preservation logic handles both "needed" and "not needed" cases -->
            
            <!-- add_build_to_modify_ship SETS inventory, doesn't ADD to it! -->
            <!-- We MUST include CURRENT equipment in tables to preserve it -->
            <!-- Pattern from vanilla interrupt.restock.xml lines 979-991 and 1009-1021 -->
            
            <!-- ALWAYS fill CM to MAX capacity -->
            <!-- add_build_to_modify_ship SETS inventory - we must set CM to capacity to preserve it -->
            <do_if value="$countermeasureCapacity gt 0">
              <!-- Get available CM types from station -->
              <set_value name="$availableCM" exact="@$equipmentStation.buildequipment.countermeasures.list"/>
              <do_if value="@$availableCM.count gt 0">
                <!-- Distribute MAX capacity across available CM types -->
                <set_value name="$cmPerType" exact="($countermeasureCapacity / $availableCM.count)i"/>
                <do_all exact="$availableCM.count" counter="$j">
                  <set_value name="$cmMacro" exact="$availableCM.{$j}"/>
                  <!-- Always set to MAX capacity -->
                  <set_value name="$ammotable.{$cmMacro}" exact="$cmPerType"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Maintenance]   - Setting CM to MAX: ' + $cmMacro + ' x' + $cmPerType + ' (capacity=' + $countermeasureCapacity + ')'" chance="100"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
            
            <!-- Collector-drone insertion was previously HERE but moved to AFTER the existing-units
                 preservation block below: the preservation block at lines ~1580-1583 add_value's
                 the ship's CURRENT defense/cargo/tower/repair counts on top of whatever balance-
                 profile targets we set. For a fully-loaded miner (e.g. 10/10 units of defense drones),
                 a pre-preservation trim got silently undone here - the final shopping list ended up
                 at preserve(10) + balanceProfile(~10) + collector(5) = ~25 entries, which the wharf
                 truncated arbitrarily, almost always dropping the collector ware.
                 The only reliable place to trim for collector slots is AFTER preservation, so the
                 trim sees the COMPLETE assembled table and can reduce non-collector categories
                 down to (maxcount - collectorTarget) before collectors are appended. See block
                 below the preservation block. -->
            
            <!-- Add CURRENT units to unit table (preserve existing units) -->
            <!-- This happens AFTER setting targets, so we add existing to target = total desired -->
            <!-- Note: Current counts already retrieved above (lines 904-907) if unit capacity exists -->
            <!-- If unit capacity is 0, we need to get current counts here -->
            <do_if value="$ship.units.maxcount == 0">
              <!-- Ship has no unit capacity - skip unit preservation -->
            </do_if>
            <do_else>
              <!-- Ship has unit capacity - preserve existing units -->
              <set_value name="$defenseWare" exact="macro.ship_gen_s_fightingdrone_01_a_macro.ware"/>
              <set_value name="$cargoWare" exact="macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware"/>
              <set_value name="$towerWare" exact="macro.ship_gen_xs_lasertower_01_a_macro.ware"/>
              <set_value name="$repairWare" exact="macro.ship_gen_xs_repairdrone_01_a_macro.ware"/>
              
              <!-- Get current counts (if not already retrieved above) -->
              <do_if value="not $currentDefenseCount?">
                <set_value name="$currentDefenseCount" exact="$ship.units.{macro.ship_gen_s_fightingdrone_01_a_macro}.count"/>
              </do_if>
              <do_if value="not $currentCargoCount?">
                <set_value name="$currentCargoCount" exact="$ship.units.{macro.ship_gen_xs_cargodrone_empty_01_a_macro}.count"/>
              </do_if>
              <do_if value="not $currentTowerCount?">
                <set_value name="$currentTowerCount" exact="$ship.units.{macro.ship_gen_xs_lasertower_01_a_macro}.count"/>
              </do_if>
              <do_if value="not $currentRepairCount?">
                <set_value name="$currentRepairCount" exact="$ship.units.{macro.ship_gen_xs_repairdrone_01_a_macro}.count"/>
              </do_if>
              
              <!-- Add existing units to table (preserve them) - add to target = total desired -->
              <!-- Always add existing, even if 0 (ensures we preserve what we have) -->
              <set_value name="$unittable.{$defenseWare}" exact="@$unittable.{$defenseWare} + $currentDefenseCount"/>
              <set_value name="$unittable.{$cargoWare}" exact="@$unittable.{$cargoWare} + $currentCargoCount"/>
              <set_value name="$unittable.{$towerWare}" exact="@$unittable.{$towerWare} + $currentTowerCount"/>
              <set_value name="$unittable.{$repairWare}" exact="@$unittable.{$repairWare} + $currentRepairCount"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   - Preserving existing units: Defense=' + $currentDefenseCount + ', Cargo=' + $currentCargoCount + ', Towers=' + $currentTowerCount + ', Repair=' + $currentRepairCount" chance="100"/>
              </do_if>
            </do_else>
            
            <!-- ============================================================================ -->
            <!-- Miner collector-drone restock (POST-preservation phase)                      -->
            <!--                                                                              -->
            <!-- Why this runs after preservation, not before:                                -->
            <!-- The preservation block above add_value's the ship's CURRENT defense/cargo/   -->
            <!-- tower/repair counts on top of the balance-profile targets. For a ship that   -->
            <!-- is currently 10/10 with non-collector drones (the exact symptom in the live  -->
            <!-- log: BSD-061 with Units=10, NeedsCollectors=1, CurrentOreCol=0), the final   -->
            <!-- $unittable already sums to ~maxcount (or more, depending on profile) BEFORE  -->
            <!-- we insert collectors. add_build_to_modify_ship's wharf handler then has to   -->
            <!-- truncate to fit unit-bay capacity. Vanilla interrupt.restock's truncation    -->
            <!-- (lines 569-590) iterates keys in insertion order and reduces counts -> the   -->
            <!-- collector ware (which we'd insert LAST) is the most likely category to be    -->
            <!-- cut to zero. Net result: BSD-061 leaves the wharf with full bays, still 0    -->
            <!-- collectors, and DoMaintenance re-detects the shortage on the next cycle ->   -->
            <!-- the "change equipment -> undock -> change equipment again" loop the player   -->
            <!-- reported.                                                                    -->
            <!--                                                                              -->
            <!-- Correct order:                                                               -->
            <!--   1. Compute total of $unittable AFTER preservation.                         -->
            <!--   2. Reserve collectorTargetCount slots.                                     -->
            <!--   3. Trim non-collector categories (defense -> tower -> cargo -> repair) by  -->
            <!--      enough to bring (total + collectorTargetCount) down to maxcount.        -->
            <!--   4. THEN insert the collector ware at exactly collectorTargetCount.         -->
            <!--                                                                              -->
            <!-- Trim priority rationale: defense first because miners don't need a max       -->
            <!-- combat drone load while collecting, then towers (passive), then trade        -->
            <!-- drones (less useful for miners), repair last (keep self-repair capability).  -->
            <!-- Each category is bounded at >= 0 (no underflow) and the loop is structurally -->
            <!-- finite (4 categories, single pass).                                          -->
            <!-- ============================================================================ -->
            <!-- Collector slots to protect = BUY target (count==0 path) + PRESERVE existing collectors.
                 Preservation runs even on probe-only / CM-only trips: add_build_to_modify_ship SETS
                 (not adds) units, so any collector ware missing from $unittable would be wiped, and
                 the next maintenance cycle would re-detect 0 collectors and re-buy them â€” the churn
                 the slider is meant to stop. Both ore and gas counts are kept so dual-bay miners
                 don't lose the other type. -->
            <set_value name="$collectorBuyMacro" exact="if $needsCollectorDrones then $collectorMacro else null"/>
            <set_value name="$collectorBuyTarget" exact="if $needsCollectorDrones then $collectorTargetCount else 0"/>
            <set_value name="$collectorOreKeep" exact="0"/>
            <set_value name="$collectorGasKeep" exact="0"/>
            <do_if value="$ship.iscapitalship and $ship.units.maxcount gt 0">
              <set_value name="$collectorOreKeep" exact="$ship.units.{unitcategory.orecollector}.count"/>
              <set_value name="$collectorGasKeep" exact="$ship.units.{unitcategory.gascollector}.count"/>
            </do_if>
            <set_value name="$collectorReserveCount" exact="$collectorBuyTarget + $collectorOreKeep + $collectorGasKeep"/>
            <do_if value="$collectorReserveCount gt 0 and $ship.units.maxcount gt 0">
              <set_value name="$collectorMaxCount" exact="$ship.units.maxcount"/>
              <!-- Sum the post-preservation table (skip collector wares - not yet inserted) -->
              <set_value name="$nonCollectorTotal" exact="(@$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware} + @$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware} + @$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware} + @$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware})"/>
              <set_value name="$slotsAvailableForOthers" exact="[$collectorMaxCount - $collectorReserveCount, 0].max"/>
              <set_value name="$collectorOverflow" exact="[$nonCollectorTotal - $slotsAvailableForOthers, 0].max"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   - Collector slot reservation: maxcount=' + $collectorMaxCount + ', buyTarget=' + $collectorBuyTarget + ', oreKeep=' + $collectorOreKeep + ', gasKeep=' + $collectorGasKeep + ', reserve=' + $collectorReserveCount + ', nonCollectorTotal=' + $nonCollectorTotal + ', slotsForOthers=' + $slotsAvailableForOthers + ', overflow_to_trim=' + $collectorOverflow" chance="100"/>
              </do_if>
              <!-- Trim cascade: defense -> tower -> cargo -> repair -->
              <do_if value="$collectorOverflow gt 0 and @$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware} gt 0">
                <set_value name="$_trimDefense" exact="[@$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware}, $collectorOverflow].min"/>
                <set_value name="$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware}" exact="@$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware} - $_trimDefense"/>
                <set_value name="$collectorOverflow" exact="$collectorOverflow - $_trimDefense"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]     Trimmed defense drones by ' + $_trimDefense + ' (new value=' + @$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware} + ', overflow remaining=' + $collectorOverflow + ')'" chance="100"/>
                </do_if>
                <remove_value name="$_trimDefense"/>
              </do_if>
              <do_if value="$collectorOverflow gt 0 and @$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware} gt 0">
                <set_value name="$_trimTower" exact="[@$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware}, $collectorOverflow].min"/>
                <set_value name="$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware}" exact="@$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware} - $_trimTower"/>
                <set_value name="$collectorOverflow" exact="$collectorOverflow - $_trimTower"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]     Trimmed laser towers by ' + $_trimTower + ' (new value=' + @$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware} + ', overflow remaining=' + $collectorOverflow + ')'" chance="100"/>
                </do_if>
                <remove_value name="$_trimTower"/>
              </do_if>
              <do_if value="$collectorOverflow gt 0 and @$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware} gt 0">
                <set_value name="$_trimCargo" exact="[@$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware}, $collectorOverflow].min"/>
                <set_value name="$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware}" exact="@$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware} - $_trimCargo"/>
                <set_value name="$collectorOverflow" exact="$collectorOverflow - $_trimCargo"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]     Trimmed trade drones by ' + $_trimCargo + ' (new value=' + @$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware} + ', overflow remaining=' + $collectorOverflow + ')'" chance="100"/>
                </do_if>
                <remove_value name="$_trimCargo"/>
              </do_if>
              <do_if value="$collectorOverflow gt 0 and @$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware} gt 0">
                <set_value name="$_trimRepair" exact="[@$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware}, $collectorOverflow].min"/>
                <set_value name="$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware}" exact="@$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware} - $_trimRepair"/>
                <set_value name="$collectorOverflow" exact="$collectorOverflow - $_trimRepair"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]     Trimmed repair drones by ' + $_trimRepair + ' (new value=' + @$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware} + ', overflow remaining=' + $collectorOverflow + ')'" chance="100"/>
                </do_if>
                <remove_value name="$_trimRepair"/>
              </do_if>
              <!-- Insert collectors LAST, after the bay has been trimmed to fit. Wharf computes the
                   install delta against current unit inventory. BUY target (set, not add) for the
                   missing type; PRESERVE existing ore/gas collectors at their current count. The
                   buy macro and a keep macro can be the same ware only when keep==0 (we only buy a
                   type the ship has 0 of), so these assignments never clobber each other. -->
              <do_if value="$collectorBuyMacro != null">
                <set_value name="$unittable.{$collectorBuyMacro.ware}" exact="$collectorBuyTarget"/>
              </do_if>
              <do_if value="$collectorOreKeep gt 0">
                <set_value name="$unittable.{macro.ship_gen_s_miningdrone_solid_01_a_macro.ware}" exact="$collectorOreKeep"/>
              </do_if>
              <do_if value="$collectorGasKeep gt 0">
                <set_value name="$unittable.{macro.ship_gen_s_miningdrone_liquid_01_a_macro.ware}" exact="$collectorGasKeep"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$_finalNonCollector" exact="(@$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware} + @$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware} + @$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware} + @$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware})"/>
                <debug_text text="'[GT-Maintenance]   - Collector insert: buy=' + (if $collectorBuyMacro != null then $collectorBuyTarget else 0) + ', oreKeep=' + $collectorOreKeep + ', gasKeep=' + $collectorGasKeep + '; final unittable: defense=' + @$unittable.{macro.ship_gen_s_fightingdrone_01_a_macro.ware} + ', cargo=' + @$unittable.{macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware} + ', tower=' + @$unittable.{macro.ship_gen_xs_lasertower_01_a_macro.ware} + ', repair=' + @$unittable.{macro.ship_gen_xs_repairdrone_01_a_macro.ware} + ', oreCol=' + @$unittable.{macro.ship_gen_s_miningdrone_solid_01_a_macro.ware} + ', gasCol=' + @$unittable.{macro.ship_gen_s_miningdrone_liquid_01_a_macro.ware} + ', sumNonCollector=' + $_finalNonCollector + ', reserve=' + $collectorReserveCount + ', maxcount=' + $collectorMaxCount" chance="100"/>
                <remove_value name="$_finalNonCollector"/>
              </do_if>
              <remove_value name="$collectorOverflow"/>
              <remove_value name="$slotsAvailableForOthers"/>
              <remove_value name="$nonCollectorTotal"/>
              <remove_value name="$collectorMaxCount"/>
            </do_if>
            <remove_value name="$collectorBuyMacro"/>
            <remove_value name="$collectorBuyTarget"/>
            <remove_value name="$collectorOreKeep"/>
            <remove_value name="$collectorGasKeep"/>
            <remove_value name="$collectorReserveCount"/>
            
            <!-- Store shopping list for AI script -->
            <!-- Ensure table exists before accessing (handles race condition) -->
            <do_if value="not global.$GT_ResupplyOrders?">
              <set_value name="global.$GT_ResupplyOrders" exact="table[]"/>
            </do_if>
            
            <!-- Ensure currentCM is initialized (defensive check) -->
            <set_value name="$storedCurrentCM" exact="if $currentCM? then $currentCM else $ship.ammostorage.countermeasure.count"/>
            <set_value name="$storedCurrentUnits" exact="if $currentUnitsCount? then $currentUnitsCount else $ship.units.count"/>
            <set_value name="$storedCurrentDeployables" exact="if $currentDeployables? then $currentDeployables else $ship.ammostorage.deployable.count"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Storing resupply order tracking for ' + $ship.idcode + ': CM=' + $storedCurrentCM + ', Units=' + $storedCurrentUnits + ', Deployables=' + $storedCurrentDeployables" chance="100"/>
              <debug_text text="'[GT-Maintenance] Final shopping list: Ammo types=' + @$ammotable.keys.count + ', Unit types=' + @$unittable.keys.count" chance="100"/>
            </do_if>
            
            <!-- =====================================================================
                 STORAGE FIX HISTORY:

                 v1 (truncation fix - retained): Inline table[$k1=v1,...] literals in X4
                 silently truncate from any null value onwards at construction time. We
                 coalesce $beforeXXX reads to 0 first to make the literal safe for ships
                 with Total Units: 0/0 capacity (where $ship.units.{macro.X}.count returns
                 null instead of 0).

                 v2 (chained-set fix - this rev): Even after the v1 fix, the live log
                 captured the SAME failure mode for capital miners: gt_maintenance prints
                 "Final shopping list: Ammo types=2, Unit types=5" then 2s later
                 order.trade.galaxyminer reports "Found pending resupply order at <station>
                 (Ammo types=null, Unit types=null)" and proceeds to call
                 add_build_to_modify_ship with NULL ammo/units (which the wharf accepts as
                 "install nothing" -> ship leaves with collectors still missing -> next
                 maintenance cycle re-detects the shortage -> infinite "change equipment"
                 loop reported by the player).

                 Root cause: chained-property assignment of the form
                   set_value name="global.X.{key}.subkey" exact="$localTable"
                 against a JUST-CREATED global table[] entry does NOT reliably persist
                 table-typed values across cue boundaries in this X4 build (scalars and
                 connection-typed values like $equipmentStation persist, which is why
                 $Station read back fine but $AmmoTable / $UnitTable read back as null).
                 The inline-literal form (assigning the whole entry in one set_value) is
                 the only form that reliably persists table values across the global
                 table; it's how the rest of the codebase stores nested tables in globals
                 and is what the trader / mk4 trader resupply executors expect to read.

                 Fix: pre-coalesce every value to a non-null sentinel, then assign the
                 ENTIRE entry as a single inline table literal. Every key is guaranteed
                 non-null at construction time, so v1's truncation rule never triggers.
                 ===================================================================== -->
            <set_value name="$storedDefenseDronesBefore" exact="if $beforeDefenseDrones? and $beforeDefenseDrones != null then $beforeDefenseDrones else 0"/>
            <set_value name="$storedCargoDronesBefore" exact="if $beforeCargoDrones? and $beforeCargoDrones != null then $beforeCargoDrones else 0"/>
            <set_value name="$storedLaserTowersBefore" exact="if $beforeLaserTowers? and $beforeLaserTowers != null then $beforeLaserTowers else 0"/>
            <set_value name="$storedRepairDronesBefore" exact="if $beforeRepairDrones? and $beforeRepairDrones != null then $beforeRepairDrones else 0"/>

            <!-- $ammotable / $unittable are guaranteed table[] (never null) - they were
                 initialized as table[] at the top of the equipment-shopping block and only
                 ever had keys ADDED, never overwritten with null. $equipmentStation is
                 guaranteed non-null because we only enter this branch after a successful
                 station-pick. $storedCurrentDeployables / $storedCurrentCM /
                 $storedCurrentUnits / $storedXXXBefore are all coalesced above. -->
            <set_value name="global.$GT_ResupplyOrders.{$ship}" exact="table[
              $Station = $equipmentStation,
              $AmmoTable = $ammotable,
              $UnitTable = $unittable,
              $DeployablesBefore = $storedCurrentDeployables,
              $CountermeasuresBefore = $storedCurrentCM,
              $UnitsBefore = $storedCurrentUnits,
              $DefenseDronesBefore = $storedDefenseDronesBefore,
              $CargoDronesBefore = $storedCargoDronesBefore,
              $LaserTowersBefore = $storedLaserTowersBefore,
              $RepairDronesBefore = $storedRepairDronesBefore
            ]"/>

            <!-- Verification log: read back what we just stored, so we can confirm
                 in the live log that the table actually persists across the cue
                 boundary. If "stored=null" appears here we know the X4 engine refused
                 the inline-table assignment too and we need a different storage
                 strategy (e.g. a holder cue's namespace.var). -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$verifyEntry" exact="@global.$GT_ResupplyOrders.{$ship}"/>
              <set_value name="$verifyAmmoCount" exact="if $verifyEntry? and $verifyEntry != null then @$verifyEntry.$AmmoTable.keys.count else null"/>
              <set_value name="$verifyUnitCount" exact="if $verifyEntry? and $verifyEntry != null then @$verifyEntry.$UnitTable.keys.count else null"/>
              <debug_text text="'[GT-Maintenance] STORAGE VERIFY for ' + $ship.idcode + ': entry=' + (if $verifyEntry? and $verifyEntry != null then 'present' else 'NULL') + ', $AmmoTable.keys.count=' + $verifyAmmoCount + ', $UnitTable.keys.count=' + $verifyUnitCount" chance="100"/>
              <remove_value name="$verifyEntry"/>
              <remove_value name="$verifyAmmoCount"/>
              <remove_value name="$verifyUnitCount"/>
            </do_if>
            
            <!-- PERFORMANCE OPTIMIZATION: Defer UI operations (ship renaming, logbook messages) -->
            <do_if value="not global.$GT_DeferredUIUpdates?">
              <set_value name="global.$GT_DeferredUIUpdates" exact="table[]"/>
            </do_if>
            <set_value name="$pilot" exact="$ship.pilot"/>
            <set_value name="global.$GT_DeferredUIUpdates.{$ship}" exact="table[
              $Type = 'equipment',
              $Ship = $ship,
              $Pilot = $pilot,
              $LogbookMessage = '{77000,3207}.[' + $pilotLevel + ',' + $equipmentStation.knownname + ',' + $ship.knownname + ']',
              $LogbookCategory = 'upkeep',
              $LogbookTitle = 'Defensive Equipment Auto-Replenishment: ' + $ship.knownname,
              $LogbookObject = $equipmentStation,
              $LogbookInteraction = 'showonmap'
            ]"/>
            <signal_cue_instantly cue="md.GT_Maintenance.ProcessDeferredUIUpdates"/>
            
            <set_value name="$equipmentOrderCreated" exact="true"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] No equipment station found for ' + $ship.idcode" chance="100"/>
            </do_if>
            <!-- PERFORMANCE OPTIMIZATION: Defer UI operations (logbook messages) -->
            <do_if value="not global.$GT_DeferredUIUpdates?">
              <set_value name="global.$GT_DeferredUIUpdates" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_DeferredUIUpdates.{$ship}" exact="table[
              $Type = 'equipment_failed',
              $Ship = $ship,
              $LogbookMessage = 'Level ' + $pilotLevel + ' ' + $ship.knownname + ' needs equipment but no suitable station found within ' + $maxJumpDistance + ' jumps.',
              $LogbookCategory = 'upkeep',
              $LogbookTitle = 'Defensive Equipment Auto-Replenishment Failed',
              $LogbookObject = $ship,
              $LogbookInteraction = 'showonmap'
            ]"/>
            <signal_cue_instantly cue="md.GT_Maintenance.ProcessDeferredUIUpdates"/>
          </do_else>
        </do_if>
        
        <!-- ========================================================================= -->
        <!-- MONITOR COMPLETION                                                        -->
        <!-- ========================================================================= -->
        
        <do_if value="$repairOrderCreated or $equipmentOrderCreated">
          <!-- Track in global table for event-driven monitoring -->
          <!-- Ensure table exists before accessing (handles race condition) -->
          <do_if value="not global.$GT_MaintenanceOrders?">
            <set_value name="global.$GT_MaintenanceOrders" exact="table[]"/>
          </do_if>
          
          <!-- Don't overwrite existing maintenance order if one is already in progress -->
          <!-- This prevents race condition where ship checks maintenance again before resupply completes -->
          <set_value name="$existingOrder" exact="@global.$GT_MaintenanceOrders.{$ship}"/>
          <set_value name="$hasExistingOrder" exact="$existingOrder?"/>
          <set_value name="$existingWaitingForEquipment" exact="if $hasExistingOrder then @$existingOrder.$WaitingForEquipment else false"/>
          <set_value name="$existingWaitingForRepair" exact="if $hasExistingOrder then @$existingOrder.$WaitingForRepair else false"/>
          
          <!-- Only consider order "in progress" if it has valid values (not null) -->
          <!-- Stale orders with null values should be cleared, not preserved -->
          <set_value name="$isValidExistingOrder" exact="$hasExistingOrder and ($existingWaitingForEquipment or $existingWaitingForRepair)"/>
          
          <do_if value="$isValidExistingOrder">
            <!-- Maintenance order already in progress - don't overwrite it! -->
            <set_value name="$existingNeededCM" exact="@$existingOrder.$NeededCM"/>
            <set_value name="$existingNeededUnits" exact="@$existingOrder.$NeededUnits"/>
            <set_value name="$existingBeforeCM" exact="@$existingOrder.$CountermeasuresBefore"/>
            <set_value name="$existingBeforeUnits" exact="@$existingOrder.$UnitsBefore"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance]  Maintenance order already in progress for ' + $ship.idcode + ' - skipping new order creation (will wait for existing order to complete)'" chance="100"/>
              <debug_text text="'[GT-Maintenance] Existing order details: NeededCM=' + $existingNeededCM + ', NeededUnits=' + $existingNeededUnits + ', BeforeCM=' + $existingBeforeCM + ', BeforeUnits=' + $existingBeforeUnits + ', WaitingForEquipment=' + $existingWaitingForEquipment" chance="100"/>
              <debug_text text="'[GT-Maintenance] Current check would have set: NeededCM=' + $needsCountermeasures + ', NeededUnits=' + $needsUnits + ', NeededDeployableLaserTowers=' + $needsDeployableLaserTowers + ' (NOT overwriting!)'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- No existing order or existing order completed - create new tracking entry -->
            <set_value name="global.$GT_MaintenanceOrders.{$ship}" exact="table[
              $Ship = $ship,
              $StartTime = player.age,
              $WaitingForRepair = $repairOrderCreated,
              $WaitingForEquipment = $equipmentOrderCreated,
              $DeployablesBefore = @global.$GT_ResupplyOrders.{$ship}.$DeployablesBefore,
              $CountermeasuresBefore = @global.$GT_ResupplyOrders.{$ship}.$CountermeasuresBefore,
              $UnitsBefore = @global.$GT_ResupplyOrders.{$ship}.$UnitsBefore,
              $NeededCM = $needsCountermeasures,
              $NeededUnits = $needsUnits,
              $NeededDeployableLaserTowers = $needsDeployableLaserTowers
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Created new maintenance order tracking: NeededCM=' + $needsCountermeasures + ', NeededUnits=' + $needsUnits + ', NeededDeployableLaserTowers=' + $needsDeployableLaserTowers + ', BeforeCM=' + (@global.$GT_ResupplyOrders.{$ship}.$CountermeasuresBefore) + ', BeforeUnits=' + (@global.$GT_ResupplyOrders.{$ship}.$UnitsBefore)" chance="100"/>
            </do_if>
          </do_else>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] â³ Tracking maintenance for ' + $ship.idcode + ' (Repair: ' + $repairOrderCreated + ', Equipment: ' + $equipmentOrderCreated + ')'" chance="100"/>
          </do_if>
          
          <!-- CONCURRENCY CONTROL: Decrement counter when ExecuteMaintenance completes (orders created, will complete later via ProcessResupplyComplete/ProcessRepairComplete) -->
          <!-- Note: Completion handlers will signal GT_Maintenance_Complete, but counter is decremented here when ExecuteMaintenance instance ends -->
          <do_if value="global.$GT_MaintenanceQueue? and global.$GT_MaintenanceQueue.$ActiveInstances? and global.$GT_MaintenanceQueue.$ActiveInstances gt 0">
            <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" operation="subtract"/>
            <!-- Signal queue processor to process next item -->
            <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- No orders created - proceed to trading, will retry after next trade -->
          <debug_text text="'[GT-Maintenance] No maintenance orders created for ' + $ship.idcode + ' (no stations with stock or no work needed), proceeding to trading'" chance="100"/>
          
          <!-- CONCURRENCY CONTROL: Decrement counter and process queue on completion -->
          <do_if value="global.$GT_MaintenanceQueue? and global.$GT_MaintenanceQueue.$ActiveInstances? and global.$GT_MaintenanceQueue.$ActiveInstances gt 0">
            <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" operation="subtract"/>
            <!-- Signal queue processor to process next item -->
            <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
          </do_if>
          
          <signal_objects object="$ship" param="'GT_Maintenance_Complete'" delay="1ms"/>
        </do_else>
      </actions>
    </cue>
    
    <!-- Process Resupply Completion (Event-Driven from diff patch) -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessResupplyComplete" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_ResupplyComplete'"/>
      </conditions>
      <actions>
        
        <do_if value="global.$GT_ResupplyCompleteQueue? and global.$GT_ResupplyCompleteQueue.count gt 0">
          <do_while value="global.$GT_ResupplyCompleteQueue.count gt 0">
            <set_value name="$data" exact="global.$GT_ResupplyCompleteQueue.{1}"/>
            <remove_from_list name="global.$GT_ResupplyCompleteQueue" exact="$data"/>
            <!-- Case-sensitive table-key fix: order.build.equip.xml (~116), order.restock.xml
                 (~120), and order.repair.xml (~19) all append rows as table[$ship = this.ship,
                 ...] using lowercase $ship. X4 expression-engine table-key lookup is
                 case-sensitive, so reading $data.$Ship returned null and cascaded the entire
                 cleanup path into "Property lookup failed: $data.$Ship" / "$ship == null"
                 spam (visible in the live log at t=2080.22, ~10 errors per resupply). The
                 ship reference must be read with the exact casing the writers used. -->
            <set_value name="$ship" exact="$data.$ship"/>
            
            <!-- Check if equipment order actually succeeded -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] Resupply completion signal received for ' + $ship.idcode" chance="100"/>
            </do_if>
            <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{$ship}?">
              <!-- Ship is actively tracked - process normally -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Found maintenance order tracking for ' + $ship.idcode + ' - processing completion'" chance="100"/>
              </do_if>
              
              <!-- Get stored values from maintenance order -->
              <set_value name="$storedNeededCM" exact="@global.$GT_MaintenanceOrders.{$ship}.$NeededCM"/>
              <set_value name="$storedNeededUnits" exact="@global.$GT_MaintenanceOrders.{$ship}.$NeededUnits"/>
              <set_value name="$storedWaitingForEquipment" exact="@global.$GT_MaintenanceOrders.{$ship}.$WaitingForEquipment"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Stored order values: NeededCM=' + $storedNeededCM + ', NeededUnits=' + $storedNeededUnits + ', WaitingForEquipment=' + $storedWaitingForEquipment" chance="100"/>
              </do_if>
              
              <!-- Get current equipment levels -->
              <!-- Log what we're reading to verify property access -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Reading CURRENT equipment levels for ' + $ship.idcode + ' after resupply completion'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Reading CM: ship.ammostorage.countermeasure.count = ' + $ship.ammostorage.countermeasure.count" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Reading CM capacity: ship.ammostorage.countermeasure.capacity = ' + $ship.ammostorage.countermeasure.capacity" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Reading Units: ship.units.count = ' + $ship.units.count" chance="100"/>
              </do_if>
              
              <set_value name="$currentDeployables" exact="$ship.ammostorage.deployable.count"/>
              <set_value name="$currentCM" exact="$ship.ammostorage.countermeasure.count"/>
              <set_value name="$currentUnitsCount" exact="$ship.units.count"/>
              <set_value name="$deployableCapacity" exact="$ship.ammostorage.deployable.capacity"/>
              <set_value name="$cmCapacity" exact="$ship.ammostorage.countermeasure.capacity"/>
              <set_value name="$unitsCapacity" exact="$ship.units.maxcount"/>
              
              <!-- Log what we read -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]   Read values: currentCM=' + $currentCM + ', cmCapacity=' + $cmCapacity + ', currentUnits=' + $currentUnitsCount + ', unitsCapacity=' + $unitsCapacity" chance="100"/>
              </do_if>
              
              <!-- Get counts for each specific unit type AFTER resupply -->
              <!-- Note: Use macro directly, not macro.ware (vanilla pattern: units.{macro}.count) -->
              <set_value name="$afterDefenseDrones" exact="$ship.units.{macro.ship_gen_s_fightingdrone_01_a_macro}.count"/>
              <set_value name="$afterCargoDrones" exact="$ship.units.{macro.ship_gen_xs_cargodrone_empty_01_a_macro}.count"/>
              <do_if value="$unitsCapacity == 0">
                <set_value name="$afterLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
              </do_if>
              <do_else>
                <set_value name="$afterLaserTowers" exact="$ship.units.{macro.ship_gen_xs_lasertower_01_a_macro}.count"/>
              </do_else>
              <set_value name="$afterRepairDrones" exact="$ship.units.{macro.ship_gen_xs_repairdrone_01_a_macro}.count"/>
              
              <!-- Get levels from before resupply -->
              <set_value name="$beforeDeployables" exact="@global.$GT_MaintenanceOrders.{$ship}.$DeployablesBefore"/>
              <set_value name="$beforeCM" exact="@global.$GT_MaintenanceOrders.{$ship}.$CountermeasuresBefore"/>
              <set_value name="$beforeUnits" exact="@global.$GT_MaintenanceOrders.{$ship}.$UnitsBefore"/>
              
              <!-- Get unit type counts from before resupply (from resupply order tracking) -->
              <set_value name="$beforeDefenseDrones" exact="@global.$GT_ResupplyOrders.{$ship}.$DefenseDronesBefore"/>
              <set_value name="$beforeCargoDrones" exact="@global.$GT_ResupplyOrders.{$ship}.$CargoDronesBefore"/>
              <set_value name="$beforeLaserTowers" exact="@global.$GT_ResupplyOrders.{$ship}.$LaserTowersBefore"/>
              <set_value name="$beforeRepairDrones" exact="@global.$GT_ResupplyOrders.{$ship}.$RepairDronesBefore"/>
              
              <!-- Get what was ordered from resupply order tracking -->
              <set_value name="$resupplyOrder" exact="@global.$GT_ResupplyOrders.{$ship}"/>
              <set_value name="$orderedCMFromOrder" exact="0"/>
              <set_value name="$orderedDefenseFromOrder" exact="0"/>
              <set_value name="$orderedCargoFromOrder" exact="0"/>
              <set_value name="$orderedTowersFromOrder" exact="0"/>
              <set_value name="$orderedRepairFromOrder" exact="0"/>
              <do_if value="$resupplyOrder?">
                <!-- Initialize to safe defaults FIRST (memory pattern) -->
                <set_value name="$ammoTableFromOrder" exact="@$resupplyOrder.$AmmoTable"/>
                <set_value name="$unitTableFromOrder" exact="@$resupplyOrder.$UnitTable"/>
                
                <!-- Extract .keys with @, then extract .count with @, then check if count exists and > 0 -->
                <set_value name="$ammoTableKeys" exact="@$ammoTableFromOrder.keys"/>
                <set_value name="$ammoTableKeysCount" exact="@$ammoTableKeys.count"/>
                <do_if value="$ammoTableKeysCount? and $ammoTableKeysCount gt 0">
                  <!-- Sum countermeasures and deployable laser towers ordered -->
                  <set_value name="$xsTowerWare" exact="macro.ship_gen_xs_lasertower_01_a_macro.ware"/>
                  <set_value name="$sTowerWare" exact="macro.ship_gen_s_lasertower_01_a_macro.ware"/>
                  <do_all exact="$ammoTableKeysCount" counter="$ammoKeyIdx">
                    <set_value name="$ammoKey" exact="$ammoTableKeys.{$ammoKeyIdx}"/>
                    <do_if value="$ammoKey == $xsTowerWare or $ammoKey == $sTowerWare">
                      <set_value name="$orderedTowersFromOrder" exact="$orderedTowersFromOrder + $ammoTableFromOrder.{$ammoKey}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$orderedCMFromOrder" exact="$orderedCMFromOrder + $ammoTableFromOrder.{$ammoKey}"/>
                    </do_else>
                  </do_all>
                  <remove_value name="$xsTowerWare"/>
                  <remove_value name="$sTowerWare"/>
                </do_if>
                
                <!-- Extract .keys with @, then extract .count with @, then check if count exists and > 0 -->
                <set_value name="$unitTableKeys" exact="@$unitTableFromOrder.keys"/>
                <set_value name="$unitTableKeysCount" exact="@$unitTableKeys.count"/>
                <do_if value="$unitTableKeysCount? and $unitTableKeysCount gt 0">
                  <set_value name="$defenseWare" exact="macro.ship_gen_s_fightingdrone_01_a_macro.ware"/>
                  <set_value name="$cargoWare" exact="macro.ship_gen_xs_cargodrone_empty_01_a_macro.ware"/>
                  <set_value name="$towerWare" exact="macro.ship_gen_xs_lasertower_01_a_macro.ware"/>
                  <set_value name="$repairWare" exact="macro.ship_gen_xs_repairdrone_01_a_macro.ware"/>
                  <set_value name="$orderedDefenseFromOrder" exact="@$unitTableFromOrder.{$defenseWare}"/>
                  <set_value name="$orderedCargoFromOrder" exact="@$unitTableFromOrder.{$cargoWare}"/>
                  <set_value name="$orderedTowersFromOrder" exact="@$unitTableFromOrder.{$towerWare}"/>
                  <set_value name="$orderedRepairFromOrder" exact="@$unitTableFromOrder.{$repairWare}"/>
                </do_if>
              </do_if>
              
              <!-- What was actually restocked when order finishes -->
              <set_value name="$cmGained" exact="$currentCM - $beforeCM"/>
              <set_value name="$defenseGained" exact="$afterDefenseDrones - $beforeDefenseDrones"/>
              <set_value name="$cargoGained" exact="$afterCargoDrones - $beforeCargoDrones"/>
              <set_value name="$towersGained" exact="$afterLaserTowers - $beforeLaserTowers"/>
              <set_value name="$repairGained" exact="$afterRepairDrones - $beforeRepairDrones"/>
              <set_value name="$totalUnitsGained" exact="$currentUnitsCount - $beforeUnits"/>
              
              <!-- Summary of what was restocked -->
              <set_value name="$restockedItems" exact="[]"/>
              <do_if value="$cmGained gt 0">
                <append_to_list name="$restockedItems" exact="'CM +' + $cmGained"/>
              </do_if>
              <do_if value="$defenseGained gt 0">
                <append_to_list name="$restockedItems" exact="'Defense Drones +' + $defenseGained"/>
              </do_if>
              <do_if value="$cargoGained gt 0">
                <append_to_list name="$restockedItems" exact="'Cargo Drones +' + $cargoGained"/>
              </do_if>
              <do_if value="$towersGained gt 0">
                <append_to_list name="$restockedItems" exact="'Laser Towers +' + $towersGained"/>
              </do_if>
              <do_if value="$repairGained gt 0">
                <append_to_list name="$restockedItems" exact="'Repair Drones +' + $repairGained"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$restockedSummary" exact="if $restockedItems.count gt 0 then $restockedItems.{1} + (if $restockedItems.count gt 1 then ', ' + $restockedItems.{2} else '') + (if $restockedItems.count gt 2 then ', ' + $restockedItems.{3} else '') + (if $restockedItems.count gt 3 then ', ' + $restockedItems.{4} else '') + (if $restockedItems.count gt 4 then ', ' + $restockedItems.{5} else '') else 'NOTHING'"/>
                <debug_text text="'[GT-Maintenance] RESUPPLY ORDER COMPLETED for ' + $ship.idcode + '  '" chance="100"/>
                <debug_text text="'[GT-Maintenance] RESTOCKED: ' + $restockedSummary" chance="100"/>
              </do_if>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] EQUIPMENT COUNTS AFTER RESUPPLY for ' + $ship.idcode + ':'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Countermeasures: ' + $beforeCM + ' ' + $currentCM + ' (ordered: ' + $orderedCMFromOrder + ', gained: ' + $cmGained + ')'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Defense Drones: ' + $beforeDefenseDrones + ' ' + $afterDefenseDrones + ' (ordered: ' + $orderedDefenseFromOrder + ', gained: ' + $defenseGained + ')'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Cargo Drones: ' + $beforeCargoDrones + ' ' + $afterCargoDrones + ' (ordered: ' + $orderedCargoFromOrder + ', gained: ' + $cargoGained + ')'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Laser Towers: ' + $beforeLaserTowers + ' ' + $afterLaserTowers + ' (ordered: ' + $orderedTowersFromOrder + ', gained: ' + $towersGained + ')'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Repair Drones: ' + $beforeRepairDrones + ' ' + $afterRepairDrones + ' (ordered: ' + $orderedRepairFromOrder + ', gained: ' + $repairGained + ')'" chance="100"/>
                <debug_text text="'[GT-Maintenance]   Total Units: ' + $beforeUnits + ' ' + $currentUnitsCount + ' (gained: ' + $totalUnitsGained + ')'" chance="100"/>
              </do_if>
              
              <!-- Check if we actually got something meaningful -->
              <!-- Accept partial restocking: if we got at least 2 of anything, that's good enough -->
              <!-- This prevents ships from cruising the entire universe trying to get fully stocked -->
              <!-- If station had limited stock, we take what we can and proceed with trading -->
              <set_value name="$deployablesGained" exact="$currentDeployables - $beforeDeployables"/>
              <set_value name="$cmGained" exact="$currentCM - $beforeCM"/>
              <set_value name="$unitsGained" exact="$currentUnitsCount - $beforeUnits"/>
              <set_value name="$minAcceptable" exact="2"/> <!-- Minimum items to consider resupply successful -->
              
              <set_value name="$gotEnoughDeployables" exact="$deployablesGained ge $minAcceptable"/>
              <set_value name="$gotEnoughCM" exact="$cmGained ge $minAcceptable"/>
              <set_value name="$gotEnoughUnits" exact="$unitsGained ge $minAcceptable"/>
              <set_value name="$resupplySuccessful" exact="$gotEnoughDeployables or $gotEnoughCM or $gotEnoughUnits"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Resupply result for ' + $ship.idcode + ': CM +' + $cmGained + ' (' + $beforeCM + 'â†’' + $currentCM + '), Deployables +' + $deployablesGained + ' (' + $beforeDeployables + 'â†’' + $currentDeployables + '), Units +' + $unitsGained + ' (' + $beforeUnits + 'â†’' + $currentUnitsCount + ') - ' + if $resupplySuccessful then 'Acceptable' else 'Insufficient'" chance="100"/>
              </do_if>
              
              <do_if value="$resupplySuccessful">
                <!-- Resupply was successful - verify that CURRENT equipment is above threshold (not just what was originally needed) -->
                <!-- Check CURRENT equipment levels against threshold, not just if originally-needed items are satisfied -->
                <!-- This prevents loops when equipment drops below threshold after resupply (e.g., CM consumed during resupply) -->
                <set_value name="$neededCM" exact="@global.$GT_MaintenanceOrders.{$ship}.$NeededCM"/>
                <set_value name="$neededUnits" exact="@global.$GT_MaintenanceOrders.{$ship}.$NeededUnits"/>
                <set_value name="$neededDeployableLaserTowers" exact="@global.$GT_MaintenanceOrders.{$ship}.$NeededDeployableLaserTowers"/>
                
                <!-- Get thresholds -->
                <set_value name="$countermeasureThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$CountermeasureThreshold"/>
                <set_value name="$unifiedThreshold" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$UnifiedThreshold"/>
                
                <!-- Check CURRENT equipment levels against threshold -->
                <set_value name="$cmPercentage" exact="if $cmCapacity gt 0 then ($currentCM * 100) / $cmCapacity else 100"/>
                <set_value name="$unitsPercentage" exact="if $unitsCapacity gt 0 then ($currentUnitsCount * 100) / $unitsCapacity else 100"/>
                <set_value name="$deployableLaserTowerPercentage" exact="100"/>
                <do_if value="$unitsCapacity == 0 and $deployableCapacity gt 0 and @global.$GT_GlobalSettings.$DefensiveEquipment.$RestockLaserTowers">
                  <set_value name="$balanceProfile" exact="@global.$GT_GlobalSettings.$DefensiveEquipment.$BalanceProfile"/>
                  <do_if value="not $balanceProfile?">
                    <set_value name="$balanceProfile" exact="2"/>
                  </do_if>
                  <set_value name="$laserTowerPct" exact="20"/>
                  <do_if value="$balanceProfile == 4">
                    <set_value name="$laserTowerPct" exact="30"/>
                  </do_if>
                  <set_value name="$deployableLaserTowerTarget" exact="[($deployableCapacity * $laserTowerPct / 100)i, 1].max"/>
                  <set_value name="$currentDeployableLaserTowers" exact="$ship.ammostorage.{deployablecategory.lasertower}.count"/>
                  <set_value name="$deployableLaserTowerPercentage" exact="if $deployableLaserTowerTarget gt 0 then ($currentDeployableLaserTowers * 100) / $deployableLaserTowerTarget else 100"/>
                  <remove_value name="$laserTowerPct"/>
                  <remove_value name="$deployableLaserTowerTarget"/>
                  <remove_value name="$currentDeployableLaserTowers"/>
                  <remove_value name="$balanceProfile"/>
                </do_if>
                
                <!-- Only check what was ORIGINALLY needed, not everything -->
                <!-- If CM wasn't needed originally, don't check it. Same for units. -->
                <!-- Use separate variables to avoid nested if-then-else (X4 doesn't support chained if-then-else) -->
                <set_value name="$cmSatisfied" exact="if not $neededCM then true else false"/>
                <set_value name="$unitsSatisfied" exact="if not $neededUnits then true else false"/>
                <set_value name="$deployableTowersSatisfied" exact="if not $neededDeployableLaserTowers then true else false"/>
                
                <!-- If needed, check if capacity is 0 or percentage is above threshold -->
                <do_if value="$neededCM and not $cmSatisfied">
                  <set_value name="$cmSatisfied" exact="if $cmCapacity == 0 then true else ($cmPercentage ge $countermeasureThreshold)"/>
                </do_if>
                <do_if value="$neededUnits and not $unitsSatisfied">
                  <set_value name="$unitsSatisfied" exact="if $unitsCapacity == 0 then true else ($unitsPercentage ge $unifiedThreshold)"/>
                </do_if>
                <do_if value="$neededDeployableLaserTowers and not $deployableTowersSatisfied">
                  <set_value name="$deployableTowersSatisfied" exact="if $deployableCapacity == 0 then true else ($deployableLaserTowerPercentage ge $unifiedThreshold)"/>
                </do_if>
                
                <!-- Track verification logic -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance] Resupply successful for ' + $ship.idcode + ' - Verification details:'" chance="100"/>
                  <debug_text text="'[GT-Maintenance]   CM: Needed=' + $neededCM + ', Current=' + $currentCM + '/' + $cmCapacity + ' (' + $cmPercentage + '%), Threshold=' + $countermeasureThreshold + '%, Satisfied=' + $cmSatisfied + ' (not needed=' + (not $neededCM) + ' OR percentage>=threshold=' + ($cmPercentage ge $countermeasureThreshold) + ')'" chance="100"/>
                  <debug_text text="'[GT-Maintenance]   Units: Needed=' + $neededUnits + ', Current=' + $currentUnitsCount + '/' + $unitsCapacity + ' (' + $unitsPercentage + '%), Threshold=' + $unifiedThreshold + '%, Satisfied=' + $unitsSatisfied + ' (not needed=' + (not $neededUnits) + ' OR percentage>=threshold=' + ($unitsPercentage ge $unifiedThreshold) + ')'" chance="100"/>
                  <debug_text text="'[GT-Maintenance]   Deployable Towers: Needed=' + $neededDeployableLaserTowers + ', CurrentPct=' + $deployableLaserTowerPercentage + '%, Threshold=' + $unifiedThreshold + '%, Satisfied=' + $deployableTowersSatisfied" chance="100"/>
                  <debug_text text="'[GT-Maintenance]   Final: All satisfied=' + ($cmSatisfied and $unitsSatisfied and $deployableTowersSatisfied) + ' (CM=' + $cmSatisfied + ', Units=' + $unitsSatisfied + ', DeployableTowers=' + $deployableTowersSatisfied + ')'" chance="100"/>
                </do_if>
                <debug_text text="'[GT-Maintenance] Resupply successful for ' + $ship.idcode + ' - Needed: CM=' + $neededCM + ' (now ' + $cmPercentage + '% >= ' + $countermeasureThreshold + '%: ' + $cmSatisfied + '), Units=' + $neededUnits + ' (now ' + $unitsPercentage + '% >= ' + $unifiedThreshold + '%: ' + $unitsSatisfied + '), DeployableTowers=' + $neededDeployableLaserTowers + ' (now ' + $deployableLaserTowerPercentage + '% >= ' + $unifiedThreshold + '%: ' + $deployableTowersSatisfied + ')'" chance="100"/>
                
                <do_if value="$cmSatisfied and $unitsSatisfied and $deployableTowersSatisfied">
                  <!-- What we needed is satisfied - complete maintenance -->
                  <set_value name="global.$GT_MaintenanceOrders.{$ship}.$WaitingForEquipment" exact="false"/>
                  
                  <!-- Check if all maintenance complete -->
                  <set_value name="$waitingForRepair" exact="@global.$GT_MaintenanceOrders.{$ship}.$WaitingForRepair"/>
                  <do_if value="not $waitingForRepair">
                    <!-- All done! -->
                    <remove_value name="global.$GT_MaintenanceOrders.{$ship}"/>
                    
                    <!-- Clear resupply order tracking -->
                    <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
                      <remove_value name="global.$GT_ResupplyOrders.{$ship}"/>
                    </do_if>
                    
                    <!-- Trigger ship rename to remove [RESUPPLY]/[MAINTENANCE] state -->
                    <do_if value="@$ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
                      <set_value name="$pilot" exact="$ship.pilot"/>
                      <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                        <param name="ship" value="$ship"/>
                        <param name="pilot" value="$pilot"/>
                        <param name="xp" value="global.$GT_Pilots.{$pilot}.$XP"/>
                        <param name="level" value="global.$GT_Pilots.{$pilot}.$Level"/>
                        <param name="rank" value="@global.$GT_Pilots.{$pilot}.$CurrentRank"/>
                        <param name="nameType" value="'trader'"/>
                      </run_actions>
                    </do_if>
                    
                    <!-- CONCURRENCY CONTROL: Decrement counter and process queue on completion -->
                    <do_if value="global.$GT_MaintenanceQueue? and global.$GT_MaintenanceQueue.$ActiveInstances? and global.$GT_MaintenanceQueue.$ActiveInstances gt 0">
                      <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" operation="subtract"/>
                      <!-- Signal queue processor to process next item -->
                      <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
                    </do_if>
                    
                    <signal_objects object="$ship" param="'GT_Maintenance_Complete'" delay="1ms"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Maintenance] All maintenance complete for ' + $ship.idcode" chance="100"/>
                    </do_if>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Equipment below threshold after resupply - DO NOT signal completion, trigger another resupply immediately -->
                  <debug_text text="'[GT-Maintenance]  Resupply completed but equipment below threshold for ' + $ship.idcode + ' - CM satisfied=' + $cmSatisfied + ' (' + $currentCM + '/' + $cmCapacity + ' = ' + $cmPercentage + '% >= ' + $countermeasureThreshold + '%), Units satisfied=' + $unitsSatisfied + ' (' + $currentUnitsCount + '/' + $unitsCapacity + ' = ' + $unitsPercentage + '% >= ' + $unifiedThreshold + '%) - triggering another resupply'" chance="100"/>
                  
                  <!-- Clear the maintenance order so DoMaintenance can create a new one -->
                  <set_value name="global.$GT_MaintenanceOrders.{$ship}.$WaitingForEquipment" exact="false"/>
                  <remove_value name="global.$GT_MaintenanceOrders.{$ship}"/>
                  
                  <!-- Clear resupply order tracking -->
                  <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
                    <remove_value name="global.$GT_ResupplyOrders.{$ship}"/>
                  </do_if>
                  
                  <!-- DO NOT signal completion - trigger another maintenance check immediately -->
                  <!-- This will check equipment again and create a new resupply order if still below threshold -->
                  <signal_objects object="player.galaxy" param="'GT_DoMaintenance'" param2="$ship"/>
                </do_else>
              </do_if>
              <do_else>
                <!-- Resupply failed (got less than minimum acceptable) - add cooldown to prevent immediate retry -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance]  Resupply insufficient for ' + $ship.idcode + ' - got less than ' + $minAcceptable + ' items, adding cooldown before retry'" chance="100"/>
                </do_if>
                
                <!-- Add to failed resupply tracking with cooldown (prevents immediate retry) -->
                
                <!-- Set cooldown: 300 seconds (5 minutes) before allowing another resupply attempt -->
                <set_value name="global.$GT_MaintenanceFailedResupply.{$ship}" exact="player.age + 300s"/>
                <debug_text text="'[GT-Maintenance] ðŸ•’ Cooldown set for ' + $ship.idcode + ' until ' + (player.age + 300s) + ' (5 minutes from now)'" chance="100"/>
                
                <!-- Clear the waiting flag and remove order so ship can proceed to trading -->
                <set_value name="global.$GT_MaintenanceOrders.{$ship}.$WaitingForEquipment" exact="false"/>
                <remove_value name="global.$GT_MaintenanceOrders.{$ship}"/>
                
                <!-- Signal ship to proceed -->
                <signal_objects object="$ship" param="'GT_Maintenance_Complete'" delay="1ms"/>
              </do_else>
            </do_if>
            <do_else>
              <!-- Ship not actively tracked - this is a stale order from old save -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance]  Ignoring resupply completion for ' + $ship.idcode + ' - no active tracking (stale order from old save or order was aborted)'" chance="100"/>
                
                <!-- Log current equipment levels for debugging -->
                <set_value name="$currentCM" exact="$ship.ammostorage.countermeasure.count"/>
                <set_value name="$currentUnits" exact="$ship.units.count"/>
                <set_value name="$cmCapacity" exact="$ship.ammostorage.countermeasure.capacity"/>
                <set_value name="$unitsCapacity" exact="$ship.units.maxcount"/>
                <set_value name="$cmPercentage" exact="if $cmCapacity gt 0 then ($currentCM * 100) / $cmCapacity else 100"/>
                <set_value name="$unitsPercentage" exact="if $unitsCapacity gt 0 then ($currentUnits * 100) / $unitsCapacity else 100"/>
                <debug_text text="'[GT-Maintenance] Current equipment levels (no tracking): CM=' + $currentCM + '/' + $cmCapacity + ' (' + $cmPercentage + '%), Units=' + $currentUnits + '/' + $unitsCapacity + ' (' + $unitsPercentage + '%)'" chance="100"/>
              </do_if>
              
              <!-- Clear stale resupply order tracking -->
              <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
                <remove_value name="global.$GT_ResupplyOrders.{$ship}"/>
              </do_if>
              
              <!-- Trigger ship rename to remove [RESUPPLY] state -->
              <do_if value="@$ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
                <set_value name="$pilot" exact="$ship.pilot"/>
                <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                  <param name="ship" value="$ship"/>
                  <param name="pilot" value="$pilot"/>
                  <param name="xp" value="global.$GT_Pilots.{$pilot}.$XP"/>
                  <param name="level" value="global.$GT_Pilots.{$pilot}.$Level"/>
                  <param name="rank" value="@global.$GT_Pilots.{$pilot}.$CurrentRank"/>
                  <param name="nameType" value="'trader'"/>
                </run_actions>
              </do_if>
              
              <!-- Still need to signal ship in case AI is waiting, but don't set cooldown -->
              <!-- This allows the ship to proceed with normal operations -->
              <signal_objects object="$ship" param="'GT_Maintenance_Complete'" delay="1ms"/>
            </do_else>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- Process Repair Completion (Event-Driven from diff patch) -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessRepairComplete" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_RepairComplete'"/>
      </conditions>
      <actions>
        
        <do_if value="global.$GT_RepairCompleteQueue? and global.$GT_RepairCompleteQueue.count gt 0">
          <do_while value="global.$GT_RepairCompleteQueue.count gt 0">
            <set_value name="$data" exact="global.$GT_RepairCompleteQueue.{1}"/>
            <remove_from_list name="global.$GT_RepairCompleteQueue" exact="$data"/>
            <!-- Case-sensitive table-key fix: order.build.equip.xml (~116), order.restock.xml
                 (~120), and order.repair.xml (~19) all append rows as table[$ship = this.ship,
                 ...] using lowercase $ship. X4 expression-engine table-key lookup is
                 case-sensitive, so reading $data.$Ship returned null and cascaded the entire
                 cleanup path into "Property lookup failed: $data.$Ship" / "$ship == null"
                 spam (visible in the live log at t=2080.22, ~10 errors per resupply). The
                 ship reference must be read with the exact casing the writers used. -->
            <set_value name="$ship" exact="$data.$ship"/>
            
            <!-- Mark repair order as complete in tracking -->
            <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{$ship}?">
              <set_value name="global.$GT_MaintenanceOrders.{$ship}.$WaitingForRepair" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] Repair complete for ' + $ship.idcode + ' (from diff patch signal)'" chance="100"/>
              </do_if>
              
              <!-- Check if all maintenance complete -->
              <set_value name="$waitingForEquipment" exact="@global.$GT_MaintenanceOrders.{$ship}.$WaitingForEquipment"/>
              <do_if value="not $waitingForEquipment">
                <!-- All done! -->
                <remove_value name="global.$GT_MaintenanceOrders.{$ship}"/>
                
                <!-- Clear repair flag -->
                <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$NeedsRepair?">
                  <remove_value name="global.$GT_Ships.{$ship}.$NeedsRepair"/>
                </do_if>
                
                <!-- Clear repair order tracking -->
                <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{$ship}?">
                  <remove_value name="global.$GT_RepairOrders.{$ship}"/>
                </do_if>
                
                <!-- Trigger ship rename to remove [REPAIR]/[MAINTENANCE] state -->
                <do_if value="@$ship.pilot and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
                  <set_value name="$pilot" exact="$ship.pilot"/>
                  <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                    <param name="ship" value="$ship"/>
                    <param name="pilot" value="$pilot"/>
                    <param name="xp" value="global.$GT_Pilots.{$pilot}.$XP"/>
                    <param name="level" value="global.$GT_Pilots.{$pilot}.$Level"/>
                    <param name="rank" value="@global.$GT_Pilots.{$pilot}.$CurrentRank"/>
                    <param name="nameType" value="'trader'"/>
                  </run_actions>
                </do_if>
                
                <!-- CONCURRENCY CONTROL: Decrement counter and process queue on completion -->
                <do_if value="global.$GT_MaintenanceQueue? and global.$GT_MaintenanceQueue.$ActiveInstances? and global.$GT_MaintenanceQueue.$ActiveInstances gt 0">
                  <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" operation="subtract"/>
                  <!-- Signal queue processor to process next item -->
                  <signal_cue_instantly cue="md.GT_Maintenance.ProcessMaintenanceQueue"/>
                </do_if>
                
                <signal_objects object="$ship" param="'GT_Maintenance_Complete'" delay="1ms"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Maintenance] All maintenance complete for ' + $ship.idcode" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- ============================================================================= -->
    <!-- Fleet-wide stale repair-state cleanup (toggle off / save hygiene)            -->
    <!-- ============================================================================= -->
    <cue name="ClearAutoRepairStateAll" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$clearedCount" exact="0"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$clearIdx">
            <set_value name="$clearShip" exact="$shipKeys.{$clearIdx}"/>
            <do_if value="$clearShip? and $clearShip.exists">
              <run_actions ref="ClearAutoRepairStateForShip" result="$didClear">
                <param name="ship" value="$clearShip"/>
              </run_actions>
              <do_if value="$didClear">
                <set_value name="$clearedCount" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <signal_cue_instantly cue="md.GT_CoreSystem.UpdateAllShipNames"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance] ClearAutoRepairStateAll: cleared repair state on ' + $clearedCount + ' ship(s)'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- ============================================================================= -->
    <!-- LIBRARY: Clear stale auto-repair registry for one ship                        -->
    <!-- ============================================================================= -->
    <library name="ClearAutoRepairStateForShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to clear auto-repair tracking for"/>
      </params>
      <actions>
        <set_value name="$didClear" exact="false"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$NeedsRepair?">
          <remove_value name="global.$GT_Ships.{$ship}.$NeedsRepair"/>
          <set_value name="$didClear" exact="true"/>
        </do_if>
        <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{$ship}?">
          <remove_value name="global.$GT_RepairOrders.{$ship}"/>
          <set_value name="$didClear" exact="true"/>
        </do_if>
        <do_if value="global.$GT_MaintenanceOrders? and global.$GT_MaintenanceOrders.{$ship}?">
          <set_value name="$maintOrder" exact="global.$GT_MaintenanceOrders.{$ship}"/>
          <set_value name="$waitingRepair" exact="if $maintOrder.$WaitingForRepair? then $maintOrder.$WaitingForRepair else false"/>
          <set_value name="$waitingEquip" exact="if $maintOrder.$WaitingForEquipment? then $maintOrder.$WaitingForEquipment else false"/>
          <do_if value="$waitingRepair">
            <set_value name="$didClear" exact="true"/>
            <do_if value="$waitingEquip">
              <set_value name="global.$GT_MaintenanceOrders.{$ship}.$WaitingForRepair" exact="false"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_MaintenanceOrders.{$ship}"/>
            </do_else>
          </do_if>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $didClear">
          <debug_text text="'[GT-Maintenance] Cleared stale auto-repair state for ' + $ship.idcode" chance="100"/>
        </do_if>
        <return value="$didClear"/>
      </actions>
    </library>
    
    <!-- ============================================================================= -->
    <!-- LIBRARY: Find Nearest Repair Station                                         -->
    <!-- ============================================================================= -->
    <library name="FindNearestRepairStation" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship that needs repair"/>
        <param name="maxJumpDistance" comment="Maximum jump distance to search for repair stations"/>
      </params>
      <actions>
        <!-- PERFORMANCE OPTIMIZATION: Cache station search results (stations don't change often) -->
        <!-- Cache key: 'repair_stations' (same for all ships, stations rarely change) -->
        <!-- Cache age: 300 seconds (5 minutes) - stations can be destroyed/built, but rarely -->
        <set_value name="$cacheKey" exact="'repair_stations'"/>
        <set_value name="$cacheAge" exact="300s"/>
        <set_value name="$useCache" exact="false"/>
        
        <!-- Check if cache exists and is fresh -->
        <!-- CRITICAL: Use {'$' + $cacheKey} pattern for string keys in X4 tables -->
        <set_value name="$cacheKeyWithDollar" exact="'$' + $cacheKey"/>
        <do_if value="global.$GT_MaintenanceStationCache? and global.$GT_MaintenanceStationCache.{$cacheKeyWithDollar}?">
          <set_value name="$cacheEntry" exact="global.$GT_MaintenanceStationCache.{$cacheKeyWithDollar}"/>
          <set_value name="$cacheTime" exact="@$cacheEntry.$Timestamp"/>
          <do_if value="(player.age - $cacheTime) lt $cacheAge">
            <set_value name="$useCache" exact="true"/>
            <set_value name="$potentialStations" exact="@$cacheEntry.$Stations"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Using cached repair station search (age: ' + (player.age - $cacheTime) + 's)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Only search if cache miss or expired -->
        <do_if value="not $useCache">
          <!-- Use capability-based search instead of station type checks -->
          <!-- Vanilla pattern: Stations can repair if they have shiptrader AND can build OR supply the ship's class -->
          <!-- Source: interrupt.restock.xml:778, order.repair.xml:71-73 -->
          <!-- Find stations with shiptrader (repair capability), then validate canbuildclass OR cansupplyclass manually -->
          <!-- Note: find_station doesn't support OR logic for canbuildclass/cansupplyclass, so we search for shiptrader and validate capability -->
          <find_station name="$potentialStations" 
            space="player.galaxy" 
            multiple="true" 
            knownto="player.entity" 
            checkoperational="true" 
            sortbygatedistanceto="$ship"
            hascontrolentity="controlpost.shiptrader">
            <match class="class.station"/>
            <match_relation_to object="$ship" relation="dock" comparison="ge"/>
          </find_station>
          
          <!-- Store in cache -->
          <!-- CRITICAL: Ensure list is never null before storing in cache -->
          <do_if value="not global.$GT_MaintenanceStationCache?">
            <set_value name="global.$GT_MaintenanceStationCache" exact="table[]"/>
          </do_if>
          <!-- Ensure list is initialized (never null) -->
          <set_value name="$stationsToCache" exact="if $potentialStations? then $potentialStations else []"/>
          <set_value name="global.$GT_MaintenanceStationCache.{$cacheKeyWithDollar}" exact="table[
            $Stations = $stationsToCache,
            $Timestamp = player.age
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Cached repair station search results (' + $potentialStations.count + ' stations)'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Found ' + $potentialStations.count + ' stations with shiptrader (sorted by distance)'" chance="100"/>
        </do_if>
        
        <!-- Validate each station has repair capability AND docking capability -->
        <!-- Vanilla check: station must be able to build OR supply this ship class (interrupt.restock.xml:778) -->
        <set_value name="$validatedStations" exact="[]"/>
        <set_value name="$preFilterRejectCapability" exact="0"/>
        <set_value name="$preFilterRejectDocking" exact="0"/>
        <do_all exact="$potentialStations.count" counter="$i">
          <set_value name="$station" exact="$potentialStations.{$i}"/>
          <set_value name="$isValid" exact="true"/>
          
          <!-- Verify repair capability: can build OR supply this ship class -->
          <set_value name="$canBuild" exact="@$station.canbuildclass.{$ship.class}"/>
          <set_value name="$canSupply" exact="@$station.cansupplyclass.{$ship.class}"/>
          <do_if value="not $canBuild and not $canSupply">
            <set_value name="$isValid" exact="false"/>
            <set_value name="$preFilterRejectCapability" operation="add"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Pre-filter REJECT: ' + $station.knownname + ' - cannot build/supply class ' + $ship.class + ' (canBuild=' + $canBuild + ', canSupply=' + $canSupply + ')'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Verify docking capability: service dual probe -->
          <do_if value="$isValid">
            <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$equipPreDockResult">
              <param name="station" value="$station"/>
              <param name="ship" value="$ship"/>
              <param name="purpose" value="'dual'"/>
            </run_actions>
            <do_if value="not $equipPreDockResult.$CanDock">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$preFilterRejectDocking" operation="add"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Pre-filter REJECT: ' + $station.knownname + ' - dock preflight failed (' + $equipPreDockResult.$Reason + ') for size ' + $ship.docksize" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <do_if value="$isValid">
            <append_to_list name="$validatedStations" exact="$station"/>
          </do_if>
        </do_all>
        
        <set_value name="$potentialStations" exact="$validatedStations"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Pre-filter: ' + $potentialStations.count + ' passed, ' + $preFilterRejectCapability + ' rejected (capability), ' + $preFilterRejectDocking + ' rejected (docking) â€” ship class=' + $ship.class + ', docksize=' + $ship.docksize" chance="100"/>
        </do_if>
        
        <!-- Prefer player-owned stations if they are within +2 jumps of nearest foreign station -->
        <set_value name="$playerStationJumpPreference" exact="2"/>
        <set_value name="$nearestStation" exact="null"/>
        <set_value name="$nearestPlayerStation" exact="null"/>
        <set_value name="$nearestPlayerDistance" exact="999999"/>
        <set_value name="$nearestForeignStation" exact="null"/>
        <set_value name="$nearestForeignDistance" exact="999999"/>
        
        <do_all exact="$potentialStations.count" counter="$i">
          <set_value name="$station" exact="$potentialStations.{$i}"/>
          <set_value name="$isValid" exact="true"/>
          <set_value name="$rejectReason" exact="''"/>
          <set_value name="$gateDistance" exact="-1"/>
          
          <!-- DIAGNOSTIC: Log each station being evaluated -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') [' + $i + '/' + $potentialStations.count + '] Evaluating: ' + $station.knownname + ' (sector: ' + @$station.sector.knownname + ', owner: ' + @$station.owner.knownname + ')'" chance="100"/>
          </do_if>
          
          <!-- SAFETY CHECK 1: Blacklist checks (station + sector) -->
          <do_if value="$isValid">
            <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
              <param name="ship" value="$ship"/>
            </run_actions>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$stationBlacklisted">
              <param name="station" value="$station"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
            </run_actions>
            <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$sectorBlacklistDetails">
              <param name="sector" value="$station.sector"/>
              <param name="ship" value="$ship"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="returnDetails" value="true"/>
            </run_actions>
            <set_value name="$sectorTravelBlacklisted" exact="$sectorBlacklistDetails.$TravelBlacklisted"/>
            <set_value name="$sectorActivityBlacklisted" exact="$sectorBlacklistDetails.$ActivityBlacklisted"/>
            
            <do_if value="$stationBlacklisted or $sectorTravelBlacklisted or $sectorActivityBlacklisted">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$rejectReason" exact="if $stationBlacklisted then 'BLACKLIST(station)' else if $sectorTravelBlacklisted then 'BLACKLIST(sector-travel)' else 'BLACKLIST(sector-activity)'"/>
            </do_if>
          </do_if>
          
          <!-- SAFETY CHECK 2: Full reachability check (station known + basic path + blacklist-aware path) -->
          <do_if value="$isValid">
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$reachabilityCheck">
              <param name="ship" value="$ship"/>
              <param name="station" value="$station"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="returnDetails" value="false"/>
            </run_actions>
            <do_if value="not $reachabilityCheck">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$rejectReason" exact="'UNREACHABLE'"/>
            </do_if>
          </do_if>
          
          <!-- SAFETY CHECK 3: Get distance and check if station is within max jump distance -->
          <do_if value="$isValid">
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$gateDistance">
              <param name="ship" value="$ship"/>
              <param name="fromSector" value="$ship.sector"/>
              <param name="toSector" value="$station.sector"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="useEscapeMode" value="false"/>
            </run_actions>
            <do_if value="$gateDistance gt $maxJumpDistance">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$rejectReason" exact="'DISTANCE(' + $gateDistance + '/' + $maxJumpDistance + ')'"/>
            </do_if>
          </do_if>
          
          <!-- SAFETY CHECK 4: Verify repair capability (double-check using vanilla pattern) -->
          <do_if value="$isValid">
            <do_if value="not $station.shiptrader?">
              <set_value name="$isValid" exact="false"/>
              <set_value name="$rejectReason" exact="'NO_SHIPTRADER'"/>
            </do_if>
            <do_else>
              <set_value name="$canBuild" exact="@$station.canbuildclass.{$ship.class}"/>
              <set_value name="$canSupply" exact="@$station.cansupplyclass.{$ship.class}"/>
              <do_if value="not $canBuild and not $canSupply">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$rejectReason" exact="'NO_BUILD_OR_SUPPLY(class=' + $ship.class + ')'"/>
              </do_if>
            </do_else>
          </do_if>
          
          <!-- SAFETY CHECK 5: dock preflight covered by pre-filter dual probe (D9) -->
          
          <!-- SAFETY CHECK 6: Check if sector is excluded (from ship configuration) -->
          <do_if value="$isValid and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$Config?">
            <do_if value="global.$GT_Ships.{$ship}.$Config.$ExcludedSectors?">
              <set_value name="$isSectorExcluded" exact="false"/>
              <do_all exact="global.$GT_Ships.{$ship}.$Config.$ExcludedSectors.count" counter="$j">
                <do_if value="global.$GT_Ships.{$ship}.$Config.$ExcludedSectors.{$j} == $station.sector">
                  <set_value name="$isSectorExcluded" exact="true"/>
                  <break/>
                </do_if>
              </do_all>
              
              <do_if value="$isSectorExcluded">
                <set_value name="$isValid" exact="false"/>
                <set_value name="$rejectReason" exact="'SECTOR_EXCLUDED'"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- DIAGNOSTIC: Always log the result for every station -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <do_if value="$isValid">
              <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') [' + $i + '/' + $potentialStations.count + '] -> ACCEPTED: ' + $station.knownname + ' (distance: ' + $gateDistance + ' jumps)'" chance="100"/>
            </do_if>
            <do_else>
              <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') [' + $i + '/' + $potentialStations.count + '] -> REJECTED: ' + $station.knownname + ' | Reason: ' + $rejectReason" chance="100"/>
            </do_else>
          </do_if>
          
          <!-- Track nearest valid player and foreign stations -->
          <do_if value="$isValid">
            <do_if value="$station.owner == faction.player">
              <do_if value="$gateDistance lt $nearestPlayerDistance">
                <set_value name="$nearestPlayerStation" exact="$station"/>
                <set_value name="$nearestPlayerDistance" exact="$gateDistance"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="$gateDistance lt $nearestForeignDistance">
                <set_value name="$nearestForeignStation" exact="$station"/>
                <set_value name="$nearestForeignDistance" exact="$gateDistance"/>
              </do_if>
            </do_else>
          </do_if>
        </do_all>
        
        <!-- Final station selection with player-station preference -->
        <do_if value="$nearestPlayerStation and $nearestForeignStation">
          <do_if value="$nearestPlayerDistance le ($nearestForeignDistance + $playerStationJumpPreference)">
            <set_value name="$nearestStation" exact="$nearestPlayerStation"/>
          </do_if>
          <do_else>
            <set_value name="$nearestStation" exact="$nearestForeignStation"/>
          </do_else>
        </do_if>
        <do_elseif value="$nearestPlayerStation">
          <set_value name="$nearestStation" exact="$nearestPlayerStation"/>
        </do_elseif>
        <do_elseif value="$nearestForeignStation">
          <set_value name="$nearestStation" exact="$nearestForeignStation"/>
        </do_elseif>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $nearestStation">
          <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') Repair station preference: selected ' + $nearestStation.knownname + ' (player dist=' + $nearestPlayerDistance + ', foreign dist=' + $nearestForeignDistance + ', threshold=' + $playerStationJumpPreference + ')'" chance="100"/>
        </do_if>
        
        <do_if value="not $nearestStation">
          <debug_text text="'[GT-Maintenance] (' + $ship.idcode + ') No suitable repair station found after checking all ' + $potentialStations.count + ' discovered stations'" chance="100"/>
        </do_if>
        
        <!-- Return nearest station (or null if none found) -->
        <return value="$nearestStation"/>
      </actions>
    </library>
    
    <!-- ============================================================================= -->
    <!-- PERFORMANCE OPTIMIZATION: Process Deferred UI Updates                       -->
    <!-- Deferred operations: Ship renaming, logbook messages                        -->
    <!-- These operations don't affect gameplay and are processed after critical path -->
    <!-- ============================================================================= -->
    <cue name="ProcessDeferredUIUpdates" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="100ms"/> <!-- Process after a small delay to allow ExecuteMaintenance to complete -->
      <actions>
        <!-- Process all deferred UI updates -->
        <do_if value="global.$GT_DeferredUIUpdates?">
          <set_value name="$updateKeys" exact="@global.$GT_DeferredUIUpdates.keys"/>
          <do_if value="$updateKeys?">
            <set_value name="$updateKeysCount" exact="@$updateKeys.count"/>
            <do_if value="$updateKeysCount? and $updateKeysCount gt 0">
              <do_all exact="$updateKeysCount" counter="$i">
                <set_value name="$ship" exact="$updateKeys.{$i}"/>
                <set_value name="$update" exact="global.$GT_DeferredUIUpdates.{$ship}"/>
                
                <!-- Ship rename (for repair and equipment orders) -->
                <do_if value="($update.$Type == 'repair' or $update.$Type == 'equipment') and $update.$Pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$update.$Pilot}?">
                  <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                    <param name="ship" value="$update.$Ship"/>
                    <param name="pilot" value="$update.$Pilot"/>
                    <param name="xp" value="global.$GT_Pilots.{$update.$Pilot}.$XP"/>
                    <param name="level" value="global.$GT_Pilots.{$update.$Pilot}.$Level"/>
                    <param name="rank" value="@global.$GT_Pilots.{$update.$Pilot}.$CurrentRank"/>
                    <param name="nameType" value="'trader'"/>
                  </run_actions>
                </do_if>
                
                <!-- Logbook message -->
                <do_if value="$update.$LogbookMessage?">
                  <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                    <param name="Message" value="$update.$LogbookMessage"/>
                    <param name="Category" value="$update.$LogbookCategory"/>
                    <param name="Title" value="$update.$LogbookTitle"/>
                    <param name="Object" value="$update.$LogbookObject"/>
                    <param name="Interaction" value="$update.$LogbookInteraction"/>
                    <param name="CheckGlobalSettings" value="false"/>
                  </run_actions>
                </do_if>
                
                <!-- Clean up -->
                <remove_value name="global.$GT_DeferredUIUpdates.{$ship}"/>
              </do_all>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_MarketIntelligence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Market Intelligence System Initialization -->
    <cue name="SystemInit" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.SystemInit"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Market Intelligence system initializing...'" chance="100"/>
        </do_if>
        
        <!-- Initialize market data structures -->
        <set_value name="global.$GT_MarketPrices" exact="table[]"/>
        <set_value name="global.$GT_MarketTrends" exact="table[]"/>
        <set_value name="global.$GT_CompetitorData" exact="table[]"/>
        <set_value name="global.$GT_MarketOpportunities" exact="[]"/>
        <set_value name="global.$GT_MarketLastUpdate" exact="player.age"/>
        
        <!-- Initialize Mobile Satellite Intelligence tracking -->
        <set_value name="global.$GT_LastTradeScan" exact="table[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Market Intelligence system initialized'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- PHASE 3 IMPROVEMENT: Event-Driven Market Data Collection -->
    <!-- Listen for signal instead of polling -->
    <!-- NOTE: Currently unused, but ready for future event-driven market updates -->
    <cue name="ProcessMarketEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_MarketIntelligence.ProcessMarketEvents"/>
      </conditions>
      <actions>
        
        <!-- Process all queued market events -->
        <do_if value="global.$GT_MarketEventQueue? and global.$GT_MarketEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] âš¡ Processing ' + global.$GT_MarketEventQueue.count + ' market events instantly'" chance="100"/>
          </do_if>
          
          <do_while value="global.$GT_MarketEventQueue.count gt 0">
            <!-- Get next event -->
            <set_value name="$event" exact="global.$GT_MarketEventQueue.{1}"/>
            <remove_from_list name="global.$GT_MarketEventQueue" exact="$event"/>
            
            <!-- Process based on event type -->
            <do_if value="$event.$eventType == 'trade_completed'">
              <signal_cue_instantly cue="HandleTradeData" param="$event"/>
            </do_if>
            <do_elseif value="$event.$eventType == 'market_scan_request'">
              <signal_cue_instantly cue="HandleMarketScan" param="$event"/>
            </do_elseif>
            <do_elseif value="$event.$eventType == 'price_change_detected'">
              <signal_cue_instantly cue="HandlePriceChange" param="$event"/>
            </do_elseif>
          </do_while>
        </do_if>
      </actions>
    </cue>

    <!-- 
    ============================================================================
    EVENT-DRIVEN MOBILE SATELLITE INTELLIGENCE (Replaces Polling System)
    ============================================================================
    
    OLD SYSTEM (REMOVED): Polling-based MobileSatelliteIntelligence
    - Polled every 10s: checkinterval="10s"
    - Processed ALL active trading ships
    - Used find_station queries (expensive)
    - High CPU overhead with large fleets
    
    NEW SYSTEM: Event-driven station detection
    - Uses vanilla gravidar scan events (event_gravidar_has_scanned)
    - Zero CPU when no stations detected
    - Only processes when stations actually enter radar range
    - Same functionality, much more efficient
    
    HOW IT WORKS:
    1. AI script detects stations via gravidar (event_gravidar_has_scanned)
    2. AI signals MD with GT_Station_Detected when station detected
    3. MD processes station (cooldown check, subscription, trade snapshot)
    4. No polling overhead - truly event-driven
    
    BENEFITS:
    - 90%+ CPU reduction (no polling, only processes when needed)
    - Uses vanilla patterns (same as threat intelligence)
    - Skill gate maintained (Level 9+ pilots only)
    - Same functionality as old system
    ============================================================================
    -->
    
    <!-- Event-Driven Station Detection Handler -->
    <cue name="ProcessStationDetection" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Station_Detected'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$ship" exact="$data.$Ship"/>
        <set_value name="$station" exact="$data.$station"/>
        <set_value name="$pilotLevel" exact="$data.$pilotLevel"/>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$mobileIntelEnabled" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$MobileIntel? and global.$GT_GlobalSettings.$MobileIntel.$Enable? and global.$GT_GlobalSettings.$MobileIntel.$Enable"/>
        
        <!-- DEBUG: Log station detection received -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-MD-Intel] Station detection received: ' + $station.knownname + ' detected by ' + $ship.knownname + ' (' + $ship.idcode + ') - Level ' + $pilotLevel" chance="100"/>
        </do_if>
        
        <!-- Validate station exists and feature state -->
        <do_if value="$station.exists and $station.isoperational and $mobileIntelEnabled and not $useVanillaXPOnly">
          <!-- Check if station already has trade subscription with faction -->
          <set_value name="$hasTradeSubscription" exact="@$station.owner.hasrelation.tradesubscription.{faction.player}"/>
          
          <!-- Only process if no faction-level subscription -->
          <do_if value="not $hasTradeSubscription">
            <!-- Per-station cooldown check -->
            <set_value name="$last" exact="@global.$GT_LastTradeScan.{$station}"/>
            <set_value name="$cooldown" exact="if global.$GT_GlobalSettings.$MobileIntel.$StationCooldown? then global.$GT_GlobalSettings.$MobileIntel.$StationCooldown else 60s"/>
            
            <do_if value="not $last or (player.age - $last) gt $cooldown">
              <!-- Process station: Update trade data and add subscription -->
              <store_trade_offer_snapshot object="$station"/>
              <set_value name="$duration" exact="if global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration? then global.$GT_GlobalSettings.$MobileIntel.$SubscriptionDuration else 10min"/>
              <add_trade_subscription object="$station" duration="$duration"/>
              <set_value name="global.$GT_LastTradeScan.{$station}" exact="player.age"/>
              
              <!-- DEBUG: Log successful processing -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-MD-Intel] Processed station: ' + $station.knownname + ' - Added ' + ($duration/1min) + ' min subscription (detected by ' + $ship.knownname + ')'" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <!-- Station on cooldown -->
              <set_value name="$timeRemaining" exact="$cooldown - (player.age - $last)"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-MD-Intel] â¸ Station on cooldown: ' + $station.knownname + ' (' + ($timeRemaining/1s) + 's remaining)'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <!-- Station has faction-level trade subscription -->
            <set_value name="$factionName" exact="if @$station.owner.knownname then $station.owner.knownname else 'unknown faction'"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MD-Intel] Station skipped (faction subscription): ' + $station.knownname + ' (player has trade subscription with ' + $factionName + ')'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <!-- Station invalid or destroyed -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-MD-Intel] âš  Station invalid: ' + $station.knownname + ' (may be destroyed or invalid)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- 
    LEGACY: Mobile Satellite Intelligence (POLLING-BASED - DISABLED)
    Replaced by event-driven ProcessStationDetection cue above.
    Kept for reference but disabled to prevent CPU overhead.
    -->
    <!--
    <cue name="MobileSatelliteIntelligence" instantiate="true" checkinterval="10s">
      <conditions>
        <check_value value="false" comment="DISABLED: Replaced by event-driven ProcessStationDetection"/>
      </conditions>
      <actions>
        <comment>This cue is disabled - use ProcessStationDetection instead</comment>
      </actions>
    </cue>
    -->
    
    <!-- Handle Trade Data -->
    <cue name="HandleTradeData" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$ship" exact="$event.$ship"/>
        <set_value name="$buyStation" exact="$event.$buyStation"/>
        <set_value name="$sellStation" exact="$event.$sellStation"/>
        <set_value name="$ware" exact="$event.$ware"/>
        <set_value name="$buyPrice" exact="$event.$buyPrice"/>
        <set_value name="$sellPrice" exact="$event.$sellPrice"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Trade data event: ' + $ship.knownname + ' traded ' + $ware.name + ' (' + $buyPrice + 'â†’' + $sellPrice + ')'" chance="100"/>
        </do_if>
        
        <!-- Store trade data immediately -->
        <signal_cue_instantly cue="StorePriceData" param="table[
            $station = $buyStation,
            $ware = $ware,
            $price = $buyPrice,
            $type = 'sell'
        ]"/>
        
        <signal_cue_instantly cue="StorePriceData" param="table[
            $station = $sellStation,
            $ware = $ware,
            $price = $sellPrice,
            $type = 'buy'
        ]"/>
        
        <!-- Trigger trend analysis -->
        <signal_cue_instantly cue="AnalyzeTrends"/>
      </actions>
    </cue>
    
    <!-- Legacy Market Data Collection - removed: Event-driven system replaces polling -->
    
    <!-- Store Price Data Point -->
    <cue name="StorePriceData" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Support both old global method and new event method -->
        <do_if value="event.param?">
          <!-- New event-driven method -->
          <set_value name="$station" exact="event.param.$station"/>
          <set_value name="$ware" exact="event.param.$ware"/>
          <set_value name="$price" exact="event.param.$price"/>
          <set_value name="$type" exact="event.param.$type"/>
          <set_value name="$amount" exact="@event.param.$amount"/>
        </do_if>
        <do_else>
          <!-- Event-driven method -->
          <set_value name="$station" exact="global.$GT_CollectStation"/>
          <set_value name="$offer" exact="global.$GT_CollectOffer"/>
          <set_value name="$type" exact="global.$GT_CollectType"/>
          <set_value name="$ware" exact="$offer.ware"/>
          <set_value name="$price" exact="$offer.price"/>
          <set_value name="$amount" exact="$offer.amount"/>
        </do_else>
        
        <!-- Create price key -->
        <set_value name="$priceKey" exact="$station.sector.idcode + '_' + $ware.id + '_' + $type"/>
        
        <!-- Initialize price history if needed -->
        <do_if value="not global.$GT_MarketPrices.{$priceKey}?">
          <set_value name="global.$GT_MarketPrices.{$priceKey}" exact="table[]"/>
          <set_value name="global.$GT_MarketPrices.{$priceKey}.$History" exact="[]"/>
          <set_value name="global.$GT_MarketPrices.{$priceKey}.$Station" exact="$station"/>
          <set_value name="global.$GT_MarketPrices.{$priceKey}.$Ware" exact="$ware"/>
          <set_value name="global.$GT_MarketPrices.{$priceKey}.$Type" exact="$type"/>
        </do_if>
        
        <!-- Get history size limit from config -->
        <set_value name="$historySize" exact="10"/>
        <do_if value="global.$GT_Config? and global.$GT_Config.$Market? and global.$GT_Config.$Market.$PriceHistorySize?">
          <set_value name="$historySize" exact="global.$GT_Config.$Market.$PriceHistorySize"/>
        </do_if>
        
        <!-- Add price point -->
        <set_value name="$pricePoint" exact="table[]"/>
        <set_value name="$pricePoint.$Price" exact="$price"/>
        <set_value name="$pricePoint.$Amount" exact="$amount"/>
        <set_value name="$pricePoint.$Time" exact="player.age"/>
        
        <append_to_list name="global.$GT_MarketPrices.{$priceKey}.$History" exact="$pricePoint"/>
        
        <!-- Maintain history size -->
        <do_while value="global.$GT_MarketPrices.{$priceKey}.$History.count gt $historySize">
          <remove_from_list name="global.$GT_MarketPrices.{$priceKey}.$History" exact="global.$GT_MarketPrices.{$priceKey}.$History.{1}"/>
        </do_while>
      </actions>
    </cue>
    
    <!-- Analyze Market Trends -->
    <cue name="AnalyzeTrends" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Analyzing market trends...'" chance="100"/>
        </do_if>
        
        <!-- Clear old opportunities -->
        <set_value name="global.$GT_MarketOpportunities" exact="[]"/>
        
        <!-- Analyze each price history -->
        <do_if value="global.$GT_MarketPrices? and global.$GT_MarketPrices.keys.count gt 0">
                  <do_all exact="global.$GT_MarketPrices.keys.count" counter="$i">
                      <set_value name="$priceKey" exact="global.$GT_MarketPrices.keys.list.{$i}"/>
            <set_value name="$priceData" exact="global.$GT_MarketPrices.{$priceKey}"/>
          
          <!-- Need at least 3 data points for trend -->
          <do_if value="$priceData.$History.count ge 3">
            <!-- Calculate average price -->
            <set_value name="$avgPrice" exact="0"/>
            <do_all exact="$priceData.$History.count" counter="$j">
              <set_value name="$avgPrice" exact="$avgPrice + $priceData.$History.{$j}.$Price"/>
            </do_all>
            <set_value name="$avgPrice" exact="$avgPrice / $priceData.$History.count"/>
            
            <!-- Get current and previous prices -->
            <set_value name="$currentPrice" exact="$priceData.$History.{$priceData.$History.count}.$Price"/>
            <set_value name="$previousPrice" exact="$priceData.$History.{$priceData.$History.count - 1}.$Price"/>
            
            <!-- Calculate trend -->
            <set_value name="$trend" exact="($currentPrice - $previousPrice) / $previousPrice * 100"/>
            
            <!-- Store trend data -->
            <do_if value="not global.$GT_MarketTrends.{$priceKey}?">
              <set_value name="global.$GT_MarketTrends.{$priceKey}" exact="table[]"/>
            </do_if>
            
            <set_value name="global.$GT_MarketTrends.{$priceKey}.$Trend" exact="$trend"/>
            <set_value name="global.$GT_MarketTrends.{$priceKey}.$Average" exact="$avgPrice"/>
            <set_value name="global.$GT_MarketTrends.{$priceKey}.$Current" exact="$currentPrice"/>
            
            <!-- Identify opportunities -->
            <do_if value="$priceData.$Type == 'sell' and $currentPrice lt ($avgPrice * 0.8)">
              <!-- Buy opportunity - price is low -->
              <set_value name="$opportunity" exact="table[]"/>
              <set_value name="$opportunity.$Type" exact="'buy'"/>
              <set_value name="$opportunity.$Station" exact="$priceData.$Station"/>
              <set_value name="$opportunity.$Ware" exact="$priceData.$Ware"/>
              <set_value name="$opportunity.$Price" exact="$currentPrice"/>
              <set_value name="$opportunity.$Score" exact="($avgPrice - $currentPrice) / $avgPrice * 100"/>
              
              <append_to_list name="global.$GT_MarketOpportunities" exact="$opportunity"/>
            </do_if>
            <do_elseif value="$priceData.$Type == 'buy' and $currentPrice gt ($avgPrice * 1.2)">
              <!-- Sell opportunity - price is high -->
              <set_value name="$opportunity" exact="table[]"/>
              <set_value name="$opportunity.$Type" exact="'sell'"/>
              <set_value name="$opportunity.$Station" exact="$priceData.$Station"/>
              <set_value name="$opportunity.$Ware" exact="$priceData.$Ware"/>
              <set_value name="$opportunity.$Price" exact="$currentPrice"/>
              <set_value name="$opportunity.$Score" exact="($currentPrice - $avgPrice) / $avgPrice * 100"/>
              
              <append_to_list name="global.$GT_MarketOpportunities" exact="$opportunity"/>
            </do_elseif>
          </do_if>
        </do_all>
        </do_if>
        
        <!-- Sort opportunities by score -->
        <do_if value="global.$GT_MarketOpportunities.count gt 1">
          <sort_list list="global.$GT_MarketOpportunities" sortbyvalue="loop.element.$Score" sortdescending="true"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Found ' + global.$GT_MarketOpportunities.count + ' market opportunities'" chance="100"/>
        </do_if>
        
        <!-- Notify about exceptional opportunities (respect MarketAlerts setting) -->
        <do_if value="global.$GT_Config? and global.$GT_Config.$Notifications? and global.$GT_Config.$Notifications.$MarketAlerts and global.$GT_MarketOpportunities.count gt 0">
          <set_value name="$bestOpp" exact="global.$GT_MarketOpportunities.{1}"/>
          <do_if value="$bestOpp.$Score gt 30">
            <show_notification text="'Exceptional ' + $bestOpp.$Type + ' opportunity: ' + $bestOpp.$Ware.name + ' at ' + $bestOpp.$Station.knownname + ' (' + $bestOpp.$Score + '% profit potential)'" timeout="10s"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- PHASE 3 IMPROVEMENT: Event-Driven Competitor Tracking -->
    <!-- Initialize competitor tracking events -->
    <cue name="InitCompetitorEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.SystemInit"/>
      </conditions>
      <actions>
        <!-- Initialize competitor event system -->
        <set_value name="global.$GT_CompetitorEventQueue" exact="[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] âš¡ Competitor tracking event system initialized'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Process Competitor Events -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessCompetitorEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_MarketIntelligence.ProcessCompetitorEvents"/>
      </conditions>
      <actions>
        
        <!-- Process all queued competitor events -->
        <do_if value="global.$GT_CompetitorEventQueue? and global.$GT_CompetitorEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] âš¡ Processing ' + global.$GT_CompetitorEventQueue.count + ' competitor events instantly'" chance="100"/>
          </do_if>
          
          <do_while value="global.$GT_CompetitorEventQueue.count gt 0">
            <!-- Get next event -->
            <set_value name="$event" exact="global.$GT_CompetitorEventQueue.{1}"/>
            <remove_from_list name="global.$GT_CompetitorEventQueue" exact="$event"/>
            
            <!-- Process based on event type -->
            <do_if value="$event.$eventType == 'competitor_spotted'">
              <signal_cue_instantly cue="HandleCompetitorSpotted" param="$event"/>
            </do_if>
            <do_elseif value="$event.$eventType == 'sector_changed'">
              <signal_cue_instantly cue="HandleSectorChanged" param="$event"/>
            </do_elseif>
            <do_elseif value="$event.$eventType == 'market_scan'">
              <signal_cue_instantly cue="HandleMarketScan" param="$event"/>
            </do_elseif>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle Competitor Spotted -->
    <cue name="HandleCompetitorSpotted" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$competitor" exact="$event.$competitor"/>
        <set_value name="$sector" exact="$event.$sector"/>
        <set_value name="$playerShip" exact="$event.$playerShip"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Competitor spotted: ' + $competitor.knownname + ' in ' + $sector.knownname" chance="100"/>
        </do_if>
        
        <!-- Initialize competitor data if missing -->
        
        <do_if value="not global.$GT_CompetitorData.{$competitor}?">
          <set_value name="global.$GT_CompetitorData.{$competitor}" exact="table[]"/>
          <set_value name="global.$GT_CompetitorData.{$competitor}.$FirstSeen" exact="player.age"/>
          <set_value name="global.$GT_CompetitorData.{$competitor}.$Sightings" exact="0"/>
        </do_if>
        
        <!-- Update competitor data -->
        <set_value name="global.$GT_CompetitorData.{$competitor}.$LastSeen" exact="player.age"/>
        <set_value name="global.$GT_CompetitorData.{$competitor}.$LastSector" exact="$sector"/>
        <set_value name="global.$GT_CompetitorData.{$competitor}.$Sightings" exact="global.$GT_CompetitorData.{$competitor}.$Sightings + 1"/>
        
        <!-- Track which player ship spotted it -->
        <do_if value="not global.$GT_CompetitorData.{$competitor}.$SpottedBy?">
          <set_value name="global.$GT_CompetitorData.{$competitor}.$SpottedBy" exact="[]"/>
        </do_if>
        
        <!-- Check if player ship already in spotted list using explicit loop (indexof unreliable for lists) -->
        <set_value name="$shipAlreadySpotted" exact="false"/>
        <do_all exact="global.$GT_CompetitorData.{$competitor}.$SpottedBy.count" counter="$i">
          <do_if value="global.$GT_CompetitorData.{$competitor}.$SpottedBy.{$i} == $playerShip">
            <set_value name="$shipAlreadySpotted" exact="true"/>
            <break/>
          </do_if>
        </do_all>
        
        <do_if value="not $shipAlreadySpotted">
          <append_to_list name="global.$GT_CompetitorData.{$competitor}.$SpottedBy" exact="$playerShip"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle Sector Changes (for competitive analysis) -->
    <cue name="HandleSectorChanged" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$ship" exact="$event.$ship"/>
        <set_value name="$newSector" exact="$event.$sector"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ship sector change: ' + $ship.knownname + ' entered ' + $newSector.knownname" chance="100"/>
        </do_if>
        
        <!-- Scan for competitors in new sector -->
        <do_if value="global.$GT_Config.$Market.$CompetitorTracking?">
          <find_ship name="$competitors" space="$newSector" multiple="true">
            <match primarypurpose="purpose.trade"/>
            <match owner="$ship.owner" negate="true"/>
          </find_ship>
          
          <!-- Create competitor spotted events for each found -->
          <do_all exact="$competitors.count" counter="$i">
            <set_value name="$competitor" exact="$competitors.{$i}"/>
            
            <!-- Queue competitor spotted event -->
            <set_value name="$competitorEvent" exact="table[]"/>
            <set_value name="$competitorEvent.$eventType" exact="'competitor_spotted'"/>
            <set_value name="$competitorEvent.$competitor" exact="$competitor"/>
            <set_value name="$competitorEvent.$sector" exact="$newSector"/>
            <set_value name="$competitorEvent.$playerShip" exact="$ship"/>
            <set_value name="$competitorEvent.$timestamp" exact="player.age"/>
            
            <append_to_list name="global.$GT_CompetitorEventQueue" exact="$competitorEvent"/>
            
            <!-- Signal MD cue directly (no polling needed) -->
            <signal_cue_instantly cue="md.GT_MarketIntelligence.ProcessCompetitorEvents"/>
          </do_all>
        </do_if>
      </actions>
    </cue>

    <!-- Competitor Tracking - removed: Event-driven system replaces polling -->
    
    <!-- Handle Market Scan Events -->
    <cue name="HandleMarketScan" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$trigger" exact="$event.$trigger"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Market scan event triggered by: ' + $trigger" chance="100"/>
        </do_if>
        
        <!-- Clean up old competitor data -->
        <set_value name="$timeout" exact="3600s"/> <!-- 1 hour -->
        <set_value name="$cleanedCount" exact="0"/>
        
        <do_if value="global.$GT_CompetitorData? and global.$GT_CompetitorData.keys.count gt 0">
          <set_value name="$competitorKeys" exact="global.$GT_CompetitorData.keys.list"/>
          <do_all exact="$competitorKeys.count" counter="$i">
            <set_value name="$competitor" exact="$competitorKeys.{$i}"/>
            
            <do_if value="not $competitor.exists or (player.age - global.$GT_CompetitorData.{$competitor}.$LastSeen) gt $timeout">
              <remove_value name="global.$GT_CompetitorData.{$competitor}"/>
              <set_value name="$cleanedCount" exact="$cleanedCount + 1"/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$cleanedCount gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Cleaned up ' + $cleanedCount + ' old competitor records'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Scan current sectors for active competitors -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$foundCompetitors" exact="0"/>
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$playerShip" exact="$shipKeys.{$i}"/>
            
            <do_if value="$playerShip.exists and $playerShip.sector?">
              <!-- Find other traders in same sector -->
              <find_ship name="$sectorShips" space="$playerShip.sector" multiple="true">
                <match primarypurpose="purpose.trade"/>
                <match owner="$playerShip.owner" negate="true"/>
              </find_ship>
              
              <!-- Create spotted events for each competitor -->
              <do_all exact="$sectorShips.count" counter="$j">
                <set_value name="$competitor" exact="$sectorShips.{$j}"/>
                
                <!-- Queue competitor spotted event -->
                <set_value name="$competitorEvent" exact="table[]"/>
                <set_value name="$competitorEvent.$eventType" exact="'competitor_spotted'"/>
                <set_value name="$competitorEvent.$competitor" exact="$competitor"/>
                <set_value name="$competitorEvent.$sector" exact="$playerShip.sector"/>
                <set_value name="$competitorEvent.$playerShip" exact="$playerShip"/>
                <set_value name="$competitorEvent.$timestamp" exact="player.age"/>
                
                <append_to_list name="global.$GT_CompetitorEventQueue" exact="$competitorEvent"/>
                <set_value name="$foundCompetitors" exact="$foundCompetitors + 1"/>
              </do_all>
            </do_if>
          </do_all>
          
          <do_if value="$foundCompetitors gt 0">
            <!-- Signal MD cue directly (no polling needed) -->
            <signal_cue_instantly cue="md.GT_MarketIntelligence.ProcessCompetitorEvents"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Market scan found ' + $foundCompetitors + ' competitors'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Market Intelligence Report -->
    <cue name="GenerateMarketReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$report" exact="'Market Intelligence Report\n\n'"/>
        
        <!-- Top opportunities -->
        <set_value name="$report" exact="$report + 'TOP MARKET OPPORTUNITIES:\n'"/>
        <set_value name="$maxOpps" exact="[global.$GT_MarketOpportunities.count, 5].min"/>
        
        <do_all exact="$maxOpps" counter="$i">
          <set_value name="$opp" exact="global.$GT_MarketOpportunities.{$i}"/>
          <set_value name="$report" exact="$report + $i + '. ' + $opp.$Type + ' ' + $opp.$Ware.name + ' at ' + $opp.$Station.knownname + ' (' + $opp.$Score + '% potential)\n'"/>
        </do_all>
        
        <!-- Market trends -->
        <set_value name="$report" exact="$report + '\nMARKET TRENDS:\n'"/>
        <set_value name="$risingCount" exact="0"/>
        <set_value name="$fallingCount" exact="0"/>
        
        <do_all exact="global.$GT_MarketTrends.keys.count" counter="$i">
          <set_value name="$trend" exact="global.$GT_MarketTrends.{global.$GT_MarketTrends.keys.list.{$i}}.$Trend"/>
          <do_if value="$trend gt 5">
            <set_value name="$risingCount" exact="$risingCount + 1"/>
          </do_if>
          <do_elseif value="$trend lt -5">
            <set_value name="$fallingCount" exact="$fallingCount + 1"/>
          </do_elseif>
        </do_all>
        
        <set_value name="$report" exact="$report + 'Rising prices: ' + $risingCount + ' wares\n'"/>
        <set_value name="$report" exact="$report + 'Falling prices: ' + $fallingCount + ' wares\n'"/>
        
        <!-- Competitor activity -->
        <set_value name="$report" exact="$report + '\nCOMPETITOR ACTIVITY:\n'"/>
        <set_value name="$report" exact="$report + 'Tracked competitors: ' + global.$GT_CompetitorData.keys.count + '\n'"/>
        
        <!-- Return report -->
        <set_value name="global.$GT_MarketReport" exact="$report"/>
      </actions>
    </cue>
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<!--
  GalaxyTrader MK1 â€” Global Settings
  
  Initializes MK1-specific settings (global.$GT_MK1_GlobalSettings) and
  registers a separate Simple Menu API options menu for MK1 Station Trader.
-->
<mdscript name="GT_MK1_GlobalSettings" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>

    <!-- ================================================================ -->
    <!-- MK1 Settings Initialization                                      -->
    <!-- Runs on game load / new game â€” preserves saved settings          -->
    <!-- ================================================================ -->
    <cue name="MK1_Init" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <!-- Only initialize if settings don't exist yet (preserve saves) -->
        <do_if value="not global.$GT_MK1_GlobalSettings?">
          <set_value name="global.$GT_MK1_GlobalSettings" exact="table[]"/>

          <!-- Station Trader Defaults -->
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultMaxSell" exact="0" comment="0 = skill-based"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultSellTarget" exact="90"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBuyTarget" exact="80"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultIgnoreTradeRules" exact="false"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBacktrackTolerance" exact="1"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$WaitTimeNoTrades" exact="60s"/>

          <!-- Debug Settings (shares global debug toggle with MK3 via $GT_GlobalSettings) -->
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK1] Settings initialized (first load)'" chance="100"/>
          </do_if>
        </do_if>

        <!-- Ensure sub-tables exist (handles saves from older versions) -->
        <do_if value="not global.$GT_MK1_GlobalSettings.$StationTrader?">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultMaxSell" exact="0"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultSellTarget" exact="90"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBuyTarget" exact="80"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultIgnoreTradeRules" exact="false"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBacktrackTolerance" exact="1"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$WaitTimeNoTrades" exact="60s"/>
        </do_if>
        <do_if value="not global.$GT_MK1_GlobalSettings.$Debug?">
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/>
        </do_if>

        <debug_text text="'[GalaxyTrader MK1] MK1 settings ready'" chance="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </actions>
    </cue>

    <!-- ================================================================ -->
    <!-- Simple Menu API Registration                                     -->
    <!-- ================================================================ -->
    <cue name="MK1_MenuRegistration" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Simple_Menu_API.Reloaded"/>
      </conditions>
      <actions>
        <!-- Ensure settings are initialized before menu registration -->
        <do_if value="not global.$GT_MK1_GlobalSettings?">
          <set_value name="global.$GT_MK1_GlobalSettings" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultMaxSell" exact="0"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultSellTarget" exact="90"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBuyTarget" exact="80"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultIgnoreTradeRules" exact="false"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBacktrackTolerance" exact="1"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$WaitTimeNoTrades" exact="60s"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug" exact="table[]"/>
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/>
        </do_if>

        <!-- MK1 global settings menu intentionally hidden.
             Keep this file for default-table initialization and save compatibility. -->
        <debug_text text="'[GalaxyTrader MK1] MK1 global settings menu hidden (order setup is authoritative)'" chance="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </actions>
    </cue>

    <!-- ================================================================ -->
    <!-- MK1 Settings Menu Builder                                        -->
    <!-- Called by Simple Menu API when player opens the MK1 settings     -->
    <!-- ================================================================ -->
    <cue name="MK1_SettingsMenu" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$menu" exact="event.param"/>

        <!-- MK1 globals intentionally have no player-editable options yet -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
          $col = 1,
          $colSpan = 6,
          $text = {77000,1063},
          $halign = 'center'
        ]"/>

      </actions>
    </cue>

    <!-- ================================================================ -->
    <!-- Slider Value Handler                                             -->
    <!-- ================================================================ -->
    <cue name="MK1_UpdateSliderValue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$echo" exact="$data.$echo"/>
        <set_value name="$value" exact="$data.$value"/>

        <do_if value="$echo == 'mk1_maxsell'">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultMaxSell" exact="$value"/>
        </do_if>
        <do_elseif value="$echo == 'mk1_selltarget'">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultSellTarget" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk1_buytarget'">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBuyTarget" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk1_backtrack'">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultBacktrackTolerance" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk1_waittime'">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$WaitTimeNoTrades" exact="$value * 1s"/>
        </do_elseif>

        <debug_text text="'[GalaxyTrader MK1] Setting updated: ' + $echo + ' = ' + $value" chance="if @global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </actions>
    </cue>

    <!-- ================================================================ -->
    <!-- Checkbox Toggle Handler                                          -->
    <!-- ================================================================ -->
    <cue name="MK1_ToggleSetting" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$echo" exact="$data.$echo"/>

        <do_if value="$echo == 'mk1_ignoretraderules'">
          <set_value name="global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultIgnoreTradeRules" exact="not global.$GT_MK1_GlobalSettings.$StationTrader.$DefaultIgnoreTradeRules"/>
        </do_if>
        <do_elseif value="$echo == 'mk1_debug'">
          <set_value name="global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging" exact="not global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging"/>
        </do_elseif>

        <debug_text text="'[GalaxyTrader MK1] Toggle: ' + $echo" chance="if @global.$GT_MK1_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<!--
  GalaxyTrader MK2 â€” Global Settings
  Initializes MK2-specific settings table and registers a Simple Menu API options menu.
-->
<mdscript name="GT_MK2_GlobalSettings" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>

    <cue name="MK2_Init" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <do_if value="not global.$GT_MK2_GlobalSettings?">
          <set_value name="global.$GT_MK2_GlobalSettings" exact="table[]"/>
        </do_if>

        <do_if value="not global.$GT_MK2_GlobalSettings.$Distribution?">
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution" exact="table[]"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMinStorage" exact="20"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$DefaultStaticStorage" exact="40"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMaxStorage" exact="70"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent" exact="25"/>
        </do_if>

        <do_if value="not global.$GT_MK2_GlobalSettings.$Notifications?">
          <set_value name="global.$GT_MK2_GlobalSettings.$Notifications" exact="table[]"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Notifications.$EnableTradeNotifications" exact="true"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Notifications.$Verbosity" exact="1"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Notifications.$LogbookEntries" exact="true"/>
        </do_if>

        <do_if value="not global.$GT_MK2_GlobalSettings.$Debug?">
          <set_value name="global.$GT_MK2_GlobalSettings.$Debug" exact="table[]"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Debug.$EnableDebugLogging" exact="false"/>
          <set_value name="global.$GT_MK2_GlobalSettings.$Debug.$DebugLevel" exact="1"/>
        </do_if>
      </actions>
    </cue>

    <cue name="MK2_MenuRegistration" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Simple_Menu_API.Reloaded"/>
      </conditions>
      <actions>
        <!-- MK2 global settings menu intentionally hidden.
             Keep this file for default-table initialization and save compatibility. -->
        <debug_text text="'[GalaxyTrader MK2] MK2 global settings menu hidden (order setup is authoritative)'" chance="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
      </actions>
    </cue>

    <cue name="MK2_SettingsMenu" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Header -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[
          $col = 1,
          $colSpan = 6,
          $text = {77000, 20501},
          $halign = 'center'
        ]"/>

        <!-- Min Storage -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[$col = 1, $colSpan = 2, $text = {77000, 20510}]"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
          $col = 3, $colSpan = 4,
          $current = global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMinStorage,
          $min = 0, $max = 98, $step = 1,
          $event = md.GT_MK2_GlobalSettings.MK2_UpdateSliderValue,
          $echo = 'mk2_default_minstorage'
        ]"/>

        <!-- Static Storage -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[$col = 1, $colSpan = 2, $text = {77000, 20511}]"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
          $col = 3, $colSpan = 4,
          $current = global.$GT_MK2_GlobalSettings.$Distribution.$DefaultStaticStorage,
          $min = 1, $max = 99, $step = 1,
          $event = md.GT_MK2_GlobalSettings.MK2_UpdateSliderValue,
          $echo = 'mk2_default_staticstorage'
        ]"/>

        <!-- Max Storage -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[$col = 1, $colSpan = 2, $text = {77000, 20512}]"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
          $col = 3, $colSpan = 4,
          $current = global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMaxStorage,
          $min = 2, $max = 100, $step = 1,
          $event = md.GT_MK2_GlobalSettings.MK2_UpdateSliderValue,
          $echo = 'mk2_default_maxstorage'
        ]"/>

        <!-- Minimum Cargo Fill -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[$col = 1, $colSpan = 2, $text = {77000, 20514}]"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
          $col = 3, $colSpan = 4,
          $current = global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent,
          $min = 10, $max = 100, $step = 5,
          $event = md.GT_MK2_GlobalSettings.MK2_UpdateSliderValue,
          $echo = 'mk2_min_cargo_fill'
        ]"/>

        <!-- Notification level -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[$col = 1, $colSpan = 2, $text = {77000, 20520}]"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
          $col = 3, $colSpan = 4,
          $current = global.$GT_MK2_GlobalSettings.$Notifications.$Verbosity,
          $min = 0, $max = 2, $step = 1,
          $event = md.GT_MK2_GlobalSettings.MK2_UpdateSliderValue,
          $echo = 'mk2_notifications_verbosity'
        ]"/>

        <!-- Debug level -->
        <signal_cue_instantly cue="md.Simple_Menu_API.Add_Row"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Text" param="table[$col = 1, $colSpan = 2, $text = {77000, 20521}]"/>
        <signal_cue_instantly cue="md.Simple_Menu_API.Make_Slider" param="table[
          $col = 3, $colSpan = 4,
          $current = global.$GT_MK2_GlobalSettings.$Debug.$DebugLevel,
          $min = 0, $max = 2, $step = 1,
          $event = md.GT_MK2_GlobalSettings.MK2_UpdateSliderValue,
          $echo = 'mk2_debug_level'
        ]"/>
      </actions>
    </cue>

    <cue name="MK2_UpdateSliderValue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$echo" exact="$data.$echo"/>
        <set_value name="$value" exact="$data.$value"/>

        <do_if value="$echo == 'mk2_default_minstorage'">
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMinStorage" exact="$value"/>
        </do_if>
        <do_elseif value="$echo == 'mk2_default_staticstorage'">
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$DefaultStaticStorage" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk2_default_maxstorage'">
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$DefaultMaxStorage" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk2_min_cargo_fill'">
          <set_value name="global.$GT_MK2_GlobalSettings.$Distribution.$MinimumCargoFillPercent" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk2_notifications_verbosity'">
          <set_value name="global.$GT_MK2_GlobalSettings.$Notifications.$Verbosity" exact="$value"/>
        </do_elseif>
        <do_elseif value="$echo == 'mk2_debug_level'">
          <set_value name="global.$GT_MK2_GlobalSettings.$Debug.$DebugLevel" exact="$value"/>
        </do_elseif>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_MK3_FactionBlacklist" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <cue name="RegisterGTActionGroup" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'Interact_Menu_API'" control="'reloaded'"/>
      </conditions>
      <actions>
        <raise_lua_event name="'Interact_Menu_API.Add_Custom_Actions_Group_Id'" param="'gt_actions'"/>
        <raise_lua_event name="'Interact_Menu_API.Add_Custom_Actions_Group_Text'" param="'GalaxyTrader'"/>
      </actions>
    </cue>

    <cue name="Init" instantiate="true">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <do_if value="not global.$GT_MK3FactionBlacklist?">
          <set_value name="global.$GT_MK3FactionBlacklist" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_MK3FactionBlacklist.$ShipSelections?">
          <set_value name="global.$GT_MK3FactionBlacklist.$ShipSelections" exact="table[]"/>
        </do_if>
        <signal_cue cue="RefreshAvailableFactions"/>
      </actions>
    </cue>

    <cue name="OnFactionChanged" instantiate="true">
      <conditions>
        <check_any>
          <event_faction_activated/>
          <event_faction_deactivated/>
        </check_any>
      </conditions>
      <actions>
        <signal_cue cue="RefreshAvailableFactions"/>
      </actions>
    </cue>

    <cue name="RefreshAvailableFactions" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_MK3FactionBlacklist?">
          <set_value name="global.$GT_MK3FactionBlacklist" exact="table[]"/>
        </do_if>
        <set_value name="$available" exact="[]"/>
        <set_value name="$availableByFaction" exact="table[]"/>
        <do_for_each name="$faction" in="lookup.faction.list">
          <!-- Keep list practical for MK3 trade use:
               known, active, economic factions that currently allow player docking. -->
          <do_if value="$faction.isactive and $faction.knowntoplayer and $faction.iseconomic and $faction != faction.player and not $faction.isvisitor and $faction.hasrelation.dock.{faction.player}">
            <set_value name="$factionName" exact="$faction.name"/>
            <do_if value="$factionName != '' and not $availableByFaction.{$faction}?">
              <append_to_list name="$available" exact="$faction"/>
              <set_value name="$availableByFaction.{$faction}" exact="true"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MK3-FBL] Available faction: ' + $faction + ' name=' + (if $factionName != '' then $factionName else '[empty-name]')" chance="100"/>
            </do_if>
          </do_if>
        </do_for_each>
        <set_value name="global.$GT_MK3FactionBlacklist.$Available" exact="$available"/>
      </actions>
    </cue>

    <cue name="AddMK3BlacklistAction" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Interact_Menu_API.Get_Actions"/>
      </conditions>
      <actions>
        <set_value name="$target" exact="event.param.$object"/>
        <do_if value="$target.isclass.{class.ship} and $target.isplayerowned">
          <!-- Fleet commander only: ship must run MK3 directly and have subordinates. -->
          <do_if value="$target.defaultorder? and @$target.defaultorder.id == 'GalaxyTraderMK3' and $target.allsubordinates? and @$target.allsubordinates.count gt 0">
            <signal_cue_instantly cue="md.Interact_Menu_API.Add_Action" param="table[
              $id = 'gt_mk3_faction_blacklist',
              $text = 'MK3 Faction Blacklist',
              $section = 'gt_actions',
              $callback = GT_MK3FactionBlacklistAction,
            ]"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <cue name="GT_MK3FactionBlacklistAction" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param.$object"/>
        <set_value name="$canOpen" exact="true"/>
        <do_if value="not $ship? or not $ship.exists">
          <show_notification text="'[GT] MK3 faction blacklist unavailable: ship missing.'" timeout="5s"/>
          <set_value name="$canOpen" exact="false"/>
        </do_if>

        <do_if value="$canOpen">
          <do_if value="not global.$GT_MK3FactionBlacklist? or not global.$GT_MK3FactionBlacklist.$Available?">
            <signal_cue cue="RefreshAvailableFactions"/>
          </do_if>

          <set_value name="global.$GT_MK3FactionBlacklist.$UIShip" exact="$ship"/>
          <signal_cue cue="PublishUIData"/>
          <raise_lua_event name="'gt.openMK3FactionBlacklist'" param="$ship.idcode"/>
        </do_if>
      </actions>
    </cue>

    <cue name="PublishUIData" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="@global.$GT_MK3FactionBlacklist.$UIShip"/>
        <set_value name="$canPublish" exact="true"/>
        <do_if value="not $ship? or not $ship.exists">
          <set_value name="$canPublish" exact="false"/>
        </do_if>

        <do_if value="$canPublish">
          <set_value name="$data" exact="''"/>
          <set_value name="$available" exact="if global.$GT_MK3FactionBlacklist.$Available? then global.$GT_MK3FactionBlacklist.$Available else []"/>
          <do_all exact="$available.count" counter="$i">
            <set_value name="$faction" exact="$available.{$i}"/>
            <set_value name="$factionName" exact="$faction.name"/>
            <set_value name="$factionShort" exact="$faction.shortname"/>
            <set_value name="$factionDisplay" exact="$factionName"/>
            <do_if value="$factionShort? and $factionShort != null and $factionShort != '' and $factionName != ''">
              <set_value name="$factionDisplay" exact="$factionShort + ' - ' + $factionName"/>
            </do_if>
            <do_elseif value="$faction.id? and $faction.id != null and $faction.id != '' and $factionName != ''">
              <set_value name="$factionDisplay" exact="$faction.id + ' - ' + $factionName"/>
            </do_elseif>
            <do_if value="$factionName == ''">
              <set_value name="$factionName" exact="'Faction ' + $i"/>
              <set_value name="$factionDisplay" exact="$factionName"/>
            </do_if>
            <set_value name="$selected" exact="'0'"/>
            <do_if value="global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}.{$faction}?">
              <set_value name="$selected" exact="'1'"/>
            </do_if>
            <set_value name="$entry" exact="$i + '||' + $factionDisplay + '||' + $selected"/>
            <do_if value="$data == ''">
              <set_value name="$data" exact="$entry"/>
            </do_if>
            <do_else>
              <set_value name="$data" exact="$data + '@@' + $entry"/>
            </do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $i le 60">
              <debug_text text="'[GT-MK3-FBL] UI row ' + $i + ': faction=' + $faction + ' short=' + (if $factionShort? and $factionShort != '' then $factionShort else '-') + ' name=' + $factionName + ' selected=' + $selected" chance="100"/>
            </do_if>
          </do_all>

          <set_value name="player.entity.$GT_MK3FBL_Data" exact="$data"/>
          <set_value name="player.entity.$GT_MK3FBL_ShipName" exact="$ship.knownname"/>
          <set_value name="player.entity.$GT_MK3FBL_ShipCode" exact="$ship.idcode"/>
          <set_value name="player.entity.$GT_MK3FBL_Total" exact="$available.count"/>

          <raise_lua_event name="'gt.refreshMK3FactionBlacklist'" param="$ship.idcode"/>
        </do_if>
      </actions>
    </cue>

    <cue name="HandleToggleFaction" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_MK3FactionBlacklist'" control="'ToggleFaction'"/>
      </conditions>
      <actions>
        <set_value name="$idx" exact="0"/>
        <set_value name="$p" exact="event.param3"/>
        <do_if value="$p? and $p.$index?">
          <set_value name="$idx" exact="$p.$index"/>
        </do_if>
        <do_elseif value="event.param2? and event.param2.$index?">
          <set_value name="$idx" exact="event.param2.$index"/>
        </do_elseif>
        <set_value name="$ship" exact="@global.$GT_MK3FactionBlacklist.$UIShip"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-MK3-FBL] Toggle request param=' + event.param + ' param2=' + event.param2 + ' param3=' + event.param3 + ' resolved_idx=' + $idx" chance="100"/>
        </do_if>

        <do_if value="$idx gt 0 and $ship? and $ship.exists and global.$GT_MK3FactionBlacklist.$Available? and global.$GT_MK3FactionBlacklist.$Available.{$idx}?">
          <set_value name="$faction" exact="global.$GT_MK3FactionBlacklist.$Available.{$idx}"/>

          <do_if value="not global.$GT_MK3FactionBlacklist.$ShipSelections?">
            <set_value name="global.$GT_MK3FactionBlacklist.$ShipSelections" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}?">
            <set_value name="global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}" exact="table[]"/>
          </do_if>

          <do_if value="global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}.{$faction}?">
            <remove_value name="global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}.{$faction}"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MK3-FBL] Unblocked faction idx=' + $idx + ' faction=' + $faction" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="global.$GT_MK3FactionBlacklist.$ShipSelections.{$ship}.{$faction}" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MK3-FBL] Blocked faction idx=' + $idx + ' faction=' + $faction" chance="100"/>
            </do_if>
          </do_else>

          <!-- Refresh names immediately for this blacklist owner + subordinates.
               Do not use GT_CoreSystem.UpdateAllShipNames here: that path rebuilds names with
               legacy logic and can delay/omit CustomBlacklist tag updates until order cycle. -->
          <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$ship.pilot"/>
            <param name="forceUpdate" value="true"/>
          </run_actions>
          <do_if value="$ship.allsubordinates? and $ship.allsubordinates.count gt 0">
            <do_all exact="$ship.allsubordinates.count" counter="$si">
              <set_value name="$sub" exact="$ship.allsubordinates.{$si}"/>
              <do_if value="$sub? and $sub.exists and $sub.isclass.ship">
                <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                  <param name="ship" value="$sub"/>
                  <param name="pilot" value="$sub.pilot"/>
                  <param name="forceUpdate" value="true"/>
                </run_actions>
              </do_if>
            </do_all>
          </do_if>
          <signal_cue cue="PublishUIData"/>
        </do_if>
      </actions>
    </cue>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Order_Monitor_Bridge" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <!--
    Bridge between Lua order monitor and MD cleanup system
    Provides batched order change detection as fallback when event_object_order_cancelled doesn't fire
  -->
  
  <cues>
    <!-- Shared scheduler for ship idcode map rebuild. -->
    <library name="OMB_RequestRebuildShipIdCodeMap" purpose="run_actions">
      <actions>
        <signal_cue_instantly cue="md.GT_Order_Monitor_Bridge.RebuildShipIdCodeMap"/>
      </actions>
    </library>

    <!-- Ensure authoritative idcode->ship map exists on startup/load -->
    <cue name="BootstrapShipIdCodeMap" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Setup.Start"/>
        <check_value value="global.$GT_Ships?"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestRebuildShipIdCodeMap"/>
      </actions>
    </cue>

    <!-- Rebuild authoritative idcode->ship map from GT registry -->
    <cue name="RebuildShipIdCodeMap" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Order_Monitor_Bridge.RebuildShipIdCodeMap"/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_ShipIDCodeMap?">
          <set_value name="global.$GT_ShipIDCodeMap" exact="table[]"/>
        </do_if>
        <do_all exact="global.$GT_Ships.keys.count" counter="$i">
          <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
          <do_if value="$ship.exists and $ship.idcode? and $ship.idcode != null and $ship.idcode != ''">
            <set_value name="global.$GT_ShipIDCodeMap.{'$' + $ship.idcode}" exact="$ship"/>
          </do_if>
        </do_all>
      </actions>
    </cue>

    <!-- Shared fallback instrumentation: ship lookup by idcode missed map cache. -->
    <library name="OMB_RecordShipLookupFallback" purpose="run_actions">
      <params>
        <param name="shipID"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Libraries_General.GT_IncrementFallbackActivation" result="$faCount">
          <param name="key" value="'OrderMonitor.ShipLookupFallback'"/>
        </run_actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-OMB] Ship lookup fallback activated for idcode=' + $shipID + ' count=' + $faCount" chance="100"/>
        </do_if>
      </actions>
    </library>

    <!-- Shared fallback instrumentation: commander-status utility unavailable. -->
    <library name="OMB_RecordCommanderStatusFallback" purpose="run_actions">
      <params>
        <param name="shipID"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Libraries_General.GT_IncrementFallbackActivation" result="$faCount">
          <param name="key" value="'OrderMonitor.CommanderStatusFallback'"/>
        </run_actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-OMB] Commander status fallback activated for ship=' + $shipID + ' count=' + $faCount" chance="100"/>
        </do_if>
      </actions>
    </library>

    <!-- Shared fast id-map lookup (no fallback side effects). -->
    <library name="OMB_TryResolveShipByIdFromMap" purpose="run_actions">
      <params>
        <param name="shipID"/>
      </params>
      <actions>
        <set_value name="$ship" exact="null"/>
        <do_if value="global.$GT_ShipIDCodeMap? and global.$GT_ShipIDCodeMap.{'$' + $shipID}?">
          <set_value name="$ship" exact="global.$GT_ShipIDCodeMap.{'$' + $shipID}"/>
        </do_if>
        <return value="$ship"/>
      </actions>
    </library>

    <!-- Shared ship resolver with map rebuild and bounded linear-scan fallback. -->
    <library name="OMB_ResolveShipById" purpose="run_actions">
      <params>
        <param name="shipID"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_TryResolveShipByIdFromMap" result="$ship">
          <param name="shipID" value="$shipID"/>
        </run_actions>
        <do_if value="not $ship">
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RecordShipLookupFallback">
            <param name="shipID" value="$shipID"/>
          </run_actions>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestRebuildShipIdCodeMap"/>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_TryResolveShipByIdFromMap" result="$ship">
            <param name="shipID" value="$shipID"/>
          </run_actions>
          <do_if value="not $ship">
            <do_if value="global.$GT_Ships?">
              <do_all exact="global.$GT_Ships.keys.count" counter="$i">
                <set_value name="$candidateShip" exact="global.$GT_Ships.keys.{$i}"/>
                <do_if value="$candidateShip.idcode == $shipID">
                  <set_value name="$ship" exact="$candidateShip"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
          </do_if>
        </do_if>
        <return value="$ship"/>
      </actions>
    </library>

    <!-- Shared original-name resolver for cleanup payloads. -->
    <library name="OMB_GetOriginalShipName" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$originalName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Ships.{$ship}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
          <set_value name="$originalName" exact="global.$GT_Pilots.{$ship.pilot}.$OriginalShipName"/>
        </do_elseif>
        <do_elseif value="$ship.macro?">
          <set_value name="$originalName" exact="@$ship.macro.name"/>
        </do_elseif>
        <return value="$originalName"/>
      </actions>
    </library>

    <!-- Shared cleanup signal emitter for Lua-detected order removals. -->
    <library name="OMB_EmitShipOrderAborted" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="reason"/>
        <param name="originalName" default="null"/>
      </params>
      <actions>
        <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
          $Ship = $ship,
          $Pilot = $pilot,
          $Reason = $reason,
          $OriginalName = $originalName
        ]"/>
      </actions>
    </library>

    <!-- Resolve original ship name and emit cleanup signal in one call. -->
    <library name="OMB_EmitShipOrderAbortedWithResolvedName" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="reason"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_GetOriginalShipName" result="$originalName">
          <param name="ship" value="$ship"/>
        </run_actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EmitShipOrderAborted">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="reason" value="$reason"/>
          <param name="originalName" value="$originalName"/>
        </run_actions>
      </actions>
    </library>

    <!-- Convenience wrapper for resolved-name cleanup using ship's current pilot. -->
    <library name="OMB_EmitShipOrderAbortedUsingShipPilot" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="reason"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EmitShipOrderAbortedWithResolvedName">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$ship.pilot"/>
          <param name="reason" value="$reason"/>
        </run_actions>
      </actions>
    </library>

    <!-- Shared handler for simple Lua cleanup events keyed by ship id. -->
    <library name="OMB_HandleSimpleCleanupByShipId" purpose="run_actions">
      <params>
        <param name="shipID"/>
        <param name="debugLabel"/>
        <param name="reason"/>
        <param name="useShipPilot" default="true"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ResolveShipById" result="$ship">
          <param name="shipID" value="$shipID"/>
        </run_actions>
        
        <do_if value="$ship and $ship.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Cleaning up ship (' + $debugLabel + '): ' + $ship.knownname + ' (ID: ' + $shipID + ')'" chance="100"/>
          </do_if>
          
          <set_value name="$pilot" exact="null"/>
          <do_if value="$useShipPilot and $ship.pilot?">
            <set_value name="$pilot" exact="$ship.pilot"/>
          </do_if>
          
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EmitShipOrderAbortedWithResolvedName">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="reason" value="$reason"/>
          </run_actions>
        </do_if>
      </actions>
    </library>

    <!-- Shared scheduler for debounced ship-list refresh requests. -->
    <library name="OMB_RequestShipListRefresh" purpose="run_actions">
      <actions>
        <signal_cue_instantly cue="md.GT_Order_Monitor_Bridge.QueueShipListRefresh"/>
      </actions>
    </library>

    <!-- Shared scheduler for debounced ship-list flush worker. -->
    <library name="OMB_RequestFlushShipListRefresh" purpose="run_actions">
      <actions>
        <signal_cue_instantly cue="md.GT_Order_Monitor_Bridge.FlushShipListRefresh"/>
      </actions>
    </library>

    <!-- Clear debounced ship-list refresh flags if state exists. -->
    <library name="OMB_ClearShipListRefreshFlags" purpose="run_actions">
      <actions>
        <do_if value="global.$GT_OrderMonitorShipListRefreshState?">
          <set_value name="global.$GT_OrderMonitorShipListRefreshState.$Pending" exact="false"/>
          <set_value name="global.$GT_OrderMonitorShipListRefreshState.$Scheduled" exact="false"/>
        </do_if>
      </actions>
    </library>

    <!-- Rebuild idcode map and return Lua ship-list string payload. -->
    <library name="OMB_BuildShipListPayload" purpose="run_actions">
      <actions>
        <set_value name="$shipListString" exact="''"/>
        <do_if value="not global.$GT_ShipIDCodeMap?">
          <set_value name="global.$GT_ShipIDCodeMap" exact="table[]"/>
        </do_if>
        <do_all exact="global.$GT_Ships.keys.count" counter="$i">
          <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
          <do_if value="$ship.exists">
            <!-- Update reverse lookup table using vanilla pattern: {'$' + idcode} -->
            <do_if value="$ship.idcode? and $ship.idcode != null and $ship.idcode != ''">
              <set_value name="global.$GT_ShipIDCodeMap.{'$' + $ship.idcode}" exact="$ship"/>
            </do_if>
            <!-- Build comma-separated string of "UniverseID:IDCode" pairs for Lua -->
            <do_if value="$shipListString != ''">
              <set_value name="$shipListString" exact="$shipListString + ','"/>
            </do_if>
            <set_value name="$shipListString" exact="$shipListString + $ship + ':' + $ship.idcode"/>
          </do_if>
        </do_all>
        <return value="$shipListString"/>
      </actions>
    </library>

    <!-- Shared Lua push for monitor ship-list payload updates. -->
    <library name="OMB_PushShipListUpdate" purpose="run_actions">
      <params>
        <param name="shipListString" default="''"/>
      </params>
      <actions>
        <raise_lua_event name="'GT_OrderMonitor.UpdateShipList'" param="$shipListString"/>
      </actions>
    </library>

    <!-- Shared GT-presence probe used by initial and delayed order-removal verification. -->
    <library name="OMB_CheckGTControlPresence" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="shipID"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[
          $HasDirectGT = false,
          $HasGTCommander = false,
          $CommanderDefaultOrderNull = false
        ]"/>

        <!-- Direct GT order still present? -->
        <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
          <set_value name="$result.$HasDirectGT" exact="true"/>
        </do_if>

        <!-- GT via commander still present? -->
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <do_if value="md.GT_Ship_State_Utilities.GT_CheckCommanderStatus?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckCommanderStatus" result="$commanderStatus">
              <param name="ship" value="$ship"/>
            </run_actions>
            <set_value name="$result.$HasGTCommander" exact="$commanderStatus.$CommanderHasGT"/>
          </do_if>
          <do_else>
            <!-- Fallback commander check for early-load/library-order edge cases -->
            <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RecordCommanderStatusFallback">
              <param name="shipID" value="$shipID"/>
            </run_actions>
            <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
              <set_value name="$result.$HasGTCommander" exact="true"/>
            </do_if>
            <do_elseif value="$ship.commander.defaultorder? and @$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.$baseorder.id}">
              <set_value name="$result.$HasGTCommander" exact="true"/>
            </do_elseif>
          </do_else>
          <do_if value="(not @$ship.commander.defaultorder) or (@$ship.commander.defaultorder == null)">
            <set_value name="$result.$CommanderDefaultOrderNull" exact="true"/>
          </do_if>
        </do_if>

        <return value="$result"/>
      </actions>
    </library>

    <!-- Shared normalized GT-presence flags for callers that need safe booleans. -->
    <library name="OMB_GetGTControlFlags" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="shipID"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_CheckGTControlPresence" result="$gtPresence">
          <param name="ship" value="$ship"/>
          <param name="shipID" value="$shipID"/>
        </run_actions>
        <set_value name="$flags" exact="table[
          $HasDirectGT = if $gtPresence.$HasDirectGT? then $gtPresence.$HasDirectGT else false,
          $HasGTCommander = if $gtPresence.$HasGTCommander? then $gtPresence.$HasGTCommander else false,
          $CommanderDefaultOrderNull = if $gtPresence.$CommanderDefaultOrderNull? then $gtPresence.$CommanderDefaultOrderNull else false
        ]"/>
        <return value="$flags"/>
      </actions>
    </library>

    <!-- Parse GT-order-removal payload variants into normalized fields. -->
    <library name="OMB_ParseOrderRemovalPayload" purpose="run_actions">
      <params>
        <param name="payload"/>
      </params>
      <actions>
        <set_value name="$parsed" exact="table[
          $ShipID = if $payload? and $payload.$ShipID? then $payload.$ShipID else if $payload? and $payload.$ship? then $payload.$ship else '',
          $OldOrder = if $payload? and $payload.$OldOrder? then $payload.$OldOrder else if $payload? and $payload.$oldOrder? then $payload.$oldOrder else null,
          $NewOrder = if $payload? and $payload.$NewOrder? then $payload.$NewOrder else if $payload? and $payload.$newOrder? then $payload.$newOrder else null
        ]"/>
        <return value="$parsed"/>
      </actions>
    </library>

    <!-- Parse order-removal payload and resolve current ship object in one call. -->
    <library name="OMB_ParseAndResolveOrderRemovalPayload" purpose="run_actions">
      <params>
        <param name="payload"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ParseOrderRemovalPayload" result="$parsed">
          <param name="payload" value="$payload"/>
        </run_actions>
        <set_value name="$shipID" exact="$parsed.$ShipID"/>
        <set_value name="$oldOrder" exact="$parsed.$OldOrder"/>
        <set_value name="$newOrder" exact="$parsed.$NewOrder"/>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ResolveShipById" result="$ship">
          <param name="shipID" value="$shipID"/>
        </run_actions>
        <return value="table[
          $ShipID = $shipID,
          $OldOrder = $oldOrder,
          $NewOrder = $newOrder,
          $Ship = $ship
        ]"/>
      </actions>
    </library>

    <!-- Decide if GT-order removal should be treated as transient/deferred. -->
    <library name="OMB_ShouldDeferGTOrderRemoval" purpose="run_actions">
      <params>
        <param name="gtFlags"/>
        <param name="oldOrder" default="null"/>
        <param name="newOrder" default="null"/>
        <param name="includeOrderTransitionHint" default="false"/>
      </params>
      <actions>
        <set_value name="$defer" exact="false"/>
        <do_if value="$gtFlags.$HasDirectGT or $gtFlags.$HasGTCommander or $gtFlags.$CommanderDefaultOrderNull">
          <set_value name="$defer" exact="true"/>
        </do_if>
        <do_elseif value="$includeOrderTransitionHint and (global.$GT_ProtectedOrderIDs? and $oldOrder? and global.$GT_ProtectedOrderIDs.indexof.{$oldOrder}) and ((not $newOrder?) or $newOrder == null or $newOrder == '')">
          <set_value name="$defer" exact="true"/>
        </do_elseif>
        <return value="$defer"/>
      </actions>
    </library>

    <!-- Resolve GT-presence flags and defer decision for order-removal handling. -->
    <library name="OMB_EvaluateGTOrderRemovalDeferral" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="shipID"/>
        <param name="oldOrder" default="null"/>
        <param name="newOrder" default="null"/>
        <param name="includeOrderTransitionHint" default="false"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_GetGTControlFlags" result="$gtFlags">
          <param name="ship" value="$ship"/>
          <param name="shipID" value="$shipID"/>
        </run_actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ShouldDeferGTOrderRemoval" result="$deferCleanup">
          <param name="gtFlags" value="$gtFlags"/>
          <param name="oldOrder" value="$oldOrder"/>
          <param name="newOrder" value="$newOrder"/>
          <param name="includeOrderTransitionHint" value="$includeOrderTransitionHint"/>
        </run_actions>
        <return value="table[
          $DeferCleanup = $deferCleanup,
          $GTFlags = $gtFlags
        ]"/>
      </actions>
    </library>
    
    <!-- Send ship list to Lua monitor when it's ready -->
    <cue name="InitializeMonitor" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_OrderMonitor'" control="'Ready'"/>
        <check_value value="global.$GT_Ships?"/>
      </conditions>
      <actions>
        <!-- Build ship list from GT registry and refresh reverse id map. -->
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_BuildShipListPayload" result="$shipListString"/>
        
        <!-- Send to Lua as comma-separated string -->
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_PushShipListUpdate">
          <param name="shipListString" value="$shipListString"/>
        </run_actions>
        
        <!-- Start monitoring -->
        <raise_lua_event name="'GT_OrderMonitor.Start'"/>
      </actions>
    </cue>
    
    <!-- Handle GT order removal detected by Lua - triggers cleanup directly -->
    <cue name="HandleGTOrderRemoved" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_OrderMonitor'" control="'GTOrderRemoved'"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ParseAndResolveOrderRemovalPayload" result="$orderRemoval">
          <param name="payload" value="event.param3"/>
        </run_actions>
        <set_value name="$shipID" exact="$orderRemoval.$ShipID"/>
        <set_value name="$oldOrder" exact="$orderRemoval.$OldOrder"/>
        <set_value name="$newOrder" exact="$orderRemoval.$NewOrder"/>
        <set_value name="$ship" exact="$orderRemoval.$Ship"/>
        
        <do_if value="$ship and $ship.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Cleanup] Cleaning up ship (GT order removed): ' + $ship.knownname + ' (ID: ' + $shipID + ')'" chance="100"/>
          </do_if>
          
          <!-- SAFETY: Lua order monitor can briefly report GT order removal during fleet commander promotion.
               Defer cleanup and verify after a short delay to avoid purging GT registry during transient states. -->
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EvaluateGTOrderRemovalDeferral" result="$deferEval">
            <param name="ship" value="$ship"/>
            <param name="shipID" value="$shipID"/>
            <param name="oldOrder" value="$oldOrder"/>
            <param name="newOrder" value="$newOrder"/>
            <param name="includeOrderTransitionHint" value="true"/>
          </run_actions>
          <set_value name="$gtFlags" exact="$deferEval.$GTFlags"/>
          <set_value name="$deferCleanup" exact="$deferEval.$DeferCleanup"/>
          
          <do_if value="$deferCleanup">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Deferring GTOrderRemoved cleanup for ' + $shipID + ' (old=' + (if $oldOrder? then $oldOrder else 'null') + ', new=' + (if $newOrder? then $newOrder else 'null') + ', directGT=' + $gtFlags.$HasDirectGT + ', viaCommander=' + $gtFlags.$HasGTCommander + ', commanderDefaultNull=' + $gtFlags.$CommanderDefaultOrderNull + ')'" chance="100"/>
            </do_if>
            <signal_cue_instantly cue="md.GT_Order_Monitor_Bridge.VerifyGTOrderRemoved" param="table[
              $ShipID = $shipID,
              $OldOrder = $oldOrder,
              $NewOrder = $newOrder
            ]"/>
          </do_if>
          
          <!-- Trigger cleanup only if not deferred -->
          <do_if value="not $deferCleanup">
            <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EmitShipOrderAbortedUsingShipPilot">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'GT order removed (Lua detection)'"/>
            </run_actions>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Verify a GT order removal after a short delay (guards against transient null default orders during promotion) -->
    <cue name="VerifyGTOrderRemoved" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Order_Monitor_Bridge.VerifyGTOrderRemoved"/>
      </conditions>
      <delay exact="3s"/>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ParseAndResolveOrderRemovalPayload" result="$orderRemoval">
          <param name="payload" value="event.param"/>
        </run_actions>
        <set_value name="$shipID" exact="$orderRemoval.$ShipID"/>
        <set_value name="$oldOrder" exact="$orderRemoval.$OldOrder"/>
        <set_value name="$newOrder" exact="$orderRemoval.$NewOrder"/>
        <set_value name="$ship" exact="$orderRemoval.$Ship"/>
        
        <do_if value="$ship and $ship.exists">
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EvaluateGTOrderRemovalDeferral" result="$deferEval">
            <param name="ship" value="$ship"/>
            <param name="shipID" value="$shipID"/>
            <param name="oldOrder" value="$oldOrder"/>
            <param name="newOrder" value="$newOrder"/>
            <param name="includeOrderTransitionHint" value="false"/>
          </run_actions>
          <set_value name="$gtFlags" exact="$deferEval.$GTFlags"/>
          <set_value name="$deferCleanup" exact="$deferEval.$DeferCleanup"/>
          
          <do_if value="$deferCleanup">
            <!-- False positive / still transitioning: do nothing -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Verified GTOrderRemoved was transient for ' + $shipID + ' (directGT=' + $gtFlags.$HasDirectGT + ', viaCommander=' + $gtFlags.$HasGTCommander + ', commanderDefaultNull=' + $gtFlags.$CommanderDefaultOrderNull + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Still removed: proceed with cleanup -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Cleanup] Verified GTOrderRemoved - cleaning up ' + $shipID + ' (old=' + (if $oldOrder? then $oldOrder else 'null') + ', new=' + (if $newOrder? then $newOrder else 'null') + ')'" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_EmitShipOrderAbortedUsingShipPilot">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'GT order removed (Lua detection, verified)'"/>
            </run_actions>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle missing pilot detection from Lua -->
    <cue name="HandleMissingPilot" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_OrderMonitor'" control="'MissingPilot'"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_HandleSimpleCleanupByShipId">
          <param name="shipID" value="event.param3.$ship"/>
          <param name="debugLabel" value="'missing pilot'"/>
          <param name="reason" value="'Missing pilot (Lua detection)'"/>
          <param name="useShipPilot" value="false"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Handle commander lost GT order from Lua -->
    <cue name="HandleCommanderLostGT" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_OrderMonitor'" control="'CommanderLostGT'"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_HandleSimpleCleanupByShipId">
          <param name="shipID" value="event.param3.$ship"/>
          <param name="debugLabel" value="'commander lost GT'"/>
          <param name="reason" value="'Commander lost GT order (Lua detection)'"/>
          <param name="useShipPilot" value="true"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Handle commander removed from Lua -->
    <cue name="HandleCommanderRemoved" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'GT_OrderMonitor'" control="'CommanderRemoved'"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_HandleSimpleCleanupByShipId">
          <param name="shipID" value="event.param3.$ship"/>
          <param name="debugLabel" value="'commander removed'"/>
          <param name="reason" value="'Commander removed (Lua detection)'"/>
          <param name="useShipPilot" value="true"/>
        </run_actions>
      </actions>
    </cue>

    <!-- Debounced ship-list refresh request queue (coalesces bursty triggers). -->
    <cue name="QueueShipListRefresh" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Order_Monitor_Bridge.QueueShipListRefresh"/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_OrderMonitorShipListRefreshState?">
          <set_value name="global.$GT_OrderMonitorShipListRefreshState" exact="table[
            $Pending = false,
            $Scheduled = false
          ]"/>
        </do_if>
        <set_value name="global.$GT_OrderMonitorShipListRefreshState.$Pending" exact="true"/>
        <do_if value="not global.$GT_OrderMonitorShipListRefreshState.$Scheduled">
          <set_value name="global.$GT_OrderMonitorShipListRefreshState.$Scheduled" exact="true"/>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestFlushShipListRefresh"/>
        </do_if>
      </actions>
    </cue>

    <!-- Debounced full ship-list rebuild/push worker. -->
    <cue name="FlushShipListRefresh" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Order_Monitor_Bridge.FlushShipListRefresh"/>
      </conditions>
      <delay exact="250ms"/>
      <actions>
        <set_value name="$proceed" exact="true"/>
        <do_if value="not global.$GT_OrderMonitorShipListRefreshState?">
          <set_value name="$proceed" exact="false"/>
        </do_if>
        <do_elseif value="not global.$GT_Ships?">
          <set_value name="$proceed" exact="false"/>
        </do_elseif>

        <do_if value="$proceed">
          <set_value name="global.$GT_OrderMonitorShipListRefreshState.$Pending" exact="false"/>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_BuildShipListPayload" result="$shipListString"/>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_PushShipListUpdate">
            <param name="shipListString" value="$shipListString"/>
          </run_actions>

          <do_if value="global.$GT_OrderMonitorShipListRefreshState.$Pending">
            <!-- Another trigger arrived while rebuilding; run one more coalesced pass. -->
            <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestFlushShipListRefresh"/>
          </do_if>
          <do_else>
            <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ClearShipListRefreshFlags"/>
          </do_else>
        </do_if>
        <do_else>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_ClearShipListRefreshFlags"/>
        </do_else>
      </actions>
    </cue>
    
    <!-- Update ship list when ships are removed from GT registry -->
    <!-- Using instantiate="false" to prevent multiple instances for same signal -->
    <cue name="UpdateShipList" instantiate="false">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_Order_Aborted'"/>
        <check_value value="global.$GT_Ships?"/>
      </conditions>
      <delay exact="500ms"/>
      <actions>
        <!-- Get ship info from signal -->
        <set_value name="$removedShip" exact="null"/>
        <set_value name="$removedShipID" exact="'UNKNOWN'"/>
        <set_value name="$removedShipName" exact="'UNKNOWN'"/>
        <do_if value="event.param2? and event.param2.$Ship? and event.param2.$Ship != null">
          <set_value name="$removedShip" exact="event.param2.$Ship"/>
          <do_if value="$removedShip.exists">
            <set_value name="$removedShipID" exact="$removedShip.idcode"/>
            <set_value name="$removedShipName" exact="$removedShip.knownname"/>
          </do_if>
        </do_if>
        
        <!-- Check if ship is still in registry (deduplication - avoid updating if already removed) -->
        <set_value name="$shipStillInRegistry" exact="false"/>
        <do_if value="$removedShipID != 'UNKNOWN' and global.$GT_Ships.{$removedShip}?">
          <set_value name="$shipStillInRegistry" exact="true"/>
        </do_if>
        
        <!-- Only queue list refresh if ship was actually removed from registry -->
        <do_if value="not $shipStillInRegistry">
          <!-- Remove from reverse lookup table -->
          <do_if value="global.$GT_ShipIDCodeMap? and global.$GT_ShipIDCodeMap.{'$' + $removedShipID}?">
            <remove_value name="global.$GT_ShipIDCodeMap.{'$' + $removedShipID}"/>
          </do_if>
          <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestShipListRefresh"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Event-driven ship list update: On ship state updates -->
    <cue name="UpdateShipList_OnStateUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_State_Update'"/>
        <check_value value="global.$GT_Ships?"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestShipListRefresh"/>
      </actions>
    </cue>
    
    <!-- Event-driven ship list update: On AI start (new/returned ships) -->
    <cue name="UpdateShipList_OnAIStarted" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_AI_Started'"/>
        <check_value value="global.$GT_Ships?"/>
      </conditions>
      <actions>
        <run_actions ref="md.GT_Order_Monitor_Bridge.OMB_RequestShipListRefresh"/>
      </actions>
    </cue>
    
  </cues>
  
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Pilot_Field_Migration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    
    <!-- One-time migration: Add $Pilot field to existing ships -->
    <!-- Runs on both new games and save game loads -->
    <cue name="MigratePilotField" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <delay exact="1s"/>
      <actions>
        <set_value name="$updatedCount" exact="0"/>
        <set_value name="$skipCount" exact="0"/>
        
        <!-- Check if GT system is initialized -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PilotMigration] Checking ' + global.$GT_Ships.keys.count + ' ships for missing $Pilot field...'" chance="100"/>
          </do_if>
          
          <!-- Iterate through all registered ships -->
          <do_all exact="global.$GT_Ships.keys.count" counter="$i">
            <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
            <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
            
            <!-- Check if Pilot field is missing but ship has a pilot -->
            <do_if value="not $shipData.$Pilot? and @$ship.pilot">
              <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$ship.pilot"/>
              <set_value name="$updatedCount" operation="add"/>
              <!-- <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-PilotMigration] Added $Pilot field to: ' + @$ship.knownname + ' (Pilot: ' + @$ship.pilot.name + ')'" chance="100"/>
              </do_if> -->
            </do_if>
            <do_else>
              <set_value name="$skipCount" operation="add"/>
            </do_else>
          </do_all>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PilotMigration] Complete: ' + $updatedCount + ' ships updated, ' + $skipCount + ' ships skipped (already had pilot or no pilot assigned)'" chance="100"/>
          </do_if>
          
          <!-- Signal info menu to refresh if it's initialized -->
          <do_if value="$updatedCount gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-PilotMigration] Triggering pilot data refresh for UI...'" chance="100"/>
            </do_if>
            <signal_cue_instantly cue="md.GT_InfoMenu_Loader.SendPilotData"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PilotMigration] No ships registered yet - skipping migration'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- One-time migration: Ensure all pilots have $TotalProfit field -->
    <cue name="MigratePilotProfit" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <delay exact="1.5s"/>
      <actions>
        <set_value name="$updatedCount" exact="0"/>
        
        <!-- Check if pilot system is initialized -->
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PilotMigration] Checking ' + global.$GT_Pilots.keys.count + ' pilots for missing $TotalProfit field...'" chance="100"/>
          </do_if>
          
          <!-- Iterate through all registered pilots -->
          <do_all exact="global.$GT_Pilots.keys.count" counter="$i">
            <set_value name="$pilot" exact="global.$GT_Pilots.keys.{$i}"/>
            <set_value name="$pilotData" exact="global.$GT_Pilots.{$pilot}"/>
            
            <!-- Check if TotalProfit field is missing -->
            <do_if value="not $pilotData.$TotalProfit?">
              <set_value name="global.$GT_Pilots.{$pilot}.$TotalProfit" exact="0"/>
              <set_value name="$updatedCount" operation="add"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-PilotMigration] Added $TotalProfit field to pilot: ' + @$pilot.name" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PilotMigration] Pilot profit migration complete: ' + $updatedCount + ' pilots updated'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Backfill $StableIdentity (seed/id) for saves from before stable pilot keys â€” enables transfer recovery + UI map. -->
    <cue name="MigratePilotStableIdentity" instantiate="true" version="3">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <delay exact="2s"/>
      <actions>
        <set_value name="$updatedCount" exact="0"/>
        <do_if value="not global.$GT_PilotsByStable?">
          <set_value name="global.$GT_PilotsByStable" exact="table[]"/>
        </do_if>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$i">
            <set_value name="$pilotRef" exact="global.$GT_Pilots.keys.{$i}"/>
            <do_if value="global.$GT_Pilots.{$pilotRef}?">
              <do_if value="not global.$GT_Pilots.{$pilotRef}.$StableIdentity? or global.$GT_Pilots.{$pilotRef}.$StableIdentity == ''">
                <do_if value="$pilotRef and $pilotRef.exists and md.GT_Ship_Management.Ensure_Pilot_Fields?">
                  <run_actions ref="md.GT_Ship_Management.Ensure_Pilot_Fields">
                    <param name="pilot" value="$pilotRef"/>
                  </run_actions>
                  <set_value name="$updatedCount" operation="add"/>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
          <!-- Build stable index: live object wins on duplicate stable keys (P12). -->
          <do_all exact="global.$GT_Pilots.keys.count" counter="$j">
            <set_value name="$pRef2" exact="global.$GT_Pilots.keys.{$j}"/>
            <do_if value="global.$GT_Pilots.{$pRef2}? and global.$GT_Pilots.{$pRef2}.$StableIdentity? and global.$GT_Pilots.{$pRef2}.$StableIdentity != ''">
              <do_all exact="global.$GT_Pilots.keys.count" counter="$m">
                <set_value name="$pRefM" exact="global.$GT_Pilots.keys.{$m}"/>
                <do_if value="$j != $m and global.$GT_Pilots.{$pRefM}? and global.$GT_Pilots.{$pRefM}.$StableIdentity? and global.$GT_Pilots.{$pRefM}.$StableIdentity == global.$GT_Pilots.{$pRef2}.$StableIdentity">
                  <do_if value="$pRef2.exists and not $pRefM.exists">
                    <remove_value name="global.$GT_Pilots.{$pRefM}"/>
                  </do_if>
                  <do_elseif value="$pRefM.exists and not $pRef2.exists">
                    <remove_value name="global.$GT_Pilots.{$pRef2}"/>
                  </do_elseif>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
          <set_value name="global.$GT_PilotsByStable" exact="table[]"/>
          <do_all exact="global.$GT_Pilots.keys.count" counter="$k">
            <set_value name="$liveOut" exact="global.$GT_Pilots.keys.{$k}"/>
            <do_if value="$liveOut and $liveOut.exists and global.$GT_Pilots.{$liveOut}?">
              <run_actions ref="md.GT_Ship_Management.Sync_Stable_Identity_Index">
                <param name="pilot" value="$liveOut"/>
              </run_actions>
            </do_if>
          </do_all>
          <do_if value="$updatedCount gt 0 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-PilotMigration] StableIdentity backfill: ' + $updatedCount + ' pilot record(s)'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
      <patch sinceversion="1" state="complete">
        <reset_cue cue="MigratePilotStableIdentity"/>
      </patch>
      <patch sinceversion="2" state="complete">
        <reset_cue cue="MigratePilotStableIdentity"/>
      </patch>
    </cue>
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Pilot_Promotion" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  
  <cues>
    <!-- Check if pilot is eligible for promotion -->
    <library name="CheckPilotPromotionEligibility" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot entity to check"/>
      </params>
      <actions>
        <set_value name="$eligibleClass" exact="null"/>
        <set_value name="$currentShipClass" exact="null"/>
        
        <!-- Get pilot's current ship -->
        <set_value name="$currentShip" exact="null"/>
        <do_if value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Ship?">
          <set_value name="$currentShip" exact="global.$GT_Pilots.{$pilot}.$Ship"/>
        </do_if>
        
        <!-- If no ship assigned, not eligible -->
        <do_if value="not $currentShip? or not $currentShip.exists">
          <return value="table[$EligibleClass=null, $CurrentShipClass=null, $CanPromote=false]"/>
        </do_if>
        
        <!-- Detect current ship class -->
        <run_actions ref="md.GT_Ship_Management.Detect_Ship_Class" result="$classInfo">
          <param name="ship" value="$currentShip"/>
        </run_actions>
        <set_value name="$currentShipClass" exact="$classInfo.$Size"/> <!-- 'S', 'M', 'L', or 'XL' -->
        
        <!-- Calculate pilot's skill level from XP -->
        <set_value name="$pilotXP" exact="0"/>
        <do_if value="global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$XP?">
          <set_value name="$pilotXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
        </do_if>
        <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level_From_XP" result="$skillLevel">
          <param name="pilot" value="$pilot"/>
          <param name="xp" value="$pilotXP"/>
        </run_actions>
        
        <!-- Check promotion thresholds based on skill level -->
        <!-- Level 4+ can promote to M-class -->
        <!-- Level 7+ can promote to L-class -->
        <!-- Level 10+ can promote to XL-class -->
        <do_if value="$skillLevel ge 10 and $currentShipClass != 'XL'">
          <set_value name="$eligibleClass" exact="'XL'"/>
        </do_if>
        <do_elseif value="$skillLevel ge 7 and $currentShipClass != 'L' and $currentShipClass != 'XL'">
          <set_value name="$eligibleClass" exact="'L'"/>
        </do_elseif>
        <do_elseif value="$skillLevel ge 4 and $currentShipClass == 'S'">
          <set_value name="$eligibleClass" exact="'M'"/>
        </do_elseif>
        
        <!-- Return eligibility result -->
        <set_value name="$canPromote" exact="($eligibleClass? and $eligibleClass != null)"/>
        <return value="table[
          $EligibleClass=$eligibleClass,
          $CurrentShipClass=$currentShipClass,
          $CanPromote=$canPromote,
          $SkillLevel=$skillLevel
        ]"/>
      </actions>
    </library>
    
    <!-- Find available ships for promotion -->
    <library name="FindAvailableShipsForPromotion" purpose="run_actions">
      <params>
        <param name="targetClass" comment="Target ship class ('M', 'L', or 'XL')"/>
        <param name="pilot" comment="Pilot entity (for distance calculation)"/>
      </params>
      <actions>
        <create_list name="$availableShips"/>
        
        <!-- Get pilot's current ship for distance calculation -->
        <set_value name="$pilotShip" exact="null"/>
        <set_value name="$pilotSector" exact="null"/>
        <do_if value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Ship?">
          <set_value name="$pilotShip" exact="global.$GT_Pilots.{$pilot}.$Ship"/>
          <do_if value="$pilotShip.exists and $pilotShip.sector?">
            <set_value name="$pilotSector" exact="$pilotShip.sector"/>
          </do_if>
        </do_if>
        
        <!-- Iterate through all player ships -->
        <set_value name="$shipsKeysCount" exact="@global.$GT_Ships.keys.count"/>
        <do_if value="$shipsKeysCount? and $shipsKeysCount gt 0">
          <do_all exact="$shipsKeysCount" counter="$i">
            <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
            
            <!-- Filter criteria -->
            <do_if value="$ship.exists and 
                          $ship.isoperational and 
                          $ship.isplayerowned and
                          not $ship.pilot?">
              
              <!-- Check ship class matches target -->
              <run_actions ref="md.GT_Ship_Management.Detect_Ship_Class" result="$shipClassInfo">
                <param name="ship" value="$ship"/>
              </run_actions>
              
              <do_if value="$shipClassInfo.$Size == $targetClass">
                <!-- Calculate distance if pilot ship available -->
                <set_value name="$distance" exact="-1"/>
                <do_if value="$pilotShip? and $pilotShip.exists and $ship.sector?">
                  <set_value name="$distance" exact="$pilotShip.gatedistance.{$ship.sector}"/>
                  <do_if value="$distance lt 0">
                    <set_value name="$distance" exact="999999"/> <!-- Unreachable -->
                  </do_if>
                </do_if>
                
                <!-- Get cargo capacity -->
                <set_value name="$cargoCapacity" exact="0"/>
                <do_if value="$ship.cargo? and $ship.cargo.capacity?">
                  <set_value name="$cargoCapacity" exact="$ship.cargo.capacity.all"/>
                </do_if>
                
                <!-- Add ship to available list -->
                <append_to_list name="$availableShips" exact="table[
                  $Ship=$ship,
                  $Name=$ship.knownname,
                  $IDCode=$ship.idcode,
                  $CargoCapacity=$cargoCapacity,
                  $SectorName=@$ship.sector.knownname,
                  $Distance=$distance
                ]"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Sort by cargo capacity (descending), then by distance (ascending) -->
        <do_if value="$availableShips.count gt 1">
          <!-- Simple bubble sort (MD doesn't have advanced sorting) -->
          <do_all exact="$availableShips.count" counter="$i">
            <do_all exact="($availableShips.count - $i)" counter="$j">
              <set_value name="$ship1" exact="$availableShips.{$j}"/>
              <set_value name="$ship2" exact="$availableShips.{$j + 1}"/>
              
              <!-- Compare: cargo first, then distance -->
              <set_value name="$shouldSwap" exact="false"/>
              <do_if value="$ship1.$CargoCapacity lt $ship2.$CargoCapacity">
                <set_value name="$shouldSwap" exact="true"/>
              </do_if>
              <do_elseif value="$ship1.$CargoCapacity == $ship2.$CargoCapacity and $ship1.$Distance gt $ship2.$Distance">
                <set_value name="$shouldSwap" exact="true"/>
              </do_elseif>
              <do_else>
                <!-- No swap needed -->
              </do_else>
              
              <do_if value="$shouldSwap">
                <set_value name="$availableShips.{$j}" exact="$ship2"/>
                <set_value name="$availableShips.{$j + 1}" exact="$ship1"/>
              </do_if>
            </do_all>
          </do_all>
        </do_if>
        
        <return value="$availableShips"/>
      </actions>
    </library>
    
    <!-- Handle promotion ship request from Lua -->
    <cue name="GT_HandlePromotionShipRequest" instantiate="true">
      <conditions>
        <event_object_signalled object="player.entity" param="'gt_promotion_request_ships'"/>
      </conditions>
      <actions>
        <set_value name="$shipId" exact="event.param2.$ShipId"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Promotion] Received ship request for promotion: ' + $shipId" chance="100"/>
        </do_if>
        
        <!-- Find ship by ID -->
        <set_value name="$ship" exact="null"/>
        <set_value name="$shipsKeysCount" exact="@global.$GT_Ships.keys.count"/>
        <do_if value="$shipsKeysCount? and $shipsKeysCount gt 0">
          <do_all exact="$shipsKeysCount" counter="$i">
            <set_value name="$checkShip" exact="global.$GT_Ships.keys.{$i}"/>
            <do_if value="$checkShip.exists and $checkShip.idcode == $shipId">
              <set_value name="$ship" exact="$checkShip"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Check if ship found and has pilot -->
        <do_if value="@$ship.exists and (@$ship.pilot != null)">
          <set_value name="$pilot" exact="$ship.pilot"/>
          
          <!-- Check eligibility -->
          <run_actions ref="md.GT_Pilot_Promotion.CheckPilotPromotionEligibility" result="$eligibility">
            <param name="pilot" value="$pilot"/>
          </run_actions>
          
          <do_if value="$eligibility.$CanPromote">
            <!-- Find available ships -->
            <run_actions ref="md.GT_Pilot_Promotion.FindAvailableShipsForPromotion" result="$availableShips">
              <param name="targetClass" value="$eligibility.$EligibleClass"/>
              <param name="pilot" value="$pilot"/>
            </run_actions>
            
            <!-- Send ship list to Lua -->
            <do_if value="$availableShips.count gt 0">
              <!-- Build ship data string for Lua -->
              <set_value name="$shipDataString" exact="''"/>
              <do_all exact="$availableShips.count" counter="$i">
                <set_value name="$shipData" exact="$availableShips.{$i}"/>
                <do_if value="$i gt 1">
                  <set_value name="$shipDataString" exact="$shipDataString + '||'"/>
                </do_if>
                <set_value name="$shipDataString" exact="$shipDataString + 
                  $shipData.$IDCode + '|' +
                  $shipData.$Name + '|' +
                  $shipData.$CargoCapacity + '|' +
                  $shipData.$SectorName + '|' +
                  $shipData.$Distance"/>
              </do_all>
              
              <!-- Send to Lua -->
              <raise_lua_event name="'GT_PromotionShips.Available'" param="table[
                $ShipId=$shipId,
                $PilotName=$pilot.name,
                $TargetClass=$eligibility.$EligibleClass,
                $ShipData=$shipDataString
              ]"/>
            </do_if>
            <do_else>
              <!-- No ships available -->
              <raise_lua_event name="'GT_PromotionShips.None'" param="table[
                $ShipId=$shipId,
                $PilotName=$pilot.name,
                $TargetClass=$eligibility.$EligibleClass
              ]"/>
            </do_else>
          </do_if>
          <do_else>
            <!-- Not eligible -->
            <raise_lua_event name="'GT_PromotionShips.NotEligible'" param="table[
              $ShipId=$shipId,
              $PilotName=$pilot.name
            ]"/>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle ship selection from Lua and execute promotion -->
    <cue name="GT_PromotePilotShipSelected" instantiate="true">
      <conditions>
        <event_object_signalled object="player.entity" param="'gt_promotion_ship_selected'"/>
      </conditions>
      <actions>
        <set_value name="$shipId" exact="event.param2.$ShipId"/>
        <set_value name="$targetShipId" exact="event.param2.$TargetShipId"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Promotion] Executing promotion: Ship ' + $shipId + ' -> ' + $targetShipId" chance="100"/>
        </do_if>
        
        <!-- Find source ship -->
        <set_value name="$sourceShip" exact="null"/>
        <set_value name="$shipsKeysCount" exact="@global.$GT_Ships.keys.count"/>
        <do_if value="$shipsKeysCount? and $shipsKeysCount gt 0">
          <do_all exact="$shipsKeysCount" counter="$i">
            <set_value name="$checkShip" exact="global.$GT_Ships.keys.{$i}"/>
            <do_if value="$checkShip.exists and $checkShip.idcode == $shipId">
              <set_value name="$sourceShip" exact="$checkShip"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Find target ship -->
        <set_value name="$targetShip" exact="null"/>
        <do_if value="$shipsKeysCount? and $shipsKeysCount gt 0">
          <do_all exact="$shipsKeysCount" counter="$i">
            <set_value name="$checkShip" exact="global.$GT_Ships.keys.{$i}"/>
            <do_if value="$checkShip.exists and $checkShip.idcode == $targetShipId">
              <set_value name="$targetShip" exact="$checkShip"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Validate ships -->
        <do_if value="@$sourceShip.exists and @$targetShip.exists and (@$sourceShip.pilot != null) and (@$targetShip.pilot == null)">
          <set_value name="$pilot" exact="$sourceShip.pilot"/>
          
          <!-- Execute pilot transfer -->
          <run_actions ref="md.GT_Pilot_Promotion.ExecutePilotPromotion" result="$result">
            <param name="pilot" value="$pilot"/>
            <param name="sourceShip" value="$sourceShip"/>
            <param name="targetShip" value="$targetShip"/>
          </run_actions>
          
          <!-- Send result to Lua -->
          <raise_lua_event name="'GT_Promotion.Complete'" param="table[
            $Success=$result.$Success,
            $Message=$result.$Message
          ]"/>
        </do_if>
        <do_else>
          <!-- Validation failed -->
          <raise_lua_event name="'GT_Promotion.Complete'" param="table[
            $Success=false,
            $Message='Promotion failed: Invalid ships'
          ]"/>
        </do_else>
      </actions>
    </cue>
    
    <!-- Execute pilot promotion (transfer pilot to new ship) -->
    <library name="ExecutePilotPromotion" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot entity to transfer"/>
        <param name="sourceShip" comment="Source ship (current ship)"/>
        <param name="targetShip" comment="Target ship (new ship)"/>
      </params>
      <actions>
        <set_value name="$success" exact="false"/>
        <set_value name="$message" exact="'Unknown error'"/>
        
        <!-- Validate inputs -->
        <do_if value="not $pilot? or not $sourceShip? or not $targetShip?">
          <return value="table[$Success=false, $Message='Invalid parameters']"/>
        </do_if>
        
        <do_if value="not $sourceShip.exists or not $targetShip.exists">
          <return value="table[$Success=false, $Message='Ship does not exist']"/>
        </do_if>
        
        <!-- Verify pilot is on source ship -->
        <do_if value="not $sourceShip.pilot? or $sourceShip.pilot != $pilot">
          <return value="table[$Success=false, $Message='Pilot not on source ship']"/>
        </do_if>
        
        <!-- Verify target ship has no pilot -->
        <do_if value="$targetShip.pilot?">
          <return value="table[$Success=false, $Message='Target ship already has a pilot']"/>
        </do_if>
        
        <!-- Store original ship name for cleanup -->
        <set_value name="$originalShipName" exact="null"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$sourceShip}? and global.$GT_Ships.{$sourceShip}.$OriginalShipName?">
          <set_value name="$originalShipName" exact="global.$GT_Ships.{$sourceShip}.$OriginalShipName"/>
        </do_if>
        <do_else>
          <!-- Extract original name from current ship name (remove GT formatting) -->
          <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$cleanedName">
            <param name="shipName" value="$sourceShip.knownname"/>
          </run_actions>
          <set_value name="$originalShipName" exact="$cleanedName"/>
        </do_else>
        
        <!-- Check if source ship has GT order -->
        <set_value name="$sourceHasGTOrder" exact="false"/>
        <do_if value="$sourceShip.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$sourceShip.defaultorder.id})">
          <set_value name="$sourceHasGTOrder" exact="true"/>
        </do_if>
        
        <!-- Step 1: Remove GT order from source ship (if present) -->
        <do_if value="$sourceHasGTOrder">
          <do_if value="$sourceShip.defaultorder?">
            <cancel_order order="$sourceShip.defaultorder"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Promotion] Removed GT order from source ship ' + $sourceShip.knownname" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Step 2: Restore original name to source ship -->
        <do_if value="$originalShipName? and $originalShipName != ''">
          <run_actions ref="md.GT_Ship_Management.Restore_Original_Ship_Name">
            <param name="ship" value="$sourceShip"/>
            <param name="pilot" value="$pilot"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Promotion] Restored original name to source ship: ' + $originalShipName" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Step 3: Update pilot registry with new ship (before actual transfer) -->
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$targetShip"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$targetShip.idcode"/>
          
          <!-- Store original name for new ship -->
          <!-- Initialize ship registry if needed -->
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{$targetShip}?">
            <set_value name="global.$GT_Ships.{$targetShip}" exact="table[]"/>
          </do_if>
          <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$targetCleanedName">
            <param name="shipName" value="$targetShip.knownname"/>
          </run_actions>
          <set_value name="global.$GT_Ships.{$targetShip}.$OriginalShipName" exact="$targetCleanedName"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Promotion] Updated pilot registry: ' + $pilot.name + ' -> ' + $targetShip.knownname" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Step 4: Assign GT order to target ship (if source had GT order) -->
        <!-- Note: Order is assigned BEFORE pilot transfer so GT system is ready -->
        <!-- Note: GT orders are created through game UI, not MD. We'll signal the system to register the ship -->
        <do_if value="$sourceHasGTOrder">
          <!-- Signal that ship should get GT order (will be handled by RegisterShip cue) -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Promotion] Target ship will receive GT order when pilot is assigned: ' + $targetShip.knownname" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Step 5: Update ship registry -->
        <do_if value="global.$GT_Ships.{$sourceShip}?">
          <!-- Remove pilot reference from old ship -->
          <remove_value name="global.$GT_Ships.{$sourceShip}.$Pilot"/>
        </do_if>
        
        <do_if value="global.$GT_Ships.{$targetShip}?">
          <!-- Do not pre-bind the pilot object on the target ship.
               The actual in-game assignment can replace the actor object, so
               HandleVanillaPilotAssignment/Register_Pilot must remain authoritative. -->
          <remove_value name="global.$GT_Ships.{$targetShip}.$Pilot"/>
        </do_if>
        
        <!-- Step 6: Assign pilot to target ship -->
        <!-- Note: X4 MD scripts cannot directly assign pilots - this must be done through game UI -->
        <!-- GT will detect the pilot assignment via GT_Update_Ship events when it happens -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Promotion] Pilot ' + $pilot.name + ' should be manually assigned to ship ' + $targetShip.knownname + ' through game UI'" chance="100"/>
        </do_if>
        
        <!-- Step 7: Write logbook message -->
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="'Pilot ' + $pilot.name + ' promotion prepared: GT order moved from ' + $sourceShip.knownname + ' to ' + $targetShip.knownname + '. Please assign pilot ' + $pilot.name + ' to ' + $targetShip.knownname + ' manually if needed.'"/>
          <param name="Category" value="'news'"/>
          <param name="Title" value="'Pilot Promotion Prepared: ' + $pilot.name"/>
          <param name="Object" value="$targetShip"/>
        </run_actions>
        
        <set_value name="$success" exact="true"/>
        <set_value name="$message" exact="'Promotion prepared - GT registry updated, orders moved. Pilot assignment may require manual intervention.'"/>
        
        <return value="table[$Success=$success, $Message=$message]"/>
      </actions>
    </library>
    
    <!-- Handle auto-transfer request (process all eligible pilots) -->
    <cue name="GT_HandleAutoTransfer" instantiate="true">
      <conditions>
        <event_object_signalled object="player.entity" param="'gt_promotion_auto_transfer'"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Promotion] Auto-transfer requested - processing all eligible pilots'" chance="100"/>
        </do_if>
        
        <set_value name="$processedCount" exact="0"/>
        <set_value name="$successCount" exact="0"/>
        <set_value name="$failedCount" exact="0"/>
        
        <!-- Get all pilots -->
        <set_value name="$pilotsKeysCount" exact="@global.$GT_Pilots.keys.count"/>
        <do_if value="$pilotsKeysCount? and $pilotsKeysCount gt 0">
          <do_all exact="$pilotsKeysCount" counter="$i">
            <set_value name="$pilot" exact="global.$GT_Pilots.keys.{$i}"/>
            
            <!-- Check if pilot is eligible -->
            <run_actions ref="md.GT_Pilot_Promotion.CheckPilotPromotionEligibility" result="$eligibility">
              <param name="pilot" value="$pilot"/>
            </run_actions>
            
            <do_if value="$eligibility.$CanPromote">
              <set_value name="$processedCount" operation="add"/>
              
              <!-- Find best available ship -->
              <run_actions ref="md.GT_Pilot_Promotion.FindAvailableShipsForPromotion" result="$availableShips">
                <param name="targetClass" value="$eligibility.$EligibleClass"/>
                <param name="pilot" value="$pilot"/>
              </run_actions>
              
              <!-- If ships available, use first one (already sorted by cargo/distance) -->
              <do_if value="$availableShips.count gt 0">
                <set_value name="$sourceShip" exact="null"/>
                <do_if value="global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Ship?">
                  <set_value name="$sourceShip" exact="global.$GT_Pilots.{$pilot}.$Ship"/>
                </do_if>
                
                <do_if value="@$sourceShip.exists">
                  <set_value name="$targetShip" exact="$availableShips.{1}.$Ship"/>
                  
                  <!-- Execute promotion -->
                  <run_actions ref="md.GT_Pilot_Promotion.ExecutePilotPromotion" result="$result">
                    <param name="pilot" value="$pilot"/>
                    <param name="sourceShip" value="$sourceShip"/>
                    <param name="targetShip" value="$targetShip"/>
                  </run_actions>
                  
                  <do_if value="$result.$Success">
                    <set_value name="$successCount" operation="add"/>
                  </do_if>
                  <do_else>
                    <set_value name="$failedCount" operation="add"/>
                  </do_else>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Send completion message to Lua -->
        <raise_lua_event name="'GT_Promotion.AutoTransferComplete'" param="table[
          $Processed=$processedCount,
          $Success=$successCount,
          $Failed=$failedCount
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$debugMsg" exact="'[GT Promotion] Auto-transfer complete: ' + $processedCount + ' processed, ' + $successCount + ' successful, ' + $failedCount + ' failed'"/>
          <debug_text text="$debugMsg" chance="100"/>
        </do_if>
      </actions>
    </cue>
  </cues>
  
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Profit_Migration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - PROFIT STATISTICS MIGRATION
         Version 0.6.0: Reset inflated profit statistics
         
         CONTEXT: Prior to v0.6.0, profit calculations tracked REVENUE instead of actual PROFIT.
         This resulted in statistics showing ~5-6x higher values than actual earnings.
         
         This migration resets all profit statistics so they start fresh with the corrected calculation.
         ======================================== -->
    
    <!-- Manual profit statistics reset (triggered by player via button in settings) -->
    <cue name="ResetInflatedProfitStats" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ProfitMigration] Starting manual profit statistics reset (player triggered)...'" chance="100"/>
        </do_if>
          
          <set_value name="$pilotCount" exact="0"/>
          <set_value name="$shipCount" exact="0"/>
          
          <!-- Reset pilot profit statistics -->
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
            <do_all exact="global.$GT_Pilots.keys.count" counter="$i">
              <set_value name="$pilot" exact="global.$GT_Pilots.keys.{$i}"/>
              <set_value name="$pilotData" exact="global.$GT_Pilots.{$pilot}"/>
              
              <!-- Check if pilot has inflated profit (TotalProfit exists and is non-zero) -->
              <do_if value="$pilotData.$TotalProfit? and $pilotData.$TotalProfit gt 0">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-ProfitMigration] Resetting pilot ' + @$pilot.name + ': ' + 
                                    ($pilotData.$TotalProfit / 100) + ' Cr (was REVENUE, not profit) 0 Cr'"
                              chance="100"/>
                </do_if>
                <set_value name="global.$GT_Pilots.{$pilot}.$TotalProfit" exact="0"/>
                <set_value name="$pilotCount" operation="add"/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Reset ship profit statistics -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
            <do_all exact="global.$GT_Ships.keys.count" counter="$i">
              <set_value name="$ship" exact="global.$GT_Ships.keys.{$i}"/>
              <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
              
              <!-- Check if ship has inflated profit (TotalProfit exists and is non-zero) -->
              <do_if value="$shipData.$TotalProfit? and $shipData.$TotalProfit gt 0">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-ProfitMigration] Resetting ship ' + $ship.idcode + ': ' + 
                                    ($shipData.$TotalProfit / 100) + ' Cr (was REVENUE, not profit) 0 Cr'"
                              chance="100"/>
                </do_if>
                <set_value name="global.$GT_Ships.{$ship}.$TotalProfit" exact="0"/>
                <set_value name="$shipCount" operation="add"/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Reset global trade statistics -->
          <do_if value="global.$GT_TradeStats? and global.$GT_TradeStats.$TotalProfit?">
            <set_value name="$oldTotalProfit" exact="global.$GT_TradeStats.$TotalProfit"/>
            <set_value name="global.$GT_TradeStats.$TotalProfit" exact="0"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ProfitMigration] Reset global statistics: ' + $oldTotalProfit + ' Cr (was REVENUE) 0 Cr'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Reset lifetime profit tracking in logging system -->
          <do_if value="global.$GT_TradeLogging? and global.$GT_TradeLogging.$LifetimeProfit?">
            <set_value name="$lifetimeCount" exact="global.$GT_TradeLogging.$LifetimeProfit.keys.count"/>
            <do_if value="$lifetimeCount gt 0">
              <!-- Clear all lifetime profit entries -->
              <remove_value name="global.$GT_TradeLogging.$LifetimeProfit"/>
              <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-ProfitMigration] Reset lifetime profit tracking for ' + $lifetimeCount + ' ships'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Show summary notification to player -->
          <show_notification text="'GalaxyTrader MK3 - Profit Statistics Reset Complete\n\n' +
                                   'All profit statistics have been reset to 0.\n\n' +
                                   'Reset Summary:\n' +
                                   'â€¢ Pilots reset: ' + $pilotCount + '\n' +
                                   'â€¢ Ships reset: ' + $shipCount + '\n\n' +
                                   'From now on, statistics will accurately track PROFIT (Revenue - Purchase Cost).\n' +
                                   'Previous versions tracked REVENUE, which showed inflated numbers.\n\n' +
                                   'Trade counts and XP are preserved.'"
                             sound="notification_generic"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ProfitMigration] Manual profit statistics reset COMPLETE!' +
                              '\n  Pilots reset: ' + $pilotCount +
                              '\n  Ships reset: ' + $shipCount +
                              '\n  Statistics will now track actual PROFIT instead of REVENUE'"
                        chance="100"/>
          </do_if>
      </actions>
    </cue>
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Reporting" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Reporting System Initialization -->
    <cue name="SystemInit" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.SystemInit"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Reporting system initializing...'" chance="100"/>
        </do_if>
        
        <!-- Initialize reporting structures -->
        <set_value name="global.$GT_Reports" exact="table[]"/>
        <set_value name="global.$GT_Reports.$LastFleetReport" exact="0"/>
        <set_value name="global.$GT_Reports.$LastMarketReport" exact="0"/>
        <set_value name="global.$GT_Reports.$LastTrainingReport" exact="0"/>
        <!-- Report intervals now use global settings -->
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Reporting system initialized'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Event-driven Fleet Report (run on demand) -->
    <cue name="FleetPerformanceReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
        <check_value value="global.$GT_Ships?"/>
        <check_value value="global.$GT_Ships.keys.count gt 0"/>
      </conditions>
      <actions>
        <!-- Initialize reports table properties if missing -->
        <do_if value="not global.$GT_Reports.$LastFleetReport?">
          <set_value name="global.$GT_Reports.$LastFleetReport" exact="0"/>
          <set_value name="global.$GT_Reports.$LastMarketReport" exact="0"/>
          <set_value name="global.$GT_Reports.$LastTrainingReport" exact="0"/>
        </do_if>
        
        <!-- Get comprehensive report frequency from settings (0 = disabled) -->
        <set_value name="$reportFrequencyMinutes" exact="30"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Notifications? and global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency?">
          <set_value name="$reportFrequencyMinutes" exact="global.$GT_GlobalSettings.$Notifications.$ComprehensiveReportFrequency"/>
        </do_if>
        
        <!-- Check if report is due (skip if disabled) -->
        <do_if value="$reportFrequencyMinutes gt 0">
          <set_value name="$timeSinceReport" exact="player.age - global.$GT_Reports.$LastFleetReport"/>
          <set_value name="$reportIntervalSeconds" exact="$reportFrequencyMinutes * 60"/>
          
          <do_if value="$timeSinceReport ge $reportIntervalSeconds">
          
          <!-- Generate comprehensive fleet report -->
          <set_value name="$report" exact="'=== GALAXYTRADER MK3 FLEET PERFORMANCE REPORT ===\n\n'"/>
          
          <!-- Report timestamp -->
          <set_value name="$sessionTime" exact="player.age - global.$GT_SessionStats.$StartTime"/>
          <set_value name="$hours" exact="($sessionTime / 3600)i"/>
          <set_value name="$minutes" exact="(($sessionTime - ($hours * 3600)) / 60)i"/>
          <set_value name="$report" exact="$report + 'Session Duration: ' + $hours + ' hours, ' + $minutes + ' minutes\n'"/>
          <set_value name="$report" exact="$report + 'Report Generated: ' + player.age + '\n\n'"/>
          
          <!-- Fleet Overview -->
          <set_value name="$report" exact="$report + '=== FLEET OVERVIEW ===\n'"/>
          <set_value name="$activeShips" exact="0"/>
          <set_value name="$totalFleetProfit" exact="0"/>
          <set_value name="$totalFleetTrades" exact="0"/>
          
          <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
            <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
            <do_all exact="$shipKeys.count" counter="$i">
              <set_value name="$ship" exact="$shipKeys.{$i}"/>
              <do_if value="$ship.exists and $ship.isoperational">
                <set_value name="$activeShips" exact="$activeShips + 1"/>
                <do_if value="global.$GT_Ships.{$ship}.$TotalProfit?">
                  <set_value name="$totalFleetProfit" exact="$totalFleetProfit + global.$GT_Ships.{$ship}.$TotalProfit"/>
                </do_if>
                <do_if value="global.$GT_Ships.{$ship}.$TradesCompleted?">
                  <set_value name="$totalFleetTrades" exact="$totalFleetTrades + global.$GT_Ships.{$ship}.$TradesCompleted"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <set_value name="$report" exact="$report + 'Active Ships: ' + $activeShips + '\n'"/>
          <!-- Format total fleet profit -->
          <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedTotalProfit">
            <param name="number" value="$totalFleetProfit / 100"/>
            <param name="suffix" value="' Cr'"/>
          </run_actions>
          <set_value name="$report" exact="$report + 'Total Fleet Profit: ' + $formattedTotalProfit + '\n'"/>
          <set_value name="$report" exact="$report + 'Total Trades Completed: ' + $totalFleetTrades + '\n'"/>
          
          <do_if value="$totalFleetTrades gt 0">
            <set_value name="$avgProfitPerTrade" exact="$totalFleetProfit / $totalFleetTrades"/>
            <!-- Format average profit per trade -->
            <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedAvgProfit">
              <param name="number" value="$avgProfitPerTrade / 100"/>
              <param name="suffix" value="' Cr'"/>
            </run_actions>
            <set_value name="$report" exact="$report + 'Average Profit per Trade: ' + $formattedAvgProfit + '\n'"/>
          </do_if>
          
          <!-- Individual Ship Performance (Top Performers Only) -->
          <set_value name="$report" exact="$report + '\n=== INDIVIDUAL SHIP PERFORMANCE (TOP 15) ===\n'"/>
          
          <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
            <!-- Build list of ships with their profit for sorting -->
            <set_value name="$shipProfitList" exact="[]"/>
            <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
            
            <do_all exact="$shipKeys.count" counter="$i">
              <set_value name="$ship" exact="$shipKeys.{$i}"/>
              <do_if value="$ship.exists and $ship.isoperational">
                <set_value name="$shipProfit" exact="0"/>
                <do_if value="global.$GT_Ships.{$ship}.$TotalProfit?">
                  <set_value name="$shipProfit" exact="global.$GT_Ships.{$ship}.$TotalProfit"/>
                </do_if>
                <append_to_list name="$shipProfitList" exact="table[$Ship=$ship, $Profit=$shipProfit]"/>
              </do_if>
            </do_all>
            
            <!-- Sort ships by profit (bubble sort - simple for small lists) -->
            <do_if value="$shipProfitList.count gt 1">
              <do_all exact="$shipProfitList.count - 1" counter="$i">
                <do_all exact="$shipProfitList.count - $i" counter="$j">
                  <do_if value="$shipProfitList.{$j}.$Profit lt $shipProfitList.{$j+1}.$Profit">
                    <!-- Swap -->
                    <set_value name="$temp" exact="$shipProfitList.{$j}"/>
                    <set_value name="$shipProfitList.{$j}" exact="$shipProfitList.{$j+1}"/>
                    <set_value name="$shipProfitList.{$j+1}" exact="$temp"/>
                  </do_if>
                </do_all>
              </do_all>
            </do_if>
            
            <!-- Display top 5 ships (X4 logbook message limit: ~20-30 lines) -->
            <set_value name="$displayCount" exact="[$shipProfitList.count, 5].min"/>
            <set_value name="$report" exact="$report + 'Showing top ' + $displayCount + ' of ' + $shipProfitList.count + ' active ships\n'"/>
            
            <do_all exact="$displayCount" counter="$i">
              <set_value name="$ship" exact="$shipProfitList.{$i}.$Ship"/>
              <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
              
              <!-- Compact format: Ship name, profit, trades, status on one line -->
              <!-- Format ship profit -->
              <set_value name="$shipProfitValue" exact="0"/>
              <do_if value="$shipData.$TotalProfit?">
                <set_value name="$shipProfitValue" exact="$shipData.$TotalProfit / 100"/>
              </do_if>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$profitStr">
                <param name="number" value="$shipProfitValue"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              
              <set_value name="$tradesStr" exact="'0'"/>
              <do_if value="$shipData.$TradesCompleted?">
                <set_value name="$tradesStr" exact="$shipData.$TradesCompleted + ''"/>
              </do_if>
              
              <!-- Status: ACTIVE, TRAINING, or BLOCKED -->
              <set_value name="$status" exact="'ACTIVE'"/>
              <do_if value="global.$GT_Ships.{$ship}.$TrainingStarted?">
                <set_value name="$status" exact="'TRAINING'"/>
              </do_if>
              <do_elseif value="global.$GT_Ships.{$ship}.$XPBlocked?">
                <set_value name="$status" exact="'BLOCKED'"/>
              </do_elseif>
              
              <!-- Compact line: #1 ShipName: 1.2M Cr, 45 trades [ACTIVE] -->
              <set_value name="$report" exact="$report + '#' + $i + ' ' + $ship.idcode + ': ' + $profitStr + ', ' + $tradesStr + ' trades [' + $status + ']\n'"/>
            </do_all>
            
            <!-- Add note about remaining ships -->
            <do_if value="$shipProfitList.count gt 5">
              <set_value name="$remainingShips" exact="$shipProfitList.count - 5"/>
              <set_value name="$report" exact="$report + '\n+' + $remainingShips + ' more ships not shown\n'"/>
            </do_if>
          </do_if>
          
          <!-- XP Training System Status -->
          <set_value name="$report" exact="$report + '\n=== XP TRAINING SYSTEM STATUS ===\n'"/>
          
          <set_value name="$blockedCount" exact="0"/>
          <set_value name="$trainingCount" exact="0"/>
          
          <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
            <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
            <do_all exact="$shipKeys.count" counter="$i">
              <set_value name="$ship" exact="$shipKeys.{$i}"/>
              <do_if value="global.$GT_Ships.{$ship}.$XPBlocked?">
                <set_value name="$blockedCount" exact="$blockedCount + 1"/>
              </do_if>
              <do_if value="global.$GT_Ships.{$ship}.$TrainingStarted?">
                <set_value name="$trainingCount" exact="$trainingCount + 1"/>
              </do_if>
            </do_all>
          </do_if>
          
          <set_value name="$report" exact="$report + 'Ships Blocked (Need Training): ' + $blockedCount + '\n'"/>
          <set_value name="$report" exact="$report + 'Ships Currently Training: ' + $trainingCount + '\n'"/>
          <!-- Build training levels list -->
          <set_value name="$trainingLevels" exact="''"/>
          <do_if value="global.$GT_Config.$Training.$RequiredLevels?">
            <do_all exact="global.$GT_Config.$Training.$RequiredLevels.count" counter="$i">
              <do_if value="$i gt 1">
                <set_value name="$trainingLevels" exact="$trainingLevels + ', '"/>
              </do_if>
              <set_value name="$trainingLevels" exact="$trainingLevels + global.$GT_Config.$Training.$RequiredLevels.{$i}"/>
            </do_all>
          </do_if>
          <set_value name="$report" exact="$report + 'Training Required Levels: ' + $trainingLevels + '\n'"/>
          
          <!-- Market Intelligence Summary -->
          <do_if value="global.$GT_Config.$Market.$TrendAnalysis? and global.$GT_MarketOpportunities?">
            <set_value name="$report" exact="$report + '\n=== MARKET INTELLIGENCE SUMMARY ===\n'"/>
            <set_value name="$report" exact="$report + 'Market Opportunities Found: ' + global.$GT_MarketOpportunities.count + '\n'"/>
            
            <do_if value="global.$GT_MarketOpportunities.count gt 0">
              <set_value name="$topOpp" exact="global.$GT_MarketOpportunities.{1}"/>
              <set_value name="$report" exact="$report + 'Best Opportunity: ' + $topOpp.$Type + ' ' + $topOpp.$Ware.name + ' (' + $topOpp.$Score + '% potential)\n'"/>
            </do_if>
          </do_if>
          
          <!-- Fleet Coordination Status -->
          <do_if value="global.$GT_Config.$Fleet.$Enabled? and global.$GT_FleetRoutes?">
            <set_value name="$report" exact="$report + '\n=== FLEET COORDINATION STATUS ===\n'"/>
            <set_value name="$report" exact="$report + 'Active Route Reservations: ' + global.$GT_FleetRoutes.$RouteReservations.keys.count + '\n'"/>
            <set_value name="$report" exact="$report + 'Max Ships per Route: ' + global.$GT_Config.$Fleet.$MaxShipsPerRoute + '\n'"/>
          </do_if>
          
          <!-- Configuration Summary -->
          <set_value name="$report" exact="$report + '\n=== CONFIGURATION SUMMARY ===\n'"/>
          <!-- Format min absolute profit -->
          <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedMinProfit">
            <param name="number" value="global.$GT_Config.$Trading.$MinAbsoluteProfit / 100"/>
            <param name="suffix" value="' Cr'"/>
          </run_actions>
          <set_value name="$report" exact="$report + 'Min Absolute Profit: ' + $formattedMinProfit + '\n'"/>
          <set_value name="$report" exact="$report + 'XP System: Enabled\n'"/>
          <set_value name="$report" exact="$report + 'Fleet Coordination: ' + if global.$GT_Config.$Fleet.$Enabled then 'Enabled' else 'Disabled' + '\n'"/>
          
          <!-- Write to player logbook -->
          <!-- Write logbook entry - don't check global settings (comprehensive reports should always write) -->
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$report"/>
            <param name="Category" value="'general'"/>
            <param name="Title" value="'GalaxyTrader MK3 Fleet Report'"/>
            <!-- IMPORTANT: Do NOT attach to a specific ship object; otherwise it appears in that ship's logbook.
                 Leaving Object=null writes to the player logbook only (vanilla pattern: write_to_logbook without object=...). -->
            <param name="Object" value="null"/>
            <param name="CheckGlobalSettings" value="false"/>
          </run_actions>
          
          <!-- Update timestamp -->
          <set_value name="global.$GT_Reports.$LastFleetReport" exact="player.age"/>
          
          <!-- Debug: Log report content to game log for debugging -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Fleet performance report generated:\n' + $report" chance="100"/>
          </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Trade Analytics Report -->
    <cue name="TradeAnalyticsReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$report" exact="'=== GALAXYTRADER MK3 TRADE ANALYTICS ===\n\n'"/>
        
        <!-- Trade Volume Analysis -->
        <set_value name="$report" exact="$report + '=== TRADE VOLUME ANALYSIS ===\n'"/>
        
        <!-- Collect trade data by ware -->
        <set_value name="$wareStats" exact="table[]"/>
        
        <!-- This would normally aggregate trade data - simplified for now -->
        <do_if value="global.$GT_FleetRoutes? and global.$GT_FleetRoutes.$RouteReservations?">
          <set_value name="$report" exact="$report + 'Total Unique Trade Routes: ' + global.$GT_FleetRoutes.$RouteReservations.keys.count + '\n'"/>
        </do_if>
        <do_else>
          <set_value name="$report" exact="$report + 'Total Unique Trade Routes: N/A\n'"/>
        </do_else>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="$cacheActive" exact="if global.$GT_SearchSemaphore.$CacheActive? then global.$GT_SearchSemaphore.$CacheActive else 0"/>
          <set_value name="$liveActive" exact="if global.$GT_SearchSemaphore.$LiveActive? then global.$GT_SearchSemaphore.$LiveActive else 0"/>
          <set_value name="$cacheQueued" exact="if global.$GT_SearchSemaphore.$CacheQueue? then global.$GT_SearchSemaphore.$CacheQueue.count else 0"/>
          <set_value name="$liveQueued" exact="if global.$GT_SearchSemaphore.$LiveQueued? then global.$GT_SearchSemaphore.$LiveQueued.keys.count else 0"/>
          <set_value name="$report" exact="$report + 'Active Trading Ships: ' + ($cacheActive + $liveActive + $cacheQueued + $liveQueued) + '\n'"/>
        </do_if>
        <do_else>
          <set_value name="$report" exact="$report + 'Active Trading Ships: N/A\n'"/>
        </do_else>
        
        <!-- Profitability Analysis -->
        <set_value name="$report" exact="$report + '\n=== PROFITABILITY ANALYSIS ===\n'"/>
        
        <set_value name="$mostProfitableShip" exact="null"/>
        <set_value name="$highestProfit" exact="0"/>
        
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <set_value name="$shipProfit" exact="if global.$GT_Ships.{$ship}.$TotalProfit? then global.$GT_Ships.{$ship}.$TotalProfit else 0"/>
            <do_if value="$shipProfit gt $highestProfit">
              <set_value name="$highestProfit" exact="$shipProfit"/>
              <set_value name="$mostProfitableShip" exact="$ship"/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$mostProfitableShip">
          <!-- Format highest profit -->
          <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedHighestProfit">
            <param name="number" value="$highestProfit / 100"/>
            <param name="suffix" value="' Cr'"/>
          </run_actions>
          <set_value name="$report" exact="$report + 'Most Profitable Ship: ' + $mostProfitableShip.knownname + ' (' + $formattedHighestProfit + ')\n'"/>
        </do_if>
        
        <!-- Return report -->
        <set_value name="global.$GT_TradeAnalyticsReport" exact="$report"/>
      </actions>
    </cue>
    
    <!-- Event-driven Training Progress Report (triggered by training events) -->
    <cue name="TrainingProgressReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
        <check_value value="true" comment="XP system is always enabled"/>
      </conditions>
      <actions>
        <!-- Check for ships in training -->
        <set_value name="$shipsInTraining" exact="[]"/>
        
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <do_if value="global.$GT_Ships.{$ship}.$TrainingStarted?">
              <append_to_list name="$shipsInTraining" exact="$ship"/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Generate report if ships are training -->
        <do_if value="$shipsInTraining.count gt 0">
          <set_value name="$report" exact="'=== TRAINING PROGRESS UPDATE ===\n\n'"/>
          <set_value name="$report" exact="$report + 'Ships in training: ' + $shipsInTraining.count + '\n\n'"/>
          
          <!-- Show max 5 ships (X4 logbook line limit) -->
          <set_value name="$displayCount" exact="[$shipsInTraining.count, 5].min"/>
          
          <do_all exact="$displayCount" counter="$i">
            <set_value name="$ship" exact="$shipsInTraining.{$i}"/>
            <set_value name="$trainingData" exact="global.$GT_Ships.{$ship}"/>
            
            <set_value name="$elapsed" exact="player.age - $trainingData.$TrainingStarted"/>
            <set_value name="$remaining" exact="[$trainingData.$TrainingDuration - $elapsed, 0s].max"/>
            <set_value name="$progress" exact="($elapsed * 100) / $trainingData.$TrainingDuration"/>
            
            <!-- Compact format: Ship: 45% done, 12 min left -->
            <set_value name="$report" exact="$report + $ship.idcode + ': ' + $progress + '% done, ' + ($remaining / 60)i + ' min left\n'"/>
          </do_all>
          
          <!-- Show remaining count -->
          <do_if value="$shipsInTraining.count gt 5">
            <set_value name="$report" exact="$report + '\n+' + ($shipsInTraining.count - 5) + ' more ships not shown\n'"/>
          </do_if>
          
          <!-- Write to player logbook -->
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$report"/>
            <param name="Category" value="'upkeep'"/>
            <param name="Title" value="'GalaxyTrader MK3 Training Progress'"/>
            <!-- Player logbook only (do not attach to player ship logbook) -->
            <param name="Object" value="null"/>
          </run_actions>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Training progress report generated'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Trigger training progress report on training events -->
    <cue name="TrainingProgressTrigger" instantiate="true">
      <conditions>
        <check_any>
          <event_object_signalled object="player.galaxy" param="'GT_Training_Needed'"/>
          <event_object_signalled object="player.galaxy" param="'GT_Training_Check_Result'"/>
        </check_any>
      </conditions>
      <actions>
        <signal_cue cue="TrainingProgressReport"/>
      </actions>
    </cue>
    
    <!-- On-Demand Report Generation -->
    <cue name="GenerateOnDemandReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$reportType" exact="event.param"/>
        
        <do_if value="$reportType == 'fleet'">
          <signal_cue cue="FleetPerformanceReport"/>
        </do_if>
        <do_elseif value="$reportType == 'market'">
          <signal_cue cue="md.GT_MarketIntelligence.GenerateMarketReport"/>
        </do_elseif>
        <do_elseif value="$reportType == 'territory'">
          <signal_cue cue="md.GT_TerritoryManagement.GenerateTerritoryReport"/>
        </do_elseif>
        <do_elseif value="$reportType == 'trade'">
          <signal_cue cue="TradeAnalyticsReport"/>
        </do_elseif>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] On-demand ' + $reportType + ' report requested'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Periodic Notification Report (Simple Popup) -->
    <!-- Triggered from trade completion when ProfitReports enabled and SimpleReportFrequency interval elapsed -->
    <cue name="GeneratePeriodicReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Respect ProfitReports setting (defense in depth) - return not allowed inside do_if, so wrap in positive check -->
        <do_if value="global.$GT_Config? and global.$GT_Config.$Notifications? and global.$GT_Config.$Notifications.$ProfitReports">
        <!-- Use @ operator to safely access keys.count -->
        <set_value name="$shipsKeysCount" exact="@global.$GT_Ships.keys.count"/>
        <do_if value="$shipsKeysCount? and $shipsKeysCount gt 0">
          <set_value name="$totalProfit" exact="0Cr"/>
          <set_value name="$totalTrades" exact="0"/>
          
          <!-- Calculate totals -->
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
            <do_if value="$shipData.$TotalProfit?">
              <set_value name="$totalProfit" exact="$totalProfit + $shipData.$TotalProfit"/>
            </do_if>
            <do_if value="$shipData.$TradesCompleted?">
              <set_value name="$totalTrades" exact="$totalTrades + $shipData.$TradesCompleted"/>
            </do_if>
          </do_all>
          
          <!-- Generate report message -->
          <set_value name="$message" exact="'GalaxyTrader MK3 Fleet Report:\n'"/>
          <set_value name="$message" exact="$message + 'Active Ships: ' + global.$GT_Ships.keys.count + '\n'"/>
          <!-- Format total profit with thousand separators and M suffix -->
          <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedTotalProfit">
            <param name="number" value="$totalProfit / 100"/>
            <param name="suffix" value="' Cr'"/>
          </run_actions>
          <set_value name="$message" exact="$message + 'Total Profit: ' + $formattedTotalProfit + '\n'"/>
          <set_value name="$message" exact="$message + 'Trades Completed: ' + $totalTrades"/>
          
          <!-- Show notification -->
          <show_notification text="$message" timeout="10s"/>
          
          <!-- Debug: Log report to game log -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Periodic fleet report:\n' + $message" chance="100"/>
          </do_if>
        </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Error Report Generator -->
    <cue name="GenerateErrorReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$errorType" exact="event.param.type"/>
        <set_value name="$errorData" exact="event.param.data"/>
        
        <set_value name="$report" exact="'GALAXYTRADER MK3 ERROR REPORT\n\n'"/>
        <set_value name="$report" exact="$report + 'Error Type: ' + $errorType + '\n'"/>
        <set_value name="$report" exact="$report + 'Timestamp: ' + player.age + '\n\n'"/>
        
        <do_if value="$errorType == 'ship_stuck'">
          <set_value name="$report" exact="$report + 'Ship: ' + $errorData.$Ship.knownname + '\n'"/>
          <set_value name="$report" exact="$report + 'Location: ' + $errorData.$Ship.sector.knownname + '\n'"/>
          <set_value name="$report" exact="$report + 'Last Order: ' + $errorData.$LastOrder + '\n'"/>
          <set_value name="$report" exact="$report + '\nRecommended Action: Check ship status and manually intervene if necessary.\n'"/>
        </do_if>
        <do_elseif value="$errorType == 'trade_failed'">
          <set_value name="$report" exact="$report + 'Ship: ' + $errorData.$Ship.knownname + '\n'"/>
          <set_value name="$report" exact="$report + 'Trade Route: ' + $errorData.$Route + '\n'"/>
          <set_value name="$report" exact="$report + 'Reason: ' + $errorData.$Reason + '\n'"/>
        </do_elseif>
        
        <!-- Write to logbook with high priority -->
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="$report"/>
          <param name="Category" value="'alerts'"/>
          <param name="Title" value="'GalaxyTrader MK3 Error'"/>
          <param name="Object" value="$errorData.$Ship"/>
          <param name="Interaction" value="'showonmap'"/>
        </run_actions>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Error report generated: ' + $errorType" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Summary Dashboard -->
    <cue name="GenerateDashboard" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$dashboard" exact="'==========================================\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '     GALAXYTRADER MK3 DASHBOARD\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '==========================================\n\n'"/>
        
        <!-- Quick Stats -->
        <set_value name="$activeShips" exact="0"/>
        <set_value name="$totalProfit" exact="0"/>
        <set_value name="$shipsTraining" exact="0"/>
        <set_value name="$shipsBlocked" exact="0"/>
        
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="global.$GT_Ships.keys.list"/>
          <do_all exact="$shipKeys.count" counter="$i">
            <set_value name="$ship" exact="$shipKeys.{$i}"/>
            <do_if value="$ship.exists and $ship.isoperational">
              <set_value name="$activeShips" exact="$activeShips + 1"/>
              <set_value name="$shipProfit" exact="if global.$GT_Ships.{$ship}.$TotalProfit? then global.$GT_Ships.{$ship}.$TotalProfit else 0"/>
              <set_value name="$totalProfit" exact="$totalProfit + $shipProfit"/>
              
              <do_if value="global.$GT_Ships.{$ship}.$TrainingStarted?">
                <set_value name="$shipsTraining" exact="$shipsTraining + 1"/>
              </do_if>
              <do_if value="global.$GT_Ships.{$ship}.$XPBlocked?">
                <set_value name="$shipsBlocked" exact="$shipsBlocked + 1"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        
        <set_value name="$dashboard" exact="$dashboard + 'Quick Stats:\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - Active Ships: ' + $activeShips + '\n'"/>
        <!-- Format total profit for dashboard -->
        <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedDashboardProfit">
          <param name="number" value="$totalProfit / 100"/>
          <param name="suffix" value="' Cr'"/>
        </run_actions>
        <set_value name="$dashboard" exact="$dashboard + '  - Total Profit: ' + $formattedDashboardProfit + '\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - Ships Training: ' + $shipsTraining + '\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - Ships Blocked: ' + $shipsBlocked + '\n\n'"/>
        
        <!-- System Status -->
        <set_value name="$dashboard" exact="$dashboard + 'System Status:\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - XP System: Enabled\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - Fleet Coord: ' + if global.$GT_Config.$Fleet.$Enabled then 'Enabled' else 'Disabled' + '\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - Market Intel: ' + if global.$GT_Config.$Market.$TrendAnalysis then 'Enabled' else 'Disabled' + '\n'"/>
        <set_value name="$dashboard" exact="$dashboard + '  - Territory Mgmt: ' + if global.$GT_Config.$Fleet.$TerritoryManagement then 'Enabled' else 'Disabled' + '\n'"/>
        
        <!-- Show notification -->
        <show_notification text="$dashboard" timeout="15s" priority="5"/>
        
        <!-- Also write to player logbook for permanent record -->
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="$dashboard"/>
          <param name="Category" value="'tips'"/>
          <param name="Title" value="'GalaxyTrader MK3 Dashboard'"/>
          <!-- Player logbook only (do not attach to player ship logbook) -->
          <param name="Object" value="null"/>
        </run_actions>
      </actions>
    </cue>
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Ship_Management" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    
    <!-- ========================================================================= -->
    <!-- SHIP MANAGEMENT LIBRARIES -->
    <!-- ========================================================================= -->
    
    <!-- Ship Registration and Initialization -->
    <library name="Register_Ship" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to register"/>
        <param name="pilot" comment="Ship's pilot"/>
        <param name="config" comment="Ship configuration"/>
      </params>
      <actions>
        
        <!-- Register ship if not already registered -->
        <do_if value="not global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
          <set_value name="global.$GT_Ships.{$ship}.$RegisterTime" exact="player.age"/>
          <set_value name="global.$GT_Ships.{$ship}.$Config" exact="$config"/>
          <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
          <set_value name="global.$GT_Ships.{$ship}.$Status" exact="'active'"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Registered ship: ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Update existing ship registration -->
          <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
        </do_else>
        
        <!-- Always store/update pilot reference in ship data (required for info menu) -->
        <do_if value="$pilot">
          <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$pilot"/>
        </do_if>
        
        <!-- Register pilot if provided -->
        <do_if value="$pilot">
          <run_actions ref="Register_Pilot">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Apply ship modifications immediately upon registration -->
          <run_actions ref="Handle_Pilot_Ship_Assignment">
            <param name="ship" value="$ship"/>
            <param name="new_pilot" value="$pilot"/>
            <param name="old_pilot" value="null"/>
          </run_actions>
        </do_if>
      </actions>
    </library>
    
    <!-- Strip GT Name Formatting from Ship Names (Language-Independent) -->
    <!-- NOTE: This library now just forwards to Lua and returns original name -->
    <!-- The CALLER must wait for the Lua response via the Strip_Name_Response cue -->
    <!-- This is because MD libraries cannot wait/be asynchronous -->
    <library name="Strip_GT_Name_Formatting" purpose="run_actions">
      <params>
        <param name="shipName" comment="Current ship name that might have GT formatting"/>
      </params>
      <actions>
        <!-- Request Lua to strip the name (async) -->
        <raise_lua_event name="'GT_StringUtils.StripShipName'" param="$shipName"/>
        
        <!-- Return original name immediately - caller must wait for Lua response -->
        <return value="$shipName"/>
      </actions>
    </library>
    
    <!-- Extract Base Name from macro.name (Remove Sentinel/Vanguard Variants) -->
    <library name="Extract_Base_Ship_Name" purpose="run_actions">
      <params>
        <param name="macroName" comment="Ship macro.name (e.g., 'Mercury Sentinel')"/>
      </params>
      <actions>
        <set_value name="$baseName" exact="$macroName"/>
        
        <!-- Remove Sentinel variant: ' ' + {20111,1201} -->
        <substitute_text source="$baseName" text="$baseName">
          <replace string="' ' + {20111,1201}" with="''"/>
        </substitute_text>
        
        <!-- Remove Vanguard variant: ' ' + {20111,1101} -->
        <substitute_text source="$baseName" text="$baseName">
          <replace string="' ' + {20111,1101}" with="''"/>
        </substitute_text>
        
        <return value="$baseName"/>
      </actions>
    </library>

    <!-- Update GT pilot display name to "(T:Level) PilotName" -->
    <library name="Update_Pilot_Name_Tag" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot entity to rename"/>
        <param name="level" default="null" comment="Optional explicit level; falls back to pilot registry"/>
      </params>
      <actions>
        <do_if value="not $pilot? or not $pilot.exists">
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag skipped: invalid pilot object'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        <do_if value="not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}?">
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag skipped: pilot not in GT registry (' + $pilot.name + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        <!-- Global toggle: allow users to disable GT pilot renaming independently from ship naming -->
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled? and not @global.$GT_GlobalSettings.$ShipNaming.$PilotRenamingEnabled">
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag skipped: PilotRenamingEnabled=false for ' + $pilot.name" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and @global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly">
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag skipped: vanilla XP mode active for ' + $pilot.name" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>

        <set_value name="$pilotLevel" exact="null"/>
        <set_value name="$levelSource" exact="'none'"/>
        <do_if value="$level? and $level != null">
          <set_value name="$pilotLevel" exact="$level"/>
          <set_value name="$levelSource" exact="'param_level'"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots.{$pilot}.$Level? and global.$GT_Pilots.{$pilot}.$Level != null">
          <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
          <set_value name="$levelSource" exact="'registry_level'"/>
        </do_elseif>
        <do_elseif value="global.$GT_Pilots.{$pilot}.$XP? and global.$GT_Pilots.{$pilot}.$XP != null">
          <run_actions ref="Calculate_Skill_Level_From_XP" result="$pilotLevel">
            <param name="pilot" value="$pilot"/>
            <param name="xp" value="global.$GT_Pilots.{$pilot}.$XP"/>
          </run_actions>
          <set_value name="$levelSource" exact="'derived_from_xp'"/>
        </do_elseif>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag level resolve: pilot=' + $pilot.name + ', source=' + $levelSource + ', level=' + (if $pilotLevel? then $pilotLevel else 'null') + ', regLevel=' + (if global.$GT_Pilots.{$pilot}.$Level? then global.$GT_Pilots.{$pilot}.$Level else 'null') + ', regXP=' + (if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 'null')" chance="100"/>
        </do_if>
        <!-- Never write a synthetic fallback level. If we cannot resolve a valid GT level,
             skip renaming to avoid incorrect tags like "(T:1)" or "(T:null)". -->
        <do_if value="not $pilotLevel? or $pilotLevel == null or $pilotLevel lt 1">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag skipped: unresolved level for pilot ' + $pilot.name" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        <!-- IMPORTANT: do NOT persist $pilotLevel to the registry when the
             caller passed it as an explicit override (source='param_level').
             Callers use the override as a display hint, e.g. "anticipated"
             rank for an XP-blocked pilot, or the locked-in academy target
             before the course completes. Mutating $Level here would silently
             promote the pilot the moment they're sent to the Trading Academy
             (BlockedLevel=7 â†’ tag becomes "(T:7)" â†’ $Level := 7), which broke
             the academy "level rises only after course completion" invariant.
             We still re-sync $Level when the level was derived from the
             registry/XP itself, since that is a no-op or a raise-only catch-up. -->
        <do_if value="global.$GT_Pilots.{$pilot}? and $levelSource != 'param_level'">
          <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$pilotLevel"/>
        </do_if>

        <!-- Preserve and reuse untagged base pilot name -->
        <set_value name="$basePilotName" exact="null"/>
        <set_value name="$baseNameSource" exact="'none'"/>
        <do_if value="global.$GT_Pilots.{$pilot}.$OriginalPilotName? and global.$GT_Pilots.{$pilot}.$OriginalPilotName != ''">
          <set_value name="$basePilotName" exact="global.$GT_Pilots.{$pilot}.$OriginalPilotName"/>
          <set_value name="$baseNameSource" exact="'original_pilot_name'"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots.{$pilot}.$PilotName? and global.$GT_Pilots.{$pilot}.$PilotName != ''">
          <set_value name="$basePilotName" exact="global.$GT_Pilots.{$pilot}.$PilotName"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$OriginalPilotName" exact="$basePilotName"/>
          <set_value name="$baseNameSource" exact="'pilot_name_backfill'"/>
        </do_elseif>
        <do_else>
          <set_value name="$basePilotName" exact="$pilot.name"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$OriginalPilotName" exact="$basePilotName"/>
          <set_value name="$baseNameSource" exact="'current_name_backfill'"/>
        </do_else>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag base resolve: pilot=' + $pilot.name + ', source=' + $baseNameSource + ', baseName=' + $basePilotName" chance="100"/>
        </do_if>

        <set_value name="$newPilotName" exact="'(T:' + $pilotLevel + ') ' + $basePilotName"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag raw-check: pilotId=' + (if $pilot.idcode? then $pilot.idcode else 'NONE') + ', currentRaw=' + $pilot.name + ', expectedTagged=' + $newPilotName + ', level=' + $pilotLevel + ', source=' + $baseNameSource" chance="100"/>
        </do_if>
        <do_if value="$pilot.name != $newPilotName">
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag rename: pilotId=' + (if $pilot.idcode? then $pilot.idcode else 'NONE') + ', old=' + $pilot.name + ' -> new=' + $newPilotName" chance="100"/>
          </do_if>
          <set_object_name object="$pilot" name="$newPilotName"/>
        </do_if>
        <do_else>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Pilot_Name_Tag no-op: already tagged correctly (' + $pilot.name + ')'" chance="100"/>
          </do_if>
        </do_else>

        <return value="true"/>
      </actions>
    </library>
    
    <!-- Pilot Registration and XP Management -->
    <library name="Register_Pilot" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to register"/>
        <param name="ship" comment="Associated ship"/>
      </params>
      <actions>
        <do_if value="not $pilot? or not $pilot.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Register_Pilot skipped: missing pilot for ship=' + (if $ship? then $ship.idcode else 'NONE')" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>

        <!-- CRITICAL: Store original ship name BEFORE renaming -->
        <!-- Initialize ship registry if needed -->
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        
        <!-- Store original ship name in ship registry (per ship, not per pilot) -->
        <!-- Only set if not already stored (preserve user's custom rename via MK3 rename functionality) -->
        <!-- MUST be done BEFORE Update_Pilot_Ship_Name renames the ship -->
        <do_if value="not global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{$ship}.$OriginalShipName?">
          <set_value name="$cleanedName" exact="null"/>
          <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName? and global.$GT_Pilots.{$pilot}.$OriginalShipName != ''">
            <set_value name="$cleanedName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
          </do_if>
          <do_else>
            <!-- Never derive base name from ship.knownname here; it may already contain GT formatting. -->
            <set_value name="$cleanedName" exact="@$ship.macro.name"/>
          </do_else>
          <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$cleanedName"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Stored original ship name BEFORE renaming (deterministic source): ' + $cleanedName + ' (ship=' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Use extracted initialization library -->
        <!-- This handles: new pilots, existing active pilots, and reactivated paused pilots -->
        <run_actions ref="Initialize_Pilot_Data" result="$wasNewPilot">
          <param name="pilot" value="$pilot"/>
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Check if pilot was paused and is being reactivated -->
        <set_value name="$wasPaused" exact="false"/>
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <do_if value="global.$GT_Pilots.{$pilot}.$ResumedTime? and (player.age - global.$GT_Pilots.{$pilot}.$ResumedTime) lt 1s">
            <set_value name="$wasPaused" exact="true"/>
          </do_if>
        </do_if>
        
        <set_value name="$nameAlreadyUpdatedInBranch" exact="false"/>
        <do_if value="$wasNewPilot">
          <!-- New pilot was initialized - update ship name with initial state -->
          <run_actions ref="Update_Pilot_Ship_Name" result="$newPilotNameResult">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="forceUpdate" value="true"/>
          </run_actions>
          <set_value name="$nameAlreadyUpdatedInBranch" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Registered NEW pilot: ' + $pilot.name + ' - name update result: ' + $newPilotNameResult" chance="100"/>
          </do_if>
          
          <!-- Send logbook message when new pilot is registered -->
          <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
          <set_value name="$logbookMessage" exact="{77000,3214}.[player.name]"/>
          
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$logbookMessage"/>
            <param name="Category" value="'general'"/>
            <param name="Title" value="'New Pilot: ' + $pilot.name"/>
            <param name="Object" value="$ship"/>
            <param name="Interaction" value="'showonmap'"/>
          </run_actions>
        </do_if>
        <do_elseif value="$wasPaused">
          <!-- Pilot was reactivated - update ship name with their preserved XP/level -->
          <run_actions ref="Update_Pilot_Ship_Name" result="$reactivatedNameResult">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="forceUpdate" value="true"/>
          </run_actions>
          <set_value name="$nameAlreadyUpdatedInBranch" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Reactivated pilot: ' + $pilot.name + ' (XP: ' + (if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 0) + ', Level: ' + (if global.$GT_Pilots.{$pilot}.$Level? then global.$GT_Pilots.{$pilot}.$Level else 1) + ') - name update result: ' + $reactivatedNameResult" chance="100"/>
          </do_if>
          
          <!-- Note: Transfer message will be added later if ship swap is detected -->
          <!-- We'll add the "back from holiday" message after ship comparison -->
        </do_elseif>
        <do_else>
          <!-- Existing active pilot on same ship:
               still force a name refresh so commander GT reassignment immediately restores GT naming
               even when pilot status did not transition through 'paused'. -->
          <run_actions ref="Update_Pilot_Ship_Name" result="$refreshNameResult">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="forceUpdate" value="true"/>
          </run_actions>
          <set_value name="$nameAlreadyUpdatedInBranch" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Refreshed active pilot registration: ' + $pilot.name + ' on ' + $ship.idcode + ' - name update result: ' + $refreshNameResult" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Ensure all fields exist (defensive programming) -->
        <run_actions ref="Ensure_Pilot_Fields">
          <param name="pilot" value="$pilot"/>
        </run_actions>
        <run_actions ref="Sync_Stable_Identity_Index">
          <param name="pilot" value="$pilot"/>
        </run_actions>
        
        <!-- Update ship association -->
        <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
        
        <!-- Initialize ship registry if needed -->
        <do_if value="not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        
        <!-- Ensure ship is fully registered in global.$GT_Ships -->
        <!-- This is critical for trade search to work properly -->
        <!-- Note: Ship registry entry was already created above (before renaming) -->
        <do_if value="not global.$GT_Ships.{$ship}.$RegisterTime?">
          <set_value name="global.$GT_Ships.{$ship}.$RegisterTime" exact="player.age"/>
          <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
          <set_value name="global.$GT_Ships.{$ship}.$Status" exact="'active'"/>
          <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$pilot"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Registered ship in Register_Pilot: ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Ship already registered - update pilot reference and last update time -->
          <set_value name="global.$GT_Ships.{$ship}.$Pilot" exact="$pilot"/>
          <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
        </do_else>
        
        <!-- Original ship name already stored above (before renaming) -->
        
        <!-- Store ship ID for reliable swap detection (ship objects can become invalid) -->
        <!-- Use both ship object AND ship ID for comparison - ID is more reliable for persistence -->
        <set_value name="$currentShipID" exact="$ship.idcode"/>
        <set_value name="$previousShipID" exact="null"/>
        <set_value name="$oldShip" exact="null"/>
        <do_if value="global.$GT_Pilots.{$pilot}.$ShipID?">
          <set_value name="$previousShipID" exact="global.$GT_Pilots.{$pilot}.$ShipID"/>
          <!-- Try to get old ship object if it still exists -->
          <do_if value="global.$GT_Pilots.{$pilot}.$Ship? and global.$GT_Pilots.{$pilot}.$Ship.exists">
            <set_value name="$oldShip" exact="global.$GT_Pilots.{$pilot}.$Ship"/>
            <!-- Verify ID matches (ship object might have been reassigned) -->
            <do_if value="$oldShip.idcode != $previousShipID">
              <set_value name="$oldShip" exact="null"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Determine if this is a new ship assignment or resuming on same ship -->
        <set_value name="$isNewShip" exact="false"/>
        
        <do_if value="global.$GT_Pilots.{$pilot}.$Ship? and $previousShipID?">
          <!-- Pilot already has a registered ship - compare ship IDs first (most reliable) -->
          <do_if value="$currentShipID == $previousShipID">
            <!-- Same ship ID - pilot resuming on same ship -->
            <!-- Also update ship object in case it was invalidated -->
            <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Pilot ' + $pilot.name + ' resuming on SAME ship: ' + $ship.knownname + ' (ID: ' + $currentShipID + ')'" chance="100"/>
            </do_if>
            
            <!-- Send logbook message when pilot returns from holiday on same ship -->
            <!-- Only send message if ship has GT default order active (not just when trade orders change) -->
            <!-- Skip holiday return copy when this reactivation followed an eject rescue. -->
            <do_if value="$wasPaused and not (global.$GT_Pilots.{$pilot}.$ResumedFromEject? and global.$GT_Pilots.{$pilot}.$ResumedFromEject)">
              <set_value name="$hasGTOrder" exact="false"/>
              <do_if value="$ship.defaultorder?">
                <do_if value="global.$GT_ProtectedOrderIDs? and $ship.defaultorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}">
                  <set_value name="$hasGTOrder" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$hasGTOrder">
                <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
                <set_value name="$logbookMessage" exact="{77000,3216}.[player.name, $ship.knownname]"/>
                
                <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                  <param name="Message" value="$logbookMessage"/>
                  <param name="Category" value="'general'"/>
                  <param name="Title" value="'Pilot Return: ' + $pilot.name"/>
                  <param name="Object" value="$ship"/>
                  <param name="Interaction" value="'showonmap'"/>
                </run_actions>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Different ship ID - pilot reassigned to NEW ship! -->
            <set_value name="$isNewShip" exact="true"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$currentShipID"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Pilot ' + $pilot.name + ' reassigned to NEW ship: ' + $ship.knownname + ' (ID: ' + $currentShipID + ', previous ID: ' + $previousShipID + ')'" chance="100"/>
            </do_if>
            
            <!-- ======================================= -->
            <!-- OLD SHIP CLEANUP (Pilot Transfer)      -->
            <!-- ======================================= -->
            <!-- Handle cleanup of old ship when pilot is transferred -->
            <do_if value="$oldShip and $oldShip.exists">
              <set_value name="$oldShipHasGTOrder" exact="false"/>
              <set_value name="$oldShipHasPilot" exact="false"/>
              
              <!-- Check if old ship has GT order -->
              <do_if value="$oldShip.defaultorder?">
                <do_if value="global.$GT_ProtectedOrderIDs? and $oldShip.defaultorder? and global.$GT_ProtectedOrderIDs.indexof.{@$oldShip.defaultorder.id}">
                  <set_value name="$oldShipHasGTOrder" exact="true"/>
                </do_if>
              </do_if>
              
              <!-- Check if old ship has a pilot -->
              <do_if value="$oldShip.pilot?">
                <set_value name="$oldShipHasPilot" exact="true"/>
              </do_if>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-ShipMgmt] Old ship cleanup check: ' + $oldShip.knownname + ' (GT order: ' + $oldShipHasGTOrder + ', Pilot: ' + $oldShipHasPilot + ')'" chance="100"/>
              </do_if>
              
              <!-- Case: Old ship has GT order but NO pilot -->
              <!-- The old ship's GT order will detect missing pilot at its next restart point -->
              <!-- No cleanup needed from transferring ship's perspective -->
              <do_if value="$oldShipHasGTOrder and not $oldShipHasPilot">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-ShipMgmt] Old ship ' + $oldShip.knownname + ' has GT order but no pilot - cleanup handled by that ship\'s GT order'" chance="100"/>
                </do_if>
              </do_if>
              
              <!-- Case: Old ship has NO GT order -->
              <!-- Restore original name if stored in ship registry -->
              <do_elseif value="not $oldShipHasGTOrder">
                <set_value name="$oldShipOriginalName" exact="null"/>
                <do_if value="global.$GT_Ships.{$oldShip}? and global.$GT_Ships.{$oldShip}.$OriginalShipName?">
                  <set_value name="$oldShipOriginalName" exact="global.$GT_Ships.{$oldShip}.$OriginalShipName"/>
                </do_if>
                
                <do_if value="$oldShipOriginalName">
                  <set_object_name object="$oldShip" name="$oldShipOriginalName"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-ShipMgmt] Restored original name for old ship ' + $oldShip.knownname + ' -> ' + $oldShipOriginalName" chance="100"/>
                  </do_if>
                </do_if>
              </do_elseif>
              
              <!-- Case: Old ship has GT order with different pilot -->
              <!-- No cleanup needed - that pilot handles the ship -->
              <do_elseif value="$oldShipHasGTOrder and $oldShipHasPilot">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-ShipMgmt] Old ship ' + $oldShip.knownname + ' has GT order with different pilot - no cleanup needed'" chance="100"/>
                </do_if>
              </do_elseif>
            </do_if>
            
            <!-- Send logbook message when pilot is transferred to new ship after reactivation -->
            <!-- Only send message if ship has GT default order active (not just when trade orders change) -->
            <do_if value="$wasPaused and not (global.$GT_Pilots.{$pilot}.$ResumedFromEject? and global.$GT_Pilots.{$pilot}.$ResumedFromEject)">
              <set_value name="$hasGTOrder" exact="false"/>
              <do_if value="$ship.defaultorder?">
                <do_if value="global.$GT_ProtectedOrderIDs? and $ship.defaultorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}">
                  <set_value name="$hasGTOrder" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$hasGTOrder">
                <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
                <set_value name="$logbookMessage" exact="{77000,3217}.[$ship.knownname, player.name]"/>
                
                <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                  <param name="Message" value="$logbookMessage"/>
                  <param name="Category" value="'general'"/>
                  <param name="Title" value="'Pilot Transfer: ' + $pilot.name"/>
                  <param name="Object" value="$ship"/>
                  <param name="Interaction" value="'showonmap'"/>
                </run_actions>
              </do_if>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <!-- First time registration OR pilot reactivated but ShipID was cleared when paused -->
          <set_value name="$isNewShip" exact="true"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$currentShipID"/>
          <!-- Original ship name already stored above (per ship, not per pilot) -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] First-time registration - pilot ' + $pilot.name + ' on ship: ' + $ship.knownname + ' (ID: ' + $currentShipID + ')'" chance="100"/>
          </do_if>
          
          <!-- Send logbook message when pilot returns from holiday (ShipID was cleared when paused) -->
          <!-- Only send message if ship has GT default order active (not just when trade orders change) -->
          <do_if value="$wasPaused and not (global.$GT_Pilots.{$pilot}.$ResumedFromEject? and global.$GT_Pilots.{$pilot}.$ResumedFromEject)">
            <set_value name="$hasGTOrder" exact="false"/>
            <do_if value="$ship.defaultorder?">
              <do_if value="global.$GT_ProtectedOrderIDs? and $ship.defaultorder? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}">
                <set_value name="$hasGTOrder" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="$hasGTOrder">
              <set_value name="$message" exact="{77000,3216}.[player.name, $ship.knownname]"/>
              <write_to_logbook 
                category="general" 
                title="'Pilot Return: ' + $pilot.name" 
                interaction="showonmap" 
                object="$ship" 
                text="$message"/>
            </do_if>
          </do_if>
        </do_else>
        
        <!-- Safety net only: do NOT rename again if already updated in branch above. -->
        <do_if value="not $nameAlreadyUpdatedInBranch">
          <run_actions ref="Update_Pilot_Ship_Name" result="$nameUpdateResult">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="forceUpdate" value="true"/>
          </run_actions>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Register_Pilot: Ship name update completed for ' + $pilot.name + ' on ' + $ship.knownname + ' (result: ' + (if $nameAlreadyUpdatedInBranch then 'branch' else $nameUpdateResult) + ')'" chance="100"/>
        </do_if>
        <do_if value="global.$GT_Pilots.{$pilot}.$ResumedFromEject?">
          <remove_value name="global.$GT_Pilots.{$pilot}.$ResumedFromEject"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Update Ship Status -->
    <library name="Update_Ship_Status" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to update"/>
        <param name="status" comment="New status"/>
      </params>
      <actions>
        <do_if value="global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}.$Status" exact="$status"/>
          <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Updated ship status: ' + $ship.knownname + ' -> ' + $status" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </library>
    
    <!-- Skill Level Calculation -->
    <library name="Calculate_Skill_Level" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
        <param name="pilot" default="null" comment="Pilot override for transient swap states"/>
        <param name="use_md_system" default="true" comment="Prefer MD system over native game skill"/>
        <param name="allow_commander_override" default="true" comment="Whether commander level may raise resolved level"/>
      </params>
      <actions>
        <set_value name="$skillLevel" exact="1"/>
        <set_value name="$pilotName" exact="'NONE'"/>
        <set_value name="$usingMDSkill" exact="false"/>
        <set_value name="$effectivePilot" exact="null"/>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        
        <do_if value="$pilot? and $pilot.exists">
          <set_value name="$effectivePilot" exact="$pilot"/>
        </do_if>
        <do_elseif value="$ship.pilot? and $ship.pilot.exists">
          <set_value name="$effectivePilot" exact="$ship.pilot"/>
        </do_elseif>
        
        <do_if value="$effectivePilot and $effectivePilot.exists">
          <set_value name="$pilotName" exact="if $effectivePilot.name? then $effectivePilot.name else 'NONE'"/>

          <!-- Vanilla mode: use native piloting skill directly (0..15). -->
          <do_if value="$useVanillaXPOnly">
            <set_value name="$skillLevel" exact="if $effectivePilot.skill.piloting? then $effectivePilot.skill.piloting else 1"/>
          </do_if>
          <!-- GT mode: resolve from GT pilot data (existing behavior). -->
          <do_elseif value="$use_md_system and global.$GT_Pilots.{$effectivePilot}?">
            <set_value name="$mdXP" exact="global.$GT_Pilots.{$effectivePilot}.$XP"/>
            <set_value name="$mdSkillLevel" exact="1"/>
            
            <!-- Calculate skill level from XP using simple thresholds if config not available -->
            <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$SkillThresholds?">
              <!-- Use configuration thresholds -->
              <do_all exact="15" counter="$skillCheck">
                <do_if value="$mdXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillCheck}">
                  <set_value name="$mdSkillLevel" exact="$skillCheck"/>
                </do_if>
              </do_all>
            </do_if>
            <do_else>
              <!-- Use simple XP-based calculation as fallback -->
              <do_if value="$mdXP ge 50000">
                <set_value name="$mdSkillLevel" exact="15"/>
              </do_if>
              <do_elseif value="$mdXP ge 30000">
                <set_value name="$mdSkillLevel" exact="10"/>
              </do_elseif>
              <do_elseif value="$mdXP ge 15000">
                <set_value name="$mdSkillLevel" exact="7"/>
              </do_elseif>
              <do_elseif value="$mdXP ge 5000">
                <set_value name="$mdSkillLevel" exact="4"/>
              </do_elseif>
              <do_elseif value="$mdXP ge 1000">
                <set_value name="$mdSkillLevel" exact="2"/>
              </do_elseif>
            </do_else>
            
            <set_value name="$skillLevel" exact="$mdSkillLevel"/>
            <set_value name="$usingMDSkill" exact="true"/>
          </do_elseif>
          <!-- No vanilla-skill fallback: GT behavior must use GT pilot data only. -->
        </do_if>
        
        <!-- Check commander GT level if better -->
        <do_if value="not $useVanillaXPOnly and $allow_commander_override and $ship.commander? and $ship.commander.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.commander.pilot}? and global.$GT_Pilots.{$ship.commander.pilot}.$Level?">
          <set_value name="$commanderSkill" exact="global.$GT_Pilots.{$ship.commander.pilot}.$Level"/>
          <set_value name="$skillLevel" exact="[$skillLevel, $commanderSkill].max"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Calculate_Skill_Level returning: Level=' + $skillLevel + ', Pilot=' + $pilotName + ', UsingMD=' + $usingMDSkill" chance="100"/>
        </do_if>
        
        <!-- Return comprehensive skill information as result -->
        <return value="table[
          $Level = $skillLevel,
          $PilotName = $pilotName,
          $UsingMDSystem = $usingMDSkill,
          $HasPilot = $ship.pilot?,
          $HasCommander = $ship.commander?
        ]"/>
      </actions>
    </library>
    
    <!-- Jump Distance Calculation Based on Skill -->
    <library name="Calculate_Jump_Distance" purpose="run_actions">
      <params>
        <param name="skill_level" comment="Pilot skill level"/>
      </params>
      <actions>
        <set_value name="$jumpDistance" exact="1"/>
        
        <!-- Skill-based jump distance calculation -->
        <do_if value="$skill_level le 2">
          <set_value name="$jumpDistance" exact="1"/>   <!-- Lehrling -->
        </do_if>
        <do_elseif value="$skill_level le 5">
          <set_value name="$jumpDistance" exact="3"/>   <!-- Kurier -->
        </do_elseif>
        <do_elseif value="$skill_level le 8">
          <set_value name="$jumpDistance" exact="5"/>   <!-- Lieferant -->
        </do_elseif>
        <do_elseif value="$skill_level le 11">
          <set_value name="$jumpDistance" exact="10"/>  <!-- HÃ¤ndler -->
        </do_elseif>
        <do_elseif value="$skill_level le 13">
          <set_value name="$jumpDistance" exact="15"/>  <!-- Kaufmann -->
        </do_elseif>
        <do_else>
          <set_value name="$jumpDistance" exact="25"/>  <!-- Fernkaufmann -->
        </do_else>
        
        <return value="$jumpDistance"/>
      </actions>
    </library>

    <!-- Apply stored jump-distance order params to pilot tier max when autoJumpDistanceByLevel is enabled. -->
    <library name="GT_Apply_AutoJumpDistance_ForShip" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship whose GT default order owns autoJumpDistanceByLevel"/>
        <param name="pilot" default="null" comment="Pilot for tier max; defaults to ship.pilot"/>
        <param name="reason" default="'unknown'" comment="training_completion | pilot_change | checkbox_enabled"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[$Applied = false, $NewTierMax = 0, $UpdatedParams = []]"/>

        <do_if value="not $ship? or not $ship.exists">
          <return value="$result"/>
        </do_if>

        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly">
          <return value="$result"/>
        </do_if>

        <do_if value="not $ship.defaultorder?">
          <return value="$result"/>
        </do_if>

        <set_value name="$gtOrder" exact="$ship.defaultorder"/>
        <set_value name="$orderId" exact="@$gtOrder.id"/>
        <set_value name="$isProtectedOrder" exact="false"/>
        <do_if value="global.$GT_ProtectedOrderIDs?">
          <do_all exact="global.$GT_ProtectedOrderIDs.count" counter="$oi">
            <do_if value="global.$GT_ProtectedOrderIDs.{$oi} == $orderId">
              <set_value name="$isProtectedOrder" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="not $isProtectedOrder">
          <return value="$result"/>
        </do_if>

        <!-- Ship-subordinate: no checkbox on Assist wings (J3). -->
        <do_if value="$ship.commander? and $ship.commander.exists and not $ship.commander.isclass.station">
          <return value="$result"/>
        </do_if>

        <do_if value="not $gtOrder.$autoJumpDistanceByLevel? or not $gtOrder.$autoJumpDistanceByLevel">
          <return value="$result"/>
        </do_if>

        <do_if value="not $pilot? or not $pilot.exists">
          <set_value name="$pilot" exact="$ship.pilot"/>
        </do_if>
        <do_if value="not $pilot? or not $pilot.exists or not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}? or not global.$GT_Pilots.{$pilot}.$Level?">
          <return value="$result"/>
        </do_if>

        <set_value name="$pilotLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>

        <do_if value="$reason == 'training_completion'">
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$AutoJumpLastAppliedLevel? and global.$GT_Ships.{$ship}.$AutoJumpLastAppliedLevel == $pilotLevel">
            <return value="$result"/>
          </do_if>
        </do_if>

        <run_actions ref="md.GT_Ship_Management.Calculate_Jump_Distance" result="$tierMax">
          <param name="skill_level" value="$pilotLevel"/>
        </run_actions>
        <set_value name="$result.$NewTierMax" exact="$tierMax"/>

        <set_value name="$paramNames" exact="[]"/>
        <do_if value="$orderId == 'GalaxyTraderMK1'">
          <append_to_list name="$paramNames" exact="'maxsell'"/>
        </do_if>
        <do_elseif value="$orderId == 'GalaxyTraderMK2'">
          <append_to_list name="$paramNames" exact="'maxDistance'"/>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyTraderMK3'">
          <append_to_list name="$paramNames" exact="'maxbuy'"/>
          <append_to_list name="$paramNames" exact="'maxsell'"/>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyTraderMK4Supply'">
          <append_to_list name="$paramNames" exact="'jumpDistanceCoverage'"/>
          <append_to_list name="$paramNames" exact="'jumpDistanceBuy'"/>
        </do_elseif>
        <do_elseif value="$orderId == 'GalaxyMiner'">
          <append_to_list name="$paramNames" exact="'maxGatherDistance'"/>
          <append_to_list name="$paramNames" exact="'maxSellDistance'"/>
        </do_elseif>
        <do_else>
          <return value="$result"/>
        </do_else>

        <set_value name="$didUpdate" exact="false"/>
        <do_all exact="$paramNames.count" counter="$pi">
          <set_value name="$paramName" exact="$paramNames.{$pi}"/>
          <set_value name="$currentVal" exact="0"/>
          <do_if value="$paramName == 'maxsell' and $gtOrder.$maxsell?">
            <set_value name="$currentVal" exact="$gtOrder.$maxsell"/>
          </do_if>
          <do_elseif value="$paramName == 'maxbuy' and $gtOrder.$maxbuy?">
            <set_value name="$currentVal" exact="$gtOrder.$maxbuy"/>
          </do_elseif>
          <do_elseif value="$paramName == 'maxDistance' and $gtOrder.$maxDistance?">
            <set_value name="$currentVal" exact="$gtOrder.$maxDistance"/>
          </do_elseif>
          <do_elseif value="$paramName == 'jumpDistanceCoverage' and $gtOrder.$jumpDistanceCoverage?">
            <set_value name="$currentVal" exact="$gtOrder.$jumpDistanceCoverage"/>
          </do_elseif>
          <do_elseif value="$paramName == 'jumpDistanceBuy' and $gtOrder.$jumpDistanceBuy?">
            <set_value name="$currentVal" exact="$gtOrder.$jumpDistanceBuy"/>
          </do_elseif>
          <do_elseif value="$paramName == 'maxGatherDistance'">
            <set_value name="$currentVal" exact="@$gtOrder.$maxGatherDistance"/>
          </do_elseif>
          <do_elseif value="$paramName == 'maxSellDistance'">
            <set_value name="$currentVal" exact="@$gtOrder.$maxSellDistance"/>
          </do_elseif>

          <do_if value="$currentVal != $tierMax">
            <edit_order_param order="$ship.defaultorder" param="$paramName" value="$tierMax"/>
            <do_if value="$ship.order? and @$ship.order.id == $orderId">
              <edit_order_param order="$ship.order" param="$paramName" value="$tierMax"/>
            </do_if>
            <append_to_list name="$result.$UpdatedParams" exact="$paramName"/>
            <set_value name="$didUpdate" exact="true"/>
          </do_if>
        </do_all>

        <do_if value="$didUpdate">
          <do_if value="not global.$GT_Ships?">
            <set_value name="global.$GT_Ships" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_Ships.{$ship}?">
            <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_Ships.{$ship}.$AutoJumpLastAppliedLevel" exact="$pilotLevel"/>
          <set_value name="$result.$Applied" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] AutoJumpDistance applied on ' + $ship.idcode + ' (' + $reason + '): tierMax=' + $tierMax + ', params=' + $result.$UpdatedParams.count" chance="100"/>
          </do_if>
        </do_if>

        <return value="$result"/>
      </actions>
    </library>

    <!-- Detect Ship Class -->
    <library name="Detect_Ship_Class" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to analyze"/>
      </params>
      <actions>
        <set_value name="$shipClass" exact="'unknown'"/>
        <set_value name="$shipSize" exact="'unknown'"/>
        <set_value name="$isSmall" exact="false"/>
        <set_value name="$isMedium" exact="false"/>
        <set_value name="$isLarge" exact="false"/>
        <set_value name="$isCapital" exact="false"/>
        
        <!-- Detect ship class using X4 native properties -->
        <do_if value="$ship.isclass.ship_s">
          <set_value name="$shipClass" exact="'small'"/>
          <set_value name="$shipSize" exact="'S'"/>
          <set_value name="$isSmall" exact="true"/>
        </do_if>
        <do_elseif value="$ship.isclass.ship_m">
          <set_value name="$shipClass" exact="'medium'"/>
          <set_value name="$shipSize" exact="'M'"/>
          <set_value name="$isMedium" exact="true"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.ship_l">
          <set_value name="$shipClass" exact="'large'"/>
          <set_value name="$shipSize" exact="'L'"/>
          <set_value name="$isLarge" exact="true"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.ship_xl">
          <set_value name="$shipClass" exact="'capital'"/>
          <set_value name="$shipSize" exact="'XL'"/>
          <set_value name="$isCapital" exact="true"/>
        </do_elseif>
        <do_else>
          <!-- Fallback: assume medium ship if detection fails -->
          <set_value name="$shipClass" exact="'medium'"/>
          <set_value name="$shipSize" exact="'M'"/>
          <set_value name="$isMedium" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] WARNING: Failed to detect ship class for ' + $ship.knownname + ', defaulting to medium'" chance="100"/>
          </do_if>
        </do_else>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Detect_Ship_Class returning: Class=' + $shipClass + ', Size=' + $shipSize + ', Small=' + $isSmall + ', Medium=' + $isMedium + ', Large=' + $isLarge + ', Capital=' + $isCapital" chance="100"/>
        </do_if>
        
        <return value="table[
          $Class = $shipClass,
          $Size = $shipSize,
          $IsSmall = $isSmall,
          $IsMedium = $isMedium,
          $IsLarge = $isLarge,
          $IsCapital = $isCapital
        ]"/>
      </actions>
    </library>
    
    <!-- Calculate ship radar range using native property -->
    <library name="Calculate_Radar_Range" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to analyze"/>
      </params>
      <actions>
        <set_value name="$radarRangeMeters" exact="$ship.maxradarrange"/>
        <return value="$radarRangeMeters"/>
      </actions>
    </library>
    
    <!-- Main Ship Modification Handler -->
    <library name="Handle_Pilot_Ship_Assignment" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship receiving modifications"/>
        <param name="new_pilot" comment="New pilot assigned"/>
        <param name="old_pilot" comment="Previous pilot (may be null)"/>
      </params>
      <actions>
        <!-- Get ship class information -->
        <run_actions ref="Detect_Ship_Class" result="$classInfo">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Get pilot skill level -->
        <run_actions ref="Calculate_Skill_Level" result="$skillInfo">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$new_pilot"/>
          <param name="allow_commander_override" value="false"/>
        </run_actions>
        <set_value name="$gtXPDebug" exact="if global.$GT_Pilots? and $new_pilot? and global.$GT_Pilots.{$new_pilot}? and global.$GT_Pilots.{$new_pilot}.$XP? then global.$GT_Pilots.{$new_pilot}.$XP else 'NONE'"/>
        <set_value name="$gtStoredLevelDebug" exact="if global.$GT_Pilots? and $new_pilot? and global.$GT_Pilots.{$new_pilot}? and global.$GT_Pilots.{$new_pilot}.$Level? then global.$GT_Pilots.{$new_pilot}.$Level else 'NONE'"/>
        
        <!-- Safety check: ensure we have valid results -->
        <do_if value="not $classInfo?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] ERROR: Detect_Ship_Class returned null for ' + $ship.knownname" chance="100"/>
          </do_if>
          <set_value name="$classInfo" exact="table[$Class = 'medium', $Size = 'M', $IsSmall = false, $IsMedium = true, $IsLarge = false, $IsCapital = false]"/>
        </do_if>
        
        <do_if value="not $skillInfo?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] ERROR: Calculate_Skill_Level returned null for ' + $ship.knownname" chance="100"/>
          </do_if>
          <set_value name="$skillInfo" exact="table[$Level = 1, $PilotName = 'UNKNOWN', $UsingMDSystem = false, $HasPilot = false, $HasCommander = false]"/>
        </do_if>
        
        <!-- Apply performance system to ship -->
        <run_actions ref="Apply_Ship_Performance_System">
          <param name="ship" value="$ship"/>
          <param name="skill_level" value="$skillInfo.$Level"/>
          <param name="pilot" value="$new_pilot"/>
        </run_actions>
        
        <!-- Use the same GT-control detection stack as cleanup/renaming. -->
        <set_value name="$hasGTOrder" exact="false"/>
        <do_if value="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus?">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="$hasGTOrder" exact="$gtStatus.$IsGTControlled"/>
        </do_if>
        
        <!-- Pilot exchange status is centralized in GT_Ship_State_Utilities for consistency. -->
        <set_value name="$peStatus" exact="table[]"/>
        <set_value name="$peStatus.$ShouldKeepPE" exact="false"/>
        <set_value name="$peStatus.$ShouldClearPE" exact="false"/>
        <set_value name="$peStatus.$CurrentOrder" exact="'NONE'"/>
        <set_value name="$peStatus.$CurrentCallerOrder" exact="'NONE'"/>
        <set_value name="$peStatus.$HasPendingDock" exact="false"/>
        <do_if value="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus?">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$peStatus">
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        
        <!-- During active/fresh pilot-exchange transitions, keep GT context for reconciliation. -->
        <do_if value="not $hasGTOrder and $peStatus.$ShouldKeepPE">
          <set_value name="$hasGTOrder" exact="true"/>
        </do_if>
        
        <!-- Fleet commanders (and any ship with a direct GT default order) can still carry
             GalaxyTrader*/GalaxyMiner on defaultorder while GT_CheckGTOrderStatus reports
             not GT-controlled during internal order recursion / coordination. Subordinates
             stay covered via Assist + commander checks; this fallback fixes missing mod
             reconciliation on level-up and order recycle for those commanders. -->
        <set_value name="$hasDirectProtectedGTDefault" exact="false"/>
        <do_if value="$ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}">
          <set_value name="$hasDirectProtectedGTDefault" exact="true"/>
        </do_if>
        
        <!-- Deterministic stale-PE scrub driven by centralized status computation. -->
        <do_if value="$peStatus.$ShouldClearPE">
          <set_value name="global.$GT_Ships.{$ship}.$PilotExchange" exact="false"/>
          <do_if value="global.$GT_RedistributePendingDockByShip? and $ship.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $ship.idcode}"/>
          </do_if>
          <do_if value="global.$GT_RedistributePendingDockSinceByShip? and $ship.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $ship.idcode}"/>
          </do_if>
          <do_if value="$ship.pilot? and $ship.pilot.exists">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$ship.pilot"/>
              <param name="reason" value="'stale_pilot_exchange_clear'"/>
            </run_actions>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Cleared stale PilotExchange flag for ' + $ship.idcode + ' (current=' + $peStatus.$CurrentOrder + ', caller=' + $peStatus.$CurrentCallerOrder + ', hadPending=' + $peStatus.$HasPendingDock + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <set_value name="$newPilotNameDbg" exact="if $new_pilot and $new_pilot.exists and $new_pilot.name? then $new_pilot.name else 'NONE'"/>
        <set_value name="$newPilotIdDbg" exact="if $new_pilot and $new_pilot.exists and $new_pilot.idcode? then $new_pilot.idcode else 'NONE'"/>
        <set_value name="$oldPilotNameDbg" exact="if $old_pilot and $old_pilot.exists and $old_pilot.name? then $old_pilot.name else 'NONE'"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Assignment trace ship=' + $ship.idcode + ' pilot=' + $newPilotNameDbg + ' pilotId=' + $newPilotIdDbg + ' oldPilot=' + $oldPilotNameDbg + ' class=' + $classInfo.$Size + ' skill=' + $skillInfo.$Level + ' usingMD=' + $skillInfo.$UsingMDSystem + ' gtXP=' + $gtXPDebug + ' gtStoredLevel=' + $gtStoredLevelDebug + ' default=' + (if $ship.defaultorder? then @$ship.defaultorder.id else 'NONE') + ' current=' + (if $ship.order? then @$ship.order.id else 'NONE') + ' pilotExchange=' + (if global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$PilotExchange? then global.$GT_Ships.{$ship}.$PilotExchange else 'NONE') + ' hasGTOrder=' + $hasGTOrder + ' directProtectedGTDefault=' + $hasDirectProtectedGTDefault" chance="100"/>
        </do_if>

        <!-- During pilot exchange the ship can briefly have no bound captain.
             Do not queue pilot-based mod reconciliation until the captain is fully rebound. -->
        <do_if value="not ($new_pilot and $new_pilot.exists)">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Assignment defers mod refresh for ' + $ship.idcode + ' because new pilot is not bound yet'" chance="100"/>
          </do_if>
          <return/>
        </do_if>
        
        <!-- Ship mod updates are authoritative, but pilot/order transitions can briefly report
             a non-GT state during recycle or pilot change. Reuse the deferred refresh queue so
             the final converge step runs after the engine has settled. -->
        <set_value name="$queueModRefresh" exact="$hasGTOrder or $hasDirectProtectedGTDefault"/>
        <do_if value="$queueModRefresh">
          <signal_cue_instantly cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh" param="table[
            $Ship = $ship,
            $source = 'pilot_assignment',
            $forceGTContext = true
          ]"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <do_if value="$queueModRefresh">
            <debug_text text="'[GT-ShipMgmt] Queued authoritative mod refresh for ' + $ship.knownname + ' and pilot ' + $newPilotNameDbg + ' (Skill: ' + $skillInfo.$Level + ', hasGTOrder=' + $hasGTOrder + ', directProtectedGTDefault=' + $hasDirectProtectedGTDefault + ')'" chance="100"/>
          </do_if>
          <do_else>
            <debug_text text="'[GT-ShipMgmt] Skipped mod refresh for ' + $ship.knownname + ' (hasGTOrder=' + $hasGTOrder + ', directProtectedGTDefault=' + $hasDirectProtectedGTDefault + ')'" chance="100"/>
          </do_else>
        </do_if>
      </actions>
    </library>
    
    <!-- Apply Ship Performance System -->
    <library name="Apply_Ship_Performance_System" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to apply performance system to"/>
        <param name="skill_level" comment="Pilot skill level"/>
        <param name="pilot" comment="Pilot"/>
      </params>
      <actions>
        <!-- Update ship performance display -->
        <run_actions ref="Update_Ship_Performance_Display">
          <param name="ship" value="$ship"/>
          <param name="pilot_level" value="$skill_level"/>
        </run_actions>
        
        <!-- Log performance application -->
        <set_value name="$pilotNameDbg" exact="if $pilot and $pilot.exists and $pilot.name? then $pilot.name else 'NONE'"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Performance system applied to ' + $ship.knownname + ' for pilot ' + $pilotNameDbg + ' (Level: ' + $skill_level + ')'" chance="100"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Calculate Ship Performance Bonus/Malus -->
    <library name="Calculate_Performance_Modifier" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to analyze"/>
        <param name="pilot_level" comment="Pilot skill level"/>
      </params>
      <actions>
        <!-- Get ship class information -->
        <run_actions ref="Detect_Ship_Class" result="$classInfo">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <!-- Safety check: ensure we have valid class info -->
        <do_if value="not $classInfo?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] ERROR: Detect_Ship_Class returned null in Calculate_Performance_Modifier for ' + $ship.knownname" chance="100"/>
          </do_if>
          <set_value name="$classInfo" exact="table[$Class = 'medium', $Size = 'M', $IsSmall = false, $IsMedium = true, $IsLarge = false, $IsCapital = false]"/>
        </do_if>
        
        <!-- Initialize performance values -->
        <set_value name="$performanceModifier" exact="0"/>
        <set_value name="$statusText" exact="'Neutral'"/>
        <set_value name="$statusColor" exact="'white'"/>
        
        <!-- Performance Matrix from Specification -->
        <do_if value="$pilot_level le 2">
          <!-- Apprentice (1-2) -->
          <do_if value="$classInfo.$IsSmall">
            <set_value name="$performanceModifier" exact="0"/>
            <set_value name="$statusText" exact="'Optimal'"/>
            <set_value name="$statusColor" exact="'green'"/>
          </do_if>
          <do_elseif value="$classInfo.$IsMedium">
            <set_value name="$performanceModifier" exact="-5"/>
            <set_value name="$statusText" exact="'Penalty'"/>
            <set_value name="$statusColor" exact="'orange'"/>
          </do_elseif>
          <do_elseif value="$classInfo.$IsLarge">
            <set_value name="$performanceModifier" exact="-15"/>
            <set_value name="$statusText" exact="'Major Penalty'"/>
            <set_value name="$statusColor" exact="'red'"/>
          </do_elseif>
          <do_elseif value="$classInfo.$IsCapital">
            <set_value name="$performanceModifier" exact="-25"/>
            <set_value name="$statusText" exact="'Severe Penalty'"/>
            <set_value name="$statusColor" exact="'red'"/>
          </do_elseif>
        </do_if>
        <do_elseif value="$pilot_level == 3">
          <!-- Basic Certified (3) -->
          <do_if value="$classInfo.$IsSmall">
            <set_value name="$performanceModifier" exact="3"/>
            <set_value name="$statusText" exact="'Bonus'"/>
            <set_value name="$statusColor" exact="'green'"/>
          </do_if>
          <do_elseif value="$classInfo.$IsMedium">
            <set_value name="$performanceModifier" exact="0"/>
            <set_value name="$statusText" exact="'Neutral'"/>
            <set_value name="$statusColor" exact="'white'"/>
          </do_elseif>
          <do_elseif value="$classInfo.$IsLarge">
            <set_value name="$performanceModifier" exact="-8"/>
            <set_value name="$statusText" exact="'Penalty'"/>
            <set_value name="$statusColor" exact="'orange'"/>
          </do_elseif>
          <do_elseif value="$classInfo.$IsCapital">
            <set_value name="$performanceModifier" exact="-15"/>
            <set_value name="$statusText" exact="'Major Penalty'"/>
            <set_value name="$statusColor" exact="'red'"/>
          </do_elseif>
        </do_elseif>
        <do_elseif value="$pilot_level ge 4 and $pilot_level le 6">
          <!-- Courier (4-6) -->
          <do_if value="$classInfo.$IsSmall">
            <set_value name="$performanceModifier" exact="3"/>
            <set_value name="$statusText" exact="'Bonus'"/>
            <set_value name="$statusColor" exact="'green'"/>
          </do_if>
          <do_elseif value="$classInfo.$IsMedium">
            <set_value name="$performanceModifier" exact="0"/>
            <set_value name="$statusText" exact="'Neutral'"/>
            <set_value name="$statusColor" exact="'white'"/>
          </do_elseif>
          <do_elseif value="$classInfo.$IsLarge">
            <set_value name="$performanceModifier" exact="-8"/>
            <set_value name="$statusText" exact="'Penalty'"/>
            <set_value name="$statusColor" exact="'orange'"/>
          </do_elseif>
          <do_elseif value="$classInfo.$IsCapital">
            <set_value name="$performanceModifier" exact="-15"/>
            <set_value name="$statusText" exact="'Major Penalty'"/>
            <set_value name="$statusColor" exact="'red'"/>
          </do_elseif>
        </do_elseif>
        <do_elseif value="$pilot_level ge 7 and $pilot_level le 15">
          <!-- Advanced levels - progressively better performance -->
          <do_if value="$pilot_level ge 12">
            <!-- Master Certified (12+) -->
            <do_if value="$classInfo.$IsSmall">
              <set_value name="$performanceModifier" exact="12"/>
            </do_if>
            <do_elseif value="$classInfo.$IsMedium">
              <set_value name="$performanceModifier" exact="9"/>
            </do_elseif>
            <do_elseif value="$classInfo.$IsLarge">
              <set_value name="$performanceModifier" exact="6"/>
            </do_elseif>
            <do_elseif value="$classInfo.$IsCapital">
              <set_value name="$performanceModifier" exact="3"/>
            </do_elseif>
          </do_if>
          <do_elseif value="$pilot_level ge 9">
            <!-- Expert Trader (9-11) -->
            <do_if value="$classInfo.$IsSmall">
              <set_value name="$performanceModifier" exact="9"/>
            </do_if>
            <do_elseif value="$classInfo.$IsMedium">
              <set_value name="$performanceModifier" exact="6"/>
            </do_elseif>
            <do_elseif value="$classInfo.$IsLarge">
              <set_value name="$performanceModifier" exact="3"/>
            </do_elseif>
            <do_elseif value="$classInfo.$IsCapital">
              <set_value name="$performanceModifier" exact="0"/>
            </do_elseif>
          </do_elseif>
          <do_else>
            <!-- Supplier (7-8) -->
            <do_if value="$classInfo.$IsSmall">
              <set_value name="$performanceModifier" exact="6"/>
            </do_if>
            <do_elseif value="$classInfo.$IsMedium">
              <set_value name="$performanceModifier" exact="3"/>
            </do_elseif>
            <do_elseif value="$classInfo.$IsLarge">
              <set_value name="$performanceModifier" exact="0"/>
            </do_elseif>
            <do_elseif value="$classInfo.$IsCapital">
              <set_value name="$performanceModifier" exact="-8"/>
            </do_elseif>
          </do_else>
          
          <!-- Set status for advanced levels -->
          <do_if value="$performanceModifier gt 0">
            <set_value name="$statusText" exact="'Bonus'"/>
            <set_value name="$statusColor" exact="'green'"/>
          </do_if>
          <do_elseif value="$performanceModifier lt 0">
            <set_value name="$statusText" exact="'Penalty'"/>
            <set_value name="$statusColor" exact="'orange'"/>
          </do_elseif>
          <do_else>
            <set_value name="$statusText" exact="'Neutral'"/>
            <set_value name="$statusColor" exact="'white'"/>
          </do_else>
        </do_elseif>
        
        <!-- Master Merchant (15) gets additional bonuses -->
        <do_if value="$pilot_level == 15">
          <set_value name="$performanceModifier" exact="$performanceModifier + 3"/>
          <set_value name="$statusText" exact="'Master Bonus'"/>
          <set_value name="$statusColor" exact="'cyan'"/>
        </do_if>
        
        <!-- Return performance data -->
        <return value="table[
          $Modifier = $performanceModifier,
          $StatusText = $statusText,
          $StatusColor = $statusColor,
          $ShipClass = $classInfo.$Class,
          $ShipSize = $classInfo.$Size
        ]"/>
      </actions>
    </library>
    
    <!-- Get Ship Performance Data -->
    <library name="Get_Ship_Performance_Data" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to get performance data for"/>
      </params>
      <actions>
        <do_if value="global.$GT_Ships.{$ship}?">
          <return value="table[
            $PerformanceInfo = global.$GT_Ships.{$ship}.$PerformanceInfo,
            $PerformanceModifier = global.$GT_Ships.{$ship}.$PerformanceModifier,
            $PerformanceStatus = global.$GT_Ships.{$ship}.$PerformanceStatus,
            $PerformanceLevel = global.$GT_Ships.{$ship}.$PerformanceLevel
          ]"/>
        </do_if>
        <do_else>
          <return value="null"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Update Ship Information Display -->
    <library name="Update_Ship_Performance_Display" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to update"/>
        <param name="pilot_level" comment="Pilot skill level"/>
      </params>
      <actions>
        <!-- Calculate performance modifier -->
        <run_actions ref="Calculate_Performance_Modifier" result="$perfData">
          <param name="ship" value="$ship"/>
          <param name="pilot_level" value="$pilot_level"/>
        </run_actions>
        
        <!-- Create performance info text -->
        <set_value name="$performanceInfo" exact="'GT Performance: ' + $perfData.$StatusText + ' (' + $perfData.$Modifier + '%) - Level ' + $pilot_level + ' pilot in ' + $perfData.$ShipSize + '-class ship'"/>
        
        <!-- Store performance data in global GT_Ships table (X4 doesn't allow custom properties on ship objects) -->
        <do_if value="global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceInfo" exact="$performanceInfo"/>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceModifier" exact="$perfData.$Modifier"/>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceStatus" exact="$perfData.$StatusText"/>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceLevel" exact="$pilot_level"/>
        </do_if>
        <do_else>
          <!-- Ship not in tracking table, initialize it first -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] WARNING: Ship ' + $ship.knownname + ' not in GT_Ships table, initializing'" chance="100"/>
          </do_if>
          <run_actions ref="Register_Ship">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$ship.pilot"/>
            <param name="config" value="table[]"/>
          </run_actions>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceInfo" exact="$performanceInfo"/>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceModifier" exact="$perfData.$Modifier"/>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceStatus" exact="$perfData.$StatusText"/>
          <set_value name="global.$GT_Ships.{$ship}.$PerformanceLevel" exact="$pilot_level"/>
        </do_else>
        
        <!-- Debug output -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Performance calculated: ' + $ship.knownname + ' - ' + $performanceInfo" chance="100"/>
        </do_if>
        
        <!-- Show performance notification to player -->
        <do_if value="global.$GT_Config? and global.$GT_Config.$Notifications? and global.$GT_Config.$Notifications.$Level? and global.$GT_Config.$Notifications.$Level ge 1">
          <show_notification text="'Ship Performance Update:\n' + $ship.knownname + '\n' + $performanceInfo" timeout="8s" priority="6"/>
        </do_if>
      </actions>
    </library>
    
    <!-- Apply Ship Modifications - DEPRECATED: Replaced by GT_Ship_Modification_System -->
    <library name="Apply_Ship_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to modify"/>
        <param name="performance_data" comment="Performance data from Calculate_Performance_Modifier"/>
        <param name="pilot_level" comment="Pilot skill level"/>
      </params>
      <actions>
        <!-- DEPRECATED: This library is no longer used. Ship modifications are now handled by -->
        <!-- the GT_Ship_Modification_System using direct engine parameter modification. -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] DEPRECATED: Apply_Ship_Modifications called - use GT_Ship_Modification_System instead'" chance="100"/>
        </do_if>
        <!-- Check if modifications are already applied -->
        <set_value name="$currentModLevel" exact="0"/>
        <set_value name="$needsUpdate" exact="true"/>
        
        <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$AppliedModifications? and global.$GT_Ships.{$ship}.$AppliedModifications.count gt 0">
          <set_value name="$latestMod" exact="global.$GT_Ships.{$ship}.$AppliedModifications.{global.$GT_Ships.{$ship}.$AppliedModifications.count}"/>
          <set_value name="$currentModLevel" exact="$latestMod.$PilotLevel"/>
          
          <!-- Check if modification level matches current pilot level -->
          <do_if value="$currentModLevel == $pilot_level">
            <set_value name="$needsUpdate" exact="false"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Ship ' + $ship.knownname + ' already has correct modifications for pilot level ' + $pilot_level" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Get modification values -->
        <set_value name="$modifier" exact="$performance_data.$Modifier"/>
        <set_value name="$shipClass" exact="$performance_data.$ShipClass"/>
        
        <!-- Convert percentage to X4 multiplier format -->
        <set_value name="$multiplier" exact="1.0 + ($modifier / 100.0)"/>
        
        <!-- Ship modifications now handled by GT_Ship_Performance_System -->
        <do_if value="$needsUpdate and $modifier != 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Performance tracking updated: ' + $ship.knownname + ' - ' + $modifier + '% (Level ' + $pilot_level + ' pilot)'" chance="100"/>
          </do_if>
          
          <!-- Store modification tracking -->
          <set_value name="$modificationData" exact="table[
            $applied_time = player.age
          ]"/>
          <set_value name="$modificationData.$Type" exact="'engine_performance'"/>
          <set_value name="$modificationData.$Multiplier" exact="$multiplier"/>
          <set_value name="$modificationData.$Percentage" exact="$modifier"/>
          <set_value name="$modificationData.$PilotLevel" exact="$pilot_level"/>
          <set_value name="$modificationData.$ShipClass" exact="$shipClass"/>
          <set_value name="$modificationData.$AppliedTime" exact="player.age"/>
          
          <append_to_list name="global.$GT_Ships.{$ship}.$AppliedModifications" exact="$modificationData"/>
          
          <!-- Show modification notification -->
          <show_notification text="'GalaxyTrader Ship Enhancement Applied:\n' + $ship.knownname + '\nEngine Performance: ' + $modifier + '%\nPilot Level: ' + $pilot_level" timeout="10s" priority="7"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] No modifications needed for ' + $ship.knownname + ' (neutral performance)'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </library>

    <!-- Clear GT Ship Modification Tracking -->
    <library name="Remove_GT_Ship_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to clear modification tracking from"/>
      </params>
      <actions>
        <!-- Note: X4 equipment modifications are permanent once applied -->
        <!-- This function only clears our tracking data -->
        <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$AppliedModifications?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Clearing GT modification tracking for ' + $ship.knownname" chance="100"/>
          </do_if>
          
          <!-- Clear modification tracking -->
          <set_value name="global.$GT_Ships.{$ship}.$AppliedModifications" exact="[]"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] GT modification tracking cleared for ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </library>

    <!-- Get Ship Modification Status -->
    <library name="Get_Ship_Modification_Status" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
      </params>
      <actions>
        <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$AppliedModifications?">
          <set_value name="$modifications" exact="global.$GT_Ships.{$ship}.$AppliedModifications"/>
          <set_value name="$hasModifications" exact="$modifications.count gt 0"/>
          
          <do_if value="$hasModifications">
            <set_value name="$latestMod" exact="$modifications.{$modifications.count}"/>
            <return value="table[
              $HasModifications = true,
              $ModificationCount = $modifications.count,
              $LatestModification = $latestMod,
              $PerformanceBonus = $latestMod.$Percentage,
              $PilotLevel = $latestMod.$PilotLevel,
              $ShipClass = $latestMod.$ShipClass
            ]"/>
          </do_if>
          <do_else>
            <return value="table[
              $HasModifications = false,
              $ModificationCount = 0
            ]"/>
          </do_else>
        </do_if>
        <do_else>
          <return value="table[
            $HasModifications = false,
            $ModificationCount = 0
          ]"/>
        </do_else>
      </actions>
    </library>

    <!-- Update Ship Modifications on Pilot Change -->
    <library name="Update_Ship_On_Pilot_Change" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship that changed pilot"/>
        <param name="new_pilot" comment="New pilot (can be null)"/>
        <param name="old_pilot" comment="Previous pilot (can be null)"/>
      </params>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Pilot change detected: ' + $ship.knownname + ' - New: ' + @$new_pilot.name + ', Old: ' + @$old_pilot.name" chance="100"/>
        </do_if>
        
        <!-- Note: Ship modifications are permanent in X4, but we update tracking for new pilot -->
        
        <!-- Apply new modifications if new pilot exists and is registered -->
        <do_if value="$new_pilot and global.$GT_Pilots.{$new_pilot}?">
          <set_value name="$pilotLevel" exact="1"/>
          
          <!-- Calculate pilot level from XP -->
          <do_if value="global.$GT_Pilots.{$new_pilot}.$XP?">
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$new_pilot}.$XP"/>
            <do_all exact="15" counter="$level">
              <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$level}">
                <set_value name="$pilotLevel" exact="$level"/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Ship modifications updated for new pilot ' + $new_pilot.name + ' (Level ' + $pilotLevel + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] No modifications applied - pilot not registered or missing'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </library>
    
    <!-- ========================================================================= -->
    <!-- EXTRACTED LIBRARY FUNCTIONS - Common Pilot Operations                    -->
    <!-- ========================================================================= -->
    
    <!-- Calculate Rank Title from Skill Level -->
    <library name="Calculate_Rank_Title" purpose="run_actions">
      <params>
        <param name="skillLevel" comment="Pilot skill level (1-15)"/>
      </params>
      <actions>
        <set_value name="$rankTitle" exact="null"/>  <!-- Initialize to null - will be set by rank calculation or remain null if lookup fails -->
        <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
          <set_value name="$rankIndex" exact="($skillLevel / 3)i + 1"/>
          <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
            <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
          </do_if>
          <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
            <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
          </do_if>
          <do_else>
            <!-- Rank lookup failed - log error instead of using fallback -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] ERROR: Calculate_Rank_Title - Rank lookup failed for skillLevel=' + $skillLevel + ', rankIndex=' + $rankIndex + ', TraderTitles.count=' + global.$GT_Config.$XP.$TraderTitles.keys.count" chance="100"/>
            </do_if>
            <!-- Keep rankTitle as null to make the issue visible -->
          </do_else>
        </do_if>
        <do_else>
          <!-- Config or TraderTitles missing - log error -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] ERROR: Calculate_Rank_Title - Config or TraderTitles missing (Config=' + (if global.$GT_Config? then 'exists' else 'NULL') + ', XP=' + (if global.$GT_Config.$XP? then 'exists' else 'NULL') + ', TraderTitles=' + (if global.$GT_Config.$XP.$TraderTitles? then 'exists' else 'NULL') + ')'" chance="100"/>
          </do_if>
          <!-- Keep rankTitle as null to make the issue visible -->
        </do_else>
        <return value="$rankTitle"/>
      </actions>
    </library>
    
    <!-- Calculate Skill Level from XP (simpler version that works with pilot directly) -->
    <library name="Calculate_Skill_Level_From_XP" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to calculate level for"/>
        <param name="xp" comment="XP value (optional, will use pilot's XP if not provided)"/>
      </params>
      <actions>
        <set_value name="$xpValue" exact="0"/>
        <do_if value="$xp?">
          <set_value name="$xpValue" exact="$xp"/>
        </do_if>
        <do_elseif value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$XP?">
          <set_value name="$xpValue" exact="global.$GT_Pilots.{$pilot}.$XP"/>
        </do_elseif>
        
        <set_value name="$skillLevel" exact="1"/>
        <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$SkillThresholds?">
          <do_all exact="15" counter="$level">
            <do_if value="$xpValue ge global.$GT_Config.$XP.$SkillThresholds.{$level}">
              <set_value name="$skillLevel" exact="$level"/>
            </do_if>
          </do_all>
        </do_if>
        
        <return value="$skillLevel"/>
      </actions>
    </library>
    
    <!-- Persistent pilot identity for XP/registry: prefer component seed (stable across vanilla role swaps),
         else idcode. Stored in $StableIdentity and never overwritten once set. Not display names. -->
    <library name="Compute_Pilot_Stable_Key" purpose="run_actions">
      <params>
        <param name="pilot" comment="NPC/pilot entity"/>
      </params>
      <actions>
        <set_value name="$result" exact="''"/>
        <do_if value="$pilot?">
          <do_if value="$pilot.seed?">
            <set_value name="$result" exact="'s:' + $pilot.seed"/>
          </do_if>
          <do_elseif value="$pilot.idcode? and $pilot.idcode != ''">
            <set_value name="$result" exact="'i:' + $pilot.idcode"/>
          </do_elseif>
        </do_if>
        <return value="$result"/>
      </actions>
    </library>

    <!-- Maintain global.$GT_PilotsByStable â€” updated only via Rebind_Pilot_Registry / Sync_Stable_Identity_Index. -->
    <library name="Sync_Stable_Identity_Index" purpose="run_actions">
      <params>
        <param name="pilot"/>
      </params>
      <actions>
        <do_if value="not global.$GT_PilotsByStable?">
          <set_value name="global.$GT_PilotsByStable" exact="table[]"/>
        </do_if>
        <do_if value="$pilot and $pilot.exists and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="$stable" exact="if global.$GT_Pilots.{$pilot}.$StableIdentity? then global.$GT_Pilots.{$pilot}.$StableIdentity else ''"/>
          <do_if value="$stable == ''">
            <run_actions ref="Compute_Pilot_Stable_Key" result="$stable">
              <param name="pilot" value="$pilot"/>
            </run_actions>
            <do_if value="$stable != ''">
              <set_value name="global.$GT_Pilots.{$pilot}.$StableIdentity" exact="$stable"/>
            </do_if>
          </do_if>
          <do_if value="$stable != ''">
            <do_if value="$pilot.seed?">
              <do_if value="not global.$GT_PilotsByStable.$s?">
                <set_value name="global.$GT_PilotsByStable.$s" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_PilotsByStable.$s.{$pilot.seed}" exact="$pilot"/>
            </do_if>
            <do_elseif value="$pilot.idcode? and $pilot.idcode != ''">
              <do_if value="not global.$GT_PilotsByStable.$i?">
                <set_value name="global.$GT_PilotsByStable.$i" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_PilotsByStable.$i.{$pilot.idcode}" exact="$pilot"/>
            </do_elseif>
          </do_if>
        </do_if>
      </actions>
    </library>

    <!-- Remove transient destroy/eject scratch fields after rescue rebind. -->
    <library name="Clear_Eject_Scratch_State" purpose="run_actions">
      <params>
        <param name="pilot"/>
      </params>
      <actions>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <remove_value name="global.$GT_Pilots.{$pilot}.$EjectedSector"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$LastKnownPilotRef"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$EjectTagBurstAttempt"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$RescueCandidateShips"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$EjectLogbookWritten"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$RescueLogbookWritten"/>
        </do_if>
      </actions>
    </library>

    <!-- Lookup pilot from nested stable index (X4 cannot use 's:â€¦' / 'i:â€¦' as flat table keys). -->
    <library name="Lookup_Pilot_From_Stable_Index" purpose="run_actions">
      <params>
        <param name="stableKey"/>
      </params>
      <actions>
        <set_value name="$found" exact="null"/>
        <do_if value="$stableKey != '' and global.$GT_PilotsByStable?">
          <do_if value="global.$GT_PilotsByStable.$s? and global.$GT_PilotsByStable.$s.keys.count gt 0">
            <do_all exact="global.$GT_PilotsByStable.$s.keys.count" counter="$si">
              <set_value name="$seedKey" exact="global.$GT_PilotsByStable.$s.keys.{$si}"/>
              <do_if value="'s:' + $seedKey == $stableKey and global.$GT_PilotsByStable.$s.{$seedKey}.exists">
                <set_value name="$found" exact="global.$GT_PilotsByStable.$s.{$seedKey}"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="not $found and global.$GT_PilotsByStable.$i? and global.$GT_PilotsByStable.$i.keys.count gt 0">
            <do_all exact="global.$GT_PilotsByStable.$i.keys.count" counter="$ii">
              <set_value name="$idKey" exact="global.$GT_PilotsByStable.$i.keys.{$ii}"/>
              <do_if value="'i:' + $idKey == $stableKey and global.$GT_PilotsByStable.$i.{$idKey}.exists">
                <set_value name="$found" exact="global.$GT_PilotsByStable.$i.{$idKey}"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <return value="$found"/>
      </actions>
    </library>

    <!-- All onboard personnel template keys (pilot seat + unassigned + service + marine). -->
    <library name="Collect_Ship_Personnel_Templates" purpose="run_actions">
      <params>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$pool" exact="[]"/>
        <do_if value="$ship and $ship.exists">
          <do_if value="$ship.people? and $ship.people.list?">
            <do_all exact="$ship.people.list.count" counter="$pi">
              <append_to_list name="$pool" exact="$ship.people.list.{$pi}"/>
            </do_all>
          </do_if>
          <do_if value="$ship.people? and $ship.people.{entityrole.unassigned}? and $ship.people.{entityrole.unassigned}.list?">
            <do_all exact="$ship.people.{entityrole.unassigned}.list.count" counter="$ui">
              <append_to_list name="$pool" exact="$ship.people.{entityrole.unassigned}.list.{$ui}"/>
            </do_all>
          </do_if>
          <do_if value="$ship.people? and $ship.people.{entityrole.service}? and $ship.people.{entityrole.service}.list?">
            <do_all exact="$ship.people.{entityrole.service}.list.count" counter="$si">
              <append_to_list name="$pool" exact="$ship.people.{entityrole.service}.list.{$si}"/>
            </do_all>
          </do_if>
          <do_if value="$ship.people? and $ship.people.{entityrole.marine}? and $ship.people.{entityrole.marine}.list?">
            <do_all exact="$ship.people.{entityrole.marine}.list.count" counter="$mi">
              <append_to_list name="$pool" exact="$ship.people.{entityrole.marine}.list.{$mi}"/>
            </do_all>
          </do_if>
          <do_if value="$ship.availablepeople? and $ship.availablepeople.list?">
            <do_all exact="$ship.availablepeople.list.count" counter="$ai">
              <append_to_list name="$pool" exact="$ship.availablepeople.list.{$ai}"/>
            </do_all>
          </do_if>
          <do_if value="$ship.availablepeople? and $ship.availablepeople.{entityrole.unassigned}? and $ship.availablepeople.{entityrole.unassigned}.list?">
            <do_all exact="$ship.availablepeople.{entityrole.unassigned}.list.count" counter="$aui">
              <append_to_list name="$pool" exact="$ship.availablepeople.{entityrole.unassigned}.list.{$aui}"/>
            </do_all>
          </do_if>
        </do_if>
        <return value="$pool"/>
      </actions>
    </library>

    <!-- Match untagged registry name against crew display names (may include (T:n) prefix). -->
    <library name="Pilot_Display_Name_Matches" purpose="run_actions">
      <params>
        <param name="displayName" default="''"/>
        <param name="originalName" default="''"/>
        <param name="taggedPilotName" default="''"/>
        <param name="pilotLevel" default="null"/>
      </params>
      <actions>
        <set_value name="$match" exact="false"/>
        <do_if value="$displayName? and $displayName != ''">
          <do_if value="$originalName != '' and $displayName == $originalName">
            <set_value name="$match" exact="true"/>
          </do_if>
          <do_if value="not $match and $taggedPilotName != '' and $displayName == $taggedPilotName">
            <set_value name="$match" exact="true"/>
          </do_if>
          <do_if value="not $match and $originalName != '' and $pilotLevel? and $pilotLevel != null and $pilotLevel ge 1">
            <set_value name="$expectedTagged" exact="'(T:' + $pilotLevel + ') ' + $originalName"/>
            <do_if value="$displayName == $expectedTagged">
              <set_value name="$match" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        <return value="$match"/>
      </actions>
    </library>

    <!-- True when a live pilot entity is the ship captain or listed in its crew pools. -->
    <library name="Pilot_Is_On_Ship" purpose="run_actions">
      <params>
        <param name="pilot"/>
        <param name="ship"/>
      </params>
      <actions>
        <set_value name="$onShip" exact="false"/>
        <do_if value="$pilot and $pilot.exists and $ship and $ship.exists">
          <do_if value="$ship.pilot? and $ship.pilot == $pilot">
            <set_value name="$onShip" exact="true"/>
          </do_if>
          <do_if value="not $onShip">
            <run_actions ref="Collect_Ship_Personnel_Templates" result="$onShipPool">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_all exact="$onShipPool.count" counter="$oi">
              <set_value name="$crewTpl" exact="$onShipPool.{$oi}"/>
              <set_value name="$crewEnt" exact="if $crewTpl and $ship.roleentity? and $ship.roleentity.{$crewTpl}? and $ship.roleentity.{$crewTpl}.exists then $ship.roleentity.{$crewTpl} else null"/>
              <do_if value="$crewEnt and $crewEnt == $pilot">
                <set_value name="$onShip" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        <return value="$onShip"/>
      </actions>
    </library>

    <!-- Stable key for a people-list template entry (seed lives on people.{template}, not the template id). -->
    <library name="Template_Stable_Key_From_Crew" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="crewTemplate"/>
      </params>
      <actions>
        <set_value name="$result" exact="''"/>
        <do_if value="$crewTemplate? and $crewTemplate != null">
          <do_if value="$ship and $ship.exists and $ship.availablepeople? and $ship.availablepeople.{$crewTemplate}? and $ship.availablepeople.{$crewTemplate}.seed?">
            <set_value name="$result" exact="'s:' + $ship.availablepeople.{$crewTemplate}.seed"/>
          </do_if>
          <do_elseif value="$ship and $ship.exists and $ship.people? and $ship.people.{$crewTemplate}? and $ship.people.{$crewTemplate}.seed?">
            <set_value name="$result" exact="'s:' + $ship.people.{$crewTemplate}.seed"/>
          </do_elseif>
          <do_elseif value="$crewTemplate.seed?">
            <set_value name="$result" exact="'s:' + $crewTemplate.seed"/>
          </do_elseif>
          <do_else>
            <set_value name="$result" exact="'s:' + $crewTemplate"/>
          </do_else>
        </do_if>
        <return value="$result"/>
      </actions>
    </library>

    <!-- Tiered live-pilot resolution: last-known ref â†’ stable index â†’ sector spacesuit scan. -->
    <library name="Resolve_Live_Pilot_Tiered" purpose="run_actions">
      <params>
        <param name="livePilotHint" default="null"/>
        <param name="stableKey" default="''"/>
        <param name="sector" default="null"/>
        <param name="ship" default="null"/>
        <param name="originalName" default="''"/>
        <param name="taggedPilotName" default="''"/>
        <param name="pilotLevel" default="null"/>
      </params>
      <actions>
        <set_value name="$resolved" exact="null"/>
        <set_value name="$matchCount" exact="0"/>

        <do_if value="$livePilotHint and $livePilotHint.exists? and $livePilotHint.exists">
          <set_value name="$hintOk" exact="true"/>
          <do_if value="$ship and $ship.exists">
            <run_actions ref="Pilot_Is_On_Ship" result="$hintOk">
              <param name="pilot" value="$livePilotHint"/>
              <param name="ship" value="$ship"/>
            </run_actions>
          </do_if>
          <do_if value="$hintOk">
            <set_value name="$resolved" exact="$livePilotHint"/>
            <set_value name="$matchCount" exact="1"/>
          </do_if>
        </do_if>

        <do_if value="not $resolved and $stableKey != ''">
          <run_actions ref="Lookup_Pilot_From_Stable_Index" result="$indexPilot">
            <param name="stableKey" value="$stableKey"/>
          </run_actions>
          <do_if value="$indexPilot and $indexPilot.exists">
            <set_value name="$indexOnShip" exact="true"/>
            <do_if value="$ship and $ship.exists">
              <run_actions ref="Pilot_Is_On_Ship" result="$indexOnShip">
                <param name="pilot" value="$indexPilot"/>
                <param name="ship" value="$ship"/>
              </run_actions>
            </do_if>
            <do_if value="$indexOnShip">
              <set_value name="$resolved" exact="$indexPilot"/>
              <set_value name="$matchCount" exact="1"/>
            </do_if>
          </do_if>
          <do_if value="not $resolved and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
            <do_all exact="global.$GT_Pilots.keys.count" counter="$ri">
              <set_value name="$regKey" exact="global.$GT_Pilots.keys.{$ri}"/>
              <do_if value="$regKey and $regKey.exists and global.$GT_Pilots.{$regKey}.$StableIdentity? and global.$GT_Pilots.{$regKey}.$StableIdentity == $stableKey">
                <set_value name="$regOnShip" exact="true"/>
                <do_if value="$ship and $ship.exists">
                  <run_actions ref="Pilot_Is_On_Ship" result="$regOnShip">
                    <param name="pilot" value="$regKey"/>
                    <param name="ship" value="$ship"/>
                  </run_actions>
                </do_if>
                <do_if value="$regOnShip">
                  <set_value name="$resolved" exact="$regKey"/>
                  <set_value name="$matchCount" exact="$matchCount + 1"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$matchCount != 1">
              <set_value name="$resolved" exact="null"/>
            </do_if>
          </do_if>
        </do_if>

        <do_if value="not $resolved and $stableKey != '' and $sector and $sector.exists">
          <set_value name="$spacesuits" exact="[]"/>
          <find_ship_by_true_owner name="$spacesuits" class="class.spacesuit" faction="faction.player" space="$sector" multiple="true"/>
          <do_all exact="$spacesuits.count" counter="$si">
            <set_value name="$suit" exact="$spacesuits.{$si}"/>
            <set_value name="$suitPilot" exact="if $suit.pilot? and $suit.pilot.exists then $suit.pilot else null"/>
            <do_if value="$suitPilot">
              <run_actions ref="Compute_Pilot_Stable_Key" result="$suitStable">
                <param name="pilot" value="$suitPilot"/>
              </run_actions>
              <do_if value="$suitStable == $stableKey">
                <set_value name="$resolved" exact="$suitPilot"/>
                <set_value name="$matchCount" exact="$matchCount + 1"/>
              </do_if>
            </do_if>
          </do_all>
          <do_if value="$matchCount != 1">
            <set_value name="$resolved" exact="null"/>
          </do_if>
          <set_value name="$matchCount" exact="0"/>
        </do_if>

        <do_if value="not $resolved and $stableKey != '' and $ship and $ship.exists">
          <set_value name="$matchCount" exact="0"/>
          <do_if value="$ship.pilot? and $ship.pilot.exists">
            <run_actions ref="Compute_Pilot_Stable_Key" result="$shipPilotStable">
              <param name="pilot" value="$ship.pilot"/>
            </run_actions>
            <do_if value="$shipPilotStable == $stableKey">
              <set_value name="$resolved" exact="$ship.pilot"/>
              <set_value name="$matchCount" exact="1"/>
            </do_if>
          </do_if>
          <do_if value="not $resolved">
            <run_actions ref="Collect_Ship_Personnel_Templates" result="$crewPool">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_all exact="$crewPool.count" counter="$ci">
              <set_value name="$crew" exact="$crewPool.{$ci}"/>
              <set_value name="$crewEntity" exact="if $crew and $ship.roleentity? and $ship.roleentity.{$crew}? and $ship.roleentity.{$crew}.exists then $ship.roleentity.{$crew} else null"/>
              <set_value name="$crewStableMatch" exact="false"/>
              <do_if value="$crewEntity and $livePilotHint and $crewEntity == $livePilotHint">
                <set_value name="$crewStableMatch" exact="true"/>
              </do_if>
              <do_if value="not $crewStableMatch and $stableKey != ''">
                <run_actions ref="Template_Stable_Key_From_Crew" result="$crewTemplateStable">
                  <param name="ship" value="$ship"/>
                  <param name="crewTemplate" value="$crew"/>
                </run_actions>
                <do_if value="$crewTemplateStable == $stableKey">
                  <set_value name="$crewStableMatch" exact="true"/>
                </do_if>
                <do_if value="not $crewStableMatch and $crewEntity">
                  <run_actions ref="Compute_Pilot_Stable_Key" result="$crewStableEnt">
                    <param name="pilot" value="$crewEntity"/>
                  </run_actions>
                  <do_if value="$crewStableEnt == $stableKey">
                    <set_value name="$crewStableMatch" exact="true"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_if value="not $crewStableMatch and $originalName != '' and $ship.people? and $ship.people.{$crew}? and $ship.people.{$crew}.name?">
                <run_actions ref="Pilot_Display_Name_Matches" result="$crewStableMatch">
                  <param name="displayName" value="$ship.people.{$crew}.name"/>
                  <param name="originalName" value="$originalName"/>
                  <param name="taggedPilotName" value="$taggedPilotName"/>
                  <param name="pilotLevel" value="$pilotLevel"/>
                </run_actions>
              </do_if>
              <do_if value="not $crewStableMatch and $originalName != '' and $crewEntity and $crewEntity.name?">
                <run_actions ref="Pilot_Display_Name_Matches" result="$crewStableMatch">
                  <param name="displayName" value="$crewEntity.name"/>
                  <param name="originalName" value="$originalName"/>
                  <param name="taggedPilotName" value="$taggedPilotName"/>
                  <param name="pilotLevel" value="$pilotLevel"/>
                </run_actions>
              </do_if>
              <do_if value="not $crewStableMatch and $originalName != '' and $ship.availablepeople? and $ship.availablepeople.{$crew}? and $ship.availablepeople.{$crew}.name?">
                <run_actions ref="Pilot_Display_Name_Matches" result="$crewStableMatch">
                  <param name="displayName" value="$ship.availablepeople.{$crew}.name"/>
                  <param name="originalName" value="$originalName"/>
                  <param name="taggedPilotName" value="$taggedPilotName"/>
                  <param name="pilotLevel" value="$pilotLevel"/>
                </run_actions>
              </do_if>
              <do_if value="$crewStableMatch and not ($crewEntity and $crewEntity.exists) and $crew and $ship.roleentity? and $ship.roleentity.{$crew}? and $ship.roleentity.{$crew}.exists">
                <set_value name="$crewEntity" exact="$ship.roleentity.{$crew}"/>
              </do_if>
              <do_if value="$crewStableMatch">
                <do_if value="$crewEntity">
                  <set_value name="$resolved" exact="$crewEntity"/>
                  <set_value name="$matchCount" exact="$matchCount + 1"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$matchCount != 1">
              <set_value name="$resolved" exact="null"/>
            </do_if>
          </do_if>
        </do_if>

        <return value="table[$Pilot = $resolved, $MatchCount = $matchCount]"/>
      </actions>
    </library>

    <!-- Sole identity-recovery path: migrate registry key + maintain stable index. -->
    <library name="Rebind_Pilot_Registry" purpose="run_actions">
      <params>
        <param name="livePilot" default="null"/>
        <param name="registryPilotHint" default="null"/>
        <param name="stableKey" default="''"/>
        <param name="ship" default="null"/>
        <param name="template" default="null"/>
        <param name="resolveTiered" default="false"/>
        <param name="sector" default="null"/>
      </params>
      <actions>
        <set_value name="$targetPilot" exact="null"/>
        <set_value name="$rebound" exact="false"/>

        <do_if value="$livePilot and $livePilot.exists? and $livePilot.exists">
          <set_value name="$targetPilot" exact="$livePilot"/>
        </do_if>

        <do_if value="not $targetPilot and $resolveTiered">
          <run_actions ref="Resolve_Live_Pilot_Tiered" result="$tierResult">
            <param name="livePilotHint" value="$registryPilotHint"/>
            <param name="stableKey" value="$stableKey"/>
            <param name="sector" value="$sector"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$tierResult.$Pilot? and $tierResult.$Pilot.exists">
            <set_value name="$targetPilot" exact="$tierResult.$Pilot"/>
          </do_if>
        </do_if>

        <do_if value="not $targetPilot and $stableKey != '' and $ship and $ship.exists">
          <do_if value="$template? and $template != null and $ship.roleentity? and $ship.roleentity.{$template}? and $ship.roleentity.{$template}.exists">
            <set_value name="$targetPilot" exact="$ship.roleentity.{$template}"/>
          </do_if>
        </do_if>

        <do_if value="not $targetPilot">
          <return value="table[$Success = false, $Pilot = null, $Rebound = false]"/>
        </do_if>

        <do_if value="$stableKey == ''">
          <run_actions ref="Compute_Pilot_Stable_Key" result="$stableKey">
            <param name="pilot" value="$targetPilot"/>
          </run_actions>
        </do_if>

        <set_value name="$registryKey" exact="null"/>
        <do_if value="$registryPilotHint and global.$GT_Pilots? and global.$GT_Pilots.{$registryPilotHint}?">
          <set_value name="$registryKey" exact="$registryPilotHint"/>
        </do_if>
        <do_elseif value="$stableKey != '' and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <set_value name="$regMatchCount" exact="0"/>
          <do_all exact="global.$GT_Pilots.keys.count" counter="$rk">
            <set_value name="$candKey" exact="global.$GT_Pilots.keys.{$rk}"/>
            <do_if value="global.$GT_Pilots.{$candKey}.$StableIdentity? and global.$GT_Pilots.{$candKey}.$StableIdentity == $stableKey">
              <do_if value="$candKey.exists">
                <set_value name="$registryKey" exact="$candKey"/>
                <set_value name="$regMatchCount" exact="$regMatchCount + 1"/>
              </do_if>
              <do_elseif value="not $registryKey? or $registryKey == null">
                <set_value name="$registryKey" exact="$candKey"/>
                <set_value name="$regMatchCount" exact="$regMatchCount + 1"/>
              </do_elseif>
            </do_if>
          </do_all>
          <do_if value="$regMatchCount gt 1 and $targetPilot.exists">
            <set_value name="$registryKey" exact="null"/>
            <do_all exact="global.$GT_Pilots.keys.count" counter="$rk2">
              <set_value name="$candKey2" exact="global.$GT_Pilots.keys.{$rk2}"/>
              <do_if value="$candKey2 == $targetPilot">
                <set_value name="$registryKey" exact="$candKey2"/>
              </do_if>
            </do_all>
          </do_if>
        </do_elseif>

        <do_if value="$registryKey and $registryKey != $targetPilot and global.$GT_Pilots.{$registryKey}? and not global.$GT_Pilots.{$targetPilot}?">
          <set_value name="global.$GT_Pilots.{$targetPilot}" exact="global.$GT_Pilots.{$registryKey}"/>
          <remove_value name="global.$GT_Pilots.{$registryKey}"/>
          <set_value name="$rebound" exact="true"/>
        </do_if>
        <do_elseif value="$registryKey and $registryKey != $targetPilot and global.$GT_Pilots.{$registryKey}? and global.$GT_Pilots.{$targetPilot}?">
          <remove_value name="global.$GT_Pilots.{$registryKey}"/>
          <set_value name="$rebound" exact="true"/>
        </do_elseif>

        <do_if value="not global.$GT_Pilots?">
          <set_value name="global.$GT_Pilots" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Pilots.{$targetPilot}?">
          <set_value name="global.$GT_Pilots.{$targetPilot}" exact="table[]"/>
        </do_if>

        <run_actions ref="Ensure_Pilot_Fields">
          <param name="pilot" value="$targetPilot"/>
        </run_actions>
        <do_if value="$targetPilot.idcode?">
          <set_value name="global.$GT_Pilots.{$targetPilot}.$PilotID" exact="$targetPilot.idcode"/>
        </do_if>
        <run_actions ref="Sync_Stable_Identity_Index">
          <param name="pilot" value="$targetPilot"/>
        </run_actions>

        <return value="table[$Success = true, $Pilot = $targetPilot, $Rebound = $rebound]"/>
      </actions>
    </library>
    
    <!-- Initialize Pilot Data Structure -->
    <library name="Initialize_Pilot_Data" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to initialize"/>
        <param name="ship" comment="Associated ship"/>
      </params>
      <actions>
        <!-- Initialize global registry if needed -->
        <do_if value="not global.$GT_Pilots?">
          <set_value name="global.$GT_Pilots" exact="table[]"/>
        </do_if>
        
        <!-- Check if pilot exists and if they were paused -->
        <set_value name="$pilotExists" exact="global.$GT_Pilots.{$pilot}?"/>
        <set_value name="$wasPaused" exact="false"/>
        <set_value name="$wasNewPilot" exact="false"/>
        <set_value name="$allowActiveIdentityRecovery" exact="false"/>
        <do_if value="$ship? and md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus?">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$initPeStatus">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$initPeStatus.$ShouldKeepPE">
            <set_value name="$allowActiveIdentityRecovery" exact="true"/>
          </do_if>
        </do_if>
        
        <do_if value="$pilotExists">
          <!-- Pilot exists - check if they were paused -->
          <!-- CRITICAL: If Status is missing, treat as paused to preserve XP (defensive check) -->
          <set_value name="$pilotStatus" exact="null"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$Status?">
            <set_value name="$pilotStatus" exact="global.$GT_Pilots.{$pilot}.$Status"/>
          </do_if>
          
          <!-- If pilot exists but Status is missing/null, treat as paused to preserve XP -->
          <!-- This prevents accidental XP loss if Status field was somehow cleared -->
          <do_if value="not $pilotStatus? or $pilotStatus == 'paused' or $pilotStatus == 'ejected'">
            <set_value name="$wasPaused" exact="true"/>
            <set_value name="$wasEjectedStatus" exact="$pilotStatus == 'ejected'"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Reactivating PAUSED/EJECTED pilot: ' + $pilot.name + ' (status=' + (if $pilotStatus? then $pilotStatus else 'NONE') + ', XP: ' + (if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 0) + ', Level: ' + (if global.$GT_Pilots.{$pilot}.$Level? then global.$GT_Pilots.{$pilot}.$Level else 1) + ')'" chance="100"/>
            </do_if>
            
            <!-- Restore pilot to active status with all previous data intact -->
            <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'active'"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$ResumedTime" exact="player.age"/>
            <do_if value="$wasEjectedStatus">
              <set_value name="global.$GT_Pilots.{$pilot}.$ResumedFromEject" exact="true"/>
            </do_if>
            <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
            <do_if value="$pilot.idcode?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="$pilot.idcode"/>
            </do_if>
            <do_elseif value="not global.$GT_Pilots.{$pilot}.$PilotID?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="''"/>
            </do_elseif>
            
            <!-- Clean up pause-related fields -->
            <remove_value name="global.$GT_Pilots.{$pilot}.$PausedTime"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$PausedReason"/>
            <run_actions ref="Clear_Eject_Scratch_State">
              <param name="pilot" value="$pilot"/>
            </run_actions>
            <run_actions ref="Ensure_Pilot_Fields">
              <param name="pilot" value="$pilot"/>
            </run_actions>
            
            <!-- Original ship name storage handled by Register_Pilot (per ship, not per pilot) -->
            
            <!-- Restore management skill level based on XP (not stored Level) -->
            <!-- Calculate current skill level from preserved XP -->
            <set_value name="$pilotXP" exact="0"/>
            <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
              <set_value name="$pilotXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            </do_if>
            <run_actions ref="Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
              <param name="pilot" value="$pilot"/>
              <param name="xp" value="$pilotXP"/>
            </run_actions>
            <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
            <do_if value="$currentSkillLevel gt $vanillaMgmtLevel">
              <set_skill entity="$pilot" type="skilltype.management" exact="$currentSkillLevel"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Synced vanilla management skill for reactivated pilot ' + $pilot.name + ': vanilla=' + $vanillaMgmtLevel + ', gt=' + $currentSkillLevel + ' (raise-only)'" chance="100"/>
            </do_if>
            
            <!-- Update stored Level field to match calculated level -->
            <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$currentSkillLevel"/>
            
            <!-- Restore paused training state if preserved during cleanup (guarded against stale post-completion markers) -->
            <run_actions ref="md.GT_CoreSystem.RestorePausedTrainingStateIfNeeded">
              <param name="pilot" value="$pilot"/>
              <param name="debugLabel" value="'TRAINING STATE RESTORED'"/>
            </run_actions>
            
            <return value="false"/>  <!-- Returns false because pilot was reactivated, not newly initialized -->
          </do_if>
          <do_else>
            <!-- Pilot exists and is already active - update ship association AND restore skill level -->
            <!-- Also restore skill level for already-active pilots (they might have lost it) -->
            <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
            <do_if value="$pilot.idcode?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="$pilot.idcode"/>
            </do_if>
            <do_elseif value="not global.$GT_Pilots.{$pilot}.$PilotID?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="''"/>
            </do_elseif>
            
            <!-- Restore management skill level based on XP -->
            <set_value name="$pilotXP" exact="0"/>
            <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
              <set_value name="$pilotXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            </do_if>
            <run_actions ref="Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
              <param name="pilot" value="$pilot"/>
              <param name="xp" value="$pilotXP"/>
            </run_actions>
            <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
            <do_if value="$currentSkillLevel gt $vanillaMgmtLevel">
              <set_skill entity="$pilot" type="skilltype.management" exact="$currentSkillLevel"/>
            </do_if>
            <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$currentSkillLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Synced vanilla management skill for active pilot ' + $pilot.name + ': vanilla=' + $vanillaMgmtLevel + ', gt=' + $currentSkillLevel + ' (raise-only)'" chance="100"/>
            </do_if>
            
            <return value="false"/>  <!-- Returns false because pilot already existed -->
          </do_else>
        </do_if>
        <do_else>
          <!-- Recovery path for vanilla pilot reassignment:
               if the pilot object key changed, try to reattach the matching GT pilot record.
               Pilot redistribution can swap active captains and still replace the crew actor object. -->
          <set_value name="$recoveredFromPilot" exact="null"/>
          <!-- Tier 0: unique match on $StableIdentity (seed/id-based, survives idcode changes). -->
          <run_actions ref="Compute_Pilot_Stable_Key" result="$incomingStable">
            <param name="pilot" value="$pilot"/>
          </run_actions>
          <set_value name="$stableRecovered" exact="false"/>
          <do_if value="$incomingStable != '' and global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
            <set_value name="$stableMatchCount" exact="0"/>
            <set_value name="$stableMatchPilot" exact="null"/>
            <set_value name="$stableKeys" exact="global.$GT_Pilots.keys.list"/>
            <do_all exact="$stableKeys.count" counter="$sxi">
              <set_value name="$candSt" exact="$stableKeys.{$sxi}"/>
              <do_if value="$candSt and $candSt != $pilot and global.$GT_Pilots.{$candSt}?">
                <do_if value="global.$GT_Pilots.{$candSt}.$StableIdentity? and global.$GT_Pilots.{$candSt}.$StableIdentity == $incomingStable">
                  <set_value name="$stableMatchCount" exact="$stableMatchCount + 1"/>
                  <set_value name="$stableMatchPilot" exact="$candSt"/>
                </do_if>
              </do_if>
            </do_all>
            <do_if value="$stableMatchCount == 1 and $stableMatchPilot">
              <set_value name="$stableWasEjected" exact="global.$GT_Pilots.{$stableMatchPilot}.$Status? and global.$GT_Pilots.{$stableMatchPilot}.$Status == 'ejected'"/>
              <set_value name="global.$GT_Pilots.{$pilot}" exact="global.$GT_Pilots.{$stableMatchPilot}"/>
              <remove_value name="global.$GT_Pilots.{$stableMatchPilot}"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'active'"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$ResumedTime" exact="player.age"/>
              <do_if value="$stableWasEjected">
                <set_value name="global.$GT_Pilots.{$pilot}.$ResumedFromEject" exact="true"/>
              </do_if>
              <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
              <do_if value="$pilot.idcode?">
                <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="$pilot.idcode"/>
              </do_if>
              <do_elseif value="not global.$GT_Pilots.{$pilot}.$PilotID?">
                <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="''"/>
              </do_elseif>
              <remove_value name="global.$GT_Pilots.{$pilot}.$PausedTime"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$PausedReason"/>
              <do_if value="$stableWasEjected">
                <run_actions ref="Clear_Eject_Scratch_State">
                  <param name="pilot" value="$pilot"/>
                </run_actions>
              </do_if>
              <set_value name="$recoveredFromPilot" exact="$stableMatchPilot"/>
              <set_value name="$stableRecovered" exact="true"/>
              <run_actions ref="Ensure_Pilot_Fields">
                <param name="pilot" value="$pilot"/>
              </run_actions>
              <set_value name="$pilotXP" exact="0"/>
              <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
                <set_value name="$pilotXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
              </do_if>
              <run_actions ref="Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$pilotXP"/>
              </run_actions>
              <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
              <do_if value="$currentSkillLevel gt $vanillaMgmtLevel">
                <set_skill entity="$pilot" type="skilltype.management" exact="$currentSkillLevel"/>
              </do_if>
              <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$currentSkillLevel"/>
              <run_actions ref="Update_Pilot_Name_Tag">
                <param name="pilot" value="$pilot"/>
                <param name="level" value="$currentSkillLevel"/>
              </run_actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-ShipMgmt] Recovered pilot by StableIdentity: ship=' + $ship.idcode + ' pilot=' + $pilot.name + ' stable=' + $incomingStable + ' XP=' + (if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 0)" chance="100"/>
              </do_if>
              <return value="false"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0 and $pilot and $ship and not $stableRecovered">
            <set_value name="$currentPilotName" exact="$pilot.name"/>
            <set_value name="$currentPilotID" exact="if $pilot.idcode? then $pilot.idcode else ''"/>
            <set_value name="$candidateKeys" exact="global.$GT_Pilots.keys.list"/>
            <set_value name="$bestCandidate" exact="null"/>
            <set_value name="$bestCandidateFound" exact="false"/>
            <set_value name="$bestCandidateNameDbg" exact="'NONE'"/>
            <set_value name="$bestScore" exact="0"/>
            <set_value name="$bestScoreCount" exact="0"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Identity recovery start ship=' + $ship.idcode + ' pilot=' + $currentPilotName + ' pilotId=' + (if $currentPilotID != '' then $currentPilotID else 'NONE') + ' allowActive=' + $allowActiveIdentityRecovery + ' registryCount=' + global.$GT_Pilots.keys.count" chance="100"/>
            </do_if>
            <do_all exact="$candidateKeys.count" counter="$ci">
              <set_value name="$candidatePilot" exact="$candidateKeys.{$ci}"/>
              <do_if value="$candidatePilot and $candidatePilot != $pilot and global.$GT_Pilots.{$candidatePilot}?">
                <set_value name="$candidateStatus" exact="if global.$GT_Pilots.{$candidatePilot}.$Status? then global.$GT_Pilots.{$candidatePilot}.$Status else ''"/>
                <do_if value="$candidateStatus == 'paused' or $candidateStatus == 'ejected' or ($allowActiveIdentityRecovery and $candidateStatus == 'active')">
                  <set_value name="$score" exact="0"/>
                  <set_value name="$candidatePilotNameDbg" exact="'NONE'"/>
                  <do_if value="global.$GT_Pilots.{$candidatePilot}.$OriginalPilotName? and global.$GT_Pilots.{$candidatePilot}.$OriginalPilotName != ''">
                    <set_value name="$candidatePilotNameDbg" exact="global.$GT_Pilots.{$candidatePilot}.$OriginalPilotName"/>
                  </do_if>
                  <do_elseif value="global.$GT_Pilots.{$candidatePilot}.$PilotName? and global.$GT_Pilots.{$candidatePilot}.$PilotName != ''">
                    <set_value name="$candidatePilotNameDbg" exact="global.$GT_Pilots.{$candidatePilot}.$PilotName"/>
                  </do_elseif>
                  <do_elseif value="$candidatePilot.exists? and $candidatePilot.exists and $candidatePilot.name?">
                    <set_value name="$candidatePilotNameDbg" exact="$candidatePilot.name"/>
                  </do_elseif>
                  
                  <!-- Strongest signal: same persistent StableIdentity (seed / fallback idcode). -->
                  <do_if value="$incomingStable != '' and global.$GT_Pilots.{$candidatePilot}.$StableIdentity? and global.$GT_Pilots.{$candidatePilot}.$StableIdentity == $incomingStable">
                    <set_value name="$score" exact="$score + 50"/>
                  </do_if>
                  
                  <!-- Primary identity match: persistent pilot id survives rename/tag changes. -->
                  <do_if value="$currentPilotID != '' and global.$GT_Pilots.{$candidatePilot}.$PilotID? and global.$GT_Pilots.{$candidatePilot}.$PilotID == $currentPilotID">
                    <set_value name="$score" exact="$score + 20"/>
                  </do_if>
                  
                  <!-- Strong signal: candidate was last associated with this ship id. -->
                  <do_if value="global.$GT_Pilots.{$candidatePilot}.$ShipID? and global.$GT_Pilots.{$candidatePilot}.$ShipID == $ship.idcode">
                    <set_value name="$score" exact="$score + 4"/>
                  </do_if>
                  
                  <!-- Legacy-save compatibility only: old records may not have $PilotID yet. -->
                  <do_if value="$currentPilotID == '' or not global.$GT_Pilots.{$candidatePilot}.$PilotID?">
                    <do_if value="global.$GT_Pilots.{$candidatePilot}.$OriginalPilotName? and global.$GT_Pilots.{$candidatePilot}.$OriginalPilotName == $currentPilotName">
                      <set_value name="$score" exact="$score + 5"/>
                    </do_if>
                    <do_elseif value="global.$GT_Pilots.{$candidatePilot}.$PilotName? and global.$GT_Pilots.{$candidatePilot}.$PilotName == $currentPilotName">
                      <set_value name="$score" exact="$score + 4"/>
                    </do_elseif>
                  </do_if>
                  
                  <do_if value="$score gt $bestScore">
                    <set_value name="$bestScore" exact="$score"/>
                    <set_value name="$bestCandidate" exact="$candidatePilot"/>
                    <set_value name="$bestCandidateFound" exact="true"/>
                    <set_value name="$bestCandidateNameDbg" exact="$candidatePilotNameDbg"/>
                    <set_value name="$bestScoreCount" exact="1"/>
                  </do_if>
                  <do_elseif value="$score gt 0 and $score == $bestScore">
                    <set_value name="$bestScoreCount" exact="$bestScoreCount + 1"/>
                  </do_elseif>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $score gt 0">
                    <debug_text text="'[GT-ShipMgmt] Identity recovery candidate ship=' + $ship.idcode + ' currentPilot=' + $currentPilotName + ' candidate=' + $candidatePilotNameDbg + ' candidateStatus=' + $candidateStatus + ' candidatePilotId=' + (if global.$GT_Pilots.{$candidatePilot}.$PilotID? and global.$GT_Pilots.{$candidatePilot}.$PilotID != '' then global.$GT_Pilots.{$candidatePilot}.$PilotID else 'NONE') + ' candidateShipId=' + (if global.$GT_Pilots.{$candidatePilot}.$ShipID? then global.$GT_Pilots.{$candidatePilot}.$ShipID else 'NONE') + ' score=' + $score" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_all>
            
            <!-- Require a unique, high-confidence match to avoid wrong XP transfer. -->
            <do_if value="$bestCandidateFound and $bestScoreCount == 1 and $bestScore ge 8 and global.$GT_Pilots.{$bestCandidate}?">
              <set_value name="global.$GT_Pilots.{$pilot}" exact="global.$GT_Pilots.{$bestCandidate}"/>
              <remove_value name="global.$GT_Pilots.{$bestCandidate}"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'active'"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$ResumedTime" exact="player.age"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
              <do_if value="$pilot.idcode?">
                <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="$pilot.idcode"/>
              </do_if>
              <do_elseif value="not global.$GT_Pilots.{$pilot}.$PilotID?">
                <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="''"/>
              </do_elseif>
              <remove_value name="global.$GT_Pilots.{$pilot}.$PausedTime"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$PausedReason"/>
              <set_value name="$recoveredFromPilot" exact="$bestCandidate"/>
              
              <run_actions ref="Ensure_Pilot_Fields">
                <param name="pilot" value="$pilot"/>
              </run_actions>
              
              <set_value name="$pilotXP" exact="0"/>
              <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
                <set_value name="$pilotXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
              </do_if>
              <run_actions ref="Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$pilotXP"/>
              </run_actions>
              <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
              <do_if value="$currentSkillLevel gt $vanillaMgmtLevel">
                <set_skill entity="$pilot" type="skilltype.management" exact="$currentSkillLevel"/>
              </do_if>
              <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$currentSkillLevel"/>
              <run_actions ref="Update_Pilot_Name_Tag">
                <param name="pilot" value="$pilot"/>
                <param name="level" value="$currentSkillLevel"/>
              </run_actions>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-ShipMgmt] Recovered pilot identity after vanilla reassignment: new=' + $pilot.name + ', recoveredFrom=' + $bestCandidateNameDbg + ', XP=' + (if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 0) + ', score=' + $bestScore" chance="100"/>
              </do_if>
              
              <return value="false"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Identity recovery no match ship=' + $ship.idcode + ' pilot=' + $currentPilotName + ' pilotId=' + (if $currentPilotID != '' then $currentPilotID else 'NONE') + ' bestCandidate=' + $bestCandidateNameDbg + ' bestScore=' + $bestScore + ' scoreCount=' + $bestScoreCount + ' allowActive=' + $allowActiveIdentityRecovery" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Initialize from scratch - ONLY if pilot truly doesn't exist -->
          <!-- CRITICAL: Double-check pilot doesn't exist before overwriting (defensive check) -->
          <do_if value="global.$GT_Pilots.{$pilot}?">
            <!-- Pilot exists but wasn't detected - this should never happen, but preserve XP if it does -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] WARNING: Pilot ' + $pilot.name + ' exists but was treated as new - preserving existing XP: ' + (if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 0)" chance="100"/>
            </do_if>
            <!-- Don't overwrite - treat as existing pilot instead -->
            <set_value name="$wasNewPilot" exact="false"/>
            <!-- Update ship association only -->
            <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
            <do_if value="$pilot.idcode?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="$pilot.idcode"/>
            </do_if>
            <do_elseif value="not global.$GT_Pilots.{$pilot}.$PilotID?">
              <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="''"/>
            </do_elseif>
            <return value="false"/>
          </do_if>
          
          <!-- Pilot truly doesn't exist - initialize from scratch -->
          <set_value name="$wasNewPilot" exact="true"/>
          <set_value name="global.$GT_Pilots.{$pilot}" exact="table[]"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="0"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="1"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TotalTrades" exact="0"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TotalProfit" exact="0Cr"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="[]"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$PilotName" exact="$pilot.name"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$OriginalPilotName" exact="$pilot.name"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="if $pilot.idcode? then $pilot.idcode else ''"/>
          <run_actions ref="Compute_Pilot_Stable_Key" result="$initStable">
            <param name="pilot" value="$pilot"/>
          </run_actions>
          <do_if value="$initStable != ''">
            <set_value name="global.$GT_Pilots.{$pilot}.$StableIdentity" exact="$initStable"/>
          </do_if>
          <set_value name="global.$GT_Pilots.{$pilot}.$RegisterTime" exact="player.age"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$AssociatedShip" exact="$ship"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$Ship" exact="$ship"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$ShipID" exact="$ship.idcode"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'active'"/>
          
          <!-- Original ship name storage handled by Register_Pilot (per ship, not per pilot) -->
          
          <!-- Set initial vanilla management skill only if lower (never lower/reset vanilla). -->
          <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
          <do_if value="$vanillaMgmtLevel lt 1">
            <set_skill entity="$pilot" type="skilltype.management" exact="1"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Initialized NEW pilot record ship=' + $ship.idcode + ' pilot=' + $pilot.name + ' pilotId=' + (if $pilot.idcode? then $pilot.idcode else 'NONE') + ' stable=' + (if $initStable != '' then $initStable else 'NONE') + ' xp=0 level=1 allowActiveRecovery=' + $allowActiveIdentityRecovery" chance="100"/>
          </do_if>
          
          <return value="true"/>  <!-- Returns true if pilot was newly initialized -->
        </do_else>
      </actions>
    </library>
    
    <!-- Update Ship Name for Pilot -->
    <library name="Update_Pilot_Ship_Name" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to update ship name for"/>
        <param name="ship" comment="Ship to rename"/>
        <param name="forceUpdate" default="false" comment="Force update even if pilot data missing"/>
      </params>
      <actions>
        <!-- Check if pilot is registered -->
        <do_if value="not global.$GT_Pilots.{$pilot}?">
          <do_if value="$forceUpdate">
            <!-- Force update with default values -->
            <run_actions ref="Calculate_Rank_Title" result="$rankTitle">
              <param name="skillLevel" value="1"/>
            </run_actions>
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[$Ship=$ship, $pilot=$pilot, $xp=0, $level=1, $rank=$rankTitle, $nameType='trader']"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] Cannot update ship name - pilot not registered: ' + $pilot.name" chance="100"/>
            </do_if>
            <return value="false"/>
          </do_else>
        </do_if>
        
        <!-- Get pilot data -->
        <set_value name="$currentXP" exact="0"/>
        <set_value name="$currentLevel" exact="1"/>
        <set_value name="$isBlocked" exact="false"/>
        <set_value name="$blockedLevel" exact="0"/>
        
        <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
          <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
        </do_if>
        
        <!-- Calculate skill level from XP -->
        <run_actions ref="Calculate_Skill_Level_From_XP" result="$currentLevel">
          <param name="pilot" value="$pilot"/>
          <param name="xp" value="$currentXP"/>
        </run_actions>
        
        <!-- Check if XP is blocked -->
        <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
          <set_value name="$isBlocked" exact="true"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$BlockedLevel?">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          </do_if>
        </do_if>

        <!-- Trading Academy: an academy enrollment also sets XPBlocked /
             BlockedLevel = the *future* target rank (e.g. lvl 7 course on a
             lvl 5 pilot). For the natural ladder it is fine to anticipate the
             next rank in the display, but a long-running academy course must
             not bump the pilot's visible level / rank until the course
             actually completes. While $AcademyEnrollment is set we therefore
             render at the pilot's current XP-derived level and skip the
             "blocked => target rank" anticipation. -->
        <set_value name="$isAcademyPending" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>

        <!-- Calculate rank title -->
        <set_value name="$levelForRank" exact="if ($isBlocked and not $isAcademyPending) then $blockedLevel else $currentLevel"/>
        <run_actions ref="Calculate_Rank_Title" result="$rankTitle">
          <param name="skillLevel" value="$levelForRank"/>
        </run_actions>

        <!-- Keep pilot name tag in sync with current GT level -->
        <run_actions ref="md.GT_Ship_Management.Update_Pilot_Name_Tag">
          <param name="pilot" value="$pilot"/>
          <param name="level" value="$levelForRank"/>
        </run_actions>
        
        <!-- Refresh ship name (nameType derived inside unified handler) -->
        <run_actions ref="md.GT_Ship_Management.GT_Process_Ship_Name_Refresh" result="$updateResult">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="xp" value="$currentXP"/>
          <param name="level" value="$levelForRank"/>
          <param name="rank" value="$rankTitle"/>
          <param name="nameType" value="'trader'"/>
        </run_actions>
        
        <return value="$updateResult"/>
      </actions>
    </library>
    
    <!-- Update Ship Name - Core Renaming Logic -->
    <!-- This library handles all ship renaming logic, replacing the old signal-based approach -->
    <library name="Update_Ship_Name" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to rename"/>
        <param name="pilot" default="null" comment="Pilot (optional, derived from ship if missing)"/>
        <param name="xp" default="null" comment="XP value (optional, derived from pilot if missing)"/>
        <param name="level" default="null" comment="Skill level (optional, derived from XP if missing)"/>
        <param name="rank" default="null" comment="Rank title (optional, derived from level if missing)"/>
        <param name="nameType" default="'trader'" comment="Name type: trader/isolated/fallback/blocked/training"/>
        <param name="skillLevel" default="null" comment="Old format: skill level (for backward compatibility)"/>
        <param name="forceUpdate" default="false" comment="Force update even if renaming disabled"/>
        <param name="applyName" default="true" comment="When true, apply name with content dedupe; always returns resolved string on success"/>
      </params>
      <actions>
        <!-- Check if ship renaming is enabled -->
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and not @global.$GT_GlobalSettings.$ShipNaming.$Enabled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Ship renaming disabled in settings - skipping rename (forceUpdate ignored)'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        
        <!-- CRITICAL: Validate ship exists before proceeding -->
        <do_if value="not $ship? or not $ship.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Ship_Name: Cannot rename - ship is null or does not exist (ship=' + (if $ship? then $ship.idcode else 'NULL') + ', exists=' + (if $ship.exists then 'yes' else 'no') + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        
        <!-- Robustness: if pilot not provided, derive from ship (subordinates often signal without pilot payload) -->
        <do_if value="not $pilot? or $pilot == null">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>
        <set_value name="$pilotNameDbg" exact="if $pilot? and $pilot != null and $pilot.name? and $pilot.name != null then $pilot.name else 'NULL'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Update_Ship_Name: ship=' + (if $ship? then $ship.idcode else 'NULL') + ', pilot=' + $pilotNameDbg + ', ship.exists=' + (if $ship.exists then 'yes' else 'no')" chance="100"/>
        </do_if>
        
        <!-- Check which parameter format we're using -->
        <set_value name="$useNewFormat" exact="$nameType != 'trader' or (($xp? and $xp != null) or ($level? and $level != null) or ($rank? and $rank != null))"/>
        <do_if value="not $useNewFormat and $skillLevel?">
          <set_value name="$useNewFormat" exact="false"/>
        </do_if>
        
        <!-- Extract parameters based on format -->
        <do_if value="$useNewFormat">
          <!-- New format - use provided parameters or calculate from pilot data if missing -->
          <!-- For nameType='fallback', parameters may be missing - use current pilot data -->
          <set_value name="$currentXP" exact="0"/>
          <set_value name="$currentLevel" exact="1"/>
          <set_value name="$rankTitle" exact="null"/>  <!-- Initialize to null - will be set by rank calculation or remain null if lookup fails -->
          
          <!-- Use provided values if available, otherwise get from pilot data -->
          <do_if value="$xp? and $xp != null">
            <set_value name="$currentXP" exact="$xp"/>
          </do_if>
          <do_else>
            <set_value name="$currentXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
            <do_if value="not $currentXP?">
              <set_value name="$currentXP" exact="0"/>
            </do_if>
          </do_else>
          
          <do_if value="$level? and $level != null">
            <set_value name="$currentLevel" exact="$level"/>
          </do_if>
          <do_else>
            <!-- Calculate level from XP if not provided -->
            <set_value name="$currentLevel" exact="1"/>
            <do_all exact="15" counter="$lvl">
              <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$lvl}">
                <set_value name="$currentLevel" exact="$lvl"/>
              </do_if>
            </do_all>
          </do_else>
          
          <do_if value="$rank? and $rank != null and $rank != ''">
            <set_value name="$rankTitle" exact="$rank"/>
          </do_if>
          <do_else>
            <!-- Calculate rank title from skill level using unified mapping -->
            <set_value name="$rankIndex" exact="($currentLevel / 3)i + 1"/>
            <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
              <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
            </do_if>
            <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
              <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
            </do_if>
            <do_else>
              <!-- Rank lookup failed - log error instead of using fallback -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-ShipMgmt] ERROR: Rank lookup failed for level=' + $currentLevel + ', rankIndex=' + $rankIndex + ', TraderTitles.count=' + (if global.$GT_Config.$XP.$TraderTitles? then global.$GT_Config.$XP.$TraderTitles.keys.count else 'NULL') + ' (ship=' + $ship.idcode + ', pilot=' + $pilotNameDbg + ')'" chance="100"/>
              </do_if>
              <!-- Keep rankTitle as null to make the issue visible -->
            </do_else>
          </do_else>
        </do_if>
        <do_else>
          <!-- Old format - calculate from skillLevel -->
          <!-- CRITICAL: If skillLevel is null, derive from pilot data -->
          <do_if value="$skillLevel? and $skillLevel != null">
            <set_value name="$currentLevel" exact="$skillLevel"/>
          </do_if>
          <do_else>
            <!-- skillLevel not provided - calculate from pilot XP -->
            <set_value name="$currentXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
            <do_if value="not $currentXP?">
              <set_value name="$currentXP" exact="0"/>
            </do_if>
            <set_value name="$currentLevel" exact="1"/>
            <do_all exact="15" counter="$lvl">
              <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$lvl}">
                <set_value name="$currentLevel" exact="$lvl"/>
              </do_if>
            </do_all>
          </do_else>
          
          <!-- Get XP if not already set -->
          <do_if value="not $currentXP?">
            <set_value name="$currentXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
            <do_if value="not $currentXP?">
              <set_value name="$currentXP" exact="0"/>
            </do_if>
          </do_if>
          
          <set_value name="$nameType" exact="'trader'"/>  <!-- Default to trader type -->
          
          <!-- Calculate rank title from skill level using unified mapping -->
          <set_value name="$rankIndex" exact="($currentLevel / 3)i + 1"/>
          <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
            <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
          </do_if>
          <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
            <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
          </do_if>
          <do_else>
            <!-- Rank lookup failed - log error instead of using fallback -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] ERROR: Rank lookup failed for level=' + $currentLevel + ', rankIndex=' + $rankIndex + ', TraderTitles.count=' + (if global.$GT_Config.$XP.$TraderTitles? then global.$GT_Config.$XP.$TraderTitles.keys.count else 'NULL') + ' (ship=' + $ship.idcode + ', pilot=' + $pilotNameDbg + ')'" chance="100"/>
            </do_if>
            <!-- Set to null to make the issue visible -->
            <set_value name="$rankTitle" exact="null"/>
          </do_else>
        </do_else>

        <!-- AUTHORITATIVE STATUS OVERRIDE (no parsing):
             The caller-provided $nameType can be stale due to async signals (e.g. trade completion triggers 'trader' rename
             while the ship is still isolated). Ensure the displayed status reflects the authoritative global flags. -->
        <do_if value="$ship? and $ship.exists">
          <set_value name="$isolatedFlagSet" exact="false"/>
          <set_value name="$fallbackFlagSet" exact="false"/>
          <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
            <set_value name="$isolatedFlagSet" exact="true"/>
            <set_value name="$nameType" exact="'isolated'"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') AUTHORITATIVE OVERRIDE: Setting nameType=isolated (global flag is set)'" chance="100"/>
            </do_if>
          </do_if>
          <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{$ship}?">
            <set_value name="$fallbackFlagSet" exact="true"/>
            <set_value name="$nameType" exact="'fallback'"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') AUTHORITATIVE OVERRIDE: Setting nameType=fallback (global flag is set)'" chance="100"/>
            </do_if>
          </do_elseif>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') No authoritative override: isolatedFlag=' + $isolatedFlagSet + ', fallbackFlag=' + $fallbackFlagSet + ', using nameType=' + $nameType" chance="100"/>
            </do_if>
          </do_else>
        </do_if>

        <!-- Naming mode: legacy toggle layout vs pattern substitution -->
        <set_value name="$useConfig" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming?"/>
        <set_value name="$useVanillaXPOnlyNaming" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$namingMode" exact="'legacy'"/>
        <do_if value="$useConfig and global.$GT_GlobalSettings.$ShipNaming.$NamingMode?">
          <set_value name="$namingMode" exact="@global.$GT_GlobalSettings.$ShipNaming.$NamingMode"/>
        </do_if>
        <set_value name="$usePatternNaming" exact="false"/>
        <do_if value="$namingMode == 'pattern' and not $useVanillaXPOnlyNaming">
          <set_value name="$usePatternNaming" exact="true"/>
        </do_if>
        <do_if value="$usePatternNaming">
          <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Resolve_Ship_Name_Pattern" result="$newShipName">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="nameType" value="$nameType"/>
            <param name="currentXP" value="$currentXP"/>
            <param name="currentLevel" value="$currentLevel"/>
            <param name="rankTitle" value="if $rankTitle? then $rankTitle else ''"/>
          </run_actions>
        </do_if>
        <do_else>
        
        <!-- Get ship's base name based on user setting -->
        <!-- Options: 'macro.name' (Model Name - with variant), 'typename' (Type Name - generic), 'macro.name.base' (Model Base - without variant), 'basename' (Custom Name - stored name) -->
        <set_value name="$nameSource" exact="'macro.name'"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource?">
          <set_value name="$nameSource" exact="global.$GT_GlobalSettings.$ShipNaming.$DefaultNameSource"/>
        </do_if>
        
        <!-- Resolve original name based on nameSource setting -->
        <set_value name="$originalName" exact="''"/>
    
        <!-- Handle different nameSource options -->
        <do_if value="$nameSource == 'basename'">
          <!-- Custom Name: Use stored OriginalShipName from registry (preserves custom renames) -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') Custom Name mode: Checking for stored name. Ship registry exists: ' + (if global.$GT_Ships? and global.$GT_Ships.{$ship}? then 'yes' else 'no')" chance="100"/>
          </do_if>
          
          <!-- Try ship registry first -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Ships.{$ship}.$OriginalShipName"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') Custom Name mode: Found in ship registry: ' + $originalName" chance="100"/>
            </do_if>
            <!-- Validate it's a non-empty string -->
            <do_if value="not $originalName? or $originalName == ''">
              <set_value name="$originalName" exact="''"/>
            </do_if>
          </do_if>
          
          <!-- Fallback to pilot registry if ship registry doesn't have it -->
          <do_if value="$originalName == '' and global.$GT_Pilots? and $pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') Custom Name mode: Found in pilot registry: ' + $originalName" chance="100"/>
            </do_if>
            <!-- Validate it's a non-empty string -->
            <do_if value="not $originalName? or $originalName == ''">
              <set_value name="$originalName" exact="''"/>
            </do_if>
          </do_if>
          
          <!-- Final fallback: use ship.macro.name if no stored name exists -->
          <do_if value="$originalName == ''">
            <set_value name="$originalName" exact="@$ship.macro.name"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') Custom Name mode: No stored name found in either registry, using macro.name: ' + $originalName" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$nameSource == 'macro.name'">
          <!-- Model Name: Use ship.macro.name directly (with variant, e.g., "Mercury Sentinel") -->
          <set_value name="$originalName" exact="@$ship.macro.name"/>
        </do_elseif>
        <do_elseif value="$nameSource == 'typename'">
          <!-- Type Name: Use ship.typename (generic type name) -->
          <set_value name="$originalName" exact="@$ship.typename"/>
          <do_if value="not $originalName? or $originalName == ''">
            <!-- Fallback to macro.name if typename is missing -->
            <set_value name="$originalName" exact="@$ship.macro.name"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$nameSource == 'macro.name.base'">
          <!-- Model Base: Strip variant suffixes from macro.name (e.g., "Mercury Sentinel" -> "Mercury") -->
          <run_actions ref="md.GT_Ship_Management.Extract_Base_Ship_Name" result="$originalName">
            <param name="macroName" value="@$ship.macro.name"/>
          </run_actions>
        </do_elseif>
        <do_else>
          <!-- Unknown nameSource: fallback to macro.name -->
          <set_value name="$originalName" exact="@$ship.macro.name"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] (' + $ship.idcode + ') Unknown nameSource: ' + $nameSource + ', using macro.name: ' + $originalName" chance="100"/>
          </do_if>
        </do_else>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Building name from ' + $nameSource + ': ' + $originalName" chance="100"/>
        </do_if>
        
        <!-- Build ship name using configurable naming system -->
        <set_value name="$nameElements" exact="[]"/>
        <set_value name="$prefixElements" exact="[]"/>
        <set_value name="$suffixElements" exact="[]"/>
        
        <!-- Status (training/blocked/advance indicators) -->
        <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$DisplayStatus">
          <set_value name="$statusText" exact="''"/>
          <do_if value="$nameType == 'blocked'">
            <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
              <param name="stateType" value="'Blocked'"/>
            </run_actions>
            <set_value name="$statusText" exact="'[' + $abbr + ']'"/>
          </do_if>
          <do_elseif value="$nameType == 'training'">
            <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
              <param name="stateType" value="'Training'"/>
            </run_actions>
            <set_value name="$statusText" exact="'[' + $abbr + ']'"/>
          </do_elseif>
          <do_elseif value="$nameType == 'fallback'">
            <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
              <param name="stateType" value="'Fallback'"/>
            </run_actions>
            <set_value name="$statusText" exact="'[' + $abbr + ']'"/>
          </do_elseif>
          <do_elseif value="$nameType == 'isolated'">
            <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
              <param name="stateType" value="'Isolated'"/>
            </run_actions>
            <set_value name="$statusText" exact="'[' + $abbr + ']'"/>
          </do_elseif>
          
          <do_if value="$statusText != ''">
            <!-- No name parsing: always rebuild name from $OriginalShipName and apply desired status. -->
            <do_if value="true">
              <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$StatusPosition == 'prefix'">
                <append_to_list name="$prefixElements" exact="$statusText"/>
              </do_if>
              <do_else>
                <append_to_list name="$suffixElements" exact="$statusText"/>
              </do_else>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Operational State Prefix (REPAIR, RESUPPLY, MAINTENANCE, ESCAPE, REROUTE, CLEARANCE) -->
        <!-- These are ADDITIONAL to status prefixes and respect user configuration -->
        <!-- Default to true if setting doesn't exist (backwards compatibility with older saves) -->
        <do_if value="(not $useConfig) or not global.$GT_GlobalSettings.$ShipNaming.$DisplayOperationalState? or @global.$GT_GlobalSettings.$ShipNaming.$DisplayOperationalState">
          <set_value name="$operationalState" exact="''"/>
          
          <!-- Check for repair/resupply state -->
          <!-- IMPORTANT: Do not depend on GT_Ships entry existing (subordinates can temporarily drop out of GT_Ships). -->
          <!-- Resupply state is tracked via GT_ResupplyOrders, so we can show [RESUPPLY] even if GT_Ships entry is missing. -->
          <set_value name="$hasRepair" exact="false"/>
          <set_value name="$hasResupply" exact="false"/>
          
          <!-- Check if ship has active resupply order (GT maintenance tracking) -->
          <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
            <set_value name="$hasResupply" exact="true"/>
          </do_if>

          <!-- Fleet resupply / "Change Equipment" orders on subordinates may not be tracked in GT_ResupplyOrders.
               Use vanilla active order IDs as a fallback, but only for GT ships or subordinates of GT ships. -->
          <set_value name="$isGTRelated" exact="false"/>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
            <set_value name="$isGTRelated" exact="true"/>
          </do_if>
          <do_else>
            <set_value name="$commander" exact="@$ship.commander"/>
            <do_if value="$commander? and global.$GT_Ships? and global.$GT_Ships.{$commander}?">
              <set_value name="$isGTRelated" exact="true"/>
            </do_if>
          </do_else>

          <do_if value="$isGTRelated">
            <set_value name="$activeOrderId" exact="@$ship.order.id"/>
            <do_if value="$activeOrderId == 'Equip' or $activeOrderId == 'Resupply'">
              <set_value name="$hasResupply" exact="true"/>
            </do_if>
            <do_elseif value="$activeOrderId == 'Repair'">
              <set_value name="$hasRepair" exact="true"/>
            </do_elseif>
          </do_if>
          
          <!-- GT_Ships-derived states (repair/reroute/clearance) are only available if ship is registered -->
          <set_value name="$shipData" exact="null"/>
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
            <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
            
            <!-- Check if ship has active repair order -->
            <do_if value="$shipData.$NeedsRepair? and $shipData.$NeedsRepair">
              <set_value name="$hasRepair" exact="true"/>
            </do_if>
            
            <!-- Check for escape state (ship is actively trying to leave a blacklisted sector) -->
            <do_if value="$shipData.$Escaping? and $shipData.$Escaping">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Escape'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_if>

            <!-- Check for reroute state (destination threatened/blacklisted) -->
            <do_if value="$shipData.$Rerouting? and $shipData.$Rerouting">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Reroute'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_if>
            
            <!-- Check for cargo safety disposal state -->
            <do_if value="$shipData.$CargoDisposal? and $shipData.$CargoDisposal">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Clearance'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_if>

            <!-- Check for unreachable routes state (all current profitable routes blocked by blacklist/pathing) -->
            <!-- Show this in red for quick visual diagnosis -->
            <do_if value="$operationalState == '' and $shipData.$Unreachable? and $shipData.$Unreachable">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Unreachable'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'\033#FFCC0000#[' + $abbr + ']\033X'"/>
            </do_if>

            <!-- Pilot exchange state (centralized status check to avoid stale PE display). -->
            <set_value name="$showPilotExchangeState" exact="false"/>
            <do_if value="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus?">
              <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$namePeStatus">
                <param name="ship" value="$ship"/>
              </run_actions>
              <do_if value="$namePeStatus.$ShouldKeepPE">
                <set_value name="$showPilotExchangeState" exact="true"/>
              </do_if>
            </do_if>
            <do_elseif value="$shipData.$PilotExchange? and $shipData.$PilotExchange">
              <!-- Backward-compatible fallback if utility is unavailable for any reason. -->
              <set_value name="$showPilotExchangeState" exact="true"/>
            </do_elseif>
            <do_if value="$showPilotExchangeState">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'PilotExchange'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_if>
          </do_if>
          
          <!-- Determine operational state text using abbreviations (only if not overridden by reroute/clearance above) -->
          <do_if value="$operationalState == ''">
            <do_if value="$hasRepair and $hasResupply">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Maintenance'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_if>
            <do_elseif value="$hasRepair">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Repair'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_elseif>
            <do_elseif value="$hasResupply">
              <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
                <param name="stateType" value="'Resupply'"/>
              </run_actions>
              <set_value name="$operationalState" exact="'[' + $abbr + ']'"/>
            </do_elseif>
          </do_if>
          
          <!-- Add operational state to appropriate list based on user config -->
          <!-- Default to prefix if setting doesn't exist (backwards compatibility) -->
          <do_if value="$operationalState != ''">
            <do_if value="(not $useConfig) or not global.$GT_GlobalSettings.$ShipNaming.$OperationalStatePosition? or @global.$GT_GlobalSettings.$ShipNaming.$OperationalStatePosition == 'prefix'">
              <append_to_list name="$prefixElements" exact="$operationalState"/>
            </do_if>
            <do_else>
              <append_to_list name="$suffixElements" exact="$operationalState"/>
            </do_else>
          </do_if>
        </do_if>

        <!-- Custom blacklist prefix tag:
             Show for commander ships with active MK3 custom blacklist and for their subordinates. -->
        <set_value name="$showCustomBlacklistTag" exact="false"/>
        <set_value name="$mk3BlacklistOwnerForTag" exact="$ship"/>
        <set_value name="$isShipAffectedByCustomBlacklist" exact="false"/>
        <do_if value="$ship.commander? and $ship.commander.exists">
          <do_if value="$ship.commander.defaultorder?">
            <do_if value="@$ship.commander.defaultorder.id == 'GalaxyTraderMK3'">
              <set_value name="$mk3BlacklistOwnerForTag" exact="$ship.commander"/>
              <set_value name="$isShipAffectedByCustomBlacklist" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK3'">
          <set_value name="$mk3BlacklistOwnerForTag" exact="$ship"/>
          <set_value name="$isShipAffectedByCustomBlacklist" exact="true"/>
        </do_elseif>
        <do_if value="$isShipAffectedByCustomBlacklist and global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerForTag}? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerForTag}.keys.count gt 0">
          <set_value name="$showCustomBlacklistTag" exact="true"/>
        </do_if>
        <do_if value="$showCustomBlacklistTag">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'CustomBlacklist'"/>
          </run_actions>
          <append_to_list name="$prefixElements" exact="'\033#FFFFFF00#[' + $abbr + ']\033X'"/>
        </do_if>

        <!-- Home sector (legacy mode) -->
        <do_if value="(not $useConfig) or @global.$GT_GlobalSettings.$ShipNaming.$DisplayHomeSector">
          <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$homeSectorForName">
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="$homeSectorForName? and $homeSectorForName.exists">
            <run_actions ref="md.GT_Libraries_General.GT_GetSectorNameSafe" result="$homeSectorName">
              <param name="sector" value="$homeSectorForName"/>
            </run_actions>
            <set_value name="$homeSegment" exact="'[' + $homeSectorName + ']'"/>
            <do_if value="(not $useConfig) or not global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition? or @global.$GT_GlobalSettings.$ShipNaming.$HomeSectorPosition == 'prefix'">
              <append_to_list name="$prefixElements" exact="$homeSegment"/>
            </do_if>
            <do_else>
              <append_to_list name="$suffixElements" exact="$homeSegment"/>
            </do_else>
          </do_if>
        </do_if>
        
        <!-- Pilot Rank -->
        <do_if value="((not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$DisplayRank) and not $useVanillaXPOnlyNaming">
          <!-- Calculate rank index from level -->
          <set_value name="$rankIndex" exact="($currentLevel / 3)i + 1"/>
          <do_if value="$rankIndex gt 6">
            <set_value name="$rankIndex" exact="6"/>  <!-- Max 6 ranks -->
          </do_if>
          
          <!-- Get translated rank title using conditional logic (X4 doesn't support variables in readtext) -->
          <set_value name="$rankTitleText" exact="'Unknown'"/>
          <do_if value="$rankIndex == 1">
            <set_value name="$rankTitleText" exact="readtext.{77000}.{6001}"/>
          </do_if>
          <do_elseif value="$rankIndex == 2">
            <set_value name="$rankTitleText" exact="readtext.{77000}.{6002}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 3">
            <set_value name="$rankTitleText" exact="readtext.{77000}.{6003}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 4">
            <set_value name="$rankTitleText" exact="readtext.{77000}.{6004}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 5">
            <set_value name="$rankTitleText" exact="readtext.{77000}.{6005}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 6">
            <set_value name="$rankTitleText" exact="readtext.{77000}.{6006}"/>
          </do_elseif>
          
          <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$RankPosition == 'prefix'">
            <append_to_list name="$prefixElements" exact="$rankTitleText"/>
          </do_if>
          <do_else>
            <append_to_list name="$suffixElements" exact="$rankTitleText"/>
          </do_else>
        </do_if>
        
        <!-- Level -->
        <do_if value="((not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$DisplayLevel) and not $useVanillaXPOnlyNaming">
          <set_value name="$levelText" exact="'Lv.' + $currentLevel"/>
          <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$LevelPosition == 'prefix'">
            <append_to_list name="$prefixElements" exact="$levelText"/>
          </do_if>
          <do_else>
            <append_to_list name="$suffixElements" exact="$levelText"/>
          </do_else>
        </do_if>
        
        <!-- XP -->
        <do_if value="((not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$DisplayXP) and not $useVanillaXPOnlyNaming">
          <set_value name="$xpText" exact="'XP:' + $currentXP"/>
          <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$XPPosition == 'prefix'">
            <append_to_list name="$prefixElements" exact="$xpText"/>
          </do_if>
          <do_else>
            <append_to_list name="$suffixElements" exact="$xpText"/>
          </do_else>
        </do_if>
        
        <!-- Ship Class -->
        <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$DisplayShipClass">
          <!-- Detect ship class using existing library -->
          <run_actions ref="md.GT_Ship_Management.Detect_Ship_Class" result="$classInfo">
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="$shipClassText" exact="$classInfo.$Size"/> <!-- Returns 'S', 'M', 'L', or 'XL' -->
          <do_if value="(not $useConfig) or global.$GT_GlobalSettings.$ShipNaming.$ShipClassPosition == 'prefix'">
            <append_to_list name="$prefixElements" exact="$shipClassText"/>
          </do_if>
          <do_else>
            <append_to_list name="$suffixElements" exact="$shipClassText"/>
          </do_else>
        </do_if>
        
        <!-- Build final name -->
        <set_value name="$newShipName" exact="$originalName"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Update_Ship_Name: Building name - originalName=' + $originalName + ', nameType=' + $nameType + ', prefixElements.count=' + $prefixElements.count + ', suffixElements.count=' + $suffixElements.count" chance="100"/>
        </do_if>
        
        <!-- Add prefix elements -->
        <do_if value="$prefixElements.count gt 0">
          <set_value name="$prefixString" exact="''"/>
          <do_all exact="$prefixElements.count" counter="$j">
            <do_if value="$j gt 1">
              <set_value name="$prefixString" exact="$prefixString + ' '"/>
            </do_if>
            <set_value name="$prefixString" exact="$prefixString + $prefixElements.{$j}"/>
          </do_all>
          <set_value name="$newShipName" exact="$prefixString + ' ' + $newShipName"/>
        </do_if>
        
        <!-- Add suffix elements -->
        <do_if value="$suffixElements.count gt 0">
          <!-- No parsing: always rebuild the complete suffix from scratch. -->
          <set_value name="$suffixString" exact="''"/>
          <do_all exact="$suffixElements.count" counter="$j">
            <do_if value="$j gt 1">
              <set_value name="$suffixString" exact="$suffixString + ' '"/>
            </do_if>
            <set_value name="$suffixString" exact="$suffixString + $suffixElements.{$j}"/>
          </do_all>
          <set_value name="$newShipName" exact="$newShipName + ' (' + $suffixString + ')'"/>
        </do_if>

        </do_else><!-- end legacy naming branch -->
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-ShipMgmt] Update_Ship_Name: Final name built - newShipName=' + $newShipName + ', ship.exists=' + (if $ship.exists then 'yes' else 'no')" chance="100"/>
        </do_if>
        
        <!-- Content dedupe + apply -->
        <do_if value="$ship? and $ship.exists">
          <set_value name="$shouldApplyName" exact="$applyName"/>
          <do_if value="$applyName">
            <set_value name="$cachedName" exact="''"/>
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$LastResolvedShipName?">
              <set_value name="$cachedName" exact="global.$GT_Ships.{$ship}.$LastResolvedShipName"/>
            </do_if>
            <do_if value="$newShipName == $cachedName">
              <set_value name="$shouldApplyName" exact="false"/>
            </do_if>
          </do_if>
          <do_if value="$shouldApplyName">
            <set_object_name object="$ship" name="$newShipName"/>
            <do_if value="not global.$GT_Ships?">
              <set_value name="global.$GT_Ships" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ships.{$ship}?">
              <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
            </do_if>
            <set_value name="global.$GT_Ships.{$ship}.$LastResolvedShipName" exact="$newShipName"/>
            <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$homeSectorCache">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="$homeSectorCache? and $homeSectorCache.exists">
              <set_value name="global.$GT_Ships.{$ship}.$LastNamedHomeSector" exact="$homeSectorCache"/>
            </do_if>
            <do_else>
              <remove_value name="global.$GT_Ships.{$ship}.$LastNamedHomeSector"/>
            </do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Ship renamed: ' + $newShipName + ' (skill level ' + $currentLevel + ', rank: ' + $rankTitle + ', XP: ' + $currentXP + ', type: ' + $nameType + ') (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
            </do_if>
          </do_if>
          <return value="$newShipName"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Update_Ship_Name: Cannot rename - ship no longer exists (was: ' + (if $ship? then $ship.idcode else 'NULL') + ', ship?=' + (if $ship? then 'yes' else 'no') + ', ship.exists=' + (if $ship.exists then 'yes' else 'no') + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_else>
      </actions>
    </library>

    <!-- Derive effective nameType when caller passes generic 'trader' -->
    <library name="GT_Derive_Effective_NameType" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="nameType" default="'trader'"/>
      </params>
      <actions>
        <do_if value="not $pilot? or $pilot == null">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>
        <set_value name="$effectiveType" exact="$nameType"/>
        <do_if value="not $effectiveType? or $effectiveType == ''">
          <set_value name="$effectiveType" exact="'trader'"/>
        </do_if>
        <do_if value="$effectiveType == 'trader'">
          <set_value name="$isTrainingActive" exact="false"/>
          <set_value name="$isBlocked" exact="false"/>
          <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
            <do_if value="global.$GT_Pilots.{$pilot}.$TrainingState? and global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress'">
              <set_value name="$isTrainingActive" exact="true"/>
            </do_if>
            <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
              <set_value name="$isBlocked" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="not $isTrainingActive and $ship? and $ship.order? and @$ship.order.id == 'DockAndTrain'">
            <set_value name="$isTrainingActive" exact="true"/>
          </do_if>
          <do_if value="$ship? and $ship.exists">
            <do_if value="global.$GT_IsolatedTradeActive? and global.$GT_IsolatedTradeActive.{$ship}?">
              <set_value name="$effectiveType" exact="'isolated'"/>
            </do_if>
            <do_elseif value="global.$GT_FallbackTradeActive? and global.$GT_FallbackTradeActive.{$ship}?">
              <set_value name="$effectiveType" exact="'fallback'"/>
            </do_elseif>
            <do_elseif value="$isTrainingActive">
              <set_value name="$effectiveType" exact="'training'"/>
            </do_elseif>
            <do_elseif value="$isBlocked">
              <set_value name="$effectiveType" exact="'blocked'"/>
            </do_elseif>
          </do_if>
        </do_if>
        <return value="$effectiveType"/>
      </actions>
    </library>

    <!-- Unified ship name refresh: derive nameType, sync pilot tag, build + dedupe via Update_Ship_Name -->
    <library name="GT_Process_Ship_Name_Refresh" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="xp" default="null"/>
        <param name="level" default="null"/>
        <param name="rank" default="null"/>
        <param name="nameType" default="'trader'"/>
        <param name="skillLevel" default="null"/>
      </params>
      <actions>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and not @global.$GT_GlobalSettings.$ShipNaming.$Enabled">
          <return value="false"/>
        </do_if>
        <do_if value="not $ship? or not $ship.exists">
          <return value="false"/>
        </do_if>
        <do_if value="not $pilot? or $pilot == null">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>
        <run_actions ref="md.GT_Ship_Management.GT_Derive_Effective_NameType" result="$effectiveNameType">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="nameType" value="$nameType"/>
        </run_actions>
        <do_if value="$pilot? and $pilot.exists">
          <run_actions ref="md.GT_Ship_Management.Update_Pilot_Name_Tag">
            <param name="pilot" value="$pilot"/>
            <param name="level" value="if $level? then $level else null"/>
          </run_actions>
        </do_if>
        <run_actions ref="md.GT_Ship_Management.Update_Ship_Name" result="$refreshResult">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="xp" value="$xp"/>
          <param name="level" value="$level"/>
          <param name="rank" value="$rank"/>
          <param name="nameType" value="$effectiveNameType"/>
          <param name="skillLevel" value="$skillLevel"/>
          <param name="applyName" value="true"/>
        </run_actions>
        <return value="$refreshResult"/>
      </actions>
    </library>

    <!-- Listen for main-loop + event refresh signals -->
    <cue name="ListenForShipNameRefresh" instantiate="true">
      <conditions>
        <check_any>
          <event_object_signalled object="player.galaxy" param="'GT_Refresh_Ship_Name'"/>
          <event_object_signalled object="player.galaxy" param="'GT_Update_Ship_Name'"/>
        </check_any>
      </conditions>
      <actions>
        <set_value name="$signalParam" exact="event.param2"/>
        <set_value name="$ship" exact="@$signalParam.$Ship"/>
        <set_value name="$pilot" exact="@$signalParam.$pilot"/>
        <do_if value="not $pilot? and $signalParam.$Pilot?">
          <set_value name="$pilot" exact="$signalParam.$Pilot"/>
        </do_if>
        <set_value name="$nameType" exact="'trader'"/>
        <do_if value="$signalParam.$nameType?">
          <set_value name="$nameType" exact="$signalParam.$nameType"/>
        </do_if>
        <run_actions ref="md.GT_Ship_Management.GT_Process_Ship_Name_Refresh" result="$refreshDone">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="$pilot"/>
          <param name="xp" value="@$signalParam.$xp"/>
          <param name="level" value="@$signalParam.$level"/>
          <param name="rank" value="@$signalParam.$rank"/>
          <param name="nameType" value="$nameType"/>
          <param name="skillLevel" value="@$signalParam.$skillLevel"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Ensure Pilot Fields Exist (Defensive Programming) -->
    <library name="Ensure_Pilot_Fields" purpose="run_actions">
      <params>
        <param name="pilot" comment="Pilot to ensure fields for"/>
      </params>
      <actions>
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <!-- Ensure all required fields exist -->
          <do_if value="not global.$GT_Pilots.{$pilot}.$XP?">
            <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="0"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$Level?">
            <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="1"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$TotalTrades?">
            <set_value name="global.$GT_Pilots.{$pilot}.$TotalTrades" exact="0"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$TotalProfit?">
            <set_value name="global.$GT_Pilots.{$pilot}.$TotalProfit" exact="0Cr"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="[]"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$PilotName?">
            <set_value name="global.$GT_Pilots.{$pilot}.$PilotName" exact="$pilot.name"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$OriginalPilotName?">
            <set_value name="global.$GT_Pilots.{$pilot}.$OriginalPilotName" exact="$pilot.name"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$PilotID? or global.$GT_Pilots.{$pilot}.$PilotID == ''">
            <set_value name="global.$GT_Pilots.{$pilot}.$PilotID" exact="if $pilot.idcode? then $pilot.idcode else ''"/>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$StableIdentity? or global.$GT_Pilots.{$pilot}.$StableIdentity == ''">
            <run_actions ref="Compute_Pilot_Stable_Key" result="$stableKey">
              <param name="pilot" value="$pilot"/>
            </run_actions>
            <do_if value="$stableKey != ''">
              <set_value name="global.$GT_Pilots.{$pilot}.$StableIdentity" exact="$stableKey"/>
            </do_if>
          </do_if>
          <do_if value="not global.$GT_Pilots.{$pilot}.$Status?">
            <set_value name="global.$GT_Pilots.{$pilot}.$Status" exact="'active'"/>
          </do_if>
          
          <return value="true"/>
        </do_if>
        <do_else>
          <return value="false"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Restore Original Ship Name -->
    <library name="Restore_Original_Ship_Name" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to restore name for"/>
        <param name="pilot" comment="Pilot associated with ship (optional, will use ship.pilot if not provided)"/>
        <param name="originalName" comment="Original name to restore (optional, will look up from pilot registry if not provided)"/>
      </params>
      <actions>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and not @global.$GT_GlobalSettings.$ShipNaming.$Enabled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Restore_Original_Ship_Name skipped: ship renaming disabled'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        <set_value name="$pilotToUse" exact="null"/>
        <do_if value="$pilot?">
          <set_value name="$pilotToUse" exact="$pilot"/>
        </do_if>
        <do_elseif value="$ship.pilot?">
          <set_value name="$pilotToUse" exact="$ship.pilot"/>
        </do_elseif>
        
        <set_value name="$nameToRestore" exact="null"/>
        
        <!-- Use provided original name if available -->
        <do_if value="$originalName?">
          <set_value name="$nameToRestore" exact="$originalName"/>
        </do_if>
        <!-- Otherwise try to get from pilot registry -->
        <do_elseif value="$pilotToUse and global.$GT_Pilots.{$pilotToUse}? and global.$GT_Pilots.{$pilotToUse}.$OriginalShipName?">
          <set_value name="$nameToRestore" exact="global.$GT_Pilots.{$pilotToUse}.$OriginalShipName"/>
        </do_elseif>
        
        <!-- Restore the name if we found one -->
        <do_if value="$nameToRestore?">
          <set_object_name object="$ship" name="$nameToRestore"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-ShipMgmt] Restored original ship name: ' + $nameToRestore + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
          <return value="true"/>
        </do_if>
        <do_else>
          <debug_text text="'[GT-ShipMgmt] WARNING: Could not restore original ship name for ' + $ship.knownname + ' (Ship ID: ' + $ship.idcode + ') - original name not found'" chance="100"/>
          <return value="false"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Get State Abbreviation (checks custom first, then defaults) -->
    <library name="Get_State_Abbreviation" purpose="run_actions">
      <params>
        <param name="stateType" comment="State type: 'Resupply', 'Repair', 'Maintenance', 'Training', 'Escape', 'Reroute', 'Clearance', 'Unreachable', 'PilotExchange', 'Blocked', 'CustomBlacklist', 'Fallback', 'Isolated', 'Trading', 'Idle'"/>
      </params>
      <actions>
        <!-- Default abbreviations -->
        <set_value name="$defaultAbbr" exact="''"/>
        <do_if value="$stateType == 'Resupply'">
          <set_value name="$defaultAbbr" exact="'RS'"/>
        </do_if>
        <do_elseif value="$stateType == 'Repair'">
          <set_value name="$defaultAbbr" exact="'RP'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Maintenance'">
          <set_value name="$defaultAbbr" exact="'MT'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Training'">
          <set_value name="$defaultAbbr" exact="'TR'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Escape'">
          <set_value name="$defaultAbbr" exact="'ES'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Reroute'">
          <set_value name="$defaultAbbr" exact="'RR'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Clearance'">
          <set_value name="$defaultAbbr" exact="'CL'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Unreachable'">
          <set_value name="$defaultAbbr" exact="'UR'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'PilotExchange'">
          <set_value name="$defaultAbbr" exact="'PE'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Blocked'">
          <set_value name="$defaultAbbr" exact="'BL'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'CustomBlacklist'">
          <set_value name="$defaultAbbr" exact="'CB'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Fallback'">
          <set_value name="$defaultAbbr" exact="'FB'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Isolated'">
          <set_value name="$defaultAbbr" exact="'IS'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Trading'">
          <set_value name="$defaultAbbr" exact="'TD'"/>
        </do_elseif>
        <do_elseif value="$stateType == 'Idle'">
          <set_value name="$defaultAbbr" exact="'ID'"/>
        </do_elseif>
        
        <!-- Check for custom abbreviation first -->
        <!-- FIX: Properly handle null/empty values - only use custom if it's a non-empty string -->
        <set_value name="$customAbbr" exact="null"/>
        <set_value name="$hasCustomAbbr" exact="false"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations?">
          <set_value name="$customAbbrTemp" exact="@global.$GT_GlobalSettings.$ShipNaming.$StateAbbreviations.{$stateType}"/>
          <!-- Only use custom abbreviation if it exists, is not null, and is not empty -->
          <do_if value="$customAbbrTemp? and $customAbbrTemp != null and $customAbbrTemp != ''">
            <set_value name="$customAbbr" exact="$customAbbrTemp"/>
            <set_value name="$hasCustomAbbr" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Return custom if valid, otherwise default -->
        <do_if value="$hasCustomAbbr">
          <return value="$customAbbr"/>
        </do_if>
        <do_else>
          <return value="$defaultAbbr"/>
        </do_else>
      </actions>
    </library>

    <cue name="GT_AutoJumpDistance_Apply_Handler" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_AutoJumpDistance_Apply'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$ship" exact="@$data.$Ship"/>
        <set_value name="$pilot" exact="if $data.$Pilot? then $data.$Pilot else null"/>
        <set_value name="$reason" exact="if $data.$Reason? then $data.$Reason else 'checkbox_enabled'"/>
        <do_if value="$ship? and $ship.exists">
          <run_actions ref="md.GT_Ship_Management.GT_Apply_AutoJumpDistance_ForShip">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="reason" value="$reason"/>
          </run_actions>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript> <?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Ship_Modifications" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - SHIP MODIFICATIONS
         Automatic modification installation/removal system
         ======================================== -->
    
    <!-- Reusable Library: Install GT Modifications for Ship -->
    <library name="Install_GT_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to install modifications on"/>
        <param name="pilot" comment="Pilot (optional, will be retrieved from ship if not provided)"/>
        <param name="forceGTContext" default="false" comment="Authoritative assignment/update path; don't treat transient state as non-GT"/>
      </params>
      <actions>
        <do_if value="not $ship? or not $ship.exists or @$ship.iswreck or not @$ship.isoperational">
          <return value="true"/>
        </do_if>
        
        <do_if value="not $pilot?">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>
        <set_value name="$pilotNameDbg" exact="if $pilot and $pilot.exists and $pilot.name? then $pilot.name else 'NONE'"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$defaultOrderId" exact="'NONE'"/>
          <set_value name="$currentOrderId" exact="'NONE'"/>
          <set_value name="$commanderOrderId" exact="'NONE'"/>
          <do_if value="$ship.defaultorder?">
            <set_value name="$defaultOrderId" exact="@$ship.defaultorder.id"/>
          </do_if>
          <do_if value="$ship.order?">
            <set_value name="$currentOrderId" exact="@$ship.order.id"/>
          </do_if>
          <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander.defaultorder?">
            <set_value name="$commanderOrderId" exact="@$ship.commander.defaultorder.id"/>
          </do_if>
          <debug_text text="'[GT-Mods] Install entry ship=' + $ship.idcode + ', pilot=' + $pilotNameDbg + ', forceGTContext=' + $forceGTContext + ', default=' + $defaultOrderId + ', current=' + $currentOrderId + ', commanderOrder=' + $commanderOrderId" chance="100"/>
        </do_if>

        <do_if value="not ($pilot and $pilot.exists)">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Deferred install waiting for pilot binding on ' + $ship.idcode + ' (pilot=' + $pilotNameDbg + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>
        
        <!-- Ensure pilot data exists before reconciliation. Missing GT level is not a valid input state. -->
        <do_if value="$pilot? and md.GT_Ship_Management.Register_Pilot? and (not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}? or not global.$GT_Pilots.{$pilot}.$Level?)">
          <run_actions ref="md.GT_Ship_Management.Register_Pilot">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        
        <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Level? and GT_Reconcile_Ship_Modifications?">
          <run_actions ref="GT_Reconcile_Ship_Modifications" result="$reconciled">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="$pilot"/>
            <param name="forceGTContext" value="$forceGTContext"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Install exit ship=' + $ship.idcode + ', pilot=' + $pilotNameDbg + ', reconciled=' + $reconciled" chance="100"/>
          </do_if>
          <return value="$reconciled"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Deferred install waiting for pilot registry on ' + $ship.idcode + ' (pilot=' + $pilotNameDbg + ')'" chance="100"/>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Reusable Library: Install Penalty Modifications for Ship -->
    <library name="Install_Penalty_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to install penalty modifications on"/>
        <param name="pilot" comment="Pilot (optional, will be retrieved from ship if not provided)"/>
      </params>
      <actions>
        <!-- CHECK: Is modification feature enabled? -->
        <set_value name="$modificationsEnabled" exact="true"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Modifications? and global.$GT_GlobalSettings.$Modifications.$Enabled?">
          <set_value name="$modificationsEnabled" exact="global.$GT_GlobalSettings.$Modifications.$Enabled"/>
        </do_if>
        
        <!-- Exit early if modifications are disabled -->
        <do_if value="not $modificationsEnabled">
          <!-- Remove any existing penalty mods if feature is disabled -->
          <set_value name="$existingPenaltyShipMod" exact="null"/>
          <set_value name="$existingPenaltyEngineMod" exact="null"/>
          <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$GTModifications?">
            <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod?">
              <set_value name="$existingPenaltyShipMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
            </do_if>
            <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod?">
              <set_value name="$existingPenaltyEngineMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
            </do_if>
          </do_if>
          <do_if value="$existingPenaltyShipMod? or $existingPenaltyEngineMod?">
            <set_value name="$shipIdCode" exact="@$ship.idcode"/>
            <do_if value="$existingPenaltyShipMod?">
              <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $existingPenaltyShipMod"/>
            </do_if>
            <do_if value="$existingPenaltyEngineMod?">
              <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $existingPenaltyEngineMod"/>
            </do_if>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Penalty] Removed penalty mods from ' + $ship.idcode + ' (modifications feature disabled)'" chance="100"/>
            </do_if>
          </do_if>
          <return value="null"/>
        </do_if>
        
        <!-- Get pilot if not provided -->
        <do_if value="not $pilot?">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>
        
        <!-- Get pilot level -->
        <set_value name="$pilotLevel" exact="0"/>
        <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{$pilot}.$Level"/>
        </do_if>
        
        <!-- Determine ship size class -->
        <set_value name="$shipClass" exact="'unknown'"/>
        <do_if value="$ship.isclass.ship_xl">
          <set_value name="$shipClass" exact="'xl'"/>
        </do_if>
        <do_elseif value="$ship.isclass.ship_l">
          <set_value name="$shipClass" exact="'l'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.ship_m">
          <set_value name="$shipClass" exact="'m'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.ship_s">
          <set_value name="$shipClass" exact="'s'"/>
        </do_elseif>
        
        <!-- Calculate penalty level based on ship class and pilot level -->
        <!-- NOTE: Penalty mods do NOT require research (unlike bonus mods) -->
        <set_value name="$penaltyLevel" exact="0"/> <!-- 0 = no penalty, 1 = light, 2 = moderate, 3 = severe -->
        <set_value name="$penaltyShipModWare" exact="null"/>
        <set_value name="$penaltyEngineModWare" exact="null"/>
        
        <do_if value="$shipClass == 'xl'">
          <do_if value="$pilotLevel le 1">
            <set_value name="$penaltyLevel" exact="3"/> <!-- Severe -->
            <set_value name="$penaltyShipModWare" exact="ware.mod_penalty_ship_severe"/>
            <set_value name="$penaltyEngineModWare" exact="ware.mod_penalty_engine_severe"/>
          </do_if>
          <do_elseif value="$pilotLevel le 3">
            <set_value name="$penaltyLevel" exact="2"/> <!-- Moderate -->
            <set_value name="$penaltyShipModWare" exact="ware.mod_penalty_ship_moderate"/>
            <set_value name="$penaltyEngineModWare" exact="ware.mod_penalty_engine_moderate"/>
          </do_elseif>
          <do_elseif value="$pilotLevel le 6">
            <set_value name="$penaltyLevel" exact="1"/> <!-- Light -->
            <set_value name="$penaltyShipModWare" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$penaltyEngineModWare" exact="ware.mod_penalty_engine_light"/>
          </do_elseif>
        </do_if>
        <do_elseif value="$shipClass == 'l'">
          <do_if value="$pilotLevel le 1">
            <set_value name="$penaltyLevel" exact="2"/> <!-- Moderate -->
            <set_value name="$penaltyShipModWare" exact="ware.mod_penalty_ship_moderate"/>
            <set_value name="$penaltyEngineModWare" exact="ware.mod_penalty_engine_moderate"/>
          </do_if>
          <do_elseif value="$pilotLevel le 3">
            <set_value name="$penaltyLevel" exact="1"/> <!-- Light -->
            <set_value name="$penaltyShipModWare" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$penaltyEngineModWare" exact="ware.mod_penalty_engine_light"/>
          </do_elseif>
        </do_elseif>
        <do_elseif value="$shipClass == 'm'">
          <do_if value="$pilotLevel le 1">
            <set_value name="$penaltyLevel" exact="1"/> <!-- Light -->
            <set_value name="$penaltyShipModWare" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$penaltyEngineModWare" exact="ware.mod_penalty_engine_light"/>
          </do_if>
        </do_elseif>
        <!-- S ships: always no penalty -->
        
        <!-- DIAGNOSTIC: Log penalty decision -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Penalty] â”€â”€ Penalty check for ' + $ship.idcode + ': class=' + $shipClass + ', pilotLevel=' + $pilotLevel + ', penaltyLevel=' + $penaltyLevel + ' â”€â”€'" chance="100"/>
        </do_if>
        
        <!-- Initialize mod tracking if needed -->
        <do_if value="not global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{$ship}.$GTModifications?">
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots?">
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="[]"/>
        </do_if>
        
        <!-- MIGRATION: Handle old save games with single $GTPenaltyMod entry -->
        <!-- Old saves had: $GTPenaltyMod = ware.mod_penalty_severe/moderate/light -->
        <!-- New structure: $GTPenaltyShipMod and $GTPenaltyEngineMod with separate wares -->
        <!-- NOTE: Import errors may occur during save load - this migration cleans up invalid references -->
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod? and 
                      not global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod? and 
                      not global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod?">
          <!-- Use safe operator to get old mod (may be invalid due to import failure) -->
          <set_value name="$oldPenaltyMod" exact="@global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod"/>
          <set_value name="$migratedShipMod" exact="null"/>
          <set_value name="$migratedEngineMod" exact="null"/>
          <set_value name="$oldModId" exact="null"/>
          
          <!-- Try to get old mod ID as string (ware might not exist due to import failure) -->
          <do_if value="$oldPenaltyMod?">
            <set_value name="$oldModId" exact="@$oldPenaltyMod.id"/>
            <do_if value="not $oldModId?">
              <!-- If .id doesn't work, try to get it as string directly (might be stored as string) -->
              <set_value name="$oldModId" exact="$oldPenaltyMod"/>
            </do_if>
          </do_if>
          
          <!-- Map old ware IDs to new separate ship/engine wares by comparing ID strings -->
          <do_if value="$oldModId? and $oldModId == 'mod_penalty_severe'">
            <set_value name="$migratedShipMod" exact="ware.mod_penalty_ship_severe"/>
            <set_value name="$migratedEngineMod" exact="ware.mod_penalty_engine_severe"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="3"/>
          </do_if>
          <do_elseif value="$oldModId? and $oldModId == 'mod_penalty_moderate'">
            <set_value name="$migratedShipMod" exact="ware.mod_penalty_ship_moderate"/>
            <set_value name="$migratedEngineMod" exact="ware.mod_penalty_engine_moderate"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="2"/>
          </do_elseif>
          <do_elseif value="$oldModId? and $oldModId == 'mod_penalty_light'">
            <set_value name="$migratedShipMod" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$migratedEngineMod" exact="ware.mod_penalty_engine_light"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="1"/>
          </do_elseif>
          
          <!-- Store migrated values and remove old entry -->
          <do_if value="$migratedShipMod? and $migratedEngineMod?">
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod" exact="$migratedShipMod"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod" exact="$migratedEngineMod"/>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$oldModName" exact="if $oldModId? then $oldModId else 'INVALID_IMPORT'"/>
              <set_value name="$shipModName" exact="@$migratedShipMod.name"/>
              <set_value name="$engineModName" exact="@$migratedEngineMod.name"/>
              <debug_text text="'[GT-Penalty] Migrated old penalty mod data for ' + $ship.idcode + ' (old: ' + $oldModName + ' ship: ' + (if $shipModName? then $shipModName else 'UNKNOWN') + ', engine: ' + (if $engineModName? then $engineModName else 'UNKNOWN') + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Old mod not recognized or import failed - remove invalid entry -->
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$oldModName" exact="if $oldModId? then $oldModId else 'INVALID_IMPORT'"/>
              <debug_text text="'[GT-Penalty] Removed invalid/unrecognized old penalty mod data for ' + $ship.idcode + ' (old: ' + $oldModName + ' - likely import failure)'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        
        <!-- Check if penalty mod is already installed -->
        <set_value name="$existingPenaltyShipMod" exact="null"/>
        <set_value name="$existingPenaltyEngineMod" exact="null"/>
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod?">
          <set_value name="$existingPenaltyShipMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
        </do_if>
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod?">
          <set_value name="$existingPenaltyEngineMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
        </do_if>
        
        <!-- Remove existing penalty mods if they're different from what we need, or if no penalty is needed -->
        <do_if value="($existingPenaltyShipMod? and $existingPenaltyShipMod != null and ($existingPenaltyShipMod != $penaltyShipModWare or not $penaltyShipModWare?)) or 
                      ($existingPenaltyEngineMod? and $existingPenaltyEngineMod != null and ($existingPenaltyEngineMod != $penaltyEngineModWare or not $penaltyEngineModWare?))">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$existingShipModName" exact="'none'"/>
            <set_value name="$existingEngineModName" exact="'none'"/>
            <do_if value="$existingPenaltyShipMod? and $existingPenaltyShipMod != null">
              <set_value name="$existingShipModName" exact="@$existingPenaltyShipMod.name"/>
            </do_if>
            <do_if value="$existingPenaltyEngineMod? and $existingPenaltyEngineMod != null">
              <set_value name="$existingEngineModName" exact="@$existingPenaltyEngineMod.name"/>
            </do_if>
            <debug_text text="'[GT-Penalty] Removing old penalty mods from ' + $ship.idcode + ' (ship: ' + (if $existingShipModName? then $existingShipModName else 'none') + ', engine: ' + (if $existingEngineModName? then $existingEngineModName else 'none') + ')'" chance="100"/>
          </do_if>
          <set_value name="$shipIdCode" exact="@$ship.idcode"/>
          <do_if value="$existingPenaltyShipMod? and $existingPenaltyShipMod != null">
            <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $existingPenaltyShipMod"/>
          </do_if>
          <do_if value="$existingPenaltyEngineMod? and $existingPenaltyEngineMod != null">
            <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $existingPenaltyEngineMod"/>
          </do_if>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel"/>
        </do_if>
        
        <!-- Install new penalty mods if needed and not already installed -->
        <do_if value="($penaltyShipModWare? and (not $existingPenaltyShipMod? or $existingPenaltyShipMod != $penaltyShipModWare)) or 
                      ($penaltyEngineModWare? and (not $existingPenaltyEngineMod? or $existingPenaltyEngineMod != $penaltyEngineModWare))">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$penaltyName" exact="'Severe'"/>
            <do_if value="$penaltyLevel == 2">
              <set_value name="$penaltyName" exact="'Moderate'"/>
            </do_if>
            <do_elseif value="$penaltyLevel == 1">
              <set_value name="$penaltyName" exact="'Light'"/>
            </do_elseif>
            <debug_text text="'[GT-Penalty] Installing ' + $penaltyName + ' penalty mods on ' + $ship.idcode + ' (Pilot Level: ' + $pilotLevel + ', Ship Size: ' + $shipClass + ')'" chance="100"/>
          </do_if>
          
          <!-- Install penalty mods in ship and engine slots (separate wares) -->
          <do_if value="$penaltyShipModWare?">
            <add_equipment_mods object="$ship">
              <ship ware="$penaltyShipModWare"/>
            </add_equipment_mods>
            <!-- Track in GTInstalledSlots to protect against removing player-installed mods -->
            <append_to_list name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="'ship'"/>
          </do_if>
          <do_if value="$penaltyEngineModWare?">
            <add_equipment_mods object="$ship">
              <engine ware="$penaltyEngineModWare"/>
            </add_equipment_mods>
            <!-- Track in GTInstalledSlots to protect against removing player-installed mods -->
            <append_to_list name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="'engine'"/>
          </do_if>
          
          <!-- Track penalty mod installation -->
          <do_if value="$penaltyShipModWare?">
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod" exact="$penaltyShipModWare"/>
          </do_if>
          <do_if value="$penaltyEngineModWare?">
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod" exact="$penaltyEngineModWare"/>
          </do_if>
          <do_if value="$penaltyLevel gt 0">
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="$penaltyLevel"/>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Penalty] Successfully installed penalty mods on ' + $ship.idcode + ' (ship: ' + (if $penaltyShipModWare != null then @$penaltyShipModWare.name else 'none') + ', engine: ' + (if $penaltyEngineModWare != null then @$penaltyEngineModWare.name else 'none') + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_elseif value="not $penaltyShipModWare? and not $penaltyEngineModWare? and ($existingPenaltyShipMod? or $existingPenaltyEngineMod?)">
          <!-- No penalty needed, but old one is present - already removed above -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Penalty] No penalty required for ' + $ship.idcode + ' (Pilot Level: ' + $pilotLevel + ', Ship Size: ' + $shipClass + ')'" chance="100"/>
          </do_if>
        </do_elseif>
      </actions>
    </library>
    
    <!-- Remove Penalty Modifications -->
    <library name="Remove_Penalty_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to remove penalty modifications from"/>
      </params>
      <actions>
        <!-- SAFETY CHECK: Only remove mods that WE installed (check GTInstalledSlots) -->
        <!-- This prevents removing player-installed mods -->
        <set_value name="$installedSlots" exact="[]"/>
        <do_if value="global.$GT_Ships.{$ship}? 
                          and global.$GT_Ships.{$ship}.$GTModifications? 
                          and global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots?">
          <set_value name="$installedSlots" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots"/>
        </do_if>
        
        <set_value name="$hasShipSlot" exact="false"/>
        <set_value name="$hasEngineSlot" exact="false"/>
        
        <!-- Check which slots we installed -->
        <do_all exact="$installedSlots.count" counter="$i">
          <do_if value="$installedSlots.{$i} == 'ship'">
            <set_value name="$hasShipSlot" exact="true"/>
          </do_if>
          <do_if value="$installedSlots.{$i} == 'engine'">
            <set_value name="$hasEngineSlot" exact="true"/>
          </do_if>
        </do_all>
        
        <set_value name="$currentPenaltyShipMod" exact="null"/>
        <set_value name="$currentPenaltyEngineMod" exact="null"/>
        <do_if value="global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$GTModifications?">
          <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod?">
            <set_value name="$currentPenaltyShipMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
          </do_if>
          <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod?">
            <set_value name="$currentPenaltyEngineMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
          </do_if>
        </do_if>

        <do_if value="($currentPenaltyShipMod? and $hasShipSlot) or ($currentPenaltyEngineMod? and $hasEngineSlot)">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$shipModName" exact="'none'"/>
            <set_value name="$engineModName" exact="'none'"/>
            <do_if value="$currentPenaltyShipMod?">
              <set_value name="$shipModName" exact="@$currentPenaltyShipMod.name"/>
            </do_if>
            <do_if value="$currentPenaltyEngineMod?">
              <set_value name="$engineModName" exact="@$currentPenaltyEngineMod.name"/>
            </do_if>
            <debug_text text="'[GT-Penalty] Removing penalty mods from ' + $ship.idcode + ' (ship: ' + (if $shipModName? then $shipModName else 'none') + ', engine: ' + (if $engineModName? then $engineModName else 'none') + ', explicit removal call)'" chance="100"/>
          </do_if>
          <set_value name="$shipIdCode" exact="@$ship.idcode"/>
          <do_if value="$currentPenaltyShipMod? and $hasShipSlot">
            <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $currentPenaltyShipMod"/>
          </do_if>
          <do_if value="$currentPenaltyEngineMod? and $hasEngineSlot">
            <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $currentPenaltyEngineMod"/>
          </do_if>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <do_if value="$currentPenaltyShipMod? or $currentPenaltyEngineMod?">
              <debug_text text="'[GT-Penalty] Skipping penalty mod removal for ' + $ship.idcode + ' - not GT-installed (player mod may be present)'" chance="100"/>
            </do_if>
            <do_else>
              <debug_text text="'[GT-Penalty] No penalty mod found on ' + $ship.idcode + ' to remove (explicit removal call)'" chance="100"/>
            </do_else>
          </do_if>
        </do_else>
      </actions>
    </library>

    <!-- Helper: check if ware belongs to GT ship mod set (bonus + penalty) -->
    <library name="GT_IsGTShipModWare" purpose="run_actions">
      <params>
        <param name="ware" comment="Ware to classify"/>
      </params>
      <actions>
        <set_value name="$isGT" exact="false"/>
        <set_value name="$wareId" exact="null"/>
        <do_if value="$ware?">
          <set_value name="$wareId" exact="@$ware.id"/>
          <do_if value="not $wareId?">
            <set_value name="$wareId" exact="$ware"/>
          </do_if>
        </do_if>
        <do_if value="$wareId? and ($wareId == 'mod_ship_gt_level1' or $wareId == 'mod_ship_gt_level2' or $wareId == 'mod_ship_gt_level3' or $wareId == 'mod_penalty_ship_light' or $wareId == 'mod_penalty_ship_moderate' or $wareId == 'mod_penalty_ship_severe' or $wareId == 'mod_penalty_light' or $wareId == 'mod_penalty_moderate' or $wareId == 'mod_penalty_severe')">
          <set_value name="$isGT" exact="true"/>
        </do_if>
        <return value="$isGT"/>
      </actions>
    </library>

    <!-- Helper: check if ware belongs to GT engine mod set (bonus + penalty) -->
    <library name="GT_IsGTEngineModWare" purpose="run_actions">
      <params>
        <param name="ware" comment="Ware to classify"/>
      </params>
      <actions>
        <set_value name="$isGT" exact="false"/>
        <set_value name="$wareId" exact="null"/>
        <do_if value="$ware?">
          <set_value name="$wareId" exact="@$ware.id"/>
          <do_if value="not $wareId?">
            <set_value name="$wareId" exact="$ware"/>
          </do_if>
        </do_if>
        <do_if value="$wareId? and ($wareId == 'mod_engine_gt_level1' or $wareId == 'mod_engine_gt_level2' or $wareId == 'mod_engine_gt_level3' or $wareId == 'mod_penalty_engine_light' or $wareId == 'mod_penalty_engine_moderate' or $wareId == 'mod_penalty_engine_severe' or $wareId == 'mod_penalty_light' or $wareId == 'mod_penalty_moderate' or $wareId == 'mod_penalty_severe')">
          <set_value name="$isGT" exact="true"/>
        </do_if>
        <return value="$isGT"/>
      </actions>
    </library>

    <!-- Reconcile one ship's GT mods to desired state, never touching vanilla/non-GT mods -->
    <library name="GT_Reconcile_Ship_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to reconcile"/>
        <param name="pilot" comment="Pilot (optional)"/>
        <param name="modificationsEnabledOverride" default="null" comment="Optional override for global toggle (e.g. from settings-changed signal)"/>
        <param name="forceGTContext" default="false" comment="Compatibility parameter; active GT callers are authoritative and do not re-check GT context here"/>
        <param name="removeGTModsOnly" default="false" comment="Force GT-managed mod removal without relying on settings override semantics"/>
      </params>
      <actions>
        <do_if value="not $ship? or not $ship.exists">
          <return value="false"/>
        </do_if>
        <!-- Wreck/non-operational components do not reliably expose equipment mod properties. -->
        <do_if value="@$ship.iswreck or not @$ship.isoperational">
          <return value="false"/>
        </do_if>

        <set_value name="$hadRegistryEntry" exact="global.$GT_Ships? and global.$GT_Ships.{$ship}?"/>
        <!-- Remove-only cleanup must never recreate registry state for detached ships. -->
        <set_value name="$trackRegistryState" exact="not $removeGTModsOnly or $hadRegistryEntry"/>

        <!-- Ensure tracking tables exist -->
        <do_if value="$trackRegistryState and not global.$GT_Ships?">
          <set_value name="global.$GT_Ships" exact="table[]"/>
        </do_if>
        <do_if value="$trackRegistryState and not global.$GT_Ships.{$ship}?">
          <set_value name="global.$GT_Ships.{$ship}" exact="table[]"/>
        </do_if>
        <do_if value="$trackRegistryState and not global.$GT_Ships.{$ship}.$GTModifications?">
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications" exact="table[]"/>
        </do_if>

        <!-- Resolve pilot -->
        <do_if value="not $pilot?">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>

        <!-- Read global toggle (or use override from settings-changed for immediate install) -->
        <set_value name="$globalModificationsEnabled" exact="true"/>
        <set_value name="$modificationsEnabledSource" exact="'implicit_true'"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Modifications? and global.$GT_GlobalSettings.$Modifications.$Enabled?">
          <set_value name="$globalModificationsEnabled" exact="global.$GT_GlobalSettings.$Modifications.$Enabled"/>
          <set_value name="$modificationsEnabledSource" exact="'global_setting'"/>
        </do_if>
        <set_value name="$modificationsEnabled" exact="true"/>
        <do_if value="$modificationsEnabledOverride != null">
          <set_value name="$modificationsEnabled" exact="$modificationsEnabledOverride"/>
          <set_value name="$modificationsEnabledSource" exact="'override'"/>
        </do_if>
        <do_elseif value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Modifications? and global.$GT_GlobalSettings.$Modifications.$Enabled?">
          <set_value name="$modificationsEnabled" exact="global.$GT_GlobalSettings.$Modifications.$Enabled"/>
        </do_elseif>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly">
          <set_value name="$modificationsEnabled" exact="false"/>
          <set_value name="$modificationsEnabledSource" exact="'vanilla_xp_mode'"/>
        </do_if>
        
        <!-- Active GT refreshes are authoritative: the caller already decided that this ship
             should converge to the GT-managed set. Only explicit removal paths disable mods. -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$defaultOrderId" exact="'NONE'"/>
          <set_value name="$currentOrderId" exact="'NONE'"/>
          <set_value name="$commanderId" exact="'NONE'"/>
          <set_value name="$commanderOrderId" exact="'NONE'"/>
          <set_value name="$trackedSlotsCount" exact="0"/>
          <do_if value="$ship.defaultorder?">
            <set_value name="$defaultOrderId" exact="@$ship.defaultorder.id"/>
          </do_if>
          <do_if value="$ship.order?">
            <set_value name="$currentOrderId" exact="@$ship.order.id"/>
          </do_if>
          <do_if value="$ship.commander? and $ship.commander.exists">
            <set_value name="$commanderId" exact="$ship.commander.idcode"/>
            <do_if value="$ship.commander.defaultorder?">
              <set_value name="$commanderOrderId" exact="@$ship.commander.defaultorder.id"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots?">
            <set_value name="$trackedSlotsCount" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots.count"/>
          </do_if>
          <debug_text text="'[GT-Mods] Reconcile entry ship=' + $ship.idcode + ', pilot=' + (if $pilot? then $pilot.name else 'NONE') + ', override=' + (if $modificationsEnabledOverride != null then $modificationsEnabledOverride else 'NULL') + ', removeOnly=' + $removeGTModsOnly + ', forceGTContext=' + $forceGTContext + ', globalEnabled=' + $globalModificationsEnabled + ', effectiveEnabled=' + $modificationsEnabled + ', source=' + $modificationsEnabledSource + ', default=' + $defaultOrderId + ', current=' + $currentOrderId + ', commander=' + $commanderId + ', commanderOrder=' + $commanderOrderId + ', trackedSlots=' + $trackedSlotsCount" chance="100"/>
        </do_if>

        <!-- Determine pilot level (GT registry only - no fallback; missing level means state is not ready yet). -->
        <do_if value="$modificationsEnabled and $pilot? and md.GT_Ship_Management.Register_Pilot? and (not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}? or not global.$GT_Pilots.{$pilot}.$Level?)">
          <run_actions ref="md.GT_Ship_Management.Register_Pilot">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
          </run_actions>
        </do_if>
        
        <set_value name="$pilotLevel" exact="0"/>
        <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$Level?">
          <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{$pilot}.$Level"/>
        </do_if>
        <do_if value="$modificationsEnabled and (not $pilot? or not global.$GT_Pilots? or not global.$GT_Pilots.{$pilot}? or not global.$GT_Pilots.{$pilot}.$Level?)">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Reconcile deferred for ' + $ship.idcode + ' - GT pilot registry not ready (pilot=' + (if $pilot? then $pilot.name else 'NONE') + ', source=' + $modificationsEnabledSource + ', effectiveEnabled=' + $modificationsEnabled + ')'" chance="100"/>
          </do_if>
          <return value="false"/>
        </do_if>

        <!-- Determine ship class -->
        <set_value name="$shipClass" exact="'unknown'"/>
        <do_if value="$ship.isclass.ship_xl">
          <set_value name="$shipClass" exact="'xl'"/>
        </do_if>
        <do_elseif value="$ship.isclass.ship_l">
          <set_value name="$shipClass" exact="'l'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.ship_m">
          <set_value name="$shipClass" exact="'m'"/>
        </do_elseif>
        <do_elseif value="$ship.isclass.ship_s">
          <set_value name="$shipClass" exact="'s'"/>
        </do_elseif>

        <!-- Determine desired penalty state -->
        <set_value name="$desiredPenaltyLevel" exact="0"/>
        <set_value name="$desiredPenaltyShipWare" exact="null"/>
        <set_value name="$desiredPenaltyEngineWare" exact="null"/>
        <do_if value="$modificationsEnabled and $shipClass == 'xl'">
          <do_if value="$pilotLevel le 1">
            <set_value name="$desiredPenaltyLevel" exact="3"/>
            <set_value name="$desiredPenaltyShipWare" exact="ware.mod_penalty_ship_severe"/>
            <set_value name="$desiredPenaltyEngineWare" exact="ware.mod_penalty_engine_severe"/>
          </do_if>
          <do_elseif value="$pilotLevel le 3">
            <set_value name="$desiredPenaltyLevel" exact="2"/>
            <set_value name="$desiredPenaltyShipWare" exact="ware.mod_penalty_ship_moderate"/>
            <set_value name="$desiredPenaltyEngineWare" exact="ware.mod_penalty_engine_moderate"/>
          </do_elseif>
          <do_elseif value="$pilotLevel le 6">
            <set_value name="$desiredPenaltyLevel" exact="1"/>
            <set_value name="$desiredPenaltyShipWare" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$desiredPenaltyEngineWare" exact="ware.mod_penalty_engine_light"/>
          </do_elseif>
        </do_if>
        <do_elseif value="$modificationsEnabled and $shipClass == 'l'">
          <do_if value="$pilotLevel le 1">
            <set_value name="$desiredPenaltyLevel" exact="2"/>
            <set_value name="$desiredPenaltyShipWare" exact="ware.mod_penalty_ship_moderate"/>
            <set_value name="$desiredPenaltyEngineWare" exact="ware.mod_penalty_engine_moderate"/>
          </do_if>
          <do_elseif value="$pilotLevel le 3">
            <set_value name="$desiredPenaltyLevel" exact="1"/>
            <set_value name="$desiredPenaltyShipWare" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$desiredPenaltyEngineWare" exact="ware.mod_penalty_engine_light"/>
          </do_elseif>
        </do_elseif>
        <do_elseif value="$modificationsEnabled and $shipClass == 'm'">
          <do_if value="$pilotLevel le 1">
            <set_value name="$desiredPenaltyLevel" exact="1"/>
            <set_value name="$desiredPenaltyShipWare" exact="ware.mod_penalty_ship_light"/>
            <set_value name="$desiredPenaltyEngineWare" exact="ware.mod_penalty_engine_light"/>
          </do_if>
        </do_elseif>

        <!-- Determine desired bonus state (only when no penalty is required) -->
        <set_value name="$desiredBonusLevel" exact="0"/>
        <set_value name="$desiredBonusShipWare" exact="null"/>
        <set_value name="$desiredBonusEngineWare" exact="null"/>
        <do_if value="$modificationsEnabled and $desiredPenaltyLevel == 0">
          <set_value name="$pilotModLevel" exact="0"/>
          <do_if value="$shipClass == 's'">
            <do_if value="$pilotLevel ge 7">
              <set_value name="$pilotModLevel" exact="3"/>
            </do_if>
            <do_elseif value="$pilotLevel ge 4">
              <set_value name="$pilotModLevel" exact="2"/>
            </do_elseif>
            <do_elseif value="$pilotLevel ge 2">
              <set_value name="$pilotModLevel" exact="1"/>
            </do_elseif>
          </do_if>
          <do_elseif value="$shipClass == 'm'">
            <do_if value="$pilotLevel ge 10">
              <set_value name="$pilotModLevel" exact="3"/>
            </do_if>
            <do_elseif value="$pilotLevel ge 7">
              <set_value name="$pilotModLevel" exact="2"/>
            </do_elseif>
            <do_elseif value="$pilotLevel ge 4">
              <set_value name="$pilotModLevel" exact="1"/>
            </do_elseif>
          </do_elseif>
          <do_elseif value="$shipClass == 'l'">
            <do_if value="$pilotLevel ge 13">
              <set_value name="$pilotModLevel" exact="3"/>
            </do_if>
            <do_elseif value="$pilotLevel ge 10">
              <set_value name="$pilotModLevel" exact="2"/>
            </do_elseif>
            <do_elseif value="$pilotLevel ge 7">
              <set_value name="$pilotModLevel" exact="1"/>
            </do_elseif>
          </do_elseif>
          <do_elseif value="$shipClass == 'xl'">
            <do_if value="$pilotLevel ge 15">
              <set_value name="$pilotModLevel" exact="3"/>
            </do_if>
            <do_elseif value="$pilotLevel ge 13">
              <set_value name="$pilotModLevel" exact="2"/>
            </do_elseif>
            <do_elseif value="$pilotLevel ge 10">
              <set_value name="$pilotModLevel" exact="1"/>
            </do_elseif>
          </do_elseif>

          <do_if value="$pilotModLevel ge 3 and ware.research_mod_ship_mk3.research.unlocked and ware.research_mod_engine_mk3.research.unlocked">
            <set_value name="$desiredBonusLevel" exact="3"/>
            <set_value name="$desiredBonusShipWare" exact="ware.mod_ship_gt_level3"/>
            <set_value name="$desiredBonusEngineWare" exact="ware.mod_engine_gt_level3"/>
          </do_if>
          <do_elseif value="$pilotModLevel ge 2 and ware.research_mod_ship_mk2.research.unlocked and ware.research_mod_engine_mk2.research.unlocked">
            <set_value name="$desiredBonusLevel" exact="2"/>
            <set_value name="$desiredBonusShipWare" exact="ware.mod_ship_gt_level2"/>
            <set_value name="$desiredBonusEngineWare" exact="ware.mod_engine_gt_level2"/>
          </do_elseif>
          <do_elseif value="$pilotModLevel ge 1 and ware.research_mod_ship_mk1.research.unlocked and ware.research_mod_engine_mk1.research.unlocked">
            <set_value name="$desiredBonusLevel" exact="1"/>
            <set_value name="$desiredBonusShipWare" exact="ware.mod_ship_gt_level1"/>
            <set_value name="$desiredBonusEngineWare" exact="ware.mod_engine_gt_level1"/>
          </do_elseif>
        </do_if>

        <!-- Final desired wares per slot -->
        <set_value name="$desiredShipWare" exact="null"/>
        <set_value name="$desiredEngineWare" exact="null"/>
        <do_if value="$desiredPenaltyLevel gt 0">
          <set_value name="$desiredShipWare" exact="$desiredPenaltyShipWare"/>
          <set_value name="$desiredEngineWare" exact="$desiredPenaltyEngineWare"/>
        </do_if>
        <do_elseif value="$desiredBonusLevel gt 0">
          <set_value name="$desiredShipWare" exact="$desiredBonusShipWare"/>
          <set_value name="$desiredEngineWare" exact="$desiredBonusEngineWare"/>
        </do_elseif>

        <!-- Resolve desired ware ids once and use id-based comparisons for update decisions. -->
        <set_value name="$desiredShipWareId" exact="null"/>
        <set_value name="$desiredEngineWareId" exact="null"/>
        <do_if value="$desiredShipWare?">
          <set_value name="$desiredShipWareId" exact="@$desiredShipWare.id"/>
          <do_if value="not $desiredShipWareId?">
            <set_value name="$desiredShipWareId" exact="$desiredShipWare"/>
          </do_if>
        </do_if>
        <do_if value="$desiredShipWareId == 'null' or $desiredShipWareId == 'none'">
          <set_value name="$desiredShipWareId" exact="null"/>
        </do_if>
        <do_if value="$desiredEngineWare?">
          <set_value name="$desiredEngineWareId" exact="@$desiredEngineWare.id"/>
          <do_if value="not $desiredEngineWareId?">
            <set_value name="$desiredEngineWareId" exact="$desiredEngineWare"/>
          </do_if>
        </do_if>
        <do_if value="$desiredEngineWareId == 'null' or $desiredEngineWareId == 'none'">
          <set_value name="$desiredEngineWareId" exact="null"/>
        </do_if>

        <!-- Current slot state -->
        <set_value name="$currentShipMod" exact="@$ship.equipmentmods.ship"/>
        <set_value name="$currentEngineMod" exact="@$ship.equipmentmods.engine"/>
        <set_value name="$hasAnyShipMod" exact="$ship.hasshipmod"/>
        <set_value name="$hasAnyEngineMod" exact="$ship.hasenginemod"/>
        <!-- Normalize placeholder/unknown slot values (including ware objects with id='null'). -->
        <set_value name="$currentShipModIdRaw" exact="null"/>
        <set_value name="$currentEngineModIdRaw" exact="null"/>
        <do_if value="$currentShipMod? and $currentShipMod.id?">
          <set_value name="$currentShipModIdRaw" exact="@$currentShipMod.id"/>
        </do_if>
        <do_elseif value="$currentShipMod?">
          <set_value name="$currentShipModIdRaw" exact="$currentShipMod"/>
        </do_elseif>
        <do_if value="$currentEngineMod? and $currentEngineMod.id?">
          <set_value name="$currentEngineModIdRaw" exact="@$currentEngineMod.id"/>
        </do_if>
        <do_elseif value="$currentEngineMod?">
          <set_value name="$currentEngineModIdRaw" exact="$currentEngineMod"/>
        </do_elseif>
        <do_if value="$currentShipModIdRaw == 'null' or $currentShipModIdRaw == 'none'">
          <set_value name="$currentShipMod" exact="null"/>
        </do_if>
        <do_if value="$currentEngineModIdRaw == 'null' or $currentEngineModIdRaw == 'none'">
          <set_value name="$currentEngineMod" exact="null"/>
        </do_if>
        <!-- Fallback detection for cases where slot ware introspection can be null -->
        <do_if value="not $currentShipMod? and $hasAnyShipMod">
          <do_if value="$ship.hasshipmod.{ware.mod_ship_gt_level1}">
            <set_value name="$currentShipMod" exact="ware.mod_ship_gt_level1"/>
          </do_if>
          <do_elseif value="$ship.hasshipmod.{ware.mod_ship_gt_level2}">
            <set_value name="$currentShipMod" exact="ware.mod_ship_gt_level2"/>
          </do_elseif>
          <do_elseif value="$ship.hasshipmod.{ware.mod_ship_gt_level3}">
            <set_value name="$currentShipMod" exact="ware.mod_ship_gt_level3"/>
          </do_elseif>
          <do_elseif value="$ship.hasshipmod.{ware.mod_penalty_ship_light}">
            <set_value name="$currentShipMod" exact="ware.mod_penalty_ship_light"/>
          </do_elseif>
          <do_elseif value="$ship.hasshipmod.{ware.mod_penalty_ship_moderate}">
            <set_value name="$currentShipMod" exact="ware.mod_penalty_ship_moderate"/>
          </do_elseif>
          <do_elseif value="$ship.hasshipmod.{ware.mod_penalty_ship_severe}">
            <set_value name="$currentShipMod" exact="ware.mod_penalty_ship_severe"/>
          </do_elseif>
        </do_if>
        <do_if value="not $currentEngineMod? and $hasAnyEngineMod">
          <do_if value="$ship.hasenginemod.{ware.mod_engine_gt_level1}">
            <set_value name="$currentEngineMod" exact="ware.mod_engine_gt_level1"/>
          </do_if>
          <do_elseif value="$ship.hasenginemod.{ware.mod_engine_gt_level2}">
            <set_value name="$currentEngineMod" exact="ware.mod_engine_gt_level2"/>
          </do_elseif>
          <do_elseif value="$ship.hasenginemod.{ware.mod_engine_gt_level3}">
            <set_value name="$currentEngineMod" exact="ware.mod_engine_gt_level3"/>
          </do_elseif>
          <do_elseif value="$ship.hasenginemod.{ware.mod_penalty_engine_light}">
            <set_value name="$currentEngineMod" exact="ware.mod_penalty_engine_light"/>
          </do_elseif>
          <do_elseif value="$ship.hasenginemod.{ware.mod_penalty_engine_moderate}">
            <set_value name="$currentEngineMod" exact="ware.mod_penalty_engine_moderate"/>
          </do_elseif>
          <do_elseif value="$ship.hasenginemod.{ware.mod_penalty_engine_severe}">
            <set_value name="$currentEngineMod" exact="ware.mod_penalty_engine_severe"/>
          </do_elseif>
        </do_if>
        <set_value name="$currentShipModId" exact="null"/>
        <set_value name="$currentEngineModId" exact="null"/>
        <do_if value="$currentShipMod? and $currentShipMod.id?">
          <set_value name="$currentShipModId" exact="@$currentShipMod.id"/>
        </do_if>
        <do_elseif value="$currentShipMod?">
          <set_value name="$currentShipModId" exact="$currentShipMod"/>
        </do_elseif>
        <do_if value="$currentEngineMod? and $currentEngineMod.id?">
          <set_value name="$currentEngineModId" exact="@$currentEngineMod.id"/>
        </do_if>
        <do_elseif value="$currentEngineMod?">
          <set_value name="$currentEngineModId" exact="$currentEngineMod"/>
        </do_elseif>
        <do_if value="$currentShipModId == 'null' or $currentShipModId == 'none'">
          <set_value name="$currentShipModId" exact="null"/>
          <set_value name="$currentShipMod" exact="null"/>
        </do_if>
        <do_if value="$currentEngineModId == 'null' or $currentEngineModId == 'none'">
          <set_value name="$currentEngineModId" exact="null"/>
          <set_value name="$currentEngineMod" exact="null"/>
        </do_if>
        <run_actions ref="GT_IsGTShipModWare" result="$currentShipIsGT">
          <param name="ware" value="$currentShipMod"/>
        </run_actions>
        <run_actions ref="GT_IsGTEngineModWare" result="$currentEngineIsGT">
          <param name="ware" value="$currentEngineMod"/>
        </run_actions>
        <!-- Runtime slot lookups can return a null-like placeholder even when no mod is installed.
             Use the actual slot-presence booleans as the source of truth for "non-GT mod present". -->
        <set_value name="$currentShipIsNonGT" exact="$hasAnyShipMod and not $currentShipIsGT"/>
        <set_value name="$currentEngineIsNonGT" exact="$hasAnyEngineMod and not $currentEngineIsGT"/>
        <set_value name="$unresolvedShipMod" exact="$hasAnyShipMod and not $currentShipMod?"/>
        <set_value name="$unresolvedEngineMod" exact="$hasAnyEngineMod and not $currentEngineMod?"/>
        <!-- Bridge unresolved MD slot state through Lua API: remove only known GT IDs -->
        <do_if value="$unresolvedShipMod or $unresolvedEngineMod">
          <set_value name="$shipIdCode" exact="@$ship.idcode"/>
          <raise_lua_event name="'GT_Mods.DismantleDetected'" param="$ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|reconcile-unresolved'"/>
        </do_if>

        <!-- Tracking-derived ownership flags (fallback when runtime slot introspection is ambiguous) -->
        <set_value name="$trackedHasShipSlot" exact="false"/>
        <set_value name="$trackedHasEngineSlot" exact="false"/>
        <set_value name="$trackedPenaltyShipMod" exact="null"/>
        <set_value name="$trackedPenaltyEngineMod" exact="null"/>
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots?">
          <do_all exact="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots.count" counter="$tsi">
            <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots.{$tsi} == 'ship'">
              <set_value name="$trackedHasShipSlot" exact="true"/>
            </do_if>
            <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots.{$tsi} == 'engine'">
              <set_value name="$trackedHasEngineSlot" exact="true"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod?">
          <set_value name="$trackedPenaltyShipMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
          <set_value name="$trackedHasShipSlot" exact="true"/>
        </do_if>
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod?">
          <set_value name="$trackedPenaltyEngineMod" exact="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
          <set_value name="$trackedHasEngineSlot" exact="true"/>
        </do_if>
        <set_value name="$hasLegacyPenaltyKey" exact="false"/>
        <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod?">
          <set_value name="$hasLegacyPenaltyKey" exact="true"/>
        </do_if>
        <set_value name="$allowUnresolvedShipRemoval" exact="$unresolvedShipMod and ($trackedHasShipSlot or $hasLegacyPenaltyKey)"/>
        <set_value name="$allowUnresolvedEngineRemoval" exact="$unresolvedEngineMod and ($trackedHasEngineSlot or $hasLegacyPenaltyKey)"/>
        <!-- If ship has a mod but slot introspection cannot resolve the ware, trust GT tracking ownership -->
        <do_if value="not $currentShipIsGT and $trackedHasShipSlot and $hasAnyShipMod">
          <set_value name="$currentShipIsGT" exact="true"/>
        </do_if>
        <do_if value="not $currentEngineIsGT and $trackedHasEngineSlot and $hasAnyEngineMod">
          <set_value name="$currentEngineIsGT" exact="true"/>
        </do_if>
        <!-- GT tracking is authoritative for ownership of previously managed slots.
             If tracking says the slot is ours, never let ambiguous runtime introspection
             block reinstall by classifying the slot as non-GT. -->
        <do_if value="$currentShipIsGT and $trackedHasShipSlot">
          <set_value name="$currentShipIsNonGT" exact="false"/>
        </do_if>
        <do_if value="$currentEngineIsGT and $trackedHasEngineSlot">
          <set_value name="$currentEngineIsNonGT" exact="false"/>
        </do_if>
        <!-- Force-GT authoritative paths (pilot_assignment/order recycle) can encounter
             a null-placeholder slot state with hasAny*=true after registry resets.
             Keep this path single-pass: probe GT ownership via Lua and continue reconcile
             in the same call (no deferred retry loops). -->
        <set_value name="$shipNullPlaceholderWithMod" exact="$hasAnyShipMod and (($currentShipModIdRaw == 'null') or ($currentShipModIdRaw == 'none') or ($currentShipModId == null))"/>
        <set_value name="$engineNullPlaceholderWithMod" exact="$hasAnyEngineMod and (($currentEngineModIdRaw == 'null') or ($currentEngineModIdRaw == 'none') or ($currentEngineModId == null))"/>
        <set_value name="$forceGTUnresolvedProbe" exact="false"/>
        <do_if value="$forceGTContext and (
          ($desiredShipWareId != null and $shipNullPlaceholderWithMod and not $currentShipIsGT and not $trackedHasShipSlot) or
          ($desiredEngineWareId != null and $engineNullPlaceholderWithMod and not $currentEngineIsGT and not $trackedHasEngineSlot)
        )">
          <set_value name="$forceGTUnresolvedProbe" exact="true"/>
        </do_if>
        <do_if value="$forceGTUnresolvedProbe">
          <set_value name="$shipIdCode" exact="@$ship.idcode"/>
          <raise_lua_event name="'GT_Mods.DismantleDetected'" param="$ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|reconcile-forcegt-probe'"/>
          <!-- Authoritative GT context: if slot identity is unresolved but desired GT ware exists,
               treat the slot as GT-managed for this reconcile pass.
               Lua probe only dismantles known GT wares; non-GT mods remain untouched. -->
          <do_if value="$desiredShipWareId != null and $shipNullPlaceholderWithMod">
            <set_value name="$currentShipIsGT" exact="true"/>
            <set_value name="$currentShipIsNonGT" exact="false"/>
          </do_if>
          <do_if value="$desiredEngineWareId != null and $engineNullPlaceholderWithMod">
            <set_value name="$currentEngineIsGT" exact="true"/>
            <set_value name="$currentEngineIsNonGT" exact="false"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Reconcile forceGT probe applied for ' + $ship.idcode + ' (shipPlaceholder=' + $shipNullPlaceholderWithMod + ', enginePlaceholder=' + $engineNullPlaceholderWithMod + ', trackedShip=' + $trackedHasShipSlot + ', trackedEngine=' + $trackedHasEngineSlot + ', desiredShip=' + (if $desiredShipWareId? then $desiredShipWareId else 'NONE') + ', desiredEngine=' + (if $desiredEngineWareId? then $desiredEngineWareId else 'NONE') + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Reconcile state ship=' + $ship.idcode + ', pilotLevel=' + $pilotLevel + ', class=' + $shipClass + ', desiredPenalty=' + $desiredPenaltyLevel + ', desiredBonus=' + $desiredBonusLevel + ', desiredShip=' + (if $desiredShipWare? then $desiredShipWare else 'NONE') + ', desiredEngine=' + (if $desiredEngineWare? then $desiredEngineWare else 'NONE') + ', hasAnyShip=' + $hasAnyShipMod + ', hasAnyEngine=' + $hasAnyEngineMod + ', currentShip=' + (if $currentShipMod? then $currentShipMod else 'NONE') + ', currentEngine=' + (if $currentEngineMod? then $currentEngineMod else 'NONE') + ', currentShipIsGT=' + $currentShipIsGT + ', currentEngineIsGT=' + $currentEngineIsGT + ', currentShipIsNonGT=' + $currentShipIsNonGT + ', currentEngineIsNonGT=' + $currentEngineIsNonGT + ', unresolvedShip=' + $unresolvedShipMod + ', unresolvedEngine=' + $unresolvedEngineMod + ', trackedShip=' + $trackedHasShipSlot + ', trackedEngine=' + $trackedHasEngineSlot" chance="100"/>
        </do_if>

        <!-- Hard-disable mode: remove only GT-managed mods and stop -->
        <do_if value="$removeGTModsOnly or not $modificationsEnabled">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Reconcile-disable reason ship=' + $ship.idcode + ', source=' + $modificationsEnabledSource + ', override=' + (if $modificationsEnabledOverride != null then $modificationsEnabledOverride else 'NULL') + ', removeOnly=' + $removeGTModsOnly + ', globalEnabled=' + $globalModificationsEnabled + ', effectiveEnabled=' + $modificationsEnabled + ', trackedShip=' + $trackedHasShipSlot + ', trackedEngine=' + $trackedHasEngineSlot + ', currentShipIsGT=' + $currentShipIsGT + ', currentEngineIsGT=' + $currentEngineIsGT + ', unresolvedShip=' + $unresolvedShipMod + ', unresolvedEngine=' + $unresolvedEngineMod" chance="100"/>
          </do_if>
          <set_value name="$shipIdCode" exact="@$ship.idcode"/>
          <!-- Deep fallback: when remove-only path sees installed mods but MD cannot classify them,
               ask Lua/CAPI to inspect the real installed ware IDs and remove only GT-owned mods. -->
          <set_value name="$needsLuaGTProbe" exact="false"/>
          <do_if value="($hasAnyShipMod and not $currentShipIsGT) or ($hasAnyEngineMod and not $currentEngineIsGT)">
            <set_value name="$needsLuaGTProbe" exact="true"/>
          </do_if>
          <do_if value="$needsLuaGTProbe">
            <raise_lua_event name="'GT_Mods.DismantleDetected'" param="$ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|reconcile-disable-probe'"/>
          </do_if>
          <do_if value="$currentShipIsGT or $trackedHasShipSlot or $allowUnresolvedShipRemoval">
            <set_value name="$shipModToRemove" exact="null"/>
            <do_if value="$currentShipIsGT">
              <set_value name="$shipModToRemove" exact="$currentShipMod"/>
            </do_if>
            <do_elseif value="$trackedPenaltyShipMod?">
              <set_value name="$shipModToRemove" exact="$trackedPenaltyShipMod"/>
            </do_elseif>
            <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $shipModToRemove"/>
          </do_if>
          <do_if value="$currentEngineIsGT or $trackedHasEngineSlot or $allowUnresolvedEngineRemoval">
            <set_value name="$engineModToRemove" exact="null"/>
            <do_if value="$currentEngineIsGT">
              <set_value name="$engineModToRemove" exact="$currentEngineMod"/>
            </do_if>
            <do_elseif value="$trackedPenaltyEngineMod?">
              <set_value name="$engineModToRemove" exact="$trackedPenaltyEngineMod"/>
            </do_elseif>
            <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $engineModToRemove"/>
          </do_if>

          <do_if value="$trackRegistryState">
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="[]"/>
            <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel" exact="0"/>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
            <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel"/>
          </do_if>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Reconcile-disable ' + $ship.idcode + ': removed GT-managed mods only (vanilla mods untouched)'" chance="if @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging then 100 else 0"/>
          </do_if>
          <return value="true"/>
        </do_if>

        <!-- Remove stale GT mods if they don't match desired state -->
        <set_value name="$shipIdCode" exact="@$ship.idcode"/>
        <!-- Legacy/unresolvable slot mods: force-clear slot so desired state can be restored -->
        <do_if value="$allowUnresolvedShipRemoval">
          <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|null'"/>
        </do_if>
        <do_if value="$allowUnresolvedEngineRemoval">
          <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|null'"/>
        </do_if>
        <do_if value="$currentShipIsGT and ($desiredShipWareId == null or $currentShipModId != $desiredShipWareId)">
          <raise_lua_event name="'GT_Mods.Dismantle'" param="'ship|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $currentShipMod"/>
        </do_if>
        <do_if value="$currentEngineIsGT and ($desiredEngineWareId == null or $currentEngineModId != $desiredEngineWareId)">
          <raise_lua_event name="'GT_Mods.Dismantle'" param="'engine|' + $ship + '|' + (if $shipIdCode? then $shipIdCode else 'UNKNOWN') + '|0|0|' + $currentEngineMod"/>
        </do_if>

        <!-- Simple authoritative rule:
             - empty slot => install GT mod when desired
             - player-owned slot => leave it alone
             - GT-owned slot with wrong ware => update it -->
        <set_value name="$shipSlotManagedByGT" exact="$desiredShipWareId != null and not $currentShipIsNonGT"/>
        <set_value name="$engineSlotManagedByGT" exact="$desiredEngineWareId != null and not $currentEngineIsNonGT"/>
        <do_if value="$desiredShipWareId != null and not $currentShipIsNonGT and ((not $hasAnyShipMod) or ($currentShipIsGT and $currentShipModId != $desiredShipWareId))">
          <raise_lua_event name="'GT_Mods.Install'" param="'ship|' + $ship + '|' + $ship.idcode + '|0|0|' + $desiredShipWareId"/>
        </do_if>
        <do_if value="$desiredEngineWareId != null and not $currentEngineIsNonGT and ((not $hasAnyEngineMod) or ($currentEngineIsGT and $currentEngineModId != $desiredEngineWareId))">
          <raise_lua_event name="'GT_Mods.Install'" param="'engine|' + $ship + '|' + $ship.idcode + '|0|0|' + $desiredEngineWareId"/>
        </do_if>

        <!-- Do not depend on same-tick slot introspection after installation.
             Track the intended GT-owned slots and let later refreshes observe the engine state. -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Reconcile apply ship=' + $ship.idcode + ', desiredShipId=' + (if $desiredShipWareId? then $desiredShipWareId else 'NONE') + ', desiredEngineId=' + (if $desiredEngineWareId? then $desiredEngineWareId else 'NONE') + ', manageShip=' + $shipSlotManagedByGT + ', manageEngine=' + $engineSlotManagedByGT" chance="100"/>
        </do_if>

        <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="[]"/>
        <do_if value="$shipSlotManagedByGT">
          <append_to_list name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="'ship'"/>
        </do_if>
        <do_if value="$engineSlotManagedByGT">
          <append_to_list name="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots" exact="'engine'"/>
        </do_if>

        <!-- Maintain penalty/bonus tracking keys -->
        <do_if value="$desiredPenaltyLevel gt 0 and $shipSlotManagedByGT and $engineSlotManagedByGT">
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod" exact="$desiredPenaltyShipWare"/>
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod" exact="$desiredPenaltyEngineWare"/>
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="$desiredPenaltyLevel"/>
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel" exact="0"/>
        </do_if>
        <do_else>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod"/>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod"/>
          <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel"/>
          <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel" exact="$desiredBonusLevel"/>
        </do_else>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Reconcile ' + $ship.idcode + ': enabled=' + $modificationsEnabled + ', pilot=' + $pilotLevel + ', class=' + $shipClass + ', desiredPenalty=' + $desiredPenaltyLevel + ', desiredBonus=' + $desiredBonusLevel + ', finalShip=' + @global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots.count" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>

    <!-- Reconcile all registered GT ships -->
    <library name="GT_Reconcile_All_GT_Ship_Modifications" purpose="run_actions">
      <params>
        <param name="modificationsEnabledOverride" default="null" comment="Optional override for global $Modifications.$Enabled (e.g. from settings-changed signal)"/>
      </params>
      <actions>
        <set_value name="$shouldEnableMods" exact="true"/>
        <do_if value="$modificationsEnabledOverride != null">
          <set_value name="$shouldEnableMods" exact="$modificationsEnabledOverride"/>
        </do_if>
        <do_elseif value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Modifications? and global.$GT_GlobalSettings.$Modifications.$Enabled?">
          <set_value name="$shouldEnableMods" exact="global.$GT_GlobalSettings.$Modifications.$Enabled"/>
        </do_elseif>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <do_all exact="global.$GT_Ships.keys.count" counter="$idx">
            <set_value name="$ship" exact="global.$GT_Ships.keys.{$idx}"/>
            <do_if value="$ship? and $ship.exists and not @$ship.iswreck and @$ship.isoperational">
              <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
                <param name="ship" value="$ship"/>
              </run_actions>
              <do_if value="not $shouldEnableMods or $gtStatus.$IsGTControlled">
                <run_actions ref="GT_Reconcile_Ship_Modifications">
                  <param name="ship" value="$ship"/>
                  <param name="pilot" value="@$ship.pilot"/>
                  <param name="modificationsEnabledOverride" value="$modificationsEnabledOverride"/>
                </run_actions>
              </do_if>
              <do_else>
                <run_actions ref="GT_Cleanup_NonGT_Ship_Modifications">
                  <param name="ship" value="$ship"/>
                </run_actions>
              </do_else>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </library>

    <library name="GT_Cleanup_NonGT_Ship_Modifications" purpose="run_actions">
      <params>
        <param name="ship" comment="Player-owned ship to validate after load"/>
      </params>
      <actions>
        <do_if value="not $ship? or not $ship.exists or not $ship.isplayerowned or @$ship.iswreck or not @$ship.isoperational">
          <return value="false"/>
        </do_if>

        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
          <param name="ship" value="$ship"/>
        </run_actions>
        <do_if value="$gtStatus.$IsGTControlled">
          <return value="false"/>
        </do_if>

        <set_value name="$hadRegistryEntry" exact="global.$GT_Ships? and global.$GT_Ships.{$ship}?"/>
        <set_value name="$currentShipMod" exact="@$ship.equipmentmods.ship"/>
        <set_value name="$currentEngineMod" exact="@$ship.equipmentmods.engine"/>
        <set_value name="$hasAnyShipMod" exact="$ship.hasshipmod"/>
        <set_value name="$hasAnyEngineMod" exact="$ship.hasenginemod"/>
        <do_if value="$currentShipMod == 'null' or $currentShipMod == 'none'">
          <set_value name="$currentShipMod" exact="null"/>
        </do_if>
        <do_if value="$currentEngineMod == 'null' or $currentEngineMod == 'none'">
          <set_value name="$currentEngineMod" exact="null"/>
        </do_if>
        <run_actions ref="GT_IsGTShipModWare" result="$currentShipIsGT">
          <param name="ware" value="$currentShipMod"/>
        </run_actions>
        <run_actions ref="GT_IsGTEngineModWare" result="$currentEngineIsGT">
          <param name="ware" value="$currentEngineMod"/>
        </run_actions>

        <set_value name="$trackedNeedsCleanup" exact="false"/>
        <do_if value="$hadRegistryEntry and global.$GT_Ships.{$ship}.$GTModifications?">
          <do_if value="global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots? and global.$GT_Ships.{$ship}.$GTModifications.$GTInstalledSlots.count gt 0">
            <set_value name="$trackedNeedsCleanup" exact="true"/>
          </do_if>
          <do_elseif value="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod? or global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod?">
            <set_value name="$trackedNeedsCleanup" exact="true"/>
          </do_elseif>
          <do_elseif value="global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel? and global.$GT_Ships.{$ship}.$GTModifications.$InstalledLevel gt 0">
            <set_value name="$trackedNeedsCleanup" exact="true"/>
          </do_elseif>
        </do_if>

        <set_value name="$identifiedGTMods" exact="($hasAnyShipMod and $currentShipIsGT) or ($hasAnyEngineMod and $currentEngineIsGT)"/>
        <set_value name="$needsCleanup" exact="$identifiedGTMods or $trackedNeedsCleanup or $gtStatus.$ShouldCleanup"/>
        <do_if value="not $needsCleanup">
          <return value="false"/>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Load cleanup scan: ship=' + $ship.idcode + ', default=' + (if $ship.defaultorder? then @$ship.defaultorder.id else 'NONE') + ', current=' + (if $ship.order? then @$ship.order.id else 'NONE') + ', identifiedGTMods=' + $identifiedGTMods + ', trackedNeedsCleanup=' + $trackedNeedsCleanup + ', shouldCleanup=' + $gtStatus.$ShouldCleanup" chance="100"/>
        </do_if>

        <run_actions ref="GT_Reconcile_Ship_Modifications">
          <param name="ship" value="$ship"/>
          <param name="pilot" value="@$ship.pilot"/>
          <param name="removeGTModsOnly" value="true"/>
        </run_actions>

        <!-- Avoid turning non-GT ships into persistent GT registry entries just because we scanned them. -->
        <do_if value="not $hadRegistryEntry and global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <remove_value name="global.$GT_Ships.{$ship}"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>
    
    <!-- MIGRATION: Clean up old penalty mod data on game load -->
    <!-- Handles save games with old $GTPenaltyMod entries (ware.mod_penalty_severe/moderate/light) -->
    <!-- Converts to new structure ($GTPenaltyShipMod and $GTPenaltyEngineMod) -->
    <cue name="MigrateOldPenaltyModData" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_game_started/>
        </check_any>
      </conditions>
      <actions>
        <set_value name="$migrationCount" exact="0"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$shipKeys" exact="@global.$GT_Ships.keys"/>
          <set_value name="$keysCount" exact="@$shipKeys.count"/>
          <do_if value="$keysCount? and $keysCount gt 0">
            <do_all exact="$keysCount" counter="$i">
              <set_value name="$ship" exact="$shipKeys.{$i}"/>
              <set_value name="$shipData" exact="@global.$GT_Ships.{$ship}"/>
              
              <!-- Check if ship has old penalty mod structure -->
              <do_if value="$shipData.$GTModifications? and 
                            $shipData.$GTModifications.$GTPenaltyMod? and 
                            (not $shipData.$GTModifications.$GTPenaltyShipMod? or not $shipData.$GTModifications.$GTPenaltyEngineMod?)">
                <!-- Use safe operator to get old mod (may be invalid due to import failure) -->
                <set_value name="$oldPenaltyMod" exact="@$shipData.$GTModifications.$GTPenaltyMod"/>
                <set_value name="$migratedShipMod" exact="null"/>
                <set_value name="$migratedEngineMod" exact="null"/>
                <set_value name="$oldModId" exact="null"/>
                
                <!-- Try to get old mod ID as string (ware might not exist due to import failure) -->
                <do_if value="$oldPenaltyMod?">
                  <set_value name="$oldModId" exact="@$oldPenaltyMod.id"/>
                  <do_if value="not $oldModId?">
                    <!-- If .id doesn't work, try to get it as string directly (might be stored as string) -->
                    <set_value name="$oldModId" exact="$oldPenaltyMod"/>
                  </do_if>
                </do_if>
                
                <!-- Map old ware IDs to new separate ship/engine wares by comparing ID strings -->
                <do_if value="$oldModId? and $oldModId == 'mod_penalty_severe'">
                  <set_value name="$migratedShipMod" exact="ware.mod_penalty_ship_severe"/>
                  <set_value name="$migratedEngineMod" exact="ware.mod_penalty_engine_severe"/>
                  <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="3"/>
                </do_if>
                <do_elseif value="$oldModId? and $oldModId == 'mod_penalty_moderate'">
                  <set_value name="$migratedShipMod" exact="ware.mod_penalty_ship_moderate"/>
                  <set_value name="$migratedEngineMod" exact="ware.mod_penalty_engine_moderate"/>
                  <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="2"/>
                </do_elseif>
                <do_elseif value="$oldModId? and $oldModId == 'mod_penalty_light'">
                  <set_value name="$migratedShipMod" exact="ware.mod_penalty_ship_light"/>
                  <set_value name="$migratedEngineMod" exact="ware.mod_penalty_engine_light"/>
                  <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyLevel" exact="1"/>
                </do_elseif>
                
                <!-- Store migrated values and remove old entry -->
                <do_if value="$migratedShipMod? and $migratedEngineMod?">
                  <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyShipMod" exact="$migratedShipMod"/>
                  <set_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyEngineMod" exact="$migratedEngineMod"/>
                  <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod"/>
                  <set_value name="$migrationCount" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$oldModName" exact="if $oldModId? then $oldModId else 'INVALID_IMPORT'"/>
                    <set_value name="$shipModName" exact="@$migratedShipMod.name"/>
                    <set_value name="$engineModName" exact="@$migratedEngineMod.name"/>
                    <debug_text text="'[GT-Penalty] Migration: Migrated old penalty mod for ' + $ship.idcode + ' (old: ' + $oldModName + ' ship: ' + (if $shipModName? then $shipModName else 'UNKNOWN') + ', engine: ' + (if $engineModName? then $engineModName else 'UNKNOWN') + ')'" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <!-- Old mod not recognized or import failed - remove invalid entry -->
                  <remove_value name="global.$GT_Ships.{$ship}.$GTModifications.$GTPenaltyMod"/>
                  <set_value name="$migrationCount" operation="add"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$oldModName" exact="if $oldModId? then $oldModId else 'INVALID_IMPORT'"/>
                    <debug_text text="'[GT-Penalty] Migration: Removed invalid/unrecognized old penalty mod for ' + $ship.idcode + ' (old: ' + $oldModName + ' - likely import failure)'" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
            </do_all>
          </do_if>
        </do_if>
        
        <do_if value="$migrationCount gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Penalty] Migration: Migrated ' + $migrationCount + ' old penalty mod entries to new structure'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Mod removal/install Lua is loaded via ui.xml like the other RegisterEvent-based UI helpers.
         Avoid Lua_Loader indirection here so event registration lives in the regular UI context. -->
    <cue name="Load_ModRemoval_Lua" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'Lua_Loader'" control="'Ready'" />
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Mod removal Lua module is provided via ui.xml'" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- Save-load cleanup for stale GT-owned mods on non-GT ships.
         This scans the whole player fleet after load, leaves active GT ships untouched,
         and removes only GT-managed mods from ships that are no longer GT-controlled. -->
    <cue name="CleanupStaleNonGTModsOnLoad" instantiate="true" version="1">
      <conditions>
        <event_game_loaded/>
      </conditions>
      <delay exact="5s"/>
      <actions>
        <set_value name="$cleanedCount" exact="0"/>
        <find_ship_by_true_owner name="$playerShips" faction="faction.player" space="player.galaxy" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true" checkoperational="true"/>
        <do_if value="$playerShips.count gt 0">
          <do_all exact="$playerShips.count" counter="$i">
            <set_value name="$ship" exact="$playerShips.{$i}"/>
            <run_actions ref="GT_Cleanup_NonGT_Ship_Modifications" result="$cleaned">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="$cleaned">
              <set_value name="$cleanedCount" operation="add"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Load cleanup completed: scanned=' + (if $playerShips.count? then $playerShips.count else 0) + ', cleaned=' + $cleanedCount" chance="100"/>
        </do_if>
      </actions>
    </cue>

    <!-- Triggered when mod settings are toggled in menu - immediate install on GT registered ships -->
    <!-- Store override in global BEFORE delay: event.param2 may not persist across delay. -->
    <cue name="ReconcileModificationsOnSettingsChanged" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Modifications_Settings_Changed'"/>
      </conditions>
      <actions>
        <!-- Extract $Enabled from signal - must capture both true AND false (not just truthy). -->
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$enabledOverride" exact="null"/>
        <do_if value="$params?">
          <do_if value="$params.$Enabled == true or $params.$Enabled == false">
            <set_value name="$enabledOverride" exact="$params.$Enabled"/>
          </do_if>
          <do_else>
            <set_value name="$enabledOverride" exact="global.$GT_GlobalSettings.$Modifications.$Enabled"/>
          </do_else>
        </do_if>
        <!-- Persist before delay - event.param2 does not survive cue resume -->
        <set_value name="global.$GT_ModReconcilePendingOverride" exact="$enabledOverride"/>
      </actions>
      <delay exact="200ms"/>
      <actions>
        <set_value name="$enabledOverride" exact="global.$GT_ModReconcilePendingOverride"/>
        <remove_value name="global.$GT_ModReconcilePendingOverride"/>
        <!-- Fallback: if override was null, use global (e.g. signal param structure differed) -->
        <do_if value="$enabledOverride == null and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Modifications? and global.$GT_GlobalSettings.$Modifications.$Enabled?">
          <set_value name="$enabledOverride" exact="global.$GT_GlobalSettings.$Modifications.$Enabled"/>
        </do_if>
        <run_actions ref="GT_Reconcile_All_GT_Ship_Modifications">
          <param name="modificationsEnabledOverride" value="$enabledOverride"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Delayed refresh for GT assignment/recycle paths.
         This avoids racing against late removal/dismantle from the previous GT order instance. -->
    <cue name="DeferredShipModificationRefresh" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh"/>
      </conditions>
      <delay exact="300ms"/>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ship" exact="@$data.$Ship"/>
        <set_value name="$source" exact="if $data? and $data.$source? then $data.$source else 'unknown'"/>
        <set_value name="$attempt" exact="if $data? and $data.$attempt? then $data.$attempt else 1"/>
        <set_value name="$forceGTContext" exact="if $data? and $data.$forceGTContext? then $data.$forceGTContext else false"/>
        
        <do_if value="(not $ship?) and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] Deferred refresh skipped: missing ship in payload (source=' + $source + ', attempt=' + $attempt + ')'" chance="100"/>
        </do_if>

        <do_if value="$ship? and $ship.exists and not @$ship.iswreck and @$ship.isoperational">
          <set_value name="$pilot" exact="if $ship.pilot? then $ship.pilot else null"/>
          <set_value name="$pilotNameDbg" exact="if $pilot and $pilot.exists and $pilot.name? then $pilot.name else 'NONE'"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$defaultOrderId" exact="'NONE'"/>
            <set_value name="$currentOrderId" exact="'NONE'"/>
            <set_value name="$commanderOrderId" exact="'NONE'"/>
            <do_if value="$ship.defaultorder?">
              <set_value name="$defaultOrderId" exact="@$ship.defaultorder.id"/>
            </do_if>
            <do_if value="$ship.order?">
              <set_value name="$currentOrderId" exact="@$ship.order.id"/>
            </do_if>
            <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander.defaultorder?">
              <set_value name="$commanderOrderId" exact="@$ship.commander.defaultorder.id"/>
            </do_if>
            <debug_text text="'[GT-Mods] Deferred refresh entry ship=' + $ship.idcode + ', source=' + $source + ', attempt=' + $attempt + ', forceGTContext=' + $forceGTContext + ', pilot=' + $pilotNameDbg + ', default=' + $defaultOrderId + ', current=' + $currentOrderId + ', commanderOrder=' + $commanderOrderId" chance="100"/>
          </do_if>

          <set_value name="$refreshComplete" exact="true"/>
          <do_if value="md.GT_Ship_Modifications.Install_GT_Modifications?">
            <run_actions ref="md.GT_Ship_Modifications.Install_GT_Modifications" result="$refreshComplete">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="forceGTContext" value="$forceGTContext"/>
            </run_actions>
          </do_if>
          
          <do_if value="not $refreshComplete and $attempt lt 4">
            <signal_cue_instantly cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh" param="table[
              $Ship = $ship,
              $source = $source,
              $attempt = $attempt + 1,
              $forceGTContext = $forceGTContext
            ]"/>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Deferred refresh processed for ' + $ship.idcode + ' source=' + $source + ' attempt=' + $attempt + ' complete=' + $refreshComplete" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Install Modifications When GT Order is Assigned -->
    <cue name="InstallModifications" instantiate="true">
      <conditions>
        <event_object_order_ready object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
        <check_value value="global.$GT_ProtectedOrderIDs? and event.param? and event.param.id? and global.$GT_ProtectedOrderIDs.indexof.{@event.param.id}"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Mods] GT order assigned - installing modifications for ship: ' + $ship.idcode" chance="100"/>
        </do_if>
        
        <signal_cue_instantly cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh" param="table[
          $Ship = $ship,
          $source = 'order_ready',
          $forceGTContext = true
        ]"/>
      </actions>
    </cue>
    
    <!-- Install modifications when ship gets a GT commander (covers subordinate attach paths) -->
    <cue name="InstallModificationsOnCommanderSet" instantiate="true">
      <conditions>
        <event_object_commander_set object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
      </conditions>
      <delay exact="100ms"/>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <set_value name="$newCommander" exact="event.param"/>
        <set_value name="$commanderHasGT" exact="false"/>
        
        <do_if value="$newCommander? and $newCommander.exists and $newCommander != $ship">
          <do_if value="$newCommander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$newCommander.defaultorder.id})">
            <set_value name="$commanderHasGT" exact="true"/>
          </do_if>
        </do_if>
        
        <do_if value="$commanderHasGT">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Commander set to GT commander - installing subordinate modifications for: ' + $ship.idcode" chance="100"/>
          </do_if>
          
          <signal_cue_instantly cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh" param="table[
            $Ship = $ship,
            $source = 'commander_set',
            $forceGTContext = true
          ]"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Also listen to state updates for GT_Order_Assigned and Commander_Changed (if sent) -->
    <cue name="InstallModificationsFromState" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_State_Update'"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$updateType" exact="$params.$UpdateType"/>
        
        <!-- Process GT_Order_Assigned events -->
        <do_if value="$updateType == 'GT_Order_Assigned'">
          <set_value name="$ship" exact="$params.$Ship"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Installing modifications for ship: ' + $ship.idcode + ' (from state update - GT order assigned)'" chance="100"/>
          </do_if>
          
          <signal_cue_instantly cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh" param="table[
            $Ship = $ship,
            $source = 'state_gt_order_assigned',
            $forceGTContext = true
          ]"/>
        </do_if>
        
        <!-- Process Commander_Changed events - install mods when ship becomes subordinate to GT commander -->
        <do_elseif value="$updateType == 'Commander_Changed'">
          <set_value name="$ship" exact="$params.$Ship"/>
          <set_value name="$commanderHasGT" exact="false"/>
          <do_if value="$params.$CommanderHasGT?">
            <set_value name="$commanderHasGT" exact="$params.$CommanderHasGT"/>
          </do_if>
          
          <!-- Only install mods if commander has GT order -->
          <do_if value="$commanderHasGT">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Mods] Installing modifications for subordinate: ' + $ship.idcode + ' (commander has GT order)'" chance="100"/>
            </do_if>
            
            <signal_cue_instantly cue="md.GT_Ship_Modifications.DeferredShipModificationRefresh" param="table[
              $Ship = $ship,
              $source = 'state_commander_changed',
              $forceGTContext = true
            ]"/>
          </do_if>
        </do_elseif>
      </actions>
    </cue>
    
    <!-- Remove Modifications When GT Order is Cancelled -->
    <cue name="RemoveModifications" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_State_Update'"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$updateType" exact="@$params.$UpdateType"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        
        <!-- PERFORMANCE FIX: Early exit check for non-GT ships -->
        <!-- Only process GT_Order_Cancelled events for ships that were GT-controlled -->
        <set_value name="$shouldProcess" exact="false"/>
        
        <!-- Only process GT_Order_Cancelled events -->
        <do_if value="$updateType == 'GT_Order_Cancelled'">
          <!-- PRIMARY CHECK: Is ship in GT_Ships registry? (definitive indicator it was GT-controlled) -->
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
            <set_value name="$shouldProcess" exact="true"/>
          </do_if>
          <do_else>
            <!-- Fallback: Check if ship currently has GT order (might be removing but still has order) -->
            <set_value name="$hasGTOrder" exact="false"/>
            <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
              <set_value name="$hasGTOrder" exact="true"/>
            </do_if>
            <do_if value="not $hasGTOrder and $ship.commander? and $ship.commander.exists and $ship.commander != $ship">
              <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
                <set_value name="$hasGTOrder" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="$hasGTOrder">
              <set_value name="$shouldProcess" exact="true"/>
            </do_if>
          </do_else>
        </do_if>
        
        <!-- EARLY EXIT: If ship is not GT-controlled, exit immediately without logging -->
        <!-- Ship IS GT-controlled and update type is GT_Order_Cancelled - proceed -->
        <do_if value="$shouldProcess">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Remove cue entry ship=' + $ship.idcode + ', updateType=' + (if $updateType then $updateType else 'NULL') + ', shouldProcess=' + $shouldProcess" chance="100"/>
          </do_if>
          
          <!-- SAFEGUARD: Never remove mods while ship is still GT-controlled -->
          <!-- A stale GT_Order_Cancelled can be emitted during script restarts on subordinates. -->
          <set_value name="$hasDirectGTOrder" exact="false"/>
          <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
            <set_value name="$hasDirectGTOrder" exact="true"/>
          </do_if>
          <set_value name="$hasGTCommander" exact="false"/>
          <do_if value="not $hasDirectGTOrder and $ship.commander? and $ship.commander.exists and $ship.commander != $ship">
            <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
              <set_value name="$hasGTCommander" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- Only proceed if ship has neither direct GT order nor GT commander -->
          <do_if value="not $hasDirectGTOrder and not $hasGTCommander">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Mods] Remove cue executing disable reconcile for ' + $ship.idcode + ' (direct=' + $hasDirectGTOrder + ', viaCommander=' + $hasGTCommander + ', updateType=' + $updateType + ')'" chance="100"/>
            </do_if>
            <!-- CRITICAL FIX: Release search locks and clear home refresh markers when GT order is cancelled -->
            <!-- This prevents ships from blocking others after losing their GT order -->
            <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'gt_order_cancelled'"/>
            </run_actions>
            
            <!-- Clear home refresh marker if this ship was the initiator -->
            <do_if value="global.$GT_TS_LiveRefreshBySector? and global.$GT_TS_LiveRefreshBySector.keys.count gt 0">
              <do_all exact="global.$GT_TS_LiveRefreshBySector.keys.count" counter="$hsIdx">
                <set_value name="$hs" exact="global.$GT_TS_LiveRefreshBySector.keys.{$hsIdx}"/>
                <do_if value="$hs? and global.$GT_TS_LiveRefreshBySector.{$hs}?">
                  <set_value name="$refreshEntry" exact="global.$GT_TS_LiveRefreshBySector.{$hs}"/>
                  <do_if value="$refreshEntry? and $refreshEntry.$Initiator? and $refreshEntry.$Initiator == $ship">
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Mods] Clearing home refresh marker (home=' + @$hs.knownname + ', initiator=' + $ship.idcode + ' lost GT order)'" chance="100"/>
                    </do_if>
                    <remove_value name="global.$GT_TS_LiveRefreshBySector.{$hs}"/>
                  </do_if>
                </do_if>
              </do_all>
            </do_if>
            
            <run_actions ref="md.GT_Ship_Modifications.GT_Reconcile_Ship_Modifications">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="@$ship.pilot"/>
              <param name="removeGTModsOnly" value="true"/>
            </run_actions>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Mods]  SAFEGUARD: Skipping mod removal for ' + $ship.idcode + ' - ship still GT-controlled (direct=' + $hasDirectGTOrder + ', viaCommander=' + $hasGTCommander + ')'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <!-- Ship is not GT-controlled or update type is not GT_Order_Cancelled - exit silently -->
          <!-- This prevents stutter from constant property lookups for non-GT ships -->
        </do_else>
      </actions>
    </cue>
    
    <!-- Backup: Remove Modifications When Name Restoration Signal is Sent -->
    <!-- This ensures mods are removed even if GT_Ship_State_Update signal is missed -->
    <cue name="RemoveModificationsOnNameRestore" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_Order_Aborted'"/>
      </conditions>
      <actions>
        <set_value name="$abortData" exact="event.param2"/>
        <set_value name="$ship" exact="$abortData.$Ship"/>
        <set_value name="$reason" exact="@$abortData.$Reason"/>
        
        <!-- Process all GT_Ship_Order_Aborted signals.
             SAFEGUARD below skips if ship is still GT-controlled (directly or via commander),
             so this remains safe while covering additional abort reasons. -->
        <do_if value="$ship? and $ship.exists">
          <!-- SAFEGUARD: ignore stale abort signals if ship is still subordinate to GT commander -->
          <set_value name="$hasDirectGTOrder" exact="false"/>
          <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
            <set_value name="$hasDirectGTOrder" exact="true"/>
          </do_if>
          <set_value name="$hasGTCommander" exact="false"/>
          <do_if value="not $hasDirectGTOrder and $ship.commander? and $ship.commander.exists and $ship.commander != $ship">
            <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
              <set_value name="$hasGTCommander" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="$hasDirectGTOrder or $hasGTCommander">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Mods]  SAFEGUARD: Skipping backup removal for ' + $ship.idcode + ' - ship still GT-controlled (direct=' + $hasDirectGTOrder + ', viaCommander=' + $hasGTCommander + ', reason=' + $reason + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Mods] Backup removal executing disable reconcile for ' + $ship.idcode + ' (reason=' + (if $reason? and $reason != '' then $reason else 'UNSPECIFIED') + ', direct=' + $hasDirectGTOrder + ', viaCommander=' + $hasGTCommander + ')'" chance="100"/>
          </do_if>
          <run_actions ref="md.GT_Ship_Modifications.GT_Reconcile_Ship_Modifications">
            <param name="ship" value="$ship"/>
            <param name="pilot" value="@$ship.pilot"/>
            <param name="removeGTModsOnly" value="true"/>
          </run_actions>
          </do_else>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Ship_Naming_Pattern" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>

    <!-- Shared op-state flag detection for legacy + pattern naming -->
    <library name="GT_Collect_Ship_OpState_Flags" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to inspect"/>
      </params>
      <actions>
        <set_value name="$flags" exact="table[
          $ShowCustomBlacklist = false,
          $Escape = false,
          $Reroute = false,
          $Clearance = false,
          $Unreachable = false,
          $PilotExchange = false,
          $HasRepair = false,
          $HasResupply = false
        ]"/>

        <set_value name="$mk3BlacklistOwnerForTag" exact="$ship"/>
        <set_value name="$isShipAffectedByCustomBlacklist" exact="false"/>
        <do_if value="$ship.commander? and $ship.commander.exists">
          <do_if value="$ship.commander.defaultorder?">
            <do_if value="@$ship.commander.defaultorder.id == 'GalaxyTraderMK3'">
              <set_value name="$mk3BlacklistOwnerForTag" exact="$ship.commander"/>
              <set_value name="$isShipAffectedByCustomBlacklist" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK3'">
          <set_value name="$mk3BlacklistOwnerForTag" exact="$ship"/>
          <set_value name="$isShipAffectedByCustomBlacklist" exact="true"/>
        </do_elseif>
        <do_if value="$isShipAffectedByCustomBlacklist and global.$GT_MK3FactionBlacklist? and global.$GT_MK3FactionBlacklist.$ShipSelections? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerForTag}? and global.$GT_MK3FactionBlacklist.$ShipSelections.{$mk3BlacklistOwnerForTag}.keys.count gt 0">
          <set_value name="$flags.$ShowCustomBlacklist" exact="true"/>
        </do_if>

        <do_if value="global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
          <set_value name="$flags.$HasResupply" exact="true"/>
        </do_if>

        <set_value name="$isGTRelated" exact="false"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <set_value name="$isGTRelated" exact="true"/>
        </do_if>
        <do_else>
          <set_value name="$commander" exact="@$ship.commander"/>
          <do_if value="$commander? and global.$GT_Ships? and global.$GT_Ships.{$commander}?">
            <set_value name="$isGTRelated" exact="true"/>
          </do_if>
        </do_else>

        <do_if value="$isGTRelated">
          <set_value name="$activeOrderId" exact="@$ship.order.id"/>
          <do_if value="$activeOrderId == 'Equip' or $activeOrderId == 'Resupply'">
            <set_value name="$flags.$HasResupply" exact="true"/>
          </do_if>
          <do_elseif value="$activeOrderId == 'Repair'">
            <set_value name="$flags.$HasRepair" exact="true"/>
          </do_elseif>
        </do_if>

        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <set_value name="$shipData" exact="global.$GT_Ships.{$ship}"/>
          <do_if value="$shipData.$NeedsRepair? and $shipData.$NeedsRepair">
            <set_value name="$flags.$HasRepair" exact="true"/>
          </do_if>
          <do_if value="$shipData.$Escaping? and $shipData.$Escaping">
            <set_value name="$flags.$Escape" exact="true"/>
          </do_if>
          <do_if value="$shipData.$Rerouting? and $shipData.$Rerouting">
            <set_value name="$flags.$Reroute" exact="true"/>
          </do_if>
          <do_if value="$shipData.$CargoDisposal? and $shipData.$CargoDisposal">
            <set_value name="$flags.$Clearance" exact="true"/>
          </do_if>
          <do_if value="$shipData.$Unreachable? and $shipData.$Unreachable">
            <set_value name="$flags.$Unreachable" exact="true"/>
          </do_if>
          <set_value name="$showPilotExchangeState" exact="false"/>
          <do_if value="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$namePeStatus">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="$namePeStatus.$ShouldKeepPE">
              <set_value name="$showPilotExchangeState" exact="true"/>
            </do_if>
          </do_if>
          <do_elseif value="$shipData.$PilotExchange? and $shipData.$PilotExchange">
            <set_value name="$showPilotExchangeState" exact="true"/>
          </do_elseif>
          <do_if value="$showPilotExchangeState">
            <set_value name="$flags.$PilotExchange" exact="true"/>
          </do_if>
        </do_if>

        <return value="$flags"/>
      </actions>
    </library>

    <!-- Multi-flag OPSTATE string for pattern mode (plain abbreviations, space-separated) -->
    <library name="GT_Build_Pattern_OpState" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to inspect"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Collect_Ship_OpState_Flags" result="$flags">
          <param name="ship" value="$ship"/>
        </run_actions>
        <set_value name="$parts" exact="[]"/>
        <set_value name="$abbr" exact="''"/>

        <do_if value="$flags.$ShowCustomBlacklist">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'CustomBlacklist'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_if value="$flags.$Escape">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'Escape'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_if value="$flags.$Reroute">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'Reroute'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_if value="$flags.$Clearance">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'Clearance'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_if value="$flags.$Unreachable">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'Unreachable'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_if value="$flags.$PilotExchange">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'PilotExchange'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_if value="$flags.$HasRepair and $flags.$HasResupply">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
            <param name="stateType" value="'Maintenance'"/>
          </run_actions>
          <append_to_list name="$parts" exact="$abbr"/>
        </do_if>
        <do_else>
          <do_if value="$flags.$HasRepair">
            <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
              <param name="stateType" value="'Repair'"/>
            </run_actions>
            <append_to_list name="$parts" exact="$abbr"/>
          </do_if>
          <do_if value="$flags.$HasResupply">
            <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$abbr">
              <param name="stateType" value="'Resupply'"/>
            </run_actions>
            <append_to_list name="$parts" exact="$abbr"/>
          </do_if>
        </do_else>

        <set_value name="$result" exact="''"/>
        <do_all exact="$parts.count" counter="$i">
          <do_if value="$i gt 1">
            <set_value name="$result" exact="$result + ' '"/>
          </do_if>
          <set_value name="$result" exact="$result + $parts.{$i}"/>
        </do_all>
        <return value="$result"/>
      </actions>
    </library>

    <!-- STATUS token for pattern mode -->
    <library name="GT_Build_Pattern_Status" purpose="run_actions">
      <params>
        <param name="nameType" default="'trader'"/>
      </params>
      <actions>
        <set_value name="$result" exact="''"/>
        <do_if value="$nameType == 'blocked'">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$result">
            <param name="stateType" value="'Blocked'"/>
          </run_actions>
        </do_if>
        <do_elseif value="$nameType == 'training'">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$result">
            <param name="stateType" value="'Training'"/>
          </run_actions>
        </do_elseif>
        <do_elseif value="$nameType == 'fallback'">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$result">
            <param name="stateType" value="'Fallback'"/>
          </run_actions>
        </do_elseif>
        <do_elseif value="$nameType == 'isolated'">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$result">
            <param name="stateType" value="'Isolated'"/>
          </run_actions>
        </do_elseif>
        <return value="$result"/>
      </actions>
    </library>

    <!-- Atomic state token from collected flags -->
    <library name="GT_Build_Pattern_Atomic_State" purpose="run_actions">
      <params>
        <param name="flags"/>
        <param name="stateType" comment="State key for Get_State_Abbreviation"/>
        <param name="active" default="false"/>
      </params>
      <actions>
        <set_value name="$result" exact="''"/>
        <do_if value="$active">
          <run_actions ref="md.GT_Ship_Management.Get_State_Abbreviation" result="$result">
            <param name="stateType" value="$stateType"/>
          </run_actions>
        </do_if>
        <return value="$result"/>
      </actions>
    </library>

    <library name="GT_Collapse_Pattern_Whitespace" purpose="run_actions">
      <params>
        <param name="text"/>
      </params>
      <actions>
        <set_value name="$result" exact="$text"/>
        <do_all exact="8" counter="$wsPass">
          <substitute_text source="$result" text="$result">
            <replace string="'  '" with="' '"/>
          </substitute_text>
        </do_all>
        <return value="$result"/>
      </actions>
    </library>

    <library name="GT_Pattern_ReplaceToken" purpose="run_actions">
      <params>
        <param name="text"/>
        <param name="token" comment="Token including braces, e.g. {MODEL}"/>
        <param name="value"/>
      </params>
      <actions>
        <set_value name="$result" exact="$text"/>
        <substitute_text source="$result" text="$result">
          <replace string="$token" with="$value"/>
        </substitute_text>
        <return value="$result"/>
      </actions>
    </library>

    <!-- Resolve $NamePattern into a display ship name -->
    <library name="GT_Resolve_Ship_Name_Pattern" purpose="run_actions">
      <params>
        <param name="ship"/>
        <param name="pilot" default="null"/>
        <param name="nameType" default="'trader'"/>
        <param name="currentXP" default="0"/>
        <param name="currentLevel" default="1"/>
        <param name="rankTitle" default="''"/>
      </params>
      <actions>
        <set_value name="$pattern" exact="'{OPSTATE} {STATUS} {MODEL} ({RANK} {LVL_LABEL} XP:{XP})'"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$ShipNaming? and global.$GT_GlobalSettings.$ShipNaming.$NamePattern? and global.$GT_GlobalSettings.$ShipNaming.$NamePattern != ''">
          <set_value name="$pattern" exact="global.$GT_GlobalSettings.$ShipNaming.$NamePattern"/>
        </do_if>

        <do_if value="not $pilot? or $pilot == null">
          <set_value name="$pilot" exact="@$ship.pilot"/>
        </do_if>

        <!-- Precompute token values -->
        <set_value name="$vMODEL" exact="@$ship.macro.name"/>
        <run_actions ref="md.GT_Ship_Management.Extract_Base_Ship_Name" result="$vMODELBASE">
          <param name="macroName" value="@$ship.macro.name"/>
        </run_actions>
        <set_value name="$vTYPENAME" exact="@$ship.typename"/>
        <do_if value="not $vTYPENAME? or $vTYPENAME == ''">
          <set_value name="$vTYPENAME" exact="$vMODEL"/>
        </do_if>
        <set_value name="$vBASE" exact="''"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$OriginalShipName?">
          <set_value name="$vBASE" exact="global.$GT_Ships.{$ship}.$OriginalShipName"/>
        </do_if>
        <do_elseif value="global.$GT_Pilots? and $pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName?">
          <set_value name="$vBASE" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
        </do_elseif>
        <set_value name="$vID" exact="$ship.idcode"/>
        <run_actions ref="md.GT_Ship_Management.Detect_Ship_Class" result="$classInfo">
          <param name="ship" value="$ship"/>
        </run_actions>
        <set_value name="$vCLASS" exact="'M'"/>
        <set_value name="$vCLASSNAME" exact="'medium'"/>
        <do_if value="$classInfo?">
          <set_value name="$vCLASS" exact="$classInfo.$Size"/>
          <set_value name="$vCLASSNAME" exact="$classInfo.$Class"/>
        </do_if>

        <set_value name="$vXP" exact="$currentXP"/>
        <set_value name="$vLVL" exact="$currentLevel"/>
        <set_value name="$vLVL_LABEL" exact="'Lv.' + $currentLevel"/>
        <set_value name="$rankIndex" exact="($currentLevel / 3)i + 1"/>
        <do_if value="$rankIndex gt 6">
          <set_value name="$rankIndex" exact="6"/>
        </do_if>
        <set_value name="$vRANK" exact="$rankTitle"/>
        <do_if value="not $vRANK? or $vRANK == ''">
          <do_if value="$rankIndex == 1">
            <set_value name="$vRANK" exact="readtext.{77000}.{6001}"/>
          </do_if>
          <do_elseif value="$rankIndex == 2">
            <set_value name="$vRANK" exact="readtext.{77000}.{6002}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 3">
            <set_value name="$vRANK" exact="readtext.{77000}.{6003}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 4">
            <set_value name="$vRANK" exact="readtext.{77000}.{6004}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 5">
            <set_value name="$vRANK" exact="readtext.{77000}.{6005}"/>
          </do_elseif>
          <do_elseif value="$rankIndex == 6">
            <set_value name="$vRANK" exact="readtext.{77000}.{6006}"/>
          </do_elseif>
        </do_if>
        <set_value name="$vRANKNUM" exact="$rankIndex"/>
        <set_value name="$vSTARS" exact="[[($currentLevel / 3)i, 1].max, 5].min"/>

        <set_value name="$vMGMT" exact="''"/>
        <set_value name="$vPILOTSKILL" exact="''"/>
        <do_if value="$pilot? and $pilot.exists">
          <set_value name="$vMGMT" exact="$pilot.skill.management"/>
          <set_value name="$vPILOTSKILL" exact="$pilot.skill.piloting"/>
        </do_if>

        <run_actions ref="md.GT_Libraries_General.GT_GetHomeSector" result="$homeSectorObj">
          <param name="ship" value="$ship"/>
        </run_actions>
        <set_value name="$vHOME" exact="''"/>
        <do_if value="$homeSectorObj? and $homeSectorObj.exists">
          <run_actions ref="md.GT_Libraries_General.GT_GetSectorNameSafe" result="$vHOME">
            <param name="sector" value="$homeSectorObj"/>
          </run_actions>
        </do_if>

        <set_value name="$homeStationObj" exact="null"/>
        <do_if value="$ship.defaultorder? and $ship.defaultorder.$homeStation? and @$ship.defaultorder.$homeStation.exists">
          <set_value name="$homeStationObj" exact="$ship.defaultorder.$homeStation"/>
        </do_if>
        <do_elseif value="$ship.defaultorder? and $ship.defaultorder.$home? and @$ship.defaultorder.$home.exists and $ship.defaultorder.$home.isclass.station">
          <set_value name="$homeStationObj" exact="$ship.defaultorder.$home"/>
        </do_elseif>
        <set_value name="$vHOMESTATION" exact="''"/>
        <set_value name="$vHOMESTATIONID" exact="''"/>
        <do_if value="$homeStationObj? and $homeStationObj.exists">
          <set_value name="$vHOMESTATION" exact="$homeStationObj.knownname"/>
          <set_value name="$vHOMESTATIONID" exact="$homeStationObj.idcode"/>
        </do_if>

        <set_value name="$vPILOT" exact="''"/>
        <set_value name="$vPILOTID" exact="''"/>
        <do_if value="$pilot? and $pilot.exists">
          <set_value name="$vPILOT" exact="$pilot.name"/>
          <do_if value="$pilot.idcode?">
            <set_value name="$vPILOTID" exact="$pilot.idcode"/>
          </do_if>
        </do_if>

        <set_value name="$vFLEET" exact="'-'"/>
        <do_if value="$ship.fleet? and $ship.fleet.commander? and $ship.fleet.commander.fleet? and $ship.fleet.commander.fleet.name?">
          <set_value name="$vFLEET" exact="$ship.fleet.commander.fleet.name"/>
        </do_if>
        <do_elseif value="$ship.fleet? and $ship.fleet.name?">
          <set_value name="$vFLEET" exact="$ship.fleet.name"/>
        </do_elseif>

        <set_value name="$vCOMMANDER" exact="''"/>
        <set_value name="$vCOMMANDERID" exact="''"/>
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <set_value name="$vCOMMANDER" exact="$ship.commander.knownname"/>
          <set_value name="$vCOMMANDERID" exact="$ship.commander.idcode"/>
        </do_if>

        <set_value name="$vORDER" exact="''"/>
        <do_if value="$ship.defaultorder?">
          <set_value name="$vORDER" exact="@$ship.defaultorder.id"/>
        </do_if>

        <set_value name="$vSECTOR" exact="''"/>
        <do_if value="$ship.sector? and $ship.sector.exists">
          <run_actions ref="md.GT_Libraries_General.GT_GetSectorNameSafe" result="$vSECTOR">
            <param name="sector" value="$ship.sector"/>
          </run_actions>
        </do_if>

        <set_value name="$vPROFIT" exact="''"/>
        <set_value name="$vTRADES" exact="''"/>
        <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <do_if value="global.$GT_Pilots.{$pilot}.$TotalProfit?">
            <set_value name="$vPROFIT" exact="(global.$GT_Pilots.{$pilot}.$TotalProfit / 100)i"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{$pilot}.$TotalTrades?">
            <set_value name="$vTRADES" exact="global.$GT_Pilots.{$pilot}.$TotalTrades"/>
          </do_if>
        </do_if>
        <set_value name="$vSHIPPROFIT" exact="''"/>
        <set_value name="$vSHIPTRADES" exact="''"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <do_if value="global.$GT_Ships.{$ship}.$TotalProfit?">
            <set_value name="$vSHIPPROFIT" exact="(global.$GT_Ships.{$ship}.$TotalProfit / 100)i"/>
          </do_if>
          <do_if value="global.$GT_Ships.{$ship}.$TotalTrades?">
            <set_value name="$vSHIPTRADES" exact="global.$GT_Ships.{$ship}.$TotalTrades"/>
          </do_if>
        </do_if>

        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_OpState" result="$vOPSTATE">
          <param name="ship" value="$ship"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Status" result="$vSTATUS">
          <param name="nameType" value="$nameType"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Collect_Ship_OpState_Flags" result="$opFlags">
          <param name="ship" value="$ship"/>
        </run_actions>

        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vCB">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'CustomBlacklist'"/>
          <param name="active" value="$opFlags.$ShowCustomBlacklist"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vRS">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Resupply'"/>
          <param name="active" value="$opFlags.$HasResupply and not ($opFlags.$HasRepair and $opFlags.$HasResupply)"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vRP">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Repair'"/>
          <param name="active" value="$opFlags.$HasRepair and not ($opFlags.$HasRepair and $opFlags.$HasResupply)"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vMT">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Maintenance'"/>
          <param name="active" value="$opFlags.$HasRepair and $opFlags.$HasResupply"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vES">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Escape'"/>
          <param name="active" value="$opFlags.$Escape"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vRR">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Reroute'"/>
          <param name="active" value="$opFlags.$Reroute"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vCL">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Clearance'"/>
          <param name="active" value="$opFlags.$Clearance"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vUR">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Unreachable'"/>
          <param name="active" value="$opFlags.$Unreachable"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vPE">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'PilotExchange'"/>
          <param name="active" value="$opFlags.$PilotExchange"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vBL">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Blocked'"/>
          <param name="active" value="$nameType == 'blocked'"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vTR">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Training'"/>
          <param name="active" value="$nameType == 'training'"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vFB">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Fallback'"/>
          <param name="active" value="$nameType == 'fallback'"/>
        </run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Build_Pattern_Atomic_State" result="$vIS">
          <param name="flags" value="$opFlags"/>
          <param name="stateType" value="'Isolated'"/>
          <param name="active" value="$nameType == 'isolated'"/>
        </run_actions>
        <set_value name="$vTD" exact="''"/>
        <set_value name="$vIDLE" exact="''"/>

        <!-- Substitute tokens (longer aliases first). Case variants omitted in v1 â€” use uppercase in patterns. -->
        <set_value name="$out" exact="$pattern"/>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{HOMESTATIONID}'"/><param name="value" value="$vHOMESTATIONID"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{HOMESTATION}'"/><param name="value" value="$vHOMESTATION"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{MODELBASE}'"/><param name="value" value="$vMODELBASE"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{LVL_LABEL}'"/><param name="value" value="$vLVL_LABEL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{OPSTATE}'"/><param name="value" value="$vOPSTATE"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{STATUS}'"/><param name="value" value="$vSTATUS"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{MODEL}'"/><param name="value" value="$vMODEL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{MACRO}'"/><param name="value" value="$vMODEL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{TYPENAME}'"/><param name="value" value="$vTYPENAME"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{TYPE}'"/><param name="value" value="$vTYPENAME"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{BASE}'"/><param name="value" value="$vBASE"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{CUSTOM}'"/><param name="value" value="$vBASE"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{BASENAME}'"/><param name="value" value="$vBASE"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{ID}'"/><param name="value" value="$vID"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{IDCODE}'"/><param name="value" value="$vID"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{CLASS}'"/><param name="value" value="$vCLASS"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{SIZE}'"/><param name="value" value="$vCLASS"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{CLASSNAME}'"/><param name="value" value="$vCLASSNAME"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{SIZENAME}'"/><param name="value" value="$vCLASSNAME"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{XP}'"/><param name="value" value="$vXP"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{LVL}'"/><param name="value" value="$vLVL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{LEVEL}'"/><param name="value" value="$vLVL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{RANK}'"/><param name="value" value="$vRANK"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{TITLE}'"/><param name="value" value="$vRANK"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{RANKNUM}'"/><param name="value" value="$vRANKNUM"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{STARS}'"/><param name="value" value="$vSTARS"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{MGMT}'"/><param name="value" value="$vMGMT"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{PILOTSKILL}'"/><param name="value" value="$vPILOTSKILL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{HOME}'"/><param name="value" value="$vHOME"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{HOMESECTOR}'"/><param name="value" value="$vHOME"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{PILOT}'"/><param name="value" value="$vPILOT"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{PILOTID}'"/><param name="value" value="$vPILOTID"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{FLEET}'"/><param name="value" value="$vFLEET"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{COMMANDER}'"/><param name="value" value="$vCOMMANDER"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{COMMANDERID}'"/><param name="value" value="$vCOMMANDERID"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{ORDER}'"/><param name="value" value="$vORDER"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{SECTOR}'"/><param name="value" value="$vSECTOR"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{PROFIT}'"/><param name="value" value="$vPROFIT"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{TRADES}'"/><param name="value" value="$vTRADES"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{SHIPPROFIT}'"/><param name="value" value="$vSHIPPROFIT"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{SHIPTRADES}'"/><param name="value" value="$vSHIPTRADES"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{CB}'"/><param name="value" value="$vCB"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{RS}'"/><param name="value" value="$vRS"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{RP}'"/><param name="value" value="$vRP"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{MT}'"/><param name="value" value="$vMT"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{TR}'"/><param name="value" value="$vTR"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{ES}'"/><param name="value" value="$vES"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{RR}'"/><param name="value" value="$vRR"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{CL}'"/><param name="value" value="$vCL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{UR}'"/><param name="value" value="$vUR"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{PE}'"/><param name="value" value="$vPE"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{BL}'"/><param name="value" value="$vBL"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{FB}'"/><param name="value" value="$vFB"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{IS}'"/><param name="value" value="$vIS"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{TD}'"/><param name="value" value="$vTD"/></run_actions>
        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Pattern_ReplaceToken" result="$out"><param name="text" value="$out"/><param name="token" value="'{IDLE}'"/><param name="value" value="$vIDLE"/></run_actions>

        <run_actions ref="md.GT_Ship_Naming_Pattern.GT_Collapse_Pattern_Whitespace" result="$out">
          <param name="text" value="$out"/>
        </run_actions>
        <return value="$out"/>
      </actions>
    </library>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Ship_Performance_System" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  
  <cues>
    
    <!-- ==================== SIMPLE SHIP PERFORMANCE TRACKING ==================== -->
    <!-- Basic performance tracking without external modifications -->
    
    <cue name="Initialize_Performance_System" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.Setup.Start"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Performance] Simple ship performance tracking system initialized'"/>
        </do_if>
        
        <!-- Initialize tracking tables -->
        <set_value name="global.$GT_Ship_Performance" exact="table[]"/>
        <set_value name="global.$GT_Performance_History" exact="[]"/>
      </actions>
    </cue>
    
    <!-- ==================== GT ORDER ASSIGNMENT MONITORING ==================== -->
    
    <cue name="Monitor_GT_Order_Assignment" instantiate="true">
      <conditions>
        <event_object_order_ready object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
        <check_value value="global.$GT_ProtectedOrderIDs? and event.param? and event.param.id? and global.$GT_ProtectedOrderIDs.indexof.{@event.param.id}"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Performance] GT order assigned to ' + $ship.knownname + ' - tracking performance'"/>
        </do_if>
        
        <!-- Track performance without modifications -->
        <signal_cue_instantly cue="Track_Performance" param="$ship"/>
      </actions>
    </cue>
    
    <!-- ==================== GT ORDER REMOVAL MONITORING ==================== -->
    
    <cue name="Monitor_GT_Order_Removal" instantiate="true">
      <conditions>
        <event_object_order_cancelled object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
        <check_value value="global.$GT_Ship_Performance.{event.object}?"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Performance] GT order removed from ' + $ship.knownname + ' - removing tracking'"/>
        </do_if>
        
        <!-- Remove performance tracking -->
        <signal_cue_instantly cue="Remove_Performance_Tracking" param="$ship"/>
      </actions>
    </cue>
    
    <!-- ==================== PILOT CHANGE MONITORING ==================== -->
    
    <cue name="Monitor_Pilot_Changes" instantiate="true">
      <conditions>
        <event_object_commander_set object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
        <check_value value="global.$GT_Ship_Performance.{event.object}?"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Performance] Pilot change detected on GT ship ' + $ship.knownname + ' - updating tracking'"/>
        </do_if>
        
        <!-- Update performance tracking for new pilot -->
        <signal_cue_instantly cue="Track_Performance" param="$ship"/>
      </actions>
    </cue>
    
    <!-- ==================== TRAINING COMPLETION MONITORING ==================== -->
    
    <cue name="Monitor_Training_Completion" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Training_Complete'"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
        <check_value value="global.$GT_Ship_Performance.{event.object}?"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Performance] Training complete for ' + $ship.knownname + ' - updating tracking'"/>
        </do_if>
        
        <!-- Update performance tracking based on new pilot level -->
        <signal_cue_instantly cue="Track_Performance" param="$ship"/>
      </actions>
    </cue>
    
    <!-- ==================== PERFORMANCE TRACKING ==================== -->
    
    <cue name="Track_Performance" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param"/>
        
        <!-- Validate ship and pilot -->
        <do_if value="not $ship.exists or not $ship.pilot.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Performance] Invalid ship or pilot - skipping performance tracking'"/>
          </do_if>
        </do_if>
        <do_else>
          
          <!-- Get pilot skill level from GT XP system -->
          <set_value name="$pilot" exact="$ship.pilot"/>
          <set_value name="$pilot_level" exact="1"/>
          
          <do_if value="global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$XP?">
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            <!-- Calculate skill level from XP -->
            <do_all exact="15" counter="$level">
              <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$level}">
                <set_value name="$pilot_level" exact="$level"/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Determine ship class string -->
          <set_value name="$ship_class" exact="'unknown'"/>
          <do_if value="$ship.isclass.ship_s">
            <set_value name="$ship_class" exact="'small'"/>
          </do_if>
          <do_elseif value="$ship.isclass.ship_m">
            <set_value name="$ship_class" exact="'medium'"/>
          </do_elseif>
          <do_elseif value="$ship.isclass.ship_l">
            <set_value name="$ship_class" exact="'large'"/>
          </do_elseif>
          <do_elseif value="$ship.isclass.ship_xl">
            <set_value name="$ship_class" exact="'capital'"/>
          </do_elseif>
          
          <!-- Calculate theoretical performance impact -->
          <set_value name="$performance_text" exact="'Baseline'"/>
          <set_value name="$speed_percentage" exact="100"/>
          
          <!-- APPRENTICE LEVEL (1-2): Ship class dependent theoretical penalties -->
          <do_if value="$pilot_level le 2">
            <do_if value="$ship.isclass.ship_s">
              <set_value name="$performance_text" exact="'Optimal'"/>
              <set_value name="$speed_percentage" exact="100"/>
            </do_if>
            <do_elseif value="$ship.isclass.ship_m">
              <set_value name="$performance_text" exact="'Sub-optimal'"/>
              <set_value name="$speed_percentage" exact="90"/>
            </do_elseif>
            <do_elseif value="$ship.isclass.ship_l">
              <set_value name="$performance_text" exact="'Poor'"/>
              <set_value name="$speed_percentage" exact="50"/>
            </do_elseif>
            <do_elseif value="$ship.isclass.ship_xl">
              <set_value name="$performance_text" exact="'Very Poor'"/>
              <set_value name="$speed_percentage" exact="10"/>
            </do_elseif>
          </do_if>
          
          <!-- BASIC LEVEL (3-8): Mixed performance -->
          <do_elseif value="$pilot_level ge 3 and $pilot_level le 8">
            <do_if value="$ship.isclass.ship_s">
              <set_value name="$performance_text" exact="'Enhanced'"/>
              <set_value name="$speed_percentage" exact="110"/>
            </do_if>
            <do_elseif value="$ship.isclass.ship_m">
              <set_value name="$performance_text" exact="'Optimal'"/>
              <set_value name="$speed_percentage" exact="100"/>
            </do_elseif>
            <do_elseif value="$ship.isclass.ship_l">
              <set_value name="$performance_text" exact="'Sub-optimal'"/>
              <set_value name="$speed_percentage" exact="90"/>
            </do_elseif>
            <do_elseif value="$ship.isclass.ship_xl">
              <set_value name="$performance_text" exact="'Poor'"/>
              <set_value name="$speed_percentage" exact="85"/>
            </do_elseif>
          </do_elseif>
          
          <!-- EXPERT LEVEL (9+): Enhanced performance -->
          <do_elseif value="$pilot_level ge 9">
            <do_if value="$ship.isclass.ship_s">
              <set_value name="$performance_text" exact="'Superior'"/>
              <set_value name="$speed_percentage" exact="125"/>
            </do_if>
            <do_elseif value="$ship.isclass.ship_m">
              <set_value name="$performance_text" exact="'Enhanced'"/>
              <set_value name="$speed_percentage" exact="110"/>
            </do_elseif>
            <do_elseif value="$ship.isclass.ship_l">
              <set_value name="$performance_text" exact="'Optimal'"/>
              <set_value name="$speed_percentage" exact="100"/>
            </do_elseif>
            <do_elseif value="$ship.isclass.ship_xl">
              <set_value name="$performance_text" exact="'Enhanced'"/>
              <set_value name="$speed_percentage" exact="110"/>
            </do_elseif>
          </do_elseif>
          
          <!-- Store performance tracking data -->
          <set_value name="global.$GT_Ship_Performance.{$ship}" exact="table[
            $pilot = $pilot,
            $pilot_level = $pilot_level,
            $ship_class = $ship_class,
            $performance_text = $performance_text,
            $speed_percentage = $speed_percentage,
            $applied_time = player.age,
            $last_updated = player.age,
            $active = true
          ]"/>
          
          <!-- Show performance notification -->
          <set_value name="$timestamp" exact="player.age"/>
          <append_to_list name="global.$GT_Performance_History" exact="table[
            $ship = $ship,
            $pilot = $pilot,
            $pilot_level = $pilot_level,
            $ship_class = $ship_class,
            $performance_text = $performance_text,
            $speed_percentage = $speed_percentage,
            $timestamp = player.age,
            $event = 'applied'
          ]"/>
          
          <!-- M3 FIX: Cap performance history to prevent unbounded growth -->
          <do_while value="global.$GT_Performance_History.count gt 200">
            <remove_from_list name="global.$GT_Performance_History" exact="global.$GT_Performance_History.{1}"/>
          </do_while>
          
          <show_notification text="'GT Performance: ' + $ship.knownname + '\nPilot Level ' + $pilot_level + ': ' + $performance_text + '\nâš¡ Theoretical Performance: ' + $speed_percentage + '%\nShip Class: ' + $ship_class" timeout="8s" priority="7"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Performance] Performance tracking applied to ' + $ship.knownname + ' - Level: ' + $pilot_level + ', Class: ' + $ship_class + ', Performance: ' + $performance_text"/>
          </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- ==================== PERFORMANCE TRACKING REMOVAL ==================== -->
    
    <cue name="Remove_Performance_Tracking" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param"/>
        
        <!-- Remove performance tracking -->
        <do_if value="global.$GT_Ship_Performance.{$ship}?">
          <set_value name="global.$GT_Ship_Performance.{$ship}.$removed_time" exact="player.age"/>
          <set_value name="global.$GT_Ship_Performance.{$ship}.$active" exact="false"/>
          
          <!-- Add to history -->
          <append_to_list name="global.$GT_Performance_History" exact="table[
            $ship = $ship,
            $timestamp = player.age,
            $event = 'removed'
          ]"/>
          
          <!-- M3 FIX: Cap performance history to prevent unbounded growth -->
          <do_while value="global.$GT_Performance_History.count gt 200">
            <remove_from_list name="global.$GT_Performance_History" exact="global.$GT_Performance_History.{1}"/>
          </do_while>
          
          <remove_value name="global.$GT_Ship_Performance.{$ship}"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT Performance] Performance tracking removed from ' + $ship.knownname"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- ==================== COMPATIBILITY WRAPPER ==================== -->
    
    <cue name="Apply_GT_Modifications" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Forward the call to the actual performance tracking system -->
        <signal_cue_instantly cue="Track_Performance" param="event.param"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT Performance] Compatibility wrapper: Apply_GT_Modifications Track_Performance'"/>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Ship_State_Manager" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - SHIP STATE MANAGER
         Event-driven state machine for tracking ship states
         ======================================== -->
    
    <!-- Update Ship State -->
    <cue name="UpdateState" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Ship_State_Manager.UpdateState"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        <set_value name="$updateType" exact="$params.$UpdateType"/>
        
        <!-- Initialize registry if needed -->
        <do_if value="not global.$GT_Ship_State?">
          <set_value name="global.$GT_Ship_State" exact="table[]"/>
        </do_if>
        
        <!-- Initialize ship state if needed -->
        <do_if value="not global.$GT_Ship_State.{$ship}?">
          <set_value name="global.$GT_Ship_State.{$ship}" exact="table[
            $OperationalState = 'idle',
            $SubordinateState = 'independent',
            $Commander = null,
            $CommanderHasGT = false,
            $HasGTOrder = false,
            $HasAssistOrder = false,
            $ActiveTradeOrders = 0,
            $LastStateUpdate = player.age,
            $StateHistory = [],
            $MacroShipName = null,
            $OriginalShipName = null,
            $DefaultOrder = null,
            $CurrentOrder = null
          ]"/>
        </do_if>
        
        <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
        <set_value name="$currentState" exact="$state"/>
        
        <!-- Ensure StateHistory is initialized for existing ships from old save games -->
        <!-- StateHistory might be null if ship state was created before StateHistory was added -->
        <do_if value="not $state.$StateHistory? or $state.$StateHistory == null">
          <set_value name="$state.$StateHistory" exact="[]"/>
        </do_if>
        
        <!-- Update state directly (removed library call that doesn't exist yet) -->
        <!-- This tests if the handler processing interferes with trade execution -->
        
        <!-- Update state based on update type -->
        <do_if value="$updateType == 'GT_Order_Assigned'">
          <!-- Reset state completely when GT order is assigned -->
          <set_value name="$state.$HasGTOrder" exact="true"/>
          <set_value name="$state.$OperationalState" exact="'idle'"/>
          <set_value name="$state.$SubordinateState" exact="'independent'"/>
          <set_value name="$state.$ActiveTradeOrders" exact="0"/>
          <set_value name="$state.$HasAssistOrder" exact="false"/>
          
          <!-- Store macro ship name if provided -->
          <do_if value="$params.$MacroShipName?">
            <set_value name="$state.$MacroShipName" exact="$params.$MacroShipName"/>
            <set_value name="$state.$OriginalShipName" exact="$params.$MacroShipName"/>
          </do_if>
          <do_else>
            <!-- Fallback: capture from ship if not provided -->
            <set_value name="$macroName" exact="@$ship.macro.name"/>
            <do_if value="$macroName?">
              <set_value name="$state.$MacroShipName" exact="$macroName"/>
              <set_value name="$state.$OriginalShipName" exact="$macroName"/>
            </do_if>
          </do_else>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] ' + $ship.idcode + ': GT order assigned - state reset to idle'" chance="100"/>
          </do_if>
          <run_actions ref="md.GT_CoreSystem.EnsureShipRegistryEntry">
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="global.$GT_Ships.{$ship}.$LogbookEntries" exact="false"/>
          <do_if value="$ship.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id} and @$ship.defaultorder.$logbookentries">
            <set_value name="global.$GT_Ships.{$ship}.$LogbookEntries" exact="true"/>
          </do_if>
          <do_elseif value="@$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id} and @$ship.commander.defaultorder.$logbookentries">
            <set_value name="global.$GT_Ships.{$ship}.$LogbookEntries" exact="true"/>
          </do_elseif>
        </do_if>
        <do_elseif value="$updateType == 'Trade_Order_Created'">
          <!-- Handle Trade_Order_Created update -->
          <set_value name="$tradeOrderCount" exact="1"/>
          <do_if value="$params.$TradeOrderCount?">
            <set_value name="$tradeOrderCount" exact="$params.$TradeOrderCount"/>
          </do_if>
          <do_elseif value="$ship.tradeorders?">
            <set_value name="$tradeOrderCount" exact="$ship.tradeorders.count"/>
          </do_elseif>
          <set_value name="$state.$ActiveTradeOrders" exact="$tradeOrderCount"/>
          <set_value name="$state.$OperationalState" exact="'trading'"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 3: ' + $ship.idcode + ' - Trade order created, state updated to trading (orders: ' + $tradeOrderCount + ')'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$updateType == 'Trade_Order_Completed'">
          <!-- Handle Trade_Order_Completed update (simplified, no library call) -->
          <set_value name="$remainingOrders" exact="0"/>
          <do_if value="$params.$RemainingOrders?">
            <set_value name="$remainingOrders" exact="$params.$RemainingOrders"/>
          </do_if>
          <do_elseif value="$ship.tradeorders?">
            <set_value name="$remainingOrders" exact="$ship.tradeorders.count"/>
          </do_elseif>
          <set_value name="$remainingOrders" exact="[$remainingOrders, 0].max"/>
          <set_value name="$state.$ActiveTradeOrders" exact="$remainingOrders"/>
          <do_if value="$state.$ActiveTradeOrders == 0">
            <set_value name="$state.$OperationalState" exact="'idle'"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 4: ' + $ship.idcode + ' - Trade order completed, state updated (remaining orders: ' + $remainingOrders + ', operational state: ' + $state.$OperationalState + ')'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$updateType == 'Commander_Removed'">
          <set_value name="$state.$Commander" exact="null"/>
          <set_value name="$state.$CommanderHasGT" exact="false"/>
          <set_value name="$state.$IsSubordinate" exact="false"/>
          
          <!-- Check if ship still has GT order -->
          <set_value name="$hasGTOrder" exact="false"/>
          <do_if value="$params.$HasGTOrder?">
            <set_value name="$hasGTOrder" exact="$params.$HasGTOrder"/>
          </do_if>
          <do_elseif value="$currentState.$HasGTOrder?">
            <set_value name="$hasGTOrder" exact="$currentState.$HasGTOrder"/>
          </do_elseif>
          <set_value name="$state.$HasGTOrder" exact="$hasGTOrder"/>
          
          <!-- Determine subordinate state -->
          <do_if value="$hasGTOrder">
            <set_value name="$state.$SubordinateState" exact="'independent'"/>
          </do_if>
          <do_else>
            <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
          </do_else>
        </do_elseif>
        <do_elseif value="$updateType == 'Commander_Changed'">
          <set_value name="$newCommander" exact="$params.$Commander"/>
          <set_value name="$commanderHasGT" exact="false"/>
          <do_if value="$params.$CommanderHasGT?">
            <set_value name="$commanderHasGT" exact="$params.$CommanderHasGT"/>
          </do_if>
          
          <set_value name="$state.$Commander" exact="$newCommander"/>
          <set_value name="$state.$CommanderHasGT" exact="$commanderHasGT"/>
          
          <!-- Recalculate subordinate state -->
          <set_value name="$state.$SubordinateState" exact="'independent'"/>
          <set_value name="$state.$IsSubordinate" exact="false"/>
          <do_if value="@$newCommander.exists">
            <set_value name="$state.$IsSubordinate" exact="true"/>
            <do_if value="$commanderHasGT">
              <set_value name="$state.$SubordinateState" exact="'subordinate'"/>
            </do_if>
            <do_else>
              <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            </do_else>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 6: ' + $ship.idcode + ' - Commander changed (commander: ' + (if @$newCommander.exists then @$newCommander.idcode else 'NONE') + ', has GT: ' + $commanderHasGT + ', subordinate state: ' + $state.$SubordinateState + ')'" chance="100"/>
          </do_if>
          
        </do_elseif>
        <do_elseif value="$updateType == 'Subordinate_Count_Changed'">
          <!-- Handle subordinate count changes (ship becomes commander or stops being one) -->
          <set_value name="$oldSubordinateCount" exact="0"/>
          <set_value name="$newSubordinateCount" exact="0"/>
          <set_value name="$wasCommander" exact="false"/>
          <set_value name="$isCommander" exact="false"/>
          
          <do_if value="$params.$OldSubordinateCount?">
            <set_value name="$oldSubordinateCount" exact="$params.$OldSubordinateCount"/>
          </do_if>
          <do_if value="$params.$NewSubordinateCount?">
            <set_value name="$newSubordinateCount" exact="$params.$NewSubordinateCount"/>
          </do_if>
          <do_if value="$params.$WasCommander?">
            <set_value name="$wasCommander" exact="$params.$WasCommander"/>
          </do_if>
          <do_if value="$params.$IsCommander?">
            <set_value name="$isCommander" exact="$params.$IsCommander"/>
          </do_if>
          
          <!-- Update state to reflect commander status -->
          <!-- Note: This doesn't change subordinate state (independent/subordinate/orphaned) -->
          <!-- It just tracks that this ship now has subordinates (is a commander) -->
          <!-- The subordinate state is about THIS ship's relationship to ITS commander -->
          <!-- This update is about THIS ship's relationship to ITS subordinates -->
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 6: ' + $ship.idcode + ' - Subordinate count changed (old: ' + $oldSubordinateCount + ', new: ' + $newSubordinateCount + ', was commander: ' + $wasCommander + ', is commander: ' + $isCommander + ')'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$updateType == 'GT_Order_Cancelled'">
          <!-- Handle GT order cancellation -->
          <set_value name="$state.$HasGTOrder" exact="false"/>
          <set_value name="$state.$OperationalState" exact="'orphaned'"/>
          <set_value name="$state.$ActiveTradeOrders" exact="0"/>
          
          <!-- Determine subordinate state -->
          <set_value name="$hasCommander" exact="false"/>
          <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
            <set_value name="$hasCommander" exact="true"/>
            <set_value name="$state.$Commander" exact="$ship.commander"/>
            
            <!-- Check if commander has GT order -->
            <set_value name="$commanderHasGT" exact="false"/>
            <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
              <set_value name="$commanderHasGT" exact="true"/>
            </do_if>
            <set_value name="$state.$CommanderHasGT" exact="$commanderHasGT"/>
            
            <do_if value="$commanderHasGT">
              <set_value name="$state.$SubordinateState" exact="'subordinate'"/>
            </do_if>
            <do_else>
              <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            </do_else>
          </do_if>
          <do_else>
            <set_value name="$state.$Commander" exact="null"/>
            <set_value name="$state.$CommanderHasGT" exact="false"/>
            <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
          </do_else>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - GT order cancelled, state updated (has commander: ' + $hasCommander + ', subordinate state: ' + $state.$SubordinateState + ')'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_elseif value="$updateType == 'Order_Ready'">
          <!-- Update from current state (state/currentState are same reference, these preserve current values) -->
          <set_value name="$state.$DefaultOrder" exact="$currentState.$DefaultOrder"/>
          <set_value name="$state.$CurrentOrder" exact="$currentState.$CurrentOrder"/>
          <set_value name="$state.$HasGTOrder" exact="$currentState.$HasGTOrder"/>
          <set_value name="$state.$IsSubordinate" exact="$currentState.$IsSubordinate"/>
          <set_value name="$state.$CommanderHasGT" exact="$currentState.$CommanderHasGT"/>
          <!-- OperationalState preserved (not changed for Order_Ready) -->
        </do_elseif>
        <do_elseif value="$updateType == 'Order_Cancelled'">
          <!-- Update from current state -->
          <set_value name="$state.$DefaultOrder" exact="$currentState.$DefaultOrder"/>
          <set_value name="$state.$CurrentOrder" exact="$currentState.$CurrentOrder"/>
          <set_value name="$state.$HasGTOrder" exact="$currentState.$HasGTOrder"/>
          <set_value name="$state.$IsSubordinate" exact="$currentState.$IsSubordinate"/>
          <set_value name="$state.$CommanderHasGT" exact="$currentState.$CommanderHasGT"/>
          
          <!-- Check if GT order was cancelled -->
          <set_value name="$cancelledOrderId" exact="null"/>
          <do_if value="$params.$CancelledOrder?">
            <set_value name="$cancelledOrderId" exact="$params.$CancelledOrder"/>
          </do_if>
          <do_if value="global.$GT_ProtectedOrderIDs? and $cancelledOrderId? and global.$GT_ProtectedOrderIDs.indexof.{$cancelledOrderId}">
            <set_value name="$state.$HasGTOrder" exact="false"/>
            <set_value name="$state.$OperationalState" exact="'orphaned'"/>
          </do_if>
          <do_else>
            <!-- OperationalState preserved (non-GT order cancelled) -->
          </do_else>
        </do_elseif>
        <do_elseif value="$updateType == 'Order_Finished'">
          <!-- Update from current state (state/currentState are same reference, these preserve current values) -->
          <set_value name="$state.$DefaultOrder" exact="$currentState.$DefaultOrder"/>
          <set_value name="$state.$CurrentOrder" exact="$currentState.$CurrentOrder"/>
          <set_value name="$state.$HasGTOrder" exact="$currentState.$HasGTOrder"/>
          <set_value name="$state.$IsSubordinate" exact="$currentState.$IsSubordinate"/>
          <set_value name="$state.$CommanderHasGT" exact="$currentState.$CommanderHasGT"/>
          <!-- OperationalState preserved (not changed for Order_Finished) -->
        </do_elseif>
        <do_elseif value="$updateType == 'Commander_Set'">
          <!-- Update from current state (state/currentState are same reference, these preserve current values) -->
          <set_value name="$state.$DefaultOrder" exact="$currentState.$DefaultOrder"/>
          <set_value name="$state.$CurrentOrder" exact="$currentState.$CurrentOrder"/>
          <set_value name="$state.$HasGTOrder" exact="$currentState.$HasGTOrder"/>
          <set_value name="$state.$IsSubordinate" exact="$currentState.$IsSubordinate"/>
          <set_value name="$state.$CommanderHasGT" exact="$currentState.$CommanderHasGT"/>
          <!-- OperationalState preserved (not changed for Commander_Set) -->
          
          <!-- Update commander reference -->
          <set_value name="$newCommander" exact="$params.$NewCommander"/>
          <set_value name="$state.$Commander" exact="$newCommander"/>
          
          <!-- Recalculate subordinate state -->
          <set_value name="$state.$SubordinateState" exact="'independent'"/>
          <set_value name="$state.$IsSubordinate" exact="false"/>
          <do_if value="@$newCommander.exists">
            <set_value name="$state.$IsSubordinate" exact="true"/>
            <set_value name="$commanderHasGT" exact="false"/>
            <do_if value="$newCommander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$newCommander.defaultorder.id})">
              <set_value name="$commanderHasGT" exact="true"/>
            </do_if>
            <set_value name="$state.$CommanderHasGT" exact="$commanderHasGT"/>
            <do_if value="$commanderHasGT">
              <set_value name="$state.$SubordinateState" exact="'subordinate'"/>
            </do_if>
            <do_else>
              <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            </do_else>
          </do_if>
        </do_elseif>
        <do_elseif value="$updateType == 'Transition_To_Independent'">
          <set_value name="$state.$SubordinateState" exact="'independent'"/>
          <set_value name="$state.$IsSubordinate" exact="false"/>
          <set_value name="$state.$Commander" exact="null"/>
          <set_value name="$state.$CommanderHasGT" exact="false"/>
        </do_elseif>
        <do_elseif value="$updateType == 'Orphaned'">
          <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
          <set_value name="$state.$OperationalState" exact="'orphaned'"/>
        </do_elseif>
        <do_elseif value="$updateType == 'Promoted_To_Commander'">
          <!-- Ship was promoted from subordinate to commander -->
          <!-- Clear commander reference (ship is now independent commander) -->
          <set_value name="$state.$Commander" exact="null"/>
          <set_value name="$state.$CommanderHasGT" exact="false"/>
          <set_value name="$state.$SubordinateState" exact="'independent'"/>
          <set_value name="$state.$IsSubordinate" exact="false"/>
          
          <!-- CRITICAL: Always extract clean OriginalShipName from current name during promotion -->
          <!-- The stored OriginalShipName might be corrupted (concatenated with destroyed commander's name) -->
          <!-- Always strip GT formatting from current name to get the true base name -->
          <set_value name="$currentName" exact="@$ship.knownname"/>
          <do_if value="$currentName? and $currentName != ''">
            <!-- Strip GT formatting to get clean original name -->
            <!-- This removes any concatenated rank/XP info from the destroyed commander -->
            <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$cleanedName">
              <param name="shipName" value="$currentName"/>
            </run_actions>
            <set_value name="$state.$OriginalShipName" exact="$cleanedName"/>
            <!-- Also update GT_Ships registry if it exists -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
              <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$cleanedName"/>
            </do_if>
            <!-- Also update GT_Pilots registry if pilot exists -->
            <set_value name="$pilot" exact="@$ship.pilot"/>
            <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
              <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$cleanedName"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] (' + $ship.idcode + ') Promoted_To_Commander: Extracted and stored OriginalShipName: ' + $cleanedName + ' (from: ' + $currentName + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Fallback to macro name if current name unavailable -->
            <set_value name="$macroName" exact="@$ship.macro.name"/>
            <do_if value="$macroName?">
              <set_value name="$state.$OriginalShipName" exact="$macroName"/>
              <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
                <set_value name="global.$GT_Ships.{$ship}.$OriginalShipName" exact="$macroName"/>
              </do_if>
              <set_value name="$pilot" exact="@$ship.pilot"/>
              <do_if value="$pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
                <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$macroName"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] (' + $ship.idcode + ') Promoted_To_Commander: Using macro name as OriginalShipName: ' + $macroName" chance="100"/>
              </do_if>
            </do_if>
          </do_else>
          
          <!-- Trigger ship name update to rebuild name with correct OriginalShipName -->
          <set_value name="$pilot" exact="@$ship.pilot"/>
          <do_if value="$pilot? and $pilot.exists">
            <set_value name="$pilotXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
            <do_if value="not $pilotXP?">
              <set_value name="$pilotXP" exact="0"/>
            </do_if>
            <set_value name="$skillLevel" exact="1"/>
            <do_all exact="15" counter="$lvl">
              <do_if value="$pilotXP ge global.$GT_Config.$XP.$SkillThresholds.{$lvl}">
                <set_value name="$skillLevel" exact="$lvl"/>
              </do_if>
            </do_all>
            <set_value name="$rankTitle" exact="'Lehrling'"/>
            <do_if value="global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$TraderTitles?">
              <set_value name="$rankIndex" exact="($skillLevel / 3)i + 1"/>
              <do_if value="$rankIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
                <set_value name="$rankIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
              </do_if>
              <do_if value="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}?">
                <set_value name="$rankTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$rankIndex}"/>
              </do_if>
            </do_if>
            
            <!-- Trigger ship name update -->
            <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
              $Ship = $ship,
              $pilot = $pilot,
              $xp = $pilotXP,
              $level = $skillLevel,
              $rank = $rankTitle,
              $nameType = 'trader'
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] (' + $ship.idcode + ') Promoted_To_Commander: Triggered ship name update'" chance="100"/>
            </do_if>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 6: ' + $ship.idcode + ' - Promoted to commander, state updated (no longer subordinate)'" chance="100"/>
          </do_if>
        </do_elseif>
        <do_else>
          <!-- Generic update: sync with current state -->
          <set_value name="$state.$DefaultOrder" exact="$currentState.$DefaultOrder"/>
          <set_value name="$state.$CurrentOrder" exact="$currentState.$CurrentOrder"/>
          <set_value name="$state.$HasTradeOrders" exact="$currentState.$HasTradeOrders"/>
          <set_value name="$state.$IsSubordinate" exact="$currentState.$IsSubordinate"/>
          <set_value name="$state.$CommanderHasGT" exact="$currentState.$CommanderHasGT"/>
          <set_value name="$state.$OperationalState" exact="$currentState.$State"/>
          
          <!-- Update commander reference -->
          <do_if value="$currentState.$IsSubordinate">
            <set_value name="$state.$Commander" exact="$ship.commander"/>
          </do_if>
          <do_else>
            <set_value name="$state.$Commander" exact="null"/>
          </do_else>
        </do_else>
        
        <!-- Update timestamp -->
        <set_value name="$state.$LastStateUpdate" exact="player.age"/>
        
        <!-- Add to history (for debugging) -->
        <!-- FIX: Ensure StateHistory is initialized (defensive check - should already be initialized by early check or migration) -->
        <!-- This is a final safety net right before append_to_list -->
        <do_if value="not $state.$StateHistory? or $state.$StateHistory == null">
          <set_value name="$state.$StateHistory" exact="[]"/>
        </do_if>
        
        <!-- Ensure DefaultOrder and CurrentOrder exist before accessing -->
        <do_if value="not $state.$DefaultOrder?">
          <set_value name="$state.$DefaultOrder" exact="@$currentState.$DefaultOrder"/>
        </do_if>
        <do_if value="not $state.$CurrentOrder?">
          <set_value name="$state.$CurrentOrder" exact="@$currentState.$CurrentOrder"/>
        </do_if>
        
        <append_to_list name="$state.$StateHistory" exact="table[
          $Time = player.age,
          $UpdateType = $updateType,
          $OperationalState = $state.$OperationalState,
          $SubordinateState = $state.$SubordinateState,
          $DefaultOrder = $state.$DefaultOrder,
          $CurrentOrder = $state.$CurrentOrder
        ]"/>
        
        <!-- Limit history size (keep last 50 entries) -->
        <!-- Use safe operator to avoid crash if StateHistory is null -->
        <set_value name="$historyCount" exact="@$state.$StateHistory.count"/>
        <do_if value="$historyCount? and $historyCount gt 50 and $state.$StateHistory?">
          <!-- Extract list with safe access -->
          <set_value name="$historyList" exact="@$state.$StateHistory"/>
          <set_value name="$listCount" exact="@$historyList.count"/>
          <do_if value="$historyList? and $listCount? and $listCount gt 50">
            <!-- Build new list with last 50 entries (safer than slicing) -->
            <!-- X4 lists are 1-indexed, so indices are 1..count -->
            <set_value name="$newHistory" exact="[]"/>
            <set_value name="$startIdx" exact="$listCount - 50 + 1"/>
            <do_all exact="50" counter="$i">
              <set_value name="$sourceIdx" exact="$startIdx + $i - 1"/>
              <do_if value="$sourceIdx ge 1 and $sourceIdx le $listCount">
                <append_to_list name="$newHistory" exact="$historyList.{$sourceIdx}"/>
              </do_if>
            </do_all>
            <!-- Replace StateHistory with trimmed list -->
            <set_value name="$state.$StateHistory" exact="$newHistory"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Signal Handler for AI Script Updates -->
    <!-- AI scripts use signal_objects, so we need to listen for that signal -->
    <cue name="HandleAIStateUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_State_Update'"/>
      </conditions>
      <actions>
        <!-- PERFORMANCE FIX: Early exit check for non-GT ships -->
        <!-- Extract ship from params and check GT order status before forwarding -->
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        
        <!-- Unified GT-control check to keep AI/MD/Lua semantics aligned -->
        <set_value name="$isGTControlled" exact="false"/>
        <do_if value="$ship? and $ship.exists and md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus?">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
            <param name="ship" value="$ship"/>
            <param name="checkRegistry" value="false"/>
            <param name="checkState" value="false"/>
          </run_actions>
          <set_value name="$isGTControlled" exact="$gtStatus.$IsGTControlled"/>
        </do_if>
        <do_elseif value="$ship? and $ship.exists">
          <!-- Fallback for early-load/library-order edge cases -->
          <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
            <set_value name="$isGTControlled" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- EARLY EXIT: If ship is not GT-controlled, exit immediately without forwarding -->
        <do_if value="not $isGTControlled">
          <!-- Ship is not GT-controlled - no state update needed, exit silently -->
          <!-- This prevents stutter from constant property lookups for non-GT ships -->
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
          <!-- Ship IS GT-controlled - forward to UpdateState cue -->
          <signal_cue_instantly cue="md.GT_Ship_State_Manager.UpdateState" param="event.param2"/>
        </do_else>
      </actions>
    </cue>
    <!-- Periodic GT Order Verification -->
    <!-- Check if ships registered in state manager still have GT orders -->
    <!-- This catches cases where GT order is manually removed and AI script terminates immediately -->
    <!-- Periodic verification as safety net for edge cases -->
    <!-- COMMENTED OUT: Event-driven detection handles all cases, no need for constant polling -->
    <!-- Note: VerifyGTOrders cue was removed due to XML comment nesting issues -->
    
    <!-- Detect when GT order is cancelled (catches "remove all commands and orders" on direct GT orders) -->
    <!-- CRITICAL: Only processes GT order cancellations (scoped like vanilla story_yaki.xml pattern) -->
    <!-- Fallback: Only used when AI script doesn't emit signal (e.g., script wasn't running) -->
    <cue name="DetectOrderCancellation" instantiate="true">
      <conditions>
        <event_object_order_cancelled object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
        <!-- Only process GT order cancellations (MK3 + MK1) -->
        <check_value value="event.param? and event.param.id? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@event.param.id}"/>
      </conditions>
      <!-- Small delay to let order cancellation complete -->
      <delay exact="100ms"/>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-State] Phase 7: DetectOrderCancellation triggered - GT order cancelled for ship: ' + $ship.idcode" chance="100"/>
        </do_if>
        
        <!-- FAST PATH: Process event.object directly (not scanning all ships) -->
        <!-- Check if ship was GT-controlled -->
        <set_value name="$wasGTControlled" exact="false"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <set_value name="$wasGTControlled" exact="true"/>
        </do_if>
        <do_elseif value="global.$GT_Ship_State? and global.$GT_Ship_State.{$ship}?">
          <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
          <do_if value="$state.$HasGTOrder? and $state.$HasGTOrder">
            <set_value name="$wasGTControlled" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Only process if ship was GT-controlled -->
        <do_if value="$wasGTControlled">
          <!-- Check if ship still has GT order (direct or via commander) -->
          <set_value name="$hasGTOrderNow" exact="false"/>
          
          <!-- Check 1: Direct GT order -->
          <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
            <set_value name="$hasGTOrderNow" exact="true"/>
          </do_if>
          
          <!-- Check 2: Subordinate to GT commander -->
          <do_if value="not $hasGTOrderNow">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckCommanderStatus" result="$commanderStatus">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="$commanderStatus.$HasCommander and $commanderStatus.$CommanderHasGT">
              <set_value name="$hasGTOrderNow" exact="true"/>
            </do_if>
          </do_if>
          
          <!-- If ship no longer has GT order, trigger cleanup (only if AI script didn't already handle it) -->
          <do_if value="not $hasGTOrderNow">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - GT order cancelled and GT order lost - triggering cleanup (FALLBACK: AI script may not have handled it)'" chance="100"/>
            </do_if>
            
            <!-- Initialize state if missing -->
            <do_if value="not global.$GT_Ship_State?">
              <set_value name="global.$GT_Ship_State" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ship_State.{$ship}?">
              <set_value name="global.$GT_Ship_State.{$ship}" exact="table[
                $OperationalState = 'orphaned',
                $SubordinateState = 'orphaned',
                $Commander = null,
                $CommanderHasGT = false,
                $HasGTOrder = false,
                $HasAssistOrder = false,
                $ActiveTradeOrders = 0,
                $LastStateUpdate = player.age
              ]"/>
            </do_if>
            
            <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
            
            <!-- Update state -->
            <set_value name="$state.$HasGTOrder" exact="false"/>
            <set_value name="$state.$OperationalState" exact="'orphaned'"/>
            <set_value name="$state.$ActiveTradeOrders" exact="0"/>
            <set_value name="$state.$Commander" exact="null"/>
            <set_value name="$state.$CommanderHasGT" exact="false"/>
            <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            <set_value name="$state.$LastStateUpdate" exact="player.age"/>
            
            <!-- Send cleanup signals -->
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = $ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
            
            <!-- EVENT-DRIVEN: Directly trigger orphaned ship check (ensures cleanup even if HandleShipStateUpdate doesn't fire) -->
            <!-- This is critical for commanders without subordinates -->
            <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] Phase 7: Triggering GT_Check_Ship_Orphaned for ' + $ship.idcode + ' (MD fallback handler - direct trigger)'" chance="100"/>
              </do_if>
              <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[$Ship = $ship]"/>
            </do_if>
            
            <set_value name="$pilot" exact="@$ship.pilot"/>
            <set_value name="$originalName" exact="null"/>
            <do_if value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
            </do_if>
            <do_elseif value="$state.$OriginalShipName?">
              <set_value name="$originalName" exact="$state.$OriginalShipName"/>
            </do_elseif>
            <do_else>
              <set_value name="$originalName" exact="@$ship.macro.name"/>
            </do_else>
            
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = $ship,
              $Pilot = $pilot,
              $Reason = 'GT order removed (MD fallback) - restoring original name',
              $OriginalName = $originalName
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: Cleanup signals sent for ' + $ship.idcode + ' (MD fallback handler)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Detect when subordinate is removed from commander (catches "remove all commands and orders" on subordinates) -->
    <!-- This is the PRIMARY event for detecting subordinate removal -->
    <!-- event.object = old commander, event.param = subordinate that was removed -->
    <cue name="DetectSubordinateRemoval" instantiate="true">
      <conditions>
        <event_object_subordinate_removed object="player.galaxy"/>
        <check_value value="event.param.isclass.ship"/>
        <check_value value="event.param.owner == faction.player"/>
      </conditions>
      <delay exact="100ms"/>
      <actions>
        <set_value name="$subordinate" exact="event.param"/>
        <set_value name="$commander" exact="event.object"/>
        
        <!-- Log event firing -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-State] DetectSubordinateRemoval EVENT FIRED - Subordinate: ' + $subordinate.idcode + ', Commander: ' + (if $commander.exists then $commander.idcode else 'NONE')" chance="100"/>
        </do_if>
        
        <!-- Check if subordinate was GT-controlled -->
        <set_value name="$wasGTControlled" exact="false"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$subordinate}?">
          <set_value name="$wasGTControlled" exact="true"/>
        </do_if>
        
        <!-- Only check if commander had GT order (subordinate was inheriting GT order) -->
        <!-- Don't check subordinates that don't inherit GT order at all -->
        <set_value name="$commanderHadGT" exact="false"/>
        <set_value name="$commanderOrder" exact="'NONE'"/>
        <do_if value="$commander.exists">
          <set_value name="$commanderOrder" exact="@$commander.defaultorder.id"/>
          <do_if value="$commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$commander.defaultorder.id})">
            <set_value name="$commanderHadGT" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- Log check results -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-State] DetectSubordinateRemoval CHECK: ' + $subordinate.idcode + ' - wasGTControlled: ' + $wasGTControlled + ', commanderHadGT: ' + $commanderHadGT + ', commanderOrder: ' + $commanderOrder" chance="100"/>
        </do_if>
        
        <!-- Only trigger delayed verification if subordinate was GT-controlled AND commander had GT order -->
        <do_if value="$wasGTControlled and $commanderHadGT">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Subordinate removed: ' + $subordinate.idcode + ' from GT commander ' + $commander.idcode + ' - starting Assist order check'" chance="100"/>
          </do_if>
          <set_value name="$cleanupTraceId" exact="$subordinate.idcode + '|STATE_SUB_REMOVED|' + (player.age / 1s)i"/>
          <set_value name="$subDefaultOrder" exact="'NONE'"/>
          <do_if value="$subordinate.defaultorder?">
            <set_value name="$subDefaultOrder" exact="@$subordinate.defaultorder.id"/>
          </do_if>
          <!-- Fallback producer intent: protects detach path when AI on_abort signal is missed. -->
          <do_if value="not global.$GT_CleanupIntent?">
            <set_value name="global.$GT_CleanupIntent" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_CleanupIntent.{$subordinate}" exact="table[
            $Active = true,
            $StartTime = player.age,
            $ExpireTime = player.age + 8s,
            $Source = 'STATE_SUB_REMOVED',
            $TraceId = $cleanupTraceId,
            $DefaultOrderAtSignal = $subDefaultOrder,
            $CommanderAtSignal = if $commander.exists then $commander.idcode else 'NONE'
          ]"/>
          
          <!-- Initialize delayed verification registry -->
          <do_if value="not global.$GT_DelayedVerification?">
            <set_value name="global.$GT_DelayedVerification" exact="table[]"/>
          </do_if>
          
          <!-- Signal orphan-check and delayed verification fallback -->
          <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
            $Ship = $subordinate,
            $Source = 'STATE_SUB_REMOVED',
            $TraceId = $cleanupTraceId
          ]"/>
          <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
            $Ship = $subordinate,
            $CheckTime = player.age,
            $Source = 'STATE_SUB_REMOVED',
            $TraceId = $cleanupTraceId
          ]"/>
        </do_if>
        <do_else>
          <!-- Subordinate removed but commander didn't have GT order - no delayed check needed -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Subordinate removed: ' + $subordinate.idcode + ' from commander ' + (if $commander.exists then $commander.idcode else 'NONE') + ' - commander had GT: ' + $commanderHadGT + ' (order: ' + $commanderOrder + ') - skipping delayed check'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- Detect when commander is set/changed (catches "remove all commands and orders" on subordinates) -->
    <!-- FAST PATH: Process event.object directly (the ship whose commander changed) -->
    <!-- FALLBACK: Only used when AI script doesn't emit signal -->
    <cue name="DetectCommanderRemoval" instantiate="true">
      <conditions>
        <event_object_commander_set object="player.galaxy"/>
        <check_value value="event.object.isclass.ship"/>
        <check_value value="event.object.owner == faction.player"/>
      </conditions>
      <!-- Small delay to let commander change complete -->
      <delay exact="100ms"/>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-State] Phase 7: DetectCommanderRemoval triggered - Commander changed for ship: ' + $ship.idcode" chance="100"/>
        </do_if>
        
        <!-- FAST PATH: Process event.object directly (not scanning all ships) -->
        <!-- Check if ship was tracked as subordinate to GT commander -->
        <set_value name="$wasSubordinate" exact="false"/>
        <do_if value="global.$GT_Ship_State? and global.$GT_Ship_State.{$ship}?">
          <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$wasSubordinate" exact="true"/>
          </do_if>
        </do_if>
        <do_elseif value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
          <!-- Ship is in GT_Ships registry - check if it was subordinate -->
          <!-- FIX: When subordinate is removed, event.param is null and $ship.commander is null -->
          <!-- Check if commander was removed (event.param is null) -->
          <set_value name="$newCommander" exact="event.param"/>
          <do_if value="not $newCommander or not $newCommander.exists">
            <!-- Commander was removed (event.param is null) -->
            <!-- Check if ship has Assist order (subordinates have Assist order) -->
            <do_if value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist'">
              <set_value name="$wasSubordinate" exact="true"/>
            </do_if>
            <!-- Fallback: If ship doesn't have direct GT order and commander was removed, it was likely a subordinate -->
            <!-- This catches cases where Assist order was already removed but ship is still in registry -->
            <do_elseif value="not ($ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}))">
              <!-- Ship is in GT_Ships but doesn't have direct GT order and commander was removed -->
              <!-- This indicates it was a subordinate that lost its commander -->
              <set_value name="$wasSubordinate" exact="true"/>
            </do_elseif>
          </do_if>
          <!-- Fallback: Check if ship currently has a commander (for commander change, not removal) -->
          <do_if value="not $wasSubordinate and $ship.commander? and $ship.commander.exists and $ship.commander != $ship">
            <!-- Was subordinate before - check if commander had GT order -->
            <set_value name="$wasSubordinate" exact="true"/>
          </do_if>
        </do_elseif>
        
        <!-- Fallback: pilot record still linked to this ship can outlive GT_Ships/state races
             during "remove assignment" or "remove all orders and assignments". -->
        <do_if value="not $wasSubordinate">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$gtStatus">
            <param name="ship" value="$ship"/>
            <param name="checkRegistry" value="true"/>
            <param name="checkState" value="true"/>
          </run_actions>
          <do_if value="$gtStatus.$PilotRegistryLinked and not $gtStatus.$HasDirectGTOrder">
            <set_value name="$wasSubordinate" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - pilot registry still linked after commander removal - treating as detached GT subordinate'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Only process if ship was tracked as subordinate to GT commander -->
        <do_if value="$wasSubordinate">
          <!-- Check if ship still has GT commander -->
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckCommanderStatus" result="$commanderStatus">
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="$hasCommander" exact="$commanderStatus.$HasCommander"/>
          <set_value name="$commanderHasGT" exact="$commanderStatus.$CommanderHasGT"/>
          <set_value name="$hasGTCommanderNow" exact="$hasCommander and $commanderHasGT"/>
          <set_value name="$isAssistCommanderTransition" exact="false"/>
          <do_if value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and (not event.param? or not event.param.exists)">
            <set_value name="$isAssistCommanderTransition" exact="true"/>
          </do_if>
          
          <!-- If ship no longer has GT commander, trigger cleanup (only if AI script didn't already handle it) -->
          <do_if value="not $hasGTCommanderNow and not $isAssistCommanderTransition">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - Commander removed and GT commander lost - triggering cleanup (FALLBACK: AI script may not have handled it)'" chance="100"/>
            </do_if>
            
            <!-- Initialize state if missing -->
            <do_if value="not global.$GT_Ship_State?">
              <set_value name="global.$GT_Ship_State" exact="table[]"/>
            </do_if>
            <do_if value="not global.$GT_Ship_State.{$ship}?">
              <set_value name="global.$GT_Ship_State.{$ship}" exact="table[
                $OperationalState = 'orphaned',
                $SubordinateState = 'orphaned',
                $Commander = null,
                $CommanderHasGT = false,
                $HasGTOrder = false,
                $HasAssistOrder = false,
                $ActiveTradeOrders = 0,
                $LastStateUpdate = player.age
              ]"/>
            </do_if>
            
            <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
            
            <!-- Update state -->
            <set_value name="$state.$HasGTOrder" exact="false"/>
              <set_value name="$state.$OperationalState" exact="'orphaned'"/>
              <set_value name="$state.$ActiveTradeOrders" exact="0"/>
            <set_value name="$state.$Commander" exact="null"/>
            <set_value name="$state.$CommanderHasGT" exact="false"/>
            <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            <set_value name="$state.$LastStateUpdate" exact="player.age"/>
            
            <!-- Send cleanup signals -->
            <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
              $Ship = $ship,
              $UpdateType = 'GT_Order_Cancelled'
            ]"/>
            
            <set_value name="$pilot" exact="@$ship.pilot"/>
            <set_value name="$originalName" exact="null"/>
            <do_if value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName?">
              <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
            </do_if>
            <do_elseif value="$state.$OriginalShipName?">
              <set_value name="$originalName" exact="$state.$OriginalShipName"/>
            </do_elseif>
            <do_else>
              <set_value name="$originalName" exact="@$ship.macro.name"/>
            </do_else>
            
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = $ship,
              $Pilot = $pilot,
              $Reason = 'Commander removed (MD fallback) - restoring original name',
              $OriginalName = $originalName
            ]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: Cleanup signals sent for ' + $ship.idcode + ' (MD fallback handler)'" chance="100"/>
            </do_if>
          </do_if>
          <do_elseif value="$isAssistCommanderTransition">
            <set_value name="$cleanupTraceId" exact="$ship.idcode + '|STATE_COMMANDER_SET_TRANSITION|' + (player.age / 1s)i"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - Assist/no-commander transition detected in DetectCommanderRemoval, deferring orphan verification'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Check_Ship_Orphaned'" param2="table[
              $Ship = $ship,
              $Source = 'STATE_COMMANDER_SET_TRANSITION',
              $TraceId = $cleanupTraceId
            ]"/>
          </do_elseif>
        </do_if>
      </actions>
    </cue>
    
    <!-- Event-driven delayed check (NO POLLING) -->
    <!-- Handles cases where "remove all commands and orders" is used but default order hasn't changed immediately -->
    <!-- Scheduled by Assist order's on_abort handler when default order is still "Assist" but commander lost GT order -->
    <!-- PERFORMANCE FIX: Checks every 2 seconds for up to 10 checks (20 seconds total) -->
    <cue name="DelayedVerification" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Delayed_Verification'"/>
      </conditions>
      <!-- PERFORMANCE FIX: Check every 2 seconds (reduced from 1s) -->
      <delay exact="2s"/>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        <set_value name="$cleanupSource" exact="'STATE_DELAYED_VERIFY'"/>
        <set_value name="$cleanupTraceId" exact="if $ship? and $ship.exists then $ship.idcode + '|STATE_DELAYED_VERIFY|' + (player.age / 1s)i else 'UNKNOWN|STATE_DELAYED_VERIFY|' + (player.age / 1s)i"/>
        <do_if value="$params? and $params.$Source?">
          <set_value name="$cleanupSource" exact="$params.$Source"/>
        </do_if>
        <do_if value="$params? and $params.$TraceId?">
          <set_value name="$cleanupTraceId" exact="$params.$TraceId"/>
        </do_if>
        
        <!-- Initialize state tracking if first run -->
        <do_if value="not global.$GT_DelayedVerificationState?">
          <set_value name="global.$GT_DelayedVerificationState" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_DelayedVerificationState.{$ship}?">
          <set_value name="global.$GT_DelayedVerificationState.{$ship}" exact="table[
            $CheckCount = 0,
            $StartTime = player.age,
            $CleanupSent = false
          ]"/>
        </do_if>
        
        <set_value name="$state" exact="global.$GT_DelayedVerificationState.{$ship}"/>
        <set_value name="$state.$CheckCount" exact="$state.$CheckCount + 1"/>
        <set_value name="$elapsedTime" exact="player.age - $state.$StartTime"/>
        
        <!-- Check: Is default order still "Assist"? -->
        <set_value name="$defaultOrder" exact="@$ship.defaultorder.id"/>
        
        <!-- Check if ship has direct GT order (not via commander - commander check is unreliable due to stale state) -->
        <set_value name="$hasDirectGT" exact="false"/>
        <do_if value="global.$GT_ProtectedOrderIDs? and $defaultOrder? and global.$GT_ProtectedOrderIDs.indexof.{$defaultOrder}">
          <set_value name="$hasDirectGT" exact="true"/>
        </do_if>
        <do_elseif value="$defaultOrder == 'Assist' and $ship.defaultorder? and $ship.defaultorder.$baseorder? and global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.$baseorder.id}">
          <set_value name="$hasDirectGT" exact="true"/>
        </do_elseif>
        
        <!-- Check commander for logging only (don't use for cancellation - can be stale) -->
        <set_value name="$hasGTCommander" exact="false"/>
        <set_value name="$currentCommander" exact="@$ship.commander"/>
        <do_if value="@$currentCommander.exists and $currentCommander != $ship">
          <do_if value="$currentCommander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$currentCommander.defaultorder.id})">
            <set_value name="$hasGTCommander" exact="true"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-CleanupTrace] trace=' + $cleanupTraceId + ' source=' + $cleanupSource + ' cue=DelayedVerification ship=' + $ship.idcode + ' check=' + $state.$CheckCount + ' elapsed=' + $elapsedTime + ' default=' + (if $defaultOrder then $defaultOrder else 'NONE')" chance="100"/>
          <debug_text text="'[GT-State] CHECK #' + $state.$CheckCount + ' (' + $elapsedTime + 's): ' + $ship.idcode + ' - Default Order: ' + (if $defaultOrder then $defaultOrder else 'NONE') + ', HasDirectGT: ' + $hasDirectGT + ', Commander: ' + (if @$currentCommander.exists then @$currentCommander.idcode else 'NONE') + ' (GT: ' + $hasGTCommander + ')'" chance="100"/>
        </do_if>
        
        <!-- PERFORMANCE FIX: Stop after 10 checks (20 seconds total with 2s interval) -->
        <do_if value="$state.$CheckCount ge 10">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Timeout after 10 checks (20s) - stopping checks for ' + $ship.idcode" chance="100"/>
          </do_if>
          <remove_value name="global.$GT_DelayedVerificationState.{$ship}"/>
        </do_if>
        <do_elseif value="$hasDirectGT">
          <!-- Ship has DIRECT GT order - cancel early (not a subordinate) -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] DelayedVerification cancelled for ' + $ship.idcode + ' - Ship has direct GT order (check #' + $state.$CheckCount + ', ' + $elapsedTime + 's)'" chance="100"/>
          </do_if>
          <remove_value name="global.$GT_DelayedVerificationState.{$ship}"/>
        </do_elseif>
        <do_else>
          <!-- Unified delayed-verification decision (handles Assist lingering with missing commander). -->
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$verifyStatus">
            <param name="ship" value="$ship"/>
            <param name="checkRegistry" value="true"/>
            <param name="checkState" value="true"/>
          </run_actions>
          
          <do_if value="$verifyStatus.$ShouldCleanup">
            <!-- Detached cleanup confirmed - trigger cleanup immediately -->
            <do_if value="not $state.$CleanupSent">
              <set_value name="$state.$CleanupSent" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] DelayedVerification confirmed DETACHED cleanup for ' + $ship.idcode + ' (check #' + $state.$CheckCount + ', ' + $elapsedTime + 's, default=' + (if $defaultOrder then $defaultOrder else 'NONE') + ')' " chance="100"/>
              </do_if>
              
              <!-- Trigger cleanup signals -->
              <signal_objects object="player.galaxy" param="'GT_Ship_State_Update'" param2="table[
                $Ship = $ship,
                $UpdateType = 'GT_Order_Cancelled'
              ]"/>
              
              <!-- Get original name and restore -->
              <set_value name="$pilot" exact="@$ship.pilot"/>
              <set_value name="$originalName" exact="null"/>
              <do_if value="$pilot? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$OriginalShipName?">
                <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
              </do_if>
              <do_else>
                <set_value name="$originalName" exact="@$ship.macro.name"/>
              </do_else>

              <!-- Idempotency guard: suppress duplicate detached-cleanup signals per ship/time bucket -->
              <set_value name="$cleanupSignalType" exact="'DETACHED_CLEANUP_REQUIRED'"/>
              <set_value name="$cleanupTokenBucket" exact="(player.age / 1s)i"/>
              <set_value name="$cleanupToken" exact="$cleanupSignalType + '|' + $cleanupTokenBucket"/>
              <do_if value="not global.$GT_CleanupSignalState?">
                <set_value name="global.$GT_CleanupSignalState" exact="table[]"/>
              </do_if>
              <do_if value="not global.$GT_CleanupSignalState.{$ship}?">
                <set_value name="global.$GT_CleanupSignalState.{$ship}" exact="table[
                  $LastCleanupToken = '',
                  $LastCleanupTime = 0s
                ]"/>
              </do_if>
              <set_value name="$signalState" exact="global.$GT_CleanupSignalState.{$ship}"/>
              <do_if value="not $signalState.$LastCleanupToken? or $signalState.$LastCleanupToken != $cleanupToken">
                <set_value name="$signalState.$LastCleanupToken" exact="$cleanupToken"/>
                <set_value name="$signalState.$LastCleanupTime" exact="player.age"/>
                <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
                  $Ship = $ship,
                  $Pilot = $pilot,
                  $Reason = 'Delayed verification detached cleanup - restoring original name',
                  $OriginalName = $originalName,
                  $Source = 'STATE_DELAYED_VERIFY',
                  $TraceId = $cleanupTraceId
                ]"/>
              </do_if>
              <do_elseif value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] Duplicate cleanup signal suppressed for ' + $ship.idcode + ' token=' + $cleanupToken" chance="100"/>
              </do_elseif>
              
              <!-- Clean up state -->
              <remove_value name="global.$GT_DelayedVerificationState.{$ship}"/>
            </do_if>
          </do_if>
          <do_elseif value="$verifyStatus.$IsGTControlled">
            <set_value name="$intentActive" exact="false"/>
            <set_value name="$intentExpired" exact="false"/>
            <do_if value="global.$GT_CleanupIntent? and global.$GT_CleanupIntent.{$ship}?">
              <set_value name="$intent" exact="global.$GT_CleanupIntent.{$ship}"/>
              <do_if value="$intent.$Active? and $intent.$Active">
                <set_value name="$intentActive" exact="true"/>
              </do_if>
              <do_if value="$intent.$ExpireTime? and player.age ge $intent.$ExpireTime">
                <set_value name="$intentExpired" exact="true"/>
              </do_if>
            </do_if>
            <!-- Do not accept stale commander-based control while detach intent is still active. -->
            <do_if value="$intentActive and not $intentExpired and not $verifyStatus.$HasDirectGTOrder">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] DelayedVerification hold for ' + $ship.idcode + ' - intent active, waiting for stable detach/control state'" chance="100"/>
              </do_if>
              <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
                $Ship = $ship,
                $CheckTime = player.age + 2s,
                $Source = $cleanupSource,
                $TraceId = $cleanupTraceId
              ]"/>
            </do_if>
            <do_else>
              <!-- Ship is GT-controlled again (reassigned or direct order) - stop verification -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] DelayedVerification cancelled for ' + $ship.idcode + ' - GT control restored'" chance="100"/>
              </do_if>
              <remove_value name="global.$GT_DelayedVerificationState.{$ship}"/>
            </do_else>
          </do_elseif>
          <do_else>
            <!-- Stable detached endpoint:
                 no GT control and no GT history markers left while on Wait with no commander. -->
            <set_value name="$commanderPresent" exact="false"/>
            <do_if value="@$currentCommander.exists and $currentCommander != $ship">
              <set_value name="$commanderPresent" exact="true"/>
            </do_if>
            <set_value name="$stableDetachedNoHistory" exact="false"/>
            <do_if value="(not $defaultOrder or $defaultOrder == 'Wait') and not $commanderPresent and not $verifyStatus.$InRegistry and not $verifyStatus.$PilotRegistryLinked and not $verifyStatus.$StateSaysHasGTOrder and not $verifyStatus.$WasSubordinate">
              <set_value name="$stableDetachedNoHistory" exact="true"/>
            </do_if>
            <do_if value="$stableDetachedNoHistory">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] DelayedVerification cancelled for ' + $ship.idcode + ' - stable detached state (default=' + (if $defaultOrder then $defaultOrder else 'NONE') + ', commander=NONE, no GT history)'" chance="100"/>
              </do_if>
              <remove_value name="global.$GT_DelayedVerificationState.{$ship}"/>
            </do_if>
            <do_else>
              <!-- Still transitional - continue checking -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] DelayedVerification requeue for ' + $ship.idcode + ' - transitional status (no cleanup, no stable GT control yet)'" chance="100"/>
              </do_if>
              <!-- PERFORMANCE FIX: Use 2s interval instead of 1s -->
              <signal_objects object="player.galaxy" param="'GT_Delayed_Verification'" param2="table[
                $Ship = $ship,
                $CheckTime = player.age + 2s,
                $Source = $cleanupSource,
                $TraceId = $cleanupTraceId
              ]"/>
            </do_else>
          </do_else>
        </do_else>
      </actions>
    </cue>
    
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Ship_State_Utilities" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================= -->
    <!-- SHIP STATE UTILITIES -->
    <!-- ========================================= -->
    
    <!-- Check Commander Status -->
    <!-- Returns table with HasCommander, CommanderHasGT, Commander -->
    <library name="GT_CheckCommanderStatus" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check commander for"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$HasCommander" exact="false"/>
        <set_value name="$result.$CommanderHasGT" exact="false"/>
        <set_value name="$result.$CommanderPromotionPending" exact="false"/>
        <set_value name="$result.$Commander" exact="null"/>
        
        <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
          <set_value name="$result.$HasCommander" exact="true"/>
          <set_value name="$result.$Commander" exact="$ship.commander"/>

          <set_value name="$directCommanderOrderId" exact="'NONE'"/>
          <do_if value="$ship.commander.defaultorder? and @$ship.commander.defaultorder != null">
            <set_value name="$directCommanderOrderId" exact="@$ship.commander.defaultorder.id"/>
          </do_if>
          <do_if value="$directCommanderOrderId == 'Assist' and $ship.commander.isplayerowned and (not $ship.commander.orders? or $ship.commander.orders.count == 0)">
            <set_value name="$result.$CommanderPromotionPending" exact="true"/>
          </do_if>

          <!-- Traverse Assist commander chain to detect GT control above a promoted interim commander.
               This prevents false detach cleanup while hierarchy settles after commander loss/promotion. -->
          <set_value name="$commanderCursor" exact="$ship.commander"/>
          <set_value name="$chainDepth" exact="0"/>
          <do_while value="not $result.$CommanderHasGT and $commanderCursor? and $commanderCursor.exists and $chainDepth lt 6">
            <set_value name="$chainDepth" exact="$chainDepth + 1"/>
            <set_value name="$cursorOrderId" exact="'NONE'"/>
            <do_if value="$commanderCursor.defaultorder? and @$commanderCursor.defaultorder != null">
              <set_value name="$cursorOrderId" exact="@$commanderCursor.defaultorder.id"/>
            </do_if>
            <do_if value="$cursorOrderId == 'GalaxyTraderMK4Supply' or $cursorOrderId == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$cursorOrderId})">
              <set_value name="$result.$CommanderHasGT" exact="true"/>
            </do_if>
            <do_elseif value="$cursorOrderId == 'Assist' and $commanderCursor.commander? and $commanderCursor.commander.exists and $commanderCursor.commander != $commanderCursor">
              <set_value name="$commanderCursor" exact="$commanderCursor.commander"/>
            </do_elseif>
            <do_else>
              <set_value name="$commanderCursor" exact="null"/>
            </do_else>
          </do_while>
        </do_if>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Is Subordinate of GT Commander -->
    <!-- Quick check if ship is subordinate to a GT commander -->
    <library name="GT_IsSubordinateOfGTCommander" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckCommanderStatus" result="$commanderStatus">
          <param name="ship" value="$ship"/>
        </run_actions>
        <return value="$commanderStatus.$HasCommander and $commanderStatus.$CommanderHasGT"/>
      </actions>
    </library>
    
    <!-- Get Ship State -->
    <!-- Returns ship state with safe property access -->
    <library name="GT_GetShipState" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to get state for"/>
      </params>
      <actions>
        <set_value name="$state" exact="null"/>
        <do_if value="global.$GT_Ship_State? and global.$GT_Ship_State.{$ship}?">
          <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
        </do_if>
        
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$State" exact="$state"/>
        <set_value name="$result.$HasGTOrder" exact="false"/>
        <set_value name="$result.$OperationalState" exact="'unknown'"/>
        <set_value name="$result.$SubordinateState" exact="'unknown'"/>
        <set_value name="$result.$CommanderHasGT" exact="false"/>
        <set_value name="$result.$OriginalShipName" exact="null"/>
        
        <do_if value="$state?">
          <do_if value="$state.$HasGTOrder? and $state.$HasGTOrder">
            <set_value name="$result.$HasGTOrder" exact="true"/>
          </do_if>
          <do_if value="$state.$OperationalState?">
            <set_value name="$result.$OperationalState" exact="$state.$OperationalState"/>
          </do_if>
          <do_if value="$state.$SubordinateState?">
            <set_value name="$result.$SubordinateState" exact="$state.$SubordinateState"/>
          </do_if>
          <do_if value="$state.$CommanderHasGT? and $state.$CommanderHasGT">
            <set_value name="$result.$CommanderHasGT" exact="true"/>
          </do_if>
          <do_if value="$state.$OriginalShipName?">
            <set_value name="$result.$OriginalShipName" exact="$state.$OriginalShipName"/>
          </do_if>
        </do_if>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Unified wrapper for deferred ship-name refresh requests. -->
    <library name="GT_RequestShipNameRefresh" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to refresh name for"/>
        <param name="pilot" default="null" comment="Pilot entity (optional, derived from ship if missing)"/>
        <param name="reason" default="''" comment="Optional reason tag for debug tracing"/>
      </params>
      <actions>
        <do_if value="not $ship? or not $ship.exists">
          <return value="false"/>
        </do_if>
        
        <do_if value="not $pilot? or not $pilot.exists">
          <set_value name="$pilot" exact="if $ship.pilot? and $ship.pilot.exists then $ship.pilot else null"/>
        </do_if>
        <do_if value="not $pilot? or not $pilot.exists">
          <return value="false"/>
        </do_if>
        
        <signal_cue_instantly cue="md.GT_CoreSystem.DeferredShipNameUpdate" param="table[
          $Ship = $ship,
          $pilot = $pilot
        ]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $reason != ''">
          <debug_text text="'[GT-StateUtils] Requested DeferredShipNameUpdate for ' + $ship.idcode + ' reason=' + $reason" chance="100"/>
        </do_if>
        <return value="true"/>
      </actions>
    </library>
    
    <!-- Restore Ship Name -->
    <!-- Handles name restoration logic with subordinate checking -->
    <library name="GT_RestoreShipName" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to restore name for"/>
        <param name="reason" comment="Reason for name restoration"/>
        <param name="checkSubordinate" default="true" comment="Check if subordinate to GT commander"/>
        <param name="state" default="null" comment="Ship state (optional, for state-based name lookup)"/>
        <param name="checkDirectGTOrder" default="true" comment="Check if ship has direct GT order"/>
      </params>
      <actions>
        <!-- Check if ship has direct GT order -->
        <set_value name="$hasDirectGTOrder" exact="false"/>
        <do_if value="$checkDirectGTOrder">
          <do_if value="$ship.defaultorder? and (@$ship.defaultorder.id == 'GalaxyTraderMK4Supply' or @$ship.defaultorder.id == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id}))">
            <set_value name="$hasDirectGTOrder" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- If ship has direct GT order, don't restore name -->
        <do_if value="$hasDirectGTOrder">
          <return value="false"/>
        </do_if>
        
        <!-- Check if ship is subordinate to GT commander -->
        <set_value name="$isSubordinateOfGTCommander" exact="false"/>
        <do_if value="$checkSubordinate">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_IsSubordinateOfGTCommander" result="$isSubordinate">
            <param name="ship" value="$ship"/>
          </run_actions>
          <set_value name="$isSubordinateOfGTCommander" exact="$isSubordinate"/>
        </do_if>
        
        <!-- Restore name if ship is not GT-controlled -->
        <set_value name="$shouldRestore" exact="false"/>
        <do_if value="not $isSubordinateOfGTCommander and $ship.pilot?">
          <set_value name="$shouldRestore" exact="true"/>
        </do_if>
        
        <do_if value="$shouldRestore">
          <set_value name="$originalName" exact="null"/>
          
          <!-- Try to get original name from pilot registry -->
          <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{$ship.pilot}.$OriginalShipName"/>
          </do_if>
          <!-- Fallback to state if available -->
          <do_elseif value="$state? and $state.$OriginalShipName?">
            <set_value name="$originalName" exact="$state.$OriginalShipName"/>
          </do_elseif>
          
          <do_if value="$originalName">
            <signal_objects object="player.galaxy" param="'GT_Ship_Order_Aborted'" param2="table[
              $Ship = $ship,
              $Pilot = $ship.pilot,
              $Reason = $reason,
              $OriginalName = $originalName
            ]"/>
            <return value="true"/>
          </do_if>
        </do_if>
        <return value="false"/>
      </actions>
    </library>
    
    <!-- Check GT Order Status (COMPREHENSIVE) -->
    <!-- Unified function that checks ALL conditions for GT order detection -->
    <!-- Consolidates logic from: order.wait.xml, order.trade.galaxytrader.xml, order.assist.xml, etc. -->
    <!-- Returns comprehensive status table for cleanup detection -->
    <library name="GT_CheckGTOrderStatus" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check GT order status for"/>
        <param name="checkRegistry" default="true" comment="Check if ship is in GT_Ships registry"/>
        <param name="checkState" default="true" comment="Check state registry for historical data"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[]"/>
        
        <!-- Initialize all result fields -->
        <set_value name="$result.$HasDirectGTOrder" exact="false"/>
        <set_value name="$result.$HasGTCommander" exact="false"/>
        <set_value name="$result.$IsGTControlled" exact="false"/>
        <set_value name="$result.$IsSubordinate" exact="false"/>
        <set_value name="$result.$DefaultOrder" exact="null"/>
        <set_value name="$result.$Commander" exact="null"/>
        <set_value name="$result.$CommanderExists" exact="false"/>
        <set_value name="$result.$InRegistry" exact="false"/>
        <set_value name="$result.$WasSubordinate" exact="false"/>
        <set_value name="$result.$StateSaysHasGTOrder" exact="false"/>
        <set_value name="$result.$PilotRegistryLinked" exact="false"/>
        <set_value name="$result.$CommanderPromotionPending" exact="false"/>
        <set_value name="$result.$ShouldCleanup" exact="false"/>
        <set_value name="$result.$ShouldRestoreName" exact="false"/>
        <set_value name="$result.$IsPermanentRemoval" exact="false"/>
        
        <!-- Get current default order -->
        <set_value name="$currentDefaultOrder" exact="@$ship.defaultorder.id"/>
        <set_value name="$result.$DefaultOrder" exact="$currentDefaultOrder"/>
        
        <!-- CHECK 1: Direct GT Order -->
        <do_if value="$currentDefaultOrder? and ($currentDefaultOrder == 'GalaxyTraderMK4Supply' or $currentDefaultOrder == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$currentDefaultOrder}))">
          <set_value name="$result.$HasDirectGTOrder" exact="true"/>
          <set_value name="$result.$IsGTControlled" exact="true"/>
        </do_if>
        
        <!-- CHECK 2: Commander Status (if not direct GT) -->
        <do_if value="not $result.$HasDirectGTOrder">
          <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckCommanderStatus" result="$commanderStatus">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <set_value name="$result.$CommanderExists" exact="$commanderStatus.$HasCommander"/>
          <set_value name="$result.$Commander" exact="$commanderStatus.$Commander"/>
          <set_value name="$result.$HasGTCommander" exact="$commanderStatus.$CommanderHasGT"/>
          <set_value name="$result.$CommanderPromotionPending" exact="$commanderStatus.$CommanderPromotionPending"/>
          
          <!-- CHECK 3: Subordinate with Assist order AND GT commander -->
          <do_if value="$currentDefaultOrder == 'Assist' and ($result.$HasGTCommander or $result.$CommanderPromotionPending)">
            <set_value name="$result.$IsSubordinate" exact="true"/>
            <do_if value="$result.$HasGTCommander">
              <set_value name="$result.$IsGTControlled" exact="true"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- CHECK 4: Registry Status -->
        <do_if value="$checkRegistry">
          <set_value name="$result.$InRegistry" exact="global.$GT_Ships? and global.$GT_Ships.{$ship}?"/>
        </do_if>
        
        <!-- CHECK 5: State Registry (Historical Data) -->
        <set_value name="$state" exact="null"/>
        <do_if value="$checkState and global.$GT_Ship_State? and global.$GT_Ship_State.{$ship}?">
          <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
          
          <!-- State says ship had GT order -->
          <do_if value="$state.$HasGTOrder? and $state.$HasGTOrder">
            <set_value name="$result.$StateSaysHasGTOrder" exact="true"/>
          </do_if>
          
          <!-- State says ship was subordinate -->
          <do_if value="$state.$SubordinateState? and $state.$SubordinateState == 'subordinate'">
            <set_value name="$result.$WasSubordinate" exact="true"/>
          </do_if>
        </do_if>
        
        <!-- CHECK 5b: Pilot registry link (survives detach races better than GT_Ships/state alone) -->
        <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$OriginalShipName?">
          <set_value name="$pilotData" exact="global.$GT_Pilots.{$ship.pilot}"/>
          <do_if value="$pilotData.$Ship? and $pilotData.$Ship == $ship">
            <set_value name="$result.$PilotRegistryLinked" exact="true"/>
          </do_if>
          <do_elseif value="$pilotData.$AssociatedShip? and $pilotData.$AssociatedShip == $ship">
            <set_value name="$result.$PilotRegistryLinked" exact="true"/>
          </do_elseif>
          <do_elseif value="$pilotData.$ShipID? and $pilotData.$ShipID == $ship.idcode">
            <set_value name="$result.$PilotRegistryLinked" exact="true"/>
          </do_elseif>
        </do_if>
        
        <!-- CHECK 6: Cleanup Decision Logic -->
        <!-- Should cleanup if: ship was GT-controlled but no longer is -->
        <set_value name="$wasGTControlled" exact="false"/>
        <do_if value="$result.$InRegistry or $result.$StateSaysHasGTOrder or $result.$WasSubordinate or $result.$PilotRegistryLinked">
          <set_value name="$wasGTControlled" exact="true"/>
        </do_if>
        
        <!-- Cleanup needed if: was GT-controlled but now is NOT -->
        <do_if value="$wasGTControlled and not $result.$IsGTControlled">
          <!-- Promotion handoff guard:
               commander is temporarily Assist-only (no looped orders yet) after promotion.
               Keep subordinate registered and let delayed checks/order-restore settle first. -->
          <do_if value="$currentDefaultOrder == 'Assist' and $result.$CommanderPromotionPending">
            <set_value name="$result.$ShouldCleanup" exact="false"/>
            <set_value name="$result.$ShouldRestoreName" exact="false"/>
            <set_value name="$result.$IsPermanentRemoval" exact="false"/>
          </do_if>
          <do_else>
            <set_value name="$result.$ShouldCleanup" exact="true"/>
            
            <!-- Permanent removal if: no direct GT AND no GT commander -->
            <do_if value="not $result.$HasDirectGTOrder and not $result.$HasGTCommander">
              <set_value name="$result.$IsPermanentRemoval" exact="true"/>
            </do_if>
            
            <!-- Should restore name if: not subordinate to GT commander -->
            <do_if value="not $result.$IsSubordinate and $ship.pilot?">
              <set_value name="$result.$ShouldRestoreName" exact="true"/>
            </do_if>
          </do_else>
        </do_if>
        
        <!-- SPECIAL CASE: Subordinate with Assist order but commander check might fail due to timing -->
        <!-- If ship has Assist order, treat as active subordinate (even if commander check fails temporarily) -->
        <do_if value="$currentDefaultOrder == 'Assist' and $result.$CommanderExists">
          <!-- Commander exists - check if it has GT order -->
          <do_if value="$result.$HasGTCommander or $result.$CommanderPromotionPending">
            <set_value name="$result.$IsSubordinate" exact="true"/>
            <do_if value="$result.$HasGTCommander">
              <set_value name="$result.$IsGTControlled" exact="true"/>
            </do_if>
            <set_value name="$result.$ShouldCleanup" exact="false"/>
            <set_value name="$result.$ShouldRestoreName" exact="false"/>
          </do_if>
        </do_if>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Check pilot-exchange lifecycle status (authoritative state only, no time grace). -->
    <library name="GT_CheckPilotExchangeStatus" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check pilot-exchange status for"/>
      </params>
      <actions>
        <set_value name="$result" exact="table[]"/>
        <set_value name="$result.$FlagSet" exact="false"/>
        <set_value name="$result.$IsOrderActive" exact="false"/>
        <set_value name="$result.$HasQueuedExchangeOrder" exact="false"/>
        <set_value name="$result.$HasPendingDock" exact="false"/>
        <set_value name="$result.$ShouldKeepPE" exact="false"/>
        <set_value name="$result.$ShouldClearPE" exact="false"/>
        <set_value name="$result.$CurrentOrder" exact="'NONE'"/>
        <set_value name="$result.$CurrentCallerOrder" exact="'NONE'"/>
        
        <do_if value="$ship? and $ship.exists">
          <do_if value="$ship.order? and $ship.order.id?">
            <set_value name="$result.$CurrentOrder" exact="@$ship.order.id"/>
          </do_if>
          <do_if value="$ship.order? and $ship.order.$callerid? and $ship.order.$callerid.id?">
            <set_value name="$result.$CurrentCallerOrder" exact="@$ship.order.$callerid.id"/>
          </do_if>
          
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$PilotExchange? and global.$GT_Ships.{$ship}.$PilotExchange">
            <set_value name="$result.$FlagSet" exact="true"/>
          </do_if>
          
          <do_if value="$result.$CurrentOrder == 'DockAndPilotExchange'">
            <set_value name="$result.$IsOrderActive" exact="true"/>
          </do_if>
          <do_elseif value="$result.$CurrentOrder == 'DockAndWait' and $result.$CurrentCallerOrder == 'DockAndPilotExchange'">
            <set_value name="$result.$IsOrderActive" exact="true"/>
          </do_elseif>
          
          <do_if value="$ship.orders? and $ship.orders.count gt 0">
            <do_all exact="$ship.orders.count" counter="$i">
              <set_value name="$orderId" exact="@$ship.orders.{$i}.id"/>
              <set_value name="$callerId" exact="''"/>
              <do_if value="$ship.orders.{$i}.$callerid? and $ship.orders.{$i}.$callerid.id?">
                <set_value name="$callerId" exact="@$ship.orders.{$i}.$callerid.id"/>
              </do_if>
              <do_if value="$orderId == 'DockAndPilotExchange' or ($orderId == 'DockAndWait' and $callerId == 'DockAndPilotExchange')">
                <set_value name="$result.$HasQueuedExchangeOrder" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="global.$GT_RedistributePendingDockByShip? and $ship.idcode? and global.$GT_RedistributePendingDockByShip.{'$' + $ship.idcode}?">
            <set_value name="$result.$HasPendingDock" exact="true"/>
          </do_if>
          
          <!-- Keep PE only while exchange order is active or queued.
               Pending-dock markers alone are transitional and must not pin PE forever. -->
          <do_if value="$result.$IsOrderActive or $result.$HasQueuedExchangeOrder">
            <set_value name="$result.$ShouldKeepPE" exact="true"/>
          </do_if>
          
          <do_if value="$result.$FlagSet and not $result.$ShouldKeepPE">
            <set_value name="$result.$ShouldClearPE" exact="true"/>
          </do_if>
        </do_if>
        
        <return value="$result"/>
      </actions>
    </library>
    
    <!-- Reconcile PE flag against authoritative ship/order state and clear stale markers. -->
    <library name="GT_ReconcilePilotExchangeState" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to reconcile PE state for"/>
        <param name="reason" default="''" comment="Optional reason tag for debug tracing"/>
      </params>
      <actions>
        <do_if value="not $ship? or not $ship.exists">
          <return value="false"/>
        </do_if>
        
        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckPilotExchangeStatus" result="$peStatus">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <set_value name="$hadChanges" exact="false"/>
        <do_if value="$peStatus.$HasPendingDock and not ($peStatus.$IsOrderActive or $peStatus.$HasQueuedExchangeOrder)">
          <do_if value="global.$GT_RedistributePendingDockByShip? and $ship.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockByShip.{'$' + $ship.idcode}"/>
          </do_if>
          <do_if value="global.$GT_RedistributePendingDockSinceByShip? and $ship.idcode?">
            <remove_value name="global.$GT_RedistributePendingDockSinceByShip.{'$' + $ship.idcode}"/>
          </do_if>
          <set_value name="$hadChanges" exact="true"/>
        </do_if>
        
        <do_if value="$peStatus.$ShouldClearPE">
          <do_if value="global.$GT_Ships? and global.$GT_Ships.{$ship}?">
            <set_value name="global.$GT_Ships.{$ship}.$PilotExchange" exact="false"/>
          </do_if>
          <do_if value="$ship.pilot?">
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RequestShipNameRefresh">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$ship.pilot"/>
              <param name="reason" value="'pe_reconcile_clear:' + $reason"/>
            </run_actions>
          </do_if>
          <set_value name="$hadChanges" exact="true"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-StateUtils] Reconciled stale PE on ' + $ship.idcode + ' reason=' + (if $reason != '' then $reason else 'none') + ' current=' + $peStatus.$CurrentOrder + ' caller=' + $peStatus.$CurrentCallerOrder + ' queued=' + $peStatus.$HasQueuedExchangeOrder + ' hadPending=' + $peStatus.$HasPendingDock" chance="100"/>
          </do_if>
        </do_if>
        
        <return value="$hadChanges"/>
      </actions>
    </library>
    
    <!-- Check if Ship Should Trigger Cleanup -->
    <!-- Simplified wrapper that returns boolean for cleanup decision -->
    <library name="GT_ShouldTriggerCleanup" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
        <param name="checkRegistry" default="true" comment="Check registry"/>
        <param name="checkState" default="true" comment="Check state"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$status">
          <param name="ship" value="$ship"/>
          <param name="checkRegistry" value="$checkRegistry"/>
          <param name="checkState" value="$checkState"/>
        </run_actions>
        <return value="$status.$ShouldCleanup"/>
      </actions>
    </library>
    
    <!-- Check if Ship is GT-Controlled (Quick Check) -->
    <!-- Simplified wrapper for quick GT-controlled check -->
    <library name="GT_IsGTControlled" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
      </params>
      <actions>
        <run_actions ref="md.GT_Ship_State_Utilities.GT_CheckGTOrderStatus" result="$status">
          <param name="ship" value="$ship"/>
          <param name="checkRegistry" value="false"/>
          <param name="checkState" value="false"/>
        </run_actions>
        <return value="$status.$IsGTControlled"/>
      </actions>
    </library>
    
    <!-- Check if Ship is in Maintenance (Repair/Resupply) -->
    <!-- Unified maintenance check used by batch processor and cleanup logic -->
    <library name="GT_IsShipInMaintenance" purpose="run_actions">
      <params>
        <param name="ship" comment="Ship to check"/>
      </params>
      <actions>
        <set_value name="$isInMaintenance" exact="false"/>
        
        <!-- Check for active repair order -->
        <do_if value="global.$GT_RepairOrders? and global.$GT_RepairOrders.{$ship}?">
          <set_value name="$isInMaintenance" exact="true"/>
        </do_if>
        
        <!-- Check for active resupply order -->
        <do_if value="not $isInMaintenance and global.$GT_ResupplyOrders? and global.$GT_ResupplyOrders.{$ship}?">
          <set_value name="$isInMaintenance" exact="true"/>
        </do_if>
        
        <!-- Check for active repair/resupply orders on ship -->
        <do_if value="not $isInMaintenance and $ship.orders? and $ship.orders.count gt 0">
          <do_all exact="$ship.orders.count" counter="$i">
            <set_value name="$orderId" exact="@$ship.orders.{$i}.id"/>
            <do_if value="$orderId == 'Repair' or $orderId == 'Resupply'">
              <set_value name="$isInMaintenance" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <return value="$isInMaintenance"/>
      </actions>
    </library>
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_TerritoryManagement" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Territory Management System Initialization -->
    <cue name="SystemInit" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.SystemInit"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Territory Management system initializing...'" chance="100"/>
        </do_if>
        
        <!-- Initialize territory structures -->
        <set_value name="global.$GT_Territories" exact="table[]"/>
        <set_value name="global.$GT_SectorExpertise" exact="table[]"/>
        <set_value name="global.$GT_TerritoryBonuses" exact="table[]"/>
        <set_value name="global.$GT_SectorAnalysis" exact="table[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Territory Management system initialized'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- PHASE 4 IMPROVEMENT: Event-Driven Territory Management -->
    <!-- Initialize territory event system -->
    <cue name="InitTerritoryEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="SystemInit"/>
      </conditions>
      <actions>
        <!-- Initialize territory event queue -->
        <set_value name="global.$GT_TerritoryEventQueue" exact="[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] âš¡ Territory event system initialized (event-driven)'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Process Territory Events -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessTerritoryEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_TerritoryManagement.ProcessTerritoryEvents"/>
      </conditions>
      <actions>
        
        <do_if value="global.$GT_TerritoryEventQueue? and global.$GT_TerritoryEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] âš¡ Processing ' + global.$GT_TerritoryEventQueue.count + ' territory events instantly'" chance="100"/>
          </do_if>
          
          <!-- Process all events in batch -->
          <do_all exact="global.$GT_TerritoryEventQueue.count" counter="$i">
            <set_value name="$event" exact="global.$GT_TerritoryEventQueue.{$i}"/>
            <set_value name="$type" exact="$event.$type"/>
            
            <!-- Route to appropriate handler -->
            <!-- PERFORMANCE: Removed 'sector_change' and 'ship_assignment' handlers - never triggered -->
            <do_if value="$type == 'trade_completion'">
              <signal_cue_instantly cue="HandleTradeCompletionEvent" param="$event"/>
            </do_if>
            <do_elseif value="$type == 'conflict_detection'">
              <signal_cue_instantly cue="HandleConflictEvent" param="$event"/>
            </do_elseif>
          </do_all>
          
          <!-- Clear processed events -->
          <set_value name="global.$GT_TerritoryEventQueue" exact="[]"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- PERFORMANCE: HandleSectorChangeEvent removed - never triggered (no code creates 'sector_change' events) -->
    <!-- UpdateExpertise is still called directly from trade completion events -->
    
    <!-- Handle Trade Completion Events -->
    <cue name="HandleTradeCompletionEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$ship" exact="$event.$ship"/>
        <set_value name="$sector" exact="$event.$sector"/>
        <set_value name="$success" exact="$event.$success"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Territory event: ' + $ship.idcode + ' completed trade in ' + $sector.knownname + ' (success: ' + $success + ')'" chance="100"/>
        </do_if>
        
        <!-- Update expertise based on trade success -->
        <set_value name="$expertiseEvent" exact="table[]"/>
        <set_value name="$expertiseEvent.$ship" exact="$ship"/>
        <set_value name="$expertiseEvent.$sector" exact="$sector"/>
        <set_value name="$expertiseEvent.$success" exact="$success"/>
        <signal_cue_instantly cue="UpdateExpertise" param="$expertiseEvent"/>
        
        <!-- Trigger conflict detection if needed -->
        <set_value name="$conflictEvent" exact="table[]"/>
        <set_value name="$conflictEvent.$type" exact="'conflict_detection'"/>
        <set_value name="$conflictEvent.$sector" exact="$sector"/>
        <set_value name="$conflictEvent.$trigger" exact="'trade_completion'"/>
        <append_to_list name="global.$GT_TerritoryEventQueue" exact="$conflictEvent"/>
        
        <!-- Signal MD cue directly (no polling needed) -->
        <signal_cue_instantly cue="md.GT_TerritoryManagement.ProcessTerritoryEvents"/>
      </actions>
    </cue>
    
    <!-- PERFORMANCE: HandleShipAssignmentEvent removed - never triggered (no code creates 'ship_assignment' events) -->
    
    <!-- Handle Conflict Events -->
    <cue name="HandleConflictEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$trigger" exact="$event.$trigger"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Territory event: Conflict check triggered by ' + $trigger" chance="100"/>
        </do_if>
        
        <!-- PERFORMANCE: ResolveConflicts removed - territories not used in trade search -->
      </actions>
    </cue>
    
    <!-- PERFORMANCE: AnalyzeSectors, CalculateSectorMetrics, and OptimizeTerritories removed -->
    <!-- These cues performed expensive analysis (find_sector, find_station, find_offers) every 10 minutes -->
    <!-- but the results were never used in trade search - territories are assigned but not checked during trade selection -->
    <!-- OptimizeTerritories was never called (handlers HandleSectorChangeEvent and HandleShipAssignmentEvent were never triggered) -->
    <!-- Even if called, OptimizeTerritories would do nothing without sector analysis data -->
    <!-- Territory assignments still exist but don't affect trade search logic -->
    
    <!-- Update Ship Expertise -->
    <cue name="UpdateExpertise" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param.ship"/>
        <set_value name="$sector" exact="event.param.sector"/>
        <set_value name="$tradeSuccess" exact="event.param.success"/>
        
        <!-- Initialize expertise tracking if needed -->
        <do_if value="not global.$GT_SectorExpertise.{$ship}?">
          <set_value name="global.$GT_SectorExpertise.{$ship}" exact="table[]"/>
        </do_if>
        
        <do_if value="not global.$GT_SectorExpertise.{$ship}.{$sector}?">
          <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}" exact="table[]"/>
          <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}.$Level" exact="0"/>
          <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}.$Experience" exact="0"/>
          <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}.$TradeCount" exact="0"/>
        </do_if>
        
        <!-- Award experience -->
        <set_value name="$expGain" exact="10"/>
        <do_if value="$tradeSuccess">
          <set_value name="$expGain" exact="25"/>
        </do_if>
        
        <!-- Bonus for trading in assigned territory -->
        <do_if value="global.$GT_Territories.{$ship}? and global.$GT_Territories.{$ship}.$Primary == $sector">
          <set_value name="$expGain" exact="$expGain * 1.5"/>
        </do_if>
        
        <!-- Update expertise -->
        <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}.$Experience" exact="global.$GT_SectorExpertise.{$ship}.{$sector}.$Experience + $expGain"/>
        <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}.$TradeCount" exact="global.$GT_SectorExpertise.{$ship}.{$sector}.$TradeCount + 1"/>
        
        <!-- Check for level up -->
        <set_value name="$currentExp" exact="global.$GT_SectorExpertise.{$ship}.{$sector}.$Experience"/>
        <set_value name="$currentLevel" exact="global.$GT_SectorExpertise.{$ship}.{$sector}.$Level"/>
        <set_value name="$requiredExp" exact="($currentLevel + 1) * 500"/>
        
        <do_if value="$currentExp ge $requiredExp and $currentLevel lt 10">
          <set_value name="global.$GT_SectorExpertise.{$ship}.{$sector}.$Level" exact="$currentLevel + 1"/>
          
          <!-- Calculate and apply bonuses -->
          <set_value name="global.$GT_CalculateBonusShip" exact="$ship"/>
          <set_value name="global.$GT_CalculateBonusSector" exact="$sector"/>
          <signal_cue cue="CalculateTerritoryBonus"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] ' + $ship.knownname + ' reached expertise level ' + ($currentLevel + 1) + ' in ' + $sector.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Calculate Territory Bonuses -->
    <cue name="CalculateTerritoryBonus" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="global.$GT_CalculateBonusShip"/>
        <set_value name="$sector" exact="global.$GT_CalculateBonusSector"/>
        
        <!-- Get expertise level -->
        <set_value name="$level" exact="0"/>
        <do_if value="global.$GT_SectorExpertise.{$ship}? and global.$GT_SectorExpertise.{$ship}.{$sector}?">
          <set_value name="$level" exact="global.$GT_SectorExpertise.{$ship}.{$sector}.$Level"/>
        </do_if>
        
        <!-- Calculate bonuses based on expertise level -->
        <set_value name="$profitBonus" exact="1.0 + ($level * 0.02)"/> <!-- 2% per level -->
        <set_value name="$negotiationBonus" exact="1.0 + ($level * 0.01)"/> <!-- 1% per level -->
        <set_value name="$speedBonus" exact="1.0 + ($level * 0.005)"/> <!-- 0.5% per level -->
        
        <!-- Store bonuses -->
        <do_if value="not global.$GT_TerritoryBonuses.{$ship}?">
          <set_value name="global.$GT_TerritoryBonuses.{$ship}" exact="table[]"/>
        </do_if>
        
        <do_if value="not global.$GT_TerritoryBonuses.{$ship}.{$sector}?">
          <set_value name="global.$GT_TerritoryBonuses.{$ship}.{$sector}" exact="table[]"/>
        </do_if>
        
        <set_value name="global.$GT_TerritoryBonuses.{$ship}.{$sector}.$ProfitMultiplier" exact="$profitBonus"/>
        <set_value name="global.$GT_TerritoryBonuses.{$ship}.{$sector}.$NegotiationMultiplier" exact="$negotiationBonus"/>
        <set_value name="global.$GT_TerritoryBonuses.{$ship}.{$sector}.$SpeedMultiplier" exact="$speedBonus"/>
        <set_value name="global.$GT_TerritoryBonuses.{$ship}.{$sector}.$LastCalculated" exact="player.age"/>
      </actions>
    </cue>
    
    <!-- Apply Territory Bonuses to Trade -->
    <cue name="ApplyTerritoryBonus" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param.ship"/>
        <set_value name="$sector" exact="event.param.sector"/>
        <set_value name="$baseProfit" exact="event.param.profit"/>
        
        <!-- Check for applicable bonuses -->
        <set_value name="$finalProfit" exact="$baseProfit"/>
        
        <do_if value="global.$GT_TerritoryBonuses.{$ship}? and global.$GT_TerritoryBonuses.{$ship}.{$sector}?">
          <set_value name="$profitMultiplier" exact="global.$GT_TerritoryBonuses.{$ship}.{$sector}.$ProfitMultiplier"/>
          <set_value name="$finalProfit" exact="$baseProfit * $profitMultiplier"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Territory bonus applied: ' + $baseProfit + ' -> ' + $finalProfit + ' (x' + $profitMultiplier + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Return modified profit -->
        <set_value name="global.$GT_TerritoryBonusResult" exact="$finalProfit"/>
      </actions>
    </cue>
    
    <!-- PERFORMANCE: ResolveConflicts removed -->
    <!-- Territories are not used in trade search, so conflict resolution is unnecessary -->
    <!-- This cue iterated through all ships every 15 minutes for no functional benefit -->
    
    <!-- Territory Performance Report -->
    <cue name="GenerateTerritoryReport" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$report" exact="'Territory Management Report\n\n'"/>
        
        <!-- Territory assignments -->
        <set_value name="$report" exact="$report + 'TERRITORY ASSIGNMENTS:\n'"/>
        
        <do_all exact="global.$GT_Ships.keys.count" counter="$i">
          <set_value name="$ship" exact="global.$GT_Ships.keys.list.{$i}"/>
          
          <do_if value="$ship.exists and global.$GT_Territories.{$ship}? and global.$GT_Territories.{$ship}.$Primary?">
            <set_value name="$primary" exact="global.$GT_Territories.{$ship}.$Primary"/>
            <set_value name="$expertise" exact="0"/>
            <set_value name="$level" exact="0"/>
            
            <do_if value="global.$GT_SectorExpertise.{$ship}? and global.$GT_SectorExpertise.{$ship}.{$primary}?">
              <set_value name="$expertise" exact="global.$GT_SectorExpertise.{$ship}.{$primary}.$Experience"/>
              <set_value name="$level" exact="global.$GT_SectorExpertise.{$ship}.{$primary}.$Level"/>
            </do_if>
            
            <set_value name="$report" exact="$report + 'â€¢ ' + $ship.knownname + ': ' + $primary.knownname + ' (Level ' + $level + ', ' + $expertise + ' XP)\n'"/>
          </do_if>
        </do_all>
        
        <!-- Top sectors by score -->
        <set_value name="$report" exact="$report + '\nTOP SECTORS BY VALUE:\n'"/>
        <set_value name="$topCount" exact="[global.$GT_SectorAnalysis.keys.count, 5].min"/>
        
        <do_all exact="$topCount" counter="$i">
          <do_if value="global.$GT_SectorAnalysis.keys.count ge $i">
            <set_value name="$sector" exact="global.$GT_SectorAnalysis.keys.list.{$i}"/>
            <set_value name="$score" exact="global.$GT_SectorAnalysis.{$sector}.$Score"/>
            <set_value name="$report" exact="$report + ($i) + '. ' + $sector.knownname + ' (Score: ' + $score + ')\n'"/>
          </do_if>
        </do_all>
        
        <!-- Return report -->
        <set_value name="global.$GT_TerritoryReport" exact="$report"/>
      </actions>
    </cue>
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_ThreatIntelligence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  
  <!-- DYNAMIC THREAT INTELLIGENCE SYSTEM -->
  <!-- Real-time hostile activity detection and fleet-wide reporting for GalaxyTrader MK3 -->
  <!-- Level Requirements: 6+ for threat detection, 12+ for mid-trade route threat analysis -->
  
  <cues>
    
    <!-- Create tracked-enemy group at MD load (before any destroy events can fire) -->
    <cue name="EnsureTrackedEnemyShipsGroup">
      <actions>
        <do_if value="not global.$GT_TrackedEnemyShipsGroup?">
          <create_group groupname="global.$GT_TrackedEnemyShipsGroup"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Initialize the Threat Intelligence System -->
    <cue name="InitializeThreatSystem" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_started/>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <!-- Initialize cleanup tracking if needed -->
        <do_if value="not global.$GT_ThreatCleanupTime? or global.$GT_ThreatCleanupTime == 0">
          <set_value name="global.$GT_ThreatCleanupTime" exact="player.age"/>
        </do_if>
        <!-- Route-reroute integration: epoch bumps when dynamic blacklist payload changes -->
        <do_if value="not global.$GT_BlacklistEpoch?">
          <set_value name="global.$GT_BlacklistEpoch" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_LastThreatBlacklistData?">
          <set_value name="global.$GT_LastThreatBlacklistData" exact="''"/>
        </do_if>
        <!-- MD group for reliable event_object_destroyed on tracked enemy ships (vanilla pattern) -->
        <do_if value="not global.$GT_TrackedEnemyShipsGroup?">
          <create_group groupname="global.$GT_TrackedEnemyShipsGroup"/>
        </do_if>
        <!-- Re-sync group membership from persisted threat data after save load -->
        <do_if value="global.$GT_ThreatIntelligence?">
          <do_all exact="global.$GT_ThreatIntelligence.keys.count" counter="$syncIdx">
            <set_value name="$syncSector" exact="global.$GT_ThreatIntelligence.keys.list.{$syncIdx}"/>
            <set_value name="$syncThreat" exact="global.$GT_ThreatIntelligence.{$syncSector}"/>
            <do_if value="$syncThreat.$TrackedEnemyShips? and $syncThreat.$TrackedEnemyShips.count gt 0">
              <do_all exact="$syncThreat.$TrackedEnemyShips.count" counter="$syncShipIdx">
                <set_value name="$syncShip" exact="null"/>
                <do_if value="$syncThreat.$TrackedEnemyShips.{$syncShipIdx}?">
                  <set_value name="$syncShip" exact="$syncThreat.$TrackedEnemyShips.{$syncShipIdx}"/>
                </do_if>
                <do_if value="$syncShip? and @$syncShip.exists and @$syncShip.isoperational">
                  <add_to_group groupname="global.$GT_TrackedEnemyShipsGroup" object="$syncShip"/>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </cue>

    <!-- Clear blacklist when player builds a defense station in a threatened sector -->
    <!-- Event-driven: triggered only when a module finishes (vanilla MD event) -->
    <cue name="ClearThreatOnPlayerDefenseStationBuilt" instantiate="true">
      <conditions>
        <!-- Vanilla: fires when a module is completed on a build anchor -->
        <event_player_build_finished_components/>
        <check_value value="event.param.buildanchor.isclass.station"/>
        <check_value value="event.param.buildanchor.isplayerowned"/>
        <check_value value="event.param.buildanchor.isdefencestation"/>
      </conditions>
      <actions>
        <set_value name="$station" exact="event.param.buildanchor"/>
        <set_value name="$sector" exact="@$station.sector"/>
        
        <!-- Only act if this sector is currently tracked/blacklisted by GT threat system -->
        <do_if value="$sector? and global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.{$sector}?">
          <run_actions ref="ClearSectorIfAllShipsGone">
            <param name="Sector" value="$sector"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          <signal_cue_instantly cue="ApplyBlacklistToFleet"/>
          
          <show_notification text="'Threat cleared: Player defense station established in ' + $sector.knownname + ' - removing sector from GT blacklist'" timeout="8s"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] Cleared blacklisted sector ' + $sector.knownname + ' due to player defense station construction: ' + @$station.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- ========================================================================= -->
    <!-- LIBRARY: Only combat-purpose ships may trigger sector blacklisting -->
    <!-- ========================================================================= -->
    <library name="CanShipTriggerBlacklist" purpose="run_actions">
      <params>
        <param name="Ship"/>
        <param name="DebugChance" default="0"/>
      </params>
      <actions>
        <set_value name="$canTrigger" exact="false"/>
        <do_if value="$Ship? and @$Ship.exists and $Ship.primarypurpose == purpose.fight">
          <set_value name="$canTrigger" exact="true"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Threat] Ship ' + (if $Ship? and @$Ship.exists then $Ship.knownname else 'UNKNOWN') + ' cannot trigger blacklist (requires purpose.fight, got ' + (if $Ship? and @$Ship.exists then $Ship.primarypurpose else 'n/a') + ')'" chance="$DebugChance"/>
          </do_if>
        </do_else>
        <return value="table[$CanTrigger = $canTrigger]"/>
      </actions>
    </library>
    
    <!-- ========================================================================= -->
    <!-- LIBRARY: Wipe all MD + Lua threat blacklist state (settings menu clear) -->
    <!-- ========================================================================= -->
    <library name="ClearAllThreatBlacklistData" purpose="run_actions">
      <params>
        <param name="Reason" default="'manual'"/>
        <param name="RefreshFleetBlacklist" default="true"/>
        <param name="DebugChance" default="0"/>
      </params>
      <actions>
        <set_value name="$clearedCount" exact="0"/>
        <do_if value="global.$GT_ThreatIntelligence?">
          <set_value name="$clearedCount" exact="global.$GT_ThreatIntelligence.keys.count"/>
          <remove_value name="global.$GT_ThreatIntelligence"/>
        </do_if>
        
        <do_if value="global.$GT_TrackedEnemyShipsGroup?">
          <clear_group group="global.$GT_TrackedEnemyShipsGroup"/>
        </do_if>
        
        <do_if value="not global.$GT_BlacklistEpoch?">
          <set_value name="global.$GT_BlacklistEpoch" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_LastThreatBlacklistData?">
          <set_value name="global.$GT_LastThreatBlacklistData" exact="''"/>
        </do_if>
        
        <!-- Force Lua + route-epoch sync even when threat table is already empty -->
        <set_value name="global.$GT_LastThreatBlacklistData" exact="''"/>
        <set_value name="global.$GT_BlacklistEpoch" exact="global.$GT_BlacklistEpoch + 1"/>
        
        <raise_lua_event name="'GT_Blacklist.Update'" param="''"/>
        
        <do_if value="$RefreshFleetBlacklist">
          <set_value name="global.$GT_ManualBlacklistAssignRequested" exact="true"/>
          <signal_cue_instantly cue="ApplyBlacklistToFleet"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Threat] ClearAllThreatBlacklistData reason=' + $Reason + ' cleared=' + $clearedCount + ' epoch=' + global.$GT_BlacklistEpoch" chance="$DebugChance"/>
        </do_if>
        
        <return value="table[$ClearedCount = $clearedCount]"/>
      </actions>
    </library>
    
    <!-- ========================================================================= -->
    <!-- LIBRARY: Check if sector should be blacklisted based on player defenses -->
    <!-- ========================================================================= -->
    <library name="ShouldBlacklistSector" purpose="run_actions">
      <params>
        <param name="Sector"/>
        <param name="EnemyThreatScore" default="0"/> <!-- Optional: if already calculated -->
        <param name="EnemyShips" default="null"/> <!-- Optional: list of enemy ships if already found -->
        <param name="DebugChance" default="0"/>
      </params>
      <actions>
        <set_value name="$shouldBlacklist" exact="true"/>
        <set_value name="$hasDefenseStation" exact="false"/>
        <set_value name="$playerFightingScore" exact="0"/>
        <set_value name="$calculatedEnemyScore" exact="0"/>
        
        <!-- Step 1: Check for defense stations -->
        <find_station name="$defenseStations" space="$Sector" owner="faction.player" defencestation="true" multiple="true"/>
        <do_if value="$defenseStations.count gt 0">
          <set_value name="$hasDefenseStation" exact="true"/>
          <set_value name="$shouldBlacklist" exact="false"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Threat] Sector ' + $Sector.knownname + ' has ' + $defenseStations.count + ' defense station(s) - skipping blacklist'" chance="$DebugChance"/>
          </do_if>
        </do_if>
        
        <!-- Step 2: If no defense station, compare enemy score vs PLAYER COMBAT SHIPS only.
             IMPORTANT: Only count ships with primarypurpose == purpose.fight (vanilla MD pattern).
             This prevents L/XL traders from being miscounted as "combat strength". -->
        <do_if value="$shouldBlacklist">
          <!-- Calculate enemy threat score -->
          <!-- Priority: Use EnemyShips if provided, otherwise use EnemyThreatScore -->
          <do_if value="$EnemyShips? and $EnemyShips != null and $EnemyShips.count gt 0">
            <do_all exact="$EnemyShips.count" counter="$i">
              <set_value name="$enemy" exact="$EnemyShips.{$i}"/>
              <do_if value="$enemy.isclass.ship_xl">
                <set_value name="$calculatedEnemyScore" exact="$calculatedEnemyScore + 5"/>
              </do_if>
              <do_elseif value="$enemy.isclass.ship_l">
                <set_value name="$calculatedEnemyScore" exact="$calculatedEnemyScore + 3"/>
              </do_elseif>
              <do_elseif value="$enemy.isclass.ship_m">
                <set_value name="$calculatedEnemyScore" exact="$calculatedEnemyScore + 2"/>
              </do_elseif>
              <do_else>
                <set_value name="$calculatedEnemyScore" exact="$calculatedEnemyScore + 1"/>
              </do_else>
            </do_all>
          </do_if>
          <do_elseif value="$EnemyThreatScore gt 0">
            <set_value name="$calculatedEnemyScore" exact="$EnemyThreatScore"/>
          </do_elseif>

          <!-- No enemy score => no blacklist -->
          <do_if value="$calculatedEnemyScore le 0">
            <set_value name="$shouldBlacklist" exact="false"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $Sector.knownname + ' has no detectable threat score - skipping blacklist'" chance="$DebugChance"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Calculate player fighting score (combat ships only) -->
            <find_ship name="$playerCombatShips" space="$Sector" owner="faction.player" primarypurpose="purpose.fight" class="[class.ship_s, class.ship_m, class.ship_l, class.ship_xl]" multiple="true"/>
            <do_all exact="$playerCombatShips.count" counter="$j">
              <set_value name="$playerShip" exact="$playerCombatShips.{$j}"/>
              <do_if value="$playerShip.isclass.ship_xl">
                <set_value name="$playerFightingScore" exact="$playerFightingScore + 5"/>
              </do_if>
              <do_elseif value="$playerShip.isclass.ship_l">
                <set_value name="$playerFightingScore" exact="$playerFightingScore + 3"/>
              </do_elseif>
              <do_elseif value="$playerShip.isclass.ship_m">
                <set_value name="$playerFightingScore" exact="$playerFightingScore + 2"/>
              </do_elseif>
              <do_else>
                <set_value name="$playerFightingScore" exact="$playerFightingScore + 1"/>
              </do_else>
            </do_all>

            <!-- Compare scores -->
            <do_if value="$playerFightingScore ge $calculatedEnemyScore">
              <set_value name="$shouldBlacklist" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] Sector ' + $Sector.knownname + ' player fighting score (' + $playerFightingScore + ') >= enemy score (' + $calculatedEnemyScore + ') - skipping blacklist'" chance="$DebugChance"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] Sector ' + $Sector.knownname + ' player fighting score (' + $playerFightingScore + ') &lt; enemy score (' + $calculatedEnemyScore + ') - blacklisting'" chance="$DebugChance"/>
              </do_if>
            </do_else>
          </do_else>
        </do_if>
        
        <!-- Return result as table -->
        <return value="table[
          $ShouldBlacklist = $shouldBlacklist,
          $HasDefenseStation = $hasDefenseStation,
          $PlayerFightingScore = $playerFightingScore,
          $EnemyThreatScore = $calculatedEnemyScore
        ]"/>
      </actions>
    </library>
    
    <!-- ========================================================================= -->
    <!-- LIBRARY: Remove one tracked enemy ship from sector list and MD group -->
    <!-- ========================================================================= -->
    <library name="RemoveTrackedEnemyShip" purpose="run_actions">
      <params>
        <param name="Sector"/>
        <param name="Ship"/>
        <param name="DebugChance" default="0"/>
      </params>
      <actions>
        <do_if value="$Ship? and $Ship != null and global.$GT_ThreatIntelligence? and global.$GT_ThreatIntelligence.{$Sector}? and global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips?">
          <remove_from_list name="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips" exact="$Ship"/>
          <do_if value="global.$GT_TrackedEnemyShipsGroup?">
            <remove_from_group group="global.$GT_TrackedEnemyShipsGroup" object="$Ship"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Threat] Removed tracked enemy ' + @$Ship.knownname + ' from sector ' + $Sector.knownname" chance="$DebugChance"/>
          </do_if>
        </do_if>
      </actions>
    </library>
    
    <!-- ========================================================================= -->
    <!-- LIBRARY: Store tracked enemy ships for sector blacklist tracking -->
    <!-- ========================================================================= -->
    <library name="StoreTrackedEnemyShips" purpose="run_actions">
      <params>
        <param name="Sector"/>
        <param name="EnemyShips"/> <!-- List of enemy ships to track -->
        <param name="DebugChance" default="0"/>
      </params>
      <actions>
        <!-- Ensure table exists before accessing (handles race condition) -->
        <do_if value="not global.$GT_ThreatIntelligence?">
          <set_value name="global.$GT_ThreatIntelligence" exact="table[]"/>
        </do_if>
        <!-- Initialize sector entry if needed -->
        <do_if value="not global.$GT_ThreatIntelligence.{$Sector}?">
          <set_value name="global.$GT_ThreatIntelligence.{$Sector}" exact="table[]"/>
        </do_if>
        <!-- Initialize tracking list if needed -->
        <do_if value="not global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips?">
          <set_value name="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips" exact="[]"/>
        </do_if>
        
        <!-- Add new enemy ships to tracking (avoid duplicates) -->
        <!-- IMPORTANT: ? only checks whether a variable is defined, not whether its value is null -->
        <do_if value="$EnemyShips == null">
          <set_value name="$EnemyShips" exact="[]"/>
        </do_if>
        <do_if value="$EnemyShips.count gt 0">
          <set_value name="$trackedShips" exact="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips"/>
          <set_value name="$newShipsAdded" exact="0"/>
          <set_value name="$newShipNames" exact="[]"/>
          
          <do_all exact="$EnemyShips.count" counter="$i">
            <set_value name="$enemyShip" exact="$EnemyShips.{$i}"/>
            
            <!-- Check if ship already tracked -->
            <set_value name="$alreadyTracked" exact="false"/>
            <do_all exact="$trackedShips.count" counter="$j">
              <do_if value="$trackedShips.{$j} == $enemyShip">
                <set_value name="$alreadyTracked" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            
            <!-- Add if not already tracked -->
            <do_if value="not $alreadyTracked">
              <append_to_list name="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips" exact="$enemyShip"/>
              <do_if value="global.$GT_TrackedEnemyShipsGroup?">
                <add_to_group groupname="global.$GT_TrackedEnemyShipsGroup" object="$enemyShip"/>
              </do_if>
              <set_value name="$newShipsAdded" exact="$newShipsAdded + 1"/>
              <append_to_list name="$newShipNames" exact="@$enemyShip.knownname + ' (' + $enemyShip.idcode + ')'"/>
            </do_if>
          </do_all>
          
          <!-- Build ship list string for logging -->
          <set_value name="$shipListString" exact="''"/>
          <do_all exact="$newShipNames.count" counter="$k">
            <do_if value="$k == 0">
              <set_value name="$shipListString" exact="$newShipNames.{$k}"/>
            </do_if>
            <do_else>
              <set_value name="$shipListString" exact="$shipListString + ', ' + $newShipNames.{$k}"/>
            </do_else>
          </do_all>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Threat] Stored ' + $newShipsAdded + ' new enemy ships for tracking in sector ' + $Sector.knownname + ' (total tracked: ' + global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips.count + '): ' + $shipListString" chance="$DebugChance"/>
          </do_if>
        </do_if>
      </actions>
    </library>
    
    <!-- ========================================================================= -->
    <!-- LIBRARY: Clear sector from blacklist when all tracked ships are gone -->
    <!-- ========================================================================= -->
    <library name="ClearSectorIfAllShipsGone" purpose="run_actions">
      <params>
        <param name="Sector"/>
        <param name="DebugChance" default="0"/>
      </params>
      <actions>
        <set_value name="$shouldClear" exact="false"/>
        
        <do_if value="not global.$GT_ThreatIntelligence? or not global.$GT_ThreatIntelligence.{$Sector}?">
          <return value="table[$SectorCleared = false]"/>
        </do_if>
        <do_else>
          <!-- Prune destroyed, invalid, or departed tracked ships -->
          <do_if value="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips?">
            <set_value name="$trackedShips" exact="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips"/>
            <do_all exact="$trackedShips.count" counter="$pruneIdx" reverse="true">
              <set_value name="$pruneShip" exact="null"/>
              <do_if value="$trackedShips.{$pruneIdx}?">
                <set_value name="$pruneShip" exact="$trackedShips.{$pruneIdx}"/>
              </do_if>
              <set_value name="$shouldPrune" exact="false"/>
              <do_if value="$pruneShip == null">
                <set_value name="$shouldPrune" exact="true"/>
              </do_if>
              <do_elseif value="not @$pruneShip.exists or not @$pruneShip.isoperational">
                <set_value name="$shouldPrune" exact="true"/>
              </do_elseif>
              <do_elseif value="$pruneShip.sector? and $pruneShip.sector != $Sector">
                <set_value name="$shouldPrune" exact="true"/>
              </do_elseif>
              <do_if value="$shouldPrune">
                <do_if value="$pruneShip? and $pruneShip != null">
                  <run_actions ref="RemoveTrackedEnemyShip">
                    <param name="Sector" value="$Sector"/>
                    <param name="Ship" value="$pruneShip"/>
                    <param name="DebugChance" value="0"/>
                  </run_actions>
                </do_if>
                <do_else>
                  <remove_from_list name="global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips" exact="$trackedShips.{$pruneIdx}"/>
                </do_else>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Live sector scan: defenses may now protect, or hostiles may be gone -->
          <find_ship name="$liveEnemies" space="$Sector" multiple="true">
            <match_relation_to object="player.entity" relation="enemy" comparison="le"/>
          </find_ship>
          <set_value name="$liveEnemyCount" exact="if $liveEnemies != null then $liveEnemies.count else 0"/>
          
          <run_actions ref="ShouldBlacklistSector" result="$defenseCheck">
            <param name="Sector" value="$Sector"/>
            <param name="EnemyShips" value="$liveEnemies"/>
            <param name="DebugChance" value="$DebugChance"/>
          </run_actions>
          
          <set_value name="$remainingTracked" exact="@global.$GT_ThreatIntelligence.{$Sector}.$TrackedEnemyShips"/>
          <set_value name="$remainingTrackedCount" exact="if $remainingTracked != null then $remainingTracked.count else 0"/>
          
          <!-- Clear when defenses protect sector, or no hostiles remain and none tracked -->
          <do_if value="not $defenseCheck.$ShouldBlacklist">
            <set_value name="$shouldClear" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $Sector.knownname + ' cleared - defenses now protect (station: ' + $defenseCheck.$HasDefenseStation + ', player score: ' + $defenseCheck.$PlayerFightingScore + ' vs enemy: ' + $defenseCheck.$EnemyThreatScore + ')'" chance="$DebugChance"/>
            </do_if>
          </do_if>
          <do_elseif value="$liveEnemyCount == 0 and $remainingTrackedCount == 0">
            <set_value name="$shouldClear" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $Sector.knownname + ' cleared from blacklist - all tracked enemy ships eliminated'" chance="$DebugChance"/>
            </do_if>
          </do_elseif>
          
          <do_if value="$shouldClear">
            <remove_value name="global.$GT_ThreatIntelligence.{$Sector}"/>
            <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
            <show_notification text="{77000,3219}.[$Sector.knownname]" timeout="8s"/>
          </do_if>
          
          <set_value name="this.$SectorCleared" exact="$shouldClear"/>
          <return value="table[$SectorCleared = $shouldClear]"/>
        </do_else>
      </actions>
    </library>
    
    <!-- Attack Threat Detection -->
    <cue name="DetectAttackThreats" instantiate="true">
      <conditions>
        <event_object_attacked object="player.galaxy"/>
      </conditions>
      <actions>
        <!-- Only process if threat avoidance is enabled -->
        <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance? or not global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled or (global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <!-- Exit: threat avoidance disabled -->
        </do_if>
        <do_else>
        <set_value name="$victim" exact="event.object"/>
        <set_value name="$attacker" exact="event.param"/>
        
        <!-- Only process attacks on GalaxyTrader ships -->
        <do_if value="$victim.isplayerowned and global.$GT_Ships.{$victim}? and $victim.sector? and $attacker?">
          <set_value name="$currentSector" exact="$victim.sector"/>
          
          <!-- Determine threat level based on attacker characteristics -->
          <set_value name="$threatLevel" exact="2"/> <!-- Default: Medium threat -->
          
          <!-- Very high threat for Xenon/Kha'ak -->
          <do_if value="$attacker.owner? and ($attacker.owner.id == 'xenon' or $attacker.owner.id == 'khaak')">
            <set_value name="$threatLevel" exact="5"/>
          </do_if>
          <!-- High threat for capital ships and large attackers -->
          <do_elseif value="$attacker.isclass.ship_xl or $attacker.isclass.ship_l">
            <set_value name="$threatLevel" exact="4"/>
          </do_elseif>
          <!-- Medium-high threat for other hostile factions -->
          <do_elseif value="$attacker.owner? and faction.player.relationto.{$attacker.owner} le -0.2">
            <set_value name="$threatLevel" exact="3"/>
          </do_elseif>
          
          <!-- Report the threat -->
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}" exact="table[]"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$Timestamp" exact="player.age"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ThreatLevel" exact="$threatLevel"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$AttackerType" exact="$attacker.idcode"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$AttackerFaction" exact="@$attacker.owner.knownname"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ReportingShip" exact="$victim.knownname"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ThreatType" exact="'Attack'"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$VictimShip" exact="$victim.knownname"/>
          
          <!-- Update ship statistics -->
          <set_value name="global.$GT_Ships.{$victim}.$ThreatReports" exact="global.$GT_Ships.{$victim}.$ThreatReports + 1"/>
          <set_value name="global.$GT_Ships.{$victim}.$LastThreatTime" exact="player.age"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3]  THREAT REPORT: ' + $victim.knownname + ' attacked by ' + @$attacker.knownname + ' (' + @$attacker.owner.knownname + ') in ' + $currentSector.knownname + ' - Threat Level: ' + $threatLevel" chance="100"/>
          </do_if>
          
          <!-- Notify fleet for high threats -->
          <do_if value="$threatLevel ge 3">
            <show_notification text="' FLEET ALERT: High threat activity in ' + $currentSector.knownname + ' - All traders advised to avoid'" timeout="10s"/>
          </do_if>
          
          <!-- Check defenses before blacklisting (combat ships only may trigger blacklist) -->
          <run_actions ref="CanShipTriggerBlacklist" result="$triggerCheck">
            <param name="Ship" value="$victim"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          <do_if value="$triggerCheck.$CanTrigger">
          <find_ship name="$enemyShips" space="$currentSector" multiple="true">
            <match_relation_to object="$victim" relation="enemy" comparison="le"/>
          </find_ship>
          
          <run_actions ref="ShouldBlacklistSector" result="$defenseCheck">
            <param name="Sector" value="$currentSector"/>
            <param name="EnemyShips" value="$enemyShips"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          
          <!-- Only blacklist if no defenses and player fighting score is lower -->
          <do_if value="$defenseCheck.$ShouldBlacklist">
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="true"/>
            <!-- Store tracked enemy ships for blacklist tracking -->
            <run_actions ref="StoreTrackedEnemyShips">
              <param name="Sector" value="$currentSector"/>
              <param name="EnemyShips" value="$enemyShips"/>
              <param name="DebugChance" value="100"/>
            </run_actions>
            
            <!-- Immediately update blacklist when threat is detected -->
            <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
          </do_if>
          <do_else>
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="false"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $currentSector.knownname + ' protected by defenses (station: ' + $defenseCheck.$HasDefenseStation + ', player score: ' + $defenseCheck.$PlayerFightingScore + ' vs enemy: ' + $defenseCheck.$EnemyThreatScore + ') - not blacklisting'" chance="100"/>
            </do_if>
          </do_else>
          </do_if>
          <do_else>
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="false"/>
          </do_else>
          
          <!-- Notify ships with destinations in this sector -->
          <signal_cue_instantly cue="NotifyShipsOfThreat" param="$currentSector"/>
        </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- Missile Threat Detection -->
    <cue name="DetectMissileThreats" instantiate="true">
      <conditions>
        <event_object_incoming_missile object="player.galaxy"/>
      </conditions>
      <actions>
        <!-- Only process if threat avoidance is enabled -->
        <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance? or not global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled or (global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <!-- Exit: threat avoidance disabled -->
        </do_if>
        <do_else>
        <set_value name="$target" exact="event.object"/>
        <set_value name="$missile" exact="event.param"/>
        
        <!-- Only process missile threats to GalaxyTrader ships -->
        <do_if value="$target.isplayerowned and global.$GT_Ships.{$target}? and $target.sector? and $missile?">
          <set_value name="$currentSector" exact="$target.sector"/>
          
          <!-- Report missile threat (high level - missiles are serious) -->
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}" exact="table[]"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$Timestamp" exact="player.age"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ThreatLevel" exact="4"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$AttackerType" exact="@$missile.launcher.idcode"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$AttackerFaction" exact="@$missile.launcher.owner.knownname"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ReportingShip" exact="$target.knownname"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ThreatType" exact="'Incoming Missile'"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$TargetShip" exact="$target.knownname"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] MISSILE THREAT: Incoming missile targeting ' + $target.knownname + ' in ' + $currentSector.knownname" chance="100"/>
          </do_if>
          
          <!-- Always notify for missile threats -->
          <show_notification text="'MISSILE ALERT: Hostile missile detected in ' + $currentSector.knownname + ' - Fleet advised extreme caution'" timeout="8s"/>
          
          <!-- Check defenses before blacklisting (combat ships only may trigger blacklist) -->
          <run_actions ref="CanShipTriggerBlacklist" result="$triggerCheck">
            <param name="Ship" value="$target"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          <do_if value="$triggerCheck.$CanTrigger">
          <find_ship name="$enemyShips" space="$currentSector" multiple="true">
            <match_relation_to object="$target" relation="enemy" comparison="le"/>
          </find_ship>
          
          <run_actions ref="ShouldBlacklistSector" result="$defenseCheck">
            <param name="Sector" value="$currentSector"/>
            <param name="EnemyShips" value="$enemyShips"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          
          <!-- Only blacklist if no defenses and player fighting score is lower -->
          <do_if value="$defenseCheck.$ShouldBlacklist">
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="true"/>
            <!-- Store tracked enemy ships for blacklist tracking -->
            <run_actions ref="StoreTrackedEnemyShips">
              <param name="Sector" value="$currentSector"/>
              <param name="EnemyShips" value="$enemyShips"/>
              <param name="DebugChance" value="100"/>
            </run_actions>
            
            <!-- Immediately update blacklist when threat is detected -->
            <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
          </do_if>
          <do_else>
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="false"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $currentSector.knownname + ' protected by defenses (station: ' + $defenseCheck.$HasDefenseStation + ', player score: ' + $defenseCheck.$PlayerFightingScore + ' vs enemy: ' + $defenseCheck.$EnemyThreatScore + ') - not blacklisting'" chance="100"/>
            </do_if>
          </do_else>
          </do_if>
          <do_else>
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="false"/>
          </do_else>
          
          <!-- Notify ships with destinations in this sector -->
          <signal_cue_instantly cue="NotifyShipsOfThreat" param="$currentSector"/>
        </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- Ship Destruction Detection -->
    <cue name="DetectShipDestruction" instantiate="true">
      <conditions>
        <event_object_destroyed object="player.galaxy"/>
      </conditions>
      <actions>
        <!-- Only process if threat avoidance is enabled -->
        <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance? or not global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled or (global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <!-- Exit: threat avoidance disabled -->
        </do_if>
        <do_else>
        <set_value name="$destroyedObject" exact="event.object"/>
        <set_value name="$killer" exact="event.param"/>
        
        <!-- Only process destruction of GalaxyTrader ships.
             IMPORTANT: Don't require $killer? and don't use strict .$sector? existence checks here.
             In some destroy cases, event.param can be null and the object can be in the process of being cleaned up.
             We still want to record the threat and blacklist the sector if appropriate. -->
        <set_value name="$isGTShip" exact="false"/>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.{$destroyedObject}?">
          <set_value name="$isGTShip" exact="true"/>
        </do_if>
        <do_else>
          <!-- Fallback: if ship is still GT-controlled, treat it as GT ship (covers timing/race cleanup).
               NOTE: default order id is the ORDER ID (e.g. 'GalaxyTraderMK3'), not the script name. -->
          <set_value name="$orderId" exact="@$destroyedObject.defaultorder.id"/>
          <do_if value="$orderId? and ((global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{$orderId}) or $orderId == 'order.trade.galaxytrader' or $orderId == 'order.trade.galaxytraderMK2' or $orderId == 'order.trade.galaxytraderMK1' or $orderId == 'order.trade.galaxyminer')">
            <set_value name="$isGTShip" exact="true"/>
          </do_if>
          <do_elseif value="$orderId? and $orderId == 'Assist'">
            <!-- Subordinate: treat as GT ship if commander has GT default order -->
            <set_value name="$commander" exact="@$destroyedObject.commander"/>
            <do_if value="$commander? and @$commander.exists and $commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$commander.defaultorder.id})">
              <set_value name="$isGTShip" exact="true"/>
            </do_if>
          </do_elseif>
        </do_else>

        <set_value name="$currentSector" exact="@$destroyedObject.sector"/>
        <do_if value="$destroyedObject.isplayerowned and $isGTShip and $currentSector?">
          <!-- Ensure threat table exists -->
          <do_if value="not global.$GT_ThreatIntelligence?">
            <set_value name="global.$GT_ThreatIntelligence" exact="table[]"/>
          </do_if>
          
          <!-- Report ship destruction (very high threat level) -->
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}" exact="table[]"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$Timestamp" exact="player.age"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ThreatLevel" exact="5"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$AttackerType" exact="if $killer? then $killer.idcode else 'UNKNOWN'"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$AttackerFaction" exact="if $killer? then @$killer.owner.knownname else 'Unknown'"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ReportingShip" exact="'Fleet Intelligence'"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ThreatType" exact="'Ship Destroyed'"/>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$DestroyedShip" exact="$destroyedObject.knownname"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] ðŸ’€ CRITICAL THREAT: ' + $destroyedObject.knownname + ' destroyed by ' + (if $killer? then @$killer.knownname else 'UNKNOWN') + ' (' + (if $killer? then @$killer.owner.knownname else 'Unknown') + ') in ' + $currentSector.knownname" chance="100"/>
          </do_if>
          
          <!-- Always notify for ship destruction -->
          <show_notification text="'ðŸ’€ FLEET EMERGENCY: Trader ship destroyed in ' + $currentSector.knownname + ' - All ships avoid this sector immediately!'" timeout="15s"/>
          
          <!-- Check if sector should be blacklisted (combat ships only; considering player defenses) -->
          <run_actions ref="CanShipTriggerBlacklist" result="$triggerCheck">
            <param name="Ship" value="$destroyedObject"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          <do_if value="$triggerCheck.$CanTrigger">
          <find_ship name="$enemyShips" space="$currentSector" multiple="true">
            <match_relation_to object="$destroyedObject" relation="enemy" comparison="le"/>
          </find_ship>
          
          <run_actions ref="ShouldBlacklistSector" result="$defenseCheck">
            <param name="Sector" value="$currentSector"/>
            <!-- If we couldn't find enemies (timing), still treat as high threat (ship destroyed). -->
            <param name="EnemyShips" value="$enemyShips"/>
            <param name="EnemyThreatScore" value="5"/>
            <param name="DebugChance" value="100"/>
          </run_actions>
          <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="$defenseCheck.$ShouldBlacklist"/>
          
          <!-- Only blacklist if no defenses and player fighting score is lower -->
          <do_if value="$defenseCheck.$ShouldBlacklist">
            <do_if value="$enemyShips? and $enemyShips != null and $enemyShips.count gt 0">
              <run_actions ref="StoreTrackedEnemyShips">
                <param name="Sector" value="$currentSector"/>
                <param name="EnemyShips" value="$enemyShips"/>
                <param name="DebugChance" value="100"/>
              </run_actions>
            </do_if>
            
            <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $currentSector.knownname + ' protected by defenses (station: ' + $defenseCheck.$HasDefenseStation + ', player score: ' + $defenseCheck.$PlayerFightingScore + ' vs enemy: ' + $defenseCheck.$EnemyThreatScore + ') - not blacklisting despite ship destruction'" chance="100"/>
            </do_if>
          </do_else>
          </do_if>
          <do_else>
            <set_value name="global.$GT_ThreatIntelligence.{$currentSector}.$ShouldBlacklist" exact="false"/>
          </do_else>
          
          <!-- Notify ships with destinations in this sector -->
          <signal_cue_instantly cue="NotifyShipsOfThreat" param="$currentSector"/>
        </do_if>
        <do_else>
          <!-- High-signal debug: destruction happened but was ignored (not player-owned GT ship or sector unavailable) -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <!-- NOTE: Avoid invalid syntax '@...?' by extracting safe values first, then testing against null -->
            <set_value name="$_destroyedName" exact="@$destroyedObject.knownname"/>
            <set_value name="$_destroyedId" exact="@$destroyedObject.idcode"/>
            <set_value name="$_defaultOrderId" exact="@$destroyedObject.defaultorder.id"/>
            <set_value name="$_sectorName" exact="@$currentSector.knownname"/>
            <set_value name="$_destroyedNameSafe" exact="if $_destroyedName != null then $_destroyedName else 'UNKNOWN'"/>
            <set_value name="$_destroyedIdSafe" exact="if $_destroyedId != null then $_destroyedId else 'UNKNOWN'"/>
            <set_value name="$_defaultOrderIdSafe" exact="if $_defaultOrderId != null then $_defaultOrderId else 'NONE'"/>
            <set_value name="$_sectorNameSafe" exact="if $_sectorName != null then $_sectorName else 'NONE'"/>
            <debug_text text="'[GT-Threat] Ship destruction ignored (not GT ship / no sector / not player-owned): destroyed='
              + $_destroyedNameSafe
              + ' id=' + $_destroyedIdSafe
              + ' playerOwned=' + (if $destroyedObject? then $destroyedObject.isplayerowned else 0)
              + ' isGTShip=' + $isGTShip
              + ' defaultOrder=' + $_defaultOrderIdSafe
              + ' sector=' + $_sectorNameSafe" chance="100"/>
          </do_if>
        </do_else>
        </do_else>
      </actions>
    </cue>
    
    <!-- ========================================================================= -->
    <!-- NOTIFY SHIPS OF THREAT                                                    -->
    <!-- Event-driven threat notification for mid-flight response                 -->
    <!-- Level 12+ Requirement: Only experienced pilots can analyze route threats -->
    <!-- ========================================================================= -->
    
    <cue name="NotifyShipsOfThreat" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$threatenedSector" exact="event.param"/>
        <set_value name="$threatData" exact="@global.$GT_ThreatIntelligence.{$threatenedSector}"/>
        
        <do_if value="$threatData?">
          <!-- Check if threat level exceeds threshold -->
          <set_value name="$threatLevel" exact="$threatData.$ThreatLevel"/>
          <set_value name="$threatThreshold" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold"/>
          <do_if value="not $threatThreshold?">
            <set_value name="$threatThreshold" exact="3"/>
          </do_if>
          
          <do_if value="$threatLevel ge $threatThreshold">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector threatened: ' + $threatenedSector.knownname + ' (Level ' + $threatLevel + ') - checking ship destinations...'" chance="100"/>
            </do_if>
        
        <!-- Find affected ships (those with destinations in threatened sector) -->
        <!-- Cooperative multitasking: process ships in batches to prevent frame stutter -->
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <!-- Snapshot ship keys and store batch state -->
          <do_if value="not global.$GT_ThreatNotifyState?">
            <set_value name="global.$GT_ThreatNotifyState" exact="table[]"/>
          </do_if>
          <set_value name="global.$GT_ThreatNotifyState.{$threatenedSector}" exact="table[
            $Sector = $threatenedSector,
            $ThreatData = $threatData,
            $ThreatLevel = $threatLevel,
            $ShipKeys = global.$GT_Ships.keys.list,
            $Index = 1,
            $BatchSize = 10,
            $ShipsNotified = 0
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Threat] Starting batched notification for ' + global.$GT_Ships.keys.count + ' ships (sector: ' + $threatenedSector.knownname + ', level: ' + $threatLevel + ')'" chance="100"/>
          </do_if>
          <signal_cue_instantly cue="md.GT_ThreatIntelligence.NotifyShipsOfThreat_Batch" param="$threatenedSector"/>
        </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- ========================================================================= -->
    <!-- BATCHED NOTIFICATION PROCESSING                                           -->
    <!-- Processes ship threat notifications in batches for cooperative multitasking -->
    <!-- ========================================================================= -->
    
    <cue name="NotifyShipsOfThreat_Batch" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <set_value name="$sector" exact="event.param"/>
        
        <!-- Validate batch state exists -->
        <do_if value="not global.$GT_ThreatNotifyState? or not global.$GT_ThreatNotifyState.{$sector}?">
          <!-- Batch state missing - nothing to process -->
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
          <set_value name="$state" exact="global.$GT_ThreatNotifyState.{$sector}"/>
          <set_value name="$shipKeys" exact="$state.$ShipKeys"/>
          <set_value name="$threatData" exact="$state.$ThreatData"/>
          <set_value name="$threatLevel" exact="$state.$ThreatLevel"/>
          <set_value name="$threatenedSector" exact="$state.$Sector"/>
          <set_value name="$batchStart" exact="$state.$Index"/>
          <set_value name="$batchEnd" exact="[$batchStart + $state.$BatchSize - 1, $shipKeys.count].min"/>
          <set_value name="$batchNotified" exact="0"/>
          
          <!-- Process batch of ships -->
          <do_all exact="$batchEnd - $batchStart + 1" counter="$offset">
            <set_value name="$idx" exact="$batchStart + $offset - 1"/>
            <set_value name="$ship" exact="$shipKeys.{$idx}"/>
            
            <!-- Validate ship exists and is operational -->
            <do_if value="@$ship.exists and @$ship.isoperational">
              <!-- Check pilot level - only Level 12+ can analyze route threats mid-trade -->
              <set_value name="$pilot" exact="@$ship.pilot"/>
              <set_value name="$pilotLevel" exact="0"/>
              <do_if value="$pilot? and global.$GT_Pilots.{$pilot}?">
                <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{$pilot}.$Level"/>
              </do_if>
              
              <!-- Only Level 12+ pilots have tactical awareness for mid-trade route analysis -->
              <do_if value="$pilotLevel ge 12">
                <set_value name="$shipHasDestination" exact="false"/>
                <set_value name="$destinationSector" exact="null"/>
                
                <!-- Check if ship has pending trades where preferred route goes through threatened sector -->
                <!-- Strategy: Compare normal gatedistance vs blacklist-aware gatedistance -->
                <!-- If blacklist distance > normal distance, preferred path goes through threat! -->
                <set_value name="$buyStation" exact="null"/>
                <set_value name="$sellStation" exact="null"/>

                <do_if value="global.$GT_TradesAwaitingValidation.{$ship}?">
                  <set_value name="$tradeList" exact="@global.$GT_TradesAwaitingValidation.{$ship}"/>
                  <do_if value="$tradeList == null">
                    <set_value name="$tradeList" exact="[]"/>
                  </do_if>
                  <do_if value="$tradeList.count gt 0">
                    <set_value name="$trade" exact="$tradeList.{1}"/>
                    <set_value name="$buyStation" exact="@$trade.$BuyOffer.owner"/>
                    <set_value name="$sellStation" exact="@$trade.$SellOffer.owner"/>
                  </do_if>
                </do_if>

                <do_if value="($buyStation == null or $sellStation == null) and global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{$ship}?">
                  <do_if value="global.$GT_ActiveTrade.{$ship}.$BuyStation? and global.$GT_ActiveTrade.{$ship}.$SellStation?">
                    <set_value name="$buyStation" exact="global.$GT_ActiveTrade.{$ship}.$BuyStation"/>
                    <set_value name="$sellStation" exact="global.$GT_ActiveTrade.{$ship}.$SellStation"/>
                  </do_if>
                </do_if>

                <do_if value="$buyStation != null or $sellStation != null">
                  <!-- Check route to buy station (if different sector) -->
                  <do_if value="$buyStation != null and @$buyStation.sector != null and @$ship.sector != null and @$ship.sector != @$buyStation.sector">
                    <set_value name="$buySector" exact="@$buyStation.sector"/>
                    <do_if value="$buySector?">
                      <set_value name="$normalDistanceToBuy" exact="$ship.gatedistance.{$buySector}"/>
                      <set_value name="$blacklistDistanceToBuy" exact="$ship.gatedistance.{$buySector}.{blacklistgroup.civilian}.{$ship}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$normalDistanceToBuy" exact="-1"/>
                      <set_value name="$blacklistDistanceToBuy" exact="-1"/>
                    </do_else>
                    
                    <do_if value="($normalDistanceToBuy ge 0) and ($blacklistDistanceToBuy gt $normalDistanceToBuy or $blacklistDistanceToBuy lt 0)">
                      <set_value name="$shipHasDestination" exact="true"/>
                      <set_value name="$destinationSector" exact="@$buyStation.sector"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-Threat] Ship %s route to buy station %s threatened (normal: %s jumps, blacklist-aware: %s jumps)'.[$ship.knownname, @$buyStation.knownname, $normalDistanceToBuy, $blacklistDistanceToBuy]" chance="100"/>
                      </do_if>
                    </do_if>
                  </do_if>
                  
                  <!-- Also check route to sell station (if different sector and not already threatened) -->
                  <do_if value="not $shipHasDestination and $sellStation != null and @$sellStation.sector != null and @$ship.sector != null and @$ship.sector != @$sellStation.sector">
                    <set_value name="$sellSector" exact="@$sellStation.sector"/>
                    <do_if value="$sellSector?">
                      <set_value name="$normalDistanceToSell" exact="$ship.gatedistance.{$sellSector}"/>
                      <set_value name="$blacklistDistanceToSell" exact="$ship.gatedistance.{$sellSector}.{blacklistgroup.civilian}.{$ship}"/>
                    </do_if>
                    <do_else>
                      <set_value name="$normalDistanceToSell" exact="-1"/>
                      <set_value name="$blacklistDistanceToSell" exact="-1"/>
                    </do_else>
                    
                    <do_if value="($normalDistanceToSell ge 0) and ($blacklistDistanceToSell gt $normalDistanceToSell or $blacklistDistanceToSell lt 0)">
                      <set_value name="$shipHasDestination" exact="true"/>
                      <set_value name="$destinationSector" exact="@$sellStation.sector"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-Threat] Ship %s route to sell station %s threatened (normal: %s jumps, blacklist-aware: %s jumps)'.[$ship.knownname, @$sellStation.knownname, $normalDistanceToSell, $blacklistDistanceToSell]" chance="100"/>
                      </do_if>
                    </do_if>
                  </do_if>
                </do_if>
                
                <!-- If ship has threatened sector in travel path, signal it -->
                <do_if value="$shipHasDestination">
                  <signal_objects object="$ship" param="'GT_Destination_Threatened'" param2="table[
                    $Sector = $threatenedSector,
                    $ThreatLevel = $threatLevel,
                    $ThreatType = $threatData.$ThreatType,
                    $AttackerFaction = @$threatData.$AttackerFaction
                  ]" delay="1ms"/>
                  
                  <set_value name="$batchNotified" operation="add"/>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Threat]   Signaled ' + $ship.idcode + ' (Pilot Lv.' + $pilotLevel + '): Threatened sector in travel path - aborting trade!'" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <!-- Lower level pilots lack tactical awareness for mid-trade route analysis -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Threat]   ' + $ship.idcode + ' (Pilot Lv.' + $pilotLevel + ') has threatened sector in route but lacks experience for mid-trade threat analysis (requires Lv.12+)'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
          </do_all>
          
          <!-- Update batch state: accumulate notified count and advance index -->
          <set_value name="global.$GT_ThreatNotifyState.{$sector}.$ShipsNotified" exact="global.$GT_ThreatNotifyState.{$sector}.$ShipsNotified + $batchNotified"/>
          <set_value name="global.$GT_ThreatNotifyState.{$sector}.$Index" exact="$batchEnd + 1"/>
          
          <!-- Check if more batches needed -->
          <do_if value="$batchEnd lt $shipKeys.count">
            <!-- More ships to process - signal next batch -->
            <signal_cue_instantly cue="md.GT_ThreatIntelligence.NotifyShipsOfThreat_Batch" param="$sector"/>
          </do_if>
          <do_else>
            <!-- All ships processed - log summary and clean up state -->
            <set_value name="$totalNotified" exact="global.$GT_ThreatNotifyState.{$sector}.$ShipsNotified"/>
            <do_if value="$totalNotified gt 0">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] Notified ' + $totalNotified + ' ships about threat in ' + $threatenedSector.knownname" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] No ships affected by threat in ' + $threatenedSector.knownname" chance="100"/>
              </do_if>
            </do_else>
            <!-- Cleanup batch state -->
            <remove_value name="global.$GT_ThreatNotifyState.{$sector}"/>
          </do_else>
        </do_else>
      </actions>
    </cue>
    
    <!-- Threat Database Cleanup - Remove old threats every 10 minutes -->
    <cue name="CleanupOldThreats">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="600s"/> <!-- 10 minutes -->
      <actions>
        <do_if value="global.$GT_ThreatIntelligence?">
          <set_value name="$currentTime" exact="player.age"/>
          <set_value name="$threatsRemoved" exact="0"/>
          
          <!-- Remove threats older than 1 hour -->
          <do_all exact="global.$GT_ThreatIntelligence.keys.count" counter="$i" reverse="true">
            <set_value name="$sector" exact="global.$GT_ThreatIntelligence.keys.list.{$i}"/>
            <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$sector}"/>
            
            <do_if value="$threatData.$Timestamp?">
              <set_value name="$age" exact="$currentTime - $threatData.$Timestamp"/>
              
              <!-- Remove threats older than 1 hour -->
              <do_if value="$age gt 3600s">
                <remove_value name="global.$GT_ThreatIntelligence.{$sector}"/>
                <set_value name="$threatsRemoved" exact="$threatsRemoved + 1"/>
              </do_if>
            </do_if>
          </do_all>
          
          <do_if value="$threatsRemoved gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Threat Intelligence cleanup: Removed ' + $threatsRemoved + ' old threat reports'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Signal self to repeat -->
        <signal_cue cue="CleanupOldThreats"/>
      </actions>
    </cue>
    
    <!-- Fleet Threat Status Reporter - Every 5 minutes, report fleet threat statistics -->
    <cue name="FleetThreatReporter">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="300s"/> <!-- 5 minutes -->
      <actions>
        <do_if value="global.$GT_Ships? and global.$GT_ThreatIntelligence?">
          <set_value name="$activeThreatSectors" exact="0"/>
          <set_value name="$highThreatSectors" exact="0"/>
          <set_value name="$currentTime" exact="player.age"/>
          
          <!-- Count active threat sectors -->
          <do_all exact="global.$GT_ThreatIntelligence.keys.count" counter="$i">
            <set_value name="$sector" exact="global.$GT_ThreatIntelligence.keys.list.{$i}"/>
            <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$sector}"/>
            
            <do_if value="$threatData.$Timestamp?">
              <set_value name="$age" exact="$currentTime - $threatData.$Timestamp"/>
              
              <!-- Only count recent threats (within last 30 minutes) -->
              <do_if value="$age le 1800s">
                <set_value name="$activeThreatSectors" exact="$activeThreatSectors + 1"/>
                
                <do_if value="$threatData.$ThreatLevel ge 3">
                  <set_value name="$highThreatSectors" exact="$highThreatSectors + 1"/>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
          
          <!-- Report significant threat activity -->
          <do_if value="$highThreatSectors gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Fleet Intelligence Report: ' + $highThreatSectors + ' high-threat sectors, ' + $activeThreatSectors + ' total active threats'" chance="100"/>
            </do_if>
            
            <do_if value="$highThreatSectors ge 3">
              <show_notification text="' FLEET WARNING: Multiple high-threat sectors detected (' + $highThreatSectors + ') - Exercise extreme caution'" timeout="8s"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Signal self to repeat -->
        <signal_cue cue="FleetThreatReporter"/>
      </actions>
    </cue>
    
    <!-- 
    ============================================================================
    REAL-TIME THREAT DETECTION (True Vanilla Event-Driven System)
    ============================================================================
    
    REMOVED: All polling-based scans (CPU waste, unnecessary)
    
    VANILLA APPROACH:
    - Threat detection integrated into trade movement via activepatrol=true
    - Uses vanilla's move.seekenemies (event-driven, zero CPU when stationary)
    - Detection occurs naturally as ships travel to buy/sell stations
    - Skill-based reporting: Only Level 6+ pilots broadcast fleet warnings
    
    HOW IT WORKS:
    1. Ship starts trade execution Movement uses activepatrol=true
    2. Vanilla system detects enemies during movement (real-time)
    3. on_enemy_detected event fires Ship checks pilot level
    4. Level 6+ Broadcasts GT_Threat_Warning to fleet
    5. Level 1-5 Detects but stays quiet (inexperienced)
    
    BENEFITS:
    - Zero polling overhead (event-driven only)
    - Truly vanilla-compatible (uses same system as Guard/Patrol orders)
    - Detection only when ships are actually moving/trading
    - Skill progression mechanic maintained
    
    GAME BALANCE:
    - Early game (Lv1-5): Ships avoid threats individually, no fleet coordination
    - Mid-game (Lv6+): Fleet intelligence emerges, experienced pilots help rookies
    ============================================================================
    -->
    
    <!-- Event-Driven Threat Detection: Ships Attacked -->
    <cue name="ShipUnderAttack" instantiate="true">
      <conditions>
        <event_object_attacked object="player.galaxy"/>
        <check_value value="event.object.isplayerowned and global.$GT_Ships.{event.object}?"/> <!-- Is this a GT ship? -->
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        <set_value name="$attacker" exact="event.param"/>
        
        <!-- Check if attacker is hostile -->
        <do_if value="$attacker.exists and $ship.mayattack.{$attacker}">
          <!-- Get pilot skill level -->
          <set_value name="$pilotLevel" exact="1"/>
          <do_if value="$ship.pilot? and global.$GT_Pilots.{$ship.pilot}?">
            <set_value name="$pilotLevel" exact="@global.$GT_Pilots.{$ship.pilot}.$Level"/>
          </do_if>
          
          <!-- Find all nearby hostiles (within radar range) -->
          <find_ship name="$nearbyHostiles" space="$ship.sector" multiple="true">
            <match_distance object="$ship" max="$ship.maxradarrange"/>
            <match_relation_to object="$ship" relation="enemy" comparison="le"/>
          </find_ship>
          
          <!-- Calculate threat with detailed ship class & faction analysis -->
          <set_value name="$threatScore" exact="0"/>
          <set_value name="$shipClass_XL" exact="0"/>
          <set_value name="$shipClass_L" exact="0"/>
          <set_value name="$shipClass_M" exact="0"/>
          <set_value name="$shipClass_S" exact="0"/>
          <set_value name="$factionCounts" exact="table[]"/> <!-- Track faction counts -->
          
          <do_all exact="$nearbyHostiles.count" counter="$h">
            <set_value name="$hostile" exact="$nearbyHostiles.{$h}"/>
            
            <!-- Count by ship class -->
            <do_if value="$hostile.isclass.ship_xl">
              <set_value name="$threatScore" exact="$threatScore + 5"/>
              <set_value name="$shipClass_XL" operation="add"/>
            </do_if>
            <do_elseif value="$hostile.isclass.ship_l">
              <set_value name="$threatScore" exact="$threatScore + 3"/>
              <set_value name="$shipClass_L" operation="add"/>
            </do_elseif>
            <do_elseif value="$hostile.isclass.ship_m">
              <set_value name="$threatScore" exact="$threatScore + 2"/>
              <set_value name="$shipClass_M" operation="add"/>
            </do_elseif>
            <do_else>
              <set_value name="$threatScore" exact="$threatScore + 1"/>
              <set_value name="$shipClass_S" operation="add"/>
            </do_else>
            
            <!-- Track faction counts -->
            <do_if value="$hostile.owner?">
              <set_value name="$faction" exact="$hostile.owner"/>
              <set_value name="$factionCounts.{$faction}" exact="@$factionCounts.{$faction} + 1"/>
            </do_if>
          </do_all>
          
          <!-- Find dominant faction (most ships) -->
          <set_value name="$primaryFaction" exact="null"/>
          <set_value name="$maxCount" exact="0"/>
          <do_all exact="$factionCounts.keys.count" counter="$f">
            <set_value name="$faction" exact="$factionCounts.keys.{$f}"/>
            <do_if value="$factionCounts.{$faction} gt $maxCount">
              <set_value name="$primaryFaction" exact="$faction"/>
              <set_value name="$maxCount" exact="$factionCounts.{$faction}"/>
            </do_if>
          </do_all>
          
          <!-- Build ship class summary string -->
          <set_value name="$classBreakdown" exact="''"/>
          <do_if value="$shipClass_XL gt 0">
            <set_value name="$classBreakdown" exact="$classBreakdown + $shipClass_XL + 'XL '"/>
          </do_if>
          <do_if value="$shipClass_L gt 0">
            <set_value name="$classBreakdown" exact="$classBreakdown + $shipClass_L + 'L '"/>
          </do_if>
          <do_if value="$shipClass_M gt 0">
            <set_value name="$classBreakdown" exact="$classBreakdown + $shipClass_M + 'M '"/>
          </do_if>
          <do_if value="$shipClass_S gt 0">
            <set_value name="$classBreakdown" exact="$classBreakdown + $shipClass_S + 'S'"/>
          </do_if>
          
          <!-- Only Level 6+ pilots broadcast to fleet -->
          <do_if value="$pilotLevel ge 6">
            <signal_objects object="player.galaxy" param="'GT_Threat_Warning'" param2="table[
              $Sector = $ship.sector,
              $DetectedBy = $ship,
              $HostileCount = $nearbyHostiles.count,
              $PrimaryFaction = $primaryFaction,
              $ShipClass_XL = $shipClass_XL,
              $ShipClass_L = $shipClass_L,
              $ShipClass_M = $shipClass_M,
              $ShipClass_S = $shipClass_S,
              $ThreatScore = $threatScore,
              $Timestamp = player.age
            ]"/>
            
            <set_value name="$factionName" exact="if $primaryFaction then $primaryFaction.knownname else 'Unknown'"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] ' + $ship.knownname + ' (Pilot Lv.' + $pilotLevel + ') UNDER ATTACK by ' + $attacker.knownname + '\n  âš” Hostiles: ' + $nearbyHostiles.count + ' (' + $classBreakdown + ') - Threat: ' + $threatScore + '\n  ðŸ´ Primary Faction: ' + $factionName + ' - FLEET WARNING BROADCAST'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] ' + $ship.knownname + ' (Pilot Lv.' + $pilotLevel + ') under attack by ' + $attacker.knownname + ' but lacks experience to report to fleet (requires Lv.6+)'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Fleet Threat Warning Receiver -->
    <cue name="ReceiveThreatWarning" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Threat_Warning'"/>
      </conditions>
      <actions>
        <!-- Only process if threat avoidance is enabled -->
        <do_if value="not global.$GT_GlobalSettings.$ThreatAvoidance? or not global.$GT_GlobalSettings.$ThreatAvoidance.$Enabled or (global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly)">
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
        <set_value name="$warning" exact="event.param2"/>
        <set_value name="$sector" exact="$warning.$Sector"/>
        <set_value name="$detectedBy" exact="$warning.$DetectedBy"/>
        <set_value name="$hostileCount" exact="$warning.$HostileCount"/>
        <set_value name="$threatScore" exact="$warning.$ThreatScore"/>
        <set_value name="$primaryFaction" exact="$warning.$PrimaryFaction"/>
        <set_value name="$shipClass_XL" exact="$warning.$ShipClass_XL"/>
        <set_value name="$shipClass_L" exact="$warning.$ShipClass_L"/>
        <set_value name="$shipClass_M" exact="$warning.$ShipClass_M"/>
        <set_value name="$shipClass_S" exact="$warning.$ShipClass_S"/>
        <set_value name="$capitalShips" exact="$shipClass_XL + $shipClass_L"/>
        
        <!-- Ensure table exists before accessing (handles race condition) -->
        <do_if value="not global.$GT_ThreatIntelligence?">
          <set_value name="global.$GT_ThreatIntelligence" exact="table[]"/>
        </do_if>
        
        <!-- Update threat intelligence database -->
        <do_if value="not global.$GT_ThreatIntelligence.{$sector}?">
          <set_value name="global.$GT_ThreatIntelligence.{$sector}" exact="table[]"/>
        </do_if>
        
        <!-- Only log "Sector Blacklisted" once per sector threat episode (not on every repeat warning) -->
        <set_value name="$wasAlreadyBlacklisted" exact="false"/>
        <do_if value="@global.$GT_ThreatIntelligence.{$sector}.$ShouldBlacklist">
          <set_value name="$wasAlreadyBlacklisted" exact="true"/>
        </do_if>
        
        <!-- Calculate threat level (1-5) -->
        <set_value name="$threatLevel" exact="2"/> <!-- Base: hostiles present -->
        <do_if value="$capitalShips gt 0">
          <set_value name="$threatLevel" exact="4"/> <!-- High: capital ships -->
        </do_if>
        <do_elseif value="$threatScore ge 6">
          <set_value name="$threatLevel" exact="3"/> <!-- Medium-High: multiple hostiles -->
        </do_elseif>
        
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ThreatLevel" exact="$threatLevel"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$HostileCount" exact="$hostileCount"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ThreatScore" exact="$threatScore"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$Timestamp" exact="player.age"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$DetectedBy" exact="$detectedBy.knownname"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ThreatType" exact="'Real-Time Detection'"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$PrimaryFaction" exact="if $primaryFaction then $primaryFaction.knownname else 'Unknown'"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ShipClass_XL" exact="$shipClass_XL"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ShipClass_L" exact="$shipClass_L"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ShipClass_M" exact="$shipClass_M"/>
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ShipClass_S" exact="$shipClass_S"/>
        
        <!-- Blacklist only when reported by a combat ship (purpose.fight) -->
        <run_actions ref="CanShipTriggerBlacklist" result="$triggerCheck">
          <param name="Ship" value="$detectedBy"/>
          <param name="DebugChance" value="100"/>
        </run_actions>
        
        <do_if value="$triggerCheck.$CanTrigger">
        <!-- Check if sector should be blacklisted (considering player defenses) -->
        <run_actions ref="ShouldBlacklistSector" result="$defenseCheck">
          <param name="Sector" value="$sector"/>
          <param name="EnemyThreatScore" value="$threatScore"/>
          <param name="DebugChance" value="100"/>
        </run_actions>
        
        <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ShouldBlacklist" exact="$defenseCheck.$ShouldBlacklist"/>
        
        <!-- Only update blacklist if defenses don't protect the sector -->
        <do_if value="$defenseCheck.$ShouldBlacklist">
          <!-- Store tracked enemy ships (radar range only - no cheating) -->
          <!-- Check if any GT ship is in sector to scan for enemies -->
          <set_value name="$gtShipInSector" exact="null"/>
          <do_if value="global.$GT_Ships?">
            <do_all exact="global.$GT_Ships.keys.count" counter="$i">
              <set_value name="$gtShip" exact="global.$GT_Ships.keys.list.{$i}"/>
              <do_if value="@$gtShip.exists and @$gtShip.isoperational and $gtShip.sector? and $gtShip.sector == $sector">
                <set_value name="$gtShipInSector" exact="$gtShip"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- If GT ship in sector, scan for enemies within radar range -->
          <do_if value="$gtShipInSector? and $gtShipInSector != null">
            <find_ship name="$enemyShips" space="$sector" multiple="true">
              <match_distance object="$gtShipInSector" max="$gtShipInSector.maxradarrange"/>
              <match_relation_to object="$gtShipInSector" relation="enemy" comparison="le"/>
            </find_ship>
            
            <!-- Debug: Log how many enemy ships were found -->
            <set_value name="$enemyShipCount" exact="if $enemyShips != null then @$enemyShips.count else 0"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Found ' + $enemyShipCount + ' enemy ships in radar range for tracking in sector ' + $sector.knownname" chance="100"/>
            </do_if>
            
            <!-- Store tracked ships -->
            <run_actions ref="StoreTrackedEnemyShips">
              <param name="Sector" value="$sector"/>
              <param name="EnemyShips" value="$enemyShips"/>
              <param name="DebugChance" value="100"/>
            </run_actions>
            
            <!-- Logbook only when sector is newly added to the blacklist (skip repeat warnings) -->
            <do_if value="not $wasAlreadyBlacklisted">
            <!-- Create logbook message with enemy ship IDs sorted by size -->
            <!-- Get tracked enemy ships -->
            <set_value name="$trackedShips" exact="@global.$GT_ThreatIntelligence.{$sector}.$TrackedEnemyShips"/>
            <do_if value="(if $trackedShips != null then $trackedShips.count else 0) gt 0">
              <!-- Sort ships by size (XL, L, M, S) -->
              <set_value name="$shipsXL" exact="[]"/>
              <set_value name="$shipsL" exact="[]"/>
              <set_value name="$shipsM" exact="[]"/>
              <set_value name="$shipsS" exact="[]"/>
              
              <do_all exact="$trackedShips.count" counter="$i">
                <set_value name="$enemyShip" exact="$trackedShips.{$i}"/>
                <do_if value="@$enemyShip.exists">
                  <set_value name="$shipID" exact="$enemyShip.idcode"/>
                  <set_value name="$shipName" exact="@$enemyShip.knownname"/>
                  <set_value name="$shipEntry" exact="(if $shipName? and $shipName != null then $shipName + ' ' else '') + $shipID"/>
                  <do_if value="$enemyShip.isclass.ship_xl">
                    <append_to_list name="$shipsXL" exact="$shipEntry"/>
                  </do_if>
                  <do_elseif value="$enemyShip.isclass.ship_l">
                    <append_to_list name="$shipsL" exact="$shipEntry"/>
                  </do_elseif>
                  <do_elseif value="$enemyShip.isclass.ship_m">
                    <append_to_list name="$shipsM" exact="$shipEntry"/>
                  </do_elseif>
                  <do_else>
                    <append_to_list name="$shipsS" exact="$shipEntry"/>
                  </do_else>
                </do_if>
              </do_all>
              
              <!-- Build ship ID string grouped by class (XL, L, M, S) -->
              <set_value name="$shipIDString" exact="''"/>
              
              <!-- XL Ships -->
              <do_if value="$shipsXL.count gt 0">
                <set_value name="$xlString" exact="'XL: '"/>
                <do_all exact="$shipsXL.count" counter="$i">
                  <do_if value="$i == 0">
                    <set_value name="$xlString" exact="$xlString + $shipsXL.{$i}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$xlString" exact="$xlString + ',' + $shipsXL.{$i}"/>
                  </do_else>
                </do_all>
                <set_value name="$shipIDString" exact="$xlString"/>
              </do_if>
              
              <!-- L Ships -->
              <do_if value="$shipsL.count gt 0">
                <set_value name="$lString" exact="'L: '"/>
                <do_all exact="$shipsL.count" counter="$i">
                  <do_if value="$i == 0">
                    <set_value name="$lString" exact="$lString + $shipsL.{$i}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$lString" exact="$lString + ',' + $shipsL.{$i}"/>
                  </do_else>
                </do_all>
                <do_if value="$shipIDString == ''">
                  <set_value name="$shipIDString" exact="$lString"/>
                </do_if>
                <do_else>
                  <set_value name="$shipIDString" exact="$shipIDString + '\n' + $lString"/>
                </do_else>
              </do_if>
              
              <!-- M Ships -->
              <do_if value="$shipsM.count gt 0">
                <set_value name="$mString" exact="'M: '"/>
                <do_all exact="$shipsM.count" counter="$i">
                  <do_if value="$i == 0">
                    <set_value name="$mString" exact="$mString + $shipsM.{$i}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$mString" exact="$mString + ',' + $shipsM.{$i}"/>
                  </do_else>
                </do_all>
                <do_if value="$shipIDString == ''">
                  <set_value name="$shipIDString" exact="$mString"/>
                </do_if>
                <do_else>
                  <set_value name="$shipIDString" exact="$shipIDString + '\n' + $mString"/>
                </do_else>
              </do_if>
              
              <!-- S Ships -->
              <do_if value="$shipsS.count gt 0">
                <set_value name="$sString" exact="'S: '"/>
                <do_all exact="$shipsS.count" counter="$i">
                  <do_if value="$i == 0">
                    <set_value name="$sString" exact="$sString + $shipsS.{$i}"/>
                  </do_if>
                  <do_else>
                    <set_value name="$sString" exact="$sString + ',' + $shipsS.{$i}"/>
                  </do_else>
                </do_all>
                <do_if value="$shipIDString == ''">
                  <set_value name="$shipIDString" exact="$sString"/>
                </do_if>
                <do_else>
                  <set_value name="$shipIDString" exact="$shipIDString + '\n' + $sString"/>
                </do_else>
              </do_if>
              
              <!-- Create logbook message with sector name, grouped ship IDs, and detecting ship ID -->
              <!-- Use dedicated TextDB entry {77000,3222} for sector blacklisting (3 parameters: sector, ship list, detecting ship) -->
              <set_value name="$detectingShipID" exact="if $detectedBy? and $detectedBy.exists then ($detectedBy.knownname + ' (' + $detectedBy.idcode + ')') else 'Unknown Ship'"/>
              <set_value name="$logbookMessage" exact="{77000,3222}.[$sector.knownname, $shipIDString, $detectingShipID]"/>
              
              <!-- Use logbook library via signal -->
              <signal_objects object="player.galaxy" param="'GT_WriteLogbook'" param2="table[
                $Message = $logbookMessage,
                $Category = 'alerts',
                $Title = 'Sector Blacklisted: ' + $sector.knownname,
                $Object = $sector,
                $Interaction = 'showonmap',
                $Highlighted = true,
                $CheckGlobalSettings = false
              ]"/>
              <set_value name="$totalShipCount" exact="$shipsXL.count + $shipsL.count + $shipsM.count + $shipsS.count"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] Logbook message created for blacklisted sector ' + $sector.knownname + ' with ' + $totalShipCount + ' enemy ships (detected by ' + $detectingShipID + '):\n' + $shipIDString" chance="100"/>
              </do_if>
            </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] Skipped duplicate Sector Blacklisted logbook for ' + $sector.knownname + ' (already blacklisted)'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] No GT ship in sector ' + $sector.knownname + ' - scanning sector-wide for enemy ships to track'" chance="100"/>
            </do_if>
            <find_ship name="$enemyShips" space="$sector" multiple="true">
              <match_relation_to object="player.entity" relation="enemy" comparison="le"/>
            </find_ship>
            <run_actions ref="StoreTrackedEnemyShips">
              <param name="Sector" value="$sector"/>
              <param name="EnemyShips" value="$enemyShips"/>
              <param name="DebugChance" value="100"/>
            </run_actions>
          </do_else>
          
          <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
        </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Threat] Sector ' + $sector.knownname + ' protected by defenses (station: ' + $defenseCheck.$HasDefenseStation + ', player score: ' + $defenseCheck.$PlayerFightingScore + ' vs enemy: ' + $defenseCheck.$EnemyThreatScore + ') - threat tracked but not blacklisted'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <set_value name="global.$GT_ThreatIntelligence.{$sector}.$ShouldBlacklist" exact="false"/>
        </do_else>
        
        <!-- Build ship class breakdown for display -->
        <set_value name="$classBreakdown" exact="''"/>
        <do_if value="$shipClass_XL gt 0">
          <set_value name="$classBreakdown" exact="$classBreakdown + $shipClass_XL + ' XL'"/>
        </do_if>
        <do_if value="$shipClass_L gt 0">
          <set_value name="$classBreakdown" exact="$classBreakdown + (if $classBreakdown != '' then ', ' else '') + $shipClass_L + ' L'"/>
        </do_if>
        <do_if value="$shipClass_M gt 0">
          <set_value name="$classBreakdown" exact="$classBreakdown + (if $classBreakdown != '' then ', ' else '') + $shipClass_M + ' M'"/>
        </do_if>
        <do_if value="$shipClass_S gt 0">
          <set_value name="$classBreakdown" exact="$classBreakdown + (if $classBreakdown != '' then ', ' else '') + $shipClass_S + ' S'"/>
        </do_if>
        
        <!-- Log to player if significant threat (capital ships or high threat) -->
        <do_if value="$capitalShips gt 0 or $threatLevel ge 3">
          <set_value name="$threatDesc" exact="if $threatLevel == 5 then 'CRITICAL' else if $threatLevel == 4 then 'HIGH' else 'MEDIUM'"/>
          <set_value name="$factionName" exact="if $primaryFaction then $primaryFaction.knownname else 'Unknown'"/>
          
          <set_value name="$logMessage" exact="'FLEET THREAT ALERT\n\n'"/>
          <set_value name="$logMessage" exact="$logMessage + $detectedBy.knownname + ' encountered hostile forces in ' + $sector.knownname + '\n\n'"/>
          <set_value name="$logMessage" exact="$logMessage + 'Threat Level: ' + $threatDesc + ' (' + $threatLevel + '/5)\n'"/>
          <set_value name="$logMessage" exact="$logMessage + 'Hostile Faction: ' + $factionName + '\n'"/>
          <set_value name="$logMessage" exact="$logMessage + 'Hostile Ships: ' + $hostileCount + ' (' + $classBreakdown + ')\n'"/>
          <set_value name="$logMessage" exact="$logMessage + '\nAll trading ships are advised to avoid this sector until the threat clears.'"/>
          
          <!-- Write logbook using centralized library -->
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$logMessage"/>
            <param name="Category" value="'alerts'"/>
            <param name="Title" value="'Fleet Alert: ' + $factionName + ' Hostiles in ' + $sector.knownname"/>
            <param name="Object" value="player.entity"/>
          </run_actions>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Threat] Fleet warning received: ' + $hostileCount + ' hostile(s) in ' + $sector.knownname + ' (' + $classBreakdown + ') - Faction: ' + (if $primaryFaction then $primaryFaction.knownname else 'Unknown') + ' - Level ' + $threatLevel + ', detected by ' + $detectedBy.knownname" chance="100"/>
        </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- ========================================================================= -->
    <!-- DYNAMIC BLACKLIST INTEGRATION                                            -->
    <!-- ========================================================================= -->
    
    <!-- Shared bootstrap: raise Lua Initialize, push threat payload, optional fleet assign.
         Called on session start (game_loaded / new game) AND on Lua Ready (UI loads before MD on menu). -->
    <library name="BootstrapBlacklistLuaIntegration" purpose="run_actions">
      <params>
        <param name="Reason" default="'unknown'"/>
        <param name="ApplyToFleet" default="true"/>
      </params>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] BootstrapBlacklistLuaIntegration reason=' + $Reason + ' applyToFleet=' + $ApplyToFleet" chance="100"/>
        </do_if>
        
        <!-- Pass relation threshold AND existing blacklist ID (if any) to Lua -->
        <set_value name="$blockEnemyFactions" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions"/>
        <do_if value="not $blockEnemyFactions?">
          <set_value name="$blockEnemyFactions" exact="true"/>
        </do_if>
        
        <set_value name="$relationValue" exact="''"/>
        <do_if value="$blockEnemyFactions">
          <set_value name="$relationValue" exact="'enemy'"/>
        </do_if>
        
        <set_value name="$existingBlacklistID" exact="@global.$GT_BlacklistID"/>
        <do_if value="not $existingBlacklistID?">
          <set_value name="$existingBlacklistID" exact="0"/>
        </do_if>
        
        <set_value name="$blacklistThreshold" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold"/>
        <do_if value="not $blacklistThreshold?">
          <set_value name="$blacklistThreshold" exact="3"/>
        </do_if>
        
        <set_value name="$initData" exact="$relationValue + '|' + $existingBlacklistID + '|' + $blacklistThreshold"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] Passing to Lua: &quot;' + $initData + '&quot; (reason=' + $Reason + ')'" chance="100"/>
        </do_if>
        <raise_lua_event name="'GT_Blacklist.Initialize'" param="$initData"/>
        
        <!-- Load existing threats into blacklist immediately after creation -->
        <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
        
        <do_if value="$ApplyToFleet and @global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist">
          <set_value name="global.$GT_ManualBlacklistAssignRequested" exact="true"/>
          <signal_cue_instantly cue="ApplyBlacklistToFleet"/>
        </do_if>
        
        <signal_cue_instantly cue="CleanupExpiredThreats_Blacklist"/>
      </actions>
    </library>
    
    <!-- Primary init path: MD is active after save load / new game (Lua Ready often fires earlier on menu). -->
    <cue name="InitializeBlacklistOnSessionStart" instantiate="true">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
          <event_game_started/>
        </check_any>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <run_actions ref="BootstrapBlacklistLuaIntegration">
          <param name="Reason" value="event.name"/>
          <param name="ApplyToFleet" value="true"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Secondary init path: Lua module loaded (may fire before MD on start menu - session start cue is the reliable fix). -->
    <cue name="InitializeBlacklistIntegration" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'gt_blacklist_manager'" control="'Ready'" />
      </conditions>
      <actions>
        <run_actions ref="BootstrapBlacklistLuaIntegration">
          <param name="Reason" value="'lua_ready'"/>
          <param name="ApplyToFleet" value="false"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Store blacklist ID after Lua creates/confirms it -->
    <cue name="StoreBlacklistID" instantiate="true">
      <conditions>
        <event_ui_triggered screen="'gt_blacklist_manager'" control="'BlacklistCreated'" />
      </conditions>
      <actions>
        <!-- Store the blacklist ID in global variable so it persists across saves -->
        <!-- event.param3 contains the third parameter passed to AddUITriggeredEvent -->
        <set_value name="global.$GT_BlacklistID" exact="event.param3"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-Blacklist] Stored blacklist ID: ' + global.$GT_BlacklistID" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Update blacklist immediately when threat is detected (event-driven, no polling) -->
    <cue name="UpdateBlacklistOnThreat" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Ensure blacklist epoch/snapshot globals exist -->
        <do_if value="not global.$GT_BlacklistEpoch?">
          <set_value name="global.$GT_BlacklistEpoch" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_LastThreatBlacklistData?">
          <set_value name="global.$GT_LastThreatBlacklistData" exact="''"/>
        </do_if>
        <!-- Only update if dynamic blacklist is enabled -->
        <do_if value="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist">
          <!-- Build list of threatened sector macros (empty when threat table cleared) -->
          <set_value name="$threatDataString" exact="''"/>
          <set_value name="$threatCount" exact="0"/>
          
          <do_if value="global.$GT_ThreatIntelligence?">
            <do_all exact="global.$GT_ThreatIntelligence.keys.count" counter="$i">
              <set_value name="$sector" exact="global.$GT_ThreatIntelligence.keys.list.{$i}"/>
              <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$sector}"/>
              
              <!-- Validate sector is valid before processing -->
              <set_value name="$sectorValid" exact="false"/>
              <do_if value="$sector?">
                <set_value name="$sectorMacroCheck" exact="@$sector.macro.id"/>
                <do_if value="$sectorMacroCheck?">
                  <set_value name="$sectorValid" exact="true"/>
                </do_if>
              </do_if>
              
              <do_if value="$threatData.$ThreatLevel? and $threatData.$Timestamp? and $sectorValid">
                <!-- Check if this sector should be blacklisted (consider defenses) -->
                <!-- If ShouldBlacklist is not set (old data), check defenses now -->
                <set_value name="$shouldBlacklist" exact="true"/>
                <do_if value="$threatData.$ShouldBlacklist?">
                  <set_value name="$shouldBlacklist" exact="$threatData.$ShouldBlacklist"/>
                </do_if>
                <do_else>
                  <!-- Legacy: Check defenses for old threat data that doesn't have the flag -->
                  <!-- Store sector in local variable to ensure it's in scope -->
                  <set_value name="$sectorToCheck" exact="$sector"/>
                  <set_value name="$threatScoreToCheck" exact="if $threatData.$ThreatScore? then $threatData.$ThreatScore else 0"/>
                  
                  <!-- Only call library if sector is still valid -->
                  <do_if value="$sectorToCheck?">
                    <run_actions ref="ShouldBlacklistSector" result="$defenseCheck">
                      <param name="Sector" value="$sectorToCheck"/>
                      <param name="EnemyThreatScore" value="$threatScoreToCheck"/>
                      <param name="DebugChance" value="0"/>
                    </run_actions>
                    <set_value name="$shouldBlacklist" exact="$defenseCheck.$ShouldBlacklist"/>
                  </do_if>
                  <do_else>
                    <!-- Sector invalid - default to blacklisting (safer) -->
                    <set_value name="$shouldBlacklist" exact="true"/>
                  </do_else>
                </do_else>
                
                <!-- Only add to blacklist if defenses don't protect the sector -->
                <do_if value="$shouldBlacklist">
                  <set_value name="$sectorMacro" exact="@$sector.macro.id"/>
                  <set_value name="$entry" exact="$sectorMacro + ':' + $threatData.$ThreatLevel + ':' + $threatData.$Timestamp"/>
                  
                  <do_if value="$threatDataString == ''">
                    <set_value name="$threatDataString" exact="$entry"/>
                  </do_if>
                  <do_else>
                    <set_value name="$threatDataString" exact="$threatDataString + '|' + $entry"/>
                  </do_else>
                  
                  <set_value name="$threatCount" exact="$threatCount + 1"/>
                </do_if>
              </do_if>
            </do_all>
          </do_if>
          
          <!-- Always sync Lua (including empty payload after manual clear) -->
          <raise_lua_event name="'GT_Blacklist.Update'" param="$threatDataString"/>
          <do_if value="$threatDataString != global.$GT_LastThreatBlacklistData">
            <set_value name="global.$GT_LastThreatBlacklistData" exact="$threatDataString"/>
            <set_value name="global.$GT_BlacklistEpoch" exact="global.$GT_BlacklistEpoch + 1"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Blacklist] Epoch advanced to ' + global.$GT_BlacklistEpoch + ' (payload changed)'" chance="100"/>
            </do_if>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $threatCount gt 0">
            <debug_text text="'[GT-Blacklist] ThreatAvoidance UPDATE: blacklisting ' + $threatCount + ' threatened sector(s) (threshold=' + @global.$GT_GlobalSettings.$ThreatAvoidance.$BlacklistThreshold + ', relation=' + (if @global.$GT_GlobalSettings.$ThreatAvoidance.$BlockEnemyFactions then 'enemy' else 'disabled') + ') data=' + $threatDataString" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Apply blacklist to all GT ships automatically (EVENT-DRIVEN, NO PERIODIC POLLING) -->
    <!-- Triggered by: threat detection, blacklist initialization, ship registration -->
    <cue name="ApplyBlacklistToFleet" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <!-- Small delay for batching multiple rapid signals (e.g., multiple threats detected) -->
      <delay exact="100ms"/>
      <actions>
        <set_value name="$processApplyBlacklist" exact="true"/>
        <!-- Manual-only guard: fleet assignment/removal must come from explicit settings button -->
        <do_if value="not global.$GT_ManualBlacklistAssignRequested? or not global.$GT_ManualBlacklistAssignRequested">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] ApplyBlacklistToFleet ignored (manual assign flag not set)'" chance="100"/>
          </do_if>
          <set_value name="$processApplyBlacklist" exact="false"/>
        </do_if>

        <do_if value="$processApplyBlacklist">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] ApplyBlacklistToFleet triggered (event-driven) - UseDynamicBlacklist: ' + @global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist + ', GT_Ships exists: ' + (global.$GT_Ships? and 1 or 0)" chance="100"/>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist">
          <!-- Setting ENABLED - apply blacklists to all ships -->
          <do_if value="global.$GT_Ships?">
            <!-- Build ship list string -->
            <set_value name="$shipListString" exact="''"/>
            <set_value name="$shipCount" exact="0"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Blacklist] Found ' + global.$GT_Ships.keys.count + ' registered GT ships'" chance="100"/>
            </do_if>
            
            <!-- Only apply blacklist to non-subordinate ships (solo + commanders) - subordinates inherit automatically -->
            <do_all exact="global.$GT_Ships.keys.count" counter="$i">
              <set_value name="$ship" exact="global.$GT_Ships.keys.list.{$i}"/>
              
              <!-- Check: operational AND not a subordinate (check live commander status, not cached data) -->
              <do_if value="$ship.isoperational and not ($ship.commander and $ship.commander != $ship)">
                <do_if value="$shipListString == ''">
                  <set_value name="$shipListString" exact="$ship + ''"/>
                </do_if>
                <do_else>
                  <set_value name="$shipListString" exact="$shipListString + ',' + $ship"/>
                </do_else>
                <set_value name="$shipCount" operation="add"/>
              </do_if>
            </do_all>
            
            <!-- Apply to fleet -->
            <do_if value="$shipListString != ''">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Blacklist] Applying blacklist to ' + $shipCount + ' non-subordinate ships (subordinates inherit from commanders)'" chance="100"/>
              </do_if>
              <raise_lua_event name="'GT_Blacklist.ApplyToFleet'" param="$shipListString"/>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Blacklist] No operational non-subordinate ships found'" chance="100"/>
              </do_if>
            </do_else>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Blacklist] global.$GT_Ships not found - no ships registered yet'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <!-- Setting DISABLED - remove blacklists from non-subordinate ships only -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Blacklist] Dynamic blacklist is DISABLED in settings'" chance="100"/>
          </do_if>
          
          <do_if value="global.$GT_Ships?">
            <!-- Only remove from non-subordinate ships (solo + commanders) - subordinates inherit automatically -->
            <do_all exact="global.$GT_Ships.keys.count" counter="$i">
              <set_value name="$ship" exact="global.$GT_Ships.keys.list.{$i}"/>
              
              <do_if value="$ship.isoperational and not ($ship.commander and $ship.commander != $ship)">
                <raise_lua_event name="'GT_Blacklist.RemoveFromShip'" param="$ship"/>
              </do_if>
            </do_all>
          </do_if>
          </do_else>

          <!-- Consume one-shot manual flag after processing -->
          <set_value name="global.$GT_ManualBlacklistAssignRequested" exact="false"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Cleanup expired threats -->
    <cue name="CleanupExpiredThreats_Blacklist" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Only cleanup if dynamic blacklist is enabled -->
        <do_if value="@global.$GT_GlobalSettings.$ThreatAvoidance.$UseDynamicBlacklist">
          <set_value name="$currentTime" exact="player.age"/>
          <set_value name="$expiryTime" exact="@global.$GT_GlobalSettings.$ThreatAvoidance.$ThreatExpiry"/>
          
          <do_if value="not $expiryTime?">
            <set_value name="$expiryTime" exact="3600"/> <!-- Default 1 hour -->
          </do_if>
          
          <!-- Re-evaluate all threatened sectors (prune dead hostiles, clear when safe) -->
          <do_if value="global.$GT_ThreatIntelligence?">
            <set_value name="$sectorsToProcess" exact="global.$GT_ThreatIntelligence.keys.list"/>
            <set_value name="$sectorsCleared" exact="0"/>
            
            <do_all exact="$sectorsToProcess.count" counter="$i">
              <set_value name="$sector" exact="$sectorsToProcess.{$i}"/>
              <run_actions ref="ClearSectorIfAllShipsGone" result="$clearResult">
                <param name="Sector" value="$sector"/>
                <param name="DebugChance" value="0"/>
              </run_actions>
              <do_if value="$clearResult.$SectorCleared">
                <set_value name="$sectorsCleared" exact="$sectorsCleared + 1"/>
              </do_if>
            </do_all>
            
            <do_if value="$sectorsCleared gt 0">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Threat] Cleanup: cleared ' + $sectorsCleared + ' sector(s) after threat re-evaluation'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          
          <!-- Signal Lua to cleanup expired threats -->
          <raise_lua_event name="'GT_Blacklist.CleanupExpired'" param="$currentTime + ':' + $expiryTime"/>
          
          <!-- Update blacklist after cleanup (event-driven: some threats may have expired or been cleared) -->
          <signal_cue_instantly cue="UpdateBlacklistOnThreat"/>
        </do_if>
      </actions>
      <cues>
        <cue name="CleanupExpiredThreats_Delay">
          <conditions>
            <event_cue_signalled/>
          </conditions>
          <delay exact="600s"/>
          <actions>
            <!-- Continue cleanup -->
            <signal_cue_instantly cue="CleanupExpiredThreats_Blacklist"/>
          </actions>
        </cue>
      </cues>
    </cue>
    
    <!-- ========================================================================= -->
    <!-- TRACK ENEMY SHIP DESTRUCTION - Remove destroyed ships from tracking -->
    <!-- ========================================================================= -->
    <cue name="TrackEnemyShipDestruction" instantiate="true">
      <conditions>
        <!-- Do not use group= in conditions: group may not exist yet on first event after load.
             Actions filter against TrackedEnemyShips; move.generic provides a backup path. -->
        <event_object_destroyed object="player.galaxy"/>
      </conditions>
      <actions>
        <set_value name="$destroyedShip" exact="event.object"/>
        
        <!-- Skip non-ship destruction noise -->
        <do_if value="not $destroyedShip.isclass.ship_s and not $destroyedShip.isclass.ship_m and not $destroyedShip.isclass.ship_l and not $destroyedShip.isclass.ship_xl">
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
        <!-- Check if destroyed ship is tracked in any sector -->
        <do_if value="global.$GT_ThreatIntelligence?">
          <set_value name="$sectorsToCheck" exact="global.$GT_ThreatIntelligence.keys.list"/>
          
          <do_all exact="$sectorsToCheck.count" counter="$i">
            <set_value name="$sector" exact="$sectorsToCheck.{$i}"/>
            <set_value name="$threatData" exact="global.$GT_ThreatIntelligence.{$sector}"/>
            
            <!-- Check if this sector has tracked ships -->
            <do_if value="$threatData.$TrackedEnemyShips? and $threatData.$TrackedEnemyShips.count gt 0">
              <set_value name="$trackedShips" exact="$threatData.$TrackedEnemyShips"/>
              <set_value name="$shipFound" exact="false"/>
              
              <!-- Find and remove destroyed ship from tracking -->
              <do_all exact="$trackedShips.count" counter="$j" reverse="true">
                <set_value name="$trackedShip" exact="null"/>
                <do_if value="$trackedShips.{$j}?">
                  <set_value name="$trackedShip" exact="$trackedShips.{$j}"/>
                </do_if>
                <do_if value="$trackedShip == null">
                  <continue/>
                </do_if>
                <do_if value="$trackedShip == $destroyedShip">
                  <set_value name="$shipFound" exact="true"/>
                  <run_actions ref="RemoveTrackedEnemyShip">
                    <param name="Sector" value="$sector"/>
                    <param name="Ship" value="$trackedShip"/>
                    <param name="DebugChance" value="100"/>
                  </run_actions>
                  <break/>
                </do_if>
              </do_all>
              
              <!-- Re-evaluate whether sector can be cleared -->
              <do_if value="$shipFound">
                <run_actions ref="ClearSectorIfAllShipsGone">
                  <param name="Sector" value="$sector"/>
                  <param name="DebugChance" value="100"/>
                </run_actions>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        </do_else>
      </actions>
    </cue>
    <!-- ========================================================================= -->
    <cue name="HandleEnemyShipDeparture" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_ClearSectorIfAllShipsGone'"/>
      </conditions>
      <actions>
        <set_value name="$signalData" exact="event.param2"/>
        <set_value name="$sector" exact="$signalData.$Sector"/>
        
        <run_actions ref="ClearSectorIfAllShipsGone">
          <param name="Sector" value="$sector"/>
          <param name="DebugChance" value="100"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Re-evaluate sector when player combat fleet arrives (may now outmatch hostiles) -->
    <cue name="HandleSectorThreatReevaluate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_ReevaluateSectorThreat'"/>
      </conditions>
      <actions>
        <set_value name="$signalData" exact="event.param2"/>
        <set_value name="$sector" exact="$signalData.$Sector"/>
        
        <run_actions ref="ClearSectorIfAllShipsGone">
          <param name="Sector" value="$sector"/>
          <param name="DebugChance" value="100"/>
        </run_actions>
      </actions>
    </cue>
    
  </cues>
  
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_TradeLogging" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    
    <!-- Initialize Trade Logging System -->
    <cue name="SystemInit" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_CoreSystem.SystemInit"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Trade logging system initializing...'" chance="100"/>
        </do_if>
        
        <!-- Initialize logbook settings -->
        <set_value name="global.$GT_TradeLogging" exact="table[]"/>
        <set_value name="global.$GT_TradeLogging.$Enabled" exact="true"/>
        <set_value name="global.$GT_TradeLogging.$TrainingMessages" exact="true"/>
        <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Trade logging system initialized'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Per-Trade Logbook Entry (TaterTrader Style) -->
    <cue name="LogTradeOrder" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogTradeOrder'"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeLogging] LogTradeOrder cue triggered'" chance="100"/>
        </do_if>
        
        <!-- Extract trade data from signal -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$sellOffer" exact="event.param2.$SellOffer"/>
        <set_value name="$buyOffer" exact="event.param2.$BuyOffer"/>
        <set_value name="$amount" exact="if event.param2.$Amount? then event.param2.$Amount else 0"/>
        <set_value name="$profit" exact="if event.param2.$Profit? then event.param2.$Profit else 0"/>
        <set_value name="$sellPrice" exact="if event.param2.$SellPrice? then event.param2.$SellPrice else 0"/>
        <set_value name="$buyPrice" exact="if event.param2.$BuyPrice? then event.param2.$BuyPrice else 0"/>
        <set_value name="$buyPriceRaw" exact="if event.param2.$BuyPriceRaw? then event.param2.$BuyPriceRaw else $buyPrice * 100"/>
        <set_value name="$sellPriceRaw" exact="if event.param2.$SellPriceRaw? then event.param2.$SellPriceRaw else $sellPrice * 100"/>
        <set_value name="$buyPrice" exact="$buyPriceRaw / 100"/>
        <set_value name="$sellPrice" exact="$sellPriceRaw / 100"/>

        <!-- MK2 distribution: queue-time supply message only (no profit / credits-due popup). -->
        <set_value name="$isMk2Distribution" exact="false"/>
        <do_if value="event.param2.$IsMk2Distribution? and event.param2.$IsMk2Distribution">
          <set_value name="$isMk2Distribution" exact="true"/>
        </do_if>

        <!-- MK1 station supply: queue-time fill-% message (no profit / credits-due popup). -->
        <set_value name="$isMk1Supply" exact="false"/>
        <do_if value="event.param2.$IsMk1Supply? and event.param2.$IsMk1Supply">
          <set_value name="$isMk1Supply" exact="true"/>
        </do_if>

        <!-- MK1 station export sell to NPC buyers. -->
        <set_value name="$isMk1Export" exact="false"/>
        <do_if value="event.param2.$IsMk1Export? and event.param2.$IsMk1Export">
          <set_value name="$isMk1Export" exact="true"/>
        </do_if>

        <!-- MK4-2 supply: queue-time undercut message (not trader profit). -->
        <set_value name="$isMk4Supply" exact="false"/>
        <do_if value="event.param2.$IsMk4Supply? and event.param2.$IsMk4Supply">
          <set_value name="$isMk4Supply" exact="true"/>
        </do_if>

        <!-- GT due override source of truth: mirror queued logbook semantics exactly. -->
        <!-- Use exact money snapshot from AI when available to avoid conversion drift. -->
        <set_value name="$moneyRawForDue" exact="if event.param2.$MoneyRaw? then event.param2.$MoneyRaw else -$amount * $buyPriceRaw"/>
        <!-- Match vanilla due semantics: reserved money only (no bonus/profit component). -->
        <set_value name="$projectedRawForDue" exact="abs($moneyRawForDue)"/>
        <do_if value="not $isMk2Distribution and not $isMk1Supply">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-MD-UI-DUE] ' + $ship.idcode +
              '\n  Signal amount: ' + $amount +
              '\n  Signal buyPrice (RAW): ' + $buyPriceRaw + ' (' + ($buyPriceRaw / 100) + ' Cr)' +
              '\n  Signal sellPrice (RAW): ' + $sellPriceRaw + ' (' + ($sellPriceRaw / 100) + ' Cr)' +
              '\n  Signal profit (RAW): ' + (if $profit? then $profit else 0) + ' (' + ((if $profit? then $profit else 0)/100) + ' Cr)' +
              '\n  Computed moneyRawForDue: ' + $moneyRawForDue + ' (' + ($moneyRawForDue/100) + ' Cr)' +
              '\n  Computed projectedRawForDue (money only): ' + $projectedRawForDue + ' (' + ($projectedRawForDue/100) + ' Cr)'" chance="100"/>
          </do_if>
          <run_actions ref="md.GT_Libraries_General.GT_SetUICreditsDueForShip">
            <param name="ship" value="$ship"/>
            <param name="projectedRaw" value="$projectedRawForDue"/>
          </run_actions>
        </do_if>

        <!-- FIX: Check if this is a sell-only trade -->
        <set_value name="$isSellOnly" exact="false"/>
        <do_if value="event.param2.$IsSellOnly?">
          <set_value name="$isSellOnly" exact="event.param2.$IsSellOnly"/>
        </do_if>
        
        <!-- Extract search pipeline type (normal / fallback / isolated) -->
        <set_value name="$searchPipeline" exact="'normal'"/>
        <do_if value="event.param2.$SearchPipeline?">
          <set_value name="$searchPipeline" exact="event.param2.$SearchPipeline"/>
        </do_if>

        <!-- MK3 'Ignore Player Pricing' marker:
             When true, this trade buys from a player-owned supplier whose production cost
             the player treats as zero. The queued logbook entry must hide the buy leg and
             report only the gross sell income as profit (set in lib.gt.tradematch). -->
        <set_value name="$playerFreeSupplier" exact="false"/>
        <do_if value="event.param2.$PlayerFreeSupplier?">
          <set_value name="$playerFreeSupplier" exact="event.param2.$PlayerFreeSupplier"/>
        </do_if>
        <set_value name="$isMultiTrade" exact="false"/>
        <do_if value="event.param2.$IsMultiTrade? and event.param2.$IsMultiTrade">
          <set_value name="$isMultiTrade" exact="true"/>
        </do_if>
        <set_value name="$multiTradeLegCount" exact="0"/>
        <do_if value="event.param2.$MultiTradeLegs? and event.param2.$MultiTradeLegs.count gt 0">
          <set_value name="$multiTradeLegCount" exact="event.param2.$MultiTradeLegs.count"/>
        </do_if>
        <set_value name="$multiTradeSummary" exact="''"/>
        <do_if value="event.param2.$MultiTradeSummary? and event.param2.$MultiTradeSummary != null">
          <set_value name="$multiTradeSummary" exact="event.param2.$MultiTradeSummary"/>
        </do_if>
        <!-- Structured multitrade legs: format summary in MD via GT_FormatStationLocation (AI cannot run_actions). -->
        <do_if value="event.param2.$MultiTradeLegs? and event.param2.$MultiTradeLegs != null and event.param2.$MultiTradeLegs.count gt 0">
          <set_value name="$multiTradeLegs" exact="event.param2.$MultiTradeLegs"/>
          <set_value name="$multiTradeSummaryMax" exact="if event.param2.$MultiTradeSummaryMax? then event.param2.$MultiTradeSummaryMax else 0"/>
          <set_value name="$multiTradeSummary" exact="''"/>
          <set_value name="$multiTradeSummaryCount" exact="0"/>
          <do_all exact="$multiTradeLegs.count" counter="$mtli">
            <do_if value="$multiTradeSummaryMax le 0 or $multiTradeSummaryCount lt $multiTradeSummaryMax">
              <set_value name="$mtLeg" exact="$multiTradeLegs.{$mtli}"/>
              <set_value name="$mtAmount" exact="if $mtLeg.$Amount? then $mtLeg.$Amount else 0"/>
              <set_value name="$mtBuyPriceRaw" exact="if $mtLeg.$BuyPriceRaw? then $mtLeg.$BuyPriceRaw else 0"/>
              <set_value name="$mtSellPriceRaw" exact="if $mtLeg.$SellPriceRaw? then $mtLeg.$SellPriceRaw else 0"/>
              <set_value name="$mtWareName" exact="if $mtLeg.$Ware? and $mtLeg.$Ware.name? then @$mtLeg.$Ware.name else '?'"/>
              <set_value name="$mtBuyStationLabel" exact="'Unknown'"/>
              <set_value name="$mtSellStationLabel" exact="'Unknown'"/>
              <do_if value="$mtLeg.$BuyStation? and $mtLeg.$BuyStation.exists">
                <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$mtBuyStationLabel">
                  <param name="station" value="$mtLeg.$BuyStation"/>
                </run_actions>
              </do_if>
              <do_if value="$mtLeg.$SellStation? and $mtLeg.$SellStation.exists">
                <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$mtSellStationLabel">
                  <param name="station" value="$mtLeg.$SellStation"/>
                </run_actions>
              </do_if>
              <set_value name="$mtSummaryItem" exact="$mtAmount + ' ' + $mtWareName + ' @ ' + ($mtBuyPriceRaw / 100) + '->' + ($mtSellPriceRaw / 100) + ' Cr [' + $mtBuyStationLabel + ' -> ' + $mtSellStationLabel + ']'"/>
              <set_value name="$multiTradeSummary" exact="$multiTradeSummary + (if $multiTradeSummary != '' then ', ' else '') + $mtSummaryItem"/>
              <set_value name="$multiTradeSummaryCount" exact="$multiTradeSummaryCount + 1"/>
            </do_if>
          </do_all>
          <do_if value="$multiTradeSummaryMax gt 0 and $multiTradeLegs.count gt $multiTradeSummaryMax">
            <set_value name="$multiTradeSummary" exact="$multiTradeSummary + ', ...+' + ($multiTradeLegs.count - $multiTradeSummaryMax) + ' more legs'"/>
          </do_if>
        </do_if>
        
        <!-- Validate trade offers before accessing properties (they may be invalid/expired) -->
        <set_value name="$buyOfferValid" exact="$buyOffer.exists"/>
        <set_value name="$sellOfferValid" exact="$sellOffer.exists"/>
        
        <!-- Build debug message with safe property access (only when debug is enabled) -->
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$debugMsg" exact="'[GT-TradeLogging] ========== RAW DATA RECEIVED ==========\nShip: ' + $ship.knownname + ' (' + $ship.idcode + ')'"/>
          
          <!-- FIX: Show "N/A (sell-only)" instead of "[INVALID/EXPIRED]" for sell-only trades -->
          <do_if value="$isSellOnly">
            <set_value name="$debugMsg" exact="$debugMsg + '\nBuyOffer: N/A (sell-only)'"/>
          </do_if>
          <do_elseif value="$buyOfferValid">
            <set_value name="$debugMsg" exact="$debugMsg + '\nBuyOffer: ' + $buyOffer.owner.knownname + ', Ware: ' + $buyOffer.ware.name + ', UnitPrice: ' + ($buyOffer.unitprice/100) + ' Cr'"/>
          </do_elseif>
          <do_else>
            <set_value name="$debugMsg" exact="$debugMsg + '\nBuyOffer: [INVALID/EXPIRED]'"/>
          </do_else>
          
          <do_if value="$sellOfferValid">
            <set_value name="$debugMsg" exact="$debugMsg + '\nSellOffer: ' + $sellOffer.owner.knownname + ', Ware: ' + $sellOffer.ware.name + ', UnitPrice: ' + ($sellOffer.unitprice/100) + ' Cr'"/>
          </do_if>
          <do_else>
            <set_value name="$debugMsg" exact="$debugMsg + '\nSellOffer: [INVALID/EXPIRED]'"/>
          </do_else>
          
          <set_value name="$debugMsg" exact="$debugMsg + '\nAmount: ' + $amount + '\nProfit: ' + ($profit/100) + ' Cr (RAW: ' + $profit + ')' + '\nBuyPrice snapshot: ' + $buyPrice + ' Cr (RAW: ' + $buyPriceRaw + ')' + '\nSellPrice snapshot: ' + $sellPrice + ' Cr (RAW: ' + $sellPriceRaw + ')' + '\nCalculated profit check: (' + $sellPrice + ' - ' + $buyPrice + ') * ' + $amount + ' = ' + (($sellPrice - $buyPrice) * $amount) + ' Cr'"/>
          <debug_text text="$debugMsg" chance="100"/>
        </do_if>
        
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_TradeLogging exists -->
        <!-- Initialize logging system if not already done -->
        <do_if value="not global.$GT_TradeLogging.$Enabled?">
          <set_value name="global.$GT_TradeLogging.$Enabled" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$TrainingMessages" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Trade logging system auto-initialized'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$Enabled">
          
          <!-- Validate we have enough data to log (multi-trade uses aggregated summary text). -->
          <do_if value="$isMultiTrade or $buyOfferValid or $sellOfferValid or ($isMk2Distribution and $amount gt 0 and event.param2.$Ware?) or ($isMk1Supply and $amount gt 0 and event.param2.$Ware?)">
            
            <!-- Get ware info from valid offer (prefer buy offer) -->
            <set_value name="$wareInfo" exact="null"/>
            <do_if value="$buyOfferValid">
              <set_value name="$wareInfo" exact="$buyOffer.ware"/>
            </do_if>
            <do_elseif value="$sellOfferValid">
              <set_value name="$wareInfo" exact="$sellOffer.ware"/>
            </do_elseif>
            <do_elseif value="event.param2.$Ware?">
              <set_value name="$wareInfo" exact="event.param2.$Ware"/>
            </do_elseif>

            <!-- Station labels: Sector - Stationname(IDCODE).
                 MK1 supply remaps BuyOffer/SellOffer for vanilla order queue order; use explicit
                 $BuyStation (source) / $SellStation (receiving home) when the AI sends them. -->
            <set_value name="$buyStationFormatted" exact="'Unknown'"/>
            <set_value name="$sellStationFormatted" exact="'Unknown'"/>
            <do_if value="$isMk1Supply and event.param2.$BuyStation? and event.param2.$BuyStation.exists">
              <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$buyStationFormatted">
                <param name="station" value="event.param2.$BuyStation"/>
              </run_actions>
            </do_if>
            <do_elseif value="$buyOfferValid and $buyOffer.owner? and $buyOffer.owner.exists">
              <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$buyStationFormatted">
                <param name="station" value="$buyOffer.owner"/>
              </run_actions>
            </do_elseif>
            <do_elseif value="event.param2.$BuyStation? and event.param2.$BuyStation.exists">
              <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$buyStationFormatted">
                <param name="station" value="event.param2.$BuyStation"/>
              </run_actions>
            </do_elseif>
            <do_if value="$isMk1Supply and event.param2.$SellStation? and event.param2.$SellStation.exists">
              <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$sellStationFormatted">
                <param name="station" value="event.param2.$SellStation"/>
              </run_actions>
            </do_if>
            <do_elseif value="$sellOfferValid and $sellOffer.owner? and $sellOffer.owner.exists">
              <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$sellStationFormatted">
                <param name="station" value="$sellOffer.owner"/>
              </run_actions>
            </do_elseif>
            <do_elseif value="event.param2.$SellStation? and event.param2.$SellStation.exists">
              <run_actions ref="md.GT_Libraries_General.GT_FormatStationLocation" result="$sellStationFormatted">
                <param name="station" value="event.param2.$SellStation"/>
              </run_actions>
            </do_elseif>
            
            <!-- Build queued trade message from snapshot prices:
                 3100 for cargo sale, 3101 for normal trade,
                 3102 for MK1/MK2 station supply (fill % only, no profit),
                 3103 for MK1 single export sell (destination station, price, profit),
                 3107 for multi-trade summary,
                 3108 for MK3 'Ignore Player Pricing' player-supplier sale (buy leg hidden,
                 profit = gross sell income because player production cost is treated as zero),
                 3110 for MK4-2 supply (NPC supplier: price undercut vs customer cap),
                 3111 for MK4-2 supply (player supplier: no money line),
                 3112 for MK4-2 supply multitrade summary (total undercut),
                 3113 for MK1 export multitrade summary. -->
            <set_value name="$logbookMessage" exact="null"/>
            <do_if value="$isMultiTrade and $isMk4Supply">
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedUndercutTotal">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$multiSummarySafe" exact="if $multiTradeSummary != '' then $multiTradeSummary else '-'"/>
              <set_value name="$logbookMessage" exact="{77000,3112}.[$multiTradeLegCount,$multiSummarySafe,$formattedUndercutTotal]"/>
            </do_if>
            <do_elseif value="$isMultiTrade and $isMk1Export">
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$multiSummarySafe" exact="if $multiTradeSummary != '' then $multiTradeSummary else '-'"/>
              <set_value name="$logbookMessage" exact="{77000,3113}.[$multiSummarySafe,$formattedProfit]"/>
            </do_elseif>
            <do_elseif value="$isMultiTrade">
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$multiSummarySafe" exact="if $multiTradeSummary != '' then $multiTradeSummary else '-'"/>
              <set_value name="$logbookMessage" exact="{77000,3107}.[$multiSummarySafe,$formattedProfit]"/>
            </do_elseif>
            <do_elseif value="$isMk1Supply and ($buyPriceRaw gt 0 or $sellPriceRaw gt 0)">
              <!-- MK1 supply: home buy cap vs NPC source price (not trader profit). Player-owned suppliers use route-only 3111. -->
              <set_value name="$mk1SupplyPlayerSource" exact="false"/>
              <do_if value="event.param2.$BuyStation? and @event.param2.$BuyStation.isplayerowned">
                <set_value name="$mk1SupplyPlayerSource" exact="true"/>
              </do_if>
              <do_if value="$mk1SupplyPlayerSource">
                <set_value name="$logbookMessage" exact="{77000,3111}.[$amount,$wareInfo,$buyStationFormatted,$sellStationFormatted]"/>
              </do_if>
              <do_else>
                <set_value name="$mk1SupplyUnitUndercutCr" exact="$sellPrice - $buyPrice"/>
                <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedBuyPrice">
                  <param name="number" value="$buyPrice"/>
                  <param name="suffix" value="' Cr'"/>
                </run_actions>
                <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSellPrice">
                  <param name="number" value="$sellPrice"/>
                  <param name="suffix" value="' Cr'"/>
                </run_actions>
                <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedUnitUndercut">
                  <param name="number" value="$mk1SupplyUnitUndercutCr"/>
                  <param name="suffix" value="' Cr'"/>
                </run_actions>
                <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedUndercutTotal">
                  <param name="number" value="$profit/100"/>
                  <param name="suffix" value="' Cr'"/>
                </run_actions>
                <set_value name="$logbookMessage" exact="{77000,3110}.[$amount,$wareInfo,$formattedBuyPrice,$buyStationFormatted,$sellStationFormatted,$formattedSellPrice,$formattedUnitUndercut,$formattedUndercutTotal]"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$isMk2Distribution">
              <!-- MK2 station supply: fill % only (no prices). -->
              <set_value name="$mk2SourceFillPercent" exact="if event.param2.$SourceFillPercent? then event.param2.$SourceFillPercent else 0"/>
              <set_value name="$mk2DestFillPercent" exact="if event.param2.$DestFillPercent? then event.param2.$DestFillPercent else 0"/>
              <set_value name="$logbookMessage" exact="{77000,3102}.[$amount,$wareInfo,$buyStationFormatted,$sellStationFormatted,$mk2SourceFillPercent,$mk2DestFillPercent]"/>
            </do_elseif>
            <do_elseif value="$isMk1Supply">
              <!-- MK1 supply fallback when no price snapshot: fill % only. -->
              <set_value name="$mk2SourceFillPercent" exact="if event.param2.$SourceFillPercent? then event.param2.$SourceFillPercent else 0"/>
              <set_value name="$mk2DestFillPercent" exact="if event.param2.$DestFillPercent? then event.param2.$DestFillPercent else 0"/>
              <set_value name="$logbookMessage" exact="{77000,3102}.[$amount,$wareInfo,$buyStationFormatted,$sellStationFormatted,$mk2SourceFillPercent,$mk2DestFillPercent]"/>
            </do_elseif>
            <do_elseif value="not $buyOfferValid">
              <!-- Selling from cargo (no buy offer) - use translation ID 3100 -->
              <!-- Format profit with thousand separators and M suffix according to global settings -->
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSellPrice">
                <param name="number" value="$sellPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$logbookMessage" exact="{77000,3100}.[$amount,$wareInfo,$sellStationFormatted,$formattedSellPrice,$formattedProfit]"/>
            </do_elseif>
            <do_elseif value="$isMk4Supply and $playerFreeSupplier">
              <!-- MK4-2 supply from player-owned supplier: internal transfer â€” route only, no prices. -->
              <set_value name="$logbookMessage" exact="{77000,3111}.[$amount,$wareInfo,$buyStationFormatted,$sellStationFormatted]"/>
            </do_elseif>
            <do_elseif value="$isMk4Supply">
              <!-- MK4-2 supply from NPC supplier: customer cap minus sourcing price (undercut), not trader profit. -->
              <set_value name="$supplyUnitUndercutCr" exact="$sellPrice - $buyPrice"/>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedBuyPrice">
                <param name="number" value="$buyPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSellPrice">
                <param name="number" value="$sellPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedUnitUndercut">
                <param name="number" value="$supplyUnitUndercutCr"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedUndercutTotal">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$logbookMessage" exact="{77000,3110}.[$amount,$wareInfo,$formattedBuyPrice,$buyStationFormatted,$sellStationFormatted,$formattedSellPrice,$formattedUnitUndercut,$formattedUndercutTotal]"/>
            </do_elseif>
            <do_elseif value="$isMk1Export">
              <!-- MK1 export sell to NPC buyer - station-trader wording (single leg). -->
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSellPrice">
                <param name="number" value="$sellPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$logbookMessage" exact="{77000,3103}.[$amount,$wareInfo,$sellStationFormatted,$formattedSellPrice,$formattedProfit]"/>
            </do_elseif>
            <do_elseif value="$playerFreeSupplier">
              <!-- MK3 'Ignore Player Pricing' player-supplier trade: hide the buy leg.
                   $profit is already overridden upstream to the gross sell income. -->
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSellPrice">
                <param name="number" value="$sellPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$logbookMessage" exact="{77000,3108}.[$amount,$wareInfo,$sellStationFormatted,$formattedSellPrice,$formattedProfit]"/>
            </do_elseif>
            <do_else>
              <!-- Normal trade (buy then sell) - use translation ID 3101 -->
              <!-- $buyPrice/$sellPrice are derived from RAW snapshot values for this created trade. -->
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedBuyPrice">
                <param name="number" value="$buyPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSellPrice">
                <param name="number" value="$sellPrice"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$logbookMessage" exact="{77000,3101}.[$amount,$wareInfo,$formattedBuyPrice,$buyStationFormatted,$formattedSellPrice,$sellStationFormatted,$formattedProfit]"/>
            </do_else>
            
            <set_value name="$msgType" exact="'3101 (normal trade)'"/>
            <do_if value="$isMultiTrade and $isMk4Supply">
              <set_value name="$msgType" exact="'3112 (mk4 supply multitrade)'"/>
            </do_if>
            <do_elseif value="$isMultiTrade and $isMk1Export">
              <set_value name="$msgType" exact="'3113 (mk1 export multitrade)'"/>
            </do_elseif>
            <do_elseif value="$isMultiTrade">
              <set_value name="$msgType" exact="'3107 (multitrade queue summary)'"/>
            </do_elseif>
            <do_elseif value="$isMk1Supply and ($buyPriceRaw gt 0 or $sellPriceRaw gt 0)">
              <set_value name="$mk1SupplyPlayerSourceDbg" exact="false"/>
              <do_if value="event.param2.$BuyStation? and @event.param2.$BuyStation.isplayerowned">
                <set_value name="$mk1SupplyPlayerSourceDbg" exact="true"/>
              </do_if>
              <do_if value="$mk1SupplyPlayerSourceDbg">
                <set_value name="$msgType" exact="'3111 (mk1 supply player source)'"/>
              </do_if>
              <do_else>
                <set_value name="$msgType" exact="'3110 (mk1 supply under cap)'"/>
              </do_else>
            </do_elseif>
            <do_elseif value="$isMk1Supply">
              <set_value name="$msgType" exact="'3102 (mk1 supply)'"/>
            </do_elseif>
            <do_elseif value="$isMk2Distribution">
              <set_value name="$msgType" exact="'3102 (mk2 distribution)'"/>
            </do_elseif>
            <do_elseif value="not $buyOfferValid">
              <set_value name="$msgType" exact="'3100 (cargo sale)'"/>
            </do_elseif>
            <do_elseif value="$isMk1Export">
              <set_value name="$msgType" exact="'3103 (mk1 export sell)'"/>
            </do_elseif>
            <do_elseif value="$isMk4Supply and $playerFreeSupplier">
              <set_value name="$msgType" exact="'3111 (mk4 supply player supplier)'"/>
            </do_elseif>
            <do_elseif value="$isMk4Supply">
              <set_value name="$msgType" exact="'3110 (mk4 supply undercut)'"/>
            </do_elseif>
            <do_elseif value="$playerFreeSupplier">
              <set_value name="$msgType" exact="'3108 (player-free-supplier sale)'"/>
            </do_elseif>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <!-- Format numbers for debug output -->
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$debugProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$debugMoney">
                <param name="number" value="abs($moneyRawForDue) / 100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              
              <!-- PROFIT DEBUG: Enhanced logging for profit calculation investigation -->
              <set_value name="$buyStationName" exact="if $buyOfferValid and $buyOffer.owner? then @$buyOffer.owner.knownname else 'NULL'"/>
              <set_value name="$sellStationName" exact="if $sellOfferValid and $sellOffer.owner? then @$sellOffer.owner.knownname else 'NULL'"/>
              <set_value name="$debugWareName" exact="if $isMultiTrade then 'MULTITRADE' else (if $wareInfo? and $wareInfo.name? then @$wareInfo.name else 'NULL')"/>
              <set_value name="$calculatedProfitCheck" exact="(($sellPrice - $buyPrice) * $amount)"/>
              <debug_text text="'[GT-TradeLogging-PROFIT] ========== LOGBOOK DATA BEING WRITTEN ==========' + 
                '\nMessage type: ' + $msgType + 
                '\nWare: ' + $debugWareName +
                '\nBuy Station: ' + $buyStationName + ' @ ' + $buyPrice + ' Cr (from snapshot)' +
                '\nSell Station: ' + $sellStationName + ' @ ' + $sellPrice + ' Cr (from snapshot)' +
                '\nAmount: ' + $amount + ' units (from param)' +
                '\nProfit (RAW from param): ' + $profit + ' = ' + ($profit/100) + ' Cr' +
                '\nProfit (formatted for display): ' + $debugProfit +
                '\nVerification calculation: (' + $sellPrice + ' - ' + $buyPrice + ') * ' + $amount + ' = ' + $calculatedProfitCheck + ' Cr' +
                '\nProfit matches verification: ' + (if abs(($profit/100) - $calculatedProfitCheck) lt 0.01 then 'YES' else 'NO (DIFF: ' + abs(($profit/100) - $calculatedProfitCheck) + ' Cr)') +
                '\nMoney field: -' + $debugMoney + 
                '\nBonus field: ' + $debugProfit + 
                '\nFinal message text: ' + $logbookMessage" chance="100"/>
            </do_if>
            
            <!-- Write to ship logbook (TaterTrader style) -->
            <!-- Build logbook title: add [FALLBACK] or [ISOLATED] prefix for non-normal pipelines -->
            <set_value name="$logbookOrderName" exact="'GalaxyTrader MK3'"/>
            <do_if value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK1'">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK1'"/>
            </do_if>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK2'">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK2'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK3'">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK3'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK4Supply'">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4 Supply'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK4Supply2'">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4-2 Supply'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK1') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK1'))">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK1'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK2') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK2'))">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK2'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK3') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK3'))">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK3'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply'))">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4 Supply'"/>
            </do_elseif>
            <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2'))">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4-2 Supply'"/>
            </do_elseif>
            <do_if value="$isMk4Supply">
              <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4-2 Supply'"/>
            </do_if>
            <set_value name="$logbookTitle" exact="$logbookOrderName + ': ' + $ship.knownname + ' (' + $ship.idcode + ')'"/>
            <do_if value="$searchPipeline == 'fallback'">
              <set_value name="$logbookTitle" exact="'[FALLBACK] ' + $logbookTitle"/>
            </do_if>
            <do_elseif value="$searchPipeline == 'isolated'">
              <set_value name="$logbookTitle" exact="'[ISOLATED] ' + $logbookTitle"/>
            </do_elseif>
            
            <!-- Logbook Money / Bonus display:
                 Default: Money = -buyValue (out for buy leg), Bonus = profit (gain).
                 MK3 'Ignore Player Pricing' override: the buy-leg credits flow within the
                 player's own economy (ship -> player station), so from the player-economy
                 perspective there is no out-flow. Show Money = 0 and Bonus = gross sell
                 income so the popup matches the queued message text.
                 The credits-due reservation ($projectedRawForDue) is unaffected â€” the ship
                 still genuinely needs cash to execute the buy leg.
                 MK2 distribution: omit Money and Bonus entirely (supply-only queue message). -->
            <set_value name="$logbookMoney" exact="if $playerFreeSupplier then 0 else $moneyRawForDue"/>
            <set_value name="$logbookBonus" exact="$profit"/>
            <do_if value="$isMk2Distribution">
              <set_value name="$logbookMoney" exact="null"/>
              <set_value name="$logbookBonus" exact="null"/>
            </do_if>
            <do_elseif value="$isMk1Supply">
              <!-- MK1 supply: show buy-leg reservation; margin is in the message text, not Bonus. -->
              <set_value name="$logbookMoney" exact="if $playerFreeSupplier then 0 else $moneyRawForDue"/>
              <set_value name="$logbookBonus" exact="null"/>
            </do_elseif>
            <do_elseif value="$isMk4Supply">
              <!-- Supply run: show buy-leg reservation in Money; never show undercut as Bonus/profit. -->
              <set_value name="$logbookMoney" exact="if $playerFreeSupplier then 0 else $moneyRawForDue"/>
              <set_value name="$logbookBonus" exact="null"/>
            </do_elseif>
            <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
              <param name="Message" value="$logbookMessage"/>
              <param name="Category" value="'tips'"/>
              <param name="Title" value="$logbookTitle"/>
              <param name="Object" value="$ship"/>
              <param name="Interaction" value="'showonmap'"/>
              <param name="Money" value="$logbookMoney"/>
              <param name="Bonus" value="$logbookBonus"/>
              <param name="CheckGlobalSettings" value="false"/>
            </run_actions>
            
            <!-- DEBUG MODE: Only log when debug is enabled -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <!-- Format profit for debug output -->
              <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$debugProfit">
                <param name="number" value="$profit/100"/>
                <param name="suffix" value="' Cr'"/>
              </run_actions>
              <set_value name="$debugLoggedWare" exact="if $isMultiTrade then 'MULTITRADE' else (if $wareInfo? and $wareInfo.name? then @$wareInfo.name else 'Unknown')"/>
              <debug_text text="'[GalaxyTrader MK3] Trade logged for ' + $ship.knownname + ' (' + $ship.idcode + '): ' + $amount + ' ' + $debugLoggedWare + ' (Profit: ' + $debugProfit + ')'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- DEBUG MODE: Only log when debug is enabled -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] WARNING: Cannot log trade - buy/sell offers invalid and no multitrade summary for ' + $ship.knownname" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Miner foreign-station cargo sale logbook entry -->
    <cue name="LogMinerCargoSale" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogMinerCargoSale'"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$station" exact="event.param2.$station"/>
        <set_value name="$ware" exact="event.param2.$ware"/>
        <set_value name="$amount" exact="event.param2.$transferredAmount"/>
        <set_value name="$saleValueRaw" exact="if event.param2.$saleValueRaw? then event.param2.$saleValueRaw else 0"/>

        <do_if value="$ship? and $ship.exists and $station? and $station.exists and $ware? and $amount? and $amount gt 0">
          <set_value name="$isForeignSale" exact="$station.owner != $ship.owner"/>
          <set_value name="$logbookMessage" exact="null"/>

          <do_if value="$isForeignSale">
            <!-- Prefer live station buy offer unit price; fallback to ware average price when no offer is available. -->
            <do_if value="$saleValueRaw le 0">
              <set_value name="$unitPriceRaw" exact="0"/>
              <find_buy_offer buyer="$station" tradepartner="$ship" result="$stationBuyOffers" multiple="true"/>
              <do_all exact="$stationBuyOffers.count" counter="$boi">
                <set_value name="$offer" exact="$stationBuyOffers.{$boi}"/>
                <do_if value="$offer.ware == $ware and $offer.unitprice gt $unitPriceRaw">
                  <set_value name="$unitPriceRaw" exact="$offer.unitprice"/>
                </do_if>
              </do_all>
              <do_if value="$unitPriceRaw le 0">
                <set_value name="$unitPriceRaw" exact="$ware.averageprice * 100"/>
              </do_if>
              <set_value name="$saleValueRaw" exact="$amount * $unitPriceRaw"/>
            </do_if>

            <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedSaleValue">
              <param name="number" value="$saleValueRaw/100"/>
              <param name="suffix" value="' Cr'"/>
            </run_actions>
            <set_value name="$logbookMessage" exact="'Queued sale: ' + $amount + ' ' + $ware.name + ' to ' + $station.knownname + '. Expected value: ' + $formattedSaleValue + '.'"/>
          </do_if>
          <do_else>
            <!-- Player-owned station supply: queue-time informational entry only (no money/profit). -->
            <set_value name="$logbookMessage" exact="'Queued delivery: ' + $amount + ' ' + $ware.name + ' to ' + $station.knownname + '.'"/>
          </do_else>

          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$logbookMessage"/>
            <param name="Category" value="'tips'"/>
            <param name="Title" value="{77000,31002} + ': ' + $ship.knownname + ' (' + $ship.idcode + ')'"/>
            <param name="Object" value="$ship"/>
            <param name="Interaction" value="'showonmap'"/>
            <param name="Bonus" value="if $isForeignSale then $saleValueRaw else 0"/>
            <param name="CheckGlobalSettings" value="false"/>
          </run_actions>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <do_if value="$isForeignSale">
              <debug_text text="'[GT-TradeLogging] Miner foreign cargo sale logged for ' + $ship.idcode + ': ' + $amount + ' ' + $ware.name + ' at ' + $station.knownname + ' (Value: ' + ($saleValueRaw / 100) + ' Cr)'" chance="100"/>
            </do_if>
            <do_else>
              <debug_text text="'[GT-TradeLogging] Miner player-station supply logged for ' + $ship.idcode + ': ' + $amount + ' ' + $ware.name + ' to ' + $station.knownname" chance="100"/>
            </do_else>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Trade Completion Logbook Entry -->
    <cue name="LogTradeCompletion" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogTradeCompletion'"/>
      </conditions>
      <actions>
        <!-- Extract completion data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$ware" exact="event.param2.$Ware"/>
        <set_value name="$amount" exact="event.param2.$Amount"/>
        <set_value name="$totalProfit" exact="event.param2.$TotalProfit"/>
        
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_TradeLogging exists -->
        <!-- Initialize logging system if not already done -->
        <do_if value="not global.$GT_TradeLogging.$Enabled?">
          <set_value name="global.$GT_TradeLogging.$Enabled" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$TrainingMessages" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
        </do_if>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$Enabled">
          <!-- Trade completion logbook message disabled by request. -->
          
          <!-- DEBUG MODE: Only log when debug is enabled -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Trade completion logbook message disabled for ' + $ship.knownname + ' (' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Cached Trade Route Logbook Entry -->
    <cue name="LogCachedTrade" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogCachedTrade'"/>
      </conditions>
      <actions>
        <!-- Extract cached trade data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$trade" exact="event.param2.$Trade"/>
        
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_TradeLogging exists -->
        <!-- Initialize logging system if not already done -->
        <do_if value="not global.$GT_TradeLogging.$Enabled?">
          <set_value name="global.$GT_TradeLogging.$Enabled" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$TrainingMessages" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
        </do_if>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$Enabled">
          
          <!-- SAFETY: Validate station owners exist before logging (prevents "nil" display) -->
          <set_value name="$buyStationName" exact="'Unknown Station'"/>
          <set_value name="$sellStationName" exact="'Unknown Station'"/>
          
          <do_if value="$trade.$BuyOffer? and $trade.$BuyOffer.owner? and $trade.$BuyOffer.owner.exists">
            <set_value name="$buyStationName" exact="$trade.$BuyOffer.owner.knownname"/>
          </do_if>
          
          <do_if value="$trade.$SellOffer? and $trade.$SellOffer.owner? and $trade.$SellOffer.owner.exists">
            <set_value name="$sellStationName" exact="$trade.$SellOffer.owner.knownname"/>
          </do_if>
          
          <!-- Write cached trade entry with safe station names -->
          <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
          <!-- Format profit with thousand separators and M suffix according to global settings -->
          <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$formattedProfit">
            <param name="number" value="$trade.$Profit/100"/>
            <param name="suffix" value="' Cr'"/>
          </run_actions>
          <set_value name="$logbookMessage" exact="{77000,3105}.[$trade.$Amount,$trade.$BuyOffer.ware,$buyStationName,$sellStationName,$formattedProfit]"/>

          <set_value name="$logbookOrderName" exact="'GalaxyTrader MK3'"/>
          <do_if value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK4Supply2'">
            <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4-2 Supply'"/>
          </do_if>
          <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK4Supply'">
            <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4 Supply'"/>
          </do_elseif>
          <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply2') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2'))">
            <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4-2 Supply'"/>
          </do_elseif>
          <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'Assist' and $ship.commander? and $ship.commander.defaultorder? and ((@$ship.commander.defaultorder.id == 'GalaxyTraderMK4Supply') or (@$ship.commander.defaultorder.id == 'Assist' and $ship.commander.defaultorder.$baseorder? and @$ship.commander.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply'))">
            <set_value name="$logbookOrderName" exact="'GalaxyTrader MK4 Supply'"/>
          </do_elseif>
          <set_value name="$logbookTitle" exact="$logbookOrderName + ': ' + $ship.knownname + ' (' + $ship.idcode + ')'"/>
          
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$logbookMessage"/>
            <param name="Category" value="'tips'"/>
            <param name="Title" value="$logbookTitle"/>
            <param name="Object" value="$ship"/>
            <param name="Interaction" value="'showonmap'"/>
            <param name="Bonus" value="$trade.$Profit"/>
            <param name="CheckGlobalSettings" value="false"/>
          </run_actions>
          
          <!-- DEBUG MODE: Only log when debug is enabled -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <!-- Format profit for debug output -->
            <run_actions ref="md.GT_Libraries_General.GT_FormatNumber" result="$debugProfit">
              <param name="number" value="$trade.$Profit/100"/>
              <param name="suffix" value="' Cr'"/>
            </run_actions>
            <debug_text text="'[GalaxyTrader MK3] Cached trade logged for ' + $ship.knownname + ': ' + $debugProfit + ' profit'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- PHASE 3: Diff Patch Trade Completion Logging -->
    <cue name="LogCompletedTrade" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <!-- Defensive: This cue is signalled from diff patch trade completion; guard against null param -->
        <set_value name="$hasTradeData" exact="true"/>
        <do_if value="$data == null">
          <set_value name="$hasTradeData" exact="false"/>
        </do_if>
        <do_if value="not $hasTradeData">
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
        <set_value name="$ship" exact="$data.$Ship"/>
        
        <!-- Check if logbook enabled for this ship -->
        <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logEnabled">
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <do_if value="$logEnabled">
          <!-- Build logbook entry using rich diff patch data -->
          <set_value name="$profitCr" exact="$data.$tradeValue / 100"/>
          
          <!-- BUGFIX: Update lifetime profit ONLY when trade actually completes (not at planning time) -->
          <!-- Tables guaranteed valid by GT_InitializeGlobalTables -->
          <set_value name="$lifetimeProfit" exact="0"/>
          <do_if value="global.$GT_TradeLogging.$LifetimeProfit.{$ship}?">
            <set_value name="$lifetimeProfit" exact="global.$GT_TradeLogging.$LifetimeProfit.{$ship}"/>
          </do_if>
          <set_value name="global.$GT_TradeLogging.$LifetimeProfit.{$ship}" exact="$lifetimeProfit + $data.$tradeValue"/>
          <set_value name="$lifetimeProfitCr" exact="global.$GT_TradeLogging.$LifetimeProfit.{$ship} / 100"/>
          
          <!-- Calculate revenue and cost for detailed display -->
          <set_value name="$revenueCr" exact="0"/>
          <set_value name="$costCr" exact="0"/>
          <do_if value="$data.$sellRevenue?">
            <set_value name="$revenueCr" exact="$data.$sellRevenue / 100"/>
          </do_if>
          <do_if value="$data.$purchaseCost?">
            <set_value name="$costCr" exact="$data.$purchaseCost / 100"/>
          </do_if>
          
          <!-- Trade completed logbook message disabled by request. -->
          
          <!-- FIX: Defensive check for race condition (initialization might not have completed yet) -->
          <do_if value="not global.$GT_TradeStats?">
            <set_value name="global.$GT_TradeStats" exact="table[]"/>
            <set_value name="global.$GT_TradeStats.$TotalTrades" exact="0"/>
            <set_value name="global.$GT_TradeStats.$TotalProfit" exact="0"/>
          </do_if>
          
          <!-- Update statistics -->
          <!-- FIX: Use nested do_if to avoid short-circuit evaluation issues -->
          <do_if value="global.$GT_TradeStats?">
            <do_if value="not global.$GT_TradeStats.$TotalTrades?">
              <set_value name="global.$GT_TradeStats.$TotalTrades" exact="0"/>
              <set_value name="global.$GT_TradeStats.$TotalProfit" exact="0"/>
            </do_if>
            
            <set_value name="global.$GT_TradeStats.$TotalTrades" operation="add"/>
            <set_value name="global.$GT_TradeStats.$TotalProfit" exact="global.$GT_TradeStats.$TotalProfit + $profitCr"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-TradeLogging] Diff patch trade logged: ' + $ship.idcode + ' - ' + $profitCr + ' Cr (Lifetime: ' + $lifetimeProfitCr + ' Cr, Total trades: ' + global.$GT_TradeStats.$TotalTrades + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- Training Started Message (Immersive) -->
    <cue name="LogTrainingStarted" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogTrainingStarted'"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeLogging] LogTrainingStarted cue triggered'" chance="100"/>
        </do_if>
        
        <!-- Extract training data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$pilot" exact="event.param2.$Pilot"/>
        <set_value name="$station" exact="event.param2.$Station"/>
        <set_value name="$trainingLevel" exact="event.param2.$TrainingLevel"/>
        <set_value name="$duration" exact="event.param2.$Duration"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeLogging] Training data extracted - Ship: ' + $ship.knownname + ', Pilot: ' + $pilot.name + ', Station: ' + $station.knownname + ', Level: ' + $trainingLevel" chance="100"/>
        </do_if>
        
        <!-- SIMPLIFIED: Initialization guarantees global.$GT_TradeLogging exists -->
        <!-- Initialize logging system if not already done -->
        <do_if value="not global.$GT_TradeLogging.$Enabled?">
          <set_value name="global.$GT_TradeLogging.$Enabled" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$TrainingMessages" exact="true"/>
          <set_value name="global.$GT_TradeLogging.$LifetimeProfit" exact="table[]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradeLogging] Training logging system auto-initialized'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeLogging] Training messages enabled: ' + global.$GT_TradeLogging.$TrainingMessages" chance="100"/>
        </do_if>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$TrainingMessages">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradeLogging] Training message will be created and sent to logbook'" chance="100"/>
          </do_if>
          
          <!-- Get pilot title for the level -->
          <set_value name="$pilotTitle" exact="'Advanced Trader'"/>
          <do_if value="global.$GT_Config.$XP.$TraderTitles.{$trainingLevel}?">
            <set_value name="$pilotTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$trainingLevel}"/>
          </do_if>
          
          <!-- Detect Trading Academy enrollment. Academy courses are
               player-funded, on-demand training (not the natural-XP
               certification ladder), so they get their own dedicated
               role-play logbook entry that calls out the paid tuition
               and the chosen course explicitly. -->
          <set_value name="$isAcademyEnrollment" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>
          
          <do_if value="$isAcademyEnrollment">
            <!-- Pull cost + duration from the academy enrollment record so
                 the message reflects what the player actually agreed to in
                 the submenu, not whatever HandleStartTraining stored after
                 type promotion. $AcademyEnrollment.$Cost is a plain integer
                 in centi-credits (Lua pre-multiplied by 100 to round-trip
                 cleanly through the player.entity blackboard); divide by
                 100 to display whole credits. $AcademyEnrollment.$Duration
                 is a plain integer in seconds. -->
            <set_value name="$academyCostCr" exact="(global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Cost / 100)i"/>
            <set_value name="$academyDurationMin" exact="(global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Duration / 60)i"/>
            <do_if value="$academyDurationMin lt 1">
              <set_value name="$academyDurationMin" exact="1"/>
            </do_if>
            
            <!-- Build dedicated academy enrollment message: same role-play
                 voice as 3200 (pilot to commander) but tailored to the
                 paid academy track. Placeholders:
                   %1 = player name      %2 = academy station name
                   %3 = course title     %4 = tuition (whole Cr)
                   %5 = duration min     %6 = pilot name
                   %7 = ship name -->
            <set_value name="$logbookMessage" exact="{77000,3226}.[player.name, $station.knownname, $pilotTitle, $academyCostCr, $academyDurationMin, $pilot.name, $ship.knownname]"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-TradeLogging] Academy training message built (cost=' + $academyCostCr + ' Cr, duration=' + $academyDurationMin + ' min, course=' + $pilotTitle + '): ' + $logbookMessage" chance="100"/>
            </do_if>
            
            <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
              <param name="Message" value="$logbookMessage"/>
              <param name="Category" value="'upkeep'"/>
              <param name="Title" value="'Trading Academy Enrollment: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
              <param name="Object" value="$ship"/>
              <param name="Interaction" value="'showonmap'"/>
              <param name="CheckGlobalSettings" value="false"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-TradeLogging] Academy enrollment logbook entry created for ' + $pilot.name + ' on ' + $ship.knownname" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Calculate duration in minutes -->
            <set_value name="$durationMinutes" exact="($duration / 60)i"/>
            
            <!-- Get training cost (stored when training started) -->
            <set_value name="$trainingCost" exact="0"/>
            <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCost?">
              <set_value name="$trainingCost" exact="global.$GT_Pilots.{$pilot}.$TrainingCost"/>
            </do_if>
            <set_value name="$trainingCostCr" exact="($trainingCost / 100)"/>
            
            <!-- Build immersive training message -->
            <set_value name="$message" exact="{77000,3200}.[player.name,$pilotTitle,$durationMinutes,$station.knownname,$pilot.name,$ship.knownname]"/>
            
            <!-- Append cost to message at the end (before signature) -->
            <do_if value="$trainingCostCr gt 0">
              <set_value name="$costText" exact="{77000,3224}.[$trainingCostCr]"/>
              <set_value name="$message" exact="$message + '\n\n' + $costText"/>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-TradeLogging] Training message built: ' + $message" chance="100"/>
            </do_if>
            
            <!-- Write to ship logbook -->
            <!-- Construct logbook message using TextDB syntax (vanilla pattern) -->
            <set_value name="$logbookMessage" exact="{77000,3200}.[player.name,$pilotTitle,$durationMinutes,$station.knownname,$pilot.name,$ship.knownname]"/>
            
            <!-- Append cost to logbook message at the end (before signature) -->
            <do_if value="$trainingCostCr gt 0">
              <set_value name="$costText" exact="{77000,3224}.[$trainingCostCr]"/>
              <set_value name="$logbookMessage" exact="$logbookMessage + '\n\n' + $costText"/>
            </do_if>
            
            <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
              <param name="Message" value="$logbookMessage"/>
              <param name="Category" value="'upkeep'"/>
              <param name="Title" value="'Training Notice: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
              <param name="Object" value="$ship"/>
              <param name="Interaction" value="'showonmap'"/>
              <param name="CheckGlobalSettings" value="false"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-TradeLogging] Training started logbook entry created for ' + $pilot.name + ' on ' + $ship.knownname" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradeLogging] Training messages are DISABLED - no logbook entry will be created'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>
    
    <!-- Training En Route Message -->
    <cue name="LogTrainingEnRoute" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogTrainingEnRoute'"/>
      </conditions>
      <actions>
        <!-- Extract training data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$pilot" exact="event.param2.$Pilot"/>
        <set_value name="$station" exact="event.param2.$Station"/>
        <set_value name="$arrivalTime" exact="event.param2.$ArrivalTime"/>
        <set_value name="$duration" exact="event.param2.$Duration"/>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$TrainingMessages">
          
          <!-- Calculate times in minutes -->
          <set_value name="$arrivalMinutes" exact="($arrivalTime / 60)i"/>
          <set_value name="$durationMinutes" exact="($duration / 60)i"/>
          
          <!-- Build en route message -->
          <set_value name="$message" exact="{77000,3203}.[player.name,$station.knownname,$arrivalMinutes,$durationMinutes,$pilot.name,$ship.knownname]"/>
          
          <!-- Write to ship logbook -->
          <write_to_logbook 
            category="upkeep" 
            title="'Training Update: ' + $pilot.name + ' (' + $ship.knownname + ')'" 
            interaction="showonmap" 
            object="$ship" 
            text="$message"
            highlighted="false"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Training en route message logged for ' + $pilot.name + ' on ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Training Completed Message (Success) -->
    <cue name="LogTrainingCompleted" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogTrainingCompleted'"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeLogging] LogTrainingCompleted cue triggered'" chance="100"/>
        </do_if>
        
        <!-- Extract completion data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$pilot" exact="event.param2.$Pilot"/>
        <set_value name="$newLevel" exact="event.param2.$Level"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-TradeLogging] Training completion data - Ship: ' + $ship.knownname + ', Pilot: ' + $pilot.name + ', New Level: ' + $newLevel" chance="100"/>
        </do_if>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$TrainingMessages">
          
          <!-- Get pilot's actual current skill level from their XP -->
          <set_value name="$currentXP" exact="@global.$GT_Pilots.{$pilot}.$XP"/>
          <set_value name="$actualSkillLevel" exact="1"/>
          <do_all exact="15" counter="$skillLevel">
            <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
              <set_value name="$actualSkillLevel" exact="$skillLevel"/>
            </do_if>
          </do_all>
          
          <!-- Map skill level to unified title index: floor(level/3)+1 -->
          <set_value name="$titleIndex" exact="($actualSkillLevel / 3)i + 1"/>
          <do_if value="$titleIndex lt 1">
            <set_value name="$titleIndex" exact="1"/>
          </do_if>
          <do_if value="$titleIndex gt global.$GT_Config.$XP.$TraderTitles.keys.count">
            <set_value name="$titleIndex" exact="global.$GT_Config.$XP.$TraderTitles.keys.count"/>
          </do_if>
          
          <!-- Get pilot title for the correct index -->
          <set_value name="$pilotTitle" exact="'Advanced Trader'"/>
          <do_if value="global.$GT_Config.$XP.$TraderTitles.{$titleIndex}?">
            <set_value name="$pilotTitle" exact="global.$GT_Config.$XP.$TraderTitles.{$titleIndex}"/>
          </do_if>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-TradeLogging] Training completion: Skill Level ' + $actualSkillLevel + ' Title Index ' + $titleIndex + ' Title: ' + $pilotTitle" chance="100"/>
          </do_if>
          
          <!-- Check if bonus levels were gained from blocked XP -->
          <set_value name="$bonusLevels" exact="0"/>
          <do_if value="$actualSkillLevel gt $newLevel">
            <set_value name="$bonusLevels" exact="$actualSkillLevel - $newLevel"/>
          </do_if>
          
          <!-- Build success message -->
          <set_value name="$message" exact="{77000,3201}.[player.name,$pilotTitle,$pilot.name,$ship.knownname]"/>
          
          <!-- Append bonus information if bonus levels were gained -->
          <do_if value="$bonusLevels gt 0">
            <set_value name="$pluralS" exact="''"/>
            <do_if value="$bonusLevels gt 1">
              <set_value name="$pluralS" exact="'s'"/>
            </do_if>
            <set_value name="$bonusText" exact="{77000,3225}.[$bonusLevels, $pluralS, $actualSkillLevel]"/>
            <set_value name="$message" exact="$message + '\n\n' + $bonusText"/>
          </do_if>
          
          <!-- Create green color string for "Training Success:" text -->
          <!-- Format: \033#AARRGGBB# where AA=Alpha, RR=Red, GG=Green, BB=Blue -->
          <!-- Green color: Alpha=255(FF), Red=0(00), Green=204(CC), Blue=0(00) -->
          <set_value name="$greenColor" exact="'\033#FF00CC00#'"/>
          <set_value name="$colorReset" exact="'\033X'"/>
          
          <!-- Apply green color to "Training Success:" prefix -->
          <set_value name="$coloredTitle" exact="$greenColor + 'Training Success: ' + $colorReset + $pilot.name + ' (' + $ship.knownname + ')'"/>
          
          <!-- Write to ship logbook with bonus indicator -->
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$message"/>
            <param name="Category" value="'upkeep'"/>
            <param name="Title" value="$coloredTitle"/>
            <param name="Object" value="$ship"/>
            <param name="Interaction" value="'showonmap'"/>
            <param name="CheckGlobalSettings" value="false"/>
          </run_actions>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Training completed message logged for ' + $pilot.name + ' on ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Training Interrupted Message -->
    <cue name="LogTrainingInterrupted" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_LogTrainingInterrupted'"/>
      </conditions>
      <actions>
        <!-- Extract interruption data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$pilot" exact="event.param2.$Pilot"/>
        <set_value name="$reason" exact="event.param2.$Reason"/>
        
        <!-- Only log if enabled -->
        <do_if value="global.$GT_TradeLogging.$TrainingMessages">
          
          <!-- Build interruption message -->
          <set_value name="$message" exact="{77000,3202}.[player.name,$pilot.name,$ship.knownname]"/>
          
          <!-- Write to ship logbook -->
          <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
            <param name="Message" value="$message"/>
            <param name="Category" value="'alerts'"/>
            <param name="Title" value="'Training Interrupted: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
            <param name="Object" value="$ship"/>
            <param name="Interaction" value="'showonmap'"/>
            <param name="CheckGlobalSettings" value="false"/>
          </run_actions>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Training interrupted message logged for ' + $pilot.name + ' on ' + $ship.knownname" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Auto-Repair Initiated Logbook Entry -->
    <cue name="LogAutoRepair" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_AutoRepair_Log'"/>
      </conditions>
      <actions>
        <!-- Extract repair data -->
        <set_value name="$ship" exact="event.param2.$Ship"/>
        <set_value name="$station" exact="event.param2.$Station"/>
        <set_value name="$hullBefore" exact="event.param2.$HullBefore"/>
        <set_value name="$pilotLevel" exact="event.param2.$PilotLevel"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-AutoRepair] Logging repair initiation for ' + $ship.knownname + ' at ' + $station.knownname" chance="100"/>
        </do_if>
        
        <!-- Build repair message -->
        <set_value name="$message" exact="'=== AUTO-REPAIR INITIATED ===\n\n'"/>
        <set_value name="$message" exact="$message + 'Ship: ' + $ship.knownname + ' (' + $ship.idcode + ')\n'"/>
        <set_value name="$message" exact="$message + 'Pilot: ' + $ship.pilot.name + ' (Level ' + $pilotLevel + ')\n'"/>
        <set_value name="$message" exact="$message + 'Hull Damage Detected: ' + $hullBefore + '%\n'"/>
        <set_value name="$message" exact="$message + 'Repair Station: ' + $station.knownname + '\n'"/>
        <!-- Determine station type -->
        <set_value name="$stationType" exact="'Unknown'"/>
        <do_if value="$station.isshipyard">
          <set_value name="$stationType" exact="'Shipyard (Schiffswerft)'"/>
        </do_if>
        <do_elseif value="$station.iswharf">
          <set_value name="$stationType" exact="'Wharf (Raumdock)'"/>
        </do_elseif>
        <do_elseif value="$station.isequipmentdock">
          <set_value name="$stationType" exact="'Equipment Dock (AusrÃ¼stungsdock)'"/>
        </do_elseif>
        <set_value name="$message" exact="$message + 'Station Type: ' + $stationType + '\n'"/>
        <set_value name="$message" exact="$message + 'Location: ' + $station.sector.knownname + '\n\n'"/>
        <set_value name="$message" exact="$message + 'The ship has been automatically sent for repairs.\n'"/>
        <set_value name="$message" exact="$message + 'Trading will resume after repairs are completed.'"/>
        
        <!-- Write to player logbook (not ship logbook) -->
        <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
          <param name="Message" value="$message"/>
          <param name="Category" value="'general'"/>
          <param name="Title" value="'GalaxyTrader MK3: Auto-Repair (' + $ship.knownname + ')'"/>
          <param name="Object" value="player.entity"/>
          <param name="Interaction" value="'showonmap'"/>
          <param name="CheckGlobalSettings" value="false"/>
        </run_actions>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Auto-repair log entry created for ' + $ship.knownname" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Toggle Trade Logging -->
    <cue name="ToggleTradeLogging" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_ToggleTradeLogging'"/>
      </conditions>
      <actions>
        <set_value name="global.$GT_TradeLogging.$Enabled" exact="not global.$GT_TradeLogging.$Enabled"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Trade logging ' + if global.$GT_TradeLogging.$Enabled then 'enabled' else 'disabled'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Toggle Training Messages -->
    <cue name="ToggleTrainingMessages" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeLogging_ToggleTrainingMessages'"/>
      </conditions>
      <actions>
        <set_value name="global.$GT_TradeLogging.$TrainingMessages" exact="not global.$GT_TradeLogging.$TrainingMessages"/>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Training messages ' + if global.$GT_TradeLogging.$TrainingMessages then 'enabled' else 'disabled'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
  </cues>
</mdscript> <?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_TradeSearch_Scheduler" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Two-phase scheduler:
         GT_Search_Request -> GT_Search_Go(phase=cache/live/clearance) -> GT_Search_Done

         Key guarantees:
         1) Home-sector live-refresh coalescing:
            If a live refresh is already active for home sector H, cache-miss ships for H wait
            (keepalive + reset wakeup) instead of queueing duplicate live refreshes.
         2) Fairness across homes:
            Live dispatch is round-robin by home sector, so one fleet/home cannot starve others.
         3) sell_only (cargo clearance) skips cache and uses the dedicated clearance live pool. -->

    <cue name="Init" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
      </actions>
    </cue>

    <cue name="InitSearchSemaphore" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore" exact="table[]"/>
        </do_if>

        <!-- Legacy single-pool fields from old saves -->
        <do_if value="global.$GT_SearchSemaphore.$Queue?"><remove_value name="global.$GT_SearchSemaphore.$Queue"/></do_if>
        <do_if value="global.$GT_SearchSemaphore.$Queued?"><remove_value name="global.$GT_SearchSemaphore.$Queued"/></do_if>
        <do_if value="global.$GT_SearchSemaphore.$ActiveShips?"><remove_value name="global.$GT_SearchSemaphore.$ActiveShips"/></do_if>
        <do_if value="global.$GT_SearchSemaphore.$Active?"><remove_value name="global.$GT_SearchSemaphore.$Active"/></do_if>
        <do_if value="global.$GT_SearchSemaphore.$MaxConcurrent?"><remove_value name="global.$GT_SearchSemaphore.$MaxConcurrent"/></do_if>
        <do_if value="global.$GT_SearchSemaphore.$DispatchScheduled?"><remove_value name="global.$GT_SearchSemaphore.$DispatchScheduled"/></do_if>

        <!-- Cache pool -->
        <!-- Always reset transient scheduler state on load/restart.
             In-flight and queued search bookkeeping cannot be resumed safely after save/load. -->
        <set_value name="global.$GT_SearchSemaphore.$CacheQueue" exact="[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheActiveShips" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheActive" exact="0"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheDispatchScheduled" exact="false"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheReadCursorByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheRetryPassCount" exact="table[]"/>

        <!-- Live pool (home-sector fair queue). Always reset active state: in-flight searches don't survive save/load. -->
        <set_value name="global.$GT_SearchSemaphore.$LiveQueueByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveActiveShips" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveActive" exact="0"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveHomeActive" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveDispatchScheduled" exact="false"/>

        <!-- MK4 dedicated live pool (isolated from generic live slots) -->
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" exact="0"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentMK4Live" exact="2"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveDispatchScheduled" exact="false"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterTickScheduled" exact="false"/>

        <!-- MK4-2 dedicated live pool (isolated from MK4 v1 and MK3) -->
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" exact="0"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentMK42Live" exact="2"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveDispatchScheduled" exact="false"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterTickScheduled" exact="false"/>

        <!-- Clearance pool (dedicated sell-only live slot) -->
        <set_value name="global.$GT_SearchSemaphore.$ClearanceQueue" exact="[]"/>
        <set_value name="global.$GT_SearchSemaphore.$ClearanceQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$ClearanceActiveShips" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$ClearanceActive" exact="0"/>
        <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentClearance" exact="1"/>
        <set_value name="global.$GT_SearchSemaphore.$ClearanceDispatchScheduled" exact="false"/>

        <!-- Home refresh waiters (ships waiting for same-home live refresh completion) -->
        <set_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$LiveWaiterTickScheduled" exact="false"/>

        <!-- MK3 cache-saturation waiters (pool has entries but per-ship read returned 0) -->
        <set_value name="global.$GT_SearchSemaphore.$CacheWaitersByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt" exact="table[]"/>
        <!-- First time a ship entered cache-waiter for this home; NOT reset on periodic wake (starve detection). -->
        <set_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt" exact="table[]"/>
        <!-- One coordinated live refresh per home while cache rows exist but no ship can read them. -->
        <set_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$CacheWaiterTickScheduled" exact="false"/>

        <!-- Cross-pool state -->
        <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip" exact="table[]"/>

        <set_value name="$maxConcurrentCache" exact="5"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches?">
          <set_value name="$maxConcurrentCache" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentCacheSearches"/>
        </do_if>
        <do_if value="$maxConcurrentCache lt 1"><set_value name="$maxConcurrentCache" exact="1"/></do_if>
        <do_if value="$maxConcurrentCache gt 10"><set_value name="$maxConcurrentCache" exact="10"/></do_if>
        <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentCache" exact="$maxConcurrentCache"/>

        <set_value name="$maxConcurrentLive" exact="1"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches?">
          <set_value name="$maxConcurrentLive" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentLiveSearches"/>
        </do_if>
        <do_if value="$maxConcurrentLive lt 1"><set_value name="$maxConcurrentLive" exact="1"/></do_if>
        <do_if value="$maxConcurrentLive gt 10"><set_value name="$maxConcurrentLive" exact="10"/></do_if>
        <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentLive" exact="$maxConcurrentLive"/>
      </actions>
    </cue>

    <!-- Legacy compatibility: older call sites can still enqueue here -->
    <cue name="Enqueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$req" exact="event.param"/>
        <do_if value="$req? and $req.$Ship? and $req.$Ship.exists">
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="$req"/>
        </do_if>
      </actions>
    </cue>

    <!-- Legacy compatibility: old delayed entrypoint now forwards to request -->
    <cue name="SearchTradeRoutes_Delayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <set_value name="$req" exact="event.param"/>
        <do_if value="$req? and $req.$Ship? and $req.$Ship.exists">
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="$req"/>
        </do_if>
      </actions>
    </cue>

    <!-- Compatibility kick points -->
    <cue name="Tick" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
      </actions>
    </cue>

    <cue name="ProcessWorkQueueDelayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
      </actions>
    </cue>

    <cue name="HandleSearchRequest" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Search_Request'"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$ship" exact="@$params.$Ship"/>
        <set_value name="$enqueueAllowed" exact="true"/>
        <set_value name="$targetPhase" exact="'cache'"/>
        <set_value name="$searchMode" exact="if $params? and $params.$SearchMode? then @$params.$SearchMode else 'buy_and_sell'"/>
        <set_value name="$forceLiveSearch" exact="if $params? and $params.$ForceLiveSearch? then @$params.$ForceLiveSearch else false"/>
        <set_value name="$useMK4LivePool" exact="if $params? and $params.$SearchPool? and $params.$SearchPool == 'mk4_supply' then true else false"/>
        <set_value name="$useMK42LivePool" exact="if $params? and $params.$SearchPool? and $params.$SearchPool == 'mk4_supply_v2' then true else false"/>

        <!-- Resolve home sector from request.
             Order: params.$HomeBase > GT_AIParameters > ship.defaultorder.$home > ship.sector.
             InternalQueueShip/gt_trading_execution send only $Ship; GT_AIParameters may have HomeBase from prior registration. -->
        <set_value name="$homeBase" exact="if $params? and $params.$HomeBase? then @$params.$HomeBase else (if $ship? and global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$HomeBase? then @global.$GT_AIParameters.{$ship}.$HomeBase else (if $ship? and $ship.defaultorder and $ship.defaultorder.$home? then @$ship.defaultorder.$home else (if $ship? then $ship.sector else null)))"/>
        <set_value name="$homeSector" exact="if $homeBase? and $homeBase.isclass.station then $homeBase.sector else (if $homeBase? and $homeBase.isclass.sector then $homeBase else (if $ship? and $ship.defaultorder and $ship.defaultorder.$home? and $ship.defaultorder.$home.sector? then @$ship.defaultorder.$home.sector else (if $ship? then $ship.sector else null)))"/>
        <do_if value="not $homeSector? or not $homeSector.exists">
          <set_value name="$homeSector" exact="if $ship? and $ship.defaultorder and $ship.defaultorder.$home? and $ship.defaultorder.$home.sector? then @$ship.defaultorder.$home.sector else (if $ship? then $ship.sector else null)"/>
        </do_if>

        <do_if value="not $ship? or not $ship.exists">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'no_ship'"/>
        </do_if>

        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore?">
          <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterStartedAt?">
            <set_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
            <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
          </do_if>
          <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterPassCount?">
            <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount" exact="table[]"/>
          </do_if>
        </do_if>

        <!-- Woken home refresh waiters: retry cache first (pool may have been repopulated since parking). -->
        <set_value name="$cacheWakeRetry" exact="false"/>
        <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
          <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
          <set_value name="$cacheWakeRetry" exact="true"/>
          <set_value name="$forceLiveSearch" exact="false"/>
        </do_if>

        <!-- Force-live requests skip cache and go directly to normal live pool.
             sell_only (clearance) is live-only: one ware, cheap scan, stale cache not used. -->
        <do_if value="$searchMode == 'sell_only'">
          <set_value name="$targetPhase" exact="'clearance'"/>
        </do_if>
        <do_elseif value="$forceLiveSearch and not $cacheWakeRetry">
          <set_value name="$targetPhase" exact="'live'"/>
        </do_elseif>

        <!-- Cross-pool dedup + validation -->
        <set_value name="$rejectReason" exact="''"/>
        <!-- Self-heal stale per-ship live-active state before dedup checks.
             Prevents permanent "REJECTED reason=LiveActiveShips" after interrupted transitions. -->
        <do_if value="$enqueueAllowed and $ship? and $ship.exists and global.$GT_SearchSemaphore?">
          <set_value name="$liveActiveEntry" exact="if global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}? then @global.$GT_SearchSemaphore.$LiveActiveShips.{$ship} else null"/>
          <set_value name="$liveStartedAt" exact="if $liveActiveEntry? and $liveActiveEntry.$StartedAt? then @$liveActiveEntry.$StartedAt else null"/>
          <set_value name="$staleLiveActive" exact="false"/>
          <do_if value="$liveActiveEntry? and ($liveStartedAt == null or (player.age - $liveStartedAt) gt 60s)">
            <set_value name="$staleLiveActive" exact="true"/>
          </do_if>
          <do_if value="$staleLiveActive">
            <do_if value="global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
              <remove_value name="global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}"/>
              <do_if value="global.$GT_SearchSemaphore.$LiveActive gt 0">
                <set_value name="global.$GT_SearchSemaphore.$LiveActive" operation="subtract"/>
              </do_if>
            </do_if>
            <do_if value="global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.keys.count gt 0">
              <set_value name="$liveHomeKeys" exact="global.$GT_SearchSemaphore.$LiveHomeActive.keys.list"/>
              <do_all exact="$liveHomeKeys.count" counter="$lhki">
                <set_value name="$liveHomeKey" exact="$liveHomeKeys.{$lhki}"/>
                <do_if value="$liveHomeKey? and global.$GT_SearchSemaphore.$LiveHomeActive.{$liveHomeKey}? and @global.$GT_SearchSemaphore.$LiveHomeActive.{$liveHomeKey} == $ship">
                  <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$liveHomeKey}"/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
              <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleSearchRequest: Cleared stale live-active state for ' + $ship.idcode + ' (startedAt=' + (if $liveStartedAt? then $liveStartedAt else 'null') + ', age=' + player.age + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Self-heal stale MK4 per-ship state before dedup checks.
             Prevents permanent "REJECTED reason=MK4LiveActiveShips/MK4LiveQueued" when legacy entries remain. -->
        <do_if value="$enqueueAllowed and $ship? and $ship.exists and global.$GT_SearchSemaphore?">
          <set_value name="$mk4LiveActiveEntry" exact="if global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}? then @global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship} else null"/>
          <set_value name="$mk4LiveStartedAt" exact="if $mk4LiveActiveEntry? and $mk4LiveActiveEntry.$StartedAt? then @$mk4LiveActiveEntry.$StartedAt else null"/>
          <set_value name="$staleMK4LiveActive" exact="false"/>
          <do_if value="$mk4LiveActiveEntry? and ($mk4LiveStartedAt == null or (player.age - $mk4LiveStartedAt) gt 60s)">
            <set_value name="$staleMK4LiveActive" exact="true"/>
          </do_if>
          <do_if value="$staleMK4LiveActive">
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
              <remove_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}"/>
              <do_if value="global.$GT_SearchSemaphore.$MK4LiveActive gt 0">
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" operation="subtract"/>
              </do_if>
            </do_if>
            <do_if value="global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}? and (@global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship} == 'mk4live_active' or @global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship} == 'mk4live_queued')">
              <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleSearchRequest: Cleared stale MK4 live-active state for ' + $ship.idcode + ' (startedAt=' + (if $mk4LiveStartedAt? then $mk4LiveStartedAt else 'null') + ', age=' + player.age + ')'" chance="100"/>
            </do_if>
          </do_if>
          <set_value name="$staleMK4Queued" exact="false"/>
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
            <set_value name="$mk4StillQueued" exact="false"/>
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.keys.count gt 0">
              <set_value name="$mk4HomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.keys.list"/>
              <do_all exact="$mk4HomeKeys.count" counter="$mk4hki">
                <set_value name="$mk4hk" exact="$mk4HomeKeys.{$mk4hki}"/>
                <do_if value="$mk4hk? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4hk}? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4hk}.count gt 0">
                  <do_all exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4hk}.count" counter="$mk4qi">
                    <do_if value="@global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4hk}.{$mk4qi}.$Ship == $ship">
                      <set_value name="$mk4StillQueued" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$mk4StillQueued">
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $mk4StillQueued">
              <set_value name="$staleMK4Queued" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="$staleMK4Queued">
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}? and @global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship} == 'mk4live_queued'">
              <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleSearchRequest: Cleared stale MK4 queued marker for ' + $ship.idcode + ' (age=' + player.age + ')'" chance="100"/>
            </do_if>
          </do_if>
          <set_value name="$staleLiveQueued" exact="false"/>
          <do_if value="global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
            <set_value name="$liveStillQueuedReq" exact="false"/>
            <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.keys.count gt 0">
              <set_value name="$liveHomeKeysReq" exact="global.$GT_SearchSemaphore.$LiveQueueByHome.keys.list"/>
              <do_all exact="$liveHomeKeysReq.count" counter="$liveHkiReq">
                <set_value name="$liveHkReq" exact="$liveHomeKeysReq.{$liveHkiReq}"/>
                <do_if value="$liveHkReq? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveHkReq}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveHkReq}.count gt 0">
                  <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveHkReq}.count" counter="$liveQiReq">
                    <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveHkReq}.{$liveQiReq}.$Ship == $ship">
                      <set_value name="$liveStillQueuedReq" exact="true"/>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$liveStillQueuedReq">
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <do_if value="not $liveStillQueuedReq">
              <set_value name="$staleLiveQueued" exact="true"/>
            </do_if>
          </do_if>
          <do_if value="$staleLiveQueued">
            <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}? and @global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship} == 'live_queued'">
              <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
            </do_if>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleSearchRequest: Cleared stale live queued marker for ' + $ship.idcode + ' (age=' + player.age + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <!-- Self-heal orphaned phase state markers when ship is not present in any queue/active table.
             Prevents permanent dedup rejection caused by stale PhaseStateByShip entries. -->
        <do_if value="$enqueueAllowed and $ship? and $ship.exists and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
          <set_value name="$phaseHasBackingState" exact="false"/>
          <do_if value="global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState and global.$GT_SearchSemaphore.$ClearanceActiveShips? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}?">
            <set_value name="$phaseHasBackingState" exact="true"/>
          </do_if>
          <do_if value="not $phaseHasBackingState">
            <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleSearchRequest: Cleared orphaned phase-state marker for ' + $ship.idcode + ' (age=' + player.age + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$enqueueAllowed and (not $homeSector? or not $homeSector.exists)">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'no_home_sector'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'PhaseStateByShip'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'CacheActiveShips'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'CacheQueued'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'LiveActiveShips'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'LiveQueued'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'MK42LiveActiveShips'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$MK42LiveQueued? and global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'MK42LiveQueued'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'MK4LiveActiveShips'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'MK4LiveQueued'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$ClearanceActiveShips? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'ClearanceActiveShips'"/>
        </do_if>
        <do_if value="$enqueueAllowed and global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}?">
          <set_value name="$enqueueAllowed" exact="false"/>
          <set_value name="$rejectReason" exact="'ClearanceQueued'"/>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging and $ship?">
          <set_value name="$homeName" exact="if $homeSector? and $homeSector.exists then @$homeSector.knownname else 'null'"/>
          <do_if value="$enqueueAllowed">
            <debug_text text="'[GT-Scheduler] HandleSearchRequest age=' + player.age + ' ship=' + $ship.idcode + ' mode=' + $searchMode + ' phase=' + $targetPhase + ' home=' + $homeName + ' -> ENQUEUED ' + $targetPhase" chance="100"/>
          </do_if>
          <do_else>
            <debug_text text="'[GT-Scheduler] HandleSearchRequest age=' + player.age + ' ship=' + $ship.idcode + ' mode=' + $searchMode + ' -> REJECTED reason=' + $rejectReason" chance="100"/>
          </do_else>
        </do_if>

        <do_if value="$enqueueAllowed">
          <do_if value="$searchMode == 'sell_only'">
            <set_value name="$clearanceParams" exact="if $params? then $params else table[$Ship = $ship]"/>
            <set_value name="$clearanceParams.$Phase" exact="'live'"/>
            <set_value name="$clearanceParams.$HomeSector" exact="$homeSector"/>
            <set_value name="$clearanceParams.$SearchMode" exact="'sell_only'"/>
            <set_value name="$clearanceParams.$ForceLiveSearch" exact="true"/>
            <append_to_list name="global.$GT_SearchSemaphore.$ClearanceQueue" exact="table[
              $Ship = $ship,
              $Params = $clearanceParams,
              $HomeSector = $homeSector,
              $EnqueuedAt = player.age
            ]"/>
            <set_value name="global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}" exact="true"/>
            <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'clearance_queued'"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
          </do_if>
          <do_elseif value="$targetPhase == 'live'">
            <do_if value="$useMK42LivePool">
              <do_if value="not global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}?">
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}" exact="[]"/>
              </do_if>
              <set_value name="$mk42LiveQueueEntry" exact="table[
                $Ship = $ship,
                $Params = $params,
                $HomeSector = $homeSector,
                $EnqueuedAt = player.age
              ]"/>
              <set_value name="$shipAlreadyInMK42LiveQueue" exact="false"/>
              <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count" counter="$mk42lqiDup">
                  <do_if value="@global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.{$mk42lqiDup}.$Ship == $ship">
                    <set_value name="$shipAlreadyInMK42LiveQueue" exact="true"/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $shipAlreadyInMK42LiveQueue">
                <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}" exact="$mk42LiveQueueEntry"/>
              </do_if>
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}" exact="true"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'mk42live_queued'"/>
              <do_if value="not global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
              <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
            </do_if>
            <do_elseif value="$useMK4LivePool">
              <do_if value="not global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}?">
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}" exact="[]"/>
              </do_if>
              <set_value name="$mk4LiveQueueEntry" exact="table[
                $Ship = $ship,
                $Params = $params,
                $HomeSector = $homeSector,
                $EnqueuedAt = player.age
              ]"/>
              <set_value name="$shipAlreadyInMK4LiveQueue" exact="false"/>
              <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count" counter="$mk4lqiDup">
                  <do_if value="@global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.{$mk4lqiDup}.$Ship == $ship">
                    <set_value name="$shipAlreadyInMK4LiveQueue" exact="true"/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $shipAlreadyInMK4LiveQueue">
                <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}" exact="$mk4LiveQueueEntry"/>
              </do_if>
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}" exact="true"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'mk4live_queued'"/>
              <do_if value="not global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
              <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
            </do_elseif>
            <do_else>
              <do_if value="not global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}?">
                <set_value name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}" exact="[]"/>
              </do_if>
              <set_value name="$liveQueueEntry" exact="table[
                $Ship = $ship,
                $Params = $params,
                $HomeSector = $homeSector,
                $EnqueuedAt = player.age
              ]"/>
              <set_value name="$shipAlreadyInLiveQueue" exact="false"/>
              <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$lqiDup">
                  <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$lqiDup}.$Ship == $ship">
                    <set_value name="$shipAlreadyInLiveQueue" exact="true"/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $shipAlreadyInLiveQueue">
                <append_to_list name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}" exact="$liveQueueEntry"/>
              </do_if>
              <set_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}" exact="true"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'live_queued'"/>
              <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
              <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
            </do_else>
          </do_elseif>
          <do_else>
            <append_to_list name="global.$GT_SearchSemaphore.$CacheQueue" exact="table[
              $Ship = $ship,
              $Params = $params,
              $HomeSector = $homeSector,
              $EnqueuedAt = player.age
            ]"/>
            <set_value name="global.$GT_SearchSemaphore.$CacheQueued.{$ship}" exact="true"/>
            <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'cache_queued'"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          </do_else>
        </do_if>

        <!-- When rejected for no_home_sector: release lock (from ProcessDelayedTradeRequest) and signal ship so AI can retry -->
        <do_if value="not $enqueueAllowed and $rejectReason == 'no_home_sector' and $ship?">
          <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
            <param name="ship" value="$ship"/>
            <param name="reason" value="'no_home_sector'"/>
          </run_actions>
          <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_home_sector'" delay="1ms"/>
        </do_if>
        <!-- Ship already queued/active in scheduler: tell AI to keep waiting and nudge dispatch. -->
        <do_if value="not $enqueueAllowed and $ship? and $ship.exists and ($rejectReason == 'CacheQueued' or $rejectReason == 'LiveQueued' or $rejectReason == 'MK4LiveQueued' or $rejectReason == 'MK42LiveQueued' or $rejectReason == 'ClearanceQueued' or $rejectReason == 'LiveActiveShips' or $rejectReason == 'MK4LiveActiveShips' or $rejectReason == 'MK42LiveActiveShips' or $rejectReason == 'ClearanceActiveShips')">
          <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
          <do_if value="$rejectReason == 'CacheQueued'">
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          </do_if>
          <do_elseif value="$rejectReason == 'MK42LiveQueued' or $rejectReason == 'MK42LiveActiveShips'">
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
          </do_elseif>
          <do_elseif value="$rejectReason == 'MK4LiveQueued' or $rejectReason == 'MK4LiveActiveShips'">
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
          </do_elseif>
          <do_elseif value="$rejectReason == 'LiveQueued' or $rejectReason == 'LiveActiveShips'">
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
          </do_elseif>
          <do_elseif value="$rejectReason == 'ClearanceQueued' or $rejectReason == 'ClearanceActiveShips'">
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
          </do_elseif>
        </do_if>
      </actions>
    </cue>

    <cue name="DispatchCacheSearchGoDelayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay min="200ms" max="1000ms"/>
      <actions>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore.$CacheDispatchScheduled" exact="false"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
      </actions>
    </cue>

    <cue name="DispatchCacheSearchGo" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>

        <do_if value="global.$GT_SearchSemaphore.$CacheQueue.count gt 0 and global.$GT_SearchSemaphore.$CacheActive ge global.$GT_SearchSemaphore.$MaxConcurrentCache">
          <do_if value="not global.$GT_SearchSemaphore.$CacheDispatchScheduled">
            <set_value name="global.$GT_SearchSemaphore.$CacheDispatchScheduled" exact="true"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGoDelayed"/>
          </do_if>
        </do_if>
        <do_else>
          <do_while value="global.$GT_SearchSemaphore.$CacheQueue.count gt 0 and global.$GT_SearchSemaphore.$CacheActive lt global.$GT_SearchSemaphore.$MaxConcurrentCache">
            <set_value name="$entry" exact="global.$GT_SearchSemaphore.$CacheQueue.{1}"/>
            <remove_from_list name="global.$GT_SearchSemaphore.$CacheQueue" exact="$entry"/>

            <set_value name="$ship" exact="@$entry.$Ship"/>
            <set_value name="$params" exact="@$entry.$Params"/>
            <set_value name="$homeSector" exact="if $entry? and $entry.$HomeSector? then @$entry.$HomeSector else (if $ship? then $ship.sector else null)"/>
            <set_value name="$dispatchParams" exact="if $params? then $params else table[]"/>
            <set_value name="$dispatchParams.$Phase" exact="'cache'"/>
            <set_value name="$dispatchParams.$HomeSector" exact="$homeSector"/>
            <do_if value="not global.$GT_SearchSemaphore.$CacheReadCursorByHome?">
              <set_value name="global.$GT_SearchSemaphore.$CacheReadCursorByHome" exact="table[]"/>
            </do_if>
            <set_value name="$cacheReadCursor" exact="if $homeSector? and global.$GT_SearchSemaphore.$CacheReadCursorByHome.{$homeSector}? then @global.$GT_SearchSemaphore.$CacheReadCursorByHome.{$homeSector} else 0"/>
            <set_value name="$dispatchParams.$CacheReadOffset" exact="$cacheReadCursor"/>
            <do_if value="$homeSector?">
              <set_value name="global.$GT_SearchSemaphore.$CacheReadCursorByHome.{$homeSector}" exact="$cacheReadCursor + 1"/>
            </do_if>

            <do_if value="$ship? and $ship.exists">
              <set_value name="global.$GT_SearchSemaphore.$CacheActive" operation="add"/>
              <set_value name="global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}" exact="table[
                $StartedAt = player.age,
                $Params = $dispatchParams,
                $HomeSector = $homeSector
              ]"/>
              <remove_value name="global.$GT_SearchSemaphore.$CacheQueued.{$ship}"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'cache_active'"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchCacheSearchGo: Sending GT_Search_Go to ' + $ship.idcode + ' (age=' + player.age + ', phase=cache)'" chance="100"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Search_Go'" param2="$dispatchParams" delay="1ms"/>
            </do_if>
            <do_else>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$CacheQueued.{$ship}"/>
              </do_if>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              </do_if>
            </do_else>
          </do_while>
        </do_else>
      </actions>
    </cue>

    <cue name="DispatchLiveSearchGoDelayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay min="200ms" max="1000ms"/>
      <actions>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore.$LiveDispatchScheduled" exact="false"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
      </actions>
    </cue>

    <cue name="DispatchMK4LiveSearchGoDelayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay min="200ms" max="1000ms"/>
      <actions>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore.$MK4LiveDispatchScheduled" exact="false"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
      </actions>
    </cue>

    <cue name="DispatchMK4LiveSearchGo" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>
        <!-- Global self-heal for stale MK4 live-active slots.
             Needed when legacy/aborted entries keep MK4LiveActive at capacity and block all new dispatches. -->
        <do_if value="global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.keys.count gt 0">
          <set_value name="$mk4ActiveKeys" exact="global.$GT_SearchSemaphore.$MK4LiveActiveShips.keys.list"/>
          <do_all exact="$mk4ActiveKeys.count" counter="$maki">
            <set_value name="$mk4ActiveShip" exact="$mk4ActiveKeys.{$maki}"/>
            <set_value name="$mk4ActiveEntry" exact="if $mk4ActiveShip? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4ActiveShip}? then @global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4ActiveShip} else null"/>
            <set_value name="$mk4ActiveStartedAt" exact="if $mk4ActiveEntry? and $mk4ActiveEntry.$StartedAt? then @$mk4ActiveEntry.$StartedAt else null"/>
            <set_value name="$mk4ActiveStale" exact="false"/>
            <do_if value="not $mk4ActiveShip? or ($mk4ActiveShip? and not $mk4ActiveShip.exists)">
              <set_value name="$mk4ActiveStale" exact="true"/>
            </do_if>
            <do_if value="not $mk4ActiveStale and ($mk4ActiveStartedAt == null or (player.age - $mk4ActiveStartedAt) gt 60s)">
              <set_value name="$mk4ActiveStale" exact="true"/>
            </do_if>
            <do_if value="$mk4ActiveStale">
              <do_if value="$mk4ActiveShip? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4ActiveShip}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4ActiveShip}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$MK4LiveActive gt 0">
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" operation="subtract"/>
              </do_if>
              <do_if value="$mk4ActiveEntry? and $mk4ActiveEntry.$HomeSector? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4ActiveEntry.$HomeSector}? and @global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4ActiveEntry.$HomeSector} == $mk4ActiveShip">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4ActiveEntry.$HomeSector}"/>
              </do_if>
              <do_if value="$mk4ActiveShip? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$mk4ActiveShip}? and @global.$GT_SearchSemaphore.$PhaseStateByShip.{$mk4ActiveShip} == 'mk4live_active'">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$mk4ActiveShip}"/>
              </do_if>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchMK4LiveSearchGo: Cleared stale MK4 active slot owner=' + (if $mk4ActiveShip? then $mk4ActiveShip.idcode else 'null') + ' startedAt=' + (if $mk4ActiveStartedAt? then $mk4ActiveStartedAt else 'null') + ' age=' + player.age" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <!-- Self-heal orphaned MK4LiveHomeActive slots (parity with MK3 LiveHomeActive). -->
        <set_value name="$mk4LiveStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$mk4LiveStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.keys.count gt 0">
          <set_value name="$mk4OrphanHomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveHomeActive.keys.list"/>
          <do_all exact="$mk4OrphanHomeKeys.count" counter="$mk4ohi">
            <set_value name="$mk4OrphanHome" exact="$mk4OrphanHomeKeys.{$mk4ohi}"/>
            <set_value name="$mk4OrphanOwner" exact="if $mk4OrphanHome? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4OrphanHome}? then @global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4OrphanHome} else null"/>
            <set_value name="$mk4OrphanHomeStale" exact="false"/>
            <do_if value="not $mk4OrphanOwner? or not $mk4OrphanOwner.exists">
              <set_value name="$mk4OrphanHomeStale" exact="true"/>
            </do_if>
            <do_if value="not $mk4OrphanHomeStale and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and not global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4OrphanOwner}?">
              <set_value name="$mk4OrphanHomeStale" exact="true"/>
            </do_if>
            <do_if value="not $mk4OrphanHomeStale and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4OrphanOwner}?">
              <set_value name="$mk4OrphanOwnerEntry" exact="@global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4OrphanOwner}"/>
              <set_value name="$mk4OrphanOwnerStartedAt" exact="if $mk4OrphanOwnerEntry? and $mk4OrphanOwnerEntry.$StartedAt? then @$mk4OrphanOwnerEntry.$StartedAt else null"/>
              <do_if value="$mk4OrphanOwnerStartedAt == null or (player.age - $mk4OrphanOwnerStartedAt) gt $mk4LiveStaleThreshold">
                <set_value name="$mk4OrphanHomeStale" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="$mk4OrphanHomeStale">
              <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4OrphanHome}"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchMK4LiveSearchGo: Cleared orphaned MK4LiveHomeActive home=' + (if $mk4OrphanHome? and $mk4OrphanHome.knownname? then @$mk4OrphanHome.knownname else '?') + ' owner=' + (if $mk4OrphanOwner? then $mk4OrphanOwner.idcode else 'null')" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="global.$GT_SearchSemaphore.$MK4LiveHomesQueue.count gt 0 and global.$GT_SearchSemaphore.$MK4LiveActive ge global.$GT_SearchSemaphore.$MaxConcurrentMK4Live">
          <do_if value="not global.$GT_SearchSemaphore.$MK4LiveDispatchScheduled">
            <set_value name="global.$GT_SearchSemaphore.$MK4LiveDispatchScheduled" exact="true"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGoDelayed"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Fair round-robin by home sector -->
          <set_value name="$mk4HomeScanBudget" exact="global.$GT_SearchSemaphore.$MK4LiveHomesQueue.count"/>
          <do_while value="$mk4HomeScanBudget gt 0 and global.$GT_SearchSemaphore.$MK4LiveActive lt global.$GT_SearchSemaphore.$MaxConcurrentMK4Live and global.$GT_SearchSemaphore.$MK4LiveHomesQueue.count gt 0">
            <set_value name="$homeSector" exact="global.$GT_SearchSemaphore.$MK4LiveHomesQueue.{1}"/>
            <remove_from_list name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="$homeSector"/>
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}"/>
            <set_value name="$mk4HomeScanBudget" operation="subtract"/>

            <!-- Skip homes that are currently active; requeue to tail -->
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$homeSector}?">
              <do_if value="not global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
              <continue/>
            </do_if>

            <do_if value="not global.$GT_SearchSemaphore.$MK4LiveQueueByHome? or not global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}? or global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count le 0">
              <continue/>
            </do_if>

            <set_value name="$entry" exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.{1}"/>
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.{1}"/>

            <set_value name="$ship" exact="@$entry.$Ship"/>
            <set_value name="$params" exact="@$entry.$Params"/>
            <set_value name="$dispatchParams" exact="if $params? then $params else table[]"/>
            <set_value name="$dispatchParams.$Phase" exact="'mk4live'"/>
            <set_value name="$dispatchParams.$HomeSector" exact="$homeSector"/>
            <set_value name="$dispatchParams.$SearchPool" exact="'mk4_supply'"/>
            <set_value name="$dispatchForceLive" exact="true"/>
            <do_if value="$homeSector? and $homeSector.exists and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}? and global.$GT_TradeCacheMK4.{$homeSector}.count gt 0">
              <set_value name="$dispatchForceLive" exact="false"/>
            </do_if>
            <set_value name="$dispatchParams.$ForceLiveSearch" exact="$dispatchForceLive"/>

            <do_if value="$ship? and $ship.exists">
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" operation="add"/>
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}" exact="table[
                $StartedAt = player.age,
                $Params = $dispatchParams,
                $HomeSector = $homeSector
              ]"/>
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$homeSector}" exact="$ship"/>
              <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'mk4live_active'"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchMK4LiveSearchGo: Sending GT_Search_Go to ' + $ship.idcode + ' (age=' + player.age + ', mk4live)'" chance="100"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Search_Go'" param2="$dispatchParams" delay="1ms"/>
            </do_if>
            <do_else>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}"/>
              </do_if>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              </do_if>
            </do_else>

            <!-- Keep home queued if there are still pending MK4 live entries for this home -->
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count gt 0">
              <do_if value="not global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
            </do_if>
          </do_while>
        </do_else>
      </actions>
    </cue>

    <cue name="DispatchClearanceSearchGoDelayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay min="200ms" max="1000ms"/>
      <actions>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore.$ClearanceDispatchScheduled" exact="false"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
      </actions>
    </cue>

    <cue name="DispatchClearanceSearchGo" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>

        <do_if value="global.$GT_SearchSemaphore.$ClearanceQueue.count gt 0 and global.$GT_SearchSemaphore.$ClearanceActive ge global.$GT_SearchSemaphore.$MaxConcurrentClearance">
          <do_if value="not global.$GT_SearchSemaphore.$ClearanceDispatchScheduled">
            <set_value name="global.$GT_SearchSemaphore.$ClearanceDispatchScheduled" exact="true"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGoDelayed"/>
          </do_if>
        </do_if>
        <do_else>
          <do_while value="global.$GT_SearchSemaphore.$ClearanceQueue.count gt 0 and global.$GT_SearchSemaphore.$ClearanceActive lt global.$GT_SearchSemaphore.$MaxConcurrentClearance">
            <set_value name="$entry" exact="global.$GT_SearchSemaphore.$ClearanceQueue.{1}"/>
            <remove_from_list name="global.$GT_SearchSemaphore.$ClearanceQueue" exact="$entry"/>

            <set_value name="$ship" exact="@$entry.$Ship"/>
            <set_value name="$params" exact="@$entry.$Params"/>
            <set_value name="$homeSector" exact="if $entry? and $entry.$HomeSector? then @$entry.$HomeSector else (if $ship? then $ship.sector else null)"/>
            <set_value name="$dispatchParams" exact="if $params? then $params else table[]"/>
            <set_value name="$dispatchParams.$Phase" exact="'live'"/>
            <set_value name="$dispatchParams.$HomeSector" exact="$homeSector"/>
            <set_value name="$dispatchParams.$ForceLiveSearch" exact="true"/>
            <set_value name="$dispatchParams.$SearchMode" exact="'sell_only'"/>

            <do_if value="$ship? and $ship.exists">
              <set_value name="global.$GT_SearchSemaphore.$ClearanceActive" operation="add"/>
              <set_value name="global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}" exact="table[
                $StartedAt = player.age,
                $Params = $dispatchParams,
                $HomeSector = $homeSector
              ]"/>
              <remove_value name="global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'clearance_active'"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchClearanceSearchGo: Sending GT_Search_Go to ' + $ship.idcode + ' (age=' + player.age + ', clearance)'" chance="100"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Search_Go'" param2="$dispatchParams" delay="1ms"/>
            </do_if>
            <do_else>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}"/>
              </do_if>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              </do_if>
            </do_else>
          </do_while>
        </do_else>
      </actions>
    </cue>

    <cue name="DispatchLiveSearchGo" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>

        <!-- Self-heal stale MK3 live-active / orphaned LiveHomeActive slots (parity with MK4 pool). -->
        <set_value name="$liveStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$liveStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.keys.count gt 0">
          <set_value name="$liveActiveKeys" exact="global.$GT_SearchSemaphore.$LiveActiveShips.keys.list"/>
          <do_all exact="$liveActiveKeys.count" counter="$laki">
            <set_value name="$liveActiveShip" exact="$liveActiveKeys.{$laki}"/>
            <set_value name="$liveActiveEntry" exact="if $liveActiveShip? and global.$GT_SearchSemaphore.$LiveActiveShips.{$liveActiveShip}? then @global.$GT_SearchSemaphore.$LiveActiveShips.{$liveActiveShip} else null"/>
            <set_value name="$liveActiveStartedAt" exact="if $liveActiveEntry? and $liveActiveEntry.$StartedAt? then @$liveActiveEntry.$StartedAt else null"/>
            <set_value name="$liveActiveStale" exact="false"/>
            <do_if value="not $liveActiveShip? or ($liveActiveShip? and not $liveActiveShip.exists)">
              <set_value name="$liveActiveStale" exact="true"/>
            </do_if>
            <do_if value="not $liveActiveStale and ($liveActiveStartedAt == null or (player.age - $liveActiveStartedAt) gt $liveStaleThreshold)">
              <set_value name="$liveActiveStale" exact="true"/>
            </do_if>
            <do_if value="$liveActiveStale">
              <set_value name="$staleLiveHome" exact="if $liveActiveEntry? and $liveActiveEntry.$HomeSector? then @$liveActiveEntry.$HomeSector else null"/>
              <do_if value="$liveActiveShip? and global.$GT_SearchSemaphore.$LiveActiveShips.{$liveActiveShip}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveActiveShips.{$liveActiveShip}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveActive gt 0">
                <set_value name="global.$GT_SearchSemaphore.$LiveActive" operation="subtract"/>
              </do_if>
              <do_if value="$staleLiveHome? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$staleLiveHome}? and @global.$GT_SearchSemaphore.$LiveHomeActive.{$staleLiveHome} == $liveActiveShip">
                <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$staleLiveHome}"/>
              </do_if>
              <do_if value="$liveActiveShip? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$liveActiveShip}? and @global.$GT_SearchSemaphore.$PhaseStateByShip.{$liveActiveShip} == 'live_active'">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$liveActiveShip}"/>
              </do_if>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchLiveSearchGo: Cleared stale live-active owner=' + (if $liveActiveShip? then $liveActiveShip.idcode else 'null') + ' startedAt=' + (if $liveActiveStartedAt? then $liveActiveStartedAt else 'null') + ' age=' + player.age" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.keys.count gt 0">
          <set_value name="$liveHomeActiveKeys" exact="global.$GT_SearchSemaphore.$LiveHomeActive.keys.list"/>
          <do_all exact="$liveHomeActiveKeys.count" counter="$lhaki">
            <set_value name="$orphanHome" exact="$liveHomeActiveKeys.{$lhaki}"/>
            <set_value name="$orphanOwner" exact="if $orphanHome? and global.$GT_SearchSemaphore.$LiveHomeActive.{$orphanHome}? then @global.$GT_SearchSemaphore.$LiveHomeActive.{$orphanHome} else null"/>
            <set_value name="$orphanHomeStale" exact="false"/>
            <do_if value="not $orphanOwner? or not $orphanOwner.exists">
              <set_value name="$orphanHomeStale" exact="true"/>
            </do_if>
            <do_if value="not $orphanHomeStale and global.$GT_SearchSemaphore.$LiveActiveShips? and not global.$GT_SearchSemaphore.$LiveActiveShips.{$orphanOwner}?">
              <set_value name="$orphanHomeStale" exact="true"/>
            </do_if>
            <do_if value="$orphanHomeStale">
              <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$orphanHome}"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchLiveSearchGo: Cleared orphaned LiveHomeActive home=' + (if $orphanHome? and $orphanHome.knownname? then @$orphanHome.knownname else '?') + ' owner=' + (if $orphanOwner? then $orphanOwner.idcode else 'null')" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <!-- Self-heal LiveQueued ships missing from LiveQueueByHome (concurrent merge-replace loss). -->
        <do_if value="global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.keys.count gt 0">
          <set_value name="$liveOrphanKeys" exact="global.$GT_SearchSemaphore.$LiveQueued.keys.list"/>
          <do_all exact="$liveOrphanKeys.count" counter="$loi">
            <set_value name="$liveOrphanShip" exact="$liveOrphanKeys.{$loi}"/>
            <do_if value="$liveOrphanShip? and $liveOrphanShip.exists and global.$GT_SearchSemaphore.$LiveQueued.{$liveOrphanShip}? and (not global.$GT_SearchSemaphore.$LiveActiveShips? or not global.$GT_SearchSemaphore.$LiveActiveShips.{$liveOrphanShip}?)">
              <set_value name="$liveOrphanInQueue" exact="false"/>
              <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.keys.count gt 0">
                <set_value name="$liveOrphanHomeKeys" exact="global.$GT_SearchSemaphore.$LiveQueueByHome.keys.list"/>
                <do_all exact="$liveOrphanHomeKeys.count" counter="$lohi">
                  <set_value name="$liveOrphanHomeKey" exact="$liveOrphanHomeKeys.{$lohi}"/>
                  <do_if value="$liveOrphanHomeKey? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHomeKey}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHomeKey}.count gt 0">
                    <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHomeKey}.count" counter="$loqi">
                      <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHomeKey}.{$loqi}.$Ship == $liveOrphanShip">
                        <set_value name="$liveOrphanInQueue" exact="true"/>
                        <break/>
                      </do_if>
                    </do_all>
                  </do_if>
                  <do_if value="$liveOrphanInQueue">
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $liveOrphanInQueue">
                <set_value name="$liveOrphanHome" exact="if $liveOrphanShip.defaultorder? and $liveOrphanShip.defaultorder.$home? and $liveOrphanShip.defaultorder.$home.sector? then @$liveOrphanShip.defaultorder.$home.sector else $liveOrphanShip.sector"/>
                <do_if value="$liveOrphanHome? and $liveOrphanHome.exists">
                  <do_if value="not global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHome}?">
                    <set_value name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHome}" exact="[]"/>
                  </do_if>
                  <set_value name="$liveOrphanParams" exact="table[$Ship = $liveOrphanShip, $Phase = 'live', $HomeSector = $liveOrphanHome, $ForceLiveSearch = true]"/>
                  <append_to_list name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$liveOrphanHome}" exact="table[
                    $Ship = $liveOrphanShip,
                    $Params = $liveOrphanParams,
                    $HomeSector = $liveOrphanHome,
                    $EnqueuedAt = player.age
                  ]"/>
                  <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$liveOrphanHome}?">
                    <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$liveOrphanHome"/>
                    <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$liveOrphanHome}" exact="true"/>
                  </do_if>
                  <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Scheduler] DispatchLiveSearchGo: Re-enqueued orphaned LiveQueued ship ' + $liveOrphanShip.idcode + ' home=' + (if $liveOrphanHome.knownname? then @$liveOrphanHome.knownname else '?')" chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="global.$GT_SearchSemaphore.$LiveHomesQueue.count gt 0 and global.$GT_SearchSemaphore.$LiveActive ge global.$GT_SearchSemaphore.$MaxConcurrentLive">
          <do_if value="not global.$GT_SearchSemaphore.$LiveDispatchScheduled">
            <set_value name="global.$GT_SearchSemaphore.$LiveDispatchScheduled" exact="true"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGoDelayed"/>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] DispatchLiveSearchGo: SLOT FULL (LiveActive=' + global.$GT_SearchSemaphore.$LiveActive + '/' + global.$GT_SearchSemaphore.$MaxConcurrentLive + ') at age ' + player.age + ' - scheduling 200-1000ms retry'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_else>
          <!-- Fair round-robin by home sector -->
          <set_value name="$homeScanBudget" exact="global.$GT_SearchSemaphore.$LiveHomesQueue.count"/>
          <do_while value="$homeScanBudget gt 0 and global.$GT_SearchSemaphore.$LiveActive lt global.$GT_SearchSemaphore.$MaxConcurrentLive and global.$GT_SearchSemaphore.$LiveHomesQueue.count gt 0">
            <set_value name="$homeSector" exact="global.$GT_SearchSemaphore.$LiveHomesQueue.{1}"/>
            <remove_from_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
            <remove_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}"/>
            <set_value name="$homeScanBudget" operation="subtract"/>

            <!-- Skip homes that are currently active; requeue to tail -->
            <do_if value="global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}?">
              <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
              <continue/>
            </do_if>

            <do_if value="not global.$GT_SearchSemaphore.$LiveQueueByHome? or not global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? or global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count le 0">
              <continue/>
            </do_if>

            <set_value name="$pickIndex" exact="1"/>
            <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$lpi">
                <set_value name="$lpiEntry" exact="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$lpi}"/>
                <set_value name="$lpiParams" exact="if $lpiEntry? and $lpiEntry.$Params? then @$lpiEntry.$Params else null"/>
                <do_if value="$lpiParams? and (($lpiParams.$ForceLiveSearch? and @$lpiParams.$ForceLiveSearch) or ($lpiParams.$LiveSearchPriority? and @$lpiParams.$LiveSearchPriority))">
                  <set_value name="$pickIndex" exact="$lpi"/>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
            <set_value name="$entry" exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$pickIndex}"/>
            <remove_value name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$pickIndex}"/>

            <set_value name="$ship" exact="@$entry.$Ship"/>
            <set_value name="$params" exact="@$entry.$Params"/>
            <set_value name="$dispatchParams" exact="if $params? then $params else table[]"/>
            <set_value name="$dispatchParams.$Phase" exact="'live'"/>
            <set_value name="$dispatchParams.$HomeSector" exact="$homeSector"/>
            <set_value name="$searchMode" exact="if $dispatchParams.$SearchMode? then @$dispatchParams.$SearchMode else 'buy_and_sell'"/>

            <!-- Guard stale sell-only entries: do not assign live slots to ships already executing trade orders. -->
            <do_if value="$ship? and $ship.exists and $searchMode == 'sell_only' and $ship.tradeorders? and $ship.tradeorders.count gt 0">
              <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
              <do_if value="global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchLiveSearchGo: Dropping sell-only request for busy ship ' + $ship.idcode + ' (tradeorders=' + $ship.tradeorders.count + ')'" chance="100"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
                <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}?">
                  <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
                  <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}" exact="true"/>
                </do_if>
              </do_if>
              <continue/>
            </do_if>

            <do_if value="$ship? and $ship.exists">
              <set_value name="global.$GT_SearchSemaphore.$LiveActive" operation="add"/>
              <set_value name="global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}" exact="table[
                $StartedAt = player.age,
                $Params = $dispatchParams,
                $HomeSector = $homeSector
              ]"/>
              <set_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}" exact="$ship"/>
              <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'live_active'"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchLiveSearchGo: Sending GT_Search_Go to ' + $ship.idcode + ' (age=' + player.age + ', mode=' + $searchMode + ')'" chance="100"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Search_Go'" param2="$dispatchParams" delay="1ms"/>
            </do_if>
            <do_else>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
              </do_if>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              </do_if>
            </do_else>

            <!-- Keep home queued if there are still pending live entries for this home -->
            <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
              <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
            </do_if>
          </do_while>
        </do_else>
      </actions>
    </cue>

    <!-- Keepalive tick for ships waiting on same-home live refresh -->
    <cue name="NotifyLiveWaitersTick" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="20s"/>
      <actions>
        <set_value name="$hasAnyActiveWaiters" exact="false"/>
        <set_value name="$waiterStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$waiterStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveWaitersByHome? and global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.count gt 0">
          <set_value name="$homeKeys" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.list"/>
          <do_all exact="$homeKeys.count" counter="$hki">
            <set_value name="$homeSector" exact="$homeKeys.{$hki}"/>
            <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count gt 0">
              <set_value name="$homeOwner" exact="if global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}? then @global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector} else null"/>
              <set_value name="$homeOwnerStale" exact="false"/>
              <do_if value="not $homeOwner? or not $homeOwner.exists">
                <set_value name="$homeOwnerStale" exact="true"/>
              </do_if>
              <do_if value="not $homeOwnerStale and global.$GT_SearchSemaphore.$LiveActiveShips? and not global.$GT_SearchSemaphore.$LiveActiveShips.{$homeOwner}?">
                <set_value name="$homeOwnerStale" exact="true"/>
              </do_if>
              <do_if value="not $homeOwnerStale and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$homeOwner}?">
                <set_value name="$homeOwnerEntry" exact="@global.$GT_SearchSemaphore.$LiveActiveShips.{$homeOwner}"/>
                <set_value name="$homeOwnerStartedAt" exact="if $homeOwnerEntry? and $homeOwnerEntry.$StartedAt? then @$homeOwnerEntry.$StartedAt else null"/>
                <do_if value="$homeOwnerStartedAt == null or (player.age - $homeOwnerStartedAt) gt $waiterStaleThreshold">
                  <set_value name="$homeOwnerStale" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$homeOwnerStale and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}"/>
              </do_if>
              <do_if value="$homeOwnerStale and $homeOwner? and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$homeOwner}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveActiveShips.{$homeOwner}"/>
                <do_if value="global.$GT_SearchSemaphore.$LiveActive gt 0">
                  <set_value name="global.$GT_SearchSemaphore.$LiveActive" operation="subtract"/>
                </do_if>
              </do_if>

              <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count" counter="$wi" reverse="true">
                <set_value name="$wShip" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$wi}"/>
                <do_if value="not $wShip? or not $wShip.exists">
                  <remove_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$wi}"/>
                  <continue/>
                </do_if>
                <set_value name="$waiterAge" exact="0s"/>
                <do_if value="global.$GT_SearchSemaphore.$LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$wShip}?">
                  <set_value name="$waiterAge" exact="player.age - @global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$wShip}"/>
                </do_if>
                <set_value name="$promoteWaiter" exact="false"/>
                <do_if value="$homeOwnerStale or $waiterAge gt $waiterStaleThreshold">
                  <set_value name="$promoteWaiter" exact="true"/>
                </do_if>
                <do_if value="$promoteWaiter">
                  <remove_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$wi}"/>
                  <do_if value="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}.{$wShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}.{$wShip}"/>
                  </do_if>
                  <do_if value="global.$GT_SearchSemaphore.$LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$wShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$wShip}"/>
                  </do_if>
                  <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$wShip}" exact="true"/>
                  <signal_objects object="$wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                  <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Scheduler] NotifyLiveWaitersTick: Promoted starved waiter ' + $wShip.idcode + ' home=' + (if $homeSector.knownname? then @$homeSector.knownname else '?') + ' waiterAge=' + $waiterAge + ' homeOwnerStale=' + $homeOwnerStale" chance="100"/>
                  </do_if>
                </do_if>
              </do_all>

              <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count gt 0 and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}?">
                <set_value name="$hasAnyActiveWaiters" exact="true"/>
                <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count" counter="$wi">
                  <set_value name="$wShip" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$wi}"/>
                  <do_if value="$wShip? and $wShip.exists">
                    <signal_objects object="$wShip" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="$hasAnyActiveWaiters">
          <set_value name="global.$GT_SearchSemaphore.$LiveWaiterTickScheduled" exact="true"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.NotifyLiveWaitersTick"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_SearchSemaphore.$LiveWaiterTickScheduled" exact="false"/>
        </do_else>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
      </actions>
    </cue>

    <!-- Wake MK3 cache waiters periodically (fleet reservation TTL=10s) so saturated entries can be retried without burning live slots. -->
    <cue name="NotifyCacheWaitersTick" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="10s"/>
      <actions>
        <set_value name="$hasAnyCacheWaiters" exact="false"/>
        <set_value name="$waiterStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$waiterStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <!-- Pool>0 but per-ship read keeps returning 0: escalate one live refresh per home sooner than live-waiter stale. -->
        <set_value name="$cacheWaiterStaleThreshold" exact="15s"/>
        <do_if value="global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$CacheWaitersByHome? and global.$GT_SearchSemaphore.$CacheWaitersByHome.keys.count gt 0">
          <set_value name="$cacheWaiterHomeKeys" exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.keys.list"/>
          <do_all exact="$cacheWaiterHomeKeys.count" counter="$cwhi">
            <set_value name="$cacheWaiterHome" exact="$cacheWaiterHomeKeys.{$cwhi}"/>
            <set_value name="$cacheRefreshLiveDispatchedForHome" exact="false"/>
            <do_if value="$cacheWaiterHome? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}.count" counter="$cwwi" reverse="true">
                <set_value name="$cwShip" exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}.{$cwwi}"/>
                <do_if value="not $cwShip? or not $cwShip.exists">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}.{$cwwi}"/>
                  <continue/>
                </do_if>
                <set_value name="$cacheWaiterAge" exact="0s"/>
                <do_if value="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cacheWaiterHome}.{$cwShip}?">
                  <set_value name="$cacheWaiterAge" exact="player.age - @global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cacheWaiterHome}.{$cwShip}"/>
                </do_if>
                <do_elseif value="global.$GT_SearchSemaphore.$CacheWaiterStartedAt? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cacheWaiterHome}.{$cwShip}?">
                  <set_value name="$cacheWaiterAge" exact="player.age - @global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cacheWaiterHome}.{$cwShip}"/>
                </do_elseif>
                <remove_value name="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}.{$cwwi}"/>
                <do_if value="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$cacheWaiterHome}.{$cwShip}?">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$cacheWaiterHome}.{$cwShip}"/>
                </do_if>
                <do_if value="global.$GT_SearchSemaphore.$CacheWaiterStartedAt? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cacheWaiterHome}.{$cwShip}?">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cacheWaiterHome}.{$cwShip}"/>
                </do_if>
                <do_if value="global.$GT_SearchSemaphore.$CacheRetryPassCount? and global.$GT_SearchSemaphore.$CacheRetryPassCount.{$cwShip}?">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheRetryPassCount.{$cwShip}"/>
                </do_if>
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$cwShip}"/>
                <set_value name="$promoteCacheWaiterToLive" exact="false"/>
                <do_if value="$cacheWaiterAge gt $cacheWaiterStaleThreshold and not $cacheRefreshLiveDispatchedForHome">
                  <set_value name="$promoteCacheWaiterToLive" exact="true"/>
                  <set_value name="$cacheRefreshLiveDispatchedForHome" exact="true"/>
                </do_if>
                <do_if value="$promoteCacheWaiterToLive">
                  <do_if value="not global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$cacheWaiterHome}" exact="true"/>
                  <do_if value="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cacheWaiterHome}.{$cwShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cacheWaiterHome}.{$cwShip}"/>
                  </do_if>
                  <set_value name="$cwLiveParams" exact="table[$Ship = $cwShip, $Phase = 'live', $HomeSector = $cacheWaiterHome, $ForceLiveSearch = true]"/>
                  <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$cwShip}?">
                    <do_if value="global.$GT_AIParameters.{$cwShip}.$HomeBase?">
                      <set_value name="$cwLiveParams.$HomeBase" exact="@global.$GT_AIParameters.{$cwShip}.$HomeBase"/>
                    </do_if>
                    <do_if value="global.$GT_AIParameters.{$cwShip}.$SearchMode?">
                      <set_value name="$cwLiveParams.$SearchMode" exact="@global.$GT_AIParameters.{$cwShip}.$SearchMode"/>
                    </do_if>
                  </do_if>
                  <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="$cwLiveParams" delay="1ms"/>
                  <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Scheduler] NotifyCacheWaitersTick: Promoted starved cache waiter ' + $cwShip.idcode + ' to live refresh home=' + (if $cacheWaiterHome.knownname? then @$cacheWaiterHome.knownname else '?') + ' age=' + $cacheWaiterAge" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <signal_objects object="$cwShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                </do_else>
              </do_all>
              <do_if value="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cacheWaiterHome}.count gt 0">
                <set_value name="$hasAnyCacheWaiters" exact="true"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$hasAnyCacheWaiters">
          <set_value name="global.$GT_SearchSemaphore.$CacheWaiterTickScheduled" exact="true"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.NotifyCacheWaitersTick"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_SearchSemaphore.$CacheWaiterTickScheduled" exact="false"/>
        </do_else>
      </actions>
    </cue>

    <!-- Keepalive tick for ships waiting on same-home MK4 live refresh -->
    <cue name="NotifyMK4LiveWaitersTick" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="20s"/>
      <actions>
        <set_value name="$hasAnyMK4ActiveWaiters" exact="false"/>
        <set_value name="$mk4WaiterStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$mk4WaiterStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.count gt 0">
          <set_value name="$mk4HomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.list"/>
          <do_all exact="$mk4HomeKeys.count" counter="$mk4hki">
            <set_value name="$mk4HomeSector" exact="$mk4HomeKeys.{$mk4hki}"/>
            <do_if value="$mk4HomeSector? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.count gt 0">
              <set_value name="$mk4HomeOwner" exact="if global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4HomeSector}? then @global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4HomeSector} else null"/>
              <set_value name="$mk4HomeOwnerStale" exact="false"/>
              <do_if value="not $mk4HomeOwner? or not $mk4HomeOwner.exists">
                <set_value name="$mk4HomeOwnerStale" exact="true"/>
              </do_if>
              <do_if value="not $mk4HomeOwnerStale and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and not global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4HomeOwner}?">
                <set_value name="$mk4HomeOwnerStale" exact="true"/>
              </do_if>
              <do_if value="not $mk4HomeOwnerStale and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4HomeOwner}?">
                <set_value name="$mk4HomeOwnerEntry" exact="@global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4HomeOwner}"/>
                <set_value name="$mk4HomeOwnerStartedAt" exact="if $mk4HomeOwnerEntry? and $mk4HomeOwnerEntry.$StartedAt? then @$mk4HomeOwnerEntry.$StartedAt else null"/>
                <do_if value="$mk4HomeOwnerStartedAt == null or (player.age - $mk4HomeOwnerStartedAt) gt $mk4WaiterStaleThreshold">
                  <set_value name="$mk4HomeOwnerStale" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$mk4HomeOwnerStale and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4HomeSector}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4HomeSector}"/>
              </do_if>
              <do_if value="$mk4HomeOwnerStale and $mk4HomeOwner? and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4HomeOwner}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$mk4HomeOwner}"/>
                <do_if value="global.$GT_SearchSemaphore.$MK4LiveActive gt 0">
                  <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" operation="subtract"/>
                </do_if>
              </do_if>

              <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.count" counter="$mk4wi" reverse="true">
                <set_value name="$mk4wShip" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.{$mk4wi}"/>
                <do_if value="not $mk4wShip? or not $mk4wShip.exists">
                  <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.{$mk4wi}"/>
                  <continue/>
                </do_if>
                <set_value name="$mk4WaiterAge" exact="0s"/>
                <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4HomeSector}.{$mk4wShip}?">
                  <set_value name="$mk4WaiterAge" exact="player.age - @global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4HomeSector}.{$mk4wShip}"/>
                </do_if>
                <set_value name="$mk4PromoteWaiter" exact="false"/>
                <do_if value="$mk4HomeOwnerStale or $mk4WaiterAge gt $mk4WaiterStaleThreshold">
                  <set_value name="$mk4PromoteWaiter" exact="true"/>
                </do_if>
                <do_if value="$mk4PromoteWaiter">
                  <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.{$mk4wi}"/>
                  <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4HomeSector}.{$mk4wShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4HomeSector}.{$mk4wShip}"/>
                  </do_if>
                  <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4HomeSector}.{$mk4wShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4HomeSector}.{$mk4wShip}"/>
                  </do_if>
                  <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk4wShip}" exact="true"/>
                  <signal_objects object="$mk4wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                  <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Scheduler] NotifyMK4LiveWaitersTick: Promoted starved MK4 waiter ' + $mk4wShip.idcode + ' home=' + (if $mk4HomeSector.knownname? then @$mk4HomeSector.knownname else '?') + ' waiterAge=' + $mk4WaiterAge + ' homeOwnerStale=' + $mk4HomeOwnerStale" chance="100"/>
                  </do_if>
                </do_if>
              </do_all>

              <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.count gt 0 and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4HomeSector}?">
                <set_value name="$hasAnyMK4ActiveWaiters" exact="true"/>
                <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.count" counter="$mk4wi">
                  <set_value name="$mk4wShip" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.{$mk4wi}"/>
                  <do_if value="$mk4wShip? and $mk4wShip.exists">
                    <signal_objects object="$mk4wShip" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="$hasAnyMK4ActiveWaiters">
          <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterTickScheduled" exact="true"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.NotifyMK4LiveWaitersTick"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterTickScheduled" exact="false"/>
        </do_else>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
      </actions>
    </cue>

    <cue name="HandleSearchDone" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Search_Done'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$ship" exact="@$data.$Ship"/>
        <set_value name="$found" exact="if $data? and $data.$Found? then @$data.$Found else false"/>
        <set_value name="$tradeList" exact="if $data? and $data.$TradeList? then @$data.$TradeList else []"/>
        <set_value name="$searchMethod" exact="if $data? and $data.$SearchMethod? then @$data.$SearchMethod else 'live'"/>
        <set_value name="$searchType" exact="if $data? and $data.$SearchType? then @$data.$SearchType else 'live'"/>
        <set_value name="$homeSectorFromDone" exact="if $data? and $data.$HomeSector? then @$data.$HomeSector else null"/>
        <set_value name="$cacheEntry" exact="if $ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}? then @global.$GT_SearchSemaphore.$CacheActiveShips.{$ship} else null"/>
        <set_value name="$liveEntry" exact="if $ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}? then @global.$GT_SearchSemaphore.$LiveActiveShips.{$ship} else null"/>
        <set_value name="$mk42LiveEntry" exact="if $ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}? then @global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship} else null"/>
        <set_value name="$mk4LiveEntry" exact="if $ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}? then @global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship} else null"/>
        <set_value name="$ownedLiveHomesEarly" exact="[]"/>
        <set_value name="$ownedMK4LiveHomesEarly" exact="[]"/>
        <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.keys.count gt 0">
          <set_value name="$liveHomeKeysEarly" exact="global.$GT_SearchSemaphore.$LiveHomeActive.keys.list"/>
          <do_all exact="$liveHomeKeysEarly.count" counter="$lhkiEarly">
            <set_value name="$lhkEarly" exact="$liveHomeKeysEarly.{$lhkiEarly}"/>
            <do_if value="$lhkEarly? and global.$GT_SearchSemaphore.$LiveHomeActive.{$lhkEarly}? and @global.$GT_SearchSemaphore.$LiveHomeActive.{$lhkEarly} == $ship">
              <append_to_list name="$ownedLiveHomesEarly" exact="$lhkEarly"/>
            </do_if>
          </do_all>
        </do_if>
        <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.keys.count gt 0">
          <set_value name="$mk4LiveHomeKeysEarly" exact="global.$GT_SearchSemaphore.$MK4LiveHomeActive.keys.list"/>
          <do_all exact="$mk4LiveHomeKeysEarly.count" counter="$mk4lhkiEarly">
            <set_value name="$mk4lhkEarly" exact="$mk4LiveHomeKeysEarly.{$mk4lhkiEarly}"/>
            <do_if value="$mk4lhkEarly? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4lhkEarly}? and @global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4lhkEarly} == $ship">
              <append_to_list name="$ownedMK4LiveHomesEarly" exact="$mk4lhkEarly"/>
            </do_if>
          </do_all>
        </do_if>
        <set_value name="$ownedMK42LiveHomesEarly" exact="[]"/>
        <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.count gt 0">
          <set_value name="$mk42LiveHomeKeysEarly" exact="global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.list"/>
          <do_all exact="$mk42LiveHomeKeysEarly.count" counter="$mk42lhkiEarly">
            <set_value name="$mk42lhkEarly" exact="$mk42LiveHomeKeysEarly.{$mk42lhkiEarly}"/>
            <do_if value="$mk42lhkEarly? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42lhkEarly}? and @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42lhkEarly} == $ship">
              <append_to_list name="$ownedMK42LiveHomesEarly" exact="$mk42lhkEarly"/>
            </do_if>
          </do_all>
        </do_if>
        <!-- Route live completion to mk42live / mk4live when MK3 live slot is not active. -->
        <do_if value="$searchType == 'live' and $mk42LiveEntry? and not $liveEntry? and not $mk4LiveEntry?">
          <set_value name="$searchType" exact="'mk42live'"/>
        </do_if>
        <do_elseif value="$searchType == 'live' and $mk4LiveEntry? and not $liveEntry?">
          <set_value name="$searchType" exact="'mk4live'"/>
        </do_elseif>

        <do_if value="$searchType == 'cache'">
          <set_value name="$homeSector" exact="if $cacheEntry? and $cacheEntry.$HomeSector? then @$cacheEntry.$HomeSector else (if $cacheEntry? and $cacheEntry.$Params? and $cacheEntry.$Params.$HomeSector? then @$cacheEntry.$Params.$HomeSector else (if $ship? then $ship.sector else null))"/>
          <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$CacheActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$CacheActive" operation="subtract"/>
            </do_if>
          </do_if>

          <do_if value="$ship? and $ship.exists">
            <do_if value="$found and $tradeList.count gt 0">
              <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              <do_if value="global.$GT_SearchSemaphore.$CacheRetryPassCount? and global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterPassCount? and global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
              </do_if>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}"/>
              </do_if>
              <!-- Cache satisfied: drop pending live-queue / waiter state from an earlier cache miss. -->
              <do_if value="global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueued? and global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.keys.count gt 0">
                <set_value name="$cacheHitLiveHomeKeys" exact="global.$GT_SearchSemaphore.$LiveQueueByHome.keys.list"/>
                <do_all exact="$cacheHitLiveHomeKeys.count" counter="$cacheHitLhk">
                  <set_value name="$cacheHitLiveHome" exact="$cacheHitLiveHomeKeys.{$cacheHitLhk}"/>
                  <do_if value="$cacheHitLiveHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$cacheHitLiveHome}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$cacheHitLiveHome}.count gt 0">
                    <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$cacheHitLiveHome}.count" counter="$cacheHitLqi" reverse="true">
                      <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$cacheHitLiveHome}.{$cacheHitLqi}.$Ship == $ship">
                        <remove_value name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$cacheHitLiveHome}.{$cacheHitLqi}"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.keys.count gt 0">
                <set_value name="$cacheHitMk4HomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.keys.list"/>
                <do_all exact="$cacheHitMk4HomeKeys.count" counter="$cacheHitMk4hi">
                  <set_value name="$cacheHitMk4Home" exact="$cacheHitMk4HomeKeys.{$cacheHitMk4hi}"/>
                  <do_if value="$cacheHitMk4Home? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$cacheHitMk4Home}? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$cacheHitMk4Home}.count gt 0">
                    <do_all exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$cacheHitMk4Home}.count" counter="$cacheHitMk4qi" reverse="true">
                      <do_if value="@global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$cacheHitMk4Home}.{$cacheHitMk4qi}.$Ship == $ship">
                        <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$cacheHitMk4Home}.{$cacheHitMk4qi}"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueueByHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.keys.count gt 0">
                <set_value name="$cacheHitMk42HomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.keys.list"/>
                <do_all exact="$cacheHitMk42HomeKeys.count" counter="$cacheHitMk42hi">
                  <set_value name="$cacheHitMk42Home" exact="$cacheHitMk42HomeKeys.{$cacheHitMk42hi}"/>
                  <do_if value="$cacheHitMk42Home? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$cacheHitMk42Home}? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$cacheHitMk42Home}.count gt 0">
                    <do_all exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$cacheHitMk42Home}.count" counter="$cacheHitMk42qi" reverse="true">
                      <do_if value="@global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$cacheHitMk42Home}.{$cacheHitMk42qi}.$Ship == $ship">
                        <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$cacheHitMk42Home}.{$cacheHitMk42qi}"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome? and global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.count gt 0">
                <set_value name="$cacheHitWaiterHomes" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.list"/>
                <do_all exact="$cacheHitWaiterHomes.count" counter="$cacheHitWhi">
                  <set_value name="$cacheHitWaiterHome" exact="$cacheHitWaiterHomes.{$cacheHitWhi}"/>
                  <do_if value="$cacheHitWaiterHome? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$cacheHitWaiterHome}? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$cacheHitWaiterHome}.{$ship}?">
                    <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$cacheHitWaiterHome}.{$ship}"/>
                  </do_if>
                  <do_if value="$cacheHitWaiterHome? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$cacheHitWaiterHome}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$cacheHitWaiterHome}.count gt 0">
                    <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$cacheHitWaiterHome}.count" counter="$cacheHitWwi" reverse="true">
                      <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$cacheHitWaiterHome}.{$cacheHitWwi} == $ship">
                        <remove_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$cacheHitWaiterHome}.{$cacheHitWwi}"/>
                      </do_if>
                    </do_all>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$CacheWaitersByHome? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.count gt 0">
                <do_if value="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}.{$ship}?">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}.{$ship}"/>
                </do_if>
                <do_if value="global.$GT_SearchSemaphore.$CacheWaiterStartedAt? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}.{$ship}?">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}.{$ship}"/>
                </do_if>
                <do_if value="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}?">
                  <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}"/>
                </do_if>
                <do_all exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.count" counter="$cacheHitCwwi" reverse="true">
                  <do_if value="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.{$cacheHitCwwi} == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.{$cacheHitCwwi}"/>
                  </do_if>
                </do_all>
              </do_if>
              <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
                $TradeList = $tradeList,
                $SearchMethod = $searchMethod
              ]" delay="1ms"/>
            </do_if>
            <do_else>
              <set_value name="$isClearanceRequest" exact="false"/>
              <do_if value="$cacheEntry? and $cacheEntry.$Params? and $cacheEntry.$Params.$SearchMode? and $cacheEntry.$Params.$SearchMode == 'sell_only'">
                <set_value name="$isClearanceRequest" exact="true"/>
              </do_if>

              <do_if value="$isClearanceRequest">
                <set_value name="$enqueueClearance" exact="true"/>
                <do_if value="global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}?">
                  <set_value name="$enqueueClearance" exact="false"/>
                </do_if>
                <do_if value="$enqueueClearance and global.$GT_SearchSemaphore.$ClearanceActiveShips? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}?">
                  <set_value name="$enqueueClearance" exact="false"/>
                </do_if>

                <do_if value="$enqueueClearance">
                  <set_value name="$clearanceParams" exact="if $cacheEntry? and $cacheEntry.$Params? then @$cacheEntry.$Params else table[$Ship = $ship]"/>
                  <set_value name="$clearanceParams.$Phase" exact="'live'"/>
                  <set_value name="$clearanceParams.$HomeSector" exact="$homeSector"/>
                  <set_value name="$clearanceParams.$SearchMode" exact="'sell_only'"/>
                  <set_value name="$clearanceParams.$ForceLiveSearch" exact="true"/>
                  <append_to_list name="global.$GT_SearchSemaphore.$ClearanceQueue" exact="table[
                    $Ship = $ship,
                    $Params = $clearanceParams,
                    $HomeSector = $homeSector,
                    $EnqueuedAt = player.age
                  ]"/>
                  <set_value name="global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}" exact="true"/>
                  <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'clearance_queued'"/>
                </do_if>
              </do_if>
              <do_else>
                <set_value name="$useMK42LivePoolFromCache" exact="false"/>
                <set_value name="$useMK4LivePoolFromCache" exact="false"/>
                <do_if value="$cacheEntry? and $cacheEntry.$Params? and $cacheEntry.$Params.$SearchPool? and $cacheEntry.$Params.$SearchPool == 'mk4_supply_v2'">
                  <set_value name="$useMK42LivePoolFromCache" exact="true"/>
                </do_if>
                <do_elseif value="$cacheEntry? and $cacheEntry.$Params? and $cacheEntry.$Params.$SearchPool? and $cacheEntry.$Params.$SearchPool == 'mk4_supply'">
                  <set_value name="$useMK4LivePoolFromCache" exact="true"/>
                </do_elseif>

                <!-- Home refresh already active: park ship as waiter unless starved (then promote to live queue). -->
                <set_value name="$homeActiveByOtherShip" exact="false"/>
                <do_if value="$useMK42LivePoolFromCache">
                  <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$homeSector}? and @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$homeSector} != $ship">
                    <set_value name="$homeActiveByOtherShip" exact="true"/>
                  </do_if>
                </do_if>
                <do_elseif value="$useMK4LivePoolFromCache">
                  <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$homeSector}? and @global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$homeSector} != $ship">
                    <set_value name="$homeActiveByOtherShip" exact="true"/>
                  </do_if>
                </do_elseif>
                <do_else>
                  <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}? and @global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector} != $ship">
                    <set_value name="$homeActiveByOtherShip" exact="true"/>
                  </do_if>
                </do_else>

                <set_value name="$waiterStaleThreshold" exact="120s"/>
                <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
                  <set_value name="$waiterStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
                </do_if>
                <set_value name="$cacheWaiterStaleThreshold" exact="15s"/>
                <set_value name="$starvedWaiter" exact="false"/>
                <do_if value="$ship? and global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
                  <set_value name="$starvedWaiter" exact="true"/>
                  <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
                </do_if>
                <do_if value="not $starvedWaiter and $ship? and global.$GT_SearchSemaphore.$LiveWaiterPassCount? and global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}? and @global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship} ge 1">
                  <set_value name="$starvedWaiter" exact="true"/>
                </do_if>
                <do_if value="not $starvedWaiter and $ship? and $homeSector?">
                  <do_if value="$useMK42LivePoolFromCache and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                    <do_if value="(player.age - @global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}.{$ship}) gt $waiterStaleThreshold">
                      <set_value name="$starvedWaiter" exact="true"/>
                    </do_if>
                  </do_if>
                  <do_elseif value="$useMK4LivePoolFromCache and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                    <do_if value="(player.age - @global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}.{$ship}) gt $waiterStaleThreshold">
                      <set_value name="$starvedWaiter" exact="true"/>
                    </do_if>
                  </do_elseif>
                  <do_elseif value="not $useMK42LivePoolFromCache and not $useMK4LivePoolFromCache and global.$GT_SearchSemaphore.$LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                    <do_if value="(player.age - @global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}) gt $waiterStaleThreshold">
                      <set_value name="$starvedWaiter" exact="true"/>
                    </do_if>
                  </do_elseif>
                  <do_elseif value="not $useMK42LivePoolFromCache and not $useMK4LivePoolFromCache and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}?">
                    <do_if value="(player.age - @global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}) gt $cacheWaiterStaleThreshold">
                      <set_value name="$starvedWaiter" exact="true"/>
                    </do_if>
                  </do_elseif>
                  <do_elseif value="not $useMK42LivePoolFromCache and not $useMK4LivePoolFromCache and global.$GT_SearchSemaphore.$CacheWaiterStartedAt? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}.{$ship}?">
                    <do_if value="(player.age - @global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}.{$ship}) gt $waiterStaleThreshold">
                      <set_value name="$starvedWaiter" exact="true"/>
                    </do_if>
                  </do_elseif>
                </do_if>

                <!-- Only one ship per home may run a cache-refresh live search; others stay parked until cache updates. -->
                <set_value name="$cacheRefreshInFlight" exact="false"/>
                <do_if value="$homeSector? and global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome? and global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$homeSector}?">
                  <set_value name="$cacheRefreshInFlight" exact="true"/>
                </do_if>
                <do_if value="not $cacheRefreshInFlight and $homeSector? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}?">
                  <set_value name="$cacheRefreshInFlight" exact="true"/>
                </do_if>
                <do_if value="$starvedWaiter and $cacheRefreshInFlight">
                  <set_value name="$starvedWaiter" exact="false"/>
                </do_if>

                <set_value name="$parkAsWaiter" exact="false"/>
                <do_if value="$homeActiveByOtherShip and not $starvedWaiter">
                  <set_value name="$parkAsWaiter" exact="true"/>
                </do_if>

                <!-- Transient cache miss while pool still has entries: retry cache before burning a live slot. -->
                <set_value name="$preferCacheRequeue" exact="false"/>
                <set_value name="$parkAsCacheWaiter" exact="false"/>
                <set_value name="$mk3HomeCacheCountOnMiss" exact="0"/>
                <do_if value="not $useMK42LivePoolFromCache and not $useMK4LivePoolFromCache">
                  <do_if value="$data? and $data.$PoolSizeAfter?">
                    <set_value name="$mk3HomeCacheCountOnMiss" exact="@$data.$PoolSizeAfter"/>
                  </do_if>
                  <do_elseif value="$homeSector? and global.$GT_TradeCache? and global.$GT_TradeCache.{$homeSector}?">
                    <set_value name="$mk3HomeCacheCountOnMiss" exact="@global.$GT_TradeCache.{$homeSector}.count"/>
                  </do_elseif>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheRetryPassCount?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheRetryPassCount" exact="table[]"/>
                  </do_if>
                  <set_value name="$cacheRetryPass" exact="if global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship}? then @global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship} else 0"/>
                  <do_if value="$mk3HomeCacheCountOnMiss gt 0 and not $starvedWaiter and $cacheRetryPass lt 2">
                    <set_value name="$preferCacheRequeue" exact="true"/>
                  </do_if>
                  <do_if value="$mk3HomeCacheCountOnMiss gt 0 and not $starvedWaiter and $cacheRetryPass ge 2">
                    <set_value name="$parkAsCacheWaiter" exact="true"/>
                  </do_if>
                  <do_if value="$cacheRefreshInFlight and $mk3HomeCacheCountOnMiss gt 0 and not $starvedWaiter">
                    <set_value name="$parkAsCacheWaiter" exact="true"/>
                    <set_value name="$preferCacheRequeue" exact="false"/>
                  </do_if>
                </do_if>

                <do_if value="$preferCacheRequeue and not $parkAsWaiter">
                  <set_value name="$cacheRequeueParams" exact="if $cacheEntry? and $cacheEntry.$Params? then @$cacheEntry.$Params else (if $data? and $data.$Params? then @$data.$Params else table[$Ship = $ship])"/>
                  <set_value name="$cacheRequeueParams.$Phase" exact="'cache'"/>
                  <set_value name="$cacheRequeueParams.$HomeSector" exact="$homeSector"/>
                  <set_value name="$cacheRequeueAllowed" exact="true"/>
                  <do_if value="global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
                    <set_value name="$cacheRequeueAllowed" exact="false"/>
                  </do_if>
                  <do_if value="$cacheRequeueAllowed and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
                    <set_value name="$cacheRequeueAllowed" exact="false"/>
                  </do_if>
                  <do_if value="$cacheRequeueAllowed">
                    <append_to_list name="global.$GT_SearchSemaphore.$CacheQueue" exact="table[
                      $Ship = $ship,
                      $Params = $cacheRequeueParams,
                      $HomeSector = $homeSector,
                      $EnqueuedAt = player.age
                    ]"/>
                    <set_value name="global.$GT_SearchSemaphore.$CacheQueued.{$ship}" exact="true"/>
                    <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'cache_queued'"/>
                    <set_value name="global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship}" exact="$cacheRetryPass + 1"/>
                    <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                    <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
                    <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT-Scheduler] HandleSearchDone: Cache miss with pool=' + $mk3HomeCacheCountOnMiss + ' - requeued cache for ' + $ship.idcode + ' pass=' + ($cacheRetryPass + 1)" chance="100"/>
                    </do_if>
                  </do_if>
                  <do_else>
                    <set_value name="$preferCacheRequeue" exact="false"/>
                  </do_else>
                </do_if>
                <do_if value="$parkAsCacheWaiter and not $preferCacheRequeue and $homeSector?">
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}" exact="[]"/>
                  </do_if>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}" exact="table[]"/>
                  </do_if>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterStartedAt?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt" exact="table[]"/>
                  </do_if>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}" exact="table[]"/>
                  </do_if>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt" exact="table[]"/>
                  </do_if>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}?">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}" exact="table[]"/>
                  </do_if>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}.{$ship}?">
                    <append_to_list name="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}" exact="$ship"/>
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$homeSector}.{$ship}" exact="true"/>
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$homeSector}.{$ship}" exact="player.age"/>
                    <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}?">
                      <set_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}" exact="player.age"/>
                    </do_if>
                  </do_if>
                  <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
                  <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                  <do_if value="not global.$GT_SearchSemaphore.$CacheWaiterTickScheduled">
                    <set_value name="global.$GT_SearchSemaphore.$CacheWaiterTickScheduled" exact="true"/>
                    <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.NotifyCacheWaitersTick"/>
                  </do_if>
                  <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Scheduler] HandleSearchDone: Cache miss with pool=' + $mk3HomeCacheCountOnMiss + ' - parked cache waiter ' + $ship.idcode + ' (entries exist but per-ship read returned 0)'" chance="100"/>
                  </do_if>
                </do_if>
                <do_if value="not $preferCacheRequeue and not $parkAsCacheWaiter">
                <do_if value="$parkAsWaiter">
                  <do_if value="$useMK42LivePoolFromCache">
                    <do_if value="not global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}" exact="[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$homeSector}" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt?">
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterPassCount?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$homeSector}.{$ship}?">
                      <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}" exact="$ship"/>
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$homeSector}.{$ship}" exact="true"/>
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}.{$ship}" exact="player.age"/>
                      <set_value name="$prevWaiterPassCount" exact="if global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}? then @global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship} else 0"/>
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}" exact="$prevWaiterPassCount + 1"/>
                    </do_if>
                    <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
                    <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                    <do_if value="not global.$GT_SearchSemaphore.$MK42LiveWaiterTickScheduled">
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterTickScheduled" exact="true"/>
                      <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.NotifyMK42LiveWaitersTick"/>
                    </do_if>
                  </do_if>
                  <do_elseif value="$useMK4LivePoolFromCache">
                    <do_if value="not global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}" exact="[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$homeSector}" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt?">
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterPassCount?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$homeSector}.{$ship}?">
                      <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}" exact="$ship"/>
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$homeSector}.{$ship}" exact="true"/>
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}.{$ship}" exact="player.age"/>
                      <set_value name="$prevWaiterPassCount" exact="if global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}? then @global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship} else 0"/>
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}" exact="$prevWaiterPassCount + 1"/>
                    </do_if>
                    <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
                    <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                    <do_if value="not global.$GT_SearchSemaphore.$MK4LiveWaiterTickScheduled">
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterTickScheduled" exact="true"/>
                      <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.NotifyMK4LiveWaitersTick"/>
                    </do_if>
                  </do_elseif>
                  <do_else>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}" exact="[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterStartedAt?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterPassCount?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount" exact="table[]"/>
                    </do_if>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}.{$ship}?">
                      <append_to_list name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}" exact="$ship"/>
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}.{$ship}" exact="true"/>
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}" exact="player.age"/>
                      <set_value name="$prevWaiterPassCount" exact="if global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}? then @global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship} else 0"/>
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}" exact="$prevWaiterPassCount + 1"/>
                    </do_if>
                    <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
                    <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterTickScheduled">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterTickScheduled" exact="true"/>
                      <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.NotifyLiveWaitersTick"/>
                    </do_if>
                  </do_else>
                </do_if>
                <do_else>
                  <!-- No active same-home live refresh, or starved waiter -> enqueue live (fair by home). -->
                  <set_value name="$enqueueLive" exact="true"/>
                  <do_if value="$useMK42LivePoolFromCache">
                    <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueued? and global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}?">
                      <set_value name="$enqueueLive" exact="false"/>
                    </do_if>
                    <do_if value="$enqueueLive and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}?">
                      <set_value name="$enqueueLive" exact="false"/>
                    </do_if>
                  </do_if>
                  <do_elseif value="$useMK4LivePoolFromCache">
                    <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
                      <set_value name="$enqueueLive" exact="false"/>
                    </do_if>
                    <do_if value="$enqueueLive and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
                      <set_value name="$enqueueLive" exact="false"/>
                    </do_if>
                  </do_elseif>
                  <do_else>
                    <do_if value="global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
                      <set_value name="$enqueueLive" exact="false"/>
                      <set_value name="$liveStillQueued" exact="false"/>
                      <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
                        <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$lqsDone">
                          <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$lqsDone}.$Ship == $ship">
                            <set_value name="$liveStillQueued" exact="true"/>
                            <break/>
                          </do_if>
                        </do_all>
                      </do_if>
                      <do_if value="not $liveStillQueued">
                        <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
                        <set_value name="$enqueueLive" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_if value="$enqueueLive and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
                      <set_value name="$enqueueLive" exact="false"/>
                    </do_if>
                  </do_else>

                  <do_if value="$enqueueLive">
                    <do_if value="$starvedWaiter and $homeSector? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}?">
                      <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}.{$ship}"/>
                    </do_if>
                    <set_value name="$liveParams" exact="if $cacheEntry? and $cacheEntry.$Params? then @$cacheEntry.$Params else (if $data? and $data.$Params? then @$data.$Params else table[$Ship = $ship])"/>
                    <set_value name="$liveParams.$Phase" exact="'live'"/>
                    <set_value name="$liveParams.$HomeSector" exact="$homeSector"/>
                    <set_value name="$liveCacheRetryPass" exact="if global.$GT_SearchSemaphore.$CacheRetryPassCount? and global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship}? then @global.$GT_SearchSemaphore.$CacheRetryPassCount.{$ship} else 0"/>
                    <do_if value="$starvedWaiter">
                      <set_value name="$liveParams.$ForceLiveSearch" exact="true"/>
                      <do_if value="$homeSector?">
                        <do_if value="not global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome?">
                          <set_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome" exact="table[]"/>
                        </do_if>
                        <set_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$homeSector}" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_elseif value="$liveCacheRetryPass ge 2 and $mk3HomeCacheCountOnMiss == 0">
                      <set_value name="$liveParams.$ForceLiveSearch" exact="true"/>
                    </do_elseif>
                    <do_elseif value="not $starvedWaiter">
                      <set_value name="$liveParams.$CachePhaseMiss" exact="true"/>
                    </do_elseif>
                    <set_value name="$useMK42LivePool" exact="$liveParams.$SearchPool? and $liveParams.$SearchPool == 'mk4_supply_v2'"/>
                    <set_value name="$useMK4LivePool" exact="$liveParams.$SearchPool? and $liveParams.$SearchPool == 'mk4_supply'"/>
                    <do_if value="$useMK42LivePool">
                      <set_value name="$liveParams.$Phase" exact="'mk42live'"/>
                      <do_if value="not global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}?">
                        <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}" exact="[]"/>
                      </do_if>
                      <set_value name="$mk42LiveQueueEntry" exact="table[
                        $Ship = $ship,
                        $Params = $liveParams,
                        $HomeSector = $homeSector,
                        $EnqueuedAt = player.age
                      ]"/>
                      <set_value name="$shipAlreadyInMK42LiveQueueDone" exact="false"/>
                      <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count gt 0">
                        <do_all exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count" counter="$mk42lqiDupDone">
                          <do_if value="@global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.{$mk42lqiDupDone}.$Ship == $ship">
                            <set_value name="$shipAlreadyInMK42LiveQueueDone" exact="true"/>
                          </do_if>
                        </do_all>
                      </do_if>
                      <do_if value="not $shipAlreadyInMK42LiveQueueDone">
                        <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}" exact="$mk42LiveQueueEntry"/>
                      </do_if>
                      <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}" exact="true"/>
                      <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'mk42live_queued'"/>
                      <do_if value="not global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}?">
                        <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$homeSector"/>
                        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}" exact="true"/>
                      </do_if>
                    </do_if>
                    <do_elseif value="$useMK4LivePool">
                      <set_value name="$liveParams.$Phase" exact="'mk4live'"/>
                      <do_if value="not global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}?">
                        <set_value name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}" exact="[]"/>
                      </do_if>
                      <set_value name="$mk4LiveQueueEntry" exact="table[
                        $Ship = $ship,
                        $Params = $liveParams,
                        $HomeSector = $homeSector,
                        $EnqueuedAt = player.age
                      ]"/>
                      <set_value name="$shipAlreadyInMK4LiveQueueDone" exact="false"/>
                      <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count gt 0">
                        <do_all exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count" counter="$mk4lqiDupDone">
                          <do_if value="@global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.{$mk4lqiDupDone}.$Ship == $ship">
                            <set_value name="$shipAlreadyInMK4LiveQueueDone" exact="true"/>
                          </do_if>
                        </do_all>
                      </do_if>
                      <do_if value="not $shipAlreadyInMK4LiveQueueDone">
                        <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}" exact="$mk4LiveQueueEntry"/>
                      </do_if>
                      <set_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}" exact="true"/>
                      <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'mk4live_queued'"/>
                      <do_if value="not global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}?">
                        <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="$homeSector"/>
                        <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}" exact="true"/>
                      </do_if>
                      <do_if value="$starvedWaiter and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-Scheduler] HandleSearchDone: Promoted starved MK4 waiter ' + $ship.idcode + ' to mk4live queue home=' + (if $homeSector? and $homeSector.knownname? then @$homeSector.knownname else '?')" chance="100"/>
                      </do_if>
                    </do_elseif>
                    <do_else>
                      <do_if value="not global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}?">
                        <set_value name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}" exact="[]"/>
                      </do_if>
                      <set_value name="$liveQueueEntry" exact="table[
                        $Ship = $ship,
                        $Params = $liveParams,
                        $HomeSector = $homeSector,
                        $EnqueuedAt = player.age
                      ]"/>
                      <set_value name="$shipAlreadyInLiveQueueDone" exact="false"/>
                      <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
                        <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$lqiDupDone">
                          <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$lqiDupDone}.$Ship == $ship">
                            <set_value name="$shipAlreadyInLiveQueueDone" exact="true"/>
                          </do_if>
                        </do_all>
                      </do_if>
                      <do_if value="not $shipAlreadyInLiveQueueDone">
                        <append_to_list name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}" exact="$liveQueueEntry"/>
                      </do_if>
                      <set_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}" exact="true"/>
                      <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'live_queued'"/>
                      <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}?">
                        <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
                        <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}" exact="true"/>
                      </do_if>
                      <do_if value="$starvedWaiter and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GT-Scheduler] HandleSearchDone: Promoted starved waiter ' + $ship.idcode + ' to live queue home=' + (if $homeSector? and $homeSector.knownname? then @$homeSector.knownname else '?')" chance="100"/>
                      </do_if>
                    </do_else>
                  </do_if>
                </do_else>
                </do_if>
              </do_else>
            </do_else>
          </do_if>
          <do_else>
            <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
              <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
            </do_if>
          </do_else>

          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
        </do_if>

        <do_if value="$searchType == 'clearance'">
          <set_value name="$homeSector" exact="if $ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$ClearanceActiveShips? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}.$HomeSector? then @global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}.$HomeSector else (if $ship? then $ship.sector else null)"/>
          <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$ClearanceActiveShips? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$ClearanceActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$ClearanceActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
          </do_if>

          <do_if value="$ship? and $ship.exists">
            <do_if value="$found and $tradeList.count gt 0">
              <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
                $TradeList = $tradeList,
                $SearchMethod = $searchMethod
              ]" delay="1ms"/>
            </do_if>
            <do_else>
              <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_trade'" delay="1ms"/>
            </do_else>
          </do_if>

          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
        </do_if>

        <do_if value="$searchType == 'mk42live'">
          <set_value name="$homeSector" exact="if $mk4LiveEntry? and $mk4LiveEntry.$HomeSector? then @$mk4LiveEntry.$HomeSector else (if $mk4LiveEntry? and $mk4LiveEntry.$Params? and $mk4LiveEntry.$Params.$HomeSector? then @$mk4LiveEntry.$Params.$HomeSector else (if $ship? then $ship.sector else null))"/>
          <set_value name="$ownedMK42LiveHomes" exact="[]"/>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.count gt 0">
            <set_value name="$mk4LiveHomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.list"/>
            <do_all exact="$mk4LiveHomeKeys.count" counter="$mk4lhki">
              <set_value name="$mk4lhk" exact="$mk4LiveHomeKeys.{$mk4lhki}"/>
              <do_if value="$mk4lhk? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk4lhk}? and @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk4lhk} == $ship">
                <append_to_list name="$ownedMK42LiveHomes" exact="$mk4lhk"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$homeSector}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$homeSector}"/>
          </do_if>
          <do_if value="$ownedMK42LiveHomes.count gt 0">
            <do_all exact="$ownedMK42LiveHomes.count" counter="$mk4ohi">
              <set_value name="$mk4OwnedHome" exact="$ownedMK42LiveHomes.{$mk4ohi}"/>
              <do_if value="$mk4OwnedHome? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk4OwnedHome}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk4OwnedHome}"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
          </do_if>

          <!-- Wake MK42 waiters for this home key -->
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.keys.count gt 0">
            <set_value name="$mk4WaiterHomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.keys.list"/>
            <do_all exact="$mk4WaiterHomeKeys.count" counter="$mk4whki">
              <set_value name="$mk4WaiterHome" exact="$mk4WaiterHomeKeys.{$mk4whki}"/>
              <set_value name="$mk4WakeThisHome" exact="false"/>
              <do_if value="$homeSector? and $mk4WaiterHome == $homeSector">
                <set_value name="$mk4WakeThisHome" exact="true"/>
              </do_if>
              <do_if value="not $mk4WakeThisHome and $ownedMK42LiveHomes.count gt 0">
                <do_all exact="$ownedMK42LiveHomes.count" counter="$mk4ohi">
                  <do_if value="$ownedMK42LiveHomes.{$mk4ohi} == $mk4WaiterHome">
                    <set_value name="$mk4WakeThisHome" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$mk4WakeThisHome and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk4WaiterHome}? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk4WaiterHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk4WaiterHome}.count" counter="$mk4wi">
                  <set_value name="$mk4wShip" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk4WaiterHome}.{$mk4wi}"/>
                  <do_if value="$mk4wShip? and $mk4wShip.exists">
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
                    </do_if>
                    <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk4wShip}" exact="true"/>
                    <signal_objects object="$mk4wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                  </do_if>
                </do_all>
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk4WaiterHome}" exact="[]"/>
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk4WaiterHome}" exact="table[]"/>
              </do_if>
            </do_all>
          </do_if>

          <!-- Re-queue home if pending MK42 live requests remain -->
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count gt 0">
            <do_if value="not global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}?">
              <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$homeSector"/>
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}" exact="true"/>
            </do_if>
          </do_if>

          <do_if value="$ship? and $ship.exists">
            <do_if value="$found and $tradeList.count gt 0">
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterPassCount? and global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
              </do_if>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$homeSector}.{$ship}"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
                $TradeList = $tradeList,
                $SearchMethod = $searchMethod
              ]" delay="1ms"/>
            </do_if>
            <do_else>
              <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_trade'" delay="1ms"/>
            </do_else>
          </do_if>

          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
        </do_if>

        <do_if value="$searchType == 'mk4live'">
          <set_value name="$homeSector" exact="if $mk4LiveEntry? and $mk4LiveEntry.$HomeSector? then @$mk4LiveEntry.$HomeSector else (if $mk4LiveEntry? and $mk4LiveEntry.$Params? and $mk4LiveEntry.$Params.$HomeSector? then @$mk4LiveEntry.$Params.$HomeSector else (if $ship? then $ship.sector else null))"/>
          <set_value name="$ownedMK4LiveHomes" exact="[]"/>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.keys.count gt 0">
            <set_value name="$mk4LiveHomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveHomeActive.keys.list"/>
            <do_all exact="$mk4LiveHomeKeys.count" counter="$mk4lhki">
              <set_value name="$mk4lhk" exact="$mk4LiveHomeKeys.{$mk4lhki}"/>
              <do_if value="$mk4lhk? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4lhk}? and @global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4lhk} == $ship">
                <append_to_list name="$ownedMK4LiveHomes" exact="$mk4lhk"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$homeSector}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$homeSector}"/>
          </do_if>
          <do_if value="$ownedMK4LiveHomes.count gt 0">
            <do_all exact="$ownedMK4LiveHomes.count" counter="$mk4ohi">
              <set_value name="$mk4OwnedHome" exact="$ownedMK4LiveHomes.{$mk4ohi}"/>
              <do_if value="$mk4OwnedHome? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4OwnedHome}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$mk4OwnedHome}"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
          </do_if>

          <!-- Wake MK4 waiters for this home key -->
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.count gt 0">
            <set_value name="$mk4WaiterHomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.list"/>
            <do_all exact="$mk4WaiterHomeKeys.count" counter="$mk4whki">
              <set_value name="$mk4WaiterHome" exact="$mk4WaiterHomeKeys.{$mk4whki}"/>
              <set_value name="$mk4WakeThisHome" exact="false"/>
              <do_if value="$homeSector? and $mk4WaiterHome == $homeSector">
                <set_value name="$mk4WakeThisHome" exact="true"/>
              </do_if>
              <do_if value="not $mk4WakeThisHome and $ownedMK4LiveHomes.count gt 0">
                <do_all exact="$ownedMK4LiveHomes.count" counter="$mk4ohi">
                  <do_if value="$ownedMK4LiveHomes.{$mk4ohi} == $mk4WaiterHome">
                    <set_value name="$mk4WakeThisHome" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$mk4WakeThisHome and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4WaiterHome}? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4WaiterHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4WaiterHome}.count" counter="$mk4wi">
                  <set_value name="$mk4wShip" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4WaiterHome}.{$mk4wi}"/>
                  <do_if value="$mk4wShip? and $mk4wShip.exists">
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
                    </do_if>
                    <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk4wShip}" exact="true"/>
                    <signal_objects object="$mk4wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                  </do_if>
                </do_all>
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4WaiterHome}" exact="[]"/>
                <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4WaiterHome}" exact="table[]"/>
              </do_if>
            </do_all>
          </do_if>

          <!-- Re-queue home if pending MK4 live requests remain -->
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count gt 0">
            <do_if value="not global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}?">
              <append_to_list name="global.$GT_SearchSemaphore.$MK4LiveHomesQueue" exact="$homeSector"/>
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveHomesQueued.{$homeSector}" exact="true"/>
            </do_if>
          </do_if>

          <do_if value="$ship? and $ship.exists">
            <do_if value="$found and $tradeList.count gt 0">
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterPassCount? and global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
              </do_if>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$homeSector}.{$ship}"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
                $TradeList = $tradeList,
                $SearchMethod = $searchMethod
              ]" delay="1ms"/>
            </do_if>
            <do_else>
              <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_trade'" delay="1ms"/>
            </do_else>
          </do_if>

          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
        </do_if>

        <do_if value="$searchType != 'cache' and $searchType != 'clearance' and $searchType != 'mk4live' and $searchType != 'mk42live'">
          <set_value name="$homeSector" exact="if $homeSectorFromDone? and $homeSectorFromDone.exists then $homeSectorFromDone else (if $liveEntry? and $liveEntry.$HomeSector? then @$liveEntry.$HomeSector else (if $liveEntry? and $liveEntry.$Params? and $liveEntry.$Params.$HomeSector? then @$liveEntry.$Params.$HomeSector else (if $ship? then $ship.sector else null)))"/>
          <set_value name="$ownedLiveHomes" exact="[]"/>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.keys.count gt 0">
            <set_value name="$liveHomeKeys" exact="global.$GT_SearchSemaphore.$LiveHomeActive.keys.list"/>
            <do_all exact="$liveHomeKeys.count" counter="$lhki">
              <set_value name="$lhk" exact="$liveHomeKeys.{$lhki}"/>
              <do_if value="$lhk? and global.$GT_SearchSemaphore.$LiveHomeActive.{$lhk}? and @global.$GT_SearchSemaphore.$LiveHomeActive.{$lhk} == $ship">
                <append_to_list name="$ownedLiveHomes" exact="$lhk"/>
              </do_if>
            </do_all>
          </do_if>

          <do_if value="$ship? and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$LiveActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$LiveActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$homeSector}"/>
          </do_if>
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome? and global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$homeSector}?">
            <remove_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$homeSector}"/>
          </do_if>
          <do_if value="$ownedLiveHomes.count gt 0">
            <do_all exact="$ownedLiveHomes.count" counter="$ohi">
              <set_value name="$ownedHome" exact="$ownedLiveHomes.{$ohi}"/>
              <do_if value="$ownedHome? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$ownedHome}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$ownedHome}"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
          </do_if>

          <!-- Wake waiters for this home key; fallback by active-home owner match to avoid missed notifications. -->
          <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome? and global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.count gt 0">
            <set_value name="$waiterHomeKeys" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.list"/>
            <do_all exact="$waiterHomeKeys.count" counter="$whki">
              <set_value name="$waiterHome" exact="$waiterHomeKeys.{$whki}"/>
              <set_value name="$wakeThisHome" exact="false"/>
              <do_if value="$homeSector? and $waiterHome == $homeSector">
                <set_value name="$wakeThisHome" exact="true"/>
              </do_if>
              <do_if value="not $wakeThisHome and $ownedLiveHomes.count gt 0">
                <do_all exact="$ownedLiveHomes.count" counter="$ohi">
                  <do_if value="$ownedLiveHomes.{$ohi} == $waiterHome">
                    <set_value name="$wakeThisHome" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="$wakeThisHome and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$waiterHome}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$waiterHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$waiterHome}.count" counter="$wi">
                  <set_value name="$wShip" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$waiterHome}.{$wi}"/>
                  <do_if value="$wShip? and $wShip.exists">
                    <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                      <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
                    </do_if>
                    <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$wShip}" exact="true"/>
                    <signal_objects object="$wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                  </do_if>
                </do_all>
                <set_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$waiterHome}" exact="[]"/>
                <set_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$waiterHome}" exact="table[]"/>
              </do_if>
            </do_all>
          </do_if>

          <!-- If this home still has pending live requests, re-queue its home bucket for fair dispatch -->
          <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
            <do_if value="not global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}?">
              <append_to_list name="global.$GT_SearchSemaphore.$LiveHomesQueue" exact="$homeSector"/>
              <set_value name="global.$GT_SearchSemaphore.$LiveHomesQueued.{$homeSector}" exact="true"/>
            </do_if>
          </do_if>

          <do_if value="$ship? and $ship.exists">
            <do_if value="$found and $tradeList.count gt 0">
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterPassCount? and global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
              </do_if>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$homeSector}.{$ship}"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
                $TradeList = $tradeList,
                $SearchMethod = $searchMethod
              ]" delay="1ms"/>
            </do_if>
            <do_else>
              <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_trade'" delay="1ms"/>
            </do_else>
          </do_if>

          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
        </do_if>

        <!-- Branch-independent fallback: if this ship owned live-home slots, wake and clear their waiters.
             This guarantees immediate waiter reset even if SearchType classification was unexpected. -->
        <do_if value="$ownedLiveHomesEarly.count gt 0 and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveWaitersByHome?">
          <do_all exact="$ownedLiveHomesEarly.count" counter="$ohiEarly">
            <set_value name="$ownedHomeEarly" exact="$ownedLiveHomesEarly.{$ohiEarly}"/>
            <do_if value="$ownedHomeEarly? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$ownedHomeEarly}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$ownedHomeEarly}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$ownedHomeEarly}.count" counter="$wi">
                <set_value name="$wShip" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$ownedHomeEarly}.{$wi}"/>
                <do_if value="$wShip? and $wShip.exists">
                  <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                    <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$wShip}" exact="true"/>
                  <signal_objects object="$wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                </do_if>
              </do_all>
              <set_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$ownedHomeEarly}" exact="[]"/>
              <set_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$ownedHomeEarly}" exact="table[]"/>
            </do_if>
          </do_all>
        </do_if>

        <!-- Branch-independent fallback: if this ship owned MK4 live-home slots, wake and clear their waiters. -->
        <do_if value="$ownedMK4LiveHomesEarly.count gt 0 and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome?">
          <do_all exact="$ownedMK4LiveHomesEarly.count" counter="$mk4ohiEarly">
            <set_value name="$mk4OwnedHomeEarly" exact="$ownedMK4LiveHomesEarly.{$mk4ohiEarly}"/>
            <do_if value="$mk4OwnedHomeEarly? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4OwnedHomeEarly}? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4OwnedHomeEarly}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4OwnedHomeEarly}.count" counter="$mk4wi">
                <set_value name="$mk4wShip" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4OwnedHomeEarly}.{$mk4wi}"/>
                <do_if value="$mk4wShip? and $mk4wShip.exists">
                  <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                    <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
                  </do_if>
                  <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk4wShip}" exact="true"/>
                  <signal_objects object="$mk4wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                </do_if>
              </do_all>
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4OwnedHomeEarly}" exact="[]"/>
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4OwnedHomeEarly}" exact="table[]"/>
            </do_if>
          </do_all>
        </do_if>

      </actions>
    </cue>

    <!-- MK4 cache metadata grew: wake ships parked in MK4 live queue so they retry cache first. -->
    <cue name="HandleMK4CacheUpdated" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_MK4_Cache_Updated'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$homeSector" exact="@$data.$HomeSector"/>
        <set_value name="$updatedMaxDistance" exact="if $data? and $data.$MaxDistance? then @$data.$MaxDistance else 0"/>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>
        <do_if value="$homeSector? and $homeSector.exists and global.$GT_SearchSemaphore?">
          <set_value name="$cachePoolUpdated" exact="if $data? and $data.$CachePool? then @$data.$CachePool else 'mk4'"/>
          <set_value name="$cacheEntryCount" exact="0"/>
          <do_if value="$cachePoolUpdated == 'mk4'">
            <do_if value="global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}?">
              <set_value name="$cacheEntryCount" exact="@global.$GT_TradeCacheMK4.{$homeSector}.count"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="global.$GT_TradeCache? and global.$GT_TradeCache.{$homeSector}?">
              <set_value name="$cacheEntryCount" exact="@global.$GT_TradeCache.{$homeSector}.count"/>
            </do_if>
          </do_else>
          <do_if value="$data? and $data.$Written? and $data.$Written gt 0">
            <!-- Fresh cache writes supersede prior per-ship skip markers on all entries. -->
            <do_if value="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}?">
              <set_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$homeSector}" exact="table[]"/>
            </do_if>
            <do_if value="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome? and global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$homeSector}?">
              <remove_value name="global.$GT_SearchSemaphore.$CacheLiveRefreshPendingByHome.{$homeSector}"/>
            </do_if>
            <do_if value="$cachePoolUpdated == 'mk4' and global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}? and global.$GT_TradeCacheMK4.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_TradeCacheMK4.{$homeSector}.count" counter="$mk4clrCi">
                <set_value name="$mk4clrEntry" exact="global.$GT_TradeCacheMK4.{$homeSector}.{$mk4clrCi}"/>
                <do_if value="$mk4clrEntry? and $mk4clrEntry.$FailedShips? and $mk4clrEntry.$FailedShips.count gt 0">
                  <set_value name="$mk4clrEntry.$FailedShips" exact="[]"/>
                  <set_value name="global.$GT_TradeCacheMK4.{$homeSector}.{$mk4clrCi}" exact="$mk4clrEntry"/>
                </do_if>
              </do_all>
            </do_if>
            <do_elseif value="$cachePoolUpdated == 'mk3' and global.$GT_TradeCache? and global.$GT_TradeCache.{$homeSector}? and global.$GT_TradeCache.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_TradeCache.{$homeSector}.count" counter="$mk3clrCi">
                <set_value name="$mk3clrEntry" exact="global.$GT_TradeCache.{$homeSector}.{$mk3clrCi}"/>
                <do_if value="$mk3clrEntry? and $mk3clrEntry.$FailedShips? and $mk3clrEntry.$FailedShips.count gt 0">
                  <set_value name="$mk3clrEntry.$FailedShips" exact="[]"/>
                  <set_value name="global.$GT_TradeCache.{$homeSector}.{$mk3clrCi}" exact="$mk3clrEntry"/>
                </do_if>
              </do_all>
            </do_elseif>
            <set_value name="$mk4WakeShips" exact="[]"/>
            <set_value name="$mk4WakeShipSeen" exact="table[]"/>
            <!-- MK4 live queue waiters -->
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.count" counter="$mk4cwi">
                <set_value name="$mk4cwEntry" exact="@global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$homeSector}.{$mk4cwi}"/>
                <set_value name="$mk4cwShip" exact="if $mk4cwEntry? and $mk4cwEntry.$Ship? then @$mk4cwEntry.$Ship else null"/>
                <do_if value="$mk4cwShip? and $mk4cwShip.exists and not $mk4WakeShipSeen.{$mk4cwShip}?">
                  <append_to_list name="$mk4WakeShips" exact="$mk4cwShip"/>
                  <set_value name="$mk4WakeShipSeen.{$mk4cwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- Legacy live queue (mk4PolicyNeedsLiveSearch path) -->
            <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$lcwi">
                <set_value name="$lcwEntry" exact="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$lcwi}"/>
                <set_value name="$lcwShip" exact="if $lcwEntry? and $lcwEntry.$Ship? then @$lcwEntry.$Ship else null"/>
                <do_if value="$lcwShip? and $lcwShip.exists and not $mk4WakeShipSeen.{$lcwShip}?">
                  <append_to_list name="$mk4WakeShips" exact="$lcwShip"/>
                  <set_value name="$mk4WakeShipSeen.{$lcwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- MK4 live refresh waiters (blocked on same-home active slot) -->
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}.count" counter="$mk4wwi">
                <set_value name="$mk4wwShip" exact="@global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$homeSector}.{$mk4wwi}"/>
                <do_if value="$mk4wwShip? and $mk4wwShip.exists and not $mk4WakeShipSeen.{$mk4wwShip}?">
                  <append_to_list name="$mk4WakeShips" exact="$mk4wwShip"/>
                  <set_value name="$mk4WakeShipSeen.{$mk4wwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- MK3 live refresh waiters (blocked on same-home active slot) -->
            <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count" counter="$mk3wwi">
                <set_value name="$mk3wwShip" exact="@global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$mk3wwi}"/>
                <do_if value="$mk3wwShip? and $mk3wwShip.exists and not $mk4WakeShipSeen.{$mk3wwShip}?">
                  <append_to_list name="$mk4WakeShips" exact="$mk3wwShip"/>
                  <set_value name="$mk4WakeShipSeen.{$mk3wwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- MK3 cache-saturation waiters (pool has entries but per-ship read returned 0) -->
            <do_if value="global.$GT_SearchSemaphore.$CacheWaitersByHome? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.count" counter="$mk3cwwi">
                <set_value name="$mk3cwShip" exact="@global.$GT_SearchSemaphore.$CacheWaitersByHome.{$homeSector}.{$mk3cwwi}"/>
                <do_if value="$mk3cwShip? and $mk3cwShip.exists and not $mk4WakeShipSeen.{$mk3cwShip}?">
                  <append_to_list name="$mk4WakeShips" exact="$mk3cwShip"/>
                  <set_value name="$mk4WakeShipSeen.{$mk3cwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- Cache-phase queue for same home -->
            <do_if value="global.$GT_SearchSemaphore.$CacheQueue? and global.$GT_SearchSemaphore.$CacheQueue.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$CacheQueue.count" counter="$ccwi">
                <set_value name="$ccwEntry" exact="@global.$GT_SearchSemaphore.$CacheQueue.{$ccwi}"/>
                <set_value name="$ccwShip" exact="if $ccwEntry? and $ccwEntry.$Ship? then @$ccwEntry.$Ship else null"/>
                <set_value name="$ccwHome" exact="if $ccwEntry? and $ccwEntry.$HomeSector? then @$ccwEntry.$HomeSector else null"/>
                <do_if value="$ccwShip? and $ccwShip.exists and $ccwHome? and $ccwHome == $homeSector and not $mk4WakeShipSeen.{$ccwShip}?">
                  <append_to_list name="$mk4WakeShips" exact="$ccwShip"/>
                  <set_value name="$mk4WakeShipSeen.{$ccwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <do_all exact="$mk4WakeShips.count" counter="$mk4wsi">
              <set_value name="$mk4wShip" exact="$mk4WakeShips.{$mk4wsi}"/>
              <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = $mk4wShip]" delay="1ms"/>
              <signal_objects object="$mk4wShip" param="'GT_TradeSearch_Reset'" delay="2ms"/>
            </do_all>
            <do_if value="$mk4WakeShips.count gt 0 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleMK4CacheUpdated: Woke ' + $mk4WakeShips.count + ' waiting ships to retry cache home=' + (if $homeSector.knownname? then @$homeSector.knownname else '?') + ' pool=' + $cachePoolUpdated + ' entries=' + $cacheEntryCount + ' maxDist=' + $updatedMaxDistance" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <cue name="HandleSearchAbort" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Search_Abort'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$ship" exact="@$data.$Ship"/>

        <do_if value="global.$GT_SearchSemaphore? and $ship?">
          <set_value name="$activeLiveHome" exact="if global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}.$HomeSector? then @global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}.$HomeSector else null"/>
          <set_value name="$activeMK4LiveHome" exact="if global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}.$HomeSector? then @global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}.$HomeSector else null"/>
          <set_value name="$activeMK42LiveHome" exact="if global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}.$HomeSector? then @global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}.$HomeSector else null"/>

          <!-- Remove from queued lookup tables -->
          <do_if value="global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$CacheQueued.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveQueued.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueued? and global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueued.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueued? and global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$ClearanceQueued? and global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$ClearanceQueued.{$ship}"/>
          </do_if>

          <!-- Remove from cache queue list -->
          <do_if value="global.$GT_SearchSemaphore.$CacheQueue? and global.$GT_SearchSemaphore.$CacheQueue.count gt 0">
            <do_all exact="global.$GT_SearchSemaphore.$CacheQueue.count" counter="$qi" reverse="true">
              <do_if value="@global.$GT_SearchSemaphore.$CacheQueue.{$qi}.$Ship == $ship">
                <remove_value name="global.$GT_SearchSemaphore.$CacheQueue.{$qi}"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$ClearanceQueue? and global.$GT_SearchSemaphore.$ClearanceQueue.count gt 0">
            <do_all exact="global.$GT_SearchSemaphore.$ClearanceQueue.count" counter="$qi" reverse="true">
              <do_if value="@global.$GT_SearchSemaphore.$ClearanceQueue.{$qi}.$Ship == $ship">
                <remove_value name="global.$GT_SearchSemaphore.$ClearanceQueue.{$qi}"/>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveQueueByHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.keys.count gt 0">
            <set_value name="$mk4AbortHomeKeys" exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.keys.list"/>
            <do_all exact="$mk4AbortHomeKeys.count" counter="$mk4ahi">
              <set_value name="$mk4AbortHome" exact="$mk4AbortHomeKeys.{$mk4ahi}"/>
              <do_if value="$mk4AbortHome? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4AbortHome}? and global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4AbortHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4AbortHome}.count" counter="$qi" reverse="true">
                  <do_if value="@global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4AbortHome}.{$qi}.$Ship == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$MK4LiveQueueByHome.{$mk4AbortHome}.{$qi}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueueByHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.keys.count gt 0">
            <set_value name="$mk42AbortHomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.keys.list"/>
            <do_all exact="$mk42AbortHomeKeys.count" counter="$mk42ahi">
              <set_value name="$mk42AbortHome" exact="$mk42AbortHomeKeys.{$mk42ahi}"/>
              <do_if value="$mk42AbortHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$mk42AbortHome}? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$mk42AbortHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$mk42AbortHome}.count" counter="$qi" reverse="true">
                  <do_if value="@global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$mk42AbortHome}.{$qi}.$Ship == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$mk42AbortHome}.{$qi}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>

          <!-- Remove from all home live queues -->
          <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.keys.count gt 0">
            <set_value name="$homeKeys" exact="global.$GT_SearchSemaphore.$LiveQueueByHome.keys.list"/>
            <do_all exact="$homeKeys.count" counter="$hki">
              <set_value name="$homeSector" exact="$homeKeys.{$hki}"/>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$qi" reverse="true">
                  <do_if value="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$qi}.$Ship == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$qi}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>

          <!-- Remove from active tables and release slots -->
          <do_if value="global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$CacheActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$CacheActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$LiveActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$LiveActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveActiveShips? and global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$MK4LiveActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$MK4LiveActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$ClearanceActiveShips? and global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$ClearanceActiveShips.{$ship}"/>
            <do_if value="global.$GT_SearchSemaphore.$ClearanceActive gt 0">
              <set_value name="global.$GT_SearchSemaphore.$ClearanceActive" operation="subtract"/>
            </do_if>
          </do_if>
          <do_if value="$activeLiveHome? and global.$GT_SearchSemaphore.$LiveHomeActive? and global.$GT_SearchSemaphore.$LiveHomeActive.{$activeLiveHome}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveHomeActive.{$activeLiveHome}"/>
          </do_if>
          <do_if value="$activeMK4LiveHome? and global.$GT_SearchSemaphore.$MK4LiveHomeActive? and global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$activeMK4LiveHome}?">
            <remove_value name="global.$GT_SearchSemaphore.$MK4LiveHomeActive.{$activeMK4LiveHome}"/>
          </do_if>
          <do_if value="$activeMK42LiveHome? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$activeMK42LiveHome}? and @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$activeMK42LiveHome} == $ship">
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$activeMK42LiveHome}"/>
          </do_if>
          <!-- Defensive: drop any MK4-2 home this ship still owns (entry HomeSector may be missing on legacy slots). -->
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.count gt 0">
            <set_value name="$mk42OwnedHomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.list"/>
            <do_all exact="$mk42OwnedHomeKeys.count" counter="$mk42ohki">
              <set_value name="$mk42OwnedHome" exact="$mk42OwnedHomeKeys.{$mk42ohki}"/>
              <do_if value="$mk42OwnedHome? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42OwnedHome}? and @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42OwnedHome} == $ship">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42OwnedHome}"/>
              </do_if>
            </do_all>
          </do_if>

          <!-- Remove from MK4 waiter lists -->
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.count gt 0">
            <set_value name="$mk4WaiterHomes" exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.keys.list"/>
            <do_all exact="$mk4WaiterHomes.count" counter="$mk4hi">
              <set_value name="$mk4HomeSector" exact="$mk4WaiterHomes.{$mk4hi}"/>
              <do_if value="$mk4HomeSector? and global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4HomeSector}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterQueuedByHome.{$mk4HomeSector}.{$ship}"/>
              </do_if>
              <do_if value="$mk4HomeSector? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}? and global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.count" counter="$mk4wi" reverse="true">
                  <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.{$mk4wi} == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaitersByHome.{$mk4HomeSector}.{$mk4wi}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.keys.count gt 0">
            <set_value name="$mk4WaiterStartedHomes" exact="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.keys.list"/>
            <do_all exact="$mk4WaiterStartedHomes.count" counter="$mk4wshi">
              <set_value name="$mk4wshHome" exact="$mk4WaiterStartedHomes.{$mk4wshi}"/>
              <do_if value="$mk4wshHome? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4wshHome}? and global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4wshHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK4LiveWaiterStartedAt.{$mk4wshHome}.{$ship}"/>
              </do_if>
            </do_all>
          </do_if>

          <!-- Remove this ship from MK4-2 waiter lists -->
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.keys.count gt 0">
            <set_value name="$mk42WaiterHomes" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.keys.list"/>
            <do_all exact="$mk42WaiterHomes.count" counter="$mk42whi">
              <set_value name="$mk42WaiterHome" exact="$mk42WaiterHomes.{$mk42whi}"/>
              <do_if value="$mk42WaiterHome? and global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk42WaiterHome}? and global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk42WaiterHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk42WaiterHome}.{$ship}"/>
              </do_if>
              <do_if value="$mk42WaiterHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42WaiterHome}? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42WaiterHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42WaiterHome}.count" counter="$mk42wci" reverse="true">
                  <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42WaiterHome}.{$mk42wci} == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42WaiterHome}.{$mk42wci}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.keys.count gt 0">
            <set_value name="$mk42WaiterStartedHomes" exact="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.keys.list"/>
            <do_all exact="$mk42WaiterStartedHomes.count" counter="$mk42wshi">
              <set_value name="$mk42wshHome" exact="$mk42WaiterStartedHomes.{$mk42wshi}"/>
              <do_if value="$mk42wshHome? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42wshHome}? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42wshHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42wshHome}.{$ship}"/>
              </do_if>
            </do_all>
          </do_if>

          <!-- Owner aborted: wake same-home MK4-2 waiters so they retry immediately, and re-queue the
               freed home so any queued fleet ships are dispatched on the next pass (instead of waiting
               for the 100s stale self-heal). -->
          <do_if value="$activeMK42LiveHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$activeMK42LiveHome}? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$activeMK42LiveHome}.count gt 0">
            <do_all exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$activeMK42LiveHome}.count" counter="$mk42wwi">
              <set_value name="$mk42wwShip" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$activeMK42LiveHome}.{$mk42wwi}"/>
              <do_if value="$mk42wwShip? and $mk42wwShip.exists">
                <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                  <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
                </do_if>
                <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk42wwShip}" exact="true"/>
                <signal_objects object="$mk42wwShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
              </do_if>
            </do_all>
            <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$activeMK42LiveHome}" exact="[]"/>
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome?">
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$activeMK42LiveHome}" exact="table[]"/>
            </do_if>
          </do_if>
          <do_if value="$activeMK42LiveHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$activeMK42LiveHome}? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$activeMK42LiveHome}.count gt 0 and not global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$activeMK42LiveHome}?">
            <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$activeMK42LiveHome"/>
            <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$activeMK42LiveHome}" exact="true"/>
          </do_if>

          <!-- Remove from waiter lists -->
          <do_if value="global.$GT_SearchSemaphore.$CacheWaitersByHome? and global.$GT_SearchSemaphore.$CacheWaitersByHome.keys.count gt 0">
            <set_value name="$cacheWaiterAbortHomes" exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.keys.list"/>
            <do_all exact="$cacheWaiterAbortHomes.count" counter="$cwhi">
              <set_value name="$cwhHome" exact="$cacheWaiterAbortHomes.{$cwhi}"/>
              <do_if value="$cwhHome? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$cwhHome}? and global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$cwhHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterQueuedByHome.{$cwhHome}.{$ship}"/>
              </do_if>
              <do_if value="$cwhHome? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cwhHome}? and global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cwhHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterStartedAt.{$cwhHome}.{$ship}"/>
              </do_if>
              <do_if value="$cwhHome? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cwhHome}? and global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cwhHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$CacheWaiterFirstParkedAt.{$cwhHome}.{$ship}"/>
              </do_if>
              <do_if value="$cwhHome? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cwhHome}? and global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cwhHome}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cwhHome}.count" counter="$cwwi" reverse="true">
                  <do_if value="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cwhHome}.{$cwwi} == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$CacheWaitersByHome.{$cwhHome}.{$cwwi}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome? and global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.count gt 0">
            <set_value name="$waiterHomes" exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.keys.list"/>
            <do_all exact="$waiterHomes.count" counter="$hi">
              <set_value name="$homeSector" exact="$waiterHomes.{$hi}"/>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterQueuedByHome.{$homeSector}.{$ship}"/>
              </do_if>
              <do_if value="$homeSector? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count gt 0">
                <do_all exact="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.count" counter="$wi" reverse="true">
                  <do_if value="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$wi} == $ship">
                    <remove_value name="global.$GT_SearchSemaphore.$LiveWaitersByHome.{$homeSector}.{$wi}"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_all>
          </do_if>

          <do_if value="global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveWaiterPassCount? and global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterPassCount.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveWaiterWakePending? and global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}?">
            <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$ship}"/>
          </do_if>
          <do_if value="global.$GT_SearchSemaphore.$LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.keys.count gt 0">
            <set_value name="$waiterStartedHomes" exact="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.keys.list"/>
            <do_all exact="$waiterStartedHomes.count" counter="$wshi">
              <set_value name="$wshHome" exact="$waiterStartedHomes.{$wshi}"/>
              <do_if value="$wshHome? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$wshHome}? and global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$wshHome}.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$LiveWaiterStartedAt.{$wshHome}.{$ship}"/>
              </do_if>
            </do_all>
          </do_if>
        </do_if>

        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchCacheSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchLiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchMK4LiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.DispatchClearanceSearchGo"/>
      </actions>
    </cue>

    <!-- Startup cleanup: reservations clear + orphan credits (2s after load). No periodic loops. -->
    <cue name="SemaphoreStaleCheckInit" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.CreditsDueLogOnLoad"/>
      </actions>
    </cue>

    <!-- At game start: clear ALL reservations (stale from prev session, block new ships), orphan cleanup (credits due), then log.
         Delayed 2s to let state settle. Full reservation clear fixes "no trades found" when assigning GT to a single ship
         after revoking fleet GT (reservations from old fleet block offers until fleet is reactivated). -->
    <cue name="CreditsDueLogOnLoad" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="2s"/>
      <actions>
        <!-- Clear ALL reservations at load - any reservation from before save is stale and blocks new GT ships from finding trades -->
        <set_value name="$reservationsCleared" exact="0"/>
        <do_if value="global.$GT_Reservations? and typeof global.$GT_Reservations == datatype.table and global.$GT_Reservations.keys.count gt 0">
          <set_value name="$reservationsCleared" exact="global.$GT_Reservations.keys.count"/>
          <set_value name="global.$GT_Reservations" exact="table[]"/>
          <do_if value="global.$GT_ReservationStats?">
            <set_value name="global.$GT_ReservationStats.$Active" exact="0"/>
            <set_value name="global.$GT_ReservationStats.$Cleared" operation="add" exact="$reservationsCleared"/>
          </do_if>
        </do_if>

        <!-- Orphan cleanup for credits due (UICreditsDueByShip) - reservations already cleared above -->
        <run_actions ref="md.GLX_Lib_Reservations.GLX_CleanupOrphanedCreditsDueAndReservations" result="$loadCleanupResult">
          <param name="traceId" value="'load'"/>
        </run_actions>

        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and global.$GT_GlobalSettings.$Debug.$EnableDebugLogging?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <run_actions ref="md.GT_Libraries_General.GT_RecalculateUICreditsDueProjected"/>
            <set_value name="$rawVal" exact="0"/>
            <do_if value="global.$GT_UICreditsDueProjectedRaw?">
              <set_value name="$rawVal" exact="global.$GT_UICreditsDueProjectedRaw"/>
            </do_if>
            <set_value name="$cleanedOnLoad" exact="0"/>
            <do_if value="$loadCleanupResult? and $loadCleanupResult.$Cleaned?">
              <set_value name="$cleanedOnLoad" exact="$loadCleanupResult.$Cleaned"/>
            </do_if>
            <debug_text text="'[GT-OrphanCleanup] Game start: GT trade due = ' + ($rawVal / 100) + ' Cr (raw=' + $rawVal + '), reservations cleared = ' + $reservationsCleared + ', credits orphans cleaned = ' + $cleanedOnLoad" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_TradeSearch_Scheduler_MK42" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <cue name="InitMK42Semaphore" instantiate="true" version="1">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler.InitSearchSemaphore"/>
        </do_if>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveQueued" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" exact="0"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MaxConcurrentMK42Live" exact="2"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveDispatchScheduled" exact="false"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt" exact="table[]"/>
        <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterTickScheduled" exact="false"/>
      </actions>
    </cue>
<cue name="DispatchMK42LiveSearchGoDelayed" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay min="200ms" max="1000ms"/>
      <actions>
        <do_if value="global.$GT_SearchSemaphore?">
          <set_value name="global.$GT_SearchSemaphore.$MK42LiveDispatchScheduled" exact="false"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
      </actions>
    </cue>
<cue name="DispatchMK42LiveSearchGo" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.InitSearchSemaphore"/>
        </do_if>
        <!-- Global self-heal for stale MK42 live-active slots.
             Needed when legacy/aborted entries keep MK42LiveActive at capacity and block all new dispatches. -->
        <do_if value="global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.keys.count gt 0">
          <set_value name="$mk42ActiveKeys" exact="global.$GT_SearchSemaphore.$MK42LiveActiveShips.keys.list"/>
          <do_all exact="$mk42ActiveKeys.count" counter="$maki">
            <set_value name="$mk42ActiveShip" exact="$mk42ActiveKeys.{$maki}"/>
            <set_value name="$mk42ActiveEntry" exact="if $mk42ActiveShip? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42ActiveShip}? then @global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42ActiveShip} else null"/>
            <set_value name="$mk42ActiveStartedAt" exact="if $mk42ActiveEntry? and $mk42ActiveEntry.$StartedAt? then @$mk42ActiveEntry.$StartedAt else null"/>
            <set_value name="$mk42ActiveStale" exact="false"/>
            <do_if value="not $mk42ActiveShip? or ($mk42ActiveShip? and not $mk42ActiveShip.exists)">
              <set_value name="$mk42ActiveStale" exact="true"/>
            </do_if>
            <do_if value="not $mk42ActiveStale and ($mk42ActiveStartedAt == null or (player.age - $mk42ActiveStartedAt) gt 60s)">
              <set_value name="$mk42ActiveStale" exact="true"/>
            </do_if>
            <do_if value="$mk42ActiveStale">
              <do_if value="$mk42ActiveShip? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42ActiveShip}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42ActiveShip}"/>
              </do_if>
              <do_if value="global.$GT_SearchSemaphore.$MK42LiveActive gt 0">
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" operation="subtract"/>
              </do_if>
              <do_if value="$mk42ActiveEntry? and $mk42ActiveEntry.$HomeSector? and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42ActiveEntry.$HomeSector}? and @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42ActiveEntry.$HomeSector} == $mk42ActiveShip">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42ActiveEntry.$HomeSector}"/>
              </do_if>
              <do_if value="$mk42ActiveShip? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$mk42ActiveShip}? and @global.$GT_SearchSemaphore.$PhaseStateByShip.{$mk42ActiveShip} == 'mk42live_active'">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$mk42ActiveShip}"/>
              </do_if>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchMK42LiveSearchGo: Cleared stale MK42 active slot owner=' + (if $mk42ActiveShip? then $mk42ActiveShip.idcode else 'null') + ' startedAt=' + (if $mk42ActiveStartedAt? then $mk42ActiveStartedAt else 'null') + ' age=' + player.age" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <!-- Self-heal orphaned MK42LiveHomeActive slots (parity with MK3 LiveHomeActive). -->
        <set_value name="$mk42LiveStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$mk42LiveStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.count gt 0">
          <set_value name="$mk42OrphanHomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveHomeActive.keys.list"/>
          <do_all exact="$mk42OrphanHomeKeys.count" counter="$mk42ohi">
            <set_value name="$mk42OrphanHome" exact="$mk42OrphanHomeKeys.{$mk42ohi}"/>
            <set_value name="$mk42OrphanOwner" exact="if $mk42OrphanHome? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42OrphanHome}? then @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42OrphanHome} else null"/>
            <set_value name="$mk42OrphanHomeStale" exact="false"/>
            <do_if value="not $mk42OrphanOwner? or not $mk42OrphanOwner.exists">
              <set_value name="$mk42OrphanHomeStale" exact="true"/>
            </do_if>
            <do_if value="not $mk42OrphanHomeStale and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and not global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42OrphanOwner}?">
              <set_value name="$mk42OrphanHomeStale" exact="true"/>
            </do_if>
            <do_if value="not $mk42OrphanHomeStale and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42OrphanOwner}?">
              <set_value name="$mk42OrphanOwnerEntry" exact="@global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42OrphanOwner}"/>
              <set_value name="$mk42OrphanOwnerStartedAt" exact="if $mk42OrphanOwnerEntry? and $mk42OrphanOwnerEntry.$StartedAt? then @$mk42OrphanOwnerEntry.$StartedAt else null"/>
              <do_if value="$mk42OrphanOwnerStartedAt == null or (player.age - $mk42OrphanOwnerStartedAt) gt $mk42LiveStaleThreshold">
                <set_value name="$mk42OrphanHomeStale" exact="true"/>
              </do_if>
            </do_if>
            <do_if value="$mk42OrphanHomeStale">
              <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42OrphanHome}"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchMK42LiveSearchGo: Cleared orphaned MK42LiveHomeActive home=' + (if $mk42OrphanHome? and $mk42OrphanHome.knownname? then @$mk42OrphanHome.knownname else '?') + ' owner=' + (if $mk42OrphanOwner? then $mk42OrphanOwner.idcode else 'null')" chance="100"/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="global.$GT_SearchSemaphore.$MK42LiveHomesQueue.count gt 0 and global.$GT_SearchSemaphore.$MK42LiveActive ge global.$GT_SearchSemaphore.$MaxConcurrentMK42Live">
          <do_if value="not global.$GT_SearchSemaphore.$MK42LiveDispatchScheduled">
            <set_value name="global.$GT_SearchSemaphore.$MK42LiveDispatchScheduled" exact="true"/>
            <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGoDelayed"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- Fair round-robin by home sector -->
          <set_value name="$mk42HomeScanBudget" exact="global.$GT_SearchSemaphore.$MK42LiveHomesQueue.count"/>
          <do_while value="$mk42HomeScanBudget gt 0 and global.$GT_SearchSemaphore.$MK42LiveActive lt global.$GT_SearchSemaphore.$MaxConcurrentMK42Live and global.$GT_SearchSemaphore.$MK42LiveHomesQueue.count gt 0">
            <set_value name="$homeSector" exact="global.$GT_SearchSemaphore.$MK42LiveHomesQueue.{1}"/>
            <remove_from_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$homeSector"/>
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}"/>
            <set_value name="$mk42HomeScanBudget" operation="subtract"/>

            <!-- Skip homes that are currently active; requeue to tail -->
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$homeSector}?">
              <do_if value="not global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
              <continue/>
            </do_if>

            <do_if value="not global.$GT_SearchSemaphore.$MK42LiveQueueByHome? or not global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}? or global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count le 0">
              <continue/>
            </do_if>

            <set_value name="$entry" exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.{1}"/>
            <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.{1}"/>

            <set_value name="$ship" exact="@$entry.$Ship"/>
            <set_value name="$params" exact="@$entry.$Params"/>
            <set_value name="$dispatchParams" exact="if $params? then $params else table[]"/>
            <set_value name="$dispatchParams.$Phase" exact="'mk42live'"/>
            <set_value name="$dispatchParams.$HomeSector" exact="$homeSector"/>
            <set_value name="$dispatchParams.$SearchPool" exact="'mk4_supply_v2'"/>
            <!-- Honor an explicit ship request for a live search. A ship raises ForceLiveSearch=true only
                 after its cache attempt already failed (every cached candidate rejected for THIS ship). If we
                 silently downgrade to a cache re-read whenever the shared pool is non-empty, the ship is handed
                 the very same already-failing entries again and loops forever, never discovering the live demand
                 that other ships have not claimed (observed: FIK/FOB stuck re-reading CUP's pool of 30, never
                 running a live search). Only apply the cache-first heuristic when the ship did NOT explicitly
                 force live. -->
            <set_value name="$shipForcedLive" exact="$params? and $params.$ForceLiveSearch? and @$params.$ForceLiveSearch"/>
            <set_value name="$dispatchForceLive" exact="true"/>
            <do_if value="not $shipForcedLive and $homeSector? and $homeSector.exists and global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$homeSector}? and global.$GT_TradeCacheMK42.{$homeSector}.count gt 0">
              <set_value name="$dispatchForceLive" exact="false"/>
            </do_if>
            <set_value name="$dispatchParams.$ForceLiveSearch" exact="$dispatchForceLive"/>

            <do_if value="$ship? and $ship.exists">
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" operation="add"/>
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$ship}" exact="table[
                $StartedAt = player.age,
                $Params = $dispatchParams,
                $HomeSector = $homeSector
              ]"/>
              <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$homeSector}" exact="$ship"/>
              <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}"/>
              <set_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}" exact="'mk42live_active'"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Scheduler] DispatchMK42LiveSearchGo: Sending GT_Search_Go to ' + $ship.idcode + ' (age=' + player.age + ', mk42live)'" chance="100"/>
              </do_if>
              <signal_objects object="$ship" param="'GT_Search_Go'" param2="$dispatchParams" delay="1ms"/>
            </do_if>
            <do_else>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$MK42LiveQueued? and global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveQueued.{$ship}"/>
              </do_if>
              <do_if value="$ship? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
                <remove_value name="global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}"/>
              </do_if>
            </do_else>

            <!-- Keep home queued if there are still pending MK42 live entries for this home -->
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueueByHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count gt 0">
              <do_if value="not global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}?">
                <append_to_list name="global.$GT_SearchSemaphore.$MK42LiveHomesQueue" exact="$homeSector"/>
                <set_value name="global.$GT_SearchSemaphore.$MK42LiveHomesQueued.{$homeSector}" exact="true"/>
              </do_if>
            </do_if>
          </do_while>
        </do_else>
      </actions>
    </cue>
<cue name="NotifyMK42LiveWaitersTick" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="20s"/>
      <actions>
        <set_value name="$hasAnyMK42ActiveWaiters" exact="false"/>
        <set_value name="$mk42WaiterStaleThreshold" exact="120s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds?">
          <set_value name="$mk42WaiterStaleThreshold" exact="@global.$GT_GlobalSettings.$Performance.$StaleThresholdSeconds"/>
        </do_if>
        <do_if value="global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.keys.count gt 0">
          <set_value name="$mk42HomeKeys" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.keys.list"/>
          <do_all exact="$mk42HomeKeys.count" counter="$mk42hki">
            <set_value name="$mk42HomeSector" exact="$mk42HomeKeys.{$mk42hki}"/>
            <do_if value="$mk42HomeSector? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.count gt 0">
              <set_value name="$mk42HomeOwner" exact="if global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42HomeSector}? then @global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42HomeSector} else null"/>
              <set_value name="$mk42HomeOwnerStale" exact="false"/>
              <do_if value="not $mk42HomeOwner? or not $mk42HomeOwner.exists">
                <set_value name="$mk42HomeOwnerStale" exact="true"/>
              </do_if>
              <do_if value="not $mk42HomeOwnerStale and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and not global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42HomeOwner}?">
                <set_value name="$mk42HomeOwnerStale" exact="true"/>
              </do_if>
              <do_if value="not $mk42HomeOwnerStale and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42HomeOwner}?">
                <set_value name="$mk42HomeOwnerEntry" exact="@global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42HomeOwner}"/>
                <set_value name="$mk42HomeOwnerStartedAt" exact="if $mk42HomeOwnerEntry? and $mk42HomeOwnerEntry.$StartedAt? then @$mk42HomeOwnerEntry.$StartedAt else null"/>
                <do_if value="$mk42HomeOwnerStartedAt == null or (player.age - $mk42HomeOwnerStartedAt) gt $mk42WaiterStaleThreshold">
                  <set_value name="$mk42HomeOwnerStale" exact="true"/>
                </do_if>
              </do_if>
              <do_if value="$mk42HomeOwnerStale and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42HomeSector}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42HomeSector}"/>
              </do_if>
              <do_if value="$mk42HomeOwnerStale and $mk42HomeOwner? and global.$GT_SearchSemaphore.$MK42LiveActiveShips? and global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42HomeOwner}?">
                <remove_value name="global.$GT_SearchSemaphore.$MK42LiveActiveShips.{$mk42HomeOwner}"/>
                <do_if value="global.$GT_SearchSemaphore.$MK42LiveActive gt 0">
                  <set_value name="global.$GT_SearchSemaphore.$MK42LiveActive" operation="subtract"/>
                </do_if>
              </do_if>

              <do_all exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.count" counter="$mk42wi" reverse="true">
                <set_value name="$mk42wShip" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.{$mk42wi}"/>
                <do_if value="not $mk42wShip? or not $mk42wShip.exists">
                  <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.{$mk42wi}"/>
                  <continue/>
                </do_if>
                <set_value name="$mk42WaiterAge" exact="0s"/>
                <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42HomeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42HomeSector}.{$mk42wShip}?">
                  <set_value name="$mk42WaiterAge" exact="player.age - @global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42HomeSector}.{$mk42wShip}"/>
                </do_if>
                <set_value name="$mk42PromoteWaiter" exact="false"/>
                <do_if value="$mk42HomeOwnerStale or $mk42WaiterAge gt $mk42WaiterStaleThreshold">
                  <set_value name="$mk42PromoteWaiter" exact="true"/>
                </do_if>
                <do_if value="$mk42PromoteWaiter">
                  <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.{$mk42wi}"/>
                  <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome? and global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk42HomeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk42HomeSector}.{$mk42wShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterQueuedByHome.{$mk42HomeSector}.{$mk42wShip}"/>
                  </do_if>
                  <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42HomeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42HomeSector}.{$mk42wShip}?">
                    <remove_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterStartedAt.{$mk42HomeSector}.{$mk42wShip}"/>
                  </do_if>
                  <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk42wShip}" exact="true"/>
                  <signal_objects object="$mk42wShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                  <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-Scheduler] NotifyMK42LiveWaitersTick: Promoted starved MK42 waiter ' + $mk42wShip.idcode + ' home=' + (if $mk42HomeSector.knownname? then @$mk42HomeSector.knownname else '?') + ' waiterAge=' + $mk42WaiterAge + ' homeOwnerStale=' + $mk42HomeOwnerStale" chance="100"/>
                  </do_if>
                </do_if>
              </do_all>

              <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.count gt 0 and global.$GT_SearchSemaphore.$MK42LiveHomeActive? and global.$GT_SearchSemaphore.$MK42LiveHomeActive.{$mk42HomeSector}?">
                <set_value name="$hasAnyMK42ActiveWaiters" exact="true"/>
                <do_all exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.count" counter="$mk42wi">
                  <set_value name="$mk42wShip" exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$mk42HomeSector}.{$mk42wi}"/>
                  <do_if value="$mk42wShip? and $mk42wShip.exists">
                    <signal_objects object="$mk42wShip" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
                  </do_if>
                </do_all>
              </do_if>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="$hasAnyMK42ActiveWaiters">
          <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterTickScheduled" exact="true"/>
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.NotifyMK42LiveWaitersTick"/>
        </do_if>
        <do_else>
          <set_value name="global.$GT_SearchSemaphore.$MK42LiveWaiterTickScheduled" exact="false"/>
        </do_else>
        <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.DispatchMK42LiveSearchGo"/>
      </actions>
    </cue>
<cue name="HandleMK42CacheUpdated" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_MK42_Cache_Updated'"/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$homeSector" exact="@$data.$HomeSector"/>
        <set_value name="$updatedMaxDistance" exact="if $data? and $data.$MaxDistance? then @$data.$MaxDistance else 0"/>
        <do_if value="not global.$GT_SearchSemaphore?">
          <signal_cue_instantly cue="md.GT_TradeSearch_Scheduler_MK42.InitSearchSemaphore"/>
        </do_if>
        <do_if value="$homeSector? and $homeSector.exists and global.$GT_SearchSemaphore?">
          <set_value name="$mk42CacheEntryCount" exact="0"/>
          <do_if value="global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$homeSector}?">
            <set_value name="$mk42CacheEntryCount" exact="@global.$GT_TradeCacheMK42.{$homeSector}.count"/>
          </do_if>
          <do_if value="$mk42CacheEntryCount gt 0 and $data? and $data.$Written? and $data.$Written gt 0">
            <!-- Fresh cache writes supersede prior per-ship skip markers on all entries. -->
            <do_all exact="global.$GT_TradeCacheMK42.{$homeSector}.count" counter="$mk42clrCi">
              <set_value name="$mk42clrEntry" exact="global.$GT_TradeCacheMK42.{$homeSector}.{$mk42clrCi}"/>
              <do_if value="$mk42clrEntry? and $mk42clrEntry.$FailedShips? and $mk42clrEntry.$FailedShips.count gt 0">
                <set_value name="$mk42clrEntry.$FailedShips" exact="[]"/>
                <set_value name="global.$GT_TradeCacheMK42.{$homeSector}.{$mk42clrCi}" exact="$mk42clrEntry"/>
              </do_if>
            </do_all>
            <set_value name="$mk42WakeShips" exact="[]"/>
            <set_value name="$mk42WakeShipSeen" exact="table[]"/>
            <!-- MK42 live queue waiters -->
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveQueueByHome? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.count" counter="$mk42cwi">
                <set_value name="$mk42cwEntry" exact="@global.$GT_SearchSemaphore.$MK42LiveQueueByHome.{$homeSector}.{$mk42cwi}"/>
                <set_value name="$mk42cwShip" exact="if $mk42cwEntry? and $mk42cwEntry.$Ship? then @$mk42cwEntry.$Ship else null"/>
                <do_if value="$mk42cwShip? and $mk42cwShip.exists and not $mk42WakeShipSeen.{$mk42cwShip}?">
                  <append_to_list name="$mk42WakeShips" exact="$mk42cwShip"/>
                  <set_value name="$mk42WakeShipSeen.{$mk42cwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- Legacy live queue (mk42PolicyNeedsLiveSearch path) -->
            <do_if value="global.$GT_SearchSemaphore.$LiveQueueByHome? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}? and global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.count" counter="$lcwi">
                <set_value name="$lcwEntry" exact="@global.$GT_SearchSemaphore.$LiveQueueByHome.{$homeSector}.{$lcwi}"/>
                <set_value name="$lcwShip" exact="if $lcwEntry? and $lcwEntry.$Ship? then @$lcwEntry.$Ship else null"/>
                <do_if value="$lcwShip? and $lcwShip.exists and not $mk42WakeShipSeen.{$lcwShip}?">
                  <append_to_list name="$mk42WakeShips" exact="$lcwShip"/>
                  <set_value name="$mk42WakeShipSeen.{$lcwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- MK42 live refresh waiters (blocked on same-home active slot) -->
            <do_if value="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}? and global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}.count" counter="$mk42wwi">
                <set_value name="$mk42wwShip" exact="@global.$GT_SearchSemaphore.$MK42LiveWaitersByHome.{$homeSector}.{$mk42wwi}"/>
                <do_if value="$mk42wwShip? and $mk42wwShip.exists and not $mk42WakeShipSeen.{$mk42wwShip}?">
                  <append_to_list name="$mk42WakeShips" exact="$mk42wwShip"/>
                  <set_value name="$mk42WakeShipSeen.{$mk42wwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <!-- Cache-phase queue for same home -->
            <do_if value="global.$GT_SearchSemaphore.$CacheQueue? and global.$GT_SearchSemaphore.$CacheQueue.count gt 0">
              <do_all exact="global.$GT_SearchSemaphore.$CacheQueue.count" counter="$ccwi">
                <set_value name="$ccwEntry" exact="@global.$GT_SearchSemaphore.$CacheQueue.{$ccwi}"/>
                <set_value name="$ccwShip" exact="if $ccwEntry? and $ccwEntry.$Ship? then @$ccwEntry.$Ship else null"/>
                <set_value name="$ccwHome" exact="if $ccwEntry? and $ccwEntry.$HomeSector? then @$ccwEntry.$HomeSector else null"/>
                <do_if value="$ccwShip? and $ccwShip.exists and $ccwHome? and $ccwHome == $homeSector and not $mk42WakeShipSeen.{$ccwShip}?">
                  <append_to_list name="$mk42WakeShips" exact="$ccwShip"/>
                  <set_value name="$mk42WakeShipSeen.{$ccwShip}" exact="true"/>
                </do_if>
              </do_all>
            </do_if>
            <do_all exact="$mk42WakeShips.count" counter="$mk42wsi">
              <set_value name="$mk42wShip" exact="$mk42WakeShips.{$mk42wsi}"/>
              <do_if value="not global.$GT_SearchSemaphore.$LiveWaiterWakePending?">
                <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending" exact="table[]"/>
              </do_if>
              <set_value name="global.$GT_SearchSemaphore.$LiveWaiterWakePending.{$mk42wShip}" exact="true"/>
              <signal_objects object="player.galaxy" param="'GT_Search_Abort'" param2="table[$Ship = $mk42wShip]" delay="1ms"/>
              <signal_objects object="$mk42wShip" param="'GT_TradeSearch_Reset'" delay="2ms"/>
            </do_all>
            <do_if value="$mk42WakeShips.count gt 0 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Scheduler] HandleMK42CacheUpdated: Woke ' + $mk42WakeShips.count + ' waiting ships to retry cache home=' + (if $homeSector.knownname? then @$homeSector.knownname else '?') + ' pool=' + $mk42CacheEntryCount + ' maxDist=' + $updatedMaxDistance" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Save/load recovery: an AI <wait> does not re-issue its trade-search request after a
         game load (the pre-save GT_Search_Request was discarded when the scheduler queues were
         reset on load), so MK4-2 ships sit in 'wait for MD response' forever until the order is
         manually re-applied. Re-kick every in-service MK4-2 ship once on load with
         GT_TradeSearch_Reset: the order's wait interrupt sees it is no longer scheduled (queues
         were just reset) and resumes its main loop, sending a fresh GT_Search_Request.
         One-shot and event-driven (no polling). The delay lets InitMK42Semaphore and the main
         scheduler's load-time reservation clear (2s) settle first. Ships that are actively
         executing a trade are unaffected (GT_TradeSearch_Reset is only caught in the response wait). -->
    <cue name="MK42ReinitShipsOnLoad" instantiate="true" version="1">
      <conditions>
        <event_game_loaded/>
      </conditions>
      <delay exact="5s"/>
      <actions>
        <do_if value="global.$GT_Ships? and global.$GT_Ships.keys.count gt 0">
          <set_value name="$mk42LoadShipKeys" exact="global.$GT_Ships.keys.list"/>
          <set_value name="$mk42LoadKicked" exact="0"/>
          <do_all exact="$mk42LoadShipKeys.count" counter="$mk42lki">
            <set_value name="$mk42LoadShip" exact="$mk42LoadShipKeys.{$mk42lki}"/>
            <do_if value="$mk42LoadShip? and $mk42LoadShip.exists and $mk42LoadShip.isplayerowned and $mk42LoadShip.defaultorder?">
              <set_value name="$mk42LoadIsMk42" exact="false"/>
              <do_if value="@$mk42LoadShip.defaultorder.id == 'GalaxyTraderMK4Supply2'">
                <set_value name="$mk42LoadIsMk42" exact="true"/>
              </do_if>
              <do_elseif value="@$mk42LoadShip.defaultorder.id == 'Assist' and $mk42LoadShip.defaultorder.$baseorder? and @$mk42LoadShip.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply2'">
                <set_value name="$mk42LoadIsMk42" exact="true"/>
              </do_elseif>
              <do_if value="$mk42LoadIsMk42">
                <signal_objects object="$mk42LoadShip" param="'GT_TradeSearch_Reset'" delay="1ms"/>
                <set_value name="$mk42LoadKicked" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
          <do_if value="$mk42LoadKicked gt 0 and global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Debug? and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Scheduler] MK42ReinitShipsOnLoad: re-kicked ' + $mk42LoadKicked + ' MK4-2 ship(s) to resume trade search after game load'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_TradingAI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - CORE COORDINATOR
         Main orchestration and AI request handlers
         
         This module coordinates between:
         - gt_tradesearch_scheduler.xml (Search Semaphore / Queue)
         - AI lib.gt.* scripts (Pathfinding / Offers / Matching)
         - gt_trading_execution.xml (Trade Execution)
         - gt_trading_signals.xml (Signal Routing)
         ======================================== -->
    
    <!-- Trading AI System Initialization -->
    <cue name="SystemInitV3" instantiate="true" version="1" comment="Renamed: old non-instantiate SystemInit stuck as complete in saves">
      <conditions>
        <check_any>
          <event_game_loaded/>
          <event_player_created/>
        </check_any>
      </conditions>
      <actions>
        <debug_text text="'[GalaxyTrader MK3] Trading AI system initializing... (SystemInitV3)'" chance="100"/>
        
        <!-- Initialize trading data structures -->
        <set_value name="global.$GT_TradingData" exact="table[]"/>
        <set_value name="global.$GT_TradingData.$ActiveTrades" exact="table[]"/>
        <set_value name="global.$GT_TradingData.$RouteCache" exact="table[]"/>
        <set_value name="global.$GT_TradingData.$LastUpdate" exact="player.age"/>
        
        <!-- Trade cache is NOT pre-initialized - X4 locks empty table[] -->
        <!-- It will be created WITH data on first cache write in gt_trading_search.xml -->
        
        <!-- Search queue/batch queue migration complete; scheduler owns queueing -->
        
        <!-- Initialize delayed ships table for variable isolation -->
        <set_value name="global.$GT_DelayedShips" exact="table[]"/>
        
        <!-- Initialize trace ID counter for pipeline logging -->
        <set_value name="global.$GT_TraceIdCounter" exact="1"/>
        
        <!-- Initialize pipeline counters for observability -->
        <set_value name="global.$GT_PipelineCounters" exact="table[
          $Queued = 0,
          $Active = 0,
          $Completed = 0,
          $Failed = 0
        ]"/>

        <!-- Hub status table (per-ship request lifecycle) -->
        <run_actions ref="md.GT_Libraries_General.GT_RequestStatus_Init"/>
        
        <!-- Legacy SearchQueue/BatchProcessorQueue removed in AI migration -->
        
        <!-- Pathfinding queue - still used by gt_core_system and gt_libraries_pathfinding -->
        <do_if value="not global.$GT_PathfindingQueue?">
          <set_value name="global.$GT_PathfindingQueue" exact="table[]"/>
          <set_value name="global.$GT_PathfindingQueue.$Requests" exact="[]"/>
          <set_value name="global.$GT_PathfindingQueue.$ActiveInstances" exact="0"/>
          <set_value name="global.$GT_PathfindingQueue.$MaxConcurrent" exact="2"/>
          <set_value name="global.$GT_PathfindingQueue.$ActiveShips" exact="[]"/>
        </do_if>
        
        <!-- Initialize trade index for cross-cache invalidation (Phase 1) -->
        <run_actions ref="md.GLX_Lib_Reservations.GLX_InitializeTradeIndex"/>
        
        <!-- Initialize central scheduler (Phase 2) -->
        <do_if value="not global.$GT_Scheduler?">
          <set_value name="global.$GT_Scheduler" exact="table[
            $WorkQueue = [],
            $ActiveWork = table[],
            $Budgets = table[
              $CheapOpsPerTick = 10,
              $OfferOpsPerTick = 5,
              $MatchOpsPerTick = 1,
              $MaxActiveHomeSearches = 1
            ],
            $Counters = table[
              $Queued = 0,
              $Active = 0,
              $Completed = 0,
              $Failed = 0
            ],
            $Processing = false,
            $LastStatsLog = player.age
          ]"/>
        </do_if>
        <do_else>
          <!-- Ensure all required properties exist -->
          <do_if value="not global.$GT_Scheduler.$WorkQueue?">
            <set_value name="global.$GT_Scheduler.$WorkQueue" exact="[]"/>
          </do_if>
          <!-- CRITICAL: Ensure ActiveWork is a table (not a list) - defensive check for save game compatibility -->
          <!-- Tables have .keys property, lists don't - use this to detect if it's NOT a table -->
          <do_if value="not global.$GT_Scheduler.$ActiveWork?">
            <set_value name="global.$GT_Scheduler.$ActiveWork" exact="table[]"/>
          </do_if>
          <do_else>
            <!-- Check if it's NOT a table by testing .keys property - if .keys doesn't exist, it's a list -->
            <do_if value="not global.$GT_Scheduler.$ActiveWork.keys?">
              <!-- ActiveWork is a list (from old save) - reinitialize as table -->
              <debug_text text="'[GT-WARN] SystemInit: ActiveWork is a list (no .keys property), reinitializing as table[]'" chance="100"/>
              <set_value name="global.$GT_Scheduler.$ActiveWork" exact="table[]"/>
            </do_if>
          </do_else>
          <do_if value="not global.$GT_Scheduler.$Budgets?">
            <!-- Initialize with defaults, will be updated from global settings if available -->
            <set_value name="$defaultFallbackSearches" exact="1"/>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches?">
              <set_value name="$defaultFallbackSearches" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches"/>
            </do_if>
            <set_value name="global.$GT_Scheduler.$Budgets" exact="table[
              $CheapOpsPerTick = 10,
              $OfferOpsPerTick = 5,
              $MatchOpsPerTick = 1,
              $MaxActiveHomeSearches = 1,
              $MaxActiveFallbackSearches = $defaultFallbackSearches
            ]"/>
          </do_if>
          <do_else>
            <!-- Ensure MaxActiveFallbackSearches exists even if Budgets was initialized elsewhere -->
            <do_if value="not global.$GT_Scheduler.$Budgets.$MaxActiveFallbackSearches?">
              <set_value name="$defaultFallbackSearches" exact="1"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches?">
                <set_value name="$defaultFallbackSearches" exact="@global.$GT_GlobalSettings.$Performance.$MaxConcurrentFallbackSearches"/>
              </do_if>
              <set_value name="global.$GT_Scheduler.$Budgets.$MaxActiveFallbackSearches" exact="$defaultFallbackSearches"/>
            </do_if>
          </do_else>
          <do_if value="not global.$GT_Scheduler.$Counters?">
            <set_value name="global.$GT_Scheduler.$Counters" exact="table[
              $Queued = 0,
              $Active = 0,
              $Completed = 0,
              $Failed = 0
            ]"/>
          </do_if>
          <do_if value="not global.$GT_Scheduler.$Processing?">
            <set_value name="global.$GT_Scheduler.$Processing" exact="false"/>
          </do_if>
          <do_if value="not global.$GT_Scheduler.$LastStatsLog?">
            <set_value name="global.$GT_Scheduler.$LastStatsLog" exact="player.age"/>
          </do_if>
        </do_else>
        
        <!-- Initialize reservation system (Phase 3) -->
        <do_if value="not global.$GT_Reservations?">
          <set_value name="global.$GT_Reservations" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_ReservationStats?">
          <set_value name="global.$GT_ReservationStats" exact="table[
            $Active = 0,
            $Expired = 0,
            $Conflicts = 0,
            $Created = 0,
            $Cleared = 0
          ]"/>
        </do_if>
        
        <!-- Initialize cached active trader count (performance optimization) -->
        <!-- Prevents O(n) loops when assigning orders to many ships -->
        <do_if value="not global.$GT_ActiveTraderCount?">
          <set_value name="global.$GT_ActiveTraderCount" exact="0"/>
        </do_if>
        
        <!-- Initialize failed trades cleanup tracking (performance optimization) -->
        <!-- Tracks last cleanup time per ship to avoid cleaning on every search -->
        <do_if value="not global.$GT_FailedTradesLastCleanup?">
          <set_value name="global.$GT_FailedTradesLastCleanup" exact="table[]"/>
        </do_if>
        
        <!-- Initialize registration queue - ONE registration at a time to prevent stuttering -->
        <set_value name="global.$GT_RegistrationQueue" exact="table[]"/>
        <set_value name="global.$GT_RegistrationQueue.$Ships" exact="[]"/>
        <set_value name="global.$GT_RegistrationQueue.$Processing" exact="false"/>
        
        <!-- Removed unused TradeRequestQueue (cleanup): requests route through GT_Search_Request scheduler entrypoint -->
        
        <!-- Initialize maintenance queue - Limit concurrent maintenance operations to prevent CPU spikes -->
        <set_value name="global.$GT_MaintenanceQueue" exact="table[]"/>
        <set_value name="global.$GT_MaintenanceQueue.$Requests" exact="[]"/>
        <set_value name="global.$GT_MaintenanceQueue.$ActiveInstances" exact="0"/>
        <set_value name="global.$GT_MaintenanceQueue.$MaxConcurrent" exact="2"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Trading AI system initialized (Modular Architecture)'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- One-Time Wake-Up for Ships Stuck in Old Wait States -->
    <cue name="WakeUpShipsStuckInOldCode" instantiate="true" version="1">
      <conditions>
        <event_game_loaded/>
      </conditions>
      <delay exact="5s" comment="Wait for ships to register"/>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-WakeUp] ONE-TIME: Waking ships stuck in old wait states from previous save'" chance="100"/>
        </do_if>
        
        <do_if value="global.$GT_Ships?">
          <do_all exact="global.$GT_Ships.keys.count" counter="$idx">
            <set_value name="$ship" exact="global.$GT_Ships.keys.{$idx}"/>
            <do_if value="$ship.exists">
              <!-- <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-WakeUp] Sending GT_No_Trade_Found signal to ' + $ship.idcode + ' to wake from old wait state'" chance="100"/>
              </do_if> -->
              <!-- Signal the ship directly - it will trigger interrupt handlers in new wait states -->
              <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'busy'" delay="1ms" comment="Wake up ships stuck in old code"/>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </cue>
    
    <!-- ========================================
         AI SCRIPT SIGNAL HANDLERS
         These handle requests from aiscripts
         ======================================== -->
    
    <!-- AI Script Trade Request Handler -->
    <cue name="HandleAITradeRequest" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Legacy_Trade_Request'"/>
      </conditions>
      <actions>
        <!-- Legacy bridge: route old request signal into the single active scheduler pipeline. -->
        <set_value name="$requestData" exact="event.param2"/>
        <set_value name="$requestShip" exact="if $requestData? and $requestData.$Ship? then @$requestData.$Ship else null"/>
        <do_if value="$requestShip? and $requestShip.exists">
          <!-- Remember last requester for on-demand hub status dump -->
          <set_value name="global.$GT_LastTradeRequestShip" exact="$requestShip"/>
          <set_value name="global.$GT_LastTradeRequestTraceId" exact="if @$requestData.$TraceId != null then @$requestData.$TraceId else ''"/>
          <set_value name="global.$GT_LastTradeRequestTime" exact="player.age"/>
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="$requestData"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-MD] Ignoring GT_Legacy_Trade_Request without valid ship payload'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>

    <!-- Legacy ProcessTradeRequestQueue/ProcessDelayedTradeRequest remain for reference, but are not used by the active pipeline. -->
    
    <!-- AI Blacklist Validation Failure Handler -->
    <cue name="HandleAITradeFailure" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Trade_Failed'"/>
      </conditions>
      <actions>
        <set_value name="$failureData" exact="event.param2"/>
        <set_value name="$ship" exact="$failureData.$Ship"/>
        
        <!-- Read structured metadata (with legacy guard for backward compatibility) -->
        <!-- Extract properties with safe access, then check if they exist -->
        <set_value name="$reasonTypeValue" exact="@$failureData.$ReasonType"/>
        <set_value name="$pathBlockedValue" exact="@$failureData.$PathBlocked"/>
        <set_value name="$shouldTryNextValue" exact="@$failureData.$ShouldTryNext"/>
        <set_value name="$reasonType" exact="if $reasonTypeValue? then $reasonTypeValue else 'MARKET'"/>
        <set_value name="$pathBlocked" exact="if $pathBlockedValue? then $pathBlockedValue else false"/>
        <set_value name="$shouldTryNext" exact="if $shouldTryNextValue? then $shouldTryNextValue else false"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-MD]   RECEIVED GT_Trade_Failed from AI: ' + $ship.idcode + ' (Reason: ' + $failureData.$Reason + ', ReasonType: ' + $reasonType + ', PathBlocked: ' + $pathBlocked + ')'" chance="100"/>
        </do_if>
        
        <!-- Store failed trade to prevent re-selection (per-sector, not per-ship) -->
        <!-- Ensure table exists before accessing (handles race condition) -->
        <!-- Note: Actual storage happens later in the code where sector pair is extracted -->
        <do_if value="not global.$GT_FailedSectorPairs?">
          <set_value name="global.$GT_FailedSectorPairs" exact="table[]"/>
        </do_if>
        
        <!-- NEW: Record failed sector for future filtering -->
        <!-- AI now handles iteration through trade list internally, so no need to signal back -->
        <do_if value="$failureData.$Partner?">
          <!-- Extract sectors from failed partner -->
          <set_value name="$buySector" exact="null"/>
          <set_value name="$sellSector" exact="null"/>
          
          <!-- Determine which sector is the buy and which is sell based on IsBuying flag -->
          <do_if value="$failureData.$IsBuying">
            <set_value name="$buySector" exact="$failureData.$Partner.sector"/>
            <!-- Try to get sell sector from trades awaiting validation (get first trade as reference) -->
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{$ship}?">
              <set_value name="$tradeList" exact="global.$GT_TradesAwaitingValidation.{$ship}"/>
              <do_if value="typeof $tradeList == datatype.list and $tradeList.count gt 0">
                <set_value name="$firstTrade" exact="$tradeList.{1}"/>
                <do_if value="$firstTrade.$SellStation?">
                  <set_value name="$sellSector" exact="@$firstTrade.$SellStation.sector"/>
                </do_if>
                <do_else>
                  <set_value name="$sellSector" exact="@$firstTrade.$SellOffer.owner.sector"/>
                </do_else>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$sellSector" exact="$failureData.$Partner.sector"/>
            <!-- Try to get buy sector from trades awaiting validation -->
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{$ship}?">
              <set_value name="$tradeList" exact="global.$GT_TradesAwaitingValidation.{$ship}"/>
              <do_if value="typeof $tradeList == datatype.list and $tradeList.count gt 0">
                <set_value name="$firstTrade" exact="$tradeList.{1}"/>
                <do_if value="$firstTrade.$BuyStation?">
                  <set_value name="$buySector" exact="@$firstTrade.$BuyStation.sector"/>
                </do_if>
                <do_else>
                  <set_value name="$buySector" exact="@$firstTrade.$BuyOffer.owner.sector"/>
                </do_else>
              </do_if>
            </do_if>
          </do_else>
          
          <!-- Store SECTOR PAIR for future filtering (per-sector, not per-ship) -->
          <!-- Ships in the same sector share failed sector pairs (same connectivity/blacklist context) -->
          <set_value name="$currentSector" exact="$ship.sector"/>
          <do_if value="$buySector? and $sellSector? and $currentSector? and $currentSector.exists">
            <run_actions ref="md.GT_Libraries_General.GT_RecordFailedSectorPair" result="$failedBuySectorCount">
              <param name="currentSector" value="$currentSector"/>
              <param name="buySector" value="$buySector"/>
              <param name="sellSector" value="$sellSector"/>
              <param name="reason" value="$failureData.$Reason"/>
            </run_actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <set_value name="$currentSectorName" exact="@$currentSector.knownname"/>
              <set_value name="$buySectorName" exact="@$buySector.knownname"/>
              <set_value name="$sellSectorName" exact="@$sellSector.knownname"/>
              <debug_text text="'[GT-MD] Added failed sector pair to blacklist for sector ' + (if $currentSectorName? then $currentSectorName else 'Unknown') + ': ' + 
                (if $buySectorName? then $buySectorName else 'Unknown') + ' â†’ ' + (if $sellSectorName? then $sellSectorName else 'Unknown') +
                ' (Ship: ' + $ship.idcode + ', buy-keys=' + $failedBuySectorCount + ', will be filtered for all ships in this sector)'" 
                chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MD] WARNING: Could not store failed trade for ' + $ship.idcode + ' - sector data incomplete'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- SendTryNextTrade cue removed -->
    <!-- No longer needed - AI now iterates through trade list internally -->
    
    
    <!-- Delayed Trade Request Processing -->
    <cue name="ProcessDelayedTradeRequest" instantiate="true">
      <conditions>
        <event_cue_signalled/>
        <check_value value="event.param.$Ship.exists"/>
      </conditions>
      <delay exact="50ms" comment="Allow AI to enter wait state before processing"/>
      <actions>
        <set_value name="$requestData" exact="event.param"/>
        <set_value name="$ship" exact="$requestData.$Ship"/>
        <set_value name="$shouldProceed" exact="true"/>
        
        <!-- Legacy hard-bridge: retire this parallel path and use the active scheduler entrypoint. -->
        <do_if value="$ship? and $ship.exists">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-MD] ProcessDelayedTradeRequest redirected to GT_Search_Request for ' + $ship.idcode" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="$requestData"/>
          <set_value name="$shouldProceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>

        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GT-MD] Processing trade request for ' + $ship.idcode + ' at game time ' + player.age" chance="100"/>
        </do_if>
        
        <!-- Validate required parameters (MaxBuy/MaxSell) - fail loudly if missing -->
        <!-- These are REQUIRED - signal must always include them (no fallbacks to hide issues) -->
        <set_value name="$forceLiveSearch" exact="@$requestData.$ForceLiveSearch"/>
        <set_value name="$maxBuy" exact="@$requestData.$MaxBuy"/>
        <set_value name="$maxSell" exact="@$requestData.$MaxSell"/>
        <set_value name="$maxBuyValid" exact="false"/>
        <set_value name="$maxSellValid" exact="false"/>
        <do_if value="$maxBuy? and $maxBuy ge 0">
          <set_value name="$maxBuyValid" exact="true"/>
        </do_if>
        <do_if value="$maxSell? and $maxSell ge 0">
          <set_value name="$maxSellValid" exact="true"/>
        </do_if>
        
        <!-- Fail loudly if required parameters are missing (no silent fallbacks) -->
        <do_if value="not $maxBuyValid or not $maxSellValid">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-MD] ERROR: Legacy trade request signal missing required MaxBuy/MaxSell parameters for ship ' + $ship.idcode + ' (MaxBuy: ' + $maxBuy + ', MaxSell: ' + $maxSell + ')'" chance="100"/>
          </do_if>
          <!-- Cannot proceed without valid distance parameters. -->
          <set_value name="$shouldProceed" exact="false"/>
          <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'busy'" delay="1ms"/>
          <!-- cancel_cue does not stop the current actions block immediately; the rest of this cue is gated by $shouldProceed -->
          <cancel_cue cue="this"/>
        </do_if>
        
        <do_if value="$shouldProceed">
          <!-- Build parameters table for Request Registry -->
          <set_value name="$parametersTable" exact="table[
            $HomeBase = @$requestData.$HomeBase,
            $MaxBuy = $maxBuy,
            $MaxSell = $maxSell,
            $CargoTarget = @$requestData.$CargoTarget,
            $WareBasket = @$requestData.$WareBasket,
            $AllowIllegal = @$requestData.$AllowIllegal,
            $EnforceRouteIllegalLegality = if $requestData.$EnforceRouteIllegalLegality? then @$requestData.$EnforceRouteIllegalLegality else false,
            $FactionPriority = @$requestData.$FactionPriority,
            $IgnoreCarrierAux = @$requestData.$IgnoreCarrierAux,
            $IgnoreBuildStorage = @$requestData.$IgnoreBuildStorage,
            $IgnoreTradeRules = @$requestData.$IgnoreTradeRules,
            $IgnorePlayerPricing = if $requestData.$IgnorePlayerPricing? then @$requestData.$IgnorePlayerPricing else false,
            $IgnoreMK1Supply = @$requestData.$IgnoreMK1Supply,
            $DistancePenalty = @$requestData.$DistancePenalty,
            $FleetCoordination = @$requestData.$FleetCoordination,
            $RequestTime = player.age,
            $ForceLiveSearch = $forceLiveSearch
          ]"/>
        
        <!-- Acquire lock and store parameters using Request Registry -->
        <!-- Check if ship already has lock BEFORE calling library (to detect duplicates) -->
        <set_value name="$alreadyLocked" exact="false"/>
        <do_if value="global.$GT_SearchLocks? and global.$GT_SearchLocks.{$ship}?">
          <set_value name="$alreadyLocked" exact="true"/>
        </do_if>
        
        <do_if value="not $alreadyLocked">
          <!-- Ship not locked - acquire lock using Request Registry -->
          <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Acquire">
            <param name="ship" value="$ship"/>
            <param name="parameters" value="$parametersTable"/>
          </run_actions>
          
          <!-- Lock acquired successfully -->
          <set_value name="this.$lockedShip" exact="$ship"/>
          
          <!-- Generate trace ID for this request -->
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_GenerateTraceId" result="$traceId"/>
          <set_value name="$parametersTable.$TraceId" exact="$traceId"/>
          <set_value name="global.$GT_AIParameters.{$ship}.$TraceId" exact="$traceId"/>
          
          <!-- Update pipeline counter -->
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_UpdatePipelineCounter">
            <param name="counterName" value="'Queued'"/>
            <param name="delta" value="1"/>
          </run_actions>
          
          <!-- CRITICAL: Cannot combine @ and ? operators in X4 - extract values first -->
          <!-- Extract values BEFORE run_actions call so they're in scope for param tag -->
          <set_value name="$homeBaseName" exact="'Unknown'"/>
          <do_if value="$requestData.$HomeBase?">
            <set_value name="$homeBase" exact="$requestData.$HomeBase"/>
            <do_if value="$homeBase.sector?">
              <set_value name="$homeBaseName" exact="@$homeBase.sector.knownname"/>
            </do_if>
          </do_if>
          <set_value name="$maxBuyVal" exact="0"/>
          <do_if value="$requestData.$MaxBuy?">
            <set_value name="$maxBuyVal" exact="$requestData.$MaxBuy"/>
          </do_if>
          <set_value name="$maxSellVal" exact="0"/>
          <do_if value="$requestData.$MaxSell?">
            <set_value name="$maxSellVal" exact="$requestData.$MaxSell"/>
          </do_if>
          
          <!-- Log request entry with structured format -->
          <run_actions ref="md.GLX_Lib_TradingLog.GLX_LogTradeSearchStructured">
            <param name="traceId" value="$traceId"/>
            <param name="stage" value="'Request'"/>
            <param name="action" value="'Start'"/>
            <param name="fields" value="table[
              $ship = $ship.idcode,
              $home = $homeBaseName,
              $maxBuy = $maxBuyVal,
              $maxSell = $maxSellVal
            ]"/>
          </run_actions>
          
          <!-- Legacy debug log (keep for compatibility) -->
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <!-- Use safe access (@) for optional properties in debug text -->
            <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') AI trade request received for ' + $ship.knownname + ' (MaxBuy: ' + @$requestData.$MaxBuy + ', MaxSell: ' + @$requestData.$MaxSell + ', TraceId: ' + $traceId + ')'" chance="100"/>
          </do_if>
          
          <!-- Queue module removed; requests go directly to scheduler -->
          
          <!-- CRITICAL: Check if ship is busy BEFORE queueing -->
          <set_value name="$isBusy" exact="false"/>
          
          <!-- Check 1: Has trade orders in queue -->
          <do_if value="$ship.tradeorders? and $ship.tradeorders.count gt 0">
            <set_value name="$isBusy" exact="true"/>
            <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') Ship busy: has ' + $ship.tradeorders.count + ' trade orders - NOT queueing'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Check 2: Has training order -->
          <do_if value="not $isBusy and $ship.order? and $ship.order.id == 'DockAndTrain'">
            <set_value name="$isBusy" exact="true"/>
            <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') Ship busy: in training - NOT queueing'" chance="100"/>
            </do_if>
          </do_if>
          
          <do_if value="not $isBusy">
            <!-- Queue module removed: request search directly from new scheduler -->
            <!-- CRITICAL: Pass full params (HomeBase, MaxBuy, MaxSell, etc.) so scheduler can resolve home sector.
                 Previously we sent only $Ship, causing scheduler to derive from ship.defaultorder.$home which can be null in edge cases. -->
            <set_value name="$parametersTable.$Ship" exact="$ship"/>
            
            <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') Requesting search directly via GT_Search_Request'" chance="100"/>
            </do_if>
            
            <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="$parametersTable"/>

            <!-- TradeRequestQueue removed (cleanup): request is accepted and queued directly -->
          </do_if>
          <do_elseif value="$isBusy">
            <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') NOT QUEUED: Ship is busy'" chance="100"/>
            </do_if>
            
            <!-- Release lock and parameters using Request Registry -->
            <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'ship_busy'"/>
            </run_actions>
            
            <!-- Signal AI that ship is busy -->
            <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'busy'" delay="1ms"/>
            
            <!-- No TradeRequestQueue to update (cleanup) -->
          </do_elseif>
        </do_if>
        <do_else>
          <!-- Ship already locked - duplicate request -->
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') Trade search already in progress, ignoring duplicate request'" chance="100"/>
          </do_if>

          <!-- IMPORTANT: Under heavy fleet load, the MD search can complete AFTER the AI wait timeout.
               The AI then sends a new request, but if we silently ignore it, the AI will wait another full timeout and still miss results.
               Mitigation:
               - If the in-progress request is OLD (older than the AI timeout), treat it as stale and clear transient state so the ship can recover.
               - Otherwise, wake the AI with a NON-BACKOFF "still working" signal so it can continue waiting without escalating retry cooldown. -->

          <set_value name="$didClearStaleState" exact="false"/>
          <set_value name="$requestAge" exact="0s"/>
          <set_value name="$hasRequestTime" exact="false"/>
          <do_if value="global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$RequestTime?">
            <set_value name="$requestAge" exact="player.age - global.$GT_AIParameters.{$ship}.$RequestTime"/>
            <set_value name="$hasRequestTime" exact="true"/>
          </do_if>

          <!-- If we have a lock but no RequestTime, the request registry got corrupted (usually by deleting AIParameters under lock).
               Treat as stale and clear the transient state + lock so the ship can recover. -->
          <do_if value="not $hasRequestTime">
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MD] (' + $ship.idcode + ') STALE lock detected: SearchLock exists but AIParameters.$RequestTime is missing - clearing transient state to recover'" chance="100"/>
            </do_if>

            <!-- Clear transient per-ship search state so new requests can proceed -->
            <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{$ship}?">
              <remove_value name="global.$GT_SearchResult.{$ship}"/>
            </do_if>

            <!-- Release request registry lock + AI parameters (if any) -->
            <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'stale_lock_missing_requesttime'"/>
            </run_actions>

            <set_value name="$didClearStaleState" exact="true"/>
          </do_if>

          <!-- If this search has been in-progress longer than the AI timeout window, clear it as stale. -->
          <!-- Note: Use standalone do_if here (not do_elseif) because the previous branch is an independent check. -->
          <!-- IMPORTANT: Under heavy fleet load, a legitimate in-progress request can exceed the AI timeout because:
               - Live searches are rate-limited
               - Batch matching is serialized (often MaxConcurrent=1)
               Only clear as stale if we see NO evidence of ongoing work for this ship. -->
          <set_value name="$hasOngoingWork" exact="false"/>
          <!-- If the ship is currently active or queued in either scheduler pool, work is ongoing. -->
          <do_if value="global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$CacheActiveShips? and global.$GT_SearchSemaphore.$CacheActiveShips.{$ship}?">
            <set_value name="$hasOngoingWork" exact="true"/>
          </do_if>
          <do_if value="not $hasOngoingWork and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$CacheQueued? and global.$GT_SearchSemaphore.$CacheQueued.{$ship}?">
            <set_value name="$hasOngoingWork" exact="true"/>
          </do_if>
          <do_if value="not $hasOngoingWork and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveActiveShips? and global.$GT_SearchSemaphore.$LiveActiveShips.{$ship}?">
            <set_value name="$hasOngoingWork" exact="true"/>
          </do_if>
          <do_if value="not $hasOngoingWork and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$LiveQueued? and global.$GT_SearchSemaphore.$LiveQueued.{$ship}?">
            <set_value name="$hasOngoingWork" exact="true"/>
          </do_if>
          <do_if value="not $hasOngoingWork and global.$GT_SearchSemaphore? and global.$GT_SearchSemaphore.$PhaseStateByShip? and global.$GT_SearchSemaphore.$PhaseStateByShip.{$ship}?">
            <set_value name="$hasOngoingWork" exact="true"/>
          </do_if>
          <!-- Home-sector refresh waiter marker (hub pipeline):
               If the ship is waiting silently for a home-sector live refresh to finish, do not treat it as stale. -->
          <do_if value="not $hasOngoingWork and global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$WaitReason? and global.$GT_AIParameters.{$ship}.$WaitReason == 'home_refresh_wait'">
            <set_value name="$hasOngoingWork" exact="true"/>
          </do_if>

          <do_if value="$hasRequestTime and $requestAge gt 95s and not $hasOngoingWork">
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MD] (' + $ship.idcode + ') STALE in-progress trade search detected on duplicate request (age: ' + $requestAge + ') - clearing transient state to recover'" chance="100"/>
            </do_if>

            <!-- Clear transient per-ship search state so new requests can proceed -->
            <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{$ship}?">
              <remove_value name="global.$GT_SearchResult.{$ship}"/>
            </do_if>

            <!-- Release request registry lock + AI parameters -->
            <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'stale_inprogress_timeout'"/>
            </run_actions>

            <set_value name="$didClearStaleState" exact="true"/>
          </do_if>
          <do_elseif value="$hasRequestTime and $requestAge gt 95s and $hasOngoingWork">
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MD] (' + $ship.idcode + ') Duplicate request while search is still in progress (age: ' + $requestAge + ') - NOT clearing state (ongoing work detected)'" chance="100"/>
            </do_if>
          </do_elseif>

          <!-- HARD SELF-HEAL (TTL):
               Old savegames can contain stale locks + stale state markers that never progress (e.g., lock set by previous version, ship removed from GT).
               If the lock is older than SearchLockTTL, clear it EVEN if stale markers exist, to prevent permanent deadlock. -->
          <set_value name="$lockTtlSeconds" exact="600"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$SearchLockTTL?">
            <set_value name="$tmpTtl" exact="@global.$GT_GlobalSettings.$Performance.$SearchLockTTL"/>
            <do_if value="$tmpTtl? and $tmpTtl != null and $tmpTtl ge 60 and $tmpTtl le 7200">
              <set_value name="$lockTtlSeconds" exact="$tmpTtl"/>
            </do_if>
          </do_if>
          <set_value name="$lockAge" exact="0s"/>
          <do_if value="global.$GT_SearchLocks? and global.$GT_SearchLocks.{$ship}?">
            <set_value name="$lockAge" exact="player.age - global.$GT_SearchLocks.{$ship}"/>
          </do_if>

          <do_if value="not $didClearStaleState and $lockAge gt ($lockTtlSeconds * 1s)">
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-MD] (' + $ship.idcode + ') STALE lock TTL exceeded (age: ' + $lockAge + ', ttl: ' + ($lockTtlSeconds * 1s) + ') - clearing state to recover'" chance="100"/>
            </do_if>

            <!-- Clear transient per-ship search state so new requests can proceed -->
            <do_if value="global.$GT_SearchResult? and global.$GT_SearchResult.{$ship}?">
              <remove_value name="global.$GT_SearchResult.{$ship}"/>
            </do_if>

            <!-- Release request registry lock + AI parameters.
                 Use stale_lock_cleanup to trigger additional queue/state cleanup in GT_RequestRegistry_Release. -->
            <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'stale_lock_cleanup'"/>
            </run_actions>

            <set_value name="$didClearStaleState" exact="true"/>
          </do_if>

          <!-- Wake AI for ignored duplicate request:
               - If we cleared stale state, tell AI to retry immediately (no backoff).
               - Otherwise, tell AI the search is still running (continue waiting, no backoff). -->
          <do_if value="$didClearStaleState">
            <signal_objects object="$ship" param="'GT_TradeSearch_Reset'" delay="1ms"/>
          </do_if>
          <do_else>
            <signal_objects object="$ship" param="'GT_TradeSearch_InProgress'" delay="1ms"/>
          </do_else>
          
          <!-- No TradeRequestQueue to update (cleanup) -->
        </do_else>

        </do_if>
        
        <!-- FIX: Search lock is now ONLY released when:
             1. Request rejected (busy/duplicate) - released above
             2. Search completes - released by SearchTradeRoutes (gt_trading_search.xml:1584-1590)
             3. Search aborted - released by queue cleanup handlers
            DO NOT release here - lock must persist until search actually runs and completes -->
        <!-- NOTE: ActiveInstances counter is decremented above when request is rejected -->
        <!-- When request succeeds and ship is queued, counter is decremented by SearchTradeRoutes after search completes -->
      </actions>
    </cue>
    
    <!-- AI Script Sell Request Handler -->
    <cue name="HandleAISellRequest" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Find_Sell'" comment="Handle sell request from AI script"/>
      </conditions>
      <actions>
        <set_value name="$requestData" exact="event.param2"/>
        <set_value name="$ship" exact="$requestData.$Ship"/>
        
        <!-- CRITICAL: Verify ship actually has cargo before searching -->
        <!-- OPTIMIZATION: Compute cargo status once and reuse for debug -->
        <set_value name="$hasCargo" exact="false"/>
        <set_value name="$cargoCount" exact="0"/>
        <do_if value="$ship.cargo.list?">
          <set_value name="$cargoCount" exact="$ship.cargo.list.count"/>
          <do_if value="$cargoCount gt 0">
            <set_value name="$hasCargo" exact="true"/>
          </do_if>
        </do_if>
        <set_value name="$allowSellEnqueue" exact="$hasCargo"/>
        
        <!-- DEBUG: AI sell request received -->
        <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <set_value name="$maxSell" exact="15"/>
          <do_if value="$requestData.$MaxSell?">
            <set_value name="$maxSell" exact="$requestData.$MaxSell"/>
          </do_if>
          <debug_text text="'[GT-Disposal] (' + $ship.idcode + ') HandleAISellRequest: Ship=' + $ship.knownname + ', HasCargo=' + $hasCargo + ' (' + $cargoCount + ' types), MaxDistance=' + $maxSell + ' jumps'" chance="100"/>
        </do_if>
        
        <do_if value="not $hasCargo">
          <!-- Ship has no cargo - signal no trade found immediately -->
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Disposal] (' + $ship.idcode + ') WARNING: GT_Find_Sell received but ship has NO cargo - signaling GT_No_Trade_Found'" chance="100"/>
          </do_if>
          <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_cargo'" delay="1ms"/>
          <set_value name="$allowSellEnqueue" exact="false"/>
        </do_if>

        <!-- Busy gate: if ship is already executing trade orders, do not consume another live search slot. -->
        <do_if value="$allowSellEnqueue and $ship.tradeorders? and $ship.tradeorders.count gt 0">
          <set_value name="$allowSellEnqueue" exact="false"/>
          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Disposal] (' + $ship.idcode + ') Ship already has ' + $ship.tradeorders.count + ' trade orders - skipping sell-only enqueue'" chance="100"/>
          </do_if>
          <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'busy'" delay="1ms"/>
        </do_if>

        <do_if value="$allowSellEnqueue">
          <!-- Route cargo-disposal search through the unified scheduler/AI pipeline. -->
          <set_value name="$maxDistance" exact="15"/>
          <do_if value="$requestData.$MaxSell?">
            <set_value name="$maxDistance" exact="$requestData.$MaxSell"/>
          </do_if>
          <set_value name="$sellWareBasket" exact="$ship.cargo.list"/>

          <set_value name="global.$GT_AIParameters.{$ship}" exact="table[
            $HomeBase = @$requestData.$HomeBase,
            $MaxSell = $maxDistance,
            $DistancePenalty = @$requestData.$DistancePenalty,
            $IgnoreCarrierAux = @$requestData.$IgnoreCarrierAux,
            $IgnoreBuildStorage = @$requestData.$IgnoreBuildStorage,
            $IgnoreTradeRules = @$requestData.$IgnoreTradeRules,
            $IgnorePlayerPricing = if $requestData.$IgnorePlayerPricing? then @$requestData.$IgnorePlayerPricing else false,
            $IgnoreMK1Supply = @$requestData.$IgnoreMK1Supply,
            $RequestTime = player.age
          ]"/>

          <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Disposal] (' + $ship.idcode + ') Enqueueing sell-only request via GT_Search_Request: MaxDistance=' + $maxDistance + ', Wares=' + $sellWareBasket.count" chance="100"/>
          </do_if>
          <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[
            $Ship = $ship,
            $HomeBase = @$requestData.$HomeBase,
            $MaxSell = $maxDistance,
            $DistancePenalty = @$requestData.$DistancePenalty,
            $IgnoreCarrierAux = @$requestData.$IgnoreCarrierAux,
            $IgnoreBuildStorage = @$requestData.$IgnoreBuildStorage,
            $IgnoreTradeRules = @$requestData.$IgnoreTradeRules,
            $IgnorePlayerPricing = if $requestData.$IgnorePlayerPricing? then @$requestData.$IgnorePlayerPricing else false,
            $IgnoreMK1Supply = @$requestData.$IgnoreMK1Supply,
            $AllowIllegal = false,
            $EnforceRouteIllegalLegality = false,
            $SearchMode = 'sell_only',
            $WareBasket = $sellWareBasket
          ]"/>
        </do_if>
      </actions>
    </cue>

    <!-- AI Script Initialization Handler -->
    <cue name="HandleAIStarted" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_AI_Started'" comment="Handle AI script startup"/>
      </conditions>
      <actions>
        <set_value name="$initData" exact="event.param2"/>
        <set_value name="$ship" exact="$initData.$Ship"/>
        <set_value name="$gtRoutineLabel" exact="'MK3'"/>
        <do_if value="$initData.$Config? and $initData.$Config.$orderType?">
          <set_value name="$gtRoutineLabel" exact="$initData.$Config.$orderType"/>
        </do_if>
        <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK1'">
          <set_value name="$gtRoutineLabel" exact="'MK1'"/>
        </do_elseif>
        <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyTraderMK2'">
          <set_value name="$gtRoutineLabel" exact="'MK2'"/>
        </do_elseif>
        <do_elseif value="$ship.defaultorder? and @$ship.defaultorder.id == 'GalaxyMiner'">
          <set_value name="$gtRoutineLabel" exact="'Miner'"/>
        </do_elseif>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader ' + $gtRoutineLabel + '] AI script started for ship ' + $ship.knownname + ' - registering with MD system'" chance="100"/>
        </do_if>
        
        <!-- Register ship with GT system if not already registered -->
        <do_if value="not global.$GT_Ships.{$ship}?">
          <signal_objects object="player.galaxy" param="'GT_Register_Ship'" param2="table[
            $Ship = $ship,
            $Config = $initData.$Config
          ]"/>
        </do_if>
        
        <!-- PHASE 1: Initialize ship state in registry (state manager initialization only) -->
        <!-- This tests if state registry initialization interferes with trade order creation -->
        <do_if value="not global.$GT_Ship_State?">
          <set_value name="global.$GT_Ship_State" exact="table[]"/>
        </do_if>
        <do_if value="not global.$GT_Ship_State.{$ship}?">
          <!-- Check if ship has GT order -->
          <set_value name="$hasGTOrder" exact="false"/>
          <do_if value="$ship.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})">
            <set_value name="$hasGTOrder" exact="true"/>
          </do_if>
          
          <set_value name="global.$GT_Ship_State.{$ship}" exact="table[
            $OperationalState = 'idle',
            $SubordinateState = 'independent',
            $Commander = null,
            $CommanderHasGT = false,
            $HasGTOrder = $hasGTOrder,
            $ActiveTradeOrders = 0,
            $LastStateUpdate = player.age,
            $MacroShipName = @$ship.macro.name
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] Phase 1: Initialized state registry for ' + $ship.idcode + ' (macro name: ' + @$ship.macro.name + ', HasGTOrder: ' + $hasGTOrder + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- PHASE 7: Check if GT order was removed when script restarts -->
          <!-- Ship already in state registry - check if GT order was removed -->
          <!-- Note: X4 always assigns a default order - when GT order is removed, it becomes "Hold Position" -->
          <set_value name="$state" exact="global.$GT_Ship_State.{$ship}"/>
          <set_value name="$currentDefaultOrder" exact="@$ship.defaultorder.id"/>
          <set_value name="$hasGTOrder" exact="false"/>
          <do_if value="global.$GT_ProtectedOrderIDs? and $currentDefaultOrder? and global.$GT_ProtectedOrderIDs.indexof.{$currentDefaultOrder}">
            <set_value name="$hasGTOrder" exact="true"/>
          </do_if>
          
          <!-- If state says ship has GT order but ship doesn't, GT order was removed -->
          <!-- Ship now has "Hold Position" or another default order -->
          <do_if value="$state.$HasGTOrder and not $hasGTOrder">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - GT order removed (detected in HandleAIStarted, new default order: ' + (if $currentDefaultOrder then $currentDefaultOrder else 'NONE') + ')'" chance="100"/>
            </do_if>
            
            <!-- Update state to reflect GT order cancellation -->
            <set_value name="$state.$HasGTOrder" exact="false"/>
            <set_value name="$state.$OperationalState" exact="'orphaned'"/>
            <set_value name="$state.$ActiveTradeOrders" exact="0"/>
            
            <!-- Determine subordinate state -->
            <set_value name="$hasCommander" exact="false"/>
            <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
              <set_value name="$hasCommander" exact="true"/>
              <set_value name="$state.$Commander" exact="$ship.commander"/>
              
              <!-- Check if commander has GT order -->
              <set_value name="$commanderHasGT" exact="false"/>
              <do_if value="$ship.commander.defaultorder? and (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.commander.defaultorder.id})">
                <set_value name="$commanderHasGT" exact="true"/>
              </do_if>
              <set_value name="$state.$CommanderHasGT" exact="$commanderHasGT"/>
              
              <do_if value="$commanderHasGT">
                <set_value name="$state.$SubordinateState" exact="'subordinate'"/>
              </do_if>
              <do_else>
                <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
              </do_else>
            </do_if>
            <do_else>
              <set_value name="$state.$Commander" exact="null"/>
              <set_value name="$state.$CommanderHasGT" exact="false"/>
              <set_value name="$state.$SubordinateState" exact="'orphaned'"/>
            </do_else>
            
            <set_value name="$state.$LastStateUpdate" exact="player.age"/>
            
            <!-- NAME RESTORATION: Restore ship name if not GT-controlled (direct or subordinate) -->
            <run_actions ref="md.GT_Ship_State_Utilities.GT_RestoreShipName" result="$nameRestored">
              <param name="ship" value="$ship"/>
              <param name="reason" value="'GT order removed - restoring original name (HandleAIStarted)'"/>
              <param name="checkSubordinate" value="true"/>
              <param name="state" value="$state"/>
              <param name="checkDirectGTOrder" value="true"/>
            </run_actions>
            <do_if value="$nameRestored">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-State] Phase 7: Name restoration signal sent for ' + $ship.idcode + ' (HandleAIStarted)'" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          <!-- If ship has GT order but state says it doesn't, update state -->
          <do_elseif value="not $state.$HasGTOrder and $hasGTOrder">
            <set_value name="$state.$HasGTOrder" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-State] Phase 7: ' + $ship.idcode + ' - GT order detected (state was false, now true)'" chance="100"/>
            </do_if>
          </do_elseif>
        </do_else>
        
        <!-- Authoritative commander startup hook:
             when commander GT AI starts/restarts, directly schedule subordinate reactivation.
             This avoids depending on fragile order event timing. -->
        <do_if value="$hasGTOrder and (($ship.allsubordinates? and @$ship.allsubordinates.count gt 0) or ($ship.subordinates? and @$ship.subordinates.count gt 0))">
          <signal_cue_instantly cue="md.GT_CoreSystem.ProcessCommanderGTReactivation" param="table[
            $Commander = $ship,
            $Attempt = 1
          ]"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-State] HandleAIStarted: commander ' + $ship.idcode + ' has GT order and subordinates - scheduling subordinate reactivation'" chance="100"/>
          </do_if>
        </do_if>

      </actions>
    </cue>

    <!-- Configuration Change Handler -->
    <cue name="OnConfigurationChanged" instantiate="true">
      <conditions>
        <event_cue_signalled comment="Handle configuration changes from GT_Configuration"/>
      </conditions>
      <actions>
        <set_value name="$changeData" exact="event.param"/>
        
        <!-- DEBUG: Configuration change received -->
        <do_if value="@global.$GT_Config.$Debug.$Enabled and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Configuration changed: ' + $changeData.$section + '.' + $changeData.$key + ' = ' + $changeData.$value" chance="100"/>
        </do_if>
        
        <!-- Configuration changes are automatically picked up from global.$GT_Config -->
        <!-- No action needed - modules read from global state -->
      </actions>
    </cue>

    <!-- Ship Trading Order Handler (Legacy - for internal order processing) -->
    <cue name="ShipTradingOrder" instantiate="true">
      <conditions>
        <event_object_order_ready object="player.entity" comment="Detect when ship is ready for new order"/>
      </conditions>
      <actions>
        <set_value name="$ship" exact="event.object"/>
        
        <!-- DEBUG: Ship order ready -->
        <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') Ship order ready: ' + $ship.knownname" chance="100"/>
        </do_if>
        
        <!-- Validate ship is registered and ready for trading -->
        <do_if value="global.$GT_Ships.{$ship}? and $ship.isplayerowned and $ship.primarypurpose == purpose.trade">
          <!-- Check if PILOT XP is blocked -->
          <set_value name="$isBlocked" exact="false"/>
          <do_if value="$ship.pilot and global.$GT_Pilots.{$ship.pilot}? and global.$GT_Pilots.{$ship.pilot}.$XPBlocked?">
            <set_value name="$isBlocked" exact="true"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] ' + $ship.knownname + ' pilot ' + $ship.pilot.name + ' is blocked for training'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Add to trading queue if not blocked -->
          <do_if value="not $isBlocked">
            <!-- Queue module removed: request search directly from new scheduler -->
            <do_if value="global.$GT_Config.$Debug.$Enabled and global.$GT_Config.$Debug.$TradeSearch and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3 DEBUG] (' + $ship.idcode + ') InternalQueueShip: requesting search via GT_Search_Request'" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[$Ship = $ship]"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
  </cues>
</mdscript>
ï»¿<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Trading_Execution" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - TRADE EXECUTION
         Handles trade order creation and completion tracking
         ======================================== -->
    
    <!-- Execute Trade -->
    <cue name="ExecuteTrade" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param"/>
        <set_value name="$ship" exact="$params.$Ship"/>
        <set_value name="$trade" exact="@$params.$Trade"/>  <!-- Use @ operator - Trade may not exist -->
        <set_value name="$tradeList" exact="@$params.$TradeList"/> <!-- Trade list for fallback -->
        <set_value name="$legacyBridged" exact="false"/>

        <!-- Legacy decommission bridge:
             Keep stale callers functional, but force all execution onto the active GT_Trade_Found / GT_No_Trade_Found flow. -->
        <do_if value="$tradeList == null">
          <set_value name="$tradeList" exact="[]"/>
        </do_if>
        <do_if value="$trade != null and $tradeList.count == 0">
          <append_to_list name="$tradeList" exact="$trade"/>
        </do_if>
        <do_if value="$ship? and $ship.exists">
          <do_if value="$tradeList.count gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Execution] ExecuteTrade bridged to GT_Trade_Found for ' + $ship.idcode + ' (trades=' + $tradeList.count + ')'" chance="100"/>
            </do_if>
            <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
              $TradeList = $tradeList,
              $SearchMethod = 'legacy_execute_trade_bridge',
              $SignalDelayMs = 0,
              $Timestamp = player.age
            ]" delay="1ms"/>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Execution] ExecuteTrade bridged to GT_No_Trade_Found for ' + $ship.idcode + ' (empty payload)'" chance="100"/>
            </do_if>
            <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'legacy_execute_trade_no_payload'" delay="1ms"/>
          </do_else>
        </do_if>
        <set_value name="$legacyBridged" exact="true"/>
        <cancel_cue cue="this"/>


      </actions>
    </cue>
    
    <!-- PHASE 4.2: TradeCompleted event monitoring REMOVED
         
         The old TradeCompleted cue (140+ lines) has been completely removed and replaced with
         the new diff patch signal system in gt_trading_signals.xml. The new system:
         
         Benefits:
         - Uses order.trade.perform.xml diff patch to inject signals directly from X4 native code
         - Provides richer trade data (actual transferred amounts, quality, exact failure reasons)
         - Eliminates complex buyer/seller matching logic
         - No longer needs ActiveTrades buy/sell phase tracking
         - More reliable and event-driven
         
         What was removed:
         - event_player_trade_completed monitoring (slow, requires matching)
         - Manual buy/sell phase tracking with global.$GT_TradingData.$ActiveTrades
         - Complex buyer/seller identification logic
         - Stale entry cleanup code
         
         The new system handles all of this automatically via diff patch signals.
    -->
    
    <!-- Delayed Signal Cue - Ensures AI wait block is active before sending signal -->
    <cue name="SignalTradeFound" instantiate="true">
      <conditions>
        <event_cue_signalled/>
        <check_value value="event.param.$Ship.exists"/>
      </conditions>
      <actions>
        <!-- V2: enqueue signal to avoid same-frame bursts -->
        <set_value name="$ship" exact="event.param.$Ship"/>
        <do_if value="not global.$GT_TS_OutputQueue?">
          <set_value name="global.$GT_TS_OutputQueue" exact="table[
            $TradeFoundQueue = [],
            $TradeFoundQueued = table[],
            $TradeFoundProcessing = false
          ]"/>
        </do_if>
        <do_if value="not global.$GT_TS_OutputQueue.$TradeFoundQueue?">
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundQueue" exact="[]"/>
        </do_if>
        <do_if value="not global.$GT_TS_OutputQueue.$TradeFoundQueued?">
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundQueued" exact="table[]"/>
        </do_if>

        <!-- Robustness: if a ship's queued marker gets stuck (e.g. crash/reload or unexpected early exit),
             it can prevent GT_Trade_Found from ever being sent again for that ship (stall).
             Use a timestamp marker and allow re-enqueue if it's stale. -->
        <set_value name="$queuedAt" exact="@global.$GT_TS_OutputQueue.$TradeFoundQueued.{$ship}"/>
        <do_if value="$queuedAt? and $queuedAt != null and (player.age - $queuedAt) gt 30s">
          <remove_value name="global.$GT_TS_OutputQueue.$TradeFoundQueued.{$ship}"/>
        </do_if>

        <do_if value="not global.$GT_TS_OutputQueue.$TradeFoundQueued.{$ship}?">
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundQueued.{$ship}" exact="player.age"/>
          <!-- Use configurable signal delay (default: 10ms) -->
          <set_value name="$signalDelay" exact="@global.$GT_GlobalSettings.$Performance.$TradeFoundSignalDelay * 1ms"/>
          <do_if value="$signalDelay lt 10ms">
            <set_value name="$signalDelay" exact="10ms"/>
          </do_if>
          <append_to_list name="global.$GT_TS_OutputQueue.$TradeFoundQueue" exact="table[
            $Ship = $ship,
            $ReadyAt = player.age + $signalDelay
          ]"/>
        </do_if>
        <signal_cue_instantly cue="md.GT_Trading_Execution.ProcessTradeFoundSignalQueue"/>
      </actions>
    </cue>

    <!-- Process TradeFound signal queue (one per tick; respects per-entry ReadyAt). -->
    <cue name="ProcessTradeFoundSignalQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- P6 fix: Restructured to avoid cancel_cue fallthrough.
             Uses nested positive-flow checks; single cancel_cue at the very end (fallthrough-safe). -->
        <set_value name="$proceed" exact="false"/>
        <set_value name="this.$TradeFoundPhase2Proceed" exact="false"/>
        <set_value name="this.$DelayTime" exact="0ms"/>
        
        <do_if value="global.$GT_TS_OutputQueue? and global.$GT_TS_OutputQueue.$TradeFoundQueue?">
          <!-- SAFEGUARD: Reset processing flag if stuck (prevents infinite stall after crash/reload) -->
          <do_if value="global.$GT_TS_OutputQueue.$TradeFoundProcessing and global.$GT_TS_OutputQueue.$TradeFoundQueue.count le 0">
            <set_value name="global.$GT_TS_OutputQueue.$TradeFoundProcessing" exact="false"/>
          </do_if>
          
          <do_if value="not global.$GT_TS_OutputQueue.$TradeFoundProcessing">
            <set_value name="global.$GT_TS_OutputQueue.$TradeFoundProcessing" exact="true"/>
            
            <do_if value="global.$GT_TS_OutputQueue.$TradeFoundQueue.count gt 0">
              <set_value name="$entry" exact="global.$GT_TS_OutputQueue.$TradeFoundQueue.{1}"/>
              <set_value name="$ship" exact="@$entry.$Ship"/>
              <set_value name="$readyAt" exact="@$entry.$ReadyAt"/>
              <do_if value="$readyAt? and $readyAt != null and player.age lt $readyAt">
                <set_value name="this.$DelayTime" exact="$readyAt - player.age"/>
              </do_if>
              <set_value name="$proceed" exact="true"/>
              <set_value name="this.$TradeFoundPhase2Proceed" exact="true"/>
            </do_if>
            
            <do_if value="not $proceed">
              <!-- Queue was empty after acquiring lock Ã¢â‚¬â€ release it -->
              <set_value name="global.$GT_TS_OutputQueue.$TradeFoundProcessing" exact="false"/>
            </do_if>
          </do_if>
        </do_if>
        
        <!-- Single cancel_cue as LAST statement Ã¢â‚¬â€ fallthrough is harmless (nothing after it) -->
        <do_if value="not $proceed">
          <set_value name="this.$TradeFoundPhase2Proceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>
      </actions>
      <delay exact="this.$DelayTime"/>
      <actions>
        <set_value name="$phase2Proceed" exact="this.$TradeFoundPhase2Proceed and global.$GT_TS_OutputQueue? and global.$GT_TS_OutputQueue.$TradeFoundQueue? and global.$GT_TS_OutputQueue.$TradeFoundQueue.count gt 0"/>
        <do_if value="not $phase2Proceed">
          <do_if value="global.$GT_TS_OutputQueue? and global.$GT_TS_OutputQueue.$TradeFoundProcessing?">
            <set_value name="global.$GT_TS_OutputQueue.$TradeFoundProcessing" exact="false"/>
          </do_if>
          <cancel_cue cue="this"/>
        </do_if>

        <!-- Pop after waiting -->
        <do_if value="$phase2Proceed">
          <set_value name="$entry" exact="global.$GT_TS_OutputQueue.$TradeFoundQueue.{1}"/>
          <remove_from_list name="global.$GT_TS_OutputQueue.$TradeFoundQueue" exact="$entry"/>
          <set_value name="$ship" exact="@$entry.$Ship"/>
          <do_if value="$ship?">
            <remove_value name="global.$GT_TS_OutputQueue.$TradeFoundQueued.{$ship}"/>
          </do_if>

          <do_if value="$ship? and $ship.exists">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-Execution] SENDING GT_Trade_Found (queued) to ' + $ship.idcode + ' at ' + player.age" chance="100"/>
            </do_if>
          
            <!-- Read trade data from global storage (stored by ExecuteTrade cue) -->
            <set_value name="$tradeList" exact="[]"/>
            <set_value name="$searchMethod" exact="''"/>
            <do_if value="global.$GT_TradesAwaitingValidation? and global.$GT_TradesAwaitingValidation.{$ship}?">
              <set_value name="$tradeList" exact="global.$GT_TradesAwaitingValidation.{$ship}"/>
            </do_if>
            <do_if value="global.$GT_TradesAwaitingValidationSearchMethod? and global.$GT_TradesAwaitingValidationSearchMethod.{$ship}?">
              <set_value name="$searchMethod" exact="@global.$GT_TradesAwaitingValidationSearchMethod.{$ship}"/>
            </do_if>
          
            <run_actions ref="md.GT_Libraries_General.GT_RequestStatus_Update">
              <param name="ship" value="$ship"/>
              <param name="stage" value="'result'"/>
              <param name="state" value="'trade_found'"/>
              <param name="reason" value="''"/>
              <param name="traceId" value="if global.$GT_AIParameters? and global.$GT_AIParameters.{$ship}? and global.$GT_AIParameters.{$ship}.$TraceId? then global.$GT_AIParameters.{$ship}.$TraceId else ''"/>
              <param name="extra" value="table[$PendingTrades = (if $tradeList != null then $tradeList.count else 0)]"/>
            </run_actions>
            <!-- Pass trade data directly in signal param2 (like GT_Training_Station_Found) -->
            <signal_objects object="$ship" param="'GT_Trade_Found'" param2="table[
              $TradeList = $tradeList,
              $SearchMethod = $searchMethod
            ]" delay="1ms"/>
          </do_if>

          <!-- Yield between signals to smooth FPS (hardcoded for now) -->
          <set_value name="global.$GT_TS_OutputQueue.$TradeFoundProcessing" exact="false"/>
          <do_if value="global.$GT_TS_OutputQueue.$TradeFoundQueue.count gt 0">
            <signal_cue_instantly cue="md.GT_Trading_Execution.ProcessTradeFoundSignalQueue"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- ========================================= -->
    <!-- CACHE MAINTENANCE SIGNAL HANDLERS        -->
    <!-- AI scripts signal these during validation -->
    <!-- to keep the trade cache clean.           -->
    <!-- ========================================= -->
    
    <!-- Scenario 1 & 2: Purge invalid/consumed cache entries.
         Triggered by AI script when:
         - Offers are genuinely dead (Scenario 1: not available, owner destroyed)
         - Trade was consumed / order created from cache (Scenario 2)
         Only purges from the ship's HOME SECTOR cache (not all sectors).
         Reason: scanning all sectors (each with 1000+ entries) caused severe frame drops.
         Stale copies in other sectors will expire via TTL or write-time cleanup. -->
    <cue name="CachePurgeHandler" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Cache_Purge'"/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <set_value name="$p" exact="event.param2"/>
        <set_value name="$buyOffer" exact="@$p.$BuyOffer"/>
        <set_value name="$sellOffer" exact="@$p.$SellOffer"/>
        <set_value name="$homeSector" exact="@$p.$HomeSector"/>
        <set_value name="$ship" exact="@$p.$Ship"/>
        <set_value name="$reason" exact="@$p.$Reason"/>
        <set_value name="$cachePool" exact="'mk3'"/>
        <do_if value="$p.$CachePool? and $p.$CachePool == 'mk4'">
          <set_value name="$cachePool" exact="'mk4'"/>
        </do_if>
        <do_elseif value="$p.$CachePool? and $p.$CachePool == 'mk42'">
          <set_value name="$cachePool" exact="'mk42'"/>
        </do_elseif>
        <set_value name="$isMk4Pool" exact="$cachePool == 'mk4'"/>
        <set_value name="$isMk42Pool" exact="$cachePool == 'mk42'"/>
        
        <!-- Must have at least a sell offer and a home sector to match -->
        <set_value name="$canPurge" exact="$sellOffer != null and $homeSector != null"/>
        <do_if value="$canPurge">
          <do_if value="$isMk4Pool">
            <set_value name="$canPurge" exact="global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}?"/>
          </do_if>
          <do_elseif value="$isMk42Pool">
            <set_value name="$canPurge" exact="global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$homeSector}?"/>
          </do_elseif>
          <do_else>
            <set_value name="$canPurge" exact="global.$GT_TradeCache? and global.$GT_TradeCache.{$homeSector}?"/>
          </do_else>
        </do_if>
        
        <do_if value="$canPurge">
          <set_value name="$totalPurged" exact="0"/>
          <set_value name="$sectorCache" exact="[]"/>
          <do_if value="$isMk4Pool">
            <set_value name="$sectorCache" exact="global.$GT_TradeCacheMK4.{$homeSector}"/>
          </do_if>
          <do_elseif value="$isMk42Pool">
            <set_value name="$sectorCache" exact="global.$GT_TradeCacheMK42.{$homeSector}"/>
          </do_elseif>
          <do_else>
            <set_value name="$sectorCache" exact="global.$GT_TradeCache.{$homeSector}"/>
          </do_else>
          
          <do_all exact="$sectorCache.count" counter="$pi" reverse="true">
            <set_value name="$entry" exact="$sectorCache.{$pi}"/>
            <do_if value="$entry != null and $entry.$SellOffer? and $entry.$SellOffer == $sellOffer">
              <!-- Match sell offer; also check buy offer if provided -->
              <set_value name="$matchBuy" exact="$buyOffer == null or (not $entry.$BuyOffer?) or ($entry.$BuyOffer? and $entry.$BuyOffer == $buyOffer)"/>
              <do_if value="$matchBuy">
                <do_if value="$isMk4Pool">
                  <remove_value name="global.$GT_TradeCacheMK4.{$homeSector}.{$pi}"/>
                </do_if>
                <do_elseif value="$isMk42Pool">
                  <remove_value name="global.$GT_TradeCacheMK42.{$homeSector}.{$pi}"/>
                </do_elseif>
                <do_else>
                  <remove_value name="global.$GT_TradeCache.{$homeSector}.{$pi}"/>
                </do_else>
                <set_value name="$totalPurged" operation="add"/>
              </do_if>
            </do_if>
          </do_all>
          
          <!-- Clean up empty cache list -->
          <do_if value="$isMk4Pool">
            <do_if value="global.$GT_TradeCacheMK4.{$homeSector}? and global.$GT_TradeCacheMK4.{$homeSector}.count == 0">
              <remove_value name="global.$GT_TradeCacheMK4.{$homeSector}"/>
            </do_if>
          </do_if>
          <do_elseif value="$isMk42Pool">
            <do_if value="global.$GT_TradeCacheMK42.{$homeSector}? and global.$GT_TradeCacheMK42.{$homeSector}.count == 0">
              <remove_value name="global.$GT_TradeCacheMK42.{$homeSector}"/>
            </do_if>
          </do_elseif>
          <do_else>
            <do_if value="global.$GT_TradeCache.{$homeSector}? and global.$GT_TradeCache.{$homeSector}.count == 0">
              <remove_value name="global.$GT_TradeCache.{$homeSector}"/>
            </do_if>
          </do_else>
          
          <do_if value="$totalPurged gt 0 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-CacheMaint] Purged ' + $totalPurged + ' ' + $cachePool + ' cache entr' + (if $totalPurged == 1 then 'y' else 'ies') + ' from ' + $homeSector.knownname + ' (reason=' + $reason + ', ship=' + (if $ship != null then $ship.idcode else 'N/A') + ')'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Scenario 3: Flag ship-specific failure on cache entry.
         Triggered by AI script when:
         - Docking denied (ship-specific permissions)
         - Path blocked (ship-specific blacklist group)
         - Cannot carry ware (ship-specific cargo bay)
         - Blacklisted station/sector (ship-specific blacklist)
         - Distance exceeded (ship-specific max distance)
         Adds the ship to $FailedShips and increments $FailCount on the
         matching cache entry so other ships can still use it. -->
    <cue name="CacheFlagShipHandler" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Cache_Flag_Ship'"/>
      </conditions>
      <delay exact="1ms"/>
      <actions>
        <set_value name="$p" exact="event.param2"/>
        <set_value name="$ship" exact="@$p.$Ship"/>
        <set_value name="$buyOffer" exact="@$p.$BuyOffer"/>
        <set_value name="$sellOffer" exact="@$p.$SellOffer"/>
        <set_value name="$homeSector" exact="@$p.$HomeSector"/>
        <set_value name="$reason" exact="@$p.$Reason"/>
        <set_value name="$cachePool" exact="'mk3'"/>
        <do_if value="$p.$CachePool? and $p.$CachePool == 'mk4'">
          <set_value name="$cachePool" exact="'mk4'"/>
        </do_if>
        <do_elseif value="$p.$CachePool? and $p.$CachePool == 'mk42'">
          <set_value name="$cachePool" exact="'mk42'"/>
        </do_elseif>
        <set_value name="$isMk4Pool" exact="$cachePool == 'mk4'"/>
        <set_value name="$isMk42Pool" exact="$cachePool == 'mk42'"/>
        
        <!-- Validate required params â€” guard flag instead of nested return -->
        <set_value name="$canFlag" exact="$ship != null and $sellOffer != null and $homeSector != null"/>
        <do_if value="$canFlag">
          <do_if value="$isMk4Pool">
            <set_value name="$canFlag" exact="global.$GT_TradeCacheMK4? and global.$GT_TradeCacheMK4.{$homeSector}?"/>
          </do_if>
          <do_elseif value="$isMk42Pool">
            <set_value name="$canFlag" exact="global.$GT_TradeCacheMK42? and global.$GT_TradeCacheMK42.{$homeSector}?"/>
          </do_elseif>
          <do_else>
            <set_value name="$canFlag" exact="global.$GT_TradeCache? and global.$GT_TradeCache.{$homeSector}?"/>
          </do_else>
        </do_if>
        
        <do_if value="$canFlag">
          <set_value name="$sectorCache" exact="[]"/>
          <do_if value="$isMk4Pool">
            <set_value name="$sectorCache" exact="global.$GT_TradeCacheMK4.{$homeSector}"/>
          </do_if>
          <do_elseif value="$isMk42Pool">
            <set_value name="$sectorCache" exact="global.$GT_TradeCacheMK42.{$homeSector}"/>
          </do_elseif>
          <do_else>
            <set_value name="$sectorCache" exact="global.$GT_TradeCache.{$homeSector}"/>
          </do_else>
          <do_all exact="$sectorCache.count" counter="$fi" reverse="true">
            <set_value name="$entry" exact="$sectorCache.{$fi}"/>
            <do_if value="$entry != null and $entry.$SellOffer? and $entry.$SellOffer == $sellOffer">
              <!-- Match sell offer; also check buy offer if provided -->
              <set_value name="$matchBuy" exact="$buyOffer == null or (not $entry.$BuyOffer?) or ($entry.$BuyOffer? and $entry.$BuyOffer == $buyOffer)"/>
              <do_if value="$matchBuy">
                <!-- Check if ship is already in FailedShips -->
                <set_value name="$alreadyFailed" exact="false"/>
                <set_value name="$failedShips" exact="@$entry.$FailedShips"/>
                <do_if value="$failedShips == null">
                  <set_value name="$failedShips" exact="[]"/>
                </do_if>
                <do_all exact="$failedShips.count" counter="$fsi">
                  <do_if value="$failedShips.{$fsi} == $ship">
                    <set_value name="$alreadyFailed" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
                
                <do_if value="not $alreadyFailed">
                  <append_to_list name="$failedShips" exact="$ship"/>
                  <set_value name="$entry.$FailedShips" exact="$failedShips"/>
                  <set_value name="$failCount" exact="@$entry.$FailCount"/>
                  <do_if value="$failCount == null">
                    <set_value name="$failCount" exact="0"/>
                  </do_if>
                  <set_value name="$entry.$FailCount" exact="$failCount + 1"/>
                  <do_if value="$isMk4Pool">
                    <set_value name="global.$GT_TradeCacheMK4.{$homeSector}.{$fi}" exact="$entry"/>
                  </do_if>
                  <do_elseif value="$isMk42Pool">
                    <set_value name="global.$GT_TradeCacheMK42.{$homeSector}.{$fi}" exact="$entry"/>
                  </do_elseif>
                  <do_else>
                    <set_value name="global.$GT_TradeCache.{$homeSector}.{$fi}" exact="$entry"/>
                  </do_else>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-CacheMaint] Flagged ' + $cachePool + ' cache entry for ' + $ship.idcode + ' (reason=' + $reason + ', FailCount=' + ($failCount + 1) + ', home=' + $homeSector.knownname + ')'" chance="100"/>
                  </do_if>
                </do_if>
                <break/>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </cue>
    
    <!-- ========================================= -->
    <!-- MAINTENANCE TASKS -->
    <!-- Consolidated from: gt_trading_maintenance.xml -->
    <!-- ========================================= -->
    
    <!-- Event-driven Route Cache Cleanup: schedule on trade success/failure -->
    <cue name="RouteCacheCleanup_ScheduleSuccess" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_DirectTrade'"/>
        <check_value value="global.$GT_TradingData?"/>
      </conditions>
      <actions>
        <signal_cue cue="RouteCacheCleanup_Run"/>
      </actions>
    </cue>
    
    <cue name="RouteCacheCleanup_ScheduleFailure" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeFailure'"/>
        <check_value value="global.$GT_TradingData?"/>
      </conditions>
      <actions>
        <signal_cue cue="RouteCacheCleanup_Run"/>
      </actions>
    </cue>
    
    <cue name="RouteCacheCleanup_Run" instantiate="true">
      <conditions>
        <event_cue_signalled/>
        <check_value value="global.$GT_TradingData?"/>
      </conditions>
      <delay exact="120s" comment="Debounce cleanup - batch multiple events"/>
      <actions>
        <!-- Clear outdated route cache entries -->
        <set_value name="$cacheAge" exact="player.age - global.$GT_TradingData.$LastUpdate"/>
        
        <do_if value="$cacheAge gt 600s">
          <set_value name="global.$GT_TradingData.$RouteCache" exact="table[]"/>
          <set_value name="global.$GT_TradingData.$LastUpdate" exact="player.age"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Route cache cleared (event-driven)'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Clean trade cache (MK3 + MK4 pools) -->
        <set_value name="$cacheMaxAge" exact="300s"/>
        <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Fleet? and global.$GT_GlobalSettings.$Fleet.$CacheTTL?">
          <set_value name="$cacheMaxAge" exact="@global.$GT_GlobalSettings.$Fleet.$CacheTTL"/>
        </do_if>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CachePool_EventCleanup" result="$mk3CleanedEntries">
          <param name="cachePool" value="'mk3'"/>
          <param name="cacheMaxAge" value="$cacheMaxAge"/>
        </run_actions>
        <run_actions ref="md.GLX_Lib_Cache.GLX_CachePool_EventCleanup" result="$mk4CleanedEntries">
          <param name="cachePool" value="'mk4'"/>
          <param name="cacheMaxAge" value="$cacheMaxAge"/>
        </run_actions>
        <set_value name="$cleanedEntries" exact="$mk3CleanedEntries + $mk4CleanedEntries"/>
        <do_if value="$cleanedEntries gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Trade cache cleanup: removed ' + $cleanedEntries + ' old/invalid entries (mk3=' + $mk3CleanedEntries + ', mk4=' + $mk4CleanedEntries + ', event-driven)'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Clean up stale trade reservations (older than 5 minutes) -->
        <do_if value="global.$GT_ActiveTradeReservations?">
          <set_value name="$shipsToRemove" exact="[]"/>
          <do_all exact="global.$GT_ActiveTradeReservations.keys.count" counter="$i">
            <set_value name="$ship" exact="global.$GT_ActiveTradeReservations.keys.{$i}"/>
            <set_value name="$reservation" exact="global.$GT_ActiveTradeReservations.{$ship}"/>
            <set_value name="$age" exact="player.age - $reservation.$Timestamp"/>
            <do_if value="$age gt 300s or not $ship.exists">
              <append_to_list name="$shipsToRemove" exact="$ship"/>
            </do_if>
          </do_all>
          <do_all exact="$shipsToRemove.count" counter="$i">
            <remove_value name="global.$GT_ActiveTradeReservations.{$shipsToRemove.{$i}}"/>
          </do_all>
          <do_if value="$shipsToRemove.count gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-FLEET] Cleaned up ' + $shipsToRemove.count + ' stale trade reservations (event-driven)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Event-driven Ship Recovery: on state updates -->
    <cue name="ShipRecovery_OnStateUpdate" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Ship_State_Update'"/>
        <check_value value="global.$GT_Ships?"/>
      </conditions>
      <actions>
        <set_value name="$params" exact="event.param2"/>
        <set_value name="$ship" exact="@$params.$Ship"/>
        <do_if value="@$ship.exists and @$ship.isoperational">
          <set_value name="$idleTime" exact="0s"/>
          <do_if value="global.$GT_Ships.{$ship}.$LastUpdate?">
            <set_value name="$idleTime" exact="player.age - global.$GT_Ships.{$ship}.$LastUpdate"/>
          </do_if>
          <do_if value="$idleTime gt 300s and not $ship.order">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Recovering idle ship (event): ' + $ship.knownname" chance="100"/>
            </do_if>
            <signal_objects object="player.galaxy" param="'GT_Search_Request'" param2="table[$Ship = $ship]"/>
            <set_value name="global.$GT_Ships.{$ship}.$LastUpdate" exact="player.age"/>
          </do_if>
        </do_if>
        
        <!-- Clean up stale search locks opportunistically -->
        <do_if value="global.$GT_SearchLocks?">
          <set_value name="$staleLocks" exact="0"/>
          <set_value name="$lockKeys" exact="global.$GT_SearchLocks.keys.list"/>
          <set_value name="$lockTtlSeconds" exact="600"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Performance? and global.$GT_GlobalSettings.$Performance.$SearchLockTTL?">
            <set_value name="$tmpTtl" exact="@global.$GT_GlobalSettings.$Performance.$SearchLockTTL"/>
            <do_if value="$tmpTtl? and $tmpTtl != null and $tmpTtl ge 60 and $tmpTtl le 7200">
              <set_value name="$lockTtlSeconds" exact="$tmpTtl"/>
            </do_if>
          </do_if>
          <do_all exact="$lockKeys.count" counter="$i">
            <set_value name="$ship" exact="$lockKeys.{$i}"/>
            <set_value name="$lockTime" exact="global.$GT_SearchLocks.{$ship}"/>
            <do_if value="$lockTime? and $lockTime != null and (player.age - $lockTime) gt ($lockTtlSeconds * 1s)">
              <run_actions ref="md.GT_Libraries_General.GT_RequestRegistry_Release">
                <param name="ship" value="$ship"/>
                <param name="reason" value="'stale_lock_cleanup'"/>
              </run_actions>
              <set_value name="$staleLocks" operation="add"/>
            </do_if>
          </do_all>
          <do_if value="$staleLocks gt 0">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Cleaned up ' + $staleLocks + ' stale search locks (event)'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
  </cues>
</mdscript>

<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_Trading_Signals" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ========================================
         GALAXY TRADER MK3 - TRADE SIGNAL HANDLER
         Centralized listener for diff patch trade signals
         Replaces complex event_player_trade_completed monitoring
         ======================================== -->
    
    <!-- Trade Success Handler -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessTradeSuccess" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_DirectTrade'"/>
      </conditions>
      <actions>
        <!-- V2: process the queue incrementally to avoid same-frame bursts on mass trades -->
        <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeSuccessQueue"/>
      </actions>
    </cue>

    <cue name="ProcessTradeSuccessQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="10ms"/>
      <actions>
        <!-- IMPORTANT: cancel_cue does NOT stop this actions block. Use explicit gating. -->
        <set_value name="$hasWork" exact="false"/>
        <do_if value="global.$GT_DirectTradeQueue? and global.$GT_DirectTradeQueue.count gt 0">
          <set_value name="$hasWork" exact="true"/>
        </do_if>
        <do_if value="not $hasWork">
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
          <set_value name="$data" exact="global.$GT_DirectTradeQueue.{1}"/>
          <remove_from_list name="global.$GT_DirectTradeQueue" exact="$data"/>

          <!-- Defensive: if queue element is missing/null, stop safely (prevents cascading null errors). -->
          <do_if value="$data == null">
            <do_if value="global.$GT_DirectTradeQueue? and global.$GT_DirectTradeQueue.count gt 0">
              <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeSuccessQueue"/>
            </do_if>
            <cancel_cue cue="this"/>
          </do_if>
          <do_else>
            <set_value name="$ship" exact="$data.$Ship"/>
            <set_value name="$skipSuccessProcessing" exact="false"/>
            
            <!-- Skip if ship is missing/destroyed before processing -->
            <do_if value="not $ship? or not $ship.exists">
              <set_value name="$skipSuccessProcessing" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] Skipping trade success for destroyed/missing ship'" chance="10"/>
              </do_if>
              <do_if value="global.$GT_DirectTradeQueue? and global.$GT_DirectTradeQueue.count gt 0">
                <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeSuccessQueue"/>
              </do_if>
              <cancel_cue cue="this"/>
            </do_if>
            
            <!-- Skip if ship no longer registered, unless it still has an active GT order (registry race recovery). -->
            <do_if value="not $skipSuccessProcessing and not global.$GT_Ships.{$ship}?">
              <set_value name="$activeGTOrder" exact="false"/>
              <do_if value="$ship.defaultorder? and ((@$ship.defaultorder.id == 'GalaxyTraderMK4Supply' or @$ship.defaultorder.id == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.id})) or (@$ship.defaultorder.id == 'Assist' and $ship.defaultorder.$baseorder? and (@$ship.defaultorder.$baseorder.id == 'GalaxyTraderMK4Supply' or @$ship.defaultorder.$baseorder.id == 'GalaxyTraderMK3' or (global.$GT_ProtectedOrderIDs? and global.$GT_ProtectedOrderIDs.indexof.{@$ship.defaultorder.$baseorder.id}))) )">
                <set_value name="$activeGTOrder" exact="true"/>
              </do_if>
              
              <do_if value="not $activeGTOrder">
                <set_value name="$skipSuccessProcessing" exact="true"/>
                <!-- Edge case: Ship removed from GT while old trade executing -->
                <!-- Reduced logging chance since this is expected behavior -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Signals] âš  Skipping trade success for unregistered ship: ' + $ship.idcode + 
                    '\n  Reason: Ship was removed from GalaxyTrader while old TradePerform order was still executing' +
                    '\n  This is expected behavior when removing ships from GT - vanilla orders continue briefly'"
                    chance="10"/>
                </do_if>
                <do_if value="global.$GT_DirectTradeQueue? and global.$GT_DirectTradeQueue.count gt 0">
                  <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeSuccessQueue"/>
                </do_if>
                <cancel_cue cue="this"/>
              </do_if>
              <do_else>
                <signal_objects object="player.galaxy" param="'GT_Register_Ship'" param2="table[
                  $Ship = $ship,
                  $Config = table[]
                ]"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Signals] Recovery: kept trade success for active GT ship with missing registry, re-registering ' + $ship.idcode" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            
            <do_if value="not $skipSuccessProcessing">
              <!-- 1. XP System -->
              <signal_cue_instantly cue="md.GT_XP_Training.ProcessSingleXPEvent" param="$data"/>
            
            <!-- 2. Trade Logging -->
            <signal_cue_instantly cue="md.GT_TradeLogging.LogCompletedTrade" param="$data"/>
            
            <!-- 2.5. Update Ship Statistics (Total Profit and Trades Completed) -->
            <do_if value="$ship? and $ship.exists and md.GT_Fleet_Coordination.UpdateShipStats?">
              <run_actions ref="md.GT_Fleet_Coordination.UpdateShipStats">
                <param name="ship" value="$ship"/>
                <param name="profit" value="$data.$tradeValue"/>
                <param name="tradesCompleted" value="1"/>
              </run_actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] Updated ship statistics for ' + $ship.idcode + ': +' + ($data.$tradeValue / 100) + ' Cr'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- 3. Fleet Coordination: Release trade reservation -->
            <do_if value="global.$GT_ActiveTradeReservations.{$ship}?">
              <remove_value name="global.$GT_ActiveTradeReservations.{$ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Fleet] Trade reservation released for ' + $ship.idcode" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- 4. Clear failed sector pairs for ship's current sector (trade succeeded, route is available) -->
            <!-- Clear per-sector so all ships in the sector benefit from successful route -->
            <set_value name="$currentSector" exact="$ship.sector"/>
            <do_if value="$currentSector? and $currentSector.exists and global.$GT_FailedSectorPairs? and global.$GT_FailedSectorPairs.{$currentSector}?">
              <!-- Savegame compatibility: sector entry can be table (new) or list (legacy). -->
              <set_value name="$failedPairsEntry" exact="global.$GT_FailedSectorPairs.{$currentSector}"/>
              <set_value name="$failedPairsCount" exact="0"/>
              <do_if value="$failedPairsEntry? and typeof $failedPairsEntry == datatype.table">
                <set_value name="$failedPairsCount" exact="$failedPairsEntry.keys.count"/>
              </do_if>
              <do_elseif value="$failedPairsEntry? and typeof $failedPairsEntry == datatype.list">
                <set_value name="$failedPairsCount" exact="$failedPairsEntry.count"/>
              </do_elseif>
              <remove_value name="global.$GT_FailedSectorPairs.{$currentSector}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$sectorName" exact="@$currentSector.knownname"/>
                <debug_text text="'[GT-Signals] Cleared ' + $failedPairsCount + ' failed sector pairs for sector ' + (if $sectorName? then $sectorName else 'Unknown') + ' (Ship: ' + $ship.idcode + ', trade succeeded - route available)'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- 4.5. Clear pending trade entry (no longer needed) -->
            <!-- Use library function to clear pending trade data -->
            <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
              <param name="ship" value="$ship"/>
            </run_actions>
            <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
              <param name="ship" value="$ship"/>
            </run_actions>
            
            <!-- Clear sell-only cargo disposal rotation state when trade completes -->
            <!-- Check if ship has no cargo left (cargo emptied by sell) -->
            <set_value name="$hasCargo" exact="false"/>
            <do_if value="$ship.cargo.list? and $ship.cargo.list.count gt 0">
              <set_value name="$hasCargo" exact="true"/>
            </do_if>
            <do_if value="not $hasCargo and global.$GT_ForcedSellLastWare? and global.$GT_ForcedSellLastWare.{$ship}?">
              <remove_value name="global.$GT_ForcedSellLastWare.{$ship}"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Disposal] (' + $ship.idcode + ') Cleared rotation state (cargo emptied by sell)'" chance="100"/>
              </do_if>
            </do_if>
            <do_if value="not $hasCargo and global.$GT_Ships? and global.$GT_Ships.{$ship}? and global.$GT_Ships.{$ship}.$CargoDisposal?">
              <remove_value name="global.$GT_Ships.{$ship}.$CargoDisposal"/>
              <do_if value="$ship.pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$ship.pilot}?">
                <signal_objects object="player.galaxy" param="'GT_Update_Ship_Name'" param2="table[
                  $Ship = $ship,
                  $pilot = $ship.pilot,
                  $xp = global.$GT_Pilots.{$ship.pilot}.$XP,
                  $level = global.$GT_Pilots.{$ship.pilot}.$Level,
                  $rank = @global.$GT_Pilots.{$ship.pilot}.$CurrentRank,
                  $nameType = 'trader'
                ]"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Disposal] (' + $ship.idcode + ') Cleared CargoDisposal flag after successful cargo clearance'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- 5. AI Script Notification (equipment check moved to pre-trade in AI script) -->
            <do_if value="$ship? and $ship.exists">
              <signal_objects object="$ship" param="'GT_Trade_Completed'" delay="1ms"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-AI] Trade completed signal sent to ' + $ship.idcode" chance="100"/>
            </do_if>
            
            <!-- Event-driven simple periodic report: check interval after trade completes (requires ProfitReports enabled) -->
            <do_if value="global.$GT_Config? and global.$GT_Config.$Notifications? and global.$GT_Config.$Notifications.$ProfitReports">
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$Notifications? and global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency?">
                <set_value name="$simpleReportFrequencyMinutes" exact="global.$GT_GlobalSettings.$Notifications.$SimpleReportFrequency"/>
                <do_if value="$simpleReportFrequencyMinutes gt 0">
                <do_if value="not global.$GT_Reports?">
                  <set_value name="global.$GT_Reports" exact="table[]"/>
                </do_if>
                <set_value name="$lastSimpleReport" exact="0"/>
                <do_if value="global.$GT_Reports.$LastSimpleReport?">
                  <set_value name="$lastSimpleReport" exact="global.$GT_Reports.$LastSimpleReport"/>
                </do_if>
                <set_value name="$timeSinceSimpleReport" exact="player.age - $lastSimpleReport"/>
                <set_value name="$simpleReportIntervalSeconds" exact="$simpleReportFrequencyMinutes * 60"/>
                <do_if value="$timeSinceSimpleReport ge $simpleReportIntervalSeconds">
                  <signal_cue cue="md.GT_Reporting.GeneratePeriodicReport"/>
                  <set_value name="global.$GT_Reports.$LastSimpleReport" exact="player.age"/>
                </do_if>
                </do_if>
              </do_if>
            </do_if>
        <!-- Continue if more items exist -->
              <do_if value="global.$GT_DirectTradeQueue? and global.$GT_DirectTradeQueue.count gt 0">
                <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeSuccessQueue"/>
              </do_if>
            </do_if>
          </do_else>
        </do_else>
      </actions>
    </cue>
    
    <!-- Trade Failure Handler -->
    <!-- Listen for signal instead of polling -->
    <cue name="ProcessTradeFailure" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_TradeFailure'"/>
      </conditions>
      <actions>
        <!-- V2: process the queue incrementally to avoid same-frame bursts -->
        <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeFailureQueue"/>
      </actions>
    </cue>

    <cue name="ProcessTradeFailureQueue" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <delay exact="10ms"/>
      <actions>
        <set_value name="$shouldProceed" exact="true"/>
        <do_if value="not global.$GT_TradeFailureQueue? or global.$GT_TradeFailureQueue.count le 0">
          <set_value name="$shouldProceed" exact="false"/>
          <cancel_cue cue="this"/>
        </do_if>
        <do_if value="$shouldProceed">
          <!-- SAFE ACCESS: Use @ operator and validate before use -->
          <set_value name="$data" exact="@global.$GT_TradeFailureQueue.{1}"/>
          <set_value name="$terminated" exact="false"/>
        
        <!-- VALIDATION: Check if data is valid before processing -->
        <!-- Pre-compute validity flag: cannot combine @ with ? in a single expression -->
        <set_value name="$dataValid" exact="false"/>
        <do_if value="$data?">
          <do_if value="$data.$Ship? and $data.$Ship != null">
            <set_value name="$dataValid" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="not $dataValid">
          <!-- Invalid entry: remove it if possible and continue to next -->
          <do_if value="$data?">
            <!-- Entry exists but is invalid - remove it -->
            <remove_from_list name="global.$GT_TradeFailureQueue" exact="$data"/>
          </do_if>
          <do_else>
            <!-- Entry was null - another instance already removed it, just cancel this instance -->
            <!-- The next signal will handle remaining items -->
          </do_else>
          
          <!-- Continue processing remaining items -->
          <do_if value="global.$GT_TradeFailureQueue? and global.$GT_TradeFailureQueue.count gt 0">
            <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeFailureQueue"/>
          </do_if>
          <set_value name="$terminated" exact="true"/>
          <cancel_cue cue="this"/>
        </do_if>
        <do_if value="not $terminated">
        <!-- Remove from queue AFTER validation -->
        <set_value name="$skipFailureProcessing" exact="not $dataValid"/>
        <set_value name="$ship" exact="null"/>
        <do_if value="$dataValid">
          <remove_from_list name="global.$GT_TradeFailureQueue" exact="$data"/>
          <set_value name="$ship" exact="@$data.$Ship"/>
        </do_if>

            <!-- Guard: ship was destroyed between queuing and processing (e.g. blown up, sold).
                 @$data.$Ship resolves to null when the component no longer exists. -->
            <do_if value="not $skipFailureProcessing and not $ship.exists">
              <set_value name="$skipFailureProcessing" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] Skipping trade failure for destroyed ship (component no longer exists). Reason: ' + @$data.$reason" chance="100"/>
              </do_if>
              <do_if value="global.$GT_TradeFailureQueue? and global.$GT_TradeFailureQueue.count gt 0">
                <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeFailureQueue"/>
              </do_if>
              <set_value name="$terminated" exact="true"/>
              <cancel_cue cue="this"/>
            </do_if>

            <!-- Skip if ship no longer registered (removed from GT while old trade executing) -->
            <do_if value="not $skipFailureProcessing and not global.$GT_Ships.{$ship}?">
              <set_value name="$skipFailureProcessing" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] âš  Skipping trade failure for unregistered ship: ' + $ship.idcode + 
                  '\n  Reason: Ship was removed from GalaxyTrader while old TradePerform order was still executing' +
                  '\n  Failure type: ' + @$data.$reason +
                  '\n  This is expected behavior when removing ships from GT - vanilla orders continue briefly'"
                  chance="100"/>
              </do_if>
              <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeFailureQueue"/>
              <set_value name="$terminated" exact="true"/>
              <cancel_cue cue="this"/>
            </do_if>
            <do_if value="not $skipFailureProcessing">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] Trade failed: ' + $ship.idcode + ' - ' + @$data.$reason" chance="100"/>
              </do_if>
              
              <!-- 1. Log failure -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Failure] ' + $ship.idcode + ' trade failed: ' + @$data.$reason + ' (' + @$data.$failureText + ')'" chance="100"/>
              </do_if>
              
              <!-- 2. Release fleet reservation if exists -->
              <do_if value="global.$GT_ActiveTradeReservations.{$ship}?">
                <remove_value name="global.$GT_ActiveTradeReservations.{$ship}"/>
              </do_if>
            
            <!-- 3. Categorize failure type and build structured payload -->
            <!-- Determine failure category and build structured payload for unified signal -->
            <set_value name="$failureCategory" exact="'MARKET'"/> <!-- Default: market failure -->
            <set_value name="$shouldTryNext" exact="false"/>
            <set_value name="$pathBlocked" exact="false"/>
            
            <!-- Check if this is a pathing failure -->
            <set_value name="$pathingFailureReasons" exact="[
              'ERR_NO_PATH_TO_DESTINATION',
              'ERR_DESTINATION_BLACKLISTED', 
              'ERR_SECTOR_BLACKLISTED',
              'TRADEPARTNER_BLACKLISTED',
              'ERR_CANNOT_DOCK',
              'ROUTE_PATH_CHANGED'
            ]"/>
            
            <set_value name="$isPathingFailure" exact="false"/>
            <do_all exact="$pathingFailureReasons.count" counter="$i">
              <do_if value="$pathingFailureReasons.{$i} == @$data.$reason">
                <set_value name="$isPathingFailure" exact="true"/>
                <set_value name="$failureCategory" exact="'PATHING'"/>
                <set_value name="$shouldTryNext" exact="true"/>
                <set_value name="$pathBlocked" exact="true"/>
                <break/>
              </do_if>
            </do_all>
            
            <!-- Handle pathing failures: track failed routes -->
            <do_if value="$isPathingFailure">
              <!-- PATHFINDING/BLACKLIST FAILURE: Trade route not accessible -->
              <!-- This means the trade is theoretically good, but ship can't reach it -->
              <!-- Solution: Try NEXT BEST TRADE from cache (skip this failed one) -->
              
              <!-- Track this failed trade so cache search skips it (per-sector, not per-ship) -->
              <!-- Initialization guarantees global.$GT_FailedSectorPairs exists -->
              <!-- Note: Actual storage happens later in the code where sector pair is extracted -->
              
              <!-- Get complete trade route from ACTIVE trade tracking (stored by AI at order creation time) -->
              <!-- Only proceed if we have complete active trade data - NO FALLBACK -->
              <do_if value="global.$GT_ActiveTrade? and global.$GT_ActiveTrade.{$ship}? and 
                            global.$GT_ActiveTrade.{$ship}.$BuyStation? and 
                            global.$GT_ActiveTrade.{$ship}.$SellStation? and 
                            global.$GT_ActiveTrade.{$ship}.$Ware?">
                <!-- Use complete route from active trade -->
                <set_value name="$buyStation" exact="global.$GT_ActiveTrade.{$ship}.$BuyStation"/>
                <set_value name="$sellStation" exact="global.$GT_ActiveTrade.{$ship}.$SellStation"/>
                <set_value name="$ware" exact="global.$GT_ActiveTrade.{$ship}.$Ware"/>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Failure] RETRIEVED complete trade from pending:' +
                    '\n  Buy: ' + @$buyStation.knownname +
                    '\n  Sell: ' + @$sellStation.knownname +
                    '\n  Ware: ' + @$ware.name"
                    chance="100"/>
                </do_if>
                
                <!-- Clean up pending trade data + active trade tracking -->
                <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
                  <param name="ship" value="$ship"/>
                </run_actions>
                
                <!-- Extract sectors - only store sector PAIR (not individual stations) -->
                <set_value name="$buySector" exact="@$buyStation.sector"/>
                <set_value name="$sellSector" exact="@$sellStation.sector"/>
                <set_value name="$currentSector" exact="$ship.sector"/>
                
                <!-- Create failed trade record with complete sector information -->
                <!-- Store per-sector (not per-ship) so ships in same sector share knowledge -->
                <!-- Store as nested table for O(1) lookup: FailedSectorPairs.{currentSector}.{buySector}.{sellSector} -->
                <do_if value="$currentSector? and $currentSector.exists">
                  <run_actions ref="md.GT_Libraries_General.GT_RecordFailedSectorPair" result="$failedBuySectorCount">
                    <param name="currentSector" value="$currentSector"/>
                    <param name="buySector" value="$buySector"/>
                    <param name="sellSector" value="$sellSector"/>
                    <param name="reason" value="@$data.$reason"/>
                  </run_actions>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <set_value name="$currentSectorName" exact="@$currentSector.knownname"/>
                    <set_value name="$buySectorName" exact="@$buySector.knownname"/>
                    <set_value name="$sellSectorName" exact="@$sellSector.knownname"/>
                    <debug_text text="'[GT-Failure] BLOCKED sector pair for sector ' + (if $currentSectorName? then $currentSectorName else 'Unknown') + ':' +
                      '\n  Ship: ' + $ship.idcode +
                      '\n  Route: ' + (if $buySectorName? then $buySectorName else 'Unknown') + ' â†’ ' + (if $sellSectorName? then $sellSectorName else 'Unknown') +
                      '\n  Reason: ' + @$data.$reason +
                      '\n  Total blocked buy-sectors for this sector: ' + $failedBuySectorCount +
                      '\n  âš  ALL ships in this sector will skip this sector pair'"
                      chance="100"/>
                  </do_if>
                </do_if>
              </do_if>
              <do_else>
                <!-- NO PENDING TRADE DATA: Cannot track failure -->
                <!-- This indicates a serious issue: pending trade was cleared before failure occurred -->
                <!-- OR pending trade was never created in the first place -->
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-Failure] CRITICAL: Cannot track failed trade for ' + $ship.idcode +
                    '\n  Pending trade entry MISSING - this should never happen!' +
                    '\n  Failure reason: ' + @$data.$reason +
                    '\n  Failure partner: ' + @$data.$partner.knownname +
                    '\n  âš  Ship will continue without blacklisting this route'" chance="100"/>
                </do_if>
              </do_else>
              
              <set_value name="$currentSector" exact="$ship.sector"/>
              <do_if value="$currentSector? and $currentSector.exists and global.$GT_FailedSectorPairs? and global.$GT_FailedSectorPairs.{$currentSector}?">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$sectorName" exact="@$currentSector.knownname"/>
                  <set_value name="$failedBuySectorCountDbg" exact="0"/>
                  <set_value name="$fspSectorDbg" exact="global.$GT_FailedSectorPairs.{$currentSector}"/>
                  <do_if value="$fspSectorDbg? and typeof $fspSectorDbg == datatype.table">
                    <set_value name="$failedBuySectorCountDbg" exact="$fspSectorDbg.keys.count"/>
                  </do_if>
                  <do_elseif value="$fspSectorDbg? and typeof $fspSectorDbg == datatype.list">
                    <set_value name="$failedBuySectorCountDbg" exact="$fspSectorDbg.count"/>
                  </do_elseif>
                  <debug_text text="'[GT-Failure]   PATHFINDING FAILURE: ' + $ship.idcode + ' | Sector: ' + (if $sectorName? then $sectorName else 'Unknown') + ' | Failed sector pairs tracked: ' + $failedBuySectorCountDbg" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
            <do_else>
              <!-- MARKET FAILURE: Market conditions changed (destroyed, no stock, etc.) -->
              <!-- Solution: Start NEW SEARCH to find current market opportunities -->
              
              <!-- Clean up pending trade entry -->
              <!-- Use library function to clear pending trade data -->
              <run_actions ref="md.GT_Libraries_General.GT_ClearPendingTradeData">
                <param name="ship" value="$ship"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_General.GT_ClearUICreditsDueForShip">
                <param name="ship" value="$ship"/>
              </run_actions>
            </do_else>
            
            <!-- Build structured failure payload for unified signal -->
            <set_value name="$failurePayload" exact="table[
              $Ship = $ship,
              $Reason = @$data.$reason,
              $FailureText = @$data.$failureText,
              $Partner = @$data.$partner,
              $IsBuying = @$data.$isBuying,
              $ReasonType = $failureCategory,
              $PathBlocked = $pathBlocked,
              $ShouldTryNext = $shouldTryNext,
              $Timestamp = player.age
            ]"/>
            
            <!-- Send unified GT_Trade_Failed signal with structured payload -->
            <do_if value="$isPathingFailure">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] Sending GT_Trade_Failed (PATHING) signal to ' + $ship.idcode + ' - will try next cached trade'" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Failure] MARKET FAILURE: ' + $ship.idcode + ' - market conditions changed - will search for new trade'" chance="100"/>
              </do_if>
            </do_else>
            
            <!-- SAFETY: cancel_cue does not stop the current actions block.
                 Guard signal dispatch explicitly so null/missing ships cannot crash this cue. -->
            <do_if value="$ship? and $ship.exists">
              <signal_objects object="$ship" param="'GT_Trade_Failed'" param2="$failurePayload" delay="1ms"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-Signals] GT_Trade_Failed signal sent successfully to ' + $ship.idcode + ' (ReasonType: ' + $failureCategory + ', ShouldTryNext: ' + $shouldTryNext + ')'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- 4. Cargo Safety: Handle destroyed sell station -->
            <do_if value="@$data.$reason == 'ERR_TRADEPARTNER_DESTROYED' and not @$data.$isBuying">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-CargoSafety] âš  Sell station destroyed for ' + $ship.idcode + ' - Cargo safety system will handle this'" chance="100"/>
              </do_if>
              <!-- TODO: Uncomment when cargo safety system is implemented -->
            </do_if>
          <!-- Continue if more items exist -->
          <do_if value="not $terminated and global.$GT_TradeFailureQueue? and global.$GT_TradeFailureQueue.count gt 0">
            <signal_cue_instantly cue="md.GT_Trading_Signals.ProcessTradeFailureQueue"/>
          </do_if>
        </do_if>
        </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Miner transfer handler: route delivery XP into shared XP pipeline -->
    <cue name="ProcessMinerTransfer" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_MinerTransfer'"/>
      </conditions>
      <actions>
        <set_value name="$transferData" exact="event.param2"/>
        <do_if value="$transferData? and $transferData.$Ship? and $transferData.$pilot? and $transferData.$xpAmount?">
          <signal_cue_instantly cue="md.GT_XP_Training.ProcessSingleXPEvent" param="$transferData"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-Miner] XP event routed for ' + $transferData.$Ship.idcode + ': +' + $transferData.$xpAmount + ' XP, ware=' + @$transferData.$ware + ', amount=' + @$transferData.$transferredAmount" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- All handlers are now inlined in ProcessTradeSuccess and ProcessTradeFailure
         for better performance and simpler debugging -->
    
  </cues>
</mdscript>
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_WareFilter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- ============================================ -->
    <!-- GALAXYTRADER MK3 - WARE FILTER MANAGEMENT   -->
    <!-- ============================================ -->
    <!-- Advanced ware filtering system allowing     -->
    <!-- dynamic blacklist/whitelist management      -->
    <!-- ============================================ -->
    
    <!-- Initialization -->
    <cue name="Init" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_Configuration.ConfigInitV3"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Initializing Ware Filter Management System...'" chance="100"/>
        </do_if>
        
        <!-- Initialize ware filter data -->
        <set_value name="global.$GT_WareFilter" exact="table[]"/>
        <set_value name="global.$GT_WareFilter.$Statistics" exact="table[]"/>
        <set_value name="global.$GT_WareFilter.$Statistics.$FiltersApplied" exact="0"/>
        <set_value name="global.$GT_WareFilter.$Statistics.$TradesBlocked" exact="0"/>
        <set_value name="global.$GT_WareFilter.$Statistics.$WaresBlocked" exact="table[]"/>
        
        <!-- Initialize dynamic ware lists -->
        <set_value name="global.$GT_WareFilter.$DefaultBlacklist" exact="[]"/>
        <set_value name="global.$GT_WareFilter.$DangerousWares" exact="[]"/>
        <set_value name="global.$GT_WareFilter.$HighValueWares" exact="[]"/>
        <set_value name="global.$GT_WareFilter.$LowValueWares" exact="[]"/>
        
        <!-- Trigger dynamic ware categorization -->
        <signal_cue cue="CategorizeWares"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ware Filter Management System initialized successfully'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Dynamic Ware Categorization -->
    <cue name="CategorizeWares" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="global.$GT_Config.$Debug.$LogLevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Categorizing wares dynamically...'" chance="100"/>
        </do_if>
        
        <!-- Get all available wares directly from WareDB (much faster than scanning stations) -->
        <!-- Use get_ware_definition to query the WareDB directly - no station scanning needed! -->
        <set_value name="$allWares" exact="[]"/>
        
        <!-- Get wares by groups and combine them to get comprehensive list -->
        <!-- This is more efficient than scanning all stations and trade offers -->
        <get_ware_definition result="$HightechWares" group="'hightech'"/>
        <get_ware_definition result="$RefinedWares" group="'refined'"/>
        <get_ware_definition result="$EnergyWares" group="'energy'"/>
        <get_ware_definition result="$FoodWares" group="'food'"/>
        <get_ware_definition result="$MedicalWares" group="'medical'"/>
        <get_ware_definition result="$WaterWares" group="'water'"/>
        <get_ware_definition result="$OreWares" group="'ore'"/>
        <get_ware_definition result="$GasWares" group="'gas'"/>
        <get_ware_definition result="$IceWares" group="'ice'"/>
        <get_ware_definition result="$ContainerWares" group="'container'"/>
        <get_ware_definition result="$ShipWares" group="'ship'"/>
        <get_ware_definition result="$StationWares" group="'station'"/>
        <get_ware_definition result="$EquipmentWares" group="'equipment'"/>
        
        <!-- Combine all ware groups into single list -->
        <append_list_elements name="$allWares" other="$HightechWares"/>
        <append_list_elements name="$allWares" other="$RefinedWares"/>
        <append_list_elements name="$allWares" other="$EnergyWares"/>
        <append_list_elements name="$allWares" other="$FoodWares"/>
        <append_list_elements name="$allWares" other="$MedicalWares"/>
        <append_list_elements name="$allWares" other="$WaterWares"/>
        <append_list_elements name="$allWares" other="$OreWares"/>
        <append_list_elements name="$allWares" other="$GasWares"/>
        <append_list_elements name="$allWares" other="$IceWares"/>
        <append_list_elements name="$allWares" other="$ContainerWares"/>
        <append_list_elements name="$allWares" other="$ShipWares"/>
        <append_list_elements name="$allWares" other="$StationWares"/>
        <append_list_elements name="$allWares" other="$EquipmentWares"/>
        
        <!-- Remove duplicates using a set -->
        <set_value name="$wareSet" exact="table[]"/>
        <set_value name="$uniqueWares" exact="[]"/>
        <do_all exact="$allWares.count" counter="$i">
          <set_value name="$ware" exact="$allWares.{$i}"/>
          <do_if value="$ware.exists and not $wareSet.{$ware}?">
            <set_value name="$wareSet.{$ware}" exact="true"/>
            <append_to_list name="$uniqueWares" exact="$ware"/>
          </do_if>
        </do_all>
        <set_value name="$allWares" exact="$uniqueWares"/>
        
        <do_if value="global.$GT_Config.$Debug.$LogLevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Found ' + $allWares.count + ' unique wares from WareDB'" chance="100"/>
        </do_if>
        
        <!-- Categorize wares based on properties and tags -->
        <do_all exact="$allWares.count" counter="$i">
          <set_value name="$ware" exact="$allWares.{$i}"/>
          
          <!-- Skip invalid wares -->
          <do_if value="$ware.exists">
            <!-- Check for low-value/problematic wares -->
            <set_value name="$isLowValue" exact="false"/>
            <set_value name="$isDangerous" exact="false"/>
            <set_value name="$isHighValue" exact="false"/>
            
            <!-- Safely get ware properties -->
            <set_value name="$wareVolume" exact="@$ware.volume"/>
            <set_value name="$warePrice" exact="@$ware.price"/>
            <set_value name="$wareName" exact="@$ware.name"/>
            <set_value name="$wareIllegal" exact="@$ware.illegal"/>
            
            <!-- Get configurable thresholds -->
            <set_value name="$lowValueThreshold" exact="@global.$GT_Config.$WareFilter.$LowValueThreshold"/>
            <set_value name="$highValueThreshold" exact="@global.$GT_Config.$WareFilter.$HighValueThreshold"/>
            <set_value name="$autoCategorizeLowValue" exact="@global.$GT_Config.$WareFilter.$AutoCategorizeLowValue"/>
            <set_value name="$autoCategorizeDangerous" exact="@global.$GT_Config.$WareFilter.$AutoCategorizeDangerous"/>
            
            <!-- Low-value ware detection using configurable threshold -->
            <do_if value="$autoCategorizeLowValue and $warePrice le $lowValueThreshold">
              <set_value name="$isLowValue" exact="true"/>
            </do_if>
            
            <!-- Detect wares with typically low profit margins -->
            <do_if value="$autoCategorizeLowValue and $wareName">
              <set_value name="$nameCheck" exact="$wareName.tolowercase"/>
              <do_if value="$nameCheck.indexof.{'food'} != -1 or $nameCheck.indexof.{'medical'} != -1 or $nameCheck.indexof.{'energy'} != -1 or $nameCheck.indexof.{'ration'} != -1">
                <set_value name="$isLowValue" exact="true"/>
              </do_if>
            </do_if>
            
            <!-- High-value ware detection using configurable threshold -->
            <do_if value="$warePrice ge $highValueThreshold">
              <set_value name="$isHighValue" exact="true"/>
            </do_if>
            
            <!-- Detect high-tech components by name -->
            <do_if value="$wareName">
              <set_value name="$nameCheck" exact="$wareName.tolowercase"/>
              <do_if value="$nameCheck.indexof.{'advanced'} != -1 or $nameCheck.indexof.{'quantum'} != -1 or $nameCheck.indexof.{'smart'} != -1 or $nameCheck.indexof.{'microchip'} != -1">
                <set_value name="$isHighValue" exact="true"/>
              </do_if>
            </do_if>
            
            <!-- Dangerous ware detection (illegal, restricted) -->
            <!-- FIX: Explicit gt 0 check to ensure legal wares (illegal=0) are not marked as dangerous -->
            <do_if value="$autoCategorizeDangerous and $wareIllegal gt 0">
              <set_value name="$isDangerous" exact="true"/>
            </do_if>
            
            <!-- Add to appropriate lists -->
            <do_if value="$isLowValue">
              <append_to_list name="global.$GT_WareFilter.$LowValueWares" exact="$ware"/>
              <append_to_list name="global.$GT_WareFilter.$DefaultBlacklist" exact="$ware"/>
            </do_if>
            
            <do_if value="$isDangerous">
              <append_to_list name="global.$GT_WareFilter.$DangerousWares" exact="$ware"/>
            </do_if>
            
            <do_if value="$isHighValue">
              <append_to_list name="global.$GT_WareFilter.$HighValueWares" exact="$ware"/>
            </do_if>
          </do_if>
        </do_all>
        
        <!-- Log categorization results -->
        <do_if value="global.$GT_Config.$Debug.$LogLevel ge 1 and @global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ware categorization complete:'" chance="100"/>
          <debug_text text="'  - Low Value/Default Blacklisted: ' + global.$GT_WareFilter.$LowValueWares.count" chance="100"/>
          <debug_text text="'  - Dangerous Wares: ' + global.$GT_WareFilter.$DangerousWares.count" chance="100"/>
          <debug_text text="'  - High Value Wares: ' + global.$GT_WareFilter.$HighValueWares.count" chance="100"/>
        </do_if>
        
        <!-- Initialize configuration with dynamic defaults -->
        <do_if value="not global.$GT_Config.$WareFilter.$BlacklistedWares? or global.$GT_Config.$WareFilter.$BlacklistedWares.count == 0">
          <set_value name="global.$GT_Config.$WareFilter.$BlacklistedWares" exact="global.$GT_WareFilter.$DefaultBlacklist"/>
        </do_if>
        
        <do_if value="not global.$GT_Config.$WareFilter.$WhitelistedWares?">
          <set_value name="global.$GT_Config.$WareFilter.$WhitelistedWares" exact="[]"/>
        </do_if>
        
        <!-- Show categorization summary -->
        <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
          <param name="text" value="$allWares.count + ' wares categorized: ' + global.$GT_WareFilter.$LowValueWares.count + ' low-value, ' + global.$GT_WareFilter.$DangerousWares.count + ' dangerous, ' + global.$GT_WareFilter.$HighValueWares.count + ' high-value'"/>
          <param name="category" value="'upkeep'"/>
          <param name="timeout" value="8s"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Manual Ware Refresh -->
    <cue name="RefreshWaresOnDemand" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Refreshing ware categories (manual)...'" chance="100"/>
        </do_if>
        
        <!-- Clear existing categories -->
        <set_value name="global.$GT_WareFilter.$DefaultBlacklist" exact="[]"/>
        <set_value name="global.$GT_WareFilter.$DangerousWares" exact="[]"/>
        <set_value name="global.$GT_WareFilter.$HighValueWares" exact="[]"/>
        <set_value name="global.$GT_WareFilter.$LowValueWares" exact="[]"/>
        
        <!-- Re-categorize -->
        <signal_cue cue="CategorizeWares"/>
        
        <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
          <param name="text" value="'Ware categories refreshed from current game state'"/>
          <param name="category" value="'upkeep'"/>
          <param name="timeout" value="5s"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Dynamic Blacklist Management -->
    <cue name="AddToBlacklist" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ware" exact="event.param"/>
        
        <do_if value="$ware">
          <!-- Check if already blacklisted -->
          <set_value name="$alreadyBlacklisted" exact="false"/>
          <do_if value="global.$GT_Config.$WareFilter.$BlacklistedWares?">
            <do_all exact="global.$GT_Config.$WareFilter.$BlacklistedWares.count" counter="$i">
              <do_if value="global.$GT_Config.$WareFilter.$BlacklistedWares.{$i} == $ware">
                <set_value name="$alreadyBlacklisted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="not $alreadyBlacklisted">
            <!-- Add to blacklist -->
            <append_to_list name="global.$GT_Config.$WareFilter.$BlacklistedWares" exact="$ware"/>
            
            <!-- Send notification -->
            <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
              <param name="text" value="'Ware ' + $ware.name + ' added to blacklist'"/>
              <param name="category" value="'upkeep'"/>
              <param name="timeout" value="5s"/>
            </run_actions>
            
            <!-- Update statistics -->
            <set_value name="global.$GT_WareFilter.$Statistics.$FiltersApplied" exact="global.$GT_WareFilter.$Statistics.$FiltersApplied + 1"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Added ' + $ware + ' to blacklist'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Ware ' + $ware + ' already blacklisted'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Remove from Blacklist -->
    <cue name="RemoveFromBlacklist" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ware" exact="event.param"/>
        
        <do_if value="$ware and global.$GT_Config.$WareFilter.$BlacklistedWares?">
          <set_value name="$found" exact="false"/>
          <do_all exact="global.$GT_Config.$WareFilter.$BlacklistedWares.count" counter="$i">
            <do_if value="global.$GT_Config.$WareFilter.$BlacklistedWares.{$i} == $ware">
              <remove_value name="global.$GT_Config.$WareFilter.$BlacklistedWares.{$i}"/>
              <set_value name="$found" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          
          <do_if value="$found">
            <!-- Send notification -->
            <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
              <param name="text" value="'Ware ' + $ware.name + ' removed from blacklist'"/>
              <param name="category" value="'upkeep'"/>
              <param name="timeout" value="5s"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Removed ' + $ware + ' from blacklist'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Ware ' + $ware + ' not found in blacklist'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    
    <!-- Whitelist Management -->
    <cue name="AddToWhitelist" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ware" exact="event.param"/>
        
        <do_if value="$ware">
          <!-- Check if already whitelisted -->
          <set_value name="$alreadyWhitelisted" exact="false"/>
          <do_if value="global.$GT_Config.$WareFilter.$WhitelistedWares?">
            <do_all exact="global.$GT_Config.$WareFilter.$WhitelistedWares.count" counter="$i">
              <do_if value="global.$GT_Config.$WareFilter.$WhitelistedWares.{$i} == $ware">
                <set_value name="$alreadyWhitelisted" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="not $alreadyWhitelisted">
            <append_to_list name="global.$GT_Config.$WareFilter.$WhitelistedWares" exact="$ware"/>
            
            <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
              <param name="text" value="'Ware ' + $ware.name + ' added to whitelist'"/>
              <param name="category" value="'upkeep'"/>
              <param name="timeout" value="5s"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Added ' + $ware + ' to whitelist'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Dangerous Ware Handler -->
    <cue name="DangerousWareDetected" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$ware" exact="event.param"/>
        <set_value name="$ship" exact="event.param2"/>
        
        <!-- Handle based on dangerous ware policy -->
        <do_if value="global.$GT_Config.$WareFilter.$DangerousWareHandling == 'priority'">
          <!-- Prioritize dangerous wares for higher profits -->
          <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
            <param name="text" value="'Prioritizing dangerous ware: ' + $ware.name"/>
            <param name="category" value="'upkeep'"/>
            <param name="timeout" value="6s"/>
          </run_actions>
        </do_if>
                 <do_elseif value="global.$GT_Config.$WareFilter.$DangerousWareHandling == 'avoid'">
           <!-- Add to temporary blacklist -->
           <signal_cue_instantly cue="AddToBlacklist" param="$ware"/>
         </do_elseif>
      </actions>
    </cue>
    
    <!-- Clear All Filters -->
    <cue name="ClearAllFilters" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Clearing all ware filters...'" chance="100"/>
        </do_if>
        
        <!-- Clear blacklist -->
        <set_value name="global.$GT_Config.$WareFilter.$BlacklistedWares" exact="[]"/>
        
        <!-- Clear whitelist -->
        <set_value name="global.$GT_Config.$WareFilter.$WhitelistedWares" exact="[]"/>
        
        <!-- Reset statistics -->
        <set_value name="global.$GT_WareFilter.$Statistics.$FiltersApplied" exact="0"/>
        <set_value name="global.$GT_WareFilter.$Statistics.$TradesBlocked" exact="0"/>
        <set_value name="global.$GT_WareFilter.$Statistics.$WaresBlocked" exact="table[]"/>
        
        <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
          <param name="text" value="'All ware filters cleared'"/>
          <param name="category" value="'upkeep'"/>
          <param name="timeout" value="5s"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- Reset to Defaults -->
    <cue name="ResetToDefaults" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Resetting filters to defaults...'" chance="100"/>
        </do_if>
        
        <!-- Reset to default blacklist -->
        <set_value name="global.$GT_Config.$WareFilter.$BlacklistedWares" exact="global.$GT_WareFilter.$DefaultBlacklist"/>
        
        <!-- Clear whitelist -->
        <set_value name="global.$GT_Config.$WareFilter.$WhitelistedWares" exact="[]"/>
        
        <!-- Reset dangerous ware handling -->
        <set_value name="global.$GT_Config.$WareFilter.$DangerousWareHandling" exact="'avoid'"/>
        
        <run_actions ref="md.GT_Libraries_General.GT_ShowNotification">
          <param name="text" value="'Ware filters reset to defaults'"/>
          <param name="category" value="'upkeep'"/>
          <param name="timeout" value="5s"/>
        </run_actions>
      </actions>
    </cue>
    
    <!-- PHASE 4 IMPROVEMENT: Event-Driven Ware Filter Intelligence -->
    <!-- Initialize ware filter event system -->
    <cue name="InitWareFilterEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="Init"/>
      </conditions>
      <actions>
        <!-- Initialize ware filter event queue -->
        <set_value name="global.$GT_WareFilterEventQueue" exact="[]"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] âš¡ Ware filter event system initialized (event-driven)'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Process Ware Filter Events -->
    <!-- EVENT-DRIVEN: Listen for signal instead of polling -->
    <cue name="ProcessWareFilterEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_WareFilter.ProcessWareFilterEvents"/>
      </conditions>
      <actions>
        
        <do_if value="global.$GT_WareFilterEventQueue? and global.$GT_WareFilterEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] âš¡ Processing ' + global.$GT_WareFilterEventQueue.count + ' ware filter events instantly'" chance="100"/>
          </do_if>
          
          <!-- Process events in batches to handle high volume -->
          <set_value name="$batchSize" exact="10"/>
          <set_value name="$processedCount" exact="0"/>
          
          <do_all exact="[$batchSize, global.$GT_WareFilterEventQueue.count].min" counter="$i">
            <set_value name="$event" exact="global.$GT_WareFilterEventQueue.{$i}"/>
            <set_value name="$type" exact="$event.$type"/>
            
            <!-- Route to appropriate handler -->
            <do_if value="$type == 'market_change'">
              <signal_cue_instantly cue="HandleMarketChangeEvent" param="$event"/>
            </do_if>
            <do_elseif value="$type == 'trade_failure'">
              <signal_cue_instantly cue="HandleTradeFailureEvent" param="$event"/>
            </do_elseif>
            <do_elseif value="$type == 'ware_performance'">
              <signal_cue_instantly cue="HandleWarePerformanceEvent" param="$event"/>
            </do_elseif>
            <do_elseif value="$type == 'filter_stats'">
              <signal_cue_instantly cue="HandleFilterStatsEvent" param="$event"/>
            </do_elseif>
            
            <set_value name="$processedCount" exact="$processedCount + 1"/>
          </do_all>
          
          <!-- Remove processed events -->
          <do_all exact="$processedCount" counter="$j" reverse="true">
            <remove_value name="global.$GT_WareFilterEventQueue.{$j}"/>
          </do_all>
          
          <!-- If more events remain, schedule next batch -->
          <do_if value="global.$GT_WareFilterEventQueue.count gt 0">
            <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
            <signal_cue cue="md.GT_WareFilter.ProcessWareFilterEvents"/>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle Market Change Events -->
    <cue name="HandleMarketChangeEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$ware" exact="$event.$ware"/>
        <set_value name="$changeType" exact="$event.$changeType"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ware filter event: Market change for ' + $ware + ' (' + $changeType + ')'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle Trade Failure Events -->
    <cue name="HandleTradeFailureEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$ware" exact="$event.$ware"/>
        <set_value name="$ship" exact="$event.$ship"/>
        <set_value name="$reason" exact="$event.$reason"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ware filter event: Trade failure for ' + $ware + ' on ' + $ship.idcode + ' (' + $reason + ')'" chance="100"/>
        </do_if>
        
        <!-- Auto-analyze for potential blacklisting -->
        <do_if value="$reason == 'unprofitable' or $reason == 'no_demand'">
          <!-- Add to performance tracking -->
          <set_value name="$performanceData" exact="table[]"/>
          <set_value name="$performanceData.$ware" exact="$ware"/>
          <set_value name="$performanceData.$ship" exact="$ship"/>
          <set_value name="$performanceData.$success" exact="false"/>
          <set_value name="$performanceData.$profit" exact="0"/>
          <signal_cue_instantly cue="TrackWarePerformance" param="$performanceData"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Handle Ware Performance Events -->
    <cue name="HandleWarePerformanceEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$ware" exact="$event.$ware"/>
        <set_value name="$performance" exact="$event.$performance"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ware filter event: Performance update for ' + $ware + ' (score: ' + $performance + ')'" chance="100"/>
        </do_if>
        
        <!-- Check for auto-blacklist criteria -->
        <do_if value="$performance lt -50"> <!-- Consistently poor performance -->
          <signal_cue_instantly cue="AddToBlacklist" param="$ware"/>
        </do_if>
        <do_elseif value="$performance gt 100"> <!-- Excellent performance -->
          <!-- Consider for whitelist if not already there -->
          <signal_cue_instantly cue="AddToWhitelist" param="$ware"/>
        </do_elseif>
      </actions>
    </cue>
    
    <!-- Handle Filter Stats Events -->
    <cue name="HandleFilterStatsEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$event" exact="event.param"/>
        <set_value name="$trigger" exact="$event.$trigger"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Ware filter event: Stats update triggered by ' + $trigger" chance="100"/>
        </do_if>
        
        <!-- Generate real-time filter effectiveness report -->
        <signal_cue_instantly cue="GenerateFilterStats"/>
      </actions>
    </cue>
    
    <!-- Track Ware Performance -->
    <cue name="TrackWarePerformance" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$ware" exact="$data.$ware"/>
        <set_value name="$ship" exact="$data.$Ship"/>
        <set_value name="$success" exact="$data.$success"/>
        <set_value name="$profit" exact="$data.$profit"/>
        
        <!-- Initialize ware performance tracking -->
        <do_if value="not global.$GT_WareFilter.$Performance?">
          <set_value name="global.$GT_WareFilter.$Performance" exact="table[]"/>
        </do_if>
        
        <do_if value="not global.$GT_WareFilter.$Performance.{$ware}?">
          <set_value name="global.$GT_WareFilter.$Performance.{$ware}" exact="table[]"/>
          <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$TotalTrades" exact="0"/>
          <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$SuccessfulTrades" exact="0"/>
          <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$TotalProfit" exact="0"/>
          <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$LastUpdate" exact="player.age"/>
        </do_if>
        
        <!-- Update performance data -->
        <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$TotalTrades" exact="global.$GT_WareFilter.$Performance.{$ware}.$TotalTrades + 1"/>
        
        <do_if value="$success">
          <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$SuccessfulTrades" exact="global.$GT_WareFilter.$Performance.{$ware}.$SuccessfulTrades + 1"/>
        </do_if>
        
        <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$TotalProfit" exact="global.$GT_WareFilter.$Performance.{$ware}.$TotalProfit + $profit"/>
        <set_value name="global.$GT_WareFilter.$Performance.{$ware}.$LastUpdate" exact="player.age"/>
        
        <!-- M5 FIX: Cap performance tracking table to prevent unbounded growth -->
        <do_if value="global.$GT_WareFilter.$Performance.keys.count gt 200">
          <set_value name="global.$GT_WareFilter.$Performance" exact="table[]"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Generate Real-time Filter Stats -->
    <cue name="GenerateFilterStats" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Real-time filter effectiveness calculation -->
        <set_value name="$totalFilters" exact="0"/>
        <set_value name="$totalBlocked" exact="0"/>
        
        <do_if value="global.$GT_WareFilter.$Statistics?">
          <set_value name="$totalFilters" exact="global.$GT_WareFilter.$Statistics.$FiltersApplied"/>
          <set_value name="$totalBlocked" exact="global.$GT_WareFilter.$Statistics.$TradesBlocked"/>
        </do_if>
        
        <!-- Performance analysis -->
        <set_value name="$avgPerformance" exact="0"/>
        <set_value name="$wareCount" exact="0"/>
        
        <do_if value="global.$GT_WareFilter.$Performance? and global.$GT_WareFilter.$Performance.keys.count gt 0">
          <do_all exact="global.$GT_WareFilter.$Performance.keys.count" counter="$i">
            <set_value name="$ware" exact="global.$GT_WareFilter.$Performance.keys.list.{$i}"/>
            <set_value name="$wareData" exact="global.$GT_WareFilter.$Performance.{$ware}"/>
            
            <do_if value="$wareData.$TotalTrades gt 0">
              <set_value name="$warePerformance" exact="($wareData.$TotalProfit / $wareData.$TotalTrades)"/>
              <set_value name="$avgPerformance" exact="$avgPerformance + $warePerformance"/>
              <set_value name="$wareCount" exact="$wareCount + 1"/>
            </do_if>
          </do_all>
          
          <do_if value="$wareCount gt 0">
            <set_value name="$avgPerformance" exact="$avgPerformance / $wareCount"/>
          </do_if>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Filter intelligence: ' + $totalFilters + ' filters, ' + $totalBlocked + ' blocked, avg performance: ' + $avgPerformance + ' Cr/trade'" chance="100"/>
        </do_if>
      </actions>
    </cue>
  </cues>
</mdscript> 
<?xml version="1.0" encoding="utf-8"?>
<mdscript name="GT_XP_Training" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../stock_game/X4 Foundations/libraries/md.xsd">
  <cues>
    <!-- Main XP and Training System -->
    <cue name="Initialize">
      <conditions>
        <check_any>
          <event_player_created/>
          <event_game_loaded/>
        </check_any>
        <check_value value="global.$GT_Config?"/>
      </conditions>
      <actions>
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] XP and Training System initialized'" chance="100"/>
        </do_if>
        
        <!-- Initialize session stats properties if needed -->
        <do_if value="not global.$GT_SessionStats.$XPGained?">
          <set_value name="global.$GT_SessionStats.$XPGained" exact="0"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- Trading Academy / in-flight training save/load recovery.
         Re-dispatch DockAndTrain when enrollment or an active timer persists
         but the ship lost its training order. When DockAndTrain still exists,
         preserve timer fields and restore XPBlocked if the load dropped it. -->
    <cue name="RecoverAcademyEnrollmentsOnLoad" instantiate="true" version="1">
      <conditions>
        <event_game_loaded/>
        <check_value value="global.$GT_Config?"/>
      </conditions>
      <delay exact="2s"/>
      <actions>
        <!-- Stale DockAndTrain sanitizer: saved destination refs can resolve to
             component.{0x0L} after load; cancel and re-queue station search. -->
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$spi">
            <set_value name="$spilot" exact="global.$GT_Pilots.keys.{$spi}"/>
            <set_value name="$sship" exact="null"/>
            <do_if value="global.$GT_Pilots.{$spilot}.$Ship? and global.$GT_Pilots.{$spilot}.$Ship.exists">
              <set_value name="$sship" exact="global.$GT_Pilots.{$spilot}.$Ship"/>
            </do_if>
            <do_if value="$sship? and $sship.pilot? and $sship.pilot == $spilot and $sship.orders?">
              <do_all exact="$sship.orders.count" counter="$soi">
                <do_if value="@$sship.orders.{$soi}.id == 'DockAndTrain'">
                  <set_value name="$staleTrainOrder" exact="$sship.orders.{$soi}"/>
                  <do_if value="not @$staleTrainOrder.$destination.exists">
                    <cancel_order order="$staleTrainOrder"/>
                    <set_value name="global.$GT_Pilots.{$spilot}.$ManualTrainingRequested" exact="true"/>
                    <set_value name="global.$GT_Pilots.{$spilot}.$TrainingState" exact="'manual_training_queued'"/>
                    <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
                      $Ship = $sship,
                      $Pilot = $spilot
                    ]"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GT Academy] Load recovery: cancelled stale DockAndTrain for ' + $spilot.name + ' on ship ' + $sship.idcode + ' (invalid destination) - re-dispatching'" chance="100"/>
                    </do_if>
                  </do_if>
                  <break/>
                </do_if>
              </do_all>
            </do_if>
          </do_all>
        </do_if>

        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.keys.count gt 0">
          <do_all exact="global.$GT_Pilots.keys.count" counter="$pi">
            <set_value name="$pilot" exact="global.$GT_Pilots.keys.{$pi}"/>
            <set_value name="$needsTrainingRecovery" exact="false"/>
            <do_if value="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?">
              <set_value name="$needsTrainingRecovery" exact="true"/>
            </do_if>
            <do_elseif value="global.$GT_Pilots.{$pilot}.$TrainingState? and global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress'">
              <set_value name="$needsTrainingRecovery" exact="true"/>
            </do_elseif>
            <do_if value="$needsTrainingRecovery">
              <set_value name="$ship" exact="null"/>
              <do_if value="global.$GT_Pilots.{$pilot}.$Ship? and global.$GT_Pilots.{$pilot}.$Ship.exists">
                <set_value name="$ship" exact="global.$GT_Pilots.{$pilot}.$Ship"/>
              </do_if>
              <do_if value="$ship? and $ship.pilot? and $ship.pilot == $pilot">
                <set_value name="$hasDockAndTrain" exact="false"/>
                <set_value name="$dockTrainOrder" exact="null"/>
                <do_if value="$ship.orders?">
                  <do_all exact="$ship.orders.count" counter="$oi">
                    <do_if value="@$ship.orders.{$oi}.id == 'DockAndTrain'">
                      <set_value name="$dockTrainOrder" exact="$ship.orders.{$oi}"/>
                      <do_if value="@$dockTrainOrder.$destination.exists">
                        <set_value name="$hasDockAndTrain" exact="true"/>
                      </do_if>
                      <do_else>
                        <cancel_order order="$dockTrainOrder"/>
                        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                          <debug_text text="'[GT Academy] Load recovery: cancelled stale DockAndTrain for ' + $pilot.name + ' on ship ' + $ship.idcode + ' (invalid destination)'" chance="100"/>
                        </do_if>
                      </do_else>
                      <break/>
                    </do_if>
                  </do_all>
                </do_if>
                <do_if value="$hasDockAndTrain and global.$GT_Pilots.{$pilot}.$TrainingState? and global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress'">
                  <do_if value="not global.$GT_Pilots.{$pilot}.$XPBlocked? and global.$GT_Pilots.{$pilot}.$BlockedLevel? and global.$GT_Pilots.{$pilot}.$BlockedLevel gt 1">
                    <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
                      <param name="pilot" value="$pilot"/>
                      <param name="level" value="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                      <param name="set_xpblocked" value="true"/>
                    </run_actions>
                    <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_in_progress'"/>
                  </do_if>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT Academy] Load recovery: preserving in-flight training for ' + $pilot.name + ' on ship ' + $ship.idcode + ' (DockAndTrain active)'" chance="100"/>
                  </do_if>
                </do_if>
                <do_elseif value="not $hasDockAndTrain">
                  <set_value name="$preserveTimer" exact="false"/>
                  <do_if value="global.$GT_Pilots.{$pilot}.$TrainingState? and global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress'">
                    <do_if value="global.$GT_Pilots.{$pilot}.$AcademyEnrollment? and global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$CostPaid?">
                      <set_value name="$preserveTimer" exact="true"/>
                    </do_if>
                    <do_elseif value="global.$GT_Pilots.{$pilot}.$TrainingStarted?">
                      <set_value name="$preserveTimer" exact="true"/>
                    </do_elseif>
                  </do_if>
                  <do_if value="not $preserveTimer">
                    <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
                    <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
                    <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
                  </do_if>
                  <set_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested" exact="true"/>
                  <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'manual_training_queued'"/>
                  <signal_objects object="player.galaxy" param="'GT_Training_Needed'" param2="table[
                    $Ship = $ship,
                    $Pilot = $pilot
                  ]"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT Academy] Load recovery: re-dispatching training for ' + $pilot.name + ' on ship ' + $ship.idcode + ' (timer preserved=' + $preserveTimer + ')'" chance="100"/>
                  </do_if>
                </do_elseif>
              </do_if>
            </do_if>
          </do_all>
        </do_if>
      </actions>
    </cue>
    
    <!-- Pilot Registration -->
    <cue name="RegisterPilot" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <!-- Prefer direct event params if provided -->
        <set_value name="$pilot" exact="event.param.$Pilot"/>
        <set_value name="$ship" exact="event.param.$Ship"/>
        <!-- Process queue-based registration first (prevents race conditions) -->
        <do_if value="(not $pilot? or not $ship?) and global.$GT_ShipRegistrationQueue? and global.$GT_ShipRegistrationQueue.count gt 0">
          <set_value name="$registrationData" exact="global.$GT_ShipRegistrationQueue.{1}"/>
          <set_value name="$ship" exact="$registrationData.$ship"/>
          <set_value name="$pilot" exact="$registrationData.$pilot"/>
          <remove_from_list name="global.$GT_ShipRegistrationQueue" exact="$registrationData"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] XP System: Processing ship from queue - ' + $pilot.name + ' on ' + $ship.knownname + ' (Ship ID: ' + $ship.idcode + ') [Queue remaining: ' + global.$GT_ShipRegistrationQueue.count + ']'" chance="100"/>
          </do_if>
        </do_if>
        <!-- Fallback to single signal system (backward compatibility) -->
        <do_elseif value="(not $pilot? or not $ship?) and global.$GT_RegisterPilot?">
          <set_value name="$pilot" exact="global.$GT_RegisterPilot"/>
          <set_value name="$ship" exact="global.$GT_RegisterShip"/>
          <remove_value name="global.$GT_RegisterPilot"/>
          <remove_value name="global.$GT_RegisterShip"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] XP System: Pilot registration - ' + $pilot.name + ' on ' + $ship.knownname + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_elseif>

        <!-- Always clear legacy single-registration globals after resolving inputs.
             Queue/event-param paths are authoritative; leaving globals set can leak stale handoff state. -->
        <do_if value="global.$GT_RegisterPilot?">
          <remove_value name="global.$GT_RegisterPilot"/>
        </do_if>
        <do_if value="global.$GT_RegisterShip?">
          <remove_value name="global.$GT_RegisterShip"/>
        </do_if>
        
        

        
        <!-- Use extracted initialization library -->
        <run_actions ref="md.GT_Ship_Management.Initialize_Pilot_Data" result="$wasNewPilot">
          <param name="pilot" value="$pilot"/>
          <param name="ship" value="$ship"/>
        </run_actions>
        
        <do_if value="$wasNewPilot">
          <!-- NEW PILOT - Update ship name with initial state -->
          <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] XP System: NEW pilot ' + $pilot.name + ' initialized with 0 XP, skill level 1, ship renamed to: ' + $ship.knownname + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_if>
        <do_else>
          <!-- EXISTING PILOT -->
          <!-- Store original ship name if not already stored (strip any existing GT formatting) -->
          <do_if value="not global.$GT_Pilots.{$pilot}.$OriginalShipName?">
            <run_actions ref="md.GT_Ship_Management.Strip_GT_Name_Formatting" result="$cleanedName">
              <param name="shipName" value="$ship.knownname"/>
            </run_actions>
            <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$cleanedName"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP] Stored cleaned original ship name for existing pilot: ' + $cleanedName + ' (from: ' + $ship.knownname + ') (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Use extracted ship name update library -->
          <run_actions ref="md.GT_Ship_Management.Update_Pilot_Ship_Name">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Calculate star rating for debug output -->
          <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
            <param name="pilot" value="$pilot"/>
          </run_actions>
          <set_value name="$starRating" exact="($currentSkillLevel / 3)i"/>
          <do_if value="$starRating gt 5">
            <set_value name="$starRating" exact="5"/>
          </do_if>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] XP System: EXISTING pilot ' + $pilot.name + ' - XP: ' + global.$GT_Pilots.{$pilot}.$XP + ', skill: ' + $currentSkillLevel + ' (' + $starRating + ' stars) (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
          </do_if>
        </do_else>
        
        <!-- Use extracted library for skill level calculation -->
        <!-- Calculate current skill level from existing XP for registration validation -->
        <run_actions ref="md.GT_Ship_Management.Calculate_Skill_Level_From_XP" result="$currentSkillLevel">
          <param name="pilot" value="$pilot"/>
        </run_actions>
        
        <!-- Only block if current skill level requires training AND pilot doesn't have training completed -->
        <!-- Check if current skill level requires training using explicit loop (indexof unreliable for lists) -->
        <set_value name="$requiresTraining" exact="false"/>
        <do_if value="global.$GT_Config.$Training.$RequiredLevels?">
          <do_all exact="global.$GT_Config.$Training.$RequiredLevels.count" counter="$i">
            <do_if value="global.$GT_Config.$Training.$RequiredLevels.{$i} == $currentSkillLevel">
              <set_value name="$requiresTraining" exact="true"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <do_if value="$requiresTraining">
          <!-- This skill level requires training - check if pilot has completed it -->
          <!-- Check if pilot has completed training using explicit loop (indexof unreliable for lists) -->
          <set_value name="$hasCompletedTraining" exact="false"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
            <do_all exact="global.$GT_Pilots.{$pilot}.$TrainingCompleted.count" counter="$j">
              <do_if value="global.$GT_Pilots.{$pilot}.$TrainingCompleted.{$j} == $currentSkillLevel">
                <set_value name="$hasCompletedTraining" exact="true"/>
                <break/>
              </do_if>
            </do_all>
          </do_if>
          
          <do_if value="not $hasCompletedTraining">
            <!-- Training required and not completed - block XP -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') BLOCKING PILOT: ' + $pilot.name + ' - skill level ' + $currentSkillLevel + ' requires training (this should NOT happen for level 1!)'" chance="100"/>
            </do_if>
            <do_if value="not global.$GT_Pilots.{$pilot}.$XPBlocked?">
              <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
                <param name="pilot" value="$pilot"/>
                <param name="level" value="$currentSkillLevel"/>
                <param name="set_xpblocked" value="true"/>
              </run_actions>
              
              <!-- UPDATE SHIP NAME TO SHOW BLOCKED STATE -->
              <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
              <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$currentXP"/>
                <param name="level" value="$currentSkillLevel"/>
                <param name="nameType" value="'blocked'"/>
              </run_actions>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') ðŸ·ï¸ Ship renamed to show blocked state: ' + $ship.knownname" chance="100"/>
              </do_if>
            </do_if>
          </do_if>
          <do_else>
            <!-- Training completed - ensure XP is not blocked -->
            <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Clearing XP block for pilot ' + $pilot.name + ' - training completed for skill level ' + $currentSkillLevel" chance="100"/>
              </do_if>
              <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
                <param name="pilot" value="$pilot"/>
                <param name="clear_blocked_level" value="true"/>
              </run_actions>
              
              <!-- UPDATE SHIP NAME TO CLEAR BLOCKED STATE (new format) -->
              <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="@global.$GT_Pilots.{$pilot}.$XP"/>
                <param name="level" value="$currentSkillLevel"/>
                <param name="nameType" value="'trader'"/>
              </run_actions>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <!-- Skill level doesn't require training - ensure XP is not blocked -->
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') NOT BLOCKING: Skill level ' + $currentSkillLevel + ' does not require training (correct for level 1)'" chance="100"/>
          </do_if>
          <do_if value="global.$GT_Pilots.{$pilot}.$XPBlocked?">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Clearing XP block for pilot ' + $pilot.name + ' - skill level ' + $currentSkillLevel + ' does not require training'" chance="100"/>
            </do_if>
            <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
              <param name="pilot" value="$pilot"/>
              <param name="clear_blocked_level" value="true"/>
            </run_actions>
            
            <!-- UPDATE SHIP NAME TO CLEAR BLOCKED STATE (new format) -->
                <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                  <param name="ship" value="$ship"/>
                  <param name="pilot" value="$pilot"/>
                  <param name="xp" value="@global.$GT_Pilots.{$pilot}.$XP"/>
                  <param name="level" value="$currentSkillLevel"/>
                  <param name="nameType" value="'trader'"/>
                </run_actions>
          </do_if>
        </do_else>
        
        <!-- Ensure all required fields exist (defensive programming) -->
        <do_if value="not global.$GT_Pilots.{$pilot}.$XP?">
          <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="0"/>
        </do_if>
        <do_if value="not global.$GT_Pilots.{$pilot}.$TrainingCompleted?">
          <set_value name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="[]"/>
        </do_if>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] XP system tracking pilot: ' + $pilot.name + ' (XP: ' + global.$GT_Pilots.{$pilot}.$XP + ') (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
        </do_if>
      </actions>
    </cue>
    
    <!-- PHASE 1 IMPROVEMENT: Event-Driven XP Award Handler -->
    <!-- EVENT-DRIVEN: Listen for signal instead of polling -->
    <cue name="ProcessXPEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_XP_Training.ProcessXPEvents"/>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <do_if value="$useVanillaXPOnly and global.$GT_XPEventQueue?">
          <remove_value name="global.$GT_XPEventQueue"/>
        </do_if>

        <!-- Source-of-truth: all queued XP events are forwarded to ProcessSingleXPEvent. -->
        <do_if value="not $useVanillaXPOnly and global.$GT_XPEventQueue? and global.$GT_XPEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GT-XP] Bridging ' + global.$GT_XPEventQueue.count + ' legacy queued XP events into ProcessSingleXPEvent'" chance="100"/>
          </do_if>
          <do_while value="global.$GT_XPEventQueue.count gt 0">
            <set_value name="$event" exact="global.$GT_XPEventQueue.{1}"/>
            <remove_from_list name="global.$GT_XPEventQueue" exact="$event"/>
            <set_value name="$eventPilot" exact="if $event? and $event.$pilot? then @$event.$pilot else (if $event? and $event.$Pilot? then @$event.$Pilot else null)"/>
            <set_value name="$eventShip" exact="if $event? and $event.$ship? then @$event.$ship else (if $event? and $event.$Ship? then @$event.$Ship else null)"/>
            <set_value name="$eventAmount" exact="if $event? and $event.$xpAmount? then @$event.$xpAmount else (if $event? and $event.$XPGained? then @$event.$XPGained else 0)"/>
            <set_value name="$eventWare" exact="if $event? and $event.$ware? then @$event.$ware else (if $event? and $event.$Ware? then @$event.$Ware else null)"/>
            <do_if value="$eventPilot? and $eventShip? and $eventAmount gt 0">
              <signal_cue_instantly cue="md.GT_XP_Training.ProcessSingleXPEvent" param="table[
                $pilot = $eventPilot,
                $Ship = $eventShip,
                $xpAmount = $eventAmount,
                $ware = $eventWare
              ]"/>
            </do_if>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- DEPRECATED: Direct Trade Completion Handler - Replaced by gt_trading_signals.xml
         
         This cue has been replaced by the centralized signal router in gt_trading_signals.xml
         which now handles all diff patch signals and routes them to appropriate systems.
         
         The new system (ProcessTradeSuccess in gt_trading_signals.xml) calls ProcessSingleXPEvent
         directly, making this intermediate handler obsolete.
    -->
    <!-- DirectTradeComplete cue removed - 60 lines of code that processed global.$GT_DirectTradeQueue
         has been replaced by gt_trading_signals.xml ProcessTradeSuccess which routes to ProcessSingleXPEvent -->
    
    <!-- PHASE 2 IMPROVEMENT: Optimized Single XP Event Processing -->
    <cue name="ProcessSingleXPEvent" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$trade_data" exact="event.param"/>
        
        <!-- Defensive: Prevent cascading errors if signal is raised with null data -->
        <!-- NOTE: cancel_cue does NOT stop the current actions block; gate explicitly. -->
        <!-- Vanilla XP mode: GT must not award XP, sync skills, or show level-up notifications. -->
        <set_value name="$hasTradeData" exact="true"/>
        <do_if value="$useVanillaXPOnly or $trade_data == null">
          <set_value name="$hasTradeData" exact="false"/>
        </do_if>
        <do_if value="not $hasTradeData">
          <cancel_cue cue="this"/>
        </do_if>
        <do_else>
        <set_value name="$pilot" exact="$trade_data.$pilot"/>
        <set_value name="$ship" exact="$trade_data.$Ship"/>
        <set_value name="$amount" exact="$trade_data.$xpAmount"/>
        <set_value name="$ware" exact="$trade_data.$ware"/>
        
        <!-- Check if pilot is valid and exists in our system -->
        <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
          <!-- Get current XP -->
          <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
          
          <!-- Calculate current skill level from XP -->
          <set_value name="$currentSkillLevel" exact="1"/>
          <do_all exact="15" counter="$skillLevel">
            <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
              <set_value name="$currentSkillLevel" exact="$skillLevel"/>
            </do_if>
          </do_all>
          
          <!-- Unified training/XP gate -->
          <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$pilotTrainingGate">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="respect_hard_force" value="true"/>
          </run_actions>
          <do_if value="$pilotTrainingGate.$XPGainBlocked">
            <set_value name="$blockedLevel" exact="$pilotTrainingGate.$BlockedLevel"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ')   XP gain blocked for pilot ' + $pilot.name + ' - training required at skill level ' + $blockedLevel + ' (attempted award: ' + $amount + ' XP)'" chance="100"/>
            </do_if>
            
            <!-- Store blocked XP for post-training award -->
            <do_if value="not global.$GT_Pilots.{$pilot}.$BlockedXPPending?">
              <set_value name="global.$GT_Pilots.{$pilot}.$BlockedXPPending" exact="0"/>
            </do_if>
            <set_value name="global.$GT_Pilots.{$pilot}.$BlockedXPPending" exact="global.$GT_Pilots.{$pilot}.$BlockedXPPending + $amount"/>
            
            <!-- Notify player occasionally about blocked XP -->
          <!--  <do_if value="global.$GT_Config.$Notifications.$TrainingRequired">
               Disabled by request: XP Blocked spam notifications/logbook entries.
                   Kept commented for quick re-enable.
              <set_value name="$message" exact="'Pilot ' + $pilot.name + ' earned ' + $amount + ' XP but needs training to advance! Total blocked: ' + global.$GT_Pilots.{$pilot}.$BlockedXPPending + ' XP'"/>
              <show_notification text="$message" timeout="6s" priority="8"/>
              <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                <param name="Message" value="$message"/>
                <param name="Category" value="'upkeep'"/>
                <param name="Title" value="'XP Blocked: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                <param name="Object" value="$ship"/>
                <param name="Interaction" value="'showonmap'"/>
                <param name="Highlighted" value="false"/>
                <param name="CheckGlobalSettings" value="false"/>
              </run_actions>
              
            </do_if>-->
          </do_if>
          <do_else>
            <!-- Add XP -->
            <set_value name="$newXP" exact="$currentXP + $amount"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="$newXP"/>
            <set_value name="global.$GT_SessionStats.$XPGained" exact="global.$GT_SessionStats.$XPGained + $amount"/>
            
            <!-- Calculate new skill level from new XP total -->
            <set_value name="$newSkillLevel" exact="1"/>
            <do_all exact="15" counter="$skillLevel">
              <do_if value="$newXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                <set_value name="$newSkillLevel" exact="$skillLevel"/>
              </do_if>
            </do_all>
            
            <!-- Calculate star rating for display (X4 management skill: 3 skill levels per star) -->
            <set_value name="$starRating" exact="($newSkillLevel / 3)i"/>
            <do_if value="$starRating gt 5">
              <set_value name="$starRating" exact="5"/>
            </do_if>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') DIRECT XP: Pilot ' + $pilot.name + ' gained ' + $amount + ' XP (total: ' + $newXP + ', skill: ' + $newSkillLevel + ', ' + $starRating + ' stars) for ' + $ware + ' trade'" chance="100"/>
            </do_if>
            
            <!-- COMMANDER XP BONUS: Award percentage of subordinate XP to commander -->
            <set_value name="$commanderBonusXP" exact="0"/>
            <do_if value="$ship.commander? and $ship.commander.exists and $ship.commander != $ship">
              <set_value name="$commander" exact="$ship.commander"/>
              <set_value name="$commanderPilot" exact="@$commander.pilot"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <set_value name="$pilotNameStr" exact="'NONE'"/>
                <do_if value="$commanderPilot?">
                  <set_value name="$pilotNameStr" exact="@$commanderPilot.name"/>
                </do_if>
                <debug_text text="'[GT-XP] Checking commander bonus for subordinate ' + $ship.idcode + ' (commander: ' + $commander.idcode + ', pilot: ' + $pilotNameStr + ')'" chance="100"/>
              </do_if>
              
              <!-- Check if commander has a GT pilot -->
              <do_if value="$commanderPilot? and global.$GT_Pilots? and global.$GT_Pilots.{$commanderPilot}?">
                <!-- Get commander bonus percentage from config (default 10%) -->
                <set_value name="$commanderBonusPercent" exact="10"/>
                <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$CommanderBonusPercent?">
                  <set_value name="$commanderBonusPercent" exact="global.$GT_GlobalSettings.$XP.$CommanderBonusPercent"/>
                </do_if>
                
                <!-- Calculate bonus XP (percentage of subordinate XP) -->
                <set_value name="$commanderBonusXP" exact="($amount * $commanderBonusPercent / 100)i"/>
                <!-- Ensure minimum 1 XP if subordinate got XP and bonus is enabled (percentage > 0) -->
                <!-- Only apply minimum if bonus is enabled - if percentage is 0%, respect that and award 0 XP -->
                <do_if value="$commanderBonusXP == 0 and $amount gt 0 and $commanderBonusPercent gt 0">
                  <set_value name="$commanderBonusXP" exact="1"/>
                </do_if>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GT-XP] Commander bonus calculated: ' + $commanderBonusXP + ' XP (' + $commanderBonusPercent + '% of ' + $amount + ')'" chance="100"/>
                </do_if>
                
                <!-- Check if commander's XP is blocked (shared gate logic) -->
                <set_value name="$commanderXPBlocked" exact="false"/>
                <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$commanderTrainingGate">
                  <param name="pilot" value="$commanderPilot"/>
                  <param name="ship" value="$commander"/>
                  <param name="respect_hard_force" value="true"/>
                </run_actions>
                <do_if value="$commanderTrainingGate.$XPGainBlocked">
                  <set_value name="$commanderXPBlocked" exact="true"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-XP] Commander XP blocked - skipping bonus award'" chance="100"/>
                  </do_if>
                </do_if>
                
                <!-- Award bonus XP if not blocked and bonus > 0 -->
                <do_if value="not $commanderXPBlocked and $commanderBonusXP gt 0">
                  <set_value name="$commanderCurrentXP" exact="global.$GT_Pilots.{$commanderPilot}.$XP"/>
                  <set_value name="$commanderNewXP" exact="$commanderCurrentXP + $commanderBonusXP"/>
                  <set_value name="global.$GT_Pilots.{$commanderPilot}.$XP" exact="$commanderNewXP"/>
                  <set_value name="global.$GT_SessionStats.$XPGained" exact="global.$GT_SessionStats.$XPGained + $commanderBonusXP"/>
                  
                  <!-- Calculate commander's current skill level -->
                  <set_value name="$commanderCurrentSkillLevel" exact="1"/>
                  <do_all exact="15" counter="$skillLevel">
                    <do_if value="$commanderCurrentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                      <set_value name="$commanderCurrentSkillLevel" exact="$skillLevel"/>
                    </do_if>
                  </do_all>
                  
                  <!-- Calculate commander's new skill level from new XP total -->
                  <set_value name="$commanderNewSkillLevel" exact="1"/>
                  <do_all exact="15" counter="$skillLevel">
                    <do_if value="$commanderNewXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                      <set_value name="$commanderNewSkillLevel" exact="$skillLevel"/>
                    </do_if>
                  </do_all>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] (' + $commander.idcode + ') Commander pilot ' + $commanderPilot.name + ' gained ' + $commanderBonusXP + ' bonus XP (' + $commanderBonusPercent + '% of ' + $amount + ') from subordinate ' + $ship.idcode + ' (total: ' + $commanderNewXP + ', skill: ' + $commanderNewSkillLevel + ')'" chance="100"/>
                  </do_if>
                  
                  <!-- Commander level-up: same training gate as direct XP (BSH-302: bonus XP must not bypass gates). -->
                  <do_if value="$commanderNewSkillLevel gt $commanderCurrentSkillLevel">
                    <run_actions ref="md.GT_Libraries_General.GT_ProcessLevelUpTrainingGate">
                      <param name="pilot" value="$commanderPilot"/>
                      <param name="ship" value="$commander"/>
                      <param name="currentSkillLevel" value="$commanderCurrentSkillLevel"/>
                      <param name="newSkillLevel" value="$commanderNewSkillLevel"/>
                      <param name="newXP" value="$commanderNewXP"/>
                      <param name="ware" value="$ware"/>
                      <param name="logTag" value="'COMMANDER BONUS'"/>
                    </run_actions>
                  </do_if>
                  <do_else>
                    <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                      <param name="ship" value="$commander"/>
                      <param name="pilot" value="$commanderPilot"/>
                      <param name="xp" value="$commanderNewXP"/>
                      <param name="level" value="$commanderNewSkillLevel"/>
                      <param name="nameType" value="'trader'"/>
                    </run_actions>
                  </do_else>
                </do_if>
                <do_else>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GT-XP] Commander bonus NOT awarded: blocked=' + $commanderXPBlocked + ', bonusXP=' + $commanderBonusXP" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <set_value name="$pilotNameStr" exact="'NONE'"/>
                  <do_if value="$commanderPilot?">
                    <set_value name="$pilotNameStr" exact="@$commanderPilot.name"/>
                  </do_if>
                  <debug_text text="'[GT-XP] Commander has no GT pilot - skipping bonus (commander: ' + $commander.idcode + ', pilot: ' + $pilotNameStr + ')'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GT-XP] Ship has no commander - skipping bonus check (ship: ' + $ship.idcode + ')'" chance="100"/>
              </do_if>
            </do_else>
            
            <!-- CHECK FOR TRAINING REQUIREMENTS BEFORE SKILL LEVEL INCREASE -->
            <do_if value="$newSkillLevel gt $currentSkillLevel">
              <run_actions ref="md.GT_Libraries_General.GT_ProcessLevelUpTrainingGate">
                <param name="pilot" value="$pilot"/>
                <param name="ship" value="$ship"/>
                <param name="currentSkillLevel" value="$currentSkillLevel"/>
                <param name="newSkillLevel" value="$newSkillLevel"/>
                <param name="newXP" value="$newXP"/>
                <param name="ware" value="$ware"/>
                <param name="logTag" value="'DIRECT'"/>
              </run_actions>
            </do_if>
            <do_else>
              <!-- No skill level change - just update stored level and ship name (raise-only sync). -->
              <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
              <do_if value="$newSkillLevel gt $vanillaMgmtLevel">
                <set_skill entity="$pilot" type="skilltype.management" exact="$newSkillLevel"/>
              </do_if>
              <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$newSkillLevel"/>
              
              <!-- Update pilot skill proportionally: Management Level 15 (5 stars) Pilot Level 9 (3 stars) -->
              <!-- Formula: pilot_level = (management_level * 9) / 15 -->
              <!-- Never reduce pilot skill, only increase if target is higher -->
              <set_value name="$currentPilotSkill" exact="0"/>
              <do_if value="$pilot.skill.piloting?">
                <set_value name="$currentPilotSkill" exact="@$pilot.skill.piloting"/>
              </do_if>
              <!-- Calculate target pilot skill level -->
              <set_value name="$targetPilotLevel" exact="($newSkillLevel * 9) / 15"/>
              <do_if value="$targetPilotLevel lt 1">
                <set_value name="$targetPilotLevel" exact="1"/>
              </do_if>
              <do_if value="$targetPilotLevel gt 9">
                <set_value name="$targetPilotLevel" exact="9"/>
              </do_if>
              <!-- Only increase pilot skill if target is higher than current -->
              <do_if value="$targetPilotLevel gt $currentPilotSkill">
                <set_skill entity="$pilot" type="skilltype.piloting" exact="$targetPilotLevel"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') âœˆï¸ Pilot skill increased from ' + $currentPilotSkill + ' to ' + $targetPilotLevel + ' (management: ' + $newSkillLevel + ')'" chance="100"/>
                </do_if>
              </do_if>
              
              <!-- ALWAYS update ship name to reflect current XP (even without level change) -->
              <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$newXP"/>
                <param name="level" value="$newSkillLevel"/>
                <param name="nameType" value="'trader'"/>
              </run_actions>
            </do_else>
          </do_else>
          
          <!-- Store the last trade data for this pilot -->
          <set_value name="global.$GT_Pilots.{$pilot}.$LastTrade" exact="$trade_data"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$LastTradeTime" exact="player.age"/>
        </do_if>
        <do_else>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3]  DIRECT XP: Pilot ' + $pilot.name + ' not found in GT system - ignoring XP award'" chance="100"/>
          </do_if>
        </do_else>
        <!-- Close outer guard (trade_data != null) -->
        </do_else>
      </actions>
    </cue>
    
    <!-- Ship Name Update Listener (for AI script signals) -->
    <!-- AI scripts cannot call libraries directly, so they signal and this cue forwards to the library -->
    <!-- Ship name refresh: handled by md.GT_Ship_Management.ListenForShipNameRefresh (GT_Refresh_Ship_Name + GT_Update_Ship_Name alias) -->

    
    <!-- Training Initiation - When pilot's ship docks -->
    <cue name="InitiateTraining" instantiate="true">
      <conditions>
        <event_object_docked object="player.entity"/>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$ship" exact="event.object"/>
        <set_value name="$station" exact="event.param"/>
        <set_value name="$pilot" exact="$ship.pilot"/>
        <set_value name="$mustTrainNow" exact="false"/>
        <do_if value="$useVanillaXPOnly">
          <set_value name="$pilot" exact="null"/>
        </do_if>
        <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
          <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$pilotTrainingGate">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="respect_hard_force" value="true"/>
          </run_actions>
          <set_value name="$mustTrainNow" exact="$pilotTrainingGate.$MustTrainNow"/>
        </do_if>
        
        <!-- Check if pilot needs training -->
        <do_if value="$pilot and global.$GT_Pilots.{$pilot}? and $mustTrainNow">
          <!-- Validate station type -->
          <set_value name="$validStation" exact="false"/>
          <do_all exact="global.$GT_Config.$Training.$ValidStationTypes.count" counter="$i">
            <do_if value="$station.macro.id? and ($station.macro.id.indexof.{global.$GT_Config.$Training.$ValidStationTypes.{$i}} != -1)">
              <set_value name="$validStation" exact="true"/>
              <break/>
            </do_if>
          </do_all>
          
          <do_if value="$validStation">
            <!-- ============================================================ -->
            <!-- Trading Academy override (FEATURE_FLEET_ACADEMY)              -->
            <!-- If the pilot enrolled via the Academy submenu the cost +      -->
            <!-- duration are pre-calculated by the Lua side and stamped on    -->
            <!-- $AcademyEnrollment. We trust those values here and skip the   -->
            <!-- normal skill_based / per-band ladder.                         -->
            <!-- ============================================================ -->
            <!-- Outer do_if (line 809) already verified global.$GT_Pilots.{$pilot}?; safe to dot in. -->
            <set_value name="$isAcademyEnrollment" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>

            <!-- Idempotency guard: HandleStartTraining is the canonical entry
                 point for AI-driven dock.train flows and runs after the ship
                 docks (GT_Start_Training is emitted post-dock in
                 order.dock.train.xml). InitiateTraining only fires when the
                 player avatar docks on a player-piloted trader; skip duplicate
                 cost+state work when HandleStartTraining already stamped
                 $CostPaid, and defer unpaid academy enrollments entirely. -->
            <set_value name="$alreadyProcessedByStart" exact="false"/>
            <do_if value="$isAcademyEnrollment and global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$CostPaid?">
              <set_value name="$alreadyProcessedByStart" exact="true"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] InitiateTraining: HandleStartTraining already processed academy enrollment for ' + $pilot.name + ' - skipping duplicate cost deduction and state writes.'" chance="100"/>
              </do_if>
            </do_if>

            <!-- Calculate training duration -->
            <do_if value="$isAcademyEnrollment">
              <set_value name="$duration" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Duration"/>
              <!-- Match against datatype.time so floats / long-fixed values
                   from the Lua blackboard are promoted too, not just ints. -->
              <do_if value="typeof $duration != datatype.time">
                <set_value name="$duration" exact="$duration * 1s"/>
              </do_if>
            </do_if>
            <do_else>
              <set_value name="$duration" exact="global.$GT_Config.$Training.$BaseDuration"/>
              
              <do_if value="global.$GT_Config.$Training.$DurationMode == 'skill_based'">
                <set_value name="$skillLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
                <set_value name="$duration" exact="$duration + ($skillLevel * global.$GT_Config.$Training.$SkillMultiplier)"/>
              </do_if>
              <do_elseif value="global.$GT_Config.$Training.$DurationMode == 'progressive'">
                <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                <set_value name="$duration" exact="$duration + (($blockedLevel - 1) * global.$GT_Config.$Training.$ProgressiveIncrement)"/>
              </do_elseif>
              
              <!-- CRITICAL FIX: Ensure duration stays as time type after calculation -->
              <do_if value="typeof $duration != datatype.time">
                <set_value name="$duration" exact="$duration * 1s"/>
              </do_if>
            </do_else>
            
            <!-- Calculate training license cost based on training level -->
            <set_value name="$trainingLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
            <set_value name="$trainingCost" exact="5000Cr"/>
            
            <do_if value="$isAcademyEnrollment">
              <!-- Academy enrollment: use the cost locked in at submenu time -->
              <set_value name="$trainingCost" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Cost"/>
            </do_if>
            <do_else>
              <!-- Set cost based on training level (natural ladder) -->
              <do_if value="$trainingLevel == 3">
                <set_value name="$trainingCost" exact="5000Cr"/>
              </do_if>
              <do_elseif value="$trainingLevel == 6">
                <set_value name="$trainingCost" exact="12000Cr"/>
              </do_elseif>
              <do_elseif value="$trainingLevel == 9">
                <set_value name="$trainingCost" exact="35000Cr"/>
              </do_elseif>
              <do_elseif value="$trainingLevel == 12">
                <set_value name="$trainingCost" exact="100000Cr"/>
              </do_elseif>
              <do_else>
                <!-- Fallback for any other level (shouldn't happen, but safety) -->
                <set_value name="$trainingCost" exact="5000Cr"/>
              </do_else>
            </do_else>
            
            <!-- Build a money-typed copy of $trainingCost. Natural ladder
                 already uses money literals (e.g. 5000Cr) and falls
                 through unchanged. Academy enrollment loaded a plain
                 centi-credits number from the Lua-written blackboard;
                 promote it via `n * 1Cr / 100` to preserve the magnitude
                 while attaching datatype.money so reward_player accepts
                 it. $trainingCost itself stays untouched because the
                 downstream debug/notification messages do `/100` math
                 against centi-credits-as-number. -->
            <set_value name="$trainingCostMoney" exact="$trainingCost"/>
            <do_if value="$isAcademyEnrollment and typeof $trainingCostMoney != datatype.money">
              <set_value name="$trainingCostMoney" exact="($trainingCost * 1Cr) / 100"/>
            </do_if>
            
            <!-- Check if player has enough money -->
            <set_value name="$playerMoney" exact="player.money"/>
            <set_value name="$canAffordTraining" exact="false"/>
            <do_if value="$playerMoney ge $trainingCostMoney">
              <set_value name="$canAffordTraining" exact="true"/>
            </do_if>
            
            <!-- Three-way chain: short-circuit when HandleStartTraining
                 already processed an academy enrollment, then the success
                 path, then the abort/insufficient-funds path. -->
            <do_if value="$alreadyProcessedByStart">
              <!-- No-op: HandleStartTraining is the source of truth for
                   academy enrollments. The debug log inside the
                   $alreadyProcessedByStart computation above is sufficient. -->
            </do_if>
            <do_elseif value="$canAffordTraining and $isAcademyEnrollment">
              <!-- Unpaid academy: HandleStartTraining owns payment + state. -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] InitiateTraining: deferring academy enrollment for ' + $pilot.name + ' to HandleStartTraining (post-dock canonical path)'" chance="100"/>
              </do_if>
            </do_elseif>
            <do_elseif value="$canAffordTraining">
              <!-- Deduct training cost from player account -->
              <reward_player money="-$trainingCostMoney"/>
              
              <!-- Training order will be created by AI handler upon GT_Training_Station_Found -->
              
              <!-- Mark training as started -->
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted" exact="player.age"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration" exact="$duration"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingStation" exact="$station"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingCost" exact="$trainingCost"/>
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_in_progress'"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt"/>
              
              <!-- Change to training name using configurable naming system -->
              <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
              
              <!-- Calculate current skill level for display -->
              <set_value name="$currentSkillLevel" exact="1"/>
              <do_all exact="15" counter="$skillLevelCheck">
                <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevelCheck}">
                  <set_value name="$currentSkillLevel" exact="$skillLevelCheck"/>
                </do_if>
              </do_all>
              
              <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="$currentXP"/>
                <param name="level" value="$currentSkillLevel"/>
                <param name="nameType" value="'training'"/>
              </run_actions>
              
              <!-- Show notification with cost info -->
              <do_if value="global.$GT_Config.$Notifications.$TrainingStarted">
                <set_value name="$message" exact="'Pilot ' + $pilot.name + ' started Level ' + $trainingLevel + ' training\n'"/>
                <set_value name="$message" exact="$message + 'Duration: ' + ($duration / 60) + ' minutes\n'"/>
                <set_value name="$message" exact="$message + 'Cost: ' + ($trainingCost / 100) + ' Cr'"/>
                <show_notification text="$message" timeout="8s" priority="6"/>

                <!-- Persist the same training start details to logbook (including cost). -->
                <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <do_if value="$logbookEnabled">
                  <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                    <param name="Message" value="$message"/>
                    <param name="Category" value="'upkeep'"/>
                    <param name="Title" value="'Training Started: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                    <param name="Object" value="$ship"/>
                    <param name="Interaction" value="'showonmap'"/>
                    <param name="Highlighted" value="false"/>
                    <param name="CheckGlobalSettings" value="false"/>
                  </run_actions>
                </do_if>
              </do_if>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Pilot ' + $pilot.name + ' started training for level ' + $trainingLevel + ' (duration: ' + $duration + ', cost: ' + ($trainingCost / 100) + ' Cr) (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
              </do_if>
            </do_elseif>
            <do_else>
              <!-- ============================================================ -->
              <!-- INSUFFICIENT FUNDS branch.                                   -->
              <!--                                                              -->
              <!-- Trading Academy enrollments are a one-shot player commitment -->
              <!-- (the cost was locked in at submenu time). If the player has  -->
              <!-- run out of money by the time the ship actually arrives at    -->
              <!-- the academy dock the course is CANCELED outright: no money   -->
              <!-- is deducted, all academy markers are wiped, the ship is      -->
              <!-- told to abort the dock.train order so it undocks and resumes -->
              <!-- normal trading, and the player has to re-enroll explicitly.  -->
              <!--                                                              -->
              <!-- Natural-ladder training keeps the existing retry-after-60s   -->
              <!-- behavior because the cost there is small and the pilot will  -->
              <!-- naturally try again on the next monitoring tick.             -->
              <!-- ============================================================ -->
              <do_if value="$isAcademyEnrollment">
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Trading Academy aborted for pilot ' + $pilot.name + ' at ' + $station.knownname + ' - insufficient funds at dock (required: ' + ($trainingCost / 100) + ' Cr, available: ' + ($playerMoney / 100) + ' Cr). Course canceled, no money deducted.'" chance="100"/>
                </do_if>

                <!-- Capture the requested level for messaging before we wipe the markers. -->
                <set_value name="$abortedTargetLevel" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Level"/>

                <!-- 1) Wipe academy commitment + transient training state. -->
                <remove_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingCost"/>

                <!-- 2) Drop the XP block so the pilot can resume trading. The
                     natural-training detector will re-set BlockedLevel on the
                     next XP tick if the pilot legitimately needs natural
                     training at their current XP-derived level. -->
                <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
                  <param name="pilot" value="$pilot"/>
                  <param name="clear_blocked_level" value="true"/>
                </run_actions>

                <!-- 3) Player notification + logbook entry. -->
                <show_notification text="{77000,9924}.[$pilot.name, $trainingCost / 100, $playerMoney / 100]" timeout="8s" priority="7"/>

                <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                  <param name="ship" value="$ship"/>
                </run_actions>
                <do_if value="$logbookEnabled">
                  <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                    <param name="Message"     value="{77000,9924}.[$pilot.name, $trainingCost / 100, $playerMoney / 100]"/>
                    <param name="Category"    value="'upkeep'"/>
                    <param name="Title"       value="'Trading Academy Aborted: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                    <param name="Object"      value="$ship"/>
                    <param name="Interaction" value="'showonmap'"/>
                    <param name="CheckGlobalSettings" value="false"/>
                  </run_actions>
                </do_if>

                <!-- 4) Refresh ship name back to the natural XP-derived rank
                     (no academy guard, no [TR]/[BL] prefix). -->
                <set_value name="$currentXP" exact="0"/>
                <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
                  <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
                </do_if>
                <set_value name="$displayLevel" exact="1"/>
                <do_all exact="15" counter="$skillLevelCheck">
                  <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevelCheck}">
                    <set_value name="$displayLevel" exact="$skillLevelCheck"/>
                  </do_if>
                </do_all>
                <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                  <param name="ship" value="$ship"/>
                  <param name="pilot" value="$pilot"/>
                  <param name="xp" value="$currentXP"/>
                  <param name="level" value="$displayLevel"/>
                  <param name="nameType" value="'trader'"/>
                </run_actions>

                <!-- 5) Break the dock.train AI wait so the ship undocks and
                     resumes its previous order. The ship-side wait listens
                     for GT_Abort_Training on `this.ship`; the AI then echoes
                     a player.galaxy abort which HandleAbortTraining picks up.
                     Because all academy markers are already cleared above,
                     HandleAbortTraining will simply refresh the ship name
                     against the natural XP-derived rank (idempotent with the
                     update we just did) and not re-block the pilot. -->
                <signal_objects object="$ship" param="'GT_Abort_Training'" param2="table[
                  $Pilot  = $pilot,
                  $Ship   = $ship,
                  $Reason = 'AcademyFundsAborted'
                ]"/>
              </do_if>
              <do_else>
              <!-- Player cannot afford natural training - same behavior as "no training station found" -->
              <!-- Temporarily clear XPBlocked to allow ship to trade, but keep BlockedLevel -->
              <!-- XP remains blocked because BlockedLevel is still set (XP system checks BlockedLevel) -->
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Training blocked for pilot ' + $pilot.name + ' - insufficient funds (required: ' + ($trainingCost / 100) + ' Cr, available: ' + ($playerMoney / 100) + ' Cr) - temporarily allowing trading. Will check again later.'" chance="100"/>
              </do_if>
              
              <!-- Write logbook message (same pattern as training station search failure) -->
              <set_value name="$blockedLevel" exact="@global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
              <set_value name="$logbookMessage" exact="null"/>
              
              <!-- Build logbook message -->
              <do_if value="$blockedLevel? and $blockedLevel gt 0">
                <set_value name="$logbookMessage" exact="'Commander,\n\nI am ready to begin my Level ' + $blockedLevel + ' training certification, but I cannot proceed due to insufficient funds.\n\nTRAINING COST: ' + ($trainingCost / 100) + ' Cr\nAVAILABLE FUNDS: ' + ($playerMoney / 100) + ' Cr\nSHORTFALL: ' + (($trainingCost - $playerMoney) / 100) + ' Cr\n\nI will proceed with trading operations as instructed, but I understand that I will not gain experience points until I can complete the required training.\n\nI will check again after my next trade run.\n\nRespectfully,\n' + $pilot.name + '\nAboard ' + $ship.knownname"/>
              </do_if>
              <do_else>
                <!-- Fallback message if BlockedLevel is missing -->
                <set_value name="$logbookMessage" exact="'Commander,\n\nI am ready to begin training, but I cannot proceed due to insufficient funds. I will proceed with trading operations, but I understand that I will not gain experience points until training can be completed.\n\nRespectfully,\n' + $pilot.name + '\nAboard ' + $ship.knownname"/>
              </do_else>
              
              <!-- Write logbook message if message was successfully constructed -->
              <do_if value="$logbookMessage? and $logbookMessage != null and $logbookMessage != ''">
                <!-- Check if logbook is enabled for this ship -->
                <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                  <param name="ship" value="$ship"/>
                </run_actions>
                
                <do_if value="$logbookEnabled">
                  <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                    <param name="Message" value="$logbookMessage"/>
                    <param name="Category" value="'upkeep'"/>
                    <param name="Title" value="'Training Blocked - Insufficient Funds: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                    <param name="Object" value="$ship"/>
                    <param name="Interaction" value="'showonmap'"/>
                    <param name="Highlighted" value="false"/>
                    <param name="CheckGlobalSettings" value="false"/>
                  </run_actions>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] Logbook message written for insufficient funds: ' + $pilot.name + ' (ship: ' + $ship.idcode + ', blocked level: ' + $blockedLevel + ', cost: ' + ($trainingCost / 100) + ' Cr)'" chance="100"/>
                  </do_if>
                </do_if>
                <do_else>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] Logbook message NOT written - logbook entries disabled for ship: ' + $ship.idcode" chance="100"/>
                  </do_if>
                </do_else>
              </do_if>
              
              <!-- Respect hard-force policy -->
              <set_value name="$hardForceTraining" exact="true"/>
              <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
                <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
              </do_if>
              <set_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt" exact="player.age + 60s"/>
              
              <do_if value="$hardForceTraining">
                <!-- Keep pilot force-blocked; retry training search later -->
                <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_unavailable_funds'"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] HardForceTraining active: keeping ' + $pilot.name + ' blocked after insufficient funds (next retry in 60s)'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <!-- Soft policy: allow trading, but keep blocked-level gate for XP -->
                <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_unavailable_funds'"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
                <!-- Keep BlockedLevel so we know what level training is needed when funds become available -->
                <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'insufficient_funds'" delay="1ms"/>
              </do_else>
              </do_else>
            </do_else>
          </do_if>
          <do_else>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Training station validation failed for pilot ' + $pilot.name + ' at ' + $station.knownname + ' (Ship ID: ' + $ship.idcode + ')'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>
    

    
    <!-- OLD CUES REMOVED IN PHASE 2: TrainingCompleted and TrainingInterrupted
         These have been replaced by ProcessTrainingEvents for instant event-driven processing -->
    
    <!-- PHASE 2 IMPROVEMENT: Event-Driven Training Completion Handler -->
    <!-- EVENT-DRIVEN: Listen for signal instead of polling -->
    <cue name="ProcessTrainingEvents" instantiate="true">
      <conditions>
        <event_cue_signalled cue="md.GT_XP_Training.ProcessTrainingEvents"/>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <do_if value="$useVanillaXPOnly and global.$GT_TrainingEventQueue?">
          <remove_value name="global.$GT_TrainingEventQueue"/>
        </do_if>
        
        <!-- Process all queued training events -->
        <do_if value="not $useVanillaXPOnly and global.$GT_TrainingEventQueue? and global.$GT_TrainingEventQueue.count gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] âš¡ Processing ' + global.$GT_TrainingEventQueue.count + ' training events instantly'" chance="100"/>
          </do_if>
          
          <do_while value="global.$GT_TrainingEventQueue.count gt 0">
            <!-- Get next event -->
            <set_value name="$event" exact="global.$GT_TrainingEventQueue.{1}"/>
            <remove_from_list name="global.$GT_TrainingEventQueue" exact="$event"/>
            
            <!-- Extract event data -->
            <set_value name="$ship" exact="$event.$ship"/>
            <set_value name="$pilot" exact="$event.$pilot"/>
            <set_value name="$eventType" exact="$event.$eventType"/>
            
            <!-- Process based on event type -->
            <do_if value="$eventType == 'training_completed'">
              <set_value name="$completedLevel" exact="$event.$completedLevel"/>
              <set_value name="$trainingStation" exact="$event.$trainingStation"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') ðŸŽ“ Training completion event received'" chance="100"/>
              </do_if>
              
              <do_if value="$pilot and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$XPBlocked?">
                <!-- Training completed! -->
                <set_value name="$shownLevelUpNotification" exact="false"/>
                <set_value name="$trainedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
                <append_to_list name="global.$GT_Pilots.{$pilot}.$TrainingCompleted" exact="$trainedLevel"/>
                
                <!-- Apply pending skill level increase if available -->
                <do_if value="global.$GT_Pilots.{$pilot}.$PendingSkillLevel?">
                  <set_value name="$pendingLevel" exact="global.$GT_Pilots.{$pilot}.$PendingSkillLevel"/>
                  
                  <!-- Now apply the skill level increase that was delayed (raise-only sync). -->
                  <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
                  <do_if value="$pendingLevel gt $vanillaMgmtLevel">
                    <set_skill entity="$pilot" type="skilltype.management" exact="$pendingLevel"/>
                  </do_if>
                  <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$pendingLevel"/>

                  <!-- Trading Academy + natural training: bump $XP to at least the
                       threshold for $pendingLevel so later helpers that recompute
                       level from XP (e.g. Initialize_Pilot_Data) do not roll the
                       stored $Level back down. For natural training the pilot
                       already has the XP so this is a no-op. For academy training
                       (XP=121 promoted to Lv.7 with threshold=1350) this is what
                       actually cements the new rank across pilot_change refreshes
                       triggered by the AI script restart after the ship undocks. -->
                  <do_if value="global.$GT_Config.$XP.$SkillThresholds.{$pendingLevel}?">
                    <set_value name="$levelThresholdXP" exact="global.$GT_Config.$XP.$SkillThresholds.{$pendingLevel}"/>
                    <set_value name="$currentStoredXP" exact="if global.$GT_Pilots.{$pilot}.$XP? then global.$GT_Pilots.{$pilot}.$XP else 0"/>
                    <do_if value="$currentStoredXP lt $levelThresholdXP">
                      <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="$levelThresholdXP"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Academy XP top-up: pilot ' + $pilot.name + ' XP raised from ' + $currentStoredXP + ' to ' + $levelThresholdXP + ' to match new Lv.' + $pendingLevel" chance="100"/>
                      </do_if>
                    </do_if>
                  </do_if>
                  
                  <!-- Update pilot skill proportionally: Management Level 15 (5 stars) Pilot Level 9 (3 stars) -->
                  <!-- Formula: pilot_level = (management_level * 9) / 15 -->
                  <!-- Never reduce pilot skill, only increase if target is higher -->
                  <set_value name="$currentPilotSkill" exact="0"/>
                  <do_if value="$pilot.skill.piloting?">
                    <set_value name="$currentPilotSkill" exact="@$pilot.skill.piloting"/>
                  </do_if>
                  <!-- Calculate target pilot skill level -->
                  <set_value name="$targetPilotLevel" exact="($pendingLevel * 9) / 15"/>
                  <do_if value="$targetPilotLevel lt 1">
                    <set_value name="$targetPilotLevel" exact="1"/>
                  </do_if>
                  <do_if value="$targetPilotLevel gt 9">
                    <set_value name="$targetPilotLevel" exact="9"/>
                  </do_if>
                  <!-- Only increase pilot skill if target is higher than current -->
                  <do_if value="$targetPilotLevel gt $currentPilotSkill">
                    <set_skill entity="$pilot" type="skilltype.piloting" exact="$targetPilotLevel"/>
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') âœˆï¸ Pilot skill increased from ' + $currentPilotSkill + ' to ' + $targetPilotLevel + ' (management: ' + $pendingLevel + ')'" chance="100"/>
                    </do_if>
                  </do_if>
                  
                  <!-- Calculate star rating for notification -->
                  <set_value name="$starRating" exact="'â­'"/>
                  <do_if value="$pendingLevel ge 13">
                    <set_value name="$starRating" exact="'â­â­â­â­â­'"/>
                  </do_if>
                  <do_elseif value="$pendingLevel ge 10">
                    <set_value name="$starRating" exact="'â­â­â­â­'"/>
                  </do_elseif>
                  <do_elseif value="$pendingLevel ge 7">
                    <set_value name="$starRating" exact="'â­â­â­'"/>
                  </do_elseif>
                  <do_elseif value="$pendingLevel ge 4">
                    <set_value name="$starRating" exact="'â­â­'"/>
                  </do_elseif>
                  
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') â­ Pilot ' + $pilot.name + ' skill level increased to ' + $pendingLevel + ' (' + $starRating + ') after training completion!'" chance="100"/>
                  </do_if>
                  
                  <!-- Show combined level-up + XP unlocked notification (replaces redundant separate messages) -->
                  <do_if value="global.$GT_Config.$Notifications.$LevelUp or global.$GT_Config.$Notifications.$TrainingCompleted">
                    <set_value name="$levelUpMessage" exact="{77000,2005}.[$pilot.name, $pendingLevel, $trainingStation.knownname]"/>
                    <set_value name="$greenColor" exact="'\033#FF00CC00#'"/>
                    <set_value name="$colorReset" exact="'\033X'"/>
                    <set_value name="$levelUpMessageColored" exact="$greenColor + $levelUpMessage + $colorReset"/>
                    <show_notification text="$levelUpMessageColored" timeout="8s"/>
                    <set_value name="$shownLevelUpNotification" exact="true"/>
                    <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                      <param name="Message" value="$levelUpMessage"/>
                      <param name="Category" value="'news'"/>
                      <param name="Title" value="'Level Up: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                      <param name="Object" value="$ship"/>
                      <param name="Interaction" value="'showonmap'"/>
                      <param name="CheckGlobalSettings" value="false"/>
                    </run_actions>
                  </do_if>
                  <do_else>
                    <set_value name="$shownLevelUpNotification" exact="true"/>
                  </do_else>
                  
                  <!-- Clean up pending skill level -->
                  <remove_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel"/>
                  
                  <set_value name="$currentSkillLevel" exact="$pendingLevel"/>
                </do_if>
                <do_else>
                  <!-- No pending skill level - calculate current level -->
                  <set_value name="$currentSkillLevel" exact="1"/>
                  <do_all exact="15" counter="$skillLevel">
                    <do_if value="global.$GT_Pilots.{$pilot}.$XP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                      <set_value name="$currentSkillLevel" exact="$skillLevel"/>
                    </do_if>
                  </do_all>
                </do_else>
                
                <!-- PHASE 2 IMPROVEMENT: Award any blocked XP that accumulated during training -->
                <do_if value="global.$GT_Pilots.{$pilot}.$BlockedXPPending?">
                  <set_value name="$blockedXP" exact="global.$GT_Pilots.{$pilot}.$BlockedXPPending"/>
                  <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                    <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Awarding blocked XP: ' + $blockedXP + ' XP to pilot ' + $pilot.name + ' after training completion'" chance="100"/>
                  </do_if>
                  
                  <!-- Award the blocked XP immediately -->
                  <set_value name="$preTrainingXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
                  <set_value name="$newTotalXP" exact="$preTrainingXP + $blockedXP"/>
                  <set_value name="global.$GT_Pilots.{$pilot}.$XP" exact="$newTotalXP"/>
                  <set_value name="global.$GT_SessionStats.$XPGained" exact="global.$GT_SessionStats.$XPGained + $blockedXP"/>
                  
                  <!-- Check if blocked XP causes additional skill level increases -->
                  <set_value name="$postTrainingSkillLevel" exact="1"/>
                  <do_all exact="15" counter="$skillLevel">
                    <do_if value="$newTotalXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                      <set_value name="$postTrainingSkillLevel" exact="$skillLevel"/>
                    </do_if>
                  </do_all>
                  
                  <!-- Update skill level if blocked XP caused additional increases -->
                  <do_if value="$postTrainingSkillLevel gt $currentSkillLevel">
                    <set_value name="$vanillaMgmtLevel" exact="if $pilot.skill.management? then $pilot.skill.management else 0"/>
                    <do_if value="$postTrainingSkillLevel gt $vanillaMgmtLevel">
                      <set_skill entity="$pilot" type="skilltype.management" exact="$postTrainingSkillLevel"/>
                    </do_if>
                    <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$postTrainingSkillLevel"/>
                    <set_value name="$currentSkillLevel" exact="$postTrainingSkillLevel"/>
                    
                    <!-- Update pilot skill proportionally: Management Level 15 (5 stars) Pilot Level 9 (3 stars) -->
                    <!-- Formula: pilot_level = (management_level * 9) / 15 -->
                    <!-- Never reduce pilot skill, only increase if target is higher -->
                    <set_value name="$currentPilotSkill" exact="0"/>
                    <do_if value="$pilot.skill.piloting?">
                      <set_value name="$currentPilotSkill" exact="@$pilot.skill.piloting"/>
                    </do_if>
                    <!-- Calculate target pilot skill level -->
                    <set_value name="$targetPilotLevel" exact="($postTrainingSkillLevel * 9) / 15"/>
                    <do_if value="$targetPilotLevel lt 1">
                      <set_value name="$targetPilotLevel" exact="1"/>
                    </do_if>
                    <do_if value="$targetPilotLevel gt 9">
                      <set_value name="$targetPilotLevel" exact="9"/>
                    </do_if>
                    <!-- Only increase pilot skill if target is higher than current -->
                    <do_if value="$targetPilotLevel gt $currentPilotSkill">
                      <set_skill entity="$pilot" type="skilltype.piloting" exact="$targetPilotLevel"/>
                      <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                        <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') âœˆï¸ Pilot skill increased from ' + $currentPilotSkill + ' to ' + $targetPilotLevel + ' (management: ' + $postTrainingSkillLevel + ')'" chance="100"/>
                      </do_if>
                    </do_if>
                    
                    <!-- Calculate new star rating -->
                    <set_value name="$newStarRating" exact="($postTrainingSkillLevel / 3)i"/>
                    <do_if value="$newStarRating gt 5">
                      <set_value name="$newStarRating" exact="5"/>
                    </do_if>
                    
                    <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                      <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') â­ Blocked XP caused additional skill increase to level ' + $postTrainingSkillLevel + ' (' + $newStarRating + ' stars)!'" chance="100"/>
                    </do_if>
                    
                    <!-- Notify player about bonus level increases -->
                    <do_if value="global.$GT_Config.$Notifications.$LevelUp">
                      <set_value name="$bonusMessage" exact="'Pilot ' + $pilot.name + ' gained additional skill levels from blocked XP!\nNow at Level ' + $postTrainingSkillLevel + ' (' + $newStarRating + ' stars)!'"/>
                      <set_value name="$greenColor" exact="'\033#FF00CC00#'"/>
                      <set_value name="$colorReset" exact="'\033X'"/>
                      <set_value name="$bonusMessageColored" exact="$greenColor + $bonusMessage + $colorReset"/>
                      <show_notification text="$bonusMessageColored" timeout="8s"/>
                      <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                        <param name="Message" value="$bonusMessage"/>
                        <param name="Category" value="'news'"/>
                        <param name="Title" value="'Bonus Level Up: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                        <param name="Object" value="$ship"/>
                        <param name="Interaction" value="'showonmap'"/>
                        <param name="CheckGlobalSettings" value="false"/>
                      </run_actions>
                    </do_if>
                  </do_if>
                  
                  <!-- Clean up blocked XP -->
                  <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedXPPending"/>
                  
                  <!-- Enhanced completion notification with XP info -->
                  <do_if value="global.$GT_Config.$Notifications.$TrainingCompleted">
                    <set_value name="$enhancedMessage" exact="'Pilot ' + $pilot.name + ' completed Level ' + $trainedLevel + ' training!\n'"/>
                    <set_value name="$enhancedMessage" exact="$enhancedMessage + 'Awarded ' + $blockedXP + ' blocked XP. Total XP: ' + $newTotalXP"/>
                    <show_notification text="$enhancedMessage" timeout="10s" priority="7"/>
                  </do_if>
                </do_if>
                
                <!-- Unblock XP progression -->
                <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
                  <param name="pilot" value="$pilot"/>
                  <param name="clear_blocked_level" value="true"/>
                </run_actions>
                <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'active'"/>
                
                <!-- Update ship name to match current skill level (new format) -->
                <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="@global.$GT_Pilots.{$pilot}.$XP"/>
                <param name="level" value="$currentSkillLevel"/>
                <param name="nameType" value="'trader'"/>
              </run_actions>
                
                <!-- Update ship modifications after training completion -->
                <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
                  $Ship = $ship,
                  $pilot = $pilot,
                  $updateType = 'training_completion'
                ]"/>
                
                <!-- Clean up training data -->
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
                <!-- Trading Academy: clear enrollment marker on success -->
                <remove_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment"/>
                
                <!-- Show completion notification (only when not already shown as combined level-up message) -->
                <do_if value="global.$GT_Config.$Notifications.$TrainingCompleted and not $shownLevelUpNotification?">
                  <set_value name="$message" exact="{77000,2007}.[$pilot.name, $trainedLevel, $trainingStation.knownname]"/>
                  <set_value name="$greenColor" exact="'\033#FF00CC00#'"/>
                  <set_value name="$colorReset" exact="'\033X'"/>
                  <set_value name="$messageColored" exact="$greenColor + $message + $colorReset"/>
                  <show_notification text="$messageColored" timeout="8s"/>
                </do_if>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Pilot ' + $pilot.name + ' completed Level ' + $trainedLevel + ' training - XP progression unlocked'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ')  Training completion event received but pilot not blocked or missing'" chance="100"/>
                </do_if>
              </do_else>
              
            </do_if>
            <do_elseif value="$eventType == 'training_interrupted'">
              <set_value name="$interruptedLevel" exact="$event.$interruptedLevel"/>
              <set_value name="$trainingStation" exact="$event.$trainingStation"/>
              
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ')  Training interruption event received'" chance="100"/>
              </do_if>
              
              <do_if value="$pilot and global.$GT_Pilots.{$pilot}?">
                <!-- Clean up training data but keep XP block -->
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
                <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
                <!-- Trading Academy: clear enrollment + pending promotion on interrupt
                     (no refund: cost was deducted on dock, but academy override is no longer in effect). -->
                <remove_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment"/>
                <do_if value="global.$GT_Pilots.{$pilot}.$PendingSkillLevel?">
                  <remove_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel"/>
                </do_if>
                <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'needs_training'"/>
                
                <!-- Restore ship name if possible -->
                <do_if value="global.$GT_Pilots.{$pilot}.$OriginalShipName?">
                  <set_value name="$currentSkillLevel" exact="1"/>
                  <do_all exact="15" counter="$skillLevel">
                    <do_if value="global.$GT_Pilots.{$pilot}.$XP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
                      <set_value name="$currentSkillLevel" exact="$skillLevel"/>
                    </do_if>
                  </do_all>
                  
                  <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
                <param name="ship" value="$ship"/>
                <param name="pilot" value="$pilot"/>
                <param name="xp" value="@global.$GT_Pilots.{$pilot}.$XP"/>
                <param name="level" value="$currentSkillLevel"/>
                <param name="nameType" value="'trader'"/>
              </run_actions>
                </do_if>
                
                <!-- Show interruption notification -->
                <do_if value="global.$GT_Config.$Notifications.$TrainingStarted">
                  <show_notification text="'Training interrupted for ' + $pilot.name + '!\nPilot still needs to complete training to unlock XP progression.'" timeout="6s" priority="5"/>
                </do_if>
                
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ')  Training interrupted for pilot ' + $pilot.name" chance="100"/>
                </do_if>
              </do_if>
            </do_elseif>
          </do_while>
        </do_if>
      </actions>
    </cue>
    
    <!-- Legacy Training Completion Check - REMOVED: Pure event-driven system -->
    <!-- Training Signal Handlers -->
    
    <!-- Training Script Starting Signal Handler -->
    <cue name="HandleTrainingScriptStarting" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Training_Script_Starting'" comment="Handle training script startup"/>
      </conditions>
      <actions>
        <set_value name="$startData" exact="event.param2"/>
        <set_value name="$ship" exact="$startData.$Ship"/>
        <set_value name="$pilot" exact="$startData.$Pilot"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Training script starting signal received for ' + $ship.knownname" chance="100"/>
        </do_if>
        
        <!-- Initialize training if needed -->
        <do_if value="$pilot and not global.$GT_Pilots.{$pilot}?">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Pilot ' + $pilot.name + ' not in registry during training start - this should not happen'" chance="100"/>
          </do_if>
          <!-- Re-register pilot with basic data if missing -->
          <signal_objects object="player.galaxy" param="'GT_AI_Started'" param2="table[
            $Ship = $ship,
            $Config = table[
              $allowillegal = false,
              $debuglevel = 2,
              $autotraining = true
            ]
          ]"/>
        </do_if>
      </actions>
    </cue>

    <!-- Check Training Required Signal Handler -->
    <cue name="HandleCheckTrainingRequired" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Check_Training_Required'" comment="Handle training requirement check"/>
      </conditions>
      <actions>
        <set_value name="$checkData" exact="event.param2"/>
        <set_value name="$ship" exact="$checkData.$Ship"/>
        <set_value name="$pilot" exact="$checkData.$Pilot"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Training requirement check for ' + $pilot.name + ' on ' + $ship.knownname" chance="100"/>
        </do_if>
        
        <!-- Check if training is required and respond -->
        <set_value name="$trainingRequired" exact="false"/>
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$pilotTrainingGate">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="respect_hard_force" value="true"/>
          </run_actions>
          <set_value name="$trainingRequired" exact="$pilotTrainingGate.$MustTrainNow"/>
        </do_if>
        
        <!-- Signal back to AI script with result -->
        <signal_objects object="player.galaxy" param="'GT_Training_Check_Result'" param2="table[
          $Ship = $ship,
          $Pilot = $pilot,
          $TrainingRequired = $trainingRequired,
          $BlockedLevel = @global.$GT_Pilots.{$pilot}.$BlockedLevel
        ]"/>
      </actions>
    </cue>

    <!-- Start Training Signal Handler.

         Fires when order.dock.train.xml signals 'GT_Start_Training' to
         player.galaxy after the ship has successfully docked at the training
         station. This is the CANONICAL entry point for both NPC trader
         training and Trading Academy enrollments because the AI script always
         emits this signal post-dock. The sibling InitiateTraining cue only
         fires for player.entity dock events (i.e. the player piloting the
         trader themselves) and treats this cue as authoritative when a marker
         indicates HandleStartTraining already processed the academy course. -->
    <cue name="HandleStartTraining" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Start_Training'" comment="Handle training start request"/>
      </conditions>
      <actions>
        <set_value name="$trainingData" exact="event.param2"/>
        <set_value name="$ship" exact="$trainingData.$Ship"/>
        <set_value name="$pilot" exact="$trainingData.$Pilot"/>
        <set_value name="$station" exact="$trainingData.$TrainingStation"/>
        <set_value name="$level" exact="$trainingData.$TrainingLevel"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Start training signal received for ' + $pilot.name + ' at level ' + $level" chance="100"/>
        </do_if>
        
        <!-- Process training start -->
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <!-- Trading Academy enrollment uses the cost + duration that Lua
               locked in at submenu time (scaled by current level). Natural
               training falls through to the legacy ladder formula. -->
          <set_value name="$isAcademyEnrollment" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>
          
          <!-- ============================================================ -->
          <!-- Resolve training duration                                    -->
          <!-- ============================================================ -->
          <do_if value="$isAcademyEnrollment">
            <set_value name="$duration" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Duration"/>
            <!-- Lua wrote the locked duration as a plain number (seconds);
                 promote it back to a time type so the AI <wait> uses the
                 right unit. Match against datatype.time (vanilla pattern) so
                 floats / long-fixed values are caught too, not just integers. -->
            <do_if value="typeof $duration != datatype.time">
              <set_value name="$duration" exact="$duration * 1s"/>
            </do_if>
          </do_if>
          <do_else>
            <set_value name="$duration" exact="global.$GT_Config.$Training.$BaseDuration"/>
            
            <do_if value="global.$GT_Config.$Training.$DurationMode == 'skill_based'">
              <set_value name="$skillLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
              <set_value name="$duration" exact="$duration + ($skillLevel * global.$GT_Config.$Training.$SkillMultiplier)"/>
            </do_if>
            <do_elseif value="global.$GT_Config.$Training.$DurationMode == 'progressive'">
              <set_value name="$duration" exact="$duration + (($level - 1) * global.$GT_Config.$Training.$ProgressiveIncrement)"/>
            </do_elseif>
            
            <do_if value="typeof $duration != datatype.time">
              <set_value name="$duration" exact="$duration * 1s"/>
            </do_if>
          </do_else>
          
          <!-- ============================================================ -->
          <!-- Resolve training cost                                        -->
          <!-- Academy: locked-in cost from Lua (already scaled).           -->
          <!-- Natural ladder: per-band table; cost is deducted by the      -->
          <!-- legacy InitiateTraining path on player-avatar docking and    -->
          <!-- is therefore left at zero here to avoid double-charging.     -->
          <!-- ============================================================ -->
          <set_value name="$trainingCost" exact="0Cr"/>
          <do_if value="$isAcademyEnrollment">
            <set_value name="$trainingCost" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$Cost"/>
          </do_if>
          
          <!-- Save/load + dock.train retry: resume in-flight session instead of
               re-charging, re-running the funds gate, or resetting the timer. -->
          <set_value name="$resumeMidTraining" exact="false"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$TrainingState? and global.$GT_Pilots.{$pilot}.$TrainingState == 'training_in_progress'">
            <do_if value="$isAcademyEnrollment and global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$CostPaid?">
              <set_value name="$resumeMidTraining" exact="true"/>
            </do_if>
            <do_elseif value="global.$GT_Pilots.{$pilot}.$TrainingStarted? and global.$GT_Pilots.{$pilot}.$TrainingDuration?">
              <set_value name="$resumeMidTraining" exact="true"/>
            </do_elseif>
          </do_if>
          <do_if value="$resumeMidTraining">
            <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
              <param name="pilot" value="$pilot"/>
              <param name="level" value="$level"/>
              <param name="set_xpblocked" value="true"/>
            </run_actions>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_in_progress'"/>
            <set_value name="$fullDuration" exact="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
            <do_if value="typeof $fullDuration != datatype.time">
              <set_value name="$fullDuration" exact="$fullDuration * 1s"/>
            </do_if>
            <set_value name="$elapsedTraining" exact="player.age - global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
            <set_value name="$remainingTraining" exact="$fullDuration - $elapsedTraining"/>
            <do_if value="$remainingTraining le 0s">
              <set_value name="$remainingTraining" exact="1s"/>
            </do_if>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration" exact="$remainingTraining"/>
            <do_if value="not global.$GT_Pilots.{$pilot}.$TrainingStation?">
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingStation" exact="$station"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] HandleStartTraining: resumed in-flight training for ' + $pilot.name + ' (remaining ' + ($remainingTraining / 1s) + 's)'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
          
          <!-- ============================================================ -->
          <!-- Insufficient-funds abort (academy only).                     -->
          <!--                                                              -->
          <!-- The academy cost was promised by the player at submenu time  -->
          <!-- but is only deducted here, when the ship actually arrives    -->
          <!-- at the academy dock. If the player has spent the credits in  -->
          <!-- the meantime the course is canceled outright: no money is    -->
          <!-- deducted, every academy marker is wiped, the ship is told    -->
          <!-- to abort the dock.train wait so it undocks and resumes its   -->
          <!-- previous order, and the player must re-enroll explicitly.    -->
          <!-- Mirrors the abort flow in InitiateTraining for the rare      -->
          <!-- case where the player happens to pilot the trader itself.    -->
          <!-- Skipped entirely when $CostPaid is already set (paid course  -->
          <!-- or save/load mid-timer resume).                              -->
          <!-- ============================================================ -->
          <set_value name="$academyAlreadyPaid" exact="false"/>
          <do_if value="$isAcademyEnrollment and global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$CostPaid?">
            <set_value name="$academyAlreadyPaid" exact="true"/>
          </do_if>
          <set_value name="$canAffordTraining" exact="true"/>
          <do_if value="$isAcademyEnrollment and not $academyAlreadyPaid">
            <set_value name="$trainingCostMoney" exact="($trainingCost * 1Cr) / 100"/>
            <do_if value="player.money lt $trainingCostMoney">
              <set_value name="$canAffordTraining" exact="false"/>
            </do_if>
          </do_if>
          
          <do_if value="$isAcademyEnrollment and not $canAffordTraining">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Trading Academy aborted in HandleStartTraining for pilot ' + $pilot.name + ' - insufficient funds at dock (required: ' + ($trainingCost / 100) + ' Cr, available: ' + (player.money / 100) + ' Cr). Course canceled, no money deducted.'" chance="100"/>
            </do_if>
            
            <!-- Wipe academy commitment + transient training state. -->
            <remove_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$PendingSkillLevel"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingCost"/>
            
            <!-- Drop the XP block so the pilot can resume trading. The
                 natural-training detector will re-set BlockedLevel on the
                 next XP tick if the pilot legitimately needs natural
                 training at their current XP-derived level. -->
            <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
              <param name="pilot" value="$pilot"/>
              <param name="clear_blocked_level" value="true"/>
            </run_actions>
            
            <!-- Player notification + logbook entry. -->
            <show_notification text="{77000,9924}.[$pilot.name, $trainingCost / 100, player.money / 100]" timeout="8s" priority="7"/>
            
            <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
              <param name="ship" value="$ship"/>
            </run_actions>
            <do_if value="$logbookEnabled">
              <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                <param name="Message"     value="{77000,9924}.[$pilot.name, $trainingCost / 100, player.money / 100]"/>
                <param name="Category"    value="'upkeep'"/>
                <param name="Title"       value="'Trading Academy Aborted: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                <param name="Object"      value="$ship"/>
                <param name="Interaction" value="'showonmap'"/>
                <param name="CheckGlobalSettings" value="false"/>
              </run_actions>
            </do_if>
            
            <!-- Refresh ship name to the natural XP-derived rank. -->
            <set_value name="$currentXP_abort" exact="0"/>
            <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
              <set_value name="$currentXP_abort" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            </do_if>
            <set_value name="$displayLevel_abort" exact="1"/>
            <do_all exact="15" counter="$skillLevelCheck">
              <do_if value="$currentXP_abort ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevelCheck}">
                <set_value name="$displayLevel_abort" exact="$skillLevelCheck"/>
              </do_if>
            </do_all>
            <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="xp" value="$currentXP_abort"/>
              <param name="level" value="$displayLevel_abort"/>
              <param name="nameType" value="'trader'"/>
            </run_actions>
            
            <!-- Break the dock.train AI wait so the ship undocks and resumes
                 its previous order. The ship-side wait listens for
                 GT_Abort_Training on `this.ship`. -->
            <signal_objects object="$ship" param="'GT_Abort_Training'" param2="table[
              $Pilot  = $pilot,
              $Ship   = $ship,
              $Reason = 'AcademyFundsAborted'
            ]"/>
          </do_if>
          <do_else>
            <!-- ========================================================== -->
            <!-- Sufficient funds (or natural training): proceed normally.  -->
            <!-- ========================================================== -->
            
            <!-- Deduct the academy fee here, on successful dock, so the player
                 only pays once the course is committed at the station. Mark
                 the enrollment as paid so the sibling InitiateTraining cue
                 (player-avatar dock case) does not deduct a second time.
                 Skip payment when $CostPaid is already set (save/load retry or
                 legacy saves that were charged before the post-dock fix).
                 
                 Lua wrote $AcademyEnrollment.$Cost as a plain number in
                 centi-credits, but reward_player demands a money-typed
                 value. Build a money-typed local without mutating
                 $trainingCost (downstream debug/notification messages still
                 expect the centi-credits-as-number form for ` / 100` math).
                 The expression `n * 1Cr / 100` keeps the same numerical
                 magnitude but attaches datatype.money. -->
            <do_if value="$isAcademyEnrollment">
              <set_value name="$academyAlreadyPaid" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$CostPaid?"/>
              <do_if value="not $academyAlreadyPaid">
                <set_value name="$trainingCostMoney" exact="($trainingCost * 1Cr) / 100"/>
                <reward_player money="-$trainingCostMoney"/>
                <set_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment.$CostPaid" exact="true"/>
                <set_value name="global.$GT_Pilots.{$pilot}.$TrainingCost" exact="$trainingCostMoney"/>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] HandleStartTraining: academy fee already paid for ' + $pilot.name + ' - skipping duplicate deduction'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted" exact="player.age"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration" exact="$duration"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingStation" exact="$station"/>
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_in_progress'"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$ManualTrainingRequested"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt"/>
            <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
              <param name="pilot" value="$pilot"/>
              <param name="level" value="$level"/>
              <param name="set_xpblocked" value="true"/>
            </run_actions>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Training started for ' + $pilot.name + ' - Level ' + $level + (if $isAcademyEnrollment then ' (ACADEMY)' else '') + ', Duration: ' + ($duration / 60s) + ' minutes, Cost: ' + ($trainingCost / 100) + ' Cr'" chance="100"/>
            </do_if>
            
            <!-- Update ship name to show training status -->
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            
            <!-- Trading Academy guard: $level here is the future *target*
                 rank (e.g. Lvl 7 for a Lvl 5 pilot). The pilot has not
                 actually earned that rank yet, so the visible "Lv.X" suffix
                 in the ship name must keep showing the current XP-derived
                 rank until the training course completes. Without this
                 guard the ship would flip to "(Supplier Lv.7)" the instant
                 DockAndTrain starts. -->
            <set_value name="$isAcademyPending" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>
            <set_value name="$displayLevel" exact="$level"/>
            <do_if value="$isAcademyPending">
              <set_value name="$displayLevel" exact="1"/>
              <do_all exact="15" counter="$skillLevelCheck">
                <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevelCheck}">
                  <set_value name="$displayLevel" exact="$skillLevelCheck"/>
                </do_if>
              </do_all>
            </do_if>
            
            <!-- Rank title is calculated internally by Update_Ship_Name from level -->
            <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="xp" value="$currentXP"/>
              <param name="level" value="$displayLevel"/>
              <param name="nameType" value="'training'"/>
            </run_actions>
          </do_else>
          </do_else>
        </do_if>
      </actions>
    </cue>

    <!-- Abort Training Signal Handler -->
    <cue name="HandleAbortTraining" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Abort_Training'" comment="Handle training abortion"/>
      </conditions>
      <actions>
        <set_value name="$abortData" exact="event.param2"/>
        <set_value name="$ship" exact="$abortData.$Ship"/>
        <set_value name="$pilot" exact="$abortData.$Pilot"/>
        <set_value name="$reason" exact="$abortData.$Reason"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Training abort signal received for ' + $pilot.name + ': ' + $reason" chance="100"/>
        </do_if>

        <!-- Drop stale DockAndTrain orders so a failed attempt cannot tight-loop
             on component.{0x0L} destination refs (order.dock.train also cancels,
             but MD cleanup covers race/aborted paths). -->
        <do_if value="$ship? and $ship.exists and $ship.orders? and ($reason == 'Docking failed' or $reason == 'Invalid destination')">
          <do_all exact="$ship.orders.count" counter="$toi">
            <do_if value="@$ship.orders.{$toi}.id == 'DockAndTrain'">
              <cancel_order order="$ship.orders.{$toi}"/>
              <break/>
            </do_if>
          </do_all>
        </do_if>
        
        <!-- Process training abortion -->
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <!-- HandleStartTraining already wiped academy markers, unblocked the
               pilot, renamed the ship, and echoed this abort to break the
               dock.train wait. Re-running blocked-state cleanup here would
               crash on missing $BlockedLevel and wrongly re-block the pilot. -->
          <do_if value="$reason == 'AcademyFundsAborted'">
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Training abort echo ignored for ' + $pilot.name + ' (AcademyFundsAborted already handled upstream)'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
          <!-- Detect academy enrollment for the display-level guard further
               below AND to decide whether enrollment markers should survive
               this abort. Trading Academy enrollment markers
               ($AcademyEnrollment / $PendingSkillLevel) MUST persist across
               transient dock.train aborts ('Docking failed',
               'Training interrupted', 'Training order aborted') because the
               retry loop in HandleTrainingNeeded re-dispatches DockAndTrain
               and the second HandleStartTraining call would otherwise miss
               the academy guard and pump the ship rank to the target level
               (e.g. Lv.7) before the course has actually completed. The
               markers are cleared by HandleCompleteTraining on success, by
               HandleAcademyCourseChosen when the player overrides with a new
               course, and by Handle_Pilot_Removed on pilot reassignment. -->
          <set_value name="$isAcademyPending" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>

          <!-- Clean up transient per-attempt training data but keep XP block -->
          <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
          <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>

          <set_value name="$currentXP" exact="0"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
          </do_if>
          <set_value name="$blockedLevel" exact="@global.$GT_Pilots.{$pilot}.$BlockedLevel"/>

          <do_if value="$blockedLevel? and $blockedLevel gt 0">
            <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'needs_training'"/>

            <!-- Trading Academy guard: $blockedLevel is the future *target*
                 rank, not yet earned. While the academy enrollment is still
                 pending the visible rank must keep showing the current
                 XP-derived level until the course actually completes. -->
            <set_value name="$displayLevel" exact="$blockedLevel"/>
            <do_if value="$isAcademyPending">
              <set_value name="$displayLevel" exact="1"/>
              <do_all exact="15" counter="$skillLevelCheck">
                <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevelCheck}">
                  <set_value name="$displayLevel" exact="$skillLevelCheck"/>
                </do_if>
              </do_all>
            </do_if>

            <!-- Rank title is calculated internally by Update_Ship_Name from level -->
            <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="xp" value="$currentXP"/>
              <param name="level" value="$displayLevel"/>
              <param name="nameType" value="'blocked'"/>
            </run_actions>

            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Training aborted for ' + $pilot.name + ' - pilot still blocked, ship renamed to show blocked status'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Pilot registry exists but $BlockedLevel is missing (e.g. race
                 with upstream clear). Refresh trader name from XP only. -->
            <set_value name="$displayLevel" exact="1"/>
            <do_all exact="15" counter="$skillLevelCheck">
              <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevelCheck}">
                <set_value name="$displayLevel" exact="$skillLevelCheck"/>
              </do_if>
            </do_all>
            <run_actions ref="md.GT_Ship_Management.Update_Ship_Name">
              <param name="ship" value="$ship"/>
              <param name="pilot" value="$pilot"/>
              <param name="xp" value="$currentXP"/>
              <param name="level" value="$displayLevel"/>
              <param name="nameType" value="'trader'"/>
            </run_actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] Training aborted for ' + $pilot.name + ' - no BlockedLevel on registry entry, refreshed trader name only'" chance="100"/>
            </do_if>
          </do_else>
          </do_else>
        </do_if>
      </actions>
    </cue>

    <!-- Complete Training Signal Handler -->
    <cue name="HandleCompleteTraining" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Complete_Training'" comment="Handle training completion"/>
      </conditions>
      <actions>
        <set_value name="$completionData" exact="event.param2"/>
        <set_value name="$ship" exact="$completionData.$Ship"/>
        <set_value name="$pilot" exact="$completionData.$Pilot"/>
        <set_value name="$completedLevel" exact="$completionData.$Level"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Training completion signal received for ' + $pilot.name + ' at level ' + $completedLevel" chance="100"/>
        </do_if>
        
        <!-- Idempotency guard: ignore duplicate completion signals in a short window -->
        <set_value name="$isDuplicateCompletion" exact="false"/>
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$LastTrainingCompletionLevel? and global.$GT_Pilots.{$pilot}.$LastTrainingCompletionAt?">
          <do_if value="global.$GT_Pilots.{$pilot}.$LastTrainingCompletionLevel == $completedLevel and (player.age - global.$GT_Pilots.{$pilot}.$LastTrainingCompletionAt) lt 2s">
            <set_value name="$isDuplicateCompletion" exact="true"/>
          </do_if>
        </do_if>
        <do_if value="$isDuplicateCompletion">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Duplicate training completion signal ignored for ' + $pilot.name + ' (level ' + $completedLevel + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <do_if value="global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="global.$GT_Pilots.{$pilot}.$LastTrainingCompletionAt" exact="player.age"/>
          <set_value name="global.$GT_Pilots.{$pilot}.$LastTrainingCompletionLevel" exact="$completedLevel"/>
        </do_if>
        
        <do_if value="not $isDuplicateCompletion">
          <!-- Add to training event queue for processing -->
          <!-- SIMPLIFIED: Initialization guarantees global.$GT_TrainingEventQueue exists -->
          <append_to_list name="global.$GT_TrainingEventQueue" exact="table[
            $ship = $ship,
            $pilot = $pilot,
            $completedLevel = $completedLevel,
            $trainingStation = @global.$GT_Pilots.{$pilot}.$TrainingStation,
            $timestamp = player.age,
            $eventType = 'training_completed'
          ]"/>
          
          <!-- EVENT-DRIVEN: Signal MD cue directly (no polling needed) -->
          <signal_cue_instantly cue="md.GT_XP_Training.ProcessTrainingEvents"/>
          
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Training completion added to event queue for processing'" chance="100"/>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Training Needed Signal Handler -->
    <cue name="HandleTrainingNeeded" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Training_Needed'" comment="Handle training needed notification"/>
      </conditions>
      <actions>
        <set_value name="$needData" exact="event.param2"/>
        <set_value name="$ship" exact="$needData.$Ship"/>
        <set_value name="$pilot" exact="$needData.$Pilot"/>
        
        <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
          <debug_text text="'[GalaxyTrader MK3] Training needed signal received for ' + $pilot.name" chance="100"/>
        </do_if>
        
        <!-- Guard: process training when mandatory, OR in soft-force mode while blocked level exists -->
        <set_value name="$mustTrainNow" exact="false"/>
        <set_value name="$hardForceTraining" exact="true"/>
        <set_value name="$blockedLevel" exact="0"/>
        <set_value name="$shouldProcessTraining" exact="false"/>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <run_actions ref="md.GT_Libraries_General.GT_GetTrainingGate" result="$pilotTrainingGate">
            <param name="pilot" value="$pilot"/>
            <param name="ship" value="$ship"/>
            <param name="respect_hard_force" value="true"/>
          </run_actions>
          <set_value name="$mustTrainNow" exact="$pilotTrainingGate.$MustTrainNow"/>
          <set_value name="$hardForceTraining" exact="$pilotTrainingGate.$HardForce"/>
          <set_value name="$blockedLevel" exact="$pilotTrainingGate.$BlockedLevel"/>
          <set_value name="$shouldProcessTraining" exact="$mustTrainNow or ((not $hardForceTraining) and $blockedLevel gt 1)"/>
        </do_if>
        <do_if value="not $shouldProcessTraining">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Ignoring GT_Training_Needed because training is not mandatory (pilot: ' + $pilot.name + ')'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Retry backoff guard:
             - hard-force mode: use cooldown
             - soft-force mode: retry each loop -->
        <set_value name="$retryReady" exact="true"/>
        <do_if value="$hardForceTraining and $pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt? and player.age lt global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt">
          <set_value name="$retryReady" exact="false"/>
        </do_if>
        
        <do_if value="not $retryReady">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <set_value name="$retryRemaining" exact="(global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt - player.age) / 1s"/>
            <debug_text text="'[GalaxyTrader MK3] Skipping training station search due to retry backoff (' + $retryRemaining + 's remaining)'" chance="100"/>
          </do_if>
        </do_if>
        
        <!-- Check if we can automatically start training, or if a manual request is queued -->
        <set_value name="$manualTrainingRequested" exact="false"/>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$ManualTrainingRequested? and global.$GT_Pilots.{$pilot}.$ManualTrainingRequested">
          <set_value name="$manualTrainingRequested" exact="true"/>
        </do_if>
        <set_value name="$academyEnrollmentPending" exact="false"/>
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}? and global.$GT_Pilots.{$pilot}.$AcademyEnrollment?">
          <set_value name="$academyEnrollmentPending" exact="true"/>
        </do_if>
        <do_if value="$shouldProcessTraining and $retryReady and (global.$GT_GlobalSettings.$XP.$AutoTraining or $manualTrainingRequested or $academyEnrollmentPending)">
          <!-- Find training stations - trading stations only; no pilot jump cap (nearest reachable wins). -->
          <create_list name="$stations"/>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Searching for training facilities (trading stations only, nearest reachable)'" chance="100"/>
          </do_if>
          
          <!-- Get blacklist group for pathfinding (needed before distance checks) -->
          <run_actions ref="md.GT_Libraries_Blacklist.GT_GetBlacklistGroup" result="$blacklistgroup">
            <param name="ship" value="$ship"/>
          </run_actions>
          
          <!-- Find trading stations - KNOWN to player, dockable -->
          <find_station name="$tradingPosts" space="player.galaxy" multiple="true" tradestation="true" tradesknownto="faction.player">
            <match class="[class.station]"/>
            <match owner="[faction.player]" negate="true"/>
            <match owner="[faction.xenon, faction.khaak, faction.yaki]" negate="true"/>
            <match_relation_to object="$ship" relation="dock" comparison="ge"/>
          </find_station>
          
          <do_all exact="$tradingPosts.count" counter="$i">
            <set_value name="$station" exact="$tradingPosts.{$i}"/>
            <set_value name="$isValid" exact="true"/>
            
            <!-- CHECK 1: Full reachability check (station known + basic path + blacklist-aware path) -->
            <!-- FIX: Check ALL reachability requirements BEFORE evaluating other checks -->
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_IsStationReachable" result="$isReachable">
              <param name="ship" value="$ship"/>
              <param name="station" value="$station"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="returnDetails" value="false"/>
            </run_actions>
            <do_if value="not $isReachable">
              <set_value name="$isValid" exact="false"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] Training station ' + $station.knownname + ' filtered out - not reachable (station unknown or no path)'" chance="100"/>
              </do_if>
            </do_if>
            
            <!-- Path distance for debug logging (nearest station picked after all filters) -->
            <set_value name="$gateDistance" exact="-1"/>
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$gateDistance">
                <param name="ship" value="$ship"/>
                <param name="fromSector" value="$ship.sector"/>
                <param name="toSector" value="$station.sector"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="useEscapeMode" value="false"/>
              </run_actions>
            </do_if>
            
            <!-- CHECK 2: Blacklist checks (station + sector) -->
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsStationBlacklisted" result="$stationBlacklisted">
                <param name="station" value="$station"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
              </run_actions>
              <run_actions ref="md.GT_Libraries_Blacklist.GT_IsSectorBlacklisted" result="$sectorBlacklistDetails">
                <param name="sector" value="$station.sector"/>
                <param name="ship" value="$ship"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="returnDetails" value="true"/>
              </run_actions>
              <set_value name="$sectorTravelBlacklisted" exact="$sectorBlacklistDetails.$TravelBlacklisted"/>
              <set_value name="$sectorActivityBlacklisted" exact="$sectorBlacklistDetails.$ActivityBlacklisted"/>
              
              <do_if value="$stationBlacklisted or $sectorTravelBlacklisted or $sectorActivityBlacklisted">
                <set_value name="$isValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Training station ' + $station.knownname + ' filtered out - blacklisted (station: ' + $stationBlacklisted + ', sector travel: ' + $sectorTravelBlacklisted + ', sector activity: ' + $sectorActivityBlacklisted + ')'" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- CHECK 3+4: Service dual probe (bay + docking permission) -->
            <do_if value="$isValid">
              <run_actions ref="md.GT_Libraries_General.GT_CanDock" result="$trainDockResult">
                <param name="station" value="$station"/>
                <param name="ship" value="$ship"/>
                <param name="purpose" value="'dual'"/>
              </run_actions>
              <do_if value="not $trainDockResult.$CanDock">
                <set_value name="$isValid" exact="false"/>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Training station ' + $station.knownname + ' filtered out - dock preflight failed (' + $trainDockResult.$Reason + ')'" chance="100"/>
                </do_if>
              </do_if>
            </do_if>
            
            <!-- Add valid station to list -->
            <do_if value="$isValid">
              <append_to_list name="$stations" exact="$station"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] âœ“ Added training station: ' + $station.knownname + ' (' + $gateDistance + ' jumps, sector: ' + $station.sector.knownname + ')'" chance="100"/>
              </do_if>
            </do_if>
          </do_all>

          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] Found ' + $stations.count + ' accessible training stations'" chance="100"/>
          </do_if>
          
          <do_if value="$stations.count gt 0">
            <!-- FIX: Find nearest station using blacklist-aware pathfinding (same as used for filtering) -->
            <set_value name="$nearestStation" exact="$stations.{1}"/>
            <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$nearestDistance">
              <param name="ship" value="$ship"/>
              <param name="fromSector" value="$ship.sector"/>
              <param name="toSector" value="$nearestStation.sector"/>
              <param name="blacklistgroup" value="$blacklistgroup"/>
              <param name="useEscapeMode" value="false"/>
            </run_actions>
            
            <!-- Find closest station using blacklist-aware pathfinding -->
            <do_all exact="$stations.count" counter="$i">
              <run_actions ref="md.GT_Libraries_Pathfinding.GT_CalculatePathDistance" result="$distance">
                <param name="ship" value="$ship"/>
                <param name="fromSector" value="$ship.sector"/>
                <param name="toSector" value="$stations.{$i}.sector"/>
                <param name="blacklistgroup" value="$blacklistgroup"/>
                <param name="useEscapeMode" value="false"/>
              </run_actions>
              <do_if value="$distance lt $nearestDistance">
                <set_value name="$nearestStation" exact="$stations.{$i}"/>
                <set_value name="$nearestDistance" exact="$distance"/>
              </do_if>
            </do_all>
            
            <!-- Dispatch the DockAndTrain order.

                 Two distinct code paths because subordinate ships and direct
                 GT-order ships behave very differently when an aiscript-level
                 interrupt handler does the create_order:

                 * Natural training ladder -> keep the legacy signal+handler
                   dispatch with immediate="true". The AI handler interrupts
                   the current trade order so the ship heads to the trainer
                   right away.

                 * Trading Academy enrollment -> create the order DIRECTLY
                   here in MD context with immediate="false". For subordinate
                   ships (e.g. miner under a GalaxyMiner commander) the AI
                   interrupt handler runs inside the *inherited* GalaxyMiner
                   aicontext, which is torn down the moment the engine
                   activates the queued DockAndTrain - that orphans the new
                   order and the engine aborts it ~70ms after init, dropping
                   the ship back into the mining loop. Creating the order in
                   MD context anchors it to the engine instead of the
                   transient inherited aicontext, so it survives the parent
                   teardown and the ship actually heads to the academy. -->
            <!-- MD dispatch (immediate=false) for academy enrollments and for
                 Assist subordinates. Inherited GT aicontexts (miner/mk1/mk2
                 under a commander) tear down when immediate DockAndTrain
                 activates, aborting training ~1ms after init. -->
            <set_value name="$isAcademyEnrollment" exact="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?"/>
            <set_value name="$useMdDockDispatch" exact="false"/>
            <do_if value="$isAcademyEnrollment">
              <set_value name="$useMdDockDispatch" exact="true"/>
            </do_if>
            <do_elseif value="$ship.defaultorder? and $ship.defaultorder.id == 'Assist'">
              <set_value name="$useMdDockDispatch" exact="true"/>
            </do_elseif>
            <do_if value="$useMdDockDispatch">
              <set_value name="$alreadyQueued" exact="false"/>
              <do_if value="$ship.orders?">
                <do_all exact="$ship.orders.count" counter="$oi">
                  <do_if value="@$ship.orders.{$oi}.id == 'DockAndTrain'">
                    <set_value name="$alreadyQueued" exact="true"/>
                    <break/>
                  </do_if>
                </do_all>
              </do_if>
              <do_if value="not $alreadyQueued">
                <create_order object="$ship" id="'DockAndTrain'" immediate="false">
                  <param name="destination" value="$nearestStation"/>
                  <param name="debugchance" value="100"/>
                </create_order>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] DockAndTrain queued via MD for ' + $pilot.name + ' (ship ' + $ship.idcode + ', academy=' + $isAcademyEnrollment + ', assist=' + ($ship.defaultorder? and $ship.defaultorder.id == 'Assist') + ') -> ' + $nearestStation.knownname" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] DockAndTrain skipped for ' + $pilot.name + ' (ship ' + $ship.idcode + ') - already queued'" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <signal_objects object="$ship" param="'GT_Training_Station_Found'" param2="table[
                $Station   = $nearestStation,
                $Level     = @global.$GT_Pilots.{$pilot}.$BlockedLevel,
                $Distance  = $nearestDistance,
                $IsAcademy = false
              ]" delay="1ms"/>
            </do_else>
          </do_if>
          <do_else>
            <!-- CRITICAL FIX: No training stations found - temporarily clear XPBlocked to allow trading -->
            <!-- Ship will continue trading and check for training stations again on next opportunity -->
            <!-- This prevents ships from being stuck when training stations are unavailable -->
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3]  No accessible training stations found for ' + $pilot.name + ' (ship: ' + $ship.idcode + ') - temporarily allowing trading. Will check for training stations again later.'" chance="100"/>
            </do_if>
            
            <!-- ROLE-PLAY LOGBOOK MESSAGE: Pilot reports training station search failure -->
            <set_value name="$blockedLevel" exact="@global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
            <!-- Include expected training license cost in the Training Notice logbook message -->
            <set_value name="$trainingCost" exact="5000Cr"/>
            <do_if value="$blockedLevel == 3">
              <set_value name="$trainingCost" exact="5000Cr"/>
            </do_if>
            <do_elseif value="$blockedLevel == 6">
              <set_value name="$trainingCost" exact="12000Cr"/>
            </do_elseif>
            <do_elseif value="$blockedLevel == 9">
              <set_value name="$trainingCost" exact="35000Cr"/>
            </do_elseif>
            <do_elseif value="$blockedLevel == 12">
              <set_value name="$trainingCost" exact="100000Cr"/>
            </do_elseif>
            <set_value name="$logbookMessage" exact="null"/>
            
            <!-- Build logbook message with fallback if BlockedLevel is missing -->
            <!-- Use TextDB reference format directly - write_to_logbook resolves it automatically -->
            <do_if value="$blockedLevel? and $blockedLevel gt 0">
              <set_value name="$logbookMessage" exact="{77000,3223}.[$blockedLevel, $ship.knownname] + '\n\n' + {77000,3224}.[$trainingCost / 100]"/>
            </do_if>
            <do_else>
              <!-- Fallback message if BlockedLevel is missing (shouldn't happen, but safety check) -->
              <set_value name="$logbookMessage" exact="'Commander,\n\nI cannot find an accessible training station for my advancement exam. I will proceed with trading operations as instructed, but I understand that I will not gain experience points until I can complete the required training.\n\nRespectfully,\nAboard ' + $ship.knownname"/>
            </do_else>
            
            <!-- Write logbook message if message was successfully constructed and non-empty -->
            <do_if value="$logbookMessage? and $logbookMessage != null and $logbookMessage != ''">
              <!-- Check if logbook is enabled for this ship -->
              <run_actions ref="md.GT_Libraries_General.GT_IsLogbookEnabled" result="$logbookEnabled">
                <param name="ship" value="$ship"/>
              </run_actions>
              
              <do_if value="$logbookEnabled">
                <run_actions ref="md.GT_Libraries_General.WriteLogbookMessage">
                  <param name="Message" value="$logbookMessage"/>
                  <param name="Category" value="'upkeep'"/>
                  <param name="Title" value="'Training Station Search Failed: ' + $pilot.name + ' (' + $ship.knownname + ')'"/>
                  <param name="Object" value="$ship"/>
                  <param name="Interaction" value="'showonmap'"/>
                  <param name="Highlighted" value="false"/>
                  <param name="CheckGlobalSettings" value="false"/>
                </run_actions>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Logbook message written for training station search failure: ' + $pilot.name + ' (ship: ' + $ship.idcode + ', blocked level: ' + $blockedLevel + ')'" chance="100"/>
                </do_if>
              </do_if>
              <do_else>
                <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                  <debug_text text="'[GalaxyTrader MK3] Logbook message NOT written - logbook entries disabled for ship: ' + $ship.idcode" chance="100"/>
                </do_if>
              </do_else>
            </do_if>
            <do_else>
              <!-- Log error if message construction failed -->
              <set_value name="$messageExists" exact="'false'"/>
              <do_if value="$logbookMessage?">
                <set_value name="$messageExists" exact="'true'"/>
              </do_if>
              <set_value name="$messageNull" exact="'false'"/>
              <do_if value="$logbookMessage == null">
                <set_value name="$messageNull" exact="'true'"/>
              </do_if>
              <set_value name="$messageEmpty" exact="'false'"/>
              <do_if value="$logbookMessage == ''">
                <set_value name="$messageEmpty" exact="'true'"/>
              </do_if>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] ERROR: Failed to construct logbook message for training station search failure - pilot: ' + $pilot.name + ', ship: ' + $ship.idcode + ', blockedLevel: ' + $blockedLevel + ', message exists: ' + $messageExists + ', message null: ' + $messageNull + ', message empty: ' + $messageEmpty" chance="100"/>
              </do_if>
            </do_else>
            
            <!-- Respect hard-force policy -->
            <set_value name="$hardForceTraining" exact="true"/>
            <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
              <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
            </do_if>
            <set_value name="global.$GT_Pilots.{$pilot}.$NextTrainingRetryAt" exact="player.age + 60s"/>
            
            <do_if value="$hardForceTraining">
              <!-- Keep pilot force-blocked; do not release into trading until training becomes available -->
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_unavailable_station'"/>
              <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
                <debug_text text="'[GalaxyTrader MK3] HardForceTraining active: keeping ' + $pilot.name + ' blocked after no-station result (next retry in 60s)'" chance="100"/>
              </do_if>
            </do_if>
            <do_else>
              <!-- Soft policy: allow trading, but keep blocked-level gate for XP -->
              <set_value name="global.$GT_Pilots.{$pilot}.$TrainingState" exact="'training_unavailable_station'"/>
              <remove_value name="global.$GT_Pilots.{$pilot}.$XPBlocked"/>
              <!-- Keep BlockedLevel so we know what level training is needed when stations become available -->
              <signal_objects object="$ship" param="'GT_No_Trade_Found'" param2="'no_training_stations'" delay="1ms"/>
            </do_else>
          </do_else>
        </do_if>
      </actions>
    </cue>



    <!-- Training Completion Monitor (disabled; kept to satisfy event-condition requirement) -->
    <cue name="MonitorTrainingCompletion" instantiate="false">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
      </actions>
    </cue>

    <!-- Update Pilot XP Signal Handler -->
    <cue name="HandleUpdatePilotXP" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Update_Pilot_XP'" comment="Handle pilot XP update"/>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$xpData" exact="event.param2"/>
        <set_value name="$ship" exact="$xpData.$Ship"/>
        <set_value name="$pilot" exact="$xpData.$Pilot"/>
        <set_value name="$xpGained" exact="@$xpData.$XPGained"/>
        <do_if value="not $ship? and $xpData.$ship?">
          <set_value name="$ship" exact="$xpData.$ship"/>
        </do_if>
        <do_if value="not $pilot? and $xpData.$pilot?">
          <set_value name="$pilot" exact="$xpData.$pilot"/>
        </do_if>
        <do_if value="(not $xpGained? or $xpGained le 0) and $xpData.$xpAmount?">
          <set_value name="$xpGained" exact="$xpData.$xpAmount"/>
        </do_if>
        <!-- Legacy MK1/MK2 signals may omit XP amount; map them to configured base XP. -->
        <do_if value="(not $xpGained? or $xpGained le 0) and $ship? and $ship.exists">
          <set_value name="$legacyOrderId" exact="@$ship.defaultorder.id"/>
          <set_value name="$legacyBaseOrderId" exact="if $ship.defaultorder? and $ship.defaultorder.$baseorder? then @$ship.defaultorder.$baseorder.id else null"/>
          <set_value name="$legacyMKSignal" exact="$legacyOrderId == 'GalaxyTraderMK1' or $legacyOrderId == 'GalaxyTraderMK2' or ($legacyOrderId == 'Assist' and ($legacyBaseOrderId == 'GalaxyTraderMK1' or $legacyBaseOrderId == 'GalaxyTraderMK2'))"/>
          <do_if value="$legacyMKSignal">
            <run_actions ref="md.GT_Libraries_General.GT_IncrementFallbackActivation" result="$legacyFallbackCount">
              <param name="key" value="'XP.LegacyMKMissingAmountFallback'"/>
            </run_actions>
            <set_value name="$legacyFallbackXP" exact="if global.$GT_Config? and global.$GT_Config.$XP? and global.$GT_Config.$XP.$BaseXPPerTrade? then global.$GT_Config.$XP.$BaseXPPerTrade else 8"/>
            <do_if value="$legacyFallbackXP lt 1">
              <set_value name="$legacyFallbackXP" exact="1"/>
            </do_if>
            <set_value name="$xpGained" exact="$legacyFallbackXP"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP] Applied legacy MK1/MK2 XP fallback for ' + $ship.idcode + ': ' + $xpGained + ' XP (count=' + $legacyFallbackCount + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
        <do_if value="$useVanillaXPOnly">
          <set_value name="$xpGained" exact="0"/>
        </do_if>
        
        <!-- Only process if we have valid XP data -->
        <do_if value="$xpGained? and $xpGained gt 0">
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] XP update signal received: ' + $xpGained + ' XP for ' + $pilot.name" chance="100"/>
          </do_if>

          <!-- Legacy bridge: route update signals into the single XP mutator cue. -->
          <do_if value="global.$GT_Pilots.{$pilot}?">
            <signal_cue_instantly cue="md.GT_XP_Training.ProcessSingleXPEvent" param="table[
              $pilot = $pilot,
              $Ship = $ship,
              $xpAmount = $xpGained,
              $ware = if $xpData.$Ware? then @$xpData.$Ware else 'legacy_update_signal'
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP] Routed GT_Update_Pilot_XP to ProcessSingleXPEvent for ' + $pilot.name + ' (' + $xpGained + ' XP)'" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <run_actions ref="md.GT_Libraries_General.GT_IncrementFallbackActivation" result="$missingPilotFallbackCount">
              <param name="key" value="'XP.UpdateSignalMissingPilot'"/>
            </run_actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP] Dropped GT_Update_Pilot_XP because pilot is not registered (pilot=' + (if $pilot? then $pilot.name else 'UNKNOWN') + ', ship=' + (if $ship? and $ship.exists then $ship.idcode else 'UNKNOWN') + ', count=' + $missingPilotFallbackCount + ')'" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
        <do_else>
          <run_actions ref="md.GT_Libraries_General.GT_IncrementFallbackActivation" result="$noAmountFallbackCount">
            <param name="key" value="'XP.UpdateSignalNoAmount'"/>
          </run_actions>
          <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
            <debug_text text="'[GalaxyTrader MK3] XP update signal received with no XP amount for ' + (if $pilot? then $pilot.name else 'UNKNOWN') + ' - skipping (count=' + $noAmountFallbackCount + ')'" chance="100"/>
          </do_if>
        </do_else>
      </actions>
    </cue>

    <!-- Central level-up detector used by all GT order types (MK1/MK2/MK3). -->
    <cue name="CheckSkillLevelIncrease" instantiate="true">
      <conditions>
        <event_cue_signalled/>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$data" exact="event.param"/>
        <set_value name="$pilot" exact="$data.$pilot"/>
        <set_value name="$ship" exact="$data.$Ship"/>

        <do_if value="not $useVanillaXPOnly and $pilot? and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="$oldLevel" exact="1"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$Level?">
            <set_value name="$oldLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
          </do_if>

          <set_value name="$currentXP" exact="0"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$XP?">
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
          </do_if>

          <set_value name="$newLevel" exact="1"/>
          <do_all exact="15" counter="$skillLevel">
            <do_if value="$currentXP ge global.$GT_Config.$XP.$SkillThresholds.{$skillLevel}">
              <set_value name="$newLevel" exact="$skillLevel"/>
            </do_if>
          </do_all>

          <do_if value="$newLevel gt $oldLevel">
            <set_value name="global.$GT_Pilots.{$pilot}.$Level" exact="$newLevel"/>
            <signal_objects object="player.galaxy" param="'GT_Update_Ship'" param2="table[
              $Ship = $ship,
              $pilot = $pilot,
              $updateType = 'level_up'
            ]"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP] Level-up detected for ' + $pilot.name + ': ' + $oldLevel + ' -> ' + $newLevel + ' (ship=' + $ship.idcode + ')'" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>
    
    <!-- Training state invariant guard (event-driven self-healing) -->
    <cue name="TrainingInvariantGuard" instantiate="true">
      <conditions>
        <check_any>
          <event_object_signalled object="player.galaxy" param="'GT_Training_Needed'"/>
          <event_object_signalled object="player.galaxy" param="'GT_Start_Training'"/>
          <event_object_signalled object="player.galaxy" param="'GT_Abort_Training'"/>
          <event_object_signalled object="player.galaxy" param="'GT_Complete_Training'"/>
          <event_object_signalled object="player.galaxy" param="'GT_Clear_XP_Block'"/>
        </check_any>
      </conditions>
      <actions>
        <set_value name="$useVanillaXPOnly" exact="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly? and global.$GT_GlobalSettings.$XP.$UseVanillaXPOnly"/>
        <set_value name="$data" exact="event.param2"/>
        <set_value name="$pilot" exact="@$data.$Pilot"/>
        <do_if value="not $pilot? and $data.$pilot?">
          <set_value name="$pilot" exact="$data.$pilot"/>
        </do_if>
        
        <do_if value="$pilot and global.$GT_Pilots? and global.$GT_Pilots.{$pilot}?">
          <set_value name="$blockedLevel" exact="0"/>
          <do_if value="global.$GT_Pilots.{$pilot}.$BlockedLevel?">
            <set_value name="$blockedLevel" exact="global.$GT_Pilots.{$pilot}.$BlockedLevel"/>
          </do_if>
          
          <!-- Invariant: Level 1 must never remain blocked -->
          <do_if value="$blockedLevel le 1 and global.$GT_Pilots.{$pilot}.$XPBlocked?">
            <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
              <param name="pilot" value="$pilot"/>
              <param name="clear_blocked_level" value="true"/>
            </run_actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP-Guard] Cleared invalid training block (blocked level lte 1) for ' + $pilot.name" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Invariant: hard-force mode requires XPBlocked when BlockedLevel exists -->
          <set_value name="$hardForceTraining" exact="true"/>
          <do_if value="global.$GT_GlobalSettings? and global.$GT_GlobalSettings.$XP? and global.$GT_GlobalSettings.$XP.$HardForceTraining?">
            <set_value name="$hardForceTraining" exact="global.$GT_GlobalSettings.$XP.$HardForceTraining"/>
          </do_if>
          <do_if value="not $useVanillaXPOnly and $hardForceTraining and $blockedLevel gt 1 and not global.$GT_Pilots.{$pilot}.$XPBlocked?">
            <run_actions ref="md.GT_Libraries_General.GT_SetTrainingBlocked">
              <param name="pilot" value="$pilot"/>
              <param name="level" value="$blockedLevel"/>
              <param name="set_xpblocked" value="true"/>
            </run_actions>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP-Guard] Restored XPBlocked for hard-force training pilot ' + $pilot.name + ' at level ' + $blockedLevel" chance="100"/>
            </do_if>
          </do_if>
          
          <!-- Invariant: stale training timer without active block should be cleaned -->
          <do_if value="global.$GT_Pilots.{$pilot}.$TrainingStarted? and not global.$GT_Pilots.{$pilot}.$XPBlocked? and $blockedLevel le 1">
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStarted"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingDuration"/>
            <remove_value name="global.$GT_Pilots.{$pilot}.$TrainingStation"/>
            <!-- Trading Academy: also drop dangling enrollment state on stale-cleanup -->
            <do_if value="global.$GT_Pilots.{$pilot}.$AcademyEnrollment?">
              <remove_value name="global.$GT_Pilots.{$pilot}.$AcademyEnrollment"/>
            </do_if>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP-Guard] Removed stale training timer state for ' + $pilot.name" chance="100"/>
            </do_if>
          </do_if>
        </do_if>
      </actions>
    </cue>

    <!-- Handle clearing incorrect XP blocks (e.g., Level 1 pilots) -->
    <cue name="HandleClearXPBlock" instantiate="true">
      <conditions>
        <event_object_signalled object="player.galaxy" param="'GT_Clear_XP_Block'" comment="Clear incorrect XP block"/>
      </conditions>
      <actions>
        <set_value name="$clearData" exact="event.param2"/>
        <set_value name="$ship" exact="$clearData.$Ship"/>
        <set_value name="$pilot" exact="$clearData.$Pilot"/>
        <set_value name="$reason" exact="@$clearData.$Reason"/>
        
        <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Clearing XP block for pilot ' + $pilot.name + ': ' + $reason" chance="100"/>
        
        <!-- Clear XP block -->
        <do_if value="global.$GT_Pilots.{$pilot}?">
          <run_actions ref="md.GT_Libraries_General.GT_ClearTrainingBlocked">
            <param name="pilot" value="$pilot"/>
            <param name="clear_blocked_level" value="true"/>
          </run_actions>
          <remove_value name="global.$GT_Pilots.{$pilot}.$BlockedXPPending"/>
          
          <!-- Update ship name to remove blocked status -->
          <do_if value="global.$GT_Pilots.{$pilot}.$OriginalShipName?">
            <set_value name="$originalName" exact="global.$GT_Pilots.{$pilot}.$OriginalShipName"/>
            <set_value name="$currentLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            
            <!-- Get skill title -->
            <set_value name="$skillTitle" exact="{77000,6001}"/>
            <do_if value="$currentLevel ge 2"><set_value name="$skillTitle" exact="{77000,6002}"/></do_if>
            <do_if value="$currentLevel ge 3"><set_value name="$skillTitle" exact="{77000,6003}"/></do_if>
            <do_if value="$currentLevel ge 4"><set_value name="$skillTitle" exact="{77000,6004}"/></do_if>
            <do_if value="$currentLevel ge 5"><set_value name="$skillTitle" exact="{77000,6005}"/></do_if>
            <do_if value="$currentLevel ge 6"><set_value name="$skillTitle" exact="{77000,6006}"/></do_if>
            
            <set_value name="$newName" exact="$originalName + ' (' + $skillTitle + ' Lv.' + $currentLevel + ' XP:' + $currentXP + ')'"/>
            <set_object_name object="$ship" name="$newName"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Ship name restored: ' + $newName" chance="100"/>
            </do_if>
          </do_if>
          <do_else>
            <!-- Fallback: Use current ship name if OriginalShipName is missing -->
            <set_value name="global.$GT_Pilots.{$pilot}.$OriginalShipName" exact="$ship.knownname"/>
            <set_value name="$originalName" exact="$ship.knownname"/>
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GT-XP] WARNING: Missing OriginalShipName for pilot ' + $pilot.name + ' in clear XP block, using current name: ' + $ship.knownname" chance="100"/>
            </do_if>
            
            <set_value name="$currentLevel" exact="global.$GT_Pilots.{$pilot}.$Level"/>
            <set_value name="$currentXP" exact="global.$GT_Pilots.{$pilot}.$XP"/>
            
            <!-- Get skill title -->
            <set_value name="$skillTitle" exact="{77000,6001}"/>
            <do_if value="$currentLevel ge 2"><set_value name="$skillTitle" exact="{77000,6002}"/></do_if>
            <do_if value="$currentLevel ge 3"><set_value name="$skillTitle" exact="{77000,6003}"/></do_if>
            <do_if value="$currentLevel ge 4"><set_value name="$skillTitle" exact="{77000,6004}"/></do_if>
            <do_if value="$currentLevel ge 5"><set_value name="$skillTitle" exact="{77000,6005}"/></do_if>
            <do_if value="$currentLevel ge 6"><set_value name="$skillTitle" exact="{77000,6006}"/></do_if>
            
            <set_value name="$newName" exact="$originalName + ' (' + $skillTitle + ' Lv.' + $currentLevel + ' XP:' + $currentXP + ')'"/>
            <set_object_name object="$ship" name="$newName"/>
            
            <do_if value="@global.$GT_GlobalSettings.$Debug.$EnableDebugLogging">
              <debug_text text="'[GalaxyTrader MK3] (' + $ship.idcode + ') Ship name restored: ' + $newName" chance="100"/>
            </do_if>
          </do_else>
        </do_if>
      </actions>
    </cue>

  </cues>
</mdscript> 
GALAXYTRADER
================

Give your traders a brain. GalaxyTrader MK3 turns your freighters into intelligent,
self-managing traders that search for profitable routes, earn XP, attend training,
and handle repairs and equipment automatically.

Releases only on Nexusmods and Steam
Nexusmods: https://www.nexusmods.com/x4foundations/mods/1857
Steam: https://steamcommunity.com/sharedfiles/filedetails/?id=3715175855

Full documentation: https://crapcode.dev/
{
  "languages": [
    {
      "language_id": 7,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 33,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 34,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 39,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 42,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 48,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 49,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 55,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 81,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 82,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 86,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 88,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 90,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 359,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    },
    {
      "language_id": 380,
      "passed": true,
      "error_count": 0,
      "warning_count": 0,
      "errors": [],
      "warnings": []
    }
  ],
  "ok": true,
  "rebuild_failures": [],
  "rebuilt_files": {
    "7": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l007.xml",
    "33": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l033.xml",
    "34": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l034.xml",
    "39": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l039.xml",
    "42": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l042.xml",
    "48": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l048.xml",
    "49": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l049.xml",
    "55": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l055.xml",
    "81": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l081.xml",
    "82": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l082.xml",
    "86": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l086.xml",
    "88": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l088.xml",
    "90": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l090.xml",
    "359": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l359.xml",
    "380": "E:\\SHARED\\_STAEUBER\\DEV\\Projects\\Cursor\\Galaxy_Trader\\galaxy_trader_v9\\galaxy_trader\\t\\0001-l380.xml"
  }
}Language 7: PASSED

Language 33: PASSED

Language 34: PASSED

Language 39: PASSED

Language 42: PASSED

Language 48: PASSED

Language 49: PASSED

Language 55: PASSED

Language 81: PASSED

Language 82: PASSED

Language 86: PASSED

Language 88: PASSED

Language 90: PASSED

Language 359: PASSED

Language 380: PASSED
<?xml version='1.0' encoding='utf-8'?>
<language id="7">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Ð¡Ñ‚Ñ‹ÐºÐ¾Ð²ÐºÐ° Ð¸ ÐžÐ¶Ð¸Ð´Ð°Ð½Ð¸Ðµ (GalaxyTrader MK3)</t>
    <t id="10002">Ð“Ð°Ð»Ð°ÐºÑÐ¸Ð¢Ñ€ÐµÐ¹Ð´ÐµÑ€ ÐœÐš3</t>
    <t id="10003">Ð¤Ð¸Ð½Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð­ÐºÐ·Ð°Ð¼ÐµÐ½ (GalaxyTrader MK3)</t>
    <t id="10004">Ð’ÑÑ‚Ñ€ÐµÑ‡Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð¿Ð¾ Ð¾Ð±Ð¼ÐµÐ½Ñƒ</t>
    <t id="10005">[Ð£Ð¡Ð¢ÐÐ Ð•Ð›Ðž] GalaxyTrader ÐŸÐ¾ÑÑ‚Ð°Ð²ÐºÐ° ÐœÐš4 (Ð£ÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ð¹)</t>
    <t id="10101">ÐŸÑ€Ð¸ÑÑ‚Ñ‹ÐºÐ¾Ð²Ð°Ñ‚ÑŒÑÑ Ðº ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸ Ð¶Ð´Ð°Ñ‚ÑŒ ÑƒÐºÐ°Ð·Ð°Ð½Ð½Ð¾Ðµ Ð²Ñ€ÐµÐ¼Ñ</t>
    <t id="10102">ÐÐ²Ñ‚Ð¾Ð½Ð¾Ð¼Ð½Ð°Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ñ Ñ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑÐ¸ÐµÐ¹ Ð½Ð°Ð²Ñ‹ÐºÐ¾Ð²</t>
    <t id="10103">Ð¡Ð´Ð°Ñ‚ÑŒ Ñ„Ð¸Ð½Ð°Ð»ÑŒÐ½Ñ‹Ð¹ ÑÐºÐ·Ð°Ð¼ÐµÐ½ Ð´Ð»Ñ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½Ð° ÑƒÑ‡ÐµÐ±Ð½Ð¾Ð¼ Ð¾Ð±ÑŠÐµÐºÑ‚Ðµ</t>
    <t id="10104">Ð”Ð¾Ðº Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð²ÑÑ‚Ñ€ÐµÑ‡Ð¸ Ð´Ð»Ñ Ð¾Ð±Ð¼ÐµÐ½Ð° Ð»Ð¾Ñ†Ð¼Ð°Ð½Ð°Ð¼Ð¸</t>
    <t id="10105">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ñ, Ð¾Ñ€Ð¸ÐµÐ½Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð½Ð° Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ, Ð´Ð»Ñ Ð¸Ð³Ñ€Ð¾Ð²Ñ‹Ñ… ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹ Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸ÐµÐ¼ ÐºÐµÑˆÐ° Ð¸ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ° (Ð£ÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ð¹)</t>
    <t id="10201">ÐšÑƒÐ¿Ð¸Ñ‚ÑŒ %s Ñƒ %s</t>
    <t id="10202">ÐŸÑ€Ð¾Ð´Ð°Ñ‚ÑŒ %s Ð² %s</t>
    <t id="10203">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ‚ÑŒ Ñ %s</t>
    <t id="1000">Ð“Ð°Ð»Ð°ÐºÑÐ¸Ð¢Ñ€ÐµÐ¹Ð´ÐµÑ€ ÐœÐš3</t>
    <t id="1001">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑÐ¸ÐµÐ¹ XP Ð¸ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÐµÐ¹ Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="1002">Ð‘Ð°Ð·Ð°</t>
    <t id="1003">Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿Ñ€ÐµÑÐµÑ‚Ñ‹</t>
    <t id="1004">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ‚ÑŒ Ð²ÑÐµÐ¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1005">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ‚ÑŒ Ð»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1006">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ‚ÑŒ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1007">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑÐ¸ÑŽ XP</t>
    <t id="1008">blubb</t>
    <t id="1009">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð°Ð½Ð°Ð»Ð¸Ð· Ñ€Ñ‹Ð½ÐºÐ°</t>
    <t id="1010">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ñ‚ÐµÑ€Ñ€Ð¸Ñ‚Ð¾Ñ€Ð¸ÐµÐ¹</t>
    <t id="1011">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ ÐÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ð¢Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="1012">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð–ÑƒÑ€Ð½Ð°Ð»Ðµ</t>
    <t id="1013">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ÑŒ Ðº Ð Ð¸ÑÐºÑƒ</t>
    <t id="1014">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹ Ð¸Ð³Ñ€Ð¾ÐºÐ°</t>
    <t id="1015">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="1016">Ð¨Ñ‚Ñ€Ð°Ñ„ Ð·Ð° Ð Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ %</t>
    <t id="1017">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹</t>
    <t id="1018">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð¤Ð»Ð¾Ñ‚Ð°</t>
    <t id="1019">Ð¦ÐµÐ»ÐµÐ²Ð¾Ðµ Ð—Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ð“Ñ€ÑƒÐ·Ð° %</t>
    <t id="1050">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° ÐžÐ±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ð Ñ‹Ð½ÐºÐ°</t>
    <t id="1051">Ð›Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐžÑ†ÐµÐ½ÐºÐ¸ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸</t>
    <t id="1052">Ð‘ÐµÐ»Ñ‹Ð¹ Ð¡Ð¿Ð¸ÑÐ¾Ðº Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¾Ð²</t>
    <t id="1054">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ ÐÐ²Ð¸Ð°Ð½Ð¾ÑÑ†Ñ‹/Ð’ÑÐ¿Ð¾Ð¼Ð¾Ð³Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ðµ ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸</t>
    <t id="1056">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¡ÐºÐ»Ð°Ð´ Ð¡Ñ‚Ñ€Ð¾Ð¸Ñ‚ÐµÐ»ÑŒÑÑ‚Ð²Ð°</t>
    <t id="1058">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ ÐŸÑ€Ð°Ð²Ð¸Ð»Ð°</t>
    <t id="1060">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÑÐµÐ¼Ñ‹Ðµ MK1</t>
    <t id="1063">Ð’ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐµ</t>
    <t id="1064">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ‹Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="1065">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð±Ð°Ð»Ð»Ð° %</t>
    <t id="1066">Ð¢Ð¾Ð²Ð°Ñ€Ñ‹, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ ÑÐ»ÐµÐ´ÑƒÐµÑ‚ Ð¾Ñ‚Ð´Ð°Ð²Ð°Ñ‚ÑŒ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ñ‚ÐµÐ½Ð¸Ðµ Ð² Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¼ Ñ€ÐµÐ¹Ñ‚Ð¸Ð½Ð³Ðµ. Ð˜Ñ… Ð¾Ñ†ÐµÐ½ÐºÐ° ÑƒÐ¼Ð½Ð¾Ð¶Ð°ÐµÑ‚ÑÑ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð°.</t>
    <t id="1067">ÐœÐ½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»ÑŒ Ð¾Ñ‡ÐºÐ¾Ð² Ð´Ð»Ñ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²: 100% = Ð½Ð¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹, 150% = +50%%, 200% = 2x, 300% = 3x. ÐŸÑ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ Ð¿Ð¾ÑÐ»ÐµÐ´Ð½Ð¸Ð¼.</t>
    <t id="1068">â”€â”€ Ð¤Ð¸Ð»ÑŒÑ‚Ñ€ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² â”€â”€</t>
    <t id="1069">Ð¢Ð¾Ð²Ð°Ñ€Ñ‹ (Ð²Ñ€ÑƒÑ‡Ð½ÑƒÑŽ)</t>
    <t id="1070">Ð¤Ð¸Ð»ÑŒÑ‚Ñ€ Ð½ÐµÐ´Ð¾Ð¿ÑƒÑÑ‚Ð¸Ð¼Ñ‹Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð²</t>
    <t id="1072">ÐŸÐ¾Ð´Ð°Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð¾Ð¼Ð°</t>
    <t id="1073">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ°-Ð¸Ð³Ñ€Ð¾ÐºÐ°</t>
    <t id="1074">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ°-Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸</t>
    <t id="1075">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ñ…Ñ€Ð°Ð½Ð¸Ð»Ð¸Ñ‰Ðµ Ð´Ð»Ñ ÑÐ±Ð¾Ñ€ÐºÐ¸</t>
    <t id="1076">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ñ€ÐµÑÑƒÑ€ÑÑ‹</t>
    <t id="1077">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ð¼ÐµÐ¶ÑƒÑ‚Ð¾Ñ‡Ð½Ñ‹Ðµ</t>
    <t id="1078">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñ‹</t>
    <t id="1080">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ ÑÐ´ÐµÐ»Ð¾Ðº Ð·Ð° Ñ†Ð¸ÐºÐ»</t>
    <t id="1081">Ð”Ð¾Ð¿ÑƒÑÐº Ð²Ð¾Ð·Ð²Ñ€Ð°Ñ‚Ð°</t>
    <t id="1082">ÐœÐ¸Ð½. Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹ Ð³Ñ€ÑƒÐ·, %</t>
    <t id="1083">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ‚Ð¾Ñ€ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð¸Ð³Ñ€Ð¾ÐºÐ° %</t>
    <t id="1085">ÐÐ°Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÑŒ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ</t>
    <t id="1086">Ð Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ð¾ÐºÑ€Ñ‹Ñ‚Ð¸Ñ</t>
    <t id="1088">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ñ€Ñ‹Ð¶ÐºÐ° Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð´Ð»Ñ Ð¿Ð¾ÐºÑ€Ñ‹Ñ‚Ð¸Ñ ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="1090">Ð’ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² ÐºÐ»Ð°ÑÑÐ° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð² ÑÐ¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ ÑÐ¿Ñ€Ð¾ÑÐ° Ð¸ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ.</t>
    <t id="1091">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ‚Ð¾Ñ€, Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÐ¼Ñ‹Ð¹ Ðº Ñ†ÐµÐ½Ð°Ð¼ Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ¾Ð², Ð¿Ñ€Ð¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð°Ñ‰Ð¸Ñ… Ð¸Ð³Ñ€Ð¾ÐºÑƒ, Ð² Ñ€Ð°ÑÑ‡ÐµÑ‚Ð°Ñ… Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ Ð¿Ð¾Ð´ÑÑ‡ÐµÑ‚Ð° Ð¾Ñ‡ÐºÐ¾Ð².</t>
    <t id="1092">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ñ†ÐµÐ½Ñ‹ Ð¸Ð³Ñ€Ð¾ÐºÐ¾Ð²</t>
    <t id="1093">ÐšÐ¾Ð³Ð´Ð° ÑÑ‚Ð° Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð°: Ð²ÑÐµÐ³Ð´Ð° Ð¿Ð¾ÐºÑƒÐ¿Ð°Ð¹Ñ‚Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ…, Ð¿Ñ€Ð¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð°Ñ‰Ð¸Ñ… Ð¸Ð³Ñ€Ð¾ÐºÐ°Ð¼, Ð½ÐµÐ·Ð°Ð²Ð¸ÑÐ¸Ð¼Ð¾ Ð¾Ñ‚ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ‹Ñ… Ð½Ð° Ð½Ð¸Ñ… Ñ†ÐµÐ½ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸, Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ñ„Ñ€Ð°ÐºÑ†Ð¸ÑÐ¼ NPC. ÐŸÐ¾Ð»ÐµÐ·Ð½Ð¾ Ð´Ð»Ñ Ð»Ð¸ÐºÐ²Ð¸Ð´Ð°Ñ†Ð¸Ð¸ Ð¸Ð·Ð»Ð¸ÑˆÐ½Ð¸Ñ… Ð·Ð°Ð¿Ð°ÑÐ¾Ð² Ð½Ð° Ð²Ð°ÑˆÐ¸Ñ… ÑÐ¾Ð±ÑÑ‚Ð²ÐµÐ½Ð½Ñ‹Ñ… ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ….</t>
    <t id="1094">Ð—Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="1095">Ð’Ñ‹Ð±Ñ€Ð°Ð½Ð½Ñ‹Ðµ Ð·Ð´ÐµÑÑŒ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸ÑÐºÐ»ÑŽÑ‡Ð°ÑŽÑ‚ÑÑ Ð¸Ð· Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ MK3. Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† Ð½Ðµ Ð±ÑƒÐ´ÐµÑ‚ Ð½Ð¸ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÑŒ Ñƒ Ð½Ð¸Ñ…, Ð½Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚ÑŒ Ð¸Ð¼.</t>
    <t id="1096">Ð¡Ñ‚Ð¾ÑÐ½ÐºÐ° Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾ÑÑ‚Ð¾Ðµ</t>
    <t id="1097">Ð•ÑÐ»Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ Ð¼Ð½Ð¾Ð³Ð¾ÐºÑ€Ð°Ñ‚Ð½Ð¾ Ð½Ðµ Ð½Ð°Ñ…Ð¾Ð´ÑÑ‚ Ñ€Ð°Ð±Ð¾Ñ‚Ñƒ, Ð¿Ð°Ñ€ÐºÑƒÑŽÑ‚ÑÑ Ñƒ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ¹ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸Ð»Ð¸ Ð² Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ¼ ÑÐµÐºÑ‚Ð¾Ñ€Ðµ. ÐŸÐ°Ñ€ÐºÐ¾Ð²ÐºÐ° Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð°ÐµÑ‚ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ°, Ð·Ð°Ñ‚ÐµÐ¼ Ð´Ñ€ÑƒÐ¶ÐµÑÑ‚Ð²ÐµÐ½Ð½Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸. Ð’Ñ€ÐµÐ¼Ñ Ð¾Ñ‚ÑÑ‚Ñ‹ÐºÐ¾Ð²ÐºÐ¸ Ð·Ð°Ð´Ð°Ñ‘Ñ‚ÑÑ Ð² Ð³Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ‹Ñ… Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ°Ñ… (0 = Ð¾ÑÑ‚Ð°Ñ‘Ñ‚ÑÑ Ñƒ Ð¿Ñ€Ð¸Ñ‡Ð°Ð»Ð°, Ð¿Ð¾ÐºÐ° Ð½Ðµ Ð½Ð°Ð¹Ð´Ñ‘Ñ‚ÑÑ Ñ€Ð°Ð±Ð¾Ñ‚Ð°).</t>
    <t id="1098">ÐÐ²Ñ‚Ð¾Ð¼Ð°ÑÑˆÑ‚Ð°Ð±</t>
    <t id="1099">Ð•ÑÐ»Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, Ð¿Ð¾Ð»Ð·ÑƒÐ½ÐºÐ¸ Ð´Ð°Ð»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð¿Ñ€Ñ‹Ð¶ÐºÐ° ÑƒÑÑ‚Ð°Ð½Ð°Ð²Ð»Ð¸Ð²Ð°ÑŽÑ‚ÑÑ Ð½Ð° Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾ Ð´Ð¾Ð¿ÑƒÑÑ‚Ð¸Ð¼ÑƒÑŽ Ð´Ð°Ð»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð¿Ð¾ÑÐ»Ðµ Ð¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð³Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð¸Ð»Ð¸ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ñ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¹ Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸. Ð¡Ð½Ð¸Ð¼Ð¸Ñ‚Ðµ Ñ„Ð»Ð°Ð¶Ð¾Ðº Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸.</t>
    <t id="11001">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ ÑÐºÐ»Ð°Ð´Ð° ÑÑ‚Ñ€Ð¾Ð¸Ñ‚ÐµÐ»ÑŒÑÑ‚Ð²Ð°</t>
    <t id="11002">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹</t>
    <t id="11003">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð²ÑÐ¿Ð¾Ð¼Ð¾Ð³Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="11004">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð°Ð²Ð¸Ð°Ð½Ð¾ÑÑ†ÐµÐ²</t>
    <t id="11005">0 = Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾. 1-10 = Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»ÑŒ Ð¾Ñ‡ÐºÐ¾Ð² (10 = Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð²ÐµÑ). Ð˜Ñ‚Ð¾Ð³ = Ð¾Ñ‡ÐºÐ¸ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ñ Ã— Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»ÑŒ.</t>
    <t id="11006">1 = Ð±ÐµÐ· Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ñ… Ð¾Ñ‡ÐºÐ¾Ð² (ÑÐ¿Ð¸ÑÐ¾Ðº Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð±ÐµÐ· Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ð¹). 2-10 = Ð´Ð¾Ð±Ð°Ð²Ð»ÑÐµÑ‚ (Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»ÑŒâˆ’1)Ã— Ð±Ð°Ð·Ð¾Ð²Ñ‹Ðµ Ð¾Ñ‡ÐºÐ¸ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ñ, ÐµÑÐ»Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€ Ð² Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¾Ð¼ ÑÐ¿Ð¸ÑÐºÐµ. ÐŸÑ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ Ð¿Ð¾Ð²ÐµÑ€Ñ… Ð¾Ñ‡ÐºÐ¾Ð² Ñ‚Ð¸Ð¿Ð°.</t>
    <t id="11007">Ð‘Ð¾Ð½ÑƒÑ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²</t>
    <t id="11008">%1: Ð’ÑÐµ Ð¿Ð¾Ð»Ð·ÑƒÐ½ÐºÐ¸ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð° Ñ†ÐµÐ»ÐµÐ¹ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ñ‹ Ð½Ð° 0 - Ñƒ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ñ€Ð¸ÐºÐ°Ð·Ð° Ð½ÐµÑ‚ Ñ†ÐµÐ»ÐµÐ¹ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸. Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ðµ Ñ…Ð¾Ñ‚Ñ Ð±Ñ‹ Ð¾Ð´Ð¸Ð½ ÐºÐ»Ð°ÑÑ (ÑÑ‚Ñ€Ð¾Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ ÑÐºÐ»Ð°Ð´, ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, Ð²ÑÐ¿Ð¾Ð¼Ð¾Ð³Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð¸Ð»Ð¸ Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»Ð¸), Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð²Ð¾Ð·Ð¾Ð±Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="7001">[ÐŸÐ ÐžÐ”Ð’Ð˜Ð–Ð•ÐÐ˜Ð•]</t>
    <t id="7002">[ÐžÐ‘Ð£Ð§Ð•ÐÐ˜Ð•]</t>
    <t id="7008">[ÐžÐ¢ÐšÐÐ¢]</t>
    <t id="7009">[Ð˜Ð—ÐžÐ›Ð˜Ð ÐžÐ’ÐÐ]</t>
    <t id="7003">[Ð Ð•ÐœÐžÐÐ¢]</t>
    <t id="7004">[ÐŸÐžÐŸÐžÐ›ÐÐ•ÐÐ˜Ð•]</t>
    <t id="7005">[ÐžÐ‘Ð¡Ð›Ð£Ð–Ð˜Ð’ÐÐÐ˜Ð•]</t>
    <t id="7006">[ÐŸÐ•Ð Ð•ÐœÐÐ Ð¨Ð Ð£Ð¢Ð˜Ð—ÐÐ¦Ð˜Ð¯]</t>
    <t id="7007">[Ð ÐÐ—Ð Ð•Ð¨Ð•ÐÐ˜Ð•]</t>
    <t id="1020">Ð’Ñ‹Ð±ÐµÑ€Ð¸Ñ‚Ðµ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ð¸Ð»Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ, Ð³Ð´Ðµ Ñ€Ð°Ð±Ð¾Ñ‚Ð°ÐµÑ‚ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†</t>
    <t id="1021">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ñ‡ÐµÑ€ÐµÐ· Ð²Ñ€Ð°Ñ‚Ð° Ð¿Ñ€Ð¸ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐµ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² (Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð½Ð°Ð²Ñ‹ÐºÐ¾Ð¼ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°)</t>
    <t id="1022">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ñ‡ÐµÑ€ÐµÐ· Ð²Ñ€Ð°Ñ‚Ð° Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² (Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð½Ð°Ð²Ñ‹ÐºÐ¾Ð¼ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°)</t>
    <t id="1023">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ð²Ñ‹Ð±Ð¾Ñ€ Ð¿Ð¾Ð´Ñ…Ð¾Ð´ÑÑ‰Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ðµ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð¸</t>
    <t id="1024">Ð ÑƒÑ‡Ð½Ð¾Ð¹ Ð²Ñ‹Ð±Ð¾Ñ€ ÐºÐ¾Ð½ÐºÑ€ÐµÑ‚Ð½Ñ‹Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²</t>
    <t id="1025">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»ÑŽ ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð±Ð°Ð½Ð´Ð¾Ð¹ Ð¸ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1026">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ÑŒ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ð¸: 0.0=Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ñ‹Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹, 1.0=ÐŸÑ€Ð¸Ð½Ð¸Ð¼Ð°Ñ‚ÑŒ Ð²ÑÐµ Ñ€Ð¸ÑÐºÐ¸</t>
    <t id="1027">Ð£Ð»ÑƒÑ‡ÑˆÐ°Ñ‚ÑŒ Ð½Ð°Ð²Ñ‹ÐºÐ¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ñ‡ÐµÑ€ÐµÐ· Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¾Ð¿Ñ‹Ñ‚</t>
    <t id="1028">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²Ð»ÑÑ‚ÑŒ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¸ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ÑÑ‚Ð¸</t>
    <t id="1029">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð½ÐµÑÐºÐ¾Ð»ÑŒÐºÐ¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ð´Ð»Ñ Ð¸Ð·Ð±ÐµÐ¶Ð°Ð½Ð¸Ñ ÐºÐ¾Ð½Ñ„Ð»Ð¸ÐºÑ‚Ð¾Ð²</t>
    <t id="1030">Ð¤Ð¾ÐºÑƒÑ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²: 0=Ð¡Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹, 1=ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ñ‹Ð¹, 2=Ð‘Ð°Ð·Ð¾Ð²Ñ‹Ðµ Ð¿Ð¾Ñ‚Ñ€ÐµÐ±Ð½Ð¾ÑÑ‚Ð¸, 3=ÐÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ð¹, 4=ÐœÐ°ÑÑÐ¾Ð²Ñ‹Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="1031">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ Ð·Ð¾Ð½Ð°: 0=Ð¡Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ, 1=Ð¤Ð¾ÐºÑƒÑ Ð½Ð° Ð±Ð°Ð·Ðµ, 2=Ð¡Ð²Ð¾Ð±Ð¾Ð´Ð½Ð¾Ðµ Ð¿ÐµÑ€ÐµÐ¼ÐµÑ‰ÐµÐ½Ð¸Ðµ</t>
    <t id="1032">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹: 0=ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹, 1=ÐžÐ±Ñ‹Ñ‡Ð½Ñ‹Ð¹, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ñ‹Ðµ ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ</t>
    <t id="1033">Ð¦ÐµÐ»ÐµÐ²Ð¾Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð³Ñ€ÑƒÐ·Ð° Ð¿ÐµÑ€ÐµÐ´ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚Ð¸Ð·Ð°Ñ†Ð¸ÐµÐ¹ Ð¿Ñ€Ð¾Ð´Ð°Ð¶</t>
    <t id="1034">ÐšÐ°Ðº Ñ‡Ð°ÑÑ‚Ð¾ Ð¾Ð±Ð½Ð¾Ð²Ð»ÑÑŽÑ‚ÑÑ Ð´Ð°Ð½Ð½Ñ‹Ðµ Ñ€Ñ‹Ð½ÐºÐ° Ð¸ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð¾ Ñ†ÐµÐ½Ð°Ñ…</t>
    <t id="1035">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸: 0=ÐÐµÑ‚, 1=Ð‘Ð°Ð·Ð¾Ð²Ñ‹Ð¹, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾Ðµ Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ</t>
    <t id="1036">Ð”ÐµÐ»Ð¸Ñ‚ÑŒÑÑ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¼Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð°Ð¼Ð¸ Ñ Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼ (ÐºÑÑˆÐ¸Ñ€ÑƒÐµÑ‚ÑÑ Ð´Ð»Ñ Ð±Ñ‹ÑÑ‚Ñ€Ð¾Ð³Ð¾ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð°)</t>
    <t id="1037">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ, Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð°Ñ Ð´Ð»Ñ ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ ÑÐ´ÐµÐ»ÐºÐ¸ Ð¸ Ð¾Ð±Ð¼ÐµÐ½Ð° Ñ Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼</t>
    <t id="1038">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÑÐ½Ð¸Ð¶ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸, Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð½Ð¾Ðµ Ð´Ð¾ Ñ‚Ð¾Ð³Ð¾, ÐºÐ°Ðº ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ ÑÑ‚Ð°Ð½ÑƒÑ‚ Ð½ÐµÐ´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¼Ð¸</t>
    <t id="1039">ÐšÐ°Ðº Ð´Ð¾Ð»Ð³Ð¾ ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ Ð¾ÑÑ‚Ð°ÑŽÑ‚ÑÑ Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¼Ð¸ Ð´Ð¾ Ð¸ÑÑ‚ÐµÑ‡ÐµÐ½Ð¸Ñ</t>
    <t id="1040">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ð¾Ðµ Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ Ð¸Ð½Ð´Ð¸Ð²Ð¸Ð´ÑƒÐ°Ð»ÑŒÐ½Ñ‹Ñ… Ð¾Ñ†ÐµÐ½Ð¾Ðº Ð¸ Ð¾Ñ‚ÐºÐ»Ð¾Ð½ÐµÐ½Ð¸Ð¹ ÑÐ´ÐµÐ»Ð¾Ðº (Ð¼Ð¾Ð¶ÐµÑ‚ Ð±Ñ‹Ñ‚ÑŒ Ð¾Ñ‡ÐµÐ½ÑŒ Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ñ‹Ð¼)</t>
    <t id="1041">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ðµ Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸ Ð¸ Ð¸Ð¼Ð¼ÐµÑ€ÑÐ¸Ð²Ð½Ñ‹Ðµ ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð¾Ð± Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ð¸ (ÑÑ‚Ð¸Ð»ÑŒ TaterTrader)</t>
    <t id="1053">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ñ‹ Ð² ÑÑ‚Ð¾Ð¼ ÑÐ¿Ð¸ÑÐºÐµ Ð¸ÑÐºÐ»ÑŽÑ‡ÐµÐ½Ñ‹ Ð¸Ð· Ñ‡ÐµÑ€Ð½Ñ‹Ñ… ÑÐ¿Ð¸ÑÐºÐ¾Ð² (Ð²ÑÐµÐ³Ð´Ð° Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ñ‹)</t>
    <t id="1055">Ð˜ÑÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð°Ð²Ð¸Ð°Ð½Ð¾ÑÑ†Ñ‹ Ð¸ Ð²ÑÐ¿Ð¾Ð¼Ð¾Ð³Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð¸Ð· Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸</t>
    <t id="1057">Ð˜ÑÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÑÐºÐ»Ð°Ð´Ñ‹ ÑÑ‚Ñ€Ð¾Ð¸Ñ‚ÐµÐ»ÑŒÑÑ‚Ð²Ð° Ð¸Ð· Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸</t>
    <t id="1059">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¿Ñ€Ð¸ Ð¿Ð¾Ð¸ÑÐºÐµ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ (Ñ€Ð°ÑÑˆÐ¸Ñ€ÐµÐ½Ð½Ð¾; Ð¼Ð¾Ð¶ÐµÑ‚ Ð²Ñ‹Ð±Ð¸Ñ€Ð°Ñ‚ÑŒ Ð¾Ð±Ñ‹Ñ‡Ð½Ð¾ Ð·Ð°Ð¿Ñ€ÐµÑ‰Ñ‘Ð½Ð½Ñ‹Ðµ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ)</t>
    <t id="1061">ÐŸÑ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ¾Ð², Ñƒ ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ñ… ÐµÑÑ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† MK1 Ñ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ‹Ð¼ Ñ€ÐµÐ¶Ð¸Ð¼Ð¾Ð¼ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ñ.</t>
    <t id="1062">Ð‘Ð¾Ð½ÑƒÑ Ðº Ð¾Ñ†ÐµÐ½ÐºÐµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð² Ñ ÑƒÑ‡Ð°ÑÑ‚Ð¸ÐµÐ¼ Ð²Ð°ÑˆÐ¸Ñ… ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹ (Ð±Ð¾Ð½ÑƒÑ 10%)</t>
    <t id="1071">ÐšÐ¾Ð³Ð´Ð° Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Â«Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹Â» Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½, Ñ‚Ð¾Ñ€Ð³ÑƒÐ¹Ñ‚Ðµ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð² Ñ‚Ð¾Ð¼ ÑÐ»ÑƒÑ‡Ð°Ðµ, ÐµÑÐ»Ð¸ Ð¾Ð½Ð¸ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ‹, Ð²Ð¾ Ð²ÑÐµÑ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ð¿ÑƒÑ‚Ð¸ Ð¿Ñ€Ñ‹Ð¶ÐºÐ° (Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ°, Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð° Ð¸ Ð¿Ñ€Ð¾Ð¼ÐµÐ¶ÑƒÑ‚Ð¾Ñ‡Ð½Ñ‹Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð°).</t>
    <t id="1087">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ñ€Ñ‹Ð¶ÐºÐ° Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð´Ð»Ñ Ð¿Ð¾Ð¸ÑÐºÐ° Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ¾Ð²</t>
    <t id="1089">Ð•ÑÐ»Ð¸ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, ÑÑƒÐ´Ð½Ð¾ Ð¼Ð¾Ð¶ÐµÑ‚ ÑÐ½Ð°Ð±Ð¶Ð°Ñ‚ÑŒ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð² Ð·Ð¾Ð½Ðµ Ð¿Ð¾ÐºÑ€Ñ‹Ñ‚Ð¸Ñ Ð¿Ð¾ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ñƒ ÑÑ€Ð¾Ñ‡Ð½Ð¾ÑÑ‚Ð¸, Ð° Ð½Ðµ Ð² Ñ€ÐµÐ¶Ð¸Ð¼Ðµ Â«Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ Ð´Ð¾Ð¼Ð°Â».</t>
    <t id="2000">%s Ð¿Ð¾Ð»ÑƒÑ‡Ð¸Ð» %s XP!</t>
    <t id="2001">%s Ð¿Ð¾Ð²Ñ‹ÑÐ¸Ð» ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ! ÐÐ¾Ð²Ñ‹Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ: %s</t>
    <t id="2002">%s Ð½ÑƒÐ¶Ð´Ð°ÐµÑ‚ÑÑ Ð² Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ð¸! ÐŸÐ¾Ð¶Ð°Ð»ÑƒÐ¹ÑÑ‚Ð°, Ð¾Ñ‚Ð¿Ñ€Ð°Ð²ÑŒÑ‚Ðµ Ð½Ð° Ð±Ð»Ð¸Ð¶Ð°Ð¹ÑˆÑƒÑŽ Ð²ÐµÑ€Ñ„ÑŒ Ð¸Ð»Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÑƒÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ.</t>
    <t id="2003">%s Ð½Ð°Ñ‡Ð°Ð» Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð² %s</t>
    <t id="2004">%s Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð» Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¸ Ñ‚ÐµÐ¿ÐµÑ€ÑŒ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½ Ð´Ð»Ñ ÑƒÑ€Ð¾Ð²Ð½Ñ %s!</t>
    <t id="2005">%s Ð´Ð¾ÑÑ‚Ð¸Ð³ Skill Level %s Ð¿Ð¾ÑÐ»Ðµ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ! ÐŸÑ€Ð¾Ð³Ñ€ÐµÑÑ XP Ñ€Ð°Ð·Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½ Ð² %s.</t>
    <t id="2006">%s Ð´Ð¾ÑÑ‚Ð¸Ð³ Skill Level %s Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ðµ %s!</t>
    <t id="2007">%s Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð» Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Level %s! ÐŸÑ€Ð¾Ð³Ñ€ÐµÑÑ XP Ñ€Ð°Ð·Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½ Ð² %s.</t>
    <t id="3000">%s Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð» ÑÐ´ÐµÐ»ÐºÑƒ! ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ: %s Cr</t>
    <t id="3001">%s Ð°Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€ÑƒÐµÑ‚ Ñ€Ñ‹Ð½Ð¾Ñ‡Ð½Ñ‹Ðµ ÑƒÑÐ»Ð¾Ð²Ð¸Ñ...</t>
    <t id="3002">%s Ð½Ð°ÑˆÐµÐ» Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚!</t>
    <t id="3003">ÐÐµÑ‚ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹Ñ… Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð² Ð´Ð»Ñ %s</t>
    <t id="3100">ÐŸÑ€Ð¾Ð´Ð°ÑŽ %1 %2 Ð¸Ð· Ð³Ñ€ÑƒÐ·Ð° Ð½Ð° %3 Ð¿Ð¾ %4. Ð¯ Ð´Ð¾Ð»Ð¶ÐµÐ½ Ð·Ð°Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚ÑŒ %5 Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸.</t>
    <t id="3101">Ð¡Ñ‚Ð°Ð²Ð»ÑŽ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð·Ð°ÐºÐ°Ð· Ð½Ð° %1 %2. ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ° Ð¿Ð¾ %3 Ð½Ð° %4, Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð° Ð¿Ð¾ %5 Ð½Ð° %6. Ð¯ Ð´Ð¾Ð»Ð¶ÐµÐ½ Ð·Ð°Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚ÑŒ %7 Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸.</t>
    <t id="3102">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¾Ð½Ð½Ñ‹Ð¹ Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†: ÐŸÐ¾ÑÑ‚Ð°Ð²Ð»ÑÑŽ %1 %2 Ð¸Ð· %3 Ð¿Ñ€Ð¸ %5%% Ð² %4 Ð¿Ñ€Ð¸ %6%%.</t>
    <t id="3103">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¾Ð½Ð½Ñ‹Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†: ÐŸÑ€Ð¾Ð´Ð°ÑŽ %1 %2 Ð½Ð° %3 Ð¿Ð¾ Ñ†ÐµÐ½Ðµ %4. ÐžÐ¶Ð¸Ð´Ð°ÐµÐ¼Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ %5.</t>
    <t id="3104">Ð¡Ð´ÐµÐ»ÐºÐ° ÑƒÑÐ¿ÐµÑˆÐ½Ð¾ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð° Ð´Ð»Ñ %1 %2. ÐžÐ±Ñ‰Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ: %3 ÐšÑ€ÐµÐ´Ð¸Ñ‚Ð¾Ð².</t>
    <t id="3105">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½: %1 %2 Ð¸Ð· %3 Ð² %4 (ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ: %5 Cr)</t>
    <t id="3106">\nÐžÐ±Ñ‰Ð°Ñ Ñ€Ð°ÑÑ‡ÐµÑ‚Ð½Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ Ð·Ð° Ð²ÑÐµ Ð²Ñ€ÐµÐ¼Ñ Ð´Ð¾ ÑÑ‚Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸: %1 Cr.</t>
    <t id="3120">ÐŸÐµÑ€ÐµÐ´Ð°Ñ‡Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð½Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾ÐµÐºÑ‚Ð° Ð½Ð°Ñ‡Ð°Ñ‚Ð°</t>
    <t id="3121">ÐŸÑ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð» Ð¿ÐµÑ€ÐµÐ´Ð°Ñ‡Ð¸ Ð¿Ð¾Ð´Ñ‚Ð²ÐµÑ€Ð¶Ð´ÐµÐ½. %1 (%2) Ð¸ %3 (%4) ÑÐ»ÐµÐ´ÑƒÑŽÑ‚ Ðº %5 (%6) Ð´Ð»Ñ ÑÑ‚Ñ‹ÐºÐ¾Ð²ÐºÐ¸ Ð¸ Ð¾Ð±Ð¼ÐµÐ½Ð° ÐºÐ¾Ð¼Ð°Ð½Ð´Ð½Ñ‹Ð¼Ð¸ Ð¼ÐµÑÑ‚Ð°Ð¼Ð¸.</t>
    <t id="3200">Ð—Ð´Ñ€Ð°Ð²ÑÑ‚Ð²ÑƒÐ¹Ñ‚Ðµ, ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¯ Ð½Ð°Ð±Ñ€Ð°Ð» Ð´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ð¾ Ð¾Ð¿Ñ‹Ñ‚Ð°, Ñ‡Ñ‚Ð¾Ð±Ñ‹ ÑÐ´Ð°Ñ‚ÑŒ ÑÐºÐ·Ð°Ð¼ÐµÐ½ Ð½Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸ÑŽ Ð´Ð»Ñ Ð·Ð²Ð°Ð½Ð¸Ñ "%2". Ð­ÐºÐ·Ð°Ð¼ÐµÐ½ Ð·Ð°Ð¹Ð¼ÐµÑ‚ Ð¿Ñ€Ð¸Ð¼ÐµÑ€Ð½Ð¾ %3 Ð¼Ð¸Ð½ÑƒÑ‚ Ð² %4.\n\nÐ­Ñ‚Ð¾ Ð²Ð°Ð¶Ð½Ð°Ñ Ð²ÐµÑ…Ð° Ð² Ð¼Ð¾ÐµÐ¼ ÐºÐ°Ñ€ÑŒÐµÑ€Ð½Ð¾Ð¼ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ð¸. Ð­ÐºÐ·Ð°Ð¼ÐµÐ½ Ð¿Ñ€Ð¾Ð²ÐµÑ€Ð¸Ñ‚ Ð¼Ð¾Ð¸ Ð·Ð½Ð°Ð½Ð¸Ñ Ð¿Ñ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ñ‹Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ð¾Ð², Ð°Ð½Ð°Ð»Ð¸Ð·Ð° Ñ€Ñ‹Ð½ÐºÐ° Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ´ÑƒÑ€ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ð¸ Ñ„Ð»Ð¾Ñ‚Ð°.\n\nÐ¯ ÑƒÐ²ÐµÑ€ÐµÐ½ Ð² ÑÐ²Ð¾Ð¸Ñ… ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚ÑÑ… Ð¸ Ñ€Ð°Ð´ Ð´Ð¾ÐºÐ°Ð·Ð°Ñ‚ÑŒ, Ñ‡Ñ‚Ð¾ Ð´Ð¾ÑÑ‚Ð¾Ð¸Ð½ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ñ. ÐŸÐ¾Ð¶ÐµÐ»Ð°Ð¹Ñ‚Ðµ Ð¼Ð½Ðµ ÑƒÐ´Ð°Ñ‡Ð¸!\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\n%5\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3201">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐžÑ‚Ð»Ð¸Ñ‡Ð½Ñ‹Ðµ Ð½Ð¾Ð²Ð¾ÑÑ‚Ð¸! Ð¯ ÑƒÑÐ¿ÐµÑˆÐ½Ð¾ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð» ÑÐºÐ·Ð°Ð¼ÐµÐ½ Ð½Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸ÑŽ Ð¸ Ð¿Ð¾Ð»ÑƒÑ‡Ð¸Ð» Ð·Ð²Ð°Ð½Ð¸Ðµ "%2"!\n\nÐ­ÐºÐ·Ð°Ð¼ÐµÐ½ Ð¾Ñ…Ð²Ð°Ñ‚Ñ‹Ð²Ð°Ð» Ð¿Ñ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ ÑÑ‚Ñ€Ð°Ñ‚ÐµÐ³Ð¸Ð¸, Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ñ‹ Ð¾Ñ†ÐµÐ½ÐºÐ¸ Ñ€Ð¸ÑÐºÐ¾Ð² Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ´ÑƒÑ€Ñ‹ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ð¸ Ñ„Ð»Ð¾Ñ‚Ð°. Ð¯ Ñ€Ð°Ð´ ÑÐ¾Ð¾Ð±Ñ‰Ð¸Ñ‚ÑŒ, Ñ‡Ñ‚Ð¾ ÑÐ´Ð°Ð» Ñ Ð¾Ñ‚Ð»Ð¸Ñ‡Ð¸ÐµÐ¼.\n\nÐ¢ÐµÐ¿ÐµÑ€ÑŒ Ñ ÐºÐ²Ð°Ð»Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½ Ð´Ð»Ñ Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹ Ñ Ð±Ð¾Ð»ÐµÐµ ÑÐ»Ð¾Ð¶Ð½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¼Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸ÑÐ¼Ð¸ Ð¸ Ñ Ð½ÐµÑ‚ÐµÑ€Ð¿ÐµÐ½Ð¸ÐµÐ¼ Ð¶Ð´Ñƒ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð²Ð½ÐµÑÑ‚Ð¸ ÐµÑ‰Ðµ Ð±Ð¾Ð»ÑŒÑˆÐ¸Ð¹ Ð²ÐºÐ»Ð°Ð´ Ð² ÑƒÑÐ¿ÐµÑ… Ð½Ð°ÑˆÐµÐ³Ð¾ Ñ„Ð»Ð¾Ñ‚Ð°. Ð¡Ð¿Ð°ÑÐ¸Ð±Ð¾ Ð·Ð° Ð¸Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ð¸Ð¸ Ð² Ð¼Ð¾Ðµ Ð¿Ñ€Ð¾Ñ„ÐµÑÑÐ¸Ð¾Ð½Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ðµ.\n\nÐ¡ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ð¾Ð¹ Ð¿Ñ€ÐµÐ´Ð°Ð½Ð½Ð¾ÑÑ‚ÑŒÑŽ,\n%3\nÐ¡ÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹ %2\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %4</t>
    <t id="3202">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¡ ÑÐ¾Ð¶Ð°Ð»ÐµÐ½Ð¸ÐµÐ¼ ÑÐ¾Ð¾Ð±Ñ‰Ð°ÑŽ, Ñ‡Ñ‚Ð¾ Ð¼Ð¾Ð¹ ÑÐºÐ·Ð°Ð¼ÐµÐ½ Ð½Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸ÑŽ Ð±Ñ‹Ð» Ð¿Ñ€ÐµÑ€Ð²Ð°Ð½ Ð¸Ð·-Ð·Ð° Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ð½Ñ‹Ñ… Ñ‚Ñ€ÐµÐ±Ð¾Ð²Ð°Ð½Ð¸Ð¹. ÐœÐ½Ðµ Ð½ÑƒÐ¶Ð½Ð¾ Ð±ÑƒÐ´ÐµÑ‚ Ð¿ÐµÑ€ÐµÐ½ÐµÑÑ‚Ð¸ ÐµÐ³Ð¾, ÐºÐ¾Ð³Ð´Ð° Ð¾Ð±ÑÑ‚Ð¾ÑÑ‚ÐµÐ»ÑŒÑÑ‚Ð²Ð° Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑ‚.\n\nÐ¯ Ð¾ÑÑ‚Ð°ÑŽÑÑŒ Ð¿Ñ€Ð¸Ð²ÐµÑ€Ð¶ÐµÐ½Ð½Ñ‹Ð¼ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸ÑŽ ÑÐ²Ð¾Ð¸Ñ… Ð½Ð°Ð²Ñ‹ÐºÐ¾Ð² Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð³Ð´Ð° ÑÐ¼Ð¾Ð³Ñƒ Ð²Ð¾Ð·Ð¾Ð±Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ñ†ÐµÑÑ ÑÐºÐ·Ð°Ð¼ÐµÐ½Ð°Ñ†Ð¸Ð¸.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\n%2\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %3</t>
    <t id="3203">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¯ ÑÐµÐ¹Ñ‡Ð°Ñ Ð² Ð¿ÑƒÑ‚Ð¸ Ðº %2 Ð´Ð»Ñ ÑÐ´Ð°Ñ‡Ð¸ ÑÐºÐ·Ð°Ð¼ÐµÐ½Ð° Ð½Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸ÑŽ. ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ðµ Ð´Ð°ÐµÑ‚ Ð¼Ð½Ðµ Ð²Ñ€ÐµÐ¼Ñ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð¸Ñ‚ÑŒ Ð¸Ð·ÑƒÑ‡ÐµÐ½Ð½Ð¾Ðµ Ð¸ Ð¼Ð¾Ñ€Ð°Ð»ÑŒÐ½Ð¾ Ð¿Ð¾Ð´Ð³Ð¾Ñ‚Ð¾Ð²Ð¸Ñ‚ÑŒÑÑ Ðº ÑÑ‚Ð¾Ð¼Ñƒ Ð²Ð°Ð¶Ð½Ð¾Ð¼Ñƒ ÑˆÐ°Ð³Ñƒ Ð² Ð¼Ð¾ÐµÐ¹ ÐºÐ°Ñ€ÑŒÐµÑ€Ðµ.\n\nÐžÐ¶Ð¸Ð´Ð°ÐµÐ¼Ð¾Ðµ Ð¿Ñ€Ð¸Ð±Ñ‹Ñ‚Ð¸Ðµ: %3 Ð¼Ð¸Ð½ÑƒÑ‚\nÐŸÑ€Ð¾Ð´Ð¾Ð»Ð¶Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ ÑÐºÐ·Ð°Ð¼ÐµÐ½Ð°: %4 Ð¼Ð¸Ð½ÑƒÑ‚\n\nÐ¯ Ñ†ÐµÐ½ÑŽ Ð²Ð°ÑˆÐµ Ð´Ð¾Ð²ÐµÑ€Ð¸Ðµ Ðº Ð¼Ð¾Ð¸Ð¼ ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚ÑÐ¼ Ð¸ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ñ.\n\nÐ¡ Ñ€ÐµÑˆÐ¸Ð¼Ð¾ÑÑ‚ÑŒÑŽ,\n%5\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3204">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¯ Ð¾Ð±Ð½Ð°Ñ€ÑƒÐ¶Ð¸Ð» Ð³Ñ€ÑƒÐ· Ð² Ð¼Ð¾ÐµÐ¼ Ñ‚Ñ€ÑŽÐ¼Ðµ Ð²Ð¾ Ð²Ñ€ÐµÐ¼Ñ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ¸ ÑÐ¸ÑÑ‚ÐµÐ¼. ÐŸÑ€ÐµÐ¶Ð´Ðµ Ñ‡ÐµÐ¼ Ñ ÑÐ¼Ð¾Ð³Ñƒ Ð½Ð°Ñ‡Ð°Ñ‚ÑŒ Ð½Ð¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸, Ð¼Ð½Ðµ Ð½ÑƒÐ¶Ð½Ð¾ Ð¿Ñ€Ð¾Ð´Ð°Ñ‚ÑŒ ÑÑ‚Ð¾Ñ‚ Ñ‚Ð¾Ð²Ð°Ñ€.\n\nÐ¯ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑŽ Ð½Ð°Ñˆ Ð¿Ð¾Ð¸ÑÐº Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð½Ð°Ð¹Ñ‚Ð¸ Ð»ÑƒÑ‡ÑˆÐµÐ³Ð¾ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ñ Ð¸ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ Ñ€Ð°Ð·Ð³Ñ€ÑƒÐ·Ð¸Ñ‚ÑŒ ÑÑ‚Ð¾Ñ‚ Ð³Ñ€ÑƒÐ·. ÐšÐ°Ðº Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð¼Ð¾Ð¹ Ñ‚Ñ€ÑŽÐ¼ Ð±ÑƒÐ´ÐµÑ‚ Ð¿ÑƒÑÑ‚, Ñ Ð¿Ñ€Ð¸ÑÑ‚ÑƒÐ¿Ð»ÑŽ Ðº Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ðµ.\n\nÐ¡Ñ‚Ð°Ñ‚ÑƒÑ: ÐŸÐ¾Ð¸ÑÐº Ð¾Ð¿Ñ‚Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¼ÐµÑÑ‚Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸\n\nÐ¡ ÑƒÑÐµÑ€Ð´Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %1</t>
    <t id="3205">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¦ÐµÐ»Ð¾ÑÑ‚Ð½Ð¾ÑÑ‚ÑŒ Ð¼Ð¾ÐµÐ³Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° ÑƒÐ¿Ð°Ð»Ð° Ð´Ð¾ %1%% (Ð¿Ð¾Ñ€Ð¾Ð³: %2%%). ÐšÐ°Ðº Ð¿Ð¸Ð»Ð¾Ñ‚ Ð£Ñ€Ð¾Ð²Ð½Ñ %3, Ñ ÑƒÐ¿Ð¾Ð»Ð½Ð¾Ð¼Ð¾Ñ‡ÐµÐ½ Ð·Ð°Ð¿Ñ€Ð¾ÑÐ¸Ñ‚ÑŒ ÑƒÑÐ»ÑƒÐ³Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð°.\n\nÐ¯ Ð½Ð°Ð¿Ñ€Ð°Ð²Ð»ÑÑŽÑÑŒ Ðº %4 Ð´Ð»Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ñ‹Ñ… Ñ€Ð°Ð±Ð¾Ñ‚. Ð Ð°ÑÑ‡ÐµÑ‚Ð½Ð°Ñ ÑÑ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚ÑŒ ÑÐ¾ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ %5 Cr, Ñ‡Ñ‚Ð¾ Ð½Ð°Ñ…Ð¾Ð´Ð¸Ñ‚ÑÑ Ð² Ð¿Ñ€ÐµÐ´ÐµÐ»Ð°Ñ… Ð½Ð°ÑˆÐµÐ³Ð¾ Ð±ÑŽÐ´Ð¶ÐµÑ‚Ð°.\n\nÐŸÐ¾ÑÐ»Ðµ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð° Ñ Ð²Ð¾Ð·Ð¾Ð±Ð½Ð¾Ð²Ð»ÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ Ñ Ð¿Ð¾Ð»Ð½Ð¾Ð¹ ÑÑ‚Ñ€ÑƒÐºÑ‚ÑƒÑ€Ð½Ð¾Ð¹ Ñ†ÐµÐ»Ð¾ÑÑ‚Ð½Ð¾ÑÑ‚ÑŒÑŽ.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3206">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¡Ð ÐžÐ§ÐÐžÐ• Ð¤Ð˜ÐÐÐÐ¡ÐžÐ’ÐžÐ• ÐŸÐ Ð•Ð”Ð£ÐŸÐ Ð•Ð–Ð”Ð•ÐÐ˜Ð•\n\nÐ¦ÐµÐ»Ð¾ÑÑ‚Ð½Ð¾ÑÑ‚ÑŒ Ð¼Ð¾ÐµÐ³Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° ÐºÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð° Ð½Ð° %1%% (Ð¿Ð¾Ñ€Ð¾Ð³: %2%%), Ð½Ð¾ Ð½Ð°ÑˆÐ¸ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹Ðµ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° (%3 Cr) Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ñ‹ Ð´Ð»Ñ Ð¿Ð¾Ð»Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð° (Ñ€Ð°ÑÑ‡ÐµÑ‚Ð½Ð°Ñ ÑÑ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚ÑŒ: %4 Cr).\n\nÐ¯ Ð½Ð°Ð¿Ñ€Ð°Ð²Ð»ÑÑŽÑÑŒ Ðº %5 Ð´Ð»Ñ Ð§ÐÐ¡Ð¢Ð˜Ð§ÐÐžÐ“Ðž Ð Ð•ÐœÐžÐÐ¢Ð, Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑ Ð½Ð°ÑˆÐ¸ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹Ðµ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð°. Ð­Ñ‚Ð¾ Ð½Ðµ Ð¸Ð´ÐµÐ°Ð»ÑŒÐ½Ð¾Ðµ Ñ€ÐµÑˆÐµÐ½Ð¸Ðµ, Ð½Ð¾ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ð´Ð»Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶Ð°Ð½Ð¸Ñ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð¾Ð¹ ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚Ð¸.\n\nÐŸÐ¾Ð¶Ð°Ð»ÑƒÐ¹ÑÑ‚Ð°, Ñ€Ð°ÑÑÐ¼Ð¾Ñ‚Ñ€Ð¸Ñ‚Ðµ Ð²Ñ‹Ð´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ñ… ÑÑ€ÐµÐ´ÑÑ‚Ð² Ð´Ð»Ñ Ð±ÑƒÐ´ÑƒÑ‰Ð¸Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¹ Ð¿Ð¾ Ñ‚ÐµÑ…Ð½Ð¸Ñ‡ÐµÑÐºÐ¾Ð¼Ñƒ Ð¾Ð±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸ÑŽ.\n\nÐžÐ±ÐµÑÐ¿Ð¾ÐºÐ¾ÐµÐ½, Ð½Ð¾ Ñ€ÐµÑˆÐ¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ Ð½Ð°ÑÑ‚Ñ€Ð¾ÐµÐ½,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3207">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐœÐ¾Ñ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð£Ñ€Ð¾Ð²Ð½Ñ %1 Ñ€Ð°Ð·Ñ€ÐµÑˆÐ°ÐµÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð³Ð¾ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ. ÐŸÐ¾ÑÐ»Ðµ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ¸ Ð¼Ð¾Ð¸Ñ… ÑÐ¸ÑÑ‚ÐµÐ¼ Ñ Ð¾Ð¿Ñ€ÐµÐ´ÐµÐ»Ð¸Ð», Ñ‡Ñ‚Ð¾ Ð¼Ð¾Ð¸ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° Ð¿Ñ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ Ð¸ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ðµ ÑƒÑÑ‚Ñ€Ð¾Ð¹ÑÑ‚Ð²Ð° Ð½Ð¸Ð¶Ðµ Ñ€ÐµÐºÐ¾Ð¼ÐµÐ½Ð´ÑƒÐµÐ¼Ñ‹Ñ… Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð².\n\nÐ¯ Ð½Ð°Ð¿Ñ€Ð°Ð²Ð»ÑÑŽÑÑŒ Ðº %2 Ð´Ð»Ñ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð¼Ð¾ÐµÐ³Ð¾ Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð³Ð¾ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ:\nâ€¢ Ð¡Ñ€ÐµÐ´ÑÑ‚Ð²Ð° Ð¿Ñ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ: ÐŸÐ¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ð´Ð¾ Ð¾Ð¿Ñ‚Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð¹ ÐµÐ¼ÐºÐ¾ÑÑ‚Ð¸\nâ€¢ Ð”Ñ€Ð¾Ð½Ñ‹ Ð·Ð°Ñ‰Ð¸Ñ‚Ñ‹, Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð´Ñ€Ð¾Ð½Ñ‹, Ð»Ð°Ð·ÐµÑ€Ð½Ñ‹Ðµ Ð±Ð°ÑˆÐ½Ð¸: ÐŸÑ€Ð¸Ð¼ÐµÐ½ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¾Ñ„Ð¸Ð»Ñ Ð±Ð°Ð»Ð°Ð½ÑÐ°\n\nÐ­Ñ‚Ð¾ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ð¾Ð±ÐµÑÐ¿ÐµÑ‡Ð¸Ð²Ð°ÐµÑ‚ Ð¼Ð½Ðµ Ð»ÑƒÑ‡ÑˆÑƒÑŽ Ð·Ð°Ñ‰Ð¸Ñ‚Ñƒ Ð¾Ñ‚ ÐºÐ¾ÑÐ¼Ð¸Ñ‡ÐµÑÐºÐ¸Ñ… ÑƒÐ³Ñ€Ð¾Ð· Ð¿Ñ€Ð¸ ÑÐ¾Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¹ ÑÑ„Ñ„ÐµÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ð¸.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %3</t>
    <t id="3212">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¦ÐµÐ»Ð¾ÑÑ‚Ð½Ð¾ÑÑ‚ÑŒ Ð¼Ð¾ÐµÐ³Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° ÑƒÐ¿Ð°Ð»Ð° Ð´Ð¾ %1%% (Ð¿Ð¾Ñ€Ð¾Ð³: %2%%), Ð¸ Ð¼Ð½Ðµ Ð½ÑƒÐ¶Ð½Ñ‹ ÑƒÑÐ»ÑƒÐ³Ð¸ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð°. ÐžÐ´Ð½Ð°ÐºÐ¾ Ð±Ð»Ð¸Ð¶Ð°Ð¹ÑˆÐ°Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð°Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð² %3 Ð² Ð½Ð°ÑÑ‚Ð¾ÑÑ‰ÐµÐµ Ð²Ñ€ÐµÐ¼Ñ Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð¸Ð·-Ð·Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ð¹ Ð½Ð° Ð¿ÐµÑ€ÐµÐ¼ÐµÑ‰ÐµÐ½Ð¸Ðµ Ð¼ÐµÐ¶Ð´Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼Ð¸ (Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹).\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸, Ð½ÐµÑÐ¼Ð¾Ñ‚Ñ€Ñ Ð½Ð° ÑÑ‚Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ. ÐšÐ°Ðº Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ ÑÐ½Ð¾Ð²Ð° ÑÑ‚Ð°Ð½ÑƒÑ‚ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹, Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¾Ð±Ñ€Ð°Ñ‰ÑƒÑÑŒ Ð·Ð° ÑƒÑÐ»ÑƒÐ³Ð°Ð¼Ð¸ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð°.\n\nÐ¯ Ð±ÑƒÐ´Ñƒ ÑÐ»ÐµÐ´Ð¸Ñ‚ÑŒ Ð·Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÐµÐ¹ Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð³Ð´Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ ÑÑ‚Ð°Ð½ÐµÑ‚ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ñ‹Ð¼.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %4</t>
    <t id="3213">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐœÐ¾Ðµ Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ðµ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ðµ Ñ‚Ñ€ÐµÐ±ÑƒÐµÑ‚ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ, Ð½Ð¾ Ð±Ð»Ð¸Ð¶Ð°Ð¹ÑˆÐ°Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ Ð² %1 Ð² Ð½Ð°ÑÑ‚Ð¾ÑÑ‰ÐµÐµ Ð²Ñ€ÐµÐ¼Ñ Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð¸Ð·-Ð·Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ð¹ Ð½Ð° Ð¿ÐµÑ€ÐµÐ¼ÐµÑ‰ÐµÐ½Ð¸Ðµ Ð¼ÐµÐ¶Ð´Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼Ð¸ (Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹).\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸, Ð½ÐµÑÐ¼Ð¾Ñ‚Ñ€Ñ Ð½Ð° ÑÑ‚Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ. ÐšÐ°Ðº Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ ÑÐ½Ð¾Ð²Ð° ÑÑ‚Ð°Ð½ÑƒÑ‚ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹, Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¾Ð±Ñ€Ð°Ñ‰ÑƒÑÑŒ Ð·Ð° ÑƒÑÐ»ÑƒÐ³Ð°Ð¼Ð¸ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ.\n\nÐ¯ Ð±ÑƒÐ´Ñƒ ÑÐ»ÐµÐ´Ð¸Ñ‚ÑŒ Ð·Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÐµÐ¹ Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð³Ð´Ð° Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ ÑÑ‚Ð°Ð½ÐµÑ‚ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ñ‹Ð¼.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %2</t>
    <t id="3208">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¯ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð» Ð¸ÑÑ‡ÐµÑ€Ð¿Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ð¹ Ð°Ð½Ð°Ð»Ð¸Ð· Ñ€Ñ‹Ð½ÐºÐ° %1 Ð¸ Ð¾ÐºÑ€ÑƒÐ¶Ð°ÑŽÑ‰Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð² (Ð² Ð¿Ñ€ÐµÐ´ÐµÐ»Ð°Ñ… %2 Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð², Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð¿Ð¾Ñ€Ð¾Ð³ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸: %3 Cr), Ð½Ð¾, Ðº ÑÐ¾Ð¶Ð°Ð»ÐµÐ½Ð¸ÑŽ, Ð½Ðµ Ð½Ð°ÑˆÐµÐ» Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ÐµÐ¹, ÑÐ¾Ð¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²ÑƒÑŽÑ‰Ð¸Ñ… Ð½Ð°ÑˆÐ¸Ð¼ Ñ‚Ñ€ÐµÐ±Ð¾Ð²Ð°Ð½Ð¸ÑÐ¼.\n\nÐžÐ¢Ð§Ð•Ð¢ ÐÐÐÐ›Ð˜Ð—Ð Ð¢ÐžÐ Ð“ÐžÐ’Ð›Ð˜:\nÐ’ÑÐµÐ³Ð¾ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ÐµÐ¹ Ð¾Ñ†ÐµÐ½ÐµÐ½Ð¾: %4\n\nÐ ÐÐ—Ð‘Ð˜Ð’ÐšÐ ÐžÐ¢ÐšÐ›ÐžÐÐ•ÐÐ˜Ð™:\n- ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ ÑÑ‚Ñ‹ÐºÐ¾Ð²ÐºÐ¸: %5 ÑÐ´ÐµÐ»Ð¾Ðº\n  (Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ðµ Ñ€Ð°Ð·Ñ€ÐµÑˆÐ°ÐµÑ‚ Ð¼Ð¾Ð¹ ÐºÐ»Ð°ÑÑ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ)\n- ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ð¾ÑÑ‚ÑŒ: %6 ÑÐ´ÐµÐ»Ð¾Ðº\n  (ÐÐ¸Ð¶Ðµ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ð° Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸)\n- ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ñ‹Ð¹ Ð¾Ð±ÑŠÐµÐ¼: %7 ÑÐ´ÐµÐ»Ð¾Ðº\n  (ÐÑƒÐ»ÐµÐ²Ð¾Ðµ Ð¸Ð»Ð¸ Ð¾Ñ‚Ñ€Ð¸Ñ†Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ðµ Ñ‚Ð¾Ñ€Ð³ÑƒÐµÐ¼Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾)\n- ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ð¸: %8 ÑÐ´ÐµÐ»Ð¾Ðº\n  (Ð—Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸Ð»Ð¸ Ð¾Ð¿Ð°ÑÐ½Ñ‹Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹)\n\nÐ Ð•ÐšÐžÐœÐ•ÐÐ”ÐÐ¦Ð˜Ð˜:\n- Ð Ð°ÑÑÐ¼Ð¾Ñ‚Ñ€Ð¸Ñ‚Ðµ ÐºÐ¾Ñ€Ñ€ÐµÐºÑ‚Ð¸Ñ€Ð¾Ð²ÐºÑƒ Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð² Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸\n- Ð Ð°ÑÑˆÐ¸Ñ€ÑŒÑ‚Ðµ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½ÑƒÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÑƒÑŽ Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ\n- ÐŸÐµÑ€ÐµÑÐ¼Ð¾Ñ‚Ñ€Ð¸Ñ‚Ðµ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ° ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð²\n- Ð”Ð¾Ð¶Ð´Ð¸Ñ‚ÐµÑÑŒ ÑƒÐ»ÑƒÑ‡ÑˆÐµÐ½Ð¸Ñ Ñ€Ñ‹Ð½Ð¾Ñ‡Ð½Ñ‹Ñ… ÑƒÑÐ»Ð¾Ð²Ð¸Ð¹\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ñƒ Ð¼Ð¾Ð½Ð¸Ñ‚Ð¾Ñ€Ð¸Ð½Ð³ Ñ€Ñ‹Ð½ÐºÐ° Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð³Ð´Ð° Ð¿Ð¾ÑÐ²ÑÑ‚ÑÑ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸.\n\nÐ’ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ð¸,\nÐš Ð²Ð°ÑˆÐ¸Ð¼ ÑƒÑÐ»ÑƒÐ³Ð°Ð¼</t>
    <t id="3209">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¡Ð ÐžÐ§ÐÐžÐ• ÐŸÐ Ð•Ð”Ð£ÐŸÐ Ð•Ð–Ð”Ð•ÐÐ˜Ð• Ðž ÐœÐÐ Ð¨Ð Ð£Ð¢Ð•\n\nÐœÐ¾Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð°Ð·Ð²ÐµÐ´ÐºÐ¸ ÑƒÐ³Ñ€Ð¾Ð· Ð¾Ð±Ð½Ð°Ñ€ÑƒÐ¶Ð¸Ð»Ð°, Ñ‡Ñ‚Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€ %1 (ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ³Ñ€Ð¾Ð·Ñ‹ %2) Ñ‚ÐµÐ¿ÐµÑ€ÑŒ Ð½Ð°Ñ…Ð¾Ð´Ð¸Ñ‚ÑÑ Ð² Ð¼Ð¾ÐµÐ¼ Ð·Ð°Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ð¼ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¼ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ðµ. Ð Ð°Ð´Ð¸ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ð¸ ÑÐºÐ¸Ð¿Ð°Ð¶Ð° Ñ Ð½ÐµÐ¼ÐµÐ´Ð»ÐµÐ½Ð½Ð¾ Ð¿Ñ€ÐµÑ€Ñ‹Ð²Ð°ÑŽ Ñ‚ÐµÐºÑƒÑ‰ÑƒÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÑƒÑŽ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸ÑŽ.\n\nÐŸÐ Ð•Ð”ÐŸÐ Ð˜ÐÐ¯Ð¢Ð«Ð• Ð”Ð•Ð™Ð¡Ð¢Ð’Ð˜Ð¯:\n- Ð’ÑÐµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð·Ð°ÐºÐ°Ð·Ñ‹ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½Ñ‹\n- Ð’Ð¾Ð·Ð²Ñ€Ð°Ñ‚ Ð² Ñ€ÐµÐ¶Ð¸Ð¼ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ñ‹Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¹\n- ÐÐ°Ð¹Ð´Ñƒ Ð°Ð»ÑŒÑ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ñ‹Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚, Ð¸Ð·Ð±ÐµÐ³Ð°ÑŽÑ‰Ð¸Ð¹ Ð¾Ð¿Ð°ÑÐ½Ñ‹Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð²\n- ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð³Ñ€ÑƒÐ·Ð°: ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ°Ñ (Ð¿Ñ€Ð¾Ð´Ð°ÑÑ‚ Ð»ÑŽÐ±Ð¾Ð¹ Ð³Ñ€ÑƒÐ· Ð² Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾Ð¼ Ð¼ÐµÑÑ‚Ðµ Ð¿Ñ€Ð¸ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ÑÑ‚Ð¸)\n\nÐ”Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÑÐºÐ°Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ° Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸Ñ‚ Ð±ÑƒÐ´ÑƒÑ‰Ð¸Ðµ ÑÐ´ÐµÐ»ÐºÐ¸ Ñ‡ÐµÑ€ÐµÐ· ÑÑ‚Ð¾Ñ‚ ÑÐµÐºÑ‚Ð¾Ñ€ Ð´Ð¾ Ñ‚ÐµÑ… Ð¿Ð¾Ñ€, Ð¿Ð¾ÐºÐ° ÑƒÐ³Ñ€Ð¾Ð·Ð° Ð½Ðµ Ð±ÑƒÐ´ÐµÑ‚ ÑƒÑÑ‚Ñ€Ð°Ð½ÐµÐ½Ð°.\n\nÐ‘ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚ÑŒ - Ð¼Ð¾Ð¹ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð¾Ð¼ÐµÑ€ Ð¾Ð´Ð¸Ð½.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %3</t>
    <t id="3210">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ˜ÐÐ˜Ð¦Ð˜Ð˜Ð ÐžÐ’ÐÐ ÐœÐÐ Ð¨Ð Ð£Ð¢ ÐŸÐžÐ‘Ð•Ð“Ð\n\nÐ¯ ÑÐµÐ¹Ñ‡Ð°Ñ Ð² Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ð¼ ÑÐµÐºÑ‚Ð¾Ñ€Ðµ %1 Ð¸ Ð½Ð°ÑˆÐµÐ» Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ð¹ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚ Ð¼Ð½Ðµ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ ÑƒÐ¹Ñ‚Ð¸.\n\nÐ¢ÐžÐ Ð“ÐžÐ’Ð«Ð™ ÐœÐÐ Ð¨Ð Ð£Ð¢:\nÐšÑƒÐ¿Ð¸Ñ‚ÑŒ: %2 (Ð¡ÐµÐºÑ‚Ð¾Ñ€: %3)\nÐŸÑ€Ð¾Ð´Ð°Ñ‚ÑŒ: %4 (Ð¡ÐµÐºÑ‚Ð¾Ñ€: %5)\nÐ¢Ð¾Ð²Ð°Ñ€: %6 (x%7)\nÐžÐ¶Ð¸Ð´Ð°ÐµÐ¼Ð°Ñ ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ: %8 Cr\n\nÐšÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð¿Ð¾ÐºÐ¸Ð½ÐµÑ‚ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ð¿Ð¾ÑÐ»Ðµ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ñ ÑÑ‚Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐš Ð²Ð°ÑˆÐ¸Ð¼ ÑƒÑÐ»ÑƒÐ³Ð°Ð¼</t>
    <t id="3211">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ Ð•Ð–Ð˜Ðœ Ð˜Ð—ÐžÐ›Ð˜Ð ÐžÐ’ÐÐÐÐžÐ™ Ð¢ÐžÐ Ð“ÐžÐ’Ð›Ð˜\n\nÐ¯ ÑÐµÐ¹Ñ‡Ð°Ñ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ %2, Ð½Ð¾ Ð²ÑÐµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ Ðº Ð´Ñ€ÑƒÐ³Ð¸Ð¼ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ñ‹ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ ÑƒÐ·Ð»Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼Ð¸. Ð­Ñ‚Ð¾ Ð¾Ð·Ð½Ð°Ñ‡Ð°ÐµÑ‚, Ñ‡Ñ‚Ð¾ Ñ Ð¼Ð¾Ð³Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð² Ð¿Ñ€ÐµÐ´ÐµÐ»Ð°Ñ… Ð¼Ð¾ÐµÐ³Ð¾ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°, Ð¿Ð¾ÐºÐ° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸Ñ Ñ Ñ‡ÐµÑ€Ð½Ñ‹Ð¼ ÑÐ¿Ð¸ÑÐºÐ¾Ð¼ Ð½Ðµ Ð¸Ð·Ð¼ÐµÐ½Ð¸Ñ‚ÑÑ.\n\nÐ¡Ð˜Ð¢Ð£ÐÐ¦Ð˜Ð¯:\nÐ¢ÐµÐºÑƒÑ‰Ð¸Ð¹ Ð¡ÐµÐºÑ‚Ð¾Ñ€: %2\nÐ¡Ñ‚Ð°Ñ‚ÑƒÑ: Ð˜Ð·Ð¾Ð»Ð¸Ñ€Ð¾Ð²Ð°Ð½ (Ð½ÐµÐ·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ñ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð°Ð¼Ð¸)\nÐ ÐµÐ¶Ð¸Ð¼ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸: Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð²Ð½ÑƒÑ‚Ñ€Ð¸ÑÐµÐºÑ‚Ð¾Ñ€Ð½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸\n\nÐœÐ¾Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ ÑÐºÐ¾Ñ€Ñ€ÐµÐºÑ‚Ð¸Ñ€Ð¾Ð²Ð°Ð»Ð° Ð¿Ð¾Ñ€Ð¾Ð³Ð¸ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸ Ð´Ð»Ñ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚Ð¸Ð·Ð°Ñ†Ð¸Ð¸ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹Ñ… Ð²Ð½ÑƒÑ‚Ñ€Ð¸ÑÐµÐºÑ‚Ð¾Ñ€Ð½Ñ‹Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ÐµÐ¹.\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ñƒ ÑÐ»ÐµÐ´Ð¸Ñ‚ÑŒ Ð·Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÐµÐ¹ Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐµÑÐ»Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ ÑÐ½Ð¾Ð²Ð° ÑÑ‚Ð°Ð½ÑƒÑ‚ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %1</t>
    <t id="3218">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐžÐ‘ÐÐÐ Ð£Ð–Ð•ÐÐž Ð˜Ð—ÐœÐ•ÐÐ•ÐÐ˜Ð• ÐœÐÐ Ð¨Ð Ð£Ð¢Ð\n\nÐŸÑ€Ð¸ Ð²Ñ…Ð¾Ð´Ðµ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %1 Ð¼Ð¾Ñ Ð½Ð°Ð²Ð¸Ð³Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð°Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð¾Ð±Ð½Ð°Ñ€ÑƒÐ¶Ð¸Ð»Ð°, Ñ‡Ñ‚Ð¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ðº Ð¼Ð¾ÐµÐ¼Ñƒ Ð¿ÑƒÐ½ÐºÑ‚Ñƒ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ %2 (%3) Ð¸Ð·Ð¼ÐµÐ½Ð¸Ð»ÑÑ.\n\nÐÐÐÐ›Ð˜Ð— ÐœÐÐ Ð¨Ð Ð£Ð¢Ð:\n- ÐÐ¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ: %4 Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð²\n- Ð Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ñ ÑƒÑ‡ÐµÑ‚Ð¾Ð¼ Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ°: %5\n- Ð¡Ñ‚Ð°Ñ‚ÑƒÑ: %6\n\nÐœÐ¾Ð¹ Ð½Ð°Ð²Ð¸Ð³Ð°Ñ†Ð¸Ð¾Ð½Ð½Ñ‹Ð¹ ÐºÐ¾Ð¼Ð¿ÑŒÑŽÑ‚ÐµÑ€ ÑƒÐºÐ°Ð·Ñ‹Ð²Ð°ÐµÑ‚, Ñ‡Ñ‚Ð¾ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ñ‚Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð½Ðµ Ð¶Ð¸Ð·Ð½ÐµÑÐ¿Ð¾ÑÐ¾Ð±ÐµÐ½ Ð¸Ð·-Ð·Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ð¹ Ð½Ð° Ð¿ÐµÑ€ÐµÐ¼ÐµÑ‰ÐµÐ½Ð¸Ðµ Ð¼ÐµÐ¶Ð´Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼Ð¸. Ð Ð°Ð´Ð¸ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ð¸ ÑÐºÐ¸Ð¿Ð°Ð¶Ð° Ñ Ð½ÐµÐ¼ÐµÐ´Ð»ÐµÐ½Ð½Ð¾ Ð¿Ñ€ÐµÑ€Ñ‹Ð²Ð°ÑŽ Ñ‚ÐµÐºÑƒÑ‰ÑƒÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÑƒÑŽ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸ÑŽ.\n\nÐŸÐ Ð•Ð”ÐŸÐ Ð˜ÐÐ¯Ð¢Ð«Ð• Ð”Ð•Ð™Ð¡Ð¢Ð’Ð˜Ð¯:\n- Ð’ÑÐµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð·Ð°ÐºÐ°Ð·Ñ‹ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½Ñ‹\n- Ð’Ð¾Ð·Ð²Ñ€Ð°Ñ‚ Ð² Ñ€ÐµÐ¶Ð¸Ð¼ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ñ‹Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¹\n- ÐÐ°Ð¹Ð´Ñƒ Ð°Ð»ÑŒÑ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ñ‹Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚, Ð¸Ð·Ð±ÐµÐ³Ð°ÑŽÑ‰Ð¸Ð¹ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð²\n- ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð³Ñ€ÑƒÐ·Ð°: ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ°Ñ (Ð¿Ñ€Ð¾Ð´Ð°ÑÑ‚ Ð»ÑŽÐ±Ð¾Ð¹ Ð³Ñ€ÑƒÐ· Ð² Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾Ð¼ Ð¼ÐµÑÑ‚Ðµ Ð¿Ñ€Ð¸ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ÑÑ‚Ð¸)\n\nÐœÐ¾Ñ Ð½Ð°Ð²Ð¸Ð³Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð°Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð±ÑƒÐ´ÐµÑ‚ Ð¸Ð·Ð±ÐµÐ³Ð°Ñ‚ÑŒ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð² Ð¿Ñ€Ð¸ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ð¸ Ð±ÑƒÐ´ÑƒÑ‰Ð¸Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð².\n\nÐ‘ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚ÑŒ - Ð¼Ð¾Ð¹ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð¾Ð¼ÐµÑ€ Ð¾Ð´Ð¸Ð½.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %7</t>
    <t id="3219">Ð¡ÐµÐºÑ‚Ð¾Ñ€ %1 Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½ - Ð’ÑÐµ ÑƒÐ³Ñ€Ð¾Ð·Ñ‹ ÑƒÑÑ‚Ñ€Ð°Ð½ÐµÐ½Ñ‹</t>
    <t id="3220">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ’Ð ÐÐ–Ð•Ð¡ÐšÐ˜Ð™ ÐšÐžÐ ÐÐ‘Ð›Ð¬ Ð¡ÐšÐ Ð«Ð›Ð¡Ð¯\n\nÐÐ°ÑˆÐ° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð°Ð·Ð²ÐµÐ´ÐºÐ¸ ÑƒÐ³Ñ€Ð¾Ð· Ð¿Ð¾Ñ‚ÐµÑ€ÑÐ»Ð° ÑÐ»ÐµÐ´ Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¾Ð³Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ %3, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ð¹ Ð¿Ð¾ÐºÐ¸Ð½ÑƒÐ» ÑÐµÐºÑ‚Ð¾Ñ€ Ð¸Ð· Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ° %1.\n\nÐ”Ð•Ð¢ÐÐ›Ð˜:\n- Ð¡ÐºÑ€Ñ‹Ð²ÑˆÐ¸Ð¹ÑÑ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ: %3\n- ÐŸÐ¾ÐºÐ¸Ð½ÑƒÑ‚Ñ‹Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€: %1\n- Ð¡ÐµÐºÑ‚Ð¾Ñ€ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ: %2\n- Ð¡Ñ‚Ð°Ñ‚ÑƒÑ: ÐžÑ‚ÑÐ»ÐµÐ¶Ð¸Ð²Ð°Ð½Ð¸Ðµ Ð¿Ð¾Ñ‚ÐµÑ€ÑÐ½Ð¾ - ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð¿Ð¾ÐºÐ¸Ð½ÑƒÐ» Ð½Ð°ÑˆÑƒ ÐºÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€ÑƒÐµÐ¼ÑƒÑŽ Ð·Ð¾Ð½Ñƒ\n\nÐ¥Ð¾Ñ‚Ñ ÑÑ‚Ð¾Ñ‚ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð½Ðµ Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ ÑƒÐ³Ñ€Ð¾Ð·Ñ‹ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ %1, Ð¼Ñ‹ Ð¿Ð¾Ñ‚ÐµÑ€ÑÐ»Ð¸ Ð²Ð¸Ð·ÑƒÐ°Ð»ÑŒÐ½Ñ‹Ð¹ ÐºÐ¾Ð½Ñ‚Ð°ÐºÑ‚ Ð¸ Ð½Ðµ Ð¼Ð¾Ð¶ÐµÐ¼ Ð¿Ð¾Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¸Ñ‚ÑŒ ÐµÐ³Ð¾ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ð¹ ÑÑ‚Ð°Ñ‚ÑƒÑ Ð¸Ð»Ð¸ Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸Ñ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ %2.\n\nÐÐ°ÑˆÐ¸ ÑÐ¸ÑÑ‚ÐµÐ¼Ñ‹ Ð¾Ñ‚ÑÐ»ÐµÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ð°Ñ‚ Ð¼Ð¾Ð½Ð¸Ñ‚Ð¾Ñ€Ð¸Ð½Ð³ ÑÐµÐºÑ‚Ð¾Ñ€Ð° %1 Ð½Ð° Ð¿Ñ€ÐµÐ´Ð¼ÐµÑ‚ Ð¾ÑÑ‚Ð°Ð²ÑˆÐ¸Ñ…ÑÑ ÑƒÐ³Ñ€Ð¾Ð·. Ð•ÑÐ»Ð¸ Ð²ÑÐµ Ð¾Ñ‚ÑÐ»ÐµÐ¶Ð¸Ð²Ð°ÐµÐ¼Ñ‹Ðµ Ð²Ñ€Ð°Ð³Ð¸ Ð¿Ð¾ÐºÐ¸Ð½ÑƒÑ‚ ÑÐµÐºÑ‚Ð¾Ñ€ Ð¸Ð»Ð¸ Ð±ÑƒÐ´ÑƒÑ‚ ÑƒÐ½Ð¸Ñ‡Ñ‚Ð¾Ð¶ÐµÐ½Ñ‹, ÑÐµÐºÑ‚Ð¾Ñ€ Ð±ÑƒÐ´ÐµÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ ÑƒÐ´Ð°Ð»ÐµÐ½ Ð¸Ð· Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ°.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒÑŽ,\nÐ¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð°Ð·Ð²ÐµÐ´ÐºÐ¸ ÑƒÐ³Ñ€Ð¾Ð·</t>
    <t id="3221">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¯ Ð½Ðµ ÑÐ¼Ð¾Ð³ Ð½Ð°Ð¹Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð° Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸ÑÑ… (Ð´Ð¾ %3 Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð²), Ð¿Ð¾ÑÐºÐ¾Ð»ÑŒÐºÑƒ ÑÑ‚Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ Ð² Ð½Ð°ÑÑ‚Ð¾ÑÑ‰ÐµÐµ Ð²Ñ€ÐµÐ¼Ñ Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹ Ð¸Ð·-Ð·Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ð¹ Ð½Ð° Ð¿ÐµÑ€ÐµÐ¼ÐµÑ‰ÐµÐ½Ð¸Ðµ Ð¼ÐµÐ¶Ð´Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼Ð¸ (Ð¿ÑƒÑ‚Ð¸ Ð² Ñ‡ÐµÑ€Ð½Ð¾Ð¼ ÑÐ¿Ð¸ÑÐºÐµ).\n\nÐ¡Ð˜Ð¢Ð£ÐÐ¦Ð˜Ð¯:\nÐ¢ÐµÐºÑƒÑ‰Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€: %2\nÐ˜ÑÑ…Ð¾Ð´Ð½Ñ‹Ð¹ Ð´Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½ Ð¿Ð¾Ð¸ÑÐºÐ°: %3 Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð²\nÐ ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ð¹ Ð´Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½ Ð¿Ð¾Ð¸ÑÐºÐ°: %4 Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð²\n\nÐ¢ÐµÐ¿ÐµÑ€ÑŒ Ñ ÑÐ¾ÑÑ€ÐµÐ´Ð¾Ñ‚Ð¾Ñ‡Ñƒ ÑÐ²Ð¾Ð¹ Ð¿Ð¾Ð¸ÑÐº Ð½Ð° Ð±Ð»Ð¸Ð·Ð»ÐµÐ¶Ð°Ñ‰Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ð² Ð¿Ñ€ÐµÐ´ÐµÐ»Ð°Ñ… %4 Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð², Ð³Ð´Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ Ñ Ð±Ð¾Ð»ÑŒÑˆÐµÐ¹ Ð²ÐµÑ€Ð¾ÑÑ‚Ð½Ð¾ÑÑ‚ÑŒÑŽ Ð±ÑƒÐ´ÑƒÑ‚ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹. Ð­Ñ‚Ð¾ Ð´Ð¾Ð»Ð¶Ð½Ð¾ Ð¿Ð¾Ð¼Ð¾Ñ‡ÑŒ Ð¼Ð½Ðµ Ð½Ð°Ð¹Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ Ñ€Ð°Ð½ÐµÐµ Ð±Ñ‹Ð»Ð¸ Ð¾Ñ‚Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ð¾Ð²Ð°Ð½Ñ‹ Ð¸Ð·-Ð·Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ð¹ Ð¿Ð¾ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸ÑŽ, Ð° Ð½Ðµ Ð¸Ð·-Ð·Ð° Ñ„Ð°ÐºÑ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ð¹ ÑƒÐ±Ñ‹Ñ‚Ð¾Ñ‡Ð½Ð¾ÑÑ‚Ð¸.\n\nÐ¯ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð¹Ð´Ñƒ Ð¿Ð¾Ð´Ñ…Ð¾Ð´ÑÑ‰Ð¸Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð² Ð±Ð»Ð¸Ð·Ð»ÐµÐ¶Ð°Ñ‰ÐµÐ¹ Ð¾Ð±Ð»Ð°ÑÑ‚Ð¸.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %1</t>
    <t id="3222">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¡Ð•ÐšÐ¢ÐžÐ  Ð’ Ð§Ð•Ð ÐÐžÐœ Ð¡ÐŸÐ˜Ð¡ÐšÐ•\n\nÐÐ°ÑˆÐ° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð°Ð·Ð²ÐµÐ´ÐºÐ¸ ÑƒÐ³Ñ€Ð¾Ð· Ð¾Ð±Ð½Ð°Ñ€ÑƒÐ¶Ð¸Ð»Ð° Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½ÑƒÑŽ Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚ÑŒ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ %1 Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð´Ð¾Ð±Ð°Ð²Ð¸Ð»Ð° ÑÑ‚Ð¾Ñ‚ ÑÐµÐºÑ‚Ð¾Ñ€ Ð² Ñ‡ÐµÑ€Ð½Ñ‹Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº Ð´Ð»Ñ Ð·Ð°Ñ‰Ð¸Ñ‚Ñ‹ Ð½Ð°ÑˆÐ¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¹.\n\nÐžÐ‘ÐÐÐ Ð£Ð–Ð•ÐÐÐ«Ð• Ð’Ð ÐÐ–Ð•Ð¡ÐšÐ˜Ð• ÐšÐžÐ ÐÐ‘Ð›Ð˜:\n%2\n\nÐžÐ‘ÐÐÐ Ð£Ð–Ð•ÐÐž: %3\n\nÐ”Ð»Ñ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ð¸ Ð½Ð°ÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ð¸ ÑÐºÐ¸Ð¿Ð°Ð¶ÐµÐ¹ Ð²ÑÐµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ‹ Ñ‡ÐµÑ€ÐµÐ· ÑÑ‚Ð¾Ñ‚ ÑÐµÐºÑ‚Ð¾Ñ€ Ð±Ñ‹Ð»Ð¸ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ñ‹. ÐÐ°ÑˆÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð±ÑƒÐ´ÑƒÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¾ÐºÐ»Ð°Ð´Ñ‹Ð²Ð°Ñ‚ÑŒ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ð² Ð¾Ð±Ñ…Ð¾Ð´ ÑÑ‚Ð¾Ð³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð° Ð´Ð¾ Ñ‚ÐµÑ… Ð¿Ð¾Ñ€, Ð¿Ð¾ÐºÐ° ÑƒÐ³Ñ€Ð¾Ð·Ð° Ð½Ðµ Ð±ÑƒÐ´ÐµÑ‚ ÑƒÑÑ‚Ñ€Ð°Ð½ÐµÐ½Ð°.\n\nÐ¡ÐµÐºÑ‚Ð¾Ñ€ Ð±ÑƒÐ´ÐµÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ ÑƒÐ´Ð°Ð»ÐµÐ½ Ð¸Ð· Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ°, ÐºÐ°Ðº Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð²ÑÐµ Ð¾Ñ‚ÑÐ»ÐµÐ¶Ð¸Ð²Ð°ÐµÐ¼Ñ‹Ðµ Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¸Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð±ÑƒÐ´ÑƒÑ‚ ÑƒÐ½Ð¸Ñ‡Ñ‚Ð¾Ð¶ÐµÐ½Ñ‹ Ð¸Ð»Ð¸ Ð¿Ð¾ÐºÐ¸Ð½ÑƒÑ‚ Ñ‚ÐµÑ€Ñ€Ð¸Ñ‚Ð¾Ñ€Ð¸ÑŽ.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒÑŽ,\nÐ¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð°Ð·Ð²ÐµÐ´ÐºÐ¸ ÑƒÐ³Ñ€Ð¾Ð·</t>
    <t id="3223">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¯ Ð½Ðµ Ð¼Ð¾Ð³Ñƒ Ð½Ð°Ð¹Ñ‚Ð¸ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½ÑƒÑŽ ÑƒÑ‡ÐµÐ±Ð½ÑƒÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ Ð´Ð»Ñ Ð¼Ð¾ÐµÐ³Ð¾ ÑÐºÐ·Ð°Ð¼ÐµÐ½Ð° ÑƒÑ€Ð¾Ð²Ð½Ñ %1. Ð¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸, ÐºÐ°Ðº ÑƒÐºÐ°Ð·Ð°Ð½Ð¾, Ð½Ð¾ Ð¿Ð¾Ð½Ð¸Ð¼Ð°ÑŽ, Ñ‡Ñ‚Ð¾ Ð½Ðµ Ð±ÑƒÐ´Ñƒ Ð¿Ð¾Ð»ÑƒÑ‡Ð°Ñ‚ÑŒ Ð¾Ñ‡ÐºÐ¸ Ð¾Ð¿Ñ‹Ñ‚Ð°, Ð¿Ð¾ÐºÐ° Ð½Ðµ ÑÐ¼Ð¾Ð³Ñƒ Ð¿Ñ€Ð¾Ð¹Ñ‚Ð¸ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾Ðµ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ. ÐŸÐ¾ÑÐ»Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ñ€ÐµÐ¹ÑÐ° Ñ ÑÐ½Ð¾Ð²Ð° Ð¿Ð¾Ð¸Ñ‰Ñƒ Ð»ÑŽÐ±ÑƒÑŽ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½ÑƒÑŽ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ÑŒ Ð´Ð»Ñ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸ÐµÐ¼,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %2</t>
    <t id="3224">ÐŸÐ»Ð°Ñ‚Ð° Ð·Ð° Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸ÑŽ Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ: %1 Cr</t>
    <t id="3225">Ð‘Ð¾Ð½ÑƒÑ: Ð¯ Ð¿Ð¾Ð»ÑƒÑ‡Ð¸Ð» %1 Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ Ð½Ð°Ð²Ñ‹ÐºÐ°%2 Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ð½Ð°ÐºÐ¾Ð¿Ð»ÐµÐ½Ð½Ð¾Ð¼Ñƒ Ð¾Ð¿Ñ‹Ñ‚Ñƒ Ð²Ð¾ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ! Ð¢ÐµÐºÑƒÑ‰Ð¸Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ: %3</t>
    <t id="3214">Ð”Ð»Ñ Ð¼ÐµÐ½Ñ Ñ‡ÐµÑÑ‚ÑŒ Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚ÑŒ Ð½Ð° Ð²Ð°Ñ, %1! Ð¯ Ñ€Ð°Ð´ Ð½Ð°Ñ‡Ð°Ñ‚ÑŒ ÑÐ²Ð¾ÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÑƒÑŽ ÐºÐ°Ñ€ÑŒÐµÑ€Ñƒ Ð¿Ð¾Ð´ Ð²Ð°ÑˆÐ¸Ð¼ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¾Ð²Ð°Ð½Ð¸ÐµÐ¼. Ð¯ ÑÐ´ÐµÐ»Ð°ÑŽ Ð²ÑÐµ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾Ðµ, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ñ…Ð¾Ñ€Ð¾ÑˆÐ¾ ÑÐ»ÑƒÐ¶Ð¸Ñ‚ÑŒ Ð²Ð°Ð¼ Ð¸ Ð²Ð½ÐµÑÑ‚Ð¸ Ð²ÐºÐ»Ð°Ð´ Ð² Ð²Ð°Ñˆ ÑƒÑÐ¿ÐµÑ….</t>
    <t id="3215">Ð¡Ð¿Ð°ÑÐ¸Ð±Ð¾ Ð·Ð° ÑÑ‚Ð¾Ñ‚ Ð·Ð°ÑÐ»ÑƒÐ¶ÐµÐ½Ð½Ñ‹Ð¹ Ð¾Ñ‚Ð¿ÑƒÑÐº, %1! Ð¯ Ð½Ð°ÑÐ»Ð°Ð´Ð¸Ð»ÑÑ Ð²Ñ€ÐµÐ¼ÐµÐ½ÐµÐ¼ Ð²Ð´Ð°Ð»Ð¸ Ð¾Ñ‚ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸, Ð¸ Ð¼Ð¾Ð¸ Ð½Ð°Ð²Ñ‹ÐºÐ¸ Ð¾ÑÑ‚Ð°Ð»Ð¸ÑÑŒ Ð½ÐµÑ‚Ñ€Ð¾Ð½ÑƒÑ‚Ñ‹Ð¼Ð¸. Ð¯ Ñ Ð½ÐµÑ‚ÐµÑ€Ð¿ÐµÐ½Ð¸ÐµÐ¼ Ð¶Ð´Ñƒ Ð²Ð¾Ð·Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ Ðº Ñ€Ð°Ð±Ð¾Ñ‚Ðµ, ÐºÐ¾Ð³Ð´Ð° Ð²Ñ‹ Ð±ÑƒÐ´ÐµÑ‚Ðµ Ð½ÑƒÐ¶Ð´Ð°Ñ‚ÑŒÑÑ Ð²Ð¾ Ð¼Ð½Ðµ. Ð”Ð¾ Ñ‚ÐµÑ… Ð¿Ð¾Ñ€ Ñ Ð±ÑƒÐ´Ñƒ Ð´ÐµÑ€Ð¶Ð°Ñ‚ÑŒ ÑÐ²Ð¾Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð·Ð½Ð°Ð½Ð¸Ñ Ð¾ÑÑ‚Ñ€Ñ‹Ð¼Ð¸!</t>
    <t id="3216">Ð¯ Ð²ÐµÑ€Ð½ÑƒÐ»ÑÑ Ð¸Ð· Ð¾Ñ‚Ð¿ÑƒÑÐºÐ° Ð¸ Ð³Ð¾Ñ‚Ð¾Ð² ÑÐ½Ð¾Ð²Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚ÑŒ, %1! ÐœÐ¾Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð½Ð°Ð²Ñ‹ÐºÐ¸ Ð¾ÑÑ‚Ð°ÑŽÑ‚ÑÑ Ð¾ÑÑ‚Ñ€Ñ‹Ð¼Ð¸, Ð¸ Ñ ÑÑ‚Ñ€ÐµÐ¼Ð»ÑŽÑÑŒ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ð¸Ñ‚ÑŒ ÑÐ»ÑƒÐ¶Ð¸Ñ‚ÑŒ Ð²Ð°Ð¼ Ð½Ð° %2. Ð¡Ð¿Ð°ÑÐ¸Ð±Ð¾ Ð·Ð° Ð·Ð°ÑÐ»ÑƒÐ¶ÐµÐ½Ð½Ñ‹Ð¹ Ð¾Ñ‚Ð´Ñ‹Ñ…!</t>
    <t id="3217">Ð¡Ð¿Ð°ÑÐ¸Ð±Ð¾ Ð·Ð° Ð¼Ð¾Ð¹ Ð¿ÐµÑ€ÐµÐ²Ð¾Ð´ Ð½Ð° %1, %2! Ð¯ ÑƒÐ´Ð¾ÑÑ‚Ð¾ÐµÐ½ ÑÑ‚Ð¾Ð³Ð¾ Ð½Ð¾Ð²Ð¾Ð³Ð¾ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¸ Ð±ÑƒÐ´Ñƒ Ð¾Ñ‚Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð°Ð±Ð¾Ñ‚Ð¸Ñ‚ÑŒÑÑ Ð¾ ÑÐ²Ð¾ÐµÐ¼ Ð½Ð¾Ð²Ð¾Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»Ðµ. ÐœÐ¾Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ Ð¾Ð¿Ñ‹Ñ‚ Ð¸ Ð½Ð°Ð²Ñ‹ÐºÐ¸ Ð¾ÑÑ‚Ð°ÑŽÑ‚ÑÑ Ð½ÐµÑ‚Ñ€Ð¾Ð½ÑƒÑ‚Ñ‹Ð¼Ð¸, Ð¸ Ñ Ð³Ð¾Ñ‚Ð¾Ð² Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ð¸Ñ‚ÑŒ ÑÐ»ÑƒÐ¶Ð¸Ñ‚ÑŒ Ð²Ð°Ð¼.</t>
    <t id="3227">ÐšÐ¾Ñ€Ð¿ÑƒÑ Ð¿Ð¾Ñ‚ÐµÑ€ÑÐ½, Ð´Ð¾ÑÑ‚Ð¾Ð¸Ð½ÑÑ‚Ð²Ð¾ Ð¶Ð´Ñ‘Ñ‚ ÑÐ²Ð°ÐºÑƒÐ°Ñ†Ð¸Ð¸</t>
    <t id="3228">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\n%2 Ð´Ð¾ÐºÐ»Ð°Ð´Ñ‹Ð²Ð°ÐµÑ‚ Ð¸Ð· %3. ÐœÐ¾Ð¹ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð²Ð·Ð¾Ñ€Ð²Ð°Ð»ÑÑ. Ð¯ - Ð½ÐµÑ‚. Ð¢ÐµÐ¿ÐµÑ€ÑŒ Ñ ÑÐ°Ð¼Ñ‹Ð¹ Ð´Ð¾Ñ€Ð¾Ð³Ð¾Ð¹ Ð¿Ð»Ð°Ð²Ð°ÑŽÑ‰Ð¸Ð¹ Ð³Ñ€ÑƒÐ· Ñ„Ð»Ð¾Ñ‚Ð°.\n\nÐœÐµÑ‚ÐºÐ° Ð½Ð° ÐºÐ°Ñ€Ñ‚Ðµ Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð°. ÐŸÐ¾Ð¶Ð°Ð»ÑƒÐ¹ÑÑ‚Ð°, Ð¿Ð¾Ñ‚Ð¾Ñ€Ð¾Ð¿Ð¸Ñ‚ÐµÑÑŒ - Ñ Ð±Ñ‹Ð» Ð½Ð° ÑÐµÑ€ÐµÐ´Ð¸Ð½Ðµ ÑÑ‡Ñ‘Ñ‚Ð°.\n\nÐŸÑ€Ð¾Ñ„ÐµÑÑÐ¸Ð¾Ð½Ð°Ð»ÑŒÐ½Ð¾ Ð´Ñ€ÐµÐ¹Ñ„ÑƒÑŽ,\n%2</t>
    <t id="3229">ÐŸÐ¸Ð»Ð¾Ñ‚ ÑÐ¿Ð°ÑÑ‘Ð½ - ÐºÐ¸ÑÐ»Ð¾Ñ€Ð¾Ð´Ð½Ð°Ñ Ð·Ð°Ð²Ð¸ÑÐ¸Ð¼Ð¾ÑÑ‚ÑŒ Ð¸Ð·Ð»ÐµÑ‡ÐµÐ½Ð°</t>
    <t id="3230">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐžÐ±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ðµ Ñ„Ð»Ð¾Ñ‚Ð°: %2 Ð¿Ð¾Ð´Ð¾Ð±Ñ€Ð°Ð½ %3 (%4) Ð¸ Ð¿Ñ€ÐµÐºÑ€Ð°Ñ‚Ð¸Ð» Ð²Ñ‹ÑÑ‚Ð°Ð²Ð»ÑÑ‚ÑŒ Ð²Ð°Ð¼ ÑÑ‡ÐµÑ‚Ð° Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð»Ñ‘Ð½Ð½ÑƒÑŽ EVA-Ð¿Ð¾Ð´Ð³Ð¾Ñ‚Ð¾Ð²ÐºÑƒ.\n\nÐŸÐµÑ€ÐµÐ¿Ñ€Ð¸Ð²ÑÐ·ÐºÐ° Ñ€ÐµÐµÑÑ‚Ñ€Ð° Ð² Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐµ. Ð ÐµÐºÐ¾Ð¼ÐµÐ½Ð´Ð°Ñ†Ð¸Ñ: Ð½Ðµ Ð·Ð°Ð´Ð°Ð²Ð°Ñ‚ÑŒ Ð²Ð¾Ð¿Ñ€Ð¾ÑÐ¾Ð² Ð¾ ÑÑ‚Ð°Ñ€Ð¾Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»Ðµ.\n\nÐ¡Ð¾ ÑÑ‚Ñ‹Ð´Ð¾Ð¼,\n%2</t>
<t id="4000">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ñ„Ð»Ð¾Ñ‚Ð°: %s Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½ Ð½Ð° Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s</t>
    <t id="4001">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ñ„Ð»Ð¾Ñ‚Ð°: ÐœÐ°Ñ€ÑˆÑ€ÑƒÑ‚ %s Ð¿Ð¾Ð»Ð½Ð¾ÑÑ‚ÑŒÑŽ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ</t>
    <t id="4002">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ñ„Ð»Ð¾Ñ‚Ð°: %s Ð¾ÑÐ²Ð¾Ð±Ð¾Ð´Ð¸Ð» Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s</t>
    <t id="5000">%s Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¾Ð¹ Ñ‚ÐµÑ€Ñ€Ð¸Ñ‚Ð¾Ñ€Ð¸ÐµÐ¹ Ð´Ð»Ñ %s</t>
    <t id="5001">%s Ð´Ð¾ÑÑ‚Ð¸Ð³ ÑƒÑ€Ð¾Ð²Ð½Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð¸Ð·Ñ‹ %s Ð² %s!</t>
    <t id="5002">Ð‘Ð¾Ð½ÑƒÑ Ñ‚ÐµÑ€Ñ€Ð¸Ñ‚Ð¾Ñ€Ð¸Ð¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÐµÐ½: %s%% ÑƒÐ²ÐµÐ»Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸ Ð² %s</t>
    <t id="9500">ÐžÑˆÐ¸Ð±ÐºÐ°: %s Ð·Ð°ÑÑ‚Ñ€ÑÐ» Ð¸ Ð½ÑƒÐ¶Ð´Ð°ÐµÑ‚ÑÑ Ð² Ð¿Ð¾Ð¼Ð¾Ñ‰Ð¸!</t>
    <t id="9501">ÐžÑˆÐ¸Ð±ÐºÐ°: Ð¡Ð´ÐµÐ»ÐºÐ° Ð¿Ñ€Ð¾Ð²Ð°Ð»Ð¸Ð»Ð°ÑÑŒ Ð´Ð»Ñ %s</t>
    <t id="9502">ÐžÑˆÐ¸Ð±ÐºÐ°: ÐÐµÐ²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ Ð·Ð°Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ %s Ð² GalaxyTrader MK3</t>
    <t id="80001">Ð¢Ð¾Ð²Ð°Ñ€ %s Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½ Ð² Ñ‡ÐµÑ€Ð½Ñ‹Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº</t>
    <t id="80002">Ð¢Ð¾Ð²Ð°Ñ€ %s ÑƒÐ´Ð°Ð»ÐµÐ½ Ð¸Ð· Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ°</t>
    <t id="80003">Ð¢Ð¾Ð²Ð°Ñ€ %s Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½ Ð² Ð±ÐµÐ»Ñ‹Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº</t>
    <t id="80004">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½ (Ð¿Ð»Ð¾Ñ…Ð°Ñ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ): %s</t>
    <t id="80005">ÐžÐ¿Ð°ÑÐ½Ñ‹Ð¹ Ñ‚Ð¾Ð²Ð°Ñ€ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½: %s</t>
    <t id="80006">Ð¤Ð¸Ð»ÑŒÑ‚Ñ€ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²: %s Ð°ÐºÑ‚Ð¸Ð²ÐµÐ½, %s Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ñ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð°</t>
    <t id="80007">Ð’ÑÐµ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ñ‹ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½Ñ‹</t>
    <t id="80008">Ð¤Ð¸Ð»ÑŒÑ‚Ñ€Ñ‹ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² ÑÐ±Ñ€Ð¾ÑˆÐµÐ½Ñ‹ Ð½Ð° Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="80009">Ð£Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð¤Ð¸Ð»ÑŒÑ‚Ñ€Ð°Ð¼Ð¸ Ð¢Ð¾Ð²Ð°Ñ€Ð¾Ð²</t>
    <t id="80010">Ð—Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ð¢Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="80011">Ð Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð½Ñ‹Ðµ Ð¢Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="80012">ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° ÐžÐ¿Ð°ÑÐ½Ñ‹Ñ… Ð¢Ð¾Ð²Ð°Ñ€Ð¾Ð²</t>
    <t id="80013">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¡Ñ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚ÑŒ Ð¢Ð¾Ð²Ð°Ñ€Ð°</t>
    <t id="80014">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¡Ñ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚ÑŒ Ð¢Ð¾Ð²Ð°Ñ€Ð°</t>
    <t id="80015">ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð½Ñ‹Ðµ Ð¤Ñ€Ð°ÐºÑ†Ð¸Ð¸</t>
    <t id="80016">ÐšÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ñ‹ Ð¸Ð· Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð¸Ð³Ñ€Ñ‹</t>
    <t id="80017">%s Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¾: %s Ð½Ð¸Ð·ÐºÐ¾Ð¹ ÑÑ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚Ð¸, %s Ð¾Ð¿Ð°ÑÐ½Ñ‹Ñ…, %s Ð²Ñ‹ÑÐ¾ÐºÐ¾Ð¹ ÑÑ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚Ð¸</t>
    <t id="80018">Ð”Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÑÐºÐ°Ñ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ð¸Ñ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð°</t>
    <t id="80019">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ°Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ° Ð´Ð»Ñ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð¸ %s Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð°</t>
    <t id="80020">ÐÐ¾Ð²Ñ‹Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹ Ð¸Ð· Ð´Ñ€ÑƒÐ³Ð¸Ñ… Ð¼Ð¾Ð´Ð¾Ð² Ð¾Ð±Ð½Ð°Ñ€ÑƒÐ¶ÐµÐ½Ñ‹ Ð¸ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ñ‹</t>
    <t id="9000">GalaxyTrader - Ð“Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ‹Ðµ ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="9010">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° XP Ð¸ ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ñ</t>
    <t id="9012">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="9013">ÐœÐ½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»ÑŒ XP</t>
    <t id="9015">ÐŸÑ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð‘Ð¾Ð½ÑƒÑÐ° ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°</t>
    <t id="9020">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð¤Ð»Ð¾Ñ‚Ð°</t>
    <t id="9021">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÑŽ Ð¤Ð»Ð¾Ñ‚Ð°</t>
    <t id="9023">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ ÐšÑÑˆ</t>
    <t id="9030">Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ</t>
    <t id="9031">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹</t>
    <t id="9040">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ð³Ð¾ Ð ÐµÐ¼Ð¾Ð½Ñ‚Ð°</t>
    <t id="9041">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ð ÐµÐ¼Ð¾Ð½Ñ‚</t>
    <t id="9042">ÐŸÐ¾Ñ€Ð¾Ð³ Ð ÐµÐ¼Ð¾Ð½Ñ‚Ð° ÐšÐ¾Ñ€Ð¿ÑƒÑÐ°</t>
    <t id="9310">Ð“Ð°Ð»Ð°ÐºÑ‚Ð¸ÐºÐ°-Ð¨Ð°Ñ…Ñ‚ÐµÑ€</t>
    <t id="9311">ÐžÐ¶Ð¸Ð´Ð°Ð½Ð¸Ðµ ÑÐºÐ°Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ð·Ð¾Ð½Ð´Ð¾Ð² Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ</t>
    <t id="9312">Ð’ÐµÑ Ð±Ð»Ð¸Ð·Ð¾ÑÑ‚Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="9043">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ ÐŸÐ¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="9004">Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½Ñ‹ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¦ÐµÐ½</t>
    <t id="9005">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¦ÐµÐ½Ð° ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ ÐŸÑ€Ð¾Ð´Ð°Ð¶Ð¸</t>
    <t id="9006">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¦ÐµÐ½Ð° ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ¸</t>
    <t id="9007">Ð˜Ð·Ð¾Ð»Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ: ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¦ÐµÐ½Ð° ÐŸÑ€Ð¾Ð´Ð°Ð¶Ð¸</t>
    <t id="9008">Ð˜Ð·Ð¾Ð»Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ: ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¦ÐµÐ½Ð° ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ¸</t>
    <t id="9009">Ð ÐµÐ·ÐµÑ€Ð²: ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¦ÐµÐ½Ð° ÐŸÑ€Ð¾Ð´Ð°Ð¶Ð¸</t>
    <t id="9014">Ð ÐµÐ·ÐµÑ€Ð²: ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¦ÐµÐ½Ð° ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ¸</t>
    <t id="9016">Ð‘Ð°Ð·Ð¾Ð²Ñ‹Ð¹ ÐŸÐ¾Ñ€Ð¾Ð³ ÐŸÑ€Ð¸Ð±Ñ‹Ð»Ð¸</t>
    <t id="9025">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ð´ÐµÐ½ÑŒÐ³Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ°</t>
    <t id="9024">Ð”Ð¾Ð¿ÑƒÑÐº ÐŸÐ°Ð´ÐµÐ½Ð¸Ñ ÐšÑÑˆÐ°</t>
    <t id="9026">Ð’Ñ€ÐµÐ¼Ñ Ð¿Ñ€Ð¾ÑÑ‚Ð¾Ñ Ð¿ÐµÑ€ÐµÐ´ Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´ÐµÐ½Ð¸ÐµÐ¼ Ð¿Ð¾Ñ€Ñ‚Ð°</t>
    <t id="9054">Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¡ÐµÐºÑ‚Ð¾Ñ€Ñ‹ Ð’Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ñ‹Ñ… Ð¤Ñ€Ð°ÐºÑ†Ð¸Ð¹</t>
    <t id="9055">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð£Ð³Ñ€Ð¾Ð·Ñ‹ Ð§ÐµÑ€Ð½Ð¾Ð³Ð¾ Ð¡Ð¿Ð¸ÑÐºÐ°</t>
    <t id="9056">Ð’Ð¾ÑÑÐ¾Ð·Ð´Ð°Ñ‚ÑŒ Ð§ÐµÑ€Ð½Ñ‹Ð¹ Ð¡Ð¿Ð¸ÑÐ¾Ðº</t>
    <t id="9057">Ð’Ð¾ÑÑÐ¾Ð·Ð´Ð°Ñ‚ÑŒ</t>
    <t id="9058">ÐÐ°Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÑŒ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ GT</t>
    <t id="9059">ÐÐ°Ð·Ð½Ð°Ñ‡Ð°Ñ‚ÑŒ</t>
    <t id="9112">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²Ð»ÑÐµÑ‚ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ, ÐºÐ¾Ð³Ð´Ð° Ð¾Ð½Ð¸ Ð´Ð¾ÑÑ‚Ð¸Ð³Ð°ÑŽÑ‚ Ñ‚Ñ€ÐµÐ±ÑƒÐµÐ¼Ñ‹Ñ… ÑƒÑ€Ð¾Ð²Ð½ÐµÐ¹. ÐžÑ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ðµ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð³Ð¾ ÐºÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ñ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ.</t>
    <t id="9113">Ð ÐµÐ³ÑƒÐ»Ð¸Ñ€ÑƒÐµÑ‚ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð¾Ð¿Ñ‹Ñ‚Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð·Ð½Ð°Ñ‡Ð°ÑŽÑ‚ Ð±Ð¾Ð»ÐµÐµ Ð±Ñ‹ÑÑ‚Ñ€ÑƒÑŽ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑÐ¸ÑŽ.</t>
    <t id="9115">ÐŸÑ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð¾Ð¿Ñ‹Ñ‚Ð° Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð½Ñ‹Ñ…, Ð¿Ñ€Ð¸ÑÑƒÐ¶Ð´Ð°ÐµÐ¼Ñ‹Ð¹ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð¾Ð². Ð£ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚Ðµ 0%, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð±Ð¾Ð½ÑƒÑÐ½Ñ‹Ð¹ Ð¾Ð¿Ñ‹Ñ‚ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 10%.</t>
    <t id="9121">Ð’ÐºÐ»ÑŽÑ‡Ð°ÐµÑ‚ Ð¸Ð½Ñ‚ÐµÐ»Ð»ÐµÐºÑ‚ÑƒÐ°Ð»ÑŒÐ½Ñ‹Ðµ Ñ„ÑƒÐ½ÐºÑ†Ð¸Ð¸ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ð¸ Ñ„Ð»Ð¾Ñ‚Ð°, Ð²ÐºÐ»ÑŽÑ‡Ð°Ñ Ð¾Ð¿Ñ‚Ð¸Ð¼Ð¸Ð·Ð°Ñ†Ð¸ÑŽ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð² Ð¸ Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð¾Ð²ÐºÑƒ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸.</t>
    <t id="9123">ÐŸÐ¾Ð·Ð²Ð¾Ð»ÑÐµÑ‚ Ð´ÐµÐ»Ð¸Ñ‚ÑŒÑÑ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¼Ð¸ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ÑÐ¼Ð¸ Ð¼ÐµÐ¶Ð´Ñƒ Ñ‡Ð»ÐµÐ½Ð°Ð¼Ð¸ Ñ„Ð»Ð¾Ñ‚Ð° Ð´Ð»Ñ Ð»ÑƒÑ‡ÑˆÐµÐ¹ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ð¸.</t>
    <t id="9131">ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€ÑƒÐµÑ‚ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ð¾ÐºÐ°Ð·Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ñ… ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹: 0=Ð¢Ð¸Ñ…Ð¾, 1=Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð²Ð°Ð¶Ð½Ñ‹Ðµ, 2=Ð’ÑÐµ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ</t>
    <t id="9141">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²Ð»ÑÐµÑ‚ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð½Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ Ð¿Ð¾ÑÐ»Ðµ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ñ ÑÐ´ÐµÐ»Ð¾Ðº, ÐºÐ¾Ð³Ð´Ð° ÐºÐ¾Ñ€Ð¿ÑƒÑ Ð¿Ð°Ð´Ð°ÐµÑ‚ Ð½Ð¸Ð¶Ðµ Ð¿Ð¾Ñ€Ð¾Ð³Ð°. Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ Ð¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² (Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ 12+). ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð²Ñ‹Ð±Ð¸Ñ€Ð°ÑŽÑ‚ ÑÐ¾Ð¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²ÑƒÑŽÑ‰ÐµÐµ ÑÐ¾Ð¾Ñ€ÑƒÐ¶ÐµÐ½Ð¸Ðµ: S/M Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ ÐžÐ±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ, L/XL Ð’ÐµÑ€Ñ„ÑŒ.</t>
    <t id="9142">ÐŸÑ€Ð¾Ñ†ÐµÐ½Ñ‚ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ°, Ð½Ð¸Ð¶Ðµ ÐºÐ¾Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ ÑÑ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 95%. ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð½Ð°Ð¿Ñ€Ð°Ð²ÑÑ‚ÑÑ Ðº Ð±Ð»Ð¸Ð¶Ð°Ð¹ÑˆÐµÐ¼Ñƒ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð¾Ð¼Ñƒ ÑÐ¾Ð¾Ñ€ÑƒÐ¶ÐµÐ½Ð¸ÑŽ Ð¿Ñ€Ð¸ Ð¿Ð¾Ð²Ñ€ÐµÐ¶Ð´ÐµÐ½Ð¸Ð¸.</t>
    <t id="9411">Ð•ÑÐ»Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, ÑˆÐ°Ñ…Ñ‚Ñ‘Ñ€Ñ‹ Ð¶Ð´ÑƒÑ‚ Ð¿Ñ€Ð¸ Ð¾Ñ†ÐµÐ½ÐºÐµ Ñ€ÐµÑÑƒÑ€ÑÐ½Ñ‹Ñ… Ð·Ð¾Ð½Ð´Ð¾Ð² Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ðµ (+5 Ñ Ð·Ð° ÐºÐ°Ð¶Ð´ÑƒÑŽ Ð·Ð¾Ð½Ð´ ÑÐ²ÐµÑ€Ñ… Ð¾Ð´Ð½Ð¾Ð¹). Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ GT Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð»Ð¸Ð½ÐµÐ¹Ð½Ð¾ ÑÐ¾ÐºÑ€Ð°Ñ‰Ð°ÐµÑ‚ ÑÑ‚Ð¾ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ðµ Ð¾Ñ‚ Ð¿Ð¾Ð»Ð½Ð¾Ð³Ð¾ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð¸ Ð½Ð° ÑƒÑ€Ð¾Ð²Ð½Ðµ 1 Ð´Ð¾ 5 ÑÐµÐºÑƒÐ½Ð´ Ð½Ð° ÑƒÑ€Ð¾Ð²Ð½Ðµ 15 (Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ñ€ÐµÐ¶Ð¸Ð¼ GT XP, ÐµÑÐ»Ð¸ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ðµ Ð¿Ñ€ÐµÐ²Ñ‹ÑˆÐ°ÐµÑ‚ 5 Ñ). Ð’Ñ‹ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ = Ð±ÐµÐ· Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ (Ð¿Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ðµ vanilla).</t>
    <t id="9412">Ð¡Ð¼ÐµÑ‰Ð°ÐµÑ‚ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ MK3/MK4 Ðº Ð±Ð¾Ð»ÐµÐµ Ð±Ð»Ð¸Ð·ÐºÐ¸Ð¼ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÐ¼ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð¿Ñ€Ð¸ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐµ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐµÐ½Ð½Ñ‹Ñ… ÑÐ´ÐµÐ»Ð¾Ðº. ÐžÑ†ÐµÐ½ÐºÐ° Ð²Ñ‹Ð±Ð¾Ñ€Ð° = Ð¾Ñ†ÐµÐ½ÐºÐ° ÑÐ´ÐµÐ»ÐºÐ¸ / (1 + Ð¿Ñ€Ñ‹Ð¶ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒâ†’Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ã— Ð²ÐµÑ). ÐŸÐ¾Ð»Ð·ÑƒÐ½Ð¾Ðº 0-100 (0 = Ð²Ñ‹ÐºÐ».; 4 = Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ 0,04). ÐÐµ Ð²Ð»Ð¸ÑÐµÑ‚ Ð½Ð° Ñ€ÐµÐ¹Ñ‚Ð¸Ð½Ð³ ÐºÑÑˆÐ° Ð¸ Ñ‚ÐµÑ€Ñ€Ð¸Ñ‚Ð¾Ñ€Ð¸Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ð»Ð¸Ð¼Ð¸Ñ‚Ñ‹ Ð´Ð°Ð»ÑŒÐ½Ð¾ÑÑ‚Ð¸.</t>
    <t id="9143">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°, Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ñ‹Ð¹ Ð´Ð»Ñ Ñ„ÑƒÐ½ÐºÑ†Ð¸Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 12 (Ð¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ‹). ÐŸÐ¸Ð»Ð¾Ñ‚Ñ‹ Ð±Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¾Ð³Ð¾ ÑƒÑ€Ð¾Ð²Ð½Ñ Ð´Ð¾Ð»Ð¶Ð½Ñ‹ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð²Ñ€ÑƒÑ‡Ð½ÑƒÑŽ.</t>
    <t id="9104">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¾Ñ‚Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ (ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð¿Ð¾ÐºÑƒÐ¿Ð°ÐµÑ‚ Ð£ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1.0 Ð´Ð¾ +1.0. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 0.5 (50% Ð²Ñ‹ÑˆÐµ ÑÑ€ÐµÐ´Ð½ÐµÐ³Ð¾). Ð’Ñ‹ÑˆÐµ = Ð´Ð¾Ñ€Ð¾Ð¶Ðµ, Ð½Ð¾ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¾Ð¿Ñ†Ð¸Ð¹.</t>
    <t id="9105">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¾Ñ‚Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ (ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð¿Ñ€Ð¾Ð´Ð°ÐµÑ‚ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÐ¼). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1.0 Ð´Ð¾ +1.0. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: -0.5 (50% Ð½Ð¸Ð¶Ðµ ÑÑ€ÐµÐ´Ð½ÐµÐ³Ð¾). ÐÐ¸Ð¶Ðµ = Ð±Ð¾Ð»ÐµÐµ Ð´ÐµÑˆÐµÐ²Ñ‹Ðµ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ð¸, Ð½Ð¾ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¾Ð¿Ñ†Ð¸Ð¹.</t>
    <t id="9106">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ Ð´Ð»Ñ Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ (Ð·Ð°ÑÑ‚Ñ€ÑÐ²ÑˆÐ¸Ñ… Ð² Ð¾Ð´Ð½Ð¾Ð¼ ÑÐµÐºÑ‚Ð¾Ñ€Ðµ). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1.0 Ð´Ð¾ +1.0. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 0.5.</t>
    <t id="9107">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð´Ð»Ñ Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ (Ð·Ð°ÑÑ‚Ñ€ÑÐ²ÑˆÐ¸Ñ… Ð² Ð¾Ð´Ð½Ð¾Ð¼ ÑÐµÐºÑ‚Ð¾Ñ€Ðµ). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1.0 Ð´Ð¾ +1.0. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: -0.5.</t>
    <t id="9108">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ Ð´Ð»Ñ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ° (Ð¿Ð¾ÑÐ»ÐµÐ´Ð½ÐµÐµ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð¾, ÐºÐ¾Ð³Ð´Ð° Ð¾Ð±Ñ‹Ñ‡Ð½Ñ‹Ð¹ Ð¿Ð¾Ð¸ÑÐº Ð½Ðµ ÑƒÐ´Ð°ÐµÑ‚ÑÑ). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1.0 Ð´Ð¾ +1.0. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 0.5. Ð ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ð¹ Ð¿Ð¾Ð¸ÑÐº Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ MaxDistance=2 Ð¸ Ñ€Ð°ÑÑÐ»Ð°Ð±Ð»ÐµÐ½Ð½Ñ‹Ðµ Ð¿Ð¾Ñ€Ð¾Ð³Ð¸ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸.</t>
    <t id="9109">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð´Ð»Ñ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ° (Ð¿Ð¾ÑÐ»ÐµÐ´Ð½ÐµÐµ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð¾, ÐºÐ¾Ð³Ð´Ð° Ð¾Ð±Ñ‹Ñ‡Ð½Ñ‹Ð¹ Ð¿Ð¾Ð¸ÑÐº Ð½Ðµ ÑƒÐ´Ð°ÐµÑ‚ÑÑ). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1.0 Ð´Ð¾ +1.0. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: -0.5. Ð ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ð¹ Ð¿Ð¾Ð¸ÑÐº Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ MaxDistance=2 Ð¸ Ñ€Ð°ÑÑÐ»Ð°Ð±Ð»ÐµÐ½Ð½Ñ‹Ðµ Ð¿Ð¾Ñ€Ð¾Ð³Ð¸ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸.</t>
    <t id="9116">Ð‘Ð°Ð·Ð¾Ð²Ð°Ñ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ Ð½Ð° ÑƒÑ€Ð¾Ð²Ð½Ðµ 15 Ð´Ð»Ñ ÑÑ€ÐµÐ´Ð½ÐµÐ³Ð¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ð° (ÑÐ¿Ñ€Ð°Ð²Ð¾Ñ‡Ð½Ñ‹Ð¹ Ð³Ñ€ÑƒÐ· 8200). Ð¤Ð°ÐºÑ‚Ð¸Ñ‡ÐµÑÐºÐ°Ñ Ð¼Ð¸Ð½Ð°Ð±ÑÐ¾Ð»ÑŽÑ‚Ð½Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ Ñ€Ð°ÑÑÑ‡Ð¸Ñ‚Ñ‹Ð²Ð°ÐµÑ‚ÑÑ Ð² Ñ€Ð°ÑÑ‡ÐµÑ‚Ðµ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° + Ð² Ð¼Ð°ÑÑˆÑ‚Ð°Ð±Ðµ Ð¾Ñ‚ Ð³Ñ€ÑƒÐ·Ð°: \n\nbase(L) = Ð±Ð°Ð·Ð° * ((L-1) _2 / 14__2) \nscald = Ð¾ÑÐ½Ð¾Ð²Ð°(L) * (Ð³Ñ€ÑƒÐ· / 8200) \nfinal = Ð¼Ð°ÐºÑ. (Ð¼Ð°ÑÑˆÑ‚Ð°Ð±, 25% Ð¾Ñ‚ Ð±Ð°Ð·Ñ‹(L) \n\nSet-0 Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð»ÑŽÐ±Ð¾Ð¹ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸ (Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ ROI/Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ/Ð´Ñ€ÑƒÐ³Ð¸Ðµ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ñ‹).</t>
    <t id="9125">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ð´ÐµÐ½ÑŒÐ³Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ° (ÐºÑ€ÐµÐ´Ð¸Ñ‚Ñ‹), Ñ‚Ñ€ÐµÐ±ÑƒÐµÐ¼Ñ‹Ðµ Ð´Ð¾ Ñ‚Ð¾Ð³Ð¾, ÐºÐ°Ðº ÑÑƒÐ´Ð° Ð±ÑƒÐ´ÑƒÑ‚ Ð¸ÑÐºÐ°Ñ‚ÑŒ ÑÐ´ÐµÐ»ÐºÐ¸. ÐšÐ¾Ð³Ð´Ð° Ð´ÐµÐ½ÑŒÐ³Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ° Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ÑÑ Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ð°, Ð²ÑÐµ ÑÑƒÐ´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ð¸ Ð²Ñ‹Ð¶Ð¸Ð´Ð°ÑŽÑ‚, Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰Ð°Ñ Ð´Ð¾Ñ€Ð¾Ð³Ð¾ÑÑ‚Ð¾ÑÑ‰ÐµÐµ ÑÐºÐ°Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐºÑÑˆÐ°, ÐºÐ¾Ñ‚Ð¾Ñ€Ð¾Ðµ Ð²Ñ‹Ð·Ñ‹Ð²Ð°ÐµÑ‚ Ð·Ð°Ð¸ÐºÐ°Ð½Ð¸Ðµ Ð¸Ð³Ñ€Ñ‹. Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: 1 000 - 100 000 Cr. name: 1 000 Cr.</t>
    <t id="9124">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚Ð½Ð¾Ðµ Ð¿Ð°Ð´ÐµÐ½Ð¸Ðµ ROI Ð¾Ñ‚ ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿ÐµÑ€ÐµÐ´ Ð¾Ñ‚ÐºÐ»Ð¾Ð½ÐµÐ½Ð¸ÐµÐ¼ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÑ€Ð¸Ð¼ÐµÑ€: 20% ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ð³Ð¾ ROI Ñ 15% Ð´Ð¾Ð¿ÑƒÑÐºÐ¾Ð¼ Ð¿Ñ€Ð¸Ð½Ð¸Ð¼Ð°ÐµÑ‚ Ð´Ð¾ 17% ROI (Ð¿Ð°Ð´ÐµÐ½Ð¸Ðµ Ð½Ð° 14%).</t>
    <t id="9126">ÐœÐ¸Ð½ÑƒÑ‚ Ñƒ Ð¿Ñ€Ð¸Ñ‡Ð°Ð»Ð° Ð¿ÐµÑ€ÐµÐ´ Ð¾Ñ‚ÑÑ‚Ñ‹ÐºÐ¾Ð²ÐºÐ¾Ð¹ Ð´Ð»Ñ Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¿Ð¾Ñ€Ñ‚Ð° (0-60). 0 = Ð¾ÑÑ‚Ð°Ñ‘Ñ‚ÑÑ Ñƒ Ð¿Ñ€Ð¸Ñ‡Ð°Ð»Ð°, Ð¿Ð¾ÐºÐ° Ð½Ðµ Ð½Ð°Ð¹Ð´Ñ‘Ñ‚ÑÑ Ð½Ð¾Ð²Ð°Ñ Ñ€Ð°Ð±Ð¾Ñ‚Ð°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1 Ð¼Ð¸Ð½ÑƒÑ‚Ð°.</t>
    <t id="9154">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€ÑƒÐµÑ‚ Ð²ÑÐµ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹, Ð¿Ñ€Ð¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð°Ñ‰Ð¸Ðµ Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ñ‹Ð¼ Ñ„Ñ€Ð°ÐºÑ†Ð¸ÑÐ¼ (Ñ„Ð»Ð°Ð¶Ð¾Ðº Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ñ Ð² Ñ‡ÐµÑ€Ð½Ð¾Ð¼ ÑÐ¿Ð¸ÑÐºÐµ)</t>
    <t id="9155">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ³Ñ€Ð¾Ð·Ñ‹ (1-5), Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ñ‹Ð¹ Ð´Ð»Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð°:\n2=Ð¡Ñ€ÐµÐ´Ð½Ð¸Ð¹ (Ð¾Ð´Ð¸Ð½Ð¾Ñ‡Ð½Ð°Ñ Ð°Ñ‚Ð°ÐºÐ°)\n3=Ð¡Ñ€ÐµÐ´Ð½Ðµ-Ð’Ñ‹ÑÐ¾ÐºÐ¸Ð¹ (Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ñ‹Ðµ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸)\n4=Ð’Ñ‹ÑÐ¾ÐºÐ¸Ð¹ (ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð²/Ñ€Ð°ÐºÐµÑ‚Ñ‹)\n5=ÐžÑ‡ÐµÐ½ÑŒ Ð’Ñ‹ÑÐ¾ÐºÐ¸Ð¹ (ÐšÑÐµÐ½Ð¾Ð½/ÐšÑ…Ð°Ð°Ðº)</t>
    <t id="9156">Ð’Ñ€ÑƒÑ‡Ð½ÑƒÑŽ Ð²Ð¾ÑÑÐ¾Ð·Ð´Ð°Ñ‚ÑŒ Ñ‡ÐµÑ€Ð½Ñ‹Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº Ð¸Ð·Ð±ÐµÐ³Ð°Ð½Ð¸Ñ ÑƒÐ³Ñ€Ð¾Ð· (Ð¿Ð¾Ð»ÐµÐ·Ð½Ð¾, ÐµÑÐ»Ð¸ Ð¾Ð½ Ð±Ñ‹Ð» ÑƒÐ´Ð°Ð»ÐµÐ½)</t>
    <t id="9157">Ð’Ñ€ÑƒÑ‡Ð½ÑƒÑŽ Ð½Ð°Ð·Ð½Ð°Ñ‡ÑŒÑ‚Ðµ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ð¹ Ð´Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ñ‡ÐµÑ€Ð½Ñ‹Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº Ð²ÑÐµÐ¼ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ ÐºÐ¾Ð¼Ð°Ð½Ð´ÑƒÑŽÑ‰ÐµÐ³Ð¾ Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼ GT. ÐŸÐ¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð½Ñ‹Ðµ Ð½Ð°ÑÐ»ÐµÐ´ÑƒÑŽÑ‚ Ð¾Ñ‚ ÑÐ²Ð¾ÐµÐ³Ð¾ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°.</t>
    <t id="6001">Ð£Ñ‡ÐµÐ½Ð¸Ðº</t>
    <t id="6002">ÐšÑƒÑ€ÑŒÐµÑ€</t>
    <t id="6003">ÐŸÐ¾ÑÑ‚Ð°Ð²Ñ‰Ð¸Ðº</t>
    <t id="6004">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†</t>
    <t id="6005">ÐšÑƒÐ¿ÐµÑ†</t>
    <t id="6006">ÐšÑƒÐ¿ÐµÑ† Ð”Ð°Ð»ÑŒÐ½ÐµÐ³Ð¾ Ð Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ñ</t>
    <t id="6101">Ð¡Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹</t>
    <t id="6102">ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹</t>
    <t id="6103">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾-ÐžÑ€Ð¸ÐµÐ½Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹</t>
    <t id="6104">Ð¢ÑÐ¶ÐµÐ»Ð°Ñ ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð°</t>
    <t id="6105">ÐŸÐ¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ° Ð‘Ð°ÑˆÐµÐ½</t>
    <t id="9050">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ð˜Ð·Ð±ÐµÐ³Ð°Ð½Ð¸Ñ Ð£Ð³Ñ€Ð¾Ð·</t>
    <t id="9051">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð˜Ð·Ð±ÐµÐ³Ð°Ð½Ð¸Ðµ Ð£Ð³Ñ€Ð¾Ð·:</t>
    <t id="9052">ÐŸÐ¾Ñ€Ð¾Ð³ Ð’Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ñ‹Ñ… ÐžÑ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ð¹:</t>
    <t id="9053">Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÑŒ Ð”Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ð§ÐµÑ€Ð½Ñ‹Ð¹ Ð¡Ð¿Ð¸ÑÐ¾Ðº:</t>
    <t id="9151">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ‹ Ð£Ñ€Ð¾Ð²Ð½Ñ 6+ Ð¾Ð±Ð½Ð°Ñ€ÑƒÐ¶Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ñ‹Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð¸ Ð¸Ð·Ð±ÐµÐ³Ð°ÑŽÑ‚ Ð¾Ð¿Ð°ÑÐ½Ñ‹Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð². ÐžÑ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ð¾ÑÑ‚Ð°Ð½Ð°Ð²Ð»Ð¸Ð²Ð°ÐµÑ‚ Ð²ÑÐµ ÑÐºÐ°Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ (ÑƒÐ»ÑƒÑ‡ÑˆÐ°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ). Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ÑŒ Ðº Ñ€Ð¸ÑÐºÑƒ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð² Ð¿Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ð¸ ÐºÐ¾Ð¼Ð°Ð½Ð´Ñ‹ (ÑˆÐºÐ°Ð»Ð° 0-10).</t>
    <t id="9152">ÐŸÐ¾Ð¼ÐµÑ‡Ð°Ñ‚ÑŒ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸ Ñ Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸ÐµÐ¼ Ñ€Ð°Ð²Ð½Ñ‹Ð¼ Ð¸Ð»Ð¸ Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÐºÐ°Ðº ÑƒÐ³Ñ€Ð¾Ð·Ñ‹. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: -20%</t>
    <t id="9153">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€ÑƒÐµÑ‚ Ð¾Ð¿Ð°ÑÐ½Ñ‹Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹ (ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ³Ñ€Ð¾Ð·Ñ‹ 3+), Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð·Ð°ÑÑ‚Ð°Ð²Ð¸Ñ‚ÑŒ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð¾Ð±Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒ ÑƒÐ³Ñ€Ð¾Ð·Ñ‹. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ Ð²Ð°Ð½Ð¸Ð»ÑŒÐ½Ñ‹Ð¹ pathfinding Ð´Ð»Ñ Ð°Ð»ÑŒÑ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ñ‹Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¾Ð².</t>
    <t id="9060">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ ÐŸÐ¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð³Ð¾ ÐžÐ±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ (Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ 15)</t>
    <t id="9061">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ ÐŸÐ¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ:</t>
    <t id="9062">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ Ð¡Ñ€ÐµÐ´ÑÑ‚Ð²Ð° ÐŸÑ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ:</t>
    <t id="9063">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ Ð”Ñ€Ð¾Ð½Ñ‹ Ð—Ð°Ñ‰Ð¸Ñ‚Ñ‹:</t>
    <t id="9064">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð”Ñ€Ð¾Ð½Ñ‹:</t>
    <t id="9065">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ Ð›Ð°Ð·ÐµÑ€Ð½Ñ‹Ðµ Ð‘Ð°ÑˆÐ½Ð¸:</t>
    <t id="9066">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ Ð”Ñ€Ð¾Ð½Ñ‹ Ð ÐµÐ¼Ð¾Ð½Ñ‚Ð°:</t>
    <t id="9067">ÐŸÐ¾Ñ€Ð¾Ð³ Ð¡Ñ€ÐµÐ´ÑÑ‚Ð² ÐŸÑ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ:</t>
    <t id="9068">ÐŸÐ¾Ñ€Ð¾Ð³ Ð•Ð´Ð¸Ð½Ð¾Ð¹ Ð•Ð¼ÐºÐ¾ÑÑ‚Ð¸:</t>
    <t id="9069">ÐŸÑ€Ð¾Ñ„Ð¸Ð»ÑŒ Ð‘Ð°Ð»Ð°Ð½ÑÐ° ÐžÐ±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ñ:</t>
    <t id="9161">ÐœÐ°ÑÑ‚ÐµÑ€Ð° Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ‹ (Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ 15) Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÑÑŽÑ‚ Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ðµ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ðµ Ð¿Ð¾ÑÐ»Ðµ ÑÐ´ÐµÐ»Ð¾Ðº. ÐŸÑ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ Ðº ÑƒÑ€Ð¾Ð²Ð½ÑŽ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð° Ð´Ð»Ñ Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð½Ñ‹Ñ….</t>
    <t id="9162">Ð’ÑÐµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ (S/M/L/XL). ÐžÑ‚Ð´ÐµÐ»ÑŒÐ½Ð°Ñ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ. ÐšÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð´Ð»Ñ Ð·Ð°Ñ‰Ð¸Ñ‚Ñ‹ Ð¾Ñ‚ Ñ€Ð°ÐºÐµÑ‚.</t>
    <t id="9163">Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ L/XL. Ð”ÐµÐ»Ð¸Ñ‚ ÐµÐ´Ð¸Ð½ÑƒÑŽ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ Ñ Ð´Ñ€ÑƒÐ³Ð¸Ð¼Ð¸ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ð¼Ð¸ ÑƒÑÑ‚Ñ€Ð¾Ð¹ÑÑ‚Ð²Ð°Ð¼Ð¸.</t>
    <t id="9164">Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ L/XL. ÐÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ð´Ð»Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¹. Ð”ÐµÐ»Ð¸Ñ‚ ÐµÐ´Ð¸Ð½ÑƒÑŽ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ.</t>
    <t id="9165">Ð’ÑÐµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸. ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸ L/XL Ð´ÐµÐ»ÑÑ‚ ÐµÐ´Ð¸Ð½ÑƒÑŽ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ, S/M Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑŽÑ‚ Ð³Ñ€ÑƒÐ·.</t>
    <t id="9166">Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ L/XL. Ð Ð°Ð±Ð¾Ñ‚Ð°ÐµÑ‚ Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð°. Ð”ÐµÐ»Ð¸Ñ‚ ÐµÐ´Ð¸Ð½ÑƒÑŽ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ.</t>
    <t id="9167">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ, ÐºÐ¾Ð³Ð´Ð° ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° Ð¿Ñ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚Ð° (Ð²ÑÐµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸, Ð¾Ñ‚Ð´ÐµÐ»ÑŒÐ½Ð°Ñ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ).</t>
    <t id="9168">ÐŸÐ¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ, ÐºÐ¾Ð³Ð´Ð° Ð¾Ð±Ñ‰ÐµÐµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ñ… ÑƒÑÑ‚Ñ€Ð¾Ð¹ÑÑ‚Ð² Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚Ð° (ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ L/XL: Ð´Ñ€Ð¾Ð½Ñ‹ + Ð±Ð°ÑˆÐ½Ð¸ Ð´ÐµÐ»ÑÑ‚ Ð¾Ð´Ð½Ñƒ ÐµÐ¼ÐºÐ¾ÑÑ‚ÑŒ).</t>
    <t id="9169">Ð Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ ÐµÐ´Ð¸Ð½Ð¾Ð¹ ÐµÐ¼ÐºÐ¾ÑÑ‚Ð¸ (ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ L/XL): Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾-ÐžÑ€Ð¸ÐµÐ½Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹ (20/50/20/10), Ð¡Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¹ (35/35/20/10), ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ (50/20/20/10), Ð¢ÑÐ¶ÐµÐ»Ð°Ñ ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð° (40/30/20/10), ÐŸÐ¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ° Ð‘Ð°ÑˆÐµÐ½ (30/30/30/10). Ð¡Ð¾Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ñ: Ð—Ð°Ñ‰Ð¸Ñ‚Ð°/Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ñ/Ð‘Ð°ÑˆÐ½Ð¸/Ð ÐµÐ¼Ð¾Ð½Ñ‚. ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ð¾Ð¿Ñ†Ð¸Ð¹.</t>
    <t id="9090">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ ÐšÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9091">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ ÐšÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9191">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ ÑƒÑÑ‚Ð°Ð½Ð°Ð²Ð»Ð¸Ð²Ð°ÐµÑ‚ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ð¸ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ðµ ÑƒÑ€Ð¾Ð²Ð½Ñ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°. Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ 9+ = ÐœÐ¾Ð´Ñ‹ Ð£Ñ€Ð¾Ð²Ð½Ñ 1, Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ 12+ = ÐœÐ¾Ð´Ñ‹ Ð£Ñ€Ð¾Ð²Ð½Ñ 2, Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ 15+ = ÐœÐ¾Ð´Ñ‹ Ð£Ñ€Ð¾Ð²Ð½Ñ 3. Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð¼Ð¾Ð´Ñ‹, ÑƒÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ‹Ðµ GT, ÑƒÐ´Ð°Ð»ÑÑŽÑ‚ÑÑ Ð¿Ñ€Ð¸ Ð¾Ñ‚Ð¼ÐµÐ½Ðµ Ð·Ð°ÐºÐ°Ð·Ð°.</t>
    <t id="9070">ÐšÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð°Ñ†Ð¸Ñ Ð˜Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ñ ÐšÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9071">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ XP:</t>
    <t id="9072">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð Ð°Ð½Ð³:</t>
    <t id="9073">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ:</t>
    <t id="9074">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð¡Ñ‚Ð°Ñ‚ÑƒÑ:</t>
    <t id="9075">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÐŸÐµÑ€ÐµÐ¸Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐšÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹:</t>
    <t id="9076">ÐŸÑ€ÐµÑ„Ð¸ÐºÑ</t>
    <t id="9077">Ð¡ÑƒÑ„Ñ„Ð¸ÐºÑ</t>
    <t id="9078">Ð˜ÑÑ‚Ð¾Ñ‡Ð½Ð¸Ðº Ð˜Ð¼ÐµÐ½Ð¸ Ð¿Ð¾ Ð£Ð¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ:</t>
    <t id="9079">Ð˜Ð¼Ñ ÐœÐ¾Ð´ÐµÐ»Ð¸</t>
    <t id="9080">Ð˜Ð¼Ñ Ð¢Ð¸Ð¿Ð°</t>
    <t id="9081">Ð‘Ð°Ð·Ð¾Ð²Ð¾Ðµ Ð˜Ð¼Ñ</t>
    <t id="9083">Ð‘Ð°Ð·Ð¾Ð²Ð¾Ðµ Ð˜Ð¼Ñ</t>
    <t id="9084">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€:</t>
    <t id="9085">Ð ÐµÐ¶Ð¸Ð¼ Ð¸Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ñ:</t>
    <t id="9086">ÐšÐ»Ð°ÑÑÐ¸Ñ‡ÐµÑÐºÐ¸Ð¹</t>
    <t id="9087">Ð¨Ð°Ð±Ð»Ð¾Ð½</t>
    <t id="9088">Ð¨Ð°Ð±Ð»Ð¾Ð½ Ð¸Ð¼ÐµÐ½Ð¸:</t>
    <t id="9089">ÐœÐ°Ñ€ÐºÐµÑ€Ñ‹: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. ÐÑ‚Ð¾Ð¼Ð°Ñ€Ð½Ñ‹Ðµ: {RS} {CB} {BL} Ð¸ Ñ‚.Ð´. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ ÑÐ¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ð¹ Ð½Ð¸Ð¶Ðµ. ÐŸÑƒÑÑ‚Ñ‹Ðµ Ð¼Ð°Ñ€ÐºÐµÑ€Ñ‹ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ÑÑ; Ð¿Ñ€Ð¾Ð±ÐµÐ»Ñ‹ ÑÐ¶Ð¸Ð¼Ð°ÑŽÑ‚ÑÑ. ÐœÐ°ÐºÑ. 128 ÑÐ¸Ð¼Ð²Ð¾Ð»Ð¾Ð².</t>
    <t id="9183">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð½Ð°ÑÑ‚Ñ€Ð¾ÐµÐ½Ð½Ñ‹Ð¹ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ð² Ð¸Ð¼ÐµÐ½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ (Ð¿Ñ€ÐµÑ„Ð¸ÐºÑ Ð¸Ð»Ð¸ ÑÑƒÑ„Ñ„Ð¸ÐºÑ).</t>
    <t id="9184">ÐŸÐ¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÑÐºÐ¸Ð¹ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚ Ð¸Ð¼ÐµÐ½Ð¸ Ñ Ð¼Ð°Ñ€ÐºÐµÑ€Ð°Ð¼Ð¸ {TOKEN} Ð²Ð¼ÐµÑÑ‚Ð¾ ÐºÐ»Ð°ÑÑÐ¸Ñ‡ÐµÑÐºÐ¸Ñ… Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡Ð°Ñ‚ÐµÐ»ÐµÐ¹. Ð¢Ñ€ÐµÐ±ÑƒÐµÑ‚ÑÑ XP GalaxyTrader (Ð½Ðµ Ñ€ÐµÐ¶Ð¸Ð¼ vanilla XP).</t>
    <t id="9092">ÐœÐ°Ñ€ÐºÐµÑ€Ñ‹ ÑˆÐ°Ð±Ð»Ð¾Ð½Ð°</t>
    <t id="9093">ÐšÐ¾Ñ€Ð°Ð±Ð»ÑŒ: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">ÐžÐ¿Ñ‹Ñ‚ GT: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Ð’Ð°Ð½Ð¸Ð»ÑŒÐ½Ñ‹Ð¹ XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Ð”Ð¾Ð¼: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Ð­ÐºÐ¸Ð¿Ð°Ð¶: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Ð¡ÐµÐºÑ‚Ð¾Ñ€: {SECTOR} | Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">ÐœÐ°Ñ€ÐºÐµÑ€Ñ‹ ÑÑ‚Ð°Ñ‚ÑƒÑÐ°:</t>
    <t id="9100">{OPSTATE}: Ð²ÑÐµ Ð°ÐºÑ‚Ð¸Ð²Ð½Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¾Ð½Ð½Ñ‹Ðµ Ñ„Ð»Ð°Ð³Ð¸ (Ð½Ð°Ð¿Ñ€. CB RS, MT)</t>
    <t id="9101">{STATUS}: Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ°, Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ, Ñ€ÐµÐ·ÐµÑ€Ð² Ð¸Ð»Ð¸ Ð¸Ð·Ð¾Ð»ÑÑ†Ð¸Ñ</t>
    <t id="9102">{CB}: Ñ‚Ð¾Ð»ÑŒÐºÐ¾ ÑÐ²Ð¾Ñ blacklist; Ð²Ñ…Ð¾Ð´Ð¸Ñ‚ Ð² {OPSTATE}; Ð½Ðµ ÑÐ¾Ð²Ð¼ÐµÑ‰Ð°Ñ‚ÑŒ</t>
    <t id="9082">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ ÐšÐ»Ð°ÑÑ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ:</t>
    <t id="9171">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ XP Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9175">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¸Ð»Ð¸ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ Ð¿ÐµÑ€ÐµÐ¸Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸ÐµÐ¹ Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ðµ</t>
    <t id="9172">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¸Ñ‚ÑƒÐ»Ñ‹ Ñ€Ð°Ð½Ð³Ð° Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9173">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ð½Ð¾Ð¼ÐµÑ€Ð° ÑƒÑ€Ð¾Ð²Ð½ÐµÐ¹ Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9174">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¹ ÑÑ‚Ð°Ñ‚ÑƒÑ Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9178">Ð’Ñ‹Ð±ÐµÑ€Ð¸Ñ‚Ðµ Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸Ðº Ð´Ð»Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ñ… Ð¸Ð¼ÐµÐ½ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹: Ð˜Ð¼Ñ ÐœÐ¾Ð´ÐµÐ»Ð¸ (Ñ Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚Ð¾Ð¼), Ð˜Ð¼Ñ Ð¢Ð¸Ð¿Ð° (Ð¾Ð±Ñ‰ÐµÐµ), Ð¸Ð»Ð¸ Ð‘Ð°Ð·Ð¾Ð²Ð¾Ðµ Ð˜Ð¼Ñ (Ð±ÐµÐ· Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚Ð°)</t>
    <t id="9182">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°Ñ‚ÑŒ ÐºÐ»Ð°ÑÑ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ (S, M, L, XL) Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹</t>
    <t id="9200">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ ÐžÑ‚Ð»Ð°Ð´ÐºÐ¸</t>
    <t id="9201">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð›Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐžÑ‚Ð»Ð°Ð´ÐºÐ¸:</t>
    <t id="9202">Ð“Ð»Ð°Ð²Ð½Ñ‹Ð¹ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡Ð°Ñ‚ÐµÐ»ÑŒ Ð´Ð»Ñ Ð²ÑÐµÐ³Ð¾ Ð²Ñ‹Ð²Ð¾Ð´Ð° debug_text. ÐšÐ¾Ð³Ð´Ð° Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, Ð²ÑÐµ Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸ Ð¿Ð¾Ð´Ð°Ð²Ð»ÑÐµÑ‚ÑÑ. ÐšÐ¾Ð³Ð´Ð° Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸ Ð¿Ð¾ÑÐ²Ð»ÑÑŽÑ‚ÑÑ Ð² DebugLog Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ðµ Ð¸Ð½Ð´Ð¸Ð²Ð¸Ð´ÑƒÐ°Ð»ÑŒÐ½Ñ‹Ñ… Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ð¹ Ð²ÐµÑ€Ð¾ÑÑ‚Ð½Ð¾ÑÑ‚Ð¸ debug_text.</t>
    <t id="9220">Ð¢ÐµÑ…Ð½Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ ÐžÐ±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ðµ &amp; Ð”Ð¸Ð°Ð³Ð½Ð¾ÑÑ‚Ð¸ÐºÐ°</t>
    <t id="9221">Ð¡Ð±Ñ€Ð¾ÑÐ¸Ñ‚ÑŒ Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÑƒ ÐŸÑ€Ð¸Ð±Ñ‹Ð»Ð¸:</t>
    <t id="9222">Ð¡Ð‘Ð ÐžÐ¡Ð˜Ð¢Ð¬</t>
    <t id="9223">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚ÑŒ Ð’ÑÐµ Ð—Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ð¡ÐµÐºÑ‚Ð¾Ñ€Ñ‹:</t>
    <t id="9224">ÐžÐ§Ð˜Ð¡Ð¢Ð˜Ð¢Ð¬</t>
    <t id="9225">Ð¡Ð±Ñ€Ð¾ÑÐ¸Ñ‚ÑŒ Ð’ÑÐµ ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ ÐŸÐ¾ Ð£Ð¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ:</t>
    <t id="9226">Ð¡Ð‘Ð ÐžÐ¡Ð˜Ð¢Ð¬ Ð’Ð¡Ð•</t>
    <t id="9323">Ð£Ð´Ð°Ð»ÑÐµÑ‚ Ð²ÑÐµ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹ Ð¸Ð· Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ° Ñ€Ð°Ð·Ð²ÐµÐ´ÐºÐ¸ ÑƒÐ³Ñ€Ð¾Ð·. Ð­Ñ‚Ð¾ Ð½ÐµÐ¼ÐµÐ´Ð»ÐµÐ½Ð½Ð¾ Ð¾Ñ‡Ð¸ÑÑ‚Ð¸Ñ‚ Ð²ÑÐµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹ Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚ Ð²Ð°ÑˆÐ¸Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¾Ð²Ð°Ñ‚ÑŒ Ð² Ñ€Ð°Ð½ÐµÐµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ðµ Ð¾Ð±Ð»Ð°ÑÑ‚Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ ÑÑ‚Ð¾, ÐµÑÐ»Ð¸ Ð²Ñ‹ Ñ…Ð¾Ñ‚Ð¸Ñ‚Ðµ ÑÐ±Ñ€Ð¾ÑÐ¸Ñ‚ÑŒ ÑÐ¸ÑÑ‚ÐµÐ¼Ñƒ Ð¸Ð·Ð±ÐµÐ³Ð°Ð½Ð¸Ñ ÑƒÐ³Ñ€Ð¾Ð· Ð¸Ð»Ð¸ ÐµÑÐ»Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ñ‹ Ð±Ñ‹Ð»Ð¸ Ð½ÐµÐ¿Ñ€Ð°Ð²Ð¸Ð»ÑŒÐ½Ð¾ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ñ‹.</t>
    <t id="9321">Ð¡Ð±Ñ€Ð°ÑÑ‹Ð²Ð°ÐµÑ‚ Ð²ÑÑŽ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÑƒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸ Ð´Ð¾ 0 Ð´Ð»Ñ Ð²ÑÐµÑ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ ÑÑ‚Ð¾ Ð¿Ð¾ÑÐ»Ðµ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ð´Ð¾ v0.6.0 Ð´Ð»Ñ Ð¾Ñ‡Ð¸ÑÑ‚ÐºÐ¸ Ð·Ð°Ð²Ñ‹ÑˆÐµÐ½Ð½Ð¾Ð¹ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ¸ Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ðµ Ð´Ð¾Ñ…Ð¾Ð´Ð¾Ð². Ð˜ÑÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ñ‚ÐµÐ¿ÐµÑ€ÑŒ Ð¾Ñ‚ÑÐ»ÐµÐ¶Ð¸Ð²Ð°ÐµÑ‚ Ñ„Ð°ÐºÑ‚Ð¸Ñ‡ÐµÑÐºÑƒÑŽ ÐŸÐ Ð˜Ð‘Ð«Ð›Ð¬ (Ð´Ð¾Ñ…Ð¾Ð´Ñ‹ - ÑÑ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚ÑŒ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸). ÐšÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ ÑÐ´ÐµÐ»Ð¾Ðº Ð¸ XP ÑÐ¾Ñ…Ñ€Ð°Ð½ÑÑŽÑ‚ÑÑ.</t>
    <t id="9325">Ð¡Ð±Ñ€Ð°ÑÑ‹Ð²Ð°ÐµÑ‚ Ð²ÑÐµ Ð³Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ðº Ð¸Ñ… Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸ÑÐ¼ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ. Ð­Ñ‚Ð¾ Ð²ÐºÐ»ÑŽÑ‡Ð°ÐµÑ‚ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ XP, ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÑŽ Ð¤Ð»Ð¾Ñ‚Ð°, Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ, ÐœÐ¾Ð±Ð¸Ð»ÑŒÐ½ÑƒÑŽ Ð Ð°Ð·Ð²ÐµÐ´ÐºÑƒ, Ð˜Ð·Ð±ÐµÐ³Ð°Ð½Ð¸Ðµ Ð£Ð³Ñ€Ð¾Ð·, Ð˜Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐšÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹, ÐÐ²Ñ‚Ð¾-Ð ÐµÐ¼Ð¾Ð½Ñ‚, ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸, ÐŸÑ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð¸ Ð¤Ð¾Ñ€Ð¼Ð°Ñ‚ Ð§Ð¸ÑÐ»Ð°. ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ° Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸ ÑÐ¾Ñ…Ñ€Ð°Ð½ÑÐµÑ‚ÑÑ Ð´Ð»Ñ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð»Ð¾Ð³Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ ÑÐ±Ñ€Ð¾ÑÐ°.</t>
    <t id="9227">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚ÑŒ ÐºÑÑˆ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ Ð´Ð»Ñ Ð²ÑÐµÑ… Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð²:</t>
    <t id="9228">ÐžÐ§Ð˜Ð¡Ð¢Ð˜Ð¢Ð¬ ÐšÐ­Ð¨</t>
    <t id="9327">ÐžÑ‡Ð¸Ñ‰Ð°ÐµÑ‚ ÐºÑÑˆ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ Ð´Ð»Ñ Ð²ÑÐµÑ… Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð². Ð­Ñ‚Ð¾ Ð·Ð°ÑÑ‚Ð°Ð²Ð¸Ñ‚ Ð²ÑÐµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð²Ñ‹Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ ÑÐ²ÐµÐ¶Ð¸Ð¹ Ð¶Ð¸Ð²Ð¾Ð¹ Ð¿Ð¾Ð¸ÑÐº Ð¿Ñ€Ð¸ ÑÐ»ÐµÐ´ÑƒÑŽÑ‰ÐµÐ¼ Ð¿Ð¾Ð¸ÑÐºÐµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ ÑÑ‚Ð¾, ÐµÑÐ»Ð¸ ÐºÑÑˆ ÐºÐ°Ð¶ÐµÑ‚ÑÑ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ð¼ Ð¸Ð»Ð¸ Ð¿Ð¾Ð²Ñ€ÐµÐ¶Ð´ÐµÐ½Ð½Ñ‹Ð¼, Ð¸Ð»Ð¸ ÐµÑÐ»Ð¸ Ð²Ñ‹ Ñ…Ð¾Ñ‚Ð¸Ñ‚Ðµ Ð¿Ñ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ Ð¾Ð±Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ ÐºÑÑˆ.</t>
    <t id="9229">ÐžÑÐ²Ð¾Ð±Ð¾Ð´Ð¸Ñ‚ÑŒ Ð²ÑÐµ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾Ð¸ÑÐºÐ°</t>
    <t id="9329">ÐžÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°ÐµÑ‚ Ð’Ð¡Ð• Ð°ÐºÑ‚Ð¸Ð²Ð½Ñ‹Ðµ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾Ð¸ÑÐºÐ° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ Ð¸ Ð¾Ñ‡Ð¸Ñ‰Ð°ÐµÑ‚ ÑÐ²ÑÐ·Ð°Ð½Ð½Ñ‹Ðµ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ðµ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ ÑÑ‚Ð¾, ÐµÑÐ»Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð·Ð°ÑÑ‚Ñ€ÑÐ»Ð¸ Ð½Ð° Â«ÐŸÐ¾Ð¸ÑÐº Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹Â» Ð¸Ð·-Ð·Ð° ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ñ… Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð¾Ðº Ð¸Ð· ÑÑ‚Ð°Ñ€Ñ‹Ñ… ÑÐ¾Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ð¹. ÐœÐ¾Ð¶ÐµÑ‚ Ð¿Ñ€ÐµÑ€Ð²Ð°Ñ‚ÑŒ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸.</t>
    <t id="9290">Ð”Ð°Ð¼Ð¿ Ð¡Ñ‚Ð°Ñ‚ÑƒÑÐ° Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ð¥Ð°Ð±Ð°:</t>
    <t id="9291">Ð”ÐÐœÐŸ</t>
    <t id="9390">ÐŸÐ¾ÐºÐ°Ð·Ñ‹Ð²Ð°ÐµÑ‚ Ð¾Ð´Ð½Ð¾Ñ€Ð°Ð·Ð¾Ð²Ñ‹Ð¹ ÑÐ½Ð¸Ð¼Ð¾Ðº ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ñ†ÐµÐ½Ñ‚Ñ€Ð°Ð»Ð¸Ð·Ð¾Ð²Ð°Ð½Ð½Ð¾Ð³Ð¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ñ…Ð°Ð±Ð° (Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° + ÑÑ‚Ð°Ñ‚ÑƒÑ Ð¿Ð¾ÑÐ»ÐµÐ´Ð½ÐµÐ³Ð¾ Ð·Ð°Ð¿Ñ€Ð°ÑˆÐ¸Ð²Ð°ÑŽÑ‰ÐµÐ³Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ) Ð² Ð»Ð¾Ð³Ðµ Ð¸ Ð² Ð²Ð¸Ð´Ðµ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ.</t>
    <t id="9292">Ð”Ð°Ð¼Ð¿ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ ÐšÑÑˆÐ° (ÐŸÐžÐ›ÐÐ«Ð™):</t>
    <t id="9293">Ð”ÐÐœÐŸ ÐšÐ­Ð¨Ð</t>
    <t id="9392">ÐŸÐžÐ›ÐÐ«Ð™ Ð´Ð°Ð¼Ð¿ ÐºÑÑˆÐ° (Ð¼Ð¾Ð¶ÐµÑ‚ Ð±Ñ‹Ñ‚ÑŒ Ð¾Ð³Ñ€Ð¾Ð¼Ð½Ñ‹Ð¼). Ð—Ð°Ð¿Ð¸ÑÑ‹Ð²Ð°ÐµÑ‚ Ð²ÑÐµ Ð·Ð°Ð¿Ð¸ÑÐ¸ ÐºÑÑˆÐ° Ð² DebugLog Ñ‡Ð°ÑÑ‚ÑÐ¼Ð¸. ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ ÑÐ½Ð¾Ð²Ð° Ð´Ð»Ñ Ð¾Ñ‚Ð¼ÐµÐ½Ñ‹.</t>
    <t id="9294">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚ÑŒ Ñ€ÐµÐ·ÐµÑ€Ð²Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ Ñ„Ð»Ð¾Ñ‚Ð°:</t>
    <t id="9295">ÐŸÐ ÐžÐ—Ð ÐÐ§ÐÐ«Ð™</t>
    <t id="9394">ÐžÑ‡Ð¸Ñ‰Ð°ÐµÑ‚ Ð²ÑÐµ Ð°ÐºÑ‚Ð¸Ð²Ð½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ñ€ÐµÐ·ÐµÑ€Ð²Ð°Ñ†Ð¸Ð¸ Ñ„Ð»Ð¾Ñ‚Ð°. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ ÑÑ‚Ð¾, ÐµÑÐ»Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð·Ð°ÑÑ‚Ñ€ÑÐ»Ð¸ Ð² Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ð¸ Ð¸ÑÑ‚ÐµÑ‡ÐµÐ½Ð¸Ñ ÑÑ€Ð¾ÐºÐ° Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ Ð·Ð°Ñ€ÐµÐ·ÐµÑ€Ð²Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… ÑÐ´ÐµÐ»Ð¾Ðº Ð¸Ð»Ð¸ ÐµÑÐ»Ð¸ Ñ‚Ð°Ð±Ð»Ð¸Ñ†Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ ÑƒÑÑ‚Ð°Ñ€ÐµÐ»Ð° Ð¿Ð¾ÑÐ»Ðµ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ ÑÑ‚Ð°Ñ€Ð¾Ð³Ð¾ ÑÐ¾Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ.</t>
    <t id="9230">ÐŸÑ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ</t>
    <t id="9231">Ð—Ð°Ð´ÐµÑ€Ð¶ÐºÐ° ÐŸÐ°ÐºÐµÑ‚Ð½Ð¾Ð¹ ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸:</t>
    <t id="9232">Ð—Ð°Ð´ÐµÑ€Ð¶ÐºÐ° Ð’Ð°Ð»Ð¸Ð´Ð°Ñ†Ð¸Ð¸:</t>
    <t id="9233">ÐœÐ°ÐºÑ ÐžÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ñ… ÐŸÐ¾Ð¸ÑÐºÐ¾Ð²:</t>
    <t id="9234">ÐœÐ°ÐºÑ Ð¡Ð´ÐµÐ»Ð¾Ðº Ð´Ð»Ñ Ð’Ð¾Ð·Ð²Ñ€Ð°Ñ‚Ð°:</t>
    <t id="9235">ÐœÐ°ÐºÑ ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð½Ð° Ð¢Ð¾Ð²Ð°Ñ€:</t>
    <t id="9236">ÐœÐ°ÐºÑ Ð¡Ð´ÐµÐ»Ð¾Ðº Ð½Ð° Ð¢Ð¾Ð²Ð°Ñ€:</t>
    <t id="9237">ÐœÐ°ÐºÑ ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð½Ð° Ð¢Ð¾Ð²Ð°Ñ€ Ð´Ð»Ñ Ð¡Ð¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ñ:</t>
    <t id="9238">ÐŸÐ¾Ñ€Ð¾Ð³ Ð Ð°Ð½Ð½ÐµÐ³Ð¾ Ð’Ñ‹Ñ…Ð¾Ð´Ð°:</t>
    <t id="9241">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¡Ñ€ÐµÐ·Ð¾Ð² Ð–Ð¸Ð²Ñ‹Ñ… ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹:</t>
    <t id="9266">Ð’Ñ€ÐµÐ¼Ñ Ð¶Ð¸Ð·Ð½Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾Ð¸ÑÐºÐ°:</t>
    <t id="9263">Ð Ð°Ð·Ð¼ÐµÑ€ ÐŸÐ°ÐºÐµÑ‚Ð° ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸:</t>
    <t id="9239">Ð¤Ð¾Ñ€Ð¼Ð°Ñ‚ Ð§Ð¸ÑÐ»Ð°</t>
    <t id="9240">Ð¡Ñ‚Ð¸Ð»ÑŒ Ð¤Ð¾Ñ€Ð¼Ð°Ñ‚Ð°:</t>
    <t id="9242">Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÑŒ Ð¡ÑƒÑ„Ñ„Ð¸ÐºÑ M</t>
    <t id="9243">ÐŸÐ¾Ñ€Ð¾Ð³ Ð¡ÑƒÑ„Ñ„Ð¸ÐºÑÐ° M:</t>
    <t id="9244">ÐÐµÐ¼ÐµÑ†ÐºÐ¸Ð¹ (123.456,78)</t>
    <t id="9245">ÐÐ½Ð³Ð»Ð¸Ð¹ÑÐºÐ¸Ð¹ (123,456.78)</t>
    <t id="9510">Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ Ð¾ Ð¿Ð¾Ð²Ñ‹ÑˆÐµÐ½Ð¸Ð¸ ÑƒÑ€Ð¾Ð²Ð½Ñ:</t>
    <t id="9511">ÐžÐ¿Ð¾Ð²ÐµÑ‰ÐµÐ½Ð¸Ñ Ð¾ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ÑÑ‚Ð¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ:</t>
    <t id="9512">Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ Ð¾ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ð¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ:</t>
    <t id="9513">ÐžÑ‚Ñ‡ÐµÑ‚Ñ‹ Ð¾ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸:</t>
    <t id="9514">Ð Ñ‹Ð½Ð¾Ñ‡Ð½Ñ‹Ðµ Ð¾Ð¿Ð¾Ð²ÐµÑ‰ÐµÐ½Ð¸Ñ:</t>
    <t id="9515">ÐžÐ±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ñ„Ð»Ð¾Ñ‚Ð°:</t>
    <t id="9516">Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð²Ð°Ð½Ð¸Ð»ÑŒÐ½Ñ‹Ð¹ XP</t>
    <t id="9610">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¸Ð»Ð¸ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð²ÑÐ¿Ð»Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ðµ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ Ð¾ Ð¿Ð¾Ð²Ñ‹ÑˆÐµÐ½Ð¸Ð¸ ÑƒÑ€Ð¾Ð²Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ð° Ð² Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹ÑÐµ Ð¸Ð³Ñ€Ð¾ÐºÐ°.</t>
    <t id="9611">ÐžÐ¿Ð¾Ð²ÐµÑ‰ÐµÐ½Ð¸Ðµ, ÐºÐ¾Ð³Ð´Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼ Ñ‚Ñ€ÐµÐ±ÑƒÐµÑ‚ÑÑ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ Ð¿Ð¾Ð²Ñ‹ÑˆÐµÐ½Ð¸Ñ ÑƒÑ€Ð¾Ð²Ð½Ñ.</t>
    <t id="9612">Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¸ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ð¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð¸ Ð¿Ð¾Ð²Ñ‹ÑˆÐµÐ½Ð¸Ð¸ Ñ€Ð°Ð½Ð³Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð².</t>
    <t id="9613">ÐŸÐµÑ€Ð¸Ð¾Ð´Ð¸Ñ‡ÐµÑÐºÐ¸Ðµ ÑÐ²Ð¾Ð´ÐºÐ¸ Ð¾ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸ (Ð¿Ñ€Ð¾ÑÑ‚Ñ‹Ðµ Ð¸ Ð¿Ð¾Ð»Ð½Ñ‹Ðµ Ð¾Ñ‚Ñ‡ÐµÑ‚Ñ‹).</t>
    <t id="9614">Ð˜ÑÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ðµ Ñ€Ñ‹Ð½Ð¾Ñ‡Ð½Ñ‹Ðµ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð¸ Ð¾Ð¿Ð¾Ð²ÐµÑ‰ÐµÐ½Ð¸Ñ Ð¾ Ð²Ñ‹Ð³Ð¾Ð´Ð½Ñ‹Ñ… ÑÐ´ÐµÐ»ÐºÐ°Ñ….</t>
    <t id="9615">Ð¡Ð¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð¾ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ð¸ Ñ„Ð»Ð¾Ñ‚Ð° Ð¸ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ ÑÑ‚Ð°Ñ‚ÑƒÑÐ°.</t>
    <t id="9616">Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐ¹Ñ‚Ðµ Pilot.skill.piloting Ð¸ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ðµ GT XP Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑ/Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ.</t>
    <t id="9246">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° ÐŸÑ€Ð¾ÑÑ‚Ð¾Ð³Ð¾ ÐžÑ‚Ñ‡ÐµÑ‚Ð°:</t>
    <t id="9247">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° ÐŸÐ¾Ð»Ð½Ð¾Ð³Ð¾ ÐžÑ‚Ñ‡ÐµÑ‚Ð°:</t>
    <t id="9248">ÐœÐ°ÐºÑ ÐžÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ñ… ÐŸÐ¾Ð¸ÑÐºÐ¾Ð² ÐšÑÑˆÐ°:</t>
    <t id="9249">ÐœÐ°ÐºÑ ÐžÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ñ… Ð–Ð¸Ð²Ñ‹Ñ… ÐŸÐ¾Ð¸ÑÐºÐ¾Ð²:</t>
    <t id="9340">Ð’Ñ‹Ð±ÐµÑ€Ð¸Ñ‚Ðµ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚ Ñ‡Ð¸ÑÐ»Ð°: ÐÐµÐ¼ÐµÑ†ÐºÐ¸Ð¹ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ '.' Ð´Ð»Ñ Ñ‚Ñ‹ÑÑÑ‡ Ð¸ ',' Ð´Ð»Ñ Ð´ÐµÑÑÑ‚Ð¸Ñ‡Ð½Ñ‹Ñ… (123.456,78), ÐÐ½Ð³Ð»Ð¸Ð¹ÑÐºÐ¸Ð¹ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ ',' Ð´Ð»Ñ Ñ‚Ñ‹ÑÑÑ‡ Ð¸ '.' Ð´Ð»Ñ Ð´ÐµÑÑÑ‚Ð¸Ñ‡Ð½Ñ‹Ñ… (123,456.78)</t>
    <t id="9342">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÑÑƒÑ„Ñ„Ð¸ÐºÑ M Ð´Ð»Ñ Ñ‡Ð¸ÑÐµÐ» Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ð¾Ñ€Ð¾Ð³Ð° (Ð½Ð°Ð¿Ñ€Ð¸Ð¼ÐµÑ€, 1.0 M Ð²Ð¼ÐµÑÑ‚Ð¾ 1,000,000)</t>
    <t id="9343">ÐŸÐ¾Ñ€Ð¾Ð³ Ð´Ð»Ñ ÑÑƒÑ„Ñ„Ð¸ÐºÑÐ° M. Ð§Ð¸ÑÐ»Ð° Ð²Ñ‹ÑˆÐµ ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð±ÑƒÐ´ÑƒÑ‚ Ð¾Ñ‚Ð¾Ð±Ñ€Ð°Ð¶Ð°Ñ‚ÑŒÑÑ Ñ ÑÑƒÑ„Ñ„Ð¸ÐºÑÐ¾Ð¼ M (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 999,999)</t>
    <t id="9346">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° Ð¿Ñ€Ð¾ÑÑ‚Ð¾Ð³Ð¾ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð° (Ð²ÑÐ¿Ð»Ñ‹Ð²Ð°ÑŽÑ‰ÐµÐµ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ðµ): 0-30 Ð¼Ð¸Ð½ÑƒÑ‚ (0 = Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ - Ð¿Ñ€Ð¾ÑÑ‚Ñ‹Ðµ Ð¾Ñ‚Ñ‡ÐµÑ‚Ñ‹ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ñ‹, Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1 Ð¼Ð¸Ð½ÑƒÑ‚Ð°)</t>
    <t id="9347">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° Ð¿Ð¾Ð»Ð½Ð¾Ð³Ð¾ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð° (Ð·Ð°Ð¿Ð¸ÑÑŒ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ðµ): 0-60 Ð¼Ð¸Ð½ÑƒÑ‚ (0 = Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ - Ð¿Ð¾Ð»Ð½Ñ‹Ðµ Ð¾Ñ‚Ñ‡ÐµÑ‚Ñ‹ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ñ‹, Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 30 Ð¼Ð¸Ð½ÑƒÑ‚)</t>
    <t id="9398">Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿ÐµÑ€ÐµÐ¾Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ ÑÑ€Ð¾ÐºÐ° Ð¿Ð¾Ð³Ð°ÑˆÐµÐ½Ð¸Ñ ÐºÑ€ÐµÐ´Ð¸Ñ‚Ð¾Ð² GT</t>
    <t id="9399">Ð—Ð°Ð¼ÐµÐ½Ð¸Ñ‚Ðµ Ð¸Ð»Ð¸ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚Ðµ ÑÑ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½ÑƒÑŽ ÑÑ‚Ñ€Ð¾ÐºÑƒ Â«CR Ðº Ð¾Ð¿Ð»Ð°Ñ‚Ðµ Ð·Ð° ÑÐ´ÐµÐ»ÐºÐ¸Â» Ð¿Ñ€Ð¾Ð³Ð½Ð¾Ð·Ð¸Ñ€ÑƒÐµÐ¼Ñ‹Ð¼ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸ÐµÐ¼ GT Ð² Ñ‚Ð¾Ð¼ Ð¶Ðµ ÑÐ»Ð¾Ñ‚Ðµ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÑÐºÐ¾Ð³Ð¾ Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹ÑÐ°.</t>
    <t id="9331">Ð—Ð°Ð´ÐµÑ€Ð¶ÐºÐ° Ð¼ÐµÐ¶Ð´Ñƒ Ð¿Ð°ÐºÐµÑ‚Ð°Ð¼Ð¸ Ð²Ð¾ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ Ð¿Ð¾Ð¸ÑÐºÐ° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ (1-100Ð¼Ñ). Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¿Ð¾Ð¸ÑÐº Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 50Ð¼Ñ. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ Ð² Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐ¾Ñ€Ðµ Ð¿Ð°ÐºÐµÑ‚Ð¾Ð² Ð¸ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ð°Ñ†Ð¸Ð¸ ÑÐ¿Ð¸ÑÐºÐ° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸.</t>
    <t id="9332">Ð—Ð°Ð´ÐµÑ€Ð¶ÐºÐ° Ð¼ÐµÐ¶Ð´Ñƒ Ð²Ð°Ð»Ð¸Ð´Ð°Ñ†Ð¸ÑÐ¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ Ð² AI ÑÐºÑ€Ð¸Ð¿Ñ‚Ðµ (1-100Ð¼Ñ). Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð²Ð°Ð»Ð¸Ð´Ð°Ñ†Ð¸ÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 50Ð¼Ñ. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ Ð¿Ñ€Ð¸ Ð²Ð°Ð»Ð¸Ð´Ð°Ñ†Ð¸Ð¸ ÑÐ¿Ð¸ÑÐºÐ° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ Ð¸Ð· ÑÐ¸ÑÑ‚ÐµÐ¼Ñ‹ MD.</t>
    <t id="9333">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ¾Ð² Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÑÑ‚ÑŒÑÑ Ð¾Ð´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ (1-10). Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ ÑÐºÐ°Ñ‡ÐºÐ¸ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9334">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ ÑÐ´ÐµÐ»Ð¾Ðº Ð´Ð»Ñ Ð²Ð¾Ð·Ð²Ñ€Ð°Ñ‚Ð° Ð¸Ð· Ð¿Ð¾Ð¸ÑÐºÐ° ÐºÑÑˆÐ° (50-1000). Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ñ€ÐµÐ´Ð¾ÑÑ‚Ð°Ð²Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ð¾Ð¿Ñ†Ð¸Ð¹, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 200.</t>
    <t id="9335">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€ Ð´Ð»Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ Ð² Ð¶Ð¸Ð²Ð¾Ð¼ Ð¿Ð¾Ð¸ÑÐºÐµ (5-100). Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñ€Ð°ÑÑÐ¼Ð°Ñ‚Ñ€Ð¸Ð²Ð°ÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 20.</t>
    <t id="9336">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ ÑÐ´ÐµÐ»Ð¾Ðº Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€ Ð²Ð¾ Ð²Ñ€ÐµÐ¼Ñ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð¹ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ (5-100). Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ ÑÐ´ÐµÐ»Ð¾Ðº Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 20.</t>
    <t id="9337">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€ Ð´Ð»Ñ ÑÐ¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð² Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐ¾Ñ€Ðµ Ð¿Ð°ÐºÐµÑ‚Ð¾Ð² (5-100). Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñ€Ð°ÑÑÐ¼Ð°Ñ‚Ñ€Ð¸Ð²Ð°ÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 20.</t>
    <t id="9338">ÐŸÐ¾Ñ€Ð¾Ð³ Ñ€Ð°Ð½Ð½ÐµÐ³Ð¾ Ð²Ñ‹Ñ…Ð¾Ð´Ð° Ð´Ð»Ñ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð¹ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ (100-10000). ÐšÐ¾Ð³Ð´Ð° Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾ ÑÑ‚Ð¾Ð»ÑŒÐºÐ¾ ÑÐ´ÐµÐ»Ð¾Ðº, Ð¿Ð°ÐºÐµÑ‚Ð½Ð°Ñ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð¾ÑÑ‚Ð°Ð½Ð°Ð²Ð»Ð¸Ð²Ð°ÐµÑ‚ÑÑ Ñ€Ð°Ð½ÑŒÑˆÐµ Ð´Ð»Ñ ÑÐºÐ¾Ð½Ð¾Ð¼Ð¸Ð¸ CPU. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ ÑÐ´ÐµÐ»Ð¾Ðº, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð²Ñ‹Ñ…Ð¾Ð´ÑÑ‚ Ñ€Ð°Ð½ÑŒÑˆÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒÐ½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 2000.</t>
    <t id="9341">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» ÑÑ€ÐµÐ·Ð¾Ð² Ð¶Ð¸Ð²Ñ‹Ñ… Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð² Ð¼Ð¸Ð»Ð»Ð¸ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (5-500Ð¼Ñ). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€ÑƒÐµÑ‚, ÐºÐ°Ðº Ñ‡Ð°ÑÑ‚Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð½Ð°Ñ‡Ð¸Ð½Ð°Ñ‚ÑŒÑÑ ÑÑ€ÐµÐ·Ñ‹ Ð¶Ð¸Ð²Ñ‹Ñ… Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ ÑÐ¾Ð±Ð¸Ñ€Ð°Ñ‚ÑŒ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÑƒ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 500Ð¼Ñ.</t>
    <t id="9363">Ð Ð°Ð·Ð¼ÐµÑ€ Ð¿Ð°ÐºÐµÑ‚Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ (5-20). ÐžÐ±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÑ‚ chunkSizeÃ—chunkSize ÐºÐ¾Ð¼Ð±Ð¸Ð½Ð°Ñ†Ð¸Ð¹ Ð½Ð° Ð¿Ð°ÐºÐµÑ‚ (Ð½Ð°Ð¿Ñ€Ð¸Ð¼ÐµÑ€, 10Ã—10 = 100 ÐºÐ¾Ð¼Ð±Ð¸Ð½Ð°Ñ†Ð¸Ð¹). Ð‘Ð¾Ð»ÐµÐµ ÐºÑ€ÑƒÐ¿Ð½Ñ‹Ðµ Ð¿Ð°ÐºÐµÑ‚Ñ‹ ÑƒÐ»ÑƒÑ‡ÑˆÐ°ÑŽÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ½ÑƒÑŽ ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚ÑŒ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU Ð½Ð° Ð¿Ð°ÐºÐµÑ‚. ÐœÐµÐ½ÑŒÑˆÐ¸Ðµ Ð¿Ð°ÐºÐµÑ‚Ñ‹ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð¿Ð¸ÐºÐ¸ CPU, Ð½Ð¾ Ñ‚Ñ€ÐµÐ±ÑƒÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ð¹. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 10.</t>
    <t id="9348">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ¾Ð² ÐºÑÑˆÐ°, ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÑÑ‚ÑŒÑÑ Ð¾Ð´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ (1-20). ÐŸÐ¾Ð¸ÑÐºÐ¸ ÐºÑÑˆÐ° Ð±Ñ‹ÑÑ‚Ñ€Ñ‹Ðµ Ð¸ Ð´ÐµÑˆÐµÐ²Ñ‹Ðµ, Ð¿Ð¾ÑÑ‚Ð¾Ð¼Ñƒ Ð±Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ð°Ñ€Ð°Ð»Ð»ÐµÐ»ÑŒÐ½Ñ‹Ñ… Ð¿Ñ€Ð¾Ð²ÐµÑ€Ð¾Ðº ÐºÑÑˆÐ° Ð±ÐµÐ· Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð³Ð¾ Ð²Ð»Ð¸ÑÐ½Ð¸Ñ Ð½Ð° CPU. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð¿Ð°Ñ€Ð°Ð»Ð»ÐµÐ»ÑŒÐ½Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸ ÐºÑÑˆÐ°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 5.</t>
    <t id="9349">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¶Ð¸Ð²Ñ‹Ñ… Ð¿Ð¾Ð¸ÑÐºÐ¾Ð², ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÑÑ‚ÑŒÑÑ Ð¾Ð´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ (1-10). Ð–Ð¸Ð²Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ñ‚Ñ€ÐµÐ±ÑƒÑŽÑ‚ Ð¼Ð½Ð¾Ð³Ð¾ CPU, Ð¿Ð¾ÑÑ‚Ð¾Ð¼Ñƒ Ð±Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ ÑÐºÐ°Ñ‡ÐºÐ¸ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9264">Ð Ð°Ð·Ð¼ÐµÑ€ Ñ‡Ð°Ð½ÐºÐ° Ð·Ð°Ð¿Ñ€Ð¾ÑÐ° ÐºÑÑˆÐ°:</t>
    <t id="9265">Ð Ð°Ð·Ð¼ÐµÑ€ Ñ‡Ð°Ð½ÐºÐ° Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¶Ð¸Ð²Ñ‹Ñ… Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹:</t>
    <t id="9364">Ð—Ð°Ð¿Ð¸ÑÐµÐ¹ ÐºÑÑˆÐ°, Ð¿Ñ€Ð¾Ð²ÐµÑ€ÑÐµÐ¼Ñ‹Ñ… Ð·Ð° Ñ‡Ð°Ð½Ðº (10-200). ÐœÐµÐ½ÑŒÑˆÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÑÑŽÑ‚ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÑƒ ÐºÑÑˆÐ° Ð¿Ð¾ Ð±Ð¾Ð»ÑŒÑˆÐµÐ¼Ñƒ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ñƒ ÐºÐ°Ð´Ñ€Ð¾Ð² (Ð¿Ð»Ð°Ð²Ð½ÐµÐµ), Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ñ‚ÑŒ Ð²Ñ€ÐµÐ¼Ñ Ð¿Ð¾Ð¸ÑÐºÐ° ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 10.</t>
    <t id="9365">ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹, Ð´Ð¾Ð±Ð°Ð²Ð»ÑÐµÐ¼Ñ‹Ñ… Ð·Ð° ÑÑ€ÐµÐ· Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ (50-2000). ÐœÐµÐ½ÑŒÑˆÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ñ€Ð°Ð±Ð¾Ñ‚Ñƒ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð² ÑÐ¿Ð¸ÑÐ¾Ðº Ð·Ð° ÐºÐ°Ð´Ñ€ (Ð¿Ð»Ð°Ð²Ð½ÐµÐµ), Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð·Ð°Ð¼ÐµÐ´Ð»Ð¸Ñ‚ÑŒ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ðµ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 200.</t>
    <t id="9366">Ð’Ñ€ÐµÐ¼Ñ Ð¶Ð¸Ð·Ð½Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾Ð¸ÑÐºÐ° Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (60-7200). Ð•ÑÐ»Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŽ Ð¾Ñ‚ÐºÐ°Ð·Ñ‹Ð²Ð°ÑŽÑ‚ Ñ ÑÐ¾Ð¾Ð±Ñ‰ÐµÐ½Ð¸ÐµÐ¼ Â«Ð¿Ð¾Ð¸ÑÐº Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ ÑƒÐ¶Ðµ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÑÐµÑ‚ÑÑÂ» Ð´Ð¾Ð»ÑŒÑˆÐµ ÑÑ‚Ð¾Ð³Ð¾ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð¸, GT ÑÐ°Ð¼Ð¾Ð¸ÑÑ†ÐµÐ»Ð¸Ñ‚ÑÑ, Ð¾Ñ‡Ð¸ÑÑ‚Ð¸Ð² ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐµÐµ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ð¾Ð¸ÑÐºÐ° Ð¸ Ð¾ÑÐ²Ð¾Ð±Ð¾Ð´Ð¸Ð² Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÑƒ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 600Ñ.</t>
    <t id="9370">ÐŸÐ¾Ñ€Ð¾Ð³ ÐœÑÐ³ÐºÐ¾Ð³Ð¾ ÐžÐ±Ñ€Ð°Ñ‚Ð½Ð¾Ð³Ð¾ Ð”Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÐŸÐ°ÐºÐµÑ‚Ð½Ð¾Ð¹ ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸:</t>
    <t id="9371">ÐŸÐ¾Ñ€Ð¾Ð³ Ð–ÐµÑÑ‚ÐºÐ¾Ð³Ð¾ ÐžÐ±Ñ€Ð°Ñ‚Ð½Ð¾Ð³Ð¾ Ð”Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÐŸÐ°ÐºÐµÑ‚Ð½Ð¾Ð¹ ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸:</t>
    <t id="9372">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¾Ð² Ð½Ð° Ð¡Ñ€ÐµÐ·:</t>
    <t id="9373">Ð’Ñ€ÐµÐ¼Ñ ÐžÑ…Ð»Ð°Ð¶Ð´ÐµÐ½Ð¸Ñ ÐžÐ±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ð”Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ³Ð¾ Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð°:</t>
    <t id="9374">Ð‘Ð°Ð·Ð¾Ð²Ð¾Ðµ Ð’Ñ€ÐµÐ¼Ñ ÐžÑ…Ð»Ð°Ð¶Ð´ÐµÐ½Ð¸Ñ ÐŸÐ¾ÑÐ»Ðµ ÐŸÑ€Ð¾Ð¼Ð°Ñ…Ð° ÐšÑÑˆÐ°:</t>
    <t id="9375">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¢Ð¸ÐºÐ° ÐŸÐ»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ°:</t>
    <t id="9376">ÐœÐ°ÐºÑ Ð—Ð°Ð¿Ñ€Ð¾ÑÐ¾Ð² ÐšÑÑˆÐ° Ð·Ð° Ð¢Ð¸Ðº:</t>
    <t id="9377">ÐœÐ°ÐºÑ ÐŸÑ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ð¹ ÐŸÐ¾Ð¸ÑÐºÐ° Ð·Ð° Ð¢Ð¸Ðº:</t>
    <t id="9378">ÐœÐ°ÐºÑ ÐšÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ð·Ð° Ð¢Ð¸Ðº:</t>
    <t id="9379">ÐœÐ°ÐºÑ Ð­Ð»ÐµÐ¼ÐµÐ½Ñ‚Ð¾Ð² Ð·Ð° Ð¢Ð¸Ðº:</t>
    <t id="9380">ÐœÐ°ÐºÑ ÐŸÑ€Ð¾Ð±ÑƒÐ¶Ð´ÐµÐ½Ð¸Ð¹ Ð·Ð° Ð¢Ð¸Ðº:</t>
    <t id="9381">ÐœÐ°ÐºÑ Ð—Ð°Ð¿Ð¸ÑÐµÐ¹ Ð—Ð°Ð¿Ñ€Ð¾ÑÐ° ÐšÑÑˆÐ°:</t>
    <t id="9382">ÐŸÐ¾Ñ€Ð¾Ð³ Ð£ÑÑ‚Ð°Ñ€ÐµÐ²Ð°Ð½Ð¸Ñ Ð² Ð¡ÐµÐºÑƒÐ½Ð´Ð°Ñ…:</t>
    <t id="9383">ÐŸÐ¾Ñ€Ð¾Ð³ Ð£ÑÑ‚Ð°Ñ€ÐµÐ²Ð°Ð½Ð¸Ñ ÐžÑ‡ÐµÑ€ÐµÐ´Ð¸ Ð² Ð¡ÐµÐºÑƒÐ½Ð´Ð°Ñ…:</t>
    <t id="9384">Ð’Ñ€ÐµÐ¼Ñ Ð˜ÑÑ‚ÐµÑ‡ÐµÐ½Ð¸Ñ ÐÐµÑƒÐ´Ð°Ñ‡Ð½Ñ‹Ñ… Ð¡Ð´ÐµÐ»Ð¾Ðº Ð² Ð¡ÐµÐºÑƒÐ½Ð´Ð°Ñ…:</t>
    <t id="9385">ÐœÐ°ÐºÑ ÐžÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ñ… Ð ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ñ… ÐŸÐ¾Ð¸ÑÐºÐ¾Ð²:</t>
    <t id="9386">ÐœÐ°ÐºÑ ÐžÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ñ… Ð ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ñ… ÐŸÐ¾Ð¸ÑÐºÐ¾Ð²:</t>
    <t id="9470">ÐœÑÐ³ÐºÐ¸Ð¹ Ð¿Ð¾Ñ€Ð¾Ð³ Ð´Ð»Ñ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐ¾Ñ€Ð° (5-50). ÐšÐ¾Ð³Ð´Ð° Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð´Ð¾ÑÑ‚Ð¸Ð³Ð°ÐµÑ‚ ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ, Ð½Ð°Ñ‡Ð¸Ð½Ð°ÐµÑ‚ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÑ‚ÑŒÑÑ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾Ðµ Ð´Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ Ð·Ð°Ð¼ÐµÐ´Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ñ‹Ñ… Ð·Ð°Ð¿Ñ€Ð¾ÑÐ¾Ð² Ð¿Ð¾Ð¸ÑÐºÐ°. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð°Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾Ðµ Ð´Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ñ€Ð°Ð½ÑŒÑˆÐµ (Ð±Ð¾Ð»ÐµÐµ ÐºÐ¾Ð½ÑÐµÑ€Ð²Ð°Ñ‚Ð¸Ð²Ð½Ð¾). ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 10.</t>
    <t id="9471">Ð–ÐµÑÑ‚ÐºÐ¸Ð¹ Ð¿Ð¾Ñ€Ð¾Ð³ Ð´Ð»Ñ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐ¾Ñ€Ð° (10-100). ÐšÐ¾Ð³Ð´Ð° Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð´Ð¾ÑÑ‚Ð¸Ð³Ð°ÐµÑ‚ ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ, Ð½Ð¾Ð²Ñ‹Ðµ Ð¶Ð¸Ð²Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€ÑƒÑŽÑ‚ÑÑ Ð´Ð¾ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐµÐ½Ð¸Ñ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€ÑƒÑŽÑ‚ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ñ€Ð°Ð½ÑŒÑˆÐµ (Ð±Ð¾Ð»ÐµÐµ ÐºÐ¾Ð½ÑÐµÑ€Ð²Ð°Ñ‚Ð¸Ð²Ð½Ð¾). ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 25.</t>
    <t id="9472">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¾Ð², Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ñ… Ð·Ð° ÑÑ€ÐµÐ· Ð² ÑÐ±Ð¾Ñ€Ðµ Ð¶Ð¸Ð²Ñ‹Ñ… Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ (1-5). ÐœÐµÐ½ÑŒÑˆÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÑÑŽÑ‚ Ñ€Ð°Ð±Ð¾Ñ‚Ñƒ Ð¿Ð¾ Ð±Ð¾Ð»ÑŒÑˆÐµÐ¼Ñƒ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ñƒ ÐºÐ°Ð´Ñ€Ð¾Ð² (Ð¿Ð»Ð°Ð²Ð½ÐµÐµ), Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð·Ð°Ð¼ÐµÐ´Ð»Ð¸Ñ‚ÑŒ ÑÐ±Ð¾Ñ€ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ ÑÐºÐ°Ñ‡ÐºÐ¸ ÐºÐ°Ð´Ñ€Ð¾Ð². ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9473">Ð’Ñ€ÐµÐ¼Ñ Ð¾Ñ…Ð»Ð°Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¿Ð¾ÑÐ»Ðµ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ñ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð° (10-120 ÑÐµÐºÑƒÐ½Ð´). ÐŸÑ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰Ð°ÐµÑ‚ Ñ‡Ñ€ÐµÐ·Ð¼ÐµÑ€Ð½Ñ‹Ðµ Ð·Ð°Ð¿Ñ€Ð¾ÑÑ‹ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÐµÐµ Ñ‡Ð°ÑÑ‚Ñ‹Ðµ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ñ‡Ð°ÑÑ‚Ð¾Ñ‚Ñƒ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ð¹, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð·Ð°Ð´ÐµÑ€Ð¶Ð°Ñ‚ÑŒ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ ÐºÑÑˆÐ°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 30Ñ.</t>
    <t id="9474">Ð‘Ð°Ð·Ð¾Ð²Ð¾Ðµ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ñ…Ð»Ð°Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¿Ð¾ÑÐ»Ðµ Ð¿Ñ€Ð¾Ð¼Ð°Ñ…Ð° ÐºÑÑˆÐ° Ð¿ÐµÑ€ÐµÐ´ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¾Ð¹ Ð¿Ð¾Ð¿Ñ‹Ñ‚ÐºÐ¾Ð¹ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ° (1-30 ÑÐµÐºÑƒÐ½Ð´). ÐŸÑ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰Ð°ÐµÑ‚ Ñ‡Ñ€ÐµÐ·Ð¼ÐµÑ€Ð½Ñ‹Ðµ Ð¿Ð¾Ð¿Ñ‹Ñ‚ÐºÐ¸ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð°. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÑÑŽÑ‚ Ñ€Ð°Ð½ÑŒÑˆÐµ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ñ‡Ð°ÑÑ‚Ð¾Ñ‚Ñƒ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð¾Ð², Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð·Ð°Ð´ÐµÑ€Ð¶Ð°Ñ‚ÑŒ Ð¿Ð¾Ð¸ÑÐº ÑÐ´ÐµÐ»Ð¾Ðº. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 10Ñ.</t>
    <t id="9475">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¼ÐµÐ¶Ð´Ñƒ Ñ‚Ð¸ÐºÐ°Ð¼Ð¸ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° Ð² Ð¼Ð¸Ð»Ð»Ð¸ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (50-500Ð¼Ñ). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€ÑƒÐµÑ‚, ÐºÐ°Ðº Ñ‡Ð°ÑÑ‚Ð¾ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸Ðº Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÑ‚ Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ñ‡Ð°Ñ‰Ðµ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ñ‚ÑŒ Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 100Ð¼Ñ.</t>
    <t id="9476">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð·Ð°Ð¿Ñ€Ð¾ÑÐ¾Ð² ÐºÑÑˆÐ°, Ð·Ð°Ð¿ÑƒÑÐºÐ°ÐµÐ¼Ñ‹Ñ… Ð·Ð° Ñ‚Ð¸Ðº Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð·Ð°Ð¿Ñ€Ð¾ÑÐ¾Ð² ÐºÑÑˆÐ° Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ ÐºÐ°Ð´Ñ€Ð¾Ð². Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ ÑÐºÐ°Ñ‡ÐºÐ¸ CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¿Ð¾Ð¸ÑÐºÐ¸ ÐºÑÑˆÐ°. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ Ð·Ð°Ð¸ÐºÐ°Ð½Ð¸Ðµ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9477">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ð¹ Ð¿Ð¾Ð¸ÑÐºÐ°, Ð·Ð°Ð¿ÑƒÑÐºÐ°ÐµÐ¼Ñ‹Ñ… Ð·Ð° Ñ‚Ð¸Ðº Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ð¹ Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ ÐºÐ°Ð´Ñ€Ð¾Ð². Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ ÑÐºÐ°Ñ‡ÐºÐ¸ CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÑƒ Ð¿Ð¾Ð¸ÑÐºÐ°. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ Ð·Ð°Ð¸ÐºÐ°Ð½Ð¸Ðµ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9478">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹, Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ñ… Ð·Ð° Ñ‚Ð¸Ðº Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ ÐºÐ°Ð´Ñ€Ð¾Ð². Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ ÑÐºÐ°Ñ‡ÐºÐ¸ CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÑƒ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ Ð·Ð°Ð¸ÐºÐ°Ð½Ð¸Ðµ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9479">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¾Ð² Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹, Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ñ‹Ñ… Ð·Ð° Ñ‚Ð¸Ðº Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¾Ð² Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ ÐºÐ°Ð´Ñ€Ð¾Ð². Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ ÑÐºÐ°Ñ‡ÐºÐ¸ CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÑƒ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ Ð·Ð°Ð¸ÐºÐ°Ð½Ð¸Ðµ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9480">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¾Ð¶Ð¸Ð´Ð°ÑŽÑ‰Ð¸Ñ…, Ð¿Ñ€Ð¾Ð±ÑƒÐ¶Ð´Ð°ÐµÐ¼Ñ‹Ñ… Ð·Ð° Ñ‚Ð¸Ðº Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‰Ð¸ÐºÐ° (1-10). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð±ÑƒÐ¶Ð´ÐµÐ½Ð¸Ñ Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ ÑÐºÐ°Ñ‡ÐºÐ¾Ð² CPU, ÐºÐ¾Ð³Ð´Ð° Ð¼Ð½Ð¾Ð³Ð¾ Ð¾Ð¶Ð¸Ð´Ð°ÑŽÑ‰Ð¸Ñ… Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ ÑÐºÐ°Ñ‡ÐºÐ¸ CPU, Ð½Ð¾ Ð·Ð°Ð¼ÐµÐ´Ð»ÑÑŽÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÑƒ Ð¾Ð¶Ð¸Ð´Ð°ÑŽÑ‰Ð¸Ñ…. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ð±Ñ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÑŽÑ‚ Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð²Ñ‹Ð·Ð²Ð°Ñ‚ÑŒ Ð·Ð°Ð¸ÐºÐ°Ð½Ð¸Ðµ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 2.</t>
    <t id="9481">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð·Ð°Ð¿Ð¸ÑÐµÐ¹ ÐºÑÑˆÐ°, Ð·Ð°Ð¿Ñ€Ð°ÑˆÐ¸Ð²Ð°ÐµÐ¼Ñ‹Ñ… Ð·Ð° Ð¿Ð°ÐºÐµÑ‚ (1-200). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€ÑƒÐµÑ‚ Ñ€Ð°Ð·Ð¼ÐµÑ€ Ð¿Ð°ÐºÐµÑ‚Ð° Ð·Ð°Ð¿Ñ€Ð¾ÑÐ° ÐºÑÑˆÐ°. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð´ÐµÐ»Ð°ÑŽÑ‚ Ð¿Ð¾Ð¸ÑÐºÐ¸ ÐºÑÑˆÐ° Ð±Ñ‹ÑÑ‚Ñ€ÐµÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒ Ð»ÑƒÑ‡ÑˆÐ¸Ðµ ÑÐ´ÐµÐ»ÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñ€Ð°ÑÑÐ¼Ð°Ñ‚Ñ€Ð¸Ð²Ð°ÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ ÐºÑÑˆÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… ÑÐ´ÐµÐ»Ð¾Ðº, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð²Ñ€ÐµÐ¼Ñ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 50.</t>
    <t id="9482">ÐŸÐ¾Ñ€Ð¾Ð³ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²Ð°Ð½Ð¸Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ° Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (60-600). ÐšÐ¾Ð³Ð´Ð° ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¶Ð¸Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð¸ÑÐºÐ° ÑÑ‚Ð°Ñ€ÑˆÐµ ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ, Ð¾Ð½Ð¾ ÑÑ‡Ð¸Ñ‚Ð°ÐµÑ‚ÑÑ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ð¼ Ð¸ Ð¾Ñ‡Ð¸Ñ‰Ð°ÐµÑ‚ÑÑ. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ñ‡Ð¸Ñ‰Ð°ÑŽÑ‚ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐµÐµ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ñ€Ð°Ð½ÑŒÑˆÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¿Ñ€ÐµÑ€Ð²Ð°Ñ‚ÑŒ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÐµÐµ Ð´Ð»Ð¸Ð½Ð½Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¾ÑÑ‚Ð°Ð²Ð¸Ñ‚ÑŒ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐµÐµ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 300Ñ.</t>
    <t id="9483">ÐŸÐ¾Ñ€Ð¾Ð³ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²Ð°Ð½Ð¸Ñ ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¾Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (30-300). ÐšÐ¾Ð³Ð´Ð° ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ‹ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ ÑÑ‚Ð°Ñ€ÑˆÐµ ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ, Ð¾Ð½Ð¸ ÑÑ‡Ð¸Ñ‚Ð°ÑŽÑ‚ÑÑ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ð¼Ð¸ Ð¸ ÑƒÐ´Ð°Ð»ÑÑŽÑ‚ÑÑ. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¾Ñ‡Ð¸Ñ‰Ð°ÑŽÑ‚ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ðµ ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ‹ Ñ€Ð°Ð½ÑŒÑˆÐµ, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ ÑƒÐ´Ð°Ð»Ð¸Ñ‚ÑŒ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ‹Ðµ ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ‹ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÐµÐµ Ð´Ð»Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ðµ Ð²Ñ€ÐµÐ¼Ñ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¾ÑÑ‚Ð°Ð²Ð¸Ñ‚ÑŒ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ðµ ÑÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ‹. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 60Ñ.</t>
    <t id="9484">Ð’Ñ€ÐµÐ¼Ñ Ð¸ÑÑ‚ÐµÑ‡ÐµÐ½Ð¸Ñ ÐºÑÑˆÐ° Ð½ÐµÑƒÐ´Ð°Ñ‡Ð½Ñ‹Ñ… ÑÐ´ÐµÐ»Ð¾Ðº Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (300-3600). ÐÐµÑƒÐ´Ð°Ñ‡Ð½Ñ‹Ðµ ÑÐ´ÐµÐ»ÐºÐ¸ ÐºÑÑˆÐ¸Ñ€ÑƒÑŽÑ‚ÑÑ, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð¸Ð·Ð±ÐµÐ¶Ð°Ñ‚ÑŒ Ð½ÐµÐ¼ÐµÐ´Ð»ÐµÐ½Ð½Ñ‹Ñ… Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ñ‹Ñ… Ð¿Ð¾Ð¿Ñ‹Ñ‚Ð¾Ðº. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¸ÑÑ‚ÐµÐºÐ°ÑŽÑ‚ Ñ€Ð°Ð½ÑŒÑˆÐµ (Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð¾Ð²), Ð½Ð¾ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ ÑÑ„Ñ„ÐµÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚ÑŒ ÐºÑÑˆÐ°. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÐºÑÑˆÐ¸Ñ€ÑƒÑŽÑ‚ Ð´Ð¾Ð»ÑŒÑˆÐµ (Ð¼ÐµÐ½ÑŒÑˆÐµ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð¾Ð²), Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð·Ð°Ð´ÐµÑ€Ð¶Ð°Ñ‚ÑŒ Ð¿Ð¾Ð¿Ñ‹Ñ‚ÐºÐ¸ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð°. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1800Ñ (30 Ð¼Ð¸Ð½ÑƒÑ‚).</t>
    <t id="9485">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¾Ð´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ñ‹Ñ… Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ñ… Ð¶Ð¸Ð²Ñ‹Ñ… Ð¿Ð¾Ð¸ÑÐºÐ¾Ð² (1-10). Ð ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸ Ð¾Ð±Ñ…Ð¾Ð´ÑÑ‚ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÑƒ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°, Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑ Ð½ÐµÑÐºÐ¾Ð»ÑŒÐºÐ¸Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ Ð¸Ð· Ð¾Ð´Ð½Ð¾Ð³Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð° Ð¸ÑÐºÐ°Ñ‚ÑŒ Ð¾Ð´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾. Ð‘Ð¾Ð»ÐµÐµ Ð½Ð¸Ð·ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÑŽÑ‚ Ð½Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð½Ð° CPU, Ð½Ð¾ Ð¼Ð¾Ð³ÑƒÑ‚ Ð·Ð°Ð¼ÐµÐ´Ð»Ð¸Ñ‚ÑŒ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ðµ Ð¿Ð¾Ð¸ÑÐºÐ¸. Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ Ð±Ð¾Ð»ÑŒÑˆÐµ Ð¿Ð°Ñ€Ð°Ð»Ð»ÐµÐ»ÑŒÐ½Ñ‹Ñ… Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ñ‹Ñ… Ð¿Ð¾Ð¸ÑÐºÐ¾Ð², Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÑŽÑ‚ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ðµ CPU. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 1.</t>
    <t id="9490">Ð—Ð°Ð´ÐµÑ€Ð¶ÐºÐ° ÑÐ¸Ð³Ð½Ð°Ð»Ð° Ð½Ð°Ð¹Ð´ÐµÐ½Ð½Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸:</t>
    <t id="9590">Ð—Ð°Ð´ÐµÑ€Ð¶ÐºÐ° Ð¿ÐµÑ€ÐµÐ´ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²ÐºÐ¾Ð¹ ÑÐ¸Ð³Ð½Ð°Ð»Ð° GT_Trade_Found ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ Ð² Ð¼Ð¸Ð»Ð»Ð¸ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (10-1000Ð¼Ñ). ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð²ÑÐµÐ³Ð´Ð° Ð¶Ð´ÑƒÑ‚ (Ð½Ð°ÑÑ‚Ñ€Ð¾ÐµÐ½Ð½Ð°Ñ Ð·Ð°Ð´ÐµÑ€Ð¶ÐºÐ° + Ð±ÑƒÑ„ÐµÑ€ 5Ð¼Ñ) Ð¿ÐµÑ€ÐµÐ´ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²ÐºÐ¾Ð¹ Ð½Ð¾Ð²Ñ‹Ñ… Ð·Ð°Ð¿Ñ€Ð¾ÑÐ¾Ð² Ð´Ð»Ñ Ð·Ð°Ñ…Ð²Ð°Ñ‚Ð° Ð·Ð°Ð´ÐµÑ€Ð¶Ð°Ð½Ð½Ñ‹Ñ… ÑÐ¸Ð³Ð½Ð°Ð»Ð¾Ð². Ð‘Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÑÑŽÑ‚ ÑÐ¸Ð³Ð½Ð°Ð»Ñ‹ Ð¼ÐµÐ¶Ð´Ñƒ ÐºÐ°Ð´Ñ€Ð°Ð¼Ð¸ Ð´Ð»Ñ Ð±Ð¾Ð»ÐµÐµ Ð¿Ð»Ð°Ð²Ð½Ð¾Ð¹ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸. ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: 10Ð¼Ñ.</t>
    <t id="8000">Ð¤Ð»Ð¾Ñ‚ GalaxyTrader</t>
    <t id="8001">Ð£Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼ GalaxyTrader Ð¸ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð²</t>
    <t id="8002">ÐŸÑ€Ð¾ÑÐ¼Ð¾Ñ‚Ñ€ Ð¸ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð²ÑÐµÐ¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸ GalaxyTrader</t>
    <t id="8100">ID ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8101">ÐŸÐ¸Ð»Ð¾Ñ‚</t>
    <t id="8102">ÐšÐ¾Ñ€Ð°Ð±Ð»ÑŒ</t>
    <t id="8103">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ</t>
    <t id="8104">Ð Ð°Ð½Ð³</t>
    <t id="8105">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ</t>
    <t id="8106">XP</t>
    <t id="8107">ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ Ð·Ð° Ð’ÑÐµ Ð’Ñ€ÐµÐ¼Ñ</t>
    <t id="8108">ÐœÐµÑÑ‚Ð¾Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ</t>
    <t id="8109">Ð‘Ð°Ð·Ð°</t>
    <t id="8110">ÐŸÐ¾ÑÐ»ÐµÐ´Ð½ÑÑ Ð¡Ð´ÐµÐ»ÐºÐ°</t>
    <t id="8111">ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ ÐŸÐ¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="8112">ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8113">ÐšÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¡Ð´ÐµÐ»Ð¾Ðº</t>
    <t id="8200">ÐžÐ±Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ</t>
    <t id="8201">Ð­ÐºÑÐ¿Ð¾Ñ€Ñ‚ CSV</t>
    <t id="8202">Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°</t>
    <t id="8203">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="8204">ÐŸÐ¾Ð¼Ð¾Ñ‰ÑŒ</t>
    <t id="8205">Ð—Ð°ÐºÑ€Ñ‹Ñ‚ÑŒ</t>
    <t id="8300">Ð’ÑÐµ ÐŸÐ¸Ð»Ð¾Ñ‚Ñ‹</t>
    <t id="8301">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ñ</t>
    <t id="8302">ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="8303">ÐžÐ±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ðµ</t>
    <t id="8304">Ð§Ñ€ÐµÐ·Ð²Ñ‹Ñ‡Ð°Ð¹Ð½Ð°Ñ Ð¡Ð¸Ñ‚ÑƒÐ°Ñ†Ð¸Ñ</t>
    <t id="8305">ÐÐ¾Ð²Ð¸Ñ‡ÐºÐ¸ (Ð£Ñ€ 1-5)</t>
    <t id="8306">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ñ‹Ðµ (Ð£Ñ€ 6-11)</t>
    <t id="8307">Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ñ‹ (Ð£Ñ€ 12+)</t>
    <t id="8308">Ð¢Ð¾Ð¿ 10 Ð—Ð°Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¾Ð²</t>
    <t id="8350">Ð¡Ð¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿Ð¾:</t>
    <t id="8351">ID ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8352">Ð˜Ð¼ÐµÐ½Ð¸ ÐŸÐ¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="8353">Ð¢Ð¸Ð¿Ñƒ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8354">Ð¡Ñ‚Ð°Ñ‚ÑƒÑÑƒ</t>
    <t id="8355">Ð Ð°Ð½Ð³Ñƒ</t>
    <t id="8356">Ð£Ñ€Ð¾Ð²Ð½ÑŽ</t>
    <t id="8357">XP</t>
    <t id="8358">ÐŸÑ€Ð¸Ð±Ñ‹Ð»Ð¸</t>
    <t id="8400">ÐÐµÑ‚ Ð·Ð°Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð²</t>
    <t id="8401">ÐÐµÑ‚ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð², ÑÐ¾Ð¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²ÑƒÑŽÑ‰Ð¸Ñ… Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ñƒ</t>
    <t id="8402">Ð’ÑÐµÐ³Ð¾ ÐŸÐ¸Ð»Ð¾Ñ‚Ð¾Ð²:</t>
    <t id="8403">ÐžÐ±Ñ‰Ð°Ñ ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ Ð¤Ð»Ð¾Ñ‚Ð°:</t>
    <t id="8404">ÐŸÐ¾ÑÐ»ÐµÐ´Ð½ÐµÐµ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ðµ:</t>
    <t id="8405">ÐŸÐ¾Ð¸ÑÐº Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð²...</t>
    <t id="8114">Ð¡ÐµÐºÑ‚Ð¾Ñ€</t>
    <t id="8320">ÐŸÐµÑ€ÐµÐ¸Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ðµ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8321">ÐŸÐ¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÑÐºÐ¾Ðµ Ð˜Ð¼Ñ</t>
    <t id="8322">Ð£ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ Ð˜Ð¼Ñ</t>
    <t id="8323">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚ÑŒ Ð˜Ð¼Ñ</t>
    <t id="8324">Ð˜Ð¼Ñ ÑƒÑÐ¿ÐµÑˆÐ½Ð¾ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾</t>
    <t id="8325">Ð˜Ð¼Ñ ÑƒÑÐ¿ÐµÑˆÐ½Ð¾ Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½Ð¾</t>
    <t id="8450">ÐžÑ‚Ð¿Ñ€Ð°Ð²Ð¸Ñ‚ÑŒ Ð½Ð° ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="8451">Ð¡Ð½ÑÑ‚ÑŒ Ñ Ð£Ñ‡ÐµÑ‚Ð°</t>
    <t id="8452">ÐŸÑ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ ÐŸÑ€Ð¾Ð´Ð°Ñ‚ÑŒ Ð“Ñ€ÑƒÐ·</t>
    <t id="8453">ÐžÑ‚Ð¿Ñ€Ð°Ð²Ð¸Ñ‚ÑŒ Ð½Ð° Ð ÐµÐ¼Ð¾Ð½Ñ‚</t>
    <t id="8454">ÐžÑ‚Ð¿Ñ€Ð°Ð²Ð¸Ñ‚ÑŒ Ð½Ð° ÐŸÐ¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ</t>
    <t id="8455">ÐžÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ Ð’ÑÐµ Ð—Ð°ÐºÐ°Ð·Ñ‹</t>
    <t id="8456">Ð”ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ</t>
    <t id="8500">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ ID ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8501">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ Ð˜Ð¼ÐµÐ½Ð¸ ÐŸÐ¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="8502">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ Ð¢Ð¸Ð¿Ñƒ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8503">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ Ð¡Ñ‚Ð°Ñ‚ÑƒÑÑƒ</t>
    <t id="8504">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ Ð Ð°Ð½Ð³Ñƒ</t>
    <t id="8505">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ Ð£Ñ€Ð¾Ð²Ð½ÑŽ</t>
    <t id="8506">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ XP</t>
    <t id="8507">ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ Ð´Ð»Ñ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¿Ð¾ ÐŸÑ€Ð¸Ð±Ñ‹Ð»Ð¸ Ð·Ð° Ð’ÑÐµ Ð’Ñ€ÐµÐ¼Ñ</t>
    <t id="8508">ÐžÐ±Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ Ð´Ð°Ð½Ð½Ñ‹Ðµ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð¸Ð· ÑÐ¸ÑÑ‚ÐµÐ¼Ñ‹ Ð¼Ð¸ÑÑÐ¸Ð¹</t>
    <t id="8509">Ð­ÐºÑÐ¿Ð¾Ñ€Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ð¹ Ð²Ð¸Ð´ Ð² CSV Ñ„Ð°Ð¹Ð»</t>
    <t id="8510">ÐŸÑ€Ð¾ÑÐ¼Ð¾Ñ‚Ñ€ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ¸ Ð¸ Ð³Ñ€Ð°Ñ„Ð¸ÐºÐ¾Ð² Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="8511">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¸Ñ‚ÑŒ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ñ‹ Ð¼ÐµÐ½ÑŽ</t>
    <t id="8512">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚ÑŒ Ð¿Ð¾Ð¼Ð¾Ñ‰ÑŒ Ð¸ Ð³Ð¾Ñ€ÑÑ‡Ð¸Ðµ ÐºÐ»Ð°Ð²Ð¸ÑˆÐ¸</t>
    <t id="8600">ÐŸÐ¸Ð»Ð¾Ñ‚Ñ‹ GalaxyTrader Ð½Ðµ Ð½Ð°Ð¹Ð´ÐµÐ½Ñ‹</t>
    <t id="8601">Ð¡Ð¾Ð·Ð´Ð°Ð¹Ñ‚Ðµ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð², Ð½Ð°Ð·Ð½Ð°Ñ‡Ð¸Ð² ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ GalaxyTrader, Ð¸Ð»Ð¸ Ð´Ð¾Ð¶Ð´Ð¸Ñ‚ÐµÑÑŒ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ Ð´Ð°Ð½Ð½Ñ‹Ñ….</t>
    <t id="9001">GT ÐŸÐµÑ€ÐµÐ¸Ð¼ÐµÐ½Ð¾Ð²Ð°Ñ‚ÑŒ</t>
    <t id="9902">ÐžÑ‚Ð¿Ñ€Ð°Ð²Ð¸Ñ‚ÑŒ Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="9903">Ð ÑƒÑ‡Ð½Ð¾Ðµ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¾ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð´Ð»Ñ %1. ÐŸÐ¸Ð»Ð¾Ñ‚ Ð½Ð°Ñ‡Ð½ÐµÑ‚ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¿Ð¾ÑÐ»Ðµ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ Ñ†Ð¸ÐºÐ»Ð°.</t>
    <t id="9904">ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¾ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð¿Ð¾ÑÐ»Ðµ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ Ñ†Ð¸ÐºÐ»Ð°</t>
    <t id="9905">ÐŸÐ¸Ð»Ð¾Ñ‚ Ð¸Ð»Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð½Ðµ Ð½Ð°Ð¹Ð´ÐµÐ½</t>
    <t id="9906">ÐÐ²Ñ‚Ð¾Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ - Ñ€ÑƒÑ‡Ð½Ð°Ñ Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð½Ðµ Ñ‚Ñ€ÐµÐ±ÑƒÐµÑ‚ÑÑ</t>
    <t id="9907">ÐŸÐ¸Ð»Ð¾Ñ‚ Ð½Ðµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½ Ð´Ð»Ñ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ</t>
    <t id="9910">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð°Ñ ÐÐºÐ°Ð´ÐµÐ¼Ð¸Ñ</t>
    <t id="9911">Ð£Ñ‡ÐµÐ½Ð¸Ðº (Ð£Ñ€. 4) - %1 / %2</t>
    <t id="9912">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† (ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ 7) - %1 / %2</t>
    <t id="9913">ÐœÐ°ÑÑ‚ÐµÑ€-Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† (ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ 13) - %1 / %2</t>
    <t id="9920">ÐŸÐ¸Ð»Ð¾Ñ‚ %1 Ð·Ð°Ñ‡Ð¸ÑÐ»ÐµÐ½ Ð½Ð° ÐºÑƒÑ€Ñ ÐÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸ Ð´Ð»Ñ ÑƒÑ€Ð¾Ð²Ð½Ñ %2. ÐžÑ‚Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð½Ð° Ð±Ð»Ð¸Ð¶Ð°Ð¹ÑˆÑƒÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÑƒÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ.</t>
    <t id="9921">ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ð¾ ÑÑ€ÐµÐ´ÑÑ‚Ð² Ð´Ð»Ñ ÑÑ‚Ð¾Ð³Ð¾ ÐºÑƒÑ€ÑÐ° (Ð½ÑƒÐ¶Ð½Ð¾ %1, ÐµÑÑ‚ÑŒ %2).</t>
    <t id="9922">ÐšÑƒÑ€Ñ Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿ÐµÐ½ - Ð¿Ð¸Ð»Ð¾Ñ‚ %1 ÑƒÐ¶Ðµ Ð´Ð¾ÑÑ‚Ð¸Ð³ ÑÑ‚Ð¾Ð³Ð¾ ÑƒÑ€Ð¾Ð²Ð½Ñ Ð¸Ð»Ð¸ Ð²Ñ‹ÑˆÐµ.</t>
    <t id="9923">ÐŸÐ¸Ð»Ð¾Ñ‚ %1 Ð·Ð°Ð¿Ð¸ÑÐ°Ð»ÑÑ Ð½Ð° ÐºÑƒÑ€Ñ %2 ÐÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸ Ñ‚Ñ€ÐµÐ¹Ð´Ð¸Ð½Ð³Ð° (ÑÑ‚Ð¾Ð¸Ð¼Ð¾ÑÑ‚ÑŒ: %3 Cr, Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ: %4 Ð¼Ð¸Ð½) Ð½Ð° Ð±Ð¾Ñ€Ñ‚Ñƒ %5.</t>
    <t id="11011">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ Ð¡Ñ€ÐµÐ´Ð½ÐµÐ³Ð¾ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ Ð£Ñ‡ÐµÐ½Ð¸ÐºÐ°</t>
    <t id="11012">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ ÑÐ»ÐµÐ³ÐºÐ° ÑÐ½Ð¸Ð¶Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð´Ð»Ñ Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° ÑÑ€ÐµÐ´Ð½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -5% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="11013">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ Ð¡Ñ€ÐµÐ´Ð½ÐµÐ³Ð¾ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð£Ñ‡ÐµÐ½Ð¸ÐºÐ°</t>
    <t id="11014">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ ÑÐ»ÐµÐ³ÐºÐ° ÑÐ½Ð¸Ð¶Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð´Ð»Ñ Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° ÑÑ€ÐµÐ´Ð½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -5% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="11021">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ Ð‘Ð¾Ð»ÑŒÑˆÐ¾Ð³Ð¾ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ Ð£Ñ‡ÐµÐ½Ð¸ÐºÐ°</t>
    <t id="11022">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ ÑÐ½Ð¸Ð¶Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð´Ð»Ñ Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="11023">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ Ð‘Ð¾Ð»ÑŒÑˆÐ¾Ð³Ð¾ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð£Ñ‡ÐµÐ½Ð¸ÐºÐ°</t>
    <t id="11024">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ ÑÐ½Ð¸Ð¶Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð´Ð»Ñ Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="11031">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ ÐšÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð° Ð£Ñ‡ÐµÐ½Ð¸ÐºÐ°</t>
    <t id="11032">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ ÑÐ½Ð¸Ð¶Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð´Ð»Ñ Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ… ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð². Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="11033">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ ÐšÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð° Ð£Ñ‡ÐµÐ½Ð¸ÐºÐ°</t>
    <t id="11034">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ ÑÐ½Ð¸Ð¶Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð´Ð»Ñ Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ… ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð². Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="12001">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ ÐœÐ°Ð»Ð¾Ð³Ð¾ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ Ð‘Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾</t>
    <t id="12002">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð¼Ð°Ð»Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +3% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="12003">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ ÐœÐ°Ð»Ð¾Ð³Ð¾ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð‘Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾</t>
    <t id="12004">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð¼Ð°Ð»Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +3% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="13001">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ Ð‘Ð¾Ð»ÑŒÑˆÐ¾Ð³Ð¾ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ Ð‘Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾</t>
    <t id="13002">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -8% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="13003">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ Ð‘Ð¾Ð»ÑŒÑˆÐ¾Ð³Ð¾ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð‘Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾</t>
    <t id="13004">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -8% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="14001">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ ÐšÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð° Ð‘Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾</t>
    <t id="14002">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð² Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="14003">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ ÐšÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð° Ð‘Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾</t>
    <t id="14004">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð² Ñ Ð±Ð°Ð·Ð¾Ð²Ñ‹Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="15001">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ ÐœÐ°Ð»Ð¾Ð³Ð¾ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ð°</t>
    <t id="15002">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð¼Ð°Ð»Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="15003">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ ÐœÐ°Ð»Ð¾Ð³Ð¾ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ð°</t>
    <t id="15004">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð¼Ð°Ð»Ñ‹Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="16001">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ Ð‘Ð¾Ð»ÑŒÑˆÐ¾Ð³Ð¾ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ð°</t>
    <t id="16002">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="16003">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ Ð‘Ð¾Ð»ÑŒÑˆÐ¾Ð³Ð¾ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ð°</t>
    <t id="16004">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ Ð±Ð¾Ð»ÑŒÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="17001">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ ÐšÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð° Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ð°</t>
    <t id="17002">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð² Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +6% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ.</t>
    <t id="17003">GT Ð£ÑÐ¸Ð»Ð¸Ñ‚ÐµÐ»ÑŒ ÐŸÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ ÐšÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð° Ð­ÐºÑÐ¿ÐµÑ€Ñ‚Ð°</t>
    <t id="17004">ÐŸÑ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ð°Ñ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð´Ð»Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð¾Ð² Ñ ÑÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ñ‹Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ AI GalaxyTrader. +6% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ÑŒ Ð¿ÑƒÑ‚ÐµÑˆÐµÑÑ‚Ð²Ð¸Ñ.</t>
    <t id="18001">Ð¡ÐµÑ€ÑŒÑ‘Ð·Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (ÐšÐ¾Ñ€Ð¿ÑƒÑ)</t>
    <t id="18002">Ð¡ÐµÑ€ÑŒÑ‘Ð·Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (ÐšÐ¾Ñ€Ð¿ÑƒÑ) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ ÑÐµÑ€ÑŒÑ‘Ð·Ð½Ñ‹Ðµ ÑˆÑ‚Ñ€Ð°Ñ„Ñ‹ Ðº Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð¸Ð·-Ð·Ð° Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ñ ÐºÑ€ÑƒÐ¿Ð½Ñ‹Ð¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼Ð¸. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ GalaxyTrader ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð²Ñ‹Ðº Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡ÐµÐ½ Ð´Ð»Ñ Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð£Ð²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ Ð¼Ð°ÑÑÑƒ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ°. (Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ¸)</t>
    <t id="18003">Ð£Ð¼ÐµÑ€ÐµÐ½Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (ÐšÐ¾Ñ€Ð¿ÑƒÑ)</t>
    <t id="18004">Ð£Ð¼ÐµÑ€ÐµÐ½Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (ÐšÐ¾Ñ€Ð¿ÑƒÑ) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ ÑƒÐ¼ÐµÑ€ÐµÐ½Ð½Ñ‹Ðµ ÑˆÑ‚Ñ€Ð°Ñ„Ñ‹ Ðº Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð¿Ñ€Ð¸ Ð°Ð´Ð°Ð¿Ñ‚Ð°Ñ†Ð¸Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðº ÑÐ»Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ GalaxyTrader ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð²Ñ‹Ðº Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡ÐµÐ½ Ð´Ð»Ñ Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð£Ð²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ Ð¼Ð°ÑÑÑƒ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ°. (Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ¸)</t>
    <t id="18005">Ð›Ñ‘Ð³ÐºÐ¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (ÐšÐ¾Ñ€Ð¿ÑƒÑ)</t>
    <t id="18006">Ð›Ñ‘Ð³ÐºÐ¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (ÐšÐ¾Ñ€Ð¿ÑƒÑ) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ Ð½ÐµÐ·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ðµ ÑˆÑ‚Ñ€Ð°Ñ„Ñ‹ Ðº Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð² Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐµ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ñ Ð½Ð°Ð²Ñ‹ÐºÐ¾Ð² Ð¿Ð¸Ð»Ð¾Ñ‚Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ GalaxyTrader ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð²Ñ‹Ðº Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡ÐµÐ½ Ð´Ð»Ñ Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð£Ð²ÐµÐ»Ð¸Ñ‡Ð¸Ð²Ð°ÐµÑ‚ Ð¼Ð°ÑÑÑƒ ÐºÐ¾Ñ€Ð¿ÑƒÑÐ°. (Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ¸)</t>
    <t id="18007">Ð¡ÐµÑ€ÑŒÑ‘Ð·Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (Ð”Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»ÑŒ)</t>
    <t id="18008">Ð¡ÐµÑ€ÑŒÑ‘Ð·Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (Ð”Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»ÑŒ) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ ÑÐµÑ€ÑŒÑ‘Ð·Ð½Ñ‹Ðµ ÑˆÑ‚Ñ€Ð°Ñ„Ñ‹ Ðº Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð¸Ð·-Ð·Ð° Ð½ÐµÐ¾Ð¿Ñ‹Ñ‚Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ñ ÐºÑ€ÑƒÐ¿Ð½Ñ‹Ð¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼Ð¸. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ GalaxyTrader ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð²Ñ‹Ðº Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡ÐµÐ½ Ð´Ð»Ñ Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð¡Ð½Ð¸Ð¶Ð°ÐµÑ‚ Ñ‚ÑÐ³Ñƒ Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ. (Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ¸)</t>
    <t id="18009">Ð£Ð¼ÐµÑ€ÐµÐ½Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (Ð”Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»ÑŒ)</t>
    <t id="18010">Ð£Ð¼ÐµÑ€ÐµÐ½Ð½Ð¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (Ð”Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»ÑŒ) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ ÑƒÐ¼ÐµÑ€ÐµÐ½Ð½Ñ‹Ðµ ÑˆÑ‚Ñ€Ð°Ñ„Ñ‹ Ðº Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð¿Ñ€Ð¸ Ð°Ð´Ð°Ð¿Ñ‚Ð°Ñ†Ð¸Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðº ÑÐ»Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ GalaxyTrader ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð²Ñ‹Ðº Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡ÐµÐ½ Ð´Ð»Ñ Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð¡Ð½Ð¸Ð¶Ð°ÐµÑ‚ Ñ‚ÑÐ³Ñƒ Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ. (Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ¸)</t>
    <t id="18011">Ð›Ñ‘Ð³ÐºÐ¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (Ð”Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»ÑŒ)</t>
    <t id="18012">Ð›Ñ‘Ð³ÐºÐ¾Ðµ ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ ÐÐ°Ð²Ñ‹ÐºÐ¾Ð² (Ð”Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»ÑŒ) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ Ð½ÐµÐ·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ðµ ÑˆÑ‚Ñ€Ð°Ñ„Ñ‹ Ðº Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ð¸ Ð² Ð¿Ñ€Ð¾Ñ†ÐµÑÑÐµ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ñ Ð½Ð°Ð²Ñ‹ÐºÐ¾Ð² Ð¿Ð¸Ð»Ð¾Ñ‚Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¿Ñ€Ð¸Ð¼ÐµÐ½ÑÐµÑ‚ÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾Ð¹ GalaxyTrader ÐºÐ¾Ð³Ð´Ð° Ð½Ð°Ð²Ñ‹Ðº Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡ÐµÐ½ Ð´Ð»Ñ Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð¡Ð½Ð¸Ð¶Ð°ÐµÑ‚ Ñ‚ÑÐ³Ñƒ Ð¸ Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ. (Ð¢Ð¾Ð»ÑŒÐºÐ¾ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð¹ ÑƒÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ¸)</t>
    <t id="9250">ÐÐ°Ð¸Ð¼ÐµÐ½Ð¾Ð²Ð°Ð½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="9350">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ° ÑÐ¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ð¹ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ð¹ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð—Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ Ð¾Ñ‚Ð¾Ð±Ñ€Ð°Ð¶Ð°ÑŽÑ‚ÑÑ Ð² Ð¿Ð¾Ð»ÑÑ… Ð²Ð²Ð¾Ð´Ð° Ð¸ Ð¼Ð¾Ð³ÑƒÑ‚ Ð±Ñ‹Ñ‚ÑŒ Ð¿ÐµÑ€ÐµÐ¾Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ñ‹. ÐœÐ°ÐºÑÐ¸Ð¼ÑƒÐ¼ 3 ÑÐ¸Ð¼Ð²Ð¾Ð»Ð°. Ð’ÑÐµ Ð¸Ð¼ÐµÐ½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ Ð±ÑƒÐ´ÑƒÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ð¾Ð±Ð½Ð¾Ð²Ð»ÑÑ‚ÑŒÑÑ Ð¿Ñ€Ð¸ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ð¸.</t>
    <t id="9251">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÐ¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ:</t>
    <t id="9252">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð ÐµÐ¼Ð¾Ð½Ñ‚Ð°:</t>
    <t id="9253">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐžÐ±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ:</t>
    <t id="9254">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ñ:</t>
    <t id="9255">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÐµÑ€ÐµÐ½Ð°Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ:</t>
    <t id="9256">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐžÑ‡Ð¸ÑÑ‚ÐºÐ¸:</t>
    <t id="9257">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸:</t>
    <t id="9258">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾:</t>
    <t id="9259">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð˜Ð·Ð¾Ð»ÑÑ†Ð¸Ð¸:</t>
    <t id="9260">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸:</t>
    <t id="9261">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÑ€Ð¾ÑÑ‚Ð¾Ñ:</t>
    <t id="9262">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð¡Ð¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÐ¾Ð±ÐµÐ³Ð°:</t>
    <t id="9268">ÐÐ±Ð±Ñ€ÐµÐ²Ð¸Ð°Ñ‚ÑƒÑ€Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð¸Ð¶Ð¸Ð¼Ð¾Ð³Ð¾ ÑˆÑ‚Ð°Ñ‚Ð°:</t>
    <t id="9269">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ ÑˆÑ‚Ð°Ñ‚Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð½Ð¾Ð³Ð¾ Ð¾Ð±Ð¼ÐµÐ½Ð°:</t>
    <t id="9270">ÐŸÐ¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÑÐºÐ¸Ð¹ Ñ‚ÐµÐ³ Ð¿Ñ€ÐµÑ„Ð¸ÐºÑÐ° Ñ‡ÐµÑ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÐ°:</t>
    <t id="9700">Ð§Ð¸Ñ‚Ñ‹ (ÑÐ»Ð¾Ð¼Ð°Ð½Ð¾. Ñ‚ÑƒÑ‚ Ð½Ð¸Ñ‡ÐµÐ³Ð¾ Ð½ÐµÑ‚!! Ð¿Ñ€Ð°Ð²Ð´Ð°!!)</t>
    <t id="9701">ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸ GT Ð½ÐµÑƒÑÐ·Ð²Ð¸Ð¼Ñ‹</t>
    <t id="9702">Ð’ÑÐµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ° Ð½ÐµÑƒÑÐ·Ð²Ð¸Ð¼Ñ‹</t>
    <t id="9800">Ð˜Ð´Ð¸Ñ‚Ðµ Ð¼Ð¸Ð¼Ð¾, Ð¿Ð¸Ð»Ð¾Ñ‚. Ð­Ñ‚Ð¾ ÑÐ»Ð¾Ð¼Ð°Ð½Ð½Ñ‹Ðµ Ð¸Ð½ÑÑ‚Ñ€ÑƒÐ¼ÐµÐ½Ñ‚Ñ‹ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚Ñ‡Ð¸ÐºÐ°, Ð° Ð½Ðµ Ð²ÐµÑÐµÐ»Ð¾Ðµ Ð¼ÐµÐ½ÑŽ. Ð¢ÑƒÑ‚ Ð½Ð¸Ñ‡ÐµÐ³Ð¾ Ð½ÐµÑ‚. ÐŸÑ€Ð°Ð²Ð´Ð°. Ð’Ð°Ñ Ð¿Ñ€ÐµÐ´ÑƒÐ¿Ñ€ÐµÐ´Ð¸Ð»Ð¸. ÐÐ°Ð²ÐµÑ€Ð½Ð¾Ðµ.</t>
    <t id="9801">ÐšÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ñ Ð¿Ñ€Ð¸ÐºÐ°Ð·Ð¾Ð¼ GalaxyTrader Ð½Ðµ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒÑÑ Ð½Ð¸Ð¶Ðµ 100% ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° Ð¸Ð»Ð¸ Ñ‰Ð¸Ñ‚Ð¾Ð². ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ ÑÐ½Ð¾Ð²Ð°, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ.</t>
    <t id="9802">Ð’ÑÐµ ÐºÐ¾Ñ€Ð°Ð±Ð»Ð¸ Ð¸Ð³Ñ€Ð¾ÐºÐ° Ð½Ðµ Ð¼Ð¾Ð³ÑƒÑ‚ Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚ÑŒÑÑ Ð½Ð¸Ð¶Ðµ 100% ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° Ð¸Ð»Ð¸ Ñ‰Ð¸Ñ‚Ð¾Ð². ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ ÑÐ½Ð¾Ð²Ð°, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ. Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ðµ Ð·Ð°Ñ‚Ñ€Ð°Ð³Ð¸Ð²Ð°ÑŽÑ‚ÑÑ.</t>
    <t id="9703">ÐžÑ‚ÐºÑ€Ñ‹Ñ‚ÑŒ Ð²ÑÐµÐ»ÐµÐ½Ð½ÑƒÑŽ Ð´Ð»Ñ Ñ‚ÐµÑÑ‚Ð¾Ð² GT</t>
    <t id="9704">ÐžÑ‚ÐºÑ€Ñ‹Ñ‚Ð¾</t>
    <t id="9705">ÐžÑ‚ÐºÑ€Ñ‹Ñ‚ÑŒ</t>
    <t id="9803">ÐžÑ‚ÐºÑ€Ñ‹Ð²Ð°ÐµÑ‚ Ñ‚ÑƒÐ¼Ð°Ð½ Ð²Ð¾Ð¹Ð½Ñ‹ Ð²Ð¾ Ð²ÑÐµÑ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ…, Ð¾Ñ‚Ð¼ÐµÑ‡Ð°ÐµÑ‚ Ð²ÑÐµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ ÐºÐ°Ðº Ð¸Ð·Ð²ÐµÑÑ‚Ð½Ñ‹Ðµ, Ð²Ñ‹Ð´Ð°ÐµÑ‚ Ð²ÑÐµ Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¹ Ð¿Ð¾Ð´Ð¿Ð¸ÑÐºÐ¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¹ Ð¸ Ð¿Ð¾Ð´Ð¿Ð¸ÑÑ‹Ð²Ð°ÐµÑ‚ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð¿Ð¾ Ð²ÑÐµÐ¹ Ð³Ð°Ð»Ð°ÐºÑ‚Ð¸ÐºÐµ. ÐÐ°Ð¶Ð¼Ð¸Ñ‚Ðµ ÑÐ½Ð¾Ð²Ð° Ð¿Ð¾ÑÐ»Ðµ Ð½Ð¾Ð²Ñ‹Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð² DLC. Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ Ñ‚ÐµÑÑ‚Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ.</t>
    <t id="9706">ÐœÐ°ÐºÑÐ¸Ð¼Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ XP Ð·Ð°Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ñ‹Ñ… Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² GT</t>
    <t id="9707">ÐœÐ°ÐºÑÐ¸Ð¼Ð¸Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¾</t>
    <t id="9708">XP Ð¼Ð°ÐºÑ</t>
    <t id="9804">Ð£ÑÑ‚Ð°Ð½Ð°Ð²Ð»Ð¸Ð²Ð°ÐµÑ‚ 15 ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ Ð¸ Ð¼Ð°ÐºÑ. XP Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð² Ñ€ÐµÐµÑÑ‚Ñ€Ðµ GT. Ð¡Ð½Ð¸Ð¼Ð°ÐµÑ‚ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ñ. ÐŸÑ€Ð¾Ð¿ÑƒÑÐºÐ°ÐµÑ‚ÑÑ Ð¿Ñ€Ð¸ Ñ€ÐµÐ¶Ð¸Ð¼Ðµ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð²Ð°Ð½Ð¸Ð»ÑŒÐ½Ñ‹Ð¹ XP. Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð»Ñ Ñ‚ÐµÑÑ‚Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ.</t>
    <t id="9351">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÐ¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: RS)</t>
    <t id="9352">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð ÐµÐ¼Ð¾Ð½Ñ‚Ð° (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: RP)</t>
    <t id="9353">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐžÐ±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: MT)</t>
    <t id="9354">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ñ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: TR)</t>
    <t id="9355">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÐµÑ€ÐµÐ½Ð°Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: RR)</t>
    <t id="9356">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐžÑ‡Ð¸ÑÑ‚ÐºÐ¸ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: CL)</t>
    <t id="9357">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: BL)</t>
    <t id="9358">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: FB)</t>
    <t id="9359">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð˜Ð·Ð¾Ð»ÑÑ†Ð¸Ð¸ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: IS)</t>
    <t id="9360">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: TD)</t>
    <t id="9361">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÑ€Ð¾ÑÑ‚Ð¾Ñ (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: ID)</t>
    <t id="9362">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ ÐŸÐ¾Ð±ÐµÐ³Ð° (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: ES)</t>
    <t id="9367">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Â«ÐÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾Â» (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: UR).</t>
    <t id="9368">Ð¡Ð¾ÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ ÑÐ¾ÑÑ‚Ð¾ÑÐ½Ð¸Ñ Pilot Exchange (Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: PE)</t>
    <t id="9369">ÐžÑ‚Ð¾Ð±Ñ€Ð°Ð¶Ð°ÐµÑ‚ÑÑ ÐºÐ°Ðº Ð¿Ñ€ÐµÑ„Ð¸ÐºÑ Ð´Ð»Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»ÐµÐ¹ MK3, Ð²Ð½ÐµÑÐµÐ½Ð½Ñ‹Ñ… Ð² Ñ‡ÐµÑ€Ð½Ñ‹Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÑÐºÐ¸Ñ… Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¹ (Ð²ÐºÐ»ÑŽÑ‡Ð°Ñ Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð½Ñ‹Ñ…). ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ: CB</t>
    <t id="30002">Ð“Ð°Ð»Ð°ÐºÑÐ¸Ð¢Ñ€ÐµÐ¹Ð´ÐµÑ€ ÐœÐš1</t>
    <t id="30102">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† ÑÑ‚Ð°Ð½Ñ†Ð¸ÐµÐ¹ - Ð¿Ñ€Ð¾Ð´Ð°ÐµÑ‚ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ†Ð¸ÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸ÑÐ¼ NPC.</t>
    <t id="30010">Ð”Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="30011">ÐœÐ°ÐºÑ. Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸</t>
    <t id="30012">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸</t>
    <t id="30013">Ð¤Ð¸Ð»ÑŒÑ‚Ñ€ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²</t>
    <t id="30014">Ð¦ÐµÐ»ÐµÐ²Ð¾Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð³Ñ€ÑƒÐ·Ð° Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸</t>
    <t id="30015">Ð”Ð¾Ð¿ÑƒÑÐº Ð²Ð¾Ð·Ð²Ñ€Ð°Ñ‚Ð°</t>
    <t id="30016">ÐšÑƒÐ¿Ð¸Ñ‚ÑŒ Ð¦ÐµÐ»ÐµÐ²Ð¾Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð³Ñ€ÑƒÐ·Ð°</t>
    <t id="30017">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ðµ</t>
    <t id="30018">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ</t>
    <t id="30019">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="30020">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸</t>
    <t id="30021">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ñ</t>
    <t id="30022">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="30023">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="30024">Ð“Ñ€ÑƒÐ·/ÐŸÑ€Ð¸Ð±Ñ‹Ð»ÑŒ</t>
    <t id="30025">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¼ÑƒÐ»ÑŒÑ‚Ð¸ÑÐ´ÐµÐ»ÐºÐ¸</t>
    <t id="30110">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ Ð¸Ð³Ñ€Ð¾ÐºÐ°, Ñ ÐºÐ¾Ñ‚Ð¾Ñ€Ð¾Ð¹ Ð¼Ð¾Ð¶Ð½Ð¾ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹ (Ñ‚Ñ€ÐµÐ±ÑƒÐµÑ‚ÑÑ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸)</t>
    <t id="30111">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð´Ð¾ Ð²Ð¾Ñ€Ð¾Ñ‚ Ð´Ð»Ñ Ð¿Ð¾Ð¸ÑÐºÐ° Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»ÐµÐ¹ NPC (Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð½Ð°Ð²Ñ‹ÐºÐ°Ð¼Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°)</t>
    <t id="30112">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€ÑƒÐ¹Ñ‚Ðµ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð½Ð° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»ÑŽ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ… â€” Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ð»ÑŽÐ±Ð¾Ð¹ Ð´Ñ€ÑƒÐ¶ÐµÑÑ‚Ð²ÐµÐ½Ð½Ð¾Ð¹ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸ Ð½ÐµÐ·Ð°Ð²Ð¸ÑÐ¸Ð¼Ð¾ Ð¾Ñ‚ Ð¿Ñ€Ð°Ð²Ð¸Ð» Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ….</t>
    <t id="30113">Ð”Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€ Ð¿Ð¾ÑÑƒÐ´Ñ‹; Ð¾ÑÑ‚Ð°Ð²ÑŒÑ‚Ðµ Ð¿ÑƒÑÑ‚Ñ‹Ð¼, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð¿Ñ€Ð¾Ð´Ð°Ñ‚ÑŒ Ð²ÑÐµ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñ‹ Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="30114">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð³Ñ€ÑƒÐ·Ð° Ð¿ÐµÑ€ÐµÐ´ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²ÐºÐ¾Ð¹ Ð² â€‹â€‹ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð¾Ð²ÐºÑƒ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="30115">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ñ… Ð¿Ñ€Ñ‹Ð¶ÐºÐ¾Ð², Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð½Ñ‹Ñ… Ð¿Ñ€Ð¸ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ð¸ Ð²Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ Ñ‚Ð¾Ð²Ð°Ñ€Ð° Ð² Ð¿Ð¾ÐµÐ·Ð´ÐºÑƒ (0 = Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ð¸ Ð½ÐµÐ¿Ð¾ÑÑ€ÐµÐ´ÑÑ‚Ð²ÐµÐ½Ð½Ð¾ Ð½Ð° Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ðµ)</t>
    <t id="30116">Ð¦ÐµÐ»ÐµÐ²Ð¾Ðµ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ð³Ñ€ÑƒÐ·Ð¾Ð² Ð´Ð»Ñ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð¾Ðº (Ð¼ÑÐ³ÐºÐ°Ñ Ñ†ÐµÐ»ÑŒ, Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€ Ð¼Ð¾Ð¶ÐµÑ‚ ÑƒÐ¹Ñ‚Ð¸ Ñ€Ð°Ð½ÑŒÑˆÐµ)</t>
    <t id="30117">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ðµ Ð¿Ð¾ ÐºÐ°Ð¶Ð´Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐµ</t>
    <t id="30118">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ: 0 = Ð¢Ð¸Ñ…Ð¸Ð¹, 1 = ÐÐ¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹, 2 = ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ñ‹Ð¹</t>
    <t id="30119">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ ÑÐ¸ÑÑ‚ÐµÐ¼Ñƒ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ð¸ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÐ° Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ñ€ÐµÐ·ÐµÑ€Ð²Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ</t>
    <t id="30120">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð²ÐµÐ´ÐµÐ½Ð¸Ñ Ð¶ÑƒÑ€Ð½Ð°Ð»Ð° Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸: 0 = Ð²Ñ‹ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, 1 = Ð½Ð¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¾, 2 = Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ð¾.</t>
    <t id="30121">ÐŸÑ€Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ð¸ Ñ‚Ð°ÐºÐ¶Ðµ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ð¹Ñ‚Ðµ Ñ€ÐµÑÑƒÑ€ÑÑ‹ Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸. ÐŸÐ¾ÑÑ‚Ð°Ð²ÐºÐ° Ð¸Ð¼ÐµÐµÑ‚ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚, ÐºÐ¾Ð³Ð´Ð° Ð¾Ð±ÑŠÐµÐ¼ Ñ…Ñ€Ð°Ð½Ð¸Ð»Ð¸Ñ‰Ð° Ð¿Ð°Ð´Ð°ÐµÑ‚ Ð½Ð¸Ð¶Ðµ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ð°.</t>
    <t id="30122">ÐšÐ¾Ð³Ð´Ð° ÐºÐ°ÐºÐ¾Ð¹-Ð»Ð¸Ð±Ð¾ Ñ€ÐµÑÑƒÑ€Ñ Ð¿Ð°Ð´Ð°ÐµÑ‚ Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚Ð° Ð¾Ñ‚ Ñ†ÐµÐ»ÐµÐ²Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ, Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ Ð¸Ð¼ÐµÐµÑ‚ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð°Ð´ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ÐµÐ¹. Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€ÑƒÐµÑ‚ÑÑ, ÐµÑÐ»Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ðµ Ð¼Ð¾Ð¶ÐµÑ‚ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚ÑŒ ÑÐµÐ±Ðµ Ñ€ÐµÑÑƒÑ€ÑÑ‹</t>
    <t id="30123">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð¸Ð»Ð¸ Ð¿Ð¾ÐºÑƒÐ¿ÐºÑƒ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ‹Ñ…/ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð±Ð°Ð½Ð´Ð½Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð², ÐµÑÐ»Ð¸ Ñ‚Ð°ÐºÐ¾Ð²Ñ‹Ðµ Ð¸Ð¼ÐµÑŽÑ‚ÑÑ.</t>
    <t id="30124">Ð’Ñ‹Ð±Ð¾Ñ€ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸: 1 - Ð³Ñ€ÑƒÐ· (Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ ÑÐºÐ»Ð°Ð´Ð° Ð¿Ð¾ Ñ‚Ð¾Ð²Ð°Ñ€Ñƒ; Ð¿Ñ€Ð¸ Ñ€Ð°Ð²ÐµÐ½ÑÑ‚Ð²Ðµ - Ð¿Ð¾ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸), 2 - Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ (Ð»ÑƒÑ‡ÑˆÐ¸Ð¹ Ð¿Ð¾ÐºÐ°Ð·Ð°Ñ‚ÐµÐ»ÑŒ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸)</t>
    <t id="30125">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¾Ð±ÑŠÐµÐ´Ð¸Ð½ÑÑ‚ÑŒ Ð½ÐµÑÐºÐ¾Ð»ÑŒÐºÐ¾ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ Ð² Ð¾Ð´Ð¸Ð½ Ñ†Ð¸ÐºÐ» (Ð´Ð¾ 3 Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð¸Ð»Ð¸ Ð½Ð°Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ð¹). ÐžÑ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ðµ Ð´Ð»Ñ Ñ€ÐµÐ¶Ð¸Ð¼Ð° Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð¾Ð´Ð½Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸ Ð·Ð° Ñ†Ð¸ÐºÐ»</t>
    <t id="30200">ÐŸÑ€Ð¾Ð´Ð°Ð¼ %1 %2 Ñ %3 Ð¿Ð¾ %4.</t>
    <t id="30201">ÐŸÐ¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ð¸ Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ†Ð¸ÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ðµ Ð½Ð°Ð¹Ð´ÐµÐ½Ñ‹ Ð² Ñ‚ÐµÑ‡ÐµÐ½Ð¸Ðµ %1 Ð¿ÐµÑ€ÐµÑ…Ð¾Ð´Ð¾Ð²</t>
    <t id="30202">Ð‘Ð°Ð·Ð¾Ð²Ð°Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ %1 ÑƒÐ½Ð¸Ñ‡Ñ‚Ð¾Ð¶ÐµÐ½Ð° â€“ Ð¿Ñ€Ð¸ÐºÐ°Ð· Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½</t>
    <t id="30203">Ð”Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ %1 Ð±Ð¾Ð»ÑŒÑˆÐµ Ð½Ðµ Ð¿Ñ€Ð¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð¸Ñ‚ Ð¸Ð³Ñ€Ð¾ÐºÑƒ â€” Ð·Ð°ÐºÐ°Ð· Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½.</t>
    <t id="30204">Ð¢Ñ€ÐµÐ±ÑƒÐµÑ‚ÑÑ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ â€“ Ð·Ð°ÐºÐ°Ð· Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½</t>
    <t id="30205">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† ÑÑ‚Ð°Ð½Ñ†Ð¸ÐµÐ¹ MK1 Ð½Ð°Ñ‡Ð°Ð» Ñ€Ð°Ð±Ð¾Ñ‚Ñƒ Ð² %1</t>
    <t id="30206">Ð—Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ð°Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð°: %1 %2 Ð¿Ñ€Ð¾Ð´Ð°Ð½Ð¾ %3 Ð·Ð° %4 Cr (Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ: %5 Cr)</t>
    <t id="30207">ÐŸÐ¾ÐµÐ·Ð´ÐºÐ° Ñ Ð½ÐµÑÐºÐ¾Ð»ÑŒÐºÐ¸Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸: Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° %1 Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð² %2 Ð¿ÑƒÐ½ÐºÑ‚Ð¾Ð² Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ.</t>
    <t id="30208">Ð”Ð¾ÑÑ‚Ð°Ð²ÐºÐ° %1 %2 Ð½Ð° %3 Ð¸Ð· %4</t>
    <t id="30500">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ GalaxyTrader MK1</t>
    <t id="30501">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="30502">ÐœÐ°ÐºÑ. Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="30503">Ð¦ÐµÐ»ÑŒ Ð¿Ð¾ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸ÑŽ Ð³Ñ€ÑƒÐ·Ð° Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="30504">ÐŸÐ¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ Ð¸Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸</t>
    <t id="30505">Ð”Ð¾Ð¿ÑƒÑÐº Ð²Ð¾Ð·Ð²Ñ€Ð°Ñ‚Ð° Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="30506">Ð’Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ, ÐºÐ¾Ð³Ð´Ð° ÑÐ´ÐµÐ»ÐºÐ¸ Ð½Ðµ Ð½Ð°Ð¹Ð´ÐµÐ½Ñ‹</t>
    <t id="30507">Ð¦ÐµÐ»ÐµÐ²Ð¾Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ Ð³Ñ€ÑƒÐ·Ð° Ð¿Ñ€Ð¸ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐµ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="31002">Ð“Ð°Ð»Ð°ÐºÑ‚Ð¸ÐºÐ°-Ð¨Ð°Ñ…Ñ‚ÐµÑ€</t>
    <t id="31102">ÐÐ²Ñ‚Ð¾Ð½Ð¾Ð¼Ð½Ð°Ñ Ð´Ð¾Ð±Ñ‹Ñ‡Ð° Ñ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸ÐµÐ¼ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹ Ð¸ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑÐ¸ÐµÐ¹ XP</t>
    <t id="31010">Ð”Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="31110">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ Ð´Ð»Ñ Ð´Ð¾Ð±Ñ‹Ñ‡Ð¸ Ð¸ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ (Ð²Ð·Ð°Ð¸Ð¼Ð¾Ð¸ÑÐºÐ»ÑŽÑ‡Ð¸Ð¼Ð¾ Ñ Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¼ ÑÐµÐºÑ‚Ð¾Ñ€Ð¾Ð¼)</t>
    <t id="31011">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€</t>
    <t id="31111">Ð¡ÐµÐºÑ‚Ð¾Ñ€ Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹; Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ÑÑ, ÐµÑÐ»Ð¸ Ð½Ðµ Ð·Ð°Ð´Ð°Ð½Ð° Ð”Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="31012">ÐšÐ¾Ñ€Ð·Ð¸Ð½Ð° Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð²</t>
    <t id="31112">Ð ÐµÑÑƒÑ€ÑÑ‹ Ð´Ð»Ñ Ð´Ð¾Ð±Ñ‹Ñ‡Ð¸; Ð¿ÑƒÑÑ‚Ð¾ = Ð¿Ð¾ ÑÐ¿Ñ€Ð¾ÑÑƒ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹</t>
    <t id="31013">Ð¦ÐµÐ»ÐµÐ²Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="31113">ÐÐµÐ¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹ Ð´Ð»Ñ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸; Ð¿ÑƒÑÑ‚Ð¾ = Ð¸Ð· Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ³Ð¾ ÐºÐ¾Ð½Ñ‚ÐµÐºÑÑ‚Ð°</t>
    <t id="31014">ÐŸÐ¾Ñ€Ð¾Ð³ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ %</t>
    <t id="31114">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¸ Ñ Ñ‚Ð°ÐºÐ¸Ð¼ Ð¸Ð»Ð¸ Ð±Ð¾Ð»ÐµÐµ Ð²Ñ‹ÑÐ¾ÐºÐ¸Ð¼ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚Ð¾Ð¼ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ ÑÑ‡Ð¸Ñ‚Ð°ÑŽÑ‚ÑÑ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð½Ñ‹Ð¼Ð¸</t>
    <t id="31015">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð¸Ð·Ð»Ð¸ÑˆÐºÐ¾Ð² Ð´Ñ€ÑƒÐ³Ð¸Ð¼</t>
    <t id="31115">Ð•ÑÐ»Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ Ð¸ Ð¾ÑÐ½Ð¾Ð²Ð½Ñ‹Ðµ Ñ†ÐµÐ»Ð¸ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ñ‹, Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚ÑŒ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÐ¼ Ð´Ñ€ÑƒÐ³Ð¸Ñ… Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¹</t>
    <t id="31016">ÐÐ°Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÑŒ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="31116">ÐÐ°Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÑŒ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð´Ð¾Ð±Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ð¼ Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð½Ñ‹Ð¼ Ð”Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ¹ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, ÐºÐ¾Ð³Ð´Ð° Ð¿Ñ€Ð¸Ð¼ÐµÐ½Ð¸Ð¼Ð¾</t>
    <t id="31017">ÐžÑÑ‚Ð°Ð²Ð°Ñ‚ÑŒÑÑ Ð´Ð¾Ð¼Ð°</t>
    <t id="31117">ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð¸Ñ‚ÑŒ Ð´Ð¾Ð±Ñ‹Ñ‡Ñƒ/Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ¹ Ð¾Ð±Ð»Ð°ÑÑ‚ÑŒÑŽ, ÐºÑ€Ð¾Ð¼Ðµ Ñ€ÐµÐ¶Ð¸Ð¼Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ Ð¸Ð·Ð»Ð¸ÑˆÐºÐ¾Ð²</t>
    <t id="31018">ÐÐ²Ñ‚Ð¾Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°Ð½Ð¸Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ½Ñ‹Ñ… Ð·Ð¾Ð½Ð´Ð¾Ð²</t>
    <t id="31118">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¸ Ñ€Ð°Ð·Ð²Ð¾Ñ€Ð°Ñ‡Ð¸Ð²Ð°Ñ‚ÑŒ Ð·Ð°Ð³Ñ€ÑƒÐ¶ÐµÐ½Ð½Ñ‹Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ½Ñ‹Ðµ Ð·Ð¾Ð½Ð´Ñ‹ Ð¸ Ð²ÐºÐ»ÑŽÑ‡Ð°Ñ‚ÑŒ Ð¸Ñ… Ð² Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ð¾Ð±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ</t>
    <t id="31019">ÐœÐ°ÐºÑ. Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ ÑÐ±Ð¾Ñ€Ð°</t>
    <t id="31119">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð² Ð¿Ñ€Ñ‹Ð¶ÐºÐ°Ñ… Ð´Ð»Ñ ÑÐ±Ð¾Ñ€Ð° (0 = Ð»Ð¸Ð¼Ð¸Ñ‚ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°/ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°)</t>
    <t id="31020">ÐœÐ°ÐºÑ. Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸</t>
    <t id="31120">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð² Ð¿Ñ€Ñ‹Ð¶ÐºÐ°Ñ… Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ (0 = Ð»Ð¸Ð¼Ð¸Ñ‚ Ð¿Ð¸Ð»Ð¾Ñ‚Ð°/ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°)</t>
    <t id="31021">Ð‘Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð¾Ð²ÐºÐ° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="31121">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð´ÐµÑ‚ÐµÑ€Ð¼Ð¸Ð½Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½ÑƒÑŽ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÑŽ Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸Ð¹ Ð´Ð»Ñ ÑÐ½Ð¸Ð¶ÐµÐ½Ð¸Ñ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹</t>
    <t id="31022">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¿ÐµÑ€ÐµÐ¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ¸ ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="31122">ÐšÐ°Ðº Ñ‡Ð°ÑÑ‚Ð¾ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÑÐµÑ‚ÑÑ Ð¾Ñ†ÐµÐ½ÐºÐ° ÑÐ¿Ñ€Ð¾ÑÐ°/Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ð¼Ð°Ð¹Ð½ÐµÑ€Ð°</t>
    <t id="31023">ÐšÑ€Ð¸Ñ‚Ð¸Ñ‡ÐµÑÐºÐ°Ñ Ð´ÐµÐ»ÑŒÑ‚Ð° ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="31123">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð´ÐµÐ»ÑŒÑ‚Ð° ÑÑ€Ð¾Ñ‡Ð½Ð¾ÑÑ‚Ð¸ Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¾Ð³Ð¾ Ñ€ÐµÑÑƒÑ€ÑÐ° Ð´Ð¾Ð±Ñ‹Ñ‡Ð¸</t>
    <t id="31024">ÐœÐ¸Ð½. Ð·Ð°Ð´ÐµÑ€Ð¶ÐºÐ° Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ</t>
    <t id="31124">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ð²Ñ€ÐµÐ¼Ñ Ð¼ÐµÐ¶Ð´Ñƒ Ð´Ð²ÑƒÐ¼Ñ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸ÑÐ¼Ð¸ Ñ€ÐµÑÑƒÑ€ÑÐ° Ð´Ð»Ñ ÑÑ‚Ð¾Ð³Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="31025">ÐœÐ¸Ð½. Ð¿Ð¾Ñ€Ð¾Ð³ Ð·Ð°ÐºÑ€ÐµÐ¿Ð»ÐµÐ½Ð¸Ñ Ð³Ñ€ÑƒÐ·Ð° %</t>
    <t id="31125">Ð•ÑÐ»Ð¸ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ñ‚Ñ€ÑŽÐ¼Ð° Ð²Ñ‹ÑˆÐµ Ð¿Ð¾Ñ€Ð¾Ð³Ð°, ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð°ÐµÑ‚ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ñ‚ÑŒ Ñ‚ÐµÐºÑƒÑ‰ÑƒÑŽ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÑƒ Ð¿ÐµÑ€ÐµÐ´ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸ÐµÐ¼</t>
    <t id="31026">Ð–ÐµÑÑ‚ÐºÐ°Ñ Ð°Ð²Ð°Ñ€Ð¸Ð¹Ð½Ð°Ñ Ð´ÐµÐ»ÑŒÑ‚Ð°</t>
    <t id="31126">Ð”ÐµÐ»ÑŒÑ‚Ð° ÑÑ€Ð¾Ñ‡Ð½Ð¾ÑÑ‚Ð¸, Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‰Ð°Ñ Ð½ÐµÐ¼ÐµÐ´Ð»ÐµÐ½Ð½Ð¾Ðµ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ð½ÐµÑÐ¼Ð¾Ñ‚Ñ€Ñ Ð½Ð° Ð¿Ð¾Ñ€Ð¾Ð³ Ð·Ð°ÐºÑ€ÐµÐ¿Ð»ÐµÐ½Ð¸Ñ Ð³Ñ€ÑƒÐ·Ð°</t>
    <t id="31027">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹</t>
    <t id="31127">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹: 0=Ð¢Ð¸Ñ…Ð¾, 1=ÐžÐ±Ñ‹Ñ‡Ð½Ñ‹Ð¹, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾</t>
    <t id="31028">Ð¢Ð¾Ð»ÑŒÐºÐ¾ Ð¸Ð³Ñ€Ð¾Ð²Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="31128">Ð•ÑÐ»Ð¸ ÑÑ‚Ð¾Ñ‚ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½, Ñ‚Ð¾Ð»ÑŒÐºÐ¾ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, Ð¿Ñ€Ð¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð°Ñ‰Ð¸Ðµ Ð¸Ð³Ñ€Ð¾ÐºÑƒ, ÑÑ‡Ð¸Ñ‚Ð°ÑŽÑ‚ÑÑ Ð¾Ð±ÑŠÐµÐºÑ‚Ð°Ð¼Ð¸ ÑÐ¿Ñ€Ð¾ÑÐ°.</t>
    <t id="31031">Ð¡Ð½Ð°Ñ‡Ð°Ð»Ð° Ð¿Ñ€Ð¾Ð²ÐµÑ€ÑÑ‚ÑŒ ÑÐ¿Ñ€Ð¾Ñ</t>
    <t id="31131">Ð•ÑÐ»Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, Ð¼Ð°Ð¹Ð½ÐµÑ€ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÑÐµÑ‚ ÑÐ¿Ñ€Ð¾Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹ Ð¿ÐµÑ€ÐµÐ´ Ð´Ð¾Ð±Ñ‹Ñ‡ÐµÐ¹ Ð¸ Ñ€Ð°ÑÑÑ‚Ð°Ð²Ð»ÑÐµÑ‚ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ñ‹ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð². Ð•ÑÐ»Ð¸ Ð²Ñ‹ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, Ð´Ð¾Ð±Ñ‹Ð²Ð°ÐµÑ‚ Ð¸Ð· ÐºÐ¾Ñ€Ð·Ð¸Ð½Ñ‹ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð² Ð±ÐµÐ· Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ¸ ÑÐ¿Ñ€Ð¾ÑÐ° Ð¸ Ð½Ð°ÐºÐ°Ð¿Ð»Ð¸Ð²Ð°ÐµÑ‚ Ð³Ñ€ÑƒÐ· Ð´Ð¾ Ð¿Ð¾ÑÐ²Ð»ÐµÐ½Ð¸Ñ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ñ (Ñ€ÐµÐºÐ¾Ð¼ÐµÐ½Ð´ÑƒÐµÑ‚ÑÑ Ð´Ð»Ñ Ñ„Ð»Ð¾Ñ‚Ð¾Ð² Ñ Ð¾Ð´Ð½Ð¸Ð¼ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð¼).</t>
    <t id="31032">ÐŸÑ€ÐµÑ€Ñ‹Ð²Ð°Ð½Ð¸Ðµ Ñ„Ð¸Ð·. ÑÐºÐ»Ð°Ð´Ð° %</t>
    <t id="31132">Ð”Ð»Ñ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¾Ð² ÑƒÑ€Ð¾Ð²Ð½Ñ 6+: Ð¿Ñ€ÐµÐºÑ€Ð°Ñ‰Ð°ÐµÑ‚ Ð´Ð¾Ð±Ñ‹Ñ‡Ñƒ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ Ñ‚Ð¾Ð²Ð°Ñ€Ð°, ÐºÐ¾Ð³Ð´Ð° Ñ„Ð¸Ð·Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ð·Ð°Ð¿Ð°Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¿Ð»ÑŽÑ Ð³Ñ€ÑƒÐ· Ñ€ÐµÐ»ÐµÐ²Ð°Ð½Ñ‚Ð½Ñ‹Ñ… Ð¼Ð°Ð¹Ð½ÐµÑ€Ð¾Ð² Ð¿Ñ€ÐµÐ²Ñ‹ÑÐ¸Ñ‚ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ð¹ Ñ„Ð¸Ð·Ð¸Ñ‡ÐµÑÐºÐ¸Ð¹ Ð·Ð°Ð¿Ð°Ñ Ð½Ð° ÑÑ‚Ð¾Ñ‚ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ Ñ€ÐµÐ°Ð»ÑŒÐ½Ñ‹Ðµ Ð³Ñ€ÑƒÐ·Ð¾Ð²Ñ‹Ðµ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð°, Ð½Ðµ Ð¿Ð¾Ñ€Ð¾Ð³ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ. 0 = Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾.</t>
    <t id="32002">GalaxyTrader ÐŸÐ¾ÑÑ‚Ð°Ð²ÐºÐ° ÐœÐš4</t>
    <t id="32102">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ† Ð¿Ð¾ÑÑ‚Ð°Ð²ÐºÐ°Ð¼Ð¸ Ð¸Ð³Ñ€Ð¾Ð²Ñ‹Ñ… ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹, Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑŽÑ‰Ð¸Ð¹ ÐºÑÑˆ GT/ÐºÐ¾Ð½Ð²ÐµÐ¹ÐµÑ€ Ð¿Ð¾Ð¸ÑÐºÐ° Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼ Ð²Ñ€ÐµÐ¼ÐµÐ½Ð¸</t>
    <t id="32010">Ð Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ð¾ÐºÑ€Ñ‹Ñ‚Ð¸Ñ</t>
    <t id="32110">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð´Ð¾ Ð²Ð¾Ñ€Ð¾Ñ‚ Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð´Ð»Ñ Ð¿Ð¾Ð¸ÑÐºÐ° Ð¿ÑƒÐ½ÐºÑ‚Ð° Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ</t>
    <t id="32011">ÐšÑƒÐ¿Ð¸Ñ‚ÑŒ Ð Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ</t>
    <t id="32111">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ñ€Ð°ÑÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð²Ð¾Ñ€Ð¾Ñ‚ Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð´Ð»Ñ Ð¿Ð¾Ð¸ÑÐºÐ° Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ¾Ð²</t>
    <t id="32012">ÐŸÐ¾Ð´Ð°Ð²Ð°Ñ‚ÑŒ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð¾Ð¼Ð°</t>
    <t id="32112">Ð•ÑÐ»Ð¸ ÑÑ‚Ð° Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð°, Ð¾Ð±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°ÐµÑ‚ÑÑ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð·Ð°Ð¿Ñ€Ð¾Ñ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ¹ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸.</t>
    <t id="32013">Ð¡Ñ‚Ñ€Ð¾Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="32113">Ð•ÑÐ»Ð¸ ÑÑ‚Ð¾Ñ‚ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½, Ð¾Ð±ÑÐ»ÑƒÐ¶Ð¸Ð²Ð°ÐµÑ‚ÑÑ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð¿Ð¾Ñ‚Ñ€ÐµÐ±Ð½Ð¾ÑÑ‚ÑŒ Ð² Ñ…Ñ€Ð°Ð½Ð¸Ð»Ð¸Ñ‰Ðµ Ð´Ð»Ñ ÑÐ±Ð¾Ñ€ÐºÐ¸.</t>
    <t id="32014">ÐšÑƒÐ¿Ð¸Ñ‚ÑŒ Ñƒ Ð¸Ð³Ñ€Ð¾ÐºÐ°</t>
    <t id="32114">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð·Ð°ÐºÑƒÐ¿ÐºÑƒ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ñƒ Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ¾Ð², Ð¿Ñ€Ð¸Ð½Ð°Ð´Ð»ÐµÐ¶Ð°Ñ‰Ð¸Ñ… Ð¸Ð³Ñ€Ð¾ÐºÐ°Ð¼.</t>
    <t id="32015">ÐšÑƒÐ¿Ð¸Ñ‚ÑŒ Ñƒ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸</t>
    <t id="32115">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð·Ð°ÐºÑƒÐ¿ÐºÑƒ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ñƒ Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ¾Ð² Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¹, Ð½Ðµ ÑÐ²Ð»ÑÑŽÑ‰Ð¸Ñ…ÑÑ Ð¸Ð³Ñ€Ð¾ÐºÐ°Ð¼Ð¸.</t>
    <t id="32016">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ñ€ÐµÑÑƒÑ€ÑÑ‹</t>
    <t id="32116">Ð’ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð² Ð² ÑÐ¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="32017">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ð¼ÐµÐ¶ÑƒÑ‚Ð¾Ñ‡Ð½Ñ‹Ðµ</t>
    <t id="32117">Ð’ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¾Ð¼ÐµÐ¶ÑƒÑ‚Ð¾Ñ‡Ð½Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð² ÑÐ¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="32018">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñ‹</t>
    <t id="32118">Ð’ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð² ÑÐ¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="32019">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ðµ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð¾Ð²Ð°Ð½Ð¸Ðµ</t>
    <t id="32119">Ð’ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð² Ð² ÑÐ¾Ð¿Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ ÑÐ¿Ñ€Ð¾ÑÐ°</t>
    <t id="20002">Ð“Ð°Ð»Ð°ÐºÑÐ¸Ð¢Ñ€ÐµÐ¹Ð´ÐµÑ€ ÐœÐš2</t>
    <t id="20102">Ð Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð¼ÐµÐ¶Ð´Ñƒ ÑÐºÐ»Ð°Ð´Ð°Ð¼Ð¸ Ñ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸ÐµÐ¼ Ð¿Ð¾Ñ€Ð¾Ð³Ð°Ð¼Ð¸ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ</t>
    <t id="20010">Ð˜ÑÑ…Ð¾Ð´Ð½Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="20011">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ</t>
    <t id="20012">ÐœÐ¸Ð½. Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ %</t>
    <t id="20013">Ð‘Ð°Ð·Ð¾Ð²Ñ‹Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ %</t>
    <t id="20014">ÐœÐ°ÐºÑ. Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ %</t>
    <t id="20015">Ð¤Ð¸Ð»ÑŒÑ‚Ñ€ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²</t>
    <t id="20016">Ð”Ð²ÑƒÐ½Ð°Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð½Ñ‹Ð¹ Ñ€ÐµÐ¶Ð¸Ð¼</t>
    <t id="20017">Ð”Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ (Ð½ÐµÐ¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð¾)</t>
    <t id="20018">ÐœÐ°ÐºÑ. Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="20032">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ (Ð½ÐµÐ¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð¾)</t>
    <t id="20019">Ð’Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ñ†Ð¸ÐºÐ»Ð°</t>
    <t id="20030">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð¼Ð°Ð»Ñ‹Ðµ Ð¾Ð±ÑŠÐµÐ¼Ñ‹</t>
    <t id="20031">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ° Ð´Ð»Ñ Ð¼Ð°Ð»Ñ‹Ñ… Ð¾Ð±ÑŠÐµÐ¼Ð¾Ð² %</t>
    <t id="20110">Ð¡Ð¿Ð¸ÑÐ¾Ðº Ð¸ÑÑ…Ð¾Ð´Ð½Ñ‹Ñ… ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹, Ñ ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ñ… Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÑÑŽÑ‚ÑÑ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹</t>
    <t id="20111">Ð¡Ð¿Ð¸ÑÐ¾Ðº ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¹/ÑÐºÐ»Ð°Ð´Ð¾Ð² Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð´Ð»Ñ Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ</t>
    <t id="20112">ÐŸÐ¾Ñ€Ð¾Ð³ ÑÑ€Ð¾Ñ‡Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ: ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ % Ð¿Ð¾Ð»ÑƒÑ‡Ð°ÑŽÑ‚ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚</t>
    <t id="20113">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð¿Ð¾Ñ€Ð¾Ð³ Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°: Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸Ðº Ð´Ð¾Ð»Ð¶ÐµÐ½ Ð±Ñ‹Ñ‚ÑŒ Ð²Ñ‹ÑˆÐµ ÑÑ‚Ð¾Ð³Ð¾ %</t>
    <t id="20114">ÐŸÐ¾Ñ€Ð¾Ð³ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°: Ð²Ñ‹ÑˆÐµ ÑÑ‚Ð¾Ð³Ð¾ % Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð¸Ð´Ñ‘Ñ‚ Ð¸ Ð² Ð½Ðµ ÑÑ€Ð¾Ñ‡Ð½Ñ‹Ðµ Ð¿ÑƒÐ½ÐºÑ‚Ñ‹</t>
    <t id="20115">ÐÐµÐ¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ Ñ„Ð¸Ð»ÑŒÑ‚Ñ€ Ñ‚Ð¾Ð²Ð°Ñ€Ð¾Ð²; Ð¿ÑƒÑÑ‚Ð¾ = Ð²ÑÐµ Ñ‚Ð¾Ð²Ð°Ñ€Ñ‹ Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°</t>
    <t id="20116">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ñ‹Ð¹ ÑÐ±Ð¾Ñ€ Ð¸Ð· Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð² Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸Ðº Ð¿Ñ€Ð¸ Ð¸Ð·Ð±Ñ‹Ñ‚ÐºÐµ</t>
    <t id="20117">ÐÐµÐ¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð´Ð»Ñ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ. Ð•ÑÐ»Ð¸ Ð¿ÑƒÑÑ‚Ð¾, ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒ Ð½Ðµ Ð±ÑƒÐ´ÐµÑ‚ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¾Ð½Ð½Ð¾ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½.</t>
    <t id="20118">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð² Ð¿Ñ€Ñ‹Ð¶ÐºÐ°Ñ… Ð¼ÐµÐ¶Ð´Ñƒ Ð¸ÑÑ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ¾Ð¼ Ð¸ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸ÐµÐ¼ (0 = Ð±ÐµÐ· Ð»Ð¸Ð¼Ð¸Ñ‚Ð°)</t>
    <t id="20132">ÐÐµÐ¾Ð±ÑÐ·Ð°Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ð´Ð»Ñ ÑÑ‚Ð¾ÑÐ½ÐºÐ¸ Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾ÑÑ‚Ð¾Ðµ, ÐµÑÐ»Ð¸ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ðµ Ð·Ð°Ð´Ð°Ð½Ð°.</t>
    <t id="20119">Ð’Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð¼ÐµÐ¶Ð´Ñƒ Ñ†Ð¸ÐºÐ»Ð°Ð¼Ð¸ Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ</t>
    <t id="20130">Ð Ð°Ð·Ñ€ÐµÑˆÐ°ÐµÑ‚ Ð¼ÐµÐ½ÑŒÑˆÐ¸Ðµ Ð¿Ð°Ñ€Ñ‚Ð¸Ð¸ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð¾Ðº Ñ ÑƒÑ‡ÐµÑ‚Ð¾Ð¼ ÑÑ€Ð¾Ñ‡Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð¸Ð¶Ðµ Ð¾Ð±Ñ‹Ñ‡Ð½Ð¾Ð³Ð¾ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ñ‚Ñ€ÑŽÐ¼Ð°.</t>
    <t id="20131">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ñ‚Ñ€ÑŽÐ¼Ð° Ð¿Ñ€Ð¸ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð½Ð¾Ð¼ Ñ€ÐµÐ¶Ð¸Ð¼Ðµ Ð¼Ð°Ð»Ñ‹Ñ… Ð¾Ð±ÑŠÐµÐ¼Ð¾Ð².</t>
    <t id="20200">Ð Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ %1 %2 Ð¸Ð· %3 Ð² %4</t>
    <t id="20201">ÐžÐ±Ñ€Ð°Ñ‚Ð½Ñ‹Ð¹ Ñ€ÐµÐ¹Ñ: ÑÐ±Ð¾Ñ€ %1 %2 Ð¸Ð· %3 Ð² %4</t>
    <t id="20202">Ð Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð½Ðµ Ñ‚Ñ€ÐµÐ±ÑƒÐµÑ‚ÑÑ - Ð²ÑÐµ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð´Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ð¾ Ð¾Ð±ÐµÑÐ¿ÐµÑ‡ÐµÐ½Ñ‹</t>
    <t id="20203">Ð’ÑÐµ Ð¸ÑÑ…Ð¾Ð´Ð½Ñ‹Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½ÐµÐ´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹ - Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð² Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ð¸</t>
    <t id="20204">Ð’ÑÐµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð½ÐµÐ´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹ - Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð² Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ð¸</t>
    <t id="20205">Ð˜ÑÑ…Ð¾Ð´Ð½Ð°Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ %1 ÑƒÐ½Ð¸Ñ‡Ñ‚Ð¾Ð¶ÐµÐ½Ð° - ÑƒÐ´Ð°Ð»ÐµÐ½Ð° Ð¸Ð· Ð¿Ñ€Ð¸ÐºÐ°Ð·Ð° Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ</t>
    <t id="20206">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ %1 ÑƒÐ½Ð¸Ñ‡Ñ‚Ð¾Ð¶ÐµÐ½Ð° - ÑƒÐ´Ð°Ð»ÐµÐ½Ð° Ð¸Ð· Ð¿Ñ€Ð¸ÐºÐ°Ð·Ð° Ñ€Ð°ÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ</t>
    <t id="20500">GalaxyTrader MK2 - Ð“Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ‹Ðµ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="20501">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ MK2 Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ</t>
    <t id="20510">ÐœÐ¸Ð½. Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ %</t>
    <t id="20511">Ð‘Ð°Ð·Ð¾Ð²Ñ‹Ð¹ ÑƒÑ€Ð¾Ð²ÐµÐ½ÑŒ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ %</t>
    <t id="20512">ÐœÐ°ÐºÑ. Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ %</t>
    <t id="20513">ÐžÐ¶Ð¸Ð´Ð°Ð½Ð¸Ðµ Ñ†Ð¸ÐºÐ»Ð° Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ (Ñ)</t>
    <t id="20514">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ðµ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ðµ Ñ‚Ñ€ÑŽÐ¼Ð° %</t>
    <t id="20520">ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾ÑÑ‚ÑŒ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ð¹</t>
    <t id="20521">Ð£Ñ€Ð¾Ð²ÐµÐ½ÑŒ Ð¾Ñ‚Ð»Ð°Ð´ÐºÐ¸</t>
    <t id="10006">Ð’ÐµÑ€Ð½ÑƒÑ‚ÑŒÑÑ Ð´Ð¾Ð¼Ð¾Ð¹</t>
    <t id="10007">GalaxyTrader ÐŸÐ¾ÑÑ‚Ð°Ð²ÐºÐ° ÐœÐš4-2</t>
    <t id="10106">ÐŸÑ€Ð¸ÑÑ‚Ñ‹ÐºÑƒÐ¹Ñ‚ÐµÑÑŒ Ðº Ð´Ð¾Ð¼Ð°ÑˆÐ½ÐµÐ¹ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸ Ð¾ÑÑ‚Ð°Ð²Ð°Ð¹Ñ‚ÐµÑÑŒ Ñ‚Ð°Ð¼ Ð´Ð¾ Ð²Ð¾Ð·Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸.</t>
    <t id="10107">Ð—Ð°ÐºÐ°Ð· ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ñ Ð¸Ð³Ñ€Ð¾ÐºÐ° Ñ Ð¿Ð¾Ð»Ð·ÑƒÐ½ÐºÐ°Ð¼Ð¸ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð° Ñ†ÐµÐ»ÐµÐ¹ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸</t>
    <t id="30026">Ð’Ð¾Ð·Ð²Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð´Ð¾Ð¼Ð¾Ð¹ Ð¼ÐµÐ¶Ð´Ñƒ Ñ†Ð¸ÐºÐ»Ð°Ð¼Ð¸</t>
    <t id="30028">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹</t>
    <t id="30029">Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½ Ñ†ÐµÐ½Ñ‹ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ñ</t>
    <t id="30027">ÐœÐ¸Ð½. Ð·Ð°Ð¿Ð°Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð° %</t>
    <t id="30126">Ð•ÑÐ»Ð¸ ÑÑ‚Ð° Ñ„ÑƒÐ½ÐºÑ†Ð¸Ñ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð°, Ð²ÐµÑ€Ð½Ð¸Ñ‚ÐµÑÑŒ Ð½Ð° Ð¸ÑÑ…Ð¾Ð´Ð½ÑƒÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ â€‹â€‹Ð¸ ÑÑ‚Ñ‹ÐºÑƒÐ¹Ñ‚ÐµÑÑŒ Ð¼ÐµÐ¶Ð´Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¼Ð¸ Ñ†Ð¸ÐºÐ»Ð°Ð¼Ð¸. Ð•ÑÐ»Ð¸ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, Ð¿Ð¾Ð¸ÑÐº Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶Ð¸Ñ‚ÑÑ Ð¸Ð· Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ Ð¼ÐµÑÑ‚Ð¾Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ (ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐµÐµ Ð¿Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ðµ).</t>
    <t id="30128">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð²Ð½ÑƒÑ‚Ñ€ÐµÐ½Ð½Ð¸Ðµ Ð¿ÐµÑ€ÐµÐ²Ð¾Ð´Ñ‹ ÑÐ¾ ÑÐºÐ»Ð°Ð´Ð° Ð±ÐµÐ· Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸/Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ Ð¾Ð±Ð¼ÐµÐ½ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸ Ð´Ð»Ñ Ð·Ð°Ð±Ð¾Ñ€Ð° Ð¸ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ Ð¸Ð· Ð±ÑƒÑ„ÐµÑ€Ð°. Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ ÑÐ¾Ñ…Ñ€Ð°Ð½ÑÑŽÑ‚ÑÑ, ÐµÑÐ»Ð¸ Â«Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸Â» Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾.</t>
    <t id="30129">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð°Ñ Ð¾Ñ‚Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ñ†ÐµÐ½Ð° Ð´Ð»Ñ NPC-Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»ÐµÐ¹ Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ðµ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¾Ð² ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸. ÐŸÐ¾Ð»Ð·ÑƒÐ½Ð¾Ðº Ð·Ð°ÐºÐ°Ð·Ð° 0-200 (100 = ÑÑ€ÐµÐ´Ð½ÑÑ, 0 = -100%, 200 = +100%), ÑÐ¾Ð¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²ÑƒÐµÑ‚ -1,0..+1,0. Ð’Ñ‹ÑˆÐµ = Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ð´Ð¾Ñ€Ð¾Ð³Ð¸Ðµ Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»Ð¸. ÐÐ¸Ð¶Ðµ = Ð±Ð¾Ð»ÑŒÑˆÐµ Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚Ð¾Ð² Ð¿Ð¾ÐºÑƒÐ¿Ð°Ñ‚ÐµÐ»ÐµÐ¹. Ð ÐµÐ¹ÑÑ‹ ÑÐ½Ð°Ð±Ð¶ÐµÐ½Ð¸Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑŽÑ‚ Ð¸Ð½Ð²ÐµÑ€Ñ‚Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð¾Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð´Ð»Ñ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ñ†ÐµÐ½ Ð¿Ð¾ÑÑ‚Ð°Ð²Ñ‰Ð¸ÐºÐ¾Ð².</t>
    <t id="30127">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÑŒÐ½Ñ‹Ð¹ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ ÑÐºÐ»Ð°Ð´Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ (Ð¾Ñ‚ Ð½Ð°ÑÑ‚Ñ€Ð¾ÐµÐ½Ð½Ð¾Ð³Ð¾ Ð¼Ð°ÐºÑÐ¸Ð¼ÑƒÐ¼Ð° Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€), Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ñ‹Ð¹ Ð¿ÐµÑ€ÐµÐ´ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ÐµÐ¹ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð° Ð¸Ð»Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°. Ð¢Ð¾Ð²Ð°Ñ€Ñ‹ Ð½Ð¸Ð¶Ðµ ÑÑ‚Ð¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ÑÑ. 0 = Ð±ÐµÐ· Ð¼Ð¸Ð½Ð¸Ð¼ÑƒÐ¼Ð°.</t>
    <t id="3107">Ð’ Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ Ð¼ÑƒÐ»ÑŒÑ‚Ð¸Ñ‚Ñ€ÐµÐ¹Ð´: %1. Ð¯ Ð´Ð¾Ð»Ð¶ÐµÐ½ Ð·Ð°Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚ÑŒ %2 Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸.</t>
    <t id="3108">ÐŸÑ€Ð¾Ð´Ð°Ð¶Ð° %1 %2 Ñ %3 Ð¿Ð¾ %4. Ð¯ Ð´Ð¾Ð»Ð¶ÐµÐ½ Ð·Ð°Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚ÑŒ %5 Ð¿Ñ€Ð¸Ð±Ñ‹Ð»Ð¸.</t>
    <t id="3110">Ð¡Ñ‚Ð°Ð²Ð»ÑŽ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð¿Ð¾ÑÑ‚Ð°Ð²ÐºÑƒ %1 %2. Ð—Ð°ÐºÑƒÐ¿ÐºÐ° Ð¿Ð¾ %3 Ñƒ %4, Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð½Ð° %5. ÐŸÐ¾Ñ‚Ð¾Ð»Ð¾Ðº Ð·Ð°ÐºÑƒÐ¿ÐºÐ¸ Ð·Ð°ÐºÐ°Ð·Ñ‡Ð¸ÐºÐ° %6 - %7/ÐµÐ´. Ð½Ð¸Ð¶Ðµ Ð¿Ð¾Ñ‚Ð¾Ð»ÐºÐ° (%8 Ð²ÑÐµÐ³Ð¾).</t>
    <t id="3111">Ð¡Ñ‚Ð°Ð²Ð»ÑŽ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´ÑŒ Ð¿Ð¾ÑÑ‚Ð°Ð²ÐºÑƒ %1 %2 Ð¸Ð· %3 Ð½Ð° %4.</t>
    <t id="3112">ÐŸÐ¾ÑÑ‚Ð°Ð²ÐºÐ° Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸ (%1 ÑÑ‚Ð°Ð¿Ð¾Ð²): %2. Ð’ÑÐµÐ³Ð¾ %3 Ð½Ð¸Ð¶Ðµ Ð¿Ð¾Ñ‚Ð¾Ð»ÐºÐ° Ð·Ð°ÐºÑƒÐ¿ÐºÐ¸ Ð·Ð°ÐºÐ°Ð·Ñ‡Ð¸ÐºÐ°.</t>
    <t id="3113">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¾Ð½Ð½Ñ‹Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†: ÑÐºÑÐ¿Ð¾Ñ€Ñ‚Ð½Ñ‹Ð¹ Ð¼ÑƒÐ»ÑŒÑ‚Ð¸Ñ‚Ñ€ÐµÐ¹Ð´ Ð² Ð¾Ñ‡ÐµÑ€ÐµÐ´Ð¸: %1. ÐžÐ¶Ð¸Ð´Ð°ÐµÐ¼Ð°Ñ Ð¿Ñ€Ð¸Ð±Ñ‹Ð»ÑŒ %2.</t>
    <t id="31029">Ð¦ÐµÐ»ÐµÐ²Ð¾Ð¹ Ð·Ð°Ð¿Ð°Ñ Ð·Ð¾Ð½Ð´Ð°</t>
    <t id="31030">ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ° Ð³Ð¾Ñ€Ð½Ð¾Ð´Ð¾Ð±Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ñ… Ð´Ñ€Ð¾Ð½Ð¾Ð²</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: Ð½ÐµÑ‚ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ‹Ñ… Ð´Ð»Ñ Ð´Ð¾Ð±Ñ‹Ñ‡Ð¸ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð². ÐšÐ¾Ñ€Ð°Ð±Ð»ÑŒ %1 [%2], Ð¤Ð»Ð¾Ñ‚: %3</t>
    <t id="31201">Galaxy-Miner: ÑƒÐºÐ°Ð¶Ð¸Ñ‚Ðµ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽÑŽ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑŽ Ð¸Ð»Ð¸ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽÑŽ Ð¿Ð¾Ð·Ð¸Ñ†Ð¸ÑŽ.</t>
    <t id="31130">Ð¡ÐºÐ¾Ð»ÑŒÐºÐ¾ Ð´Ñ€Ð¾Ð½Ð¾Ð²-ÑÐ±Ð¾Ñ€Ñ‰Ð¸ÐºÐ¾Ð² (Ð³Ð¾Ñ€Ð½Ð¾Ð´Ð¾Ð±Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ñ…) Ð¿Ð¾ÐºÑƒÐ¿Ð°ÐµÑ‚ ÑˆÐ°Ñ…Ñ‚Ñ‘Ñ€, ÐºÐ¾Ð³Ð´Ð° Ñƒ Ð½ÐµÐ³Ð¾ Ð·Ð°ÐºÐ°Ð½Ñ‡Ð¸Ð²Ð°ÐµÑ‚ÑÑ Ð½ÑƒÐ¶Ð½Ñ‹Ð¹ Ñ‚Ð¸Ð¿ (Ñ‚Ð²Ñ‘Ñ€Ð´Ñ‹Ð¹/Ñ€ÑƒÐ´Ð° Ð¸Ð»Ð¸ Ð¶Ð¸Ð´ÐºÐ¸Ð¹/Ð³Ð°Ð·). ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ° Ð·Ð°Ð¿ÑƒÑÐºÐ°ÐµÑ‚ÑÑ Ð¢ÐžÐ›Ð¬ÐšÐž ÐºÐ¾Ð³Ð´Ð° Ñƒ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ð½ÐµÑ‚ ÑÐ±Ð¾Ñ€Ñ‰Ð¸ÐºÐ¾Ð² ÑÑ‚Ð¾Ð³Ð¾ Ñ‚Ð¸Ð¿Ð° - ÑˆÐ°Ñ…Ñ‚Ñ‘Ñ€, Ñƒ ÐºÐ¾Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ ÐµÑ‰Ñ‘ ÐµÑÑ‚ÑŒ Ñ…Ð¾Ñ‚Ñ Ð±Ñ‹ Ð¾Ð´Ð¸Ð½, Ð½Ð¸ÐºÐ¾Ð³Ð´Ð° Ð½Ðµ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÑÐµÑ‚ÑÑ Ð¸ Ð½Ðµ Ð¿Ð¾ÐºÑƒÐ¿Ð°ÐµÑ‚ÑÑ Ð·Ð°Ð½Ð¾Ð²Ð¾, Ð¸Ð¼ÐµÑŽÑ‰Ð¸ÐµÑÑ Ð´Ñ€Ð¾Ð½Ñ‹ ÑÐ¾Ñ…Ñ€Ð°Ð½ÑÑŽÑ‚ÑÑ. ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð²Ð¼ÐµÑÑ‚Ð¸Ð¼Ð¾ÑÑ‚ÑŒÑŽ Ð¾Ñ‚ÑÐµÐºÐ° ÑŽÐ½Ð¸Ñ‚Ð¾Ð² ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð£ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚Ðµ 0, Ñ‡Ñ‚Ð¾Ð±Ñ‹ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÑƒÑŽ Ð¿Ð¾ÐºÑƒÐ¿ÐºÑƒ Ð´Ñ€Ð¾Ð½Ð¾Ð²-ÑÐ±Ð¾Ñ€Ñ‰Ð¸ÐºÐ¾Ð² Ð¸ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÑÑ‚ÑŒ Ð´Ñ€Ð¾Ð½Ð°Ð¼Ð¸ Ð²Ñ€ÑƒÑ‡Ð½ÑƒÑŽ. Ð—Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð¿Ð¾ ÑƒÐ¼Ð¾Ð»Ñ‡Ð°Ð½Ð¸ÑŽ 5 - Ð¿Ð¾Ð»Ð½Ñ‹Ð¹ Ð½Ð°Ð±Ð¾Ñ€ Ð´Ñ€Ð¾Ð½Ð¾Ð² Ð´Ð»Ñ Ð½Ð¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð¹ ÑÐºÐ¾Ñ€Ð¾ÑÑ‚Ð¸ Ð´Ð¾Ð±Ñ‹Ñ‡Ð¸.</t>
    <t id="31129">ÐšÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð¾ Ð¿Ñ€Ð¾Ð± Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð², ÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ðµ Ð¼Ð°Ð¹Ð½ÐµÑ€ Ð¿Ð¾ÐºÑƒÐ¿Ð°ÐµÑ‚ Ð·Ð° Ð¾Ð´Ð½Ñƒ Ð¿Ð¾ÐµÐ·Ð´ÐºÑƒ Ð¿Ð¾ Ð¿Ð¾Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸ÑŽ Ð·Ð°Ð¿Ð°ÑÐ¾Ð². ÐŸÐ¾ÐºÑƒÐ¿ÐºÐ° ÑÑ€Ð°Ð±Ð°Ñ‚Ñ‹Ð²Ð°ÐµÑ‚ Ð¢ÐžÐ›Ð¬ÐšÐž Ñ‚Ð¾Ð³Ð´Ð°, ÐºÐ¾Ð³Ð´Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ðµ Ð·Ð°ÐºÐ¾Ð½Ñ‡Ð¸Ð»Ð¸ÑÑŒ Ð·Ð¾Ð½Ð´Ñ‹ (ÑÑ‡ÐµÑ‚Ñ‡Ð¸Ðº = 0), Ð° Ð½Ðµ Ð¿Ñ€Ð¸ ÐºÐ°Ð¶Ð´Ð¾Ð¼ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°Ð½Ð¸Ð¸ - Ñ‚Ð°ÐºÐ¸Ð¼ Ð¾Ð±Ñ€Ð°Ð·Ð¾Ð¼ Ð¼Ð°Ð¹Ð½ÐµÑ€ Ð¿Ñ€Ð¾Ñ…Ð¾Ð´Ð¸Ñ‚ Ð¿Ð¾Ð»Ð½ÑƒÑŽ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÑƒ Ð·Ð¾Ð½Ð´Ð¾Ð² Ð¼ÐµÐ¶Ð´Ñƒ Ð·Ð°Ð¿ÑƒÑÐºÐ°Ð¼Ð¸ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð¾Ðº, Ð° Ð½Ðµ Ð´ÐµÐ»Ð°ÐµÑ‚ Ð¾Ð±Ñ…Ð¾Ð´ Ð¿Ð¾ÑÐ»Ðµ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°Ð½Ð¸Ñ. ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð¾Ð±Ñ‰ÐµÐ¹ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ð¾Ð¹ ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚ÑŒÑŽ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ (ÑÐ¾Ð²Ð¼ÐµÑÑ‚Ð½Ð¾ ÑÐ¾ ÑÐ¿ÑƒÑ‚Ð½Ð¸ÐºÐ°Ð¼Ð¸/Ð¼Ð¸Ð½Ð°Ð¼Ð¸/Ð¸ Ñ‚.Â Ð´.); Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð¿Ð¾Ð»Ð·ÑƒÐ½ÐºÐ°, Ð¿Ñ€ÐµÐ²Ñ‹ÑˆÐ°ÑŽÑ‰ÐµÐµ ÑÐ²Ð¾Ð±Ð¾Ð´Ð½Ð¾Ðµ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°ÐµÐ¼Ð¾Ðµ Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÑ‚Ð²Ð¾, Ð¿Ð»Ð°Ð²Ð½Ð¾ ÑƒÐ¼ÐµÐ½ÑŒÑˆÐ°ÐµÑ‚ÑÑ Ð´Ð¾ Â«Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ñ‚Ð¾Ð³Ð¾, Ñ‡Ñ‚Ð¾ Ð¿Ð¾Ð´Ñ…Ð¾Ð´Ð¸Ñ‚Â». Ð’ÑÑ‚ÑƒÐ¿Ð°ÐµÑ‚ Ð² ÑÐ¸Ð»Ñƒ Ñ‚Ð¾Ð»ÑŒÐºÐ¾ Ñ‚Ð¾Ð³Ð´Ð°, ÐºÐ¾Ð³Ð´Ð° Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÑÐºÐ¾Ðµ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°Ð½Ð¸Ðµ Ð·Ð¾Ð½Ð´Ð¾Ð² Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð² - ÑÑ‚Ð¾Ñ‚ Ð¶Ðµ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Ñ‚Ð°ÐºÐ¶Ðµ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÑÐµÑ‚ Ð¾Ð¿Ð¿Ð¾Ñ€Ñ‚ÑƒÐ½Ð¸ÑÑ‚Ð¸Ñ‡ÐµÑÐºÐ¸Ð¼ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°Ð½Ð¸ÐµÐ¼ Ð·Ð¾Ð½Ð´Ð¾Ð² Ð² Ð³Ð¾Ñ€Ð½Ð¾Ð´Ð¾Ð±Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ð¸ ÑÐ±Ð¾Ñ€Ð¾Ð¼ ÑƒÑÑ‚Ð°Ñ€ÐµÐ²ÑˆÐ¸Ñ… Ð·Ð¾Ð½Ð´Ð¾Ð² (Ð·Ð¾Ð½Ð´Ð¾Ð² Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ…, Ð³Ð´Ðµ Ð½ÐµÑ‚ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð², ÑÐ¾Ð¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²ÑƒÑŽÑ‰Ð¸Ñ… ÐºÐ¾Ñ€Ð·Ð¸Ð½Ðµ).</t>
    <t id="3226">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¯ Ð¿Ñ€Ð¸ÑˆÐ²Ð°Ñ€Ñ‚Ð¾Ð²Ð°Ð»ÑÑ Ð² %2, Ð¸ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð°Ñ‚Ð¾Ñ€ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¹ Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸ Ð¿Ð¾Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¸Ð» Ð¼Ð¾Ðµ Ð·Ð°Ñ‡Ð¸ÑÐ»ÐµÐ½Ð¸Ðµ Ð² Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ñƒ Â«%3Â». Ð¡Ð¾ ÑÑ‡ÐµÑ‚Ð° Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÐ° Ð±Ñ‹Ð»Ð¾ ÑÐ¿Ð¸ÑÐ°Ð½Ð¾ %4 Cr Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ, Ð¸ Ñ Ð½Ðµ Ð¾Ñ‚Ð½Ð¾ÑˆÑƒÑÑŒ Ðº ÑÑ‚Ð¸Ð¼ Ð¸Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ð¸ÑÐ¼ Ð»ÐµÐ³ÐºÐ¾Ð¼Ñ‹ÑÐ»ÐµÐ½Ð½Ð¾.\n\nÐ­Ñ‚Ð¾ Ð½Ðµ Ð¾Ð±Ñ‹Ñ‡Ð½Ð°Ñ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ. ÐŸÑ€ÐµÐ¿Ð¾Ð´Ð°Ð²Ð°Ñ‚ÐµÐ»Ð¸ Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸ - Ð¾Ð¿Ñ‹Ñ‚Ð½Ñ‹Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ‹ Ð¸ Ð¿ÐµÑ€ÐµÐ³Ð¾Ð²Ð¾Ñ€Ñ‰Ð¸ÐºÐ¸ ÐºÐ¾Ð½ÑÐ¾Ñ€Ñ†Ð¸ÑƒÐ¼Ð¾Ð², Ð° ÑƒÑ‡ÐµÐ±Ð½Ð°Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð° Ð·Ð´ÐµÑÑŒ Ð³Ð¾Ñ€Ð°Ð·Ð´Ð¾ Ð±Ð¾Ð»ÐµÐµ Ñ‚Ñ€ÐµÐ±Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÐ½Ð°, Ñ‡ÐµÐ¼ ÑÑ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ñ‹Ð¹ ÑÐºÐ·Ð°Ð¼ÐµÐ½ Ð´Ð»Ñ Ð¿Ð¾Ð²Ñ‹ÑˆÐµÐ½Ð¸Ñ ÐºÐ²Ð°Ð»Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸. Ð’ Ñ‚ÐµÑ‡ÐµÐ½Ð¸Ðµ ÑÐ»ÐµÐ´ÑƒÑŽÑ‰Ð¸Ñ… %5 Ð¼Ð¸Ð½ÑƒÑ‚ Ñ Ð¿Ñ€Ð¾Ð¹Ð´Ñƒ Ð¸Ð½Ñ‚ÐµÐ½ÑÐ¸Ð²Ð½Ð¾Ðµ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¿Ñ€Ð¾Ð´Ð²Ð¸Ð½ÑƒÑ‚Ñ‹Ð¼ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ð¼ Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ð°Ð¼, Ð°Ð½Ð°Ð»Ð¸Ð·Ñƒ Ñ€Ñ‹Ð½ÐºÐ° Ð¿Ð¾Ð´ Ð´Ð°Ð²Ð»ÐµÐ½Ð¸ÐµÐ¼ Ð¸ Ñ‚Ð°ÐºÑ‚Ð¸ÐºÐµ Ð²ÐµÐ´ÐµÐ½Ð¸Ñ Ð¿ÐµÑ€ÐµÐ³Ð¾Ð²Ð¾Ñ€Ð¾Ð², ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ Ð¾Ñ‚Ð»Ð¸Ñ‡Ð°ÐµÑ‚ ÑƒÑ‡ÐµÐ½Ð¸ÐºÐ¾Ð² Ð¾Ñ‚ Ð¼Ð°ÑÑ‚ÐµÑ€Ð¾Ð².\n\nÐšÐ¾Ð³Ð´Ð° Ð·Ð°ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ð¹ ÑÐºÐ·Ð°Ð¼ÐµÐ½ Ð±ÑƒÐ´ÐµÑ‚ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½ Ð¸ Ñ Ð¾Ñ‚ÑÑ‚Ñ‹ÐºÑƒÑŽÑÑŒ, Ñ Ð¿Ð¾Ð»ÑƒÑ‡Ñƒ Ñ‚Ð¸Ñ‚ÑƒÐ» "%3" Ð¸ Ð¿Ñ€Ð¸Ð½ÐµÑÑƒ Ð²ÑÐµ, Ñ‡ÐµÐ¼Ñƒ Ð½Ð°ÑƒÑ‡Ð¸Ð»ÑÑ, Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾ Ð² Ð½Ð°ÑˆÐ¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸. Ð¯ Ð½Ðµ ÑƒÐ¿ÑƒÑ‰Ñƒ Ð½Ð¸ ÐµÐ´Ð¸Ð½Ð¾Ð³Ð¾ Ð±Ð°Ð»Ð»Ð° ÑÑ‚Ð¾Ð¹ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸.\n\nÐ¡ Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ð½Ð¾ÑÑ‚ÑŒÑŽ Ð¸ Ñ€ÐµÑˆÐ¸Ð¼Ð¾ÑÑ‚ÑŒÑŽ,\n%6\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %7</t>
    <t id="9924">ÐšÑƒÑ€Ñ ÐÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸ Ñ‚Ñ€ÐµÐ¹Ð´Ð¸Ð½Ð³Ð° Ð¿Ñ€ÐµÑ€Ð²Ð°Ð½: Ð¿Ð¸Ð»Ð¾Ñ‚ %1 Ð½Ðµ Ð¼Ð¾Ð¶ÐµÑ‚ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚ÑŒ ÑÐµÐ±Ðµ Ð¾Ð¿Ð»Ð°Ñ‚Ñƒ %2 Cr Ð² Ð´Ð¾ÐºÐµ Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸Ð¸ (Ð¸Ð¼ÐµÐµÑ‚ %3 Cr). ÐšÑƒÑ€Ñ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½, Ð¿Ð¸Ð»Ð¾Ñ‚ Ð²Ð¾Ð·Ð¾Ð±Ð½Ð¾Ð²Ð»ÑÐµÑ‚ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»ÑŽ.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="33">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Docker et attendre (GalaxyTrader MK3)</t>
    <t id="10002">Galaxy Trader MK3</t>
    <t id="10003">Examen final (GalaxyTrader MK3)</t>
    <t id="10004">Rendez-vous d'Ã©change pilote</t>
    <t id="10005">[OBSOLÃˆTE] GalaxyTrader Alimentation MK4 (HÃ©ritage)</t>
    <t id="10101">S'arrimer Ã  la station et attendre la durÃ©e spÃ©cifiÃ©e</t>
    <t id="10102">Commerce autonome avec progression des compÃ©tences</t>
    <t id="10103">Passer l'examen final pour la certification de pilote Ã  l'installation d'entraÃ®nement</t>
    <t id="10104">Amarrez-vous Ã  la station de rendez-vous pour l'Ã©change de pilotes</t>
    <t id="10105">Commerce axÃ© sur l'offre pour les stations de joueurs utilisant le cache et la recherche en direct (HÃ©ritage)</t>
    <t id="10201">Achetez %s auprÃ¨s de %s</t>
    <t id="10202">Vendre %s Ã  %s</t>
    <t id="10203">Ã‰changez avec %s</t>
    <t id="1000">Galaxy Trader MK3</t>
    <t id="1001">SystÃ¨me de commerce avancÃ© avec progression XP et coordination de flotte</t>
    <t id="1002">Base d'OpÃ©rations</t>
    <t id="1003">Utiliser les prÃ©rÃ©glages</t>
    <t id="1004">Ã‰changez toutes les marchandises</t>
    <t id="1005">Commercer les marchandises lÃ©gales</t>
    <t id="1006">Commercer les marchandises illÃ©gales</t>
    <t id="1007">Activer la progression XP</t>
    <t id="1008">Activer la coordination de la flotte</t>
    <t id="1009">Activer l'analyse de marchÃ©</t>
    <t id="1010">Activer la gestion du territoire</t>
    <t id="1011">Autoriser les Marchandises IllÃ©gales</t>
    <t id="1012">EntrÃ©es dans le Journal de Bord</t>
    <t id="1013">TolÃ©rance au Risque</t>
    <t id="1014">Prioriser les stations de joueurs</t>
    <t id="1015">Marchandises automatiques</t>
    <t id="1016">PÃ©nalitÃ© de Distance %</t>
    <t id="1017">Niveau de notification</t>
    <t id="1018">Coordination de la flotte</t>
    <t id="1019">% cible de remplissage du fret</t>
    <t id="1050">FrÃ©quence de Mise Ã  Jour du MarchÃ©</t>
    <t id="1051">Journalisation d'Ã‰valuation du Commerce</t>
    <t id="1052">Liste blanche du secteur</t>
    <t id="1054">Ignorer les navires transporteurs/auxiliaires</t>
    <t id="1056">Ignorer le stockage de construction</t>
    <t id="1058">Ignorer les rÃ¨gles commerciales</t>
    <t id="1060">Ignorer les stations fournies par MK1</t>
    <t id="1063">En dÃ©veloppement</t>
    <t id="1064">Marchandises prioritaires</t>
    <t id="1065">Score prioritÃ© %</t>
    <t id="1066">Marchandises Ã  privilÃ©gier dans la notation commerciale. Leur score est multipliÃ© par le % de score de prioritÃ©.</t>
    <t id="1067">Multiplicateur de score pour les marchandises prioritaires : 100 %=normal, 150 %=+50 % %, 200 %=2x, 300 %=3x. AppliquÃ© en dernier.</t>
    <t id="1068">â”€â”€ Filtre marchandises prioritaires â”€â”€</t>
    <t id="1069">Marchandises (manuel)</t>
    <t id="1070">Filtre d'itinÃ©raire illÃ©gal</t>
    <t id="1072">Servir Ã  la maison seulement</t>
    <t id="1073">PrioritÃ© fournisseur joueur</t>
    <t id="1074">PrioritÃ© fournisseur faction</t>
    <t id="1075">Inclure le stockage de build</t>
    <t id="1076">Inclure des ressources</t>
    <t id="1077">Inclure les intermÃ©diaires</t>
    <t id="1078">Inclure les produits commerciaux</t>
    <t id="1080">Nombre maximum de transactions par cycle</t>
    <t id="1081">TolÃ©rance de retour en arriÃ¨re</t>
    <t id="1082">% de fret minimum utilisÃ©</t>
    <t id="1083">% de modificateur d'achat du joueur</t>
    <t id="1085">Attribuer Ã  la station d'accueil</t>
    <t id="1086">Distance de couverture</t>
    <t id="1088">Distance de saut maximale depuis le domicile pour la couverture de la demande</t>
    <t id="1090">Inclure les marchandises de classe tradeware dans la correspondance demande/offre</t>
    <t id="1091">Modificateur appliquÃ© aux prix des fournisseurs appartenant aux joueurs dans les calculs de notation uniquement</t>
    <t id="1092">Ignorer les prix des joueurs</t>
    <t id="1093">Lorsqu'il est activÃ©Â : achetez toujours dans les stations appartenant aux joueurs, quels que soient leurs prix de vente fixÃ©s, et ne vendez qu'aux factions de PNJ. Utile pour liquider les stocks excÃ©dentaires de vos propres stations.</t>
    <t id="1094">Stations bloquÃ©es</t>
    <t id="1095">Les stations sÃ©lectionnÃ©es ici sont exclues du commerce MK3. Le commerÃ§ant n'y achÃ¨tera ni n'y vendra.</t>
    <t id="1096">Stationnement en attente</t>
    <t id="1097">Si activÃ©, les vaisseaux qui ne trouvent pas de travail Ã  plusieurs reprises stationnent Ã  leur station d'accueil ou dans leur secteur d'accueil. Le stationnement de secteur privilÃ©gie les stations du joueur, puis les stations amies. Le temps de libÃ©ration du dock se rÃ¨gle dans les paramÃ¨tres globaux (0 = reste Ã  quai jusqu'Ã  ce qu'un travail soit trouvÃ©).</t>
    <t id="1098">Auto-Ã©chelle</t>
    <t id="1099">Si activÃ©, les curseurs de distance de saut sont rÃ©glÃ©s sur la portÃ©e maximale autorisÃ©e du pilote aprÃ¨s la formation obligatoire ou l'achÃ¨vement de l'AcadÃ©mie commerciale. DÃ©sactiver pour dÃ©finir les distances manuellement.</t>
    <t id="11001">PrioritÃ© stockage de construction</t>
    <t id="11002">PrioritÃ© stations</t>
    <t id="11003">PrioritÃ© vaisseaux auxiliaires</t>
    <t id="11004">PrioritÃ© porte-avions</t>
    <t id="11005">0 = dÃ©sactivÃ©. 1-10 = multiplicateur de score (10 = biais maximal). Score final = score d'approvisionnement Ã— multiplicateur.</t>
    <t id="11006">1 = pas de score supplÃ©mentaire (liste de marchandises prioritaires inchangÃ©e). 2-10 = ajoute (multiplicateurâˆ’1)Ã— score d'approvisionnement de base si la marchandise est dans la liste prioritaire. S'ajoute au score de type.</t>
    <t id="11007">Bonus marchandises prioritaires</t>
    <t id="11008">%1 : Tous les curseurs de prioritÃ© des cibles de livraison sont Ã  0 - cet ordre n'a aucune cible de livraison. Activez au moins une classe (stockage de construction, stations, vaisseaux auxiliaires ou porte-vaisseaux) pour reprendre les approvisionnements.</t>
    <t id="7001">[AVANCE]</t>
    <t id="7002">[ENTRAÃŽNEMENT]</t>
    <t id="7008">[RETOMBER]</t>
    <t id="7009">[ISOLÃ‰]</t>
    <t id="7003">[RÃ‰PARATION]</t>
    <t id="7004">[RÃ‰APPROVISIONNEMENT]</t>
    <t id="7005">[ENTRETIEN]</t>
    <t id="7006">[RÃ‰ACHEMINEMENT]</t>
    <t id="7007">[AUTORISATION]</t>
    <t id="1020">Choisir le secteur ou la station d'origine oÃ¹ le commerÃ§ant opÃ¨re</t>
    <t id="1021">Distance maximale de portail de saut lors de l'achat de marchandises (limitÃ©e par la compÃ©tence du pilote)</t>
    <t id="1022">Distance maximale de portail de saut lors de la vente de marchandises (limitÃ©e par la compÃ©tence du pilote)</t>
    <t id="1023">SÃ©lection automatique de marchandises appropriÃ©es basÃ©e sur la catÃ©gorie</t>
    <t id="1024">SÃ©lection manuelle de marchandises commerciales spÃ©cifiques</t>
    <t id="1025">Autoriser le commerce de contrebande et de biens illÃ©gaux</t>
    <t id="1026">TolÃ©rance de sÃ©curitÃ© : 0.0=Seulement secteurs sÃ»rs, 1.0=Accepter tous les risques</t>
    <t id="1027">AmÃ©liorer les compÃ©tences du pilote grÃ¢ce Ã  l'expÃ©rience commerciale</t>
    <t id="1028">Envoyer automatiquement les pilotes en formation lorsque nÃ©cessaire</t>
    <t id="1029">Coordonner plusieurs vaisseaux commerciaux pour Ã©viter les conflits</t>
    <t id="1030">Focus marchandises : 0=Ã‰quilibrÃ©, 1=AvancÃ©, 2=Besoins de base, 3=IllÃ©gal, 4=Marchandises en vrac</t>
    <t id="1031">Zone commerciale : 0=Ã‰quilibrÃ©, 1=Focus origine, 2=Errance libre</t>
    <t id="1032">Niveau de notification : 0=Minimal, 1=Normal, 2=Messages dÃ©taillÃ©s</t>
    <t id="1033">Cibler le pourcentage d'utilisation du fret avant de donner la prioritÃ© aux ventes</t>
    <t id="1034">FrÃ©quence de mise Ã  jour des donnÃ©es de marchÃ© et des informations de prix</t>
    <t id="1035">Niveau de sortie de dÃ©bogage : 0=Aucun, 1=De base, 2=Journalisation dÃ©taillÃ©e</t>
    <t id="1036">Partager les routes commerciales rentables avec la flotte (mises en cache pour accÃ¨s rapide)</t>
    <t id="1037">BÃ©nÃ©fice minimum requis pour mettre en cache les Ã©changes et les partager avec la flotte</t>
    <t id="1038">DÃ©clin de profit maximum autorisÃ© avant que les routes commerciales en cache deviennent invalides</t>
    <t id="1039">DurÃ©e de validitÃ© des routes commerciales en cache avant expiration</t>
    <t id="1040">Activer la journalisation dÃ©taillÃ©e des Ã©valuations et rejets de commerce individuels (peut Ãªtre trÃ¨s verbeux)</t>
    <t id="1041">Activer les entrÃ©es de journal de bord par commerce et messages d'entraÃ®nement immersifs (style TaterTrader)</t>
    <t id="1053">Les secteurs de cette liste sont exclus des listes noires (toujours autorisÃ©s)</t>
    <t id="1055">Exclure les transporteurs et les navires auxiliaires du commerce</t>
    <t id="1057">Exclure les navires de stockage de construction du commerce</t>
    <t id="1059">Ignorer les rÃ¨gles commerciales de station lors de la recherche d'offres (avancÃ© ; peut sÃ©lectionner des offres normalement bloquÃ©es)</t>
    <t id="1061">Ignorer les stations de joueurs qui ont un commerÃ§ant MK1 avec le mode d'approvisionnement attribuÃ©</t>
    <t id="1062">AmÃ©liorez les scores commerciaux pour les itinÃ©raires impliquant vos propres gares (bonus de score de 10 %)</t>
    <t id="1071">Lorsque Autoriser les marchandises illÃ©gales est activÃ©, n'Ã©changez des marchandises illÃ©gales que si elles sont lÃ©gales dans tous les secteurs du chemin de saut (secteurs d'achat, de vente et intermÃ©diaires).</t>
    <t id="1087">Distance de saut maximale depuis le domicile pour la recherche d'achat fournisseur</t>
    <t id="1089">Lorsqu'il est dÃ©sactivÃ©, le navire peut approvisionner les stations dans la zone de couverture en prioritÃ© d'urgence au lieu du mode domestique uniquement.</t>
    <t id="2000">%s a gagnÃ© %s XP !</t>
    <t id="2001">%s a montÃ© de niveau ! Nouveau niveau : %s</t>
    <t id="2002">%s a besoin d'entraÃ®nement ! Veuillez envoyer au chantier naval ou Ã  la station commerciale la plus proche.</t>
    <t id="2003">%s a commencÃ© l'entraÃ®nement Ã  %s</t>
    <t id="2004">%s a terminÃ© l'entraÃ®nement et est maintenant certifiÃ© pour le niveau %s !</t>
    <t id="2005">%s a atteint le Skill Level %s aprÃ¨s l'entraÃ®nement ! Progression XP dÃ©bloquÃ©e Ã  %s.</t>
    <t id="2006">%s a atteint le Skill Level %s grÃ¢ce au commerce de %s !</t>
    <t id="2007">%s a terminÃ© l'entraÃ®nement Level %s ! Progression XP dÃ©bloquÃ©e Ã  %s.</t>
    <t id="3000">%s a complÃ©tÃ© un commerce ! Profit : %s Cr</t>
    <t id="3001">%s analyse les conditions du marchÃ©...</t>
    <t id="3002">%s a trouvÃ© une route commerciale rentable !</t>
    <t id="3003">Aucune route commerciale rentable disponible pour %s</t>
    <t id="3100">Vente de %1 %2 de la cargaison Ã  %3 au prix de %4. Je devrais gagner %5 de profit.</t>
    <t id="3101">Mise en file d'ordre commercial pour %1 %2. Achat Ã  %3 depuis %4, vente Ã  %5 vers %6. Je devrais gagner %7 de profit.</t>
    <t id="3102">CommerÃ§ant de Station : Approvisionnement de %1 %2 de %3 Ã  %5%% vers %4 Ã  %6%%.</t>
    <t id="3103">CommerÃ§ant de Station : Vente de %1 %2 vers %3 Ã  %4. Profit attendu : %5.</t>
    <t id="3104">Commerce complÃ©tÃ© avec succÃ¨s pour %1 %2. Profit total : %3 CrÃ©dits.</t>
    <t id="3105">Route commerciale mise en cacheÂ : %1 %2 de %3 Ã  %4 (BÃ©nÃ©ficeÂ : %5 Cr)</t>
    <t id="3106">\nProfit total estimÃ© sur la durÃ©e de vie avant ce commerce : %1 Cr.</t>
    <t id="3120">Transfert pilote lancÃ©</t>
    <t id="3121">Protocole de transfert reconnu. %1 (%2) et %3 (%4) se dirigent vers %5 (%6) pour accoster et Ã©changer les siÃ¨ges de commandement.</t>
    <t id="3200">Bonjour Commandant %1,\n\nJ'ai acquis suffisamment d'expÃ©rience pour passer mon examen de certification pour le titre "%2". L'examen durera approximativement %3 minutes Ã  %4.\n\nC'est une Ã©tape importante dans mon dÃ©veloppement de carriÃ¨re. L'examen testera mes connaissances des protocoles commerciaux avancÃ©s, de l'analyse de marchÃ© et des procÃ©dures de coordination de flotte.\n\nJe suis confiant en mes capacitÃ©s et excitÃ© de prouver que je mÃ©rite cette promotion. Souhaitez-moi bonne chance !\n\nRespectueusement,\n%5\nÃ€ bord de %6</t>
    <t id="3201">Commandant %1,\n\nExcellentes nouvelles ! J'ai rÃ©ussi mon examen de certification et obtenu le titre "%2" !\n\nL'examen couvrait les stratÃ©gies commerciales avancÃ©es, les protocoles d'Ã©valuation des risques et les procÃ©dures de coordination de flotte. Je suis heureux de rapporter que j'ai rÃ©ussi avec distinction.\n\nJe suis maintenant qualifiÃ© pour gÃ©rer des opÃ©rations commerciales plus complexes et j'ai hÃ¢te de contribuer encore plus au succÃ¨s de notre flotte. Merci d'avoir investi dans mon dÃ©veloppement professionnel.\n\nAvec dÃ©vouement renouvelÃ©,\n%3\nCertifiÃ© %2\nÃ€ bord de %4</t>
    <t id="3202">Commandant %1,\n\nJe regrette de vous informer que mon examen de certification a Ã©tÃ© interrompu en raison d'exigences opÃ©rationnelles. Je devrai le reprogrammer lorsque les circonstances le permettront.\n\nJe reste engagÃ© Ã  faire progresser mes compÃ©tences et vous notifierai lorsque je pourrai reprendre le processus d'examen.\n\nRespectueusement,\n%2\nÃ€ bord de %3</t>
    <t id="3203">Commandant %1,\n\nJe suis actuellement en route vers %2 pour mon examen de certification. Le voyage me donne le temps de rÃ©viser mes Ã©tudes et de me prÃ©parer mentalement pour cette Ã©tape importante de ma carriÃ¨re.\n\nArrivÃ©e prÃ©vue : %3 minutes\nDurÃ©e de l'examen : %4 minutes\n\nJ'apprÃ©cie votre confiance en mes capacitÃ©s et l'opportunitÃ© d'avancement.\n\nAvec dÃ©termination,\n%5\nÃ€ bord de %6</t>
    <t id="3204">Commandant,\n\nJ'ai dÃ©tectÃ© de la cargaison dans ma soute lors de ma vÃ©rification des systÃ¨mes. Avant de pouvoir commencer les opÃ©rations commerciales normales, je dois vendre cette marchandise.\n\nJ'utilise notre recherche commerciale pour trouver le meilleur acheteur et dÃ©charger cette cargaison en toute sÃ©curitÃ©. Une fois ma soute vide, je procÃ©derai au commerce automatisÃ©.\n\nStatut : Recherche du lieu de vente optimal\n\nAvec diligence,\nÃ€ bord de %1</t>
    <t id="3205">Commandant,\n\nL'intÃ©gritÃ© de ma coque est tombÃ©e Ã  %1%% (seuil : %2%%). En tant que pilote de Niveau %3, je suis autorisÃ© Ã  demander des services de rÃ©paration automatique.\n\nJe me dirige vers %4 pour les travaux de rÃ©paration. Le coÃ»t estimÃ© est de %5 Cr, ce qui est dans notre budget.\n\nUne fois les rÃ©parations terminÃ©es, je reprendrai les opÃ©rations commerciales avec une intÃ©gritÃ© structurelle complÃ¨te.\n\nRespectueusement,\nÃ€ bord de %6</t>
    <t id="3206">Commandant,\n\nAVERTISSEMENT FINANCIER URGENT\n\nL'intÃ©gritÃ© de ma coque est critique Ã  %1%% (seuil : %2%%), mais nos fonds disponibles (%3 Cr) sont insuffisants pour des rÃ©parations complÃ¨tes (coÃ»t estimÃ© : %4 Cr).\n\nJe me dirige vers %5 pour des RÃ‰PARATIONS PARTIELLES en utilisant nos fonds disponibles. Ce n'est pas une solution idÃ©ale, mais c'est nÃ©cessaire pour maintenir la capacitÃ© opÃ©rationnelle.\n\nVeuillez considÃ©rer l'allocation de fonds supplÃ©mentaires pour les futures opÃ©rations de maintenance.\n\nPrÃ©occupÃ© mais dÃ©terminÃ©,\nÃ€ bord de %6</t>
    <t id="3207">Commandant,\n\nMa certification de Niveau %1 autorise le rÃ©approvisionnement automatique d'Ã©quipement dÃ©fensif. AprÃ¨s avoir vÃ©rifiÃ© mes systÃ¨mes, j'ai dÃ©terminÃ© que mes contremesures et Ã©quipements dÃ©ployables sont en dessous des seuils recommandÃ©s.\n\nJe me dirige vers %2 pour rÃ©approvisionner mon Ã©quipement dÃ©fensif :\nâ€¢ Contremesures : RÃ©approvisionnement Ã  capacitÃ© optimale\nâ€¢ Drones de dÃ©fense, drones commerciaux, tours laser : Application du profil d'Ã©quilibre\n\nCe rÃ©approvisionnement garantit que je suis mieux protÃ©gÃ© contre les menaces spatiales tout en maintenant l'efficacitÃ© commerciale.\n\nAvec vigilance,\nÃ€ bord de %3</t>
    <t id="3212">Commandant,\n\nL'intÃ©gritÃ© de ma coque est tombÃ©e Ã  %1%% (seuil : %2%%), et j'ai besoin de services de rÃ©paration. Cependant, la station de rÃ©paration la plus proche Ã  %3 est actuellement inaccessible en raison de restrictions de voyage sectoriel (routes sur liste noire).\n\nJe continuerai avec les opÃ©rations commerciales malgrÃ© cette limitation. Une fois que les routes sÃ»res redeviendront disponibles, je chercherai automatiquement des services de rÃ©paration.\n\nJe surveillerai la situation et vous notifierai lorsque les rÃ©parations deviendront possibles.\n\nRespectueusement,\nÃ€ bord de %4</t>
    <t id="3213">Commandant,\n\nMon Ã©quipement dÃ©fensif nÃ©cessite un rÃ©approvisionnement, mais la station d'Ã©quipement la plus proche Ã  %1 est actuellement inaccessible en raison de restrictions de voyage sectoriel (routes sur liste noire).\n\nJe continuerai avec les opÃ©rations commerciales malgrÃ© cette limitation. Une fois que les routes sÃ»res redeviendront disponibles, je chercherai automatiquement des services de rÃ©approvisionnement.\n\nJe surveillerai la situation et vous notifierai lorsque le rÃ©approvisionnement deviendra possible.\n\nRespectueusement,\nÃ€ bord de %2</t>
    <t id="3208">Commandant,\n\nJ'ai complÃ©tÃ© une analyse exhaustive du marchÃ© de %1 et des secteurs environnants (dans un rayon de %2 sauts, seuil de profit minimum : %3 Cr), mais malheureusement je n'ai trouvÃ© aucune opportunitÃ© commerciale rentable qui rÃ©ponde Ã  nos exigences.\n\nRAPPORT D'ANALYSE COMMERCIALE :\nTotal d'opportunitÃ©s Ã©valuÃ©es : %4\n\nDÃ‰TAIL DES REJETS :\n- Restrictions d'amarrage : %5 commerces\n  (La station ne permet pas ma classe de vaisseau)\n- RentabilitÃ© insuffisante : %6 commerces\n  (En dessous du seuil de profit minimum)\n- Volume insuffisant : %7 commerces\n  (QuantitÃ© commercialisable nulle ou nÃ©gative)\n- Restrictions de sÃ©curitÃ© : %8 commerces\n  (Stations sur liste noire ou secteurs dangereux)\n\nRECOMMANDATIONS :\n- ConsidÃ©rez l'ajustement des seuils de profit\n- Ã‰tendez la distance commerciale maximale\n- RÃ©visez les paramÃ¨tres de liste noire sectorielle\n- Attendez que les conditions du marchÃ© s'amÃ©liorent\n\nJe continuerai de surveiller le marchÃ© et vous notifierai lorsque des opportunitÃ©s rentables deviendront disponibles.\n\nEn attente,\nÃ€ votre service</t>
    <t id="3209">Commandant,\n\nALERTE DE ROUTE URGENTE\n\nMon systÃ¨me de renseignement sur les menaces a dÃ©tectÃ© que le secteur %1 (niveau de menace %2) est maintenant dans ma route commerciale planifiÃ©e. Pour la sÃ©curitÃ© du vaisseau et de l'Ã©quipage, j'abandonne immÃ©diatement l'opÃ©ration commerciale actuelle.\n\nACTIONS PRISES :\n- Tous les ordres commerciaux annulÃ©s\n- Retour au mode d'opÃ©rations sÃ©curisÃ©\n- Trouvera une route commerciale alternative qui Ã©vite les secteurs dangereux\n- Gestion de la cargaison : Automatique (vendront toute cargaison Ã  un endroit sÃ»r si nÃ©cessaire)\n\nLe systÃ¨me de liste noire dynamique empÃªchera les futurs commerces Ã  travers ce secteur jusqu'Ã  ce que la menace soit Ã©liminÃ©e.\n\nLa sÃ©curitÃ© est ma premiÃ¨re prioritÃ©.\n\nAvec vigilance,\nÃ€ bord de %3</t>
    <t id="3210">Commandant,\n\nROUTE D'Ã‰VASION INITIÃ‰E\n\nJe suis actuellement dans le secteur sur liste noire %1 et j'ai trouvÃ© une route commerciale qui me permettra de m'Ã©chapper en toute sÃ©curitÃ©.\n\nROUTE COMMERCIALE :\nAchat : %2 (Secteur : %3)\nVente : %4 (Secteur : %5)\nMarchandise : %6 (x%7)\nProfit Attendu : %8 Cr\n\nLe vaisseau s'Ã©chappera du secteur sur liste noire aprÃ¨s avoir complÃ©tÃ© ce commerce.\n\nRespectueusement,\nÃ€ votre service</t>
    <t id="3211">Commandant,\n\nMODE DE COMMERCE ISOLÃ‰\n\nJe suis actuellement dans le secteur %2, mais toutes les routes vers d'autres secteurs sont bloquÃ©es par des secteurs hub sur liste noire. Cela signifie que je ne peux commercer que dans mon secteur actuel jusqu'Ã  ce que la situation de liste noire change.\n\nSITUATION :\nSecteur Actuel : %2\nStatut : IsolÃ© (secteur non sur liste noire avec routes bloquÃ©es)\nMode Commercial : Commerces intra-sectoriels uniquement\n\nMon systÃ¨me commercial a automatiquement ajustÃ© les seuils de profit pour prioriser les opportunitÃ©s commerciales intra-sectorielles disponibles.\n\nJe continuerai de surveiller la situation et vous notifierai si les routes redeviennent disponibles.\n\nRespectueusement,\nÃ€ bord de %1</t>
    <t id="3218">Commandant,\n\nCHANGEMENT DE TRAJET DE ROUTE DÃ‰TECTÃ‰\n\nEn entrant dans le secteur %1, mon systÃ¨me de navigation a dÃ©tectÃ© que la route vers ma destination %2 (%3) a changÃ©.\n\nANALYSE DE TRAJET :\n- Distance normale : %4 sauts\n- Distance avec liste noire : %5\n- Statut : %6\n\nMon ordinateur de navigation indique que la route prÃ©fÃ©rÃ©e n'est plus viable en raison de restrictions de voyage sectoriel. Pour la sÃ©curitÃ© du vaisseau et de l'Ã©quipage, j'abandonne immÃ©diatement l'opÃ©ration commerciale actuelle.\n\nACTIONS PRISES :\n- Tous les ordres commerciaux annulÃ©s\n- Retour au mode d'opÃ©rations sÃ©curisÃ©\n- Trouvera une route commerciale alternative qui Ã©vite les secteurs bloquÃ©s\n- Gestion de la cargaison : Automatique (vendront toute cargaison Ã  un endroit sÃ»r si nÃ©cessaire)\n\nMon systÃ¨me de navigation Ã©vitera automatiquement les secteurs bloquÃ©s dans la planification future des routes.\n\nLa sÃ©curitÃ© est ma premiÃ¨re prioritÃ©.\n\nAvec vigilance,\nÃ€ bord de %7</t>
    <t id="3219">Secteur %1 nettoyÃ© - Toutes les menaces Ã©liminÃ©es</t>
    <t id="3220">Commandant,\n\nVAISSEAU ENNEMI Ã‰CHAPPÃ‰\n\nNotre systÃ¨me de renseignement sur les menaces a perdu la trace du vaisseau ennemi %3, qui s'est Ã©chappÃ© du secteur sur liste noire %1.\n\nDÃ‰TAILS :\n- Vaisseau Ã‰chappÃ© : %3\n- Secteur QuittÃ© : %1\n- Secteur de Destination : %2\n- Statut : Suivi perdu - le vaisseau a quittÃ© notre zone surveillÃ©e\n\nBien que ce vaisseau ne soit plus une menace dans le secteur %1, nous avons perdu le contact visuel et ne pouvons pas confirmer son statut actuel ou ses intentions dans le secteur %2.\n\nNos systÃ¨mes de suivi continueront de surveiller le secteur %1 pour les menaces restantes. Si tous les ennemis suivis partent ou sont Ã©liminÃ©s, le secteur sera automatiquement retirÃ© de la liste noire.\n\nAvec vigilance,\nSystÃ¨me de Renseignement sur les Menaces</t>
    <t id="3221">Commandant,\n\nJe n'ai pas pu trouver d'opportunitÃ©s commerciales rentables Ã  de plus grandes distances (jusqu'Ã  %3 sauts) car ces routes sont actuellement inaccessibles en raison de restrictions de voyage sectoriel (chemins sur liste noire).\n\nSITUATION :\nSecteur Actuel : %2\nPortÃ©e de Recherche Originale : %3 sauts\nPortÃ©e de Recherche Alternative : %4 sauts\n\nJe vais maintenant concentrer ma recherche sur les secteurs proches dans un rayon de %4 sauts, oÃ¹ les routes sont plus susceptibles d'Ãªtre accessibles. Cela devrait m'aider Ã  trouver des commerces rentables qui ont Ã©tÃ© prÃ©cÃ©demment filtrÃ©s en raison de restrictions de distance plutÃ´t que d'une non-rentabilitÃ© rÃ©elle.\n\nJe vous notifierai lorsque je trouverai des opportunitÃ©s commerciales appropriÃ©es dans la zone proche.\n\nRespectueusement,\nÃ€ bord de %1</t>
    <t id="3222">Commandant,\n\nSECTEUR SUR LISTE NOIRE\n\nNotre systÃ¨me de renseignement sur les menaces a dÃ©tectÃ© une activitÃ© hostile dans le secteur %1 et a automatiquement mis ce secteur sur liste noire pour protÃ©ger nos opÃ©rations commerciales.\n\nVAISSEAUX ENNEMIS DÃ‰TECTÃ‰S :\n%2\n\nDÃ‰TECTÃ‰ PAR : %3\n\nPour la sÃ©curitÃ© de nos vaisseaux et de l'Ã©quipage, toutes les routes commerciales Ã  travers ce secteur ont Ã©tÃ© bloquÃ©es. Nos vaisseaux contourneront automatiquement ce secteur jusqu'Ã  ce que la menace soit Ã©liminÃ©e.\n\nLe secteur sera automatiquement retirÃ© de la liste noire une fois que tous les vaisseaux ennemis suivis sont Ã©liminÃ©s ou quittent la zone.\n\nAvec vigilance,\nSystÃ¨me de Renseignement sur les Menaces</t>
    <t id="3223">Commandant,\n\nJe ne peux pas trouver de station de formation accessible pour mon examen de niveau %1. Je vais poursuivre les opÃ©rations commerciales comme demandÃ©, mais je comprends que je ne gagnerai pas de points d'expÃ©rience jusqu'Ã  ce que je puisse terminer la formation requise. AprÃ¨s cette course commerciale, je chercherai Ã  nouveau une opportunitÃ© de formation possible.\n\nRespectueusement,\nÃ€ bord de %2</t>
    <t id="3224">Frais de licence de formationÂ : %1 Cr</t>
    <t id="3225">Bonus : J'ai gagnÃ© %1 niveau de compÃ©tence supplÃ©mentaire%2 grÃ¢ce Ã  l'expÃ©rience accumulÃ©e pendant la formation ! Niveau actuel : %3</t>
    <t id="3214">C'est un honneur de travailler pour vous, %1 ! Je suis excitÃ© de commencer ma carriÃ¨re commerciale sous votre commandement. Je ferai de mon mieux pour vous servir et contribuer Ã  votre succÃ¨s.</t>
    <t id="3215">Merci de m'avoir donnÃ© ces vacances bien mÃ©ritÃ©es, %1 ! J'ai apprÃ©ciÃ© mon temps loin du commerce et mes compÃ©tences restent intactes. J'ai hÃ¢te de retourner au travail chaque fois que vous aurez besoin de moi. Jusque-lÃ , je garderai mes connaissances commerciales affÃ»tÃ©es !</t>
    <t id="3216">Je suis de retour des vacances et prÃªt Ã  travailler Ã  nouveau, %1 ! Mes compÃ©tences commerciales restent affÃ»tÃ©es et j'ai hÃ¢te de continuer Ã  vous servir sur %2. Merci pour le repos bien mÃ©ritÃ© !</t>
    <t id="3217">Merci pour mon transfert vers %1, %2 ! Je suis honorÃ© par cette nouvelle affectation et prendrai excellent soin de mon nouveau vaisseau. Mon expÃ©rience et mes compÃ©tences commerciales restent intactes, et je suis prÃªt Ã  continuer Ã  vous servir.</t>
    <t id="3227">Coque perdue, dignitÃ© en attente de rÃ©cupÃ©ration</t>
    <t id="3228">Commandant %1,\n\n%2 signale depuis %3. Mon vaisseau a explosÃ©. Pas moi. Je suis dÃ©sormais la cargaison flottante la plus chÃ¨re de la flotte.\n\nMarqueur cartographique joint. DÃ©pÃªchez-vous - j'Ã©tais en pleine facturation.\n\nFlottant professionnellement,\n%2</t>
    <t id="3229">Pilote rÃ©cupÃ©rÃ© - DÃ©pendance Ã  l'oxygÃ¨ne guÃ©rie</t>
    <t id="3230">Commandant %1,\n\nMise Ã  jour de flotte : %2 a Ã©tÃ© rÃ©cupÃ©rÃ© par %3 (%4) et ne vous facture plus la formation EVA prolongÃ©e.\n\nReconnexion du registre en cours. Recommandation : ne poser aucune question sur l'ancien vaisseau.\n\nHonteusement vÃ´tre,\n%2</t>
<t id="4000">Coordination de flotte : %s a Ã©tÃ© assignÃ© Ã  la route %s</t>
    <t id="4001">Coordination de flotte : La route %s est entiÃ¨rement utilisÃ©e</t>
    <t id="4002">Coordination de flotte : %s a libÃ©rÃ© la route %s</t>
    <t id="5000">%s a Ã©tÃ© assignÃ© comme territoire primaire pour %s</t>
    <t id="5001">%s a atteint le niveau d'expertise %s en %sÂ !</t>
    <t id="5002">Bonus de territoire appliquÃ© : %s%% d'augmentation de profit dans %s</t>
    <t id="9500">Erreur : %s est bloquÃ© et a besoin d'assistance !</t>
    <t id="9501">Erreur : Commerce Ã©chouÃ© pour %s</t>
    <t id="9502">ErreurÂ : Impossible d'enregistrer %s avec GalaxyTrader MK3</t>
    <t id="80001">Marchandise %s ajoutÃ©e Ã  la liste noire</t>
    <t id="80002">Marchandise %s retirÃ©e de la liste noire</t>
    <t id="80003">Marchandise %s ajoutÃ©e Ã  la liste blanche</t>
    <t id="80004">Automatiquement sur liste noire (mauvaises performances)Â : %s</t>
    <t id="80005">Marchandise dangereuse priorisÃ©e : %s</t>
    <t id="80006">Filtre de marchandises : %s actif, %s commerces bloquÃ©s</t>
    <t id="80007">Tous les filtres de marchandises effacÃ©s</t>
    <t id="80008">Filtres de marchandises rÃ©initialisÃ©s par dÃ©faut</t>
    <t id="80009">Gestion des filtres d'articles</t>
    <t id="80010">Marchandises BloquÃ©es</t>
    <t id="80011">Marchandises AutorisÃ©es</t>
    <t id="80012">Manipulation d'articles dangereux</t>
    <t id="80013">Valeur minimale des marchandises</t>
    <t id="80014">Valeur maximale des marchandises</t>
    <t id="80015">Factions restreintes</t>
    <t id="80016">CatÃ©gories de marchandises mises Ã  jour depuis l'Ã©tat actuel du jeu</t>
    <t id="80017">%s marchandises catÃ©gorisÃ©es : %s Ã  faible valeur, %s dangereuses, %s Ã  haute valeur</t>
    <t id="80018">CatÃ©gorisation dynamique de marchandises activÃ©e</t>
    <t id="80019">Liste noire automatique pour la catÃ©gorie %s dÃ©sactivÃ©e</t>
    <t id="80020">Nouvelles marchandises d'autres mods dÃ©tectÃ©es et catÃ©gorisÃ©es</t>
    <t id="9000">GalaxyTrader - ParamÃ¨tres Globaux</t>
    <t id="9010">SystÃ¨me XP et EntraÃ®nement</t>
    <t id="9012">EntraÃ®nement Automatique</t>
    <t id="9013">Multiplicateur d'XP</t>
    <t id="9015">Pourcentage de bonus de commandant</t>
    <t id="9020">Coordination de la flotte</t>
    <t id="9021">Activer la coordination de la flotte</t>
    <t id="9023">Activer le cache d'Ã©change</t>
    <t id="9030">Notifications</t>
    <t id="9031">Niveau de notification</t>
    <t id="9040">SystÃ¨me de RÃ©paration Automatique</t>
    <t id="9041">Activer la RÃ©paration Automatique</t>
    <t id="9042">Seuil de RÃ©paration de Coque</t>
    <t id="9310">Mineur de Galaxie</t>
    <t id="9311">Attente scan sondes ressources par secteur</t>
    <t id="9312">Poids de proximitÃ© du vaisseau</t>
    <t id="9043">Niveau pilote minimum</t>
    <t id="9004">Fourchettes de prix de nÃ©gociation</t>
    <t id="9005">Prix â€‹â€‹d'offre de vente maximum</t>
    <t id="9006">Prix â€‹â€‹de l'offre d'achat minimum</t>
    <t id="9007">IsolÃ© : Prix Maximum de Vente</t>
    <t id="9008">IsolÃ© : Prix Minimum d'Achat</t>
    <t id="9009">Solution de repliÂ : prix de vente maximum</t>
    <t id="9014">Solution de repliÂ : prix d'achat minimum</t>
    <t id="9016">Base du seuil de profit</t>
    <t id="9025">Argent minimum du joueur</t>
    <t id="9024">TolÃ©rance de Chute du Cache</t>
    <t id="9026">DurÃ©e de stationnement inactif avant libÃ©ration</t>
    <t id="9054">Bloquer les secteurs des factions ennemies</t>
    <t id="9055">Niveau de menace de la liste noire</t>
    <t id="9056">RecrÃ©er la Liste Noire</t>
    <t id="9057">RecrÃ©er</t>
    <t id="9058">Attribuer aux navires GT</t>
    <t id="9059">Attribuer</t>
    <t id="9112">Envoie automatiquement les pilotes en formation lorsqu'ils atteignent les niveaux requis. DÃ©sactiver pour contrÃ´ler manuellement le moment de la formation.</t>
    <t id="9113">Ajuste la vitesse Ã  laquelle les pilotes gagnent de l'expÃ©rience. Des valeurs plus Ã©levÃ©es signifient une progression plus rapide.</t>
    <t id="9115">Pourcentage d'XP des subordonnÃ©s attribuÃ© aux pilotes commandants. RÃ©glez sur 0% pour dÃ©sactiver le bonus d'XP du commandant. Par dÃ©faut : 10%.</t>
    <t id="9121">Active les fonctionnalitÃ©s intelligentes de coordination de flotte incluant l'optimisation de route et l'Ã©quilibrage de charge.</t>
    <t id="9123">Permet de partager les opportunitÃ©s commerciales rentables entre les membres de la flotte pour une meilleure coordination.</t>
    <t id="9131">ContrÃ´le le nombre de notifications affichÃ©es : 0=Silencieux, 1=Important uniquement, 2=Toutes les notifications</t>
    <t id="9141">Envoie automatiquement les vaisseaux en rÃ©paration aprÃ¨s avoir complÃ©tÃ© des commerces lorsque la coque tombe en dessous du seuil. Uniquement pour les pilotes expÃ©rimentÃ©s (Niveau 12+). Les vaisseaux choisissent l'installation appropriÃ©e : S/M Station d'Ã‰quipement, L/XL Chantier Naval.</t>
    <t id="9142">Pourcentage de coque en dessous duquel la rÃ©paration automatique est dÃ©clenchÃ©e. Par dÃ©faut : 95%. Les vaisseaux iront automatiquement Ã  l'installation de rÃ©paration la plus proche lorsqu'ils sont endommagÃ©s.</t>
    <t id="9411">Si activÃ©, les mineurs attendent lors de l'Ã©valuation des sondes de ressources de la faction dans le secteur (+5 s par sonde au-delÃ  d'une). Le niveau GT du pilote rÃ©duit cette attente linÃ©airement, du temps complet au niveau 1 Ã  5 secondes au niveau 15 (mode XP GT uniquement, si l'attente dÃ©passe 5 s). DÃ©sactivÃ© = aucune attente (comportement vanilla).</t>
    <t id="9412">Favorise les vaisseaux MK3/MK4 vers des stations d'achat plus proches lors du tri des trades validÃ©s. Score de sÃ©lection = score du trade / (1 + sauts vaisseauâ†’achat Ã— poids). Curseur 0-100 (0 = off ; 4 = dÃ©faut 0,04). N'affecte ni le classement du cache ni les limites de portÃ©e territoriale.</t>
    <t id="9143">Niveau minimum du pilote requis pour la fonctionnalitÃ© de rÃ©paration automatique. Par dÃ©faut : 12 (commerÃ§ants expÃ©rimentÃ©s). Les pilotes de niveau infÃ©rieur doivent rÃ©parer manuellement.</t>
    <t id="9104">Prix relatif maximum pour les offres de vente (le vaisseau achÃ¨te DES stations). Plage : -1.0 Ã  +1.0. Par dÃ©faut : 0.5 (50% au-dessus de la moyenne). Plus Ã©levÃ© = plus cher mais plus d'options.</t>
    <t id="9105">Prix relatif minimum pour les offres d'achat (le vaisseau vend AUX stations). Plage : -1.0 Ã  +1.0. Par dÃ©faut : -0.5 (50% en dessous de la moyenne). Plus bas = acheteurs moins chers mais plus d'options.</t>
    <t id="9106">Prix maximum de vente pour les vaisseaux isolÃ©s (bloquÃ©s dans un seul secteur). Plage : -1.0 Ã  +1.0. Par dÃ©faut : 0.5.</t>
    <t id="9107">Prix minimum d'achat pour les vaisseaux isolÃ©s (bloquÃ©s dans un seul secteur). Plage : -1.0 Ã  +1.0. Par dÃ©faut : -0.5.</t>
    <t id="9108">Prix maximum de vente pour la recherche de recours (dernier recours lorsque la recherche normale Ã©choue). Plage : -1.0 Ã  +1.0. Par dÃ©faut : 0.5. La recherche de recours utilise MaxDistance=2 et des seuils de profit assouplis.</t>
    <t id="9109">Prix minimum d'achat pour la recherche de recours (dernier recours lorsque la recherche normale Ã©choue). Plage : -1.0 Ã  +1.0. Par dÃ©faut : -0.5. La recherche de recours utilise MaxDistance=2 et des seuils de profit assouplis.</t>
    <t id="9116">BÃ©nÃ©fice minimum de base au niveau 15 pour un commerÃ§ant moyen (rÃ©fÃ©rence cargo 8200). Le MinAbsoluteProfit rÃ©el est calculÃ© par pilote + mis Ã  l'Ã©chelle par cargoÂ :\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(mis Ã  l'Ã©chelle, 25Â % de la base(L))\n\nRÃ©glÃ© sur 0 pour accepter tout profit (uniquement ROI/distance/autres filtres applicables).</t>
    <t id="9125">Minimum d'argent du joueur (crÃ©dits) requis avant que les navires chercheront des trades. Lorsque l'argent du joueur tombe en dessous de ce seuil, tous les navires sautent les recherches commerciales et d'attendre, empÃªchant la numÃ©risation de cache coÃ»teuse qui cause le bÃ©gaiement du jeu.</t>
    <t id="9124">Chute de pourcentage ROI maximum depuis la valeur en cache avant de rejeter le commerce. Exemple : 20% ROI en cache avec 15% de tolÃ©rance accepte jusqu'Ã  17% ROI (chute de 14%).</t>
    <t id="9126">Minutes Ã  quai avant de dÃ©samarrer pour libÃ©rer le port (0-60). 0 = reste Ã  quai jusqu'Ã  ce qu'un nouveau travail soit trouvÃ©. Par dÃ©faut : 1 minute.</t>
    <t id="9154">Met automatiquement sur liste noire tous les secteurs appartenant aux factions ennemies (case Ã  cocher de relation dans la liste noire)</t>
    <t id="9155">Niveau de menace minimum (1-5) requis pour mettre un secteur sur liste noire :\n2=Moyen (attaque unique)\n3=Moyen-Ã‰levÃ© (factions hostiles)\n4=Ã‰levÃ© (vaisseaux capitaux/missiles)\n5=TrÃ¨s Ã‰levÃ© (Xenon/Khaak)</t>
    <t id="9156">RecrÃ©er manuellement la liste noire d'Ã©vitement de menaces (utile si elle a Ã©tÃ© supprimÃ©e)</t>
    <t id="9157">Attribuez manuellement la liste noire dynamique actuelle Ã  tous les navires commandant de flotte GT. Les subordonnÃ©s hÃ©ritent de leur commandant.</t>
    <t id="6001">Apprenti</t>
    <t id="6002">Courrier</t>
    <t id="6003">Fournisseur</t>
    <t id="6004">CommerÃ§ant</t>
    <t id="6005">Marchand</t>
    <t id="6006">CommerÃ§ant longue distance</t>
    <t id="6101">Ã‰quilibrÃ©</t>
    <t id="6102">DÃ©fensif</t>
    <t id="6103">AxÃ© Commerce</t>
    <t id="6104">DÃ©fense Lourde</t>
    <t id="6105">Prise en charge de la tour</t>
    <t id="9050">SystÃ¨me d'Ã‰vitement de Menaces</t>
    <t id="9051">Activer l'Ã‰vitement de Menaces :</t>
    <t id="9052">Seuil de relation hostileÂ :</t>
    <t id="9053">Utiliser la liste noire dynamiqueÂ :</t>
    <t id="9151">Les commerÃ§ants de Niveau 6+ dÃ©tectent les vaisseaux hostiles et Ã©vitent les routes dangereuses. DÃ©sactiver arrÃªte toutes les analyses (amÃ©liore les performances). TolÃ©rance au risque par vaisseau dans le comportement de commande (Ã©chelle 0-10).</t>
    <t id="9152">Marque uniquement les factions avec une relation Ã©gale ou infÃ©rieure Ã  cette valeur comme menaces. Par dÃ©faut : -20%</t>
    <t id="9153">Met automatiquement sur liste noire les secteurs dangereux (niveau de menace 3+) pour forcer les vaisseaux Ã  contourner les menaces. Utilise le pathfinding vanilla pour les routes alternatives.</t>
    <t id="9060">RÃ©approvisionnement Automatique d'Ã‰quipement DÃ©fensif (Niveau 15)</t>
    <t id="9061">Activer le RÃ©approvisionnement Automatique :</t>
    <t id="9062">RÃ©approvisionner les Contremesures :</t>
    <t id="9063">RÃ©approvisionner les Drones de DÃ©fense :</t>
    <t id="9064">RÃ©approvisionner les Drones Commerciaux :</t>
    <t id="9065">RÃ©approvisionner les Tours Laser :</t>
    <t id="9066">RÃ©approvisionner les Drones de RÃ©paration :</t>
    <t id="9067">Seuil de contre-mesureÂ :</t>
    <t id="9068">Seuil de CapacitÃ© UnifiÃ©e :</t>
    <t id="9069">Profil d'Ã‰quilibre d'Ã‰quipement :</t>
    <t id="9161">Les MaÃ®tres CommerÃ§ants (Niveau 15) rÃ©approvisionnent automatiquement l'Ã©quipement dÃ©fensif aprÃ¨s les commerces. S'applique au niveau de commandant pour les subordonnÃ©s.</t>
    <t id="9162">Tous les vaisseaux (S/M/L/XL). CapacitÃ© sÃ©parÃ©e. Critique pour la dÃ©fense contre les missiles.</t>
    <t id="9163">Vaisseaux L/XL uniquement. Partage la capacitÃ© unifiÃ©e avec d'autres Ã©quipements dÃ©ployables.</t>
    <t id="9164">Vaisseaux L/XL uniquement. Essentiel pour les opÃ©rations commerciales. Partage la capacitÃ© unifiÃ©e.</t>
    <t id="9165">Tous les vaisseaux. Les vaisseaux L/XL partagent la capacitÃ© unifiÃ©e, S/M utilisent la cargaison.</t>
    <t id="9166">Vaisseaux L/XL uniquement. Fonctionne avec le systÃ¨me de rÃ©paration automatique. Partage la capacitÃ© unifiÃ©e.</t>
    <t id="9167">RÃ©approvisionner lorsque les contremesures sont en dessous de ce pourcentage (tous les vaisseaux, capacitÃ© sÃ©parÃ©e).</t>
    <t id="9168">RÃ©approvisionner lorsque le total des Ã©quipements dÃ©ployables est en dessous de ce pourcentage (vaisseaux L/XL : drones + tours partagent une capacitÃ©).</t>
    <t id="9169">Distribution de la capacitÃ© unifiÃ©e (vaisseaux L/XL) : AxÃ© Commerce (20/50/20/10), Ã‰quilibrÃ© (35/35/20/10), DÃ©fensif (50/20/20/10), DÃ©fense Lourde (40/30/20/10), Support de Tours (30/30/30/10). Ratios : DÃ©fense/Commerce/Tours/RÃ©paration. Cliquez pour parcourir les options.</t>
    <t id="9090">Modifications du navire</t>
    <t id="9091">Activer les modifications du navire</t>
    <t id="9191">Installe automatiquement les modifications de vaisseau et de moteur basÃ©es sur le niveau du pilote. Niveau 9+ = Mods Niveau 1, Niveau 12+ = Mods Niveau 2, Niveau 15+ = Mods Niveau 3. Seuls les mods installÃ©s par GT sont retirÃ©s lorsque l'ordre est annulÃ©.</t>
    <t id="9070">Configuration de dÃ©nomination des navires</t>
    <t id="9071">Afficher XPÂ :</t>
    <t id="9072">Classement d'affichageÂ :</t>
    <t id="9073">Niveau d'affichageÂ :</t>
    <t id="9074">Statut d'affichageÂ :</t>
    <t id="9075">Activer le renommage du navireÂ :</t>
    <t id="9076">PrÃ©fixe</t>
    <t id="9077">Suffixe</t>
    <t id="9078">Source de Nom par DÃ©faut :</t>
    <t id="9079">Nom de ModÃ¨le</t>
    <t id="9080">Nom du type</t>
    <t id="9081">Base du modÃ¨le</t>
    <t id="9083">Nom personnalisÃ©</t>
    <t id="9084">Afficher le secteur d'origine :</t>
    <t id="9085">Mode de nommage :</t>
    <t id="9086">Classique</t>
    <t id="9087">ModÃ¨le</t>
    <t id="9088">ModÃ¨le de nom :</t>
    <t id="9089">Jetons : {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. Atomiques : {RS} {CB} {BL}, etc. Utilise les abrÃ©viations d'Ã©tat ci-dessous. Les jetons vides sont omis ; les espaces sont rÃ©duits. 128 caractÃ¨res max.</t>
    <t id="9183">Afficher le secteur d'origine configurÃ© dans le nom du vaisseau (prÃ©fixe ou suffixe).</t>
    <t id="9184">Format de nom personnalisÃ© avec jetons {TOKEN} au lieu des options de mise en page classique. NÃ©cessite l'XP GalaxyTrader (pas le mode XP vanilla).</t>
    <t id="9092">Jetons de modÃ¨le</t>
    <t id="9093">Vaisseau : {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT : {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP : {MGMT} {PILOTSKILL}</t>
    <t id="9096">Base : {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Ã‰quipage : {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Secteur : {SECTOR} | Stats : {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Jetons d'Ã©tat :</t>
    <t id="9100">{OPSTATE}: tous les indicateurs opÃ©rationnels actifs (ex. CB RS, MT)</t>
    <t id="9101">{STATUS}: bloquÃ©, formation, secours ou isolÃ©</t>
    <t id="9102">{CB}: blacklist perso. uniquement ; inclus dans {OPSTATE} ; ne pas combiner</t>
    <t id="9082">Afficher la classe du navireÂ :</t>
    <t id="9171">Afficher les valeurs XP dans les noms des navires</t>
    <t id="9175">Activer ou dÃ©sactiver le renommage automatique de vaisseau avec les informations du pilote</t>
    <t id="9172">Afficher les titres de classement dans les noms des navires</t>
    <t id="9173">Afficher les numÃ©ros de niveau dans les noms de vaisseaux</t>
    <t id="9174">Afficher le statut commercial dans les noms des navires</t>
    <t id="9178">Choisir la source pour les noms de base des vaisseaux : Nom de ModÃ¨le (avec variante), Nom de Type (gÃ©nÃ©rique), ou Nom de Base (sans variante)</t>
    <t id="9182">Afficher la classe du navire (S, M, L, XL) dans les noms des navires</t>
    <t id="9200">ParamÃ¨tres de DÃ©bogage</t>
    <t id="9201">Activer la Journalisation de DÃ©bogage :</t>
    <t id="9202">Interrupteur maÃ®tre pour toute sortie debug_text. Lorsque dÃ©sactivÃ©, toute journalisation de dÃ©bogage est supprimÃ©e. Lorsque activÃ©, les messages de dÃ©bogage apparaissent dans le DebugLog basÃ©s sur les valeurs de chance individuelles debug_text.</t>
    <t id="9220">Entretien et diagnostic</t>
    <t id="9221">RÃ©initialiser les Statistiques de Profit :</t>
    <t id="9222">RÃ‰INITIALISER</t>
    <t id="9223">Effacer tous les secteurs sur liste noireÂ :</t>
    <t id="9224">CLAIR</t>
    <t id="9225">RÃ©initialiser Tous les ParamÃ¨tres par DÃ©faut :</t>
    <t id="9226">TOUT RÃ‰INITIALISER</t>
    <t id="9323">Retire tous les secteurs de la liste noire de renseignement sur les menaces. Cela effacera immÃ©diatement tous les secteurs sur liste noire et permettra Ã  vos vaisseaux de voyager vers les zones prÃ©cÃ©demment bloquÃ©es. Utilisez ceci si vous voulez rÃ©initialiser le systÃ¨me d'Ã©vitement de menaces ou si des secteurs ont Ã©tÃ© incorrectement mis sur liste noire.</t>
    <t id="9321">RÃ©initialise toutes les statistiques de profit Ã  0 pour tous les pilotes et vaisseaux. Utilisez ceci aprÃ¨s la mise Ã  niveau vers v0.6.0 pour effacer les statistiques gonflÃ©es basÃ©es sur les revenus. La correction suit maintenant le PROFIT rÃ©el (revenus - coÃ»t d'achat). Les comptes de commerce et XP sont prÃ©servÃ©s.</t>
    <t id="9325">RÃ©initialise tous les paramÃ¨tres globaux Ã  leurs valeurs par dÃ©faut. Cela inclut les paramÃ¨tres XP, Coordination de Flotte, Notifications, Renseignement Mobile, Ã‰vitement de Menaces, DÃ©nomination des Vaisseaux, RÃ©paration Auto, Modifications, Performance et Format de Nombre. Le paramÃ¨tre de journalisation de dÃ©bogage est prÃ©servÃ© pour permettre la journalisation de l'opÃ©ration de rÃ©initialisation.</t>
    <t id="9227">Effacer le cache commercial pour tous les secteurs dâ€™origineÂ :</t>
    <t id="9228">EFFACER LE CACHE</t>
    <t id="9327">Efface le cache commercial pour tous les secteurs d'origine. Cela forcera tous les vaisseaux Ã  effectuer des recherches en direct fraÃ®ches lors de leur prochaine recherche commerciale. Utilisez ceci si le cache semble obsolÃ¨te ou corrompu, ou si vous souhaitez forcer un rafraÃ®chissement complet du cache.</t>
    <t id="9229">LibÃ©rer tous les verrous de recherche</t>
    <t id="9329">LibÃ¨re TOUS les verrous de recherche commerciale en cours et efface les Ã©tats transitoires associÃ©s. Utilisez ceci si les vaisseaux sont bloquÃ©s sur Â« Recherche de commerces Â» en raison de verrous obsolÃ¨tes provenant d'anciennes sauvegardes. Peut interrompre des recherches lÃ©gitimes.</t>
    <t id="9290">Statut du Dump Trade HubÂ :</t>
    <t id="9291">DÃ‰CHARGE</t>
    <t id="9390">Affiche un instantanÃ© unique du hub commercial centralisÃ© (files d'attente du planificateur + statut du dernier vaisseau demandeur) dans le journal et sous forme de notification.</t>
    <t id="9292">Vider le cache d'Ã©change (COMPLET)Â :</t>
    <t id="9293">Vider le cache</t>
    <t id="9392">Export COMPLET du cache (peut Ãªtre volumineux). Ã‰crit toutes les entrÃ©es du cache dans le DebugLog par morceaux. Cliquez Ã  nouveau pour annuler.</t>
    <t id="9294">Effacer les rÃ©servations de flotteÂ :</t>
    <t id="9295">CLAIR</t>
    <t id="9394">Efface toutes les rÃ©servations commerciales de flotte actives. Utilisez-le si les navires semblent bloquÃ©s en attendant l'expiration des Ã©changes rÃ©servÃ©s, ou si la table de rÃ©servation est devenue obsolÃ¨te aprÃ¨s le chargement d'une ancienne sauvegarde.</t>
    <t id="9230">Performance</t>
    <t id="9231">DÃ©lai de Traitement par Lots :</t>
    <t id="9232">DÃ©lai de Validation :</t>
    <t id="9233">Recherches SimultanÃ©es Max :</t>
    <t id="9234">Commerces Max Ã  Retourner :</t>
    <t id="9235">Offres maximales par articleÂ :</t>
    <t id="9236">Nombre maximum d'Ã©changes par articleÂ :</t>
    <t id="9237">Offres maximales par article pour la correspondanceÂ :</t>
    <t id="9238">Seuil de Sortie AnticipÃ©e :</t>
    <t id="9241">Intervalle de tranche d'offre en directÂ :</t>
    <t id="9266">Recherche TTL de verrouillageÂ :</t>
    <t id="9263">Taille des morceaux de lotsÂ :</t>
    <t id="9239">Format des nombres</t>
    <t id="9240">Style de formatÂ :</t>
    <t id="9242">Utiliser le suffixe M</t>
    <t id="9243">Seuil du suffixeÂ MÂ :</t>
    <t id="9244">Allemand (123.456,78)</t>
    <t id="9245">Anglais (123 456,78)</t>
    <t id="9510">Notifications de montÃ©e de niveau :</t>
    <t id="9511">Alertes de formation requise :</t>
    <t id="9512">Notifications de formation terminÃ©e :</t>
    <t id="9513">Rapports de profit :</t>
    <t id="9514">Alertes de marchÃ© :</t>
    <t id="9515">Mises Ã  jour de flotte :</t>
    <t id="9516">Utilisez uniquement la vanille XP</t>
    <t id="9610">Activer ou dÃ©sactiver les notifications popup de montÃ©e de niveau du trader dans l'interface joueur.</t>
    <t id="9611">Alerte lorsque les pilotes ont besoin d'une formation pour passer au niveau suivant.</t>
    <t id="9612">Notification lorsque les pilotes terminent leur formation et montent en grade.</t>
    <t id="9613">RÃ©sumÃ©s de profit pÃ©riodiques (rapports simples et complets).</t>
    <t id="9614">OpportunitÃ©s de marchÃ© exceptionnelles et alertes de trades Ã  haute valeur.</t>
    <t id="9615">Messages de coordination de flotte et mises Ã  jour de statut.</t>
    <t id="9616">Utilisez pilot.skill.piloting et dÃ©sactivez la progression/caps GT XP.</t>
    <t id="9246">FrÃ©quence Rapport Simple :</t>
    <t id="9247">FrÃ©quence Rapport Complet :</t>
    <t id="9248">Recherches Cache SimultanÃ©es Max :</t>
    <t id="9249">Recherches Live SimultanÃ©es Max :</t>
    <t id="9340">Choisissez le format de nombre : L'allemand utilise '.' pour les milliers et ',' pour les dÃ©cimales (123.456,78), l'anglais utilise ',' pour les milliers et '.' pour les dÃ©cimales (123,456.78)</t>
    <t id="9342">Activer le suffixe M pour les nombres supÃ©rieurs au seuil (par exemple, 1.0 M au lieu de 1,000,000)</t>
    <t id="9343">Seuil pour le suffixe M. Les nombres supÃ©rieurs Ã  cette valeur seront affichÃ©s avec le suffixe M (par dÃ©faut : 999,999)</t>
    <t id="9346">FrÃ©quence du rapport simple (notification popup) : 0-30 minutes (0 = dÃ©sactivÃ© - les rapports simples sont dÃ©sactivÃ©s, par dÃ©faut : 1 minute)</t>
    <t id="9347">FrÃ©quence du rapport complet (entrÃ©e de journal) : 0-60 minutes (0 = dÃ©sactivÃ© - les rapports complets sont dÃ©sactivÃ©s, par dÃ©faut : 30 minutes)</t>
    <t id="9398">Utiliser le remplacement des crÃ©dits GT dus</t>
    <t id="9399">Remplace ou complÃ¨te la ligne vanilla "CR dus des Ã©changes" avec la valeur projetÃ©e GT dans le mÃªme emplacement UI.</t>
    <t id="9331">DÃ©lai entre les lots pendant le traitement de recherche commerciale (1-100ms). Des valeurs plus Ã©levÃ©es rÃ©duisent la charge CPU mais ralentissent les recherches commerciales. Par dÃ©faut : 50ms. UtilisÃ© dans le processeur de lots et le filtrage de liste commerciale.</t>
    <t id="9332">DÃ©lai entre les validations de commerce dans le script AI (1-100ms). Des valeurs plus Ã©levÃ©es rÃ©duisent la charge CPU mais ralentissent la validation de commerce. Par dÃ©faut : 50ms. UtilisÃ© lors de la validation de la liste commerciale du systÃ¨me MD.</t>
    <t id="9333">Nombre maximum de recherches commerciales qui peuvent s'exÃ©cuter simultanÃ©ment (1-10). Des valeurs plus basses rÃ©duisent la charge CPU mais augmentent les temps d'attente en file. Des valeurs plus Ã©levÃ©es traitent les recherches plus rapidement mais peuvent causer des pics de performance. Par dÃ©faut : 1.</t>
    <t id="9334">Nombre maximum de commerces Ã  retourner de la recherche en cache (50-1000). Des valeurs plus Ã©levÃ©es fournissent plus d'options commerciales mais augmentent le temps de traitement. Des valeurs plus basses rÃ©duisent la charge CPU mais peuvent manquer des commerces rentables. Par dÃ©faut : 200.</t>
    <t id="9335">Nombre maximum d'offres par marchandise Ã  traiter dans la recherche en direct (5-100). Des valeurs plus Ã©levÃ©es considÃ¨rent plus d'offres mais augmentent le temps de traitement. Des valeurs plus basses rÃ©duisent la charge CPU mais peuvent manquer des commerces rentables. Par dÃ©faut : 20.</t>
    <t id="9336">Nombre maximum de commerces par marchandise pendant le traitement par lots (5-100). Des valeurs plus Ã©levÃ©es permettent plus de commerces par marchandise mais augmentent le temps de traitement. Des valeurs plus basses rÃ©duisent la charge CPU mais peuvent manquer des commerces rentables. Par dÃ©faut : 20.</t>
    <t id="9337">Nombre maximum d'offres par marchandise pour correspondance dans le processeur de lots (5-100). Des valeurs plus Ã©levÃ©es considÃ¨rent plus d'offres mais augmentent le temps de traitement. Des valeurs plus basses rÃ©duisent la charge CPU mais peuvent manquer des commerces rentables. Par dÃ©faut : 20.</t>
    <t id="9338">Seuil de sortie anticipÃ©e pour le traitement par lots (100-10000). Lorsque ce nombre de commerces est trouvÃ©, le traitement par lots s'arrÃªte tÃ´t pour Ã©conomiser le CPU. Des valeurs plus Ã©levÃ©es traitent plus de commerces mais augmentent la charge CPU. Des valeurs plus basses sortent plus tÃ´t mais peuvent manquer des commerces rentables. Par dÃ©faut : 2000.</t>
    <t id="9341">Intervalle de tranche d'offres en direct en millisecondes (5-500ms). ContrÃ´le la frÃ©quence Ã  laquelle les tranches d'offres en direct peuvent commencer. Des valeurs plus basses permettent une collecte d'offres plus rapide mais augmentent la charge CPU. Des valeurs plus Ã©levÃ©es rÃ©duisent la charge CPU mais ralentissent le traitement de recherche en direct. Par dÃ©faut : 500ms.</t>
    <t id="9363">Taille de lot de traitement (5-20). Traite chunkSizeÃ—chunkSize combinaisons par lot (par exemple, 10Ã—10 = 100 combinaisons). Des lots plus grands amÃ©liorent le dÃ©bit mais augmentent la charge CPU par lot. Des lots plus petits rÃ©duisent les pics CPU mais nÃ©cessitent plus de continuations. Par dÃ©faut : 10.</t>
    <t id="9348">Nombre maximum de recherches en cache qui peuvent s'exÃ©cuter simultanÃ©ment (1-20). Les recherches en cache sont rapides et peu coÃ»teuses, donc des valeurs plus Ã©levÃ©es permettent plus de vÃ©rifications de cache parallÃ¨les sans impact CPU significatif. Des valeurs plus basses rÃ©duisent les recherches de cache parallÃ¨les. Par dÃ©faut : 5.</t>
    <t id="9349">Nombre maximum de recherches en direct qui peuvent s'exÃ©cuter simultanÃ©ment (1-10). Les recherches en direct sont intensives en CPU, donc des valeurs plus basses rÃ©duisent la charge CPU mais augmentent les temps d'attente en file. Des valeurs plus Ã©levÃ©es traitent les recherches plus rapidement mais peuvent causer des pics de performance. Par dÃ©faut : 1.</t>
    <t id="9264">Taille de Lot de RequÃªte Cache :</t>
    <t id="9265">Taille du fragment d'ajout d'offre en directÂ :</t>
    <t id="9364">EntrÃ©es de cache validÃ©es par lot (10-200). Des valeurs plus petites rÃ©partissent la validation du cache sur plus de frames (plus fluide) mais peuvent augmenter le temps pour trouver un commerce en cache. Par dÃ©faut : 10.</t>
    <t id="9365">Offres ajoutÃ©es par tranche d'ajout (50-2000). Des valeurs plus petites rÃ©duisent le travail d'ajout de liste par frame (plus fluide) mais peuvent ralentir l'achÃ¨vement de la recherche en direct. Par dÃ©faut : 200.</t>
    <t id="9366">DurÃ©e de vie du verrou de recherche en secondes (60-7200). Si un vaisseau est refusÃ© avec Â« recherche commerciale dÃ©jÃ  en cours Â» pendant plus longtemps que cela, GT s'auto-guÃ©rira en effaÃ§ant l'Ã©tat de recherche obsolÃ¨te et en libÃ©rant le verrou. Par dÃ©faut : 600s.</t>
    <t id="9370">Seuil souple de contre-pression par lotsÂ :</t>
    <t id="9371">Seuil strict de contre-pression par lotsÂ :</t>
    <t id="9372">Secteurs par trancheÂ :</t>
    <t id="9373">DÃ©lai de RafraÃ®chissement Secteur Domicile :</t>
    <t id="9374">DÃ©lai de Base aprÃ¨s Ã‰chec Cache :</t>
    <t id="9375">Intervalle de tick du planificateurÂ :</t>
    <t id="9376">RequÃªtes Cache Max par Tic :</t>
    <t id="9377">Nombre maximum de continuations de recherche par tickÂ :</t>
    <t id="9378">Nombre maximum d'expÃ©ditions par tickÂ :</t>
    <t id="9379">Ã‰lÃ©ments Max par Tic :</t>
    <t id="9380">RÃ©veils Max par Tic :</t>
    <t id="9381">EntrÃ©es Max RequÃªte Cache :</t>
    <t id="9382">Seuil DÃ©suet en Secondes :</t>
    <t id="9383">Seuil DÃ©suet File en Secondes :</t>
    <t id="9384">Expiration Ã‰checs Commerce en Secondes :</t>
    <t id="9385">Recherches de Secours SimultanÃ©es Max :</t>
    <t id="9386">Recherches de Secours SimultanÃ©es Max :</t>
    <t id="9470">Seuil doux pour la file d'attente du processeur par lots (5-50). Lorsque la file atteint cette valeur, la contre-pression commence Ã  Ãªtre appliquÃ©e pour ralentir les nouvelles requÃªtes de recherche. Des valeurs plus faibles dÃ©clenchent la contre-pression plus tÃ´t (plus conservateur). Par dÃ©faut : 10.</t>
    <t id="9471">Seuil dur pour la file d'attente du processeur par lots (10-100). Lorsque la file atteint cette valeur, les nouvelles recherches en direct sont bloquÃ©es jusqu'Ã  ce que la file diminue. Des valeurs plus faibles bloquent les recherches plus tÃ´t (plus conservateur). Par dÃ©faut : 25.</t>
    <t id="9472">Secteurs traitÃ©s par tranche dans la collecte d'offres en direct (1-5). Des valeurs plus faibles rÃ©partissent le travail sur plus de frames (plus fluide) mais peuvent ralentir la collecte d'offres. Des valeurs plus Ã©levÃ©es traitent plus rapidement mais peuvent causer des pics de frame. Par dÃ©faut : 1.</t>
    <t id="9473">DÃ©lai aprÃ¨s la fin du rafraÃ®chissement du secteur domicile (10-120 secondes). EmpÃªche les requÃªtes de rafraÃ®chissement excessives. Des valeurs plus faibles permettent des rafraÃ®chissements plus frÃ©quents mais augmentent la charge CPU. Des valeurs plus Ã©levÃ©es rÃ©duisent la frÃ©quence de rafraÃ®chissement mais peuvent retarder les mises Ã  jour du cache. Par dÃ©faut : 30s.</t>
    <t id="9474">DÃ©lai de base aprÃ¨s un Ã©chec de cache avant de rÃ©essayer une recherche en direct (1-30 secondes). EmpÃªche les tentatives de rÃ©essai excessives. Des valeurs plus faibles rÃ©essayent plus tÃ´t mais augmentent la charge CPU. Des valeurs plus Ã©levÃ©es rÃ©duisent la frÃ©quence de rÃ©essai mais peuvent retarder la recherche de commerces. Par dÃ©faut : 10s.</t>
    <t id="9475">Intervalle entre les tics du planificateur en millisecondes (50-500ms). ContrÃ´le la frÃ©quence Ã  laquelle le planificateur traite la file d'attente de travail. Des valeurs plus faibles traitent plus frÃ©quemment mais augmentent la charge CPU. Des valeurs plus Ã©levÃ©es rÃ©duisent la charge CPU mais peuvent augmenter les temps d'attente en file. Par dÃ©faut : 100ms.</t>
    <t id="9476">Nombre maximum de requÃªtes de cache dÃ©marrÃ©es par tic du planificateur (1-5). Limite le taux de requÃªtes de cache pour Ã©viter le blocage des frames. Des valeurs plus faibles rÃ©duisent les pics CPU mais ralentissent les recherches de cache. Des valeurs plus Ã©levÃ©es traitent plus rapidement mais peuvent causer des saccades. Par dÃ©faut : 1.</t>
    <t id="9477">Nombre maximum de poursuites de recherche dÃ©marrÃ©es par tic du planificateur (1-5). Limite le taux de poursuite pour Ã©viter le blocage des frames. Des valeurs plus faibles rÃ©duisent les pics CPU mais ralentissent le traitement de recherche. Des valeurs plus Ã©levÃ©es traitent plus rapidement mais peuvent causer des saccades. Par dÃ©faut : 1.</t>
    <t id="9478">Nombre maximum de vaisseaux traitÃ©s par tic du planificateur (1-5). Limite le taux de traitement des vaisseaux pour Ã©viter le blocage des frames. Des valeurs plus faibles rÃ©duisent les pics CPU mais ralentissent le traitement de la file. Des valeurs plus Ã©levÃ©es traitent plus rapidement mais peuvent causer des saccades. Par dÃ©faut : 1.</t>
    <t id="9479">Nombre maximum d'Ã©lÃ©ments de travail traitÃ©s par tic du planificateur (1-5). Limite le taux de traitement des Ã©lÃ©ments pour Ã©viter le blocage des frames. Des valeurs plus faibles rÃ©duisent les pics CPU mais ralentissent le traitement de la file. Des valeurs plus Ã©levÃ©es traitent plus rapidement mais peuvent causer des saccades. Par dÃ©faut : 1.</t>
    <t id="9480">Nombre maximum d'attentes rÃ©veillÃ©es par tic du planificateur (1-10). Limite le taux de rÃ©veil pour Ã©viter les pics CPU lorsque de nombreuses attentes sont en file. Des valeurs plus faibles rÃ©duisent les pics CPU mais ralentissent le traitement des attentes. Des valeurs plus Ã©levÃ©es traitent plus rapidement mais peuvent causer des saccades. Par dÃ©faut : 2.</t>
    <t id="9481">Nombre maximum d'entrÃ©es de cache interrogÃ©es par lot (1-200). ContrÃ´le la taille du lot de requÃªte de cache. Des valeurs plus faibles rendent les recherches de cache plus rapides mais peuvent manquer de meilleurs commerces. Des valeurs plus Ã©levÃ©es considÃ¨rent plus de commerces en cache mais augmentent le temps de validation. Par dÃ©faut : 50.</t>
    <t id="9482">Seuil de dÃ©suÃ©tude de l'Ã©tat de recherche en direct en secondes (60-600). Lorsque l'Ã©tat de recherche en direct est plus ancien que cette valeur, il est considÃ©rÃ© comme dÃ©suet et effacÃ©. Des valeurs plus faibles effacent l'Ã©tat dÃ©suet plus tÃ´t mais peuvent interrompre des recherches lÃ©gitimes. Des valeurs plus Ã©levÃ©es permettent des recherches plus longues mais peuvent laisser un Ã©tat dÃ©suet. Par dÃ©faut : 300s.</t>
    <t id="9483">Seuil de dÃ©suÃ©tude des Ã©lÃ©ments de file en secondes (30-300). Lorsque les Ã©lÃ©ments de file sont plus anciens que cette valeur, ils sont considÃ©rÃ©s comme dÃ©suets et supprimÃ©s. Des valeurs plus faibles effacent les Ã©lÃ©ments dÃ©suets plus tÃ´t mais peuvent supprimer des Ã©lÃ©ments de file lÃ©gitimes. Des valeurs plus Ã©levÃ©es permettent des temps de file plus longs mais peuvent laisser des Ã©lÃ©ments dÃ©suets. Par dÃ©faut : 60s.</t>
    <t id="9484">Expiration du cache des commerces Ã©chouÃ©s en secondes (300-3600). Les commerces Ã©chouÃ©s sont mis en cache pour Ã©viter de rÃ©essayer immÃ©diatement. Des valeurs plus faibles expirent les commerces Ã©chouÃ©s plus tÃ´t (plus de rÃ©essais) mais rÃ©duisent l'efficacitÃ© du cache. Des valeurs plus Ã©levÃ©es mettent en cache plus longtemps (moins de rÃ©essais) mais peuvent retarder les tentatives de rÃ©essai. Par dÃ©faut : 1800s (30 minutes).</t>
    <t id="9485">Nombre maximum de recherches en direct de secours simultanÃ©es (1-10). Les recherches de secours contournent le verrouillage du secteur domicile, permettant Ã  plusieurs vaisseaux du mÃªme secteur domicile de rechercher simultanÃ©ment. Des valeurs plus faibles rÃ©duisent la charge CPU mais peuvent ralentir les recherches de secours. Des valeurs plus Ã©levÃ©es permettent plus de recherches de secours parallÃ¨les mais augmentent l'utilisation du CPU. Par dÃ©faut : 1.</t>
    <t id="9490">DÃ©lai de signal dÃ©tectÃ© par le commerceÂ :</t>
    <t id="9590">DÃ©lai avant l'envoi du signal GT_Trade_Found aux vaisseaux en millisecondes (10-1000ms). Les vaisseaux attendent toujours (dÃ©lai configurÃ© + tampon de 5ms) avant d'envoyer de nouvelles requÃªtes pour capturer les signaux retardÃ©s. Des valeurs plus Ã©levÃ©es distribuent les signaux sur plusieurs frames pour des performances plus fluides. Par dÃ©faut : 10ms.</t>
    <t id="8000">Flotte GalaxyTrader</t>
    <t id="8001">Gestion de flotte GalaxyTrader et statistiques de pilotes</t>
    <t id="8002">Visualiser et gÃ©rer tous les pilotes GalaxyTrader</t>
    <t id="8100">ID du navire</t>
    <t id="8101">Pilote</t>
    <t id="8102">Bateau</t>
    <t id="8103">Statut</t>
    <t id="8104">Rang</t>
    <t id="8105">Niveau</t>
    <t id="8106">XP</t>
    <t id="8107">BÃ©nÃ©fice Ã  vie</t>
    <t id="8108">Emplacement</t>
    <t id="8109">Base d'OpÃ©rations</t>
    <t id="8110">Dernier Ã©change</t>
    <t id="8111">BÃ©nÃ©fice pilote</t>
    <t id="8112">BÃ©nÃ©fice du navire</t>
    <t id="8113">Nombre d'Ã©changes</t>
    <t id="8200">RafraÃ®chir</t>
    <t id="8201">Exporter au format CSV</t>
    <t id="8202">Statistiques</t>
    <t id="8203">ParamÃ¨tres</t>
    <t id="8204">Aide</t>
    <t id="8205">Fermer</t>
    <t id="8300">Tous les pilotes</t>
    <t id="8301">Commerce</t>
    <t id="8302">EntraÃ®nement</t>
    <t id="8303">Entretien</t>
    <t id="8304">Urgence</t>
    <t id="8305">DÃ©butants (Nv 1-5)</t>
    <t id="8306">AvancÃ©s (Nv 6-11)</t>
    <t id="8307">Experts (Niv 12+)</t>
    <t id="8308">Les 10 meilleurs salariÃ©s</t>
    <t id="8350">Trier par:</t>
    <t id="8351">ID du navire</t>
    <t id="8352">Nom du pilote</t>
    <t id="8353">Type de navire</t>
    <t id="8354">Statut</t>
    <t id="8355">Rang</t>
    <t id="8356">Niveau</t>
    <t id="8357">XP</t>
    <t id="8358">Profit</t>
    <t id="8400">Aucun pilote enregistrÃ©</t>
    <t id="8401">Aucun pilote ne correspond au filtre</t>
    <t id="8402">Nombre total de pilotesÂ :</t>
    <t id="8403">BÃ©nÃ©fice total de la flotteÂ :</t>
    <t id="8404">DerniÃ¨re mise Ã  jour :</t>
    <t id="8405">Rechercher des pilotes...</t>
    <t id="8114">Secteur</t>
    <t id="8320">Renommer le navire</t>
    <t id="8321">Nom PersonnalisÃ©</t>
    <t id="8322">DÃ©finir Nom</t>
    <t id="8323">Effacer le nom</t>
    <t id="8324">Nom dÃ©fini avec succÃ¨s</t>
    <t id="8325">Nom effacÃ© avec succÃ¨s</t>
    <t id="8450">Envoyer en EntraÃ®nement</t>
    <t id="8451">DÃ©senregistrer</t>
    <t id="8452">Forcer la vente de marchandises</t>
    <t id="8453">Envoyer en RÃ©paration</t>
    <t id="8454">Envoyer au rÃ©approvisionnement</t>
    <t id="8455">ArrÃªter Toutes les Ordres</t>
    <t id="8456">Actes</t>
    <t id="8500">Cliquez pour trier par ID de navire</t>
    <t id="8501">Cliquez pour trier par nom de pilote</t>
    <t id="8502">Cliquez pour trier par type de navire</t>
    <t id="8503">Cliquez pour trier par statut</t>
    <t id="8504">Cliquez pour trier par classement</t>
    <t id="8505">Cliquez pour trier par niveau</t>
    <t id="8506">Cliquez pour trier par XP</t>
    <t id="8507">Cliquez pour trier par bÃ©nÃ©fice Ã  vie</t>
    <t id="8508">Actualiser les donnÃ©es de pilote du systÃ¨me de mission</t>
    <t id="8509">Exporter la vue actuelle vers un fichier CSV</t>
    <t id="8510">Afficher les statistiques et les graphiques de la flotte</t>
    <t id="8511">Configurer les paramÃ¨tres du menu</t>
    <t id="8512">Afficher l'aide et les raccourcis clavier</t>
    <t id="8600">Aucun pilote GalaxyTrader trouvÃ©</t>
    <t id="8601">CrÃ©ez des pilotes en assignant des vaisseaux Ã  GalaxyTrader, ou attendez que les donnÃ©es se chargent.</t>
    <t id="9001">GT Renommer</t>
    <t id="9902">Envoyer Ã  la formation</t>
    <t id="9903">Formation manuelle en file d'attente pour %1. Le pilote commencera sa formation aprÃ¨s le cycle en cours.</t>
    <t id="9904">Formation mise en file d'attente aprÃ¨s le cycle en cours</t>
    <t id="9905">Pilote ou navire introuvable</t>
    <t id="9906">L'AutoTraining est activÃ© - la file d'attente manuelle n'est pas requise</t>
    <t id="9907">Le pilote n'est pas bloquÃ© en formation</t>
    <t id="9910">AcadÃ©mie de Commerce</t>
    <t id="9911">Apprenti (Niv 4) - %1 / %2</t>
    <t id="9912">Marchand (Niv 7) - %1 / %2</t>
    <t id="9913">MaÃ®tre Marchand (Niv 13) - %1 / %2</t>
    <t id="9920">Le pilote %1 est inscrit au cours d'AcadÃ©mie pour le Niveau %2. DÃ©part pour la station commerciale la plus proche.</t>
    <t id="9921">Fonds insuffisants pour ce cours (requis : %1, disponibles : %2).</t>
    <t id="9922">Cours indisponible - le pilote %1 est dÃ©jÃ  Ã  ce niveau ou au-dessus.</t>
    <t id="9923">Le pilote %1 s'est inscrit au cours d'AcadÃ©mie Niveau %2 (coÃ»t : %3 Cr, durÃ©e : %4 min) Ã  bord du %5.</t>
    <t id="11011">GT RÃ©ducteur Vaisseau Moyen Apprenti</t>
    <t id="11012">Modification de moteur qui rÃ©duit lÃ©gÃ¨rement les performances pour les pilotes inexpÃ©rimentÃ©s sur les vaisseaux moyens. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -5% vitesse, poussÃ©e et rotation.</t>
    <t id="11013">GT RÃ©ducteur Voyage Moyen Apprenti</t>
    <t id="11014">Modification de moteur qui rÃ©duit lÃ©gÃ¨rement les performances de voyage pour les pilotes inexpÃ©rimentÃ©s sur les vaisseaux moyens. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -5% vitesse de voyage.</t>
    <t id="11021">GT RÃ©ducteur Grand Vaisseau Apprenti</t>
    <t id="11022">Modification de moteur qui rÃ©duit les performances pour les pilotes inexpÃ©rimentÃ©s sur les grands vaisseaux. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -15% vitesse, poussÃ©e et rotation.</t>
    <t id="11023">GT RÃ©ducteur Voyage Grand Vaisseau Apprenti</t>
    <t id="11024">Modification de moteur qui rÃ©duit les performances de voyage pour les pilotes inexpÃ©rimentÃ©s sur les grands vaisseaux. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -15% vitesse de voyage.</t>
    <t id="11031">GT RÃ©ducteur Vaisseau Capital Apprenti</t>
    <t id="11032">Modification de moteur qui rÃ©duit significativement les performances pour les pilotes inexpÃ©rimentÃ©s sur les vaisseaux capitaux. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -25% vitesse, poussÃ©e et rotation.</t>
    <t id="11033">GT RÃ©ducteur Voyage Vaisseau Capital Apprenti</t>
    <t id="11034">Modification de moteur qui rÃ©duit significativement les performances de voyage pour les pilotes inexpÃ©rimentÃ©s sur les vaisseaux capitaux. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -25% vitesse de voyage.</t>
    <t id="12001">GT AmÃ©liorateur Petit Vaisseau Basique</t>
    <t id="12002">Modification de moteur spÃ©cialisÃ©e pour les petits vaisseaux avec des pilotes certifiÃ©s basiques. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +3% vitesse, poussÃ©e et rotation.</t>
    <t id="12003">GT AmÃ©liorateur Voyage Petit Vaisseau Basique</t>
    <t id="12004">Modification de moteur spÃ©cialisÃ©e pour les petits vaisseaux avec des pilotes certifiÃ©s basiques. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +3% vitesse de voyage.</t>
    <t id="13001">GT RÃ©ducteur Grand Vaisseau Basique</t>
    <t id="13002">Modification de moteur spÃ©cialisÃ©e pour les grands vaisseaux avec des pilotes certifiÃ©s basiques. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -8% vitesse, poussÃ©e et rotation.</t>
    <t id="13003">GT RÃ©ducteur Voyage Grand Vaisseau Basique</t>
    <t id="13004">Modification de moteur spÃ©cialisÃ©e pour les grands vaisseaux avec des pilotes certifiÃ©s basiques. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -8% vitesse de voyage.</t>
    <t id="14001">GT RÃ©ducteur Vaisseau Capital Basique</t>
    <t id="14002">Modification de moteur spÃ©cialisÃ©e pour les vaisseaux capitaux avec des pilotes certifiÃ©s basiques. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -15% vitesse, poussÃ©e et rotation.</t>
    <t id="14003">GT RÃ©ducteur Voyage Vaisseau Capital Basique</t>
    <t id="14004">Modification de moteur spÃ©cialisÃ©e pour les vaisseaux capitaux avec des pilotes certifiÃ©s basiques. UtilisÃ© par le systÃ¨me AI GalaxyTrader. -15% vitesse de voyage.</t>
    <t id="15001">GT AmÃ©liorateur Petit Vaisseau Expert</t>
    <t id="15002">Modification de moteur avancÃ©e pour les petits vaisseaux avec des pilotes experts. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +25% vitesse, poussÃ©e et rotation.</t>
    <t id="15003">GT AmÃ©liorateur Voyage Petit Vaisseau Expert</t>
    <t id="15004">Modification de moteur avancÃ©e pour les petits vaisseaux avec des pilotes experts. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +25% vitesse de voyage.</t>
    <t id="16001">GT AmÃ©liorateur Grand Vaisseau Expert</t>
    <t id="16002">Modification de moteur avancÃ©e pour les grands vaisseaux avec des pilotes experts. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +15% vitesse, poussÃ©e et rotation.</t>
    <t id="16003">GT AmÃ©liorateur Voyage Grand Vaisseau Expert</t>
    <t id="16004">Modification de moteur avancÃ©e pour les grands vaisseaux avec des pilotes experts. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +15% vitesse de voyage.</t>
    <t id="17001">GT AmÃ©liorateur Vaisseau Capital Expert</t>
    <t id="17002">Modification de moteur avancÃ©e pour les vaisseaux capitaux avec des pilotes experts. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +6% vitesse, poussÃ©e et rotation.</t>
    <t id="17003">GT AmÃ©liorateur Voyage Vaisseau Capital Expert</t>
    <t id="17004">Modification de moteur avancÃ©e pour les vaisseaux capitaux avec des pilotes experts. UtilisÃ© par le systÃ¨me AI GalaxyTrader. +6% vitesse de voyage.</t>
    <t id="18001">Limitation SÃ©vÃ¨re de CompÃ©tences (Vaisseau)</t>
    <t id="18002">Limitation SÃ©vÃ¨re de CompÃ©tences (Vaisseau) - ReprÃ©sente des pÃ©nalitÃ©s de performance sÃ©vÃ¨res dues Ã  l'inexpÃ©rience du pilote avec les grands vaisseaux. AppliquÃ©e automatiquement par le systÃ¨me GalaxyTrader lorsque la compÃ©tence du pilote est insuffisante pour la taille du vaisseau. Augmente la masse du vaisseau. (SystÃ¨me GT uniquement - Non disponible pour installation manuelle)</t>
    <t id="18003">Limitation ModÃ©rÃ©e de CompÃ©tences (Vaisseau)</t>
    <t id="18004">Limitation ModÃ©rÃ©e de CompÃ©tences (Vaisseau) - ReprÃ©sente des pÃ©nalitÃ©s de performance modÃ©rÃ©es pendant l'adaptation du pilote Ã  la complexitÃ© du vaisseau. AppliquÃ©e automatiquement par le systÃ¨me GalaxyTrader lorsque la compÃ©tence du pilote est insuffisante pour la taille du vaisseau. Augmente la masse du vaisseau. (SystÃ¨me GT uniquement - Non disponible pour installation manuelle)</t>
    <t id="18005">Limitation LÃ©gÃ¨re de CompÃ©tences (Vaisseau)</t>
    <t id="18006">Limitation LÃ©gÃ¨re de CompÃ©tences (Vaisseau) - ReprÃ©sente des pÃ©nalitÃ©s de performance mineures pendant le dÃ©veloppement des compÃ©tences du pilote. AppliquÃ©e automatiquement par le systÃ¨me GalaxyTrader lorsque la compÃ©tence du pilote est insuffisante pour la taille du vaisseau. Augmente la masse du vaisseau. (SystÃ¨me GT uniquement - Non disponible pour installation manuelle)</t>
    <t id="18007">Limitation SÃ©vÃ¨re de CompÃ©tences (Moteur)</t>
    <t id="18008">Limitation SÃ©vÃ¨re de CompÃ©tences (Moteur) - ReprÃ©sente des pÃ©nalitÃ©s de performance sÃ©vÃ¨res dues Ã  l'inexpÃ©rience du pilote avec les grands vaisseaux. AppliquÃ©e automatiquement par le systÃ¨me GalaxyTrader lorsque la compÃ©tence du pilote est insuffisante pour la taille du vaisseau. RÃ©duit la poussÃ©e et la rotation du moteur. (SystÃ¨me GT uniquement - Non disponible pour installation manuelle)</t>
    <t id="18009">Limitation ModÃ©rÃ©e de CompÃ©tences (Moteur)</t>
    <t id="18010">Limitation ModÃ©rÃ©e de CompÃ©tences (Moteur) - ReprÃ©sente des pÃ©nalitÃ©s de performance modÃ©rÃ©es pendant l'adaptation du pilote Ã  la complexitÃ© du vaisseau. AppliquÃ©e automatiquement par le systÃ¨me GalaxyTrader lorsque la compÃ©tence du pilote est insuffisante pour la taille du vaisseau. RÃ©duit la poussÃ©e et la rotation du moteur. (SystÃ¨me GT uniquement - Non disponible pour installation manuelle)</t>
    <t id="18011">Limitation LÃ©gÃ¨re de CompÃ©tences (Moteur)</t>
    <t id="18012">Limitation LÃ©gÃ¨re de CompÃ©tences (Moteur) - ReprÃ©sente des pÃ©nalitÃ©s de performance mineures pendant le dÃ©veloppement des compÃ©tences du pilote. AppliquÃ©e automatiquement par le systÃ¨me GalaxyTrader lorsque la compÃ©tence du pilote est insuffisante pour la taille du vaisseau. RÃ©duit la poussÃ©e et la rotation du moteur. (SystÃ¨me GT uniquement - Non disponible pour installation manuelle)</t>
    <t id="9250">DÃ©nomination de l'Ã‰tat du Vaisseau</t>
    <t id="9350">Personnaliser les abrÃ©viations d'Ã©tat du vaisseau. Les valeurs par dÃ©faut sont affichÃ©es dans les champs de saisie et peuvent Ãªtre remplacÃ©es. Maximum 3 caractÃ¨res. Tous les noms de vaisseaux seront automatiquement mis Ã  jour lors des modifications.</t>
    <t id="9251">AbrÃ©viation Ã‰tat RÃ©approvisionnement:</t>
    <t id="9252">AbrÃ©viation Ã‰tat RÃ©paration:</t>
    <t id="9253">AbrÃ©viation Ã‰tat Maintenance:</t>
    <t id="9254">AbrÃ©viation Ã‰tat Formation:</t>
    <t id="9255">AbrÃ©viation Ã‰tat RÃ©acheminement:</t>
    <t id="9256">AbrÃ©viation Ã‰tat Autorisation:</t>
    <t id="9257">AbrÃ©viation Ã‰tat BloquÃ©:</t>
    <t id="9258">AbrÃ©viation Ã‰tat Fallback:</t>
    <t id="9259">AbrÃ©viation Ã‰tat IsolÃ©:</t>
    <t id="9260">AbrÃ©viation Ã‰tat Commerce:</t>
    <t id="9261">AbrÃ©viation Ã‰tat Inactif:</t>
    <t id="9262">AbrÃ©viation Ã‰tat Ã‰vasion:</t>
    <t id="9268">AbrÃ©viation de l'Ã©tat inaccessibleÂ :</t>
    <t id="9269">AbrÃ©viation de lâ€™Ã©tat dâ€™Ã©change piloteÂ :</t>
    <t id="9270">Balise de prÃ©fixe de liste noire personnalisÃ©eÂ :</t>
    <t id="9700">TRICHES (casse. rien a voir ici!! vraiment!!)</t>
    <t id="9701">Vaisseaux GT invulnerables</t>
    <t id="9702">Tous les vaisseaux du joueur invulnerables</t>
    <t id="9800">Circulez, pilote. Outils de test developpeur casses, pas un menu amusant. Rien a voir ici. Vraiment. Vous avez ete averti. Probablement.</t>
    <t id="9801">Les vaisseaux sous ordre GalaxyTrader ne peuvent pas descendre sous 100% de coque ou de boucliers. Cliquez a nouveau pour desactiver.</t>
    <t id="9802">Tous les vaisseaux du joueur ne peuvent pas descendre sous 100% de coque ou de boucliers. Cliquez a nouveau pour desactiver. Les stations ne sont pas affectees.</t>
    <t id="9703">Reveler l univers pour tests GT</t>
    <t id="9704">Revele</t>
    <t id="9705">Reveler</t>
    <t id="9803">Revele le brouillard de guerre de tous les secteurs, marque toutes les stations comme connues, accorde toutes les licences d abonnement commercial et abonne les offres commerciales dans toute la galaxie. Cliquez a nouveau apres de nouveaux secteurs DLC. Pour les tests uniquement.</t>
    <t id="9706">Maximiser l XP des pilotes GT enregistres</t>
    <t id="9707">Maximise</t>
    <t id="9708">XP max</t>
    <t id="9804">Passe au niveau 15 et XP max pour chaque pilote du registre GT. Supprime les blocages d entrainement. Ignore si XP vanilla seulement est actif. Pour les tests uniquement.</t>
    <t id="9351">AbrÃ©viation pour l'Ã©tat RÃ©approvisionnement (par dÃ©faut: RS)</t>
    <t id="9352">AbrÃ©viation pour l'Ã©tat RÃ©paration (par dÃ©faut: RP)</t>
    <t id="9353">AbrÃ©viation pour l'Ã©tat Maintenance (par dÃ©faut: MT)</t>
    <t id="9354">AbrÃ©viation pour l'Ã©tat Formation (par dÃ©faut: TR)</t>
    <t id="9355">AbrÃ©viation pour l'Ã©tat RÃ©acheminement (par dÃ©faut: RR)</t>
    <t id="9356">AbrÃ©viation pour l'Ã©tat Autorisation (par dÃ©faut: CL)</t>
    <t id="9357">AbrÃ©viation pour l'Ã©tat BloquÃ© (par dÃ©faut: BL)</t>
    <t id="9358">AbrÃ©viation pour l'Ã©tat Fallback (par dÃ©faut: FB)</t>
    <t id="9359">AbrÃ©viation pour l'Ã©tat IsolÃ© (par dÃ©faut: IS)</t>
    <t id="9360">AbrÃ©viation pour l'Ã©tat Commerce (par dÃ©faut: TD)</t>
    <t id="9361">AbrÃ©viation pour l'Ã©tat Inactif (par dÃ©faut: ID)</t>
    <t id="9362">AbrÃ©viation pour l'Ã©tat Ã‰vasion (par dÃ©faut: ES)</t>
    <t id="9367">AbrÃ©viation de Ã‰tat inaccessible (par dÃ©fautÂ : UR)</t>
    <t id="9368">AbrÃ©viation de Pilot Exchange state (par dÃ©fautÂ :Â PE)</t>
    <t id="9369">AffichÃ© comme prÃ©fixe pour les vaisseaux MK3 affectÃ©s par une liste noire de faction personnalisÃ©e (y compris les subordonnÃ©s). Par dÃ©fautÂ :Â CB</t>
    <t id="30002">Galaxy Trader MK1</t>
    <t id="30102">CommerÃ§ant de station - vend des produits de station aux factions de PNJ</t>
    <t id="30010">Station d'accueil</t>
    <t id="30011">Distance de vente maximale</t>
    <t id="30012">Ignorer les rÃ¨gles commerciales</t>
    <t id="30013">Filtre d'articles</t>
    <t id="30014">% cible de remplissage du fret de vente</t>
    <t id="30015">TolÃ©rance de retour en arriÃ¨re</t>
    <t id="30016">Acheter le % dâ€™objectif de remplissage de la cargaison</t>
    <t id="30017">EntrÃ©es du journal de bord</t>
    <t id="30018">Niveau de notification</t>
    <t id="30019">Coordination de la flotte</t>
    <t id="30020">Niveau de dÃ©bogage</t>
    <t id="30021">Station de ravitaillement</t>
    <t id="30022">% de stockage minimum de la station</t>
    <t id="30023">Autoriser les marchandises illÃ©gales</t>
    <t id="30024">Cargaison/BÃ©nÃ©fice</t>
    <t id="30025">Autoriser le multi-Ã©change</t>
    <t id="30110">Station de joueur Ã  partir de laquelle vendre des marchandises (affectation de station requise)</t>
    <t id="30111">Distance maximale de porte pour trouver des acheteurs de PNJ (limitÃ©e par la compÃ©tence du pilote)</t>
    <t id="30112">Ignorez les restrictions commerciales de la station - vendez Ã  n'importe quelle faction amie, quelles que soient les rÃ¨gles commerciales de la station.</t>
    <t id="30113">Filtre d'articles en optionÂ ; laisser vide pour vendre tous les produits et articles de la station</t>
    <t id="30114">Pourcentage minimum de remplissage du fret avant de partir en voyage de vente</t>
    <t id="30115">Nombre maximum de sauts supplÃ©mentaires autorisÃ©s lors de l'ajout d'un deuxiÃ¨me article Ã  un voyage (0 = uniquement les acheteurs directement sur l'itinÃ©raire)</t>
    <t id="30116">Cibler le remplissage des marchandises pour les courses de ravitaillement (cible souple, le commerÃ§ant peut partir plus tÃ´t)</t>
    <t id="30117">Activer les entrÃ©es du journal de bord par transaction</t>
    <t id="30118">Niveau de notification : 0=Silencieux, 1=Normal, 2=Verbeux</t>
    <t id="30119">Activer la coordination de la flotte et le systÃ¨me de rÃ©servation commerciale</t>
    <t id="30120">Niveau de journalisation du dÃ©bogageÂ : 0=DÃ©sactivÃ©, 1=Normal, 2=Verbeux</t>
    <t id="30121">Lorsqu'il est activÃ©, achetez Ã©galement des ressources pour la station. Lâ€™approvisionnement est prioritaire lorsque le stockage descend en dessous du seuil minimum</t>
    <t id="30122">Lorsqu'une ressource tombe en dessous de ce pourcentage de son objectif, l'offre est prioritaire sur la vente. IgnorÃ© si la station ne peut pas se permettre des ressources</t>
    <t id="30123">Autoriser la vente ou l'achat de marchandises illÃ©gales/de contrebande lorsqu'elles sont disponibles</t>
    <t id="30124">SÃ©lection des ventes : 1 = Cargaison (prioritÃ© au remplissage le plus Ã©levÃ© pour la marchandise ; Ã©galitÃ© selon le bÃ©nÃ©fice), 2 = BÃ©nÃ©fice (meilleur score de bÃ©nÃ©fice)</t>
    <t id="30125">Permet d'enchaÃ®ner plusieurs ventes dans un cycle (jusqu'Ã  3 marchandises ou destinations). DÃ©sactiver pour n'exÃ©cuter qu'un seul Ã©change par cycle</t>
    <t id="30200">Vente de %1 %2 du %3 au %4</t>
    <t id="30201">Aucun acheteur trouvÃ© pour les produits de la station dans les %1 sauts</t>
    <t id="30202">Station d'attache %1 dÃ©truite - commande de commerÃ§ant de station annulÃ©e</t>
    <t id="30203">La station d'accueil %1 n'appartient plus au joueurÂ -Â commande annulÃ©e</t>
    <t id="30204">Affectation de station requise - commande annulÃ©e</t>
    <t id="30205">MK1 Station Trader a dÃ©marrÃ© Ã  %1</t>
    <t id="30206">Vente finalisÃ©eÂ : %1 %2 vendu Ã  %3 pour %4 Cr (bÃ©nÃ©ficeÂ : %5 Cr)</t>
    <t id="30207">Voyage multi-articlesÂ : livraison de %1 marchandises vers %2 destinations</t>
    <t id="30208">Fournir %1 %2 Ã  %3 Ã  partir de %4</t>
    <t id="30500">ParamÃ¨tres du GalaxyTrader MK1</t>
    <t id="30501">ParamÃ¨tres par dÃ©faut du commerÃ§ant de station</t>
    <t id="30502">Distance de vente maximale par dÃ©faut</t>
    <t id="30503">Objectif de remplissage du fret de vente par dÃ©faut</t>
    <t id="30504">Par dÃ©faut, ignorer les rÃ¨gles commerciales</t>
    <t id="30505">TolÃ©rance de retour en arriÃ¨re par dÃ©faut</t>
    <t id="30506">Temps d'attente lorsqu'aucune transaction n'est trouvÃ©e</t>
    <t id="30507">Cible de remplissage de fret d'achat par dÃ©faut</t>
    <t id="31002">Mineur de Galaxie</t>
    <t id="31102">Exploitation miniÃ¨re autonome avec ravitaillement en station et progression XP</t>
    <t id="31010">Station d'accueil</t>
    <t id="31110">Station Ã  exploiter et Ã  livrer (mutuellement exclusive avec le secteur domestique)</t>
    <t id="31011">Secteur Accueil</t>
    <t id="31111">Secteur dans lequel opÃ©rerÂ ; utilisÃ© lorsqu'aucune station d'accueil n'est dÃ©finie</t>
    <t id="31012">Panier de ressources</t>
    <t id="31112">Marchandises Ã  moiÂ ; vide suit la rÃ©solution de la demande de la station</t>
    <t id="31013">Stations cibles</t>
    <t id="31113">Filtre de station en option pour les livraisonsÂ ; vide dÃ©rive du contexte domestique</t>
    <t id="31014">Seuil de dÃ©bordement %</t>
    <t id="31114">Les stations Ã©gales ou supÃ©rieures Ã  ce pourcentage de stockage sont traitÃ©es comme pleines</t>
    <t id="31015">Autoriser le dÃ©bordement Vendre Ã  d'autres</t>
    <t id="31115">Lorsque cette option est activÃ©e et que les cibles principales sont pleines, vendez-les Ã  d'autres stations de faction.</t>
    <t id="31016">Attribuer Ã  la station</t>
    <t id="31116">DÃ©signer le navire comme subordonnÃ© minier de la station d'accueil, le cas Ã©chÃ©ant</t>
    <t id="31017">Restez Ã  la maison</t>
    <t id="31117">Restreindre l'exploitation miniÃ¨re/la vente Ã  la zone d'origine, sauf les opÃ©rations de secours en cas de dÃ©bordement</t>
    <t id="31018">Sondes de ressources Ã  dÃ©ploiement automatique</t>
    <t id="31118">DÃ©ployez automatiquement les sondes de ressources chargÃ©es et incluez les sondes dans le rÃ©approvisionnement de maintenance</t>
    <t id="31019">Distance de collecte maximale</t>
    <t id="31119">Distance maximale de la porte pour le rassemblement (0 utilise le plafond de compÃ©tences du pilote/commandant)</t>
    <t id="31020">Distance de vente maximale</t>
    <t id="31120">Distance maximale de la porte pour la vente (0 utilise le plafond de compÃ©tences du pilote/commandant)</t>
    <t id="31021">Ã‰quilibrage de la flotte</t>
    <t id="31121">Permettre une coordination dÃ©terministe des intentions pour rÃ©duire le dÃ©bordement des stations</t>
    <t id="31022">Intervalle de revÃ©rification de la demande</t>
    <t id="31122">Ã€ quelle frÃ©quence lâ€™Ã©valuation de la demande/du changement des mineurs est exÃ©cutÃ©e</t>
    <t id="31023">Delta de demande critique</t>
    <t id="31123">Delta d'urgence minimum requis pour changer de logiciel d'exploitation miniÃ¨re actif</t>
    <t id="31024">Temps de recharge minimum du commutateur</t>
    <t id="31124">DÃ©lai minimum entre deux changements de matÃ©riel pour ce vaisseau</t>
    <t id="31025">% d'engagement de fret minimum</t>
    <t id="31125">Si le remplissage de la cargaison est supÃ©rieur Ã  ce chiffre, le navire prÃ©fÃ¨re terminer la livraison en cours avant le changement.</t>
    <t id="31026">Delta d'urgence difficile</t>
    <t id="31126">Delta d'urgence qui permet un changement immÃ©diat malgrÃ© le seuil d'engagement de fret</t>
    <t id="31027">Niveau de notification</t>
    <t id="31127">Niveau de notification : 0=Silencieux, 1=Normal, 2=Verbeux</t>
    <t id="31028">Stations de joueurs uniquement</t>
    <t id="31128">Lorsqu'elle est activÃ©e, seules les stations appartenant aux joueurs sont considÃ©rÃ©es comme des cibles de demande.</t>
    <t id="31031">VÃ©rifier la demande d'abord</t>
    <t id="31131">Si activÃ©, le mineur vÃ©rifie la demande des stations avant d'extraire et priorise les marchandises en consÃ©quence. Si dÃ©sactivÃ©, il extrait depuis le panier de ressources sans contrÃ´le de demande et stocke jusqu'Ã  ce qu'un acheteur soit disponible (recommandÃ© pour les flottes mono-ressource).</t>
    <t id="31032">ArrÃªt stockage physique %</t>
    <t id="31132">Pour pilotes niveau 6+ : arrÃªte l'extraction de la marchandise actuelle lorsque le stock physique de la station plus la cargaison des mineurs concernÃ©s dÃ©passerait le stock physique actuel de ce pourcentage. Utilise les quantitÃ©s rÃ©elles en cargaison, pas le seuil de dÃ©bordement. 0 = dÃ©sactivÃ©.</t>
    <t id="32002">GalaxyTrader Alimentation MK4</t>
    <t id="32102">NÃ©gociant de fournitures de station de joueur utilisant le pipeline de cache/recherche en direct GT</t>
    <t id="32010">Distance de couverture</t>
    <t id="32110">Distance maximale du portail par rapport au domicile pour la recherche de demande de destination</t>
    <t id="32011">Acheter Ã  distance</t>
    <t id="32111">Distance maximale du portail par rapport au domicile pour la recherche de fournisseurs</t>
    <t id="32012">Servir Ã  la maison seulement</t>
    <t id="32112">Lorsqu'elle est activÃ©e, seule la demande de la station d'accueil est satisfaite</t>
    <t id="32013">Construire des stations uniquement</t>
    <t id="32113">Lorsqu'elle est activÃ©e, seule la demande de stockage de build est satisfaite</t>
    <t id="32014">Acheter auprÃ¨s du joueur</t>
    <t id="32114">Autoriser l'approvisionnement en marchandises auprÃ¨s de fournisseurs appartenant aux joueurs</t>
    <t id="32015">Acheter chez Faction</t>
    <t id="32115">Autoriser l'approvisionnement en marchandises auprÃ¨s de fournisseurs de factions non-joueurs</t>
    <t id="32016">Autoriser les ressources</t>
    <t id="32116">Inclure les ressources dans la correspondance avec la demande</t>
    <t id="32017">Autoriser les intermÃ©diaires</t>
    <t id="32117">Inclure les produits intermÃ©diaires dans la correspondance de la demande</t>
    <t id="32018">Autoriser les produits</t>
    <t id="32118">Inclure les produits dans la correspondance de la demande</t>
    <t id="32019">Autoriser les logiciels commerciaux</t>
    <t id="32119">Inclure les produits commerciaux dans la correspondance de la demande</t>
    <t id="20002">Galaxy Trader MK2</t>
    <t id="20102">Distribution en entrepÃ´t avec gestion des seuils de stockage</t>
    <t id="20010">Stations sources</t>
    <t id="20011">Gares de destination</t>
    <t id="20012">% de stockage minimum</t>
    <t id="20013">% de stockage statique</t>
    <t id="20014">% de stockage maximum</t>
    <t id="20015">Filtre d'articles</t>
    <t id="20016">Mode bidirectionnel</t>
    <t id="20017">Station d'accueil (en option)</t>
    <t id="20018">Distance maximale</t>
    <t id="20032">Secteur d'accueil (en option)</t>
    <t id="20019">Temps d'attente du cycle</t>
    <t id="20030">Autoriser un faible volume</t>
    <t id="20031">% de plancher Ã  faible volume</t>
    <t id="20110">Liste des stations sources Ã  partir desquelles distribuer les marchandises</t>
    <t id="20111">Liste des gares/entrepÃ´ts de destination vers lesquels distribuer les marchandises</t>
    <t id="20112">Seuil d'urgence de destination : les stations en dessous de ce % de stockage reÃ§oivent des livraisons prioritaires</t>
    <t id="20113">Seuil minimum de la sourceÂ : la source doit avoir plus que ce % pour pouvoir Ãªtre distribuÃ©e</t>
    <t id="20114">Seuil de dÃ©bordement de la sourceÂ : au-dessus de ce %, la source distribue mÃªme vers des destinations non urgentes</t>
    <t id="20115">Filtre d'articles en optionÂ ; laisser vide pour distribuer toutes les marchandises depuis la source</t>
    <t id="20116">Activer la collecte aller-retour des destinations vers la source lorsque les destinations ont un excÃ©dent</t>
    <t id="20117">Station d'appartement en option pour l'affectation. S'il est vide, le navire reste non affectÃ© aux stations.</t>
    <t id="20118">Distance de porte maximale entre la source et les destinations (0 = illimitÃ©)</t>
    <t id="20132">Secteur d'accueil optionnel utilisÃ© pour le stationnement en attente lorsqu'aucune station d'accueil n'est dÃ©finie.</t>
    <t id="20119">Temps d'attente entre les cycles de distribution</t>
    <t id="20130">Autorisez des livraisons plus petites, en fonction de l'urgence, en dessous du remplissage minimum normal de la cargaison.</t>
    <t id="20131">% de remplissage minimum de la cargaison utilisÃ© lorsque le mode faible volume est activÃ©.</t>
    <t id="20200">Distribuer %1 %2 du %3 au %4</t>
    <t id="20201">Aller-retourÂ : collecte %1 %2 du %3 au %4</t>
    <t id="20202">Aucune distribution necessaire - toutes les destinations sont suffisamment approvisionnees</t>
    <t id="20203">Toutes les stations source sont invalides - distribution en attente</t>
    <t id="20204">Toutes les stations de destination sont invalides - distribution en attente</t>
    <t id="20205">Station source %1 detruite - retiree de l'ordre de distribution</t>
    <t id="20206">Station de destination %1 detruite - retiree de l'ordre de distribution</t>
    <t id="20500">GalaxyTrader MK2 - ParamÃ¨tres globaux</t>
    <t id="20501">ParamÃ¨tres par dÃ©faut de la distribution MK2</t>
    <t id="20510">% de stockage minimum par dÃ©faut</t>
    <t id="20511">% de stockage statique par dÃ©faut</t>
    <t id="20512">% de stockage maximum par dÃ©faut</t>
    <t id="20513">Attente(s) de cycle par dÃ©faut</t>
    <t id="20514">% de remplissage minimum de la cargaison</t>
    <t id="20520">VerbositÃ© des notifications</t>
    <t id="20521">Niveau de dÃ©bogage</t>
    <t id="10006">Retour Ã  la maison</t>
    <t id="10007">GalaxyTrader Alimentation MK4-2</t>
    <t id="10106">Amarrez-vous Ã  la station d'attache et restez-y jusqu'Ã  la reprise des Ã©changes.</t>
    <t id="10107">Ordre d'approvisionnement joueur avec curseurs de prioritÃ© des cibles de livraison</t>
    <t id="30026">Retour Ã  la maison entre les cycles</t>
    <t id="30028">Ignorer les paramÃ¨tres d'offres</t>
    <t id="30029">Fourchette de prix acheteur</t>
    <t id="30027">% stockage produit min.</t>
    <t id="30126">Lorsqu'il est activÃ©, retournez Ã  la station d'accueil et accoster entre les cycles d'Ã©change. Lorsqu'il est dÃ©sactivÃ©, continuez la recherche Ã  partir de l'emplacement actuel (ancien comportement)</t>
    <t id="30128">Autoriser les transferts de stockage internes sans offres d'achat/vente de station. Utilise l'Ã©change de marchandises pour la collecte et la livraison des stocks tampons. Les rÃ¨gles commerciales de la station s'appliquent tant que Ignorer les rÃ¨gles commerciales est dÃ©sactivÃ©.</t>
    <t id="30129">Prix relatif minimum pour les acheteurs NPC lors de la vente de produits de station. Curseur d'ordre 0-200 (100 = moyenne, 0 = -100%, 200 = +100%), mappÃ© sur -1,0 Ã  +1,0. Plus Ã©levÃ© = uniquement des acheteurs chers. Plus bas = plus d'options d'acheteurs. Les courses d'approvisionnement utilisent la valeur inverse pour les plafonds de prix fournisseurs.</t>
    <t id="30127">Pourcentage minimum de remplissage du stockage de la station (par rapport au maximum configurÃ© par marchandise) requis avant de vendre un produit ou une marchandise. Les marchandises en dessous de ce seuil sont ignorÃ©es. 0 = aucun minimum.</t>
    <t id="3107">File d'attente multitradeÂ : %1. Je devrais gagner %2 de bÃ©nÃ©fice.</t>
    <t id="3108">Vente de %1 %2 depuis %3 au prix de %4. Je devrais gagner %5 de bÃ©nÃ©fice.</t>
    <t id="3110">Mise en file d'approvisionnement pour %1 %2. Approvisionnement Ã  %3 depuis %4, livraison vers %5. Plafond d'achat client %6 - %7/unitÃ© sous le plafond (%8 au total).</t>
    <t id="3111">Mise en file d'approvisionnement pour %1 %2 de %3 vers %4.</t>
    <t id="3112">Approvisionnement en file (%1 Ã©tapes) : %2. Total %3 sous le plafond d'achat client.</t>
    <t id="3113">CommerÃ§ant de station : export multitrade en file : %1. Profit attendu %2.</t>
    <t id="31029">Cible de stock de sonde</t>
    <t id="31030">Drones de minage Ã  acheter</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner : aucune ressource minable disponible. Vaisseau %1 [%2], Flotte : %3</t>
    <t id="31201">Galaxy-Miner : dÃ©finir la station d'accueil ou la position d'accueil.</t>
    <t id="31130">Nombre de drones collecteurs (de minage) que le mineur achÃ¨te lorsqu'il n'a plus le type requis (solide/minerai ou liquide/gaz). L'achat est dÃ©clenchÃ© UNIQUEMENT lorsque le navire n'a aucun collecteur de ce type - un mineur qui en possÃ¨de encore au moins un n'est jamais rÃ©approvisionnÃ© ni rachetÃ©, les drones existants sont conservÃ©s. PlafonnÃ© par la capacitÃ© de la baie d'unitÃ©s du navire. Mettez Ã  0 pour dÃ©sactiver l'achat automatique de drones collecteurs et gÃ©rer les drones manuellement. La valeur par dÃ©faut 5 correspond Ã  un jeu complet de drones pour une vitesse de minage normale.</t>
    <t id="31129">Nombre de sondes de ressources que le mineur achÃ¨te par voyage de rÃ©approvisionnement. L'achat est dÃ©clenchÃ© UNIQUEMENT lorsque le navire est Ã  court de sondes (nombre = 0), et non Ã  chaque dÃ©ploiement. De cette faÃ§on, le mineur exÃ©cute toute sa charge de sondes entre les courses d'approvisionnement au lieu de faire un dÃ©tour aprÃ¨s chaque dÃ©ploiement. PlafonnÃ© par la capacitÃ© dÃ©ployable totale du navire (partagÃ©e avec les satellites/mines/etc) ; une valeur de curseur supÃ©rieure Ã  l'espace dÃ©ployable libre se dÃ©grade gracieusement pour "remplir ce qui convient". Ne prend effet que lorsque le dÃ©ploiement automatique des sondes de ressources est activÃ©Â : le mÃªme paramÃ¨tre entraÃ®ne Ã©galement le dÃ©ploiement opportuniste de sondes dans les secteurs miniers et la collecte de sondes obsolÃ¨tes (sondes dans des secteurs sans ressources pertinentes pour le panier).</t>
    <t id="3226">Commandant %1,\n\nJe suis amarrÃ© Ã  %2 et le registraire de la Trading Academy a confirmÃ© mon inscription au programme "%3". Le compte de la flotte a Ã©tÃ© dÃ©bitÃ© de %4 Cr pour les frais de scolaritÃ©, et je ne prends pas cet investissement Ã  la lÃ©gÃ¨re.\n\nIl ne s'agit pas d'une certification de routine. Les instructeurs de l'acadÃ©mie sont des marchands chevronnÃ©s et des nÃ©gociateurs de consortium, et le programme ici est bien plus exigeant que l'examen d'avancement standard. Au cours des %5 prochaines minutes, je suivrai un enseignement intensif sur les protocoles de trading avancÃ©s, l'analyse de marchÃ© sous pression et les tactiques de nÃ©gociation qui sÃ©parent les apprentis des maÃ®tres.\n\nLorsque l'examen final sera terminÃ© et que je me dÃ©tacherai, je dÃ©tiendrai le titre de "%3" et je rapporterai tout ce que j'ai appris Ã  nos opÃ©rations de trading. Je ne gaspillerai pas un seul crÃ©dit de cette opportunitÃ©.\n\nAvec gratitude et dÃ©termination,\n%6\nÃ€ bord du %7</t>
    <t id="9924">Cours de la Trading Academy abandonnÃ©Â : le pilote %1 ne peut pas payer les frais de %2 Cr au quai de l'acadÃ©mie (avoir %3 Cr). Cours annulÃ©, le pilote reprend les Ã©changes.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="34">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Atracar y esperar (GalaxyTrader MK3)</t>
    <t id="10002">Galaxy Trader MK3</t>
    <t id="10003">Examen final (GalaxyTrader MK3)</t>
    <t id="10004">Encuentro de intercambio piloto</t>
    <t id="10005">[OBSOLETO] GalaxyTrader Suministro MK4 (Heredado)</t>
    <t id="10101">Atracar en la estaciÃ³n y esperar la duraciÃ³n especificada</t>
    <t id="10102">Comercio autÃ³nomo con progresiÃ³n de habilidades</t>
    <t id="10103">Realizar examen final para certificaciÃ³n de piloto en instalaciÃ³n de entrenamiento</t>
    <t id="10104">Atraque en la estaciÃ³n de encuentro para intercambio de pilotos.</t>
    <t id="10105">Comercio centrado en el suministro para estaciones de jugadores mediante cachÃ© y bÃºsqueda en vivo (Heredado)</t>
    <t id="10201">Compre %s de %s</t>
    <t id="10202">Vender %s a %s</t>
    <t id="10203">Comerciar con %s</t>
    <t id="1000">Galaxy Trader MK3</t>
    <t id="1001">Sistema avanzado de comercio con progresiÃ³n XP y coordinaciÃ³n de flota</t>
    <t id="1002">Base de operaciones</t>
    <t id="1003">Usar ajustes preestablecidos</t>
    <t id="1004">Comerciar todas las mercancÃ­as</t>
    <t id="1005">Comerciar mercancÃ­as legales</t>
    <t id="1006">Comerciar mercancÃ­as ilegales</t>
    <t id="1007">Activar progresiÃ³n XP</t>
    <t id="1008">Activar coordinaciÃ³n de flota</t>
    <t id="1009">Activar anÃ¡lisis de mercado</t>
    <t id="1010">Activar gestiÃ³n de territorio</t>
    <t id="1011">Permitir MercancÃ­as Ilegales</t>
    <t id="1012">Entradas en el Diario de NavegaciÃ³n</t>
    <t id="1013">Tolerancia al riesgo</t>
    <t id="1014">Priorizar estaciones de jugadores</t>
    <t id="1015">MercancÃ­as AutomÃ¡ticas</t>
    <t id="1016">PenalizaciÃ³n de Distancia %</t>
    <t id="1017">Nivel de NotificaciÃ³n</t>
    <t id="1018">CoordinaciÃ³n de Flota</t>
    <t id="1019">% objetivo de llenado de carga</t>
    <t id="1050">Frecuencia de ActualizaciÃ³n del Mercado</t>
    <t id="1051">Registro de EvaluaciÃ³n de Comercio</t>
    <t id="1052">Lista blanca de sectores</t>
    <t id="1054">Ignorar barcos de transporte/auxiliares</t>
    <t id="1056">Ignorar AlmacÃ©n de ConstrucciÃ³n</t>
    <t id="1058">Ignorar las reglas comerciales</t>
    <t id="1060">Ignorar estaciones suministradas por MK1</t>
    <t id="1063">En desarrollo</t>
    <t id="1064">MercancÃ­as prioritarias</t>
    <t id="1065">PuntuaciÃ³n prioridad %</t>
    <t id="1066">MercancÃ­as a favorecer en la puntuaciÃ³n comercial. Su puntuaciÃ³n se multiplica por el % de puntuaciÃ³n de prioridad.</t>
    <t id="1067">Multiplicador de puntuaciÃ³n para productos prioritarios: 100%=normal, 150%=+50%%, 200%=2x, 300%=3x. Aplicado por Ãºltimo.</t>
    <t id="1068">â”€â”€ Filtro de mercancÃ­as prioritarias â”€â”€</t>
    <t id="1069">MercancÃ­as (manual)</t>
    <t id="1070">Filtro de ruta ilegal</t>
    <t id="1072">Servir solo a domicilio</t>
    <t id="1073">Prioridad proveedor jugador</t>
    <t id="1074">Prioridad proveedor facciÃ³n</t>
    <t id="1075">Incluir almacenamiento de compilaciÃ³n</t>
    <t id="1076">Incluir recursos</t>
    <t id="1077">Incluir intermedios</t>
    <t id="1078">Incluir artÃ­culos comerciales</t>
    <t id="1080">Operaciones mÃ¡ximas por ciclo</t>
    <t id="1081">Tolerancia de retroceso</t>
    <t id="1082">% de carga mÃ­nima utilizada</t>
    <t id="1083">% del modificador de compra del jugador</t>
    <t id="1085">Asignar a la estaciÃ³n base</t>
    <t id="1086">Distancia de cobertura</t>
    <t id="1088">Distancia mÃ¡xima de salto desde casa para cobertura de demanda</t>
    <t id="1090">Incluir productos de clase comercial en la comparaciÃ³n de oferta y demanda.</t>
    <t id="1091">Modificador aplicado a los precios de proveedores propiedad de jugadores en cÃ¡lculos de puntuaciÃ³n Ãºnicamente</t>
    <t id="1092">Ignorar precios de jugador</t>
    <t id="1093">Cuando estÃ¡ habilitado: compre siempre en estaciones propiedad de los jugadores, independientemente de sus precios de venta establecidos, y solo venda a facciones de NPC. Ãštil para liquidar exceso de stock de tus propias estaciones.</t>
    <t id="1094">Estaciones bloqueadas</t>
    <t id="1095">Las estaciones seleccionadas aquÃ­ se excluyen del comercio MK3. El comerciante no comprarÃ¡ ni venderÃ¡ en ellas.</t>
    <t id="1096">Estacionamiento en inactividad</t>
    <t id="1097">Si estÃ¡ activado, las naves que no encuentran trabajo repetidamente se estacionan en su estaciÃ³n base o sector base. El estacionamiento en sector prefiere estaciones del jugador, luego estaciones amistosas. El tiempo de liberaciÃ³n del muelle se configura en Ajustes globales (0 = permanece amarrado hasta encontrar trabajo).</t>
    <t id="1098">Autoescala</t>
    <t id="1099">Si estÃ¡ activado, los controles de distancia de salto se ajustan al alcance mÃ¡ximo permitido del piloto tras completar la formaciÃ³n obligatoria o la Academia de Comercio. DesactÃ­velo para establecer las distancias manualmente.</t>
    <t id="11001">Prioridad almacÃ©n de construcciÃ³n</t>
    <t id="11002">Prioridad estaciones</t>
    <t id="11003">Prioridad naves auxiliares</t>
    <t id="11004">Prioridad portadores</t>
    <t id="11005">0 = desactivado. 1-10 = multiplicador de puntuaciÃ³n (10 = mayor peso). PuntuaciÃ³n final = puntuaciÃ³n de suministro Ã— multiplicador.</t>
    <t id="11006">1 = sin puntuaciÃ³n extra (lista de mercancÃ­as prioritarias sin cambios). 2-10 = suma (multiplicadorâˆ’1)Ã— puntuaciÃ³n base de suministro si la mercancÃ­a estÃ¡ en la lista prioritaria. Se aplica sobre la puntuaciÃ³n de tipo.</t>
    <t id="11007">Bonus de mercancÃ­as prioritarias</t>
    <t id="11008">%1: Todos los controles de prioridad de destino de entrega estÃ¡n en 0 - esta orden no tiene destinos de entrega. Active al menos una clase (almacÃ©n de construcciÃ³n, estaciones, naves auxiliares o portanaves) para reanudar los suministros.</t>
    <t id="7001">[AVANCE]</t>
    <t id="7002">[CAPACITACIÃ“N]</t>
    <t id="7008">[RETROCEDER]</t>
    <t id="7009">[AISLADO]</t>
    <t id="7003">[REPARACIÃ“N]</t>
    <t id="7004">[REABASTECIMIENTO]</t>
    <t id="7005">[MANTENIMIENTO]</t>
    <t id="7006">[REDIRECCIÃ“N]</t>
    <t id="7007">[AUTORIZACIÃ“N]</t>
    <t id="1020">Elegir sector o estaciÃ³n base donde opera el comerciante</t>
    <t id="1021">Distancia mÃ¡xima de portal de salto al comprar mercancÃ­as (limitada por la habilidad del piloto)</t>
    <t id="1022">Distancia mÃ¡xima de portal de salto al vender mercancÃ­as (limitada por la habilidad del piloto)</t>
    <t id="1023">SelecciÃ³n automÃ¡tica de mercancÃ­as adecuadas basada en categorÃ­a</t>
    <t id="1024">SelecciÃ³n manual de mercancÃ­as comerciales especÃ­ficas</t>
    <t id="1025">Permitir el comercio de contrabando y bienes ilegales.</t>
    <t id="1026">Tolerancia de seguridad: 0.0=Solo sectores seguros, 1.0=Aceptar todos los riesgos</t>
    <t id="1027">Mejorar las habilidades del piloto a travÃ©s de la experiencia comercial.</t>
    <t id="1028">Enviar automÃ¡ticamente pilotos para entrenamiento cuando sea necesario</t>
    <t id="1029">Coordinar mÃºltiples naves comerciales para evitar conflictos</t>
    <t id="1030">Enfoque de mercancÃ­as: 0=Equilibrado, 1=Avanzado, 2=Necesidades bÃ¡sicas, 3=Ilegal, 4=MercancÃ­as a granel</t>
    <t id="1031">Ãrea comercial: 0=Equilibrado, 1=Enfoque base, 2=Errancia libre</t>
    <t id="1032">Nivel de notificaciÃ³n: 0=MÃ­nimo, 1=Normal, 2=Mensajes detallados</t>
    <t id="1033">Porcentaje de utilizaciÃ³n de carga objetivo antes de priorizar ventas</t>
    <t id="1034">Frecuencia de actualizaciÃ³n de datos de mercado e informaciÃ³n de precios</t>
    <t id="1035">Nivel de salida de depuraciÃ³n: 0=Ninguno, 1=BÃ¡sico, 2=Registro detallado</t>
    <t id="1036">Compartir rutas comerciales rentables con la flota (en cachÃ© para acceso rÃ¡pido)</t>
    <t id="1037">Beneficio mÃ­nimo requerido para almacenar comercio en cachÃ© y compartir con la flota</t>
    <t id="1038">Declive mÃ¡ximo de beneficio permitido antes de que las rutas comerciales en cachÃ© se vuelvan invÃ¡lidas</t>
    <t id="1039">DuraciÃ³n de validez de las rutas comerciales en cachÃ© antes de expirar</t>
    <t id="1040">Habilite el registro detallado de evaluaciones y rechazos comerciales individuales (puede ser muy detallado)</t>
    <t id="1041">Activar entradas de diario de navegaciÃ³n por comercio y mensajes de entrenamiento inmersivos (estilo TaterTrader)</t>
    <t id="1053">Los sectores en esta lista estÃ¡n excluidos de las listas negras (siempre permitidos)</t>
    <t id="1055">Excluir del comercio a los transportistas y buques auxiliares.</t>
    <t id="1057">Excluir naves de almacÃ©n de construcciÃ³n del comercio</t>
    <t id="1059">Ignorar las reglas comerciales de la estaciÃ³n durante la bÃºsqueda de ofertas (avanzado; puede seleccionar ofertas normalmente bloqueadas)</t>
    <t id="1061">Salta las estaciones de jugadores que tengan un comerciante MK1 con el modo de suministro asignado</t>
    <t id="1062">BonificaciÃ³n de puntuaciÃ³n para rutas con tus propias estaciones (bonificaciÃ³n del 10%)</t>
    <t id="1071">Cuando Permitir mercancÃ­as ilegales estÃ¡ habilitado, solo intercambie mercancÃ­as ilegales si son legales en todos los sectores en la ruta de salto (compra, venta y sectores intermedios).</t>
    <t id="1087">Distancia mÃ¡xima de salto desde casa para bÃºsqueda de compra de proveedores</t>
    <t id="1089">Cuando estÃ¡ deshabilitado, el barco puede suministrar estaciones en el Ã¡rea de cobertura mediante prioridad de urgencia en lugar del modo de solo hogar.</t>
    <t id="2000">Â¡%s ha ganado %s XP!</t>
    <t id="2001">Â¡%s ha subido de nivel! Nuevo nivel: %s</t>
    <t id="2002">Â¡%s necesita entrenamiento! Por favor, envÃ­e al astillero o estaciÃ³n comercial mÃ¡s cercana.</t>
    <t id="2003">%s ha comenzado a entrenar a las %s</t>
    <t id="2004">Â¡%s ha completado el entrenamiento y ahora estÃ¡ certificado para el nivel %s!</t>
    <t id="2005">Â¡%s alcanzÃ³ el Skill Level %s despuÃ©s del entrenamiento! Progreso XP desbloqueado en %s.</t>
    <t id="2006">Â¡%s alcanzÃ³ el Skill Level %s con el comercio de %s!</t>
    <t id="2007">Â¡%s completÃ³ el entrenamiento Level %s! Progreso XP desbloqueado en %s.</t>
    <t id="3000">Â¡%s ha completado un comercio! Beneficio: %s Cr</t>
    <t id="3001">%s estÃ¡ analizando las condiciones del mercado...</t>
    <t id="3002">Â¡%s ha encontrado una ruta comercial rentable!</t>
    <t id="3003">No hay rutas comerciales rentables disponibles para %s</t>
    <t id="3100">Vendiendo %1 %2 de la carga a %3 al precio de %4. DeberÃ­a ganar %5 de beneficio.</t>
    <t id="3101">Encolando orden comercial para %1 %2. Comprando en %3 desde %4, vendiendo en %5 a %6. DeberÃ­a ganar %7 de beneficio.</t>
    <t id="3102">Comerciante de EstaciÃ³n: Suministrando %1 %2 de %3 al %5%% a %4 al %6%%.</t>
    <t id="3103">Comerciante de EstaciÃ³n: Vendiendo %1 %2 a %3 a %4. El beneficio esperado es %5.</t>
    <t id="3104">Comercio completado con Ã©xito para %1 %2. Beneficio total: %3 CrÃ©ditos.</t>
    <t id="3105">Ruta comercial en cachÃ©: %1 %2 de %3 a %4 (Beneficio: %5 Cr)</t>
    <t id="3106">\nBeneficio total estimado de por vida antes de esta operaciÃ³n: %1 Cr.</t>
    <t id="3120">Transferencia piloto iniciada</t>
    <t id="3121">Protocolo de transferencia reconocido. %1 (%2) y %3 (%4) se dirigen a %5 (%6) para atracar e intercambiar asientos de mando.</t>
    <t id="3200">Hola Comandante %1,\n\nHe adquirido suficiente experiencia para realizar mi examen de certificaciÃ³n para el tÃ­tulo "%2". El examen tomarÃ¡ aproximadamente %3 minutos en %4.\n\nEste es un hito importante en mi desarrollo profesional. El examen probarÃ¡ mis conocimientos de protocolos comerciales avanzados, anÃ¡lisis de mercado y procedimientos de coordinaciÃ³n de flota.\n\nTengo confianza en mis habilidades y estoy emocionado de demostrar que soy digno de este avance. Â¡Deseame suerte!\n\nRespetuosamente,\n%5\nA bordo de %6</t>
    <t id="3201">Comandante %1,\n\nÂ¡Excelentes noticias! He completado exitosamente mi examen de certificaciÃ³n y obtuve el tÃ­tulo "%2"!\n\nEl examen cubriÃ³ estrategias comerciales avanzadas, protocolos de evaluaciÃ³n de riesgos y procedimientos de coordinaciÃ³n de flota. Me complace informar que aprobÃ© con distinciÃ³n.\n\nAhora estoy calificado para manejar operaciones comerciales mÃ¡s complejas y espero contribuir aÃºn mÃ¡s al Ã©xito de nuestra flota. Gracias por invertir en mi desarrollo profesional.\n\nCon dedicaciÃ³n renovada,\n%3\nCertificado %2\nA bordo de %4</t>
    <t id="3202">Comandante %1,\n\nLamento informarle que mi examen de certificaciÃ³n fue interrumpido debido a requisitos operativos. NecesitarÃ© reprogramarlo cuando las circunstancias lo permitan.\n\nPermanezco comprometido a avanzar mis habilidades y le notificarÃ© cuando pueda reanudar el proceso de examen.\n\nRespetuosamente,\n%2\nA bordo de %3</t>
    <t id="3203">Comandante %1,\n\nActualmente estoy en ruta hacia %2 para mi examen de certificaciÃ³n. El viaje me da tiempo para revisar mis estudios y prepararme mentalmente para este paso importante en mi carrera.\n\nLlegada esperada: %3 minutos\nDuraciÃ³n del examen: %4 minutos\n\nAprecio su confianza en mis habilidades y la oportunidad de avance.\n\nCon determinaciÃ³n,\n%5\nA bordo de %6</t>
    <t id="3204">Comandante,\n\nHe detectado carga en mi bodega durante mi verificaciÃ³n de sistemas. Antes de poder comenzar operaciones comerciales normales, necesito vender esta mercancÃ­a.\n\nEstoy usando nuestra bÃºsqueda comercial para encontrar el mejor comprador y descargar esta carga de forma segura. Una vez que mi bodega estÃ© vacÃ­a, procederÃ© con el comercio automatizado.\n\nEstado: Buscando ubicaciÃ³n de venta Ã³ptima\n\nCon diligencia,\nA bordo de %1</t>
    <t id="3205">Comandante,\n\nLa integridad de mi casco ha caÃ­do al %1%% (umbral: %2%%). Como piloto de Nivel %3, estoy autorizado a solicitar servicios de reparaciÃ³n automÃ¡tica.\n\nMe dirijo a %4 para trabajos de reparaciÃ³n. El costo estimado es de %5 Cr, que estÃ¡ dentro de nuestro presupuesto.\n\nUna vez que las reparaciones estÃ©n completas, reanudarÃ© las operaciones comerciales con integridad estructural completa.\n\nRespetuosamente,\nA bordo de %6</t>
    <t id="3206">Comandante,\n\nADVERTENCIA FINANCIERA URGENTE\n\nLa integridad de mi casco es crÃ­tica al %1%% (umbral: %2%%), pero nuestros fondos disponibles (%3 Cr) son insuficientes para reparaciones completas (costo estimado: %4 Cr).\n\nMe dirijo a %5 para REPARACIONES PARCIALES usando nuestros fondos disponibles. Esta no es una soluciÃ³n ideal, pero es necesaria para mantener la capacidad operativa.\n\nPor favor, considere asignar fondos adicionales para futuras operaciones de mantenimiento.\n\nPreocupado pero determinado,\nA bordo de %6</t>
    <t id="3207">Comandante,\n\nMi certificaciÃ³n de Nivel %1 autoriza el reabastecimiento automÃ¡tico de equipo defensivo. DespuÃ©s de verificar mis sistemas, he determinado que mis contramedidas y equipos desplegables estÃ¡n por debajo de los umbrales recomendados.\n\nMe dirijo a %2 para reabastecer mi equipo defensivo:\nâ€¢ Contramedidas: Reabasteciendo a capacidad Ã³ptima\nâ€¢ Drones de defensa, drones comerciales, torres lÃ¡ser: Aplicando perfil de equilibrio\n\nEste reabastecimiento asegura que estoy mejor protegido contra amenazas espaciales mientras mantengo la eficiencia comercial.\n\nCon vigilancia,\nA bordo de %3</t>
    <t id="3212">Comandante,\n\nLa integridad de mi casco ha caÃ­do al %1%% (umbral: %2%%), y necesito servicios de reparaciÃ³n. Sin embargo, la estaciÃ³n de reparaciÃ³n mÃ¡s cercana en %3 estÃ¡ actualmente inaccesible debido a restricciones de viaje sectorial (rutas en lista negra).\n\nContinuarÃ© con operaciones comerciales a pesar de esta limitaciÃ³n. Una vez que las rutas seguras vuelvan a estar disponibles, buscarÃ© automÃ¡ticamente servicios de reparaciÃ³n.\n\nMonitorearÃ© la situaciÃ³n y le notificarÃ© cuando las reparaciones sean posibles.\n\nRespetuosamente,\nA bordo de %4</t>
    <t id="3213">Comandante,\n\nMi equipo defensivo requiere reabastecimiento, pero la estaciÃ³n de equipo mÃ¡s cercana en %1 estÃ¡ actualmente inaccesible debido a restricciones de viaje sectorial (rutas en lista negra).\n\nContinuarÃ© con operaciones comerciales a pesar de esta limitaciÃ³n. Una vez que las rutas seguras vuelvan a estar disponibles, buscarÃ© automÃ¡ticamente servicios de reabastecimiento.\n\nMonitorearÃ© la situaciÃ³n y le notificarÃ© cuando el reabastecimiento sea posible.\n\nRespetuosamente,\nA bordo de %2</t>
    <t id="3208">Comandante,\n\nHe completado un anÃ¡lisis exhaustivo del mercado de %1 y sectores circundantes (dentro de %2 saltos, umbral de beneficio mÃ­nimo: %3 Cr), pero desafortunadamente no encontrÃ© oportunidades comerciales rentables que cumplan con nuestros requisitos.\n\nINFORME DE ANÃLISIS COMERCIAL:\nTotal de oportunidades evaluadas: %4\n\nDESGLOSE DE RECHAZOS:\n- Restricciones de atraque: %5 comercios\n  (La estaciÃ³n no permite mi clase de nave)\n- Rentabilidad insuficiente: %6 comercios\n  (Por debajo del umbral de beneficio mÃ­nimo)\n- Volumen insuficiente: %7 comercios\n  (Cantidad comercializable cero o negativa)\n- Restricciones de seguridad: %8 comercios\n  (Estaciones en lista negra o sectores peligrosos)\n\nRECOMENDACIONES:\n- Considere ajustar los umbrales de beneficio\n- Expanda la distancia comercial mÃ¡xima\n- Revise la configuraciÃ³n de lista negra sectorial\n- Espere a que las condiciones del mercado mejoren\n\nContinuarÃ© monitoreando el mercado y le notificarÃ© cuando las oportunidades rentables estÃ©n disponibles.\n\nEn espera,\nA su servicio</t>
    <t id="3209">Comandante,\n\nALERTA DE RUTA URGENTE\n\nMi sistema de inteligencia de amenazas ha detectado que el sector %1 (nivel de amenaza %2) ahora estÃ¡ en mi ruta comercial planificada. Por la seguridad de la nave y la tripulaciÃ³n, estoy abortando inmediatamente la operaciÃ³n comercial actual.\n\nACCIONES TOMADAS:\n- Todas las Ã³rdenes comerciales canceladas\n- Regresando al modo de operaciones seguras\n- EncontrarÃ¡ una ruta comercial alternativa que evita sectores peligrosos\n- Manejo de carga: AutomÃ¡tico (venderÃ¡ cualquier carga en ubicaciÃ³n segura si es necesario)\n\nEl sistema de lista negra dinÃ¡mica impedirÃ¡ futuros comercios a travÃ©s de este sector hasta que la amenaza sea eliminada.\n\nLa seguridad es mi primera prioridad.\n\nCon vigilancia,\nA bordo de %3</t>
    <t id="3210">Comandante,\n\nRUTA DE ESCAPE INICIADA\n\nActualmente estoy en el sector en lista negra %1 y he encontrado una ruta comercial que me permitirÃ¡ escapar de forma segura.\n\nRUTA COMERCIAL:\nComprar: %2 (Sector: %3)\nVender: %4 (Sector: %5)\nMercancÃ­a: %6 (x%7)\nBeneficio Esperado: %8 Cr\n\nLa nave escaparÃ¡ del sector en lista negra despuÃ©s de completar este comercio.\n\nRespetuosamente,\nA su servicio</t>
    <t id="3211">Comandante,\n\nMODO DE COMERCIO AISLADO\n\nActualmente estoy en el sector %2, pero todas las rutas hacia otros sectores estÃ¡n bloqueadas por sectores hub en lista negra. Esto significa que solo puedo comerciar dentro de mi sector actual hasta que la situaciÃ³n de lista negra cambie.\n\nSITUACIÃ“N:\nSector Actual: %2\nEstado: Aislado (sector no en lista negra con rutas bloqueadas)\nModo Comercial: Solo comercios intra-sectoriales\n\nMi sistema comercial ha ajustado automÃ¡ticamente los umbrales de beneficio para priorizar oportunidades comerciales intra-sectoriales disponibles.\n\nContinuarÃ© monitoreando la situaciÃ³n y le notificarÃ© si las rutas vuelven a estar disponibles.\n\nRespetuosamente,\nA bordo de %1</t>
    <t id="3218">Comandante,\n\nCAMBIO DE TRAYECTO DE RUTA DETECTADO\n\nAl entrar en el sector %1, mi sistema de navegaciÃ³n detectÃ³ que la ruta hacia mi destino %2 (%3) ha cambiado.\n\nANÃLISIS DE TRAYECTO:\n- Distancia normal: %4 saltos\n- Distancia con lista negra: %5\n- Estado: %6\n\nMi computadora de navegaciÃ³n indica que la ruta preferida ya no es viable debido a restricciones de viaje sectorial. Por la seguridad de la nave y la tripulaciÃ³n, estoy abortando inmediatamente la operaciÃ³n comercial actual.\n\nACCIONES TOMADAS:\n- Todas las Ã³rdenes comerciales canceladas\n- Regresando al modo de operaciones seguras\n- EncontrarÃ¡ una ruta comercial alternativa que evita sectores bloqueados\n- Manejo de carga: AutomÃ¡tico (venderÃ¡ cualquier carga en ubicaciÃ³n segura si es necesario)\n\nMi sistema de navegaciÃ³n evitarÃ¡ automÃ¡ticamente sectores bloqueados en la planificaciÃ³n futura de rutas.\n\nLa seguridad es mi primera prioridad.\n\nCon vigilancia,\nA bordo de %7</t>
    <t id="3219">Sector %1 despejado: todas las amenazas eliminadas</t>
    <t id="3220">Comandante,\n\nNAVE ENEMIGA ESCAPÃ“\n\nNuestro sistema de inteligencia de amenazas ha perdido el rastro de la nave enemiga %3, que ha escapado del sector en lista negra %1.\n\nDETALLES:\n- Nave Escapada: %3\n- Sector Abandonado: %1\n- Sector de Destino: %2\n- Estado: Rastreo perdido - la nave ha dejado nuestra Ã¡rea monitoreada\n\nAunque esta nave ya no es una amenaza en el sector %1, hemos perdido contacto visual y no podemos confirmar su estado actual o intenciones en el sector %2.\n\nNuestros sistemas de rastreo continuarÃ¡n monitoreando el sector %1 para amenazas restantes. Si todos los enemigos rastreados se van o son eliminados, el sector serÃ¡ automÃ¡ticamente eliminado de la lista negra.\n\nCon vigilancia,\nSistema de Inteligencia de Amenazas</t>
    <t id="3221">Comandante,\n\nNo pude encontrar oportunidades comerciales rentables a mayores distancias (hasta %3 saltos) porque estas rutas estÃ¡n actualmente inaccesibles debido a restricciones de viaje sectorial (trayectos en lista negra).\n\nSITUACIÃ“N:\nSector Actual: %2\nRango de BÃºsqueda Original: %3 saltos\nRango de BÃºsqueda Alternativo: %4 saltos\n\nAhora me enfocarÃ© en buscar sectores cercanos dentro de %4 saltos, donde las rutas tienen mÃ¡s probabilidades de estar accesibles. Esto deberÃ­a ayudarme a encontrar comercios rentables que fueron previamente filtrados debido a restricciones de distancia en lugar de falta real de rentabilidad.\n\nLe notificarÃ© cuando encuentre oportunidades comerciales adecuadas en el Ã¡rea cercana.\n\nRespetuosamente,\nA bordo de %1</t>
    <t id="3222">Comandante,\n\nSECTOR EN LISTA NEGRA\n\nNuestro sistema de inteligencia de amenazas ha detectado actividad hostil en el sector %1 y ha puesto automÃ¡ticamente este sector en lista negra para proteger nuestras operaciones comerciales.\n\nNAVES ENEMIGAS DETECTADAS:\n%2\n\nDETECTADO POR: %3\n\nPor la seguridad de nuestras naves y tripulaciÃ³n, todas las rutas comerciales a travÃ©s de este sector han sido bloqueadas. Nuestras naves automÃ¡ticamente rodearÃ¡n este sector hasta que la amenaza sea eliminada.\n\nEl sector serÃ¡ automÃ¡ticamente eliminado de la lista negra una vez que todas las naves enemigas rastreadas sean eliminadas o abandonen el Ã¡rea.\n\nCon vigilancia,\nSistema de Inteligencia de Amenazas</t>
    <t id="3223">Comandante,\n\nNo puedo encontrar una estaciÃ³n de entrenamiento accesible para mi examen de nivel %1. ProcederÃ© con las operaciones comerciales segÃºn las instrucciones, pero entiendo que no ganarÃ© puntos de experiencia hasta que pueda completar el entrenamiento requerido. DespuÃ©s de esta carrera comercial, buscarÃ© nuevamente cualquier oportunidad posible de entrenamiento.\n\nRespetuosamente,\nA bordo de %2</t>
    <t id="3224">Tasa de licencia de formaciÃ³n: %1 Cr</t>
    <t id="3225">Bonus: Â¡GanÃ© %1 nivel de habilidad adicional%2 gracias a la experiencia acumulada durante el entrenamiento! Nivel actual: %3</t>
    <t id="3214">Â¡Es un honor trabajar para usted, %1! Estoy emocionado de comenzar mi carrera comercial bajo su mando. HarÃ© mi mejor esfuerzo para servirle bien y contribuir a su Ã©xito.</t>
    <t id="3215">Â¡Gracias por darme estas merecidas vacaciones, %1! He disfrutado mi tiempo lejos del comercio y mis habilidades permanecen intactas. Espero regresar al trabajo siempre que me necesite. Hasta entonces, mantendrÃ© mis conocimientos comerciales afilados!</t>
    <t id="3216">Â¡Estoy de vuelta de las vacaciones y listo para trabajar de nuevo, %1! Mis habilidades comerciales permanecen afiladas y estoy ansioso por continuar sirviÃ©ndole en %2. Â¡Gracias por el merecido descanso!</t>
    <t id="3217">Â¡Gracias por mi transferencia a %1, %2! Estoy honrado por esta nueva asignaciÃ³n y cuidarÃ© excelentemente mi nueva nave. Mi experiencia y habilidades comerciales permanecen intactas, y estoy listo para continuar sirviÃ©ndole.</t>
    <t id="3227">Casco perdido, dignidad pendiente de recogida</t>
    <t id="3228">Comandante %1,\n\n%2 informando desde %3. Mi nave explotÃ³. Yo no. Ahora soy la carga flotante mÃ¡s cara de la flota.\n\nMarcador en el mapa adjunto. Por favor, apresÃºrese - estaba en medio de una factura.\n\nFlotando profesionalmente,\n%2</t>
    <t id="3229">Piloto recuperado - AdicciÃ³n al oxÃ­geno curada</t>
    <t id="3230">Comandante %1,\n\nActualizaciÃ³n de flota: %2 ha sido recogido por %3 (%4) y ha dejado de facturarle el entrenamiento EVA extendido.\n\nReenlace del registro en curso. RecomendaciÃ³n: no hacer preguntas sobre la nave anterior.\n\nAtentamente avergonzado,\n%2</t>
<t id="4000">CoordinaciÃ³n de flota: %s ha sido asignado a la ruta %s</t>
    <t id="4001">CoordinaciÃ³n de flota: La ruta %s estÃ¡ completamente utilizada</t>
    <t id="4002">CoordinaciÃ³n de flota: %s ha liberado la ruta %s</t>
    <t id="5000">%s ha sido asignado como territorio principal para %s</t>
    <t id="5001">Â¡%s ha alcanzado el nivel de experiencia %s en %s!</t>
    <t id="5002">BonificaciÃ³n de territorio aplicada: %s%% de aumento de ganancias en %s</t>
    <t id="9500">Error: Â¡%s estÃ¡ atascado y necesita asistencia!</t>
    <t id="9501">Error: el intercambio fallÃ³ para %s</t>
    <t id="9502">Error: No se puede registrar %s con GalaxyTrader MK3</t>
    <t id="80001">MercancÃ­a %s aÃ±adida a la lista negra</t>
    <t id="80002">MercancÃ­a %s eliminada de la lista negra</t>
    <t id="80003">MercancÃ­a %s aÃ±adida a la lista blanca</t>
    <t id="80004">AutomÃ¡ticamente en lista negra (mal rendimiento): %s</t>
    <t id="80005">MercancÃ­a peligrosa priorizada: %s</t>
    <t id="80006">Filtro de mercancÃ­as: %s activo, %s comercios bloqueados</t>
    <t id="80007">Todos los filtros de mercancÃ­as limpiados</t>
    <t id="80008">Filtros de mercancÃ­as restablecidos a predeterminado</t>
    <t id="80009">GestiÃ³n de Filtros de MercancÃ­as</t>
    <t id="80010">MercancÃ­as Bloqueadas</t>
    <t id="80011">MercancÃ­as Permitidas</t>
    <t id="80012">Manejo de MercancÃ­as Peligrosas</t>
    <t id="80013">Valor MÃ­nimo de MercancÃ­a</t>
    <t id="80014">Valor MÃ¡ximo de MercancÃ­a</t>
    <t id="80015">Facciones restringidas</t>
    <t id="80016">CategorÃ­as de mercancÃ­as actualizadas desde el estado actual del juego</t>
    <t id="80017">%s mercancÃ­as categorizadas: %s de bajo valor, %s peligrosas, %s de alto valor</t>
    <t id="80018">CategorizaciÃ³n dinÃ¡mica de mercancÃ­as activada</t>
    <t id="80019">Lista negra automÃ¡tica para la categorÃ­a %s desactivada</t>
    <t id="80020">Nuevas mercancÃ­as de otros mods detectadas y categorizadas</t>
    <t id="9000">GalaxyTrader - ConfiguraciÃ³n Global</t>
    <t id="9010">XP y sistema de entrenamiento</t>
    <t id="9012">Entrenamiento AutomÃ¡tico</t>
    <t id="9013">Multiplicador de XP</t>
    <t id="9015">Porcentaje de BonificaciÃ³n del Comandante</t>
    <t id="9020">CoordinaciÃ³n de Flota</t>
    <t id="9021">Activar CoordinaciÃ³n de Flota</t>
    <t id="9023">Activar CachÃ© Comercial</t>
    <t id="9030">Notificaciones</t>
    <t id="9031">Nivel de NotificaciÃ³n</t>
    <t id="9040">Sistema de ReparaciÃ³n AutomÃ¡tica</t>
    <t id="9041">Activar ReparaciÃ³n AutomÃ¡tica</t>
    <t id="9042">Umbral de ReparaciÃ³n de Casco</t>
    <t id="9310">Minero de galaxias</t>
    <t id="9311">Espera de escaneo de sondas por sector</t>
    <t id="9312">Peso de proximidad de la nave</t>
    <t id="9043">Nivel MÃ­nimo del Piloto</t>
    <t id="9004">Rangos de precios comerciales</t>
    <t id="9005">Precio MÃ¡ximo de Oferta de Venta</t>
    <t id="9006">Precio MÃ­nimo de Oferta de Compra</t>
    <t id="9007">Aislado: Precio MÃ¡ximo de Venta</t>
    <t id="9008">Aislado: Precio MÃ­nimo de Compra</t>
    <t id="9009">Respaldo: Precio MÃ¡ximo de Venta</t>
    <t id="9014">Respaldo: Precio MÃ­nimo de Compra</t>
    <t id="9016">Base del umbral de beneficio</t>
    <t id="9025">Dinero mÃ­nimo del jugador</t>
    <t id="9024">Tolerancia de CaÃ­da del CachÃ©</t>
    <t id="9026">Tiempo de estacionamiento inactivo antes de liberar</t>
    <t id="9054">Bloquear sectores de facciones enemigas</t>
    <t id="9055">Nivel de amenaza de la lista negra</t>
    <t id="9056">Recrear lista negra</t>
    <t id="9057">Recrear</t>
    <t id="9058">Asignar a GT barcos</t>
    <t id="9059">Asignar</t>
    <t id="9112">EnvÃ­a automÃ¡ticamente pilotos para entrenamiento cuando alcanzan los niveles requeridos. Desactivar para controlar manualmente el momento del entrenamiento.</t>
    <t id="9113">Ajusta quÃ© tan rÃ¡pido los pilotos ganan experiencia. Valores mÃ¡s altos significan progresiÃ³n mÃ¡s rÃ¡pida.</t>
    <t id="9115">Porcentaje de XP subordinado otorgado a los pilotos comandantes. ConfigÃºrelo en 0% para desactivar la bonificaciÃ³n de XP del comandante. Predeterminado: 10%.</t>
    <t id="9121">Activa caracterÃ­sticas inteligentes de coordinaciÃ³n de flota incluyendo optimizaciÃ³n de rutas y equilibrio de carga.</t>
    <t id="9123">Permite compartir oportunidades comerciales rentables entre miembros de la flota para mejor coordinaciÃ³n.</t>
    <t id="9131">Controla cuÃ¡ntas notificaciones se muestran: 0=Silencioso, 1=Solo importantes, 2=Todas las notificaciones</t>
    <t id="9141">EnvÃ­a automÃ¡ticamente naves para reparaciÃ³n despuÃ©s de completar comercios cuando el casco cae por debajo del umbral. Solo para pilotos experimentados (Nivel 12+). Las naves eligen la instalaciÃ³n apropiada: S/M EstaciÃ³n de Equipamiento, L/XL Astillero.</t>
    <t id="9142">Porcentaje de casco por debajo del cual se activa la reparaciÃ³n automÃ¡tica. Predeterminado: 95%. Las naves irÃ¡n automÃ¡ticamente a la instalaciÃ³n de reparaciÃ³n mÃ¡s cercana cuando estÃ©n daÃ±adas.</t>
    <t id="9411">Si estÃ¡ activado, los mineros esperan al evaluar sondas de recursos de la facciÃ³n en el sector (+5 s por sonda por encima de una). El nivel GT del piloto reduce esa espera linealmente, del tiempo completo en nivel 1 a 5 segundos en nivel 15 (solo modo XP GT, si la espera supera 5 s). Desactivado = sin espera (comportamiento vanilla).</t>
    <t id="9412">Orienta a las naves MK3/MK4 hacia estaciones de compra mÃ¡s cercanas al ordenar trades validados. PuntuaciÃ³n de selecciÃ³n = puntuaciÃ³n del trade / (1 + saltos naveâ†’compra Ã— peso). Control deslizante 0-100 (0 = off; 4 = predeterminado 0,04). No afecta la clasificaciÃ³n de cachÃ© ni los lÃ­mites de alcance territorial.</t>
    <t id="9143">Nivel mÃ­nimo del piloto requerido para la caracterÃ­stica de reparaciÃ³n automÃ¡tica. Predeterminado: 12 (comerciantes experimentados). Los pilotos de nivel inferior deben reparar manualmente.</t>
    <t id="9104">Precio relativo mÃ¡ximo para ofertas de venta (la nave compra DE las estaciones). Rango: -1.0 a +1.0. Predeterminado: 0.5 (50% por encima del promedio). MÃ¡s alto = mÃ¡s caro pero mÃ¡s opciones.</t>
    <t id="9105">Precio relativo mÃ­nimo para ofertas de compra (la nave vende A las estaciones). Rango: -1.0 a +1.0. Predeterminado: -0.5 (50% por debajo del promedio). MÃ¡s bajo = compradores mÃ¡s baratos pero mÃ¡s opciones.</t>
    <t id="9106">Precio mÃ¡ximo de venta para naves aisladas (atrapadas en un solo sector). Rango: -1.0 a +1.0. Predeterminado: 0.5.</t>
    <t id="9107">Precio mÃ­nimo de compra para naves aisladas (atrapadas en un solo sector). Rango: -1.0 a +1.0. Predeterminado: -0.5.</t>
    <t id="9108">Precio mÃ¡ximo de venta para bÃºsqueda de respaldo (Ãºltimo recurso cuando la bÃºsqueda normal falla). Rango: -1.0 a +1.0. Predeterminado: 0.5. La bÃºsqueda de respaldo usa MaxDistance=2 y umbrales de beneficio relajados.</t>
    <t id="9109">Precio mÃ­nimo de compra para bÃºsqueda de respaldo (Ãºltimo recurso cuando la bÃºsqueda normal falla). Rango: -1.0 a +1.0. Predeterminado: -0.5. La bÃºsqueda de respaldo usa MaxDistance=2 y umbrales de beneficio relajados.</t>
    <t id="9116">El beneficio mÃ­nimo base en el nivel 15 para un comerciante medio (carga de referencia 8200).El beneficio real de MinAbsolute se calcula por piloto + escalado por carga:\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(escalado, 25% de base(L))\n\nConfigurar a 0 para aceptar cualquier beneficio (solo se aplican ROI/distancia/otros filtros).</t>
    <t id="9125">Cuando el dinero del jugador cae por debajo de este umbral, todas las naves omiten las bÃºsquedas comerciales y esperen, evitando el escaneo de cachÃ© costoso que causa tartamudeo del juego. Rango: 1.000 - 100.000 Cr. Por defecto: 1.000 Cr.</t>
    <t id="9124">CaÃ­da de porcentaje ROI mÃ¡ximo desde el valor en cachÃ© antes de rechazar el comercio. Ejemplo: 20% ROI en cachÃ© con 15% de tolerancia acepta hasta 17% ROI (caÃ­da del 14%).</t>
    <t id="9126">Minutos amarrados antes de desacoplar para liberar el puerto (0-60). 0 = permanece amarrado hasta encontrar nuevo trabajo. Predeterminado: 1 minuto.</t>
    <t id="9154">Pone automÃ¡ticamente en lista negra todos los sectores propiedad de facciones enemigas (casilla de relaciÃ³n en la lista negra)</t>
    <t id="9155">Nivel de amenaza mÃ­nimo (1-5) requerido para poner un sector en lista negra:\n2=Medio (ataque Ãºnico)\n3=Medio-Alto (facciones hostiles)\n4=Alto (naves capitales/misiles)\n5=Muy Alto (Xenon/Khaak)</t>
    <t id="9156">Recrear manualmente la lista negra de evitaciÃ³n de amenazas (Ãºtil si fue eliminada)</t>
    <t id="9157">Asigne manualmente la lista negra dinÃ¡mica actual a todos los GT barcos comandantes de flota. Los subordinados heredan de su comandante.</t>
    <t id="6001">Aprendiz</t>
    <t id="6002">Mensajero</t>
    <t id="6003">Proveedor</t>
    <t id="6004">Comerciante</t>
    <t id="6005">Comerciante</t>
    <t id="6006">Comerciante de larga distancia</t>
    <t id="6101">Equilibrado</t>
    <t id="6102">Defensivo</t>
    <t id="6103">Centrado en el comercio</t>
    <t id="6104">Defensa pesada</t>
    <t id="6105">Soporte de torre</t>
    <t id="9050">Sistema de EvitaciÃ³n de Amenazas</t>
    <t id="9051">Activar EvitaciÃ³n de Amenazas:</t>
    <t id="9052">Umbral de RelaciÃ³n Hostil:</t>
    <t id="9053">Usar Lista Negra DinÃ¡mica:</t>
    <t id="9151">Los comerciantes de nivel 6+ detectan barcos hostiles y evitan rutas peligrosas. La desactivaciÃ³n detiene todo el anÃ¡lisis (mejora el rendimiento). Tolerancia al riesgo por buque en comportamiento de mando (escala 0-10).</t>
    <t id="9152">Solo marca facciones con relaciÃ³n igual o inferior a este valor como amenazas. Predeterminado: -20%</t>
    <t id="9153">Pone automÃ¡ticamente en lista negra sectores peligrosos (nivel de amenaza 3+) para forzar a las naves a rodear las amenazas. Usa pathfinding vanilla para rutas alternativas.</t>
    <t id="9060">Reabastecimiento AutomÃ¡tico de Equipo Defensivo (Nivel 15)</t>
    <t id="9061">Activar Reabastecimiento AutomÃ¡tico:</t>
    <t id="9062">Contramedidas de reabastecimiento:</t>
    <t id="9063">Reabastecimiento de drones de defensa:</t>
    <t id="9064">Reabastecimiento de drones comerciales:</t>
    <t id="9065">Reabastecer Torres LÃ¡ser:</t>
    <t id="9066">Reabastecer Drones de ReparaciÃ³n:</t>
    <t id="9067">Umbral de contramedida:</t>
    <t id="9068">Umbral de capacidad unificada:</t>
    <t id="9069">Perfil de equilibrio del equipo:</t>
    <t id="9161">Los Maestros Comerciantes (Nivel 15) reabastecen automÃ¡ticamente el equipo defensivo despuÃ©s de los comercios. Se aplica al nivel de comandante para subordinados.</t>
    <t id="9162">Todas las naves (S/M/L/XL). Capacidad separada. CrÃ­tico para la defensa contra misiles.</t>
    <t id="9163">EnvÃ­os L/XL Ãºnicamente. Comparte capacidad unificada con otros implementables.</t>
    <t id="9164">EnvÃ­os L/XL Ãºnicamente. Esencial para operaciones comerciales. Comparte capacidad unificada.</t>
    <t id="9165">Todos los barcos. Los barcos L/XL comparten capacidad unificada, los S/M utilizan carga.</t>
    <t id="9166">Naves L/XL solamente. Funciona con el sistema de reparaciÃ³n automÃ¡tica. Comparte capacidad unificada.</t>
    <t id="9167">Reabastecer cuando las contramedidas estÃ©n por debajo de este porcentaje (todas las naves, capacidad separada).</t>
    <t id="9168">Reabastecer cuando el total de equipos desplegables estÃ© por debajo de este porcentaje (naves L/XL: drones + torres comparten una capacidad).</t>
    <t id="9169">DistribuciÃ³n de capacidad unificada (naves L/XL): Enfocado en Comercio (20/50/20/10), Equilibrado (35/35/20/10), Defensivo (50/20/20/10), Defensa Pesada (40/30/20/10), Soporte de Torres (30/30/30/10). Proporciones: Defensa/Comercio/Torres/ReparaciÃ³n. Haga clic para recorrer las opciones.</t>
    <t id="9090">Modificaciones de barcos</t>
    <t id="9091">Habilitar modificaciones de envÃ­o</t>
    <t id="9191">Instala automÃ¡ticamente modificaciones de nave y motor basadas en el nivel del piloto. Nivel 9+ = Mods Nivel 1, Nivel 12+ = Mods Nivel 2, Nivel 15+ = Mods Nivel 3. Solo los mods instalados por GT se eliminan cuando la orden es cancelada.</t>
    <t id="9070">ConfiguraciÃ³n de Nombrado de Nave</t>
    <t id="9071">Mostrar XP:</t>
    <t id="9072">ClasificaciÃ³n de visualizaciÃ³n:</t>
    <t id="9073">Nivel de visualizaciÃ³n:</t>
    <t id="9074">Estado de visualizaciÃ³n:</t>
    <t id="9075">Habilitar cambio de nombre de barco:</t>
    <t id="9076">Prefijo</t>
    <t id="9077">Sufijo</t>
    <t id="9078">Fuente de nombre predeterminada:</t>
    <t id="9079">Nombre del modelo</t>
    <t id="9080">Tipo Nombre</t>
    <t id="9081">Base del modelo</t>
    <t id="9083">Nombre personalizado</t>
    <t id="9084">Mostrar sector base:</t>
    <t id="9085">Modo de nomenclatura:</t>
    <t id="9086">ClÃ¡sico</t>
    <t id="9087">PatrÃ³n</t>
    <t id="9088">PatrÃ³n de nombre:</t>
    <t id="9089">Marcadores: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. AtÃ³micos: {RS} {CB} {BL}, etc. Usa las abreviaturas de estado abajo. Los marcadores vacÃ­os se omiten; los espacios se colapsan. MÃ¡x. 128 caracteres.</t>
    <t id="9183">Mostrar el sector base configurado en el nombre de la nave (prefijo o sufijo).</t>
    <t id="9184">Formato de nombre personalizado con marcadores {TOKEN} en lugar de opciones clÃ¡sicas. Requiere XP GalaxyTrader (no modo XP vanilla).</t>
    <t id="9092">Marcadores de patrÃ³n</t>
    <t id="9093">Nave: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Base: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">TripulaciÃ³n: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Sector: {SECTOR} | EstadÃ­sticas: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Marcadores de estado:</t>
    <t id="9100">{OPSTATE}: todos los indicadores operativos activos (p. ej. CB RS, MT)</t>
    <t id="9101">{STATUS}: bloqueado, entrenamiento, reserva o aislado</t>
    <t id="9102">{CB}: solo blacklist personalizada; incluido en {OPSTATE}; no combinar</t>
    <t id="9082">Mostrar clase de barco:</t>
    <t id="9171">Mostrar valores de XP en los nombres de los barcos</t>
    <t id="9175">Activar o desactivar renombrado automÃ¡tico de nave con informaciÃ³n del piloto</t>
    <t id="9172">Mostrar tÃ­tulos de rango en los nombres de las naves</t>
    <t id="9173">Mostrar nÃºmeros de nivel en los nombres de las naves</t>
    <t id="9174">Mostrar el estado comercial en los nombres de los barcos</t>
    <t id="9178">Elegir la fuente para los nombres base de las naves: Nombre de Modelo (con variante), Nombre de Tipo (genÃ©rico), o Nombre Base (sin variante)</t>
    <t id="9182">Mostrar clase de barco (S, M, L, XL) en los nombres de los barcos</t>
    <t id="9200">ConfiguraciÃ³n de DepuraciÃ³n</t>
    <t id="9201">Activar Registro de DepuraciÃ³n:</t>
    <t id="9202">Interruptor maestro para toda la salida debug_text. Cuando estÃ¡ desactivado, todo el registro de depuraciÃ³n se suprime. Cuando estÃ¡ activado, los mensajes de depuraciÃ³n aparecen en el DebugLog basados en valores de probabilidad individuales debug_text.</t>
    <t id="9220">Mantenimiento &amp; DiagnÃ³sticos</t>
    <t id="9221">Restablecer EstadÃ­sticas de Beneficio:</t>
    <t id="9222">REINICIAR</t>
    <t id="9223">Borrar todos los sectores incluidos en la lista negra:</t>
    <t id="9224">CLARO</t>
    <t id="9225">Restablecer todas las configuraciones a los valores predeterminados:</t>
    <t id="9226">REINICIAR TODO</t>
    <t id="9323">Elimina todos los sectores de la lista negra de inteligencia de amenazas. Esto limpiarÃ¡ inmediatamente todos los sectores en lista negra y permitirÃ¡ que sus naves viajen a Ã¡reas previamente bloqueadas. Use esto si desea restablecer el sistema de evitaciÃ³n de amenazas o si los sectores fueron incorrectamente puestos en lista negra.</t>
    <t id="9321">Restablece todas las estadÃ­sticas de beneficio a 0 para todos los pilotos y naves. Use esto despuÃ©s de actualizar a v0.6.0 para limpiar estadÃ­sticas infladas basadas en ingresos. La correcciÃ³n ahora rastrea el BENEFICIO real (ingresos - costo de compra). Los conteos de comercio y XP se preservan.</t>
    <t id="9325">Restablece todas las configuraciones globales a sus valores predeterminados. Esto incluye configuraciones de XP, CoordinaciÃ³n de Flota, Notificaciones, Inteligencia MÃ³vil, EvitaciÃ³n de Amenazas, Nombrado de Naves, Auto-ReparaciÃ³n, Modificaciones, Rendimiento y Formato de NÃºmero. La configuraciÃ³n de registro de depuraciÃ³n se preserva para permitir el registro de la operaciÃ³n de restablecimiento.</t>
    <t id="9227">Limpiar cachÃ© comercial para todos los sectores de origen:</t>
    <t id="9228">LIMPIAR CACHÃ‰</t>
    <t id="9327">Limpia el cachÃ© comercial para todos los sectores de origen. Esto forzarÃ¡ a todas las naves a realizar bÃºsquedas en vivo frescas en su prÃ³xima bÃºsqueda comercial. Use esto si el cachÃ© parece obsoleto o corrupto, o si desea forzar una actualizaciÃ³n completa del cachÃ©.</t>
    <t id="9229">Liberar todos los bloqueos de bÃºsqueda</t>
    <t id="9329">Libera TODOS los bloqueos de bÃºsqueda comercial en curso y limpia los estados transitorios relacionados. Use esto si las naves estÃ¡n atascadas en "BÃºsqueda de comercios" debido a bloqueos obsoletos de guardados antiguos. Puede interrumpir bÃºsquedas legÃ­timas.</t>
    <t id="9290">Estado del centro de comercio de volcado:</t>
    <t id="9291">VERTEDERO</t>
    <t id="9390">Muestra una instantÃ¡nea Ãºnica del hub comercial centralizado (colas del planificador + estado del Ãºltimo barco solicitante) en el registro y como notificaciÃ³n.</t>
    <t id="9292">Volcado de la CachÃ© Comercial (COMPLETO):</t>
    <t id="9293">VOLCAR CACHÃ‰</t>
    <t id="9392">Volcado COMPLETO de la cachÃ© (puede ser enorme). Escribe todas las entradas de la cachÃ© en el DebugLog en fragmentos. Haz clic de nuevo para cancelar.</t>
    <t id="9294">Borrar reservas de flota:</t>
    <t id="9295">CLARO</t>
    <t id="9394">Borra todas las reservas comerciales de flotas activas. UtilÃ­zalo si los barcos parecen atascados esperando que caduquen los intercambios reservados, o si la tabla de reservas se ha vuelto obsoleta despuÃ©s de cargar un guardado antiguo.</t>
    <t id="9230">ActuaciÃ³n</t>
    <t id="9231">Retraso en el procesamiento por lotes:</t>
    <t id="9232">Retraso de ValidaciÃ³n:</t>
    <t id="9233">BÃºsquedas SimultÃ¡neas MÃ¡x:</t>
    <t id="9234">Comercios MÃ¡x a Retornar:</t>
    <t id="9235">Ofertas MÃ¡x por MercancÃ­a:</t>
    <t id="9236">Comercios MÃ¡x por MercancÃ­a:</t>
    <t id="9237">Ofertas MÃ¡x por MercancÃ­a para Correspondencia:</t>
    <t id="9238">Umbral de salida anticipada:</t>
    <t id="9241">Intervalo de porciÃ³n de oferta en vivo:</t>
    <t id="9266">TTL del Bloqueo de BÃºsqueda:</t>
    <t id="9263">TamaÃ±o de Lote de Procesamiento:</t>
    <t id="9239">Formato de NÃºmeros</t>
    <t id="9240">Estilo de formato:</t>
    <t id="9242">Utilice el sufijo M</t>
    <t id="9243">Umbral de sufijo M:</t>
    <t id="9244">AlemÃ¡n (123.456,78)</t>
    <t id="9245">InglÃ©s (123,456.78)</t>
    <t id="9510">Notificaciones de subida de nivel:</t>
    <t id="9511">Alertas de formaciÃ³n requerida:</t>
    <t id="9512">Notificaciones de formaciÃ³n completada:</t>
    <t id="9513">Informes de beneficios:</t>
    <t id="9514">Alertas de mercado:</t>
    <t id="9515">Actualizaciones de flota:</t>
    <t id="9516">Utilice vainilla XP Ãºnicamente</t>
    <t id="9610">Activar o desactivar las notificaciones emergentes de subida de nivel del comerciante en la interfaz del jugador.</t>
    <t id="9611">Alerta cuando los pilotos necesitan formaciÃ³n para avanzar al siguiente nivel.</t>
    <t id="9612">Notificar cuando los pilotos completan la formaciÃ³n y ascienden de rango.</t>
    <t id="9613">ResÃºmenes de beneficios periÃ³dicos (informes simples y completos).</t>
    <t id="9614">Oportunidades de mercado excepcionales y alertas de comercio de alto valor.</t>
    <t id="9615">Mensajes de coordinaciÃ³n de flota y actualizaciones de estado.</t>
    <t id="9616">Utilice pilot.skill.piloting y desactive GT XP progresiÃ³n/caps.</t>
    <t id="9246">Frecuencia de informe simple:</t>
    <t id="9247">Frecuencia de informes completos:</t>
    <t id="9248">BÃºsquedas Cache SimultÃ¡neas MÃ¡x:</t>
    <t id="9249">BÃºsquedas Live SimultÃ¡neas MÃ¡x:</t>
    <t id="9340">Elija el formato de nÃºmero: El alemÃ¡n usa '.' para miles y ',' para decimales (123.456,78), el inglÃ©s usa ',' para miles y '.' para decimales (123,456.78)</t>
    <t id="9342">Habilitar sufijo M para nÃºmeros mayores que el umbral (por ejemplo, 1.0 M en lugar de 1,000,000)</t>
    <t id="9343">Umbral para el sufijo M. Los nÃºmeros por encima de este valor se mostrarÃ¡n con el sufijo M (predeterminado: 999,999)</t>
    <t id="9346">Frecuencia del informe simple (notificaciÃ³n emergente): 0-30 minutos (0 = desactivado - los informes simples estÃ¡n desactivados, por defecto: 1 minuto)</t>
    <t id="9347">Frecuencia del informe completo (entrada en diario): 0-60 minutos (0 = desactivado - los informes completos estÃ¡n desactivados, por defecto: 30 minutos)</t>
    <t id="9398">Utilice la anulaciÃ³n de crÃ©ditos GT vencidos</t>
    <t id="9399">Reemplace o aumente la lÃ­nea bÃ¡sica "CR debido a intercambios" con el valor proyectado de GT en el mismo espacio de la interfaz de usuario.</t>
    <t id="9331">Retraso entre lotes durante el procesamiento de bÃºsqueda comercial (1-100ms). Valores mÃ¡s altos reducen la carga de CPU pero ralentizan las bÃºsquedas comerciales. Predeterminado: 50ms. Usado en el procesador de lotes y filtrado de lista comercial.</t>
    <t id="9332">Retraso entre validaciones de comercio en el script AI (1-100ms). Valores mÃ¡s altos reducen la carga de CPU pero ralentizan la validaciÃ³n de comercio. Predeterminado: 50ms. Usado al validar la lista comercial del sistema MD.</t>
    <t id="9333">NÃºmero mÃ¡ximo de bÃºsquedas comerciales que pueden ejecutarse simultÃ¡neamente (1-10). Valores mÃ¡s bajos reducen la carga de CPU pero aumentan los tiempos de espera en cola. Valores mÃ¡s altos procesan bÃºsquedas mÃ¡s rÃ¡pido pero pueden causar picos de rendimiento. Predeterminado: 1.</t>
    <t id="9334">NÃºmero mÃ¡ximo de comercios a retornar de la bÃºsqueda en cachÃ© (50-1000). Valores mÃ¡s altos proporcionan mÃ¡s opciones comerciales pero aumentan el tiempo de procesamiento. Valores mÃ¡s bajos reducen la carga de CPU pero pueden perder comercios rentables. Predeterminado: 200.</t>
    <t id="9335">NÃºmero mÃ¡ximo de ofertas por mercancÃ­a para procesar en bÃºsqueda en vivo (5-100). Valores mÃ¡s altos consideran mÃ¡s ofertas pero aumentan el tiempo de procesamiento. Valores mÃ¡s bajos reducen la carga de CPU pero pueden perder comercios rentables. Predeterminado: 20.</t>
    <t id="9336">NÃºmero mÃ¡ximo de comercios por mercancÃ­a durante el procesamiento por lotes (5-100). Valores mÃ¡s altos permiten mÃ¡s comercios por mercancÃ­a pero aumentan el tiempo de procesamiento. Valores mÃ¡s bajos reducen la carga de CPU pero pueden perder comercios rentables. Predeterminado: 20.</t>
    <t id="9337">NÃºmero mÃ¡ximo de ofertas por mercancÃ­a para correspondencia en el procesador de lotes (5-100). Valores mÃ¡s altos consideran mÃ¡s ofertas pero aumentan el tiempo de procesamiento. Valores mÃ¡s bajos reducen la carga de CPU pero pueden perder comercios rentables. Predeterminado: 20.</t>
    <t id="9338">Umbral de salida temprana para procesamiento por lotes (100-10000). Cuando se encuentran esta cantidad de comercios, el procesamiento por lotes se detiene temprano para ahorrar CPU. Valores mÃ¡s altos procesan mÃ¡s comercios pero aumentan la carga de CPU. Valores mÃ¡s bajos salen antes pero pueden perder comercios rentables. Predeterminado: 2000.</t>
    <t id="9341">Intervalo de rebanada de ofertas en vivo en milisegundos (5-500ms). Controla con quÃ© frecuencia pueden comenzar las rebanadas de ofertas en vivo. Valores mÃ¡s bajos permiten una recolecciÃ³n de ofertas mÃ¡s rÃ¡pida pero aumentan la carga de CPU. Valores mÃ¡s altos reducen la carga de CPU pero ralentizan el procesamiento de bÃºsqueda en vivo. Predeterminado: 500ms.</t>
    <t id="9363">TamaÃ±o de lote de procesamiento (5-20). Procesa chunkSizeÃ—chunkSize combinaciones por lote (por ejemplo, 10Ã—10 = 100 combinaciones). Lotes mÃ¡s grandes mejoran el rendimiento pero aumentan la carga de CPU por lote. Lotes mÃ¡s pequeÃ±os reducen los picos de CPU pero requieren mÃ¡s continuaciones. Predeterminado: 10.</t>
    <t id="9348">NÃºmero mÃ¡ximo de bÃºsquedas en cachÃ© que pueden ejecutarse simultÃ¡neamente (1-20). Las bÃºsquedas en cachÃ© son rÃ¡pidas y econÃ³micas, por lo que valores mÃ¡s altos permiten mÃ¡s verificaciones de cachÃ© paralelas sin impacto significativo en CPU. Valores mÃ¡s bajos reducen las bÃºsquedas de cachÃ© paralelas. Predeterminado: 5.</t>
    <t id="9349">NÃºmero mÃ¡ximo de bÃºsquedas en vivo que pueden ejecutarse simultÃ¡neamente (1-10). Las bÃºsquedas en vivo son intensivas en CPU, por lo que valores mÃ¡s bajos reducen la carga de CPU pero aumentan los tiempos de espera en cola. Valores mÃ¡s altos procesan bÃºsquedas mÃ¡s rÃ¡pido pero pueden causar picos de rendimiento. Predeterminado: 1.</t>
    <t id="9264">TamaÃ±o de Lote de Consulta de CachÃ©:</t>
    <t id="9265">TamaÃ±o de Lote de AnexiÃ³n de Ofertas en Vivo:</t>
    <t id="9364">Entradas de cachÃ© validadas por lote (10-200). Valores mÃ¡s pequeÃ±os distribuyen la validaciÃ³n del cachÃ© en mÃ¡s frames (mÃ¡s suave) pero pueden aumentar el tiempo para encontrar un comercio en cachÃ©. Predeterminado: 10.</t>
    <t id="9365">Ofertas anexadas por rebanada de anexiÃ³n (50-2000). Valores mÃ¡s pequeÃ±os reducen el trabajo de anexiÃ³n de lista por frame (mÃ¡s suave) pero pueden ralentizar la finalizaciÃ³n de la bÃºsqueda en vivo. Predeterminado: 200.</t>
    <t id="9366">Tiempo de vida del bloqueo de bÃºsqueda en segundos (60-7200). Si una nave es denegada con "bÃºsqueda comercial ya en progreso" por mÃ¡s tiempo que esto, GT se auto-sanarÃ¡ limpiando el estado de bÃºsqueda obsoleto y liberando el bloqueo. Predeterminado: 600s.</t>
    <t id="9370">Umbral Suave de ContrapresiÃ³n por Lotes:</t>
    <t id="9371">Umbral Duro de ContrapresiÃ³n por Lotes:</t>
    <t id="9372">Sectores por sector:</t>
    <t id="9373">Tiempo de Espera de ActualizaciÃ³n Sector Hogar:</t>
    <t id="9374">Tiempo de Espera Base tras Fallo de CachÃ©:</t>
    <t id="9375">Intervalo de tic del programador:</t>
    <t id="9376">Consultas CachÃ© MÃ¡x. por Tic:</t>
    <t id="9377">Continuaciones BÃºsqueda MÃ¡x. por Tic:</t>
    <t id="9378">Naves MÃ¡x. por Tic:</t>
    <t id="9379">Elementos MÃ¡x. por Tic:</t>
    <t id="9380">Despertados MÃ¡x. por Tic:</t>
    <t id="9381">Entradas MÃ¡x. Consulta CachÃ©:</t>
    <t id="9382">Segundos de umbral obsoletos:</t>
    <t id="9383">Segundos de umbral de cola obsoleta:</t>
    <t id="9384">ExpiraciÃ³n Fallos Comercio en Segundos:</t>
    <t id="9385">BÃºsquedas de Respaldo SimultÃ¡neas MÃ¡x.:</t>
    <t id="9386">BÃºsquedas de Respaldo SimultÃ¡neas MÃ¡x.:</t>
    <t id="9470">Umbral suave para la cola del procesador por lotes (5-50). Cuando la cola alcanza este valor, comienza a aplicarse contrapresiÃ³n para ralentizar nuevas solicitudes de bÃºsqueda. Valores mÃ¡s bajos activan la contrapresiÃ³n antes (mÃ¡s conservador). Predeterminado: 10.</t>
    <t id="9471">Umbral duro para la cola del procesador por lotes (10-100). Cuando la cola alcanza este valor, las nuevas bÃºsquedas en vivo se bloquean hasta que la cola disminuya. Valores mÃ¡s bajos bloquean las bÃºsquedas antes (mÃ¡s conservador). Predeterminado: 25.</t>
    <t id="9472">Sectores procesados por segmento en la recolecciÃ³n de ofertas en vivo (1-5). Valores mÃ¡s bajos distribuyen el trabajo en mÃ¡s frames (mÃ¡s suave) pero pueden ralentizar la recolecciÃ³n de ofertas. Valores mÃ¡s altos procesan mÃ¡s rÃ¡pido pero pueden causar picos de frame. Predeterminado: 1.</t>
    <t id="9473">Tiempo de espera tras completar la actualizaciÃ³n del sector hogar (10-120 segundos). Previene solicitudes de actualizaciÃ³n excesivas. Valores mÃ¡s bajos permiten actualizaciones mÃ¡s frecuentes pero aumentan la carga de CPU. Valores mÃ¡s altos reducen la frecuencia de actualizaciÃ³n pero pueden retrasar las actualizaciones de cachÃ©. Predeterminado: 30s.</t>
    <t id="9474">Tiempo de espera base tras un fallo de cachÃ© antes de reintentar bÃºsqueda en vivo (1-30 segundos). Previene intentos de reintento excesivos. Valores mÃ¡s bajos reintentan antes pero aumentan la carga de CPU. Valores mÃ¡s altos reducen la frecuencia de reintento pero pueden retrasar la bÃºsqueda de intercambios. Predeterminado: 10s.</t>
    <t id="9475">Intervalo entre tics del planificador en milisegundos (50-500ms). Controla la frecuencia con la que el planificador procesa la cola de trabajo. Valores mÃ¡s bajos procesan con mÃ¡s frecuencia pero aumentan la carga de CPU. Valores mÃ¡s altos reducen la carga de CPU pero pueden aumentar los tiempos de espera en cola. Predeterminado: 100ms.</t>
    <t id="9476">NÃºmero mÃ¡ximo de consultas de cachÃ© iniciadas por tic del planificador (1-5). Limita la tasa de consultas de cachÃ© para evitar el bloqueo de frames. Valores mÃ¡s bajos reducen los picos de CPU pero ralentizan las bÃºsquedas de cachÃ©. Valores mÃ¡s altos procesan mÃ¡s rÃ¡pido pero pueden causar tartamudeo. Predeterminado: 1.</t>
    <t id="9477">NÃºmero mÃ¡ximo de continuaciones de bÃºsqueda iniciadas por tic del planificador (1-5). Limita la tasa de continuaciÃ³n para evitar el bloqueo de frames. Valores mÃ¡s bajos reducen los picos de CPU pero ralentizan el procesamiento de bÃºsqueda. Valores mÃ¡s altos procesan mÃ¡s rÃ¡pido pero pueden causar tartamudeo. Predeterminado: 1.</t>
    <t id="9478">NÃºmero mÃ¡ximo de naves procesadas por tic del planificador (1-5). Limita la tasa de procesamiento de naves para evitar el bloqueo de frames. Valores mÃ¡s bajos reducen los picos de CPU pero ralentizan el procesamiento de cola. Valores mÃ¡s altos procesan mÃ¡s rÃ¡pido pero pueden causar tartamudeo. Predeterminado: 1.</t>
    <t id="9479">NÃºmero mÃ¡ximo de elementos de trabajo procesados por tic del planificador (1-5). Limita la tasa de procesamiento de elementos para evitar el bloqueo de frames. Valores mÃ¡s bajos reducen los picos de CPU pero ralentizan el procesamiento de cola. Valores mÃ¡s altos procesan mÃ¡s rÃ¡pido pero pueden causar tartamudeo. Predeterminado: 1.</t>
    <t id="9480">NÃºmero mÃ¡ximo de esperas despertadas por tic del planificador (1-10). Limita la tasa de despertar para evitar picos de CPU cuando muchas esperas estÃ¡n en cola. Valores mÃ¡s bajos reducen los picos de CPU pero ralentizan el procesamiento de esperas. Valores mÃ¡s altos procesan mÃ¡s rÃ¡pido pero pueden causar tartamudeo. Predeterminado: 2.</t>
    <t id="9481">NÃºmero mÃ¡ximo de entradas de cachÃ© consultadas por lote (1-200). Controla el tamaÃ±o del lote de consulta de cachÃ©. Valores mÃ¡s bajos hacen las bÃºsquedas de cachÃ© mÃ¡s rÃ¡pidas pero pueden perder mejores intercambios. Valores mÃ¡s altos consideran mÃ¡s intercambios en cachÃ© pero aumentan el tiempo de validaciÃ³n. Predeterminado: 50.</t>
    <t id="9482">Umbral de obsolescencia del estado de bÃºsqueda en vivo en segundos (60-600). Cuando el estado de bÃºsqueda en vivo es mÃ¡s antiguo que este valor, se considera obsoleto y se limpia. Valores mÃ¡s bajos limpian el estado obsoleto antes pero pueden interrumpir bÃºsquedas legÃ­timas. Valores mÃ¡s altos permiten bÃºsquedas mÃ¡s largas pero pueden dejar estado obsoleto. Predeterminado: 300s.</t>
    <t id="9483">Umbral de obsolescencia de elementos de cola en segundos (30-300). Cuando los elementos de cola son mÃ¡s antiguos que este valor, se consideran obsoletos y se eliminan. Valores mÃ¡s bajos limpian los elementos obsoletos antes pero pueden eliminar elementos de cola legÃ­timos. Valores mÃ¡s altos permiten tiempos de cola mÃ¡s largos pero pueden dejar elementos obsoletos. Predeterminado: 60s.</t>
    <t id="9484">ExpiraciÃ³n del cachÃ© de intercambios fallidos en segundos (300-3600). Los intercambios fallidos se almacenan en cachÃ© para evitar reintentar inmediatamente. Valores mÃ¡s bajos expiran los intercambios fallidos antes (mÃ¡s reintentos) pero reducen la efectividad del cachÃ©. Valores mÃ¡s altos almacenan en cachÃ© por mÃ¡s tiempo (menos reintentos) pero pueden retrasar los intentos de reintento. Predeterminado: 1800s (30 minutos).</t>
    <t id="9485">NÃºmero mÃ¡ximo de bÃºsquedas en vivo de respaldo simultÃ¡neas (1-10). Las bÃºsquedas de respaldo omiten el bloqueo del sector hogar, permitiendo que mÃºltiples naves del mismo sector hogar busquen simultÃ¡neamente. Valores mÃ¡s bajos reducen la carga de CPU pero pueden ralentizar las bÃºsquedas de respaldo. Valores mÃ¡s altos permiten mÃ¡s bÃºsquedas de respaldo paralelas pero aumentan el uso de CPU. Predeterminado: 1.</t>
    <t id="9490">Retraso de seÃ±al encontrada comercial:</t>
    <t id="9590">Retraso antes de enviar la seÃ±al GT_Trade_Found a las naves en milisegundos (10-1000ms). Las naves siempre esperan (retraso configurado + bÃºfer de 5ms) antes de enviar nuevas solicitudes para capturar seÃ±ales retrasadas. Valores mÃ¡s altos distribuyen seÃ±ales entre frames para un rendimiento mÃ¡s suave. Predeterminado: 10ms.</t>
    <t id="8000">Flota GalaxyTrader</t>
    <t id="8001">GestiÃ³n de flota GalaxyTrader y estadÃ­sticas de pilotos</t>
    <t id="8002">Ver y administrar todos los pilotos de GalaxyTrader</t>
    <t id="8100">ID del barco</t>
    <t id="8101">Piloto</t>
    <t id="8102">Barco</t>
    <t id="8103">Estado</t>
    <t id="8104">Rango</t>
    <t id="8105">Nivel</t>
    <t id="8106">experiencia</t>
    <t id="8107">Beneficio de por vida</t>
    <t id="8108">UbicaciÃ³n</t>
    <t id="8109">Base de operaciones</t>
    <t id="8110">Ãšltimo Comercio</t>
    <t id="8111">Beneficio piloto</t>
    <t id="8112">Beneficio del barco</t>
    <t id="8113">Conteo comercial</t>
    <t id="8200">Refrescar</t>
    <t id="8201">Exportar CSV</t>
    <t id="8202">EstadÃ­sticas</t>
    <t id="8203">ConfiguraciÃ³n</t>
    <t id="8204">Ayuda</t>
    <t id="8205">Cerca</t>
    <t id="8300">Todos los pilotos</t>
    <t id="8301">Comercio</t>
    <t id="8302">CapacitaciÃ³n</t>
    <t id="8303">Mantenimiento</t>
    <t id="8304">Emergencia</t>
    <t id="8305">Principiantes (Niveles 1-5)</t>
    <t id="8306">Avanzado (Nivel 6-11)</t>
    <t id="8307">Expertos (Nivel 12+)</t>
    <t id="8308">Los 10 principales ganadores</t>
    <t id="8350">Ordenar por:</t>
    <t id="8351">ID del barco</t>
    <t id="8352">Nombre del piloto</t>
    <t id="8353">Tipo de barco</t>
    <t id="8354">Estado</t>
    <t id="8355">Rango</t>
    <t id="8356">Nivel</t>
    <t id="8357">experiencia</t>
    <t id="8358">Ganancia</t>
    <t id="8400">No hay pilotos registrados.</t>
    <t id="8401">NingÃºn piloto coincide con el filtro</t>
    <t id="8402">Pilotos totales:</t>
    <t id="8403">Beneficio total de la flota:</t>
    <t id="8404">Ãšltima actualizaciÃ³n:</t>
    <t id="8405">Buscar pilotos...</t>
    <t id="8114">Sector</t>
    <t id="8320">Cambio de nombre del barco</t>
    <t id="8321">Nombre personalizado</t>
    <t id="8322">Establecer nombre</t>
    <t id="8323">Borrar nombre</t>
    <t id="8324">Nombre configurado correctamente</t>
    <t id="8325">Nombre borrado exitosamente</t>
    <t id="8450">Enviar a CapacitaciÃ³n</t>
    <t id="8451">Darse de baja</t>
    <t id="8452">Forzar la venta de carga</t>
    <t id="8453">Enviar a ReparaciÃ³n</t>
    <t id="8454">Enviar a reabastecimiento</t>
    <t id="8455">Detener Todas las Ã“rdenes</t>
    <t id="8456">Comportamiento</t>
    <t id="8500">Haga clic para ordenar por ID de envÃ­o</t>
    <t id="8501">Haga clic para ordenar por nombre del piloto</t>
    <t id="8502">Haga clic para ordenar por tipo de envÃ­o</t>
    <t id="8503">Haga clic para ordenar por estado</t>
    <t id="8504">Haga clic para ordenar por rango</t>
    <t id="8505">Haga clic para ordenar por nivel</t>
    <t id="8506">Haga clic para ordenar por XP</t>
    <t id="8507">Haga clic para ordenar por beneficio de por vida</t>
    <t id="8508">Actualizar los datos del piloto del sistema de misiÃ³n.</t>
    <t id="8509">Exportar la vista actual a un archivo CSV</t>
    <t id="8510">Ver estadÃ­sticas y grÃ¡ficos de la flota</t>
    <t id="8511">Configurar ajustes del menÃº</t>
    <t id="8512">Mostrar ayuda y atajos de teclado</t>
    <t id="8600">No se encontraron pilotos de GalaxyTrader</t>
    <t id="8601">Cree pilotos asignando barcos a GalaxyTrader o espere a que se carguen los datos.</t>
    <t id="9001">Cambiar nombre GT</t>
    <t id="9902">Enviar a CapacitaciÃ³n</t>
    <t id="9903">Entrenamiento manual en cola para %1. El piloto comenzarÃ¡ a entrenar despuÃ©s del ciclo actual.</t>
    <t id="9904">Entrenamiento en cola despuÃ©s del ciclo actual</t>
    <t id="9905">Piloto o barco no encontrado</t>
    <t id="9906">AutoTraining estÃ¡ habilitado: no se requiere cola manual</t>
    <t id="9907">El piloto no tiene bloqueado el entrenamiento.</t>
    <t id="9910">Academia de Comercio</t>
    <t id="9911">Aprendiz (Nvl 4) - %1 / %2</t>
    <t id="9912">Comerciante (Nvl 7) - %1 / %2</t>
    <t id="9913">Maestro Comerciante (Nvl 13) - %1 / %2</t>
    <t id="9920">Piloto %1 inscrito en el curso de Academia para Nivel %2. Despegando hacia la estaciÃ³n comercial mÃ¡s cercana.</t>
    <t id="9921">Fondos insuficientes para este curso (se necesitan %1, disponibles %2).</t>
    <t id="9922">Curso no disponible - el piloto %1 ya estÃ¡ en este nivel o por encima.</t>
    <t id="9923">Piloto %1 inscrito en el curso Nivel %2 de la Academia de Comercio (coste: %3 Cr, duraciÃ³n: %4 min) a bordo de %5.</t>
    <t id="11011">Reductor de buque mediano GT Apprentice</t>
    <t id="11012">ModificaciÃ³n de motor que reduce ligeramente el rendimiento para pilotos inexpertos en naves medianas. Usado por el sistema AI GalaxyTrader. -5% velocidad, empuje y rotaciÃ³n.</t>
    <t id="11013">Reductor de viaje mediano GT Apprentice</t>
    <t id="11014">ModificaciÃ³n de motor que reduce ligeramente el rendimiento de viaje para pilotos inexpertos en naves medianas. Usado por el sistema AI GalaxyTrader. -5% velocidad de viaje.</t>
    <t id="11021">Reductor de barco grande GT Apprentice</t>
    <t id="11022">ModificaciÃ³n de motor que reduce el rendimiento para pilotos inexpertos en naves grandes. Usado por el sistema AI GalaxyTrader. -15% velocidad, empuje y rotaciÃ³n.</t>
    <t id="11023">Reductor de viaje grande GT Apprentice</t>
    <t id="11024">ModificaciÃ³n de motor que reduce el rendimiento de viaje para pilotos inexpertos en naves grandes. Usado por el sistema AI GalaxyTrader. -15% velocidad de viaje.</t>
    <t id="11031">Reductor de buque capital GT Apprentice</t>
    <t id="11032">ModificaciÃ³n de motor que reduce significativamente el rendimiento para pilotos inexpertos en naves capitales. Usado por el sistema AI GalaxyTrader. -25% velocidad, empuje y rotaciÃ³n.</t>
    <t id="11033">Reductor de viajes GT Apprentice Capital</t>
    <t id="11034">ModificaciÃ³n de motor que reduce significativamente el rendimiento de viaje para pilotos inexpertos en naves capitales. Usado por el sistema AI GalaxyTrader. -25% velocidad de viaje.</t>
    <t id="12001">GT Mejorador de Nave PequeÃ±a BÃ¡sico</t>
    <t id="12002">ModificaciÃ³n de motor especializada para naves pequeÃ±as con pilotos certificados bÃ¡sicos. Usado por el sistema AI GalaxyTrader. +3% velocidad, empuje y rotaciÃ³n.</t>
    <t id="12003">GT Mejorador de Viaje PequeÃ±o BÃ¡sico</t>
    <t id="12004">ModificaciÃ³n de motor especializada para naves pequeÃ±as con pilotos certificados bÃ¡sicos. Usado por el sistema AI GalaxyTrader. +3% velocidad de viaje.</t>
    <t id="13001">GT Reductor de Nave Grande BÃ¡sico</t>
    <t id="13002">ModificaciÃ³n de motor especializada para naves grandes con pilotos certificados bÃ¡sicos. Usado por el sistema AI GalaxyTrader. -8% velocidad, empuje y rotaciÃ³n.</t>
    <t id="13003">GT Reductor de Viaje Grande BÃ¡sico</t>
    <t id="13004">ModificaciÃ³n de motor especializada para naves grandes con pilotos certificados bÃ¡sicos. Usado por el sistema AI GalaxyTrader. -8% velocidad de viaje.</t>
    <t id="14001">GT Reductor de Nave Capital BÃ¡sico</t>
    <t id="14002">ModificaciÃ³n de motor especializada para naves capitales con pilotos certificados bÃ¡sicos. Usado por el sistema AI GalaxyTrader. -15% velocidad, empuje y rotaciÃ³n.</t>
    <t id="14003">GT Reductor de Viaje Capital BÃ¡sico</t>
    <t id="14004">ModificaciÃ³n de motor especializada para naves capitales con pilotos certificados bÃ¡sicos. Usado por el sistema AI GalaxyTrader. -15% velocidad de viaje.</t>
    <t id="15001">GT Mejorador de Nave PequeÃ±a Experto</t>
    <t id="15002">ModificaciÃ³n de motor avanzada para naves pequeÃ±as con pilotos expertos. Usado por el sistema AI GalaxyTrader. +25% velocidad, empuje y rotaciÃ³n.</t>
    <t id="15003">GT Mejorador de Viaje PequeÃ±o Experto</t>
    <t id="15004">ModificaciÃ³n de motor avanzada para naves pequeÃ±as con pilotos expertos. Usado por el sistema AI GalaxyTrader. +25% velocidad de viaje.</t>
    <t id="16001">Mejorador de barcos grandes GT Expert</t>
    <t id="16002">ModificaciÃ³n de motor avanzada para naves grandes con pilotos expertos. Usado por el sistema AI GalaxyTrader. +15% velocidad, empuje y rotaciÃ³n.</t>
    <t id="16003">Mejorador de viaje grande GT Expert</t>
    <t id="16004">ModificaciÃ³n de motor avanzada para naves grandes con pilotos expertos. Usado por el sistema AI GalaxyTrader. +15% velocidad de viaje.</t>
    <t id="17001">Mejorador de nave capital GT Expert</t>
    <t id="17002">ModificaciÃ³n de motor avanzada para naves capitales con pilotos expertos. Usado por el sistema AI GalaxyTrader. +6% velocidad, empuje y rotaciÃ³n.</t>
    <t id="17003">Mejorador de viajes de GT Expert Capital</t>
    <t id="17004">ModificaciÃ³n de motor avanzada para naves capitales con pilotos expertos. Usado por el sistema AI GalaxyTrader. +6% velocidad de viaje.</t>
    <t id="18001">LimitaciÃ³n Severa de Habilidades (Nave)</t>
    <t id="18002">LimitaciÃ³n Severa de Habilidades (Nave) - Representa penalizaciones severas de rendimiento debido a la inexperiencia del piloto con naves grandes. Aplicada automÃ¡ticamente por el sistema GalaxyTrader cuando la habilidad del piloto es insuficiente para el tamaÃ±o de la nave. Aumenta la masa de la nave. (Solo sistema GT - No disponible para instalaciÃ³n manual)</t>
    <t id="18003">LimitaciÃ³n Moderada de Habilidades (Nave)</t>
    <t id="18004">LimitaciÃ³n Moderada de Habilidades (Nave) - Representa penalizaciones moderadas de rendimiento mientras el piloto se adapta a la complejidad de la nave. Aplicada automÃ¡ticamente por el sistema GalaxyTrader cuando la habilidad del piloto es insuficiente para el tamaÃ±o de la nave. Aumenta la masa de la nave. (Solo sistema GT - No disponible para instalaciÃ³n manual)</t>
    <t id="18005">LimitaciÃ³n Leve de Habilidades (Nave)</t>
    <t id="18006">LimitaciÃ³n Leve de Habilidades (Nave) - Representa penalizaciones menores de rendimiento durante el desarrollo de habilidades del piloto. Aplicada automÃ¡ticamente por el sistema GalaxyTrader cuando la habilidad del piloto es insuficiente para el tamaÃ±o de la nave. Aumenta la masa de la nave. (Solo sistema GT - No disponible para instalaciÃ³n manual)</t>
    <t id="18007">LimitaciÃ³n Severa de Habilidades (Motor)</t>
    <t id="18008">LimitaciÃ³n Severa de Habilidades (Motor) - Representa penalizaciones severas de rendimiento debido a la inexperiencia del piloto con naves grandes. Aplicada automÃ¡ticamente por el sistema GalaxyTrader cuando la habilidad del piloto es insuficiente para el tamaÃ±o de la nave. Reduce el empuje y la rotaciÃ³n del motor. (Solo sistema GT - No disponible para instalaciÃ³n manual)</t>
    <t id="18009">LimitaciÃ³n Moderada de Habilidades (Motor)</t>
    <t id="18010">LimitaciÃ³n Moderada de Habilidades (Motor) - Representa penalizaciones moderadas de rendimiento mientras el piloto se adapta a la complejidad de la nave. Aplicada automÃ¡ticamente por el sistema GalaxyTrader cuando la habilidad del piloto es insuficiente para el tamaÃ±o de la nave. Reduce el empuje y la rotaciÃ³n del motor. (Solo sistema GT - No disponible para instalaciÃ³n manual)</t>
    <t id="18011">LimitaciÃ³n Leve de Habilidades (Motor)</t>
    <t id="18012">LimitaciÃ³n Leve de Habilidades (Motor) - Representa penalizaciones menores de rendimiento durante el desarrollo de habilidades del piloto. Aplicada automÃ¡ticamente por el sistema GalaxyTrader cuando la habilidad del piloto es insuficiente para el tamaÃ±o de la nave. Reduce el empuje y la rotaciÃ³n del motor. (Solo sistema GT - No disponible para instalaciÃ³n manual)</t>
    <t id="9250">DenominaciÃ³n del Estado de la Nave</t>
    <t id="9350">Personalizar las abreviaciones del estado de la nave. Los valores predeterminados se muestran en los cuadros de entrada y pueden ser sobrescritos. MÃ¡ximo 3 caracteres. Todos los nombres de las naves se actualizarÃ¡n automÃ¡ticamente cuando se cambien.</t>
    <t id="9251">Abreviatura del estado de reabastecimiento:</t>
    <t id="9252">Abreviatura Estado ReparaciÃ³n:</t>
    <t id="9253">Abreviatura del estado de mantenimiento:</t>
    <t id="9254">Abreviatura del estado de formaciÃ³n:</t>
    <t id="9255">Abreviatura Estado RedirecciÃ³n:</t>
    <t id="9256">Abreviatura Estado AutorizaciÃ³n:</t>
    <t id="9257">Abreviatura del estado bloqueado:</t>
    <t id="9258">Abreviatura del estado alternativo:</t>
    <t id="9259">Abreviatura de estado aislado:</t>
    <t id="9260">Abreviatura del estado comercial:</t>
    <t id="9261">Abreviatura de estado inactivo:</t>
    <t id="9262">Abreviatura del estado de escape:</t>
    <t id="9268">Abreviatura de estado inalcanzable:</t>
    <t id="9269">Abreviatura del estado de intercambio piloto:</t>
    <t id="9270">Etiqueta de prefijo de lista negra personalizada:</t>
    <t id="9700">TRUCOS (roto. no hay nada que ver aqui!! de verdad!!)</t>
    <t id="9701">Naves GT invulnerables</t>
    <t id="9702">Todas las naves del jugador invulnerables</t>
    <t id="9800">Siga de largo, piloto. Herramientas de prueba rotas, no un menu divertido. Nada que ver aqui. De verdad. Ha sido advertido. Probablemente.</t>
    <t id="9801">Las naves con orden GalaxyTrader no pueden bajar del 100% de casco o escudos. Pulse de nuevo para desactivar.</t>
    <t id="9802">Todas las naves del jugador no pueden bajar del 100% de casco o escudos. Pulse de nuevo para desactivar. Las estaciones no se ven afectadas.</t>
    <t id="9703">Revelar universo para pruebas GT</t>
    <t id="9704">Revelado</t>
    <t id="9705">Revelar</t>
    <t id="9803">Revela la niebla de guerra de todos los sectores, marca todas las estaciones como conocidas, concede todas las licencias de suscripcion comercial y suscribe ofertas comerciales en toda la galaxia. Pulse de nuevo tras nuevos sectores DLC. Solo para pruebas.</t>
    <t id="9706">Maximizar XP de pilotos GT registrados</t>
    <t id="9707">Maximizado</t>
    <t id="9708">XP max</t>
    <t id="9804">Establece nivel 15 y XP max para cada piloto del registro GT. Elimina bloqueos de entrenamiento. Se omite si solo XP vanilla esta activo. Solo para pruebas.</t>
    <t id="9351">Abreviatura de estado de reabastecimiento (predeterminado: RS)</t>
    <t id="9352">Abreviatura para el estado ReparaciÃ³n (predeterminado: RP)</t>
    <t id="9353">Abreviatura de estado de mantenimiento (predeterminado: MT)</t>
    <t id="9354">Abreviatura de Estado de entrenamiento (predeterminado: TR)</t>
    <t id="9355">Abreviatura para el estado RedirecciÃ³n (predeterminado: RR)</t>
    <t id="9356">Abreviatura para el estado AutorizaciÃ³n (predeterminado: CL)</t>
    <t id="9357">Abreviatura de Estado bloqueado (predeterminado: BL)</t>
    <t id="9358">Abreviatura de estado de reserva (predeterminado: FB)</t>
    <t id="9359">Abreviatura de estado aislado (predeterminado: IS)</t>
    <t id="9360">Abreviatura de Estado comercial (predeterminado: TD)</t>
    <t id="9361">Abreviatura de Estado inactivo (predeterminado: ID)</t>
    <t id="9362">Abreviatura de Estado de escape (predeterminado: ES)</t>
    <t id="9367">Abreviatura de estado inalcanzable (predeterminado: UR)</t>
    <t id="9368">Abreviatura de estado de intercambio piloto (predeterminado: PE)</t>
    <t id="9369">Se muestra como prefijo para MK3 barcos afectados por una lista negra de facciones personalizada (incluidos los subordinados). Predeterminado: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Comerciante de estaciones: vende productos de la estaciÃ³n a facciones de NPC</t>
    <t id="30010">EstaciÃ³n de inicio</t>
    <t id="30011">Distancia mÃ¡xima de venta</t>
    <t id="30012">Ignorar las reglas comerciales</t>
    <t id="30013">Filtro de artÃ­culos</t>
    <t id="30014">% objetivo de llenado de carga de venta</t>
    <t id="30015">Tolerancia de retroceso</t>
    <t id="30016">% objetivo de llenado de carga de compra</t>
    <t id="30017">Entradas del libro de registro</t>
    <t id="30018">Nivel de notificaciÃ³n</t>
    <t id="30019">CoordinaciÃ³n de flota</t>
    <t id="30020">Nivel de depuraciÃ³n</t>
    <t id="30021">EstaciÃ³n de suministro</t>
    <t id="30022">% mÃ­nimo de almacenamiento en la estaciÃ³n</t>
    <t id="30023">Permitir mercancÃ­as ilegales</t>
    <t id="30024">Carga/Beneficio</t>
    <t id="30025">Permitir multioperaciÃ³n</t>
    <t id="30110">EstaciÃ³n de jugador desde la que vender productos (se requiere asignaciÃ³n de estaciÃ³n)</t>
    <t id="30111">Distancia mÃ¡xima de puerta para encontrar compradores NPC (limitada por la habilidad del piloto)</t>
    <t id="30112">Ignora las restricciones comerciales de la estaciÃ³n: vende a cualquier facciÃ³n amiga independientemente de las reglas comerciales de la estaciÃ³n.</t>
    <t id="30113">Filtro de vajilla opcional; dÃ©jelo vacÃ­o para vender todos los productos y artÃ­culos comerciales de la estaciÃ³n</t>
    <t id="30114">Porcentaje mÃ­nimo de llenado de carga antes de partir en viajes de venta</t>
    <t id="30115">MÃ¡ximos saltos adicionales permitidos al agregar una segunda mercancÃ­a a un viaje (0 = solo compradores directamente en la ruta)</t>
    <t id="30116">Llenado de carga objetivo para recorridos de suministro (objetivo fÃ¡cil, el comerciante puede partir antes)</t>
    <t id="30117">Habilitar entradas del libro de registro por operaciÃ³n</t>
    <t id="30118">Nivel de notificaciÃ³n: 0=Silencioso, 1=Normal, 2=Detallado</t>
    <t id="30119">Habilitar la coordinaciÃ³n de flotas y el sistema de reservas comerciales.</t>
    <t id="30120">Nivel de registro de depuraciÃ³n: 0=Desactivado, 1=Normal, 2=Detallado</t>
    <t id="30121">Cuando estÃ© habilitado, tambiÃ©n compre recursos para la estaciÃ³n. El suministro tiene prioridad cuando el almacenamiento cae por debajo del umbral mÃ­nimo</t>
    <t id="30122">Cuando cualquier recurso cae por debajo de este porcentaje de su objetivo, la oferta tiene prioridad sobre la venta. Ignorado si la estaciÃ³n no puede permitirse recursos</t>
    <t id="30123">Permitir la venta o compra de productos ilegales o de contrabando cuando estÃ©n disponibles.</t>
    <t id="30124">SelecciÃ³n de venta: 1 = Carga (prioriza el mayor llenado del almacÃ©n por mercancÃ­a; empates por beneficio), 2 = Beneficio (mejor puntuaciÃ³n de beneficio)</t>
    <t id="30125">Permite encadenar varias ventas en un mismo ciclo (hasta 3 mercancÃ­as o destinos). DesactÃ­valo para ciclos de una sola operaciÃ³n</t>
    <t id="30200">Vendiendo %1 %2 de %3 a %4</t>
    <t id="30201">No se encontraron compradores para productos de estaciÃ³n dentro de %1 saltos</t>
    <t id="30202">EstaciÃ³n base %1 destruida: orden del comerciante de estaciÃ³n cancelada</t>
    <t id="30203">La estaciÃ³n local %1 ya no es propiedad del jugador: pedido cancelado</t>
    <t id="30204">Se requiere asignaciÃ³n de estaciÃ³n: pedido cancelado</t>
    <t id="30205">El comerciante de la estaciÃ³n MK1 comenzÃ³ en %1</t>
    <t id="30206">Venta completada: %1 %2 vendida a %3 por %4 Cr (beneficio: %5 Cr)</t>
    <t id="30207">Viaje multiservicio: entrega de %1 productos a %2 destinos</t>
    <t id="30208">Suministrando %1 %2 a %3 desde %4</t>
    <t id="30500">ConfiguraciÃ³n de GalaxyTrader MK1</t>
    <t id="30501">Valores predeterminados del comerciante de estaciones</t>
    <t id="30502">Distancia mÃ¡xima de venta predeterminada</t>
    <t id="30503">Objetivo de llenado de carga de venta predeterminado</t>
    <t id="30504">Predeterminado Ignorar reglas comerciales</t>
    <t id="30505">Tolerancia de retroceso predeterminada</t>
    <t id="30506">Tiempo de espera cuando no se encuentran operaciones</t>
    <t id="30507">Objetivo de llenado de carga de compra predeterminado</t>
    <t id="31002">Minero de galaxias</t>
    <t id="31102">MinerÃ­a autÃ³noma con suministro de estaciones y progresiÃ³n de XP</t>
    <t id="31010">EstaciÃ³n de inicio</t>
    <t id="31110">EstaciÃ³n para extraer y entregar (mutuamente excluyente con el sector inicial)</t>
    <t id="31011">Sector Hogar</t>
    <t id="31111">Sector a operar; Se utiliza cuando no hay ninguna estaciÃ³n base configurada.</t>
    <t id="31012">Canasta de recursos</t>
    <t id="31112">MercancÃ­as para la mÃ­a; vacÃ­o sigue la resoluciÃ³n de demanda de la estaciÃ³n</t>
    <t id="31013">Estaciones objetivo</t>
    <t id="31113">Filtro de estaciÃ³n opcional para entregas; vacÃ­o deriva del contexto del hogar</t>
    <t id="31014">% de umbral de desbordamiento</t>
    <t id="31114">Las estaciones que se encuentran en o por encima de este porcentaje de almacenamiento se tratan como llenas.</t>
    <t id="31015">Permitir venta desbordada a otros</t>
    <t id="31115">Cuando estÃ© habilitado y los objetivos principales estÃ©n llenos, venda a otras estaciones de facciÃ³n</t>
    <t id="31016">Asignar a la estaciÃ³n</t>
    <t id="31116">Asignar barco como subordinado minero de la estaciÃ³n base cuando corresponda</t>
    <t id="31017">Quedarse en casa</t>
    <t id="31117">Restringir la minerÃ­a/venta al Ã¡rea de origen, excepto las ejecuciones de reserva de desbordamiento</t>
    <t id="31018">Sondas de recursos de implementaciÃ³n automÃ¡tica</t>
    <t id="31118">Implemente sondas de recursos cargadas automÃ¡ticamente e incluya sondas en el reabastecimiento de mantenimiento</t>
    <t id="31019">Distancia mÃ¡xima de reuniÃ³n</t>
    <t id="31119">Distancia mÃ¡xima de puerta para reunirse (0 usa el lÃ­mite de habilidad de piloto/comandante)</t>
    <t id="31020">Distancia mÃ¡xima de venta</t>
    <t id="31120">Distancia mÃ¡xima de puerta para vender (0 usa el lÃ­mite de habilidad de piloto/comandante)</t>
    <t id="31021">Equilibrio de flota</t>
    <t id="31121">Habilite la coordinaciÃ³n de intenciones determinista para reducir el desbordamiento de la estaciÃ³n</t>
    <t id="31022">Intervalo de nueva verificaciÃ³n de demanda</t>
    <t id="31122">Con quÃ© frecuencia se ejecuta la evaluaciÃ³n de cambio/demanda del minero</t>
    <t id="31023">Delta de demanda crÃ­tica</t>
    <t id="31123">Delta de urgencia mÃ­nimo requerido para cambiar el software de minerÃ­a activo</t>
    <t id="31024">Enfriamiento mÃ­nimo del interruptor</t>
    <t id="31124">Tiempo mÃ­nimo entre dos cambios de mercancÃ­as para este barco.</t>
    <t id="31025">% mÃ­nimo de compromiso de carga</t>
    <t id="31125">Si el llenado de carga estÃ¡ por encima de esto, el barco prefiere finalizar la entrega actual antes del cambio.</t>
    <t id="31026">Delta de emergencia dura</t>
    <t id="31126">Delta de urgencia que permite el cambio inmediato a pesar del umbral de compromiso de carga</t>
    <t id="31027">Nivel de notificaciÃ³n</t>
    <t id="31127">Nivel de notificaciÃ³n: 0=Silencioso, 1=Normal, 2=Detallado</t>
    <t id="31028">Solo estaciones de reproductor</t>
    <t id="31128">Cuando estÃ¡ habilitado, solo las estaciones propiedad de los jugadores se consideran objetivos de demanda.</t>
    <t id="31031">Comprobar demanda primero</t>
    <t id="31131">Si estÃ¡ activado, el minero comprueba la demanda de las estaciones antes de extraer y prioriza los recursos en consecuencia. Si estÃ¡ desactivado, extrae del cesto de recursos sin comprobar la demanda y acumula hasta que haya un comprador (recomendado para flotas de un solo recurso).</t>
    <t id="31032">Abortar almacÃ©n fÃ­sico %</t>
    <t id="31132">Para pilotos nivel 6+: detiene la extracciÃ³n de la mercancÃ­a actual cuando el stock fÃ­sico de la estaciÃ³n mÃ¡s la carga de los mineros relevantes superarÃ­a el stock fÃ­sico actual en este porcentaje. Usa cantidades reales de carga, no el umbral de desbordamiento. 0 = desactivado.</t>
    <t id="32002">GalaxyTrader Suministro MK4</t>
    <t id="32102">Comerciante de suministros de estaciones de jugadores que utiliza GT cachÃ©/canal de bÃºsqueda en vivo</t>
    <t id="32010">Distancia de cobertura</t>
    <t id="32110">Distancia mÃ¡xima de puerta desde casa para bÃºsqueda de demanda de destino</t>
    <t id="32011">Comprar Distancia</t>
    <t id="32111">Distancia mÃ¡xima de puerta desde casa para bÃºsqueda de proveedores</t>
    <t id="32012">Servir solo a domicilio</t>
    <t id="32112">Cuando estÃ¡ habilitado, solo se atiende la demanda de la estaciÃ³n base.</t>
    <t id="32013">Solo construir estaciones</t>
    <t id="32113">Cuando estÃ¡ habilitado, solo se atiende la demanda de almacenamiento de compilaciÃ³n</t>
    <t id="32014">Comprar del jugador</t>
    <t id="32114">Permitir el abastecimiento de productos de proveedores propiedad de los jugadores.</t>
    <t id="32015">Comprar de facciÃ³n</t>
    <t id="32115">Permitir el abastecimiento de productos de proveedores de facciones que no sean jugadores.</t>
    <t id="32016">Permitir recursos</t>
    <t id="32116">Incluir artÃ­culos de recursos en el ajuste de la demanda.</t>
    <t id="32017">Permitir intermedios</t>
    <t id="32117">Incluir mercancÃ­as intermedias en el ajuste de la demanda.</t>
    <t id="32018">Permitir productos</t>
    <t id="32118">Incluir artÃ­culos de productos en la coincidencia de demanda.</t>
    <t id="32019">Permitir artÃ­culos comerciales</t>
    <t id="32119">Incluir productos comerciales en el ajuste de la demanda.</t>
    <t id="20002">Galaxy Trader MK2</t>
    <t id="20102">DistribuciÃ³n de almacenes con gestiÃ³n de umbrales de almacenamiento.</t>
    <t id="20010">Estaciones fuente</t>
    <t id="20011">Estaciones de destino</t>
    <t id="20012">% mÃ­nimo de almacenamiento</t>
    <t id="20013">% de almacenamiento estÃ¡tico</t>
    <t id="20014">% de almacenamiento mÃ¡ximo</t>
    <t id="20015">Filtro de artÃ­culos</t>
    <t id="20016">Modo bidireccional</t>
    <t id="20017">EstaciÃ³n base (opcional)</t>
    <t id="20018">Distancia mÃ¡xima</t>
    <t id="20032">Sector base (opcional)</t>
    <t id="20019">Tiempo de espera del ciclo</t>
    <t id="20030">Permitir volumen bajo</t>
    <t id="20031">% de piso de bajo volumen</t>
    <t id="20110">Lista de estaciones de origen para distribuir productos desde</t>
    <t id="20111">Lista de estaciones/almacenes de destino para distribuir mercancÃ­as</t>
    <t id="20112">Umbral de urgencia del destino: las estaciones por debajo de este porcentaje de almacenamiento reciben entregas prioritarias</t>
    <t id="20113">Umbral mÃ­nimo de fuente: la fuente debe tener mÃ¡s de este porcentaje para distribuirse</t>
    <t id="20114">Umbral de desbordamiento de fuente: por encima de este porcentaje, la fuente se distribuye incluso a destinos no urgentes.</t>
    <t id="20115">Filtro de vajilla opcional; dejar vacÃ­o para distribuir todos los productos desde la fuente</t>
    <t id="20116">Habilite la recolecciÃ³n de viaje de regreso desde los destinos hasta el origen cuando los destinos tengan exceso</t>
    <t id="20117">EstaciÃ³n local opcional para asignaciÃ³n. Si estÃ¡ vacÃ­o, el barco permanece sin asignar a las estaciones.</t>
    <t id="20118">Distancia mÃ¡xima de puerta entre origen y destinos (0 = ilimitado)</t>
    <t id="20132">Sector base opcional usado para estacionamiento en inactividad cuando no hay una estaciÃ³n base establecida.</t>
    <t id="20119">Tiempo de espera entre ciclos de distribuciÃ³n</t>
    <t id="20130">Permita porciones de entrega mÃ¡s pequeÃ±as, conscientes de la urgencia, por debajo del llenado de carga mÃ­nimo normal.</t>
    <t id="20131">% mÃ­nimo de llenado de carga utilizado cuando el modo de bajo volumen estÃ¡ habilitado.</t>
    <t id="20200">Distribuyendo %1 %2 de %3 a %4</t>
    <t id="20201">Viaje de vuelta: recogida de %1 %2 de %3 a %4</t>
    <t id="20202">No se necesita distribucion - todos los destinos estan suficientemente abastecidos</t>
    <t id="20203">Todas las estaciones origen no son validas - distribucion en espera</t>
    <t id="20204">Todas las estaciones destino no son validas - distribucion en espera</t>
    <t id="20205">Estacion origen %1 destruida - eliminada del orden de distribucion</t>
    <t id="20206">Estacion destino %1 destruida - eliminada del orden de distribucion</t>
    <t id="20500">GalaxyTrader MK2 - ConfiguraciÃ³n global</t>
    <t id="20501">Valores predeterminados de distribuciÃ³n de MK2</t>
    <t id="20510">% de almacenamiento mÃ­nimo predeterminado</t>
    <t id="20511">% de almacenamiento estÃ¡tico predeterminado</t>
    <t id="20512">% de almacenamiento mÃ¡ximo predeterminado</t>
    <t id="20513">Espera(s) de ciclo predeterminadas</t>
    <t id="20514">% mÃ­nimo de llenado de carga</t>
    <t id="20520">Verbosidad de notificaciÃ³n</t>
    <t id="20521">Nivel de depuraciÃ³n</t>
    <t id="10006">Regresar a casa</t>
    <t id="10007">GalaxyTrader Suministro MK4-2</t>
    <t id="10106">Atraque en la estaciÃ³n base y permanezca allÃ­ hasta que se reanude el comercio.</t>
    <t id="10107">Orden de suministro del jugador con controles de prioridad de destino de entrega</t>
    <t id="30026">Regreso a casa entre ciclos</t>
    <t id="30028">Ignorar configuraciÃ³n de ofertas</t>
    <t id="30029">Rango de precio del comprador</t>
    <t id="30027">% mÃ­n. almacenamiento producto</t>
    <t id="30126">Cuando estÃ© habilitado, regrese a la estaciÃ³n base y atraque entre ciclos comerciales. Cuando estÃ¡ deshabilitado, continÃºa buscando desde la ubicaciÃ³n actual (comportamiento heredado)</t>
    <t id="30128">Permitir transferencias internas de almacenamiento sin ofertas de compra/venta de estaciÃ³n. Usa intercambio de mercancÃ­as para recogida y entrega del bÃºfer. Las reglas comerciales de la estaciÃ³n siguen aplicÃ¡ndose si Ignorar reglas comerciales estÃ¡ desactivado.</t>
    <t id="30129">Precio relativo mÃ­nimo para compradores NPC al vender productos de estaciÃ³n. Control deslizante del orden 0-200 (100 = media, 0 = -100%, 200 = +100%), mapeado a -1,0..+1,0. Mayor = solo compradores caros. Menor = mÃ¡s opciones de compradores. Las rutas de suministro usan el valor invertido para lÃ­mites de precio de proveedores.</t>
    <t id="30127">Porcentaje mÃ­nimo de llenado del almacÃ©n de la estaciÃ³n (respecto al mÃ¡ximo configurado por mercancÃ­a) requerido antes de vender un producto o mercancÃ­a. Las mercancÃ­as por debajo de este umbral se omiten. 0 = sin mÃ­nimo.</t>
    <t id="3107">Cola de operaciones mÃºltiples: %1. DeberÃ­a obtener %2 de ganancias.</t>
    <t id="3108">Vendiendo %1 %2 desde %3 al precio de %4. DeberÃ­a obtener %5 de ganancias.</t>
    <t id="3110">Encolando suministro de %1 %2. Abastecimiento a %3 desde %4, entrega a %5. Tope de compra del cliente %6 - %7/unidad por debajo del tope (%8 en total).</t>
    <t id="3111">Encolando suministro de %1 %2 desde %3 a %4.</t>
    <t id="3112">Suministro en cola (%1 tramos): %2. Total %3 por debajo del tope de compra del cliente.</t>
    <t id="3113">Comerciante de estaciÃ³n: exportaciÃ³n multitrade en cola: %1. Beneficio esperado %2.</t>
    <t id="31029">Objetivo de stock de sonda</t>
    <t id="31030">Drones de minerÃ­a a comprar</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: no hay materias minables disponibles. Nave %1 [%2], Flota: %3</t>
    <t id="31201">Galaxy-Miner: establezca la estaciÃ³n base o la posiciÃ³n base.</t>
    <t id="31130">CuÃ¡ntos drones recolectores (de minerÃ­a) compra el minero cuando se ha quedado sin el tipo necesario (sÃ³lido/mineral o lÃ­quido/gas). La compra se activa SÃ“LO cuando el barco no tiene recolectores de ese tipo; un minero que todavÃ­a tiene al menos uno nunca se reabastece ni se vuelve a comprar, los drones existentes se conservan. Limitado por la capacidad de la bahÃ­a de unidades del barco. Ponlo en 0 para desactivar la compra automÃ¡tica de drones recolectores y gestionarlos manualmente. El valor predeterminado 5 es un juego completo de drones para una velocidad de minerÃ­a normal.</t>
    <t id="31129">NÃºmero de sondas de recursos que compra el minero por viaje de reabastecimiento. La compra se activa SÃ“LO cuando el barco se ha quedado sin sondas (recuento = 0), no en cada despliegue; de â€‹â€‹esa manera, el minero ejecuta toda su carga de sonda entre recorridos de suministro en lugar de desviarse despuÃ©s de cada despliegue. Limitado por la capacidad desplegable total del barco (compartida con satÃ©lites/minas/etc.); un valor del control deslizante mayor que el espacio libre desplegable se degrada elegantemente para "llenar lo que cabe". Solo tiene efecto cuando estÃ¡ habilitado Auto Deploy Resource Probes; la misma configuraciÃ³n tambiÃ©n impulsa la implementaciÃ³n de sondas oportunistas en sectores mineros y la recopilaciÃ³n de sondas obsoletas (sondas en sectores sin recursos relevantes para la cesta).</t>
    <t id="3226">Comandante %1,\n\nHe atracado en %2 y el registrador de la Academia de Comercio ha confirmado mi inscripciÃ³n en el programa "%3". Se han debitado %4 Cr de la cuenta de la flota por la matrÃ­cula del curso y no tomo esa inversiÃ³n a la ligera.\n\nEsta no es una certificaciÃ³n de rutina. Los instructores de la academia son comerciantes veteranos y negociadores de consorcios, y el plan de estudios aquÃ­ es mucho mÃ¡s exigente que el examen de avance estÃ¡ndar. Durante los prÃ³ximos %5 minutos recibirÃ© instrucciÃ³n intensiva sobre protocolos comerciales avanzados, anÃ¡lisis de mercado bajo presiÃ³n y las tÃ¡cticas de negociaciÃ³n que separan a los aprendices de los maestros.\n\nCuando se complete el examen final y me desacople, tendrÃ© el tÃ­tulo de "%3" y traerÃ© todo lo que he aprendido a nuestras operaciones comerciales. No desperdiciarÃ© ni un solo crÃ©dito de esta oportunidad.\n\nCon gratitud y determinaciÃ³n,\n%6\nA bordo de %7</t>
    <t id="9924">Curso de la Academia de Comercio cancelado: el piloto %1 no puede pagar la tarifa de %2 Cr en el muelle de la academia (tiene %3 Cr). Curso cancelado, el piloto reanuda sus operaciones.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="39">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Aggancia e attendi (GalaxyTrader MK3)</t>
    <t id="10002">Galaxy Trader MK3</t>
    <t id="10003">Esame finale (GalaxyTrader MK3)</t>
    <t id="10004">Incontro di scambio pilota</t>
    <t id="10005">[OBSOLETO] GalaxyTrader Fornitura MK4 (Legacy)</t>
    <t id="10101">Attracca alla stazione e attendi la durata specificata</t>
    <t id="10102">Commercio autonomo con progressione delle abilitÃ </t>
    <t id="10103">Sostenere l'esame finale per la certificazione di pilota presso la struttura di formazione</t>
    <t id="10104">Attracco alla stazione d'incontro per lo scambio di piloti</t>
    <t id="10105">Trading focalizzato sull'offerta per le stazioni dei giocatori utilizzando cache e ricerca dal vivo (Legacy)</t>
    <t id="10201">Acquista %s da %s</t>
    <t id="10202">Vendi %s a %s</t>
    <t id="10203">Fai trading con %s</t>
    <t id="1000">Galaxy Trader MK3</t>
    <t id="1001">Sistema commerciale avanzato con progressione XP e coordinamento della flotta</t>
    <t id="1002">Base domestica</t>
    <t id="1003">Usa i preset</t>
    <t id="1004">Scambia tutte le merci</t>
    <t id="1005">Commercio di articoli legali</t>
    <t id="1006">Commercia merci illegali</t>
    <t id="1007">Abilita la progressione XP</t>
    <t id="1008">Abilita il coordinamento della flotta</t>
    <t id="1009">Abilita l'analisi di mercato</t>
    <t id="1010">Abilita la gestione del territorio</t>
    <t id="1011">Consenti merci illegali</t>
    <t id="1012">Voci del registro</t>
    <t id="1013">Tolleranza al rischio</t>
    <t id="1014">PrioritÃ  Stazioni Giocatore</t>
    <t id="1015">Merci automatiche</t>
    <t id="1016">PenalitÃ  Distanza %</t>
    <t id="1017">Livello di notifica</t>
    <t id="1018">Coordinamento della flotta</t>
    <t id="1019">% target di riempimento del carico</t>
    <t id="1050">Frequenza di aggiornamento del mercato</t>
    <t id="1051">Registrazione della valutazione commerciale</t>
    <t id="1052">Whitelist di settore</t>
    <t id="1054">Ignora le navi portaerei/ausiliarie</t>
    <t id="1056">Ignora l'archiviazione di build</t>
    <t id="1058">Ignora le regole commerciali</t>
    <t id="1060">Ignora le stazioni fornite da MK1</t>
    <t id="1063">In fase di sviluppo</t>
    <t id="1064">Merce prioritaria</t>
    <t id="1065">Punteggio prioritÃ  %</t>
    <t id="1066">Merci da favorire nel punteggio commerciale. Il loro punteggio viene moltiplicato per la percentuale del punteggio di prioritÃ .</t>
    <t id="1067">Moltiplicatore di punteggio per le merci prioritarie: 100%=normale, 150%=+50%%, 200%=2x, 300%=3x. Applicato per ultimo.</t>
    <t id="1068">â”€â”€ Filtro merci prioritarie â”€â”€</t>
    <t id="1069">Merce (manuale)</t>
    <t id="1070">Filtro percorso illegale</t>
    <t id="1072">Servire solo a domicilio</t>
    <t id="1073">PrioritÃ  fornitore giocatore</t>
    <t id="1074">PrioritÃ  fornitore fazione</t>
    <t id="1075">Includi spazio di archiviazione</t>
    <t id="1076">Includi risorse</t>
    <t id="1077">Includi intermedi</t>
    <t id="1078">Includi prodotti commerciali</t>
    <t id="1080">Numero massimo di operazioni per ciclo</t>
    <t id="1081">Tolleranza di tornare indietro</t>
    <t id="1082">Carico minimo utilizzato%</t>
    <t id="1083">% modificatore acquisto giocatore</t>
    <t id="1085">Assegna alla stazione di casa</t>
    <t id="1086">Distanza di copertura</t>
    <t id="1088">Distanza massima di salto da casa per la copertura della domanda</t>
    <t id="1090">Includere articoli di classe tradeware nell'abbinamento domanda/offerta</t>
    <t id="1091">Modificatore applicato ai prezzi dei fornitori di proprietÃ  del giocatore nei calcoli relativi al solo punteggio</t>
    <t id="1092">Ignora i prezzi dei giocatori</t>
    <t id="1093">Se abilitato: acquista sempre dalle stazioni di proprietÃ  dei giocatori indipendentemente dai prezzi di vendita impostati e vendi solo alle fazioni NPC. Utile per liquidare le scorte in eccesso delle proprie postazioni.</t>
    <t id="1094">Stazioni bloccate</t>
    <t id="1095">Le stazioni selezionate qui sono escluse dal commercio MK3. Il mercante non comprerÃ  nÃ© venderÃ  presso di esse.</t>
    <t id="1096">Parcheggio in inattivitÃ </t>
    <t id="1097">Se attivo, le navi che non trovano lavoro piÃ¹ volte parcheggiano alla stazione domestica o nel settore domestico. Il parcheggio nel settore preferisce le stazioni del giocatore, poi quelle amiche. Il tempo di rilascio del dock si imposta nelle impostazioni globali (0 = resta ormeggiata finchÃ© non viene trovato lavoro).</t>
    <t id="1098">Auto-scala</t>
    <t id="1099">Se attivo, i cursori della distanza di salto vengono impostati sulla portata massima consentita al pilota dopo l'addestramento obbligatorio o il completamento dell'Accademia commerciale. Disattivare per impostare le distanze manualmente.</t>
    <t id="11001">PrioritÃ  deposito costruzione</t>
    <t id="11002">PrioritÃ  stazioni</t>
    <t id="11003">PrioritÃ  navi ausiliarie</t>
    <t id="11004">PrioritÃ  portaerei</t>
    <t id="11005">0 = disattivato. 1-10 = moltiplicatore punteggio (10 = peso massimo). Punteggio finale = punteggio rifornimento Ã— moltiplicatore.</t>
    <t id="11006">1 = nessun punteggio extra (elenco merci prioritarie invariato). 2-10 = aggiunge (moltiplicatoreâˆ’1)Ã— punteggio base rifornimento se la merce Ã¨ nell'elenco prioritario. Si applica sopra il punteggio di tipo.</t>
    <t id="11007">Bonus merci prioritarie</t>
    <t id="11008">%1: Tutti i cursori di prioritÃ  obiettivo consegna sono impostati su 0 - questo ordine non ha obiettivi di consegna. Abilita almeno una classe (deposito costruzioni, stazioni, navi ausiliarie o portaerei) per riprendere i rifornimenti.</t>
    <t id="7001">[ANTICIPO]</t>
    <t id="7002">[FORMAZIONE]</t>
    <t id="7008">[RICADERCI]</t>
    <t id="7009">[ISOLATO]</t>
    <t id="7003">[RIPARAZIONE]</t>
    <t id="7004">[RIFORNIMENTI]</t>
    <t id="7005">[MANUTENZIONE]</t>
    <t id="7006">[CINURARE]</t>
    <t id="7007">[LIQUIRAZIONE]</t>
    <t id="1020">Scegli il settore di residenza o la stazione in cui opera il trader</t>
    <t id="1021">Distanza massima del gate di salto quando si comprano merci (limitata dall'abilitÃ  del piloto)</t>
    <t id="1022">Distanza massima del gate di salto quando si vendono merci (limitata dall'abilitÃ  del piloto)</t>
    <t id="1023">Selezione automatica degli articoli adatti in base alla categoria</t>
    <t id="1024">Selezione manuale di articoli commerciali specifici</t>
    <t id="1025">Consentire il commercio di contrabbando e di beni illegali</t>
    <t id="1026">Tolleranza alla sicurezza: 0.0=Solo settori sicuri, 1.0=Accetta tutti i rischi</t>
    <t id="1027">Migliora le abilitÃ  del piloto attraverso l'esperienza commerciale</t>
    <t id="1028">Invia automaticamente i piloti per l'addestramento quando necessario</t>
    <t id="1029">Coordina piÃ¹ navi commerciali per evitare conflitti</t>
    <t id="1030">Focus merci: 0=Bilanciato, 1=Avanzato, 2=NecessitÃ  base, 3=Illegale, 4=Merci sfuse</t>
    <t id="1031">Area di scambio: 0=Bilanciata, 1=Focalizzazione sulla casa, 2=Viaggiamento libero</t>
    <t id="1032">Livello di notifica: 0=Minimo, 1=Normale, 2=Messaggi dettagliati</t>
    <t id="1033">Percentuale di utilizzo cargo obiettivo prima di dare prioritÃ  alle vendite</t>
    <t id="1034">La frequenza con cui vengono aggiornati i dati di mercato e le informazioni sui prezzi</t>
    <t id="1035">Livello di output di debug: 0=Nessuno, 1=Base, 2=Registrazione dettagliata</t>
    <t id="1036">Condividi rotte commerciali redditizie con la flotta (memorizzate nella cache per un rapido accesso)</t>
    <t id="1037">Profitto minimo richiesto per nascondere il commercio e condividerlo con la flotta</t>
    <t id="1038">Diminuzione massima del profitto consentita prima che le rotte commerciali memorizzate nella cache diventino non valide</t>
    <t id="1039">Per quanto tempo le rotte commerciali memorizzate nella cache rimangono valide prima della scadenza</t>
    <t id="1040">Abilita la registrazione dettagliata delle valutazioni e dei rifiuti dei singoli commerci (puÃ² essere molto verboso)</t>
    <t id="1041">Abilita voci di registro per operazione e messaggi di formazione coinvolgenti (stile TaterTrader)</t>
    <t id="1053">I settori in questo elenco sono esclusi dalle liste nere (sempre consentite)</t>
    <t id="1055">Escludere le portaerei e le navi ausiliarie dal commercio</t>
    <t id="1057">Escludere le navi deposito dal commercio</t>
    <t id="1059">Ignora le regole di commercio della stazione durante la ricerca offerte (avanzato; puÃ² selezionare offerte normalmente bloccate)</t>
    <t id="1061">Salta le stazioni dei giocatori che hanno un commerciante MK1 con la modalitÃ  Rifornimento assegnata</t>
    <t id="1062">Aumenta i punteggi commerciali per le rotte che coinvolgono le tue stazioni (bonus del punteggio del 10%)</t>
    <t id="1071">Quando Consenti merci illegali Ã¨ abilitato, commercia merci illegali solo se legali in tutti i settori sul percorso di salto (acquisto, vendita e settori intermedi).</t>
    <t id="1087">Distanza massima di salto da casa per la ricerca acquisto fornitore</t>
    <t id="1089">Quando disabilitata, la nave puÃ² fornire stazioni nell'area di copertura in base alla prioritÃ  di urgenza anzichÃ© alla modalitÃ  solo casa</t>
    <t id="2000">%s ha guadagnato %s XP!</t>
    <t id="2001">%s Ã¨ salito di livello! Nuovo livello: %s</t>
    <t id="2002">%s ha bisogno di addestramento! Si prega di inviare al cantiere navale o alla stazione commerciale piÃ¹ vicina.</t>
    <t id="2003">%s ha iniziato la formazione alle %s</t>
    <t id="2004">%s ha completato l'addestramento ed Ã¨ ora certificato per il livello %s!</t>
    <t id="2005">%s ha raggiunto lo Skill Level %s dopo l'addestramento! Progressione XP sbloccata a %s.</t>
    <t id="2006">%s ha raggiunto lo Skill Level %s con il commercio di %s!</t>
    <t id="2007">%s ha completato l'addestramento Level %s! Progressione XP sbloccata a %s.</t>
    <t id="3000">%s ha completato uno scambio! Profitto: %s Cr</t>
    <t id="3001">%s sta analizzando le condizioni del mercato...</t>
    <t id="3002">%s ha trovato una rotta commerciale redditizia!</t>
    <t id="3003">Nessuna rotta commerciale redditizia disponibile per %s</t>
    <t id="3100">Vendita di %1 %2 dal carico a %3 al prezzo di %4. Dovrei guadagnare %5 di profitto.</t>
    <t id="3101">Ordine commerciale in coda per %1 %2. Acquisto a %3 da %4, vendita a %5 a %6. Dovrei guadagnare %7 di profitto.</t>
    <t id="3102">Commerciante di stazione: rifornisco %1 %2 da %3 al %5%% a %4 al %6%%.</t>
    <t id="3103">Commerciante Stazione: Vendendo %1 %2 a %3 a %4. Profitto atteso %5.</t>
    <t id="3104">Scambio completato con successo per %1 %2. Profitto totale: %3 crediti.</t>
    <t id="3105">Rotta commerciale memorizzata nella cache: %1 %2 da %3 a %4 (Profitto: %5 Cr)</t>
    <t id="3106">\nProfitto totale stimato prima di questa operazione: %1 Cr.</t>
    <t id="3120">Trasferimento pilota avviato</t>
    <t id="3121">Protocollo di trasferimento riconosciuto. %1 (%2) e %3 (%4) stanno procedendo verso %5 (%6) per attraccare e scambiarsi i posti di comando.</t>
    <t id="3200">Salve Comandante %1,\n\nHo guadagnato abbastanza esperienza per sostenere il mio esame di certificazione per il titolo "%2". L'esame durerÃ  approssimativamente %3 minuti presso %4.\n\nQuesto Ã¨ un traguardo importante nel mio sviluppo professionale. L'esame testerÃ  la mia conoscenza dei protocolli commerciali avanzati, dell'analisi di mercato e delle procedure di coordinamento della flotta.\n\nSono fiducioso nelle mie capacitÃ  ed entusiasta di dimostrarmi degno di questa promozione. Auguratemi buona fortuna!\n\nRispettosamente,\n%5\nA bordo di %6</t>
    <t id="3201">Comandante %1,\n\nEccellenti notizie! Ho completato con successo il mio esame di certificazione e ho guadagnato il titolo "%2"!\n\nL'esame ha coperto strategie commerciali avanzate, protocolli di valutazione del rischio e procedure di coordinamento della flotta. Sono lieto di riferire che ho superato con distinzione.\n\nSono ora qualificato per gestire operazioni commerciali piÃ¹ complesse e non vedo l'ora di contribuire ancora di piÃ¹ al successo della nostra flotta. Grazie per aver investito nel mio sviluppo professionale.\n\nCon rinnovata dedizione,\n%3\nCertificato %2\nA bordo di %4</t>
    <t id="3202">Comandante %1,\n\nMi dispiace informarla che il mio esame di certificazione Ã¨ stato interrotto a causa di requisiti operativi. DovrÃ² riprogrammare quando le circostanze lo permetteranno.\n\nRimango impegnato ad avanzare le mie abilitÃ  e la notificherÃ² quando potrÃ² riprendere il processo di esame.\n\nRispettosamente,\n%2\nA bordo di %3</t>
    <t id="3203">Comandante %1,\n\nSono attualmente in viaggio verso %2 per il mio esame di certificazione. Il viaggio mi dÃ  tempo per rivedere i miei studi e prepararmi mentalmente per questo importante passo nella mia carriera.\n\nArrivo previsto: %3 minuti\nDurata esame: %4 minuti\n\nApprezzo la sua fiducia nelle mie capacitÃ  e l'opportunitÃ  di avanzamento.\n\nCon determinazione,\n%5\nA bordo di %6</t>
    <t id="3204">Comandante,\n\nHo rilevato cargo nella mia stiva durante il controllo dei sistemi. Prima di poter iniziare le normali operazioni commerciali, devo vendere questa merce.\n\nSto usando la nostra ricerca commerciale per trovare il miglior acquirente e scaricare in sicurezza questo cargo. Una volta che la mia stiva sarÃ  vuota, procederÃ² con il commercio automatizzato.\n\nStato: Cercando la posizione di vendita ottimale\n\nCon diligenza,\nA bordo di %1</t>
    <t id="3205">Comandante,\n\nL'integritÃ  del mio scafo Ã¨ scesa al %1%% (soglia: %2%%). Come piloto di Livello %3, sono autorizzato a richiedere servizi di riparazione automatica.\n\nSto procedendo verso %4 per i lavori di riparazione. Il costo stimato Ã¨ %5 Cr, che Ã¨ nel nostro budget.\n\nUna volta completate le riparazioni, riprenderÃ² le operazioni commerciali con piena integritÃ  strutturale.\n\nRispettosamente,\nA bordo di %6</t>
    <t id="3206">Comandante,\n\nAVVISO FINANZIARIO URGENTE\n\nL'integritÃ  del mio scafo Ã¨ critica al %1%% (soglia: %2%%), ma i nostri fondi disponibili (%3 Cr) sono insufficienti per riparazioni complete (costo stimato: %4 Cr).\n\nSto procedendo verso %5 per RIPARAZIONI PARZIALI utilizzando i nostri fondi disponibili. Questa non Ã¨ una soluzione ideale, ma Ã¨ necessaria per mantenere la capacitÃ  operativa.\n\nSi prega di considerare l'allocazione di fondi aggiuntivi per future operazioni di manutenzione.\n\nPreoccupato ma determinato,\nA bordo di %6</t>
    <t id="3207">Comandante,\n\nLa mia certificazione di Livello %1 autorizza il rifornimento automatico dell'equipaggiamento difensivo. Dopo aver controllato i miei sistemi, ho determinato che le mie contromisure e gli equipaggiamenti dispiegabili sono al di sotto delle soglie raccomandate.\n\nSto procedendo verso %2 per rifornire il mio equipaggiamento difensivo:\nâ€¢ Contromisure: Rifornimento alla capacitÃ  ottimale\nâ€¢ Droni di difesa, droni commerciali, torri laser: Applicazione del profilo di equilibrio\n\nQuesto rifornimento garantisce che io sia meglio protetto contro le minacce spaziali mantenendo l'efficienza commerciale.\n\nCon vigilanza,\nA bordo di %3</t>
    <t id="3212">Comandante,\n\nL'integritÃ  del mio scafo Ã¨ scesa al %1%% (soglia: %2%%), e ho bisogno di servizi di riparazione. Tuttavia, la stazione di riparazione piÃ¹ vicina presso %3 Ã¨ attualmente irraggiungibile a causa di restrizioni di viaggio settoriale (rotte in lista nera).\n\nContinuerÃ² con le operazioni commerciali nonostante questa limitazione. Una volta che le rotte sicure diventeranno di nuovo disponibili, cercherÃ² automaticamente servizi di riparazione.\n\nMonitorerÃ² la situazione e la notificherÃ² quando le riparazioni diventeranno possibili.\n\nRispettosamente,\nA bordo di %4</t>
    <t id="3213">Comandante,\n\nIl mio equipaggiamento difensivo richiede rifornimento, ma la stazione di equipaggiamento piÃ¹ vicina presso %1 Ã¨ attualmente irraggiungibile a causa di restrizioni di viaggio settoriale (rotte in lista nera).\n\nContinuerÃ² con le operazioni commerciali nonostante questa limitazione. Una volta che le rotte sicure diventeranno di nuovo disponibili, cercherÃ² automaticamente servizi di rifornimento.\n\nMonitorerÃ² la situazione e la notificherÃ² quando il rifornimento diventerÃ  possibile.\n\nRispettosamente,\nA bordo di %2</t>
    <t id="3208">Comandante,\n\nHo completato un'analisi di mercato esaustiva di %1 e dei settori circostanti (entro %2 salti, soglia di profitto minimo: %3 Cr), ma purtroppo non ho trovato opportunitÃ  commerciali redditizie che soddisfino i nostri requisiti.\n\nREPORT ANALISI COMMERCIO:\nOpportunitÃ  totali valutate: %4\n\nRIEPILOGO RIFIUTI:\n- Restrizioni di attracco: %5 commerci\n  (La stazione non permette la mia classe di nave)\n- RedditivitÃ  insufficiente: %6 commerci\n  (Al di sotto della soglia di profitto minimo)\n- Volume insufficiente: %7 commerci\n  (QuantitÃ  commerciabile zero o negativa)\n- Restrizioni di sicurezza: %8 commerci\n  (Stazioni in lista nera o settori pericolosi)\n\nRACCOMANDAZIONI:\n- Considerare l'aggiustamento delle soglie di profitto\n- Espandere la distanza commerciale massima\n- Rivedere le impostazioni della lista nera settoriale\n- Attendere che le condizioni di mercato migliorino\n\nContinuerÃ² a monitorare il mercato e la notificherÃ² quando le opportunitÃ  redditizie diventeranno disponibili.\n\nIn attesa,\nAl suo servizio</t>
    <t id="3209">Comandante,\n\nALLERTA ROTTA URGENTE\n\nIl mio sistema di intelligence delle minacce ha rilevato che il settore %1 (livello di minaccia %2) Ã¨ ora nella mia rotta commerciale pianificata. Per la sicurezza della nave e dell'equipaggio, sto interrompendo immediatamente l'operazione commerciale corrente.\n\nAZIONI INTRAPRESE:\n- Tutti gli ordini commerciali cancellati\n- Ritorno alla modalitÃ  operativa sicura\n- CercherÃ² una rotta commerciale alternativa che eviti settori pericolosi\n- Gestione cargo: Automatica (venderÃ  qualsiasi cargo in una posizione sicura se necessario)\n\nIl sistema di lista nera dinamica impedirÃ  futuri commerci attraverso questo settore fino a quando la minaccia non sarÃ  eliminata.\n\nLa sicurezza Ã¨ la mia prima prioritÃ .\n\nCon vigilanza,\nA bordo di %3</t>
    <t id="3210">Comandante,\n\nROTTA DI FUGA INIZIATA\n\nSono attualmente nel settore in lista nera %1 e ho trovato una rotta commerciale che mi permetterÃ  di fuggire in sicurezza.\n\nROTTA COMMERCIALE:\nCompra: %2 (Settore: %3)\nVendi: %4 (Settore: %5)\nMerce: %6 (x%7)\nProfitto Atteso: %8 Cr\n\nLa nave fuggirÃ  dal settore in lista nera dopo aver completato questo commercio.\n\nRispettosamente,\nAl suo servizio</t>
    <t id="3211">Comandante,\n\nMODALITÃ€ COMMERCIO ISOLATO\n\nSono attualmente nel settore %2, ma tutte le rotte verso altri settori sono bloccate da settori hub in lista nera. Questo significa che posso commerciare solo all'interno del mio settore corrente fino a quando la situazione della lista nera non cambia.\n\nSITUAZIONE:\nSettore Corrente: %2\nStato: Isolato (settore non in lista nera con rotte bloccate)\nModalitÃ  Commercio: Solo commerci intra-settore\n\nIl mio sistema commerciale ha automaticamente aggiustato le soglie di profitto per dare prioritÃ  alle opportunitÃ  commerciali intra-settore disponibili.\n\nContinuerÃ² a monitorare la situazione e la notificherÃ² se le rotte diventeranno di nuovo disponibili.\n\nRispettosamente,\nA bordo di %1</t>
    <t id="3218">Comandante,\n\nCAMBIO PERCORSO ROTTA RILEVATO\n\nEntrando nel settore %1, il mio sistema di navigazione ha rilevato che la rotta verso la mia destinazione %2 (%3) Ã¨ cambiata.\n\nANALISI PERCORSO:\n- Distanza normale: %4 salti\n- Distanza consapevole della lista nera: %5\n- Stato: %6\n\nIl mio computer di navigazione indica che la rotta preferita non Ã¨ piÃ¹ praticabile a causa di restrizioni di viaggio settoriale. Per la sicurezza della nave e dell'equipaggio, sto interrompendo immediatamente l'operazione commerciale corrente.\n\nAZIONI INTRAPRESE:\n- Tutti gli ordini commerciali cancellati\n- Ritorno alla modalitÃ  operativa sicura\n- CercherÃ² una rotta commerciale alternativa che eviti settori bloccati\n- Gestione cargo: Automatica (venderÃ  qualsiasi cargo in una posizione sicura se necessario)\n\nIl mio sistema di navigazione eviterÃ  automaticamente i settori bloccati nella pianificazione futura delle rotte.\n\nLa sicurezza Ã¨ la mia prima prioritÃ .\n\nCon vigilanza,\nA bordo di %7</t>
    <t id="3219">Settore %1 ripulito: tutte le minacce eliminate</t>
    <t id="3220">Comandante,\n\nNAVE NEMICA SFUGGITA\n\nIl nostro sistema di intelligence sulle minacce ha perso le tracce della nave nemica %3, che Ã¨ fuggita dal settore in lista nera %1.\n\nDETTAGLI:\n- Nave fuggita: %3\n- Settore abbandonato: %1\n- Settore di destinazione: %2\n- Stato: Tracciamento perso - la nave ha lasciato la nostra area monitorata\n\nSebbene questa nave non rappresenti piÃ¹ una minaccia nel settore %1, abbiamo perso il contatto visivo e non possiamo confermare il suo stato attuale o le sue intenzioni nel settore %2.\n\nI nostri sistemi di tracciamento continueranno a monitorare il settore %1 per le minacce rimanenti. Se tutti i nemici tracciati lasciano o vengono eliminati, il settore verrÃ  automaticamente rimosso dalla lista nera.\n\nCon vigilanza,\nSistema di Intelligence sulle Minacce</t>
    <t id="3221">Comandante,\n\nNon sono riuscito a trovare opportunitÃ  commerciali redditizie a distanze maggiori (fino a %3 salti) perchÃ© queste rotte sono attualmente irraggiungibili a causa di restrizioni di viaggio settoriale (percorsi in lista nera).\n\nSITUAZIONE:\nSettore Corrente: %2\nIntervallo di Ricerca Originale: %3 salti\nIntervallo di Ricerca Alternativo: %4 salti\n\nOra concentrerÃ² la mia ricerca sui settori vicini entro %4 salti, dove le rotte hanno maggiori probabilitÃ  di essere accessibili. Questo dovrebbe aiutarmi a trovare commerci redditizi che sono stati precedentemente filtrati a causa di restrizioni di distanza piuttosto che di reale non redditivitÃ .\n\nTi notificherÃ² quando troverÃ² opportunitÃ  commerciali adeguate nell'area vicina.\n\nRispettosamente,\nA bordo di %1</t>
    <t id="3222">Comandante,\n\nSETTORE IN LISTA NERA\n\nIl nostro sistema di intelligence sulle minacce ha rilevato attivitÃ  ostili nel settore %1 e ha automaticamente inserito questo settore nella lista nera per proteggere le nostre operazioni commerciali.\n\nNAVI NEMICHE RILEVATE:\n%2\n\nRILEVATO DA: %3\n\nPer la sicurezza delle nostre navi e dell'equipaggio, tutte le rotte commerciali attraverso questo settore sono state bloccate. Le nostre navi ruoteranno automaticamente attorno a questo settore fino a quando la minaccia non sarÃ  eliminata.\n\nIl settore verrÃ  automaticamente rimosso dalla lista nera una volta che tutte le navi nemiche tracciate saranno eliminate o avranno lasciato l'area.\n\nCon vigilanza,\nSistema di Intelligence sulle Minacce</t>
    <t id="3223">Comandante,\n\nNon riesco a trovare una stazione di addestramento accessibile per il mio esame di livello %1. ProcederÃ² con le operazioni commerciali come richiesto, ma capisco che non guadagnerÃ² punti esperienza fino a quando non potrÃ² completare l'addestramento richiesto. Dopo questa corsa commerciale, cercherÃ² nuovamente qualsiasi possibile opportunitÃ  di addestramento.\n\nRispettosamente,\nA bordo di %2</t>
    <t id="3224">Tassa di licenza per la formazione: %1 Cr</t>
    <t id="3225">Bonus: Ho guadagnato %1 livello di abilitÃ  aggiuntivo%2 grazie all'esperienza accumulata durante l'addestramento! Livello attuale: %3</t>
    <t id="3214">Ãˆ un onore lavorare per lei, %1! Sono entusiasta di iniziare la mia carriera commerciale sotto il suo comando. FarÃ² del mio meglio per servirla bene e contribuire al suo successo.</t>
    <t id="3215">Grazie per avermi dato questa meritata vacanza, %1! Ho goduto del mio tempo lontano dal commercio e le mie abilitÃ  rimangono intatte. Non vedo l'ora di tornare al lavoro ogni volta che ha bisogno di me. Fino ad allora, manterrÃ² le mie conoscenze commerciali affilate!</t>
    <t id="3216">Sono tornato dalle vacanze e pronto a lavorare di nuovo, %1! Le mie abilitÃ  commerciali rimangono affilate e sono ansioso di continuare a servirla su %2. Grazie per il meritato riposo!</t>
    <t id="3217">Grazie per il mio trasferimento su %1, %2! Sono onorato da questo nuovo incarico e avrÃ² ottima cura della mia nuova nave. La mia esperienza e le mie abilitÃ  commerciali rimangono intatte, e sono pronto a continuare a servirla.</t>
    <t id="3227">Scafo perso, dignitÃ  in attesa di recupero</t>
    <t id="3228">Comandante %1,\n\n%2 riporta da %3. La mia nave Ã¨ esplosa. Io no. Ora sono il carico flottante piÃ¹ costoso della flotta.\n\nSegnalatore sulla mappa allegato. Si affretti, per favore - ero a metÃ  fattura.\n\nFlottante professionalmente,\n%2</t>
    <t id="3229">Pilota recuperato - Dipendenza dall'ossigeno curata</t>
    <t id="3230">Comandante %1,\n\nAggiornamento flotta: %2 Ã¨ stato recuperato da %3 (%4) e ha smesso di addebitarle la formazione EVA estesa.\n\nRicollegamento registro in corso. Raccomandazione: nessuna domanda sulla vecchia nave.\n\nVergognosamente,\n%2</t>
<t id="4000">Coordinazione flotta: %s Ã¨ stata assegnata alla rotta %s</t>
    <t id="4001">Coordinazione flotta: La rotta %s Ã¨ completamente utilizzata</t>
    <t id="4002">Coordinamento flotta: %s ha rilasciato la rotta %s</t>
    <t id="5000">%s Ã¨ stato assegnato come territorio primario per %s</t>
    <t id="5001">%s ha raggiunto il livello di competenza %s in %s!</t>
    <t id="5002">Bonus territoriale applicato: %s%% aumento profitto in %s</t>
    <t id="9500">Errore: %s Ã¨ bloccato e ha bisogno di assistenza!</t>
    <t id="9501">Errore: scambio non riuscito per %s</t>
    <t id="9502">Errore: impossibile registrare %s con GalaxyTrader MK3</t>
    <t id="80001">Ware %s aggiunto alla lista nera</t>
    <t id="80002">Articoli %s rimossi dalla lista nera</t>
    <t id="80003">Ware %s aggiunto alla lista bianca</t>
    <t id="80004">Inserito automaticamente nella lista nera (prestazioni scarse): %s</t>
    <t id="80005">PrioritÃ  agli articoli pericolosi: %s</t>
    <t id="80006">Filtro articoli: %s attivo, %s commercio bloccato</t>
    <t id="80007">Tutti i filtri degli articoli sono stati cancellati</t>
    <t id="80008">I filtri degli articoli vengono ripristinati ai valori predefiniti</t>
    <t id="80009">Gestione del filtro degli articoli</t>
    <t id="80010">Merci bloccate</t>
    <t id="80011">Merci consentite</t>
    <t id="80012">Manipolazione di merci pericolose</t>
    <t id="80013">Valore minimo della merce</t>
    <t id="80014">Valore massimo della merce</t>
    <t id="80015">Fazioni limitate</t>
    <t id="80016">Categorie di articoli aggiornate dallo stato attuale del gioco</t>
    <t id="80017">%s articoli classificati: %s di basso valore, %s pericoloso, %s di alto valore</t>
    <t id="80018">Categorizzazione dinamica degli articoli abilitata</t>
    <t id="80019">Inserimento automatico nella lista nera per la categoria %s disattivata</t>
    <t id="80020">Nuovi articoli di altri mod rilevati e classificati</t>
    <t id="9000">GalaxyTrader - Impostazioni globali</t>
    <t id="9010">XP e sistema di allenamento</t>
    <t id="9012">Formazione automatica</t>
    <t id="9013">Moltiplicatore di XP</t>
    <t id="9015">Percentuale bonus comandante</t>
    <t id="9020">Coordinamento della flotta</t>
    <t id="9021">Abilita il coordinamento della flotta</t>
    <t id="9023">Abilita cache commerciale</t>
    <t id="9030">Notifiche</t>
    <t id="9031">Livello di notifica</t>
    <t id="9040">Sistema di riparazione automatica</t>
    <t id="9041">Abilita la riparazione automatica</t>
    <t id="9042">Soglia di riparazione dello scafo</t>
    <t id="9310">Galaxy-Miner</t>
    <t id="9311">Attesa scansione sonde risorse per settore</t>
    <t id="9312">Peso prossimitÃ  nave</t>
    <t id="9043">Livello pilota minimo</t>
    <t id="9004">Intervalli di prezzo di negoziazione</t>
    <t id="9005">Prezzo offerta di vendita max</t>
    <t id="9006">Prezzo offerta acquisto min</t>
    <t id="9007">Isolato: prezzo di vendita max</t>
    <t id="9008">Isolato: prezzo di acquisto minimo</t>
    <t id="9009">Fallback: prezzo di vendita max</t>
    <t id="9014">Fallback: prezzo di acquisto minimo</t>
    <t id="9016">Base della soglia di profitto</t>
    <t id="9025">Soldi minimi del giocatore</t>
    <t id="9024">Tolleranza di abbandono della cache</t>
    <t id="9026">Tempo di sosta inattiva prima del rilascio</t>
    <t id="9054">Blocca i settori delle fazioni nemiche</t>
    <t id="9055">Livello di minaccia della lista nera</t>
    <t id="9056">Ricrea la lista nera</t>
    <t id="9057">Ricreare</t>
    <t id="9058">Assegna alle navi GT</t>
    <t id="9059">Assegnare</t>
    <t id="9112">Invia automaticamente i piloti all'addestramento quando raggiungono i livelli richiesti. Disabilitare per controllare manualmente i tempi di allenamento.</t>
    <t id="9113">Regola quanto velocemente i piloti guadagnano esperienza. Valori piÃ¹ alti significano progressione piÃ¹ veloce.</t>
    <t id="9115">Percentuale di XP subordinati assegnati ai piloti comandanti. Impostalo su 0% per disabilitare i XP bonus del comandante. Predefinito: 10%.</t>
    <t id="9121">Abilita funzionalitÃ  di coordinamento intelligente della flotta, tra cui l'ottimizzazione del percorso e il bilanciamento del carico.</t>
    <t id="9123">Permette di condividere opportunitÃ  commerciali redditizie tra membri della flotta per migliore coordinazione.</t>
    <t id="9131">Controlla quante notifiche vengono visualizzate: 0=Silenzioso, 1=Solo Importanti, 2=Tutte le notifiche</t>
    <t id="9141">Invia automaticamente le navi in â€‹â€‹riparazione dopo aver completato gli scambi quando lo scafo scende al di sotto della soglia. Solo per piloti esperti (Livello 12+). Le navi scelgono la struttura appropriata: Bacino delle attrezzature S/M, Cantiere navale L/XL.</t>
    <t id="9142">Percentuale scafo sotto la quale viene attivata la riparazione automatica. Predefinito: 95%. Le navi andranno automaticamente alla struttura di riparazione piÃ¹ vicina quando danneggiate.</t>
    <t id="9411">Se abilitato, i minatori attendono durante la valutazione delle sonde risorse della fazione nel settore (+5 s per sonda oltre la prima). Il livello GT del pilota riduce linearmente questa attesa, dal tempo completo al livello 1 a 5 secondi al livello 15 (solo modalitÃ  XP GT, se l'attesa supera 5 s). Disabilitato = nessuna attesa (comportamento vanilla).</t>
    <t id="9412">Spinge le navi MK3/MK4 verso stazioni di acquisto piÃ¹ vicine quando ordinano i trade validati. Punteggio di selezione = punteggio trade / (1 + salti naveâ†’acquisto Ã— peso). Cursore 0-100 (0 = off; 4 = predefinito 0,04). Non influisce sulla classifica cache nÃ© sui limiti di portata territoriale.</t>
    <t id="9143">Livello pilota minimo richiesto per la funzione di riparazione automatica. Impostazione predefinita: 12 (trader esperti). I piloti di livello inferiore devono riparare manualmente.</t>
    <t id="9104">Prezzo relativo massimo per offerte di vendita (la nave compra DALLE stazioni). Intervallo: -1.0 a +1.0. Predefinito: 0.5 (50% sopra la media). PiÃ¹ alto = piÃ¹ costoso ma piÃ¹ opzioni.</t>
    <t id="9105">Prezzo relativo minimo per offerte di compra (la nave vende ALLE stazioni). Intervallo: -1.0 a +1.0. Predefinito: -0.5 (50% sotto la media). PiÃ¹ basso = compratori piÃ¹ economici ma piÃ¹ opzioni.</t>
    <t id="9106">Prezzo di vendita massimo per navi isolate (bloccate in un singolo settore). Intervallo: da -1,0 a +1,0. Impostazione predefinita: 0,5.</t>
    <t id="9107">Acquista il prezzo minimo per le navi isolate (bloccate in un singolo settore). Intervallo: da -1,0 a +1,0. Impostazione predefinita: -0,5.</t>
    <t id="9108">Prezzo di vendita massimo per la ricerca di fallback (ultima risorsa quando la ricerca normale fallisce). Intervallo: da -1,0 a +1,0. Impostazione predefinita: 0,5. La ricerca di fallback utilizza MaxDistance=2 e soglie di profitto rilassate.</t>
    <t id="9109">Acquista il prezzo minimo per la ricerca fallback (ultima risorsa quando la ricerca normale fallisce). Intervallo: da -1,0 a +1,0. Impostazione predefinita: -0,5. La ricerca di fallback utilizza MaxDistance=2 e soglie di profitto rilassate.</t>
    <t id="9116">Utile minimo di base al livello 15 per un commerciante medio (carico di riferimento 8200). MinAbsoluteProfit effettivo Ã¨ calcolato per pilota + scalato per carico:\n\nbase(L) = base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinale = max(scaled, 25% of base(L))\n\nSet to 0 to accept any profit (soltanto ROI/distanza/altri filtri si applicano).</t>
    <t id="9125">Quando il denaro del giocatore cade al di sotto di questa soglia, tutte le navi saltano le ricerche commerciali e aspettano, prevenendo la scansione costosa della cache che provoca balbuzie di gioco. Range: 1.000 - 100.000 Cr. Predefinito: 1.000 Cr.</t>
    <t id="9124">Percentuale massima di riduzione del ROI dal valore memorizzato nella cache prima di rifiutare l'operazione. Esempio: un ROI memorizzato nella cache del 20% con una tolleranza del 15% accetta un ROI fino al 17% (riduzione del 14%).</t>
    <t id="9126">Minuti ormeggiati prima di disancorarsi per liberare il porto (0-60). 0 = resta ormeggiato fino a trovare nuovo lavoro. Predefinito: 1 minuto.</t>
    <t id="9154">Mette automaticamente in lista nera tutti i settori di proprietÃ  di faczioni nemiche (casella relazione nella lista nera)</t>
    <t id="9155">Livello di minaccia minimo (1-5) richiesto per inserire un settore nella lista nera:\n2=Medio (attacco singolo)\n3=Medio-alto (fazioni ostili)\n4=Alto (navi capitali/missili)\n5=Molto alto (Xenon/Khaak)</t>
    <t id="9156">Ricrea manualmente la lista nera di evitazione minacce (utile se Ã¨ stata eliminata)</t>
    <t id="9157">Assegna manualmente l'attuale lista nera dinamica a tutte le navi comandanti della flotta GT. I subordinati ereditano dal loro comandante.</t>
    <t id="6001">Apprendista</t>
    <t id="6002">Corriere</t>
    <t id="6003">Fornitore</t>
    <t id="6004">Commerciante</t>
    <t id="6005">Mercante</t>
    <t id="6006">Commerciante a lunga distanza</t>
    <t id="6101">Equilibrato</t>
    <t id="6102">Difensiva</t>
    <t id="6103">Focalizzato sul trading</t>
    <t id="6104">Difesa Pesante</t>
    <t id="6105">Supporto della torre</t>
    <t id="9050">Sistema di prevenzione delle minacce</t>
    <t id="9051">Abilita l'elusione delle minacce:</t>
    <t id="9052">Soglia di relazione ostile:</t>
    <t id="9053">Utilizza la lista nera dinamica:</t>
    <t id="9151">I commercianti di livello 6+ rilevano navi ostili ed evitano rotte pericolose. La disattivazione interrompe tutte le scansioni (migliora le prestazioni). Tolleranza al rischio per nave nel comportamento di comando (scala 0-10).</t>
    <t id="9152">Contrassegna come minacce solo le fazioni con una relazione pari o inferiore a questo valore. Predefinito: -20%</t>
    <t id="9153">Inserisci automaticamente nella lista nera i settori pericolosi (livello di minaccia 3+) per costringere le navi a aggirare le minacce. Utilizza il pathfinding Vanilla per percorsi alternativi.</t>
    <t id="9060">Rifornimento automatico dell'equipaggiamento difensivo (livello 15)</t>
    <t id="9061">Abilita il rifornimento automatico:</t>
    <t id="9062">Contromisure per il rifornimento:</t>
    <t id="9063">Rifornimento dei droni da difesa:</t>
    <t id="9064">Rifornimento di droni commerciali:</t>
    <t id="9065">Rifornimento torri laser:</t>
    <t id="9066">Rifornimento di droni di riparazione:</t>
    <t id="9067">Soglia di contromisura:</t>
    <t id="9068">Soglia CapacitÃ  Unificata:</t>
    <t id="9069">Profilo di equilibrio dell'attrezzatura:</t>
    <t id="9161">I Maestri Commercianti (Livello 15) riforniscono automaticamente l'equipaggiamento difensivo dopo gli scambi. Si applica al livello comandante per i subordinati.</t>
    <t id="9162">Tutte le navi (S/M/L/XL). CapacitÃ  separata. Critico per la difesa contro misili.</t>
    <t id="9163">Navi L/XL solamente. Condivide capacitÃ  unificata con altri equipaggiamenti dispiegabili.</t>
    <t id="9164">Navi L/XL solamente. Essenziale per operazioni commerciali. Condivide capacitÃ  unificata.</t>
    <t id="9165">Tutte le navi. Le navi L/XL condividono capacitÃ  unificata, S/M usano cargo.</t>
    <t id="9166">Navi L/XL solamente. Funziona con il sistema di riparazione automatica. Condivide capacitÃ  unificata.</t>
    <t id="9167">Rifornisci quando le contromisure sono sotto questa percentuale (tutte le navi, capacitÃ  separata).</t>
    <t id="9168">Rifornisci quando il totale degli equipaggiamenti dispiegabili Ã¨ sotto questa percentuale (navi L/XL: droni + torri condividono una capacitÃ ).</t>
    <t id="9169">Distribuzione capacitÃ  unificata (navi L/XL): Focalizzato sul Commercio (20/50/20/10), Bilanciato (35/35/20/10), Defensivo (50/20/20/10), Difesa Pesante (40/30/20/10), Supporto Torre (30/30/30/10). Rapporti: Difesa/Commercio/Torri/Riparazione. Clicca per scorrere le opzioni.</t>
    <t id="9090">Modifiche alla nave</t>
    <t id="9091">Abilita modifiche alla nave</t>
    <t id="9191">Installa automaticamente modifiche nave e motore basate sul livello del piloto. Livello 9+ = Mod Livello 1, Livello 12+ = Mod Livello 2, Livello 15+ = Mod Livello 3. Solo i mod installati da GT vengono rimossi quando l'ordine Ã¨ cancellato.</t>
    <t id="9070">Configurazione della denominazione della nave</t>
    <t id="9071">Visualizza XP:</t>
    <t id="9072">Classifica di visualizzazione:</t>
    <t id="9073">Livello di visualizzazione:</t>
    <t id="9074">Stato di visualizzazione:</t>
    <t id="9075">Abilita la ridenominazione della nave:</t>
    <t id="9076">Prefisso</t>
    <t id="9077">Suffisso</t>
    <t id="9078">Origine nome predefinito:</t>
    <t id="9079">Nome del modello</t>
    <t id="9080">Digitare Nome</t>
    <t id="9081">Base del modello</t>
    <t id="9083">Nome personalizzato</t>
    <t id="9084">Mostra settore di origine:</t>
    <t id="9085">ModalitÃ  denominazione:</t>
    <t id="9086">Classica</t>
    <t id="9087">Modello</t>
    <t id="9088">Modello nome:</t>
    <t id="9089">Segnaposto: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. Atomici: {RS} {CB} {BL}, ecc. Usa le abbreviazioni di stato sotto. I segnaposto vuoti vengono omessi; gli spazi si comprimono. Max 128 caratteri.</t>
    <t id="9183">Mostra il settore di origine configurato nel nome della nave (prefisso o suffisso).</t>
    <t id="9184">Formato nome personalizzato con segnaposto {TOKEN} al posto delle opzioni classiche. Richiede XP GalaxyTrader (non modalitÃ  XP vanilla).</t>
    <t id="9092">Segnaposto modello</t>
    <t id="9093">Nave: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Base: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Equipaggio: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Settore: {SECTOR} | Statistiche: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Segnaposto stato:</t>
    <t id="9100">{OPSTATE}: tutti i flag operativi attivi combinati (es. CB RS, MT)</t>
    <t id="9101">{STATUS}: bloccato, addestramento, fallback o isolato</t>
    <t id="9102">{CB}: solo blacklist personalizzata; incluso in {OPSTATE}; non combinare</t>
    <t id="9082">Visualizza la classe della nave:</t>
    <t id="9171">Mostra i valori XP nei nomi delle navi</t>
    <t id="9175">Abilita o disabilita la ridenominazione automatica della nave con le informazioni del pilota</t>
    <t id="9172">Mostra i titoli di rango nei nomi delle navi</t>
    <t id="9173">Mostra i numeri di livello nei nomi delle navi</t>
    <t id="9174">Mostra lo stato commerciale nei nomi delle navi</t>
    <t id="9178">Scegli l'origine per i nomi delle basi della nave: Nome modello (con variante), Nome tipo (generico), Base modello (senza variante) o Nome personalizzato (nome memorizzato)</t>
    <t id="9182">Mostra la classe della nave (S, M, L, XL) nei nomi della nave</t>
    <t id="9200">Impostazioni di debug</t>
    <t id="9201">Abilita registrazione debug:</t>
    <t id="9202">Interruttore maestro per tutta l'uscita debug_text. Quando disabilitato, tutta la registrazione debug Ã¨ soppressa. Quando abilitato, i messaggi debug appaiono nel DebugLog basati su valori di probabilitÃ  individuali debug_text.</t>
    <t id="9220">Manutenzione e diagnostica</t>
    <t id="9221">Reimposta le statistiche dei profitti:</t>
    <t id="9222">RESET</t>
    <t id="9223">Cancella tutti i settori nella lista nera:</t>
    <t id="9224">CHIARO</t>
    <t id="9225">Ripristina tutte le impostazioni ai valori predefiniti:</t>
    <t id="9226">RESETTA TUTTO</t>
    <t id="9323">Rimuove tutti i settori dalla lista nera di intelligence delle minacce. Questo cancellerÃ  immediatamente tutti i settori in lista nera e permetterÃ  alle tue navi di viaggiare in aree precedentemente bloccate. Usa questo se vuoi ripristinare il sistema di evitamento minacce o se i settori sono stati erroneamente messi in lista nera.</t>
    <t id="9321">Ripristina tutte le statistiche dei profitti su 0 per tutti i piloti e le navi. Utilizzalo dopo l'aggiornamento alla versione 0.6.0 per cancellare le statistiche basate sulle entrate gonfiate. La correzione ora tiene traccia del PROFITTO effettivo (entrate - costi di acquisto). I conteggi degli scambi e gli XP vengono conservati.</t>
    <t id="9325">Ripristina tutte le impostazioni globali ai loro valori predefiniti. Questo include impostazioni XP, Coordinamento Flotta, Notifiche, Intelligence Mobile, Evitamento Minacce, Denominazione Navi, Auto-Riparazione, Modifiche, Prestazioni e Formato Numero. L'impostazione di registrazione debug Ã¨ preservata per consentire la registrazione dell'operazione di ripristino.</t>
    <t id="9227">Cancella cache commerciale per tutti i settori domestici:</t>
    <t id="9228">CANCELLARE CACHE</t>
    <t id="9327">Cancella la cache commerciale per tutti i settori di origine. Questo forzerÃ  tutte le navi a eseguire ricerche in diretta fresche nella loro prossima ricerca commerciale. Usa questo se la cache sembra obsoleta o corrotta, o se vuoi forzare un aggiornamento completo della cache.</t>
    <t id="9229">Rilascia tutti i blocchi di ricerca</t>
    <t id="9329">Rilascia TUTTI i blocchi di ricerca commerciale in corso e cancella gli stati transitori correlati. Usa questo se le navi sono bloccate su "Ricerca commerci" a causa di blocchi obsoleti provenienti da salvataggi vecchi. PuÃ² interrompere ricerche legittime.</t>
    <t id="9290">Stato dell'Hub commerciale discarica:</t>
    <t id="9291">SCARICO</t>
    <t id="9390">Mostra un'istantanea unica dell'hub commerciale centralizzato (code dello scheduler + stato dell'ultima spedizione richiedente) nel registro e come notifica.</t>
    <t id="9292">Scarica la cache commerciale (COMPLETA):</t>
    <t id="9293">SCARICA LA CACHE</t>
    <t id="9392">Dump COMPLETO della cache (puÃ² essere enorme). Scrive tutte le voci della cache nel DebugLog a blocchi. Clicca di nuovo per annullare.</t>
    <t id="9294">Cancella prenotazioni flotta:</t>
    <t id="9295">CHIARO</t>
    <t id="9394">Cancella tutte le prenotazioni commerciali attive della flotta. Usalo se le navi sembrano bloccate in attesa della scadenza delle transazioni riservate o se la tabella delle prenotazioni Ã¨ diventata obsoleta dopo aver caricato un vecchio salvataggio.</t>
    <t id="9230">Prestazione</t>
    <t id="9231">Ritardo elaborazione batch:</t>
    <t id="9232">Ritardo di convalida:</t>
    <t id="9233">Numero massimo di ricerche simultanee:</t>
    <t id="9234">Numero massimo di operazioni da restituire:</t>
    <t id="9235">Offerte massime per articolo:</t>
    <t id="9236">Massimi scambi per articolo:</t>
    <t id="9237">Offerte massime per articolo per abbinamento:</t>
    <t id="9238">Soglia di uscita anticipata:</t>
    <t id="9241">Intervallo di sezioni dell'offerta in tempo reale:</t>
    <t id="9266">Blocco ricerca TTL:</t>
    <t id="9263">Dimensione del blocco batch:</t>
    <t id="9239">Formato numero</t>
    <t id="9240">Stile formato:</t>
    <t id="9242">Utilizza il suffisso M</t>
    <t id="9243">Soglia suffisso M:</t>
    <t id="9244">Tedesco (123.456,78)</t>
    <t id="9245">Inglese (123.456,78)</t>
    <t id="9510">Notifiche di avanzamento di livello:</t>
    <t id="9511">Avvisi di formazione richiesta:</t>
    <t id="9512">Notifiche di formazione completata:</t>
    <t id="9513">Rapporti di profitto:</t>
    <t id="9514">Avvisi di mercato:</t>
    <t id="9515">Aggiornamenti flotta:</t>
    <t id="9516">Utilizza solo Vanilla XP</t>
    <t id="9610">Abilita o disabilita le notifiche popup di avanzamento di livello del trader nell'interfaccia giocatore.</t>
    <t id="9611">Avviso quando i piloti necessitano di formazione per avanzare al livello successivo.</t>
    <t id="9612">Notifica quando i piloti completano la formazione e avanzano di rango.</t>
    <t id="9613">Riepilogo periodico dei profitti (rapporti semplici e completi).</t>
    <t id="9614">OpportunitÃ  di mercato eccezionali e avvisi di scambi ad alto valore.</t>
    <t id="9615">Messaggi di coordinamento flotta e aggiornamenti di stato.</t>
    <t id="9616">Utilizza pilot.skill.piloting e disabilita GT XP progression/caps.</t>
    <t id="9246">Frequenza del rapporto semplice:</t>
    <t id="9247">Frequenza del rapporto completo:</t>
    <t id="9248">Numero massimo di ricerche simultanee nella cache:</t>
    <t id="9249">Numero massimo di ricerche live simultanee:</t>
    <t id="9340">Scegli il formato numerico: il tedesco usa '.' per le migliaia e ',' per i decimali (123.456,78), l'inglese usa ',' per le migliaia e '.' per i decimali (123.456,78)</t>
    <t id="9342">Abilita il suffisso M per i numeri superiori alla soglia (ad esempio, 1,0 M invece di 1.000.000)</t>
    <t id="9343">Soglia per il suffisso M. I numeri sopra questo valore verranno visualizzati con il suffisso M (impostazione predefinita: 999.999)</t>
    <t id="9346">Frequenza del report semplice (notifica popup): 0-30 minuti (0 = disabilitato - i report semplici sono disabilitati, impostazione predefinita: 1 minuto)</t>
    <t id="9347">Frequenza del rapporto completo (voce del registro): 0-60 minuti (0 = disabilitato - i rapporti completi sono disabilitati, impostazione predefinita: 30 minuti)</t>
    <t id="9398">Utilizza la sostituzione dei crediti GT dovuti</t>
    <t id="9399">Sostituisci o aumenta la riga standard "CR dovuta dalle transazioni" con il valore previsto in GT nello stesso slot dell'interfaccia utente.</t>
    <t id="9331">Ritardo tra lotti durante l'elaborazione ricerca commercio (1-100ms). Valori piÃ¹ alti riducono il carico CPU ma rallentano le ricerche commercio. Predefinito: 50ms. Usato nell'elaboratore lotti e filtraggio lista commercio.</t>
    <t id="9332">Ritardo tra validazioni commercio nello script AI (1-100ms). Valori piÃ¹ alti riducono il carico CPU ma rallentano la validazione commercio. Predefinito: 50ms. Usato quando si valida la lista commercio dal sistema MD.</t>
    <t id="9333">Numero massimo di ricerche commercio che possono essere eseguite simultaneamente (1-10). Valori piÃ¹ bassi riducono il carico CPU ma aumentano i tempi di attesa in coda. Valori piÃ¹ alti elaborano ricerche piÃ¹ velocemente ma possono causare picchi di prestazioni. Predefinito: 1.</t>
    <t id="9334">Numero massimo di commerci da restituire dalla ricerca cache (50-1000). Valori piÃ¹ alti forniscono piÃ¹ opzioni commercio ma aumentano il tempo di elaborazione. Valori piÃ¹ bassi riducono il carico CPU ma possono perdere commerci redditizi. Predefinito: 200.</t>
    <t id="9335">Numero massimo di offerte per merce da elaborare nella ricerca in tempo reale (5-100). Valori piÃ¹ alti considerano piÃ¹ offerte ma aumentano il tempo di elaborazione. Valori piÃ¹ bassi riducono il carico CPU ma possono perdere commerci redditizi. Predefinito: 20.</t>
    <t id="9336">Numero massimo di commerci per merce durante l'elaborazione lotti (5-100). Valori piÃ¹ alti permettono piÃ¹ commerci per merce ma aumentano il tempo di elaborazione. Valori piÃ¹ bassi riducono il carico CPU ma possono perdere commerci redditizi. Predefinito: 20.</t>
    <t id="9337">Numero massimo di offerte per merce per corrispondenza nell'elaboratore lotti (5-100). Valori piÃ¹ alti considerano piÃ¹ offerte ma aumentano il tempo di elaborazione. Valori piÃ¹ bassi riducono il carico CPU ma possono perdere commerci redditizi. Predefinito: 20.</t>
    <t id="9338">Soglia uscita anticipata per elaborazione lotti (100-10000). Quando vengono trovati cosÃ¬ tanti commerci, l'elaborazione lotti si ferma anticipatamente per risparmiare CPU. Valori piÃ¹ alti elaborano piÃ¹ commerci ma aumentano il carico CPU. Valori piÃ¹ bassi escono prima ma possono perdere commerci redditizi. Predefinito: 2000.</t>
    <t id="9341">Intervallo fetta offerte in diretta in millisecondi (5-500ms). Controlla la frequenza con cui possono iniziare le fette di offerte in diretta. Valori piÃ¹ bassi consentono una raccolta di offerte piÃ¹ veloce ma aumentano il carico CPU. Valori piÃ¹ alti riducono il carico CPU ma rallentano l'elaborazione della ricerca in diretta. Predefinito: 500ms.</t>
    <t id="9363">Dimensione lotto elaborazione (5-20). Elabora chunkSizeÃ—chunkSize combinazioni per lotto (ad esempio, 10Ã—10 = 100 combinazioni). Lotti piÃ¹ grandi migliorano la produttivitÃ  ma aumentano il carico CPU per lotto. Lotti piÃ¹ piccoli riducono i picchi CPU ma richiedono piÃ¹ continuazioni. Predefinito: 10.</t>
    <t id="9348">Numero massimo di ricerche cache che possono essere eseguite simultaneamente (1-20). Le ricerche cache sono veloci ed economiche, quindi valori piÃ¹ alti consentono piÃ¹ controlli cache paralleli senza impatto significativo sulla CPU. Valori piÃ¹ bassi riducono le ricerche cache parallele. Predefinito: 5.</t>
    <t id="9349">Numero massimo di ricerche live che possono essere eseguite simultaneamente (1-10). Le ricerche live sono intensive per la CPU, quindi valori piÃ¹ bassi riducono il carico CPU ma aumentano i tempi di attesa in coda. Valori piÃ¹ alti elaborano ricerche piÃ¹ velocemente ma possono causare picchi di prestazioni. Predefinito: 1.</t>
    <t id="9264">Dimensione blocco query cache:</t>
    <t id="9265">Offerta live Aggiungi dimensione blocco:</t>
    <t id="9364">Voci cache validate per lotto (10-200). Valori piÃ¹ piccoli distribuiscono la validazione cache su piÃ¹ frame (piÃ¹ fluido) ma possono aumentare il tempo per trovare un commercio in cache. Predefinito: 10.</t>
    <t id="9365">Offerte aggiunte per fetta aggiunta (50-2000). Valori piÃ¹ piccoli riducono il lavoro di aggiunta lista per frame (piÃ¹ fluido) ma possono rallentare il completamento della ricerca live. Predefinito: 200.</t>
    <t id="9366">Tempo di vita del blocco ricerca in secondi (60-7200). Se una nave viene negata con "ricerca commerciale giÃ  in corso" per piÃ¹ tempo di questo, GT si auto-guarirÃ  cancellando lo stato ricerca obsoleto e rilasciando il blocco. Predefinito: 600s.</t>
    <t id="9370">Soglia flessibile di contropressione batch:</t>
    <t id="9371">Soglia rigida di contropressione batch:</t>
    <t id="9372">Settori per fetta:</t>
    <t id="9373">Raffreddamento aggiornamento casa:</t>
    <t id="9374">Cache Miss Cooldown Base:</t>
    <t id="9375">Intervallo tick dello scheduler:</t>
    <t id="9376">Numero massimo di query cache per tick:</t>
    <t id="9377">Numero massimo di continuazioni di ricerca per tick:</t>
    <t id="9378">Numero massimo di spedizioni per tick:</t>
    <t id="9379">Numero massimo di articoli per tick:</t>
    <t id="9380">Riattivazione massima per tick:</t>
    <t id="9381">Voci massime query cache:</t>
    <t id="9382">Secondi di soglia obsoleti:</t>
    <t id="9383">Secondi soglia coda non aggiornati:</t>
    <t id="9384">Secondi di scadenza dell'operazione non riuscita:</t>
    <t id="9385">Numero massimo di ricerche di fallback simultanee:</t>
    <t id="9386">Numero massimo di ricerche di fallback simultanee:</t>
    <t id="9470">Soglia morbida per la coda del processore batch (5-50). Quando la coda raggiunge questo valore, inizia ad essere applicata contropressione per rallentare nuove richieste di ricerca. Valori piÃ¹ bassi attivano la contropressione prima (piÃ¹ conservativo). Predefinito: 10.</t>
    <t id="9471">Soglia dura per la coda del processore batch (10-100). Quando la coda raggiunge questo valore, le nuove ricerche in tempo reale vengono bloccate fino a quando la coda diminuisce. Valori piÃ¹ bassi bloccano le ricerche prima (piÃ¹ conservativo). Predefinito: 25.</t>
    <t id="9472">Settori elaborati per fetta nella raccolta offerte in tempo reale (1-5). Valori piÃ¹ bassi distribuiscono il lavoro su piÃ¹ frame (piÃ¹ fluido) ma possono rallentare la raccolta offerte. Valori piÃ¹ alti elaborano piÃ¹ velocemente ma possono causare picchi di frame. Predefinito: 1.</t>
    <t id="9473">Tempo di attesa dopo il completamento dell'aggiornamento del settore base (10-120 secondi). Previene richieste di aggiornamento eccessive. Valori piÃ¹ bassi consentono aggiornamenti piÃ¹ frequenti ma aumentano il carico CPU. Valori piÃ¹ alti riducono la frequenza di aggiornamento ma possono ritardare gli aggiornamenti della cache. Predefinito: 30s.</t>
    <t id="9474">Tempo di attesa base dopo un fallimento della cache prima di riprovare ricerca in tempo reale (1-30 secondi). Previene tentativi di riprova eccessivi. Valori piÃ¹ bassi riprovano prima ma aumentano il carico CPU. Valori piÃ¹ alti riducono la frequenza di riprova ma possono ritardare la ricerca di scambi. Predefinito: 10s.</t>
    <t id="9475">Intervallo tra i tick dello scheduler in millisecondi (50-500ms). Controlla la frequenza con cui lo scheduler elabora la coda di lavoro. Valori piÃ¹ bassi elaborano piÃ¹ frequentemente ma aumentano il carico CPU. Valori piÃ¹ alti riducono il carico CPU ma possono aumentare i tempi di attesa in coda. Predefinito: 100ms.</t>
    <t id="9476">Numero massimo di query cache avviate per tick dello scheduler (1-5). Limita la velocitÃ  delle query cache per evitare il blocco dei frame. Valori piÃ¹ bassi riducono i picchi CPU ma rallentano le ricerche cache. Valori piÃ¹ alti elaborano piÃ¹ velocemente ma possono causare sfarfallio. Predefinito: 1.</t>
    <t id="9477">Numero massimo di continuazioni ricerca avviate per tick dello scheduler (1-5). Limita la velocitÃ  di continuazione per evitare il blocco dei frame. Valori piÃ¹ bassi riducono i picchi CPU ma rallentano l'elaborazione ricerca. Valori piÃ¹ alti elaborano piÃ¹ velocemente ma possono causare sfarfallio. Predefinito: 1.</t>
    <t id="9478">Numero massimo di navi elaborate per tick dello scheduler (1-5). Limita la velocitÃ  di elaborazione navi per evitare il blocco dei frame. Valori piÃ¹ bassi riducono i picchi CPU ma rallentano l'elaborazione coda. Valori piÃ¹ alti elaborano piÃ¹ velocemente ma possono causare sfarfallio. Predefinito: 1.</t>
    <t id="9479">Numero massimo di elementi lavoro elaborati per tick dello scheduler (1-5). Limita la velocitÃ  di elaborazione elementi per evitare il blocco dei frame. Valori piÃ¹ bassi riducono i picchi CPU ma rallentano l'elaborazione coda. Valori piÃ¹ alti elaborano piÃ¹ velocemente ma possono causare sfarfallio. Predefinito: 1.</t>
    <t id="9480">Numero massimo di attese risvegliate per tick dello scheduler (1-10). Limita la velocitÃ  di risveglio per evitare picchi CPU quando molte attese sono in coda. Valori piÃ¹ bassi riducono i picchi CPU ma rallentano l'elaborazione attese. Valori piÃ¹ alti elaborano piÃ¹ velocemente ma possono causare sfarfallio. Predefinito: 2.</t>
    <t id="9481">Numero massimo di voci cache interrogate per lotto (1-200). Controlla la dimensione del lotto query cache. Valori piÃ¹ bassi rendono le ricerche cache piÃ¹ veloci ma possono perdere scambi migliori. Valori piÃ¹ alti considerano piÃ¹ scambi in cache ma aumentano il tempo di validazione. Predefinito: 50.</t>
    <t id="9482">Soglia di obsolescenza dello stato ricerca in tempo reale in secondi (60-600). Quando lo stato ricerca in tempo reale Ã¨ piÃ¹ vecchio di questo valore, Ã¨ considerato obsoleto e viene pulito. Valori piÃ¹ bassi puliscono lo stato obsoleto prima ma possono interrompere ricerche legittime. Valori piÃ¹ alti consentono ricerche piÃ¹ lunghe ma possono lasciare stato obsoleto. Predefinito: 300s.</t>
    <t id="9483">Soglia di obsolescenza elementi coda in secondi (30-300). Quando gli elementi coda sono piÃ¹ vecchi di questo valore, sono considerati obsoleti e vengono rimossi. Valori piÃ¹ bassi puliscono gli elementi obsoleti prima ma possono rimuovere elementi coda legittimi. Valori piÃ¹ alti consentono tempi coda piÃ¹ lunghi ma possono lasciare elementi obsoleti. Predefinito: 60s.</t>
    <t id="9484">Scadenza cache scambi falliti in secondi (300-3600). Gli scambi falliti vengono memorizzati in cache per evitare di riprovare immediatamente. Valori piÃ¹ bassi fanno scadere gli scambi falliti prima (piÃ¹ riprove) ma riducono l'efficacia della cache. Valori piÃ¹ alti memorizzano in cache piÃ¹ a lungo (meno riprove) ma possono ritardare i tentativi di riprova. Predefinito: 1800s (30 minuti).</t>
    <t id="9485">Numero massimo di ricerche in tempo reale di fallback simultanee (1-10). Le ricerche di fallback ignorano il blocco del settore base, consentendo a piÃ¹ navi dello stesso settore base di cercare simultaneamente. Valori piÃ¹ bassi riducono il carico CPU ma possono rallentare le ricerche di fallback. Valori piÃ¹ alti consentono piÃ¹ ricerche di fallback parallele ma aumentano l'uso della CPU. Predefinito: 1.</t>
    <t id="9490">Ritardo del segnale del trade trovato:</t>
    <t id="9590">Ritardo prima di inviare il segnale GT_Trade_Found alle navi in millisecondi (10-1000ms). Le navi attendono sempre (ritardo configurato + buffer di 5ms) prima di inviare nuove richieste per catturare segnali ritardati. Valori piÃ¹ alti distribuiscono i segnali tra i frame per prestazioni piÃ¹ fluide. Predefinito: 10ms.</t>
    <t id="8000">Flotta GalaxyTrader</t>
    <t id="8001">Gestione della flotta GalaxyTrader e statistiche dei piloti</t>
    <t id="8002">Visualizza e gestisci tutti i piloti GalaxyTrader</t>
    <t id="8100">Identificativo della nave</t>
    <t id="8101">Pilota</t>
    <t id="8102">Nave</t>
    <t id="8103">Stato</t>
    <t id="8104">Rango</t>
    <t id="8105">Livello</t>
    <t id="8106">XP</t>
    <t id="8107">Profitto a vita</t>
    <t id="8108">Posizione</t>
    <t id="8109">Base domestica</t>
    <t id="8110">Ultimo scambio</t>
    <t id="8111">Profitto pilota</t>
    <t id="8112">Profitto della nave</t>
    <t id="8113">Conteggio degli scambi</t>
    <t id="8200">Aggiorna</t>
    <t id="8201">Esporta CSV</t>
    <t id="8202">Statistiche</t>
    <t id="8203">Impostazioni</t>
    <t id="8204">Aiuto</t>
    <t id="8205">Vicino</t>
    <t id="8300">Tutti i piloti</t>
    <t id="8301">Commercio</t>
    <t id="8302">Formazione</t>
    <t id="8303">Manutenzione</t>
    <t id="8304">Emergenza</t>
    <t id="8305">Principianti (Lv 1-5)</t>
    <t id="8306">Avanzato (Lv 6-11)</t>
    <t id="8307">Esperti (Liv. 12+)</t>
    <t id="8308">I 10 migliori guadagni</t>
    <t id="8350">Ordina per:</t>
    <t id="8351">Identificativo della nave</t>
    <t id="8352">Nome del pilota</t>
    <t id="8353">Tipo di nave</t>
    <t id="8354">Stato</t>
    <t id="8355">Rango</t>
    <t id="8356">Livello</t>
    <t id="8357">XP</t>
    <t id="8358">Profitto</t>
    <t id="8400">Nessun pilota registrato</t>
    <t id="8401">Nessun pilota corrisponde al filtro</t>
    <t id="8402">Piloti totali:</t>
    <t id="8403">Profitto totale della flotta:</t>
    <t id="8404">Ultimo aggiornamento:</t>
    <t id="8405">Cerca piloti...</t>
    <t id="8114">Settore</t>
    <t id="8320">Rinominazione della nave</t>
    <t id="8321">Nome personalizzato</t>
    <t id="8322">Imposta nome</t>
    <t id="8323">Cancella nome</t>
    <t id="8324">Nome impostato correttamente</t>
    <t id="8325">Nome cancellato con successo</t>
    <t id="8450">Invia alla formazione</t>
    <t id="8451">Annulla registrazione</t>
    <t id="8452">Vendita forzata di merci</t>
    <t id="8453">Invia in riparazione</t>
    <t id="8454">Invia per rifornire</t>
    <t id="8455">Interrompi tutti gli ordini</t>
    <t id="8456">Azioni</t>
    <t id="8500">Fare clic per ordinare per ID nave</t>
    <t id="8501">Fare clic per ordinare per nome del pilota</t>
    <t id="8502">Fare clic per ordinare per tipo di spedizione</t>
    <t id="8503">Fare clic per ordinare per Stato</t>
    <t id="8504">Fare clic per ordinare in base alla posizione</t>
    <t id="8505">Fare clic per ordinare per livello</t>
    <t id="8506">Fare clic per ordinare per XP</t>
    <t id="8507">Fare clic per ordinare in base al profitto a vita</t>
    <t id="8508">Aggiorna i dati del pilota dal sistema di missione</t>
    <t id="8509">Esporta la vista corrente in un file CSV</t>
    <t id="8510">Visualizza statistiche e grafici della flotta</t>
    <t id="8511">Configurare le impostazioni del menu</t>
    <t id="8512">Mostra la guida e le scorciatoie da tastiera</t>
    <t id="8600">Nessun pilota GalaxyTrader trovato</t>
    <t id="8601">Crea piloti assegnando navi a GalaxyTrader o attendi il caricamento dei dati.</t>
    <t id="9001">Rinomina GT</t>
    <t id="9902">Invia alla formazione</t>
    <t id="9903">Addestramento manuale in coda per %1. Il pilota inizierÃ  l'addestramento dopo il ciclo corrente.</t>
    <t id="9904">Allenamento in coda dopo il ciclo corrente</t>
    <t id="9905">Pilota o nave non trovati</t>
    <t id="9906">La formazione automatica Ã¨ abilitata: coda manuale non richiesta</t>
    <t id="9907">L'addestramento del pilota non Ã¨ bloccato</t>
    <t id="9910">Accademia Commerciale</t>
    <t id="9911">Apprendista (Lvl 4) - %1 / %2</t>
    <t id="9912">Commerciante (Lvl 7) - %1 / %2</t>
    <t id="9913">Mastro Commerciante (Lvl 13) - %1 / %2</t>
    <t id="9920">Pilota %1 iscritto al corso dell'Accademia per il Livello %2. In partenza per la stazione commerciale piÃ¹ vicina.</t>
    <t id="9921">Fondi insufficienti per questo corso (servono %1, disponibili %2).</t>
    <t id="9922">Corso non disponibile - il pilota %1 Ã¨ giÃ  a questo livello o superiore.</t>
    <t id="9923">Pilota %1 iscritto al corso di Livello %2 dell'Accademia Commerciale (costo: %3 Cr, durata: %4 min) a bordo di %5.</t>
    <t id="11011">Riduttore per nave media GT Apprentice</t>
    <t id="11012">Modifica motore che riduce leggermente le prestazioni per piloti inesperti su navi medie. Usato dal sistema AI GalaxyTrader. -5% velocitÃ , spinta e rotazione.</t>
    <t id="11013">Riduttore da viaggio medio GT Apprentice</t>
    <t id="11014">Modifica motore che riduce leggermente le prestazioni di viaggio per piloti inesperti su navi medie. Usato dal sistema AI GalaxyTrader. -5% velocitÃ  di viaggio.</t>
    <t id="11021">Riduttore per navi di grandi dimensioni GT Apprentice</t>
    <t id="11022">Modifica motore che riduce le prestazioni per piloti inesperti su navi grandi. Usato dal sistema AI GalaxyTrader. -15% velocitÃ , spinta e rotazione.</t>
    <t id="11023">Riduttore da viaggio grande GT Apprentice</t>
    <t id="11024">Modifica motore che riduce le prestazioni di viaggio per piloti inesperti su navi grandi. Usato dal sistema AI GalaxyTrader. -15% velocitÃ  di viaggio.</t>
    <t id="11031">Riduttore per navi capitali GT Apprentice</t>
    <t id="11032">Modifica motore che riduce significativamente le prestazioni per piloti inesperti su navi capitali. Usato dal sistema AI GalaxyTrader. -25% velocitÃ , spinta e rotazione.</t>
    <t id="11033">Riduttore di viaggio capitale GT Apprentice</t>
    <t id="11034">Modifica motore che riduce significativamente le prestazioni di viaggio per piloti inesperti su navi capitali. Usato dal sistema AI GalaxyTrader. -25% velocitÃ  di viaggio.</t>
    <t id="12001">Potenziamento base GT per piccole navi</t>
    <t id="12002">Modifica motore specializzata per navi piccole con piloti certificati base. Usato dal sistema AI GalaxyTrader. +3% velocitÃ , spinta e rotazione.</t>
    <t id="12003">Potenziatore da viaggio piccolo GT Basic</t>
    <t id="12004">Modifica motore specializzata per navi piccole con piloti certificati base. Usato dal sistema AI GalaxyTrader. +3% velocitÃ  di viaggio.</t>
    <t id="13001">Riduttore per navi di grandi dimensioni GT Basic</t>
    <t id="13002">Modifica motore specializzata per navi grandi con piloti certificati base. Usato dal sistema AI GalaxyTrader. -8% velocitÃ , spinta e rotazione.</t>
    <t id="13003">Riduttore da corsa grande GT Basic</t>
    <t id="13004">Modifica motore specializzata per navi grandi con piloti certificati base. Usato dal sistema AI GalaxyTrader. -8% velocitÃ  di viaggio.</t>
    <t id="14001">Riduttore base GT per navi capitali</t>
    <t id="14002">Modifica motore specializzata per navi capitali con piloti certificati base. Usato dal sistema AI GalaxyTrader. -15% velocitÃ , spinta e rotazione.</t>
    <t id="14003">Riduttore di corsa del capitale GT Basic</t>
    <t id="14004">Modifica motore specializzata per navi capitali con piloti certificati base. Usato dal sistema AI GalaxyTrader. -15% velocitÃ  di viaggio.</t>
    <t id="15001">Potenziatore per piccole navi GT Expert</t>
    <t id="15002">Modifica motore avanzata per navi piccole con piloti esperti. Usato dal sistema AI GalaxyTrader. +25% velocitÃ , spinta e rotazione.</t>
    <t id="15003">Potenziatore da viaggio piccolo GT Expert</t>
    <t id="15004">Modifica motore avanzata per navi piccole con piloti esperti. Usato dal sistema AI GalaxyTrader. +25% velocitÃ  di viaggio.</t>
    <t id="16001">Potenziatore per navi grandi GT Expert</t>
    <t id="16002">Modifica motore avanzata per navi grandi con piloti esperti. Usato dal sistema AI GalaxyTrader. +15% velocitÃ , spinta e rotazione.</t>
    <t id="16003">Potenziatore di viaggio di grandi dimensioni GT Expert</t>
    <t id="16004">Modifica motore avanzata per navi grandi con piloti esperti. Usato dal sistema AI GalaxyTrader. +15% velocitÃ  di viaggio.</t>
    <t id="17001">Potenziatore di navi capitali GT Expert</t>
    <t id="17002">Modifica motore avanzata per navi capitali con piloti esperti. Usato dal sistema AI GalaxyTrader. +6% velocitÃ , spinta e rotazione.</t>
    <t id="17003">Potenziatore di viaggi di capitale GT Expert</t>
    <t id="17004">Modifica motore avanzata per navi capitali con piloti esperti. Usato dal sistema AI GalaxyTrader. +6% velocitÃ  di viaggio.</t>
    <t id="18001">Limitazione Grave delle AbilitÃ  (Nave)</t>
    <t id="18002">Limitazione Grave delle AbilitÃ  (Nave) - Rappresenta penalitÃ  di prestazione gravi dovute all'inesperienza del pilota con navi grandi. Applicata automaticamente dal sistema GalaxyTrader quando l'abilitÃ  del pilota Ã¨ insufficiente per le dimensioni della nave. Aumenta la massa della nave. (Solo sistema GT - Non disponibile per installazione manuale)</t>
    <t id="18003">Limitazione Moderata delle AbilitÃ  (Nave)</t>
    <t id="18004">Limitazione Moderata delle AbilitÃ  (Nave) - Rappresenta penalitÃ  di prestazione moderate durante l'adattamento del pilota alla complessitÃ  della nave. Applicata automaticamente dal sistema GalaxyTrader quando l'abilitÃ  del pilota Ã¨ insufficiente per le dimensioni della nave. Aumenta la massa della nave. (Solo sistema GT - Non disponibile per installazione manuale)</t>
    <t id="18005">Limitazione Lieve delle AbilitÃ  (Nave)</t>
    <t id="18006">Limitazione Lieve delle AbilitÃ  (Nave) - Rappresenta penalitÃ  di prestazione minori durante lo sviluppo delle abilitÃ  del pilota. Applicata automaticamente dal sistema GalaxyTrader quando l'abilitÃ  del pilota Ã¨ insufficiente per le dimensioni della nave. Aumenta la massa della nave. (Solo sistema GT - Non disponibile per installazione manuale)</t>
    <t id="18007">Limitazione Grave delle AbilitÃ  (Motore)</t>
    <t id="18008">Limitazione Grave delle AbilitÃ  (Motore) - Rappresenta penalitÃ  di prestazione gravi dovute all'inesperienza del pilota con navi grandi. Applicata automaticamente dal sistema GalaxyTrader quando l'abilitÃ  del pilota Ã¨ insufficiente per le dimensioni della nave. Riduce la spinta e la rotazione del motore. (Solo sistema GT - Non disponibile per installazione manuale)</t>
    <t id="18009">Limitazione Moderata delle AbilitÃ  (Motore)</t>
    <t id="18010">Limitazione Moderata delle AbilitÃ  (Motore) - Rappresenta penalitÃ  di prestazione moderate durante l'adattamento del pilota alla complessitÃ  della nave. Applicata automaticamente dal sistema GalaxyTrader quando l'abilitÃ  del pilota Ã¨ insufficiente per le dimensioni della nave. Riduce la spinta e la rotazione del motore. (Solo sistema GT - Non disponibile per installazione manuale)</t>
    <t id="18011">Limitazione Lieve delle AbilitÃ  (Motore)</t>
    <t id="18012">Limitazione Lieve delle AbilitÃ  (Motore) - Rappresenta penalitÃ  di prestazione minori durante lo sviluppo delle abilitÃ  del pilota. Applicata automaticamente dal sistema GalaxyTrader quando l'abilitÃ  del pilota Ã¨ insufficiente per le dimensioni della nave. Riduce la spinta e la rotazione del motore. (Solo sistema GT - Non disponibile per installazione manuale)</t>
    <t id="9250">Denominazione dello stato della nave</t>
    <t id="9350">Personalizza le abbreviazioni dello stato della nave. I valori predefiniti vengono visualizzati nelle caselle di input e possono essere sovrascritti. Massimo 3 caratteri. Tutti i nomi delle navi verranno aggiornati automaticamente quando modificati.</t>
    <t id="9251">Abbreviazione dello stato di rifornimento:</t>
    <t id="9252">Abbreviazione dello stato di riparazione:</t>
    <t id="9253">Abbreviazione dello stato di manutenzione:</t>
    <t id="9254">Abbreviazione dello stato di formazione:</t>
    <t id="9255">Abbreviazione dello stato del reindirizzamento:</t>
    <t id="9256">Abbreviazione dello stato di autorizzazione:</t>
    <t id="9257">Abbreviazione dello stato bloccato:</t>
    <t id="9258">Abbreviazione dello stato di fallback:</t>
    <t id="9259">Abbreviazione dello stato isolato:</t>
    <t id="9260">Abbreviazione dello stato commerciale:</t>
    <t id="9261">Abbreviazione dello stato di inattivitÃ :</t>
    <t id="9262">Abbreviazione dello stato di fuga:</t>
    <t id="9268">Abbreviazione dello stato irraggiungibile:</t>
    <t id="9269">Abbreviazione dello stato dello scambio pilota:</t>
    <t id="9270">Tag prefisso lista nera personalizzato:</t>
    <t id="9700">TRUCCHI (rotto. non c e nulla da vedere!! davvero!!)</t>
    <t id="9701">Navi GT invulnerabili</t>
    <t id="9702">Tutte le navi del giocatore invulnerabili</t>
    <t id="9800">Avanti, pilota. Strumenti di test rotti, non un menu divertente. Niente da vedere qui. Davvero. Sei stato avvertito. Probabilmente.</t>
    <t id="9801">Le navi con ordine GalaxyTrader non possono scendere sotto il 100% di scafo o scudi. Clicca di nuovo per disattivare.</t>
    <t id="9802">Tutte le navi del giocatore non possono scendere sotto il 100% di scafo o scudi. Clicca di nuovo per disattivare. Le stazioni non sono interessate.</t>
    <t id="9703">Rivela universo per test GT</t>
    <t id="9704">Rivelato</t>
    <t id="9705">Rivela</t>
    <t id="9803">Rivela la nebbia di guerra di tutti i settori, segna tutte le stazioni come note, concede tutte le licenze di abbonamento commerciale e sottoscrive le offerte commerciali in tutta la galassia. Clicca di nuovo dopo nuovi settori DLC. Solo per test.</t>
    <t id="9706">Massimizza XP piloti GT registrati</t>
    <t id="9707">Massimizzato</t>
    <t id="9708">XP max</t>
    <t id="9804">Imposta livello 15 e XP max per ogni pilota nel registro GT. Rimuove blocchi addestramento. Ignorato con solo XP vanilla. Solo per test.</t>
    <t id="9351">Abbreviazione per stato di rifornimento (predefinito: RS)</t>
    <t id="9352">Abbreviazione di Stato riparazione (impostazione predefinita: RP)</t>
    <t id="9353">Abbreviazione di Stato di manutenzione (impostazione predefinita: MT)</t>
    <t id="9354">Abbreviazione di Stato di allenamento (predefinito: TR)</t>
    <t id="9355">Abbreviazione di Stato reindirizzamento (impostazione predefinita: RR)</t>
    <t id="9356">Abbreviazione di Stato di autorizzazione (predefinito: CL)</t>
    <t id="9357">Abbreviazione per stato Bloccato (predefinito: BL)</t>
    <t id="9358">Abbreviazione per stato Fallback (impostazione predefinita: FB)</t>
    <t id="9359">Abbreviazione di Stato isolato (impostazione predefinita: IS)</t>
    <t id="9360">Abbreviazione di Stato commerciale (impostazione predefinita: TD)</t>
    <t id="9361">Abbreviazione di Stato inattivo (impostazione predefinita: ID)</t>
    <t id="9362">Abbreviazione di Escape state (default: ES)</t>
    <t id="9367">Abbreviazione di Stato irraggiungibile (predefinito: UR)</t>
    <t id="9368">Abbreviazione per stato Pilot Exchange (predefinito: PE)</t>
    <t id="9369">Mostrato come prefisso per le navi MK3 interessate da una lista nera di fazioni personalizzata (inclusi i subordinati). Predefinito: CB</t>
    <t id="30002">Galaxy Trader MK1</t>
    <t id="30102">Commerciante di stazioni: vende prodotti di stazioni alle fazioni NPC</t>
    <t id="30010">Stazione domestica</t>
    <t id="30011">Distanza massima di vendita</t>
    <t id="30012">Ignora le regole commerciali</t>
    <t id="30013">Filtro articoli</t>
    <t id="30014">Vendi target di riempimento del carico%</t>
    <t id="30015">Tolleranza di tornare indietro</t>
    <t id="30016">Acquista percentuale di riempimento del carico</t>
    <t id="30017">Voci del registro</t>
    <t id="30018">Livello di notifica</t>
    <t id="30019">Coordinamento della flotta</t>
    <t id="30020">Livello di debug</t>
    <t id="30021">Stazione di rifornimento</t>
    <t id="30022">% di memoria minima della stazione</t>
    <t id="30023">Consenti merci illegali</t>
    <t id="30024">Carico/Profitto</t>
    <t id="30025">Consenti multi-scambio</t>
    <t id="30110">Stazione del giocatore da cui vendere le merci (Ã¨ richiesta l'assegnazione della stazione)</t>
    <t id="30111">Distanza massima del cancello per trovare acquirenti NPC (limitata dall'abilitÃ  del pilota)</t>
    <t id="30112">Ignora le restrizioni sul commercio delle stazioni: vendi a qualsiasi fazione amica indipendentemente dalle regole del commercio delle stazioni</t>
    <t id="30113">Filtro articoli opzionale; lasciare vuoto per vendere tutti i prodotti e i prodotti della stazione</t>
    <t id="30114">Percentuale minima di riempimento del carico prima della partenza per i viaggi di vendita</t>
    <t id="30115">Numero massimo di salti extra consentiti quando si aggiunge un secondo articolo a un viaggio (0 = solo acquirenti direttamente sul percorso)</t>
    <t id="30116">Obiettivo di riempimento del carico per i viaggi di rifornimento (obiettivo morbido, il commerciante puÃ² partire prima)</t>
    <t id="30117">Abilita le voci del registro per operazione</t>
    <t id="30118">Livello di notifica: 0=Silenzioso, 1=Normale, 2=Verboso</t>
    <t id="30119">Abilita il coordinamento della flotta e il sistema di prenotazione commerciale</t>
    <t id="30120">Livello di registrazione del debug: 0=Disattivato, 1=Normale, 2=Verboso</t>
    <t id="30121">Se abilitato, acquista anche risorse per la stazione. La fornitura ha la prioritÃ  quando lo stoccaggio scende al di sotto della soglia minima</t>
    <t id="30122">Quando una risorsa scende al di sotto di questa percentuale del suo obiettivo, l'offerta ha la prioritÃ  sulla vendita. Ignorato se la stazione non puÃ² permettersi risorse</t>
    <t id="30123">Consentire la vendita o l'acquisto di articoli illegali/di contrabbando quando disponibili</t>
    <t id="30124">Selezione vendite: 1 = Carico (prioritÃ  al maggior riempimento del deposito per merce; paritÃ  per profitto), 2 = Profitto (miglior punteggio di profitto)</t>
    <t id="30125">Consente di concatenare piÃ¹ vendite in un ciclo (fino a 3 merci o destinazioni). Disattiva per cicli con un solo scambio</t>
    <t id="30200">Vendo %1 %2 da %3 a %4</t>
    <t id="30201">Nessun acquirente trovato per i prodotti della stazione nel raggio di %1 salti</t>
    <t id="30202">Stazione di partenza %1 distrutta - ordine del commerciante di stazione annullato</t>
    <t id="30203">La stazione di casa %1 non Ã¨ piÃ¹ di proprietÃ  del giocatore: ordine annullato</t>
    <t id="30204">Ãˆ richiesta l'assegnazione della stazione: ordine annullato</t>
    <t id="30205">MK1 Station Trader ha iniziato alle %1</t>
    <t id="30206">Vendita completata: %1 %2 venduto a %3 per %4 Cr (profitto: %5 Cr)</t>
    <t id="30207">Viaggio multi-ware: consegna di %1 articoli a %2 destinazioni</t>
    <t id="30208">Fornitura di %1 %2 a %3 da %4</t>
    <t id="30500">Impostazioni GalaxyTrader MK1</t>
    <t id="30501">Impostazioni predefinite del commerciante di stazione</t>
    <t id="30502">Distanza di vendita massima predefinita</t>
    <t id="30503">Obiettivo di riempimento del carico di vendita predefinito</t>
    <t id="30504">Impostazione predefinita Ignora regole commerciali</t>
    <t id="30505">Tolleranza di backtrack predefinita</t>
    <t id="30506">Tempo di attesa quando non Ã¨ stata trovata alcuna operazione</t>
    <t id="30507">Obiettivo di riempimento del carico di acquisto predefinito</t>
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">Mining autonomo con rifornimento di stazioni e progressione di XP</t>
    <t id="31010">Stazione domestica</t>
    <t id="31110">Stazione per l'estrazione e la consegna (mutuamente esclusivi con il settore Home)</t>
    <t id="31011">Settore Casa</t>
    <t id="31111">Settore in cui operare; utilizzato quando non Ã¨ impostata alcuna stazione domestica</t>
    <t id="31012">Carrello delle risorse</t>
    <t id="31112">Merci da miniera; vuoto segue la risoluzione della domanda della stazione</t>
    <t id="31013">Stazioni bersaglio</t>
    <t id="31113">Filtro stazione opzionale per consegne; vuoto deriva dal contesto domestico</t>
    <t id="31014">Soglia di overflow%</t>
    <t id="31114">Le stazioni pari o superiori a questa percentuale di memoria vengono considerate piene</t>
    <t id="31015">Consenti la vendita in eccesso ad altri</t>
    <t id="31115">Quando abilitato e gli obiettivi primari sono pieni, vendi ad altre stazioni di fazione</t>
    <t id="31016">Assegna alla stazione</t>
    <t id="31116">Assegnare la nave come subordinata mineraria della Stazione di origine, quando applicabile</t>
    <t id="31017">Resta a casa</t>
    <t id="31117">Limitare l'estrazione/vendita all'area di residenza, ad eccezione delle esecuzioni di fallback in overflow</t>
    <t id="31018">Distribuzione automatica delle sonde delle risorse</t>
    <t id="31118">Distribuisci automaticamente le sonde delle risorse caricate e includi le sonde nel rifornimento di manutenzione</t>
    <t id="31019">Distanza massima di raccolta</t>
    <t id="31119">Distanza massima del gate per il raduno (0 utilizza il limite di abilitÃ  pilota/comandante)</t>
    <t id="31020">Distanza massima di vendita</t>
    <t id="31120">Distanza massima del cancello per la vendita (0 utilizza il limite di abilitÃ  pilota/comandante)</t>
    <t id="31021">Bilanciamento della flotta</t>
    <t id="31121">Abilita il coordinamento deterministico degli intenti per ridurre l'overflow della stazione</t>
    <t id="31022">Intervallo di ricontrollo della domanda</t>
    <t id="31122">La frequenza con cui viene eseguita la valutazione della domanda/cambiamento del miner</t>
    <t id="31023">Delta della domanda critica</t>
    <t id="31123">Delta di urgenza minimo richiesto per cambiare il mining ware attivo</t>
    <t id="31024">Tempo di ricarica minimo per il cambio</t>
    <t id="31124">Tempo minimo tra due cambi di merce per questa nave</t>
    <t id="31025">% impegno carico minimo</t>
    <t id="31125">Se il riempimento del carico Ã¨ superiore a questo valore, la nave preferisce terminare la consegna corrente prima del cambio</t>
    <t id="31026">Delta di emergenza difficile</t>
    <t id="31126">Delta di urgenza che consente il passaggio immediato nonostante la soglia di impegno del carico</t>
    <t id="31027">Livello di notifica</t>
    <t id="31127">Livello di notifica: 0=Silenzioso, 1=Normale, 2=Verboso</t>
    <t id="31028">Solo stazioni giocatore</t>
    <t id="31128">Se abilitato, solo le stazioni di proprietÃ  dei giocatori sono considerate obiettivi della domanda.</t>
    <t id="31031">Verifica domanda prima</t>
    <t id="31131">Se attivato, il minatore controlla la domanda delle stazioni prima di estrarre e priorizza le merci di conseguenza. Se disattivato, estrae dal paniere risorse senza controlli di domanda e accumula fino a un acquirente disponibile (consigliato per flotte mono-risorsa).</t>
    <t id="31032">Interruzione magazzino fisico %</t>
    <t id="31132">Per piloti di livello 6+: interrompe l'estrazione della merce corrente quando lo stock fisico della stazione piÃ¹ il carico dei minatori rilevanti supererebbe lo stock fisico attuale di questa percentuale. Usa quantitÃ  di carico reali, non la soglia di overflow. 0 = disattivato.</t>
    <t id="32002">GalaxyTrader Fornitura MK4</t>
    <t id="32102">Commerciante di forniture della stazione del giocatore che utilizza la pipeline di ricerca cache/live GT</t>
    <t id="32010">Distanza di copertura</t>
    <t id="32110">Distanza massima del gate da casa per la ricerca della domanda di destinazione</t>
    <t id="32011">Acquista Distanza</t>
    <t id="32111">Distanza massima del cancello da casa per la ricerca dei fornitori</t>
    <t id="32012">Servire solo a domicilio</t>
    <t id="32112">Quando abilitato, viene soddisfatta solo la domanda della stazione domestica</t>
    <t id="32013">Costruisci solo stazioni</t>
    <t id="32113">Se abilitato, viene soddisfatta solo la richiesta di archiviazione di build</t>
    <t id="32014">Acquista dal giocatore</t>
    <t id="32114">Consenti l'approvvigionamento di articoli da fornitori di proprietÃ  dei giocatori</t>
    <t id="32015">Acquista dalla fazione</t>
    <t id="32115">Consenti l'approvvigionamento di merci da fornitori di fazioni non giocanti</t>
    <t id="32016">Consenti risorse</t>
    <t id="32116">Includere articoli di risorse nella corrispondenza della domanda</t>
    <t id="32017">Consenti intermedi</t>
    <t id="32117">Includere gli articoli intermedi nella corrispondenza della domanda</t>
    <t id="32018">Consenti prodotti</t>
    <t id="32118">Includere i prodotti nella corrispondenza della domanda</t>
    <t id="32019">Consenti Tradewares</t>
    <t id="32119">Includere articoli commerciali nella corrispondenza della domanda</t>
    <t id="20002">Galaxy Trader MK2</t>
    <t id="20102">Distribuzione magazzino con gestione soglie di stoccaggio</t>
    <t id="20010">Stazioni di origine</t>
    <t id="20011">Stazioni di destinazione</t>
    <t id="20012">% di archiviazione minima</t>
    <t id="20013">% di archiviazione statica</t>
    <t id="20014">% di archiviazione massima</t>
    <t id="20015">Filtro articoli</t>
    <t id="20016">ModalitÃ  bidirezionale</t>
    <t id="20017">Stazione domestica (opzionale)</t>
    <t id="20018">Distanza massima</t>
    <t id="20032">Settore domestico (opzionale)</t>
    <t id="20019">Tempo di attesa del ciclo</t>
    <t id="20030">Consenti volume basso</t>
    <t id="20031">% minima del volume minimo</t>
    <t id="20110">Elenco delle stazioni di origine da cui distribuire le merci</t>
    <t id="20111">Elenco delle stazioni/magazzini di destinazione a cui distribuire le merci</t>
    <t id="20112">Soglia urgenza destinazione: sotto questa % la stazione ha prioritÃ </t>
    <t id="20113">Soglia minima della fonte: la fonte deve avere piÃ¹ di questa percentuale per essere distribuita</t>
    <t id="20114">Soglia di overflow della sorgente: al di sopra di questa % la sorgente distribuisce anche a destinazioni non urgenti</t>
    <t id="20115">Filtro articoli opzionale; lasciare vuoto per distribuire tutti gli articoli dalla fonte</t>
    <t id="20116">Abilita raccolta di ritorno dalle destinazioni alla sorgente quando c'Ã¨ eccesso</t>
    <t id="20117">Stazione domestica opzionale per l'assegnazione. Se vuota, la nave rimane non assegnata alle stazioni.</t>
    <t id="20118">Distanza massima del gate tra sorgente e destinazioni (0 = illimitata)</t>
    <t id="20132">Settore domestico opzionale usato per il parcheggio in inattivitÃ  quando non Ã¨ impostata una stazione domestica.</t>
    <t id="20119">Tempo di attesa tra i cicli di distribuzione</t>
    <t id="20130">Consente consegne piÃ¹ piccole basate sull'urgenza al di sotto del normale riempimento minimo della stiva.</t>
    <t id="20131">Percentuale minima di riempimento stiva quando la modalitÃ  a basso volume Ã¨ attiva.</t>
    <t id="20200">Distribuzione di %1 %2 da %3 a %4</t>
    <t id="20201">Viaggio di andata e ritorno: ritiro %1 %2 da %3 a %4</t>
    <t id="20202">Nessuna distribuzione necessaria - tutte le destinazioni sono adeguatamente rifornite</t>
    <t id="20203">Tutte le stazioni sorgente non valide - distribuzione in attesa</t>
    <t id="20204">Tutte le stazioni di destinazione non valide - distribuzione in attesa</t>
    <t id="20205">Stazione sorgente %1 distrutta - rimossa dall'ordine di distribuzione</t>
    <t id="20206">Stazione di destinazione %1 distrutta - rimossa dall'ordine di distribuzione</t>
    <t id="20500">GalaxyTrader MK2 - Impostazioni globali</t>
    <t id="20501">Impostazioni predefinite della distribuzione MK2</t>
    <t id="20510">% di archiviazione minima predefinita</t>
    <t id="20511">% di archiviazione statica predefinita</t>
    <t id="20512">% di archiviazione massima predefinita</t>
    <t id="20513">Attese del ciclo predefinite</t>
    <t id="20514">% di riempimento minimo del carico</t>
    <t id="20520">VerbositÃ  notifiche</t>
    <t id="20521">Livello di debug</t>
    <t id="10006">Ritorno a casa</t>
    <t id="10007">GalaxyTrader Fornitura MK4-2</t>
    <t id="10106">Attracca alla stazione di partenza e rimani lÃ¬ finchÃ© non riprende il commercio</t>
    <t id="10107">Ordine di rifornimento giocatore con cursori di prioritÃ  obiettivo consegna</t>
    <t id="30026">Ritorno a casa tra un ciclo e l'altro</t>
    <t id="30028">Ignora impostazioni offerte</t>
    <t id="30029">Intervallo prezzo acquirente</t>
    <t id="30027">% min. stoccaggio prodotti</t>
    <t id="30126">Quando abilitato, torna alla stazione di partenza e attracca tra i cicli commerciali. Quando disabilitato, continua la ricerca dalla posizione corrente (comportamento legacy)</t>
    <t id="30128">Consenti trasferimenti di stoccaggio interni senza offerte di acquisto/vendita della stazione. Usa lo scambio merci per ritiro e consegna del buffer. Le regole commerciali della stazione restano attive se Ignora regole commerciali Ã¨ disattivato.</t>
    <t id="30129">Prezzo relativo minimo per gli acquirenti NPC durante la vendita dei prodotti della stazione. Cursore ordine 0-200 (100 = media, 0 = -100%, 200 = +100%), mappato su -1,0..+1,0. PiÃ¹ alto = solo acquirenti costosi. PiÃ¹ basso = piÃ¹ opzioni di acquirenti. Le corse di approvvigionamento usano il valore invertito per i limiti di prezzo dei fornitori.</t>
    <t id="30127">Percentuale minima di riempimento dello stoccaggio della stazione (rispetto al massimo configurato per merce) richiesta prima di vendere un prodotto o una merce. Le merci sotto questa soglia vengono ignorate. 0 = nessun minimo.</t>
    <t id="3107">Multitrade in coda: %1. Dovrei guadagnare %2 di profitto.</t>
    <t id="3108">Vendo %1 %2 da %3 al prezzo di %4. Dovrei guadagnare %5 di profitto.</t>
    <t id="3110">Accodamento rifornimento per %1 %2. Approvvigionamento a %3 da %4, consegna a %5. Tetto di acquisto cliente %6 - %7/unitÃ  sotto il tetto (%8 totale).</t>
    <t id="3111">Accodamento rifornimento per %1 %2 da %3 a %4.</t>
    <t id="3112">Rifornimento in coda (%1 tratte): %2. Totale %3 sotto il tetto di acquisto cliente.</t>
    <t id="3113">Commerciante di stazione: export multitrade in coda: %1. Profitto atteso %2.</t>
    <t id="31029">Obiettivo azionario della sonda</t>
    <t id="31030">Droni da estrazione da acquistare</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: nessuna materia estraibile disponibile. Nave %1 [%2], Flotta: %3</t>
    <t id="31201">Galaxy-Miner: impostare la stazione di base o la posizione di base.</t>
    <t id="31130">Quanti droni raccoglitori (da estrazione) acquista il minatore quando ha esaurito il tipo necessario (solido/minerale o liquido/gas). L'acquisto viene attivato SOLO quando la nave non ha raccoglitori di quel tipo: un minatore che ne possiede ancora almeno uno non viene mai rifornito nÃ© riacquistato e i droni esistenti vengono conservati. Limitato dalla capacitÃ  del vano unitÃ  della nave. Imposta a 0 per disattivare l'acquisto automatico dei droni raccoglitori e gestirli manualmente. Il valore predefinito 5 Ã¨ un set completo di droni per una normale velocitÃ  di estrazione.</t>
    <t id="31129">Numero di sonde di risorse acquistate dal minatore per viaggio di rifornimento. L'acquisto viene attivato SOLO quando la nave ha esaurito le sonde (conteggio = 0), non a ogni distribuzione: in questo modo il minatore attraversa l'intero carico di sonda tra i cicli di rifornimento invece di deviare dopo ogni distribuzione. Limitato alla capacitÃ  totale dispiegabile della nave (condivisa con satelliti/mine/ecc.); un valore del dispositivo di scorrimento maggiore dello spazio distribuibile libero si degrada con garbo per "riempire ciÃ² che si adatta". Ha effetto solo quando Ã¨ abilitata la distribuzione automatica delle sonde delle risorse: la stessa impostazione guida anche la distribuzione opportunistica delle sonde nei settori minerari e la raccolta di sonde obsolete (sonde in settori senza risorse rilevanti per il paniere).</t>
    <t id="3226">Comandante %1,\n\nHo attraccato a %2 e il registrar della Trading Academy ha confermato la mia iscrizione al programma "%3". Sul conto della flotta sono stati addebitati %4 Cr per le lezioni del corso e non prendo alla leggera questo investimento.\n\nQuesta non Ã¨ una certificazione di routine. Gli istruttori dell'accademia sono commercianti veterani e negoziatori di consorzi, e il curriculum qui Ã¨ molto piÃ¹ impegnativo dell'esame di avanzamento standard. Nei prossimi %5 minuti seguirÃ² istruzioni intensive sui protocolli di trading avanzati, sull'analisi del mercato sotto pressione e sulle tattiche di negoziazione che separano gli apprendisti dai maestri.\n\nUna volta completato l'esame finale e mi slanciarÃ², manterrÃ² il titolo di "%3" e riporterÃ² tutto ciÃ² che ho imparato nelle nostre operazioni di trading. Non sprecherÃ² un solo credito di questa opportunitÃ .\n\nCon gratitudine e determinazione,\n%6\nA bordo di %7</t>
    <t id="9924">Corso della Trading Academy interrotto: il pilota %1 non puÃ² permettersi la tariffa di %2 Cr al molo dell'accademia (ha %3 Cr). Corso annullato, il pilota riprende il commercio.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="42">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Ukotvit a poÄkat (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">ZÃ¡vÄ›reÄnÃ¡ zkouÅ¡ka (GalaxyTrader MK3)</t>
    <t id="10004">PilotnÃ­ vÃ½mÄ›na Rendezvous</t>
    <t id="10005">[ZASTARALÃ‰] GalaxyTrader Zdroj MK4 (ZastaralÃ©)</t>
    <t id="10101">Zaparkujte na stanici a poÄkejte stanovenou dobu</t>
    <t id="10102">AutonomnÃ­ obchodovÃ¡nÃ­ s progresÃ­ dovednostÃ­</t>
    <t id="10103">Absolvujte zÃ¡vÄ›reÄnou zkouÅ¡ku pro certifikaci pilota ve vÃ½cvikovÃ©m zaÅ™Ã­zenÃ­</t>
    <t id="10104">Dok na schÅ¯zku pro vÃ½mÄ›nu pilotÅ¯</t>
    <t id="10105">ObchodovÃ¡nÃ­ zamÄ›Å™enÃ© na nabÃ­dku pro hrÃ¡ÄskÃ© stanice pomocÃ­ cache a Å¾ivÃ©ho vyhledÃ¡vÃ¡nÃ­ (ZastaralÃ©)</t>
    <t id="10201">Koupit %s od %s</t>
    <t id="10202">Prodejte %s spoleÄnosti %s</t>
    <t id="10203">Obchodujte s %s</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">PokroÄilÃ½ obchodnÃ­ systÃ©m s progresÃ­ XP a koordinacÃ­ flotily</t>
    <t id="1002">DomÃ¡cÃ­ zÃ¡kladna</t>
    <t id="1003">PouÅ¾ijte pÅ™edvolby</t>
    <t id="1004">Obchodujte se vÅ¡Ã­m zboÅ¾Ã­m</t>
    <t id="1005">Obchodujte legÃ¡lnÃ­ zboÅ¾Ã­</t>
    <t id="1006">Obchodujte s nelegÃ¡lnÃ­m zboÅ¾Ã­m</t>
    <t id="1007">Povolit postup XP</t>
    <t id="1008">Povolit koordinaci vozovÃ©ho parku</t>
    <t id="1009">Povolit analÃ½zu trhu</t>
    <t id="1010">Povolit sprÃ¡vu ÃºzemÃ­</t>
    <t id="1011">Povolit nelegÃ¡lnÃ­ zboÅ¾Ã­</t>
    <t id="1012">ZÃ¡znamy v denÃ­ku</t>
    <t id="1013">Tolerance rizika</t>
    <t id="1014">UpÅ™ednostnÄ›te hrÃ¡ÄskÃ© stanice</t>
    <t id="1015">AutomatickÃ© zboÅ¾Ã­</t>
    <t id="1016">Pokuta za vzdÃ¡lenost %</t>
    <t id="1017">ÃšroveÅˆ oznÃ¡menÃ­</t>
    <t id="1018">Koordinace flotily</t>
    <t id="1019">CÃ­l naplnÄ›nÃ­ nÃ¡kladu v %</t>
    <t id="1050">Frekvence aktualizace trhu</t>
    <t id="1051">ProtokolovÃ¡nÃ­ hodnocenÃ­ obchodu</t>
    <t id="1052">Seznam povolenÃ½ch sektorÅ¯</t>
    <t id="1054">Ignorujte pÅ™epravnÃ­/pomocnÃ© lodÄ›</t>
    <t id="1056">Ignorovat sestavenÃ­ ÃºloÅ¾iÅ¡tÄ›</t>
    <t id="1058">Ignorujte obchodnÃ­ pravidla</t>
    <t id="1060">Ignorujte stanice dodanÃ© MK1</t>
    <t id="1063">Ve vÃ½voji</t>
    <t id="1064">PrioritnÃ­ zboÅ¾Ã­</t>
    <t id="1065">PrioritnÃ­ skÃ³re %</t>
    <t id="1066">ZboÅ¾Ã­ upÅ™ednostÅˆovanÃ© v obchodnÃ­m bodovÃ¡nÃ­. Jejich skÃ³re se vynÃ¡sobÃ­ procentem skÃ³re priority.</t>
    <t id="1067">NÃ¡sobitel skÃ³re pro prioritnÃ­ zboÅ¾Ã­: 100 %=normÃ¡lnÃ­, 150%=+50%%, 200%=2x, 300%=3x. AplikovÃ¡no jako poslednÃ­.</t>
    <t id="1068">â”€â”€ Filtru prioritnÃ­ho zboÅ¾Ã­ â”€â”€</t>
    <t id="1069">ZboÅ¾Ã­ (ruÄnÃ­)</t>
    <t id="1070">NelegÃ¡lnÃ­ filtr trasy</t>
    <t id="1072">Obsluhujte pouze doma</t>
    <t id="1073">Priorita dodavatele hrÃ¡Äe</t>
    <t id="1074">Priorita dodavatele frakce</t>
    <t id="1075">Zahrnout ÃºloÅ¾iÅ¡tÄ› sestavenÃ­</t>
    <t id="1076">Zahrnout zdroje</t>
    <t id="1077">Zahrnout meziprodukty</t>
    <t id="1078">Zahrnout Tradewares</t>
    <t id="1080">MaximÃ¡lnÃ­ poÄet obchodÅ¯ za cyklus</t>
    <t id="1081">Tolerance zpÄ›tnÃ©ho chodu</t>
    <t id="1082">MinimÃ¡lnÃ­ vyuÅ¾itÃ½ nÃ¡klad %</t>
    <t id="1083">% modifikÃ¡tor nÃ¡kupu hrÃ¡Äe</t>
    <t id="1085">PÅ™iÅ™adit k domÃ¡cÃ­ stanici</t>
    <t id="1086">PokrytÃ­ VzdÃ¡lenost</t>
    <t id="1088">MaximÃ¡lnÃ­ vzdÃ¡lenost skoku z domova pro pokrytÃ­ poptÃ¡vky</t>
    <t id="1090">Zahrnout zboÅ¾Ã­ tÅ™Ã­dy tradeware do pÃ¡rovÃ¡nÃ­ poptÃ¡vky a nabÃ­dky</t>
    <t id="1091">ModifikÃ¡tor pouÅ¾itÃ½ na ceny dodavatele vlastnÄ›nÃ© hrÃ¡Äem ve vÃ½poÄtech pouze pro bodovÃ¡nÃ­</t>
    <t id="1092">Ignorovat ceny pro hrÃ¡Äe</t>
    <t id="1093">KdyÅ¾ je povoleno: vÅ¾dy nakupujte od stanic vlastnÄ›nÃ½ch hrÃ¡Äem bez ohledu na jejich nastavenÃ© prodejnÃ­ ceny a prodÃ¡vejte pouze NPC frakcÃ­m. UÅ¾iteÄnÃ© pro likvidaci pÅ™ebyteÄnÃ½ch zÃ¡sob z vlastnÃ­ch stanic.</t>
    <t id="1094">BlokovanÃ© stanice</t>
    <t id="1095">Zde vybranÃ© stanice jsou vylouÄeny z obchodovÃ¡nÃ­ MK3. ObchodnÃ­k na nich nebude nakupovat ani prodÃ¡vat.</t>
    <t id="1096">ParkovÃ¡nÃ­ pÅ™i neÄinnosti</t>
    <t id="1097">Je-li zapnuto, lodÄ›, kterÃ© opakovanÄ› nenajdou prÃ¡ci, zaparkujÃ­ u svÃ© domovskÃ© stanice nebo v domovskÃ©m sektoru. ParkovÃ¡nÃ­ v sektoru upÅ™ednostnÃ­ hrÃ¡ÄskÃ© stanice, potÃ© pÅ™Ã¡telskÃ© stanice. Doba uvolnÄ›nÃ­ doku se nastavuje v globÃ¡lnÃ­m nastavenÃ­ (0 = zÅ¯stane v doku, dokud nenÃ­ nalezena prÃ¡ce).</t>
    <t id="1098">AutoskÃ¡lovÃ¡nÃ­</t>
    <t id="1099">Je-li zapnuto, posuvnÃ­ky vzdÃ¡lenosti skokÅ¯ se po povinnÃ©m vÃ½cviku nebo absolvovÃ¡nÃ­ ObchodnÃ­ akademie nastavÃ­ na maximÃ¡lnÃ­ povolenÃ½ dosah pilota. Pro ruÄnÃ­ nastavenÃ­ vypnÄ›te.</t>
    <t id="11001">Priorita skladiÅ¡tÄ› stavby</t>
    <t id="11002">Priorita stanic</t>
    <t id="11003">Priorita pomocnÃ½ch lodÃ­</t>
    <t id="11004">Priorita letadlovÃ½ch lodÃ­</t>
    <t id="11005">0 = vypnuto. 1-10 = nÃ¡sobiÄ skÃ³re (10 = nejsilnÄ›jÅ¡Ã­ vÃ¡ha). KoneÄnÃ© skÃ³re = skÃ³re zÃ¡sobovÃ¡nÃ­ Ã— nÃ¡sobiÄ.</t>
    <t id="11006">1 = Å¾Ã¡dnÃ© extra skÃ³re (seznam prioritnÃ­ch vÃ½robkÅ¯ beze zmÄ›ny). 2-10 = pÅ™iÄte (nÃ¡sobiÄâˆ’1)Ã— zÃ¡kladnÃ­ skÃ³re zÃ¡sobovÃ¡nÃ­, pokud je vÃ½robek v prioritnÃ­m seznamu. Aplikuje se navÃ­c k typovÃ©mu skÃ³re.</t>
    <t id="11007">Bonus prioritnÃ­ch vÃ½robkÅ¯</t>
    <t id="11008">%1: VÅ¡echny posuvnÃ­ky priority cÃ­lÅ¯ dodÃ¡vky jsou nastaveny na 0 - tento rozkaz nemÃ¡ Å¾Ã¡dnÃ© cÃ­le dodÃ¡vky. Povolte alespoÅˆ jednu tÅ™Ã­du (stavby sklad, stanice, pomocnÃ© lodÄ› nebo nosiÄe), aby se obnovily zÃ¡sobovacÃ­ lety.</t>
    <t id="7001">[ZÃLOHA]</t>
    <t id="7002">[VÃCVIK]</t>
    <t id="7008">[FALLBACK]</t>
    <t id="7009">[IZOLOVANÃ]</t>
    <t id="7003">[OPRAVIT]</t>
    <t id="7004">[ZNOVU DODAT]</t>
    <t id="7005">[ÃšDRÅ½BA]</t>
    <t id="7006">[REROUTE]</t>
    <t id="7007">[ODBAVENÃ]</t>
    <t id="1020">Vyberte domÃ¡cÃ­ sektor nebo stanici, kde obchodnÃ­k pÅ¯sobÃ­</t>
    <t id="1021">MaximÃ¡lnÃ­ vzdÃ¡lenost skokovÃ© brÃ¡ny pÅ™i nÃ¡kupu zboÅ¾Ã­ (omezeno schopnostÃ­ pilota)</t>
    <t id="1022">MaximÃ¡lnÃ­ vzdÃ¡lenost skokovÃ© brÃ¡ny pÅ™i prodeji zboÅ¾Ã­ (omezeno dovednostmi pilota)</t>
    <t id="1023">AutomatickÃ½ vÃ½bÄ›r vhodnÃ©ho zboÅ¾Ã­ na zÃ¡kladÄ› kategorie</t>
    <t id="1024">ManuÃ¡lnÃ­ vÃ½bÄ›r konkrÃ©tnÃ­ho obchodnÃ­ho zboÅ¾Ã­</t>
    <t id="1025">Povolit obchodovÃ¡nÃ­ s paÅ¡ovanÃ½m a nelegÃ¡lnÃ­m zboÅ¾Ã­m</t>
    <t id="1026">Tolerance zabezpeÄenÃ­: 0,0=Pouze bezpeÄnÃ© sektory, 1,0=PÅ™ijmout vÅ¡echna rizika</t>
    <t id="1027">ZlepÅ¡ete pilotnÃ­ dovednosti prostÅ™ednictvÃ­m obchodnÃ­ch zkuÅ¡enostÃ­</t>
    <t id="1028">V pÅ™Ã­padÄ› potÅ™eby automaticky posÃ­lejte piloty na vÃ½cvik</t>
    <t id="1029">Koordinujte vÃ­ce obchodnÃ­ch lodÃ­, abyste se vyhnuli konfliktÅ¯m</t>
    <t id="1030">ZamÄ›Å™enÃ­ zboÅ¾Ã­: 0=vyvÃ¡Å¾enÃ©, 1=pokroÄilÃ©, 2=zÃ¡kladnÃ­ potÅ™eby, 3=nelegÃ¡lnÃ­, 4=hromadnÃ© zboÅ¾Ã­</t>
    <t id="1031">Oblast obchodovÃ¡nÃ­: 0=vyvÃ¡Å¾enÃ¡, 1=domÃ¡cÃ­ zamÄ›Å™enÃ­, 2=volnÃ½ pohyb</t>
    <t id="1032">ÃšroveÅˆ upozornÄ›nÃ­: 0=MinimÃ¡lnÃ­, 1=NormÃ¡lnÃ­, 2=PodrobnÃ© zprÃ¡vy</t>
    <t id="1033">NeÅ¾ upÅ™ednostnÃ­te prodej, zamÄ›Å™te se na procento vyuÅ¾itÃ­ nÃ¡kladu</t>
    <t id="1034">Jak Äasto se aktualizujÃ­ Ãºdaje o trhu a informace o cenÃ¡ch</t>
    <t id="1035">ÃšroveÅˆ vÃ½stupu ladÄ›nÃ­: 0=Å½Ã¡dnÃ¡, 1=ZÃ¡kladnÃ­, 2=PodrobnÃ© protokolovÃ¡nÃ­</t>
    <t id="1036">SdÃ­lejte ziskovÃ© obchodnÃ­ cesty s flotilou (uloÅ¾eno do mezipamÄ›ti pro rychlÃ½ pÅ™Ã­stup)</t>
    <t id="1037">MinimÃ¡lnÃ­ zisk nutnÃ½ pro obchodovÃ¡nÃ­ s mezipamÄ›tÃ­ a sdÃ­lenÃ­ s flotilou</t>
    <t id="1038">MaximÃ¡lnÃ­ povolenÃ½ pokles zisku pÅ™ed tÃ­m, neÅ¾ se obchodnÃ­ cesty uloÅ¾enÃ© v mezipamÄ›ti stanou neplatnÃ½mi</t>
    <t id="1039">Jak dlouho zÅ¯stÃ¡vajÃ­ obchodnÃ­ cesty uloÅ¾enÃ© v mezipamÄ›ti platnÃ© pÅ™ed vyprÅ¡enÃ­m platnosti</t>
    <t id="1040">Povolit podrobnÃ© protokolovÃ¡nÃ­ jednotlivÃ½ch hodnocenÃ­ a zamÃ­tnutÃ­ obchodÅ¯ (mÅ¯Å¾e bÃ½t velmi podrobnÃ©)</t>
    <t id="1041">Povolit zÃ¡znamy v denÃ­ku jednotlivÃ½ch obchodÅ¯ a pohlcujÃ­cÃ­ trÃ©ninkovÃ© zprÃ¡vy (styl TaterTrader)</t>
    <t id="1053">Sektory v tomto seznamu jsou vylouÄeny z blacklistÅ¯ (vÅ¾dy povoleno)</t>
    <t id="1055">VylouÄit pÅ™epravce a pomocnÃ© lodÄ› z obchodovÃ¡nÃ­</t>
    <t id="1057">VyluÄte z obchodovÃ¡nÃ­ skladovacÃ­ lodÄ›</t>
    <t id="1059">Ignorovat obchodnÃ­ pravidla stanice bÄ›hem vyhledÃ¡vÃ¡nÃ­ nabÃ­dky (pokroÄilÃ©; mÅ¯Å¾e vybrat nabÃ­dky normÃ¡lnÄ› blokovanÃ©)</t>
    <t id="1061">PÅ™eskoÄte hrÃ¡ÄskÃ© stanice, kterÃ© majÃ­ pÅ™iÅ™azenÃ©ho obchodnÃ­ka MK1 s reÅ¾imem Supply</t>
    <t id="1062">ZvyÅ¡te obchodnÃ­ skÃ³re na trasÃ¡ch zahrnujÃ­cÃ­ch vaÅ¡e vlastnÃ­ stanice (10% bonus za skÃ³re)</t>
    <t id="1071">KdyÅ¾ je povoleno Povolit nelegÃ¡lnÃ­ zboÅ¾Ã­, obchodujte s nelegÃ¡lnÃ­m zboÅ¾Ã­m, pouze pokud je legÃ¡lnÃ­ ve vÅ¡ech sektorech na cestÄ› skoku (nÃ¡kup, prodej a zprostÅ™edkujÃ­cÃ­ sektory).</t>
    <t id="1087">MaximÃ¡lnÃ­ vzdÃ¡lenost skoku z domova pro hledÃ¡nÃ­ nÃ¡kupu dodavatele</t>
    <t id="1089">Je-li deaktivovÃ¡n, mÅ¯Å¾e loÄ zÃ¡sobovat stanice v oblasti pokrytÃ­ podle priority nalÃ©havosti namÃ­sto reÅ¾imu pouze doma</t>
    <t id="2000">%s zÃ­skal %s XP!</t>
    <t id="2001">%s postoupil o ÃºroveÅˆ vÃ½Å¡! NovÃ¡ ÃºroveÅˆ: %s</t>
    <t id="2002">%s potÅ™ebuje Å¡kolenÃ­! OdeÅ¡lete prosÃ­m do nejbliÅ¾Å¡Ã­ lodÄ›nice nebo obchodnÃ­ stanice.</t>
    <t id="2003">%s zahÃ¡jil trÃ©nink v %s</t>
    <t id="2004">%s dokonÄil Å¡kolenÃ­ a je nynÃ­ certifikovÃ¡n pro ÃºroveÅˆ %s!</t>
    <t id="2005">%s dosÃ¡hl Skill Level %s po Å¡kolenÃ­! XP progrese odemÄena v %s.</t>
    <t id="2006">%s dosÃ¡hl Skill Level %s obchodem s %s!</t>
    <t id="2007">%s dokonÄil Level %s Å¡kolenÃ­! XP progrese odemÄena v %s.</t>
    <t id="3000">%s dokonÄil obchod! Zisk: %s kr</t>
    <t id="3001">%s analyzuje podmÃ­nky na trhu...</t>
    <t id="3002">%s naÅ¡el ziskovou obchodnÃ­ cestu!</t>
    <t id="3003">Pro %s nejsou k dispozici Å¾Ã¡dnÃ© ziskovÃ© obchodnÃ­ cesty</t>
    <t id="3100">Prodej %1 %2 z nÃ¡kladu do %3 za %4. MÄ›l bych vydÄ›lat %5 zisku.</t>
    <t id="3101">ZaÅ™azenÃ­ obchodnÃ­ho pÅ™Ã­kazu do fronty pro %1 %2. NÃ¡kup za %3 z %4, prodej za %5 do %6. MÄ›l bych vydÄ›lat %7 zisku.</t>
    <t id="3102">Station Trader: ZÃ¡sobovÃ¡nÃ­ %1 %2 od %3 pÅ™i %5%% do %4 pÅ™i %6%%.</t>
    <t id="3103">Station Trader: Prodej %1 %2 do %3 za %4. OÄekÃ¡vanÃ½ zisk je %5.</t>
    <t id="3104">Obchod pro %1 %2 byl ÃºspÄ›Å¡nÄ› dokonÄen. CelkovÃ½ zisk: %3 kreditÅ¯.</t>
    <t id="3105">ObchodnÃ­ cesta uloÅ¾enÃ¡ v mezipamÄ›ti: %1 %2 z %3 do %4 (Zisk: %5 Cr)</t>
    <t id="3106">\nCelkovÃ½ odhadovanÃ½ celoÅ¾ivotnÃ­ zisk pÅ™ed tÃ­mto obchodem: %1 kr.</t>
    <t id="3120">PilotnÃ­ pÅ™enos zahÃ¡jen</t>
    <t id="3121">PÅ™enosovÃ½ protokol potvrzen. %1 (%2) a %3 (%4) pÅ™echÃ¡zejÃ­ do %5 (%6), aby ukotvili a vymÄ›nili si velitelskÃ¡ mÃ­sta.</t>
    <t id="3200">DobrÃ½ den, veliteli %1,\n\nzÃ­skal jsem dostatek zkuÅ¡enostÃ­, abych mohl sloÅ¾it certifikaÄnÃ­ zkouÅ¡ku pro titul â€ž%2â€œ. ZkouÅ¡ka bude trvat pÅ™ibliÅ¾nÄ› %3 minut v %4.\n\nToto je dÅ¯leÅ¾itÃ½ milnÃ­k v mÃ©m kariÃ©rnÃ­m rozvoji. ZkouÅ¡ka provÄ›Å™Ã­ mÃ© znalosti pokroÄilÃ½ch obchodnÃ­ch protokolÅ¯, analÃ½zy trhu a postupÅ¯ koordinace vozovÃ©ho parku.\n\nJsem si jistÃ½ svÃ½mi schopnostmi a jsem nadÅ¡enÃ½, Å¾e dokÃ¡Å¾u, Å¾e si tohoto pokroku zaslouÅ¾Ã­m. PÅ™ejte mi Å¡tÄ›stÃ­!\n\nS Ãºctou\n%5\nNa palubÄ› %6</t>
    <t id="3201">Veliteli %1,\n\nSkvÄ›lÃ© zprÃ¡vy! ÃšspÄ›Å¡nÄ› jsem dokonÄil certifikaÄnÃ­ zkouÅ¡ku a zÃ­skal jsem titul "%2"!\n\nZkouÅ¡ka zahrnovala pokroÄilÃ© obchodnÃ­ strategie, protokoly hodnocenÃ­ rizik a postupy koordinace vozovÃ©ho parku. S potÄ›Å¡enÃ­m oznamuji, Å¾e jsem proÅ¡el s vyznamenÃ¡nÃ­m.\n\nNynÃ­ jsem zpÅ¯sobilÃ½ zvlÃ¡dnout sloÅ¾itÄ›jÅ¡Ã­ obchodnÃ­ operace a tÄ›Å¡Ã­m se, Å¾e jeÅ¡tÄ› vÃ­ce pÅ™ispÄ›ji k ÃºspÄ›chu naÅ¡Ã­ flotily. DÄ›kuji, Å¾e investujete do mÃ©ho profesnÃ­ho rozvoje.\n\nS obnovenÃ½m odhodlÃ¡nÃ­m,\n%3\nCertifikovanÃ½ %2\nNa palubÄ› %4</t>
    <t id="3202">Veliteli %1,\n\nS politovÃ¡nÃ­m vÃ¡m musÃ­m oznÃ¡mit, Å¾e moje certifikaÄnÃ­ zkouÅ¡ka byla pÅ™eruÅ¡ena z dÅ¯vodu provoznÃ­ch poÅ¾adavkÅ¯. Budu muset pÅ™eplÃ¡novat, jakmile to okolnosti dovolÃ­.\n\nZÅ¯stÃ¡vÃ¡m odhodlÃ¡n rozvÃ­jet svÃ© dovednosti a upozornÃ­m vÃ¡s, aÅ¾ budu moci pokraÄovat ve zkuÅ¡ebnÃ­m procesu.\n\nS Ãºctou\n%2\nNa palubÄ› %3</t>
    <t id="3203">Commander %1,\n\nI am currently en route to %2 for my certification examination. The journey gives me time to review my studies and prepare mentally for this important step in my career.\n\nExpected arrival: %3 minutes\nExamination duration: %4 minutes\n\nI appreciate your confidence in my abilities and the opportunity for advancement.\n\nWith determination,\n%5\nAboard %6</t>
    <t id="3204">Veliteli,\n\nPÅ™i kontrole systÃ©mÅ¯ jsem ve svÃ©m nÃ¡kladnÃ­m prostoru zjistil nÃ¡klad. NeÅ¾ budu moci zaÄÃ­t s normÃ¡lnÃ­mi obchodnÃ­mi operacemi, musÃ­m toto zboÅ¾Ã­ prodat.\n\nPouÅ¾Ã­vÃ¡m naÅ¡e obchodnÃ­ vyhledÃ¡vÃ¡nÃ­, abych naÅ¡el nejlepÅ¡Ã­ho kupce a bezpeÄnÄ› vyloÅ¾il tento nÃ¡klad. Jakmile bude moje drÅ¾enÃ­ ÄistÃ©, budu pokraÄovat v automatizovanÃ©m obchodovÃ¡nÃ­.\n\nStav: HledÃ¡nÃ­ optimÃ¡lnÃ­ho mÃ­sta prodeje\n\nS peÄlivostÃ­\nNa palubÄ› %1</t>
    <t id="3205">Veliteli,\n\nintegrita mÃ©ho trupu klesla na %1%% (prÃ¡h: %2%%). Jako pilot ÃºrovnÄ› %3 mÃ¡m oprÃ¡vnÄ›nÃ­ poÅ¾adovat sluÅ¾by automatickÃ½ch oprav.\n\nPÅ™echÃ¡zÃ­m na %4 kvÅ¯li opravÃ¡m. OdhadovanÃ¡ cena je %5 Cr, coÅ¾ je v rÃ¡mci naÅ¡eho rozpoÄtu.\n\nJakmile budou opravy dokonÄeny, obnovÃ­m obchodnÃ­ operace s plnou strukturÃ¡lnÃ­ integritou.\n\nS Ãºctou\nNa palubÄ› %6</t>
    <t id="3206">Commander,\n\nURGENT FINANCIAL WARNING\n\nMy hull integrity is critical at %1%% (threshold: %2%%), but our available funds (%3 Cr) are insufficient for full repairs (estimated cost: %4 Cr).\n\nI'm proceeding to %5 for PARTIAL REPAIRS using our available funds. This isn't an ideal solution, but it's necessary to maintain operational capability.\n\nPlease consider allocating additional funds for future maintenance operations.\n\nConcerned but determined,\nAboard %6</t>
    <t id="3207">Veliteli,\n\ncertifikace mÃ© ÃºrovnÄ› %1 opravÅˆuje automatickÃ© doplÅˆovÃ¡nÃ­ obrannÃ©ho vybavenÃ­. Po kontrole svÃ½ch systÃ©mÅ¯ jsem zjistil, Å¾e moje protiopatÅ™enÃ­ a nasaditelnÃ© prvky jsou pod doporuÄenÃ½mi prahovÃ½mi hodnotami.\n\nPÅ™echÃ¡zÃ­m na %2, abych doplnil zÃ¡soby svÃ©ho obrannÃ©ho vybavenÃ­:\nâ€¢ ProtiopatÅ™enÃ­: DoplnÄ›nÃ­ na optimÃ¡lnÃ­ kapacitu\nâ€¢ ObrannÃ© drony, obchodnÃ­ drony, laserovÃ© vÄ›Å¾e: PouÅ¾itÃ­ profilu vyvÃ¡Å¾enÃ­ pÅ™i zachovÃ¡nÃ­ chrÃ¡nÄ›nÃ©ho prostoru pÅ™ed hrozbou\n\nToto nejlepÅ¡Ã­ zÃ¡sobovÃ¡nÃ­ efektivitu.\n\nS ostraÅ¾itostÃ­\nNa palubÄ› %3</t>
    <t id="3212">Veliteli,\n\nintegrita mÃ©ho trupu klesla na %1%% (prÃ¡h: %2%%) a potÅ™ebuji opravu. NejbliÅ¾Å¡Ã­ opravÃ¡renskÃ¡ stanice na adrese %3 je vÅ¡ak v souÄasnÃ© dobÄ› nedostupnÃ¡ z dÅ¯vodu omezenÃ­ cestovÃ¡nÃ­ po sektoru (trasy na ÄernÃ© listinÄ›).\n\nI pÅ™es toto omezenÃ­ budu pokraÄovat v obchodnÃ­ch operacÃ­ch. Jakmile budou opÄ›t dostupnÃ© bezpeÄnÃ© trasy, automaticky vyhledÃ¡m opravÃ¡renskÃ© sluÅ¾by.\n\nBudu sledovat situaci a upozornÃ­m vÃ¡s, aÅ¾ budou moÅ¾nÃ© opravy.\n\nS Ãºctou\nNa palubÄ› %4</t>
    <t id="3213">Veliteli,\n\nMoje obrannÃ© vybavenÃ­ vyÅ¾aduje doplnÄ›nÃ­, ale nejbliÅ¾Å¡Ã­ stanice s vybavenÃ­m na %1 je momentÃ¡lnÄ› nedosaÅ¾itelnÃ¡ z dÅ¯vodu omezenÃ­ cestovÃ¡nÃ­ po sektoru (trasy na ÄernÃ© listinÄ›).\n\nI pÅ™es toto omezenÃ­ budu pokraÄovat v obchodnÃ­ch operacÃ­ch. Jakmile budou opÄ›t dostupnÃ© bezpeÄnÃ© trasy, automaticky vyhledÃ¡m zÃ¡sobovacÃ­ sluÅ¾by.\n\nBudu sledovat situaci a upozornÃ­m vÃ¡s, aÅ¾ bude moÅ¾nÃ© obnovenÃ­ zÃ¡sob.\n\nS Ãºctou\nNa palubÄ› %2</t>
    <t id="3208">Commander,\n\nI've completed an exhaustive market analysis of %1 and surrounding sectors (within %2 jumps, minimum profit threshold: %3 Cr), but unfortunately found no profitable trading opportunities that meet our requirements.\n\nTRADE ANALYSIS REPORT:\nTotal opportunities evaluated: %4\n\nREJECTION BREAKDOWN:\n- Docking restrictions: %5 trades\n  (Station doesn't permit my ship class)\n- Insufficient profitability: %6 trades\n  (Below minimum profit threshold)\n- Insufficient volume: %7 trades\n  (Zero or negative tradeable amount)\n- Safety restrictions: %8 trades\n  (Blacklisted stations or dangerous sectors)\n\nRECOMMENDATIONS:\n- Consider adjusting profit thresholds\n- Expand maximum trading distance\n- Review sector blacklist settings\n- Wait for market conditions to improve\n\nI'll continue monitoring the market and will notify you when profitable opportunities become available.\n\nStanding by,\nAboard your service</t>
    <t id="3209">Veliteli, \n\nURGENT ROUTE ALERT\n\nMÅ¯j systÃ©m zpravodajstvÃ­ o hrozbÃ¡ch zjistil, Å¾e sektor %1 (ÃºroveÅˆ ohroÅ¾enÃ­ %2) je nynÃ­ na mÃ© plÃ¡novanÃ© obchodnÃ­ trase. Pro bezpeÄnost lodi a posÃ¡dky okamÅ¾itÄ› pÅ™eruÅ¡uji souÄasnou obchodnÃ­ operaci.\n\nPROVEDENÃ‰ AKCE:\n- VÅ¡echny obchodnÃ­ pÅ™Ã­kazy zruÅ¡eny\n- NÃ¡vrat do reÅ¾imu bezpeÄnÃ©ho provozu\n- Najde alternativnÃ­ obchodnÃ­ cestu, kterÃ¡ se vyhÃ½bÃ¡ nebezpeÄnÃ½m sektorÅ¯m, pokud prodÃ¡ jakÃ©koli auto na bezpeÄnÃ©m mÃ­stÄ›:\n- potÅ™eba)\n\nDynamickÃ½ systÃ©m ÄernÃ© listiny zabrÃ¡nÃ­ budoucÃ­m obchodÅ¯m pÅ™es tento sektor, dokud nebude hrozba odstranÄ›na.\n\nBezpeÄnost je mou prvnÃ­ prioritou.\n\nS ostraÅ¾itostÃ­ \nNa palubÄ› %3</t>
    <t id="3210">Commander,\n\nESCAPE ROUTE INITIATED\n\nI'm currently in blacklisted sector %1 and have found a trade route that will allow me to escape safely.\n\nTRADE ROUTE:\nBuy: %2 (Sector: %3)\nSell: %4 (Sector: %5)\nWare: %6 (x%7)\nExpected Profit: %8 Cr\n\nThe ship will escape the blacklisted sector after completing this trade.\n\nRespectfully,\nAboard your service</t>
    <t id="3211">Commander,\n\nISOLATED TRADING MODE\n\nI'm currently in sector %2, but all routes to other sectors are blocked by blacklisted hub sectors. This means I can only trade within my current sector until the blacklist situation changes.\n\nSITUATION:\nCurrent Sector: %2\nStatus: Isolated (non-blacklisted sector with blocked routes)\nTrading Mode: Intra-sector trades only\n\nMy trading system has automatically adjusted profit thresholds to prioritize available intra-sector trading opportunities.\n\nI will continue monitoring the situation and notify you if routes become available again.\n\nRespectfully,\nAboard %1</t>
    <t id="3218">Commander,\n\nROUTE PATH CHANGE DETECTED\n\nUpon entering sector %1, my navigation system detected that the route to my destination %2 (%3) has changed.\n\nPATH ANALYSIS:\n- Normal distance: %4 jumps\n- Blacklist-aware distance: %5\n- Status: %6\n\nMy navigation computer indicates that the preferred route is no longer viable due to sector travel restrictions. For the safety of the ship and crew, I am immediately aborting the current trade operation.\n\nACTIONS TAKEN:\n- All trade orders cancelled\n- Returning to safe operations mode\n- Will find alternative trade route that avoids blocked sectors\n- Cargo handling: Automatic (will sell any cargo at safe location if needed)\n\nMy navigation system will automatically avoid blocked sectors in future route planning.\n\nSafety is my first priority.\n\nWith vigilance,\nAboard %7</t>
    <t id="3219">Sektor %1 vyÄiÅ¡tÄ›n - vÅ¡echny hrozby odstranÄ›ny</t>
    <t id="3220">Commander,\n\nENEMY SHIP ESCAPED\n\nOur threat intelligence system has lost track of enemy ship %3, which has escaped from blacklisted sector %1.\n\nDETAILS:\n- Escaped Ship: %3\n- Sector Left: %1\n- Destination Sector: %2\n- Status: Tracking lost - ship has left our monitored area\n\nWhile this ship is no longer a threat in sector %1, we have lost visual contact and cannot confirm its current status or intentions in sector %2.\n\nOur tracking systems will continue monitoring sector %1 for remaining threats. If all tracked enemies leave or are eliminated, the sector will be automatically cleared from the blacklist.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3221">Commander,\n\nI was unable to find profitable trading opportunities at greater distances (up to %3 jumps) because these routes are currently unreachable due to sector travel restrictions (blacklisted paths).\n\nSITUATION:\nCurrent Sector: %2\nOriginal Search Range: %3 jumps\nFallback Search Range: %4 jumps\n\nI will now focus my search on nearby sectors within %4 jumps, where routes are more likely to be accessible. This should help me find profitable trades that were previously filtered out due to distance restrictions rather than actual unprofitability.\n\nI'll notify you when I find suitable trading opportunities in the nearby area.\n\nRespectfully,\nAboard %1</t>
    <t id="3222">Veliteli, \n\nSECTOR BLACKLISTED\n\nNÃ¡Å¡ systÃ©m pro zpravodajstvÃ­ o hrozbÃ¡ch detekoval nepÅ™Ã¡telskou aktivitu v sektoru %1 a automaticky zaÅ™adil tento sektor na Äernou listinu, aby chrÃ¡nil naÅ¡e obchodnÃ­ operace.\n\nDETEKOVANÃ NEPÅ˜ÃTEL LODÄš:\n%2\n\nZJIÅ TÄšNO: %3\n\nPro bezpeÄnost naÅ¡ich lodÃ­ a posÃ¡dky byly vÅ¡echny obchodnÃ­ cesty pÅ™es tento sektor zablokovÃ¡ny. NaÅ¡e lodÄ› budou automaticky obÃ­hat tento sektor, dokud nebude hrozba odstranÄ›na.\n\nSektor bude automaticky vymazÃ¡n z ÄernÃ© listiny, jakmile budou vÅ¡echny sledovanÃ© nepÅ™Ã¡telskÃ© lodÄ› eliminovÃ¡ny nebo opustÃ­ oblast.\n\nS ostraÅ¾itostÃ­\nThreat Intelligence System</t>
    <t id="3223">Veliteli,\n\nnemohu najÃ­t pÅ™Ã­stupnou Å¡kolicÃ­ stanici pro svou pokroÄilou zkouÅ¡ku ÃºrovnÄ› %1. Budu pokraÄovat v obchodnÃ­ch operacÃ­ch podle pokynÅ¯, ale chÃ¡pu, Å¾e nezÃ­skÃ¡m zkuÅ¡enostnÃ­ body, dokud nedokonÄÃ­m poÅ¾adovanÃ© Å¡kolenÃ­. Po tomto obchodnÃ­m bÄ›hu budu znovu hledat jakoukoli moÅ¾nou pÅ™Ã­leÅ¾itost k trÃ©ninku.\n\nS Ãºctou\nNa palubÄ› %2</t>
    <t id="3224">LicenÄnÃ­ poplatek za Å¡kolenÃ­: %1 Cr</t>
    <t id="3225">Bonus: ZÃ­skal jsem %1 dalÅ¡Ã­ ÃºroveÅˆ dovednostÃ­%2 z nashromÃ¡Å¾dÄ›nÃ½ch zkuÅ¡enostÃ­ bÄ›hem trÃ©ninku! AktuÃ¡lnÃ­ ÃºroveÅˆ: %3</t>
    <t id="3214">Je mi ctÃ­ pro vÃ¡s pracovat, %1! Jsem nadÅ¡enÃ½, Å¾e mohu zaÄÃ­t svou obchodnÃ­ kariÃ©ru pod vaÅ¡Ã­m velenÃ­m. UdÄ›lÃ¡m vÅ¡e pro to, abych vÃ¡m dobÅ™e slouÅ¾il a pÅ™ispÄ›l k vaÅ¡emu ÃºspÄ›chu.</t>
    <t id="3215">DÄ›kuji, Å¾e jste mi dopÅ™Ã¡li tuto zaslouÅ¾enou dovolenou, %1! UÅ¾il jsem si Äas mimo obchodovÃ¡nÃ­ a mÃ© dovednosti zÅ¯stÃ¡vajÃ­ nedotÄeny. TÄ›Å¡Ã­m se na nÃ¡vrat do prÃ¡ce, kdykoli mÄ› budete potÅ™ebovat. Do tÃ© doby budu mÃ­t svÃ© obchodnÃ­ znalosti ostrÃ©!</t>
    <t id="3216">Jsem zpÄ›t z dovolenÃ© a jsem pÅ™ipraven znovu pracovat, %1! Moje obchodnÃ­ dovednosti jsou stÃ¡le ostrÃ© a tÄ›Å¡Ã­m se, Å¾e vÃ¡m budu nadÃ¡le slouÅ¾it na %2. DÄ›kujeme za zaslouÅ¾enÃ½ odpoÄinek!</t>
    <t id="3217">DÄ›kuji za mÅ¯j pÅ™evod do %1, %2! Jsem poctÄ›n tÃ­mto novÃ½m Ãºkolem a o svou novou loÄ se skvÄ›le postarÃ¡m. Moje obchodnÃ­ zkuÅ¡enosti a dovednosti zÅ¯stÃ¡vajÃ­ nedotÄeny a jsem pÅ™ipraven vÃ¡m nadÃ¡le slouÅ¾it.</t>
    <t id="3227">Trup ztracen, dÅ¯stojnost ÄekÃ¡ na vyzvednutÃ­</t>
    <t id="3228">Veliteli %1,\n\n%2 hlÃ¡sÃ­ ze sektoru %3. Moje loÄ explodovala. JÃ¡ ne. NynÃ­ jsem nejdraÅ¾Å¡Ã­ plovoucÃ­ nÃ¡klad flotily.\n\nMapovÃ¡ znaÄka pÅ™ipojena. ProsÃ­m pospÄ›Å¡te si - byl jsem uprostÅ™ed faktury.\n\nProfesionÃ¡lnÄ› ve volnÃ©m prostoru,\n%2</t>
    <t id="3229">Pilot zachrÃ¡nÄ›n - ZÃ¡vislost na kyslÃ­ku vylÃ©Äena</t>
    <t id="3230">Veliteli %1,\n\nFlotilnÃ­ zprÃ¡va: %2 byl vyzvednut lodÃ­ %3 (%4) a pÅ™estal vÃ¡m ÃºÄtovat prodlouÅ¾enÃ½ vÃ½cvik EVA.\n\nProbÃ­hÃ¡ opÄ›tovnÃ© propojenÃ­ registru. DoporuÄenÃ­: neptat se na starou loÄ.\n\nUstupnÄ› vÃ¡Å¡,\n%2</t>
<t id="4000">Koordinace flotily: %s byla pÅ™idÄ›lena trasa %s</t>
    <t id="4001">Koordinace flotily: Trasa %s je plnÄ› vyuÅ¾Ã­vÃ¡na</t>
    <t id="4002">Koordinace flotily: %s uvolnila trasu %s</t>
    <t id="5000">%s bylo pÅ™iÅ™azeno jako primÃ¡rnÃ­ ÃºzemÃ­ pro %s</t>
    <t id="5001">%s dosÃ¡hl ÃºrovnÄ› odbornosti %s v %s!</t>
    <t id="5002">UplatnÄ›n bonus ÃºzemÃ­: %s%% nÃ¡rÅ¯st zisku za %s</t>
    <t id="9500">Chyba: %s se zaseklo a potÅ™ebuje pomoc!</t>
    <t id="9501">Chyba: Obchod s %s se nezdaÅ™il</t>
    <t id="9502">Chyba: Nelze zaregistrovat %s s GalaxyTrader MK3</t>
    <t id="80001">Ware %s pÅ™idÃ¡no na Äernou listinu</t>
    <t id="80002">Ware %s byl odstranÄ›n z ÄernÃ© listiny</t>
    <t id="80003">Ware %s pÅ™idÃ¡no na bÃ­lou listinu</t>
    <t id="80004">Automaticky na ÄernÃ© listinÄ› (nÃ­zkÃ½ vÃ½kon): %s</t>
    <t id="80005">UpÅ™ednostnÄ›no nebezpeÄnÃ© zboÅ¾Ã­: %s</t>
    <t id="80006">Ware filter: %s aktivnÃ­, %s obchodovÃ¡nÃ­ blokovÃ¡no</t>
    <t id="80007">VÅ¡echny filtry zboÅ¾Ã­ vymazÃ¡ny</t>
    <t id="80008">Filtry zboÅ¾Ã­ byly resetovÃ¡ny na vÃ½chozÃ­</t>
    <t id="80009">SprÃ¡va filtru zboÅ¾Ã­</t>
    <t id="80010">BlokovanÃ© zboÅ¾Ã­</t>
    <t id="80011">PovolenÃ© zboÅ¾Ã­</t>
    <t id="80012">Manipulace s nebezpeÄnÃ½m zboÅ¾Ã­m</t>
    <t id="80013">MinimÃ¡lnÃ­ hodnota zboÅ¾Ã­</t>
    <t id="80014">MaximÃ¡lnÃ­ hodnota zboÅ¾Ã­</t>
    <t id="80015">OmezenÃ© frakce</t>
    <t id="80016">Kategorie zboÅ¾Ã­ aktualizovÃ¡ny z aktuÃ¡lnÃ­ho stavu hry</t>
    <t id="80017">%s zboÅ¾Ã­ kategorizovanÃ©: %s s nÃ­zkou hodnotou, %s nebezpeÄnÃ©, %s s vysokou hodnotou</t>
    <t id="80018">DynamickÃ¡ kategorizace zboÅ¾Ã­ povolena</t>
    <t id="80019">AutomatickÃ© pÅ™idÃ¡vÃ¡nÃ­ na Äernou listinu pro kategorii %s zakÃ¡zÃ¡no</t>
    <t id="80020">ZjiÅ¡tÄ›no a kategorizovÃ¡no novÃ© zboÅ¾Ã­ z jinÃ½ch modÅ¯</t>
    <t id="9000">GalaxyTrader - GlobÃ¡lnÃ­ nastavenÃ­</t>
    <t id="9010">XP a trÃ©ninkovÃ½ systÃ©m</t>
    <t id="9012">AutomatickÃ© Å¡kolenÃ­</t>
    <t id="9013">XP multiplikÃ¡tor</t>
    <t id="9015">Procento bonusu velitele</t>
    <t id="9020">Koordinace flotily</t>
    <t id="9021">Povolit koordinaci flotily</t>
    <t id="9023">Povolit mezipamÄ›Å¥ obchodu</t>
    <t id="9030">OznÃ¡menÃ­</t>
    <t id="9031">ÃšroveÅˆ oznÃ¡menÃ­</t>
    <t id="9040">SystÃ©m automatickÃ½ch oprav</t>
    <t id="9041">Povolit automatickÃ© opravy</t>
    <t id="9042">PrÃ¡h opravy trupu</t>
    <t id="9310">Galaxy-Miner</t>
    <t id="9311">ÄŒekÃ¡nÃ­ na sken sond zdrojÅ¯ v sektoru</t>
    <t id="9312">VÃ¡ha blÃ­zkosti lodi</t>
    <t id="9043">MinimÃ¡lnÃ­ ÃºroveÅˆ pilota</t>
    <t id="9004">CenovÃ© rozpÄ›tÃ­ obchodovÃ¡nÃ­</t>
    <t id="9005">Prodej NabÃ­dkovÃ¡ cena Max</t>
    <t id="9006">Koupit NabÃ­dkovÃ¡ cena Min</t>
    <t id="9007">IzolovanÃ½: ProdejnÃ­ cena Max</t>
    <t id="9008">IzolovanÃ©: KupnÃ­ cena Min</t>
    <t id="9009">ZÃ¡loÅ¾nÃ­: ProdejnÃ­ cena Max</t>
    <t id="9014">ZÃ¡loÅ¾nÃ­: KupnÃ­ cena min</t>
    <t id="9016">Profit Threshold Base</t>
    <t id="9025">MinimÃ¡lnÃ­ hrÃ¡ÄskÃ© penÃ­ze</t>
    <t id="9024">Tolerance poklesu mezipamÄ›ti</t>
    <t id="9026">Doba neÄinnÃ©ho parkovÃ¡nÃ­ pÅ™ed uvolnÄ›nÃ­m</t>
    <t id="9054">Blokovat sektory nepÅ™Ã¡telskÃ© frakce</t>
    <t id="9055">ÃšroveÅˆ hrozeb na ÄernÃ© listinÄ›</t>
    <t id="9056">Znovu vytvoÅ™it Äernou listinu</t>
    <t id="9057">Znovu vytvoÅ™it</t>
    <t id="9058">PÅ™iÅ™adit k GT lodÃ­m</t>
    <t id="9059">PÅ™iÅ™adit</t>
    <t id="9112">Automaticky posÃ­lÃ¡ piloty na vÃ½cvik, kdyÅ¾ dosÃ¡hnou poÅ¾adovanÃ© ÃºrovnÄ›. ZakÃ¡zat, chcete-li ruÄnÄ› ovlÃ¡dat naÄasovÃ¡nÃ­ trÃ©ninku.</t>
    <t id="9113">Upravuje, jak rychle piloti zÃ­skÃ¡vajÃ­ zkuÅ¡enosti. VyÅ¡Å¡Ã­ hodnoty znamenajÃ­ rychlejÅ¡Ã­ progresi.</t>
    <t id="9115">Procento podÅ™Ã­zenÃ½ch XP udÄ›lenÃ½ch velitelskÃ½m pilotÅ¯m. NastavenÃ­m na 0 % deaktivujete velitelskÃ½ bonus XP. VÃ½chozÃ­: 10 %.</t>
    <t id="9121">UmoÅ¾Åˆuje inteligentnÃ­ funkce koordinace vozovÃ©ho parku vÄetnÄ› optimalizace trasy a vyvaÅ¾ovÃ¡nÃ­ zÃ¡tÄ›Å¾e.</t>
    <t id="9123">UmoÅ¾Åˆuje sdÃ­lenÃ­ ziskovÃ½ch obchodnÃ­ch pÅ™Ã­leÅ¾itostÃ­ mezi Äleny flotily pro lepÅ¡Ã­ koordinaci.</t>
    <t id="9131">Å˜Ã­dÃ­, kolik oznÃ¡menÃ­ se zobrazÃ­: 0=TichÃ½, 1=Pouze dÅ¯leÅ¾itÃ¡, 2=VÅ¡echna oznÃ¡menÃ­</t>
    <t id="9141">Automaticky posÃ­lÃ¡ lodÄ› na opravu po dokonÄenÃ­ obchodÅ¯, kdyÅ¾ trup klesne pod prahovou hodnotu. Pouze pro zkuÅ¡enÃ© piloty (ÃºroveÅˆ 12+). LodÄ› si vybÃ­rajÃ­ vhodnÃ© zaÅ™Ã­zenÃ­: S/M dok vybavenÃ­, L/XL lodÄ›nice.</t>
    <t id="9142">Procento trupu, pod kterÃ½m se spustÃ­ automatickÃ¡ oprava. VÃ½chozÃ­: 95 %. PÅ™i poÅ¡kozenÃ­ se lodÄ› automaticky pÅ™esunou do nejbliÅ¾Å¡Ã­ho opravÃ¡renskÃ©ho zaÅ™Ã­zenÃ­.</t>
    <t id="9411">Pokud je povoleno, tÄ›Å¾aÅ™i ÄekajÃ­ pÅ™i vyhodnocovÃ¡nÃ­ sond zdrojÅ¯ frakce v sektoru (+5 s za kaÅ¾dou sondu nad jednu). ÃšroveÅˆ GT pilota tuto dobu lineÃ¡rnÄ› zkracuje od plnÃ© doby na Ãºrovni 1 do 5 sekund na Ãºrovni 15 (pouze reÅ¾im GT XP, pokud doba pÅ™esahuje 5 s). Vypnuto = bez ÄekÃ¡nÃ­ (chovÃ¡nÃ­ vanilla).</t>
    <t id="9412">PÅ™i Å™azenÃ­ validovanÃ½ch obchodÅ¯ tlaÄÃ­ lodÄ› MK3/MK4 k bliÅ¾Å¡Ã­m nÃ¡kupnÃ­m stanicÃ­m. VÃ½bÄ›rovÃ© skÃ³re = skÃ³re obchodu / (1 + skoky loÄâ†’nÃ¡kup Ã— vÃ¡ha). PosuvnÃ­k 0-100 (0 = vypnuto; 4 = vÃ½chozÃ­ 0,04). NeovlivÅˆuje poÅ™adÃ­ cache ani ÃºzemnÃ­ dosahovÃ© limity.</t>
    <t id="9143">MinimÃ¡lnÃ­ pilotnÃ­ ÃºroveÅˆ poÅ¾adovanÃ¡ pro funkci automatickÃ© opravy. VÃ½chozÃ­: 12 (zkuÅ¡enÃ­ obchodnÃ­ci). Piloti niÅ¾Å¡Ã­ ÃºrovnÄ› musÃ­ opravit ruÄnÄ›.</t>
    <t id="9104">MaximÃ¡lnÃ­ relativnÃ­ cena za nabÃ­dky prodeje (loÄ nakupuje ZE stanic). Rozsah: -1,0 aÅ¾ +1,0. VÃ½chozÃ­: 0,5 (50 % nad prÅ¯mÄ›rem). VyÅ¡Å¡Ã­ = draÅ¾Å¡Ã­, ale vÃ­ce moÅ¾nostÃ­.</t>
    <t id="9105">MinimÃ¡lnÃ­ relativnÃ­ cena za nabÃ­dky nÃ¡kupu (loÄ prodÃ¡vÃ¡ stanice TO). Rozsah: -1,0 aÅ¾ +1,0. VÃ½chozÃ­: -0,5 (50 % pod prÅ¯mÄ›rem). NiÅ¾Å¡Ã­ = levnÄ›jÅ¡Ã­ kupujÃ­cÃ­, ale vÃ­ce moÅ¾nostÃ­.</t>
    <t id="9106">ProdejnÃ­ cena max. za izolovanÃ© lodÄ› (zaseknutÃ© v jednom sektoru). Rozsah: -1,0 aÅ¾ +1,0. VÃ½chozÃ­: 0,5.</t>
    <t id="9107">KupnÃ­ cena min za izolovanÃ© lodÄ› (uvÃ­zlÃ© v jednom sektoru). Rozsah: -1,0 aÅ¾ +1,0. VÃ½chozÃ­: -0,5.</t>
    <t id="9108">ProdejnÃ­ cena max. pro zÃ¡loÅ¾nÃ­ vyhledÃ¡vÃ¡nÃ­ (poslednÃ­ moÅ¾nost, kdyÅ¾ normÃ¡lnÃ­ vyhledÃ¡vÃ¡nÃ­ selÅ¾e). Rozsah: -1,0 aÅ¾ +1,0. VÃ½chozÃ­: 0,5. ZÃ¡loÅ¾nÃ­ vyhledÃ¡vÃ¡nÃ­ pouÅ¾Ã­vÃ¡ MaxDistance=2 a uvolnÄ›nÃ© prahovÃ© hodnoty zisku.</t>
    <t id="9109">Kupte si minimÃ¡lnÃ­ cenu pro zÃ¡loÅ¾nÃ­ vyhledÃ¡vÃ¡nÃ­ (poslednÃ­ moÅ¾nost, kdyÅ¾ normÃ¡lnÃ­ vyhledÃ¡vÃ¡nÃ­ selÅ¾e). Rozsah: -1,0 aÅ¾ +1,0. VÃ½chozÃ­: -0,5. ZÃ¡loÅ¾nÃ­ vyhledÃ¡vÃ¡nÃ­ pouÅ¾Ã­vÃ¡ MaxDistance=2 a uvolnÄ›nÃ© prahovÃ© hodnoty zisku.</t>
    <t id="9116">ZÃ¡kladnÃ­ minimÃ¡lnÃ­ zisk na Ãºrovni 15 pro stÅ™ednÃ­ho obchodnÃ­ka (referenÄnÃ­ nÃ¡klad 8200). SkuteÄnÃ½ MinAbsoluteProfit je vypoÄÃ­tÃ¡n na pilota + Å¡kÃ¡lovÃ¡n podle nÃ¡kladu:\n\nzÃ¡klad (L) = zÃ¡klad * ((L-1)^2 / 14^2)\nÅ¡kÃ¡lovanÃ½ = zÃ¡klad (L) * (nÃ¡klad / 8200)\nkoneÄnÃ½ = max (pÅ™imÄ›Å™enÃ½, 25 % zÃ¡kladu (L))\n\nJakÃ½koli jinÃ½ zisk/ROI platÃ­ pouze pro akceptovÃ¡nÃ­/nastavenÃ­ na 0).</t>
    <t id="9125">MinimÃ¡lnÃ­ hrÃ¡ÄskÃ© penÃ­ze (kredity) poÅ¾adovanÃ© pÅ™ed tÃ­m, neÅ¾ budou lodÄ› hledat obchody. KdyÅ¾ hrÃ¡ÄskÃ© penÃ­ze klesnou pod tuto hranici, vÅ¡echny lodÄ› pÅ™eskoÄÃ­ obchodnÃ­ hledÃ¡nÃ­ a ÄekajÃ­, ÄÃ­mÅ¾ zabrÃ¡nÃ­ drahÃ©mu skenovÃ¡nÃ­ mezipamÄ›ti, kterÃ© zpÅ¯sobÃ­ zasekÃ¡vÃ¡nÃ­ hry. Rozsah: 1 000 - 100 000 kr. VÃ½chozÃ­: 1 000 kr.</t>
    <t id="9124">MaximÃ¡lnÃ­ procentuÃ¡lnÃ­ pokles ROI z hodnoty uloÅ¾enÃ© v mezipamÄ›ti pÅ™ed odmÃ­tnutÃ­m obchodu. PÅ™Ã­klad: 20% ROI uloÅ¾enÃ© v mezipamÄ›ti s 15% tolerancÃ­ pÅ™ijme aÅ¾ 17% ROI (14% pokles).</t>
    <t id="9126">Minuty v doku pÅ™ed odokovÃ¡nÃ­m pro uvolnÄ›nÃ­ pÅ™Ã­stavu (0-60). 0 = zÅ¯stane v doku, dokud nenÃ­ nalezena novÃ¡ prÃ¡ce. VÃ½chozÃ­: 1 minuta.</t>
    <t id="9154">Automaticky zakÃ¡zat vÅ¡echny sektory vlastnÄ›nÃ© nepÅ™Ã¡telskÃ½mi frakcemi (zaÅ¡krtÃ¡vacÃ­ polÃ­Äko vztahu na ÄernÃ© listinÄ›)</t>
    <t id="9155">MinimÃ¡lnÃ­ ÃºroveÅˆ ohroÅ¾enÃ­ (1-5) vyÅ¾adovanÃ¡ pro Äernou listinu sektoru:\n2=StÅ™ednÃ­ (jedinÃ½ Ãºtok)\n3=StÅ™ednÄ› vysokÃ¡ (nepÅ™Ã¡telskÃ© frakce)\n4=VysokÃ¡ (hlavnÃ­ lodÄ›/rakety)\n5=Velmi vysokÃ¡ (Xenon/Khaak)</t>
    <t id="9156">RuÄnÄ› znovu vytvoÅ™it Äernou listinu vyhÃ½bÃ¡nÃ­ se hrozbÃ¡m (uÅ¾iteÄnÃ©, pokud byla odstranÄ›na)</t>
    <t id="9157">RuÄnÄ› pÅ™iÅ™aÄte aktuÃ¡lnÃ­ dynamickou Äernou listinu vÅ¡em GT lodÃ­m velitelÅ¯ flotily. PodÅ™Ã­zenÃ­ dÄ›dÃ­ po svÃ©m veliteli.</t>
    <t id="6001">UÄeÅˆ</t>
    <t id="6002">KurÃ½r</t>
    <t id="6003">Dodavatel</t>
    <t id="6004">ObchodnÃ­k</t>
    <t id="6005">ObchodnÃ­k</t>
    <t id="6006">ObchodnÃ­k na dlouhÃ© vzdÃ¡lenosti</t>
    <t id="6101">VyrovnanÃ½</t>
    <t id="6102">ObrannÃ½</t>
    <t id="6103">ZamÄ›Å™enÃ© na obchodovÃ¡nÃ­</t>
    <t id="6104">TÄ›Å¾kÃ¡ obrana</t>
    <t id="6105">Podpora vÄ›Å¾e</t>
    <t id="9050">SystÃ©m pÅ™edchÃ¡zenÃ­ hrozbÃ¡m</t>
    <t id="9051">Povolit pÅ™edchÃ¡zenÃ­ hrozbÃ¡m:</t>
    <t id="9052">PrÃ¡h nepÅ™Ã¡telskÃ½ch vztahÅ¯:</t>
    <t id="9053">PouÅ¾Ã­t dynamickou Äernou listinu:</t>
    <t id="9151">ObchodnÃ­ci na Ãºrovni 6+ odhalujÃ­ nepÅ™Ã¡telskÃ© lodÄ› a vyhÃ½bajÃ­ se nebezpeÄnÃ½m trasÃ¡m. Deaktivace zastavÃ­ veÅ¡kerÃ© skenovÃ¡nÃ­ (zlepÅ¡Ã­ vÃ½kon). Tolerance rizika na loÄ v chovÃ¡nÃ­ velenÃ­ (stupnice 0-10).</t>
    <t id="9152">Jako hrozbu oznaÄte pouze frakce se vztahem na nebo pod touto hodnotou. VÃ½chozÃ­: -20 %</t>
    <t id="9153">Automaticky zablokujte nebezpeÄnÃ© sektory (ÃºroveÅˆ ohroÅ¾enÃ­ 3+), abyste pÅ™inutili lodÄ› obchÃ¡zet hrozby. Pro alternativnÃ­ cesty pouÅ¾Ã­vÃ¡ vanilku.</t>
    <t id="9060">AutomatickÃ© doplÅˆovÃ¡nÃ­ obrannÃ©ho vybavenÃ­ (ÃºroveÅˆ 15)</t>
    <t id="9061">Povolit automatickÃ© doplÅˆovÃ¡nÃ­:</t>
    <t id="9062">ProtiopatÅ™enÃ­ na doplnÄ›nÃ­ zÃ¡sob:</t>
    <t id="9063">DoplnÄ›nÃ­ obrannÃ½ch dronÅ¯:</t>
    <t id="9064">DoplÅˆkovÃ© obchodnÃ­ drony:</t>
    <t id="9065">DoplnÄ›nÃ­ zÃ¡sob laserovÃ½ch vÄ›Å¾Ã­:</t>
    <t id="9066">Drony na opravu zÃ¡sob:</t>
    <t id="9067">PrÃ¡h protiopatÅ™enÃ­:</t>
    <t id="9068">SjednocenÃ½ limit kapacity:</t>
    <t id="9069">Profil vyvÃ¡Å¾enÃ­ vybavenÃ­:</t>
    <t id="9161">Master Traders (ÃºroveÅˆ 15) po obchodech automaticky obnovujÃ­ zÃ¡soby obrannÃ©ho vybavenÃ­. PlatÃ­ pro ÃºroveÅˆ velitele pro podÅ™Ã­zenÃ©.</t>
    <t id="9162">VÅ¡echny lodÄ› (S/M/L/XL). SamostatnÃ¡ kapacita. RozhodujÃ­cÃ­ pro protiraketovou obranu.</t>
    <t id="9163">DodÃ¡vÃ¡me pouze L/XL. SdÃ­lÃ­ jednotnou kapacitu s ostatnÃ­mi nasaditelnÃ½mi.</t>
    <t id="9164">DodÃ¡vÃ¡me pouze L/XL. NezbytnÃ© pro obchodnÃ­ operace. SdÃ­lÃ­ jednotnou kapacitu.</t>
    <t id="9165">VÅ¡echny lodÄ›. LodÄ› L/XL sdÃ­lejÃ­ jednotnou kapacitu, S/M vyuÅ¾Ã­vajÃ­ nÃ¡klad.</t>
    <t id="9166">DodÃ¡vÃ¡me pouze L/XL. Pracuje se systÃ©mem automatickÃ½ch oprav. SdÃ­lÃ­ jednotnou kapacitu.</t>
    <t id="9167">DoplÅˆte zÃ¡soby, kdyÅ¾ protiopatÅ™enÃ­ pod toto procento (vÅ¡echny lodÄ›, samostatnÃ¡ kapacita).</t>
    <t id="9168">DoplÅˆte zÃ¡soby, kdyÅ¾ je celkovÃ½ poÄet nasazenÃ­ pod toto procento (lodÄ› L/XL: drony + vÄ›Å¾e sdÃ­lejÃ­ jednu kapacitu).</t>
    <t id="9169">RozdÄ›lenÃ­ jednotnÃ© kapacity (lodÄ› L/XL): ZamÄ›Å™enÃ© na obchodovÃ¡nÃ­ (20/50/20/10), VyvÃ¡Å¾enÃ© (35/35/20/10), ObrannÃ© (50/20/20/10), TÄ›Å¾kÃ¡ obrana (40/30/20/10), Podpora vÄ›Å¾Ã­ (30/30/30/10). PomÄ›ry: Obrana/Obchod/VÄ›Å¾e/Opravy. KliknutÃ­m mÅ¯Å¾ete prochÃ¡zet moÅ¾nosti.</t>
    <t id="9090">Ãšpravy lodÃ­</t>
    <t id="9091">Povolit Ãºpravy lodÃ­</t>
    <t id="9191">Automaticky nainstalujte modifikace lodi a motoru na zÃ¡kladÄ› pilotnÃ­ ÃºrovnÄ›. ÃšroveÅˆ 9+ = Ãšpravy ÃºrovnÄ› 1, ÃšroveÅˆ 12+ = Ãšpravy ÃºrovnÄ› 2, ÃšroveÅˆ 15+ = Ãšpravy ÃºrovnÄ› 3. PÅ™i zruÅ¡enÃ­ objednÃ¡vky jsou odstranÄ›ny pouze mody nainstalovanÃ© v GT.</t>
    <t id="9070">Konfigurace pojmenovÃ¡nÃ­ lodÃ­</t>
    <t id="9071">Displej XP:</t>
    <t id="9072">PoÅ™adÃ­ zobrazenÃ­:</t>
    <t id="9073">ÃšroveÅˆ zobrazenÃ­:</t>
    <t id="9074">Stav zobrazenÃ­:</t>
    <t id="9075">Povolit pÅ™ejmenovÃ¡nÃ­ lodi:</t>
    <t id="9076">PÅ™edpona</t>
    <t id="9077">PÅ™Ã­pona</t>
    <t id="9078">VÃ½chozÃ­ zdroj nÃ¡zvu:</t>
    <t id="9079">NÃ¡zev modelu</t>
    <t id="9080">Zadejte NÃ¡zev</t>
    <t id="9081">ModelovÃ¡ zÃ¡kladna</t>
    <t id="9083">VlastnÃ­ nÃ¡zev</t>
    <t id="9084">Zobrazit domovskÃ½ sektor:</t>
    <t id="9085">ReÅ¾im pojmenovÃ¡nÃ­:</t>
    <t id="9086">KlasickÃ½</t>
    <t id="9087">Vzor</t>
    <t id="9088">Vzor nÃ¡zvu:</t>
    <t id="9089">ZÃ¡stupnÃ© symboly: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. AtomickÃ©: {RS} {CB} {BL} atd. PouÅ¾Ã­vÃ¡ zkratky stavÅ¯ nÃ­Å¾e. PrÃ¡zdnÃ© tokeny se vynechajÃ­; mezery se slouÄÃ­. Max. 128 znakÅ¯.</t>
    <t id="9183">Zobrazit nastavenÃ½ domovskÃ½ sektor v nÃ¡zvu lodi (pÅ™edpona nebo pÅ™Ã­pona).</t>
    <t id="9184">VlastnÃ­ formÃ¡t nÃ¡zvu se zÃ¡stupnÃ½mi symboly {TOKEN} mÃ­sto klasickÃ½ch pÅ™epÃ­naÄÅ¯. VyÅ¾aduje XP GalaxyTrader (ne reÅ¾im vanilla XP).</t>
    <t id="9092">ZÃ¡stupnÃ© symboly vzoru</t>
    <t id="9093">LoÄ: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT (mod): {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Domov: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">PosÃ¡dka: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Sektor: {SECTOR} | Statistiky: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">ZnaÄky stavu:</t>
    <t id="9100">{OPSTATE}: vÅ¡echny aktivnÃ­ provoznÃ­ pÅ™Ã­znaky dohromady (napÅ™. CB RS, MT)</t>
    <t id="9101">{STATUS}: blokovÃ¡no, vÃ½cvik, zÃ¡loha nebo izolovÃ¡no</t>
    <t id="9102">{CB}: pouze vlastnÃ­ blacklist; souÄÃ¡st {OPSTATE}; nekombinovat</t>
    <t id="9082">Zobrazit tÅ™Ã­du lodi:</t>
    <t id="9171">Zobrazit hodnoty XP ve jmÃ©nech lodÃ­</t>
    <t id="9175">Povolit nebo zakÃ¡zat automatickÃ© pÅ™ejmenovÃ¡nÃ­ lodi s informacemi o pilotovi</t>
    <t id="9172">Zobrazovat hodnostnÃ­ tituly ve jmÃ©nech lodÃ­</t>
    <t id="9173">Zobrazte ÄÃ­sla ÃºrovnÃ­ v nÃ¡zvech lodÃ­</t>
    <t id="9174">Zobrazit obchodnÃ­ stav v nÃ¡zvech lodÃ­</t>
    <t id="9178">Vyberte zdroj nÃ¡zvÅ¯ zÃ¡kladen lodÃ­: NÃ¡zev modelu (s variantou), NÃ¡zev typu (obecnÃ½), ZÃ¡kladna modelu (bez varianty) nebo VlastnÃ­ nÃ¡zev (uloÅ¾enÃ½ nÃ¡zev)</t>
    <t id="9182">UveÄte tÅ™Ã­du lodi (S, M, L, XL) v nÃ¡zvech lodÃ­</t>
    <t id="9200">NastavenÃ­ ladÄ›nÃ­</t>
    <t id="9201">Povolit protokolovÃ¡nÃ­ ladÄ›nÃ­:</t>
    <t id="9202">HlavnÃ­ pÅ™epÃ­naÄ pro veÅ¡kerÃ½ vÃ½stup debug_text. Je-li zakÃ¡zÃ¡no, veÅ¡kerÃ© protokolovÃ¡nÃ­ ladÄ›nÃ­ je potlaÄeno. Je-li povoleno, ladicÃ­ zprÃ¡vy se zobrazujÃ­ v DebugLog na zÃ¡kladÄ› jednotlivÃ½ch hodnot pravdÄ›podobnosti debug_text.</t>
    <t id="9220">ÃšdrÅ¾ba a diagnostika</t>
    <t id="9221">Resetovat statistiky zisku:</t>
    <t id="9222">RESETOVAT</t>
    <t id="9223">Vymazat vÅ¡echny sektory na ÄernÃ© listinÄ›:</t>
    <t id="9224">JASNÃ</t>
    <t id="9225">Obnovit vÅ¡echna nastavenÃ­ na vÃ½chozÃ­:</t>
    <t id="9226">RESETOVAT VÅ E</t>
    <t id="9323">Odebere vÅ¡echny sektory z ÄernÃ© listiny informacÃ­ o hrozbÃ¡ch. To okamÅ¾itÄ› vymaÅ¾e vÅ¡echny sektory na ÄernÃ© listinÄ› a umoÅ¾nÃ­ vaÅ¡im lodÃ­m cestovat do dÅ™Ã­ve zablokovanÃ½ch oblastÃ­. Tuto moÅ¾nost pouÅ¾ijte, pokud chcete resetovat systÃ©m vyhÃ½bÃ¡nÃ­ se hrozbÃ¡m nebo pokud byly sektory nesprÃ¡vnÄ› uvedeny na ÄernÃ© listinÄ›.</t>
    <t id="9321">Resetuje vÅ¡echny statistiky zisku na 0 pro vÅ¡echny piloty a lodÄ›. PouÅ¾ijte to po upgradu na verzi 0.6.0 k vymazÃ¡nÃ­ nadsazenÃ½ch statistik zaloÅ¾enÃ½ch na pÅ™Ã­jmech. Oprava nynÃ­ sleduje skuteÄnÃ½ ZISK (vÃ½nos - poÅ™izovacÃ­ cena). PoÄty obchodÅ¯ a XP jsou zachovÃ¡ny.</t>
    <t id="9325">ObnovÃ­ vÅ¡echna globÃ¡lnÃ­ nastavenÃ­ na vÃ½chozÃ­ hodnoty. To zahrnuje nastavenÃ­ XP, koordinaci flotily, upozornÄ›nÃ­, Mobile Intel, pÅ™edchÃ¡zenÃ­ hrozbÃ¡m, pojmenovÃ¡nÃ­ lodÃ­, automatickÃ© opravy, Ãºpravy, vÃ½kon a nastavenÃ­ formÃ¡tu ÄÃ­sel. NastavenÃ­ protokolovÃ¡nÃ­ ladÄ›nÃ­ je zachovÃ¡no, aby bylo moÅ¾nÃ© protokolovat operaci resetovÃ¡nÃ­.</t>
    <t id="9227">Vymazat mezipamÄ›Å¥ obchodu pro vÅ¡echny domÃ¡cÃ­ sektory:</t>
    <t id="9228">VYMAZAT CACHE</t>
    <t id="9327">VymaÅ¾e mezipamÄ›Å¥ obchodu pro vÅ¡echny domÃ¡cÃ­ sektory. To pÅ™inutÃ­ vÅ¡echny lodÄ›, aby pÅ™i pÅ™Ã­Å¡tÃ­m obchodnÃ­m hledÃ¡nÃ­ provedly novÃ© Å¾ivÃ© vyhledÃ¡vÃ¡nÃ­. Tuto moÅ¾nost pouÅ¾ijte, pokud se mezipamÄ›Å¥ zdÃ¡ zastaralÃ¡ nebo poÅ¡kozenÃ¡, nebo pokud chcete vynutit ÃºplnÃ© obnovenÃ­ mezipamÄ›ti.</t>
    <t id="9229">UvolnÄ›te vÅ¡echny zÃ¡mky vyhledÃ¡vÃ¡nÃ­</t>
    <t id="9329">UvolnÃ­ VÅ ECHNY zÃ¡mky obchodnÃ­ho vyhledÃ¡vÃ¡nÃ­ za letu a vymaÅ¾e souvisejÃ­cÃ­ pÅ™echodnÃ© stavy. PouÅ¾ijte to, pokud lodÄ› uvÃ­zly na â€žHledÃ¡nÃ­ obchodÅ¯â€œ kvÅ¯li zastaralÃ½m zÃ¡mkÅ¯m ze starÃ½ch uloÅ¾enÃ­. To mÅ¯Å¾e pÅ™eruÅ¡it legitimnÃ­ vyhledÃ¡vÃ¡nÃ­.</t>
    <t id="9290">Stav Dump Trade Hub:</t>
    <t id="9291">SKLAD</t>
    <t id="9390">Zobrazuje jednorÃ¡zovÃ½ snÃ­mek centralizovanÃ©ho obchodnÃ­ho centra (fronty plÃ¡novaÄe + stav poslednÃ­ Å¾Ã¡dosti o odeslÃ¡nÃ­) v protokolu a jako upozornÄ›nÃ­.</t>
    <t id="9292">Dump Trade Cache (FULL):</t>
    <t id="9293">VYLOÅ½IT CACHE</t>
    <t id="9392">FULL cache dump (mÅ¯Å¾e bÃ½t obrovskÃ½). Zapisuje vÅ¡echny poloÅ¾ky mezipamÄ›ti do DebugLog po ÄÃ¡stech. Pro zruÅ¡enÃ­ kliknÄ›te znovu.</t>
    <t id="9294">Vymazat rezervace flotily:</t>
    <t id="9295">JASNÃ</t>
    <t id="9394">VymaÅ¾e vÅ¡echny aktivnÃ­ obchodnÃ­ rezervace flotily. Tuto moÅ¾nost pouÅ¾ijte, pokud se lodÄ› zdajÃ­ bÃ½t zaseknutÃ© a ÄekajÃ­ na vyprÅ¡enÃ­ rezervovanÃ½ch obchodÅ¯ nebo pokud je rezervaÄnÃ­ tabulka zastaralÃ¡ po naÄtenÃ­ starÃ©ho uloÅ¾enÃ­.</t>
    <t id="9230">VÃ½kon</t>
    <t id="9231">ZpoÅ¾dÄ›nÃ­ dÃ¡vkovÃ©ho zpracovÃ¡nÃ­:</t>
    <t id="9232">ZpoÅ¾dÄ›nÃ­ ovÄ›Å™enÃ­:</t>
    <t id="9233">MaximÃ¡lnÃ­ poÄet soubÄ›Å¾nÃ½ch vyhledÃ¡vÃ¡nÃ­:</t>
    <t id="9234">MaximÃ¡lnÃ­ poÄet obchodÅ¯ k vrÃ¡cenÃ­:</t>
    <t id="9235">MaximÃ¡lnÃ­ nabÃ­dky za zboÅ¾Ã­:</t>
    <t id="9236">MaximÃ¡lnÃ­ poÄet obchodÅ¯ na zboÅ¾Ã­:</t>
    <t id="9237">MaximÃ¡lnÃ­ nabÃ­dky za zboÅ¾Ã­ za odpovÃ­dajÃ­cÃ­:</t>
    <t id="9238">PrÃ¡h pÅ™edÄasnÃ©ho odchodu:</t>
    <t id="9241">Interval vÃ½Å™ezÅ¯ Å¾ivÃ© nabÃ­dky:</t>
    <t id="9266">TTL zÃ¡mku vyhledÃ¡vÃ¡nÃ­:</t>
    <t id="9263">Velikost dÃ¡vky:</t>
    <t id="9239">FormÃ¡t ÄÃ­sla</t>
    <t id="9240">Styl formÃ¡tu:</t>
    <t id="9242">PouÅ¾ijte pÅ™Ã­ponu M</t>
    <t id="9243">PrÃ¡h pÅ™Ã­pony M:</t>
    <t id="9244">nÄ›mÄina (123 456,78)</t>
    <t id="9245">angliÄtina (123 456,78)</t>
    <t id="9510">OznÃ¡menÃ­ o povÃ½Å¡enÃ­ ÃºrovnÄ›:</t>
    <t id="9511">UpozornÄ›nÃ­ na potÅ™ebu Å¡kolenÃ­:</t>
    <t id="9512">OznÃ¡menÃ­ o dokonÄenÃ­ Å¡kolenÃ­:</t>
    <t id="9513">ZprÃ¡vy o zisku:</t>
    <t id="9514">TrÅ¾nÃ­ upozornÄ›nÃ­:</t>
    <t id="9515">Aktualizace flotily:</t>
    <t id="9516">PouÅ¾Ã­vejte pouze vanilku XP</t>
    <t id="9610">Povolit nebo zakÃ¡zat vyskakovacÃ­ oznÃ¡menÃ­ o povÃ½Å¡enÃ­ ÃºrovnÄ› obchodnÃ­ka v rozhranÃ­ hrÃ¡Äe.</t>
    <t id="9611">UpozornÄ›nÃ­, kdyÅ¾ piloti potÅ™ebujÃ­ Å¡kolenÃ­ pro postup na dalÅ¡Ã­ ÃºroveÅˆ.</t>
    <t id="9612">OznÃ¡menÃ­ pÅ™i dokonÄenÃ­ Å¡kolenÃ­ pilotÅ¯ a postupu v hodnosti.</t>
    <t id="9613">PravidelnÃ© souhrny ziskÅ¯ (jednoduchÃ© a komplexnÃ­ zprÃ¡vy).</t>
    <t id="9614">VÃ½jimeÄnÃ© pÅ™Ã­leÅ¾itosti na trhu a upozornÄ›nÃ­ na vysokohodnotnÃ© obchody.</t>
    <t id="9615">ZprÃ¡vy o koordinaci flotily a aktualizace stavu.</t>
    <t id="9616">PouÅ¾ijte pilot.skill.piloting a deaktivujte GT XP progresi/caps.</t>
    <t id="9246">Frekvence jednoduchÃ©ho pÅ™ehledu:</t>
    <t id="9247">Frekvence komplexnÃ­ch zprÃ¡v:</t>
    <t id="9248">MaximÃ¡lnÃ­ poÄet soubÄ›Å¾nÃ½ch vyhledÃ¡vÃ¡nÃ­ v mezipamÄ›ti:</t>
    <t id="9249">MaximÃ¡lnÃ­ poÄet soubÄ›Å¾nÃ½ch Å¾ivÃ½ch vyhledÃ¡vÃ¡nÃ­:</t>
    <t id="9340">Vyberte formÃ¡t ÄÃ­sla: NÄ›mÄina pouÅ¾Ã­vÃ¡ '.' pro tisÃ­ce a ',' pro desetinnÃ¡ mÃ­sta (123.456,78), angliÄtina pouÅ¾Ã­vÃ¡ ',' pro tisÃ­ce a '.' pro desetinnÃ¡ mÃ­sta (123 456,78)</t>
    <t id="9342">Povolit pÅ™Ã­ponu M pro ÄÃ­sla vÄ›tÅ¡Ã­ neÅ¾ prahovÃ¡ hodnota (napÅ™. 1,0 M mÃ­sto 1 000 000)</t>
    <t id="9343">PrÃ¡h pro pÅ™Ã­ponu M. ÄŒÃ­sla nad touto hodnotou se zobrazÃ­ s pÅ™Ã­ponou M (vÃ½chozÃ­: 999 999)</t>
    <t id="9346">Frekvence jednoduchÃ©ho reportu (vyskakovacÃ­ upozornÄ›nÃ­): 0-30 minut (0 = vypnuto - jednoduchÃ© reporty jsou vypnuty, vÃ½chozÃ­: 1 minuta)</t>
    <t id="9347">Frekvence komplexnÃ­ zprÃ¡vy (zÃ¡pis do denÃ­ku): 0-60 minut (0 = vypnuto - komplexnÃ­ zprÃ¡vy jsou zakÃ¡zÃ¡ny, vÃ½chozÃ­: 30 minut)</t>
    <t id="9398">PouÅ¾ijte GT Credits Due Override</t>
    <t id="9399">NahraÄte nebo rozÅ¡iÅ™te vanilkovÃ½ Å™Ã¡dek â€žCR splatnÃ© z obchodÅ¯â€œ pÅ™edpoklÃ¡danou hodnotou GT ve stejnÃ©m slotu uÅ¾ivatelskÃ©ho rozhranÃ­.</t>
    <t id="9331">Prodleva mezi dÃ¡vkami bÄ›hem zpracovÃ¡nÃ­ obchodnÃ­ho vyhledÃ¡vÃ¡nÃ­ (1-500 ms). VyÅ¡Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale zpomalujÃ­ obchodnÃ­ vyhledÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 120 ms. PouÅ¾Ã­vÃ¡ se v dÃ¡vkovÃ©m procesoru a filtrovÃ¡nÃ­ obchodnÃ­ch seznamÅ¯.</t>
    <t id="9332">Prodleva mezi obchodnÃ­mi ovÄ›Å™enÃ­mi ve skriptu AI (1-500 ms). VyÅ¡Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale zpomalujÃ­ ovÄ›Å™ovÃ¡nÃ­ obchodu. VÃ½chozÃ­: 50 ms. PouÅ¾Ã­vÃ¡ se pÅ™i validaci obchodnÃ­ho listu ze systÃ©mu MD.</t>
    <t id="9333">MaximÃ¡lnÃ­ poÄet obchodnÃ­ch vyhledÃ¡vÃ¡nÃ­, kterÃ¡ mohou probÃ­hat souÄasnÄ› (1-10). NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zatÃ­Å¾enÃ­ procesoru, ale prodluÅ¾ujÃ­ doby ÄekÃ¡nÃ­ ve frontÄ›. VyÅ¡Å¡Ã­ hodnoty zpracovÃ¡vajÃ­ vyhledÃ¡vÃ¡nÃ­ rychleji, ale mohou zpÅ¯sobit nÃ¡rÅ¯st vÃ½konu. VÃ½chozÃ­: 1.</t>
    <t id="9334">MaximÃ¡lnÃ­ poÄet obchodÅ¯, kterÃ© se majÃ­ vrÃ¡tit z vyhledÃ¡vÃ¡nÃ­ mezipamÄ›ti (1-100). VyÅ¡Å¡Ã­ hodnoty poskytujÃ­ vÃ­ce obchodnÃ­ch moÅ¾nostÃ­, ale prodluÅ¾ujÃ­ dobu ovÄ›Å™enÃ­ mezipamÄ›ti. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale mohou minout Å¾ivotaschopnÃ© obchody. VÃ½chozÃ­: 20.</t>
    <t id="9335">MaximÃ¡lnÃ­ poÄet nabÃ­dek na zboÅ¾Ã­ ke zpracovÃ¡nÃ­ v Å¾ivÃ©m vyhledÃ¡vÃ¡nÃ­ (5-100). VyÅ¡Å¡Ã­ hodnoty zohledÅˆujÃ­ vÃ­ce nabÃ­dek, ale prodluÅ¾ujÃ­ dobu zpracovÃ¡nÃ­. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale mohou minout ziskovÃ© obchody. VÃ½chozÃ­: 20.</t>
    <t id="9336">MaximÃ¡lnÃ­ poÄet obchodÅ¯ na zboÅ¾Ã­ bÄ›hem dÃ¡vkovÃ©ho zpracovÃ¡nÃ­ (5-100). VyÅ¡Å¡Ã­ hodnoty umoÅ¾ÅˆujÃ­ vÃ­ce obchodÅ¯ na zboÅ¾Ã­, ale prodluÅ¾ujÃ­ dobu zpracovÃ¡nÃ­. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale mohou minout ziskovÃ© obchody. VÃ½chozÃ­: 20.</t>
    <t id="9337">MaximÃ¡lnÃ­ poÄet nabÃ­dek na zboÅ¾Ã­ pro pÃ¡rovÃ¡nÃ­ v dÃ¡vkovÃ©m procesoru (5-100). VyÅ¡Å¡Ã­ hodnoty zohledÅˆujÃ­ vÃ­ce nabÃ­dek, ale prodluÅ¾ujÃ­ dobu zpracovÃ¡nÃ­. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale mohou minout ziskovÃ© obchody. VÃ½chozÃ­: 20.</t>
    <t id="9338">PrÃ¡h pÅ™edÄasnÃ©ho ukonÄenÃ­ pro dÃ¡vkovÃ© zpracovÃ¡nÃ­ (100-10000). KdyÅ¾ je nalezeno tolik obchodÅ¯, dÃ¡vkovÃ© zpracovÃ¡nÃ­ se zastavÃ­ dÅ™Ã­ve, aby se uÅ¡etÅ™ilo CPU. VyÅ¡Å¡Ã­ hodnoty zpracujÃ­ vÃ­ce obchodÅ¯, ale zvÃ½Å¡Ã­ zatÃ­Å¾enÃ­ CPU. NiÅ¾Å¡Ã­ hodnoty odejdou dÅ™Ã­ve, ale mohou minout ziskovÃ© obchody. VÃ½chozÃ­: 2000.</t>
    <t id="9341">Interval vÃ½Å™ezu Å¾ivÃ© nabÃ­dky v milisekundÃ¡ch (5-2000 ms). Å˜Ã­dÃ­, jak Äasto se mohou spustit vÃ½Å™ezy Å¾ivÃ© nabÃ­dky. NiÅ¾Å¡Ã­ hodnoty umoÅ¾ÅˆujÃ­ rychlejÅ¡Ã­ shromaÅ¾ÄovÃ¡nÃ­ nabÃ­dek, ale zvyÅ¡ujÃ­ zatÃ­Å¾enÃ­ procesoru. VyÅ¡Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale zpomalujÃ­ zpracovÃ¡nÃ­ Å¾ivÃ©ho vyhledÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 500 ms.</t>
    <t id="9363">Velikost bloku pro dÃ¡vkovÃ© zpracovÃ¡nÃ­ (5-20). Zpracuje kombinace chunkSizeÃ—chunkSize na blok (napÅ™. 5Ã—5 = 25 kombinacÃ­). VÄ›tÅ¡Ã­ bloky zlepÅ¡ujÃ­ propustnost, ale zvyÅ¡ujÃ­ zatÃ­Å¾enÃ­ procesoru na blok. MenÅ¡Ã­ ÄÃ¡sti sniÅ¾ujÃ­ Å¡piÄky CPU, ale vyÅ¾adujÃ­ vÃ­ce pokraÄovÃ¡nÃ­. VÃ½chozÃ­: 5.</t>
    <t id="9348">MaximÃ¡lnÃ­ poÄet prohledÃ¡vÃ¡nÃ­ mezipamÄ›ti, kterÃ© lze spustit souÄasnÄ› (1-20). VyhledÃ¡vÃ¡nÃ­ mezipamÄ›ti je rychlÃ© a levnÃ©; niÅ¾Å¡Ã­ hodnoty mohou snÃ­Å¾it prasknutÃ­ u velkÃ½ch vozovÃ½ch parkÅ¯. VÃ½chozÃ­: 2.</t>
    <t id="9349">MaximÃ¡lnÃ­ poÄet Å¾ivÃ½ch vyhledÃ¡vÃ¡nÃ­, kterÃ¡ mohou bÄ›Å¾et souÄasnÄ› (1-10). Å½ivÃ© vyhledÃ¡vÃ¡nÃ­ je nÃ¡roÄnÃ© na CPU, takÅ¾e niÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zÃ¡tÄ›Å¾ CPU, ale prodluÅ¾ujÃ­ ÄekacÃ­ doby ve frontÄ›. VyÅ¡Å¡Ã­ hodnoty zpracovÃ¡vajÃ­ vyhledÃ¡vÃ¡nÃ­ rychleji, ale mohou zpÅ¯sobit nÃ¡rÅ¯st vÃ½konu. VÃ½chozÃ­: 1.</t>
    <t id="9264">Velikost bloku dotazu mezipamÄ›ti:</t>
    <t id="9265">Velikost ÄÃ¡sti pro pÅ™ipojenÃ­ Å¾ivÃ© nabÃ­dky:</t>
    <t id="9364">ZÃ¡znamy mezipamÄ›ti ovÄ›Å™enÃ© na blok (10-200). MenÅ¡Ã­ hodnoty rozÅ¡iÅ™ujÃ­ ovÄ›Å™enÃ­ mezipamÄ›ti na vÃ­ce snÃ­mkÅ¯ (hladÅ¡Ã­), ale mohou prodlouÅ¾it Äas na nalezenÃ­ obchodu uloÅ¾enÃ©ho v mezipamÄ›ti. VÃ½chozÃ­: 10.</t>
    <t id="9365">NabÃ­dky pÅ™ipojenÃ© na jeden dodatkovÃ½ segment (50-2000). MenÅ¡Ã­ hodnoty sniÅ¾ujÃ­ prÃ¡ci s pÅ™ipojovÃ¡nÃ­m seznamu na snÃ­mek (plynulejÅ¡Ã­), ale mohou zpomalit dokonÄenÃ­ Å¾ivÃ©ho vyhledÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 200.</t>
    <t id="9366">Doba Å¾ivotnosti zÃ¡mku vyhledÃ¡vÃ¡nÃ­ v sekundÃ¡ch (60-7200). Pokud je loÄ odmÃ­tnuta s â€žobchodnÃ­m vyhledÃ¡vÃ¡nÃ­m jiÅ¾ probÃ­hÃ¡â€œ dÃ©le, neÅ¾ je tato doba, GT se samo uzdravÃ­ vymazÃ¡nÃ­m zastaralÃ©ho stavu vyhledÃ¡vÃ¡nÃ­ a uvolnÄ›nÃ­m zÃ¡mku. VÃ½chozÃ­: 600 s.</t>
    <t id="9370">MÄ›kkÃ½ prÃ¡h dÃ¡vkovÃ©ho protitlaku:</t>
    <t id="9371">TvrdÃ½ prÃ¡h dÃ¡vkovÃ©ho protitlaku:</t>
    <t id="9372">Sektory na plÃ¡tek:</t>
    <t id="9373">Home Refresh Cooldown:</t>
    <t id="9374">VyrovnÃ¡vacÃ­ pamÄ›Å¥ Miss Cooldown Base:</t>
    <t id="9375">Interval tikÃ¡nÃ­ plÃ¡novaÄe:</t>
    <t id="9376">MaximÃ¡lnÃ­ poÄet dotazÅ¯ v mezipamÄ›ti na zaÅ¡krtnutÃ­:</t>
    <t id="9377">MaximÃ¡lnÃ­ poÄet pokraÄovÃ¡nÃ­ ve vyhledÃ¡vÃ¡nÃ­ na zaÅ¡krtnutÃ­:</t>
    <t id="9378">MaximÃ¡lnÃ­ poÄet zÃ¡silek na jeden tick:</t>
    <t id="9379">MaximÃ¡lnÃ­ poÄet poloÅ¾ek na tick:</t>
    <t id="9380">MaximÃ¡lnÃ­ poÄet probuzenÃ­ za tiknutÃ­:</t>
    <t id="9381">MaximÃ¡lnÃ­ poÄet poloÅ¾ek dotazu v mezipamÄ›ti:</t>
    <t id="9382">Stale Threshold Seconds:</t>
    <t id="9383">PoÄet sekund ve frontÄ›:</t>
    <t id="9384">PoÄet sekund vyprÅ¡enÃ­ neÃºspÄ›Å¡nÃ©ho obchodu:</t>
    <t id="9385">MaximÃ¡lnÃ­ poÄet soubÄ›Å¾nÃ½ch zÃ¡loÅ¾nÃ­ch vyhledÃ¡vÃ¡nÃ­:</t>
    <t id="9386">MaximÃ¡lnÃ­ poÄet soubÄ›Å¾nÃ½ch zÃ¡loÅ¾nÃ­ch vyhledÃ¡vÃ¡nÃ­:</t>
    <t id="9470">MÄ›kkÃ½ prÃ¡h pro nevyÅ™Ã­zenÃ© dÃ¡vky dÃ¡vkovÃ©ho procesoru (5-50). KdyÅ¾ nevyÅ™Ã­zenÃ© poloÅ¾ky dosÃ¡hnou tÃ©to hodnoty, zaÄne se uplatÅˆovat zpÄ›tnÃ½ tlak ke zpomalenÃ­ novÃ½ch poÅ¾adavkÅ¯ na vyhledÃ¡vÃ¡nÃ­. NiÅ¾Å¡Ã­ hodnoty spouÅ¡tÄ›jÃ­ protitlak dÅ™Ã­ve (konzervativnÄ›jÅ¡Ã­). VÃ½chozÃ­: 10.</t>
    <t id="9471">PevnÃ½ prÃ¡h pro nevyÅ™Ã­zenÃ© dÃ¡vky procesoru (10-100). KdyÅ¾ nevyÅ™Ã­zenÃ© poloÅ¾ky dosÃ¡hnou tÃ©to hodnoty, novÃ© Å¾ivÃ© vyhledÃ¡vÃ¡nÃ­ se zablokujÃ­, dokud se nevyÅ™Ã­zenÃ© poloÅ¾ky nesnÃ­Å¾Ã­. NiÅ¾Å¡Ã­ hodnoty blokujÃ­ vyhledÃ¡vÃ¡nÃ­ dÅ™Ã­ve (konzervativnÄ›jÅ¡Ã­). VÃ½chozÃ­: 25.</t>
    <t id="9472">Sektory zpracovanÃ© na Å™ez v kolekci Å¾ivÃ½ch nabÃ­dek (1-5). MenÅ¡Ã­ hodnoty rozloÅ¾Ã­ prÃ¡ci na vÃ­ce snÃ­mkÅ¯ (hladÅ¡Ã­), ale mohou zpomalit shromaÅ¾ÄovÃ¡nÃ­ nabÃ­dek. VÄ›tÅ¡Ã­ hodnoty se zpracovÃ¡vajÃ­ rychleji, ale mohou zpÅ¯sobit Å¡piÄky snÃ­mkÅ¯. VÃ½chozÃ­: 1.</t>
    <t id="9473">Cooldown po dokonÄenÃ­ obnovy domÃ¡cÃ­ho sektoru (10-120 sekund). ZabraÅˆuje nadmÄ›rnÃ©mu poÅ¾adavku na obnovenÃ­. NiÅ¾Å¡Ã­ hodnoty umoÅ¾ÅˆujÃ­ ÄastÄ›jÅ¡Ã­ obnovovÃ¡nÃ­, ale zvyÅ¡ujÃ­ zatÃ­Å¾enÃ­ procesoru. VyÅ¡Å¡Ã­ hodnoty sniÅ¾ujÃ­ obnovovacÃ­ frekvenci, ale mohou zpozdit aktualizace mezipamÄ›ti. VÃ½chozÃ­: 30 s.</t>
    <t id="9474">ZÃ¡kladnÃ­ cooldown po vynechÃ¡nÃ­ mezipamÄ›ti pÅ™ed opÄ›tovnÃ½m pokusem o Å¾ivÃ© vyhledÃ¡vÃ¡nÃ­ (1-30 sekund). ZabraÅˆuje nadmÄ›rnÃ½m pokusÅ¯m o opakovÃ¡nÃ­. NiÅ¾Å¡Ã­ hodnoty opakujte dÅ™Ã­ve, ale zvyÅ¡te zatÃ­Å¾enÃ­ procesoru. VyÅ¡Å¡Ã­ hodnoty sniÅ¾ujÃ­ frekvenci opakovÃ¡nÃ­, ale mohou zpozdit nalezenÃ­ obchodu. VÃ½chozÃ­: 10 s.</t>
    <t id="9475">Interval mezi tikÃ¡nÃ­m plÃ¡novaÄe v milisekundÃ¡ch (50-500 ms). Å˜Ã­dÃ­, jak Äasto plÃ¡novaÄ zpracovÃ¡vÃ¡ pracovnÃ­ frontu. NiÅ¾Å¡Ã­ hodnoty zpracovÃ¡vajÃ­ ÄastÄ›ji, ale zvyÅ¡ujÃ­ zatÃ­Å¾enÃ­ procesoru. VyÅ¡Å¡Ã­ hodnoty sniÅ¾ujÃ­ zatÃ­Å¾enÃ­ procesoru, ale mohou prodlouÅ¾it dobu ÄekÃ¡nÃ­ ve frontÄ›. VÃ½chozÃ­: 100 ms.</t>
    <t id="9476">MaximÃ¡lnÃ­ poÄet dotazÅ¯ mezipamÄ›ti zahÃ¡jenÃ½ch na jeden tick plÃ¡novaÄe (1-5). Omezuje rychlost dotazÅ¯ v mezipamÄ›ti, aby se zabrÃ¡nilo blokovÃ¡nÃ­ snÃ­mkÅ¯. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ Å¡piÄky CPU, ale zpomalujÃ­ vyhledÃ¡vÃ¡nÃ­ mezipamÄ›ti. VyÅ¡Å¡Ã­ hodnoty se zpracovÃ¡vajÃ­ rychleji, ale mohou zpÅ¯sobit zadrhÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 1.</t>
    <t id="9477">MaximÃ¡lnÃ­ poÄet zapoÄatÃ½ch pokraÄovÃ¡nÃ­ hledÃ¡nÃ­ na zaÅ¡krtnutÃ­ plÃ¡novaÄe (1-5). Omezuje rychlost pokraÄovÃ¡nÃ­, aby se zabrÃ¡nilo blokovÃ¡nÃ­ snÃ­mkÅ¯. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ Å¡piÄky CPU, ale zpomalujÃ­ zpracovÃ¡nÃ­ vyhledÃ¡vÃ¡nÃ­. VyÅ¡Å¡Ã­ hodnoty se zpracovÃ¡vajÃ­ rychleji, ale mohou zpÅ¯sobit zadrhÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 1.</t>
    <t id="9478">MaximÃ¡lnÃ­ poÄet zpracovanÃ½ch lodÃ­ na jedno oznaÄenÃ­ plÃ¡novaÄe (1-5). Omezuje rychlost zpracovÃ¡nÃ­ lodi, aby se zabrÃ¡nilo blokovÃ¡nÃ­ snÃ­mkÅ¯. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ Å¡piÄky CPU, ale zpomalujÃ­ zpracovÃ¡nÃ­ fronty. VyÅ¡Å¡Ã­ hodnoty se zpracovÃ¡vajÃ­ rychleji, ale mohou zpÅ¯sobit zadrhÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 1.</t>
    <t id="9479">MaximÃ¡lnÃ­ poÄet pracovnÃ­ch poloÅ¾ek zpracovanÃ½ch na jednu znaÄku plÃ¡novaÄe (1-5). Omezuje rychlost zpracovÃ¡nÃ­ pracovnÃ­ch poloÅ¾ek, aby se zabrÃ¡nilo blokovÃ¡nÃ­ snÃ­mkÅ¯. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ Å¡piÄky CPU, ale zpomalujÃ­ zpracovÃ¡nÃ­ fronty. VyÅ¡Å¡Ã­ hodnoty se zpracovÃ¡vajÃ­ rychleji, ale mohou zpÅ¯sobit zadrhÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 1.</t>
    <t id="9480">MaximÃ¡lnÃ­ poÄet probuzenÃ½ch ÄÃ­Å¡nÃ­kÅ¯ na jedno tiknutÃ­ plÃ¡novaÄe (1-10). Omezuje rychlost probuzenÃ­, aby se zabrÃ¡nilo Å¡piÄkÃ¡m CPU, kdyÅ¾ je ve frontÄ› mnoho ÄÃ­Å¡nÃ­kÅ¯. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ Å¡piÄky CPU, ale zpomalujÃ­ zpracovÃ¡nÃ­ ÄÃ­Å¡nÃ­ka. VyÅ¡Å¡Ã­ hodnoty se zpracovÃ¡vajÃ­ rychleji, ale mohou zpÅ¯sobit zadrhÃ¡vÃ¡nÃ­. VÃ½chozÃ­: 2.</t>
    <t id="9481">MaximÃ¡lnÃ­ poÄet dotazovanÃ½ch poloÅ¾ek mezipamÄ›ti na dÃ¡vku (1-200). Å˜Ã­dÃ­ velikost dÃ¡vky dotazÅ¯ mezipamÄ›ti. NiÅ¾Å¡Ã­ hodnoty zrychlÃ­ vyhledÃ¡vÃ¡nÃ­ mezipamÄ›ti, ale mohou minout lepÅ¡Ã­ obchody. VyÅ¡Å¡Ã­ hodnoty zohledÅˆujÃ­ vÃ­ce obchodÅ¯ uloÅ¾enÃ½ch v mezipamÄ›ti, ale prodluÅ¾ujÃ­ dobu ovÄ›Å™enÃ­. VÃ½chozÃ­: 50.</t>
    <t id="9482">PrahovÃ¡ hodnota zastaralÃ©ho stavu Å¾ivÃ©ho vyhledÃ¡vÃ¡nÃ­ v sekundÃ¡ch (60-600). KdyÅ¾ je stav Å¾ivÃ©ho vyhledÃ¡vÃ¡nÃ­ starÅ¡Ã­ neÅ¾ tento, povaÅ¾uje se za zastaralÃ½ a vymazanÃ½. NiÅ¾Å¡Ã­ hodnoty vyÄistÃ­ zastaralÃ½ stav dÅ™Ã­ve, ale mohou pÅ™eruÅ¡it legitimnÃ­ vyhledÃ¡vÃ¡nÃ­. VyÅ¡Å¡Ã­ hodnoty umoÅ¾ÅˆujÃ­ delÅ¡Ã­ vyhledÃ¡vÃ¡nÃ­, ale mohou ponechat zastaralÃ½ stav. VÃ½chozÃ­: 300 s.</t>
    <t id="9483">PrÃ¡h zastaralÃ© poloÅ¾ky fronty v sekundÃ¡ch (30-300). KdyÅ¾ jsou poloÅ¾ky fronty starÅ¡Ã­ neÅ¾ tato, jsou povaÅ¾ovÃ¡ny za zastaralÃ© a odstranÄ›nÃ©. NiÅ¾Å¡Ã­ hodnoty odstranÃ­ zastaralÃ© poloÅ¾ky dÅ™Ã­ve, ale mohou odstranit legitimnÃ­ poloÅ¾ky ve frontÄ›. VyÅ¡Å¡Ã­ hodnoty umoÅ¾ÅˆujÃ­ delÅ¡Ã­ dobu ve frontÄ›, ale mohou ponechat zastaralÃ© poloÅ¾ky. VÃ½chozÃ­: 60 s.</t>
    <t id="9484">NeÃºspÄ›Å¡nÃ© vyprÅ¡enÃ­ obchodnÃ­ mezipamÄ›ti v sekundÃ¡ch (300-3600). NeÃºspÄ›Å¡nÃ© obchody jsou uklÃ¡dÃ¡ny do mezipamÄ›ti, aby se zabrÃ¡nilo okamÅ¾itÃ©mu opakovÃ¡nÃ­. NiÅ¾Å¡Ã­ hodnoty vyprÅ¡Ã­ neÃºspÄ›Å¡nÃ© obchody dÅ™Ã­ve (vÃ­ce opakovÃ¡nÃ­), ale sniÅ¾ujÃ­ efektivitu mezipamÄ›ti. VyÅ¡Å¡Ã­ hodnoty uklÃ¡dajÃ­ do mezipamÄ›ti dÃ©le (mÃ©nÄ› opakovÃ¡nÃ­), ale mohou zpozdit pokusy o opakovÃ¡nÃ­. VÃ½chozÃ­: 1800 s (30 minut).</t>
    <t id="9485">MaximÃ¡lnÃ­ poÄet soubÄ›Å¾nÃ½ch zÃ¡loÅ¾nÃ­ch Å¾ivÃ½ch vyhledÃ¡vÃ¡nÃ­ (1-10). ZÃ¡loÅ¾nÃ­ vyhledÃ¡vÃ¡nÃ­ obchÃ¡zÃ­ zÃ¡mek domovskÃ©ho sektoru a umoÅ¾Åˆuje vÃ­ce lodÃ­m ze stejnÃ©ho domovskÃ©ho sektoru hledat souÄasnÄ›. NiÅ¾Å¡Ã­ hodnoty sniÅ¾ujÃ­ zatÃ­Å¾enÃ­ procesoru, ale mohou zpomalit zÃ¡loÅ¾nÃ­ vyhledÃ¡vÃ¡nÃ­. VyÅ¡Å¡Ã­ hodnoty umoÅ¾ÅˆujÃ­ vÃ­ce paralelnÃ­ch zÃ¡loÅ¾nÃ­ch vyhledÃ¡vÃ¡nÃ­, ale zvyÅ¡ujÃ­ vyuÅ¾itÃ­ procesoru. VÃ½chozÃ­: 1.</t>
    <t id="9490">ZpoÅ¾dÄ›nÃ­ signÃ¡lu nalezenÃ©ho obchodu:</t>
    <t id="9590">ZpoÅ¾dÄ›nÃ­ pÅ™ed odeslÃ¡nÃ­m signÃ¡lu GT_Trade_Found lodÃ­m v milisekundÃ¡ch (10-1000 ms). LodÄ› vÅ¾dy ÄekajÃ­ (konfigurovanÃ© zpoÅ¾dÄ›nÃ­ + 5 ms vyrovnÃ¡vacÃ­ pamÄ›Å¥) pÅ™ed odeslÃ¡nÃ­m novÃ½ch poÅ¾adavkÅ¯ na zachycenÃ­ zpoÅ¾dÄ›nÃ½ch signÃ¡lÅ¯. VyÅ¡Å¡Ã­ hodnoty Å¡Ã­Å™Ã­ signÃ¡ly mezi snÃ­mky pro hladÅ¡Ã­ vÃ½kon. VÃ½chozÃ­: 10 ms.</t>
    <t id="8000">Flotila GalaxyTrader</t>
    <t id="8001">SprÃ¡va flotily GalaxyTrader a statistiky pilotÅ¯</t>
    <t id="8002">ProhlÃ­Å¾ejte a spravujte vÅ¡echny piloty GalaxyTrader</t>
    <t id="8100">ID lodi</t>
    <t id="8101">Pilot</t>
    <t id="8102">LoÄ</t>
    <t id="8103">PostavenÃ­</t>
    <t id="8104">PoÅ™adÃ­</t>
    <t id="8105">ÃšroveÅˆ</t>
    <t id="8106">XP</t>
    <t id="8107">DoÅ¾ivotnÃ­ zisk</t>
    <t id="8108">UmÃ­stÄ›nÃ­</t>
    <t id="8109">DomÃ¡cÃ­ zÃ¡kladna</t>
    <t id="8110">PoslednÃ­ obchod</t>
    <t id="8111">PilotnÃ­ zisk</t>
    <t id="8112">LodnÃ­ zisk</t>
    <t id="8113">Obchod Count</t>
    <t id="8200">Obnovit</t>
    <t id="8201">Export CSV</t>
    <t id="8202">Statistika</t>
    <t id="8203">NastavenÃ­</t>
    <t id="8204">Pomoc</t>
    <t id="8205">BlÃ­zko</t>
    <t id="8300">VÅ¡ichni piloti</t>
    <t id="8301">ObchodovÃ¡nÃ­</t>
    <t id="8302">VÃ½cvik</t>
    <t id="8303">ÃšdrÅ¾ba</t>
    <t id="8304">Stav nouze</t>
    <t id="8305">ZaÄÃ¡teÄnÃ­ci (Lv 1-5)</t>
    <t id="8306">PokroÄilÃ­ (Lv 6-11)</t>
    <t id="8307">Experti (Lv 12+)</t>
    <t id="8308">10 nejlÃ©pe vydÄ›lÃ¡vajÃ­cÃ­ch</t>
    <t id="8350">SeÅ™adit podle:</t>
    <t id="8351">ID lodi</t>
    <t id="8352">JmÃ©no pilota</t>
    <t id="8353">Typ lodi</t>
    <t id="8354">PostavenÃ­</t>
    <t id="8355">PoÅ™adÃ­</t>
    <t id="8356">ÃšroveÅˆ</t>
    <t id="8357">XP</t>
    <t id="8358">Zisk</t>
    <t id="8400">Å½Ã¡dnÃ­ piloti registrovÃ¡ni</t>
    <t id="8401">Filtru neodpovÃ­dajÃ­ Å¾Ã¡dnÃ­ piloti</t>
    <t id="8402">CelkovÃ½ poÄet pilotÅ¯:</t>
    <t id="8403">CelkovÃ½ zisk flotily:</t>
    <t id="8404">PoslednÃ­ aktualizace:</t>
    <t id="8405">Hledat piloty...</t>
    <t id="8114">Sektor</t>
    <t id="8320">PÅ™ejmenovÃ¡nÃ­ lodi</t>
    <t id="8321">VlastnÃ­ nÃ¡zev</t>
    <t id="8322">Nastavit nÃ¡zev</t>
    <t id="8323">Vymazat jmÃ©no</t>
    <t id="8324">JmÃ©no bylo ÃºspÄ›Å¡nÄ› nastaveno</t>
    <t id="8325">NÃ¡zev byl ÃºspÄ›Å¡nÄ› vymazÃ¡n</t>
    <t id="8450">Odeslat na Å¡kolenÃ­</t>
    <t id="8451">ZruÅ¡it registraci</t>
    <t id="8452">Vynutit prodej nÃ¡kladu</t>
    <t id="8453">Odeslat do opravy</t>
    <t id="8454">Odeslat do Resupply</t>
    <t id="8455">Zastavit vÅ¡echny objednÃ¡vky</t>
    <t id="8456">Akce</t>
    <t id="8500">KliknutÃ­m seÅ™adÃ­te podle ID lodi</t>
    <t id="8501">KlepnutÃ­m seÅ™adÃ­te podle nÃ¡zvu pilota</t>
    <t id="8502">KliknutÃ­m seÅ™adÃ­te podle typu lodi</t>
    <t id="8503">KliknutÃ­m seÅ™adÃ­te podle stavu</t>
    <t id="8504">KliknutÃ­m seÅ™adÃ­te podle poÅ™adÃ­</t>
    <t id="8505">KliknutÃ­m seÅ™adÃ­te podle ÃºrovnÄ›</t>
    <t id="8506">KliknutÃ­m seÅ™adÃ­te podle XP</t>
    <t id="8507">KliknutÃ­m seÅ™adÃ­te podle celoÅ¾ivotnÃ­ho zisku</t>
    <t id="8508">Obnovte pilotnÃ­ data ze systÃ©mu mise</t>
    <t id="8509">Export aktuÃ¡lnÃ­ho zobrazenÃ­ do souboru CSV</t>
    <t id="8510">ProhlÃ©dnÄ›te si statistiky a grafy vozovÃ©ho parku</t>
    <t id="8511">Konfigurace nastavenÃ­ nabÃ­dky</t>
    <t id="8512">Zobrazit nÃ¡povÄ›du a klÃ¡vesovÃ© zkratky</t>
    <t id="8600">Nebyli nalezeni Å¾Ã¡dnÃ­ piloti GalaxyTrader</t>
    <t id="8601">VytvoÅ™te piloty pÅ™iÅ™azenÃ­m lodÃ­ k GalaxyTrader nebo poÄkejte, aÅ¾ se naÄtou data.</t>
    <t id="9001">PÅ™ejmenovÃ¡nÃ­ GT</t>
    <t id="9902">Odeslat na Å¡kolenÃ­</t>
    <t id="9903">RuÄnÃ­ Å¡kolenÃ­ ve frontÄ› pro %1. Pilot zahÃ¡jÃ­ vÃ½cvik po aktuÃ¡lnÃ­m cyklu.</t>
    <t id="9904">TrÃ©nink ve frontÄ› po aktuÃ¡lnÃ­m cyklu</t>
    <t id="9905">Pilot nebo loÄ nebyla nalezena</t>
    <t id="9906">AutoTraining je povolen - nenÃ­ vyÅ¾adovÃ¡na manuÃ¡lnÃ­ fronta</t>
    <t id="9907">Pilot nenÃ­ blokovÃ¡n vÃ½cvikem</t>
    <t id="9910">ObchodnÃ­ akademie</t>
    <t id="9911">UÄeÅˆ (Lvl 4) - %1 / %2</t>
    <t id="9912">Trader (Lvl 7) â€“ %1 / %2</t>
    <t id="9913">Master Trader (Lvl 13) â€“ %1 / %2</t>
    <t id="9920">Pilot %1 se zapsal do kurzu Akademie pro ÃºroveÅˆ %2. Odjezd na nejbliÅ¾Å¡Ã­ obchodnÃ­ stanici.</t>
    <t id="9921">Nedostatek finanÄnÃ­ch prostÅ™edkÅ¯ na tento kurz (potÅ™ebujete %1, mÃ¡te %2).</t>
    <t id="9922">Kurz nenÃ­ k dispozici - pilot %1 je jiÅ¾ na tÃ©to Ãºrovni nebo nad nÃ­.</t>
    <t id="9923">Pilot %1 se zapsal do kurzu Trading Academy Level %2 (cena: %3 Cr, trvÃ¡nÃ­: %4 min) na palubÄ› %5.</t>
    <t id="11011">GT Apprentice Medium Ship Reduktor</t>
    <t id="11012">Ãšprava motoru, kterÃ¡ mÃ­rnÄ› sniÅ¾uje vÃ½kon pro nezkuÅ¡enÃ© piloty na stÅ™ednÃ­ch lodÃ­ch. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -5% rychlosti, tahu a rotace.</t>
    <t id="11013">StÅ™ednÃ­ cestovnÃ­ redukce GT Apprentice</t>
    <t id="11014">Ãšprava motoru, kterÃ¡ mÃ­rnÄ› sniÅ¾uje cestovnÃ­ vÃ½kon pro nezkuÅ¡enÃ© piloty na stÅ™ednÃ­ch lodÃ­ch. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -5% cestovnÃ­ rychlost.</t>
    <t id="11021">Reduktor velkÃ½ch lodÃ­ GT Apprentice</t>
    <t id="11022">Ãšprava motoru, kterÃ¡ sniÅ¾uje vÃ½kon pro nezkuÅ¡enÃ© piloty na velkÃ½ch lodÃ­ch. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -15% rychlost, tah a rotace.</t>
    <t id="11023">VelkÃ½ cestovnÃ­ reduktor GT Apprentice</t>
    <t id="11024">Ãšprava motoru, kterÃ¡ sniÅ¾uje cestovnÃ­ vÃ½kon pro nezkuÅ¡enÃ© piloty na velkÃ½ch lodÃ­ch. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -15% cestovnÃ­ rychlost.</t>
    <t id="11031">GT Apprentice Capital Ship Reduktor</t>
    <t id="11032">Ãšprava motoru, kterÃ¡ vÃ½raznÄ› sniÅ¾uje vÃ½kon pro nezkuÅ¡enÃ© piloty na kapitÃ¡lovÃ½ch lodÃ­ch. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -25% rychlost, tah a rotace.</t>
    <t id="11033">GT Apprentice Capital Travel Reduktor</t>
    <t id="11034">Ãšprava motoru, kterÃ¡ vÃ½raznÄ› sniÅ¾uje cestovnÃ­ vÃ½kon pro nezkuÅ¡enÃ© piloty na kapitÃ¡lovÃ½ch lodÃ­ch. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -25% cestovnÃ­ rychlost.</t>
    <t id="12001">GT Basic Small Ship Enhancer</t>
    <t id="12002">SpecializovanÃ¡ Ãºprava motoru pro malÃ© lodÄ› se zÃ¡kladnÃ­mi certifikovanÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +3% rychlosti, tahu a rotace.</t>
    <t id="12003">GT Basic Small Travel Enhancer</t>
    <t id="12004">SpecializovanÃ¡ Ãºprava motoru pro malÃ© lodÄ› se zÃ¡kladnÃ­mi certifikovanÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +3% cestovnÃ­ rychlost.</t>
    <t id="13001">GT Basic Large Ship Reduktor</t>
    <t id="13002">SpecializovanÃ¡ Ãºprava motoru pro velkÃ© lodÄ› se zÃ¡kladnÃ­mi certifikovanÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -8% rychlosti, tahu a rotace.</t>
    <t id="13003">VelkÃ¡ cestovnÃ­ redukce GT Basic</t>
    <t id="13004">SpecializovanÃ¡ Ãºprava motoru pro velkÃ© lodÄ› se zÃ¡kladnÃ­mi certifikovanÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -8% cestovnÃ­ rychlost.</t>
    <t id="14001">GT Basic Capital Ship Reduktor</t>
    <t id="14002">SpecializovanÃ¡ Ãºprava motoru pro kapitÃ¡lovÃ© lodÄ› se zÃ¡kladnÃ­mi certifikovanÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -15% rychlost, tah a rotace.</t>
    <t id="14003">GT Basic Capital Travel Reduktor</t>
    <t id="14004">SpecializovanÃ¡ Ãºprava motoru pro kapitÃ¡lovÃ© lodÄ› se zÃ¡kladnÃ­mi certifikovanÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. -15% cestovnÃ­ rychlost.</t>
    <t id="15001">GT Expert Small Ship Enhancer</t>
    <t id="15002">PokroÄilÃ¡ Ãºprava motoru pro malÃ© lodÄ› s zkuÅ¡enÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +25 % rychlosti, tahu a rotace.</t>
    <t id="15003">GT Expert Small Travel Enhancer</t>
    <t id="15004">PokroÄilÃ¡ Ãºprava motoru pro malÃ© lodÄ› s zkuÅ¡enÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +25% cestovnÃ­ rychlost.</t>
    <t id="16001">GT Expert Large Ship Enhancer</t>
    <t id="16002">PokroÄilÃ¡ Ãºprava motoru pro velkÃ© lodÄ› s zkuÅ¡enÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +15% rychlosti, tahu a rotace.</t>
    <t id="16003">GT Expert Large Travel Enhancer</t>
    <t id="16004">PokroÄilÃ¡ Ãºprava motoru pro velkÃ© lodÄ› s zkuÅ¡enÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +15% cestovnÃ­ rychlost.</t>
    <t id="17001">GT Expert Capital Ship Enhancer</t>
    <t id="17002">PokroÄilÃ¡ Ãºprava motoru pro kapitÃ¡lovÃ© lodÄ› s zkuÅ¡enÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +6% rychlost, tah a rotace.</t>
    <t id="17003">GT Expert Capital Travel Enhancer</t>
    <t id="17004">PokroÄilÃ¡ Ãºprava motoru pro kapitÃ¡lovÃ© lodÄ› s zkuÅ¡enÃ½mi piloty. PouÅ¾Ã­vÃ¡ se systÃ©mem GalaxyTrader AI. +6% cestovnÃ­ rychlost.</t>
    <t id="18001">VÃ¡Å¾nÃ© omezenÃ­ dovednostÃ­ (loÄ)</t>
    <t id="18002">ZÃ¡vaÅ¾nÃ© omezenÃ­ dovednostÃ­ (loÄ) - pÅ™edstavuje pÅ™Ã­snÃ© tresty za vÃ½kon v dÅ¯sledku nezkuÅ¡enosti pilota s velkÃ½mi plavidly. Automaticky aplikovÃ¡no systÃ©mem GalaxyTrader, kdyÅ¾ pilotnÃ­ dovednosti nestaÄÃ­ pro velikost lodi. ZvyÅ¡uje hmotnost lodi. (Pouze systÃ©m GT - nenÃ­ k dispozici pro ruÄnÃ­ instalaci)</t>
    <t id="18003">StÅ™ednÃ­ omezenÃ­ dovednostÃ­ (loÄ)</t>
    <t id="18004">StÅ™ednÃ­ omezenÃ­ dovednostÃ­ (loÄ) - pÅ™edstavuje mÃ­rnÃ© tresty za vÃ½kon, kdyÅ¾ se pilot pÅ™izpÅ¯sobuje sloÅ¾itosti plavidla. Automaticky aplikovÃ¡no systÃ©mem GalaxyTrader, kdyÅ¾ pilotnÃ­ dovednosti nestaÄÃ­ pro velikost lodi. ZvyÅ¡uje hmotnost lodi. (Pouze systÃ©m GT - nenÃ­ k dispozici pro ruÄnÃ­ instalaci)</t>
    <t id="18005">LehkÃ© omezenÃ­ dovednostÃ­ (loÄ)</t>
    <t id="18006">LehkÃ© omezenÃ­ dovednostÃ­ (loÄ) - PÅ™edstavuje menÅ¡Ã­ tresty za vÃ½kon bÄ›hem rozvoje pilotnÃ­ch dovednostÃ­. Automaticky aplikovÃ¡no systÃ©mem GalaxyTrader, kdyÅ¾ pilotnÃ­ dovednosti nestaÄÃ­ pro velikost lodi. ZvyÅ¡uje hmotnost lodi. (Pouze systÃ©m GT - nenÃ­ k dispozici pro ruÄnÃ­ instalaci)</t>
    <t id="18007">VÃ¡Å¾nÃ© omezenÃ­ dovednostÃ­ (motor)</t>
    <t id="18008">ZÃ¡vaÅ¾nÃ© omezenÃ­ dovednostÃ­ (motor) - pÅ™edstavuje pÅ™Ã­snÃ© tresty za vÃ½kon v dÅ¯sledku nezkuÅ¡enosti pilota s velkÃ½mi plavidly. Automaticky aplikovÃ¡no systÃ©mem GalaxyTrader, kdyÅ¾ pilotnÃ­ dovednosti nestaÄÃ­ pro velikost lodi. SniÅ¾uje tah motoru a otÃ¡ÄenÃ­. (Pouze systÃ©m GT - nenÃ­ k dispozici pro ruÄnÃ­ instalaci)</t>
    <t id="18009">StÅ™ednÃ­ omezenÃ­ dovednostÃ­ (motor)</t>
    <t id="18010">StÅ™ednÃ­ omezenÃ­ dovednostÃ­ (motor) - PÅ™edstavuje mÃ­rnÃ© tresty za vÃ½kon, kdyÅ¾ se pilot pÅ™izpÅ¯sobuje sloÅ¾itosti plavidla. Automaticky aplikovÃ¡no systÃ©mem GalaxyTrader, kdyÅ¾ pilotnÃ­ dovednosti nestaÄÃ­ pro velikost lodi. SniÅ¾uje tah motoru a otÃ¡ÄenÃ­. (Pouze systÃ©m GT - nenÃ­ k dispozici pro ruÄnÃ­ instalaci)</t>
    <t id="18011">LehkÃ© omezenÃ­ dovednostÃ­ (motor)</t>
    <t id="18012">LehkÃ© omezenÃ­ dovednostÃ­ (motor) - pÅ™edstavuje menÅ¡Ã­ vÃ½konovÃ© tresty bÄ›hem rozvoje pilotnÃ­ch dovednostÃ­. Automaticky aplikovÃ¡no systÃ©mem GalaxyTrader, kdyÅ¾ pilotnÃ­ dovednosti nestaÄÃ­ pro velikost lodi. SniÅ¾uje tah motoru a otÃ¡ÄenÃ­. (Pouze systÃ©m GT - nenÃ­ k dispozici pro ruÄnÃ­ instalaci)</t>
    <t id="9250">PojmenovÃ¡nÃ­ stavu lodi</t>
    <t id="9350">PÅ™izpÅ¯sobte si zkratky stavu lodi. VÃ½chozÃ­ hodnoty jsou zobrazeny ve vstupnÃ­ch polÃ­ch a lze je pÅ™epsat. MaximÃ¡lnÄ› 3 znaky. VÅ¡echna jmÃ©na lodÃ­ se pÅ™i zmÄ›nÄ› automaticky aktualizujÃ­.</t>
    <t id="9251">Zkratka stavu zÃ¡sob:</t>
    <t id="9252">Zkratka stavu opravy:</t>
    <t id="9253">Zkratka stavu ÃºdrÅ¾by:</t>
    <t id="9254">Zkratka vÃ½cvikovÃ©ho stÃ¡tu:</t>
    <t id="9255">Zkratka stÃ¡tu pÅ™esmÄ›rovÃ¡nÃ­:</t>
    <t id="9256">Zkratka stavu odbavenÃ­:</t>
    <t id="9257">Zkratka blokovanÃ©ho stavu:</t>
    <t id="9258">Zkratka zÃ¡loÅ¾nÃ­ho stÃ¡tu:</t>
    <t id="9259">Zkratka izolovanÃ©ho stÃ¡tu:</t>
    <t id="9260">Zkratka obchodnÃ­ho stÃ¡tu:</t>
    <t id="9261">Zkratka neÄinnÃ©ho stavu:</t>
    <t id="9262">Zkratka ÃºnikovÃ©ho stavu:</t>
    <t id="9268">Zkratka nedostupnÃ©ho stÃ¡tu:</t>
    <t id="9269">PilotnÃ­ burzovnÃ­ zkratka stÃ¡tu:</t>
    <t id="9270">VlastnÃ­ znaÄka pÅ™edpony ÄernÃ© listiny:</t>
    <t id="9700">CHEATY (nefunguje to. nic tu neni!! opravdu!!)</t>
    <t id="9701">GT lode neznicitelne</t>
    <t id="9702">Vsechny hracovy lode neznicitelne</t>
    <t id="9800">Jdete dal, pilote. Rozbite testovaci nastroje, ne zabavne menu. Nic tu neni. Opravdu. Byli jste varovani. Asi.</t>
    <t id="9801">Lode s prikazem GalaxyTrader nemohou klesnout pod 100% trupu nebo stitu. Kliknete znovu pro vypnuti.</t>
    <t id="9802">Vsechny hracovy lode nemohou klesnout pod 100% trupu nebo stitu. Kliknete znovu pro vypnuti. Stanice nejsou ovlivneny.</t>
    <t id="9703">Odhalit vesmir pro testy GT</t>
    <t id="9704">Odhaleno</t>
    <t id="9705">Odhalit</t>
    <t id="9803">Odhali mlhu valky ve vsech sektorech, oznaci vsechny stanice jako zname, prida vsechny licence obchodniho predplatneho a predplati obchodni nabidky v cele galaxii. Po novych DLC sektorech kliknete znovu. Pouze pro testovani.</t>
    <t id="9706">Maximalizovat EP registrovanych GT pilotu</t>
    <t id="9707">Maximalizovano</t>
    <t id="9708">EP max</t>
    <t id="9804">Nastavi uroven 15 a maximalni EP pro kazdeho pilota v GT registru. Odstrani blokace treninku. Preskoci se pri rezimu pouze vanilla EP. Pouze pro testovani.</t>
    <t id="9351">Zkratka pro stav zÃ¡sobovÃ¡nÃ­ (vÃ½chozÃ­: RS)</t>
    <t id="9352">Zkratka pro stav opravy (vÃ½chozÃ­: RP)</t>
    <t id="9353">Zkratka pro stav ÃºdrÅ¾by (vÃ½chozÃ­: MT)</t>
    <t id="9354">Zkratka pro stav Å¡kolenÃ­ (vÃ½chozÃ­: TR)</t>
    <t id="9355">Zkratka pro stav pÅ™esmÄ›rovÃ¡nÃ­ (vÃ½chozÃ­: RR)</t>
    <t id="9356">Zkratka pro stav povolenÃ­ (vÃ½chozÃ­: CL)</t>
    <t id="9357">Zkratka pro stav BlokovÃ¡no (vÃ½chozÃ­: BL)</t>
    <t id="9358">Zkratka pro zÃ¡loÅ¾nÃ­ stav (vÃ½chozÃ­: FB)</t>
    <t id="9359">Zkratka pro izolovanÃ½ stav (vÃ½chozÃ­: IS)</t>
    <t id="9360">Zkratka pro stav obchodovÃ¡nÃ­ (vÃ½chozÃ­: TD)</t>
    <t id="9361">Zkratka pro stav neÄinnosti (vÃ½chozÃ­: ID)</t>
    <t id="9362">Zkratka pro Escape state (vÃ½chozÃ­: ES)</t>
    <t id="9367">Zkratka pro stav nedostupnÃ½ (vÃ½chozÃ­: UR)</t>
    <t id="9368">Zkratka pro stav pilotnÃ­ vÃ½mÄ›ny (vÃ½chozÃ­: PE)</t>
    <t id="9369">Zobrazuje se jako pÅ™edpona pro lodÄ› MK3 ovlivnÄ›nÃ© Äernou listinou vlastnÃ­ frakce (vÄetnÄ› podÅ™Ã­zenÃ½ch). VÃ½chozÃ­: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">ObchodnÃ­k na stanici - prodÃ¡vÃ¡ produkty stanice NPC frakcÃ­m</t>
    <t id="30010">DomÃ¡cÃ­ stanice</t>
    <t id="30011">MaximÃ¡lnÃ­ prodejnÃ­ vzdÃ¡lenost</t>
    <t id="30012">Ignorujte obchodnÃ­ pravidla</t>
    <t id="30013">Filtr zboÅ¾Ã­</t>
    <t id="30014">Prodat cÃ­l naplnÄ›nÃ­ nÃ¡kladu v %</t>
    <t id="30015">Tolerance zpÄ›tnÃ©ho chodu</t>
    <t id="30016">Koupit cÃ­l plnÄ›nÃ­ nÃ¡kladu v %</t>
    <t id="30017">ZÃ¡znamy v denÃ­ku</t>
    <t id="30018">ÃšroveÅˆ oznÃ¡menÃ­</t>
    <t id="30019">Koordinace flotily</t>
    <t id="30020">ÃšroveÅˆ ladÄ›nÃ­</t>
    <t id="30021">ZÃ¡sobovacÃ­ stanice</t>
    <t id="30022">MinimÃ¡lnÃ­ % ÃºloÅ¾iÅ¡tÄ› stanice</t>
    <t id="30023">Povolit nelegÃ¡lnÃ­ zboÅ¾Ã­</t>
    <t id="30024">NÃ¡klad/Zisk</t>
    <t id="30025">Povolit vÃ­ce obchodÅ¯ v jednÃ© cestÄ›</t>
    <t id="30110">HrÃ¡ÄskÃ¡ stanice k prodeji zboÅ¾Ã­ (vyÅ¾aduje pÅ™iÅ™azenÃ­ stanice)</t>
    <t id="30111">MaximÃ¡lnÃ­ vzdÃ¡lenost brÃ¡ny pro nalezenÃ­ kupcÅ¯ NPC (omezeno dovednostmi pilota)</t>
    <t id="30112">Ignorujte omezenÃ­ obchodu na stanici â€“ prodÃ¡vejte jakÃ©koli spÅ™Ã¡telenÃ© frakci bez ohledu na pravidla obchodu na stanici</t>
    <t id="30113">VolitelnÃ½ filtr na nÃ¡dobÃ­; ponechte prÃ¡zdnÃ©, chcete-li prodat vÅ¡echny produkty stanice a obchodnÃ­ zboÅ¾Ã­</t>
    <t id="30114">MinimÃ¡lnÃ­ procento naplnÄ›nÃ­ nÃ¡kladu pÅ™ed odjezdem na prodejnÃ­ cesty</t>
    <t id="30115">MaximÃ¡lnÃ­ povolenÃ½ poÄet skokÅ¯ navÃ­c pÅ™i pÅ™idÃ¡vÃ¡nÃ­ druhÃ©ho zboÅ¾Ã­ na cestu (0 = pouze kupujÃ­cÃ­ pÅ™Ã­mo na trase)</t>
    <t id="30116">CÃ­lovÃ¡ nÃ¡plÅˆ nÃ¡kladu pro dodÃ¡vky (mÄ›kkÃ½ cÃ­l, obchodnÃ­k mÅ¯Å¾e odjet dÅ™Ã­ve)</t>
    <t id="30117">Povolit zÃ¡znamy v denÃ­ku pro jednotlivÃ© obchody</t>
    <t id="30118">ÃšroveÅˆ upozornÄ›nÃ­: 0 = TichÃ½, 1 = NormÃ¡lnÃ­, 2 = PodrobnÃ½</t>
    <t id="30119">Povolit koordinaci vozovÃ©ho parku a systÃ©m rezervace obchodÅ¯</t>
    <t id="30120">ÃšroveÅˆ protokolovÃ¡nÃ­ ladÄ›nÃ­: 0=Vypnuto, 1=NormÃ¡lnÃ­, 2=PodrobnÃ©</t>
    <t id="30121">Je-li povoleno, kupujte takÃ© zdroje pro stanici. DodÃ¡vka mÃ¡ pÅ™ednost, kdyÅ¾ skladovacÃ­ kapacita klesne pod minimÃ¡lnÃ­ prÃ¡h</t>
    <t id="30122">KdyÅ¾ nÄ›kterÃ½ zdroj klesne pod toto procento svÃ©ho cÃ­le, mÃ¡ nabÃ­dka pÅ™ednost pÅ™ed prodejem. IgnorovÃ¡no, pokud si stanice nemÅ¯Å¾e dovolit zdroje</t>
    <t id="30123">Povolit prodej nebo nÃ¡kup nelegÃ¡lnÃ­ho/paÅ¡ovanÃ©ho zboÅ¾Ã­, je-li k dispozici</t>
    <t id="30124">VÃ½bÄ›r prodeje: 1 = nÃ¡klad (upÅ™ednostnit nejvyÅ¡Å¡Ã­ naplnÄ›nÃ­ skladu u zboÅ¾Ã­; pÅ™i remÃ­ze zisk), 2 = zisk (nejlepÅ¡Ã­ skÃ³re zisku)</t>
    <t id="30125">UmoÅ¾nÃ­ spojit vÃ­ce prodejÅ¯ do jednoho cyklu (aÅ¾ 3 zboÅ¾Ã­ nebo cÃ­le). VypnÄ›te pro reÅ¾im jen jednoho obchodu na cyklus</t>
    <t id="30200">Prodej %1 %2 od %3 do %4</t>
    <t id="30201">V okruhu %1 skokÅ¯ nebyli nalezeni Å¾Ã¡dnÃ­ kupci pro produkty stanice</t>
    <t id="30202">DomovskÃ¡ stanice %1 zniÄena â€“ objednÃ¡vka obchodnÃ­ka stanice zruÅ¡ena</t>
    <t id="30203">DomovskÃ¡ stanice %1 jiÅ¾ nenÃ­ ve vlastnictvÃ­ hrÃ¡Äe â€“ objednÃ¡vka byla zruÅ¡ena</t>
    <t id="30204">NutnÃ© pÅ™iÅ™azenÃ­ stanice - objednÃ¡vka zruÅ¡ena</t>
    <t id="30205">MK1 Station Trader zaÄal v %1</t>
    <t id="30206">DokonÄenÃ½ prodej: %1 %2 prodÃ¡no %3 za %4 Cr (zisk: %5 Cr)</t>
    <t id="30207">VÃ½let s vÃ­ce zboÅ¾Ã­m: dodÃ¡nÃ­ %1 zboÅ¾Ã­ do %2 destinacÃ­</t>
    <t id="30208">ZÃ¡sobovÃ¡nÃ­ %1 %2 do %3 od %4</t>
    <t id="30500">NastavenÃ­ GalaxyTrader MK1</t>
    <t id="30501">VÃ½chozÃ­ nastavenÃ­ aplikace Station Trader</t>
    <t id="30502">VÃ½chozÃ­ maximÃ¡lnÃ­ prodejnÃ­ vzdÃ¡lenost</t>
    <t id="30503">VÃ½chozÃ­ cÃ­l pro naplnÄ›nÃ­ nÃ¡kladu</t>
    <t id="30504">VÃ½chozÃ­ Ignorovat pravidla obchodu</t>
    <t id="30505">VÃ½chozÃ­ tolerance zpÄ›tnÃ©ho chodu</t>
    <t id="30506">ÄŒekacÃ­ doba, kdyÅ¾ nebyly nalezeny Å¾Ã¡dnÃ© obchody</t>
    <t id="30507">VÃ½chozÃ­ cÃ­l nÃ¡kupu nÃ¡kladu</t>
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">AutonomnÃ­ tÄ›Å¾ba se zÃ¡sobovÃ¡nÃ­m stanic a progresÃ­ XP</t>
    <t id="31010">DomÃ¡cÃ­ stanice</t>
    <t id="31110">Stanice k tÄ›Å¾bÄ› a doruÄovÃ¡nÃ­ (vzÃ¡jemnÄ› exkluzivnÃ­ s domÃ¡cÃ­m sektorem)</t>
    <t id="31011">DomÃ¡cÃ­ sektor</t>
    <t id="31111">OdvÄ›tvÃ­, ve kterÃ©m se mÃ¡ pÅ¯sobit; pouÅ¾Ã­vÃ¡ se, kdyÅ¾ nenÃ­ nastavena Å¾Ã¡dnÃ¡ domÃ¡cÃ­ stanice</t>
    <t id="31012">KoÅ¡Ã­k zdrojÅ¯</t>
    <t id="31112">ZboÅ¾Ã­ k tÄ›Å¾bÄ›; prÃ¡zdnÃ½ nÃ¡sleduje rozliÅ¡enÃ­ poÅ¾adavku stanice</t>
    <t id="31013">CÃ­lovÃ© stanice</t>
    <t id="31113">VolitelnÃ½ staniÄnÃ­ filtr pro dodÃ¡vky; prÃ¡zdnÃ½ pochÃ¡zÃ­ z domÃ¡cÃ­ho kontextu</t>
    <t id="31014">PrÃ¡h pÅ™eteÄenÃ­ %</t>
    <t id="31114">Stanice s tÃ­mto procentem ÃºloÅ¾iÅ¡tÄ› nebo nad nÃ­m jsou povaÅ¾ovÃ¡ny za plnÃ©</t>
    <t id="31015">Povolit pÅ™epadovÃ½ prodej ostatnÃ­m</t>
    <t id="31115">KdyÅ¾ je povoleno a primÃ¡rnÃ­ cÃ­le jsou plnÃ©, prodÃ¡vejte jinÃ½m stanicÃ­m frakce</t>
    <t id="31016">PÅ™iÅ™adit ke stanici</t>
    <t id="31116">PÅ™iÅ™aÄte loÄ jako podÅ™Ã­zenou tÄ›Å¾bÄ› domovskÃ© stanice, pokud je to moÅ¾nÃ©</t>
    <t id="31017">ZÅ¯staÅˆte doma</t>
    <t id="31117">Omezte tÄ›Å¾bu/prodej do domovskÃ© oblasti s vÃ½jimkou zÃ¡loÅ¾nÃ­ch bÄ›hÅ¯ pÅ™eteÄenÃ­</t>
    <t id="31018">AutomatickÃ© rozmÃ­stÄ›nÃ­ sond zdrojÅ¯</t>
    <t id="31118">Automaticky rozmÃ­stÄ›te naÄtenÃ© sondy zdrojÅ¯ a zahrÅˆte sondy do ÃºdrÅ¾by</t>
    <t id="31019">MaximÃ¡lnÃ­ shromaÅ¾ÄovacÃ­ vzdÃ¡lenost</t>
    <t id="31119">MaximÃ¡lnÃ­ vzdÃ¡lenost brÃ¡ny pro shromÃ¡Å¾dÄ›nÃ­ (0 pouÅ¾Ã­vÃ¡ Äepici dovednostÃ­ pilota/velitele)</t>
    <t id="31020">MaximÃ¡lnÃ­ prodejnÃ­ vzdÃ¡lenost</t>
    <t id="31120">MaximÃ¡lnÃ­ vzdÃ¡lenost brÃ¡ny pro prodej (0 pouÅ¾Ã­vÃ¡ limit dovednostÃ­ pilota/velitele)</t>
    <t id="31021">VyvaÅ¾ovÃ¡nÃ­ flotily</t>
    <t id="31121">Povolte deterministickou koordinaci zÃ¡mÄ›rÅ¯ pro snÃ­Å¾enÃ­ pÅ™eteÄenÃ­ stanice</t>
    <t id="31022">Interval opÄ›tovnÃ© kontroly poptÃ¡vky</t>
    <t id="31122">Jak Äasto probÃ­hÃ¡ vyhodnocenÃ­ poptÃ¡vky/pÅ™epÃ­naÄe tÄ›Å¾aÅ™e</t>
    <t id="31023">Delta kritickÃ© poptÃ¡vky</t>
    <t id="31123">MinimÃ¡lnÃ­ delta nalÃ©havosti potÅ™ebnÃ¡ k pÅ™epnutÃ­ aktivnÃ­ho tÄ›Å¾ebnÃ­ho ware</t>
    <t id="31024">OchlazovÃ¡nÃ­ min. spÃ­naÄe</t>
    <t id="31124">MinimÃ¡lnÃ­ doba mezi dvÄ›ma vÃ½mÄ›nami zboÅ¾Ã­ pro tuto loÄ</t>
    <t id="31025">Min. zÃ¡vazek k nÃ¡kladu %</t>
    <t id="31125">Pokud je nÃ¡plÅˆ nÃ¡kladu vyÅ¡Å¡Ã­ neÅ¾ tato, loÄ upÅ™ednostÅˆuje dokonÄenÃ­ dodÃ¡vky proudu pÅ™ed zmÄ›nou</t>
    <t id="31026">TvrdÃ¡ nouzovÃ¡ delta</t>
    <t id="31126">UrgentnÃ­ delta, kterÃ¡ umoÅ¾Åˆuje okamÅ¾itÃ© pÅ™epnutÃ­ navzdory prahu potvrzenÃ­ nÃ¡kladu</t>
    <t id="31027">ÃšroveÅˆ oznÃ¡menÃ­</t>
    <t id="31127">ÃšroveÅˆ upozornÄ›nÃ­: 0 = TichÃ½, 1 = NormÃ¡lnÃ­, 2 = PodrobnÃ½</t>
    <t id="31028">Pouze hrÃ¡ÄskÃ© stanice</t>
    <t id="31128">Pokud je tato moÅ¾nost povolena, jsou za cÃ­le poptÃ¡vky povaÅ¾ovÃ¡ny pouze stanice vlastnÄ›nÃ© hrÃ¡Äem.</t>
    <t id="31031">Nejprve zkontrolovat poptÃ¡vku</t>
    <t id="31131">Pokud je zapnuto, tÄ›Å¾ebnÃ­ loÄ pÅ™ed tÄ›Å¾bou kontroluje poptÃ¡vku stanic a podle toho urÄuje priority surovin. Pokud je vypnuto, tÄ›Å¾Ã­ z koÅ¡e surovin bez kontroly poptÃ¡vky a skladuje do doby, neÅ¾ bude k dispozici odbÄ›ratel (doporuÄeno pro flotily s jednou surovinou).</t>
    <t id="31032">PÅ™eruÅ¡enÃ­ fyzickÃ©ho skladu %</t>
    <t id="31132">Pro piloty ÃºrovnÄ› 6+: zastavÃ­ tÄ›Å¾bu aktuÃ¡lnÃ­ suroviny, kdyÅ¾ fyzickÃ½ stav na stanici plus nÃ¡klad relevantnÃ­ch tÄ›Å¾aÅ™Å¯ pÅ™ekroÄÃ­ aktuÃ¡lnÃ­ fyzickÃ½ stav o toto procento. PouÅ¾Ã­vÃ¡ skuteÄnÃ© nÃ¡kladnÃ­ mnoÅ¾stvÃ­, ne prÃ¡h pÅ™eteÄenÃ­. 0 = vypnuto.</t>
    <t id="32002">GalaxyTrader Zdroj MK4</t>
    <t id="32102">ObchodnÃ­k s nabÃ­dkou hrÃ¡ÄskÃ½ch stanic pomocÃ­ GT cache/Å¾ivÃ©ho vyhledÃ¡vacÃ­ho kanÃ¡lu</t>
    <t id="32010">PokrytÃ­ VzdÃ¡lenost</t>
    <t id="32110">MaximÃ¡lnÃ­ vzdÃ¡lenost brÃ¡ny od domova pro hledÃ¡nÃ­ cÃ­lovÃ©ho mÃ­sta</t>
    <t id="32011">Koupit Distance</t>
    <t id="32111">MaximÃ¡lnÃ­ vzdÃ¡lenost brÃ¡ny od domova pro hledÃ¡nÃ­ dodavatele</t>
    <t id="32012">Obsluhujte pouze doma</t>
    <t id="32112">Je-li povoleno, je obsluhovÃ¡na pouze poptÃ¡vka bytovÃ© stanice</t>
    <t id="32013">Pouze budovat stanice</t>
    <t id="32113">KdyÅ¾ je povoleno, je obsluhovÃ¡na pouze poptÃ¡vka po sestavenÃ­</t>
    <t id="32014">Koupit od Player</t>
    <t id="32114">Povolit zÃ­skÃ¡vÃ¡nÃ­ zboÅ¾Ã­ od dodavatelÅ¯ vlastnÄ›nÃ½ch hrÃ¡Äem</t>
    <t id="32015">Koupit od frakce</t>
    <t id="32115">Povolit zÃ­skÃ¡vÃ¡nÃ­ zboÅ¾Ã­ od dodavatelÅ¯ nehrÃ¡ÄskÃ½ch frakcÃ­</t>
    <t id="32016">Povolit zdroje</t>
    <t id="32116">Zahrnout zboÅ¾Ã­ zdrojÅ¯ do pÃ¡rovÃ¡nÃ­ poptÃ¡vky</t>
    <t id="32017">Povolit stÅ™ednÄ› pokroÄilÃ©</t>
    <t id="32117">Zahrnout meziprodukty do pÃ¡rovÃ¡nÃ­ poptÃ¡vky</t>
    <t id="32018">Povolit produkty</t>
    <t id="32118">Zahrnout produktovÃ© zboÅ¾Ã­ do pÃ¡rovÃ¡nÃ­ poptÃ¡vky</t>
    <t id="32019">Povolit Tradewares</t>
    <t id="32119">Zahrnout obchodnÃ­ zboÅ¾Ã­ do pÃ¡rovÃ¡nÃ­ poptÃ¡vky</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">SkladovÃ¡ distribuce s Å™Ã­zenÃ­m skladovacÃ­ch prahÅ¯</t>
    <t id="20010">ZdrojovÃ© stanice</t>
    <t id="20011">CÃ­lovÃ© stanice</t>
    <t id="20012">MinimÃ¡lnÃ­ % ÃºloÅ¾iÅ¡tÄ›</t>
    <t id="20013">StatickÃ© ÃºloÅ¾iÅ¡tÄ› %</t>
    <t id="20014">Max ÃºloÅ¾iÅ¡tÄ› %</t>
    <t id="20015">Filtr zboÅ¾Ã­</t>
    <t id="20016">ObousmÄ›rnÃ½ reÅ¾im</t>
    <t id="20017">DomÃ¡cÃ­ stanice (volitelnÃ©)</t>
    <t id="20018">MaximÃ¡lnÃ­ vzdÃ¡lenost</t>
    <t id="20032">DomovskÃ½ sektor (volitelnÃ©)</t>
    <t id="20019">Doba ÄekÃ¡nÃ­ cyklu</t>
    <t id="20030">Povolit nÃ­zkou hlasitost</t>
    <t id="20031">NÃ­zkÃ¡ objemovÃ¡ minimÃ¡lnÃ­ %</t>
    <t id="20110">Seznam zdrojovÃ½ch stanic pro distribuci zboÅ¾Ã­</t>
    <t id="20111">Seznam cÃ­lovÃ½ch stanic/skladÅ¯ pro distribuci zboÅ¾Ã­</t>
    <t id="20112">PrÃ¡h nalÃ©havosti cÃ­le: stanice pod tÃ­mto % ÃºloÅ¾iÅ¡tÄ› obdrÅ¾Ã­ prioritnÃ­ dodÃ¡vky</t>
    <t id="20113">MinimÃ¡lnÃ­ prahovÃ¡ hodnota zdroje: zdroj musÃ­ mÃ­t vÃ­ce neÅ¾ toto %, aby se vÅ¯bec mohl distribuovat</t>
    <t id="20114">PrahovÃ¡ hodnota pÅ™eteÄenÃ­ zdroje: nad tÃ­mto % se zdroj distribuuje i do neurgentnÃ­ch destinacÃ­</t>
    <t id="20115">VolitelnÃ½ filtr na nÃ¡dobÃ­; ponechte prÃ¡zdnÃ©, chcete-li distribuovat veÅ¡kerÃ© zboÅ¾Ã­ ze zdroje</t>
    <t id="20116">Povolit sbÄ›r zpÃ¡teÄnÃ­ cesty z destinacÃ­ zpÄ›t ke zdroji, kdyÅ¾ majÃ­ cÃ­le pÅ™ebytek</t>
    <t id="20117">VolitelnÃ¡ bytovÃ¡ stanice pro pÅ™iÅ™azenÃ­. Pokud je prÃ¡zdnÃ¡, loÄ zÅ¯stane nepÅ™iÅ™azena ke stanicÃ­m.</t>
    <t id="20118">MaximÃ¡lnÃ­ vzdÃ¡lenost brÃ¡ny mezi zdrojem a cÃ­li (0 = neomezeno)</t>
    <t id="20132">VolitelnÃ½ domovskÃ½ sektor pouÅ¾itÃ½ pro parkovÃ¡nÃ­ pÅ™i neÄinnosti, pokud nenÃ­ nastavena domovskÃ¡ stanice.</t>
    <t id="20119">ÄŒas ÄekÃ¡nÃ­ mezi distribuÄnÃ­mi cykly</t>
    <t id="20130">Povolte menÅ¡Ã­ dodÃ¡vky s ohledem na nalÃ©havost pod normÃ¡lnÃ­ minimÃ¡lnÃ­ naplnÄ›nÃ­ nÃ¡kladu.</t>
    <t id="20131">MinimÃ¡lnÃ­ % naplnÄ›nÃ­ nÃ¡kladu pouÅ¾Ã­vanÃ© pÅ™i aktivaci reÅ¾imu nÃ­zkÃ©ho objemu.</t>
    <t id="20200">Distribuce %1 %2 od %3 do %4</t>
    <t id="20201">ZpÃ¡teÄnÃ­ cesta: vyzvednutÃ­ %1 %2 od %3 do %4</t>
    <t id="20202">NenÃ­ potÅ™eba distribuce - vÅ¡echna mÃ­sta urÄenÃ­ jsou dostateÄnÄ› zÃ¡sobena</t>
    <t id="20203">Vsechny zdrojove stanice neplatne - distribuce ceka</t>
    <t id="20204">Vsechny cilove stanice neplatne - distribuce ceka</t>
    <t id="20205">Zdrojova stanice %1 znicena - odstranena z prikazu distribuce</t>
    <t id="20206">Cilova stanice %1 znicena - odstranena z prikazu distribuce</t>
    <t id="20500">GalaxyTrader MK2 - GlobÃ¡lnÃ­ nastavenÃ­</t>
    <t id="20501">VÃ½chozÃ­ nastavenÃ­ distribuce MK2</t>
    <t id="20510">VÃ½chozÃ­ min. % ÃºloÅ¾iÅ¡tÄ›</t>
    <t id="20511">VÃ½chozÃ­ statickÃ© ÃºloÅ¾iÅ¡tÄ› %</t>
    <t id="20512">VÃ½chozÃ­ maximÃ¡lnÃ­ % ÃºloÅ¾iÅ¡tÄ›</t>
    <t id="20513">VÃ½chozÃ­ ÄekÃ¡nÃ­ cyklu (y)</t>
    <t id="20514">MinimÃ¡lnÃ­ % naplnÄ›nÃ­ nÃ¡kladu</t>
    <t id="20520">VÃ½Å™eÄnost oznÃ¡menÃ­</t>
    <t id="20521">ÃšroveÅˆ ladÄ›nÃ­</t>
    <t id="10006">NÃ¡vrat domÅ¯</t>
    <t id="10007">GalaxyTrader ZÃ¡sobovÃ¡nÃ­ MK4-2</t>
    <t id="10106">Zakotvte na domovskÃ© stanici a zÅ¯staÅˆte tam, dokud nebude obchodovÃ¡nÃ­ obnoveno</t>
    <t id="10107">HrÃ¡ÄskÃ½ zÃ¡sobovacÃ­ rozkaz s posuvnÃ­ky priority cÃ­lÅ¯ dodÃ¡vky</t>
    <t id="30026">NÃ¡vrat domÅ¯ mezi cykly</t>
    <t id="30028">Ignorovat nastavenÃ­ nabÃ­dek</t>
    <t id="30029">Rozsah ceny kupujÃ­cÃ­ho</t>
    <t id="30027">Min. sklad produktÅ¯ %</t>
    <t id="30126">Je-li povoleno, vraÅ¥te se do domovskÃ© stanice a doku mezi obchodnÃ­mi cykly. KdyÅ¾ je zakÃ¡zÃ¡no, pokraÄovat ve vyhledÃ¡vÃ¡nÃ­ z aktuÃ¡lnÃ­ polohy (starÅ¡Ã­ chovÃ¡nÃ­)</t>
    <t id="30128">Povolit internÃ­ pÅ™esuny skladu bez nÃ¡kupnÃ­ch/prodejnÃ­ch nabÃ­dek stanice. PouÅ¾Ã­vÃ¡ smÄ›nu zboÅ¾Ã­ pro vyzvednutÃ­ a dodÃ¡nÃ­ z vyrovnÃ¡vacÃ­ho skladu. ObchodnÃ­ pravidla stanice platÃ­, pokud je Ignorovat obchodnÃ­ pravidla vypnuto.</t>
    <t id="30129">MinimÃ¡lnÃ­ relativnÃ­ cena pro NPC kupujÃ­cÃ­ pÅ™i prodeji produktÅ¯ stanice. PosuvnÃ­k objednÃ¡vky 0-200 (100 = prÅ¯mÄ›r, 0 = -100%, 200 = +100%), mapovÃ¡no na -1,0 aÅ¾ +1,0. VyÅ¡Å¡Ã­ = pouze draÅ¾Å¡Ã­ kupujÃ­cÃ­. NiÅ¾Å¡Ã­ = vÃ­ce moÅ¾nostÃ­ kupujÃ­cÃ­ch. ZÃ¡sobovacÃ­ cesty pouÅ¾Ã­vajÃ­ obrÃ¡cenou hodnotu pro cenovÃ© stropy dodavatelÅ¯.</t>
    <t id="30127">MinimÃ¡lnÃ­ procento naplnÄ›nÃ­ skladu stanice (vzhledem ke konfigurovanÃ©mu maximu na zboÅ¾Ã­) vyÅ¾adovanÃ© pÅ™ed prodejem produktu nebo zboÅ¾Ã­. ZboÅ¾Ã­ pod touto hranicÃ­ je pÅ™eskoÄeno. 0 = bez minima.</t>
    <t id="3107">ZaÅ™azenÃ­ do fronty pro vÃ­ce obchodÅ¯: %1. MÄ›l bych vydÄ›lat %2 zisku.</t>
    <t id="3108">Prodej %1 %2 z %3 za %4. MÄ›l bych vydÄ›lat %5 zisku.</t>
    <t id="3110">ZaÅ™azenÃ­ zÃ¡sobovacÃ­ho letu pro %1 %2. NÃ¡kup za %3 z %4, dodÃ¡nÃ­ do %5. HornÃ­ hranice nÃ¡kupu zÃ¡kaznÃ­ka %6 - %7/jednotka pod limitem (%8 celkem).</t>
    <t id="3111">ZaÅ™azenÃ­ zÃ¡sobovacÃ­ho letu pro %1 %2 z %3 do %4.</t>
    <t id="3112">ZÃ¡sobovÃ¡nÃ­ ve frontÄ› (%1 ÃºsekÅ¯): %2. Celkem %3 pod hornÃ­ hranicÃ­ nÃ¡kupu zÃ¡kaznÃ­ka.</t>
    <t id="3113">Station Trader: ZaÅ™azovÃ¡nÃ­ exportnÃ­ho multitrade: %1. OÄekÃ¡vanÃ½ zisk %2.</t>
    <t id="31029">Probe Stock Target</t>
    <t id="31030">TÄ›Å¾ebnÃ­ drony k nÃ¡kupu</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: nejsou k dispozici tÄ›Å¾itelnÃ© suroviny. LoÄ %1 [%2], Flotila: %3</t>
    <t id="31201">Galaxy-Miner: nastavte domovskou stanici nebo domovskou pozici.</t>
    <t id="31130">Kolik sbÄ›rnÃ½ch (tÄ›Å¾ebnÃ­ch) dronÅ¯ tÄ›Å¾aÅ™ koupÃ­, kdyÅ¾ mu dojde potÅ™ebnÃ½ typ (pevnÃ½/ruda nebo kapalnÃ½/plyn). NÃ¡kup se spustÃ­ POUZE tehdy, kdyÅ¾ loÄ nemÃ¡ Å¾Ã¡dnÃ© sbÄ›raÄe danÃ©ho typu - tÄ›Å¾aÅ™, kterÃ½ stÃ¡le mÃ¡ alespoÅˆ jeden, se nikdy nedoplÅˆuje ani znovu nekupuje a stÃ¡vajÃ­cÃ­ drony zÅ¯stÃ¡vajÃ­ zachovÃ¡ny. Omezeno kapacitou jednotkovÃ©ho hangÃ¡ru lodi. Nastavte na 0 pro vypnutÃ­ automatickÃ©ho nÃ¡kupu sbÄ›rnÃ½ch dronÅ¯ a ruÄnÃ­ sprÃ¡vu dronÅ¯. VÃ½chozÃ­ hodnota 5 je plnÃ¡ sada dronÅ¯ pro normÃ¡lnÃ­ rychlost tÄ›Å¾by.</t>
    <t id="31129">PoÄet sond zdrojÅ¯, kterÃ© si tÄ›Å¾aÅ™ koupÃ­ za cestu doplnÄ›nÃ­ zÃ¡sob. NÃ¡kup se spustÃ­ POUZE, kdyÅ¾ lodi dojdou sondy (poÄet = 0), ne pÅ™i kaÅ¾dÃ©m nasazenÃ­ - tak tÄ›Å¾aÅ™ projde celou zÃ¡tÄ›Å¾ sondou mezi spuÅ¡tÄ›nÃ­mi zÃ¡sobovÃ¡nÃ­ mÃ­sto toho, aby po kaÅ¾dÃ©m nasazenÃ­ obchÃ¡zel. LimitovÃ¡no celkovou vyuÅ¾itelnou kapacitou lodi (sdÃ­lenou se satelity/minami/atd.); hodnota posuvnÃ­ku vÄ›tÅ¡Ã­ neÅ¾ volnÃ½ rozmÃ­stitelnÃ½ prostor se elegantnÄ› degraduje, aby â€žvyplnil, co se hodÃ­â€œ. ProjevÃ­ se pouze tehdy, kdyÅ¾ je povoleno automatickÃ© nasazovÃ¡nÃ­ sond zdrojÅ¯ - stejnÃ© nastavenÃ­ takÃ© Å™Ã­dÃ­ pÅ™Ã­leÅ¾itostnÃ© nasazenÃ­ sond v tÄ›Å¾ebnÃ­ch sektorech a shromaÅ¾ÄovÃ¡nÃ­ zastaralÃ½ch sond (sondy v sektorech bez zdrojÅ¯ relevantnÃ­ch pro koÅ¡).</t>
    <t id="3226">Veliteli %1,\n\nZakotvil jsem na %2 a registrÃ¡tor Trading Academy potvrdil mou registraci do programu â€ž%3â€œ. Z ÃºÄtu flotily bylo strÅ¾eno %4 Cr za Å¡kolnÃ© kurzu a tuto investici neberu na lehkou vÃ¡hu.\n\nToto nenÃ­ Å¾Ã¡dnÃ¡ rutinnÃ­ certifikace. InstruktoÅ™i akademie jsou zkuÅ¡enÃ­ obchodnÃ­ci a vyjednavaÄi konsorcia a uÄebnÃ­ plÃ¡n je zde mnohem nÃ¡roÄnÄ›jÅ¡Ã­ neÅ¾ standardnÃ­ postupovÃ¡ zkouÅ¡ka. BÄ›hem nÃ¡sledujÃ­cÃ­ch %5 minut podstoupÃ­m intenzivnÃ­ vÃ½uku pokroÄilÃ½ch obchodnÃ­ch protokolÅ¯, analÃ½zy trhu pod tlakem a taktiky vyjednÃ¡vÃ¡nÃ­, kterÃ© oddÄ›lujÃ­ uÄnÄ› od mistrÅ¯.\n\nAÅ¾ bude zÃ¡vÄ›reÄnÃ¡ zkouÅ¡ka dokonÄena a jÃ¡ se odpojÃ­m, budu drÅ¾et titul â€ž%3â€œ a vÅ¡e, co jsem se nauÄil, pÅ™inesu zpÄ›t do naÅ¡ich obchodnÃ­ch operacÃ­. NepromarnÃ­m jedinÃ½ kredit tÃ©to pÅ™Ã­leÅ¾itosti.\n\nS vdÄ›ÄnostÃ­ a odhodlÃ¡nÃ­m\n%6\nNa palubÄ› %7</t>
    <t id="9924">Kurz Trading Academy byl pÅ™eruÅ¡en: pilotnÃ­ %1 si nemÅ¯Å¾e dovolit poplatek %2 Cr v doku akademie (mÃ­t %3 Cr). Kurz zruÅ¡en, pilot pokraÄuje v obchodovÃ¡nÃ­.</t>
  </page>
</language>
<?xml version="1.0" encoding="utf-8"?>
<language id="44">
  
  <!-- GalaxyTrader MK3 AI Order -->
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <!-- Order Names -->
    <t id="10001">Dock and Wait (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">Final Examination (GalaxyTrader MK3)</t>
    <t id="10004">Pilot Exchange Rendezvous</t>
    <t id="10005">[DEPRECATED] GalaxyTrader MK4 Supply (Legacy)</t>
    <t id="10006">Return Home</t>
    <t id="10007">GalaxyTrader MK4-2 Supply</t>
    
    <!-- Order Descriptions -->
    <t id="10101">Dock at station and wait for specified duration</t>
    <t id="10102">Autonomous trading with skill progression</t>
    <t id="10103">Take final examination for pilot certification at training facility</t>
    <t id="10104">Dock at rendezvous station for pilot exchange</t>
    <t id="10105">Supply-focused trading for player stations using cache and live search (Legacy)</t>
    <t id="10106">Dock at home station and remain there until trading resumes</t>
    <t id="10107">Player supply order with delivery-target priority sliders</t>
    
    <!-- Trade Order Names -->
    <t id="10201">Buy %s from %s</t>
    <t id="10202">Sell %s to %s</t>
    <t id="10203">Trade with %s</t>
    <t id="1000">{77000,10002}</t>
    <t id="1001">Advanced trading system with XP progression and fleet coordination</t>
    <t id="1002">Home Base</t>
    <t id="1003">Use presets</t>
    <t id="1004">Trade all wares</t>
    <t id="1005">Trade legal wares</t>
    <t id="1006">Trade illegal wares</t>
    <t id="1007">Enable XP progression</t>
    <t id="1008">Enable fleet coordination</t>
    <t id="1009">Enable market analysis</t>
    <t id="1010">Enable territory management</t>
    
    <!-- Order Parameter Names -->
    <t id="1011">Allow Illegal Wares</t>
    <t id="1012">Logbook Entries</t>
    <t id="1013">Risk Tolerance</t>
    <t id="1014">Prioritize Player Stations</t>
    <t id="1015">Auto Wares</t>
    <t id="1016">Distance Penalty %</t>
    <t id="1017">Notification Level</t>
    <t id="1018">Fleet Coordination</t>
    <t id="1019">Cargo Fill Target %</t>
    <t id="1050">Market Update Frequency</t>
    <t id="1051">Trade Evaluation Logging</t>
    <t id="1052">Sector Whitelist</t>
    <t id="1054">Ignore Carrier/Aux Ships</t>
    <t id="1056">Ignore Build Storage</t>
    <t id="1058">Ignore Trade Rules</t>
    <t id="1060">Ignore MK1-Supplied Stations</t>
    <t id="1063">Under development</t>
    <t id="1064">Priority Wares</t>
    <t id="1065">Priority Score %</t>
    <t id="1066">Wares to favor in trade scoring. Their score is multiplied by Priority Score %.</t>
    <t id="1067">Score multiplier for Priority Wares: 125%=+25% min, 150%=+50%%, 200%=2x, 300%=3x. Applied last.</t>
    <t id="1068">â”€â”€ Priority Ware Filter â”€â”€</t>
    <t id="1069">Wares (Manual)</t>
    <t id="1070">Illegal Route Filter</t>
    <t id="1072">Serve Home Only</t>
    <t id="1073">Player Supplier Priority</t>
    <t id="1074">Faction Supplier Priority</t>
    <t id="1075">Include Build Storage</t>
    <t id="1076">Include Resources</t>
    <t id="1077">Include Intermediates</t>
    <t id="1078">Include Tradewares</t>
    <t id="1080">Max Trades per Cycle</t>
    <t id="1081">Backtrack Tolerance</t>
    <t id="1082">Min Cargo Used %</t>
    <t id="1083">Player Buy Modifier %</t>
    <t id="1085">Assign to Home Station</t>
    <t id="1086">Coverage Distance</t>
    <t id="1088">Maximum jump distance from home for demand coverage</t>
    <t id="1090">Include tradeware-class wares in demand/supply matching</t>
    <t id="1091">Modifier applied to player-owned supplier pricing in scoring-only calculations</t>
    <t id="1092">Ignore Player Pricing</t>
    <t id="1093">When enabled: always buy from player-owned stations regardless of their set sell prices, and only sell to NPC factions. Useful for liquidating excess stock from your own stations.</t>
    <t id="1094">Blocked Stations</t>
    <t id="1095">Stations selected here are excluded from MK3 trading. The trader will neither buy from nor sell to them.</t>
    <t id="1096">Idle Parking</t>
    <t id="1097">When enabled, ships that repeatedly fail to find work park at their home station or home sector. Sector parking prefers player stations, then friendly stations. Dock release time is set in Global Settings (0 = stay docked until work is found).</t>
    <t id="1098">Autoscale</t>
    <t id="1099">When enabled, jump-distance sliders are set to the pilot's maximum allowed range after mandatory training or Trading Academy completion. Untick to set distances manually.</t>
    <t id="11001">Build Storage Priority</t>
    <t id="11002">Stations Priority</t>
    <t id="11003">Aux Ships Priority</t>
    <t id="11004">Carrier Ships Priority</t>
    <t id="11005">0 = disabled. 1-10 = score multiplier (10 = strongest bias). Final score = supply score Ã— multiplier.</t>
    <t id="11006">1 = no extra score (priority ware list unchanged). 2-10 = add (multiplierâˆ’1)Ã— base supply score when the trade ware is in the priority list. Applied on top of the type score.</t>
    <t id="11007">Priority Ware Bonus</t>
    <t id="11008">%1: All delivery-target priority sliders are set to 0 - this order has no delivery targets. Enable at least one class (Build Storage, Stations, Aux Ships, or Carriers) to resume supply runs.</t>
    
    <!-- Ship Name Status Prefixes -->
    <t id="7001">[ADVANCE]</t>
    <t id="7002">[TRAINING]</t>
    <t id="7008">[FALLBACK]</t>
    <t id="7009">[ISOLATED]</t>
    
    <!-- Ship Name Operational State Prefixes -->
    <t id="7003">[REPAIR]</t>
    <t id="7004">[RESUPPLY]</t>
    <t id="7005">[MAINTENANCE]</t>
    <t id="7006">[REROUTE]</t>
    <t id="7007">[CLEARANCE]</t>
    
    <!-- Parameter Tooltips -->
    <t id="1020">Choose home sector or station where trader operates</t>
    <t id="1021">Maximum jump gate distance when buying wares (limited by pilot skill)</t>
    <t id="1022">Maximum jump gate distance when selling wares (limited by pilot skill)</t>
    <t id="1023">Automatic selection of suitable wares based on category</t>
    <t id="1024">Manual selection of specific trading wares</t>
    <t id="1025">Allow trading in contraband and illegal goods</t>
    <t id="1026">Security tolerance: 0.0=Only safe sectors, 1.0=Accept all risks</t>
    <t id="1027">Improve pilot skills through trading experience</t>
    <t id="1028">Automatically send pilots for training when needed</t>
    <t id="1029">Coordinate multiple trading ships to avoid conflicts</t>
    <t id="1030">Ware focus: 0=Balanced, 1=Advanced, 2=Basic needs, 3=Illegal, 4=Bulk goods</t>
    <t id="1031">Trading area: 0=Balanced, 1=Home focus, 2=Free roam</t>
    <t id="1032">Notification level: 0=Minimal, 1=Normal, 2=Detailed messages</t>
    <t id="1033">Target cargo utilization percentage before prioritizing sales</t>
    <t id="1034">How often market data and price information is updated</t>
    <t id="1035">Debug output level: 0=None, 1=Basic, 2=Verbose logging</t>
    <t id="1036">Share profitable trade routes with fleet (cached for quick access)</t>
    <t id="1037">Minimum profit required to cache trade and share with fleet</t>
    <t id="1038">Maximum profit decline allowed before cached trade routes become invalid</t>
    <t id="1039">How long cached trade routes remain valid before expiring</t>
    <t id="1040">Enable detailed logging of individual trade evaluations and rejections (can be very verbose)</t>
    <t id="1041">Enable per-trade logbook entries and immersive training messages (TaterTrader style)</t>
    <t id="1053">Sectors in this list are excluded from blacklists (always allowed)</t>
    <t id="1055">Exclude carriers and auxiliary ships from trading</t>
    <t id="1057">Exclude build storage ships from trading</t>
    <t id="1059">Ignore station trade rules during offer search (advanced; may select offers normally blocked)</t>
    <t id="1061">Skip player stations that have an MK1 trader with Supply mode assigned</t>
    <t id="1062">Boost trade scores for routes involving your own stations (10% score bonus)</t>
    <t id="1071">When Allow Illegal Wares is enabled, only trade illegal wares if legal in all sectors on the jump path (buy, sell, and intermediate sectors).</t>
    <t id="1087">Maximum jump distance from home for supplier purchase search</t>
    <t id="1089">When disabled, ship can supply stations in coverage area by urgency priority instead of home-only mode</t>
    
    <!-- XP and Training Messages -->
    <t id="2000">%s has gained %s XP!</t>
    <t id="2001">%s has leveled up! New level: %s</t>
    <t id="2002">%s needs training! Please send to nearest shipyard or trading station.</t>
    <t id="2003">%s has started training at %s</t>
    <t id="2004">%s has completed training and is now certified for level %s!</t>
    <t id="2005">%s reached Skill Level %s after training! XP progression unlocked at %s.</t>
    <t id="2006">%s reached Skill Level %s from %s trade!</t>
    <t id="2007">%s completed Level %s training! XP progression unlocked at %s.</t>
    
    <!-- Trade Messages -->
    <t id="3000">%s has completed a trade! Profit: %s Cr</t>
    <t id="3001">%s is analyzing market conditions...</t>
    <t id="3002">%s has found a profitable trade route!</t>
    <t id="3003">No profitable trade routes available for %s</t>
    
    <!-- Per-Trade Logbook Messages (TaterTrader style) -->
    <t id="3100">Selling %1 %2 from cargo to %3 at %4. I should earn %5 in profit.</t>
    <t id="3101">Queuing up trade order for %1 %2. Buying at %3 from %4, selling at %5 to %6. I should earn %7 in profit.</t>
    <t id="3102">Station Trader: Supplying %1 %2 from %3 at %5%% to %4 at %6%%.</t>
    <t id="3103">Station Trader: Selling %1 %2 to %3 at %4. Expected profit is %5.</t>
    <t id="3104">Trade completed successfully for %1 %2. Total profit: %3 Credits.</t>
    <t id="3105">Trade route cached: %1 %2 from %3 to %4 (Profit: %5 Cr)</t>
    <t id="3106">\nTotal estimated lifetime profit before this trade: %1 Cr.</t>
    <t id="3107">Queuing up multitrade: %1. I should earn %2 in profit.</t>
    <t id="3108">Selling %1 %2 from %3 at %4. I should earn %5 in profit.</t>
    <t id="3110">Queuing supply run for %1 %2. Sourcing at %3 from %4, delivering to %5. Customer buy cap %6 - %7/unit under cap (%8 total).</t>
    <t id="3111">Queuing supply run for %1 %2 from %3 to %4.</t>
    <t id="3112">Queuing supply run (%1 legs): %2. Total %3 under customer buy cap.</t>
    <t id="3113">Station Trader: Queuing export multitrade: %1. Expected profit %2.</t>
    <t id="3120">Pilot Transfer Initiated</t>
    <t id="3121">Transfer protocol acknowledged. %1 (%2) and %3 (%4) are proceeding to %5 (%6) to dock and exchange command seats.</t>
    
    <!-- Training Messages (Immersive/Roleplay Style) -->
    <t id="3200">Hello Commander %1,\n\nI have gained enough experience to take my certification exam for the title "%2". The examination will take approximately %3 minutes at %4.\n\nThis is an important milestone in my career development. The exam will test my knowledge of advanced trading protocols, market analysis, and fleet coordination procedures.\n\nI'm confident in my abilities and excited to prove myself worthy of this advancement. Wish me luck!\n\nRespectfully,\n%5\nAboard %6</t>
    <t id="3201">Commander %1,\n\nExcellent news! I have successfully completed my certification examination and earned the title "%2"!\n\nThe examination covered advanced trading strategies, risk assessment protocols, and fleet coordination procedures. I'm pleased to report that I passed with distinction.\n\nI'm now qualified to handle more complex trading operations and look forward to contributing even more to our fleet's success. Thank you for investing in my professional development.\n\nWith renewed dedication,\n%3\nCertified %2\nAboard %4</t>
    <t id="3202">Commander %1,\n\nI regret to inform you that my certification exam was interrupted due to operational requirements. I will need to reschedule when circumstances permit.\n\nI remain committed to advancing my skills and will notify you when I can resume the examination process.\n\nRespectfully,\n%2\nAboard %3</t>
    <t id="3203">Commander %1,\n\nI am currently en route to %2 for my certification examination. The journey gives me time to review my studies and prepare mentally for this important step in my career.\n\nExpected arrival: %3 minutes\nExamination duration: %4 minutes\n\nI appreciate your confidence in my abilities and the opportunity for advancement.\n\nWith determination,\n%5\nAboard %6</t>
    
    <!-- Cargo Safety and Maintenance Messages (Roleplay Style) -->
    <t id="3204">Commander,\n\nI've detected cargo in my hold during my systems check. Before I can begin normal trading operations, I need to sell this merchandise.\n\nI'm using our trade search to find the best buyer and safely offload this cargo. Once my hold is clear, I'll proceed with automated trading.\n\nStatus: Searching for optimal sale location\n\nWith diligence,\nAboard %1</t>
    <t id="3205">Commander,\n\nMy hull integrity has dropped to %1%% (threshold: %2%%). As a Level %3 pilot, I'm authorized to request auto-repair services.\n\nI'm proceeding to %4 for repair work. The estimated cost is %5 Cr, which is within our budget.\n\nOnce repairs are complete, I'll resume trading operations with full structural integrity.\n\nRespectfully,\nAboard %6</t>
    <t id="3206">Commander,\n\nURGENT FINANCIAL WARNING\n\nMy hull integrity is critical at %1%% (threshold: %2%%), but our available funds (%3 Cr) are insufficient for full repairs (estimated cost: %4 Cr).\n\nI'm proceeding to %5 for PARTIAL REPAIRS using our available funds. This isn't an ideal solution, but it's necessary to maintain operational capability.\n\nPlease consider allocating additional funds for future maintenance operations.\n\nConcerned but determined,\nAboard %6</t>
    <t id="3207">Commander,\n\nMy Level %1 certification authorizes automatic resupply of defensive equipment. After checking my systems, I've determined that my countermeasures and deployables are below recommended thresholds.\n\nI'm proceeding to %2 to restock my defensive equipment:\nâ€¢ Countermeasures: Replenishing to optimal capacity\nâ€¢ Defense drones, trade drones, laser towers: Applying balance profile\n\nThis resupply ensures I'm best protected against space threats while maintaining trading efficiency.\n\nWith vigilance,\nAboard %3</t>
    <t id="3212">Commander,\n\nMy hull integrity has dropped to %1%% (threshold: %2%%), and I need repair services. However, the nearest repair station at %3 is currently unreachable due to sector travel restrictions (blacklisted routes).\n\nI will continue with trading operations despite this limitation. Once safe routes become available again, I will automatically seek repair services.\n\nI will monitor the situation and notify you when repairs become possible.\n\nRespectfully,\nAboard %4</t>
    <t id="3213">Commander,\n\nMy defensive equipment requires resupply, but the nearest equipment station at %1 is currently unreachable due to sector travel restrictions (blacklisted routes).\n\nI will continue with trading operations despite this limitation. Once safe routes become available again, I will automatically seek resupply services.\n\nI will monitor the situation and notify you when resupply becomes possible.\n\nRespectfully,\nAboard %2</t>
    <t id="3208">Commander,\n\nI've completed an exhaustive market analysis of %1 and surrounding sectors (within %2 jumps, minimum profit threshold: %3 Cr), but unfortunately found no profitable trading opportunities that meet our requirements.\n\nTRADE ANALYSIS REPORT:\nTotal opportunities evaluated: %4\n\nREJECTION BREAKDOWN:\n- Docking restrictions: %5 trades\n  (Station doesn't permit my ship class)\n- Insufficient profitability: %6 trades\n  (Below minimum profit threshold)\n- Insufficient volume: %7 trades\n  (Zero or negative tradeable amount)\n- Safety restrictions: %8 trades\n  (Blacklisted stations or dangerous sectors)\n\nRECOMMENDATIONS:\n- Consider adjusting profit thresholds\n- Expand maximum trading distance\n- Review sector blacklist settings\n- Wait for market conditions to improve\n\nI'll continue monitoring the market and will notify you when profitable opportunities become available.\n\nStanding by,\nAt your service</t>
    <t id="3209">Commander,\n\nURGENT ROUTE ALERT\n\nMy threat intelligence system has detected that sector %1 (threat level %2) is now in my planned trade route. For the safety of the ship and crew, I am immediately aborting the current trade operation.\n\nACTIONS TAKEN:\n- All trade orders cancelled\n- Returning to safe operations mode\n- Will find alternative trade route that avoids dangerous sectors\n- Cargo handling: Automatic (will sell any cargo at safe location if needed)\n\nThe dynamic blacklist system will prevent future trades through this sector until the threat is cleared.\n\nSafety is my first priority.\n\nWith vigilance,\nAboard %3</t>
    <t id="3210">Commander,\n\nESCAPE ROUTE INITIATED\n\nI'm currently in blacklisted sector %1 and have found a trade route that will allow me to escape safely.\n\nTRADE ROUTE:\nBuy: %2 (Sector: %3)\nSell: %4 (Sector: %5)\nWare: %6 (x%7)\nExpected Profit: %8 Cr\n\nThe ship will escape the blacklisted sector after completing this trade.\n\nRespectfully,\nAt your service</t>
    <t id="3211">Commander,\n\nISOLATED TRADING MODE\n\nI'm currently in sector %2, but all routes to other sectors are blocked by blacklisted hub sectors. This means I can only trade within my current sector until the blacklist situation changes.\n\nSITUATION:\nCurrent Sector: %2\nStatus: Isolated (non-blacklisted sector with blocked routes)\nTrading Mode: Intra-sector trades only\n\nMy trading system has automatically adjusted profit thresholds to prioritize available intra-sector trading opportunities.\n\nI will continue monitoring the situation and notify you if routes become available again.\n\nRespectfully,\nAboard %1</t>
    <t id="3218">Commander,\n\nROUTE PATH CHANGE DETECTED\n\nUpon entering sector %1, my navigation system detected that the route to my destination %2 (%3) has changed.\n\nPATH ANALYSIS:\n- Normal distance: %4 jumps\n- Blacklist-aware distance: %5\n- Status: %6\n\nMy navigation computer indicates that the preferred route is no longer viable due to sector travel restrictions. For the safety of the ship and crew, I am immediately aborting the current trade operation.\n\nACTIONS TAKEN:\n- All trade orders cancelled\n- Returning to safe operations mode\n- Will find alternative trade route that avoids blocked sectors\n- Cargo handling: Automatic (will sell any cargo at safe location if needed)\n\nMy navigation system will automatically avoid blocked sectors in future route planning.\n\nSafety is my first priority.\n\nWith vigilance,\nAboard %7</t>
    <t id="3219">Sector %1 cleared - All threats eliminated</t>
    <t id="3220">Commander,\n\nENEMY SHIP ESCAPED\n\nOur threat intelligence system has lost track of enemy ship %3, which has escaped from blacklisted sector %1.\n\nDETAILS:\n- Escaped Ship: %3\n- Sector Left: %1\n- Destination Sector: %2\n- Status: Tracking lost - ship has left our monitored area\n\nWhile this ship is no longer a threat in sector %1, we have lost visual contact and cannot confirm its current status or intentions in sector %2.\n\nOur tracking systems will continue monitoring sector %1 for remaining threats. If all tracked enemies leave or are eliminated, the sector will be automatically cleared from the blacklist.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3221">Commander,\n\nI was unable to find profitable trading opportunities at greater distances (up to %3 jumps) because these routes are currently unreachable due to sector travel restrictions (blacklisted paths).\n\nSITUATION:\nCurrent Sector: %2\nOriginal Search Range: %3 jumps\nFallback Search Range: %4 jumps\n\nI will now focus my search on nearby sectors within %4 jumps, where routes are more likely to be accessible. This should help me find profitable trades that were previously filtered out due to distance restrictions rather than actual unprofitability.\n\nI'll notify you when I find suitable trading opportunities in the nearby area.\n\nRespectfully,\nAboard %1</t>
    <t id="3222">Commander,\n\nSECTOR BLACKLISTED\n\nOur threat intelligence system has detected hostile activity in sector %1 and has automatically blacklisted this sector to protect our trading operations.\n\nDETECTED ENEMY SHIPS:\n%2\n\nDETECTED BY: %3\n\nFor the safety of our ships and crew, all trading routes through this sector have been blocked. Our ships will automatically route around this sector until the threat is eliminated.\n\nThe sector will be automatically cleared from the blacklist once all tracked enemy ships are eliminated or leave the area.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3223">Commander,\n\nI cannot find an accessible training station for my Level %1 advancement exam. I will proceed with trading operations as instructed, but I understand that I will not gain experience points until I can complete the required training. After this trade run, I will search again for any possible opportunity to train.\n\nRespectfully,\nAboard %2</t>
    <t id="3224">Training license fee: %1 Cr</t>
    <t id="3225">Bonus: I gained %1 additional skill level%2 from accumulated experience during training! Current level: %3</t>
    <t id="3226">Commander %1,\n\nI have docked at %2 and the Trading Academy registrar has confirmed my enrollment in the "%3" program. The fleet account has been debited %4 Cr for the course tuition, and I do not take that investment lightly.\n\nThis is no routine certification. The academy's instructors are veteran merchants and consortium negotiators, and the curriculum here is far more demanding than the standard advancement exam. Over the next %5 minutes I will undergo intensive instruction in advanced trading protocols, market analysis under pressure, and the negotiation tactics that separate apprentices from masters.\n\nWhen the final examination is complete and I undock, I will hold the title of "%3" and bring everything I have learned back to our trading operations. I will not waste a single credit of this opportunity.\n\nWith gratitude and resolve,\n%6\nAboard %7</t>
    
    <!-- Pilot Lifecycle Messages (Roleplay Style) -->
    <t id="3214">It is an honor to work for you, %1! I am excited to begin my trading career under your command. I will do my best to serve you well and contribute to your success.</t>
    <t id="3215">Thank you for giving me this well-deserved holiday, %1! I have enjoyed my time away from trading and my skills remain intact. I am looking forward to returning to work whenever you need me. Until then, I will keep my trading knowledge sharp!</t>
    <t id="3216">I am back from holiday and ready to work again, %1! My trading skills remain sharp and I am eager to continue serving you on %2. Thank you for the well-deserved rest!</t>
    <t id="3217">Thank you for my transfer to %1, %2! I am honored by this new assignment and will take excellent care of my new ship. My trading experience and skills remain intact, and I am ready to continue serving you.</t>
    <t id="3227">Hull Lost, Dignity Pending Pickup</t>
    <t id="3228">Commander %1,\n\n%2 reporting from %3. My ship exploded. I did not. I am now the fleet's most expensive floating cargo.\n\nMap marker attached. Please hurry - I was mid-invoice.\n\nFloating professionally,\n%2</t>
    <t id="3229">Pilot Retrieved - Oxygen Addiction Cured</t>
    <t id="3230">Commander %1,\n\nFleet update: %2 has been scooped up by %3 (%4) and has stopped billing you for extended EVA training.\n\nRegistry rebind in progress. Recommend no questions about what happened to the old ship.\n\nSheepishly yours,\n%2</t>
<!-- Fleet Messages -->
    <t id="4000">Fleet coordination: %s has been assigned route %s</t>
    <t id="4001">Fleet coordination: Route %s is fully utilized</t>
    <t id="4002">Fleet coordination: %s has released route %s</t>
    
    <!-- Territory Messages -->
    <t id="5000">%s has been assigned as primary territory for %s</t>
    <t id="5001">%s has reached expertise level %s in %s!</t>
    <t id="5002">Territory bonus applied: %s%% profit increase in %s</t>
    
    <!-- Error Messages -->
    <t id="9500">Error: %s is stuck and needs assistance!</t>
    <t id="9501">Error: Trade failed for %s</t>
    <t id="9502">Error: Cannot register %s with GalaxyTrader MK3</t>
    
    <!-- Ware Filter Messages -->
    <t id="80001">Ware %s added to blacklist</t>
    <t id="80002">Ware %s removed from blacklist</t>
    <t id="80003">Ware %s added to whitelist</t>
    <t id="80004">Automatically blacklisted (poor performance): %s</t>
    <t id="80005">Dangerous ware prioritized: %s</t>
    <t id="80006">Ware filter: %s active, %s trading blocked</t>
    <t id="80007">All ware filters cleared</t>
    <t id="80008">Ware filters reset to default</t>
    <t id="80009">Ware Filter Management</t>
    <t id="80010">Blocked Wares</t>
    <t id="80011">Allowed Wares</t>
    <t id="80012">Dangerous Ware Handling</t>
    <t id="80013">Minimum Ware Value</t>
    <t id="80014">Maximum Ware Value</t>
    <t id="80015">Restricted Factions</t>
    <t id="80016">Ware categories updated from current game state</t>
    <t id="80017">%s wares categorized: %s low-value, %s dangerous, %s high-value</t>
    <t id="80018">Dynamic ware categorization enabled</t>
    <t id="80019">Auto-blacklisting for category %s disabled</t>
    <t id="80020">New wares from other mods detected and categorized</t>
    
    <!-- Global Settings UI -->
    <t id="9000">GalaxyTrader - Global Settings</t>
    <t id="9010">XP and Training System</t>
    <t id="9012">Automatic Training</t>
    <t id="9013">XP Multiplier</t>
    <t id="9015">Commander Bonus Percent</t>
    <t id="9020">Fleet Coordination</t>
    <t id="9021">Enable Fleet Coordination</t>
    <t id="9023">Enable Trade Cache</t>
    <t id="9030">Notifications</t>
    <t id="9031">Notification Level</t>
    <t id="9040">Auto-Repair System</t>
    <t id="9041">Enable Auto-Repair</t>
    <t id="9042">Hull Repair Threshold</t>
    <t id="9310">Galaxy Miner</t>
    <t id="9311">Resource Probe Sector Scan Wait</t>
    <t id="9312">Ship Proximity Weight</t>
    <t id="9043">Minimum Pilot Level</t>
    
    <!-- Trading Price Ranges Settings -->
    <t id="9004">Trading Price Ranges</t>
    <t id="9005">Sell Offer Price Max</t>
    <t id="9006">Buy Offer Price Min</t>
    <t id="9007">Isolated: Sell Price Max</t>
    <t id="9008">Isolated: Buy Price Min</t>
    <t id="9009">Fallback: Sell Price Max</t>
    <t id="9014">Fallback: Buy Price Min</t>
    <t id="9016">Profit Threshold Base</t>
    <t id="9025">Min Player Money</t>
    <t id="9024">Cache Dropoff Tolerance</t>
    <t id="9026">Idle Parking Release Time</t>
    <t id="9054">Block Enemy Faction Sectors</t>
    <t id="9055">Blacklist Threat Level</t>
    <t id="9056">Recreate Blacklist</t>
    <t id="9057">Recreate</t>
    <t id="9058">Assign to GT ships</t>
    <t id="9059">Assign</t>
    
    <!-- Global Settings Tooltips -->
    <t id="9112">Automatically sends pilots for training when they reach required levels. Disable to manually control training timing.</t>
    <t id="9113">Adjusts how fast pilots gain experience. Higher values mean faster progression.</t>
    <t id="9115">Percentage of subordinate XP awarded to commander pilots. Set to 0% to disable commander bonus XP. Default: 10%.</t>
    <t id="9121">Enables intelligent fleet coordination features including route optimization and load balancing.</t>
    <t id="9123">Allows sharing profitable trade opportunities between fleet members for better coordination.</t>
    <t id="9131">Controls how many notifications are shown: 0=Quiet, 1=Important only, 2=All notifications</t>
    <t id="9141">Automatically sends ships for repairs after completing trades when hull falls below threshold. Only for experienced pilots (Level 12+). Ships choose appropriate facility: S/M Equipment Dock, L/XL Shipyard.</t>
    <t id="9142">Hull percentage below which auto-repair is triggered. Default: 95%. Ships will automatically go to nearest repair facility when damaged.</t>
    <t id="9411">When enabled, miners wait while evaluating faction resource probes in the sector (+5s per probe above one). GT pilot level scales that wait linearly from full time at level 1 to 5 seconds at level 15 (GT XP mode only, when wait exceeds 5 seconds). When disabled, no wait is applied (vanilla behavior).</t>
    <t id="9412">Nudge MK3/MK4 ships toward nearer buy stations when sorting validated trades. Selection score = trade score / (1 + shipâ†’buy jumps Ã— weight). Slider 0-100 (0 = off; 4 = default 0.04). Does not affect cache ranking or territorial range limits.</t>
    <t id="9143">Minimum pilot level required for auto-repair feature. Default: 12 (experienced traders). Lower level pilots must repair manually.</t>
    <t id="9104">Maximum relative price for sell offers (ship buys FROM stations). Range: -1.0 to +1.0. Default: 0.5 (50% above average). Higher = more expensive but more options.</t>
    <t id="9105">Minimum relative price for buy offers (ship sells TO stations). Range: -1.0 to +1.0. Default: -0.5 (50% below average). Lower = cheaper buyers but more options.</t>
    <t id="9106">Sell price max for isolated ships (stuck in single sector). Range: -1.0 to +1.0. Default: 0.5.</t>
    <t id="9107">Buy price min for isolated ships (stuck in single sector). Range: -1.0 to +1.0. Default: -0.5.</t>
    <t id="9108">Sell price max for fallback search (last resort when normal search fails). Range: -1.0 to +1.0. Default: 0.5. Fallback search uses MaxDistance=2 and relaxed profit thresholds.</t>
    <t id="9109">Buy price min for fallback search (last resort when normal search fails). Range: -1.0 to +1.0. Default: -0.5. Fallback search uses MaxDistance=2 and relaxed profit thresholds.</t>
    <t id="9116">Base minimum profit at Level 15 for a medium trader (reference cargo 8200). Actual MinAbsoluteProfit is computed per pilot + scaled by cargo:\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(scaled, 25% of base(L))\n\nSet to 0 to accept any profit (only ROI/distance/other filters apply).</t>
    <t id="9125">Minimum player money (credits) required before ships will search for trades. When player money falls below this threshold, all ships skip trade searches and wait, preventing expensive cache scanning that causes game stutter. Range: 1,000 - 100,000 Cr. Default: 1,000 Cr.</t>
    <t id="9124">Maximum percentage ROI drop from cached value before rejecting trade. Example: 20% cached ROI with 15% tolerance accepts down to 17% ROI (14% drop).</t>
    <t id="9126">Minutes docked before undocking to free the port (0-60). 0 = stay docked until new work is found. Default: 1 minute.</t>
    <t id="9154">Automatically blacklist all sectors owned by enemy factions (relation checkbox in blacklist)</t>
    <t id="9155">Minimum threat level (1-5) required to blacklist a sector:\n2=Medium (single attack)\n3=Medium-High (hostile factions)\n4=High (capital ships/missiles)\n5=Very High (Xenon/Khaak)</t>
    <t id="9156">Manually recreate the threat avoidance blacklist (useful if it was deleted)</t>
    <t id="9157">Manually assign the current dynamic blacklist to all GT fleet commander ships. Subordinates inherit from their commander.</t>
    
    <!-- Trader Titles (English) -->
    <t id="6001">Apprentice</t>
    <t id="6002">Courier</t>
    <t id="6003">Supplier</t>
    <t id="6004">Trader</t>
    <t id="6005">Merchant</t>
    <t id="6006">Long-Distance Merchant</t>
    
    <!-- Defensive Equipment Balance Profiles -->
    <t id="6101">Balanced</t>
    <t id="6102">Defensive</t>
    <t id="6103">Trading-Focused</t>
    <t id="6104">Heavy Defense</t>
    <t id="6105">Tower Support</t>
    
    <!-- Threat Avoidance System Settings -->
    <t id="9050">Threat Avoidance System</t>
    <t id="9051">Enable Threat Avoidance:</t>
    <t id="9052">Hostile Relation Threshold:</t>
    <t id="9053">Use Dynamic Blacklist:</t>
    <t id="9151">Level 6+ traders detect hostile ships and avoid dangerous routes. Disabling stops all scanning (improves performance). Risk tolerance per ship in command behavior (0-10 scale).</t>
    <t id="9152">Only flag factions with relation at or below this value as threats. Default: -20%</t>
    <t id="9153">Automatically blacklist dangerous sectors (threat level 3+) to force ships to route around threats. Uses vanilla pathfinding for alternative routes.</t>
    
    <!-- Defensive Equipment Settings -->
    <t id="9060">Defensive Equipment Auto-Replenishment (Level 15)</t>
    <t id="9061">Enable Auto-Replenishment:</t>
    <t id="9062">Restock Countermeasures:</t>
    <t id="9063">Restock Defense Drones:</t>
    <t id="9064">Restock Trade Drones:</t>
    <t id="9065">Restock Laser Towers:</t>
    <t id="9066">Restock Repair Drones:</t>
    <t id="9067">Countermeasure Threshold:</t>
    <t id="9068">Unified Capacity Threshold:</t>
    <t id="9069">Equipment Balance Profile:</t>
    <t id="9161">Master Traders (Level 15) automatically restock defensive equipment after trades. Applies to commander level for subordinates.</t>
    <t id="9162">All ships (S/M/L/XL). Separate capacity. Critical for missile defense.</t>
    <t id="9163">L/XL ships only. Shares unified capacity with other deployables.</t>
    <t id="9164">L/XL ships only. Essential for trading operations. Shares unified capacity.</t>
    <t id="9165">All ships. L/XL ships share unified capacity, S/M use cargo.</t>
    <t id="9166">L/XL ships only. Works with auto-repair system. Shares unified capacity.</t>
    <t id="9167">Restock when countermeasures below this percentage (all ships, separate capacity).</t>
    <t id="9168">Restock when total deployables below this percentage (L/XL ships: drones + towers share one capacity).</t>
    <t id="9169">Distribution of unified capacity (L/XL ships): Trading-Focused (20/50/20/10), Balanced (35/35/20/10), Defensive (50/20/20/10), Heavy Defense (40/30/20/10), Tower Support (30/30/30/10). Ratios: Defense/Trade/Towers/Repair. Click to cycle through options.</t>
    
    <!-- Ship Modifications Settings -->
    <t id="9090">Ship Modifications</t>
    <t id="9091">Enable Ship Modifications</t>
    <t id="9191">Automatically install ship and engine modifications based on pilot level. Level 9+ = Level 1 mods, Level 12+ = Level 2 mods, Level 15+ = Level 3 mods. Only GT-installed mods are removed when order is cancelled.</t>
    
    <!-- Ship Naming Settings -->
    <t id="9070">Ship Naming Configuration</t>
    <t id="9071">Display XP:</t>
    <t id="9072">Display Rank:</t>
    <t id="9073">Display Level:</t>
    <t id="9074">Display Status:</t>
    <t id="9075">Enable Ship Renaming:</t>
    <t id="9076">Prefix</t>
    <t id="9077">Suffix</t>
    <t id="9078">Default Name Source:</t>
    <t id="9079">Model Name</t>
    <t id="9080">Type Name</t>
    <t id="9081">Model Base</t>
    <t id="9083">Custom Name</t>
    <t id="9084">Display Home Sector:</t>
    <t id="9085">Naming Mode:</t>
    <t id="9086">Legacy</t>
    <t id="9087">Pattern</t>
    <t id="9088">Name Pattern:</t>
    <t id="9089">Placeholders: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. Atomic: {RS} {CB} {BL} etc. Uses State Abbreviations below. Empty tokens are omitted; spaces collapse. Max 128 characters.</t>
    <t id="9183">Show the ship's configured home sector in the ship name (prefix or suffix).</t>
    <t id="9184">Custom name format using {TOKEN} placeholders instead of legacy layout toggles. Requires GalaxyTrader XP (not vanilla XP mode).</t>
    <t id="9092">Pattern Placeholders</t>
    <t id="9093">Ship: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT XP: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Home: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Crew: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Sector: {SECTOR} | Stats: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Status tokens:</t>
    <t id="9100">{OPSTATE}: all active operational flags combined (e.g. CB RS, MT)</t>
    <t id="9101">{STATUS}: blocked, training, fallback, or isolated</t>
    <t id="9102">{CB}: custom blacklist only; included in {OPSTATE}; do not combine</t>
    <t id="9082">Display Ship Class:</t>
    <t id="9171">Show XP values in ship names</t>
    <t id="9175">Enable or disable automatic ship renaming with pilot information</t>
    <t id="9172">Show rank titles in ship names</t>
    <t id="9173">Show level numbers in ship names</t>
    <t id="9174">Show trading status in ship names</t>
    <t id="9178">Choose the source for ship base names: Model Name (with variant), Type Name (generic), Model Base (without variant), or Custom Name (stored name)</t>
    <t id="9182">Show ship class (S, M, L, XL) in ship names</t>
    
    <!-- Debug Settings -->
    <t id="9200">Debug Settings</t>
    <t id="9201">Enable Debug Logging:</t>
    <t id="9202">Master toggle for all debug_text output. When disabled, all debug logging is suppressed. When enabled, debug messages appear in the DebugLog based on individual debug_text chance values.</t>
    
    <!-- Maintenance and Diagnostics Settings -->
    <t id="9220">Maintenance &amp; Diagnostics</t>
    <t id="9221">Reset Profit Statistics:</t>
    <t id="9222">RESET</t>
    <t id="9223">Clear All Blacklisted Sectors:</t>
    <t id="9224">CLEAR</t>
    <t id="9225">Reset All Settings to Defaults:</t>
    <t id="9226">RESET ALL</t>
    <t id="9323">Removes all sectors from the threat intelligence blacklist. This will immediately clear all blacklisted sectors and allow your ships to travel to previously blocked areas. Use this if you want to reset the threat avoidance system or if sectors were incorrectly blacklisted.</t>
    <t id="9321">Resets all profit statistics to 0 for all pilots and ships. Use this after upgrading to v0.6.0 to clear inflated revenue-based statistics. The fix now tracks actual PROFIT (revenue - purchase cost). Trade counts and XP are preserved.</t>
    <t id="9325">Resets all global settings to their default values. This includes XP settings, Fleet Coordination, Notifications, Mobile Intel, Threat Avoidance, Ship Naming, Auto-Repair, Modifications, Performance, and Number Format settings. Debug logging setting is preserved to allow logging of the reset operation.</t>
    <t id="9227">Clear Trade Cache for All Home Sectors:</t>
    <t id="9228">CLEAR CACHE</t>
    <t id="9327">Clears the trade cache for all home sectors. This will force all ships to perform fresh live searches on their next trade search. Use this if the cache appears stale or corrupted, or if you want to force a complete cache refresh.</t>
    <t id="9229">Release all search locks</t>
    <t id="9329">Releases ALL in-flight trade-search locks and clears related transient state. Use this if ships are stuck on â€œSearching for tradesâ€ due to stale locks from old saves. This may interrupt legitimate searches.</t>
    <t id="9290">Dump Trade Hub Status:</t>
    <t id="9291">DUMP</t>
    <t id="9390">Shows a one-shot snapshot of the centralized trade hub (scheduler queues + last requesting ship status) in the log and as a notification.</t>
    <t id="9292">Dump Trade Cache (FULL):</t>
    <t id="9293">DUMP CACHE</t>
    <t id="9392">FULL cache dump (can be huge). Writes all cache entries to DebugLog in chunks. Click again to cancel.</t>
    <t id="9294">Clear Fleet Reservations:</t>
    <t id="9295">{77000,9224}</t>
    <t id="9394">Clears all active fleet trade reservations. Use this if ships appear stuck waiting for reserved trades to expire, or if the reservation table has become stale after loading an old save.</t>
    
    <!-- Performance Settings -->
    <t id="9230">Performance</t>
    <t id="9231">Batch Processing Delay:</t>
    <t id="9232">Validation Delay:</t>
    <t id="9233">Max Concurrent Searches:</t>
    <t id="9234">Max Trades To Return:</t>
    <t id="9235">Max Offers Per Ware:</t>
    <t id="9236">Max Trades Per Ware:</t>
    <t id="9237">Max Offers Per Ware For Matching:</t>
    <t id="9238">Early Exit Threshold:</t>
    <t id="9241">Live Offer Slice Interval:</t>
    <t id="9266">Search Lock TTL:</t>
    <t id="9263">Batch Chunk Size:</t>
    <t id="9239">Number Format</t>
    <t id="9240">Format Style:</t>
    <t id="9242">Use M Suffix</t>
    <t id="9243">M Suffix Threshold:</t>
    <t id="9244">German (123.456,78)</t>
    <t id="9245">English (123,456.78)</t>
    <t id="9510">Level-Up Popup Notifications:</t>
    <t id="9511">Training Required Alerts:</t>
    <t id="9512">Training Completed Notifications:</t>
    <t id="9513">Profit Reports:</t>
    <t id="9514">Market Alerts:</t>
    <t id="9515">Fleet Updates:</t>
    <t id="9516">Use vanilla XP only</t>
    <t id="9610">Enable or disable trader level-up popup notifications in the player UI.</t>
    <t id="9611">Alert when pilots need training to advance to the next level.</t>
    <t id="9612">Notify when pilots complete training and advance in rank.</t>
    <t id="9613">Periodic profit summaries (simple and comprehensive reports).</t>
    <t id="9614">Exceptional market opportunities and high-value trade alerts.</t>
    <t id="9615">Fleet coordination messages and status updates.</t>
    <t id="9616">Use pilot.skill.piloting and disable GT XP progression/caps.</t>
    <t id="9246">Simple Report Frequency:</t>
    <t id="9247">Comprehensive Report Frequency:</t>
    <t id="9248">Max Concurrent Cache Searches:</t>
    <t id="9249">Max Concurrent Live Searches:</t>
    <t id="9340">Choose number format: German uses '.' for thousands and ',' for decimals (123.456,78), English uses ',' for thousands and '.' for decimals (123,456.78)</t>
    <t id="9342">Enable M suffix for numbers greater than threshold (e.g., 1.0 M instead of 1,000,000)</t>
    <t id="9343">Threshold for M suffix. Numbers above this value will be displayed with M suffix (default: 999,999)</t>
    <t id="9346">Frequency of simple report (popup notification): 1-30 minutes (default: 1 minute). Use Profit Reports toggle to disable.</t>
    <t id="9347">Frequency of comprehensive report (logbook entry): 1-60 minutes (default: 30 minutes). Use Profit Reports toggle to disable.</t>
    <t id="9398">Use GT Credits Due Override</t>
    <t id="9399">Replace or augment the vanilla "CR due from trades" line with the GT projected value in the same UI slot.</t>
    <t id="9331">Delay between batches during trade search processing (1-500ms). Higher values reduce CPU load but slow down trade searches. Default: 120ms. Used in batch processor and trade list filtering.</t>
    <t id="9332">Delay between trade validations in AI script (1-500ms). Higher values reduce CPU load but slow down trade validation. Default: 50ms. Used when validating trade list from MD system.</t>
    <t id="9333">Maximum number of trade searches that can run simultaneously (1-10). Lower values reduce CPU load but increase queue wait times. Higher values process searches faster but may cause performance spikes. Default: 1.</t>
    <t id="9334">Maximum number of trades to return from cache search (1-100). Higher values provide more trade options but increase cache validation time. Lower values reduce CPU load but may miss viable trades. Default: 20.</t>
    <t id="9335">Maximum number of offers per ware to process in live search (5-100). Higher values consider more offers but increase processing time. Lower values reduce CPU load but may miss profitable trades. Default: 20.</t>
    <t id="9336">Maximum number of trades per ware during batch processing (5-100). Higher values allow more trades per ware but increase processing time. Lower values reduce CPU load but may miss profitable trades. Default: 20.</t>
    <t id="9337">Maximum number of offers per ware for matching in batch processor (5-100). Higher values consider more offers but increase processing time. Lower values reduce CPU load but may miss profitable trades. Default: 20.</t>
    <t id="9338">Early exit threshold for batch processing (100-10000). When this many trades are found, batch processing stops early to save CPU. Higher values process more trades but increase CPU load. Lower values exit sooner but may miss profitable trades. Default: 2000.</t>
    <t id="9341">Live offer slice interval in milliseconds (5-2000ms). Controls how often live offer slices can start. Lower values allow faster offer collection but increase CPU load. Higher values reduce CPU load but slow down live search processing. Default: 500ms.</t>
    <t id="9363">Batch processing chunk size (5-20). Processes chunkSizeÃ—chunkSize combinations per chunk (e.g., 5Ã—5 = 25 combinations). Larger chunks improve throughput but increase CPU load per chunk. Smaller chunks reduce CPU spikes but require more continuations. Default: 5.</t>
    <t id="9348">Maximum number of cache searches that can run simultaneously (1-20). Cache searches are fast and cheap; lower values can reduce burstiness under huge fleets. Default: 2.</t>
    <t id="9349">Maximum number of live searches that can run simultaneously (1-10). Live searches are CPU-intensive, so lower values reduce CPU load but increase queue wait times. Higher values process searches faster but may cause performance spikes. Default: 1.</t>
    <t id="9264">Cache Query Chunk Size:</t>
    <t id="9265">Live Offer Append Chunk Size:</t>
    <t id="9364">Cache entries validated per chunk (10-200). Smaller values spread cache validation across more frames (smoother) but may increase time to find a cached trade. Default: 10.</t>
    <t id="9365">Offers appended per append-slice (50-2000). Smaller values reduce per-frame list-append work (smoother) but may slow live search completion. Default: 200.</t>
    <t id="9366">Search lock time-to-live in seconds (60-7200). If a ship is denied with "trade search already in progress" for longer than this, GT will self-heal by clearing stale search state and releasing the lock. Default: 600s.</t>
    <t id="9370">Batch Backpressure Soft Threshold:</t>
    <t id="9371">Batch Backpressure Hard Threshold:</t>
    <t id="9372">Sectors Per Slice:</t>
    <t id="9373">Home Refresh Cooldown:</t>
    <t id="9374">Cache Miss Cooldown Base:</t>
    <t id="9375">Scheduler Tick Interval:</t>
    <t id="9376">Max Cache Queries Per Tick:</t>
    <t id="9377">Max Search Continuations Per Tick:</t>
    <t id="9378">Max Ships Per Tick:</t>
    <t id="9379">Max Items Per Tick:</t>
    <t id="9380">Max Wake Per Tick:</t>
    <t id="9381">Cache Query Max Entries:</t>
    <t id="9382">Stale Threshold Seconds:</t>
    <t id="9383">Queue Stale Threshold Seconds:</t>
    <t id="9384">Failed Trade Expiration Seconds:</t>
    <t id="9385">Max Concurrent Fallback Searches:</t>
    <t id="9386">{77000,9385}</t>
    <t id="9470">Soft threshold for batch processor backlog (5-50). When backlog reaches this value, backpressure starts being applied to slow down new search requests. Lower values trigger backpressure sooner (more conservative). Default: 10.</t>
    <t id="9471">Hard threshold for batch processor backlog (10-100). When backlog reaches this value, new live searches are blocked until backlog decreases. Lower values block searches sooner (more conservative). Default: 25.</t>
    <t id="9472">Sectors processed per slice in live offer collection (1-5). Smaller values spread work across more frames (smoother) but may slow down offer collection. Larger values process faster but may cause frame spikes. Default: 1.</t>
    <t id="9473">Cooldown after home-sector refresh completes (10-120 seconds). Prevents excessive refresh requests. Lower values allow more frequent refreshes but increase CPU load. Higher values reduce refresh frequency but may delay cache updates. Default: 30s.</t>
    <t id="9474">Base cooldown after cache miss before retrying live search (1-30 seconds). Prevents excessive retry attempts. Lower values retry sooner but increase CPU load. Higher values reduce retry frequency but may delay trade finding. Default: 10s.</t>
    <t id="9475">Interval between scheduler ticks in milliseconds (50-500ms). Controls how often the scheduler processes work queue. Lower values process more frequently but increase CPU load. Higher values reduce CPU load but may increase queue wait times. Default: 100ms.</t>
    <t id="9476">Maximum cache queries started per scheduler tick (1-5). Limits cache query rate to prevent frame blocking. Lower values reduce CPU spikes but slow down cache searches. Higher values process faster but may cause stutter. Default: 1.</t>
    <t id="9477">Maximum search continuations started per scheduler tick (1-5). Limits continuation rate to prevent frame blocking. Lower values reduce CPU spikes but slow down search processing. Higher values process faster but may cause stutter. Default: 1.</t>
    <t id="9478">Maximum ships processed per scheduler tick (1-5). Limits ship processing rate to prevent frame blocking. Lower values reduce CPU spikes but slow down queue processing. Higher values process faster but may cause stutter. Default: 1.</t>
    <t id="9479">Maximum work items processed per scheduler tick (1-5). Limits work item processing rate to prevent frame blocking. Lower values reduce CPU spikes but slow down queue processing. Higher values process faster but may cause stutter. Default: 1.</t>
    <t id="9480">Maximum waiters woken per scheduler tick (1-10). Limits wake rate to prevent CPU spikes when many waiters are queued. Lower values reduce CPU spikes but slow down waiter processing. Higher values process faster but may cause stutter. Default: 2.</t>
    <t id="9481">Maximum cached trades kept per home sector (1-200). Limits cache pool size after live-search writes and how many entries cache reads scan. Lower values reduce validation cost but shrink trade variety for large fleets sharing one home. Default: 50.</t>
    <t id="9482">Live search state stale threshold in seconds (60-600). When live search state is older than this, it's considered stale and cleared. Lower values clear stale state sooner but may interrupt legitimate searches. Higher values allow longer searches but may leave stale state. Default: 300s.</t>
    <t id="9483">Queue item stale threshold in seconds (30-300). When queue items are older than this, they're considered stale and removed. Lower values clear stale items sooner but may remove legitimate queued items. Higher values allow longer queue times but may leave stale items. Default: 60s.</t>
    <t id="9484">Failed trade cache expiration in seconds (300-3600). Failed trades are cached to avoid retrying immediately. Lower values expire failed trades sooner (more retries) but reduce cache effectiveness. Higher values cache longer (fewer retries) but may delay retry attempts. Default: 1800s (30 minutes).</t>
    <t id="9485">Maximum concurrent fallback live searches (1-10). Fallback searches bypass home-sector lock, allowing multiple ships from the same home sector to search simultaneously. Lower values reduce CPU load but may slow down fallback searches. Higher values allow more parallel fallback searches but increase CPU usage. Default: 1.</t>
    <t id="9490">Trade Found Signal Delay:</t>
    <t id="9590">Delay before sending GT_Trade_Found signal to ships in milliseconds (10-1000ms). Ships always wait (configured delay + 5ms buffer) before sending new requests to catch delayed signals. Higher values spread signals across frames for smoother performance. Default: 10ms.</t>
    
    <!-- GalaxyTrader Info Menu UI -->
    <t id="8000">GalaxyTrader Fleet</t>
    <t id="8001">GalaxyTrader fleet management and pilot statistics</t>
    <t id="8002">View and manage all GalaxyTrader pilots</t>
    
    <!-- Column Headers -->
    <t id="8100">Ship ID</t>
    <t id="8101">Pilot</t>
    <t id="8102">Ship</t>
    <t id="8103">Status</t>
    <t id="8104">Rank</t>
    <t id="8105">Level</t>
    <t id="8106">XP</t>
    <t id="8107">Lifetime Profit</t>
    <t id="8108">Location</t>
    <t id="8109">Home Base</t>
    <t id="8110">Last Trade</t>
    <t id="8111">Pilot Profit</t>
    <t id="8112">Ship Profit</t>
    <t id="8113">Trade Count</t>
    
    <!-- Actions -->
    <t id="8200">Refresh</t>
    <t id="8201">Export CSV</t>
    <t id="8202">Statistics</t>
    <t id="8203">Settings</t>
    <t id="8204">Help</t>
    <t id="8205">Close</t>
    
    <!-- Filter Options -->
    <t id="8300">All Pilots</t>
    <t id="8301">Trading</t>
    <t id="8302">Training</t>
    <t id="8303">Maintenance</t>
    <t id="8304">Emergency</t>
    <t id="8305">Beginners (Lv 1-5)</t>
    <t id="8306">Advanced (Lv 6-11)</t>
    <t id="8307">Experts (Lv 12+)</t>
    <t id="8308">Top 10 Earners</t>
    
    <!-- Sort Options -->
    <t id="8350">Sort by:</t>
    <t id="8351">Ship ID</t>
    <t id="8352">Pilot Name</t>
    <t id="8353">Ship Type</t>
    <t id="8354">Status</t>
    <t id="8355">Rank</t>
    <t id="8356">Level</t>
    <t id="8357">XP</t>
    <t id="8358">Profit</t>
    
    <!-- Messages -->
    <t id="8400">No pilots registered</t>
    <t id="8401">No pilots match filter</t>
    <t id="8402">Total Pilots:</t>
    <t id="8403">Total Fleet Profit:</t>
    <t id="8404">Last updated:</t>
    <t id="8405">Search pilots...</t>
    
    <!-- Column Headers -->
    <t id="8114">Sector</t>
    
    <!-- Renaming Tab -->
    <t id="8320">Ship Renaming</t>
    <t id="8321">Custom Name</t>
    <t id="8322">Set Name</t>
    <t id="8323">Clear Name</t>
    <t id="8324">Name set successfully</t>
    <t id="8325">Name cleared successfully</t>
    
    <!-- Action Buttons -->
    <t id="8450">Send to Training</t>
    <t id="8451">Deregister</t>
    <t id="8452">Force Sell Cargo</t>
    <t id="8453">Send to Repair</t>
    <t id="8454">Send to Resupply</t>
    <t id="8455">Stop All Orders</t>
    <t id="8456">Actions</t>
    
    <!-- Tooltips -->
    <t id="8500">Click to sort by Ship ID</t>
    <t id="8501">Click to sort by Pilot Name</t>
    <t id="8502">Click to sort by Ship Type</t>
    <t id="8503">Click to sort by Status</t>
    <t id="8504">Click to sort by Rank</t>
    <t id="8505">Click to sort by Level</t>
    <t id="8506">Click to sort by XP</t>
    <t id="8507">Click to sort by Lifetime Profit</t>
    <t id="8508">Refresh pilot data from mission system</t>
    <t id="8509">Export current view to CSV file</t>
    <t id="8510">View fleet statistics and charts</t>
    <t id="8511">Configure menu settings</t>
    <t id="8512">Show help and keyboard shortcuts</t>
    <t id="8600">No GalaxyTrader pilots found</t>
    <t id="8601">Create pilots by assigning ships to GalaxyTrader, or wait for data to load.</t>
    
    <!-- Context Menu Rename -->
    <t id="9001">GT Rename</t>
    <t id="9902">{77000,8450}</t>
    <t id="9903">Manual training queued for %1. Pilot will begin training after current cycle.</t>
    <t id="9904">Training queued after current cycle</t>
    <t id="9905">Pilot or ship not found</t>
    <t id="9906">AutoTraining is enabled - manual queue not required</t>
    <t id="9907">Pilot is not training blocked</t>

    <!-- Trading Academy (Fleet Academy) - see DOCS/Spec/FEATURE_FLEET_ACADEMY.md -->
    <t id="9910">Trading Academy</t>
    <t id="9911">Apprentice (Lvl 4) - %1 / %2</t>
    <t id="9912">Trader (Lvl 7) - %1 / %2</t>
    <t id="9913">Master Trader (Lvl 13) - %1 / %2</t>
    <t id="9920">Pilot %1 enrolled in Academy course for Level %2. Departing for the nearest trade station.</t>
    <t id="9921">Insufficient funds for this course (need %1, have %2).</t>
    <t id="9922">Course unavailable - pilot %1 is already at or above this level.</t>
    <t id="9923">Pilot %1 enrolled in Trading Academy Level %2 course (cost: %3 Cr, duration: %4 min) aboard %5.</t>
    <t id="9924">Trading Academy course aborted: pilot %1 cannot afford the %2 Cr fee at the academy dock (have %3 Cr). Course canceled, pilot resumes trading.</t>

    <!-- APPRENTICE LEVEL PENALTIES (Levels 1-2) - Ship class dependent -->
    <!-- Small ships: NO PENALTY (no modifications needed) -->
    
    <!-- Medium ships: -5% penalty -->
    <t id="11011">GT Apprentice Medium Ship Reducer</t>
    <t id="11012">Engine modification that slightly reduces performance for inexperienced pilots on medium ships. Used by GalaxyTrader AI system. -5% speed, thrust and rotation.</t>
    <t id="11013">GT Apprentice Medium Travel Reducer</t>
    <t id="11014">Engine modification that slightly reduces travel performance for inexperienced pilots on medium ships. Used by GalaxyTrader AI system. -5% travel speed.</t>
    
    <!-- Large ships: -15% penalty -->
    <t id="11021">GT Apprentice Large Ship Reducer</t>
    <t id="11022">Engine modification that reduces performance for inexperienced pilots on large ships. Used by GalaxyTrader AI system. -15% speed, thrust and rotation.</t>
    <t id="11023">GT Apprentice Large Travel Reducer</t>
    <t id="11024">Engine modification that reduces travel performance for inexperienced pilots on large ships. Used by GalaxyTrader AI system. -15% travel speed.</t>
    
    <!-- Capital ships: -25% penalty -->
    <t id="11031">GT Apprentice Capital Ship Reducer</t>
    <t id="11032">Engine modification that significantly reduces performance for inexperienced pilots on capital ships. Used by GalaxyTrader AI system. -25% speed, thrust and rotation.</t>
    <t id="11033">GT Apprentice Capital Travel Reducer</t>
    <t id="11034">Engine modification that significantly reduces travel performance for inexperienced pilots on capital ships. Used by GalaxyTrader AI system. -25% travel speed.</t>
    
    <!-- BASIC CERTIFIED LEVEL - Small ships (Levels 3-8) -->
    <t id="12001">GT Basic Small Ship Enhancer</t>
    <t id="12002">Specialized engine modification for small ships with basic certified pilots. Used by GalaxyTrader AI system. +3% speed, thrust and rotation.</t>
    <t id="12003">GT Basic Small Travel Enhancer</t>
    <t id="12004">Specialized engine modification for small ships with basic certified pilots. Used by GalaxyTrader AI system. +3% travel speed.</t>
    
    <!-- BASIC CERTIFIED LEVEL - Large ships (Levels 3-8) -->
    <t id="13001">GT Basic Large Ship Reducer</t>
    <t id="13002">Specialized engine modification for large ships with basic certified pilots. Used by GalaxyTrader AI system. -8% speed, thrust and rotation.</t>
    <t id="13003">GT Basic Large Travel Reducer</t>
    <t id="13004">Specialized engine modification for large ships with basic certified pilots. Used by GalaxyTrader AI system. -8% travel speed.</t>
    
    <!-- BASIC CERTIFIED LEVEL - Capital ships (Levels 3-8) -->
    <t id="14001">GT Basic Capital Ship Reducer</t>
    <t id="14002">Specialized engine modification for capital ships with basic certified pilots. Used by GalaxyTrader AI system. -15% speed, thrust and rotation.</t>
    <t id="14003">GT Basic Capital Travel Reducer</t>
    <t id="14004">Specialized engine modification for capital ships with basic certified pilots. Used by GalaxyTrader AI system. -15% travel speed.</t>
    
    <!-- EXPERT LEVEL BONUSES - Small/Medium ships (Level 9+) -->
    <t id="15001">GT Expert Small Ship Enhancer</t>
    <t id="15002">Advanced engine modification for small ships with expert pilots. Used by GalaxyTrader AI system. +25% speed, thrust and rotation.</t>
    <t id="15003">GT Expert Small Travel Enhancer</t>
    <t id="15004">Advanced engine modification for small ships with expert pilots. Used by GalaxyTrader AI system. +25% travel speed.</t>
    
    <!-- EXPERT LEVEL BONUSES - Large ships (Level 9+) -->
    <t id="16001">GT Expert Large Ship Enhancer</t>
    <t id="16002">Advanced engine modification for large ships with expert pilots. Used by GalaxyTrader AI system. +15% speed, thrust and rotation.</t>
    <t id="16003">GT Expert Large Travel Enhancer</t>
    <t id="16004">Advanced engine modification for large ships with expert pilots. Used by GalaxyTrader AI system. +15% travel speed.</t>
    
    <!-- EXPERT LEVEL BONUSES - Capital ships (Level 9+) -->
    <t id="17001">GT Expert Capital Ship Enhancer</t>
    <t id="17002">Advanced engine modification for capital ships with expert pilots. Used by GalaxyTrader AI system. +6% speed, thrust and rotation.</t>
    <t id="17003">GT Expert Capital Travel Enhancer</t>
    <t id="17004">Advanced engine modification for capital ships with expert pilots. Used by GalaxyTrader AI system. +6% travel speed.</t>
    
    <!-- PENALTY MODIFICATIONS - Skill Limitation Penalties -->
    <!-- These represent performance penalties for inexperienced pilots on larger ships -->
    <!-- Separate translations for ship and engine mods (X4 doesn't allow same ware for both types) -->
    
    <!-- Ship Penalty Mods -->
    <t id="18001">Severe Skill Limitation (Ship)</t>
    <t id="18002">Severe Skill Limitation (Ship) - Represents severe performance penalties due to pilot inexperience with large vessels. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Increases ship mass. (GT System Only - Not Available for Manual Installation)</t>
    <t id="18003">Moderate Skill Limitation (Ship)</t>
    <t id="18004">Moderate Skill Limitation (Ship) - Represents moderate performance penalties as pilot adapts to vessel complexity. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Increases ship mass. (GT System Only - Not Available for Manual Installation)</t>
    <t id="18005">Light Skill Limitation (Ship)</t>
    <t id="18006">Light Skill Limitation (Ship) - Represents minor performance penalties during pilot skill development. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Increases ship mass. (GT System Only - Not Available for Manual Installation)</t>
    
    <!-- Engine Penalty Mods -->
    <t id="18007">Severe Skill Limitation (Engine)</t>
    <t id="18008">Severe Skill Limitation (Engine) - Represents severe performance penalties due to pilot inexperience with large vessels. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Reduces engine thrust and rotation. (GT System Only - Not Available for Manual Installation)</t>
    <t id="18009">Moderate Skill Limitation (Engine)</t>
    <t id="18010">Moderate Skill Limitation (Engine) - Represents moderate performance penalties as pilot adapts to vessel complexity. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Reduces engine thrust and rotation. (GT System Only - Not Available for Manual Installation)</t>
    <t id="18011">Light Skill Limitation (Engine)</t>
    <t id="18012">Light Skill Limitation (Engine) - Represents minor performance penalties during pilot skill development. Automatically applied by GalaxyTrader system when pilot skill is insufficient for ship size. Reduces engine thrust and rotation. (GT System Only - Not Available for Manual Installation)</t>
    
    <!-- Ship State Naming -->
    <t id="9250">Ship State Naming</t>
    <t id="9350">Customize ship state abbreviations. Default values are shown in input boxes and can be overridden. Maximum 3 characters. All ship names will automatically update when changed.</t>
    <t id="9251">Resupply State Abbreviation:</t>
    <t id="9252">Repair State Abbreviation:</t>
    <t id="9253">Maintenance State Abbreviation:</t>
    <t id="9254">Training State Abbreviation:</t>
    <t id="9255">Reroute State Abbreviation:</t>
    <t id="9256">Clearance State Abbreviation:</t>
    <t id="9257">Blocked State Abbreviation:</t>
    <t id="9258">Fallback State Abbreviation:</t>
    <t id="9259">Isolated State Abbreviation:</t>
    <t id="9260">Trading State Abbreviation:</t>
    <t id="9261">Idle State Abbreviation:</t>
    <t id="9262">Escape State Abbreviation:</t>
    <t id="9268">Unreachable State Abbreviation:</t>
    <t id="9269">Pilot Exchange State Abbreviation:</t>
    <t id="9270">Custom Blacklist Prefix Tag:</t>
    <t id="9700">CHEATS (this is broken. nothing to see here!! really!!)</t>
    <t id="9701">GT ships invulnerable</t>
    <t id="9702">All player ships invulnerable</t>
    <t id="9800">Move along, pilot. These are broken developer testing tools, not a fun button menu. Nothing to see here. Really. You have been warned. Probably.</t>
    <t id="9801">Ships running a GalaxyTrader order cannot drop below 100% hull or shields. Click again to disable.</t>
    <t id="9802">All player-owned ships cannot drop below 100% hull or shields. Click again to disable. Stations are not affected.</t>
    <t id="9703">Reveal universe for GT testing</t>
    <t id="9704">Revealed</t>
    <t id="9705">Reveal</t>
    <t id="9803">Reveal all sector fog of war, mark every station known, grant all faction trade subscription licences, and subscribe trade offers galaxy-wide. Click again after new DLC sectors appear. For testing only.</t>
    <t id="9706">Max registered GT pilot XP</t>
    <t id="9707">Maxed</t>
    <t id="9708">Max XP</t>
    <t id="9804">Sets level 15 and max XP for every pilot in the GT registry. Clears training gates and blocks. Skipped while Use Vanilla XP Only is enabled. For testing only.</t>
    <t id="9351">Abbreviation for Resupply state (default: RS)</t>
    <t id="9352">Abbreviation for Repair state (default: RP)</t>
    <t id="9353">Abbreviation for Maintenance state (default: MT)</t>
    <t id="9354">Abbreviation for Training state (default: TR)</t>
    <t id="9355">Abbreviation for Reroute state (default: RR)</t>
    <t id="9356">Abbreviation for Clearance state (default: CL)</t>
    <t id="9357">Abbreviation for Blocked state (default: BL)</t>
    <t id="9358">Abbreviation for Fallback state (default: FB)</t>
    <t id="9359">Abbreviation for Isolated state (default: IS)</t>
    <t id="9360">Abbreviation for Trading state (default: TD)</t>
    <t id="9361">Abbreviation for Idle state (default: ID)</t>
    <t id="9362">Abbreviation for Escape state (default: ES)</t>
    <t id="9367">Abbreviation for Unreachable state (default: UR)</t>
    <t id="9368">Abbreviation for Pilot Exchange state (default: PE)</t>
    <t id="9369">Shown as prefix for MK3 ships affected by a custom faction blacklist (including subordinates). Default: CB</t>
    
    <!-- ========================================== -->
    <!-- GalaxyTrader MK1 - Station Trader          -->
    <!-- ID Range: 30000-30999                      -->
    <!-- ========================================== -->
    
    <!-- Order Name and Description -->
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Station trader - sells station products to NPC factions</t>
    
    <!-- Parameter Labels -->
    <t id="30010">Home Station</t>
    <t id="30011">Max Sell Distance</t>
    <t id="30012">Ignore Trade Rules</t>
    <t id="30013">Ware Filter</t>
    <t id="30014">Sell Cargo Fill Target %</t>
    <t id="30015">Backtrack Tolerance</t>
    <t id="30016">Buy Cargo Fill Target %</t>
    <t id="30017">Logbook Entries</t>
    <t id="30018">Notification Level</t>
    <t id="30019">Fleet Coordination</t>
    <t id="30020">Debug Level</t>
    <t id="30021">Supply Station</t>
    <t id="30022">Min Station Storage %</t>
    <t id="30023">Allow Illegal Wares</t>
    <t id="30024">Cargo/Profit</t>
    <t id="30025">Allow Multi-Trade</t>
    <t id="30026">Return Home Between Cycles</t>
    <t id="30028">Ignore Offer Settings</t>
    <t id="30029">Buyer Price Range</t>
    <t id="30027">Min Product Storage %</t>
    
    <!-- Parameter Tooltips -->
    <t id="30110">Player station to sell wares from (station assignment required)</t>
    <t id="30111">Maximum gate distance for finding NPC buyers (limited by pilot skill)</t>
    <t id="30112">Ignore station trade restrictions - sell to any friendly faction regardless of station trade rules</t>
    <t id="30113">Optional ware filter; leave empty to sell all station products and tradewares</t>
    <t id="30114">Minimum cargo fill percentage before departing on sell trips</t>
    <t id="30115">Max extra jumps allowed when adding a second ware to a trip (0 = only buyers directly on the route)</t>
    <t id="30116">Target cargo fill for supply runs (soft target, trader may depart earlier)</t>
    <t id="30117">Enable per-trade logbook entries</t>
    <t id="30118">Notification level: 0=Quiet, 1=Normal, 2=Verbose</t>
    <t id="30119">Enable fleet coordination and trade reservation system</t>
    <t id="30120">Debug logging level: 0=Off, 1=Normal, 2=Verbose</t>
    <t id="30121">When enabled, also buy resources for the station. Supply takes priority when storage drops below minimum threshold</t>
    <t id="30122">When any resource drops below this percentage of its target, supply takes priority over selling. Ignored if station cannot afford resources</t>
    <t id="30123">Allow selling or buying illegal/contraband wares when available</t>
    <t id="30124">Sell selection: 1 = Cargo (prefer highest station storage fill % for that ware; ties broken by profit score), 2 = Profit (highest profit score)</t>
    <t id="30125">Allow chaining multiple sell trades in one cycle (up to 3 wares/targets). Disable to run single-trade cycles only</t>
    <t id="30126">When enabled, return to home station and dock between trade cycles. When disabled, continue searching from current location (legacy behavior)</t>
    <t id="30128">Allow internal storage transfers without station buy/sell offers. Uses ware exchange for buffer pickup and delivery. Station trade rules still apply when Ignore Trade Rules is off.</t>
    <t id="30129">Minimum relative price for NPC buyers when selling station products. Order slider 0-200 (100 = average, 0 = -100%, 200 = +100%) maps to normalized -1.0 to +1.0. Higher = only expensive buyers. Lower = more buyer options. Supply runs use the inverted value for supplier price caps.</t>
    <t id="30127">Minimum station storage fill % (of configured per-ware max) required before a product or tradeware is sold. Wares below this threshold are skipped. 0 = no minimum.</t>
    
    <!-- Logbook and Notification Messages -->
    <t id="30200">Selling %1 %2 from %3 to %4</t>
    <t id="30201">No buyers found for station products within %1 jumps</t>
    <t id="30202">Home station %1 destroyed - station trader order cancelled</t>
    <t id="30203">Home station %1 is no longer player-owned - order cancelled</t>
    <t id="30204">Station assignment required - order cancelled</t>
    <t id="30205">MK1 Station Trader started at %1</t>
    <t id="30206">Completed sale: %1 %2 sold to %3 for %4 Cr (profit: %5 Cr)</t>
    <t id="30207">Multi-ware trip: delivering %1 wares to %2 destinations</t>
    <t id="30208">Supplying %1 %2 to %3 from %4</t>
    
    <!-- Settings Menu -->
    <t id="30500">GalaxyTrader MK1 Settings</t>
    <t id="30501">Station Trader Defaults</t>
    <t id="30502">Default Max Sell Distance</t>
    <t id="30503">Default Sell Cargo Fill Target</t>
    <t id="30504">Default Ignore Trade Rules</t>
    <t id="30505">Default Backtrack Tolerance</t>
    <t id="30506">Wait Time When No Trades Found</t>
    <t id="30507">Default Buy Cargo Fill Target</t>

    <!-- ========================================== -->
    <!-- Galaxy-Miner                               -->
    <!-- ID Range: 31000-31999                      -->
    <!-- ========================================== -->
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">Autonomous mining with station supply and XP progression</t>
    <t id="31010">Home Station</t>
    <t id="31110">Station to mine for and deliver to (mutually exclusive with Home Sector)</t>
    <t id="31011">Home Sector</t>
    <t id="31111">Sector to operate in; used when no Home Station is set</t>
    <t id="31012">Resource Basket</t>
    <t id="31112">Wares to mine; empty follows station demand resolution</t>
    <t id="31013">Target Stations</t>
    <t id="31113">Optional station filter for deliveries; empty derives from home context</t>
    <t id="31014">Overflow Threshold %</t>
    <t id="31114">Stations at or above this storage percent are treated as full</t>
    <t id="31015">Allow Overflow Sell to Others</t>
    <t id="31115">When enabled and primary targets are full, sell to other faction stations</t>
    <t id="31016">Assign to Station</t>
    <t id="31116">Assign ship as mining subordinate of Home Station when applicable</t>
    <t id="31017">Stay at Home</t>
    <t id="31117">Restrict mining/selling to home area except overflow fallback runs</t>
    <t id="31018">Auto Deploy Resource Probes</t>
    <t id="31118">Hybrid scout-and-mine: opportunistically deploys probes in mining sectors, collects stale probes from sectors that no longer match the basket, and - when find_closest_resource turns up nothing because the basket asteroids are undiscovered - flies to a sector that has the asteroid type, runs the vanilla resource-scout sweep there to drop a probe, then resumes normal mining the next loop iteration. The Probe Stock Target slider controls per-trip restock amount when the ship runs out.</t>
    <t id="31019">Max Gather Distance</t>
    <t id="31119">Maximum gate distance for gathering (0 uses pilot/commander skill cap)</t>
    <t id="31020">Max Sell Distance</t>
    <t id="31120">Maximum gate distance for selling (0 uses pilot/commander skill cap)</t>
    <t id="31021">Fleet Balancing</t>
    <t id="31121">Enable deterministic intent coordination to reduce station overflow</t>
    <t id="31022">Demand Recheck Interval</t>
    <t id="31122">How often miner demand/switch evaluation runs</t>
    <t id="31023">Critical Demand Delta</t>
    <t id="31123">Minimum urgency delta required to switch active mining ware</t>
    <t id="31024">Min Switch Cooldown</t>
    <t id="31124">Minimum time between two ware switches for this ship</t>
    <t id="31025">Min Cargo Commit %</t>
    <t id="31125">If cargo fill is above this, ship prefers finishing current delivery before switch</t>
    <t id="31026">Hard Emergency Delta</t>
    <t id="31126">Urgency delta that allows immediate switch despite cargo commit threshold</t>
    <t id="31027">Notification Level</t>
    <t id="31127">Notification level: 0=Quiet, 1=Normal, 2=Verbose</t>
    <t id="31028">Player Stations Only</t>
    <t id="31128">When enabled, only player-owned stations are considered as demand targets.</t>
    <t id="31031">Check Demand First</t>
    <t id="31131">When enabled, the miner checks station demand before mining and prioritises wares accordingly. When disabled, it mines from the Resource Basket without demand checks and stockpiles until a buyer is available (recommended for single-resource fleets).</t>
    <t id="31032">Physical storage abort %</t>
    <t id="31132">For pilots level 6+: stop mining the current ware when station physical stock plus all relevant miners' in-flight cargo would exceed current station stock by this percentage. Uses live cargo counts, not the overflow threshold. 0 = disabled.</t>
    <t id="31029">Probe Stock Target</t>
    <t id="31030">Mining Drones to Buy</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: no mineable wares available. Ship %1 [%2], Fleet: %3</t>
    <t id="31201">Galaxy-Miner: set Home Station or Home Position.</t>
    <t id="31130">How many collector (mining) drones the miner buys when it has run OUT of the needed type (solid ore / liquid gas). The buy is triggered ONLY when the ship has zero collectors of that type - a miner that still has at least one is never topped up or re-bought, so existing drones are kept. Capped by the ship's unit-bay capacity. Set to 0 to disable automatic collector-drone purchases and manage drones manually. Default 5 is a full drone set for normal mining speed.</t>
    <t id="31129">Number of resource probes the miner buys per restock trip. The buy is triggered ONLY when the ship has run out of probes (count = 0), not on every deploy - that way the miner runs through its full probe load between supply runs instead of detouring after each deployment. Capped by the ship's total deployable capacity (shared with satellites/mines/etc); a slider value larger than free deployable space gracefully degrades to "fill what fits". Only takes effect when Auto Deploy Resource Probes is enabled - the same setting also drives opportunistic probe deployment in mining sectors and collection of stale probes (probes in sectors with no basket-relevant resources).</t>

    <!-- ========================================== -->
    <!-- GalaxyTrader MK4 - Supply Trader           -->
    <!-- ID Range: 32000-32999                      -->
    <!-- ========================================== -->
    <t id="32002">GalaxyTrader MK4 Supply</t>
    <t id="32102">Player station supply trader using GT cache/live search pipeline</t>
    <t id="32010">Coverage Distance</t>
    <t id="32110">Maximum gate distance from home for destination demand search</t>
    <t id="32011">Buy Distance</t>
    <t id="32111">Maximum gate distance from home for supplier search</t>
    <t id="32012">Serve Home Only</t>
    <t id="32112">When enabled, only home station demand is served</t>
    <t id="32013">Build Stations Only</t>
    <t id="32113">When enabled, only build storage demand is served</t>
    <t id="32014">Buy from Player</t>
    <t id="32114">Allow sourcing wares from player-owned suppliers</t>
    <t id="32015">Buy from Faction</t>
    <t id="32115">Allow sourcing wares from non-player faction suppliers</t>
    <t id="32016">Allow Resources</t>
    <t id="32116">Include resource wares in demand matching</t>
    <t id="32017">Allow Intermediates</t>
    <t id="32117">Include intermediate wares in demand matching</t>
    <t id="32018">Allow Products</t>
    <t id="32118">Include product wares in demand matching</t>
    <t id="32019">Allow Tradewares</t>
    <t id="32119">Include tradeware wares in demand matching</t>

    <!-- ========================================== -->
    <!-- GalaxyTrader MK2 - Distribution Trader     -->
    <!-- ID Range: 20000-20999                      -->
    <!-- ========================================== -->
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">Warehouse distribution with storage threshold management</t>
    <t id="20010">Source Stations</t>
    <t id="20011">Destination Stations</t>
    <t id="20012">Min Storage %</t>
    <t id="20013">Static Storage %</t>
    <t id="20014">Max Storage %</t>
    <t id="20015">Ware Filter</t>
    <t id="20016">Bidirectional Mode</t>
    <t id="20017">Home Station (optional)</t>
    <t id="20018">Max Distance</t>
    <t id="20032">Home Sector (optional)</t>
    <t id="20019">Cycle Wait Time</t>
    <t id="20030">Allow Low Volume</t>
    <t id="20031">Low Volume Floor %</t>
    <t id="20110">List of source stations to distribute wares from</t>
    <t id="20111">List of destination stations/warehouses to distribute wares to</t>
    <t id="20112">Destination urgency threshold: stations below this storage % receive priority deliveries</t>
    <t id="20113">Source minimum threshold: source must have more than this % to distribute at all</t>
    <t id="20114">Source overflow threshold: above this % source distributes even to non-urgent destinations</t>
    <t id="20115">Optional ware filter; leave empty to distribute all wares from the source</t>
    <t id="20116">Enable return-trip collection from destinations back to source when destinations have excess</t>
    <t id="20117">Optional home station for assignment. If empty, ship remains unassigned to stations.</t>
    <t id="20118">Maximum gate distance between source and destinations (0 = unlimited)</t>
    <t id="20132">Optional home sector used for Idle Parking when no home station is set.</t>
    <t id="20119">Time to wait between distribution cycles</t>
    <t id="20130">Allow smaller urgency-aware delivery chunks below normal minimum cargo fill.</t>
    <t id="20131">Minimum cargo fill % used when low-volume mode is enabled.</t>
    <t id="20200">Distributing %1 %2 from %3 to %4</t>
    <t id="20201">Return trip: collecting %1 %2 from %3 to %4</t>
    <t id="20202">No distribution needed - all destinations adequately supplied</t>
    <t id="20203">All source stations invalid - distribution standing by</t>
    <t id="20204">All destination stations invalid - distribution standing by</t>
    <t id="20205">Source station %1 destroyed - removed from distribution order</t>
    <t id="20206">Destination station %1 destroyed - removed from distribution order</t>
    <t id="20500">GalaxyTrader MK2 - Global Settings</t>
    <t id="20501">MK2 Distribution Defaults</t>
    <t id="20510">Default Min Storage %</t>
    <t id="20511">Default Static Storage %</t>
    <t id="20512">Default Max Storage %</t>
    <t id="20513">Default Cycle Wait (s)</t>
    <t id="20514">Minimum Cargo Fill %</t>
    <t id="20520">Notification Verbosity</t>
    <t id="20521">Debug Level</t>
    
  </page>
  

  
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="48">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Zadokuj i poczekaj (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">Egzamin koÅ„cowy (GalaxyTrader MK3)</t>
    <t id="10004">Spotkanie wymiany pilotÃ³w</t>
    <t id="10005">[PRZESTARZAÅE] GalaxyTrader Zasilanie MK4 (Legacy)</t>
    <t id="10101">Zadokuj na stacji i poczekaj okreÅ›lony czas</t>
    <t id="10102">Autonomiczny handel z postÄ™pem umiejÄ™tnoÅ›ci</t>
    <t id="10103">PrzystÄ…p do egzaminu koÅ„cowego w celu uzyskania certyfikatu pilota w oÅ›rodku szkoleniowym</t>
    <t id="10104">Zadokuj na stacji spotkania w celu wymiany pilotÃ³w</t>
    <t id="10105">Handel skoncentrowany na dostawach dla stacji graczy przy uÅ¼yciu pamiÄ™ci podrÄ™cznej i wyszukiwania na Å¼ywo (Legacy)</t>
    <t id="10201">Kup %s od %s</t>
    <t id="10202">Sprzedaj %s %s</t>
    <t id="10203">Handluj z %s</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">Zaawansowany system handlu z progresjÄ… XP i koordynacjÄ… floty</t>
    <t id="1002">Baza domowa</t>
    <t id="1003">UÅ¼yj gotowych ustawieÅ„</t>
    <t id="1004">Handluj wszystkimi towarami</t>
    <t id="1005">Handluj legalnymi towarami</t>
    <t id="1006">Handluj nielegalnymi towarami</t>
    <t id="1007">WÅ‚Ä…cz progresjÄ™ XP</t>
    <t id="1008">WÅ‚Ä…cz koordynacjÄ™ floty</t>
    <t id="1009">WÅ‚Ä…cz analizÄ™ rynku</t>
    <t id="1010">WÅ‚Ä…cz zarzÄ…dzanie terytorium</t>
    <t id="1011">Zezwalaj na nielegalne towary</t>
    <t id="1012">Wpisy do dziennika</t>
    <t id="1013">Tolerancja ryzyka</t>
    <t id="1014">Nadaj priorytet stacjom graczy</t>
    <t id="1015">Towary automatyczne</t>
    <t id="1016">Kara za odlegÅ‚oÅ›Ä‡%</t>
    <t id="1017">Poziom powiadomieÅ„</t>
    <t id="1018">Koordynacja floty</t>
    <t id="1019">Docelowy procent wypeÅ‚nienia Å‚adunku</t>
    <t id="1050">CzÄ™stotliwoÅ›Ä‡ aktualizacji rynku</t>
    <t id="1051">Rejestrowanie ocen transakcji</t>
    <t id="1052">BiaÅ‚a lista sektorÃ³w</t>
    <t id="1054">Ignoruj â€‹â€‹statki przewoÅºnika/pomocnicze</t>
    <t id="1056">Ignoruj â€‹â€‹â€‹â€‹magazyn kompilacji</t>
    <t id="1058">Ignoruj â€‹â€‹zasady handlu</t>
    <t id="1060">Ignoruj â€‹â€‹stacje dostarczane przez MK1</t>
    <t id="1063">W fazie rozwoju</t>
    <t id="1064">Towary priorytetowe</t>
    <t id="1065">Priorytet wynikÃ³w %</t>
    <t id="1066">Towary faworyzowane w punktacji handlowej. Ich wynik jest mnoÅ¼ony przez % Wyniku Priorytetu.</t>
    <t id="1067">MnoÅ¼nik punktÃ³w dla towarÃ³w priorytetowych: 100%=normalny, 150%=+50%%, 200%=2x, 300%=3x. Zastosowano jako ostatnie.</t>
    <t id="1068">â”€â”€ Filtr towarÃ³w priorytetowych â”€â”€</t>
    <t id="1069">Towary (rÄ™czne)</t>
    <t id="1070">Filtr nielegalnych tras</t>
    <t id="1072">Podawaj tylko w domu</t>
    <t id="1073">Priorytet dostawcy gracza</t>
    <t id="1074">Priorytet dostawcy frakcji</t>
    <t id="1075">UwzglÄ™dnij magazyn kompilacji</t>
    <t id="1076">UwzglÄ™dnij zasoby</t>
    <t id="1077">UwzglÄ™dnij pÃ³Å‚produkty</t>
    <t id="1078">UwzglÄ™dnij produkty handlowe</t>
    <t id="1080">Maksymalna liczba transakcji na cykl</t>
    <t id="1081">Tolerancja wsteczna</t>
    <t id="1082">Minimalny wykorzystany Å‚adunek%</t>
    <t id="1083">Gracz Kup Modyfikator%</t>
    <t id="1085">Przypisz do stacji domowej</t>
    <t id="1086">OdlegÅ‚oÅ›Ä‡ zasiÄ™gu</t>
    <t id="1088">Maksymalna odlegÅ‚oÅ›Ä‡ skoku od domu w celu pokrycia zapotrzebowania</t>
    <t id="1090">UwzglÄ™dnij towary klasy handlowej w dopasowaniu popytu/podaÅ¼y</t>
    <t id="1091">Modyfikator zastosowany do cen dostawcÃ³w bÄ™dÄ…cych wÅ‚asnoÅ›ciÄ… gracza w obliczeniach wyÅ‚Ä…cznie punktowych</t>
    <t id="1092">Ignoruj â€‹â€‹ceny graczy</t>
    <t id="1093">Po wÅ‚Ä…czeniu: zawsze kupuj na stacjach naleÅ¼Ä…cych do gracza, niezaleÅ¼nie od ustalonych przez nich cen sprzedaÅ¼y i sprzedawaj tylko frakcjom NPC. Przydatne przy likwidacji nadwyÅ¼ek magazynowych z wÅ‚asnych stacji.</t>
    <t id="1094">Zablokowane stacje</t>
    <t id="1095">Wybrane tutaj stacje sÄ… wykluczone z handlu MK3. Handlowiec nie bÄ™dzie na nich kupowaÄ‡ ani im sprzedawaÄ‡.</t>
    <t id="1096">PostÃ³j bezczynny</t>
    <t id="1097">Po wÅ‚Ä…czeniu statki, ktÃ³re wielokrotnie nie znajdujÄ… pracy, parkujÄ… przy stacji domowej lub w sektorze domowym. Parkowanie w sektorze preferuje stacje gracza, potem przyjazne stacje. Czas zwolnienia doku ustawia siÄ™ w ustawieniach globalnych (0 = pozostaje zacumowany, dopÃ³ki nie znajdzie pracy).</t>
    <t id="1098">Autoskalowanie</t>
    <t id="1099">Po wÅ‚Ä…czeniu suwaki zasiÄ™gu skokÃ³w sÄ… ustawiane na maksymalny dozwolony zasiÄ™g pilota po obowiÄ…zkowym szkoleniu lub ukoÅ„czeniu Akademii Handlowej. Odznacz, aby ustawiÄ‡ dystanse rÄ™cznie.</t>
    <t id="11001">Priorytet magazynu budowy</t>
    <t id="11002">Priorytet stacji</t>
    <t id="11003">Priorytet statkÃ³w pomocniczych</t>
    <t id="11004">Priorytet lotniskowcÃ³w</t>
    <t id="11005">0 = wyÅ‚Ä…czone. 1-10 = mnoÅ¼nik wyniku (10 = najsilniejsze waÅ¼enie). Wynik koÅ„cowy = wynik zaopatrzenia Ã— mnoÅ¼nik.</t>
    <t id="11006">1 = brak dodatkowego wyniku (lista towarÃ³w priorytetowych bez zmian). 2-10 = dodaje (mnoÅ¼nikâˆ’1)Ã— bazowy wynik zaopatrzenia, gdy towar jest na liÅ›cie priorytetowej. NakÅ‚adane na wynik typu.</t>
    <t id="11007">Bonus towarÃ³w priorytetowych</t>
    <t id="11008">%1: Wszystkie suwaki priorytetu celÃ³w dostawy sÄ… ustawione na 0 - to zlecenie nie ma celÃ³w dostawy. WÅ‚Ä…cz co najmniej jednÄ… klasÄ™ (magazyn budowlany, stacje, statki pomocnicze lub lotniskowce), aby wznowiÄ‡ dostawy.</t>
    <t id="7001">[OSIÄ„GNIÄ˜CIE]</t>
    <t id="7002">[SZKOLENIE]</t>
    <t id="7008">[POWRÃ“T]</t>
    <t id="7009">[ODOSOBNIONY]</t>
    <t id="7003">[NAPRAWA]</t>
    <t id="7004">[Zaopatrzenie]</t>
    <t id="7005">[KONSERWACJA]</t>
    <t id="7006">[PRZEPROWADÅ¹]</t>
    <t id="7007">[LUZ]</t>
    <t id="1020">Wybierz sektor macierzysty lub stacjÄ™, na ktÃ³rej dziaÅ‚a trader</t>
    <t id="1021">Maksymalna odlegÅ‚oÅ›Ä‡ skoku przy zakupie towarÃ³w (ograniczona umiejÄ™tnoÅ›ciami pilota)</t>
    <t id="1022">Maksymalna odlegÅ‚oÅ›Ä‡ skoku podczas sprzedaÅ¼y towarÃ³w (ograniczona umiejÄ™tnoÅ›ciami pilota)</t>
    <t id="1023">Automatyczny wybÃ³r odpowiednich towarÃ³w na podstawie kategorii</t>
    <t id="1024">RÄ™czny wybÃ³r konkretnych towarÃ³w handlowych</t>
    <t id="1025">Zezwalaj na handel kontrabandÄ… i nielegalnymi towarami</t>
    <t id="1026">Tolerancja bezpieczeÅ„stwa: 0,0=Tylko bezpieczne sektory, 1,0=Akceptuj wszystkie ryzyka</t>
    <t id="1027">Udoskonalaj umiejÄ™tnoÅ›ci pilota poprzez doÅ›wiadczenie handlowe</t>
    <t id="1028">W razie potrzeby automatycznie wysyÅ‚aj pilotÃ³w na szkolenie</t>
    <t id="1029">Koordynuj wiele statkÃ³w handlowych, aby uniknÄ…Ä‡ konfliktÃ³w</t>
    <t id="1030">Koncentracja na towarach: 0=ZrÃ³wnowaÅ¼ony, 1=Zaawansowany, 2=Podstawowe potrzeby, 3=Nielegalne, 4=Towary masowe</t>
    <t id="1031">Obszar handlu: 0=ZrÃ³wnowaÅ¼ony, 1=Skupienie na domu, 2=Swoboda poruszania siÄ™</t>
    <t id="1032">Poziom powiadamiania: 0=Minimalny, 1=Normalny, 2=SzczegÃ³Å‚owe wiadomoÅ›ci</t>
    <t id="1033">Docelowy procent wykorzystania Å‚adunku przed ustaleniem priorytetu sprzedaÅ¼y</t>
    <t id="1034">Jak czÄ™sto aktualizowane sÄ… dane rynkowe i informacje o cenach</t>
    <t id="1035">Poziom wyjÅ›ciowy debugowania: 0 = brak, 1 = podstawowy, 2 = peÅ‚ne rejestrowanie</t>
    <t id="1036">UdostÄ™pniaj dochodowe szlaki handlowe flocie (w pamiÄ™ci podrÄ™cznej w celu szybkiego dostÄ™pu)</t>
    <t id="1037">Minimalny zysk wymagany do buforowania handlu i udostÄ™pniania go flocie</t>
    <t id="1038">Maksymalny dozwolony spadek zysku, zanim buforowane szlaki handlowe stanÄ… siÄ™ niewaÅ¼ne</t>
    <t id="1039">Jak dÅ‚ugo buforowane szlaki handlowe pozostajÄ… waÅ¼ne przed wygaÅ›niÄ™ciem</t>
    <t id="1040">WÅ‚Ä…cz szczegÃ³Å‚owe rejestrowanie ocen i odrzuceÅ„ poszczegÃ³lnych transakcji (moÅ¼e byÄ‡ bardzo szczegÃ³Å‚owe)</t>
    <t id="1041">WÅ‚Ä…cz wpisy w dzienniku transakcji i wciÄ…gajÄ…ce komunikaty szkoleniowe (styl TaterTrader)</t>
    <t id="1053">Sektory na tej liÅ›cie sÄ… wykluczone z czarnych list (zawsze dozwolone)</t>
    <t id="1055">Wyklucz z handlu lotniskowce i statki pomocnicze</t>
    <t id="1057">Wyklucz z handlu statki do skÅ‚adowania konstrukcji</t>
    <t id="1059">Ignoruj â€‹â€‹zasady handlu stacjami podczas wyszukiwania ofert (zaawansowane; moÅ¼e wybieraÄ‡ oferty normalnie blokowane)</t>
    <t id="1061">PomiÅ„ stacje graczy, do ktÃ³rych przypisany jest handlarz MK1 z trybem zaopatrzenia</t>
    <t id="1062">ZwiÄ™ksz wyniki handlowe dla tras obejmujÄ…cych Twoje wÅ‚asne stacje (bonus 10% wyniku)</t>
    <t id="1071">Gdy wÅ‚Ä…czona jest opcja Zezwalaj na nielegalne towary, handluj tylko nielegalnymi towarami, jeÅ›li sÄ… legalne we wszystkich sektorach na Å›cieÅ¼ce przeskoku (sektory kupna, sprzedaÅ¼y i sektory poÅ›rednie).</t>
    <t id="1087">Maksymalna odlegÅ‚oÅ›Ä‡ skoku od domu w celu wyszukiwania zakupu dostawcy</t>
    <t id="1089">Po wyÅ‚Ä…czeniu statek moÅ¼e zaopatrywaÄ‡ stacje w obszarze zasiÄ™gu wedÅ‚ug priorytetu pilnoÅ›ci, a nie w trybie â€žtylko w domuâ€.</t>
    <t id="2000">%s zdobyÅ‚ %s XP!</t>
    <t id="2001">%s awansowaÅ‚! Nowy poziom: %s</t>
    <t id="2002">%s potrzebuje szkolenia! ProszÄ™ wysÅ‚aÄ‡ do najbliÅ¼szej stoczni lub stacji handlowej.</t>
    <t id="2003">%s rozpoczÄ…Å‚ szkolenie w %s</t>
    <t id="2004">%s ukoÅ„czyÅ‚ szkolenie i posiada teraz certyfikat na poziomie %s!</t>
    <t id="2005">%s osiÄ…gnÄ…Å‚ Skill Level %s po szkoleniu! PostÄ™p XP odblokowany w %s.</t>
    <t id="2006">%s osiÄ…gnÄ…Å‚ Skill Level %s dziÄ™ki handlowi %s!</t>
    <t id="2007">%s ukoÅ„czyÅ‚ szkolenie Level %s! PostÄ™p XP odblokowany w %s.</t>
    <t id="3000">%s zakoÅ„czyÅ‚ transakcjÄ™! Zysk: %s Kr</t>
    <t id="3001">%s analizuje warunki rynkowe...</t>
    <t id="3002">%s znalazÅ‚ opÅ‚acalny szlak handlowy!</t>
    <t id="3003">Brak dostÄ™pnych dochodowych szlakÃ³w handlowych dla %s</t>
    <t id="3100">SprzedajÄ™ %1 %2 z Å‚adunku do %3 po %4. Powinienem zarobiÄ‡ %5 zysku.</t>
    <t id="3101">Kolejkowanie zlecenia handlowego dla %1 %2. Kupno po %3 z %4, sprzedaÅ¼ po %5 do %6. Powinienem zarobiÄ‡ %7 zysku.</t>
    <t id="3102">Sprzedawca stacji: Zaopatruje %1 %2 od %3 przy %5%% do %4 przy %6%%.</t>
    <t id="3103">Station Trader: SprzedajÄ™ %1 %2 do %3 po %4. Oczekiwany zysk to %5.</t>
    <t id="3104">Transakcja zakoÅ„czona pomyÅ›lnie dla %1 %2. CaÅ‚kowity zysk: %3 Kredyty.</t>
    <t id="3105">Szlak handlowy zapisany w pamiÄ™ci podrÄ™cznej: %1 %2 z %3 do %4 (Zysk: %5 Cr)</t>
    <t id="3106">\nCaÅ‚kowity szacowany zysk w caÅ‚ym okresie przed tÄ… transakcjÄ…: %1 Cr.</t>
    <t id="3120">RozpoczÄ™to transfer pilotaÅ¼owy</t>
    <t id="3121">ProtokÃ³Å‚ przekazania potwierdzony. %1 (%2) i %3 (%4) udajÄ… siÄ™ do %5 (%6), aby zadokowaÄ‡ i wymieniÄ‡ siÄ™ stanowiskami dowodzenia.</t>
    <t id="3200">Witaj DowÃ³dco %1,\n\nZdobyÅ‚em wystarczajÄ…ce doÅ›wiadczenie, aby przystÄ…piÄ‡ do egzaminu certyfikacyjnego na tytuÅ‚ â€ž%2â€. Egzamin zajmie okoÅ‚o %3 minut o godzinie %4.\n\nTo waÅ¼ny kamieÅ„ milowy w moim rozwoju kariery. Egzamin sprawdzi mojÄ… wiedzÄ™ na temat zaawansowanych protokoÅ‚Ã³w handlowych, analizy rynku i procedur koordynacji floty.\n\nJestem pewny swoich umiejÄ™tnoÅ›ci i podekscytowany moÅ¼liwoÅ›ciÄ… udowodnienia, Å¼e â€‹â€‹jestem godny tego awansu. Å»yczcie mi powodzenia!\n\nZ powaÅ¼aniem,\n%5\nNa pokÅ‚adzie %6</t>
    <t id="3201">DowÃ³dco %1,\n\nWspaniaÅ‚a wiadomoÅ›Ä‡! PomyÅ›lnie ukoÅ„czyÅ‚em egzamin certyfikacyjny i uzyskaÅ‚em tytuÅ‚ â€ž%2â€!\n\nEgzamin obejmowaÅ‚ zaawansowane strategie handlowe, protokoÅ‚y oceny ryzyka i procedury koordynacji floty. Z przyjemnoÅ›ciÄ… ogÅ‚aszam, Å¼e zdaÅ‚em egzamin z wyrÃ³Å¼nieniem.\n\nMam teraz kwalifikacje do obsÅ‚ugi bardziej zÅ‚oÅ¼onych operacji handlowych i nie mogÄ™ siÄ™ doczekaÄ‡, aby jeszcze bardziej przyczyniÄ‡ siÄ™ do sukcesu naszej floty. DziÄ™kujÄ™ za inwestowanie w mÃ³j rozwÃ³j zawodowy.\n\nZ nowym zaangaÅ¼owaniem,\n%3\nCertyfikat %2\nNa pokÅ‚adzie %4</t>
    <t id="3202">DowÃ³dco %1,\n\nZ przykroÅ›ciÄ… informujÄ™, Å¼e mÃ³j egzamin certyfikacyjny zostaÅ‚ przerwany ze wzglÄ™du na wymagania operacyjne. BÄ™dÄ™ musiaÅ‚ przeÅ‚oÅ¼yÄ‡ termin egzaminu, jeÅ›li okolicznoÅ›ci na to pozwolÄ….\n\nNadal bÄ™dÄ™ zaangaÅ¼owany w doskonalenie swoich umiejÄ™tnoÅ›ci i powiadomiÄ™ CiÄ™, kiedy bÄ™dÄ™ mÃ³gÅ‚ wznowiÄ‡ proces egzaminacyjny.\n\nZ powaÅ¼aniem,\n%2\nNa pokÅ‚adzie %3</t>
    <t id="3203">DowÃ³dco %1,\n\nJestem obecnie w drodze do %2 na egzamin certyfikacyjny. Ta podrÃ³Å¼ daje mi czas na podsumowanie studiÃ³w i przygotowanie psychiczne na ten waÅ¼ny etap w mojej karierze.\n\nOczekiwany przyjazd: %3 minut\nCzas trwania egzaminu: %4 minut\n\nDoceniam TwojÄ… wiarÄ™ w moje umiejÄ™tnoÅ›ci i moÅ¼liwoÅ›ci awansu.\n\nZ determinacjÄ…\n%5\nNa pokÅ‚adzie %6</t>
    <t id="3204">Komandorze,\n\nPodczas sprawdzania systemÃ³w wykryÅ‚em Å‚adunek w mojej Å‚adowni. Zanim bÄ™dÄ™ mÃ³gÅ‚ rozpoczÄ…Ä‡ normalne operacje handlowe, muszÄ™ sprzedaÄ‡ ten towar.\n\nKorzystam z naszej wyszukiwarki transakcji, aby znaleÅºÄ‡ najlepszego kupca i bezpiecznie wyÅ‚adowaÄ‡ ten Å‚adunek. Gdy moja blokada bÄ™dzie juÅ¼ jasna, przejdÄ™ do automatycznego handlu.\n\nStan: Wyszukiwanie optymalnej lokalizacji sprzedaÅ¼y\n\nZ naleÅ¼ytÄ… starannoÅ›ciÄ…,\nNa pokÅ‚adzie %1</t>
    <t id="3205">DowÃ³dco,\n\nIntegralnoÅ›Ä‡ mojego kadÅ‚uba spadÅ‚a do %1%% (prÃ³g: %2%%). Jako pilot poziomu %3 mam uprawnienia do zamawiania usÅ‚ug naprawy automatycznej.\n\nUdajÄ™ siÄ™ do %4 w celu naprawy. Szacunkowy koszt to %5 Cr i mieÅ›ci siÄ™ w naszym budÅ¼ecie.\n\nPo zakoÅ„czeniu naprawy wznowiÄ™ dziaÅ‚alnoÅ›Ä‡ handlowÄ… z zachowaniem peÅ‚nej integralnoÅ›ci strukturalnej.\n\nZ wyrazami szacunku,\nNa pokÅ‚adzie %6</t>
    <t id="3206">DowÃ³dco,\n\nPILNE OSTRZEÅ»ENIE FINANSOWE\n\nMoja integralnoÅ›Ä‡ kadÅ‚uba jest krytyczna na poziomie %1%% (prÃ³g: %2%%), ale nasze dostÄ™pne fundusze (%3 Cr) sÄ… niewystarczajÄ…ce na peÅ‚ne naprawy (szacunkowy koszt: %4 Cr).\n\nPrzystÄ™pujÄ™ do %5 w celu NAPRAW CZÄ˜ÅšCIOWYCH, korzystajÄ…c z naszych dostÄ™pnych Å›rodkÃ³w. Nie jest to idealne rozwiÄ…zanie, ale konieczne do utrzymania zdolnoÅ›ci operacyjnej.\n\nProszÄ™ rozwaÅ¼yÄ‡ przeznaczenie dodatkowych Å›rodkÃ³w na przyszÅ‚e operacje konserwacyjne.\n\nZaniepokojony, ale zdeterminowany,\nNa pokÅ‚adzie %6</t>
    <t id="3207">DowÃ³dco,\n\nCertyfikacja mojego poziomu %1 upowaÅ¼nia do automatycznego uzupeÅ‚niania sprzÄ™tu obronnego. Po sprawdzeniu moich systemÃ³w ustaliÅ‚em, Å¼e moje Å›rodki zaradcze i urzÄ…dzenia do rozmieszczenia sÄ… poniÅ¼ej zalecanych progÃ³w.\n\nUdajÄ™ siÄ™ do %2, aby uzupeÅ‚niÄ‡ mÃ³j sprzÄ™t obronny:\n â€¢ Åšrodki zaradcze: uzupeÅ‚nienie do optymalnej pojemnoÅ›ci\nâ€¢ Drony obronne, drony handlowe, wieÅ¼e laserowe: zastosowanie profilu rÃ³wnowagi\n\nTo zaopatrzenie zapewnia mi najlepszÄ… ochronÄ™ przed zagroÅ¼eniami kosmicznymi przy jednoczesnym zachowaniu efektywnoÅ›ci handlu.\n\nDziÄ™ki czujnoÅ›Ä‡,\nNa pokÅ‚adzie %3</t>
    <t id="3212">DowÃ³dco,\n\nMoja integralnoÅ›Ä‡ kadÅ‚uba spadÅ‚a do %1%% (prÃ³g: %2%%) i potrzebujÄ™ usÅ‚ug naprawczych. Jednak najbliÅ¼sza stacja naprawcza pod adresem %3 jest obecnie nieosiÄ…galna ze wzglÄ™du na ograniczenia w podrÃ³Å¼owaniu do tego sektora (trasy znajdujÄ… siÄ™ na czarnej liÅ›cie).\n\nBÄ™dÄ™ kontynuowaÅ‚ dziaÅ‚alnoÅ›Ä‡ handlowÄ… pomimo tego ograniczenia. Gdy bezpieczne trasy stanÄ… siÄ™ ponownie dostÄ™pne, automatycznie poszukam usÅ‚ug naprawy.\n\nBÄ™dÄ™ monitorowaÄ‡ sytuacjÄ™ i powiadomiÄ™ CiÄ™, gdy naprawa stanie siÄ™ moÅ¼liwa.\n\nZ wyrazami szacunku,\nNa pokÅ‚adzie %4</t>
    <t id="3213">DowÃ³dco,\n\nMÃ³j sprzÄ™t obronny wymaga uzupeÅ‚nienia, ale najbliÅ¼sza stacja wyposaÅ¼enia w %1 jest obecnie nieosiÄ…galna ze wzglÄ™du na ograniczenia w podrÃ³Å¼owaniu do sektora (trasy na czarnej liÅ›cie).\n\nBÄ™dÄ™ kontynuowaÅ‚ dziaÅ‚alnoÅ›Ä‡ handlowÄ… pomimo tego ograniczenia. Gdy bezpieczne trasy stanÄ… siÄ™ ponownie dostÄ™pne, automatycznie poszukam usÅ‚ug zaopatrzenia.\n\nBÄ™dÄ™ monitorowaÄ‡ sytuacjÄ™ i powiadomiÄ™ CiÄ™, gdy zaopatrzenie stanie siÄ™ moÅ¼liwe.\n\nZ wyrazami szacunku,\nNa pokÅ‚adzie %2</t>
    <t id="3208">DowÃ³dco,\n\nUkoÅ„czyÅ‚em wyczerpujÄ…cÄ… analizÄ™ rynku %1 i sÄ…siednich sektorÃ³w (w zakresie %2 skokÃ³w, minimalny prÃ³g zysku: %3 Cr), ale niestety nie znalazÅ‚em Å¼adnych zyskownych moÅ¼liwoÅ›ci handlowych speÅ‚niajÄ…cych nasze wymagania.\n\nRAPORT Z ANALIZY HANDLU:\nOceniona caÅ‚kowita liczba moÅ¼liwoÅ›ci: %4\n\nPODZIAÅ ODRZUCENIA:\n- Ograniczenia dokowania: %5 transakcje\n (Stacja nie pozwala na klasÄ™ mojego statku)\n- NiewystarczajÄ…ca rentownoÅ›Ä‡: %6 transakcje\n (PoniÅ¼ej minimalnego progu zysku)\n- NiewystarczajÄ…cy wolumen: %7 transakcje\n (Zero lub ujemna kwota handlowa)\n- Ograniczenia bezpieczeÅ„stwa: %8 transakcje\n (Stacje na czarnej liÅ›cie lub niebezpieczne sektory)\n\nZALECENIA:\n- RozwaÅ¼ skorygowanie zysku progi\n- ZwiÄ™ksz maksymalnÄ… odlegÅ‚oÅ›Ä‡ handlowÄ…\n- SprawdÅº ustawienia czarnej listy sektorÃ³w\n- Poczekaj, aÅ¼ warunki rynkowe siÄ™ poprawiÄ…\n\nBÄ™dÄ™ nadal monitorowaÄ‡ rynek i powiadomiÄ™ CiÄ™, gdy pojawiÄ… siÄ™ zyskowne moÅ¼liwoÅ›ci.\n\nCzekamy,\nNa pokÅ‚adzie Twojej usÅ‚ugi</t>
    <t id="3209">DowÃ³dco,\n\nPILNY ALARM NA TRAsie\n\nMÃ³j system analizy zagroÅ¼eÅ„ wykryÅ‚, Å¼e sektor %1 (poziom zagroÅ¼enia %2) znajduje siÄ™ teraz na moim planowanym szlaku handlowym. Dla bezpieczeÅ„stwa statku i zaÅ‚ogi natychmiast przerywam obecnÄ… operacjÄ™ handlowÄ….\n\nPODJÄ˜TE DZIAÅANIA:\n- Wszystkie zlecenia handlowe anulowane\n- PowrÃ³t do trybu bezpiecznej operacji\n- ZnajdÄ™ alternatywnÄ… trasÄ™ handlowÄ…, ktÃ³ra ominie niebezpieczne sektory\n- ObsÅ‚uga Å‚adunku: Automatyczna (w razie potrzeby sprzeda kaÅ¼dy Å‚adunek w bezpiecznym miejscu)\n\nSystem dynamicznej czarnej listy uniemoÅ¼liwi przyszÅ‚e transakcje w tym sektorze do czasu usuniÄ™cia zagroÅ¼enia.\n\nBezpieczeÅ„stwo jest dla mnie najwaÅ¼niejsze. priorytet.\n\nZ zachowaniem czujnoÅ›ci\nNa pokÅ‚adzie %3</t>
    <t id="3210">DowÃ³dco,\n\nURZÄ„DZONY TRASA UCIECZKI\n\nObecnie znajdujÄ™ siÄ™ na czarnej liÅ›cie sektora %1 i znalazÅ‚em szlak handlowy, ktÃ³ry pozwoli mi bezpiecznie uciec.\n\nTRASA HANDLOWA:\nKup: %2 (Sektor: %3)\nSprzedaj: %4 (Sektor: %5)\nTowary: %6 (x%7)\nOczekiwany zysk: %8 Cr\n\nPo zakoÅ„czeniu tej transakcji statek opuÅ›ci sektor znajdujÄ…cy siÄ™ na czarnej liÅ›cie.\n\nZ wyrazami szacunku,\nNa pokÅ‚adzie Twojej sÅ‚uÅ¼by</t>
    <t id="3211">DowÃ³dco,\n\nIZOLOWANY TRYB HANDLU\n\nJestem obecnie w sektorze %2, ale wszystkie trasy do innych sektorÃ³w sÄ… blokowane przez sektory centralne znajdujÄ…ce siÄ™ na czarnej liÅ›cie. Oznacza to, Å¼e mogÄ™ handlowaÄ‡ tylko w obrÄ™bie mojego obecnego sektora, dopÃ³ki nie zmieni siÄ™ sytuacja na czarnej liÅ›cie.\n\nSYTUACJA:\nBieÅ¼Ä…cy sektor: %2\nStan: Odizolowany (sektor nie znajdujÄ…cy siÄ™ na czarnej liÅ›cie z zablokowanymi trasami)\nTryb handlu: Tylko transakcje wewnÄ…trzsektorowe\n\nMÃ³j system transakcyjny automatycznie dostosowaÅ‚ progi zysku, aby nadaÄ‡ priorytet dostÄ™pnym moÅ¼liwoÅ›ciom handlu wewnÄ…trzsektorowego.\n\nBÄ™dÄ™ nadal monitorowaÄ‡ sytuacjÄ™ i powiadomiÄ‡ CiÄ™, jeÅ›li trasy stanÄ… siÄ™ dostÄ™pne jeszcze raz.\n\nZ wyrazami szacunku,\nNa pokÅ‚adzie %1</t>
    <t id="3218">DowÃ³dco,\n\nWYKRYTO ZMIANÄ˜ TRASY\n\nPo wejÅ›ciu do sektora %1 mÃ³j system nawigacji wykryÅ‚, Å¼e trasa do mojego miejsca docelowego %2 (%3) ulegÅ‚a zmianie.\n\nANALIZA TRASY:\n- Normalny dystans: %4 skokÃ³w\n- OdlegÅ‚oÅ›Ä‡ uwzglÄ™dniana na czarnej liÅ›cie: %5\n- Stan: %6\n\nMoja nawigacja komputer wskazuje, Å¼e preferowana trasa nie jest juÅ¼ wykonalna ze wzglÄ™du na ograniczenia w podrÃ³Å¼owaniu w sektorze. Dla bezpieczeÅ„stwa statku i zaÅ‚ogi natychmiast przerywam obecnÄ… operacjÄ™ handlowÄ….\n\nPODJÄ˜TE DZIAÅANIA:\n- Wszystkie zlecenia handlowe anulowane\n- PowrÃ³t do trybu bezpiecznych operacji\n- ZnajdÄ™ alternatywnÄ… trasÄ™ handlowÄ…, ktÃ³ra ominie zablokowane sektory\n- ObsÅ‚uga Å‚adunku: Automatyczna (w razie potrzeby sprzeda kaÅ¼dy Å‚adunek w bezpiecznym miejscu)\n\nMÃ³j system nawigacji automatycznie ominie zablokowane sektory podczas przyszÅ‚ego planowania trasy.\n\nBezpieczeÅ„stwo jest moim priorytetem.\n\nDziÄ™ki czujnoÅ›Ä‡,\nNa pokÅ‚adzie %7</t>
    <t id="3219">Sektor %1 wyczyszczony - wszystkie zagroÅ¼enia wyeliminowane</t>
    <t id="3220">DowÃ³dco,\n\nWRÃ“G STATEK UCIEKÅ\n\nNasz system wykrywania zagroÅ¼eÅ„ straciÅ‚ trop wrogiego statku %3, ktÃ³ry uciekÅ‚ z sektora znajdujÄ…cego siÄ™ na czarnej liÅ›cie %1.\n\nSZCZEGÃ“ÅY:\n- UciekÅ‚ statek: %3\n- Sektor lewy: %1\n- Sektor docelowy: %2\n- Status: Utracono Å›ledzenie - statek opuÅ›ciÅ‚ nasz monitorowany obszar\n\nChociaÅ¼ ten statek nie stanowi juÅ¼ zagroÅ¼enia w sektorze %1, straciliÅ›my kontakt wzrokowy i nie moÅ¼emy potwierdziÄ‡ jego obecnego stanu ani zamiarÃ³w w sektorze %2.\n\nNasze systemy Å›ledzenia bÄ™dÄ… nadal monitorowaÄ‡ sektor %1 pod kÄ…tem pozostaÅ‚ych zagroÅ¼eÅ„. JeÅ›li wszyscy Å›ledzeni wrogowie opuszczÄ… lub zostanÄ… wyeliminowani, sektor zostanie automatycznie usuniÄ™ty z czarnej listy.\n\nPrzy zachowaniu czujnoÅ›ci\nSystem analizy zagroÅ¼eÅ„</t>
    <t id="3221">DowÃ³dco,\n\nNie udaÅ‚o mi siÄ™ znaleÅºÄ‡ zyskownych okazji do handlu na wiÄ™kszych dystansach (do %3 skokÃ³w), poniewaÅ¼ te trasy sÄ… obecnie niedostÄ™pne ze wzglÄ™du na ograniczenia w podrÃ³Å¼owaniu do sektorÃ³w (Å›cieÅ¼ki na czarnej liÅ›cie).\n\nSYTUACJA:\nBieÅ¼Ä…cy sektor: %2\nOryginalny zakres wyszukiwania: %3 skokÃ³w\nZakres wyszukiwania zastÄ™pczego: %4 skokÃ³w\n\nSkoncentrujÄ™ teraz swoje poszukiwania na pobliskich sektory w obrÄ™bie %4 skokÃ³w, gdzie trasy sÄ… bardziej dostÄ™pne. Powinno mi to pomÃ³c w znalezieniu zyskownych transakcji, ktÃ³re wczeÅ›niej zostaÅ‚y odfiltrowane ze wzglÄ™du na ograniczenia odlegÅ‚oÅ›ci, a nie rzeczywistÄ… nieopÅ‚acalnoÅ›Ä‡.\n\nPowiadomiÄ™ CiÄ™, gdy znajdÄ™ odpowiednie moÅ¼liwoÅ›ci handlowe w pobliskiej okolicy.\n\nZ powaÅ¼aniem,\nNa pokÅ‚adzie %1</t>
    <t id="3222">DowÃ³dco,\n\nSEKTOR NA CZARNEJ LIÅšCIE\n\nNasz system wykrywania zagroÅ¼eÅ„ wykryÅ‚ wrogÄ… dziaÅ‚alnoÅ›Ä‡ w sektorze %1 i automatycznie umieÅ›ciÅ‚ ten sektor na czarnej liÅ›cie, aby chroniÄ‡ nasze operacje handlowe.\n\nWYKRYTE STATKI WROGA:\n%2\n\n WYKRYTE PRZEZ: %3\n\nW trosce o bezpieczeÅ„stwo naszych statkÃ³w i zaÅ‚ogi wszystkie szlaki handlowe przez ten sektor zostaÅ‚y zablokowane. Nasze statki bÄ™dÄ… automatycznie omijaÄ‡ ten sektor, dopÃ³ki zagroÅ¼enie nie zostanie wyeliminowane.\n\nSektor zostanie automatycznie usuniÄ™ty z czarnej listy po wyeliminowaniu wszystkich Å›ledzonych statkÃ³w wroga lub opuszczeniu obszaru.\n\nPrzy zachowaniu czujnoÅ›ci\nSystem wykrywania zagroÅ¼eÅ„</t>
    <t id="3223">DowÃ³dco,\n\nNie mogÄ™ znaleÅºÄ‡ dostÄ™pnej stacji szkoleniowej do egzaminu na poziomie %1. BÄ™dÄ™ kontynuowaÄ‡ transakcje handlowe zgodnie z instrukcjami, ale rozumiem, Å¼e nie zdobÄ™dÄ™ punktÃ³w doÅ›wiadczenia, dopÃ³ki nie ukoÅ„czÄ™ wymaganego szkolenia. Po tej wymianie handlowej ponownie bÄ™dÄ™ szukaÄ‡ okazji do odbycia szkolenia.\n\nZ powaÅ¼aniem,\nNa pokÅ‚adzie %2</t>
    <t id="3224">OpÅ‚ata za licencjÄ™ szkoleniowÄ…: %1 Cr</t>
    <t id="3225">Bonus: ZyskaÅ‚em %1 dodatkowy poziom umiejÄ™tnoÅ›ci%2 dziÄ™ki zgromadzonemu doÅ›wiadczeniu podczas szkolenia! Obecny poziom: %3</t>
    <t id="3214">To zaszczyt dla Ciebie pracowaÄ‡, %1! Jestem podekscytowany moÅ¼liwoÅ›ciÄ… rozpoczÄ™cia mojej kariery handlowej pod Twoim dowÃ³dztwem. DoÅ‚oÅ¼Ä™ wszelkich staraÅ„, aby dobrze Ci sÅ‚uÅ¼yÄ‡ i przyczyniÄ‡ siÄ™ do Twojego sukcesu.</t>
    <t id="3215">DziÄ™kujÄ™ za umoÅ¼liwienie mi tego zasÅ‚uÅ¼onego urlopu, %1! MiÅ‚o spÄ™dziÅ‚em czas z dala od handlu, a moje umiejÄ™tnoÅ›ci pozostaÅ‚y nienaruszone. Nie mogÄ™ siÄ™ doczekaÄ‡ powrotu do pracy, kiedy tylko bÄ™dziesz mnie potrzebowaÄ‡. Do tego czasu bÄ™dÄ™ utrzymywaÄ‡ swojÄ… wiedzÄ™ handlowÄ… na wysokim poziomie!</t>
    <t id="3216">WrÃ³ciÅ‚em z wakacji i znÃ³w jestem gotowy do pracy, %1! Moje umiejÄ™tnoÅ›ci handlowe pozostajÄ… wysokie i chÄ™tnie bÄ™dÄ™ nadal sÅ‚uÅ¼yÄ‡ Ci w dniu %2. DziÄ™kujemy za zasÅ‚uÅ¼ony odpoczynek!</t>
    <t id="3217">DziÄ™kujÄ™ za mÃ³j transfer do %1, %2! Jestem zaszczycony tym nowym zadaniem i doskonale zaopiekujÄ™ siÄ™ moim nowym statkiem. Moje doÅ›wiadczenie handlowe i umiejÄ™tnoÅ›ci pozostajÄ… nienaruszone i jestem gotowy, aby nadal Ci sÅ‚uÅ¼yÄ‡.</t>
    <t id="3227">KadÅ‚ub stracony, godnoÅ›Ä‡ czeka na odbiÃ³r</t>
    <t id="3228">Komandorze %1,\n\n%2 zgÅ‚asza siÄ™ z sektora %3. MÃ³j statek eksplodowaÅ‚. Ja nie. Jestem teraz najdroÅ¼szym unoszÄ…cym siÄ™ Å‚adunkiem floty.\n\nZnacznik na mapie doÅ‚Ä…czony. ProszÄ™ siÄ™ spieszyÄ‡ - byÅ‚em w trakcie faktury.\n\nUnoszÄ…c siÄ™ profesjonalnie,\n%2</t>
    <t id="3229">Pilot uratowany - UzaleÅ¼nienie od tlenu wyleczone</t>
    <t id="3230">Komandorze %1,\n\nAktualizacja floty: %2 zostaÅ‚ zabrany przez %3 (%4) i przestaÅ‚ naliczaÄ‡ przedÅ‚uÅ¼one szkolenie EVA.\n\nTrwa ponowne powiÄ…zanie rejestru. Zalecenie: nie pytaÄ‡ o stary statek.\n\nZe wstydem,\n%2</t>
<t id="4000">Koordynacja floty: %s przydzielono trasÄ™ %s</t>
    <t id="4001">Koordynacja floty: Trasa %s jest w peÅ‚ni wykorzystana</t>
    <t id="4002">Koordynacja floty: %s zwolniÅ‚a trasÄ™ %s</t>
    <t id="5000">%s zostaÅ‚o przypisane jako terytorium gÅ‚Ã³wne dla %s</t>
    <t id="5001">%s osiÄ…gnÄ…Å‚ poziom wiedzy %s w %s!</t>
    <t id="5002">Zastosowano premiÄ™ terytorialnÄ…: %s%% wzrostu zysku w %s</t>
    <t id="9500">BÅ‚Ä…d: %s utknÄ…Å‚ i potrzebuje pomocy!</t>
    <t id="9501">BÅ‚Ä…d: transakcja nie powiodÅ‚a siÄ™ dla %s</t>
    <t id="9502">BÅ‚Ä…d: Nie moÅ¼na zarejestrowaÄ‡ %s w GalaxyTrader MK3</t>
    <t id="80001">Towar %s dodany do czarnej listy</t>
    <t id="80002">Produkt %s usuniÄ™ty z czarnej listy</t>
    <t id="80003">Towar %s dodano do biaÅ‚ej listy</t>
    <t id="80004">Automatycznie na czarnej liÅ›cie (sÅ‚aba wydajnoÅ›Ä‡): %s</t>
    <t id="80005">Priorytetowo traktowane sÄ… niebezpieczne produkty: %s</t>
    <t id="80006">Filtr towarÃ³w: %s aktywny, handel %s zablokowany</t>
    <t id="80007">Wszystkie filtry oprogramowania zostaÅ‚y wyczyszczone</t>
    <t id="80008">Filtry Ware zresetowane do wartoÅ›ci domyÅ›lnych</t>
    <t id="80009">ZarzÄ…dzanie filtrami towarÃ³w</t>
    <t id="80010">Zablokowane towary</t>
    <t id="80011">Dozwolone towary</t>
    <t id="80012">PostÄ™powanie z niebezpiecznymi towarami</t>
    <t id="80013">Minimalna wartoÅ›Ä‡ towaru</t>
    <t id="80014">Maksymalna wartoÅ›Ä‡ towaru</t>
    <t id="80015">Ograniczone frakcje</t>
    <t id="80016">Kategorie przedmiotÃ³w zaktualizowane na podstawie bieÅ¼Ä…cego stanu gry</t>
    <t id="80017">%s towary podzielone na kategorie: %s o niskiej wartoÅ›ci, %s niebezpieczne, %s o wysokiej wartoÅ›ci</t>
    <t id="80018">WÅ‚Ä…czono dynamicznÄ… kategoryzacjÄ™ produktÃ³w</t>
    <t id="80019">Automatyczna czarna lista dla kategorii %s wyÅ‚Ä…czona</t>
    <t id="80020">Wykryto i sklasyfikowano nowe towary z innych modÃ³w</t>
    <t id="9000">GalaxyTrader - Ustawienia globalne</t>
    <t id="9010">XP i system szkolenia</t>
    <t id="9012">Trening automatyczny</t>
    <t id="9013">MnoÅ¼nik XP</t>
    <t id="9015">Procent premii dowÃ³dczej</t>
    <t id="9020">Koordynacja floty</t>
    <t id="9021">WÅ‚Ä…cz koordynacjÄ™ floty</t>
    <t id="9023">WÅ‚Ä…cz pamiÄ™Ä‡ podrÄ™cznÄ… handlu</t>
    <t id="9030">Powiadomienia</t>
    <t id="9031">Poziom powiadomieÅ„</t>
    <t id="9040">System automatycznej naprawy</t>
    <t id="9041">WÅ‚Ä…cz automatycznÄ… naprawÄ™</t>
    <t id="9042">PrÃ³g naprawy kadÅ‚uba</t>
    <t id="9310">GÃ³rnik Galaxy</t>
    <t id="9311">Czas oczekiwania na skan sond w sektorze</t>
    <t id="9312">Waga bliskoÅ›ci statku</t>
    <t id="9043">Minimalny poziom pilota</t>
    <t id="9004">PrzedziaÅ‚y cen handlowych</t>
    <t id="9005">Sprzedam Oferta Cena Max</t>
    <t id="9006">Kup Oferta Cena Min</t>
    <t id="9007">Izolowane: Cena sprzedaÅ¼y maks</t>
    <t id="9008">Izolowane: Kup Cena min</t>
    <t id="9009">RozwiÄ…zanie awaryjne: cena sprzedaÅ¼y maks</t>
    <t id="9014">RozwiÄ…zanie zastÄ™pcze: Kup Cena min</t>
    <t id="9016">Podstawa progu zysku</t>
    <t id="9025">Minimalne pieniÄ…dze gracza</t>
    <t id="9024">Tolerancja usuwania pamiÄ™ci podrÄ™cznej</t>
    <t id="9026">Czas parkowania bezczynnego przed zwolnieniem</t>
    <t id="9054">Blokuj sektory frakcji wroga</t>
    <t id="9055">Poziom zagroÅ¼enia na czarnej liÅ›cie</t>
    <t id="9056">UtwÃ³rz ponownie czarnÄ… listÄ™</t>
    <t id="9057">OdtwarzaÄ‡</t>
    <t id="9058">Przypisz do statkÃ³w GT</t>
    <t id="9059">PrzydzielaÄ‡</t>
    <t id="9112">Automatycznie wysyÅ‚a pilotÃ³w na szkolenie, gdy osiÄ…gnÄ… wymagany poziom. WyÅ‚Ä…cz rÄ™czne sterowanie czasem treningu.</t>
    <t id="9113">Reguluje szybkoÅ›Ä‡ zdobywania doÅ›wiadczenia przez pilotÃ³w. WyÅ¼sze wartoÅ›ci oznaczajÄ… szybszy postÄ™p.</t>
    <t id="9115">Procent podrzÄ™dnego XP przyznanego pilotom-dowÃ³dcom. Ustaw na 0%, aby wyÅ‚Ä…czyÄ‡ dodatkowe PD dowÃ³dcy. DomyÅ›lnie: 10%.</t>
    <t id="9121">UmoÅ¼liwia inteligentne funkcje koordynacji floty, w tym optymalizacjÄ™ tras i rÃ³wnowaÅ¼enie obciÄ…Å¼enia.</t>
    <t id="9123">UmoÅ¼liwia dzielenie siÄ™ zyskownymi moÅ¼liwoÅ›ciami handlowymi pomiÄ™dzy czÅ‚onkami floty w celu lepszej koordynacji.</t>
    <t id="9131">Kontroluje liczbÄ™ wyÅ›wietlanych powiadomieÅ„: 0=Ciche, 1=Tylko waÅ¼ne, 2=Wszystkie powiadomienia</t>
    <t id="9141">Automatycznie wysyÅ‚a statki do naprawy po zakoÅ„czeniu transakcji, gdy kadÅ‚ub spadnie poniÅ¼ej progu. Tylko dla doÅ›wiadczonych pilotÃ³w (poziom 12+). Statki wybierajÄ… odpowiedni obiekt: Dok SprzÄ™towy S/M, Stocznia L/XL.</t>
    <t id="9142">Procent kadÅ‚uba, poniÅ¼ej ktÃ³rego uruchamiana jest automatyczna naprawa. DomyÅ›lnie: 95%. W przypadku uszkodzenia statki automatycznie udajÄ… siÄ™ do najbliÅ¼szego zakÅ‚adu naprawczego.</t>
    <t id="9411">Po wÅ‚Ä…czeniu gÃ³rnicy czekajÄ… podczas oceny sond zasobÃ³w frakcji w sektorze (+5 s za kaÅ¼dÄ… sondÄ™ powyÅ¼ej jednej). Poziom GT pilota liniowo skraca ten czas od peÅ‚nego na poziomie 1 do 5 sekund na poziomie 15 (tylko tryb XP GT, gdy czas przekracza 5 s). WyÅ‚Ä…czone = brak oczekiwania (zachowanie vanilla).</t>
    <t id="9412">SkÅ‚ania statki MK3/MK4 do bliÅ¼szych stacji kupna przy sortowaniu zatwierdzonych transakcji. Wynik selekcji = wynik transakcji / (1 + skoki statekâ†’kupno Ã— waga). Suwak 0-100 (0 = wyÅ‚.; 4 = domyÅ›lnie 0,04). Nie wpÅ‚ywa na ranking cache ani limity zasiÄ™gu terytorialnego.</t>
    <t id="9143">Minimalny poziom pilota wymagany do funkcji automatycznej naprawy. DomyÅ›lnie: 12 (doÅ›wiadczeni handlarze). Piloci niÅ¼szego poziomu muszÄ… naprawiaÄ‡ rÄ™cznie.</t>
    <t id="9104">Maksymalna cena wzglÄ™dna dla ofert sprzedaÅ¼y (statek kupuje OD stacji). Zakres: -1,0 do +1,0. DomyÅ›lnie: 0,5 (50% powyÅ¼ej Å›redniej). WyÅ¼szy = droÅ¼szy, ale wiÄ™cej opcji.</t>
    <t id="9105">Minimalna cena wzglÄ™dna dla ofert kupna (statek sprzedaje stacje TO). Zakres: -1,0 do +1,0. DomyÅ›lnie: -0,5 (50% poniÅ¼ej Å›redniej). NiÅ¼szy = taÅ„si kupujÄ…cy, ale wiÄ™cej opcji.</t>
    <t id="9106">Maksymalna cena sprzedaÅ¼y dla izolowanych statkÃ³w (utkniÄ™tych w jednym sektorze). Zakres: -1,0 do +1,0. WartoÅ›Ä‡ domyÅ›lna: 0,5.</t>
    <t id="9107">Kup cenÄ™ min. dla izolowanych statkÃ³w (utkniÄ™tych w jednym sektorze). Zakres: -1,0 do +1,0. WartoÅ›Ä‡ domyÅ›lna: -0,5.</t>
    <t id="9108">Sprzedaj cenÄ™ maksymalnÄ… w przypadku wyszukiwania zastÄ™pczego (ostatecznoÅ›Ä‡, gdy normalne wyszukiwanie nie powiedzie siÄ™). Zakres: -1,0 do +1,0. WartoÅ›Ä‡ domyÅ›lna: 0,5. Wyszukiwanie zastÄ™pcze wykorzystuje MaxDistance=2 i luÅºne progi zysku.</t>
    <t id="9109">Kup cenÄ™ minimalnÄ… w przypadku wyszukiwania zastÄ™pczego (ostatecznoÅ›Ä‡, gdy normalne wyszukiwanie nie powiedzie siÄ™). Zakres: -1,0 do +1,0. WartoÅ›Ä‡ domyÅ›lna: -0,5. Wyszukiwanie zastÄ™pcze wykorzystuje MaxDistance=2 i luÅºne progi zysku.</t>
    <t id="9116">Podstawowy minimalny zysk na poziomie 15 dla Å›redniego handlowca (Å‚adunek referencyjny 8200). Rzeczywisty MinAbsoluteProfit jest obliczany na pilota + skalowany wedÅ‚ug Å‚adunku:\n\npodstawa(L) = podstawa * ((L-1)^2 / 14^2)\nskalowany = podstawa(L) * (Å‚adunek / 8200)\nkoÅ„cowy = max(skalowany, 25% podstawy(L))\n\nUstaw na 0, aby zaakceptowaÄ‡ dowolny zysk (obowiÄ…zujÄ… tylko ROI/odlegÅ‚oÅ›Ä‡/inne filtry).</t>
    <t id="9125">Minimalna iloÅ›Ä‡ pieniÄ™dzy gracza (kredytÃ³w) wymagana, zanim statki zacznÄ… szukaÄ‡ okazji do wymiany. Kiedy pieniÄ…dze gracza spadnÄ… poniÅ¼ej tego progu, wszystkie statki pomijajÄ… wyszukiwanie transakcji i czekajÄ…, zapobiegajÄ…c kosztownemu skanowaniu pamiÄ™ci podrÄ™cznej, ktÃ³re powoduje zacinanie siÄ™ gry. Zakres: 1 000 - 100 000 Kr. WartoÅ›Ä‡ domyÅ›lna: 1000 kr.</t>
    <t id="9124">Maksymalny procentowy spadek ROI z wartoÅ›ci buforowanej przed odrzuceniem transakcji. PrzykÅ‚ad: 20% buforowanego ROI z tolerancjÄ… 15% akceptuje ROI do 17% (spadek o 14%).</t>
    <t id="9126">Minuty zacumowane przed odcumowaniem w celu zwolnienia portu (0-60). 0 = pozostaje zacumowany do znalezienia nowej pracy. DomyÅ›lnie: 1 minuta.</t>
    <t id="9154">Automatycznie umieszczaj na czarnej liÅ›cie wszystkie sektory naleÅ¼Ä…ce do wrogich frakcji (pole wyboru relacji na czarnej liÅ›cie)</t>
    <t id="9155">Minimalny poziom zagroÅ¼enia (1-5) wymagany do umieszczenia sektora na czarnej liÅ›cie:\n2=Åšredni (pojedynczy atak)\n3=Åšrednio-wysoki (wrogie frakcje)\n4=Wysoki (statki/pociski kapitaÅ‚owe)\n5=Bardzo wysoki (Xenon/Khaak)</t>
    <t id="9156">RÄ™cznie odtwÃ³rz czarnÄ… listÄ™ unikania zagroÅ¼eÅ„ (przydatne, jeÅ›li zostaÅ‚a usuniÄ™ta)</t>
    <t id="9157">RÄ™cznie przypisz bieÅ¼Ä…cÄ… dynamicznÄ… czarnÄ… listÄ™ do wszystkich statkÃ³w dowÃ³dcÃ³w floty GT. PodwÅ‚adni dziedziczÄ… po swoim dowÃ³dcy.</t>
    <t id="6001">UczeÅ„</t>
    <t id="6002">Kurier</t>
    <t id="6003">Dostawca</t>
    <t id="6004">Handlowiec</t>
    <t id="6005">Kupiec</t>
    <t id="6006">Sprzedawca dalekobieÅ¼ny</t>
    <t id="6101">ZrÃ³wnowaÅ¼ony</t>
    <t id="6102">Obronny</t>
    <t id="6103">Skoncentrowany na handlu</t>
    <t id="6104">CiÄ™Å¼ka obrona</t>
    <t id="6105">Wsparcie wieÅ¼y</t>
    <t id="9050">System unikania zagroÅ¼eÅ„</t>
    <t id="9051">WÅ‚Ä…cz unikanie zagroÅ¼eÅ„:</t>
    <t id="9052">PrÃ³g wrogiej relacji:</t>
    <t id="9053">UÅ¼yj dynamicznej czarnej listy:</t>
    <t id="9151">Handlarze na poziomie 6 lub wyÅ¼szym wykrywajÄ… wrogie statki i unikajÄ… niebezpiecznych tras. WyÅ‚Ä…czenie zatrzymuje caÅ‚e skanowanie (poprawia wydajnoÅ›Ä‡). Tolerancja ryzyka na statek w zachowaniu dowodzenia (skala 0-10).</t>
    <t id="9152">Oznacz jako zagroÅ¼enie tylko frakcje, ktÃ³rych relacja jest rÃ³wna lub niÅ¼sza od tej wartoÅ›ci. DomyÅ›lnie: -20%</t>
    <t id="9153">Automatycznie umieszczaj na czarnej liÅ›cie niebezpieczne sektory (poziom zagroÅ¼enia 3+), aby zmusiÄ‡ statki do omijania zagroÅ¼eÅ„. UÅ¼ywa podstawowego wyszukiwania Å›cieÅ¼ek dla alternatywnych tras.</t>
    <t id="9060">Automatyczne uzupeÅ‚nianie wyposaÅ¼enia obronnego (poziom 15)</t>
    <t id="9061">WÅ‚Ä…cz automatyczne uzupeÅ‚nianie:</t>
    <t id="9062">Åšrodki zaradcze dotyczÄ…ce uzupeÅ‚nienia zapasÃ³w:</t>
    <t id="9063">UzupeÅ‚nij zapasy dronÃ³w obronnych:</t>
    <t id="9064">UzupeÅ‚nij zapasy dronÃ³w handlowych:</t>
    <t id="9065">UzupeÅ‚nij wieÅ¼e laserowe:</t>
    <t id="9066">UzupeÅ‚nij zapasy dronÃ³w naprawczych:</t>
    <t id="9067">PrÃ³g przeciwdziaÅ‚ania:</t>
    <t id="9068">Ujednolicony prÃ³g pojemnoÅ›ci:</t>
    <t id="9069">Profil rÃ³wnowagi sprzÄ™tu:</t>
    <t id="9161">Mistrzowie Handlowi (poziom 15) automatycznie uzupeÅ‚niajÄ… sprzÄ™t obronny po transakcjach. Dotyczy poziomu dowÃ³dcy dla podwÅ‚adnych.</t>
    <t id="9162">Wszystkie statki (S/M/L/XL). Oddzielna pojemnoÅ›Ä‡. Krytyczne dla obrony przeciwrakietowej.</t>
    <t id="9163">Tylko statki L/XL. Dzieli ujednoliconÄ… pojemnoÅ›Ä‡ z innymi urzÄ…dzeniami do wdroÅ¼enia.</t>
    <t id="9164">Tylko statki L/XL. NiezbÄ™dne do operacji handlowych. UdostÄ™pnia ujednoliconÄ… pojemnoÅ›Ä‡.</t>
    <t id="9165">Wszystkie statki. Statki L/XL majÄ… wspÃ³lnÄ… pojemnoÅ›Ä‡, S/M korzystajÄ… z Å‚adunku.</t>
    <t id="9166">Tylko statki L/XL. WspÃ³Å‚pracuje z systemem automatycznej naprawy. UdostÄ™pnia ujednoliconÄ… pojemnoÅ›Ä‡.</t>
    <t id="9167">UzupeÅ‚nij zapasy, gdy Å›rodki zaradcze bÄ™dÄ… mniejsze niÅ¼ ten procent (wszystkie statki, osobna pojemnoÅ›Ä‡).</t>
    <t id="9168">UzupeÅ‚nij zapasy, gdy Å‚Ä…czna liczba jednostek do rozmieszczenia spadnie poniÅ¼ej tego procentu (statki L/XL: drony i wieÅ¼e majÄ… tÄ™ samÄ… pojemnoÅ›Ä‡).</t>
    <t id="9169">Dystrybucja ujednoliconej pojemnoÅ›ci (statki L/XL): Skupiona na handlu (20/50/20/10), ZrÃ³wnowaÅ¼ona (35/35/20/10), Defensywna (50/20/20/10), CiÄ™Å¼ka obrona (40/30/20/10), Wsparcie wieÅ¼y (30/30/30/10). Stosunki: Obrona/Handel/WieÅ¼e/Naprawa. Kliknij, aby przeÅ‚Ä…czaÄ‡ opcje.</t>
    <t id="9090">Modyfikacje statku</t>
    <t id="9091">WÅ‚Ä…cz modyfikacje statku</t>
    <t id="9191">Automatycznie instaluj modyfikacje statku i silnika w oparciu o poziom pilota. Poziom 9+ = mody poziomu 1, Poziom 12+ = mody poziomu 2, Poziom 15+ = mody poziomu 3. W przypadku anulowania zamÃ³wienia usuwane sÄ… tylko mody zainstalowane w GT.</t>
    <t id="9070">Konfiguracja nazewnictwa statkÃ³w</t>
    <t id="9071">WyÅ›wietl XP:</t>
    <t id="9072">Ranking wyÅ›wietlania:</t>
    <t id="9073">Poziom wyÅ›wietlania:</t>
    <t id="9074">Stan wyÅ›wietlania:</t>
    <t id="9075">WÅ‚Ä…cz zmianÄ™ nazwy statku:</t>
    <t id="9076">Prefiks</t>
    <t id="9077">Przyrostek</t>
    <t id="9078">DomyÅ›lne ÅºrÃ³dÅ‚o nazwy:</t>
    <t id="9079">Nazwa modelu</t>
    <t id="9080">Wpisz nazwÄ™</t>
    <t id="9081">Baza modelu</t>
    <t id="9083">Nazwa niestandardowa</t>
    <t id="9084">WyÅ›wietl sektor macierzysty:</t>
    <t id="9085">Tryb nazewnictwa:</t>
    <t id="9086">Klasyczny</t>
    <t id="9087">Wzorzec</t>
    <t id="9088">Wzorzec nazwy:</t>
    <t id="9089">Tokeny: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. Atomowe: {RS} {CB} {BL} itd. UÅ¼ywa skrÃ³tÃ³w stanu poniÅ¼ej. Puste tokeny sÄ… pomijane; spacje siÄ™ redukujÄ…. Maks. 128 znakÃ³w.</t>
    <t id="9183">PokaÅ¼ skonfigurowany sektor macierzysty w nazwie statku (prefiks lub sufiks).</t>
    <t id="9184">Niestandardowy format nazwy z tokenami {TOKEN} zamiast klasycznych przeÅ‚Ä…cznikÃ³w. Wymaga XP GalaxyTrader (nie tryb vanilla XP).</t>
    <t id="9092">Tokeny wzorca</t>
    <t id="9093">Statek: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Baza: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">ZaÅ‚oga: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Sektor: {SECTOR} | Statystyki: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Tokeny statusu:</t>
    <t id="9100">{OPSTATE}: wszystkie aktywne flagi operacyjne (np. CB RS, MT)</t>
    <t id="9101">{STATUS}: zablokowany, szkolenie, rezerwa lub odciÄ™ty</t>
    <t id="9102">{CB}: tylko wÅ‚asna blacklista; zawarte w {OPSTATE}; nie Å‚Ä…czyÄ‡</t>
    <t id="9082">WyÅ›wietl klasÄ™ statku:</t>
    <t id="9171">PokaÅ¼ wartoÅ›ci XP w nazwach statkÃ³w</t>
    <t id="9175">WÅ‚Ä…cz lub wyÅ‚Ä…cz automatycznÄ… zmianÄ™ nazwy statku na podstawie informacji o pilocie</t>
    <t id="9172">PokaÅ¼ tytuÅ‚y rang w nazwach statkÃ³w</t>
    <t id="9173">PokaÅ¼ numery poziomÃ³w w nazwach statkÃ³w</t>
    <t id="9174">PokaÅ¼ status handlowy w nazwach statkÃ³w</t>
    <t id="9178">Wybierz ÅºrÃ³dÅ‚o podstawowych nazw statkÃ³w: Nazwa modelu (z wariantem), Nazwa typu (ogÃ³lna), Baza modelu (bez wariantu) lub Nazwa niestandardowa (nazwa przechowywana)</t>
    <t id="9182">PokaÅ¼ klasÄ™ statku (S, M, L, XL) w nazwach statkÃ³w</t>
    <t id="9200">Ustawienia debugowania</t>
    <t id="9201">WÅ‚Ä…cz rejestrowanie debugowania:</t>
    <t id="9202">GÅ‚Ã³wny przeÅ‚Ä…cznik dla wszystkich wynikÃ³w debug_text. Gdy ta opcja jest wyÅ‚Ä…czona, wszelkie rejestrowanie debugowania jest pomijane. Po wÅ‚Ä…czeniu komunikaty debugowania pojawiajÄ… siÄ™ w dzienniku debugowania w oparciu o indywidualne wartoÅ›ci szans debug_text.</t>
    <t id="9220">Konserwacja i diagnostyka</t>
    <t id="9221">Zresetuj statystyki zyskÃ³w:</t>
    <t id="9222">NASTAWIÄ†</t>
    <t id="9223">UsuÅ„ wszystkie sektory z czarnej listy:</t>
    <t id="9224">JASNE</t>
    <t id="9225">Zresetuj wszystkie ustawienia do wartoÅ›ci domyÅ›lnych:</t>
    <t id="9226">ZRESETUJ WSZYSTKO</t>
    <t id="9323">Usuwa wszystkie sektory z czarnej listy analizy zagroÅ¼eÅ„. Spowoduje to natychmiastowe wyczyszczenie wszystkich sektorÃ³w znajdujÄ…cych siÄ™ na czarnej liÅ›cie i umoÅ¼liwi Twoim statkom podrÃ³Å¼ do wczeÅ›niej zablokowanych obszarÃ³w. UÅ¼yj tej opcji, jeÅ›li chcesz zresetowaÄ‡ system unikania zagroÅ¼eÅ„ lub jeÅ›li sektory zostaÅ‚y nieprawidÅ‚owo umieszczone na czarnej liÅ›cie.</t>
    <t id="9321">Resetuje wszystkie statystyki zyskÃ³w do 0 dla wszystkich pilotÃ³w i statkÃ³w. UÅ¼yj tej opcji po aktualizacji do wersji 0.6.0, aby wyczyÅ›ciÄ‡ zawyÅ¼one statystyki oparte na przychodach. Poprawka Å›ledzi teraz rzeczywisty ZYSK (przychÃ³d - koszt zakupu). Liczby handlowe i XP zostajÄ… zachowane.</t>
    <t id="9325">Resetuje wszystkie ustawienia globalne do wartoÅ›ci domyÅ›lnych. Obejmuje to ustawienia XP, koordynacjÄ™ floty, powiadomienia, mobilne informacje wywiadowcze, unikanie zagroÅ¼eÅ„, nazewnictwo statkÃ³w, automatycznÄ… naprawÄ™, modyfikacje, wydajnoÅ›Ä‡ i ustawienia formatu liczb. Ustawienie rejestrowania debugowania zostaje zachowane, aby umoÅ¼liwiÄ‡ rejestrowanie operacji resetowania.</t>
    <t id="9227">WyczyÅ›Ä‡ pamiÄ™Ä‡ podrÄ™cznÄ… handlu dla wszystkich sektorÃ³w domowych:</t>
    <t id="9228">WYCZYÅšÄ† PAMIÄ˜Ä†</t>
    <t id="9327">CzyÅ›ci pamiÄ™Ä‡ podrÄ™cznÄ… handlu dla wszystkich sektorÃ³w macierzystych. Zmusi to wszystkie statki do przeprowadzenia nowych poszukiwaÅ„ na Å¼ywo podczas nastÄ™pnego wyszukiwania handlu. UÅ¼yj tej opcji, jeÅ›li pamiÄ™Ä‡ podrÄ™czna wydaje siÄ™ nieaktualna lub uszkodzona albo jeÅ›li chcesz wymusiÄ‡ peÅ‚ne odÅ›wieÅ¼enie pamiÄ™ci podrÄ™cznej.</t>
    <t id="9229">Zwolnij wszystkie blokady wyszukiwania</t>
    <t id="9329">Zwalnia WSZYSTKIE blokady wyszukiwania handlu w locie i kasuje powiÄ…zany stan przejÅ›ciowy. UÅ¼yj tej opcji, jeÅ›li statki utknÄ™Å‚y w trybie â€žWyszukiwanie transakcjiâ€ z powodu nieaktualnych zamkÃ³w ze starych zapisÃ³w. MoÅ¼e to przerwaÄ‡ legalne wyszukiwania.</t>
    <t id="9290">Stan centrum handlu zrzutowego:</t>
    <t id="9291">WYSYPISKO</t>
    <t id="9390">Pokazuje jednorazowÄ… migawkÄ™ scentralizowanego centrum handlu (kolejki harmonogramu + status ostatniego statku, ktÃ³ry zaÅ¼Ä…daÅ‚) w dzienniku i jako powiadomienie.</t>
    <t id="9292">ZrzuÄ‡ pamiÄ™Ä‡ podrÄ™cznÄ… transakcji (PEÅNA):</t>
    <t id="9293">ZRZUÄ† PAMIÄ˜Ä† PODRÄ˜CZNÄ„</t>
    <t id="9392">PEÅNY zrzut pamiÄ™ci podrÄ™cznej (moÅ¼e byÄ‡ ogromny). Zapisuje wszystkie wpisy pamiÄ™ci podrÄ™cznej w DebugLog w fragmentach. Kliknij ponownie, aby anulowaÄ‡.</t>
    <t id="9294">WyczyÅ›Ä‡ rezerwacje floty:</t>
    <t id="9295">JASNE</t>
    <t id="9394">CzyÅ›ci wszystkie aktywne rezerwacje handlowe floty. UÅ¼yj tej opcji, jeÅ›li statki wydajÄ… siÄ™ utknÄ…Ä‡ w oczekiwaniu na wygaÅ›niÄ™cie zarezerwowanych transakcji lub jeÅ›li tabela rezerwacji staÅ‚a siÄ™ nieaktualna po wczytaniu starego zapisu.</t>
    <t id="9230">WydajnoÅ›Ä‡</t>
    <t id="9231">OpÃ³Åºnienie przetwarzania wsadowego:</t>
    <t id="9232">OpÃ³Åºnienie walidacji:</t>
    <t id="9233">Maksymalna liczba jednoczesnych wyszukiwaÅ„:</t>
    <t id="9234">Maksymalna liczba transakcji do zwrotu:</t>
    <t id="9235">Maksymalna liczba ofert na towar:</t>
    <t id="9236">Maksymalna liczba transakcji na towar:</t>
    <t id="9237">Maksymalna liczba ofert na towar w celu dopasowania:</t>
    <t id="9238">PrÃ³g wczesnego wyjÅ›cia:</t>
    <t id="9241">InterwaÅ‚ fragmentu oferty na Å¼ywo:</t>
    <t id="9266">Wyszukaj blokadÄ™ TTL:</t>
    <t id="9263">Rozmiar porcji partii:</t>
    <t id="9239">Format liczb</t>
    <t id="9240">Styl formatu:</t>
    <t id="9242">UÅ¼yj przyrostka M</t>
    <t id="9243">PrÃ³g przyrostka M:</t>
    <t id="9244">Niemiecki (123.456,78)</t>
    <t id="9245">angielski (123 456,78)</t>
    <t id="9510">Powiadomienia o awansie poziomu:</t>
    <t id="9511">Alerty o wymaganym szkoleniu:</t>
    <t id="9512">Powiadomienia o ukoÅ„czeniu szkolenia:</t>
    <t id="9513">Raporty zyskÃ³w:</t>
    <t id="9514">Alerty rynkowe:</t>
    <t id="9515">Aktualizacje floty:</t>
    <t id="9516">UÅ¼ywaj tylko wanilii XP</t>
    <t id="9610">WÅ‚Ä…cz lub wyÅ‚Ä…cz wyskakujÄ…ce powiadomienia o awansie poziomu handlowca w interfejsie gracza.</t>
    <t id="9611">Alert, gdy piloci potrzebujÄ… szkolenia, aby awansowaÄ‡ na nastÄ™pny poziom.</t>
    <t id="9612">Powiadomienie, gdy piloci ukoÅ„czÄ… szkolenie i awansujÄ… w randze.</t>
    <t id="9613">Okresowe podsumowania zyskÃ³w (raporty proste i kompleksowe).</t>
    <t id="9614">WyjÄ…tkowe okazje rynkowe i alerty o wysokowartoÅ›ciowych transakcjach.</t>
    <t id="9615">WiadomoÅ›ci koordynacji floty i aktualizacje statusu.</t>
    <t id="9616">UÅ¼yj pilota.skill.piloting i wyÅ‚Ä…cz GT XP progresjÄ™/ograniczenia.</t>
    <t id="9246">Prosta czÄ™stotliwoÅ›Ä‡ raportÃ³w:</t>
    <t id="9247">CzÄ™stotliwoÅ›Ä‡ raportÃ³w kompleksowych:</t>
    <t id="9248">Maksymalna liczba jednoczesnych wyszukiwaÅ„ w pamiÄ™ci podrÄ™cznej:</t>
    <t id="9249">Maksymalna liczba jednoczesnych wyszukiwaÅ„ na Å¼ywo:</t>
    <t id="9340">Wybierz format liczb: w jÄ™zyku niemieckim uÅ¼ywa siÄ™ â€ž.â€ dla tysiÄ™cy i â€ž,â€ dla miejsc dziesiÄ™tnych (123.456,78), w jÄ™zyku angielskim uÅ¼ywa siÄ™ â€ž,â€ dla tysiÄ™cy i â€ž.â€ dla miejsc dziesiÄ™tnych (123 456,78)</t>
    <t id="9342">WÅ‚Ä…cz przyrostek M dla liczb wiÄ™kszych niÅ¼ prÃ³g (np. 1,0 M zamiast 1 000 000)</t>
    <t id="9343">PrÃ³g dla przyrostka M. Liczby powyÅ¼ej tej wartoÅ›ci bÄ™dÄ… wyÅ›wietlane z przyrostkiem M (domyÅ›lnie: 999,999)</t>
    <t id="9346">CzÄ™stotliwoÅ›Ä‡ prostego raportu (powiadomienie wyskakujÄ…ce): 0-30 minut (0 = wyÅ‚Ä…czone - proste raporty sÄ… wyÅ‚Ä…czone, domyÅ›lnie: 1 minuta)</t>
    <t id="9347">CzÄ™stotliwoÅ›Ä‡ kompleksowego raportu (wpis do dziennika): 0-60 minut (0 = wyÅ‚Ä…czone - kompleksowe raporty sÄ… wyÅ‚Ä…czone, domyÅ›lnie: 30 minut)</t>
    <t id="9398">UÅ¼yj naleÅ¼nego zastÄ…pienia Å›rodkÃ³w GT</t>
    <t id="9399">ZastÄ…p lub uzupeÅ‚nij zwykÅ‚Ä… liniÄ™ â€žCR z tytuÅ‚u transakcjiâ€ przewidywanÄ… wartoÅ›ciÄ… GT w tym samym miejscu interfejsu uÅ¼ytkownika.</t>
    <t id="9331">OpÃ³Åºnienie pomiÄ™dzy partiami podczas przetwarzania wyszukiwania transakcji (1-500ms). WyÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale spowalniajÄ… wyszukiwanie transakcji. WartoÅ›Ä‡ domyÅ›lna: 120 ms. UÅ¼ywany w przetwarzaniu wsadowym i filtrowaniu list handlowych.</t>
    <t id="9332">OpÃ³Åºnienie miÄ™dzy walidacjami transakcji w skrypcie AI (1-500ms). WyÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale spowalniajÄ… walidacjÄ™ transakcji. WartoÅ›Ä‡ domyÅ›lna: 50 ms. UÅ¼ywane podczas sprawdzania listy transakcji z systemu MD.</t>
    <t id="9333">Maksymalna liczba wyszukiwaÅ„ branÅ¼owych, ktÃ³re mogÄ… odbywaÄ‡ siÄ™ jednoczeÅ›nie (1-10). NiÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale wydÅ‚uÅ¼ajÄ… czas oczekiwania w kolejce. WyÅ¼sze wartoÅ›ci przetwarzajÄ… wyszukiwania szybciej, ale mogÄ… powodowaÄ‡ skoki wydajnoÅ›ci. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9334">Maksymalna liczba transakcji zwracanych z wyszukiwania w pamiÄ™ci podrÄ™cznej (1-100). WyÅ¼sze wartoÅ›ci zapewniajÄ… wiÄ™cej opcji handlu, ale wydÅ‚uÅ¼ajÄ… czas sprawdzania poprawnoÅ›ci pamiÄ™ci podrÄ™cznej. NiÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale mogÄ… pomijaÄ‡ opÅ‚acalne transakcje. WartoÅ›Ä‡ domyÅ›lna: 20.</t>
    <t id="9335">Maksymalna liczba ofert na oprogramowanie do przetworzenia w wyszukiwaniu na Å¼ywo (5-100). WyÅ¼sze wartoÅ›ci uwzglÄ™dniajÄ… wiÄ™cej ofert, ale wydÅ‚uÅ¼ajÄ… czas przetwarzania. NiÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale mogÄ… pominÄ…Ä‡ zyskowne transakcje. WartoÅ›Ä‡ domyÅ›lna: 20.</t>
    <t id="9336">Maksymalna liczba transakcji na towar podczas przetwarzania wsadowego (5-100). WyÅ¼sze wartoÅ›ci umoÅ¼liwiajÄ… wiÄ™kszÄ… liczbÄ™ transakcji na towar, ale wydÅ‚uÅ¼ajÄ… czas przetwarzania. NiÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale mogÄ… pominÄ…Ä‡ zyskowne transakcje. WartoÅ›Ä‡ domyÅ›lna: 20.</t>
    <t id="9337">Maksymalna liczba ofert na towar do dopasowania w procesorze wsadowym (5-100). WyÅ¼sze wartoÅ›ci uwzglÄ™dniajÄ… wiÄ™cej ofert, ale wydÅ‚uÅ¼ajÄ… czas przetwarzania. NiÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale mogÄ… pominÄ…Ä‡ zyskowne transakcje. WartoÅ›Ä‡ domyÅ›lna: 20.</t>
    <t id="9338">PrÃ³g wczesnego wyjÅ›cia dla przetwarzania wsadowego (100-10000). Po znalezieniu takiej liczby transakcji przetwarzanie wsadowe zatrzymuje siÄ™ wczeÅ›niej, aby zaoszczÄ™dziÄ‡ procesor. WyÅ¼sze wartoÅ›ci przetwarzajÄ… wiÄ™cej transakcji, ale zwiÄ™kszajÄ… obciÄ…Å¼enie procesora. NiÅ¼sze wartoÅ›ci wychodzÄ… szybciej, ale mogÄ… przegapiÄ‡ zyskowne transakcje. WartoÅ›Ä‡ domyÅ›lna: 2000.</t>
    <t id="9341">InterwaÅ‚ wycinka oferty na Å¼ywo w milisekundach (5-2000 ms). Kontroluje czÄ™stotliwoÅ›Ä‡ uruchamiania fragmentÃ³w oferty na Å¼ywo. NiÅ¼sze wartoÅ›ci umoÅ¼liwiajÄ… szybsze zbieranie ofert, ale zwiÄ™kszajÄ… obciÄ…Å¼enie procesora. WyÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale spowalniajÄ… przetwarzanie wyszukiwania na Å¼ywo. WartoÅ›Ä‡ domyÅ›lna: 500 ms.</t>
    <t id="9363">Rozmiar porcji przetwarzania wsadowego (5-20). Przetwarza kombinacje chunkSizeÃ—chunkSize na porcjÄ™ (np. 5Ã—5 = 25 kombinacji). WiÄ™ksze porcje poprawiajÄ… przepustowoÅ›Ä‡, ale zwiÄ™kszajÄ… obciÄ…Å¼enie procesora na porcjÄ™. Mniejsze fragmenty zmniejszajÄ… skoki wydajnoÅ›ci procesora, ale wymagajÄ… wiÄ™kszej liczby kontynuacji. WartoÅ›Ä‡ domyÅ›lna: 5.</t>
    <t id="9348">Maksymalna liczba przeszukiwaÅ„ pamiÄ™ci podrÄ™cznej, ktÃ³re moÅ¼na uruchomiÄ‡ jednoczeÅ›nie (1-20). Wyszukiwanie pamiÄ™ci podrÄ™cznej jest szybkie i tanie; niÅ¼sze wartoÅ›ci mogÄ… zmniejszyÄ‡ ryzyko wybuchu w przypadku duÅ¼ych flot. WartoÅ›Ä‡ domyÅ›lna: 2.</t>
    <t id="9349">Maksymalna liczba wyszukiwaÅ„ na Å¼ywo, ktÃ³re mogÄ… odbywaÄ‡ siÄ™ jednoczeÅ›nie (1-10). Wyszukiwania na Å¼ywo intensywnie obciÄ…Å¼ajÄ… procesor, wiÄ™c niÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale wydÅ‚uÅ¼ajÄ… czas oczekiwania w kolejce. WyÅ¼sze wartoÅ›ci przetwarzajÄ… wyszukiwania szybciej, ale mogÄ… powodowaÄ‡ skoki wydajnoÅ›ci. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9264">Rozmiar fragmentu zapytania o pamiÄ™Ä‡ podrÄ™cznÄ…:</t>
    <t id="9265">Oferta na Å¼ywo DoÅ‚Ä…cz rozmiar fragmentu:</t>
    <t id="9364">Wpisy w pamiÄ™ci podrÄ™cznej sprawdzane wedÅ‚ug fragmentu (10-200). Mniejsze wartoÅ›ci rozkÅ‚adajÄ… weryfikacjÄ™ pamiÄ™ci podrÄ™cznej na wiÄ™cej ramek (pÅ‚ynniej), ale mogÄ… wydÅ‚uÅ¼yÄ‡ czas znalezienia transakcji w pamiÄ™ci podrÄ™cznej. WartoÅ›Ä‡ domyÅ›lna: 10.</t>
    <t id="9365">Oferty doÅ‚Ä…czane na wycinek doÅ‚Ä…czania (50-2000). Mniejsze wartoÅ›ci ograniczajÄ… pracÄ™ zwiÄ…zanÄ… z dodawaniem list do poszczegÃ³lnych klatek (pÅ‚ynniej), ale mogÄ… spowolniÄ‡ zakoÅ„czenie wyszukiwania na Å¼ywo. WartoÅ›Ä‡ domyÅ›lna: 200.</t>
    <t id="9366">Wyszukaj czas Å¼ycia blokady w sekundach (60-7200). JeÅ›li statek zostanie odrzucony, a â€žwyszukiwanie handlu jest juÅ¼ w tokuâ€ przez dÅ‚uÅ¼szy czas, GT samoleczy siÄ™, usuwajÄ…c nieaktualny stan wyszukiwania i zwalniajÄ…c blokadÄ™. WartoÅ›Ä‡ domyÅ›lna: 600 s.</t>
    <t id="9370">Åagodny prÃ³g przeciwciÅ›nienia wsadowego:</t>
    <t id="9371">Twardy prÃ³g przeciwciÅ›nienia wsadowego:</t>
    <t id="9372">Sektory na plasterek:</t>
    <t id="9373">Czas odnowienia w domu:</t>
    <t id="9374">Baza czasu odnowienia braku pamiÄ™ci podrÄ™cznej:</t>
    <t id="9375">InterwaÅ‚ zaznaczenia harmonogramu:</t>
    <t id="9376">Maksymalna liczba zapytaÅ„ dotyczÄ…cych pamiÄ™ci podrÄ™cznej na takt:</t>
    <t id="9377">Maksymalna liczba kontynuacji wyszukiwania na tick:</t>
    <t id="9378">Maksymalna liczba statkÃ³w na takt:</t>
    <t id="9379">Maksymalna liczba elementÃ³w na tick:</t>
    <t id="9380">Maksymalne wybudzenie na takt:</t>
    <t id="9381">Maksymalna liczba wpisÃ³w zapytaÅ„ o pamiÄ™Ä‡ podrÄ™cznÄ…:</t>
    <t id="9382">Nieaktualne progowe sekundy:</t>
    <t id="9383">PrÃ³g nieaktualnoÅ›ci kolejki w sekundach:</t>
    <t id="9384">Sekundy wygaÅ›niÄ™cia nieudanej transakcji:</t>
    <t id="9385">Maksymalna liczba jednoczesnych wyszukiwaÅ„ zastÄ™pczych:</t>
    <t id="9386">Maksymalna liczba jednoczesnych wyszukiwaÅ„ zastÄ™pczych:</t>
    <t id="9470">MiÄ™kki prÃ³g zalegÅ‚oÅ›ci procesora wsadowego (5-50). Gdy zalegÅ‚oÅ›ci osiÄ…gnÄ… tÄ™ wartoÅ›Ä‡, rozpoczyna siÄ™ stosowanie przeciwciÅ›nienia w celu spowolnienia nowych Å¼Ä…daÅ„ wyszukiwania. NiÅ¼sze wartoÅ›ci powodujÄ… wczeÅ›niejsze wywoÅ‚anie przeciwciÅ›nienia (bardziej konserwatywne). WartoÅ›Ä‡ domyÅ›lna: 10.</t>
    <t id="9471">Twardy prÃ³g zalegÅ‚oÅ›ci procesora wsadowego (10-100). Kiedy zalegÅ‚oÅ›ci osiÄ…gnÄ… tÄ™ wartoÅ›Ä‡, nowe wyszukiwania na Å¼ywo sÄ… blokowane do czasu zmniejszenia zalegÅ‚oÅ›ci. NiÅ¼sze wartoÅ›ci blokujÄ… wyszukiwanie wczeÅ›niej (bardziej konserwatywnie). WartoÅ›Ä‡ domyÅ›lna: 25.</t>
    <t id="9472">Sektory przetworzone na wycinek w kolekcji ofert na Å¼ywo (1-5). Mniejsze wartoÅ›ci rozkÅ‚adajÄ… pracÄ™ na wiÄ™cej klatek (pÅ‚ynniej), ale mogÄ… spowolniÄ‡ zbieranie ofert. WiÄ™ksze wartoÅ›ci sÄ… przetwarzane szybciej, ale mogÄ… powodowaÄ‡ skoki liczby klatek na sekundÄ™. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9473">Czas odnowienia po zakoÅ„czeniu odÅ›wieÅ¼ania sektora domowego (10-120 sekund). Zapobiega nadmiernym Å¼Ä…daniom odÅ›wieÅ¼enia. NiÅ¼sze wartoÅ›ci umoÅ¼liwiajÄ… czÄ™stsze odÅ›wieÅ¼anie, ale zwiÄ™kszajÄ… obciÄ…Å¼enie procesora. WyÅ¼sze wartoÅ›ci zmniejszajÄ… czÄ™stotliwoÅ›Ä‡ odÅ›wieÅ¼ania, ale mogÄ… opÃ³ÅºniaÄ‡ aktualizacje pamiÄ™ci podrÄ™cznej. WartoÅ›Ä‡ domyÅ›lna: 30 s.</t>
    <t id="9474">Podstawowy czas odnowienia po ominiÄ™ciu pamiÄ™ci podrÄ™cznej przed ponownÄ… prÃ³bÄ… wyszukiwania na Å¼ywo (1-30 sekund). Zapobiega nadmiernej liczbie ponownych prÃ³b. NiÅ¼sze wartoÅ›ci ponÃ³w prÃ³bÄ™ wczeÅ›niej, ale zwiÄ™ksz obciÄ…Å¼enie procesora. WyÅ¼sze wartoÅ›ci zmniejszajÄ… czÄ™stotliwoÅ›Ä‡ ponownych prÃ³b, ale mogÄ… opÃ³ÅºniÄ‡ znalezienie transakcji. WartoÅ›Ä‡ domyÅ›lna: 10 s.</t>
    <t id="9475">OdstÄ™p miÄ™dzy taktami harmonogramu w milisekundach (50-500 ms). Kontroluje, jak czÄ™sto program planujÄ…cy przetwarza kolejkÄ™ roboczÄ…. NiÅ¼sze wartoÅ›ci przetwarzajÄ… czÄ™Å›ciej, ale zwiÄ™kszajÄ… obciÄ…Å¼enie procesora. WyÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale mogÄ… wydÅ‚uÅ¼yÄ‡ czas oczekiwania w kolejce. WartoÅ›Ä‡ domyÅ›lna: 100 ms.</t>
    <t id="9476">Maksymalna liczba zapytaÅ„ o pamiÄ™Ä‡ podrÄ™cznÄ… rozpoczÄ™tych na takt harmonogramu (1-5). Ogranicza czÄ™stotliwoÅ›Ä‡ zapytaÅ„ o pamiÄ™Ä‡ podrÄ™cznÄ…, aby zapobiec blokowaniu ramek. NiÅ¼sze wartoÅ›ci zmniejszajÄ… skoki wydajnoÅ›ci procesora, ale spowalniajÄ… przeszukiwanie pamiÄ™ci podrÄ™cznej. WyÅ¼sze wartoÅ›ci sÄ… przetwarzane szybciej, ale mogÄ… powodowaÄ‡ zacinanie siÄ™. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9477">Maksymalna liczba rozpoczÄ™tych kontynuacji wyszukiwania na znacznik harmonogramu (1-5). Ogranicza szybkoÅ›Ä‡ kontynuacji, aby zapobiec blokowaniu ramek. NiÅ¼sze wartoÅ›ci zmniejszajÄ… skoki wydajnoÅ›ci procesora, ale spowalniajÄ… przetwarzanie wyszukiwania. WyÅ¼sze wartoÅ›ci sÄ… przetwarzane szybciej, ale mogÄ… powodowaÄ‡ zacinanie siÄ™. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9478">Maksymalna liczba statkÃ³w przetworzonych na znacznik harmonogramu (1-5). Ogranicza szybkoÅ›Ä‡ przetwarzania statku, aby zapobiec blokowaniu ramek. NiÅ¼sze wartoÅ›ci zmniejszajÄ… skoki wydajnoÅ›ci procesora, ale spowalniajÄ… przetwarzanie kolejki. WyÅ¼sze wartoÅ›ci sÄ… przetwarzane szybciej, ale mogÄ… powodowaÄ‡ zacinanie siÄ™. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9479">Maksymalna liczba elementÃ³w pracy przetworzonych na znacznik harmonogramu (1-5). Ogranicza szybkoÅ›Ä‡ przetwarzania elementu roboczego, aby zapobiec blokowaniu ramek. NiÅ¼sze wartoÅ›ci zmniejszajÄ… skoki wydajnoÅ›ci procesora, ale spowalniajÄ… przetwarzanie kolejki. WyÅ¼sze wartoÅ›ci sÄ… przetwarzane szybciej, ale mogÄ… powodowaÄ‡ zacinanie siÄ™. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9480">Maksymalna liczba obudzonych kelnerÃ³w na kaÅ¼dy znacznik harmonogramu (1-10). Ogranicza czÄ™stotliwoÅ›Ä‡ wybudzania, aby zapobiec skokom procesora, gdy w kolejce znajduje siÄ™ wielu kelnerÃ³w. NiÅ¼sze wartoÅ›ci zmniejszajÄ… skoki wydajnoÅ›ci procesora, ale spowalniajÄ… przetwarzanie kelnerskie. WyÅ¼sze wartoÅ›ci sÄ… przetwarzane szybciej, ale mogÄ… powodowaÄ‡ zacinanie siÄ™. WartoÅ›Ä‡ domyÅ›lna: 2.</t>
    <t id="9481">Maksymalna liczba wpisÃ³w pamiÄ™ci podrÄ™cznej odpytywanych na partiÄ™ (1-200). Kontroluje rozmiar partii zapytaÅ„ o pamiÄ™Ä‡ podrÄ™cznÄ…. NiÅ¼sze wartoÅ›ci przyspieszajÄ… przeszukiwanie pamiÄ™ci podrÄ™cznej, ale mogÄ… pomijaÄ‡ lepsze transakcje. WyÅ¼sze wartoÅ›ci uwzglÄ™dniajÄ… wiÄ™cej transakcji buforowanych, ale wydÅ‚uÅ¼ajÄ… czas sprawdzania poprawnoÅ›ci. WartoÅ›Ä‡ domyÅ›lna: 50.</t>
    <t id="9482">PrÃ³g nieaktualnego stanu wyszukiwania na Å¼ywo w sekundach (60-600). JeÅ›li stan wyszukiwania na Å¼ywo jest starszy, jest uwaÅ¼any za nieaktualny i wyczyszczony. NiÅ¼sze wartoÅ›ci szybciej usuwajÄ… nieaktualny stan, ale mogÄ… zakÅ‚Ã³caÄ‡ prawidÅ‚owe wyszukiwania. WyÅ¼sze wartoÅ›ci umoÅ¼liwiajÄ… dÅ‚uÅ¼sze wyszukiwania, ale mogÄ… pozostawiÄ‡ nieaktualny stan. WartoÅ›Ä‡ domyÅ›lna: 300 s.</t>
    <t id="9483">PrÃ³g nieaktualnych elementÃ³w kolejki w sekundach (30-300). JeÅ›li elementy kolejki sÄ… starsze, sÄ… uznawane za nieaktualne i usuwane. NiÅ¼sze wartoÅ›ci powodujÄ… szybsze usuniÄ™cie nieaktualnych elementÃ³w, ale mogÄ… spowodowaÄ‡ usuniÄ™cie prawidÅ‚owych elementÃ³w z kolejki. WyÅ¼sze wartoÅ›ci wydÅ‚uÅ¼ajÄ… czas oczekiwania w kolejce, ale mogÄ… pozostawiÄ‡ nieaktualne elementy. WartoÅ›Ä‡ domyÅ›lna: 60 s.</t>
    <t id="9484">Nieudane wygaÅ›niÄ™cie pamiÄ™ci podrÄ™cznej transakcji w sekundach (300-3600). Nieudane transakcje sÄ… buforowane, aby uniknÄ…Ä‡ natychmiastowego ponawiania transakcji. NiÅ¼sze wartoÅ›ci szybciej wygasajÄ… nieudane transakcje (wiÄ™cej ponownych prÃ³b), ale zmniejszajÄ… efektywnoÅ›Ä‡ pamiÄ™ci podrÄ™cznej. WyÅ¼sze wartoÅ›ci buforujÄ… dÅ‚uÅ¼ej (mniej ponownych prÃ³b), ale mogÄ… opÃ³ÅºniaÄ‡ ponowne prÃ³by. WartoÅ›Ä‡ domyÅ›lna: 1800 s (30 minut).</t>
    <t id="9485">Maksymalna liczba jednoczesnych wyszukiwaÅ„ awaryjnych na Å¼ywo (1-10). Wyszukiwania awaryjne omijajÄ… blokadÄ™ sektora macierzystego, umoÅ¼liwiajÄ…c jednoczesne przeszukiwanie wielu statkÃ³w z tego samego sektora macierzystego. NiÅ¼sze wartoÅ›ci zmniejszajÄ… obciÄ…Å¼enie procesora, ale mogÄ… spowolniÄ‡ wyszukiwanie zastÄ™pcze. WyÅ¼sze wartoÅ›ci umoÅ¼liwiajÄ… wiÄ™cej rÃ³wnolegÅ‚ych wyszukiwaÅ„ zastÄ™pczych, ale zwiÄ™kszajÄ… uÅ¼ycie procesora. WartoÅ›Ä‡ domyÅ›lna: 1.</t>
    <t id="9490">OpÃ³Åºnienie sygnaÅ‚u znalezionego handlu:</t>
    <t id="9590">OpÃ³Åºnienie przed wysÅ‚aniem sygnaÅ‚u GT_Trade_Found do statkÃ³w w milisekundach (10-1000ms). Statki zawsze czekajÄ… (skonfigurowane opÃ³Åºnienie + bufor 5 ms) przed wysÅ‚aniem nowych Å¼Ä…daÅ„ w celu przechwycenia opÃ³Åºnionych sygnaÅ‚Ã³w. WyÅ¼sze wartoÅ›ci rozkÅ‚adajÄ… sygnaÅ‚y pomiÄ™dzy klatkami, zapewniajÄ…c pÅ‚ynniejszÄ… pracÄ™. WartoÅ›Ä‡ domyÅ›lna: 10 ms.</t>
    <t id="8000">Flota GalaxyTraderÃ³w</t>
    <t id="8001">ZarzÄ…dzanie flotÄ… GalaxyTrader i statystyki pilotaÅ¼owe</t>
    <t id="8002">PrzeglÄ…daj i zarzÄ…dzaj wszystkimi pilotami GalaxyTrader</t>
    <t id="8100">Identyfikator statku</t>
    <t id="8101">Pilot</t>
    <t id="8102">Statek</t>
    <t id="8103">Status</t>
    <t id="8104">StopieÅ„</t>
    <t id="8105">Poziom</t>
    <t id="8106">XP</t>
    <t id="8107">Zysk Å¼yciowy</t>
    <t id="8108">Lokalizacja</t>
    <t id="8109">Baza domowa</t>
    <t id="8110">Ostatni handel</t>
    <t id="8111">Zysk pilota</t>
    <t id="8112">Zysk statku</t>
    <t id="8113">Licznik handlu</t>
    <t id="8200">OdÅ›wieÅ¼aÄ‡</t>
    <t id="8201">Eksportuj plik CSV</t>
    <t id="8202">Statystyka</t>
    <t id="8203">Ustawienia</t>
    <t id="8204">Pomoc</t>
    <t id="8205">ZamknÄ…Ä‡</t>
    <t id="8300">Wszyscy piloci</t>
    <t id="8301">Handlowy</t>
    <t id="8302">Szkolenie</t>
    <t id="8303">Konserwacja</t>
    <t id="8304">NagÅ‚y wypadek</t>
    <t id="8305">PoczÄ…tkujÄ…cy (Poz. 1-5)</t>
    <t id="8306">Zaawansowane (Poz. 6-11)</t>
    <t id="8307">Eksperci (poz. 12+)</t>
    <t id="8308">10 najlepszych zarabiajÄ…cych</t>
    <t id="8350">Sortuj wedÅ‚ug:</t>
    <t id="8351">Identyfikator statku</t>
    <t id="8352">ImiÄ™ pilota</t>
    <t id="8353">Typ statku</t>
    <t id="8354">Status</t>
    <t id="8355">StopieÅ„</t>
    <t id="8356">Poziom</t>
    <t id="8357">XP</t>
    <t id="8358">Zysk</t>
    <t id="8400">Brak zarejestrowanych pilotÃ³w</t>
    <t id="8401">Å»aden pilot nie pasuje do filtra</t>
    <t id="8402">CaÅ‚kowita liczba pilotÃ³w:</t>
    <t id="8403">CaÅ‚kowity zysk floty:</t>
    <t id="8404">Ostatnia aktualizacja:</t>
    <t id="8405">Szukaj pilotÃ³w...</t>
    <t id="8114">Sektor</t>
    <t id="8320">Zmiana nazwy statku</t>
    <t id="8321">Nazwa niestandardowa</t>
    <t id="8322">Ustaw nazwÄ™</t>
    <t id="8323">WyczyÅ›Ä‡ nazwÄ™</t>
    <t id="8324">Nazwa zostaÅ‚a ustawiona pomyÅ›lnie</t>
    <t id="8325">Nazwa zostaÅ‚a pomyÅ›lnie wyczyszczona</t>
    <t id="8450">WyÅ›lij na szkolenie</t>
    <t id="8451">Wyrejestruj siÄ™</t>
    <t id="8452">WymuÅ› sprzedaÅ¼ Å‚adunku</t>
    <t id="8453">WyÅ›lij do naprawy</t>
    <t id="8454">WyÅ›lij do zaopatrzenia</t>
    <t id="8455">Zatrzymaj wszystkie zamÃ³wienia</t>
    <t id="8456">DziaÅ‚ania</t>
    <t id="8500">Kliknij, aby posortowaÄ‡ wedÅ‚ug identyfikatora statku</t>
    <t id="8501">Kliknij, aby posortowaÄ‡ wedÅ‚ug nazwy pilota</t>
    <t id="8502">Kliknij, aby posortowaÄ‡ wedÅ‚ug typu statku</t>
    <t id="8503">Kliknij, aby posortowaÄ‡ wedÅ‚ug stanu</t>
    <t id="8504">Kliknij, aby posortowaÄ‡ wedÅ‚ug rangi</t>
    <t id="8505">Kliknij, aby posortowaÄ‡ wedÅ‚ug poziomu</t>
    <t id="8506">Kliknij, aby posortowaÄ‡ wedÅ‚ug XP</t>
    <t id="8507">Kliknij, aby posortowaÄ‡ wedÅ‚ug zysku Å¼yciowego</t>
    <t id="8508">OdÅ›wieÅ¼ dane pilota z systemu misji</t>
    <t id="8509">Eksportuj bieÅ¼Ä…cy widok do pliku CSV</t>
    <t id="8510">PrzeglÄ…daj statystyki i wykresy floty</t>
    <t id="8511">Skonfiguruj ustawienia menu</t>
    <t id="8512">PokaÅ¼ pomoc i skrÃ³ty klawiaturowe</t>
    <t id="8600">Nie znaleziono pilotÃ³w GalaxyTrader</t>
    <t id="8601">TwÃ³rz pilotÃ³w, przypisujÄ…c statki do GalaxyTrader lub czekaj na zaÅ‚adowanie danych.</t>
    <t id="9001">ZmieÅ„ nazwÄ™ GT</t>
    <t id="9902">WyÅ›lij na szkolenie</t>
    <t id="9903">Trening rÄ™czny w kolejce dla %1. Pilot rozpocznie szkolenie po bieÅ¼Ä…cym cyklu.</t>
    <t id="9904">Trening w kolejce po bieÅ¼Ä…cym cyklu</t>
    <t id="9905">Nie znaleziono pilota ani statku</t>
    <t id="9906">AutoTraining jest wÅ‚Ä…czony - rÄ™czna kolejka nie jest wymagana</t>
    <t id="9907">Pilot nie jest zablokowany podczas szkolenia</t>
    <t id="9910">Akademia Handlu</t>
    <t id="9911">UczeÅ„ (poziom 4) - %1 / %2</t>
    <t id="9912">Handlarz (7 poziom) - %1 / %2</t>
    <t id="9913">Mistrz Handlowy (poziom 13) - %1 / %2</t>
    <t id="9920">Pilot %1 zapisaÅ‚ siÄ™ na kurs Akademii na poziomie %2. Wyjazd do najbliÅ¼szej stacji handlowej.</t>
    <t id="9921">NiewystarczajÄ…ce Å›rodki na ten kurs (potrzebujesz %1, masz %2).</t>
    <t id="9922">Kurs niedostÄ™pny - pilot %1 jest juÅ¼ na tym poziomie lub powyÅ¼ej.</t>
    <t id="9923">Pilot %1 zapisaÅ‚ siÄ™ na kurs Akademii Handlowej na poziomie %2 (koszt: %3 Cr, czas trwania: %4 min) na pokÅ‚adzie %5.</t>
    <t id="11011">Reduktor Å›rednich statkÃ³w GT Apprentice</t>
    <t id="11012">Modyfikacja silnika, ktÃ³ra nieznacznie zmniejsza wydajnoÅ›Ä‡ dla niedoÅ›wiadczonych pilotÃ³w na Å›rednich statkach. UÅ¼ywany przez system AI GalaxyTrader. -5% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="11013">Åšredni reduktor skoku GT Apprentice</t>
    <t id="11014">Modyfikacja silnika, ktÃ³ra nieznacznie zmniejsza wydajnoÅ›Ä‡ podrÃ³Å¼y dla niedoÅ›wiadczonych pilotÃ³w na Å›rednich statkach. UÅ¼ywany przez system AI GalaxyTrader. -5% prÄ™dkoÅ›ci jazdy.</t>
    <t id="11021">Reduktor duÅ¼ych statkÃ³w GT Apprentice</t>
    <t id="11022">Modyfikacja silnika zmniejszajÄ…ca wydajnoÅ›Ä‡ niedoÅ›wiadczonych pilotÃ³w na duÅ¼ych statkach. UÅ¼ywany przez system AI GalaxyTrader. -15% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="11023">DuÅ¼y reduktor skoku GT Apprentice</t>
    <t id="11024">Modyfikacja silnika zmniejszajÄ…ca wydajnoÅ›Ä‡ podrÃ³Å¼y niedoÅ›wiadczonych pilotÃ³w na duÅ¼ych statkach. UÅ¼ywany przez system AI GalaxyTrader. -15% prÄ™dkoÅ›ci jazdy.</t>
    <t id="11031">Reduktor statku GT Apprentice Capital</t>
    <t id="11032">Modyfikacja silnika, ktÃ³ra znacznie zmniejsza osiÄ…gi dla niedoÅ›wiadczonych pilotÃ³w na statkach flagowych. UÅ¼ywany przez system AI GalaxyTrader. -25% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="11033">Redukcja kosztÃ³w podrÃ³Å¼y kapitaÅ‚u praktykanta GT</t>
    <t id="11034">Modyfikacja silnika, ktÃ³ra znacznie zmniejsza wydajnoÅ›Ä‡ podrÃ³Å¼y niedoÅ›wiadczonych pilotÃ³w na statkach flagowych. UÅ¼ywany przez system AI GalaxyTrader. -25% prÄ™dkoÅ›ci jazdy.</t>
    <t id="12001">Podstawowy wzmacniacz do maÅ‚ych statkÃ³w GT</t>
    <t id="12002">Specjalistyczne modyfikacje silnikÃ³w dla maÅ‚ych statkÃ³w z podstawowymi certyfikowanymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +3% do prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="12003">GT Basic MaÅ‚y wzmacniacz podrÃ³Å¼ny</t>
    <t id="12004">Specjalistyczne modyfikacje silnikÃ³w dla maÅ‚ych statkÃ³w z podstawowymi certyfikowanymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +3% szybkoÅ›ci podrÃ³Å¼y.</t>
    <t id="13001">Reduktor GT Basic do duÅ¼ych statkÃ³w</t>
    <t id="13002">Specjalistyczne modyfikacje silnikÃ³w dla duÅ¼ych statkÃ³w z podstawowymi certyfikowanymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. -8% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="13003">GT Podstawowy duÅ¼y reduktor skoku</t>
    <t id="13004">Specjalistyczne modyfikacje silnikÃ³w dla duÅ¼ych statkÃ³w z podstawowymi certyfikowanymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. -8% prÄ™dkoÅ›ci jazdy.</t>
    <t id="14001">GT Podstawowy reduktor statku kapitaÅ‚owego</t>
    <t id="14002">Specjalistyczne modyfikacje silnikÃ³w dla okrÄ™tÃ³w wojennych z podstawowymi certyfikowanymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. -15% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="14003">Podstawowy reduktor podrÃ³Å¼y kapitaÅ‚u GT</t>
    <t id="14004">Specjalistyczne modyfikacje silnikÃ³w dla okrÄ™tÃ³w wojennych z podstawowymi certyfikowanymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. -15% prÄ™dkoÅ›ci jazdy.</t>
    <t id="15001">Wzmacniacz maÅ‚ych statkÃ³w GT Expert</t>
    <t id="15002">Zaawansowana modyfikacja silnika dla maÅ‚ych statkÃ³w z doÅ›wiadczonymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +25% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="15003">MaÅ‚y wzmacniacz podrÃ³Å¼ny GT Expert</t>
    <t id="15004">Zaawansowana modyfikacja silnika dla maÅ‚ych statkÃ³w z doÅ›wiadczonymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +25% prÄ™dkoÅ›ci podrÃ³Å¼y.</t>
    <t id="16001">Ekspert GT, wzmacniacz duÅ¼ych statkÃ³w</t>
    <t id="16002">Zaawansowana modyfikacja silnika dla duÅ¼ych statkÃ³w z doÅ›wiadczonymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +15% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="16003">GT Expert DuÅ¼y wzmacniacz podrÃ³Å¼y</t>
    <t id="16004">Zaawansowana modyfikacja silnika dla duÅ¼ych statkÃ³w z doÅ›wiadczonymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +15% prÄ™dkoÅ›ci podrÃ³Å¼y.</t>
    <t id="17001">Ekspert GT Wzmacniacz statkÃ³w stoÅ‚ecznych</t>
    <t id="17002">Zaawansowana modyfikacja silnika dla okrÄ™tÃ³w wojennych z doÅ›wiadczonymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +6% prÄ™dkoÅ›ci, ciÄ…gu i obrotu.</t>
    <t id="17003">Wzmacniacz podrÃ³Å¼y GT Expert Capital</t>
    <t id="17004">Zaawansowana modyfikacja silnika dla okrÄ™tÃ³w wojennych z doÅ›wiadczonymi pilotami. UÅ¼ywany przez system AI GalaxyTrader. +6% szybkoÅ›ci podrÃ³Å¼y.</t>
    <t id="18001">PowaÅ¼ne ograniczenie umiejÄ™tnoÅ›ci (statek)</t>
    <t id="18002">PowaÅ¼ne ograniczenie umiejÄ™tnoÅ›ci (statek) - oznacza powaÅ¼ne kary za wydajnoÅ›Ä‡ wynikajÄ…ce z braku doÅ›wiadczenia pilota na duÅ¼ych statkach. Automatycznie stosowane przez system GalaxyTrader, gdy umiejÄ™tnoÅ›ci pilota sÄ… niewystarczajÄ…ce w stosunku do wielkoÅ›ci statku. ZwiÄ™ksza masÄ™ statku. (Tylko system GT - niedostÄ™pny w przypadku instalacji rÄ™cznej)</t>
    <t id="18003">Umiarkowane ograniczenie umiejÄ™tnoÅ›ci (statek)</t>
    <t id="18004">Umiarkowane ograniczenie umiejÄ™tnoÅ›ci (statek) - oznacza umiarkowane kary za wydajnoÅ›Ä‡, gdy pilot dostosowuje siÄ™ do zÅ‚oÅ¼onoÅ›ci statku. Automatycznie stosowane przez system GalaxyTrader, gdy umiejÄ™tnoÅ›ci pilota sÄ… niewystarczajÄ…ce w stosunku do wielkoÅ›ci statku. ZwiÄ™ksza masÄ™ statku. (Tylko system GT - niedostÄ™pny w przypadku instalacji rÄ™cznej)</t>
    <t id="18005">Ograniczenie umiejÄ™tnoÅ›ci Å›wiatÅ‚a (statek)</t>
    <t id="18006">Ograniczenie umiejÄ™tnoÅ›ci lekkich (statek) - reprezentuje niewielkie spadki wydajnoÅ›ci podczas rozwoju umiejÄ™tnoÅ›ci pilota. Automatycznie stosowane przez system GalaxyTrader, gdy umiejÄ™tnoÅ›ci pilota sÄ… niewystarczajÄ…ce w stosunku do wielkoÅ›ci statku. ZwiÄ™ksza masÄ™ statku. (Tylko system GT - niedostÄ™pny w przypadku instalacji rÄ™cznej)</t>
    <t id="18007">PowaÅ¼ne ograniczenie umiejÄ™tnoÅ›ci (silnik)</t>
    <t id="18008">PowaÅ¼ne ograniczenie umiejÄ™tnoÅ›ci (silnik) - oznacza powaÅ¼ne kary za wydajnoÅ›Ä‡ wynikajÄ…ce z braku doÅ›wiadczenia pilota na duÅ¼ych statkach. Automatycznie stosowane przez system GalaxyTrader, gdy umiejÄ™tnoÅ›ci pilota sÄ… niewystarczajÄ…ce w stosunku do wielkoÅ›ci statku. Zmniejsza ciÄ…g i obroty silnika. (Tylko system GT - niedostÄ™pny w przypadku instalacji rÄ™cznej)</t>
    <t id="18009">Umiarkowane ograniczenie umiejÄ™tnoÅ›ci (silnik)</t>
    <t id="18010">Umiarkowane ograniczenie umiejÄ™tnoÅ›ci (silnik) - oznacza umiarkowane spadki wydajnoÅ›ci w miarÄ™ dostosowywania siÄ™ pilota do zÅ‚oÅ¼onoÅ›ci statku. Automatycznie stosowane przez system GalaxyTrader, gdy umiejÄ™tnoÅ›ci pilota sÄ… niewystarczajÄ…ce w stosunku do wielkoÅ›ci statku. Zmniejsza ciÄ…g i obroty silnika. (Tylko system GT - niedostÄ™pny w przypadku instalacji rÄ™cznej)</t>
    <t id="18011">Ograniczenie umiejÄ™tnoÅ›ci lekkich (silnik)</t>
    <t id="18012">Ograniczenie lekkich umiejÄ™tnoÅ›ci (silnik) - reprezentuje niewielkie spadki wydajnoÅ›ci podczas rozwijania umiejÄ™tnoÅ›ci pilota. Automatycznie stosowane przez system GalaxyTrader, gdy umiejÄ™tnoÅ›ci pilota sÄ… niewystarczajÄ…ce w stosunku do wielkoÅ›ci statku. Zmniejsza ciÄ…g i obroty silnika. (Tylko system GT - niedostÄ™pny w przypadku instalacji rÄ™cznej)</t>
    <t id="9250">Nazewnictwo stanu statku</t>
    <t id="9350">Dostosuj skrÃ³ty stanu statku. WartoÅ›ci domyÅ›lne sÄ… wyÅ›wietlane w polach wejÅ›ciowych i moÅ¼na je zastÄ…piÄ‡. Maksymalnie 3 znaki. Wszystkie nazwy statkÃ³w zostanÄ… automatycznie zaktualizowane po zmianie.</t>
    <t id="9251">SkrÃ³t stanu zaopatrzenia:</t>
    <t id="9252">SkrÃ³t stanu naprawy:</t>
    <t id="9253">SkrÃ³t stanu konserwacji:</t>
    <t id="9254">SkrÃ³t stanu szkolenia:</t>
    <t id="9255">SkrÃ³t stanu przekierowania:</t>
    <t id="9256">SkrÃ³t stanu dopuszczenia:</t>
    <t id="9257">SkrÃ³t stanu zablokowania:</t>
    <t id="9258">SkrÃ³t stanu awaryjnego:</t>
    <t id="9259">SkrÃ³t stanu izolowanego:</t>
    <t id="9260">SkrÃ³t stanu handlowego:</t>
    <t id="9261">SkrÃ³t stanu bezczynnoÅ›ci:</t>
    <t id="9262">SkrÃ³t stanu ucieczki:</t>
    <t id="9268">SkrÃ³t stanu nieosiÄ…galnego:</t>
    <t id="9269">SkrÃ³t stanu wymiany pilotaÅ¼owej:</t>
    <t id="9270">Niestandardowy tag prefiksu czarnej listy:</t>
    <t id="9700">CHEATY (zepsute. nic tu nie ma!! serio!!)</t>
    <t id="9701">Statki GT niezniszczalne</t>
    <t id="9702">Wszystkie statki gracza niezniszczalne</t>
    <t id="9800">Idz dalej, pilocie. Zepsute narzedzia testowe, nie menu zabawy. Nic tu nie ma. Serio. Zostales ostrzezony. Prawdopodobnie.</t>
    <t id="9801">Statki z rozkazem GalaxyTrader nie moga zejsc ponizej 100% kadluba lub tarcz. Kliknij ponownie, aby wylaczyc.</t>
    <t id="9802">Wszystkie statki gracza nie moga zejsc ponizej 100% kadluba lub tarcz. Kliknij ponownie, aby wylaczyc. Stacje nie sa dotkniete.</t>
    <t id="9703">Odkryj wszechswiat do testow GT</t>
    <t id="9704">Odkryto</t>
    <t id="9705">Odkryj</t>
    <t id="9803">Odkrywa mgle wojny we wszystkich sektorach, oznacza wszystkie stacje jako znane, przyznaje wszystkie licencje subskrypcji handlowej i subskrybuje oferty handlowe w calej galaktyce. Kliknij ponownie po nowych sektorach DLC. Tylko do testow.</t>
    <t id="9706">Maksymalizuj XP zarejestrowanych pilotow GT</t>
    <t id="9707">Zmaksymalizowano</t>
    <t id="9708">XP max</t>
    <t id="9804">Ustawia poziom 15 i maksymalne XP dla kazdego pilota w rejestrze GT. Usuwa blokady treningu. Pomijane przy trybie tylko vanilla XP. Tylko do testow.</t>
    <t id="9351">SkrÃ³t od stanu zaopatrzenia (domyÅ›lnie: RS)</t>
    <t id="9352">SkrÃ³t od stanu naprawy (domyÅ›lnie: RP)</t>
    <t id="9353">SkrÃ³t od stanu konserwacji (domyÅ›lnie: MT)</t>
    <t id="9354">SkrÃ³t od stanu treningu (domyÅ›lnie: TR)</t>
    <t id="9355">SkrÃ³t od stanu przekierowania (domyÅ›lnie: RR)</t>
    <t id="9356">SkrÃ³t od stanu dopuszczenia (domyÅ›lnie: CL)</t>
    <t id="9357">SkrÃ³t od stanu zablokowania (domyÅ›lnie: BL)</t>
    <t id="9358">SkrÃ³t od stanu awaryjnego (domyÅ›lnie: FB)</t>
    <t id="9359">SkrÃ³t od stanu izolowanego (domyÅ›lnie: IS)</t>
    <t id="9360">SkrÃ³t oznaczajÄ…cy stan handlowy (domyÅ›lnie: TD)</t>
    <t id="9361">SkrÃ³t oznaczajÄ…cy stan bezczynnoÅ›ci (domyÅ›lnie: ID)</t>
    <t id="9362">SkrÃ³t od stanu ucieczki (domyÅ›lnie: ES)</t>
    <t id="9367">SkrÃ³t od stanu nieosiÄ…galnego (domyÅ›lnie: UR)</t>
    <t id="9368">SkrÃ³t od stanu wymiany pilotÃ³w (domyÅ›lnie: PE)</t>
    <t id="9369">WyÅ›wietlany jako przedrostek dla statkÃ³w MK3, na ktÃ³re wpÅ‚ywa czarna lista niestandardowych frakcji (w tym podwÅ‚adni). WartoÅ›Ä‡ domyÅ›lna: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Sprzedawca stacji - sprzedaje produkty stacji frakcjom NPC</t>
    <t id="30010">Stacja domowa</t>
    <t id="30011">Maksymalna odlegÅ‚oÅ›Ä‡ sprzedaÅ¼y</t>
    <t id="30012">Ignoruj â€‹â€‹zasady handlu</t>
    <t id="30013">Filtr towarÃ³w</t>
    <t id="30014">Sprzedaj docelowy procent wypeÅ‚nienia Å‚adunku</t>
    <t id="30015">Tolerancja wsteczna</t>
    <t id="30016">Kup docelowy procent wypeÅ‚nienia Å‚adunku</t>
    <t id="30017">Wpisy do dziennika</t>
    <t id="30018">Poziom powiadomieÅ„</t>
    <t id="30019">Koordynacja floty</t>
    <t id="30020">Poziom debugowania</t>
    <t id="30021">Stacja zaopatrzenia</t>
    <t id="30022">Min. miejsce przechowywania stacji %</t>
    <t id="30023">Zezwalaj na nielegalne towary</t>
    <t id="30024">Åadunek/Zysk</t>
    <t id="30025">ZezwÃ³l na wiele transakcji</t>
    <t id="30110">Stacja gracza, z ktÃ³rej moÅ¼na sprzedawaÄ‡ towary (wymagane przypisanie stacji)</t>
    <t id="30111">Maksymalna odlegÅ‚oÅ›Ä‡ bramy do znalezienia kupcÃ³w NPC (ograniczona umiejÄ™tnoÅ›ciami pilota)</t>
    <t id="30112">Ignoruj â€‹â€‹â€‹â€‹ograniczenia w handlu stacjami - sprzedawaj dowolnej przyjaznej frakcji, niezaleÅ¼nie od zasad handlu na stacji</t>
    <t id="30113">Opcjonalny filtr ware; pozostaw puste, aby sprzedawaÄ‡ wszystkie produkty stacji i towary handlowe</t>
    <t id="30114">Minimalny procent wypeÅ‚nienia Å‚adunku przed wyjazdem w podrÃ³Å¼ sprzedaÅ¼owÄ…</t>
    <t id="30115">Maksymalna liczba dodatkowych skokÃ³w dozwolonych przy dodawaniu drugiego towaru do wycieczki (0 = tylko kupujÄ…cy bezpoÅ›rednio na trasie)</t>
    <t id="30116">Docelowe wypeÅ‚nienie Å‚adunku dla dostaw (cel miÄ™kki, handlarz moÅ¼e wyjechaÄ‡ wczeÅ›niej)</t>
    <t id="30117">WÅ‚Ä…cz wpisy w dzienniku transakcji dla poszczegÃ³lnych transakcji</t>
    <t id="30118">Poziom powiadamiania: 0=cichy, 1=normalny, 2=peÅ‚ny</t>
    <t id="30119">WÅ‚Ä…cz koordynacjÄ™ floty i system rezerwacji handlowych</t>
    <t id="30120">Poziom rejestrowania debugowania: 0=wyÅ‚Ä…czony, 1=normalny, 2=peÅ‚ny</t>
    <t id="30121">Gdy ta opcja jest wÅ‚Ä…czona, kupuj takÅ¼e zasoby dla stacji. Zaopatrzenie ma priorytet, gdy magazynowanie spadnie poniÅ¼ej minimalnego progu</t>
    <t id="30122">Kiedy jakikolwiek zasÃ³b spadnie poniÅ¼ej tego procentu celu, podaÅ¼ ma pierwszeÅ„stwo przed sprzedaÅ¼Ä…. Ignorowane, jeÅ›li stacja nie moÅ¼e sobie pozwoliÄ‡ na zasoby</t>
    <t id="30123">Zezwalaj na sprzedaÅ¼ lub zakup nielegalnych/kontrabandowych towarÃ³w, jeÅ›li sÄ… dostÄ™pne</t>
    <t id="30124">WybÃ³r sprzedaÅ¼y: 1 = Å‚adunek (preferuj najwyÅ¼sze zapeÅ‚nienie magazynu dla towaru; remisy wedÅ‚ug zysku), 2 = zysk (najlepszy wynik zysku)</t>
    <t id="30125">Pozwala Å‚Ä…czyÄ‡ kilka sprzedaÅ¼y w jednym cyklu (do 3 towarÃ³w lub celÃ³w). WyÅ‚Ä…cz, aby wykonywaÄ‡ tylko jednÄ… transakcjÄ™ na cyklus</t>
    <t id="30200">SprzedajÄ™ %1 %2 od %3 do %4</t>
    <t id="30201">Nie znaleziono nabywcÃ³w produktÃ³w stacji w obrÄ™bie %1 skokÃ³w</t>
    <t id="30202">Stacja domowa %1 zniszczona - zlecenie handlowca stacji anulowane</t>
    <t id="30203">Stacja domowa %1 nie jest juÅ¼ wÅ‚asnoÅ›ciÄ… gracza â€“ zamÃ³wienie anulowane</t>
    <t id="30204">Wymagane przypisanie stacji - zamÃ³wienie anulowane</t>
    <t id="30205">MK1 Station Trader rozpoczÄ…Å‚ siÄ™ o %1</t>
    <t id="30206">ZakoÅ„czona sprzedaÅ¼: %1 %2 sprzedana %3 za %4 Cr (zysk: %5 Cr)</t>
    <t id="30207">PodrÃ³Å¼ obejmujÄ…ca wiele towarÃ³w: dostawa %1 towarÃ³w do %2 miejsc docelowych</t>
    <t id="30208">Dostarczanie %1 %2 do %3 z %4</t>
    <t id="30500">Ustawienia GalaxyTradera MK1</t>
    <t id="30501">DomyÅ›lne ustawienia Station Tradera</t>
    <t id="30502">DomyÅ›lna maksymalna odlegÅ‚oÅ›Ä‡ sprzedaÅ¼y</t>
    <t id="30503">DomyÅ›lny cel sprzedaÅ¼y Å‚adunku</t>
    <t id="30504">DomyÅ›lne ignorowanie zasad handlu</t>
    <t id="30505">DomyÅ›lna tolerancja cofania</t>
    <t id="30506">Czas oczekiwania, gdy nie znaleziono Å¼adnych transakcji</t>
    <t id="30507">DomyÅ›lny cel zakupu Å‚adunku</t>
    <t id="31002">GÃ³rnik Galaxy</t>
    <t id="31102">Autonomiczne wydobycie z zaopatrzeniem stacji i progresjÄ… XP</t>
    <t id="31010">Stacja domowa</t>
    <t id="31110">Stacja do wydobywania i dostarczania do (wzajemna wyÅ‚Ä…cznoÅ›Ä‡ z Home Sector)</t>
    <t id="31011">Sektor domowy</t>
    <t id="31111">Sektor, w ktÃ³rym naleÅ¼y dziaÅ‚aÄ‡; uÅ¼ywany, gdy nie ustawiono Å¼adnej stacji domowej</t>
    <t id="31012">Kosz zasobÃ³w</t>
    <t id="31112">Towary moje; pusty nastÄ™puje po rozwiÄ…zaniu zapotrzebowania stacji</t>
    <t id="31013">Stacje docelowe</t>
    <t id="31113">Opcjonalny filtr stacyjny do dostaw; pusty wywodzi siÄ™ z kontekstu domowego</t>
    <t id="31014">PrÃ³g przepeÅ‚nienia %</t>
    <t id="31114">Stacje na poziomie lub powyÅ¼ej tego procentu przechowywania sÄ… traktowane jako peÅ‚ne</t>
    <t id="31015">Zezwalaj na sprzedaÅ¼ z przepeÅ‚nieniem innym</t>
    <t id="31115">Gdy ta opcja jest wÅ‚Ä…czona, a cele gÅ‚Ã³wne sÄ… zajÄ™te, sprzedawaj stacjom innych frakcji</t>
    <t id="31016">Przypisz do stacji</t>
    <t id="31116">JeÅ›li ma to zastosowanie, przypisz statek jako podrzÄ™dny gÃ³rniczy stacji macierzystej</t>
    <t id="31017">SiedzieÄ‡ w domu</t>
    <t id="31117">Ogranicz wydobycie/sprzedaÅ¼ do obszaru rodzinnego, z wyjÄ…tkiem sytuacji awaryjnych zwiÄ…zanych z przepeÅ‚nieniem</t>
    <t id="31018">Automatyczne wdraÅ¼anie sond zasobÃ³w</t>
    <t id="31118">Automatycznie wdraÅ¼aj zaÅ‚adowane sondy zasobÃ³w i uwzglÄ™dniaj sondy w ramach uzupeÅ‚niania zapasÃ³w w ramach konserwacji</t>
    <t id="31019">Maksymalna odlegÅ‚oÅ›Ä‡ zbierania</t>
    <t id="31119">Maksymalna odlegÅ‚oÅ›Ä‡ od bramy do gromadzenia (0 wykorzystuje limit umiejÄ™tnoÅ›ci pilota/dowÃ³dcy)</t>
    <t id="31020">Maksymalna odlegÅ‚oÅ›Ä‡ sprzedaÅ¼y</t>
    <t id="31120">Maksymalna odlegÅ‚oÅ›Ä‡ od bramy do sprzedaÅ¼y (0 wykorzystuje limit umiejÄ™tnoÅ›ci pilota/dowÃ³dcy)</t>
    <t id="31021">RÃ³wnowaÅ¼enie floty</t>
    <t id="31121">WÅ‚Ä…cz deterministycznÄ… koordynacjÄ™ zamierzeÅ„, aby zmniejszyÄ‡ przepeÅ‚nienie stacji</t>
    <t id="31022">InterwaÅ‚ ponownego sprawdzania zapotrzebowania</t>
    <t id="31122">Jak czÄ™sto przeprowadzana jest ocena zapotrzebowania/zmiany gÃ³rnika</t>
    <t id="31023">Krytyczna delta popytu</t>
    <t id="31123">Minimalna delta pilnoÅ›ci wymagana do przeÅ‚Ä…czenia aktywnego oprogramowania wydobywczego</t>
    <t id="31024">Minimalny czas odnowienia zmiany</t>
    <t id="31124">Minimalny czas miÄ™dzy dwiema zmianami sprzÄ™tu dla tego statku</t>
    <t id="31025">Minimalny udziaÅ‚ w Å‚adunku%</t>
    <t id="31125">JeÅ¼eli zapeÅ‚nienie Å‚adunku jest wyÅ¼sze, statek preferuje dokoÅ„czenie bieÅ¼Ä…cych dostaw przed przeÅ‚Ä…czeniem</t>
    <t id="31026">Twarda awaryjna Delta</t>
    <t id="31126">Delta pilnoÅ›ci, ktÃ³ra umoÅ¼liwia natychmiastowÄ… zmianÄ™ pomimo progu zatwierdzenia Å‚adunku</t>
    <t id="31027">Poziom powiadomieÅ„</t>
    <t id="31127">Poziom powiadamiania: 0=cichy, 1=normalny, 2=peÅ‚ny</t>
    <t id="31028">Tylko stacje graczy</t>
    <t id="31128">Gdy ta opcja jest wÅ‚Ä…czona, tylko stacje naleÅ¼Ä…ce do gracza sÄ… uznawane za cele popytu.</t>
    <t id="31031">SprawdÅº popyt najpierw</t>
    <t id="31131">Po wÅ‚Ä…czeniu gÃ³rnik sprawdza popyt stacji przed wydobyciem i odpowiednio ustala priorytety surowcÃ³w. Po wyÅ‚Ä…czeniu wydobywa z koszyka zasobÃ³w bez sprawdzania popytu i magazynuje do czasu pojawienia siÄ™ nabywcy (zalecane dla flot jednosurowcowych).</t>
    <t id="31032">Przerwanie przy magazynie fizycznym %</t>
    <t id="31132">Dla pilotÃ³w poziomu 6+: zatrzymuje wydobycie bieÅ¼Ä…cej surowiny, gdy fizyczny zapas stacji plus Å‚adunek powiÄ…zanych gÃ³rnikÃ³w przekroczy bieÅ¼Ä…cy fizyczny zapas o ten procent. UÅ¼ywa rzeczywistych iloÅ›ci Å‚adunku, nie progu przepeÅ‚nienia. 0 = wyÅ‚Ä…czone.</t>
    <t id="32002">GalaxyTrader Zasilanie MK4</t>
    <t id="32102">Sprzedawca zaopatrzenia stacji gracza przy uÅ¼yciu potoku pamiÄ™ci podrÄ™cznej/wyszukiwania na Å¼ywo GT</t>
    <t id="32010">OdlegÅ‚oÅ›Ä‡ zasiÄ™gu</t>
    <t id="32110">Maksymalna odlegÅ‚oÅ›Ä‡ bramy od domu w celu wyszukiwania popytu na miejsce docelowe</t>
    <t id="32011">Kup OdlegÅ‚oÅ›Ä‡</t>
    <t id="32111">Maksymalna odlegÅ‚oÅ›Ä‡ bramy od domu w celu wyszukiwania dostawcÃ³w</t>
    <t id="32012">Podawaj tylko w domu</t>
    <t id="32112">Po wÅ‚Ä…czeniu obsÅ‚ugiwane jest tylko Å¼Ä…danie stacji domowej</t>
    <t id="32013">Buduj tylko stacje</t>
    <t id="32113">Gdy ta opcja jest wÅ‚Ä…czona, obsÅ‚ugiwane jest tylko zapotrzebowanie na pamiÄ™Ä‡ kompilacji</t>
    <t id="32014">Kup od Gracza</t>
    <t id="32114">Zezwalaj na pozyskiwanie towarÃ³w od dostawcÃ³w bÄ™dÄ…cych wÅ‚asnoÅ›ciÄ… gracza</t>
    <t id="32015">Kup od Frakcji</t>
    <t id="32115">Zezwalaj na pozyskiwanie towarÃ³w od dostawcÃ³w frakcji niebÄ™dÄ…cych graczami</t>
    <t id="32016">Zezwalaj na zasoby</t>
    <t id="32116">UwzglÄ™dnij towary surowcowe w dopasowaniu popytu</t>
    <t id="32017">Zezwalaj na pÃ³Å‚produkty</t>
    <t id="32117">UwzglÄ™dnij towary poÅ›rednie w dopasowaniu popytu</t>
    <t id="32018">Zezwalaj na produkty</t>
    <t id="32118">UwzglÄ™dnij towary produktowe w dopasowaniu popytu</t>
    <t id="32019">Zezwalaj na Tradewares</t>
    <t id="32119">UwzglÄ™dnij towary handlowe w dopasowaniu popytu</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">Dystrybucja magazynu z zarzÄ…dzaniem progami skÅ‚adowania</t>
    <t id="20010">Stacje ÅºrÃ³dÅ‚owe</t>
    <t id="20011">Stacje docelowe</t>
    <t id="20012">Minimalny procent przechowywania</t>
    <t id="20013">PamiÄ™Ä‡ statyczna%</t>
    <t id="20014">Maksymalny% przechowywania</t>
    <t id="20015">Filtr towarÃ³w</t>
    <t id="20016">Tryb dwukierunkowy</t>
    <t id="20017">Stacja domowa (opcjonalnie)</t>
    <t id="20018">Maksymalna odlegÅ‚oÅ›Ä‡</t>
    <t id="20032">Sektor domowy (opcjonalnie)</t>
    <t id="20019">Czas oczekiwania na cykl</t>
    <t id="20030">Zezwalaj na niskÄ… gÅ‚oÅ›noÅ›Ä‡</t>
    <t id="20031">% niskiego wolumenu</t>
    <t id="20110">Lista stacji ÅºrÃ³dÅ‚owych, z ktÃ³rych dystrybuuje siÄ™ towary</t>
    <t id="20111">Lista docelowych stacji/magazynÃ³w, do ktÃ³rych naleÅ¼y dystrybuowaÄ‡ towary</t>
    <t id="20112">PrÃ³g pilnoÅ›ci miejsca docelowego: stacje poniÅ¼ej tego % pamiÄ™ci otrzymujÄ… dostawy priorytetowe</t>
    <t id="20113">Minimalny prÃ³g ÅºrÃ³dÅ‚a: ÅºrÃ³dÅ‚o musi mieÄ‡ wiÄ™cej niÅ¼ ten %, aby w ogÃ³le mÃ³c dystrybuowaÄ‡</t>
    <t id="20114">PrÃ³g przepeÅ‚nienia ÅºrÃ³dÅ‚a: powyÅ¼ej tego % ÅºrÃ³dÅ‚o dystrybuuje nawet do niepilnych miejsc docelowych</t>
    <t id="20115">Opcjonalny filtr ware; pozostaw puste, aby dystrybuowaÄ‡ wszystkie towary ze ÅºrÃ³dÅ‚a</t>
    <t id="20116">WÅ‚Ä…cz odbiÃ³r w obie strony z miejsc docelowych z powrotem do ÅºrÃ³dÅ‚a, gdy w miejscach docelowych jest nadmiar</t>
    <t id="20117">Opcjonalna stacja domowa do przypisania. JeÅ›li jest pusty, statek pozostaje nieprzypisany do stacji.</t>
    <t id="20118">Maksymalna odlegÅ‚oÅ›Ä‡ bramki miÄ™dzy ÅºrÃ³dÅ‚em a miejscem docelowym (0 = nieograniczona)</t>
    <t id="20132">Opcjonalny sektor domowy uÅ¼ywany do postoju bezczynnego, gdy nie ustawiono stacji domowej.</t>
    <t id="20119">Czas oczekiwania pomiÄ™dzy cyklami dystrybucji</t>
    <t id="20130">Zezwalaj na mniejsze, uwzglÄ™dniajÄ…ce pilnoÅ›Ä‡, dostawy poniÅ¼ej normalnego minimalnego wypeÅ‚nienia Å‚adunkiem.</t>
    <t id="20131">Minimalny % wypeÅ‚nienia Å‚adunku uÅ¼ywany, gdy wÅ‚Ä…czony jest tryb maÅ‚ej objÄ™toÅ›ci.</t>
    <t id="20200">Dystrybucja %1 %2 z %3 do %4</t>
    <t id="20201">PodrÃ³Å¼ powrotna: odbiÃ³r %1 %2 z %3 do %4</t>
    <t id="20202">Nie ma potrzeby dystrybucji - wszystkie miejsca docelowe sÄ… odpowiednio zaopatrzone</t>
    <t id="20203">Wszystkie stacje zrodlowe sa nieprawidlowe - dystrybucja wstrzymana</t>
    <t id="20204">Wszystkie stacje docelowe sa nieprawidlowe - dystrybucja wstrzymana</t>
    <t id="20205">Stacja zrodlowa %1 zniszczona - usunieta z zlecenia dystrybucji</t>
    <t id="20206">Stacja docelowa %1 zniszczona - usunieta z zlecenia dystrybucji</t>
    <t id="20500">GalaxyTrader MK2 - Ustawienia globalne</t>
    <t id="20501">DomyÅ›lne ustawienia dystrybucji MK2</t>
    <t id="20510">DomyÅ›lny minimalny procent przechowywania</t>
    <t id="20511">DomyÅ›lny procent pamiÄ™ci statycznej</t>
    <t id="20512">DomyÅ›lny maksymalny procent przechowywania</t>
    <t id="20513">DomyÅ›lne oczekiwanie na cykl (y)</t>
    <t id="20514">Minimalny% wypeÅ‚nienia Å‚adunku</t>
    <t id="20520">SzczegÃ³Å‚owoÅ›Ä‡ powiadomieÅ„</t>
    <t id="20521">Poziom debugowania</t>
    <t id="10006">WrÃ³Ä‡ do domu</t>
    <t id="10007">GalaxyTrader Zaopatrzenie MK4-2</t>
    <t id="10106">Zadokuj na stacji domowej i pozostaÅ„ tam do momentu wznowienia handlu</t>
    <t id="10107">Zlecenie zaopatrzenia gracza z suwakami priorytetu celÃ³w dostawy</t>
    <t id="30026">PowrÃ³t do domu pomiÄ™dzy cyklami</t>
    <t id="30028">Ignoruj ustawienia ofert</t>
    <t id="30029">Zakres ceny kupujÄ…cego</t>
    <t id="30027">Min. magazyn produktÃ³w %</t>
    <t id="30126">Po wÅ‚Ä…czeniu wrÃ³Ä‡ do stacji domowej i dokuj pomiÄ™dzy cyklami handlowymi. Gdy wyÅ‚Ä…czone, kontynuuj wyszukiwanie z bieÅ¼Ä…cej lokalizacji (starsze zachowanie)</t>
    <t id="30128">Zezwalaj na wewnÄ™trzne transfery magazynowe bez ofert kupna/sprzedaÅ¼y stacji. UÅ¼ywa wymiany towarÃ³w do odbioru i dostawy bufora. Zasady handlu stacji nadal obowiÄ…zujÄ…, gdy Ignoruj zasady handlu jest wyÅ‚Ä…czone.</t>
    <t id="30129">Minimalna cena wzglÄ™dna dla kupujÄ…cych NPC przy sprzedaÅ¼y produktÃ³w stacji. Suwak zlecenia 0-200 (100 = Å›rednia, 0 = -100%, 200 = +100%), mapowany na -1,0..+1,0. WyÅ¼szy = tylko drodzy kupujÄ…cy. NiÅ¼szy = wiÄ™cej opcji kupujÄ…cych. Trasy zaÅ‚adunkowe uÅ¼ywajÄ… odwrÃ³conej wartoÅ›ci dla limitÃ³w cen dostawcÃ³w.</t>
    <t id="30127">Minimalny procent zapeÅ‚nienia magazynu stacji (w stosunku do skonfigurowanego maksimum na towar) wymagany przed sprzedaÅ¼Ä… produktu lub towaru. Towary poniÅ¼ej tego progu sÄ… pomijane. 0 = brak minimum.</t>
    <t id="3107">W kolejce multitrade: %1. Powinienem zarobiÄ‡ %2 zysku.</t>
    <t id="3108">SprzedajÄ™ %1 %2 z %3 po %4. Powinienem zarobiÄ‡ %5 zysku.</t>
    <t id="3110">Kolejkowanie zlecenia zaopatrzenia dla %1 %2. Pozyskanie po %3 z %4, dostawa do %5. Limit zakupu klienta %6 - %7/szt. poniÅ¼ej limitu (%8 Å‚Ä…cznie).</t>
    <t id="3111">Kolejkowanie zaopatrzenia %1 %2 z %3 do %4.</t>
    <t id="3112">Zaopatrzenie w kolejce (%1 odcinkÃ³w): %2. ÅÄ…cznie %3 poniÅ¼ej limitu zakupu klienta.</t>
    <t id="3113">Station Trader: Kolejkowanie eksportu wielu transakcji: %1. Oczekiwany zysk %2.</t>
    <t id="31029">Docelowy zapas sondy</t>
    <t id="31030">Drony gÃ³rnicze do kupienia</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: brak dostÄ™pnych surowcÃ³w do wydobycia. Statek %1 [%2], Flota: %3</t>
    <t id="31201">Galaxy-Miner: ustaw stacjÄ™ macierzystÄ… lub pozycjÄ™ macierzystÄ….</t>
    <t id="31130">Ile dronÃ³w zbierajÄ…cych (gÃ³rniczych) kupuje gÃ³rnik, gdy zabraknie mu wymaganego typu (staÅ‚y/ruda lub pÅ‚ynny/gaz). Zakup nastÄ™puje TYLKO wtedy, gdy statek nie ma Å¼adnych zbieraczy tego typu - gÃ³rnik, ktÃ³ry nadal ma co najmniej jednego, nigdy nie jest uzupeÅ‚niany ani kupowany ponownie, a istniejÄ…ce drony sÄ… zachowywane. Ograniczone pojemnoÅ›ciÄ… Å‚adowni jednostek statku. Ustaw na 0, aby wyÅ‚Ä…czyÄ‡ automatyczny zakup dronÃ³w zbierajÄ…cych i zarzÄ…dzaÄ‡ dronami rÄ™cznie. WartoÅ›Ä‡ domyÅ›lna 5 to peÅ‚ny zestaw dronÃ³w dla normalnej prÄ™dkoÅ›ci wydobycia.</t>
    <t id="31129">Liczba sond zasobÃ³w, ktÃ³re gÃ³rnik kupuje podczas jednej podrÃ³Å¼y uzupeÅ‚niania zapasÃ³w. Zakup nastÄ™puje TYLKO wtedy, gdy na statku skoÅ„czÄ… siÄ™ sondy (liczba = 0), a nie przy kaÅ¼dym rozmieszczeniu - w ten sposÃ³b gÃ³rnik przejeÅ¼dÅ¼a przez peÅ‚ny Å‚adunek sondy pomiÄ™dzy dostawami, zamiast obieraÄ‡ objazd po kaÅ¼dym rozmieszczeniu. Ograniczone przez caÅ‚kowitÄ… moÅ¼liwÄ… do rozmieszczenia pojemnoÅ›Ä‡ statku (wspÃ³Å‚dzielonÄ… z satelitami/minami/itp.); wartoÅ›Ä‡ suwaka wiÄ™ksza niÅ¼ wolna przestrzeÅ„, ktÃ³rÄ… moÅ¼na rozmieÅ›ciÄ‡, z wdziÄ™kiem zmniejsza siÄ™, aby â€žwypeÅ‚niÄ‡ to, co pasujeâ€. DziaÅ‚a tylko wtedy, gdy wÅ‚Ä…czona jest opcja automatycznego wdraÅ¼ania sond zasobÃ³w - to samo ustawienie steruje rÃ³wnieÅ¼ oportunistycznym wdraÅ¼aniem sond w sektorach wydobywczych i gromadzeniem nieaktualnych sond (sond w sektorach bez zasobÃ³w istotnych dla koszyka).</t>
    <t id="3226">DowÃ³dco %1,\n\nZadokowaÅ‚em w %2, a rejestrator Akademii Handlowej potwierdziÅ‚ mojÄ… rejestracjÄ™ w programie â€ž%3â€. Konto floty zostaÅ‚o obciÄ…Å¼one kwotÄ… %4 Cr z tytuÅ‚u czesnego, a ja nie traktujÄ™ tej inwestycji lekko.\n\nTo nie jest rutynowa certyfikacja. Instruktorami akademii sÄ… doÅ›wiadczeni kupcy i negocjatorzy konsorcjÃ³w, a program nauczania tutaj jest znacznie bardziej wymagajÄ…cy niÅ¼ standardowy egzamin awansowy. W ciÄ…gu nastÄ™pnych %5 minut przejdÄ™ intensywne szkolenie w zakresie zaawansowanych protokoÅ‚Ã³w handlowych, analizy rynku pod presjÄ… i taktyk negocjacyjnych oddzielajÄ…cych uczniÃ³w od mistrzÃ³w.\n\nPo zakoÅ„czeniu egzaminu koÅ„cowego i odÅ‚Ä…czeniu siÄ™ od doku bÄ™dÄ™ nosiÄ‡ tytuÅ‚ â€ž%3â€ i wszystko, czego siÄ™ nauczyÅ‚em, przyniosÄ™ z powrotem do naszych operacji handlowych. Nie zmarnujÄ™ ani jednego kredytu z tej okazji.\n\nZ wdziÄ™cznoÅ›ciÄ… i determinacjÄ…\n%6\nNa pokÅ‚adzie %7</t>
    <t id="9924">Kurs Trading Academy zostaÅ‚ przerwany: pilota %1 nie staÄ‡ na opÅ‚atÄ™ %2 Cr w stacji dokujÄ…cej akademii (mam %3 Cr). Kurs odwoÅ‚any, pilot wznawia handel.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="49">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Andocken und warten (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">AbschlussprÃ¼fung (GalaxyTrader MK3)</t>
    <t id="10004">Pilotenaustausch-Rendezvous</t>
    <t id="10005">[VERALTET] GalaxyTrader MK4-Versorgung (Legacy)</t>
    <t id="10101">An Station andocken und fÃ¼r angegebene Dauer warten</t>
    <t id="10102">Autonomer Handel mit FÃ¤higkeitsfortschritt</t>
    <t id="10103">AbschlussprÃ¼fung fÃ¼r Piloten-Zertifizierung in AusbildungsstÃ¤tte ablegen</t>
    <t id="10104">Legen Sie am Treffpunkt fÃ¼r den Pilotenaustausch an</t>
    <t id="10105">Angebotsorientierter Handel fÃ¼r Spielerstationen mittels Cache und Live-Suche (Legacy)</t>
    <t id="10201">Kaufen Sie %s von %s</t>
    <t id="10202">Verkaufe %s an %s</t>
    <t id="10203">Handeln Sie mit %s</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">Fortschrittliches Handelssystem mit XP-Fortschritt und Flottenkoordination</t>
    <t id="1002">Heimatbasis</t>
    <t id="1003">Verwenden Sie Voreinstellungen</t>
    <t id="1004">Handeln Sie mit allen Waren</t>
    <t id="1005">Handeln Sie mit legalen Waren</t>
    <t id="1006">Handel mit illegalen Waren</t>
    <t id="1007">Aktivieren Sie den XP-Fortschritt</t>
    <t id="1008">ErmÃ¶glichen Sie die Flottenkoordination</t>
    <t id="1009">Aktivieren Sie Marktanalysen</t>
    <t id="1010">Aktivieren Sie die Gebietsverwaltung</t>
    <t id="1011">Illegale Waren zulassen</t>
    <t id="1012">Logbuch-EintrÃ¤ge</t>
    <t id="1013">Risikotoleranz</t>
    <t id="1014">Priorisieren Sie Spielerstationen</t>
    <t id="1015">Autowaren</t>
    <t id="1016">Distanzstrafe %</t>
    <t id="1017">Benachrichtigungsebene</t>
    <t id="1018">Flottenkoordination</t>
    <t id="1019">Laderaum-FÃ¼llziel %</t>
    <t id="1050">HÃ¤ufigkeit der Marktaktualisierung</t>
    <t id="1051">Protokollierung der Handelsbewertung</t>
    <t id="1052">Sektor-Whitelist</t>
    <t id="1054">TrÃ¤ger/Hilfsschiffe Ignorieren</t>
    <t id="1056">Build-Speicher ignorieren</t>
    <t id="1058">Ignorieren Sie Handelsregeln</t>
    <t id="1060">Von MK1 bereitgestellte Stationen ignorieren</t>
    <t id="1063">In Entwicklung</t>
    <t id="1064">PrioritÃ¤tswaren</t>
    <t id="1065">PrioritÃ¤ts-Punkte %</t>
    <t id="1066">Waren in dieser Liste erhalten einen Punktebonus bei der Handelsauswahl. Wird zuletzt angewendet.</t>
    <t id="1067">Punkte-Multiplikator fÃ¼r PrioritÃ¤tswaren: 100%=normal, 150%=+50%%, 200%=doppelt. Wird zuletzt angewendet.</t>
    <t id="1068">â”€â”€ PrioritÃ¤tswaren-Filter â”€â”€</t>
    <t id="1069">Waren (manuell)</t>
    <t id="1070">UnzulÃ¤ssiger Routenfilter</t>
    <t id="1072">Nur zu Hause servieren</t>
    <t id="1073">Spieler-LieferantenprioritÃ¤t</t>
    <t id="1074">Fraktions-LieferantenprioritÃ¤t</t>
    <t id="1075">Build-Speicher einschlieÃŸen</t>
    <t id="1076">Ressourcen einbeziehen</t>
    <t id="1077">Beziehen Sie Fortgeschrittene ein</t>
    <t id="1078">Handelswaren einbeziehen</t>
    <t id="1080">Maximale Trades pro Zyklus</t>
    <t id="1081">Backtrack-Toleranz</t>
    <t id="1082">Min. genutzte Fracht %</t>
    <t id="1083">Spielerkaufmodifikator %</t>
    <t id="1085">Der Heimatstation zuweisen</t>
    <t id="1086">Abdeckungsentfernung</t>
    <t id="1088">Maximale Sprungentfernung von zu Hause zur Bedarfsdeckung</t>
    <t id="1090">Beziehen Sie Waren der Handelswarenklasse in den Nachfrage-/Angebotsabgleich ein</t>
    <t id="1091">Modifikator, der bei reinen Punkteberechnungen auf die Preise spielereigener Lieferanten angewendet wird</t>
    <t id="1092">Spielerpreise ignorieren</t>
    <t id="1093">Wenn aktiviert: Kaufen Sie immer auf spielereigenen Stationen, unabhÃ¤ngig von den festgelegten Verkaufspreisen, und verkaufen Sie nur an NPC-Fraktionen. NÃ¼tzlich fÃ¼r die Liquidation Ã¼berschÃ¼ssiger LagerbestÃ¤nde an Ihren eigenen Stationen.</t>
    <t id="1094">Gesperrte Stationen</t>
    <t id="1095">Die hier ausgewÃ¤hlten Stationen werden vom MK3-Handel ausgeschlossen. Der HÃ¤ndler kauft dort weder ein noch verkauft er dorthin.</t>
    <t id="1096">Leerlauf-Parken</t>
    <t id="1097">Wenn aktiviert, parken Schiffe, die wiederholt keine Arbeit finden, an ihrer Heimatstation oder in ihrem Heimatsektor. Sektorparken bevorzugt Spielerstationen, danach freundliche Stationen. Die Abdockzeit wird in den globalen Einstellungen festgelegt (0 = bleibt angedockt, bis Arbeit gefunden wird).</t>
    <t id="1098">Autoskalierung</t>
    <t id="1099">Wenn aktiviert, werden die Sprungentfernungs-Regler nach obligatorischem Training oder Abschluss der Handelsakademie auf die maximal zulÃ¤ssige Reichweite des Piloten gesetzt. Zum manuellen Einstellen deaktivieren.</t>
    <t id="11001">Build-Speicher-PrioritÃ¤t</t>
    <t id="11002">Stations-PrioritÃ¤t</t>
    <t id="11003">Hilfsschiff-PrioritÃ¤t</t>
    <t id="11004">TrÃ¤ger-PrioritÃ¤t</t>
    <t id="11005">0 = deaktiviert. 1-10 = Score-Multiplikator (10 = stÃ¤rkste Gewichtung). Endscore = Versorgungsscore Ã— Multiplikator.</t>
    <t id="11006">1 = kein Extra-Score (PrioritÃ¤tswarenliste unverÃ¤ndert). 2-10 = addiert (Multiplikatorâˆ’1)Ã— Basis-Versorgungsscore, wenn die Handelsware in der PrioritÃ¤tsliste steht. Wird auf den Typ-Score addiert.</t>
    <t id="11007">PrioritÃ¤tswaren-Bonus</t>
    <t id="11008">%1: Alle PrioritÃ¤tsregler fÃ¼r Lieferziele stehen auf 0 - dieser Auftrag hat keine Lieferziele. Aktivieren Sie mindestens eine Klasse (Bauspeicher, Stationen, Hilfsschiffe oder TrÃ¤ger), um VersorgungslÃ¤ufe fortzusetzen.</t>
    <t id="7001">[AUFSTIEG]</t>
    <t id="7002">[AUSBILDUNG]</t>
    <t id="7008">[ZURÃœCKGREIFEN]</t>
    <t id="7009">[ISOLIERT]</t>
    <t id="7003">[REPARIEREN]</t>
    <t id="7004">[Nachschub]</t>
    <t id="7005">[WARTUNG]</t>
    <t id="7006">[UMLEITEN]</t>
    <t id="7007">[FREIGABE]</t>
    <t id="1020">Heimatsektor oder Station wÃ¤hlen, an der der HÃ¤ndler arbeitet</t>
    <t id="1021">Maximale Sprungtor-Entfernung beim Kauf von Waren (begrenzt durch PilotenfÃ¤higkeit)</t>
    <t id="1022">Maximale Sprungtor-Entfernung beim Verkauf von Waren (begrenzt durch PilotenfÃ¤higkeit)</t>
    <t id="1023">Automatische Auswahl geeigneter Waren nach Kategorie</t>
    <t id="1024">Manuelle Auswahl spezifischer Handelswaren</t>
    <t id="1025">Handel mit Schmuggelware und illegalen GÃ¼tern erlauben</t>
    <t id="1026">Sicherheitstoleranz: 0,0 = Nur sichere Sektoren, 1,0 = Alle Risiken akzeptieren</t>
    <t id="1027">PilotenfÃ¤higkeiten durch Handelserfahrung verbessern</t>
    <t id="1028">Piloten automatisch zum Training senden, wenn nÃ¶tig</t>
    <t id="1029">Koordinieren Sie mehrere Handelsschiffe, um Konflikte zu vermeiden</t>
    <t id="1030">Waren-Fokus: 0=Ausgewogen, 1=Fortgeschritten, 2=GrundbedÃ¼rfnisse, 3=Illegal, 4=Massenwaren</t>
    <t id="1031">Handelsbereich: 0=Ausgeglichen, 1=Home-Fokus, 2=Free Roam</t>
    <t id="1032">Benachrichtigungsstufe: 0=Minimal, 1=Normal, 2=Detaillierte Nachrichten</t>
    <t id="1033">Ziel-Laderaumnutzungsprozentsatz vor Priorisierung von VerkÃ¤ufen</t>
    <t id="1034">Wie oft werden Marktdaten und Preisinformationen aktualisiert?</t>
    <t id="1035">Debug-Ausgabestufe: 0=Keine, 1=Basis, 2=AusfÃ¼hrliche Protokollierung</t>
    <t id="1036">Profitable Handelsrouten mit Flotte teilen (zwischengespeichert fÃ¼r schnellen Zugriff)</t>
    <t id="1037">Mindestgewinn erforderlich, um den Handel zwischenzuspeichern und mit der Flotte zu teilen</t>
    <t id="1038">Maximaler GewinnrÃ¼ckgang erlaubt, bevor gecachte Handelsrouten ungÃ¼ltig werden</t>
    <t id="1039">Wie lange gecachte Handelsrouten gÃ¼ltig bleiben, bevor sie ablaufen</t>
    <t id="1040">Detaillierte Protokollierung einzelner Handelsauswertungen und Ablehnungen aktivieren (kann sehr ausfÃ¼hrlich sein)</t>
    <t id="1041">Pro-Handel Logbuch-EintrÃ¤ge und immersive Trainings-Nachrichten aktivieren (TaterTrader-Stil)</t>
    <t id="1053">Sektoren in dieser Liste sind von Blacklists ausgeschlossen (immer erlaubt)</t>
    <t id="1055">TrÃ¤ger und Hilfsschiffe vom Handel ausschlieÃŸen</t>
    <t id="1057">Bau-Lager-Schiffe vom Handel ausschlieÃŸen</t>
    <t id="1059">Stations-Handelsregeln bei der Angebotssuche ignorieren (fortgeschritten; kann normalerweise blockierte Angebote auswÃ¤hlen)</t>
    <t id="1061">Ãœberspringen Sie Spielerstationen, denen ein MK1-HÃ¤ndler mit Versorgungsmodus zugewiesen ist</t>
    <t id="1062">Steigern Sie die Handelspunkte fÃ¼r Strecken, an denen Ihre eigenen Stationen beteiligt sind (10 % Punktebonus)</t>
    <t id="1071">Wenn â€žIllegale Waren zulassenâ€œ aktiviert ist, handeln Sie nur illegale Waren, wenn diese in allen Sektoren auf dem Sprungpfad (Kauf-, Verkaufs- und Zwischensektoren) legal sind.</t>
    <t id="1087">Maximale Sprungentfernung von zu Hause aus fÃ¼r die Suche nach LieferanteneinkÃ¤ufen</t>
    <t id="1089">Bei Deaktivierung kann das Schiff Stationen im Abdeckungsbereich nach DringlichkeitsprioritÃ¤t statt im Nur-Heim-Modus versorgen</t>
    <t id="2000">%s hat %s XP gewonnen!</t>
    <t id="2001">%s ist aufgestiegen! Neues Level: %s</t>
    <t id="2002">%s benÃ¶tigt Training! Bitte zur nÃ¤chsten Werft oder Handelsstation senden.</t>
    <t id="2003">%s hat mit der Ausbildung bei %s begonnen</t>
    <t id="2004">%s hat das Training abgeschlossen und ist jetzt fÃ¼r Level %s zertifiziert!</t>
    <t id="2005">%s hat Skill Level %s nach dem Training erreicht! XP-Fortschritt bei %s freigeschaltet.</t>
    <t id="2006">%s hat Skill Level %s durch %s-Handel erreicht!</t>
    <t id="2007">%s hat Level-%s-Training abgeschlossen! XP-Fortschritt bei %s freigeschaltet.</t>
    <t id="3000">%s hat einen Handel abgeschlossen! Gewinn: %s Cr</t>
    <t id="3001">%s analysiert die Marktbedingungen...</t>
    <t id="3002">%s hat eine profitable Handelsroute gefunden!</t>
    <t id="3003">Keine profitablen Handelsrouten fÃ¼r %s verfÃ¼gbar</t>
    <t id="3100">Verkauf von %1 %2 aus Fracht an %3 zu %4. Ich sollte einen Gewinn von %5 erzielen.</t>
    <t id="3101">Handelsauftrag fÃ¼r %1 %2 in Warteschlange. Kauf bei %3 von %4, Verkauf bei %5 an %6. Ich sollte %7 Gewinn erzielen.</t>
    <t id="3102">Station HÃ¤ndler: Versorge %1 %2 von %3 bei %5%% nach %4 bei %6%%.</t>
    <t id="3103">Station HÃ¤ndler: Verkaufe %1 %2 an %3 zu %4. Erwarteter Gewinn ist %5.</t>
    <t id="3104">Handel erfolgreich abgeschlossen fÃ¼r %1 %2. Gesamtgewinn: %3 Credits.</t>
    <t id="3105">Gespeicherte Handelsroute: %1 %2 von %3 bis %4 (Gewinn: %5 Cr)</t>
    <t id="3106">\nGesamter geschÃ¤tzter Lebenszeitgewinn vor diesem Handel: %1 Cr.</t>
    <t id="3107">Mehrfachhandel in Warteschlange: %1. Ich sollte %2 Gewinn erzielen.</t>
    <t id="3108">Verkaufe %1 %2 von %3 zu %4. Ich sollte einen Gewinn von %5 erzielen.</t>
    <t id="3110">Versorgungslauf fÃ¼r %1 %2 in Warteschlange. Bezug zu %3 von %4, Lieferung nach %5. Kunden-Einkaufsobergrenze %6 - %7/Einheit unter Obergrenze (%8 gesamt).</t>
    <t id="3111">Versorgungslauf fÃ¼r %1 %2 in Warteschlange von %3 nach %4.</t>
    <t id="3112">Versorgungslauf in Warteschlange (%1 Etappen): %2. Insgesamt %3 unter Kunden-Einkaufsobergrenze.</t>
    <t id="3113">Station HÃ¤ndler: Export-Mehrfachhandel in Warteschlange: %1. Erwarteter Gewinn %2.</t>
    <t id="3120">Pilotentransfer eingeleitet</t>
    <t id="3121">Ãœbertragungsprotokoll bestÃ¤tigt. %1 (%2) und %3 (%4) fahren zu %5 (%6), um anzudocken und Kommandositze auszutauschen.</t>
    <t id="3200">Hallo Kommandant %1,\n\nIch habe genug Erfahrung gesammelt, um meine ZertifizierungsprÃ¼fung fÃ¼r den Titel "%2" abzulegen. Die PrÃ¼fung wird etwa %3 Minuten bei %4 dauern.\n\nDies ist ein wichtiger Meilenstein in meiner Karriereentwicklung. Die PrÃ¼fung wird mein Wissen Ã¼ber fortgeschrittene Handelsprotokolle, Marktanalyse und Flottenkoordinationsverfahren testen.\n\nIch bin zuversichtlich in meine FÃ¤higkeiten und freue mich darauf, mich als wÃ¼rdig fÃ¼r diesen Aufstieg zu erweisen. WÃ¼nschen Sie mir GlÃ¼ck!\n\nHochachtungsvoll,\n%5\nAn Bord von %6</t>
    <t id="3201">Kommandant %1,\n\nAusgezeichnete Nachrichten! Ich habe meine ZertifizierungsprÃ¼fung erfolgreich abgeschlossen und den Titel "%2" erhalten!\n\nDie PrÃ¼fung umfasste fortgeschrittene Handelsstrategien, Risikobewertungsprotokolle und Flottenkoordinationsverfahren. Ich freue mich, berichten zu kÃ¶nnen, dass ich mit Auszeichnung bestanden habe.\n\nIch bin jetzt qualifiziert, komplexere Handelsoperationen durchzufÃ¼hren und freue mich darauf, noch mehr zum Erfolg unserer Flotte beizutragen. Vielen Dank fÃ¼r die Investition in meine berufliche Entwicklung.\n\nMit erneuter Hingabe,\n%3\nZertifiziert %2\nAn Bord von %4</t>
    <t id="3202">Kommandant %1,\n\nIch bedaure, Ihnen mitteilen zu mÃ¼ssen, dass meine ZertifizierungsprÃ¼fung aufgrund operativer Anforderungen unterbrochen wurde. Ich werde sie neu terminieren mÃ¼ssen, sobald die UmstÃ¤nde es erlauben.\n\nIch bleibe dem Fortschritt meiner FÃ¤higkeiten verpflichtet und werde Sie benachrichtigen, wenn ich den PrÃ¼fungsprozess fortsetzen kann.\n\nHochachtungsvoll,\n%2\nAn Bord von %3</t>
    <t id="3203">Kommandant %1,\n\nIch bin derzeit auf dem Weg nach %2 fÃ¼r meine ZertifizierungsprÃ¼fung. Die Reise gibt mir Zeit, meine Studien zu Ã¼berprÃ¼fen und mich mental auf diesen wichtigen Schritt in meiner Karriere vorzubereiten.\n\nErwartete Ankunft: %3 Minuten\nPrÃ¼fungsdauer: %4 Minuten\n\nIch schÃ¤tze Ihr Vertrauen in meine FÃ¤higkeiten und die Gelegenheit zum Aufstieg.\n\nMit Entschlossenheit,\n%5\nAn Bord von %6</t>
    <t id="3204">Kommandant,\n\nIch habe wÃ¤hrend meiner SystemprÃ¼fung Ladung in meinem Laderaum festgestellt. Bevor ich normale Handelsoperationen beginnen kann, muss ich diese Waren verkaufen.\n\nIch nutze unsere Handelssuche, um den besten KÃ¤ufer zu finden und diese Ladung sicher zu entladen. Sobald mein Laderaum leer ist, werde ich mit automatisiertem Handel fortfahren.\n\nStatus: Suche nach optimalem Verkaufsort\n\nMit Sorgfalt,\nAn Bord von %1</t>
    <t id="3205">Kommandant,\n\nMeine RumpfintegritÃ¤t ist auf %1%% gesunken (Schwelle: %2%%). Als Level-%3-Pilot bin ich berechtigt, Auto-Reparaturdienste anzufordern.\n\nIch begebe mich nach %4 fÃ¼r Reparaturarbeiten. Die geschÃ¤tzten Kosten betragen %5 Cr, was innerhalb unseres Budgets liegt.\n\nSobald die Reparaturen abgeschlossen sind, werde ich die Handelsoperationen mit vollstÃ¤ndiger struktureller IntegritÃ¤t fortsetzen.\n\nHochachtungsvoll,\nAn Bord von %6</t>
    <t id="3206">Kommandant,\n\nDRINGENDE FINANZWARNUNG\n\nMeine RumpfintegritÃ¤t ist kritisch bei %1%% (Schwelle: %2%%), aber unsere verfÃ¼gbaren Mittel (%3 Cr) sind unzureichend fÃ¼r vollstÃ¤ndige Reparaturen (geschÃ¤tzte Kosten: %4 Cr).\n\nIch begebe mich nach %5 fÃ¼r TEILREPARATUREN mit unseren verfÃ¼gbaren Mitteln. Dies ist keine ideale LÃ¶sung, aber notwendig, um die BetriebsfÃ¤higkeit aufrechtzuerhalten.\n\nBitte erwÃ¤gen Sie, zusÃ¤tzliche Mittel fÃ¼r zukÃ¼nftige Wartungsoperationen bereitzustellen.\n\nBesorgt aber entschlossen,\nAn Bord von %6</t>
    <t id="3207">Kommandant,\n\nMeine Level-%1-Zertifizierung autorisiert automatische NachrÃ¼stung von VerteidigungsausrÃ¼stung. Nach ÃœberprÃ¼fung meiner Systeme habe ich festgestellt, dass meine GegenmaÃŸnahmen und Einsetzbaren unter den empfohlenen Schwellenwerten liegen.\n\nIch begebe mich nach %2, um meine VerteidigungsausrÃ¼stung aufzustocken:\nâ€¢ GegenmaÃŸnahmen: AuffÃ¼llen auf optimale KapazitÃ¤t\nâ€¢ Verteidigungsdrohnen, Handelsdrohnen, LasertÃ¼rme: Anwenden des Balance-Profils\n\nDiese NachrÃ¼stung stellt sicher, dass ich bestmÃ¶glich gegen Weltraum-Bedrohungen geschÃ¼tzt bin, wÃ¤hrend ich die Handelseffizienz aufrechterhalte.\n\nMit Wachsamkeit,\nAn Bord von %3</t>
    <t id="3212">Kommandant,\n\nMeine RumpfintegritÃ¤t ist auf %1%% gesunken (Schwelle: %2%%), und ich benÃ¶tige Reparaturservices. Die nÃ¤chste Reparaturstation bei %3 ist jedoch derzeit aufgrund von Sektor-ReisebeschrÃ¤nkungen (schwarze Routen) nicht erreichbar.\n\nIch werde trotz dieser EinschrÃ¤nkung mit Handelsoperationen fortfahren. Sobald sichere Routen wieder verfÃ¼gbar sind, werde ich automatisch Reparaturservices suchen.\n\nIch werde die Situation Ã¼berwachen und Sie benachrichtigen, wenn Reparaturen mÃ¶glich werden.\n\nHochachtungsvoll,\nAn Bord von %4</t>
    <t id="3213">Kommandant,\n\nMeine VerteidigungsausrÃ¼stung benÃ¶tigt NachrÃ¼stung, aber die nÃ¤chste AusrÃ¼stungsstation bei %1 ist derzeit aufgrund von Sektor-ReisebeschrÃ¤nkungen (schwarze Routen) nicht erreichbar.\n\nIch werde trotz dieser EinschrÃ¤nkung mit Handelsoperationen fortfahren. Sobald sichere Routen wieder verfÃ¼gbar sind, werde ich automatisch NachrÃ¼stungsservices suchen.\n\nIch werde die Situation Ã¼berwachen und Sie benachrichtigen, wenn NachrÃ¼stung mÃ¶glich wird.\n\nHochachtungsvoll,\nAn Bord von %2</t>
    <t id="3208">Kommandant,\n\nIch habe eine umfassende Marktanalyse von %1 und umliegenden Sektoren (innerhalb %2 SprÃ¼ngen, Mindestgewinnschwelle: %3 Cr) abgeschlossen, aber leider keine profitablen HandelsmÃ¶glichkeiten gefunden, die unseren Anforderungen entsprechen.\n\nHANDELSANALYSEBERICHT:\nGesamt bewertete MÃ¶glichkeiten: %4\n\nABLEHNUNGSÃœBERSICHT:\n- AndockbeschrÃ¤nkungen: %5 Handels\n  (Station erlaubt meine Schiffsklasse nicht)\n- Unzureichende ProfitabilitÃ¤t: %6 Handels\n  (Unter Mindestgewinnschwelle)\n- Unzureichendes Volumen: %7 Handels\n  (Null oder negative handelbare Menge)\n- SicherheitsbeschrÃ¤nkungen: %8 Handels\n  (Schwarze Stationen oder gefÃ¤hrliche Sektoren)\n\nEMPFOHLUNGEN:\n- Gewinnschwellen anpassen erwÃ¤gen\n- Maximale Handelsdistanz erweitern\n- Sektor-Schwarze-Liste-Einstellungen Ã¼berprÃ¼fen\n- Auf Verbesserung der Marktbedingungen warten\n\nIch werde den Markt weiter Ã¼berwachen und Sie benachrichtigen, wenn profitable MÃ¶glichkeiten verfÃ¼gbar werden.\n\nBereitstehend,\nAn Bord Ihres Dienstes</t>
    <t id="3209">Kommandant,\n\nDRINGENDE ROUTENWARNUNG\n\nMein BedrohungsaufklÃ¤rungssystem hat festgestellt, dass Sektor %1 (Bedrohungsstufe %2) jetzt in meiner geplanten Handelsroute liegt. FÃ¼r die Sicherheit des Schiffes und der Besatzung breche ich sofort die aktuelle Handelsoperation ab.\n\nDURCHGEFÃœHRTE MAÃŸNAHMEN:\n- Alle HandelsauftrÃ¤ge storniert\n- RÃ¼ckkehr zum sicheren Betriebsmodus\n- Werde alternative Handelsroute finden, die gefÃ¤hrliche Sektoren vermeidet\n- Ladungshandhabung: Automatisch (wird bei Bedarf Ladung an sicherem Ort verkaufen)\n\nDas dynamische Schwarze-Liste-System wird zukÃ¼nftige Handels durch diesen Sektor verhindern, bis die Bedrohung beseitigt ist.\n\nSicherheit hat oberste PrioritÃ¤t.\n\nMit Wachsamkeit,\nAn Bord von %3</t>
    <t id="3210">Kommandant,\n\nFLUCHTROUTE INITIIERT\n\nIch befinde mich derzeit in schwarzem Sektor %1 und habe eine Handelsroute gefunden, die mir eine sichere Flucht ermÃ¶glicht.\n\nHANDELSROUTE:\nKaufen: %2 (Sektor: %3)\nVerkaufen: %4 (Sektor: %5)\nWare: %6 (x%7)\nErwarteter Gewinn: %8 Cr\n\nDas Schiff wird den schwarzen Sektor nach Abschluss dieses Handels verlassen.\n\nHochachtungsvoll,\nAn Bord Ihres Dienstes</t>
    <t id="3211">Kommandant,\n\nISOLIERTER HANDELSMODUS\n\nIch befinde mich derzeit in Sektor %2, aber alle Routen zu anderen Sektoren sind durch schwarze Hub-Sektoren blockiert. Das bedeutet, ich kann nur innerhalb meines aktuellen Sektors handeln, bis sich die Schwarze-Liste-Situation Ã¤ndert.\n\nSITUATION:\nAktueller Sektor: %2\nStatus: Isoliert (nicht-schwarzer Sektor mit blockierten Routen)\nHandelsmodus: Nur Sektor-interner Handel\n\nMein Handelssystem hat automatisch Gewinnschwellen angepasst, um verfÃ¼gbare Sektor-interner HandelsmÃ¶glichkeiten zu priorisieren.\n\nIch werde die Situation weiter Ã¼berwachen und Sie benachrichtigen, wenn Routen wieder verfÃ¼gbar werden.\n\nHochachtungsvoll,\nAn Bord von %1</t>
    <t id="3218">Kommandant,\n\nROUTENWEGÃ„NDERUNG ERKANNT\n\nBeim Betreten von Sektor %1 hat mein Navigationssystem festgestellt, dass sich die Route zu meinem Ziel %2 (%3) geÃ¤ndert hat.\n\nWEGANALYSE:\n- Normale Distanz: %4 SprÃ¼nge\n- Schwarze-Liste-bewusste Distanz: %5\n- Status: %6\n\nMein Navigationscomputer zeigt an, dass die bevorzugte Route aufgrund von Sektor-ReisebeschrÃ¤nkungen nicht mehr gangbar ist. FÃ¼r die Sicherheit des Schiffes und der Besatzung breche ich sofort die aktuelle Handelsoperation ab.\n\nDURCHGEFÃœHRTE MAÃŸNAHMEN:\n- Alle HandelsauftrÃ¤ge storniert\n- RÃ¼ckkehr zum sicheren Betriebsmodus\n- Werde alternative Handelsroute finden, die blockierte Sektoren vermeidet\n- Ladungshandhabung: Automatisch (wird bei Bedarf Ladung an sicherem Ort verkaufen)\n\nMein Navigationssystem wird automatisch blockierte Sektoren bei zukÃ¼nftiger Routenplanung vermeiden.\n\nSicherheit hat oberste PrioritÃ¤t.\n\nMit Wachsamkeit,\nAn Bord von %7</t>
    <t id="3219">Sektor %1 gerÃ¤umt - Alle Bedrohungen beseitigt</t>
    <t id="3220">Kommandant,\n\nFEINDSCHIFF ENTKOMEN\n\nUnser BedrohungsaufklÃ¤rungssystem hat das Feindschiff %3 verloren, das aus schwarzem Sektor %1 entkommen ist.\n\nDETAILS:\n- Entkommenes Schiff: %3\n- Verlassener Sektor: %1\n- Zielsektor: %2\n- Status: Verfolgung verloren - Schiff hat unseren Ã¼berwachten Bereich verlassen\n\nWÃ¤hrend dieses Schiff keine Bedrohung mehr in Sektor %1 darstellt, haben wir den Sichtkontakt verloren und kÃ¶nnen seinen aktuellen Status oder seine Absichten in Sektor %2 nicht bestÃ¤tigen.\n\nUnsere Verfolgungssysteme werden Sektor %1 weiter auf verbleibende Bedrohungen Ã¼berwachen. Wenn alle verfolgten Feinde gehen oder eliminiert werden, wird der Sektor automatisch von der Schwarzen Liste entfernt.\n\nMit Wachsamkeit,\nBedrohungsaufklÃ¤rungssystem</t>
    <t id="3221">Kommandant,\n\nIch konnte keine profitablen HandelsmÃ¶glichkeiten in grÃ¶ÃŸerer Entfernung (bis zu %3 SprÃ¼ngen) finden, da diese Routen derzeit aufgrund von Sektor-ReisebeschrÃ¤nkungen (schwarze Wege) nicht erreichbar sind.\n\nSITUATION:\nAktueller Sektor: %2\nUrsprÃ¼nglicher Suchbereich: %3 SprÃ¼nge\nFallback-Suchbereich: %4 SprÃ¼nge\n\nIch werde meine Suche nun auf nahegelegene Sektoren innerhalb von %4 SprÃ¼ngen konzentrieren, wo Routen wahrscheinlicher zugÃ¤nglich sind. Dies sollte mir helfen, profitable Handels zu finden, die zuvor aufgrund von DistanzbeschrÃ¤nkungen herausgefiltert wurden, nicht aufgrund tatsÃ¤chlicher UnprofitabilitÃ¤t.\n\nIch werde Sie benachrichtigen, wenn ich geeignete HandelsmÃ¶glichkeiten in der nahen Umgebung finde.\n\nHochachtungsvoll,\nAn Bord von %1</t>
    <t id="3222">Kommandant,\n\nSEKTOR AUF SCHWARZE LISTE GESETZT\n\nUnser BedrohungsaufklÃ¤rungssystem hat feindliche AktivitÃ¤t in Sektor %1 erkannt und diesen Sektor automatisch auf die Schwarze Liste gesetzt, um unsere Handelsoperationen zu schÃ¼tzen.\n\nERKANNTE FEINDSCHIFFE:\n%2\n\nERKANNT VON: %3\n\nFÃ¼r die Sicherheit unserer Schiffe und Besatzung wurden alle Handelsrouten durch diesen Sektor blockiert. Unsere Schiffe werden automatisch um diesen Sektor herum routen, bis die Bedrohung eliminiert ist.\n\nDer Sektor wird automatisch von der Schwarzen Liste entfernt, sobald alle verfolgten Feindschiffe eliminiert sind oder das Gebiet verlassen.\n\nMit Wachsamkeit,\nBedrohungsaufklÃ¤rungssystem</t>
    <t id="3223">Kommandant,\n\nIch kann keine zugÃ¤ngliche Trainingsstation fÃ¼r meine PrÃ¼fung der Stufe %1 finden. Ich werde mit Handelsoperationen fortfahren, wie angewiesen, aber ich verstehe, dass ich keine Erfahrungspunkte erhalten werde, bis ich die erforderliche Ausbildung abschlieÃŸen kann. Nach diesem Handelslauf werde ich erneut nach einer mÃ¶glichen TrainingsmÃ¶glichkeit suchen.\n\nHochachtungsvoll,\nAn Bord von %2</t>
    <t id="3224">TrainingslizenzgebÃ¼hr: %1 Cr</t>
    <t id="3225">Bonus: Ich habe %1 zusÃ¤tzliche FÃ¤higkeitsstufe%2 durch angesammelte Erfahrung wÃ¤hrend des Trainings erhalten! Aktuelle Stufe: %3</t>
    <t id="3214">Es ist eine Ehre, fÃ¼r Sie zu arbeiten, %1! Ich freue mich darauf, meine Handelskarriere unter Ihrem Kommando zu beginnen. Ich werde mein Bestes tun, um Ihnen gut zu dienen und zu Ihrem Erfolg beizutragen.</t>
    <t id="3215">Vielen Dank fÃ¼r diesen wohlverdienten Urlaub, %1! Ich habe meine Zeit abseits des Handels genossen und meine FÃ¤higkeiten bleiben intakt. Ich freue mich darauf, zur Arbeit zurÃ¼ckzukehren, wann immer Sie mich brauchen. Bis dahin werde ich mein Handelswissen scharf halten!</t>
    <t id="3216">Ich bin aus dem Urlaub zurÃ¼ck und bereit, wieder zu arbeiten, %1! Meine HandelsfÃ¤higkeiten bleiben scharf und ich bin begierig darauf, Ihnen weiterhin auf %2 zu dienen. Vielen Dank fÃ¼r die wohlverdiente Ruhe!</t>
    <t id="3217">Vielen Dank fÃ¼r meine Versetzung zu %1, %2! Ich fÃ¼hle mich durch diese neue Aufgabe geehrt und werde ausgezeichnet auf mein neues Schiff aufpassen. Meine Handelserfahrung und FÃ¤higkeiten bleiben intakt, und ich bin bereit, Ihnen weiterhin zu dienen.</t>
    <t id="3227">Rumpf verloren, WÃ¼rde wartet auf Abholung</t>
    <t id="3228">Kommandant %1,\n\n%2 meldet sich aus %3. Mein Schiff ist explodiert. Ich nicht. Ich bin jetzt die teuerste schwebende Fracht der Flotte.\n\nKartenmarkierung angehÃ¤ngt. Bitte beeilen Sie sich - ich war mitten in einer Rechnung.\n\nProfessionell schwebend,\n%2</t>
    <t id="3229">Pilot gerettet - Sauerstoffsucht geheilt</t>
    <t id="3230">Kommandant %1,\n\nFlottenmeldung: %2 wurde von %3 (%4) aufgesammelt und stellt Ihnen keine verlÃ¤ngerte EVA-Ausbildung mehr in Rechnung.\n\nRegistrierung wird neu verknÃ¼pft. Empfehlung: keine Fragen zum alten Schiff.\n\nVerlegen,\n%2</t>
<t id="4000">Flottenkoordination: %s wurde Route %s zugewiesen</t>
    <t id="4001">Flottenkoordination: Route %s ist vollstÃ¤ndig ausgelastet</t>
    <t id="4002">Flottenkoordination: %s hat Route %s freigegeben</t>
    <t id="5000">%s wurde als primÃ¤res Gebiet fÃ¼r %s zugewiesen</t>
    <t id="5001">%s hat in %s die Kompetenzstufe %s erreicht!</t>
    <t id="5002">Angewendeter Gebietsbonus: %s %% Gewinnsteigerung in %s</t>
    <t id="9500">Fehler: %s steckt fest und benÃ¶tigt Hilfe!</t>
    <t id="9501">Fehler: Handel fehlgeschlagen fÃ¼r %s</t>
    <t id="9502">Fehler: %s kann nicht bei GalaxyTrader MK3 registriert werden</t>
    <t id="80001">Ware %s zur Schwarzen Liste hinzugefÃ¼gt</t>
    <t id="80002">Ware %s von der Blacklist entfernt</t>
    <t id="80003">Ware %s zur WeiÃŸen Liste hinzugefÃ¼gt</t>
    <t id="80004">Automatisch auf die schwarze Liste gesetzt (schlechte Leistung): %s</t>
    <t id="80005">GefÃ¤hrliche Ware priorisiert: %s</t>
    <t id="80006">Warenfilter: %s aktiv, %s Handel gesperrt</t>
    <t id="80007">Alle Warenfilter gelÃ¶scht</t>
    <t id="80008">Warenfilter auf Standard zurÃ¼ckgesetzt</t>
    <t id="80009">Warenfilterverwaltung</t>
    <t id="80010">Gesperrte Ware</t>
    <t id="80011">Erlaubte Waren</t>
    <t id="80012">GefÃ¤hrliche Waren-Behandlung</t>
    <t id="80013">Mindestwarenwert</t>
    <t id="80014">Maximaler Warenwert</t>
    <t id="80015">EingeschrÃ¤nkte Fraktionen</t>
    <t id="80016">Warenkategorien wurden vom aktuellen Spielstand aktualisiert</t>
    <t id="80017">%s Waren kategorisiert: %s Niedrigwert, %s gefÃ¤hrlich, %s Hochwert</t>
    <t id="80018">Dynamische Warenkategorisierung aktiviert</t>
    <t id="80019">Auto-Schwarze-Liste fÃ¼r Kategorie %s deaktiviert</t>
    <t id="80020">Neue Ware von anderen Mods erkannt und kategorisiert</t>
    <t id="9000">GalaxyTrader - Globale Einstellungen</t>
    <t id="9010">XP und Trainingssystem</t>
    <t id="9012">Automatisches Training</t>
    <t id="9013">XP-Multiplikator</t>
    <t id="9015">Kommandantenbonusprozentsatz</t>
    <t id="9020">Flottenkoordination</t>
    <t id="9021">Aktivieren Sie die Flottenkoordination</t>
    <t id="9023">Aktivieren Sie den Handelscache</t>
    <t id="9030">Benachrichtigungen</t>
    <t id="9031">Benachrichtigungsebene</t>
    <t id="9040">Autoreparatursystem</t>
    <t id="9041">Aktivieren Sie die automatische Reparatur</t>
    <t id="9042">Rumpfreparaturschwelle</t>
    <t id="9310">Galaxy-Miner</t>
    <t id="9311">Ressourcen-Sonden-Sektor-Scan-Wartezeit</t>
    <t id="9312">Schiffs-NÃ¤he-Gewichtung</t>
    <t id="9043">Mindestpilotenniveau</t>
    <t id="9004">Handelspreisspannen</t>
    <t id="9005">Verkauf Angebotspreis max</t>
    <t id="9006">Kaufangebotspreis Min</t>
    <t id="9007">Isoliert: Verkaufspreis max</t>
    <t id="9008">Isoliert: Kaufpreis Min</t>
    <t id="9009">Fallback: Verkaufspreis max</t>
    <t id="9014">Fallback: Kaufpreis min</t>
    <t id="9016">Gewinnschwellenbasis</t>
    <t id="9025">Min. Spielergeld</t>
    <t id="9024">Cache-Dropoff-Toleranz</t>
    <t id="9026">Leerlauf-Parkzeit bis Abdocken</t>
    <t id="9054">Blockieren Sie Sektoren feindlicher Fraktionen</t>
    <t id="9055">Bedrohungsstufe auf die schwarze Liste setzen</t>
    <t id="9056">Blacklist neu erstellen</t>
    <t id="9057">Neu erstellen</t>
    <t id="9058">Zuweisen zu GT Schiffen</t>
    <t id="9059">Zuordnen</t>
    <t id="9112">Sendet Piloten automatisch zum Training, wenn sie erforderliche Levels erreichen. Deaktivieren fÃ¼r manuelle Kontrolle des Trainingszeitpunkts.</t>
    <t id="9113">Passt an, wie schnell Piloten Erfahrung gewinnen. HÃ¶here Werte bedeuten schnelleren Fortschritt.</t>
    <t id="9115">Prozentsatz der untergeordneten XP, die an Kommandantenpiloten vergeben werden. Auf 0 % einstellen, um den Kommandanten-Bonus-EP zu deaktivieren. Standard: 10 %.</t>
    <t id="9121">Aktiviert intelligente Flottenkoordinationsfunktionen einschlieÃŸlich Routenoptimierung und Lastausgleich.</t>
    <t id="9123">ErmÃ¶glicht das Teilen profitabler HandelsmÃ¶glichkeiten zwischen Flottenmitgliedern fÃ¼r bessere Koordination.</t>
    <t id="9131">Steuert, wie viele Benachrichtigungen angezeigt werden: 0=Ruhe, 1=Nur wichtig, 2=Alle Benachrichtigungen</t>
    <t id="9141">Sendet Schiffe automatisch zur Reparatur nach Abschluss von Handels, wenn Rumpf unter Schwelle fÃ¤llt. Nur fÃ¼r erfahrene Piloten (Level 12+). Schiffe wÃ¤hlen geeignete Einrichtung: S/M AusrÃ¼stungsdock, L/XL Werft.</t>
    <t id="9142">Rumpfprozentsatz, unter dem Auto-Reparatur ausgelÃ¶st wird. Standard: 95%. Schiffe gehen automatisch zur nÃ¤chsten Reparatureinrichtung, wenn beschÃ¤digt.</t>
    <t id="9411">Wenn aktiviert, warten Minen-Schiffe beim Auswerten eigener Ressourcen-Sonden im Sektor (+5s pro Sonde Ã¼ber einer). Das GT-Pilotenlevel skaliert diese Wartezeit linear vom vollen Wert auf Stufe 1 bis 5 Sekunden auf Stufe 15 (nur GT-XP-Modus, wenn Wartezeit Ã¼ber 5 Sekunden). Deaktiviert = kein Warten (Vanilla-Verhalten).</t>
    <t id="9412">Lenkt MK3/MK4-Schiffe beim Sortieren validierter Trades zu nÃ¤heren Kaufstationen. Auswahl-Score = Handels-Score / (1 + SprÃ¼nge Schiffâ†’Kauf Ã— Gewicht). Schieberegler 0-100 (0 = aus; 4 = Standard 0,04). Beeinflusst weder Cache-Ranking noch Reichweitenlimits.</t>
    <t id="9143">Mindest-Pilotenlevel erforderlich fÃ¼r Auto-Reparatur-Funktion. Standard: 12 (erfahrene HÃ¤ndler). Niedrigere Level-Piloten mÃ¼ssen manuell reparieren.</t>
    <t id="9104">Maximaler relativer Preis fÃ¼r Verkaufsangebote (Schiff kauft VON Stationen). Bereich: -1.0 bis +1.0. Standard: 0.5 (50% Ã¼ber Durchschnitt). HÃ¶her = teurer aber mehr Optionen.</t>
    <t id="9105">Minimaler relativer Preis fÃ¼r Kaufangebote (Schiff verkauft AN Stationen). Bereich: -1.0 bis +1.0. Standard: -0.5 (50% unter Durchschnitt). Niedriger = gÃ¼nstigere KÃ¤ufer aber mehr Optionen.</t>
    <t id="9106">Verkaufspreis max fÃ¼r isolierte Schiffe (in einzelnen Sektor feststecken). Bereich: -1.0 bis +1.0. Standard: 0.5.</t>
    <t id="9107">Kaufpreis min fÃ¼r isolierte Schiffe (in einzelnen Sektor feststecken). Bereich: -1.0 bis +1.0. Standard: -0.5.</t>
    <t id="9108">Verkaufspreis max fÃ¼r Fallback-Suche (letzter Ausweg, wenn normale Suche fehlschlÃ¤gt). Bereich: -1.0 bis +1.0. Standard: 0.5. Fallback-Suche verwendet MaxDistance=2 und entspannte Gewinnschwellen.</t>
    <t id="9109">Kaufpreis min fÃ¼r Fallback-Suche (letzter Ausweg, wenn normale Suche fehlschlÃ¤gt). Bereich: -1.0 bis +1.0. Standard: -0.5. Fallback-Suche verwendet MaxDistance=2 und entspannte Gewinnschwellen.</t>
    <t id="9116">Basisminimumgewinn auf Level 15 fÃ¼r einen mittleren Trader (Referenzfracht 8200). Der tatsÃ¤chliche MinAbsoluteProfit wird pro Pilot berechnet und nach Fracht skaliert:\n\nbase(L) = Basis * ((L-1)^2 / 14^2)\nskaliert = Basis(L) * (Fracht / 8200)\nfinal = max(skaliert, 25% von Basis(L))\n\nAuf 0 setzen, um jeden Gewinn zu akzeptieren (es gelten nur ROI/Distanz/andere Filter).</t>
    <t id="9125">Minimales Spielergeld (Kredite) erforderlich, bevor Schiffe nach Trades suchen. Wenn Spielergeld unter diese Schwelle fÃ¤llt, Ã¼berspringen alle Schiffe Handelssuchen und warten, verhindern teures Cache-Scannen, das Spiel stottert. Bereich: 1.000 - 100.000 Cr. Standard: 1.000 Cr.</t>
    <t id="9124">Maximaler prozentualer ROI-Abfall vom zwischengespeicherten Wert vor der Ablehnung des Handels. Beispiel: 20 % zwischengespeicherter ROI mit 15 % Toleranz akzeptiert bis zu 17 % ROI (14 % RÃ¼ckgang).</t>
    <t id="9126">Minuten im Dock, bevor zum Freigeben des Dockplatzes abgedockt wird (0-60). 0 = bleibt angedockt, bis neue Arbeit gefunden wird. Standard: 1 Minute.</t>
    <t id="9154">Alle Sektoren, die feindlichen Fraktionen gehÃ¶ren, automatisch auf die schwarze Liste setzen (KontrollkÃ¤stchen â€žBeziehungâ€œ in der schwarzen Liste)</t>
    <t id="9155">Mindestbedrohungsstufe (1-5), die erforderlich ist, um einen Sektor auf die schwarze Liste zu setzen:\n2=Mittel (Einzelangriff)\n3=Mittel-Hoch (feindliche Fraktionen)\n4=Hoch (GroÃŸkampfschiffe/Raketen)\n5=Sehr hoch (Xenon/Khaak)</t>
    <t id="9156">Bedrohungsvermeidungs-Schwarze Liste manuell neu erstellen (nÃ¼tzlich, wenn gelÃ¶scht)</t>
    <t id="9157">Weisen Sie die aktuelle dynamische Blacklist manuell allen GT Flottenkommandantenschiffen zu. Untergebene erben von ihrem Kommandanten.</t>
    <t id="6001">Lehrling</t>
    <t id="6002">Kurier</t>
    <t id="6003">Anbieter</t>
    <t id="6004">HÃ¤ndler</t>
    <t id="6005">HÃ¤ndler</t>
    <t id="6006">FernhÃ¤ndler</t>
    <t id="6101">Ausgewogen</t>
    <t id="6102">Defensive</t>
    <t id="6103">Tradingorientiert</t>
    <t id="6104">Schwere Verteidigung</t>
    <t id="6105">Turm-UnterstÃ¼tzung</t>
    <t id="9050">System zur Bedrohungsvermeidung</t>
    <t id="9051">Bedrohungsvermeidung aktivieren:</t>
    <t id="9052">Schwelle fÃ¼r feindselige Beziehungen:</t>
    <t id="9053">Verwenden Sie die dynamische Blacklist:</t>
    <t id="9151">Level 6+ HÃ¤ndler erkennen feindliche Schiffe und vermeiden gefÃ¤hrliche Routen. Deaktivierung stoppt alle Scans (verbessert Leistung). Risikotoleranz pro Schiff im Kommando-Verhalten (0-10 Skala).</t>
    <t id="9152">Markieren Sie nur Fraktionen, deren Verwandtschaft diesen Wert erreicht oder unterschreitet, als Bedrohung. Standard: -20 %</t>
    <t id="9153">Automatisch gefÃ¤hrliche Sektoren (Bedrohungsstufe 3+) auf Schwarze Liste setzen, um Schiffe zu zwingen, um Bedrohungen herum zu routen. Verwendet Vanilla-Pfadfindung fÃ¼r alternative Routen.</t>
    <t id="9060">VerteidigungsausrÃ¼stung Auto-NachrÃ¼stung (Level 15)</t>
    <t id="9061">Auto-NachrÃ¼stung aktivieren:</t>
    <t id="9062">GegenmaÃŸnahmen auffÃ¼llen:</t>
    <t id="9063">Verteidigungsdrohnen auffÃ¼llen:</t>
    <t id="9064">Handelsdrohnen auffÃ¼llen:</t>
    <t id="9065">LasertÃ¼rme auffÃ¼llen:</t>
    <t id="9066">Reparaturdrohnen auffÃ¼llen:</t>
    <t id="9067">GegenmaÃŸnahmen-Schwelle:</t>
    <t id="9068">Einheitliche KapazitÃ¤tsschwelle:</t>
    <t id="9069">AusrÃ¼stungs-Balance-Profil:</t>
    <t id="9161">Meister-HÃ¤ndler (Level 15) rÃ¼sten automatisch VerteidigungsausrÃ¼stung nach Handels auf. Gilt fÃ¼r Kommandanten-Level bei Untergebenen.</t>
    <t id="9162">Alle Schiffe (S/M/L/XL). Separate KapazitÃ¤t. Kritisch fÃ¼r Raketenabwehr.</t>
    <t id="9163">Nur L/XL Schiffe. Teilt einheitliche KapazitÃ¤t mit anderen Einsetzbaren.</t>
    <t id="9164">Nur L/XL Schiffe. Wesentlich fÃ¼r Handelsoperationen. Teilt einheitliche KapazitÃ¤t.</t>
    <t id="9165">Alle Schiffe. L/XL Schiffe teilen einheitliche KapazitÃ¤t, S/M verwenden Laderaum.</t>
    <t id="9166">Nur L/XL Schiffe. Funktioniert mit Auto-Reparatur-System. Teilt einheitliche KapazitÃ¤t.</t>
    <t id="9167">AuffÃ¼llen, wenn GegenmaÃŸnahmen unter diesem Prozentsatz (alle Schiffe, separate KapazitÃ¤t).</t>
    <t id="9168">AuffÃ¼llen, wenn Gesamt-Einsetzbare unter diesem Prozentsatz (L/XL Schiffe: Drohnen + TÃ¼rme teilen eine KapazitÃ¤t).</t>
    <t id="9169">Verteilung der einheitlichen KapazitÃ¤t (L/XL Schiffe): Handelsorientiert (20/50/20/10), Ausgewogen (35/35/20/10), Defensiv (50/20/20/10), Schwere Verteidigung (40/30/20/10), Turm-UnterstÃ¼tzung (30/30/30/10). VerhÃ¤ltnisse: Verteidigung/Handel/TÃ¼rme/Reparatur. Klicken zum Durchschalten der Optionen.</t>
    <t id="9090">Schiffsmodifikationen</t>
    <t id="9091">Schiffsmodifikationen aktivieren</t>
    <t id="9191">Installieren Sie automatisch Schiffs- und Motormodifikationen basierend auf der Pilotenebene. Level 9+ = Level 1-Mods, Level 12+ = Level 2-Mods, Level 15+ = Level 3-Mods. Wenn die Bestellung storniert wird, werden nur von GT installierte Mods entfernt.</t>
    <t id="9070">Konfiguration der Schiffsbenennung</t>
    <t id="9071">XP anzeigen:</t>
    <t id="9072">Anzeigerang:</t>
    <t id="9073">Anzeigeebene:</t>
    <t id="9074">Anzeigestatus:</t>
    <t id="9075">Schiffsumbenennung aktivieren:</t>
    <t id="9076">PrÃ¤fix</t>
    <t id="9077">Suffix</t>
    <t id="9078">Standard-Namensquelle:</t>
    <t id="9079">Modellname</t>
    <t id="9080">Typname</t>
    <t id="9081">Modellbasis</t>
    <t id="9083">Benutzerdefinierter Name</t>
    <t id="9084">Heimatsektor anzeigen:</t>
    <t id="9085">Benennungsmodus:</t>
    <t id="9086">Klassisch</t>
    <t id="9087">Muster</t>
    <t id="9088">Namensmuster:</t>
    <t id="9089">Platzhalter: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. Atomar: {RS} {CB} {BL} usw. Nutzt Status-AbkÃ¼rzungen unten. Leere Token entfallen; Leerzeichen werden zusammengefasst. Max. 128 Zeichen.</t>
    <t id="9183">Den konfigurierten Heimatsektor im Schiffsnamen anzeigen (PrÃ¤fix oder Suffix).</t>
    <t id="9184">Benutzerdefiniertes Namensformat mit {TOKEN}-Platzhaltern statt Legacy-Layout. Erfordert GalaxyTrader-XP (kein Vanilla-XP-Modus).</t>
    <t id="9092">Muster-Platzhalter</t>
    <t id="9093">Schiff: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT-XP: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla-XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Heimat: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Besatzung: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Sektor: {SECTOR} | Statistik: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Status-Marker:</t>
    <t id="9100">{OPSTATE}: alle aktiven Betriebsflags kombiniert (z. B. CB RS, MT)</t>
    <t id="9101">{STATUS}: blockiert, Training, Fallback oder isoliert</t>
    <t id="9102">{CB}: nur eigene Blacklist; in {OPSTATE} enthalten; nicht kombinieren</t>
    <t id="9082">Schiffsklasse anzeigen:</t>
    <t id="9171">XP-Werte in Schiffsnamen anzeigen</t>
    <t id="9175">Aktivieren oder deaktivieren Sie die automatische Schiffsumbenennung mit Piloteninformationen</t>
    <t id="9172">Rangtitel in Schiffsnamen anzeigen</t>
    <t id="9173">Levelnummern in Schiffsnamen anzeigen</t>
    <t id="9174">Handelsstatus in Schiffsnamen anzeigen</t>
    <t id="9178">Quelle fÃ¼r Schiffs-Basisnamen wÃ¤hlen: Modellname (mit Variante), Typname (generisch) oder Basisname (ohne Variante)</t>
    <t id="9182">Schiffsklasse (S, M, L, XL) in Schiffsnamen anzeigen</t>
    <t id="9200">Debug-Einstellungen</t>
    <t id="9201">Aktivieren Sie die Debug-Protokollierung:</t>
    <t id="9202">Hauptumschalter fÃ¼r alle debug_text-Ausgaben. Wenn deaktiviert, wird alle Debug-Protokollierung unterdrÃ¼ckt. Wenn aktiviert, erscheinen Debug-Nachrichten im DebugLog basierend auf individuellen debug_text-Chance-Werten.</t>
    <t id="9220">Wartung und Diagnose</t>
    <t id="9221">Gewinnstatistiken zurÃ¼cksetzen:</t>
    <t id="9222">ZURÃœCKSETZEN</t>
    <t id="9223">Alle schwarzen Sektoren lÃ¶schen:</t>
    <t id="9224">LÃ–SCHEN</t>
    <t id="9225">Alle Einstellungen auf Standardwerte zurÃ¼cksetzen:</t>
    <t id="9226">ALLE ZURÃœCKSETZEN</t>
    <t id="9323">Entfernt alle Sektoren von der BedrohungsaufklÃ¤rungs-Schwarzen Liste. Dies lÃ¶scht sofort alle schwarzen Sektoren und erlaubt Ihren Schiffen, zu zuvor blockierten Gebieten zu reisen. Verwenden Sie dies, wenn Sie das Bedrohungsvermeidungssystem zurÃ¼cksetzen mÃ¶chten oder wenn Sektoren fÃ¤lschlicherweise auf die Schwarze Liste gesetzt wurden.</t>
    <t id="9321">Setzt alle Gewinnstatistiken auf 0 fÃ¼r alle Piloten und Schiffe zurÃ¼ck. Verwenden Sie dies nach Upgrade auf v0.6.0, um aufgeblÃ¤hte umsatzbasierte Statistiken zu lÃ¶schen. Die Korrektur verfolgt jetzt tatsÃ¤chlichen GEWINN (Umsatz - Kaufkosten). Handelsanzahlen und XP bleiben erhalten.</t>
    <t id="9325">Setzt alle globalen Einstellungen auf ihre Standardwerte zurÃ¼ck. Dies umfasst XP-Einstellungen, Flottenkoordination, Benachrichtigungen, Mobile AufklÃ¤rung, Bedrohungsvermeidung, Schiffsbenennung, Auto-Reparatur, Modifikationen, Leistung und Zahlenformat. Die Debug-Protokollierungseinstellung bleibt erhalten, um die Protokollierung des ZurÃ¼cksetzungsvorgangs zu ermÃ¶glichen.</t>
    <t id="9227">Handels-Cache fÃ¼r alle Heimatsektoren lÃ¶schen:</t>
    <t id="9228">CACHE LÃ–SCHEN</t>
    <t id="9327">LÃ¶scht den Handels-Cache fÃ¼r alle Heimatsektoren. Dies zwingt alle Schiffe, bei ihrer nÃ¤chsten Handelssuche frische Live-Suchen durchzufÃ¼hren. Verwenden Sie dies, wenn der Cache veraltet oder beschÃ¤digt erscheint, oder wenn Sie eine vollstÃ¤ndige Cache-Aktualisierung erzwingen mÃ¶chten.</t>
    <t id="9229">Alle Suchsperren lÃ¶sen</t>
    <t id="9329">LÃ¶st ALLE aktiven Handelssuch-Sperren und leert zugehÃ¶rige temporÃ¤re ZustÃ¤nde. Verwenden Sie dies, wenn Schiffe durch veraltete Sperren aus alten SpielstÃ¤nden in â€žSuche nach Handelsangebotenâ€œ festhÃ¤ngen. Kann legitime Suchen unterbrechen.</t>
    <t id="9290">Status des Dump Trade Hubs:</t>
    <t id="9291">ENTSORGEN</t>
    <t id="9390">Zeigt einen einmaligen Schnappschuss des zentralen Handelshubs (Schedulerwarteschlangen + Status des letzten anfragenden Schiffs) im Protokoll und als Benachrichtigung.</t>
    <t id="9292">Handels-Cache ausgeben (VOLLSTÃ„NDIG):</t>
    <t id="9293">Cache lÃ¶schen</t>
    <t id="9392">VOLLSTÃ„NDIGER Cache-Dump (kann sehr groÃŸ sein). Schreibt alle Cache-EintrÃ¤ge in BlÃ¶cken ins DebugLog. Erneut klicken zum Abbrechen.</t>
    <t id="9294">Flottenreservierungen lÃ¶schen:</t>
    <t id="9295">{77000,9224}</t>
    <t id="9394">LÃ¶scht alle aktiven Flottenhandelsreservierungen. Verwenden Sie dies, wenn Schiffe festzusitzen scheinen und darauf warten, dass reservierte GeschÃ¤fte ablaufen, oder wenn die Reservierungstabelle nach dem Laden eines alten Speicherstands veraltet ist.</t>
    <t id="9230">Leistung</t>
    <t id="9231">Batch-VerarbeitungsverzÃ¶gerung:</t>
    <t id="9232">ValidierungsverzÃ¶gerung:</t>
    <t id="9233">Max. gleichzeitige Suchanfragen:</t>
    <t id="9234">Max. zurÃ¼ckzugebende Handels:</t>
    <t id="9235">Maximale Angebote pro Ware:</t>
    <t id="9236">Max. Trades pro Ware:</t>
    <t id="9237">Max. Angebote pro Ware fÃ¼r Matching:</t>
    <t id="9238">FrÃ¼he Ausstiegsschwelle:</t>
    <t id="9241">Live-Angebot-Slice-Intervall:</t>
    <t id="9266">TTL fÃ¼r Suchsperre:</t>
    <t id="9263">Batch-Verarbeitungs-Chunk-GrÃ¶ÃŸe:</t>
    <t id="9239">Zahlenformat</t>
    <t id="9240">Formatstil:</t>
    <t id="9242">Verwenden Sie das Suffix M</t>
    <t id="9243">M-Suffix-Schwellenwert:</t>
    <t id="9244">Deutsch (123.456,78)</t>
    <t id="9245">Englisch (123,456.78)</t>
    <t id="9510">Level-Aufstieg Popup-Benachrichtigungen:</t>
    <t id="9511">Schulungsbedarf-Warnungen:</t>
    <t id="9512">Schulungsabschluss-Benachrichtigungen:</t>
    <t id="9513">Gewinnberichte:</t>
    <t id="9514">Marktbenachrichtigungen:</t>
    <t id="9515">Flotten-Updates:</t>
    <t id="9516">Verwenden Sie nur Vanilla XP</t>
    <t id="9610">Aktivieren oder deaktivieren Sie HÃ¤ndler-Level-Aufstiegs-Popup-Benachrichtigungen in der Spieler-UI.</t>
    <t id="9611">Warnung, wenn Piloten eine Schulung benÃ¶tigen, um auf die nÃ¤chste Stufe aufzusteigen.</t>
    <t id="9612">Benachrichtigung, wenn Piloten die Schulung abschlieÃŸen und im Rang aufsteigen.</t>
    <t id="9613">Periodische Gewinnzusammenfassungen (einfache und umfassende Berichte).</t>
    <t id="9614">AuÃŸergewÃ¶hnliche Marktchancen und hochwertige Handelswarnungen.</t>
    <t id="9615">Flottenkoordinationsnachrichten und Statusaktualisierungen.</t>
    <t id="9616">Verwenden Sie pilot.skill.piloting und deaktivieren Sie GT XP progression/caps.</t>
    <t id="9246">Einfacher Bericht HÃ¤ufigkeit:</t>
    <t id="9247">Umfassender Bericht HÃ¤ufigkeit:</t>
    <t id="9248">Max. gleichzeitige Cache-Suchen:</t>
    <t id="9249">Max. gleichzeitige Live-Suchen:</t>
    <t id="9340">Zahlenformat wÃ¤hlen: Deutsch verwendet '.' fÃ¼r Tausender und ',' fÃ¼r Dezimalstellen (123.456,78), Englisch verwendet ',' fÃ¼r Tausender und '.' fÃ¼r Dezimalstellen (123,456.78)</t>
    <t id="9342">M-Suffix fÃ¼r Zahlen grÃ¶ÃŸer als Schwellenwert aktivieren (z.B. 1.0 M statt 1,000,000)</t>
    <t id="9343">Schwellenwert fÃ¼r M-Suffix. Zahlen Ã¼ber diesem Wert werden mit M-Suffix angezeigt (Standard: 999,999)</t>
    <t id="9346">HÃ¤ufigkeit des einfachen Berichts (Popup-Benachrichtigung): 1-30 Minuten (Standard: 1 Minute). Gewinnberichte-Schalter zum Deaktivieren verwenden.</t>
    <t id="9347">HÃ¤ufigkeit des umfassenden Berichts (Logbucheintrag): 1-60 Minuten (Standard: 30 Minuten). Gewinnberichte-Schalter zum Deaktivieren verwenden.</t>
    <t id="9398">Verwenden Sie die Ãœberschreibung der fÃ¤lligen GT-Credits</t>
    <t id="9399">Ersetzen oder erweitern Sie die Vanilla-Zeile â€žCR fÃ¤llig aus Tradesâ€œ durch den prognostizierten GT-Wert im selben UI-Slot.</t>
    <t id="9331">VerzÃ¶gerung zwischen Batches wÃ¤hrend Handelsuch-Verarbeitung (1-100ms). HÃ¶here Werte reduzieren CPU-Last, verlangsamen aber Handelsuchen. Standard: 50ms. Verwendet in Batch-Prozessor und Handelslisten-Filterung.</t>
    <t id="9332">VerzÃ¶gerung zwischen Handelsvalidierungen im AI-Skript (1-100ms). HÃ¶here Werte reduzieren CPU-Last, verlangsamen aber Handelsvalidierung. Standard: 50ms. Verwendet beim Validieren der Handelsliste vom MD-System.</t>
    <t id="9333">Maximale Anzahl von Handelsuchen, die gleichzeitig laufen kÃ¶nnen (1-10). Niedrigere Werte reduzieren CPU-Last, erhÃ¶hen aber Warteschlangen-Wartezeiten. HÃ¶here Werte verarbeiten Suchen schneller, kÃ¶nnen aber Leistungsspitzen verursachen. Standard: 1.</t>
    <t id="9334">Maximale Anzahl von Handels, die von Cache-Suche zurÃ¼ckgegeben werden (50-1000). HÃ¶here Werte bieten mehr Handelsoptionen, erhÃ¶hen aber Verarbeitungszeit. Niedrigere Werte reduzieren CPU-Last, kÃ¶nnen aber profitable Handels verpassen. Standard: 200.</t>
    <t id="9335">Maximale Anzahl von Angeboten pro Ware zur Verarbeitung in Live-Suche (5-100). HÃ¶here Werte berÃ¼cksichtigen mehr Angebote, erhÃ¶hen aber Verarbeitungszeit. Niedrigere Werte reduzieren CPU-Last, kÃ¶nnen aber profitable Handels verpassen. Standard: 20.</t>
    <t id="9336">Maximale Anzahl von Handels pro Ware wÃ¤hrend Batch-Verarbeitung (5-100). HÃ¶here Werte erlauben mehr Handels pro Ware, erhÃ¶hen aber Verarbeitungszeit. Niedrigere Werte reduzieren CPU-Last, kÃ¶nnen aber profitable Handels verpassen. Standard: 20.</t>
    <t id="9337">Maximale Anzahl von Angeboten pro Ware fÃ¼r Matching im Batch-Prozessor (5-100). HÃ¶here Werte berÃ¼cksichtigen mehr Angebote, erhÃ¶hen aber Verarbeitungszeit. Niedrigere Werte reduzieren CPU-Last, kÃ¶nnen aber profitable Handels verpassen. Standard: 20.</t>
    <t id="9338">FrÃ¼he Ausstiegsschwelle fÃ¼r Batch-Verarbeitung (100-10000). Wenn so viele Handels gefunden werden, stoppt Batch-Verarbeitung frÃ¼h, um CPU zu sparen. HÃ¶here Werte verarbeiten mehr Handels, erhÃ¶hen aber CPU-Last. Niedrigere Werte beenden frÃ¼her, kÃ¶nnen aber profitable Handels verpassen. Standard: 2000.</t>
    <t id="9341">Live-Angebots-Slice-Intervall in Millisekunden (5-500ms). Steuert, wie oft Live-Angebots-Slices starten kÃ¶nnen. Niedrigere Werte ermÃ¶glichen schnellere Angebotssammlung, erhÃ¶hen aber die CPU-Last. HÃ¶here Werte reduzieren die CPU-Last, verlangsamen aber die Live-Such-Verarbeitung. Standard: 500ms.</t>
    <t id="9363">Batch-Verarbeitungs-Chunk-GrÃ¶ÃŸe (5-20). Verarbeitet chunkSizeÃ—chunkSize Kombinationen pro Chunk (z.B. 10Ã—10 = 100 Kombinationen). GrÃ¶ÃŸere Chunks verbessern den Durchsatz, erhÃ¶hen aber die CPU-Last pro Chunk. Kleinere Chunks reduzieren CPU-Spitzen, erfordern aber mehr Fortsetzungen. Standard: 10.</t>
    <t id="9348">Maximale Anzahl von Cache-Suchen, die gleichzeitig laufen kÃ¶nnen (1-20). Cache-Suchen sind schnell und gÃ¼nstig, daher erlauben hÃ¶here Werte mehr parallele Cache-PrÃ¼fungen ohne signifikante CPU-Auswirkung. Niedrigere Werte reduzieren parallele Cache-Suchen. Standard: 5.</t>
    <t id="9349">Maximale Anzahl von Live-Suchen, die gleichzeitig laufen kÃ¶nnen (1-10). Live-Suchen sind CPU-intensiv, daher reduzieren niedrigere Werte CPU-Last, erhÃ¶hen aber Warteschlangen-Wartezeiten. HÃ¶here Werte verarbeiten Suchen schneller, kÃ¶nnen aber Leistungsspitzen verursachen. Standard: 1.</t>
    <t id="9264">Cache-Abfrage-Chunk-GrÃ¶ÃŸe:</t>
    <t id="9265">Live-Angebots-AnhÃ¤nge-Chunk-GrÃ¶ÃŸe:</t>
    <t id="9364">Cache-EintrÃ¤ge pro Chunk validiert (10-200). Kleinere Werte verteilen die Cache-Validierung Ã¼ber mehr Frames (glatter), kÃ¶nnen aber die Zeit erhÃ¶hen, um einen gecachten Handel zu finden. Standard: 10.</t>
    <t id="9365">Angebote pro AnhÃ¤nge-Slice angehÃ¤ngt (50-2000). Kleinere Werte reduzieren die Listen-AnhÃ¤nge-Arbeit pro Frame (glatter), kÃ¶nnen aber die Live-Such-Vollendung verlangsamen. Standard: 200.</t>
    <t id="9366">Suchsperren-Zeit-zu-Leben in Sekunden (60-7200). Wenn einem Schiff lÃ¤nger als dies mit "Handelssuche bereits im Gange" verweigert wird, wird GT sich selbst heilen, indem es den veralteten Suchzustand lÃ¶scht und die Sperre freigibt. Standard: 600s.</t>
    <t id="9370">Weicher Schwellenwert fÃ¼r Batch-Gegendruck:</t>
    <t id="9371">Harter Schwellenwert fÃ¼r Batch-Gegendruck:</t>
    <t id="9372">Sektoren pro Slice:</t>
    <t id="9373">Abklingzeit der Home-Aktualisierung:</t>
    <t id="9374">Cache-Miss-Abklingzeitbasis:</t>
    <t id="9375">Scheduler-Tick-Intervall:</t>
    <t id="9376">Maximale Cache-Abfragen pro Tick:</t>
    <t id="9377">Max. Suchfortsetzungen pro Tick:</t>
    <t id="9378">Maximale Anzahl an Schiffen pro Tick:</t>
    <t id="9379">Max. Elemente pro Tick:</t>
    <t id="9380">Max. Wake-per-Tick:</t>
    <t id="9381">Max Cache-Abfrage-EintrÃ¤ge:</t>
    <t id="9382">Abgelaufene Schwellenwerte in Sekunden:</t>
    <t id="9383">Warteschlangen-Veraltungsschwellenwert in Sekunden:</t>
    <t id="9384">Sekunden des fehlgeschlagenen Handelsablaufs:</t>
    <t id="9385">Max. gleichzeitige Fallback-Suchen:</t>
    <t id="9386">Max. gleichzeitige Fallback-Suchen:</t>
    <t id="9470">Weicher Schwellenwert fÃ¼r die Warteschlange des Batch-Prozessors (5-50). Wenn die Warteschlange diesen Wert erreicht, beginnt Gegendruck angewendet zu werden, um neue Suchanfragen zu verlangsamen. Niedrigere Werte lÃ¶sen Gegendruck frÃ¼her aus (konservativer). Standard: 10.</t>
    <t id="9471">Harter Schwellenwert fÃ¼r die Warteschlange des Batch-Prozessors (10-100). Wenn die Warteschlange diesen Wert erreicht, werden neue Live-Suchen blockiert, bis die Warteschlange abnimmt. Niedrigere Werte blockieren Suchen frÃ¼her (konservativer). Standard: 25.</t>
    <t id="9472">Sektoren verarbeitet pro Segment bei der Live-Angebotssammlung (1-5). Niedrigere Werte verteilen die Arbeit auf mehr Frames (flÃ¼ssiger), kÃ¶nnen aber die Angebotssammlung verlangsamen. HÃ¶here Werte verarbeiten schneller, kÃ¶nnen aber Frame-Spitzen verursachen. Standard: 1.</t>
    <t id="9473">Abklingzeit nach Abschluss der Heimatsektor-Aktualisierung (10-120 Sekunden). Verhindert Ã¼bermÃ¤ÃŸige Aktualisierungsanfragen. Niedrigere Werte ermÃ¶glichen hÃ¤ufigere Aktualisierungen, erhÃ¶hen aber die CPU-Last. HÃ¶here Werte reduzieren die Aktualisierungsfrequenz, kÃ¶nnen aber Cache-Updates verzÃ¶gern. Standard: 30s.</t>
    <t id="9474">Basis-Abklingzeit nach einem Cache-Fehler vor erneutem Live-Suchversuch (1-30 Sekunden). Verhindert Ã¼bermÃ¤ÃŸige Wiederholungsversuche. Niedrigere Werte versuchen frÃ¼her erneut, erhÃ¶hen aber die CPU-Last. HÃ¶here Werte reduzieren die Wiederholungsfrequenz, kÃ¶nnen aber die Tradesuche verzÃ¶gern. Standard: 10s.</t>
    <t id="9475">Intervall zwischen Scheduler-Ticks in Millisekunden (50-500ms). Steuert, wie oft der Scheduler die Arbeitswarteschlange verarbeitet. Niedrigere Werte verarbeiten hÃ¤ufiger, erhÃ¶hen aber die CPU-Last. HÃ¶here Werte reduzieren die CPU-Last, kÃ¶nnen aber Wartezeiten in der Warteschlange erhÃ¶hen. Standard: 100ms.</t>
    <t id="9476">Maximale Anzahl von Cache-Abfragen, die pro Scheduler-Tick gestartet werden (1-5). Begrenzt die Cache-Abfrage-Rate, um Frame-Blockierung zu vermeiden. Niedrigere Werte reduzieren CPU-Spitzen, verlangsamen aber Cache-Suchen. HÃ¶here Werte verarbeiten schneller, kÃ¶nnen aber Ruckeln verursachen. Standard: 1.</t>
    <t id="9477">Maximale Anzahl von Suchfortsetzungen, die pro Scheduler-Tick gestartet werden (1-5). Begrenzt die Fortsetzungsrate, um Frame-Blockierung zu vermeiden. Niedrigere Werte reduzieren CPU-Spitzen, verlangsamen aber die Suchverarbeitung. HÃ¶here Werte verarbeiten schneller, kÃ¶nnen aber Ruckeln verursachen. Standard: 1.</t>
    <t id="9478">Maximale Anzahl von Schiffen, die pro Scheduler-Tick verarbeitet werden (1-5). Begrenzt die Schiffsverarbeitungsrate, um Frame-Blockierung zu vermeiden. Niedrigere Werte reduzieren CPU-Spitzen, verlangsamen aber die Warteschlangenverarbeitung. HÃ¶here Werte verarbeiten schneller, kÃ¶nnen aber Ruckeln verursachen. Standard: 1.</t>
    <t id="9479">Maximale Anzahl von Arbeitselementen, die pro Scheduler-Tick verarbeitet werden (1-5). Begrenzt die Elementverarbeitungsrate, um Frame-Blockierung zu vermeiden. Niedrigere Werte reduzieren CPU-Spitzen, verlangsamen aber die Warteschlangenverarbeitung. HÃ¶here Werte verarbeiten schneller, kÃ¶nnen aber Ruckeln verursachen. Standard: 1.</t>
    <t id="9480">Maximale Anzahl von Wartenden, die pro Scheduler-Tick geweckt werden (1-10). Begrenzt die Weckrate, um CPU-Spitzen zu vermeiden, wenn viele Wartende in der Warteschlange sind. Niedrigere Werte reduzieren CPU-Spitzen, verlangsamen aber die Wartendenverarbeitung. HÃ¶here Werte verarbeiten schneller, kÃ¶nnen aber Ruckeln verursachen. Standard: 2.</t>
    <t id="9481">Maximale Anzahl von Cache-EintrÃ¤gen, die pro Los abgefragt werden (1-200). Steuert die GrÃ¶ÃŸe des Cache-Abfrage-Loses. Niedrigere Werte machen Cache-Suchen schneller, kÃ¶nnen aber bessere Trades verpassen. HÃ¶here Werte berÃ¼cksichtigen mehr gecachte Trades, erhÃ¶hen aber die Validierungszeit. Standard: 50.</t>
    <t id="9482">Veraltungs-Schwellenwert fÃ¼r Live-Suchstatus in Sekunden (60-600). Wenn der Live-Suchstatus Ã¤lter als dieser Wert ist, wird er als veraltet betrachtet und gelÃ¶scht. Niedrigere Werte lÃ¶schen veralteten Status frÃ¼her, kÃ¶nnen aber legitime Suchen unterbrechen. HÃ¶here Werte ermÃ¶glichen lÃ¤ngere Suchen, kÃ¶nnen aber veralteten Status hinterlassen. Standard: 300s.</t>
    <t id="9483">Veraltungs-Schwellenwert fÃ¼r Warteschlangenelemente in Sekunden (30-300). Wenn Warteschlangenelemente Ã¤lter als dieser Wert sind, werden sie als veraltet betrachtet und entfernt. Niedrigere Werte lÃ¶schen veraltete Elemente frÃ¼her, kÃ¶nnen aber legitime Warteschlangenelemente entfernen. HÃ¶here Werte ermÃ¶glichen lÃ¤ngere Wartezeiten, kÃ¶nnen aber veraltete Elemente hinterlassen. Standard: 60s.</t>
    <t id="9484">Ablaufzeit des Caches fÃ¼r fehlgeschlagene Trades in Sekunden (300-3600). Fehlgeschlagene Trades werden gecacht, um sofortige Wiederholungsversuche zu vermeiden. Niedrigere Werte lassen fehlgeschlagene Trades frÃ¼her ablaufen (mehr Wiederholungen), reduzieren aber die Cache-EffektivitÃ¤t. HÃ¶here Werte cachen lÃ¤nger (weniger Wiederholungen), kÃ¶nnen aber Wiederholungsversuche verzÃ¶gern. Standard: 1800s (30 Minuten).</t>
    <t id="9485">Maximale Anzahl gleichzeitiger Fallback-Live-Suchen (1-10). Fallback-Suchen umgehen die Heimatsektor-Sperre, sodass mehrere Schiffe aus demselben Heimatsektor gleichzeitig suchen kÃ¶nnen. Niedrigere Werte reduzieren die CPU-Last, kÃ¶nnen aber Fallback-Suchen verlangsamen. HÃ¶here Werte ermÃ¶glichen mehr parallele Fallback-Suchen, erhÃ¶hen aber die CPU-Nutzung. Standard: 1.</t>
    <t id="9490">VerzÃ¶gerung des Trade-Found-Signals:</t>
    <t id="9590">VerzÃ¶gerung vor dem Senden des GT_Trade_Found-Signals an Schiffe in Millisekunden (10-1000ms). Schiffe warten immer (konfigurierte VerzÃ¶gerung + 5ms Puffer) bevor sie neue Anfragen senden, um verzÃ¶gerte Signale abzufangen. HÃ¶here Werte verteilen Signale Ã¼ber Frames fÃ¼r flÃ¼ssigere Leistung. Standard: 10ms.</t>
    <t id="8000">GalaxyTrader-Flotte</t>
    <t id="8001">GalaxyTrader-Flottenmanagement und Pilotenstatistiken</t>
    <t id="8002">Alle GalaxyTrader-Piloten anzeigen und verwalten</t>
    <t id="8100">Schiffs-ID</t>
    <t id="8101">Pilot</t>
    <t id="8102">Schiff</t>
    <t id="8103">Status</t>
    <t id="8104">Rang</t>
    <t id="8105">Ebene</t>
    <t id="8106">XP</t>
    <t id="8107">Lebenslanger Gewinn</t>
    <t id="8108">Standort</t>
    <t id="8109">Heimatbasis</t>
    <t id="8110">Letzter Handel</t>
    <t id="8111">Pilotgewinn</t>
    <t id="8112">Schiffsgewinn</t>
    <t id="8113">Handelsanzahl</t>
    <t id="8200">Aktualisieren</t>
    <t id="8201">CSV exportieren</t>
    <t id="8202">Statistiken</t>
    <t id="8203">Einstellungen</t>
    <t id="8204">Helfen</t>
    <t id="8205">SchlieÃŸen</t>
    <t id="8300">Alle Piloten</t>
    <t id="8301">Handel</t>
    <t id="8302">Ausbildung</t>
    <t id="8303">Wartung</t>
    <t id="8304">Notfall</t>
    <t id="8305">AnfÃ¤nger (Lv 1-5)</t>
    <t id="8306">Fortgeschritten (Stufe 6-11)</t>
    <t id="8307">Experten (Lv 12+)</t>
    <t id="8308">Top 10-Verdiener</t>
    <t id="8350">Sortieren nach:</t>
    <t id="8351">Schiffs-ID</t>
    <t id="8352">Pilotenname</t>
    <t id="8353">Schiffstyp</t>
    <t id="8354">Status</t>
    <t id="8355">Rang</t>
    <t id="8356">Ebene</t>
    <t id="8357">XP</t>
    <t id="8358">Gewinn</t>
    <t id="8400">Keine Piloten registriert</t>
    <t id="8401">Keine Piloten passen zum Filter</t>
    <t id="8402">Gesamtzahl der Piloten:</t>
    <t id="8403">Gesamtgewinn der Flotte:</t>
    <t id="8404">Letzte Aktualisierung:</t>
    <t id="8405">Piloten suchen...</t>
    <t id="8114">Sektor</t>
    <t id="8320">Schiffsumbenennung</t>
    <t id="8321">Benutzerdefinierter Name</t>
    <t id="8322">Namen festlegen</t>
    <t id="8323">Name lÃ¶schen</t>
    <t id="8324">Name erfolgreich festgelegt</t>
    <t id="8325">Name erfolgreich gelÃ¶scht</t>
    <t id="8450">Zur Schulung senden</t>
    <t id="8451">Abmelden</t>
    <t id="8452">Zwangsverkauf von Fracht</t>
    <t id="8453">Zur Reparatur senden</t>
    <t id="8454">An Resupply senden</t>
    <t id="8455">Alle AuftrÃ¤ge stoppen</t>
    <t id="8456">Aktionen</t>
    <t id="8500">Klicken Sie, um nach Schiffs-ID zu sortieren</t>
    <t id="8501">Klicken Sie, um nach Pilotennamen zu sortieren</t>
    <t id="8502">Klicken Sie, um nach Schiffstyp zu sortieren</t>
    <t id="8503">Klicken Sie, um nach Status zu sortieren</t>
    <t id="8504">Klicken Sie, um nach Rang zu sortieren</t>
    <t id="8505">Klicken Sie, um nach Ebene zu sortieren</t>
    <t id="8506">Klicken Sie, um nach XP zu sortieren</t>
    <t id="8507">Klicken Sie, um nach Lifetime Profit zu sortieren</t>
    <t id="8508">Aktualisieren Sie die Pilotendaten aus dem Missionssystem</t>
    <t id="8509">Aktuelle Ansicht in eine CSV-Datei exportieren</t>
    <t id="8510">Sehen Sie sich Flottenstatistiken und Diagramme an</t>
    <t id="8511">MenÃ¼einstellungen konfigurieren</t>
    <t id="8512">Hilfe und TastenkÃ¼rzel anzeigen</t>
    <t id="8600">Keine GalaxyTrader-Piloten gefunden</t>
    <t id="8601">Erstellen Sie Piloten, indem Sie GalaxyTrader Schiffe zuweisen, oder warten Sie, bis die Daten geladen sind.</t>
    <t id="9001">GT umbenennen</t>
    <t id="9902">Zur Schulung senden</t>
    <t id="9903">Manuelle Schulung fÃ¼r %1 in der Warteschlange. Der Pilot wird nach dem aktuellen Zyklus mit der Ausbildung beginnen.</t>
    <t id="9904">Das Training steht nach dem aktuellen Zyklus in der Warteschlange</t>
    <t id="9905">Pilot oder Schiff nicht gefunden</t>
    <t id="9906">AutoTraining ist aktiviert - eine manuelle Warteschlange ist nicht erforderlich</t>
    <t id="9907">Der Pilot ist nicht im Training blockiert</t>
    <t id="9910">Handelsakademie</t>
    <t id="9911">Lehrling (Lvl 4) - %1 / %2</t>
    <t id="9912">HÃ¤ndler (Lvl 7) - %1 / %2</t>
    <t id="9913">MeisterhÃ¤ndler (Lvl 13) - %1 / %2</t>
    <t id="9920">Pilot %1 wurde fÃ¼r den Akademiekurs Level %2 angemeldet. Schiff bricht zur nÃ¤chsten Handelsstation auf.</t>
    <t id="9921">Nicht genÃ¼gend Guthaben fÃ¼r diesen Kurs (benÃ¶tigt %1, vorhanden %2).</t>
    <t id="9922">Kurs nicht verfÃ¼gbar - Pilot %1 ist bereits auf oder Ã¼ber diesem Level.</t>
    <t id="9923">Pilot %1 hat sich an der Handelsakademie fÃ¼r Level %2 eingeschrieben (Kosten: %3 Cr, Dauer: %4 Min) an Bord der %5.</t>
    <t id="11011">Mittlerer GT-Schiffsreduzierer â€žApprenticeâ€œ.</t>
    <t id="11012">Antriebsmodifikation, die die Leistung fÃ¼r unerfahrene Piloten auf Mittelklasse-Schiffen leicht reduziert. Verwendet vom GalaxyTrader AI-System. -5% Geschwindigkeit, Schub und Rotation.</t>
    <t id="11013">GT Apprentice Mittelhubreduzierer</t>
    <t id="11014">Antriebsmodifikation, die die Reiseleistung fÃ¼r unerfahrene Piloten auf Mittelklasse-Schiffen leicht reduziert. Verwendet vom GalaxyTrader AI-System. -5% Reisegeschwindigkeit.</t>
    <t id="11021">GT Lehrling GroÃŸschiff Reduzierer</t>
    <t id="11022">Antriebsmodifikation, die die Leistung fÃ¼r unerfahrene Piloten auf GroÃŸschiffen reduziert. Verwendet vom GalaxyTrader AI-System. -15% Geschwindigkeit, Schub und Rotation.</t>
    <t id="11023">GT Lehrling GroÃŸschiff-Reise Reduzierer</t>
    <t id="11024">Antriebsmodifikation, die die Reiseleistung fÃ¼r unerfahrene Piloten auf GroÃŸschiffen reduziert. Verwendet vom GalaxyTrader AI-System. -15% Reisegeschwindigkeit.</t>
    <t id="11031">GT Lehrling fÃ¼r GroÃŸkampfschiff-Reduzierer</t>
    <t id="11032">Antriebsmodifikation, die die Leistung fÃ¼r unerfahrene Piloten auf Kapitalschiffen erheblich reduziert. Verwendet vom GalaxyTrader AI-System. -25% Geschwindigkeit, Schub und Rotation.</t>
    <t id="11033">GT Lehrling Kapitalreisereduzierer</t>
    <t id="11034">Antriebsmodifikation, die die Reiseleistung fÃ¼r unerfahrene Piloten auf Kapitalschiffen erheblich reduziert. Verwendet vom GalaxyTrader AI-System. -25% Reisegeschwindigkeit.</t>
    <t id="12001">GT Basis Kleinschiff VerstÃ¤rker</t>
    <t id="12002">Spezialisierte Antriebsmodifikation fÃ¼r Kleinschiffe mit grundlegend zertifizierten Piloten. Verwendet vom GalaxyTrader AI-System. +3% Geschwindigkeit, Schub und Rotation.</t>
    <t id="12003">GT Basis Kleinschiff-Reise VerstÃ¤rker</t>
    <t id="12004">Spezialisierte Antriebsmodifikation fÃ¼r Kleinschiffe mit grundlegend zertifizierten Piloten. Verwendet vom GalaxyTrader AI-System. +3% Reisegeschwindigkeit.</t>
    <t id="13001">GT Basis GroÃŸschiff Reduzierer</t>
    <t id="13002">Spezialisierte Antriebsmodifikation fÃ¼r GroÃŸschiffe mit grundlegend zertifizierten Piloten. Verwendet vom GalaxyTrader AI-System. -8% Geschwindigkeit, Schub und Rotation.</t>
    <t id="13003">GT Basis GroÃŸschiff-Reise Reduzierer</t>
    <t id="13004">Spezialisierte Antriebsmodifikation fÃ¼r GroÃŸschiffe mit grundlegend zertifizierten Piloten. Verwendet vom GalaxyTrader AI-System. -8% Reisegeschwindigkeit.</t>
    <t id="14001">GT Grundlegender GroÃŸkampfschiff-Reduzierer</t>
    <t id="14002">Spezialisierte Antriebsmodifikation fÃ¼r Kapitalschiffe mit grundlegend zertifizierten Piloten. Verwendet vom GalaxyTrader AI-System. -15% Geschwindigkeit, Schub und Rotation.</t>
    <t id="14003">GT Basic Capital Travel Reducer</t>
    <t id="14004">Spezialisierte Antriebsmodifikation fÃ¼r Kapitalschiffe mit grundlegend zertifizierten Piloten. Verwendet vom GalaxyTrader AI-System. -15% Reisegeschwindigkeit.</t>
    <t id="15001">GT Experte Kleinschiff VerstÃ¤rker</t>
    <t id="15002">Fortgeschrittene Antriebsmodifikation fÃ¼r Kleinschiffe mit Experten-Piloten. Verwendet vom GalaxyTrader AI-System. +25% Geschwindigkeit, Schub und Rotation.</t>
    <t id="15003">GT Experte Kleinschiff-Reise VerstÃ¤rker</t>
    <t id="15004">Fortgeschrittene Antriebsmodifikation fÃ¼r Kleinschiffe mit Experten-Piloten. Verwendet vom GalaxyTrader AI-System. +25% Reisegeschwindigkeit.</t>
    <t id="16001">GT Experte GroÃŸschiff VerstÃ¤rker</t>
    <t id="16002">Fortgeschrittene Antriebsmodifikation fÃ¼r GroÃŸschiffe mit Experten-Piloten. Verwendet vom GalaxyTrader AI-System. +15% Geschwindigkeit, Schub und Rotation.</t>
    <t id="16003">GT Experte GroÃŸschiff-Reise VerstÃ¤rker</t>
    <t id="16004">Fortgeschrittene Antriebsmodifikation fÃ¼r GroÃŸschiffe mit Experten-Piloten. Verwendet vom GalaxyTrader AI-System. +15% Reisegeschwindigkeit.</t>
    <t id="17001">GT Experte Kapitalschiff VerstÃ¤rker</t>
    <t id="17002">Fortgeschrittene Antriebsmodifikation fÃ¼r Kapitalschiffe mit Experten-Piloten. Verwendet vom GalaxyTrader AI-System. +6% Geschwindigkeit, Schub und Rotation.</t>
    <t id="17003">GT Experte Kapitalschiff-Reise VerstÃ¤rker</t>
    <t id="17004">Fortgeschrittene Antriebsmodifikation fÃ¼r Kapitalschiffe mit Experten-Piloten. Verwendet vom GalaxyTrader AI-System. +6% Reisegeschwindigkeit.</t>
    <t id="18001">Schwere FÃ¤higkeitsbegrenzung (Schiff)</t>
    <t id="18002">Schwere FÃ¤higkeitsbegrenzung (Schiff) - Stellt schwere LeistungseinbuÃŸen aufgrund der Unerfahrenheit des Piloten mit groÃŸen Schiffen dar. Wird automatisch vom GalaxyTrader-System angewendet, wenn die FÃ¤higkeiten des Piloten fÃ¼r die SchiffsgrÃ¶ÃŸe unzureichend sind. ErhÃ¶ht die Schiffsmasse. (Nur GT-System - Nicht fÃ¼r manuelle Installation verfÃ¼gbar)</t>
    <t id="18003">Moderate FÃ¤higkeitsbegrenzung (Schiff)</t>
    <t id="18004">Moderate FÃ¤higkeitsbegrenzung (Schiff) - Stellt moderate LeistungseinbuÃŸen dar, wÃ¤hrend sich der Pilot an die KomplexitÃ¤t des Schiffes anpasst. Wird automatisch vom GalaxyTrader-System angewendet, wenn die FÃ¤higkeiten des Piloten fÃ¼r die SchiffsgrÃ¶ÃŸe unzureichend sind. ErhÃ¶ht die Schiffsmasse. (Nur GT-System - Nicht fÃ¼r manuelle Installation verfÃ¼gbar)</t>
    <t id="18005">Leichte FÃ¤higkeitsbegrenzung (Schiff)</t>
    <t id="18006">Leichte FÃ¤higkeitsbegrenzung (Schiff) - Stellt geringfÃ¼gige LeistungseinbuÃŸen wÃ¤hrend der FÃ¤higkeitsentwicklung des Piloten dar. Wird automatisch vom GalaxyTrader-System angewendet, wenn die FÃ¤higkeiten des Piloten fÃ¼r die SchiffsgrÃ¶ÃŸe unzureichend sind. ErhÃ¶ht die Schiffsmasse. (Nur GT-System - Nicht fÃ¼r manuelle Installation verfÃ¼gbar)</t>
    <t id="18007">Schwere FÃ¤higkeitsbegrenzung (Triebwerk)</t>
    <t id="18008">Schwere FÃ¤higkeitsbegrenzung (Triebwerk) - Stellt schwere LeistungseinbuÃŸen aufgrund der Unerfahrenheit des Piloten mit groÃŸen Schiffen dar. Wird automatisch vom GalaxyTrader-System angewendet, wenn die FÃ¤higkeiten des Piloten fÃ¼r die SchiffsgrÃ¶ÃŸe unzureichend sind. Reduziert Schub und Rotation des Triebwerks. (Nur GT-System - Nicht fÃ¼r manuelle Installation verfÃ¼gbar)</t>
    <t id="18009">Moderate FÃ¤higkeitsbegrenzung (Triebwerk)</t>
    <t id="18010">Moderate FÃ¤higkeitsbegrenzung (Triebwerk) - Stellt moderate LeistungseinbuÃŸen dar, wÃ¤hrend sich der Pilot an die KomplexitÃ¤t des Schiffes anpasst. Wird automatisch vom GalaxyTrader-System angewendet, wenn die FÃ¤higkeiten des Piloten fÃ¼r die SchiffsgrÃ¶ÃŸe unzureichend sind. Reduziert Schub und Rotation des Triebwerks. (Nur GT-System - Nicht fÃ¼r manuelle Installation verfÃ¼gbar)</t>
    <t id="18011">Leichte FÃ¤higkeitsbegrenzung (Triebwerk)</t>
    <t id="18012">Leichte FÃ¤higkeitsbegrenzung (Triebwerk) - Stellt geringfÃ¼gige LeistungseinbuÃŸen wÃ¤hrend der FÃ¤higkeitsentwicklung des Piloten dar. Wird automatisch vom GalaxyTrader-System angewendet, wenn die FÃ¤higkeiten des Piloten fÃ¼r die SchiffsgrÃ¶ÃŸe unzureichend sind. Reduziert Schub und Rotation des Triebwerks. (Nur GT-System - Nicht fÃ¼r manuelle Installation verfÃ¼gbar)</t>
    <t id="9250">Benennung des Schiffsstaates</t>
    <t id="9350">Schiffsstatus-AbkÃ¼rzungen anpassen. Standardwerte werden in Eingabefeldern angezeigt und kÃ¶nnen Ã¼berschrieben werden. Maximal 3 Zeichen. Alle Schiffsnamen werden automatisch aktualisiert, wenn geÃ¤ndert.</t>
    <t id="9251">Nachschub-Status AbkÃ¼rzung:</t>
    <t id="9252">Reparatur-Status AbkÃ¼rzung:</t>
    <t id="9253">Wartungs-Status AbkÃ¼rzung:</t>
    <t id="9254">Ausbildung-Status AbkÃ¼rzung:</t>
    <t id="9255">Umleitung-Status AbkÃ¼rzung:</t>
    <t id="9256">Freigabe-Status AbkÃ¼rzung:</t>
    <t id="9257">Blockiert-Status AbkÃ¼rzung:</t>
    <t id="9258">Fallback-Status AbkÃ¼rzung:</t>
    <t id="9259">Isoliert-Status AbkÃ¼rzung:</t>
    <t id="9260">Handel-Status AbkÃ¼rzung:</t>
    <t id="9261">Leerlauf-Status AbkÃ¼rzung:</t>
    <t id="9262">Flucht-Status AbkÃ¼rzung:</t>
    <t id="9268">AbkÃ¼rzung fÃ¼r nicht erreichbaren Staat:</t>
    <t id="9269">AbkÃ¼rzung des Pilot Exchange State:</t>
    <t id="9270">Benutzerdefiniertes Blacklist-PrÃ¤fix-Tag:</t>
    <t id="9700">SPIELHILFEN (kaputt. hier gibt es nichts!! wirklich!!)</t>
    <t id="9701">GT-Schiffe unverwundbar</t>
    <t id="9702">Alle Spielerschiffe unverwundbar</t>
    <t id="9800">Weitergehen, Pilot. Das sind kaputte Entwickler-Testtools, kein Spielzeug-Menue. Hier gibt es nichts. Wirklich. Du wurdest gewarnt. Wahrscheinlich.</t>
    <t id="9801">Schiffe mit GalaxyTrader-Auftrag koennen nicht unter 100% Rumpf oder Schilde fallen. Erneut klicken zum Deaktivieren.</t>
    <t id="9802">Alle spielereigenen Schiffe koennen nicht unter 100% Rumpf oder Schilde fallen. Erneut klicken zum Deaktivieren. Stationen sind nicht betroffen.</t>
    <t id="9703">Universum fuer GT-Tests aufdecken</t>
    <t id="9704">Aufgedeckt</t>
    <t id="9705">Aufdecken</t>
    <t id="9803">Deckt Nebel des Krieges in allen Sektoren auf, markiert alle Stationen als bekannt, gewaehrt alle Handelsabonnement-Lizenzen und abonniert Handelsangebote galaxieweit. Nach neuen DLC-Sektoren erneut klicken. Nur zum Testen.</t>
    <t id="9706">GT-Pilot-EP fuer registrierte Piloten maximieren</t>
    <t id="9707">Maximiert</t>
    <t id="9708">EP max</t>
    <t id="9804">Setzt Stufe 15 und maximale EP fuer alle Piloten im GT-Register. Entfernt Trainings-Sperren. Wird bei Nur-Vanilla-EP uebersprungen. Nur zum Testen.</t>
    <t id="9351">AbkÃ¼rzung fÃ¼r Nachschub-Status (Standard: RS)</t>
    <t id="9352">AbkÃ¼rzung fÃ¼r Reparatur-Status (Standard: RP)</t>
    <t id="9353">AbkÃ¼rzung fÃ¼r Wartungs-Status (Standard: MT)</t>
    <t id="9354">AbkÃ¼rzung fÃ¼r Ausbildung-Status (Standard: TR)</t>
    <t id="9355">AbkÃ¼rzung fÃ¼r Umleitung-Status (Standard: RR)</t>
    <t id="9356">AbkÃ¼rzung fÃ¼r Freigabe-Status (Standard: CL)</t>
    <t id="9357">AbkÃ¼rzung fÃ¼r Blockiert-Status (Standard: BL)</t>
    <t id="9358">AbkÃ¼rzung fÃ¼r Fallback-Status (Standard: FB)</t>
    <t id="9359">AbkÃ¼rzung fÃ¼r Isoliert-Status (Standard: IS)</t>
    <t id="9360">AbkÃ¼rzung fÃ¼r Handel-Status (Standard: TD)</t>
    <t id="9361">AbkÃ¼rzung fÃ¼r Leerlauf-Status (Standard: ID)</t>
    <t id="9362">AbkÃ¼rzung fÃ¼r Flucht-Status (Standard: ES)</t>
    <t id="9367">AbkÃ¼rzung fÃ¼r Unreachable State (Standard: UR)</t>
    <t id="9368">AbkÃ¼rzung fÃ¼r Pilot Exchange State (Standard: PE)</t>
    <t id="9369">Wird als PrÃ¤fix fÃ¼r MK3-Schiffe angezeigt, die von einer benutzerdefinierten Fraktions-Blacklist betroffen sind (einschlieÃŸlich Untergebener). Standard: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">StationshÃ¤ndler â€“ verkauft Stationsprodukte an NPC-Fraktionen</t>
    <t id="30010">Heimatstation</t>
    <t id="30011">Maximale Verkaufsdistanz</t>
    <t id="30012">Ignorieren Sie Handelsregeln</t>
    <t id="30013">Warenfilter</t>
    <t id="30014">FrachtfÃ¼llungsziel % verkaufen</t>
    <t id="30015">Backtrack-Toleranz</t>
    <t id="30016">Kaufen Sie FrachtfÃ¼llungsziel %</t>
    <t id="30017">LogbucheintrÃ¤ge</t>
    <t id="30018">Benachrichtigungsebene</t>
    <t id="30019">Flottenkoordination</t>
    <t id="30020">Debug-Ebene</t>
    <t id="30021">Versorgungsstation</t>
    <t id="30022">Min. Stationsspeicher %</t>
    <t id="30023">Illegale Waren zulassen</t>
    <t id="30024">Fracht/Gewinn</t>
    <t id="30025">Mehrfachhandel zulassen</t>
    <t id="30110">Spielerstation zum Verkauf von Waren (Stationszuweisung erforderlich)</t>
    <t id="30111">Maximale Torentfernung zum Finden von NPC-KÃ¤ufern (begrenzt durch die FÃ¤higkeiten des Piloten)</t>
    <t id="30112">Ignorieren Sie HandelsbeschrÃ¤nkungen fÃ¼r Stationen â€“ verkaufen Sie sie an jede befreundete Fraktion, unabhÃ¤ngig von den Regeln fÃ¼r den Stationshandel</t>
    <t id="30113">Optionaler Warenfilter; Lassen Sie es leer, um alle Stationsprodukte und Handelswaren zu verkaufen</t>
    <t id="30114">Mindestprozentsatz der LadungsfÃ¼llung vor der Abreise zu Verkaufsreisen</t>
    <t id="30115">Maximal zulÃ¤ssige zusÃ¤tzliche SprÃ¼nge beim HinzufÃ¼gen einer zweiten Ware zu einer Reise (0 = nur KÃ¤ufer direkt auf der Route)</t>
    <t id="30116">ZielladungsfÃ¼llung fÃ¼r VersorgungslÃ¤ufe (weiches Ziel, HÃ¤ndler kann frÃ¼her abreisen)</t>
    <t id="30117">Aktivieren Sie LogbucheintrÃ¤ge pro Trade</t>
    <t id="30118">Benachrichtigungsstufe: 0=Ruhe, 1=Normal, 2=AusfÃ¼hrlich</t>
    <t id="30119">Aktivieren Sie ein System zur Flottenkoordination und Handelsreservierung</t>
    <t id="30120">Debug-Protokollierungsebene: 0 = Aus, 1 = Normal, 2 = AusfÃ¼hrlich</t>
    <t id="30121">Wenn aktiviert, kaufen Sie auch Ressourcen fÃ¼r die Station. Die Versorgung hat Vorrang, wenn die Lagerung unter den Mindestschwellenwert fÃ¤llt</t>
    <t id="30122">Wenn eine Ressource unter diesen Prozentsatz ihres Ziels fÃ¤llt, hat das Angebot Vorrang vor dem Verkauf. Wird ignoriert, wenn die Station sich keine Ressourcen leisten kann</t>
    <t id="30123">Erlauben Sie den Verkauf oder Kauf illegaler/geschmuggelter Waren, sofern verfÃ¼gbar</t>
    <t id="30124">Verkaufsauswahl: 1 = Fracht (hÃ¶chste WarenfÃ¼llung bevorzugen; bei Gleichstand Gewinn), 2 = Gewinn (bester Gewinn-Score)</t>
    <t id="30125">Erlaubt, mehrere VerkÃ¤ufe in einem Zyklus zu verketten (bis zu 3 Waren oder Ziele). Deaktivieren fÃ¼r Zyklen mit nur einem Handel</t>
    <t id="30200">Verkauf von %1 %2 von %3 an %4</t>
    <t id="30201">Innerhalb von %1 SprÃ¼ngen wurden keine KÃ¤ufer fÃ¼r Stationsprodukte gefunden</t>
    <t id="30202">Heimatstation %1 zerstÃ¶rt â€“ Auftrag des StationshÃ¤ndlers storniert</t>
    <t id="30203">Die Heimatstation %1 ist nicht mehr im Besitz des Spielers â€“ Bestellung storniert</t>
    <t id="30204">Stationszuweisung erforderlich â€“ Auftrag storniert</t>
    <t id="30205">MK1 Station Trader startete um %1</t>
    <t id="30206">Abgeschlossener Verkauf: %1 %2 verkauft an %3 fÃ¼r %4 Cr (Gewinn: %5 Cr)</t>
    <t id="30207">Multi-Ware-Reise: Lieferung von %1 Waren an %2 Ziele</t>
    <t id="30208">Lieferung von %1 %2 bis %3 von %4</t>
    <t id="30500">GalaxyTrader MK1-Einstellungen</t>
    <t id="30501">Standardeinstellungen fÃ¼r StationshÃ¤ndler</t>
    <t id="30502">StandardmÃ¤ÃŸiger maximaler Verkaufsabstand</t>
    <t id="30503">StandardmÃ¤ÃŸiges Verkaufsfracht-FÃ¼llungsziel</t>
    <t id="30504">StandardmÃ¤ÃŸig Handelsregeln ignorieren</t>
    <t id="30505">Standard-Backtrack-Toleranz</t>
    <t id="30506">Wartezeit, wenn keine Trades gefunden werden</t>
    <t id="30507">StandardmÃ¤ÃŸiges Kauffracht-FÃ¼llungsziel</t>
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">Autonomer Bergbau mit Stationsversorgung und XP-Fortschritt</t>
    <t id="31010">Heimatstation</t>
    <t id="31110">Station zum Abbau und zur Lieferung an diese Station (schlieÃŸt sich gegenseitig mit dem Heimatsektor aus)</t>
    <t id="31011">Heimsektor</t>
    <t id="31111">Branche, in der Sie tÃ¤tig sein mÃ¶chten; Wird verwendet, wenn keine Home Station eingestellt ist</t>
    <t id="31012">Ressourcenkorb</t>
    <t id="31112">Zu fÃ¶rdernde Waren; leer folgt der AuflÃ¶sung der Stationsnachfrage</t>
    <t id="31013">Zielstationen</t>
    <t id="31113">Optionaler Stationsfilter fÃ¼r Lieferungen; empty stammt aus dem Home-Kontext</t>
    <t id="31014">Ãœberlaufschwelle %</t>
    <t id="31114">Stationen mit oder Ã¼ber diesem Speicherprozentsatz werden als voll behandelt</t>
    <t id="31015">Ãœberlaufverkauf an andere zulassen</t>
    <t id="31115">Wenn aktiviert und die PrimÃ¤rziele voll sind, verkaufen Sie es an andere Fraktionsstationen</t>
    <t id="31016">Der Station zuweisen</t>
    <t id="31116">Weisen Sie das Schiff ggf. als Mining-Untergebener der Heimatstation zu</t>
    <t id="31017">Bleib zu Hause</t>
    <t id="31117">BeschrÃ¤nken Sie den Abbau/Verkauf auf den Heimatbereich, mit Ausnahme von Ãœberlauf-Fallback-LÃ¤ufen</t>
    <t id="31018">Ressourcenproben automatisch bereitstellen</t>
    <t id="31118">Stellen Sie geladene Ressourcen-Probes automatisch bereit und beziehen Sie Probes in die WartungsauffÃ¼llung ein</t>
    <t id="31019">Maximale Sammeldistanz</t>
    <t id="31119">Maximale Torentfernung zum Sammeln (0 nutzt die FÃ¤higkeitsgrenze von Pilot/Kommandant)</t>
    <t id="31020">Maximale Verkaufsdistanz</t>
    <t id="31120">Maximale Torentfernung fÃ¼r den Verkauf (0 nutzt die FÃ¤higkeitsgrenze von Piloten/Kommandanten)</t>
    <t id="31021">Flottenausgleich</t>
    <t id="31121">Aktivieren Sie die deterministische Absichtskoordination, um den StationsÃ¼berlauf zu reduzieren</t>
    <t id="31022">Intervall fÃ¼r erneute ÃœberprÃ¼fung des Bedarfs</t>
    <t id="31122">Wie oft wird die Miner-Nachfrage-/Wechselbewertung ausgefÃ¼hrt?</t>
    <t id="31023">Kritisches Nachfragedelta</t>
    <t id="31123">Minimales Dringlichkeitsdelta, das fÃ¼r den Wechsel aktiver Mining-Ware erforderlich ist</t>
    <t id="31024">Min. Abklingzeit des Wechsels</t>
    <t id="31124">Mindestzeit zwischen zwei Warenwechseln fÃ¼r dieses Schiff</t>
    <t id="31025">Min. Fracht-Commit %</t>
    <t id="31125">Wenn die LadungsfÃ¼llung darÃ¼ber liegt, mÃ¶chte das Schiff die aktuelle Lieferung lieber vor dem Wechsel beenden</t>
    <t id="31026">Hartes Notfalldelta</t>
    <t id="31126">Dringlichkeitsdelta, das trotz des Fracht-Commit-Schwellenwerts einen sofortigen Wechsel ermÃ¶glicht</t>
    <t id="31027">Benachrichtigungsebene</t>
    <t id="31127">Benachrichtigungsstufe: 0=Ruhe, 1=Normal, 2=AusfÃ¼hrlich</t>
    <t id="31028">Nur Spielerstationen</t>
    <t id="31128">Wenn diese Option aktiviert ist, werden nur spielereigene Stationen als Nachfrageziele berÃ¼cksichtigt.</t>
    <t id="31031">Nachfrage zuerst prÃ¼fen</t>
    <t id="31131">Wenn aktiviert, prÃ¼ft der Miner die Stationsnachfrage vor dem Abbau und priorisiert Waren entsprechend. Wenn deaktiviert, baut er aus dem Ressourcenkorb ohne NachfrageprÃ¼fung ab und lagert bis zum Verkauf (empfohlen fÃ¼r Einzel-Ressourcen-Flotten).</t>
    <t id="31032">Physischer Lagerabbruch %</t>
    <t id="31132">FÃ¼r Piloten Stufe 6+: stoppt den Abbau der aktuellen Ware, wenn physischer Stationsbestand plus Fracht aller relevanten Miner den aktuellen physischen Bestand um diesen Prozentsatz Ã¼berschreiten wÃ¼rde. Nutzt echte Frachtmengen, nicht den Ãœberlauf-Schwellenwert. 0 = deaktiviert.</t>
    <t id="32002">GalaxyTrader MK4-Versorgung</t>
    <t id="32102">Spielerstation-VersorgungshÃ¤ndler nutzt GT-Cache/Live-Suchpipeline</t>
    <t id="32010">Abdeckungsentfernung</t>
    <t id="32110">Maximale Gate-Entfernung von zu Hause fÃ¼r die Suche nach Zielnachfrage</t>
    <t id="32011">Distanz kaufen</t>
    <t id="32111">Maximale Gate-Entfernung von zu Hause fÃ¼r die Lieferantensuche</t>
    <t id="32012">Nur zu Hause servieren</t>
    <t id="32112">Wenn diese Option aktiviert ist, wird nur der Bedarf der Heimstation bedient</t>
    <t id="32013">Nur Baustationen</t>
    <t id="32113">Wenn diese Option aktiviert ist, wird nur der Build-Speicherbedarf gedeckt</t>
    <t id="32014">Kaufen Sie beim Player</t>
    <t id="32114">Erlauben Sie die Beschaffung von Waren von spielereigenen Lieferanten</t>
    <t id="32015">Kaufen Sie bei Fraktion</t>
    <t id="32115">Erlauben Sie die Beschaffung von Waren von Nicht-Spieler-Fraktionslieferanten</t>
    <t id="32016">Ressourcen zulassen</t>
    <t id="32116">Beziehen Sie Ressourcenwaren in die Nachfrageabgleichung ein</t>
    <t id="32017">Fortgeschrittene zulassen</t>
    <t id="32117">Beziehen Sie Zwischenwaren in die Bedarfsabstimmung ein</t>
    <t id="32018">Produkte zulassen</t>
    <t id="32118">Beziehen Sie Produktwaren in den Nachfrageabgleich ein</t>
    <t id="32019">Tradewares zulassen</t>
    <t id="32119">Beziehen Sie Handelswaren in die Nachfrageabgleichung ein</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">Lagerverteilung mit Lagerschwellenverwaltung</t>
    <t id="20010">Quellstationen</t>
    <t id="20011">Zielstationen</t>
    <t id="20012">Min. Speicher %</t>
    <t id="20013">Statischer Speicher %</t>
    <t id="20014">Maximaler Speicher %</t>
    <t id="20015">Warenfilter</t>
    <t id="20016">Bidirektionaler Modus</t>
    <t id="20017">Heimatstation (optional)</t>
    <t id="20018">Maximale Entfernung</t>
    <t id="20032">Heimatsektor (optional)</t>
    <t id="20019">Zykluswartezeit</t>
    <t id="20030">Kleine Liefermengen zulassen</t>
    <t id="20031">MindestfÃ¼llstand fÃ¼r niedriges Volumen %</t>
    <t id="20110">Liste der Quellstationen, von denen aus Waren verteilt werden</t>
    <t id="20111">Liste der Zielstationen/Lager, an die Waren verteilt werden sollen</t>
    <t id="20112">Zieldringlichkeitsschwellenwert: Stationen unterhalb dieses Speicherprozentsatzes erhalten vorrangige Lieferungen</t>
    <t id="20113">Mindestschwelle Quelle: Quelle muss Ã¼ber diesem % liegen, um zu verteilen</t>
    <t id="20114">Ãœberlauf-Schwelle Quelle: oberhalb dieses % wird auch an nicht dringende Ziele verteilt</t>
    <t id="20115">Optionaler Warenfilter; Lassen Sie dieses Feld leer, um alle Waren von der Quelle zu verteilen</t>
    <t id="20116">RÃ¼cktransport von Zielen zur Quelle aktivieren, wenn Ziele Ãœberschuss haben</t>
    <t id="20117">Optionale Wohnungsstation zur Belegung. Wenn es leer ist, bleibt das Schiff keiner Station zugeordnet.</t>
    <t id="20118">Maximaler Gate-Abstand zwischen Quelle und Zielen (0 = unbegrenzt)</t>
    <t id="20132">Optionaler Heimatsektor fÃ¼r Leerlauf-Parken, wenn keine Heimatstation festgelegt ist.</t>
    <t id="20119">Wartezeit zwischen den Verteilungszyklen</t>
    <t id="20130">Erlaubt kleinere, dringlichkeitsabhÃ¤ngige Liefermengen unterhalb der normalen Mindestfrachtauslastung.</t>
    <t id="20131">MindestladungsfÃ¼llung in % wird verwendet, wenn der Low-Volume-Modus aktiviert ist.</t>
    <t id="20200">Verteilen von %1 %2 von %3 bis %4</t>
    <t id="20201">RÃ¼cktransport: hole %1 %2 von %3 nach %4</t>
    <t id="20202">Keine Verteilung nÃ¶tig - alle Ziele sind ausreichend versorgt</t>
    <t id="20203">Alle Quellstationen ungÃ¼ltig - Verteilung wartet</t>
    <t id="20204">Alle Zielstationen ungÃ¼ltig - Verteilung wartet</t>
    <t id="20205">Quellstation %1 zerstÃ¶rt - aus Verteilungsbefehl entfernt</t>
    <t id="20206">Zielstation %1 zerstÃ¶rt - aus Verteilungsbefehl entfernt</t>
    <t id="20500">GalaxyTrader MK2 - Globale Einstellungen</t>
    <t id="20501">Standardeinstellungen fÃ¼r die MK2-Verteilung</t>
    <t id="20510">Standard-Min.-Speicher %</t>
    <t id="20511">StandardmÃ¤ÃŸiger statischer Speicher %</t>
    <t id="20512">StandardmÃ¤ÃŸiger maximaler Speicher %</t>
    <t id="20513">Standardzykluswartezeit(en)</t>
    <t id="20514">Minimale FrachtraumfÃ¼llung %</t>
    <t id="20520">AusfÃ¼hrlichkeit der Benachrichtigung</t>
    <t id="20521">Debug-Ebene</t>
    <t id="10006">Heimkehr</t>
    <t id="10007">GalaxyTrader MK4-2 Versorgung</t>
    <t id="10106">Docken Sie an der Heimatstation an und bleiben Sie dort, bis der Handel wieder aufgenommen wird</t>
    <t id="10107">Spieler-Versorgungsauftrag mit PrioritÃ¤tsreglern fÃ¼r Lieferziele</t>
    <t id="30026">RÃ¼ckkehr nach Hause zwischen den Zyklen</t>
    <t id="30028">Angebotseinstellungen ignorieren</t>
    <t id="30029">KÃ¤ufer-Preisspanne</t>
    <t id="30027">Min. Produktlager %</t>
    <t id="30126">Wenn aktiviert, kehren Sie zwischen den Handelszyklen zur Heimatstation zurÃ¼ck und andocken Sie an. Wenn deaktiviert, setzen Sie die Suche vom aktuellen Standort aus fort (altes Verhalten).</t>
    <t id="30128">Interne Lagertransfers ohne Stations-Kauf-/Verkaufsangebote erlauben. Nutzt Warenaustausch fÃ¼r Puffer-Abholung und -Lieferung. Stations-Handelsregeln gelten weiter, wenn Handelsregeln ignorieren aus ist.</t>
    <t id="30129">Mindest-Relativpreis fÃ¼r NPC-KÃ¤ufer beim Verkauf von Stationsprodukten. Auftragsschieberegler 0-200 (100 = Durchschnitt, 0 = -100%, 200 = +100%), abbildbar auf -1,0 bis +1,0. HÃ¶her = nur teure KÃ¤ufer. Niedriger = mehr KÃ¤uferoptionen. Versorgungsfahrten nutzen den invertierten Wert fÃ¼r Lieferanten-Preisobergrenzen.</t>
    <t id="30127">MindestfÃ¼llstand des Stationslagers in % (bezogen auf das konfigurierte Max. pro Ware), bevor ein Produkt oder Handelsware verkauft wird. Waren unter diesem Schwellenwert werden Ã¼bersprungen. 0 = kein Minimum.</t>
    <t id="31029">Aktienziel prÃ¼fen</t>
    <t id="31030">Zu kaufende Bergbaudrohnen</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: keine abbaubaren Waren verfÃ¼gbar. Schiff %1 [%2], Flotte: %3</t>
    <t id="31201">Galaxy-Miner: Heimatstation oder Heimatposition festlegen.</t>
    <t id="31130">Wie viele Sammel-(Bergbau-)Drohnen der Miner kauft, wenn ihm der benÃ¶tigte Typ ausgegangen ist (Feststoff/Erz oder FlÃ¼ssigkeit/Gas). Der Kauf wird NUR ausgelÃ¶st, wenn das Schiff keine Sammler dieses Typs mehr hat - ein Miner, der noch mindestens einen besitzt, wird nie aufgefÃ¼llt oder neu gekauft, vorhandene Drohnen bleiben erhalten. Begrenzt durch die EinheitenkapazitÃ¤t des Schiffs. Auf 0 setzen, um den automatischen Kauf von Sammeldrohnen zu deaktivieren und Drohnen manuell zu verwalten. Standard 5 entspricht einem vollen Drohnensatz fÃ¼r normale Abbaugeschwindigkeit.</t>
    <t id="31129">Anzahl der Ressourcensonden, die der Miner pro AuffÃ¼llungsfahrt kauft. Der Kauf wird NUR ausgelÃ¶st, wenn das Schiff keine Sonden mehr hat (Anzahl = 0), nicht bei jedem Einsatz - auf diese Weise verbraucht der Miner zwischen den VersorgungslÃ¤ufen seine volle Sondenlast, anstatt nach jedem Einsatz einen Umweg zu machen. Begrenzt durch die gesamte einsetzbare KapazitÃ¤t des Schiffs (gemeinsam mit Satelliten/Minen usw.); Ein Schiebereglerwert, der grÃ¶ÃŸer als der frei einsetzbare Speicherplatz ist, wird elegant herabgestuft, um â€žzu fÃ¼llen, was passtâ€œ. Wird nur wirksam, wenn â€žRessourcenproben automatisch bereitstellenâ€œ aktiviert ist - die gleiche Einstellung steuert auch die opportunistische Sondenbereitstellung in Mining-Sektoren und die Sammlung veralteter Sonden (Proben in Sektoren ohne korbrelevante Ressourcen).</t>
    <t id="3226">Commander %1,\n\nIch habe an %2 angedockt und der Registrar der Trading Academy hat meine Anmeldung zum Programm â€ž%3â€œ bestÃ¤tigt. Vom Flottenkonto wurden %4 Cr fÃ¼r die KursgebÃ¼hren abgebucht, und ich nehme diese Investition nicht auf die leichte Schulter.\n\nDies ist keine routinemÃ¤ÃŸige Zertifizierung. Die Ausbilder der Akademie sind erfahrene Kaufleute und Konsortialverhandler, und der Lehrplan hier ist weitaus anspruchsvoller als die Standard-AufstiegsprÃ¼fung. In den nÃ¤chsten %5 Minuten werde ich intensiven Unterricht in fortgeschrittenen Handelsprotokollen, Marktanalysen unter Druck und den Verhandlungstaktiken erhalten, die Lehrlinge von Meistern unterscheiden.\n\nWenn die AbschlussprÃ¼fung abgeschlossen ist und ich abdocke, werde ich den Titel â€ž%3â€œ tragen und alles, was ich gelernt habe, in unsere HandelsaktivitÃ¤ten zurÃ¼ckbringen. Ich werde keinen einzigen Kredit dieser Gelegenheit verschwenden.\n\nMit Dankbarkeit und Entschlossenheit,\n%6\nAn Bord von %7</t>
    <t id="9924">Kurs der Handelsakademie abgebrochen: Pilot %1 kann sich die GebÃ¼hr von %2 Cr am Akademiedock nicht leisten (habe %3 Cr). Kurs abgesagt, Pilot nimmt den Handel wieder auf.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="55">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Ancorar e aguardar (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">Exame Final (GalaxyTrader MK3)</t>
    <t id="10004">Encontro de IntercÃ¢mbio Piloto</t>
    <t id="10005">[OBSOLETO] GalaxyTrader Fornecimento MK4 (Legado)</t>
    <t id="10101">Atraque na estaÃ§Ã£o e aguarde a duraÃ§Ã£o especificada</t>
    <t id="10102">NegociaÃ§Ã£o autÃ´noma com progressÃ£o de habilidades</t>
    <t id="10103">FaÃ§a o exame final para certificaÃ§Ã£o de piloto no centro de treinamento</t>
    <t id="10104">Atracar na estaÃ§Ã£o de encontro para troca de pilotos</t>
    <t id="10105">NegociaÃ§Ã£o focada no fornecimento para estaÃ§Ãµes de jogadores usando cache e pesquisa ao vivo (Legado)</t>
    <t id="10201">Compre %s de %s</t>
    <t id="10202">Vender %s para %s</t>
    <t id="10203">Negocie com %s</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">Sistema de negociaÃ§Ã£o avanÃ§ado com progressÃ£o XP e coordenaÃ§Ã£o de frota</t>
    <t id="1002">Base inicial</t>
    <t id="1003">Usar predefiniÃ§Ãµes</t>
    <t id="1004">Negocie todos os produtos</t>
    <t id="1005">ComÃ©rcio de produtos legais</t>
    <t id="1006">ComÃ©rcio de produtos ilegais</t>
    <t id="1007">Ativar progressÃ£o XP</t>
    <t id="1008">Habilite a coordenaÃ§Ã£o da frota</t>
    <t id="1009">Habilite a anÃ¡lise de mercado</t>
    <t id="1010">Habilitar gerenciamento de territÃ³rio</t>
    <t id="1011">Permitir produtos ilegais</t>
    <t id="1012">Entradas no diÃ¡rio de bordo</t>
    <t id="1013">TolerÃ¢ncia ao Risco</t>
    <t id="1014">Priorize as estaÃ§Ãµes dos jogadores</t>
    <t id="1015">Mercadorias automÃ¡ticas</t>
    <t id="1016">% de penalidade de distÃ¢ncia</t>
    <t id="1017">NÃ­vel de notificaÃ§Ã£o</t>
    <t id="1018">CoordenaÃ§Ã£o de Frota</t>
    <t id="1019">% alvo de preenchimento de carga</t>
    <t id="1050">FrequÃªncia de atualizaÃ§Ã£o do mercado</t>
    <t id="1051">Registro de avaliaÃ§Ã£o comercial</t>
    <t id="1052">Lista de permissÃµes do setor</t>
    <t id="1054">Ignorar navios transportadores/auxiliares</t>
    <t id="1056">Ignorar armazenamento de compilaÃ§Ã£o</t>
    <t id="1058">Ignorar as regras comerciais</t>
    <t id="1060">Ignorar estaÃ§Ãµes fornecidas por MK1</t>
    <t id="1063">Em desenvolvimento</t>
    <t id="1064">Mercadorias prioritÃ¡rias</t>
    <t id="1065">PontuaÃ§Ã£o prioridade %</t>
    <t id="1066">Mercadorias a favor na pontuaÃ§Ã£o comercial. Sua pontuaÃ§Ã£o Ã© multiplicada pela% da pontuaÃ§Ã£o de prioridade.</t>
    <t id="1067">Multiplicador de pontuaÃ§Ã£o para produtos prioritÃ¡rios: 100%=normal, 150%=+50%%, 200%=2x, 300%=3x. Aplicado por Ãºltimo.</t>
    <t id="1068">â”€â”€ Filtro de mercadorias prioritÃ¡rias â”€â”€</t>
    <t id="1069">Mercadorias (manual)</t>
    <t id="1070">Filtro de rota ilegal</t>
    <t id="1072">Servir apenas em casa</t>
    <t id="1073">Prioridade do fornecedor jogador</t>
    <t id="1074">Prioridade do fornecedor facÃ§Ã£o</t>
    <t id="1075">Incluir armazenamento de compilaÃ§Ã£o</t>
    <t id="1076">Incluir recursos</t>
    <t id="1077">Incluir intermediÃ¡rios</t>
    <t id="1078">Incluir produtos comerciais</t>
    <t id="1080">MÃ¡ximo de negociaÃ§Ãµes por ciclo</t>
    <t id="1081">TolerÃ¢ncia de retrocesso</t>
    <t id="1082">% de carga mÃ­nima usada</t>
    <t id="1083">% de modificador de compra de jogador</t>
    <t id="1085">Atribuir Ã  estaÃ§Ã£o inicial</t>
    <t id="1086">DistÃ¢ncia de cobertura</t>
    <t id="1088">DistÃ¢ncia mÃ¡xima de salto de casa para cobertura de demanda</t>
    <t id="1090">Incluir produtos de classe tradeware na correspondÃªncia entre demanda e oferta</t>
    <t id="1091">Modificador aplicado aos preÃ§os dos fornecedores de propriedade do jogador em cÃ¡lculos somente de pontuaÃ§Ã£o</t>
    <t id="1092">Ignorar o preÃ§o do jogador</t>
    <t id="1093">Quando ativado: sempre compre em estaÃ§Ãµes de propriedade do jogador, independentemente dos preÃ§os de venda definidos, e venda apenas para facÃ§Ãµes de NPCs. Ãštil para liquidar o excesso de estoque de suas prÃ³prias estaÃ§Ãµes.</t>
    <t id="1094">EstaÃ§Ãµes bloqueadas</t>
    <t id="1095">As estaÃ§Ãµes selecionadas aqui sÃ£o excluÃ­das do comÃ©rcio MK3. O comerciante nÃ£o comprarÃ¡ nem venderÃ¡ nelas.</t>
    <t id="1096">Estacionamento em inatividade</t>
    <t id="1097">Quando ativado, naves que repetidamente nÃ£o encontram trabalho estacionam na estaÃ§Ã£o inicial ou no setor inicial. O estacionamento no setor prefere estaÃ§Ãµes do jogador, depois estaÃ§Ãµes amigas. O tempo de liberaÃ§Ã£o da doca Ã© definido nas configuraÃ§Ãµes globais (0 = permanece atracado atÃ© encontrar trabalho).</t>
    <t id="1098">Autoescala</t>
    <t id="1099">Quando ativado, os controlos de distÃ¢ncia de salto sÃ£o definidos para o alcance mÃ¡ximo permitido do piloto apÃ³s a formaÃ§Ã£o obrigatÃ³ria ou conclusÃ£o da Academia de ComÃ©rcio. Desative para definir as distÃ¢ncias manualmente.</t>
    <t id="11001">Prioridade armazenamento de construÃ§Ã£o</t>
    <t id="11002">Prioridade estaÃ§Ãµes</t>
    <t id="11003">Prioridade navios auxiliares</t>
    <t id="11004">Prioridade porta-aviÃµes</t>
    <t id="11005">0 = desativado. 1-10 = multiplicador de pontuaÃ§Ã£o (10 = maior peso). PontuaÃ§Ã£o final = pontuaÃ§Ã£o de fornecimento Ã— multiplicador.</t>
    <t id="11006">1 = sem pontuaÃ§Ã£o extra (lista de mercadorias prioritÃ¡rias inalterada). 2-10 = adiciona (multiplicadorâˆ’1)Ã— pontuaÃ§Ã£o base de fornecimento se a mercadoria estiver na lista prioritÃ¡ria. Aplicado sobre a pontuaÃ§Ã£o de tipo.</t>
    <t id="11007">BÃ³nus de mercadorias prioritÃ¡rias</t>
    <t id="11008">%1: Todos os controlos de prioridade do destino de entrega estÃ£o em 0 - esta ordem nÃ£o tem destinos de entrega. Ative pelo menos uma classe (armazÃ©m de construÃ§Ã£o, estaÃ§Ãµes, naves auxiliares ou porta-aviÃµes) para retomar os fornecimentos.</t>
    <t id="7001">[AVANÃ‡AR]</t>
    <t id="7002">[TREINAMENTO]</t>
    <t id="7008">[RESERVA]</t>
    <t id="7009">[ISOLADO]</t>
    <t id="7003">[REPARAR]</t>
    <t id="7004">[REABASTECIMENTO]</t>
    <t id="7005">[MANUTENÃ‡ÃƒO]</t>
    <t id="7006">[REARROTA]</t>
    <t id="7007">[LIBERAÃ‡ÃƒO]</t>
    <t id="1020">Escolha o setor de origem ou estaÃ§Ã£o onde o trader atua</t>
    <t id="1021">DistÃ¢ncia mÃ¡xima do portÃ£o de salto ao comprar mercadorias (limitada pela habilidade do piloto)</t>
    <t id="1022">DistÃ¢ncia mÃ¡xima do portÃ£o de salto ao vender mercadorias (limitada pela habilidade do piloto)</t>
    <t id="1023">SeleÃ§Ã£o automÃ¡tica de produtos adequados com base na categoria</t>
    <t id="1024">SeleÃ§Ã£o manual de produtos comerciais especÃ­ficos</t>
    <t id="1025">Permitir o comÃ©rcio de contrabando e produtos ilegais</t>
    <t id="1026">TolerÃ¢ncia de seguranÃ§a: 0,0=Apenas setores seguros, 1,0=Aceitar todos os riscos</t>
    <t id="1027">Melhore as habilidades do piloto atravÃ©s da experiÃªncia de negociaÃ§Ã£o</t>
    <t id="1028">Enviar pilotos automaticamente para treinamento quando necessÃ¡rio</t>
    <t id="1029">Coordene vÃ¡rios navios mercantes para evitar conflitos</t>
    <t id="1030">Foco no produto: 0 = Equilibrado, 1 = AvanÃ§ado, 2 = Necessidades bÃ¡sicas, 3 = Ilegal, 4 = Mercadorias a granel</t>
    <t id="1031">Ãrea de negociaÃ§Ã£o: 0=Balanceado, 1=Foco inicial, 2=Roam livre</t>
    <t id="1032">NÃ­vel de notificaÃ§Ã£o: 0=MÃ­nimo, 1=Normal, 2=Mensagens detalhadas</t>
    <t id="1033">Almeje a porcentagem de utilizaÃ§Ã£o da carga antes de priorizar as vendas</t>
    <t id="1034">Com que frequÃªncia os dados de mercado e as informaÃ§Ãµes de preÃ§os sÃ£o atualizados</t>
    <t id="1035">NÃ­vel de saÃ­da de depuraÃ§Ã£o: 0=Nenhum, 1=BÃ¡sico, 2=Registro detalhado</t>
    <t id="1036">Compartilhe rotas comerciais lucrativas com a frota (armazenadas em cache para acesso rÃ¡pido)</t>
    <t id="1037">Lucro mÃ­nimo necessÃ¡rio para armazenar em cache o comÃ©rcio e compartilhar com a frota</t>
    <t id="1038">Queda mÃ¡xima de lucro permitida antes que as rotas comerciais armazenadas em cache se tornem invÃ¡lidas</t>
    <t id="1039">Quanto tempo as rotas comerciais armazenadas em cache permanecem vÃ¡lidas antes de expirarem</t>
    <t id="1040">Habilite o registro detalhado de avaliaÃ§Ãµes e rejeiÃ§Ãµes comerciais individuais (pode ser muito detalhado)</t>
    <t id="1041">Habilite entradas de registro por negociaÃ§Ã£o e mensagens de treinamento imersivas (estilo TaterTrader)</t>
    <t id="1053">Os setores nesta lista sÃ£o excluÃ­dos das listas negras (sempre permitido)</t>
    <t id="1055">Excluir transportadores e navios auxiliares do comÃ©rcio</t>
    <t id="1057">Excluir construÃ§Ã£o de navios de armazenamento do comÃ©rcio</t>
    <t id="1059">Ignorar regras de troca de estaÃ§Ã£o durante a busca de ofertas (avanÃ§ado; pode selecionar ofertas normalmente bloqueadas)</t>
    <t id="1061">Ignorar estaÃ§Ãµes de jogadores que tenham um comerciante MK1 com modo de abastecimento atribuÃ­do</t>
    <t id="1062">Aumente as pontuaÃ§Ãµes comerciais para rotas envolvendo suas prÃ³prias estaÃ§Ãµes (bÃ´nus de pontuaÃ§Ã£o de 10%)</t>
    <t id="1071">Quando Permitir Mercadorias Ilegais estiver ativado, sÃ³ negocie produtos ilegais se forem legais em todos os setores no caminho de salto (compra, venda e setores intermediÃ¡rios).</t>
    <t id="1087">DistÃ¢ncia mÃ¡xima de salto de casa para pesquisa de compra de fornecedor</t>
    <t id="1089">Quando desativado, o navio pode abastecer estaÃ§Ãµes na Ã¡rea de cobertura com prioridade de urgÃªncia, em vez de modo somente residencial</t>
    <t id="2000">%s ganhou %s XP!</t>
    <t id="2001">%s subiu de nÃ­vel! Novo nÃ­vel: %s</t>
    <t id="2002">%s precisa de treinamento! Por favor, envie para o estaleiro ou estaÃ§Ã£o comercial mais prÃ³ximo.</t>
    <t id="2003">%s comeÃ§ou a treinar em %s</t>
    <t id="2004">%s concluiu o treinamento e agora estÃ¡ certificado para o nÃ­vel %s!</t>
    <t id="2005">%s atingiu o Skill Level %s apÃ³s o treinamento! Progresso XP desbloqueado em %s.</t>
    <t id="2006">%s atingiu o Skill Level %s com o comÃ©rcio de %s!</t>
    <t id="2007">%s completou o treinamento Level %s! Progresso XP desbloqueado em %s.</t>
    <t id="3000">%s concluiu uma negociaÃ§Ã£o! Lucro: %s Cr</t>
    <t id="3001">%s estÃ¡ analisando as condiÃ§Ãµes do mercado...</t>
    <t id="3002">%s encontrou uma rota comercial lucrativa!</t>
    <t id="3003">Nenhuma rota comercial lucrativa disponÃ­vel para %s</t>
    <t id="3100">Vendendo %1 %2 de carga para %3 a %4. Eu deveria ganhar %5 de lucro.</t>
    <t id="3101">Enfileirando ordem de negociaÃ§Ã£o para %1 %2. Comprar a %3 de %4, vender a %5 para %6. Eu deveria ganhar %7 de lucro.</t>
    <t id="3102">Comerciante de EstaÃ§Ã£o: Fornecendo %1 %2 de %3 a %5%% para %4 a %6%%.</t>
    <t id="3103">Comerciante de EstaÃ§Ã£o: Vendendo %1 %2 para %3 a %4. O lucro esperado Ã© %5.</t>
    <t id="3104">NegociaÃ§Ã£o concluÃ­da com sucesso para %1 %2. Lucro total: %3 CrÃ©ditos.</t>
    <t id="3105">Rota comercial armazenada em cache: %1 %2 de %3 a %4 (Lucro: %5 Cr)</t>
    <t id="3106">\nLucro vitalÃ­cio total estimado antes desta negociaÃ§Ã£o: %1 Cr.</t>
    <t id="3120">TransferÃªncia piloto iniciada</t>
    <t id="3121">Protocolo de transferÃªncia reconhecido. %1 (%2) e %3 (%4) estÃ£o seguindo para %5 (%6) para atracar e trocar assentos de comando.</t>
    <t id="3200">OlÃ¡ Comandante %1,\n\nGanhei experiÃªncia suficiente para fazer meu exame de certificaÃ§Ã£o para o tÃ­tulo "%2". O exame levarÃ¡ aproximadamente %3 minutos Ã s %4.\n\nEste Ã© um marco importante no desenvolvimento de minha carreira. O exame testarÃ¡ meu conhecimento de protocolos comerciais avanÃ§ados, anÃ¡lise de mercado e procedimentos de coordenaÃ§Ã£o de frota.\n\nEstou confiante em minhas habilidades e animado para provar que sou digno desse avanÃ§o. Deseje-me sorte!\n\nAtenciosamente,\n%5\nA bordo do %6</t>
    <t id="3201">Comandante %1,\n\nExcelentes notÃ­cias! ConcluÃ­ com Ãªxito meu exame de certificaÃ§Ã£o e ganhei o tÃ­tulo "%2"!\n\nO exame abrangeu estratÃ©gias comerciais avanÃ§adas, protocolos de avaliaÃ§Ã£o de risco e procedimentos de coordenaÃ§Ã£o de frota. Tenho o prazer de informar que fui aprovado com distinÃ§Ã£o.\n\nAgora estou qualificado para lidar com operaÃ§Ãµes comerciais mais complexas e espero contribuir ainda mais para o sucesso da nossa frota. Obrigado por investir no meu desenvolvimento profissional.\n\nCom dedicaÃ§Ã£o renovada,\n%3\nCertificado %2\nA bordo do %4</t>
    <t id="3202">Comandante %1,\n\n Lamento informar que meu exame de certificaÃ§Ã£o foi interrompido devido a requisitos operacionais. Precisarei reagendar quando as circunstÃ¢ncias permitirem.\n\nContinuo comprometido em aprimorar minhas habilidades e notificarei vocÃª quando puder retomar o processo de exame.\n\nAtenciosamente,\n%2\nA bordo do %3</t>
    <t id="3203">Comandante %1,\n\nNo momento, estou a caminho de %2 para meu exame de certificaÃ§Ã£o. A jornada me dÃ¡ tempo para revisar meus estudos e me preparar mentalmente para esta importante etapa em minha carreira.\n\nChegada esperada: %3 minutos\nDuraÃ§Ã£o do exame: %4 minutos\n\nAgradeÃ§o sua confianÃ§a em minhas habilidades e a oportunidade de avanÃ§o.\n\nCom determinaÃ§Ã£o,\n%5\nA bordo %6</t>
    <t id="3204">Comandante,\n\nDetectei carga no meu porÃ£o durante a verificaÃ§Ã£o dos sistemas. Antes de iniciar as operaÃ§Ãµes comerciais normais, preciso vender esta mercadoria.\n\nEstou usando nossa pesquisa comercial para encontrar o melhor comprador e descarregar esta carga com seguranÃ§a. Assim que minha retenÃ§Ã£o for liberada, prosseguirei com a negociaÃ§Ã£o automatizada.\n\nStatus: Procurando o local de venda ideal\n\nCom diligÃªncia,\nA bordo de %1</t>
    <t id="3205">Comandante,\n\nA integridade do meu casco caiu para %1%% (limite: %2%%). Como piloto nÃ­vel %3, estou autorizado a solicitar serviÃ§os de reparo automÃ¡tico.\n\nEstou seguindo para %4 para reparos. O custo estimado Ã© de %5 Cr, que estÃ¡ dentro do nosso orÃ§amento.\n\nAssim que os reparos forem concluÃ­dos, retomarei as operaÃ§Ãµes comerciais com total integridade estrutural.\n\nRespeitosamente,\nA bordo de %6</t>
    <t id="3206">Comandante,\n\nAVISO FINANCEIRO URGENTE\n\nA integridade do meu casco Ã© crÃ­tica em %1%% (limite: %2%%), mas nossos fundos disponÃ­veis (%3 Cr) sÃ£o insuficientes para reparos completos (custo estimado: %4 Cr).\n\nEstou prosseguindo para %5 para REPAROS PARCIAIS usando nossos fundos disponÃ­veis. Esta nÃ£o Ã© uma soluÃ§Ã£o ideal, mas Ã© necessÃ¡ria para manter a capacidade operacional.\n\nPor favor, considere alocar fundos adicionais para futuras operaÃ§Ãµes de manutenÃ§Ã£o.\n\nPreocupado, mas determinado,\nA bordo do %6</t>
    <t id="3207">Comandante, a certificaÃ§Ã£o \n\nMeu nÃ­vel %1 autoriza o reabastecimento automÃ¡tico de equipamento defensivo. Depois de verificar meus sistemas, determinei que minhas contramedidas e implantÃ¡veis estÃ£o abaixo dos limites recomendados.\n\nEstou indo para %2 para reabastecer meu equipamento defensivo:\nâ€¢ Contramedidas: reabastecer atÃ© a capacidade ideal\nâ€¢ Drones de defesa, drones comerciais, torres de laser: aplicar perfil de equilÃ­brio\n\nEste reabastecimento garante que eu esteja mais protegido contra ameaÃ§as espaciais, mantendo a eficiÃªncia comercial.\n\nCom vigilÃ¢ncia,\nA bordo de %3</t>
    <t id="3212">Comandante,\n\nA integridade do meu casco caiu para %1%% (limite: %2%%) e preciso de serviÃ§os de reparo. No entanto, a estaÃ§Ã£o de reparaÃ§Ã£o mais prÃ³xima em %3 estÃ¡ atualmente inacessÃ­vel devido a restriÃ§Ãµes de viagens do setor (rotas na lista negra).\n\nContinuarei com as operaÃ§Ãµes comerciais apesar desta limitaÃ§Ã£o. Assim que rotas seguras estiverem disponÃ­veis novamente, procurarei automaticamente serviÃ§os de reparo.\n\nMonitorarei a situaÃ§Ã£o e notificarei vocÃª quando os reparos forem possÃ­veis.\n\nRespeitosamente,\nA bordo do %4</t>
    <t id="3213">Comandante,\n\nMeu equipamento defensivo requer reabastecimento, mas a estaÃ§Ã£o de equipamento mais prÃ³xima em %1 estÃ¡ atualmente inacessÃ­vel devido a restriÃ§Ãµes de viagem do setor (rotas na lista negra).\n\nContinuarei com as operaÃ§Ãµes comerciais apesar desta limitaÃ§Ã£o. Assim que rotas seguras estiverem disponÃ­veis novamente, procurarei automaticamente serviÃ§os de reabastecimento.\n\nMonitorarei a situaÃ§Ã£o e notificarei vocÃª quando o reabastecimento for possÃ­vel.\n\nRespeitosamente,\nA bordo de %2</t>
    <t id="3208">Comandante,\n\nConcluÃ­ uma anÃ¡lise de mercado exaustiva de %1 e setores adjacentes (dentro de %2 saltos, limite mÃ­nimo de lucro: %3 Cr), mas infelizmente nÃ£o encontrei oportunidades de negociaÃ§Ã£o lucrativas que atendam aos nossos requisitos.\n\nRELATÃ“RIO DE ANÃLISE DE COMÃ‰RCIO:\nTotal de oportunidades avaliadas: %4\n\nREJEIÃ‡ÃƒO BREAKDOWN:\n- RestriÃ§Ãµes de atracaÃ§Ã£o: %5 negociaÃ§Ãµes\n (a estaÃ§Ã£o nÃ£o permite minha classe de navio)\n- Rentabilidade insuficiente: %6 negociaÃ§Ãµes\n (abaixo do limite mÃ­nimo de lucro)\n- Volume insuficiente: %7 negociaÃ§Ãµes\n (valor negociÃ¡vel zero ou negativo)\n- RestriÃ§Ãµes de seguranÃ§a: %8 negociaÃ§Ãµes\n (estaÃ§Ãµes na lista negra ou setores perigosos)\n\nRECOMENDAÃ‡Ã•ES:\n- Considere ajustar os limites de lucro\n- Expanda a distÃ¢ncia mÃ¡xima de negociaÃ§Ã£o\n- Revise as configuraÃ§Ãµes da lista negra do setor\n- Aguarde que as condiÃ§Ãµes do mercado melhorem\n\nContinuarei monitorando o mercado e notificarei vocÃª quando surgirem oportunidades lucrativas disponÃ­vel.\n\nAguardando,\nA bordo do seu serviÃ§o</t>
    <t id="3209">Comandante,\n\nALERTA DE ROTA URGENTE\n\nMeu sistema de inteligÃªncia de ameaÃ§as detectou que o setor %1 (nÃ­vel de ameaÃ§a %2) estÃ¡ agora em minha rota comercial planejada. Para a seguranÃ§a do navio e da tripulaÃ§Ã£o, estou abortando imediatamente a operaÃ§Ã£o comercial atual.\n\nAÃ‡Ã•ES TOMADAS:\n- Todas as ordens comerciais canceladas\n- Retornando ao modo de operaÃ§Ãµes seguras\n- EncontrarÃ¡ uma rota comercial alternativa que evite setores perigosos\n- Manuseio de carga: AutomÃ¡tico (venderÃ¡ qualquer carga em local seguro, se necessÃ¡rio)\n\nO sistema dinÃ¢mico de lista negra impedirÃ¡ negociaÃ§Ãµes futuras atravÃ©s deste setor atÃ© que a ameaÃ§a seja eliminada.\n\nA seguranÃ§a Ã© minha primeira prioridade.\n\nCom vigilÃ¢ncia,\nA bordo %3</t>
    <t id="3210">Comandante,\n\nROTA DE ESCAPE INICIADA\n\nAtualmente estou no setor da lista negra %1 e encontrei uma rota comercial que me permitirÃ¡ escapar com seguranÃ§a.\n\nROTA DE COMÃ‰RCIO:\nCompre: %2 (Setor: %3)\nVenda: %4 (Setor: %5)\nWare: %6 (x%7)\nLucro esperado: %8 Cr\n\nO navio escaparÃ¡ do setor da lista negra apÃ³s concluir esta negociaÃ§Ã£o.\n\nRespeitosamente,\nA bordo do seu serviÃ§o</t>
    <t id="3211">Comandante,\n\nMODO DE NEGOCIAÃ‡ÃƒO ISOLADO\n\nAtualmente estou no setor %2, mas todas as rotas para outros setores estÃ£o bloqueadas por setores centrais na lista negra. Isso significa que sÃ³ posso negociar dentro do meu setor atual atÃ© que a situaÃ§Ã£o da lista negra mude.\n\nSITUAÃ‡ÃƒO:\nSetor atual: %2\nStatus: Isolado (setor nÃ£o incluÃ­do na lista negra com rotas bloqueadas)\nModo de negociaÃ§Ã£o: Somente negociaÃ§Ãµes intra-setoriais\n\nMeu sistema de negociaÃ§Ã£o ajustou automaticamente os limites de lucro para priorizar a negociaÃ§Ã£o intra-setorial disponÃ­vel oportunidades.\n\nContinuarei monitorando a situaÃ§Ã£o e notificarei vocÃª se as rotas estiverem disponÃ­veis novamente.\n\nAtenciosamente,\nA bordo do %1</t>
    <t id="3218">Comandante,\n\nMUDANÃ‡A DE CAMINHO DE ROTA DETECTADA\n\nAo entrar no setor %1, meu sistema de navegaÃ§Ã£o detectou que a rota para meu destino %2 (%3) foi alterada.\n\nANÃLISE DE CAMINHO:\n- DistÃ¢ncia normal: %4 saltos\n- Consciente da lista negra distÃ¢ncia: %5\n- Status: %6\n\nMeu computador de navegaÃ§Ã£o indica que a rota preferida nÃ£o Ã© mais viÃ¡vel devido a restriÃ§Ãµes de viagem do setor. Para a seguranÃ§a do navio e da tripulaÃ§Ã£o, estou abortando imediatamente a operaÃ§Ã£o comercial atual.\n\nAÃ‡Ã•ES TOMADAS:\n- Todas as ordens comerciais canceladas\n- Retornando ao modo de operaÃ§Ãµes seguras\n- EncontrarÃ¡ uma rota comercial alternativa que evite setores bloqueados\n- Manuseio de carga: AutomÃ¡tico (venderÃ¡ qualquer carga em local seguro, se necessÃ¡rio)\n\nMeu sistema de navegaÃ§Ã£o evitarÃ¡ automaticamente setores bloqueados no futuro planejamento de rota.\n\nA seguranÃ§a Ã© minha primeira prioridade.\n\nCom vigilÃ¢ncia,\nA bordo %7</t>
    <t id="3219">Setor %1 limpo - Todas as ameaÃ§as eliminadas</t>
    <t id="3220">Comandante,\n\nNAVIO INIMIGO ESCAPOU\n\nNosso sistema de inteligÃªncia de ameaÃ§as perdeu o rastro do navio inimigo %3, que escapou do setor na lista negra %1.\n\nDETALHES:\n- Navio escapado: %3\n- Setor esquerdo: %1\n- Destino Setor: %2\n- Status: Rastreamento perdido - o navio saiu de nossa Ã¡rea monitorada\n\nEmbora este navio nÃ£o seja mais uma ameaÃ§a no setor %1, perdemos contato visual e nÃ£o podemos confirmar seu status atual ou intenÃ§Ãµes no setor %2.\n\nNossos sistemas de rastreamento continuarÃ£o monitorando o setor %1 em busca de ameaÃ§as restantes. Se todos os inimigos rastreados saÃ­rem ou forem eliminados, o setor serÃ¡ automaticamente removido da lista negra.\n\nCom vigilÃ¢ncia,\nSistema de InteligÃªncia de AmeaÃ§as</t>
    <t id="3221">Comandante,\n\nNÃ£o consegui encontrar oportunidades comerciais lucrativas em distÃ¢ncias maiores (atÃ© %3 saltos) porque essas rotas estÃ£o atualmente inacessÃ­veis devido a restriÃ§Ãµes de viagem do setor (caminhos na lista negra).\n\nSITUAÃ‡ÃƒO:\nSetor atual: %2\nIntervalo de pesquisa original: %3 saltos\nPesquisa de fallback Alcance: %4 saltos\n\nAgora focarei minha pesquisa em setores prÃ³ximos dentro de %4 saltos, onde as rotas tÃªm maior probabilidade de serem acessÃ­veis. Isso deve me ajudar a encontrar negociaÃ§Ãµes lucrativas que foram filtradas anteriormente devido a restriÃ§Ãµes de distÃ¢ncia, e nÃ£o Ã  falta de lucratividade real.\n\nIrei notificÃ¡-lo quando encontrar oportunidades de negociaÃ§Ã£o adequadas nas proximidades.\n\nAtenciosamente,\nA bordo de %1</t>
    <t id="3222">Comandante,\n\nSECTOR BLACKLISTED\n\nNosso sistema de inteligÃªncia de ameaÃ§as detectou atividade hostil no setor %1 e colocou este setor automaticamente na lista negra para proteger nossas operaÃ§Ãµes comerciais.\n\nNAVOS INIMIGOS DETECTADOS:\n%2\n\nDETECTADO POR: %3\n\nPara seguranÃ§a de nossos navios e tripulaÃ§Ã£o, todas as rotas comerciais atravÃ©s deste setor foram bloqueadas. Nossos navios rotarÃ£o automaticamente em torno deste setor atÃ© que a ameaÃ§a seja eliminada.\n\nO setor serÃ¡ automaticamente removido da lista negra assim que todos os navios inimigos rastreados forem eliminados ou deixarem a Ã¡rea.\n\nCom vigilÃ¢ncia,\nSistema de InteligÃªncia de AmeaÃ§as</t>
    <t id="3223">Comandante,\n\nNÃ£o consigo encontrar uma estaÃ§Ã£o de treinamento acessÃ­vel para meu exame de avanÃ§o de nÃ­vel %1. Prosseguirei com as operaÃ§Ãµes de negociaÃ§Ã£o conforme as instruÃ§Ãµes, mas entendo que nÃ£o ganharei pontos de experiÃªncia atÃ© concluir o treinamento exigido. ApÃ³s esta negociaÃ§Ã£o, procurarei novamente qualquer oportunidade possÃ­vel para treinar.\n\nRespeitosamente,\nA bordo %2</t>
    <t id="3224">Taxa de licenÃ§a de treinamento: %1 Cr</t>
    <t id="3225">BÃ´nus: ganhei %1 nÃ­vel de habilidade adicional%2 com a experiÃªncia acumulada durante o treinamento! NÃ­vel atual: %3</t>
    <t id="3214">Ã‰ uma honra trabalhar para vocÃª, %1! Estou animado para comeÃ§ar minha carreira comercial sob seu comando. Farei o meu melhor para atendÃª-lo bem e contribuir para o seu sucesso.</t>
    <t id="3215">Obrigado por me proporcionar estas merecidas fÃ©rias, %1! Aproveitei meu tempo longe da negociaÃ§Ã£o e minhas habilidades permanecem intactas. Estou ansioso para voltar ao trabalho sempre que precisar de mim. AtÃ© entÃ£o, manterei meu conhecimento de negociaÃ§Ã£o afiado!</t>
    <t id="3216">Voltei das fÃ©rias e pronto para trabalhar novamente, %1! Minhas habilidades de negociaÃ§Ã£o continuam aguÃ§adas e estou ansioso para continuar servindo vocÃª em %2. Obrigado pelo merecido descanso!</t>
    <t id="3217">Obrigado pela minha transferÃªncia para %1, %2! Estou honrado com esta nova missÃ£o e cuidarei muito bem do meu novo navio. Minha experiÃªncia e habilidades de negociaÃ§Ã£o permanecem intactas e estou pronto para continuar servindo vocÃª.</t>
    <t id="3227">Casco perdido, dignidade aguardando resgate</t>
    <t id="3228">Comandante %1,\n\n%2 reportando de %3. Minha nave explodiu. Eu nÃ£o. Agora sou a carga flutuante mais cara da frota.\n\nMarcador no mapa anexado. Por favor, apresse-se - eu estava no meio de uma fatura.\n\nFlutuando profissionalmente,\n%2</t>
    <t id="3229">Piloto recuperado - VÃ­cio em oxigÃªnio curado</t>
    <t id="3230">Comandante %1,\n\nAtualizaÃ§Ã£o da frota: %2 foi recolhido por %3 (%4) e parou de cobrar o treinamento EVA estendido.\n\nReassociaÃ§Ã£o do registro em andamento. RecomendaÃ§Ã£o: nÃ£o fazer perguntas sobre a nave antiga.\n\nVergonhosamente,\n%2</t>
<t id="4000">CoordenaÃ§Ã£o da frota: %s foi atribuÃ­da Ã  rota %s</t>
    <t id="4001">CoordenaÃ§Ã£o de frota: Rota %s Ã© totalmente utilizada</t>
    <t id="4002">CoordenaÃ§Ã£o de frota: %s liberou rota %s</t>
    <t id="5000">%s foi atribuÃ­do como territÃ³rio principal para %s</t>
    <t id="5001">%s atingiu o nÃ­vel de especializaÃ§Ã£o %s em %s!</t>
    <t id="5002">BÃ´nus de territÃ³rio aplicado: %s%% de aumento de lucro em %s</t>
    <t id="9500">Erro: %s estÃ¡ travado e precisa de ajuda!</t>
    <t id="9501">Erro: Falha na negociaÃ§Ã£o de %s</t>
    <t id="9502">Erro: nÃ£o Ã© possÃ­vel registrar %s com GalaxyTrader MK3</t>
    <t id="80001">Ware %s adicionado Ã  lista negra</t>
    <t id="80002">Ware %s removido da lista negra</t>
    <t id="80003">Ware %s adicionado Ã  lista de permissÃµes</t>
    <t id="80004">Colocado automaticamente na lista negra (desempenho ruim): %s</t>
    <t id="80005">Mercadorias perigosas priorizadas: %s</t>
    <t id="80006">Filtro Ware: %s ativo, %s negociaÃ§Ã£o bloqueada</t>
    <t id="80007">Todos os filtros de mercadorias foram limpos</t>
    <t id="80008">Filtros de Ware redefinidos para o padrÃ£o</t>
    <t id="80009">Gerenciamento de filtros de mercadorias</t>
    <t id="80010">Mercadorias bloqueadas</t>
    <t id="80011">Mercadorias permitidas</t>
    <t id="80012">Manuseio de Mercadorias Perigosas</t>
    <t id="80013">Valor MÃ­nimo de Ware</t>
    <t id="80014">Valor mÃ¡ximo de mercadorias</t>
    <t id="80015">FacÃ§Ãµes Restritas</t>
    <t id="80016">Categorias de Ware atualizadas a partir do estado atual do jogo</t>
    <t id="80017">%s produtos categorizados: %s de baixo valor, %s perigoso, %s de alto valor</t>
    <t id="80018">CategorizaÃ§Ã£o dinÃ¢mica de mercadorias habilitada</t>
    <t id="80019">Lista negra automÃ¡tica para a categoria %s desativada</t>
    <t id="80020">Novos produtos de outros mods detectados e categorizados</t>
    <t id="9000">GalaxyTrader - ConfiguraÃ§Ãµes globais</t>
    <t id="9010">XP e sistema de treinamento</t>
    <t id="9012">Treinamento AutomÃ¡tico</t>
    <t id="9013">XP Multiplicador</t>
    <t id="9015">Porcentagem de bÃ´nus de comandante</t>
    <t id="9020">CoordenaÃ§Ã£o de Frota</t>
    <t id="9021">Habilitar coordenaÃ§Ã£o de frota</t>
    <t id="9023">Habilitar cache comercial</t>
    <t id="9030">NotificaÃ§Ãµes</t>
    <t id="9031">NÃ­vel de notificaÃ§Ã£o</t>
    <t id="9040">Sistema de reparo automÃ¡tico</t>
    <t id="9041">Ativar reparo automÃ¡tico</t>
    <t id="9042">Limite de reparo do casco</t>
    <t id="9310">Galaxy-Miner</t>
    <t id="9311">Espera de varredura de sondas por setor</t>
    <t id="9312">Peso de proximidade da nave</t>
    <t id="9043">NÃ­vel mÃ­nimo de piloto</t>
    <t id="9004">Faixas de preÃ§os de negociaÃ§Ã£o</t>
    <t id="9005">PreÃ§o de oferta de venda mÃ¡ximo</t>
    <t id="9006">Comprar oferta preÃ§o mÃ­nimo</t>
    <t id="9007">Isolado: preÃ§o de venda mÃ¡ximo</t>
    <t id="9008">Isolado: preÃ§o mÃ­nimo de compra</t>
    <t id="9009">Fallback: preÃ§o de venda mÃ¡ximo</t>
    <t id="9014">Fallback: preÃ§o mÃ­nimo de compra</t>
    <t id="9016">Base do limite de lucro</t>
    <t id="9025">Dinheiro mÃ­nimo do jogador</t>
    <t id="9024">TolerÃ¢ncia de queda de cache</t>
    <t id="9026">Tempo de estacionamento ocioso antes de liberar</t>
    <t id="9054">Bloquear setores de facÃ§Ãµes inimigas</t>
    <t id="9055">NÃ­vel de ameaÃ§a da lista negra</t>
    <t id="9056">Recriar lista negra</t>
    <t id="9057">Recriar</t>
    <t id="9058">Atribuir a GT navios</t>
    <t id="9059">Atribuir</t>
    <t id="9112">Envia automaticamente pilotos para treinamento quando atingem os nÃ­veis exigidos. Desative para controlar manualmente o tempo de treinamento.</t>
    <t id="9113">Ajusta a rapidez com que os pilotos ganham experiÃªncia. Valores mais altos significam progressÃ£o mais rÃ¡pida.</t>
    <t id="9115">Porcentagem de XP subordinados concedidos a pilotos comandantes. Defina como 0% para desativar o bÃ´nus de comandante XP. PadrÃ£o: 10%.</t>
    <t id="9121">Permite recursos inteligentes de coordenaÃ§Ã£o de frota, incluindo otimizaÃ§Ã£o de rotas e balanceamento de carga.</t>
    <t id="9123">Permite compartilhar oportunidades comerciais lucrativas entre os membros da frota para uma melhor coordenaÃ§Ã£o.</t>
    <t id="9131">Controla quantas notificaÃ§Ãµes sÃ£o mostradas: 0=Silencioso, 1=Apenas importantes, 2=Todas as notificaÃ§Ãµes</t>
    <t id="9141">Envia navios automaticamente para reparos apÃ³s concluir negociaÃ§Ãµes quando o casco cai abaixo do limite. Apenas para pilotos experientes (NÃ­vel 12+). Os navios escolhem as instalaÃ§Ãµes apropriadas: Doca de Equipamentos S/M, Estaleiro L/XL.</t>
    <t id="9142">Porcentagem do casco abaixo da qual o reparo automÃ¡tico Ã© acionado. PadrÃ£o: 95%. Os navios irÃ£o automaticamente para a oficina de reparos mais prÃ³xima quando danificados.</t>
    <t id="9411">Quando ativado, mineradores aguardam ao avaliar sondas de recursos da facÃ§Ã£o no setor (+5 s por sonda acima de uma). O nÃ­vel GT do piloto reduz linearmente essa espera, do tempo completo no nÃ­vel 1 a 5 segundos no nÃ­vel 15 (apenas modo XP GT, se a espera exceder 5 s). Desativado = sem espera (comportamento vanilla).</t>
    <t id="9412">Inclina naves MK3/MK4 para estaÃ§Ãµes de compra mais prÃ³ximas ao ordenar trades validados. PontuaÃ§Ã£o de seleÃ§Ã£o = pontuaÃ§Ã£o do trade / (1 + saltos naveâ†’compra Ã— peso). Controle deslizante 0-100 (0 = off; 4 = padrÃ£o 0,04). NÃ£o afeta a classificaÃ§Ã£o do cache nem os limites de alcance territorial.</t>
    <t id="9143">NÃ­vel mÃ­nimo de piloto necessÃ¡rio para o recurso de reparo automÃ¡tico. PadrÃ£o: 12 (comerciantes experientes). Os pilotos de nÃ­vel inferior devem reparar manualmente.</t>
    <t id="9104">PreÃ§o relativo mÃ¡ximo para ofertas de venda (compra de navio das estaÃ§Ãµes). Faixa: -1,0 a +1,0. PadrÃ£o: 0,5 (50% acima da mÃ©dia). Maior = mais caro, mas mais opÃ§Ãµes.</t>
    <t id="9105">PreÃ§o relativo mÃ­nimo para ofertas de compra (navio vende estaÃ§Ãµes TO). Faixa: -1,0 a +1,0. PadrÃ£o: -0,5 (50% abaixo da mÃ©dia). Menor = compradores mais baratos, mas mais opÃ§Ãµes.</t>
    <t id="9106">PreÃ§o mÃ¡ximo de venda para navios isolados (presos em um Ãºnico setor). Faixa: -1,0 a +1,0. PadrÃ£o: 0,5.</t>
    <t id="9107">PreÃ§o mÃ­nimo de compra para navios isolados (presos em um Ãºnico setor). Faixa: -1,0 a +1,0. PadrÃ£o: -0,5.</t>
    <t id="9108">PreÃ§o mÃ¡ximo de venda para pesquisa substituta (Ãºltimo recurso quando a pesquisa normal falha). Faixa: -1,0 a +1,0. PadrÃ£o: 0,5. A pesquisa de fallback usa MaxDistance=2 e limites de lucro relaxados.</t>
    <t id="9109">Compre o preÃ§o mÃ­nimo para pesquisa substituta (Ãºltimo recurso quando a pesquisa normal falha). Faixa: -1,0 a +1,0. PadrÃ£o: -0,5. A pesquisa de fallback usa MaxDistance=2 e limites de lucro relaxados.</t>
    <t id="9116">Lucro mÃ­nimo bÃ¡sico no NÃ­vel 15 para um comerciante mÃ©dio (carga de referÃªncia 8200). O MinAbsoluteProfit real Ã© calculado por piloto + escalado por carga:\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (carga / 8200)\nfinal = max(scaled, 25% da base(L))\n\nDefina como 0 para aceitar qualquer lucro (somente ROI/distÃ¢ncia/outros filtros se aplicam).</t>
    <t id="9125">Dinheiro mÃ­nimo do jogador (crÃ©ditos) necessÃ¡rio antes que os navios procurem negociaÃ§Ãµes. Quando o dinheiro do jogador cai abaixo desse limite, todos os navios ignoram as buscas comerciais e esperam, evitando a cara verificaÃ§Ã£o do cache que causa travamentos no jogo. Faixa: 1.000 - 100.000 Cr. PadrÃ£o: 1.000 Cr.</t>
    <t id="9124">Queda percentual mÃ¡xima do ROI do valor armazenado em cache antes de rejeitar a negociaÃ§Ã£o. Exemplo: ROI armazenado em cache de 20% com tolerÃ¢ncia de 15% aceita ROI de atÃ© 17% (queda de 14%).</t>
    <t id="9126">Minutos atracados antes de desatracar para liberar a doca (0-60). 0 = permanece atracado atÃ© encontrar novo trabalho. PadrÃ£o: 1 minuto.</t>
    <t id="9154">Colocar automaticamente na lista negra todos os setores pertencentes a facÃ§Ãµes inimigas (caixa de seleÃ§Ã£o de relaÃ§Ã£o na lista negra)</t>
    <t id="9155">NÃ­vel mÃ­nimo de ameaÃ§a (1-5) necessÃ¡rio para colocar um setor na lista negra:\n2=MÃ©dio (ataque Ãºnico)\n3=MÃ©dio-Alto (facÃ§Ãµes hostis)\n4=Alto (navios capitais/mÃ­sseis)\n5=Muito Alto (Xenon/Khaak)</t>
    <t id="9156">Recrie manualmente a lista negra de prevenÃ§Ã£o de ameaÃ§as (Ãºtil se ela tiver sido excluÃ­da)</t>
    <t id="9157">Atribua manualmente a lista negra dinÃ¢mica atual a todos os navios comandantes de frota GT. Os subordinados herdam de seu comandante.</t>
    <t id="6001">Aprendiz</t>
    <t id="6002">Correio</t>
    <t id="6003">Fornecedor</t>
    <t id="6004">Comerciante</t>
    <t id="6005">Comerciante</t>
    <t id="6006">Comerciante de longa distÃ¢ncia</t>
    <t id="6101">Equilibrado</t>
    <t id="6102">Defensiva</t>
    <t id="6103">Focado na negociaÃ§Ã£o</t>
    <t id="6104">Defesa Pesada</t>
    <t id="6105">Suporte de torre</t>
    <t id="9050">Sistema de prevenÃ§Ã£o de ameaÃ§as</t>
    <t id="9051">Habilite a prevenÃ§Ã£o de ameaÃ§as:</t>
    <t id="9052">Limiar de relaÃ§Ã£o hostil:</t>
    <t id="9053">Use lista negra dinÃ¢mica:</t>
    <t id="9151">Comerciantes de nÃ­vel 6+ detectam navios hostis e evitam rotas perigosas. A desativaÃ§Ã£o interrompe todas as verificaÃ§Ãµes (melhora o desempenho). TolerÃ¢ncia ao risco por navio no comportamento de comando (escala 0-10).</t>
    <t id="9152">Apenas sinalize facÃ§Ãµes com relaÃ§Ã£o igual ou inferior a esse valor como ameaÃ§as. PadrÃ£o: -20%</t>
    <t id="9153">Coloque automaticamente setores perigosos na lista negra (nÃ­vel de ameaÃ§a 3+) para forÃ§ar os navios a contornar as ameaÃ§as. Usa pathfinding vanilla para rotas alternativas.</t>
    <t id="9060">Reabastecimento AutomÃ¡tico de Equipamento Defensivo (NÃ­vel 15)</t>
    <t id="9061">Ative o reabastecimento automÃ¡tico:</t>
    <t id="9062">Contramedidas de reabastecimento:</t>
    <t id="9063">Reabastecer Drones de Defesa:</t>
    <t id="9064">Reabastecer drones comerciais:</t>
    <t id="9065">Reabastecer torres de laser:</t>
    <t id="9066">Reabastecer drones de reparo:</t>
    <t id="9067">Limite de contramedida:</t>
    <t id="9068">Limite de capacidade unificado:</t>
    <t id="9069">Perfil de equilÃ­brio do equipamento:</t>
    <t id="9161">Master Traders (NÃ­vel 15) reabastecem automaticamente o equipamento defensivo apÃ³s as negociaÃ§Ãµes. Aplica-se ao nÃ­vel de comandante para subordinados.</t>
    <t id="9162">Todos os navios (S/M/L/XL). Capacidade separada. CrÃ­tico para defesa antimÃ­sseis.</t>
    <t id="9163">Somente envio L/XL. Compartilha capacidade unificada com outros implementÃ¡veis.</t>
    <t id="9164">Somente envio L/XL. Essencial para operaÃ§Ãµes comerciais. Compartilha capacidade unificada.</t>
    <t id="9165">Todos os navios. Os navios L/XL compartilham capacidade unificada, os navios S/M usam carga.</t>
    <t id="9166">Somente envio L/XL. Funciona com sistema de reparo automÃ¡tico. Compartilha capacidade unificada.</t>
    <t id="9167">Reabastecer quando as contramedidas estiverem abaixo deste percentual (todos os navios, capacidade separada).</t>
    <t id="9168">ReabasteÃ§a quando o total de implementÃ¡veis â€‹â€‹estiver abaixo desta porcentagem (navios L/XL: drones + torres compartilham uma capacidade).</t>
    <t id="9169">DistribuiÃ§Ã£o de capacidade unificada (navios L/XL): Focado em NegociaÃ§Ã£o (20/50/20/10), Equilibrado (35/35/20/10), Defensivo (50/20/20/10), Defesa Pesada (40/30/20/10), Suporte de Torre (30/30/30/10). ProporÃ§Ãµes: Defesa/ComÃ©rcio/Torres/Reparo. Clique para percorrer as opÃ§Ãµes.</t>
    <t id="9090">ModificaÃ§Ãµes de navio</t>
    <t id="9091">Habilitar modificaÃ§Ãµes de navio</t>
    <t id="9191">Instale automaticamente modificaÃ§Ãµes no navio e no motor com base no nÃ­vel do piloto. NÃ­vel 9+ = mods de nÃ­vel 1, NÃ­vel 12+ = mods de nÃ­vel 2, NÃ­vel 15+ = mods de nÃ­vel 3. Somente mods instalados por GT sÃ£o removidos quando o pedido Ã© cancelado.</t>
    <t id="9070">ConfiguraÃ§Ã£o de nomenclatura de navio</t>
    <t id="9071">Exibir XP:</t>
    <t id="9072">ClassificaÃ§Ã£o de exibiÃ§Ã£o:</t>
    <t id="9073">NÃ­vel de exibiÃ§Ã£o:</t>
    <t id="9074">Status de exibiÃ§Ã£o:</t>
    <t id="9075">Ativar renomeaÃ§Ã£o de navio:</t>
    <t id="9076">Prefixo</t>
    <t id="9077">Sufixo</t>
    <t id="9078">Fonte de nome padrÃ£o:</t>
    <t id="9079">Nome do modelo</t>
    <t id="9080">Nome do tipo</t>
    <t id="9081">Base do modelo</t>
    <t id="9083">Nome personalizado</t>
    <t id="9084">Mostrar setor base:</t>
    <t id="9085">Modo de nomenclatura:</t>
    <t id="9086">ClÃ¡ssico</t>
    <t id="9087">PadrÃ£o</t>
    <t id="9088">PadrÃ£o de nome:</t>
    <t id="9089">Marcadores: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. AtÃ³micos: {RS} {CB} {BL}, etc. Usa abreviaÃ§Ãµes de estado abaixo. Marcadores vazios sÃ£o omitidos; espaÃ§os sÃ£o colapsados. MÃ¡x. 128 caracteres.</t>
    <t id="9183">Mostrar o setor base configurado no nome da nave (prefixo ou sufixo).</t>
    <t id="9184">Formato de nome personalizado com marcadores {TOKEN} em vez das opÃ§Ãµes clÃ¡ssicas. Requer XP GalaxyTrader (nÃ£o modo XP vanilla).</t>
    <t id="9092">Marcadores de padrÃ£o</t>
    <t id="9093">Nave: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Base: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">TripulaÃ§Ã£o: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Setor: {SECTOR} | EstatÃ­sticas: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Marcadores de estado:</t>
    <t id="9100">{OPSTATE}: todos os indicadores operacionais ativos (ex. CB RS, MT)</t>
    <t id="9101">{STATUS}: bloqueado, treino, reserva ou isolado</t>
    <t id="9102">{CB}: sÃ³ blacklist personalizada; incluÃ­do em {OPSTATE}; nÃ£o combinar</t>
    <t id="9082">Exibir classe do navio:</t>
    <t id="9171">Mostrar valores XP em nomes de navios</t>
    <t id="9175">Habilite ou desabilite a renomeaÃ§Ã£o automÃ¡tica de navios com informaÃ§Ãµes do piloto</t>
    <t id="9172">Mostrar tÃ­tulos de classificaÃ§Ã£o em nomes de navios</t>
    <t id="9173">Mostrar nÃºmeros de nÃ­vel em nomes de navios</t>
    <t id="9174">Mostrar status comercial em nomes de navios</t>
    <t id="9178">Escolha a origem dos nomes das bases de envio: Nome do modelo (com variante), Nome do tipo (genÃ©rico), Base do modelo (sem variante) ou Nome personalizado (nome armazenado)</t>
    <t id="9182">Mostrar classe de navio (S, M, L, XL) nos nomes dos navios</t>
    <t id="9200">ConfiguraÃ§Ãµes de depuraÃ§Ã£o</t>
    <t id="9201">Habilite o registro de depuraÃ§Ã£o:</t>
    <t id="9202">AlternÃ¢ncia mestre para todas as saÃ­das debug_text. Quando desabilitado, todos os logs de depuraÃ§Ã£o sÃ£o suprimidos. Quando habilitado, mensagens de depuraÃ§Ã£o aparecem no DebugLog com base em valores de chance de debug_text individuais.</t>
    <t id="9220">ManutenÃ§Ã£o e DiagnÃ³stico</t>
    <t id="9221">Redefinir estatÃ­sticas de lucro:</t>
    <t id="9222">REINICIAR</t>
    <t id="9223">Limpar todos os setores da lista negra:</t>
    <t id="9224">CLARO</t>
    <t id="9225">Redefinir todas as configuraÃ§Ãµes para os padrÃµes:</t>
    <t id="9226">REINICIAR TUDO</t>
    <t id="9323">Remove todos os setores da lista negra de inteligÃªncia contra ameaÃ§as. Isso limparÃ¡ imediatamente todos os setores da lista negra e permitirÃ¡ que suas naves viajem para Ã¡reas anteriormente bloqueadas. Use isto se quiser redefinir o sistema de prevenÃ§Ã£o de ameaÃ§as ou se os setores foram colocados incorretamente na lista negra.</t>
    <t id="9321">Redefine todas as estatÃ­sticas de lucro para 0 para todos os pilotos e navios. Use-o apÃ³s atualizar para a v0.6.0 para limpar estatÃ­sticas inflacionadas com base em receitas. A correÃ§Ã£o agora rastreia o LUCRO real (receita - custo de compra). As contagens comerciais e XP sÃ£o preservadas.</t>
    <t id="9325">Redefine todas as configuraÃ§Ãµes globais para seus valores padrÃ£o. Isso inclui configuraÃ§Ãµes de XP, coordenaÃ§Ã£o de frota, notificaÃ§Ãµes, Intel mÃ³vel, prevenÃ§Ã£o de ameaÃ§as, nomeaÃ§Ã£o de navios, reparo automÃ¡tico, modificaÃ§Ãµes, desempenho e configuraÃ§Ãµes de formato de nÃºmero. A configuraÃ§Ã£o do log de depuraÃ§Ã£o Ã© preservada para permitir o log da operaÃ§Ã£o de redefiniÃ§Ã£o.</t>
    <t id="9227">Limpe o cache comercial para todos os setores domÃ©sticos:</t>
    <t id="9228">LIMPAR CACHE</t>
    <t id="9327">Limpa o cache comercial de todos os setores domÃ©sticos. Isso forÃ§arÃ¡ todos os navios a realizar novas buscas ao vivo em sua prÃ³xima busca comercial. Use isto se o cache parecer obsoleto ou corrompido, ou se vocÃª quiser forÃ§ar uma atualizaÃ§Ã£o completa do cache.</t>
    <t id="9229">Liberar todos os bloqueios de pesquisa</t>
    <t id="9329">Libera TODOS os bloqueios de busca comercial em voo e limpa o estado transitÃ³rio relacionado. Use isto se os navios estiverem presos em â€œProcurando negociaÃ§Ãµesâ€ devido a fechaduras obsoletas de salvamentos antigos. Isto pode interromper pesquisas legÃ­timas.</t>
    <t id="9290">Status do Centro para o ComÃ©rcio:</t>
    <t id="9291">JOGAR FORA</t>
    <t id="9390">Mostra um instantÃ¢neo Ãºnico do centro comercial centralizado (filas do agendador + status do Ãºltimo pedido de envio) no registro e como uma notificaÃ§Ã£o.</t>
    <t id="9292">Despejar cache comercial (completo):</t>
    <t id="9293">DESPEJAR CACHE</t>
    <t id="9392">Despejo de cache COMPLETO (pode ser enorme). Grava todas as entradas de cache no DebugLog em partes. Clique novamente para cancelar.</t>
    <t id="9294">Limpar reservas de frota:</t>
    <t id="9295">CLARO</t>
    <t id="9394">Limpa todas as reservas comerciais de frota ativas. Use isto se os navios parecerem presos esperando a expiraÃ§Ã£o de negociaÃ§Ãµes reservadas ou se a tabela de reservas ficar obsoleta apÃ³s carregar um salvamento antigo.</t>
    <t id="9230">Desempenho</t>
    <t id="9231">Atraso no processamento em lote:</t>
    <t id="9232">Atraso na validaÃ§Ã£o:</t>
    <t id="9233">MÃ¡ximo de pesquisas simultÃ¢neas:</t>
    <t id="9234">MÃ¡ximo de negociaÃ§Ãµes para retornar:</t>
    <t id="9235">Ofertas mÃ¡ximas por produto:</t>
    <t id="9236">MÃ¡ximo de negociaÃ§Ãµes por mercadoria:</t>
    <t id="9237">Ofertas mÃ¡ximas por produto para correspondÃªncia:</t>
    <t id="9238">Limite de saÃ­da antecipada:</t>
    <t id="9241">Intervalo de fatia de oferta ao vivo:</t>
    <t id="9266">TTL de bloqueio de pesquisa:</t>
    <t id="9263">Tamanho do pedaÃ§o do lote:</t>
    <t id="9239">Formato numÃ©rico</t>
    <t id="9240">Estilo de formato:</t>
    <t id="9242">Usar sufixo M</t>
    <t id="9243">Limite do sufixo M:</t>
    <t id="9244">AlemÃ£o (123.456,78)</t>
    <t id="9245">InglÃªs (123.456,78)</t>
    <t id="9510">NotificaÃ§Ãµes de subida de nÃ­vel:</t>
    <t id="9511">Alertas de treinamento necessÃ¡rio:</t>
    <t id="9512">NotificaÃ§Ãµes de treinamento concluÃ­do:</t>
    <t id="9513">RelatÃ³rios de lucro:</t>
    <t id="9514">Alertas de mercado:</t>
    <t id="9515">AtualizaÃ§Ãµes de frota:</t>
    <t id="9516">Use apenas vanilla XP</t>
    <t id="9610">Ativar ou desativar notificaÃ§Ãµes popup de subida de nÃ­vel do comerciante na interface do jogador.</t>
    <t id="9611">Alerta quando os pilotos precisam de treinamento para avanÃ§ar ao prÃ³ximo nÃ­vel.</t>
    <t id="9612">Notificar quando os pilotos concluem o treinamento e avanÃ§am de patente.</t>
    <t id="9613">Resumos periÃ³dicos de lucro (relatÃ³rios simples e abrangentes).</t>
    <t id="9614">Oportunidades de mercado excepcionais e alertas de negÃ³cios de alto valor.</t>
    <t id="9615">Mensagens de coordenaÃ§Ã£o de frota e atualizaÃ§Ãµes de status.</t>
    <t id="9616">Use pilot.skill.piloting e desative GT XP progressÃ£o/caps.</t>
    <t id="9246">FrequÃªncia de relatÃ³rio simples:</t>
    <t id="9247">FrequÃªncia de relatÃ³rio abrangente:</t>
    <t id="9248">MÃ¡ximo de pesquisas simultÃ¢neas em cache:</t>
    <t id="9249">MÃ¡ximo de pesquisas simultÃ¢neas ao vivo:</t>
    <t id="9340">Escolha o formato do nÃºmero: o alemÃ£o usa '.' para milhares e ',' para decimais (123.456,78), o inglÃªs usa ',' para milhares e '.' para decimais (123.456,78)</t>
    <t id="9342">Habilite o sufixo M para nÃºmeros maiores que o limite (por exemplo, 1,0 M em vez de 1.000.000)</t>
    <t id="9343">Limite para o sufixo M. Os nÃºmeros acima deste valor serÃ£o exibidos com o sufixo M (padrÃ£o: 999.999)</t>
    <t id="9346">FrequÃªncia do relatÃ³rio simples (notificaÃ§Ã£o pop-up): 0-30 minutos (0 = desabilitado - os relatÃ³rios simples estÃ£o desabilitados, padrÃ£o: 1 minuto)</t>
    <t id="9347">FrequÃªncia do relatÃ³rio abrangente (entrada no diÃ¡rio de bordo): 0-60 minutos (0 = desabilitado - relatÃ³rios abrangentes estÃ£o desabilitados, padrÃ£o: 30 minutos)</t>
    <t id="9398">Usar GT SubstituiÃ§Ã£o de CrÃ©ditos Vencidos</t>
    <t id="9399">Substitua ou aumente a linha bÃ¡sica "CR devido de negociaÃ§Ãµes" pelo valor projetado GT no mesmo slot da UI.</t>
    <t id="9331">Atraso entre lotes durante o processamento da pesquisa comercial (1-500 ms). Valores mais altos reduzem a carga da CPU, mas retardam as pesquisas comerciais. PadrÃ£o: 120 ms. Usado no processador de lote e filtragem de listas comerciais.</t>
    <t id="9332">Atraso entre validaÃ§Ãµes comerciais no script AI (1-500ms). Valores mais altos reduzem a carga da CPU, mas retardam a validaÃ§Ã£o da negociaÃ§Ã£o. PadrÃ£o: 50 ms. Usado ao validar a lista comercial do sistema MD.</t>
    <t id="9333">NÃºmero mÃ¡ximo de pesquisas comerciais que podem ser executadas simultaneamente (1-10). Valores mais baixos reduzem a carga da CPU, mas aumentam os tempos de espera na fila. Valores mais altos processam pesquisas mais rapidamente, mas podem causar picos de desempenho. PadrÃ£o: 1.</t>
    <t id="9334">NÃºmero mÃ¡ximo de negociaÃ§Ãµes a serem retornadas da pesquisa de cache (1-100). Valores mais altos fornecem mais opÃ§Ãµes de negociaÃ§Ã£o, mas aumentam o tempo de validaÃ§Ã£o do cache. Valores mais baixos reduzem a carga da CPU, mas podem perder negociaÃ§Ãµes viÃ¡veis. PadrÃ£o: 20.</t>
    <t id="9335">NÃºmero mÃ¡ximo de ofertas por produto para processar na pesquisa ao vivo (5-100). Valores mais altos consideram mais ofertas, mas aumentam o tempo de processamento. Valores mais baixos reduzem a carga da CPU, mas podem perder negociaÃ§Ãµes lucrativas. PadrÃ£o: 20.</t>
    <t id="9336">NÃºmero mÃ¡ximo de negociaÃ§Ãµes por produto durante o processamento em lote (5-100). Valores mais altos permitem mais negociaÃ§Ãµes por produto, mas aumentam o tempo de processamento. Valores mais baixos reduzem a carga da CPU, mas podem perder negociaÃ§Ãµes lucrativas. PadrÃ£o: 20.</t>
    <t id="9337">NÃºmero mÃ¡ximo de ofertas por produto para correspondÃªncia no processador em lote (5-100). Valores mais altos consideram mais ofertas, mas aumentam o tempo de processamento. Valores mais baixos reduzem a carga da CPU, mas podem perder negociaÃ§Ãµes lucrativas. PadrÃ£o: 20.</t>
    <t id="9338">Limite de saÃ­da antecipada para processamento em lote (100-10000). Quando tantas negociaÃ§Ãµes sÃ£o encontradas, o processamento em lote Ã© interrompido antecipadamente para economizar CPU. Valores mais altos processam mais negociaÃ§Ãµes, mas aumentam a carga da CPU. Valores mais baixos saem mais cedo, mas podem perder negociaÃ§Ãµes lucrativas. PadrÃ£o: 2000.</t>
    <t id="9341">Intervalo de fatia de oferta ao vivo em milissegundos (5-2.000 ms). Controla a frequÃªncia com que as fatias de oferta ao vivo podem ser iniciadas. Valores mais baixos permitem uma coleta de ofertas mais rÃ¡pida, mas aumentam a carga da CPU. Valores mais altos reduzem a carga da CPU, mas retardam o processamento da pesquisa em tempo real. PadrÃ£o: 500 ms.</t>
    <t id="9363">Tamanho do bloco de processamento em lote (5-20). Processa combinaÃ§Ãµes chunkSizeÃ—chunkSize por pedaÃ§o (por exemplo, 5Ã—5 = 25 combinaÃ§Ãµes). PedaÃ§os maiores melhoram o rendimento, mas aumentam a carga da CPU por pedaÃ§o. PedaÃ§os menores reduzem os picos de CPU, mas exigem mais continuaÃ§Ãµes. PadrÃ£o: 5.</t>
    <t id="9348">NÃºmero mÃ¡ximo de pesquisas de cache que podem ser executadas simultaneamente (1-20). As pesquisas em cache sÃ£o rÃ¡pidas e baratas; valores mais baixos podem reduzir a explosÃ£o em frotas enormes. PadrÃ£o: 2.</t>
    <t id="9349">NÃºmero mÃ¡ximo de pesquisas em tempo real que podem ser executadas simultaneamente (1 a 10). As pesquisas em tempo real exigem muita CPU, portanto, valores mais baixos reduzem a carga da CPU, mas aumentam os tempos de espera na fila. Valores mais altos processam pesquisas mais rapidamente, mas podem causar picos de desempenho. PadrÃ£o: 1.</t>
    <t id="9264">Tamanho do bloco de consulta de cache:</t>
    <t id="9265">Tamanho do pedaÃ§o anexado da oferta ao vivo:</t>
    <t id="9364">Entradas de cache validadas por bloco (10-200). Valores menores espalham a validaÃ§Ã£o do cache por mais frames (mais suave), mas podem aumentar o tempo para encontrar uma negociaÃ§Ã£o em cache. PadrÃ£o: 10.</t>
    <t id="9365">Ofertas anexadas por fatia anexada (50-2000). Valores menores reduzem o trabalho de anexaÃ§Ã£o de lista por quadro (mais suave), mas podem retardar a conclusÃ£o da pesquisa ao vivo. PadrÃ£o: 200.</t>
    <t id="9366">Tempo de vida do bloqueio de pesquisa em segundos (60-7200). Se um navio for negado com "busca comercial jÃ¡ em andamento" por mais tempo do que isso, GT irÃ¡ se auto-curar limpando o estado de busca obsoleto e liberando o bloqueio. PadrÃ£o: 600s.</t>
    <t id="9370">Limite suave de contrapressÃ£o de lote:</t>
    <t id="9371">Limite rÃ­gido de contrapressÃ£o de lote:</t>
    <t id="9372">Setores por fatia:</t>
    <t id="9373">Recarga de atualizaÃ§Ã£o inicial:</t>
    <t id="9374">Base de resfriamento de falta de cache:</t>
    <t id="9375">Intervalo de tick do agendador:</t>
    <t id="9376">MÃ¡ximo de consultas de cache por tick:</t>
    <t id="9377">ContinuaÃ§Ãµes mÃ¡ximas de pesquisa por tick:</t>
    <t id="9378">MÃ¡ximo de envios por tick:</t>
    <t id="9379">MÃ¡ximo de itens por tick:</t>
    <t id="9380">MÃ¡ximo de ativaÃ§Ã£o por tick:</t>
    <t id="9381">Entradas mÃ¡ximas de consulta de cache:</t>
    <t id="9382">Segundos limite obsoletos:</t>
    <t id="9383">Segundos do limite obsoleto da fila:</t>
    <t id="9384">Segundos de expiraÃ§Ã£o de negociaÃ§Ã£o com falha:</t>
    <t id="9385">MÃ¡ximo de pesquisas alternativas simultÃ¢neas:</t>
    <t id="9386">MÃ¡ximo de pesquisas alternativas simultÃ¢neas:</t>
    <t id="9470">Limite flexÃ­vel para pendÃªncias do processador em lote (5-50). Quando o backlog atinge esse valor, a contrapressÃ£o comeÃ§a a ser aplicada para retardar novas solicitaÃ§Ãµes de pesquisa. Valores mais baixos acionam a contrapressÃ£o mais cedo (mais conservador). PadrÃ£o: 10.</t>
    <t id="9471">Limite rÃ­gido para pendÃªncias do processador em lote (10-100). Quando o backlog atinge esse valor, novas pesquisas em tempo real sÃ£o bloqueadas atÃ© que o backlog diminua. Valores mais baixos bloqueiam pesquisas mais cedo (mais conservadores). PadrÃ£o: 25.</t>
    <t id="9472">Setores processados â€‹â€‹por fatia na coleta de ofertas ao vivo (1-5). Valores menores distribuem o trabalho por mais quadros (mais suaves), mas podem retardar a coleta de ofertas. Valores maiores sÃ£o processados â€‹â€‹mais rapidamente, mas podem causar picos de quadros. PadrÃ£o: 1.</t>
    <t id="9473">Tempo de espera apÃ³s a conclusÃ£o da atualizaÃ§Ã£o do setor domÃ©stico (10 a 120 segundos). Evita solicitaÃ§Ãµes de atualizaÃ§Ã£o excessivas. Valores mais baixos permitem atualizaÃ§Ãµes mais frequentes, mas aumentam a carga da CPU. Valores mais altos reduzem a frequÃªncia de atualizaÃ§Ã£o, mas podem atrasar as atualizaÃ§Ãµes do cache. PadrÃ£o: 30s.</t>
    <t id="9474">Recarga bÃ¡sica apÃ³s perda de cache antes de tentar novamente a pesquisa ao vivo (1 a 30 segundos). Evita tentativas excessivas de repetiÃ§Ã£o. Valores mais baixos tentam novamente mais cedo, mas aumentam a carga da CPU. Valores mais altos reduzem a frequÃªncia de novas tentativas, mas podem atrasar a descoberta de negociaÃ§Ãµes. PadrÃ£o: 10s.</t>
    <t id="9475">Intervalo entre os ticks do agendador em milissegundos (50-500ms). Controla a frequÃªncia com que o agendador processa a fila de trabalho. Valores mais baixos sÃ£o processados â€‹â€‹com mais frequÃªncia, mas aumentam a carga da CPU. Valores mais altos reduzem a carga da CPU, mas podem aumentar o tempo de espera na fila. PadrÃ£o: 100ms.</t>
    <t id="9476">MÃ¡ximo de consultas de cache iniciadas por tick do agendador (1-5). Limita a taxa de consulta do cache para evitar o bloqueio de quadros. Valores mais baixos reduzem picos de CPU, mas retardam as pesquisas no cache. Valores mais altos sÃ£o processados â€‹â€‹mais rapidamente, mas podem causar falhas. PadrÃ£o: 1.</t>
    <t id="9477">MÃ¡ximo de continuaÃ§Ãµes de pesquisa iniciadas por tick do agendador (1-5). Limita a taxa de continuaÃ§Ã£o para evitar o bloqueio de quadros. Valores mais baixos reduzem picos de CPU, mas retardam o processamento de pesquisa. Valores mais altos sÃ£o processados â€‹â€‹mais rapidamente, mas podem causar falhas. PadrÃ£o: 1.</t>
    <t id="9478">MÃ¡ximo de navios processados â€‹â€‹por tick do agendador (1-5). Limita a taxa de processamento de envio para evitar o bloqueio de quadros. Valores mais baixos reduzem picos de CPU, mas retardam o processamento da fila. Valores mais altos sÃ£o processados â€‹â€‹mais rapidamente, mas podem causar falhas. PadrÃ£o: 1.</t>
    <t id="9479">MÃ¡ximo de itens de trabalho processados â€‹â€‹por tick do agendador (1-5). Limita a taxa de processamento de itens de trabalho para evitar o bloqueio de quadros. Valores mais baixos reduzem picos de CPU, mas retardam o processamento da fila. Valores mais altos sÃ£o processados â€‹â€‹mais rapidamente, mas podem causar falhas. PadrÃ£o: 1.</t>
    <t id="9480">MÃ¡ximo de garÃ§ons acordados por tick do agendador (1-10). Limita a taxa de ativaÃ§Ã£o para evitar picos de CPU quando muitos waiters estÃ£o na fila. Valores mais baixos reduzem picos de CPU, mas retardam o processamento do waiter. Valores mais altos sÃ£o processados â€‹â€‹mais rapidamente, mas podem causar falhas. PadrÃ£o: 2.</t>
    <t id="9481">MÃ¡ximo de entradas de cache consultadas por lote (1-200). Controla o tamanho do lote de consulta de cache. Valores mais baixos tornam as pesquisas no cache mais rÃ¡pidas, mas podem perder negociaÃ§Ãµes melhores. Valores mais altos consideram mais negociaÃ§Ãµes em cache, mas aumentam o tempo de validaÃ§Ã£o. PadrÃ£o: 50.</t>
    <t id="9482">Limite de obsolescÃªncia do estado de pesquisa em tempo real em segundos (60-600). Quando o estado de pesquisa ao vivo Ã© mais antigo que isso, ele Ã© considerado obsoleto e limpo. Valores mais baixos eliminam o estado obsoleto mais cedo, mas podem interromper pesquisas legÃ­timas. Valores mais altos permitem pesquisas mais longas, mas podem deixar o estado obsoleto. PadrÃ£o: 300s.</t>
    <t id="9483">Limite de itens obsoletos da fila em segundos (30-300). Quando os itens da fila sÃ£o mais antigos que isso, eles sÃ£o considerados obsoletos e removidos. Valores mais baixos eliminam itens obsoletos mais cedo, mas podem remover itens legÃ­timos na fila. Valores mais altos permitem tempos de fila mais longos, mas podem deixar itens obsoletos. PadrÃ£o: 60 anos.</t>
    <t id="9484">Falha na expiraÃ§Ã£o do cache comercial em segundos (300-3600). As negociaÃ§Ãµes com falha sÃ£o armazenadas em cache para evitar novas tentativas imediatamente. Valores mais baixos expiram as negociaÃ§Ãµes com falha mais cedo (mais tentativas), mas reduzem a eficÃ¡cia do cache. Valores mais altos armazenam em cache por mais tempo (menos tentativas), mas podem atrasar as novas tentativas. PadrÃ£o: 1800 (30 minutos).</t>
    <t id="9485">MÃ¡ximo de pesquisas ao vivo de fallback simultÃ¢neas (1-10). As buscas alternativas contornam o bloqueio do setor de origem, permitindo que vÃ¡rios navios do mesmo setor de origem faÃ§am buscas simultaneamente. Valores mais baixos reduzem a carga da CPU, mas podem retardar as pesquisas alternativas. Valores mais altos permitem mais pesquisas paralelas de fallback, mas aumentam o uso da CPU. PadrÃ£o: 1.</t>
    <t id="9490">Atraso no sinal de negociaÃ§Ã£o encontrada:</t>
    <t id="9590">Atraso antes de enviar o sinal GTTrade_Found para navios em milissegundos (10-1000ms). Os navios sempre esperam (atraso configurado + buffer de 5ms) antes de enviar novas solicitaÃ§Ãµes para capturar sinais atrasados. Valores mais altos espalham sinais entre quadros para um desempenho mais suave. PadrÃ£o: 10ms.</t>
    <t id="8000">GalaxyTrader Frota</t>
    <t id="8001">GalaxyTrader gerenciamento de frota e estatÃ­sticas de pilotos</t>
    <t id="8002">Ver e gerenciar todos os GalaxyTrader pilotos</t>
    <t id="8100">ID do navio</t>
    <t id="8101">Piloto</t>
    <t id="8102">Enviar</t>
    <t id="8103">Status</t>
    <t id="8104">ClassificaÃ§Ã£o</t>
    <t id="8105">NÃ­vel</t>
    <t id="8106">XP</t>
    <t id="8107">Lucro vitalÃ­cio</t>
    <t id="8108">LocalizaÃ§Ã£o</t>
    <t id="8109">Base inicial</t>
    <t id="8110">Ãšltima negociaÃ§Ã£o</t>
    <t id="8111">Lucro piloto</t>
    <t id="8112">Lucro do navio</t>
    <t id="8113">Contagem comercial</t>
    <t id="8200">Atualizar</t>
    <t id="8201">Exportar CSV</t>
    <t id="8202">EstatÃ­sticas</t>
    <t id="8203">ConfiguraÃ§Ãµes</t>
    <t id="8204">Ajuda</t>
    <t id="8205">Fechar</t>
    <t id="8300">Todos os pilotos</t>
    <t id="8301">NegociaÃ§Ã£o</t>
    <t id="8302">Treinamento</t>
    <t id="8303">ManutenÃ§Ã£o</t>
    <t id="8304">EmergÃªncia</t>
    <t id="8305">Iniciantes (NÃ­vel 1-5)</t>
    <t id="8306">AvanÃ§ado (NÃ­vel 6-11)</t>
    <t id="8307">Especialistas (NÃ­vel 12+)</t>
    <t id="8308">Os 10 maiores ganhadores</t>
    <t id="8350">Ordenar por:</t>
    <t id="8351">ID do navio</t>
    <t id="8352">Nome do piloto</t>
    <t id="8353">Tipo de navio</t>
    <t id="8354">Status</t>
    <t id="8355">ClassificaÃ§Ã£o</t>
    <t id="8356">NÃ­vel</t>
    <t id="8357">XP</t>
    <t id="8358">Lucro</t>
    <t id="8400">Nenhum piloto cadastrado</t>
    <t id="8401">Nenhum piloto corresponde ao filtro</t>
    <t id="8402">Total de pilotos:</t>
    <t id="8403">Lucro total da frota:</t>
    <t id="8404">Ãšltima atualizaÃ§Ã£o:</t>
    <t id="8405">Pesquisar pilotos...</t>
    <t id="8114">Setor</t>
    <t id="8320">RenomeaÃ§Ã£o de navio</t>
    <t id="8321">Nome personalizado</t>
    <t id="8322">Definir nome</t>
    <t id="8323">Limpar nome</t>
    <t id="8324">Nome definido com sucesso</t>
    <t id="8325">Nome apagado com sucesso</t>
    <t id="8450">Enviar para treinamento</t>
    <t id="8451">Cancelar registro</t>
    <t id="8452">ForÃ§ar venda de carga</t>
    <t id="8453">Enviar para reparo</t>
    <t id="8454">Enviar para reabastecimento</t>
    <t id="8455">Interromper todos os pedidos</t>
    <t id="8456">AÃ§Ãµes</t>
    <t id="8500">Clique para classificar por ID do navio</t>
    <t id="8501">Clique para classificar por nome do piloto</t>
    <t id="8502">Clique para classificar por tipo de navio</t>
    <t id="8503">Clique para classificar por status</t>
    <t id="8504">Clique para classificar por classificaÃ§Ã£o</t>
    <t id="8505">Clique para classificar por nÃ­vel</t>
    <t id="8506">Clique para classificar por XP</t>
    <t id="8507">Clique para classificar por lucro vitalÃ­cio</t>
    <t id="8508">Atualizar dados do piloto do sistema de missÃ£o</t>
    <t id="8509">Exportar visualizaÃ§Ã£o atual para arquivo CSV</t>
    <t id="8510">Veja estatÃ­sticas e grÃ¡ficos da frota</t>
    <t id="8511">Definir configuraÃ§Ãµes do menu</t>
    <t id="8512">Mostrar ajuda e atalhos de teclado</t>
    <t id="8600">Nenhum piloto GalaxyTrader encontrado</t>
    <t id="8601">Crie pilotos atribuindo navios a GalaxyTrader ou aguarde o carregamento dos dados.</t>
    <t id="9001">GT Renomear</t>
    <t id="9902">Enviar para treinamento</t>
    <t id="9903">Treinamento manual na fila para %1. O piloto comeÃ§arÃ¡ o treinamento apÃ³s o ciclo atual.</t>
    <t id="9904">Treinamento na fila apÃ³s o ciclo atual</t>
    <t id="9905">Piloto ou navio nÃ£o encontrado</t>
    <t id="9906">O AutoTraining estÃ¡ ativado - fila manual nÃ£o Ã© necessÃ¡ria</t>
    <t id="9907">O piloto nÃ£o estÃ¡ com o treinamento bloqueado</t>
    <t id="9910">Academia de ComÃ©rcio</t>
    <t id="9911">Aprendiz (Nvl 4) - %1 / %2</t>
    <t id="9912">Comerciante (Nvl 7) - %1 / %2</t>
    <t id="9913">Mestre Comerciante (Nvl 13) - %1 / %2</t>
    <t id="9920">Piloto %1 inscrito no curso da Academia para NÃ­vel %2. Partindo para a estaÃ§Ã£o comercial mais prÃ³xima.</t>
    <t id="9921">Fundos insuficientes para este curso (necessÃ¡rios %1, disponÃ­veis %2).</t>
    <t id="9922">Curso indisponÃ­vel - o piloto %1 jÃ¡ estÃ¡ neste nÃ­vel ou acima.</t>
    <t id="9923">Piloto %1 inscrito no curso NÃ­vel %2 da Academia de ComÃ©rcio (custo: %3 Cr, duraÃ§Ã£o: %4 min) a bordo de %5.</t>
    <t id="11011">GT Redutor de Navio MÃ©dio Aprendiz</t>
    <t id="11012">ModificaÃ§Ã£o do motor que reduz ligeiramente o desempenho para pilotos inexperientes em navios mÃ©dios. Usado pelo sistema de IA GalaxyTrader. -5% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="11013">GT Redutor de viagem mÃ©dio para aprendiz</t>
    <t id="11014">ModificaÃ§Ã£o do motor que reduz ligeiramente o desempenho de viagem para pilotos inexperientes em navios mÃ©dios. Usado pelo sistema de IA GalaxyTrader. -5% de velocidade de deslocamento.</t>
    <t id="11021">GT Aprendiz de Redutor de Navio Grande</t>
    <t id="11022">ModificaÃ§Ã£o do motor que reduz o desempenho de pilotos inexperientes em navios de grande porte. Usado pelo sistema de IA GalaxyTrader. -15% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="11023">GT Redutor de viagem grande para aprendiz</t>
    <t id="11024">ModificaÃ§Ã£o do motor que reduz o desempenho de viagem para pilotos inexperientes em navios de grande porte. Usado pelo sistema de IA GalaxyTrader. -15% de velocidade de deslocamento.</t>
    <t id="11031">GT Redutor de Navio Capital Aprendiz</t>
    <t id="11032">ModificaÃ§Ã£o do motor que reduz significativamente o desempenho de pilotos inexperientes em navios capitais. Usado pelo sistema de IA GalaxyTrader. -25% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="11033">GT Redutor de viagem de capital de aprendiz</t>
    <t id="11034">ModificaÃ§Ã£o do motor que reduz significativamente o desempenho de viagem para pilotos inexperientes em navios capitais. Usado pelo sistema de IA GalaxyTrader. -25% de velocidade de deslocamento.</t>
    <t id="12001">GT Aprimorador BÃ¡sico de Navios Pequenos</t>
    <t id="12002">ModificaÃ§Ã£o especializada de motores para pequenos navios com pilotos bÃ¡sicos certificados. Usado pelo sistema de IA GalaxyTrader. +3% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="12003">GT Melhorador BÃ¡sico de Pequenas Viagens</t>
    <t id="12004">ModificaÃ§Ã£o especializada de motores para pequenos navios com pilotos bÃ¡sicos certificados. Usado pelo sistema de IA GalaxyTrader. +3% de velocidade de viagem.</t>
    <t id="13001">GT Redutor bÃ¡sico para navios grandes</t>
    <t id="13002">ModificaÃ§Ã£o especializada de motores para navios de grande porte com pilotos bÃ¡sicos certificados. Usado pelo sistema de IA GalaxyTrader. -8% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="13003">GT Redutor bÃ¡sico de deslocamento grande</t>
    <t id="13004">ModificaÃ§Ã£o especializada de motores para navios de grande porte com pilotos bÃ¡sicos certificados. Usado pelo sistema de IA GalaxyTrader. -8% de velocidade de deslocamento.</t>
    <t id="14001">GT Redutor BÃ¡sico de Navio de Capital</t>
    <t id="14002">ModificaÃ§Ã£o especializada de motores para navios capitais com pilotos bÃ¡sicos certificados. Usado pelo sistema de IA GalaxyTrader. -15% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="14003">GT Redutor de viagem de capital bÃ¡sico</t>
    <t id="14004">ModificaÃ§Ã£o especializada de motores para navios capitais com pilotos bÃ¡sicos certificados. Usado pelo sistema de IA GalaxyTrader. -15% de velocidade de deslocamento.</t>
    <t id="15001">GT Aprimorador Especialista de Pequenos Navios</t>
    <t id="15002">ModificaÃ§Ã£o avanÃ§ada de motores para navios pequenos com pilotos experientes. Usado pelo sistema de IA GalaxyTrader. +25% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="15003">GT Melhorador de viagens pequenas especializado</t>
    <t id="15004">ModificaÃ§Ã£o avanÃ§ada de motores para navios pequenos com pilotos experientes. Usado pelo sistema de IA GalaxyTrader. +25% de velocidade de viagem.</t>
    <t id="16001">GT Aprimorador Especialista de Grandes Navios</t>
    <t id="16002">ModificaÃ§Ã£o avanÃ§ada de motores para navios grandes com pilotos experientes. Usado pelo sistema de IA GalaxyTrader. +15% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="16003">GT Grande intensificador de viagens especializado</t>
    <t id="16004">ModificaÃ§Ã£o avanÃ§ada de motores para navios grandes com pilotos experientes. Usado pelo sistema de IA GalaxyTrader. +15% de velocidade de viagem.</t>
    <t id="17001">GT Aprimorador de navio de capital especializado</t>
    <t id="17002">ModificaÃ§Ã£o avanÃ§ada de motores para navios capitais com pilotos experientes. Usado pelo sistema de IA GalaxyTrader. +6% de velocidade, impulso e rotaÃ§Ã£o.</t>
    <t id="17003">GT Potenciador de viagens de capital especializado</t>
    <t id="17004">ModificaÃ§Ã£o avanÃ§ada de motores para navios capitais com pilotos experientes. Usado pelo sistema de IA GalaxyTrader. +6% de velocidade de viagem.</t>
    <t id="18001">LimitaÃ§Ã£o Severa de Habilidade (Navio)</t>
    <t id="18002">LimitaÃ§Ã£o Severa de Habilidade (Navio) - Representa penalidades severas de desempenho devido Ã  inexperiÃªncia do piloto com embarcaÃ§Ãµes de grande porte. Aplicado automaticamente pelo sistema GalaxyTrader quando a habilidade do piloto Ã© insuficiente para o tamanho do navio. Aumenta a massa do navio. (GT Somente sistema - NÃ£o disponÃ­vel para instalaÃ§Ã£o manual)</t>
    <t id="18003">LimitaÃ§Ã£o moderada de habilidade (navio)</t>
    <t id="18004">LimitaÃ§Ã£o Moderada de Habilidade (Navio) - Representa penalidades moderadas de desempenho Ã  medida que o piloto se adapta Ã  complexidade da embarcaÃ§Ã£o. Aplicado automaticamente pelo sistema GalaxyTrader quando a habilidade do piloto Ã© insuficiente para o tamanho do navio. Aumenta a massa do navio. (GT Somente sistema - NÃ£o disponÃ­vel para instalaÃ§Ã£o manual)</t>
    <t id="18005">LimitaÃ§Ã£o de habilidade leve (navio)</t>
    <t id="18006">LimitaÃ§Ã£o de habilidade leve (navio) - Representa pequenas penalidades de desempenho durante o desenvolvimento de habilidades do piloto. Aplicado automaticamente pelo sistema GalaxyTrader quando a habilidade do piloto Ã© insuficiente para o tamanho do navio. Aumenta a massa do navio. (GT Somente sistema - NÃ£o disponÃ­vel para instalaÃ§Ã£o manual)</t>
    <t id="18007">LimitaÃ§Ã£o Severa de Habilidade (Motor)</t>
    <t id="18008">LimitaÃ§Ã£o Severa de Habilidade (Motor) - Representa penalidades severas de desempenho devido Ã  inexperiÃªncia do piloto com embarcaÃ§Ãµes de grande porte. Aplicado automaticamente pelo sistema GalaxyTrader quando a habilidade do piloto Ã© insuficiente para o tamanho do navio. Reduz o empuxo e a rotaÃ§Ã£o do motor. (GT Somente sistema - NÃ£o disponÃ­vel para instalaÃ§Ã£o manual)</t>
    <t id="18009">LimitaÃ§Ã£o moderada de habilidade (motor)</t>
    <t id="18010">LimitaÃ§Ã£o Moderada de Habilidade (Motor) - Representa penalidades moderadas de desempenho Ã  medida que o piloto se adapta Ã  complexidade da embarcaÃ§Ã£o. Aplicado automaticamente pelo sistema GalaxyTrader quando a habilidade do piloto Ã© insuficiente para o tamanho do navio. Reduz o empuxo e a rotaÃ§Ã£o do motor. (GT Somente sistema - NÃ£o disponÃ­vel para instalaÃ§Ã£o manual)</t>
    <t id="18011">LimitaÃ§Ã£o de habilidade leve (motor)</t>
    <t id="18012">LimitaÃ§Ã£o de habilidade leve (motor) - Representa pequenas penalidades de desempenho durante o desenvolvimento de habilidades do piloto. Aplicado automaticamente pelo sistema GalaxyTrader quando a habilidade do piloto Ã© insuficiente para o tamanho do navio. Reduz o empuxo e a rotaÃ§Ã£o do motor. (GT Somente sistema - NÃ£o disponÃ­vel para instalaÃ§Ã£o manual)</t>
    <t id="9250">Nomenclatura do estado do navio</t>
    <t id="9350">Personalize as abreviaÃ§Ãµes do estado do navio. Os valores padrÃ£o sÃ£o mostrados em caixas de entrada e podem ser substituÃ­dos. MÃ¡ximo de 3 caracteres. Todos os nomes de navios serÃ£o atualizados automaticamente quando alterados.</t>
    <t id="9251">Abreviatura do estado de reabastecimento:</t>
    <t id="9252">Abreviatura do estado de reparo:</t>
    <t id="9253">Abreviatura do estado de manutenÃ§Ã£o:</t>
    <t id="9254">Abreviatura do estado de treinamento:</t>
    <t id="9255">AbreviaÃ§Ã£o do estado de redirecionamento:</t>
    <t id="9256">Abreviatura do estado de liberaÃ§Ã£o:</t>
    <t id="9257">Abreviatura do estado bloqueado:</t>
    <t id="9258">Abreviatura do estado substituto:</t>
    <t id="9259">Abreviatura de estado isolado:</t>
    <t id="9260">Abreviatura do estado de negociaÃ§Ã£o:</t>
    <t id="9261">Abreviatura do estado ocioso:</t>
    <t id="9262">AbreviaÃ§Ã£o do estado de fuga:</t>
    <t id="9268">Abreviatura de estado inacessÃ­vel:</t>
    <t id="9269">Abreviatura do estado do intercÃ¢mbio piloto:</t>
    <t id="9270">Tag de prefixo de lista negra personalizada:</t>
    <t id="9700">TRUQUES (partido. nao ha nada para ver aqui!! a serio!!)</t>
    <t id="9701">Naves GT invulneraveis</t>
    <t id="9702">Todas as naves do jogador invulneraveis</t>
    <t id="9800">Siga em frente, piloto. Ferramentas de teste partidas, nao um menu divertido. Nada para ver aqui. A serio. Foi avisado. Provavelmente.</t>
    <t id="9801">Naves com ordem GalaxyTrader nao podem cair abaixo de 100% de casco ou escudos. Clique novamente para desativar.</t>
    <t id="9802">Todas as naves do jogador nao podem cair abaixo de 100% de casco ou escudos. Clique novamente para desativar. Estacoes nao sao afetadas.</t>
    <t id="9703">Revelar universo para testes GT</t>
    <t id="9704">Revelado</t>
    <t id="9705">Revelar</t>
    <t id="9803">Revela a nevoa de guerra de todos os setores, marca todas as estacoes como conhecidas, concede todas as licencas de subscricao comercial e subscreve ofertas comerciais em toda a galaxia. Clique novamente apos novos setores DLC. Apenas para testes.</t>
    <t id="9706">Maximizar XP de pilotos GT registados</t>
    <t id="9707">Maximizado</t>
    <t id="9708">XP max</t>
    <t id="9804">Define nivel 15 e XP max para cada piloto no registo GT. Remove bloqueios de treino. Ignorado com apenas XP vanilla ativo. Apenas para testes.</t>
    <t id="9351">Abreviatura de estado de reabastecimento (padrÃ£o: RS)</t>
    <t id="9352">Abreviatura de Estado de reparo (padrÃ£o: RP)</t>
    <t id="9353">Abreviatura de Estado de manutenÃ§Ã£o (padrÃ£o: MT)</t>
    <t id="9354">Abreviatura de Estado de treinamento (padrÃ£o: TR)</t>
    <t id="9355">Abreviatura de estado de redirecionamento (padrÃ£o: RR)</t>
    <t id="9356">Abreviatura de Estado de liberaÃ§Ã£o (padrÃ£o: CL)</t>
    <t id="9357">Abreviatura de estado bloqueado (padrÃ£o: BL)</t>
    <t id="9358">Abreviatura de estado Fallback (padrÃ£o: FB)</t>
    <t id="9359">Abreviatura de estado isolado (padrÃ£o: IS)</t>
    <t id="9360">Abreviatura de estado de negociaÃ§Ã£o (padrÃ£o: TD)</t>
    <t id="9361">Abreviatura de estado inativo (padrÃ£o: ID)</t>
    <t id="9362">Abreviatura de Escape state (padrÃ£o: ES)</t>
    <t id="9367">Abreviatura de estado inacessÃ­vel (padrÃ£o: UR)</t>
    <t id="9368">Abreviatura de estado Pilot Exchange (padrÃ£o: PE)</t>
    <t id="9369">Mostrado como prefixo para navios MK3 afetados por uma lista negra de facÃ§Ã£o personalizada (incluindo subordinados). PadrÃ£o: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Comerciante de estaÃ§Ã£o - vende produtos de estaÃ§Ã£o para facÃ§Ãµes NPC</t>
    <t id="30010">EstaÃ§Ã£o inicial</t>
    <t id="30011">DistÃ¢ncia mÃ¡xima de venda</t>
    <t id="30012">Ignorar as regras comerciais</t>
    <t id="30013">Filtro de mercadorias</t>
    <t id="30014">Venda % de meta de preenchimento de carga</t>
    <t id="30015">TolerÃ¢ncia de retrocesso</t>
    <t id="30016">Comprar% de meta de preenchimento de carga</t>
    <t id="30017">Entradas no diÃ¡rio de bordo</t>
    <t id="30018">NÃ­vel de notificaÃ§Ã£o</t>
    <t id="30019">CoordenaÃ§Ã£o de Frota</t>
    <t id="30020">NÃ­vel de depuraÃ§Ã£o</t>
    <t id="30021">EstaÃ§Ã£o de abastecimento</t>
    <t id="30022">% mÃ­nimo de armazenamento da estaÃ§Ã£o</t>
    <t id="30023">Permitir produtos ilegais</t>
    <t id="30024">Carga/Lucro</t>
    <t id="30025">Permitir mÃºltiplas negociaÃ§Ãµes</t>
    <t id="30110">EstaÃ§Ã£o de jogador para vender produtos (atribuiÃ§Ã£o de estaÃ§Ã£o necessÃ¡ria)</t>
    <t id="30111">DistÃ¢ncia mÃ¡xima do portÃ£o para encontrar compradores NPC (limitada pela habilidade do piloto)</t>
    <t id="30112">Ignore as restriÃ§Ãµes comerciais da estaÃ§Ã£o - venda para qualquer facÃ§Ã£o amiga, independentemente das regras comerciais da estaÃ§Ã£o</t>
    <t id="30113">Filtro de louÃ§a opcional; deixe em branco para vender todos os produtos e mercadorias da estaÃ§Ã£o</t>
    <t id="30114">Porcentagem mÃ­nima de preenchimento de carga antes de partir em viagens de venda</t>
    <t id="30115">MÃ¡ximo de saltos extras permitidos ao adicionar um segundo produto a uma viagem (0 = somente compradores diretamente na rota)</t>
    <t id="30116">Abastecimento de carga alvo para operaÃ§Ãµes de abastecimento (alvo fÃ¡cil, o comerciante pode partir mais cedo)</t>
    <t id="30117">Habilitar entradas no diÃ¡rio de bordo por negociaÃ§Ã£o</t>
    <t id="30118">NÃ­vel de notificaÃ§Ã£o: 0=Silencioso, 1=Normal, 2=Detalhado</t>
    <t id="30119">Habilite a coordenaÃ§Ã£o da frota e o sistema de reservas comerciais</t>
    <t id="30120">NÃ­vel de registro de depuraÃ§Ã£o: 0=Desligado, 1=Normal, 2=Detalhado</t>
    <t id="30121">Quando habilitado, compre tambÃ©m recursos para a estaÃ§Ã£o. O fornecimento tem prioridade quando o armazenamento cai abaixo do limite mÃ­nimo</t>
    <t id="30122">Quando qualquer recurso cai abaixo desta percentagem do seu objectivo, a oferta tem prioridade sobre a venda. Ignorado se a estaÃ§Ã£o nÃ£o puder pagar os recursos</t>
    <t id="30123">Permitir a venda ou compra de produtos ilegais/contrabandeados, quando disponÃ­veis</t>
    <t id="30124">SeleÃ§Ã£o de venda: 1 = Carga (prioriza o maior enchimento do armazÃ©m por mercadoria; empates por lucro), 2 = Lucro (melhor pontuaÃ§Ã£o de lucro)</t>
    <t id="30125">Permite encadear vÃ¡rias vendas num ciclo (atÃ© 3 mercadorias ou destinos). Desative para ciclos com apenas uma negociaÃ§Ã£o</t>
    <t id="30200">Vendendo %1 %2 de %3 a %4</t>
    <t id="30201">Nenhum comprador encontrado para produtos de estaÃ§Ã£o em %1 saltos</t>
    <t id="30202">EstaÃ§Ã£o inicial %1 destruÃ­da - pedido do comerciante da estaÃ§Ã£o cancelado</t>
    <t id="30203">A estaÃ§Ã£o central %1 nÃ£o Ã© mais propriedade do jogador - pedido cancelado</t>
    <t id="30204">AtribuiÃ§Ã£o de estaÃ§Ã£o necessÃ¡ria - pedido cancelado</t>
    <t id="30205">MK1 Station Trader comeÃ§ou em %1</t>
    <t id="30206">Venda concluÃ­da: %1 %2 vendido para %3 por %4 Cr (lucro: %5 Cr)</t>
    <t id="30207">Viagem multimercadorias: entrega de %1 mercadorias para %2 destinos</t>
    <t id="30208">Fornecendo %1 %2 para %3 de %4</t>
    <t id="30500">GalaxyTrader MK1 ConfiguraÃ§Ãµes</t>
    <t id="30501">PadrÃµes do Comerciante de EstaÃ§Ã£o</t>
    <t id="30502">DistÃ¢ncia mÃ¡xima de venda padrÃ£o</t>
    <t id="30503">Alvo de preenchimento de carga de venda padrÃ£o</t>
    <t id="30504">PadrÃ£o Ignorar Regras Comerciais</t>
    <t id="30505">TolerÃ¢ncia de retrocesso padrÃ£o</t>
    <t id="30506">Tempo de espera quando nenhuma negociaÃ§Ã£o for encontrada</t>
    <t id="30507">Alvo de preenchimento de carga de compra padrÃ£o</t>
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">MineraÃ§Ã£o autÃ´noma com abastecimento de estaÃ§Ã£o e progressÃ£o XP</t>
    <t id="31010">EstaÃ§Ã£o inicial</t>
    <t id="31110">EstaÃ§Ã£o para minerar e entregar (mutuamente exclusivo com o Setor DomÃ©stico)</t>
    <t id="31011">Setor residencial</t>
    <t id="31111">Setor onde atuar; usado quando nenhum Home Station estÃ¡ definido</t>
    <t id="31012">Cesta de recursos</t>
    <t id="31112">Mercadorias para minar; vazio segue a resoluÃ§Ã£o da demanda da estaÃ§Ã£o</t>
    <t id="31013">EstaÃ§Ãµes alvo</t>
    <t id="31113">Filtro de estaÃ§Ã£o opcional para entregas; vazio deriva do contexto inicial</t>
    <t id="31014">Limite de estouro %</t>
    <t id="31114">As estaÃ§Ãµes iguais ou superiores a esse percentual de armazenamento sÃ£o tratadas como cheias.</t>
    <t id="31015">Permitir venda excessiva para terceiros</t>
    <t id="31115">Quando ativado e os alvos primÃ¡rios estiverem cheios, venda para estaÃ§Ãµes de outras facÃ§Ãµes</t>
    <t id="31016">Atribuir Ã  estaÃ§Ã£o</t>
    <t id="31116">Atribuir navio como subordinado de mineraÃ§Ã£o da EstaÃ§Ã£o Principal, quando aplicÃ¡vel</t>
    <t id="31017">Ficar em casa</t>
    <t id="31117">Restringir a mineraÃ§Ã£o/venda Ã  Ã¡rea de origem, exceto execuÃ§Ãµes de fallback de transbordamento</t>
    <t id="31018">Implantar automaticamente sondagens de recursos</t>
    <t id="31118">Implante testes de recursos carregados automaticamente e inclua testes no reabastecimento de manutenÃ§Ã£o</t>
    <t id="31019">DistÃ¢ncia mÃ¡xima de coleta</t>
    <t id="31119">DistÃ¢ncia mÃ¡xima do portÃ£o para coleta (0 usa o limite de habilidade do piloto/comandante)</t>
    <t id="31020">DistÃ¢ncia mÃ¡xima de venda</t>
    <t id="31120">DistÃ¢ncia mÃ¡xima do portÃ£o para venda (0 usa o limite de habilidade do piloto/comandante)</t>
    <t id="31021">Balanceamento de Frota</t>
    <t id="31121">Habilite a coordenaÃ§Ã£o de intenÃ§Ã£o determinÃ­stica para reduzir o excesso de estaÃ§Ã£o</t>
    <t id="31022">Intervalo de nova verificaÃ§Ã£o de demanda</t>
    <t id="31122">Com que frequÃªncia a avaliaÃ§Ã£o de demanda/troca do minerador Ã© executada</t>
    <t id="31023">Delta da Demanda CrÃ­tica</t>
    <t id="31123">Delta de urgÃªncia mÃ­nima necessÃ¡ria para trocar produtos de mineraÃ§Ã£o ativos</t>
    <t id="31024">Resfriamento mÃ­nimo do interruptor</t>
    <t id="31124">Tempo mÃ­nimo entre duas trocas de mercadorias para este navio</t>
    <t id="31025">% de comprometimento mÃ­nimo de carga</t>
    <t id="31125">Se o preenchimento da carga estiver acima disso, o navio prefere terminar a entrega atual antes da troca</t>
    <t id="31026">Delta de EmergÃªncia DifÃ­cil</t>
    <t id="31126">Delta de urgÃªncia que permite troca imediata apesar do limite de comprometimento de carga</t>
    <t id="31027">NÃ­vel de notificaÃ§Ã£o</t>
    <t id="31127">NÃ­vel de notificaÃ§Ã£o: 0=Silencioso, 1=Normal, 2=Detalhado</t>
    <t id="31028">Somente estaÃ§Ãµes de jogadores</t>
    <t id="31128">Quando ativado, apenas as estaÃ§Ãµes de propriedade do jogador sÃ£o consideradas alvos de demanda.</t>
    <t id="31031">Verificar demanda primeiro</t>
    <t id="31131">Quando ativado, o minerador verifica a demanda das estaÃ§Ãµes antes de minerar e prioriza os recursos em conformidade. Quando desativado, minera do cesto de recursos sem verificar a demanda e acumula atÃ© haver um comprador (recomendado para frotas de recurso Ãºnico).</t>
    <t id="31032">Abortar armazenamento fÃ­sico %</t>
    <t id="31132">Para pilotos nÃ­vel 6+: interrompe a extraÃ§Ã£o da mercadoria atual quando o estoque fÃ­sico da estaÃ§Ã£o mais a carga dos mineradores relevantes exceder o estoque fÃ­sico atual nesta percentagem. Usa quantidades reais de carga, nÃ£o o limiar de overflow. 0 = desativado.</t>
    <t id="32002">GalaxyTrader Fornecimento MK4</t>
    <t id="32102">Comerciante de fornecimento de estaÃ§Ã£o de jogador usando GT cache/pipeline de pesquisa ao vivo</t>
    <t id="32010">DistÃ¢ncia de cobertura</t>
    <t id="32110">DistÃ¢ncia mÃ¡xima do portÃ£o de casa para pesquisa de demanda de destino</t>
    <t id="32011">Comprar distÃ¢ncia</t>
    <t id="32111">DistÃ¢ncia mÃ¡xima do portÃ£o de casa para busca de fornecedores</t>
    <t id="32012">Servir apenas em casa</t>
    <t id="32112">Quando ativado, apenas a demanda do posto interno Ã© atendida</t>
    <t id="32013">Construir apenas estaÃ§Ãµes</t>
    <t id="32113">Quando ativado, apenas a demanda de armazenamento de build Ã© atendida</t>
    <t id="32014">Compre do jogador</t>
    <t id="32114">Permitir a aquisiÃ§Ã£o de produtos de fornecedores de propriedade dos jogadores</t>
    <t id="32015">Compre da facÃ§Ã£o</t>
    <t id="32115">Permitir a aquisiÃ§Ã£o de produtos de fornecedores de facÃ§Ãµes que nÃ£o sejam jogadores</t>
    <t id="32016">Permitir recursos</t>
    <t id="32116">Incluir recursos de recursos na correspondÃªncia de demanda</t>
    <t id="32017">Permitir intermediÃ¡rios</t>
    <t id="32117">Incluir produtos intermediÃ¡rios na correspondÃªncia de demanda</t>
    <t id="32018">Permitir produtos</t>
    <t id="32118">Incluir produtos na correspondÃªncia de demanda</t>
    <t id="32019">Permitir Tradewares</t>
    <t id="32119">Incluir produtos comerciais na correspondÃªncia de demanda</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">DistribuiÃ§Ã£o de armazÃ©m com gerenciamento de limite de armazenamento</t>
    <t id="20010">EstaÃ§Ãµes de origem</t>
    <t id="20011">EstaÃ§Ãµes de destino</t>
    <t id="20012">% de armazenamento mÃ­nimo</t>
    <t id="20013">% de armazenamento estÃ¡tico</t>
    <t id="20014">% de armazenamento mÃ¡ximo</t>
    <t id="20015">Filtro de mercadorias</t>
    <t id="20016">Modo Bidirecional</t>
    <t id="20017">EstaÃ§Ã£o inicial (opcional)</t>
    <t id="20018">DistÃ¢ncia mÃ¡xima</t>
    <t id="20032">Setor inicial (opcional)</t>
    <t id="20019">Tempo de espera do ciclo</t>
    <t id="20030">Permitir volume baixo</t>
    <t id="20031">% de piso de baixo volume</t>
    <t id="20110">Lista de estaÃ§Ãµes de origem para distribuiÃ§Ã£o de mercadorias</t>
    <t id="20111">Lista de estaÃ§Ãµes/armazÃ©ns de destino para distribuiÃ§Ã£o de mercadorias</t>
    <t id="20112">Limite de urgÃªncia do destino: estaÃ§Ãµes abaixo desta % de armazenamento recebem entregas prioritÃ¡rias</t>
    <t id="20113">Limite mÃ­nimo da fonte: a fonte deve ter mais do que esta% para distribuir</t>
    <t id="20114">Limite de estouro da fonte: acima desta % a fonte distribui atÃ© mesmo para destinos nÃ£o urgentes</t>
    <t id="20115">Filtro de louÃ§a opcional; deixe em branco para distribuir todos os produtos da fonte</t>
    <t id="20116">Habilitar coleta de viagem de volta dos destinos atÃ© a origem quando os destinos tiverem excesso</t>
    <t id="20117">EstaÃ§Ã£o interna opcional para atribuiÃ§Ã£o. Se estiver vazio, o navio permanece sem estaÃ§Ãµes atribuÃ­das.</t>
    <t id="20118">DistÃ¢ncia mÃ¡xima do portÃ£o entre origem e destino (0 = ilimitado)</t>
    <t id="20132">Setor inicial opcional usado para estacionamento em inatividade quando nenhuma estaÃ§Ã£o inicial estÃ¡ definida.</t>
    <t id="20119">Tempo de espera entre os ciclos de distribuiÃ§Ã£o</t>
    <t id="20130">Permitir entregas menores com consciÃªncia de urgÃªncia abaixo do preenchimento mÃ­nimo normal de carga.</t>
    <t id="20131">% mÃ­nima de preenchimento de carga usada quando o modo de baixo volume estÃ¡ ativado.</t>
    <t id="20200">Distribuindo %1 %2 de %3 para %4</t>
    <t id="20201">Viagem de volta: coleta de %1 %2 de %3 a %4</t>
    <t id="20202">NÃ£o Ã© necessÃ¡ria distribuiÃ§Ã£o - todos os destinos sÃ£o adequadamente abastecidos</t>
    <t id="20203">Todas as estacoes de origem sao invalidas - distribuicao em espera</t>
    <t id="20204">Todas as estacoes de destino sao invalidas - distribuicao em espera</t>
    <t id="20205">Estacao de origem %1 destruida - removida da ordem de distribuicao</t>
    <t id="20206">Estacao de destino %1 destruida - removida da ordem de distribuicao</t>
    <t id="20500">GalaxyTrader MK2 - ConfiguraÃ§Ãµes globais</t>
    <t id="20501">MK2 PadrÃµes de distribuiÃ§Ã£o</t>
    <t id="20510">% de armazenamento mÃ­nimo padrÃ£o</t>
    <t id="20511">% de armazenamento estÃ¡tico padrÃ£o</t>
    <t id="20512">% de armazenamento mÃ¡ximo padrÃ£o</t>
    <t id="20513">Espera(s) de ciclo padrÃ£o</t>
    <t id="20514">% de preenchimento mÃ­nimo de carga</t>
    <t id="20520">Verbosidade da notificaÃ§Ã£o</t>
    <t id="20521">NÃ­vel de depuraÃ§Ã£o</t>
    <t id="10006">Voltar para casa</t>
    <t id="10007">GalaxyTrader Fornecimento MK4-2</t>
    <t id="10106">Atraque na estaÃ§Ã£o de origem e permaneÃ§a lÃ¡ atÃ© que a negociaÃ§Ã£o seja retomada</t>
    <t id="10107">Ordem de fornecimento do jogador com controlos de prioridade do destino de entrega</t>
    <t id="30026">Voltar para casa entre os ciclos</t>
    <t id="30028">Ignorar definiÃ§Ãµes de ofertas</t>
    <t id="30029">Intervalo de preÃ§o do comprador</t>
    <t id="30027">% mÃ­n. armazenamento de produto</t>
    <t id="30126">Quando ativado, retorna Ã  estaÃ§Ã£o inicial e atraca entre os ciclos comerciais. Quando desativado, continue pesquisando a partir do local atual (comportamento legado)</t>
    <t id="30128">Permitir transferÃªncias internas de armazenamento sem ofertas de compra/venda da estaÃ§Ã£o. Usa troca de mercadorias para recolha e entrega do buffer. As regras comerciais da estaÃ§Ã£o continuam a aplicar-se quando Ignorar regras comerciais estÃ¡ desativado.</t>
    <t id="30129">PreÃ§o relativo mÃ­nimo para compradores NPC ao vender produtos da estaÃ§Ã£o. Controlo deslizante da ordem 0-200 (100 = mÃ©dia, 0 = -100%, 200 = +100%), mapeado para -1,0..+1,0. Mais alto = apenas compradores caros. Mais baixo = mais opÃ§Ãµes de compradores. Corridas de abastecimento usam o valor invertido para limites de preÃ§o de fornecedores.</t>
    <t id="30127">Percentual mÃ­nimo de preenchimento do armazenamento da estaÃ§Ã£o (em relaÃ§Ã£o ao mÃ¡ximo configurado por mercadoria) necessÃ¡rio antes de vender um produto ou mercadoria. Mercadorias abaixo deste limite sÃ£o ignoradas. 0 = sem mÃ­nimo.</t>
    <t id="3107">Enfileirando multitrade: %1. Eu deveria ganhar %2 de lucro.</t>
    <t id="3108">Vendendo %1 %2 de %3 a %4. Eu deveria ganhar %5 de lucro.</t>
    <t id="3110">Enfileirando abastecimento de %1 %2. AquisiÃ§Ã£o a %3 de %4, entrega em %5. Teto de compra do cliente %6 - %7/unidade abaixo do teto (%8 no total).</t>
    <t id="3111">Enfileirando abastecimento de %1 %2 de %3 para %4.</t>
    <t id="3112">Abastecimento na fila (%1 etapas): %2. Total %3 abaixo do teto de compra do cliente.</t>
    <t id="3113">Comerciante de estaÃ§Ã£o: exportaÃ§Ã£o multitrade na fila: %1. Lucro esperado %2.</t>
    <t id="31029">Alvo de estoque de sonda</t>
    <t id="31030">Drones de mineraÃ§Ã£o para comprar</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: nenhuma matÃ©ria minÃ¡vel disponÃ­vel. Nave %1 [%2], Frota: %3</t>
    <t id="31201">Galaxy-Miner: defina a estaÃ§Ã£o inicial ou a posiÃ§Ã£o inicial.</t>
    <t id="31130">Quantos drones coletores (de mineraÃ§Ã£o) o minerador compra quando fica sem o tipo necessÃ¡rio (sÃ³lido/minÃ©rio ou lÃ­quido/gÃ¡s). A compra Ã© acionada SOMENTE quando o navio nÃ£o tem coletores desse tipo - um minerador que ainda tem pelo menos um nunca Ã© reabastecido ou comprado novamente, e os drones existentes sÃ£o mantidos. Limitado pela capacidade do compartimento de unidades do navio. Defina como 0 para desativar a compra automÃ¡tica de drones coletores e gerenciar os drones manualmente. O padrÃ£o 5 Ã© um conjunto completo de drones para velocidade de mineraÃ§Ã£o normal.</t>
    <t id="31129">NÃºmero de sondas de recursos que o minerador compra por viagem de reabastecimento. A compra Ã© acionada SOMENTE quando o navio fica sem sondas (contagem = 0), nÃ£o em cada implantaÃ§Ã£o - dessa forma, o minerador executa toda a sua carga de sonda entre as execuÃ§Ãµes de abastecimento, em vez de desviar apÃ³s cada implantaÃ§Ã£o. Limitado pela capacidade total destacÃ¡vel do navio (compartilhada com satÃ©lites/minas/etc); um valor do controle deslizante maior que o espaÃ§o livre implantÃ¡vel Ã© degradado normalmente para "preencher o que cabe". SÃ³ entra em vigor quando a implantaÃ§Ã£o automÃ¡tica de sondas de recursos estÃ¡ habilitada - a mesma configuraÃ§Ã£o tambÃ©m impulsiona a implantaÃ§Ã£o de sondas oportunistas em setores de mineraÃ§Ã£o e a coleta de sondas obsoletas (investigaÃ§Ãµes em setores sem recursos relevantes para a cesta).</t>
    <t id="3226">Comandante %1,\n\nAtraquei em %2 e o registrador da Trading Academy confirmou minha inscriÃ§Ã£o no programa "%3". A conta da frota foi debitada em %4 Cr referente ao valor do curso, e nÃ£o considero esse investimento levianamente.\n\nEsta nÃ£o Ã© uma certificaÃ§Ã£o de rotina. Os instrutores da academia sÃ£o comerciantes veteranos e negociadores de consÃ³rcios, e o currÃ­culo aqui Ã© muito mais exigente do que o exame de avanÃ§o padrÃ£o. Nos prÃ³ximos %5 minutos, passarei por instruÃ§Ãµes intensivas sobre protocolos de negociaÃ§Ã£o avanÃ§ados, anÃ¡lise de mercado sob pressÃ£o e tÃ¡ticas de negociaÃ§Ã£o que separam os aprendizes dos mestres.\n\nQuando o exame final for concluÃ­do e eu desencaixar, manterei o tÃ­tulo de "%3" e trarei tudo o que aprendi de volta Ã s nossas operaÃ§Ãµes de negociaÃ§Ã£o. NÃ£o desperdiÃ§arei um Ãºnico crÃ©dito desta oportunidade.\n\nCom gratidÃ£o e determinaÃ§Ã£o,\n%6\nA bordo do %7</t>
    <t id="9924">Curso da Trading Academy abortado: o piloto %1 nÃ£o pode pagar a taxa de %2 Cr na doca da academia (tem %3 Cr). Curso cancelado, piloto retoma a negociaÃ§Ã£o.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="81">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">ãƒ‰ãƒƒã‚¯ã—ã¦å¾…æ©Ÿ (GalaxyTrader MK3)</t>
    <t id="10002">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼MK3</t>
    <t id="10003">æœ€çµ‚è©¦é¨“ï¼ˆGalaxyTrader MK3ï¼‰</t>
    <t id="10004">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆäº¤æ›ãƒ©ãƒ³ãƒ‡ãƒ–ãƒ¼</t>
    <t id="10005">[éžæŽ¨å¥¨] GalaxyTrader MK4 ä¾›çµ¦ï¼ˆãƒ¬ã‚¬ã‚·ãƒ¼ï¼‰</t>
    <t id="10101">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«ãƒ‰ãƒƒã‚­ãƒ³ã‚°ã—ã€æŒ‡å®šã•ã‚ŒãŸæœŸé–“å¾…æ©Ÿã—ã¾ã™</t>
    <t id="10102">ã‚¹ã‚­ãƒ«ã®é€²æ­©ã«ã‚ˆã‚‹è‡ªå¾‹å–å¼•</t>
    <t id="10103">è¨“ç·´æ–½è¨­ã§ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆè³‡æ ¼ã®æœ€çµ‚è©¦é¨“ã‚’å—ã‘ã‚‹</t>
    <t id="10104">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆäº¤æ›ã®ãŸã‚ãƒ©ãƒ³ãƒ‡ãƒ–ãƒ¼ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«åœæ³Š</t>
    <t id="10105">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã¨ãƒ©ã‚¤ãƒ–æ¤œç´¢ã‚’ä½¿ç”¨ã—ãŸãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ä¾›çµ¦é‡è¦–ã®å–å¼•ï¼ˆãƒ¬ã‚¬ã‚·ãƒ¼ï¼‰</t>
    <t id="10201">%s ã‹ã‚‰ %s ã‚’è³¼å…¥</t>
    <t id="10202">%s ã‚’ %s ã«è²©å£²ã—ã¾ã™</t>
    <t id="10203">%s ã¨å–å¼•ã™ã‚‹</t>
    <t id="1000">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼MK3</t>
    <t id="1001">XPã®é€²è¡Œã¨ãƒ•ãƒªãƒ¼ãƒˆã®èª¿æ•´ã‚’å‚™ãˆãŸé«˜åº¦ãªå–å¼•ã‚·ã‚¹ãƒ†ãƒ </t>
    <t id="1002">ãƒ›ãƒ¼ãƒ ãƒ™ãƒ¼ã‚¹</t>
    <t id="1003">ãƒ—ãƒªã‚»ãƒƒãƒˆã‚’ä½¿ç”¨ã™ã‚‹</t>
    <t id="1004">ã™ã¹ã¦ã®å•†å“ã‚’å–å¼•ã™ã‚‹</t>
    <t id="1005">åˆæ³•çš„ãªå•†å“ã‚’å–å¼•ã™ã‚‹</t>
    <t id="1006">é•æ³•å•†å“ã®å–å¼•</t>
    <t id="1007">XPã®é€²è¡Œã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="1008">ãƒ•ãƒªãƒ¼ãƒˆã®èª¿æ•´ã‚’å¯èƒ½ã«ã™ã‚‹</t>
    <t id="1009">å¸‚å ´åˆ†æžã‚’å¯èƒ½ã«ã™ã‚‹</t>
    <t id="1010">ãƒ†ãƒªãƒˆãƒªãƒ¼ç®¡ç†ã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="1011">é•æ³•å•†å“ã®è¨±å¯</t>
    <t id="1012">ãƒ­ã‚°ãƒ–ãƒƒã‚¯ã®ã‚¨ãƒ³ãƒˆãƒª</t>
    <t id="1013">ãƒªã‚¹ã‚¯è¨±å®¹åº¦</t>
    <t id="1014">ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’å„ªå…ˆã™ã‚‹</t>
    <t id="1015">è‡ªå‹•é¸æŠžå•†å“</t>
    <t id="1016">è·é›¢ãƒšãƒŠãƒ«ãƒ†ã‚£%</t>
    <t id="1017">é€šçŸ¥ãƒ¬ãƒ™ãƒ«</t>
    <t id="1018">è‰¦éšŠèª¿æ•´</t>
    <t id="1019">è²¨ç‰©å……å¡«ç›®æ¨™%</t>
    <t id="1050">å¸‚å ´ã®æ›´æ–°é »åº¦</t>
    <t id="1051">å–å¼•è©•ä¾¡ã®ãƒ­ã‚°è¨˜éŒ²</t>
    <t id="1052">ã‚»ã‚¯ã‚¿ãƒ¼ã®ãƒ›ãƒ¯ã‚¤ãƒˆãƒªã‚¹ãƒˆ</t>
    <t id="1054">ç©ºæ¯/è£œåŠ©èˆ¹ã‚’ç„¡è¦–ã™ã‚‹</t>
    <t id="1056">ãƒ“ãƒ«ãƒ‰ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã‚’ç„¡è¦–ã™ã‚‹</t>
    <t id="1058">è²¿æ˜“ãƒ«ãƒ¼ãƒ«ã‚’ç„¡è¦–ã™ã‚‹</t>
    <t id="1060">MK1 ãŒæä¾›ã™ã‚‹ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’ç„¡è¦–ã™ã‚‹</t>
    <t id="1063">é–‹ç™ºä¸­</t>
    <t id="1064">å„ªå…ˆå•†å“</t>
    <t id="1065">å„ªå…ˆã‚¹ã‚³ã‚¢ %</t>
    <t id="1066">ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚¹â€‹â€‹ã‚³ã‚¢ãƒªãƒ³ã‚°ã«æœ‰åˆ©ãªã‚¦ã‚§ã‚¢ã€‚å½¼ã‚‰ã®ã‚¹ã‚³ã‚¢ã«ã¯å„ªå…ˆåº¦ã‚¹ã‚³ã‚¢ % ãŒä¹—ç®—ã•ã‚Œã¾ã™ã€‚</t>
    <t id="1067">å„ªå…ˆã‚¦ã‚§ã‚¢ã®ã‚¹ã‚³ã‚¢å€çŽ‡: 100%=é€šå¸¸ã€150%=+50%%ã€200%=2xã€300%=3xã€‚æœ€å¾Œã«é©ç”¨ã•ã‚Œã¾ã—ãŸã€‚</t>
    <t id="1068">â”€â”€ å„ªå…ˆã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ â”€â”€</t>
    <t id="1069">ã‚¦ã‚§ã‚¢ï¼ˆæ‰‹å‹•ï¼‰</t>
    <t id="1070">ä¸æ­£ãƒ«ãƒ¼ãƒˆãƒ•ã‚£ãƒ«ã‚¿ãƒ¼</t>
    <t id="1072">è‡ªå®…ã®ã¿ã§æä¾›</t>
    <t id="1073">ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼å„ªå…ˆåº¦</t>
    <t id="1074">ãƒ•ã‚¡ã‚¯ã‚·ãƒ§ãƒ³ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼å„ªå…ˆåº¦</t>
    <t id="1075">ãƒ“ãƒ«ãƒ‰ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã‚’å«ã‚ã‚‹</t>
    <t id="1076">ãƒªã‚½ãƒ¼ã‚¹ã‚’å«ã‚ã‚‹</t>
    <t id="1077">ä¸­é–“ä½“ã‚’å«ã‚€</t>
    <t id="1078">ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‚’å«ã‚€</t>
    <t id="1080">ã‚µã‚¤ã‚¯ãƒ«ã”ã¨ã®æœ€å¤§å–å¼•æ•°</t>
    <t id="1081">ãƒãƒƒã‚¯ãƒˆãƒ©ãƒƒã‚¯è¨±å®¹åº¦</t>
    <t id="1082">æœ€å°ä½¿ç”¨è²¨ç‰©%</t>
    <t id="1083">ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã®è³¼å…¥ãƒ¢ãƒ‡ã‚£ãƒ•ã‚¡ã‚¤ã‚¢ %</t>
    <t id="1085">ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«å‰²ã‚Šå½“ã¦ã‚‹</t>
    <t id="1086">åˆ°é”è·é›¢</t>
    <t id="1088">éœ€è¦ã‚’ã‚«ãƒãƒ¼ã™ã‚‹ãŸã‚ã®è‡ªå®…ã‹ã‚‰ã®æœ€å¤§ã‚¸ãƒ£ãƒ³ãƒ—è·é›¢</t>
    <t id="1090">éœ€è¦ã¨ä¾›çµ¦ã®ãƒžãƒƒãƒãƒ³ã‚°ã«ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‚¯ãƒ©ã‚¹ã®å•†å“ã‚’å«ã‚ã‚‹</t>
    <t id="1091">ã‚¹ã‚³ã‚¢ã®ã¿ã®è¨ˆç®—ã§ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼æ‰€æœ‰ã®ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼ã®ä¾¡æ ¼è¨­å®šã«é©ç”¨ã•ã‚Œã‚‹ä¿®é£¾å­</t>
    <t id="1092">ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã®ä¾¡æ ¼è¨­å®šã‚’ç„¡è¦–ã™ã‚‹</t>
    <t id="1093">æœ‰åŠ¹ãªå ´åˆ: è¨­å®šã•ã‚ŒãŸè²©å£²ä¾¡æ ¼ã«é–¢ä¿‚ãªãã€å¸¸ã«ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼æ‰€æœ‰ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‹ã‚‰è³¼å…¥ã—ã€NPC å‹¢åŠ›ã«ã®ã¿è²©å£²ã—ã¾ã™ã€‚è‡ªç¤¾ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ä½™å‰°åœ¨åº«ã‚’æ•´ç†ã™ã‚‹ã®ã«ä¾¿åˆ©ã§ã™ã€‚</t>
    <t id="1094">ãƒ–ãƒ­ãƒƒã‚¯ã™ã‚‹ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³</t>
    <t id="1095">ã“ã“ã§é¸æŠžã—ãŸã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¯MK3äº¤æ˜“ã‹ã‚‰é™¤å¤–ã•ã‚Œã¾ã™ã€‚ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã¯ãã‚Œã‚‰ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã§è³¼å…¥ã‚‚è²©å£²ã‚‚ã—ã¾ã›ã‚“ã€‚</t>
    <t id="1096">å¾…æ©Ÿæ™‚ãƒ‘ãƒ¼ã‚­ãƒ³ã‚°</t>
    <t id="1097">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€ä»•äº‹ã‚’ç¹°ã‚Šè¿”ã—è¦‹ã¤ã‘ã‚‰ã‚Œãªã‹ã£ãŸè‰¦èˆ¹ã¯ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¾ãŸã¯ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã«é€€é¿ã—ã¾ã™ã€‚ã‚»ã‚¯ã‚¿ãƒ¼é€€é¿ã§ã¯ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼æ‰€æœ‰ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’å„ªå…ˆã—ã€æ¬¡ã«å‹å¥½ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’é¸ã³ã¾ã™ã€‚ãƒ‰ãƒƒã‚¯è§£é™¤æ™‚é–“ã¯ã‚°ãƒ­ãƒ¼ãƒãƒ«è¨­å®šã§æŒ‡å®šã—ã¾ã™ï¼ˆ0 = ä»•äº‹ãŒè¦‹ã¤ã‹ã‚‹ã¾ã§ãƒ‰ãƒƒã‚¯ã«ç•™ã¾ã‚‹ï¼‰ã€‚</t>
    <t id="1098">è‡ªå‹•ã‚¹ã‚±ãƒ¼ãƒ«</t>
    <t id="1099">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€å¿…é ˆè¨“ç·´ã¾ãŸã¯ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼ä¿®äº†å¾Œã«ã€ã‚¸ãƒ£ãƒ³ãƒ—è·é›¢ã‚¹ãƒ©ã‚¤ãƒ€ãƒ¼ãŒãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®æœ€å¤§è¨±å®¹ç¯„å›²ã«è¨­å®šã•ã‚Œã¾ã™ã€‚æ‰‹å‹•ã§è·é›¢ã‚’è¨­å®šã™ã‚‹å ´åˆã¯ã‚ªãƒ•ã«ã—ã¦ãã ã•ã„ã€‚</t>
    <t id="11001">å»ºé€ ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸å„ªå…ˆåº¦</t>
    <t id="11002">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³å„ªå…ˆåº¦</t>
    <t id="11003">è£œåŠ©è‰¦å„ªå…ˆåº¦</t>
    <t id="11004">ç©ºæ¯å„ªå…ˆåº¦</t>
    <t id="11005">0 = ç„¡åŠ¹ã€‚1-10 = ã‚¹ã‚³ã‚¢å€çŽ‡ï¼ˆ10 = æœ€å¤§ã®é‡ã¿ï¼‰ã€‚æœ€çµ‚ã‚¹ã‚³ã‚¢ = ä¾›çµ¦ã‚¹ã‚³ã‚¢ Ã— å€çŽ‡ã€‚</t>
    <t id="11006">1 = è¿½åŠ ã‚¹ã‚³ã‚¢ãªã—ï¼ˆå„ªå…ˆç‰©è³‡ãƒªã‚¹ãƒˆã¯å¤‰æ›´ãªã—ï¼‰ã€‚2-10 = å–å¼•ç‰©è³‡ãŒå„ªå…ˆãƒªã‚¹ãƒˆã«ã‚ã‚‹å ´åˆã€(å€çŽ‡âˆ’1)Ã— åŸºæœ¬ä¾›çµ¦ã‚¹ã‚³ã‚¢ã‚’åŠ ç®—ã€‚ã‚¿ã‚¤ãƒ—ã‚¹ã‚³ã‚¢ã«ä¸Šä¹—ã›ã€‚</t>
    <t id="11007">å„ªå…ˆç‰©è³‡ãƒœãƒ¼ãƒŠã‚¹</t>
    <t id="11008">%1ï¼šé…é€å…ˆå„ªå…ˆåº¦ã‚¹ãƒ©ã‚¤ãƒ€ãƒ¼ãŒã™ã¹ã¦0ã«è¨­å®šã•ã‚Œã¦ã„ã¾ã™ã€‚ã“ã®å‘½ä»¤ã«ã¯é…é€å…ˆãŒã‚ã‚Šã¾ã›ã‚“ã€‚ä¾›çµ¦ã‚’å†é–‹ã™ã‚‹ã«ã¯ã€å°‘ãªãã¨ã‚‚1ã¤ã®ã‚¯ãƒ©ã‚¹ï¼ˆå»ºè¨­ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã€ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã€è£œåŠ©è‰¦ã€ã‚­ãƒ£ãƒªã‚¢ï¼‰ã‚’æœ‰åŠ¹ã«ã—ã¦ãã ã•ã„ã€‚</t>
    <t id="7001">[å‰é€²]</t>
    <t id="7002">[ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°]</t>
    <t id="7008">[å¾Œé€€ã™ã‚‹]</t>
    <t id="7009">[å­¤ç«‹]</t>
    <t id="7003">[ä¿®ç†]</t>
    <t id="7004">ã€è£œçµ¦ã€‘</t>
    <t id="7005">[ãƒ¡ãƒ³ãƒ†ãƒŠãƒ³ã‚¹]</t>
    <t id="7006">[ãƒ«ãƒ¼ãƒˆå¤‰æ›´]</t>
    <t id="7007">[ã‚¯ãƒªã‚¢ãƒ©ãƒ³ã‚¹]</t>
    <t id="1020">ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ãŒæ´»å‹•ã™ã‚‹å›½å†…éƒ¨é–€ã¾ãŸã¯ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’é¸æŠžã—ã¦ãã ã•ã„</t>
    <t id="1021">å•†å“è³¼å…¥æ™‚ã®æœ€å¤§ã‚¸ãƒ£ãƒ³ãƒ—ã‚²ãƒ¼ãƒˆè·é›¢ï¼ˆãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ã«ã‚ˆã£ã¦åˆ¶é™ã•ã‚Œã¾ã™ï¼‰</t>
    <t id="1022">å•†å“è²©å£²æ™‚ã®æœ€å¤§ã‚¸ãƒ£ãƒ³ãƒ—ã‚²ãƒ¼ãƒˆè·é›¢ï¼ˆãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚¹ã‚­ãƒ«ã«ã‚ˆã‚Šåˆ¶é™ã‚ã‚Šï¼‰</t>
    <t id="1023">ã‚«ãƒ†ã‚´ãƒªã«åŸºã¥ã„ã¦é©åˆ‡ãªå•†å“ã‚’è‡ªå‹•é¸æŠž</t>
    <t id="1024">ç‰¹å®šã®å–å¼•å•†å“ã®æ‰‹å‹•é¸æŠž</t>
    <t id="1025">å¯†è¼¸å“ã‚„é•æ³•å•†å“ã®å–å¼•ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="1026">ã‚»ã‚­ãƒ¥ãƒªãƒ†ã‚£è¨±å®¹åº¦: 0.0=å®‰å…¨ãªã‚»ã‚¯ã‚¿ãƒ¼ã®ã¿ã€1.0=ã™ã¹ã¦ã®ãƒªã‚¹ã‚¯ã‚’å—ã‘å…¥ã‚Œã‚‹</t>
    <t id="1027">å–å¼•çµŒé¨“ã‚’é€šã˜ã¦ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚¹ã‚­ãƒ«ã‚’å‘ä¸Šã•ã›ã‚‹</t>
    <t id="1028">å¿…è¦ã«å¿œã˜ã¦ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã®ãŸã‚ã«è‡ªå‹•çš„ã«é€ä¿¡ã—ã¾ã™</t>
    <t id="1029">è¤‡æ•°ã®è²¿æ˜“èˆ¹ã‚’èª¿æ•´ã—ã¦è¡çªã‚’å›žé¿ã™ã‚‹</t>
    <t id="1030">ã‚¦ã‚§ã‚¢ã®ç„¦ç‚¹: 0=ãƒãƒ©ãƒ³ã‚¹ã®å–ã‚ŒãŸã€1=é«˜åº¦ãªã€2=åŸºæœ¬çš„ãªãƒ‹ãƒ¼ã‚ºã€3=é•æ³•ã€4=ãƒãƒ«ã‚¯å“</t>
    <t id="1031">å–å¼•ã‚¨ãƒªã‚¢: 0=ãƒãƒ©ãƒ³ã‚¹ã€1=ãƒ›ãƒ¼ãƒ ãƒ•ã‚©ãƒ¼ã‚«ã‚¹ã€2=ãƒ•ãƒªãƒ¼ãƒ­ãƒ¼ãƒŸãƒ³ã‚°</t>
    <t id="1032">é€šçŸ¥ãƒ¬ãƒ™ãƒ«: 0=æœ€å°é™ã€1=é€šå¸¸ã€2=è©³ç´°ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸</t>
    <t id="1033">è²©å£²ã‚’å„ªå…ˆã™ã‚‹å‰ã«è²¨ç‰©åˆ©ç”¨çŽ‡ã‚’ç›®æ¨™ã«ã™ã‚‹</t>
    <t id="1034">å¸‚å ´ãƒ‡ãƒ¼ã‚¿ã¨ä¾¡æ ¼æƒ…å ±ãŒæ›´æ–°ã•ã‚Œã‚‹é »åº¦</t>
    <t id="1035">ãƒ‡ãƒãƒƒã‚°å‡ºåŠ›ãƒ¬ãƒ™ãƒ«: 0=ãªã—ã€1=åŸºæœ¬ã€2=è©³ç´°ãƒ­ã‚°</t>
    <t id="1036">åŽç›Šæ€§ã®é«˜ã„äº¤æ˜“ãƒ«ãƒ¼ãƒˆã‚’ãƒ•ãƒªãƒ¼ãƒˆã¨å…±æœ‰ã—ã¾ã™ï¼ˆã™ãã«ã‚¢ã‚¯ã‚»ã‚¹ã§ãã‚‹ã‚ˆã†ã«ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚Œã¦ã„ã¾ã™ï¼‰</t>
    <t id="1037">å–å¼•ã‚’ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã—ã¦ãƒ•ãƒªãƒ¼ãƒˆã¨å…±æœ‰ã™ã‚‹ãŸã‚ã«å¿…è¦ãªæœ€å°é™ã®åˆ©ç›Š</t>
    <t id="1038">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚ŒãŸäº¤æ˜“ãƒ«ãƒ¼ãƒˆãŒç„¡åŠ¹ã«ãªã‚‹å‰ã«è¨±å®¹ã•ã‚Œã‚‹æœ€å¤§ã®åˆ©ç›Šæ¸›å°‘</t>
    <t id="1039">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚ŒãŸè²¿æ˜“ãƒ«ãƒ¼ãƒˆãŒæœŸé™åˆ‡ã‚Œã«ãªã‚‹ã¾ã§ã®æœ‰åŠ¹æœŸé–“</t>
    <t id="1040">å€‹ã€…ã®å–å¼•ã®è©•ä¾¡ã¨æ‹’å¦ã®è©³ç´°ãªãƒ­ã‚°ã‚’æœ‰åŠ¹ã«ã—ã¾ã™ (éžå¸¸ã«å†—é•·ã«ãªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™)</t>
    <t id="1041">å–å¼•ã”ã¨ã®ãƒ­ã‚°ãƒ–ãƒƒã‚¯ã®ã‚¨ãƒ³ãƒˆãƒªã¨æ²¡å…¥åž‹ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚° ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã‚’æœ‰åŠ¹ã«ã™ã‚‹ (TaterTrader ã‚¹ã‚¿ã‚¤ãƒ«)</t>
    <t id="1053">ã“ã®ãƒªã‚¹ãƒˆå†…ã®ã‚»ã‚¯ã‚¿ãƒ¼ã¯ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‹ã‚‰é™¤å¤–ã•ã‚Œã¾ã™ (å¸¸ã«è¨±å¯ã•ã‚Œã¾ã™)</t>
    <t id="1055">ç©ºæ¯ã¨è£œåŠ©èˆ¹ã‚’å–å¼•ã‹ã‚‰é™¤å¤–ã™ã‚‹</t>
    <t id="1057">å»ºé€ å€‰åº«èˆ¹ã‚’å–å¼•ã‹ã‚‰é™¤å¤–ã™ã‚‹</t>
    <t id="1059">ã‚ªãƒ•ã‚¡ãƒ¼æ¤œç´¢ä¸­ã«ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å–å¼•ãƒ«ãƒ¼ãƒ«ã‚’ç„¡è¦–ã—ã¾ã™ (ä¸Šç´šè€…; é€šå¸¸ã¯ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¦ã„ã‚‹ã‚ªãƒ•ã‚¡ãƒ¼ã‚’é¸æŠžã§ãã¾ã™)</t>
    <t id="1061">ä¾›çµ¦ãƒ¢ãƒ¼ãƒ‰ãŒå‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¦ã„ã‚‹ MK1 ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã‚’æŒã¤ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’ã‚¹ã‚­ãƒƒãƒ—ã—ã¾ã™</t>
    <t id="1062">è‡ªåˆ†ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’å«ã‚€ãƒ«ãƒ¼ãƒˆã®è²¿æ˜“ã‚¹ã‚³ã‚¢ã‚’ãƒ–ãƒ¼ã‚¹ãƒˆã—ã¾ã™ (10% ã®ã‚¹ã‚³ã‚¢ãƒœãƒ¼ãƒŠã‚¹)</t>
    <t id="1071">[é•æ³•å•†å“ã®è¨±å¯] ãŒæœ‰åŠ¹ã«ãªã£ã¦ã„ã‚‹å ´åˆã€ã‚¸ãƒ£ãƒ³ãƒ— ãƒ‘ã‚¹ä¸Šã®ã™ã¹ã¦ã®ã‚»ã‚¯ã‚¿ãƒ¼ (è²·ã„ã€å£²ã‚Šã€ä¸­é–“ã‚»ã‚¯ã‚¿ãƒ¼) ã§åˆæ³•ã§ã‚ã‚‹å ´åˆã«ã®ã¿ã€é•æ³•å•†å“ã‚’å–å¼•ã—ã¾ã™ã€‚</t>
    <t id="1087">ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼è³¼å…¥æ¤œç´¢ã®ãŸã‚ã®è‡ªå®…ã‹ã‚‰ã®æœ€å¤§ã‚¸ãƒ£ãƒ³ãƒ—è·é›¢</t>
    <t id="1089">ç„¡åŠ¹ã«ã™ã‚‹ã¨ã€èˆ¹èˆ¶ã¯è‡ªå®…å°‚ç”¨ãƒ¢ãƒ¼ãƒ‰ã§ã¯ãªãç·Šæ€¥å„ªå…ˆã§ã‚«ãƒãƒ¬ãƒƒã‚¸ã‚¨ãƒªã‚¢å†…ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«ä¾›çµ¦ã§ãã‚‹ã‚ˆã†ã«ãªã‚Šã¾ã™ã€‚</t>
    <t id="2000">%s ã¯ %s XP ã‚’ç²å¾—ã—ã¾ã—ãŸ!</t>
    <t id="2001">%s ãŒãƒ¬ãƒ™ãƒ«ã‚¢ãƒƒãƒ—ã—ã¾ã—ãŸ!æ–°ã—ã„ãƒ¬ãƒ™ãƒ«: %s</t>
    <t id="2002">%s ã«ã¯ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ãŒå¿…è¦ã§ã™!æœ€å¯„ã‚Šã®é€ èˆ¹æ‰€ã¾ãŸã¯è²¿æ˜“ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«é€ã£ã¦ãã ã•ã„ã€‚</t>
    <t id="2003">%s ã¯ %s ã§ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã‚’é–‹å§‹ã—ã¾ã—ãŸ</t>
    <t id="2004">%s ã¯ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã‚’å®Œäº†ã—ã€ãƒ¬ãƒ™ãƒ« %s ã®èªå®šã‚’å—ã‘ã¾ã—ãŸã€‚</t>
    <t id="2005">%s ã¯ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°å¾Œã«ã‚¹ã‚­ãƒ«ãƒ¬ãƒ™ãƒ« %s ã«åˆ°é”ã—ã¾ã—ãŸï¼%s ã§XPé€²è¡ŒãŒè§£é™¤ã•ã‚Œã¾ã—ãŸã€‚</t>
    <t id="2006">%s ã¯ã‚¹ã‚­ãƒ«ãƒ¬ãƒ™ãƒ« %s ã« %s ã®å–å¼•ã§åˆ°é”ã—ã¾ã—ãŸï¼</t>
    <t id="2007">%s ã¯ãƒ¬ãƒ™ãƒ« %s ã®ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã‚’å®Œäº†ã—ã¾ã—ãŸï¼%s ã§XPé€²è¡ŒãŒè§£é™¤ã•ã‚Œã¾ã—ãŸã€‚</t>
    <t id="3000">%s ãŒå–å¼•ã‚’å®Œäº†ã—ã¾ã—ãŸã€‚åˆ©ç›Š: %s Cr</t>
    <t id="3001">%s ã¯å¸‚å ´çŠ¶æ³ã‚’åˆ†æžã—ã¦ã„ã¾ã™...</t>
    <t id="3002">%s ã¯æœ‰ç›Šãªäº¤æ˜“ãƒ«ãƒ¼ãƒˆã‚’ç™ºè¦‹ã—ã¾ã—ãŸ!</t>
    <t id="3003">%s ã«ã¯æœ‰ç›Šãªè²¿æ˜“ãƒ«ãƒ¼ãƒˆãŒã‚ã‚Šã¾ã›ã‚“</t>
    <t id="3100">%1 %2 ã‚’ %3 ã¸ %4 ã§è²¨ç‰©ã‹ã‚‰è²©å£²ã—ã¾ã™ã€‚ %5 ã®åˆ©ç›Šã‚’å¾—ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚</t>
    <t id="3101">%1 %2 ã®å–å¼•æ³¨æ–‡ã‚’ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã¦ã„ã¾ã™ã€‚ %3 ã§ %4 ã‹ã‚‰è³¼å…¥ã—ã€%5 ã§ %6 ã¸è²©å£²ã—ã¾ã™ã€‚ %7 ã®åˆ©ç›Šã‚’å¾—ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚</t>
    <t id="3102">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãƒ»ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ï¼š%3ï¼ˆ%5%%ï¼‰ã‹ã‚‰ %4ï¼ˆ%6%%ï¼‰ã¸ %1 %2 ã‚’ä¾›çµ¦ä¸­ã€‚</t>
    <t id="3103">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼: %1 %2 ã‚’ %3 ã« %4 ã§è²©å£²ã—ã¾ã™ã€‚äºˆæƒ³åˆ©ç›Šã¯ %5 ã§ã™ã€‚</t>
    <t id="3104">%1 %2 ã®å–å¼•ãŒæ­£å¸¸ã«å®Œäº†ã—ã¾ã—ãŸã€‚ç·åˆ©ç›Š: %3 ã‚¯ãƒ¬ã‚¸ãƒƒãƒˆã€‚</t>
    <t id="3105">Trade route cached: %1 %2 from %3 to %4 (Profit: %5 Cr)</t>
    <t id="3106">\nã“ã®å–å¼•å‰ã®æŽ¨å®šç”Ÿæ¶¯åˆ©ç›Šã®åˆè¨ˆ: %1 Cr.</t>
    <t id="3120">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆè»¢é€ãŒé–‹å§‹ã•ã‚Œã¾ã—ãŸ</t>
    <t id="3121">è»¢é€ãƒ—ãƒ­ãƒˆã‚³ãƒ«ãŒèªè­˜ã•ã‚Œã¾ã—ãŸã€‚ %1 (%2) ã¨ %3 (%4) ã¯ãƒ‰ãƒƒã‚­ãƒ³ã‚°ã—ã¦æŒ‡æ®å¸­ã‚’äº¤æ›ã™ã‚‹ãŸã‚ã« %5 (%6) ã«å‘ã‹ã£ã¦ã„ã¾ã™ã€‚</t>
    <t id="3200">Hello Commander %1,\n\nI have gained enough experience to take my certification exam for the title "%2". The examination will take approximately %3 minutes at %4.\n\nThis is an important milestone in my career development. The exam will test my knowledge of advanced trading protocols, market analysis, and fleet coordination procedures.\n\nI'm confident in my abilities and excited to prove myself worthy of this advancement. Wish me luck!\n\nRespectfully,\n%5\nAboard %6</t>
    <t id="3201">%1 å¸ä»¤å®˜ã€\n\nç´ æ™´ã‚‰ã—ã„ãƒ‹ãƒ¥ãƒ¼ã‚¹ã§ã™!èªå®šè©¦é¨“ã‚’ç„¡äº‹ã«å®Œäº†ã—ã€ç§°å·ã€Œ%2ã€ã‚’ç²å¾—ã—ã¾ã—ãŸ!\n\nè©¦é¨“ã§ã¯ã€é«˜åº¦ãªå–å¼•æˆ¦ç•¥ã€ãƒªã‚¹ã‚¯è©•ä¾¡ãƒ—ãƒ­ãƒˆã‚³ãƒ«ã€ãƒ•ãƒªãƒ¼ãƒˆèª¿æ•´æ‰‹é †ãŒå–ã‚Šä¸Šã’ã‚‰ã‚Œã¾ã—ãŸã€‚å„ªç§€ãªæˆç¸¾ã§åˆæ ¼ã—ãŸã“ã¨ã‚’å ±å‘Šã§ãã‚‹ã“ã¨ã‚’ã†ã‚Œã—ãæ€ã„ã¾ã™ã€‚\n\nç¾åœ¨ã€ã‚ˆã‚Šè¤‡é›‘ãªå–å¼•æ¥­å‹™ã‚’å‡¦ç†ã™ã‚‹è³‡æ ¼ãŒã‚ã‚Šã€ãƒ•ãƒªãƒ¼ãƒˆã®æˆåŠŸã«ã•ã‚‰ã«è²¢çŒ®ã§ãã‚‹ã“ã¨ã‚’æ¥½ã—ã¿ã«ã—ã¦ã„ã¾ã™ã€‚ç§ã®å°‚é–€èƒ½åŠ›é–‹ç™ºã«æŠ•è³‡ã—ã¦ã„ãŸã ãã‚ã‚ŠãŒã¨ã†ã”ã–ã„ã¾ã™ã€‚\n\næ–°ãŸãªçŒ®èº«çš„ãªå–ã‚Šçµ„ã¿ã«ã‚ˆã‚Šã€\n%3\nèªå®š%2\n%4ã«æ­ä¹—ã—ã¾ã™</t>
    <t id="3202">%1 å¸ä»¤å®˜ã€\n\næ®‹å¿µãªãŒã‚‰ã€ç§ã®èªå®šè©¦é¨“ã¯é‹ç”¨ä¸Šã®éƒ½åˆã«ã‚ˆã‚Šä¸­æ–­ã•ã‚Œã¾ã—ãŸã€‚çŠ¶æ³ãŒè¨±ã›ã°ã€ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ«ã‚’å¤‰æ›´ã™ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚\n\nç§ã¯å¼•ãç¶šãã‚¹ã‚­ãƒ«ã®å‘ä¸Šã«åŠªã‚ã€è©¦é¨“ãƒ—ãƒ­ã‚»ã‚¹ã‚’å†é–‹ã§ãã‚‹ã‚ˆã†ã«ãªã£ãŸã‚‰ãŠçŸ¥ã‚‰ã›ã—ã¾ã™ã€‚\n\nã‚ˆã‚ã—ããŠé¡˜ã„ã„ãŸã—ã¾ã™ã€‚\n%2\n%3 ã«ä¹—èˆ¹ã—ã¾ã™ã€‚</t>
    <t id="3203">å¸ä»¤å®˜ %1ã€\n\nç¾åœ¨ã€èªå®šè©¦é¨“ã®ãŸã‚ %2 ã¸å‘ã‹ã£ã¦ã„ã¾ã™ã€‚ã“ã®æ—…ã¯ã€å‹‰å¼·ã‚’æŒ¯ã‚Šè¿”ã‚Šã€ã‚­ãƒ£ãƒªã‚¢ã«ãŠã‘ã‚‹ã“ã®é‡è¦ãªã‚¹ãƒ†ãƒƒãƒ—ã«å‘ã‘ã¦ç²¾ç¥žçš„ã«æº–å‚™ã™ã‚‹æ™‚é–“ã‚’ä¸Žãˆã¦ãã‚Œã¾ã™ã€‚\n\nåˆ°ç€äºˆå®šæ™‚åˆ»: %3 åˆ†\nè©¦é¨“æ™‚é–“: %4 åˆ†\n\nç§ã®èƒ½åŠ›ã¨æ˜‡é€²ã®æ©Ÿä¼šã‚’ä¿¡é ¼ã—ã¦ãã ã•ã£ãŸã“ã¨ã«æ„Ÿè¬ã—ã¾ã™ã€‚\n\næ±ºæ„ã‚’æŒã£ã¦ã€\n%5\n%6 ã«ä¹—èˆ¹ã—ã¦ãã ã•ã„ã€‚</t>
    <t id="3204">æŒ‡æ®å®˜ã€\n\nã‚·ã‚¹ãƒ†ãƒ ãƒã‚§ãƒƒã‚¯ä¸­ã«è²¨ç‰©å€‰ã«è²¨ç‰©ã‚’ç™ºè¦‹ã—ã¾ã—ãŸã€‚é€šå¸¸ã®å–å¼•æ“ä½œã‚’é–‹å§‹ã™ã‚‹å‰ã«ã€ã“ã®å•†å“ã‚’è²©å£²ã™ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚\n\nå–å¼•æ¤œç´¢ã‚’ä½¿ç”¨ã—ã¦æœ€é©ãªè³¼å…¥è€…ã‚’è¦‹ã¤ã‘ã€ã“ã®è²¨ç‰©ã‚’å®‰å…¨ã«é™ã‚ã—ã¦ã„ã¾ã™ã€‚ä¿ç•™ãŒè§£é™¤ã•ã‚ŒãŸã‚‰ã€è‡ªå‹•å–å¼•ã‚’ç¶šè¡Œã—ã¾ã™ã€‚\n\nã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹: æœ€é©ãªè²©å£²å ´æ‰€ã‚’æŽ¢ã—ã¦ã„ã¾ã™\n\nç†±å¿ƒã«ã€\n%1 ã«ä¹—èˆ¹ã—ã¾ã™ã€‚</t>
    <t id="3205">æŒ‡æ®å®˜ã€\n\nèˆ¹ä½“ã®å¥å…¨æ€§ãŒ %1%% (ã—ãã„å€¤: %2%%) ã«ä½Žä¸‹ã—ã¾ã—ãŸã€‚ãƒ¬ãƒ™ãƒ« %3 ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¨ã—ã¦ã€ç§ã¯è‡ªå‹•ä¿®å¾©ã‚µãƒ¼ãƒ“ã‚¹ã‚’ãƒªã‚¯ã‚¨ã‚¹ãƒˆã™ã‚‹æ¨©é™ã‚’æŒã£ã¦ã„ã¾ã™ã€‚\n\nä¿®â€‹â€‹å¾©ä½œæ¥­ã®ãŸã‚ %4 ã«é€²ã¿ã¾ã™ã€‚æŽ¨å®šã‚³ã‚¹ãƒˆã¯ %5 Cr ã§ã€äºˆç®—å†…ã§ã™ã€‚\n\nä¿®â€‹â€‹ç†ãŒå®Œäº†ã—ãŸã‚‰ã€æ§‹é€ çš„ã«å®Œå…¨ãªçŠ¶æ…‹ã§å–å¼•æ¥­å‹™ã‚’å†é–‹ã—ã¾ã™ã€‚\n\næ•¬æ„ã‚’è¡¨ã—ã€\n%6 ã«ä¹—èˆ¹ã—ã¾ã™ã€‚</t>
    <t id="3206">æŒ‡æ®å®˜ã€\n\nç·Šæ€¥ã®è²¡å‹™è­¦å‘Š\n\nèˆ¹ä½“ã®å®Œå…¨æ€§ã¯ %1%% (ã—ãã„å€¤: %2%%) ã§å±æ©Ÿçš„ã§ã™ãŒã€åˆ©ç”¨å¯èƒ½ãªè³‡é‡‘ (%3 Cr) ã§ã¯å®Œå…¨ãªä¿®ç† (æŽ¨å®šã‚³ã‚¹ãƒˆ: %4 Cr) ã«ã¯ä¸ååˆ†ã§ã™ã€‚\n\nåˆ©ç”¨å¯èƒ½ãªè³‡é‡‘ã‚’ä½¿ã£ã¦éƒ¨åˆ†ä¿®ç†ã®ãŸã‚ %5 ã«é€²ã¿ã¾ã™ã€‚ã“ã‚Œã¯ç†æƒ³çš„ãªè§£æ±ºç­–ã§ã¯ã‚ã‚Šã¾ã›ã‚“ãŒã€é‹ç”¨èƒ½åŠ›ã‚’ç¶­æŒã™ã‚‹ãŸã‚ã«ã¯å¿…è¦ã§ã™ã€‚\n\nå°†æ¥ã®ä¿å®ˆé‹ç”¨ã®ãŸã‚ã«è¿½åŠ ã®è³‡é‡‘ã‚’å‰²ã‚Šå½“ã¦ã‚‹ã“ã¨ã‚’æ¤œè¨Žã—ã¦ãã ã•ã„ã€‚\n\næ‡¸å¿µã¯ã‚ã‚Šã¾ã™ãŒã€æ±ºæ„ã—ã¾ã—ãŸã€‚\n%6 ã«ä¹—èˆ¹ã—ã¾ã™ã€‚</t>
    <t id="3207">æŒ‡æ®å®˜ã€\n\nç§ã®ãƒ¬ãƒ™ãƒ« %1 èªå®šã«ã‚ˆã‚Šã€é˜²å¾¡è£…å‚™ã®è‡ªå‹•è£œçµ¦ãŒè¨±å¯ã•ã‚Œã¾ã™ã€‚ã‚·ã‚¹ãƒ†ãƒ ã‚’ãƒã‚§ãƒƒã‚¯ã—ãŸçµæžœã€å¯¾æŠ—æ‰‹æ®µã¨é…å‚™å¯èƒ½ãªç‰©å“ãŒæŽ¨å¥¨ã—ãã„å€¤ã‚’ä¸‹å›žã£ã¦ã„ã‚‹ã¨åˆ¤æ–­ã—ã¾ã—ãŸã€‚\n\né˜²è¡›è£…å‚™ã‚’è£œå……ã™ã‚‹ãŸã‚ã«%2ã«é€²ã‚“ã§ã„ã¾ã™:\nâ€¢ å¯¾æŠ—ç­–: æœ€é©ãªå®¹é‡ã¾ã§è£œå……\nâ€¢ é˜²è¡›ãƒ‰ãƒ­ãƒ¼ãƒ³ã€è²¿æ˜“ãƒ‰ãƒ­ãƒ¼ãƒ³ã€ãƒ¬ãƒ¼ã‚¶ãƒ¼ã‚¿ãƒ¯ãƒ¼: ãƒãƒ©ãƒ³ã‚¹ãƒ—ãƒ­ãƒ•ã‚¡ã‚¤ãƒ«ã‚’é©ç”¨ã—ã¦ã„ã¾ã™\n\nã“ã®è£œçµ¦ã«ã‚ˆã‚Šã€äº¤æ˜“åŠ¹çŽ‡ã‚’ç¶­æŒã—ãªãŒã‚‰å®‡å®™ã®è„…å¨ã‹ã‚‰æœ€å¤§é™ã«ä¿è­·ã•ã‚Œã¾ã™ã€‚\n\nè­¦æˆ’ã—ãªãŒã‚‰ã€\nä¹—èˆ¹ã—ã¦ãã ã•ã„ã€‚ %3</t>
    <t id="3212">æŒ‡æ®å®˜ã€\n\nèˆ¹ä½“ã®å®Œå…¨æ€§ãŒ %1%% (ã—ãã„å€¤: %2%%) ã«ä½Žä¸‹ã—ãŸãŸã‚ã€ä¿®ç†ã‚µãƒ¼ãƒ“ã‚¹ãŒå¿…è¦ã§ã™ã€‚ãŸã ã—ã€%3 ã«ã‚ã‚‹æœ€å¯„ã‚Šã®ä¿®ç†ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¯ã€ã‚»ã‚¯ã‚¿ãƒ¼ã®ç§»å‹•åˆ¶é™ (ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«è¼‰ã£ã¦ã„ã‚‹ãƒ«ãƒ¼ãƒˆ) ã®ãŸã‚ã€ç¾åœ¨ã‚¢ã‚¯ã‚»ã‚¹ã§ãã¾ã›ã‚“ã€‚\n\nã“ã®åˆ¶é™ã«ã‚‚ã‹ã‹ã‚ã‚‰ãšã€å–å¼•æ¥­å‹™ã‚’ç¶šè¡Œã—ã¾ã™ã€‚å®‰å…¨ãªãƒ«ãƒ¼ãƒˆãŒå†ã³åˆ©ç”¨å¯èƒ½ã«ãªã£ãŸã‚‰ã€è‡ªå‹•çš„ã«ä¿®ç†ã‚µãƒ¼ãƒ“ã‚¹ã‚’ä¾é ¼ã—ã¾ã™ã€‚\n\nçŠ¶æ³ã‚’ç›£è¦–ã—ã€ä¿®ç†ãŒå¯èƒ½ã«ãªã£ãŸã‚‰ãŠçŸ¥ã‚‰ã›ã—ã¾ã™ã€‚\n\nã‚ˆã‚ã—ããŠé¡˜ã„ã„ãŸã—ã¾ã™ã€‚\n%4 ã«ã”ä¹—è»Šãã ã•ã„ã€‚</t>
    <t id="3213">æŒ‡æ®å®˜ã€\n\nç§ã®é˜²è¡›è£…å‚™ã«ã¯è£œçµ¦ãŒå¿…è¦ã§ã™ãŒã€%1 ã«ã‚ã‚‹æœ€å¯„ã‚Šã®è£…å‚™ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¯ã€ã‚»ã‚¯ã‚¿ãƒ¼ã®ç§»å‹•åˆ¶é™ (ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«è¼‰ã£ã¦ã„ã‚‹ãƒ«ãƒ¼ãƒˆ) ã®ãŸã‚ã€ç¾åœ¨ã‚¢ã‚¯ã‚»ã‚¹ã§ãã¾ã›ã‚“ã€‚\n\nã“ã®åˆ¶é™ã«ã‚‚ã‹ã‹ã‚ã‚‰ãšã€ç§ã¯è²¿æ˜“æ¥­å‹™ã‚’ç¶šè¡Œã—ã¾ã™ã€‚å®‰å…¨ãªãƒ«ãƒ¼ãƒˆãŒå†ã³åˆ©ç”¨å¯èƒ½ã«ãªã£ãŸã‚‰ã€è‡ªå‹•çš„ã«è£œçµ¦ã‚µãƒ¼ãƒ“ã‚¹ã‚’æŽ¢ã—ã¾ã™ã€‚\n\nçŠ¶æ³ã‚’ç›£è¦–ã—ã€è£œçµ¦ãŒå¯èƒ½ã«ãªã£ãŸã‚‰ãŠçŸ¥ã‚‰ã›ã—ã¾ã™ã€‚\n\nè¬¹ã‚“ã§ã€\n%2 ã«ã”æ­ä¹—ãã ã•ã„ã€‚</t>
    <t id="3208">æŒ‡æ®å®˜ã€\n\n%1 ã¨ãã®å‘¨è¾ºã‚»ã‚¯ã‚¿ãƒ¼ (%2 ã‚¸ãƒ£ãƒ³ãƒ—ä»¥å†…ã€æœ€å°åˆ©ç›ŠåŸºæº–: %3 Cr) ã®å¾¹åº•çš„ãªå¸‚å ´åˆ†æžã‚’å®Œäº†ã—ã¾ã—ãŸãŒã€æ®‹å¿µãªãŒã‚‰è¦ä»¶ã‚’æº€ãŸã™åŽç›Šæ€§ã®é«˜ã„å–å¼•æ©Ÿä¼šãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“ã§ã—ãŸã€‚\n\nè²¿æ˜“åˆ†æžãƒ¬ãƒãƒ¼ãƒˆ:\nè©•ä¾¡ã•ã‚ŒãŸæ©Ÿä¼šã®åˆè¨ˆ: %4\n\næ‹’å¦ã®å†…è¨³:\n- ãƒ‰ãƒƒã‚­ãƒ³ã‚°åˆ¶é™: %5å–å¼•\n (ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãŒç§ã®èˆ¹ã‚¯ãƒ©ã‚¹ã‚’è¨±å¯ã—ã¦ã„ã¾ã›ã‚“)\n- ä¸ååˆ†ãªåŽç›Šæ€§: %6 ä»¶ã®å–å¼•\n (æœ€ä½Žåˆ©ç›Šã—ãã„å€¤ã‚’ä¸‹å›žã‚Šã¾ã™)\n- ä¸ååˆ†ãªé‡: %7 ä»¶ã®å–å¼•\n (ã‚¼ãƒ­ã¾ãŸã¯ãƒžã‚¤ãƒŠã‚¹ã®å–å¼•å¯èƒ½é¡)\n- å®‰å…¨åˆ¶é™: %8 ä»¶ã®å–å¼•\n (ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚ŒãŸã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¾ãŸã¯å±é™ºãªã‚»ã‚¯ã‚¿ãƒ¼)\n\næŽ¨å¥¨äº‹é …:\n- åˆ©ç›Šã®èª¿æ•´ã‚’æ¤œè¨Žã—ã¦ãã ã•ã„ã—ãã„å€¤\n- æœ€å¤§å–å¼•è·é›¢ã‚’æ‹¡å¤§ã—ã¾ã™\n- ã‚»ã‚¯ã‚¿ãƒ¼ã®ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆè¨­å®šã‚’ç¢ºèªã—ã¾ã™\n- å¸‚æ³ãŒæ”¹å–„ã™ã‚‹ã¾ã§å¾…ã¡ã¾ã™\n\nå¼•ãç¶šãå¸‚å ´ã‚’ç›£è¦–ã—ã€åŽç›Šæ€§ã®é«˜ã„æ©Ÿä¼šãŒåˆ©ç”¨å¯èƒ½ã«ãªã£ãŸã‚‰ãŠçŸ¥ã‚‰ã›ã—ã¾ã™ã€‚\n\nå¾…æ©Ÿä¸­ã€\nã‚µãƒ¼ãƒ“ã‚¹ã«ä¹—ã‚Šå‡ºã—ã¾ã™</t>
    <t id="3209">æŒ‡æ®å®˜ã€\n\nç·Šæ€¥ãƒ«ãƒ¼ãƒˆè­¦å ±\n\nç§ã®è„…å¨ã‚¤ãƒ³ãƒ†ãƒªã‚¸ã‚§ãƒ³ã‚¹ ã‚·ã‚¹ãƒ†ãƒ ã¯ã€ã‚»ã‚¯ã‚¿ãƒ¼ %1 (è„…å¨ãƒ¬ãƒ™ãƒ« %2) ãŒç¾åœ¨è¨ˆç”»ã—ã¦ã„ã‚‹äº¤æ˜“ãƒ«ãƒ¼ãƒˆå†…ã«ã‚ã‚‹ã“ã¨ã‚’æ¤œå‡ºã—ã¾ã—ãŸã€‚èˆ¹ã¨ä¹—çµ„å“¡ã®å®‰å…¨ã®ãŸã‚ã€ç¾åœ¨ã®è²¿æ˜“æ¥­å‹™ã‚’ãŸã ã¡ã«ä¸­æ­¢ã—ã¾ã™ã€‚\n\nå–ã‚‰ã‚ŒãŸæŽªç½®:\n- ã™ã¹ã¦ã®è²¿æ˜“æ³¨æ–‡ãŒã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã¾ã—ãŸ\n- å®‰å…¨é‹èˆªãƒ¢ãƒ¼ãƒ‰ã«æˆ»ã‚Šã¾ã™\n- å±é™ºãªã‚»ã‚¯ã‚¿ãƒ¼ã‚’å›žé¿ã™ã‚‹ä»£æ›¿è²¿æ˜“ãƒ«ãƒ¼ãƒˆã‚’è¦‹ã¤ã‘ã¾ã™\n- è·å½¹: è‡ªå‹• (å¿…è¦ã«å¿œã˜ã¦è²¨ç‰©ã‚’å®‰å…¨ãªå ´æ‰€ã§è²©å£²ã—ã¾ã™)\n\nå‹•çš„ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆ ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã‚Šã€è„…å¨ãŒé™¤åŽ»ã•ã‚Œã‚‹ã¾ã§ã“ã®ã‚»ã‚¯ã‚¿ãƒ¼ã‚’ä»‹ã—ãŸä»Šå¾Œã®å–å¼•ãŒé˜»æ­¢ã•ã‚Œã¾ã™ã€‚\n\nå®‰å…¨ãŒç¬¬ä¸€ã§ã™ã€‚ \n\næ³¨æ„ã—ã¦\n%3ã«ã”ä¹—èˆ¹ãã ã•ã„ã€‚</t>
    <t id="3210">æŒ‡æ®å®˜ã€\n\nè„±å‡ºãƒ«ãƒ¼ãƒˆã‚’é–‹å§‹ã—ã¾ã—ãŸ\n\nç§ã¯ç¾åœ¨ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚Œã¦ã„ã‚‹ã‚»ã‚¯ã‚¿ãƒ¼ %1 ã«ã„ã¾ã™ãŒã€å®‰å…¨ã«è„±å‡ºã§ãã‚‹äº¤æ˜“ãƒ«ãƒ¼ãƒˆã‚’è¦‹ã¤ã‘ã¾ã—ãŸã€‚\n\näº¤æ˜“ãƒ«ãƒ¼ãƒˆ:\nè²·ã„: %2 (ã‚»ã‚¯ã‚¿ãƒ¼: %3)\nå£²ã‚Š: %4 (ã‚»ã‚¯ã‚¿ãƒ¼: %5)\nã‚¦ã‚§ã‚¢: %6 (x%7)\næœŸå¾…åˆ©ç›Š: %8 Cr\n\nã“ã®å–å¼•ã‚’å®Œäº†ã™ã‚‹ã¨ã€èˆ¹ã¯ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«è¼‰ã£ã¦ã„ã‚‹åŒºåŸŸã‹ã‚‰è„±å‡ºã—ã¾ã™ã€‚\n\nè¬¹ã‚“ã§\nã”ä¹—èˆ¹ãã ã•ã„ã€‚</t>
    <t id="3211">æŒ‡æ®å®˜ã€\n\nåˆ†é›¢å–å¼•ãƒ¢ãƒ¼ãƒ‰\n\nç¾åœ¨ã‚»ã‚¯ã‚¿ãƒ¼ %2 ã«ã„ã¾ã™ãŒã€ä»–ã®ã‚»ã‚¯ã‚¿ãƒ¼ã¸ã®ãƒ«ãƒ¼ãƒˆã¯ã™ã¹ã¦ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚ŒãŸãƒãƒ– ã‚»ã‚¯ã‚¿ãƒ¼ã«ã‚ˆã£ã¦ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¦ã„ã¾ã™ã€‚ã“ã‚Œã¯ã€ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã®çŠ¶æ³ãŒå¤‰ã‚ã‚‹ã¾ã§ã€ç¾åœ¨ã®ã‚»ã‚¯ã‚¿ãƒ¼å†…ã§ã®ã¿å–å¼•ã§ãã‚‹ã“ã¨ã‚’æ„å‘³ã—ã¾ã™ã€‚\n\nçŠ¶æ³:\nç¾åœ¨ã®ã‚»ã‚¯ã‚¿ãƒ¼: %2\nã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹: å­¤ç«‹ (ãƒ«ãƒ¼ãƒˆãŒãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¦ã„ã‚‹ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚Œã¦ã„ãªã„ã‚»ã‚¯ã‚¿ãƒ¼)\nå–å¼•ãƒ¢ãƒ¼ãƒ‰: ã‚»ã‚¯ã‚¿ãƒ¼å†…å–å¼•ã®ã¿\n\nç§ã®å–å¼•ã‚·ã‚¹ãƒ†ãƒ ã¯ã€åˆ©ç”¨å¯èƒ½ãªã‚»ã‚¯ã‚¿ãƒ¼å†…å–å¼•æ©Ÿä¼šã‚’å„ªå…ˆã™ã‚‹ãŸã‚ã«åˆ©ç›Šã—ãã„å€¤ã‚’è‡ªå‹•çš„ã«èª¿æ•´ã—ã¦ã„ã¾ã™ã€‚\n\nå¼•ãç¶šãçŠ¶æ³ã‚’ç›£è¦–ã—ã€ãƒ«ãƒ¼ãƒˆãŒåˆ©ç”¨å¯èƒ½ã«ãªã£ãŸå ´åˆã¯é€šçŸ¥ã—ã¾ã™ã€‚ \n\nè¬¹ã‚“ã§\n%1ã«ã”ä¹—è»Šãã ã•ã„</t>
    <t id="3218">æŒ‡æ®å®˜ã€\n\nãƒ«ãƒ¼ãƒˆ ãƒ‘ã‚¹ã®å¤‰æ›´ãŒæ¤œå‡ºã•ã‚Œã¾ã—ãŸ\n\nã‚»ã‚¯ã‚¿ãƒ¼ %1 ã«å…¥ã‚‹ã¨ã€ãƒŠãƒ“ã‚²ãƒ¼ã‚·ãƒ§ãƒ³ ã‚·ã‚¹ãƒ†ãƒ ãŒç›®çš„åœ° %2 (%3) ã¸ã®ãƒ«ãƒ¼ãƒˆãŒå¤‰æ›´ã•ã‚ŒãŸã“ã¨ã‚’æ¤œå‡ºã—ã¾ã—ãŸã€‚\n\nãƒ‘ã‚¹åˆ†æž:\n- é€šå¸¸ã®è·é›¢: %4 ã‚¸ãƒ£ãƒ³ãƒ—\n- ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆèªè­˜è·é›¢: %5\n- ã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹: %6\n\nãƒŠãƒ“ã‚²ãƒ¼ã‚·ãƒ§ãƒ³ ã‚³ãƒ³ãƒ”ãƒ¥ãƒ¼ã‚¿ãƒ¼ã¯ã€åŒºé–“ã®ç§»å‹•åˆ¶é™ã«ã‚ˆã‚Šã€å„ªå…ˆãƒ«ãƒ¼ãƒˆãŒåˆ©ç”¨ã§ããªããªã£ãŸã“ã¨ã‚’ç¤ºã—ã¾ã™ã€‚èˆ¹ã¨ä¹—çµ„å“¡ã®å®‰å…¨ã®ãŸã‚ã€ç¾åœ¨ã®è²¿æ˜“æ¥­å‹™ã‚’ç›´ã¡ã«ä¸­æ­¢ã—ã¾ã™ã€‚\n\nå–ã‚‰ã‚ŒãŸæŽªç½®:\n- ã™ã¹ã¦ã®è²¿æ˜“æ³¨æ–‡ãŒã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã¾ã—ãŸ\n- å®‰å…¨é‹èˆªãƒ¢ãƒ¼ãƒ‰ã«æˆ»ã‚Šã¾ã™\n- å°éŽ–ã•ã‚ŒãŸã‚»ã‚¯ã‚¿ãƒ¼ã‚’å›žé¿ã™ã‚‹ä»£æ›¿è²¿æ˜“ãƒ«ãƒ¼ãƒˆã‚’è¦‹ã¤ã‘ã¾ã™\n- è·å½¹: è‡ªå‹• (å¿…è¦ã«å¿œã˜ã¦å®‰å…¨ãªå ´æ‰€ã§è²¨ç‰©ã‚’è²©å£²ã—ã¾ã™)\n\nä»Šå¾Œã®ãƒ«ãƒ¼ãƒˆè¨ˆç”»ã§ã¯ã€ãƒŠãƒ“ã‚²ãƒ¼ã‚·ãƒ§ãƒ³ ã‚·ã‚¹ãƒ†ãƒ ãŒè‡ªå‹•çš„ã«å°éŽ–ã•ã‚ŒãŸã‚»ã‚¯ã‚¿ãƒ¼ã‚’å›žé¿ã—ã¾ã™ã€‚\n\nå®‰å…¨ãŒæœ€å„ªå…ˆã§ã™ã€‚\n\nè­¦æˆ’ã—ã¦ãã ã•ã„ã€\n%7ã«ä¹—ã£ã¦ãã ã•ã„</t>
    <t id="3219">ã‚»ã‚¯ã‚¿ãƒ¼ %1 ã‚’ã‚¯ãƒªã‚¢ - ã™ã¹ã¦ã®è„…å¨ã‚’æŽ’é™¤</t>
    <t id="3220">Commander,\n\nENEMY SHIP ESCAPED\n\nOur threat intelligence system has lost track of enemy ship %3, which has escaped from blacklisted sector %1.\n\nDETAILS:\n- Escaped Ship: %3\n- Sector Left: %1\n- Destination Sector: %2\n- Status: Tracking lost - ship has left our monitored area\n\nWhile this ship is no longer a threat in sector %1, we have lost visual contact and cannot confirm its current status or intentions in sector %2.\n\nOur tracking systems will continue monitoring sector %1 for remaining threats. If all tracked enemies leave or are eliminated, the sector will be automatically cleared from the blacklist.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3221">æŒ‡æ®å®˜ã€\n\nã“ã‚Œã‚‰ã®ãƒ«ãƒ¼ãƒˆã¯ã‚»ã‚¯ã‚¿ãƒ¼ã®ç§»å‹•åˆ¶é™ (ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚ŒãŸãƒ‘ã‚¹) ã«ã‚ˆã‚Šç¾åœ¨åˆ°é”ã§ããªã„ãŸã‚ã€é•·è·é›¢ (æœ€å¤§ %3 ã‚¸ãƒ£ãƒ³ãƒ—) ã§åŽç›Šæ€§ã®é«˜ã„å–å¼•ã®æ©Ÿä¼šã‚’è¦‹ã¤ã‘ã‚‹ã“ã¨ãŒã§ãã¾ã›ã‚“ã§ã—ãŸã€‚\n\nçŠ¶æ³:\nç¾åœ¨ã®ã‚»ã‚¯ã‚¿ãƒ¼: %2\nå…ƒã®æ¤œç´¢ç¯„å›²: %3 ã‚¸ãƒ£ãƒ³ãƒ—\nãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ç¯„å›²: %4 ã‚¸ãƒ£ãƒ³ãƒ—\n\nä»Šåº¦ã¯è¿‘ãã®ã‚»ã‚¯ã‚¿ãƒ¼ã«ç„¦ç‚¹ã‚’å½“ã¦ã¦æ¤œç´¢ã—ã¾ã™ã€‚ %4 ã‚¸ãƒ£ãƒ³ãƒ—å†…ã€‚ãƒ«ãƒ¼ãƒˆã«ã‚¢ã‚¯ã‚»ã‚¹ã§ãã‚‹å¯èƒ½æ€§ãŒé«˜ããªã‚Šã¾ã™ã€‚ã“ã‚Œã¯ã€å®Ÿéš›ã«ã¯åˆ©ç›ŠãŒå¾—ã‚‰ã‚Œãªã„ã¨ã„ã†ã‚ˆã‚Šã‚‚ã€è·é›¢åˆ¶é™ã«ã‚ˆã£ã¦ä»¥å‰ã¯é™¤å¤–ã•ã‚Œã¦ã„ãŸåˆ©ç›Šã®å‡ºã‚‹å–å¼•ã‚’è¦‹ã¤ã‘ã‚‹ã®ã«å½¹ç«‹ã¡ã¾ã™ã€‚\n\nè¿‘éš£ã‚¨ãƒªã‚¢ã§é©åˆ‡ãªå–å¼•ã®æ©Ÿä¼šãŒè¦‹ã¤ã‹ã£ãŸã‚‰ã€ãŠçŸ¥ã‚‰ã›ã—ã¾ã™ã€‚\n\nè¬¹ã‚“ã§ã€\n%1 ã«ã”ä¹—è»Šãã ã•ã„ã€‚</t>
    <t id="3222">æŒ‡æ®å®˜ã€\n\nã‚»ã‚¯ã‚¿ãƒ¼ãŒãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚Œã¾ã—ãŸ\n\næˆ‘ãŒå›½ã®è„…å¨ã‚¤ãƒ³ãƒ†ãƒªã‚¸ã‚§ãƒ³ã‚¹ ã‚·ã‚¹ãƒ†ãƒ ã¯ã‚»ã‚¯ã‚¿ãƒ¼ %1 ã§ã®æ•µå¯¾çš„ãªæ´»å‹•ã‚’æ¤œå‡ºã—ã€è²¿æ˜“æ¥­å‹™ã‚’ä¿è­·ã™ã‚‹ãŸã‚ã«ã“ã®ã‚»ã‚¯ã‚¿ãƒ¼ã‚’è‡ªå‹•çš„ã«ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã—ã¾ã—ãŸã€‚\n\næ¤œå‡ºã•ã‚ŒãŸæ•µèˆ¹:\n%2\n\næ¤œå‡ºè€…: %3\n\nèˆ¹èˆ¶ã¨ä¹—çµ„å“¡ã®å®‰å…¨ã®ãŸã‚ã€ã“ã®ã‚»ã‚¯ã‚¿ãƒ¼ã‚’é€šã‚‹ã™ã¹ã¦ã®äº¤æ˜“ãƒ«ãƒ¼ãƒˆãŒãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¾ã—ãŸã€‚è„…å¨ãŒæŽ’é™¤ã•ã‚Œã‚‹ã¾ã§ã€æˆ‘ãŒå›½ã®èˆ¹èˆ¶ã¯è‡ªå‹•çš„ã«ã“ã®ã‚»ã‚¯ã‚¿ãƒ¼ã‚’è¿‚å›žã—ã¾ã™ã€‚\n\nè¿½è·¡ä¸­ã®æ•µèˆ¹èˆ¶ãŒã™ã¹ã¦æŽ’é™¤ã•ã‚Œã‚‹ã‹ã€ãã®åœ°åŸŸã‹ã‚‰é›¢ã‚Œã‚‹ã¨ã€ã“ã®ã‚»ã‚¯ã‚¿ãƒ¼ã¯è‡ªå‹•çš„ã«ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‹ã‚‰å‰Šé™¤ã•ã‚Œã¾ã™ã€‚\n\nè­¦æˆ’ã—ãªãŒã‚‰ã€\nè„…å¨æƒ…å ±ã‚·ã‚¹ãƒ†ãƒ </t>
    <t id="3223">æŒ‡æ®å®˜ã€\n\nãƒ¬ãƒ™ãƒ« %1 ã®æ˜‡æ ¼è©¦é¨“ã«å‚åŠ ã§ãã‚‹ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚° ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“ã€‚æŒ‡ç¤ºã«å¾“ã£ã¦å–å¼•æ“ä½œã‚’é€²ã‚ã¦ã„ãã¾ã™ãŒã€å¿…è¦ãªãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã‚’å®Œäº†ã™ã‚‹ã¾ã§çµŒé¨“å€¤ãŒå¾—ã‚‰ã‚Œãªã„ã“ã¨ã‚’ç†è§£ã—ã¦ã„ã¾ã™ã€‚ã“ã®å–å¼•ãŒçµ‚äº†ã—ãŸã‚‰ã€ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã®æ©Ÿä¼šãŒãªã„ã‹å†åº¦æŽ¢ã—ã¾ã™ã€‚\n\nè¬¹ã‚“ã§ã€\n%2 ã«ä¹—èˆ¹ã—ã¾ã™ã€‚</t>
    <t id="3224">ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚° ãƒ©ã‚¤ã‚»ãƒ³ã‚¹æ–™é‡‘: %1 Cr</t>
    <t id="3225">ãƒœãƒ¼ãƒŠã‚¹: ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ä¸­ã«è“„ç©ã•ã‚ŒãŸçµŒé¨“ã«ã‚ˆã‚Šã€%1 ã®è¿½åŠ ã‚¹ã‚­ãƒ« ãƒ¬ãƒ™ãƒ«%2 ã‚’ç²å¾—ã—ã¾ã—ãŸã€‚ç¾åœ¨ã®ãƒ¬ãƒ™ãƒ«: %3</t>
    <t id="3214">%1ã€ã‚ãªãŸã®ãŸã‚ã«åƒã‘ã¦å…‰æ „ã§ã™!ã‚ãªãŸã®æŒ‡æ®ã®ä¸‹ã§ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°ã®ã‚­ãƒ£ãƒªã‚¢ã‚’ã‚¹ã‚¿ãƒ¼ãƒˆã§ãã‚‹ã“ã¨ã«èˆˆå¥®ã—ã¦ã„ã¾ã™ã€‚è²´ç¤¾ã«è²¢çŒ®ã—ã€è²´ç¤¾ã®æˆåŠŸã«è²¢çŒ®ã§ãã‚‹ã‚ˆã†æœ€å–„ã‚’å°½ãã—ã¾ã™ã€‚</t>
    <t id="3215">%1 ã•ã‚“ã€ã“ã®è²´é‡ãªä¼‘æš‡ã‚’ç§ã«ä¸Žãˆã¦ãã‚Œã¦ã‚ã‚ŠãŒã¨ã†!ç§ã¯ãƒˆãƒ¬ãƒ¼ãƒ‰ã‹ã‚‰é›¢ã‚ŒãŸæ™‚é–“ã‚’æ¥½ã—ã‚“ã§ãŠã‚Šã€ã‚¹ã‚­ãƒ«ã¯ãã®ã¾ã¾æ®‹ã£ã¦ã„ã¾ã™ã€‚ã‚ãªãŸãŒç§ã‚’å¿…è¦ã¨ã™ã‚‹ã¨ãã¯ã„ã¤ã§ã‚‚ä»•äº‹ã«æˆ»ã‚‹ã“ã¨ã‚’æ¥½ã—ã¿ã«ã—ã¦ã„ã¾ã™ã€‚ãã‚Œã¾ã§ã¯ãƒˆãƒ¬ãƒ¼ãƒ‰ã®çŸ¥è­˜ã‚’ç£¨ãç¶šã‘ã¾ã™ï¼</t>
    <t id="3216">ä¼‘æš‡ã‹ã‚‰æˆ»ã‚Šã€å†ã³ä»•äº‹ã‚’ã™ã‚‹æº–å‚™ãŒã§ãã¾ã—ãŸã€%1!ç§ã®å–å¼•ã‚¹ã‚­ãƒ«ã¯ä¾ç„¶ã¨ã—ã¦å„ªã‚Œã¦ãŠã‚Šã€%2 ã‚‚å¼•ãç¶šãã‚µãƒ¼ãƒ“ã‚¹ã‚’æä¾›ã—ã¦ã„ããŸã„ã¨è€ƒãˆã¦ã„ã¾ã™ã€‚è²´é‡ãªãŠä¼‘ã¿ã‚’ã‚ã‚ŠãŒã¨ã†ã”ã–ã„ã¾ã—ãŸï¼</t>
    <t id="3217">%1ã€%2 ã¸ã®è»¢é€ã‚ã‚ŠãŒã¨ã†ã”ã–ã„ã¾ã™ã€‚ç§ã¯ã“ã®æ–°ã—ã„ä»»å‹™ã‚’å…‰æ „ã«æ€ã£ã¦ãŠã‚Šã€æ–°ã—ã„èˆ¹ã‚’å¤§åˆ‡ã«æ‰±ã„ã¾ã™ã€‚ç§ã®å–å¼•çµŒé¨“ã¨ã‚¹ã‚­ãƒ«ã¯ãã®ã¾ã¾ã§ã‚ã‚Šã€ä»Šå¾Œã‚‚ã‚µãƒ¼ãƒ“ã‚¹ã‚’æä¾›ã—ç¶šã‘ã‚‹æº–å‚™ãŒã§ãã¦ã„ã¾ã™ã€‚</t>
    <t id="3227">èˆ¹ä½“å–ªå¤±ã€å°ŠåŽ³ã¯å›žåŽå¾…ã¡</t>
    <t id="3228">%1 å¸ä»¤å®˜ã€\n\n%3 ã‹ã‚‰ %2 ã§ã™ã€‚èˆ¹ãŒçˆ†ç™ºã—ã¾ã—ãŸã€‚ç§ã¯ç„¡äº‹ã§ã™ã€‚ä»Šã‚„è‰¦éšŠã§æœ€ã‚‚é«˜ä¾¡ãªæµ®éŠè²¨ç‰©ã§ã™ã€‚\n\nåœ°å›³ãƒžãƒ¼ã‚«ãƒ¼ã‚’æ·»ä»˜ã—ã¾ã—ãŸã€‚æ€¥ã„ã§ãã ã•ã„ - è«‹æ±‚æ›¸ã®é€”ä¸­ã§ã—ãŸã€‚\n\nãƒ—ãƒ­ã¨ã—ã¦æµ®éŠä¸­ã€\n%2</t>
    <t id="3229">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆå›žåŽ - é…¸ç´ ä¾å­˜ç—‡æ²»ç™’</t>
    <t id="3230">%1 å¸ä»¤å®˜ã€\n\nè‰¦éšŠæ›´æ–°ï¼š%2 ã¯ %3 (%4) ã«ã‚ˆã£ã¦å›žåŽã•ã‚Œã€å»¶é•· EVA è¨“ç·´ã®è«‹æ±‚ã‚’åœæ­¢ã—ã¾ã—ãŸã€‚\n\nãƒ¬ã‚¸ã‚¹ãƒˆãƒªã®å†ç´ä»˜ã‘ä¸­ã€‚æ—§èˆ¹ã«ã¤ã„ã¦ã¯è³ªå•ã—ãªã„ã“ã¨ã‚’æŽ¨å¥¨ã—ã¾ã™ã€‚\n\næ¥ãšã‹ã—ã’ã«ã€\n%2</t>
<t id="4000">ãƒ•ãƒªãƒ¼ãƒˆã®èª¿æ•´: %s ã«ã¯ãƒ«ãƒ¼ãƒˆ %s ãŒå‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¾ã—ãŸ</t>
    <t id="4001">è‰¦éšŠèª¿æ•´: ãƒ«ãƒ¼ãƒˆ %s ã¯å®Œå…¨ã«åˆ©ç”¨ã•ã‚Œã¦ã„ã¾ã™</t>
    <t id="4002">è‰¦éšŠèª¿æ•´: %s ãŒãƒ«ãƒ¼ãƒˆ %s ã‚’ãƒªãƒªãƒ¼ã‚¹ã—ã¾ã—ãŸ</t>
    <t id="5000">%s ã¯ %s ã®ãƒ—ãƒ©ã‚¤ãƒžãƒª ãƒ†ãƒªãƒˆãƒªãƒ¼ã¨ã—ã¦å‰²ã‚Šå½“ã¦ã‚‰ã‚Œã¦ã„ã¾ã™</t>
    <t id="5001">%s ã¯ã€%s ã§å°‚é–€çŸ¥è­˜ãƒ¬ãƒ™ãƒ« %s ã«åˆ°é”ã—ã¾ã—ãŸã€‚</t>
    <t id="5002">é©ç”¨ã•ã‚ŒãŸãƒ†ãƒªãƒˆãƒªãƒ¼ ãƒœãƒ¼ãƒŠã‚¹: %s%% åˆ©ç›Šå¢—åŠ  (%s)</t>
    <t id="9500">ã‚¨ãƒ©ãƒ¼: %s ãŒã‚¹ã‚¿ãƒƒã‚¯ã—ã¦ã„ã‚‹ãŸã‚ã€æ”¯æ´ãŒå¿…è¦ã§ã™ã€‚</t>
    <t id="9501">ã‚¨ãƒ©ãƒ¼: %s ã®å–å¼•ã«å¤±æ•—ã—ã¾ã—ãŸ</t>
    <t id="9502">ã‚¨ãƒ©ãƒ¼: %s ã‚’ GalaxyTrader MK3 ã«ç™»éŒ²ã§ãã¾ã›ã‚“</t>
    <t id="80001">ã‚¦ã‚§ã‚¢ %s ãŒãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«è¿½åŠ ã•ã‚Œã¾ã—ãŸ</t>
    <t id="80002">ã‚¦ã‚§ã‚¢ %s ãŒãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‹ã‚‰å‰Šé™¤ã•ã‚Œã¾ã—ãŸ</t>
    <t id="80003">ã‚¦ã‚§ã‚¢ %s ãŒãƒ›ãƒ¯ã‚¤ãƒˆãƒªã‚¹ãƒˆã«è¿½åŠ ã•ã‚Œã¾ã—ãŸ</t>
    <t id="80004">è‡ªå‹•çš„ã«ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚Œã‚‹ (ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ä½Žä¸‹): %s</t>
    <t id="80005">å±é™ºãªè£½å“ã®å„ªå…ˆé †ä½: %s</t>
    <t id="80006">ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼: %s ã‚¢ã‚¯ãƒ†ã‚£ãƒ–ã€%s å–å¼•ã¯ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¦ã„ã¾ã™</t>
    <t id="80007">ã™ã¹ã¦ã®ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ãŒã‚¯ãƒªã‚¢ã•ã‚Œã¾ã—ãŸ</t>
    <t id="80008">ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ãŒãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã«ãƒªã‚»ãƒƒãƒˆã•ã‚Œã¾ã—ãŸ</t>
    <t id="80009">ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ç®¡ç†</t>
    <t id="80010">ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚ŒãŸå•†å“</t>
    <t id="80011">è¨±å¯ã•ã‚ŒãŸå•†å“</t>
    <t id="80012">å±é™ºç‰©ã®å–ã‚Šæ‰±ã„</t>
    <t id="80013">æœ€å°ã‚¦ã‚§ã‚¢ä¾¡å€¤</t>
    <t id="80014">æœ€å¤§ã‚¦ã‚§ã‚¢ä¾¡å€¤</t>
    <t id="80015">åˆ¶é™ã•ã‚ŒãŸæ´¾é–¥</t>
    <t id="80016">ç¾åœ¨ã®ã‚²ãƒ¼ãƒ çŠ¶æ…‹ã‹ã‚‰æ›´æ–°ã•ã‚ŒãŸã‚¦ã‚§ã‚¢ ã‚«ãƒ†ã‚´ãƒª</t>
    <t id="80017">%s ã‚¦ã‚§ã‚¢ã¯åˆ†é¡žã•ã‚Œã¾ã™: %s ä½Žä¾¡å€¤ã€%s å±é™ºã€%s é«˜é¡</t>
    <t id="80018">å‹•çš„ãªã‚¦ã‚§ã‚¢åˆ†é¡žãŒæœ‰åŠ¹ã«ãªã‚Šã¾ã—ãŸ</t>
    <t id="80019">ã‚«ãƒ†ã‚´ãƒª %s ã®è‡ªå‹•ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆç™»éŒ²ãŒç„¡åŠ¹ã«ãªã‚Šã¾ã—ãŸ</t>
    <t id="80020">ä»–ã® MOD ã‹ã‚‰ã®æ–°ã—ã„ã‚¦ã‚§ã‚¢ãŒæ¤œå‡ºã•ã‚Œã€åˆ†é¡žã•ã‚Œã¾ã—ãŸ</t>
    <t id="9000">GalaxyTrader - ã‚°ãƒ­ãƒ¼ãƒãƒ«è¨­å®š</t>
    <t id="9010">XPã¨ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã‚·ã‚¹ãƒ†ãƒ </t>
    <t id="9012">è‡ªå‹•ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°</t>
    <t id="9013">XPãƒžãƒ«ãƒãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼</t>
    <t id="9015">æŒ‡æ®å®˜ãƒœãƒ¼ãƒŠã‚¹ãƒ‘ãƒ¼ã‚»ãƒ³ãƒˆ</t>
    <t id="9020">è‰¦éšŠèª¿æ•´</t>
    <t id="9021">ãƒ•ãƒªãƒ¼ãƒˆã®èª¿æ•´ã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="9023">ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="9030">é€šçŸ¥</t>
    <t id="9031">é€šçŸ¥ãƒ¬ãƒ™ãƒ«</t>
    <t id="9040">è‡ªå‹•ä¿®å¾©ã‚·ã‚¹ãƒ†ãƒ </t>
    <t id="9041">è‡ªå‹•ä¿®å¾©ã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="9042">èˆ¹ä½“ä¿®ç†ã®é–¾å€¤</t>
    <t id="9310">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒžã‚¤ãƒŠãƒ¼</t>
    <t id="9311">ã‚»ã‚¯ã‚¿ãƒ¼å†…ãƒ—ãƒ­ãƒ¼ãƒ–ã‚¹ã‚­ãƒ£ãƒ³å¾…æ©Ÿ</t>
    <t id="9312">è‡ªè‰¦æŽ¥è¿‘å„ªå…ˆã‚¦ã‚§ã‚¤ãƒˆ</t>
    <t id="9043">æœ€ä½Žãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãƒ¬ãƒ™ãƒ«</t>
    <t id="9004">å–å¼•ä¾¡æ ¼å¸¯</t>
    <t id="9005">æœ€å¤§å£²ã‚Šã‚ªãƒ•ã‚¡ãƒ¼ä¾¡æ ¼</t>
    <t id="9006">æœ€ä½Žè³¼å…¥ã‚ªãƒ•ã‚¡ãƒ¼ä¾¡æ ¼</t>
    <t id="9007">å­¤ç«‹: æœ€å¤§è²©å£²ä¾¡æ ¼</t>
    <t id="9008">åˆ†é›¢: æœ€å°è³¼å…¥ä¾¡æ ¼</t>
    <t id="9009">ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯: æœ€å¤§è²©å£²ä¾¡æ ¼</t>
    <t id="9014">ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯: æœ€ä½Žè³¼å…¥ä¾¡æ ¼</t>
    <t id="9016">åˆ©ç›Šé–¾å€¤ãƒ™ãƒ¼ã‚¹</t>
    <t id="9025">æœ€å°ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ãƒžãƒãƒ¼</t>
    <t id="9024">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ãƒ‰ãƒ­ãƒƒãƒ—ã‚ªãƒ•è¨±å®¹åº¦</t>
    <t id="9026">ã‚¢ã‚¤ãƒ‰ãƒ«åœæ³Šè§£é™¤ã¾ã§ã®æ™‚é–“</t>
    <t id="9054">æ•µã®å‹¢åŠ›ã‚»ã‚¯ã‚¿ãƒ¼ã‚’ãƒ–ãƒ­ãƒƒã‚¯ã™ã‚‹</t>
    <t id="9055">ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã®è„…å¨ãƒ¬ãƒ™ãƒ«</t>
    <t id="9056">ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã®å†ä½œæˆ</t>
    <t id="9057">å†ä½œæˆ</t>
    <t id="9058">GT èˆ¹ã«å‰²ã‚Šå½“ã¦ã¾ã™</t>
    <t id="9059">å‰²ã‚Šå½“ã¦ã‚‹</t>
    <t id="9112">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒå¿…è¦ãªãƒ¬ãƒ™ãƒ«ã«é”ã™ã‚‹ã¨ã€è‡ªå‹•çš„ã«è¨“ç·´ã®ãŸã‚ã«ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’é€ã‚Šã¾ã™ã€‚ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã®ã‚¿ã‚¤ãƒŸãƒ³ã‚°ã‚’æ‰‹å‹•ã§åˆ¶å¾¡ã™ã‚‹ã«ã¯ç„¡åŠ¹ã«ã—ã¾ã™ã€‚</t>
    <t id="9113">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒçµŒé¨“ã‚’ç©ã‚€é€Ÿåº¦ã‚’èª¿æ•´ã—ã¾ã™ã€‚å€¤ãŒé«˜ã„ã»ã©ã€é€²è¡ŒãŒé€Ÿããªã‚Šã¾ã™ã€‚</t>
    <t id="9115">æŒ‡æ®å®˜ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ä¸Žãˆã‚‰ã‚Œã‚‹éƒ¨ä¸‹ XP ã®å‰²åˆã€‚ 0% ã«è¨­å®šã™ã‚‹ã¨ã€æŒ‡æ®å®˜ãƒœãƒ¼ãƒŠã‚¹ XP ãŒç„¡åŠ¹ã«ãªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 10%ã€‚</t>
    <t id="9121">ãƒ«ãƒ¼ãƒˆã®æœ€é©åŒ–ã‚„è² è·åˆ†æ•£ãªã©ã®ã‚¤ãƒ³ãƒ†ãƒªã‚¸ã‚§ãƒ³ãƒˆãªãƒ•ãƒªãƒ¼ãƒˆèª¿æ•´æ©Ÿèƒ½ã‚’æœ‰åŠ¹ã«ã—ã¾ã™ã€‚</t>
    <t id="9123">ãƒ•ãƒªãƒ¼ãƒˆãƒ¡ãƒ³ãƒãƒ¼é–“ã§æœ‰ç›Šãªå–å¼•æ©Ÿä¼šã‚’å…±æœ‰ã—ã€èª¿æ•´ã‚’æ”¹å–„ã™ã‚‹ã“ã¨ãŒã§ãã¾ã™ã€‚</t>
    <t id="9131">è¡¨ç¤ºã™ã‚‹é€šçŸ¥ã®æ•°ã‚’åˆ¶å¾¡ã—ã¾ã™: 0=é™ã‹ã€1=é‡è¦ã®ã¿ã€2=ã™ã¹ã¦ã®é€šçŸ¥</t>
    <t id="9141">èˆ¹ä½“ãŒã—ãã„å€¤ã‚’ä¸‹å›žã£ãŸå ´åˆã€å–å¼•å®Œäº†å¾Œã«è‡ªå‹•çš„ã«èˆ¹ã‚’ä¿®ç†ã®ãŸã‚ã«é€ã‚Šã¾ã™ã€‚çµŒé¨“è±Šå¯Œãªãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã¿ï¼ˆãƒ¬ãƒ™ãƒ« 12 ä»¥ä¸Šï¼‰ã€‚èˆ¹èˆ¶ã¯é©åˆ‡ãªæ–½è¨­ã‚’é¸æŠžã—ã¾ã™: S/M æ©Ÿå™¨ãƒ‰ãƒƒã‚¯ã€L/XL é€ èˆ¹æ‰€ã€‚</t>
    <t id="9142">èˆ¹ä½“ãƒ‘ãƒ¼ã‚»ãƒ³ãƒ†ãƒ¼ã‚¸ã‚’ä¸‹å›žã‚‹ã¨è‡ªå‹•ä¿®å¾©ãŒãƒˆãƒªã‚¬ãƒ¼ã•ã‚Œã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 95%ã€‚èˆ¹èˆ¶ãŒæå‚·ã—ãŸå ´åˆã€è‡ªå‹•çš„ã«æœ€å¯„ã‚Šã®ä¿®ç†æ–½è¨­ã¸å‘ã‹ã„ã¾ã™ã€‚</t>
    <t id="9411">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€æŽ¡æŽ˜èˆ¹ã¯ã‚»ã‚¯ã‚¿ãƒ¼å†…ã®æ´¾é–¥è³‡æºãƒ—ãƒ­ãƒ¼ãƒ–è©•ä¾¡ä¸­ã«å¾…æ©Ÿã—ã¾ã™ï¼ˆ2æœ¬ç›®ä»¥é™ã¯1æœ¬ã‚ãŸã‚Š+5ç§’ï¼‰ã€‚GTãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãƒ¬ãƒ™ãƒ«ã«ã‚ˆã‚Šã€å¾…æ©Ÿæ™‚é–“ã¯ãƒ¬ãƒ™ãƒ«1ã®ãƒ•ãƒ«æ™‚é–“ã‹ã‚‰ãƒ¬ãƒ™ãƒ«15ã®5ç§’ã¾ã§ç·šå½¢ã«çŸ­ç¸®ã•ã‚Œã¾ã™ï¼ˆGT XPãƒ¢ãƒ¼ãƒ‰ã®ã¿ã€å¾…æ©ŸãŒ5ç§’ã‚’è¶…ãˆã‚‹å ´åˆï¼‰ã€‚ç„¡åŠ¹ï¼å¾…æ©Ÿãªã—ï¼ˆãƒãƒ‹ãƒ©åŒç­‰ï¼‰ã€‚</t>
    <t id="9412">MK3/MK4è‰¦ãŒæ¤œè¨¼æ¸ˆã¿å–å¼•ã‚’ä¸¦ã¹æ›¿ãˆã‚‹éš›ã€ã‚ˆã‚Šè¿‘ã„è³¼å…¥ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’å„ªå…ˆã—ã¾ã™ã€‚é¸æŠžã‚¹ã‚³ã‚¢ï¼å–å¼•ã‚¹ã‚³ã‚¢ / (1 + è‡ªè‰¦â†’è³¼å…¥ã‚¸ãƒ£ãƒ³ãƒ— Ã— ã‚¦ã‚§ã‚¤ãƒˆ)ã€‚ã‚¹ãƒ©ã‚¤ãƒ€ãƒ¼0-100ï¼ˆ0ï¼ã‚ªãƒ•ã€4ï¼æ—¢å®š0.04ï¼‰ã€‚ã‚­ãƒ£ãƒƒã‚·ãƒ¥é †ä½ã‚„é ˜åŸŸå°„ç¨‹åˆ¶é™ã«ã¯å½±éŸ¿ã—ã¾ã›ã‚“ã€‚</t>
    <t id="9143">è‡ªå‹•ä¿®å¾©æ©Ÿèƒ½ã«å¿…è¦ãªæœ€å°ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ ãƒ¬ãƒ™ãƒ«ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 12 (çµŒé¨“è±Šå¯Œãªãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼)ã€‚ä½Žãƒ¬ãƒ™ãƒ«ã®ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¯æ‰‹å‹•ã§ä¿®ç†ã™ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚</t>
    <t id="9104">å£²ã‚Šã‚ªãƒ•ã‚¡ãƒ¼ã®æœ€å¤§ç›¸å¯¾ä¾¡æ ¼ (ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‹ã‚‰ã®èˆ¹ã®è²·ã„)ã€‚ç¯„å›²: -1.0 ï½ž +1.0ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 0.5 (å¹³å‡ã‚’ 50% ä¸Šå›žã‚‹)ã€‚é«˜ã„ = é«˜ä¾¡ã§ã™ãŒã€ã‚ªãƒ—ã‚·ãƒ§ãƒ³ãŒå¤šããªã‚Šã¾ã™ã€‚</t>
    <t id="9105">è³¼å…¥ã‚ªãƒ•ã‚¡ãƒ¼ã®æœ€ä½Žç›¸å¯¾ä¾¡æ ¼ (èˆ¹èˆ¶ã¯ TO ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’è²©å£²ã—ã¾ã™)ã€‚ç¯„å›²: -1.0 ï½ž +1.0ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: -0.5 (å¹³å‡ã‚ˆã‚Š 50% ä½Žã„)ã€‚ä½Žã„ = è³¼å…¥è€…ã¯å®‰ããªã‚Šã¾ã™ãŒã€é¸æŠžè‚¢ã¯å¤šããªã‚Šã¾ã™ã€‚</t>
    <t id="9106">å­¤ç«‹ã—ãŸèˆ¹èˆ¶ (å˜ä¸€ã‚»ã‚¯ã‚¿ãƒ¼ã§ç«‹ã¡å¾€ç”Ÿã—ã¦ã„ã‚‹) ã®æœ€å¤§å£²å´ä¾¡æ ¼ã€‚ç¯„å›²: -1.0 ï½ž +1.0ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 0.5ã€‚</t>
    <t id="9107">å­¤ç«‹ã—ãŸèˆ¹èˆ¶ (å˜ä¸€ã‚»ã‚¯ã‚¿ãƒ¼ã«ç•™ã¾ã£ã¦ã„ã‚‹) ã®æœ€å°è³¼å…¥ä¾¡æ ¼ã€‚ç¯„å›²: -1.0 ï½ž +1.0ã€‚ Default: -0.5.</t>
    <t id="9108">ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ï¼ˆé€šå¸¸ã®æ¤œç´¢ãŒå¤±æ•—ã—ãŸå ´åˆã®æœ€å¾Œã®æ‰‹æ®µï¼‰ã®æœ€å¤§è²©å£²ä¾¡æ ¼ã€‚ç¯„å›²: -1.0 ï½ž +1.0ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 0.5ã€‚ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ã§ã¯ MaxDistance=2 ã‚’ä½¿ç”¨ã—ã€åˆ©ç›Šã®ã—ãã„å€¤ã‚’ç·©å’Œã—ã¾ã™ã€‚</t>
    <t id="9109">ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ (é€šå¸¸ã®æ¤œç´¢ãŒå¤±æ•—ã—ãŸå ´åˆã®æœ€å¾Œã®æ‰‹æ®µ) ã®æœ€å°è³¼å…¥ä¾¡æ ¼ã€‚ç¯„å›²: -1.0 ï½ž +1.0ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: -0.5ã€‚ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ã§ã¯ MaxDistance=2 ã‚’ä½¿ç”¨ã—ã€åˆ©ç›Šã®ã—ãã„å€¤ã‚’ç·©å’Œã—ã¾ã™ã€‚</t>
    <t id="9116">ä¸­åž‹ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã®ãƒ¬ãƒ™ãƒ« 15 ã§ã®æœ€ä½Žåˆ©ç›Šã®åŸºç¤Ž (å‚ç…§è²¨ç‰© 8200)ã€‚å®Ÿéš›ã® MinAbsoluteProfit ã¯ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã”ã¨ã«è¨ˆç®—ã•ã‚Œã€è²¨ç‰©ã«ã‚ˆã£ã¦ã‚¹ã‚±ãƒ¼ãƒªãƒ³ã‚°ã•ã‚Œã¾ã™:\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = Base(L) * (cargo / 8200)\nfinal = max(scaled, Base(L) ã® 25%)\n\nä»»æ„ã®åˆ©ç›Šã‚’å—ã‘å…¥ã‚Œã‚‹ã«ã¯ 0 ã«è¨­å®šã—ã¾ã™ (ROI/è·é›¢/ãã®ä»–ã®ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã®ã¿ãŒé©ç”¨ã•ã‚Œã¾ã™)ã€‚</t>
    <t id="9125">èˆ¹ãŒå–å¼•ã‚’æŽ¢ã™å‰ã«å¿…è¦ãªæœ€å°ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ãƒžãƒãƒ¼ (ã‚¯ãƒ¬ã‚¸ãƒƒãƒˆ)ã€‚ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ã®è³‡é‡‘ãŒã“ã®ã—ãã„å€¤ã‚’ä¸‹å›žã‚‹ã¨ã€ã™ã¹ã¦ã®èˆ¹ã¯è²¿æ˜“æ¤œç´¢ã‚’ã‚¹ã‚­ãƒƒãƒ—ã—ã¦å¾…æ©Ÿã—ã€ã‚²ãƒ¼ãƒ ã®é€”åˆ‡ã‚Œã‚’å¼•ãèµ·ã“ã™é«˜ä¾¡ãªã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¹ã‚­ãƒ£ãƒ³ã‚’é˜²ãŽã¾ã™ã€‚ç¯„å›²: 1,000 - 100,000 Crã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1,000 Crã€‚</t>
    <t id="9124">å–å¼•ã‚’æ‹’å¦ã™ã‚‹å‰ã«ã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚ŒãŸå€¤ã‹ã‚‰ ROI ãŒä½Žä¸‹ã™ã‚‹æœ€å¤§å‰²åˆã€‚ä¾‹: ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚ŒãŸ ROI ãŒ 20% ã§ã€è¨±å®¹ç¯„å›²ãŒ 15% ã®å ´åˆã€ROI ã¯ 17% (14% ä½Žä¸‹) ã¾ã§è¨±å®¹ã•ã‚Œã¾ã™ã€‚</t>
    <t id="9126">ãƒãƒ¼ãƒˆã‚’ç©ºã‘ã‚‹ãŸã‚ã«ãƒ‰ãƒƒã‚¯ã‹ã‚‰é›¢è„±ã™ã‚‹ã¾ã§ã®åˆ†æ•°ï¼ˆ0-60ï¼‰ã€‚0 = æ–°ã—ã„ä»•äº‹ãŒè¦‹ã¤ã‹ã‚‹ã¾ã§ãƒ‰ãƒƒã‚¯ã«ç•™ã¾ã‚‹ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆï¼š1åˆ†ã€‚</t>
    <t id="9154">æ•µå‹¢åŠ›ãŒæ‰€æœ‰ã™ã‚‹ã™ã¹ã¦ã®ã‚»ã‚¯ã‚¿ãƒ¼ã‚’è‡ªå‹•çš„ã«ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã—ã¾ã™ (ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã®é–¢ä¿‚ãƒã‚§ãƒƒã‚¯ãƒœãƒƒã‚¯ã‚¹)</t>
    <t id="9155">ã‚»ã‚¯ã‚¿ãƒ¼ã‚’ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã™ã‚‹ãŸã‚ã«å¿…è¦ãªæœ€å°è„…å¨ãƒ¬ãƒ™ãƒ« (1 ï½ž 5):\n2= ä¸­ (å˜ä¸€æ”»æ’ƒ)\n3= ä¸­ï½žé«˜ (æ•µå¯¾å‹¢åŠ›)\n4= é«˜ (ä¸»åŠ›è‰¦/ãƒŸã‚µã‚¤ãƒ«)\n5= éžå¸¸ã«é«˜ (ã‚­ã‚»ãƒŽãƒ³/ã‚«ãƒ¼ã‚¯)</t>
    <t id="9156">è„…å¨å›žé¿ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‚’æ‰‹å‹•ã§å†ä½œæˆã—ã¾ã™ (å‰Šé™¤ã•ã‚ŒãŸå ´åˆã«å½¹ç«‹ã¡ã¾ã™)</t>
    <t id="9157">ç¾åœ¨ã®å‹•çš„ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‚’ã™ã¹ã¦ã® GT è‰¦éšŠå¸ä»¤å®˜ã®èˆ¹ã«æ‰‹å‹•ã§å‰²ã‚Šå½“ã¦ã¾ã™ã€‚éƒ¨ä¸‹ã¯æŒ‡æ®å®˜ã‹ã‚‰ç¶™æ‰¿ã—ã¾ã™ã€‚</t>
    <t id="6001">è¦‹ç¿’ã„</t>
    <t id="6002">å®…é…ä¾¿</t>
    <t id="6003">ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼</t>
    <t id="6004">ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼</t>
    <t id="6005">å•†äºº</t>
    <t id="6006">é•·è·é›¢è²©å£²æ¥­è€…</t>
    <t id="6101">ãƒãƒ©ãƒ³ã‚¹ã®ã¨ã‚ŒãŸ</t>
    <t id="6102">å®ˆå‚™çš„</t>
    <t id="6103">ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°ä¸­å¿ƒ</t>
    <t id="6104">é‡é˜²å¾¡</t>
    <t id="6105">ã‚¿ãƒ¯ãƒ¼ã‚µãƒãƒ¼ãƒˆ</t>
    <t id="9050">è„…å¨å›žé¿ã‚·ã‚¹ãƒ†ãƒ </t>
    <t id="9051">è„…å¨å›žé¿ã‚’æœ‰åŠ¹ã«ã™ã‚‹:</t>
    <t id="9052">æ•µå¯¾é–¢ä¿‚ã®ã—ãã„å€¤:</t>
    <t id="9053">å‹•çš„ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‚’ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9151">ãƒ¬ãƒ™ãƒ« 6 ä»¥ä¸Šã®ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã¯æ•µå¯¾çš„ãªèˆ¹ã‚’ç™ºè¦‹ã—ã€å±é™ºãªãƒ«ãƒ¼ãƒˆã‚’å›žé¿ã—ã¾ã™ã€‚ç„¡åŠ¹ã«ã™ã‚‹ã¨ã™ã¹ã¦ã®ã‚¹ã‚­ãƒ£ãƒ³ãŒåœæ­¢ã—ã¾ã™ (ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ãŒå‘ä¸Šã—ã¾ã™)ã€‚æŒ‡æ®è¡Œå‹•ã«ãŠã‘ã‚‹èˆ¹èˆ¶ã”ã¨ã®ãƒªã‚¹ã‚¯è¨±å®¹åº¦ (0 ï½ž 10 ã‚¹ã‚±ãƒ¼ãƒ«)ã€‚</t>
    <t id="9152">ã“ã®å€¤ä»¥ä¸‹ã®é–¢ä¿‚ã‚’æŒã¤æ´¾é–¥ã®ã¿ã‚’è„…å¨ã¨ã—ã¦ãƒ•ãƒ©ã‚°ã‚’ç«‹ã¦ã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: -20%</t>
    <t id="9153">å±é™ºãªã‚»ã‚¯ã‚¿ãƒ¼ï¼ˆè„…å¨ãƒ¬ãƒ™ãƒ« 3 ä»¥ä¸Šï¼‰ã‚’è‡ªå‹•çš„ã«ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã—ã€èˆ¹èˆ¶ã«è„…å¨ã‚’å›žé¿ã•ã›ã¾ã™ã€‚ä»£æ›¿ãƒ«ãƒ¼ãƒˆã«ã¯ãƒãƒ‹ãƒ©ã®ãƒ‘ã‚¹ãƒ•ã‚¡ã‚¤ãƒ³ãƒ‡ã‚£ãƒ³ã‚°ã‚’ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9060">é˜²å¾¡è£…å‚™ã®è‡ªå‹•è£œå……ï¼ˆãƒ¬ãƒ™ãƒ«15ï¼‰</t>
    <t id="9061">è‡ªå‹•è£œå……ã‚’æœ‰åŠ¹ã«ã™ã‚‹:</t>
    <t id="9062">å†å…¥è·å¯¾ç­–ï¼š</t>
    <t id="9063">é˜²è¡›ãƒ‰ãƒ­ãƒ¼ãƒ³ã‚’å†å…¥è·:</t>
    <t id="9064">è²¿æ˜“ç”¨ãƒ‰ãƒ­ãƒ¼ãƒ³ã‚’å†å…¥è·:</t>
    <t id="9065">ãƒ¬ãƒ¼ã‚¶ãƒ¼ã‚¿ãƒ¯ãƒ¼ã‚’å†å…¥è·:</t>
    <t id="9066">ä¿®ç†ç”¨ãƒ‰ãƒ­ãƒ¼ãƒ³ã‚’å†å…¥è·:</t>
    <t id="9067">å¯¾ç­–é–¾å€¤ï¼š</t>
    <t id="9068">çµ±åˆå®¹é‡ã®ã—ãã„å€¤:</t>
    <t id="9069">æ©Ÿå™¨ãƒãƒ©ãƒ³ã‚¹ãƒ—ãƒ­ãƒ•ã‚¡ã‚¤ãƒ«:</t>
    <t id="9161">ãƒžã‚¹ã‚¿ãƒ¼ ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ (ãƒ¬ãƒ™ãƒ« 15) ã¯ã€å–å¼•å¾Œã«é˜²å¾¡è£…å‚™ã‚’è‡ªå‹•çš„ã«è£œå……ã—ã¾ã™ã€‚éƒ¨ä¸‹ã®æŒ‡æ®å®˜ãƒ¬ãƒ™ãƒ«ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚</t>
    <t id="9162">ã™ã¹ã¦ã®ç™ºé€ (S/M/L/XL)ã€‚ç‹¬ç«‹ã—ãŸå®¹é‡ã€‚ãƒŸã‚µã‚¤ãƒ«é˜²è¡›ã«ä¸å¯æ¬ ã€‚</t>
    <t id="9163">L/XLã®ã¿ã®ç™ºé€ã¨ãªã‚Šã¾ã™ã€‚çµ±åˆã•ã‚ŒãŸå®¹é‡ã‚’ä»–ã®å±•é–‹å¯èƒ½ãªã‚‚ã®ã¨å…±æœ‰ã—ã¾ã™ã€‚</t>
    <t id="9164">L/XLã®ã¿ã®ç™ºé€ã¨ãªã‚Šã¾ã™ã€‚å–å¼•æ¥­å‹™ã«ã¯å¿…é ˆã§ã™ã€‚çµ±åˆã•ã‚ŒãŸå®¹é‡ã‚’å…±æœ‰ã—ã¾ã™ã€‚</t>
    <t id="9165">ã™ã¹ã¦ã®èˆ¹ã€‚ L/XL èˆ¹ã¯çµ±ä¸€ã•ã‚ŒãŸå®¹é‡ã‚’å…±æœ‰ã—ã€S/M ã¯è²¨ç‰©ã‚’ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9166">L/XLã®ã¿ã®ç™ºé€ã¨ãªã‚Šã¾ã™ã€‚è‡ªå‹•ä¿®å¾©ã‚·ã‚¹ãƒ†ãƒ ã§å‹•ä½œã—ã¾ã™ã€‚çµ±åˆã•ã‚ŒãŸå®¹é‡ã‚’å…±æœ‰ã—ã¾ã™ã€‚</t>
    <t id="9167">å¯¾ç­–ãŒã“ã®ãƒ‘ãƒ¼ã‚»ãƒ³ãƒ†ãƒ¼ã‚¸ã‚’ä¸‹å›žã£ãŸå ´åˆã¯è£œå……ã—ã¾ã™ (ã™ã¹ã¦ã®èˆ¹ã€å€‹åˆ¥ã®å®¹é‡)ã€‚</t>
    <t id="9168">å±•é–‹å¯èƒ½ãªç·é‡ãŒã“ã®å‰²åˆã‚’ä¸‹å›žã£ãŸå ´åˆã«è£œå……ã—ã¾ã™ (L/XL èˆ¹: ãƒ‰ãƒ­ãƒ¼ãƒ³ + ã‚¿ãƒ¯ãƒ¼ãŒ 1 ã¤ã®å®¹é‡ã‚’å…±æœ‰ã—ã¾ã™)ã€‚</t>
    <t id="9169">çµ±ä¸€èƒ½åŠ›ã®åˆ†å¸ƒ (L/XL èˆ¹): è²¿æ˜“é‡è¦– (20/50/20/10)ã€ãƒãƒ©ãƒ³ã‚¹åž‹ (35/35/20/10)ã€é˜²å¾¡åž‹ (50/20/20/10)ã€é‡é˜²å¾¡åž‹ (40/30/20/10)ã€ã‚¿ãƒ¯ãƒ¼ã‚µãƒãƒ¼ãƒˆ (30/30/30/10)ã€‚æ¯”çŽ‡: é˜²å¾¡/è²¿æ˜“/ã‚¿ãƒ¯ãƒ¼/ä¿®ç†ã€‚ã‚¯ãƒªãƒƒã‚¯ã—ã¦ã‚ªãƒ—ã‚·ãƒ§ãƒ³ã‚’é †ç•ªã«åˆ‡ã‚Šæ›¿ãˆã¾ã™ã€‚</t>
    <t id="9090">èˆ¹ã®æ”¹é€ </t>
    <t id="9091">èˆ¹ã®æ”¹é€ ã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="9191">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãƒ¬ãƒ™ãƒ«ã«åŸºã¥ã„ã¦èˆ¹ã¨ã‚¨ãƒ³ã‚¸ãƒ³ã®ä¿®æ­£ã‚’è‡ªå‹•çš„ã«ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã—ã¾ã™ã€‚ãƒ¬ãƒ™ãƒ« 9+ = ãƒ¬ãƒ™ãƒ« 1 æ”¹é€ ã€ãƒ¬ãƒ™ãƒ« 12+ = ãƒ¬ãƒ™ãƒ« 2 æ”¹é€ ã€ãƒ¬ãƒ™ãƒ« 15+ = ãƒ¬ãƒ™ãƒ« 3 æ”¹é€ ã€‚æ³¨æ–‡ãŒã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã‚‹ã¨ã€GT ã§ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã•ã‚ŒãŸ MOD ã®ã¿ãŒå‰Šé™¤ã•ã‚Œã¾ã™ã€‚</t>
    <t id="9070">èˆ¹èˆ¶ã®å‘½åè¨­å®š</t>
    <t id="9071">XP ã‚’è¡¨ç¤º:</t>
    <t id="9072">è¡¨ç¤ºãƒ©ãƒ³ã‚¯ï¼š</t>
    <t id="9073">è¡¨ç¤ºãƒ¬ãƒ™ãƒ«:</t>
    <t id="9074">è¡¨ç¤ºã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹:</t>
    <t id="9075">èˆ¹ã®åå‰å¤‰æ›´ã‚’æœ‰åŠ¹ã«ã™ã‚‹:</t>
    <t id="9076">ãƒ—ãƒ¬ãƒ•ã‚£ãƒƒã‚¯ã‚¹</t>
    <t id="9077">ã‚µãƒ•ã‚£ãƒƒã‚¯ã‚¹</t>
    <t id="9078">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆåã®ã‚½ãƒ¼ã‚¹:</t>
    <t id="9079">ãƒ¢ãƒ‡ãƒ«å</t>
    <t id="9080">åž‹å</t>
    <t id="9081">ãƒ¢ãƒ‡ãƒ«ãƒ™ãƒ¼ã‚¹</t>
    <t id="9083">ã‚«ã‚¹ã‚¿ãƒ å</t>
    <t id="9084">ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã‚’è¡¨ç¤º:</t>
    <t id="9085">å‘½åãƒ¢ãƒ¼ãƒ‰:</t>
    <t id="9086">ãƒ¬ã‚¬ã‚·ãƒ¼</t>
    <t id="9087">ãƒ‘ã‚¿ãƒ¼ãƒ³</t>
    <t id="9088">åç§°ãƒ‘ã‚¿ãƒ¼ãƒ³:</t>
    <t id="9089">ãƒ—ãƒ¬ãƒ¼ã‚¹ãƒ›ãƒ«ãƒ€: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}ã€‚å€‹åˆ¥: {RS} {CB} {BL} ãªã©ã€‚ä¸‹ã®çŠ¶æ…‹ç•¥ç§°ã‚’ä½¿ç”¨ã€‚ç©ºã®ãƒˆãƒ¼ã‚¯ãƒ³ã¯çœç•¥ã€ä½™åˆ†ãªç©ºç™½ã¯åœ§ç¸®ã€‚æœ€å¤§128æ–‡å­—ã€‚</t>
    <t id="9183">è¨­å®šã•ã‚ŒãŸãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã‚’èˆ¹åã«è¡¨ç¤ºï¼ˆæŽ¥é ­è¾žã¾ãŸã¯æŽ¥å°¾è¾žï¼‰ã€‚</t>
    <t id="9184">ãƒ¬ã‚¬ã‚·ãƒ¼é…ç½®ã®ä»£ã‚ã‚Šã« {TOKEN} ãƒ—ãƒ¬ãƒ¼ã‚¹ãƒ›ãƒ«ãƒ€ã§èˆ¹åã‚’æ§‹æˆã€‚GalaxyTrader XP ãŒå¿…è¦ï¼ˆãƒãƒ‹ãƒ©XPãƒ¢ãƒ¼ãƒ‰ä¸å¯ï¼‰ã€‚</t>
    <t id="9092">ãƒ‘ã‚¿ãƒ¼ãƒ³ã®ãƒ—ãƒ¬ãƒ¼ã‚¹ãƒ›ãƒ«ãƒ€</t>
    <t id="9093">èˆ¹: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT XPï¼ˆMODï¼‰: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">ãƒãƒ‹ãƒ©: {MGMT} {PILOTSKILL}</t>
    <t id="9096">æ‹ ç‚¹: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">ä¹—çµ„: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">ã‚»ã‚¯ã‚¿ãƒ¼: {SECTOR} | çµ±è¨ˆ: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">çŠ¶æ…‹ãƒˆãƒ¼ã‚¯ãƒ³:</t>
    <t id="9100">{OPSTATE}: æœ‰åŠ¹ãªé‹ç”¨ãƒ•ãƒ©ã‚°ã‚’ã™ã¹ã¦çµåˆï¼ˆä¾‹: CB RS, MTï¼‰</t>
    <t id="9101">{STATUS}: ãƒ–ãƒ­ãƒƒã‚¯ã€è¨“ç·´ã€ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯ã€å­¤ç«‹</t>
    <t id="9102">{CB}: ã‚«ã‚¹ã‚¿ãƒ BLã®ã¿, {OPSTATE}ã«å«ã¾ã‚Œã‚‹, ä½µç”¨ä¸å¯</t>
    <t id="9082">èˆ¹ç´šã®è¡¨ç¤º:</t>
    <t id="9171">èˆ¹åã«XPå€¤ã‚’è¡¨ç¤º</t>
    <t id="9175">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆæƒ…å ±ã«ã‚ˆã‚‹èˆ¹ã®è‡ªå‹•åå‰å¤‰æ›´ã‚’æœ‰åŠ¹ã¾ãŸã¯ç„¡åŠ¹ã«ã™ã‚‹</t>
    <t id="9172">è‰¦åã«éšŽç´šç§°å·ã‚’è¡¨ç¤º</t>
    <t id="9173">èˆ¹åã«ãƒ¬ãƒ™ãƒ«ç•ªå·ã‚’è¡¨ç¤º</t>
    <t id="9174">è²¿æ˜“çŠ¶æ³ã‚’èˆ¹åã§è¡¨ç¤º</t>
    <t id="9178">å‡ºè·ãƒ™ãƒ¼ã‚¹åã®ã‚½ãƒ¼ã‚¹ã‚’é¸æŠžã—ã¾ã™: ãƒ¢ãƒ‡ãƒ«å (ãƒãƒªã‚¢ãƒ³ãƒˆä»˜ã)ã€ã‚¿ã‚¤ãƒ—å (æ±Žç”¨)ã€ãƒ¢ãƒ‡ãƒ« ãƒ™ãƒ¼ã‚¹ (ãƒãƒªã‚¢ãƒ³ãƒˆãªã—)ã€ã¾ãŸã¯ã‚«ã‚¹ã‚¿ãƒ å (ä¿å­˜å)</t>
    <t id="9182">èˆ¹åã«èˆ¹ã‚¯ãƒ©ã‚¹ï¼ˆSã€Mã€Lã€XLï¼‰ã‚’è¡¨ç¤º</t>
    <t id="9200">ãƒ‡ãƒãƒƒã‚°è¨­å®š</t>
    <t id="9201">ãƒ‡ãƒãƒƒã‚°ãƒ­ã‚°ã‚’æœ‰åŠ¹ã«ã—ã¾ã™ã€‚</t>
    <t id="9202">ã™ã¹ã¦ã® debug_text å‡ºåŠ›ã®ãƒžã‚¹ã‚¿ãƒ¼åˆ‡ã‚Šæ›¿ãˆã€‚ç„¡åŠ¹ã«ã™ã‚‹ã¨ã€ã™ã¹ã¦ã®ãƒ‡ãƒãƒƒã‚° ãƒ­ã‚°ãŒæŠ‘åˆ¶ã•ã‚Œã¾ã™ã€‚æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€å€‹ã€…ã® debug_text ãƒãƒ£ãƒ³ã‚¹å€¤ã«åŸºã¥ã„ã¦ãƒ‡ãƒãƒƒã‚° ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ãŒ DebugLog ã«è¡¨ç¤ºã•ã‚Œã¾ã™ã€‚</t>
    <t id="9220">ãƒ¡ãƒ³ãƒ†ãƒŠãƒ³ã‚¹ã¨è¨ºæ–­</t>
    <t id="9221">åˆ©ç›Šçµ±è¨ˆã®ãƒªã‚»ãƒƒãƒˆ:</t>
    <t id="9222">ãƒªã‚»ãƒƒãƒˆ</t>
    <t id="9223">ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚ŒãŸã‚»ã‚¯ã‚¿ãƒ¼ã‚’ã™ã¹ã¦ã‚¯ãƒªã‚¢ã—ã¾ã™:</t>
    <t id="9224">ã‚¯ãƒªã‚¢</t>
    <t id="9225">ã™ã¹ã¦ã®è¨­å®šã‚’ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã«ãƒªã‚»ãƒƒãƒˆã—ã¾ã™ã€‚</t>
    <t id="9226">ã™ã¹ã¦ãƒªã‚»ãƒƒãƒˆ</t>
    <t id="9323">è„…å¨ã‚¤ãƒ³ãƒ†ãƒªã‚¸ã‚§ãƒ³ã‚¹ã®ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã‹ã‚‰ã™ã¹ã¦ã®ã‚»ã‚¯ã‚¿ãƒ¼ã‚’å‰Šé™¤ã—ã¾ã™ã€‚ã“ã‚Œã«ã‚ˆã‚Šã€ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚ŒãŸã™ã¹ã¦ã®ã‚»ã‚¯ã‚¿ãƒ¼ãŒå³åº§ã«ã‚¯ãƒªã‚¢ã•ã‚Œã€ä»¥å‰ã«ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¦ã„ãŸåœ°åŸŸã¸ã®èˆ¹èˆ¶ã®èˆªè¡ŒãŒå¯èƒ½ã«ãªã‚Šã¾ã™ã€‚è„…å¨å›žé¿ã‚·ã‚¹ãƒ†ãƒ ã‚’ãƒªã‚»ãƒƒãƒˆã™ã‚‹å ´åˆã€ã¾ãŸã¯ã‚»ã‚¯ã‚¿ãƒ¼ãŒèª¤ã£ã¦ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆã«ç™»éŒ²ã•ã‚ŒãŸå ´åˆã«ã“ã‚Œã‚’ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9321">ã™ã¹ã¦ã®ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¨èˆ¹èˆ¶ã®åˆ©ç›Šçµ±è¨ˆã‚’ã™ã¹ã¦ 0 ã«ãƒªã‚»ãƒƒãƒˆã—ã¾ã™ã€‚ v0.6.0 ã«ã‚¢ãƒƒãƒ—ã‚°ãƒ¬ãƒ¼ãƒ‰ã—ãŸå¾Œã«ã“ã‚Œã‚’ä½¿ç”¨ã—ã¦ã€æ°´å¢—ã—ã•ã‚ŒãŸåŽç›Šãƒ™ãƒ¼ã‚¹ã®çµ±è¨ˆã‚’ã‚¯ãƒªã‚¢ã—ã¾ã™ã€‚ã“ã®ä¿®æ­£ã«ã‚ˆã‚Šã€å®Ÿéš›ã® PROFIT (åŽç›Š - è³¼å…¥ã‚³ã‚¹ãƒˆ) ãŒè¿½è·¡ã•ã‚Œã‚‹ã‚ˆã†ã«ãªã‚Šã¾ã—ãŸã€‚å–å¼•æ•°ã¨ XP ã¯ä¿æŒã•ã‚Œã¾ã™ã€‚</t>
    <t id="9325">ã™ã¹ã¦ã®ã‚°ãƒ­ãƒ¼ãƒãƒ«è¨­å®šã‚’ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆå€¤ã«ãƒªã‚»ãƒƒãƒˆã—ã¾ã™ã€‚ã“ã‚Œã«ã¯ã€XP è¨­å®šã€ãƒ•ãƒªãƒ¼ãƒˆèª¿æ•´ã€é€šçŸ¥ã€ãƒ¢ãƒã‚¤ãƒ« ã‚¤ãƒ³ãƒ†ãƒ«ã€è„…å¨å›žé¿ã€èˆ¹èˆ¶ã®å‘½åã€è‡ªå‹•ä¿®å¾©ã€å¤‰æ›´ã€ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã€ãŠã‚ˆã³ç•ªå·å½¢å¼ã®è¨­å®šãŒå«ã¾ã‚Œã¾ã™ã€‚ãƒ‡ãƒãƒƒã‚° ãƒ­ã‚°è¨­å®šã¯ä¿æŒã•ã‚Œã€ãƒªã‚»ãƒƒãƒˆæ“ä½œã®ãƒ­ã‚°ã‚’è¨˜éŒ²ã§ãã‚‹ã‚ˆã†ã«ãªã‚Šã¾ã™ã€‚</t>
    <t id="9227">ã™ã¹ã¦ã®å®¶åº­éƒ¨é–€ã®è²¿æ˜“ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã‚’ã‚¯ãƒªã‚¢:</t>
    <t id="9228">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã®ã‚¯ãƒªã‚¢</t>
    <t id="9327">ã™ã¹ã¦ã®ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã®å–å¼•ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã‚’ã‚¯ãƒªã‚¢ã—ã¾ã™ã€‚ã“ã‚Œã«ã‚ˆã‚Šã€ã™ã¹ã¦ã®èˆ¹èˆ¶ãŒæ¬¡å›žã®è²¿æ˜“æŽ¢ç´¢ã§æ–°ãŸãªãƒ©ã‚¤ãƒ–æŽ¢ç´¢ã‚’å®Ÿè¡Œã™ã‚‹ã“ã¨ãŒå¼·åˆ¶ã•ã‚Œã¾ã™ã€‚ã‚­ãƒ£ãƒƒã‚·ãƒ¥ãŒå¤ã„ã‹å£Šã‚Œã¦ã„ã‚‹ã¨æ€ã‚ã‚Œã‚‹å ´åˆã€ã¾ãŸã¯ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã‚’å®Œå…¨ã«æ›´æ–°ã™ã‚‹å¿…è¦ãŒã‚ã‚‹å ´åˆã¯ã€ã“ã‚Œã‚’ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9229">ã™ã¹ã¦ã®æ¤œç´¢ãƒ­ãƒƒã‚¯ã‚’è§£é™¤ã™ã‚‹</t>
    <t id="9329">ã™ã¹ã¦ã®é€²è¡Œä¸­ã®å–å¼•æ¤œç´¢ãƒ­ãƒƒã‚¯ã‚’è§£æ”¾ã—ã€é–¢é€£ã™ã‚‹ä¸€æ™‚çŠ¶æ…‹ã‚’ã‚¯ãƒªã‚¢ã—ã¾ã™ã€‚å¤ã„ã‚»ãƒ¼ãƒ–ã®ãƒ­ãƒƒã‚¯ãŒå¤ã„ãŸã‚ã€èˆ¹ãŒã€Œè²¿æ˜“ã®æ¤œç´¢ã€ã§ã‚¹ã‚¿ãƒƒã‚¯ã—ã¦ã„ã‚‹å ´åˆã«ã“ã‚Œã‚’ä½¿ç”¨ã—ã¾ã™ã€‚ã“ã‚Œã«ã‚ˆã‚Šã€æ­£å½“ãªæ¤œç´¢ãŒä¸­æ–­ã•ã‚Œã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚</t>
    <t id="9290">ãƒ€ãƒ³ãƒ—ãƒˆãƒ¬ãƒ¼ãƒ‰ãƒãƒ–ã®ã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹:</t>
    <t id="9291">ã”ã¿</t>
    <t id="9390">é›†ä¸­è²¿æ˜“ãƒãƒ–ã®ãƒ¯ãƒ³ã‚·ãƒ§ãƒƒãƒˆ ã‚¹ãƒŠãƒƒãƒ—ã‚·ãƒ§ãƒƒãƒˆ (ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ©ãƒ¼ ã‚­ãƒ¥ãƒ¼ + æœ€å¾Œã«è¦æ±‚ã—ãŸå‡ºè·ã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹) ã‚’ãƒ­ã‚°ãŠã‚ˆã³é€šçŸ¥ã¨ã—ã¦è¡¨ç¤ºã—ã¾ã™ã€‚</t>
    <t id="9292">ãƒˆãƒ¬ãƒ¼ãƒ‰ ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã‚’ãƒ€ãƒ³ãƒ— (ãƒ•ãƒ«):</t>
    <t id="9293">ãƒ€ãƒ³ãƒ—ã‚­ãƒ£ãƒƒã‚·ãƒ¥</t>
    <t id="9392">å®Œå…¨ãªã‚­ãƒ£ãƒƒã‚·ãƒ¥ ãƒ€ãƒ³ãƒ— (å·¨å¤§ã«ãªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™)ã€‚ã™ã¹ã¦ã®ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¨ãƒ³ãƒˆãƒªã‚’ãƒãƒ£ãƒ³ã‚¯ã§ DebugLog ã«æ›¸ãè¾¼ã¿ã¾ã™ã€‚ã‚­ãƒ£ãƒ³ã‚»ãƒ«ã™ã‚‹ã«ã¯ã‚‚ã†ä¸€åº¦ã‚¯ãƒªãƒƒã‚¯ã—ã¾ã™ã€‚</t>
    <t id="9294">ãƒ•ãƒªãƒ¼ãƒˆäºˆç´„ã®ã‚¯ãƒªã‚¢:</t>
    <t id="9295">ã‚¯ãƒªã‚¢</t>
    <t id="9394">ã‚¢ã‚¯ãƒ†ã‚£ãƒ–ãªè‰¦éšŠè²¿æ˜“äºˆç´„ã‚’ã™ã¹ã¦ã‚¯ãƒªã‚¢ã—ã¾ã™ã€‚äºˆç´„ã•ã‚ŒãŸå–å¼•ã®æœ‰åŠ¹æœŸé™ãŒåˆ‡ã‚Œã‚‹ã®ã‚’å¾…ã£ã¦èˆ¹ãŒã‚¹ã‚¿ãƒƒã‚¯ã—ã¦ã„ã‚‹ã‚ˆã†ã«è¦‹ãˆã‚‹å ´åˆã€ã¾ãŸã¯å¤ã„ä¿å­˜ã‚’ãƒ­ãƒ¼ãƒ‰ã—ãŸå¾Œã«äºˆç´„ãƒ†ãƒ¼ãƒ–ãƒ«ãŒå¤ããªã£ãŸå ´åˆã«ã€ã“ã‚Œã‚’ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9230">ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹</t>
    <t id="9231">ãƒãƒƒãƒå‡¦ç†ã®é…å»¶:</t>
    <t id="9232">æ¤œè¨¼ã®é…å»¶:</t>
    <t id="9233">æœ€å¤§åŒæ™‚æ¤œç´¢æ•°:</t>
    <t id="9234">ãƒªã‚¿ãƒ¼ãƒ³ã™ã‚‹æœ€å¤§å–å¼•æ•°:</t>
    <t id="9235">ã‚¦ã‚§ã‚¢ã”ã¨ã®æœ€å¤§ã‚ªãƒ•ã‚¡ãƒ¼:</t>
    <t id="9236">ã‚¦ã‚§ã‚¢ã‚ãŸã‚Šã®æœ€å¤§å–å¼•æ•°:</t>
    <t id="9237">ãƒžãƒƒãƒãƒ³ã‚°ã®ãŸã‚ã®ã‚¦ã‚§ã‚¢ã”ã¨ã®æœ€å¤§ã‚ªãƒ•ã‚¡ãƒ¼:</t>
    <t id="9238">æ—©æœŸçµ‚äº†ã®ã—ãã„å€¤:</t>
    <t id="9241">ãƒ©ã‚¤ãƒ–ã‚ªãƒ•ã‚¡ãƒ¼ã‚¹ãƒ©ã‚¤ã‚¹é–“éš”:</t>
    <t id="9266">æ¤œç´¢ãƒ­ãƒƒã‚¯TTL:</t>
    <t id="9263">ãƒãƒƒãƒãƒãƒ£ãƒ³ã‚¯ã‚µã‚¤ã‚º:</t>
    <t id="9239">æ•°å€¤ã®å½¢å¼</t>
    <t id="9240">ãƒ•ã‚©ãƒ¼ãƒžãƒƒãƒˆã‚¹ã‚¿ã‚¤ãƒ«:</t>
    <t id="9242">M ã‚µãƒ•ã‚£ãƒƒã‚¯ã‚¹ã‚’ä½¿ç”¨ã™ã‚‹</t>
    <t id="9243">M ã‚µãƒ•ã‚£ãƒƒã‚¯ã‚¹ã®ã—ãã„å€¤:</t>
    <t id="9244">ãƒ‰ã‚¤ãƒ„èªž (123.456,78)</t>
    <t id="9245">è‹±èªž (123,456.78)</t>
    <t id="9510">ãƒ¬ãƒ™ãƒ«ã‚¢ãƒƒãƒ—ãƒãƒƒãƒ—ã‚¢ãƒƒãƒ—é€šçŸ¥:</t>
    <t id="9511">è¨“ç·´å¿…è¦ã‚¢ãƒ©ãƒ¼ãƒˆ:</t>
    <t id="9512">è¨“ç·´å®Œäº†é€šçŸ¥:</t>
    <t id="9513">åˆ©ç›Šãƒ¬ãƒãƒ¼ãƒˆ:</t>
    <t id="9514">ãƒžãƒ¼ã‚±ãƒƒãƒˆã‚¢ãƒ©ãƒ¼ãƒˆ:</t>
    <t id="9515">è‰¦éšŠã‚¢ãƒƒãƒ—ãƒ‡ãƒ¼ãƒˆ:</t>
    <t id="9516">ãƒãƒ‹ãƒ© XP ã®ã¿ã‚’ä½¿ç”¨ã—ã¦ãã ã•ã„</t>
    <t id="9610">ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼UIã§ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã®ãƒ¬ãƒ™ãƒ«ã‚¢ãƒƒãƒ—ãƒãƒƒãƒ—ã‚¢ãƒƒãƒ—é€šçŸ¥ã‚’æœ‰åŠ¹ã¾ãŸã¯ç„¡åŠ¹ã«ã—ã¾ã™ã€‚</t>
    <t id="9611">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒæ¬¡ã®ãƒ¬ãƒ™ãƒ«ã«é€²ã‚€ãŸã‚ã«è¨“ç·´ãŒå¿…è¦ãªå ´åˆã«è­¦å‘Šã—ã¾ã™ã€‚</t>
    <t id="9612">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒè¨“ç·´ã‚’å®Œäº†ã—ã¦ãƒ©ãƒ³ã‚¯ãŒä¸ŠãŒã£ãŸã¨ãã«é€šçŸ¥ã—ã¾ã™ã€‚</t>
    <t id="9613">å®šæœŸçš„ãªåˆ©ç›Šã‚µãƒžãƒªãƒ¼ï¼ˆã‚·ãƒ³ãƒ—ãƒ«ãŠã‚ˆã³åŒ…æ‹¬ãƒ¬ãƒãƒ¼ãƒˆï¼‰ã€‚</t>
    <t id="9614">ä¾‹å¤–çš„ãªãƒžãƒ¼ã‚±ãƒƒãƒˆæ©Ÿä¼šã¨é«˜ä¾¡å€¤å–å¼•ã‚¢ãƒ©ãƒ¼ãƒˆã€‚</t>
    <t id="9615">è‰¦éšŠèª¿æ•´ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã¨ã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹æ›´æ–°ã€‚</t>
    <t id="9616">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ.ã‚¹ã‚­ãƒ«.ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’ä½¿ç”¨ã—ã€GT XP ã®é€²è¡Œ/ä¸Šé™ã‚’ç„¡åŠ¹ã«ã—ã¾ã™ã€‚</t>
    <t id="9246">å˜ç´”ãªãƒ¬ãƒãƒ¼ãƒˆã®é »åº¦:</t>
    <t id="9247">åŒ…æ‹¬çš„ãªãƒ¬ãƒãƒ¼ãƒˆã®é »åº¦:</t>
    <t id="9248">æœ€å¤§åŒæ™‚ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œç´¢æ•°:</t>
    <t id="9249">æœ€å¤§åŒæ™‚ãƒ©ã‚¤ãƒ–æ¤œç´¢:</t>
    <t id="9340">æ•°å€¤å½¢å¼ã®é¸æŠž: ãƒ‰ã‚¤ãƒ„èªžã§ã¯ã€Œ.ã€ãŒä½¿ç”¨ã•ã‚Œã¾ã™ã€‚åƒã®å ´åˆã¯ã€Œ,ã€ã€å°æ•°ã®å ´åˆã¯ã€Œ,ã€(123.456,78)ã€è‹±èªžã§ã¯åƒã®å ´åˆã¯ã€Œ,ã€ã€å°æ•°ã®å ´åˆã¯ã€Œ.ã€ã‚’ä½¿ç”¨ã—ã¾ã™ã€‚å°æ•°ã®å ´åˆ (123,456.78)</t>
    <t id="9342">ã—ãã„å€¤ã‚ˆã‚Šå¤§ãã„æ•°å€¤ã«å¯¾ã—ã¦ M ã‚µãƒ•ã‚£ãƒƒã‚¯ã‚¹ã‚’æœ‰åŠ¹ã«ã—ã¾ã™ (ä¾‹: 1,000,000 ã®ä»£ã‚ã‚Šã« 1.0 M)</t>
    <t id="9343">M ã‚µãƒ•ã‚£ãƒƒã‚¯ã‚¹ã®ã—ãã„å€¤ã€‚ã“ã®å€¤ã‚’è¶…ãˆã‚‹æ•°å€¤ã¯ M ã¨ã„ã†æŽ¥å°¾è¾žã‚’ä»˜ã‘ã¦è¡¨ç¤ºã•ã‚Œã¾ã™ (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 999,999)</t>
    <t id="9346">ç°¡æ˜“ãƒ¬ãƒãƒ¼ãƒˆ (ãƒãƒƒãƒ—ã‚¢ãƒƒãƒ—é€šçŸ¥) ã®é »åº¦: 0 ï½ž 30 åˆ† (0 = ç„¡åŠ¹ - ç°¡æ˜“ãƒ¬ãƒãƒ¼ãƒˆã¯ç„¡åŠ¹ã€ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1 åˆ†)</t>
    <t id="9347">åŒ…æ‹¬çš„ãªãƒ¬ãƒãƒ¼ãƒˆã®é »åº¦ (ãƒ­ã‚°ãƒ–ãƒƒã‚¯ã®ã‚¨ãƒ³ãƒˆãƒª): 0 ï½ž 60 åˆ† (0 = ç„¡åŠ¹ - åŒ…æ‹¬çš„ãªãƒ¬ãƒãƒ¼ãƒˆã¯ç„¡åŠ¹ã€ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 30 åˆ†)</t>
    <t id="9398">ã‚ªãƒ¼ãƒãƒ¼ãƒ©ã‚¤ãƒ‰ã«ã‚ˆã‚‹ GT ã‚¯ãƒ¬ã‚¸ãƒƒãƒˆã®ä½¿ç”¨</t>
    <t id="9399">ãƒãƒ‹ãƒ©ã®ã€ŒCR due from tradesã€è¡Œã‚’ã€åŒã˜ UI ã‚¹ãƒ­ãƒƒãƒˆã® GT äºˆæ¸¬å€¤ã«ç½®ãæ›ãˆã‚‹ã‹ã€è¿½åŠ ã—ã¾ã™ã€‚</t>
    <t id="9331">å–å¼•æ¤œç´¢å‡¦ç†ä¸­ã®ãƒãƒƒãƒé–“ã®é…å»¶ (1 ï½ž 500 ãƒŸãƒªç§’)ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€å–å¼•æ¤œç´¢ãŒé…ããªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 120msã€‚ãƒãƒƒãƒãƒ—ãƒ­ã‚»ãƒƒã‚µãŠã‚ˆã³å–å¼•ãƒªã‚¹ãƒˆã®ãƒ•ã‚£ãƒ«ã‚¿ãƒªãƒ³ã‚°ã§ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚</t>
    <t id="9332">AI ã‚¹ã‚¯ãƒªãƒ—ãƒˆã§ã®å–å¼•æ¤œè¨¼é–“ã®é…å»¶ (1 ï½ž 500 ãƒŸãƒªç§’)ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€å–å¼•ã®æ¤œè¨¼ãŒé…ããªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 50msã€‚ MDã‚·ã‚¹ãƒ†ãƒ ã‹ã‚‰ãƒˆãƒ¬ãƒ¼ãƒ‰ãƒªã‚¹ãƒˆã‚’æ¤œè¨¼ã™ã‚‹éš›ã«ä½¿ç”¨ã—ã¾ã™ã€‚</t>
    <t id="9333">åŒæ™‚ã«å®Ÿè¡Œã§ãã‚‹å–å¼•æ¤œç´¢ã®æœ€å¤§æ•° (1 ï½ž 10)ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€ã‚­ãƒ¥ãƒ¼ã®å¾…æ©Ÿæ™‚é–“ãŒå¢—åŠ ã—ã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨æ¤œç´¢ã®å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ãŒæ€¥ä¸Šæ˜‡ã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9334">ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œç´¢ã‹ã‚‰è¿”ã•ã‚Œã‚‹å–å¼•ã®æœ€å¤§æ•° (1 ï½ž 100)ã€‚å€¤ãŒå¤§ãã„ã»ã©ã€ã‚ˆã‚Šå¤šãã®å–å¼•ã‚ªãƒ—ã‚·ãƒ§ãƒ³ãŒæä¾›ã•ã‚Œã¾ã™ãŒã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã®æ¤œè¨¼æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€å®Ÿè¡Œå¯èƒ½ãªå–å¼•ã‚’é€ƒã™å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 20ã€‚</t>
    <t id="9335">ãƒ©ã‚¤ãƒ–æ¤œç´¢ã§å‡¦ç†ã™ã‚‹ã‚¦ã‚§ã‚¢ã”ã¨ã®ã‚ªãƒ•ã‚¡ãƒ¼ã®æœ€å¤§æ•° (5 ï½ž 100)ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ã‚ˆã‚Šå¤šãã®ã‚ªãƒ•ã‚¡ãƒ¼ãŒè€ƒæ…®ã•ã‚Œã¾ã™ãŒã€å‡¦ç†æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€åŽç›Šæ€§ã®é«˜ã„å–å¼•ã‚’é€ƒã™å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 20ã€‚</t>
    <t id="9336">ãƒãƒƒãƒå‡¦ç†ä¸­ã®ã‚¦ã‚§ã‚¢ã”ã¨ã®æœ€å¤§å–å¼•æ•° (5 ï½ž 100)ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ã‚¦ã‚§ã‚¢ã”ã¨ã®å–å¼•ãŒå¯èƒ½ã«ãªã‚Šã¾ã™ãŒã€å‡¦ç†æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€åŽç›Šæ€§ã®é«˜ã„å–å¼•ã‚’é€ƒã™å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 20ã€‚</t>
    <t id="9337">ãƒãƒƒãƒãƒ—ãƒ­ã‚»ãƒƒã‚µã§ã®ãƒžãƒƒãƒãƒ³ã‚°ã®ãŸã‚ã®ã‚¦ã‚§ã‚¢ã”ã¨ã®ã‚ªãƒ•ã‚¡ãƒ¼ã®æœ€å¤§æ•° (5 ï½ž 100)ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ã‚ˆã‚Šå¤šãã®ã‚ªãƒ•ã‚¡ãƒ¼ãŒè€ƒæ…®ã•ã‚Œã¾ã™ãŒã€å‡¦ç†æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€åŽç›Šæ€§ã®é«˜ã„å–å¼•ã‚’é€ƒã™å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 20ã€‚</t>
    <t id="9338">ãƒãƒƒãƒå‡¦ç†ã®æ—©æœŸçµ‚äº†ã—ãã„å€¤ (100 ï½ž 10000)ã€‚ã“ã‚Œã ã‘å¤šãã®å–å¼•ãŒè¦‹ã¤ã‹ã‚‹ã¨ã€CPU ã‚’ç¯€ç´„ã™ã‚‹ãŸã‚ã«ãƒãƒƒãƒå‡¦ç†ãŒæ—©æœŸã«åœæ­¢ã•ã‚Œã¾ã™ã€‚å€¤ãŒå¤§ãã„ã»ã©ã€ã‚ˆã‚Šå¤šãã®å–å¼•ãŒå‡¦ç†ã•ã‚Œã¾ã™ãŒã€CPU è² è·ãŒå¢—åŠ ã—ã¾ã™ã€‚å€¤ãŒä½Žã„ã»ã©æ—©ãçµ‚äº†ã—ã¾ã™ãŒã€åŽç›Šæ€§ã®é«˜ã„å–å¼•ã‚’é€ƒã™å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 2000ã€‚</t>
    <t id="9341">ãƒŸãƒªç§’å˜ä½ã®ãƒ©ã‚¤ãƒ– ã‚ªãƒ•ã‚¡ãƒ¼ ã‚¹ãƒ©ã‚¤ã‚¹é–“éš” (5 ï½ž 2000 ãƒŸãƒªç§’)ã€‚ãƒ©ã‚¤ãƒ–ã‚ªãƒ•ã‚¡ãƒ¼ã‚¹ãƒ©ã‚¤ã‚¹ã‚’é–‹å§‹ã§ãã‚‹é »åº¦ã‚’åˆ¶å¾¡ã—ã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€ã‚ªãƒ•ã‚¡ãƒ¼ã®åŽé›†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€CPU è² è·ãŒå¢—åŠ ã—ã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€ãƒ©ã‚¤ãƒ–æ¤œç´¢å‡¦ç†ãŒé…ããªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 500msã€‚</t>
    <t id="9363">ãƒãƒƒãƒå‡¦ç†ã®ãƒãƒ£ãƒ³ã‚¯ ã‚µã‚¤ã‚º (5 ï½ž 20)ã€‚ãƒãƒ£ãƒ³ã‚¯ã”ã¨ã« chunkSizeÃ—chunkSize ã®çµ„ã¿åˆã‚ã›ã‚’å‡¦ç†ã—ã¾ã™ (ä¾‹: 5Ã—5 = 25 å€‹ã®çµ„ã¿åˆã‚ã›)ã€‚ãƒãƒ£ãƒ³ã‚¯ãŒå¤§ãããªã‚‹ã¨ã‚¹ãƒ«ãƒ¼ãƒ—ãƒƒãƒˆã¯å‘ä¸Šã—ã¾ã™ãŒã€ãƒãƒ£ãƒ³ã‚¯ã‚ãŸã‚Šã® CPU è² è·ãŒå¢—åŠ ã—ã¾ã™ã€‚ãƒãƒ£ãƒ³ã‚¯ãŒå°ã•ã„ã¨ CPU ã®ã‚¹ãƒ‘ã‚¤ã‚¯ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€ã‚ˆã‚Šå¤šãã®ç¶™ç¶šãŒå¿…è¦ã«ãªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 5ã€‚</t>
    <t id="9348">åŒæ™‚ã«å®Ÿè¡Œã§ãã‚‹ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œç´¢ã®æœ€å¤§æ•° (1 ï½ž 20)ã€‚ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œç´¢ã¯é«˜é€Ÿã‹ã¤å®‰ä¾¡ã§ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€å·¨å¤§ãªãƒ•ãƒªãƒ¼ãƒˆã®ä¸‹ã§ã®ãƒãƒ¼ã‚¹ãƒˆæ€§ãŒè»½æ¸›ã•ã‚Œã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 2ã€‚</t>
    <t id="9349">åŒæ™‚ã«å®Ÿè¡Œã§ãã‚‹ãƒ©ã‚¤ãƒ–æ¤œç´¢ã®æœ€å¤§æ•° (1 ï½ž 10)ã€‚ãƒ©ã‚¤ãƒ–æ¤œç´¢ã¯ CPU ã‚’å¤§é‡ã«ä½¿ç”¨ã™ã‚‹ãŸã‚ã€å€¤ã‚’ä½Žãã™ã‚‹ã¨ CPU è² è·ã¯è»½æ¸›ã•ã‚Œã¾ã™ãŒã€ã‚­ãƒ¥ãƒ¼ã®å¾…æ©Ÿæ™‚é–“ã¯é•·ããªã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨æ¤œç´¢ã®å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ãŒæ€¥ä¸Šæ˜‡ã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9264">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¯ã‚¨ãƒª ãƒãƒ£ãƒ³ã‚¯ ã‚µã‚¤ã‚º:</t>
    <t id="9265">ãƒ©ã‚¤ãƒ– ã‚ªãƒ•ã‚¡ãƒ¼è¿½åŠ ãƒãƒ£ãƒ³ã‚¯ ã‚µã‚¤ã‚º:</t>
    <t id="9364">ãƒãƒ£ãƒ³ã‚¯ã”ã¨ã«æ¤œè¨¼ã•ã‚Œã‚‹ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¨ãƒ³ãƒˆãƒª (10 ï½ž 200)ã€‚å€¤ãŒå°ã•ã„ã»ã©ã€ã‚ˆã‚Šå¤šãã®ãƒ•ãƒ¬ãƒ¼ãƒ ã«ã‚ãŸã£ã¦ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œè¨¼ãŒåˆ†æ•£ã•ã‚Œã¾ã™ (ã‚¹ãƒ ãƒ¼ã‚ºã«ãªã‚Šã¾ã™) ãŒã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚ŒãŸå–å¼•ã‚’è¦‹ã¤ã‘ã‚‹ã¾ã§ã®æ™‚é–“ãŒé•·ããªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 10ã€‚</t>
    <t id="9365">ã‚ªãƒ•ã‚¡ãƒ¼ã¯è¿½åŠ ã‚¹ãƒ©ã‚¤ã‚¹ã”ã¨ã«è¿½åŠ ã•ã‚Œã¾ã™ (50 ï½ž 2000)ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€ãƒ•ãƒ¬ãƒ¼ãƒ ã”ã¨ã®ãƒªã‚¹ãƒˆè¿½åŠ ä½œæ¥­ãŒè»½æ¸›ã•ã‚Œ (ã‚¹ãƒ ãƒ¼ã‚ºã«ãªã‚Šã¾ã™)ã€ãƒ©ã‚¤ãƒ–æ¤œç´¢ã®å®Œäº†ãŒé…ããªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 200ã€‚</t>
    <t id="9366">æ¤œç´¢ãƒ­ãƒƒã‚¯ã®æœ‰åŠ¹æœŸé™ (ç§’å˜ä½) (60 ï½ž 7200)ã€‚ã“ã‚Œã‚ˆã‚Šé•·ãã€Œè²¿æ˜“æ¤œç´¢ãŒã™ã§ã«é€²è¡Œä¸­ã€ã¨ã—ã¦èˆ¹ãŒæ‹’å¦ã•ã‚ŒãŸå ´åˆã€GT ã¯å¤ã„æ¤œç´¢çŠ¶æ…‹ã‚’ã‚¯ãƒªã‚¢ã—ã¦ãƒ­ãƒƒã‚¯ã‚’è§£æ”¾ã™ã‚‹ã“ã¨ã§è‡ªå·±ä¿®å¾©ã—ã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 600 ç§’ã€‚</t>
    <t id="9370">ãƒãƒƒãƒãƒãƒƒã‚¯ãƒ—ãƒ¬ãƒƒã‚·ãƒ£ãƒ¼ã®ã‚½ãƒ•ãƒˆã—ãã„å€¤:</t>
    <t id="9371">ãƒãƒƒãƒãƒãƒƒã‚¯ãƒ—ãƒ¬ãƒƒã‚·ãƒ£ãƒ¼ã®ãƒãƒ¼ãƒ‰ã—ãã„å€¤:</t>
    <t id="9372">ã‚¹ãƒ©ã‚¤ã‚¹ã‚ãŸã‚Šã®ã‚»ã‚¯ã‚¿ãƒ¼æ•°:</t>
    <t id="9373">ãƒ›ãƒ¼ãƒ ãƒªãƒ•ãƒ¬ãƒƒã‚·ãƒ¥ã‚¯ãƒ¼ãƒ«ãƒ€ã‚¦ãƒ³:</t>
    <t id="9374">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ãƒŸã‚¹ã‚¯ãƒ¼ãƒ«ãƒ€ã‚¦ãƒ³ãƒ™ãƒ¼ã‚¹:</t>
    <t id="9375">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ©ã®ãƒ†ã‚£ãƒƒã‚¯é–“éš”:</t>
    <t id="9376">ãƒ†ã‚£ãƒƒã‚¯ã‚ãŸã‚Šã®æœ€å¤§ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¯ã‚¨ãƒªæ•°:</t>
    <t id="9377">ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã®æœ€å¤§æ¤œç´¢ç¶™ç¶šæ•°:</t>
    <t id="9378">ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã®æœ€å¤§å‡ºè·æ•°:</t>
    <t id="9379">ãƒ†ã‚£ãƒƒã‚¯ã‚ãŸã‚Šã®æœ€å¤§ã‚¢ã‚¤ãƒ†ãƒ æ•°:</t>
    <t id="9380">ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã®æœ€å¤§ã‚¦ã‚§ã‚¤ã‚¯:</t>
    <t id="9381">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¯ã‚¨ãƒªã®æœ€å¤§ã‚¨ãƒ³ãƒˆãƒªæ•°:</t>
    <t id="9382">å¤ã„ã—ãã„å€¤ç§’:</t>
    <t id="9383">ã‚­ãƒ¥ãƒ¼ã®å¤ã„ã—ãã„å€¤ç§’:</t>
    <t id="9384">å¤±æ•—ã—ãŸå–å¼•ã®æœ‰åŠ¹æœŸé™ç§’:</t>
    <t id="9385">æœ€å¤§åŒæ™‚ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢:</t>
    <t id="9386">æœ€å¤§åŒæ™‚ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢:</t>
    <t id="9470">ãƒãƒƒãƒ ãƒ—ãƒ­ã‚»ãƒƒã‚µ ãƒãƒƒã‚¯ãƒ­ã‚°ã®ã‚½ãƒ•ãƒˆã—ãã„å€¤ (5 ï½ž 50)ã€‚ãƒãƒƒã‚¯ãƒ­ã‚°ãŒã“ã®å€¤ã«é”ã™ã‚‹ã¨ã€æ–°ã—ã„æ¤œç´¢ãƒªã‚¯ã‚¨ã‚¹ãƒˆã‚’é…ãã™ã‚‹ãŸã‚ã«ãƒãƒƒã‚¯ãƒ—ãƒ¬ãƒƒã‚·ãƒ£ãƒ¼ãŒé©ç”¨ã•ã‚Œå§‹ã‚ã¾ã™ã€‚å€¤ãŒä½Žã„ã»ã©ã€ãƒãƒƒã‚¯ãƒ—ãƒ¬ãƒƒã‚·ãƒ£ãƒ¼ãŒã‚ˆã‚Šæ—©ããƒˆãƒªã‚¬ãƒ¼ã•ã‚Œã¾ã™ (ã‚ˆã‚ŠæŽ§ãˆã‚ã«ãªã‚Šã¾ã™)ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 10ã€‚</t>
    <t id="9471">ãƒãƒƒãƒ ãƒ—ãƒ­ã‚»ãƒƒã‚µ ãƒãƒƒã‚¯ãƒ­ã‚°ã®ãƒãƒ¼ãƒ‰ã—ãã„å€¤ (10 ï½ž 100)ã€‚ãƒãƒƒã‚¯ãƒ­ã‚°ãŒã“ã®å€¤ã«é”ã™ã‚‹ã¨ã€ãƒãƒƒã‚¯ãƒ­ã‚°ãŒæ¸›å°‘ã™ã‚‹ã¾ã§ã€æ–°ã—ã„ãƒ©ã‚¤ãƒ–æ¤œç´¢ã¯ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€æ¤œç´¢ãŒã™ãã«ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¾ã™ (ã‚ˆã‚Šä¿å®ˆçš„ã«ãªã‚Šã¾ã™)ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 25ã€‚</t>
    <t id="9472">ãƒ©ã‚¤ãƒ– ã‚ªãƒ•ã‚¡ãƒ¼ ã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ã®ã‚¹ãƒ©ã‚¤ã‚¹ã”ã¨ã«å‡¦ç†ã•ã‚Œã‚‹ã‚»ã‚¯ã‚¿ãƒ¼ (1 ï½ž 5)ã€‚å€¤ãŒå°ã•ã„ã»ã©ã€ã‚ˆã‚Šå¤šãã®ãƒ•ãƒ¬ãƒ¼ãƒ ã«ä½œæ¥­ãŒåˆ†æ•£ã•ã‚Œã¾ã™ (ã‚¹ãƒ ãƒ¼ã‚ºã«ãªã‚Šã¾ã™) ãŒã€ã‚ªãƒ•ã‚¡ãƒ¼ã®åŽé›†ãŒé…ããªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚å€¤ãŒå¤§ãã„ã»ã©å‡¦ç†ã¯é€Ÿããªã‚Šã¾ã™ãŒã€ãƒ•ãƒ¬ãƒ¼ãƒ  ã‚¹ãƒ‘ã‚¤ã‚¯ãŒç™ºç”Ÿã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9473">ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã®ãƒªãƒ•ãƒ¬ãƒƒã‚·ãƒ¥å®Œäº†å¾Œã®ã‚¯ãƒ¼ãƒ«ãƒ€ã‚¦ãƒ³ (10 ï½ž 120 ç§’)ã€‚éŽå‰°ãªãƒªãƒ•ãƒ¬ãƒƒã‚·ãƒ¥è¦æ±‚ã‚’é˜²ãŽã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€æ›´æ–°é »åº¦ãŒé«˜ããªã‚Šã¾ã™ãŒã€CPU è² è·ãŒå¢—åŠ ã—ã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨æ›´æ–°é »åº¦ãŒæ¸›ã‚Šã¾ã™ãŒã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã®æ›´æ–°ãŒé…ã‚Œã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 30 ç§’ã€‚</t>
    <t id="9474">ã‚­ãƒ£ãƒƒã‚·ãƒ¥ãƒŸã‚¹å¾Œã®ãƒ©ã‚¤ãƒ–æ¤œç´¢ã‚’å†è©¦è¡Œã™ã‚‹ã¾ã§ã®åŸºæœ¬ã‚¯ãƒ¼ãƒ«ãƒ€ã‚¦ãƒ³ (1 ï½ž 30 ç§’)ã€‚éŽå‰°ãªå†è©¦è¡Œã‚’é˜²æ­¢ã—ã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨å†è©¦è¡ŒãŒæ—©ããªã‚Šã¾ã™ãŒã€CPU è² è·ãŒå¢—åŠ ã—ã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨å†è©¦è¡Œã®é »åº¦ãŒæ¸›ã‚Šã¾ã™ãŒã€å–å¼•ã®ç™ºè¦‹ãŒé…ã‚Œã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 10ç§’ã€‚</t>
    <t id="9475">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ©ã®ãƒ†ã‚£ãƒƒã‚¯é–“ã®é–“éš” (ãƒŸãƒªç§’å˜ä½) (50 ï½ž 500 ãƒŸãƒªç§’)ã€‚ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ©ãŒä½œæ¥­ã‚­ãƒ¥ãƒ¼ã‚’å‡¦ç†ã™ã‚‹é »åº¦ã‚’åˆ¶å¾¡ã—ã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€å‡¦ç†ã®é »åº¦ãŒé«˜ããªã‚Šã¾ã™ãŒã€CPU è² è·ãŒå¢—åŠ ã—ã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€ã‚­ãƒ¥ãƒ¼ã®å¾…æ©Ÿæ™‚é–“ãŒé•·ããªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 100msã€‚</t>
    <t id="9476">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ© ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã«é–‹å§‹ã•ã‚Œã‚‹ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¯ã‚¨ãƒªã®æœ€å¤§æ•° (1 ï½ž 5)ã€‚ãƒ•ãƒ¬ãƒ¼ãƒ ã®ãƒ–ãƒ­ãƒƒã‚¯ã‚’é˜²ããŸã‚ã«ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¯ã‚¨ãƒª ãƒ¬ãƒ¼ãƒˆã‚’åˆ¶é™ã—ã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€CPU ã‚¹ãƒ‘ã‚¤ã‚¯ãŒæ¸›å°‘ã—ã¾ã™ãŒã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œç´¢ãŒé…ããªã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€é€”åˆ‡ã‚ŒãŒç™ºç”Ÿã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9477">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ© ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã«é–‹å§‹ã•ã‚Œã‚‹æ¤œç´¢ç¶™ç¶šã®æœ€å¤§æ•° (1 ï½ž 5)ã€‚ãƒ•ãƒ¬ãƒ¼ãƒ ãƒ–ãƒ­ãƒƒã‚¯ã‚’é˜²ããŸã‚ã«ç¶™ç¶šçŽ‡ã‚’åˆ¶é™ã—ã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€CPU ã‚¹ãƒ‘ã‚¤ã‚¯ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€æ¤œç´¢å‡¦ç†ãŒé…ããªã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€é€”åˆ‡ã‚ŒãŒç™ºç”Ÿã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9478">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ© ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã«å‡¦ç†ã•ã‚Œã‚‹å‡ºè·ã®æœ€å¤§æ•° (1 ï½ž 5)ã€‚ãƒ•ãƒ¬ãƒ¼ãƒ ã®ãƒ–ãƒ­ãƒƒã‚¯ã‚’é˜²ããŸã‚ã«ã€ã‚·ãƒƒãƒ—ã®å‡¦ç†é€Ÿåº¦ã‚’åˆ¶é™ã—ã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€CPU ã‚¹ãƒ‘ã‚¤ã‚¯ãŒæ¸›å°‘ã—ã¾ã™ãŒã€ã‚­ãƒ¥ãƒ¼ã®å‡¦ç†ãŒé…ããªã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€é€”åˆ‡ã‚ŒãŒç™ºç”Ÿã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9479">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ© ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã«å‡¦ç†ã•ã‚Œã‚‹ä½œæ¥­é …ç›®ã®æœ€å¤§æ•° (1 ï½ž 5)ã€‚ãƒ•ãƒ¬ãƒ¼ãƒ ã®ãƒ–ãƒ­ãƒƒã‚¯ã‚’é˜²ããŸã‚ã«ãƒ¯ãƒ¼ã‚¯ã‚¢ã‚¤ãƒ†ãƒ ã®å‡¦ç†é€Ÿåº¦ã‚’åˆ¶é™ã—ã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€CPU ã‚¹ãƒ‘ã‚¤ã‚¯ãŒæ¸›å°‘ã—ã¾ã™ãŒã€ã‚­ãƒ¥ãƒ¼ã®å‡¦ç†ãŒé…ããªã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€é€”åˆ‡ã‚ŒãŒç™ºç”Ÿã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9480">ã‚¹ã‚±ã‚¸ãƒ¥ãƒ¼ãƒ© ãƒ†ã‚£ãƒƒã‚¯ã”ã¨ã«ç›®è¦šã‚ã‚‹ã‚¦ã‚§ã‚¤ã‚¿ãƒ¼ã®æœ€å¤§æ•° (1 ï½ž 10)ã€‚ã‚¦ã‚§ã‚¤ã‚¯ ãƒ¬ãƒ¼ãƒˆã‚’åˆ¶é™ã—ã¦ã€å¤šãã®ã‚¦ã‚§ã‚¤ã‚¿ãƒ¼ãŒã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã‚‰ã‚Œã¦ã„ã‚‹å ´åˆã® CPU ã®ã‚¹ãƒ‘ã‚¤ã‚¯ã‚’é˜²ãŽã¾ã™ã€‚å€¤ã‚’ä½Žãã™ã‚‹ã¨ã€CPU ã®ã‚¹ãƒ‘ã‚¤ã‚¯ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€ã‚¦ã‚§ã‚¤ã‚¿ãƒ¼ã®å‡¦ç†ãŒé…ããªã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨å‡¦ç†ãŒé€Ÿããªã‚Šã¾ã™ãŒã€é€”åˆ‡ã‚ŒãŒç™ºç”Ÿã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 2ã€‚</t>
    <t id="9481">ãƒãƒƒãƒã”ã¨ã«ã‚¯ã‚¨ãƒªã•ã‚Œã‚‹ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¨ãƒ³ãƒˆãƒªã®æœ€å¤§æ•° (1 ï½ž 200)ã€‚ã‚­ãƒ£ãƒƒã‚·ãƒ¥ ã‚¯ã‚¨ãƒªã®ãƒãƒƒãƒ ã‚µã‚¤ã‚ºã‚’åˆ¶å¾¡ã—ã¾ã™ã€‚å€¤ãŒä½Žã„ã»ã©ã‚­ãƒ£ãƒƒã‚·ãƒ¥æ¤œç´¢ã¯é€Ÿããªã‚Šã¾ã™ãŒã€ã‚ˆã‚Šè‰¯ã„å–å¼•ã‚’é€ƒã™å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚ŒãŸå–å¼•ãŒã‚ˆã‚Šå¤šãè€ƒæ…®ã•ã‚Œã¾ã™ãŒã€æ¤œè¨¼æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 50ã€‚</t>
    <t id="9482">ãƒ©ã‚¤ãƒ–æ¤œç´¢çŠ¶æ…‹ã®å¤ã„ã—ãã„å€¤ (ç§’å˜ä½) (60 ï½ž 600)ã€‚ãƒ©ã‚¤ãƒ–æ¤œç´¢çŠ¶æ…‹ãŒã“ã‚Œã‚ˆã‚Šã‚‚å¤ã„å ´åˆã€å¤ã„ã‚‚ã®ã¨ã¿ãªã•ã‚Œã€ã‚¯ãƒªã‚¢ã•ã‚Œã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€å¤ã„çŠ¶æ…‹ãŒã‚ˆã‚Šæ—©ãã‚¯ãƒªã‚¢ã•ã‚Œã¾ã™ãŒã€æ­£å½“ãªæ¤œç´¢ãŒä¸­æ–­ã•ã‚Œã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨æ¤œç´¢æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ãŒã€å¤ã„çŠ¶æ…‹ã®ã¾ã¾ã«ãªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 300 ç§’ã€‚</t>
    <t id="9483">ã‚­ãƒ¥ãƒ¼ã‚¢ã‚¤ãƒ†ãƒ ã®å¤ã„ã—ãã„å€¤ (ç§’å˜ä½) (30 ï½ž 300)ã€‚ã‚­ãƒ¥ãƒ¼é …ç›®ãŒã“ã‚Œã‚ˆã‚Šå¤ã„å ´åˆã€ãã‚Œã‚‰ã¯å¤ã„ã¨ã¿ãªã•ã‚Œã€å‰Šé™¤ã•ã‚Œã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ã€å¤ã„ã‚¢ã‚¤ãƒ†ãƒ ãŒã™ãã«å‰Šé™¤ã•ã‚Œã¾ã™ãŒã€ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã‚‰ã‚ŒãŸæ­£å½“ãªã‚¢ã‚¤ãƒ†ãƒ ãŒå‰Šé™¤ã•ã‚Œã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã‚­ãƒ¥ãƒ¼æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ãŒã€ã‚¢ã‚¤ãƒ†ãƒ ãŒå¤ã„ã¾ã¾ã«ãªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 60 ç§’ã€‚</t>
    <t id="9484">å¤±æ•—ã—ãŸå–å¼•ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã®æœ‰åŠ¹æœŸé™ (ç§’å˜ä½) (300 ï½ž 3600)ã€‚å¤±æ•—ã—ãŸå–å¼•ã¯ã™ãã«å†è©¦è¡Œã•ã‚Œãªã„ã‚ˆã†ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã•ã‚Œã¾ã™ã€‚å€¤ãŒä½Žã„ã»ã©ã€å¤±æ•—ã—ãŸå–å¼•ã®æœ‰åŠ¹æœŸé™ãŒæ—©ããªã‚Šã¾ã™ (å†è©¦è¡Œå›žæ•°ãŒå¢—ãˆã¾ã™) ãŒã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã®åŠ¹çŽ‡ã¯ä½Žä¸‹ã—ã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ã‚­ãƒ£ãƒƒã‚·ãƒ¥ã«ã‹ã‹ã‚‹æ™‚é–“ãŒé•·ããªã‚Šã¾ã™ (å†è©¦è¡ŒãŒå°‘ãªããªã‚Šã¾ã™) ãŒã€å†è©¦è¡ŒãŒé…ã‚Œã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1800 ç§’ (30 åˆ†)ã€‚</t>
    <t id="9485">åŒæ™‚ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯ ãƒ©ã‚¤ãƒ–æ¤œç´¢ã®æœ€å¤§æ•° (1 ï½ž 10)ã€‚ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ã¯ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã®ãƒ­ãƒƒã‚¯ã‚’ãƒã‚¤ãƒ‘ã‚¹ã—ã€åŒã˜ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã®è¤‡æ•°ã®èˆ¹èˆ¶ãŒåŒæ™‚ã«æ¤œç´¢ã§ãã‚‹ã‚ˆã†ã«ã—ã¾ã™ã€‚å€¤ã‚’å°ã•ãã™ã‚‹ã¨ CPU è² è·ãŒè»½æ¸›ã•ã‚Œã¾ã™ãŒã€ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ãŒé…ããªã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ã‚ˆã‚Šå¤šãã®ä¸¦åˆ—ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯æ¤œç´¢ãŒå¯èƒ½ã«ãªã‚Šã¾ã™ãŒã€CPU ä½¿ç”¨çŽ‡ãŒå¢—åŠ ã—ã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 1ã€‚</t>
    <t id="9490">ãƒˆãƒ¬ãƒ¼ãƒ‰ãƒ•ã‚¡ã‚¦ãƒ³ãƒ‰ã‚·ã‚°ãƒŠãƒ«é…å»¶:</t>
    <t id="9590">GT_Trade_Found ã‚·ã‚°ãƒŠãƒ«ã‚’å‡ºè·ã«é€ä¿¡ã™ã‚‹ã¾ã§ã®é…å»¶ (ãƒŸãƒªç§’å˜ä½) (10 ï½ž 1000 ãƒŸãƒªç§’)ã€‚ã‚·ãƒƒãƒ—ã¯ã€é…å»¶ä¿¡å·ã‚’ã‚­ãƒ£ãƒƒãƒã™ã‚‹ãŸã‚ã«æ–°ã—ã„ãƒªã‚¯ã‚¨ã‚¹ãƒˆã‚’é€ä¿¡ã™ã‚‹å‰ã«å¸¸ã«å¾…æ©Ÿã—ã¾ã™ (è¨­å®šã•ã‚ŒãŸé…å»¶ + 5ms ãƒãƒƒãƒ•ã‚¡ãƒ¼)ã€‚å€¤ã‚’å¤§ããã™ã‚‹ã¨ã€ä¿¡å·ãŒãƒ•ãƒ¬ãƒ¼ãƒ å…¨ä½“ã«åˆ†æ•£ã•ã‚Œã€ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ãŒã‚ˆã‚Šã‚¹ãƒ ãƒ¼ã‚ºã«ãªã‚Šã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: 10msã€‚</t>
    <t id="8000">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ãƒ•ãƒªãƒ¼ãƒˆ</t>
    <t id="8001">GalaxyTrader ãƒ•ãƒªãƒ¼ãƒˆç®¡ç†ã¨ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆçµ±è¨ˆ</t>
    <t id="8002">ã™ã¹ã¦ã® GalaxyTrader ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’è¡¨ç¤ºãŠã‚ˆã³ç®¡ç†ã™ã‚‹</t>
    <t id="8100">èˆ¹ID</t>
    <t id="8101">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ</t>
    <t id="8102">èˆ¹</t>
    <t id="8103">çŠ¶æ…‹</t>
    <t id="8104">ãƒ©ãƒ³ã‚¯</t>
    <t id="8105">ãƒ¬ãƒ™ãƒ«</t>
    <t id="8106">XP</t>
    <t id="8107">ç”Ÿæ¶¯åˆ©ç›Š</t>
    <t id="8108">ä½ç½®</t>
    <t id="8109">ãƒ›ãƒ¼ãƒ ãƒ™ãƒ¼ã‚¹</t>
    <t id="8110">æœ€å¾Œã®å–å¼•</t>
    <t id="8111">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆåˆ©ç›Š</t>
    <t id="8112">èˆ¹èˆ¶ã®åˆ©ç›Š</t>
    <t id="8113">å–å¼•æ•°</t>
    <t id="8200">ãƒªãƒ•ãƒ¬ãƒƒã‚·ãƒ¥</t>
    <t id="8201">CSVã®ã‚¨ã‚¯ã‚¹ãƒãƒ¼ãƒˆ</t>
    <t id="8202">çµ±è¨ˆ</t>
    <t id="8203">è¨­å®š</t>
    <t id="8204">ãƒ˜ãƒ«ãƒ—</t>
    <t id="8205">è¿‘ã„</t>
    <t id="8300">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆå…¨å“¡</t>
    <t id="8301">ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°</t>
    <t id="8302">ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°</t>
    <t id="8303">ãƒ¡ãƒ³ãƒ†ãƒŠãƒ³ã‚¹</t>
    <t id="8304">ç·Šæ€¥</t>
    <t id="8305">åˆç´šè€…(Lv1ï½ž5)</t>
    <t id="8306">ä¸Šç´š(Lv6ï½ž11)</t>
    <t id="8307">ã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆ(Lv12ä»¥ä¸Š)</t>
    <t id="8308">ä¸Šä½ 10 äººã®åŽç›Šè€…</t>
    <t id="8350">ä¸¦ã¹æ›¿ãˆï¼š</t>
    <t id="8351">èˆ¹ID</t>
    <t id="8352">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆå</t>
    <t id="8353">èˆ¹ã®ç¨®é¡ž</t>
    <t id="8354">çŠ¶æ…‹</t>
    <t id="8355">ãƒ©ãƒ³ã‚¯</t>
    <t id="8356">ãƒ¬ãƒ™ãƒ«</t>
    <t id="8357">XP</t>
    <t id="8358">åˆ©ç›Š</t>
    <t id="8400">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¯ç™»éŒ²ã•ã‚Œã¦ã„ã¾ã›ã‚“</t>
    <t id="8401">ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã«ä¸€è‡´ã™ã‚‹ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¯ã‚ã‚Šã¾ã›ã‚“</t>
    <t id="8402">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆç·æ•°:</t>
    <t id="8403">ãƒ•ãƒªãƒ¼ãƒˆç·åˆ©ç›Š:</t>
    <t id="8404">æœ€çµ‚æ›´æ–°æ—¥:</t>
    <t id="8405">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’æ¤œç´¢...</t>
    <t id="8114">ã‚»ã‚¯ã‚¿</t>
    <t id="8320">èˆ¹åã®å¤‰æ›´</t>
    <t id="8321">ã‚«ã‚¹ã‚¿ãƒ å</t>
    <t id="8322">ã‚»ãƒƒãƒˆå</t>
    <t id="8323">ã‚¯ãƒªã‚¢ãƒãƒ¼ãƒ </t>
    <t id="8324">åå‰ãŒæ­£å¸¸ã«è¨­å®šã•ã‚Œã¾ã—ãŸ</t>
    <t id="8325">åå‰ã¯æ­£å¸¸ã«æ¶ˆåŽ»ã•ã‚Œã¾ã—ãŸ</t>
    <t id="8450">ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã«é€ä¿¡</t>
    <t id="8451">ç™»éŒ²ã‚’è§£é™¤ã™ã‚‹</t>
    <t id="8452">è²¨ç‰©ã®å¼·åˆ¶è²©å£²</t>
    <t id="8453">ä¿®ç†ã«å‡ºã™</t>
    <t id="8454">è£œçµ¦ã«é€ã‚‹</t>
    <t id="8455">ã™ã¹ã¦ã®æ³¨æ–‡ã‚’åœæ­¢ã™ã‚‹</t>
    <t id="8456">ã‚¢ã‚¯ã‚·ãƒ§ãƒ³</t>
    <t id="8500">ã‚¯ãƒªãƒƒã‚¯ã—ã¦èˆ¹IDé †ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8501">ã‚¯ãƒªãƒƒã‚¯ã—ã¦ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆåã§ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8502">ã‚¯ãƒªãƒƒã‚¯ã—ã¦èˆ¹ã®ç¨®é¡žã”ã¨ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8503">ã‚¯ãƒªãƒƒã‚¯ã—ã¦ã‚¹ãƒ†ãƒ¼ã‚¿ã‚¹é †ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8504">ã‚¯ãƒªãƒƒã‚¯ã—ã¦ãƒ©ãƒ³ã‚¯é †ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8505">ã‚¯ãƒªãƒƒã‚¯ã—ã¦ãƒ¬ãƒ™ãƒ«åˆ¥ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8506">ã‚¯ãƒªãƒƒã‚¯ã—ã¦ XP é †ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8507">ã‚¯ãƒªãƒƒã‚¯ã—ã¦ç”Ÿæ¶¯åˆ©ç›Šé †ã«ä¸¦ã¹æ›¿ãˆã¾ã™</t>
    <t id="8508">ãƒŸãƒƒã‚·ãƒ§ãƒ³ã‚·ã‚¹ãƒ†ãƒ ã‹ã‚‰ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãƒ‡ãƒ¼ã‚¿ã‚’æ›´æ–°</t>
    <t id="8509">ç¾åœ¨ã®ãƒ“ãƒ¥ãƒ¼ã‚’ CSV ãƒ•ã‚¡ã‚¤ãƒ«ã«ã‚¨ã‚¯ã‚¹ãƒãƒ¼ãƒˆ</t>
    <t id="8510">ãƒ•ãƒªãƒ¼ãƒˆã®çµ±è¨ˆã¨ã‚°ãƒ©ãƒ•ã‚’è¡¨ç¤ºã™ã‚‹</t>
    <t id="8511">ãƒ¡ãƒ‹ãƒ¥ãƒ¼è¨­å®šã‚’æ§‹æˆã™ã‚‹</t>
    <t id="8512">ãƒ˜ãƒ«ãƒ—ã¨ã‚­ãƒ¼ãƒœãƒ¼ãƒ‰ ã‚·ãƒ§ãƒ¼ãƒˆã‚«ãƒƒãƒˆã‚’è¡¨ç¤ºã™ã‚‹</t>
    <t id="8600">GalaxyTrader ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“</t>
    <t id="8601">èˆ¹ã‚’ GalaxyTrader ã«å‰²ã‚Šå½“ã¦ã¦ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’ä½œæˆã™ã‚‹ã‹ã€ãƒ‡ãƒ¼ã‚¿ãŒãƒ­ãƒ¼ãƒ‰ã•ã‚Œã‚‹ã¾ã§å¾…ã¡ã¾ã™ã€‚</t>
    <t id="9001">GT ã®åå‰å¤‰æ›´</t>
    <t id="9902">ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ã«é€ä¿¡</t>
    <t id="9903">æ‰‹å‹•ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ãŒ %1 ã®ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã‚‰ã‚Œã¾ã—ãŸã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¯ç¾åœ¨ã®ã‚µã‚¤ã‚¯ãƒ«å¾Œã«è¨“ç·´ã‚’é–‹å§‹ã—ã¾ã™ã€‚</t>
    <t id="9904">ç¾åœ¨ã®ã‚µã‚¤ã‚¯ãƒ«å¾Œã«ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ãŒã‚­ãƒ¥ãƒ¼ã«è¿½åŠ ã•ã‚Œã¾ã—ãŸ</t>
    <t id="9905">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¾ãŸã¯èˆ¹ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“</t>
    <t id="9906">è‡ªå‹•ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°ãŒæœ‰åŠ¹ã«ãªã£ã¦ã„ã¾ã™ - æ‰‹å‹•ã‚­ãƒ¥ãƒ¼ã¯å¿…è¦ã‚ã‚Šã¾ã›ã‚“</t>
    <t id="9907">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã¯è¨“ç·´ä¸­ã§ã¯ã‚ã‚Šã¾ã›ã‚“ãŒãƒ–ãƒ­ãƒƒã‚¯ã•ã‚Œã¦ã„ã¾ã™</t>
    <t id="9910">ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚°ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼</t>
    <t id="9911">è¦‹ç¿’ã„ (ãƒ¬ãƒ™ãƒ« 4) - %1 / %2</t>
    <t id="9912">ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ (ãƒ¬ãƒ™ãƒ« 7) - %1 / %2</t>
    <t id="9913">ãƒžã‚¹ã‚¿ãƒ¼ ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ (ãƒ¬ãƒ™ãƒ« 13) - %1 / %2</t>
    <t id="9920">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ %1 ã¯ã€ãƒ¬ãƒ™ãƒ« %2 ã®ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼ ã‚³ãƒ¼ã‚¹ã«ç™»éŒ²ã—ã¾ã—ãŸã€‚æœ€å¯„ã‚Šã®è²¿æ˜“ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«å‘ã‘ã¦å‡ºç™ºã—ã¾ã™ã€‚</t>
    <t id="9921">ã“ã®ã‚³ãƒ¼ã‚¹ã«ã¯è³‡é‡‘ãŒä¸è¶³ã—ã¦ã„ã¾ã™ (%1 ãŒå¿…è¦ã€%2 ãŒå¿…è¦)ã€‚</t>
    <t id="9922">ã‚³ãƒ¼ã‚¹ã¯åˆ©ç”¨ã§ãã¾ã›ã‚“ - ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ %1 ã¯ã™ã§ã«ã“ã®ãƒ¬ãƒ™ãƒ«ä»¥ä¸Šã§ã™ã€‚</t>
    <t id="9923">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ %1 ã¯ã€%5 ã®ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚° ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼ ãƒ¬ãƒ™ãƒ« %2 ã‚³ãƒ¼ã‚¹ (è²»ç”¨: %3 Crã€æ‰€è¦æ™‚é–“: %4 åˆ†) ã«ç™»éŒ²ã—ã¾ã—ãŸã€‚</t>
    <t id="11011">GTè¦‹ç¿’ã„ä¸­åž‹èˆ¹æ¸›é€Ÿæ©Ÿ</t>
    <t id="11012">ä¸­åž‹èˆ¹ã®çµŒé¨“ã®æµ…ã„ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã‚’ã‚ãšã‹ã«ä½Žä¸‹ã•ã›ã‚‹ã‚¨ãƒ³ã‚¸ãƒ³ã®æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -5% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="11013">GT ã‚¢ãƒ—ãƒ¬ãƒ³ãƒ†ã‚£ã‚¹ ä¸­åž‹ãƒˆãƒ©ãƒ™ãƒ« ãƒ¬ãƒ‡ãƒ¥ãƒ¼ã‚µãƒ¼</t>
    <t id="11014">ä¸­åž‹èˆ¹ã®çµŒé¨“ã®æµ…ã„ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®èµ°è¡Œæ€§èƒ½ã‚’ã‚ãšã‹ã«ä½Žä¸‹ã•ã›ã‚‹ã‚¨ãƒ³ã‚¸ãƒ³ã®æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ç§»å‹•é€Ÿåº¦ -5%ã€‚</t>
    <t id="11021">GTè¦‹ç¿’ã„å¤§åž‹èˆ¹æ¸›é€Ÿæ©Ÿ</t>
    <t id="11022">å¤§åž‹èˆ¹ã®çµŒé¨“ã®æµ…ã„ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã‚’ä½Žä¸‹ã•ã›ã‚‹ã‚¨ãƒ³ã‚¸ãƒ³ã®æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -15% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="11023">GT ã‚¢ãƒ—ãƒ¬ãƒ³ãƒ†ã‚£ã‚¹å¤§åž‹ãƒˆãƒ©ãƒ™ãƒ«æ¸›é€Ÿæ©Ÿ</t>
    <t id="11024">å¤§åž‹èˆ¹ã®çµŒé¨“ã®æµ…ã„ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®èˆªè¡Œæ€§èƒ½ã‚’ä½Žä¸‹ã•ã›ã‚‹ã‚¨ãƒ³ã‚¸ãƒ³ã®æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -15% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="11031">GTè¦‹ç¿’ã„ä¸»åŠ›è‰¦ãƒªãƒ‡ãƒ¥ãƒ¼ã‚µãƒ¼</t>
    <t id="11032">ä¸»åŠ›è‰¦ã®çµŒé¨“ã®æµ…ã„ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã‚’å¤§å¹…ã«ä½Žä¸‹ã•ã›ã‚‹ã‚¨ãƒ³ã‚¸ãƒ³ã®æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -25% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="11033">GT ã‚¢ãƒ—ãƒ¬ãƒ³ãƒ†ã‚£ã‚¹ ã‚­ãƒ£ãƒ”ã‚¿ãƒ« ãƒˆãƒ©ãƒ™ãƒ« ãƒªãƒ‡ãƒ¥ãƒ¼ã‚µãƒ¼</t>
    <t id="11034">ä¸»åŠ›è‰¦ã®çµŒé¨“ã®æµ…ã„ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®èµ°è¡Œæ€§èƒ½ã‚’å¤§å¹…ã«ä½Žä¸‹ã•ã›ã‚‹ã‚¨ãƒ³ã‚¸ãƒ³ã®æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -25% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="12001">GTãƒ™ãƒ¼ã‚·ãƒƒã‚¯å°åž‹èˆ¹ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="12002">åŸºæœ¬çš„ãªèªå®šãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’å‚™ãˆãŸå°åž‹èˆ¹èˆ¶å‘ã‘ã®ç‰¹æ®Šãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +3% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="12003">GT ãƒ™ãƒ¼ã‚·ãƒƒã‚¯ ã‚¹ãƒ¢ãƒ¼ãƒ« ãƒˆãƒ©ãƒ™ãƒ« ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="12004">åŸºæœ¬çš„ãªèªå®šãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’å‚™ãˆãŸå°åž‹èˆ¹èˆ¶å‘ã‘ã®ç‰¹æ®Šãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +3% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="13001">GTãƒ™ãƒ¼ã‚·ãƒƒã‚¯å¤§åž‹èˆ¹èˆ¶ç”¨æ¸›é€Ÿæ©Ÿ</t>
    <t id="13002">åŸºæœ¬èªå®šãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹å¤§åž‹èˆ¹èˆ¶å‘ã‘ã®ç‰¹æ®Šãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -8% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="13003">GTãƒ™ãƒ¼ã‚·ãƒƒã‚¯å¤§åž‹ãƒˆãƒ©ãƒ™ãƒ«ãƒ¬ã‚¸ãƒ¥ãƒ¼ã‚µ</t>
    <t id="13004">åŸºæœ¬èªå®šãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹å¤§åž‹èˆ¹èˆ¶å‘ã‘ã®ç‰¹æ®Šãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -8% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="14001">GTãƒ™ãƒ¼ã‚·ãƒƒã‚¯ã‚­ãƒ£ãƒ”ã‚¿ãƒ«ã‚·ãƒƒãƒ—ãƒªãƒ‡ãƒ¥ãƒ¼ã‚µãƒ¼</t>
    <t id="14002">åŸºæœ¬çš„ãªèªå®šãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’å‚™ãˆãŸä¸»åŠ›è‰¦å‘ã‘ã®ç‰¹æ®Šãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -15% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="14003">GT ãƒ™ãƒ¼ã‚·ãƒƒã‚¯ ã‚­ãƒ£ãƒ”ã‚¿ãƒ« ãƒˆãƒ©ãƒ™ãƒ« ãƒªãƒ‡ãƒ¥ãƒ¼ã‚µãƒ¼</t>
    <t id="14004">åŸºæœ¬çš„ãªèªå®šãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’å‚™ãˆãŸä¸»åŠ›è‰¦å‘ã‘ã®ç‰¹æ®Šãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ -15% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="15001">GTã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆå°åž‹èˆ¹èˆ¶ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="15002">å°‚é–€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹å°åž‹èˆ¹èˆ¶å‘ã‘ã®é«˜åº¦ãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +25% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="15003">GT ã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆ ã‚¹ãƒ¢ãƒ¼ãƒ« ãƒˆãƒ©ãƒ™ãƒ« ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="15004">å°‚é–€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹å°åž‹èˆ¹èˆ¶å‘ã‘ã®é«˜åº¦ãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +25% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="16001">GTã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆå¤§åž‹èˆ¹ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="16002">å°‚é–€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹å¤§åž‹èˆ¹å‘ã‘ã®é«˜åº¦ãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +15% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="16003">GTã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆãƒ©ãƒ¼ã‚¸ãƒˆãƒ©ãƒ™ãƒ«ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="16004">å°‚é–€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹å¤§åž‹èˆ¹å‘ã‘ã®é«˜åº¦ãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +15% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="17001">GTã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆã‚­ãƒ£ãƒ”ã‚¿ãƒ«ã‚·ãƒƒãƒ—ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="17002">å°‚é–€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹ä¸»åŠ›è‰¦ã®é«˜åº¦ãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +6% é€Ÿåº¦ã€æŽ¨åŠ›ã€å›žè»¢ã€‚</t>
    <t id="17003">GT ã‚¨ã‚­ã‚¹ãƒ‘ãƒ¼ãƒˆ ã‚­ãƒ£ãƒ”ã‚¿ãƒ« ãƒˆãƒ©ãƒ™ãƒ« ã‚¨ãƒ³ãƒãƒ³ã‚µãƒ¼</t>
    <t id="17004">å°‚é–€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã«ã‚ˆã‚‹ä¸»åŠ›è‰¦ã®é«˜åº¦ãªã‚¨ãƒ³ã‚¸ãƒ³æ”¹é€ ã€‚ GalaxyTrader AI ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦ä½¿ç”¨ã•ã‚Œã¾ã™ã€‚ +6% ç§»å‹•é€Ÿåº¦ã€‚</t>
    <t id="18001">åŽ³ã—ã„ã‚¹ã‚­ãƒ«åˆ¶é™ï¼ˆèˆ¹ï¼‰</t>
    <t id="18002">é‡å¤§ãªã‚¹ã‚­ãƒ«åˆ¶é™ (èˆ¹èˆ¶) - å¤§åž‹èˆ¹èˆ¶ã§ã®ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®çµŒé¨“ä¸è¶³ã«ã‚ˆã‚‹åŽ³ã—ã„ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ãƒšãƒŠãƒ«ãƒ†ã‚£ã‚’è¡¨ã—ã¾ã™ã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ãŒèˆ¹ã®ã‚µã‚¤ã‚ºã«å¯¾ã—ã¦ä¸ååˆ†ãªå ´åˆã€GalaxyTrader ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦è‡ªå‹•çš„ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚èˆ¹ã®è³ªé‡ã‚’å¢—åŠ ã•ã›ã¾ã™ã€‚ (GT ã‚·ã‚¹ãƒ†ãƒ ã®ã¿ - æ‰‹å‹•ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“)</t>
    <t id="18003">ä¸­ç¨‹åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ (èˆ¹)</t>
    <t id="18004">ä¸­ç¨‹åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ (èˆ¹èˆ¶) - ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒèˆ¹èˆ¶ã®è¤‡é›‘ã•ã«é©å¿œã™ã‚‹ãŸã‚ã€ä¸­ç¨‹åº¦ã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã®ãƒšãƒŠãƒ«ãƒ†ã‚£ã‚’è¡¨ã—ã¾ã™ã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ãŒèˆ¹ã®ã‚µã‚¤ã‚ºã«å¯¾ã—ã¦ä¸ååˆ†ãªå ´åˆã€GalaxyTrader ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦è‡ªå‹•çš„ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚èˆ¹ã®è³ªé‡ã‚’å¢—åŠ ã•ã›ã¾ã™ã€‚ (GT ã‚·ã‚¹ãƒ†ãƒ ã®ã¿ - æ‰‹å‹•ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“)</t>
    <t id="18005">è»½åº¦ã‚¹ã‚­ãƒ«åˆ¶é™ï¼ˆèˆ¹ï¼‰</t>
    <t id="18006">è»½åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ (èˆ¹) - ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«é–‹ç™ºä¸­ã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã®è»½å¾®ãªãƒšãƒŠãƒ«ãƒ†ã‚£ã‚’è¡¨ã—ã¾ã™ã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ãŒèˆ¹ã®ã‚µã‚¤ã‚ºã«å¯¾ã—ã¦ä¸ååˆ†ãªå ´åˆã€GalaxyTrader ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦è‡ªå‹•çš„ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚èˆ¹ã®è³ªé‡ã‚’å¢—åŠ ã•ã›ã¾ã™ã€‚ (GT ã‚·ã‚¹ãƒ†ãƒ ã®ã¿ - æ‰‹å‹•ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“)</t>
    <t id="18007">åŽ³ã—ã„ã‚¹ã‚­ãƒ«åˆ¶é™ï¼ˆã‚¨ãƒ³ã‚¸ãƒ³ï¼‰</t>
    <t id="18008">é‡å¤§ãªã‚¹ã‚­ãƒ«åˆ¶é™ (ã‚¨ãƒ³ã‚¸ãƒ³) - å¤§åž‹èˆ¹èˆ¶ã®ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®çµŒé¨“ä¸è¶³ã«ã‚ˆã‚‹åŽ³ã—ã„ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ãƒšãƒŠãƒ«ãƒ†ã‚£ã‚’è¡¨ã—ã¾ã™ã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ãŒèˆ¹ã®ã‚µã‚¤ã‚ºã«å¯¾ã—ã¦ä¸ååˆ†ãªå ´åˆã€GalaxyTrader ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦è‡ªå‹•çš„ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚ã‚¨ãƒ³ã‚¸ãƒ³ã®æŽ¨åŠ›ã¨å›žè»¢ã‚’ä½Žä¸‹ã•ã›ã¾ã™ã€‚ (GT ã‚·ã‚¹ãƒ†ãƒ ã®ã¿ - æ‰‹å‹•ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“)</t>
    <t id="18009">ä¸­ç¨‹åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ (ã‚¨ãƒ³ã‚¸ãƒ³)</t>
    <t id="18010">ä¸­ç¨‹åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ (ã‚¨ãƒ³ã‚¸ãƒ³) - ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆãŒèˆ¹èˆ¶ã®è¤‡é›‘ã•ã«é©å¿œã™ã‚‹ãŸã‚ã€ä¸­ç¨‹åº¦ã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã®ãƒšãƒŠãƒ«ãƒ†ã‚£ãŒç™ºç”Ÿã—ã¾ã™ã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ãŒèˆ¹ã®ã‚µã‚¤ã‚ºã«å¯¾ã—ã¦ä¸ååˆ†ãªå ´åˆã€GalaxyTrader ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦è‡ªå‹•çš„ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚ã‚¨ãƒ³ã‚¸ãƒ³ã®æŽ¨åŠ›ã¨å›žè»¢ã‚’ä½Žä¸‹ã•ã›ã¾ã™ã€‚ (GT ã‚·ã‚¹ãƒ†ãƒ ã®ã¿ - æ‰‹å‹•ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“)</t>
    <t id="18011">è»½åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ï¼ˆã‚¨ãƒ³ã‚¸ãƒ³ï¼‰</t>
    <t id="18012">è»½åº¦ã®ã‚¹ã‚­ãƒ«åˆ¶é™ (ã‚¨ãƒ³ã‚¸ãƒ³) - ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«é–‹ç™ºä¸­ã®ãƒ‘ãƒ•ã‚©ãƒ¼ãƒžãƒ³ã‚¹ã®è»½å¾®ãªãƒšãƒŠãƒ«ãƒ†ã‚£ã‚’è¡¨ã—ã¾ã™ã€‚ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ãŒèˆ¹ã®ã‚µã‚¤ã‚ºã«å¯¾ã—ã¦ä¸ååˆ†ãªå ´åˆã€GalaxyTrader ã‚·ã‚¹ãƒ†ãƒ ã«ã‚ˆã£ã¦è‡ªå‹•çš„ã«é©ç”¨ã•ã‚Œã¾ã™ã€‚ã‚¨ãƒ³ã‚¸ãƒ³ã®æŽ¨åŠ›ã¨å›žè»¢ã‚’ä½Žä¸‹ã•ã›ã¾ã™ã€‚ (GT ã‚·ã‚¹ãƒ†ãƒ ã®ã¿ - æ‰‹å‹•ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ã«ã¯ä½¿ç”¨ã§ãã¾ã›ã‚“)</t>
    <t id="9250">èˆ¹ã®çŠ¶æ…‹ã®å‘½å</t>
    <t id="9350">èˆ¹ã®çŠ¶æ…‹ã®ç•¥èªžã‚’ã‚«ã‚¹ã‚¿ãƒžã‚¤ã‚ºã—ã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆå€¤ãŒå…¥åŠ›ãƒœãƒƒã‚¯ã‚¹ã«è¡¨ç¤ºã•ã‚Œã€ä¸Šæ›¸ãã§ãã¾ã™ã€‚æœ€å¤§ 3 æ–‡å­—ã€‚ã™ã¹ã¦ã®èˆ¹åã¯å¤‰æ›´ã•ã‚Œã‚‹ã¨è‡ªå‹•çš„ã«æ›´æ–°ã•ã‚Œã¾ã™ã€‚</t>
    <t id="9251">è£œçµ¦çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9252">ä¿®ç†çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9253">ãƒ¡ãƒ³ãƒ†ãƒŠãƒ³ã‚¹çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9254">ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9255">ãƒªãƒ«ãƒ¼ãƒˆçŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9256">ã‚¯ãƒªã‚¢ãƒ©ãƒ³ã‚¹çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9257">ãƒ–ãƒ­ãƒƒã‚¯ã•ã‚ŒãŸçŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9258">ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9259">å­¤ç«‹çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9260">å–å¼•çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9261">ã‚¢ã‚¤ãƒ‰ãƒ«çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9262">ã‚¨ã‚¹ã‚±ãƒ¼ãƒ—çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9268">åˆ°é”ä¸èƒ½çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9269">ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆäº¤æ›çŠ¶æ…‹ã®ç•¥èªž:</t>
    <t id="9270">ã‚«ã‚¹ã‚¿ãƒ  ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆ ãƒ—ãƒ¬ãƒ•ã‚£ãƒƒã‚¯ã‚¹ ã‚¿ã‚°:</t>
    <t id="9700">ãƒãƒ¼ãƒˆ (å£Šã‚Œã¦ã¾ã™ã€‚ä½•ã‚‚ã‚ã‚Šã¾ã›ã‚“!! æœ¬å½“ã«!!)</t>
    <t id="9701">GTè‰¦èˆ¹ã‚’ç„¡æ•µåŒ–</t>
    <t id="9702">ã™ã¹ã¦ã®ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼è‰¦èˆ¹ã‚’ç„¡æ•µåŒ–</t>
    <t id="9800">ãã®ã¾ã¾ãŠé€²ã¿ãã ã•ã„ã€‚å£Šã‚ŒãŸé–‹ç™ºè€…ç”¨ãƒ†ã‚¹ãƒˆãƒ„ãƒ¼ãƒ«ã§ã™ã€‚æ¥½ã—ã„ãƒœã‚¿ãƒ³ãƒ¡ãƒ‹ãƒ¥ãƒ¼ã§ã¯ã‚ã‚Šã¾ã›ã‚“ã€‚ä½•ã‚‚ã‚ã‚Šã¾ã›ã‚“ã€‚æœ¬å½“ã«ã€‚è­¦å‘Šã—ã¾ã—ãŸã€‚ãŸã¶ã‚“ã€‚</t>
    <t id="9801">GalaxyTraderå‘½ä»¤ä¸­ã®è‰¦èˆ¹ã¯èˆ¹ä½“ã¨ã‚·ãƒ¼ãƒ«ãƒ‰ãŒ100%æœªæº€ã«ãªã‚Šã¾ã›ã‚“ã€‚ã‚‚ã†ä¸€åº¦ã‚¯ãƒªãƒƒã‚¯ã§ç„¡åŠ¹åŒ–ã€‚</t>
    <t id="9802">ã™ã¹ã¦ã®ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼è‰¦èˆ¹ã¯èˆ¹ä½“ã¨ã‚·ãƒ¼ãƒ«ãƒ‰ãŒ100%æœªæº€ã«ãªã‚Šã¾ã›ã‚“ã€‚ã‚‚ã†ä¸€åº¦ã‚¯ãƒªãƒƒã‚¯ã§ç„¡åŠ¹åŒ–ã€‚ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¯å¯¾è±¡å¤–ã§ã™ã€‚</t>
    <t id="9703">GTãƒ†ã‚¹ãƒˆç”¨ã«å®‡å®™ã‚’é–‹ç¤º</t>
    <t id="9704">é–‹ç¤ºæ¸ˆã¿</t>
    <t id="9705">é–‹ç¤º</t>
    <t id="9803">å…¨ã‚»ã‚¯ã‚¿ãƒ¼ã®æˆ¦äº‰ã®éœ§ã‚’é–‹ç¤ºã—ã€ã™ã¹ã¦ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚’æ—¢çŸ¥ã«ã—ã€å…¨æ´¾é–¥ã®è²¿æ˜“ã‚µãƒ–ã‚¹ã‚¯ãƒªãƒ—ã‚·ãƒ§ãƒ³ãƒ©ã‚¤ã‚»ãƒ³ã‚¹ã‚’ä»˜ä¸Žã—ã€éŠ€æ²³å…¨ä½“ã®è²¿æ˜“ã‚ªãƒ•ã‚¡ãƒ¼ã‚’è³¼èª­ã—ã¾ã™ã€‚æ–°ã—ã„DLCã‚»ã‚¯ã‚¿ãƒ¼å¾Œã«å†åº¦ã‚¯ãƒªãƒƒã‚¯ã—ã¦ãã ã•ã„ã€‚ãƒ†ã‚¹ãƒˆå°‚ç”¨ã§ã™ã€‚</t>
    <t id="9706">ç™»éŒ²æ¸ˆã¿GTãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®XPã‚’æœ€å¤§ã«</t>
    <t id="9707">æœ€å¤§æ¸ˆã¿</t>
    <t id="9708">XPæœ€å¤§</t>
    <t id="9804">GTãƒ¬ã‚¸ã‚¹ãƒˆãƒªã®å…¨ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã‚’ãƒ¬ãƒ™ãƒ«15ãƒ»æœ€å¤§XPã«è¨­å®šã€‚è¨“ç·´ã‚²ãƒ¼ãƒˆã¨ãƒ–ãƒ­ãƒƒã‚¯ã‚’è§£é™¤ã€‚ãƒãƒ‹ãƒ©XPã®ã¿æœ‰åŠ¹æ™‚ã¯ã‚¹ã‚­ãƒƒãƒ—ã€‚ãƒ†ã‚¹ãƒˆå°‚ç”¨ã€‚</t>
    <t id="9351">Resupply state ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: RS)</t>
    <t id="9352">Repair stateã®ç•¥ç§°ï¼ˆãƒ‡ãƒ•ã‚©ãƒ«ãƒˆï¼šRPï¼‰</t>
    <t id="9353">ãƒ¡ãƒ³ãƒ†ãƒŠãƒ³ã‚¹çŠ¶æ…‹ã®ç•¥ç§°ï¼ˆãƒ‡ãƒ•ã‚©ãƒ«ãƒˆï¼šMTï¼‰</t>
    <t id="9354">ãƒˆãƒ¬ãƒ¼ãƒ‹ãƒ³ã‚°çŠ¶æ…‹ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: TR)</t>
    <t id="9355">Reroute state ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: RR)</t>
    <t id="9356">Clearance state ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: CL)</t>
    <t id="9357">Blocked stateã®ç•¥ç§°ï¼ˆãƒ‡ãƒ•ã‚©ãƒ«ãƒˆï¼šBLï¼‰</t>
    <t id="9358">Fallback çŠ¶æ…‹ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: FB)</t>
    <t id="9359">å­¤ç«‹çŠ¶æ…‹ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: IS)</t>
    <t id="9360">Trading stateã®ç•¥ç§°ï¼ˆãƒ‡ãƒ•ã‚©ãƒ«ãƒˆï¼šTDï¼‰</t>
    <t id="9361">ã‚¢ã‚¤ãƒ‰ãƒ«çŠ¶æ…‹ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: ID)</t>
    <t id="9362">Escape stateã®ç•¥ç§°ï¼ˆãƒ‡ãƒ•ã‚©ãƒ«ãƒˆï¼šESï¼‰</t>
    <t id="9367">Unreachable çŠ¶æ…‹ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: UR)</t>
    <t id="9368">Pilot Exchange state ã®ç•¥ç§° (ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: PE)</t>
    <t id="9369">ã‚«ã‚¹ã‚¿ãƒ æ´¾é–¥ãƒ–ãƒ©ãƒƒã‚¯ãƒªã‚¹ãƒˆ (éƒ¨ä¸‹ã‚’å«ã‚€) ã®å½±éŸ¿ã‚’å—ã‘ã‚‹ MK3 èˆ¹ã®æŽ¥é ­è¾žã¨ã—ã¦è¡¨ç¤ºã•ã‚Œã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ: CB</t>
    <t id="30002">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ MK1</t>
    <t id="30102">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ - ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³è£½å“ã‚’NPCå‹¢åŠ›ã«è²©å£²ã—ã¾ã™</t>
    <t id="30010">ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³</t>
    <t id="30011">æœ€å¤§è²©å£²è·é›¢</t>
    <t id="30012">è²¿æ˜“ãƒ«ãƒ¼ãƒ«ã‚’ç„¡è¦–ã™ã‚‹</t>
    <t id="30013">ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼</t>
    <t id="30014">è²©å£²è²¨ç‰©å……å¡«ç›®æ¨™%</t>
    <t id="30015">ãƒãƒƒã‚¯ãƒˆãƒ©ãƒƒã‚¯è¨±å®¹åº¦</t>
    <t id="30016">è³¼å…¥ã‚«ãƒ¼ã‚´ãƒ•ã‚£ãƒ«ç›®æ¨™%</t>
    <t id="30017">ãƒ­ã‚°ãƒ–ãƒƒã‚¯ã®ã‚¨ãƒ³ãƒˆãƒª</t>
    <t id="30018">é€šçŸ¥ãƒ¬ãƒ™ãƒ«</t>
    <t id="30019">è‰¦éšŠèª¿æ•´</t>
    <t id="30020">ãƒ‡ãƒãƒƒã‚°ãƒ¬ãƒ™ãƒ«</t>
    <t id="30021">ä¾›çµ¦ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³</t>
    <t id="30022">æœ€å°ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="30023">é•æ³•å•†å“ã®è¨±å¯</t>
    <t id="30024">è²¨ç‰©/åˆ©ç›Š</t>
    <t id="30025">è¤‡æ•°å–å¼•ã‚’è¨±å¯</t>
    <t id="30110">å•†å“ã‚’è²©å£²ã™ã‚‹ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ (ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å‰²ã‚Šå½“ã¦ãŒå¿…è¦ã§ã™)</t>
    <t id="30111">NPCè³¼å…¥è€…ã‚’è¦‹ã¤ã‘ã‚‹ãŸã‚ã®æœ€å¤§ã‚²ãƒ¼ãƒˆè·é›¢ï¼ˆãƒ‘ã‚¤ãƒ­ãƒƒãƒˆã®ã‚¹ã‚­ãƒ«ã«ã‚ˆã£ã¦åˆ¶é™ã•ã‚Œã¾ã™ï¼‰</t>
    <t id="30112">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å–å¼•åˆ¶é™ã‚’ç„¡è¦–ã—ã¾ã™ - ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å–å¼•ãƒ«ãƒ¼ãƒ«ã«é–¢ä¿‚ãªãã€å‹å¥½çš„ãªå‹¢åŠ›ã«è²©å£²ã—ã¾ã™</t>
    <t id="30113">ã‚ªãƒ—ã‚·ãƒ§ãƒ³ã®ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã€‚ã™ã¹ã¦ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³è£½å“ã¨ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‚’è²©å£²ã™ã‚‹ã«ã¯ç©ºã®ã¾ã¾ã«ã—ã¾ã™</t>
    <t id="30114">è²©å£²æ—…è¡Œå‡ºç™ºå‰ã®æœ€ä½Žè²¨ç‰©å……å¡«çŽ‡</t>
    <t id="30115">æ—…è¡Œã« 2 ã¤ç›®ã®å•†å“ã‚’è¿½åŠ ã™ã‚‹ã¨ãã«è¨±å¯ã•ã‚Œã‚‹è¿½åŠ ã‚¸ãƒ£ãƒ³ãƒ—ã®æœ€å¤§æ•° (0 = ãƒ«ãƒ¼ãƒˆã«ç›´æŽ¥å‚åŠ ã™ã‚‹è³¼å…¥è€…ã®ã¿)</t>
    <t id="30116">ä¾›çµ¦ãƒ©ãƒ³ã®ç›®æ¨™è²¨ç‰©å……å¡«ï¼ˆã‚½ãƒ•ãƒˆã‚¿ãƒ¼ã‚²ãƒƒãƒˆã€ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã¯æ—©ã‚ã«å‡ºç™ºã™ã‚‹å¯èƒ½æ€§ãŒã‚ã‚Šã¾ã™ï¼‰</t>
    <t id="30117">å–å¼•ã”ã¨ã®ãƒ­ã‚°ãƒ–ãƒƒã‚¯ã‚¨ãƒ³ãƒˆãƒªã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="30118">é€šçŸ¥ãƒ¬ãƒ™ãƒ«: 0=é™ã‹ã€1=æ¨™æº–ã€2=è©³ç´°</t>
    <t id="30119">ãƒ•ãƒªãƒ¼ãƒˆèª¿æ•´ã¨å–å¼•äºˆç´„ã‚·ã‚¹ãƒ†ãƒ ã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="30120">ãƒ‡ãƒãƒƒã‚°ãƒ­ã‚°ãƒ¬ãƒ™ãƒ«: 0=ã‚ªãƒ•ã€1=é€šå¸¸ã€2=è©³ç´°</t>
    <t id="30121">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ãƒªã‚½ãƒ¼ã‚¹ã‚‚è³¼å…¥ã—ã¾ã™ã€‚ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ãŒæœ€å°ã—ãã„å€¤ã‚’ä¸‹å›žã£ãŸå ´åˆã€ä¾›çµ¦ãŒå„ªå…ˆã•ã‚Œã¾ã™</t>
    <t id="30122">ã„ãšã‚Œã‹ã®ãƒªã‚½ãƒ¼ã‚¹ãŒç›®æ¨™ã®ã“ã®å‰²åˆã‚’ä¸‹å›žã‚‹ã¨ã€è²©å£²ã‚ˆã‚Šã‚‚ä¾›çµ¦ãŒå„ªå…ˆã•ã‚Œã¾ã™ã€‚ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«ãƒªã‚½ãƒ¼ã‚¹ãŒãªã„å ´åˆã¯ç„¡è¦–ã•ã‚Œã¾ã™</t>
    <t id="30123">å¯èƒ½ãªå ´åˆã¯ã€é•æ³•/ç¦åˆ¶å“ã®è²©å£²ã¾ãŸã¯è³¼å…¥ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="30124">è²©å£²é¸æŠžï¼š1ï¼è²¨ç‰©ï¼ˆãã®å•†å“ã®åœ¨åº«å……å¡«çŽ‡ãŒæœ€ã‚‚é«˜ã„ã‚‚ã®ã‚’å„ªå…ˆã€åŒçŽ‡ãªã‚‰åˆ©ç›Šï¼‰ã€2ï¼åˆ©ç›Šï¼ˆæœ€é«˜ã®åˆ©ç›Šã‚¹ã‚³ã‚¢ï¼‰</t>
    <t id="30125">1ã‚µã‚¤ã‚¯ãƒ«ã§è¤‡æ•°ã®è²©å£²å–å¼•ã‚’é€£çµã§ãã¾ã™ï¼ˆæœ€å¤§3ç¨®ã®å•†å“ã¾ãŸã¯è¡Œãå…ˆï¼‰ã€‚ç„¡åŠ¹ã«ã™ã‚‹ã¨1ã‚µã‚¤ã‚¯ãƒ«1å–å¼•ã®ã¿</t>
    <t id="30200">%1 %2 ã‚’ %3 ã‹ã‚‰ %4 ã¾ã§è²©å£²ã—ã¾ã™</t>
    <t id="30201">%1 ã‚¸ãƒ£ãƒ³ãƒ—ä»¥å†…ã«ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³è£½å“ã®è³¼å…¥è€…ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“ã§ã—ãŸ</t>
    <t id="30202">ãƒ›ãƒ¼ãƒ  ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ %1 ãŒç ´å£Šã•ã‚Œã¾ã—ãŸ - ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã®æ³¨æ–‡ã¯ã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã¾ã—ãŸ</t>
    <t id="30203">ãƒ›ãƒ¼ãƒ  ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ %1 ã¯ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã®æ‰€æœ‰ã§ã¯ãªããªã‚Šã¾ã—ãŸ - æ³¨æ–‡ã¯ã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã¾ã—ãŸ</t>
    <t id="30204">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å‰²ã‚Šå½“ã¦ãŒå¿…è¦ã§ã™ - æ³¨æ–‡ã¯ã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã¾ã—ãŸ</t>
    <t id="30205">MK1 ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã¯ %1 ã«é–‹å§‹ã•ã‚Œã¾ã—ãŸ</t>
    <t id="30206">è²©å£²å®Œäº†: %1 %2 ãŒ %3 ã« %4 Cr ã§è²©å£²ã•ã‚Œã¾ã—ãŸ (åˆ©ç›Š: %5 Cr)</t>
    <t id="30207">è¤‡æ•°ã®å•†å“ã®é…é€: %1 å•†å“ã‚’ %2 ã®ç›®çš„åœ°ã«é…é€ã—ã¾ã™</t>
    <t id="30208">Supplying %1 %2 to %3 from %4</t>
    <t id="30500">GalaxyTrader MK1ã®è¨­å®š</t>
    <t id="30501">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼ã®ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ</t>
    <t id="30502">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®æœ€å¤§è²©å£²è·é›¢</t>
    <t id="30503">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®è²©å£²ã‚«ãƒ¼ã‚´ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã‚²ãƒƒãƒˆ</t>
    <t id="30504">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã§ã¯å–å¼•ãƒ«ãƒ¼ãƒ«ã‚’ç„¡è¦–ã—ã¾ã™</t>
    <t id="30505">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®ãƒãƒƒã‚¯ãƒˆãƒ©ãƒƒã‚¯è¨±å®¹å€¤</t>
    <t id="30506">å–å¼•ãŒè¦‹ã¤ã‹ã‚‰ãªã‹ã£ãŸå ´åˆã®å¾…ã¡æ™‚é–“</t>
    <t id="30507">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®è³¼å…¥ã‚«ãƒ¼ã‚´ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã‚²ãƒƒãƒˆ</t>
    <t id="31002">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒžã‚¤ãƒŠãƒ¼</t>
    <t id="31102">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ä¾›çµ¦ã¨ XP ã®é€²è¡Œã«ã‚ˆã‚‹è‡ªå¾‹æŽ¡æŽ˜</t>
    <t id="31010">ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³</t>
    <t id="31110">æŽ¡æŽ˜ãŠã‚ˆã³é…é”å…ˆã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ (å®¶åº­éƒ¨é–€ã¨ç›¸äº’ã«æŽ’ä»–çš„)</t>
    <t id="31011">å®¶åº­éƒ¨é–€</t>
    <t id="31111">æ´»å‹•ã™ã‚‹ã‚»ã‚¯ã‚¿ãƒ¼;ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãŒè¨­å®šã•ã‚Œã¦ã„ãªã„å ´åˆã«ä½¿ç”¨</t>
    <t id="31012">ãƒªã‚½ãƒ¼ã‚¹ãƒã‚¹ã‚±ãƒƒãƒˆ</t>
    <t id="31112">é‰±å±±ã¸ã®å•†å“ã€‚ç©ºã¯ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³è¦æ±‚ã®è§£æ±ºã«å¾“ã„ã¾ã™</t>
    <t id="31013">å¯¾è±¡å±€</t>
    <t id="31113">é…é€ç”¨ã®ã‚ªãƒ—ã‚·ãƒ§ãƒ³ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã€‚ç©ºã¯ãƒ›ãƒ¼ãƒ ã‚³ãƒ³ãƒ†ã‚­ã‚¹ãƒˆã‹ã‚‰æ´¾ç”Ÿã—ã¾ã™</t>
    <t id="31014">ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒ­ãƒ¼ã—ãã„å€¤ %</t>
    <t id="31114">ã“ã®ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ ãƒ‘ãƒ¼ã‚»ãƒ³ãƒˆä»¥ä¸Šã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¯æº€æ¯ã¨ã—ã¦æ‰±ã‚ã‚Œã¾ã™</t>
    <t id="31015">ä»–è€…ã¸ã®ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒ­ãƒ¼è²©å£²ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="31115">æœ‰åŠ¹ã§ãƒ—ãƒ©ã‚¤ãƒžãƒªã‚¿ãƒ¼ã‚²ãƒƒãƒˆãŒã„ã£ã±ã„ã®å ´åˆã€ä»–ã®æ´¾é–¥ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«è²©å£²ã—ã¾ã™</t>
    <t id="31016">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«å‰²ã‚Šå½“ã¦ã‚‹</t>
    <t id="31116">è©²å½“ã™ã‚‹å ´åˆã€èˆ¹ã‚’ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®æŽ¡æŽ˜å¾“å±žã¨ã—ã¦å‰²ã‚Šå½“ã¦ã¾ã™</t>
    <t id="31017">ã‚¹ãƒ†ã‚¤ãƒ»ã‚¢ãƒƒãƒˆãƒ»ãƒ›ãƒ¼ãƒ </t>
    <t id="31117">ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒ­ãƒ¼ãƒ•ã‚©ãƒ¼ãƒ«ãƒãƒƒã‚¯å®Ÿè¡Œã‚’é™¤ãã€ãƒžã‚¤ãƒ‹ãƒ³ã‚°/è²©å£²ã‚’ãƒ›ãƒ¼ãƒ ã‚¨ãƒªã‚¢ã«åˆ¶é™ã™ã‚‹</t>
    <t id="31018">ãƒªã‚½ãƒ¼ã‚¹ãƒ—ãƒ­ãƒ¼ãƒ–ã®è‡ªå‹•å±•é–‹</t>
    <t id="31118">ãƒ­ãƒ¼ãƒ‰ã•ã‚ŒãŸãƒªã‚½ãƒ¼ã‚¹ ãƒ—ãƒ­ãƒ¼ãƒ–ã‚’è‡ªå‹•çš„ã«å±•é–‹ã—ã€ãƒ¡ãƒ³ãƒ†ãƒŠãƒ³ã‚¹ã®è£œå……ã«ãƒ—ãƒ­ãƒ¼ãƒ–ã‚’å«ã‚ã¾ã™</t>
    <t id="31019">æœ€å¤§åŽé›†è·é›¢</t>
    <t id="31119">é›†åˆã®ãŸã‚ã®æœ€å¤§ã‚²ãƒ¼ãƒˆè·é›¢ (0 ã¯ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ/æŒ‡æ®å®˜ã®ã‚¹ã‚­ãƒ« ã‚­ãƒ£ãƒƒãƒ—ã‚’ä½¿ç”¨)</t>
    <t id="31020">æœ€å¤§è²©å£²è·é›¢</t>
    <t id="31120">è²©å£²ã®ãŸã‚ã®æœ€å¤§ã‚²ãƒ¼ãƒˆè·é›¢ (0 ã¯ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ/æŒ‡æ®å®˜ã®ã‚¹ã‚­ãƒ«ã‚­ãƒ£ãƒƒãƒ—ã‚’ä½¿ç”¨)</t>
    <t id="31021">ãƒ•ãƒªãƒ¼ãƒˆã®ãƒãƒ©ãƒ³ã‚¹èª¿æ•´</t>
    <t id="31121">æ±ºå®šè«–çš„ãªã‚¤ãƒ³ãƒ†ãƒ³ãƒˆèª¿æ•´ã‚’æœ‰åŠ¹ã«ã—ã¦ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒ­ãƒ¼ã‚’å‰Šæ¸›ã—ã¾ã™</t>
    <t id="31022">ãƒ‡ãƒžãƒ³ãƒ‰å†ãƒã‚§ãƒƒã‚¯é–“éš”</t>
    <t id="31122">ãƒžã‚¤ãƒŠãƒ¼ ãƒ‡ãƒžãƒ³â€‹â€‹ãƒ‰/ã‚¹ã‚¤ãƒƒãƒè©•ä¾¡ã®å®Ÿè¡Œé »åº¦</t>
    <t id="31023">ã‚¯ãƒªãƒ†ã‚£ã‚«ãƒ«ãƒ‡ãƒžãƒ³ãƒ‰ãƒ‡ãƒ«ã‚¿</t>
    <t id="31123">ã‚¢ã‚¯ãƒ†ã‚£ãƒ–ãªãƒžã‚¤ãƒ‹ãƒ³ã‚°ã‚¦ã‚§ã‚¢ã‚’åˆ‡ã‚Šæ›¿ãˆã‚‹ãŸã‚ã«å¿…è¦ãªæœ€å°ç·Šæ€¥ãƒ‡ãƒ«ã‚¿</t>
    <t id="31024">æœ€å°ã‚¹ã‚¤ãƒƒãƒã‚¯ãƒ¼ãƒ«ãƒ€ã‚¦ãƒ³</t>
    <t id="31124">ã“ã®èˆ¹ã® 2 ã¤ã®ã‚¦ã‚§ã‚¢ ã‚¹ã‚¤ãƒƒãƒé–“ã®æœ€å°æ™‚é–“</t>
    <t id="31025">æœ€å°è²¨ç‰©ã‚³ãƒŸãƒƒãƒˆãƒ¡ãƒ³ãƒˆ%</t>
    <t id="31125">è²¨ç‰©ã®å……å¡«é‡ãŒã“ã‚Œã‚’è¶…ãˆã‚‹å ´åˆã€èˆ¹ã¯åˆ‡ã‚Šæ›¿ãˆå‰ã«ç¾åœ¨ã®é…é€ã‚’å®Œäº†ã™ã‚‹ã“ã¨ã‚’å„ªå…ˆã—ã¾ã™</t>
    <t id="31026">ãƒãƒ¼ãƒ‰ã‚¨ãƒžãƒ¼ã‚¸ã‚§ãƒ³ã‚·ãƒ¼ãƒ‡ãƒ«ã‚¿</t>
    <t id="31126">ã‚«ãƒ¼ã‚´ã‚³ãƒŸãƒƒãƒˆã—ãã„å€¤ã«é–¢ã‚ã‚‰ãšå³æ™‚åˆ‡ã‚Šæ›¿ãˆã‚’å¯èƒ½ã«ã™ã‚‹ç·Šæ€¥åº¦ãƒ‡ãƒ«ã‚¿</t>
    <t id="31027">é€šçŸ¥ãƒ¬ãƒ™ãƒ«</t>
    <t id="31127">é€šçŸ¥ãƒ¬ãƒ™ãƒ«: 0=é™ã‹ã€1=æ¨™æº–ã€2=è©³ç´°</t>
    <t id="31028">ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ã¿</t>
    <t id="31128">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ãŒæ‰€æœ‰ã™ã‚‹ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ã¿ãŒãƒ‡ãƒžãƒ³ãƒ‰ ã‚¿ãƒ¼ã‚²ãƒƒãƒˆã¨ã¿ãªã•ã‚Œã¾ã™ã€‚</t>
    <t id="31031">éœ€è¦ã‚’å…ˆã«ç¢ºèª</t>
    <t id="31131">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€æŽ¡æŽ˜å‰ã«ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®éœ€è¦ã‚’ç¢ºèªã—ã€è³‡æºã®å„ªå…ˆé †ä½ã‚’æ±ºå®šã—ã¾ã™ã€‚ç„¡åŠ¹ã«ã™ã‚‹ã¨ã€éœ€è¦ç¢ºèªãªã—ã§ãƒªã‚½ãƒ¼ã‚¹ãƒã‚¹ã‚±ãƒƒãƒˆã‹ã‚‰æŽ¡æŽ˜ã—ã€è²·ã„æ‰‹ãŒç¾ã‚Œã‚‹ã¾ã§è²¯è”µã—ã¾ã™ï¼ˆå˜ä¸€è³‡æºãƒ•ãƒªãƒ¼ãƒˆå‘ã‘ï¼‰ã€‚</t>
    <t id="31032">ç‰©ç†ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ä¸­æ­¢ %</t>
    <t id="31132">ãƒ¬ãƒ™ãƒ«6ä»¥ä¸Šã®ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆå‘ã‘ï¼šã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ç‰©ç†åœ¨åº«ã¨é–¢é€£æŽ¡æŽ˜èˆ¹ã®ç©è¼‰è²¨ç‰©ã®åˆè¨ˆãŒã€ç¾åœ¨ã®ç‰©ç†åœ¨åº«ã‚’ã“ã®å‰²åˆã ã‘è¶…ãˆã‚‹å ´åˆã€å½“è©²è³‡æºã®æŽ¡æŽ˜ã‚’ä¸­æ­¢ã—ã¾ã™ã€‚å®Ÿéš›ã®ç©è¼‰é‡ã‚’ä½¿ç”¨ã—ã€ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒ­ãƒ¼é–¾å€¤ã¨ã¯åˆ¥ã§ã™ã€‚0ã§ç„¡åŠ¹ã€‚</t>
    <t id="32002">GalaxyTrader MK4 ä¾›çµ¦</t>
    <t id="32102">GT ã‚­ãƒ£ãƒƒã‚·ãƒ¥/ãƒ©ã‚¤ãƒ–æ¤œç´¢ãƒ‘ã‚¤ãƒ—ãƒ©ã‚¤ãƒ³ã‚’ä½¿ç”¨ã™ã‚‹ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ä¾›çµ¦ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼</t>
    <t id="32010">åˆ°é”è·é›¢</t>
    <t id="32110">ç›®çš„åœ°ãƒ‡ãƒžãƒ³ãƒ‰æ¤œç´¢æ™‚ã®è‡ªå®…ã‹ã‚‰ã®æœ€å¤§ã‚²ãƒ¼ãƒˆè·é›¢</t>
    <t id="32011">è³¼å…¥è·é›¢</t>
    <t id="32111">ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼æ¤œç´¢ã®ãŸã‚ã®è‡ªå®…ã‹ã‚‰ã®æœ€å¤§ã‚²ãƒ¼ãƒˆè·é›¢</t>
    <t id="32012">è‡ªå®…ã®ã¿ã§æä¾›</t>
    <t id="32112">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€ãƒ›ãƒ¼ãƒ  ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®è¦æ±‚ã®ã¿ãŒå‡¦ç†ã•ã‚Œã¾ã™</t>
    <t id="32013">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ã¿ã‚’æ§‹ç¯‰ã™ã‚‹</t>
    <t id="32113">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€ãƒ“ãƒ«ãƒ‰ ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã®éœ€è¦ã®ã¿ãŒå‡¦ç†ã•ã‚Œã¾ã™</t>
    <t id="32014">ãƒ—ãƒ¬ãƒ¼ãƒ¤ãƒ¼ã‹ã‚‰è³¼å…¥ã™ã‚‹</t>
    <t id="32114">ãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼æ‰€æœ‰ã®ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼ã‹ã‚‰å•†å“ã‚’èª¿é”ã§ãã‚‹ã‚ˆã†ã«ã™ã‚‹</t>
    <t id="32015">ãƒ•ã‚¡ã‚¯ã‚·ãƒ§ãƒ³ã‹ã‚‰è³¼å…¥</t>
    <t id="32115">éžãƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼é™£å–¶ã®ã‚µãƒ—ãƒ©ã‚¤ãƒ¤ãƒ¼ã‹ã‚‰å•†å“ã‚’èª¿é”ã§ãã‚‹ã‚ˆã†ã«ã™ã‚‹</t>
    <t id="32016">ãƒªã‚½ãƒ¼ã‚¹ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="32116">éœ€è¦ãƒžãƒƒãƒãƒ³ã‚°ã«ãƒªã‚½ãƒ¼ã‚¹ã‚¦ã‚§ã‚¢ã‚’å«ã‚ã‚‹</t>
    <t id="32017">ä¸­é–“ä½“ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="32117">éœ€è¦ãƒžãƒƒãƒãƒ³ã‚°ã«ä¸­é–“è£½å“ã‚’å«ã‚ã‚‹</t>
    <t id="32018">è£½å“ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="32118">éœ€è¦ãƒžãƒƒãƒãƒ³ã‚°ã«è£½å“ã‚’å«ã‚ã‚‹</t>
    <t id="32019">ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="32119">ãƒˆãƒ¬ãƒ¼ãƒ‰ã‚¦ã‚§ã‚¢ã‚’éœ€è¦ãƒžãƒƒãƒãƒ³ã‚°ã«å«ã‚ã‚‹</t>
    <t id="20002">ã‚®ãƒ£ãƒ©ã‚¯ã‚·ãƒ¼ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼MK2</t>
    <t id="20102">ä¿ç®¡ã—ãã„å€¤ç®¡ç†ã«ã‚ˆã‚‹å€‰åº«åˆ†æ•£</t>
    <t id="20010">ç™ºä¿¡å±€</t>
    <t id="20011">ç›®çš„åœ°é§…</t>
    <t id="20012">æœ€å°ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="20013">é™çš„ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="20014">æœ€å¤§ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="20015">ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼</t>
    <t id="20016">åŒæ–¹å‘ãƒ¢ãƒ¼ãƒ‰</t>
    <t id="20017">ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ï¼ˆã‚ªãƒ—ã‚·ãƒ§ãƒ³ï¼‰</t>
    <t id="20018">æœ€å¤§è·é›¢</t>
    <t id="20032">ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ï¼ˆã‚ªãƒ—ã‚·ãƒ§ãƒ³ï¼‰</t>
    <t id="20019">ã‚µã‚¤ã‚¯ãƒ«å¾…ã¡æ™‚é–“</t>
    <t id="20030">å°ã•ãªéŸ³é‡ã‚’è¨±å¯ã™ã‚‹</t>
    <t id="20031">ä½Žå®¹é‡ãƒ•ãƒ­ã‚¢ %</t>
    <t id="20110">å•†å“ã®é…é€å…ƒã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®ãƒªã‚¹ãƒˆ</t>
    <t id="20111">å•†å“ã®é…é€å…ˆã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³/å€‰åº«ã®ãƒªã‚¹ãƒˆ</t>
    <t id="20112">ç›®çš„åœ°ç·Šæ€¥åº¦ã®ã—ãã„å€¤: ã“ã®ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸ã‚ˆã‚Šä¸‹ã®ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ % ãŒå„ªå…ˆé…é€ã‚’å—ã‘å–ã‚Šã¾ã™</t>
    <t id="20113">ã‚½ãƒ¼ã‚¹ã®æœ€å°ã—ãã„å€¤: é…å¸ƒã™ã‚‹ã«ã¯ã€ã‚½ãƒ¼ã‚¹ã«ã“ã® % ã‚’è¶…ãˆã‚‹å€¤ãŒå¿…è¦ã§ã™</t>
    <t id="20114">ã‚½ãƒ¼ã‚¹ ã‚ªãƒ¼ãƒãƒ¼ãƒ•ãƒ­ãƒ¼ã®ã—ãã„å€¤: ã“ã® % ã‚’è¶…ãˆã‚‹ã¨ã€ã‚½ãƒ¼ã‚¹ã¯ç·Šæ€¥ã§ãªã„å®›å…ˆã«ã‚‚é…ä¿¡ã•ã‚Œã¾ã™ã€‚</t>
    <t id="20115">ã‚ªãƒ—ã‚·ãƒ§ãƒ³ã®ã‚¦ã‚§ã‚¢ãƒ•ã‚£ãƒ«ã‚¿ãƒ¼ã€‚ã™ã¹ã¦ã®å•†å“ã‚’ã‚½ãƒ¼ã‚¹ã‹ã‚‰é…å¸ƒã™ã‚‹ã«ã¯ç©ºã®ã¾ã¾ã«ã—ã¾ã™</t>
    <t id="20116">ç›®çš„åœ°ã«è¶…éŽãŒã‚ã‚‹å ´åˆã€ç›®çš„åœ°ã‹ã‚‰å‡ºç™ºåœ°ã¸ã®å¾€å¾©å›žåŽã‚’æœ‰åŠ¹ã«ã™ã‚‹</t>
    <t id="20117">å‰²ã‚Šå½“ã¦ç”¨ã®ã‚ªãƒ—ã‚·ãƒ§ãƒ³ã®ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã€‚ç©ºã®å ´åˆã€ã‚·ãƒƒãƒ—ã¯ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«å‰²ã‚Šå½“ã¦ã‚‰ã‚Œãªã„ã¾ã¾ã«ãªã‚Šã¾ã™ã€‚</t>
    <t id="20118">é€ä¿¡å…ƒã¨å®›å…ˆé–“ã®æœ€å¤§ã‚²ãƒ¼ãƒˆè·é›¢ (0 = ç„¡åˆ¶é™)</t>
    <t id="20132">ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãŒè¨­å®šã•ã‚Œã¦ã„ãªã„å ´åˆã«å¾…æ©Ÿæ™‚ãƒ‘ãƒ¼ã‚­ãƒ³ã‚°ã§ä½¿ç”¨ã™ã‚‹ä»»æ„ã®ãƒ›ãƒ¼ãƒ ã‚»ã‚¯ã‚¿ãƒ¼ã§ã™ã€‚</t>
    <t id="20119">é…å¸ƒã‚µã‚¤ã‚¯ãƒ«é–“ã®å¾…æ©Ÿæ™‚é–“</t>
    <t id="20130">é€šå¸¸ã®æœ€å°è²¨ç‰©å……å¡«é‡ã‚’ä¸‹å›žã‚‹ã€ç·Šæ€¥æ€§ã‚’è€ƒæ…®ã—ãŸå°ã•ãªé…é€ãƒãƒ£ãƒ³ã‚¯ã‚’è¨±å¯ã—ã¾ã™ã€‚</t>
    <t id="20131">ä½Žå®¹é‡ãƒ¢ãƒ¼ãƒ‰ãŒæœ‰åŠ¹ãªå ´åˆã«ä½¿ç”¨ã•ã‚Œã‚‹æœ€å°è²¨ç‰©å……å¡«çŽ‡ã€‚</t>
    <t id="20200">%1 %2 ã‚’ %3 ã‹ã‚‰ %4 ã«é…å¸ƒã—ã¾ã™</t>
    <t id="20201">Return trip: collecting %1 %2 from %3 to %4</t>
    <t id="20202">é…å¸ƒã¯å¿…è¦ã‚ã‚Šã¾ã›ã‚“ - ã™ã¹ã¦ã®å®›å…ˆã«é©åˆ‡ã«æä¾›ã•ã‚Œã¾ã™</t>
    <t id="20203">ã™ã¹ã¦ã®é€ä¿¡å…ƒã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãŒç„¡åŠ¹ã§ã™ - é…ä¿¡ã¯å¾…æ©Ÿä¸­ã§ã™</t>
    <t id="20204">ã™ã¹ã¦ã®å®›å…ˆã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãŒç„¡åŠ¹ã§ã™ - é…ä¿¡ã¯å¾…æ©Ÿä¸­ã§ã™</t>
    <t id="20205">é€ä¿¡å…ƒã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ %1 ãŒç ´å£Šã•ã‚Œã¾ã—ãŸ - é…ä¿¡ã‚ªãƒ¼ãƒ€ãƒ¼ã‹ã‚‰å‰Šé™¤ã•ã‚Œã¾ã—ãŸ</t>
    <t id="20206">å®›å…ˆã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ %1 ãŒç ´å£Šã•ã‚Œã¾ã—ãŸ - é…ä¿¡ã‚ªãƒ¼ãƒ€ãƒ¼ã‹ã‚‰å‰Šé™¤ã•ã‚Œã¾ã—ãŸ</t>
    <t id="20500">GalaxyTrader MK2 - ã‚°ãƒ­ãƒ¼ãƒãƒ«è¨­å®š</t>
    <t id="20501">MK2 ãƒ‡ã‚£ã‚¹ãƒˆãƒªãƒ“ãƒ¥ãƒ¼ã‚·ãƒ§ãƒ³ã®ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ</t>
    <t id="20510">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®æœ€å°ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="20511">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®é™çš„ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="20512">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®æœ€å¤§ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸%</t>
    <t id="20513">ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®ã‚µã‚¤ã‚¯ãƒ«å¾…æ©Ÿ (ç§’)</t>
    <t id="20514">æœ€å°è²¨ç‰©å……å¡«çŽ‡</t>
    <t id="20520">é€šçŸ¥ã®å†—é•·æ€§</t>
    <t id="20521">ãƒ‡ãƒãƒƒã‚°ãƒ¬ãƒ™ãƒ«</t>
    <t id="10006">å®¶ã«å¸°ã‚‹</t>
    <t id="10007">GalaxyTrader MK4-2 ä¾›çµ¦</t>
    <t id="10106">ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«åœæ³Šã—ã€å–å¼•ãŒå†é–‹ã•ã‚Œã‚‹ã¾ã§ãã“ã«ç•™ã¾ã‚Šã¾ã™</t>
    <t id="10107">é…é€å…ˆå„ªå…ˆåº¦ã‚¹ãƒ©ã‚¤ãƒ€ãƒ¼ä»˜ããƒ—ãƒ¬ã‚¤ãƒ¤ãƒ¼ä¾›çµ¦å‘½ä»¤</t>
    <t id="30026">ã‚µã‚¤ã‚¯ãƒ«é–“ã®å¸°å®…</t>
    <t id="30028">ã‚ªãƒ•ã‚¡ãƒ¼è¨­å®šã‚’ç„¡è¦–</t>
    <t id="30029">è²·ã„æ‰‹ä¾¡æ ¼ç¯„å›²</t>
    <t id="30027">æœ€å°è£½å“è²¯è”µ%</t>
    <t id="30126">æœ‰åŠ¹ã«ã™ã‚‹ã¨ã€ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã«æˆ»ã‚Šã€å–å¼•ã‚µã‚¤ã‚¯ãƒ«ã®é–“ã«ãƒ‰ãƒƒã‚­ãƒ³ã‚°ã—ã¾ã™ã€‚ç„¡åŠ¹ã«ã™ã‚‹ã¨ã€ç¾åœ¨ã®å ´æ‰€ã‹ã‚‰æ¤œç´¢ã‚’ç¶šè¡Œã—ã¾ã™ (å¾“æ¥ã®å‹•ä½œ)</t>
    <t id="30128">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®å£²è²·ã‚ªãƒ•ã‚¡ãƒ¼ãªã—ã§å†…éƒ¨ã‚¹ãƒˆãƒ¬ãƒ¼ã‚¸è»¢é€ã‚’è¨±å¯ã€‚ãƒãƒƒãƒ•ã‚¡ã®é›†è·ãƒ»é…é€ã«ç‰©å“äº¤æ›ã‚’ä½¿ç”¨ã€‚ã€Œè²¿æ˜“è¦å‰‡ã‚’ç„¡è¦–ã€ãŒã‚ªãƒ•ã®å ´åˆã¯ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã®è²¿æ˜“è¦å‰‡ãŒé©ç”¨ã•ã‚Œã¾ã™ã€‚</t>
    <t id="30129">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³è£½å“ã‚’å£²å´ã™ã‚‹éš›ã® NPC è²·ã„æ‰‹ã®æœ€ä½Žç›¸å¯¾ä¾¡æ ¼ã€‚å‘½ä»¤ã‚¹ãƒ©ã‚¤ãƒ€ãƒ¼ 0-200ï¼ˆ100 = å¹³å‡ã€0 = -100%ã€200 = +100%ï¼‰ã¯ -1.0 ã‹ã‚‰ +1.0 ã«å¯¾å¿œã€‚é«˜ã„ã»ã©é«˜å€¤ã®è²·ã„æ‰‹ã®ã¿ã€‚ä½Žã„ã»ã©è²·ã„æ‰‹ã®é¸æŠžè‚¢ãŒå¢—ãˆã‚‹ã€‚è£œçµ¦èµ°è¡Œã§ã¯ä¾›çµ¦å´ã®ä¾¡æ ¼ä¸Šé™ã«åè»¢ã—ãŸå€¤ã‚’ä½¿ç”¨ã€‚</t>
    <t id="30127">è£½å“ã¾ãŸã¯äº¤æ˜“å“ã‚’è²©å£²ã™ã‚‹å‰ã«å¿…è¦ãªã€ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³è²¯è”µã®æœ€å°å……å¡«çŽ‡ï¼ˆå“ç›®ã”ã¨ã®è¨­å®šæœ€å¤§å€¤ã«å¯¾ã™ã‚‹%ï¼‰ã€‚ã“ã®ã—ãã„å€¤æœªæº€ã®å“ç›®ã¯ã‚¹ã‚­ãƒƒãƒ—ã•ã‚Œã¾ã™ã€‚0 = æœ€å°ãªã—ã€‚</t>
    <t id="3107">ãƒžãƒ«ãƒãƒˆãƒ¬ãƒ¼ãƒ‰ã‚’ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã¦ã„ã¾ã™: %1ã€‚ %2 ã®åˆ©ç›Šã‚’å¾—ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚</t>
    <t id="3108">%1 %2 ã‚’ %3 ã‹ã‚‰ %4 ã§è²©å£²ã—ã¾ã™ã€‚ %5 ã®åˆ©ç›Šã‚’å¾—ã‚‹å¿…è¦ãŒã‚ã‚Šã¾ã™ã€‚</t>
    <t id="3110">%1 %2 ã®ä¾›çµ¦ã‚’ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã¦ã„ã¾ã™ã€‚%4 ã‹ã‚‰ %3 ã§èª¿é”ã—ã€%5 ã¸é…é€ã—ã¾ã™ã€‚é¡§å®¢ã®è²·å€¤ä¸Šé™ %6 - ä¸Šé™ã‚ˆã‚Š %7/å˜ä½å®‰ã„ï¼ˆåˆè¨ˆ %8ï¼‰ã€‚</t>
    <t id="3111">%1 %2 ã®ä¾›çµ¦ã‚’ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã¦ã„ã¾ã™ã€‚%3 ã‹ã‚‰ %4 ã¸ã€‚</t>
    <t id="3112">ä¾›çµ¦ã‚’ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã¦ã„ã¾ã™ï¼ˆ%1 åŒºé–“ï¼‰ï¼š%2ã€‚é¡§å®¢è²·å€¤ä¸Šé™ã‚ˆã‚Šåˆè¨ˆ %3 å®‰ã„ã€‚</t>
    <t id="3113">ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ãƒˆãƒ¬ãƒ¼ãƒ€ãƒ¼: è¼¸å‡ºãƒžãƒ«ãƒãƒˆãƒ¬ãƒ¼ãƒ‰ã‚’ã‚­ãƒ¥ãƒ¼ã«å…¥ã‚Œã¦ã„ã¾ã™: %1ã€‚äºˆæƒ³åˆ©ç›Š %2ã€‚</t>
    <t id="31029">ãƒ—ãƒ­ãƒ¼ãƒ–åœ¨åº«ç›®æ¨™</t>
    <t id="31030">è³¼å…¥ã™ã‚‹æŽ¡æŽ˜ãƒ‰ãƒ­ãƒ¼ãƒ³æ•°</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: æŽ¡æŽ˜å¯èƒ½ãªç‰©è³‡ãŒã‚ã‚Šã¾ã›ã‚“ã€‚èˆ¹ %1 [%2]ã€è‰¦éšŠï¼š%3</t>
    <t id="31201">Galaxy-Miner: ãƒ›ãƒ¼ãƒ ã‚¹ãƒ†ãƒ¼ã‚·ãƒ§ãƒ³ã¾ãŸã¯ãƒ›ãƒ¼ãƒ ä½ç½®ã‚’è¨­å®šã—ã¦ãã ã•ã„ã€‚</t>
    <t id="31130">å¿…è¦ãªã‚¿ã‚¤ãƒ—ï¼ˆå›ºä½“/é‰±çŸ³ã¾ãŸã¯æ¶²ä½“/ã‚¬ã‚¹ï¼‰ã‚’ä½¿ã„æžœãŸã—ãŸã¨ãã«ã€ãƒžã‚¤ãƒŠãƒ¼ãŒè³¼å…¥ã™ã‚‹åŽé›†ï¼ˆæŽ¡æŽ˜ï¼‰ãƒ‰ãƒ­ãƒ¼ãƒ³ã®æ•°ã€‚è³¼å…¥ã¯ã€èˆ¹ã«ãã®ã‚¿ã‚¤ãƒ—ã®åŽé›†ãƒ‰ãƒ­ãƒ¼ãƒ³ãŒ1ã¤ã‚‚ãªã„å ´åˆã«ã®ã¿ï¼ˆã‚«ã‚¦ãƒ³ãƒˆ=0ï¼‰ãƒˆãƒªã‚¬ãƒ¼ã•ã‚Œã¾ã™ã€‚å°‘ãªãã¨ã‚‚1ã¤æŒã£ã¦ã„ã‚‹ãƒžã‚¤ãƒŠãƒ¼ã¯è£œå……ã‚‚å†è³¼å…¥ã‚‚ã•ã‚Œãšã€æ—¢å­˜ã®ãƒ‰ãƒ­ãƒ¼ãƒ³ã¯ä¿æŒã•ã‚Œã¾ã™ã€‚èˆ¹ã®ãƒ¦ãƒ‹ãƒƒãƒˆãƒ™ã‚¤å®¹é‡ã«ã‚ˆã£ã¦åˆ¶é™ã•ã‚Œã¾ã™ã€‚åŽé›†ãƒ‰ãƒ­ãƒ¼ãƒ³ã®è‡ªå‹•è³¼å…¥ã‚’ç„¡åŠ¹ã«ã—ã¦æ‰‹å‹•ã§ç®¡ç†ã™ã‚‹ã«ã¯0ã«è¨­å®šã—ã¾ã™ã€‚ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆã®5ã¯é€šå¸¸ã®æŽ¡æŽ˜é€Ÿåº¦ã®ãŸã‚ã®å®Œå…¨ãªãƒ‰ãƒ­ãƒ¼ãƒ³ã‚»ãƒƒãƒˆã§ã™ã€‚</t>
    <t id="31129">ãƒžã‚¤ãƒŠãƒ¼ãŒè£œå……æ—…è¡Œã”ã¨ã«è³¼å…¥ã™ã‚‹ãƒªã‚½ãƒ¼ã‚¹ ãƒ—ãƒ­ãƒ¼ãƒ–ã®æ•°ã€‚è³¼å…¥ã¯ã€ãƒ‡ãƒ—ãƒ­ã‚¤ã”ã¨ã§ã¯ãªãã€èˆ¹ãŒãƒ—ãƒ­ãƒ¼ãƒ–ã‚’ä½¿ã„æžœãŸã—ãŸã¨ã (ã‚«ã‚¦ãƒ³ãƒˆ = 0) ã«ã®ã¿ãƒˆãƒªã‚¬ãƒ¼ã•ã‚Œã¾ã™ã€‚ã“ã‚Œã«ã‚ˆã‚Šã€ãƒžã‚¤ãƒŠãƒ¼ã¯ã€å„ãƒ‡ãƒ—ãƒ­ã‚¤å¾Œã«è¿‚å›žã™ã‚‹ã®ã§ã¯ãªãã€ä¾›çµ¦å®Ÿè¡Œã®é–“ã«ãƒ—ãƒ­ãƒ¼ãƒ–ã®å…¨è² è·ã‚’å®Ÿè¡Œã—ã¾ã™ã€‚èˆ¹ã®å±•é–‹å¯èƒ½ãªç·å®¹é‡ã«ã‚ˆã£ã¦åˆ¶é™ã•ã‚Œã¾ã™ï¼ˆè¡›æ˜Ÿ/é‰±å±±ãªã©ã¨å…±æœ‰ï¼‰ã€‚å±•é–‹å¯èƒ½ãªç©ºãã‚¹ãƒšãƒ¼ã‚¹ã‚ˆã‚Šå¤§ãã„ã‚¹ãƒ©ã‚¤ãƒ€ãƒ¼å€¤ã¯ã€ã€Œé©åˆã™ã‚‹ã‚‚ã®ã‚’åŸ‹ã‚ã‚‹ã€ãŸã‚ã«æ­£å¸¸ã«ä½Žä¸‹ã—ã¾ã™ã€‚ Auto Deploy Resource Probes ãŒæœ‰åŠ¹ã«ãªã£ã¦ã„ã‚‹å ´åˆã«ã®ã¿æœ‰åŠ¹ã§ã™ã€‚åŒã˜è¨­å®šã«ã‚ˆã‚Šã€æŽ¡æŽ˜ã‚»ã‚¯ã‚¿ãƒ¼ã§ã®æ—¥å’Œè¦‹çš„ãªãƒ—ãƒ­ãƒ¼ãƒ–ã®ãƒ‡ãƒ—ãƒ­ã‚¤ãƒ¡ãƒ³ãƒˆã¨ã€å¤ã„ãƒ—ãƒ­ãƒ¼ãƒ– (ãƒã‚¹ã‚±ãƒƒãƒˆé–¢é€£ã®ãƒªã‚½ãƒ¼ã‚¹ãŒãªã„ã‚»ã‚¯ã‚¿ãƒ¼ã®ãƒ—ãƒ­ãƒ¼ãƒ–) ã®åŽé›†ã‚‚ä¿ƒé€²ã•ã‚Œã¾ã™ã€‚</t>
    <t id="3226">å¸ä»¤å®˜ %1 æ§˜ã€\n\nç§ã¯ %2 ã«åœæ³Šã—ã¦ãŠã‚Šã€Trading Academy ç™»éŒ²æ‹…å½“è€…ãŒç§ã® "%3" ãƒ—ãƒ­ã‚°ãƒ©ãƒ ã¸ã®ç™»éŒ²ã‚’ç¢ºèªã—ã¾ã—ãŸã€‚ãƒ•ãƒªãƒ¼ãƒˆ ã‚¢ã‚«ã‚¦ãƒ³ãƒˆã«ã¯ã‚³ãƒ¼ã‚¹ã®æŽˆæ¥­æ–™ã¨ã—ã¦ %4 Cr ãŒå¼•ãè½ã¨ã•ã‚Œã¦ãŠã‚Šã€ç§ã¯ãã®æŠ•è³‡ã‚’è»½è¦–ã—ã¦ã„ã¾ã›ã‚“ã€‚\n\nã“ã‚Œã¯æ—¥å¸¸çš„ãªèªå®šã§ã¯ã‚ã‚Šã¾ã›ã‚“ã€‚ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼ã®è¬›å¸«ã¯ãƒ™ãƒ†ãƒ©ãƒ³ã®å•†äººã‚„ã‚³ãƒ³ã‚½ãƒ¼ã‚·ã‚¢ãƒ ã®äº¤æ¸‰äººã§ã‚ã‚Šã€ã“ã“ã§ã®ã‚«ãƒªã‚­ãƒ¥ãƒ©ãƒ ã¯æ¨™æº–çš„ãªæ˜‡é€²è©¦é¨“ã‚ˆã‚Šã‚‚ã¯ã‚‹ã‹ã«åŽ³ã—ã„ã‚‚ã®ã§ã™ã€‚ä»Šå¾Œ %5 åˆ†é–“ã§ã€é«˜åº¦ãªå–å¼•ãƒ—ãƒ­ãƒˆã‚³ãƒ«ã€ãƒ—ãƒ¬ãƒƒã‚·ãƒ£ãƒ¼ã®ä¸‹ã§ã®å¸‚å ´åˆ†æžã€è¦‹ç¿’ã„è€…ã¨é”äººã‚’åˆ†ã‘ã‚‹äº¤æ¸‰æˆ¦è¡“ã«ã¤ã„ã¦é›†ä¸­çš„ã«æŒ‡å°Žã‚’å—ã‘ã¾ã™ã€‚\n\næœ€çµ‚è©¦é¨“ãŒå®Œäº†ã—ã¦ãƒ‰ãƒƒã‚­ãƒ³ã‚°ã‚’è§£é™¤ã—ãŸã‚‰ã€ç§ã¯ã€Œ%3ã€ã®ç§°å·ã‚’ä¿æŒã—ã€å­¦ã‚“ã ã™ã¹ã¦ã‚’å–å¼•æ¥­å‹™ã«æŒã¡å¸°ã‚‹ã“ã¨ã«ãªã‚Šã¾ã™ã€‚ã“ã®æ©Ÿä¼šã‚’ 1 å˜ä½ã‚‚ç„¡é§„ã«ã¯ã—ã¾ã›ã‚“ã€‚\n\næ„Ÿè¬ã¨æ±ºæ„ã‚’è¾¼ã‚ã¦ã€\n%6\n%7 ã«ä¹—èˆ¹ã—ã¾ã™ã€‚</t>
    <t id="9924">ãƒˆãƒ¬ãƒ¼ãƒ‡ã‚£ãƒ³ã‚° ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼ ã‚³ãƒ¼ã‚¹ã¯ä¸­æ­¢ã•ã‚Œã¾ã—ãŸ: ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆ %1 ã¯ã‚¢ã‚«ãƒ‡ãƒŸãƒ¼ ãƒ‰ãƒƒã‚¯ã§ %2 Cr ã®æ–™é‡‘ã‚’æ”¯æ‰•ã†ä½™è£•ãŒã‚ã‚Šã¾ã›ã‚“ (%3 Cr ã‚’æŒã£ã¦ã„ã¾ã™)ã€‚ã‚³ãƒ¼ã‚¹ã¯ã‚­ãƒ£ãƒ³ã‚»ãƒ«ã•ã‚Œã€ãƒ‘ã‚¤ãƒ­ãƒƒãƒˆå–å¼•ãŒå†é–‹ã•ã‚Œã¾ã™ã€‚</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="82">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">ë„í‚¹ ë° ëŒ€ê¸° (GalaxyTrader MK3)</t>
    <t id="10002">ê°¤ëŸ­ì‹œíŠ¸ë ˆì´ë” MK3</t>
    <t id="10003">ìµœì¢… ì‹œí—˜ (GalaxyTrader MK3)</t>
    <t id="10004">íŒŒì¼ëŸ¿ êµí™˜ ëž‘ë°ë¶€</t>
    <t id="10005">[ì‚¬ìš© ì¤‘ë‹¨] GalaxyTrader MK4 ê³µê¸‰ (ë ˆê±°ì‹œ)</t>
    <t id="10101">ìŠ¤í…Œì´ì…˜ì— ë„í‚¹í•˜ê³  ì§€ì •ëœ ì‹œê°„ ë™ì•ˆ ëŒ€ê¸°</t>
    <t id="10102">ìŠ¤í‚¬ ì§„í–‰ì´ ìžˆëŠ” ìžìœ¨ ë¬´ì—­</t>
    <t id="10103">í›ˆë ¨ ì‹œì„¤ì—ì„œ íŒŒì¼ëŸ¿ ì¸ì¦ì„ ìœ„í•œ ìµœì¢… ì‹œí—˜ ì‘ì‹œ</t>
    <t id="10104">ì¡°ì¢…ì‚¬ êµí™˜ì„ ìœ„í•´ ì§‘ê²°ì§€ì— ì •ë°•</t>
    <t id="10105">ìºì‹œì™€ ì‹¤ì‹œê°„ ê²€ìƒ‰ì„ í™œìš©í•œ í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜ ê³µê¸‰ ì¤‘ì‹¬ ê±°ëž˜ (ë ˆê±°ì‹œ)</t>
    <t id="10201">%sì—ì„œ %s êµ¬ë§¤</t>
    <t id="10202">%sì— %s íŒë§¤</t>
    <t id="10203">%sì™€ ë¬´ì—­</t>
    <t id="1000">ê°¤ëŸ­ì‹œíŠ¸ë ˆì´ë” MK3</t>
    <t id="1001">XP ì§„í–‰ ë° í•¨ëŒ€ ì¡°ì •ì´ ìžˆëŠ” ê³ ê¸‰ ë¬´ì—­ ì‹œìŠ¤í…œ</t>
    <t id="1002">ìž‘ì „ ê¸°ì§€</t>
    <t id="1003">ì‚¬ì „ ì„¤ì • ì‚¬ìš©</t>
    <t id="1004">ëª¨ë“  ìƒí’ˆ ë¬´ì—­</t>
    <t id="1005">í•©ë²• ìƒí’ˆ ë¬´ì—­</t>
    <t id="1006">ë¶ˆë²• ìƒí’ˆ ë¬´ì—­</t>
    <t id="1007">XP ì§„í–‰ í™œì„±í™”</t>
    <t id="1008">í•¨ëŒ€ ì¡°ì • í™œì„±í™”</t>
    <t id="1009">ì‹œìž¥ ë¶„ì„ í™œì„±í™”</t>
    <t id="1010">ì˜ì—­ ê´€ë¦¬ í™œì„±í™”</t>
    <t id="1011">ë¶ˆë²• ìƒí’ˆ í—ˆìš©</t>
    <t id="1012">í•­í•´ ì¼ì§€ í•­ëª©</t>
    <t id="1013">ìœ„í—˜ í—ˆìš©ë„</t>
    <t id="1014">í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜ ìš°ì„ </t>
    <t id="1015">ìžë™ ìƒí’ˆ</t>
    <t id="1016">ê±°ë¦¬ íŽ˜ë„í‹° %</t>
    <t id="1017">ì•Œë¦¼ ìˆ˜ì¤€</t>
    <t id="1018">í•¨ëŒ€ ì¡°ì •</t>
    <t id="1019">í™”ë¬¼ ì ìž¬ ëª©í‘œ %</t>
    <t id="1050">ì‹œìž¥ ì—…ë°ì´íŠ¸ ë¹ˆë„</t>
    <t id="1051">ë¬´ì—­ í‰ê°€ ê¸°ë¡</t>
    <t id="1052">ì„¹í„° í™”ì´íŠ¸ë¦¬ìŠ¤íŠ¸</t>
    <t id="1054">í•­ê³µëª¨í•¨/ë³´ì¡°í•¨ ë¬´ì‹œ</t>
    <t id="1056">ê±´ì„¤ ì €ìž¥ì†Œ ë¬´ì‹œ</t>
    <t id="1058">ê±°ëž˜ ê·œì¹™ ë¬´ì‹œ</t>
    <t id="1060">MK1 ì œê³µ ìŠ¤í…Œì´ì…˜ ë¬´ì‹œ</t>
    <t id="1063">ê°œë°œì¤‘</t>
    <t id="1064">ìš°ì„  ìƒí’ˆ</t>
    <t id="1065">ìš°ì„  ì ìˆ˜ %</t>
    <t id="1066">ë¬´ì—­ ì±„ì ì—ì„œ ì„ í˜¸í•˜ëŠ” ìƒí’ˆìž…ë‹ˆë‹¤. í•´ë‹¹ ì ìˆ˜ì— ìš°ì„ ìˆœìœ„ ì ìˆ˜ %ë¥¼ ê³±í•©ë‹ˆë‹¤.</t>
    <t id="1067">ìš°ì„ ìˆœìœ„ ìƒí’ˆì— ëŒ€í•œ ì ìˆ˜ ë°°ìœ¨: 100%=ë³´í†µ, 150%=+50%%, 200%=2x, 300%=3x. ë§ˆì§€ë§‰ìœ¼ë¡œ ì ìš©ë˜ì—ˆìŠµë‹ˆë‹¤.</t>
    <t id="1068">â”€â”€ ìš°ì„  ìƒí’ˆ í•„í„° â”€â”€</t>
    <t id="1069">ìƒí’ˆ (ìˆ˜ë™)</t>
    <t id="1070">ë¶ˆë²• ê²½ë¡œ í•„í„°</t>
    <t id="1072">ì§‘ì—ì„œë§Œ ì„œë¹„ìŠ¤ ì œê³µ</t>
    <t id="1073">í”Œë ˆì´ì–´ ê³µê¸‰ìž ìš°ì„ ìˆœìœ„</t>
    <t id="1074">íŒ©ì…˜ ê³µê¸‰ìž ìš°ì„ ìˆœìœ„</t>
    <t id="1075">ë¹Œë“œ ì €ìž¥ì†Œ í¬í•¨</t>
    <t id="1076">ë¦¬ì†ŒìŠ¤ í¬í•¨</t>
    <t id="1077">ì¤‘ê°„ì²´ í¬í•¨</t>
    <t id="1078">ìƒí‘œ í¬í•¨</t>
    <t id="1080">ì£¼ê¸°ë‹¹ ìµœëŒ€ ê±°ëž˜</t>
    <t id="1081">ì—­ì¶”ì  ê³µì°¨</t>
    <t id="1082">ìµœì†Œ í™”ë¬¼ ì‚¬ìš© %</t>
    <t id="1083">í”Œë ˆì´ì–´ êµ¬ë§¤ ìˆ˜ì •ìž %</t>
    <t id="1085">í™ˆ ìŠ¤í…Œì´ì…˜ì— í• ë‹¹</t>
    <t id="1086">ì ìš© ê±°ë¦¬</t>
    <t id="1088">ìˆ˜ìš” ì»¤ë²„ë¦¬ì§€ë¥¼ ìœ„í•œ ì§‘ìœ¼ë¡œë¶€í„°ì˜ ìµœëŒ€ ì í”„ ê±°ë¦¬</t>
    <t id="1090">ìˆ˜ìš”/ê³µê¸‰ ë§¤ì¹­ì— ë¬´ì—­ìš© ì œí’ˆ í¬í•¨</t>
    <t id="1091">ì ìˆ˜ ì „ìš© ê³„ì‚°ì—ì„œ í”Œë ˆì´ì–´ ì†Œìœ  ê³µê¸‰ì—…ì²´ ê°€ê²©ì— ìˆ˜ì •ìžê°€ ì ìš©ë¨</t>
    <t id="1092">í”Œë ˆì´ì–´ ê°€ê²© ë¬´ì‹œ</t>
    <t id="1093">í™œì„±í™”ë˜ë©´ ì„¤ì •ëœ íŒë§¤ ê°€ê²©ì— ê´€ê³„ì—†ì´ í•­ìƒ í”Œë ˆì´ì–´ ì†Œìœ  ìŠ¤í…Œì´ì…˜ì—ì„œ êµ¬ë§¤í•˜ê³  NPC ì„¸ë ¥ì—ë§Œ íŒë§¤í•©ë‹ˆë‹¤. ìžì‹ ì˜ ìŠ¤í…Œì´ì…˜ì—ì„œ ì´ˆê³¼ ìž¬ê³ ë¥¼ ì²­ì‚°í•˜ëŠ” ë° ìœ ìš©í•©ë‹ˆë‹¤.</t>
    <t id="1094">ì°¨ë‹¨ëœ ì •ê±°ìž¥</t>
    <t id="1095">ì—¬ê¸°ì—ì„œ ì„ íƒí•œ ì •ê±°ìž¥ì€ MK3 ê±°ëž˜ì—ì„œ ì œì™¸ë©ë‹ˆë‹¤. ìƒì¸ì€ í•´ë‹¹ ì •ê±°ìž¥ì—ì„œ êµ¬ë§¤í•˜ê±°ë‚˜ íŒë§¤í•˜ì§€ ì•ŠìŠµë‹ˆë‹¤.</t>
    <t id="1096">ìœ íœ´ ì£¼ì°¨</t>
    <t id="1097">í™œì„±í™”í•˜ë©´ ìž‘ì—…ì„ ë°˜ë³µí•´ì„œ ì°¾ì§€ ëª»í•œ í•¨ì„ ì´ ëª¨í•­ ìŠ¤í…Œì´ì…˜ ë˜ëŠ” ëª¨í•­ ì„¹í„°ì— ì£¼ì°¨í•©ë‹ˆë‹¤. ì„¹í„° ì£¼ì°¨ëŠ” í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜ì„ ìš°ì„ í•˜ê³  ê·¸ë‹¤ìŒ ìš°í˜¸ ìŠ¤í…Œì´ì…˜ì„ ì„ íƒí•©ë‹ˆë‹¤. ë„í‚¹ í•´ì œ ì‹œê°„ì€ ì „ì—­ ì„¤ì •ì—ì„œ ì§€ì •í•©ë‹ˆë‹¤(0 = ìž‘ì—…ì„ ì°¾ì„ ë•Œê¹Œì§€ docked ìƒíƒœ ìœ ì§€).</t>
    <t id="1098">ìžë™ ìŠ¤ì¼€ì¼</t>
    <t id="1099">í™œì„±í™”í•˜ë©´ í•„ìˆ˜ í›ˆë ¨ ë˜ëŠ” ë¬´ì—­ ì•„ì¹´ë°ë¯¸ ì´ìˆ˜ í›„ ì í”„ ê±°ë¦¬ ìŠ¬ë¼ì´ë”ê°€ íŒŒì¼ëŸ¿ì˜ ìµœëŒ€ í—ˆìš© ë²”ìœ„ë¡œ ì„¤ì •ë©ë‹ˆë‹¤. ìˆ˜ë™ìœ¼ë¡œ ê±°ë¦¬ë¥¼ ì„¤ì •í•˜ë ¤ë©´ í•´ì œí•˜ì„¸ìš”.</t>
    <t id="11001">ê±´ì„¤ ì €ìž¥ì†Œ ìš°ì„ ìˆœìœ„</t>
    <t id="11002">ì •ê±°ìž¥ ìš°ì„ ìˆœìœ„</t>
    <t id="11003">ë³´ì¡° í•¨ì„  ìš°ì„ ìˆœìœ„</t>
    <t id="11004">í•­ê³µëª¨í•¨ ìš°ì„ ìˆœìœ„</t>
    <t id="11005">0 = ë¹„í™œì„±. 1-10 = ì ìˆ˜ ë°°ìœ¨(10 = ìµœëŒ€ ê°€ì¤‘ì¹˜). ìµœì¢… ì ìˆ˜ = ê³µê¸‰ ì ìˆ˜ Ã— ë°°ìœ¨.</t>
    <t id="11006">1 = ì¶”ê°€ ì ìˆ˜ ì—†ìŒ(ìš°ì„  í’ˆëª© ëª©ë¡ ìœ ì§€). 2-10 = ê±°ëž˜ í’ˆëª©ì´ ìš°ì„  ëª©ë¡ì— ìžˆìœ¼ë©´ (ë°°ìœ¨âˆ’1)Ã— ê¸°ë³¸ ê³µê¸‰ ì ìˆ˜ë¥¼ ë”í•¨. ìœ í˜• ì ìˆ˜ ìœ„ì— ì ìš©.</t>
    <t id="11007">ìš°ì„  í’ˆëª© ë³´ë„ˆìŠ¤</t>
    <t id="11008">%1: ëª¨ë“  ë°°ì†¡ ëŒ€ìƒ ìš°ì„ ìˆœìœ„ ìŠ¬ë¼ì´ë”ê°€ 0ìœ¼ë¡œ ì„¤ì •ë˜ì–´ ìžˆìŠµë‹ˆë‹¤. ì´ ëª…ë ¹ì—ëŠ” ë°°ì†¡ ëŒ€ìƒì´ ì—†ìŠµë‹ˆë‹¤. ê³µê¸‰ì„ ìž¬ê°œí•˜ë ¤ë©´ ìµœì†Œ í•œ ê°œì˜ í´ëž˜ìŠ¤(ê±´ì„¤ ì €ìž¥ì†Œ, ìŠ¤í…Œì´ì…˜, ë³´ì¡° í•¨ì„  ë˜ëŠ” ìºë¦¬ì–´)ë¥¼ í™œì„±í™”í•˜ì„¸ìš”.</t>
    <t id="7001">[ì§„ê¸‰]</t>
    <t id="7002">[í›ˆë ¨]</t>
    <t id="7008">[í´ë°±]</t>
    <t id="7009">[ê²©ë¦¬ë¨]</t>
    <t id="7003">[ìˆ˜ë¦¬]</t>
    <t id="7004">[ë³´ê¸‰]</t>
    <t id="7005">[ì •ë¹„]</t>
    <t id="7006">[ìž¬ê²½ë¡œ]</t>
    <t id="7007">[ìŠ¹ì¸]</t>
    <t id="1020">ìƒì¸ì´ ìž‘ì „í•˜ëŠ” í™ˆ ì„¹í„° ë˜ëŠ” ìŠ¤í…Œì´ì…˜ ì„ íƒ</t>
    <t id="1021">ìƒí’ˆ êµ¬ë§¤ ì‹œ ìµœëŒ€ ê²Œì´íŠ¸ ì í”„ ê±°ë¦¬ (íŒŒì¼ëŸ¿ ìŠ¤í‚¬ë¡œ ì œí•œë¨)</t>
    <t id="1022">ìƒí’ˆ íŒë§¤ ì‹œ ìµœëŒ€ ê²Œì´íŠ¸ ì í”„ ê±°ë¦¬ (íŒŒì¼ëŸ¿ ìŠ¤í‚¬ë¡œ ì œí•œë¨)</t>
    <t id="1023">ì¹´í…Œê³ ë¦¬ ê¸°ë°˜ ì ì ˆí•œ ìƒí’ˆ ìžë™ ì„ íƒ</t>
    <t id="1024">íŠ¹ì • ë¬´ì—­ ìƒí’ˆ ìˆ˜ë™ ì„ íƒ</t>
    <t id="1025">ë°€ìˆ˜ ë° ë¶ˆë²• ìƒí’ˆ ë¬´ì—­ í—ˆìš©</t>
    <t id="1026">ë³´ì•ˆ í—ˆìš©ë„: 0.0=ì•ˆì „í•œ ì„¹í„°ë§Œ, 1.0=ëª¨ë“  ìœ„í—˜ ìˆ˜ìš©</t>
    <t id="1027">ë¬´ì—­ ê²½í—˜ì„ í†µí•´ íŒŒì¼ëŸ¿ ìŠ¤í‚¬ í–¥ìƒ</t>
    <t id="1028">í•„ìš” ì‹œ íŒŒì¼ëŸ¿ì„ ìžë™ìœ¼ë¡œ í›ˆë ¨ì†Œë¡œ ë³´ëƒ„</t>
    <t id="1029">ì¶©ëŒì„ í”¼í•˜ê¸° ìœ„í•´ ì—¬ëŸ¬ ë¬´ì—­ì„  ì¡°ì •</t>
    <t id="1030">ìƒí’ˆ í¬ì»¤ìŠ¤: 0=ê· í˜•, 1=ê³ ê¸‰, 2=ê¸°ë³¸ í•„ìš”í’ˆ, 3=ë¶ˆë²•, 4=ëŒ€ëŸ‰ ìƒí’ˆ</t>
    <t id="1031">ë¬´ì—­ ì§€ì—­: 0=ê· í˜•, 1=í™ˆ í¬ì»¤ìŠ¤, 2=ìžìœ  ì´ë™</t>
    <t id="1032">ì•Œë¦¼ ìˆ˜ì¤€: 0=ìµœì†Œ, 1=ì¼ë°˜, 2=ìƒì„¸ ë©”ì‹œì§€</t>
    <t id="1033">íŒë§¤ ìš°ì„ ìˆœìœ„ ì§€ì • ì „ ëª©í‘œ í™”ë¬¼ ì‚¬ìš©ë¥  ë°±ë¶„ìœ¨</t>
    <t id="1034">ì‹œìž¥ ë°ì´í„° ë° ê°€ê²© ì •ë³´ ì—…ë°ì´íŠ¸ ë¹ˆë„</t>
    <t id="1035">ë””ë²„ê·¸ ì¶œë ¥ ìˆ˜ì¤€: 0=ì—†ìŒ, 1=ê¸°ë³¸, 2=ìƒì„¸ ê¸°ë¡</t>
    <t id="1036">ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ ê²½ë¡œë¥¼ í•¨ëŒ€ì™€ ê³µìœ  (ë¹ ë¥¸ ì ‘ê·¼ì„ ìœ„í•´ ìºì‹œë¨)</t>
    <t id="1037">ë¬´ì—­ì„ ìºì‹œí•˜ê³  í•¨ëŒ€ì™€ ê³µìœ í•˜ëŠ” ë° í•„ìš”í•œ ìµœì†Œ ì´ìµ</t>
    <t id="1038">ìºì‹œëœ ë¬´ì—­ ê²½ë¡œê°€ ë¬´íš¨í™”ë˜ê¸° ì „ í—ˆìš©ë˜ëŠ” ìµœëŒ€ ì´ìµ ê°ì†Œ</t>
    <t id="1039">ìºì‹œëœ ë¬´ì—­ ê²½ë¡œê°€ ë§Œë£Œë˜ê¸° ì „ ìœ íš¨í•œ ê¸°ê°„</t>
    <t id="1040">ê°œë³„ ë¬´ì—­ í‰ê°€ ë° ê±°ë¶€ì— ëŒ€í•œ ìƒì„¸ ê¸°ë¡ í™œì„±í™” (ë§¤ìš° ìƒì„¸í•  ìˆ˜ ìžˆìŒ)</t>
    <t id="1041">ë¬´ì—­ë‹¹ í•­í•´ ì¼ì§€ í•­ëª© ë° ëª°ìž…í˜• í›ˆë ¨ ë©”ì‹œì§€ í™œì„±í™” (TaterTrader ìŠ¤íƒ€ì¼)</t>
    <t id="1053">ì´ ëª©ë¡ì˜ ì„¹í„°ëŠ” ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì—ì„œ ì œì™¸ë©ë‹ˆë‹¤ (í•­ìƒ í—ˆìš©ë¨)</t>
    <t id="1055">ë¬´ì—­ì—ì„œ í•­ê³µëª¨í•¨ ë° ë³´ì¡°í•¨ ì œì™¸</t>
    <t id="1057">ë¬´ì—­ì—ì„œ ê±´ì„¤ ì €ìž¥ì†Œ í•¨ì„  ì œì™¸</t>
    <t id="1059">ì œì•ˆ ê²€ìƒ‰ ì‹œ ìŠ¤í…Œì´ì…˜ ê±°ëž˜ ê·œì¹™ì„ ë¬´ì‹œí•©ë‹ˆë‹¤ (ê³ ê¸‰; ì¼ë°˜ì ìœ¼ë¡œ ì°¨ë‹¨ëœ ì œì•ˆì„ ì„ íƒí•  ìˆ˜ ìžˆìŒ)</t>
    <t id="1061">ë³´ê¸‰ ëª¨ë“œê°€ í• ë‹¹ëœ MK1 ìƒì¸ì´ ìžˆëŠ” í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜ ê±´ë„ˆë›°ê¸°</t>
    <t id="1062">ìžì‹ ì˜ ìŠ¤í…Œì´ì…˜ì´ í¬í•¨ëœ ë¬´ì—­ ê²½ë¡œì— ì ìˆ˜ ë³´ë„ˆìŠ¤ (10% ë³´ë„ˆìŠ¤)</t>
    <t id="1071">ë¶ˆë²• ìƒí’ˆ í—ˆìš©ì´ í™œì„±í™”ë˜ë©´ ì í”„ ê²½ë¡œì˜ ëª¨ë“  ë¶€ë¬¸(êµ¬ë§¤, íŒë§¤ ë° ì¤‘ê°œ ë¶€ë¬¸)ì—ì„œ í•©ë²•ì ì¸ ê²½ìš° ë¶ˆë²• ìƒí’ˆë§Œ ê±°ëž˜í•©ë‹ˆë‹¤.</t>
    <t id="1087">ê³µê¸‰ìž êµ¬ë§¤ ê²€ìƒ‰ì„ ìœ„í•œ ì§‘ì—ì„œ ìµœëŒ€ ì í”„ ê±°ë¦¬</t>
    <t id="1089">ë¹„í™œì„±í™”ë˜ë©´ ì„ ë°•ì€ ê°€ì • ì „ìš© ëª¨ë“œ ëŒ€ì‹  ê¸´ê¸‰ ìš°ì„ ìˆœìœ„ì— ë”°ë¼ ì„œë¹„ìŠ¤ ì§€ì—­ì— ìŠ¤í…Œì´ì…˜ì„ ê³µê¸‰í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤.</t>
    <t id="2000">%sì´(ê°€) %s XPë¥¼ íšë“í–ˆìŠµë‹ˆë‹¤!</t>
    <t id="2001">%sì´(ê°€) ë ˆë²¨ì—…í–ˆìŠµë‹ˆë‹¤! ìƒˆ ë ˆë²¨: %s</t>
    <t id="2002">%sì´(ê°€) í›ˆë ¨ì´ í•„ìš”í•©ë‹ˆë‹¤! ê°€ìž¥ ê°€ê¹Œìš´ ì¡°ì„ ì†Œ ë˜ëŠ” ë¬´ì—­ ìŠ¤í…Œì´ì…˜ìœ¼ë¡œ ë³´ë‚´ì£¼ì„¸ìš”.</t>
    <t id="2003">%sì´(ê°€) %sì—ì„œ í›ˆë ¨ì„ ì‹œìž‘í–ˆìŠµë‹ˆë‹¤</t>
    <t id="2004">%sì´(ê°€) í›ˆë ¨ì„ ì™„ë£Œí•˜ê³  ë ˆë²¨ %s ì¸ì¦ì„ ë°›ì•˜ìŠµë‹ˆë‹¤!</t>
    <t id="2005">%sì´(ê°€) í›ˆë ¨ í›„ ìŠ¤í‚¬ ë ˆë²¨ %sì— ë„ë‹¬í–ˆìŠµë‹ˆë‹¤! %sì—ì„œ XP ì§„í–‰ì´ í•´ì œë˜ì—ˆìŠµë‹ˆë‹¤.</t>
    <t id="2006">%sì´(ê°€) ìŠ¤í‚¬ ë ˆë²¨ %sì— %s ê±°ëž˜ë¡œ ë„ë‹¬í–ˆìŠµë‹ˆë‹¤!</t>
    <t id="2007">%sì´(ê°€) ë ˆë²¨ %s í›ˆë ¨ì„ ì™„ë£Œí–ˆìŠµë‹ˆë‹¤! %sì—ì„œ XP ì§„í–‰ì´ í•´ì œë˜ì—ˆìŠµë‹ˆë‹¤.</t>
    <t id="3000">%sì´(ê°€) ë¬´ì—­ì„ ì™„ë£Œí–ˆìŠµë‹ˆë‹¤! ì´ìµ: %s Cr</t>
    <t id="3001">%sì´(ê°€) ì‹œìž¥ ìƒí™©ì„ ë¶„ì„ ì¤‘...</t>
    <t id="3002">%sì´(ê°€) ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ ê²½ë¡œë¥¼ ì°¾ì•˜ìŠµë‹ˆë‹¤!</t>
    <t id="3003">%sì— ëŒ€í•œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ ê²½ë¡œê°€ ì—†ìŠµë‹ˆë‹¤</t>
    <t id="3100">í™”ë¬¼ì—ì„œ %1 %2ì„(ë¥¼) %3ì— %4ì— íŒë§¤ ì¤‘ìž…ë‹ˆë‹¤. %5ì˜ ì´ìµì„ ì–»ì„ ê²ƒìž…ë‹ˆë‹¤.</t>
    <t id="3101">%1 %2ì— ëŒ€í•œ ë¬´ì—­ ì£¼ë¬¸ì„ ëŒ€ê¸°ì—´ì— ì¶”ê°€í–ˆìŠµë‹ˆë‹¤. %3ì— %4ì—ì„œ êµ¬ë§¤í•˜ì—¬ %5ì— %6ì— íŒë§¤í•©ë‹ˆë‹¤. %7ì˜ ì´ìµì„ ì–»ì„ ê²ƒìž…ë‹ˆë‹¤.</t>
    <t id="3102">ìŠ¤í…Œì´ì…˜ íŠ¸ë ˆì´ë”: %3(%5%%)ì—ì„œ %4(%6%%)ë¡œ %1 %2 ê³µê¸‰ ì¤‘.</t>
    <t id="3103">ìŠ¤í…Œì´ì…˜ íŠ¸ë ˆì´ë”: %1 %2ì„(ë¥¼) %3ì— %4ì— íŒë§¤í•©ë‹ˆë‹¤. ì˜ˆìƒ ì´ìµì€ %5ìž…ë‹ˆë‹¤.</t>
    <t id="3104">%1 %2ì— ëŒ€í•œ ë¬´ì—­ì´ ì„±ê³µì ìœ¼ë¡œ ì™„ë£Œë˜ì—ˆìŠµë‹ˆë‹¤. ì´ ì´ìµ: %3 í¬ë ˆë”§.</t>
    <t id="3105">ìºì‹œëœ ë¬´ì—­ ê²½ë¡œ: %1 %2 ì—ì„œ %3 ì—ì„œ %4 (ì´ìµ: %5 Cr)</t>
    <t id="3106">\nì´ ë¬´ì—­ ì „ê¹Œì§€ì˜ ì´ ì˜ˆìƒ ì´ìµ: %1 Cr.</t>
    <t id="3120">íŒŒì¼ëŸ¿ ì „ì†¡ ì‹œìž‘ë¨</t>
    <t id="3121">ì „ì†¡ í”„ë¡œí† ì½œì´ ìŠ¹ì¸ë˜ì—ˆìŠµë‹ˆë‹¤. %1(%2) ë° %3(%4)ëŠ” ë„í‚¹ ë° ì§€íœ˜ ì¢Œì„ êµí™˜ì„ ìœ„í•´ %5(%6)ë¡œ ì´ë™ ì¤‘ìž…ë‹ˆë‹¤.</t>
    <t id="3200">Hello Commander %1,\n\nI have gained enough experience to take my certification exam for the title "%2". The examination will take approximately %3 minutes at %4.\n\nThis is an important milestone in my career development. The exam will test my knowledge of advanced trading protocols, market analysis, and fleet coordination procedures.\n\nI'm confident in my abilities and excited to prove myself worthy of this advancement. Wish me luck!\n\nRespectfully,\n%5\nAboard %6</t>
    <t id="3201">ì§€íœ˜ê´€ %1ë‹˜ê»˜,\n\nì¢‹ì€ ì†Œì‹ìž…ë‹ˆë‹¤! ì¸ì¦ ì‹œí—˜ì„ ì„±ê³µì ìœ¼ë¡œ ì™„ë£Œí•˜ê³  "%2" ì¹­í˜¸ë¥¼ ë°›ì•˜ìŠµë‹ˆë‹¤!\n\nì‹œí—˜ì€ ê³ ê¸‰ ë¬´ì—­ ì „ëžµ, ìœ„í—˜ í‰ê°€ í”„ë¡œí† ì½œ ë° í•¨ëŒ€ ì¡°ì • ì ˆì°¨ë¥¼ ë‹¤ë£¨ì—ˆìŠµë‹ˆë‹¤. ìš°ìˆ˜í•œ ì„±ì ìœ¼ë¡œ í†µê³¼í–ˆë‹¤ê³  ë³´ê³ ë“œë¦½ë‹ˆë‹¤.\n\nì´ì œ ë” ë³µìž¡í•œ ë¬´ì—­ ìž‘ì—…ì„ ì²˜ë¦¬í•  ìžê²©ì´ ìžˆìœ¼ë©° í•¨ëŒ€ì˜ ì„±ê³µì— ë” í° ê¸°ì—¬ë¥¼ í•  ìˆ˜ ìžˆê²Œ ë˜ì–´ ê¸°ì©ë‹ˆë‹¤. ì œ ì „ë¬¸ì„± ê°œë°œì— íˆ¬ìží•´ ì£¼ì…”ì„œ ê°ì‚¬í•©ë‹ˆë‹¤.\n\nìƒˆë¡œìš´ í—Œì‹ ê³¼ í•¨ê»˜,\n%3\nì¸ì¦ëœ %2\n%4 í•¨ì„ ì—ì„œ</t>
    <t id="3202">ì§€íœ˜ê´€ %1ë‹˜ê»˜,\n\nìž‘ì „ ìš”êµ¬ì‚¬í•­ìœ¼ë¡œ ì¸í•´ ì¸ì¦ ì‹œí—˜ì´ ì¤‘ë‹¨ë˜ì—ˆìŒì„ ì•Œë ¤ë“œë¦½ë‹ˆë‹¤. ìƒí™©ì´ í—ˆë½í•  ë•Œ ë‹¤ì‹œ ì˜ˆì•½í•´ì•¼ í•©ë‹ˆë‹¤.\n\nì €ëŠ” ì œ ìŠ¤í‚¬ì„ í–¥ìƒì‹œí‚¤ëŠ” ë° ê³„ì† í—Œì‹ í•˜ë©° ì‹œí—˜ ê³¼ì •ì„ ìž¬ê°œí•  ìˆ˜ ìžˆì„ ë•Œ ì•Œë ¤ë“œë¦¬ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%2\n%3 í•¨ì„ ì—ì„œ</t>
    <t id="3203">ì§€íœ˜ê´€ %1ë‹˜ê»˜,\n\ní˜„ìž¬ ì¸ì¦ ì‹œí—˜ì„ ìœ„í•´ %2ë¡œ í–¥í•˜ëŠ” ì¤‘ìž…ë‹ˆë‹¤. ì—¬í–‰ì€ ì œê°€ ë°°ìš´ ê²ƒì„ ë³µìŠµí•˜ê³  ê²½ë ¥ì˜ ì´ ì¤‘ìš”í•œ ë‹¨ê³„ì— ëŒ€í•´ ì •ì‹ ì ìœ¼ë¡œ ì¤€ë¹„í•  ì‹œê°„ì„ ì¤ë‹ˆë‹¤.\n\nì˜ˆìƒ ë„ì°©: %3ë¶„\nì‹œí—˜ ì†Œìš” ì‹œê°„: %4ë¶„\n\nì œ ëŠ¥ë ¥ì— ëŒ€í•œ ì‹ ë¢°ì™€ ìŠ¹ì§„ ê¸°íšŒì— ê°ì‚¬ë“œë¦½ë‹ˆë‹¤.\n\nê²°ì˜ë¥¼ ê°€ì§€ê³ ,\n%5\n%6 í•¨ì„ ì—ì„œ</t>
    <t id="3204">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nì‹œìŠ¤í…œ ì ê²€ ì¤‘ í™”ë¬¼ì°½ì—ì„œ í™”ë¬¼ì„ ë°œê²¬í–ˆìŠµë‹ˆë‹¤. ì •ìƒì ì¸ ë¬´ì—­ ìž‘ì—…ì„ ì‹œìž‘í•˜ê¸° ì „ì— ì´ ìƒí’ˆì„ íŒë§¤í•´ì•¼ í•©ë‹ˆë‹¤.\n\nìš°ë¦¬ ë¬´ì—­ ê²€ìƒ‰ì„ ì‚¬ìš©í•˜ì—¬ ìµœê³ ì˜ êµ¬ë§¤ìžë¥¼ ì°¾ê³  ì´ í™”ë¬¼ì„ ì•ˆì „í•˜ê²Œ ë‚´ë¦´ ê²ƒìž…ë‹ˆë‹¤. í™”ë¬¼ì°½ì´ ë¹„ë©´ ìžë™í™”ëœ ë¬´ì—­ì„ ì§„í–‰í•˜ê² ìŠµë‹ˆë‹¤.\n\nìƒíƒœ: ìµœì  íŒë§¤ ìž¥ì†Œ ê²€ìƒ‰ ì¤‘\n\nì„±ì‹¤ížˆ,\n%1 í•¨ì„ ì—ì„œ</t>
    <t id="3205">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nì„ ì²´ ë¬´ê²°ì„±ì´ %1%%ë¡œ ë–¨ì–´ì¡ŒìŠµë‹ˆë‹¤ (ìž„ê³„ê°’: %2%%). ë ˆë²¨ %3 íŒŒì¼ëŸ¿ìœ¼ë¡œì„œ ìžë™ ìˆ˜ë¦¬ ì„œë¹„ìŠ¤ë¥¼ ìš”ì²­í•  ê¶Œí•œì´ ìžˆìŠµë‹ˆë‹¤.\n\nìˆ˜ë¦¬ ìž‘ì—…ì„ ìœ„í•´ %4ë¡œ í–¥í•˜ëŠ” ì¤‘ìž…ë‹ˆë‹¤. ì˜ˆìƒ ë¹„ìš©ì€ %5 Crì´ë©° ì˜ˆì‚° ë²”ìœ„ ë‚´ìž…ë‹ˆë‹¤.\n\nìˆ˜ë¦¬ê°€ ì™„ë£Œë˜ë©´ ì™„ì „í•œ êµ¬ì¡°ì  ë¬´ê²°ì„±ìœ¼ë¡œ ë¬´ì—­ ìž‘ì—…ì„ ìž¬ê°œí•˜ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%6 í•¨ì„ ì—ì„œ</t>
    <t id="3206">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nê¸´ê¸‰ ìž¬ì • ê²½ê³ \n\nì„ ì²´ ë¬´ê²°ì„±ì´ %1%%ë¡œ ìœ„í—˜ ìˆ˜ì¤€ìž…ë‹ˆë‹¤ (ìž„ê³„ê°’: %2%%), í•˜ì§€ë§Œ ì‚¬ìš© ê°€ëŠ¥í•œ ìžê¸ˆ(%3 Cr)ì´ ì™„ì „í•œ ìˆ˜ë¦¬(ì˜ˆìƒ ë¹„ìš©: %4 Cr)ì— ì¶©ë¶„í•˜ì§€ ì•ŠìŠµë‹ˆë‹¤.\n\nì‚¬ìš© ê°€ëŠ¥í•œ ìžê¸ˆì„ ì‚¬ìš©í•˜ì—¬ %5ë¡œ ë¶€ë¶„ ìˆ˜ë¦¬ë¥¼ ìœ„í•´ í–¥í•˜ëŠ” ì¤‘ìž…ë‹ˆë‹¤. ì´ìƒì ì¸ í•´ê²°ì±…ì€ ì•„ë‹ˆì§€ë§Œ ìž‘ì „ ëŠ¥ë ¥ì„ ìœ ì§€í•˜ëŠ” ë° í•„ìš”í•©ë‹ˆë‹¤.\n\ní–¥í›„ ìœ ì§€ë³´ìˆ˜ ìž‘ì—…ì„ ìœ„í•´ ì¶”ê°€ ìžê¸ˆ í• ë‹¹ì„ ê³ ë ¤í•´ ì£¼ì‹œê¸° ë°”ëžë‹ˆë‹¤.\n\nìš°ë ¤í•˜ì§€ë§Œ ê²°ì˜ë¥¼ ê°€ì§€ê³ ,\n%6 í•¨ì„ ì—ì„œ</t>
    <t id="3207">ì§€íœ˜ê´€ë‹˜ê»˜,\n\në ˆë²¨ %1 ì¸ì¦ì€ ë°©ì–´ ìž¥ë¹„ì˜ ìžë™ ë³´ê¸‰ì„ í—ˆìš©í•©ë‹ˆë‹¤. ì‹œìŠ¤í…œì„ í™•ì¸í•œ í›„ ëŒ€ì‘ ìˆ˜ë‹¨ ë° ë°°ì¹˜ ê°€ëŠ¥í•œ ìž¥ë¹„ê°€ ê¶Œìž¥ ìž„ê³„ê°’ ì´í•˜ìž„ì„ í™•ì¸í–ˆìŠµë‹ˆë‹¤.\n\në°©ì–´ ìž¥ë¹„ë¥¼ ë³´ê¸‰í•˜ê¸° ìœ„í•´ %2ë¡œ í–¥í•˜ëŠ” ì¤‘ìž…ë‹ˆë‹¤:\nâ€¢ ëŒ€ì‘ ìˆ˜ë‹¨: ìµœì  ìš©ëŸ‰ê¹Œì§€ ë³´ê¸‰\nâ€¢ ë°©ì–´ ë“œë¡ , ë¬´ì—­ ë“œë¡ , ë ˆì´ì € í„°ë ›: ê· í˜• í”„ë¡œí•„ ì ìš©\n\nì´ ë³´ê¸‰ì€ ë¬´ì—­ íš¨ìœ¨ì„±ì„ ìœ ì§€í•˜ë©´ì„œ ìš°ì£¼ ìœ„í˜‘ì— ëŒ€í•´ ë” ë‚˜ì€ ë³´í˜¸ë¥¼ ë³´ìž¥í•©ë‹ˆë‹¤.\n\nê²½ê³„í•˜ë©°,\n%3 í•¨ì„ ì—ì„œ</t>
    <t id="3212">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nì„ ì²´ ë¬´ê²°ì„±ì´ %1%%ë¡œ ë–¨ì–´ì¡ŒìŠµë‹ˆë‹¤ (ìž„ê³„ê°’: %2%%), ìˆ˜ë¦¬ ì„œë¹„ìŠ¤ê°€ í•„ìš”í•©ë‹ˆë‹¤. ê·¸ëŸ¬ë‚˜ %3ì˜ ê°€ìž¥ ê°€ê¹Œìš´ ìˆ˜ë¦¬ ìŠ¤í…Œì´ì…˜ì´ í˜„ìž¬ ì„¹í„° ì´ë™ ì œí•œ(ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ê²½ë¡œ)ìœ¼ë¡œ ì¸í•´ ì ‘ê·¼í•  ìˆ˜ ì—†ìŠµë‹ˆë‹¤.\n\nì´ ì œí•œì—ë„ ë¶ˆêµ¬í•˜ê³  ë¬´ì—­ ìž‘ì—…ì„ ê³„ì†í•˜ê² ìŠµë‹ˆë‹¤. ì•ˆì „í•œ ê²½ë¡œê°€ ë‹¤ì‹œ ì‚¬ìš© ê°€ëŠ¥í•´ì§€ë©´ ìžë™ìœ¼ë¡œ ìˆ˜ë¦¬ ì„œë¹„ìŠ¤ë¥¼ ì°¾ê² ìŠµë‹ˆë‹¤.\n\nìƒí™©ì„ ëª¨ë‹ˆí„°ë§í•˜ê³  ìˆ˜ë¦¬ê°€ ê°€ëŠ¥í•´ì§€ë©´ ì•Œë ¤ë“œë¦¬ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%4 í•¨ì„ ì—ì„œ</t>
    <t id="3213">ì§€íœ˜ê´€ë‹˜ê»˜,\n\në°©ì–´ ìž¥ë¹„ ë³´ê¸‰ì´ í•„ìš”í•˜ì§€ë§Œ %1ì˜ ê°€ìž¥ ê°€ê¹Œìš´ ìž¥ë¹„ ìŠ¤í…Œì´ì…˜ì´ í˜„ìž¬ ì„¹í„° ì´ë™ ì œí•œ(ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ê²½ë¡œ)ìœ¼ë¡œ ì¸í•´ ì ‘ê·¼í•  ìˆ˜ ì—†ìŠµë‹ˆë‹¤.\n\nì´ ì œí•œì—ë„ ë¶ˆêµ¬í•˜ê³  ë¬´ì—­ ìž‘ì—…ì„ ê³„ì†í•˜ê² ìŠµë‹ˆë‹¤. ì•ˆì „í•œ ê²½ë¡œê°€ ë‹¤ì‹œ ì‚¬ìš© ê°€ëŠ¥í•´ì§€ë©´ ìžë™ìœ¼ë¡œ ë³´ê¸‰ ì„œë¹„ìŠ¤ë¥¼ ì°¾ê² ìŠµë‹ˆë‹¤.\n\nìƒí™©ì„ ëª¨ë‹ˆí„°ë§í•˜ê³  ë³´ê¸‰ì´ ê°€ëŠ¥í•´ì§€ë©´ ì•Œë ¤ë“œë¦¬ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%2 í•¨ì„ ì—ì„œ</t>
    <t id="3208">ì§€íœ˜ê´€ë‹˜ê»˜,\n\n%1 ë° ì£¼ë³€ ì„¹í„°(ë°˜ê²½ %2 ì í”„, ìµœì†Œ ì´ìµ ìž„ê³„ê°’: %3 Cr)ì˜ ì‹œìž¥ì— ëŒ€í•œ ì² ì €í•œ ë¶„ì„ì„ ì™„ë£Œí–ˆì§€ë§Œ, ìš”êµ¬ì‚¬í•­ì„ ì¶©ì¡±í•˜ëŠ” ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ ê¸°íšŒë¥¼ ì°¾ì§€ ëª»í–ˆìŠµë‹ˆë‹¤.\n\në¬´ì—­ ë¶„ì„ ë³´ê³ ì„œ:\ní‰ê°€ëœ ì´ ê¸°íšŒ: %4\n\nê±°ë¶€ ì„¸ë¶€ì‚¬í•­:\n- ë„í‚¹ ì œí•œ: %5ê±´ì˜ ë¬´ì—­\n  (ìŠ¤í…Œì´ì…˜ì´ ì œ í•¨ì„  ë“±ê¸‰ì„ í—ˆìš©í•˜ì§€ ì•ŠìŒ)\n- ìˆ˜ìµì„± ë¶€ì¡±: %6ê±´ì˜ ë¬´ì—­\n  (ìµœì†Œ ì´ìµ ìž„ê³„ê°’ ë¯¸ë§Œ)\n- ë¶€ì¡±í•œ ë³¼ë¥¨: %7ê±´ì˜ ë¬´ì—­\n  (ê±°ëž˜ ê°€ëŠ¥í•œ ìˆ˜ëŸ‰ì´ 0 ë˜ëŠ” ìŒìˆ˜)\n- ë³´ì•ˆ ì œí•œ: %8ê±´ì˜ ë¬´ì—­\n  (ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ìŠ¤í…Œì´ì…˜ ë˜ëŠ” ìœ„í—˜í•œ ì„¹í„°)\n\nê¶Œìž¥ì‚¬í•­:\n- ì´ìµ ìž„ê³„ê°’ ì¡°ì • ê³ ë ¤\n- ìµœëŒ€ ë¬´ì—­ ê±°ë¦¬ í™•ìž¥\n- ì„¹í„° ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ì„¤ì • ê²€í† \n- ì‹œìž¥ ìƒí™© ê°œì„  ëŒ€ê¸°\n\nì‹œìž¥ì„ ê³„ì† ëª¨ë‹ˆí„°ë§í•˜ê³  ìˆ˜ìµì„± ìžˆëŠ” ê¸°íšŒê°€ ìƒê¸°ë©´ ì•Œë ¤ë“œë¦¬ê² ìŠµë‹ˆë‹¤.\n\nëŒ€ê¸° ì¤‘,\në´‰ì‚¬í•©ë‹ˆë‹¤</t>
    <t id="3209">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nê¸´ê¸‰ ê²½ë¡œ ê²½ê³ \n\nìœ„í˜‘ ì •ë³´ ì‹œìŠ¤í…œì´ ê³„íšëœ ë¬´ì—­ ê²½ë¡œì— ì„¹í„° %1(ìœ„í˜‘ ìˆ˜ì¤€ %2)ì´ í¬í•¨ë˜ì–´ ìžˆìŒì„ ê°ì§€í–ˆìŠµë‹ˆë‹¤. í•¨ì„ ê³¼ ìŠ¹ë¬´ì›ì˜ ì•ˆì „ì„ ìœ„í•´ ì¦‰ì‹œ í˜„ìž¬ ë¬´ì—­ ìž‘ì—…ì„ ì¤‘ë‹¨í•©ë‹ˆë‹¤.\n\nì·¨í•´ì§„ ì¡°ì¹˜:\n- ëª¨ë“  ë¬´ì—­ ì£¼ë¬¸ ì·¨ì†Œ\n- ì•ˆì „ ìž‘ì „ ëª¨ë“œë¡œ ë³µê·€\n- ìœ„í—˜í•œ ì„¹í„°ë¥¼ í”¼í•˜ëŠ” ëŒ€ì²´ ë¬´ì—­ ê²½ë¡œ ì°¾ê¸°\n- í™”ë¬¼ ì²˜ë¦¬: ìžë™ (í•„ìš”ì‹œ ì•ˆì „í•œ ìž¥ì†Œì—ì„œ ëª¨ë“  í™”ë¬¼ íŒë§¤)\n\në™ì  ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ì‹œìŠ¤í…œì€ ìœ„í˜‘ì´ ì œê±°ë  ë•Œê¹Œì§€ ì´ ì„¹í„°ë¥¼ í†µí•œ í–¥í›„ ë¬´ì—­ì„ ë°©ì§€í•©ë‹ˆë‹¤.\n\nì•ˆì „ì´ ì œ ìµœìš°ì„  ê³¼ì œìž…ë‹ˆë‹¤.\n\nê²½ê³„í•˜ë©°,\n%3 í•¨ì„ ì—ì„œ</t>
    <t id="3210">ì§€íœ˜ê´€ë‹˜ê»˜,\n\níƒˆì¶œ ê²½ë¡œ ì‹œìž‘ë¨\n\ní˜„ìž¬ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ì„¹í„° %1ì— ìžˆìœ¼ë©° ì•ˆì „í•˜ê²Œ íƒˆì¶œí•  ìˆ˜ ìžˆëŠ” ë¬´ì—­ ê²½ë¡œë¥¼ ì°¾ì•˜ìŠµë‹ˆë‹¤.\n\në¬´ì—­ ê²½ë¡œ:\nêµ¬ë§¤: %2 (ì„¹í„°: %3)\níŒë§¤: %4 (ì„¹í„°: %5)\nìƒí’ˆ: %6 (x%7)\nì˜ˆìƒ ì´ìµ: %8 Cr\n\ní•¨ì„ ì€ ì´ ë¬´ì—­ì„ ì™„ë£Œí•œ í›„ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ì„¹í„°ë¥¼ ë– ë‚  ê²ƒìž…ë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\në´‰ì‚¬í•©ë‹ˆë‹¤</t>
    <t id="3211">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nê²©ë¦¬ ë¬´ì—­ ëª¨ë“œ\n\ní˜„ìž¬ ì„¹í„° %2ì— ìžˆì§€ë§Œ ë‹¤ë¥¸ ì„¹í„°ë¡œì˜ ëª¨ë“  ê²½ë¡œê°€ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ í—ˆë¸Œ ì„¹í„°ë¡œ ì¸í•´ ì°¨ë‹¨ë˜ì—ˆìŠµë‹ˆë‹¤. ì´ëŠ” ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ìƒí™©ì´ ë³€ê²½ë  ë•Œê¹Œì§€ í˜„ìž¬ ì„¹í„° ë‚´ì—ì„œë§Œ ë¬´ì—­í•  ìˆ˜ ìžˆìŒì„ ì˜ë¯¸í•©ë‹ˆë‹¤.\n\nìƒí™©:\ní˜„ìž¬ ì„¹í„°: %2\nìƒíƒœ: ê²©ë¦¬ë¨ (ë¸”ëž™ë¦¬ìŠ¤íŠ¸ë˜ì§€ ì•Šì€ ì„¹í„°ì´ì§€ë§Œ ê²½ë¡œê°€ ì°¨ë‹¨ë¨)\në¬´ì—­ ëª¨ë“œ: ì„¹í„° ë‚´ ë¬´ì—­ë§Œ\n\në¬´ì—­ ì‹œìŠ¤í…œì´ ì‚¬ìš© ê°€ëŠ¥í•œ ì„¹í„° ë‚´ ë¬´ì—­ ê¸°íšŒë¥¼ ìš°ì„ ì‹œí•˜ë„ë¡ ì´ìµ ìž„ê³„ê°’ì„ ìžë™ìœ¼ë¡œ ì¡°ì •í–ˆìŠµë‹ˆë‹¤.\n\nìƒí™©ì„ ê³„ì† ëª¨ë‹ˆí„°ë§í•˜ê³  ê²½ë¡œê°€ ë‹¤ì‹œ ì‚¬ìš© ê°€ëŠ¥í•´ì§€ë©´ ì•Œë ¤ë“œë¦¬ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%1 í•¨ì„ ì—ì„œ</t>
    <t id="3218">ì§€íœ˜ê´€ë‹˜ê»˜,\n\nê²½ë¡œ ë³€ê²½ ê°ì§€ë¨\n\nì„¹í„° %1ì— ì§„ìž…í•  ë•Œ í•­ë²• ì‹œìŠ¤í…œì´ ëª©ì ì§€ %2 (%3)ë¡œì˜ ê²½ë¡œê°€ ë³€ê²½ë˜ì—ˆìŒì„ ê°ì§€í–ˆìŠµë‹ˆë‹¤.\n\nê²½ë¡œ ë¶„ì„:\n- ì •ìƒ ê±°ë¦¬: %4 ì í”„\n- ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ê³ ë ¤ ê±°ë¦¬: %5\n- ìƒíƒœ: %6\n\ní•­ë²• ì»´í“¨í„°ëŠ” ì„¹í„° ì´ë™ ì œí•œìœ¼ë¡œ ì¸í•´ ì„ í˜¸ ê²½ë¡œê°€ ë” ì´ìƒ ì‹¤í–‰ ê°€ëŠ¥í•˜ì§€ ì•ŠìŒì„ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. í•¨ì„ ê³¼ ìŠ¹ë¬´ì›ì˜ ì•ˆì „ì„ ìœ„í•´ ì¦‰ì‹œ í˜„ìž¬ ë¬´ì—­ ìž‘ì—…ì„ ì¤‘ë‹¨í•©ë‹ˆë‹¤.\n\nì·¨í•´ì§„ ì¡°ì¹˜:\n- ëª¨ë“  ë¬´ì—­ ì£¼ë¬¸ ì·¨ì†Œ\n- ì•ˆì „ ìž‘ì „ ëª¨ë“œë¡œ ë³µê·€\n- ì°¨ë‹¨ëœ ì„¹í„°ë¥¼ í”¼í•˜ëŠ” ëŒ€ì²´ ë¬´ì—­ ê²½ë¡œ ì°¾ê¸°\n- í™”ë¬¼ ì²˜ë¦¬: ìžë™ (í•„ìš”ì‹œ ì•ˆì „í•œ ìž¥ì†Œì—ì„œ ëª¨ë“  í™”ë¬¼ íŒë§¤)\n\ní•­ë²• ì‹œìŠ¤í…œì€ í–¥í›„ ê²½ë¡œ ê³„íšì—ì„œ ì°¨ë‹¨ëœ ì„¹í„°ë¥¼ ìžë™ìœ¼ë¡œ í”¼í•  ê²ƒìž…ë‹ˆë‹¤.\n\nì•ˆì „ì´ ì œ ìµœìš°ì„  ê³¼ì œìž…ë‹ˆë‹¤.\n\nê²½ê³„í•˜ë©°,\n%7 í•¨ì„ ì—ì„œ</t>
    <t id="3219">ì„¹í„° %1 ì •í™”ë¨ - ëª¨ë“  ìœ„í˜‘ ì œê±°ë¨</t>
    <t id="3220">Commander,\n\nENEMY SHIP ESCAPED\n\nOur threat intelligence system has lost track of enemy ship %3, which has escaped from blacklisted sector %1.\n\nDETAILS:\n- Escaped Ship: %3\n- Sector Left: %1\n- Destination Sector: %2\n- Status: Tracking lost - ship has left our monitored area\n\nWhile this ship is no longer a threat in sector %1, we have lost visual contact and cannot confirm its current status or intentions in sector %2.\n\nOur tracking systems will continue monitoring sector %1 for remaining threats. If all tracked enemies leave or are eliminated, the sector will be automatically cleared from the blacklist.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3221">ì§€íœ˜ê´€ë‹˜ê»˜,\n\në” ë¨¼ ê±°ë¦¬(ìµœëŒ€ %3 ì í”„)ì—ì„œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ ê¸°íšŒë¥¼ ì°¾ì„ ìˆ˜ ì—†ì—ˆìŠµë‹ˆë‹¤. ì´ëŸ¬í•œ ê²½ë¡œê°€ í˜„ìž¬ ì„¹í„° ì´ë™ ì œí•œ(ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ê²½ë¡œ)ìœ¼ë¡œ ì¸í•´ ì ‘ê·¼í•  ìˆ˜ ì—†ê¸° ë•Œë¬¸ìž…ë‹ˆë‹¤.\n\nìƒí™©:\ní˜„ìž¬ ì„¹í„°: %2\nì›ëž˜ ê²€ìƒ‰ ë²”ìœ„: %3 ì í”„\ní´ë°± ê²€ìƒ‰ ë²”ìœ„: %4 ì í”„\n\nì´ì œ %4 ì í”„ ë‚´ì˜ ì¸ê·¼ ì„¹í„°ì— ê²€ìƒ‰ì„ ì§‘ì¤‘í•˜ê² ìŠµë‹ˆë‹¤. ì´ ì§€ì—­ì—ì„œëŠ” ê²½ë¡œê°€ ì ‘ê·¼ ê°€ëŠ¥í•  ê°€ëŠ¥ì„±ì´ ë” ë†’ìŠµë‹ˆë‹¤. ì´ê²ƒì€ ì‹¤ì œ ìˆ˜ìµì„± ë¶€ì¡±ì´ ì•„ë‹Œ ê±°ë¦¬ ì œí•œìœ¼ë¡œ ì¸í•´ ì´ì „ì— í•„í„°ë§ëœ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ì„ ì°¾ëŠ” ë° ë„ì›€ì´ ë  ê²ƒìž…ë‹ˆë‹¤.\n\nì¸ê·¼ ì§€ì—­ì—ì„œ ì ì ˆí•œ ë¬´ì—­ ê¸°íšŒë¥¼ ì°¾ìœ¼ë©´ ì•Œë ¤ë“œë¦¬ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%1 í•¨ì„ ì—ì„œ</t>
    <t id="3222">ì§€íœ˜ê´€ë‹˜ê»˜,\n\në¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ì„¹í„°\n\nìœ„í˜‘ ì •ë³´ ì‹œìŠ¤í…œì´ ì„¹í„° %1ì—ì„œ ì ëŒ€ì  í™œë™ì„ ê°ì§€í•˜ê³  ë¬´ì—­ ìž‘ì—…ì„ ë³´í˜¸í•˜ê¸° ìœ„í•´ ì´ ì„¹í„°ë¥¼ ìžë™ìœ¼ë¡œ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì— ì¶”ê°€í–ˆìŠµë‹ˆë‹¤.\n\nê°ì§€ëœ ì  í•¨ì„ :\n%2\n\nê°ì§€í•œ í•¨ì„ : %3\n\nìš°ë¦¬ í•¨ì„ ê³¼ ìŠ¹ë¬´ì›ì˜ ì•ˆì „ì„ ìœ„í•´ ì´ ì„¹í„°ë¥¼ í†µí•œ ëª¨ë“  ë¬´ì—­ ê²½ë¡œê°€ ì°¨ë‹¨ë˜ì—ˆìŠµë‹ˆë‹¤. ìš°ë¦¬ í•¨ì„ ì€ ìœ„í˜‘ì´ ì œê±°ë  ë•Œê¹Œì§€ ì´ ì„¹í„°ë¥¼ ìžë™ìœ¼ë¡œ ìš°íšŒí•  ê²ƒìž…ë‹ˆë‹¤.\n\nì¶”ì  ì¤‘ì¸ ëª¨ë“  ì  í•¨ì„ ì´ ì œê±°ë˜ê±°ë‚˜ ì§€ì—­ì„ ë– ë‚˜ë©´ ì„¹í„°ê°€ ìžë™ìœ¼ë¡œ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì—ì„œ ì œê±°ë©ë‹ˆë‹¤.\n\nê²½ê³„í•˜ë©°,\nìœ„í˜‘ ì •ë³´ ì‹œìŠ¤í…œ</t>
    <t id="3223">ì§€íœ˜ê´€ë‹˜ê»˜,\n\në ˆë²¨ %1 ì‹œí—˜ì„ ìœ„í•œ ì ‘ê·¼ ê°€ëŠ¥í•œ í›ˆë ¨ ìŠ¤í…Œì´ì…˜ì„ ì°¾ì„ ìˆ˜ ì—†ìŠµë‹ˆë‹¤. ìš”ì²­í•˜ì‹  ëŒ€ë¡œ ë¬´ì—­ ìž‘ì—…ì„ ê³„ì†í•˜ê² ì§€ë§Œ, í•„ìš”í•œ í›ˆë ¨ì„ ì™„ë£Œí•  ë•Œê¹Œì§€ ê²½í—˜ì¹˜ë¥¼ ì–»ì§€ ëª»í•  ê²ƒìž„ì„ ì´í•´í•©ë‹ˆë‹¤. ì´ ë¬´ì—­ í•­í•´ í›„ ë‹¤ì‹œ ê°€ëŠ¥í•œ í›ˆë ¨ ê¸°íšŒë¥¼ ì°¾ì•„ë³´ê² ìŠµë‹ˆë‹¤.\n\nì¡´ê²½ì„ ë‹´ì•„,\n%2 í•¨ì„ ì—ì„œ</t>
    <t id="3224">í›ˆë ¨ ë¼ì´ì„ ìŠ¤ ìˆ˜ìˆ˜ë£Œ: %1 Cr</t>
    <t id="3225">ë³´ë„ˆìŠ¤: í›ˆë ¨ ì¤‘ ì¶•ì ëœ ê²½í—˜ìœ¼ë¡œ %1ê°œì˜ ì¶”ê°€ ê¸°ìˆ  ë ˆë²¨%2ì„ íšë“í–ˆìŠµë‹ˆë‹¤! í˜„ìž¬ ë ˆë²¨: %3</t>
    <t id="3214">%1ë‹˜ì„ ìœ„í•´ ì¼í•˜ê²Œ ë˜ì–´ ì˜ê´‘ìž…ë‹ˆë‹¤! ê·€í•˜ì˜ ì§€íœ˜ í•˜ì— ë¬´ì—­ ê²½ë ¥ì„ ì‹œìž‘í•˜ê²Œ ë˜ì–´ ê¸°ì©ë‹ˆë‹¤. ê·€í•˜ë¥¼ ìž˜ ì„¬ê¸°ê³  ì„±ê³µì— ê¸°ì—¬í•˜ê¸° ìœ„í•´ ìµœì„ ì„ ë‹¤í•˜ê² ìŠµë‹ˆë‹¤.</t>
    <t id="3215">%1ë‹˜, ì´ë²ˆ íœ´ê°€ë¥¼ ì£¼ì…”ì„œ ê°ì‚¬í•©ë‹ˆë‹¤! ë¬´ì—­ì—ì„œ ë–¨ì–´ì ¸ ìžˆëŠ” ì‹œê°„ì„ ì¦ê²¼ìœ¼ë©° ì œ ìŠ¤í‚¬ì€ ê·¸ëŒ€ë¡œ ìœ ì§€ë˜ì—ˆìŠµë‹ˆë‹¤. í•„ìš”í•˜ì‹¤ ë•Œë§ˆë‹¤ ë‹¤ì‹œ ì¼í•  ìˆ˜ ìžˆê¸°ë¥¼ ê¸°ëŒ€í•©ë‹ˆë‹¤. ê·¸ë•Œê¹Œì§€ ì œ ë¬´ì—­ ì§€ì‹ì„ ë‚ ì¹´ë¡­ê²Œ ìœ ì§€í•˜ê² ìŠµë‹ˆë‹¤!</t>
    <t id="3216">íœ´ê°€ì—ì„œ ëŒì•„ì™€ ë‹¤ì‹œ ì¼í•  ì¤€ë¹„ê°€ ë˜ì—ˆìŠµë‹ˆë‹¤, %1ë‹˜! ì œ ë¬´ì—­ ìŠ¤í‚¬ì€ ì—¬ì „ížˆ ë‚ ì¹´ë¡­ë©° %2ì—ì„œ ê·€í•˜ë¥¼ ê³„ì† ì„¬ê¸°ê¸°ë¥¼ ê¸°ëŒ€í•©ë‹ˆë‹¤. ìž˜ ì‰¬ì—ˆìŠµë‹ˆë‹¤!</t>
    <t id="3217">%1ë¡œì˜ ì „ì†ì„ ì£¼ì…”ì„œ ê°ì‚¬í•©ë‹ˆë‹¤, %2ë‹˜! ì´ ìƒˆë¡œìš´ ë°°ì •ì„ ì˜ê´‘ìœ¼ë¡œ ìƒê°í•˜ë©° ìƒˆ í•¨ì„ ì„ ìž˜ ëŒë³¼ ê²ƒìž…ë‹ˆë‹¤. ì œ ë¬´ì—­ ê²½í—˜ê³¼ ìŠ¤í‚¬ì€ ê·¸ëŒ€ë¡œ ìœ ì§€ë˜ì—ˆìœ¼ë©° ê·€í•˜ë¥¼ ê³„ì† ì„¬ê¸¸ ì¤€ë¹„ê°€ ë˜ì–´ ìžˆìŠµë‹ˆë‹¤.</t>
    <t id="3227">ì„ ì²´ ìƒì‹¤, ì¡´ì—„ íšŒìˆ˜ ëŒ€ê¸° ì¤‘</t>
    <t id="3228">%1 ì‚¬ë ¹ê´€ë‹˜,\n\n%3ì—ì„œ %2 ë³´ê³ í•©ë‹ˆë‹¤. ì œ í•¨ì„ ì´ í­ë°œí–ˆìŠµë‹ˆë‹¤. ì €ëŠ” ì•„ë‹™ë‹ˆë‹¤. ì´ì œ í•¨ëŒ€ì—ì„œ ê°€ìž¥ ë¹„ì‹¼ ë¶€ìœ  í™”ë¬¼ìž…ë‹ˆë‹¤.\n\nì§€ë„ ë§ˆì»¤ ì²¨ë¶€. ì„œë‘ë¥´ì„¸ìš” - ì†¡ìž¥ ìž‘ì„± ì¤‘ì´ì—ˆìŠµë‹ˆë‹¤.\n\nì „ë¬¸ì ìœ¼ë¡œ ë¶€ìœ  ì¤‘,\n%2</t>
    <t id="3229">íŒŒì¼ëŸ¿ íšŒìˆ˜ - ì‚°ì†Œ ì¤‘ë… ì¹˜ë£Œ ì™„ë£Œ</t>
    <t id="3230">%1 ì‚¬ë ¹ê´€ë‹˜,\n\ní•¨ëŒ€ ì—…ë°ì´íŠ¸: %2ê°€ %3 (%4)ì— ì˜í•´ íšŒìˆ˜ë˜ì—ˆìœ¼ë©° ì—°ìž¥ EVA í›ˆë ¨ ë¹„ìš© ì²­êµ¬ë¥¼ ì¤‘ë‹¨í–ˆìŠµë‹ˆë‹¤.\n\në ˆì§€ìŠ¤íŠ¸ë¦¬ ìž¬ì—°ê²° ì§„í–‰ ì¤‘. ì´ì „ í•¨ì„ ì— ëŒ€í•´ì„œëŠ” ì§ˆë¬¸í•˜ì§€ ì•ŠëŠ” ê²ƒì„ ê¶Œìž¥í•©ë‹ˆë‹¤.\n\në¯¸ì•ˆí•œ ë§ˆìŒìœ¼ë¡œ,\n%2</t>
<t id="4000">í•¨ëŒ€ ì¡°ì •: %sì´(ê°€) ê²½ë¡œ %sì— í• ë‹¹ë˜ì—ˆìŠµë‹ˆë‹¤</t>
    <t id="4001">í•¨ëŒ€ ì¡°ì •: ê²½ë¡œ %sì´(ê°€) ì™„ì „ížˆ ì‚¬ìš© ì¤‘ìž…ë‹ˆë‹¤</t>
    <t id="4002">í•¨ëŒ€ ì¡°ì •: %sì´(ê°€) ê²½ë¡œ %sì„(ë¥¼) í•´ì œí–ˆìŠµë‹ˆë‹¤</t>
    <t id="5000">%sì´(ê°€) %sì˜ ì£¼ìš” ì˜ì—­ìœ¼ë¡œ í• ë‹¹ë˜ì—ˆìŠµë‹ˆë‹¤</t>
    <t id="5001">%sì´(ê°€) %sì—ì„œ ì „ë¬¸ì„± ìˆ˜ì¤€ %sì— ë„ë‹¬í–ˆìŠµë‹ˆë‹¤!</t>
    <t id="5002">ì˜ì—­ ë³´ë„ˆìŠ¤ ì ìš©: %sì—ì„œ %s%% ì´ìµ ì¦ê°€</t>
    <t id="9500">ì˜¤ë¥˜: %sì´(ê°€) ë§‰í˜€ ë„ì›€ì´ í•„ìš”í•©ë‹ˆë‹¤!</t>
    <t id="9501">ì˜¤ë¥˜: %sì— ëŒ€í•œ ë¬´ì—­ ì‹¤íŒ¨</t>
    <t id="9502">ì˜¤ë¥˜: GalaxyTrader MK3ì— %sì„(ë¥¼) ë“±ë¡í•  ìˆ˜ ì—†ìŠµë‹ˆë‹¤</t>
    <t id="80001">ìƒí’ˆ %sì´(ê°€) ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì— ì¶”ê°€ë˜ì—ˆìŠµë‹ˆë‹¤</t>
    <t id="80002">ìƒí’ˆ %sì´(ê°€) ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì—ì„œ ì œê±°ë˜ì—ˆìŠµë‹ˆë‹¤</t>
    <t id="80003">ìƒí’ˆ %sì´(ê°€) í™”ì´íŠ¸ë¦¬ìŠ¤íŠ¸ì— ì¶”ê°€ë˜ì—ˆìŠµë‹ˆë‹¤</t>
    <t id="80004">ìžë™ìœ¼ë¡œ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ë¨ (ì„±ëŠ¥ ë¶ˆëŸ‰): %s</t>
    <t id="80005">ìœ„í—˜ ìƒí’ˆ ìš°ì„ ìˆœìœ„ ì§€ì •ë¨: %s</t>
    <t id="80006">ìƒí’ˆ í•„í„°: %s í™œì„±, %s ë¬´ì—­ ì°¨ë‹¨ë¨</t>
    <t id="80007">ëª¨ë“  ìƒí’ˆ í•„í„° ì§€ì›Œì§</t>
    <t id="80008">ìƒí’ˆ í•„í„°ê°€ ê¸°ë³¸ê°’ìœ¼ë¡œ ìž¬ì„¤ì •ë¨</t>
    <t id="80009">ìƒí’ˆ í•„í„° ê´€ë¦¬</t>
    <t id="80010">ì°¨ë‹¨ëœ ìƒí’ˆ</t>
    <t id="80011">í—ˆìš©ëœ ìƒí’ˆ</t>
    <t id="80012">ìœ„í—˜ ìƒí’ˆ ì²˜ë¦¬</t>
    <t id="80013">ìµœì†Œ ìƒí’ˆ ê°€ì¹˜</t>
    <t id="80014">ìµœëŒ€ ìƒí’ˆ ê°€ì¹˜</t>
    <t id="80015">ì œí•œëœ íŒ©ì…˜</t>
    <t id="80016">ìƒí’ˆ ì¹´í…Œê³ ë¦¬ê°€ ê²Œìž„ì˜ í˜„ìž¬ ìƒíƒœì—ì„œ ì—…ë°ì´íŠ¸ë¨</t>
    <t id="80017">%s ìƒí’ˆì´ ì¹´í…Œê³ ë¦¬í™”ë¨: %s ì €ê°€ì¹˜, %s ìœ„í—˜, %s ê³ ê°€ì¹˜</t>
    <t id="80018">ë™ì  ìƒí’ˆ ì¹´í…Œê³ ë¦¬í™” í™œì„±í™”ë¨</t>
    <t id="80019">ì¹´í…Œê³ ë¦¬ %sì— ëŒ€í•œ ìžë™ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ë¹„í™œì„±í™”ë¨</t>
    <t id="80020">ë‹¤ë¥¸ ëª¨ë“œì—ì„œ ìƒˆë¡œìš´ ìƒí’ˆì´ ê°ì§€ë˜ì–´ ì¹´í…Œê³ ë¦¬í™”ë¨</t>
    <t id="9000">GalaxyTrader - ì „ì—­ ì„¤ì •</t>
    <t id="9010">XP ë° í›ˆë ¨ ì‹œìŠ¤í…œ</t>
    <t id="9012">ìžë™ í›ˆë ¨</t>
    <t id="9013">XP ë°°ìˆ˜</t>
    <t id="9015">ì§€íœ˜ê´€ ë³´ë„ˆìŠ¤ í¼ì„¼íŠ¸</t>
    <t id="9020">í•¨ëŒ€ ì¡°ì •</t>
    <t id="9021">í•¨ëŒ€ ì¡°ì • í™œì„±í™”</t>
    <t id="9023">ë¬´ì—­ ìºì‹œ í™œì„±í™”</t>
    <t id="9030">ì•Œë¦¼</t>
    <t id="9031">ì•Œë¦¼ ìˆ˜ì¤€</t>
    <t id="9040">ìžë™ ìˆ˜ë¦¬ ì‹œìŠ¤í…œ</t>
    <t id="9041">ìžë™ ìˆ˜ë¦¬ í™œì„±í™”</t>
    <t id="9042">ì„ ì²´ ìˆ˜ë¦¬ ìž„ê³„ê°’</t>
    <t id="9310">ê°¤ëŸ­ì‹œ ë§ˆì´ë„ˆ</t>
    <t id="9311">ì„¹í„° ìžì› í”„ë¡œë¸Œ ìŠ¤ìº” ëŒ€ê¸°</t>
    <t id="9312">í•¨ì„  ê·¼ì ‘ ê°€ì¤‘ì¹˜</t>
    <t id="9043">ìµœì†Œ íŒŒì¼ëŸ¿ ë ˆë²¨</t>
    <t id="9004">ë¬´ì—­ ê°€ê²© ë²”ìœ„</t>
    <t id="9005">íŒë§¤ ì œì•ˆ ìµœëŒ€ ê°€ê²©</t>
    <t id="9006">êµ¬ë§¤ ì œì•ˆ ìµœì†Œ ê°€ê²©</t>
    <t id="9007">ê²©ë¦¬: ìµœëŒ€ íŒë§¤ ê°€ê²©</t>
    <t id="9008">ê²©ë¦¬: ìµœì†Œ êµ¬ë§¤ ê°€ê²©</t>
    <t id="9009">í´ë°±: ìµœëŒ€ íŒë§¤ ê°€ê²©</t>
    <t id="9014">í´ë°±: ìµœì†Œ êµ¬ë§¤ ê°€ê²©</t>
    <t id="9016">ìˆ˜ìµ ìž„ê³„ê°’ ê¸°ì¤€</t>
    <t id="9025">ìµœì†Œ í”Œë ˆì´ì–´ ëˆ</t>
    <t id="9024">ìºì‹œ í•˜ë½ í—ˆìš©ë„</t>
    <t id="9026">ìœ íœ´ ì£¼ì°¨ í•´ì œ ì‹œê°„</t>
    <t id="9054">ì ëŒ€ì  íŒ©ì…˜ ì„¹í„° ì°¨ë‹¨</t>
    <t id="9055">ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ìœ„í˜‘ ìˆ˜ì¤€</t>
    <t id="9056">ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ìž¬ìƒì„±</t>
    <t id="9057">ìž¬ìƒì„±</t>
    <t id="9058">GT ì„ ë°•ì— í• ë‹¹</t>
    <t id="9059">ì–‘ìˆ˜ì¸</t>
    <t id="9112">íŒŒì¼ëŸ¿ì´ í•„ìš”í•œ ë ˆë²¨ì— ë„ë‹¬í•˜ë©´ ìžë™ìœ¼ë¡œ í›ˆë ¨ì†Œë¡œ ë³´ëƒ…ë‹ˆë‹¤. í›ˆë ¨ ì‹œì ì„ ìˆ˜ë™ìœ¼ë¡œ ì œì–´í•˜ë ¤ë©´ ë¹„í™œì„±í™”í•˜ì„¸ìš”.</t>
    <t id="9113">íŒŒì¼ëŸ¿ì´ ê²½í—˜ì„ ì–»ëŠ” ì†ë„ë¥¼ ì¡°ì •í•©ë‹ˆë‹¤. ê°’ì´ ë†’ì„ìˆ˜ë¡ ë” ë¹ ë¥¸ ì§„í–‰ì„ ì˜ë¯¸í•©ë‹ˆë‹¤.</t>
    <t id="9115">ë¶€í•˜ì˜ XP ì¤‘ ì§€íœ˜ê´€ íŒŒì¼ëŸ¿ì—ê²Œ ì§€ê¸‰ë˜ëŠ” ë¹„ìœ¨ìž…ë‹ˆë‹¤. ì§€íœ˜ê´€ ë³´ë„ˆìŠ¤ XPë¥¼ ë¹„í™œì„±í™”í•˜ë ¤ë©´ 0%ë¡œ ì„¤ì •í•˜ì„¸ìš”. ê¸°ë³¸ê°’: 10%.</t>
    <t id="9121">ê²½ë¡œ ìµœì í™” ë° ë¶€í•˜ ê· í˜•ì„ í¬í•¨í•œ ì§€ëŠ¥í˜• í•¨ëŒ€ ì¡°ì • ê¸°ëŠ¥ì„ í™œì„±í™”í•©ë‹ˆë‹¤.</t>
    <t id="9123">ë” ë‚˜ì€ ì¡°ì •ì„ ìœ„í•´ í•¨ëŒ€ êµ¬ì„±ì› ê°„ì— ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ ê¸°íšŒë¥¼ ê³µìœ í•  ìˆ˜ ìžˆê²Œ í•©ë‹ˆë‹¤.</t>
    <t id="9131">í‘œì‹œë˜ëŠ” ì•Œë¦¼ ìˆ˜ë¥¼ ì œì–´í•©ë‹ˆë‹¤: 0=ì¡°ìš©í•¨, 1=ì¤‘ìš”í•œ ê²ƒë§Œ, 2=ëª¨ë“  ì•Œë¦¼</t>
    <t id="9141">ì„ ì²´ê°€ ìž„ê³„ê°’ ì´í•˜ë¡œ ë–¨ì–´ì§€ë©´ ë¬´ì—­ ì™„ë£Œ í›„ ìžë™ìœ¼ë¡œ í•¨ì„ ì„ ìˆ˜ë¦¬ì†Œë¡œ ë³´ëƒ…ë‹ˆë‹¤. ê²½í—˜ ë§Žì€ íŒŒì¼ëŸ¿(ë ˆë²¨ 12+)ë§Œ í•´ë‹¹ë©ë‹ˆë‹¤. í•¨ì„ ì€ ì ì ˆí•œ ì‹œì„¤ì„ ì„ íƒí•©ë‹ˆë‹¤: S/M ìž¥ë¹„ ìŠ¤í…Œì´ì…˜, L/XL ì¡°ì„ ì†Œ.</t>
    <t id="9142">ìžë™ ìˆ˜ë¦¬ê°€ íŠ¸ë¦¬ê±°ë˜ëŠ” ì„ ì²´ ë°±ë¶„ìœ¨. ê¸°ë³¸ê°’: 95%. í•¨ì„ ì´ ì†ìƒë˜ë©´ ìžë™ìœ¼ë¡œ ê°€ìž¥ ê°€ê¹Œìš´ ìˆ˜ë¦¬ ì‹œì„¤ë¡œ í–¥í•©ë‹ˆë‹¤.</t>
    <t id="9411">í™œì„±í™”í•˜ë©´ ì±„ê´‘ì„ ì´ ì„¹í„° ë‚´ íŒ©ì…˜ ìžì› í”„ë¡œë¸Œ í‰ê°€ ì¤‘ ëŒ€ê¸°í•©ë‹ˆë‹¤(ì²« ë²ˆì§¸ ì´í›„ í”„ë¡œë¸Œë‹¹ +5ì´ˆ). GT íŒŒì¼ëŸ¿ ë ˆë²¨ì— ë”°ë¼ ëŒ€ê¸° ì‹œê°„ì´ ë ˆë²¨ 1ì˜ ì „ì²´ ì‹œê°„ì—ì„œ ë ˆë²¨ 15ì˜ 5ì´ˆê¹Œì§€ ì„ í˜•ìœ¼ë¡œ ì¤„ì–´ë“­ë‹ˆë‹¤(GT XP ëª¨ë“œë§Œ, ëŒ€ê¸° ì‹œê°„ì´ 5ì´ˆë¥¼ ì´ˆê³¼í•  ë•Œ). ë¹„í™œì„±í™” = ëŒ€ê¸° ì—†ìŒ(ë°”ë‹ë¼ ë™ìž‘).</t>
    <t id="9412">MK3/MK4 í•¨ì„ ì´ ê²€ì¦ëœ ê±°ëž˜ë¥¼ ì •ë ¬í•  ë•Œ ë” ê°€ê¹Œìš´ êµ¬ë§¤ ì •ê±°ìž¥ì„ ì„ í˜¸í•©ë‹ˆë‹¤. ì„ íƒ ì ìˆ˜ = ê±°ëž˜ ì ìˆ˜ / (1 + í•¨ì„ â†’êµ¬ë§¤ ì í”„ Ã— ê°€ì¤‘ì¹˜). ìŠ¬ë¼ì´ë” 0-100(0 = ë”, 4 = ê¸°ë³¸ 0.04). ìºì‹œ ìˆœìœ„ë‚˜ ì˜ì—­ ì‚¬ê±°ë¦¬ ì œí•œì—ëŠ” ì˜í–¥ ì—†ìŒ.</t>
    <t id="9143">ìžë™ ìˆ˜ë¦¬ ê¸°ëŠ¥ì— í•„ìš”í•œ ìµœì†Œ íŒŒì¼ëŸ¿ ë ˆë²¨. ê¸°ë³¸ê°’: 12 (ê²½í—˜ ë§Žì€ ìƒì¸). ë‚®ì€ ë ˆë²¨ì˜ íŒŒì¼ëŸ¿ì€ ìˆ˜ë™ìœ¼ë¡œ ìˆ˜ë¦¬í•´ì•¼ í•©ë‹ˆë‹¤.</t>
    <t id="9104">íŒë§¤ ì œì•ˆì— ëŒ€í•œ ìµœëŒ€ ìƒëŒ€ ê°€ê²© (í•¨ì„ ì´ ìŠ¤í…Œì´ì…˜ì—ì„œ êµ¬ë§¤). ë²”ìœ„: -1.0 ~ +1.0. ê¸°ë³¸ê°’: 0.5 (í‰ê· ë³´ë‹¤ 50% ë†’ìŒ). ê°’ì´ ë†’ì„ìˆ˜ë¡ ë” ë¹„ì‹¸ì§€ë§Œ ë” ë§Žì€ ì˜µì…˜ì„ ì˜ë¯¸í•©ë‹ˆë‹¤.</t>
    <t id="9105">êµ¬ë§¤ ì œì•ˆì— ëŒ€í•œ ìµœì†Œ ìƒëŒ€ ê°€ê²© (í•¨ì„ ì´ ìŠ¤í…Œì´ì…˜ì— íŒë§¤). ë²”ìœ„: -1.0 ~ +1.0. ê¸°ë³¸ê°’: -0.5 (í‰ê· ë³´ë‹¤ 50% ë‚®ìŒ). ê°’ì´ ë‚®ì„ìˆ˜ë¡ ë” ì €ë ´í•œ êµ¬ë§¤ìžì´ì§€ë§Œ ë” ë§Žì€ ì˜µì…˜ì„ ì˜ë¯¸í•©ë‹ˆë‹¤.</t>
    <t id="9106">ê²©ë¦¬ëœ í•¨ì„ (ë‹¨ì¼ ì„¹í„°ì— ê°‡íž˜)ì— ëŒ€í•œ ìµœëŒ€ íŒë§¤ ê°€ê²©. ë²”ìœ„: -1.0 ~ +1.0. ê¸°ë³¸ê°’: 0.5.</t>
    <t id="9107">ê²©ë¦¬ëœ í•¨ì„ (ë‹¨ì¼ ì„¹í„°ì— ê°‡íž˜)ì— ëŒ€í•œ ìµœì†Œ êµ¬ë§¤ ê°€ê²©. ë²”ìœ„: -1.0 ~ +1.0. ê¸°ë³¸ê°’: -0.5.</t>
    <t id="9108">í´ë°± ê²€ìƒ‰(ì¼ë°˜ ê²€ìƒ‰ì´ ì‹¤íŒ¨í•  ë•Œì˜ ìµœí›„ì˜ ìˆ˜ë‹¨)ì— ëŒ€í•œ ìµœëŒ€ íŒë§¤ ê°€ê²©. ë²”ìœ„: -1.0 ~ +1.0. ê¸°ë³¸ê°’: 0.5. í´ë°± ê²€ìƒ‰ì€ MaxDistance=2ì™€ ì™„í™”ëœ ì´ìµ ìž„ê³„ê°’ì„ ì‚¬ìš©í•©ë‹ˆë‹¤.</t>
    <t id="9109">í´ë°± ê²€ìƒ‰(ì¼ë°˜ ê²€ìƒ‰ì´ ì‹¤íŒ¨í•  ë•Œì˜ ìµœí›„ì˜ ìˆ˜ë‹¨)ì— ëŒ€í•œ ìµœì†Œ êµ¬ë§¤ ê°€ê²©. ë²”ìœ„: -1.0 ~ +1.0. ê¸°ë³¸ê°’: -0.5. í´ë°± ê²€ìƒ‰ì€ MaxDistance=2ì™€ ì™„í™”ëœ ì´ìµ ìž„ê³„ê°’ì„ ì‚¬ìš©í•©ë‹ˆë‹¤.</t>
    <t id="9116">ì¤‘ê°„ ê·œëª¨ ê±°ëž˜ìžì˜ ê²½ìš° ë ˆë²¨ 15ì˜ ê¸°ë³¸ ìµœì†Œ ì´ìµ(ì°¸ì¡° í™”ë¬¼ 8200). ì‹¤ì œ MinAbsoluteProfitì€ ì¡°ì¢…ì‚¬ë‹¹ ê³„ì‚°ë˜ê³  í™”ë¬¼ë³„ë¡œ ì¡°ì •ë©ë‹ˆë‹¤. \n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(scaled, 25% of base(L))\n\nëª¨ë“  ì´ìµì„ í—ˆìš©í•˜ë ¤ë©´ 0ìœ¼ë¡œ ì„¤ì •í•©ë‹ˆë‹¤(ë§Œ) ROI/ê±°ë¦¬/ê¸°íƒ€ í•„í„° ì ìš©).</t>
    <t id="9125">ì„ ë°•ì´ ê±°ëž˜ë¥¼ ê²€ìƒ‰í•˜ê¸° ì „ì— í•„ìš”í•œ ìµœì†Œ í”Œë ˆì´ì–´ ëˆ(í¬ë ˆë”§)ìž…ë‹ˆë‹¤. í”Œë ˆì´ì–´ ëˆì´ ì´ ìž„ê³„ê°’ ì•„ëž˜ë¡œ ë–¨ì–´ì§€ë©´ ëª¨ë“  ì„ ë°•ì€ ê±°ëž˜ ê²€ìƒ‰ì„ ê±´ë„ˆë›°ê³  ëŒ€ê¸°í•˜ì—¬ ê²Œìž„ ì¤‘ë‹¨ì„ ìœ ë°œí•˜ëŠ” ê°’ë¹„ì‹¼ ìºì‹œ ìŠ¤ìº”ì„ ë°©ì§€í•©ë‹ˆë‹¤. ë²”ìœ„: 1,000 - 100,000 Cr. ê¸°ë³¸ê°’: 1,000 Cr.</t>
    <t id="9124">ë¬´ì—­ì„ ê±°ë¶€í•˜ê¸° ì „ ìºì‹œëœ ê°’ì—ì„œ ìµœëŒ€ ROI ë°±ë¶„ìœ¨ í•˜ë½. ì˜ˆ: 15% í—ˆìš©ë„ë¡œ 20% ìºì‹œëœ ROIëŠ” ìµœëŒ€ 17% ROI(14% í•˜ë½)ê¹Œì§€ ìˆ˜ìš©í•©ë‹ˆë‹¤.</t>
    <t id="9126">í•­êµ¬ë¥¼ ë¹„ìš°ê¸° ìœ„í•´ docked ìƒíƒœì—ì„œ ì¶œí•­í•˜ê¸°ê¹Œì§€ì˜ ì‹œê°„(ë¶„, 0-60). 0 = ìƒˆ ìž‘ì—…ì„ ì°¾ì„ ë•Œê¹Œì§€ docked ìƒíƒœ ìœ ì§€. ê¸°ë³¸ê°’: 1ë¶„.</t>
    <t id="9154">ì ëŒ€ì  íŒ©ì…˜(ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì˜ ê´€ê³„ ì²´í¬ë°•ìŠ¤)ì— ì†í•œ ëª¨ë“  ì„¹í„°ë¥¼ ìžë™ìœ¼ë¡œ ë¸”ëž™ë¦¬ìŠ¤íŠ¸í•©ë‹ˆë‹¤</t>
    <t id="9155">ì„¹í„°ë¥¼ ë¸”ëž™ë¦¬ìŠ¤íŠ¸í•˜ëŠ” ë° í•„ìš”í•œ ìµœì†Œ ìœ„í˜‘ ìˆ˜ì¤€ (1-5):\n2=ì¤‘ê°„ (ë‹¨ì¼ ê³µê²©)\n3=ì¤‘ìƒ (ì ëŒ€ì  íŒ©ì…˜)\n4=ë†’ìŒ (ìºí”¼í„¸ í•¨ì„ /ë¯¸ì‚¬ì¼)\n5=ë§¤ìš° ë†’ìŒ (ì œë…¼/ì¹´ì•…)</t>
    <t id="9156">ìœ„í˜‘ íšŒí”¼ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ë¥¼ ìˆ˜ë™ìœ¼ë¡œ ìž¬ìƒì„±í•©ë‹ˆë‹¤ (ì‚­ì œëœ ê²½ìš° ìœ ìš©í•¨)</t>
    <t id="9157">ëª¨ë“  GT í•¨ëŒ€ ì‚¬ë ¹ê´€ ì„ ë°•ì— í˜„ìž¬ ë™ì  ë¸”ëž™ë¦¬ìŠ¤íŠ¸ë¥¼ ìˆ˜ë™ìœ¼ë¡œ í• ë‹¹í•©ë‹ˆë‹¤. ë¶€í•˜ë“¤ì€ ì§€íœ˜ê´€ìœ¼ë¡œë¶€í„° ë¬¼ë ¤ë°›ìŠµë‹ˆë‹¤.</t>
    <t id="6001">ê²¬ìŠµìƒ</t>
    <t id="6002">ì „ë‹¬ìž</t>
    <t id="6003">ê³µê¸‰ìž</t>
    <t id="6004">ìƒì¸</t>
    <t id="6005">ë¬´ì—­ìƒ</t>
    <t id="6006">ìž¥ê±°ë¦¬ ë¬´ì—­ìƒ</t>
    <t id="6101">ê· í˜•</t>
    <t id="6102">ë°©ì–´</t>
    <t id="6103">ë¬´ì—­ ì¤‘ì‹¬</t>
    <t id="6104">ì¤‘ë¬´ìž¥ ë°©ì–´</t>
    <t id="6105">í„°ë › ì§€ì›</t>
    <t id="9050">ìœ„í˜‘ íšŒí”¼ ì‹œìŠ¤í…œ</t>
    <t id="9051">ìœ„í˜‘ íšŒí”¼ í™œì„±í™”:</t>
    <t id="9052">ì ëŒ€ì  ê´€ê³„ ìž„ê³„ê°’:</t>
    <t id="9053">ë™ì  ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ì‚¬ìš©:</t>
    <t id="9151">ë ˆë²¨ 6+ ìƒì¸ì€ ì ëŒ€ì  í•¨ì„ ì„ ê°ì§€í•˜ê³  ìœ„í—˜í•œ ê²½ë¡œë¥¼ í”¼í•©ë‹ˆë‹¤. ë¹„í™œì„±í™”í•˜ë©´ ëª¨ë“  ìŠ¤ìº”ì´ ì¤‘ì§€ë©ë‹ˆë‹¤ (ì„±ëŠ¥ í–¥ìƒ). ëª…ë ¹ ë™ìž‘ì—ì„œ í•¨ì„ ë‹¹ ìœ„í—˜ í—ˆìš©ë„ (0-10 ìŠ¤ì¼€ì¼).</t>
    <t id="9152">ì´ ê°’ ì´í•˜ì˜ ê´€ê³„ë¥¼ ê°€ì§„ íŒ©ì…˜ë§Œ ìœ„í˜‘ìœ¼ë¡œ í‘œì‹œí•©ë‹ˆë‹¤. ê¸°ë³¸ê°’: -20%</t>
    <t id="9153">ìœ„í—˜í•œ ì„¹í„°(ìœ„í˜‘ ìˆ˜ì¤€ 3+)ë¥¼ ìžë™ìœ¼ë¡œ ë¸”ëž™ë¦¬ìŠ¤íŠ¸í•˜ì—¬ í•¨ì„ ì´ ìœ„í˜‘ì„ ìš°íšŒí•˜ë„ë¡ ê°•ì œí•©ë‹ˆë‹¤. ëŒ€ì²´ ê²½ë¡œì— ëŒ€í•´ ë°”ë‹ë¼ ê²½ë¡œ ì°¾ê¸°ë¥¼ ì‚¬ìš©í•©ë‹ˆë‹¤.</t>
    <t id="9060">ìžë™ ë°©ì–´ ìž¥ë¹„ ë³´ê¸‰ (ë ˆë²¨ 15)</t>
    <t id="9061">ìžë™ ë³´ê¸‰ í™œì„±í™”:</t>
    <t id="9062">ëŒ€ì‘ ìˆ˜ë‹¨ ë³´ê¸‰:</t>
    <t id="9063">ë°©ì–´ ë“œë¡  ë³´ê¸‰:</t>
    <t id="9064">ë¬´ì—­ ë“œë¡  ë³´ê¸‰:</t>
    <t id="9065">ë ˆì´ì € í„°ë › ë³´ê¸‰:</t>
    <t id="9066">ìˆ˜ë¦¬ ë“œë¡  ë³´ê¸‰:</t>
    <t id="9067">ëŒ€ì‘ ìˆ˜ë‹¨ ìž„ê³„ê°’:</t>
    <t id="9068">í†µí•© ìš©ëŸ‰ ìž„ê³„ê°’:</t>
    <t id="9069">ìž¥ë¹„ ê· í˜• í”„ë¡œí•„:</t>
    <t id="9161">ë§ˆìŠ¤í„° ìƒì¸(ë ˆë²¨ 15)ì€ ë¬´ì—­ í›„ ìžë™ìœ¼ë¡œ ë°©ì–´ ìž¥ë¹„ë¥¼ ë³´ê¸‰í•©ë‹ˆë‹¤. ë¶€í•˜ì—ê²ŒëŠ” ì§€íœ˜ê´€ ë ˆë²¨ì´ ì ìš©ë©ë‹ˆë‹¤.</t>
    <t id="9162">ëª¨ë“  í•¨ì„  (S/M/L/XL). ë³„ë„ ìš©ëŸ‰. ë¯¸ì‚¬ì¼ ë°©ì–´ì— ì¤‘ìš”í•©ë‹ˆë‹¤.</t>
    <t id="9163">L/XL í•¨ì„ ë§Œ. ë‹¤ë¥¸ ë°°ì¹˜ ê°€ëŠ¥í•œ ìž¥ë¹„ì™€ í†µí•© ìš©ëŸ‰ì„ ê³µìœ í•©ë‹ˆë‹¤.</t>
    <t id="9164">L/XL í•¨ì„ ë§Œ. ë¬´ì—­ ìž‘ì—…ì— í•„ìˆ˜ì ìž…ë‹ˆë‹¤. í†µí•© ìš©ëŸ‰ì„ ê³µìœ í•©ë‹ˆë‹¤.</t>
    <t id="9165">ëª¨ë“  í•¨ì„ . L/XL í•¨ì„ ì€ í†µí•© ìš©ëŸ‰ì„ ê³µìœ í•˜ê³ , S/Mì€ í™”ë¬¼ì„ ì‚¬ìš©í•©ë‹ˆë‹¤.</t>
    <t id="9166">L/XL í•¨ì„ ë§Œ. ìžë™ ìˆ˜ë¦¬ ì‹œìŠ¤í…œê³¼ í•¨ê»˜ ìž‘ë™í•©ë‹ˆë‹¤. í†µí•© ìš©ëŸ‰ì„ ê³µìœ í•©ë‹ˆë‹¤.</t>
    <t id="9167">ëŒ€ì‘ ìˆ˜ë‹¨ì´ ì´ ë°±ë¶„ìœ¨ ì´í•˜ì¼ ë•Œ ë³´ê¸‰ (ëª¨ë“  í•¨ì„ , ë³„ë„ ìš©ëŸ‰).</t>
    <t id="9168">ì´ ë°°ì¹˜ ê°€ëŠ¥í•œ ìž¥ë¹„ê°€ ì´ ë°±ë¶„ìœ¨ ì´í•˜ì¼ ë•Œ ë³´ê¸‰ (L/XL í•¨ì„ : ë“œë¡  + í„°ë ›ì´ í•˜ë‚˜ì˜ ìš©ëŸ‰ ê³µìœ ).</t>
    <t id="9169">í†µí•© ìš©ëŸ‰ ë¶„ë°° (L/XL í•¨ì„ ): ë¬´ì—­ ì¤‘ì‹¬ (20/50/20/10), ê· í˜• (35/35/20/10), ë°©ì–´ (50/20/20/10), ì¤‘ë¬´ìž¥ ë°©ì–´ (40/30/20/10), í„°ë › ì§€ì› (30/30/30/10). ë¹„ìœ¨: ë°©ì–´/ë¬´ì—­/í„°ë ›/ìˆ˜ë¦¬. ì˜µì…˜ì„ ìˆœí™˜í•˜ë ¤ë©´ í´ë¦­í•˜ì„¸ìš”.</t>
    <t id="9090">í•¨ì„  ìˆ˜ì •</t>
    <t id="9091">í•¨ì„  ìˆ˜ì • í™œì„±í™”</t>
    <t id="9191">íŒŒì¼ëŸ¿ ë ˆë²¨ì— ë”°ë¼ í•¨ì„  ë° ì—”ì§„ ìˆ˜ì •ì„ ìžë™ìœ¼ë¡œ ì„¤ì¹˜í•©ë‹ˆë‹¤. ë ˆë²¨ 9+ = ë ˆë²¨ 1 ëª¨ë“œ, ë ˆë²¨ 12+ = ë ˆë²¨ 2 ëª¨ë“œ, ë ˆë²¨ 15+ = ë ˆë²¨ 3 ëª¨ë“œ. ì£¼ë¬¸ì´ ì·¨ì†Œë˜ë©´ GTê°€ ì„¤ì¹˜í•œ ëª¨ë“œë§Œ ì œê±°ë©ë‹ˆë‹¤.</t>
    <t id="9070">í•¨ì„  ëª…ëª… êµ¬ì„±</t>
    <t id="9071">XP í‘œì‹œ:</t>
    <t id="9072">ê³„ê¸‰ í‘œì‹œ:</t>
    <t id="9073">ë ˆë²¨ í‘œì‹œ:</t>
    <t id="9074">ìƒíƒœ í‘œì‹œ:</t>
    <t id="9075">í•¨ì„  ì´ë¦„ ë³€ê²½ í™œì„±í™”:</t>
    <t id="9076">ì ‘ë‘ì‚¬</t>
    <t id="9077">ì ‘ë¯¸ì‚¬</t>
    <t id="9078">ê¸°ë³¸ ì´ë¦„ ì†ŒìŠ¤:</t>
    <t id="9079">ëª¨ë¸ ì´ë¦„</t>
    <t id="9080">íƒ€ìž… ì´ë¦„</t>
    <t id="9081">ê¸°ë³¸ ì´ë¦„</t>
    <t id="9083">ê¸°ë³¸ ì´ë¦„</t>
    <t id="9084">í™ˆ ì„¹í„° í‘œì‹œ:</t>
    <t id="9085">ëª…ëª… ëª¨ë“œ:</t>
    <t id="9086">ë ˆê±°ì‹œ</t>
    <t id="9087">íŒ¨í„´</t>
    <t id="9088">ì´ë¦„ íŒ¨í„´:</t>
    <t id="9089">í”Œë ˆì´ìŠ¤í™€ë”: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. ê°œë³„: {RS} {CB} {BL} ë“±. ì•„ëž˜ ìƒíƒœ ì•½ì–´ ì‚¬ìš©. ë¹ˆ í† í°ì€ ìƒëžµ, ê³µë°± ì¶•ì†Œ. ìµœëŒ€ 128ìž.</t>
    <t id="9183">ì„¤ì •ëœ í™ˆ ì„¹í„°ë¥¼ í•¨ì„  ì´ë¦„ì— í‘œì‹œ(ì ‘ë‘ì‚¬ ë˜ëŠ” ì ‘ë¯¸ì‚¬).</t>
    <t id="9184">ë ˆê±°ì‹œ ë ˆì´ì•„ì›ƒ ëŒ€ì‹  {TOKEN} í”Œë ˆì´ìŠ¤í™€ë”ë¡œ ì´ë¦„ í˜•ì‹ ì§€ì •. GalaxyTrader XP í•„ìš”(ë°”ë‹ë¼ XP ëª¨ë“œ ë¶ˆê°€).</t>
    <t id="9092">íŒ¨í„´ í”Œë ˆì´ìŠ¤í™€ë”</t>
    <t id="9093">í•¨ì„ : {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT XP (ëª¨ë“œ): {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">ë°”ë‹ë¼: {MGMT} {PILOTSKILL}</t>
    <t id="9096">ê±°ì : {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">ìŠ¹ë¬´ì›: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">ì„¹í„°: {SECTOR} | í†µê³„: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">ìƒíƒœ í† í°:</t>
    <t id="9100">{OPSTATE}: í™œì„± ìš´ìš© í”Œëž˜ê·¸ ì „ì²´ ê²°í•© (ì˜ˆ: CB RS, MT)</t>
    <t id="9101">{STATUS}: ì°¨ë‹¨, í›ˆë ¨, í´ë°± ë˜ëŠ” ê³ ë¦½</t>
    <t id="9102">{CB}: ì‚¬ìš©ìž BLë§Œ, {OPSTATE}ì— í¬í•¨, í•¨ê»˜ ì“°ì§€ ë§ ê²ƒ</t>
    <t id="9082">í•¨ì„  ë“±ê¸‰ í‘œì‹œ:</t>
    <t id="9171">í•¨ì„  ì´ë¦„ì— XP ê°’ í‘œì‹œ</t>
    <t id="9175">íŒŒì¼ëŸ¿ ì •ë³´ê°€ ìžˆëŠ” ìžë™ í•¨ì„  ì´ë¦„ ë³€ê²½ í™œì„±í™” ë˜ëŠ” ë¹„í™œì„±í™”</t>
    <t id="9172">í•¨ì„  ì´ë¦„ì— ê³„ê¸‰ ì¹­í˜¸ í‘œì‹œ</t>
    <t id="9173">í•¨ì„  ì´ë¦„ì— ë ˆë²¨ ë²ˆí˜¸ í‘œì‹œ</t>
    <t id="9174">í•¨ì„  ì´ë¦„ì— ë¬´ì—­ ìƒíƒœ í‘œì‹œ</t>
    <t id="9178">í•¨ì„  ê¸°ë³¸ ì´ë¦„ì˜ ì†ŒìŠ¤ ì„ íƒ: ëª¨ë¸ ì´ë¦„ (ë³€í˜• í¬í•¨), íƒ€ìž… ì´ë¦„ (ì¼ë°˜), ë˜ëŠ” ê¸°ë³¸ ì´ë¦„ (ë³€í˜• ì—†ìŒ)</t>
    <t id="9182">í•¨ì„  ì´ë¦„ì— í•¨ì„  ë“±ê¸‰ (S, M, L, XL) í‘œì‹œ</t>
    <t id="9200">ë””ë²„ê·¸ ì„¤ì •</t>
    <t id="9201">ë””ë²„ê·¸ ê¸°ë¡ í™œì„±í™”:</t>
    <t id="9202">ëª¨ë“  debug_text ì¶œë ¥ì˜ ë§ˆìŠ¤í„° ìŠ¤ìœ„ì¹˜. ë¹„í™œì„±í™”ë˜ë©´ ëª¨ë“  ë””ë²„ê·¸ ê¸°ë¡ì´ ì–µì œë©ë‹ˆë‹¤. í™œì„±í™”ë˜ë©´ ë””ë²„ê·¸ ë©”ì‹œì§€ê°€ ê°œë³„ debug_text í™•ë¥  ê°’ì— ë”°ë¼ DebugLogì— ë‚˜íƒ€ë‚©ë‹ˆë‹¤.</t>
    <t id="9220">ìœ ì§€ë³´ìˆ˜ ë° ì§„ë‹¨</t>
    <t id="9221">ì´ìµ í†µê³„ ìž¬ì„¤ì •:</t>
    <t id="9222">ìž¬ì„¤ì •</t>
    <t id="9223">ëª¨ë“  ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ì„¹í„° ì§€ìš°ê¸°:</t>
    <t id="9224">ì§€ìš°ê¸°</t>
    <t id="9225">ëª¨ë“  ì„¤ì •ì„ ê¸°ë³¸ê°’ìœ¼ë¡œ ìž¬ì„¤ì •:</t>
    <t id="9226">ëª¨ë‘ ìž¬ì„¤ì •</t>
    <t id="9323">ìœ„í˜‘ ì •ë³´ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ì—ì„œ ëª¨ë“  ì„¹í„°ë¥¼ ì œê±°í•©ë‹ˆë‹¤. ì´ê²ƒì€ ì¦‰ì‹œ ëª¨ë“  ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ì„¹í„°ë¥¼ ì§€ìš°ê³  í•¨ì„ ì´ ì´ì „ì— ì°¨ë‹¨ëœ ì˜ì—­ìœ¼ë¡œ ì´ë™í•  ìˆ˜ ìžˆê²Œ í•©ë‹ˆë‹¤. ìœ„í˜‘ íšŒí”¼ ì‹œìŠ¤í…œì„ ìž¬ì„¤ì •í•˜ê±°ë‚˜ ì„¹í„°ê°€ ìž˜ëª» ë¸”ëž™ë¦¬ìŠ¤íŠ¸ëœ ê²½ìš° ì´ê²ƒì„ ì‚¬ìš©í•˜ì„¸ìš”.</t>
    <t id="9321">ëª¨ë“  íŒŒì¼ëŸ¿ê³¼ í•¨ì„ ì— ëŒ€í•œ ëª¨ë“  ì´ìµ í†µê³„ë¥¼ 0ìœ¼ë¡œ ìž¬ì„¤ì •í•©ë‹ˆë‹¤. v0.6.0ìœ¼ë¡œ ì—…ê·¸ë ˆì´ë“œí•œ í›„ ìˆ˜ìµ ê¸°ë°˜ì˜ ë¶€í’€ë ¤ì§„ í†µê³„ë¥¼ ì§€ìš°ëŠ” ë° ì‚¬ìš©í•˜ì„¸ìš”. ìˆ˜ì • ì‚¬í•­ì€ ì´ì œ ì‹¤ì œ ì´ìµ(ìˆ˜ìµ - êµ¬ë§¤ ë¹„ìš©)ì„ ì¶”ì í•©ë‹ˆë‹¤. ë¬´ì—­ íšŸìˆ˜ì™€ XPëŠ” ë³´ì¡´ë©ë‹ˆë‹¤.</t>
    <t id="9325">ëª¨ë“  ì „ì—­ ì„¤ì •ì„ ê¸°ë³¸ê°’ìœ¼ë¡œ ìž¬ì„¤ì •í•©ë‹ˆë‹¤. ì—¬ê¸°ì—ëŠ” XP ì„¤ì •, í•¨ëŒ€ ì¡°ì •, ì•Œë¦¼, ëª¨ë°”ì¼ ì¸í…”ë¦¬ì „ìŠ¤, ìœ„í˜‘ íšŒí”¼, í•¨ì„  ëª…ëª…, ìžë™ ìˆ˜ë¦¬, ìˆ˜ì •, ì„±ëŠ¥ ë° ìˆ«ìž í˜•ì‹ ì„¤ì •ì´ í¬í•¨ë©ë‹ˆë‹¤. ë””ë²„ê·¸ ë¡œê¹… ì„¤ì •ì€ ìž¬ì„¤ì • ìž‘ì—…ì˜ ë¡œê¹…ì„ í—ˆìš©í•˜ê¸° ìœ„í•´ ë³´ì¡´ë©ë‹ˆë‹¤.</t>
    <t id="9227">ëª¨ë“  í™ˆ ì„¹í„°ì— ëŒ€í•œ ë¬´ì—­ ìºì‹œ ì§€ìš°ê¸°:</t>
    <t id="9228">ìºì‹œ ì§€ìš°ê¸°</t>
    <t id="9327">ëª¨ë“  í™ˆ ì„¹í„°ì— ëŒ€í•œ ë¬´ì—­ ìºì‹œë¥¼ ì§€ì›ë‹ˆë‹¤. ì´ê²ƒì€ ëª¨ë“  í•¨ì„ ì´ ë‹¤ìŒ ë¬´ì—­ ê²€ìƒ‰ì—ì„œ ìƒˆë¡œìš´ ë¼ì´ë¸Œ ê²€ìƒ‰ì„ ìˆ˜í–‰í•˜ë„ë¡ ê°•ì œí•©ë‹ˆë‹¤. ìºì‹œê°€ ì˜¤ëž˜ë˜ì—ˆê±°ë‚˜ ì†ìƒëœ ê²ƒìœ¼ë¡œ ë³´ì´ê±°ë‚˜ ì™„ì „í•œ ìºì‹œ ìƒˆë¡œê³ ì¹¨ì„ ê°•ì œí•˜ë ¤ëŠ” ê²½ìš° ì´ê²ƒì„ ì‚¬ìš©í•˜ì„¸ìš”.</t>
    <t id="9229">ëª¨ë“  ê²€ìƒ‰ ìž ê¸ˆ í•´ì œ</t>
    <t id="9329">ì§„í–‰ ì¤‘ì¸ ëª¨ë“  ë¬´ì—­ ê²€ìƒ‰ ìž ê¸ˆì„ í•´ì œí•˜ê³  ê´€ë ¨ ìž„ì‹œ ìƒíƒœë¥¼ ì§€ì›ë‹ˆë‹¤. ì˜¤ëž˜ëœ ì €ìž¥ íŒŒì¼ì˜ ì˜¤ëž˜ëœ ìž ê¸ˆìœ¼ë¡œ ì¸í•´ í•¨ì„ ì´ "ë¬´ì—­ ê²€ìƒ‰ ì¤‘"ì— ë©ˆì¶˜ ê²½ìš° ì´ê²ƒì„ ì‚¬ìš©í•˜ì„¸ìš”. í•©ë²•ì ì¸ ê²€ìƒ‰ì„ ì¤‘ë‹¨í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤.</t>
    <t id="9290">ë¬´ì—­ í—ˆë¸Œ ìƒíƒœ ë¤í”„:</t>
    <t id="9291">ë¤í”„</t>
    <t id="9390">ì¤‘ì•™ ë¬´ì—­ í—ˆë¸Œì˜ ì¼íšŒì„± ìŠ¤ëƒ…ìƒ·ì„ ë¡œê·¸ì™€ ì•Œë¦¼ìœ¼ë¡œ í‘œì‹œí•©ë‹ˆë‹¤ (ìŠ¤ì¼€ì¤„ëŸ¬ ëŒ€ê¸°ì—´ + ë§ˆì§€ë§‰ ìš”ì²­ ì„ ë°• ìƒíƒœ).</t>
    <t id="9292">ë¬´ì—­ ìºì‹œ ë¤í”„ (ì „ì²´):</t>
    <t id="9293">ìºì‹œ ë¤í”„</t>
    <t id="9392">ì „ì²´ ìºì‹œ ë¤í”„ (ë§¤ìš° í´ ìˆ˜ ìžˆìŒ). ëª¨ë“  ìºì‹œ í•­ëª©ì„ ì²­í¬ ë‹¨ìœ„ë¡œ DebugLogì— ê¸°ë¡í•©ë‹ˆë‹¤. ë‹¤ì‹œ í´ë¦­í•˜ë©´ ì·¨ì†Œë©ë‹ˆë‹¤.</t>
    <t id="9294">í•¨ëŒ€ ì˜ˆì•½ ì§€ìš°ê¸°:</t>
    <t id="9295">ë¶„ëª…í•œ</t>
    <t id="9394">ëª¨ë“  í™œì„± í•¨ëŒ€ ë¬´ì—­ ì˜ˆì•½ì„ ì§€ì›ë‹ˆë‹¤. ì„ ë°•ì´ ì˜ˆì•½ëœ ê±°ëž˜ê°€ ë§Œë£Œë  ë•Œê¹Œì§€ ê¸°ë‹¤ë¦¬ì§€ ëª»í•˜ëŠ” ê²½ìš° ë˜ëŠ” ì´ì „ ì €ìž¥ íŒŒì¼ì„ ë¡œë“œí•œ í›„ ì˜ˆì•½ í…Œì´ë¸”ì´ ì˜¤ëž˜ ëœ ê²½ìš° ì´ ê¸°ëŠ¥ì„ ì‚¬ìš©í•˜ì„¸ìš”.</t>
    <t id="9230">ì„±ëŠ¥</t>
    <t id="9231">ë°°ì¹˜ ì²˜ë¦¬ ì§€ì—°:</t>
    <t id="9232">ê²€ì¦ ì§€ì—°:</t>
    <t id="9233">ìµœëŒ€ ë™ì‹œ ê²€ìƒ‰:</t>
    <t id="9234">ë°˜í™˜í•  ìµœëŒ€ ë¬´ì—­:</t>
    <t id="9235">ìƒí’ˆë‹¹ ìµœëŒ€ ì œì•ˆ:</t>
    <t id="9236">ìƒí’ˆë‹¹ ìµœëŒ€ ë¬´ì—­:</t>
    <t id="9237">ë§¤ì¹­ì„ ìœ„í•œ ìƒí’ˆë‹¹ ìµœëŒ€ ì œì•ˆ:</t>
    <t id="9238">ì¡°ê¸° ì¢…ë£Œ ìž„ê³„ê°’:</t>
    <t id="9241">ë¼ì´ë¸Œ ì œì•ˆ ìŠ¬ë¼ì´ìŠ¤ ê°„ê²©:</t>
    <t id="9266">ê²€ìƒ‰ ìž ê¸ˆ TTL:</t>
    <t id="9263">ë°°ì¹˜ ì²­í¬ í¬ê¸°:</t>
    <t id="9239">ìˆ«ìž í˜•ì‹</t>
    <t id="9240">í˜•ì‹ ìŠ¤íƒ€ì¼:</t>
    <t id="9242">M ì ‘ë¯¸ì‚¬ ì‚¬ìš©</t>
    <t id="9243">M ì ‘ë¯¸ì‚¬ ìž„ê³„ê°’:</t>
    <t id="9244">ë…ì¼ì–´ (123.456,78)</t>
    <t id="9245">ì˜ì–´ (123,456.78)</t>
    <t id="9510">ë ˆë²¨ì—… íŒì—… ì•Œë¦¼:</t>
    <t id="9511">í›ˆë ¨ í•„ìš” ì•Œë¦¼:</t>
    <t id="9512">í›ˆë ¨ ì™„ë£Œ ì•Œë¦¼:</t>
    <t id="9513">ìˆ˜ìµ ë³´ê³ ì„œ:</t>
    <t id="9514">ì‹œìž¥ ì•Œë¦¼:</t>
    <t id="9515">í•¨ëŒ€ ì—…ë°ì´íŠ¸:</t>
    <t id="9516">ë°”ë‹ë¼ XPë§Œ ì‚¬ìš©í•˜ì„¸ìš”</t>
    <t id="9610">í”Œë ˆì´ì–´ UIì—ì„œ ê±°ëž˜ìž ë ˆë²¨ì—… íŒì—… ì•Œë¦¼ì„ í™œì„±í™”í•˜ê±°ë‚˜ ë¹„í™œì„±í™”í•©ë‹ˆë‹¤.</t>
    <t id="9611">íŒŒì¼ëŸ¿ì´ ë‹¤ìŒ ë ˆë²¨ë¡œ ì§„í–‰í•˜ê¸° ìœ„í•´ í›ˆë ¨ì´ í•„ìš”í•  ë•Œ ì•Œë¦¼í•©ë‹ˆë‹¤.</t>
    <t id="9612">íŒŒì¼ëŸ¿ì´ í›ˆë ¨ì„ ì™„ë£Œí•˜ê³  ê³„ê¸‰ì´ ì˜¬ëžì„ ë•Œ ì•Œë¦¼í•©ë‹ˆë‹¤.</t>
    <t id="9613">ì •ê¸° ìˆ˜ìµ ìš”ì•½(ê°„ë‹¨ ë° ìƒì„¸ ë³´ê³ ì„œ).</t>
    <t id="9614">ì˜ˆì™¸ì ì¸ ì‹œìž¥ ê¸°íšŒ ë° ê³ ê°€ì¹˜ ê±°ëž˜ ì•Œë¦¼.</t>
    <t id="9615">í•¨ëŒ€ ì¡°ì • ë©”ì‹œì§€ ë° ìƒíƒœ ì—…ë°ì´íŠ¸.</t>
    <t id="9616">Pilot.skill.pilotingì„ ì‚¬ìš©í•˜ê³  GT XP ì§„í–‰/í•œë„ë¥¼ ë¹„í™œì„±í™”í•˜ì„¸ìš”.</t>
    <t id="9246">ê°„ë‹¨ ë³´ê³ ì„œ ë¹ˆë„:</t>
    <t id="9247">ìƒì„¸ ë³´ê³ ì„œ ë¹ˆë„:</t>
    <t id="9248">ìµœëŒ€ ë™ì‹œ ìºì‹œ ê²€ìƒ‰:</t>
    <t id="9249">ìµœëŒ€ ë™ì‹œ ë¼ì´ë¸Œ ê²€ìƒ‰:</t>
    <t id="9340">ìˆ«ìž í˜•ì‹ ì„ íƒ: ë…ì¼ì–´ëŠ” ì²œ ë‹¨ìœ„ì— '.'ë¥¼ ì‚¬ìš©í•˜ê³  ì†Œìˆ˜ì ì— ','ë¥¼ ì‚¬ìš©í•©ë‹ˆë‹¤ (123.456,78), ì˜ì–´ëŠ” ì²œ ë‹¨ìœ„ì— ','ë¥¼ ì‚¬ìš©í•˜ê³  ì†Œìˆ˜ì ì— '.'ë¥¼ ì‚¬ìš©í•©ë‹ˆë‹¤ (123,456.78)</t>
    <t id="9342">ìž„ê³„ê°’ë³´ë‹¤ í° ìˆ«ìžì— M ì ‘ë¯¸ì‚¬ í™œì„±í™” (ì˜ˆ: 1,000,000 ëŒ€ì‹  1.0 M)</t>
    <t id="9343">M ì ‘ë¯¸ì‚¬ ìž„ê³„ê°’. ì´ ê°’ë³´ë‹¤ í° ìˆ«ìžëŠ” M ì ‘ë¯¸ì‚¬ë¡œ í‘œì‹œë©ë‹ˆë‹¤ (ê¸°ë³¸ê°’: 999,999)</t>
    <t id="9346">ê°„ë‹¨ ë³´ê³ ì„œ ë¹ˆë„ (íŒì—… ì•Œë¦¼): 0-30ë¶„ (0 = ë¹„í™œì„±í™” - ê°„ë‹¨ ë³´ê³ ì„œê°€ ë¹„í™œì„±í™”ë¨, ê¸°ë³¸ê°’: 1ë¶„)</t>
    <t id="9347">ìƒì„¸ ë³´ê³ ì„œ ë¹ˆë„ (í•­í•´ ì¼ì§€ í•­ëª©): 0-60ë¶„ (0 = ë¹„í™œì„±í™” - ìƒì„¸ ë³´ê³ ì„œê°€ ë¹„í™œì„±í™”ë¨, ê¸°ë³¸ê°’: 30ë¶„)</t>
    <t id="9398">GT í¬ë ˆë”§ ëŒ€ì²´ ì‚¬ìš©</t>
    <t id="9399">ë°”ë‹ë¼ "ê±°ëž˜ë¡œ ì¸í•œ CR" ì¤„ì„ ë™ì¼í•œ UI ìŠ¬ë¡¯ì˜ GT ì˜ˆìƒ ê°’ìœ¼ë¡œ ë°”ê¾¸ê±°ë‚˜ ëŠ˜ë¦½ë‹ˆë‹¤.</t>
    <t id="9331">ë¬´ì—­ ê²€ìƒ‰ ì²˜ë¦¬ ì¤‘ ë°°ì¹˜ ê°„ ì§€ì—° (1-100ms). ê°’ì´ ë†’ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ë¬´ì—­ ê²€ìƒ‰ì„ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ê¸°ë³¸ê°’: 50ms. ë°°ì¹˜ í”„ë¡œì„¸ì„œ ë° ë¬´ì—­ ëª©ë¡ í•„í„°ë§ì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤.</t>
    <t id="9332">AI ìŠ¤í¬ë¦½íŠ¸ì—ì„œ ë¬´ì—­ ê²€ì¦ ê°„ ì§€ì—° (1-100ms). ê°’ì´ ë†’ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ë¬´ì—­ ê²€ì¦ì„ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ê¸°ë³¸ê°’: 50ms. MD ì‹œìŠ¤í…œì—ì„œ ë¬´ì—­ ëª©ë¡ì„ ê²€ì¦í•  ë•Œ ì‚¬ìš©ë©ë‹ˆë‹¤.</t>
    <t id="9333">ë™ì‹œì— ì‹¤í–‰í•  ìˆ˜ ìžˆëŠ” ìµœëŒ€ ë¬´ì—­ ê²€ìƒ‰ ìˆ˜ (1-10). ê°’ì´ ë‚®ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ëŒ€ê¸°ì—´ ëŒ€ê¸° ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë†’ì„ìˆ˜ë¡ ê²€ìƒ‰ì„ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ì„±ëŠ¥ ìŠ¤íŒŒì´í¬ë¥¼ ì¼ìœ¼í‚¬ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9334">ìºì‹œ ê²€ìƒ‰ì—ì„œ ë°˜í™˜í•  ìµœëŒ€ ë¬´ì—­ ìˆ˜ (50-1000). ê°’ì´ ë†’ì„ìˆ˜ë¡ ë” ë§Žì€ ë¬´ì—­ ì˜µì…˜ì„ ì œê³µí•˜ì§€ë§Œ ì²˜ë¦¬ ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë‚®ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ì„ ë†“ì¹  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 200.</t>
    <t id="9335">ë¼ì´ë¸Œ ê²€ìƒ‰ì—ì„œ ì²˜ë¦¬í•  ìƒí’ˆë‹¹ ìµœëŒ€ ì œì•ˆ ìˆ˜ (5-100). ê°’ì´ ë†’ì„ìˆ˜ë¡ ë” ë§Žì€ ì œì•ˆì„ ê³ ë ¤í•˜ì§€ë§Œ ì²˜ë¦¬ ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë‚®ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ì„ ë†“ì¹  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 20.</t>
    <t id="9336">ë°°ì¹˜ ì²˜ë¦¬ ì¤‘ ìƒí’ˆë‹¹ ìµœëŒ€ ë¬´ì—­ ìˆ˜ (5-100). ê°’ì´ ë†’ì„ìˆ˜ë¡ ìƒí’ˆë‹¹ ë” ë§Žì€ ë¬´ì—­ì„ í—ˆìš©í•˜ì§€ë§Œ ì²˜ë¦¬ ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë‚®ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ì„ ë†“ì¹  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 20.</t>
    <t id="9337">ë°°ì¹˜ í”„ë¡œì„¸ì„œì—ì„œ ë§¤ì¹­ì„ ìœ„í•œ ìƒí’ˆë‹¹ ìµœëŒ€ ì œì•ˆ ìˆ˜ (5-100). ê°’ì´ ë†’ì„ìˆ˜ë¡ ë” ë§Žì€ ì œì•ˆì„ ê³ ë ¤í•˜ì§€ë§Œ ì²˜ë¦¬ ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë‚®ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ì„ ë†“ì¹  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 20.</t>
    <t id="9338">ë°°ì¹˜ ì²˜ë¦¬ë¥¼ ìœ„í•œ ì¡°ê¸° ì¢…ë£Œ ìž„ê³„ê°’ (100-10000). ì´ë§Œí¼ì˜ ë¬´ì—­ì´ ë°œê²¬ë˜ë©´ CPUë¥¼ ì ˆì•½í•˜ê¸° ìœ„í•´ ë°°ì¹˜ ì²˜ë¦¬ê°€ ì¼ì° ì¢…ë£Œë©ë‹ˆë‹¤. ê°’ì´ ë†’ì„ìˆ˜ë¡ ë” ë§Žì€ ë¬´ì—­ì„ ì²˜ë¦¬í•˜ì§€ë§Œ CPU ë¶€í•˜ë¥¼ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë‚®ì„ìˆ˜ë¡ ë” ì¼ì° ì¢…ë£Œë˜ì§€ë§Œ ìˆ˜ìµì„± ìžˆëŠ” ë¬´ì—­ì„ ë†“ì¹  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 2000.</t>
    <t id="9341">ë°€ë¦¬ì´ˆ ë‹¨ìœ„ì˜ ë¼ì´ë¸Œ ì œì•ˆ ìŠ¬ë¼ì´ìŠ¤ ê°„ê²© (5-500ms). ë¼ì´ë¸Œ ì œì•ˆ ìŠ¬ë¼ì´ìŠ¤ê°€ ì‹œìž‘ë  ìˆ˜ ìžˆëŠ” ë¹ˆë„ë¥¼ ì œì–´í•©ë‹ˆë‹¤. ë” ë‚®ì€ ê°’ì€ ë” ë¹ ë¥¸ ì œì•ˆ ìˆ˜ì§‘ì„ í—ˆìš©í•˜ì§€ë§Œ CPU ë¶€í•˜ë¥¼ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ë” ë†’ì€ ê°’ì€ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ë¼ì´ë¸Œ ê²€ìƒ‰ ì²˜ë¦¬ë¥¼ ëŠë¦¬ê²Œ ë§Œë“­ë‹ˆë‹¤. ê¸°ë³¸ê°’: 500ms.</t>
    <t id="9363">ë°°ì¹˜ ì²˜ë¦¬ ì²­í¬ í¬ê¸° (5-20). ì²­í¬ë‹¹ chunkSizeÃ—chunkSize ì¡°í•©ì„ ì²˜ë¦¬í•©ë‹ˆë‹¤ (ì˜ˆ: 10Ã—10 = 100 ì¡°í•©). ë” í° ì²­í¬ëŠ” ì²˜ë¦¬ëŸ‰ì„ í–¥ìƒì‹œí‚¤ì§€ë§Œ ì²­í¬ë‹¹ CPU ë¶€í•˜ë¥¼ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ë” ìž‘ì€ ì²­í¬ëŠ” CPU ìŠ¤íŒŒì´í¬ë¥¼ ì¤„ì´ì§€ë§Œ ë” ë§Žì€ ì—°ì†ì´ í•„ìš”í•©ë‹ˆë‹¤. ê¸°ë³¸ê°’: 10.</t>
    <t id="9348">ë™ì‹œì— ì‹¤í–‰í•  ìˆ˜ ìžˆëŠ” ìµœëŒ€ ìºì‹œ ê²€ìƒ‰ ìˆ˜ (1-20). ìºì‹œ ê²€ìƒ‰ì€ ë¹ ë¥´ê³  ì €ë ´í•˜ë¯€ë¡œ ê°’ì´ ë†’ì„ìˆ˜ë¡ CPUì— í° ì˜í–¥ì„ ì£¼ì§€ ì•Šê³  ë” ë§Žì€ ë³‘ë ¬ ìºì‹œ í™•ì¸ì„ í—ˆìš©í•©ë‹ˆë‹¤. ê°’ì´ ë‚®ì„ìˆ˜ë¡ ë³‘ë ¬ ìºì‹œ ê²€ìƒ‰ì„ ì¤„ìž…ë‹ˆë‹¤. ê¸°ë³¸ê°’: 5.</t>
    <t id="9349">ë™ì‹œì— ì‹¤í–‰í•  ìˆ˜ ìžˆëŠ” ìµœëŒ€ ë¼ì´ë¸Œ ê²€ìƒ‰ ìˆ˜ (1-10). ë¼ì´ë¸Œ ê²€ìƒ‰ì€ CPU ì§‘ì•½ì ì´ë¯€ë¡œ ê°’ì´ ë‚®ì„ìˆ˜ë¡ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ëŒ€ê¸°ì—´ ëŒ€ê¸° ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê°’ì´ ë†’ì„ìˆ˜ë¡ ê²€ìƒ‰ì„ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ì„±ëŠ¥ ìŠ¤íŒŒì´í¬ë¥¼ ì¼ìœ¼í‚¬ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9264">ìºì‹œ ì¿¼ë¦¬ ì²­í¬ í¬ê¸°:</t>
    <t id="9265">ë¼ì´ë¸Œ ì œì•ˆ ì¶”ê°€ ì²­í¬ í¬ê¸°:</t>
    <t id="9364">ì²­í¬ë‹¹ ê²€ì¦ëœ ìºì‹œ í•­ëª© (10-200). ë” ìž‘ì€ ê°’ì€ ìºì‹œ ê²€ì¦ì„ ë” ë§Žì€ í”„ë ˆìž„ì— ë¶„ì‚°ì‹œí‚µë‹ˆë‹¤ (ë” ë¶€ë“œëŸ¬ì›€) í•˜ì§€ë§Œ ìºì‹œëœ ë¬´ì—­ì„ ì°¾ëŠ” ì‹œê°„ì„ ëŠ˜ë¦´ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 10.</t>
    <t id="9365">ì¶”ê°€ ìŠ¬ë¼ì´ìŠ¤ë‹¹ ì¶”ê°€ëœ ì œì•ˆ (50-2000). ë” ìž‘ì€ ê°’ì€ í”„ë ˆìž„ë‹¹ ëª©ë¡ ì¶”ê°€ ìž‘ì—…ì„ ì¤„ìž…ë‹ˆë‹¤ (ë” ë¶€ë“œëŸ¬ì›€) í•˜ì§€ë§Œ ë¼ì´ë¸Œ ê²€ìƒ‰ ì™„ë£Œë¥¼ ëŠë¦¬ê²Œ í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 200.</t>
    <t id="9366">ê²€ìƒ‰ ìž ê¸ˆ ì‹œê°„-ìƒì¡´ ì‹œê°„(ì´ˆ) (60-7200). í•¨ì„ ì´ ì´ê²ƒë³´ë‹¤ ë” ì˜¤ëž˜ "ë¬´ì—­ ê²€ìƒ‰ì´ ì´ë¯¸ ì§„í–‰ ì¤‘"ìœ¼ë¡œ ê±°ë¶€ë˜ë©´ GTëŠ” ì˜¤ëž˜ëœ ê²€ìƒ‰ ìƒíƒœë¥¼ ì§€ìš°ê³  ìž ê¸ˆì„ í•´ì œí•˜ì—¬ ìžê°€ ì¹˜ìœ í•©ë‹ˆë‹¤. ê¸°ë³¸ê°’: 600ì´ˆ.</t>
    <t id="9370">ë°°ì¹˜ ì—­ì•• ì†Œí”„íŠ¸ ìž„ê³„ê°’:</t>
    <t id="9371">ë°°ì¹˜ ì—­ì•• í•˜ë“œ ìž„ê³„ê°’:</t>
    <t id="9372">ìŠ¬ë¼ì´ìŠ¤ë‹¹ ì„¹í„°:</t>
    <t id="9373">í™ˆ ì„¹í„° ìƒˆë¡œê³ ì¹¨ ëŒ€ê¸° ì‹œê°„:</t>
    <t id="9374">ìºì‹œ ì‹¤íŒ¨ ê¸°ë³¸ ëŒ€ê¸° ì‹œê°„:</t>
    <t id="9375">ìŠ¤ì¼€ì¤„ëŸ¬ í‹± ê°„ê²©:</t>
    <t id="9376">í‹±ë‹¹ ìµœëŒ€ ìºì‹œ ì¿¼ë¦¬:</t>
    <t id="9377">í‹±ë‹¹ ìµœëŒ€ ê²€ìƒ‰ ì—°ì†:</t>
    <t id="9378">í‹±ë‹¹ ìµœëŒ€ í•¨ì„ :</t>
    <t id="9379">í‹±ë‹¹ ìµœëŒ€ í•­ëª©:</t>
    <t id="9380">í‹±ë‹¹ ìµœëŒ€ ê¹¨ì›€:</t>
    <t id="9381">ìºì‹œ ì¿¼ë¦¬ ìµœëŒ€ í•­ëª©:</t>
    <t id="9382">ì˜¤ëž˜ëœ ìž„ê³„ê°’(ì´ˆ):</t>
    <t id="9383">í ì˜¤ëž˜ëœ ìž„ê³„ê°’(ì´ˆ):</t>
    <t id="9384">ì‹¤íŒ¨í•œ ê±°ëž˜ ë§Œë£Œ(ì´ˆ):</t>
    <t id="9385">ìµœëŒ€ ë™ì‹œ ëŒ€ì²´ ê²€ìƒ‰:</t>
    <t id="9386">ìµœëŒ€ ë™ì‹œ ëŒ€ì²´ ê²€ìƒ‰:</t>
    <t id="9470">ë°°ì¹˜ í”„ë¡œì„¸ì„œ ë°±ë¡œê·¸ì˜ ì†Œí”„íŠ¸ ìž„ê³„ê°’ (5-50). ë°±ë¡œê·¸ê°€ ì´ ê°’ì— ë„ë‹¬í•˜ë©´ ìƒˆë¡œìš´ ê²€ìƒ‰ ìš”ì²­ì„ ëŠ¦ì¶”ê¸° ìœ„í•´ ì—­ì••ì´ ì ìš©ë˜ê¸° ì‹œìž‘í•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ì—­ì••ì„ ë” ì¼ì° íŠ¸ë¦¬ê±°í•©ë‹ˆë‹¤(ë” ë³´ìˆ˜ì ). ê¸°ë³¸ê°’: 10.</t>
    <t id="9471">ë°°ì¹˜ í”„ë¡œì„¸ì„œ ë°±ë¡œê·¸ì˜ í•˜ë“œ ìž„ê³„ê°’ (10-100). ë°±ë¡œê·¸ê°€ ì´ ê°’ì— ë„ë‹¬í•˜ë©´ ë°±ë¡œê·¸ê°€ ê°ì†Œí•  ë•Œê¹Œì§€ ìƒˆë¡œìš´ ì‹¤ì‹œê°„ ê²€ìƒ‰ì´ ì°¨ë‹¨ë©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ê²€ìƒ‰ì„ ë” ì¼ì° ì°¨ë‹¨í•©ë‹ˆë‹¤(ë” ë³´ìˆ˜ì ). ê¸°ë³¸ê°’: 25.</t>
    <t id="9472">ì‹¤ì‹œê°„ ì œì•ˆ ìˆ˜ì§‘ì—ì„œ ìŠ¬ë¼ì´ìŠ¤ë‹¹ ì²˜ë¦¬ë˜ëŠ” ì„¹í„° (1-5). ë‚®ì€ ê°’ì€ ìž‘ì—…ì„ ë” ë§Žì€ í”„ë ˆìž„ì— ë¶„ì‚°ì‹œí‚µë‹ˆë‹¤(ë” ë¶€ë“œëŸ¬ì›€) í•˜ì§€ë§Œ ì œì•ˆ ìˆ˜ì§‘ì„ ëŠë¦¬ê²Œ í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ í”„ë ˆìž„ ìŠ¤íŒŒì´í¬ë¥¼ ìœ ë°œí•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9473">í™ˆ ì„¹í„° ìƒˆë¡œê³ ì¹¨ ì™„ë£Œ í›„ ëŒ€ê¸° ì‹œê°„ (10-120ì´ˆ). ê³¼ë„í•œ ìƒˆë¡œê³ ì¹¨ ìš”ì²­ì„ ë°©ì§€í•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ë” ìžì£¼ ìƒˆë¡œê³ ì¹¨ì„ í—ˆìš©í•˜ì§€ë§Œ CPU ë¶€í•˜ë¥¼ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ë†’ì€ ê°’ì€ ìƒˆë¡œê³ ì¹¨ ë¹ˆë„ë¥¼ ì¤„ì´ì§€ë§Œ ìºì‹œ ì—…ë°ì´íŠ¸ë¥¼ ì§€ì—°ì‹œí‚¬ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 30ì´ˆ.</t>
    <t id="9474">ìºì‹œ ì‹¤íŒ¨ í›„ ì‹¤ì‹œê°„ ê²€ìƒ‰ì„ ë‹¤ì‹œ ì‹œë„í•˜ê¸° ì „ ê¸°ë³¸ ëŒ€ê¸° ì‹œê°„ (1-30ì´ˆ). ê³¼ë„í•œ ìž¬ì‹œë„ ì‹œë„ë¥¼ ë°©ì§€í•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ë” ì¼ì° ìž¬ì‹œë„í•˜ì§€ë§Œ CPU ë¶€í•˜ë¥¼ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ë†’ì€ ê°’ì€ ìž¬ì‹œë„ ë¹ˆë„ë¥¼ ì¤„ì´ì§€ë§Œ ê±°ëž˜ ì°¾ê¸°ë¥¼ ì§€ì—°ì‹œí‚¬ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 10ì´ˆ.</t>
    <t id="9475">ìŠ¤ì¼€ì¤„ëŸ¬ í‹± ê°„ì˜ ê°„ê²©(ë°€ë¦¬ì´ˆ) (50-500ms). ìŠ¤ì¼€ì¤„ëŸ¬ê°€ ìž‘ì—… íë¥¼ ì²˜ë¦¬í•˜ëŠ” ë¹ˆë„ë¥¼ ì œì–´í•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ë” ìžì£¼ ì²˜ë¦¬í•˜ì§€ë§Œ CPU ë¶€í•˜ë¥¼ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ë†’ì€ ê°’ì€ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ í ëŒ€ê¸° ì‹œê°„ì„ ì¦ê°€ì‹œí‚¬ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 100ms.</t>
    <t id="9476">ìŠ¤ì¼€ì¤„ëŸ¬ í‹±ë‹¹ ì‹œìž‘ë˜ëŠ” ìµœëŒ€ ìºì‹œ ì¿¼ë¦¬ ìˆ˜ (1-5). í”„ë ˆìž„ ì°¨ë‹¨ì„ ë°©ì§€í•˜ê¸° ìœ„í•´ ìºì‹œ ì¿¼ë¦¬ ì†ë„ë¥¼ ì œí•œí•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ CPU ìŠ¤íŒŒì´í¬ë¥¼ ì¤„ì´ì§€ë§Œ ìºì‹œ ê²€ìƒ‰ì„ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ëŠê¹€ì„ ìœ ë°œí•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9477">ìŠ¤ì¼€ì¤„ëŸ¬ í‹±ë‹¹ ì‹œìž‘ë˜ëŠ” ìµœëŒ€ ê²€ìƒ‰ ì—°ì† ìˆ˜ (1-5). í”„ë ˆìž„ ì°¨ë‹¨ì„ ë°©ì§€í•˜ê¸° ìœ„í•´ ì—°ì† ì†ë„ë¥¼ ì œí•œí•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ CPU ìŠ¤íŒŒì´í¬ë¥¼ ì¤„ì´ì§€ë§Œ ê²€ìƒ‰ ì²˜ë¦¬ë¥¼ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ëŠê¹€ì„ ìœ ë°œí•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9478">ìŠ¤ì¼€ì¤„ëŸ¬ í‹±ë‹¹ ì²˜ë¦¬ë˜ëŠ” ìµœëŒ€ í•¨ì„  ìˆ˜ (1-5). í”„ë ˆìž„ ì°¨ë‹¨ì„ ë°©ì§€í•˜ê¸° ìœ„í•´ í•¨ì„  ì²˜ë¦¬ ì†ë„ë¥¼ ì œí•œí•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ CPU ìŠ¤íŒŒì´í¬ë¥¼ ì¤„ì´ì§€ë§Œ í ì²˜ë¦¬ë¥¼ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ëŠê¹€ì„ ìœ ë°œí•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9479">ìŠ¤ì¼€ì¤„ëŸ¬ í‹±ë‹¹ ì²˜ë¦¬ë˜ëŠ” ìµœëŒ€ ìž‘ì—… í•­ëª© ìˆ˜ (1-5). í”„ë ˆìž„ ì°¨ë‹¨ì„ ë°©ì§€í•˜ê¸° ìœ„í•´ í•­ëª© ì²˜ë¦¬ ì†ë„ë¥¼ ì œí•œí•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ CPU ìŠ¤íŒŒì´í¬ë¥¼ ì¤„ì´ì§€ë§Œ í ì²˜ë¦¬ë¥¼ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ëŠê¹€ì„ ìœ ë°œí•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9480">ìŠ¤ì¼€ì¤„ëŸ¬ í‹±ë‹¹ ê¹¨ì›Œì§€ëŠ” ìµœëŒ€ ëŒ€ê¸° ìˆ˜ (1-10). ë§Žì€ ëŒ€ê¸°ê°€ íì— ìžˆì„ ë•Œ CPU ìŠ¤íŒŒì´í¬ë¥¼ ë°©ì§€í•˜ê¸° ìœ„í•´ ê¹¨ì›€ ì†ë„ë¥¼ ì œí•œí•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ CPU ìŠ¤íŒŒì´í¬ë¥¼ ì¤„ì´ì§€ë§Œ ëŒ€ê¸° ì²˜ë¦¬ë¥¼ ëŠë¦¬ê²Œ í•©ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¹ ë¥´ê²Œ ì²˜ë¦¬í•˜ì§€ë§Œ ëŠê¹€ì„ ìœ ë°œí•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 2.</t>
    <t id="9481">ë°°ì¹˜ë‹¹ ì¿¼ë¦¬ë˜ëŠ” ìµœëŒ€ ìºì‹œ í•­ëª© ìˆ˜ (1-200). ìºì‹œ ì¿¼ë¦¬ ë°°ì¹˜ í¬ê¸°ë¥¼ ì œì–´í•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ìºì‹œ ê²€ìƒ‰ì„ ë” ë¹ ë¥´ê²Œ í•˜ì§€ë§Œ ë” ë‚˜ì€ ê±°ëž˜ë¥¼ ë†“ì¹  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë§Žì€ ìºì‹œëœ ê±°ëž˜ë¥¼ ê³ ë ¤í•˜ì§€ë§Œ ê²€ì¦ ì‹œê°„ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê¸°ë³¸ê°’: 50.</t>
    <t id="9482">ì‹¤ì‹œê°„ ê²€ìƒ‰ ìƒíƒœ ì˜¤ëž˜ëœ ìž„ê³„ê°’(ì´ˆ) (60-600). ì‹¤ì‹œê°„ ê²€ìƒ‰ ìƒíƒœê°€ ì´ ê°’ë³´ë‹¤ ì˜¤ëž˜ë˜ë©´ ì˜¤ëž˜ëœ ê²ƒìœ¼ë¡œ ê°„ì£¼ë˜ì–´ ì§€ì›Œì§‘ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ì˜¤ëž˜ëœ ìƒíƒœë¥¼ ë” ì¼ì° ì§€ìš°ì§€ë§Œ í•©ë²•ì ì¸ ê²€ìƒ‰ì„ ì¤‘ë‹¨í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ê¸´ ê²€ìƒ‰ì„ í—ˆìš©í•˜ì§€ë§Œ ì˜¤ëž˜ëœ ìƒíƒœë¥¼ ë‚¨ê¸¸ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 300ì´ˆ.</t>
    <t id="9483">í í•­ëª© ì˜¤ëž˜ëœ ìž„ê³„ê°’(ì´ˆ) (30-300). í í•­ëª©ì´ ì´ ê°’ë³´ë‹¤ ì˜¤ëž˜ë˜ë©´ ì˜¤ëž˜ëœ ê²ƒìœ¼ë¡œ ê°„ì£¼ë˜ì–´ ì œê±°ë©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ì˜¤ëž˜ëœ í•­ëª©ì„ ë” ì¼ì° ì§€ìš°ì§€ë§Œ í•©ë²•ì ì¸ í í•­ëª©ì„ ì œê±°í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ê¸´ í ì‹œê°„ì„ í—ˆìš©í•˜ì§€ë§Œ ì˜¤ëž˜ëœ í•­ëª©ì„ ë‚¨ê¸¸ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 60ì´ˆ.</t>
    <t id="9484">ì‹¤íŒ¨í•œ ê±°ëž˜ ìºì‹œ ë§Œë£Œ(ì´ˆ) (300-3600). ì‹¤íŒ¨í•œ ê±°ëž˜ëŠ” ì¦‰ì‹œ ìž¬ì‹œë„ë¥¼ í”¼í•˜ê¸° ìœ„í•´ ìºì‹œë©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ ì‹¤íŒ¨í•œ ê±°ëž˜ë¥¼ ë” ì¼ì° ë§Œë£Œì‹œí‚µë‹ˆë‹¤(ë” ë§Žì€ ìž¬ì‹œë„) í•˜ì§€ë§Œ ìºì‹œ íš¨ê³¼ë¥¼ ì¤„ìž…ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ì˜¤ëž˜ ìºì‹œí•©ë‹ˆë‹¤(ë” ì ì€ ìž¬ì‹œë„) í•˜ì§€ë§Œ ìž¬ì‹œë„ ì‹œë„ë¥¼ ì§€ì—°ì‹œí‚¬ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ê¸°ë³¸ê°’: 1800ì´ˆ(30ë¶„).</t>
    <t id="9485">ìµœëŒ€ ë™ì‹œ ëŒ€ì²´ ì‹¤ì‹œê°„ ê²€ìƒ‰ (1-10). ëŒ€ì²´ ê²€ìƒ‰ì€ í™ˆ ì„¹í„° ìž ê¸ˆì„ ìš°íšŒí•˜ì—¬ ë™ì¼í•œ í™ˆ ì„¹í„°ì˜ ì—¬ëŸ¬ í•¨ì„ ì´ ë™ì‹œì— ê²€ìƒ‰í•  ìˆ˜ ìžˆë„ë¡ í•©ë‹ˆë‹¤. ë‚®ì€ ê°’ì€ CPU ë¶€í•˜ë¥¼ ì¤„ì´ì§€ë§Œ ëŒ€ì²´ ê²€ìƒ‰ì„ ëŠë¦¬ê²Œ í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë§Žì€ ë³‘ë ¬ ëŒ€ì²´ ê²€ìƒ‰ì„ í—ˆìš©í•˜ì§€ë§Œ CPU ì‚¬ìš©ëŸ‰ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. ê¸°ë³¸ê°’: 1.</t>
    <t id="9490">í•¨ì„ ì— GT_Trade_Found ì‹ í˜¸ë¥¼ ë³´ë‚´ê¸° ì „ ì§€ì—° ì‹œê°„(ë°€ë¦¬ì´ˆ) (0-1000ms). 0 = ì¦‰ì‹œ ì „ë‹¬ (ì‹ ë¢°ì„±ì„ ìœ„í•´ ê¶Œìž¥ - ê²½ìŸ ì¡°ê±´ ì œê±°). í•¨ì„ ì€ ì§€ì—°ëœ ì‹ í˜¸ë¥¼ ìž¡ê¸° ìœ„í•´ í•­ìƒ (êµ¬ì„±ëœ ì§€ì—° + 5ms ë²„í¼) ëŒ€ê¸°í•œ í›„ ìƒˆ ìš”ì²­ì„ ë³´ëƒ…ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¶€ë“œëŸ¬ìš´ ì„±ëŠ¥ì„ ìœ„í•´ í”„ë ˆìž„ì— ì‹ í˜¸ë¥¼ ë¶„ì‚°ì‹œí‚µë‹ˆë‹¤. ê¸°ë³¸ê°’: 0ms.</t>
    <t id="9590">í•¨ì„ ì— GT_Trade_Found ì‹ í˜¸ë¥¼ ë³´ë‚´ê¸° ì „ ì§€ì—° ì‹œê°„(ë°€ë¦¬ì´ˆ) (10-1000ms). í•¨ì„ ì€ ì§€ì—°ëœ ì‹ í˜¸ë¥¼ ìž¡ê¸° ìœ„í•´ í•­ìƒ (êµ¬ì„±ëœ ì§€ì—° + 5ms ë²„í¼) ëŒ€ê¸°í•œ í›„ ìƒˆ ìš”ì²­ì„ ë³´ëƒ…ë‹ˆë‹¤. ë†’ì€ ê°’ì€ ë” ë¶€ë“œëŸ¬ìš´ ì„±ëŠ¥ì„ ìœ„í•´ í”„ë ˆìž„ì— ì‹ í˜¸ë¥¼ ë¶„ì‚°ì‹œí‚µë‹ˆë‹¤. ê¸°ë³¸ê°’: 10ms.</t>
    <t id="8000">GalaxyTrader í•¨ëŒ€</t>
    <t id="8001">GalaxyTrader í•¨ëŒ€ ê´€ë¦¬ ë° íŒŒì¼ëŸ¿ í†µê³„</t>
    <t id="8002">ëª¨ë“  GalaxyTrader íŒŒì¼ëŸ¿ ë³´ê¸° ë° ê´€ë¦¬</t>
    <t id="8100">í•¨ì„  ID</t>
    <t id="8101">íŒŒì¼ëŸ¿</t>
    <t id="8102">í•¨ì„ </t>
    <t id="8103">ìƒíƒœ</t>
    <t id="8104">ê³„ê¸‰</t>
    <t id="8105">ë ˆë²¨</t>
    <t id="8106">XP</t>
    <t id="8107">ì´ ì´ìµ</t>
    <t id="8108">ìœ„ì¹˜</t>
    <t id="8109">ìž‘ì „ ê¸°ì§€</t>
    <t id="8110">ë§ˆì§€ë§‰ ë¬´ì—­</t>
    <t id="8111">íŒŒì¼ëŸ¿ ì´ìµ</t>
    <t id="8112">í•¨ì„  ì´ìµ</t>
    <t id="8113">ë¬´ì—­ íšŸìˆ˜</t>
    <t id="8200">ìƒˆë¡œê³ ì¹¨</t>
    <t id="8201">CSV ë‚´ë³´ë‚´ê¸°</t>
    <t id="8202">í†µê³„</t>
    <t id="8203">ì„¤ì •</t>
    <t id="8204">ë„ì›€ë§</t>
    <t id="8205">ë‹«ê¸°</t>
    <t id="8300">ëª¨ë“  íŒŒì¼ëŸ¿</t>
    <t id="8301">ë¬´ì—­</t>
    <t id="8302">í›ˆë ¨</t>
    <t id="8303">ì •ë¹„</t>
    <t id="8304">ë¹„ìƒ</t>
    <t id="8305">ì´ˆë³´ìž (ë ˆë²¨ 1-5)</t>
    <t id="8306">ê³ ê¸‰ (ë ˆë²¨ 6-11)</t>
    <t id="8307">ì „ë¬¸ê°€ (ë ˆë²¨ 12+)</t>
    <t id="8308">ìƒìœ„ 10 ìˆ˜ìµ</t>
    <t id="8350">ì •ë ¬ ê¸°ì¤€:</t>
    <t id="8351">í•¨ì„  ID</t>
    <t id="8352">íŒŒì¼ëŸ¿ ì´ë¦„</t>
    <t id="8353">í•¨ì„  íƒ€ìž…</t>
    <t id="8354">ìƒíƒœ</t>
    <t id="8355">ê³„ê¸‰</t>
    <t id="8356">ë ˆë²¨</t>
    <t id="8357">XP</t>
    <t id="8358">ì´ìµ</t>
    <t id="8400">ë“±ë¡ëœ íŒŒì¼ëŸ¿ ì—†ìŒ</t>
    <t id="8401">í•„í„°ì™€ ì¼ì¹˜í•˜ëŠ” íŒŒì¼ëŸ¿ ì—†ìŒ</t>
    <t id="8402">ì´ íŒŒì¼ëŸ¿:</t>
    <t id="8403">í•¨ëŒ€ ì´ ì´ìµ:</t>
    <t id="8404">ë§ˆì§€ë§‰ ì—…ë°ì´íŠ¸:</t>
    <t id="8405">íŒŒì¼ëŸ¿ ê²€ìƒ‰ ì¤‘...</t>
    <t id="8114">ì„¹í„°</t>
    <t id="8320">í•¨ì„  ì´ë¦„ ë³€ê²½</t>
    <t id="8321">ì‚¬ìš©ìž ì •ì˜ ì´ë¦„</t>
    <t id="8322">ì´ë¦„ ì„¤ì •</t>
    <t id="8323">ì´ë¦„ ì§€ìš°ê¸°</t>
    <t id="8324">ì´ë¦„ì´ ì„±ê³µì ìœ¼ë¡œ ì„¤ì •ë¨</t>
    <t id="8325">ì´ë¦„ì´ ì„±ê³µì ìœ¼ë¡œ ì§€ì›Œì§</t>
    <t id="8450">í›ˆë ¨ì†Œë¡œ ë³´ë‚´ê¸°</t>
    <t id="8451">ë“±ë¡ í•´ì œ</t>
    <t id="8452">í™”ë¬¼ ê°•ì œ íŒë§¤</t>
    <t id="8453">ìˆ˜ë¦¬ì†Œë¡œ ë³´ë‚´ê¸°</t>
    <t id="8454">ë³´ê¸‰ì†Œë¡œ ë³´ë‚´ê¸°</t>
    <t id="8455">ëª¨ë“  ì£¼ë¬¸ ì¤‘ì§€</t>
    <t id="8456">ìž‘ì—…</t>
    <t id="8500">í•¨ì„  IDë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8501">íŒŒì¼ëŸ¿ ì´ë¦„ìœ¼ë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8502">í•¨ì„  íƒ€ìž…ìœ¼ë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8503">ìƒíƒœë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8504">ê³„ê¸‰ìœ¼ë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8505">ë ˆë²¨ë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8506">XPë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8507">ì´ ì´ìµìœ¼ë¡œ ì •ë ¬í•˜ë ¤ë©´ í´ë¦­</t>
    <t id="8508">ë¯¸ì…˜ ì‹œìŠ¤í…œì—ì„œ íŒŒì¼ëŸ¿ ë°ì´í„° ìƒˆë¡œê³ ì¹¨</t>
    <t id="8509">í˜„ìž¬ ë³´ê¸°ë¥¼ CSV íŒŒì¼ë¡œ ë‚´ë³´ë‚´ê¸°</t>
    <t id="8510">í•¨ëŒ€ í†µê³„ ë° ê·¸ëž˜í”„ ë³´ê¸°</t>
    <t id="8511">ë©”ë‰´ ì„¤ì • êµ¬ì„±</t>
    <t id="8512">ë„ì›€ë§ ë° ë‹¨ì¶•í‚¤ í‘œì‹œ</t>
    <t id="8600">GalaxyTrader íŒŒì¼ëŸ¿ì„ ì°¾ì„ ìˆ˜ ì—†ìŒ</t>
    <t id="8601">í•¨ì„ ì„ GalaxyTraderì— í• ë‹¹í•˜ì—¬ íŒŒì¼ëŸ¿ì„ ë§Œë“¤ê±°ë‚˜ ë°ì´í„°ê°€ ë¡œë“œë  ë•Œê¹Œì§€ ê¸°ë‹¤ë¦¬ì„¸ìš”.</t>
    <t id="9001">GT ì´ë¦„ ë³€ê²½</t>
    <t id="9902">í›ˆë ¨ ë³´ë‚´ê¸°</t>
    <t id="9903">%1ì— ëŒ€í•œ ìˆ˜ë™ í›ˆë ¨ì´ ëŒ€ê¸°ì—´ì— ì¶”ê°€ë˜ì—ˆìŠµë‹ˆë‹¤. ì¡°ì¢…ì‚¬ëŠ” í˜„ìž¬ ì£¼ê¸°ê°€ ëë‚œ í›„ í›ˆë ¨ì„ ì‹œìž‘í•©ë‹ˆë‹¤.</t>
    <t id="9904">í˜„ìž¬ ì£¼ê¸° í›„ í›ˆë ¨ì´ ëŒ€ê¸°ì—´ì— ì¶”ê°€ë¨</t>
    <t id="9905">ì¡°ì¢…ì‚¬ ë˜ëŠ” í•¨ì„ ì„ ì°¾ì„ ìˆ˜ ì—†ìŠµë‹ˆë‹¤</t>
    <t id="9906">ìžë™ í›ˆë ¨ì´ í™œì„±í™”ë˜ì–´ ìˆ˜ë™ ëŒ€ê¸°ì—´ì´ í•„ìš”í•˜ì§€ ì•ŠìŠµë‹ˆë‹¤</t>
    <t id="9907">ì¡°ì¢…ì‚¬ê°€ í›ˆë ¨ ì°¨ë‹¨ ìƒíƒœê°€ ì•„ë‹™ë‹ˆë‹¤</t>
    <t id="9910">íŠ¸ë ˆì´ë”© ì•„ì¹´ë°ë¯¸</t>
    <t id="9911">ê²¬ìŠµìƒ (Lvl 4) - %1 / %2</t>
    <t id="9912">ìƒì¸ (Lvl 7) - %1 / %2</t>
    <t id="9913">ë§ˆìŠ¤í„° íŠ¸ë ˆì´ë” (Lvl 13) - %1 / %2</t>
    <t id="9920">ì¡°ì¢…ì‚¬ %1ì´(ê°€) ë ˆë²¨ %2 ì•„ì¹´ë°ë¯¸ ê³¼ì •ì— ë“±ë¡í–ˆìŠµë‹ˆë‹¤. ê°€ìž¥ ê°€ê¹Œìš´ ë¬´ì—­ì—­ìœ¼ë¡œ ì¶œë°œí•©ë‹ˆë‹¤.</t>
    <t id="9921">ì´ ê³¼ì •ì— ëŒ€í•œ ìžê¸ˆì´ ë¶€ì¡±í•©ë‹ˆë‹¤(%1 í•„ìš”, %2 ìžˆìŒ).</t>
    <t id="9922">ê°•ì¢Œë¥¼ ì´ìš©í•  ìˆ˜ ì—†ìŠµë‹ˆë‹¤. íŒŒì¼ëŸ¿ %1ì€(ëŠ”) ì´ë¯¸ ì´ ìˆ˜ì¤€ ì´ìƒìž…ë‹ˆë‹¤.</t>
    <t id="9923">ì¡°ì¢…ì‚¬ %1ëŠ” %5 íƒ‘ìŠ¹í•˜ì—¬ Trading Academy ë ˆë²¨ %2 ê³¼ì •(ë¹„ìš©: %3 Cr, ê¸°ê°„: %4 ë¶„)ì— ë“±ë¡í–ˆìŠµë‹ˆë‹¤.</t>
    <t id="11011">GT ê²¬ìŠµìƒ ì¤‘í˜• í•¨ì„  ê°ì†Œê¸°</t>
    <t id="11012">ì¤‘í˜• í•¨ì„ ì—ì„œ ê²½í—˜ì´ ë¶€ì¡±í•œ íŒŒì¼ëŸ¿ì˜ ì„±ëŠ¥ì„ ì•½ê°„ ê°ì†Œì‹œí‚¤ëŠ” ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -5% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="11013">GT ê²¬ìŠµìƒ ì¤‘í˜• ì—¬í–‰ ê°ì†Œê¸°</t>
    <t id="11014">ì¤‘í˜• í•¨ì„ ì—ì„œ ê²½í—˜ì´ ë¶€ì¡±í•œ íŒŒì¼ëŸ¿ì˜ ì—¬í–‰ ì„±ëŠ¥ì„ ì•½ê°„ ê°ì†Œì‹œí‚¤ëŠ” ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -5% ì—¬í–‰ ì†ë„.</t>
    <t id="11021">GT ê²¬ìŠµìƒ ëŒ€í˜• í•¨ì„  ê°ì†Œê¸°</t>
    <t id="11022">ëŒ€í˜• í•¨ì„ ì—ì„œ ê²½í—˜ì´ ë¶€ì¡±í•œ íŒŒì¼ëŸ¿ì˜ ì„±ëŠ¥ì„ ê°ì†Œì‹œí‚¤ëŠ” ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -15% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="11023">GT ê²¬ìŠµìƒ ëŒ€í˜• ì—¬í–‰ ê°ì†Œê¸°</t>
    <t id="11024">ëŒ€í˜• í•¨ì„ ì—ì„œ ê²½í—˜ì´ ë¶€ì¡±í•œ íŒŒì¼ëŸ¿ì˜ ì—¬í–‰ ì„±ëŠ¥ì„ ê°ì†Œì‹œí‚¤ëŠ” ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -15% ì—¬í–‰ ì†ë„.</t>
    <t id="11031">GT ê²¬ìŠµìƒ ìºí”¼í„¸ í•¨ì„  ê°ì†Œê¸°</t>
    <t id="11032">ìºí”¼í„¸ í•¨ì„ ì—ì„œ ê²½í—˜ì´ ë¶€ì¡±í•œ íŒŒì¼ëŸ¿ì˜ ì„±ëŠ¥ì„ í¬ê²Œ ê°ì†Œì‹œí‚¤ëŠ” ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -25% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="11033">GT ê²¬ìŠµìƒ ìºí”¼í„¸ ì—¬í–‰ ê°ì†Œê¸°</t>
    <t id="11034">ìºí”¼í„¸ í•¨ì„ ì—ì„œ ê²½í—˜ì´ ë¶€ì¡±í•œ íŒŒì¼ëŸ¿ì˜ ì—¬í–‰ ì„±ëŠ¥ì„ í¬ê²Œ ê°ì†Œì‹œí‚¤ëŠ” ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -25% ì—¬í–‰ ì†ë„.</t>
    <t id="12001">GT ê¸°ë³¸ ì†Œí˜• í•¨ì„  í–¥ìƒê¸°</t>
    <t id="12002">ê¸°ë³¸ ì¸ì¦ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ì†Œí˜• í•¨ì„ ì„ ìœ„í•œ ì „ë¬¸ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +3% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="12003">GT ê¸°ë³¸ ì†Œí˜• ì—¬í–‰ í–¥ìƒê¸°</t>
    <t id="12004">ê¸°ë³¸ ì¸ì¦ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ì†Œí˜• í•¨ì„ ì„ ìœ„í•œ ì „ë¬¸ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +3% ì—¬í–‰ ì†ë„.</t>
    <t id="13001">GT ê¸°ë³¸ ëŒ€í˜• í•¨ì„  ê°ì†Œê¸°</t>
    <t id="13002">ê¸°ë³¸ ì¸ì¦ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ëŒ€í˜• í•¨ì„ ì„ ìœ„í•œ ì „ë¬¸ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -8% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="13003">GT ê¸°ë³¸ ëŒ€í˜• ì—¬í–‰ ê°ì†Œê¸°</t>
    <t id="13004">ê¸°ë³¸ ì¸ì¦ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ëŒ€í˜• í•¨ì„ ì„ ìœ„í•œ ì „ë¬¸ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -8% ì—¬í–‰ ì†ë„.</t>
    <t id="14001">GT ê¸°ë³¸ ìºí”¼í„¸ í•¨ì„  ê°ì†Œê¸°</t>
    <t id="14002">ê¸°ë³¸ ì¸ì¦ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ìºí”¼í„¸ í•¨ì„ ì„ ìœ„í•œ ì „ë¬¸ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -15% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="14003">GT ê¸°ë³¸ ìºí”¼í„¸ ì—¬í–‰ ê°ì†Œê¸°</t>
    <t id="14004">ê¸°ë³¸ ì¸ì¦ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ìºí”¼í„¸ í•¨ì„ ì„ ìœ„í•œ ì „ë¬¸ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. -15% ì—¬í–‰ ì†ë„.</t>
    <t id="15001">GT ì „ë¬¸ê°€ ì†Œí˜• í•¨ì„  í–¥ìƒê¸°</t>
    <t id="15002">ì „ë¬¸ê°€ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ì†Œí˜• í•¨ì„ ì„ ìœ„í•œ ê³ ê¸‰ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +25% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="15003">GT ì „ë¬¸ê°€ ì†Œí˜• ì—¬í–‰ í–¥ìƒê¸°</t>
    <t id="15004">ì „ë¬¸ê°€ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ì†Œí˜• í•¨ì„ ì„ ìœ„í•œ ê³ ê¸‰ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +25% ì—¬í–‰ ì†ë„.</t>
    <t id="16001">GT ì „ë¬¸ê°€ ëŒ€í˜• í•¨ì„  í–¥ìƒê¸°</t>
    <t id="16002">ì „ë¬¸ê°€ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ëŒ€í˜• í•¨ì„ ì„ ìœ„í•œ ê³ ê¸‰ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +15% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="16003">GT ì „ë¬¸ê°€ ëŒ€í˜• ì—¬í–‰ í–¥ìƒê¸°</t>
    <t id="16004">ì „ë¬¸ê°€ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ëŒ€í˜• í•¨ì„ ì„ ìœ„í•œ ê³ ê¸‰ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +15% ì—¬í–‰ ì†ë„.</t>
    <t id="17001">GT ì „ë¬¸ê°€ ìºí”¼í„¸ í•¨ì„  í–¥ìƒê¸°</t>
    <t id="17002">ì „ë¬¸ê°€ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ìºí”¼í„¸ í•¨ì„ ì„ ìœ„í•œ ê³ ê¸‰ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +6% ì†ë„, ì¶”ë ¥ ë° íšŒì „.</t>
    <t id="17003">GT ì „ë¬¸ê°€ ìºí”¼í„¸ ì—¬í–‰ í–¥ìƒê¸°</t>
    <t id="17004">ì „ë¬¸ê°€ íŒŒì¼ëŸ¿ì´ ìžˆëŠ” ìºí”¼í„¸ í•¨ì„ ì„ ìœ„í•œ ê³ ê¸‰ ì—”ì§„ ìˆ˜ì •. GalaxyTrader AI ì‹œìŠ¤í…œì—ì„œ ì‚¬ìš©ë©ë‹ˆë‹¤. +6% ì—¬í–‰ ì†ë„.</t>
    <t id="18001">ì‹¬ê°í•œ ê¸°ìˆ  ì œí•œ (ì„ ì²´)</t>
    <t id="18002">ì‹¬ê°í•œ ê¸°ìˆ  ì œí•œ (ì„ ì²´) - ëŒ€í˜• ì„ ë°•ì— ëŒ€í•œ íŒŒì¼ëŸ¿ì˜ ê²½í—˜ ë¶€ì¡±ìœ¼ë¡œ ì¸í•œ ì‹¬ê°í•œ ì„±ëŠ¥ íŽ˜ë„í‹°ë¥¼ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. íŒŒì¼ëŸ¿ ê¸°ìˆ ì´ ì„ ë°• í¬ê¸°ì— ë¶€ì¡±í•  ë•Œ GalaxyTrader ì‹œìŠ¤í…œì— ì˜í•´ ìžë™ìœ¼ë¡œ ì ìš©ë©ë‹ˆë‹¤. ì„ ë°• ì§ˆëŸ‰ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. (GT ì‹œìŠ¤í…œ ì „ìš© - ìˆ˜ë™ ì„¤ì¹˜ ë¶ˆê°€)</t>
    <t id="18003">ì¤‘ê°„ ê¸°ìˆ  ì œí•œ (ì„ ì²´)</t>
    <t id="18004">ì¤‘ê°„ ê¸°ìˆ  ì œí•œ (ì„ ì²´) - íŒŒì¼ëŸ¿ì´ ì„ ë°•ì˜ ë³µìž¡ì„±ì— ì ì‘í•˜ëŠ” ë™ì•ˆì˜ ì¤‘ê°„ ì„±ëŠ¥ íŽ˜ë„í‹°ë¥¼ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. íŒŒì¼ëŸ¿ ê¸°ìˆ ì´ ì„ ë°• í¬ê¸°ì— ë¶€ì¡±í•  ë•Œ GalaxyTrader ì‹œìŠ¤í…œì— ì˜í•´ ìžë™ìœ¼ë¡œ ì ìš©ë©ë‹ˆë‹¤. ì„ ë°• ì§ˆëŸ‰ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. (GT ì‹œìŠ¤í…œ ì „ìš© - ìˆ˜ë™ ì„¤ì¹˜ ë¶ˆê°€)</t>
    <t id="18005">ê²½ë¯¸í•œ ê¸°ìˆ  ì œí•œ (ì„ ì²´)</t>
    <t id="18006">ê²½ë¯¸í•œ ê¸°ìˆ  ì œí•œ (ì„ ì²´) - íŒŒì¼ëŸ¿ ê¸°ìˆ  ê°œë°œ ì¤‘ì˜ ê²½ë¯¸í•œ ì„±ëŠ¥ íŽ˜ë„í‹°ë¥¼ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. íŒŒì¼ëŸ¿ ê¸°ìˆ ì´ ì„ ë°• í¬ê¸°ì— ë¶€ì¡±í•  ë•Œ GalaxyTrader ì‹œìŠ¤í…œì— ì˜í•´ ìžë™ìœ¼ë¡œ ì ìš©ë©ë‹ˆë‹¤. ì„ ë°• ì§ˆëŸ‰ì„ ì¦ê°€ì‹œí‚µë‹ˆë‹¤. (GT ì‹œìŠ¤í…œ ì „ìš© - ìˆ˜ë™ ì„¤ì¹˜ ë¶ˆê°€)</t>
    <t id="18007">ì‹¬ê°í•œ ê¸°ìˆ  ì œí•œ (ì—”ì§„)</t>
    <t id="18008">ì‹¬ê°í•œ ê¸°ìˆ  ì œí•œ (ì—”ì§„) - ëŒ€í˜• ì„ ë°•ì— ëŒ€í•œ íŒŒì¼ëŸ¿ì˜ ê²½í—˜ ë¶€ì¡±ìœ¼ë¡œ ì¸í•œ ì‹¬ê°í•œ ì„±ëŠ¥ íŽ˜ë„í‹°ë¥¼ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. íŒŒì¼ëŸ¿ ê¸°ìˆ ì´ ì„ ë°• í¬ê¸°ì— ë¶€ì¡±í•  ë•Œ GalaxyTrader ì‹œìŠ¤í…œì— ì˜í•´ ìžë™ìœ¼ë¡œ ì ìš©ë©ë‹ˆë‹¤. ì—”ì§„ ì¶”ë ¥ê³¼ íšŒì „ì„ ê°ì†Œì‹œí‚µë‹ˆë‹¤. (GT ì‹œìŠ¤í…œ ì „ìš© - ìˆ˜ë™ ì„¤ì¹˜ ë¶ˆê°€)</t>
    <t id="18009">ì¤‘ê°„ ê¸°ìˆ  ì œí•œ (ì—”ì§„)</t>
    <t id="18010">ì¤‘ê°„ ê¸°ìˆ  ì œí•œ (ì—”ì§„) - íŒŒì¼ëŸ¿ì´ ì„ ë°•ì˜ ë³µìž¡ì„±ì— ì ì‘í•˜ëŠ” ë™ì•ˆì˜ ì¤‘ê°„ ì„±ëŠ¥ íŽ˜ë„í‹°ë¥¼ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. íŒŒì¼ëŸ¿ ê¸°ìˆ ì´ ì„ ë°• í¬ê¸°ì— ë¶€ì¡±í•  ë•Œ GalaxyTrader ì‹œìŠ¤í…œì— ì˜í•´ ìžë™ìœ¼ë¡œ ì ìš©ë©ë‹ˆë‹¤. ì—”ì§„ ì¶”ë ¥ê³¼ íšŒì „ì„ ê°ì†Œì‹œí‚µë‹ˆë‹¤. (GT ì‹œìŠ¤í…œ ì „ìš© - ìˆ˜ë™ ì„¤ì¹˜ ë¶ˆê°€)</t>
    <t id="18011">ê²½ë¯¸í•œ ê¸°ìˆ  ì œí•œ (ì—”ì§„)</t>
    <t id="18012">ê²½ë¯¸í•œ ê¸°ìˆ  ì œí•œ (ì—”ì§„) - íŒŒì¼ëŸ¿ ê¸°ìˆ  ê°œë°œ ì¤‘ì˜ ê²½ë¯¸í•œ ì„±ëŠ¥ íŽ˜ë„í‹°ë¥¼ ë‚˜íƒ€ëƒ…ë‹ˆë‹¤. íŒŒì¼ëŸ¿ ê¸°ìˆ ì´ ì„ ë°• í¬ê¸°ì— ë¶€ì¡±í•  ë•Œ GalaxyTrader ì‹œìŠ¤í…œì— ì˜í•´ ìžë™ìœ¼ë¡œ ì ìš©ë©ë‹ˆë‹¤. ì—”ì§„ ì¶”ë ¥ê³¼ íšŒì „ì„ ê°ì†Œì‹œí‚µë‹ˆë‹¤. (GT ì‹œìŠ¤í…œ ì „ìš© - ìˆ˜ë™ ì„¤ì¹˜ ë¶ˆê°€)</t>
    <t id="9250">í•¨ì„  ìƒíƒœ ëª…ëª…</t>
    <t id="9350">í•¨ì„  ìƒíƒœ ì•½ì–´ë¥¼ ì‚¬ìš©ìž ì •ì˜í•©ë‹ˆë‹¤. ê¸°ë³¸ê°’ì€ ìž…ë ¥ ìƒìžì— í‘œì‹œë˜ë©° ë®ì–´ì“¸ ìˆ˜ ìžˆìŠµë‹ˆë‹¤. ìµœëŒ€ 3ìž. ë³€ê²½í•˜ë©´ ëª¨ë“  í•¨ì„  ì´ë¦„ì´ ìžë™ìœ¼ë¡œ ì—…ë°ì´íŠ¸ë©ë‹ˆë‹¤.</t>
    <t id="9251">ë³´ê¸‰ ìƒíƒœ ì•½ì–´:</t>
    <t id="9252">ìˆ˜ë¦¬ ìƒíƒœ ì•½ì–´:</t>
    <t id="9253">ìœ ì§€ë³´ìˆ˜ ìƒíƒœ ì•½ì–´:</t>
    <t id="9254">í›ˆë ¨ ìƒíƒœ ì•½ì–´:</t>
    <t id="9255">ìž¬ë¼ìš°íŒ… ìƒíƒœ ì•½ì–´:</t>
    <t id="9256">í´ë¦¬ì–´ëŸ°ìŠ¤ ìƒíƒœ ì•½ì–´:</t>
    <t id="9257">ì°¨ë‹¨ ìƒíƒœ ì•½ì–´:</t>
    <t id="9258">í´ë°± ìƒíƒœ ì•½ì–´:</t>
    <t id="9259">ê²©ë¦¬ ìƒíƒœ ì•½ì–´:</t>
    <t id="9260">ë¬´ì—­ ìƒíƒœ ì•½ì–´:</t>
    <t id="9261">ìœ íœ´ ìƒíƒœ ì•½ì–´:</t>
    <t id="9262">íƒˆì¶œ ìƒíƒœ ì•½ì–´:</t>
    <t id="9268">ë„ë‹¬í•  ìˆ˜ ì—†ëŠ” ìƒíƒœ ì•½ì–´:</t>
    <t id="9269">íŒŒì¼ëŸ¿ êµí™˜ ìƒíƒœ ì•½ì–´:</t>
    <t id="9270">ì‚¬ìš©ìž ì •ì˜ ë¸”ëž™ë¦¬ìŠ¤íŠ¸ ì ‘ë‘ì‚¬ íƒœê·¸:</t>
    <t id="9700">ì¹˜íŠ¸ (ê³ ìž¥ë‚¬ìŠµë‹ˆë‹¤. ë³¼ ê²ƒ ì—†ìŒ!! ì§„ì§œ!!)</t>
    <t id="9701">GT í•¨ì„  ë¬´ì </t>
    <t id="9702">ëª¨ë“  í”Œë ˆì´ì–´ í•¨ì„  ë¬´ì </t>
    <t id="9800">ê·¸ëƒ¥ ì§€ë‚˜ê°€ì„¸ìš”. ê³ ìž¥ ë‚œ ê°œë°œìž í…ŒìŠ¤íŠ¸ ë„êµ¬ìž…ë‹ˆë‹¤. ìž¬ë¯¸ìžˆëŠ” ë²„íŠ¼ ë©”ë‰´ê°€ ì•„ë‹™ë‹ˆë‹¤. ë³¼ ê²ƒ ì—†ìŠµë‹ˆë‹¤. ì§„ì§œë¡œ. ê²½ê³ í–ˆìŠµë‹ˆë‹¤. ì•„ë§ˆë„.</t>
    <t id="9801">GalaxyTrader ëª…ë ¹ ì¤‘ì¸ í•¨ì„ ì€ ì„ ì²´ì™€ ì‹¤ë“œê°€ 100% ì•„ëž˜ë¡œ ë–¨ì–´ì§€ì§€ ì•ŠìŠµë‹ˆë‹¤. ë‹¤ì‹œ í´ë¦­í•˜ë©´ ë¹„í™œì„±í™”ë©ë‹ˆë‹¤.</t>
    <t id="9802">ëª¨ë“  í”Œë ˆì´ì–´ í•¨ì„ ì€ ì„ ì²´ì™€ ì‹¤ë“œê°€ 100% ì•„ëž˜ë¡œ ë–¨ì–´ì§€ì§€ ì•ŠìŠµë‹ˆë‹¤. ë‹¤ì‹œ í´ë¦­í•˜ë©´ ë¹„í™œì„±í™”ë©ë‹ˆë‹¤. ì •ê±°ìž¥ì€ ì˜í–¥ì„ ë°›ì§€ ì•ŠìŠµë‹ˆë‹¤.</t>
    <t id="9703">GT í…ŒìŠ¤íŠ¸ìš© ìš°ì£¼ ê³µê°œ</t>
    <t id="9704">ê³µê°œë¨</t>
    <t id="9705">ê³µê°œ</t>
    <t id="9803">ëª¨ë“  ì„¹í„°ì˜ ì „ìŸ ì•ˆê°œë¥¼ ê³µê°œí•˜ê³  ëª¨ë“  ì •ê±°ìž¥ì„ ì•Œë ¤ì§„ ìƒíƒœë¡œ í‘œì‹œí•˜ë©° ëª¨ë“  íŒ©ì…˜ ë¬´ì—­ êµ¬ë… ë¼ì´ì„ ìŠ¤ë¥¼ ë¶€ì—¬í•˜ê³  ì€í•˜ ì „ì²´ ë¬´ì—­ ì œì•ˆì„ êµ¬ë…í•©ë‹ˆë‹¤. ìƒˆ DLC ì„¹í„° í›„ ë‹¤ì‹œ í´ë¦­í•˜ì„¸ìš”. í…ŒìŠ¤íŠ¸ ì „ìš©ìž…ë‹ˆë‹¤.</t>
    <t id="9706">ë“±ë¡ëœ GT íŒŒì¼ëŸ¿ XP ìµœëŒ€í™”</t>
    <t id="9707">ìµœëŒ€í™”ë¨</t>
    <t id="9708">XP ìµœëŒ€</t>
    <t id="9804">GT ë ˆì§€ìŠ¤íŠ¸ë¦¬ì˜ ëª¨ë“  íŒŒì¼ëŸ¿ì„ ë ˆë²¨ 15 ë° ìµœëŒ€ XPë¡œ ì„¤ì •í•©ë‹ˆë‹¤. í›ˆë ¨ ê²Œì´íŠ¸ì™€ ì°¨ë‹¨ì„ í•´ì œí•©ë‹ˆë‹¤. ë°”ë‹ë¼ XP ì „ìš© ëª¨ë“œì—ì„œëŠ” ê±´ë„ˆëœë‹ˆë‹¤. í…ŒìŠ¤íŠ¸ ì „ìš©.</t>
    <t id="9351">ë³´ê¸‰ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: RS)</t>
    <t id="9352">ìˆ˜ë¦¬ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: RP)</t>
    <t id="9353">ìœ ì§€ë³´ìˆ˜ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: MT)</t>
    <t id="9354">í›ˆë ¨ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: TR)</t>
    <t id="9355">ìž¬ë¼ìš°íŒ… ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: RR)</t>
    <t id="9356">í´ë¦¬ì–´ëŸ°ìŠ¤ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: CL)</t>
    <t id="9357">ì°¨ë‹¨ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: BL)</t>
    <t id="9358">í´ë°± ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: FB)</t>
    <t id="9359">ê²©ë¦¬ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: IS)</t>
    <t id="9360">ë¬´ì—­ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: TD)</t>
    <t id="9361">ìœ íœ´ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: ID)</t>
    <t id="9362">íƒˆì¶œ ìƒíƒœì˜ ì•½ì–´ (ê¸°ë³¸ê°’: ES)</t>
    <t id="9367">Unreachable ìƒíƒœì˜ ì•½ì–´(ê¸°ë³¸ê°’: UR)</t>
    <t id="9368">Pilot Exchange ìƒíƒœì˜ ì•½ì–´(ê¸°ë³¸ê°’: PE)</t>
    <t id="9369">ì‚¬ìš©ìž ì •ì˜ ì„¸ë ¥ ë¸”ëž™ë¦¬ìŠ¤íŠ¸(í•˜ìœ„ ì„ ë°• í¬í•¨)ì˜ ì˜í–¥ì„ ë°›ëŠ” MK3 ì„ ë°•ì˜ ì ‘ë‘ì‚¬ë¡œ í‘œì‹œë©ë‹ˆë‹¤. ê¸°ë³¸ê°’: CB</t>
    <t id="30002">ê°¤ëŸ­ì‹œíŠ¸ë ˆì´ë” MK1</t>
    <t id="30102">ì—­ ìƒì¸ - NPC ì„¸ë ¥ì— ì—­ ì œí’ˆì„ íŒë§¤í•©ë‹ˆë‹¤.</t>
    <t id="30010">í™ˆ ìŠ¤í…Œì´ì…˜</t>
    <t id="30011">ìµœëŒ€ íŒë§¤ ê±°ë¦¬</t>
    <t id="30012">ë¬´ì—­ ê·œì¹™ ë¬´ì‹œ</t>
    <t id="30013">ë„ìžê¸° í•„í„°</t>
    <t id="30014">í™”ë¬¼ ì±„ìš°ê¸° ëª©í‘œ % íŒë§¤</t>
    <t id="30015">ì—­ì¶”ì  ê³µì°¨</t>
    <t id="30016">í™”ë¬¼ ì¶©ì „ ëª©í‘œ % êµ¬ë§¤</t>
    <t id="30017">ë¡œê·¸ë¶ í•­ëª©</t>
    <t id="30018">ì•Œë¦¼ ìˆ˜ì¤€</t>
    <t id="30019">í•¨ëŒ€ ì¡°ì •</t>
    <t id="30020">ë””ë²„ê·¸ ìˆ˜ì¤€</t>
    <t id="30021">ë³´ê¸‰ì†Œ</t>
    <t id="30022">ìµœì†Œ ìŠ¤í…Œì´ì…˜ ì €ìž¥ %</t>
    <t id="30023">ë¶ˆë²• ìƒí’ˆ í—ˆìš©</t>
    <t id="30024">í™”ë¬¼/ì´ìµ</t>
    <t id="30025">ë‹¤ì¤‘ ê±°ëž˜ í—ˆìš©</t>
    <t id="30110">ìƒí’ˆì„ íŒë§¤í•  í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜(ìŠ¤í…Œì´ì…˜ í• ë‹¹ í•„ìš”)</t>
    <t id="30111">NPC êµ¬ë§¤ìžë¥¼ ì°¾ëŠ” ìµœëŒ€ ê²Œì´íŠ¸ ê±°ë¦¬(íŒŒì¼ëŸ¿ ìŠ¤í‚¬ì— ë”°ë¼ ì œí•œë¨)</t>
    <t id="30112">ìŠ¤í…Œì´ì…˜ ë¬´ì—­ ì œí•œ ë¬´ì‹œ - ìŠ¤í…Œì´ì…˜ ë¬´ì—­ ê·œì¹™ì— ê´€ê³„ì—†ì´ ëª¨ë“  ìš°í˜¸ ì„¸ë ¥ì—ê²Œ íŒë§¤</t>
    <t id="30113">ì„ íƒì ì¸ ë„ìžê¸° í•„í„°; ëª¨ë“  ìŠ¤í…Œì´ì…˜ ì œí’ˆ ë° ìƒí’ˆì„ íŒë§¤í•˜ë ¤ë©´ ë¹„ì›Œë‘ì„¸ìš”.</t>
    <t id="30114">íŒë§¤ ì—¬í–‰ ì¶œë°œ ì „ ìµœì†Œ í™”ë¬¼ ì¶©ì „ ë¹„ìœ¨</t>
    <t id="30115">ì—¬í–‰ì— ë‘ ë²ˆì§¸ ìƒí’ˆì„ ì¶”ê°€í•  ë•Œ í—ˆìš©ë˜ëŠ” ìµœëŒ€ ì¶”ê°€ ì í”„(0 = ê²½ë¡œì— ì§ì ‘ êµ¬ë§¤ìžë§Œ)</t>
    <t id="30116">ê³µê¸‰ ì‹¤í–‰ì„ ìœ„í•œ ëª©í‘œ í™”ë¬¼ ì±„ìš°ê¸°(ì†Œí”„íŠ¸ ëª©í‘œ, ê±°ëž˜ìžëŠ” ë” ì¼ì° ì¶œë°œí•  ìˆ˜ ìžˆìŒ)</t>
    <t id="30117">ê±°ëž˜ë³„ ë¡œê·¸ë¶ í•­ëª© í™œì„±í™”</t>
    <t id="30118">ì•Œë¦¼ ìˆ˜ì¤€: 0=ì¡°ìš©í•¨, 1=ë³´í†µ, 2=ìƒì„¸</t>
    <t id="30119">ì°¨ëŸ‰ ì¡°ì • ë° ê±°ëž˜ ì˜ˆì•½ ì‹œìŠ¤í…œ í™œì„±í™”</t>
    <t id="30120">ë””ë²„ê·¸ ë¡œê¹… ìˆ˜ì¤€: 0=í•´ì œ, 1=ë³´í†µ, 2=ìƒì„¸</t>
    <t id="30121">í™œì„±í™”ë˜ë©´ ìŠ¤í…Œì´ì…˜ì— ëŒ€í•œ ë¦¬ì†ŒìŠ¤ë„ êµ¬ë§¤í•©ë‹ˆë‹¤. ì €ìž¥ëŸ‰ì´ ìµœì†Œ ìž„ê³„ê°’ ë¯¸ë§Œìœ¼ë¡œ ë–¨ì–´ì§€ë©´ ê³µê¸‰ì´ ìš°ì„  ì ìš©ë©ë‹ˆë‹¤.</t>
    <t id="30122">ìžì›ì´ ëª©í‘œì˜ ì´ ë¹„ìœ¨ ì•„ëž˜ë¡œ ë–¨ì–´ì§€ë©´ ê³µê¸‰ì´ íŒë§¤ë³´ë‹¤ ìš°ì„ ì‹œë©ë‹ˆë‹¤. ìŠ¤í…Œì´ì…˜ì´ ë¦¬ì†ŒìŠ¤ë¥¼ ê°ë‹¹í•  ìˆ˜ ì—†ìœ¼ë©´ ë¬´ì‹œë©ë‹ˆë‹¤.</t>
    <t id="30123">ê°€ëŠ¥í•œ ê²½ìš° ë¶ˆë²•/ë°€ìˆ˜í’ˆ íŒë§¤ ë˜ëŠ” êµ¬ë§¤ë¥¼ í—ˆìš©í•©ë‹ˆë‹¤.</t>
    <t id="30124">íŒë§¤ ì„ íƒ: 1=í™”ë¬¼(í•´ë‹¹ ìƒí’ˆì˜ ì°½ê³  ì¶©ì „ë¥ ì´ ê°€ìž¥ ë†’ì€ ê²ƒ ìš°ì„ , ë™ë¥ ì´ë©´ ì´ìµ), 2=ì´ìµ(ìµœê³  ì´ìµ ì ìˆ˜)</t>
    <t id="30125">í•œ ì£¼ê¸°ì— ì—¬ëŸ¬ íŒë§¤ ê±°ëž˜ë¥¼ ì—°ê²°í•  ìˆ˜ ìžˆìŠµë‹ˆë‹¤(ìµœëŒ€ 3ì¢… ìƒí’ˆ ë˜ëŠ” ëª©ì ì§€). ë¹„í™œì„±í™”í•˜ë©´ í•œ ì£¼ê¸°ì— ë‹¨ì¼ ê±°ëž˜ë§Œ ì‹¤í–‰</t>
    <t id="30200">%1 %2ì„(ë¥¼) %3ì—ì„œ %4(ìœ¼)ë¡œ íŒë§¤</t>
    <t id="30201">%1 ì í”„ ì´ë‚´ì— ë°©ì†¡êµ­ ì œí’ˆì— ëŒ€í•œ êµ¬ë§¤ìžë¥¼ ì°¾ì„ ìˆ˜ ì—†ìŠµë‹ˆë‹¤.</t>
    <t id="30202">í™ˆ ìŠ¤í…Œì´ì…˜ %1 íŒŒê´´ - ìŠ¤í…Œì´ì…˜ íŠ¸ë ˆì´ë” ì£¼ë¬¸ ì·¨ì†Œ</t>
    <t id="30203">í™ˆ ìŠ¤í…Œì´ì…˜ %1ì€(ëŠ”) ë” ì´ìƒ í”Œë ˆì´ì–´ ì†Œìœ ê°€ ì•„ë‹™ë‹ˆë‹¤. ì£¼ë¬¸ì´ ì·¨ì†Œë˜ì—ˆìŠµë‹ˆë‹¤.</t>
    <t id="30204">ìŠ¤í…Œì´ì…˜ í• ë‹¹ í•„ìš” - ì£¼ë¬¸ ì·¨ì†Œë¨</t>
    <t id="30205">MK1 ìŠ¤í…Œì´ì…˜ íŠ¸ë ˆì´ë”ê°€ %1ì— ì‹œìž‘ë˜ì—ˆìŠµë‹ˆë‹¤.</t>
    <t id="30206">Completed sale: %1 %2 sold to %3 for %4 Cr (profit: %5 Cr)</t>
    <t id="30207">ë‹¤ì¤‘ ìƒí’ˆ ì—¬í–‰: %1 ìƒí’ˆì„ %2 ëª©ì ì§€ë¡œ ë°°ì†¡</t>
    <t id="30208">Supplying %1 %2 to %3 from %4</t>
    <t id="30500">GalaxyTrader MK1 ì„¤ì •</t>
    <t id="30501">ìŠ¤í…Œì´ì…˜ íŠ¸ë ˆì´ë” ê¸°ë³¸ê°’</t>
    <t id="30502">ê¸°ë³¸ ìµœëŒ€ íŒë§¤ ê±°ë¦¬</t>
    <t id="30503">ê¸°ë³¸ íŒë§¤ í™”ë¬¼ ì±„ìš°ê¸° ëª©í‘œ</t>
    <t id="30504">ê¸°ë³¸ ë¬´ì‹œ ë¬´ì—­ ê·œì¹™</t>
    <t id="30505">ê¸°ë³¸ ì—­ì¶”ì  í—ˆìš© ì˜¤ì°¨</t>
    <t id="30506">ê±°ëž˜ê°€ ì—†ì„ ë•Œì˜ ëŒ€ê¸° ì‹œê°„</t>
    <t id="30507">ê¸°ë³¸ êµ¬ë§¤ í™”ë¬¼ ì±„ìš°ê¸° ëª©í‘œ</t>
    <t id="31002">ê°¤ëŸ­ì‹œ ë§ˆì´ë„ˆ</t>
    <t id="31102">ìŠ¤í…Œì´ì…˜ ë³´ê¸‰ ë° XP ì„±ìž¥ì´ í¬í•¨ëœ ìžìœ¨ ì±„êµ´</t>
    <t id="31010">ëª¨í•­ ìŠ¤í…Œì´ì…˜</t>
    <t id="31110">ì±„êµ´ ë° ë‚©í’ˆ ëŒ€ìƒ ìŠ¤í…Œì´ì…˜ (ëª¨í•­ ì„¹í„°ì™€ ìƒí˜¸ ë°°íƒ€)</t>
    <t id="31011">ëª¨í•­ ì„¹í„°</t>
    <t id="31111">ìš´ìš© ì„¹í„°; ëª¨í•­ ìŠ¤í…Œì´ì…˜ì´ ì—†ì„ ë•Œ ì‚¬ìš©</t>
    <t id="31012">ìžì› ë°”ìŠ¤ì¼“</t>
    <t id="31112">ì±„êµ´í•  ìžì›; ë¹„ì–´ ìžˆìœ¼ë©´ ìŠ¤í…Œì´ì…˜ ìˆ˜ìš”ë¥¼ ë”°ë¦„</t>
    <t id="31013">ëŒ€ìƒ ìŠ¤í…Œì´ì…˜</t>
    <t id="31113">ë‚©í’ˆìš© ì„ íƒ ìŠ¤í…Œì´ì…˜ í•„í„°; ë¹„ì–´ ìžˆìœ¼ë©´ ëª¨í•­ ê¸°ì¤€ìœ¼ë¡œ ê²°ì •</t>
    <t id="31014">ì˜¤ë²„í”Œë¡œ ìž„ê³„ê°’ %</t>
    <t id="31114">ì €ìž¥ ë¹„ìœ¨ì´ ì´ ê°’ ì´ìƒì¸ ìŠ¤í…Œì´ì…˜ì€ ê°€ë“ ì°¸ìœ¼ë¡œ ì²˜ë¦¬</t>
    <t id="31015">ì˜¤ë²„í”Œë¡œ íƒ€ ì„¸ë ¥ íŒë§¤ í—ˆìš©</t>
    <t id="31115">í™œì„±í™” ì‹œ ì£¼ìš” ëŒ€ìƒì´ ê°€ë“ ì°¨ë©´ ë‹¤ë¥¸ ì„¸ë ¥ ìŠ¤í…Œì´ì…˜ì— íŒë§¤</t>
    <t id="31016">ìŠ¤í…Œì´ì…˜ì— ë°°ì†</t>
    <t id="31116">ê°€ëŠ¥í•œ ê²½ìš° í•¨ì„ ì„ ëª¨í•­ ìŠ¤í…Œì´ì…˜ì˜ ì±„êµ´ í•˜ìœ„í•¨ìœ¼ë¡œ ë°°ì†</t>
    <t id="31017">ëª¨í•­ ìœ ì§€</t>
    <t id="31117">ì˜¤ë²„í”Œë¡œ ì˜ˆì™¸ë¥¼ ì œì™¸í•˜ê³  ì±„êµ´/íŒë§¤ë¥¼ ëª¨í•­ êµ¬ì—­ìœ¼ë¡œ ì œí•œ</t>
    <t id="31018">ìžì› í”„ë¡œë¸Œ ìžë™ ë°°ì¹˜</t>
    <t id="31118">ì ìž¬ëœ ìžì› í”„ë¡œë¸Œë¥¼ ìžë™ ë°°ì¹˜í•˜ê³  ì •ë¹„ ìž¬ë³´ê¸‰ì— í”„ë¡œë¸Œë¥¼ í¬í•¨</t>
    <t id="31019">ìµœëŒ€ ì±„ì§‘ ê±°ë¦¬</t>
    <t id="31119">ì±„ì§‘ ìµœëŒ€ ê²Œì´íŠ¸ ê±°ë¦¬ (0ì€ íŒŒì¼ëŸ¿/ì‚¬ë ¹ê´€ í•œë„ ì‚¬ìš©)</t>
    <t id="31020">ìµœëŒ€ íŒë§¤ ê±°ë¦¬</t>
    <t id="31120">íŒë§¤ ìµœëŒ€ ê²Œì´íŠ¸ ê±°ë¦¬ (0ì€ íŒŒì¼ëŸ¿/ì‚¬ë ¹ê´€ í•œë„ ì‚¬ìš©)</t>
    <t id="31021">í•¨ëŒ€ ê· í˜• ì¡°ì •</t>
    <t id="31121">ìŠ¤í…Œì´ì…˜ ê³¼ìž‰ì„ ì¤„ì´ê¸° ìœ„í•´ ê²°ì •ì  ì˜ë„ ì¡°ì •ì„ í™œì„±í™”</t>
    <t id="31022">ìˆ˜ìš” ìž¬í™•ì¸ ê°„ê²©</t>
    <t id="31122">ì±„êµ´ì„ ì˜ ìˆ˜ìš”/ì „í™˜ í‰ê°€ë¥¼ ì‹¤í–‰í•˜ëŠ” ì£¼ê¸°</t>
    <t id="31023">ìž„ê³„ ìˆ˜ìš” ë¸íƒ€</t>
    <t id="31123">í™œì„± ì±„êµ´ ìžì›ì„ ì „í™˜í•˜ê¸° ìœ„í•œ ìµœì†Œ ê¸´ê¸‰ë„ ì°¨ì´</t>
    <t id="31024">ìµœì†Œ ì „í™˜ ì¿¨ë‹¤ìš´</t>
    <t id="31124">ì´ í•¨ì„ ì˜ ë‘ ë²ˆì˜ ìžì› ì „í™˜ ì‚¬ì´ ìµœì†Œ ì‹œê°„</t>
    <t id="31025">ìµœì†Œ í™”ë¬¼ ê³ ì • %</t>
    <t id="31125">í™”ë¬¼ ì ìž¬ìœ¨ì´ ì´ ê°’ì„ ë„˜ìœ¼ë©´ ì „í™˜ ì „ í˜„ìž¬ ë‚©í’ˆ ì™„ë£Œë¥¼ ìš°ì„ </t>
    <t id="31026">ê¸´ê¸‰ ì¦‰ì‹œ ì „í™˜ ë¸íƒ€</t>
    <t id="31126">í™”ë¬¼ ê³ ì • ìž„ê³„ê°’ì„ ë„˜ë”ë¼ë„ ì¦‰ì‹œ ì „í™˜ì„ í—ˆìš©í•˜ëŠ” ê¸´ê¸‰ë„ ì°¨ì´</t>
    <t id="31027">ì•Œë¦¼ ìˆ˜ì¤€</t>
    <t id="31127">ì•Œë¦¼ ìˆ˜ì¤€: 0=ì¡°ìš©ížˆ, 1=ë³´í†µ, 2=ìƒì„¸</t>
    <t id="31028">í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜ë§Œ</t>
    <t id="31128">í™œì„±í™”ë˜ë©´ í”Œë ˆì´ì–´ ì†Œìœ  ìŠ¤í…Œì´ì…˜ë§Œ ìˆ˜ìš” ëª©í‘œë¡œ ê°„ì£¼ë©ë‹ˆë‹¤.</t>
    <t id="31031">ìˆ˜ìš” ë¨¼ì € í™•ì¸</t>
    <t id="31131">í™œì„±í™”í•˜ë©´ ì±„êµ´ ì „ì— ìŠ¤í…Œì´ì…˜ ìˆ˜ìš”ë¥¼ í™•ì¸í•˜ê³  ìžì› ìš°ì„ ìˆœìœ„ë¥¼ ì •í•©ë‹ˆë‹¤. ë¹„í™œì„±í™”í•˜ë©´ ìˆ˜ìš” í™•ì¸ ì—†ì´ ìžì› ë°”êµ¬ë‹ˆì—ì„œ ì±„êµ´í•˜ê³  êµ¬ë§¤ìžê°€ ë‚˜íƒ€ë‚  ë•Œê¹Œì§€ ë¹„ì¶•í•©ë‹ˆë‹¤(ë‹¨ì¼ ìžì› í•¨ëŒ€ì— ê¶Œìž¥).</t>
    <t id="31032">ë¬¼ë¦¬ ì €ìž¥ ì¤‘ë‹¨ %</t>
    <t id="31132">ë ˆë²¨ 6 ì´ìƒ íŒŒì¼ëŸ¿ìš©: ìŠ¤í…Œì´ì…˜ ë¬¼ë¦¬ ìž¬ê³ ì™€ ê´€ë ¨ ì±„êµ´ì„ ì˜ ì ìž¬ í™”ë¬¼ í•©ì´ í˜„ìž¬ ë¬¼ë¦¬ ìž¬ê³ ë¥¼ ì´ ë¹„ìœ¨ë§Œí¼ ì´ˆê³¼í•˜ë©´ í•´ë‹¹ ìžì› ì±„êµ´ì„ ì¤‘ë‹¨í•©ë‹ˆë‹¤. ì‹¤ì œ í™”ë¬¼ ìˆ˜ëŸ‰ì„ ì‚¬ìš©í•˜ë©° ì˜¤ë²„í”Œë¡œ ìž„ê³„ê°’ê³¼ ë³„ê°œìž…ë‹ˆë‹¤. 0ì´ë©´ ë¹„í™œì„±.</t>
    <t id="32002">GalaxyTrader MK4 ê³µê¸‰</t>
    <t id="32102">GT ìºì‹œ/ì‹¤ì‹œê°„ ê²€ìƒ‰ íŒŒì´í”„ë¼ì¸ì„ ì‚¬ìš©í•˜ëŠ” í”Œë ˆì´ì–´ ìŠ¤í…Œì´ì…˜ ê³µê¸‰ ìƒì¸</t>
    <t id="32010">ì ìš© ê±°ë¦¬</t>
    <t id="32110">ëª©ì ì§€ ìˆ˜ìš” ê²€ìƒ‰ì„ ìœ„í•œ ì§‘ê¹Œì§€ì˜ ìµœëŒ€ ê²Œì´íŠ¸ ê±°ë¦¬</t>
    <t id="32011">ê±°ë¦¬ êµ¬ë§¤</t>
    <t id="32111">ê³µê¸‰ì—…ì²´ ê²€ìƒ‰ì„ ìœ„í•œ ì§‘ê³¼ì˜ ìµœëŒ€ ê²Œì´íŠ¸ ê±°ë¦¬</t>
    <t id="32012">ì§‘ì—ì„œë§Œ ì„œë¹„ìŠ¤ ì œê³µ</t>
    <t id="32112">í™œì„±í™”ë˜ë©´ í™ˆ ìŠ¤í…Œì´ì…˜ ìˆ˜ìš”ë§Œ ì œê³µë©ë‹ˆë‹¤.</t>
    <t id="32013">ìŠ¤í…Œì´ì…˜ë§Œ êµ¬ì¶•</t>
    <t id="32113">í™œì„±í™”ë˜ë©´ ë¹Œë“œ ìŠ¤í† ë¦¬ì§€ ìˆ˜ìš”ë§Œ ì œê³µë©ë‹ˆë‹¤.</t>
    <t id="32014">í”Œë ˆì´ì–´ì—ì„œ êµ¬ë§¤</t>
    <t id="32114">í”Œë ˆì´ì–´ ì†Œìœ  ê³µê¸‰ì—…ì²´ì˜ ìƒí’ˆ ì†Œì‹± í—ˆìš©</t>
    <t id="32015">íŒ©ì…˜ì—ì„œ êµ¬ë§¤</t>
    <t id="32115">í”Œë ˆì´ì–´ê°€ ì•„ë‹Œ ì„¸ë ¥ ê³µê¸‰ìžë¡œë¶€í„° ìƒí’ˆì„ ì†Œì‹±í•˜ëŠ” ê²ƒì„ í—ˆìš©í•©ë‹ˆë‹¤.</t>
    <t id="32016">ë¦¬ì†ŒìŠ¤ í—ˆìš©</t>
    <t id="32116">ìˆ˜ìš” ë§¤ì¹­ì— ìžì› ìƒí’ˆ í¬í•¨</t>
    <t id="32017">ì¤‘ê°„ì²´ í—ˆìš©</t>
    <t id="32117">ìˆ˜ìš” ë§¤ì¹­ì— ì¤‘ê°„ ìƒí’ˆ í¬í•¨</t>
    <t id="32018">ì œí’ˆ í—ˆìš©</t>
    <t id="32118">ìˆ˜ìš” ë§¤ì¹­ì— ì œí’ˆ ìƒí’ˆ í¬í•¨</t>
    <t id="32019">ìƒí‘œ í—ˆìš©</t>
    <t id="32119">ìˆ˜ìš” ë§¤ì¹­ì— íŠ¸ë ˆì´ë“œì›¨ì–´ í¬í•¨</t>
    <t id="20002">ê°¤ëŸ­ì‹œíŠ¸ë ˆì´ë” MK2</t>
    <t id="20102">ì €ìž¥ ìž„ê³„ê°’ ê´€ë¦¬ê°€ í¬í•¨ëœ ì°½ê³  ë¶„ë°°</t>
    <t id="20010">ê³µê¸‰ ìŠ¤í…Œì´ì…˜</t>
    <t id="20011">ëŒ€ìƒ ìŠ¤í…Œì´ì…˜</t>
    <t id="20012">ìµœì†Œ ì €ìž¥ëŸ‰ %</t>
    <t id="20013">ì •ì  ì €ìž¥ëŸ‰ %</t>
    <t id="20014">ìµœëŒ€ ì €ìž¥ëŸ‰ %</t>
    <t id="20015">ìƒí’ˆ í•„í„°</t>
    <t id="20016">ì–‘ë°©í–¥ ëª¨ë“œ</t>
    <t id="20017">ëª¨í•­ ìŠ¤í…Œì´ì…˜(ì„ íƒ)</t>
    <t id="20018">ìµœëŒ€ ê±°ë¦¬</t>
    <t id="20032">ëª¨í•­ ì„¹í„°(ì„ íƒ)</t>
    <t id="20019">ì‚¬ì´í´ ëŒ€ê¸° ì‹œê°„</t>
    <t id="20030">ì €ìš©ëŸ‰ í—ˆìš©</t>
    <t id="20031">ì €ìš©ëŸ‰ ìµœì†Œ ì ìž¬ìœ¨ %</t>
    <t id="20110">ìƒí’ˆì„ ë¶„ë°°í•  ê³µê¸‰ ìŠ¤í…Œì´ì…˜ ëª©ë¡</t>
    <t id="20111">ë¶„ë°° ëŒ€ìƒ ìŠ¤í…Œì´ì…˜/ì°½ê³  ëª©ë¡</t>
    <t id="20112">ëŒ€ìƒ ê¸´ê¸‰ ìž„ê³„ê°’: ì´ ì €ìž¥ % ì´í•˜ ìŠ¤í…Œì´ì…˜ì— ìš°ì„  ë°°ì†¡</t>
    <t id="20113">ê³µê¸‰ ìµœì†Œ ìž„ê³„ê°’: ì´ %ë¥¼ ì´ˆê³¼í•´ì•¼ ë¶„ë°° ê°€ëŠ¥</t>
    <t id="20114">ê³µê¸‰ ê³¼ìž‰ ìž„ê³„ê°’: ì´ %ë¥¼ ë„˜ìœ¼ë©´ ë¹„ê¸´ê¸‰ ëŒ€ìƒì—ë„ ë¶„ë°°</t>
    <t id="20115">ì„ íƒ ìƒí’ˆ í•„í„°; ë¹„ì›Œë‘ë©´ ê³µê¸‰ì›ì˜ ëª¨ë“  ìƒí’ˆ ë¶„ë°°</t>
    <t id="20116">ëŒ€ìƒì— ì´ˆê³¼ë¶„ì´ ìžˆì„ ë•Œ ëŒ€ìƒì—ì„œ ê³µê¸‰ì›ìœ¼ë¡œ ì—­íšŒìˆ˜ í™œì„±í™”</t>
    <t id="20117">í• ë‹¹ìš© ëª¨í•­ ìŠ¤í…Œì´ì…˜(ì„ íƒ). ë¹„ì›Œë‘ë©´ ìŠ¤í…Œì´ì…˜ì— í• ë‹¹ë˜ì§€ ì•ŠìŒ.</t>
    <t id="20118">ê³µê¸‰ì›-ëŒ€ìƒ ê°„ ìµœëŒ€ ê²Œì´íŠ¸ ê±°ë¦¬(0 = ì œí•œ ì—†ìŒ)</t>
    <t id="20132">ëª¨í•­ ìŠ¤í…Œì´ì…˜ì´ ì„¤ì •ë˜ì§€ ì•Šì•˜ì„ ë•Œ ìœ íœ´ ì£¼ì°¨ì— ì‚¬ìš©í•  ì„ íƒì  ëª¨í•­ ì„¹í„°ìž…ë‹ˆë‹¤.</t>
    <t id="20119">ë¶„ë°° ì‚¬ì´í´ ê°„ ëŒ€ê¸° ì‹œê°„</t>
    <t id="20130">ì¼ë°˜ ìµœì†Œ ì ìž¬ìœ¨ë³´ë‹¤ ë‚®ë”ë¼ë„ ê¸´ê¸‰ë„ ê¸°ë°˜ì˜ ì†ŒëŸ‰ ìš´ì†¡ì„ í—ˆìš©í•©ë‹ˆë‹¤.</t>
    <t id="20131">ì €ìš©ëŸ‰ ëª¨ë“œ í™œì„±í™” ì‹œ ì ìš©ë˜ëŠ” ìµœì†Œ ì ìž¬ìœ¨(%).</t>
    <t id="20200">%1 %2ì„(ë¥¼) %3ì—ì„œ %4ë¡œ ë¶„ë°° ì¤‘</t>
    <t id="20201">ë³µê·€ ìš´ì†¡: %1 %2ì„(ë¥¼) %3ì—ì„œ %4ë¡œ íšŒìˆ˜ ì¤‘</t>
    <t id="20202">ë¶„ë°° ë¶ˆí•„ìš” - ëª¨ë“  ëŒ€ìƒì´ ì¶©ë¶„ížˆ ê³µê¸‰ë¨</t>
    <t id="20203">ëª¨ë“  ê³µê¸‰ ìŠ¤í…Œì´ì…˜ì´ ìœ íš¨í•˜ì§€ ì•ŠìŒ - ë¶„ë°° ëŒ€ê¸° ì¤‘</t>
    <t id="20204">ëª¨ë“  ëŒ€ìƒ ìŠ¤í…Œì´ì…˜ì´ ìœ íš¨í•˜ì§€ ì•ŠìŒ - ë¶„ë°° ëŒ€ê¸° ì¤‘</t>
    <t id="20205">ê³µê¸‰ ìŠ¤í…Œì´ì…˜ %1 íŒŒê´´ - ë¶„ë°° ëª…ë ¹ì—ì„œ ì œê±°ë¨</t>
    <t id="20206">ëŒ€ìƒ ìŠ¤í…Œì´ì…˜ %1 íŒŒê´´ - ë¶„ë°° ëª…ë ¹ì—ì„œ ì œê±°ë¨</t>
    <t id="20500">GalaxyTrader MK2 - ì „ì—­ ì„¤ì •</t>
    <t id="20501">MK2 ë¶„ë°° ê¸°ë³¸ê°’</t>
    <t id="20510">ê¸°ë³¸ ìµœì†Œ ì €ìž¥ëŸ‰ %</t>
    <t id="20511">ê¸°ë³¸ ì •ì  ì €ìž¥ëŸ‰ %</t>
    <t id="20512">ê¸°ë³¸ ìµœëŒ€ ì €ìž¥ëŸ‰ %</t>
    <t id="20513">ê¸°ë³¸ ì‚¬ì´í´ ëŒ€ê¸°(ì´ˆ)</t>
    <t id="20514">ìµœì†Œ í™”ë¬¼ ì ìž¬ìœ¨ %</t>
    <t id="20520">ì•Œë¦¼ ìƒì„¸ë„</t>
    <t id="20521">ë””ë²„ê·¸ ë ˆë²¨</t>
    <t id="10006">ì§‘ìœ¼ë¡œ ëŒì•„ê°€ê¸°</t>
    <t id="10007">GalaxyTrader MK4-2 ê³µê¸‰</t>
    <t id="10106">í™ˆ ìŠ¤í…Œì´ì…˜ì— ë„í‚¹í•˜ê³  ê±°ëž˜ê°€ ìž¬ê°œë  ë•Œê¹Œì§€ ê·¸ê³³ì— ë¨¸ë¬¼ëŸ¬ ìžˆìŠµë‹ˆë‹¤.</t>
    <t id="10107">ë°°ì†¡ ëŒ€ìƒ ìš°ì„ ìˆœìœ„ ìŠ¬ë¼ì´ë”ê°€ ìžˆëŠ” í”Œë ˆì´ì–´ ê³µê¸‰ ëª…ë ¹</t>
    <t id="30026">ì‚¬ì´í´ ì‚¬ì´ì— ì§‘ìœ¼ë¡œ ëŒì•„ê°€ê¸°</t>
    <t id="30028">ì˜¤í¼ ì„¤ì • ë¬´ì‹œ</t>
    <t id="30029">êµ¬ë§¤ìž ê°€ê²© ë²”ìœ„</t>
    <t id="30027">ìµœì†Œ ì œí’ˆ ì €ìž¥ %</t>
    <t id="30126">í™œì„±í™”ë˜ë©´ í™ˆ ìŠ¤í…Œì´ì…˜ìœ¼ë¡œ ëŒì•„ê°€ ê±°ëž˜ ì£¼ê¸° ì‚¬ì´ì— ë„í‚¹í•©ë‹ˆë‹¤. ë¹„í™œì„±í™”ë˜ë©´ í˜„ìž¬ ìœ„ì¹˜ì—ì„œ ê³„ì† ê²€ìƒ‰í•©ë‹ˆë‹¤(ê¸°ì¡´ ë™ìž‘).</t>
    <t id="30128">ìŠ¤í…Œì´ì…˜ ë§¤ìˆ˜/ë§¤ë„ ì˜¤í¼ ì—†ì´ ë‚´ë¶€ ì €ìž¥ì†Œ ì´ì „ í—ˆìš©. ë²„í¼ í”½ì—… ë° ë°°ì†¡ì— ë¬¼í’ˆ êµí™˜ ì‚¬ìš©. 'ë¬´ì—­ ê·œì¹™ ë¬´ì‹œ'ê°€ êº¼ì ¸ ìžˆìœ¼ë©´ ì—­ ë¬´ì—­ ê·œì¹™ì´ ê³„ì† ì ìš©ë©ë‹ˆë‹¤.</t>
    <t id="30129">ì—­ ì œí’ˆì„ íŒë§¤í•  ë•Œ NPC êµ¬ë§¤ìžì˜ ìµœì†Œ ìƒëŒ€ ê°€ê²©. ëª…ë ¹ ìŠ¬ë¼ì´ë” 0-200(100 = í‰ê· , 0 = -100%, 200 = +100%)ì€ -1.0..+1.0ì— ëŒ€ì‘. ë†’ì„ìˆ˜ë¡ ë¹„ì‹¼ êµ¬ë§¤ìžë§Œ. ë‚®ì„ìˆ˜ë¡ êµ¬ë§¤ìž ì„ íƒì§€ ì¦ê°€. ë³´ê¸‰ ìš´í–‰ì€ ê³µê¸‰ìž ê°€ê²© ìƒí•œì— ë°˜ì „ëœ ê°’ì„ ì‚¬ìš©.</t>
    <t id="30127">ì œí’ˆ ë˜ëŠ” ê±°ëž˜í’ˆì„ íŒë§¤í•˜ê¸° ì „ì— í•„ìš”í•œ ìŠ¤í…Œì´ì…˜ ì €ìž¥ì†Œ ìµœì†Œ ì¶©ì „ë¥ (í’ˆëª©ë³„ êµ¬ì„±ëœ ìµœëŒ€ì¹˜ ëŒ€ë¹„ %). ì´ ìž„ê³„ê°’ ë¯¸ë§Œì˜ í’ˆëª©ì€ ê±´ë„ˆëœë‹ˆë‹¤. 0 = ìµœì†Œ ì—†ìŒ.</t>
    <t id="3107">ë‹¤ì¤‘ ê±°ëž˜ ëŒ€ê¸° ì¤‘: %1. ë‚˜ëŠ” %2ì˜ ì´ìµì„ ë²Œì–´ì•¼ í•©ë‹ˆë‹¤.</t>
    <t id="3108">%1 %2ì„(ë¥¼) %3ì—ì„œ %4ì— íŒë§¤í•©ë‹ˆë‹¤. %5ì˜ ì´ìµì„ ì–»ì„ ê²ƒìž…ë‹ˆë‹¤.</t>
    <t id="3110">%1 %2 ë³´ê¸‰ì„ ëŒ€ê¸°ì—´ì— ì¶”ê°€í–ˆìŠµë‹ˆë‹¤. %4ì—ì„œ %3ì— ì¡°ë‹¬, %5(ìœ¼)ë¡œ ë°°ì†¡í•©ë‹ˆë‹¤. ê³ ê° ë§¤ìˆ˜ í•œë„ %6 - í•œë„ ëŒ€ë¹„ %7/ë‹¨ìœ„ ì ˆê° (ì´ %8).</t>
    <t id="3111">%1 %2 ë³´ê¸‰ì„ ëŒ€ê¸°ì—´ì— ì¶”ê°€í–ˆìŠµë‹ˆë‹¤. %3ì—ì„œ %4(ìœ¼)ë¡œ.</t>
    <t id="3112">ë³´ê¸‰ ëŒ€ê¸° ì¤‘ (%1 êµ¬ê°„): %2. ê³ ê° ë§¤ìˆ˜ í•œë„ ëŒ€ë¹„ ì´ %3 ì ˆê°.</t>
    <t id="3113">ìŠ¤í…Œì´ì…˜ íŠ¸ë ˆì´ë”: ìˆ˜ì¶œ ë‹¤ì¤‘ ê±°ëž˜ ëŒ€ê¸° ì¤‘: %1. ì˜ˆìƒ ì´ìµ %2.</t>
    <t id="31029">í”„ë¡œë¸Œ ìž¬ê³  ëŒ€ìƒ</t>
    <t id="31030">êµ¬ë§¤í•  ì±„êµ´ ë“œë¡  ìˆ˜</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: ì±„êµ´ ê°€ëŠ¥í•œ ë¬¼ìžê°€ ì—†ìŠµë‹ˆë‹¤. í•¨ì„  %1 [%2], í•¨ëŒ€: %3</t>
    <t id="31201">Galaxy-Miner: ëª¨í•­ ìŠ¤í…Œì´ì…˜ ë˜ëŠ” ëª¨í•­ ìœ„ì¹˜ë¥¼ ì„¤ì •í•˜ì‹­ì‹œì˜¤.</t>
    <t id="31130">í•„ìš”í•œ ìœ í˜•(ê³ ì²´/ê´‘ì„ ë˜ëŠ” ì•¡ì²´/ê°€ìŠ¤)ì´ ë–¨ì–´ì¡Œì„ ë•Œ ì±„êµ´ì„ ì´ êµ¬ë§¤í•˜ëŠ” ìˆ˜ì§‘(ì±„êµ´) ë“œë¡ ì˜ ìˆ˜ìž…ë‹ˆë‹¤. êµ¬ë§¤ëŠ” ì„ ë°•ì— í•´ë‹¹ ìœ í˜•ì˜ ìˆ˜ì§‘ ë“œë¡ ì´ í•˜ë‚˜ë„ ì—†ì„ ë•Œë§Œ(ê°œìˆ˜ = 0) íŠ¸ë¦¬ê±°ë©ë‹ˆë‹¤. ì ì–´ë„ í•˜ë‚˜ë¥¼ ê°€ì§„ ì±„êµ´ì„ ì€ ë³´ì¶©ë˜ê±°ë‚˜ ë‹¤ì‹œ êµ¬ë§¤ë˜ì§€ ì•Šìœ¼ë©° ê¸°ì¡´ ë“œë¡ ì€ ìœ ì§€ë©ë‹ˆë‹¤. ì„ ë°•ì˜ ìœ ë‹› ë² ì´ ìš©ëŸ‰ìœ¼ë¡œ ì œí•œë©ë‹ˆë‹¤. ìˆ˜ì§‘ ë“œë¡  ìžë™ êµ¬ë§¤ë¥¼ ë¹„í™œì„±í™”í•˜ê³  ë“œë¡ ì„ ìˆ˜ë™ìœ¼ë¡œ ê´€ë¦¬í•˜ë ¤ë©´ 0ìœ¼ë¡œ ì„¤ì •í•˜ì„¸ìš”. ê¸°ë³¸ê°’ 5ëŠ” ì •ìƒì ì¸ ì±„êµ´ ì†ë„ë¥¼ ìœ„í•œ ì „ì²´ ë“œë¡  ì„¸íŠ¸ìž…ë‹ˆë‹¤.</t>
    <t id="31129">ê´‘ë¶€ê°€ ìž¬ìž…ê³  ì—¬í–‰ë‹¹ êµ¬ë§¤í•˜ëŠ” ìžì› ì¡°ì‚¬ ìˆ˜ìž…ë‹ˆë‹¤. êµ¬ë§¤ëŠ” ë°°í¬í•  ë•Œë§ˆë‹¤ê°€ ì•„ë‹ˆë¼ ì„ ë°•ì— í”„ë¡œë¸Œê°€ ë¶€ì¡±í•  ë•Œë§Œ(ê°œìˆ˜ = 0) íŠ¸ë¦¬ê±°ë©ë‹ˆë‹¤. ì´ë ‡ê²Œ í•˜ë©´ ì±„êµ´ìžëŠ” ê° ë°°í¬ í›„ ìš°íšŒí•˜ëŠ” ëŒ€ì‹  ê³µê¸‰ ì‹¤í–‰ ì‚¬ì´ì— ì „ì²´ í”„ë¡œë¸Œ ë¡œë“œë¥¼ ì‹¤í–‰í•©ë‹ˆë‹¤. í•¨ì„ ì˜ ì´ ë°°ì¹˜ ê°€ëŠ¥ ìš©ëŸ‰(ìœ„ì„±/ê¸°ë¢° ë“±ê³¼ ê³µìœ )ìœ¼ë¡œ ì œí•œë©ë‹ˆë‹¤. ë¬´ë£Œ ë°°í¬ ê°€ëŠ¥ ê³µê°„ë³´ë‹¤ í° ìŠ¬ë¼ì´ë” ê°’ì€ "ì í•©í•œ í¬ê¸° ì±„ìš°ê¸°"ë¡œ ìš°ì•„í•˜ê²Œ ì €í•˜ë©ë‹ˆë‹¤. Auto Deploy ë¦¬ì†ŒìŠ¤ í”„ë¡œë¸Œê°€ í™œì„±í™”ëœ ê²½ìš°ì—ë§Œ ì ìš©ë©ë‹ˆë‹¤. ë™ì¼í•œ ì„¤ì •ì€ ê´‘ì‚° ë¶€ë¬¸ì—ì„œ ê¸°íšŒì£¼ì˜ì  í”„ë¡œë¸Œ ë°°í¬ì™€ ì˜¤ëž˜ëœ í”„ë¡œë¸Œ(ë°”êµ¬ë‹ˆ ê´€ë ¨ ë¦¬ì†ŒìŠ¤ê°€ ì—†ëŠ” ë¶€ë¬¸ì˜ í”„ë¡œë¸Œ) ìˆ˜ì§‘ì„ ìœ ë„í•©ë‹ˆë‹¤.</t>
    <t id="3226">%1 ì‚¬ë ¹ê´€ë‹˜,\n\nì €ëŠ” %2ì— ì •ë°•í–ˆìœ¼ë©° ë¬´ì—­ ì•„ì¹´ë°ë¯¸ ë“±ë¡ ê¸°ê´€ì—ì„œ "%3" í”„ë¡œê·¸ëž¨ ë“±ë¡ì„ í™•ì¸í–ˆìŠµë‹ˆë‹¤. ì°¨ëŸ‰ ê³„ì¢Œì—ì„œ ê°•ì¢Œ ìˆ˜ì—…ë£Œë¡œ %4 Crì´ ì¸ì¶œë˜ì—ˆìœ¼ë©° ì €ëŠ” ê·¸ íˆ¬ìžë¥¼ ê°€ë³ê²Œ ì—¬ê¸°ì§€ ì•ŠìŠµë‹ˆë‹¤.\n\nì´ê²ƒì€ ì¼ìƒì ì¸ ì¸ì¦ì´ ì•„ë‹™ë‹ˆë‹¤. í•™ì›ì˜ ê°•ì‚¬ëŠ” ë² í…Œëž‘ ìƒì¸ì´ìž ì»¨ì†Œì‹œì—„ í˜‘ìƒê°€ì´ë©°, ì´ê³³ì˜ ì»¤ë¦¬í˜ëŸ¼ì€ í‘œì¤€ ìŠ¹ê¸‰ ì‹œí—˜ë³´ë‹¤ í›¨ì”¬ ê¹Œë‹¤ë¡­ìŠµë‹ˆë‹¤. ë‹¤ìŒ %5ë¶„ ë™ì•ˆ ì €ëŠ” ê³ ê¸‰ ê±°ëž˜ í”„ë¡œí† ì½œ, ì••ë ¥ì´ ê°€í•´ì§€ëŠ” ì‹œìž¥ ë¶„ì„, ê²¬ìŠµìƒê³¼ ë§ˆìŠ¤í„°ë¥¼ ë¶„ë¦¬í•˜ëŠ” í˜‘ìƒ ì „ìˆ ì— ëŒ€í•œ ì§‘ì¤‘ì ì¸ êµìœ¡ì„ ë°›ê²Œ ë  ê²ƒìž…ë‹ˆë‹¤.\n\nìµœì¢… ì‹œí—˜ì´ ì™„ë£Œë˜ê³  ë„í‚¹ì´ í•´ì œë˜ë©´ ì €ëŠ” "%3"ì˜ ì§í•¨ì„ ê°–ê³  ì œê°€ ë°°ìš´ ëª¨ë“  ê²ƒì„ ê±°ëž˜ ìž‘ì—…ì— ë‹¤ì‹œ ì ìš©í•  ê²ƒìž…ë‹ˆë‹¤. ì €ëŠ” ì´ ê¸°íšŒë¥¼ ë‹¨ í•œ í‘¼ë„ ë‚­ë¹„í•˜ì§€ ì•Šì„ ê²ƒìž…ë‹ˆë‹¤.\n\nê°ì‚¬ì™€ ê²°ë‹¨ì„ ë‹´ì•„,\n%6\n%7ì— íƒ‘ìŠ¹í•˜ì„¸ìš”.</t>
    <t id="9924">íŠ¸ë ˆì´ë”© ì•„ì¹´ë°ë¯¸ ê³¼ì •ì´ ì¤‘ë‹¨ë˜ì—ˆìŠµë‹ˆë‹¤. ì¡°ì¢…ì‚¬ %1ì€ ì•„ì¹´ë°ë¯¸ ë¶€ë‘ì—ì„œ %2 Cr ìˆ˜ìˆ˜ë£Œë¥¼ ê°ë‹¹í•  ìˆ˜ ì—†ìŠµë‹ˆë‹¤(%3 Cr ìžˆìŒ). ì½”ìŠ¤ê°€ ì·¨ì†Œë˜ê³  íŒŒì¼ëŸ¿ì´ ê±°ëž˜ë¥¼ ìž¬ê°œí•©ë‹ˆë‹¤.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="86">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">åœé å¹¶ç­‰å¾… (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">æœ€ç»ˆè€ƒè¯• (GalaxyTrader MK3)</t>
    <t id="10004">é£žè¡Œå‘˜äº¤æµä¼šåˆç‚¹</t>
    <t id="10005">[å·²å¼ƒç”¨] GalaxyTrader MK4 Supplyï¼ˆæ—§ç‰ˆï¼‰</t>
    <t id="10101">åœé åœ¨ç©ºé—´ç«™å¹¶ç­‰å¾…æŒ‡å®šæ—¶é—´</t>
    <t id="10102">å…·æœ‰æŠ€èƒ½è¿›é˜¶çš„è‡ªä¸»è´¸æ˜“</t>
    <t id="10103">åœ¨è®­ç»ƒè®¾æ–½å‚åŠ é£žè¡Œå‘˜è®¤è¯çš„æœ€ç»ˆè€ƒè¯•</t>
    <t id="10104">åœé åœ¨äº¤æ±‡ç«™è¿›è¡Œé£žè¡Œå‘˜äº¤æ¢</t>
    <t id="10105">ä½¿ç”¨ç¼“å­˜å’Œå®žæ—¶æœç´¢ä¸ºçŽ©å®¶ç«™æä¾›ä»¥ä¾›åº”ä¸ºä¸­å¿ƒçš„äº¤æ˜“ï¼ˆæ—§ç‰ˆï¼‰</t>
    <t id="10201">ä»Ž %s è´­ä¹° %s</t>
    <t id="10202">å‘ %s å‡ºå”® %s</t>
    <t id="10203">ä¸Ž %s äº¤æ˜“</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">å…·æœ‰XPè¿›é˜¶å’Œèˆ°é˜Ÿåè°ƒçš„é«˜çº§è´¸æ˜“ç³»ç»Ÿ</t>
    <t id="1002">åŸºåœ°</t>
    <t id="1003">ä½¿ç”¨é¢„è®¾</t>
    <t id="1004">äº¤æ˜“æ‰€æœ‰å•†å“</t>
    <t id="1005">äº¤æ˜“åˆæ³•å•†å“</t>
    <t id="1006">äº¤æ˜“éžæ³•å•†å“</t>
    <t id="1007">å¯ç”¨XPè¿›é˜¶</t>
    <t id="1008">å¯ç”¨èˆ°é˜Ÿåè°ƒ</t>
    <t id="1009">å¯ç”¨å¸‚åœºåˆ†æž</t>
    <t id="1010">å¯ç”¨é¢†åœ°ç®¡ç†</t>
    <t id="1011">å…è®¸éžæ³•å•†å“</t>
    <t id="1012">æ—¥å¿—æ¡ç›®</t>
    <t id="1013">é£Žé™©å®¹å¿åº¦</t>
    <t id="1014">ä¼˜å…ˆçŽ©å®¶ç©ºé—´ç«™</t>
    <t id="1015">è‡ªåŠ¨å•†å“</t>
    <t id="1016">è·ç¦»æƒ©ç½š %</t>
    <t id="1017">é€šçŸ¥çº§åˆ«</t>
    <t id="1018">èˆ°é˜Ÿåè°ƒ</t>
    <t id="1019">è´§èˆ±å¡«å……ç›®æ ‡ %</t>
    <t id="1050">å¸‚åœºæ›´æ–°é¢‘çŽ‡</t>
    <t id="1051">è´¸æ˜“è¯„ä¼°æ—¥å¿—</t>
    <t id="1052">æ‰‡åŒºç™½åå•</t>
    <t id="1054">å¿½ç•¥èˆªæ¯/è¾…åŠ©èˆ°</t>
    <t id="1056">å¿½ç•¥å»ºé€ å­˜å‚¨</t>
    <t id="1058">å¿½ç•¥äº¤æ˜“è§„åˆ™</t>
    <t id="1060">å¿½ç•¥ MK1 æä¾›çš„ç”µå°</t>
    <t id="1063">å¼€å‘ä¸­</t>
    <t id="1064">ä¼˜å…ˆå•†å“</t>
    <t id="1065">ä¼˜å…ˆåˆ†æ•° %</t>
    <t id="1066">åœ¨è´¸æ˜“è®¡åˆ†ä¸­å—é’ççš„å•†å“ã€‚ä»–ä»¬çš„åˆ†æ•°ä¹˜ä»¥ä¼˜å…ˆåˆ†æ•°ï¼…ã€‚</t>
    <t id="1067">ä¼˜å…ˆå•†å“çš„åˆ†æ•°ä¹˜æ•°ï¼š100%=æ­£å¸¸ï¼Œ150%=+50%%ï¼Œ200%=2xï¼Œ300%=3xã€‚æœ€åŽåº”ç”¨ã€‚</t>
    <t id="1068">â”€â”€ ä¼˜å…ˆå•†å“è¿‡æ»¤å™¨ â”€â”€</t>
    <t id="1069">å•†å“ï¼ˆæ‰‹åŠ¨ï¼‰</t>
    <t id="1070">éžæ³•è·¯ç”±è¿‡æ»¤å™¨</t>
    <t id="1072">åªä¸ºå®¶åº­æœåŠ¡</t>
    <t id="1073">çŽ©å®¶ä¾›åº”å•†ä¼˜å…ˆçº§</t>
    <t id="1074">æ´¾ç³»ä¾›åº”å•†ä¼˜å…ˆçº§</t>
    <t id="1075">åŒ…æ‹¬æž„å»ºå­˜å‚¨</t>
    <t id="1076">åŒ…å«èµ„æº</t>
    <t id="1077">åŒ…æ‹¬ä¸­é—´ä½“</t>
    <t id="1078">åŒ…æ‹¬å•†ä¸šè½¯ä»¶</t>
    <t id="1080">æ¯ä¸ªå‘¨æœŸæœ€å¤§äº¤æ˜“æ•°</t>
    <t id="1081">å›žæº¯å®¹å·®</t>
    <t id="1082">æœ€å°è´§ç‰©ä½¿ç”¨ç™¾åˆ†æ¯”</t>
    <t id="1083">çŽ©å®¶è´­ä¹°ä¿®æ”¹%</t>
    <t id="1085">åˆ†é…è‡³ä¸»ç«™</t>
    <t id="1086">è¦†ç›–è·ç¦»</t>
    <t id="1088">æ»¡è¶³éœ€æ±‚è¦†ç›–çš„ç¦»å®¶æœ€å¤§è·³è·ƒè·ç¦»</t>
    <t id="1090">å°†è´¸æ˜“å“ç±»å•†å“çº³å…¥éœ€æ±‚/ä¾›åº”åŒ¹é…ä¸­</t>
    <t id="1091">åœ¨ä»…è®¡åˆ†è®¡ç®—ä¸­åº”ç”¨äºŽçŽ©å®¶æ‹¥æœ‰çš„ä¾›åº”å•†å®šä»·çš„ä¿®æ”¹å™¨</t>
    <t id="1092">å¿½ç•¥çŽ©å®¶å®šä»·</t>
    <t id="1093">å¯ç”¨åŽï¼šå§‹ç»ˆä»ŽçŽ©å®¶æ‹¥æœ‰çš„ç«™ç‚¹è´­ä¹°ï¼Œæ— è®ºå…¶è®¾å®šçš„å”®ä»·å¦‚ä½•ï¼Œå¹¶ä¸”ä»…å‡ºå”®ç»™ NPC æ´¾ç³»ã€‚å¯¹äºŽæ¸…ç†æ‚¨è‡ªå·±çš„ç«™ç‚¹ä¸­çš„å¤šä½™åº“å­˜å¾ˆæœ‰ç”¨ã€‚</t>
    <t id="1094">å·²å±è”½ç©ºé—´ç«™</t>
    <t id="1095">æ­¤å¤„é€‰æ‹©çš„ç©ºé—´ç«™å°†ä»Ž MK3 äº¤æ˜“ä¸­æŽ’é™¤ã€‚è´¸æ˜“èˆ¹ä¸ä¼šä»Žè¿™äº›ç©ºé—´ç«™è´­ä¹°ï¼Œä¹Ÿä¸ä¼šå‘å…¶å‡ºå”®ã€‚</t>
    <t id="1096">é—²ç½®åœé </t>
    <t id="1097">å¯ç”¨åŽï¼Œåå¤æ‰¾ä¸åˆ°å·¥ä½œçš„èˆ°èˆ¹ä¼šåœé åœ¨å…¶æ¯ç«™æˆ–æ¯æ˜ŸåŒºã€‚æ˜ŸåŒºåœé ä¼šä¼˜å…ˆé€‰æ‹©çŽ©å®¶ç©ºé—´ç«™ï¼Œå…¶æ¬¡æ˜¯å‹å¥½ç©ºé—´ç«™ã€‚åœé é‡Šæ”¾æ—¶é—´åœ¨å…¨å±€è®¾ç½®ä¸­é…ç½®ï¼ˆ0 = ä¿æŒåœé ç›´åˆ°æ‰¾åˆ°å·¥ä½œï¼‰ã€‚</t>
    <t id="1098">è‡ªåŠ¨ç¼©æ”¾</t>
    <t id="1099">å¯ç”¨åŽï¼Œåœ¨å¼ºåˆ¶è®­ç»ƒæˆ–è´¸æ˜“å­¦é™¢å®ŒæˆåŽï¼Œè·³è·ƒè·ç¦»æ»‘å—ä¼šè®¾ç½®ä¸ºé£žè¡Œå‘˜å…è®¸çš„æœ€å¤§èŒƒå›´ã€‚å–æ¶ˆå‹¾é€‰å¯æ‰‹åŠ¨è®¾ç½®è·ç¦»ã€‚</t>
    <t id="11001">å»ºé€ ä»“å‚¨ä¼˜å…ˆçº§</t>
    <t id="11002">ç©ºé—´ç«™ä¼˜å…ˆçº§</t>
    <t id="11003">è¾…åŠ©èˆ°èˆ¹ä¼˜å…ˆçº§</t>
    <t id="11004">èˆªæ¯ä¼˜å…ˆçº§</t>
    <t id="11005">0 = ç¦ç”¨ã€‚1-10 = åˆ†æ•°å€çŽ‡ï¼ˆ10 = æœ€å¼ºåå‘ï¼‰ã€‚æœ€ç»ˆåˆ†æ•° = ä¾›ç»™åˆ†æ•° Ã— å€çŽ‡ã€‚</t>
    <t id="11006">1 = æ— é¢å¤–åˆ†æ•°ï¼ˆä¼˜å…ˆè´§ç‰©åˆ—è¡¨ä¸å˜ï¼‰ã€‚2-10 = å½“äº¤æ˜“è´§ç‰©åœ¨ä¼˜å…ˆåˆ—è¡¨ä¸­æ—¶ï¼Œå¢žåŠ ï¼ˆå€çŽ‡âˆ’1ï¼‰Ã— åŸºç¡€ä¾›ç»™åˆ†æ•°ã€‚å åŠ åœ¨ç±»åž‹åˆ†æ•°ä¹‹ä¸Šã€‚</t>
    <t id="11007">ä¼˜å…ˆè´§ç‰©åŠ æˆ</t>
    <t id="11008">%1ï¼šæ‰€æœ‰äº¤ä»˜ç›®æ ‡ä¼˜å…ˆçº§æ»‘å—å‡è®¾ä¸º 0 - æ­¤å‘½ä»¤æ²¡æœ‰äº¤ä»˜ç›®æ ‡ã€‚è¯·å¯ç”¨è‡³å°‘ä¸€ä¸ªç±»åˆ«ï¼ˆå»ºé€ ä»“å‚¨ã€ç©ºé—´ç«™ã€è¾…åŠ©èˆ°èˆ¹æˆ–èˆªæ¯ï¼‰ä»¥æ¢å¤è¡¥ç»™è¿è¡Œã€‚</t>
    <t id="7001">[æ™‹å‡]</t>
    <t id="7002">[è®­ç»ƒ]</t>
    <t id="7008">[åŽå¤‡]</t>
    <t id="7009">[éš”ç¦»]</t>
    <t id="7003">[ç»´ä¿®]</t>
    <t id="7004">[è¡¥ç»™]</t>
    <t id="7005">[ç»´æŠ¤]</t>
    <t id="7006">[é‡æ–°è·¯ç”±]</t>
    <t id="7007">[è®¸å¯]</t>
    <t id="1020">é€‰æ‹©è´¸æ˜“å•†è¿è¥çš„åŸºåœ°æ‰‡åŒºæˆ–ç©ºé—´ç«™</t>
    <t id="1021">è´­ä¹°å•†å“æ—¶çš„æœ€å¤§è·³è·ƒé—¨è·ç¦»ï¼ˆå—é£žè¡Œå‘˜æŠ€èƒ½é™åˆ¶ï¼‰</t>
    <t id="1022">å‡ºå”®å•†å“æ—¶çš„æœ€å¤§è·³è·ƒé—¨è·ç¦»ï¼ˆå—é£žè¡Œå‘˜æŠ€èƒ½é™åˆ¶ï¼‰</t>
    <t id="1023">æ ¹æ®ç±»åˆ«è‡ªåŠ¨é€‰æ‹©åˆé€‚å•†å“</t>
    <t id="1024">æ‰‹åŠ¨é€‰æ‹©ç‰¹å®šè´¸æ˜“å•†å“</t>
    <t id="1025">å…è®¸äº¤æ˜“è¿ç¦å“å’Œéžæ³•è´§ç‰©</t>
    <t id="1026">å®‰å…¨å®¹å¿åº¦ï¼š0.0=ä»…å®‰å…¨æ‰‡åŒºï¼Œ1.0=æŽ¥å—æ‰€æœ‰é£Žé™©</t>
    <t id="1027">é€šè¿‡è´¸æ˜“ç»éªŒæå‡é£žè¡Œå‘˜æŠ€èƒ½</t>
    <t id="1028">éœ€è¦æ—¶è‡ªåŠ¨æ´¾é£é£žè¡Œå‘˜è¿›è¡Œè®­ç»ƒ</t>
    <t id="1029">åè°ƒå¤šè‰˜è´¸æ˜“èˆ¹ä»¥é¿å…å†²çª</t>
    <t id="1030">å•†å“ç„¦ç‚¹ï¼š0=å¹³è¡¡ï¼Œ1=é«˜çº§ï¼Œ2=åŸºæœ¬éœ€æ±‚ï¼Œ3=éžæ³•ï¼Œ4=å¤§å®—å•†å“</t>
    <t id="1031">è´¸æ˜“åŒºåŸŸï¼š0=å¹³è¡¡ï¼Œ1=åŸºåœ°ç„¦ç‚¹ï¼Œ2=è‡ªç”±æ¼«æ¸¸</t>
    <t id="1032">é€šçŸ¥çº§åˆ«ï¼š0=æœ€å°‘ï¼Œ1=æ­£å¸¸ï¼Œ2=è¯¦ç»†æ¶ˆæ¯</t>
    <t id="1033">ä¼˜å…ˆé”€å”®å‰çš„ç›®æ ‡è´§èˆ±åˆ©ç”¨çŽ‡ç™¾åˆ†æ¯”</t>
    <t id="1034">å¸‚åœºæ•°æ®å’Œä»·æ ¼ä¿¡æ¯æ›´æ–°é¢‘çŽ‡</t>
    <t id="1035">è°ƒè¯•è¾“å‡ºçº§åˆ«ï¼š0=æ— ï¼Œ1=åŸºæœ¬ï¼Œ2=è¯¦ç»†æ—¥å¿—</t>
    <t id="1036">ä¸Žèˆ°é˜Ÿåˆ†äº«æœ‰åˆ©å¯å›¾çš„è´¸æ˜“è·¯çº¿ï¼ˆç¼“å­˜ä»¥ä¾¿å¿«é€Ÿè®¿é—®ï¼‰</t>
    <t id="1037">ç¼“å­˜äº¤æ˜“å¹¶ä¸Žèˆ°é˜Ÿåˆ†äº«æ‰€éœ€çš„æœ€å°åˆ©æ¶¦</t>
    <t id="1038">ç¼“å­˜çš„è´¸æ˜“è·¯çº¿å¤±æ•ˆå‰å…è®¸çš„æœ€å¤§åˆ©æ¶¦ä¸‹é™</t>
    <t id="1039">ç¼“å­˜çš„è´¸æ˜“è·¯çº¿åœ¨è¿‡æœŸå‰ä¿æŒæœ‰æ•ˆçš„æ—¶é—´</t>
    <t id="1040">å¯ç”¨å•ä¸ªè´¸æ˜“è¯„ä¼°å’Œæ‹’ç»çš„è¯¦ç»†æ—¥å¿—ï¼ˆå¯èƒ½éžå¸¸è¯¦ç»†ï¼‰</t>
    <t id="1041">å¯ç”¨æ¯ç¬”äº¤æ˜“çš„æ—¥å¿—æ¡ç›®å’Œæ²‰æµ¸å¼è®­ç»ƒæ¶ˆæ¯ï¼ˆTaterTraderé£Žæ ¼ï¼‰</t>
    <t id="1053">æ­¤åˆ—è¡¨ä¸­çš„æ‰‡åŒºè¢«æŽ’é™¤åœ¨é»‘åå•ä¹‹å¤–ï¼ˆå§‹ç»ˆå…è®¸ï¼‰</t>
    <t id="1055">ä»Žè´¸æ˜“ä¸­æŽ’é™¤èˆªæ¯å’Œè¾…åŠ©èˆ°</t>
    <t id="1057">ä»Žè´¸æ˜“ä¸­æŽ’é™¤å»ºé€ å­˜å‚¨èˆ¹</t>
    <t id="1059">åœ¨æœç´¢æŠ¥ä»·æ—¶å¿½ç•¥ç©ºé—´ç«™äº¤æ˜“è§„åˆ™ï¼ˆé«˜çº§ï¼›å¯èƒ½é€‰æ‹©é€šå¸¸è¢«é˜»æ­¢çš„æŠ¥ä»·ï¼‰</t>
    <t id="1061">è·³è¿‡å…·æœ‰åˆ†é…äº†ä¾›åº”æ¨¡å¼çš„ MK1 äº¤æ˜“å‘˜çš„çŽ©å®¶ç«™</t>
    <t id="1062">æ¶‰åŠè‡ªå·±ç©ºé—´ç«™çš„è´¸æ˜“è·¯çº¿èŽ·å¾—è¯„åˆ†åŠ æˆï¼ˆ10%åŠ æˆï¼‰</t>
    <t id="1071">å¯ç”¨â€œå…è®¸éžæ³•å•†å“â€åŽï¼Œä»…åœ¨è·³è·ƒè·¯å¾„ä¸Šçš„æ‰€æœ‰éƒ¨é—¨ï¼ˆè´­ä¹°ã€é”€å”®å’Œä¸­é—´éƒ¨é—¨ï¼‰åˆæ³•çš„æƒ…å†µä¸‹äº¤æ˜“éžæ³•å•†å“ã€‚</t>
    <t id="1087">ä¾›åº”å•†é‡‡è´­æœç´¢ç¦»å®¶çš„æœ€å¤§è·³è·ƒè·ç¦»</t>
    <t id="1089">ç¦ç”¨æ—¶ï¼Œèˆ¹èˆ¶å¯ä»¥æŒ‰ç´§æ€¥ä¼˜å…ˆçº§è€Œä¸æ˜¯ä»…åœ¨å®¶æ¨¡å¼å‘è¦†ç›–åŒºåŸŸå†…çš„ç”µå°æä¾›è¡¥ç»™</t>
    <t id="2000">%s èŽ·å¾—äº† %s XPï¼</t>
    <t id="2001">%s å‡çº§äº†ï¼æ–°ç­‰çº§ï¼š%s</t>
    <t id="2002">%s éœ€è¦è®­ç»ƒï¼è¯·æ´¾é£åˆ°æœ€è¿‘çš„èˆ¹åŽ‚æˆ–è´¸æ˜“ç«™ã€‚</t>
    <t id="2003">%s å·²åœ¨ %s å¼€å§‹è®­ç»ƒ</t>
    <t id="2004">%s å·²å®Œæˆè®­ç»ƒï¼ŒçŽ°å·²èŽ·å¾— %s çº§è®¤è¯ï¼</t>
    <t id="2005">%s åœ¨è®­ç»ƒåŽè¾¾åˆ°æŠ€èƒ½ç­‰çº§ %sï¼%s å¤„å·²è§£é” XP è¿›åº¦ã€‚</t>
    <t id="2006">%s é€šè¿‡ %s äº¤æ˜“è¾¾åˆ°æŠ€èƒ½ç­‰çº§ %sï¼</t>
    <t id="2007">%s å®Œæˆäº†ç­‰çº§ %s è®­ç»ƒï¼%s å¤„å·²è§£é” XP è¿›åº¦ã€‚</t>
    <t id="3000">%s å®Œæˆäº†ä¸€ç¬”äº¤æ˜“ï¼åˆ©æ¶¦ï¼š%s Cr</t>
    <t id="3001">%s æ­£åœ¨åˆ†æžå¸‚åœºçŠ¶å†µ...</t>
    <t id="3002">%s æ‰¾åˆ°äº†ä¸€æ¡æœ‰åˆ©å¯å›¾çš„è´¸æ˜“è·¯çº¿ï¼</t>
    <t id="3003">%s æ²¡æœ‰å¯ç”¨çš„æœ‰åˆ©å¯å›¾è´¸æ˜“è·¯çº¿</t>
    <t id="3100">å°† %1 %2 çš„è´§ç‰©å‡ºå”®è‡³ %3ï¼Œä»·æ ¼ä¸º %4ã€‚æˆ‘åº”è¯¥èƒ½èµšå– %5 çš„åˆ©æ¶¦ã€‚</t>
    <t id="3101">å°† %1 %2 çš„è´¸æ˜“è®¢å•åŠ å…¥é˜Ÿåˆ—ã€‚åœ¨ %3 ä»Ž %4 è´­ä¹°ï¼Œåœ¨ %5 å‘ %6 å‡ºå”®ã€‚æˆ‘åº”è¯¥èƒ½èµšå– %7 çš„åˆ©æ¶¦ã€‚</t>
    <t id="3102">ç©ºé—´ç«™è´¸æ˜“å•†ï¼šæ­£ä»Ž %3ï¼ˆ%5%%ï¼‰å‘ %4ï¼ˆ%6%%ï¼‰ä¾›åº” %1 %2ã€‚</t>
    <t id="3103">ç©ºé—´ç«™è´¸æ˜“å•†ï¼šå‘ %3 å‡ºå”® %1 %2ï¼Œå•ä»· %4ã€‚é¢„æœŸåˆ©æ¶¦ %5ã€‚</t>
    <t id="3104">%1 %2 çš„äº¤æ˜“æˆåŠŸå®Œæˆã€‚æ€»åˆ©æ¶¦ï¼š%3 ä¿¡ç”¨ç‚¹ã€‚</t>
    <t id="3105">è´¸æ˜“è·¯çº¿å·²ç¼“å­˜ï¼š%1 %2 ä»Ž %3 åˆ° %4ï¼ˆåˆ©æ¶¦ï¼š%5 Crï¼‰</t>
    <t id="3106">\næ­¤äº¤æ˜“å‰çš„æ€»ä¼°è®¡ç»ˆèº«åˆ©æ¶¦ï¼š%1 Crã€‚</t>
    <t id="3120">è¯•ç‚¹è½¬ç§»å¯åŠ¨</t>
    <t id="3121">ä¼ è¾“åè®®å·²ç¡®è®¤ã€‚ %1 (%2) å’Œ %3 (%4) æ­£å‰å¾€ %5 (%6) åœé å¹¶äº¤æ¢æŒ‡æŒ¥åº§ä½ã€‚</t>
    <t id="3200">æŒ‡æŒ¥å®˜æ‚¨å¥½%1ï¼Œ\n\næˆ‘å·²ç»èŽ·å¾—äº†è¶³å¤Ÿçš„ç»éªŒæ¥å‚åŠ â€œ%2â€å¤´è¡”çš„è®¤è¯è€ƒè¯•ã€‚è€ƒè¯•å¤§çº¦éœ€è¦ %3 åˆ†é’Ÿï¼Œæ—¶é—´ä¸º %4.\n\nè¿™æ˜¯æˆ‘èŒä¸šå‘å±•ä¸­çš„ä¸€ä¸ªé‡è¦é‡Œç¨‹ç¢‘ã€‚è¯¥è€ƒè¯•å°†æµ‹è¯•æˆ‘å¯¹é«˜çº§äº¤æ˜“åè®®ã€å¸‚åœºåˆ†æžå’Œè½¦é˜Ÿåè°ƒç¨‹åºçš„äº†è§£ã€‚\n\næˆ‘å¯¹è‡ªå·±çš„èƒ½åŠ›å……æ»¡ä¿¡å¿ƒï¼Œå¹¶å¾ˆé«˜å…´è¯æ˜Žè‡ªå·±å€¼å¾—è¿™ä¸€è¿›æ­¥ã€‚ç¥æˆ‘å¥½è¿ï¼\n\nè°¨è‡´\n%5\nç™»ä¸Š%6</t>
    <t id="3201">æŒ‡æŒ¥å®˜ %1ï¼Œ\n\nå¥½æ¶ˆæ¯ï¼æˆ‘æˆåŠŸå®Œæˆäº†è®¤è¯è€ƒè¯•å¹¶èŽ·å¾—äº† "%2" å¤´è¡”ï¼\n\nè€ƒè¯•æ¶µç›–äº†é«˜çº§è´¸æ˜“ç­–ç•¥ã€é£Žé™©è¯„ä¼°åè®®å’Œèˆ°é˜Ÿåè°ƒç¨‹åºã€‚æˆ‘å¾ˆé«˜å…´åœ°æŠ¥å‘Šï¼Œæˆ‘ä»¥ä¼˜å¼‚æˆç»©é€šè¿‡äº†è€ƒè¯•ã€‚\n\næˆ‘çŽ°åœ¨æœ‰èµ„æ ¼å¤„ç†æ›´å¤æ‚çš„è´¸æ˜“æ“ä½œï¼Œå¹¶æœŸå¾…ä¸ºæˆ‘ä»¬çš„èˆ°é˜ŸæˆåŠŸåšå‡ºæ›´å¤§è´¡çŒ®ã€‚æ„Ÿè°¢æ‚¨å¯¹æˆ‘ä¸“ä¸šå‘å±•çš„æŠ•èµ„ã€‚\n\nä»¥æ›´æ–°çš„å¥‰çŒ®ç²¾ç¥žï¼Œ\n%3\nè®¤è¯ %2\nåœ¨ %4 ä¸Š</t>
    <t id="3202">æŒ‡æŒ¥å®˜ %1ï¼Œ\n\næˆ‘å¾ˆé—æ†¾åœ°é€šçŸ¥æ‚¨ï¼Œç”±äºŽæ“ä½œè¦æ±‚ï¼Œæˆ‘çš„è®¤è¯è€ƒè¯•è¢«ä¸­æ–­ã€‚æˆ‘éœ€è¦åœ¨æƒ…å†µå…è®¸æ—¶é‡æ–°å®‰æŽ’ã€‚\n\næˆ‘ä»ç„¶è‡´åŠ›äºŽæå‡è‡ªå·±çš„æŠ€èƒ½ï¼Œå¹¶ä¼šåœ¨èƒ½å¤Ÿæ¢å¤è€ƒè¯•è¿‡ç¨‹æ—¶é€šçŸ¥æ‚¨ã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\n%2\nåœ¨ %3 ä¸Š</t>
    <t id="3203">æŒ‡æŒ¥å®˜ %1ï¼Œ\n\næˆ‘ç›®å‰æ­£åœ¨å‰å¾€ %2 å‚åŠ è®¤è¯è€ƒè¯•ã€‚è¿™æ®µæ—…ç¨‹ç»™äº†æˆ‘æ—¶é—´å¤ä¹ æ‰€å­¦çŸ¥è¯†ï¼Œå¹¶ä¸ºèŒä¸šç”Ÿæ¶¯ä¸­çš„è¿™ä¸€é‡è¦æ­¥éª¤åšå¥½å¿ƒç†å‡†å¤‡ã€‚\n\né¢„è®¡åˆ°è¾¾æ—¶é—´ï¼š%3 åˆ†é’Ÿ\nè€ƒè¯•æŒç»­æ—¶é—´ï¼š%4 åˆ†é’Ÿ\n\næˆ‘æ„Ÿè°¢æ‚¨å¯¹æˆ‘èƒ½åŠ›çš„ä¿¡ä»»ä»¥åŠæ™‹å‡çš„æœºä¼šã€‚\n\nä»¥å†³å¿ƒï¼Œ\n%5\nåœ¨ %6 ä¸Š</t>
    <t id="3204">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘åœ¨ç³»ç»Ÿæ£€æŸ¥æ—¶å‘çŽ°è´§èˆ±ä¸­æœ‰è´§ç‰©ã€‚åœ¨æˆ‘å¼€å§‹æ­£å¸¸è´¸æ˜“æ“ä½œä¹‹å‰ï¼Œæˆ‘éœ€è¦å‡ºå”®è¿™äº›å•†å“ã€‚\n\næˆ‘æ­£åœ¨ä½¿ç”¨æˆ‘ä»¬çš„è´¸æ˜“æœç´¢æ¥æ‰¾åˆ°æœ€ä½³ä¹°å®¶å¹¶å®‰å…¨åœ°å¸è½½è¿™äº›è´§ç‰©ã€‚ä¸€æ—¦æˆ‘çš„è´§èˆ±æ¸…ç©ºï¼Œæˆ‘å°†ç»§ç»­è¿›è¡Œè‡ªåŠ¨åŒ–è´¸æ˜“ã€‚\n\nçŠ¶æ€ï¼šæ­£åœ¨æœç´¢æœ€ä½³é”€å”®åœ°ç‚¹\n\nä»¥å‹¤å‹‰ï¼Œ\nåœ¨ %1 ä¸Š</t>
    <t id="3205">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘çš„èˆ¹ä½“å®Œæ•´æ€§å·²é™è‡³ %1%%ï¼ˆé˜ˆå€¼ï¼š%2%%ï¼‰ã€‚ä½œä¸º %3 çº§é£žè¡Œå‘˜ï¼Œæˆ‘å·²è¢«æŽˆæƒè¯·æ±‚è‡ªåŠ¨ç»´ä¿®æœåŠ¡ã€‚\n\næˆ‘æ­£åœ¨å‰å¾€ %4 è¿›è¡Œç»´ä¿®å·¥ä½œã€‚ä¼°è®¡è´¹ç”¨ä¸º %5 Crï¼Œè¿™åœ¨æˆ‘ä»¬çš„é¢„ç®—èŒƒå›´å†…ã€‚\n\nä¸€æ—¦ç»´ä¿®å®Œæˆï¼Œæˆ‘å°†ä»¥å®Œæ•´çš„ç»“æž„å®Œæ•´æ€§æ¢å¤è´¸æ˜“æ“ä½œã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nåœ¨ %6 ä¸Š</t>
    <t id="3206">æŒ‡æŒ¥å®˜ï¼Œ\n\nç´§æ€¥è´¢åŠ¡è­¦å‘Š\n\næˆ‘çš„èˆ¹ä½“å®Œæ•´æ€§å¤„äºŽ %1%% çš„ä¸´ç•ŒçŠ¶æ€ï¼ˆé˜ˆå€¼ï¼š%2%%ï¼‰ï¼Œä½†æˆ‘ä»¬å¯ç”¨çš„èµ„é‡‘ï¼ˆ%3 Crï¼‰ä¸è¶³ä»¥è¿›è¡Œå®Œæ•´ç»´ä¿®ï¼ˆä¼°è®¡è´¹ç”¨ï¼š%4 Crï¼‰ã€‚\n\næˆ‘æ­£åœ¨å‰å¾€ %5 ä½¿ç”¨æˆ‘ä»¬å¯ç”¨çš„èµ„é‡‘è¿›è¡Œéƒ¨åˆ†ç»´ä¿®ã€‚è¿™ä¸æ˜¯ç†æƒ³çš„è§£å†³æ–¹æ¡ˆï¼Œä½†ä¸ºäº†ç»´æŒæ“ä½œèƒ½åŠ›æ˜¯å¿…è¦çš„ã€‚\n\nè¯·è€ƒè™‘ä¸ºæœªæ¥çš„ç»´æŠ¤æ“ä½œåˆ†é…é¢å¤–èµ„é‡‘ã€‚\n\næ‹…å¿§ä½†åšå®šï¼Œ\nåœ¨ %6 ä¸Š</t>
    <t id="3207">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘çš„ %1 çº§è®¤è¯æŽˆæƒè‡ªåŠ¨è¡¥å……é˜²å¾¡è£…å¤‡ã€‚åœ¨æ£€æŸ¥æˆ‘çš„ç³»ç»ŸåŽï¼Œæˆ‘ç¡®å®šæˆ‘çš„å¯¹æŠ—æŽªæ–½å’Œå¯éƒ¨ç½²è®¾å¤‡ä½ŽäºŽæŽ¨èé˜ˆå€¼ã€‚\n\næˆ‘æ­£åœ¨å‰å¾€ %2 è¡¥å……æˆ‘çš„é˜²å¾¡è£…å¤‡ï¼š\nâ€¢ å¯¹æŠ—æŽªæ–½ï¼šè¡¥å……è‡³æœ€ä½³å®¹é‡\nâ€¢ é˜²å¾¡æ— äººæœºã€è´¸æ˜“æ— äººæœºã€æ¿€å…‰å¡”ï¼šåº”ç”¨å¹³è¡¡é…ç½®\n\nè¿™æ¬¡è¡¥å……ç¡®ä¿æˆ‘åœ¨ä¿æŒè´¸æ˜“æ•ˆçŽ‡çš„åŒæ—¶èŽ·å¾—æœ€ä½³çš„ç©ºé—´å¨èƒä¿æŠ¤ã€‚\n\nä»¥è­¦æƒ•ï¼Œ\nåœ¨ %3 ä¸Š</t>
    <t id="3212">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘çš„èˆ¹ä½“å®Œæ•´æ€§å·²é™è‡³ %1%%ï¼ˆé˜ˆå€¼ï¼š%2%%ï¼‰ï¼Œæˆ‘éœ€è¦ç»´ä¿®æœåŠ¡ã€‚ç„¶è€Œï¼Œ%3 æœ€è¿‘çš„ç»´ä¿®ç«™ç›®å‰ç”±äºŽæ‰‡åŒºæ—…è¡Œé™åˆ¶ï¼ˆé»‘åå•è·¯çº¿ï¼‰è€Œæ— æ³•åˆ°è¾¾ã€‚\n\nå°½ç®¡æœ‰è¿™ä¸€é™åˆ¶ï¼Œæˆ‘å°†ç»§ç»­è´¸æ˜“æ“ä½œã€‚ä¸€æ—¦å®‰å…¨è·¯çº¿å†æ¬¡å¯ç”¨ï¼Œæˆ‘å°†è‡ªåŠ¨å¯»æ±‚ç»´ä¿®æœåŠ¡ã€‚\n\næˆ‘å°†ç›‘æŽ§æƒ…å†µï¼Œå¹¶åœ¨ç»´ä¿®æˆä¸ºå¯èƒ½æ—¶é€šçŸ¥æ‚¨ã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nåœ¨ %4 ä¸Š</t>
    <t id="3213">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘çš„é˜²å¾¡è£…å¤‡éœ€è¦è¡¥å……ï¼Œä½† %1 æœ€è¿‘çš„è£…å¤‡ç«™ç›®å‰ç”±äºŽæ‰‡åŒºæ—…è¡Œé™åˆ¶ï¼ˆé»‘åå•è·¯çº¿ï¼‰è€Œæ— æ³•åˆ°è¾¾ã€‚\n\nå°½ç®¡æœ‰è¿™ä¸€é™åˆ¶ï¼Œæˆ‘å°†ç»§ç»­è´¸æ˜“æ“ä½œã€‚ä¸€æ—¦å®‰å…¨è·¯çº¿å†æ¬¡å¯ç”¨ï¼Œæˆ‘å°†è‡ªåŠ¨å¯»æ±‚è¡¥å……æœåŠ¡ã€‚\n\næˆ‘å°†ç›‘æŽ§æƒ…å†µï¼Œå¹¶åœ¨è¡¥å……æˆä¸ºå¯èƒ½æ—¶é€šçŸ¥æ‚¨ã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nåœ¨ %2 ä¸Š</t>
    <t id="3208">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘å·²ç»å®Œæˆäº†å¯¹ %1 åŠå‘¨è¾¹æ‰‡åŒºï¼ˆ%2 è·³è·ƒèŒƒå›´å†…ï¼Œæœ€å°åˆ©æ¶¦é˜ˆå€¼ï¼š%3 Crï¼‰çš„è¯¦å°½å¸‚åœºåˆ†æžï¼Œä½†é—æ†¾çš„æ˜¯æ²¡æœ‰æ‰¾åˆ°ç¬¦åˆæˆ‘ä»¬è¦æ±‚çš„æœ‰åˆ©å¯å›¾è´¸æ˜“æœºä¼šã€‚\n\nè´¸æ˜“åˆ†æžæŠ¥å‘Šï¼š\nè¯„ä¼°çš„æœºä¼šæ€»æ•°ï¼š%4\n\næ‹’ç»æ˜Žç»†ï¼š\n- åœé é™åˆ¶ï¼š%5 ç¬”äº¤æ˜“\n  ï¼ˆç©ºé—´ç«™ä¸å…è®¸æˆ‘çš„èˆ¹çº§ï¼‰\n- åˆ©æ¶¦ä¸è¶³ï¼š%6 ç¬”äº¤æ˜“\n  ï¼ˆä½ŽäºŽæœ€å°åˆ©æ¶¦é˜ˆå€¼ï¼‰\n- æ•°é‡ä¸è¶³ï¼š%7 ç¬”äº¤æ˜“\n  ï¼ˆé›¶æˆ–è´Ÿå¯äº¤æ˜“æ•°é‡ï¼‰\n- å®‰å…¨é™åˆ¶ï¼š%8 ç¬”äº¤æ˜“\n  ï¼ˆé»‘åå•ç©ºé—´ç«™æˆ–å±é™©æ‰‡åŒºï¼‰\n\nå»ºè®®ï¼š\n- è€ƒè™‘è°ƒæ•´åˆ©æ¶¦é˜ˆå€¼\n- æ‰©å¤§æœ€å¤§è´¸æ˜“è·ç¦»\n- å®¡æŸ¥æ‰‡åŒºé»‘åå•è®¾ç½®\n- ç­‰å¾…å¸‚åœºæ¡ä»¶æ”¹å–„\n\næˆ‘å°†ç»§ç»­ç›‘æŽ§å¸‚åœºï¼Œå¹¶åœ¨æœ‰åˆ©å¯å›¾çš„æœºä¼šå‡ºçŽ°æ—¶é€šçŸ¥æ‚¨ã€‚\n\nå¾…å‘½ä¸­ï¼Œ\nä¸ºæ‚¨æœåŠ¡</t>
    <t id="3209">æŒ‡æŒ¥å®˜ï¼Œ\n\nç´§æ€¥è·¯çº¿è­¦æŠ¥\n\næˆ‘çš„å¨èƒæƒ…æŠ¥ç³»ç»Ÿå·²æ£€æµ‹åˆ°æ‰‡åŒº %1ï¼ˆå¨èƒçº§åˆ« %2ï¼‰çŽ°åœ¨ä½äºŽæˆ‘è®¡åˆ’çš„è´¸æ˜“è·¯çº¿ä¸­ã€‚ä¸ºäº†èˆ¹èˆ¶å’Œèˆ¹å‘˜çš„å®‰å…¨ï¼Œæˆ‘ç«‹å³ä¸­æ­¢å½“å‰çš„è´¸æ˜“æ“ä½œã€‚\n\nå·²é‡‡å–çš„è¡ŒåŠ¨ï¼š\n- æ‰€æœ‰è´¸æ˜“è®¢å•å·²å–æ¶ˆ\n- è¿”å›žå®‰å…¨æ“ä½œæ¨¡å¼\n- å°†å¯»æ‰¾é¿å¼€å±é™©æ‰‡åŒºçš„æ›¿ä»£è´¸æ˜“è·¯çº¿\n- è´§ç‰©å¤„ç†ï¼šè‡ªåŠ¨ï¼ˆå¦‚éœ€è¦ï¼Œå°†åœ¨å®‰å…¨åœ°ç‚¹å‡ºå”®ä»»ä½•è´§ç‰©ï¼‰\n\nåŠ¨æ€é»‘åå•ç³»ç»Ÿå°†é˜»æ­¢æœªæ¥é€šè¿‡æ­¤æ‰‡åŒºçš„äº¤æ˜“ï¼Œç›´åˆ°å¨èƒè¢«æ¸…é™¤ã€‚\n\nå®‰å…¨æ˜¯æˆ‘çš„ç¬¬ä¸€è¦åŠ¡ã€‚\n\nä»¥è­¦æƒ•ï¼Œ\nåœ¨ %3 ä¸Š</t>
    <t id="3210">æŒ‡æŒ¥å®˜ï¼Œ\n\né€ƒç”Ÿè·¯çº¿å·²å¯åŠ¨\n\næˆ‘ç›®å‰åœ¨é»‘åå•æ‰‡åŒº %1ï¼Œå¹¶æ‰¾åˆ°äº†ä¸€æ¡å¯ä»¥è®©æˆ‘å®‰å…¨é€ƒç”Ÿçš„è´¸æ˜“è·¯çº¿ã€‚\n\nè´¸æ˜“è·¯çº¿ï¼š\nè´­ä¹°ï¼š%2ï¼ˆæ‰‡åŒºï¼š%3ï¼‰\nå‡ºå”®ï¼š%4ï¼ˆæ‰‡åŒºï¼š%5ï¼‰\nå•†å“ï¼š%6ï¼ˆx%7ï¼‰\né¢„æœŸåˆ©æ¶¦ï¼š%8 Cr\n\nå®Œæˆæ­¤äº¤æ˜“åŽï¼Œèˆ¹èˆ¶å°†é€ƒç¦»é»‘åå•æ‰‡åŒºã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nä¸ºæ‚¨æœåŠ¡</t>
    <t id="3211">æŒ‡æŒ¥å®˜ï¼Œ\n\néš”ç¦»è´¸æ˜“æ¨¡å¼\n\næˆ‘ç›®å‰åœ¨æ‰‡åŒº %2ï¼Œä½†å‰å¾€å…¶ä»–æ‰‡åŒºçš„æ‰€æœ‰è·¯çº¿éƒ½è¢«é»‘åå•æž¢çº½æ‰‡åŒºé˜»æŒ¡ã€‚è¿™æ„å‘³ç€æˆ‘åªèƒ½åœ¨æˆ‘å½“å‰çš„æ‰‡åŒºå†…è¿›è¡Œè´¸æ˜“ï¼Œç›´åˆ°é»‘åå•æƒ…å†µå‘ç”Ÿå˜åŒ–ã€‚\n\næƒ…å†µï¼š\nå½“å‰æ‰‡åŒºï¼š%2\nçŠ¶æ€ï¼šéš”ç¦»ï¼ˆéžé»‘åå•æ‰‡åŒºï¼Œä½†è·¯çº¿è¢«é˜»æŒ¡ï¼‰\nè´¸æ˜“æ¨¡å¼ï¼šä»…æ‰‡åŒºå†…äº¤æ˜“\n\næˆ‘çš„è´¸æ˜“ç³»ç»Ÿå·²è‡ªåŠ¨è°ƒæ•´åˆ©æ¶¦é˜ˆå€¼ï¼Œä»¥ä¼˜å…ˆè€ƒè™‘å¯ç”¨çš„æ‰‡åŒºå†…è´¸æ˜“æœºä¼šã€‚\n\næˆ‘å°†ç»§ç»­ç›‘æŽ§æƒ…å†µï¼Œå¦‚æžœè·¯çº¿å†æ¬¡å¯ç”¨ï¼Œæˆ‘ä¼šé€šçŸ¥æ‚¨ã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nåœ¨ %1 ä¸Š</t>
    <t id="3218">æŒ‡æŒ¥å®˜ï¼Œ\n\næ£€æµ‹åˆ°è·¯çº¿è·¯å¾„å˜æ›´\n\nè¿›å…¥æ‰‡åŒº %1 æ—¶ï¼Œæˆ‘çš„å¯¼èˆªç³»ç»Ÿæ£€æµ‹åˆ°å‰å¾€ç›®çš„åœ° %2ï¼ˆ%3ï¼‰çš„è·¯çº¿å·²æ›´æ”¹ã€‚\n\nè·¯å¾„åˆ†æžï¼š\n- æ­£å¸¸è·ç¦»ï¼š%4 è·³è·ƒ\n- é»‘åå•æ„ŸçŸ¥è·ç¦»ï¼š%5\n- çŠ¶æ€ï¼š%6\n\næˆ‘çš„å¯¼èˆªè®¡ç®—æœºæŒ‡ç¤ºï¼Œç”±äºŽæ‰‡åŒºæ—…è¡Œé™åˆ¶ï¼Œé¦–é€‰è·¯çº¿ä¸å†å¯è¡Œã€‚ä¸ºäº†èˆ¹èˆ¶å’Œèˆ¹å‘˜çš„å®‰å…¨ï¼Œæˆ‘ç«‹å³ä¸­æ­¢å½“å‰çš„è´¸æ˜“æ“ä½œã€‚\n\nå·²é‡‡å–çš„è¡ŒåŠ¨ï¼š\n- æ‰€æœ‰è´¸æ˜“è®¢å•å·²å–æ¶ˆ\n- è¿”å›žå®‰å…¨æ“ä½œæ¨¡å¼\n- å°†å¯»æ‰¾é¿å¼€è¢«é˜»æŒ¡æ‰‡åŒºçš„æ›¿ä»£è´¸æ˜“è·¯çº¿\n- è´§ç‰©å¤„ç†ï¼šè‡ªåŠ¨ï¼ˆå¦‚éœ€è¦ï¼Œå°†åœ¨å®‰å…¨åœ°ç‚¹å‡ºå”®ä»»ä½•è´§ç‰©ï¼‰\n\næˆ‘çš„å¯¼èˆªç³»ç»Ÿå°†åœ¨æœªæ¥çš„è·¯çº¿è§„åˆ’ä¸­è‡ªåŠ¨é¿å¼€è¢«é˜»æŒ¡çš„æ‰‡åŒºã€‚\n\nå®‰å…¨æ˜¯æˆ‘çš„ç¬¬ä¸€è¦åŠ¡ã€‚\n\nä»¥è­¦æƒ•ï¼Œ\nåœ¨ %7 ä¸Š</t>
    <t id="3219">æ‰‡åŒº %1 å·²æ¸…é™¤ - æ‰€æœ‰å¨èƒå·²æ¶ˆé™¤</t>
    <t id="3220">æŒ‡æŒ¥å®˜ï¼Œ\n\næ•Œæ–¹èˆ°èˆ¹å·²é€ƒè„±\n\næˆ‘ä»¬çš„å¨èƒæƒ…æŠ¥ç³»ç»Ÿå·²å¤±åŽ»å¯¹æ•Œæ–¹èˆ°èˆ¹ %3 çš„è¿½è¸ªï¼Œè¯¥èˆ°èˆ¹å·²ä»Žé»‘åå•æ‰‡åŒº %1 é€ƒè„±ã€‚\n\nè¯¦æƒ…ï¼š\n- é€ƒè„±çš„èˆ°èˆ¹ï¼š%3\n- ç¦»å¼€çš„æ‰‡åŒºï¼š%1\n- ç›®çš„åœ°æ‰‡åŒºï¼š%2\n- çŠ¶æ€ï¼šè¿½è¸ªä¸¢å¤± - èˆ°èˆ¹å·²ç¦»å¼€æˆ‘ä»¬çš„ç›‘æŽ§åŒºåŸŸ\n\nè™½ç„¶è¿™è‰˜èˆ°èˆ¹åœ¨æ‰‡åŒº %1 ä¸­ä¸å†æ˜¯å¨èƒï¼Œä½†æˆ‘ä»¬å·²å¤±åŽ»è§†è§‰æŽ¥è§¦ï¼Œæ— æ³•ç¡®è®¤å…¶åœ¨æ‰‡åŒº %2 çš„å½“å‰çŠ¶æ€æˆ–æ„å›¾ã€‚\n\næˆ‘ä»¬çš„è¿½è¸ªç³»ç»Ÿå°†ç»§ç»­ç›‘æŽ§æ‰‡åŒº %1 çš„å‰©ä½™å¨èƒã€‚å¦‚æžœæ‰€æœ‰è¢«è¿½è¸ªçš„æ•Œäººç¦»å¼€æˆ–è¢«æ¶ˆç­ï¼Œæ‰‡åŒºå°†è‡ªåŠ¨ä»Žé»‘åå•ä¸­æ¸…é™¤ã€‚\n\nä»¥è­¦æƒ•ï¼Œ\nå¨èƒæƒ…æŠ¥ç³»ç»Ÿ</t>
    <t id="3221">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘æ— æ³•åœ¨æ›´è¿œçš„è·ç¦»ï¼ˆæœ€å¤š %3 è·³è·ƒï¼‰æ‰¾åˆ°æœ‰åˆ©å¯å›¾çš„è´¸æ˜“æœºä¼šï¼Œå› ä¸ºè¿™äº›è·¯çº¿ç›®å‰ç”±äºŽæ‰‡åŒºæ—…è¡Œé™åˆ¶ï¼ˆé»‘åå•è·¯å¾„ï¼‰è€Œæ— æ³•åˆ°è¾¾ã€‚\n\næƒ…å†µï¼š\nå½“å‰æ‰‡åŒºï¼š%2\nåŽŸå§‹æœç´¢èŒƒå›´ï¼š%3 è·³è·ƒ\nå¤‡ç”¨æœç´¢èŒƒå›´ï¼š%4 è·³è·ƒ\n\næˆ‘çŽ°åœ¨å°†æœç´¢é‡ç‚¹æ”¾åœ¨ %4 è·³è·ƒèŒƒå›´å†…çš„é™„è¿‘æ‰‡åŒºï¼Œé‚£é‡Œçš„è·¯çº¿æ›´å¯èƒ½å¯ä»¥è®¿é—®ã€‚è¿™åº”è¯¥èƒ½å¸®åŠ©æˆ‘æ‰¾åˆ°ä¹‹å‰å› è·ç¦»é™åˆ¶è€Œéžå®žé™…æ— åˆ©å¯å›¾è€Œè¢«è¿‡æ»¤æŽ‰çš„æœ‰åˆ©å¯å›¾äº¤æ˜“ã€‚\n\nå½“æˆ‘åœ¨é™„è¿‘åŒºåŸŸæ‰¾åˆ°åˆé€‚çš„è´¸æ˜“æœºä¼šæ—¶ï¼Œæˆ‘ä¼šé€šçŸ¥æ‚¨ã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nåœ¨ %1 ä¸Š</t>
    <t id="3222">æŒ‡æŒ¥å®˜ï¼Œ\n\næ‰‡åŒºå·²åˆ—å…¥é»‘åå•\n\næˆ‘ä»¬çš„å¨èƒæƒ…æŠ¥ç³»ç»Ÿå·²æ£€æµ‹åˆ°æ‰‡åŒº %1 ä¸­çš„æ•Œå¯¹æ´»åŠ¨ï¼Œå¹¶å·²è‡ªåŠ¨å°†æ­¤æ‰‡åŒºåˆ—å…¥é»‘åå•ä»¥ä¿æŠ¤æˆ‘ä»¬çš„è´¸æ˜“æ“ä½œã€‚\n\næ£€æµ‹åˆ°çš„æ•Œæ–¹èˆ°èˆ¹ï¼š\n%2\n\næ£€æµ‹è€…ï¼š%3\n\nä¸ºäº†æˆ‘ä»¬èˆ°èˆ¹å’Œèˆ¹å‘˜çš„å®‰å…¨ï¼Œé€šè¿‡æ­¤æ‰‡åŒºçš„æ‰€æœ‰è´¸æ˜“è·¯çº¿å·²è¢«é˜»æŒ¡ã€‚æˆ‘ä»¬çš„èˆ°èˆ¹å°†è‡ªåŠ¨ç»•è¿‡æ­¤æ‰‡åŒºï¼Œç›´åˆ°å¨èƒè¢«æ¶ˆé™¤ã€‚\n\nä¸€æ—¦æ‰€æœ‰è¢«è¿½è¸ªçš„æ•Œæ–¹èˆ°èˆ¹è¢«æ¶ˆç­æˆ–ç¦»å¼€è¯¥åŒºåŸŸï¼Œæ‰‡åŒºå°†è‡ªåŠ¨ä»Žé»‘åå•ä¸­æ¸…é™¤ã€‚\n\nä»¥è­¦æƒ•ï¼Œ\nå¨èƒæƒ…æŠ¥ç³»ç»Ÿ</t>
    <t id="3223">æŒ‡æŒ¥å®˜ï¼Œ\n\næˆ‘æ— æ³•æ‰¾åˆ°å¯è®¿é—®çš„è®­ç»ƒç«™æ¥è¿›è¡Œæˆ‘çš„ %1 çº§è¿›é˜¶è€ƒè¯•ã€‚æˆ‘å°†æŒ‰ç…§æŒ‡ç¤ºç»§ç»­è¿›è¡Œè´¸æ˜“æ“ä½œï¼Œä½†æˆ‘ç†è§£åœ¨å®Œæˆæ‰€éœ€è®­ç»ƒä¹‹å‰ï¼Œæˆ‘å°†æ— æ³•èŽ·å¾—ç»éªŒç‚¹ã€‚åœ¨è¿™æ¬¡è´¸æ˜“è¿è¡ŒåŽï¼Œæˆ‘å°†å†æ¬¡å¯»æ‰¾ä»»ä½•å¯èƒ½çš„è®­ç»ƒæœºä¼šã€‚\n\næ­¤è‡´æ•¬ç¤¼ï¼Œ\nåœ¨ %2 ä¸Š</t>
    <t id="3224">è®­ç»ƒè®¸å¯è¯è´¹ç”¨ï¼š%1 Cr</t>
    <t id="3225">å¥–åŠ±ï¼šæˆ‘åœ¨è®­ç»ƒæœŸé—´é€šè¿‡ç§¯ç´¯çš„ç»éªŒèŽ·å¾—äº† %1 ä¸ªé¢å¤–çš„æŠ€èƒ½ç­‰çº§%2ï¼å½“å‰ç­‰çº§ï¼š%3</t>
    <t id="3214">ä¸ºæ‚¨å·¥ä½œæ˜¯æˆ‘çš„è£å¹¸ï¼Œ%1ï¼æˆ‘å¾ˆå…´å¥‹èƒ½åœ¨æ‚¨çš„æŒ‡æŒ¥ä¸‹å¼€å§‹æˆ‘çš„è´¸æ˜“ç”Ÿæ¶¯ã€‚æˆ‘å°†å°½æˆ‘æ‰€èƒ½ä¸ºæ‚¨æœåŠ¡è‰¯å¥½å¹¶ä¸ºæ‚¨çš„æˆåŠŸåšå‡ºè´¡çŒ®ã€‚</t>
    <t id="3215">æ„Ÿè°¢æ‚¨ç»™æˆ‘è¿™ä¸ªåº”å¾—çš„å‡æœŸï¼Œ%1ï¼æˆ‘å¾ˆäº«å—è¿œç¦»è´¸æ˜“çš„æ—¶å…‰ï¼Œæˆ‘çš„æŠ€èƒ½ä¿æŒå®Œå¥½ã€‚æˆ‘æœŸå¾…åœ¨æ‚¨éœ€è¦æˆ‘æ—¶éšæ—¶è¿”å›žå·¥ä½œã€‚åœ¨é‚£ä¹‹å‰ï¼Œæˆ‘å°†ä¿æŒæˆ‘çš„è´¸æ˜“çŸ¥è¯†æ•é”ï¼</t>
    <t id="3216">æˆ‘ä»Žå‡æœŸå›žæ¥äº†ï¼Œå‡†å¤‡å†æ¬¡å·¥ä½œï¼Œ%1ï¼æˆ‘çš„è´¸æ˜“æŠ€èƒ½ä¿æŒæ•é”ï¼Œæˆ‘æ¸´æœ›ç»§ç»­åœ¨ %2 ä¸Šä¸ºæ‚¨æœåŠ¡ã€‚æ„Ÿè°¢åº”å¾—çš„ä¼‘æ¯ï¼</t>
    <t id="3217">æ„Ÿè°¢æ‚¨å°†æˆ‘è°ƒä»»åˆ° %1ï¼Œ%2ï¼æˆ‘å¾ˆè£å¹¸æŽ¥å—è¿™ä¸ªæ–°ä»»åŠ¡ï¼Œå¹¶å°†å¾ˆå¥½åœ°ç…§é¡¾æˆ‘çš„æ–°èˆ¹ã€‚æˆ‘çš„è´¸æ˜“ç»éªŒå’ŒæŠ€èƒ½ä¿æŒå®Œå¥½ï¼Œæˆ‘å‡†å¤‡ç»§ç»­ä¸ºæ‚¨æœåŠ¡ã€‚</t>
    <t id="3227">èˆ¹ä½“ä¸¢å¤±ï¼Œå°Šä¸¥å¾…å›žæ”¶</t>
    <t id="3228">%1 æŒ‡æŒ¥å®˜ï¼Œ\n\n%2 ä»Ž %3 æŠ¥å‘Šã€‚æˆ‘çš„é£žèˆ¹çˆ†ç‚¸äº†ã€‚æˆ‘æ²¡æœ‰ã€‚æˆ‘çŽ°åœ¨æ˜¯èˆ°é˜Ÿæœ€æ˜‚è´µçš„æ¼‚æµ®è´§ç‰©ã€‚\n\nå·²é™„åŠ åœ°å›¾æ ‡è®°ã€‚è¯·å¿«ç‚¹ - æˆ‘æ­£åœ¨å¼€å‘ç¥¨ã€‚\n\nä¸“ä¸šåœ°æ¼‚æµ®ç€ï¼Œ\n%2</t>
    <t id="3229">é£žè¡Œå‘˜å·²å›žæ”¶ - æ°§æ°”æˆç˜¾å·²æ²»æ„ˆ</t>
    <t id="3230">%1 æŒ‡æŒ¥å®˜ï¼Œ\n\nèˆ°é˜Ÿæ›´æ–°ï¼š%2 å·²è¢« %3 (%4) æžèµ·ï¼Œä¸å†å‘æ‚¨æ”¶å–å»¶é•¿ EVA è®­ç»ƒè´¹ç”¨ã€‚\n\næ­£åœ¨é‡æ–°ç»‘å®šæ³¨å†Œè¡¨ã€‚å»ºè®®ä¸è¦è¿½é—®æ—§é£žèˆ¹çš„ä¸‹è½ã€‚\n\næƒ­æ„§åœ°ï¼Œ\n%2</t>
<t id="4000">èˆ°é˜Ÿåè°ƒï¼š%s å·²è¢«åˆ†é…åˆ°è·¯çº¿ %s</t>
    <t id="4001">èˆ°é˜Ÿåè°ƒï¼šè·¯çº¿ %s å·²å®Œå…¨ä½¿ç”¨</t>
    <t id="4002">èˆ°é˜Ÿåè°ƒï¼š%s å·²é‡Šæ”¾è·¯çº¿ %s</t>
    <t id="5000">%s å·²è¢«æŒ‡å®šä¸º %s çš„ä¸»è¦é¢†åœ°</t>
    <t id="5001">%s å·²è¾¾åˆ° %s çš„ä¸“ä¸šæ°´å¹³ %sï¼</t>
    <t id="5002">é€‚ç”¨åœ°åŒºå¥–é‡‘:%såˆ©æ¶¦å¢žåŠ %s</t>
    <t id="9500">é”™è¯¯ï¼š%s è¢«å›°å¹¶éœ€è¦å¸®åŠ©ï¼</t>
    <t id="9501">é”™è¯¯ï¼š%s çš„äº¤æ˜“å¤±è´¥</t>
    <t id="9502">é”™è¯¯ï¼šæ— æ³•å°† %s æ³¨å†Œåˆ° GalaxyTrader MK3</t>
    <t id="80001">å•†å“ %s å·²æ·»åŠ åˆ°é»‘åå•</t>
    <t id="80002">å•†å“ %s å·²ä»Žé»‘åå•ç§»é™¤</t>
    <t id="80003">å•†å“ %s å·²æ·»åŠ åˆ°ç™½åå•</t>
    <t id="80004">è‡ªåŠ¨åˆ—å…¥é»‘åå•ï¼ˆæ€§èƒ½å·®ï¼‰ï¼š%s</t>
    <t id="80005">å±é™©å•†å“å·²ä¼˜å…ˆï¼š%s</t>
    <t id="80006">å•†å“è¿‡æ»¤å™¨ï¼š%s æ´»è·ƒï¼Œ%s è´¸æ˜“è¢«é˜»æŒ¡</t>
    <t id="80007">æ‰€æœ‰å•†å“è¿‡æ»¤å™¨å·²æ¸…é™¤</t>
    <t id="80008">å•†å“è¿‡æ»¤å™¨å·²é‡ç½®ä¸ºé»˜è®¤å€¼</t>
    <t id="80009">å•†å“è¿‡æ»¤å™¨ç®¡ç†</t>
    <t id="80010">è¢«é˜»æŒ¡çš„å•†å“</t>
    <t id="80011">å…è®¸çš„å•†å“</t>
    <t id="80012">å±é™©å•†å“å¤„ç†</t>
    <t id="80013">æœ€å°å•†å“ä»·å€¼</t>
    <t id="80014">æœ€å¤§å•†å“ä»·å€¼</t>
    <t id="80015">å—é™æ´¾ç³»</t>
    <t id="80016">å•†å“ç±»åˆ«å·²ä»Žå½“å‰æ¸¸æˆçŠ¶æ€æ›´æ–°</t>
    <t id="80017">%s å•†å“å·²åˆ†ç±»ï¼š%s ä½Žä»·å€¼ï¼Œ%s å±é™©ï¼Œ%s é«˜ä»·å€¼</t>
    <t id="80018">åŠ¨æ€å•†å“åˆ†ç±»å·²å¯ç”¨</t>
    <t id="80019">ç±»åˆ« %s çš„è‡ªåŠ¨é»‘åå•å·²ç¦ç”¨</t>
    <t id="80020">å·²æ£€æµ‹å¹¶åˆ†ç±»æ¥è‡ªå…¶ä»–æ¨¡ç»„çš„æ–°å•†å“</t>
    <t id="9000">GalaxyTrader - å…¨å±€è®¾ç½®</t>
    <t id="9010">ç»éªŒå€¼å’Œè®­ç»ƒç³»ç»Ÿ</t>
    <t id="9012">è‡ªåŠ¨è®­ç»ƒ</t>
    <t id="9013">ç»éªŒå€¼å€æ•°</t>
    <t id="9015">æŒ‡æŒ¥å®˜å¥–åŠ±ç™¾åˆ†æ¯”</t>
    <t id="9020">èˆ°é˜Ÿåè°ƒ</t>
    <t id="9021">å¯ç”¨èˆ°é˜Ÿåè°ƒ</t>
    <t id="9023">å¯ç”¨è´¸æ˜“ç¼“å­˜</t>
    <t id="9030">é€šçŸ¥</t>
    <t id="9031">é€šçŸ¥çº§åˆ«</t>
    <t id="9040">è‡ªåŠ¨ç»´ä¿®ç³»ç»Ÿ</t>
    <t id="9041">å¯ç”¨è‡ªåŠ¨ç»´ä¿®</t>
    <t id="9042">èˆ¹ä½“ç»´ä¿®é˜ˆå€¼</t>
    <t id="9310">é“¶æ²³çŸ¿å·¥</t>
    <t id="9311">æ‰‡åŒºèµ„æºæŽ¢æµ‹æ‰«æç­‰å¾…</t>
    <t id="9312">èˆ°èˆ¹æŽ¥è¿‘æƒé‡</t>
    <t id="9043">æœ€ä½Žé£žè¡Œå‘˜ç­‰çº§</t>
    <t id="9004">è´¸æ˜“ä»·æ ¼èŒƒå›´</t>
    <t id="9005">å‡ºå”®æŠ¥ä»·æœ€é«˜ä»·æ ¼</t>
    <t id="9006">è´­ä¹°æŠ¥ä»·æœ€ä½Žä»·æ ¼</t>
    <t id="9007">éš”ç¦»ï¼šå‡ºå”®ä»·æ ¼æœ€é«˜</t>
    <t id="9008">éš”ç¦»ï¼šè´­ä¹°ä»·æ ¼æœ€ä½Ž</t>
    <t id="9009">å¤‡ç”¨ï¼šå‡ºå”®ä»·æ ¼æœ€é«˜</t>
    <t id="9014">å¤‡ç”¨ï¼šè´­ä¹°ä»·æ ¼æœ€ä½Ž</t>
    <t id="9016">åˆ©æ¶¦é˜ˆå€¼åŸºå‡†</t>
    <t id="9025">æœ€ä½ŽçŽ©å®¶èµ„é‡‘</t>
    <t id="9024">ç¼“å­˜ä¸‹é™å®¹å¿åº¦</t>
    <t id="9026">ç©ºé—²åœæ³Šé‡Šæ”¾æ—¶é—´</t>
    <t id="9054">é˜»æŒ¡æ•Œæ–¹æ´¾ç³»æ‰‡åŒº</t>
    <t id="9055">é»‘åå•å¨èƒçº§åˆ«</t>
    <t id="9056">é‡æ–°åˆ›å»ºé»‘åå•</t>
    <t id="9057">é‡æ–°åˆ›å»º</t>
    <t id="9058">åˆ†é…ç»™ GT è‰˜èˆ¹</t>
    <t id="9059">åˆ†é…</t>
    <t id="9112">å½“é£žè¡Œå‘˜è¾¾åˆ°æ‰€éœ€ç­‰çº§æ—¶è‡ªåŠ¨é€ä»–ä»¬åŽ»è®­ç»ƒã€‚ç¦ç”¨ä»¥æ‰‹åŠ¨æŽ§åˆ¶è®­ç»ƒæ—¶æœºã€‚</t>
    <t id="9113">è°ƒæ•´é£žè¡Œå‘˜èŽ·å¾—ç»éªŒçš„é€Ÿåº¦ã€‚å€¼è¶Šé«˜æ„å‘³ç€è¿›åº¦è¶Šå¿«ã€‚</t>
    <t id="9115">æŽˆäºˆæŒ‡æŒ¥å®˜é£žè¡Œå‘˜çš„ subordinate XP ç™¾åˆ†æ¯”ã€‚è®¾ç½®ä¸º 0% ä»¥ç¦ç”¨æŒ‡æŒ¥å®˜å¥–åŠ± XPã€‚é»˜è®¤å€¼ï¼š10%ã€‚</t>
    <t id="9121">å¯ç”¨æ™ºèƒ½èˆ°é˜Ÿåè°ƒåŠŸèƒ½ï¼ŒåŒ…æ‹¬è·¯çº¿ä¼˜åŒ–å’Œè´Ÿè½½å¹³è¡¡ã€‚</t>
    <t id="9123">å…è®¸åœ¨èˆ°é˜Ÿæˆå‘˜ä¹‹é—´å…±äº«æœ‰åˆ©å¯å›¾çš„è´¸æ˜“æœºä¼šä»¥æ›´å¥½åœ°åè°ƒã€‚</t>
    <t id="9131">æŽ§åˆ¶æ˜¾ç¤ºå¤šå°‘é€šçŸ¥ï¼š0=å®‰é™ï¼Œ1=ä»…é‡è¦ï¼Œ2=æ‰€æœ‰é€šçŸ¥</t>
    <t id="9141">å½“èˆ¹ä½“ä½ŽäºŽé˜ˆå€¼æ—¶ï¼Œåœ¨å®Œæˆè´¸æ˜“åŽè‡ªåŠ¨é€èˆ°èˆ¹åŽ»ç»´ä¿®ã€‚ä»…é€‚ç”¨äºŽç»éªŒä¸°å¯Œçš„é£žè¡Œå‘˜ï¼ˆ12 çº§ä»¥ä¸Šï¼‰ã€‚èˆ°èˆ¹é€‰æ‹©é€‚å½“çš„è®¾æ–½ï¼šS/M è£…å¤‡ç å¤´ï¼ŒL/XL é€ èˆ¹åŽ‚ã€‚</t>
    <t id="9142">è§¦å‘è‡ªåŠ¨ç»´ä¿®çš„èˆ¹ä½“ç™¾åˆ†æ¯”ã€‚é»˜è®¤å€¼ï¼š95%ã€‚èˆ°èˆ¹å—æŸæ—¶å°†è‡ªåŠ¨å‰å¾€æœ€è¿‘çš„ç»´ä¿®è®¾æ–½ã€‚</t>
    <t id="9411">å¯ç”¨åŽï¼Œé‡‡çŸ¿èˆ¹åœ¨è¯„ä¼°æ‰‡åŒºå†…æ´¾ç³»èµ„æºæŽ¢æµ‹å™¨æ—¶ä¼šç­‰å¾…ï¼ˆæ¯å¤šä¸€ä¸ªæŽ¢æµ‹å™¨+5ç§’ï¼‰ã€‚GTé£žè¡Œå‘˜ç­‰çº§å°†ç­‰å¾…æ—¶é—´ä»Ž1çº§çš„å®Œæ•´æ—¶é—´çº¿æ€§ç¼©çŸ­è‡³15çº§çš„5ç§’ï¼ˆä»…GT XPæ¨¡å¼ï¼Œä¸”ç­‰å¾…è¶…è¿‡5ç§’æ—¶ï¼‰ã€‚ç¦ç”¨æ—¶=ä¸ç­‰å¾…ï¼ˆä¸ŽåŽŸç‰ˆç›¸åŒï¼‰ã€‚</t>
    <t id="9412">MK3/MK4èˆ°èˆ¹åœ¨æŽ’åºå·²éªŒè¯è´¸æ˜“æ—¶åå‘æ›´è¿‘çš„è´­ä¹°ç«™ã€‚é€‰æ‹©åˆ†æ•° = è´¸æ˜“åˆ†æ•° / (1 + èˆ°èˆ¹â†’è´­ä¹°è·³è·ƒæ•° Ã— æƒé‡)ã€‚æ»‘å—0-100ï¼ˆ0=å…³é—­ï¼Œ4=é»˜è®¤0.04ï¼‰ã€‚ä¸å½±å“ç¼“å­˜æŽ’åæˆ–é¢†åœŸèˆªç¨‹é™åˆ¶ã€‚</t>
    <t id="9143">è‡ªåŠ¨ç»´ä¿®åŠŸèƒ½æ‰€éœ€çš„æœ€ä½Žé£žè¡Œå‘˜ç­‰çº§ã€‚é»˜è®¤å€¼ï¼š12ï¼ˆç»éªŒä¸°å¯Œçš„è´¸æ˜“å•†ï¼‰ã€‚è¾ƒä½Žç­‰çº§çš„é£žè¡Œå‘˜å¿…é¡»æ‰‹åŠ¨ç»´ä¿®ã€‚</t>
    <t id="9104">å‡ºå”®æŠ¥ä»·çš„æœ€é«˜ç›¸å¯¹ä»·æ ¼ï¼ˆèˆ°èˆ¹ä»Žç©ºé—´ç«™è´­ä¹°ï¼‰ã€‚èŒƒå›´ï¼š-1.0 åˆ° +1.0ã€‚é»˜è®¤å€¼ï¼š0.5ï¼ˆé«˜äºŽå¹³å‡å€¼ 50%ï¼‰ã€‚å€¼è¶Šé«˜ = è¶Šè´µä½†é€‰é¡¹è¶Šå¤šã€‚</t>
    <t id="9105">è´­ä¹°æŠ¥ä»·çš„æœ€ä½Žç›¸å¯¹ä»·æ ¼ï¼ˆèˆ°èˆ¹å‘ç©ºé—´ç«™å‡ºå”®ï¼‰ã€‚èŒƒå›´ï¼š-1.0 åˆ° +1.0ã€‚é»˜è®¤å€¼ï¼š-0.5ï¼ˆä½ŽäºŽå¹³å‡å€¼ 50%ï¼‰ã€‚å€¼è¶Šä½Ž = ä¹°å®¶è¶Šä¾¿å®œä½†é€‰é¡¹è¶Šå¤šã€‚</t>
    <t id="9106">éš”ç¦»èˆ°èˆ¹ï¼ˆå›°åœ¨å•ä¸ªæ‰‡åŒºï¼‰çš„å‡ºå”®ä»·æ ¼æœ€é«˜ã€‚èŒƒå›´ï¼š-1.0 åˆ° +1.0ã€‚é»˜è®¤å€¼ï¼š0.5ã€‚</t>
    <t id="9107">éš”ç¦»èˆ°èˆ¹ï¼ˆå›°åœ¨å•ä¸ªæ‰‡åŒºï¼‰çš„è´­ä¹°ä»·æ ¼æœ€ä½Žã€‚èŒƒå›´ï¼š-1.0 åˆ° +1.0ã€‚é»˜è®¤å€¼ï¼š-0.5ã€‚</t>
    <t id="9108">å¤‡ç”¨æœç´¢ï¼ˆæ­£å¸¸æœç´¢å¤±è´¥æ—¶çš„æœ€åŽæ‰‹æ®µï¼‰çš„å‡ºå”®ä»·æ ¼æœ€é«˜ã€‚èŒƒå›´ï¼š-1.0 åˆ° +1.0ã€‚é»˜è®¤å€¼ï¼š0.5ã€‚å¤‡ç”¨æœç´¢ä½¿ç”¨ MaxDistance=2 å’Œæ”¾å®½çš„åˆ©æ¶¦é˜ˆå€¼ã€‚</t>
    <t id="9109">å¤‡ç”¨æœç´¢ï¼ˆæ­£å¸¸æœç´¢å¤±è´¥æ—¶çš„æœ€åŽæ‰‹æ®µï¼‰çš„è´­ä¹°ä»·æ ¼æœ€ä½Žã€‚èŒƒå›´ï¼š-1.0 åˆ° +1.0ã€‚é»˜è®¤å€¼ï¼š-0.5ã€‚å¤‡ç”¨æœç´¢ä½¿ç”¨ MaxDistance=2 å’Œæ”¾å®½çš„åˆ©æ¶¦é˜ˆå€¼ã€‚</t>
    <t id="9116">ä¸­åž‹è´¸æ˜“å•†çš„æœ€ä½Žåˆ©æ¶¦åŸºå‡†ä¸º 15 çº§ï¼ˆå‚è€ƒè´§ç‰© 8200ï¼‰ã€‚å®žé™… MinAbsoluteProfit æ˜¯æŒ‰é£žè¡Œå‘˜è®¡ç®— + æŒ‰è´§ç‰©ç¼©æ”¾ï¼š\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(scaled, 25% of base(L))\n\nè®¾ç½®ä¸º 0 ä»¥æŽ¥å—ä»»ä½•åˆ©æ¶¦ï¼ˆä»…é€‚ç”¨ ROI/è·ç¦»/å…¶ä»–è¿‡æ»¤å™¨ï¼‰ã€‚</t>
    <t id="9125">èˆ¹èˆ¶åœ¨å¯»æ‰¾äº¤æ˜“å‰å¿…é¡»çš„æœ€ä½ŽçŽ©å®¶é‡‘é¢( ä¿¡ç”¨) ã€‚ å½“çŽ©å®¶é‡‘é¢ä½ŽäºŽè¿™ä¸ªé—¨æ§›æ—¶, æ‰€æœ‰èˆ¹èˆ¶éƒ½ä¼šè·³è¿‡è´¸æ˜“æœç´¢å’Œç­‰å¾…, é˜²æ­¢æ˜‚è´µçš„ç¼“å­˜æ‰«æå¯¼è‡´æ¸¸æˆç»“å·´ã€‚ èŒƒå›´: 1 000 - 100 000 Cr. é»˜è®¤å€¼: 1 000 Cr.</t>
    <t id="9124">åœ¨æ‹’ç»è´¸æ˜“ä¹‹å‰ï¼Œä»Žç¼“å­˜å€¼ä¸‹é™çš„æœ€å¤§ç™¾åˆ†æ¯” ROIã€‚ç¤ºä¾‹ï¼š20% ç¼“å­˜ ROI å’Œ 15% å®¹å¿åº¦æŽ¥å—ä½Žè‡³ 17% ROIï¼ˆä¸‹é™ 14%ï¼‰ã€‚</t>
    <t id="9126">åœé åŽé‡Šæ”¾æ¸¯å£å‰ç­‰å¾…çš„åˆ†é’Ÿæ•°ï¼ˆ0-60ï¼‰ã€‚0 = ä¿æŒåœé ç›´åˆ°æ‰¾åˆ°æ–°å·¥ä½œã€‚é»˜è®¤ï¼š1 åˆ†é’Ÿã€‚</t>
    <t id="9154">è‡ªåŠ¨å°†æ•Œæ–¹æ´¾ç³»æ‹¥æœ‰çš„æ‰€æœ‰æ‰‡åŒºåˆ—å…¥é»‘åå•ï¼ˆé»‘åå•ä¸­çš„å…³ç³»å¤é€‰æ¡†ï¼‰</t>
    <t id="9155">å°†æ‰‡åŒºåˆ—å…¥é»‘åå•æ‰€éœ€çš„æœ€å°å¨èƒçº§åˆ«ï¼ˆ1-5ï¼‰ï¼š\n2=ä¸­ç­‰ï¼ˆå•æ¬¡æ”»å‡»ï¼‰\n3=ä¸­é«˜ï¼ˆæ•Œå¯¹æ´¾ç³»ï¼‰\n4=é«˜ï¼ˆä¸»åŠ›èˆ°/å¯¼å¼¹ï¼‰\n5=éžå¸¸é«˜ï¼ˆXenon/Khaakï¼‰</t>
    <t id="9156">æ‰‹åŠ¨é‡æ–°åˆ›å»ºå¨èƒè§„é¿é»‘åå•ï¼ˆå¦‚æžœå·²åˆ é™¤åˆ™å¾ˆæœ‰ç”¨ï¼‰</t>
    <t id="9157">æ‰‹åŠ¨å°†å½“å‰åŠ¨æ€é»‘åå•åˆ†é…ç»™æ‰€æœ‰GTèˆ°é˜ŸæŒ‡æŒ¥èˆ°ã€‚ä¸‹å±žç»§æ‰¿äº†ä»–ä»¬çš„æŒ‡æŒ¥å®˜ã€‚</t>
    <t id="6001">å­¦å¾’</t>
    <t id="6002">ä¿¡ä½¿</t>
    <t id="6003">ä¾›åº”å•†</t>
    <t id="6004">è´¸æ˜“å•†</t>
    <t id="6005">å•†äºº</t>
    <t id="6006">é•¿é€”å•†äºº</t>
    <t id="6101">å¹³è¡¡</t>
    <t id="6102">é˜²å¾¡</t>
    <t id="6103">è´¸æ˜“ä¸“æ³¨</t>
    <t id="6104">é‡é˜²å¾¡</t>
    <t id="6105">å¡”æ”¯æ´</t>
    <t id="9050">å¨èƒè§„é¿ç³»ç»Ÿ</t>
    <t id="9051">å¯ç”¨å¨èƒè§„é¿ï¼š</t>
    <t id="9052">æ•Œå¯¹å…³ç³»é˜ˆå€¼ï¼š</t>
    <t id="9053">ä½¿ç”¨åŠ¨æ€é»‘åå•ï¼š</t>
    <t id="9151">6 çº§ä»¥ä¸Šçš„è´¸æ˜“å•†æ£€æµ‹æ•Œå¯¹èˆ°èˆ¹å¹¶é¿å¼€å±é™©è·¯çº¿ã€‚ç¦ç”¨ä¼šåœæ­¢æ‰€æœ‰æ‰«æï¼ˆæé«˜æ€§èƒ½ï¼‰ã€‚æ¯è‰˜èˆ°èˆ¹åœ¨å‘½ä»¤è¡Œä¸ºä¸­çš„é£Žé™©å®¹å¿åº¦ï¼ˆ0-10 ç­‰çº§ï¼‰ã€‚</t>
    <t id="9152">ä»…å°†å…³ç³»ç­‰äºŽæˆ–ä½ŽäºŽæ­¤å€¼çš„æ´¾ç³»æ ‡è®°ä¸ºå¨èƒã€‚é»˜è®¤å€¼ï¼š-20%</t>
    <t id="9153">è‡ªåŠ¨å°†å±é™©æ‰‡åŒºï¼ˆå¨èƒçº§åˆ« 3+ï¼‰åˆ—å…¥é»‘åå•ï¼Œä»¥å¼ºåˆ¶èˆ°èˆ¹ç»•è¿‡å¨èƒã€‚ä½¿ç”¨åŽŸç”Ÿè·¯å¾„æŸ¥æ‰¾å¯»æ‰¾æ›¿ä»£è·¯çº¿ã€‚</t>
    <t id="9060">é˜²å¾¡è£…å¤‡è‡ªåŠ¨è¡¥å……ï¼ˆ15 çº§ï¼‰</t>
    <t id="9061">å¯ç”¨è‡ªåŠ¨è¡¥å……ï¼š</t>
    <t id="9062">è¡¥å……å¯¹æŠ—æŽªæ–½ï¼š</t>
    <t id="9063">è¡¥å……é˜²å¾¡æ— äººæœºï¼š</t>
    <t id="9064">è¡¥å……è´¸æ˜“æ— äººæœºï¼š</t>
    <t id="9065">è¡¥å……æ¿€å…‰å¡”ï¼š</t>
    <t id="9066">è¡¥å……ç»´ä¿®æ— äººæœºï¼š</t>
    <t id="9067">å¯¹æŠ—æŽªæ–½é˜ˆå€¼ï¼š</t>
    <t id="9068">ç»Ÿä¸€å®¹é‡é˜ˆå€¼ï¼š</t>
    <t id="9069">è£…å¤‡å¹³è¡¡é…ç½®ï¼š</t>
    <t id="9161">å¤§å¸ˆçº§è´¸æ˜“å•†ï¼ˆ15 çº§ï¼‰åœ¨è´¸æ˜“åŽè‡ªåŠ¨è¡¥å……é˜²å¾¡è£…å¤‡ã€‚é€‚ç”¨äºŽä¸‹å±žçš„æŒ‡æŒ¥å®˜ç­‰çº§ã€‚</t>
    <t id="9162">æ‰€æœ‰èˆ°èˆ¹ï¼ˆS/M/L/XLï¼‰ã€‚ç‹¬ç«‹å®¹é‡ã€‚å¯¹å¯¼å¼¹é˜²å¾¡è‡³å…³é‡è¦ã€‚</t>
    <t id="9163">ä»… L/XL èˆ°èˆ¹ã€‚ä¸Žå…¶ä»–å¯éƒ¨ç½²è®¾å¤‡å…±äº«ç»Ÿä¸€å®¹é‡ã€‚</t>
    <t id="9164">ä»… L/XL èˆ°èˆ¹ã€‚å¯¹è´¸æ˜“æ“ä½œè‡³å…³é‡è¦ã€‚å…±äº«ç»Ÿä¸€å®¹é‡ã€‚</t>
    <t id="9165">æ‰€æœ‰èˆ°èˆ¹ã€‚L/XL èˆ°èˆ¹å…±äº«ç»Ÿä¸€å®¹é‡ï¼ŒS/M ä½¿ç”¨è´§èˆ±ã€‚</t>
    <t id="9166">ä»… L/XL èˆ°èˆ¹ã€‚ä¸Žè‡ªåŠ¨ç»´ä¿®ç³»ç»Ÿé…åˆä½¿ç”¨ã€‚å…±äº«ç»Ÿä¸€å®¹é‡ã€‚</t>
    <t id="9167">å½“å¯¹æŠ—æŽªæ–½ä½ŽäºŽæ­¤ç™¾åˆ†æ¯”æ—¶è¡¥å……ï¼ˆæ‰€æœ‰èˆ°èˆ¹ï¼Œç‹¬ç«‹å®¹é‡ï¼‰ã€‚</t>
    <t id="9168">å½“æ€»å¯éƒ¨ç½²è®¾å¤‡ä½ŽäºŽæ­¤ç™¾åˆ†æ¯”æ—¶è¡¥å……ï¼ˆL/XL èˆ°èˆ¹ï¼šæ— äººæœº + å¡”å…±äº«ä¸€ä¸ªå®¹é‡ï¼‰ã€‚</t>
    <t id="9169">ç»Ÿä¸€å®¹é‡çš„åˆ†é…ï¼ˆL/XL èˆ°èˆ¹ï¼‰ï¼šè´¸æ˜“ä¸“æ³¨ï¼ˆ20/50/20/10ï¼‰ï¼Œå¹³è¡¡ï¼ˆ35/35/20/10ï¼‰ï¼Œé˜²å¾¡ï¼ˆ50/20/20/10ï¼‰ï¼Œé‡é˜²å¾¡ï¼ˆ40/30/20/10ï¼‰ï¼Œå¡”æ”¯æ´ï¼ˆ30/30/30/10ï¼‰ã€‚æ¯”çŽ‡ï¼šé˜²å¾¡/è´¸æ˜“/å¡”/ç»´ä¿®ã€‚ç‚¹å‡»å¾ªçŽ¯æµè§ˆé€‰é¡¹ã€‚</t>
    <t id="9090">èˆ°èˆ¹æ”¹è£…</t>
    <t id="9091">å¯ç”¨èˆ°èˆ¹æ”¹è£…</t>
    <t id="9191">æ ¹æ®é£žè¡Œå‘˜ç­‰çº§è‡ªåŠ¨å®‰è£…èˆ°èˆ¹å’Œå¼•æ“Žæ”¹è£…ã€‚9 çº§ä»¥ä¸Š = 1 çº§æ”¹è£…ï¼Œ12 çº§ä»¥ä¸Š = 2 çº§æ”¹è£…ï¼Œ15 çº§ä»¥ä¸Š = 3 çº§æ”¹è£…ã€‚å–æ¶ˆè®¢å•æ—¶ä»…ç§»é™¤ GT å®‰è£…çš„æ”¹è£…ã€‚</t>
    <t id="9070">èˆ°èˆ¹å‘½åé…ç½®</t>
    <t id="9071">æ˜¾ç¤ºç»éªŒå€¼ï¼š</t>
    <t id="9072">æ˜¾ç¤ºç­‰çº§ï¼š</t>
    <t id="9073">æ˜¾ç¤ºçº§åˆ«ï¼š</t>
    <t id="9074">æ˜¾ç¤ºçŠ¶æ€ï¼š</t>
    <t id="9075">å¯ç”¨èˆ°èˆ¹é‡å‘½åï¼š</t>
    <t id="9076">å‰ç¼€</t>
    <t id="9077">åŽç¼€</t>
    <t id="9078">é»˜è®¤åç§°æ¥æºï¼š</t>
    <t id="9079">åž‹å·åç§°</t>
    <t id="9080">ç±»åž‹åç§°</t>
    <t id="9081">åŸºç¡€åç§°</t>
    <t id="9083">åŸºç¡€åç§°</t>
    <t id="9084">æ˜¾ç¤ºæ¯æ˜ŸåŒº:</t>
    <t id="9085">å‘½åæ¨¡å¼:</t>
    <t id="9086">ä¼ ç»Ÿ</t>
    <t id="9087">æ¨¡æ¿</t>
    <t id="9088">åç§°æ¨¡æ¿:</t>
    <t id="9089">å ä½ç¬¦: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}ã€‚åŽŸå­æ ‡è®°: {RS} {CB} {BL} ç­‰ã€‚ä½¿ç”¨ä¸‹æ–¹çŠ¶æ€ç¼©å†™ã€‚ç©ºæ ‡è®°çœç•¥ï¼Œå¤šä½™ç©ºæ ¼åˆå¹¶ã€‚æœ€å¤š128å­—ç¬¦ã€‚</t>
    <t id="9183">åœ¨èˆ°èˆ¹åç§°ä¸­æ˜¾ç¤ºå·²é…ç½®çš„é¦–åºœæ˜ŸåŒºï¼ˆå‰ç¼€æˆ–åŽç¼€ï¼‰ã€‚</t>
    <t id="9184">ä½¿ç”¨ {TOKEN} å ä½ç¬¦è‡ªå®šä¹‰åç§°æ ¼å¼ï¼Œæ›¿ä»£ä¼ ç»Ÿå¸ƒå±€å¼€å…³ã€‚éœ€è¦ GalaxyTrader XPï¼ˆéžåŽŸç‰ˆ XP æ¨¡å¼ï¼‰ã€‚</t>
    <t id="9092">æ¨¡å¼å ä½ç¬¦</t>
    <t id="9093">èˆ°èˆ¹: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT XPï¼ˆæ¨¡ç»„ï¼‰: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">åŽŸç‰ˆ: {MGMT} {PILOTSKILL}</t>
    <t id="9096">æ¯æ¸¯: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">èˆ¹å‘˜: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">åŒºåŸŸ: {SECTOR} | ç»Ÿè®¡: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">çŠ¶æ€å ä½ç¬¦:</t>
    <t id="9100">{OPSTATE}: åˆå¹¶æ‰€æœ‰æ´»è·ƒè¿è¡Œæ ‡å¿—ï¼ˆå¦‚ CB RSã€MTï¼‰</t>
    <t id="9101">{STATUS}: å°é”ã€è®­ç»ƒã€å¤‡ç”¨æˆ–å­¤ç«‹</t>
    <t id="9102">{CB}: ä»…è‡ªå®šä¹‰é»‘åå•, å·²å«äºŽ {OPSTATE}, å‹¿ç»„åˆä½¿ç”¨</t>
    <t id="9082">æ˜¾ç¤ºèˆ°èˆ¹çº§åˆ«ï¼š</t>
    <t id="9171">åœ¨èˆ°èˆ¹åç§°ä¸­æ˜¾ç¤ºç»éªŒå€¼</t>
    <t id="9175">å¯ç”¨æˆ–ç¦ç”¨å¸¦æœ‰é£žè¡Œå‘˜ä¿¡æ¯çš„è‡ªåŠ¨èˆ°èˆ¹é‡å‘½å</t>
    <t id="9172">åœ¨èˆ°èˆ¹åç§°ä¸­æ˜¾ç¤ºç­‰çº§å¤´è¡”</t>
    <t id="9173">åœ¨èˆ°èˆ¹åç§°ä¸­æ˜¾ç¤ºçº§åˆ«æ•°å­—</t>
    <t id="9174">åœ¨èˆ°èˆ¹åç§°ä¸­æ˜¾ç¤ºè´¸æ˜“çŠ¶æ€</t>
    <t id="9178">é€‰æ‹©èˆ°èˆ¹åŸºç¡€åç§°çš„æ¥æºï¼šåž‹å·åç§°ï¼ˆå¸¦å˜ä½“ï¼‰ã€ç±»åž‹åç§°ï¼ˆé€šç”¨ï¼‰æˆ–åŸºç¡€åç§°ï¼ˆæ— å˜ä½“ï¼‰</t>
    <t id="9182">åœ¨èˆ°èˆ¹åç§°ä¸­æ˜¾ç¤ºèˆ°èˆ¹çº§åˆ«ï¼ˆSã€Mã€Lã€XLï¼‰</t>
    <t id="9200">è°ƒè¯•è®¾ç½®</t>
    <t id="9201">å¯ç”¨è°ƒè¯•æ—¥å¿—ï¼š</t>
    <t id="9202">æ‰€æœ‰ debug_text è¾“å‡ºçš„ä¸»å¼€å…³ã€‚ç¦ç”¨æ—¶ï¼Œæ‰€æœ‰è°ƒè¯•æ—¥å¿—éƒ½è¢«æŠ‘åˆ¶ã€‚å¯ç”¨æ—¶ï¼Œè°ƒè¯•æ¶ˆæ¯æ ¹æ®å„ä¸ª debug_text æœºä¼šå€¼å‡ºçŽ°åœ¨ DebugLog ä¸­ã€‚</t>
    <t id="9220">ç»´æŠ¤å’Œè¯Šæ–­</t>
    <t id="9221">é‡ç½®åˆ©æ¶¦ç»Ÿè®¡ï¼š</t>
    <t id="9222">é‡ç½®</t>
    <t id="9223">æ¸…é™¤æ‰€æœ‰é»‘åå•æ‰‡åŒºï¼š</t>
    <t id="9224">æ¸…é™¤</t>
    <t id="9225">å°†æ‰€æœ‰è®¾ç½®é‡ç½®ä¸ºé»˜è®¤å€¼ï¼š</t>
    <t id="9226">å…¨éƒ¨é‡ç½®</t>
    <t id="9323">ä»Žå¨èƒæƒ…æŠ¥é»‘åå•ä¸­ç§»é™¤æ‰€æœ‰æ‰‡åŒºã€‚è¿™å°†ç«‹å³æ¸…é™¤æ‰€æœ‰é»‘åå•æ‰‡åŒºï¼Œå¹¶å…è®¸æ‚¨çš„èˆ°èˆ¹å‰å¾€ä¹‹å‰è¢«é˜»æŒ¡çš„åŒºåŸŸã€‚å¦‚æžœæ‚¨æƒ³é‡ç½®å¨èƒè§„é¿ç³»ç»Ÿæˆ–æ‰‡åŒºè¢«é”™è¯¯åœ°åˆ—å…¥é»‘åå•ï¼Œè¯·ä½¿ç”¨æ­¤åŠŸèƒ½ã€‚</t>
    <t id="9321">å°†æ‰€æœ‰é£žè¡Œå‘˜å’Œèˆ°èˆ¹çš„æ‰€æœ‰åˆ©æ¶¦ç»Ÿè®¡é‡ç½®ä¸º 0ã€‚åœ¨å‡çº§åˆ° v0.6.0 åŽä½¿ç”¨æ­¤åŠŸèƒ½ä»¥æ¸…é™¤åŸºäºŽæ”¶å…¥çš„è†¨èƒ€ç»Ÿè®¡ã€‚ä¿®å¤çŽ°åœ¨è·Ÿè¸ªå®žé™…åˆ©æ¶¦ï¼ˆæ”¶å…¥ - è´­ä¹°æˆæœ¬ï¼‰ã€‚è´¸æ˜“è®¡æ•°å’Œç»éªŒå€¼ä¿æŒä¸å˜ã€‚</t>
    <t id="9325">å°†æ‰€æœ‰å…¨å±€è®¾ç½®é‡ç½®ä¸ºå…¶é»˜è®¤å€¼ã€‚è¿™åŒ…æ‹¬ XP è®¾ç½®ã€èˆ°é˜Ÿåè°ƒã€é€šçŸ¥ã€ç§»åŠ¨æƒ…æŠ¥ã€å¨èƒè§„é¿ã€èˆ°èˆ¹å‘½åã€è‡ªåŠ¨ç»´ä¿®ã€ä¿®æ”¹ã€æ€§èƒ½å’Œæ•°å­—æ ¼å¼è®¾ç½®ã€‚è°ƒè¯•æ—¥å¿—è®¾ç½®ä¼šè¢«ä¿ç•™ï¼Œä»¥å…è®¸è®°å½•é‡ç½®æ“ä½œã€‚</t>
    <t id="9227">æ¸…é™¤æ‰€æœ‰èµ·å§‹æ‰‡åŒºçš„è´¸æ˜“ç¼“å­˜ï¼š</t>
    <t id="9228">æ¸…é™¤ç¼“å­˜</t>
    <t id="9327">æ¸…é™¤æ‰€æœ‰èµ·å§‹æ‰‡åŒºçš„è´¸æ˜“ç¼“å­˜ã€‚è¿™å°†å¼ºåˆ¶æ‰€æœ‰èˆ°èˆ¹åœ¨ä¸‹æ¬¡è´¸æ˜“æœç´¢æ—¶æ‰§è¡Œæ–°çš„å®žæ—¶æœç´¢ã€‚å¦‚æžœç¼“å­˜çœ‹èµ·æ¥è¿‡æ—¶æˆ–æŸåï¼Œæˆ–è€…æ‚¨æƒ³å¼ºåˆ¶å®Œå…¨åˆ·æ–°ç¼“å­˜ï¼Œè¯·ä½¿ç”¨æ­¤åŠŸèƒ½ã€‚</t>
    <t id="9229">é‡Šæ”¾æ‰€æœ‰æœç´¢é”å®š</t>
    <t id="9329">é‡Šæ”¾æ‰€æœ‰æ­£åœ¨è¿›è¡Œçš„è´¸æ˜“æœç´¢é”å®šå¹¶æ¸…é™¤ç›¸å…³çš„ä¸´æ—¶çŠ¶æ€ã€‚å¦‚æžœèˆ°èˆ¹ç”±äºŽæ—§å­˜æ¡£ä¸­çš„è¿‡æœŸé”å®šè€Œå¡åœ¨"æœç´¢è´¸æ˜“"çŠ¶æ€ï¼Œè¯·ä½¿ç”¨æ­¤åŠŸèƒ½ã€‚å¯èƒ½ä¼šä¸­æ–­åˆæ³•çš„æœç´¢ã€‚</t>
    <t id="9290">å¯¼å‡ºè´¸æ˜“ä¸­å¿ƒçŠ¶æ€ï¼š</t>
    <t id="9291">å¯¼å‡º</t>
    <t id="9390">æ˜¾ç¤ºé›†ä¸­è´¸æ˜“ä¸­å¿ƒçš„ä¸€æ¬¡æ€§å¿«ç…§ï¼ˆè°ƒåº¦å™¨é˜Ÿåˆ— + æœ€åŽè¯·æ±‚èˆ¹åªçŠ¶æ€ï¼‰åˆ°æ—¥å¿—å’Œé€šçŸ¥ä¸­ã€‚</t>
    <t id="9292">å¯¼å‡ºè´¸æ˜“ç¼“å­˜ï¼ˆå®Œæ•´ï¼‰ï¼š</t>
    <t id="9293">å¯¼å‡ºç¼“å­˜</t>
    <t id="9392">å®Œæ•´ç¼“å­˜å¯¼å‡ºï¼ˆå¯èƒ½å¾ˆå¤§ï¼‰ã€‚å°†æ‰€æœ‰ç¼“å­˜æ¡ç›®åˆ†å—å†™å…¥DebugLogã€‚å†æ¬¡ç‚¹å‡»å–æ¶ˆã€‚</t>
    <t id="9294">æ¸…é™¤è½¦é˜Ÿé¢„è®¢ï¼š</t>
    <t id="9295">æ¸…é™¤</t>
    <t id="9394">æ¸…é™¤æ‰€æœ‰æ´»è·ƒçš„è½¦é˜Ÿè´¸æ˜“é¢„è®¢ã€‚å¦‚æžœèˆ¹èˆ¶å¡åœ¨ç­‰å¾…é¢„è®¢äº¤æ˜“åˆ°æœŸï¼Œæˆ–è€…é¢„è®¢è¡¨åœ¨åŠ è½½æ—§ä¿å­˜åŽå˜å¾—é™ˆæ—§ï¼Œè¯·ä½¿ç”¨æ­¤é€‰é¡¹ã€‚</t>
    <t id="9230">æ€§èƒ½</t>
    <t id="9231">æ‰¹å¤„ç†å»¶è¿Ÿï¼š</t>
    <t id="9232">éªŒè¯å»¶è¿Ÿï¼š</t>
    <t id="9233">æœ€å¤§å¹¶å‘æœç´¢ï¼š</t>
    <t id="9234">æœ€å¤§è¿”å›žè´¸æ˜“æ•°ï¼š</t>
    <t id="9235">æ¯ä¸ªå•†å“çš„æœ€å¤§æŠ¥ä»·æ•°ï¼š</t>
    <t id="9236">æ¯ä¸ªå•†å“çš„æœ€å¤§è´¸æ˜“æ•°ï¼š</t>
    <t id="9237">åŒ¹é…æ—¶æ¯ä¸ªå•†å“çš„æœ€å¤§æŠ¥ä»·æ•°ï¼š</t>
    <t id="9238">æå‰é€€å‡ºé˜ˆå€¼ï¼š</t>
    <t id="9241">å®žæ—¶æŠ¥ä»·åˆ‡ç‰‡é—´éš”ï¼š</t>
    <t id="9266">æœç´¢é”å®š TTLï¼š</t>
    <t id="9263">æ‰¹å¤„ç†å—å¤§å°ï¼š</t>
    <t id="9239">æ•°å­—æ ¼å¼</t>
    <t id="9240">æ ¼å¼æ ·å¼ï¼š</t>
    <t id="9242">ä½¿ç”¨ M åŽç¼€</t>
    <t id="9243">M åŽç¼€é˜ˆå€¼ï¼š</t>
    <t id="9244">å¾·è¯­ (123.456,78)</t>
    <t id="9245">è‹±è¯­ (123,456.78)</t>
    <t id="9510">å‡çº§å¼¹çª—é€šçŸ¥ï¼š</t>
    <t id="9511">éœ€è¦åŸ¹è®­æé†’ï¼š</t>
    <t id="9512">åŸ¹è®­å®Œæˆé€šçŸ¥ï¼š</t>
    <t id="9513">åˆ©æ¶¦æŠ¥å‘Šï¼š</t>
    <t id="9514">å¸‚åœºæé†’ï¼š</t>
    <t id="9515">èˆ°é˜Ÿæ›´æ–°ï¼š</t>
    <t id="9516">ä»…ä½¿ç”¨æ™®é€š XP</t>
    <t id="9610">åœ¨çŽ©å®¶ç•Œé¢ä¸­å¯ç”¨æˆ–ç¦ç”¨äº¤æ˜“å‘˜å‡çº§å¼¹çª—é€šçŸ¥ã€‚</t>
    <t id="9611">å½“é£žè¡Œå‘˜éœ€è¦åŸ¹è®­ä»¥æ™‹å‡ä¸‹ä¸€çº§æ—¶æé†’ã€‚</t>
    <t id="9612">å½“é£žè¡Œå‘˜å®ŒæˆåŸ¹è®­å¹¶æ™‹å‡æ—¶é€šçŸ¥ã€‚</t>
    <t id="9613">å®šæœŸåˆ©æ¶¦æ‘˜è¦ï¼ˆç®€å•å’Œå®Œæ•´æŠ¥å‘Šï¼‰ã€‚</t>
    <t id="9614">ç‰¹æ®Šå¸‚åœºæœºä¼šå’Œé«˜ä»·å€¼äº¤æ˜“æé†’ã€‚</t>
    <t id="9615">èˆ°é˜Ÿåè°ƒæ¶ˆæ¯å’ŒçŠ¶æ€æ›´æ–°ã€‚</t>
    <t id="9616">ä½¿ç”¨ Pilot.skill.piloting å¹¶ç¦ç”¨ GT XP è¿›åº¦/ä¸Šé™ã€‚</t>
    <t id="9246">ç®€å•æŠ¥å‘Šé¢‘çŽ‡ï¼š</t>
    <t id="9247">å®Œæ•´æŠ¥å‘Šé¢‘çŽ‡ï¼š</t>
    <t id="9248">æœ€å¤§å¹¶å‘ç¼“å­˜æœç´¢ï¼š</t>
    <t id="9249">æœ€å¤§å¹¶å‘å®žæ—¶æœç´¢ï¼š</t>
    <t id="9340">é€‰æ‹©æ•°å­—æ ¼å¼ï¼šå¾·è¯­ä½¿ç”¨ '.' ä½œä¸ºåƒä½åˆ†éš”ç¬¦ï¼Œ',' ä½œä¸ºå°æ•°åˆ†éš”ç¬¦ (123.456,78)ï¼Œè‹±è¯­ä½¿ç”¨ ',' ä½œä¸ºåƒä½åˆ†éš”ç¬¦ï¼Œ'.' ä½œä¸ºå°æ•°åˆ†éš”ç¬¦ (123,456.78)</t>
    <t id="9342">ä¸ºå¤§äºŽé˜ˆå€¼çš„æ•°å­—å¯ç”¨ M åŽç¼€ï¼ˆä¾‹å¦‚ï¼Œ1.0 M è€Œä¸æ˜¯ 1,000,000ï¼‰</t>
    <t id="9343">M åŽç¼€çš„é˜ˆå€¼ã€‚å¤§äºŽæ­¤å€¼çš„æ•°å­—å°†æ˜¾ç¤º M åŽç¼€ï¼ˆé»˜è®¤å€¼ï¼š999,999ï¼‰</t>
    <t id="9346">ç®€å•æŠ¥å‘Šé¢‘çŽ‡ï¼ˆå¼¹å‡ºé€šçŸ¥ï¼‰ï¼š0-30 åˆ†é’Ÿï¼ˆ0 = ç¦ç”¨ - ç®€å•æŠ¥å‘Šå·²ç¦ç”¨ï¼Œé»˜è®¤å€¼ï¼š1 åˆ†é’Ÿï¼‰</t>
    <t id="9347">å®Œæ•´æŠ¥å‘Šé¢‘çŽ‡ï¼ˆæ—¥å¿—æ¡ç›®ï¼‰ï¼š0-60 åˆ†é’Ÿï¼ˆ0 = ç¦ç”¨ - å®Œæ•´æŠ¥å‘Šå·²ç¦ç”¨ï¼Œé»˜è®¤å€¼ï¼š30 åˆ†é’Ÿï¼‰</t>
    <t id="9398">ä½¿ç”¨ GT ç§¯åˆ†åˆ°æœŸè¦†ç›–</t>
    <t id="9399">åœ¨åŒä¸€ UI æ’æ§½ä¸­ç”¨ GT é¢„è®¡å€¼æ›¿æ¢æˆ–å¢žå¼ºåŽŸç‰ˆâ€œäº¤æ˜“äº§ç”Ÿçš„ CRâ€è¡Œã€‚</t>
    <t id="9331">è´¸æ˜“æœç´¢å¤„ç†æœŸé—´æ‰¹æ¬¡ä¹‹é—´çš„å»¶è¿Ÿï¼ˆ1-100 æ¯«ç§’ï¼‰ã€‚å€¼è¶Šé«˜å‡å°‘ CPU è´Ÿè½½ä½†å‡æ…¢è´¸æ˜“æœç´¢ã€‚é»˜è®¤å€¼ï¼š50 æ¯«ç§’ã€‚ç”¨äºŽæ‰¹å¤„ç†å™¨å’Œè´¸æ˜“åˆ—è¡¨è¿‡æ»¤ã€‚</t>
    <t id="9332">AI è„šæœ¬ä¸­è´¸æ˜“éªŒè¯ä¹‹é—´çš„å»¶è¿Ÿï¼ˆ1-100 æ¯«ç§’ï¼‰ã€‚å€¼è¶Šé«˜å‡å°‘ CPU è´Ÿè½½ä½†å‡æ…¢è´¸æ˜“éªŒè¯ã€‚é»˜è®¤å€¼ï¼š50 æ¯«ç§’ã€‚éªŒè¯æ¥è‡ª MD ç³»ç»Ÿçš„è´¸æ˜“åˆ—è¡¨æ—¶ä½¿ç”¨ã€‚</t>
    <t id="9333">å¯ä»¥åŒæ—¶è¿è¡Œçš„æœ€å¤§è´¸æ˜“æœç´¢æ•°ï¼ˆ1-10ï¼‰ã€‚å€¼è¶Šä½Žå‡å°‘ CPU è´Ÿè½½ä½†å¢žåŠ é˜Ÿåˆ—ç­‰å¾…æ—¶é—´ã€‚å€¼è¶Šé«˜æ›´å¿«å¤„ç†æœç´¢ä½†å¯èƒ½å¯¼è‡´æ€§èƒ½å³°å€¼ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9334">ä»Žç¼“å­˜æœç´¢è¿”å›žçš„æœ€å¤§è´¸æ˜“æ•°ï¼ˆ50-1000ï¼‰ã€‚å€¼è¶Šé«˜æä¾›æ›´å¤šè´¸æ˜“é€‰é¡¹ä½†å¢žåŠ å¤„ç†æ—¶é—´ã€‚å€¼è¶Šä½Žå‡å°‘ CPU è´Ÿè½½ä½†å¯èƒ½é”™è¿‡æœ‰åˆ©å¯å›¾çš„è´¸æ˜“ã€‚é»˜è®¤å€¼ï¼š200ã€‚</t>
    <t id="9335">å®žæ—¶æœç´¢ä¸­æ¯ä¸ªå•†å“è¦å¤„ç†çš„æœ€å¤§æŠ¥ä»·æ•°ï¼ˆ5-100ï¼‰ã€‚å€¼è¶Šé«˜è€ƒè™‘æ›´å¤šæŠ¥ä»·ä½†å¢žåŠ å¤„ç†æ—¶é—´ã€‚å€¼è¶Šä½Žå‡å°‘ CPU è´Ÿè½½ä½†å¯èƒ½é”™è¿‡æœ‰åˆ©å¯å›¾çš„è´¸æ˜“ã€‚é»˜è®¤å€¼ï¼š20ã€‚</t>
    <t id="9336">æ‰¹å¤„ç†æœŸé—´æ¯ä¸ªå•†å“çš„æœ€å¤§è´¸æ˜“æ•°ï¼ˆ5-100ï¼‰ã€‚å€¼è¶Šé«˜å…è®¸æ¯ä¸ªå•†å“æ›´å¤šè´¸æ˜“ä½†å¢žåŠ å¤„ç†æ—¶é—´ã€‚å€¼è¶Šä½Žå‡å°‘ CPU è´Ÿè½½ä½†å¯èƒ½é”™è¿‡æœ‰åˆ©å¯å›¾çš„è´¸æ˜“ã€‚é»˜è®¤å€¼ï¼š20ã€‚</t>
    <t id="9337">æ‰¹å¤„ç†å™¨ä¸­åŒ¹é…æ—¶æ¯ä¸ªå•†å“çš„æœ€å¤§æŠ¥ä»·æ•°ï¼ˆ5-100ï¼‰ã€‚å€¼è¶Šé«˜è€ƒè™‘æ›´å¤šæŠ¥ä»·ä½†å¢žåŠ å¤„ç†æ—¶é—´ã€‚å€¼è¶Šä½Žå‡å°‘ CPU è´Ÿè½½ä½†å¯èƒ½é”™è¿‡æœ‰åˆ©å¯å›¾çš„è´¸æ˜“ã€‚é»˜è®¤å€¼ï¼š20ã€‚</t>
    <t id="9338">æ‰¹å¤„ç†çš„æå‰é€€å‡ºé˜ˆå€¼ï¼ˆ100-10000ï¼‰ã€‚å½“æ‰¾åˆ°è¿™ä¹ˆå¤šè´¸æ˜“æ—¶ï¼Œæ‰¹å¤„ç†æå‰åœæ­¢ä»¥èŠ‚çœ CPUã€‚å€¼è¶Šé«˜å¤„ç†æ›´å¤šè´¸æ˜“ä½†å¢žåŠ  CPU è´Ÿè½½ã€‚å€¼è¶Šä½Žæ›´æ—©é€€å‡ºä½†å¯èƒ½é”™è¿‡æœ‰åˆ©å¯å›¾çš„è´¸æ˜“ã€‚é»˜è®¤å€¼ï¼š2000ã€‚</t>
    <t id="9341">å®žæ—¶æŠ¥ä»·åˆ‡ç‰‡é—´éš”ï¼ˆæ¯«ç§’ï¼‰(5-500ms)ã€‚æŽ§åˆ¶å®žæ—¶æŠ¥ä»·åˆ‡ç‰‡å¯ä»¥å¼€å§‹çš„é¢‘çŽ‡ã€‚æ›´ä½Žçš„å€¼å…è®¸æ›´å¿«çš„æŠ¥ä»·æ”¶é›†ä½†å¢žåŠ  CPU è´Ÿè½½ã€‚æ›´é«˜çš„å€¼å‡å°‘ CPU è´Ÿè½½ä½†å‡æ…¢å®žæ—¶æœç´¢å¤„ç†ã€‚é»˜è®¤å€¼ï¼š500msã€‚</t>
    <t id="9363">æ‰¹å¤„ç†å—å¤§å° (5-20)ã€‚æ¯ä¸ªå—å¤„ç† chunkSizeÃ—chunkSize ç»„åˆï¼ˆä¾‹å¦‚ï¼Œ10Ã—10 = 100 ç»„åˆï¼‰ã€‚æ›´å¤§çš„å—æé«˜åžåé‡ä½†å¢žåŠ æ¯ä¸ªå—çš„ CPU è´Ÿè½½ã€‚æ›´å°çš„å—å‡å°‘ CPU å³°å€¼ä½†éœ€è¦æ›´å¤šç»§ç»­ã€‚é»˜è®¤å€¼ï¼š10ã€‚</t>
    <t id="9348">å¯ä»¥åŒæ—¶è¿è¡Œçš„æœ€å¤§ç¼“å­˜æœç´¢æ•°ï¼ˆ1-20ï¼‰ã€‚ç¼“å­˜æœç´¢å¿«é€Ÿä¸”æˆæœ¬ä½Žï¼Œå› æ­¤æ›´é«˜çš„å€¼å…è®¸æ›´å¤šå¹¶è¡Œç¼“å­˜æ£€æŸ¥è€Œä¸ä¼šæ˜¾è‘—å½±å“ CPUã€‚è¾ƒä½Žçš„å€¼å‡å°‘å¹¶è¡Œç¼“å­˜æœç´¢ã€‚é»˜è®¤å€¼ï¼š5ã€‚</t>
    <t id="9349">å¯ä»¥åŒæ—¶è¿è¡Œçš„æœ€å¤§å®žæ—¶æœç´¢æ•°ï¼ˆ1-10ï¼‰ã€‚å®žæ—¶æœç´¢æ˜¯ CPU å¯†é›†åž‹çš„ï¼Œå› æ­¤è¾ƒä½Žçš„å€¼å‡å°‘ CPU è´Ÿè½½ä½†å¢žåŠ é˜Ÿåˆ—ç­‰å¾…æ—¶é—´ã€‚è¾ƒé«˜çš„å€¼æ›´å¿«å¤„ç†æœç´¢ä½†å¯èƒ½å¯¼è‡´æ€§èƒ½å³°å€¼ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9264">ç¼“å­˜æŸ¥è¯¢å—å¤§å°ï¼š</t>
    <t id="9265">å®žæ—¶æŠ¥ä»·è¿½åŠ å—å¤§å°ï¼š</t>
    <t id="9364">æ¯ä¸ªå—éªŒè¯çš„ç¼“å­˜æ¡ç›®ï¼ˆ10-200ï¼‰ã€‚è¾ƒå°çš„å€¼å°†ç¼“å­˜éªŒè¯åˆ†æ•£åˆ°æ›´å¤šå¸§ï¼ˆæ›´å¹³æ»‘ï¼‰ï¼Œä½†å¯èƒ½å¢žåŠ æ‰¾åˆ°ç¼“å­˜è´¸æ˜“çš„æ—¶é—´ã€‚é»˜è®¤å€¼ï¼š10ã€‚</t>
    <t id="9365">æ¯ä¸ªè¿½åŠ åˆ‡ç‰‡è¿½åŠ çš„æŠ¥ä»·ï¼ˆ50-2000ï¼‰ã€‚è¾ƒå°çš„å€¼å‡å°‘æ¯å¸§çš„åˆ—è¡¨è¿½åŠ å·¥ä½œï¼ˆæ›´å¹³æ»‘ï¼‰ï¼Œä½†å¯èƒ½å‡æ…¢å®žæ—¶æœç´¢å®Œæˆã€‚é»˜è®¤å€¼ï¼š200ã€‚</t>
    <t id="9366">æœç´¢é”å®šç”Ÿå­˜æ—¶é—´ï¼ˆç§’ï¼‰(60-7200)ã€‚å¦‚æžœèˆ°èˆ¹è¢«æ‹’ç»"è´¸æ˜“æœç´¢å·²åœ¨è¿›è¡Œä¸­"çš„æ—¶é—´è¶…è¿‡æ­¤å€¼ï¼ŒGT å°†é€šè¿‡æ¸…é™¤è¿‡æ—¶çš„æœç´¢çŠ¶æ€å¹¶é‡Šæ”¾é”å®šæ¥è‡ªæˆ‘ä¿®å¤ã€‚é»˜è®¤å€¼ï¼š600ç§’ã€‚</t>
    <t id="9370">æ‰¹å¤„ç†ååŽ‹è½¯é˜ˆå€¼ï¼š</t>
    <t id="9371">æ‰¹å¤„ç†ååŽ‹ç¡¬é˜ˆå€¼ï¼š</t>
    <t id="9372">æ¯ç‰‡æ®µçš„æ‰‡åŒºæ•°ï¼š</t>
    <t id="9373">ä¸»æ‰‡åŒºåˆ·æ–°å†·å´æ—¶é—´ï¼š</t>
    <t id="9374">ç¼“å­˜æœªå‘½ä¸­åŸºç¡€å†·å´æ—¶é—´ï¼š</t>
    <t id="9375">è°ƒåº¦å™¨æ»´ç­”é—´éš”ï¼š</t>
    <t id="9376">æ¯æ»´ç­”æœ€å¤§ç¼“å­˜æŸ¥è¯¢æ•°ï¼š</t>
    <t id="9377">æ¯æ»´ç­”æœ€å¤§æœç´¢å»¶ç»­æ•°ï¼š</t>
    <t id="9378">æ¯æ»´ç­”æœ€å¤§èˆ°èˆ¹æ•°ï¼š</t>
    <t id="9379">æ¯æ»´ç­”æœ€å¤§é¡¹ç›®æ•°ï¼š</t>
    <t id="9380">æ¯æ»´ç­”æœ€å¤§å”¤é†’æ•°ï¼š</t>
    <t id="9381">ç¼“å­˜æŸ¥è¯¢æœ€å¤§æ¡ç›®æ•°ï¼š</t>
    <t id="9382">è¿‡æ—¶é˜ˆå€¼ï¼ˆç§’ï¼‰ï¼š</t>
    <t id="9383">é˜Ÿåˆ—è¿‡æ—¶é˜ˆå€¼ï¼ˆç§’ï¼‰ï¼š</t>
    <t id="9384">å¤±è´¥äº¤æ˜“è¿‡æœŸæ—¶é—´ï¼ˆç§’ï¼‰ï¼š</t>
    <t id="9385">æœ€å¤§å¹¶å‘åŽå¤‡æœç´¢ï¼š</t>
    <t id="9386">æœ€å¤§å¹¶å‘åŽå¤‡æœç´¢ï¼š</t>
    <t id="9470">æ‰¹å¤„ç†å™¨ç§¯åŽ‹çš„è½¯é˜ˆå€¼ (5-50)ã€‚å½“ç§¯åŽ‹è¾¾åˆ°æ­¤å€¼æ—¶ï¼Œå¼€å§‹åº”ç”¨ååŽ‹ä»¥å‡æ…¢æ–°çš„æœç´¢è¯·æ±‚ã€‚è¾ƒä½Žçš„å€¼ä¼šæ›´å¿«è§¦å‘ååŽ‹ï¼ˆæ›´ä¿å®ˆï¼‰ã€‚é»˜è®¤å€¼ï¼š10ã€‚</t>
    <t id="9471">æ‰¹å¤„ç†å™¨ç§¯åŽ‹çš„ç¡¬é˜ˆå€¼ (10-100)ã€‚å½“ç§¯åŽ‹è¾¾åˆ°æ­¤å€¼æ—¶ï¼Œæ–°çš„å®žæ—¶æœç´¢å°†è¢«é˜»æ­¢ï¼Œç›´åˆ°ç§¯åŽ‹å‡å°‘ã€‚è¾ƒä½Žçš„å€¼ä¼šæ›´å¿«é˜»æ­¢æœç´¢ï¼ˆæ›´ä¿å®ˆï¼‰ã€‚é»˜è®¤å€¼ï¼š25ã€‚</t>
    <t id="9472">å®žæ—¶æŠ¥ä»·æ”¶é›†ä¸­æ¯ä¸ªç‰‡æ®µå¤„ç†çš„æ‰‡åŒº (1-5)ã€‚è¾ƒä½Žçš„å€¼å°†å·¥ä½œåˆ†æ•£åˆ°æ›´å¤šå¸§ï¼ˆæ›´å¹³æ»‘ï¼‰ï¼Œä½†å¯èƒ½å‡æ…¢æŠ¥ä»·æ”¶é›†ã€‚è¾ƒé«˜çš„å€¼å¤„ç†æ›´å¿«ï¼Œä½†å¯èƒ½å¯¼è‡´å¸§å³°å€¼ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9473">ä¸»æ‰‡åŒºåˆ·æ–°å®ŒæˆåŽçš„å†·å´æ—¶é—´ (10-120ç§’)ã€‚é˜²æ­¢è¿‡å¤šçš„åˆ·æ–°è¯·æ±‚ã€‚è¾ƒä½Žçš„å€¼å…è®¸æ›´é¢‘ç¹çš„åˆ·æ–°ï¼Œä½†ä¼šå¢žåŠ  CPU è´Ÿè½½ã€‚è¾ƒé«˜çš„å€¼å‡å°‘åˆ·æ–°é¢‘çŽ‡ï¼Œä½†å¯èƒ½å»¶è¿Ÿç¼“å­˜æ›´æ–°ã€‚é»˜è®¤å€¼ï¼š30ç§’ã€‚</t>
    <t id="9474">ç¼“å­˜æœªå‘½ä¸­åŽé‡è¯•å®žæ—¶æœç´¢å‰çš„åŸºç¡€å†·å´æ—¶é—´ (1-30ç§’)ã€‚é˜²æ­¢è¿‡å¤šçš„é‡è¯•å°è¯•ã€‚è¾ƒä½Žçš„å€¼ä¼šæ›´æ—©é‡è¯•ï¼Œä½†ä¼šå¢žåŠ  CPU è´Ÿè½½ã€‚è¾ƒé«˜çš„å€¼å‡å°‘é‡è¯•é¢‘çŽ‡ï¼Œä½†å¯èƒ½å»¶è¿Ÿäº¤æ˜“æŸ¥æ‰¾ã€‚é»˜è®¤å€¼ï¼š10ç§’ã€‚</t>
    <t id="9475">è°ƒåº¦å™¨æ»´ç­”ä¹‹é—´çš„é—´éš”ï¼ˆæ¯«ç§’ï¼‰(50-500ms)ã€‚æŽ§åˆ¶è°ƒåº¦å™¨å¤„ç†å·¥ä½œé˜Ÿåˆ—çš„é¢‘çŽ‡ã€‚è¾ƒä½Žçš„å€¼æ›´é¢‘ç¹åœ°å¤„ç†ï¼Œä½†ä¼šå¢žåŠ  CPU è´Ÿè½½ã€‚è¾ƒé«˜çš„å€¼å‡å°‘ CPU è´Ÿè½½ï¼Œä½†å¯èƒ½å¢žåŠ é˜Ÿåˆ—ç­‰å¾…æ—¶é—´ã€‚é»˜è®¤å€¼ï¼š100msã€‚</t>
    <t id="9476">æ¯ä¸ªè°ƒåº¦å™¨æ»´ç­”å¯åŠ¨çš„æœ€å¤§ç¼“å­˜æŸ¥è¯¢æ•° (1-5)ã€‚é™åˆ¶ç¼“å­˜æŸ¥è¯¢é€ŸçŽ‡ä»¥é˜²æ­¢å¸§é˜»å¡žã€‚è¾ƒä½Žçš„å€¼å‡å°‘ CPU å³°å€¼ï¼Œä½†å‡æ…¢ç¼“å­˜æœç´¢ã€‚è¾ƒé«˜çš„å€¼å¤„ç†æ›´å¿«ï¼Œä½†å¯èƒ½å¯¼è‡´å¡é¡¿ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9477">æ¯ä¸ªè°ƒåº¦å™¨æ»´ç­”å¯åŠ¨çš„æœ€å¤§æœç´¢å»¶ç»­æ•° (1-5)ã€‚é™åˆ¶å»¶ç»­é€ŸçŽ‡ä»¥é˜²æ­¢å¸§é˜»å¡žã€‚è¾ƒä½Žçš„å€¼å‡å°‘ CPU å³°å€¼ï¼Œä½†å‡æ…¢æœç´¢å¤„ç†ã€‚è¾ƒé«˜çš„å€¼å¤„ç†æ›´å¿«ï¼Œä½†å¯èƒ½å¯¼è‡´å¡é¡¿ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9478">æ¯ä¸ªè°ƒåº¦å™¨æ»´ç­”å¤„ç†çš„æœ€å¤§èˆ°èˆ¹æ•° (1-5)ã€‚é™åˆ¶èˆ°èˆ¹å¤„ç†é€ŸçŽ‡ä»¥é˜²æ­¢å¸§é˜»å¡žã€‚è¾ƒä½Žçš„å€¼å‡å°‘ CPU å³°å€¼ï¼Œä½†å‡æ…¢é˜Ÿåˆ—å¤„ç†ã€‚è¾ƒé«˜çš„å€¼å¤„ç†æ›´å¿«ï¼Œä½†å¯èƒ½å¯¼è‡´å¡é¡¿ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9479">æ¯ä¸ªè°ƒåº¦å™¨æ»´ç­”å¤„ç†çš„æœ€å¤§å·¥ä½œé¡¹ç›®æ•° (1-5)ã€‚é™åˆ¶é¡¹ç›®å¤„ç†é€ŸçŽ‡ä»¥é˜²æ­¢å¸§é˜»å¡žã€‚è¾ƒä½Žçš„å€¼å‡å°‘ CPU å³°å€¼ï¼Œä½†å‡æ…¢é˜Ÿåˆ—å¤„ç†ã€‚è¾ƒé«˜çš„å€¼å¤„ç†æ›´å¿«ï¼Œä½†å¯èƒ½å¯¼è‡´å¡é¡¿ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9480">æ¯ä¸ªè°ƒåº¦å™¨æ»´ç­”å”¤é†’çš„æœ€å¤§ç­‰å¾…æ•° (1-10)ã€‚é™åˆ¶å”¤é†’é€ŸçŽ‡ä»¥é˜²æ­¢é˜Ÿåˆ—ä¸­æœ‰è®¸å¤šç­‰å¾…æ—¶å‡ºçŽ° CPU å³°å€¼ã€‚è¾ƒä½Žçš„å€¼å‡å°‘ CPU å³°å€¼ï¼Œä½†å‡æ…¢ç­‰å¾…å¤„ç†ã€‚è¾ƒé«˜çš„å€¼å¤„ç†æ›´å¿«ï¼Œä½†å¯èƒ½å¯¼è‡´å¡é¡¿ã€‚é»˜è®¤å€¼ï¼š2ã€‚</t>
    <t id="9481">æ¯æ‰¹æŸ¥è¯¢çš„æœ€å¤§ç¼“å­˜æ¡ç›®æ•° (1-200)ã€‚æŽ§åˆ¶ç¼“å­˜æŸ¥è¯¢æ‰¹æ¬¡å¤§å°ã€‚è¾ƒä½Žçš„å€¼ä½¿ç¼“å­˜æœç´¢æ›´å¿«ï¼Œä½†å¯èƒ½é”™è¿‡æ›´å¥½çš„äº¤æ˜“ã€‚è¾ƒé«˜çš„å€¼è€ƒè™‘æ›´å¤šç¼“å­˜äº¤æ˜“ï¼Œä½†å¢žåŠ éªŒè¯æ—¶é—´ã€‚é»˜è®¤å€¼ï¼š50ã€‚</t>
    <t id="9482">å®žæ—¶æœç´¢çŠ¶æ€è¿‡æ—¶é˜ˆå€¼ï¼ˆç§’ï¼‰(60-600)ã€‚å½“å®žæ—¶æœç´¢çŠ¶æ€æ¯”æ­¤å€¼æ›´æ—§æ—¶ï¼Œå®ƒè¢«è§†ä¸ºè¿‡æ—¶å¹¶è¢«æ¸…é™¤ã€‚è¾ƒä½Žçš„å€¼æ›´æ—©æ¸…é™¤è¿‡æ—¶çŠ¶æ€ï¼Œä½†å¯èƒ½ä¸­æ–­åˆæ³•æœç´¢ã€‚è¾ƒé«˜çš„å€¼å…è®¸æ›´é•¿çš„æœç´¢ï¼Œä½†å¯èƒ½ç•™ä¸‹è¿‡æ—¶çŠ¶æ€ã€‚é»˜è®¤å€¼ï¼š300ç§’ã€‚</t>
    <t id="9483">é˜Ÿåˆ—é¡¹ç›®è¿‡æ—¶é˜ˆå€¼ï¼ˆç§’ï¼‰(30-300)ã€‚å½“é˜Ÿåˆ—é¡¹ç›®æ¯”æ­¤å€¼æ›´æ—§æ—¶ï¼Œå®ƒä»¬è¢«è§†ä¸ºè¿‡æ—¶å¹¶è¢«åˆ é™¤ã€‚è¾ƒä½Žçš„å€¼æ›´æ—©æ¸…é™¤è¿‡æ—¶é¡¹ç›®ï¼Œä½†å¯èƒ½åˆ é™¤åˆæ³•çš„é˜Ÿåˆ—é¡¹ç›®ã€‚è¾ƒé«˜çš„å€¼å…è®¸æ›´é•¿çš„é˜Ÿåˆ—æ—¶é—´ï¼Œä½†å¯èƒ½ç•™ä¸‹è¿‡æ—¶é¡¹ç›®ã€‚é»˜è®¤å€¼ï¼š60ç§’ã€‚</t>
    <t id="9484">å¤±è´¥äº¤æ˜“ç¼“å­˜è¿‡æœŸæ—¶é—´ï¼ˆç§’ï¼‰(300-3600)ã€‚å¤±è´¥äº¤æ˜“è¢«ç¼“å­˜ä»¥é¿å…ç«‹å³é‡è¯•ã€‚è¾ƒä½Žçš„å€¼ä½¿å¤±è´¥äº¤æ˜“æ›´æ—©è¿‡æœŸï¼ˆæ›´å¤šé‡è¯•ï¼‰ï¼Œä½†é™ä½Žç¼“å­˜æœ‰æ•ˆæ€§ã€‚è¾ƒé«˜çš„å€¼ç¼“å­˜æ›´é•¿æ—¶é—´ï¼ˆæ›´å°‘é‡è¯•ï¼‰ï¼Œä½†å¯èƒ½å»¶è¿Ÿé‡è¯•å°è¯•ã€‚é»˜è®¤å€¼ï¼š1800ç§’ï¼ˆ30åˆ†é’Ÿï¼‰ã€‚</t>
    <t id="9485">æœ€å¤§å¹¶å‘åŽå¤‡å®žæ—¶æœç´¢ (1-10)ã€‚åŽå¤‡æœç´¢ç»•è¿‡ä¸»æ‰‡åŒºé”å®šï¼Œå…è®¸å¤šä¸ªæ¥è‡ªåŒä¸€ä¸»æ‰‡åŒºçš„èˆ°èˆ¹åŒæ—¶æœç´¢ã€‚è¾ƒä½Žçš„å€¼å‡å°‘CPUè´Ÿè½½ï¼Œä½†å¯èƒ½å‡æ…¢åŽå¤‡æœç´¢ã€‚è¾ƒé«˜çš„å€¼å…è®¸æ›´å¤šå¹¶è¡ŒåŽå¤‡æœç´¢ï¼Œä½†å¢žåŠ CPUä½¿ç”¨ã€‚é»˜è®¤å€¼ï¼š1ã€‚</t>
    <t id="9490">å‘é£žèˆ¹å‘é€ GT_Trade_Found ä¿¡å·å‰çš„å»¶è¿Ÿï¼ˆæ¯«ç§’ï¼‰(0-1000ms)ã€‚0 = ç«‹å³ä¼ é€’ï¼ˆæŽ¨èç”¨äºŽå¯é æ€§ - æ¶ˆé™¤ç«žäº‰æ¡ä»¶ï¼‰ã€‚é£žèˆ¹åœ¨å‘é€æ–°è¯·æ±‚å‰æ€»æ˜¯ç­‰å¾…ï¼ˆé…ç½®çš„å»¶è¿Ÿ + 5ms ç¼“å†²ï¼‰ä»¥æ•èŽ·å»¶è¿Ÿçš„ä¿¡å·ã€‚è¾ƒé«˜çš„å€¼åœ¨å¸§ä¹‹é—´åˆ†é…ä¿¡å·ä»¥èŽ·å¾—æ›´æµç•…çš„æ€§èƒ½ã€‚é»˜è®¤å€¼ï¼š0msã€‚</t>
    <t id="9590">å‘é£žèˆ¹å‘é€ GT_Trade_Found ä¿¡å·å‰çš„å»¶è¿Ÿï¼ˆæ¯«ç§’ï¼‰(10-1000ms)ã€‚é£žèˆ¹åœ¨å‘é€æ–°è¯·æ±‚å‰æ€»æ˜¯ç­‰å¾…ï¼ˆé…ç½®çš„å»¶è¿Ÿ + 5ms ç¼“å†²ï¼‰ä»¥æ•èŽ·å»¶è¿Ÿçš„ä¿¡å·ã€‚è¾ƒé«˜çš„å€¼åœ¨å¸§ä¹‹é—´åˆ†é…ä¿¡å·ä»¥èŽ·å¾—æ›´æµç•…çš„æ€§èƒ½ã€‚é»˜è®¤å€¼ï¼š10msã€‚</t>
    <t id="8000">GalaxyTrader èˆ°é˜Ÿ</t>
    <t id="8001">GalaxyTrader èˆ°é˜Ÿç®¡ç†å’Œé£žè¡Œå‘˜ç»Ÿè®¡</t>
    <t id="8002">æŸ¥çœ‹å’Œç®¡ç†æ‰€æœ‰ GalaxyTrader é£žè¡Œå‘˜</t>
    <t id="8100">èˆ°èˆ¹ ID</t>
    <t id="8101">é£žè¡Œå‘˜</t>
    <t id="8102">èˆ°èˆ¹</t>
    <t id="8103">çŠ¶æ€</t>
    <t id="8104">ç­‰çº§</t>
    <t id="8105">çº§åˆ«</t>
    <t id="8106">ç»éªŒå€¼</t>
    <t id="8107">ç»ˆèº«åˆ©æ¶¦</t>
    <t id="8108">ä½ç½®</t>
    <t id="8109">ä¸»åŸºåœ°</t>
    <t id="8110">æœ€åŽè´¸æ˜“</t>
    <t id="8111">é£žè¡Œå‘˜åˆ©æ¶¦</t>
    <t id="8112">èˆ°èˆ¹åˆ©æ¶¦</t>
    <t id="8113">è´¸æ˜“è®¡æ•°</t>
    <t id="8200">åˆ·æ–°</t>
    <t id="8201">å¯¼å‡º CSV</t>
    <t id="8202">ç»Ÿè®¡</t>
    <t id="8203">è®¾ç½®</t>
    <t id="8204">å¸®åŠ©</t>
    <t id="8205">å…³é—­</t>
    <t id="8300">æ‰€æœ‰é£žè¡Œå‘˜</t>
    <t id="8301">è´¸æ˜“ä¸­</t>
    <t id="8302">è®­ç»ƒä¸­</t>
    <t id="8303">ç»´æŠ¤ä¸­</t>
    <t id="8304">ç´§æ€¥</t>
    <t id="8305">åˆå­¦è€…ï¼ˆ1-5 çº§ï¼‰</t>
    <t id="8306">é«˜çº§ï¼ˆ6-11 çº§ï¼‰</t>
    <t id="8307">ä¸“å®¶ï¼ˆ12 çº§ä»¥ä¸Šï¼‰</t>
    <t id="8308">å‰ 10 åæ”¶å…¥è€…</t>
    <t id="8350">æŽ’åºæ–¹å¼ï¼š</t>
    <t id="8351">èˆ°èˆ¹ ID</t>
    <t id="8352">é£žè¡Œå‘˜åç§°</t>
    <t id="8353">èˆ°èˆ¹ç±»åž‹</t>
    <t id="8354">çŠ¶æ€</t>
    <t id="8355">ç­‰çº§</t>
    <t id="8356">çº§åˆ«</t>
    <t id="8357">ç»éªŒå€¼</t>
    <t id="8358">åˆ©æ¶¦</t>
    <t id="8400">æœªæ³¨å†Œé£žè¡Œå‘˜</t>
    <t id="8401">æ²¡æœ‰é£žè¡Œå‘˜åŒ¹é…è¿‡æ»¤å™¨</t>
    <t id="8402">æ€»é£žè¡Œå‘˜æ•°ï¼š</t>
    <t id="8403">æ€»èˆ°é˜Ÿåˆ©æ¶¦ï¼š</t>
    <t id="8404">æœ€åŽæ›´æ–°ï¼š</t>
    <t id="8405">æœç´¢é£žè¡Œå‘˜...</t>
    <t id="8114">æ‰‡åŒº</t>
    <t id="8320">èˆ°èˆ¹é‡å‘½å</t>
    <t id="8321">è‡ªå®šä¹‰åç§°</t>
    <t id="8322">è®¾ç½®åç§°</t>
    <t id="8323">æ¸…é™¤åç§°</t>
    <t id="8324">åç§°è®¾ç½®æˆåŠŸ</t>
    <t id="8325">åç§°æ¸…é™¤æˆåŠŸ</t>
    <t id="8450">é€åŽ»è®­ç»ƒ</t>
    <t id="8451">æ³¨é”€</t>
    <t id="8452">å¼ºåˆ¶å‡ºå”®è´§ç‰©</t>
    <t id="8453">é€åŽ»ç»´ä¿®</t>
    <t id="8454">é€åŽ»è¡¥å……</t>
    <t id="8455">åœæ­¢æ‰€æœ‰è®¢å•</t>
    <t id="8456">æ“ä½œ</t>
    <t id="8500">ç‚¹å‡»æŒ‰èˆ°èˆ¹ ID æŽ’åº</t>
    <t id="8501">ç‚¹å‡»æŒ‰é£žè¡Œå‘˜åç§°æŽ’åº</t>
    <t id="8502">ç‚¹å‡»æŒ‰èˆ°èˆ¹ç±»åž‹æŽ’åº</t>
    <t id="8503">ç‚¹å‡»æŒ‰çŠ¶æ€æŽ’åº</t>
    <t id="8504">ç‚¹å‡»æŒ‰ç­‰çº§æŽ’åº</t>
    <t id="8505">ç‚¹å‡»æŒ‰çº§åˆ«æŽ’åº</t>
    <t id="8506">ç‚¹å‡»æŒ‰ç»éªŒå€¼æŽ’åº</t>
    <t id="8507">ç‚¹å‡»æŒ‰ç»ˆèº«åˆ©æ¶¦æŽ’åº</t>
    <t id="8508">ä»Žä»»åŠ¡ç³»ç»Ÿåˆ·æ–°é£žè¡Œå‘˜æ•°æ®</t>
    <t id="8509">å°†å½“å‰è§†å›¾å¯¼å‡ºåˆ° CSV æ–‡ä»¶</t>
    <t id="8510">æŸ¥çœ‹èˆ°é˜Ÿç»Ÿè®¡å’Œå›¾è¡¨</t>
    <t id="8511">é…ç½®èœå•è®¾ç½®</t>
    <t id="8512">æ˜¾ç¤ºå¸®åŠ©å’Œé”®ç›˜å¿«æ·é”®</t>
    <t id="8600">æœªæ‰¾åˆ° GalaxyTrader é£žè¡Œå‘˜</t>
    <t id="8601">é€šè¿‡å°†èˆ°èˆ¹åˆ†é…ç»™ GalaxyTrader åˆ›å»ºé£žè¡Œå‘˜ï¼Œæˆ–ç­‰å¾…æ•°æ®åŠ è½½ã€‚</t>
    <t id="9001">GT é‡å‘½å</t>
    <t id="9902">é€åŽ»è®­ç»ƒ</t>
    <t id="9903">å·²ä¸º %1 æŽ’å…¥æ‰‹åŠ¨è®­ç»ƒé˜Ÿåˆ—ã€‚é£žè¡Œå‘˜å°†åœ¨å½“å‰å¾ªçŽ¯ç»“æŸåŽå¼€å§‹è®­ç»ƒã€‚</t>
    <t id="9904">è®­ç»ƒå·²æŽ’é˜Ÿï¼Œå°†åœ¨å½“å‰å¾ªçŽ¯åŽå¼€å§‹</t>
    <t id="9905">æœªæ‰¾åˆ°é£žè¡Œå‘˜æˆ–èˆ°èˆ¹</t>
    <t id="9906">è‡ªåŠ¨è®­ç»ƒå·²å¯ç”¨ - æ— éœ€æ‰‹åŠ¨æŽ’é˜Ÿ</t>
    <t id="9907">é£žè¡Œå‘˜æœªå¤„äºŽè®­ç»ƒé˜»å¡žçŠ¶æ€</t>
    <t id="9910">äº¤æ˜“å­¦é™¢</t>
    <t id="9911">å­¦å¾’ï¼ˆ4 çº§ï¼‰- %1 / %2</t>
    <t id="9912">äº¤æ˜“è€…ï¼ˆ7 çº§ï¼‰- %1 / %2</t>
    <t id="9913">äº¤æ˜“å¤§å¸ˆ (Lvl 13) - %1 / %2</t>
    <t id="9920">é£žè¡Œå‘˜ %1 å‚åŠ äº† %2 çº§çš„å­¦é™¢è¯¾ç¨‹ã€‚å‡ºå‘å‰å¾€æœ€è¿‘çš„è´¸æ˜“ç«™ã€‚</t>
    <t id="9921">æœ¬è¯¾ç¨‹èµ„é‡‘ä¸è¶³ï¼ˆéœ€è¦ %1ï¼Œæœ‰ %2ï¼‰ã€‚</t>
    <t id="9922">è¯¾ç¨‹ä¸å¯ç”¨ - é£žè¡Œå‘˜ %1 å·²è¾¾åˆ°æˆ–é«˜äºŽæ­¤çº§åˆ«ã€‚</t>
    <t id="9923">é£žè¡Œå‘˜ %1 åœ¨ %5 ä¸Šå‚åŠ äº†äº¤æ˜“å­¦é™¢çº§åˆ« %2 è¯¾ç¨‹ï¼ˆè´¹ç”¨ï¼š%3 Crï¼ŒæŒç»­æ—¶é—´ï¼š%4 åˆ†é’Ÿï¼‰ã€‚</t>
    <t id="11011">GT å­¦å¾’ä¸­åž‹èˆ°èˆ¹å‡é€Ÿå™¨</t>
    <t id="11012">ä¸ºä¸­åž‹èˆ°èˆ¹ä¸Šç»éªŒä¸è¶³çš„é£žè¡Œå‘˜ç•¥å¾®é™ä½Žæ€§èƒ½çš„å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-5% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="11013">GT å­¦å¾’ä¸­åž‹æ—…è¡Œå‡é€Ÿå™¨</t>
    <t id="11014">ä¸ºä¸­åž‹èˆ°èˆ¹ä¸Šç»éªŒä¸è¶³çš„é£žè¡Œå‘˜ç•¥å¾®é™ä½Žæ—…è¡Œæ€§èƒ½çš„å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-5% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="11021">GT å­¦å¾’å¤§åž‹èˆ°èˆ¹å‡é€Ÿå™¨</t>
    <t id="11022">ä¸ºå¤§åž‹èˆ°èˆ¹ä¸Šç»éªŒä¸è¶³çš„é£žè¡Œå‘˜é™ä½Žæ€§èƒ½çš„å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-15% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="11023">GT å­¦å¾’å¤§åž‹æ—…è¡Œå‡é€Ÿå™¨</t>
    <t id="11024">ä¸ºå¤§åž‹èˆ°èˆ¹ä¸Šç»éªŒä¸è¶³çš„é£žè¡Œå‘˜é™ä½Žæ—…è¡Œæ€§èƒ½çš„å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-15% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="11031">GT å­¦å¾’ä¸»åŠ›èˆ°å‡é€Ÿå™¨</t>
    <t id="11032">ä¸ºä¸»åŠ›èˆ°ä¸Šç»éªŒä¸è¶³çš„é£žè¡Œå‘˜æ˜¾è‘—é™ä½Žæ€§èƒ½çš„å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-25% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="11033">GT å­¦å¾’ä¸»åŠ›èˆ°æ—…è¡Œå‡é€Ÿå™¨</t>
    <t id="11034">ä¸ºä¸»åŠ›èˆ°ä¸Šç»éªŒä¸è¶³çš„é£žè¡Œå‘˜æ˜¾è‘—é™ä½Žæ—…è¡Œæ€§èƒ½çš„å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-25% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="12001">GT åŸºç¡€å°åž‹èˆ°èˆ¹å¢žå¼ºå™¨</t>
    <t id="12002">ä¸ºå…·æœ‰åŸºç¡€è®¤è¯é£žè¡Œå‘˜çš„å°åž‹èˆ°èˆ¹çš„ä¸“ä¸šå¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+3% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="12003">GT åŸºç¡€å°åž‹æ—…è¡Œå¢žå¼ºå™¨</t>
    <t id="12004">ä¸ºå…·æœ‰åŸºç¡€è®¤è¯é£žè¡Œå‘˜çš„å°åž‹èˆ°èˆ¹çš„ä¸“ä¸šå¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+3% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="13001">GT åŸºç¡€å¤§åž‹èˆ°èˆ¹å‡é€Ÿå™¨</t>
    <t id="13002">ä¸ºå…·æœ‰åŸºç¡€è®¤è¯é£žè¡Œå‘˜çš„å¤§åž‹èˆ°èˆ¹çš„ä¸“ä¸šå¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-8% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="13003">GT åŸºç¡€å¤§åž‹æ—…è¡Œå‡é€Ÿå™¨</t>
    <t id="13004">ä¸ºå…·æœ‰åŸºç¡€è®¤è¯é£žè¡Œå‘˜çš„å¤§åž‹èˆ°èˆ¹çš„ä¸“ä¸šå¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-8% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="14001">GT åŸºç¡€ä¸»åŠ›èˆ°å‡é€Ÿå™¨</t>
    <t id="14002">ä¸ºå…·æœ‰åŸºç¡€è®¤è¯é£žè¡Œå‘˜çš„ä¸»åŠ›èˆ°çš„ä¸“ä¸šå¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-15% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="14003">GT åŸºç¡€ä¸»åŠ›èˆ°æ—…è¡Œå‡é€Ÿå™¨</t>
    <t id="14004">ä¸ºå…·æœ‰åŸºç¡€è®¤è¯é£žè¡Œå‘˜çš„ä¸»åŠ›èˆ°çš„ä¸“ä¸šå¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚-15% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="15001">GT ä¸“å®¶å°åž‹èˆ°èˆ¹å¢žå¼ºå™¨</t>
    <t id="15002">ä¸ºå…·æœ‰ä¸“å®¶é£žè¡Œå‘˜çš„å°åž‹èˆ°èˆ¹çš„é«˜çº§å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+25% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="15003">GT ä¸“å®¶å°åž‹æ—…è¡Œå¢žå¼ºå™¨</t>
    <t id="15004">ä¸ºå…·æœ‰ä¸“å®¶é£žè¡Œå‘˜çš„å°åž‹èˆ°èˆ¹çš„é«˜çº§å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+25% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="16001">GT ä¸“å®¶å¤§åž‹èˆ°èˆ¹å¢žå¼ºå™¨</t>
    <t id="16002">ä¸ºå…·æœ‰ä¸“å®¶é£žè¡Œå‘˜çš„å¤§åž‹èˆ°èˆ¹çš„é«˜çº§å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+15% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="16003">GT ä¸“å®¶å¤§åž‹æ—…è¡Œå¢žå¼ºå™¨</t>
    <t id="16004">ä¸ºå…·æœ‰ä¸“å®¶é£žè¡Œå‘˜çš„å¤§åž‹èˆ°èˆ¹çš„é«˜çº§å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+15% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="17001">GT ä¸“å®¶ä¸»åŠ›èˆ°å¢žå¼ºå™¨</t>
    <t id="17002">ä¸ºå…·æœ‰ä¸“å®¶é£žè¡Œå‘˜çš„ä¸»åŠ›èˆ°çš„é«˜çº§å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+6% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½¬ã€‚</t>
    <t id="17003">GT ä¸“å®¶ä¸»åŠ›èˆ°æ—…è¡Œå¢žå¼ºå™¨</t>
    <t id="17004">ä¸ºå…·æœ‰ä¸“å®¶é£žè¡Œå‘˜çš„ä¸»åŠ›èˆ°çš„é«˜çº§å¼•æ“Žæ”¹è£…ã€‚ç”± GalaxyTrader AI ç³»ç»Ÿä½¿ç”¨ã€‚+6% æ—…è¡Œé€Ÿåº¦ã€‚</t>
    <t id="18001">ä¸¥é‡æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹ä½“ï¼‰</t>
    <t id="18002">ä¸¥é‡æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹ä½“ï¼‰ - ä»£è¡¨é£žè¡Œå‘˜å¯¹å¤§åž‹èˆ¹åªç»éªŒä¸è¶³å¯¼è‡´çš„ä¸¥é‡æ€§èƒ½æƒ©ç½šã€‚å½“é£žè¡Œå‘˜æŠ€èƒ½ä¸è¶³ä»¥æ“æŽ§è¯¥å°ºå¯¸èˆ¹åªæ—¶ï¼Œç”±GalaxyTraderç³»ç»Ÿè‡ªåŠ¨åº”ç”¨ã€‚å¢žåŠ èˆ¹ä½“è´¨é‡ã€‚ï¼ˆä»…GTç³»ç»Ÿ - ä¸å¯æ‰‹åŠ¨å®‰è£…ï¼‰</t>
    <t id="18003">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹ä½“ï¼‰</t>
    <t id="18004">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹ä½“ï¼‰ - ä»£è¡¨é£žè¡Œå‘˜é€‚åº”èˆ¹åªå¤æ‚æ€§æœŸé—´çš„ä¸­ç­‰æ€§èƒ½æƒ©ç½šã€‚å½“é£žè¡Œå‘˜æŠ€èƒ½ä¸è¶³ä»¥æ“æŽ§è¯¥å°ºå¯¸èˆ¹åªæ—¶ï¼Œç”±GalaxyTraderç³»ç»Ÿè‡ªåŠ¨åº”ç”¨ã€‚å¢žåŠ èˆ¹ä½“è´¨é‡ã€‚ï¼ˆä»…GTç³»ç»Ÿ - ä¸å¯æ‰‹åŠ¨å®‰è£…ï¼‰</t>
    <t id="18005">è½»å¾®æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹ä½“ï¼‰</t>
    <t id="18006">è½»å¾®æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹ä½“ï¼‰ - ä»£è¡¨é£žè¡Œå‘˜æŠ€èƒ½å‘å±•è¿‡ç¨‹ä¸­çš„è½»å¾®æ€§èƒ½æƒ©ç½šã€‚å½“é£žè¡Œå‘˜æŠ€èƒ½ä¸è¶³ä»¥æ“æŽ§è¯¥å°ºå¯¸èˆ¹åªæ—¶ï¼Œç”±GalaxyTraderç³»ç»Ÿè‡ªåŠ¨åº”ç”¨ã€‚å¢žåŠ èˆ¹ä½“è´¨é‡ã€‚ï¼ˆä»…GTç³»ç»Ÿ - ä¸å¯æ‰‹åŠ¨å®‰è£…ï¼‰</t>
    <t id="18007">ä¸¥é‡æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰</t>
    <t id="18008">ä¸¥é‡æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰ - ä»£è¡¨é£žè¡Œå‘˜å¯¹å¤§åž‹èˆ¹åªç»éªŒä¸è¶³å¯¼è‡´çš„ä¸¥é‡æ€§èƒ½æƒ©ç½šã€‚å½“é£žè¡Œå‘˜æŠ€èƒ½ä¸è¶³ä»¥æ“æŽ§è¯¥å°ºå¯¸èˆ¹åªæ—¶ï¼Œç”±GalaxyTraderç³»ç»Ÿè‡ªåŠ¨åº”ç”¨ã€‚é™ä½Žå¼•æ“ŽæŽ¨åŠ›å’Œæ—‹è½¬ã€‚ï¼ˆä»…GTç³»ç»Ÿ - ä¸å¯æ‰‹åŠ¨å®‰è£…ï¼‰</t>
    <t id="18009">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰</t>
    <t id="18010">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰ - ä»£è¡¨é£žè¡Œå‘˜é€‚åº”èˆ¹åªå¤æ‚æ€§æœŸé—´çš„ä¸­ç­‰æ€§èƒ½æƒ©ç½šã€‚å½“é£žè¡Œå‘˜æŠ€èƒ½ä¸è¶³ä»¥æ“æŽ§è¯¥å°ºå¯¸èˆ¹åªæ—¶ï¼Œç”±GalaxyTraderç³»ç»Ÿè‡ªåŠ¨åº”ç”¨ã€‚é™ä½Žå¼•æ“ŽæŽ¨åŠ›å’Œæ—‹è½¬ã€‚ï¼ˆä»…GTç³»ç»Ÿ - ä¸å¯æ‰‹åŠ¨å®‰è£…ï¼‰</t>
    <t id="18011">è½»å¾®æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰</t>
    <t id="18012">è½»å¾®æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰ - ä»£è¡¨é£žè¡Œå‘˜æŠ€èƒ½å‘å±•è¿‡ç¨‹ä¸­çš„è½»å¾®æ€§èƒ½æƒ©ç½šã€‚å½“é£žè¡Œå‘˜æŠ€èƒ½ä¸è¶³ä»¥æ“æŽ§è¯¥å°ºå¯¸èˆ¹åªæ—¶ï¼Œç”±GalaxyTraderç³»ç»Ÿè‡ªåŠ¨åº”ç”¨ã€‚é™ä½Žå¼•æ“ŽæŽ¨åŠ›å’Œæ—‹è½¬ã€‚ï¼ˆä»…GTç³»ç»Ÿ - ä¸å¯æ‰‹åŠ¨å®‰è£…ï¼‰</t>
    <t id="9250">èˆ°èˆ¹çŠ¶æ€å‘½å</t>
    <t id="9350">è‡ªå®šä¹‰èˆ°èˆ¹çŠ¶æ€ç¼©å†™ã€‚é»˜è®¤å€¼æ˜¾ç¤ºåœ¨è¾“å…¥æ¡†ä¸­ï¼Œå¯ä»¥è¦†ç›–ã€‚æœ€å¤š 3 ä¸ªå­—ç¬¦ã€‚æ›´æ”¹åŽï¼Œæ‰€æœ‰èˆ°èˆ¹åç§°å°†è‡ªåŠ¨æ›´æ–°ã€‚</t>
    <t id="9251">è¡¥ç»™çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9252">ç»´ä¿®çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9253">ç»´æŠ¤çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9254">è®­ç»ƒçŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9255">é‡æ–°è·¯ç”±çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9256">è®¸å¯çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9257">é˜»æ­¢çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9258">å¤‡ç”¨çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9259">éš”ç¦»çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9260">è´¸æ˜“çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9261">ç©ºé—²çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9262">é€ƒç¦»çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9268">ä¸å¯è¾¾çŠ¶æ€ç¼©å†™ï¼š</t>
    <t id="9269">è¯•ç‚¹äº¤æ˜“æ‰€å›½å®¶ç¼©å†™ï¼š</t>
    <t id="9270">è‡ªå®šä¹‰é»‘åå•å‰ç¼€æ ‡ç­¾ï¼š</t>
    <t id="9700">ä½œå¼Š (åäº†ã€‚è¿™é‡Œä»€ä¹ˆéƒ½æ²¡æœ‰!! çœŸçš„!!)</t>
    <t id="9701">GTé£žèˆ¹æ— æ•Œ</t>
    <t id="9702">æ‰€æœ‰çŽ©å®¶é£žèˆ¹æ— æ•Œ</t>
    <t id="9800">è¯·èµ°å¼€ï¼Œé£žè¡Œå‘˜ã€‚è¿™æ˜¯åæŽ‰çš„å¼€å‘è€…æµ‹è¯•å·¥å…·ï¼Œä¸æ˜¯å¥½çŽ©çš„æŒ‰é’®èœå•ã€‚è¿™é‡Œä»€ä¹ˆéƒ½æ²¡æœ‰ã€‚çœŸçš„ã€‚ä½ å·²ç»æ”¶åˆ°è­¦å‘Šäº†ã€‚å¤§æ¦‚å§ã€‚</t>
    <t id="9801">æ‰§è¡ŒGalaxyTraderå‘½ä»¤çš„é£žèˆ¹èˆ¹ä½“ä¸ŽæŠ¤ç›¾ä¸ä¼šä½ŽäºŽ100%ã€‚å†æ¬¡ç‚¹å‡»å¯å…³é—­ã€‚</t>
    <t id="9802">æ‰€æœ‰çŽ©å®¶é£žèˆ¹çš„èˆ¹ä½“ä¸ŽæŠ¤ç›¾ä¸ä¼šä½ŽäºŽ100%ã€‚å†æ¬¡ç‚¹å‡»å¯å…³é—­ã€‚ç©ºé—´ç«™ä¸å—å½±å“ã€‚</t>
    <t id="9703">ä¸ºGTæµ‹è¯•æ­ç¤ºå…¨å®‡å®™</t>
    <t id="9704">å·²æ­ç¤º</t>
    <t id="9705">æ­ç¤º</t>
    <t id="9803">æ­ç¤ºæ‰€æœ‰æ˜ŸåŒºæˆ˜äº‰è¿·é›¾ï¼Œæ ‡è®°æ‰€æœ‰ç©ºé—´ç«™ä¸ºå·²çŸ¥ï¼ŒæŽˆäºˆæ‰€æœ‰æ´¾ç³»è´¸æ˜“è®¢é˜…è®¸å¯ï¼Œå¹¶è®¢é˜…å…¨é“¶æ²³è´¸æ˜“æŠ¥ä»·ã€‚å‡ºçŽ°æ–°DLCæ˜ŸåŒºåŽå¯å†æ¬¡ç‚¹å‡»ã€‚ä»…ç”¨äºŽæµ‹è¯•ã€‚</t>
    <t id="9706">æœ€å¤§åŒ–å·²æ³¨å†ŒGTé£žè¡Œå‘˜XP</t>
    <t id="9707">å·²æœ€å¤§åŒ–</t>
    <t id="9708">æœ€å¤§XP</t>
    <t id="9804">å°†GTæ³¨å†Œè¡¨ä¸­æ¯ä½é£žè¡Œå‘˜è®¾ä¸º15çº§å’Œæœ€å¤§XPã€‚æ¸…é™¤è®­ç»ƒé—¨æ§›å’Œé˜»å¡žã€‚å¯ç”¨ä»…åŽŸç‰ˆXPæ—¶è·³è¿‡ã€‚ä»…ç”¨äºŽæµ‹è¯•ã€‚</t>
    <t id="9351">è¡¥ç»™çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šRSï¼‰</t>
    <t id="9352">ç»´ä¿®çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šRPï¼‰</t>
    <t id="9353">ç»´æŠ¤çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šMTï¼‰</t>
    <t id="9354">è®­ç»ƒçŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šTRï¼‰</t>
    <t id="9355">é‡æ–°è·¯ç”±çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šRRï¼‰</t>
    <t id="9356">è®¸å¯çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šCLï¼‰</t>
    <t id="9357">é˜»æ­¢çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šBLï¼‰</t>
    <t id="9358">å¤‡ç”¨çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šFBï¼‰</t>
    <t id="9359">éš”ç¦»çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šISï¼‰</t>
    <t id="9360">è´¸æ˜“çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šTDï¼‰</t>
    <t id="9361">ç©ºé—²çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šIDï¼‰</t>
    <t id="9362">é€ƒç¦»çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šESï¼‰</t>
    <t id="9367">æ— æ³•åˆ°è¾¾çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤å€¼ï¼šURï¼‰</t>
    <t id="9368">Pilot Exchange çŠ¶æ€çš„ç¼©å†™ï¼ˆé»˜è®¤ï¼šPEï¼‰</t>
    <t id="9369">æ˜¾ç¤ºä¸º MK3 èˆ¹èˆ¶çš„å‰ç¼€ï¼Œå—è‡ªå®šä¹‰æ´¾ç³»é»‘åå•ï¼ˆåŒ…æ‹¬ä¸‹å±žï¼‰å½±å“ã€‚é»˜è®¤å€¼ï¼šCB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">è½¦ç«™å•†äºº - å‘ NPC æ´¾ç³»å‡ºå”®è½¦ç«™äº§å“</t>
    <t id="30010">ä¸»ç«™</t>
    <t id="30011">æœ€å¤§å–å‡ºè·ç¦»</t>
    <t id="30012">å¿½è§†è´¸æ˜“è§„åˆ™</t>
    <t id="30013">æ´å…·è¿‡æ»¤å™¨</t>
    <t id="30014">é”€å”®è´§ç‰©å¡«å……ç›®æ ‡%</t>
    <t id="30015">å›žæº¯å®¹å·®</t>
    <t id="30016">è´­ä¹°è´§ç‰©å¡«å……ç›®æ ‡%</t>
    <t id="30017">æ—¥å¿—æ¡ç›®</t>
    <t id="30018">é€šçŸ¥çº§åˆ«</t>
    <t id="30019">èˆ°é˜Ÿåè°ƒ</t>
    <t id="30020">è°ƒè¯•çº§åˆ«</t>
    <t id="30021">è¡¥ç»™ç«™</t>
    <t id="30022">æœ€å°ç«™å­˜å‚¨ç™¾åˆ†æ¯”</t>
    <t id="30023">å…è®¸éžæ³•å•†å“</t>
    <t id="30024">è´§ç‰©/åˆ©æ¶¦</t>
    <t id="30025">å…è®¸å¤šå®—äº¤æ˜“</t>
    <t id="30110">å‡ºå”®å•†å“çš„çŽ©å®¶ç«™ï¼ˆéœ€è¦ç«™åˆ†é…ï¼‰</t>
    <t id="30111">å¯»æ‰¾NPCä¹°å®¶çš„æœ€å¤§é—¨è·ç¦»ï¼ˆå—é£žè¡Œå‘˜æŠ€èƒ½é™åˆ¶ï¼‰</t>
    <t id="30112">å¿½ç•¥è½¦ç«™è´¸æ˜“é™åˆ¶ - æ— è®ºè½¦ç«™è´¸æ˜“è§„åˆ™å¦‚ä½•ï¼Œéƒ½å¯ä»¥å‡ºå”®ç»™ä»»ä½•å‹å¥½æ´¾ç³»</t>
    <t id="30113">å¯é€‰é…æ´å…·è¿‡æ»¤å™¨ï¼›ç•™ç©ºä»¥å‡ºå”®æ‰€æœ‰è½¦ç«™äº§å“å’Œå•†å“</t>
    <t id="30114">é”€å”®è¡Œç¨‹å‡ºå‘å‰çš„æœ€ä½Žè´§ç‰©è£…è½½ç™¾åˆ†æ¯”</t>
    <t id="30115">åœ¨è¡Œç¨‹ä¸­æ·»åŠ ç¬¬äºŒä¸ªå•†å“æ—¶å…è®¸çš„æœ€å¤§é¢å¤–è·³è·ƒæ¬¡æ•°ï¼ˆ0 = ä»…ç›´æŽ¥åœ¨è·¯çº¿ä¸Šçš„ä¹°å®¶ï¼‰</t>
    <t id="30116">ä¾›åº”è¿è¡Œçš„ç›®æ ‡è´§ç‰©å¡«å……é‡ï¼ˆè½¯ç›®æ ‡ï¼Œè´¸æ˜“å•†å¯èƒ½ä¼šæå‰å‡ºå‘ï¼‰</t>
    <t id="30117">å¯ç”¨æ¯ç¬”äº¤æ˜“æ—¥å¿—æ¡ç›®</t>
    <t id="30118">é€šçŸ¥çº§åˆ«ï¼š0=å®‰é™ã€1=æ­£å¸¸ã€2=è¯¦ç»†</t>
    <t id="30119">å¯ç”¨è½¦é˜Ÿåè°ƒå’Œè´¸æ˜“é¢„è®¢ç³»ç»Ÿ</t>
    <t id="30120">è°ƒè¯•æ—¥å¿—è®°å½•çº§åˆ«ï¼š0=å…³é—­ã€1=æ­£å¸¸ã€2=è¯¦ç»†</t>
    <t id="30121">å¯ç”¨åŽï¼Œè¿˜å¯ä»¥ä¸ºè¯¥ç«™è´­ä¹°èµ„æºã€‚å½“å­˜å‚¨é‡ä½ŽäºŽæœ€ä½Žé˜ˆå€¼æ—¶ï¼Œä¾›åº”ä¼˜å…ˆ</t>
    <t id="30122">å½“ä»»ä½•èµ„æºä½ŽäºŽå…¶ç›®æ ‡ç™¾åˆ†æ¯”æ—¶ï¼Œä¾›åº”ä¼˜å…ˆäºŽé”€å”®ã€‚å¦‚æžœç«™æ— æ³•æ‰¿æ‹…èµ„æºåˆ™è¢«å¿½ç•¥</t>
    <t id="30123">å…è®¸å‡ºå”®æˆ–è´­ä¹°éžæ³•/è¿ç¦å•†å“ï¼ˆå¦‚æœ‰ï¼‰</t>
    <t id="30124">é”€å”®é€‰æ‹©ï¼š1=è´§ç‰©ï¼ˆä¼˜å…ˆè¯¥å•†å“åº“å­˜å æ¯”æœ€é«˜ï¼›å¹³å±€æŒ‰åˆ©æ¶¦ï¼‰ï¼Œ2=åˆ©æ¶¦ï¼ˆæœ€é«˜åˆ©æ¶¦è¯„åˆ†ï¼‰</t>
    <t id="30125">å…è®¸åœ¨ä¸€ä¸ªå‘¨æœŸå†…ä¸²è”å¤šç¬”é”€å”®ï¼ˆæœ€å¤š3ç§å•†å“æˆ–ç›®çš„åœ°ï¼‰ã€‚å…³é—­åŽæ¯å‘¨æœŸä»…æ‰§è¡Œå•ç¬”äº¤æ˜“</t>
    <t id="30200">å°† %1 %2 ä»Ž %3 å‡ºå”®åˆ° %4</t>
    <t id="30201">åœ¨ %1 è·³å†…æœªæ‰¾åˆ°ç”µå°äº§å“çš„ä¹°å®¶</t>
    <t id="30202">ä¸»ç«™ %1 è¢«æ¯ - ç«™äº¤æ˜“è€…è®¢å•è¢«å–æ¶ˆ</t>
    <t id="30203">ä¸»ç«™ %1 ä¸å†ç”±çŽ©å®¶æ‹¥æœ‰ - è®¢å•å·²å–æ¶ˆ</t>
    <t id="30204">éœ€è¦åˆ†é…è½¦ç«™ - è®¢å•å·²å–æ¶ˆ</t>
    <t id="30205">MK1 Station Trader äºŽ %1 å¼€å§‹</t>
    <t id="30206">å·²å®Œæˆé”€å”®: %1%2å‡ºå”®ç»™ %3Cr %4Cr (ç›ˆåˆ©:%5Cr)</t>
    <t id="30207">å¤šä»¶ç‰©å“ä¹‹æ—…ï¼šå°† %1 ä»¶ç‰©å“è¿é€åˆ° %2 ä¸ªç›®çš„åœ°</t>
    <t id="30208">Supplying %1 %2 to %3 from %4</t>
    <t id="30500">GalaxyTrader MK1 è®¾ç½®</t>
    <t id="30501">ç«™äº¤æ˜“é»˜è®¤å€¼</t>
    <t id="30502">é»˜è®¤æœ€å¤§é”€å”®è·ç¦»</t>
    <t id="30503">é»˜è®¤é”€å”®è´§ç‰©å¡«å……ç›®æ ‡</t>
    <t id="30504">é»˜è®¤å¿½ç•¥äº¤æ˜“è§„åˆ™</t>
    <t id="30505">é»˜è®¤å›žæº¯å®¹å·®</t>
    <t id="30506">æœªæ‰¾åˆ°äº¤æ˜“æ—¶çš„ç­‰å¾…æ—¶é—´</t>
    <t id="30507">é»˜è®¤ä¹°å…¥è´§ç‰©å¡«å……ç›®æ ‡</t>
    <t id="31002">é“¶æ²³çŸ¿å·¥</t>
    <t id="31102">å…·æœ‰ç©ºé—´ç«™è¡¥ç»™ä¸ŽXPæˆé•¿çš„è‡ªä¸»é‡‡çŸ¿</t>
    <t id="31010">æ¯ç«™</t>
    <t id="31110">ç”¨äºŽé‡‡çŸ¿ä¸Žäº¤ä»˜çš„ç©ºé—´ç«™ï¼ˆä¸Žæ¯æ‰‡åŒºäº’æ–¥ï¼‰</t>
    <t id="31011">æ¯æ‰‡åŒº</t>
    <t id="31111">ä½œä¸šæ‰‡åŒºï¼›æœªè®¾ç½®æ¯ç«™æ—¶ä½¿ç”¨</t>
    <t id="31012">èµ„æºç¯®</t>
    <t id="31112">è¦é‡‡é›†çš„è´§ç‰©ï¼›ä¸ºç©ºæ—¶æŒ‰ç©ºé—´ç«™éœ€æ±‚å†³ç­–</t>
    <t id="31013">ç›®æ ‡ç©ºé—´ç«™</t>
    <t id="31113">å¯é€‰äº¤ä»˜ç«™ç‚¹è¿‡æ»¤ï¼›ä¸ºç©ºæ—¶ç”±æ¯ç«™/æ¯æ‰‡åŒºä¸Šä¸‹æ–‡æŽ¨å¯¼</t>
    <t id="31014">æº¢å‡ºé˜ˆå€¼ %</t>
    <t id="31114">å­˜å‚¨æ¯”ä¾‹è¾¾åˆ°æˆ–è¶…è¿‡è¯¥å€¼çš„ç©ºé—´ç«™å°†è§†ä¸ºå·²æ»¡</t>
    <t id="31015">å…è®¸å‘å…¶ä»–åŠ¿åŠ›å‡ºå”®æº¢å‡ºè´§ç‰©</t>
    <t id="31115">å¯ç”¨åŽå½“ä¸»è¦ç›®æ ‡å·²æ»¡æ—¶ï¼Œå‘å…¶ä»–åŠ¿åŠ›ç©ºé—´ç«™å‡ºå”®</t>
    <t id="31016">åˆ†é…åˆ°ç©ºé—´ç«™</t>
    <t id="31116">åœ¨é€‚ç”¨æ—¶å°†èˆ°èˆ¹ä½œä¸ºæ¯ç«™é‡‡çŸ¿ä¸‹å±žè¿›è¡Œåˆ†é…</t>
    <t id="31017">ç•™åœ¨åŸºåœ°</t>
    <t id="31117">å°†é‡‡é›†/å‡ºå”®é™åˆ¶åœ¨åŸºåœ°èŒƒå›´å†…ï¼ˆæº¢å‡ºå›žé€€å‡ºå”®é™¤å¤–ï¼‰</t>
    <t id="31018">è‡ªåŠ¨éƒ¨ç½²èµ„æºæŽ¢é’ˆ</t>
    <t id="31118">è‡ªåŠ¨éƒ¨ç½²å·²è£…è½½çš„èµ„æºæŽ¢é’ˆï¼Œå¹¶åœ¨ç»´æŠ¤è¡¥ç»™ä¸­åŒ…å«æŽ¢é’ˆ</t>
    <t id="31019">æœ€å¤§é‡‡é›†è·ç¦»</t>
    <t id="31119">é‡‡é›†æœ€å¤§é—¨è·³è·ç¦»ï¼ˆ0 ä½¿ç”¨é£žè¡Œå‘˜/æŒ‡æŒ¥å®˜ä¸Šé™ï¼‰</t>
    <t id="31020">æœ€å¤§å‡ºå”®è·ç¦»</t>
    <t id="31120">å‡ºå”®æœ€å¤§é—¨è·³è·ç¦»ï¼ˆ0 ä½¿ç”¨é£žè¡Œå‘˜/æŒ‡æŒ¥å®˜ä¸Šé™ï¼‰</t>
    <t id="31021">èˆ°é˜Ÿå‡è¡¡</t>
    <t id="31121">å¯ç”¨ç¡®å®šæ€§æ„å›¾åè°ƒä»¥å‡å°‘ç©ºé—´ç«™æº¢å‡º</t>
    <t id="31022">éœ€æ±‚å¤æ£€é—´éš”</t>
    <t id="31122">çŸ¿å·¥æ‰§è¡Œéœ€æ±‚/åˆ‡æ¢è¯„ä¼°çš„é¢‘çŽ‡</t>
    <t id="31023">å…³é”®éœ€æ±‚å·®å€¼</t>
    <t id="31123">åˆ‡æ¢å½“å‰é‡‡çŸ¿è´§ç‰©æ‰€éœ€çš„æœ€å°ç´§æ€¥åº¦å·®å€¼</t>
    <t id="31024">æœ€å°åˆ‡æ¢å†·å´</t>
    <t id="31124">è¯¥èˆ°èˆ¹ä¸¤æ¬¡è´§ç‰©åˆ‡æ¢ä¹‹é—´çš„æœ€çŸ­æ—¶é—´</t>
    <t id="31025">æœ€ä½Žè´§èˆ±æ‰¿è¯º %</t>
    <t id="31125">å½“è´§èˆ±å ç”¨é«˜äºŽè¯¥å€¼æ—¶ï¼Œä¼˜å…ˆå®Œæˆå½“å‰äº¤ä»˜å†åˆ‡æ¢</t>
    <t id="31026">ç¡¬ç´§æ€¥å·®å€¼</t>
    <t id="31126">å³ä½¿è¶…è¿‡è´§èˆ±æ‰¿è¯ºé˜ˆå€¼ä¹Ÿå…è®¸ç«‹å³åˆ‡æ¢çš„ç´§æ€¥åº¦å·®å€¼</t>
    <t id="31027">é€šçŸ¥çº§åˆ«</t>
    <t id="31127">é€šçŸ¥çº§åˆ«ï¼š0=é™é»˜ï¼Œ1=æ™®é€šï¼Œ2=è¯¦ç»†</t>
    <t id="31028">ä»…é™çŽ©å®¶ç«™</t>
    <t id="31128">å¯ç”¨åŽï¼Œåªæœ‰çŽ©å®¶æ‹¥æœ‰çš„ç”µå°æ‰ä¼šè¢«è§†ä¸ºéœ€æ±‚ç›®æ ‡ã€‚</t>
    <t id="31031">å…ˆæ£€æŸ¥éœ€æ±‚</t>
    <t id="31131">å¯ç”¨åŽï¼Œé‡‡çŸ¿èˆ¹åœ¨é‡‡çŸ¿å‰ä¼šæ£€æŸ¥ç©ºé—´ç«™éœ€æ±‚å¹¶æ®æ­¤ç¡®å®šèµ„æºä¼˜å…ˆçº§ã€‚ç¦ç”¨åŽï¼Œä¸æ£€æŸ¥éœ€æ±‚ï¼Œç›´æŽ¥ä»Žèµ„æºç¯®é‡‡çŸ¿å¹¶å›¤ç§¯è‡³æœ‰ä¹°å®¶ï¼ˆæŽ¨èç”¨äºŽå•ä¸€èµ„æºèˆ°é˜Ÿï¼‰ã€‚</t>
    <t id="31032">ç‰©ç†åº“å­˜ä¸­æ­¢ %</t>
    <t id="31132">é€‚ç”¨äºŽç­‰çº§6ä»¥ä¸Šé©¾é©¶å‘˜ï¼šå½“ç©ºé—´ç«™ç‰©ç†åº“å­˜åŠ ä¸Šç›¸å…³é‡‡çŸ¿èˆ¹åœ¨é€”è´§ç‰©å°†è¶…è¿‡å½“å‰ç‰©ç†åº“å­˜æ­¤ç™¾åˆ†æ¯”æ—¶ï¼Œåœæ­¢å¼€é‡‡å½“å‰èµ„æºã€‚ä½¿ç”¨å®žé™…è´§ç‰©æ•°é‡ï¼Œä¸Žæº¢å‡ºé˜ˆå€¼æ— å…³ã€‚0ä¸ºç¦ç”¨ã€‚</t>
    <t id="32002">GalaxyTrader MK4 Supply</t>
    <t id="32102">ä½¿ç”¨ GT ç¼“å­˜/å®žæ—¶æœç´¢ç®¡é“çš„çŽ©å®¶ç«™ä¾›åº”äº¤æ˜“è€…</t>
    <t id="32010">è¦†ç›–è·ç¦»</t>
    <t id="32110">ç›®çš„åœ°éœ€æ±‚æœç´¢è·å®¶çš„æœ€å¤§ç™»æœºå£è·ç¦»</t>
    <t id="32011">è´­ä¹°è·ç¦»</t>
    <t id="32111">ä¾›åº”å•†æœç´¢æ—¶è·å®¶çš„æœ€å¤§é—¨è·</t>
    <t id="32012">åªä¸ºå®¶åº­æœåŠ¡</t>
    <t id="32112">å¯ç”¨åŽï¼Œä»…æ»¡è¶³ä¸»ç«™éœ€æ±‚</t>
    <t id="32013">ä»…å»ºé€ ç«™</t>
    <t id="32113">å¯ç”¨åŽï¼Œä»…æ»¡è¶³æž„å»ºå­˜å‚¨éœ€æ±‚</t>
    <t id="32014">ä»ŽçŽ©å®¶å¤„è´­ä¹°</t>
    <t id="32114">å…è®¸ä»ŽçŽ©å®¶æ‹¥æœ‰çš„ä¾›åº”å•†å¤„é‡‡è´­å•†å“</t>
    <t id="32015">ä»Žæ´¾ç³»è´­ä¹°</t>
    <t id="32115">å…è®¸ä»ŽéžçŽ©å®¶æ´¾ç³»ä¾›åº”å•†å¤„é‡‡è´­å•†å“</t>
    <t id="32016">å…è®¸èµ„æº</t>
    <t id="32116">å°†èµ„æºå•†å“çº³å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="32017">å…è®¸ä¸­é—´ä½“</t>
    <t id="32117">å°†ä¸­é—´ä»¶çº³å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="32018">å…è®¸äº§å“</t>
    <t id="32118">å°†äº§å“çº³å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="32019">å…è®¸è´¸æ˜“è½¯ä»¶</t>
    <t id="32119">å°†è´¸æ˜“å•†å“çº³å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">å¸¦å­˜å‚¨é˜ˆå€¼ç®¡ç†çš„ä»“åº“åˆ†å‘</t>
    <t id="20010">æ¥æºç©ºé—´ç«™</t>
    <t id="20011">ç›®æ ‡ç©ºé—´ç«™</t>
    <t id="20012">æœ€ä½Žå­˜å‚¨ %</t>
    <t id="20013">é™æ€å­˜å‚¨ %</t>
    <t id="20014">æœ€é«˜å­˜å‚¨ %</t>
    <t id="20015">å•†å“ç­›é€‰</t>
    <t id="20016">åŒå‘æ¨¡å¼</t>
    <t id="20017">æ¯ç«™ï¼ˆå¯é€‰ï¼‰</t>
    <t id="20018">æœ€å¤§è·ç¦»</t>
    <t id="20032">æ¯æ˜ŸåŒºï¼ˆå¯é€‰ï¼‰</t>
    <t id="20019">å¾ªçŽ¯ç­‰å¾…æ—¶é—´</t>
    <t id="20030">å…è®¸ä½Žè£…è½½é‡</t>
    <t id="20031">ä½Žè£…è½½é‡ä¸‹é™ %</t>
    <t id="20110">ç”¨äºŽåˆ†å‘å•†å“çš„æ¥æºç©ºé—´ç«™åˆ—è¡¨</t>
    <t id="20111">ç”¨äºŽåˆ†å‘çš„ç›®æ ‡ç©ºé—´ç«™/ä»“åº“åˆ—è¡¨</t>
    <t id="20112">ç›®æ ‡ç´§æ€¥é˜ˆå€¼ï¼šä½ŽäºŽè¯¥å­˜å‚¨ % çš„ç«™ç‚¹ä¼˜å…ˆè¡¥ç»™</t>
    <t id="20113">æ¥æºæœ€ä½Žé˜ˆå€¼ï¼šæ¥æºå¿…é¡»é«˜äºŽè¯¥ % æ‰ä¼šåˆ†å‘</t>
    <t id="20114">æ¥æºæº¢å‡ºé˜ˆå€¼ï¼šé«˜äºŽè¯¥ % æ—¶ä¹Ÿä¼šåˆ†å‘åˆ°éžç´§æ€¥ç›®æ ‡</t>
    <t id="20115">å¯é€‰å•†å“ç­›é€‰ï¼›ç•™ç©ºåˆ™åˆ†å‘æ¥æºä¸­çš„å…¨éƒ¨å•†å“</t>
    <t id="20116">å¯ç”¨å›žç¨‹æ”¶é›†ï¼šå½“ç›®æ ‡æœ‰ç›ˆä½™æ—¶ä»Žç›®æ ‡å›žæ”¶è‡³æ¥æº</t>
    <t id="20117">ç”¨äºŽåˆ†é…çš„æ¯ç«™ï¼ˆå¯é€‰ï¼‰ã€‚ç•™ç©ºåˆ™èˆ°èˆ¹ä¸åˆ†é…åˆ°ç©ºé—´ç«™ã€‚</t>
    <t id="20118">æ¥æºä¸Žç›®æ ‡ä¹‹é—´æœ€å¤§æ˜Ÿé—¨è·ç¦»ï¼ˆ0 = ä¸é™åˆ¶ï¼‰</t>
    <t id="20132">æœªè®¾ç½®æ¯ç«™æ—¶ï¼Œç”¨äºŽé—²ç½®åœé çš„å¯é€‰æ¯æ˜ŸåŒºã€‚</t>
    <t id="20119">åˆ†å‘å¾ªçŽ¯ä¹‹é—´çš„ç­‰å¾…æ—¶é—´</t>
    <t id="20130">å…è®¸åœ¨ä½ŽäºŽå¸¸è§„æœ€ä½Žè´§èˆ±è£…è½½çŽ‡æ—¶ï¼Œæ ¹æ®ç´§æ€¥ç¨‹åº¦æ‰§è¡Œå°æ‰¹é‡é…é€ã€‚</t>
    <t id="20131">å¯ç”¨ä½Žè£…è½½é‡æ¨¡å¼æ—¶ä½¿ç”¨çš„æœ€ä½Žè´§èˆ±è£…è½½çŽ‡ï¼ˆ%ï¼‰ã€‚</t>
    <t id="20200">æ­£åœ¨å°† %1 %2 ä»Ž %3 åˆ†å‘åˆ° %4</t>
    <t id="20201">è¿”ç¨‹è¿è¾“ï¼šæ­£åœ¨å°† %1 %2 ä»Ž %3 æ”¶é›†åˆ° %4</t>
    <t id="20202">æ— éœ€åˆ†å‘ - æ‰€æœ‰ç›®æ ‡åº“å­˜å……è¶³</t>
    <t id="20203">æ‰€æœ‰æ¥æºç©ºé—´ç«™æ— æ•ˆ - åˆ†å‘å¾…å‘½</t>
    <t id="20204">æ‰€æœ‰ç›®æ ‡ç©ºé—´ç«™æ— æ•ˆ - åˆ†å‘å¾…å‘½</t>
    <t id="20205">æ¥æºç©ºé—´ç«™ %1 å·²è¢«æ‘§æ¯ - å·²ä»Žåˆ†å‘å‘½ä»¤ä¸­ç§»é™¤</t>
    <t id="20206">ç›®æ ‡ç©ºé—´ç«™ %1 å·²è¢«æ‘§æ¯ - å·²ä»Žåˆ†å‘å‘½ä»¤ä¸­ç§»é™¤</t>
    <t id="20500">GalaxyTrader MK2 - å…¨å±€è®¾ç½®</t>
    <t id="20501">MK2 åˆ†å‘é»˜è®¤å€¼</t>
    <t id="20510">é»˜è®¤æœ€ä½Žå­˜å‚¨ %</t>
    <t id="20511">é»˜è®¤é™æ€å­˜å‚¨ %</t>
    <t id="20512">é»˜è®¤æœ€é«˜å­˜å‚¨ %</t>
    <t id="20513">é»˜è®¤å¾ªçŽ¯ç­‰å¾…ï¼ˆç§’ï¼‰</t>
    <t id="20514">æœ€ä½Žè´§èˆ±è£…è½½ %</t>
    <t id="20520">é€šçŸ¥è¯¦ç»†ç¨‹åº¦</t>
    <t id="20521">è°ƒè¯•çº§åˆ«</t>
    <t id="10006">å›žå®¶</t>
    <t id="10007">GalaxyTrader MK4-2 ä¾›ç»™</t>
    <t id="10106">åœé åœ¨ä¸»ç«™å¹¶ç•™åœ¨é‚£é‡Œç›´åˆ°äº¤æ˜“æ¢å¤</t>
    <t id="10107">å¸¦äº¤ä»˜ç›®æ ‡ä¼˜å…ˆçº§æ»‘å—çš„çŽ©å®¶ä¾›ç»™è®¢å•</t>
    <t id="30026">å‘¨æœŸä¹‹é—´è¿”å›žå®¶</t>
    <t id="30028">å¿½ç•¥æŠ¥ä»·è®¾ç½®</t>
    <t id="30029">ä¹°æ–¹ä»·æ ¼èŒƒå›´</t>
    <t id="30027">æœ€å°äº§å“å­˜å‚¨ %</t>
    <t id="30126">å¯ç”¨åŽï¼Œè¿”å›žä¸»ç«™å¹¶åœ¨äº¤æ˜“å‘¨æœŸä¹‹é—´åœé ã€‚ç¦ç”¨åŽï¼Œä»Žå½“å‰ä½ç½®ç»§ç»­æœç´¢ï¼ˆæ—§è¡Œä¸ºï¼‰</t>
    <t id="30128">å…è®¸åœ¨æ— è½¦ç«™ä¹°å–æŠ¥ä»·çš„æƒ…å†µä¸‹è¿›è¡Œå†…éƒ¨ä»“å‚¨è½¬ç§»ã€‚ä½¿ç”¨è´§ç‰©äº¤æ¢è¿›è¡Œç¼“å†²åŒºçš„å–è´§ä¸Žäº¤ä»˜ã€‚æœªå¯ç”¨â€œå¿½ç•¥è´¸æ˜“è§„åˆ™â€æ—¶ï¼Œè½¦ç«™è´¸æ˜“è§„åˆ™ä»ç„¶ç”Ÿæ•ˆã€‚</t>
    <t id="30129">å‡ºå”®è½¦ç«™äº§å“æ—¶ NPC ä¹°æ–¹çš„æœ€ä½Žç›¸å¯¹ä»·æ ¼ã€‚å‘½ä»¤æ»‘å— 0-200ï¼ˆ100 = å¹³å‡ï¼Œ0 = -100%ï¼Œ200 = +100%ï¼‰å¯¹åº” -1.0 è‡³ +1.0ã€‚è¶Šé«˜åˆ™ä»…æŽ¥å—é«˜ä»·ä¹°æ–¹ï¼Œè¶Šä½Žåˆ™ä¹°æ–¹é€‰æ‹©æ›´å¤šã€‚è¡¥ç»™è¡Œç¨‹å¯¹ä¾›åº”å•†ä»·æ ¼ä¸Šé™ä½¿ç”¨åè½¬å€¼ã€‚</t>
    <t id="30127">é”€å”®äº§å“æˆ–è´¸æ˜“å“ä¹‹å‰æ‰€éœ€çš„æœ€ä½Žç«™ç‚¹å­˜å‚¨å¡«å……ç™¾åˆ†æ¯”ï¼ˆç›¸å¯¹äºŽæ¯ç§è´§ç‰©é…ç½®çš„æœ€å¤§å€¼ï¼‰ã€‚ä½ŽäºŽæ­¤é˜ˆå€¼çš„è´§ç‰©å°†è¢«è·³è¿‡ã€‚0 = æ— æœ€ä½Žè¦æ±‚ã€‚</t>
    <t id="3107">æ­£åœ¨æŽ’é˜Ÿå¤šé‡äº¤æ˜“ï¼š%1ã€‚æˆ‘åº”è¯¥èµšå– %2 åˆ©æ¶¦ã€‚</t>
    <t id="3108">ä»Ž %3 å‡ºå”® %1 %2ï¼Œä»·æ ¼ä¸º %4ã€‚æˆ‘åº”è¯¥èµšå– %5 åˆ©æ¶¦ã€‚</t>
    <t id="3110">æ­£åœ¨æŽ’é˜Ÿä¾›åº” %1 %2ã€‚ä»¥ %3 ä»Ž %4 é‡‡è´­ï¼Œè¿é€è‡³ %5ã€‚å®¢æˆ·ä¹°å…¥ä¸Šé™ %6 - æ¯å•ä½ä½ŽäºŽä¸Šé™ %7ï¼ˆåˆè®¡ %8ï¼‰ã€‚</t>
    <t id="3111">æ­£åœ¨æŽ’é˜Ÿä¾›åº” %1 %2ï¼Œä»Ž %3 è‡³ %4ã€‚</t>
    <t id="3112">ä¾›åº”æŽ’é˜Ÿä¸­ï¼ˆ%1 æ®µï¼‰ï¼š%2ã€‚åˆè®¡ä½ŽäºŽå®¢æˆ·ä¹°å…¥ä¸Šé™ %3ã€‚</t>
    <t id="3113">ç©ºé—´ç«™è´¸æ˜“å•†ï¼šæ­£åœ¨æŽ’é˜Ÿå‡ºå£å¤šé‡äº¤æ˜“ï¼š%1ã€‚é¢„æœŸåˆ©æ¶¦ %2ã€‚</t>
    <t id="31029">æŽ¢æµ‹åº“å­˜ç›®æ ‡</t>
    <t id="31030">è´­ä¹°çš„é‡‡çŸ¿æ— äººæœºæ•°é‡</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Minerï¼šæ²¡æœ‰å¯å¼€é‡‡çš„è´§ç‰©ã€‚èˆ°èˆ¹ %1 [%2]ï¼Œèˆ°é˜Ÿï¼š%3</t>
    <t id="31201">Galaxy-Minerï¼šè¯·è®¾ç½®æ¯ç«™æˆ–æ¯ä½ç½®ã€‚</t>
    <t id="31130">å½“çŸ¿èˆ¹ç”¨å®Œæ‰€éœ€ç±»åž‹ï¼ˆå›ºä½“/çŸ¿çŸ³æˆ–æ¶²ä½“/æ°”ä½“ï¼‰æ—¶è´­ä¹°çš„é‡‡é›†ï¼ˆé‡‡çŸ¿ï¼‰æ— äººæœºæ•°é‡ã€‚ä»…å½“èˆ¹ä¸Šæ²¡æœ‰è¯¥ç±»åž‹çš„é‡‡é›†æ— äººæœºæ—¶ï¼ˆæ•°é‡=0ï¼‰æ‰ä¼šè§¦å‘è´­ä¹°â€”â€”ä»æ‹¥æœ‰è‡³å°‘ä¸€ä¸ªçš„çŸ¿èˆ¹æ°¸è¿œä¸ä¼šè¢«è¡¥å……æˆ–é‡æ–°è´­ä¹°ï¼ŒçŽ°æœ‰æ— äººæœºå°†è¢«ä¿ç•™ã€‚å—èˆ¹èˆ¶å•ä½æœºåº“å®¹é‡é™åˆ¶ã€‚è®¾ä¸º 0 å¯ç¦ç”¨é‡‡é›†æ— äººæœºçš„è‡ªåŠ¨è´­ä¹°å¹¶æ‰‹åŠ¨ç®¡ç†æ— äººæœºã€‚é»˜è®¤å€¼ 5 æ˜¯ç”¨äºŽæ­£å¸¸é‡‡çŸ¿é€Ÿåº¦çš„å®Œæ•´æ— äººæœºå¥—è£…ã€‚</t>
    <t id="31129">çŸ¿å·¥æ¯æ¬¡è¡¥è´§è¡Œç¨‹è´­ä¹°çš„èµ„æºæŽ¢é’ˆæ•°é‡ã€‚ä»…å½“èˆ¹èˆ¶ç”¨å®ŒæŽ¢æµ‹å™¨ï¼ˆè®¡æ•° = 0ï¼‰æ—¶æ‰ä¼šè§¦å‘è´­ä¹°ï¼Œè€Œä¸æ˜¯åœ¨æ¯æ¬¡éƒ¨ç½²æ—¶è§¦å‘ - è¿™æ ·çŸ¿å·¥å°±ä¼šåœ¨ä¾›åº”è¿è¡Œä¹‹é—´è¿è¡Œå…¶å…¨éƒ¨æŽ¢æµ‹å™¨è´Ÿè½½ï¼Œè€Œä¸æ˜¯åœ¨æ¯æ¬¡éƒ¨ç½²åŽç»•é“ã€‚å—èˆ¹èˆ¶æ€»å¯éƒ¨ç½²èƒ½åŠ›é™åˆ¶ï¼ˆä¸Žå«æ˜Ÿ/æ°´é›·/ç­‰å…±äº«ï¼‰ï¼›å¤§äºŽå¯ç”¨å¯éƒ¨ç½²ç©ºé—´çš„æ»‘å—å€¼ä¼šä¼˜é›…åœ°é™çº§ä¸ºâ€œå¡«å……é€‚åˆçš„ç©ºé—´â€ã€‚ä»…åœ¨å¯ç”¨è‡ªåŠ¨éƒ¨ç½²èµ„æºæŽ¢é’ˆæ—¶ç”Ÿæ•ˆ - ç›¸åŒçš„è®¾ç½®è¿˜ä¼šé©±åŠ¨é‡‡çŸ¿éƒ¨é—¨ä¸­çš„æœºä¼šæ€§æŽ¢é’ˆéƒ¨ç½²å’Œè¿‡æ—¶æŽ¢é’ˆçš„æ”¶é›†ï¼ˆæ²¡æœ‰ç¯®å­ç›¸å…³èµ„æºçš„éƒ¨é—¨ä¸­çš„æŽ¢é’ˆï¼‰ã€‚</t>
    <t id="3226">æŒ‡æŒ¥å®˜%1ï¼Œ\n\næˆ‘å·²åœé åœ¨%2ï¼Œäº¤æ˜“å­¦é™¢æ³¨å†Œå‘˜å·²ç¡®è®¤æˆ‘å·²æ³¨å†Œâ€œ%3â€è®¡åˆ’ã€‚è½¦é˜Ÿè´¦æˆ·å·²æ‰£é™¤ %4 Cr çš„è¯¾ç¨‹å­¦è´¹ï¼Œæˆ‘ä¸ä¼šè½»è§†è¿™ç¬”æŠ•èµ„ã€‚\n\nè¿™ä¸æ˜¯ä¾‹è¡Œè®¤è¯ã€‚å­¦é™¢çš„å¯¼å¸ˆéƒ½æ˜¯ç»éªŒä¸°å¯Œçš„å•†äººå’Œè´¢å›¢è°ˆåˆ¤ä»£è¡¨ï¼Œè¿™é‡Œçš„è¯¾ç¨‹è¿œæ¯”æ ‡å‡†çš„è¿›é˜¶è€ƒè¯•è¦æ±‚æ›´é«˜ã€‚åœ¨æŽ¥ä¸‹æ¥çš„ %5 åˆ†é’Ÿå†…ï¼Œæˆ‘å°†æŽ¥å—é«˜çº§äº¤æ˜“åè®®ã€åŽ‹åŠ›ä¸‹çš„å¸‚åœºåˆ†æžä»¥åŠå¸ˆå¾’åŒºåˆ†çš„è°ˆåˆ¤ç­–ç•¥çš„å¯†é›†æŒ‡å¯¼ã€‚\n\nå½“æœŸæœ«è€ƒè¯•å®Œæˆå¹¶ä¸”æˆ‘è„±ç¦»ç å¤´æ—¶ï¼Œæˆ‘å°†æ‹¥æœ‰â€œ%3â€çš„ç§°å·ï¼Œå¹¶å°†æˆ‘æ‰€å­¦åˆ°çš„ä¸€åˆ‡å¸¦å›žåˆ°æˆ‘ä»¬çš„äº¤æ˜“æ“ä½œä¸­ã€‚æˆ‘ä¸ä¼šæµªè´¹è¿™ä¸ªæœºä¼šçš„ä»»ä½•ä¸€ä¸ªç§¯åˆ†ã€‚\n\nå¸¦ç€æ„Ÿæ¿€å’Œå†³å¿ƒï¼Œ\n%6\nç™»ä¸Š %7</t>
    <t id="9924">äº¤æ˜“å­¦é™¢è¯¾ç¨‹ä¸­æ­¢ï¼šé£žè¡Œå‘˜ %1 æ— æ³•è´Ÿæ‹…å­¦é™¢ç å¤´çš„ %2 Cr è´¹ç”¨ï¼ˆæœ‰ %3 Crï¼‰ã€‚è¯¾ç¨‹å–æ¶ˆï¼Œè¯•ç‚¹æ¢å¤äº¤æ˜“ã€‚</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="88">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">å°æŽ¥ä¸¦ç­‰å¾… (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">æœŸæœ«è€ƒï¼ˆGalaxyTrader MK3ï¼‰</t>
    <t id="10004">é£›è¡Œå“¡äº¤æµæœƒåˆé»ž</t>
    <t id="10005">[å·²æ£„ç”¨] GalaxyTrader MK4 Supplyï¼ˆèˆŠç‰ˆï¼‰</t>
    <t id="10101">åœé åœ¨è»Šç«™ä¸¦ç­‰å¾…æŒ‡å®šæ™‚é–“</t>
    <t id="10102">å…·æœ‰æŠ€èƒ½é€²æ­¥çš„è‡ªä¸»äº¤æ˜“</t>
    <t id="10103">åœ¨åŸ¹è¨“æ©Ÿæ§‹åƒåŠ é£›è¡Œå“¡èªè­‰æœŸæœ«è€ƒè©¦</t>
    <t id="10104">åœé åœ¨äº¤æœƒç«™é€²è¡Œé£›è¡Œå“¡äº¤æ›</t>
    <t id="10105">ä½¿ç”¨å¿«å–å’Œå³æ™‚æœå°‹ç‚ºçŽ©å®¶ç«™æä¾›ä»¥ä¾›æ‡‰ç‚ºä¸­å¿ƒçš„äº¤æ˜“ï¼ˆèˆŠç‰ˆï¼‰</t>
    <t id="10201">å¾ž %s è³¼è²· %s</t>
    <t id="10202">å°‡ %s å‡ºå”®çµ¦ %s</t>
    <t id="10203">èˆ‡ %s é€²è¡Œäº¤æ˜“</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">å…·æœ‰ XP é€²åº¦å’Œè»ŠéšŠå”èª¿åŠŸèƒ½çš„é«˜éšŽäº¤æ˜“ç³»çµ±</t>
    <t id="1002">åŸºåœ°</t>
    <t id="1003">ä½¿ç”¨é è¨­</t>
    <t id="1004">äº¤æ˜“æ‰€æœ‰å•†å“</t>
    <t id="1005">è²¿æ˜“åˆæ³•å•†å“</t>
    <t id="1006">äº¤æ˜“éžæ³•å•†å“</t>
    <t id="1007">å•Ÿç”¨ XP é€²åº¦</t>
    <t id="1008">å•Ÿç”¨è»ŠéšŠå”èª¿</t>
    <t id="1009">å•Ÿç”¨å¸‚å ´åˆ†æž</t>
    <t id="1010">å•Ÿç”¨å€åŸŸç®¡ç†</t>
    <t id="1011">å…è¨±éžæ³•å•†å“</t>
    <t id="1012">æ—¥èªŒæ¢ç›®</t>
    <t id="1013">é¢¨éšªæ‰¿å—èƒ½åŠ›</t>
    <t id="1014">å„ªå…ˆè€ƒæ…®çŽ©å®¶ç«™</t>
    <t id="1015">è‡ªå‹•é¸æ“‡å•†å“</t>
    <t id="1016">è·é›¢ç½°åˆ†%</t>
    <t id="1017">é€šçŸ¥ç´šåˆ¥</t>
    <t id="1018">è‰¦éšŠå”èª¿</t>
    <t id="1019">è²¨ç‰©è£è¼‰ç›®æ¨™%</t>
    <t id="1050">å¸‚å ´æ›´æ–°é »çŽ‡</t>
    <t id="1051">è²¿æ˜“è©•ä¼°è¨˜éŒ„</t>
    <t id="1052">æ‰‡å€ç™½åå–®</t>
    <t id="1054">å¿½ç•¥èˆªæ¯/è¼”åŠ©è‰¦</t>
    <t id="1056">å¿½ç•¥å»ºç½®å„²å­˜</t>
    <t id="1058">å¿½è¦–è²¿æ˜“è¦å‰‡</t>
    <t id="1060">å¿½ç•¥ MK1 æä¾›çš„é›»å°</t>
    <t id="1063">é–‹ç™¼ä¸­</t>
    <t id="1064">å„ªå…ˆå•†å“</t>
    <t id="1065">å„ªå…ˆåˆ†æ•¸ %</t>
    <t id="1066">åœ¨è²¿æ˜“è¨ˆåˆ†ä¸­å—é’çžçš„å•†å“ã€‚ä»–å€‘çš„åˆ†æ•¸ä¹˜ä»¥å„ªå…ˆåˆ†æ•¸ï¼…ã€‚</t>
    <t id="1067">å„ªå…ˆå•†å“çš„åˆ†æ•¸ä¹˜æ•¸ï¼š100%=æ­£å¸¸ï¼Œ150%=+50%%ï¼Œ200%=2xï¼Œ300%=3xã€‚æœ€å¾Œæ‡‰ç”¨ã€‚</t>
    <t id="1068">â”€â”€ å„ªå…ˆå•†å“ç¯©é¸å™¨ â”€â”€</t>
    <t id="1069">å•†å“ï¼ˆæ‰‹å‹•ï¼‰</t>
    <t id="1070">éžæ³•è·¯ç”±éŽæ¿¾å™¨</t>
    <t id="1072">åªç‚ºå®¶åº­æœå‹™</t>
    <t id="1073">çŽ©å®¶ä¾›æ‡‰å•†å„ªå…ˆé †åº</t>
    <t id="1074">æ´¾ç³»ä¾›æ‡‰å•†å„ªå…ˆé †åº</t>
    <t id="1075">åŒ…æ‹¬å»ºç½®å„²å­˜</t>
    <t id="1076">åŒ…å«è³‡æº</t>
    <t id="1077">åŒ…æ‹¬ä¸­é–“é«”</t>
    <t id="1078">åŒ…æ‹¬å•†æ¥­è»Ÿé«”</t>
    <t id="1080">æ¯å€‹é€±æœŸæœ€å¤§äº¤æ˜“æ•¸</t>
    <t id="1081">å›žæº¯å®¹å·®</t>
    <t id="1082">æœ€å°è²¨ç‰©ä½¿ç”¨ç™¾åˆ†æ¯”</t>
    <t id="1083">çŽ©å®¶è³¼è²·ä¿®æ”¹%</t>
    <t id="1085">åˆ†é…è‡³ä¸»ç«™</t>
    <t id="1086">è¦†è“‹è·é›¢</t>
    <t id="1088">æ»¿è¶³éœ€æ±‚è¦†è“‹çš„é›¢å®¶æœ€å¤§è·³èºè·é›¢</t>
    <t id="1090">å°‡è²¿æ˜“å“é¡žå•†å“ç´å…¥éœ€æ±‚/ä¾›æ‡‰åŒ¹é…ä¸­</t>
    <t id="1091">åœ¨åƒ…è¨ˆåˆ†è¨ˆç®—ä¸­æ‡‰ç”¨æ–¼çŽ©å®¶æ“æœ‰çš„ä¾›æ‡‰å•†å®šåƒ¹çš„ä¿®æ”¹å™¨</t>
    <t id="1092">å¿½ç•¥çŽ©å®¶å®šåƒ¹</t>
    <t id="1093">å•Ÿç”¨å¾Œï¼šå§‹çµ‚å¾žçŽ©å®¶æ“æœ‰çš„ç¶²ç«™è³¼è²·ï¼Œç„¡è«–å…¶è¨­å®šçš„å”®åƒ¹å¦‚ä½•ï¼Œä¸¦ä¸”åƒ…å‡ºå”®çµ¦ NPC æ´¾ç³»ã€‚å°æ–¼æ¸…ç†æ‚¨è‡ªå·±çš„ç«™é»žä¸­çš„å¤šé¤˜åº«å­˜å¾ˆæœ‰ç”¨ã€‚</t>
    <t id="1094">å·²å°éŽ–å¤ªç©ºç«™</t>
    <t id="1095">æ­¤è™•é¸å–çš„å¤ªç©ºç«™æœƒå¾ž MK3 äº¤æ˜“ä¸­æŽ’é™¤ã€‚è²¿æ˜“èˆ¹ä¸æœƒå¾žé€™äº›å¤ªç©ºç«™è³¼è²·ï¼Œä¹Ÿä¸æœƒå‘å…¶å‡ºå”®ã€‚</t>
    <t id="1096">é–’ç½®åœæ³Š</t>
    <t id="1097">å•Ÿç”¨å¾Œï¼Œåè¦†æ‰¾ä¸åˆ°å·¥ä½œçš„èˆ¹è‰¦æœƒåœæ³Šåœ¨å…¶ä¸»ç«™æˆ–ä¸»å€åŸŸã€‚å€åŸŸåœæ³Šæœƒå„ªå…ˆé¸æ“‡çŽ©å®¶ç©ºé–“ç«™ï¼Œå…¶æ¬¡æ˜¯å‹å¥½ç©ºé–“ç«™ã€‚åœé é‡‹æ”¾æ™‚é–“åœ¨å…¨åŸŸè¨­å®šä¸­é…ç½®ï¼ˆ0 = ä¿æŒåœé ç›´åˆ°æ‰¾åˆ°å·¥ä½œï¼‰ã€‚</t>
    <t id="1098">è‡ªå‹•ç¸®æ”¾</t>
    <t id="1099">å•Ÿç”¨å¾Œï¼Œåœ¨å¼·åˆ¶è¨“ç·´æˆ–è²¿æ˜“å­¸é™¢å®Œæˆå¾Œï¼Œè·³èºè·é›¢æ»‘æ¡¿æœƒè¨­å®šç‚ºé£›è¡Œå“¡å…è¨±çš„æœ€å¤§ç¯„åœã€‚å–æ¶ˆå‹¾é¸å¯æ‰‹å‹•è¨­å®šè·é›¢ã€‚</t>
    <t id="11001">å»ºé€ å„²å­˜å„ªå…ˆé †åº</t>
    <t id="11002">å¤ªç©ºç«™å„ªå…ˆé †åº</t>
    <t id="11003">è¼”åŠ©è‰¦èˆ¹å„ªå…ˆé †åº</t>
    <t id="11004">èˆªæ¯å„ªå…ˆé †åº</t>
    <t id="11005">0 = åœç”¨ã€‚1-10 = åˆ†æ•¸å€çŽ‡ï¼ˆ10 = æœ€å¼·åå‘ï¼‰ã€‚æœ€çµ‚åˆ†æ•¸ = ä¾›çµ¦åˆ†æ•¸ Ã— å€çŽ‡ã€‚</t>
    <t id="11006">1 = ç„¡é¡å¤–åˆ†æ•¸ï¼ˆå„ªå…ˆè²¨ç‰©æ¸…å–®ä¸è®Šï¼‰ã€‚2-10 = ç•¶äº¤æ˜“è²¨ç‰©åœ¨å„ªå…ˆæ¸…å–®ä¸­æ™‚ï¼Œå¢žåŠ ï¼ˆå€çŽ‡âˆ’1ï¼‰Ã— åŸºç¤Žä¾›çµ¦åˆ†æ•¸ã€‚ç–ŠåŠ åœ¨é¡žåž‹åˆ†æ•¸ä¹‹ä¸Šã€‚</t>
    <t id="11007">å„ªå…ˆè²¨ç‰©åŠ æˆ</t>
    <t id="11008">%1ï¼šæ‰€æœ‰äº¤ä»˜ç›®æ¨™å„ªå…ˆé †åºæ»‘æ¡¿å‡è¨­ç‚º 0 - æ­¤å‘½ä»¤æ²’æœ‰äº¤ä»˜ç›®æ¨™ã€‚è«‹å•Ÿç”¨è‡³å°‘ä¸€å€‹é¡žåˆ¥ï¼ˆå»ºé€ å€‰å„²ã€ç©ºé–“ç«™ã€è¼”åŠ©è‰¦èˆ¹æˆ–èˆªæ¯ï¼‰ä»¥æ¢å¾©è£œçµ¦é‹è¡Œã€‚</t>
    <t id="7001">[é€²æ­¥]</t>
    <t id="7002">[è¨“ç·´]</t>
    <t id="7008">[å€’é€€]</t>
    <t id="7009">[å­¤ç«‹]</t>
    <t id="7003">[ç¶­ä¿®]</t>
    <t id="7004">[è£œçµ¦]</t>
    <t id="7005">[ç¶­è­·]</t>
    <t id="7006">[æ›´æ”¹è·¯ç·š]</t>
    <t id="7007">[æ¸…é™¤]</t>
    <t id="1020">é¸æ“‡äº¤æ˜“è€…ç¶“ç‡Ÿæ‰€åœ¨çš„æ‰€å±¬éƒ¨é–€æˆ–ç«™é»ž</t>
    <t id="1021">è³¼è²·ç‰©å“æ™‚çš„æœ€å¤§è·³é–€è·é›¢ï¼ˆå—é£›è¡Œå“¡æŠ€èƒ½é™åˆ¶ï¼‰</t>
    <t id="1022">å‡ºå”®å•†å“æ™‚çš„æœ€å¤§è·³é–€è·é›¢ï¼ˆå—é£›è¡Œå“¡æŠ€èƒ½é™åˆ¶ï¼‰</t>
    <t id="1023">æ ¹æ“šé¡žåˆ¥è‡ªå‹•é¸æ“‡åˆé©çš„å•†å“</t>
    <t id="1024">æ‰‹å‹•é¸æ“‡ç‰¹å®šäº¤æ˜“å“ç¨®</t>
    <t id="1025">å…è¨±é•ç¦å“å’Œéžæ³•å•†å“äº¤æ˜“</t>
    <t id="1026">å®‰å…¨å®¹å¿åº¦ï¼š0.0=åƒ…å®‰å…¨æ‰‡å€ï¼Œ1.0=æŽ¥å—æ‰€æœ‰é¢¨éšª</t>
    <t id="1027">é€éŽäº¤æ˜“ç¶“é©—æå‡é£›è¡Œå“¡æŠ€èƒ½</t>
    <t id="1028">éœ€è¦æ™‚è‡ªå‹•æ´¾å‡ºé£›è¡Œå“¡é€²è¡ŒåŸ¹è¨“</t>
    <t id="1029">å”èª¿å¤šè‰˜è²¿æ˜“èˆ¹ä»¥é¿å…è¡çª</t>
    <t id="1030">è²¨ç‰©é‡é»žï¼š0=å¹³è¡¡ï¼Œ1=é«˜ç´šï¼Œ2=åŸºæœ¬éœ€æ±‚ï¼Œ3=éžæ³•ï¼Œ4=æ•£è£è²¨ç‰©</t>
    <t id="1031">äº¤æ˜“å€åŸŸï¼š0=å¹³è¡¡ï¼Œ1=ä¸»å ´ï¼Œ2=è‡ªç”±æ¼«éŠ</t>
    <t id="1032">é€šçŸ¥ç­‰ç´šï¼š0=æœ€å°ã€1=æ­£å¸¸ã€2=è©³ç´°è¨Šæ¯</t>
    <t id="1033">åœ¨å„ªå…ˆéŠ·å”®ä¹‹å‰è¨­å®šç›®æ¨™è²¨ç‰©åˆ©ç”¨çŽ‡</t>
    <t id="1034">å¸‚å ´æ•¸æ“šå’Œåƒ¹æ ¼è³‡è¨Šçš„æ›´æ–°é »çŽ‡</t>
    <t id="1035">èª¿è©¦è¼¸å‡ºç­‰ç´šï¼š0=ç„¡ã€1=åŸºæœ¬ã€2=è©³ç´°æ—¥èªŒè¨˜éŒ„</t>
    <t id="1036">èˆ‡è‰¦éšŠå…±äº«æœ‰åˆ©å¯åœ–çš„è²¿æ˜“è·¯ç·šï¼ˆå¿«å–ä»¥ä¾¿å¿«é€Ÿå­˜å–ï¼‰</t>
    <t id="1037">ç·©å­˜äº¤æ˜“ä¸¦èˆ‡è»ŠéšŠåˆ†äº«æ‰€éœ€çš„æœ€ä½Žåˆ©æ½¤</t>
    <t id="1038">ç·©å­˜è²¿æ˜“è·¯ç·šå¤±æ•ˆå‰å…è¨±çš„æœ€å¤§åˆ©æ½¤ä¸‹é™</t>
    <t id="1039">ç·©å­˜çš„è²¿æ˜“è·¯ç·šåœ¨éŽæœŸå‰ä¿æŒæœ‰æ•ˆå¤šé•·æ™‚é–“</t>
    <t id="1040">å•Ÿç”¨å–®ä¸€äº¤æ˜“è©•ä¼°å’Œæ‹’çµ•çš„è©³ç´°è¨˜éŒ„ï¼ˆå¯èƒ½éžå¸¸è©³ç´°ï¼‰</t>
    <t id="1041">å•Ÿç”¨æ¯ç­†äº¤æ˜“æ—¥èªŒæ¢ç›®å’Œæ²ˆæµ¸å¼è¨“ç·´è¨Šæ¯ï¼ˆTaterTrader é¢¨æ ¼ï¼‰</t>
    <t id="1053">æ­¤æ¸…å–®ä¸­çš„ç£å€ä¸è¢«åˆ—å…¥é»‘åå–®ï¼ˆå§‹çµ‚å…è¨±ï¼‰</t>
    <t id="1055">å°‡é‹è¼¸èˆ¹å’Œè¼”åŠ©èˆ¹æŽ’é™¤åœ¨äº¤æ˜“ä¹‹å¤–</t>
    <t id="1057">å°‡å»ºé€ å„²å­˜èˆ¹æŽ’é™¤åœ¨äº¤æ˜“ä¹‹å¤–</t>
    <t id="1059">åœ¨å ±åƒ¹æœå°‹æœŸé–“å¿½ç•¥ç«™äº¤æ˜“è¦å‰‡ï¼ˆé€²éšŽï¼›å¯ä»¥é¸æ“‡é€šå¸¸è¢«å°éŽ–çš„å ±åƒ¹ï¼‰</t>
    <t id="1061">è·³éŽå…·æœ‰åˆ†é…äº†ä¾›æ‡‰æ¨¡å¼çš„ MK1 äº¤æ˜“å“¡çš„çŽ©å®¶ç«™</t>
    <t id="1062">æé«˜æ¶‰åŠæ‚¨è‡ªå·±ç«™é»žçš„è·¯ç·šçš„è²¿æ˜“åˆ†æ•¸ï¼ˆ10% åˆ†æ•¸çŽå‹µï¼‰</t>
    <t id="1071">å•Ÿç”¨ã€Œå…è¨±éžæ³•å•†å“ã€å¾Œï¼Œåƒ…åœ¨è·³èºè·¯å¾‘ä¸Šçš„æ‰€æœ‰éƒ¨é–€ï¼ˆè³¼è²·ã€éŠ·å”®å’Œä¸­é–“éƒ¨é–€ï¼‰åˆæ³•çš„æƒ…æ³ä¸‹äº¤æ˜“éžæ³•å•†å“ã€‚</t>
    <t id="1087">ä¾›æ‡‰å•†æŽ¡è³¼æœå°‹é›¢å®¶çš„æœ€å¤§è·³èºè·é›¢</t>
    <t id="1089">ç¦ç”¨æ™‚ï¼Œèˆ¹èˆ¶å¯ä»¥æŒ‰ç·Šæ€¥å„ªå…ˆç´šè€Œä¸æ˜¯åƒ…åœ¨å®¶æ¨¡å¼å‘è¦†è“‹å€åŸŸå…§çš„é›»å°æä¾›è£œçµ¦</t>
    <t id="2000">%s å·²ç²å¾— %s XPï¼</t>
    <t id="2001">%s å·²å‡ç´šï¼æ–°ç­‰ç´šï¼š%s</t>
    <t id="2002">%s éœ€è¦åŸ¹è¨“ï¼è«‹å¯„è‡³æœ€è¿‘çš„èˆ¹å» æˆ–è²¿æ˜“ç«™ã€‚</t>
    <t id="2003">%s å·²åœ¨ %s é–‹å§‹åŸ¹è¨“</t>
    <t id="2004">%s å·²å®ŒæˆåŸ¹è¨“ï¼Œç¾å·²ç²å¾— %s ç´šèªè­‰ï¼</t>
    <t id="2005">%s åœ¨åŸ¹è¨“å¾Œé”åˆ°æŠ€èƒ½ç­‰ç´š %sï¼%s è™•å·²è§£éŽ– XP é€²åº¦ã€‚</t>
    <t id="2006">%s é€éŽ %s äº¤æ˜“é”åˆ°æŠ€èƒ½ç­‰ç´š %sï¼</t>
    <t id="2007">%s å®Œæˆäº†ç­‰ç´š %s åŸ¹è¨“ï¼%s è™•å·²è§£éŽ– XP é€²åº¦ã€‚</t>
    <t id="3000">%s å·²å®Œæˆäº¤æ˜“ï¼åˆ©æ½¤ï¼š%s Cr</t>
    <t id="3001">%s æ­£åœ¨åˆ†æžå¸‚å ´ç‹€æ³...</t>
    <t id="3002">%s æ‰¾åˆ°äº†ä¸€æ¢æœ‰åˆ©å¯åœ–çš„è²¿æ˜“è·¯ç·šï¼</t>
    <t id="3003">%s æ²’æœ‰å¯ç”¨çš„æœ‰åˆ©å¯åœ–çš„è²¿æ˜“è·¯ç·š</t>
    <t id="3100">å°‡ %1 %2 çš„è²¨ç‰©å‡ºå”®è‡³ %3ï¼Œåƒ¹æ ¼ç‚º %4ã€‚æˆ‘æ‡‰è©²è³ºå– %5 åˆ©æ½¤ã€‚</t>
    <t id="3101">æ­£åœ¨æŽ’éšŠ %1 %2 çš„äº¤æ˜“è¨‚å–®ã€‚ä»¥ %3 å¾ž %4 è²·å…¥ï¼Œä»¥ %5 å‘ %6 è³£å‡ºã€‚æˆ‘æ‡‰è©²è³ºå– %7 åˆ©æ½¤ã€‚</t>
    <t id="3102">å¤ªç©ºç«™è²¿æ˜“å•†ï¼šæ­£å¾ž %3ï¼ˆ%5%%ï¼‰å‘ %4ï¼ˆ%6%%ï¼‰ä¾›æ‡‰ %1 %2ã€‚</t>
    <t id="3103">å¤ªç©ºç«™è²¿æ˜“å•†ï¼šå‘ %3 å‡ºå”® %1 %2ï¼Œå–®åƒ¹ %4ã€‚é æœŸåˆ©æ½¤ %5ã€‚</t>
    <t id="3104">%1 %2 çš„äº¤æ˜“å·²æˆåŠŸå®Œæˆã€‚ç¸½åˆ©æ½¤ï¼š%3 ç©åˆ†ã€‚</t>
    <t id="3105">å¿«å–çš„è²¿æ˜“è·¯ç·šï¼š%1 %2 å¾ž %3 åˆ° %4ï¼ˆåˆ©æ½¤ï¼š%5 Crï¼‰</t>
    <t id="3106">\næœ¬æ¬¡äº¤æ˜“å‰çš„é æœŸçµ‚èº«åˆ©æ½¤ç¸½é¡ï¼š%1 Crã€‚</t>
    <t id="3120">è©¦é»žè½‰ç§»å•Ÿå‹•</t>
    <t id="3121">å‚³è¼¸å”å®šå·²ç¢ºèªã€‚ %1 (%2) å’Œ %3 (%4) æ­£å‰å¾€ %5 (%6) åœé ä¸¦äº¤æ›æŒ‡æ®åº§ä½ã€‚</t>
    <t id="3200">æŒ‡æ®å®˜æ‚¨å¥½%1ï¼Œ\n\næˆ‘å·²ç¶“ç²å¾—äº†è¶³å¤ çš„ç¶“é©—ä¾†åƒåŠ ã€Œ%2ã€é ­éŠœçš„èªè­‰è€ƒè©¦ã€‚è€ƒè©¦å¤§ç´„éœ€è¦ %3 åˆ†é˜ï¼Œæ™‚é–“ç‚º %4.\n\né€™æ˜¯æˆ‘è·æ¥­ç™¼å±•ä¸­çš„ä¸€å€‹é‡è¦é‡Œç¨‹ç¢‘ã€‚è©²è€ƒè©¦å°‡æ¸¬è©¦æˆ‘å°é«˜ç´šäº¤æ˜“å”è­°ã€å¸‚å ´åˆ†æžå’Œè»ŠéšŠå”èª¿ç¨‹åºçš„äº†è§£ã€‚ \n\næˆ‘å°è‡ªå·±çš„èƒ½åŠ›å……æ»¿ä¿¡å¿ƒï¼Œä¸¦å¾ˆé«˜èˆˆè­‰æ˜Žè‡ªå·±å€¼å¾—é€™ä¸€é€²æ­¥ã€‚ç¥æˆ‘å¥½é‹ï¼ \n\nè¬¹è‡´\n%5\nç™»ä¸Š%6</t>
    <t id="3201">æŒ‡æ®å®˜%1ï¼Œ\n\nå¥½æ¶ˆæ¯ï¼æˆ‘å·²æˆåŠŸå®Œæˆèªè­‰è€ƒè©¦ä¸¦ç²å¾—â€œ%2â€ç¨±è™Ÿï¼ \n\nè€ƒè©¦æ¶µè“‹é«˜ç´šäº¤æ˜“ç­–ç•¥ã€é¢¨éšªè©•ä¼°å”è­°å’Œè»ŠéšŠå”èª¿ç¨‹åºã€‚æˆ‘å¾ˆé«˜èˆˆåœ°å ±å‘Šï¼Œæˆ‘ä»¥å„ªç•°çš„æˆç¸¾é€šéŽäº†è€ƒè©¦ã€‚ \n\næˆ‘ç¾åœ¨æœ‰è³‡æ ¼è™•ç†æ›´è¤‡é›œçš„è²¿æ˜“æ“ä½œï¼Œä¸¦æœŸå¾…ç‚ºæˆ‘å€‘èˆ¹éšŠçš„æˆåŠŸåšå‡ºæ›´å¤šè²¢ç»ã€‚æ„Ÿè¬æ‚¨å°æˆ‘çš„è·æ¥­ç™¼å±•çš„æŠ•è³‡ã€‚ \n\næ†‘è—‰è‘—æ–°çš„å¥‰ç»ç²¾ç¥žï¼Œ\n%3\nç²å¾—èªè­‰ %2\nåŠ å…¥ %4</t>
    <t id="3202">%1æŒ‡æ®å®˜ï¼Œ\n\nå¾ˆéºæ†¾åœ°é€šçŸ¥æ‚¨ï¼Œç”±æ–¼ä½œæ¥­éœ€è¦ï¼Œæˆ‘çš„èªè­‰è€ƒè©¦è¢«ä¸­æ–·ã€‚åœ¨æƒ…æ³å…è¨±çš„æƒ…æ³ä¸‹ï¼Œæˆ‘éœ€è¦é‡æ–°å®‰æŽ’æ™‚é–“ã€‚ \n\næˆ‘ä»ç„¶è‡´åŠ›æ–¼æé«˜æˆ‘çš„æŠ€èƒ½ï¼Œä¸¦å°‡åœ¨å¯ä»¥æ¢å¾©è€ƒè©¦éŽç¨‹æ™‚é€šçŸ¥æ‚¨ã€‚ \n\nå°Šæ•¬çš„ï¼Œ\n%2\nç™»ä¸Š %3</t>
    <t id="3203">æŒ‡æ®å®˜ %1ï¼Œ\n\næˆ‘ç›®å‰æ­£åœ¨å‰å¾€ %2 åƒåŠ èªè­‰è€ƒè©¦çš„é€”ä¸­ã€‚é€™æ®µæ—…ç¨‹è®“æˆ‘æœ‰æ™‚é–“å›žé¡§æˆ‘çš„å­¸æ¥­ï¼Œä¸¦ç‚ºæˆ‘è·æ¥­ç”Ÿæ¶¯ä¸­çš„é€™ä¸€é‡è¦æ­¥é©Ÿåšå¥½å¿ƒç†æº–å‚™ã€‚ \n\né è¨ˆæŠµé”ï¼š%3 åˆ†é˜\nè€ƒè©¦æ™‚é–“ï¼š%4 åˆ†é˜\n\næ„Ÿè¬æ‚¨å°æˆ‘çš„èƒ½åŠ›çš„ä¿¡å¿ƒå’Œé€²æ­¥çš„æ©Ÿæœƒã€‚ \n\nå¸¶è‘—æ±ºå¿ƒï¼Œ\n%5\nç™»ä¸Š %6</t>
    <t id="3204">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘åœ¨ç³»çµ±æª¢æŸ¥æœŸé–“åµæ¸¬åˆ°è²¨è‰™å…§æœ‰è²¨ç‰©ã€‚åœ¨é–‹å§‹æ­£å¸¸çš„äº¤æ˜“æ“ä½œä¹‹å‰ï¼Œæˆ‘éœ€è¦å‡ºå”®è©²å•†å“ã€‚ \n\næˆ‘æ­£åœ¨ä½¿ç”¨æˆ‘å€‘çš„è²¿æ˜“æœå°‹ä¾†å°‹æ‰¾æœ€ä½³è²·å®¶ä¸¦å®‰å…¨åœ°å¸ä¸‹è©²è²¨ç‰©ã€‚ä¸€æ—¦æˆ‘çš„æŒå€‰æ¸…ç©ºï¼Œæˆ‘å°‡ç¹¼çºŒé€²è¡Œè‡ªå‹•äº¤æ˜“ã€‚ \n\nç‹€æ…‹ï¼šæ­£åœ¨æœå°‹æœ€ä½³éŠ·å”®ä½ç½®\n\nç¶“éŽåŠªåŠ›ï¼Œ\nç™»ä¸Š %1</t>
    <t id="3205">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘çš„èˆ¹é«”å®Œæ•´æ€§å·²é™è‡³ %1%%ï¼ˆé–¾å€¼ï¼š%2%%ï¼‰ã€‚èº«ç‚º %3 ç´šé£›è¡Œå“¡ï¼Œæˆ‘æœ‰æ¬Šè«‹æ±‚è‡ªå‹•ç¶­ä¿®æœå‹™ã€‚ \n\næˆ‘å°‡å‰å¾€ %4 é€²è¡Œç¶­ä¿®å·¥ä½œã€‚é è¨ˆæˆæœ¬ç‚º %5 Crï¼Œåœ¨æˆ‘å€‘çš„é ç®—ä¹‹å…§ã€‚ \n\nä¿®â€‹â€‹å¾©å®Œæˆå¾Œï¼Œæˆ‘å°‡åœ¨çµæ§‹å®Œå…¨å®Œæ•´çš„æƒ…æ³ä¸‹æ¢å¾©äº¤æ˜“æ“ä½œã€‚ \n\nå°Šæ•¬çš„ï¼Œ\nç™»ä¸Š %6</t>
    <t id="3206">æŒ‡æ®å®˜ï¼Œ\n\nç·Šæ€¥è²¡å‹™è­¦å‘Š\n\næˆ‘çš„èˆ¹é«”å®Œæ•´æ€§åœ¨ %1%% è™•è‡³é—œé‡è¦ï¼ˆé–¾å€¼ï¼š%2%%ï¼‰ï¼Œä½†æˆ‘å€‘çš„å¯ç”¨è³‡é‡‘ (%3 Cr) ä¸è¶³ä»¥é€²è¡Œå…¨é¢ç¶­ä¿®ï¼ˆé è¨ˆæˆæœ¬ï¼š%4 Crï¼‰ã€‚ \n\næˆ‘å°‡ä½¿ç”¨æˆ‘å€‘çš„å¯ç”¨è³‡é‡‘å‰å¾€ %5 é€²è¡Œéƒ¨åˆ†ç¶­ä¿®ã€‚é€™ä¸æ˜¯ä¸€å€‹ç†æƒ³çš„è§£æ±ºæ–¹æ¡ˆï¼Œä½†ç¶­æŒç‡Ÿé‹èƒ½åŠ›æ˜¯å¿…è¦çš„ã€‚ \n\nè«‹è€ƒæ…®ç‚ºæœªä¾†çš„ç¶­è­·ç‡Ÿé‹åˆ†é…é¡å¤–çš„è³‡é‡‘ã€‚ \n\né—œå¿ƒä½†æ±ºå¿ƒï¼Œ\nç™»ä¸Š %6</t>
    <t id="3207">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘çš„ç­‰ç´š%1èªè­‰æŽˆæ¬Šè‡ªå‹•è£œçµ¦é˜²ç¦¦è£å‚™ã€‚æª¢æŸ¥æˆ‘çš„ç³»çµ±å¾Œï¼Œæˆ‘ç¢ºå®šæˆ‘çš„å°ç­–å’Œå¯éƒ¨ç½²è£å‚™ä½Žæ–¼å»ºè­°çš„é–¾å€¼ã€‚ \n\næˆ‘å°‡ç¹¼çºŒ %2 è£œå……æˆ‘çš„é˜²ç¦¦è¨­å‚™ï¼š\nâ€¢ å°ç­–ï¼šè£œå……è‡³æœ€ä½³å®¹é‡\nâ€¢ é˜²ç¦¦ç„¡äººæ©Ÿã€è²¿æ˜“ç„¡äººæ©Ÿã€æ¿€å…‰å¡”ï¼šæ‡‰ç”¨å¹³è¡¡é…ç½®æ–‡ä»¶\n\næ­¤è£œçµ¦å¯ç¢ºä¿æˆ‘åœ¨ä¿æŒäº¤æ˜“æ•ˆçŽ‡çš„åŒæ™‚æœ€å¥½åœ°æŠµç¦¦å¤ªç©ºå¨è„…ã€‚ \n\nä¿æŒè­¦æƒ•ï¼Œ\nç™»ä¸Š%3</t>
    <t id="3212">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘çš„èˆ¹é«”å®Œæ•´æ€§å·²é™è‡³%1%%ï¼ˆé–¾å€¼ï¼š%2%%ï¼‰ï¼Œéœ€è¦ç¶­ä¿®æœå‹™ã€‚ç„¶è€Œï¼Œç”±æ–¼éƒ¨é–€æ—…è¡Œé™åˆ¶ï¼ˆåˆ—å…¥é»‘åå–®çš„è·¯ç·šï¼‰ï¼Œç›®å‰ç„¡æ³•åˆ°é”æœ€è¿‘çš„ç¶­ä¿®ç«™ %3ã€‚ \n\nå„˜ç®¡æœ‰æ­¤é™åˆ¶ï¼Œæˆ‘ä»å°‡ç¹¼çºŒé€²è¡Œäº¤æ˜“æ“ä½œã€‚ä¸€æ—¦å®‰å…¨è·¯ç·šå†æ¬¡å¯ç”¨ï¼Œæˆ‘å°‡è‡ªå‹•å°‹æ±‚ç¶­ä¿®æœå‹™ã€‚ \n\næˆ‘å°‡ç›£æŽ§æƒ…æ³ä¸¦åœ¨å¯ä»¥ç¶­ä¿®æ™‚é€šçŸ¥æ‚¨ã€‚ \n\nå°Šæ•¬çš„ï¼Œ\nç™»ä¸Š %4</t>
    <t id="3213">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘çš„é˜²ç¦¦è£å‚™éœ€è¦è£œçµ¦ï¼Œä½†ç”±æ–¼å€åŸŸæ—…è¡Œé™åˆ¶ï¼ˆé»‘åå–®è·¯ç·šï¼‰ï¼Œç›®å‰ç„¡æ³•åˆ°é”æœ€è¿‘çš„è£å‚™ç«™%1ã€‚ \n\nå„˜ç®¡æœ‰æ­¤é™åˆ¶ï¼Œæˆ‘ä»å°‡ç¹¼çºŒé€²è¡Œäº¤æ˜“æ“ä½œã€‚ä¸€æ—¦å®‰å…¨è·¯ç·šå†æ¬¡å¯ç”¨ï¼Œæˆ‘å°‡è‡ªå‹•å°‹æ±‚è£œçµ¦æœå‹™ã€‚ \n\næˆ‘å°‡ç›£è¦–æƒ…æ³ä¸¦åœ¨å¯ä»¥è£œçµ¦æ™‚é€šçŸ¥æ‚¨ã€‚ \n\nå°Šæ•¬çš„ï¼Œ\nç™»ä¸Š %2</t>
    <t id="3208">Commander,\n\nI've completed an exhaustive market analysis of %1 and surrounding sectors (within %2 jumps, minimum profit threshold: %3 Cr), but unfortunately found no profitable trading opportunities that meet our requirements.\n\nTRADE ANALYSIS REPORT:\nTotal opportunities evaluated: %4\n\nREJECTION BREAKDOWN:\n- Docking restrictions: %5 trades\n  (Station doesn't permit my ship class)\n- Insufficient profitability: %6 trades\n  (Below minimum profit threshold)\n- Insufficient volume: %7 trades\n  (Zero or negative tradeable amount)\n- Safety restrictions: %8 trades\n  (Blacklisted stations or dangerous sectors)\n\nRECOMMENDATIONS:\n- Consider adjusting profit thresholds\n- Expand maximum trading distance\n- Review sector blacklist settings\n- Wait for market conditions to improve\n\nI'll continue monitoring the market and will notify you when profitable opportunities become available.\n\nStanding by,\nAboard your service</t>
    <t id="3209">æŒ‡æ®å®˜ï¼Œ\n\nç·Šæ€¥è·¯ç·šè­¦å ±\n\næˆ‘çš„å¨è„…æƒ…å ±ç³»çµ±åµæ¸¬åˆ°ç£å€ %1ï¼ˆå¨è„…ç­‰ç´š %2ï¼‰ç¾åœ¨ä½æ–¼æˆ‘è¨ˆç•«çš„è²¿æ˜“è·¯ç·šä¸­ã€‚ç‚ºäº†èˆ¹èˆ¶å’Œèˆ¹å“¡çš„å®‰å…¨ï¼Œæˆ‘ç«‹å³ä¸­æ­¢ç›®å‰çš„è²¿æ˜“ä½œæ¥­ã€‚ \n\næŽ¡å–çš„è¡Œå‹•ï¼š\n- å–æ¶ˆæ‰€æœ‰è²¿æ˜“è¨‚å–®\n- è¿”å›žå®‰å…¨æ“ä½œæ¨¡å¼\n- å°‡æ‰¾åˆ°é¿é–‹å±éšªå€åŸŸçš„æ›¿ä»£è²¿æ˜“è·¯ç·š\n- è²¨ç‰©è£å¸ï¼šè‡ªå‹•ï¼ˆå¦‚æžœéœ€è¦ï¼Œå°‡åœ¨å®‰å…¨ä½ç½®å‡ºå”®ä»»ä½•è²¨ç‰©ï¼‰\n\nå‹•æ…‹é»‘åå–®ç³»çµ±å°‡é˜»æ­¢æœªä¾†é€šéŽè©²å€åŸŸçš„äº¤æ˜“ï¼Œç›´åˆ°å¨è„…è¢«æ¸…é™¤ã€‚ \n\nå®‰å…¨æ˜¯æˆ‘çš„é¦–è¦ä»»å‹™å„ªå…ˆã€‚ \n\nä¿æŒè­¦æƒ•ï¼Œ\nç™»ä¸Š %3</t>
    <t id="3210">æŒ‡æ®å®˜ï¼Œ\n\né€ƒç”Ÿè·¯ç·šå·²å•Ÿå‹•\n\næˆ‘ç›®å‰ä½æ–¼é»‘åå–®æ‰‡å€%1ï¼Œä¸¦æ‰¾åˆ°äº†ä¸€æ¢å¯ä»¥å®‰å…¨é€ƒè„«çš„è²¿æ˜“è·¯ç·šã€‚ \n\nè²¿æ˜“è·¯ç·šï¼š\nè³¼è²·ï¼š%2ï¼ˆæ‰‡å€ï¼š%3ï¼‰\nå‡ºå”®ï¼š%4ï¼ˆæ‰‡å€ï¼š%5ï¼‰\nè²¨ç‰©ï¼š%6 (x%7)\né æœŸåˆ©æ½¤ï¼š%8 Cr\n\nå®Œæˆæœ¬æ¬¡äº¤æ˜“å¾Œï¼Œèˆ¹èˆ¶å°‡è„«é›¢é»‘åå–®å€åŸŸã€‚ \n\nå°Šæ•¬çš„\nç™»ä¸Šæ‚¨çš„æœå‹™</t>
    <t id="3211">æŒ‡æ®å®˜ï¼Œ\n\néš”é›¢äº¤æ˜“æ¨¡å¼\n\næˆ‘ç›®å‰ä½æ–¼%2æ‰‡å€ï¼Œä½†æ‰€æœ‰é€šå¾€å…¶ä»–æ‰‡å€çš„è·¯ç·šéƒ½è¢«åˆ—å…¥é»‘åå–®çš„æ¨žç´æ‰‡å€å°éŽ–ã€‚é€™æ„å‘³è‘—æˆ‘åªèƒ½åœ¨ç•¶å‰çš„è¡Œæ¥­å…§é€²è¡Œäº¤æ˜“ï¼Œç›´åˆ°é»‘åå–®æƒ…æ³ç™¼ç”Ÿè®ŠåŒ–ã€‚ \n\næƒ…æ³ï¼š\nç•¶å‰è¡Œæ¥­ï¼š%2\nç‹€æ…‹ï¼šéš”é›¢ï¼ˆéžé»‘åå–®è¡Œæ¥­ï¼Œè·¯ç·šè¢«å°éŽ–ï¼‰\näº¤æ˜“æ¨¡å¼ï¼šåƒ…é™è¡Œæ¥­å…§äº¤æ˜“\n\næˆ‘çš„äº¤æ˜“ç³»çµ±å·²è‡ªå‹•èª¿æ•´åˆ©æ½¤é–¾å€¼ï¼Œä»¥å„ªå…ˆè€ƒæ…®å¯ç”¨çš„è¡Œæ¥­å…§äº¤æ˜“æ©Ÿæœƒã€‚ \n\næˆ‘å°‡ç¹¼çºŒç›£æŽ§æƒ…æ³ï¼Œä¸¦åœ¨è·¯ç·šå¯ç”¨æ™‚é€šçŸ¥æ‚¨å†æ¬¡ã€‚ \n\nå°Šæ•¬çš„ï¼Œ\nç™»ä¸Š %1</t>
    <t id="3218">æŒ‡æ®å®˜ï¼Œ\n\nåµæ¸¬åˆ°è·¯ç·šè·¯å¾‘è®Šæ›´\n\né€²å…¥ç£å€ %1 å¾Œï¼Œæˆ‘çš„å°Žè¦½ç³»çµ±åµæ¸¬åˆ°å‰å¾€ç›®çš„åœ° %2 (%3) çš„è·¯ç·šå·²è®Šæ›´ã€‚ \n\nè·¯å¾‘åˆ†æžï¼š\n- æ­£å¸¸è·é›¢ï¼š%4 è·³èº\n- é»‘åå–®æ„ŸçŸ¥è·é›¢ï¼š%5\n- ç‹€æ…‹ï¼š%6\n\næˆ‘çš„å°Žèˆªè¨ˆç®—æ©Ÿè¡¨ç¤ºç”±æ–¼èˆªæ®µæ—…è¡Œé™åˆ¶ï¼Œé¦–é¸è·¯ç·šä¸å†å¯è¡Œã€‚ç‚ºäº†èˆ¹èˆ¶å’Œèˆ¹å“¡çš„å®‰å…¨ï¼Œæˆ‘ç«‹å³ä¸­æ­¢ç›®å‰çš„è²¿æ˜“ä½œæ¥­ã€‚ \n\næŽ¡å–çš„è¡Œå‹•ï¼š\n- æ‰€æœ‰è²¿æ˜“è¨‚å–®å–æ¶ˆ\n- è¿”å›žå®‰å…¨æ“ä½œæ¨¡å¼\n- å°‡æ‰¾åˆ°é¿é–‹å°éŽ–èˆªæ®µçš„æ›¿ä»£è²¿æ˜“è·¯ç·š\n- é¿é–‹è²¨ç‰©è£å¸ï¼šè‡ªå‹•ï¼ˆå¦‚æžœéœ€è¦ï¼Œå°‡åœ¨å®‰å…¨ä½ç½®å‡ºå”®ä»»ä½•è²¨ç‰©ï¼‰\n\næˆ‘çš„å°Žèˆªç³»çµ±å°‡åœ¨æœªä¾†çš„è·¯ç·šè¦åŠƒä¸­è‡ªå‹•å°éŽ–èˆªæ®µã€‚ \n\nå®‰å…¨æ˜¯æˆ‘çš„é¦–è¦ä»»å‹™ã€‚ \n\nèˆ‡ä¿æŒè­¦æƒ•ï¼Œ\nç™»ä¸Š %7</t>
    <t id="3219">ç£å€ %1 å·²æ¸…é™¤ - æ‰€æœ‰å¨è„…å‡å·²æ¶ˆé™¤</t>
    <t id="3220">Commander,\n\nENEMY SHIP ESCAPED\n\nOur threat intelligence system has lost track of enemy ship %3, which has escaped from blacklisted sector %1.\n\nDETAILS:\n- Escaped Ship: %3\n- Sector Left: %1\n- Destination Sector: %2\n- Status: Tracking lost - ship has left our monitored area\n\nWhile this ship is no longer a threat in sector %1, we have lost visual contact and cannot confirm its current status or intentions in sector %2.\n\nOur tracking systems will continue monitoring sector %1 for remaining threats. If all tracked enemies leave or are eliminated, the sector will be automatically cleared from the blacklist.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3221">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘ç„¡æ³•åœ¨æ›´é çš„è·é›¢ï¼ˆæœ€å¤š%3è·³èºï¼‰æ‰¾åˆ°æœ‰åˆ©å¯åœ–çš„äº¤æ˜“æ©Ÿæœƒï¼Œå› ç‚ºç”±æ–¼æ‰‡å€æ—…è¡Œé™åˆ¶ï¼ˆåˆ—å…¥é»‘åå–®çš„è·¯å¾‘ï¼‰ï¼Œé€™äº›è·¯ç·šç›®å‰ç„¡æ³•åˆ°é”ã€‚ \n\næƒ…æ³ï¼š\nç›®å‰ç£å€ï¼š%2\nåŽŸå§‹æœå°‹ç¯„åœï¼š%3è·³èº\nå›žé€€æœå°‹ç¯„åœï¼š%4è·³èº\n\næˆ‘ç¾åœ¨å°‡æœå°‹é›†ä¸­åœ¨é™„è¿‘çš„ç£å€åœ¨ %4 è·³èºå…§ï¼Œè·¯ç·šæ›´æœ‰å¯èƒ½å¯é”ã€‚é€™æ‡‰è©²å¯ä»¥å¹«åŠ©æˆ‘æ‰¾åˆ°ä¹‹å‰å› è·é›¢é™è£½è€Œä¸æ˜¯å¯¦éš›ç„¡åˆ©å¯åœ–è€Œè¢«éŽæ¿¾æŽ‰çš„æœ‰åˆ©å¯åœ–çš„äº¤æ˜“ã€‚ \n\nç•¶æˆ‘åœ¨é™„è¿‘å€åŸŸæ‰¾åˆ°åˆé©çš„äº¤æ˜“æ©Ÿæœƒæ™‚ï¼Œæˆ‘æœƒé€šçŸ¥æ‚¨ã€‚ \n\nå°Šæ•¬çš„ï¼Œ\nç™»ä¸Š %1</t>
    <t id="3222">æŒ‡æ®å®˜ï¼Œ\n\nå·²åˆ—å…¥é»‘åå–®çš„æ‰‡å€\n\næˆ‘å€‘çš„å¨è„…æƒ…å ±ç³»çµ±å·²æª¢æ¸¬åˆ°æ‰‡å€ %1 ä¸­çš„æ•µå°æ´»å‹•ï¼Œä¸¦è‡ªå‹•å°‡è©²æ‰‡å€åˆ—å…¥é»‘åå–®ï¼Œä»¥ä¿è­·æˆ‘å€‘çš„è²¿æ˜“é‹ç‡Ÿã€‚ \n\nåµæ¸¬åˆ°çš„æ•µè‰¦ï¼š\n%2\n\nåµæ¸¬è€…ï¼š%3\n\nç‚ºäº†æˆ‘å€‘èˆ¹éš»å’Œèˆ¹å“¡çš„å®‰å…¨ï¼Œç¶“éŽè©²æ‰‡å€çš„æ‰€æœ‰è²¿æ˜“è·¯ç·šå‡å·²è¢«å°éŽ–ã€‚æˆ‘æ–¹è‰¦è‰‡å°‡è‡ªå‹•ç¹žè¡Œè©²å€åŸŸï¼Œç›´åˆ°å¨è„…è¢«æ¶ˆé™¤ã€‚ \n\nä¸€æ—¦æ‰€æœ‰è¿½è¹¤çš„æ•µè‰¦è¢«æ¶ˆæ»…æˆ–é›¢é–‹è©²å€åŸŸï¼Œè©²å€åŸŸå°‡è‡ªå‹•å¾žé»‘åå–®ä¸­æ¸…é™¤ã€‚ \n\nåœ¨ä¿æŒè­¦æƒ•çš„æƒ…æ³ä¸‹ï¼Œ\nå¨è„…æƒ…å ±ç³»çµ±</t>
    <t id="3223">æŒ‡æ®å®˜ï¼Œ\n\næˆ‘æ‰¾ä¸åˆ°é©åˆ %1 ç´šé€²éšŽè€ƒè©¦çš„ç„¡éšœç¤™è¨“ç·´ç«™ã€‚æˆ‘å°‡æŒ‰ç…§æŒ‡ç¤ºé€²è¡Œäº¤æ˜“æ“ä½œï¼Œä½†æˆ‘äº†è§£ï¼Œåœ¨å®Œæˆæ‰€éœ€çš„åŸ¹è¨“ä¹‹å‰ï¼Œæˆ‘ä¸æœƒç²å¾—ç¶“é©—å€¼ã€‚é€™æ¬¡äº¤æ˜“çµæŸå¾Œï¼Œæˆ‘å°‡å†æ¬¡å°‹æ‰¾ä»»ä½•å¯èƒ½çš„åŸ¹è¨“æ©Ÿæœƒã€‚ \n\nå°Šæ•¬çš„\nç™»ä¸Š %2</t>
    <t id="3224">è¨“ç·´è¨±å¯è²»ï¼š%1 Cr</t>
    <t id="3225">çŽå‹µï¼šæˆ‘å¾žè¨“ç·´æœŸé–“ç´¯ç©çš„ç¶“é©—ä¸­ç²å¾—äº†%1é¡å¤–æŠ€èƒ½ç­‰ç´š%2ï¼ç›®å‰ç­‰ç´šï¼š%3</t>
    <t id="3214">å¾ˆæ¦®å¹¸ç‚ºæ‚¨å·¥ä½œï¼Œ%1ï¼æˆ‘å¾ˆé«˜èˆˆèƒ½åœ¨æ‚¨çš„æŒ‡æ®ä¸‹é–‹å§‹æˆ‘çš„äº¤æ˜“ç”Ÿæ¶¯ã€‚æˆ‘å°‡ç«­ç›¡å…¨åŠ›ç‚ºæ‚¨æœå‹™ï¼Œç‚ºæ‚¨çš„æˆåŠŸåšå‡ºè²¢ç»ã€‚</t>
    <t id="3215">æ„Ÿè¬æ‚¨çµ¦äº†æˆ‘é€™å€‹ç•¶ä¹‹ç„¡æ„§çš„å‡æœŸï¼Œ%1ï¼æˆ‘å¾ˆäº«å—é é›¢äº¤æ˜“çš„æ™‚å…‰ï¼Œè€Œä¸”æˆ‘çš„æŠ€èƒ½ä»ç„¶å®Œå¥½ç„¡æã€‚æˆ‘æœŸå¾…è‘—åœ¨æ‚¨éœ€è¦æˆ‘çš„æ™‚å€™é‡è¿”å·¥ä½œå´—ä½ã€‚åœ¨é‚£ä¹‹å‰ï¼Œæˆ‘å°‡ä¿æŒæˆ‘çš„äº¤æ˜“çŸ¥è­˜æ•éŠ³ï¼</t>
    <t id="3216">æˆ‘åº¦å‡å›žä¾†ï¼Œæº–å‚™å†æ¬¡å·¥ä½œï¼Œ%1ï¼æˆ‘çš„äº¤æ˜“æŠ€å·§ä¾ç„¶æ•éŠ³ï¼Œæˆ‘æ¸´æœ›ç¹¼çºŒåœ¨ %2 ä¸Šç‚ºæ‚¨æœå‹™ã€‚æ„Ÿè¬æ‚¨æ‡‰å¾—çš„ä¼‘æ¯ï¼</t>
    <t id="3217">æ„Ÿè¬æ‚¨å°‡æˆ‘è½‰è‡³ %1ã€%2ï¼æˆ‘å°é€™é …æ–°ä»»å‹™æ„Ÿåˆ°å¾ˆæ¦®å¹¸ï¼Œä¸¦å°‡å¦¥å–„ä¿ç®¡æˆ‘çš„æ–°èˆ¹ã€‚æˆ‘çš„äº¤æ˜“ç¶“é©—å’ŒæŠ€èƒ½ä»ç„¶å®Œå¥½ç„¡æï¼Œæˆ‘å·²æº–å‚™å¥½ç¹¼çºŒç‚ºæ‚¨æœå‹™ã€‚</t>
    <t id="3227">èˆ¹é«”éºå¤±ï¼Œå°Šåš´å¾…å›žæ”¶</t>
    <t id="3228">%1 æŒ‡æ®å®˜ï¼Œ\n\n%2 å¾ž %3 å ±å‘Šã€‚æˆ‘çš„é£›èˆ¹çˆ†ç‚¸äº†ã€‚æˆ‘æ²’æœ‰ã€‚æˆ‘ç¾åœ¨æ˜¯è‰¦éšŠæœ€æ˜‚è²´çš„æ¼‚æµ®è²¨ç‰©ã€‚\n\nå·²é™„åŠ åœ°åœ–æ¨™è¨˜ã€‚è«‹å¿«é»ž - æˆ‘æ­£åœ¨é–‹ç™¼ç¥¨ã€‚\n\nå°ˆæ¥­åœ°æ¼‚æµ®è‘—ï¼Œ\n%2</t>
    <t id="3229">é£›è¡Œå“¡å·²å›žæ”¶ - æ°§æ°£æˆç™®å·²æ²»ç™’</t>
    <t id="3230">%1 æŒ‡æ®å®˜ï¼Œ\n\nè‰¦éšŠæ›´æ–°ï¼š%2 å·²è¢« %3 (%4) æ’ˆèµ·ï¼Œä¸å†å‘æ‚¨æ”¶å–å»¶é•· EVA è¨“ç·´è²»ç”¨ã€‚\n\næ­£åœ¨é‡æ–°ç¶å®šè¨»å†Šè¡¨ã€‚å»ºè­°ä¸è¦è¿½å•èˆŠé£›èˆ¹çš„ä¸‹è½ã€‚\n\næ…šæ„§åœ°ï¼Œ\n%2</t>
<t id="4000">è»ŠéšŠå”èª¿ï¼š%s å·²åˆ†é…èˆªç·š %s</t>
    <t id="4001">è»ŠéšŠå”èª¿ï¼šè·¯ç·š %s å·²å……åˆ†åˆ©ç”¨</t>
    <t id="4002">è»ŠéšŠå”èª¿ï¼š%s å·²ç™¼å¸ƒèˆªç·š %s</t>
    <t id="5000">%s å·²è¢«æŒ‡å®šç‚º %s çš„ä¸»è¦é ˜åœŸ</t>
    <t id="5001">%s å·²é”åˆ° %s çš„å°ˆæ¥­çŸ¥è­˜ç­‰ç´š %sï¼</t>
    <t id="5002">æ‡‰ç”¨çš„åœ°å€çŽé‡‘ï¼š%s å¹´åˆ©æ½¤å¢žåŠ  %s%%</t>
    <t id="9500">éŒ¯èª¤ï¼š%s å¡ä½äº†ï¼Œéœ€è¦å¹«å¿™ï¼</t>
    <t id="9501">éŒ¯èª¤ï¼š%s äº¤æ˜“å¤±æ•—</t>
    <t id="9502">éŒ¯èª¤ï¼šç„¡æ³•ä½¿ç”¨ GalaxyTrader MK3 è¨»å†Š %s</t>
    <t id="80001">å•†å“ %s åŠ å…¥é»‘åå–®</t>
    <t id="80002">å•†å“ %s å·²å¾žé»‘åå–®ä¸­åˆªé™¤</t>
    <t id="80003">è»Ÿé«” %s åŠ å…¥ç™½åå–®</t>
    <t id="80004">è‡ªå‹•åˆ—å…¥é»‘åå–®ï¼ˆæ•ˆèƒ½ä¸ä½³ï¼‰ï¼š%s</t>
    <t id="80005">å±éšªå“å„ªå…ˆï¼š%s</t>
    <t id="80006">å•†å“éŽæ¿¾å™¨ï¼š%s æ´»èºï¼Œ%s äº¤æ˜“è¢«é˜»æ­¢</t>
    <t id="80007">æ‰€æœ‰æ½”å…·éŽæ¿¾å™¨å·²æ¸…é™¤</t>
    <t id="80008">æ½”å…·éŽæ¿¾å™¨é‡è¨­ç‚ºé è¨­å€¼</t>
    <t id="80009">æ½”å…·éŽæ¿¾å™¨ç®¡ç†</t>
    <t id="80010">è¢«å°éŽ–çš„å•†å“</t>
    <t id="80011">å…è¨±æ”œå¸¶çš„å•†å“</t>
    <t id="80012">å±éšªç‰©å“è™•ç†</t>
    <t id="80013">æœ€ä½Žå•†å“åƒ¹å€¼</t>
    <t id="80014">æœ€å¤§å•†å“åƒ¹å€¼</t>
    <t id="80015">å—é™åˆ¶çš„æ´¾ç³»</t>
    <t id="80016">æ ¹æ“šç›®å‰éŠæˆ²ç‹€æ…‹æ›´æ–°çš„å•†å“é¡žåˆ¥</t>
    <t id="80017">%s å•†å“åˆ†é¡žï¼š%s ä½Žåƒ¹å€¼ã€%s å±éšªã€%s é«˜åƒ¹å€¼</t>
    <t id="80018">å•Ÿç”¨å‹•æ…‹å•†å“åˆ†é¡ž</t>
    <t id="80019">é¡žåˆ¥ %s çš„è‡ªå‹•é»‘åå–®å·²åœç”¨</t>
    <t id="80020">åµæ¸¬åˆ°å…¶ä»–æ¨¡çµ„çš„æ–°å•†å“ä¸¦é€²è¡Œåˆ†é¡ž</t>
    <t id="9000">GalaxyTrader - å…¨åŸŸè¨­ç½®</t>
    <t id="9010">XPå’Œè¨“ç·´ç³»çµ±</t>
    <t id="9012">è‡ªå‹•è¨“ç·´</t>
    <t id="9013">ç¶“é©—ä¹˜æ•¸</t>
    <t id="9015">æŒ‡æ®å®˜çŽé‡‘ç™¾åˆ†æ¯”</t>
    <t id="9020">è‰¦éšŠå”èª¿</t>
    <t id="9021">å•Ÿç”¨è»ŠéšŠå”èª¿</t>
    <t id="9023">å•Ÿç”¨äº¤æ˜“å¿«å–</t>
    <t id="9030">é€šçŸ¥</t>
    <t id="9031">é€šçŸ¥ç´šåˆ¥</t>
    <t id="9040">è‡ªå‹•ä¿®å¾©ç³»çµ±</t>
    <t id="9041">å•Ÿç”¨è‡ªå‹•ä¿®å¾©</t>
    <t id="9042">èˆ¹é«”ä¿®å¾©é–¾å€¼</t>
    <t id="9310">éŠ€æ²³ç¤¦å·¥</t>
    <t id="9311">æ‰‡å€è³‡æºæŽ¢æ¸¬æŽƒæç­‰å¾…</t>
    <t id="9312">è‰¦èˆ¹æŽ¥è¿‘æ¬Šé‡</t>
    <t id="9043">æœ€ä½Žé£›è¡Œå“¡ç´šåˆ¥</t>
    <t id="9004">äº¤æ˜“åƒ¹æ ¼ç¯„åœ</t>
    <t id="9005">æœ€é«˜è³£å‡ºåƒ¹</t>
    <t id="9006">æœ€ä½Žè²·å…¥å ±åƒ¹</t>
    <t id="9007">éš”é›¢ï¼šæœ€é«˜å”®åƒ¹</t>
    <t id="9008">éš”é›¢ï¼šæœ€ä½Žè³¼è²·åƒ¹æ ¼</t>
    <t id="9009">å¾Œå‚™ï¼šæœ€é«˜å”®åƒ¹</t>
    <t id="9014">å¾Œå‚™ï¼šæœ€ä½Žè³¼è²·åƒ¹æ ¼</t>
    <t id="9016">åˆ©æ½¤é–€æª»åŸºç¤Ž</t>
    <t id="9025">æœ€ä½ŽçŽ©å®¶è³‡é‡‘</t>
    <t id="9024">ç·©å­˜ä¸Ÿæ£„å®¹é™</t>
    <t id="9026">é–’ç½®åœæ³Šé‡‹æ”¾æ™‚é–“</t>
    <t id="9054">é˜»æ­¢æ•µæ–¹æ´¾ä¿‚éƒ¨é–€</t>
    <t id="9055">é»‘åå–®å¨è„…ç´šåˆ¥</t>
    <t id="9056">é‡æ–°å»ºç«‹é»‘åå–®</t>
    <t id="9057">é‡æ–°å‰µé€ </t>
    <t id="9058">åˆ†é…çµ¦ GT è‰˜èˆ¹</t>
    <t id="9059">åˆ†é…</t>
    <t id="9112">ç•¶é£›è¡Œå“¡é”åˆ°æ‰€éœ€ç­‰ç´šæ™‚ï¼Œè‡ªå‹•ç™¼é€é£›è¡Œå“¡é€²è¡Œè¨“ç·´ã€‚ç¦ç”¨æ‰‹å‹•æŽ§åˆ¶è¨“ç·´æ™‚é–“ã€‚</t>
    <t id="9113">èª¿æ•´é£›è¡Œå“¡ç²å¾—ç¶“é©—çš„é€Ÿåº¦ã€‚æ•¸å€¼è¶Šé«˜æ„å‘³è‘—é€²å±•è¶Šå¿«ã€‚</t>
    <t id="9115">æŽˆäºˆé£›è¡Œå“¡æŒ‡æ®å®˜çš„ä¸‹å±¬ XP ç™¾åˆ†æ¯”ã€‚è¨­å®šç‚º 0% å¯åœç”¨æŒ‡æ®å®˜çŽå‹µ XPã€‚é è¨­å€¼ï¼š10%ã€‚</t>
    <t id="9121">å¯¦ç¾æ™ºæ…§è»ŠéšŠå”èª¿åŠŸèƒ½ï¼ŒåŒ…æ‹¬è·¯ç·šå„ªåŒ–å’Œè² è¼‰å¹³è¡¡ã€‚</t>
    <t id="9123">å…è¨±èˆ¹éšŠæˆå“¡ä¹‹é–“å…±äº«æœ‰åˆ©å¯åœ–çš„è²¿æ˜“æ©Ÿæœƒï¼Œä»¥å¯¦ç¾æ›´å¥½çš„å”èª¿ã€‚</t>
    <t id="9131">æŽ§åˆ¶é¡¯ç¤ºçš„é€šçŸ¥æ•¸é‡ï¼š0=å®‰éœï¼Œ1=åƒ…é‡è¦ï¼Œ2=æ‰€æœ‰é€šçŸ¥</t>
    <t id="9141">ç•¶èˆ¹é«”ä½Žæ–¼é–¾å€¼æ™‚ï¼Œå®Œæˆäº¤æ˜“å¾Œè‡ªå‹•ç™¼é€èˆ¹èˆ¶é€²è¡Œç¶­ä¿®ã€‚åƒ…é©ç”¨æ–¼ç¶“é©—è±å¯Œçš„é£›è¡Œå“¡ï¼ˆ12 ç´šä»¥ä¸Šï¼‰ã€‚èˆ¹èˆ¶é¸æ“‡åˆé©çš„è¨­æ–½ï¼šS/Mè¨­å‚™ç¢¼é ­ã€L/XLèˆ¹å» ã€‚</t>
    <t id="9142">ä½Žæ–¼è©²ç™¾åˆ†æ¯”æœƒè§¸ç™¼è‡ªå‹•ä¿®å¾©çš„èˆ¹é«”ç™¾åˆ†æ¯”ã€‚é»˜è®¤å€¼ï¼š95%ã€‚èˆ¹èˆ¶å—ææ™‚æœƒè‡ªå‹•å‰å¾€æœ€è¿‘çš„ç¶­ä¿®è¨­æ–½ã€‚</t>
    <t id="9411">å•Ÿç”¨å¾Œï¼ŒæŽ¡ç¤¦èˆ¹åœ¨è©•ä¼°æ‰‡å€å…§æ´¾ç³»è³‡æºæŽ¢æ¸¬å™¨æ™‚æœƒç­‰å¾…ï¼ˆæ¯å¤šä¸€å€‹æŽ¢æ¸¬å™¨+5ç§’ï¼‰ã€‚GTé£›è¡Œå“¡ç­‰ç´šå°‡ç­‰å¾…æ™‚é–“å¾ž1ç´šçš„å®Œæ•´æ™‚é–“ç·šæ€§ç¸®çŸ­è‡³15ç´šçš„5ç§’ï¼ˆåƒ…GT XPæ¨¡å¼ï¼Œä¸”ç­‰å¾…è¶…éŽ5ç§’æ™‚ï¼‰ã€‚åœç”¨=ä¸ç­‰å¾…ï¼ˆèˆ‡åŽŸç‰ˆç›¸åŒï¼‰ã€‚</t>
    <t id="9412">MK3/MK4è‰¦èˆ¹åœ¨æŽ’åºå·²é©—è­‰è²¿æ˜“æ™‚åå‘æ›´è¿‘çš„è³¼è²·ç«™ã€‚é¸æ“‡åˆ†æ•¸ = è²¿æ˜“åˆ†æ•¸ / (1 + è‰¦èˆ¹â†’è³¼è²·è·³èºæ•¸ Ã— æ¬Šé‡)ã€‚æ»‘æ¡¿0-100ï¼ˆ0=é—œé–‰ï¼Œ4=é è¨­0.04ï¼‰ã€‚ä¸å½±éŸ¿å¿«å–æŽ’åæˆ–é ˜åœŸèˆªç¨‹é™åˆ¶ã€‚</t>
    <t id="9143">è‡ªå‹•ä¿®å¾©åŠŸèƒ½æ‰€éœ€çš„æœ€ä½Žé£›è¡Œå“¡ç­‰ç´šã€‚é è¨­å€¼ï¼š12ï¼ˆæœ‰ç¶“é©—çš„äº¤æ˜“è€…ï¼‰ã€‚è¼ƒä½ŽéšŽçš„é£›è¡Œå“¡å¿…é ˆæ‰‹å‹•ä¿®ç†ã€‚</t>
    <t id="9104">è³£å‡ºå ±åƒ¹çš„æœ€é«˜ç›¸å°åƒ¹æ ¼ï¼ˆèˆ¹èˆ¶å¾žè»Šç«™è³¼è²·ï¼‰ã€‚ç¯„åœï¼š-1.0 è‡³ +1.0ã€‚é è¨­å€¼ï¼š0.5ï¼ˆé«˜æ–¼å¹³å‡å€¼ 50%ï¼‰ã€‚æ›´é«˜=æ›´è²´ä½†æœ‰æ›´å¤šé¸æ“‡ã€‚</t>
    <t id="9105">è²·å…¥å ±åƒ¹çš„æœ€ä½Žç›¸å°åƒ¹æ ¼ï¼ˆèˆ¹èˆ¶å‘è»Šç«™å‡ºå”®ï¼‰ã€‚ç¯„åœï¼š-1.0 è‡³ +1.0ã€‚é è¨­å€¼ï¼š-0.5ï¼ˆä½Žæ–¼å¹³å‡å€¼ 50%ï¼‰ã€‚æ›´ä½Ž=è²·å®¶æ›´ä¾¿å®œä½†é¸æ“‡æ›´å¤šã€‚</t>
    <t id="9106">å­¤ç«‹èˆ¹èˆ¶çš„æœ€é«˜å”®åƒ¹ï¼ˆå¡åœ¨å–®ä¸€å€åŸŸï¼‰ã€‚ç¯„åœï¼š-1.0 è‡³ +1.0ã€‚é è¨­å€¼ï¼š0.5ã€‚</t>
    <t id="9107">è³¼è²·å­¤ç«‹èˆ¹èˆ¶çš„æœ€ä½Žåƒ¹æ ¼ï¼ˆå¡åœ¨å–®ä¸€å€åŸŸï¼‰ã€‚ç¯„åœï¼š-1.0 è‡³ +1.0ã€‚é è¨­å€¼ï¼š-0.5ã€‚</t>
    <t id="9108">å¾Œå‚™æœå°‹çš„æœ€é«˜å”®åƒ¹ï¼ˆæ­£å¸¸æœå°‹å¤±æ•—æ™‚çš„æœ€å¾Œæ‰‹æ®µï¼‰ã€‚ç¯„åœï¼š-1.0 è‡³ +1.0ã€‚é è¨­å€¼ï¼š0.5ã€‚å›žé€€æœå°‹ä½¿ç”¨ MaxDistance=2 ä¸¦æ”¾å¯¬åˆ©æ½¤é–¾å€¼ã€‚</t>
    <t id="9109">è³¼è²·å¾Œå‚™æœå°‹çš„æœ€ä½Žåƒ¹æ ¼ï¼ˆæ­£å¸¸æœå°‹å¤±æ•—æ™‚çš„æœ€å¾Œæ‰‹æ®µï¼‰ã€‚ç¯„åœï¼š-1.0 è‡³ +1.0ã€‚é è¨­å€¼ï¼š-0.5ã€‚å›žé€€æœå°‹ä½¿ç”¨ MaxDistance=2 ä¸¦æ”¾å¯¬åˆ©æ½¤é–¾å€¼ã€‚</t>
    <t id="9116">Base minimum profit at Level 15 for a medium trader (reference cargo 8200). Actual MinAbsoluteProfit is computed per pilot + scaled by cargo:\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(scaled, 25% of base(L))\n\nSet to 0 to accept any profit (only ROI/distance/other filters apply).</t>
    <t id="9125">èˆ¹åªæœç´¢äº¤æ˜“ä¹‹å‰æ‰€éœ€çš„æœ€ä½ŽçŽ©å®¶èµ„é‡‘ï¼ˆç§¯åˆ†ï¼‰ã€‚å½“çŽ©å®¶èµ„é‡‘ä½ŽäºŽæ­¤é˜ˆå€¼æ—¶ï¼Œæ‰€æœ‰èˆ¹åªéƒ½ä¼šè·³è¿‡äº¤æ˜“æœç´¢å¹¶ç­‰å¾…ï¼Œä»Žè€Œé˜²æ­¢æ˜‚è´µçš„ç¼“å­˜æ‰«æå¯¼è‡´æ¸¸æˆå¡é¡¿ã€‚ç¯„åœï¼š1,000 - 100,000 Crã€‚é è¨­å€¼ï¼š1,000 Crã€‚</t>
    <t id="9124">åœ¨æ‹’çµ•äº¤æ˜“ä¹‹å‰ï¼Œå¿«å–å€¼çš„æŠ•è³‡å ±é…¬çŽ‡ä¸‹é™çš„æœ€å¤§ç™¾åˆ†æ¯”ã€‚ç¯„ä¾‹ï¼š20% çš„å¿«å– ROI å’Œ 15% çš„å®¹å·®å¯æŽ¥å—ä½Žè‡³ 17% çš„ ROIï¼ˆä¸‹é™ 14%ï¼‰ã€‚</t>
    <t id="9126">åœé å¾Œé‡‹æ”¾æ¸¯å£å‰ç­‰å¾…çš„åˆ†é˜æ•¸ï¼ˆ0-60ï¼‰ã€‚0 = ä¿æŒåœé ç›´åˆ°æ‰¾åˆ°æ–°å·¥ä½œã€‚é è¨­ï¼š1 åˆ†é˜ã€‚</t>
    <t id="9154">è‡ªå‹•å°‡æ•µæ–¹æ´¾ç³»æ“æœ‰çš„æ‰€æœ‰æ‰‡å€åˆ—å…¥é»‘åå–®ï¼ˆé»‘åå–®ä¸­çš„é—œä¿‚è¤‡é¸æ¡†ï¼‰</t>
    <t id="9155">å°‡æ‰‡å€åˆ—å…¥é»‘åå–®æ‰€éœ€çš„æœ€ä½Žå¨è„…ç­‰ç´š (1-5):\n2=ä¸­ï¼ˆå–®æ¬¡æ”»æ“Šï¼‰\n3=ä¸­-é«˜ï¼ˆæ•µå°æ´¾ç³»ï¼‰\n4=é«˜ï¼ˆä¸»åŠ›è‰¦/é£›å½ˆï¼‰\n5=éžå¸¸é«˜ï¼ˆXenon/Khaakï¼‰</t>
    <t id="9156">æ‰‹å‹•é‡æ–°å»ºç«‹å¨è„…è¦é¿é»‘åå–®ï¼ˆå¦‚æžœå·²åˆªé™¤å‰‡æœ‰ç”¨ï¼‰</t>
    <t id="9157">æ‰‹å‹•å°‡ç›®å‰å‹•æ…‹é»‘åå–®åˆ†é…çµ¦æ‰€æœ‰GTè‰¦éšŠæŒ‡æ®è‰¦ã€‚ä¸‹å±¬ç¹¼æ‰¿äº†ä»–å€‘çš„æŒ‡æ®å®˜ã€‚</t>
    <t id="6001">å­¸å¾’</t>
    <t id="6002">å°ŽéŠ</t>
    <t id="6003">ä¾›æ‡‰å•†</t>
    <t id="6004">å•†</t>
    <t id="6005">å•†äºº</t>
    <t id="6006">é•·é€”å•†å®¶</t>
    <t id="6101">å‡è¡¡</t>
    <t id="6102">é˜²å®ˆåž‹</t>
    <t id="6103">ä»¥äº¤æ˜“ç‚ºä¸­å¿ƒ</t>
    <t id="6104">é‡ç”²é˜²ç¦¦</t>
    <t id="6105">å¡”æž¶æ”¯æ’</t>
    <t id="9050">å¨è„…è¦é¿ç³»çµ±</t>
    <t id="9051">å•Ÿç”¨å¨è„…è¦é¿ï¼š</t>
    <t id="9052">æ•µå°é—œä¿‚é–¾å€¼ï¼š</t>
    <t id="9053">ä½¿ç”¨å‹•æ…‹é»‘åå–®ï¼š</t>
    <t id="9151">6 ç´šä»¥ä¸Šçš„å•†äººå¯ä»¥ç™¼ç¾æ•µå°èˆ¹éš»ä¸¦é¿é–‹å±éšªè·¯ç·šã€‚åœç”¨æœƒåœæ­¢æ‰€æœ‰æŽƒæï¼ˆæé«˜æ•ˆèƒ½ï¼‰ã€‚æŒ‡æ®è¡Œç‚ºä¸­æ¯è‰˜èˆ¹çš„é¢¨éšªæ‰¿å—èƒ½åŠ›ï¼ˆ0-10 ç´šï¼‰ã€‚</t>
    <t id="9152">åƒ…å°‡é—œä¿‚ç­‰æ–¼æˆ–ä½Žæ–¼è©²å€¼çš„æ´¾ç³»æ¨™è¨˜ç‚ºå¨è„…ã€‚é è¨­å€¼ï¼š-20%</t>
    <t id="9153">è‡ªå‹•å°‡å±éšªå€åŸŸï¼ˆå¨è„…ç­‰ç´š 3+ï¼‰åˆ—å…¥é»‘åå–®ï¼Œè¿«ä½¿èˆ¹éš»ç¹žéŽå¨è„…ã€‚ä½¿ç”¨æ™®é€šå°‹è·¯ä¾†å°‹æ‰¾æ›¿ä»£è·¯ç·šã€‚</t>
    <t id="9060">é˜²ç¦¦è£å‚™è‡ªå‹•è£œå……ï¼ˆ15ç´šï¼‰</t>
    <t id="9061">å•Ÿç”¨è‡ªå‹•è£œè²¨ï¼š</t>
    <t id="9062">è£œè²¨å°ç­–ï¼š</t>
    <t id="9063">è£œå……é˜²ç¦¦ç„¡äººæ©Ÿï¼š</t>
    <t id="9064">è£œè²¨è²¿æ˜“ç„¡äººæ©Ÿï¼š</t>
    <t id="9065">è£œå……é›·å°„å¡”ï¼š</t>
    <t id="9066">è£œè²¨ç¶­ä¿®ç„¡äººæ©Ÿï¼š</t>
    <t id="9067">å°ç­–é–¾å€¼ï¼š</t>
    <t id="9068">çµ±ä¸€å®¹é‡é–¾å€¼ï¼š</t>
    <t id="9069">è¨­å‚™å¹³è¡¡ç°¡ä»‹ï¼š</t>
    <t id="9161">äº¤æ˜“å¤§å¸«ï¼ˆ15ç´šï¼‰åœ¨äº¤æ˜“å¾Œè‡ªå‹•è£œå……é˜²ç¦¦è£å‚™ã€‚é©ç”¨æ–¼ä¸‹å±¬çš„æŒ‡æ®å®˜ç´šåˆ¥ã€‚</t>
    <t id="9162">æ‰€æœ‰èˆ¹èˆ¶ï¼ˆS/M/L/XLï¼‰ã€‚ç¨ç«‹å®¹é‡ã€‚å°æ–¼å°Žå½ˆé˜²ç¦¦è‡³é—œé‡è¦ã€‚</t>
    <t id="9163">åƒ…é‹é€ L/XLã€‚èˆ‡å…¶ä»–å¯éƒ¨ç½²è¨­å‚™å…±äº«çµ±ä¸€å®¹é‡ã€‚</t>
    <t id="9164">åƒ…é‹é€ L/XLã€‚å°æ–¼äº¤æ˜“æ“ä½œè‡³é—œé‡è¦ã€‚å…±äº«çµ±ä¸€å®¹é‡ã€‚</t>
    <t id="9165">æ‰€æœ‰èˆ¹éš»ã€‚ L/XLèˆ¹çµ±ä¸€é‹åŠ›ï¼ŒS/Mèˆ¹ä½¿ç”¨è²¨ç‰©ã€‚</t>
    <t id="9166">åƒ…é‹é€ L/XLã€‚èˆ‡è‡ªå‹•ä¿®å¾©ç³»çµ±é…åˆä½¿ç”¨ã€‚å…±äº«çµ±ä¸€å®¹é‡ã€‚</t>
    <t id="9167">ç•¶å°ç­–ä½Žæ–¼æ­¤ç™¾åˆ†æ¯”æ™‚é‡æ–°é€²è²¨ï¼ˆæ‰€æœ‰èˆ¹èˆ¶ï¼Œå–®ç¨å®¹é‡ï¼‰ã€‚</t>
    <t id="9168">ç•¶å¯éƒ¨ç½²ç¸½é‡ä½Žæ–¼æ­¤ç™¾åˆ†æ¯”æ™‚é‡æ–°åº«å­˜ï¼ˆL/XL è‰¦è‰‡ï¼šç„¡äººæ©Ÿ + å¡”å…±äº«ä¸€å€‹å®¹é‡ï¼‰ã€‚</t>
    <t id="9169">çµ±ä¸€å®¹é‡åˆ†ä½ˆï¼ˆL/XLèˆ¹ï¼‰ï¼šè²¿æ˜“åž‹ï¼ˆ20/50/20/10ï¼‰ã€å¹³è¡¡åž‹ï¼ˆ35/35/20/10ï¼‰ã€é˜²ç¦¦åž‹ï¼ˆ50/20/20/10ï¼‰ã€é‡åž‹é˜²ç¦¦åž‹ï¼ˆ40/30/20/10ï¼‰ã€å¡”æ¨“æ”¯æ´åž‹ï¼ˆ30/30/30/10ï¼‰ã€‚æ¯”çŽ‡ï¼šé˜²ç¦¦/è²¿æ˜“/å¡”æ¨“/ç¶­ä¿®ã€‚æŒ‰ä¸€ä¸‹å¯å¾ªç’°é¸æ“‡é¸é …ã€‚</t>
    <t id="9090">èˆ¹èˆ¶æ”¹è£</t>
    <t id="9091">å•Ÿç”¨èˆ¹èˆ¶ä¿®æ”¹</t>
    <t id="9191">æ ¹æ“šé£›è¡Œå“¡ç´šåˆ¥è‡ªå‹•å®‰è£èˆ¹èˆ¶å’Œå¼•æ“Žæ”¹è£ã€‚ 9ç´š+ = 1ç´šæ¨¡çµ„ï¼Œ12ç´š+ = 2ç´šæ¨¡çµ„ï¼Œ15ç´š+ = 3ç´šæ¨¡çµ„ã€‚å–æ¶ˆè¨‚å–®æ™‚ï¼Œåƒ…åˆªé™¤ GT å®‰è£çš„æ¨¡çµ„ã€‚</t>
    <t id="9070">èˆ¹èˆ¶å‘½åé…ç½®</t>
    <t id="9071">é¡¯ç¤ºXPï¼š</t>
    <t id="9072">é¡¯ç¤ºæŽ’åï¼š</t>
    <t id="9073">é¡¯ç¤ºç­‰ç´šï¼š</t>
    <t id="9074">é¡¯ç¤ºç‹€æ…‹ï¼š</t>
    <t id="9075">å•Ÿç”¨èˆ¹èˆ¶é‡å‘½åï¼š</t>
    <t id="9076">å‰ç¶´</t>
    <t id="9077">å¾Œç¶´</t>
    <t id="9078">é è¨­åç¨±ä¾†æºï¼š</t>
    <t id="9079">åž‹è™Ÿåç¨±</t>
    <t id="9080">é¡žåž‹åç¨±</t>
    <t id="9081">æ¨¡åž‹åº«</t>
    <t id="9083">è‡ªè¨‚åç¨±</t>
    <t id="9084">é¡¯ç¤ºæ¯æ˜Ÿå€:</t>
    <t id="9085">å‘½åæ¨¡å¼:</t>
    <t id="9086">å‚³çµ±</t>
    <t id="9087">ç¯„æœ¬</t>
    <t id="9088">åç¨±ç¯„æœ¬:</t>
    <t id="9089">å ä½ç¬¦: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}ã€‚åŽŸå­æ¨™è¨˜: {RS} {CB} {BL} ç­‰ã€‚ä½¿ç”¨ä¸‹æ–¹ç‹€æ…‹ç¸®å¯«ã€‚ç©ºæ¨™è¨˜çœç•¥ï¼Œå¤šé¤˜ç©ºæ ¼åˆä½µã€‚æœ€å¤š128å­—å…ƒã€‚</t>
    <t id="9183">åœ¨è‰¦èˆ¹åç¨±ä¸­é¡¯ç¤ºå·²è¨­å®šçš„æ¯æ˜Ÿå€ï¼ˆå‰ç¶´æˆ–å¾Œç¶´ï¼‰ã€‚</t>
    <t id="9184">ä½¿ç”¨ {TOKEN} å ä½ç¬¦è‡ªè¨‚åç¨±æ ¼å¼ï¼Œå–ä»£å‚³çµ±ç‰ˆé¢é–‹é—œã€‚éœ€è¦ GalaxyTrader XPï¼ˆéžåŽŸç‰ˆ XP æ¨¡å¼ï¼‰ã€‚</t>
    <t id="9092">æ¨¡å¼å ä½ç¬¦</t>
    <t id="9093">è‰¦èˆ¹: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT XPï¼ˆæ¨¡çµ„ï¼‰: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">åŽŸç‰ˆ: {MGMT} {PILOTSKILL}</t>
    <t id="9096">æ¯æ¸¯: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">èˆ¹å“¡: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">å€åŸŸ: {SECTOR} | çµ±è¨ˆ: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">ç‹€æ…‹å ä½ç¬¦:</t>
    <t id="9100">{OPSTATE}: åˆä½µæ‰€æœ‰æ´»èºé‹è¡Œæ——æ¨™ï¼ˆå¦‚ CB RSã€MTï¼‰</t>
    <t id="9101">{STATUS}: å°éŽ–ã€è¨“ç·´ã€å‚™ç”¨æˆ–å­¤ç«‹</t>
    <t id="9102">{CB}: åƒ…è‡ªè¨‚é»‘åå–®, å·²å«æ–¼ {OPSTATE}, å‹¿çµ„åˆä½¿ç”¨</t>
    <t id="9082">é¡¯ç¤ºèˆ¹èˆ¶ç­‰ç´šï¼š</t>
    <t id="9171">åœ¨èˆ¹è‰¦åç¨±ä¸­é¡¯ç¤º XP å€¼</t>
    <t id="9175">å•Ÿç”¨æˆ–åœç”¨å¸¶æœ‰é£›è¡Œå“¡è³‡è¨Šçš„è‡ªå‹•èˆ¹èˆ¶é‡å‘½å</t>
    <t id="9172">åœ¨èˆ¹èˆ¶åç¨±ä¸­é¡¯ç¤ºç­‰ç´šé ­éŠœ</t>
    <t id="9173">åœ¨èˆ¹èˆ¶åç¨±ä¸­é¡¯ç¤ºç­‰ç´šæ•¸å­—</t>
    <t id="9174">ä»¥èˆ¹èˆ¶åç¨±é¡¯ç¤ºäº¤æ˜“ç‹€æ…‹</t>
    <t id="9178">é¸æ“‡èˆ¹èˆ¶åŸºç¤Žåç¨±çš„ä¾†æºï¼šæ¨¡åž‹åç¨±ï¼ˆå¸¶è®Šé«”ï¼‰ã€é¡žåž‹åç¨±ï¼ˆé€šç”¨ï¼‰ã€æ¨¡åž‹åŸºç¤Žï¼ˆä¸å«è®Šé«”ï¼‰æˆ–è‡ªè¨‚åç¨±ï¼ˆå„²å­˜çš„åç¨±ï¼‰</t>
    <t id="9182">åœ¨èˆ¹èˆ¶åç¨±ä¸­é¡¯ç¤ºèˆ¹èˆ¶é¡žåˆ¥ï¼ˆSã€Mã€Lã€XLï¼‰</t>
    <t id="9200">åµéŒ¯è¨­å®š</t>
    <t id="9201">å•Ÿç”¨èª¿è©¦æ—¥èªŒè¨˜éŒ„ï¼š</t>
    <t id="9202">æ‰€æœ‰ debug_text è¼¸å‡ºçš„ä¸»é–‹é—œã€‚åœç”¨å¾Œï¼Œæ‰€æœ‰åµéŒ¯æ—¥èªŒè¨˜éŒ„éƒ½æœƒè¢«æŠ‘åˆ¶ã€‚å•Ÿç”¨å¾Œï¼ŒåµéŒ¯è¨Šæ¯å°‡æ ¹æ“šå„å€‹ debug_text æ©Ÿæœƒå€¼é¡¯ç¤ºåœ¨ DebugLog ä¸­ã€‚</t>
    <t id="9220">ç¶­è­·èˆ‡è¨ºæ–·</t>
    <t id="9221">é‡ç½®åˆ©æ½¤çµ±è¨ˆï¼š</t>
    <t id="9222">é‡ç½®</t>
    <t id="9223">æ¸…é™¤æ‰€æœ‰åˆ—å…¥é»‘åå–®çš„æ‰‡å€ï¼š</t>
    <t id="9224">æ¸…é™¤</t>
    <t id="9225">å°‡æ‰€æœ‰è¨­å®šé‡è¨­ç‚ºé è¨­å€¼ï¼š</t>
    <t id="9226">å…¨éƒ¨é‡ç½®</t>
    <t id="9323">å°‡æ‰€æœ‰éƒ¨é–€å¾žå¨è„…æƒ…å ±é»‘åå–®ä¸­åˆªé™¤ã€‚é€™å°‡ç«‹å³æ¸…é™¤æ‰€æœ‰åˆ—å…¥é»‘åå–®çš„å€åŸŸï¼Œä¸¦å…è¨±æ‚¨çš„èˆ¹éš»å‰å¾€å…ˆå‰è¢«å°éŽ–çš„å€åŸŸã€‚å¦‚æžœæ‚¨æƒ³è¦é‡ç½®å¨è„…è¦é¿ç³»çµ±æˆ–ç£å€è¢«éŒ¯èª¤åœ°åˆ—å…¥é»‘åå–®ï¼Œè«‹ä½¿ç”¨æ­¤é¸é …ã€‚</t>
    <t id="9321">å°‡æ‰€æœ‰é£›è¡Œå“¡å’Œèˆ¹éš»çš„æ‰€æœ‰åˆ©æ½¤çµ±è¨ˆé‡è¨­ç‚º 0ã€‚å‡ç´šåˆ° v0.6.0 å¾Œä½¿ç”¨æ­¤åŠŸèƒ½å¯ä»¥æ¸…é™¤åŸºæ–¼æ”¶å…¥çš„èª‡å¤§çµ±è¨ˆè³‡æ–™ã€‚è©²ä¿®å¾©ç¾åœ¨è·Ÿè¸ªå¯¦éš›åˆ©æ½¤ï¼ˆæ”¶å…¥ - è³¼è²·æˆæœ¬ï¼‰ã€‚äº¤æ˜“è¨ˆæ•¸å’Œç¶“é©—å€¼å°‡è¢«ä¿ç•™ã€‚</t>
    <t id="9325">å°‡æ‰€æœ‰å…¨åŸŸè¨­å®šé‡è¨­ç‚ºå…¶é è¨­å€¼ã€‚é€™åŒ…æ‹¬ XP è¨­å®šã€è‰¦éšŠå”èª¿ã€é€šçŸ¥ã€è¡Œå‹•æƒ…å ±ã€å¨è„…è¦é¿ã€èˆ¹èˆ¶å‘½åã€è‡ªå‹•ä¿®å¾©ã€ä¿®æ”¹ã€æ€§èƒ½å’Œæ•¸ä½æ ¼å¼è¨­å®šã€‚ä¿ç•™èª¿è©¦æ—¥èªŒè¨˜éŒ„è¨­å®šä»¥å…è¨±è¨˜éŒ„é‡ç½®æ“ä½œã€‚</t>
    <t id="9227">æ¸…é™¤æ‰€æœ‰å®¶å±…ç”¢æ¥­çš„è²¿æ˜“å¿«å–ï¼š</t>
    <t id="9228">æ¸…é™¤å¿«å–</t>
    <t id="9327">æ¸…é™¤æ‰€æœ‰åœ‹å…§éƒ¨é–€çš„è²¿æ˜“å¿«å–ã€‚é€™å°‡è¿«ä½¿æ‰€æœ‰èˆ¹èˆ¶åœ¨ä¸‹ä¸€æ¬¡è²¿æ˜“æœç´¢ä¸­é€²è¡Œæ–°çš„å³æ™‚æœç´¢ã€‚å¦‚æžœå¿«å–çœ‹èµ·ä¾†é™³èˆŠæˆ–æå£žï¼Œæˆ–è€…æ‚¨æƒ³è¦å¼·è£½å®Œå…¨åˆ·æ–°ç·©å­˜ï¼Œè«‹ä½¿ç”¨æ­¤é¸é …ã€‚</t>
    <t id="9229">é‡‹æ”¾æ‰€æœ‰æœå°‹éŽ–</t>
    <t id="9329">é‡‹æ”¾æ‰€æœ‰æ­£åœ¨é€²è¡Œçš„äº¤æ˜“æœå°‹éŽ–å®šä¸¦æ¸…é™¤ç›¸é—œçš„çž¬æ…‹ã€‚å¦‚æžœèˆ¹èˆ¶å› èˆŠä¿å­˜çš„é™³èˆŠéŽ–å®šè€Œé™·å…¥â€œæœå°‹äº¤æ˜“â€ï¼Œè«‹ä½¿ç”¨æ­¤é¸é …ã€‚é€™å¯èƒ½æœƒä¸­æ–·åˆæ³•çš„æœå°‹ã€‚</t>
    <t id="9290">è½‰å„²è²¿æ˜“ä¸­å¿ƒç‹€æ…‹ï¼š</t>
    <t id="9291">å‚¾å€’</t>
    <t id="9390">åœ¨æ—¥èªŒä¸­å’Œé€šçŸ¥ä¸­é¡¯ç¤ºé›†ä¸­è²¿æ˜“ä¸­å¿ƒçš„ä¸€æ¬¡æ€§å¿«ç…§ï¼ˆèª¿åº¦ç¨‹åºä½‡åˆ— + æœ€å¾Œè«‹æ±‚çš„èˆ¹èˆ¶ç‹€æ…‹ï¼‰ã€‚</t>
    <t id="9292">è½‰å„²äº¤æ˜“å¿«å–ï¼ˆå®Œæ•´ï¼‰ï¼š</t>
    <t id="9293">è½‰å„²ç·©å­˜</t>
    <t id="9392">å®Œæ•´å¿«å–è½‰å„²ï¼ˆå¯èƒ½å¾ˆå¤§ï¼‰ã€‚å°‡æ‰€æœ‰å¿«å–æ¢ç›®åˆ†å¡Šå¯«å…¥ DebugLogã€‚å†æ¬¡é»žæ“Šå³å¯å–æ¶ˆã€‚</t>
    <t id="9294">æ¸…é™¤è»ŠéšŠé è¨‚ï¼š</t>
    <t id="9295">æ¸…é™¤</t>
    <t id="9394">æ¸…é™¤æ‰€æœ‰æ´»èºçš„è»ŠéšŠè²¿æ˜“é è¨‚ã€‚å¦‚æžœèˆ¹èˆ¶å¡åœ¨ç­‰å¾…é è¨‚äº¤æ˜“åˆ°æœŸï¼Œæˆ–é è¨‚è¡¨åœ¨åŠ è¼‰èˆŠä¿å­˜å¾Œè®Šå¾—é™³èˆŠï¼Œè«‹ä½¿ç”¨æ­¤é¸é …ã€‚</t>
    <t id="9230">è¡¨ç¾</t>
    <t id="9231">æ‰¹æ¬¡å»¶é²ï¼š</t>
    <t id="9232">é©—è­‰å»¶é²ï¼š</t>
    <t id="9233">æœ€å¤§ä¸¦ç™¼æœå°‹æ•¸ï¼š</t>
    <t id="9234">æœ€å¤§äº¤æ˜“è¿”å›žï¼š</t>
    <t id="9235">æ¯ä»¶å•†å“çš„æœ€å¤§å„ªæƒ ï¼š</t>
    <t id="9236">æ¯ä»¶å•†å“çš„æœ€å¤§äº¤æ˜“æ•¸ï¼š</t>
    <t id="9237">æ¯å€‹å•†å“çš„æœ€å¤§åŒ¹é…å ±åƒ¹ï¼š</t>
    <t id="9238">æå‰é€€å‡ºé–€æª»ï¼š</t>
    <t id="9241">å³æ™‚å„ªæƒ åˆ‡ç‰‡é–“éš”ï¼š</t>
    <t id="9266">æœå°‹éŽ–å®š TTLï¼š</t>
    <t id="9263">æ‰¹é‡å¡Šå¤§å°ï¼š</t>
    <t id="9239">æ•¸å­—æ ¼å¼</t>
    <t id="9240">æ ¼å¼æ¨£å¼ï¼š</t>
    <t id="9242">ä½¿ç”¨ M å¾Œç¶´</t>
    <t id="9243">M å¾Œç¶´é–¾å€¼ï¼š</t>
    <t id="9244">å¾·èªž (123.456,78)</t>
    <t id="9245">è‹±èªž (123,456.78)</t>
    <t id="9510">å‡ç´šå½ˆçª—é€šçŸ¥ï¼š</t>
    <t id="9511">éœ€è¦åŸ¹è¨“æé†’ï¼š</t>
    <t id="9512">åŸ¹è¨“å®Œæˆé€šçŸ¥ï¼š</t>
    <t id="9513">åˆ©æ½¤å ±å‘Šï¼š</t>
    <t id="9514">å¸‚å ´æé†’ï¼š</t>
    <t id="9515">è‰¦éšŠæ›´æ–°ï¼š</t>
    <t id="9516">åƒ…ä½¿ç”¨æ™®é€š XP</t>
    <t id="9610">åœ¨çŽ©å®¶ä»‹é¢ä¸­å•Ÿç”¨æˆ–åœç”¨äº¤æ˜“å“¡å‡ç´šå½ˆçª—é€šçŸ¥ã€‚</t>
    <t id="9611">ç•¶é£›è¡Œå“¡éœ€è¦åŸ¹è¨“ä»¥æ™‰å‡ä¸‹ä¸€ç´šæ™‚æé†’ã€‚</t>
    <t id="9612">ç•¶é£›è¡Œå“¡å®ŒæˆåŸ¹è¨“ä¸¦æ™‰å‡æ™‚é€šçŸ¥ã€‚</t>
    <t id="9613">å®šæœŸåˆ©æ½¤æ‘˜è¦ï¼ˆç°¡å–®å’Œå®Œæ•´å ±å‘Šï¼‰ã€‚</t>
    <t id="9614">ç‰¹æ®Šå¸‚å ´æ©Ÿæœƒå’Œé«˜åƒ¹å€¼äº¤æ˜“æé†’ã€‚</t>
    <t id="9615">è‰¦éšŠå”èª¿è¨Šæ¯å’Œç‹€æ…‹æ›´æ–°ã€‚</t>
    <t id="9616">ä½¿ç”¨ Pilot.skill.piloting ä¸¦åœç”¨ GT XP é€²åº¦/ä¸Šé™ã€‚</t>
    <t id="9246">ç°¡å–®å ±å‘Šé »çŽ‡ï¼š</t>
    <t id="9247">ç¶œåˆå ±å‘Šé »çŽ‡ï¼š</t>
    <t id="9248">æœ€å¤§ä¸¦ç™¼å¿«å–æœå°‹ï¼š</t>
    <t id="9249">æœ€å¤§ä¸¦ç™¼å³æ™‚æœå°‹ï¼š</t>
    <t id="9340">é¸æ“‡æ•¸å­—æ ¼å¼ï¼šå¾·èªžä½¿ç”¨â€œ.â€åƒä½ç”¨ ',' è¡¨ç¤ºå°æ•¸ (123.456,78)ï¼Œè‹±èªžç”¨ ',' è¡¨ç¤ºåƒä½ï¼Œ'.'å°æ–¼å°æ•¸ (123,456.78)</t>
    <t id="9342">å°å¤§æ–¼é–¾å€¼çš„æ•¸å­—å•Ÿç”¨ M å¾Œç¶´ï¼ˆä¾‹å¦‚ï¼Œ1.0 M è€Œä¸æ˜¯ 1,000,000ï¼‰</t>
    <t id="9343">M å¾Œç¶´çš„é–¾å€¼ã€‚é«˜æ–¼æ­¤å€¼çš„æ•¸å­—å°‡ä»¥ M å¾Œç¶´é¡¯ç¤ºï¼ˆé è¨­å€¼ï¼š999,999ï¼‰</t>
    <t id="9346">ç°¡å–®å ±å‘Šï¼ˆå½ˆå‡ºé€šçŸ¥ï¼‰çš„é »çŽ‡ï¼š0-30 åˆ†é˜ï¼ˆ0 = åœç”¨ - ç°¡å–®å ±å‘Šå·²åœç”¨ï¼Œé è¨­å€¼ï¼š1 åˆ†é˜ï¼‰</t>
    <t id="9347">ç¶œåˆå ±å‘Šï¼ˆæ—¥èªŒæ¢ç›®ï¼‰çš„é »çŽ‡ï¼š0-60 åˆ†é˜ï¼ˆ0 = åœç”¨ - ç¶œåˆå ±å‘Šå·²åœç”¨ï¼Œé è¨­å€¼ï¼š30 åˆ†é˜ï¼‰</t>
    <t id="9398">ä½¿ç”¨ GT ç©åˆ†åˆ°æœŸè¦†è“‹</t>
    <t id="9399">åœ¨åŒä¸€ UI æ’æ§½ä¸­ç”¨ GT é è¨ˆå€¼å–ä»£æˆ–å¢žå¼·åŽŸå§‹ã€Œäº¤æ˜“ç”¢ç”Ÿçš„ CRã€è¡Œã€‚</t>
    <t id="9331">äº¤æ˜“æœå°‹è™•ç†æœŸé–“æ‰¹æ¬¡ä¹‹é–“çš„å»¶é²ï¼ˆ1-500 æ¯«ç§’ï¼‰ã€‚è¼ƒé«˜çš„å€¼æœƒé™ä½Ž CPU è² è¼‰ï¼Œä½†æœƒæ¸›æ…¢äº¤æ˜“æœå°‹é€Ÿåº¦ã€‚é è¨­å€¼ï¼š120 æ¯«ç§’ã€‚ç”¨æ–¼æ‰¹æ¬¡è™•ç†å™¨å’Œäº¤æ˜“æ¸…å–®éŽæ¿¾ã€‚</t>
    <t id="9332">AI è…³æœ¬ä¸­äº¤æ˜“é©—è­‰ä¹‹é–“çš„å»¶é²ï¼ˆ1-500 æ¯«ç§’ï¼‰ã€‚è¼ƒé«˜çš„å€¼æœƒé™ä½Ž CPU è² è¼‰ï¼Œä½†æœƒæ¸›æ…¢äº¤æ˜“é©—è­‰é€Ÿåº¦ã€‚é è¨­å€¼ï¼š50 æ¯«ç§’ã€‚åœ¨é©—è­‰ MD ç³»çµ±çš„è²¿æ˜“æ¸…å–®æ™‚ä½¿ç”¨ã€‚</t>
    <t id="9333">å¯åŒæ™‚é‹è¡Œçš„äº¤æ˜“æœå°‹çš„æœ€å¤§æ•¸é‡ (1-10)ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†æœƒå¢žåŠ ä½‡åˆ—ç­‰å¾…æ™‚é–“ã€‚å€¼è¶Šé«˜ï¼Œæœå°‹éŽç¨‹è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´æ•ˆèƒ½é«˜å³°ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9334">å¾žå¿«å–æœå°‹å‚³å›žçš„æœ€å¤§äº¤æ˜“æ•¸ (1-100)ã€‚è¼ƒé«˜çš„å€¼æä¾›æ›´å¤šçš„äº¤æ˜“é¸é …ï¼Œä½†æœƒå¢žåŠ å¿«å–é©—è­‰æ™‚é–“ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†å¯èƒ½æœƒéŒ¯éŽå¯è¡Œçš„äº¤æ˜“ã€‚é è¨­å€¼ï¼š20ã€‚</t>
    <t id="9335">å³æ™‚æœå°‹ä¸­æ¯å€‹å•†å“è¦è™•ç†çš„æœ€å¤§å ±åƒ¹æ•¸é‡ (5-100)ã€‚è¼ƒé«˜çš„å€¼æœƒè€ƒæ…®æ›´å¤šå„ªæƒ ï¼Œä½†æœƒå¢žåŠ è™•ç†æ™‚é–“ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†å¯èƒ½æœƒéŒ¯éŽæœ‰åˆ©å¯åœ–çš„äº¤æ˜“ã€‚é è¨­å€¼ï¼š20ã€‚</t>
    <t id="9336">æ‰¹æ¬¡æœŸé–“æ¯å€‹å•†å“çš„æœ€å¤§äº¤æ˜“æ•¸é‡ (5-100)ã€‚è¼ƒé«˜çš„å€¼å…è¨±æ¯å€‹å•†å“é€²è¡Œæ›´å¤šäº¤æ˜“ï¼Œä½†æœƒå¢žåŠ è™•ç†æ™‚é–“ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†å¯èƒ½æœƒéŒ¯éŽæœ‰åˆ©å¯åœ–çš„äº¤æ˜“ã€‚é è¨­å€¼ï¼š20ã€‚</t>
    <t id="9337">æ‰¹è™•ç†å™¨ä¸­ç”¨æ–¼åŒ¹é…çš„æ¯å€‹å•†å“çš„æœ€å¤§å ±åƒ¹æ•¸ (5-100)ã€‚è¼ƒé«˜çš„å€¼æœƒè€ƒæ…®æ›´å¤šå„ªæƒ ï¼Œä½†æœƒå¢žåŠ è™•ç†æ™‚é–“ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†å¯èƒ½æœƒéŒ¯éŽæœ‰åˆ©å¯åœ–çš„äº¤æ˜“ã€‚é è¨­å€¼ï¼š20ã€‚</t>
    <t id="9338">æ‰¹æ¬¡çš„æå‰é€€å‡ºé–¾å€¼ï¼ˆ100-10000ï¼‰ã€‚ç•¶ç™¼ç¾é€™éº¼å¤šäº¤æ˜“æ™‚ï¼Œæ‰¹æ¬¡æœƒæå‰åœæ­¢ä»¥ç¯€çœ CPUã€‚è¼ƒé«˜çš„å€¼å¯è™•ç†æ›´å¤šäº¤æ˜“ï¼Œä½†æœƒå¢žåŠ  CPU è² è¼‰ã€‚è¼ƒä½Žçš„åƒ¹å€¼æœƒæ›´å¿«é€€å‡ºï¼Œä½†å¯èƒ½æœƒéŒ¯éŽæœ‰åˆ©å¯åœ–çš„äº¤æ˜“ã€‚é è¨­å€¼ï¼š2000ã€‚</t>
    <t id="9341">å³æ™‚å ±åƒ¹åˆ‡ç‰‡é–“éš”ä»¥æ¯«ç§’ç‚ºå–®ä½ (5-2000ms)ã€‚æŽ§åˆ¶å³æ™‚å ±åƒ¹åˆ‡ç‰‡çš„å•Ÿå‹•é »çŽ‡ã€‚è¼ƒä½Žçš„å€¼å¯ä»¥åŠ å¿«å ±åƒ¹æ”¶é›†é€Ÿåº¦ï¼Œä½†æœƒå¢žåŠ  CPU è² è¼‰ã€‚è¼ƒé«˜çš„å€¼æœƒé™ä½Ž CPU è² è¼‰ï¼Œä½†æœƒæ¸›æ…¢å³æ™‚æœå°‹è™•ç†é€Ÿåº¦ã€‚é è¨­å€¼ï¼š500 æ¯«ç§’ã€‚</t>
    <t id="9363">æ‰¹æ¬¡å€å¡Šå¤§å° (5-20)ã€‚è™•ç†æ¯å€‹å€å¡Šçš„ chunkSizeÃ—chunkSize çµ„åˆï¼ˆä¾‹å¦‚ï¼Œ5Ã—5 = 25 å€‹çµ„åˆï¼‰ã€‚è¼ƒå¤§çš„å€å¡Šå¯ä»¥æé«˜åžåé‡ï¼Œä½†æœƒå¢žåŠ æ¯å€‹å€å¡Šçš„ CPU è² è¼‰ã€‚è¼ƒå°çš„å€å¡Šå¯ä»¥æ¸›å°‘ CPU å³°å€¼ï¼Œä½†éœ€è¦æ›´å¤šçš„é€£çºŒæ€§ã€‚é è¨­å€¼ï¼š5ã€‚</t>
    <t id="9348">å¯ä»¥åŒæ™‚é‹è¡Œçš„å¿«å–æœå°‹çš„æœ€å¤§æ•¸é‡ (1-20)ã€‚å¿«å–æœå°‹é€Ÿåº¦å¿«ä¸”æˆæœ¬ä½Žï¼›è¼ƒä½Žçš„å€¼å¯ä»¥æ¸›å°‘å¤§åž‹ä¸»æ©Ÿä¸‹çš„çªç™¼æ€§ã€‚é è¨­å€¼ï¼š2ã€‚</t>
    <t id="9349">å¯åŒæ™‚é‹è¡Œçš„å³æ™‚æœå°‹çš„æœ€å¤§æ•¸é‡ (1-10)ã€‚å³æ™‚æœå°‹æ˜¯ CPU å¯†é›†çš„ï¼Œå› æ­¤è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†æœƒå¢žåŠ ä½‡åˆ—ç­‰å¾…æ™‚é–“ã€‚å€¼è¶Šé«˜ï¼Œæœå°‹éŽç¨‹è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´æ•ˆèƒ½é«˜å³°ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9264">å¿«å–æŸ¥è©¢å€å¡Šå¤§å°ï¼š</t>
    <t id="9265">å³æ™‚å„ªæƒ é™„åŠ å€å¡Šå¤§å°ï¼š</t>
    <t id="9364">æ¯å€‹å€å¡Š (10-200) é©—è­‰çš„å¿«å–æ¢ç›®ã€‚è¼ƒå°çš„å€¼å°‡å¿«å–é©—è­‰åˆ†æ•£åˆ°æ›´å¤šå¹€ï¼ˆæ›´å¹³æ»‘ï¼‰ï¼Œä½†å¯èƒ½æœƒå¢žåŠ æŸ¥æ‰¾å¿«å–äº¤æ˜“çš„æ™‚é–“ã€‚é è¨­å€¼ï¼š10ã€‚</t>
    <t id="9365">æ¯å€‹é™„åŠ åˆ‡ç‰‡é™„åŠ çš„å„ªæƒ  (50-2000)ã€‚è¼ƒå°çš„å€¼æœƒæ¸›å°‘æ¯å¹€åˆ—è¡¨é™„åŠ å·¥ä½œï¼ˆæ›´å¹³æ»‘ï¼‰ï¼Œä½†å¯èƒ½æœƒæ¸›æ…¢å³æ™‚æœå°‹çš„å®Œæˆé€Ÿåº¦ã€‚é è¨­å€¼ï¼š200ã€‚</t>
    <t id="9366">æœå°‹éŽ–å®šå­˜æ´»æ™‚é–“ï¼ˆä»¥ç§’ç‚ºå–®ä½ï¼‰(60-7200)ã€‚å¦‚æžœä¸€è‰˜èˆ¹å› ã€Œäº¤æ˜“æœå°‹å·²åœ¨é€²è¡Œä¸­ã€è€Œè¢«æ‹’çµ•çš„æ™‚é–“è¶…éŽæ­¤æ™‚é–“ï¼ŒGT å°‡é€éŽæ¸…é™¤éŽæ™‚çš„æœå°‹ç‹€æ…‹ä¸¦é‡‹æ”¾éŽ–å®šä¾†é€²è¡Œè‡ªæˆ‘ä¿®å¾©ã€‚é»˜è®¤å€¼ï¼š600 ç§’ã€‚</t>
    <t id="9370">æ‰¹é‡èƒŒå£“è»Ÿé–¾å€¼ï¼š</t>
    <t id="9371">æ‰¹é‡èƒŒå£“ç¡¬é–¾å€¼ï¼š</t>
    <t id="9372">æ¯ç‰‡æ‰‡å€æ•¸ï¼š</t>
    <t id="9373">ä¸»é åˆ·æ–°å†·å»æ™‚é–“ï¼š</t>
    <t id="9374">ç·©å­˜æœªå‘½ä¸­å†·å»åŸºç¤Žï¼š</t>
    <t id="9375">èª¿åº¦ç¨‹åºåˆ»åº¦é–“éš”ï¼š</t>
    <t id="9376">æ¯å€‹ Tick çš„æœ€å¤§å¿«å–æŸ¥è©¢æ•¸ï¼š</t>
    <t id="9377">æ¯å€‹åˆ»åº¦çš„æœ€å¤§æœå°‹é€£çºŒæ•¸ï¼š</t>
    <t id="9378">æ¯å€‹åˆ»åº¦çš„æœ€å¤§å‡ºè²¨é‡ï¼š</t>
    <t id="9379">æ¯å€‹åˆ»åº¦çš„æœ€å¤§ç‰©å“æ•¸ï¼š</t>
    <t id="9380">æ¯å€‹æ»´ç­”è²çš„æœ€å¤§å–šé†’æ™‚é–“ï¼š</t>
    <t id="9381">å¿«å–æŸ¥è©¢æœ€å¤§æ¢ç›®æ•¸ï¼š</t>
    <t id="9382">éŽæ™‚é–¾å€¼ç§’æ•¸ï¼š</t>
    <t id="9383">éšŠåˆ—éŽæ™‚é–¾å€¼ç§’æ•¸ï¼š</t>
    <t id="9384">å¤±æ•—äº¤æ˜“åˆ°æœŸç§’æ•¸ï¼š</t>
    <t id="9385">æœ€å¤§ä¸¦ç™¼å›žé€€æœå°‹ï¼š</t>
    <t id="9386">æœ€å¤§ä¸¦ç™¼å›žé€€æœå°‹ï¼š</t>
    <t id="9470">æ‰¹è™•ç†å™¨ç©å£“çš„è»Ÿé–¾å€¼ (5-50)ã€‚ç•¶ç©å£“é”åˆ°æ­¤å€¼æ™‚ï¼Œé–‹å§‹æ‡‰ç”¨èƒŒå£“ä»¥æ¸›æ…¢æ–°çš„æœå°‹è«‹æ±‚ã€‚è¼ƒä½Žçš„å€¼æœƒæ›´å¿«è§¸ç™¼èƒŒå£“ï¼ˆæ›´ä¿å®ˆï¼‰ã€‚é è¨­å€¼ï¼š10ã€‚</t>
    <t id="9471">æ‰¹è™•ç†å™¨ç©å£“çš„ç¡¬é–¾å€¼ (10-100)ã€‚ç•¶ç©å£“é”åˆ°æ­¤å€¼æ™‚ï¼Œæ–°çš„å³æ™‚æœå°‹å°‡è¢«é˜»æ­¢ï¼Œç›´åˆ°ç©å£“æ¸›å°‘ã€‚è¼ƒä½Žçš„å€¼æœƒæ›´å¿«åœ°é˜»æ­¢æœå°‹ï¼ˆæ›´ä¿å®ˆï¼‰ã€‚é è¨­å€¼ï¼š25ã€‚</t>
    <t id="9472">å³æ™‚å ±åƒ¹é›†åˆä¸­æ¯å€‹åˆ‡ç‰‡è™•ç†çš„ç£å€ (1-5)ã€‚è¼ƒå°çš„å€¼å°‡å·¥ä½œåˆ†æ•£åˆ°æ›´å¤šå¹€ï¼ˆæ›´å¹³æ»‘ï¼‰ï¼Œä½†å¯èƒ½æœƒæ¸›æ…¢å ±åƒ¹æ”¶é›†é€Ÿåº¦ã€‚å€¼è¶Šå¤§è™•ç†é€Ÿåº¦è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´å¹€å³°å€¼ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9473">ä¸»æ‰‡å€åˆ·æ–°å®Œæˆå¾Œçš„å†·å»æ™‚é–“ï¼ˆ10-120 ç§’ï¼‰ã€‚é˜²æ­¢éŽå¤šçš„åˆ·æ–°è«‹æ±‚ã€‚è¼ƒä½Žçš„å€¼å…è¨±æ›´é »ç¹çš„åˆ·æ–°ï¼Œä½†æœƒå¢žåŠ  CPU è² è¼‰ã€‚è¼ƒé«˜çš„å€¼æœƒé™ä½Žåˆ·æ–°é »çŽ‡ï¼Œä½†å¯èƒ½æœƒå»¶é²å¿«å–æ›´æ–°ã€‚é è¨­å€¼ï¼š30 ç§’ã€‚</t>
    <t id="9474">å¿«å–æœªå‘½ä¸­å¾Œé‡è©¦å³æ™‚æœå°‹ä¹‹å‰çš„åŸºæœ¬å†·å»æ™‚é–“ï¼ˆ1-30 ç§’ï¼‰ã€‚é˜²æ­¢éŽåº¦é‡è©¦ã€‚è¼ƒä½Žçš„å€¼æœƒæ›´å¿«é‡è©¦ï¼Œä½†æœƒå¢žåŠ  CPU è² è¼‰ã€‚è¼ƒé«˜çš„å€¼æœƒé™ä½Žé‡è©¦é »çŽ‡ï¼Œä½†å¯èƒ½æœƒå»¶é²äº¤æ˜“æŸ¥æ‰¾ã€‚é è¨­å€¼ï¼š10 ç§’ã€‚</t>
    <t id="9475">èª¿åº¦ç¨‹åºæ»´ç­”ä¹‹é–“çš„æ™‚é–“é–“éš”ï¼ˆä»¥æ¯«ç§’ç‚ºå–®ä½ï¼‰ï¼ˆ50-500 æ¯«ç§’ï¼‰ã€‚æŽ§åˆ¶èª¿åº¦ç¨‹åºè™•ç†å·¥ä½œä½‡åˆ—çš„é »çŽ‡ã€‚å€¼è¶Šä½Žï¼Œè™•ç†è¶Šé »ç¹ï¼Œä½†æœƒå¢žåŠ  CPU è² è¼‰ã€‚è¼ƒé«˜çš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†å¯èƒ½æœƒå¢žåŠ ä½‡åˆ—ç­‰å¾…æ™‚é–“ã€‚é è¨­å€¼ï¼š100 æ¯«ç§’ã€‚</t>
    <t id="9476">æ¯å€‹èª¿åº¦ç¨‹åºæ»´ç­”å•Ÿå‹•çš„æœ€å¤§å¿«å–æŸ¥è©¢æ•¸ (1-5)ã€‚é™åˆ¶å¿«å–æŸ¥è©¢é€ŸçŽ‡ä»¥é˜²æ­¢å¹€é˜»å¡žã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU å³°å€¼ï¼Œä½†æœƒæ¸›æ…¢å¿«å–æœå°‹é€Ÿåº¦ã€‚æ•¸å€¼è¶Šé«˜è™•ç†é€Ÿåº¦è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´å¡é “ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9477">æ¯å€‹èª¿åº¦ç¨‹åºåˆ»åº¦ (1-5) é–‹å§‹çš„æœ€å¤§æœå°‹ç¹¼çºŒæ¬¡æ•¸ã€‚é™åˆ¶é€£çºŒé€ŸçŽ‡ä»¥é˜²æ­¢å¹€é˜»å¡žã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU å³°å€¼ï¼Œä½†æœƒæ¸›æ…¢æœå°‹è™•ç†é€Ÿåº¦ã€‚æ•¸å€¼è¶Šé«˜è™•ç†é€Ÿåº¦è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´å¡é “ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9478">æ¯å€‹èª¿åº¦ç¨‹åºåˆ»åº¦ (1-5) è™•ç†çš„æœ€å¤§èˆ¹èˆ¶ã€‚é™åˆ¶èˆ¹èˆ¶è™•ç†é€ŸçŽ‡ä»¥é˜²æ­¢å¹€é˜»å¡žã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU å³°å€¼ï¼Œä½†æœƒæ¸›æ…¢ä½‡åˆ—è™•ç†é€Ÿåº¦ã€‚æ•¸å€¼è¶Šé«˜è™•ç†é€Ÿåº¦è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´å¡é “ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9479">æ¯å€‹èª¿åº¦ç¨‹åºåˆ»åº¦è™•ç†çš„æœ€å¤§å·¥ä½œé …æ•¸ (1-5)ã€‚é™åˆ¶å·¥ä½œé …è™•ç†é€ŸçŽ‡ä»¥é˜²æ­¢å¹€é˜»å¡žã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU å³°å€¼ï¼Œä½†æœƒæ¸›æ…¢ä½‡åˆ—è™•ç†é€Ÿåº¦ã€‚æ•¸å€¼è¶Šé«˜è™•ç†é€Ÿåº¦è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´å¡é “ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9480">æ¯å€‹èª¿åº¦ç¨‹åºæ»´ç­”è²å–šé†’çš„æœ€å¤§ç­‰å¾…è€…æ•¸ (1-10)ã€‚é™åˆ¶å–šé†’çŽ‡ï¼Œä»¥é˜²æ­¢ç•¶è¨±å¤šæœå‹™å“¡æŽ’éšŠæ™‚å‡ºç¾ CPU å³°å€¼ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU å³°å€¼ï¼Œä½†æœƒæ¸›æ…¢æœå‹™å“¡è™•ç†é€Ÿåº¦ã€‚æ•¸å€¼è¶Šé«˜è™•ç†é€Ÿåº¦è¶Šå¿«ï¼Œä½†å¯èƒ½æœƒå°Žè‡´å¡é “ã€‚é è¨­å€¼ï¼š2ã€‚</t>
    <t id="9481">æ¯æ‰¹æŸ¥è©¢çš„æœ€å¤§å¿«å–æ¢ç›®æ•¸ (1-200)ã€‚æŽ§åˆ¶å¿«å–æŸ¥è©¢æ‰¹æ¬¡å¤§å°ã€‚è¼ƒä½Žçš„å€¼ä½¿å¿«å–æœå°‹é€Ÿåº¦æ›´å¿«ï¼Œä½†å¯èƒ½æœƒéŒ¯éŽæ›´å¥½çš„äº¤æ˜“ã€‚è¼ƒé«˜çš„å€¼æœƒè€ƒæ…®æ›´å¤šå¿«å–äº¤æ˜“ï¼Œä½†æœƒå¢žåŠ é©—è­‰æ™‚é–“ã€‚é è¨­å€¼ï¼š50ã€‚</t>
    <t id="9482">å³æ™‚æœå°‹ç‹€æ…‹éŽæ™‚é–¾å€¼ï¼ˆä»¥ç§’ç‚ºå–®ä½ï¼‰(60-600)ã€‚ç•¶å³æ™‚æœå°‹ç‹€æ…‹æ—©æ–¼æ­¤æ™‚ï¼Œå®ƒè¢«èªç‚ºæ˜¯é™³èˆŠçš„ä¸¦è¢«æ¸…é™¤ã€‚è¼ƒä½Žçš„å€¼æœƒæ›´å¿«åœ°æ¸…é™¤éŽæ™‚ç‹€æ…‹ï¼Œä½†å¯èƒ½æœƒä¸­æ–·åˆæ³•æœå°‹ã€‚è¼ƒé«˜çš„å€¼å…è¨±æ›´é•·çš„æœç´¢ï¼Œä½†å¯èƒ½æœƒç•™ä¸‹é™³èˆŠç‹€æ…‹ã€‚é è¨­å€¼ï¼š300 ç§’ã€‚</t>
    <t id="9483">éšŠåˆ—é …ç›®é™³èˆŠé–¾å€¼ï¼ˆä»¥ç§’ç‚ºå–®ä½ï¼‰(30-300)ã€‚ç•¶éšŠåˆ—é …ç›®æ—©æ–¼æ­¤å€¼æ™‚ï¼Œå®ƒå€‘å°‡è¢«è¦–ç‚ºéŽæ™‚ä¸¦è¢«åˆªé™¤ã€‚è¼ƒä½Žçš„å€¼æœƒæ›´å¿«åœ°æ¸…é™¤éŽæ™‚çš„é …ç›®ï¼Œä½†å¯èƒ½æœƒåˆªé™¤åˆæ³•çš„æŽ’éšŠé …ç›®ã€‚è¼ƒé«˜çš„å€¼å…è¨±è¼ƒé•·çš„æŽ’éšŠæ™‚é–“ï¼Œä½†å¯èƒ½æœƒç•™ä¸‹é™³èˆŠçš„é …ç›®ã€‚é è¨­å€¼ï¼š60 ç§’ã€‚</t>
    <t id="9484">äº¤æ˜“ç·©å­˜éŽæœŸå¤±æ•—ï¼ˆ300-3600 ç§’ï¼‰ã€‚å¤±æ•—çš„äº¤æ˜“æœƒè¢«ç·©å­˜ä»¥é¿å…ç«‹å³é‡è©¦ã€‚è¼ƒä½Žçš„å€¼æœƒä½¿å¤±æ•—çš„äº¤æ˜“æ›´å¿«éŽæœŸï¼ˆæ›´å¤šé‡è©¦ï¼‰ï¼Œä½†æœƒé™ä½Žå¿«å–æœ‰æ•ˆæ€§ã€‚æ•¸å€¼è¶Šé«˜ï¼Œå¿«å–æ™‚é–“è¶Šé•·ï¼ˆé‡è©¦æ¬¡æ•¸è¶Šå°‘ï¼‰ï¼Œä½†å¯èƒ½æœƒå»¶é²é‡è©¦å˜—è©¦ã€‚é è¨­å€¼ï¼š1800 ç§’ï¼ˆ30 åˆ†é˜ï¼‰ã€‚</t>
    <t id="9485">æœ€å¤§ä¸¦ç™¼å›žé€€å³æ™‚æœå°‹ (1-10)ã€‚å¾Œå‚™æœå°‹ç¹žéŽæ¯å€éŽ–å®šï¼Œå…è¨±ä¾†è‡ªåŒä¸€æ¯å€çš„å¤šè‰˜èˆ¹éš»åŒæ™‚æœå°‹ã€‚è¼ƒä½Žçš„å€¼æœƒæ¸›å°‘ CPU è² è¼‰ï¼Œä½†å¯èƒ½æœƒæ¸›æ…¢å›žé€€æœå°‹é€Ÿåº¦ã€‚è¼ƒé«˜çš„å€¼å…è¨±æ›´å¤šä¸¦è¡Œå›žé€€æœç´¢ï¼Œä½†æœƒå¢žåŠ  CPU ä½¿ç”¨çŽ‡ã€‚é è¨­å€¼ï¼š1ã€‚</t>
    <t id="9490">è²¿æ˜“ç™¼ç¾è¨Šè™Ÿå»¶é²ï¼š</t>
    <t id="9590">å‘èˆ¹èˆ¶ç™¼é€ GT_Trade_Found è¨Šè™Ÿä¹‹å‰çš„å»¶é²ï¼ˆä»¥æ¯«ç§’ç‚ºå–®ä½ï¼ˆ10-1000 æ¯«ç§’ï¼‰ï¼‰ã€‚åœ¨ç™¼é€æ–°è«‹æ±‚ä»¥æ•ç²å»¶é²è¨Šè™Ÿä¹‹å‰ï¼Œèˆ¹èˆ¶å§‹çµ‚ç­‰å¾…ï¼ˆé…ç½®çš„å»¶é² + 5ms ç·©è¡å€ï¼‰ã€‚è¼ƒé«˜çš„å€¼å°‡è¨Šè™Ÿåˆ†æ•£åˆ°å¹€ä¹‹é–“ä»¥ç²å¾—æ›´å¹³æ»‘çš„æ€§èƒ½ã€‚é è¨­å€¼ï¼š10 æ¯«ç§’ã€‚</t>
    <t id="8000">GalaxyTrader è‰¦éšŠ</t>
    <t id="8001">GalaxyTrader è»ŠéšŠç®¡ç†èˆ‡è©¦é»žçµ±è¨ˆ</t>
    <t id="8002">æŸ¥çœ‹ä¸¦ç®¡ç†æ‰€æœ‰ GalaxyTrader è©¦é»ž</t>
    <t id="8100">èˆ¹èˆ¶ç·¨è™Ÿ</t>
    <t id="8101">é£›è¡Œå“¡</t>
    <t id="8102">èˆ¹</t>
    <t id="8103">åœ°ä½</t>
    <t id="8104">ç§©</t>
    <t id="8105">ç­‰ç´š</t>
    <t id="8106">XP</t>
    <t id="8107">çµ‚ç”Ÿåˆ©æ½¤</t>
    <t id="8108">åœ°é»ž</t>
    <t id="8109">åŸºåœ°</t>
    <t id="8110">æœ€å¾Œäº¤æ˜“</t>
    <t id="8111">è©¦è¾¦åˆ©æ½¤</t>
    <t id="8112">èˆ¹èˆ¶åˆ©æ½¤</t>
    <t id="8113">äº¤æ˜“æ•¸é‡</t>
    <t id="8200">é‡æ–°æ•´ç†</t>
    <t id="8201">åŒ¯å‡º CSV</t>
    <t id="8202">çµ±è¨ˆæ•¸æ“š</t>
    <t id="8203">è¨­å®š</t>
    <t id="8204">å¹«åŠ©</t>
    <t id="8205">é—œé–‰</t>
    <t id="8300">æ‰€æœ‰é£›è¡Œå“¡</t>
    <t id="8301">è²¿æ˜“</t>
    <t id="8302">è¨“ç·´</t>
    <t id="8303">ç¶­è­·</t>
    <t id="8304">ç·Šæ€¥ç‹€æ³</t>
    <t id="8305">åˆç´šï¼ˆLv 1-5ï¼‰</t>
    <t id="8306">é«˜ç´šï¼ˆLv 6-11ï¼‰</t>
    <t id="8307">å°ˆå®¶ (Lv 12+)</t>
    <t id="8308">å‰ 10 åæ”¶å…¥è€…</t>
    <t id="8350">æŽ’åºæ–¹å¼ï¼š</t>
    <t id="8351">èˆ¹èˆ¶ç·¨è™Ÿ</t>
    <t id="8352">é£›è¡Œå“¡å§“å</t>
    <t id="8353">èˆ¹èˆ¶é¡žåž‹</t>
    <t id="8354">åœ°ä½</t>
    <t id="8355">ç§©</t>
    <t id="8356">ç­‰ç´š</t>
    <t id="8357">XP</t>
    <t id="8358">åˆ©æ½¤</t>
    <t id="8400">æ²’æœ‰è¨»å†Šé£›è¡Œå“¡</t>
    <t id="8401">æ²’æœ‰é£›è¡Œå“¡åŒ¹é…éŽæ¿¾å™¨</t>
    <t id="8402">é£›è¡Œå“¡ç¸½æ•¸ï¼š</t>
    <t id="8403">èˆ¹éšŠç¸½åˆ©æ½¤ï¼š</t>
    <t id="8404">æœ€å¾Œæ›´æ–°ï¼š</t>
    <t id="8405">æœå°‹é£›è¡Œå“¡...</t>
    <t id="8114">éƒ¨é–€</t>
    <t id="8320">èˆ¹èˆ¶æ›´å</t>
    <t id="8321">è‡ªè¨‚åç¨±</t>
    <t id="8322">è¨­å®šåç¨±</t>
    <t id="8323">æ¸…æ™°çš„åå­—</t>
    <t id="8324">åç¨±è¨­å®šæˆåŠŸ</t>
    <t id="8325">åç¨±æ¸…é™¤æˆåŠŸ</t>
    <t id="8450">å¯„è‡³åŸ¹è¨“</t>
    <t id="8451">è¨»éŠ·</t>
    <t id="8452">å¼·åˆ¶å‡ºå”®è²¨ç‰©</t>
    <t id="8453">é€åŽ»ç¶­ä¿®</t>
    <t id="8454">ç™¼é€è‡³è£œçµ¦</t>
    <t id="8455">åœæ­¢æ‰€æœ‰è¨‚å–®</t>
    <t id="8456">è¡Œå‹•</t>
    <t id="8500">é»žæ“ŠæŒ‰èˆ¹èˆ¶ ID æŽ’åº</t>
    <t id="8501">é»žæ“ŠæŒ‰é£›è¡Œå“¡å§“åæŽ’åº</t>
    <t id="8502">é»žæ“ŠæŒ‰èˆ¹èˆ¶é¡žåž‹æŽ’åº</t>
    <t id="8503">é»žæ“ŠæŒ‰ç‹€æ…‹æŽ’åº</t>
    <t id="8504">é»žæ“ŠæŒ‰æŽ’åæŽ’åº</t>
    <t id="8505">é»žæ“ŠæŒ‰ç­‰ç´šæŽ’åº</t>
    <t id="8506">é»žæ“ŠæŒ‰XPæŽ’åº</t>
    <t id="8507">é»žæ“ŠæŒ‰çµ‚èº«åˆ©æ½¤æŽ’åº</t>
    <t id="8508">å¾žä»»å‹™ç³»çµ±åˆ·æ–°é£›è¡Œå“¡æ•¸æ“š</t>
    <t id="8509">å°‡ç›®å‰è¦–åœ–åŒ¯å‡ºåˆ° CSV æ–‡ä»¶</t>
    <t id="8510">æŸ¥çœ‹æ©ŸéšŠçµ±è¨ˆæ•¸æ“šå’Œåœ–è¡¨</t>
    <t id="8511">é…ç½®é¸å–®è¨­å®š</t>
    <t id="8512">é¡¯ç¤ºå¹«åŠ©å’Œéµç›¤å¿«æ·éµ</t>
    <t id="8600">æœªæ‰¾åˆ° GalaxyTrader é£›è¡Œå“¡</t>
    <t id="8601">é€éŽå°‡èˆ¹éš»åˆ†é…çµ¦ GalaxyTrader ä¾†å»ºç«‹é£›è¡Œå“¡ï¼Œæˆ–ç­‰å¾…è³‡æ–™è¼‰å…¥ã€‚</t>
    <t id="9001">GTé‡æ–°å‘½å</t>
    <t id="9902">å¯„è‡³åŸ¹è¨“</t>
    <t id="9903">æ‰‹å‹•è¨“ç·´æŽ’éšŠç­‰å¾… %1ã€‚é£›è¡Œå“¡å°‡åœ¨æœ¬é€±æœŸçµæŸå¾Œé–‹å§‹è¨“ç·´ã€‚</t>
    <t id="9904">ç•¶å‰é€±æœŸå¾ŒæŽ’éšŠçš„è¨“ç·´</t>
    <t id="9905">æœªæ‰¾åˆ°é£›è¡Œå“¡æˆ–èˆ¹éš»</t>
    <t id="9906">è‡ªå‹•è¨“ç·´å·²å•Ÿç”¨ - ä¸éœ€è¦æ‰‹å‹•éšŠåˆ—</t>
    <t id="9907">é£›è¡Œå“¡è¨“ç·´æœªå—é˜»</t>
    <t id="9910">äº¤æ˜“å­¸é™¢</t>
    <t id="9911">å­¸å¾’ï¼ˆ4 ç´šï¼‰- %1 / %2</t>
    <t id="9912">äº¤æ˜“è€…ï¼ˆ7 ç´šï¼‰- %1 / %2</t>
    <t id="9913">äº¤æ˜“å¤§å¸« (Lvl 13) - %1 / %2</t>
    <t id="9920">é£›è¡Œå“¡ %1 åƒåŠ äº† %2 ç´šçš„å­¸é™¢èª²ç¨‹ã€‚å‡ºç™¼å‰å¾€æœ€è¿‘çš„è²¿æ˜“ç«™ã€‚</t>
    <t id="9921">æœ¬èª²ç¨‹è³‡é‡‘ä¸è¶³ï¼ˆéœ€ %1ï¼Œæœ‰ %2ï¼‰ã€‚</t>
    <t id="9922">èª²ç¨‹ä¸å¯ç”¨ - é£›è¡Œå“¡ %1 å·²é”åˆ°æˆ–é«˜æ–¼æ­¤ç­‰ç´šã€‚</t>
    <t id="9923">é£›è¡Œå“¡ %1 åœ¨ %5 ä¸ŠåƒåŠ äº†äº¤æ˜“å­¸é™¢ç­‰ç´š %2 èª²ç¨‹ï¼ˆè²»ç”¨ï¼š%3 Crï¼ŒæŒçºŒæ™‚é–“ï¼š%4 åˆ†é˜ï¼‰ã€‚</t>
    <t id="11011">GT Apprentice ä¸­åž‹èˆ¹èˆ¶æ¸›é€Ÿæ©Ÿ</t>
    <t id="11012">å¼•æ“Žæ”¹è£æœƒç•¥å¾®é™ä½Žä¸­åž‹èˆ¹èˆ¶ä¸Šç¼ºä¹ç¶“é©—çš„é£›è¡Œå“¡çš„æ€§èƒ½ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -5% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="11013">GT Apprentice ä¸­åž‹è¡Œç¨‹æ¸›é€Ÿå™¨</t>
    <t id="11014">å¼•æ“Žæ”¹è£æœƒç•¥å¾®é™ä½Žä¸­åž‹èˆ¹èˆ¶ä¸Šç¼ºä¹ç¶“é©—çš„é£›è¡Œå“¡çš„è¡Œé§›æ€§èƒ½ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -5% è¡Œé§›é€Ÿåº¦ã€‚</t>
    <t id="11021">GT Apprenticeå¤§åž‹èˆ¹èˆ¶æ¸›é€Ÿæ©Ÿ</t>
    <t id="11022">å¼•æ“Žæ”¹è£æœƒé™ä½Žå¤§åž‹èˆ¹èˆ¶ä¸Šç¼ºä¹ç¶“é©—çš„é£›è¡Œå“¡çš„æ€§èƒ½ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -15% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="11023">GT Apprentice å¤§è¡Œç¨‹æ¸›é€Ÿæ©Ÿ</t>
    <t id="11024">å¼•æ“Žæ”¹è£æœƒé™ä½Žç¼ºä¹ç¶“é©—çš„é£›è¡Œå“¡åœ¨å¤§åž‹èˆ¹èˆ¶ä¸Šçš„è¡Œé§›æ€§èƒ½ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -15% è¡Œé§›é€Ÿåº¦ã€‚</t>
    <t id="11031">GT å­¸å¾’ä¸»åŠ›è‰¦æ¸›é€Ÿæ©Ÿ</t>
    <t id="11032">å¼•æ“Žæ”¹è£æœƒé¡¯è‘—é™ä½Žä¸»åŠ›è‰¦ä¸Šç¼ºä¹ç¶“é©—çš„é£›è¡Œå“¡çš„æ€§èƒ½ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -25% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="11033">GT Apprentice Capital æ—…è¡Œæ¸›é€Ÿæ©Ÿ</t>
    <t id="11034">å¼•æ“Žæ”¹è£æœƒé¡¯è‘—é™ä½Žç¼ºä¹ç¶“é©—çš„é£›è¡Œå“¡åœ¨ä¸»åŠ›è‰¦ä¸Šçš„æ—…è¡Œæ€§èƒ½ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -25% è¡Œé§›é€Ÿåº¦ã€‚</t>
    <t id="12001">GT åŸºæœ¬å°åž‹èˆ¹èˆ¶å¢žå¼·å™¨</t>
    <t id="12002">é‡å°æ“æœ‰åŸºæœ¬èªè­‰é£›è¡Œå“¡çš„å°åž‹èˆ¹èˆ¶çš„å°ˆæ¥­å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +3% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="12003">GT åŸºæœ¬å°åž‹æ—…è¡Œå¢žå¼·å™¨</t>
    <t id="12004">é‡å°æ“æœ‰åŸºæœ¬èªè­‰é£›è¡Œå“¡çš„å°åž‹èˆ¹èˆ¶çš„å°ˆæ¥­å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +3% è¡Œé€²é€Ÿåº¦ã€‚</t>
    <t id="13001">GTåŸºæœ¬åž‹å¤§åž‹èˆ¹èˆ¶æ¸›é€Ÿæ©Ÿ</t>
    <t id="13002">é‡å°æ“æœ‰åŸºæœ¬èªè­‰é£›è¡Œå“¡çš„å¤§åž‹èˆ¹èˆ¶é€²è¡Œå°ˆæ¥­å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -8% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="13003">GT åŸºæœ¬åž‹å¤§è¡Œç¨‹æ¸›é€Ÿæ©Ÿ</t>
    <t id="13004">é‡å°æ“æœ‰åŸºæœ¬èªè­‰é£›è¡Œå“¡çš„å¤§åž‹èˆ¹èˆ¶é€²è¡Œå°ˆæ¥­å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -8% è¡Œé§›é€Ÿåº¦ã€‚</t>
    <t id="14001">GT åŸºæœ¬ä¸»åŠ›è‰¦æ¸›é€Ÿæ©Ÿ</t>
    <t id="14002">é‡å°æ“æœ‰åŸºæœ¬èªè­‰é£›è¡Œå“¡çš„ä¸»åŠ›è‰¦é€²è¡Œå°ˆæ¥­å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -15% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="14003">GT åŸºæœ¬è³‡æœ¬æ—…è¡Œæ¸›é€Ÿå™¨</t>
    <t id="14004">é‡å°æ“æœ‰åŸºæœ¬èªè­‰é£›è¡Œå“¡çš„ä¸»åŠ›è‰¦é€²è¡Œå°ˆæ¥­å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ -15% è¡Œé§›é€Ÿåº¦ã€‚</t>
    <t id="15001">GT å°ˆå®¶å°åž‹èˆ¹èˆ¶å¢žå¼·å™¨</t>
    <t id="15002">é…å‚™å°ˆæ¥­é£›è¡Œå“¡çš„å°åž‹èˆ¹èˆ¶çš„å…ˆé€²å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +25% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="15003">GT Expert å°åž‹æ—…éŠå¢žå¼·å™¨</t>
    <t id="15004">é…å‚™å°ˆæ¥­é£›è¡Œå“¡çš„å°åž‹èˆ¹èˆ¶çš„å…ˆé€²å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +25% è¡Œé€²é€Ÿåº¦ã€‚</t>
    <t id="16001">GT Expert å¤§åž‹èˆ¹èˆ¶å¢žå¼·å™¨</t>
    <t id="16002">é…å‚™å°ˆæ¥­é£›è¡Œå“¡çš„å¤§åž‹èˆ¹èˆ¶çš„å…ˆé€²å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +15% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="16003">GT Expert å¤§è¡Œç¨‹å¢žå¼·å™¨</t>
    <t id="16004">é…å‚™å°ˆæ¥­é£›è¡Œå“¡çš„å¤§åž‹èˆ¹èˆ¶çš„å…ˆé€²å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +15% è¡Œé€²é€Ÿåº¦ã€‚</t>
    <t id="17001">GT å°ˆå®¶ä¸»åŠ›è‰¦å¢žå¼·å™¨</t>
    <t id="17002">ç”±å°ˆå®¶é£›è¡Œå“¡å°ä¸»åŠ›è‰¦é€²è¡Œå…ˆé€²çš„å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +6% é€Ÿåº¦ã€æŽ¨åŠ›å’Œæ—‹è½‰ã€‚</t>
    <t id="17003">GT å°ˆå®¶è³‡æœ¬ä¹‹æ—…å¢žå¼·å™¨</t>
    <t id="17004">ç”±å°ˆå®¶é£›è¡Œå“¡å°ä¸»åŠ›è‰¦é€²è¡Œå…ˆé€²çš„å¼•æ“Žæ”¹è£ã€‚ç”± GalaxyTrader AI ç³»çµ±ä½¿ç”¨ã€‚ +6% è¡Œé€²é€Ÿåº¦ã€‚</t>
    <t id="18001">åš´é‡æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹èˆ¶ï¼‰</t>
    <t id="18002">åš´é‡æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹èˆ¶ï¼‰- è¡¨ç¤ºç”±æ–¼é£›è¡Œå“¡ç¼ºä¹å¤§åž‹èˆ¹èˆ¶ç¶“é©—è€Œå°Žè‡´åš´é‡çš„æ€§èƒ½æå¤±ã€‚ç•¶é£›è¡Œå“¡æŠ€èƒ½ä¸è¶³ä»¥æ»¿è¶³èˆ¹èˆ¶å°ºå¯¸æ™‚ï¼Œç”± GalaxyTrader ç³»çµ±è‡ªå‹•æ‡‰ç”¨ã€‚å¢žåŠ èˆ¹èˆ¶è³ªé‡ã€‚ ï¼ˆåƒ…é™ GT ç³»çµ± - ä¸å¯æ‰‹å‹•å®‰è£ï¼‰</t>
    <t id="18003">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹èˆ¶ï¼‰</t>
    <t id="18004">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹èˆ¶ï¼‰- è¡¨ç¤ºé£›è¡Œå“¡é©æ‡‰èˆ¹èˆ¶è¤‡é›œæ€§æ™‚çš„ä¸­ç­‰æ€§èƒ½æå¤±ã€‚ç•¶é£›è¡Œå“¡æŠ€èƒ½ä¸è¶³ä»¥æ»¿è¶³èˆ¹èˆ¶å°ºå¯¸æ™‚ï¼Œç”± GalaxyTrader ç³»çµ±è‡ªå‹•æ‡‰ç”¨ã€‚å¢žåŠ èˆ¹èˆ¶è³ªé‡ã€‚ ï¼ˆåƒ…é™ GT ç³»çµ± - ä¸å¯æ‰‹å‹•å®‰è£ï¼‰</t>
    <t id="18005">è¼•åž‹æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹èˆ¶ï¼‰</t>
    <t id="18006">è¼•åº¦æŠ€èƒ½é™åˆ¶ï¼ˆèˆ¹èˆ¶ï¼‰- è¡¨ç¤ºé£›è¡Œå“¡æŠ€èƒ½ç™¼å±•éŽç¨‹ä¸­çš„è¼•å¾®æ€§èƒ½æå¤±ã€‚ç•¶é£›è¡Œå“¡æŠ€èƒ½ä¸è¶³ä»¥æ»¿è¶³èˆ¹èˆ¶å°ºå¯¸æ™‚ï¼Œç”± GalaxyTrader ç³»çµ±è‡ªå‹•æ‡‰ç”¨ã€‚å¢žåŠ èˆ¹èˆ¶è³ªé‡ã€‚ ï¼ˆåƒ…é™ GT ç³»çµ± - ä¸å¯æ‰‹å‹•å®‰è£ï¼‰</t>
    <t id="18007">åš´é‡æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰</t>
    <t id="18008">åš´é‡æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰- è¡¨ç¤ºç”±æ–¼é£›è¡Œå“¡ç¼ºä¹å¤§åž‹èˆ¹èˆ¶ç¶“é©—è€Œå°Žè‡´åš´é‡çš„æ€§èƒ½æå¤±ã€‚ç•¶é£›è¡Œå“¡æŠ€èƒ½ä¸è¶³ä»¥æ»¿è¶³èˆ¹èˆ¶å°ºå¯¸æ™‚ï¼Œç”± GalaxyTrader ç³»çµ±è‡ªå‹•æ‡‰ç”¨ã€‚æ¸›å°‘ç™¼å‹•æ©ŸæŽ¨åŠ›å’Œæ—‹è½‰ã€‚ ï¼ˆåƒ…é™ GT ç³»çµ± - ä¸å¯æ‰‹å‹•å®‰è£ï¼‰</t>
    <t id="18009">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰</t>
    <t id="18010">ä¸­ç­‰æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰- è¡¨ç¤ºé£›è¡Œå“¡é©æ‡‰èˆ¹èˆ¶è¤‡é›œæ€§æ™‚çš„ä¸­ç­‰æ€§èƒ½æå¤±ã€‚ç•¶é£›è¡Œå“¡æŠ€èƒ½ä¸è¶³ä»¥æ»¿è¶³èˆ¹èˆ¶å°ºå¯¸æ™‚ï¼Œç”± GalaxyTrader ç³»çµ±è‡ªå‹•æ‡‰ç”¨ã€‚æ¸›å°‘ç™¼å‹•æ©ŸæŽ¨åŠ›å’Œæ—‹è½‰ã€‚ ï¼ˆåƒ…é™ GT ç³»çµ± - ä¸å¯æ‰‹å‹•å®‰è£ï¼‰</t>
    <t id="18011">è¼•æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰</t>
    <t id="18012">è¼•åº¦æŠ€èƒ½é™åˆ¶ï¼ˆå¼•æ“Žï¼‰- è¡¨ç¤ºé£›è¡Œå“¡æŠ€èƒ½ç™¼å±•éŽç¨‹ä¸­çš„è¼•å¾®æ€§èƒ½æå¤±ã€‚ç•¶é£›è¡Œå“¡æŠ€èƒ½ä¸è¶³ä»¥æ»¿è¶³èˆ¹èˆ¶å°ºå¯¸æ™‚ï¼Œç”± GalaxyTrader ç³»çµ±è‡ªå‹•æ‡‰ç”¨ã€‚æ¸›å°‘ç™¼å‹•æ©ŸæŽ¨åŠ›å’Œæ—‹è½‰ã€‚ ï¼ˆåƒ…é™ GT ç³»çµ± - ä¸å¯æ‰‹å‹•å®‰è£ï¼‰</t>
    <t id="9250">èˆ¹åœ‹å‘½å</t>
    <t id="9350">è‡ªè¨‚èˆ¹èˆ¶ç‹€æ…‹ç¸®å¯«ã€‚é è¨­å€¼é¡¯ç¤ºåœ¨è¼¸å…¥æ¡†ä¸­ä¸¦ä¸”å¯ä»¥è¢«è¦†å¯«ã€‚æœ€å¤š 3 å€‹å­—å…ƒã€‚æ‰€æœ‰èˆ¹èˆ¶åç¨±è®Šæ›´å¾Œéƒ½æœƒè‡ªå‹•æ›´æ–°ã€‚</t>
    <t id="9251">è£œçµ¦ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9252">ä¿®å¾©ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9253">ç¶­è­·ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9254">è¨“ç·´ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9255">é‡æ–°è·¯ç”±ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9256">æ¸…é—œç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9257">é˜»å¡žç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9258">å¾Œå‚™ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9259">å­¤ç«‹ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9260">äº¤æ˜“ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9261">ç©ºé–’ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9262">é€ƒé€¸ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9268">ä¸å¯é”ç‹€æ…‹ç¸®å¯«ï¼š</t>
    <t id="9269">è©¦é»žäº¤æ˜“æ‰€åœ‹å®¶ç¸®å¯«ï¼š</t>
    <t id="9270">è‡ªè¨‚é»‘åå–®å‰ç¶´æ¨™ç±¤ï¼š</t>
    <t id="9700">ä½œå¼Š (å£žäº†ã€‚é€™è£¡ä»€éº¼éƒ½æ²’æœ‰!! çœŸçš„!!)</t>
    <t id="9701">GTé£›èˆ¹ç„¡æ•µ</t>
    <t id="9702">æ‰€æœ‰çŽ©å®¶é£›èˆ¹ç„¡æ•µ</t>
    <t id="9800">è«‹èµ°é–‹ï¼Œé£›è¡Œå“¡ã€‚é€™æ˜¯å£žæŽ‰çš„é–‹ç™¼è€…æ¸¬è©¦å·¥å…·ï¼Œä¸æ˜¯å¥½çŽ©çš„æŒ‰éˆ•é¸å–®ã€‚é€™è£¡ä»€éº¼éƒ½æ²’æœ‰ã€‚çœŸçš„ã€‚ä½ å·²ç¶“æ”¶åˆ°è­¦å‘Šäº†ã€‚å¤§æ¦‚å§ã€‚</t>
    <t id="9801">åŸ·è¡ŒGalaxyTraderå‘½ä»¤çš„é£›èˆ¹èˆ¹é«”èˆ‡è­·ç›¾ä¸æœƒä½Žæ–¼100%ã€‚å†æ¬¡é»žæ“Šå¯é—œé–‰ã€‚</t>
    <t id="9802">æ‰€æœ‰çŽ©å®¶é£›èˆ¹çš„èˆ¹é«”èˆ‡è­·ç›¾ä¸æœƒä½Žæ–¼100%ã€‚å†æ¬¡é»žæ“Šå¯é—œé–‰ã€‚å¤ªç©ºç«™ä¸å—å½±éŸ¿ã€‚</t>
    <t id="9703">ç‚ºGTæ¸¬è©¦æ­ç¤ºå…¨å®‡å®™</t>
    <t id="9704">å·²æ­ç¤º</t>
    <t id="9705">æ­ç¤º</t>
    <t id="9803">æ­ç¤ºæ‰€æœ‰æ˜Ÿå€æˆ°çˆ­è¿·éœ§ï¼Œæ¨™è¨˜æ‰€æœ‰å¤ªç©ºç«™ç‚ºå·²çŸ¥ï¼ŒæŽˆäºˆæ‰€æœ‰æ´¾ç³»è²¿æ˜“è¨‚é–±è¨±å¯ï¼Œä¸¦è¨‚é–±å…¨éŠ€æ²³è²¿æ˜“å ±åƒ¹ã€‚å‡ºç¾æ–°DLCæ˜Ÿå€å¾Œå¯å†æ¬¡é»žæ“Šã€‚åƒ…ç”¨æ–¼æ¸¬è©¦ã€‚</t>
    <t id="9706">æœ€å¤§åŒ–å·²è¨»å†ŠGTé£›è¡Œå“¡XP</t>
    <t id="9707">å·²æœ€å¤§åŒ–</t>
    <t id="9708">æœ€å¤§XP</t>
    <t id="9804">å°‡GTè¨»å†Šè¡¨ä¸­æ¯ä½é£›è¡Œå“¡è¨­ç‚º15ç´šå’Œæœ€å¤§XPã€‚æ¸…é™¤è¨“ç·´é–€æª»å’Œé˜»å¡žã€‚å•Ÿç”¨åƒ…åŽŸç‰ˆXPæ™‚è·³éŽã€‚åƒ…ç”¨æ–¼æ¸¬è©¦ã€‚</t>
    <t id="9351">è£œçµ¦ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šRSï¼‰</t>
    <t id="9352">ä¿®å¾©ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šRPï¼‰</t>
    <t id="9353">ç¶­è­·ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šMTï¼‰</t>
    <t id="9354">è¨“ç·´ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­ï¼šTRï¼‰</t>
    <t id="9355">é‡æ–°è·¯ç”±ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­ï¼šRRï¼‰</t>
    <t id="9356">è¨±å¯ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šCLï¼‰</t>
    <t id="9357">é˜»å¡žç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šBLï¼‰</t>
    <t id="9358">å›žé€€ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šFBï¼‰</t>
    <t id="9359">éš”é›¢ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šISï¼‰</t>
    <t id="9360">äº¤æ˜“ç‹€æ…‹ç¸®å¯«ï¼ˆé è¨­ï¼šTDï¼‰</t>
    <t id="9361">ç©ºé–’ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­ï¼šIDï¼‰</t>
    <t id="9362">é€ƒé€¸ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šESï¼‰</t>
    <t id="9367">ç„¡æ³•åˆ°é”ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­å€¼ï¼šURï¼‰</t>
    <t id="9368">Pilot Exchange ç‹€æ…‹çš„ç¸®å¯«ï¼ˆé è¨­ï¼šPEï¼‰</t>
    <t id="9369">é¡¯ç¤ºç‚º MK3 èˆ¹èˆ¶çš„å‰ç¶´ï¼Œå—è‡ªè¨‚æ´¾ç³»é»‘åå–®ï¼ˆåŒ…æ‹¬ä¸‹å±¬ï¼‰å½±éŸ¿ã€‚é è¨­å€¼ï¼šCB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">è»Šç«™å•†äºº - å‘ NPC æ´¾ä¿‚å‡ºå”®è»Šç«™ç”¢å“</t>
    <t id="30010">ä¸»ç«™</t>
    <t id="30011">æœ€å¤§è³£å‡ºè·é›¢</t>
    <t id="30012">å¿½è¦–è²¿æ˜“è¦å‰‡</t>
    <t id="30013">æ½”å…·éŽæ¿¾å™¨</t>
    <t id="30014">éŠ·å”®è²¨ç‰©å¡«å……ç›®æ¨™%</t>
    <t id="30015">å›žæº¯å®¹å·®</t>
    <t id="30016">è³¼è²·è²¨ç‰©å¡«å……ç›®æ¨™%</t>
    <t id="30017">æ—¥èªŒæ¢ç›®</t>
    <t id="30018">é€šçŸ¥ç´šåˆ¥</t>
    <t id="30019">è‰¦éšŠå”èª¿</t>
    <t id="30020">åµéŒ¯ç­‰ç´š</t>
    <t id="30021">è£œçµ¦ç«™</t>
    <t id="30022">æœ€å°ç«™å„²å­˜ç™¾åˆ†æ¯”</t>
    <t id="30023">å…è¨±éžæ³•å•†å“</t>
    <t id="30024">è²¨ç‰©/åˆ©æ½¤</t>
    <t id="30025">å…è¨±å¤šç­†äº¤æ˜“</t>
    <t id="30110">å‡ºå”®å•†å“çš„çŽ©å®¶ç«™ï¼ˆéœ€ç«™ä½åˆ†é…ï¼‰</t>
    <t id="30111">å°‹æ‰¾NPCè²·å®¶çš„æœ€å¤§é–€è·é›¢ï¼ˆå—é£›è¡Œå“¡æŠ€èƒ½é™åˆ¶ï¼‰</t>
    <t id="30112">å¿½ç•¥è»Šç«™è²¿æ˜“é™åˆ¶ - ç„¡è«–è»Šç«™è²¿æ˜“è¦å‰‡å¦‚ä½•ï¼Œéƒ½å¯ä»¥å‡ºå”®çµ¦ä»»ä½•å‹å¥½æ´¾ç³»</t>
    <t id="30113">å¯é¸é…æ½”å…·éŽæ¿¾å™¨ï¼›ç•™ç©ºä»¥å‡ºå”®æ‰€æœ‰è»Šç«™ç”¢å“å’Œå•†å“</t>
    <t id="30114">éŠ·å”®è¡Œç¨‹å‡ºç™¼å‰çš„æœ€ä½Žè²¨ç‰©è£è¼‰ç™¾åˆ†æ¯”</t>
    <t id="30115">åœ¨è¡Œç¨‹ä¸­æ–°å¢žç¬¬äºŒå€‹å•†å“æ™‚å…è¨±çš„æœ€å¤§é¡å¤–è·³èºæ¬¡æ•¸ï¼ˆ0 = åƒ…ç›´æŽ¥åœ¨è·¯ç·šä¸Šçš„è²·å®¶ï¼‰</t>
    <t id="30116">ä¾›æ‡‰é‹ä½œçš„ç›®æ¨™è²¨ç‰©å¡«å……é‡ï¼ˆè»Ÿç›®æ¨™ï¼Œè²¿æ˜“å•†å¯èƒ½æœƒæå‰å‡ºç™¼ï¼‰</t>
    <t id="30117">å•Ÿç”¨æ¯ç­†äº¤æ˜“æ—¥èªŒæ¢ç›®</t>
    <t id="30118">é€šçŸ¥ç­‰ç´šï¼š0=å®‰éœã€1=æ­£å¸¸ã€2=è©³ç´°</t>
    <t id="30119">å•Ÿç”¨è»ŠéšŠå”èª¿å’Œè²¿æ˜“é è¨‚ç³»çµ±</t>
    <t id="30120">èª¿è©¦æ—¥èªŒè¨˜éŒ„ç­‰ç´šï¼š0=é—œé–‰ã€1=æ­£å¸¸ã€2=è©³ç´°</t>
    <t id="30121">å•Ÿç”¨å¾Œï¼Œä¹Ÿå¯ä»¥ç‚ºè©²ç«™è³¼è²·è³‡æºã€‚ç•¶å„²å­˜é‡ä½Žæ–¼æœ€ä½Žé–¾å€¼æ™‚ï¼Œä¾›æ‡‰å„ªå…ˆ</t>
    <t id="30122">ç•¶ä»»ä½•è³‡æºä½Žæ–¼å…¶ç›®æ¨™ç™¾åˆ†æ¯”æ™‚ï¼Œä¾›æ‡‰å„ªå…ˆæ–¼éŠ·å”®ã€‚å¦‚æžœç«™ç„¡æ³•æ‰¿æ“”è³‡æºå‰‡è¢«å¿½ç•¥</t>
    <t id="30123">å…è¨±å‡ºå”®æˆ–è³¼è²·éžæ³•/é•ç¦å•†å“ï¼ˆå¦‚æœ‰ï¼‰</t>
    <t id="30124">éŠ·å”®é¸æ“‡ï¼š1=è²¨ç‰©ï¼ˆå„ªå…ˆè©²å•†å“åº«å­˜å æ¯”æœ€é«˜ï¼›å¹³æ‰‹å‰‡ä¾åˆ©æ½¤ï¼‰ï¼Œ2=åˆ©æ½¤ï¼ˆæœ€é«˜åˆ©æ½¤è©•åˆ†ï¼‰</t>
    <t id="30125">å…è¨±åœ¨ä¸€å€‹é€±æœŸå…§ä¸²è¯å¤šç­†éŠ·å”®ï¼ˆæœ€å¤š3ç¨®å•†å“æˆ–ç›®çš„åœ°ï¼‰ã€‚é—œé–‰å¾Œæ¯é€±æœŸåƒ…åŸ·è¡Œå–®ç­†äº¤æ˜“</t>
    <t id="30200">å°‡ %1 %2 å¾ž %3 å‡ºå”®åˆ° %4</t>
    <t id="30201">åœ¨ %1 è·³å…§æœªæ‰¾åˆ°é›»å°ç”¢å“çš„è²·å®¶</t>
    <t id="30202">ä¸»ç«™ %1 è¢«æ¯€ - ç«™äº¤æ˜“è€…è¨‚å–®è¢«å–æ¶ˆ</t>
    <t id="30203">ä¸»ç«™ %1 ä¸å†ç”±çŽ©å®¶æ“æœ‰ - è¨‚å–®å·²å–æ¶ˆ</t>
    <t id="30204">éœ€è¦åˆ†é…è»Šç«™ - è¨‚å–®å·²å–æ¶ˆ</t>
    <t id="30205">MK1 Station Trader æ–¼ %1 é–‹å§‹</t>
    <t id="30206">å·²å®Œæˆé”€å”®: %1%2å‡ºå”®ç»™ %3Cr %4Cr (ç›ˆåˆ©:%5Cr)</t>
    <t id="30207">å¤šä»¶ç‰©å“ä¹‹æ—…ï¼šå°‡ %1 ä»¶ç‰©å“é‹é€åˆ° %2 å€‹ç›®çš„åœ°</t>
    <t id="30208">Supplying %1 %2 to %3 from %4</t>
    <t id="30500">GalaxyTrader MK1 è¨­å®š</t>
    <t id="30501">ç«™äº¤æ˜“é è¨­å€¼</t>
    <t id="30502">é è¨­æœ€å¤§éŠ·å”®è·é›¢</t>
    <t id="30503">é è¨­éŠ·å”®è²¨ç‰©å¡«å……ç›®æ¨™</t>
    <t id="30504">é è¨­å¿½ç•¥äº¤æ˜“è¦å‰‡</t>
    <t id="30505">é è¨­å›žæº¯å®¹å·®</t>
    <t id="30506">æœªæ‰¾åˆ°äº¤æ˜“æ™‚çš„ç­‰å¾…æ™‚é–“</t>
    <t id="30507">é è¨­è²·å…¥è²¨ç‰©å¡«å……ç›®æ¨™</t>
    <t id="31002">éŠ€æ²³ç¤¦å·¥</t>
    <t id="31102">å…·æœ‰ç«™é»žä¾›æ‡‰å’Œ XP é€²åº¦çš„è‡ªä¸»æŽ¡ç¤¦</t>
    <t id="31010">ä¸»ç«™</t>
    <t id="31110">é–‹æŽ¡ä¸¦é‹é€åˆ°çš„ç«™é»žï¼ˆèˆ‡æœ¬åœŸéƒ¨é–€äº’æ–¥ï¼‰</t>
    <t id="31011">å®¶å±…ç”¢æ¥­</t>
    <t id="31111">ç¶“ç‡Ÿæ¥­ï¼›æœªè¨­ç½®ä¸»ç«™æ™‚ä½¿ç”¨</t>
    <t id="31012">è³‡æºç±ƒ</t>
    <t id="31112">é–‹æŽ¡çš„å•†å“ï¼›ç©ºè·Ÿéš¨ç«™éœ€æ±‚è§£æž</t>
    <t id="31013">ç›®æ¨™ç«™</t>
    <t id="31113">å¯é¸é…çš„è¼¸é€ç«™éŽæ¿¾å™¨ï¼›ç©ºæºè‡ªå®¶åº­ä¸Šä¸‹æ–‡</t>
    <t id="31014">æº¢å‡ºé–¾å€¼%</t>
    <t id="31114">ç­‰æ–¼æˆ–é«˜æ–¼æ­¤å„²å­˜ç™¾åˆ†æ¯”çš„ç¶²ç«™å°‡è¢«è¦–ç‚ºå·²æ»¿</t>
    <t id="31015">å…è¨±æº¢å‡ºéŠ·å”®çµ¦å…¶ä»–äºº</t>
    <t id="31115">ç•¶å•Ÿç”¨ä¸”ä¸»è¦ç›®æ¨™å·²æ»¿æ™‚ï¼Œå‡ºå”®çµ¦å…¶ä»–æ´¾ç³»ç«™</t>
    <t id="31016">åˆ†é…è‡³é›»å°</t>
    <t id="31116">é©ç”¨æ™‚å°‡èˆ¹èˆ¶æŒ‡å®šç‚ºæœ¬ç«™çš„æŽ¡ç¤¦ä¸‹å±¬</t>
    <t id="31017">å¾…åœ¨å®¶è£¡</t>
    <t id="31117">é™åˆ¶åœ¨å®¶é„‰åœ°å€æŽ¡ç¤¦/éŠ·å”®ï¼Œæº¢æµå¾Œå‚™é‹ä½œé™¤å¤–</t>
    <t id="31018">è‡ªå‹•éƒ¨ç½²è³‡æºæŽ¢æ¸¬å™¨</t>
    <t id="31118">è‡ªå‹•éƒ¨ç½²è¼‰å…¥çš„è³‡æºæŽ¢é‡ä¸¦å°‡æŽ¢é‡åŒ…å«åœ¨ç¶­è­·è£œè²¨ä¸­</t>
    <t id="31019">æœ€å¤§èšé›†è·é›¢</t>
    <t id="31119">èšé›†çš„æœ€å¤§é–€è·é›¢ï¼ˆ0ä½¿ç”¨é£›è¡Œå“¡/æŒ‡æ®å®˜æŠ€èƒ½ä¸Šé™ï¼‰</t>
    <t id="31020">æœ€å¤§è³£å‡ºè·é›¢</t>
    <t id="31120">å‡ºå”®çš„æœ€å¤§é–€è·é›¢ï¼ˆ0 ä½¿ç”¨é£›è¡Œå“¡/æŒ‡æ®å®˜æŠ€èƒ½ä¸Šé™ï¼‰</t>
    <t id="31021">è»ŠéšŠå¹³è¡¡</t>
    <t id="31121">å¯¦ç¾ç¢ºå®šæ€§æ„åœ–å”èª¿ä»¥æ¸›å°‘ç«™é»žæº¢å‡º</t>
    <t id="31022">éœ€æ±‚è¤‡æŸ¥é–“éš”</t>
    <t id="31122">ç¤¦å·¥éœ€æ±‚/é–‹é—œè©•ä¼°é‹ä½œçš„é »çŽ‡</t>
    <t id="31023">é—œéµéœ€æ±‚å¢žé‡</t>
    <t id="31123">åˆ‡æ›æ´»èºæŒ–ç¤¦è»Ÿé«”æ‰€éœ€çš„æœ€ä½Žç·Šæ€¥ç¨‹åº¦å¢žé‡</t>
    <t id="31024">æœ€å°åˆ‡æ›å†·å»æ™‚é–“</t>
    <t id="31124">è©²èˆ¹å…©æ¬¡è²¨ç‰©åˆ‡æ›ä¹‹é–“çš„æœ€çŸ­æ™‚é–“</t>
    <t id="31025">æœ€ä½Žè²¨ç‰©æ‰¿è«¾ç™¾åˆ†æ¯”</t>
    <t id="31125">å¦‚æžœè²¨ç‰©è£è¼‰é‡é«˜æ–¼æ­¤å€¼ï¼Œèˆ¹æ–¹æ›´é¡˜æ„åœ¨åˆ‡æ›ä¹‹å‰å®Œæˆç•¶å‰äº¤è²¨</t>
    <t id="31026">ç¡¬ç·Šæ€¥ä¸‰è§’æ´²</t>
    <t id="31126">å„˜ç®¡è²¨ç‰©æäº¤é–¾å€¼å…è¨±ç«‹å³åˆ‡æ›çš„ç·Šæ€¥å¢žé‡</t>
    <t id="31027">é€šçŸ¥ç´šåˆ¥</t>
    <t id="31127">é€šçŸ¥ç­‰ç´šï¼š0=å®‰éœã€1=æ­£å¸¸ã€2=è©³ç´°</t>
    <t id="31028">åƒ…é™çŽ©å®¶ç«™</t>
    <t id="31128">å•Ÿç”¨å¾Œï¼Œåªæœ‰çŽ©å®¶æ“æœ‰çš„é›»å°æ‰æœƒè¢«è¦–ç‚ºéœ€æ±‚ç›®æ¨™ã€‚</t>
    <t id="31031">å…ˆæª¢æŸ¥éœ€æ±‚</t>
    <t id="31131">å•Ÿç”¨å¾Œï¼ŒæŽ¡ç¤¦èˆ¹åœ¨æŽ¡ç¤¦å‰æœƒæª¢æŸ¥å¤ªç©ºç«™éœ€æ±‚ä¸¦æ“šæ­¤ç¢ºå®šè³‡æºå„ªå…ˆé †åºã€‚åœç”¨å¾Œï¼Œä¸æª¢æŸ¥éœ€æ±‚ï¼Œç›´æŽ¥å¾žè³‡æºç±ƒæŽ¡ç¤¦ä¸¦å›¤ç©è‡³æœ‰è²·å®¶ï¼ˆå»ºè­°ç”¨æ–¼å–®ä¸€è³‡æºè‰¦éšŠï¼‰ã€‚</t>
    <t id="31032">å¯¦é«”å„²å­˜ä¸­æ­¢ %</t>
    <t id="31132">é©ç”¨ç­‰ç´š6ä»¥ä¸Šé§•é§›å“¡ï¼šç•¶å¤ªç©ºç«™å¯¦é«”åº«å­˜åŠ ä¸Šç›¸é—œæŽ¡ç¤¦èˆ¹åœ¨é€”è²¨ç‰©å°‡è¶…éŽç›®å‰å¯¦é«”åº«å­˜æ­¤ç™¾åˆ†æ¯”æ™‚ï¼Œåœæ­¢é–‹æŽ¡ç•¶å‰è³‡æºã€‚ä½¿ç”¨å¯¦éš›è²¨ç‰©æ•¸é‡ï¼Œèˆ‡æº¢ä½é–¾å€¼ç„¡é—œã€‚0ç‚ºåœç”¨ã€‚</t>
    <t id="32002">GalaxyTrader MK4 Supply</t>
    <t id="32102">ä½¿ç”¨ GT å¿«å–/å³æ™‚æœå°‹ç®¡é“çš„çŽ©å®¶ç«™ä¾›æ‡‰äº¤æ˜“è€…</t>
    <t id="32010">è¦†è“‹è·é›¢</t>
    <t id="32110">ç›®çš„åœ°éœ€æ±‚æœå°‹è·é›¢å®¶ä¸­æœ€å¤§çš„ç™»æ©Ÿå£è·é›¢</t>
    <t id="32011">è³¼è²·è·é›¢</t>
    <t id="32111">ä¾›æ‡‰å•†æœå°‹æ™‚è·å®¶çš„æœ€å¤§é–€è·</t>
    <t id="32012">åªç‚ºå®¶åº­æœå‹™</t>
    <t id="32112">å•Ÿç”¨å¾Œï¼Œåƒ…æ»¿è¶³ä¸»ç«™éœ€æ±‚</t>
    <t id="32013">åƒ…å»ºé€ ç«™</t>
    <t id="32113">å•Ÿç”¨å¾Œï¼Œåƒ…æ»¿è¶³å»ºç½®å„²å­˜éœ€æ±‚</t>
    <t id="32014">å¾žçŽ©å®¶è³¼è²·</t>
    <t id="32114">å…è¨±å¾žçŽ©å®¶æ“æœ‰çš„ä¾›æ‡‰å•†æŽ¡è³¼å•†å“</t>
    <t id="32015">å¾žæ´¾ç³»è³¼è²·</t>
    <t id="32115">å…è¨±å¾žéžçŽ©å®¶æ´¾ç³»ä¾›æ‡‰å•†æŽ¡è³¼å•†å“</t>
    <t id="32016">å…è¨±è³‡æº</t>
    <t id="32116">å°‡è³‡æºå•†å“ç´å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="32017">å…è¨±ä¸­é–“é«”</t>
    <t id="32117">å°‡ä¸­ä»‹è»Ÿé«”ç´å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="32018">å…è¨±ç”¢å“</t>
    <t id="32118">å°‡ç”¢å“ç´å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="32019">å…è¨±è²¿æ˜“è»Ÿé«”</t>
    <t id="32119">å°‡è²¿æ˜“å•†å“ç´å…¥éœ€æ±‚åŒ¹é…</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">å…·æœ‰å­˜å„²é–¾å€¼ç®¡ç†çš„å€‰åº«åˆ†é…</t>
    <t id="20010">æºç«™</t>
    <t id="20011">ç›®çš„åœ°ç«™</t>
    <t id="20012">æœ€å°‘å„²å­˜ç™¾åˆ†æ¯”</t>
    <t id="20013">éœæ…‹å„²å­˜%</t>
    <t id="20014">æœ€å¤§å„²å­˜ç™¾åˆ†æ¯”</t>
    <t id="20015">æ½”å…·éŽæ¿¾å™¨</t>
    <t id="20016">é›™å‘æ¨¡å¼</t>
    <t id="20017">ä¸»ç«™ï¼ˆå¯é¸ï¼‰</t>
    <t id="20018">æœ€å¤§è·é›¢</t>
    <t id="20032">ä¸»å€åŸŸï¼ˆå¯é¸ï¼‰</t>
    <t id="20019">å¾ªç’°ç­‰å¾…æ™‚é–“</t>
    <t id="20030">å…è¨±ä½ŽéŸ³é‡</t>
    <t id="20031">ä½Žæˆäº¤é‡ä¸‹é™ç™¾åˆ†æ¯”</t>
    <t id="20110">åˆ†ç™¼å•†å“çš„ä¾†æºç«™åˆ—è¡¨</t>
    <t id="20111">é…é€è²¨ç‰©çš„ç›®çš„åœ°ç«™/å€‰åº«åˆ—è¡¨</t>
    <t id="20112">ç›®çš„åœ°ç·Šæ€¥é–¾å€¼ï¼šä½Žæ–¼æ­¤å„²å­˜ç™¾åˆ†æ¯”çš„ç«™é»žæŽ¥æ”¶å„ªå…ˆäº¤ä»˜</t>
    <t id="20113">ä¾†æºæœ€ä½Žé–¾å€¼ï¼šä¾†æºå¿…é ˆæœ‰è¶…éŽæ­¤ç™¾åˆ†æ¯”æ‰èƒ½åˆ†ç™¼</t>
    <t id="20114">ä¾†æºæº¢å‡ºé–¾å€¼ï¼šé«˜æ–¼æ­¤ç™¾åˆ†æ¯”ä¾†æºç”šè‡³æœƒåˆ†ç™¼åˆ°éžç·Šæ€¥ç›®çš„åœ°</t>
    <t id="20115">å¯é¸é…æ½”å…·éŽæ¿¾å™¨ï¼›ç•™ç©ºä»¥å¾žæºé ­åˆ†ç™¼æ‰€æœ‰å•†å“</t>
    <t id="20116">ç•¶ç›®çš„åœ°æœ‰å¤šé¤˜çš„æ™‚ï¼Œå•Ÿç”¨å¾žç›®çš„åœ°è¿”å›žæºåœ°çš„å›žç¨‹æ”¶é›†</t>
    <t id="20117">å¯é¸çš„åˆ†é…ä¸»ç«™ã€‚å¦‚æžœç‚ºç©ºï¼Œèˆ¹èˆ¶å°‡ä¿æŒæœªåˆ†é…çµ¦ç«™é»žçš„ç‹€æ…‹ã€‚</t>
    <t id="20118">æºé ­èˆ‡ç›®çš„åœ°ä¹‹é–“çš„æœ€å¤§é–€è·é›¢ï¼ˆ0 =â€‹â€‹ ç„¡é™åˆ¶ï¼‰</t>
    <t id="20132">æœªè¨­å®šä¸»ç«™æ™‚ï¼Œç”¨æ–¼é–’ç½®åœæ³Šçš„å¯é¸ä¸»å€åŸŸã€‚</t>
    <t id="20119">åˆ†ç™¼é€±æœŸä¹‹é–“çš„ç­‰å¾…æ™‚é–“</t>
    <t id="20130">å…è¨±è¼ƒå°çš„ç·Šæ€¥æ„ŸçŸ¥äº¤ä»˜å¡Šä½Žæ–¼æ­£å¸¸çš„æœ€ä½Žè²¨ç‰©å¡«å……é‡ã€‚</t>
    <t id="20131">å•Ÿç”¨ä½Žå®¹é‡æ¨¡å¼æ™‚ä½¿ç”¨çš„æœ€å°è²¨ç‰©å¡«å……ç™¾åˆ†æ¯”ã€‚</t>
    <t id="20200">å°‡ %1 %2 å¾ž %3 åˆ†é…åˆ° %4</t>
    <t id="20201">Return trip: collecting %1 %2 from %3 to %4</t>
    <t id="20202">ç„¡éœ€é…é€ï¼æ‰€æœ‰ç›®çš„åœ°å‡æœ‰å……è¶³ä¾›æ‡‰</t>
    <t id="20203">æ‰€æœ‰ä¾†æºç«™ç„¡æ•ˆ - é…é€å¾…å‘½</t>
    <t id="20204">æ‰€æœ‰ç›®çš„åœ°ç«™ç„¡æ•ˆ - é…é€å¾…å‘½</t>
    <t id="20205">ä¾†æºç«™ %1 è¢«æ‘§æ¯€ - å·²å¾žé…é€è¨‚å–®ä¸­ç§»é™¤</t>
    <t id="20206">ç›®çš„åœ°ç«™ %1 è¢«æ‘§æ¯€ - å·²å¾žé…é€è¨‚å–®ä¸­ç§»é™¤</t>
    <t id="20500">GalaxyTrader MK2 - å…¨åŸŸè¨­ç½®</t>
    <t id="20501">MK2 åˆ†ç™¼é è¨­å€¼</t>
    <t id="20510">é è¨­æœ€å°å„²å­˜ç™¾åˆ†æ¯”</t>
    <t id="20511">é è¨­éœæ…‹å„²å­˜ç™¾åˆ†æ¯”</t>
    <t id="20512">é è¨­æœ€å¤§å„²å­˜ç™¾åˆ†æ¯”</t>
    <t id="20513">é è¨­é€±æœŸç­‰å¾…ï¼ˆç§’ï¼‰</t>
    <t id="20514">æœ€ä½Žè²¨ç‰©è£è¼‰ç™¾åˆ†æ¯”</t>
    <t id="20520">é€šçŸ¥è©³ç´°ç¨‹åº¦</t>
    <t id="20521">åµéŒ¯ç­‰ç´š</t>
    <t id="10006">å›žå®¶</t>
    <t id="10007">GalaxyTrader MK4-2 ä¾›çµ¦</t>
    <t id="10106">åœé åœ¨ä¸»ç«™ä¸¦ç•™åœ¨é‚£è£¡ç›´åˆ°äº¤æ˜“æ¢å¾©</t>
    <t id="10107">å¸¶äº¤ä»˜ç›®æ¨™å„ªå…ˆé †åºæ»‘æ¡¿çš„çŽ©å®¶ä¾›çµ¦å‘½ä»¤</t>
    <t id="30026">é€±æœŸä¹‹é–“è¿”å›žå®¶</t>
    <t id="30028">å¿½ç•¥å ±åƒ¹è¨­å®š</t>
    <t id="30029">è²·æ–¹åƒ¹æ ¼ç¯„åœ</t>
    <t id="30027">æœ€å°ç”¢å“å„²å­˜ %</t>
    <t id="30126">å•Ÿç”¨å¾Œï¼Œè¿”å›žä¸»ç«™ä¸¦åœ¨äº¤æ˜“é€±æœŸä¹‹é–“åœé ã€‚åœç”¨å¾Œï¼Œå¾žç›®å‰ä½ç½®ç¹¼çºŒæœå°‹ï¼ˆèˆŠè¡Œç‚ºï¼‰</t>
    <t id="30128">å…è¨±åœ¨ç„¡è»Šç«™è²·è³£å ±åƒ¹çš„æƒ…æ³ä¸‹é€²è¡Œå…§éƒ¨å€‰å„²è½‰ç§»ã€‚ä½¿ç”¨è²¨ç‰©äº¤æ›é€²è¡Œç·©è¡å€çš„å–è²¨èˆ‡äº¤ä»˜ã€‚æœªå•Ÿç”¨ã€Œå¿½ç•¥è²¿æ˜“è¦å‰‡ã€æ™‚ï¼Œè»Šç«™è²¿æ˜“è¦å‰‡ä»ç„¶ç”Ÿæ•ˆã€‚</t>
    <t id="30129">å‡ºå”®è»Šç«™ç”¢å“æ™‚ NPC è²·æ–¹çš„æœ€ä½Žç›¸å°åƒ¹æ ¼ã€‚å‘½ä»¤æ»‘å¡Š 0-200ï¼ˆ100 = å¹³å‡ï¼Œ0 = -100%ï¼Œ200 = +100%ï¼‰å°æ‡‰ -1.0 è‡³ +1.0ã€‚è¶Šé«˜å‰‡åƒ…æŽ¥å—é«˜åƒ¹è²·æ–¹ï¼Œè¶Šä½Žå‰‡è²·æ–¹é¸æ“‡æ›´å¤šã€‚è£œçµ¦è¡Œç¨‹å°ä¾›æ‡‰å•†åƒ¹æ ¼ä¸Šé™ä½¿ç”¨åè½‰å€¼ã€‚</t>
    <t id="30127">éŠ·å”®ç”¢å“æˆ–è²¿æ˜“å“ä¹‹å‰æ‰€éœ€çš„æœ€ä½Žç«™é»žå„²å­˜å¡«å……ç™¾åˆ†æ¯”ï¼ˆç›¸å°æ–¼æ¯ç¨®è²¨ç‰©è¨­å®šçš„æœ€å¤§å€¼ï¼‰ã€‚ä½Žæ–¼æ­¤é–¾å€¼çš„è²¨ç‰©å°‡è¢«è·³éŽã€‚0 = ç„¡æœ€ä½Žè¦æ±‚ã€‚</t>
    <t id="3107">æ­£åœ¨æŽ’éšŠå¤šé‡äº¤æ˜“ï¼š%1ã€‚æˆ‘æ‡‰è©²è³ºå– %2 åˆ©æ½¤ã€‚</t>
    <t id="3108">å¾ž %3 å‡ºå”® %1 %2ï¼Œåƒ¹æ ¼ç‚º %4ã€‚æˆ‘æ‡‰è©²è³ºå– %5 åˆ©æ½¤ã€‚</t>
    <t id="3110">æ­£åœ¨æŽ’éšŠä¾›æ‡‰ %1 %2ã€‚ä»¥ %3 å¾ž %4 æŽ¡è³¼ï¼Œé‹é€è‡³ %5ã€‚å®¢æˆ¶è²·å…¥ä¸Šé™ %6 - æ¯å–®ä½ä½Žæ–¼ä¸Šé™ %7ï¼ˆåˆè¨ˆ %8ï¼‰ã€‚</t>
    <t id="3111">æ­£åœ¨æŽ’éšŠä¾›æ‡‰ %1 %2ï¼Œå¾ž %3 è‡³ %4ã€‚</t>
    <t id="3112">ä¾›æ‡‰æŽ’éšŠä¸­ï¼ˆ%1 æ®µï¼‰ï¼š%2ã€‚åˆè¨ˆä½Žæ–¼å®¢æˆ¶è²·å…¥ä¸Šé™ %3ã€‚</t>
    <t id="3113">å¤ªç©ºç«™è²¿æ˜“å•†ï¼šæ­£åœ¨æŽ’éšŠå‡ºå£å¤šé‡äº¤æ˜“ï¼š%1ã€‚é æœŸåˆ©æ½¤ %2ã€‚</t>
    <t id="31029">åµæ¸¬åº«å­˜ç›®æ¨™</t>
    <t id="31030">è³¼è²·çš„æŽ¡ç¤¦ç„¡äººæ©Ÿæ•¸é‡</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Minerï¼šæ²’æœ‰å¯é–‹æŽ¡çš„è²¨ç‰©ã€‚è‰¦èˆ¹ %1 [%2]ï¼Œè‰¦éšŠï¼š%3</t>
    <t id="31201">Galaxy-Minerï¼šè«‹è¨­å®šä¸»ç«™æˆ–ä¸»ä½ç½®ã€‚</t>
    <t id="31130">ç•¶ç¤¦èˆ¹ç”¨å®Œæ‰€éœ€é¡žåž‹ï¼ˆå›ºé«”/ç¤¦çŸ³æˆ–æ¶²é«”/æ°£é«”ï¼‰æ™‚è³¼è²·çš„æŽ¡é›†ï¼ˆæŽ¡ç¤¦ï¼‰ç„¡äººæ©Ÿæ•¸é‡ã€‚åƒ…ç•¶èˆ¹ä¸Šæ²’æœ‰è©²é¡žåž‹çš„æŽ¡é›†ç„¡äººæ©Ÿæ™‚ï¼ˆæ•¸é‡=0ï¼‰æ‰æœƒè§¸ç™¼è³¼è²·â€”â€”ä»æ“æœ‰è‡³å°‘ä¸€å€‹çš„ç¤¦èˆ¹æ°¸é ä¸æœƒè¢«è£œå……æˆ–é‡æ–°è³¼è²·ï¼Œç¾æœ‰ç„¡äººæ©Ÿå°‡è¢«ä¿ç•™ã€‚å—èˆ¹èˆ¶å–®ä½æ©Ÿåº«å®¹é‡é™åˆ¶ã€‚è¨­ç‚º 0 å¯åœç”¨æŽ¡é›†ç„¡äººæ©Ÿçš„è‡ªå‹•è³¼è²·ä¸¦æ‰‹å‹•ç®¡ç†ç„¡äººæ©Ÿã€‚é è¨­å€¼ 5 æ˜¯ç”¨æ–¼æ­£å¸¸æŽ¡ç¤¦é€Ÿåº¦çš„å®Œæ•´ç„¡äººæ©Ÿå¥—è£ã€‚</t>
    <t id="31129">ç¤¦å·¥æ¯æ¬¡è£œè²¨è¡Œç¨‹è³¼è²·çš„è³‡æºæŽ¢é‡æ•¸é‡ã€‚åªæœ‰ç•¶èˆ¹èˆ¶ç”¨å®ŒæŽ¢æ¸¬å™¨ï¼ˆè¨ˆæ•¸ = 0ï¼‰æ™‚æ‰æœƒè§¸ç™¼è³¼è²·ï¼Œè€Œä¸æ˜¯åœ¨æ¯æ¬¡éƒ¨ç½²æ™‚è§¸ç™¼ - é€™æ¨£ç¤¦å·¥å°±æœƒåœ¨ä¾›æ‡‰é‹è¡Œä¹‹é–“é‹è¡Œå…¶å…¨éƒ¨æŽ¢æ¸¬å™¨è² è¼‰ï¼Œè€Œä¸æ˜¯åœ¨æ¯æ¬¡éƒ¨ç½²å¾Œç¹žé“ã€‚å—èˆ¹èˆ¶ç¸½å¯éƒ¨ç½²èƒ½åŠ›é™åˆ¶ï¼ˆèˆ‡è¡›æ˜Ÿ/æ°´é›·/ç­‰å…±äº«ï¼‰ï¼›å¤§æ–¼å¯ç”¨å¯éƒ¨ç½²ç©ºé–“çš„æ»‘å¡Šå€¼æœƒå„ªé›…åœ°é™ç´šç‚ºâ€œå¡«å……é©åˆçš„ç©ºé–“â€ã€‚åƒ…åœ¨å•Ÿç”¨è‡ªå‹•éƒ¨ç½²è³‡æºæŽ¢é‡æ™‚ç”Ÿæ•ˆ - ç›¸åŒçš„è¨­ç½®é‚„æœƒé©…å‹•æŽ¡ç¤¦éƒ¨é–€ä¸­çš„æ©Ÿæœƒæ€§æŽ¢é‡éƒ¨ç½²å’ŒéŽæ™‚æŽ¢é‡çš„æ”¶é›†ï¼ˆæ²’æœ‰ç±ƒå­ç›¸é—œè³‡æºçš„éƒ¨é–€ä¸­çš„æŽ¢é‡ï¼‰ã€‚</t>
    <t id="3226">æŒ‡æ®å®˜%1ï¼Œ\n\næˆ‘å·²åœé åœ¨%2ï¼Œäº¤æ˜“å­¸é™¢è¨»å†Šå“¡å·²ç¢ºèªæˆ‘å·²è¨»å†Šã€Œ%3ã€è¨ˆç•«ã€‚è»ŠéšŠå¸³æˆ¶å·²æ‰£é™¤ %4 Cr çš„èª²ç¨‹å­¸è²»ï¼Œæˆ‘ä¸æœƒè¼•è¦–é€™ç­†æŠ•è³‡ã€‚ \n\né€™ä¸æ˜¯ä¾‹è¡Œèªè­‰ã€‚å­¸é™¢çš„å°Žå¸«éƒ½æ˜¯ç¶“é©—è±å¯Œçš„å•†äººå’Œè²¡åœ˜è«‡åˆ¤ä»£è¡¨ï¼Œé€™è£¡çš„èª²ç¨‹é æ¯”æ¨™æº–çš„é€²éšŽè€ƒè©¦è¦æ±‚æ›´é«˜ã€‚åœ¨æŽ¥ä¸‹ä¾†çš„ %5 åˆ†é˜å…§ï¼Œæˆ‘å°‡æŽ¥å—é«˜ç´šäº¤æ˜“å”è­°ã€å£“åŠ›ä¸‹çš„å¸‚å ´åˆ†æžä»¥åŠå¸«å¾’å€åˆ†çš„è«‡åˆ¤ç­–ç•¥çš„å¯†é›†æŒ‡å°Žã€‚ \n\nç•¶æœŸæœ«è€ƒè©¦å®Œæˆä¸¦ä¸”æˆ‘è„«é›¢ç¢¼é ­æ™‚ï¼Œæˆ‘å°‡æ“æœ‰â€œ%3â€çš„ç¨±è™Ÿï¼Œä¸¦å°‡æˆ‘æ‰€å­¸åˆ°çš„ä¸€åˆ‡å¸¶å›žæˆ‘å€‘çš„äº¤æ˜“æ“ä½œä¸­ã€‚æˆ‘ä¸æœƒæµªè²»é€™å€‹æ©Ÿæœƒçš„ä»»ä½•ä¸€å€‹ç©åˆ†ã€‚ \n\nå¸¶è‘—æ„Ÿæ¿€å’Œæ±ºå¿ƒï¼Œ\n%6\nç™»ä¸Š %7</t>
    <t id="9924">äº¤æ˜“å­¸é™¢èª²ç¨‹ä¸­æ­¢ï¼šé£›è¡Œå“¡ %1 ç„¡æ³•è² æ“”å­¸é™¢ç¢¼é ­çš„ %2 Cr è²»ç”¨ï¼ˆæœ‰ %3 Crï¼‰ã€‚èª²ç¨‹å–æ¶ˆï¼Œè©¦è¾¦æ¢å¾©äº¤æ˜“ã€‚</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="90">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Tak ve Bekle (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">Final SÄ±navÄ± (GalaxyTrader MK3)</t>
    <t id="10004">Pilot DeÄŸiÅŸim BuluÅŸmasÄ±</t>
    <t id="10005">[KULLANIMDAN KALDIRILDI] GalaxyTrader MK4 Temini (Eski)</t>
    <t id="10101">Ä°stasyona yanaÅŸÄ±n ve belirtilen sÃ¼re kadar bekleyin</t>
    <t id="10102">Beceri ilerlemesi ile otonom ticaret</t>
    <t id="10103">EÄŸitim tesisinde pilot sertifikasyonu iÃ§in final sÄ±navÄ±na girin</t>
    <t id="10104">Pilot deÄŸiÅŸimi iÃ§in buluÅŸma istasyonuna yanaÅŸÄ±n</t>
    <t id="10105">Ã–nbellek ve canlÄ± aramayÄ± kullanan oyuncu istasyonlarÄ± iÃ§in tedarik odaklÄ± ticaret (Eski)</t>
    <t id="10201">%s adlÄ± kiÅŸiden %s satÄ±n alÄ±n</t>
    <t id="10202">%s Ã¼rÃ¼nÃ¼nÃ¼ %s Ã¼rÃ¼nÃ¼ne sat</t>
    <t id="10203">%s ile iÅŸlem yapÄ±n</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">XP ilerleme ve filo koordinasyonuna sahip geliÅŸmiÅŸ ticaret sistemi</t>
    <t id="1002">Ev ÃœssÃ¼</t>
    <t id="1003">Ã–n ayarlarÄ± kullan</t>
    <t id="1004">TÃ¼m mallarÄ±n ticaretini yapÄ±n</t>
    <t id="1005">Yasal mallarÄ±n ticareti</t>
    <t id="1006">YasadÄ±ÅŸÄ± mallarÄ±n ticaretini yapÄ±n</t>
    <t id="1007">XP ilerlemeyi etkinleÅŸtir</t>
    <t id="1008">Filo koordinasyonunu etkinleÅŸtirin</t>
    <t id="1009">Pazar analizini etkinleÅŸtirin</t>
    <t id="1010">BÃ¶lge yÃ¶netimini etkinleÅŸtir</t>
    <t id="1011">YasadÄ±ÅŸÄ± Mallara Ä°zin Ver</t>
    <t id="1012">Seyir Defteri GiriÅŸleri</t>
    <t id="1013">Risk ToleransÄ±</t>
    <t id="1014">Oyuncu Ä°stasyonlarÄ±na Ã–ncelik Verin</t>
    <t id="1015">Otomatik ÃœrÃ¼nler</t>
    <t id="1016">Mesafe CezasÄ± %</t>
    <t id="1017">Bildirim DÃ¼zeyi</t>
    <t id="1018">Filo Koordinasyonu</t>
    <t id="1019">Kargo Doldurma Hedefi %</t>
    <t id="1050">Piyasa GÃ¼ncelleme SÄ±klÄ±ÄŸÄ±</t>
    <t id="1051">Ticaret DeÄŸerlendirme GÃ¼nlÃ¼ÄŸÃ¼</t>
    <t id="1052">SektÃ¶r Beyaz Listesi</t>
    <t id="1054">TaÅŸÄ±yÄ±cÄ±yÄ±/YardÄ±mcÄ± Gemileri Yoksay</t>
    <t id="1056">Derleme DepolamayÄ± Yoksay</t>
    <t id="1058">Ticaret KurallarÄ±nÄ± Yoksay</t>
    <t id="1060">MK1-SaÄŸlanan Ä°stasyonlarÄ± Yoksay</t>
    <t id="1063">GeliÅŸtirilme aÅŸamasÄ±nda</t>
    <t id="1064">Ã–ncelikli mallar</t>
    <t id="1065">Ã–ncelik puanÄ± %</t>
    <t id="1066">Ticaret puanlamasÄ±nda tercih edilen mallar. PuanlarÄ± Ã–ncelik PuanÄ± %'si ile Ã§arpÄ±lÄ±r.</t>
    <t id="1067">Score multiplier for Priority Wares: 100%=normal, 150%=+50%%, 200%=2x, 300%=3x. Applied last.</t>
    <t id="1068">â”€â”€ Ã–ncelikli mal filtresi â”€â”€</t>
    <t id="1069">Mallar (manuel)</t>
    <t id="1070">YasadÄ±ÅŸÄ± Rota Filtresi</t>
    <t id="1072">YalnÄ±zca Eve Servis YapÄ±n</t>
    <t id="1073">Oyuncu TedarikÃ§i Ã–nceliÄŸi</t>
    <t id="1074">Fraksiyon TedarikÃ§i Ã–nceliÄŸi</t>
    <t id="1075">Derleme DepolamayÄ± Dahil Et</t>
    <t id="1076">KaynaklarÄ± Ekle</t>
    <t id="1077">Ara Maddeleri Dahil Et</t>
    <t id="1078">Ticari ÃœrÃ¼nleri Dahil Et</t>
    <t id="1080">DÃ¶ngÃ¼ BaÅŸÄ±na Maksimum Ä°ÅŸlem</t>
    <t id="1081">Geri Ä°zleme ToleransÄ±</t>
    <t id="1082">Min. KullanÄ±lan Kargo %'si</t>
    <t id="1083">Oyuncu SatÄ±n Alma DeÄŸiÅŸtiricisi %</t>
    <t id="1085">Ana Ä°stasyona Ata</t>
    <t id="1086">Kapsama Mesafesi</t>
    <t id="1088">Talep kapsamÄ± iÃ§in evden maksimum atlama mesafesi</t>
    <t id="1090">Ticari yazÄ±lÄ±m sÄ±nÄ±fÄ± Ã¼rÃ¼nleri talep/arz eÅŸleÅŸtirmesine dahil edin</t>
    <t id="1091">YalnÄ±zca puanlama hesaplamalarÄ±nda oyuncuya ait tedarikÃ§i fiyatlandÄ±rmasÄ±na uygulanan deÄŸiÅŸtirici</t>
    <t id="1092">Oyuncu FiyatlandÄ±rmasÄ±nÄ± Yoksay</t>
    <t id="1093">EtkinleÅŸtirildiÄŸinde: belirlenen satÄ±ÅŸ fiyatlarÄ±ndan baÄŸÄ±msÄ±z olarak her zaman oyuncularÄ±n sahip olduÄŸu istasyonlardan satÄ±n alÄ±n ve yalnÄ±zca NPC gruplarÄ±na satÄ±ÅŸ yapÄ±n. Kendi istasyonlarÄ±nÄ±zdaki fazla stoÄŸu tasfiye etmek iÃ§in kullanÄ±ÅŸlÄ±dÄ±r.</t>
    <t id="1094">Engellenen Ä°stasyonlar</t>
    <t id="1095">Burada seÃ§ilen istasyonlar MK3 ticaretinden hariÃ§ tutulur. TÃ¼ccar bu istasyonlardan ne alÄ±m yapar ne de satÄ±ÅŸ yapar.</t>
    <t id="1096">BoÅŸta Park Etme</t>
    <t id="1097">EtkinleÅŸtirildiÄŸinde, tekrar tekrar iÅŸ bulamayan gemiler ana istasyonlarÄ±nda veya ana sektÃ¶rlerinde park eder. SektÃ¶r parkÄ± Ã¶nce oyuncu istasyonlarÄ±nÄ±, sonra dost istasyonlarÄ± tercih eder. YanaÅŸma bÄ±rakma sÃ¼resi genel ayarlarda belirlenir (0 = iÅŸ bulunana kadar yanaÅŸmÄ±ÅŸ kalÄ±r).</t>
    <t id="1098">Otomatik Ã¶lÃ§ek</t>
    <t id="1099">EtkinleÅŸtirildiÄŸinde, zorunlu eÄŸitim veya Ticaret Akademisi tamamlandÄ±ktan sonra atlama mesafesi kaydÄ±rÄ±cÄ±larÄ± pilota izin verilen maksimum menzile ayarlanÄ±r. Mesafeleri elle ayarlamak iÃ§in kapatÄ±n.</t>
    <t id="11001">Ä°nÅŸa Deposu Ã–nceliÄŸi</t>
    <t id="11002">Ä°stasyon Ã–nceliÄŸi</t>
    <t id="11003">YardÄ±mcÄ± Gemi Ã–nceliÄŸi</t>
    <t id="11004">TaÅŸÄ±yÄ±cÄ± Ã–nceliÄŸi</t>
    <t id="11005">0 = devre dÄ±ÅŸÄ±. 1-10 = skor Ã§arpanÄ± (10 = en gÃ¼Ã§lÃ¼ aÄŸÄ±rlÄ±k). Nihai skor = tedarik skoru Ã— Ã§arpan.</t>
    <t id="11006">1 = ekstra skor yok (Ã¶ncelikli mal listesi deÄŸiÅŸmez). 2-10 = ticaret malÄ± Ã¶ncelik listesindeyse (Ã§arpanâˆ’1)Ã— temel tedarik skoru ekler. TÃ¼r skorunun Ã¼zerine uygulanÄ±r.</t>
    <t id="11007">Ã–ncelikli mal bonusu</t>
    <t id="11008">%1: TÃ¼m teslimat hedefi Ã¶ncelik kaydÄ±rÄ±cÄ±larÄ± 0 olarak ayarlandÄ± - bu emrin teslimat hedefi yok. Tedarik seferlerine devam etmek iÃ§in en az bir sÄ±nÄ±fÄ± (inÅŸaat deposu, istasyonlar, yardÄ±mcÄ± gemiler veya taÅŸÄ±yÄ±cÄ±lar) etkinleÅŸtirin.</t>
    <t id="7001">[Ä°LERLEMEK]</t>
    <t id="7002">[EÄžÄ°TÄ°M]</t>
    <t id="7008">[GERÄ° Ã‡EKÄ°LMEK]</t>
    <t id="7009">[Ä°ZOLASYON]</t>
    <t id="7003">[TAMÄ°RAT]</t>
    <t id="7004">[Ä°kmal]</t>
    <t id="7005">[BAKIM]</t>
    <t id="7006">[YENÄ° YÃ–NLENDÄ°R]</t>
    <t id="7007">[TEMÄ°ZLÄ°K]</t>
    <t id="1020">TÃ¼ccarÄ±n faaliyet gÃ¶sterdiÄŸi ana sektÃ¶rÃ¼ veya istasyonu seÃ§in</t>
    <t id="1021">Mal satÄ±n alÄ±rken maksimum atlama kapÄ±sÄ± mesafesi (pilot becerisiyle sÄ±nÄ±rlÄ±dÄ±r)</t>
    <t id="1022">Mal satarken maksimum atlama kapÄ±sÄ± mesafesi (pilot becerisiyle sÄ±nÄ±rlÄ±dÄ±r)</t>
    <t id="1023">Kategoriye gÃ¶re uygun Ã¼rÃ¼nlerin otomatik seÃ§imi</t>
    <t id="1024">Belirli ticari mallarÄ±n manuel seÃ§imi</t>
    <t id="1025">KaÃ§ak ve yasadÄ±ÅŸÄ± mallarÄ±n ticaretine izin ver</t>
    <t id="1026">GÃ¼venlik toleransÄ±: 0,0=YalnÄ±zca gÃ¼venli sektÃ¶rler, 1,0=TÃ¼m riskleri kabul et</t>
    <t id="1027">Ticaret deneyimi yoluyla pilot becerilerinizi geliÅŸtirin</t>
    <t id="1028">GerektiÄŸinde pilotlarÄ± otomatik olarak eÄŸitime gÃ¶nderin</t>
    <t id="1029">Ã‡atÄ±ÅŸmalarÄ± Ã¶nlemek iÃ§in birden fazla ticaret gemisini koordine edin</t>
    <t id="1030">ÃœrÃ¼n odaÄŸÄ±: 0=Dengeli, 1=GeliÅŸmiÅŸ, 2=Temel ihtiyaÃ§lar, 3=YasadÄ±ÅŸÄ±, 4=Toplu mallar</t>
    <t id="1031">Ticaret alanÄ±: 0=Dengeli, 1=Ana odak, 2=Serbest dolaÅŸÄ±m</t>
    <t id="1032">Bildirim dÃ¼zeyi: 0=Minimum, 1=Normal, 2=AyrÄ±ntÄ±lÄ± mesajlar</t>
    <t id="1033">SatÄ±ÅŸlara Ã¶ncelik vermeden Ã¶nce kargo kullanÄ±m yÃ¼zdesini hedefleyin</t>
    <t id="1034">Piyasa verileri ve fiyat bilgileri ne sÄ±klÄ±kta gÃ¼ncellenir?</t>
    <t id="1035">Hata ayÄ±klama Ã§Ä±ktÄ± dÃ¼zeyi: 0=Yok, 1=Temel, 2=AyrÄ±ntÄ±lÄ± gÃ¼nlÃ¼k kaydÄ±</t>
    <t id="1036">Filo ile karlÄ± ticaret rotalarÄ±nÄ± paylaÅŸÄ±n (hÄ±zlÄ± eriÅŸim iÃ§in Ã¶nbelleÄŸe alÄ±nÄ±r)</t>
    <t id="1037">Ticareti Ã¶nbelleÄŸe almak ve filoyla paylaÅŸmak iÃ§in gereken minimum kar</t>
    <t id="1038">Ã–nbelleÄŸe alÄ±nmÄ±ÅŸ ticaret rotalarÄ± geÃ§ersiz hale gelmeden Ã¶nce izin verilen maksimum kar dÃ¼ÅŸÃ¼ÅŸÃ¼</t>
    <t id="1039">Ã–nbelleÄŸe alÄ±nmÄ±ÅŸ ticaret rotalarÄ±nÄ±n sÃ¼resi dolmadan ne kadar sÃ¼re geÃ§erli kalÄ±r?</t>
    <t id="1040">Bireysel ticari deÄŸerlendirmelerin ve retlerin ayrÄ±ntÄ±lÄ± gÃ¼nlÃ¼ÄŸe kaydedilmesini etkinleÅŸtirin (Ã§ok ayrÄ±ntÄ±lÄ± olabilir)</t>
    <t id="1041">Ä°ÅŸlem baÅŸÄ±na kayÄ±t defteri giriÅŸlerini ve kapsamlÄ± eÄŸitim mesajlarÄ±nÄ± etkinleÅŸtirin (TaterTrader stili)</t>
    <t id="1053">Bu listedeki sektÃ¶rler kara listelerin dÄ±ÅŸÄ±nda bÄ±rakÄ±lÄ±r (her zaman izin verilir)</t>
    <t id="1055">TaÅŸÄ±yÄ±cÄ±larÄ± ve yardÄ±mcÄ± gemileri ticaretin dÄ±ÅŸÄ±nda tutun</t>
    <t id="1057">Ä°nÅŸa depolama gemilerini ticaretin dÄ±ÅŸÄ±nda bÄ±rak</t>
    <t id="1059">Teklif arama sÄ±rasÄ±nda istasyon ticaret kurallarÄ±nÄ± gÃ¶z ardÄ± et (geliÅŸmiÅŸ; normalde engellenen teklifleri seÃ§ebilir)</t>
    <t id="1061">Tedarik modu atanmÄ±ÅŸ MK1 tÃ¼ccarÄ±n bulunduÄŸu oyuncu istasyonlarÄ±nÄ± atla</t>
    <t id="1062">Boost trade scores for routes involving your own stations (10% score bonus)</t>
    <t id="1071">YasadÄ±ÅŸÄ± Mallara Ä°zin Ver etkinleÅŸtirildiÄŸinde, yalnÄ±zca atlama yolundaki tÃ¼m sektÃ¶rlerde (alÄ±ÅŸ, satÄ±ÅŸ ve ara sektÃ¶rler) yasalsa yasa dÄ±ÅŸÄ± mallarÄ±n ticaretini yapÄ±n.</t>
    <t id="1087">TedarikÃ§i satÄ±n alma aramasÄ± iÃ§in evden maksimum atlama mesafesi</t>
    <t id="1089">Devre dÄ±ÅŸÄ± bÄ±rakÄ±ldÄ±ÄŸÄ±nda gemi, yalnÄ±zca ev modu yerine aciliyet Ã¶nceliÄŸine gÃ¶re kapsama alanÄ±ndaki istasyonlara tedarik saÄŸlayabilir</t>
    <t id="2000">%s, %s XP kazandÄ±!</t>
    <t id="2001">%s seviye atladÄ±! Yeni seviye: %s</t>
    <t id="2002">%s eÄŸitime ihtiyaÃ§ duyuyor! LÃ¼tfen en yakÄ±n tersaneye veya ticaret istasyonuna gÃ¶nderin.</t>
    <t id="2003">%s, %s saatinde eÄŸitime baÅŸladÄ±</t>
    <t id="2004">%s eÄŸitimi tamamladÄ± ve artÄ±k %s seviyesi iÃ§in sertifika aldÄ±!</t>
    <t id="2005">%s eÄŸitim sonrasÄ± Beceri Seviyesi %s'ye ulaÅŸtÄ±! %s'de XP ilerlemesi aÃ§Ä±ldÄ±.</t>
    <t id="2006">%s Beceri Seviyesi %s'ye %s ticareti ile ulaÅŸtÄ±!</t>
    <t id="2007">%s Seviye %s eÄŸitimini tamamladÄ±! %s'de XP ilerlemesi aÃ§Ä±ldÄ±.</t>
    <t id="3000">%s bir takasÄ± tamamladÄ±! KÃ¢r: %s Cr</t>
    <t id="3001">%s piyasa koÅŸullarÄ±nÄ± analiz ediyor...</t>
    <t id="3002">%s karlÄ± bir ticaret yolu buldu!</t>
    <t id="3003">%s iÃ§in karlÄ± ticaret yolu yok</t>
    <t id="3100">%1 %2 kargodan %3 istasyonuna %4 fiyatÄ±na satÄ±lÄ±yor. %5 kar elde etmeliyim.</t>
    <t id="3101">%1 %2 iÃ§in ticari emir sÄ±raya alÄ±nÄ±yor. %3 fiyattan %4 konumundan alÄ±nÄ±yor ve %5 fiyattan %6 konumuna satÄ±lÄ±yor. %7 kar elde etmeliyim.</t>
    <t id="3102">Ä°stasyon TÃ¼ccarÄ±: %1 %2 malzemesini %3 konumundan %5%% seviyesinde %4 konumuna %6%% seviyesinde tedarik ediyor.</t>
    <t id="3103">Ä°stasyon TÃ¼ccarÄ±: %1 %2 Ã¼rÃ¼nÃ¼nÃ¼ %3 konumuna %4 fiyatÄ±na satÄ±yor. Beklenen kÃ¢r %5.</t>
    <t id="3104">%1 %2 iÃ§in iÅŸlem baÅŸarÄ±yla tamamlandÄ±. Toplam kÃ¢r: %3 Kredi.</t>
    <t id="3105">Ticaret yolu Ã¶nbelleÄŸe alÄ±ndÄ±: %1 %2, %3'den %4'e (Kar: %5 Cr)</t>
    <t id="3106">\nBu iÅŸlemden Ã¶nceki toplam tahmini Ã¶mÃ¼r boyu kar: %1 Cr.</t>
    <t id="3120">Pilot Transferi BaÅŸlatÄ±ldÄ±</t>
    <t id="3121">AktarÄ±m protokolÃ¼ onaylandÄ±. %1 (%2) ve %3 (%4), yanaÅŸmak ve komuta koltuklarÄ±nÄ± deÄŸiÅŸtirmek iÃ§in %5 (%6)'ye doÄŸru ilerliyor.</t>
    <t id="3200">Hello Commander %1,\n\nI have gained enough experience to take my certification exam for the title "%2". The examination will take approximately %3 minutes at %4.\n\nThis is an important milestone in my career development. The exam will test my knowledge of advanced trading protocols, market analysis, and fleet coordination procedures.\n\nI'm confident in my abilities and excited to prove myself worthy of this advancement. Wish me luck!\n\nRespectfully,\n%5\nAboard %6</t>
    <t id="3201">Komutan %1,\n\nMÃ¼kemmel haber! Sertifikasyon sÄ±navÄ±mÄ± baÅŸarÄ±yla tamamladÄ±m ve "%2" unvanÄ±nÄ± kazandÄ±m!\n\nSÄ±nav, geliÅŸmiÅŸ ticaret stratejilerini, risk deÄŸerlendirme protokollerini ve filo koordinasyon prosedÃ¼rlerini kapsÄ±yordu. ÃœstÃ¼n bir baÅŸarÄ± ile geÃ§tiÄŸimi bildirmekten memnuniyet duyuyorum.\n\nArtÄ±k daha karmaÅŸÄ±k ticaret operasyonlarÄ±nÄ± yÃ¶netebilecek yeterliliÄŸe sahibim ve filomuzun baÅŸarÄ±sÄ±na daha da fazla katkÄ±da bulunmayÄ± sabÄ±rsÄ±zlÄ±kla bekliyorum. Mesleki geliÅŸimime yatÄ±rÄ±m yaptÄ±ÄŸÄ±nÄ±z iÃ§in teÅŸekkÃ¼r ederim.\n\nYenilenen Ã¶zveriyle,\n%3\nSertifikalÄ± %2\nYerde %4</t>
    <t id="3202">Komutan %1,\n\nSertifika sÄ±navÄ±mÄ±n operasyonel gereklilikler nedeniyle kesintiye uÄŸradÄ±ÄŸÄ±nÄ± Ã¼zÃ¼lerek bildiririm. KoÅŸullar izin verdiÄŸinde yeniden planlama yapmam gerekecek.\n\nBecerilerimi geliÅŸtirmeye kararlÄ±yÄ±m ve sÄ±nav sÃ¼recine devam edebileceÄŸim zaman sizi bilgilendireceÄŸim.\n\nSaygÄ±larÄ±mla,\n%2\nUÃ§akta %3</t>
    <t id="3203">Komutan %1,\n\nÅžu anda sertifika sÄ±navÄ±m iÃ§in %2 yolundayÄ±m. Yolculuk bana Ã§alÄ±ÅŸmalarÄ±mÄ± gÃ¶zden geÃ§irmem ve kariyerimdeki bu Ã¶nemli adÄ±ma zihinsel olarak hazÄ±rlanmam iÃ§in zaman veriyor.\n\nBeklenen varÄ±ÅŸ: %3 dakika\nSÄ±nav sÃ¼resi: %4 dakika\n\nYeteneklerime ve ilerleme fÄ±rsatÄ±na olan gÃ¼veninizi takdir ediyorum.\n\nKararlÄ±lÄ±kla,\n%5\nUÃ§aÄŸa %6</t>
    <t id="3204">Komutan,\n\nSistem kontrolÃ¼m sÄ±rasÄ±nda ambarÄ±mda kargo tespit ettim. Normal ticaret iÅŸlemlerine baÅŸlamadan Ã¶nce bu Ã¼rÃ¼nÃ¼ satmam gerekiyor.\n\nEn iyi alÄ±cÄ±yÄ± bulmak ve bu kargoyu gÃ¼venli bir ÅŸekilde boÅŸaltmak iÃ§in ticari aramamÄ±zÄ± kullanÄ±yorum. Bekletme durumum netleÅŸtiÄŸinde, otomatik ticarete devam edeceÄŸim.\n\nDurum: Optimum satÄ±ÅŸ konumu aranÄ±yor\n\nÃ–zenle,\nYerde %1</t>
    <t id="3205">Komutan,\n\nGÃ¶vde bÃ¼tÃ¼nlÃ¼ÄŸÃ¼m %%1%'ye dÃ¼ÅŸtÃ¼ (eÅŸik: %%2%). %3 Seviye bir pilot olarak, oto tamir hizmetleri talep etme yetkim var.\n\nOnarÄ±m iÅŸi iÃ§in %4 ÅŸehrine gidiyorum. Tahmini maliyet %5 Cr olup, bÃ¼tÃ§emiz dahilindedir.\n\nOnarÄ±mlar tamamlandÄ±ktan sonra, ticari faaliyetlerime tam yapÄ±sal bÃ¼tÃ¼nlÃ¼kle devam edeceÄŸim.\n\nSaygÄ±larÄ±mla,\nGemiye %6</t>
    <t id="3206">Komutan,\n\nACÄ°L MALÄ° UYARI\n\nGÃ¶vde bÃ¼tÃ¼nlÃ¼ÄŸÃ¼m %1%% (eÅŸik: %2%%) seviyesinde kritik, ancak mevcut paramÄ±z (%3 Cr) tam onarÄ±mlar iÃ§in yetersiz (tahmini maliyet: %4 Cr).\n\nDevam ediyorum Mevcut fonlarÄ±mÄ±zÄ± kullanarak KISMÄ° ONARIMLAR iÃ§in %5. Bu ideal bir Ã§Ã¶zÃ¼m deÄŸil, ancak operasyonel kapasiteyi korumak iÃ§in gerekli.\n\nLÃ¼tfen gelecekteki bakÄ±m operasyonlarÄ± iÃ§in ek fon ayÄ±rmayÄ± dÃ¼ÅŸÃ¼nÃ¼n.\n\nEndiÅŸeli ama kararlÄ±,\nYerde %6</t>
    <t id="3207">Komutan,\n\nSeviyem %1 sertifikasÄ±, savunma ekipmanÄ±nÄ±n otomatik olarak ikmal edilmesine izin veriyor. Sistemlerimi kontrol ettikten sonra, karÅŸÄ± Ã¶nlemlerimin ve konuÅŸlandÄ±rÄ±labilir Ã¶ÄŸelerimin Ã¶nerilen eÅŸiklerin altÄ±nda olduÄŸunu belirledim.\n\nSavunma ekipmanÄ±mÄ± yeniden stoklamak iÃ§in %2'e gidiyorum:\nâ€¢ KarÅŸÄ± Ã¶nlemler: Optimum kapasiteye kadar yenileme\nâ€¢ Savunma dronlarÄ±, ticaret dronlarÄ±, lazer kuleleri: Denge profili uygulama\n\nBu ikmal, en iyi ÅŸekilde korunmamÄ± saÄŸlÄ±yor Ticaret verimliliÄŸini korurken uzay tehditlerine karÅŸÄ±.\n\nTikkatli bir ÅŸekilde,\nGemiye %3</t>
    <t id="3212">Komutan,\n\nGÃ¶vde bÃ¼tÃ¼nlÃ¼ÄŸÃ¼m %%1%'ye (eÅŸik: %2%%) dÃ¼ÅŸtÃ¼ ve onarÄ±m servislerine ihtiyacÄ±m var. Ancak, sektÃ¶r seyahat kÄ±sÄ±tlamalarÄ± (kara listedeki rotalar) nedeniyle %3 adresindeki en yakÄ±n tamir istasyonuna ÅŸu anda ulaÅŸÄ±lamÄ±yor.\n\nBu sÄ±nÄ±rlamaya raÄŸmen ticari faaliyetlerime devam edeceÄŸim. GÃ¼venli rotalar tekrar kullanÄ±labilir hale geldiÄŸinde, otomatik olarak onarÄ±m hizmetleri arayacaÄŸÄ±m.\n\nDurumu izleyeceÄŸim ve onarÄ±mlar mÃ¼mkÃ¼n olduÄŸunda sizi bilgilendireceÄŸim.\n\nSaygÄ±larÄ±mla,\nUÃ§akta %4</t>
    <t id="3213">Komutan,\n\nSavunma ekipmanÄ±m ikmal gerektiriyor, ancak %1 adresindeki en yakÄ±n ekipman istasyonuna sektÃ¶r seyahat kÄ±sÄ±tlamalarÄ± (kara listedeki rotalar) nedeniyle ÅŸu anda ulaÅŸÄ±lamÄ±yor.\n\nBu sÄ±nÄ±rlamaya raÄŸmen ticari operasyonlara devam edeceÄŸim. GÃ¼venli rotalar yeniden kullanÄ±labilir hale geldiÄŸinde, otomatik olarak ikmal hizmetlerini arayacaÄŸÄ±m.\n\nDurumu izleyeceÄŸim ve ikmal mÃ¼mkÃ¼n olduÄŸunda sizi bilgilendireceÄŸim.\n\nSaygÄ±larÄ±mla,\nUÃ§akta %2</t>
    <t id="3208">Komutan,\n\n%1 ve Ã§evresindeki sektÃ¶rlerin kapsamlÄ± bir piyasa analizini tamamladÄ±m (%2 sÄ±Ã§ramalar dahilinde, minimum kÃ¢r eÅŸiÄŸi: %3 Cr), ancak ne yazÄ±k ki gereksinimlerimizi karÅŸÄ±layan hiÃ§bir kÃ¢rlÄ± ticaret fÄ±rsatÄ± bulamadÄ±m.\n\nTÄ°CARET ANALÄ°ZÄ° RAPORU:\nDeÄŸerlendirilen toplam fÄ±rsatlar: %4\n\nREDDETME DAÄžILIMI:\n- BaÄŸlantÄ± kÄ±sÄ±tlamalarÄ±: %5 esnaf\n (Ä°stasyon gemi sÄ±nÄ±fÄ±ma izin vermiyor)\n- Yetersiz karlÄ±lÄ±k: %6 esnaf\n (Minimum kar eÅŸiÄŸinin altÄ±nda)\n- Yetersiz hacim: %7 iÅŸlemler\n (SÄ±fÄ±r veya negatif ticaret tutarÄ±)\n- GÃ¼venlik kÄ±sÄ±tlamalarÄ±: %8 iÅŸlemler\n (Kara listeye alÄ±nmÄ±ÅŸ istasyonlar veya tehlikeli sektÃ¶rler)\n\nÃ–NERÄ°LER:\n- KÃ¢r eÅŸiklerini ayarlamayÄ± dÃ¼ÅŸÃ¼nÃ¼n\n- Maksimum ticaret mesafesini geniÅŸletin\n- SektÃ¶r kara listesi ayarlarÄ±nÄ± inceleyin\n- Piyasa koÅŸullarÄ±nÄ±n dÃ¼zelmesini bekleyin iyileÅŸtirme\n\nPiyasayÄ± izlemeye devam edeceÄŸim ve karlÄ± fÄ±rsatlar ortaya Ã§Ä±ktÄ±ÄŸÄ±nda sizi bilgilendireceÄŸim.\n\nBeklemeye hazÄ±rÄ±m,\nHizmetinizdeyiz</t>
    <t id="3209">Komutan,\n\nACÄ°L ROTA UYARISI\n\nTehdit istihbarat sistemim, %1 sektÃ¶rÃ¼nÃ¼n (tehdit seviyesi %2) artÄ±k planladÄ±ÄŸÄ±m ticaret rotamda olduÄŸunu tespit etti. Geminin ve mÃ¼rettebatÄ±n gÃ¼venliÄŸi iÃ§in, mevcut ticaret operasyonunu derhal iptal ediyorum.\n\nALINAN EYLEMLER:\n- TÃ¼m ticari sipariÅŸler iptal edildi\n- GÃ¼venli operasyonlar moduna dÃ¶nÃ¼lÃ¼yor\n- Tehlikeli sektÃ¶rlerden kaÃ§Ä±nan alternatif ticaret rotasÄ± bulacaÄŸÄ±m\n- Kargo elleÃ§leme: Otomatik (gerekirse herhangi bir kargoyu gÃ¼venli yerde satacak)\n\nDinamik kara liste sistemi gelecekte tehdit ortadan kalkana kadar bu sektÃ¶rde ticaret yapar.\n\nGÃ¼venlik benim ilk Ã¶nceliÄŸimdir.\n\nTikkatli bir ÅŸekilde,\nGemiye %3</t>
    <t id="3210">Komutan,\n\nKAÃ‡IÅž YOLU BAÅžLATILDI\n\nÅžu anda kara listedeki %1 sektÃ¶rÃ¼ndeyim ve gÃ¼venli bir ÅŸekilde kaÃ§mamÄ± saÄŸlayacak bir ticaret yolu buldum.\n\nTÄ°CARET ROTA:\nSatÄ±n Al: %2 (SektÃ¶r: %3)\nSat: %4 (SektÃ¶r: %5)\nÃœrÃ¼n: %6 (x%7)\nBeklenen KÃ¢r: %8 Cr\n\nGemi, bu ticareti tamamladÄ±ktan sonra kara listedeki sektÃ¶rden Ã§Ä±kacak.\n\nSaygÄ±larÄ±mla,\nHizmetinizdeyiz</t>
    <t id="3211">Komutan,\n\nÄ°ZOLASYONLU TÄ°CARET MODU\n\nÅžu anda %2 sektÃ¶rÃ¼ndeyim, ancak diÄŸer sektÃ¶rlere giden tÃ¼m yollar kara listedeki merkez sektÃ¶rleri tarafÄ±ndan engelleniyor. Bu, kara liste durumu deÄŸiÅŸene kadar yalnÄ±zca mevcut sektÃ¶rÃ¼mde iÅŸlem yapabileceÄŸim anlamÄ±na gelir.\n\nDURUM:\nMevcut SektÃ¶r: %2\nDurum: Ä°zole edilmiÅŸ (kara listede olmayan ve yollarÄ± engellenen sektÃ¶r)\nTicaret Modu: YalnÄ±zca sektÃ¶r iÃ§i iÅŸlemler\n\nTicaret sistemim, mevcut sektÃ¶r iÃ§i ticarete Ã¶ncelik vermek iÃ§in kar eÅŸiklerini otomatik olarak ayarladÄ± fÄ±rsatlar.\n\nDurumu izlemeye devam edeceÄŸim ve rotalar tekrar kullanÄ±labilir hale gelirse sizi bilgilendireceÄŸim.\n\nSaygÄ±larÄ±mla,\nUÃ§akta %1</t>
    <t id="3218">Komutan,\n\nROTA YOLU DEÄžÄ°ÅžÄ°KLÄ°ÄžÄ° TESPÄ°T EDÄ°LDÄ°\n\n%1 sektÃ¶rÃ¼ne girdikten sonra, navigasyon sistemim %2 (%3) hedefime giden rotanÄ±n deÄŸiÅŸtiÄŸini tespit etti.\n\nYOL ANALÄ°ZÄ°:\n- Normal mesafe: %4 atlamalar\n- Kara listeye duyarlÄ± mesafe: %5\n- Durum: %6\n\nNavigasyon bilgisayarÄ±m, sektÃ¶r seyahat kÄ±sÄ±tlamalarÄ± nedeniyle tercih edilen rotanÄ±n artÄ±k geÃ§erli olmadÄ±ÄŸÄ±nÄ± gÃ¶steriyor. Geminin ve mÃ¼rettebatÄ±n gÃ¼venliÄŸi iÃ§in, mevcut ticaret operasyonunu derhal iptal ediyorum.\n\nALINAN EYLEMLER:\n- TÃ¼m ticari sipariÅŸler iptal edildi\n- GÃ¼venli operasyonlar moduna dÃ¶nÃ¼lÃ¼yor\n- Engellenen sektÃ¶rlerden kaÃ§Ä±nan alternatif ticaret rotasÄ± bulacaÄŸÄ±m\n- Kargo elleÃ§leme: Otomatik (gerekirse herhangi bir kargoyu gÃ¼venli yerde satacak)\n\nNavigasyon sistemim, bÃ¶lgedeki engellenen sektÃ¶rlerden otomatik olarak kaÃ§Ä±nacak gelecekteki rota planlamasÄ±.\n\nGÃ¼venlik benim ilk Ã¶nceliÄŸimdir.\n\nTikkatli bir ÅŸekilde,\nUÃ§akta %7</t>
    <t id="3219">%1 SektÃ¶rÃ¼ temizlendi - TÃ¼m tehditler ortadan kaldÄ±rÄ±ldÄ±</t>
    <t id="3220">Commander,\n\nENEMY SHIP ESCAPED\n\nOur threat intelligence system has lost track of enemy ship %3, which has escaped from blacklisted sector %1.\n\nDETAILS:\n- Escaped Ship: %3\n- Sector Left: %1\n- Destination Sector: %2\n- Status: Tracking lost - ship has left our monitored area\n\nWhile this ship is no longer a threat in sector %1, we have lost visual contact and cannot confirm its current status or intentions in sector %2.\n\nOur tracking systems will continue monitoring sector %1 for remaining threats. If all tracked enemies leave or are eliminated, the sector will be automatically cleared from the blacklist.\n\nWith vigilance,\nThreat Intelligence System</t>
    <t id="3221">Komutan,\n\nDaha uzak mesafelerde (%3 sÄ±Ã§ramaya kadar) karlÄ± ticaret fÄ±rsatlarÄ± bulamadÄ±m Ã§Ã¼nkÃ¼ bu rotalara sektÃ¶r seyahat kÄ±sÄ±tlamalarÄ± (kara listedeki yollar) nedeniyle ÅŸu anda ulaÅŸÄ±lamÄ±yor.\n\nDURUM:\nMevcut SektÃ¶r: %2\nOrijinal Arama AralÄ±ÄŸÄ±: %3 atlamalar\nGeri Arama AramasÄ± AralÄ±k: %4 atlamalar\n\nArtÄ±k aramamÄ± %4 atlamalar iÃ§indeki, rotalarÄ±n eriÅŸilebilir olma olasÄ±lÄ±ÄŸÄ±nÄ±n daha yÃ¼ksek olduÄŸu yakÄ±ndaki sektÃ¶rlere odaklayacaÄŸÄ±m. Bu, fiili kÃ¢rsÄ±zlÄ±k yerine mesafe kÄ±sÄ±tlamalarÄ± nedeniyle daha Ã¶nce filtrelenen kÃ¢rlÄ± iÅŸlemleri bulmama yardÄ±mcÄ± olacaktÄ±r.\n\nYakÄ±ndaki bÃ¶lgede uygun ticaret fÄ±rsatlarÄ± bulduÄŸumda sizi bilgilendireceÄŸim.\n\nSaygÄ±larÄ±mla,\nYerde %1</t>
    <t id="3222">Komutan,\n\nSEKTÃ–R KARA LÄ°STELENDÄ°\n\nTehdit istihbarat sistemimiz %1 sektÃ¶rÃ¼nde dÃ¼ÅŸmanca faaliyet tespit etti ve ticaret operasyonlarÄ±mÄ±zÄ± korumak iÃ§in bu sektÃ¶rÃ¼ otomatik olarak kara listeye aldÄ±.\n\nDÃœÅžMAN GEMÄ°LERÄ°NÄ° TESPÄ°T ETTÄ°:\n%2\n\nALGILANANLAR: %3\n\nGemilerimizin ve mÃ¼rettebatÄ±mÄ±zÄ±n gÃ¼venliÄŸi iÃ§in bu sektÃ¶rdeki tÃ¼m ticaret yollarÄ± engellendi. Tehdit ortadan kaldÄ±rÄ±lÄ±ncaya kadar gemilerimiz otomatik olarak bu sektÃ¶rÃ¼n etrafÄ±ndan dolaÅŸacaktÄ±r.\n\nTakip edilen tÃ¼m dÃ¼ÅŸman gemileri ortadan kaldÄ±rÄ±ldÄ±ÄŸÄ±nda veya bÃ¶lgeyi terk ettiÄŸinde sektÃ¶r kara listeden otomatik olarak temizlenecektir.\n\nTikkatli bir ÅŸekilde,\nTehdit Ä°stihbarat Sistemi</t>
    <t id="3223">Komutan,\n\nSeviye %1 ilerleme sÄ±navÄ±m iÃ§in eriÅŸilebilir bir eÄŸitim istasyonu bulamÄ±yorum. Talimatlara gÃ¶re alÄ±m satÄ±m iÅŸlemlerine devam edeceÄŸim ancak gerekli eÄŸitimi tamamlayana kadar deneyim puanÄ± kazanamayacaÄŸÄ±mÄ± anlÄ±yorum. Bu takas sonrasÄ±nda olasÄ± eÄŸitim fÄ±rsatlarÄ±nÄ± tekrar araÅŸtÄ±racaÄŸÄ±m.\n\nSaygÄ±larÄ±mla,\nUÃ§akta %2</t>
    <t id="3224">EÄŸitim lisans Ã¼creti: %1 Cr</t>
    <t id="3225">Bonus: EÄŸitim sÄ±rasÄ±nda biriken deneyimden %1 ek beceri dÃ¼zeyi%2 kazandÄ±m! Mevcut seviye: %3</t>
    <t id="3214">Sizin iÃ§in Ã§alÄ±ÅŸmak bir onurdur, %1! Ticaret kariyerime emriniz altÄ±nda baÅŸlayacaÄŸÄ±m iÃ§in heyecanlÄ±yÄ±m. Sizlere iyi hizmet etmek ve baÅŸarÄ±nÄ±za katkÄ±da bulunmak iÃ§in elimden geleni yapacaÄŸÄ±m.</t>
    <t id="3215">Bana bu hak edilmiÅŸ tatili verdiÄŸin iÃ§in teÅŸekkÃ¼r ederim %1! Ticaretten uzakta geÃ§irdiÄŸim zamanÄ±n tadÄ±nÄ± Ã§Ä±kardÄ±m ve becerilerim bozulmadan kaldÄ±. Bana ihtiyacÄ±n olduÄŸunda iÅŸe dÃ¶nmeyi sabÄ±rsÄ±zlÄ±kla bekliyorum. O zamana kadar ticaret bilgimi keskin tutacaÄŸÄ±m!</t>
    <t id="3216">Tatilden dÃ¶ndÃ¼m ve tekrar Ã§alÄ±ÅŸmaya hazÄ±rÄ±m, %1! Ticaret becerilerim hala keskin ve size %2 Ã¼zerinden hizmet vermeye devam etmek iÃ§in sabÄ±rsÄ±zlanÄ±yorum. Hak ettiÄŸiniz dinlenme iÃ§in teÅŸekkÃ¼r ederiz!</t>
    <t id="3217">%1, %2 adresine transferim iÃ§in teÅŸekkÃ¼r ederim! Bu yeni gÃ¶revden onur duyuyorum ve yeni gemime mÃ¼kemmel bir ÅŸekilde bakacaÄŸÄ±m. Ticaret deneyimim ve becerilerim deÄŸiÅŸmedi ve size hizmet etmeye devam etmeye hazÄ±rÄ±m.</t>
    <t id="3227">GÃ¶vde kaybedildi, itibar alÄ±m bekliyor</t>
    <t id="3228">Komutan %1,\n\n%3'ten %2 rapor ediyor. Gemim patladÄ±. Ben patlamadÄ±m. ArtÄ±k filonun en pahalÄ± yÃ¼zen yÃ¼kÃ¼yÃ¼m.\n\nHarita iÅŸareti eklendi. LÃ¼tfen acele edin - fatura ortasÄ±ndaydÄ±m.\n\nProfesyonelce sÃ¼zÃ¼lÃ¼yorum,\n%2</t>
    <t id="3229">Pilot kurtarÄ±ldÄ± - Oksijen baÄŸÄ±mlÄ±lÄ±ÄŸÄ± tedavi edildi</t>
    <t id="3230">Komutan %1,\n\nFilo gÃ¼ncellemesi: %2, %3 (%4) tarafÄ±ndan toplandÄ± ve uzatÄ±lmÄ±ÅŸ EVA eÄŸitimi faturalandÄ±rmayÄ± bÄ±raktÄ±.\n\nKayÄ±t yeniden baÄŸlanÄ±yor. Eski gemi hakkÄ±nda soru sormamanÄ±zÄ± Ã¶neririm.\n\nUtanÃ§la,\n%2</t>
<t id="4000">Filo koordinasyonu: %s'ye %s rotasÄ± atandÄ±</t>
    <t id="4001">Filo koordinasyonu: %s rotasÄ± tamamen kullanÄ±ldÄ±</t>
    <t id="4002">Filo koordinasyonu: %s, %s rotasÄ±nÄ± yayÄ±nladÄ±</t>
    <t id="5000">%s, %s iÃ§in birincil bÃ¶lge olarak atandÄ±</t>
    <t id="5001">%s, %s yÄ±lÄ±nda %s uzmanlÄ±k dÃ¼zeyine ulaÅŸtÄ±!</t>
    <t id="5002">Uygulanan bÃ¶lge bonusu: %s yÄ±lÄ±nda %%%s kÃ¢r artÄ±ÅŸÄ±</t>
    <t id="9500">Hata: %s takÄ±lÄ± kaldÄ± ve yardÄ±ma ihtiyacÄ± var!</t>
    <t id="9501">Hata: %s iÃ§in iÅŸlem baÅŸarÄ±sÄ±z oldu</t>
    <t id="9502">Hata: %s, GalaxyTrader MK3 ile kaydedilemiyor</t>
    <t id="80001">Ware %s kara listeye eklendi</t>
    <t id="80002">Ware %s kara listeden kaldÄ±rÄ±ldÄ±</t>
    <t id="80003">Ware %s beyaz listeye eklendi</t>
    <t id="80004">Otomatik olarak kara listeye alÄ±ndÄ± â€‹â€‹(dÃ¼ÅŸÃ¼k performans): %s</t>
    <t id="80005">Tehlikeli yazÄ±lÄ±mlara Ã¶ncelik verildi: %s</t>
    <t id="80006">Ware filtresi: %s etkin, %s ticareti engellendi</t>
    <t id="80007">TÃ¼m eÅŸya filtreleri temizlendi</t>
    <t id="80008">Ware filtreleri varsayÄ±lana sÄ±fÄ±rlandÄ±</t>
    <t id="80009">Ware Filtre YÃ¶netimi</t>
    <t id="80010">Bloke Mallar</t>
    <t id="80011">Ä°zin Verilen Mallar</t>
    <t id="80012">Tehlikeli EÅŸya TaÅŸÄ±ma</t>
    <t id="80013">Minimum EÅŸya DeÄŸeri</t>
    <t id="80014">Maksimum EÅŸya DeÄŸeri</t>
    <t id="80015">KÄ±sÄ±tlanmÄ±ÅŸ Gruplar</t>
    <t id="80016">Mevcut oyun durumuna gÃ¶re gÃ¼ncellenen eÅŸya kategorileri</t>
    <t id="80017">%s mallar kategorize edildi: %s dÃ¼ÅŸÃ¼k deÄŸerli, %s tehlikeli, %s yÃ¼ksek deÄŸerli</t>
    <t id="80018">Dinamik yazÄ±lÄ±m kategorizasyonu etkinleÅŸtirildi</t>
    <t id="80019">%s kategorisi iÃ§in otomatik kara listeye alma devre dÄ±ÅŸÄ± bÄ±rakÄ±ldÄ±</t>
    <t id="80020">DiÄŸer modlardan yeni Ã¼rÃ¼nler tespit edildi ve kategorize edildi</t>
    <t id="9000">GalaxyTrader - Genel Ayarlar</t>
    <t id="9010">XP ve EÄŸitim Sistemi</t>
    <t id="9012">Otomatik EÄŸitim</t>
    <t id="9013">XP Ã‡arpan</t>
    <t id="9015">Komutan Bonus YÃ¼zdesi</t>
    <t id="9020">Filo Koordinasyonu</t>
    <t id="9021">Filo Koordinasyonunu EtkinleÅŸtir</t>
    <t id="9023">Ticaret Ã–nbelleÄŸini EtkinleÅŸtir</t>
    <t id="9030">Bildirimler</t>
    <t id="9031">Bildirim DÃ¼zeyi</t>
    <t id="9040">Otomatik OnarÄ±m Sistemi</t>
    <t id="9041">Otomatik OnarÄ±mÄ± EtkinleÅŸtir</t>
    <t id="9042">GÃ¶vde OnarÄ±m EÅŸiÄŸi</t>
    <t id="9310">Galaxy-Miner</t>
    <t id="9311">SektÃ¶r kaynak sondasÄ± tarama beklemesi</t>
    <t id="9312">Gemi yakÄ±nlÄ±k aÄŸÄ±rlÄ±ÄŸÄ±</t>
    <t id="9043">Minimum Pilot Seviyesi</t>
    <t id="9004">Ticaret Fiyat AralÄ±klarÄ±</t>
    <t id="9005">SatÄ±ÅŸ Teklifi FiyatÄ± Maksimum</t>
    <t id="9006">SatÄ±n Al Teklif FiyatÄ± Min.</t>
    <t id="9007">Ä°zole: Maksimum SatÄ±ÅŸ FiyatÄ±</t>
    <t id="9008">Ä°zole: Min. SatÄ±n Alma FiyatÄ±</t>
    <t id="9009">Geri DÃ¶nÃ¼ÅŸ: Maksimum SatÄ±ÅŸ FiyatÄ±</t>
    <t id="9014">Geri DÃ¶nÃ¼ÅŸ: Minimum SatÄ±n Alma FiyatÄ±</t>
    <t id="9016">KÃ¢r EÅŸiÄŸi TabanÄ±</t>
    <t id="9025">Minimum Oyuncu ParasÄ±</t>
    <t id="9024">Ã–nbellek BÄ±rakma ToleransÄ±</t>
    <t id="9026">BoÅŸta park bÄ±rakma sÃ¼resi</t>
    <t id="9054">DÃ¼ÅŸman Grup SektÃ¶rlerini Engelle</t>
    <t id="9055">Kara Liste Tehdit DÃ¼zeyi</t>
    <t id="9056">Kara Listeyi Yeniden OluÅŸtur</t>
    <t id="9057">Yeniden oluÅŸtur</t>
    <t id="9058">GT gemiye ata</t>
    <t id="9059">Atamak</t>
    <t id="9112">Pilotlar gerekli seviyeye ulaÅŸtÄ±klarÄ±nda otomatik olarak eÄŸitime gÃ¶nderilir. EÄŸitim zamanlamasÄ±nÄ± manuel olarak kontrol etmeyi devre dÄ±ÅŸÄ± bÄ±rakÄ±n.</t>
    <t id="9113">PilotlarÄ±n ne kadar hÄ±zlÄ± deneyim kazanacaÄŸÄ±nÄ± ayarlar. Daha yÃ¼ksek deÄŸerler daha hÄ±zlÄ± ilerleme anlamÄ±na gelir.</t>
    <t id="9115">Percentage of subordinate XP awarded to commander pilots. Set to 0% to disable commander bonus XP. Default: 10%.</t>
    <t id="9121">Rota optimizasyonu ve yÃ¼k dengeleme dahil olmak Ã¼zere akÄ±llÄ± filo koordinasyon Ã¶zelliklerini etkinleÅŸtirir.</t>
    <t id="9123">Daha iyi koordinasyon iÃ§in filo Ã¼yeleri arasÄ±nda karlÄ± ticaret fÄ±rsatlarÄ±nÄ±n paylaÅŸÄ±lmasÄ±na olanak tanÄ±r.</t>
    <t id="9131">KaÃ§ bildirimin gÃ¶sterileceÄŸini kontrol eder: 0=Sessiz, 1=YalnÄ±zca Ã¶nemli, 2=TÃ¼m bildirimler</t>
    <t id="9141">GÃ¶vde eÅŸiÄŸin altÄ±na dÃ¼ÅŸtÃ¼ÄŸÃ¼nde, ticaret tamamlandÄ±ktan sonra gemileri otomatik olarak onarÄ±ma gÃ¶nderir. YalnÄ±zca deneyimli pilotlar iÃ§in (Seviye 12+). Gemiler uygun tesisi seÃ§er: S/M Equipment Dock, L/XL Tersanesi.</t>
    <t id="9142">Hull percentage below which auto-repair is triggered. Default: 95%. Ships will automatically go to nearest repair facility when damaged.</t>
    <t id="9411">EtkinleÅŸtirildiÄŸinde madenciler, sektÃ¶rdeki fraksiyon kaynak sondalarÄ±nÄ± deÄŸerlendirirken bekler (birden fazla sonda baÅŸÄ±na +5 sn). GT pilot seviyesi bu beklemeyi 1. seviyede tam sÃ¼reden 15. seviyede 5 saniyeye doÄŸrusal olarak azaltÄ±r (yalnÄ±zca GT XP modu, bekleme 5 sn'yi aÅŸtÄ±ÄŸÄ±nda). Devre dÄ±ÅŸÄ± = bekleme yok (vanilla davranÄ±ÅŸÄ±).</t>
    <t id="9412">MK3/MK4 gemileri doÄŸrulanmÄ±ÅŸ ticaretleri sÄ±ralarken daha yakÄ±n alÄ±m istasyonlarÄ±na yÃ¶nlendirir. SeÃ§im puanÄ± = ticaret puanÄ± / (1 + gemiâ†’alÄ±m sÄ±Ã§ramasÄ± Ã— aÄŸÄ±rlÄ±k). KaydÄ±rÄ±cÄ± 0-100 (0 = kapalÄ±; 4 = varsayÄ±lan 0,04). Ã–nbellek sÄ±ralamasÄ±nÄ± veya bÃ¶lgesel menzil limitlerini etkilemez.</t>
    <t id="9143">Otomatik onarÄ±m Ã¶zelliÄŸi iÃ§in gereken minimum pilot seviyesi. VarsayÄ±lan: 12 (deneyimli yatÄ±rÄ±mcÄ±lar). DÃ¼ÅŸÃ¼k seviyeli pilotlar manuel olarak tamir etmelidir.</t>
    <t id="9104">Maximum relative price for sell offers (ship buys FROM stations). Range: -1.0 to +1.0. Default: 0.5 (50% above average). Higher = more expensive but more options.</t>
    <t id="9105">Minimum relative price for buy offers (ship sells TO stations). Range: -1.0 to +1.0. Default: -0.5 (50% below average). Lower = cheaper buyers but more options.</t>
    <t id="9106">Ä°zole gemiler iÃ§in maksimum satÄ±ÅŸ fiyatÄ± (tek sektÃ¶rde sÄ±kÄ±ÅŸÄ±p kalmÄ±ÅŸ). AralÄ±k: -1,0 ila +1,0. VarsayÄ±lan: 0,5.</t>
    <t id="9107">Ä°zole gemiler iÃ§in minimum satÄ±n alma fiyatÄ± (tek sektÃ¶rde sÄ±kÄ±ÅŸmÄ±ÅŸ). AralÄ±k: -1,0 ila +1,0. VarsayÄ±lan: -0,5.</t>
    <t id="9108">Geri dÃ¶nÃ¼ÅŸ aramasÄ± iÃ§in maksimum satÄ±ÅŸ fiyatÄ± (normal arama baÅŸarÄ±sÄ±z olduÄŸunda son Ã§are). AralÄ±k: -1,0 ila +1,0. VarsayÄ±lan: 0,5. Geri dÃ¶nÃ¼ÅŸ aramasÄ± MaxDistance=2 ve rahat kar eÅŸiklerini kullanÄ±r.</t>
    <t id="9109">Geri dÃ¶nÃ¼ÅŸ aramasÄ± iÃ§in minimum satÄ±n alma fiyatÄ± (normal arama baÅŸarÄ±sÄ±z olduÄŸunda son Ã§are). AralÄ±k: -1,0 ila +1,0. VarsayÄ±lan: -0,5. Geri dÃ¶nÃ¼ÅŸ aramasÄ± MaxDistance=2 ve rahat kar eÅŸiklerini kullanÄ±r.</t>
    <t id="9116">Base minimum profit at Level 15 for a medium trader (reference cargo 8200). Actual MinAbsoluteProfit is computed per pilot + scaled by cargo:\n\nbase(L) = Base * ((L-1)^2 / 14^2)\nscaled = base(L) * (cargo / 8200)\nfinal = max(scaled, 25% of base(L))\n\nSet to 0 to accept any profit (only ROI/distance/other filters apply).</t>
    <t id="9125">Gemilerin takas aramasÄ±ndan Ã¶nce gereken minimum oyuncu parasÄ± (kredi). Oyuncu parasÄ± bu eÅŸiÄŸin altÄ±na dÃ¼ÅŸtÃ¼ÄŸÃ¼nde, tÃ¼m gemiler ticaret aramalarÄ±nÄ± atlar ve bekler, bÃ¶ylece oyunda takÄ±lmalara neden olan pahalÄ± Ã¶nbellek taramasÄ±nÄ±n Ã¶nÃ¼ne geÃ§ilir. AralÄ±k: 1.000 - 100.000 Cr. VarsayÄ±lan: 1.000 Cr.</t>
    <t id="9124">Maximum percentage ROI drop from cached value before rejecting trade. Example: 20% cached ROI with 15% tolerance accepts down to 17% ROI (14% drop).</t>
    <t id="9126">LimanÄ± boÅŸaltmak iÃ§in yanaÅŸmadan ayrÄ±lmadan Ã¶nceki dakika (0-60). 0 = yeni iÅŸ bulunana kadar yanaÅŸmÄ±ÅŸ kalÄ±r. VarsayÄ±lan: 1 dakika.</t>
    <t id="9154">DÃ¼ÅŸman gruplarÄ±nÄ±n sahip olduÄŸu tÃ¼m sektÃ¶rleri otomatik olarak kara listeye alÄ±n (kara listedeki iliÅŸki onay kutusu)</t>
    <t id="9155">Bir sektÃ¶rÃ¼ kara listeye almak iÃ§in gereken minimum tehdit dÃ¼zeyi (1-5):\n2=Orta (tek saldÄ±rÄ±)\n3=Orta-YÃ¼ksek (dÃ¼ÅŸman gruplar)\n4=YÃ¼ksek (ana gemiler/fÃ¼zeler)\n5=Ã‡ok YÃ¼ksek (Xenon/Khaak)</t>
    <t id="9156">Tehditten kaÃ§Ä±nma kara listesini manuel olarak yeniden oluÅŸturun (silinmiÅŸse faydalÄ±dÄ±r)</t>
    <t id="9157">GeÃ§erli dinamik kara listeyi tÃ¼m GT filo komutan gemilerine manuel olarak atayÄ±n. Astlar komutanlarÄ±ndan miras alÄ±rlar.</t>
    <t id="6001">Ã‡Ä±rak</t>
    <t id="6002">Kurye</t>
    <t id="6003">TedarikÃ§i</t>
    <t id="6004">TÃ¼ccar</t>
    <t id="6005">TÃ¼ccar</t>
    <t id="6006">Uzun Mesafe TÃ¼ccarÄ±</t>
    <t id="6101">Dengeli</t>
    <t id="6102">SavunmacÄ±</t>
    <t id="6103">Ticaret OdaklÄ±</t>
    <t id="6104">AÄŸÄ±r Savunma</t>
    <t id="6105">Kule DesteÄŸi</t>
    <t id="9050">Tehdit Ã–nleme Sistemi</t>
    <t id="9051">Tehditten KaÃ§Ä±nmayÄ± EtkinleÅŸtir:</t>
    <t id="9052">DÃ¼ÅŸmanca Ä°liÅŸki EÅŸiÄŸi:</t>
    <t id="9053">Dinamik Kara Listeyi Kullan:</t>
    <t id="9151">Seviye 6+ tÃ¼ccarlar dÃ¼ÅŸman gemilerini tespit eder ve tehlikeli rotalardan kaÃ§Ä±nÄ±r. Devre dÄ±ÅŸÄ± bÄ±rakmak tÃ¼m taramayÄ± durdurur (performansÄ± artÄ±rÄ±r). Komuta davranÄ±ÅŸÄ±nda gemi baÅŸÄ±na risk toleransÄ± (0-10 Ã¶lÃ§ek).</t>
    <t id="9152">Only flag factions with relation at or below this value as threats. Default: -20%</t>
    <t id="9153">Gemileri tehditlerin etrafÄ±ndan dolaÅŸmaya zorlamak iÃ§in tehlikeli sektÃ¶rleri (tehdit seviyesi 3+) otomatik olarak kara listeye alÄ±n. Alternatif rotalar iÃ§in standart yol bulmayÄ± kullanÄ±r.</t>
    <t id="9060">Savunma EkipmanÄ± Otomatik Yenileme (Seviye 15)</t>
    <t id="9061">Otomatik Yenilemeyi EtkinleÅŸtir:</t>
    <t id="9062">Yeniden Stok KarÅŸÄ± Ã–nlemleri:</t>
    <t id="9063">Savunma Drone'larÄ±nÄ± yeniden stoklayÄ±n:</t>
    <t id="9064">Ticari Drone'larÄ±n Stokunu Yeniden YapÄ±n:</t>
    <t id="9065">Lazer Kulelerini Yeniden StoklayÄ±n:</t>
    <t id="9066">OnarÄ±m Drone'larÄ±nÄ± yeniden stoklayÄ±n:</t>
    <t id="9067">KarÅŸÄ± Tedbir EÅŸiÄŸi:</t>
    <t id="9068">BirleÅŸik Kapasite EÅŸiÄŸi:</t>
    <t id="9069">Ekipman Denge Profili:</t>
    <t id="9161">Usta TÃ¼ccarlar (Seviye 15) ticaretten sonra savunma ekipmanlarÄ±nÄ± otomatik olarak yeniden stoklar. Astlar iÃ§in komutan seviyesinde geÃ§erlidir.</t>
    <t id="9162">TÃ¼m gemiler (S/M/L/XL). AyrÄ± kapasite. FÃ¼ze savunmasÄ± iÃ§in kritik.</t>
    <t id="9163">YalnÄ±zca L/XL gÃ¶nderilir. BirleÅŸik kapasiteyi diÄŸer konuÅŸlandÄ±rÄ±labilir Ã¶ÄŸelerle paylaÅŸÄ±r.</t>
    <t id="9164">YalnÄ±zca L/XL gÃ¶nderilir. Ticaret iÅŸlemleri iÃ§in gereklidir. BirleÅŸik kapasiteyi paylaÅŸÄ±r.</t>
    <t id="9165">BÃ¼tÃ¼n gemiler. L/XL gemileri birleÅŸik kapasiteyi paylaÅŸÄ±r, S/M kargo kullanÄ±r.</t>
    <t id="9166">YalnÄ±zca L/XL gÃ¶nderilir. Otomatik onarÄ±m sistemiyle Ã§alÄ±ÅŸÄ±r. BirleÅŸik kapasiteyi paylaÅŸÄ±r.</t>
    <t id="9167">KarÅŸÄ± Ã¶nlemler bu yÃ¼zdenin altÄ±na dÃ¼ÅŸtÃ¼ÄŸÃ¼nde stoku yeniden yapÄ±n (tÃ¼m gemiler, ayrÄ± kapasite).</t>
    <t id="9168">Toplam konuÅŸlandÄ±rÄ±labilirler bu yÃ¼zdenin altÄ±na dÃ¼ÅŸtÃ¼ÄŸÃ¼nde yeniden stok yapÄ±n (L/XL gemiler: dronlar + kuleler aynÄ± kapasiteyi paylaÅŸÄ±r).</t>
    <t id="9169">BirleÅŸik kapasite daÄŸÄ±lÄ±mÄ± (L/XL gemiler): Ticaret OdaklÄ± (20/50/20/10), Dengeli (35/35/20/10), Savunma (50/20/20/10), AÄŸÄ±r Savunma (40/30/20/10), Kule DesteÄŸi (30/30/30/10). Oranlar: Savunma/Ticaret/Kuleler/OnarÄ±m. SeÃ§enekler arasÄ±nda geÃ§iÅŸ yapmak iÃ§in tÄ±klayÄ±n.</t>
    <t id="9090">Gemi DeÄŸiÅŸiklikleri</t>
    <t id="9091">Gemi DeÄŸiÅŸikliklerini EtkinleÅŸtir</t>
    <t id="9191">Pilot seviyesine gÃ¶re gemi ve motor modifikasyonlarÄ±nÄ± otomatik olarak yÃ¼kleyin. Seviye 9+ = Seviye 1 modlarÄ±, Seviye 12+ = Seviye 2 modlarÄ±, Seviye 15+ = Seviye 3 modlarÄ±. SipariÅŸ iptal edildiÄŸinde yalnÄ±zca GT yÃ¼klÃ¼ modlar kaldÄ±rÄ±lÄ±r.</t>
    <t id="9070">Gemi AdlandÄ±rma YapÄ±landÄ±rmasÄ±</t>
    <t id="9071">XP'yÄ± gÃ¶rÃ¼ntÃ¼le:</t>
    <t id="9072">GÃ¶sterim SÄ±ralamasÄ±:</t>
    <t id="9073">Ekran Seviyesi:</t>
    <t id="9074">GÃ¶rÃ¼ntÃ¼ Durumu:</t>
    <t id="9075">Geminin Yeniden AdlandÄ±rÄ±lmasÄ±nÄ± EtkinleÅŸtir:</t>
    <t id="9076">Ã–nek</t>
    <t id="9077">son ek</t>
    <t id="9078">VarsayÄ±lan Ad KaynaÄŸÄ±:</t>
    <t id="9079">Model AdÄ±</t>
    <t id="9080">AdÄ± yazÄ±n</t>
    <t id="9081">Modeli TabanÄ±</t>
    <t id="9083">Ã–zel Ad</t>
    <t id="9084">Ana sektÃ¶rÃ¼ gÃ¶ster:</t>
    <t id="9085">AdlandÄ±rma modu:</t>
    <t id="9086">Klasik</t>
    <t id="9087">KalÄ±p</t>
    <t id="9088">Ad kalÄ±bÄ±:</t>
    <t id="9089">Yer tutucular: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. Atomik: {RS} {CB} {BL} vb. AÅŸaÄŸÄ±daki durum kÄ±saltmalarÄ±nÄ± kullanÄ±r. BoÅŸ jetonlar atlanÄ±r; boÅŸluklar sÄ±kÄ±ÅŸtÄ±rÄ±lÄ±r. Maks. 128 karakter.</t>
    <t id="9183">YapÄ±landÄ±rÄ±lmÄ±ÅŸ ana sektÃ¶rÃ¼ gemi adÄ±nda gÃ¶ster (Ã¶nek veya sonek).</t>
    <t id="9184">Klasik dÃ¼zen anahtarlarÄ± yerine {TOKEN} yer tutucularÄ±yla Ã¶zel ad formatÄ±. GalaxyTrader XP gerekir (vanilla XP modu deÄŸil).</t>
    <t id="9092">Desen yer tutucularÄ±</t>
    <t id="9093">Gemi: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">GT XP (mod): {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Ãœs: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">MÃ¼rettebat: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">SektÃ¶r: {SECTOR} | Ä°statistik: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">Durum belirteÃ§leri:</t>
    <t id="9100">{OPSTATE}: tÃ¼m aktif operasyon bayraklarÄ± birleÅŸik (Ã¶r. CB RS, MT)</t>
    <t id="9101">{STATUS}: engelli, eÄŸitim, yedek veya izole</t>
    <t id="9102">{CB}: yalnÄ±zca Ã¶zel kara liste, {OPSTATE} iÃ§inde, birlikte kullanmayÄ±n</t>
    <t id="9082">Gemi SÄ±nÄ±fÄ±nÄ± GÃ¶rÃ¼ntÃ¼le:</t>
    <t id="9171">Gemi adlarÄ±nda XP deÄŸerlerini gÃ¶ster</t>
    <t id="9175">Pilot bilgileriyle otomatik gemi yeniden adlandÄ±rmayÄ± etkinleÅŸtirme veya devre dÄ±ÅŸÄ± bÄ±rakma</t>
    <t id="9172">Gemi adlarÄ±nda rÃ¼tbe unvanlarÄ±nÄ± gÃ¶ster</t>
    <t id="9173">Gemi adlarÄ±nda seviye numaralarÄ±nÄ± gÃ¶ster</t>
    <t id="9174">Gemi adlarÄ±nda ticaret durumunu gÃ¶ster</t>
    <t id="9178">Gemi Ã¼ssÃ¼ adlarÄ± iÃ§in kaynaÄŸÄ± seÃ§in: Model AdÄ± (varyant ile), Tip AdÄ± (jenerik), Model TabanÄ± (varyant olmadan) veya Ã–zel Ad (kaydedilen ad)</t>
    <t id="9182">Gemi adlarÄ±nda gemi sÄ±nÄ±fÄ±nÄ± (S, M, L, XL) gÃ¶ster</t>
    <t id="9200">Hata AyÄ±klama AyarlarÄ±</t>
    <t id="9201">Hata AyÄ±klama GÃ¼nlÃ¼ÄŸÃ¼nÃ¼ EtkinleÅŸtir:</t>
    <t id="9202">TÃ¼m debug_text Ã§Ä±ktÄ±larÄ± iÃ§in ana geÃ§iÅŸ. Devre dÄ±ÅŸÄ± bÄ±rakÄ±ldÄ±ÄŸÄ±nda tÃ¼m hata ayÄ±klama gÃ¼nlÃ¼kleri bastÄ±rÄ±lÄ±r. EtkinleÅŸtirildiÄŸinde, bireysel debug_text olasÄ±lÄ±k deÄŸerlerine dayalÄ± olarak DebugLog'da hata ayÄ±klama mesajlarÄ± gÃ¶rÃ¼nÃ¼r.</t>
    <t id="9220">BakÄ±m ve TeÅŸhis</t>
    <t id="9221">KÃ¢r Ä°statistiklerini SÄ±fÄ±rla:</t>
    <t id="9222">SIFIRLAMA</t>
    <t id="9223">Kara Listedeki TÃ¼m SektÃ¶rleri Temizle:</t>
    <t id="9224">TEMÄ°ZLEMEK</t>
    <t id="9225">TÃ¼m AyarlarÄ± VarsayÄ±lanlara SÄ±fÄ±rla:</t>
    <t id="9226">TÃœMÃœNÃœ SIFIRLA</t>
    <t id="9323">TÃ¼m sektÃ¶rleri tehdit istihbaratÄ± kara listesinden kaldÄ±rÄ±r. Bu, kara listeye alÄ±nan tÃ¼m sektÃ¶rleri anÄ±nda temizleyecek ve gemilerinizin daha Ã¶nce engellenen bÃ¶lgelere seyahat etmesine olanak tanÄ±yacaktÄ±r. Tehdit Ã¶nleme sistemini sÄ±fÄ±rlamak istiyorsanÄ±z veya sektÃ¶rler yanlÄ±ÅŸlÄ±kla kara listeye alÄ±nmÄ±ÅŸsa bunu kullanÄ±n.</t>
    <t id="9321">TÃ¼m pilotlar ve gemiler iÃ§in tÃ¼m kar istatistiklerini 0'a sÄ±fÄ±rlar. ÅžiÅŸirilmiÅŸ gelire dayalÄ± istatistikleri temizlemek iÃ§in v0.6.0'a yÃ¼kselttikten sonra bunu kullanÄ±n. DÃ¼zeltme artÄ±k gerÃ§ek KÃ‚RI (gelir - satÄ±n alma maliyeti) izliyor. Ä°ÅŸlem sayÄ±larÄ± ve XP korunur.</t>
    <t id="9325">TÃ¼m genel ayarlarÄ± varsayÄ±lan deÄŸerlerine sÄ±fÄ±rlar. Buna XP ayarlarÄ±, Filo Koordinasyonu, Bildirimler, Mobil Bilgi, Tehditten KaÃ§Ä±nma, Gemi AdlandÄ±rma, Otomatik OnarÄ±m, DeÄŸiÅŸiklikler, Performans ve Numara FormatÄ± ayarlarÄ± dahildir. Hata ayÄ±klama gÃ¼nlÃ¼ÄŸÃ¼ ayarÄ±, sÄ±fÄ±rlama iÅŸleminin gÃ¼nlÃ¼ÄŸe kaydedilmesine izin vermek iÃ§in korunur.</t>
    <t id="9227">TÃ¼m Ev SektÃ¶rleri iÃ§in Ticaret Ã–nbelleÄŸini Temizle:</t>
    <t id="9228">Ã–NBELLEÄžÄ° TEMÄ°ZLE</t>
    <t id="9327">TÃ¼m ana sektÃ¶rler iÃ§in ticaret Ã¶nbelleÄŸini temizler. Bu, tÃ¼m gemileri bir sonraki ticari aramalarÄ±nda yeni canlÄ± aramalar yapmaya zorlayacaktÄ±r. Ã–nbellek eski veya bozuk gÃ¶rÃ¼nÃ¼yorsa ya da Ã¶nbelleÄŸin tamamen yenilenmesini zorlamak istiyorsanÄ±z bunu kullanÄ±n.</t>
    <t id="9229">TÃ¼m arama kilitlerini serbest bÄ±rakÄ±n</t>
    <t id="9329">TÃœM uÃ§uÅŸ iÃ§i ticaret arama kilitlerini serbest bÄ±rakÄ±r ve ilgili geÃ§ici durumu temizler. Gemiler, eski kayÄ±tlardaki eski kilitler nedeniyle "Ticaret aranÄ±yor" durumunda takÄ±lÄ±p kalÄ±rsa bunu kullanÄ±n. Bu, meÅŸru aramalarÄ± kesintiye uÄŸratabilir.</t>
    <t id="9290">Ticaret Merkezi Durumunu DÃ¶kÃ¼mÃ¼:</t>
    <t id="9291">Ã‡Ã–PLÃœK</t>
    <t id="9390">GÃ¼nlÃ¼kte ve bildirim olarak merkezi ticaret merkezinin (zamanlayÄ±cÄ± kuyruklarÄ± + son talep eden gemi durumu) tek seferlik anlÄ±k gÃ¶rÃ¼ntÃ¼sÃ¼nÃ¼ gÃ¶sterir.</t>
    <t id="9292">Ticaret Ã–nbelleÄŸini DÃ¶kÃ¼mÃ¼ (TAM):</t>
    <t id="9293">Ã–NBELLEK DÃ–KÃœMÃœ</t>
    <t id="9392">TAM Ã¶nbellek dÃ¶kÃ¼mÃ¼ (Ã§ok bÃ¼yÃ¼k olabilir). TÃ¼m Ã¶nbellek giriÅŸlerini parÃ§alar halinde DebugLog'a yazar. Ä°ptal etmek iÃ§in tekrar tÄ±klayÄ±n.</t>
    <t id="9294">Filo RezervasyonlarÄ±nÄ± Temizle:</t>
    <t id="9295">TEMÄ°ZLEMEK</t>
    <t id="9394">TÃ¼m aktif filo ticaret rezervasyonlarÄ±nÄ± temizler. Gemiler ayrÄ±lmÄ±ÅŸ iÅŸlemlerin sÃ¼resinin dolmasÄ±nÄ± beklerken takÄ±lÄ±p kalmÄ±ÅŸsa veya eski bir kayÄ±t yÃ¼klendikten sonra rezervasyon tablosu eskimiÅŸse bunu kullanÄ±n.</t>
    <t id="9230">Performans</t>
    <t id="9231">Toplu Ä°ÅŸleme Gecikmesi:</t>
    <t id="9232">DoÄŸrulama Gecikmesi:</t>
    <t id="9233">Maksimum EÅŸzamanlÄ± Arama:</t>
    <t id="9234">Geri DÃ¶nÃ¼lecek Maksimum Ä°ÅŸlemler:</t>
    <t id="9235">ÃœrÃ¼n BaÅŸÄ±na Maksimum Teklif:</t>
    <t id="9236">Mal BaÅŸÄ±na Maksimum Ä°ÅŸlem:</t>
    <t id="9237">EÅŸleÅŸtirme Ä°Ã§in ÃœrÃ¼n BaÅŸÄ±na Maksimum Teklifler:</t>
    <t id="9238">Erken Ã‡Ä±kÄ±ÅŸ EÅŸiÄŸi:</t>
    <t id="9241">CanlÄ± Teklif Dilim AralÄ±ÄŸÄ±:</t>
    <t id="9266">Arama Kilidi TTL:</t>
    <t id="9263">Toplu ParÃ§a Boyutu:</t>
    <t id="9239">SayÄ± FormatÄ±</t>
    <t id="9240">BiÃ§im Stili:</t>
    <t id="9242">M Sonekini Kullan</t>
    <t id="9243">M Sonek EÅŸiÄŸi:</t>
    <t id="9244">Almanca (123.456,78)</t>
    <t id="9245">Ä°ngilizce (123.456,78)</t>
    <t id="9510">Seviye YÃ¼kseltme AÃ§Ä±lÄ±r Bildirimleri:</t>
    <t id="9511">EÄŸitim Gerekli UyarÄ±larÄ±:</t>
    <t id="9512">EÄŸitim TamamlandÄ± Bildirimleri:</t>
    <t id="9513">KÃ¢r RaporlarÄ±:</t>
    <t id="9514">Piyasa UyarÄ±larÄ±:</t>
    <t id="9515">Filo GÃ¼ncellemeleri:</t>
    <t id="9516">YalnÄ±zca vanilya XP kullanÄ±n</t>
    <t id="9610">Oyuncu arayÃ¼zÃ¼nde tÃ¼ccar seviye yÃ¼kseltme aÃ§Ä±lÄ±r bildirimlerini etkinleÅŸtirin veya devre dÄ±ÅŸÄ± bÄ±rakÄ±n.</t>
    <t id="9611">PilotlarÄ±n bir sonraki seviyeye geÃ§mek iÃ§in eÄŸitime ihtiyaÃ§ duyduÄŸunda uyarÄ± verir.</t>
    <t id="9612">Pilotlar eÄŸitimi tamamlayÄ±p rÃ¼tbe atladÄ±ÄŸÄ±nda bildirir.</t>
    <t id="9613">Periyodik kÃ¢r Ã¶zetleri (basit ve kapsamlÄ± raporlar).</t>
    <t id="9614">OlaÄŸanÃ¼stÃ¼ piyasa fÄ±rsatlarÄ± ve yÃ¼ksek deÄŸerli ticaret uyarÄ±larÄ±.</t>
    <t id="9615">Filo koordinasyon mesajlarÄ± ve durum gÃ¼ncellemeleri.</t>
    <t id="9616">pilot.skill.piloting'i kullanÄ±n ve GT XP ilerlemeyi/sÄ±nÄ±rlarÄ± devre dÄ±ÅŸÄ± bÄ±rakÄ±n.</t>
    <t id="9246">Basit Rapor SÄ±klÄ±ÄŸÄ±:</t>
    <t id="9247">KapsamlÄ± Rapor SÄ±klÄ±ÄŸÄ±:</t>
    <t id="9248">Maksimum EÅŸzamanlÄ± Ã–nbellek AramasÄ±:</t>
    <t id="9249">Maksimum EÅŸzamanlÄ± CanlÄ± Arama SayÄ±sÄ±:</t>
    <t id="9340">SayÄ± biÃ§imini seÃ§in: Almanca '.' kullanÄ±r. binler iÃ§in ',' ondalÄ±k sayÄ±lar iÃ§in (123.456,78), Ä°ngilizce binler iÃ§in ',' ve '.' kullanÄ±r. ondalÄ±k sayÄ±lar iÃ§in (123.456,78)</t>
    <t id="9342">EÅŸiÄŸin Ã¼zerindeki sayÄ±lar iÃ§in M son ekini etkinleÅŸtirin (Ã¶r. 1.000.000 yerine 1,0 M)</t>
    <t id="9343">M son eki iÃ§in eÅŸik. Bu deÄŸerin Ã¼zerindeki sayÄ±lar M sonekiyle gÃ¶rÃ¼ntÃ¼lenecektir (varsayÄ±lan: 999,999)</t>
    <t id="9346">Basit raporun sÄ±klÄ±ÄŸÄ± (aÃ§Ä±lÄ±r pencere bildirimi): 0-30 dakika (0 = devre dÄ±ÅŸÄ± - basit raporlar devre dÄ±ÅŸÄ±dÄ±r, varsayÄ±lan: 1 dakika)</t>
    <t id="9347">KapsamlÄ± raporun sÄ±klÄ±ÄŸÄ± (kayÄ±t defteri giriÅŸi): 0-60 dakika (0 = devre dÄ±ÅŸÄ± - kapsamlÄ± raporlar devre dÄ±ÅŸÄ±, varsayÄ±lan: 30 dakika)</t>
    <t id="9398">GT Kredi Vadesi GeÃ§ersiz KÄ±lma'yÄ± kullanÄ±n</t>
    <t id="9399">AynÄ± kullanÄ±cÄ± arayÃ¼zÃ¼ yuvasÄ±ndaki vanilya "Ä°ÅŸlemlerden kaynaklanan CR" satÄ±rÄ±nÄ± GT Ã¶ngÃ¶rÃ¼len deÄŸerle deÄŸiÅŸtirin veya artÄ±rÄ±n.</t>
    <t id="9331">Ticari arama iÅŸlemi sÄ±rasÄ±nda gruplar arasÄ±ndaki gecikme (1-500ms). Daha yÃ¼ksek deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak ticari aramalarÄ± yavaÅŸlatÄ±r. VarsayÄ±lan: 120ms. Toplu iÅŸlemci ve ticari liste filtrelemede kullanÄ±lÄ±r.</t>
    <t id="9332">AI komut dosyasÄ±ndaki ticari doÄŸrulamalar arasÄ±ndaki gecikme (1-500 ms). Daha yÃ¼ksek deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak ticaret doÄŸrulamasÄ±nÄ± yavaÅŸlatÄ±r. VarsayÄ±lan: 50 ms. MD sisteminden ticaret listesini doÄŸrularken kullanÄ±lÄ±r.</t>
    <t id="9333">AynÄ± anda yÃ¼rÃ¼tÃ¼lebilecek maksimum ticari arama sayÄ±sÄ± (1-10). Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak kuyrukta bekleme sÃ¼relerini artÄ±rÄ±r. Daha yÃ¼ksek deÄŸerler, aramalarÄ± daha hÄ±zlÄ± iÅŸler ancak performansta artÄ±ÅŸlara neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9334">Ã–nbellek aramasÄ±ndan dÃ¶ndÃ¼rÃ¼lecek maksimum iÅŸlem sayÄ±sÄ± (1-100). Daha yÃ¼ksek deÄŸerler daha fazla ticaret seÃ§eneÄŸi sunar ancak Ã¶nbellek doÄŸrulama sÃ¼resini artÄ±rÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak geÃ§erli iÅŸlemleri kaÃ§Ä±rabilir. VarsayÄ±lan: 20.</t>
    <t id="9335">CanlÄ± aramada iÅŸlenecek yazÄ±lÄ±m baÅŸÄ±na maksimum teklif sayÄ±sÄ± (5-100). Daha yÃ¼ksek deÄŸerler daha fazla teklifi dikkate alÄ±r ancak iÅŸlem sÃ¼resini artÄ±rÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak karlÄ± iÅŸlemleri kaÃ§Ä±rabilir. VarsayÄ±lan: 20.</t>
    <t id="9336">Toplu iÅŸleme sÄ±rasÄ±nda eÅŸya baÅŸÄ±na maksimum iÅŸlem sayÄ±sÄ± (5-100). Daha yÃ¼ksek deÄŸerler eÅŸya baÅŸÄ±na daha fazla iÅŸleme izin verir ancak iÅŸlem sÃ¼resini artÄ±rÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak karlÄ± iÅŸlemleri kaÃ§Ä±rabilir. VarsayÄ±lan: 20.</t>
    <t id="9337">Toplu iÅŸlemcide eÅŸleÅŸtirme iÃ§in yazÄ±lÄ±m baÅŸÄ±na maksimum teklif sayÄ±sÄ± (5-100). Daha yÃ¼ksek deÄŸerler daha fazla teklifi dikkate alÄ±r ancak iÅŸlem sÃ¼resini artÄ±rÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak karlÄ± iÅŸlemleri kaÃ§Ä±rabilir. VarsayÄ±lan: 20.</t>
    <t id="9338">Toplu iÅŸleme iÃ§in erken Ã§Ä±kÄ±ÅŸ eÅŸiÄŸi (100-10000). Bu kadar Ã§ok iÅŸlem bulunduÄŸunda toplu iÅŸleme, CPU'dan tasarruf etmek iÃ§in erken durdurulur. Daha yÃ¼ksek deÄŸerler daha fazla iÅŸlem gerÃ§ekleÅŸtirir ancak CPU yÃ¼kÃ¼nÃ¼ artÄ±rÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler daha erken Ã§Ä±kar ancak karlÄ± iÅŸlemleri kaÃ§Ä±rabilir. VarsayÄ±lan: 2000.</t>
    <t id="9341">Milisaniye cinsinden canlÄ± teklif dilim aralÄ±ÄŸÄ± (5-2000 ms). CanlÄ± teklif dilimlerinin ne sÄ±klÄ±kta baÅŸlayabileceÄŸini kontrol eder. Daha dÃ¼ÅŸÃ¼k deÄŸerler daha hÄ±zlÄ± teklif toplamaya olanak tanÄ±r ancak CPU yÃ¼kÃ¼nÃ¼ artÄ±rÄ±r. Daha yÃ¼ksek deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak canlÄ± arama iÅŸlemini yavaÅŸlatÄ±r. VarsayÄ±lan: 500ms.</t>
    <t id="9363">Toplu iÅŸleme yÄ±ÄŸÄ±n boyutu (5-20). ParÃ§a baÅŸÄ±na chunkSizeÃ—chunkSize kombinasyonlarÄ±nÄ± iÅŸler (Ã¶rneÄŸin, 5Ã—5 = 25 kombinasyon). Daha bÃ¼yÃ¼k parÃ§alar verimi artÄ±rÄ±r ancak parÃ§a baÅŸÄ±na CPU yÃ¼kÃ¼nÃ¼ artÄ±rÄ±r. Daha kÃ¼Ã§Ã¼k parÃ§alar CPU artÄ±ÅŸlarÄ±nÄ± azaltÄ±r ancak daha fazla devamlÄ±lÄ±k gerektirir. VarsayÄ±lan: 5.</t>
    <t id="9348">AynÄ± anda Ã§alÄ±ÅŸtÄ±rÄ±labilecek maksimum Ã¶nbellek arama sayÄ±sÄ± (1-20). Ã–nbellek aramalarÄ± hÄ±zlÄ± ve ucuzdur; daha dÃ¼ÅŸÃ¼k deÄŸerler bÃ¼yÃ¼k filolarda patlamayÄ± azaltabilir. VarsayÄ±lan: 2.</t>
    <t id="9349">AynÄ± anda yÃ¼rÃ¼tÃ¼lebilecek maksimum canlÄ± arama sayÄ±sÄ± (1-10). CanlÄ± aramalar CPU yoÄŸun olduÄŸundan dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak kuyrukta bekleme sÃ¼relerini artÄ±rÄ±r. Daha yÃ¼ksek deÄŸerler, aramalarÄ± daha hÄ±zlÄ± iÅŸler ancak performansta artÄ±ÅŸlara neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9264">Ã–nbellek Sorgu Ã–beÄŸi Boyutu:</t>
    <t id="9265">CanlÄ± Teklif ParÃ§a Boyutu Ekle:</t>
    <t id="9364">ParÃ§a baÅŸÄ±na doÄŸrulanan Ã¶nbellek giriÅŸleri (10-200). Daha kÃ¼Ã§Ã¼k deÄŸerler, Ã¶nbellek doÄŸrulamasÄ±nÄ± daha fazla Ã§erÃ§eveye yayar (daha sorunsuz), ancak Ã¶nbelleÄŸe alÄ±nmÄ±ÅŸ bir iÅŸlemi bulma sÃ¼resini artÄ±rabilir. VarsayÄ±lan: 10.</t>
    <t id="9365">Ek dilim baÅŸÄ±na eklenen teklifler (50-2000). Daha kÃ¼Ã§Ã¼k deÄŸerler, kare baÅŸÄ±na liste ekleme iÅŸini azaltÄ±r (daha dÃ¼zgÃ¼n), ancak canlÄ± aramanÄ±n tamamlanmasÄ±nÄ± yavaÅŸlatabilir. VarsayÄ±lan: 200.</t>
    <t id="9366">Kilitlenme sÃ¼resini saniye cinsinden arayÄ±n (60-7200). Bir gemi "ticaret araÅŸtÄ±rmasÄ± zaten devam ediyor" nedeniyle bundan daha uzun bir sÃ¼re reddedilirse, GT eski arama durumunu temizleyerek ve kilidi serbest bÄ±rakarak kendi kendini iyileÅŸtirecektir. VarsayÄ±lan: 600s.</t>
    <t id="9370">Toplu Geri BasÄ±nÃ§ YumuÅŸak EÅŸiÄŸi:</t>
    <t id="9371">Toplu Geri BasÄ±nÃ§ Sert EÅŸiÄŸi:</t>
    <t id="9372">Dilim BaÅŸÄ±na SektÃ¶rler:</t>
    <t id="9373">Ev Yenileme Bekleme SÃ¼resi:</t>
    <t id="9374">Ã–nbellek Eksik Bekleme SÃ¼resi TabanÄ±:</t>
    <t id="9375">ZamanlayÄ±cÄ± Onay AralÄ±ÄŸÄ±:</t>
    <t id="9376">Onay BaÅŸÄ±na Maksimum Ã–nbellek Sorgusu:</t>
    <t id="9377">Onay BaÅŸÄ±na Maksimum Arama DevamlÄ±lÄ±ÄŸÄ±:</t>
    <t id="9378">Onay BaÅŸÄ±na Maksimum GÃ¶nderim SayÄ±sÄ±:</t>
    <t id="9379">Onay BaÅŸÄ±na Maksimum Ã–ÄŸe SayÄ±sÄ±:</t>
    <t id="9380">Tik BaÅŸÄ±na Maksimum Uyanma:</t>
    <t id="9381">Ã–nbellek Sorgu Maksimum GiriÅŸ SayÄ±sÄ±:</t>
    <t id="9382">Bayat EÅŸik Saniye:</t>
    <t id="9383">Kuyruk Eski EÅŸiÄŸi Saniye:</t>
    <t id="9384">BaÅŸarÄ±sÄ±z Ä°ÅŸlem Sona Erme Saniyeleri:</t>
    <t id="9385">Maksimum EÅŸzamanlÄ± Geri DÃ¶nme AramalarÄ±:</t>
    <t id="9386">Maksimum EÅŸzamanlÄ± Geri DÃ¶nme AramalarÄ±:</t>
    <t id="9470">Toplu iÅŸlemci biriktirme listesi iÃ§in yumuÅŸak eÅŸik (5-50). BirikmiÅŸ iÅŸ bu deÄŸere ulaÅŸtÄ±ÄŸÄ±nda, yeni arama isteklerini yavaÅŸlatmak iÃ§in karÅŸÄ± basÄ±nÃ§ uygulanmaya baÅŸlar. Daha dÃ¼ÅŸÃ¼k deÄŸerler karÅŸÄ± basÄ±ncÄ± daha erken tetikler (daha ihtiyatlÄ±). VarsayÄ±lan: 10.</t>
    <t id="9471">Toplu iÅŸlemci biriktirme listesi iÃ§in sabit eÅŸik (10-100). Biriktirme listesi bu deÄŸere ulaÅŸtÄ±ÄŸÄ±nda, birikme miktarÄ± azalÄ±ncaya kadar yeni canlÄ± aramalar engellenir. Daha dÃ¼ÅŸÃ¼k deÄŸerler aramalarÄ± daha erken engeller (daha ihtiyatlÄ±). VarsayÄ±lan: 25.</t>
    <t id="9472">CanlÄ± teklif koleksiyonunda dilim baÅŸÄ±na iÅŸlenen sektÃ¶rler (1-5). Daha kÃ¼Ã§Ã¼k deÄŸerler Ã§alÄ±ÅŸmayÄ± daha fazla kareye yayar (daha dÃ¼zgÃ¼n) ancak teklif toplamayÄ± yavaÅŸlatabilir. Daha bÃ¼yÃ¼k deÄŸerler daha hÄ±zlÄ± iÅŸlenir ancak kare ani artÄ±ÅŸlarÄ±na neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9473">Ana sektÃ¶r yenilemesi tamamlandÄ±ktan sonra bekleme sÃ¼resi (10-120 saniye). AÅŸÄ±rÄ± yenileme isteklerini Ã¶nler. Daha dÃ¼ÅŸÃ¼k deÄŸerler daha sÄ±k yenilemeye izin verir ancak CPU yÃ¼kÃ¼nÃ¼ artÄ±rÄ±r. Daha yÃ¼ksek deÄŸerler yenileme sÄ±klÄ±ÄŸÄ±nÄ± azaltÄ±r ancak Ã¶nbellek gÃ¼ncellemelerini geciktirebilir. VarsayÄ±lan: 30s.</t>
    <t id="9474">CanlÄ± aramayÄ± yeniden denemeden Ã¶nce Ã¶nbellek kaÃ§Ä±rÄ±ldÄ±ktan sonra temel bekleme sÃ¼resi (1-30 saniye). AÅŸÄ±rÄ± yeniden deneme giriÅŸimlerini Ã¶nler. Daha dÃ¼ÅŸÃ¼k deÄŸerler daha erken yeniden deneyin ancak CPU yÃ¼kÃ¼nÃ¼ artÄ±rÄ±n. Daha yÃ¼ksek deÄŸerler yeniden deneme sÄ±klÄ±ÄŸÄ±nÄ± azaltÄ±r ancak ticari bulmayÄ± geciktirebilir. VarsayÄ±lan: 10s.</t>
    <t id="9475">ZamanlayÄ±cÄ± tÄ±klamalarÄ± arasÄ±ndaki aralÄ±k milisaniye cinsinden (50-500ms). ZamanlayÄ±cÄ±nÄ±n iÅŸ kuyruÄŸunu ne sÄ±klÄ±kta iÅŸlediÄŸini kontrol eder. Daha dÃ¼ÅŸÃ¼k deÄŸerler daha sÄ±k iÅŸlenir ancak CPU yÃ¼kÃ¼nÃ¼ artÄ±rÄ±r. Daha yÃ¼ksek deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak sÄ±ra bekleme sÃ¼relerini artÄ±rabilir. VarsayÄ±lan: 100ms.</t>
    <t id="9476">ZamanlayÄ±cÄ± iÅŸareti baÅŸÄ±na baÅŸlatÄ±lan maksimum Ã¶nbellek sorgusu (1-5). Ã‡erÃ§eve engellemeyi Ã¶nlemek iÃ§in Ã¶nbellek sorgu hÄ±zÄ±nÄ± sÄ±nÄ±rlar. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU artÄ±ÅŸlarÄ±nÄ± azaltÄ±r ancak Ã¶nbellek aramalarÄ±nÄ± yavaÅŸlatÄ±r. Daha yÃ¼ksek deÄŸerler daha hÄ±zlÄ± iÅŸlenir ancak takÄ±lmaya neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9477">ZamanlayÄ±cÄ± iÅŸareti baÅŸÄ±na maksimum arama devamlÄ±lÄ±ÄŸÄ± baÅŸlatÄ±ldÄ± (1-5). Ã‡erÃ§eve engellemesini Ã¶nlemek iÃ§in devam hÄ±zÄ±nÄ± sÄ±nÄ±rlar. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU artÄ±ÅŸlarÄ±nÄ± azaltÄ±r ancak arama iÅŸlemini yavaÅŸlatÄ±r. Daha yÃ¼ksek deÄŸerler daha hÄ±zlÄ± iÅŸlenir ancak takÄ±lmaya neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9478">ZamanlayÄ±cÄ± iÅŸareti baÅŸÄ±na iÅŸlenen maksimum gemi (1-5). Ã‡erÃ§eve engellemesini Ã¶nlemek iÃ§in gemi iÅŸleme hÄ±zÄ±nÄ± sÄ±nÄ±rlar. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU artÄ±ÅŸlarÄ±nÄ± azaltÄ±r ancak kuyruk iÅŸlemeyi yavaÅŸlatÄ±r. Daha yÃ¼ksek deÄŸerler daha hÄ±zlÄ± iÅŸlenir ancak takÄ±lmaya neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9479">ZamanlayÄ±cÄ± iÅŸareti baÅŸÄ±na iÅŸlenen maksimum iÅŸ Ã¶ÄŸesi (1-5). Ã‡erÃ§eve engellemesini Ã¶nlemek iÃ§in iÅŸ Ã¶ÄŸesi iÅŸleme hÄ±zÄ±nÄ± sÄ±nÄ±rlar. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU artÄ±ÅŸlarÄ±nÄ± azaltÄ±r ancak kuyruk iÅŸlemeyi yavaÅŸlatÄ±r. Daha yÃ¼ksek deÄŸerler daha hÄ±zlÄ± iÅŸlenir ancak takÄ±lmaya neden olabilir. VarsayÄ±lan: 1.</t>
    <t id="9480">ZamanlayÄ±cÄ± iÅŸareti baÅŸÄ±na uyandÄ±rÄ±lan maksimum garson sayÄ±sÄ± (1-10). Ã‡ok sayÄ±da garson sÄ±raya girdiÄŸinde CPU artÄ±ÅŸlarÄ±nÄ± Ã¶nlemek iÃ§in uyanma hÄ±zÄ±nÄ± sÄ±nÄ±rlar. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU artÄ±ÅŸlarÄ±nÄ± azaltÄ±r ancak garsonun iÅŸlemlerini yavaÅŸlatÄ±r. Daha yÃ¼ksek deÄŸerler daha hÄ±zlÄ± iÅŸlenir ancak takÄ±lmaya neden olabilir. VarsayÄ±lan: 2.</t>
    <t id="9481">Toplu iÅŸ baÅŸÄ±na sorgulanan maksimum Ã¶nbellek giriÅŸi sayÄ±sÄ± (1-200). Ã–nbellek sorgusu toplu boyutunu kontrol eder. Daha dÃ¼ÅŸÃ¼k deÄŸerler Ã¶nbellek aramalarÄ±nÄ± hÄ±zlandÄ±rÄ±r ancak daha iyi iÅŸlemleri kaÃ§Ä±rabilir. Daha yÃ¼ksek deÄŸerler, daha fazla Ã¶nbelleÄŸe alÄ±nmÄ±ÅŸ iÅŸlemi dikkate alÄ±r ancak doÄŸrulama sÃ¼resini artÄ±rÄ±r. VarsayÄ±lan: 50.</t>
    <t id="9482">Saniye cinsinden canlÄ± arama durumu eski eÅŸiÄŸi (60-600). CanlÄ± arama durumu bundan daha eski olduÄŸunda eski ve temiz olarak kabul edilir. Daha dÃ¼ÅŸÃ¼k deÄŸerler eski durumu daha Ã§abuk temizler ancak meÅŸru aramalarÄ± kesintiye uÄŸratabilir. Daha yÃ¼ksek deÄŸerler daha uzun aramalara izin verir ancak eski durumu bÄ±rakabilir. VarsayÄ±lan: 300s.</t>
    <t id="9483">Saniye cinsinden kuyruk Ã¶ÄŸesi eskime eÅŸiÄŸi (30-300). Kuyruk Ã¶ÄŸeleri bundan daha eski olduÄŸunda eski kabul edilir ve kaldÄ±rÄ±lÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler eski Ã¶ÄŸeleri daha Ã§abuk temizler ancak sÄ±raya alÄ±nmÄ±ÅŸ meÅŸru Ã¶ÄŸeleri kaldÄ±rabilir. Daha yÃ¼ksek deÄŸerler daha uzun kuyruk sÃ¼relerine izin verir ancak Ã¶ÄŸelerin eskimesine neden olabilir. VarsayÄ±lan: 60s.</t>
    <t id="9484">Ticaret Ã¶nbelleÄŸinin saniye cinsinden sona ermesi baÅŸarÄ±sÄ±z oldu (300-3600). BaÅŸarÄ±sÄ±z olan iÅŸlemler, hemen yeniden denemeyi Ã¶nlemek iÃ§in Ã¶nbelleÄŸe alÄ±nÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler baÅŸarÄ±sÄ±z iÅŸlemleri daha Ã§abuk sona erdirir (daha fazla yeniden deneme), ancak Ã¶nbellek etkinliÄŸini azaltÄ±r. Daha yÃ¼ksek deÄŸerler daha uzun sÃ¼re Ã¶nbelleÄŸe alÄ±nÄ±r (daha az yeniden deneme) ancak yeniden deneme giriÅŸimlerini geciktirebilir. VarsayÄ±lan: 1800s (30 dakika).</t>
    <t id="9485">Maksimum eÅŸzamanlÄ± yedek canlÄ± aramalar (1-10). Geri dÃ¶nÃ¼ÅŸ aramalarÄ±, ana sektÃ¶r kilidini atlayarak aynÄ± ana sektÃ¶rden birden fazla geminin aynÄ± anda arama yapmasÄ±na olanak tanÄ±r. Daha dÃ¼ÅŸÃ¼k deÄŸerler CPU yÃ¼kÃ¼nÃ¼ azaltÄ±r ancak geri dÃ¶nÃ¼ÅŸ aramalarÄ±nÄ± yavaÅŸlatabilir. Daha yÃ¼ksek deÄŸerler daha fazla paralel geri dÃ¶nÃ¼ÅŸ aramasÄ±na izin verir ancak CPU kullanÄ±mÄ±nÄ± artÄ±rÄ±r. VarsayÄ±lan: 1.</t>
    <t id="9490">Takas Bulundu Sinyal Gecikmesi:</t>
    <t id="9590">Milisaniye cinsinden (10-1000ms) GTTrade_Found sinyalinin gemilere gÃ¶nderilmesinden Ã¶nceki gecikme. Gemiler, gecikmiÅŸ sinyalleri yakalamak iÃ§in yeni istekler gÃ¶ndermeden Ã¶nce her zaman bekler (yapÄ±landÄ±rÄ±lmÄ±ÅŸ gecikme + 5 ms arabellek). Daha yÃ¼ksek deÄŸerler, daha dÃ¼zgÃ¼n performans iÃ§in sinyalleri Ã§erÃ§evelere yayar. VarsayÄ±lan: 10ms.</t>
    <t id="8000">GalaxyTrader Filo</t>
    <t id="8001">GalaxyTrader filo yÃ¶netimi ve pilot istatistikleri</t>
    <t id="8002">TÃ¼m GalaxyTrader pilot programlarÄ±nÄ± gÃ¶rÃ¼ntÃ¼leyin ve yÃ¶netin</t>
    <t id="8100">Gemi kimliÄŸi</t>
    <t id="8101">Pilot</t>
    <t id="8102">Gemi</t>
    <t id="8103">Durum</t>
    <t id="8104">RÃ¼tbe</t>
    <t id="8105">Seviye</t>
    <t id="8106">XP</t>
    <t id="8107">Ã–mÃ¼r Boyu KÃ¢r</t>
    <t id="8108">Konum</t>
    <t id="8109">Ev ÃœssÃ¼</t>
    <t id="8110">Son Ä°ÅŸlem</t>
    <t id="8111">Pilot KarÄ±</t>
    <t id="8112">Gemi KarÄ±</t>
    <t id="8113">Ticaret SayÄ±sÄ±</t>
    <t id="8200">Yenile</t>
    <t id="8201">CSV'yi dÄ±ÅŸa aktar</t>
    <t id="8202">Ä°statistikler</t>
    <t id="8203">Ayarlar</t>
    <t id="8204">YardÄ±m</t>
    <t id="8205">KapalÄ±</t>
    <t id="8300">TÃ¼m Pilotlar</t>
    <t id="8301">Ticaret</t>
    <t id="8302">EÄŸitim</t>
    <t id="8303">BakÄ±m</t>
    <t id="8304">Acil durum</t>
    <t id="8305">Yeni BaÅŸlayanlar (Sv 1-5)</t>
    <t id="8306">Ä°leri DÃ¼zey (Sv 6-11)</t>
    <t id="8307">Uzmanlar (Sv 12+)</t>
    <t id="8308">Ä°lk 10 Kazanan</t>
    <t id="8350">GÃ¶re sÄ±rala:</t>
    <t id="8351">Gemi kimliÄŸi</t>
    <t id="8352">Pilot AdÄ±</t>
    <t id="8353">Gemi Tipi</t>
    <t id="8354">Durum</t>
    <t id="8355">RÃ¼tbe</t>
    <t id="8356">Seviye</t>
    <t id="8357">XP</t>
    <t id="8358">KÃ¢r</t>
    <t id="8400">KayÄ±tlÄ± pilot yok</t>
    <t id="8401">Pilot eÅŸleÅŸmesi filtresi yok</t>
    <t id="8402">Toplam Pilotlar:</t>
    <t id="8403">Toplam Filo KarÄ±:</t>
    <t id="8404">Son gÃ¼ncelleme:</t>
    <t id="8405">PilotlarÄ± arayÄ±n...</t>
    <t id="8114">SektÃ¶r</t>
    <t id="8320">Geminin Yeniden AdlandÄ±rÄ±lmasÄ±</t>
    <t id="8321">Ã–zel Ad</t>
    <t id="8322">AdÄ± Ayarla</t>
    <t id="8323">AdÄ± Temizle</t>
    <t id="8324">Ad baÅŸarÄ±yla ayarlandÄ±</t>
    <t id="8325">Ad baÅŸarÄ±yla temizlendi</t>
    <t id="8450">EÄŸitime GÃ¶nder</t>
    <t id="8451">KaydÄ± sil</t>
    <t id="8452">Kargo SatÄ±ÅŸÄ±nÄ± Zorla</t>
    <t id="8453">OnarÄ±ma GÃ¶nder</t>
    <t id="8454">Ä°kmal'e gÃ¶nder</t>
    <t id="8455">TÃ¼m SipariÅŸleri Durdur</t>
    <t id="8456">Eylemler</t>
    <t id="8500">Gemi KimliÄŸine gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8501">Pilot AdÄ±na gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8502">Gemi Tipine gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8503">Duruma gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8504">SÄ±ralamaya gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8505">Seviyeye gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8506">XP'ye gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8507">YaÅŸam Boyu Kazanca gÃ¶re sÄ±ralamak iÃ§in tÄ±klayÄ±n</t>
    <t id="8508">Pilot verilerini gÃ¶rev sisteminden yenile</t>
    <t id="8509">GeÃ§erli gÃ¶rÃ¼nÃ¼mÃ¼ CSV dosyasÄ±na aktar</t>
    <t id="8510">Filo istatistiklerini ve Ã§izelgelerini gÃ¶rÃ¼ntÃ¼leyin</t>
    <t id="8511">MenÃ¼ ayarlarÄ±nÄ± yapÄ±landÄ±rma</t>
    <t id="8512">YardÄ±mÄ± ve klavye kÄ±sayollarÄ±nÄ± gÃ¶ster</t>
    <t id="8600">GalaxyTrader pilot bulunamadÄ±</t>
    <t id="8601">Gemileri GalaxyTrader'e atayarak pilotlar oluÅŸturun veya verilerin yÃ¼klenmesini bekleyin.</t>
    <t id="9001">GT Yeniden adlandÄ±r</t>
    <t id="9902">EÄŸitime GÃ¶nder</t>
    <t id="9903">Manuel eÄŸitim %1 iÃ§in sÄ±raya alÄ±ndÄ±. Pilot mevcut dÃ¶ngÃ¼den sonra eÄŸitime baÅŸlayacak.</t>
    <t id="9904">EÄŸitim mevcut dÃ¶ngÃ¼den sonra kuyruÄŸa alÄ±ndÄ±</t>
    <t id="9905">Pilot veya gemi bulunamadÄ±</t>
    <t id="9906">Otomatik EÄŸitim etkinleÅŸtirildi - manuel sÄ±raya gerek yok</t>
    <t id="9907">Pilotun eÄŸitimi engellenmiyor</t>
    <t id="9910">Ticaret Akademisi</t>
    <t id="9911">Ã‡Ä±rak (Lvl 4) - %1 / %2</t>
    <t id="9912">TÃ¼ccar (Lvl 7) - %1 / %2</t>
    <t id="9913">Usta TÃ¼ccar (Lvl 13) - %1 / %2</t>
    <t id="9920">Pilot %1, %2 Seviyesi iÃ§in Akademi kursuna kaydoldu. En yakÄ±n ticaret istasyonuna doÄŸru yola Ã§Ä±kÄ±yoruz.</t>
    <t id="9921">Bu kurs iÃ§in yeterli fon yok (%1 gerekiyor, %2 var).</t>
    <t id="9922">Kurs kullanÄ±lamÄ±yor - %1 pilotu zaten bu seviyede veya bu seviyede.</t>
    <t id="9923">Pilot %1, %5 gemisinde Trading Academy Seviye %2 kursuna (Ã¼cret: %3 Cr, sÃ¼re: %4 dakika) kaydoldu.</t>
    <t id="11011">GT Ã‡Ä±rak Orta Boy Gemi RedÃ¼ktÃ¶rÃ¼</t>
    <t id="11012">Engine modification that slightly reduces performance for inexperienced pilots on medium ships. Used by GalaxyTrader AI system. -5% speed, thrust and rotation.</t>
    <t id="11013">GT Ã‡Ä±rak Orta Seyahat DÃ¼ÅŸÃ¼rÃ¼cÃ¼</t>
    <t id="11014">Engine modification that slightly reduces travel performance for inexperienced pilots on medium ships. Used by GalaxyTrader AI system. -5% travel speed.</t>
    <t id="11021">GT Ã‡Ä±rak BÃ¼yÃ¼k Gemi RedÃ¼ktÃ¶rÃ¼</t>
    <t id="11022">Engine modification that reduces performance for inexperienced pilots on large ships. Used by GalaxyTrader AI system. -15% speed, thrust and rotation.</t>
    <t id="11023">GT Ã‡Ä±rak BÃ¼yÃ¼k Seyahat RedÃ¼ktÃ¶rÃ¼</t>
    <t id="11024">Engine modification that reduces travel performance for inexperienced pilots on large ships. Used by GalaxyTrader AI system. -15% travel speed.</t>
    <t id="11031">GT Ã‡Ä±rak Sermaye Gemi RedÃ¼ktÃ¶rÃ¼</t>
    <t id="11032">Engine modification that significantly reduces performance for inexperienced pilots on capital ships. Used by GalaxyTrader AI system. -25% speed, thrust and rotation.</t>
    <t id="11033">GT Ã‡Ä±rak Sermayesi Seyahat DÃ¼ÅŸÃ¼rÃ¼cÃ¼</t>
    <t id="11034">Engine modification that significantly reduces travel performance for inexperienced pilots on capital ships. Used by GalaxyTrader AI system. -25% travel speed.</t>
    <t id="12001">GT Temel KÃ¼Ã§Ã¼k Gemi GeliÅŸtirici</t>
    <t id="12002">Specialized engine modification for small ships with basic certified pilots. Used by GalaxyTrader AI system. +3% speed, thrust and rotation.</t>
    <t id="12003">GT Temel KÃ¼Ã§Ã¼k Seyahat GeliÅŸtirici</t>
    <t id="12004">Specialized engine modification for small ships with basic certified pilots. Used by GalaxyTrader AI system. +3% travel speed.</t>
    <t id="13001">GT Temel BÃ¼yÃ¼k Gemi RedÃ¼ktÃ¶rÃ¼</t>
    <t id="13002">Specialized engine modification for large ships with basic certified pilots. Used by GalaxyTrader AI system. -8% speed, thrust and rotation.</t>
    <t id="13003">GT Temel BÃ¼yÃ¼k Seyahat RedÃ¼ktÃ¶rÃ¼</t>
    <t id="13004">Specialized engine modification for large ships with basic certified pilots. Used by GalaxyTrader AI system. -8% travel speed.</t>
    <t id="14001">GT Temel Sermaye Gemi RedÃ¼ktÃ¶rÃ¼</t>
    <t id="14002">Specialized engine modification for capital ships with basic certified pilots. Used by GalaxyTrader AI system. -15% speed, thrust and rotation.</t>
    <t id="14003">GT Temel Sermaye Seyahat RedÃ¼ktÃ¶rÃ¼</t>
    <t id="14004">Specialized engine modification for capital ships with basic certified pilots. Used by GalaxyTrader AI system. -15% travel speed.</t>
    <t id="15001">GT Uzman KÃ¼Ã§Ã¼k Gemi GeliÅŸtirici</t>
    <t id="15002">Advanced engine modification for small ships with expert pilots. Used by GalaxyTrader AI system. +25% speed, thrust and rotation.</t>
    <t id="15003">GT Uzman KÃ¼Ã§Ã¼k Seyahat GeliÅŸtirici</t>
    <t id="15004">Advanced engine modification for small ships with expert pilots. Used by GalaxyTrader AI system. +25% travel speed.</t>
    <t id="16001">GT Uzman BÃ¼yÃ¼k Gemi GeliÅŸtirici</t>
    <t id="16002">Advanced engine modification for large ships with expert pilots. Used by GalaxyTrader AI system. +15% speed, thrust and rotation.</t>
    <t id="16003">GT Uzman BÃ¼yÃ¼k Seyahat GeliÅŸtirici</t>
    <t id="16004">Advanced engine modification for large ships with expert pilots. Used by GalaxyTrader AI system. +15% travel speed.</t>
    <t id="17001">GT Uzman Sermaye Gemi ArttÄ±rÄ±cÄ±</t>
    <t id="17002">Advanced engine modification for capital ships with expert pilots. Used by GalaxyTrader AI system. +6% speed, thrust and rotation.</t>
    <t id="17003">GT Expert Capital Seyahat GeliÅŸtirici</t>
    <t id="17004">Advanced engine modification for capital ships with expert pilots. Used by GalaxyTrader AI system. +6% travel speed.</t>
    <t id="18001">Ciddi Beceri SÄ±nÄ±rlamasÄ± (Gemi)</t>
    <t id="18002">Åžiddetli Beceri SÄ±nÄ±rlamasÄ± (Gemi) - Pilotun bÃ¼yÃ¼k gemilerdeki deneyimsizliÄŸinden kaynaklanan ciddi performans cezalarÄ±nÄ± temsil eder. Pilot becerisinin gemi boyutuna gÃ¶re yetersiz olduÄŸu durumlarda GalaxyTrader sistemi tarafÄ±ndan otomatik olarak uygulanÄ±r. Gemi kÃ¼tlesini arttÄ±rÄ±r. (GT YalnÄ±zca Sistem - Manuel Kurulum Ä°Ã§in KullanÄ±lamaz)</t>
    <t id="18003">Orta Seviye Beceri SÄ±nÄ±rlamasÄ± (Gemi)</t>
    <t id="18004">Orta DÃ¼zeyde Beceri SÄ±nÄ±rlamasÄ± (Gemi) - Pilotun geminin karmaÅŸÄ±klÄ±ÄŸÄ±na uyum saÄŸlamasÄ± nedeniyle orta dÃ¼zeyde performans cezalarÄ±nÄ± temsil eder. Pilot becerisinin gemi boyutuna gÃ¶re yetersiz olduÄŸu durumlarda GalaxyTrader sistemi tarafÄ±ndan otomatik olarak uygulanÄ±r. Gemi kÃ¼tlesini arttÄ±rÄ±r. (GT YalnÄ±zca Sistem - Manuel Kurulum Ä°Ã§in KullanÄ±lamaz)</t>
    <t id="18005">Hafif Beceri SÄ±nÄ±rlamasÄ± (Gemi)</t>
    <t id="18006">Hafif Beceri SÄ±nÄ±rlamasÄ± (Gemi) - Pilot beceri geliÅŸimi sÄ±rasÄ±ndaki kÃ¼Ã§Ã¼k performans cezalarÄ±nÄ± temsil eder. Pilot becerisinin gemi boyutuna gÃ¶re yetersiz olduÄŸu durumlarda GalaxyTrader sistemi tarafÄ±ndan otomatik olarak uygulanÄ±r. Gemi kÃ¼tlesini arttÄ±rÄ±r. (GT YalnÄ±zca Sistem - Manuel Kurulum Ä°Ã§in KullanÄ±lamaz)</t>
    <t id="18007">Ciddi Beceri SÄ±nÄ±rlamasÄ± (Motor)</t>
    <t id="18008">Ciddi Beceri SÄ±nÄ±rlamasÄ± (Motor) - Pilotun bÃ¼yÃ¼k gemilerdeki deneyimsizliÄŸinden kaynaklanan ciddi performans cezalarÄ±nÄ± temsil eder. Pilot becerisinin gemi boyutuna gÃ¶re yetersiz olduÄŸu durumlarda GalaxyTrader sistemi tarafÄ±ndan otomatik olarak uygulanÄ±r. Motor itiÅŸini ve dÃ¶nÃ¼ÅŸÃ¼nÃ¼ azaltÄ±r. (GT YalnÄ±zca Sistem - Manuel Kurulum Ä°Ã§in KullanÄ±lamaz)</t>
    <t id="18009">Orta Derecede Beceri SÄ±nÄ±rlamasÄ± (Motor)</t>
    <t id="18010">Orta DÃ¼zeyde Beceri SÄ±nÄ±rlamasÄ± (Motor) - Pilotun geminin karmaÅŸÄ±klÄ±ÄŸÄ±na uyum saÄŸlamasÄ± nedeniyle orta dÃ¼zeyde performans cezalarÄ±nÄ± temsil eder. Pilot becerisinin gemi boyutuna gÃ¶re yetersiz olduÄŸu durumlarda GalaxyTrader sistemi tarafÄ±ndan otomatik olarak uygulanÄ±r. Motor itiÅŸini ve dÃ¶nÃ¼ÅŸÃ¼nÃ¼ azaltÄ±r. (GT YalnÄ±zca Sistem - Manuel Kurulum Ä°Ã§in KullanÄ±lamaz)</t>
    <t id="18011">Hafif Beceri SÄ±nÄ±rlamasÄ± (Motor)</t>
    <t id="18012">Hafif Beceri SÄ±nÄ±rlamasÄ± (Motor) - Pilot beceri geliÅŸimi sÄ±rasÄ±ndaki kÃ¼Ã§Ã¼k performans cezalarÄ±nÄ± temsil eder. Pilot becerisinin gemi boyutuna gÃ¶re yetersiz olduÄŸu durumlarda GalaxyTrader sistemi tarafÄ±ndan otomatik olarak uygulanÄ±r. Motor itiÅŸini ve dÃ¶nÃ¼ÅŸÃ¼nÃ¼ azaltÄ±r. (GT YalnÄ±zca Sistem - Manuel Kurulum Ä°Ã§in KullanÄ±lamaz)</t>
    <t id="9250">Gemi Durumu AdlandÄ±rmasÄ±</t>
    <t id="9350">Gemi durumu kÄ±saltmalarÄ±nÄ± Ã¶zelleÅŸtirin. VarsayÄ±lan deÄŸerler giriÅŸ kutularÄ±nda gÃ¶sterilir ve geÃ§ersiz kÄ±lÄ±nabilir. Maksimum 3 karakter. TÃ¼m gemi adlarÄ± deÄŸiÅŸtirildiÄŸinde otomatik olarak gÃ¼ncellenecektir.</t>
    <t id="9251">Ä°kmal Durumu KÄ±saltmasÄ±:</t>
    <t id="9252">OnarÄ±m Durumu KÄ±saltmasÄ±:</t>
    <t id="9253">BakÄ±m Durumu KÄ±saltmasÄ±:</t>
    <t id="9254">EÄŸitim Durumu KÄ±saltmasÄ±:</t>
    <t id="9255">Durum KÄ±saltmasÄ±nÄ± Yeniden YÃ¶nlendir:</t>
    <t id="9256">GÃ¼mrÃ¼kleme Durumu KÄ±saltmasÄ±:</t>
    <t id="9257">Engellenen Durum KÄ±saltmasÄ±:</t>
    <t id="9258">Geri DÃ¶nÃ¼ÅŸ Durumu KÄ±saltmasÄ±:</t>
    <t id="9259">YalÄ±tÄ±lmÄ±ÅŸ Durum KÄ±saltmasÄ±:</t>
    <t id="9260">Ticaret Durumu KÄ±saltmasÄ±:</t>
    <t id="9261">BoÅŸta Durumu KÄ±saltmasÄ±:</t>
    <t id="9262">KaÃ§Ä±ÅŸ Durumu KÄ±saltmasÄ±:</t>
    <t id="9268">UlaÅŸÄ±lamaz Durum KÄ±saltmasÄ±:</t>
    <t id="9269">Pilot DeÄŸiÅŸim Durumu KÄ±saltmasÄ±:</t>
    <t id="9270">Ã–zel Kara Liste Ã–neki Etiketi:</t>
    <t id="9700">HILELER (bozuk. burada bir sey yok!! gercekten!!)</t>
    <t id="9701">GT gemileri yenilmez</t>
    <t id="9702">Tum oyuncu gemileri yenilmez</t>
    <t id="9800">Yoluna devam et, pilot. Bunlar bozuk gelistirici test araclari, eglenceli bir dugme menusu degil. Burada bir sey yok. Gercekten. Uyarildin. Muhtemelen.</t>
    <t id="9801">GalaxyTrader emrindeki gemilerin govde ve kalkanlari %100 altina dusmez. Kapatmak icin tekrar tiklayin.</t>
    <t id="9802">Tum oyuncu gemilerinin govde ve kalkanlari %100 altina dusmez. Kapatmak icin tekrar tiklayin. Istasyonlar etkilenmez.</t>
    <t id="9703">GT testi icin evreni ac</t>
    <t id="9704">Acildi</t>
    <t id="9705">Ac</t>
    <t id="9803">Tum sektorlerin savas sisini acar, tum istasyonlari bilinen olarak isaretler, tum fraksiyon ticaret abonelik lisanslarini verir ve galaksi genelinde ticaret tekliflerine abone olur. Yeni DLC sektorlerinden sonra tekrar tiklayin. Yalnizca test icin.</t>
    <t id="9706">Kayitli GT pilot XP sini maksimize et</t>
    <t id="9707">Maksimize edildi</t>
    <t id="9708">XP max</t>
    <t id="9804">GT kayitindaki her pilotu 15. seviye ve maks XP yapar. Egitim engellerini kaldirir. Yalnizca vanilla XP acikken atlanir. Yalnizca test icin.</t>
    <t id="9351">Ä°kmal durumunun kÄ±saltmasÄ± (varsayÄ±lan: RS)</t>
    <t id="9352">OnarÄ±m durumunun kÄ±saltmasÄ± (varsayÄ±lan: RP)</t>
    <t id="9353">BakÄ±m durumunun kÄ±saltmasÄ± (varsayÄ±lan: MT)</t>
    <t id="9354">EÄŸitim durumunun kÄ±saltmasÄ± (varsayÄ±lan: TR)</t>
    <t id="9355">Yeniden YÃ¶nlendirme durumunun kÄ±saltmasÄ± (varsayÄ±lan: RR)</t>
    <t id="9356">AÃ§Ä±klÄ±k durumunun kÄ±saltmasÄ± (varsayÄ±lan: CL)</t>
    <t id="9357">EngellenmiÅŸ durumun kÄ±saltmasÄ± (varsayÄ±lan: BL)</t>
    <t id="9358">Geri dÃ¶nÃ¼ÅŸ durumunun kÄ±saltmasÄ± (varsayÄ±lan: FB)</t>
    <t id="9359">YalÄ±tÄ±lmÄ±ÅŸ durumun kÄ±saltmasÄ± (varsayÄ±lan: IS)</t>
    <t id="9360">Ticaret durumunun kÄ±saltmasÄ± (varsayÄ±lan: TD)</t>
    <t id="9361">BoÅŸta durumunun kÄ±saltmasÄ± (varsayÄ±lan: ID)</t>
    <t id="9362">KaÃ§Ä±ÅŸ durumunun kÄ±saltmasÄ± (varsayÄ±lan: ES)</t>
    <t id="9367">UlaÅŸÄ±lamaz durumun kÄ±saltmasÄ± (varsayÄ±lan: UR)</t>
    <t id="9368">Pilot Exchange durumunun kÄ±saltmasÄ± (varsayÄ±lan: PE)</t>
    <t id="9369">Ã–zel bir grup kara listesinden (astlar dahil) etkilenen MK3 gemiler iÃ§in Ã¶nek olarak gÃ¶sterilir. VarsayÄ±lan: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Ä°stasyon tÃ¼ccarÄ± - istasyon Ã¼rÃ¼nlerini NPC gruplarÄ±na satar</t>
    <t id="30010">Ana Ä°stasyon</t>
    <t id="30011">Maksimum SatÄ±ÅŸ Mesafesi</t>
    <t id="30012">Ticaret KurallarÄ±nÄ± Yoksay</t>
    <t id="30013">EÅŸya Filtresi</t>
    <t id="30014">Kargo Doldurma Hedefi YÃ¼zdesi Sat</t>
    <t id="30015">Geri Ä°zleme ToleransÄ±</t>
    <t id="30016">SatÄ±n Al Kargo Doldurma Hedefi YÃ¼zdesi</t>
    <t id="30017">Seyir Defteri GiriÅŸleri</t>
    <t id="30018">Bildirim DÃ¼zeyi</t>
    <t id="30019">Filo Koordinasyonu</t>
    <t id="30020">Hata AyÄ±klama DÃ¼zeyi</t>
    <t id="30021">Tedarik Ä°stasyonu</t>
    <t id="30022">Min. Ä°stasyon Depolama YÃ¼zdesi</t>
    <t id="30023">YasadÄ±ÅŸÄ± Mallara Ä°zin Ver</t>
    <t id="30024">Kargo/KÃ¢r</t>
    <t id="30025">Ã‡oklu ticarete izin ver</t>
    <t id="30110">MallarÄ±n satÄ±lacaÄŸÄ± oyuncu istasyonu (istasyon atamasÄ± gereklidir)</t>
    <t id="30111">NPC alÄ±cÄ±larÄ±nÄ± bulmak iÃ§in maksimum kapÄ± mesafesi (pilot becerisiyle sÄ±nÄ±rlÄ±dÄ±r)</t>
    <t id="30112">Ä°stasyon ticaret kÄ±sÄ±tlamalarÄ±nÄ± gÃ¶z ardÄ± edin; istasyon ticaret kurallarÄ±na bakÄ±lmaksÄ±zÄ±n herhangi bir dost gruba satÄ±ÅŸ yapÄ±n</t>
    <t id="30113">Ä°steÄŸe baÄŸlÄ± eÅŸya filtresi; tÃ¼m istasyon Ã¼rÃ¼nlerini ve ticari Ã¼rÃ¼nlerini satmak iÃ§in boÅŸ bÄ±rakÄ±n</t>
    <t id="30114">SatÄ±ÅŸ gezilerine Ã§Ä±kmadan Ã¶nce minimum kargo dolum yÃ¼zdesi</t>
    <t id="30115">Bir yolculuÄŸa ikinci bir eÅŸya eklerken izin verilen maksimum ekstra atlamalar (0 = yalnÄ±zca doÄŸrudan rotadaki alÄ±cÄ±lar)</t>
    <t id="30116">Tedarik seferleri iÃ§in kargo dolumunu hedefleyin (yumuÅŸak hedef, tÃ¼ccar daha erken ayrÄ±labilir)</t>
    <t id="30117">Ä°ÅŸlem baÅŸÄ±na kayÄ±t defteri giriÅŸlerini etkinleÅŸtir</t>
    <t id="30118">Bildirim dÃ¼zeyi: 0=Sessiz, 1=Normal, 2=AyrÄ±ntÄ±lÄ±</t>
    <t id="30119">Filo koordinasyonunu ve ticari rezervasyon sistemini etkinleÅŸtirin</t>
    <t id="30120">Hata ayÄ±klama gÃ¼nlÃ¼k kaydÄ± dÃ¼zeyi: 0=KapalÄ±, 1=Normal, 2=AyrÄ±ntÄ±lÄ±</t>
    <t id="30121">EtkinleÅŸtirildiÄŸinde istasyon iÃ§in kaynaklarÄ± da satÄ±n alÄ±n. Depolama minimum eÅŸiÄŸin altÄ±na dÃ¼ÅŸtÃ¼ÄŸÃ¼nde tedarik Ã¶ncelikli hale gelir</t>
    <t id="30122">Herhangi bir kaynak hedefin bu yÃ¼zdesinin altÄ±na dÃ¼ÅŸtÃ¼ÄŸÃ¼nde arz, satÄ±ÅŸa gÃ¶re Ã¶ncelikli hale gelir. Ä°stasyonun kaynaklarÄ± karÅŸÄ±layamamasÄ± durumunda gÃ¶z ardÄ± edilir</t>
    <t id="30123">MÃ¼mkÃ¼n olduÄŸunda yasa dÄ±ÅŸÄ±/kaÃ§ak mallarÄ±n satÄ±lmasÄ±na veya satÄ±n alÄ±nmasÄ±na izin ver</t>
    <t id="30124">SatÄ±ÅŸ seÃ§imi: 1 = Kargo (o mal iÃ§in en yÃ¼ksek depo doluluÄŸu; eÅŸitlikte kÃ¢r), 2 = KÃ¢r (en iyi kÃ¢r skoru)</t>
    <t id="30125">Bir dÃ¶ngÃ¼de birden fazla satÄ±ÅŸÄ± zincirlemeye izin verir (en fazla 3 mal veya hedef). KapatÄ±rsanÄ±z dÃ¶ngÃ¼ baÅŸÄ±na yalnÄ±zca tek iÅŸlem</t>
    <t id="30200">%1 %2, %3'den %4'e satÄ±lÄ±yor</t>
    <t id="30201">%1 atlama aralÄ±ÄŸÄ±nda istasyon Ã¼rÃ¼nleri iÃ§in alÄ±cÄ± bulunamadÄ±</t>
    <t id="30202">%1 ana istasyonu yok edildi - istasyon tÃ¼ccarÄ±nÄ±n sipariÅŸi iptal edildi</t>
    <t id="30203">Ana istasyon %1 artÄ±k oyuncuya ait deÄŸil - sipariÅŸ iptal edildi</t>
    <t id="30204">Ä°stasyon atamasÄ± gerekli - sipariÅŸ iptal edildi</t>
    <t id="30205">MK1 Ä°stasyon TÃ¼ccarÄ± %1'da baÅŸladÄ±</t>
    <t id="30206">Completed sale: %1 %2 sold to %3 for %4 Cr (profit: %5 Cr)</t>
    <t id="30207">Ã‡oklu Ã¼rÃ¼n gezisi: %1 Ã¼rÃ¼nÃ¼n %2 varÄ±ÅŸ noktasÄ±na teslim edilmesi</t>
    <t id="30208">%1 %2, %3'ye %4 tarihinden itibaren saÄŸlanÄ±yor</t>
    <t id="30500">GalaxyTrader MK1 Ayarlar</t>
    <t id="30501">Ä°stasyon TÃ¼ccarÄ± VarsayÄ±lanlarÄ±</t>
    <t id="30502">VarsayÄ±lan Maksimum SatÄ±ÅŸ Mesafesi</t>
    <t id="30503">VarsayÄ±lan SatÄ±ÅŸ Kargo Doldurma Hedefi</t>
    <t id="30504">VarsayÄ±lan Ticaret KurallarÄ±nÄ± Yoksay</t>
    <t id="30505">VarsayÄ±lan Geri Ä°zleme ToleransÄ±</t>
    <t id="30506">HiÃ§bir Ä°ÅŸlem BulunmadÄ±ÄŸÄ±nda Bekleme SÃ¼resi</t>
    <t id="30507">VarsayÄ±lan SatÄ±n Alma Kargo Doldurma Hedefi</t>
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">Ä°stasyon tedariÄŸi ve XP ilerlemeyle otonom madencilik</t>
    <t id="31010">Ana Ä°stasyon</t>
    <t id="31110">Madencilik yapÄ±lacak ve teslim edilecek istasyon (Ä°Ã§ SektÃ¶r ile karÅŸÄ±lÄ±klÄ± olarak Ã¶zel)</t>
    <t id="31011">Ev SektÃ¶rÃ¼</t>
    <t id="31111">Faaliyet gÃ¶sterilecek sektÃ¶r; HiÃ§bir Ana Ä°stasyon ayarlanmadÄ±ÄŸÄ±nda kullanÄ±lÄ±r</t>
    <t id="31012">Kaynak Sepeti</t>
    <t id="31112">Benim iÃ§in mallar; boÅŸ istasyon talep Ã§Ã¶zÃ¼mÃ¼nÃ¼ takip eder</t>
    <t id="31013">Hedef Ä°stasyonlar</t>
    <t id="31113">Teslimatlar iÃ§in isteÄŸe baÄŸlÄ± istasyon filtresi; boÅŸ ev baÄŸlamÄ±ndan kaynaklanÄ±r</t>
    <t id="31014">TaÅŸma EÅŸiÄŸi %</t>
    <t id="31114">Bu depolama yÃ¼zdesine sahip veya Ã¼zerindeki istasyonlar dolu olarak kabul edilir</t>
    <t id="31015">BaÅŸkalarÄ±na TaÅŸma SatÄ±ÅŸÄ±na Ä°zin Ver</t>
    <t id="31115">EtkinleÅŸtirildiÄŸinde ve birincil hedefler dolduÄŸunda diÄŸer grup istasyonlarÄ±na satÄ±ÅŸ yapÄ±n</t>
    <t id="31016">Ä°stasyona Ata</t>
    <t id="31116">Uygun olduÄŸunda gemiyi Ana Ä°stasyonun madencilik astÄ± olarak atayÄ±n</t>
    <t id="31017">Evde KalÄ±n</t>
    <t id="31117">TaÅŸma geri dÃ¶nÃ¼ÅŸ Ã§alÄ±ÅŸmalarÄ± dÄ±ÅŸÄ±nda madenciliÄŸi/satÄ±ÅŸÄ± ana alana kÄ±sÄ±tlayÄ±n</t>
    <t id="31018">Kaynak AraÅŸtÄ±rmalarÄ±nÄ± Otomatik Olarak DaÄŸÄ±t</t>
    <t id="31118">YÃ¼klenen kaynak araÅŸtÄ±rmalarÄ±nÄ± otomatik olarak daÄŸÄ±tÄ±n ve araÅŸtÄ±rmalarÄ± bakÄ±m stokuna dahil edin</t>
    <t id="31019">Maksimum Toplama Mesafesi</t>
    <t id="31119">Toplama iÃ§in maksimum geÃ§it mesafesi (0, pilot/komutan beceri sÄ±nÄ±rÄ±nÄ± kullanÄ±r)</t>
    <t id="31020">Maksimum SatÄ±ÅŸ Mesafesi</t>
    <t id="31120">SatÄ±ÅŸ iÃ§in maksimum kapÄ± mesafesi (0, pilot/komutan beceri sÄ±nÄ±rÄ±nÄ± kullanÄ±r)</t>
    <t id="31021">Filo Dengeleme</t>
    <t id="31121">Ä°stasyon taÅŸmasÄ±nÄ± azaltmak iÃ§in deterministik amaÃ§ koordinasyonunu etkinleÅŸtirin</t>
    <t id="31022">Talep Yeniden Kontrol AralÄ±ÄŸÄ±</t>
    <t id="31122">Madenci talebi/geÃ§iÅŸ deÄŸerlendirmesi ne sÄ±klÄ±kta yapÄ±lÄ±r?</t>
    <t id="31023">Kritik Talep DeltasÄ±</t>
    <t id="31123">Aktif madencilik yazÄ±lÄ±mÄ±nÄ± deÄŸiÅŸtirmek iÃ§in gereken minimum aciliyet deltasÄ±</t>
    <t id="31024">Minimum GeÃ§iÅŸ Bekleme SÃ¼resi</t>
    <t id="31124">Bu gemi iÃ§in iki donanÄ±m anahtarÄ± arasÄ±ndaki minimum sÃ¼re</t>
    <t id="31025">Min Kargo TaahhÃ¼t %'si</t>
    <t id="31125">Kargo dolumu bunun Ã¼zerindeyse gemi geÃ§iÅŸ yapmadan Ã¶nce mevcut teslimatÄ± bitirmeyi tercih eder</t>
    <t id="31026">Sert Acil Durum DeltasÄ±</t>
    <t id="31126">Kargo taahhÃ¼t eÅŸiÄŸine raÄŸmen anÄ±nda geÃ§iÅŸe izin veren aciliyet deltasÄ±</t>
    <t id="31027">Bildirim DÃ¼zeyi</t>
    <t id="31127">Bildirim dÃ¼zeyi: 0=Sessiz, 1=Normal, 2=AyrÄ±ntÄ±lÄ±</t>
    <t id="31028">YalnÄ±zca Oyuncu Ä°stasyonlarÄ±</t>
    <t id="31128">EtkinleÅŸtirildiÄŸinde yalnÄ±zca oyuncunun sahip olduÄŸu istasyonlar talep hedefleri olarak kabul edilir.</t>
    <t id="31031">Ã–nce talebi kontrol et</t>
    <t id="31131">EtkinleÅŸtirildiÄŸinde madenci, madencilikten Ã¶nce istasyon talebini kontrol eder ve kaynaklarÄ± buna gÃ¶re Ã¶nceliklendirir. Devre dÄ±ÅŸÄ± bÄ±rakÄ±ldÄ±ÄŸÄ±nda talep kontrolÃ¼ olmadan kaynak sepetinden madencilik yapar ve bir alÄ±cÄ± bulunana kadar stoklar (tek kaynak filolarÄ± iÃ§in Ã¶nerilir).</t>
    <t id="31032">Fiziksel depo durdurma %</t>
    <t id="31132">Seviye 6+ pilotlar iÃ§in: istasyon fiziksel stoÄŸu ile ilgili madencilerin yoldaki kargosu toplamÄ±, mevcut fiziksel stoÄŸu bu yÃ¼zde kadar aÅŸacaksa mevcut kaynaÄŸÄ± Ã§Ä±karmayÄ± durdurur. CanlÄ± kargo sayÄ±larÄ± kullanÄ±lÄ±r, taÅŸma eÅŸiÄŸi deÄŸil. 0 = devre dÄ±ÅŸÄ±.</t>
    <t id="32002">GalaxyTrader MK4 Temini</t>
    <t id="32102">GT Ã¶nbellek/canlÄ± arama hattÄ±nÄ± kullanan oynatÄ±cÄ± istasyonu tedarik tÃ¼ccarÄ±</t>
    <t id="32010">Kapsama Mesafesi</t>
    <t id="32110">Hedef talep aramasÄ± iÃ§in evden maksimum kapÄ± mesafesi</t>
    <t id="32011">Mesafe SatÄ±n Al</t>
    <t id="32111">TedarikÃ§i aramasÄ± iÃ§in evden maksimum kapÄ± mesafesi</t>
    <t id="32012">YalnÄ±zca Eve Servis YapÄ±n</t>
    <t id="32112">EtkinleÅŸtirildiÄŸinde yalnÄ±zca ana istasyon talebi karÅŸÄ±lanÄ±r</t>
    <t id="32013">YalnÄ±zca Ä°nÅŸaat Ä°stasyonlarÄ±</t>
    <t id="32113">EtkinleÅŸtirildiÄŸinde yalnÄ±zca derleme depolama talebi sunulur</t>
    <t id="32014">Player'dan SatÄ±n Al</t>
    <t id="32114">OyuncularÄ±n sahip olduÄŸu tedarikÃ§ilerden Ã¼rÃ¼n tedarik edilmesine izin ver</t>
    <t id="32015">Faction'dan satÄ±n alÄ±n</t>
    <t id="32115">Oyuncu olmayan grup tedarikÃ§ilerinden Ã¼rÃ¼n tedarik edilmesine izin ver</t>
    <t id="32016">Kaynaklara Ä°zin Ver</t>
    <t id="32116">Kaynak Ã¼rÃ¼nlerini talep eÅŸleÅŸtirmeye dahil edin</t>
    <t id="32017">Ara ÃœrÃ¼nlere Ä°zin Ver</t>
    <t id="32117">Ara mallarÄ± talep eÅŸleÅŸtirmeye dahil edin</t>
    <t id="32018">ÃœrÃ¼nlere Ä°zin Ver</t>
    <t id="32118">ÃœrÃ¼n mallarÄ±nÄ± talep eÅŸleÅŸtirmeye dahil edin</t>
    <t id="32019">Ticari ÃœrÃ¼nlere Ä°zin Ver</t>
    <t id="32119">Talep eÅŸleÅŸtirmeye ticari yazÄ±lÄ±m Ã¼rÃ¼nlerini dahil edin</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">Depolama eÅŸik yÃ¶netimi ile depo daÄŸÄ±tÄ±mÄ±</t>
    <t id="20010">Kaynak Ä°stasyonlarÄ±</t>
    <t id="20011">Hedef Ä°stasyonlar</t>
    <t id="20012">Minimum Depolama YÃ¼zdesi</t>
    <t id="20013">Statik Depolama %'si</t>
    <t id="20014">Maksimum Depolama YÃ¼zdesi</t>
    <t id="20015">EÅŸya Filtresi</t>
    <t id="20016">Ã‡ift YÃ¶nlÃ¼ Mod</t>
    <t id="20017">Ana Ä°stasyon (isteÄŸe baÄŸlÄ±)</t>
    <t id="20018">Maksimum Mesafe</t>
    <t id="20032">Ana SektÃ¶r (isteÄŸe baÄŸlÄ±)</t>
    <t id="20019">DÃ¶ngÃ¼ Bekleme SÃ¼resi</t>
    <t id="20030">DÃ¼ÅŸÃ¼k Hacme Ä°zin Ver</t>
    <t id="20031">DÃ¼ÅŸÃ¼k Hacimli Kat %</t>
    <t id="20110">MallarÄ±n daÄŸÄ±tÄ±lacaÄŸÄ± kaynak istasyonlarÄ±nÄ±n listesi</t>
    <t id="20111">MallarÄ±n daÄŸÄ±tÄ±lacaÄŸÄ± varÄ±ÅŸ istasyonlarÄ±nÄ±n/depolarÄ±nÄ±n listesi</t>
    <t id="20112">Hedef aciliyet eÅŸiÄŸi: bu depolama yÃ¼zdesinin altÄ±ndaki istasyonlar Ã¶ncelikli teslimatlarÄ± alÄ±r</t>
    <t id="20113">Kaynak minimum eÅŸiÄŸi: kaynaÄŸÄ±n daÄŸÄ±tÄ±labilmesi iÃ§in bu yÃ¼zdeden daha fazlasÄ±na sahip olmasÄ± gerekir</t>
    <t id="20114">Kaynak taÅŸma eÅŸiÄŸi: bu %'nin Ã¼zerinde kaynak, acil olmayan hedeflere bile daÄŸÄ±tÄ±m yapar</t>
    <t id="20115">Ä°steÄŸe baÄŸlÄ± eÅŸya filtresi; TÃ¼m mallarÄ± kaynaktan daÄŸÄ±tmak iÃ§in boÅŸ bÄ±rakÄ±n</t>
    <t id="20116">Hedeflerde fazlalÄ±k olduÄŸunda, destinasyonlardan kaynaÄŸa dÃ¶nÃ¼ÅŸ yolculuÄŸu toplamayÄ± etkinleÅŸtirin</t>
    <t id="20117">Atama iÃ§in isteÄŸe baÄŸlÄ± ana istasyon. BoÅŸsa gemi istasyonlara atanmamÄ±ÅŸ olarak kalÄ±r.</t>
    <t id="20118">Kaynak ve hedefler arasÄ±ndaki maksimum kapÄ± mesafesi (0 = sÄ±nÄ±rsÄ±z)</t>
    <t id="20132">Ana istasyon ayarlanmadÄ±ÄŸÄ±nda BoÅŸta Park Etme iÃ§in kullanÄ±lan isteÄŸe baÄŸlÄ± ana sektÃ¶r.</t>
    <t id="20119">DaÄŸÄ±tÄ±m dÃ¶ngÃ¼leri arasÄ±nda bekleme sÃ¼resi</t>
    <t id="20130">Aciliyete duyarlÄ± teslimat parÃ§alarÄ±nÄ±n normal minimum kargo dolumunun altÄ±nda olmasÄ±na izin verin.</t>
    <t id="20131">DÃ¼ÅŸÃ¼k hacimli mod etkinleÅŸtirildiÄŸinde kullanÄ±lan minimum kargo dolumu yÃ¼zdesi.</t>
    <t id="20200">%1 %2 %3'den %4'e daÄŸÄ±tÄ±lÄ±yor</t>
    <t id="20201">DÃ¶nÃ¼ÅŸ yolculuÄŸu: %1 %2 toplu taÅŸÄ±ma ile %3'den %4'e</t>
    <t id="20202">DaÄŸÄ±tÄ±ma gerek yok; tÃ¼m destinasyonlara yeterli dÃ¼zeyde tedarik saÄŸlanÄ±yor</t>
    <t id="20203">Tum kaynak istasyonlar gecersiz - dagitim beklemede</t>
    <t id="20204">Tum hedef istasyonlar gecersiz - dagitim beklemede</t>
    <t id="20205">Kaynak istasyon %1 imha edildi - dagitim emrinden kaldirildi</t>
    <t id="20206">Hedef istasyon %1 imha edildi - dagitim emrinden kaldirildi</t>
    <t id="20500">GalaxyTrader MK2 - Genel Ayarlar</t>
    <t id="20501">MK2 DaÄŸÄ±tÄ±m VarsayÄ±lanlarÄ±</t>
    <t id="20510">VarsayÄ±lan Minimum Depolama YÃ¼zdesi</t>
    <t id="20511">VarsayÄ±lan Statik Depolama YÃ¼zdesi</t>
    <t id="20512">VarsayÄ±lan Maksimum Depolama YÃ¼zdesi</t>
    <t id="20513">VarsayÄ±lan DÃ¶ngÃ¼ Bekleme(ler)i</t>
    <t id="20514">Minimum Kargo Doldurma YÃ¼zdesi</t>
    <t id="20520">Bildirim AyrÄ±ntÄ±larÄ±</t>
    <t id="20521">Hata AyÄ±klama DÃ¼zeyi</t>
    <t id="10006">Eve DÃ¶nÃ¼ÅŸ</t>
    <t id="10007">GalaxyTrader MK4-2 Tedarik</t>
    <t id="10106">Ana istasyona yanaÅŸÄ±n ve ticaret devam edene kadar orada kalÄ±n</t>
    <t id="10107">Teslimat hedefi Ã¶ncelik kaydÄ±rÄ±cÄ±larÄ±yla oyuncu tedarik emri</t>
    <t id="30026">DÃ¶ngÃ¼ler ArasÄ±nda Eve DÃ¶nÃ¼ÅŸ</t>
    <t id="30028">Teklif ayarlarÄ±nÄ± yoksay</t>
    <t id="30029">AlÄ±cÄ± fiyat aralÄ±ÄŸÄ±</t>
    <t id="30027">Min. ÃœrÃ¼n Depolama %</t>
    <t id="30126">EtkinleÅŸtirildiÄŸinde, ana istasyona dÃ¶nÃ¼n ve ticaret dÃ¶ngÃ¼leri arasÄ±nda yanaÅŸÄ±n. Devre dÄ±ÅŸÄ± bÄ±rakÄ±ldÄ±ÄŸÄ±nda, mevcut konumdan aramaya devam edin (eski davranÄ±ÅŸ)</t>
    <t id="30128">Ä°stasyon alÄ±m/satÄ±ÅŸ teklifleri olmadan dahili depo transferlerine izin ver. Tampon alÄ±m ve teslimat iÃ§in mal deÄŸiÅŸimi kullanÄ±r. Ticaret kurallarÄ±nÄ± yoksay kapalÄ±yken istasyon ticaret kurallarÄ± geÃ§erlidir.</t>
    <t id="30129">Ä°stasyon Ã¼rÃ¼nleri satÄ±lÄ±rken NPC alÄ±cÄ±lar iÃ§in minimum gÃ¶reli fiyat. Emir kaydÄ±rÄ±cÄ±sÄ± 0-200 (100 = ortalama, 0 = -100%, 200 = +100%), -1,0..+1,0 ile eÅŸlenir. Daha yÃ¼ksek = yalnÄ±zca pahalÄ± alÄ±cÄ±lar. Daha dÃ¼ÅŸÃ¼k = daha fazla alÄ±cÄ± seÃ§eneÄŸi. Tedarik koÅŸularÄ± tedarikÃ§i fiyat Ã¼st sÄ±nÄ±rlarÄ± iÃ§in ters deÄŸeri kullanÄ±r.</t>
    <t id="30127">Bir Ã¼rÃ¼n veya ticari mal satÄ±lmadan Ã¶nce gereken minimum istasyon depolama doluluk yÃ¼zdesi (mal baÅŸÄ±na yapÄ±landÄ±rÄ±lmÄ±ÅŸ maksimuma gÃ¶re). Bu eÅŸiÄŸin altÄ±ndaki mallar atlanÄ±r. 0 = minimum yok.</t>
    <t id="3107">Ã‡oklu ticaret sÄ±raya alÄ±nÄ±yor: %1. %2 kar elde etmeliyim.</t>
    <t id="3108">%1 %2, %3 konumundan %4 fiyatÄ±na satÄ±lÄ±yor. %5 kar elde etmeliyim.</t>
    <t id="3110">%1 %2 tedarik gÃ¶revi sÄ±raya alÄ±nÄ±yor. %4 konumundan %3 fiyatÄ±na tedarik, %5 konumuna teslimat. MÃ¼ÅŸteri alÄ±ÅŸ Ã¼st limiti %6 - limitin %7/birim altÄ±nda (%8 toplam).</t>
    <t id="3111">%1 %2 tedariki sÄ±raya alÄ±nÄ±yor: %3'ten %4'e.</t>
    <t id="3112">Tedarik sÄ±raya alÄ±ndÄ± (%1 bacak): %2. MÃ¼ÅŸteri alÄ±ÅŸ limitinin toplam %3 altÄ±nda.</t>
    <t id="3113">Ä°stasyon TÃ¼ccarÄ±: ihracat Ã§oklu ticaret sÄ±raya alÄ±nÄ±yor: %1. Beklenen kÃ¢r %2.</t>
    <t id="31029">Prob Stok Hedefi</t>
    <t id="31030">SatÄ±n AlÄ±nacak Madencilik DronlarÄ±</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: madenciliÄŸe uygun kaynak yok. Gemi %1 [%2], Filo: %3</t>
    <t id="31201">Galaxy-Miner: Ana Ä°stasyon veya ev konumunu ayarlayÄ±n.</t>
    <t id="31130">Madenci, ihtiyaÃ§ duyduÄŸu tÃ¼r (katÄ±/cevher veya sÄ±vÄ±/gaz) tÃ¼kendiÄŸinde kaÃ§ toplayÄ±cÄ± (madencilik) dronu satÄ±n alÄ±r. SatÄ±n alma YALNIZCA gemide o tÃ¼rden toplayÄ±cÄ± kalmadÄ±ÄŸÄ±nda (sayÄ± = 0) tetiklenir; hÃ¢lÃ¢ en az bir tane bulunan bir madenci asla yeniden doldurulmaz veya yeniden satÄ±n alÄ±nmaz, mevcut dronlar korunur. Geminin birim yuvasÄ± kapasitesiyle sÄ±nÄ±rlÄ±dÄ±r. ToplayÄ±cÄ± dron otomatik satÄ±n almayÄ± kapatmak ve dronlarÄ± elle yÃ¶netmek iÃ§in 0 olarak ayarlayÄ±n. VarsayÄ±lan 5, normal madencilik hÄ±zÄ± iÃ§in tam bir dron setidir.</t>
    <t id="31129">Madencinin yeniden stoklama gezisi baÅŸÄ±na satÄ±n aldÄ±ÄŸÄ± kaynak araÅŸtÄ±rmalarÄ±nÄ±n sayÄ±sÄ±. SatÄ±n alma, her konuÅŸlandÄ±rmada deÄŸil, YALNIZCA gemideki sondalar bittiÄŸinde (sayÄ± = 0) tetiklenir; bu ÅŸekilde madenci, her konuÅŸlandÄ±rmadan sonra yoldan sapmak yerine tedarik Ã§alÄ±ÅŸmalarÄ± arasÄ±nda tÃ¼m sonda yÃ¼kÃ¼nÃ¼ tamamlar. Geminin toplam konuÅŸlandÄ±rÄ±labilir kapasitesiyle sÄ±nÄ±rlÄ±dÄ±r (uydular/mayÄ±nlar/vb. ile paylaÅŸÄ±lÄ±r); boÅŸ konuÅŸlandÄ±rÄ±labilir alandan daha bÃ¼yÃ¼k bir kaydÄ±rÄ±cÄ± deÄŸeri, "uygun olanÄ± dolduracak" ÅŸekilde zarif bir ÅŸekilde bozulur. YalnÄ±zca Kaynak AraÅŸtÄ±rmalarÄ±nÄ± Otomatik Olarak DaÄŸÄ±t etkinleÅŸtirildiÄŸinde etkili olur; aynÄ± ayar aynÄ± zamanda madencilik sektÃ¶rlerinde fÄ±rsatÃ§Ä± araÅŸtÄ±rma daÄŸÄ±tÄ±mÄ±nÄ± ve eski araÅŸtÄ±rmalarÄ±n (sepetle ilgili kaynaklara sahip olmayan sektÃ¶rlerdeki araÅŸtÄ±rmalarÄ±n) toplanmasÄ±nÄ± da saÄŸlar.</t>
    <t id="3226">Komutan %1,\n\n%2 noktasÄ±na yanaÅŸtÄ±m ve Ticaret Akademisi kayÄ±t memuru "%3" programÄ±na kaydÄ±mÄ± onayladÄ±. Kurs Ã¼creti iÃ§in filo hesabÄ±ndan %4 Cr borÃ§landÄ±rÄ±ldÄ± ve bu yatÄ±rÄ±mÄ± hafife almÄ±yorum.\n\nBu rutin bir sertifikasyon deÄŸil. Akademinin eÄŸitmenleri deneyimli tÃ¼ccarlar ve konsorsiyum mÃ¼zakerecilerinden oluÅŸuyor ve buradaki mÃ¼fredat standart ilerleme sÄ±navÄ±ndan Ã§ok daha zorlu. Ã–nÃ¼mÃ¼zdeki %5 dakika iÃ§inde geliÅŸmiÅŸ ticaret protokolleri, baskÄ± altÄ±ndaki piyasa analizi ve Ã§Ä±raklarÄ± ustalardan ayÄ±ran mÃ¼zakere taktikleri hakkÄ±nda yoÄŸun bir eÄŸitimden geÃ§eceÄŸim.\n\nFinal sÄ±navÄ± tamamlanÄ±p kenetlendiÄŸimde, "%3" unvanÄ±nÄ± taÅŸÄ±yacaÄŸÄ±m ve Ã¶ÄŸrendiÄŸim her ÅŸeyi ticaret operasyonlarÄ±mÄ±za geri getireceÄŸim. Bu fÄ±rsatÄ±n tek bir kredisini bile boÅŸa harcamayacaÄŸÄ±m.\n\nMinnettarlÄ±kla ve kararlÄ±lÄ±kla\n%6\nGemiye %7</t>
    <t id="9924">Trading Academy kursu iptal edildi: %1 pilotu, akademi iskelesindeki %2 Cr Ã¼cretini karÅŸÄ±layamÄ±yor (%3 Cr'ye sahip). Kurs iptal edildi, pilot ticarete devam etti.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="359">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Ð”Ð¾Ðº Ð¸ Ð¸Ð·Ñ‡Ð°ÐºÐ°Ð¹Ñ‚Ðµ (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">Ð¤Ð¸Ð½Ð°Ð»ÐµÐ½ Ð¸Ð·Ð¿Ð¸Ñ‚ (GalaxyTrader MK3)</t>
    <t id="10004">Ð Ð°Ð½Ð´ÐµÐ²Ñƒ Ð·Ð° Ð¾Ð±Ð¼ÐµÐ½ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸</t>
    <t id="10005">[ÐžÐ¡Ð¢ÐÐ Ð¯Ð›Ðž] GalaxyTrader Ð”Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð½Ð° MK4 (ÐžÑÑ‚Ð°Ñ€ÑÐ»)</t>
    <t id="10101">ÐÐºÐ¾ÑÑ‚Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð½Ð° Ð³Ð°Ñ€Ð°Ñ‚Ð° Ð¸ Ð¸Ð·Ñ‡Ð°ÐºÐ°Ð¹Ñ‚Ðµ Ð¾Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¾Ñ‚Ð¾ Ð²Ñ€ÐµÐ¼Ðµ</t>
    <t id="10102">ÐÐ²Ñ‚Ð¾Ð½Ð¾Ð¼Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ñ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÐ¸Ñ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð°</t>
    <t id="10103">Ð’Ð·ÐµÐ¼ÐµÑ‚Ðµ Ð¾ÐºÐ¾Ð½Ñ‡Ð°Ñ‚ÐµÐ»ÐµÐ½ Ð¸Ð·Ð¿Ð¸Ñ‚ Ð·Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚ Ð² ÑƒÑ‡ÐµÐ±Ð½Ð¾ Ð·Ð°Ð²ÐµÐ´ÐµÐ½Ð¸Ðµ</t>
    <t id="10104">ÐŸÑ€Ð¸ÑÑ‚Ð°Ð½ÐµÑ‚Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð° Ð·Ð° ÑÑ€ÐµÑ‰Ð° Ð·Ð° Ñ€Ð°Ð·Ð¼ÑÐ½Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸</t>
    <t id="10105">Ð¤Ð¾ÐºÑƒÑÐ¸Ñ€Ð°Ð½Ð° Ð²ÑŠÑ€Ñ…Ñƒ Ð¿Ñ€ÐµÐ´Ð»Ð°Ð³Ð°Ð½ÐµÑ‚Ð¾ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð·Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸, Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ñ‰Ð¸ ÐºÐµÑˆ Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾ (ÐžÑÑ‚Ð°Ñ€ÑÐ»)</t>
    <t id="10201">ÐšÑƒÐ¿ÐµÑ‚Ðµ %s Ð¾Ñ‚ %s</t>
    <t id="10202">ÐŸÑ€Ð¾Ð´Ð°Ð¹Ñ‚Ðµ %s Ð½Ð° %s</t>
    <t id="10203">Ð¢ÑŠÑ€Ð³ÑƒÐ²Ð°Ð¹Ñ‚Ðµ Ñ %s</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">Ð Ð°Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ñ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÐ¸Ñ€Ð°Ð½Ðµ Ð½Ð° XP Ð¸ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="1002">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð° Ð±Ð°Ð·Ð°</t>
    <t id="1003">Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ð¿Ñ€ÐµÐ´Ð²Ð°Ñ€Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð·Ð°Ð´Ð°Ð´ÐµÐ½Ð¸ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="1004">Ð¢ÑŠÑ€Ð³ÑƒÐ²Ð°Ð¹Ñ‚Ðµ Ñ Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1005">Ð¢ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ñ Ð»ÐµÐ³Ð°Ð»Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1006">Ð¢ÑŠÑ€Ð³ÑƒÐ²Ð°Ð¹Ñ‚Ðµ Ñ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1007">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÐ¸ÑÑ‚Ð° Ð½Ð° XP</t>
    <t id="1008">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÑÑ‚Ð° Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="1009">Ð Ð°Ð·Ñ€ÐµÑˆÐµÑ‚Ðµ Ð°Ð½Ð°Ð»Ð¸Ð· Ð½Ð° Ð¿Ð°Ð·Ð°Ñ€Ð°</t>
    <t id="1010">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ð¸ÑÑ‚Ð°</t>
    <t id="1011">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1012">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð±Ð¾Ñ€Ð´Ð¾Ð²Ð¸Ñ Ð´Ð½ÐµÐ²Ð½Ð¸Ðº</t>
    <t id="1013">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ ÐºÑŠÐ¼ Ñ€Ð¸ÑÐºÐ°</t>
    <t id="1014">Ð”Ð°Ð¹Ñ‚Ðµ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸Ñ‚Ðµ</t>
    <t id="1015">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1016">ÐÐ°ÐºÐ°Ð·Ð°Ñ‚ÐµÐ»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ %</t>
    <t id="1017">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ</t>
    <t id="1018">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="1019">Ð¦ÐµÐ»ÐµÐ²Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð°</t>
    <t id="1050">Ð§ÐµÑÑ‚Ð¾Ñ‚Ð° Ð½Ð° Ð°ÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¿Ð°Ð·Ð°Ñ€Ð°</t>
    <t id="1051">Ð ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ° Ð¾Ñ†ÐµÐ½ÐºÐ°</t>
    <t id="1052">Ð‘ÑÐ» ÑÐ¿Ð¸ÑÑŠÐº Ð½Ð° ÑÐµÐºÑ‚Ð¾Ñ€Ð¸</t>
    <t id="1054">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Carrier/Aux Ships</t>
    <t id="1056">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Build Storage</t>
    <t id="1058">ÐŸÑ€ÐµÐ½ÐµÐ±Ñ€ÐµÐ³Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð°</t>
    <t id="1060">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ, Ð´Ð¾ÑÑ‚Ð°Ð²ÐµÐ½Ð¸ Ð¾Ñ‚ MK1</t>
    <t id="1063">Ð’ Ð¿Ñ€Ð¾Ñ†ÐµÑ Ð½Ð° Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°</t>
    <t id="1064">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1065">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ÐµÐ½ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ %</t>
    <t id="1066">ÐŸÑ€ÐµÐ´Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð°Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð¿Ñ€Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¾ Ð¾Ñ†ÐµÐ½ÑÐ²Ð°Ð½Ðµ. Ð ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ÑŠÑ‚ Ð¸Ð¼ ÑÐµ ÑƒÐ¼Ð½Ð¾Ð¶Ð°Ð²Ð° Ð¿Ð¾ % Ð½Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸Ñ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚.</t>
    <t id="1067">ÐœÐ½Ð¾Ð¶Ð¸Ñ‚ÐµÐ» Ð½Ð° Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚Ð° Ð·Ð° ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸: 100%=Ð½Ð¾Ñ€Ð¼Ð°Ð»Ð½Ð¾, 150%=+50%%, 200%=2x, 300%=3x. ÐŸÑ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¾ Ð¿Ð¾ÑÐ»ÐµÐ´Ð½Ð¾.</t>
    <t id="1068">â”€â”€ Ð¤Ð¸Ð»Ñ‚ÑŠÑ€ Ð½Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸ â”€â”€</t>
    <t id="1069">Ð¡Ñ‚Ð¾ÐºÐ¸ (Ñ€ÑŠÑ‡Ð½Ð¾)</t>
    <t id="1070">Ð¤Ð¸Ð»Ñ‚ÑŠÑ€ Ð·Ð° Ð½ÐµÐ·Ð°ÐºÐ¾Ð½ÐµÐ½ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚</t>
    <t id="1072">Ð¡ÐµÑ€Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÐ°Ð¼Ð¾ Ñƒ Ð´Ð¾Ð¼Ð°</t>
    <t id="1073">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ðº Ð¸Ð³Ñ€Ð°Ñ‡</t>
    <t id="1074">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ðº Ñ„Ñ€Ð°ÐºÑ†Ð¸Ñ</t>
    <t id="1075">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Build Storage</t>
    <t id="1076">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="1077">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ð¼ÐµÐ¶Ð´Ð¸Ð½Ð½Ð¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="1078">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="1080">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸ Ð½Ð° Ñ†Ð¸ÐºÑŠÐ»</t>
    <t id="1081">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ ÐºÑŠÐ¼ Ð²Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð½Ð°Ð·Ð°Ð´</t>
    <t id="1082">ÐœÐ¸Ð½. Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð½ Ñ‚Ð¾Ð²Ð°Ñ€ %</t>
    <t id="1083">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ‚Ð¾Ñ€ Ð·Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡ %</t>
    <t id="1085">ÐŸÑ€Ð¸ÑÐ²Ð¾ÑÐ²Ð°Ð½Ðµ Ð½Ð° Home Station</t>
    <t id="1086">Ð Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ð¸Ðµ</t>
    <t id="1088">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð·Ð° ÑÐºÐ¾Ðº Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð·Ð° Ð¿Ð¾ÐºÑ€Ð¸Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="1090">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ ÑÑ‚Ð¾ÐºÐ¸ Ð¾Ñ‚ ÐºÐ»Ð°Ñ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÐ¾Ñ„Ñ‚ÑƒÐµÑ€ Ð² ÑÑŠÐ¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾/Ð¿Ñ€ÐµÐ´Ð»Ð°Ð³Ð°Ð½ÐµÑ‚Ð¾</t>
    <t id="1091">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ‚Ð¾Ñ€, Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½ ÐºÑŠÐ¼ Ñ†ÐµÐ½Ð¸Ñ‚Ðµ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ñ†Ð¸, Ð¿Ñ€Ð¸Ñ‚ÐµÐ¶Ð°Ð²Ð°Ð½Ð¸ Ð¾Ñ‚ Ð¸Ð³Ñ€Ð°Ñ‡Ð¸, Ð¿Ñ€Ð¸ Ð¸Ð·Ñ‡Ð¸ÑÐ»ÐµÐ½Ð¸Ñ ÑÐ°Ð¼Ð¾ Ð·Ð° Ñ‚Ð¾Ñ‡ÐºÑƒÐ²Ð°Ð½Ðµ</t>
    <t id="1092">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ñ†ÐµÐ½Ð¸Ñ‚Ðµ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸Ñ‚Ðµ</t>
    <t id="1093">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾: Ð²Ð¸Ð½Ð°Ð³Ð¸ ÐºÑƒÐ¿ÑƒÐ²Ð°Ð¹Ñ‚Ðµ Ð¾Ñ‚ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, Ð¿Ñ€Ð¸Ñ‚ÐµÐ¶Ð°Ð²Ð°Ð½Ð¸ Ð¾Ñ‚ Ð¸Ð³Ñ€Ð°Ñ‡Ð¸, Ð½ÐµÐ·Ð°Ð²Ð¸ÑÐ¸Ð¼Ð¾ Ð¾Ñ‚ Ñ‚ÐµÑ…Ð½Ð¸Ñ‚Ðµ Ð·Ð°Ð´Ð°Ð´ÐµÐ½Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð½Ð¸ Ñ†ÐµÐ½Ð¸, Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ ÑÐ°Ð¼Ð¾ Ð½Ð° NPC Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸. ÐŸÐ¾Ð»ÐµÐ·Ð½Ð¾ Ð·Ð° Ð»Ð¸ÐºÐ²Ð¸Ð´Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¸Ð·Ð»Ð¸ÑˆÐ½Ð¸ Ð·Ð°Ð¿Ð°ÑÐ¸ Ð¾Ñ‚ Ð²Ð°ÑˆÐ¸Ñ‚Ðµ ÑÐ¾Ð±ÑÑ‚Ð²ÐµÐ½Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸.</t>
    <t id="1094">Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="1095">Ð˜Ð·Ð±Ñ€Ð°Ð½Ð¸Ñ‚Ðµ Ñ‚ÑƒÐº ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ ÑÐµ Ð¸Ð·ÐºÐ»ÑŽÑ‡Ð²Ð°Ñ‚ Ð¾Ñ‚ MK3 Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð°. Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ†ÑŠÑ‚ Ð½ÑÐ¼Ð° Ð½Ð¸Ñ‚Ð¾ Ð´Ð° ÐºÑƒÐ¿ÑƒÐ²Ð° Ð¾Ñ‚ Ñ‚ÑÑ…, Ð½Ð¸Ñ‚Ð¾ Ð´Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð° Ð½Ð° Ñ‚ÑÑ….</t>
    <t id="1096">ÐŸÐ°Ñ€ÐºÐ¸Ñ€Ð°Ð½Ðµ Ð¿Ñ€Ð¸ Ð¿Ñ€ÐµÑÑ‚Ð¾Ð¹</t>
    <t id="1097">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¼Ð½Ð¾Ð³Ð¾ÐºÑ€Ð°Ñ‚Ð½Ð¾ Ð½Ðµ Ð½Ð°Ð¼Ð¸Ñ€Ð°Ñ‚ Ñ€Ð°Ð±Ð¾Ñ‚Ð°, Ð¿Ð°Ñ€ÐºÐ¸Ñ€Ð°Ñ‚ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð°Ñ‚Ð° ÑÐ¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð¸Ð»Ð¸ Ð² Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ñ ÑÐµÐºÑ‚Ð¾Ñ€. ÐŸÐ°Ñ€ÐºÐ¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð°, Ð¿Ð¾ÑÐ»Ðµ Ð¿Ñ€Ð¸ÑÑ‚ÐµÐ»ÑÐºÐ¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸. Ð’Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð´Ð¾ÐºÐ° ÑÐµ Ð·Ð°Ð´Ð°Ð²Ð° Ð² Ð³Ð»Ð¾Ð±Ð°Ð»Ð½Ð¸Ñ‚Ðµ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ (0 = Ð¾ÑÑ‚Ð°Ð²Ð° Ð½Ð° Ð´Ð¾Ðº, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð½Ðµ Ð±ÑŠÐ´Ðµ Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð°).</t>
    <t id="1098">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¼Ð°Ñ‰Ð°Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="1099">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, Ð¿Ð»ÑŠÐ·Ð³Ð°Ñ‡Ð¸Ñ‚Ðµ Ð·Ð° Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ð° ÑÐºÐ¾Ðº ÑÐµ Ð·Ð°Ð´Ð°Ð²Ð°Ñ‚ Ð½Ð° Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ð´Ð¾Ð¿ÑƒÑÑ‚Ð¸Ð¼Ð¸Ñ Ð¾Ð±Ñ…Ð²Ð°Ñ‚ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° ÑÐ»ÐµÐ´ Ð·Ð°Ð´ÑŠÐ»Ð¶Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð¸Ð»Ð¸ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ²Ð°Ð½Ðµ Ð½Ð° Ð¢ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ°Ñ‚Ð° Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸Ñ. ÐŸÑ€ÐµÐ¼Ð°Ñ…Ð½ÐµÑ‚Ðµ Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ°Ñ‚Ð° Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð·Ð°Ð´Ð°Ð²Ð°Ð½Ðµ.</t>
    <t id="11001">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° ÑÐºÐ»Ð°Ð´ Ð·Ð° ÑÑ‚Ñ€Ð¾ÐµÐ¶</t>
    <t id="11002">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="11003">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° ÑÐ¿Ð¾Ð¼Ð°Ð³Ð°Ñ‚ÐµÐ»Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸</t>
    <t id="11004">ÐŸÑ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° ÑÐ°Ð¼Ð¾Ð»ÐµÑ‚Ð¾Ð½Ð¾ÑÐ°Ñ‡Ð¸</t>
    <t id="11005">0 = Ð¸Ð·ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾. 1-10 = Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ» Ð½Ð° Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ (10 = Ð½Ð°Ð¹-ÑÐ¸Ð»ÐµÐ½ Ð°ÐºÑ†ÐµÐ½Ñ‚). ÐšÑ€Ð°ÐµÐ½ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ = Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ Ã— Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ».</t>
    <t id="11006">1 = Ð±ÐµÐ· Ð´Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»ÐµÐ½ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ (ÑÐ¿Ð¸ÑÑŠÐºÑŠÑ‚ Ñ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð½Ðµ ÑÐµ Ð¿Ñ€Ð¾Ð¼ÐµÐ½Ñ). 2-10 = Ð´Ð¾Ð±Ð°Ð²Ñ (Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»âˆ’1)Ã— Ð±Ð°Ð·Ð¾Ð² Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ, Ð°ÐºÐ¾ ÑÑ‚Ð¾ÐºÐ°Ñ‚Ð° Ðµ Ð² Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº. ÐŸÑ€Ð¸Ð»Ð°Ð³Ð° ÑÐµ Ð²ÑŠÑ€Ñ…Ñƒ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚Ð° Ð¿Ð¾ Ñ‚Ð¸Ð¿.</t>
    <t id="11007">Ð‘Ð¾Ð½ÑƒÑ Ð·Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="11008">%1: Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ð»ÑŠÐ·Ð³Ð°Ñ‡Ð¸ Ð·Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° Ñ†ÐµÐ»Ð¸Ñ‚Ðµ Ð·Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° ÑÐ° Ð½Ð° 0 - Ñ‚Ð°Ð·Ð¸ Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ° Ð½ÑÐ¼Ð° Ñ†ÐµÐ»Ð¸ Ð·Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ°. ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¿Ð¾Ð½Ðµ ÐµÐ´Ð¸Ð½ ÐºÐ»Ð°Ñ (ÑÐºÐ»Ð°Ð´ Ð·Ð° ÑÑ‚Ñ€Ð¾Ð¸Ñ‚ÐµÐ»ÑÑ‚Ð²Ð¾, ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, Ð¿Ð¾Ð¼Ð¾Ñ‰Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð¸Ð»Ð¸ Ð½Ð¾ÑÐ°Ñ‡Ð¸), Ð·Ð° Ð´Ð° Ð²ÑŠÐ·Ð¾Ð±Ð½Ð¾Ð²Ð¸Ñ‚Ðµ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½ÐµÑ‚Ð¾.</t>
    <t id="7001">[ÐŸÐ Ð•Ð”Ð’ÐÐ Ð˜Ð¢Ð•Ð›ÐÐž]</t>
    <t id="7002">[ÐžÐ‘Ð£Ð§Ð•ÐÐ˜Ð•]</t>
    <t id="7008">[Ð Ð•Ð—Ð•Ð Ð’Ð•Ð]</t>
    <t id="7009">[Ð˜Ð—ÐžÐ›Ð˜Ð ÐÐ]</t>
    <t id="7003">[Ð Ð•ÐœÐžÐÐ¢]</t>
    <t id="7004">[Ð”ÐžÐ¡Ð¢ÐÐ’ÐšÐ]</t>
    <t id="7005">[ÐŸÐžÐ”Ð”Ð ÐªÐ–ÐšÐ]</t>
    <t id="7006">[ÐŸÐ Ð•ÐÐÐŸÐ ÐÐ’Ð¯ÐÐ•]</t>
    <t id="7007">[Ð ÐÐ—Ð§Ð˜Ð¡Ð¢Ð’ÐÐÐ•]</t>
    <t id="1020">Ð˜Ð·Ð±ÐµÑ€ÐµÑ‚Ðµ Ð´Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€ Ð¸Ð»Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ, ÐºÑŠÐ´ÐµÑ‚Ð¾ Ñ€Ð°Ð±Ð¾Ñ‚Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ†ÑŠÑ‚</t>
    <t id="1021">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð·Ð° ÑÐºÐ¾Ðº Ð¿Ñ€Ð¸ Ð·Ð°ÐºÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÑÑ‚Ð¾ÐºÐ¸ (Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð¾Ñ‚ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°)</t>
    <t id="1022">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð·Ð° ÑÐºÐ¾Ðº Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð½Ð° ÑÑ‚Ð¾ÐºÐ¸ (Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð¾Ñ‚ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°)</t>
    <t id="1023">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÐ½ Ð¸Ð·Ð±Ð¾Ñ€ Ð½Ð° Ð¿Ð¾Ð´Ñ…Ð¾Ð´ÑÑ‰Ð¸ ÑÑ‚Ð¾ÐºÐ¸ ÑÐ¿Ð¾Ñ€ÐµÐ´ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸ÑÑ‚Ð°</t>
    <t id="1024">Ð ÑŠÑ‡ÐµÐ½ Ð¸Ð·Ð±Ð¾Ñ€ Ð½Ð° ÐºÐ¾Ð½ÐºÑ€ÐµÑ‚Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1025">Ð Ð°Ð·Ñ€ÐµÑˆÐµÑ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð° Ñ ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð±Ð°Ð½Ð´Ð½Ð¸ Ð¸ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1026">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ Ð½Ð° ÑÐ¸Ð³ÑƒÑ€Ð½Ð¾ÑÑ‚Ñ‚Ð°: 0.0=Ð¡Ð°Ð¼Ð¾ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸, 1.0=ÐŸÑ€Ð¸ÐµÐ¼Ð°Ð½Ðµ Ð½Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ñ€Ð¸ÑÐºÐ¾Ð²Ðµ</t>
    <t id="1027">ÐŸÐ¾Ð´Ð¾Ð±Ñ€ÐµÑ‚Ðµ Ð¿Ð¸Ð»Ð¾Ñ‚ÑÐºÐ¸Ñ‚Ðµ ÑƒÐ¼ÐµÐ½Ð¸Ñ Ñ‡Ñ€ÐµÐ· Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ð¿Ð¸Ñ‚</t>
    <t id="1028">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¸Ð·Ð¿Ñ€Ð°Ñ‰Ð°Ð½Ðµ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾</t>
    <t id="1029">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¼Ð½Ð¾Ð¶ÐµÑÑ‚Ð²Ð¾ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸, Ð·Ð° Ð´Ð° Ð¸Ð·Ð±ÐµÐ³Ð½ÐµÑ‚Ðµ ÐºÐ¾Ð½Ñ„Ð»Ð¸ÐºÑ‚Ð¸</t>
    <t id="1030">Ð¤Ð¾ÐºÑƒÑ Ð²ÑŠÑ€Ñ…Ñƒ ÑÑ‚Ð¾ÐºÐ¸Ñ‚Ðµ: 0=Ð‘Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½, 1=Ð Ð°Ð·ÑˆÐ¸Ñ€ÐµÐ½, 2=ÐžÑÐ½Ð¾Ð²Ð½Ð¸ Ð½ÑƒÐ¶Ð´Ð¸, 3=ÐÐµÐ·Ð°ÐºÐ¾Ð½ÐµÐ½, 4=ÐÐ°ÑÐ¸Ð¿Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="1031">Ð—Ð¾Ð½Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ: 0=Ð‘Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½, 1=ÐÐ°Ñ‡Ð°Ð»ÐµÐ½ Ñ„Ð¾ÐºÑƒÑ, 2=Ð¡Ð²Ð¾Ð±Ð¾Ð´ÐµÐ½ Ñ€Ð¾ÑƒÐ¼Ð¸Ð½Ð³</t>
    <t id="1032">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ: 0=ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾, 1=ÐÐ¾Ñ€Ð¼Ð°Ð»Ð½Ð¾, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¸ ÑÑŠÐ¾Ð±Ñ‰ÐµÐ½Ð¸Ñ</t>
    <t id="1033">Ð¦ÐµÐ»ÐµÐ²Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð°, Ð¿Ñ€ÐµÐ´Ð¸ Ð´Ð° Ð´Ð°Ð´ÐµÑ‚Ðµ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð¸Ñ‚Ðµ</t>
    <t id="1034">ÐšÐ¾Ð»ÐºÐ¾ Ñ‡ÐµÑÑ‚Ð¾ ÑÐµ Ð°ÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ñ‚ Ð¿Ð°Ð·Ð°Ñ€Ð½Ð¸Ñ‚Ðµ Ð´Ð°Ð½Ð½Ð¸ Ð¸ Ñ†ÐµÐ½Ð¾Ð²Ð° Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ</t>
    <t id="1035">Ð˜Ð·Ñ…Ð¾Ð´Ð½Ð¾ Ð½Ð¸Ð²Ð¾ Ð½Ð° Ð¾Ñ‚ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸: 0=ÐÑÐ¼Ð°, 1=ÐžÑÐ½Ð¾Ð²Ð½Ð¾, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="1036">Ð¡Ð¿Ð¾Ð´ÐµÐ»ÑÐ¹Ñ‚Ðµ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ñ Ñ„Ð»Ð¾Ñ‚Ð° (ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð¸ Ð·Ð° Ð±ÑŠÑ€Ð· Ð´Ð¾ÑÑ‚ÑŠÐ¿)</t>
    <t id="1037">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°, Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð° Ð·Ð° ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð¸ ÑÐ¿Ð¾Ð´ÐµÐ»ÑÐ½Ðµ Ñ Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="1038">ÐŸÐ¾Ð·Ð²Ð¾Ð»ÐµÐ½ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ ÑÐ¿Ð°Ð´ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°Ñ‚Ð°, Ð¿Ñ€ÐµÐ´Ð¸ ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð´Ð° ÑÑ‚Ð°Ð½Ð°Ñ‚ Ð½ÐµÐ²Ð°Ð»Ð¸Ð´Ð½Ð¸</t>
    <t id="1039">ÐšÐ¾Ð»ÐºÐ¾ Ð²Ñ€ÐµÐ¼Ðµ Ð¾ÑÑ‚Ð°Ð²Ð°Ñ‚ Ð²Ð°Ð»Ð¸Ð´Ð½Ð¸ ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð¿Ñ€ÐµÐ´Ð¸ Ð´Ð° Ð¸Ð·Ñ‚ÐµÐºÐ°Ñ‚</t>
    <t id="1040">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ð¾ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¸Ð½Ð´Ð¸Ð²Ð¸Ð´ÑƒÐ°Ð»Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ñ†ÐµÐ½ÐºÐ¸ Ð¸ Ð¾Ñ‚Ñ…Ð²ÑŠÑ€Ð»ÑÐ½Ð¸Ñ (Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð±ÑŠÐ´Ðµ Ð¼Ð½Ð¾Ð³Ð¾ Ð¿Ð¾Ð´Ñ€Ð¾Ð±Ð½Ð¾)</t>
    <t id="1041">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð´Ð½ÐµÐ²Ð½Ð¸ÐºÐ° Ð·Ð° Ð²ÑÑÐºÐ° ÑÐ´ÐµÐ»ÐºÐ° Ð¸ Ð·Ð°Ð²Ð»Ð°Ð´ÑÐ²Ð°Ñ‰Ð¸ ÑÑŠÐ¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ (ÑÑ‚Ð¸Ð» TaterTrader)</t>
    <t id="1053">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¸Ñ‚Ðµ Ð² Ñ‚Ð¾Ð·Ð¸ ÑÐ¿Ð¸ÑÑŠÐº ÑÐ° Ð¸Ð·ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸ Ð¾Ñ‚ Ñ‡ÐµÑ€Ð½Ð¸Ñ‚Ðµ ÑÐ¿Ð¸ÑÑŠÑ†Ð¸ (Ð²Ð¸Ð½Ð°Ð³Ð¸ Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð¸)</t>
    <t id="1055">Ð˜Ð·ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ð¿Ñ€ÐµÐ²Ð¾Ð·Ð²Ð°Ñ‡Ð¸Ñ‚Ðµ Ð¸ ÑÐ¿Ð¾Ð¼Ð°Ð³Ð°Ñ‚ÐµÐ»Ð½Ð¸Ñ‚Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð¾Ñ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð°</t>
    <t id="1057">Ð˜Ð·ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ð¸Ð·Ð³Ñ€Ð°Ð¶Ð´Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð·Ð° ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð¾Ñ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ</t>
    <t id="1059">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð°Ñ‚Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ (Ñ€Ð°Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð¾; Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¸Ð·Ð±ÐµÑ€ÐµÑ‚Ðµ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¾Ð±Ð¸ÐºÐ½Ð¾Ð²ÐµÐ½Ð¾ ÑÐ° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸)</t>
    <t id="1061">ÐŸÑ€Ð¾Ð¿ÑƒÑÐ½ÐµÑ‚Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð·Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¸Ð¼Ð°Ñ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† MK1 Ñ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½ Ñ€ÐµÐ¶Ð¸Ð¼ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ°</t>
    <t id="1062">Ð£Ð²ÐµÐ»Ð¸Ñ‡ÐµÑ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚Ð¸ Ð·Ð° Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸, Ð²ÐºÐ»ÑŽÑ‡Ð²Ð°Ñ‰Ð¸ Ð²Ð°ÑˆÐ¸Ñ‚Ðµ ÑÐ¾Ð±ÑÑ‚Ð²ÐµÐ½Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ (10% Ð±Ð¾Ð½ÑƒÑ Ð·Ð° Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚)</t>
    <t id="1071">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾ Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½ÐµÐ»ÐµÐ³Ð°Ð»Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸, Ñ‚ÑŠÑ€Ð³ÑƒÐ²Ð°Ð¹Ñ‚Ðµ ÑÐ°Ð¼Ð¾ Ñ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸, Ð°ÐºÐ¾ ÑÐ° Ð·Ð°ÐºÐ¾Ð½Ð½Ð¸ Ð²ÑŠÐ² Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð¿Ð¾ Ð¿ÑŠÑ‚Ñ Ð½Ð° Ð¿Ñ€ÐµÑÐºÐ°Ñ‡Ð°Ð½Ðµ (ÐºÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ, Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð¸ Ð¼ÐµÐ¶Ð´Ð¸Ð½Ð½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸).</t>
    <t id="1087">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð·Ð° ÑÐºÐ¾Ðº Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ðº</t>
    <t id="1089">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½, ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð² Ð·Ð¾Ð½Ð°Ñ‚Ð° Ð½Ð° Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ð¸Ðµ Ð¿Ð¾ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° ÑÐ¿ÐµÑˆÐ½Ð¾ÑÑ‚ Ð²Ð¼ÐµÑÑ‚Ð¾ Ð² Ñ€ÐµÐ¶Ð¸Ð¼ ÑÐ°Ð¼Ð¾ Ð·Ð° Ð´Ð¾Ð¼Ð°</t>
    <t id="2000">%s ÑÐ¿ÐµÑ‡ÐµÐ»Ð¸ %s XP!</t>
    <t id="2001">%s Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ð° Ð½Ð¸Ð²Ð¾! ÐÐ¾Ð²Ð¾ Ð½Ð¸Ð²Ð¾: %s</t>
    <t id="2002">%s Ð¸Ð¼Ð° Ð½ÑƒÐ¶Ð´Ð° Ð¾Ñ‚ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ! ÐœÐ¾Ð»Ñ, Ð¸Ð·Ð¿Ñ€Ð°Ñ‚ÐµÑ‚Ðµ Ð´Ð¾ Ð½Ð°Ð¹-Ð±Ð»Ð¸Ð·ÐºÐ°Ñ‚Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¾ÑÑ‚Ñ€Ð¾Ð¸Ñ‚ÐµÐ»Ð½Ð¸Ñ†Ð° Ð¸Ð»Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ.</t>
    <t id="2003">%s Ð·Ð°Ð¿Ð¾Ñ‡Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð² %s</t>
    <t id="2004">%s Ð·Ð°Ð²ÑŠÑ€ÑˆÐ¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð¸ Ð²ÐµÑ‡Ðµ Ðµ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ Ð·Ð° Ð½Ð¸Ð²Ð¾ %s!</t>
    <t id="2005">%s Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ð° Skill Level %s ÑÐ»ÐµÐ´ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ! XP Ð½Ð°Ð¿Ñ€ÐµÐ´Ð²Ð°Ð½ÐµÑ‚Ð¾ Ðµ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ Ð² %s.</t>
    <t id="2006">%s Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ð° Skill Level %s Ñ‡Ñ€ÐµÐ· Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ñ %s!</t>
    <t id="2007">%s Ð·Ð°Ð²ÑŠÑ€ÑˆÐ¸ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Level %s! XP Ð½Ð°Ð¿Ñ€ÐµÐ´Ð²Ð°Ð½ÐµÑ‚Ð¾ Ðµ Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ Ð² %s.</t>
    <t id="3000">%s Ð·Ð°Ð²ÑŠÑ€ÑˆÐ¸ ÑÐ´ÐµÐ»ÐºÐ°! ÐŸÐµÑ‡Ð°Ð»Ð±Ð°: %s Cr</t>
    <t id="3001">%s Ð°Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð° Ð¿Ð°Ð·Ð°Ñ€Ð½Ð¸Ñ‚Ðµ ÑƒÑÐ»Ð¾Ð²Ð¸Ñ...</t>
    <t id="3002">%s Ð½Ð°Ð¼ÐµÑ€Ð¸ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²Ñˆ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿ÑŠÑ‚!</t>
    <t id="3003">ÐÑÐ¼Ð° Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿ÑŠÑ‚Ð¸Ñ‰Ð° Ð·Ð° %s</t>
    <t id="3100">ÐŸÑ€Ð¾Ð´Ð°Ð²Ð°Ð¼ %1 %2 Ð¾Ñ‚ ÐºÐ°Ñ€Ð³Ð¾ Ð½Ð° %3 Ð½Ð° Ñ†ÐµÐ½Ð° %4. Ð¢Ñ€ÑÐ±Ð²Ð° Ð´Ð° ÑÐ¿ÐµÑ‡ÐµÐ»Ñ %5 Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°.</t>
    <t id="3101">ÐŸÐ¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ° Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ° Ð·Ð° %1 %2. ÐšÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° %3 Ð¾Ñ‚ %4, Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð½Ð° %5 ÐºÑŠÐ¼ %6. Ð¢Ñ€ÑÐ±Ð²Ð° Ð´Ð° ÑÐ¿ÐµÑ‡ÐµÐ»Ñ %7 Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°.</t>
    <t id="3102">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ: Ð”Ð¾ÑÑ‚Ð°Ð²Ñ %1 %2 Ð¾Ñ‚ %3 Ð¿Ñ€Ð¸ %5%% Ð´Ð¾ %4 Ð¿Ñ€Ð¸ %6%%.</t>
    <t id="3103">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ: ÐŸÑ€Ð¾Ð´Ð°Ð²Ð°Ð¼ %1 %2 Ð½Ð° %3 Ð½Ð° Ñ†ÐµÐ½Ð° %4. ÐžÑ‡Ð°ÐºÐ²Ð°Ð½Ð°Ñ‚Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° Ðµ %5.</t>
    <t id="3104">Ð¢ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð° Ð¿Ñ€Ð¸ÐºÐ»ÑŽÑ‡Ð¸ ÑƒÑÐ¿ÐµÑˆÐ½Ð¾ Ð·Ð° %1 %2. ÐžÐ±Ñ‰Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°: %3 ÐºÑ€ÐµÐ´Ð¸Ñ‚Ð°.</t>
    <t id="3105">ÐšÐµÑˆÐ¸Ñ€Ð°Ð½ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚: %1 %2 Ð¾Ñ‚ %3 Ð´Ð¾ %4 (ÐŸÐµÑ‡Ð°Ð»Ð±Ð°: %5 Cr)</t>
    <t id="3106">\nÐžÐ±Ñ‰Ð° Ð¾Ñ‡Ð°ÐºÐ²Ð°Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° Ð·Ð° Ñ†ÐµÐ»Ð¸Ñ Ð¶Ð¸Ð²Ð¾Ñ‚ Ð¿Ñ€ÐµÐ´Ð¸ Ñ‚Ð°Ð·Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ: %1 Cr.</t>
    <t id="3120">Ð—Ð°Ð¿Ð¾Ñ‡Ð½Ð° Ñ‚Ñ€Ð°Ð½ÑÑ„ÐµÑ€ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚</t>
    <t id="3121">ÐŸÑ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»ÑŠÑ‚ Ð·Ð° Ð¿Ñ€ÐµÐ´Ð°Ð²Ð°Ð½Ðµ Ðµ Ð¿Ð¾Ñ‚Ð²ÑŠÑ€Ð´ÐµÐ½. %1 (%2) Ð¸ %3 (%4) Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ð²Ð°Ñ‚ ÐºÑŠÐ¼ %5 (%6), Ð·Ð° Ð´Ð° Ð´Ð¾ÐºÐ¸Ñ€Ð°Ñ‚ Ð¸ Ñ€Ð°Ð·Ð¼ÐµÐ½ÑÑ‚ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð½Ð¸Ñ‚Ðµ Ð¼ÐµÑÑ‚Ð°.</t>
    <t id="3200">Ð—Ð´Ñ€Ð°Ð²ÐµÐ¹Ñ‚Ðµ ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ %1,\n\nÐÐ°Ñ‚Ñ€ÑƒÐ¿Ð°Ñ… Ð´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð¾Ð¿Ð¸Ñ‚, Ð·Ð° Ð´Ð° ÑÐµ ÑÐ²Ñ Ð½Ð° Ð¸Ð·Ð¿Ð¸Ñ‚Ð° ÑÐ¸ Ð·Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ðµ Ð·Ð° Ñ‚Ð¸Ñ‚Ð»Ð°Ñ‚Ð° "%2". Ð˜Ð·Ð¿Ð¸Ñ‚ÑŠÑ‚ Ñ‰Ðµ Ð¾Ñ‚Ð½ÐµÐ¼Ðµ Ð¿Ñ€Ð¸Ð±Ð»Ð¸Ð·Ð¸Ñ‚ÐµÐ»Ð½Ð¾ %3 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸ Ð² %4.\n\nÐ¢Ð¾Ð²Ð° Ðµ Ð²Ð°Ð¶ÐµÐ½ ÐºÑ€Ð°Ð¹ÑŠÐ³ÑŠÐ»ÐµÐ½ ÐºÐ°Ð¼ÑŠÐº Ð² ÐºÐ°Ñ€Ð¸ÐµÑ€Ð½Ð¾Ñ‚Ð¾ Ð¼Ð¸ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ðµ. Ð˜Ð·Ð¿Ð¸Ñ‚ÑŠÑ‚ Ñ‰Ðµ Ñ‚ÐµÑÑ‚Ð²Ð° Ð·Ð½Ð°Ð½Ð¸ÑÑ‚Ð° Ð¼Ð¸ Ð·Ð° ÑƒÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð¸ Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ, Ð°Ð½Ð°Ð»Ð¸Ð· Ð½Ð° Ð¿Ð°Ð·Ð°Ñ€Ð° Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ´ÑƒÑ€Ð¸ Ð·Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°.\n\nÐ£Ð²ÐµÑ€ÐµÐ½ ÑÑŠÐ¼ Ð² ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚Ð¸Ñ‚Ðµ ÑÐ¸ Ð¸ ÑÐµ Ð²ÑŠÐ»Ð½ÑƒÐ²Ð°Ð¼ Ð´Ð° Ð´Ð¾ÐºÐ°Ð¶Ð°, Ñ‡Ðµ ÑÑŠÐ¼ Ð´Ð¾ÑÑ‚Ð¾ÐµÐ½ Ð·Ð° Ñ‚Ð¾Ð·Ð¸ Ð½Ð°Ð¿Ñ€ÐµÐ´ÑŠÐº. ÐŸÐ¾Ð¶ÐµÐ»Ð°Ð¹Ñ‚Ðµ Ð¼Ð¸ ÐºÑŠÑÐ¼ÐµÑ‚!\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\n%5\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %6</t>
    <t id="3201">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐžÑ‚Ð»Ð¸Ñ‡Ð½Ð¸ Ð½Ð¾Ð²Ð¸Ð½Ð¸! Ð£ÑÐ¿ÐµÑˆÐ½Ð¾ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ¸Ñ… Ð¸Ð·Ð¿Ð¸Ñ‚Ð° ÑÐ¸ Ð·Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ðµ Ð¸ ÑÐ¿ÐµÑ‡ÐµÐ»Ð¸Ñ… Ñ‚Ð¸Ñ‚Ð»Ð°Ñ‚Ð° â€ž%2â€œ!\n\nÐ˜Ð·Ð¿Ð¸Ñ‚ÑŠÑ‚ Ð¾Ð±Ñ…Ð²Ð°Ð½Ð° ÑƒÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð¸ ÑÑ‚Ñ€Ð°Ñ‚ÐµÐ³Ð¸Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ, Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ð¸ Ð·Ð° Ð¾Ñ†ÐµÐ½ÐºÐ° Ð½Ð° Ñ€Ð¸ÑÐºÐ° Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ´ÑƒÑ€Ð¸ Ð·Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°. Ð˜Ð¼Ð°Ð¼ ÑƒÐ´Ð¾Ð²Ð¾Ð»ÑÑ‚Ð²Ð¸ÐµÑ‚Ð¾ Ð´Ð° ÑÑŠÐ¾Ð±Ñ‰Ñ, Ñ‡Ðµ ÑÐµ ÑÐ¿Ñ€Ð°Ð²Ð¸Ñ… Ñ Ð¾Ñ‚Ð»Ð¸Ñ‡Ð¸Ðµ.\n\nÐ’ÐµÑ‡Ðµ ÑÑŠÐ¼ ÐºÐ²Ð°Ð»Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ Ð´Ð° ÑÐµ ÑÐ¿Ñ€Ð°Ð²ÑÐ¼ Ñ Ð¿Ð¾-ÑÐ»Ð¾Ð¶Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ Ð¸ Ð¾Ñ‡Ð°ÐºÐ²Ð°Ð¼ Ñ Ð½ÐµÑ‚ÑŠÑ€Ð¿ÐµÐ½Ð¸Ðµ Ð´Ð° Ð´Ð¾Ð¿Ñ€Ð¸Ð½ÐµÑÐ° Ð¾Ñ‰Ðµ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð·Ð° ÑƒÑÐ¿ÐµÑ…Ð° Ð½Ð° Ð½Ð°ÑˆÐ¸Ñ Ñ„Ð»Ð¾Ñ‚. Ð‘Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ð²Ð¸, Ñ‡Ðµ Ð¸Ð½Ð²ÐµÑÑ‚Ð¸Ñ€Ð°Ñ…Ñ‚Ðµ Ð² Ð¿Ñ€Ð¾Ñ„ÐµÑÐ¸Ð¾Ð½Ð°Ð»Ð½Ð¾Ñ‚Ð¾ Ð¼Ð¸ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ðµ.\n\nÐ¡ Ð¿Ð¾Ð´Ð½Ð¾Ð²ÐµÐ½Ð° Ð¾Ñ‚Ð´Ð°Ð´ÐµÐ½Ð¾ÑÑ‚,\n%3\nÐ¡ÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ %2\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %4</t>
    <t id="3202">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¡ÑŠÐ¶Ð°Ð»ÑÐ²Ð°Ð¼ Ð´Ð° Ð²Ð¸ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð¸Ñ€Ð°Ð¼, Ñ‡Ðµ Ð¸Ð·Ð¿Ð¸Ñ‚ÑŠÑ‚ Ð¼Ð¸ Ð·Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ðµ Ð±ÐµÑˆÐµ Ð¿Ñ€ÐµÐºÑŠÑÐ½Ð°Ñ‚ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ð½Ð¸ Ð¸Ð·Ð¸ÑÐºÐ²Ð°Ð½Ð¸Ñ. Ð©Ðµ Ñ‚Ñ€ÑÐ±Ð²Ð° Ð´Ð° Ð¿Ñ€ÐµÐ½Ð°ÑÑ€Ð¾Ñ‡Ð°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¾Ð±ÑÑ‚Ð¾ÑÑ‚ÐµÐ»ÑÑ‚Ð²Ð°Ñ‚Ð° Ð³Ð¾ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚.\n\nÐžÑÑ‚Ð°Ð²Ð°Ð¼ Ð°Ð½Ð³Ð°Ð¶Ð¸Ñ€Ð°Ð½ Ñ ÑƒÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° ÑÐ¸ Ð¸ Ñ‰Ðµ Ð²Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ñ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¼Ð¾Ð³Ð° Ð´Ð° Ð²ÑŠÐ·Ð¾Ð±Ð½Ð¾Ð²Ñ Ð¸Ð·Ð¿Ð¸Ñ‚Ð½Ð¸Ñ Ð¿Ñ€Ð¾Ñ†ÐµÑ.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\n%2\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %3</t>
    <t id="3203">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ’ Ð¼Ð¾Ð¼ÐµÐ½Ñ‚Ð° ÑÑŠÐ¼ Ð½Ð° Ð¿ÑŠÑ‚ Ð·Ð° %2 Ð·Ð° Ð¼Ð¾Ñ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¾Ð½ÐµÐ½ Ð¸Ð·Ð¿Ð¸Ñ‚. ÐŸÑŠÑ‚ÑƒÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð¼Ð¸ Ð´Ð°Ð²Ð° Ð²Ñ€ÐµÐ¼Ðµ Ð´Ð° Ð¿Ñ€ÐµÐ³Ð»ÐµÐ´Ð°Ð¼ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸ÐµÑ‚Ð¾ ÑÐ¸ Ð¸ Ð´Ð° ÑÐµ Ð¿Ð¾Ð´Ð³Ð¾Ñ‚Ð²Ñ Ð¿ÑÐ¸Ñ…Ð¸Ñ‡ÐµÑÐºÐ¸ Ð·Ð° Ñ‚Ð°Ð·Ð¸ Ð²Ð°Ð¶Ð½Ð° ÑÑ‚ÑŠÐ¿ÐºÐ° Ð² Ð¼Ð¾ÑÑ‚Ð° ÐºÐ°Ñ€Ð¸ÐµÑ€Ð°.\n\nÐžÑ‡Ð°ÐºÐ²Ð°Ð½Ð¾ Ð¿Ñ€Ð¸ÑÑ‚Ð¸Ð³Ð°Ð½Ðµ: %3 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸\nÐŸÑ€Ð¾Ð´ÑŠÐ»Ð¶Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚ Ð½Ð° Ð¸Ð·Ð¿Ð¸Ñ‚Ð°: %4 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸\n\nÐžÑ†ÐµÐ½ÑÐ²Ð°Ð¼ Ð´Ð¾Ð²ÐµÑ€Ð¸ÐµÑ‚Ð¾ Ð²Ð¸ Ð² ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚Ð¸Ñ‚Ðµ Ð¼Ð¸ Ð¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð·Ð° Ð½Ð°Ð¿Ñ€ÐµÐ´ÑŠÐº.\n\nÐ¡ Ñ€ÐµÑˆÐ¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\n%5\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %6</t>
    <t id="3204">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐžÑ‚ÐºÑ€Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€ Ð² Ñ‚Ñ€ÑŽÐ¼Ð° ÑÐ¸ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ°Ñ‚Ð° Ð½Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸Ñ‚Ðµ Ð¼Ð¸. ÐŸÑ€ÐµÐ´Ð¸ Ð´Ð° Ð¼Ð¾Ð³Ð° Ð´Ð° Ð·Ð°Ð¿Ð¾Ñ‡Ð½Ð° Ð½Ð¾Ñ€Ð¼Ð°Ð»Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸, Ñ‚Ñ€ÑÐ±Ð²Ð° Ð´Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¼ Ñ‚Ð°Ð·Ð¸ ÑÑ‚Ð¾ÐºÐ°.\n\nÐ˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¼ Ð½Ð°ÑˆÐµÑ‚Ð¾ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ, Ð·Ð° Ð´Ð° Ð½Ð°Ð¼ÐµÑ€Ñ Ð½Ð°Ð¹-Ð´Ð¾Ð±Ñ€Ð¸Ñ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡ Ð¸ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ Ð´Ð° Ñ€Ð°Ð·Ñ‚Ð¾Ð²Ð°Ñ€Ñ Ñ‚Ð¾Ð·Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€. Ð¡Ð»ÐµÐ´ ÐºÐ°Ñ‚Ð¾ Ð·Ð°Ð´ÑŠÑ€Ð¶Ð°Ð½ÐµÑ‚Ð¾ Ð¼Ð¸ Ð±ÑŠÐ´Ðµ Ð¸Ð·Ñ‡Ð¸ÑÑ‚ÐµÐ½Ð¾, Ñ‰Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð°Ñ‚Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ.\n\nÐ¡Ñ‚Ð°Ñ‚ÑƒÑ: Ð¢ÑŠÑ€ÑÑ Ð¾Ð¿Ñ‚Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð¼ÑÑÑ‚Ð¾ Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°\n\nÐ¡ ÑƒÑÑŠÑ€Ð´Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° %1</t>
    <t id="3205">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¦ÐµÐ»Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° Ð¼Ð¸ ÑÐ¿Ð°Ð´Ð½Ð° Ð´Ð¾ %1%% (Ð¿Ñ€Ð°Ð³: %2%%). ÐšÐ°Ñ‚Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚ Ð¾Ñ‚ Ð½Ð¸Ð²Ð¾ %3 ÑÑŠÐ¼ ÑƒÐ¿ÑŠÐ»Ð½Ð¾Ð¼Ð¾Ñ‰ÐµÐ½ Ð´Ð° Ð¿Ð¾Ð¸ÑÐºÐ°Ð¼ ÑƒÑÐ»ÑƒÐ³Ð¸ Ð·Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÐ½ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚.\n\nÐŸÑ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ð²Ð°Ð¼ ÐºÑŠÐ¼ %4 Ð·Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð¸ Ð´ÐµÐ¹Ð½Ð¾ÑÑ‚Ð¸. ÐŸÑ€Ð¸Ð±Ð»Ð¸Ð·Ð¸Ñ‚ÐµÐ»Ð½Ð°Ñ‚Ð° Ñ†ÐµÐ½Ð° Ðµ %5 Cr, ÐºÐ¾ÐµÑ‚Ð¾ Ðµ Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ Ð½Ð° Ð½Ð°ÑˆÐ¸Ñ Ð±ÑŽÐ´Ð¶ÐµÑ‚.\n\nÐ¡Ð»ÐµÐ´ ÐºÐ°Ñ‚Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ÑŠÑ‚ Ð¿Ñ€Ð¸ÐºÐ»ÑŽÑ‡Ð¸, Ñ‰Ðµ Ð²ÑŠÐ·Ð¾Ð±Ð½Ð¾Ð²Ñ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ Ñ Ð¿ÑŠÐ»Ð½Ð° ÑÑ‚Ñ€ÑƒÐºÑ‚ÑƒÑ€Ð½Ð° Ñ†ÑÐ»Ð¾ÑÑ‚.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %6</t>
    <t id="3206">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¡ÐŸÐ•Ð¨ÐÐž Ð¤Ð˜ÐÐÐÐ¡ÐžÐ’Ðž ÐŸÐ Ð•Ð”Ð£ÐŸÐ Ð•Ð–Ð”Ð•ÐÐ˜Ð•\n\nÐ¦ÐµÐ»Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° Ð¼Ð¸ Ðµ ÐºÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð° Ð¿Ñ€Ð¸ %1%% (Ð¿Ñ€Ð°Ð³: %2%%), Ð½Ð¾ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸Ñ‚Ðµ Ð½Ð¸ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° (%3 Cr) Ð½Ðµ ÑÐ° Ð´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¸ Ð·Ð° Ð¿ÑŠÐ»ÐµÐ½ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ (Ð¿Ñ€Ð¸Ð±Ð»Ð¸Ð·Ð¸Ñ‚ÐµÐ»Ð½Ð° Ñ†ÐµÐ½Ð°: %4 Cr).\n\nÐŸÑ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ð²Ð°Ð¼ ÐºÑŠÐ¼ %5 Ð·Ð° Ð§ÐÐ¡Ð¢Ð˜Ð§ÐÐ˜ Ð Ð•ÐœÐžÐÐ¢Ð˜ Ñ Ð½Ð°ÑˆÐ¸Ñ‚Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð°. Ð¢Ð¾Ð²Ð° Ð½Ðµ Ðµ Ð¸Ð´ÐµÐ°Ð»Ð½Ð¾Ñ‚Ð¾ Ñ€ÐµÑˆÐµÐ½Ð¸Ðµ, Ð½Ð¾ Ðµ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾, Ð·Ð° Ð´Ð° ÑÐµ Ð¿Ð¾Ð´Ð´ÑŠÑ€Ð¶Ð° Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ð½Ð°Ñ‚Ð° ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚.\n\nÐœÐ¾Ð»Ñ, Ð¾Ð±Ð¼Ð¸ÑÐ»ÐµÑ‚Ðµ Ð¾Ñ‚Ð´ÐµÐ»ÑÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð´Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¸ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° Ð·Ð° Ð±ÑŠÐ´ÐµÑ‰Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ Ð¿Ð¾ Ð¿Ð¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ°.\n\nÐ—Ð°Ð³Ñ€Ð¸Ð¶ÐµÐ½, Ð½Ð¾ Ñ€ÐµÑˆÐµÐ½,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %6</t>
    <t id="3207">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐœÐ¾ÐµÑ‚Ð¾ Ð½Ð¸Ð²Ð¾ Ð½Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ðµ %1 Ñ€Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ Ñ Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½Ðµ. Ð¡Ð»ÐµÐ´ ÐºÐ°Ñ‚Ð¾ Ð¿Ñ€Ð¾Ð²ÐµÑ€Ð¸Ñ… ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸Ñ‚Ðµ ÑÐ¸, ÑƒÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ…, Ñ‡Ðµ Ð¼Ð¾Ð¸Ñ‚Ðµ ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð¼ÐµÑ€ÐºÐ¸ Ð¸ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° Ð·Ð° Ñ€Ð°Ð·Ð³Ñ€ÑŠÑ‰Ð°Ð½Ðµ ÑÐ° Ð¿Ð¾Ð´ Ð¿Ñ€ÐµÐ¿Ð¾Ñ€ÑŠÑ‡Ð°Ð½Ð¸Ñ‚Ðµ Ð¿Ñ€Ð°Ð³Ð¾Ð²Ðµ.\n\nÐŸÑ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ð²Ð°Ð¼ ÐºÑŠÐ¼ %2, Ð·Ð° Ð´Ð° Ð²ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²Ñ Ð·Ð°Ð¿Ð°ÑÐ¸Ñ‚Ðµ ÑÐ¸ Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½Ðµ:\nâ€¢ ÐšÐ¾Ð½Ñ‚Ñ€Ð°Ð¼ÐµÑ€ÐºÐ¸: ÐŸÐ¾Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð´Ð¾ Ð¾Ð¿Ñ‚Ð¸Ð¼Ð°Ð»ÐµÐ½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚\nâ€¢ Ð—Ð°Ñ‰Ð¸Ñ‚Ð½Ð¸ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ, Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ, Ð»Ð°Ð·ÐµÑ€Ð½Ð¸ ÐºÑƒÐ»Ð¸: ÐŸÑ€Ð¸Ð»Ð°Ð³Ð°Ð½Ðµ Ð½Ð° Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½ Ð¿Ñ€Ð¾Ñ„Ð¸Ð»\n\nÐ¢Ð¾Ð²Ð° ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ Ð³Ð°Ñ€Ð°Ð½Ñ‚Ð¸Ñ€Ð°, Ñ‡Ðµ ÑÑŠÐ¼ Ð½Ð°Ð¹-Ð´Ð¾Ð±Ñ€Ð¸ÑÑ‚ Ð·Ð°Ñ‰Ð¸Ñ‚ÐµÐ½ ÑÑ€ÐµÑ‰Ñƒ ÐºÐ¾ÑÐ¼Ð¸Ñ‡ÐµÑÐºÐ¸ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸, ÐºÐ°Ñ‚Ð¾ ÑÑŠÑ‰ÐµÐ²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ Ð¿Ð¾Ð´Ð´ÑŠÑ€Ð¶Ð° ÐµÑ„ÐµÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð°.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %3</t>
    <t id="3212">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¦ÐµÐ»Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð¿ÑƒÑÐ° Ð¼Ð¸ Ðµ ÑÐ¿Ð°Ð´Ð½Ð°Ð»Ð° Ð´Ð¾ %1%% (Ð¿Ñ€Ð°Ð³: %2%%) Ð¸ Ð¸Ð¼Ð°Ð¼ Ð½ÑƒÐ¶Ð´Ð° Ð¾Ñ‚ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð¸ ÑƒÑÐ»ÑƒÐ³Ð¸. Ð’ÑŠÐ¿Ñ€ÐµÐºÐ¸ Ñ‚Ð¾Ð²Ð° Ð½Ð°Ð¹-Ð±Ð»Ð¸Ð·ÐºÐ°Ñ‚Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð·Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ Ð½Ð° %3 Ð² Ð¼Ð¾Ð¼ÐµÐ½Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚ÑŠÐ¿Ð½Ð° Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð° (Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº).\n\nÐ©Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ñ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ Ð²ÑŠÐ¿Ñ€ÐµÐºÐ¸ Ñ‚Ð¾Ð²Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ. Ð¡Ð»ÐµÐ´ ÐºÐ°Ñ‚Ð¾ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¸Ñ‚Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ ÑÑ‚Ð°Ð½Ð°Ñ‚ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸, Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ‰Ðµ Ð¿Ð¾Ñ‚ÑŠÑ€ÑÑ ÑƒÑÐ»ÑƒÐ³Ð¸ Ð·Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚.\n\nÐ©Ðµ Ð½Ð°Ð±Ð»ÑŽÐ´Ð°Ð²Ð°Ð¼ ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÑÑ‚Ð° Ð¸ Ñ‰Ðµ Ð²Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ñ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ÑŠÑ‚ ÑÑ‚Ð°Ð½Ðµ Ð²ÑŠÐ·Ð¼Ð¾Ð¶ÐµÐ½.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %4</t>
    <t id="3213">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐžÑ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¾Ñ‚Ð¾ Ð¼Ð¸ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½Ðµ Ð¸Ð·Ð¸ÑÐºÐ²Ð° ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ, Ð½Ð¾ Ð½Ð°Ð¹-Ð±Ð»Ð¸Ð·ÐºÐ°Ñ‚Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð·Ð° Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½Ðµ Ð½Ð° %1 Ð² Ð¼Ð¾Ð¼ÐµÐ½Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚ÑŠÐ¿Ð½Ð° Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð° (Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº).\n\nÐ©Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ñ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ Ð²ÑŠÐ¿Ñ€ÐµÐºÐ¸ Ñ‚Ð¾Ð²Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ. Ð¡Ð»ÐµÐ´ ÐºÐ°Ñ‚Ð¾ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ ÑÑ‚Ð°Ð½Ð°Ñ‚ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸, Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ‰Ðµ Ð¿Ð¾Ñ‚ÑŠÑ€ÑÑ ÑƒÑÐ»ÑƒÐ³Ð¸ Ð·Ð° ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ.\n\nÐ©Ðµ Ð½Ð°Ð±Ð»ÑŽÐ´Ð°Ð²Ð°Ð¼ ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÑÑ‚Ð° Ð¸ Ñ‰Ðµ Ð²Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ñ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½ÐµÑ‚Ð¾ ÑÑ‚Ð°Ð½Ðµ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %2</t>
    <t id="3208">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ—Ð°Ð²ÑŠÑ€ÑˆÐ¸Ñ… Ð¸Ð·Ñ‡ÐµÑ€Ð¿Ð°Ñ‚ÐµÐ»ÐµÐ½ Ð¿Ð°Ð·Ð°Ñ€ÐµÐ½ Ð°Ð½Ð°Ð»Ð¸Ð· Ð½Ð° %1 Ð¸ Ð¾ÐºÐ¾Ð»Ð½Ð¸Ñ‚Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ (Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ Ð½Ð° %2 ÑÐºÐ¾ÐºÐ¾Ð²Ðµ, Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ Ð¿Ñ€Ð°Ð³ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°: %3 Cr), Ð½Ð¾ Ð·Ð° ÑÑŠÐ¶Ð°Ð»ÐµÐ½Ð¸Ðµ Ð½Ðµ Ð¾Ñ‚ÐºÑ€Ð¸Ñ… Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð´Ð° Ð¾Ñ‚Ð³Ð¾Ð²Ð°Ñ€ÑÑ‚ Ð½Ð° Ð½Ð°ÑˆÐ¸Ñ‚Ðµ Ð¸Ð·Ð¸ÑÐºÐ²Ð°Ð½Ð¸Ñ.\n\nÐžÐ¢Ð§Ð•Ð¢ Ð—Ð ÐÐÐÐ›Ð˜Ð— ÐÐ Ð¢ÐªÐ Ð“ÐžÐ’Ð˜Ð¯Ð¢Ð:\nÐžÐ±Ñ‰Ð¾ Ð¾Ñ†ÐµÐ½ÐµÐ½Ð¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸: %4\n\nÐ ÐÐ—Ð‘Ð˜Ð ÐÐÐ• ÐÐ ÐžÐ¢Ð¥Ð’ÐªÐ Ð›Ð¯ÐÐ•Ð¢Ðž:\n- ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð° Ð´Ð¾ÐºÐ¸Ð½Ð³: %5 ÑÐ´ÐµÐ»ÐºÐ¸\n (Ð¡Ñ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð° Ð½Ðµ Ñ€Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð° Ð¼Ð¾Ñ ÐºÐ»Ð°Ñ ÐºÐ¾Ñ€Ð°Ð±)\n- ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð° Ð´Ð¾Ñ…Ð¾Ð´Ð½Ð¾ÑÑ‚: %6 ÑÐ´ÐµÐ»ÐºÐ¸\n (ÐŸÐ¾Ð´ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¸Ñ Ð¿Ñ€Ð°Ð³ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°Ñ‚Ð°)\n- ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡ÐµÐ½ Ð¾Ð±ÐµÐ¼: %7 ÑÐ´ÐµÐ»ÐºÐ¸\n (ÐÑƒÐ»Ð° Ð¸Ð»Ð¸ Ð¾Ñ‚Ñ€Ð¸Ñ†Ð°Ñ‚ÐµÐ»Ð½Ð° Ñ‚ÑŠÑ€Ð³ÑƒÐµÐ¼Ð¾ÑÑ‚ ÑÑƒÐ¼Ð°)\n- ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚: %8 ÑÐ´ÐµÐ»ÐºÐ¸\n (Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº Ð¸Ð»Ð¸ Ð¾Ð¿Ð°ÑÐ½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸)\n\nÐŸÐ Ð•ÐŸÐžÐ ÐªÐšÐ˜:\n- ÐŸÐ¾Ð¼Ð¸ÑÐ»ÐµÑ‚Ðµ Ð·Ð° ÐºÐ¾Ñ€Ð¸Ð³Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€Ð°Ð³Ð¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð¸Ñ‚Ðµ\n- Ð Ð°Ð·ÑˆÐ¸Ñ€ÐµÑ‚Ðµ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾Ñ‚Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ\n- ÐŸÑ€ÐµÐ³Ð»ÐµÐ´Ð°Ð¹Ñ‚Ðµ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸Ñ‚Ðµ Ð½Ð° Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº Ð½Ð° ÑÐµÐºÑ‚Ð¾Ñ€Ð°\n- Ð˜Ð·Ñ‡Ð°ÐºÐ°Ð¹Ñ‚Ðµ Ð¿Ð°Ð·Ð°Ñ€Ð½Ð¸Ñ‚Ðµ ÑƒÑÐ»Ð¾Ð²Ð¸Ñ Ð´Ð° ÑÐµ Ð¿Ð¾Ð´Ð¾Ð±Ñ€ÑÑ‚\n\nÐ©Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ð´Ð° Ð½Ð°Ð±Ð»ÑŽÐ´Ð°Ð²Ð°Ð¼ Ð¿Ð°Ð·Ð°Ñ€Ð° Ð¸ Ñ‰Ðµ Ð²Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ñ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð²ÑŠÐ·Ð½Ð¸ÐºÐ½Ð°Ñ‚ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð° Ñ€Ð°Ð·Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ.\n\nÐ’ Ð³Ð¾Ñ‚Ð¾Ð²Ð½Ð¾ÑÑ‚,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° Ð²Ð°ÑˆÐ°Ñ‚Ð° ÑƒÑÐ»ÑƒÐ³Ð°</t>
    <t id="3209">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¡ÐŸÐ•Ð¨ÐÐž ÐŸÐ Ð•Ð”Ð£ÐŸÐ Ð•Ð–Ð”Ð•ÐÐ˜Ð• Ð—Ð ÐœÐÐ Ð¨Ð Ð£Ð¢Ð\n\nÐœÐ¾ÑÑ‚Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ñ€Ð°Ð·ÑƒÐ·Ð½Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ Ð¾Ñ‚ÐºÑ€Ð¸, Ñ‡Ðµ ÑÐµÐºÑ‚Ð¾Ñ€ %1 (Ð½Ð¸Ð²Ð¾ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð° %2) Ð²ÐµÑ‡Ðµ Ðµ Ð² Ð¼Ð¾Ñ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð°Ð½ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚. Ð—Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° Ð¸ ÐµÐºÐ¸Ð¿Ð°Ð¶Ð° Ð½ÐµÐ·Ð°Ð±Ð°Ð²Ð½Ð¾ Ð¿Ñ€ÐµÐºÑ€Ð°Ñ‚ÑÐ²Ð°Ð¼ Ñ‚ÐµÐºÑƒÑ‰Ð°Ñ‚Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ° Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ñ.\n\nÐŸÐ Ð•Ð”ÐŸÐ Ð˜Ð•Ð¢Ð˜ Ð”Ð•Ð™Ð¡Ð¢Ð’Ð˜Ð¯:\n- Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ ÑÐ° Ð°Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ð¸\n- Ð’Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð² Ñ€ÐµÐ¶Ð¸Ð¼ Ð½Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸\n- Ð©Ðµ ÑÐµ Ð½Ð°Ð¼ÐµÑ€Ð¸ Ð°Ð»Ñ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²ÐµÐ½ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿ÑŠÑ‚, ÐºÐ¾Ð¹Ñ‚Ð¾ Ð¸Ð·Ð±ÑÐ³Ð²Ð° Ð¾Ð¿Ð°ÑÐ½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸\n- ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð¸: ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ (Ñ‰Ðµ Ð¿Ñ€Ð¾Ð´Ð°Ð´Ðµ Ð²ÑÐµÐºÐ¸ Ñ‚Ð¾Ð²Ð°Ñ€ Ð½Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ Ð¼ÑÑÑ‚Ð¾, Ð°ÐºÐ¾ Ðµ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾)\n\nÐ¡Ð¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° Ñ Ð´Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÐ½ Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº Ñ‰Ðµ Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸ Ð±ÑŠÐ´ÐµÑ‰Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸ Ð¿Ñ€ÐµÐ· Ñ‚Ð¾Ð·Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð°Ñ‚Ð° Ð½Ðµ Ð¸Ð·Ñ‡ÐµÐ·Ð½Ðµ. Ñ€Ð°Ð·Ñ€ÐµÑˆÐµÐ½Ð¾.\n\nÐ‘ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ñ‚Ð° Ðµ Ð¼Ð¾Ð¹ Ð¿ÑŠÑ€Ð²Ð¸ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %3</t>
    <t id="3210">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ—ÐÐŸÐžÐ§Ð•Ð ÐŸÐªÐ¢ Ð—Ð Ð‘Ð¯Ð“Ð¡Ð¢Ð’Ðž\n\nÐ’ Ð¼Ð¾Ð¼ÐµÐ½Ñ‚Ð° ÑÑŠÐ¼ Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº ÑÐµÐºÑ‚Ð¾Ñ€ %1 Ð¸ Ð¾Ñ‚ÐºÑ€Ð¸Ñ… Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿ÑŠÑ‚, ÐºÐ¾Ð¹Ñ‚Ð¾ Ñ‰Ðµ Ð¼Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸ Ð´Ð° Ð¸Ð·Ð±ÑÐ³Ð°Ð¼ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾.\n\nÐ¢ÐªÐ Ð“ÐžÐ’Ð¡ÐšÐ˜ ÐŸÐªÐ¢:\nÐšÑƒÐ¿ÐµÑ‚Ðµ: %2 (Ð¡ÐµÐºÑ‚Ð¾Ñ€: %3)\nÐŸÑ€Ð¾Ð´Ð°Ð¹Ñ‚Ðµ: %4 (Ð¡ÐµÐºÑ‚Ð¾Ñ€: %5)\nÐ¡Ñ‚Ð¾Ð¹ÐºÐ°: %6 (x%7)\nÐžÑ‡Ð°ÐºÐ²Ð°Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°: %8 Cr\n\nÐšÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ñ‰Ðµ Ð¸Ð·Ð±ÑÐ³Ð° Ð¾Ñ‚ ÑÐµÐºÑ‚Ð¾Ñ€Ð° Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº ÑÐ»ÐµÐ´ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð°Ð·Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° Ð²Ð°ÑˆÐ°Ñ‚Ð° ÑƒÑÐ»ÑƒÐ³Ð°</t>
    <t id="3211">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ˜Ð—ÐžÐ›Ð˜Ð ÐÐ Ð Ð•Ð–Ð˜Ðœ ÐÐ Ð¢ÐªÐ Ð“ÐžÐ’Ð˜Ð¯\n\nÐ’ Ð¼Ð¾Ð¼ÐµÐ½Ñ‚Ð° ÑÑŠÐ¼ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %2, Ð½Ð¾ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ ÐºÑŠÐ¼ Ð´Ñ€ÑƒÐ³Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ ÑÐ° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸ Ð¾Ñ‚ Ñ†ÐµÐ½Ñ‚Ñ€Ð°Ð»Ð½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº. Ð¢Ð¾Ð²Ð° Ð¾Ð·Ð½Ð°Ñ‡Ð°Ð²Ð°, Ñ‡Ðµ Ð¼Ð¾Ð³Ð° Ð´Ð° Ñ‚ÑŠÑ€Ð³ÑƒÐ²Ð°Ð¼ ÑÐ°Ð¼Ð¾ Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ Ð½Ð° Ñ‚ÐµÐºÑƒÑ‰Ð¸Ñ ÑÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÑÑ‚Ð° Ñ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº ÑÐµ Ð¿Ñ€Ð¾Ð¼ÐµÐ½Ð¸.\n\nÐ¡Ð˜Ð¢Ð£ÐÐ¦Ð˜Ð¯:\nÐ¢ÐµÐºÑƒÑ‰ ÑÐµÐºÑ‚Ð¾Ñ€: %2\nÐ¡Ñ‚Ð°Ñ‚ÑƒÑ: Ð˜Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½ (ÑÐµÐºÑ‚Ð¾Ñ€ Ð±ÐµÐ· Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸)\nÐ ÐµÐ¶Ð¸Ð¼ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ: Ð¡Ð°Ð¼Ð¾ Ð²ÑŠÑ‚Ñ€ÐµÑˆÐ½Ð¾ÑÐµÐºÑ‚Ð¾Ñ€Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸\n\nÐœÐ¾ÑÑ‚Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÐºÐ¾Ñ€Ð¸Ð³Ð¸Ñ€Ð° Ð¿Ñ€Ð°Ð³Ð¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°Ñ‚Ð°, Ð·Ð° Ð´Ð° Ð´Ð°Ð´Ðµ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸Ñ‚Ðµ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ Ð½Ð° ÑÐµÐºÑ‚Ð¾Ñ€Ð°.\n\nÐ©Ðµ Ð³Ð¾ Ð½Ð°Ð¿Ñ€Ð°Ð²Ñ. Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶ÐµÑ‚Ðµ Ð´Ð° Ð½Ð°Ð±Ð»ÑŽÐ´Ð°Ð²Ð°Ñ‚Ðµ ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ð¸ÑÑ‚Ð° Ð¸ Ñ‰Ðµ Ð²Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ð¸Ð¼, Ð°ÐºÐ¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸Ñ‚Ðµ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ ÑÑ‚Ð°Ð½Ð°Ñ‚ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %1</t>
    <t id="3218">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐžÐ¢ÐšÐ Ð˜Ð¢Ð ÐŸÐ ÐžÐœÐ¯ÐÐ ÐÐ ÐŸÐªÐ¢Ð¯ ÐÐ ÐœÐÐ Ð¨Ð Ð£Ð¢Ð\n\nÐŸÑ€Ð¸ Ð½Ð°Ð²Ð»Ð¸Ð·Ð°Ð½Ðµ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %1, Ð½Ð°Ð²Ð¸Ð³Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð°Ñ‚Ð° Ð¼Ð¸ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð¾Ñ‚ÐºÑ€Ð¸, Ñ‡Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ÑŠÑ‚ Ð´Ð¾ Ð¼Ð¾ÑÑ‚Ð° Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ñ %2 (%3) ÑÐµ Ðµ Ð¿Ñ€Ð¾Ð¼ÐµÐ½Ð¸Ð».\n\nÐÐÐÐ›Ð˜Ð— ÐÐ ÐŸÐªÐ¢Ð¯:\n- ÐÐ¾Ñ€Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ: %4 ÑÐºÐ¾ÐºÐ°\n- Ð Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº: %5\n- Ð¡Ñ‚Ð°Ñ‚ÑƒÑ: %6\n\nÐœÐ¾ÑÑ‚ Ð½Ð°Ð²Ð¸Ð³Ð°Ñ†Ð¸Ð¾Ð½ÐµÐ½ ÐºÐ¾Ð¼Ð¿ÑŽÑ‚ÑŠÑ€ Ð¿Ð¾ÐºÐ°Ð·Ð²Ð°, Ñ‡Ðµ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð°Ð½Ð¸ÑÑ‚ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ð²ÐµÑ‡Ðµ Ð½Ðµ Ðµ Ð¶Ð¸Ð·Ð½ÐµÑÐ¿Ð¾ÑÐ¾Ð±ÐµÐ½ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð°. Ð—Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° Ð¸ ÐµÐºÐ¸Ð¿Ð°Ð¶Ð° Ð½ÐµÐ·Ð°Ð±Ð°Ð²Ð½Ð¾ Ð¿Ñ€ÐµÐºÑ€Ð°Ñ‚ÑÐ²Ð°Ð¼ Ñ‚ÐµÐºÑƒÑ‰Ð°Ñ‚Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ° Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ñ.\n\nÐŸÐ Ð•Ð”ÐŸÐ Ð˜Ð•Ð¢Ð˜ Ð”Ð•Ð™Ð¡Ð¢Ð’Ð˜Ð¯:\n- Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ¸ ÑÐ° Ð°Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ð¸\n- Ð’Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð² Ñ€ÐµÐ¶Ð¸Ð¼ Ð½Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸\n- Ð©Ðµ ÑÐµ Ð½Ð°Ð¼ÐµÑ€Ð¸ Ð°Ð»Ñ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²ÐµÐ½ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚, ÐºÐ¾Ð¹Ñ‚Ð¾ Ð¸Ð·Ð±ÑÐ³Ð²Ð° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸Ñ‚Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸\n- ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð°: ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ (Ñ‰Ðµ Ð¿Ñ€Ð¾Ð´Ð°Ð´Ðµ Ð²ÑÐµÐºÐ¸ Ñ‚Ð¾Ð²Ð°Ñ€ Ð½Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ Ð¼ÑÑÑ‚Ð¾, Ð°ÐºÐ¾ Ðµ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾)\n\nÐœÐ¾ÑÑ‚Ð° Ð½Ð°Ð²Ð¸Ð³Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ‰Ðµ Ð¸Ð·Ð±ÑÐ³Ð²Ð° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸Ñ‚Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð² Ð±ÑŠÐ´ÐµÑ‰ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð°Ð½Ðµ.\n\nÐ‘ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ñ‚Ð° Ðµ Ð¼Ð¾ÑÑ‚ Ð¿ÑŠÑ€Ð²Ð¸ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %7</t>
    <t id="3219">Ð¡ÐµÐºÑ‚Ð¾Ñ€ %1 Ð¸Ð·Ñ‡Ð¸ÑÑ‚ÐµÐ½ - Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ ÑÐ° ÐµÐ»Ð¸Ð¼Ð¸Ð½Ð¸Ñ€Ð°Ð½Ð¸</t>
    <t id="3220">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ’Ð ÐÐ–Ð•Ð’Ð˜Ð¯Ð¢ ÐšÐžÐ ÐÐ‘ Ð˜Ð—Ð‘Ð¯Ð“ÐÐ\n\nÐÐ°ÑˆÐ°Ñ‚Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ñ€Ð°Ð·ÑƒÐ·Ð½Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ Ðµ Ð¸Ð·Ð³ÑƒÐ±Ð¸Ð»Ð° ÑÐ»ÐµÐ´Ð¸Ñ‚Ðµ Ð½Ð° Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¸Ñ ÐºÐ¾Ñ€Ð°Ð± %3, ÐºÐ¾Ð¹Ñ‚Ð¾ Ðµ Ð¸Ð·Ð±ÑÐ³Ð°Ð» Ð¾Ñ‚ ÑÐµÐºÑ‚Ð¾Ñ€Ð° %1 Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº.\n\nÐŸÐžÐ”Ð ÐžÐ‘ÐÐžÐ¡Ð¢Ð˜:\n- Ð˜Ð·Ð±ÑÐ³Ð°Ð» ÐºÐ¾Ñ€Ð°Ð±: %3\n- Ð¡ÐµÐºÑ‚Ð¾Ñ€ Ð²Ð»ÑÐ²Ð¾: %1\n- Ð”ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð¡ÐµÐºÑ‚Ð¾Ñ€: %2\n- Ð¡Ñ‚Ð°Ñ‚ÑƒÑ: ÐŸÑ€Ð¾ÑÐ»ÐµÐ´ÑÐ²Ð°Ð½ÐµÑ‚Ð¾ Ðµ Ð¸Ð·Ð³ÑƒÐ±ÐµÐ½Ð¾ - ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ðµ Ð½Ð°Ð¿ÑƒÑÐ½Ð°Ð» Ð½Ð°ÑˆÐ°Ñ‚Ð° Ð½Ð°Ð±Ð»ÑŽÐ´Ð°Ð²Ð°Ð½Ð° Ð·Ð¾Ð½Ð°\n\nÐ’ÑŠÐ¿Ñ€ÐµÐºÐ¸ Ñ‡Ðµ Ñ‚Ð¾Ð·Ð¸ ÐºÐ¾Ñ€Ð°Ð± Ð²ÐµÑ‡Ðµ Ð½Ðµ Ðµ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð° Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %1, Ð·Ð°Ð³ÑƒÐ±Ð¸Ñ…Ð¼Ðµ Ð²Ð¸Ð·ÑƒÐ°Ð»ÐµÐ½ ÐºÐ¾Ð½Ñ‚Ð°ÐºÑ‚ Ð¸ Ð½Ðµ Ð¼Ð¾Ð¶ÐµÐ¼ Ð´Ð° Ð¿Ð¾Ñ‚Ð²ÑŠÑ€Ð´Ð¸Ð¼ Ñ‚ÐµÐºÑƒÑ‰Ð¾Ñ‚Ð¾ Ð¼Ñƒ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¸Ð»Ð¸ Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸Ñ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %2.\n\nÐÐ°ÑˆÐ¸Ñ‚Ðµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸ Ð·Ð° Ð¿Ñ€Ð¾ÑÐ»ÐµÐ´ÑÐ²Ð°Ð½Ðµ Ñ‰Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ñ‚ Ð´Ð° Ð½Ð°Ð±Ð»ÑŽÐ´Ð°Ð²Ð°Ñ‚ ÑÐµÐºÑ‚Ð¾Ñ€ %1 Ð·Ð° Ð¾ÑÑ‚Ð°Ð²Ð°Ñ‰Ð¸ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸. ÐÐºÐ¾ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ñ€Ð¾ÑÐ»ÐµÐ´ÐµÐ½Ð¸ Ð²Ñ€Ð°Ð³Ð¾Ð²Ðµ Ð½Ð°Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¸Ð»Ð¸ Ð±ÑŠÐ´Ð°Ñ‚ ÐµÐ»Ð¸Ð¼Ð¸Ð½Ð¸Ñ€Ð°Ð½Ð¸, ÑÐµÐºÑ‚Ð¾Ñ€ÑŠÑ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ‰Ðµ Ð±ÑŠÐ´Ðµ Ð¸Ð·Ñ‡Ð¸ÑÑ‚ÐµÐ½ Ð¾Ñ‚ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\nThreat Intelligence System</t>
    <t id="3221">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐÐµ ÑƒÑÐ¿ÑÑ… Ð´Ð° Ð½Ð°Ð¼ÐµÑ€Ñ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð½Ð° Ð¿Ð¾-Ð³Ð¾Ð»ÐµÐ¼Ð¸ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ñ (Ð´Ð¾ %3 ÑÐºÐ¾ÐºÐ¾Ð²Ðµ), Ñ‚ÑŠÐ¹ ÐºÐ°Ñ‚Ð¾ Ñ‚ÐµÐ·Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð² Ð¼Ð¾Ð¼ÐµÐ½Ñ‚Ð° ÑÐ° Ð½ÐµÐ´Ð¾ÑÑ‚ÑŠÐ¿Ð½Ð¸ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð·Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð° (Ð¿ÑŠÑ‚ÐµÐºÐ¸ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº).\n\nÐ¡Ð˜Ð¢Ð£ÐÐ¦Ð˜Ð¯:\nÐ¢ÐµÐºÑƒÑ‰ ÑÐµÐºÑ‚Ð¾Ñ€: %2\nÐžÑ€Ð¸Ð³Ð¸Ð½Ð°Ð»ÐµÐ½ Ð´Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ: %3 ÑÐºÐ¾ÐºÐ°\nÐ ÐµÐ·ÐµÑ€Ð²ÐµÐ½ Ð´Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ: %4 ÑÐºÐ¾ÐºÐ¾Ð²Ðµ\n\nÐ¡ÐµÐ³Ð° Ñ‰Ðµ Ñ„Ð¾ÐºÑƒÑÐ¸Ñ€Ð°Ð¼ Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ ÑÐ¸ Ð²ÑŠÑ€Ñ…Ñƒ Ð±Ð»Ð¸Ð·ÐºÐ¸Ñ‚Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ Ð½Ð° %4 ÑÐºÐ¾ÐºÐ¾Ð²Ðµ, ÐºÑŠÐ´ÐµÑ‚Ð¾ Ðµ Ð¿Ð¾-Ð²ÐµÑ€Ð¾ÑÑ‚Ð½Ð¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸Ñ‚Ðµ Ð´Ð° Ð±ÑŠÐ´Ð°Ñ‚ Ð´Ð¾ÑÑ‚ÑŠÐ¿Ð½Ð¸. Ð¢Ð¾Ð²Ð° Ñ‚Ñ€ÑÐ±Ð²Ð° Ð´Ð° Ð¼Ð¸ Ð¿Ð¾Ð¼Ð¾Ð³Ð½Ðµ Ð´Ð° Ð½Ð°Ð¼ÐµÑ€Ñ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ ÑÐ´ÐµÐ»ÐºÐ¸, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¿Ñ€ÐµÐ´Ð¸ Ñ‚Ð¾Ð²Ð° Ð±ÑÑ…Ð° Ñ„Ð¸Ð»Ñ‚Ñ€Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð½Ð° Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾, Ð° Ð½Ðµ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»Ð½Ð° Ð½ÐµÑ€ÐµÐ½Ñ‚Ð°Ð±Ð¸Ð»Ð½Ð¾ÑÑ‚.\n\nÐ©Ðµ Ð²Ð¸ ÑƒÐ²ÐµÐ´Ð¾Ð¼Ñ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½Ð°Ð¼ÐµÑ€Ñ Ð¿Ð¾Ð´Ñ…Ð¾Ð´ÑÑ‰Ð¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð² Ð±Ð»Ð¸Ð·ÐºÐ¸Ñ Ñ€Ð°Ð¹Ð¾Ð½.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %1</t>
    <t id="3222">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¡Ð•ÐšÐ¢ÐžÐ ÐªÐ¢ Ð’ Ð§Ð•Ð Ð•Ð Ð¡ÐŸÐ˜Ð¡ÐªÐš\n\nÐÐ°ÑˆÐ°Ñ‚Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ñ€Ð°Ð·ÑƒÐ·Ð½Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ Ð¾Ñ‚ÐºÑ€Ð¸ Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ð° Ð´ÐµÐ¹Ð½Ð¾ÑÑ‚ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %1 Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð¸ Ñ‚Ð¾Ð·Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº, Ð·Ð° Ð´Ð° Ð·Ð°Ñ‰Ð¸Ñ‚Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð½Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸.\n\nÐžÐ¢ÐšÐ Ð˜Ð¢Ð˜ Ð’Ð ÐÐ–Ð•Ð’Ð¡ÐšÐ˜ ÐšÐžÐ ÐÐ‘Ð˜:\n%2\n\nÐžÐ¢ÐšÐ Ð˜Ð¢Ð˜ ÐžÐ¢: %3\n\nÐ—Ð° Ð±ÐµÐ·Ð¾Ð¿Ð°ÑÐ½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð½Ð°ÑˆÐ¸Ñ‚Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð¸ ÐµÐºÐ¸Ð¿Ð°Ð¶, Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¿ÑŠÑ‚Ð¸Ñ‰Ð° Ð¿Ñ€ÐµÐ· Ñ‚Ð¾Ð·Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€ ÑÐ° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸. ÐÐ°ÑˆÐ¸Ñ‚Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ‰Ðµ Ð¾Ð±Ð¸ÐºÐ°Ð»ÑÑ‚ Ñ‚Ð¾Ð·Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð°Ñ‚Ð° Ð±ÑŠÐ´Ðµ ÐµÐ»Ð¸Ð¼Ð¸Ð½Ð¸Ñ€Ð°Ð½Ð°.\n\nÐ¡ÐµÐºÑ‚Ð¾Ñ€ÑŠÑ‚ Ñ‰Ðµ Ð±ÑŠÐ´Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¸Ð·Ñ‡Ð¸ÑÑ‚ÐµÐ½ Ð¾Ñ‚ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº, ÑÐ»ÐµÐ´ ÐºÐ°Ñ‚Ð¾ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ñ€Ð¾ÑÐ»ÐµÐ´ÐµÐ½Ð¸ Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð±ÑŠÐ´Ð°Ñ‚ ÐµÐ»Ð¸Ð¼Ð¸Ð½Ð¸Ñ€Ð°Ð½Ð¸ Ð¸Ð»Ð¸ Ð½Ð°Ð¿ÑƒÑÐ½Ð°Ñ‚ Ñ€Ð°Ð¹Ð¾Ð½Ð°.\n\nÐ¡ Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\nThreat Intelligence System</t>
    <t id="3223">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐÐµ Ð¼Ð¾Ð³Ð° Ð´Ð° Ð½Ð°Ð¼ÐµÑ€Ñ Ð´Ð¾ÑÑ‚ÑŠÐ¿Ð½Ð° Ñ‚Ñ€ÐµÐ½Ð¸Ñ€Ð¾Ð²ÑŠÑ‡Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð·Ð° Ð¼Ð¾Ñ Ð¸Ð·Ð¿Ð¸Ñ‚ Ð·Ð° Ð½Ð°Ð¿Ñ€ÐµÐ´Ð²Ð°Ð½Ðµ Ð½Ð° Ð½Ð¸Ð²Ð¾ %1. Ð©Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ñ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸ ÑÐ¿Ð¾Ñ€ÐµÐ´ Ð¸Ð½ÑÑ‚Ñ€ÑƒÐºÑ†Ð¸Ð¸Ñ‚Ðµ, Ð½Ð¾ Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð¼, Ñ‡Ðµ Ð½ÑÐ¼Ð° Ð´Ð° ÑÐ¿ÐµÑ‡ÐµÐ»Ñ Ñ‚Ð¾Ñ‡ÐºÐ¸ Ð·Ð° Ð¾Ð¿Ð¸Ñ‚, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð½Ðµ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ° Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾Ñ‚Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ. Ð¡Ð»ÐµÐ´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð¾Ð±ÐµÐ³ Ñ‰Ðµ Ð¿Ð¾Ñ‚ÑŠÑ€ÑÑ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ Ð²ÑÑÐºÐ° Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð° Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ.\n\nÐ¡ ÑƒÐ²Ð°Ð¶ÐµÐ½Ð¸Ðµ,\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %2</t>
    <t id="3224">Ð¢Ð°ÐºÑÐ° Ð·Ð° Ð»Ð¸Ñ†ÐµÐ½Ð· Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ: %1 Cr</t>
    <t id="3225">Ð‘Ð¾Ð½ÑƒÑ: Ð¡Ð¿ÐµÑ‡ÐµÐ»Ð¸Ñ… %1 Ð´Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð½Ð¸Ð²Ð¾ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸Ñ%2 Ð¾Ñ‚ Ð½Ð°Ñ‚Ñ€ÑƒÐ¿Ð°Ð½Ð¸Ñ Ð¾Ð¿Ð¸Ñ‚ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ! Ð¢ÐµÐºÑƒÑ‰Ð¾ Ð½Ð¸Ð²Ð¾: %3</t>
    <t id="3214">Ð—Ð° Ð¼ÐµÐ½ Ðµ Ñ‡ÐµÑÑ‚ Ð´Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ñ Ð·Ð° Ð²Ð°Ñ, %1! Ð’ÑŠÐ»Ð½ÑƒÐ²Ð°Ð¼ ÑÐµ Ð´Ð° Ð·Ð°Ð¿Ð¾Ñ‡Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ°Ñ‚Ð° ÑÐ¸ ÐºÐ°Ñ€Ð¸ÐµÑ€Ð° Ð¿Ð¾Ð´ Ð²Ð°ÑˆÐµ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð²Ð°Ð½Ðµ. Ð©Ðµ Ð½Ð°Ð¿Ñ€Ð°Ð²Ñ Ð²ÑÐ¸Ñ‡ÐºÐ¾ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ Ð´Ð° Ð²Ð¸ ÑÐ»ÑƒÐ¶Ð° Ð´Ð¾Ð±Ñ€Ðµ Ð¸ Ð´Ð° Ð´Ð¾Ð¿Ñ€Ð¸Ð½ÐµÑÐ° Ð·Ð° Ð²Ð°ÑˆÐ¸Ñ ÑƒÑÐ¿ÐµÑ….</t>
    <t id="3215">Ð‘Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ñ‚Ð¸, Ñ‡Ðµ Ð¼Ð¸ Ð¿Ð¾Ð´Ð°Ñ€Ð¸ Ñ‚Ð°Ð·Ð¸ Ð·Ð°ÑÐ»ÑƒÐ¶ÐµÐ½Ð° Ð¿Ð¾Ñ‡Ð¸Ð²ÐºÐ°, %1! ÐÐ°ÑÐ»Ð°Ð¶Ð´Ð°Ð²Ð°Ñ… ÑÐµ Ð½Ð° Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ ÑÐ¸ Ð´Ð°Ð»ÐµÑ‡ Ð¾Ñ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð° Ð¸ ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð¼Ð¸ Ð¾ÑÑ‚Ð°Ð²Ð°Ñ‚ Ð½ÐµÐ¿Ð¾ÐºÑŠÑ‚Ð½Ð°Ñ‚Ð¸. ÐžÑ‡Ð°ÐºÐ²Ð°Ð¼ Ñ Ð½ÐµÑ‚ÑŠÑ€Ð¿ÐµÐ½Ð¸Ðµ Ð´Ð° ÑÐµ Ð²ÑŠÑ€Ð½Ð° Ð½Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¸Ð¼Ð°Ñ‚Ðµ Ð½ÑƒÐ¶Ð´Ð° Ð¾Ñ‚ Ð¼ÐµÐ½. Ð”Ð¾Ñ‚Ð¾Ð³Ð°Ð²Ð° Ñ‰Ðµ Ð¿Ð¾Ð´Ð´ÑŠÑ€Ð¶Ð°Ð¼ Ð´Ð¾Ð±Ñ€Ðµ Ð¿Ð¾Ð·Ð½Ð°Ð½Ð¸ÑÑ‚Ð° ÑÐ¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ!</t>
    <t id="3216">Ð’ÑŠÑ€Ð½Ð°Ñ… ÑÐµ Ð¾Ñ‚ Ð¿Ð¾Ñ‡Ð¸Ð²ÐºÐ° Ð¸ ÑÑŠÐ¼ Ð³Ð¾Ñ‚Ð¾Ð² Ð´Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ñ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾, %1! Ð£Ð¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð¼Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð¾ÑÑ‚Ð°Ð²Ð°Ñ‚ Ð²Ð¸ÑÐ¾ÐºÐ¸ Ð¸ Ð½ÑÐ¼Ð°Ð¼ Ñ‚ÑŠÑ€Ð¿ÐµÐ½Ð¸Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ð´Ð° Ð²Ð¸ Ð¾Ð±ÑÐ»ÑƒÐ¶Ð²Ð°Ð¼ Ð½Ð° %2. Ð‘Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ð·Ð° Ð·Ð°ÑÐ»ÑƒÐ¶ÐµÐ½Ð°Ñ‚Ð° Ð¿Ð¾Ñ‡Ð¸Ð²ÐºÐ°!</t>
    <t id="3217">Ð‘Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ñ Ð²Ð¸ Ð·Ð° Ð¿Ñ€ÐµÑ…Ð²ÑŠÑ€Ð»ÑÐ½ÐµÑ‚Ð¾ Ð¼Ð¸ ÐºÑŠÐ¼ %1, %2! Ð—Ð° Ð¼ÐµÐ½ Ðµ Ñ‡ÐµÑÑ‚ Ð¾Ñ‚ Ñ‚Ð¾Ð²Ð° Ð½Ð¾Ð²Ð¾ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð¸ Ñ‰Ðµ ÑÐµ Ð³Ñ€Ð¸Ð¶Ð° Ð¾Ñ‚Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ð¼Ð¾Ñ Ð½Ð¾Ð² ÐºÐ¾Ñ€Ð°Ð±. ÐœÐ¾ÑÑ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ð¿Ð¸Ñ‚ Ð¸ ÑƒÐ¼ÐµÐ½Ð¸Ñ Ð¾ÑÑ‚Ð°Ð²Ð°Ñ‚ Ð½ÐµÐ¿Ð¾ÐºÑŠÑ‚Ð½Ð°Ñ‚Ð¸ Ð¸ ÑÑŠÐ¼ Ð³Ð¾Ñ‚Ð¾Ð² Ð´Ð° Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð° Ð´Ð° Ð²Ð¸ ÑÐ»ÑƒÐ¶Ð°.</t>
    <t id="3227">ÐšÐ¾Ñ€Ð¿ÑƒÑ Ð·Ð°Ð³ÑƒÐ±ÐµÐ½, Ð´Ð¾ÑÑ‚Ð¾Ð¹Ð½ÑÑ‚Ð²Ð¾Ñ‚Ð¾ Ñ‡Ð°ÐºÐ° Ð¿Ñ€Ð¸Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="3228">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð° %1,\n\n%2 Ð´Ð¾ÐºÐ»Ð°Ð´Ð²Ð° Ð¾Ñ‚ %3. ÐšÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð¼Ð¸ Ð³Ñ€ÑŠÐ¼Ð½Ð°. ÐÐ· - Ð½Ðµ. Ð’ÐµÑ‡Ðµ ÑÑŠÐ¼ Ð½Ð°Ð¹-ÑÐºÑŠÐ¿Ð¸ÑÑ‚ Ð¿Ð»ÑƒÐ²Ð°Ñ‰ Ñ‚Ð¾Ð²Ð°Ñ€ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°.\n\nÐœÐ°Ñ€ÐºÐµÑ€ Ð½Ð° ÐºÐ°Ñ€Ñ‚Ð°Ñ‚Ð° Ðµ Ð¿Ñ€Ð¸ÐºÐ°Ñ‡ÐµÐ½. ÐœÐ¾Ð»Ñ, Ð¿Ð¾Ð±ÑŠÑ€Ð·Ð°Ð¹Ñ‚Ðµ - Ð±ÑÑ… Ð¿Ð¾ ÑÑ€ÐµÐ´Ð°Ñ‚Ð° Ð½Ð° Ñ„Ð°ÐºÑ‚ÑƒÑ€Ð°.\n\nÐŸÑ€Ð¾Ñ„ÐµÑÐ¸Ð¾Ð½Ð°Ð»Ð½Ð¾ Ð¿Ð»ÑƒÐ²Ð°Ð¼,\n%2</t>
    <t id="3229">ÐŸÐ¸Ð»Ð¾Ñ‚ÑŠÑ‚ Ðµ ÑÐ¿Ð°ÑÐµÐ½ - Ð·Ð°Ð²Ð¸ÑÐ¸Ð¼Ð¾ÑÑ‚Ñ‚Ð° Ð¾Ñ‚ ÐºÐ¸ÑÐ»Ð¾Ñ€Ð¾Ð´ Ðµ Ð¸Ð·Ð»ÐµÑ‡ÐµÐ½Ð°</t>
    <t id="3230">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð° %1,\n\nÐÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°: %2 Ð±ÐµÑˆÐµ Ð¿Ñ€Ð¸Ð±Ñ€Ð°Ð½ Ð¾Ñ‚ %3 (%4) Ð¸ ÑÐ¿Ñ€Ñ Ð´Ð° Ð²Ð¸ Ñ‚Ð°ÐºÑÑƒÐ²Ð° Ð·Ð° ÑƒÐ´ÑŠÐ»Ð¶ÐµÐ½Ð¾ EVA Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ.\n\nÐŸÑ€ÐµÐ²Ñ€ÑŠÐ·Ð²Ð°Ð½Ðµ Ð½Ð° Ñ€ÐµÐ³Ð¸ÑÑ‚ÑŠÑ€Ð° Ð² Ñ…Ð¾Ð´. ÐŸÑ€ÐµÐ¿Ð¾Ñ€ÑŠÐºÐ°: Ð±ÐµÐ· Ð²ÑŠÐ¿Ñ€Ð¾ÑÐ¸ Ð·Ð° ÑÑ‚Ð°Ñ€Ð¸Ñ ÐºÐ¾Ñ€Ð°Ð±.\n\nÐ¡Ñ€Ð°Ð¼ÐµÐ¶Ð»Ð¸Ð²Ð¾ Ð²Ð°Ñˆ,\n%2</t>
<t id="4000">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°: %s Ð¿Ð¾Ð»ÑƒÑ‡Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s</t>
    <t id="4001">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°: ÐœÐ°Ñ€ÑˆÑ€ÑƒÑ‚ %s ÑÐµ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° Ð½Ð°Ð¿ÑŠÐ»Ð½Ð¾</t>
    <t id="4002">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°: %s Ð¿ÑƒÑÐ½Ð° Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s</t>
    <t id="5000">%s Ðµ Ð¾Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð° ÐºÐ°Ñ‚Ð¾ Ð¾ÑÐ½Ð¾Ð²Ð½Ð° Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ð¸Ñ Ð·Ð° %s</t>
    <t id="5001">%s Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ð° Ð½Ð¸Ð²Ð¾ Ð½Ð° ÐµÐºÑÐ¿ÐµÑ€Ñ‚Ð½Ð¾ÑÑ‚ %s Ð² %s!</t>
    <t id="5002">ÐŸÑ€Ð¸Ð»Ð¾Ð¶ÐµÐ½ Ð±Ð¾Ð½ÑƒÑ Ð·Ð° Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ð¸Ñ: %s%% ÑƒÐ²ÐµÐ»Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°Ñ‚Ð° Ð² %s</t>
    <t id="9500">Ð“Ñ€ÐµÑˆÐºÐ°: %s Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð° Ð¸ ÑÐµ Ð½ÑƒÐ¶Ð´Ð°Ðµ Ð¾Ñ‚ Ð¿Ð¾Ð¼Ð¾Ñ‰!</t>
    <t id="9501">Ð“Ñ€ÐµÑˆÐºÐ°: ÐÐµÑƒÑÐ¿ÐµÑˆÐ½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð·Ð° %s</t>
    <t id="9502">Ð“Ñ€ÐµÑˆÐºÐ°: ÐÐµ Ð¼Ð¾Ð¶Ðµ Ð´Ð° ÑÐµ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð° %s Ñ GalaxyTrader MK3</t>
    <t id="80001">Ware %s Ðµ Ð´Ð¾Ð±Ð°Ð²ÐµÐ½ ÐºÑŠÐ¼ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº</t>
    <t id="80002">Ware %s Ðµ Ð¿Ñ€ÐµÐ¼Ð°Ñ…Ð½Ð°Ñ‚ Ð¾Ñ‚ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº</t>
    <t id="80003">Ware %s Ðµ Ð´Ð¾Ð±Ð°Ð²ÐµÐ½ ÐºÑŠÐ¼ Ð±ÐµÐ»Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº</t>
    <t id="80004">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº (ÑÐ»Ð°Ð±Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚): %s</t>
    <t id="80005">ÐžÐ¿Ð°ÑÐµÐ½ Ñ„Ð°ÑÐ½Ñ Ñ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚: %s</t>
    <t id="80006">Ð¤Ð¸Ð»Ñ‚ÑŠÑ€ Ð·Ð° ÑÑ‚Ð¾ÐºÐ¸: %s Ð°ÐºÑ‚Ð¸Ð²ÐµÐ½, %s Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð°</t>
    <t id="80007">Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ñ„Ð¸Ð»Ñ‚Ñ€Ð¸ Ð·Ð° ÑÑ‚Ð¾ÐºÐ¸ ÑÐ° Ð¸Ð·Ñ‡Ð¸ÑÑ‚ÐµÐ½Ð¸</t>
    <t id="80008">Ð¤Ð¸Ð»Ñ‚Ñ€Ð¸Ñ‚Ðµ Ð½Ð° Ware ÑÐµ Ð½ÑƒÐ»Ð¸Ñ€Ð°Ñ‚ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="80009">Ð£Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð½Ð° Ware Filter</t>
    <t id="80010">Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="80011">ÐŸÐ¾Ð·Ð²Ð¾Ð»ÐµÐ½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="80012">Ð‘Ð¾Ñ€Ð°Ð²ÐµÐ½Ðµ Ñ Ð¾Ð¿Ð°ÑÐ½Ð¸ ÑÑŠÐ´Ð¾Ð²Ðµ</t>
    <t id="80013">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð°</t>
    <t id="80014">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ð½Ð° Ð¸Ð·Ð´ÐµÐ»Ð¸ÑÑ‚Ð°</t>
    <t id="80015">ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸</t>
    <t id="80016">ÐšÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð¸Ñ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ñ‚Ðµ ÑÐ° Ð°ÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¸ Ð¾Ñ‚ Ñ‚ÐµÐºÑƒÑ‰Ð¾Ñ‚Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‚Ð°</t>
    <t id="80017">%s ÑÑ‚Ð¾ÐºÐ¸, ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¸: %s Ñ Ð½Ð¸ÑÐºÐ° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚, %s Ð¾Ð¿Ð°ÑÐ½Ð¸, %s Ñ Ð²Ð¸ÑÐ¾ÐºÐ° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚</t>
    <t id="80018">Ð”Ð¸Ð½Ð°Ð¼Ð¸Ñ‡Ð½Ð°Ñ‚Ð° ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ð¸Ñ Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ñ‚Ðµ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð°</t>
    <t id="80019">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ñ‚Ð¾ Ð¿Ð¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº Ð·Ð° ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ñ %s Ðµ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾</t>
    <t id="80020">ÐžÑ‚ÐºÑ€Ð¸Ñ‚Ð¸ Ð¸ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¸ Ð½Ð¾Ð²Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð¾Ñ‚ Ð´Ñ€ÑƒÐ³Ð¸ Ð¼Ð¾Ð´Ð¾Ð²Ðµ</t>
    <t id="9000">GalaxyTrader - Ð“Ð»Ð¾Ð±Ð°Ð»Ð½Ð¸ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="9010">XP Ð¸ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="9012">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="9013">XP Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÐµÐ»</t>
    <t id="9015">Ð‘Ð¾Ð½ÑƒÑ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€</t>
    <t id="9020">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="9021">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÑÑ‚Ð° Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="9023">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ ÐºÐµÑˆ</t>
    <t id="9030">Ð˜Ð·Ð²ÐµÑÑ‚Ð¸Ñ</t>
    <t id="9031">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ</t>
    <t id="9040">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="9041">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ñ‚Ð¾ Ð¿Ð¾Ð¿Ñ€Ð°Ð²ÑÐ½Ðµ</t>
    <t id="9042">ÐŸÑ€Ð°Ð³ Ð·Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ Ð½Ð° ÐºÐ¾Ñ€Ð¿ÑƒÑÐ°</t>
    <t id="9310">Galaxy-Miner</t>
    <t id="9311">Ð˜Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð¿Ñ€Ð¸ ÑÐºÐ°Ð½Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÑÐ¾Ð½Ð´Ð¸ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð°</t>
    <t id="9312">Ð¢ÐµÐ³Ð»Ð¾ Ð½Ð° Ð±Ð»Ð¸Ð·Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="9043">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð½Ð¸Ð²Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚</t>
    <t id="9004">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ñ†ÐµÐ½Ð¾Ð²Ð¸ Ð´Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½Ð¸</t>
    <t id="9005">Ð¦ÐµÐ½Ð° Ð½Ð° Ð¾Ñ„ÐµÑ€Ñ‚Ð° Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° ÐœÐ°ÐºÑ</t>
    <t id="9006">ÐšÑƒÐ¿ÐµÑ‚Ðµ ÐžÑ„ÐµÑ€Ñ‚Ð° Ð¦ÐµÐ½Ð° ÐœÐ¸Ð½</t>
    <t id="9007">Ð˜Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½Ð¸: ÐœÐ°ÐºÑ. Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð½Ð° Ñ†ÐµÐ½Ð°</t>
    <t id="9008">Ð˜Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½Ð¸: Ð¦ÐµÐ½Ð° Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° ÐœÐ¸Ð½</t>
    <t id="9009">Ð ÐµÐ·ÐµÑ€Ð²ÐµÐ½ Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚: ÐœÐ°ÐºÑ. Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð½Ð° Ñ†ÐµÐ½Ð°</t>
    <t id="9014">Ð ÐµÐ·ÐµÑ€Ð²ÐµÐ½ Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚: Ð¦ÐµÐ½Ð° Ð·Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° ÐœÐ¸Ð½</t>
    <t id="9016">ÐžÑÐ½Ð¾Ð²Ð° Ð½Ð° Ð¿Ñ€Ð°Ð³Ð° Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°Ñ‚Ð°</t>
    <t id="9025">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¸ Ð¿Ð°Ñ€Ð¸ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð°</t>
    <t id="9024">Ð”Ð¾Ð¿ÑƒÑÑ‚Ð¸Ð¼Ð¾ Ð¾Ñ‚ÐºÐ»Ð¾Ð½ÐµÐ½Ð¸Ðµ Ð¾Ñ‚ ÐºÐµÑˆÐ°</t>
    <t id="9026">Ð’Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð½ÐµÐ°ÐºÑ‚Ð¸Ð²ÐµÐ½ Ð¿Ð°Ñ€ÐºÐ¸Ð½Ð³ Ð¿Ñ€ÐµÐ´Ð¸ Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°Ð²Ð°Ð½Ðµ</t>
    <t id="9054">Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð½Ð° Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸</t>
    <t id="9055">ÐÐ¸Ð²Ð¾ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð° Ð¾Ñ‚ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº</t>
    <t id="9056">Ð¡ÑŠÐ·Ð´Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½Ð¾Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº</t>
    <t id="9057">ÐŸÑ€ÐµÑÑŠÐ·Ð´Ð°Ð¹Ñ‚Ðµ</t>
    <t id="9058">ÐŸÑ€Ð¸ÑÐ²Ð¾ÑÐ²Ð°Ð½Ðµ Ð½Ð° GT ÐºÐ¾Ñ€Ð°Ð±Ð¸</t>
    <t id="9059">ÐŸÑ€Ð¸ÑÐ²Ð¾ÑÐ²Ð°Ð½Ðµ</t>
    <t id="9112">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¸Ð·Ð¿Ñ€Ð°Ñ‰Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ð°Ñ‚ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¸Ñ‚Ðµ Ð½Ð¸Ð²Ð°. Ð”ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ, Ð·Ð° Ð´Ð° ÐºÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€Ð°Ñ‚Ðµ Ñ€ÑŠÑ‡Ð½Ð¾ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ.</t>
    <t id="9113">Ð ÐµÐ³ÑƒÐ»Ð¸Ñ€Ð° ÐºÐ¾Ð»ÐºÐ¾ Ð±ÑŠÑ€Ð·Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸Ñ‚Ðµ Ð¿Ñ€Ð¸Ð´Ð¾Ð±Ð¸Ð²Ð°Ñ‚ Ð¾Ð¿Ð¸Ñ‚. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¾Ð·Ð½Ð°Ñ‡Ð°Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð° Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÐ¸Ñ.</t>
    <t id="9115">ÐŸÑ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð¾Ñ‚ Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð¸ XP, Ð¿Ñ€Ð¸ÑÑŠÐ´ÐµÐ½Ð¸ Ð½Ð° ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð¸-Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð—Ð°Ð´Ð°Ð¹Ñ‚Ðµ Ð½Ð° 0%, Ð·Ð° Ð´Ð° Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ñ‚Ðµ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ÑÐºÐ¸Ñ Ð±Ð¾Ð½ÑƒÑ XP. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 10%.</t>
    <t id="9121">ÐŸÐ¾Ð·Ð²Ð¾Ð»ÑÐ²Ð° Ð¸Ð½Ñ‚ÐµÐ»Ð¸Ð³ÐµÐ½Ñ‚Ð½Ð¸ Ñ„ÑƒÐ½ÐºÑ†Ð¸Ð¸ Ð·Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°, Ð²ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð¾Ð¿Ñ‚Ð¸Ð¼Ð¸Ð·Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð° Ð¸ Ð±Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾.</t>
    <t id="9123">ÐŸÐ¾Ð·Ð²Ð¾Ð»ÑÐ²Ð° ÑÐ¿Ð¾Ð´ÐµÐ»ÑÐ½Ðµ Ð½Ð° Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð¼ÐµÐ¶Ð´Ñƒ Ñ‡Ð»ÐµÐ½Ð¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð° Ð·Ð° Ð¿Ð¾-Ð´Ð¾Ð±Ñ€Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ.</t>
    <t id="9131">ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€Ð° ÐºÐ¾Ð»ÐºÐ¾ Ð¸Ð·Ð²ÐµÑÑ‚Ð¸Ñ Ð´Ð° ÑÐµ Ð¿Ð¾ÐºÐ°Ð·Ð²Ð°Ñ‚: 0=Ð¢Ð¸Ñ…Ð¾, 1=Ð¡Ð°Ð¼Ð¾ Ð²Ð°Ð¶Ð½Ð¸, 2=Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ð¸Ð·Ð²ÐµÑÑ‚Ð¸Ñ</t>
    <t id="9141">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¸Ð·Ð¿Ñ€Ð°Ñ‰Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð·Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ ÑÐ»ÐµÐ´ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ²Ð°Ð½Ðµ Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ¸, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÑŠÑ‚ Ð¿Ð°Ð´Ð½Ðµ Ð¿Ð¾Ð´ Ð¿Ñ€Ð°Ð³Ð°. Ð¡Ð°Ð¼Ð¾ Ð·Ð° Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ (ÐÐ¸Ð²Ð¾ 12+). ÐšÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð¸Ð·Ð±Ð¸Ñ€Ð°Ñ‚ Ð¿Ð¾Ð´Ñ…Ð¾Ð´ÑÑ‰Ð¾ ÑÑŠÐ¾Ñ€ÑŠÐ¶ÐµÐ½Ð¸Ðµ: S/M Equipment Dock, L/XL Shipyard.</t>
    <t id="9142">ÐŸÑ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° ÐºÐ¾Ñ€Ð¿ÑƒÑÐ°, Ð¿Ð¾Ð´ ÐºÐ¾Ð¹Ñ‚Ð¾ ÑÐµ Ð·Ð°Ð´ÐµÐ¹ÑÑ‚Ð²Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÐ½ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 95%. ÐšÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ‰Ðµ Ð¾Ñ‚Ð¸Ð´Ð°Ñ‚ Ð´Ð¾ Ð½Ð°Ð¹-Ð±Ð»Ð¸Ð·ÐºÐ¸Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ÐµÐ½ Ñ†ÐµÐ½Ñ‚ÑŠÑ€, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑÐ° Ð¿Ð¾Ð²Ñ€ÐµÐ´ÐµÐ½Ð¸.</t>
    <t id="9411">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, Ð¼Ð¸Ð½ÑŒÐ¾Ñ€Ð¸Ñ‚Ðµ Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ñ‚ Ð¿Ñ€Ð¸ Ð¾Ñ†ÐµÐ½ÐºÐ° Ð½Ð° Ñ€ÐµÑÑƒÑ€ÑÐ½Ð¸ ÑÐ¾Ð½Ð´Ð¸ Ð½Ð° Ñ„Ñ€Ð°ÐºÑ†Ð¸ÑÑ‚Ð° Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð° (+5 s Ð·Ð° Ð²ÑÑÐºÐ° ÑÐ¾Ð½Ð´Ð° Ð½Ð°Ð´ ÐµÐ´Ð½Ð°). GT Ð½Ð¸Ð²Ð¾Ñ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð»Ð¸Ð½ÐµÐ¹Ð½Ð¾ Ñ‚Ð¾Ð²Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ - Ð¾Ñ‚ Ð¿ÑŠÐ»Ð½Ð¾Ñ‚Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð½Ð¸Ð²Ð¾ 1 Ð´Ð¾ 5 ÑÐµÐºÑƒÐ½Ð´Ð¸ Ð½Ð° Ð½Ð¸Ð²Ð¾ 15 (ÑÐ°Ð¼Ð¾ GT XP Ñ€ÐµÐ¶Ð¸Ð¼, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð°Ð´Ð²Ð¸ÑˆÐ°Ð²Ð° 5 s). Ð˜Ð·ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾ = Ð±ÐµÐ· Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ (vanilla Ð¿Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ðµ).</t>
    <t id="9412">ÐÐ°ÑÐ¾Ñ‡Ð²Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸ MK3/MK4 ÐºÑŠÐ¼ Ð¿Ð¾-Ð±Ð»Ð¸Ð·ÐºÐ¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð·Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ð¿Ñ€Ð¸ ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐžÑ†ÐµÐ½ÐºÐ° Ð·Ð° Ð¸Ð·Ð±Ð¾Ñ€ = Ð¾Ñ†ÐµÐ½ÐºÐ° Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ°Ñ‚Ð° / (1 + ÑÐºÐ¾ÐºÐ¾Ð²Ðµ ÐºÐ¾Ñ€Ð°Ð±â†’Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ã— Ñ‚ÐµÐ³Ð»Ð¾). ÐŸÐ»ÑŠÐ·Ð³Ð°Ñ‡ 0-100 (0 = Ð¸Ð·ÐºÐ».; 4 = Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ 0,04). ÐÐµ Ð²Ð»Ð¸ÑÐµ Ð½Ð° ÐºÐµÑˆ ÐºÐ»Ð°ÑÐ°Ñ†Ð¸ÑÑ‚Ð° Ð¸Ð»Ð¸ Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ð¸Ð°Ð»Ð½Ð¸Ñ‚Ðµ Ð»Ð¸Ð¼Ð¸Ñ‚Ð¸ Ð½Ð° Ð¾Ð±Ñ…Ð²Ð°Ñ‚.</t>
    <t id="9143">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ð½Ð¾ Ð½Ð¸Ð²Ð¾, Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ð·Ð° Ñ„ÑƒÐ½ÐºÑ†Ð¸ÑÑ‚Ð° Ð·Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾Ð¿Ñ€Ð°Ð²ÑÐ½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 12 (Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ñ†Ð¸). ÐŸÐ¸Ð»Ð¾Ñ‚Ð¸Ñ‚Ðµ Ð¾Ñ‚ Ð¿Ð¾-Ð½Ð¸ÑÐºÐ¾ Ð½Ð¸Ð²Ð¾ Ñ‚Ñ€ÑÐ±Ð²Ð° Ð´Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð¸Ñ€Ð°Ñ‚ Ñ€ÑŠÑ‡Ð½Ð¾.</t>
    <t id="9104">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð° Ð¾Ñ‚Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»Ð½Ð° Ñ†ÐµÐ½Ð° Ð·Ð° Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° (ÐºÐ¾Ñ€Ð°Ð± ÐºÑƒÐ¿ÑƒÐ²Ð° ÐžÐ¢ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1,0 Ð´Ð¾ +1,0. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 0,5 (50% Ð½Ð°Ð´ ÑÑ€ÐµÐ´Ð½Ð¾Ñ‚Ð¾). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¾ = Ð¿Ð¾-ÑÐºÑŠÐ¿Ð¾, Ð½Ð¾ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¾Ð¿Ñ†Ð¸Ð¸.</t>
    <t id="9105">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð° Ð¾Ñ‚Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»Ð½Ð° Ñ†ÐµÐ½Ð° Ð·Ð° Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð·Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° (ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð° TO ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1,0 Ð´Ð¾ +1,0. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: -0,5 (50% Ð¿Ð¾Ð´ ÑÑ€ÐµÐ´Ð½Ð¾Ñ‚Ð¾). ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¾ = Ð¿Ð¾-ÐµÐ²Ñ‚Ð¸Ð½Ð¸ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸, Ð½Ð¾ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸.</t>
    <t id="9106">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð½Ð° Ñ†ÐµÐ½Ð° Ð·Ð° Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ (Ð·Ð°ÑÐµÐ´Ð½Ð°Ð»Ð¸ Ð² ÐµÐ´Ð¸Ð½ ÑÐµÐºÑ‚Ð¾Ñ€). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1,0 Ð´Ð¾ +1,0. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 0,5.</t>
    <t id="9107">ÐœÐ¸Ð½. Ñ†ÐµÐ½Ð° Ð·Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ð·Ð° Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ (Ð·Ð°ÑÐµÐ´Ð½Ð°Ð»Ð¸ Ð² ÐµÐ´Ð¸Ð½ ÑÐµÐºÑ‚Ð¾Ñ€). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1,0 Ð´Ð¾ +1,0. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: -0,5.</t>
    <t id="9108">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð½Ð° Ñ†ÐµÐ½Ð° Ð·Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ (Ð¿Ð¾ÑÐ»ÐµÐ´Ð½Ð° Ð¼ÑÑ€ÐºÐ°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½Ð¾Ñ€Ð¼Ð°Ð»Ð½Ð¾Ñ‚Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ðµ Ð½ÐµÑƒÑÐ¿ÐµÑˆÐ½Ð¾). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1,0 Ð´Ð¾ +1,0. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 0,5. Ð ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ñ‚Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° MaxDistance=2 Ð¸ Ð¾Ð±Ð»ÐµÐºÑ‡ÐµÐ½Ð¸ Ð¿Ñ€Ð°Ð³Ð¾Ð²Ðµ Ð·Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°.</t>
    <t id="9109">ÐšÑƒÐ¿ÐµÑ‚Ðµ Ð¼Ð¸Ð½. Ñ†ÐµÐ½Ð° Ð·Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ (Ð¿Ð¾ÑÐ»ÐµÐ´Ð½Ð° Ð¼ÑÑ€ÐºÐ°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½Ð¾Ñ€Ð¼Ð°Ð»Ð½Ð¾Ñ‚Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ðµ Ð½ÐµÑƒÑÐ¿ÐµÑˆÐ½Ð¾). Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½: -1,0 Ð´Ð¾ +1,0. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: -0,5. Ð ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ñ‚Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° MaxDistance=2 Ð¸ Ð¾Ð±Ð»ÐµÐºÑ‡ÐµÐ½Ð¸ Ð¿Ñ€Ð°Ð³Ð¾Ð²Ðµ Ð·Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°.</t>
    <t id="9116">ÐžÑÐ½Ð¾Ð²Ð½Ð° Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° Ð½Ð° Ð½Ð¸Ð²Ð¾ 15 Ð·Ð° ÑÑ€ÐµÐ´ÐµÐ½ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† (Ñ€ÐµÑ„ÐµÑ€ÐµÐ½Ñ‚ÐµÐ½ Ñ‚Ð¾Ð²Ð°Ñ€ 8200). Ð”ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»Ð½Ð°Ñ‚Ð° MinAbsoluteProfit ÑÐµ Ð¸Ð·Ñ‡Ð¸ÑÐ»ÑÐ²Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚ + Ð¼Ð°Ñ‰Ð°Ð±Ð¸Ñ€Ð°Ð½Ð° Ð¿Ð¾ Ñ‚Ð¾Ð²Ð°Ñ€:\n\nÐ±Ð°Ð·Ð°(L) = Ð‘Ð°Ð·Ð° * ((L-1)^2 / 14^2)\nÐ¼Ð°Ñ‰Ð°Ð± = Ð±Ð°Ð·Ð°(L) * (Ñ‚Ð¾Ð²Ð°Ñ€ / 8200)\nÐ¾ÐºÐ¾Ð½Ñ‡Ð°Ñ‚ÐµÐ»Ð½Ð° = Ð¼Ð°ÐºÑ.(Ð¼Ð°Ñ‰Ð°Ð±Ð¸Ñ€Ð°Ð½Ð¾, 25% Ð¾Ñ‚ Ð±Ð°Ð·Ð°(L))\n\nÐ—Ð°Ð´Ð°Ð¹Ñ‚Ðµ Ð½Ð° 0, Ð·Ð° Ð´Ð° Ð¿Ñ€Ð¸ÐµÐ¼ÐµÑ‚Ðµ Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° (ÑÐ°Ð¼Ð¾ ROI/Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ/Ð´Ñ€ÑƒÐ³Ð¸ Ñ„Ð¸Ð»Ñ‚Ñ€Ð¸ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð°Ð¼).</t>
    <t id="9125">ÐÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¸ ÑÐ° Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¸ Ð¿Ð°Ñ€Ð¸ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð° (ÐºÑ€ÐµÐ´Ð¸Ñ‚Ð¸), Ð¿Ñ€ÐµÐ´Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð´Ð° Ñ‚ÑŠÑ€ÑÑÑ‚ ÑÐ´ÐµÐ»ÐºÐ¸. ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ð¿Ð°Ñ€Ð¸Ñ‚Ðµ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð° Ð¿Ð°Ð´Ð½Ð°Ñ‚ Ð¿Ð¾Ð´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð°Ð³, Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°Ñ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð¸ Ñ‡Ð°ÐºÐ°Ñ‚, Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚ÑÐ²Ð°Ð¹ÐºÐ¸ ÑÐºÑŠÐ¿Ð¾Ñ‚Ð¾ ÑÐºÐ°Ð½Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÐºÐµÑˆÐ°, ÐºÐ¾ÐµÑ‚Ð¾ Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÐ²Ð° Ð·Ð°ÐµÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‚Ð°. ÐžÐ±Ñ…Ð²Ð°Ñ‚: 1000 - 100 000 Cr. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1000 Cr.</t>
    <t id="9124">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ ÑÐ¿Ð°Ð´ Ð½Ð° ROI Ð¾Ñ‚ ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð°Ñ‚Ð° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ð¿Ñ€ÐµÐ´Ð¸ Ð¾Ñ‚Ñ…Ð²ÑŠÑ€Ð»ÑÐ½Ðµ Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ°Ñ‚Ð°. ÐŸÑ€Ð¸Ð¼ÐµÑ€: 20% ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð° ROI Ñ 15% Ñ‚Ð¾Ð»ÐµÑ€Ð°Ð½Ñ Ð¿Ñ€Ð¸ÐµÐ¼Ð° Ð´Ð¾ 17% ROI (14% ÑÐ¿Ð°Ð´).</t>
    <t id="9126">ÐœÐ¸Ð½ÑƒÑ‚Ð¸ Ð½Ð° Ð´Ð¾Ðº Ð¿Ñ€ÐµÐ´Ð¸ Ð¾Ñ‚ÐºÐ°Ñ‡Ð²Ð°Ð½Ðµ Ð·Ð° Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ð¾Ñ€Ñ‚Ð° (0-60). 0 = Ð¾ÑÑ‚Ð°Ð²Ð° Ð½Ð° Ð´Ð¾Ðº, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð½Ðµ Ð±ÑŠÐ´Ðµ Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð° Ð½Ð¾Ð²Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´razÐ±Ð¸Ñ€Ð°Ð½Ðµ: 1 Ð¼Ð¸Ð½ÑƒÑ‚Ð°.</t>
    <t id="9154">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº Ð½Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸, Ð¿Ñ€Ð¸Ñ‚ÐµÐ¶Ð°Ð²Ð°Ð½Ð¸ Ð¾Ñ‚ Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸ (Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ° Ð·Ð° Ð²Ñ€ÑŠÐ·ÐºÐ° Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº)</t>
    <t id="9155">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð½Ð¸Ð²Ð¾ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð° (1-5), Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ð·Ð° Ð¿Ð¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð½Ð° ÑÐµÐºÑ‚Ð¾Ñ€ Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº:\n2=Ð¡Ñ€ÐµÐ´Ð½Ð¾ (ÐµÐ´Ð¸Ð½Ð¸Ñ‡Ð½Ð° Ð°Ñ‚Ð°ÐºÐ°)\n3=Ð¡Ñ€ÐµÐ´Ð½Ð¾-Ð²Ð¸ÑÐ¾ÐºÐ¾ (Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ð¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸)\n4=Ð’Ð¸ÑÐ¾ÐºÐ¾ (ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸/Ñ€Ð°ÐºÐµÑ‚Ð¸)\n5=ÐœÐ½Ð¾Ð³Ð¾ Ð²Ð¸ÑÐ¾ÐºÐ¾ (Xenon/Khaak)</t>
    <t id="9156">Ð ÑŠÑ‡Ð½Ð¾ Ð¿Ñ€ÐµÑÑŠÐ·Ð´Ð°Ð¹Ñ‚Ðµ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº Ð·Ð° Ð¸Ð·Ð±ÑÐ³Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ (Ð¿Ð¾Ð»ÐµÐ·Ð½Ð¾, Ð°ÐºÐ¾ Ðµ Ð±Ð¸Ð» Ð¸Ð·Ñ‚Ñ€Ð¸Ñ‚)</t>
    <t id="9157">Ð ÑŠÑ‡Ð½Ð¾ Ð¿Ñ€Ð¸ÑÐ²Ð¾ÐµÑ‚Ðµ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ñ Ð´Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÐ½ Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº ÐºÑŠÐ¼ Ð²ÑÐ¸Ñ‡ÐºÐ¸ GT ÐºÐ¾Ð¼Ð°Ð½Ð´Ð²Ð°Ñ‰Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°. ÐŸÐ¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð¸Ñ‚Ðµ Ð½Ð°ÑÐ»ÐµÐ´ÑÐ²Ð°Ñ‚ Ð¾Ñ‚ ÑÐ²Ð¾Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€.</t>
    <t id="6001">Ð§Ð¸Ñ€Ð°Ðº</t>
    <t id="6002">ÐšÑƒÑ€Ð¸ÐµÑ€</t>
    <t id="6003">Ð”Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ðº</t>
    <t id="6004">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ†</t>
    <t id="6005">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ†</t>
    <t id="6006">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° Ð´ÑŠÐ»Ð³Ð¸ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ñ</t>
    <t id="6101">Ð‘Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½</t>
    <t id="6102">ÐžÑ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð°</t>
    <t id="6103">Ð¤Ð¾ÐºÑƒÑÐ¸Ñ€Ð°Ð½ Ð²ÑŠÑ€Ñ…Ñƒ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð°</t>
    <t id="6104">Ð¢ÐµÐ¶ÐºÐ° Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð°</t>
    <t id="6105">ÐŸÐ¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ° Ð½Ð° ÐºÑƒÐ»Ð°</t>
    <t id="9050">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ð¸Ð·Ð±ÑÐ³Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸</t>
    <t id="9051">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¸Ð·Ð±ÑÐ³Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸:</t>
    <t id="9052">ÐŸÑ€Ð°Ð³ Ð½Ð° Ð²Ñ€Ð°Ð¶Ð´ÐµÐ±Ð½Ð° Ð²Ñ€ÑŠÐ·ÐºÐ°:</t>
    <t id="9053">Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ð´Ð¸Ð½Ð°Ð¼Ð¸Ñ‡ÐµÐ½ Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº:</t>
    <t id="9151">Ð¢ÑŠÑ€Ð³Ð¾Ð²Ñ†Ð¸Ñ‚Ðµ Ð¾Ñ‚ Ð½Ð¸Ð²Ð¾ 6+ Ð¾Ñ‚ÐºÑ€Ð¸Ð²Ð°Ñ‚ Ð²Ñ€Ð°Ð¶ÐµÑÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð¸ Ð¸Ð·Ð±ÑÐ³Ð²Ð°Ñ‚ Ð¾Ð¿Ð°ÑÐ½Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸. Ð”ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ ÑÐ¿Ð¸Ñ€Ð° Ñ†ÑÐ»Ð¾Ñ‚Ð¾ ÑÐºÐ°Ð½Ð¸Ñ€Ð°Ð½Ðµ (Ð¿Ð¾Ð´Ð¾Ð±Ñ€ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð°). Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ ÐºÑŠÐ¼ Ñ€Ð¸ÑÐº Ð·Ð° ÐºÐ¾Ñ€Ð°Ð± Ð² ÐºÐ¾Ð¼Ð°Ð½Ð´Ð½Ð¾ Ð¿Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ðµ (ÑÐºÐ°Ð»Ð° 0-10).</t>
    <t id="9152">ÐœÐ°Ñ€ÐºÐ¸Ñ€Ð°Ð¹Ñ‚Ðµ ÐºÐ°Ñ‚Ð¾ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ ÑÐ°Ð¼Ð¾ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸ Ñ Ð¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ðµ Ð½Ð° Ð¸Ð»Ð¸ Ð¿Ð¾Ð´ Ñ‚Ð°Ð·Ð¸ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: -20%</t>
    <t id="9153">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑÐ½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº (Ð½Ð¸Ð²Ð¾ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð° 3+), Ð·Ð° Ð´Ð° Ð¿Ñ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð´Ð° Ð·Ð°Ð¾Ð±Ð¸ÐºÐ¾Ð»ÑÑ‚ Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸Ñ‚Ðµ. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° vanilla pathfinding Ð·Ð° Ð°Ð»Ñ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸.</t>
    <t id="9060">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½Ðµ (Ð½Ð¸Ð²Ð¾ 15)</t>
    <t id="9061">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ:</t>
    <t id="9062">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð¼ÐµÑ€ÐºÐ¸:</t>
    <t id="9063">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð°ÑÐ¸Ñ‚Ðµ Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¸ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ:</t>
    <t id="9064">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ:</t>
    <t id="9065">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÐµÑ‚Ðµ Ð›Ð°Ð·ÐµÑ€Ð½Ð¸Ñ‚Ðµ ÐºÑƒÐ»Ð¸:</t>
    <t id="9066">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð°ÑÐ¸Ñ‚Ðµ Ð·Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ Ð½Ð° Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ:</t>
    <t id="9067">ÐŸÑ€Ð°Ð³ Ð½Ð° Ð¿Ñ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ðµ:</t>
    <t id="9068">Ð£Ð½Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ Ð¿Ñ€Ð°Ð³ Ð½Ð° ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚:</t>
    <t id="9069">ÐŸÑ€Ð¾Ñ„Ð¸Ð» Ð½Ð° Ð±Ð°Ð»Ð°Ð½ÑÐ° Ð½Ð° Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½ÐµÑ‚Ð¾:</t>
    <t id="9161">Master Traders (Ð½Ð¸Ð²Ð¾ 15) Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ñ€ÐµÐ·Ð°Ñ€ÐµÐ¶Ð´Ð° Ð·Ð°Ñ‰Ð¸Ñ‚Ð½Ð¾ Ð¾Ð±Ð¾Ñ€ÑƒÐ´Ð²Ð°Ð½Ðµ ÑÐ»ÐµÐ´ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÑ€Ð¸Ð»Ð°Ð³Ð° ÑÐµ Ð½Ð° Ð½Ð¸Ð²Ð¾ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ Ð·Ð° Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð¸.</t>
    <t id="9162">Ð’ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ (S/M/L/XL). ÐžÑ‚Ð´ÐµÐ»ÐµÐ½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚. ÐšÑ€Ð¸Ñ‚Ð¸Ñ‡ÐµÐ½ Ð·Ð° Ð¿Ñ€Ð¾Ñ‚Ð¸Ð²Ð¾Ñ€Ð°ÐºÐµÑ‚Ð½Ð°Ñ‚Ð° Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð°.</t>
    <t id="9163">Ð˜Ð·Ð¿Ñ€Ð°Ñ‰Ð° ÑÐµ ÑÐ°Ð¼Ð¾ L/XL. Ð¡Ð¿Ð¾Ð´ÐµÐ»Ñ ÑƒÐ½Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚ Ñ Ð´Ñ€ÑƒÐ³Ð¸ Ñ€Ð°Ð·Ð¿Ð¾Ð»Ð°Ð³Ð°ÐµÐ¼Ð¸ ÑƒÑÑ‚Ñ€Ð¾Ð¹ÑÑ‚Ð²Ð°.</t>
    <t id="9164">Ð˜Ð·Ð¿Ñ€Ð°Ñ‰Ð° ÑÐµ ÑÐ°Ð¼Ð¾ L/XL. ÐžÑ‚ ÑÑŠÑ‰ÐµÑÑ‚Ð²ÐµÐ½Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸. Ð¡Ð¿Ð¾Ð´ÐµÐ»Ñ Ð¾Ð±ÐµÐ´Ð¸Ð½ÐµÐ½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚.</t>
    <t id="9165">Ð’ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. L/XL ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ ÑÐ¿Ð¾Ð´ÐµÐ»ÑÑ‚ ÑƒÐ½Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚, S/M Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ñ‚ Ñ‚Ð¾Ð²Ð°Ñ€Ð¸.</t>
    <t id="9166">Ð˜Ð·Ð¿Ñ€Ð°Ñ‰Ð° ÑÐµ ÑÐ°Ð¼Ð¾ L/XL. Ð Ð°Ð±Ð¾Ñ‚Ð¸ ÑÑŠÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ. Ð¡Ð¿Ð¾Ð´ÐµÐ»Ñ Ð¾Ð±ÐµÐ´Ð¸Ð½ÐµÐ½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚.</t>
    <t id="9167">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÐµÑ‚Ðµ Ð·Ð°Ð¿Ð°ÑÐ¸Ñ‚Ðµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð¼ÐµÑ€ÐºÐ¸Ñ‚Ðµ ÑÐ° Ð¿Ð¾Ð´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ (Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸, Ð¾Ñ‚Ð´ÐµÐ»ÐµÐ½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚).</t>
    <t id="9168">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð°ÑÐ¸Ñ‚Ðµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¾Ð±Ñ‰Ð¸ÑÑ‚ Ð±Ñ€Ð¾Ð¹ Ð½Ð° Ñ€Ð°Ð·Ð¿Ð¾Ð»Ð°Ð³Ð°ÐµÐ¼Ð¸Ñ‚Ðµ Ñ‡Ð°ÑÑ‚Ð¸ Ðµ Ð¿Ð¾Ð´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ (L/XL ÐºÐ¾Ñ€Ð°Ð±Ð¸: Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ + ÐºÑƒÐ»Ð¸ ÑÐ¿Ð¾Ð´ÐµÐ»ÑÑ‚ ÐµÐ´Ð¸Ð½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚).</t>
    <t id="9169">Ð Ð°Ð·Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ½Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚ (L/XL ÐºÐ¾Ñ€Ð°Ð±Ð¸): Ð¤Ð¾ÐºÑƒÑÐ¸Ñ€Ð°Ð½ Ð²ÑŠÑ€Ñ…Ñƒ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ (20/50/20/10), Ð‘Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½ (35/35/20/10), ÐžÑ‚Ð±Ñ€Ð°Ð½Ð¸Ñ‚ÐµÐ»ÐµÐ½ (50/20/20/10), Ð¢ÐµÐ¶ÐºÐ° Ð¾Ñ‚Ð±Ñ€Ð°Ð½Ð° (40/30/20/10), ÐŸÐ¾Ð´ÐºÑ€ÐµÐ¿Ð° Ð½Ð° ÐºÑƒÐ»Ð° (30/30/30/10). Ð¡ÑŠÐ¾Ñ‚Ð½Ð¾ÑˆÐµÐ½Ð¸Ñ: Ð—Ð°Ñ‰Ð¸Ñ‚Ð°/Ð¢ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ/ÐšÑƒÐ»Ð¸/Ð ÐµÐ¼Ð¾Ð½Ñ‚. ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° Ð¿Ñ€ÐµÐ¼Ð¸Ð½ÐµÑ‚Ðµ Ð¿Ñ€ÐµÐ· Ð¾Ð¿Ñ†Ð¸Ð¸Ñ‚Ðµ.</t>
    <t id="9090">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="9091">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸Ñ‚Ðµ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="9191">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° Ð¸ Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð²ÑŠÐ· Ð¾ÑÐ½Ð¾Ð²Ð° Ð½Ð° Ð½Ð¸Ð²Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚. ÐÐ¸Ð²Ð¾ 9+ = ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ Ð¾Ñ‚ Ð½Ð¸Ð²Ð¾ 1, ÐÐ¸Ð²Ð¾ 12+ = ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ Ð¾Ñ‚ Ð½Ð¸Ð²Ð¾ 2, ÐÐ¸Ð²Ð¾ 15+ = ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸ Ð¾Ñ‚ Ð½Ð¸Ð²Ð¾ 3. Ð¡Ð°Ð¼Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ð¸Ñ‚Ðµ Ð² GT Ð¼Ð¾Ð´Ð¾Ð²Ðµ ÑÐµ Ð¿Ñ€ÐµÐ¼Ð°Ñ…Ð²Ð°Ñ‚, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ°Ñ‚Ð° Ð±ÑŠÐ´Ðµ Ð°Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ð°.</t>
    <t id="9070">ÐšÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð°Ñ†Ð¸Ñ Ð·Ð° Ð¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="9071">Ð”Ð¸ÑÐ¿Ð»ÐµÐ¹ XP:</t>
    <t id="9072">Ð”Ð¸ÑÐ¿Ð»ÐµÐ¹ Ñ€Ð°Ð½Ð³:</t>
    <t id="9073">ÐÐ¸Ð²Ð¾ Ð½Ð° Ð´Ð¸ÑÐ¿Ð»ÐµÑ:</t>
    <t id="9074">Ð¡ÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð´Ð¸ÑÐ¿Ð»ÐµÑ:</t>
    <t id="9075">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€ÐµÐ¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°:</t>
    <t id="9076">ÐŸÑ€ÐµÑ„Ð¸ÐºÑ</t>
    <t id="9077">Ð¡ÑƒÑ„Ð¸ÐºÑ</t>
    <t id="9078">Ð˜Ð¼Ðµ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ Ð˜Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸Ðº:</t>
    <t id="9079">Ð˜Ð¼Ðµ Ð½Ð° Ð¼Ð¾Ð´ÐµÐ»Ð°</t>
    <t id="9080">Ð¢Ð¸Ð¿ Ð¸Ð¼Ðµ</t>
    <t id="9081">ÐœÐ¾Ð´ÐµÐ»Ð½Ð° Ð±Ð°Ð·Ð°</t>
    <t id="9083">ÐŸÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¾ Ð¸Ð¼Ðµ</t>
    <t id="9084">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€:</t>
    <t id="9085">Ð ÐµÐ¶Ð¸Ð¼ Ð½Ð° Ð¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ:</t>
    <t id="9086">ÐšÐ»Ð°ÑÐ¸Ñ‡ÐµÑÐºÐ¸</t>
    <t id="9087">Ð¨Ð°Ð±Ð»Ð¾Ð½</t>
    <t id="9088">Ð¨Ð°Ð±Ð»Ð¾Ð½ Ð·Ð° Ð¸Ð¼Ðµ:</t>
    <t id="9089">ÐœÐ°Ñ€ÐºÐµÑ€Ð¸: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. ÐÑ‚Ð¾Ð¼Ð°Ñ€Ð½Ð¸: {RS} {CB} {BL} Ð¸ Ñ‚.Ð½. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸ÑÑ‚Ð° Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ð¾-Ð´Ð¾Ð»Ñƒ. ÐŸÑ€Ð°Ð·Ð½Ð¸Ñ‚Ðµ Ð¼Ð°Ñ€ÐºÐµÑ€Ð¸ ÑÐµ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°Ñ‚; Ð¸Ð½Ñ‚ÐµÑ€Ð²Ð°Ð»Ð¸Ñ‚Ðµ ÑÐµ ÑÐ³ÑŠÑÑ‚ÑÐ²Ð°Ñ‚. ÐœÐ°ÐºÑ. 128 Ð·Ð½Ð°ÐºÐ°.</t>
    <t id="9183">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð¸Ñ€Ð°Ð½Ð¸Ñ Ð´Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€ Ð² Ð¸Ð¼ÐµÑ‚Ð¾ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° (Ð¿Ñ€ÐµÑ„Ð¸ÐºÑ Ð¸Ð»Ð¸ ÑÑƒÑ„Ð¸ÐºÑ).</t>
    <t id="9184">ÐŸÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚ Ð½Ð° Ð¸Ð¼ÐµÑ‚Ð¾ Ñ Ð¼Ð°Ñ€ÐºÐµÑ€Ð¸ {TOKEN} Ð²Ð¼ÐµÑÑ‚Ð¾ ÐºÐ»Ð°ÑÐ¸Ñ‡ÐµÑÐºÐ¸Ñ‚Ðµ Ð¿Ñ€ÐµÐ²ÐºÐ»ÑŽÑ‡Ð²Ð°Ñ‚ÐµÐ»Ð¸. Ð˜Ð·Ð¸ÑÐºÐ²Ð° GalaxyTrader XP (Ð½Ðµ vanilla XP Ñ€ÐµÐ¶Ð¸Ð¼).</t>
    <t id="9092">ÐœÐ°Ñ€ÐºÐµÑ€Ð¸ Ð½Ð° ÑˆÐ°Ð±Ð»Ð¾Ð½</t>
    <t id="9093">ÐšÐ¾Ñ€Ð°Ð±: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP Ð½Ð° GT: {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Ð‘Ð°Ð·Ð°: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Ð•ÐºÐ¸Ð¿Ð°Ð¶: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Ð¡ÐµÐºÑ‚Ð¾Ñ€: {SECTOR} | Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">ÐœÐ°Ñ€ÐºÐµÑ€Ð¸ Ð½Ð° ÑÑ‚Ð°Ñ‚ÑƒÑ:</t>
    <t id="9100">{OPSTATE}: Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ð½Ð¸ Ñ„Ð»Ð°Ð³Ð¾Ð²Ðµ (Ð½Ð°Ð¿Ñ€. CB RS, MT)</t>
    <t id="9101">{STATUS}: Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½, Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ, Ñ€ÐµÐ·ÐµÑ€Ð² Ð¸Ð»Ð¸ Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½</t>
    <t id="9102">{CB}: ÑÐ°Ð¼Ð¾ Ð¿ÐµÑ€ÑÐ¾Ð½Ð°Ð»ÐµÐ½ blacklist, Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½ Ð² {OPSTATE}, Ð½Ðµ ÐºÐ¾Ð¼Ð±Ð¸Ð½Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ</t>
    <t id="9082">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° ÐºÐ»Ð°Ñ ÐºÐ¾Ñ€Ð°Ð±:</t>
    <t id="9171">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° XP ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ</t>
    <t id="9175">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¸Ð»Ð¸ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ñ‚Ð¾ Ð¿Ñ€ÐµÐ¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð± Ñ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð·Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="9172">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ñ€Ð°Ð½Ð³Ð¾Ð²Ðµ Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ</t>
    <t id="9173">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ð½Ð¾Ð¼ÐµÑ€Ð°Ñ‚Ð° Ð½Ð° Ð½Ð¸Ð²Ð°Ñ‚Ð° Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ</t>
    <t id="9174">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÑ‚Ð°Ñ‚ÑƒÑ Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ</t>
    <t id="9178">Ð˜Ð·Ð±ÐµÑ€ÐµÑ‚Ðµ Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ° Ð·Ð° Ð¸Ð¼ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° Ð±Ð°Ð·Ð°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°: Ð˜Ð¼Ðµ Ð½Ð° Ð¼Ð¾Ð´ÐµÐ»Ð° (Ñ Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚), Ð˜Ð¼Ðµ Ð½Ð° Ñ‚Ð¸Ð¿Ð° (Ð¾Ð±Ñ‰Ð¾), Ð‘Ð°Ð·Ð° Ð½Ð° Ð¼Ð¾Ð´ÐµÐ»Ð° (Ð±ÐµÐ· Ð²Ð°Ñ€Ð¸Ð°Ð½Ñ‚) Ð¸Ð»Ð¸ ÐŸÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¾ Ð¸Ð¼Ðµ (ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¾ Ð¸Ð¼Ðµ)</t>
    <t id="9182">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° ÐºÐ»Ð°ÑÐ° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° (S, M, L, XL) Ð² Ð¸Ð¼ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="9200">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð·Ð° Ð¾Ñ‚ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸</t>
    <t id="9201">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸:</t>
    <t id="9202">Ð“Ð»Ð°Ð²ÐµÐ½ Ð¿Ñ€ÐµÐ²ÐºÐ»ÑŽÑ‡Ð²Ð°Ñ‚ÐµÐ» Ð·Ð° Ñ†ÐµÐ»Ð¸Ñ Ð¸Ð·Ñ…Ð¾Ð´ debug_text. ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, Ñ†ÑÐ»Ð¾Ñ‚Ð¾ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸ ÑÐµ Ð¿Ð¾Ñ‚Ð¸ÑÐºÐ°. ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, ÑÑŠÐ¾Ð±Ñ‰ÐµÐ½Ð¸ÑÑ‚Ð° Ð·Ð° Ð¾Ñ‚ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸ ÑÐµ Ð¿Ð¾ÑÐ²ÑÐ²Ð°Ñ‚ Ð² DebugLog Ð²ÑŠÐ· Ð¾ÑÐ½Ð¾Ð²Ð° Ð½Ð° Ð¸Ð½Ð´Ð¸Ð²Ð¸Ð´ÑƒÐ°Ð»Ð½Ð¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð° ÑˆÐ°Ð½ÑÐ° debug_text.</t>
    <t id="9220">ÐŸÐ¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ° Ð¸ Ð´Ð¸Ð°Ð³Ð½Ð¾ÑÑ‚Ð¸ÐºÐ°</t>
    <t id="9221">ÐÑƒÐ»Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°Ñ‚Ð° Ð·Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°Ñ‚Ð°:</t>
    <t id="9222">ÐÐ£Ð›Ð˜Ð ÐÐÐ•</t>
    <t id="9223">Ð˜Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð°Ð½Ðµ Ð½Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð² Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº:</t>
    <t id="9224">Ð¯Ð¡ÐÐž</t>
    <t id="9225">ÐÑƒÐ»Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð´Ð¾ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸Ñ‚Ðµ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ:</t>
    <t id="9226">ÐÐ£Ð›Ð˜Ð ÐÐ™Ð¢Ð• Ð’Ð¡Ð˜Ð§ÐšÐ˜</t>
    <t id="9323">ÐŸÑ€ÐµÐ¼Ð°Ñ…Ð²Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð¾Ñ‚ Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº Ð·Ð° Ñ€Ð°Ð·ÑƒÐ·Ð½Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸. This will immediately clear all blacklisted sectors and allow your ships to travel to previously blocked areas. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð°, Ð°ÐºÐ¾ Ð¸ÑÐºÐ°Ñ‚Ðµ Ð´Ð° Ð½ÑƒÐ»Ð¸Ñ€Ð°Ñ‚Ðµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° Ð·Ð° Ð¸Ð·Ð±ÑÐ³Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸ Ð¸Ð»Ð¸ Ð°ÐºÐ¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸Ñ‚Ðµ ÑÐ° Ð½ÐµÐ¿Ñ€Ð°Ð²Ð¸Ð»Ð½Ð¾ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸ Ð² Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº.</t>
    <t id="9321">ÐÑƒÐ»Ð¸Ñ€Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ¸ Ð·Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð¸ Ð´Ð¾ 0 Ð·Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð° ÑÐ»ÐµÐ´ Ð½Ð°Ð´Ð³Ñ€Ð°Ð¶Ð´Ð°Ð½Ðµ Ð´Ð¾ v0.6.0, Ð·Ð° Ð´Ð° Ð¸Ð·Ñ‡Ð¸ÑÑ‚Ð¸Ñ‚Ðµ Ð·Ð°Ð²Ð¸ÑˆÐµÐ½Ð¸Ñ‚Ðµ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ¸, Ð±Ð°Ð·Ð¸Ñ€Ð°Ð½Ð¸ Ð½Ð° Ð¿Ñ€Ð¸Ñ…Ð¾Ð´Ð¸. ÐšÐ¾Ñ€ÐµÐºÑ†Ð¸ÑÑ‚Ð° Ð²ÐµÑ‡Ðµ Ð¿Ñ€Ð¾ÑÐ»ÐµÐ´ÑÐ²Ð° Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ‚ÐµÐ»Ð½Ð°Ñ‚Ð° ÐŸÐ•Ð§ÐÐ›Ð‘Ð (Ð¿Ñ€Ð¸Ñ…Ð¾Ð´ - Ñ†ÐµÐ½Ð° Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ°). Ð‘Ñ€Ð¾ÑÑ‚ Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ¸Ñ‚Ðµ Ð¸ XP ÑÐµ Ð·Ð°Ð¿Ð°Ð·Ð²Ð°Ñ‚.</t>
    <t id="9325">Ð’ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð³Ð»Ð¾Ð±Ð°Ð»Ð½Ð¸ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð´Ð¾ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸Ñ‚Ðµ Ð¸Ð¼ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ. Ð¢Ð¾Ð²Ð° Ð²ÐºÐ»ÑŽÑ‡Ð²Ð° Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð·Ð° XP, ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°, Ð¸Ð·Ð²ÐµÑÑ‚Ð¸Ñ, Ð¼Ð¾Ð±Ð¸Ð»ÐµÐ½ Intel, Ð¸Ð·Ð±ÑÐ³Ð²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð»Ð°Ñ…Ð¸, Ð¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸, Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡ÐµÐ½ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚, Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ð¸, Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚ Ð¸ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð·Ð° Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚ Ð½Ð° Ð½Ð¾Ð¼ÐµÑ€Ð°. ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ°Ñ‚Ð° Ð·Ð° Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸ ÑÐµ Ð·Ð°Ð¿Ð°Ð·Ð²Ð°, Ð·Ð° Ð´Ð° Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸ÑÑ‚Ð° Ð·Ð° Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ðµ.</t>
    <t id="9227">Ð˜Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ ÐºÐµÑˆ Ð·Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸:</t>
    <t id="9228">Ð˜Ð—Ð§Ð˜Ð¡Ð¢Ð’ÐÐÐ• ÐÐ ÐšÐ•Ð¨Ð</t>
    <t id="9327">Ð˜Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ ÐºÐµÑˆ Ð·Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸. Ð¢Ð¾Ð²Ð° Ñ‰Ðµ Ð¿Ñ€Ð¸Ð½ÑƒÐ´Ð¸ Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð´Ð° Ð¸Ð·Ð²ÑŠÑ€ÑˆÐ²Ð°Ñ‚ Ð½Ð¾Ð²Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð½Ð° Ð¶Ð¸Ð²Ð¾ Ð¿Ñ€Ð¸ ÑÐ»ÐµÐ´Ð²Ð°Ñ‰Ð¾Ñ‚Ð¾ ÑÐ¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð°, Ð°ÐºÐ¾ ÐºÐµÑˆÑŠÑ‚ Ð¸Ð·Ð³Ð»ÐµÐ¶Ð´Ð° Ð¾ÑÑ‚Ð°Ñ€ÑÐ» Ð¸Ð»Ð¸ Ð¿Ð¾Ð²Ñ€ÐµÐ´ÐµÐ½, Ð¸Ð»Ð¸ Ð°ÐºÐ¾ Ð¸ÑÐºÐ°Ñ‚Ðµ Ð´Ð° Ð¿Ñ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚Ðµ Ð¿ÑŠÐ»Ð½Ð¾ Ð¾Ð¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½Ðµ Ð½Ð° ÐºÐµÑˆÐ°.</t>
    <t id="9229">ÐžÑÐ²Ð¾Ð±Ð¾Ð´ÐµÑ‚Ðµ Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ»ÑŽÑ‡Ð°Ð»ÐºÐ¸ Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ</t>
    <t id="9329">ÐžÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°Ð²Ð° Ð’Ð¡Ð˜Ð§ÐšÐ˜ Ð·Ð°ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ð¸Ñ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð¿Ð¾Ð»ÐµÑ‚ Ð¸ Ð¸Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð° ÑÐ²ÑŠÑ€Ð·Ð°Ð½Ð¾Ñ‚Ð¾ Ð¿Ñ€ÐµÑ…Ð¾Ð´Ð½Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð°, Ð°ÐºÐ¾ ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ ÑÐ° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸ Ð½Ð° â€žÐ¢ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ¸â€œ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð¾ÑÑ‚Ð°Ñ€ÐµÐ»Ð¸ ÐºÐ»ÑŽÑ‡Ð°Ð»ÐºÐ¸ Ð¾Ñ‚ ÑÑ‚Ð°Ñ€Ð¸ Ð·Ð°Ð¿Ð¸ÑÐ²Ð°Ð½Ð¸Ñ. Ð¢Ð¾Ð²Ð° Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€ÐµÐºÑŠÑÐ½Ðµ Ð·Ð°ÐºÐ¾Ð½Ð½Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ.</t>
    <t id="9290">Ð¡ÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Dump Trade Hub:</t>
    <t id="9291">Ð”ÐªÐœÐŸ</t>
    <t id="9390">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð° ÐµÐ´Ð½Ð¾ÐºÑ€Ð°Ñ‚Ð½Ð° ÑÐ½Ð¸Ð¼ÐºÐ° Ð½Ð° Ñ†ÐµÐ½Ñ‚Ñ€Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¸Ñ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ñ†ÐµÐ½Ñ‚ÑŠÑ€ (Ð¾Ð¿Ð°ÑˆÐºÐ¸ Ð·Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð°Ð½Ðµ + ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¿Ð¾ÑÐ»ÐµÐ´Ð½Ð¸Ñ Ð·Ð°ÑÐ²ÐµÐ½ ÐºÐ¾Ñ€Ð°Ð±) Ð² Ð´Ð½ÐµÐ²Ð½Ð¸ÐºÐ° Ð¸ ÐºÐ°Ñ‚Ð¾ Ð¸Ð·Ð²ÐµÑÑ‚Ð¸Ðµ.</t>
    <t id="9292">Ð˜Ð·Ñ…Ð²ÑŠÑ€Ð»ÐµÑ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ ÐºÐµÑˆ (ÐŸÐªÐ›Ð•Ð):</t>
    <t id="9293">Ð”ÐªÐœÐŸ ÐšÐ•Ð¨</t>
    <t id="9392">ÐŸÐªÐ›Ð•Ð Ð´ÑŠÐ¼Ð¿ Ð½Ð° ÐºÐµÑˆÐ° (Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð±ÑŠÐ´Ðµ Ð¾Ð³Ñ€Ð¾Ð¼ÐµÐ½). Ð—Ð°Ð¿Ð¸ÑÐ²Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² ÐºÐµÑˆÐ° Ð² DebugLog Ð½Ð° Ñ‡Ð°ÑÑ‚Ð¸. ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾, Ð·Ð° Ð´Ð° Ð¾Ñ‚Ð¼ÐµÐ½Ð¸Ñ‚Ðµ.</t>
    <t id="9294">Ð˜Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð°Ð½Ðµ Ð½Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð°Ñ†Ð¸Ð¸Ñ‚Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°:</t>
    <t id="9295">Ð¯Ð¡ÐÐž</t>
    <t id="9394">Ð˜Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð°Ñ†Ð¸Ð¸ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð°, Ð°ÐºÐ¾ ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð¸Ð·Ð³Ð»ÐµÐ¶Ð´Ð°Ñ‚ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¸ Ð² Ð¾Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¸Ð·Ñ‚Ð¸Ñ‡Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð°Ð·ÐµÐ½Ð¸Ñ‚Ðµ ÑÐ´ÐµÐ»ÐºÐ¸ Ð¸Ð»Ð¸ Ð°ÐºÐ¾ Ñ‚Ð°Ð±Ð»Ð¸Ñ†Ð°Ñ‚Ð° Ð·Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð°Ñ†Ð¸Ð¸ Ðµ Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð° ÑÐ»ÐµÐ´ Ð·Ð°Ñ€ÐµÐ¶Ð´Ð°Ð½Ðµ Ð½Ð° ÑÑ‚Ð°Ñ€Ð¾ Ð·Ð°Ð¿Ð°Ð·Ð²Ð°Ð½Ðµ.</t>
    <t id="9230">Ð˜Ð·Ð¿ÑŠÐ»Ð½ÐµÐ½Ð¸Ðµ</t>
    <t id="9231">Ð—Ð°Ð±Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ð¿Ð°ÐºÐµÑ‚Ð½Ð°Ñ‚Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°:</t>
    <t id="9232">Ð—Ð°Ð±Ð°Ð²ÑÐ½Ðµ Ð¿Ñ€Ð¸ Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½Ðµ:</t>
    <t id="9233">ÐœÐ°ÐºÑ. ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ:</t>
    <t id="9234">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸ Ð·Ð° Ð²Ñ€ÑŠÑ‰Ð°Ð½Ðµ:</t>
    <t id="9235">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¸ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð·Ð° ÑÑ‚Ð¾ÐºÐ°:</t>
    <t id="9236">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸ Ð½Ð° ÑÑ‚Ð¾ÐºÐ°:</t>
    <t id="9237">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¸ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð·Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚ Ð·Ð° ÑÑŠÐ²Ð¿Ð°Ð´ÐµÐ½Ð¸Ðµ:</t>
    <t id="9238">ÐŸÑ€Ð°Ð³ Ð·Ð° Ñ€Ð°Ð½Ð½Ð¾ Ð¸Ð·Ð»Ð¸Ð·Ð°Ð½Ðµ:</t>
    <t id="9241">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð½Ð° Ñ‡Ð°ÑÑ‚ Ð¾Ñ‚ Ð¾Ñ„ÐµÑ€Ñ‚Ð°Ñ‚Ð° Ð½Ð° Ð¶Ð¸Ð²Ð¾:</t>
    <t id="9266">TTL Ð·Ð° Ð·Ð°ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾:</t>
    <t id="9263">Ð Ð°Ð·Ð¼ÐµÑ€ Ð½Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð½Ð¸Ñ Ð±Ð»Ð¾Ðº:</t>
    <t id="9239">Ð§Ð¸ÑÐ»Ð¾Ð² Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚</t>
    <t id="9240">Ð¡Ñ‚Ð¸Ð» Ð½Ð° Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚Ð¸Ñ€Ð°Ð½Ðµ:</t>
    <t id="9242">Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ ÑÑƒÑ„Ð¸ÐºÑ M</t>
    <t id="9243">ÐŸÑ€Ð°Ð³ Ð½Ð° ÑÑƒÑ„Ð¸ÐºÑ M:</t>
    <t id="9244">Ð½ÐµÐ¼ÑÐºÐ¸ (123 456,78)</t>
    <t id="9245">Ð°Ð½Ð³Ð»Ð¸Ð¹ÑÐºÐ¸ (123 456,78)</t>
    <t id="9510">Ð˜Ð·Ð²ÐµÑÑ‚Ð¸Ñ Ð·Ð° Ð¿Ð¾Ð²Ð¸ÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½Ð¸Ð²Ð¾:</t>
    <t id="9511">Ð¡Ð¸Ð³Ð½Ð°Ð»Ð¸ Ð·Ð° Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ:</t>
    <t id="9512">Ð˜Ð·Ð²ÐµÑÑ‚Ð¸Ñ Ð·Ð° Ð·Ð°Ð²ÑŠÑ€ÑˆÐµÐ½Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ:</t>
    <t id="9513">ÐžÑ‚Ñ‡ÐµÑ‚Ð¸ Ð·Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°:</t>
    <t id="9514">ÐŸÐ°Ð·Ð°Ñ€Ð½Ð¸ ÑÐ¸Ð³Ð½Ð°Ð»Ð¸:</t>
    <t id="9515">ÐžÐ±Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°:</t>
    <t id="9516">Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ ÑÐ°Ð¼Ð¾ Ð²Ð°Ð½Ð¸Ð»Ð¸Ñ XP</t>
    <t id="9610">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¸Ð»Ð¸ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð¸Ð·ÑÐºÐ°Ñ‡Ð°Ñ‰Ð¸Ñ‚Ðµ Ð¸Ð·Ð²ÐµÑÑ‚Ð¸Ñ Ð·Ð° Ð¿Ð¾Ð²Ð¸ÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½Ð¸Ð²Ð¾ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ†Ð° Ð² Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹ÑÐ° Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð°.</t>
    <t id="9611">Ð¡Ð¸Ð³Ð½Ð°Ð», ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸Ñ‚Ðµ ÑÐµ Ð½ÑƒÐ¶Ð´Ð°ÑÑ‚ Ð¾Ñ‚ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð·Ð° Ð½Ð°Ð¿Ñ€ÐµÐ´Ð²Ð°Ð½Ðµ Ð½Ð° ÑÐ»ÐµÐ´Ð²Ð°Ñ‰Ð¾ Ð½Ð¸Ð²Ð¾.</t>
    <t id="9612">Ð˜Ð·Ð²ÐµÑÑ‚Ð¸Ðµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸Ñ‚Ðµ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ°Ñ‚ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð¸ Ð½Ð°Ð¿Ñ€ÐµÐ´Ð½Ð°Ñ‚ Ð² Ñ€Ð°Ð½Ð³.</t>
    <t id="9613">ÐŸÐµÑ€Ð¸Ð¾Ð´Ð¸Ñ‡Ð½Ð¸ Ð¾Ð±Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð¸Ñ‚Ðµ (Ð¿Ñ€Ð¾ÑÑ‚Ð¸ Ð¸ Ð¸Ð·Ñ‡ÐµÑ€Ð¿Ð°Ñ‚ÐµÐ»Ð½Ð¸ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð¸).</t>
    <t id="9614">Ð˜ÑÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¸ Ð¿Ð°Ð·Ð°Ñ€Ð½Ð¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ð¸ Ð¸ ÑÐ¸Ð³Ð½Ð°Ð»Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ñ Ð²Ð¸ÑÐ¾ÐºÐ° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚.</t>
    <t id="9615">Ð¡ÑŠÐ¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð·Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð° Ð¸ Ð¾Ð±Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ð¸Ñ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾.</t>
    <t id="9616">Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ pilot.skill.piloting Ð¸ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ GT XP progression/caps.</t>
    <t id="9246">Ð§ÐµÑÑ‚Ð¾Ñ‚Ð° Ð½Ð° Ð¿Ñ€Ð¾ÑÑ‚Ð¸ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð¸:</t>
    <t id="9247">Ð§ÐµÑÑ‚Ð¾Ñ‚Ð° Ð½Ð° Ð¸Ð·Ñ‡ÐµÑ€Ð¿Ð°Ñ‚ÐµÐ»Ð½Ð¸ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð¸:</t>
    <t id="9248">ÐœÐ°ÐºÑ ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð² ÐºÐµÑˆÐ°:</t>
    <t id="9249">ÐœÐ°ÐºÑ. ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð½Ð° Ð¶Ð¸Ð²Ð¾:</t>
    <t id="9340">Ð˜Ð·Ð±ÐµÑ€ÐµÑ‚Ðµ Ñ‡Ð¸ÑÐ»Ð¾Ð² Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚: ÐÐµÐ¼ÑÐºÐ¸ÑÑ‚ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° '.' Ð·Ð° Ñ…Ð¸Ð»ÑÐ´Ð¸ Ð¸ ',' Ð·Ð° Ð´ÐµÑÐµÑ‚Ð¸Ñ‡Ð½Ð¸ Ð·Ð½Ð°Ñ†Ð¸ (123.456,78), Ð°Ð½Ð³Ð»Ð¸Ð¹ÑÐºÐ¸ÑÑ‚ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ',' Ð·Ð° Ñ…Ð¸Ð»ÑÐ´Ð¸ Ð¸ '.' Ð·Ð° Ð´ÐµÑÐµÑ‚Ð¸Ñ‡Ð½Ð¸ Ð·Ð½Ð°Ñ†Ð¸ (123 456,78)</t>
    <t id="9342">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÑÑƒÑ„Ð¸ÐºÑ M Ð·Ð° Ñ‡Ð¸ÑÐ»Ð°, Ð¿Ð¾-Ð³Ð¾Ð»ÐµÐ¼Ð¸ Ð¾Ñ‚ Ð¿Ñ€Ð°Ð³Ð° (Ð½Ð°Ð¿Ñ€. 1,0 M Ð²Ð¼ÐµÑÑ‚Ð¾ 1 000 000)</t>
    <t id="9343">ÐŸÑ€Ð°Ð³ Ð·Ð° M ÑÑƒÑ„Ð¸ÐºÑ. Ð§Ð¸ÑÐ»Ð°Ñ‚Ð° Ð½Ð°Ð´ Ñ‚Ð°Ð·Ð¸ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ñ‰Ðµ ÑÐµ Ð¿Ð¾ÐºÐ°Ð·Ð²Ð°Ñ‚ Ñ M Ð½Ð°ÑÑ‚Ð°Ð²ÐºÐ° (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 999 999)</t>
    <t id="9346">Ð§ÐµÑÑ‚Ð¾Ñ‚Ð° Ð½Ð° Ð¿Ñ€Ð¾ÑÑ‚ Ð¾Ñ‚Ñ‡ÐµÑ‚ (Ð¸Ð·ÑÐºÐ°Ñ‡Ð°Ñ‰Ð¾ Ð¸Ð·Ð²ÐµÑÑ‚Ð¸Ðµ): 0-30 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸ (0 = Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾ - Ð¿Ñ€Ð¾ÑÑ‚Ð¸Ñ‚Ðµ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð¸ ÑÐ° Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¸, Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1 Ð¼Ð¸Ð½ÑƒÑ‚Ð°)</t>
    <t id="9347">Ð§ÐµÑÑ‚Ð¾Ñ‚Ð° Ð½Ð° Ð¸Ð·Ñ‡ÐµÑ€Ð¿Ð°Ñ‚ÐµÐ»ÐµÐ½ Ð¾Ñ‚Ñ‡ÐµÑ‚ (Ð·Ð°Ð¿Ð¸Ñ Ð² Ð´Ð½ÐµÐ²Ð½Ð¸ÐºÐ°): 0-60 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸ (0 = Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾ - Ð¸Ð·Ñ‡ÐµÑ€Ð¿Ð°Ñ‚ÐµÐ»Ð½Ð¸Ñ‚Ðµ Ð¾Ñ‚Ñ‡ÐµÑ‚Ð¸ ÑÐ° Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¸, Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 30 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸)</t>
    <t id="9398">Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð¹Ñ‚Ðµ GT Credits Due Override</t>
    <t id="9399">Ð—Ð°Ð¼ÐµÐ½ÐµÑ‚Ðµ Ð¸Ð»Ð¸ Ñ€Ð°Ð·ÑˆÐ¸Ñ€ÐµÑ‚Ðµ Ñ€ÐµÐ´Ð° â€žCR Ð´ÑŠÐ»Ð¶Ð¸Ð¼Ð¸ Ð¾Ñ‚ ÑÐ´ÐµÐ»ÐºÐ¸â€œ Ñ Ð¿Ñ€Ð¾Ð³Ð½Ð¾Ð·Ð½Ð°Ñ‚Ð° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ð½Ð° GT Ð² ÑÑŠÑ‰Ð¸Ñ ÑÐ»Ð¾Ñ‚ Ð½Ð° Ð¿Ð¾Ñ‚Ñ€ÐµÐ±Ð¸Ñ‚ÐµÐ»ÑÐºÐ¸Ñ Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹Ñ.</t>
    <t id="9331">Ð—Ð°Ð±Ð°Ð²ÑÐ½Ðµ Ð¼ÐµÐ¶Ð´Ñƒ Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð¸Ñ‚Ðµ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ (1-500ms). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 120ms. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð² Ð¿Ð°Ñ€Ñ‚Ð¸Ð´ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€ Ð¸ Ñ„Ð¸Ð»Ñ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÐ¿Ð¸ÑÑŠÑ†Ð¸.</t>
    <t id="9332">Ð—Ð°Ð±Ð°Ð²ÑÐ½Ðµ Ð¼ÐµÐ¶Ð´Ñƒ Ð²Ð°Ð»Ð¸Ð´Ð°Ñ†Ð¸Ð¸Ñ‚Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð° Ð² AI ÑÐºÑ€Ð¸Ð¿Ñ‚ (1-500ms). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 50ms. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¿Ñ€Ð¸ Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÐ¿Ð¸ÑÑŠÐº Ð¾Ñ‚ MD ÑÐ¸ÑÑ‚ÐµÐ¼Ð°.</t>
    <t id="9333">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° ÑÐµ Ð¸Ð·Ð¿ÑŠÐ»Ð½ÑÐ²Ð°Ñ‚ ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ (1-10). ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°Ñ‚Ð°. ÐŸÑ€Ð¾Ñ†ÐµÑÑŠÑ‚ Ð½Ð° Ð¿Ð¾-Ð²Ð¸ÑÐ¾ÐºÐ¸ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ñ‚ÑŠÑ€ÑÐ¸ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð´Ð¾Ð²ÐµÐ´Ðµ Ð´Ð¾ ÑÐºÐ¾ÐºÐ¾Ð²Ðµ Ð² Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9334">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸ Ð·Ð° Ð²Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð¾Ñ‚ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð² ÐºÐµÑˆÐ° (1-100). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ñ€ÐµÐ´Ð¾ÑÑ‚Ð°Ð²ÑÑ‚ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¾Ð¿Ñ†Ð¸Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÐºÐµÑˆÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¶Ð¸Ð·Ð½ÐµÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 20.</t>
    <t id="9335">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð·Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚ Ð·Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð¿Ñ€Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾ (5-100). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð²Ð·ÐµÐ¼Ð°Ñ‚ Ð¿Ñ€ÐµÐ´Ð²Ð¸Ð´ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 20.</t>
    <t id="9336">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ ÑÐ´ÐµÐ»ÐºÐ¸ Ð½Ð° ÑÑ‚Ð¾ÐºÐ° Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð½Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° (5-100). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚ Ð¿Ð¾Ð²ÐµÑ‡Ðµ ÑÐ´ÐµÐ»ÐºÐ¸ Ð½Ð° ÑÑ‚Ð¾ÐºÐ°, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 20.</t>
    <t id="9337">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð·Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚ Ð·Ð° ÑÑŠÐ²Ð¿Ð°Ð´ÐµÐ½Ð¸Ðµ Ð² Ð¿Ð°Ñ€Ñ‚Ð¸Ð´ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€ (5-100). ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð²Ð·ÐµÐ¼Ð°Ñ‚ Ð¿Ñ€ÐµÐ´Ð²Ð¸Ð´ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 20.</t>
    <t id="9338">ÐŸÑ€Ð°Ð³ Ð·Ð° Ñ€Ð°Ð½Ð½Ð¾ Ð¸Ð·Ð»Ð¸Ð·Ð°Ð½Ðµ Ð·Ð° Ð¿Ð°ÐºÐµÑ‚Ð½Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° (100-10000). ÐšÐ¾Ð³Ð°Ñ‚Ð¾ ÑÐµ Ð¾Ñ‚ÐºÑ€Ð¸ÑÑ‚ Ñ‚Ð¾Ð»ÐºÐ¾Ð²Ð° Ð¼Ð½Ð¾Ð³Ð¾ ÑÐ´ÐµÐ»ÐºÐ¸, Ð³Ñ€ÑƒÐ¿Ð¾Ð²Ð°Ñ‚Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° ÑÐ¿Ð¸Ñ€Ð° Ñ€Ð°Ð½Ð¾, Ð·Ð° Ð´Ð° ÑÐ¿ÐµÑÑ‚Ð¸ CPU. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾Ð²ÐµÑ‡Ðµ ÑÐ´ÐµÐ»ÐºÐ¸, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¸Ð·Ð»Ð¸Ð·Ð°Ñ‚ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 2000.</t>
    <t id="9341">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð½Ð° Ð¾Ñ‚Ñ€ÑÐ·ÑŠÑ†Ð¸ Ð¾Ñ‚ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð½Ð° Ð¶Ð¸Ð²Ð¾ Ð² Ð¼Ð¸Ð»Ð¸ÑÐµÐºÑƒÐ½Ð´Ð¸ (5-2000 ms). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€Ð° ÐºÐ¾Ð»ÐºÐ¾ Ñ‡ÐµÑÑ‚Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð·Ð°Ð¿Ð¾Ñ‡Ð²Ð°Ñ‚ ÑÐµÐ³Ð¼ÐµÐ½Ñ‚Ð¸ Ñ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð½Ð° Ð¶Ð¸Ð²Ð¾. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾ ÑÑŠÐ±Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¾Ñ„ÐµÑ€Ñ‚Ð¸, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°Ñ‚Ð° Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 500ms.</t>
    <t id="9363">Ð Ð°Ð·Ð¼ÐµÑ€ Ð½Ð° Ð±Ð»Ð¾ÐºÐ° Ð·Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð½Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° (5-20). ÐžÐ±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð° ÐºÐ¾Ð¼Ð±Ð¸Ð½Ð°Ñ†Ð¸Ð¸ chunkSizeÃ—chunkSize Ð½Ð° Ð¿Ð°Ñ€Ñ‡Ðµ (Ð½Ð°Ð¿Ñ€. 5Ã—5 = 25 ÐºÐ¾Ð¼Ð±Ð¸Ð½Ð°Ñ†Ð¸Ð¸). ÐŸÐ¾-Ð³Ð¾Ð»ÐµÐ¼Ð¸Ñ‚Ðµ Ð¿Ð°Ñ€Ñ‡ÐµÑ‚Ð° Ð¿Ð¾Ð´Ð¾Ð±Ñ€ÑÐ²Ð°Ñ‚ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°Ñ‚ÐµÐ»Ð½Ð°Ñ‚Ð° ÑÐ¿Ð¾ÑÐ¾Ð±Ð½Ð¾ÑÑ‚, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð° Ð½Ð° Ð¿Ð°Ñ€Ñ‡Ðµ. ÐŸÐ¾-Ð¼Ð°Ð»ÐºÐ¸Ñ‚Ðµ Ð¿Ð°Ñ€Ñ‡ÐµÑ‚Ð° Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÑÐºÐ¾ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¸Ð·Ð¸ÑÐºÐ²Ð°Ñ‚ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶ÐµÐ½Ð¸Ñ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 5.</t>
    <t id="9348">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð² ÐºÐµÑˆÐ°, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° ÑÐµ Ð¸Ð·Ð¿ÑŠÐ»Ð½ÑÐ²Ð°Ñ‚ ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ (1-20). Ð¢ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð² ÐºÐµÑˆÐ° Ðµ Ð±ÑŠÑ€Ð·Ð¾ Ð¸ ÐµÐ²Ñ‚Ð¸Ð½Ð¾; Ð¿Ð¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð½Ð°Ð¼Ð°Ð»ÑÑ‚ ÑÐ¿ÑƒÐºÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð¿Ñ€Ð¸ Ð¾Ð³Ñ€Ð¾Ð¼Ð½Ð¸ Ñ„Ð»Ð¾Ñ‚Ð¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 2.</t>
    <t id="9349">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð½Ð° Ð¶Ð¸Ð²Ð¾, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° ÑÐµ Ð¸Ð·Ð¿ÑŠÐ»Ð½ÑÐ²Ð°Ñ‚ ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾ (1-10). Ð¢ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð¶Ð¸Ð²Ð¾ Ð¸Ð·Ð¸ÑÐºÐ²Ð° CPU, Ñ‚Ð°ÐºÐ° Ñ‡Ðµ Ð¿Ð¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° CPU, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°. ÐŸÑ€Ð¾Ñ†ÐµÑÑŠÑ‚ Ð½Ð° Ð¿Ð¾-Ð²Ð¸ÑÐ¾ÐºÐ¸ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ñ‚ÑŠÑ€ÑÐ¸ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð´Ð¾Ð²ÐµÐ´Ðµ Ð´Ð¾ ÑÐºÐ¾ÐºÐ¾Ð²Ðµ Ð² Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9264">Ð Ð°Ð·Ð¼ÐµÑ€ Ð½Ð° Ñ‡Ð°ÑÑ‚ Ð¾Ñ‚ ÐºÐµÑˆ Ð·Ð°ÑÐ²ÐºÐ°Ñ‚Ð°:</t>
    <t id="9265">Ð Ð°Ð·Ð¼ÐµÑ€ Ð½Ð° Ð´Ð¾Ð±Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ñ‡Ð°ÑÑ‚ Ð¾Ñ‚ Ð¾Ñ„ÐµÑ€Ñ‚Ð°Ñ‚Ð° Ð½Ð° Ð¶Ð¸Ð²Ð¾:</t>
    <t id="9364">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² ÐºÐµÑˆÐ°, Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½Ð¸ Ð·Ð° Ð¿Ð°Ñ€Ñ‡Ðµ (10-200). ÐŸÐ¾-Ð¼Ð°Ð»ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ñ‚ Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÐºÐµÑˆÐ° Ð² Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ñ€Ð°Ð¼ÐºÐ¸ (Ð¿Ð¾-Ð¿Ð»Ð°Ð²Ð½Ð¾), Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° ÑƒÐ´ÑŠÐ»Ð¶Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð½Ð°Ð¼Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 10.</t>
    <t id="9365">ÐžÑ„ÐµÑ€Ñ‚Ð¸, Ð´Ð¾Ð±Ð°Ð²ÐµÐ½Ð¸ Ð½Ð° ÑÑ€ÐµÐ· Ð·Ð° Ð´Ð¾Ð±Ð°Ð²ÑÐ½Ðµ (50-2000). ÐŸÐ¾-Ð¼Ð°Ð»ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ñ€Ð°Ð±Ð¾Ñ‚Ð°Ñ‚Ð° Ð¿Ð¾ Ð´Ð¾Ð±Ð°Ð²ÑÐ½Ðµ Ð½Ð° ÑÐ¿Ð¸ÑÑŠÐº ÐºÑŠÐ¼ ÐºÐ°Ð´ÑŠÑ€ (Ð¿Ð¾-Ð¿Ð»Ð°Ð²Ð½Ð¾), Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð¶Ð¸Ð²Ð¾. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 200.</t>
    <t id="9366">Ð’Ñ€ÐµÐ¼Ðµ Ð·Ð° Ð¶Ð¸Ð²Ð¾Ñ‚ Ð¿Ñ€Ð¸ Ð·Ð°ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð² ÑÐµÐºÑƒÐ½Ð´Ð¸ (60-7200). ÐÐºÐ¾ Ð´Ð°Ð´ÐµÐ½ ÐºÐ¾Ñ€Ð°Ð± Ð±ÑŠÐ´Ðµ Ð¾Ñ‚ÐºÐ°Ð·Ð°Ð½ Ñ â€žÑ‚ÑŠÑ€ÑÐµÐ½Ðµ, ÐºÐ¾ÐµÑ‚Ð¾ Ð²ÐµÑ‡Ðµ Ðµ Ð² Ñ…Ð¾Ð´â€œ Ð·Ð° Ð¿Ð¾-Ð´ÑŠÐ»Ð³Ð¾ Ð¾Ñ‚ Ñ‚Ð¾Ð²Ð° Ð²Ñ€ÐµÐ¼Ðµ, GT Ñ‰Ðµ ÑÐµ ÑÐ°Ð¼Ð¾Ð²ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸, ÐºÐ°Ñ‚Ð¾ Ð¸Ð·Ñ‡Ð¸ÑÑ‚Ð¸ Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð¾Ñ‚Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð¸ Ð¾ÑÐ²Ð¾Ð±Ð¾Ð´Ð¸ Ð·Ð°ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½ÐµÑ‚Ð¾. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 600s.</t>
    <t id="9370">ÐœÐµÐº Ð¿Ñ€Ð°Ð³ Ð½Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð½Ð¾ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾ Ð½Ð°Ð»ÑÐ³Ð°Ð½Ðµ:</t>
    <t id="9371">Ð¢Ð²ÑŠÑ€Ð´ Ð¿Ñ€Ð°Ð³ Ð½Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð½Ð¾ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾ Ð½Ð°Ð»ÑÐ³Ð°Ð½Ðµ:</t>
    <t id="9372">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð½Ð° ÑÑ€ÐµÐ·:</t>
    <t id="9373">ÐžÐ¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð´Ð¾Ð¼Ð°:</t>
    <t id="9374">ÐšÐµÑˆÐ¸Ñ€Ð°Ð¹Ñ‚Ðµ Miss Cooldown Base:</t>
    <t id="9375">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð½Ð° Ñ‚Ð¸ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ°:</t>
    <t id="9376">ÐœÐ°ÐºÑ. ÐºÐµÑˆ Ð·Ð°ÑÐ²ÐºÐ¸ Ð½Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ°:</t>
    <t id="9377">ÐœÐ°ÐºÑ. Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ð²Ð°Ð½Ð¸Ñ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ°:</t>
    <t id="9378">ÐœÐ°ÐºÑ. Ð¸Ð·Ð¿Ñ€Ð°Ñ‰Ð°Ð½Ð¸Ñ Ð½Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ°:</t>
    <t id="9379">ÐœÐ°ÐºÑ. Ð°Ñ€Ñ‚Ð¸ÐºÑƒÐ»Ð¸ Ð½Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ°:</t>
    <t id="9380">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ ÑÑŠÐ±ÑƒÐ¶Ð´Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¸Ðº:</t>
    <t id="9381">ÐœÐ°ÐºÑ. Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² ÐºÐµÑˆÐ° Ð½Ð° Ð·Ð°ÑÐ²ÐºÐ¸Ñ‚Ðµ:</t>
    <t id="9382">Ð¡Ñ‚Ð°Ñ€Ð¸ Ð¿Ñ€Ð°Ð³Ð¾Ð²Ð¸ ÑÐµÐºÑƒÐ½Ð´Ð¸:</t>
    <t id="9383">ÐŸÑ€Ð°Ð³ Ð·Ð° Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð° Ð¾Ð¿Ð°ÑˆÐºÐ° Ð·Ð° ÑÐµÐºÑƒÐ½Ð´Ð¸:</t>
    <t id="9384">Ð¡ÐµÐºÑƒÐ½Ð´Ð¸ Ð·Ð° Ð¸Ð·Ñ‚Ð¸Ñ‡Ð°Ð½Ðµ Ð½Ð° Ð½ÐµÑƒÑÐ¿ÐµÑˆÐ½Ð° ÑÐ´ÐµÐ»ÐºÐ°:</t>
    <t id="9385">ÐœÐ°ÐºÑ. ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ:</t>
    <t id="9386">ÐœÐ°ÐºÑ. ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ:</t>
    <t id="9470">ÐœÐµÐº Ð¿Ñ€Ð°Ð³ Ð·Ð° Ð½Ð°Ñ‚Ñ€ÑƒÐ¿Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€ (5-50). ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ð¸Ð·Ð¾ÑÑ‚Ð°Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ðµ Ñ‚Ð°Ð·Ð¸ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚, Ð·Ð°Ð¿Ð¾Ñ‡Ð²Ð° Ð´Ð° ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¿Ñ€Ð¾Ñ‚Ð¸Ð²Ð¾Ð´ÐµÐ¹ÑÑ‚Ð²Ð¸Ðµ, Ð·Ð° Ð´Ð° ÑÐµ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð½Ð¾Ð²Ð¸Ñ‚Ðµ Ð·Ð°ÑÐ²ÐºÐ¸ Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ñ€ÐµÐ´Ð¸Ð·Ð²Ð¸ÐºÐ²Ð°Ñ‚ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾ Ð½Ð°Ð»ÑÐ³Ð°Ð½Ðµ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾ (Ð¿Ð¾-ÐºÐ¾Ð½ÑÐµÑ€Ð²Ð°Ñ‚Ð¸Ð²Ð½Ð¾). ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 10.</t>
    <t id="9471">Ð¢Ð²ÑŠÑ€Ð´ Ð¿Ñ€Ð°Ð³ Ð·Ð° Ð¸Ð·Ð¾ÑÑ‚Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ð°ÐºÐµÑ‚Ð½Ð¸Ñ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€ (10-100). ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ð¸Ð·Ð¾ÑÑ‚Ð°Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð´Ð¾ÑÑ‚Ð¸Ð³Ð½Ðµ Ñ‚Ð°Ð·Ð¸ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚, Ð½Ð¾Ð²Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð½Ð° Ð¶Ð¸Ð²Ð¾ ÑÐµ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ñ‚, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð¸Ð·Ð¾ÑÑ‚Ð°Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð°Ð¼Ð°Ð»ÐµÐµ. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ñ‚ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸ÑÑ‚Ð° Ð¿Ð¾-Ñ€Ð°Ð½Ð¾ (Ð¿Ð¾-ÐºÐ¾Ð½ÑÐµÑ€Ð²Ð°Ñ‚Ð¸Ð²Ð½Ð¾). ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 25.</t>
    <t id="9472">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¸, Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐµÐ½Ð¸ Ð½Ð° Ð¾Ñ‚Ñ€ÑÐ·ÑŠÐº Ð² ÐºÐ¾Ð»ÐµÐºÑ†Ð¸Ñ Ð¾Ñ‚ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð½Ð° Ð¶Ð¸Ð²Ð¾ (1-5). ÐŸÐ¾-Ð¼Ð°Ð»ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ñ€Ð°Ð·Ð¿Ñ€ÑŠÑÐ½Ð°Ñ‚Ð¸ Ñ€Ð°Ð±Ð¾Ñ‚ÑÑ‚ Ð² Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ñ€Ð°Ð¼ÐºÐ¸ (Ð¿Ð¾-Ð¿Ð»Ð°Ð²Ð½Ð¾), Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð·Ð°Ð±Ð°Ð²ÑÑ‚ ÑÑŠÐ±Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¾Ñ„ÐµÑ€Ñ‚Ð¸. ÐŸÐ¾-Ð³Ð¾Ð»ÐµÐ¼Ð¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ‚ Ð¿Ð¸ÐºÐ¾Ð²Ðµ Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9473">ÐžÑ…Ð»Ð°Ð¶Ð´Ð°Ð½Ðµ ÑÐ»ÐµÐ´ Ð·Ð°Ð²ÑŠÑ€ÑˆÐ²Ð°Ð½Ðµ Ð½Ð° Ð¾Ð¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ñ ÑÐµÐºÑ‚Ð¾Ñ€ (10-120 ÑÐµÐºÑƒÐ½Ð´Ð¸). ÐŸÑ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚ÑÐ²Ð° Ð¿Ñ€ÐµÐºÐ¾Ð¼ÐµÑ€Ð½Ð¸Ñ‚Ðµ Ð·Ð°ÑÐ²ÐºÐ¸ Ð·Ð° Ð¾Ð¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½Ðµ. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚ Ð¿Ð¾-Ñ‡ÐµÑÑ‚Ð¸ Ð¾Ð¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½Ð¸Ñ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ñ‡ÐµÑÑ‚Ð¾Ñ‚Ð°Ñ‚Ð° Ð½Ð° Ð¾Ð¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½Ðµ, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð°ÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð°Ñ†Ð¸Ð¸Ñ‚Ðµ Ð½Ð° ÐºÐµÑˆÐ°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 30s.</t>
    <t id="9474">Ð‘Ð°Ð·Ð¾Ð²Ð¾ Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ ÑÐ»ÐµÐ´ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐº Ð² ÐºÐµÑˆÐ° Ð¿Ñ€ÐµÐ´Ð¸ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÐµÐ½ Ð¾Ð¿Ð¸Ñ‚ Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾ (1-30 ÑÐµÐºÑƒÐ½Ð´Ð¸). ÐŸÑ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚ÑÐ²Ð° Ð¿Ñ€ÐµÐºÐ¾Ð¼ÐµÑ€Ð½Ð¸Ñ‚Ðµ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸ Ð¾Ð¿Ð¸Ñ‚Ð¸. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¾Ð¿Ð¸Ñ‚Ð°Ð¹Ñ‚Ðµ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡ÐµÑ‚Ðµ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ñ‡ÐµÑÑ‚Ð¾Ñ‚Ð°Ñ‚Ð° Ð½Ð° Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸ Ð¾Ð¿Ð¸Ñ‚Ð¸, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð½Ð°Ð¼Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 10s.</t>
    <t id="9475">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¼ÐµÐ¶Ð´Ñƒ Ñ‚Ð¸ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ° Ð² Ð¼Ð¸Ð»Ð¸ÑÐµÐºÑƒÐ½Ð´Ð¸ (50-500ms). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€Ð° ÐºÐ¾Ð»ÐºÐ¾ Ñ‡ÐµÑÑ‚Ð¾ Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÑŠÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð½Ð°Ñ‚Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ñ‡ÐµÑÑ‚Ð¾, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°Ñ‚Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 100ms.</t>
    <t id="9476">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ð·Ð°ÑÐ²ÐºÐ¸ Ð·Ð° ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ðµ, ÑÑ‚Ð°Ñ€Ñ‚Ð¸Ñ€Ð°Ð½Ð¸ Ð·Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ° Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð°Ð²Ð° Ñ‡ÐµÑÑ‚Ð¾Ñ‚Ð°Ñ‚Ð° Ð½Ð° Ð·Ð°ÑÐ²ÐºÐ¸Ñ‚Ðµ Ð² ÐºÐµÑˆÐ°, Ð·Ð° Ð´Ð° Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÐºÐ°Ð´Ñ€Ð¸. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÑÐºÐ¾ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸ÑÑ‚Ð° Ð² ÐºÐµÑˆÐ°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ‚ Ð·Ð°ÐµÐºÐ²Ð°Ð½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9477">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶ÐµÐ½Ð¸Ñ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾, ÑÑ‚Ð°Ñ€Ñ‚Ð¸Ñ€Ð°Ð½Ð¸ Ð·Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ° Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð°Ð²Ð° ÑÐºÐ¾Ñ€Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð°Ð²Ð°Ð½Ðµ, Ð·Ð° Ð´Ð° Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ñ€Ð°Ð¼ÐºÐ°Ñ‚Ð°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÑÐºÐ¾ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°Ñ‚Ð° Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ‚ Ð·Ð°ÐµÐºÐ²Ð°Ð½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9478">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐµÐ½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð·Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ° Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð°Ð²Ð° ÑÐºÐ¾Ñ€Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°, Ð·Ð° Ð´Ð° Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ€Ð°Ð¼ÐºÐ°Ñ‚Ð°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÑÐºÐ¾ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°Ñ‚Ð° Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ‚ Ð·Ð°ÐµÐºÐ²Ð°Ð½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9479">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ñ€Ð°Ð±Ð¾Ñ‚Ð½Ð¸ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸, Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐµÐ½Ð¸ Ð·Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ° Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ° (1-5). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð°Ð²Ð° ÑÐºÐ¾Ñ€Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ° Ð½Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð½Ð¸Ñ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚, Ð·Ð° Ð´Ð° Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ñ€Ð°Ð¼ÐºÐ°Ñ‚Ð°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÑÐºÐ¾ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°Ñ‚Ð° Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ‚ Ð·Ð°ÐµÐºÐ²Ð°Ð½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9480">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ ÑÑŠÐ±ÑƒÐ´ÐµÐ½Ð¸ ÑÐµÑ€Ð²Ð¸Ñ‚ÑŒÐ¾Ñ€Ð¸ Ð·Ð° Ð¾Ñ‚Ð¼ÐµÑ‚ÐºÐ° Ð½Ð° Ð¿Ð»Ð°Ð½Ð¸Ñ€Ð¾Ð²Ñ‡Ð¸ÐºÐ° (1-10). ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð°Ð²Ð° ÑÐºÐ¾Ñ€Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÑÑŠÐ±ÑƒÐ¶Ð´Ð°Ð½Ðµ, Ð·Ð° Ð´Ð° Ð¿Ñ€ÐµÐ´Ð¾Ñ‚Ð²Ñ€Ð°Ñ‚Ð¸ Ð¿Ð¸ÐºÐ¾Ð²Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¼Ð½Ð¾Ð³Ð¾ ÑÐµÑ€Ð²Ð¸Ñ‚ÑŒÐ¾Ñ€Ð¸ ÑÐ° Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÑÐºÐ¾ÐºÐ¾Ð²ÐµÑ‚Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ°Ñ‚Ð° Ð½Ð° ÑÐµÑ€Ð²Ð¸Ñ‚ÑŒÐ¾Ñ€Ð°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ Ð¾Ð±Ñ€Ð°Ð±Ð¾Ñ‚Ð²Ð°Ñ‚ Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ‚ Ð·Ð°ÐµÐºÐ²Ð°Ð½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 2.</t>
    <t id="9481">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ Ð·Ð°ÑÐ²ÐµÐ½Ð¸ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² ÐºÐµÑˆÐ° Ð·Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð° (1-200). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»Ð¸Ñ€Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° Ð¿Ð°Ñ€Ñ‚Ð¸Ð´Ð°Ñ‚Ð° Ð½Ð° Ð·Ð°ÑÐ²ÐºÐ¸Ñ‚Ðµ Ð·Ð° ÐºÐµÑˆÐ°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ñ€Ð°Ð²ÑÑ‚ Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð² ÐºÐµÑˆÐ° Ð¿Ð¾-Ð±ÑŠÑ€Ð·Ð¾, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€Ð¾Ð¿ÑƒÑÐ½Ð°Ñ‚ Ð¿Ð¾-Ð´Ð¾Ð±Ñ€Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð²Ð·ÐµÐ¼Ð°Ñ‚ Ð¿Ñ€ÐµÐ´Ð²Ð¸Ð´ Ð¿Ð¾Ð²ÐµÑ‡Ðµ ÐºÐµÑˆÐ¸Ñ€Ð°Ð½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð²Ñ€ÐµÐ¼ÐµÑ‚Ð¾ Ð·Ð° Ð²Ð°Ð»Ð¸Ð´Ð¸Ñ€Ð°Ð½Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 50.</t>
    <t id="9482">ÐŸÑ€Ð°Ð³ Ð½Ð° Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾ Ð·Ð° ÑÐµÐºÑƒÐ½Ð´Ð¸ (60-600). ÐšÐ¾Ð³Ð°Ñ‚Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾ Ðµ Ð¿Ð¾-ÑÑ‚Ð°Ñ€Ð¾ Ð¾Ñ‚ Ñ‚Ð¾Ð²Ð°, Ñ‚Ð¾ ÑÐµ ÑÑ‡Ð¸Ñ‚Ð° Ð·Ð° Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð¾ Ð¸ ÑÐµ Ð¸Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¸Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð°Ñ‚ Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð¾Ñ‚Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¿Ñ€ÐµÐºÑŠÑÐ½Ð°Ñ‚ Ð»ÐµÐ³Ð¸Ñ‚Ð¸Ð¼Ð½Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚ Ð¿Ð¾-Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¾ÑÑ‚Ð°Ð²ÑÑ‚ Ð¾ÑÑ‚Ð°Ñ€ÑÐ»Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 300s.</t>
    <t id="9483">ÐŸÑ€Ð°Ð³ Ð½Ð° Ð¾ÑÑ‚Ð°Ñ€ÑÐ» ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚ Ð² Ð¾Ð¿Ð°ÑˆÐºÐ°Ñ‚Ð° Ð² ÑÐµÐºÑƒÐ½Ð´Ð¸ (30-300). ÐšÐ¾Ð³Ð°Ñ‚Ð¾ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸Ñ‚Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°Ñ‚Ð° ÑÐ° Ð¿Ð¾-ÑÑ‚Ð°Ñ€Ð¸ Ð¾Ñ‚ Ñ‚Ð¾Ð²Ð°, Ñ‚Ðµ ÑÐµ ÑÑ‡Ð¸Ñ‚Ð°Ñ‚ Ð·Ð° Ð¾ÑÑ‚Ð°Ñ€ÐµÐ»Ð¸ Ð¸ ÑÐµ Ð¿Ñ€ÐµÐ¼Ð°Ñ…Ð²Ð°Ñ‚. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¸Ð·Ñ‡Ð¸ÑÑ‚Ð²Ð°Ñ‚ Ð¾ÑÑ‚Ð°Ñ€ÐµÐ»Ð¸Ñ‚Ðµ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ñ€ÐµÐ¼Ð°Ñ…Ð½Ð°Ñ‚ Ð»ÐµÐ³Ð¸Ñ‚Ð¸Ð¼Ð½Ð¸Ñ‚Ðµ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸ Ð² Ð¾Ð¿Ð°ÑˆÐºÐ°Ñ‚Ð°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚ Ð¿Ð¾-Ð´ÑŠÐ»Ð³Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°, Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð¾ÑÑ‚Ð°Ð²ÑÑ‚ Ð¾ÑÑ‚Ð°Ñ€ÐµÐ»Ð¸ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 60s.</t>
    <t id="9484">ÐÐµÑƒÑÐ¿ÐµÑˆÐ½Ð¾ Ð¸Ð·Ñ‚Ð¸Ñ‡Ð°Ð½Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ ÐºÐµÑˆ Ð·Ð° ÑÐµÐºÑƒÐ½Ð´Ð¸ (300-3600). ÐÐµÑƒÑÐ¿ÐµÑˆÐ½Ð¸Ñ‚Ðµ ÑÐ´ÐµÐ»ÐºÐ¸ ÑÐµ ÐºÐµÑˆÐ¸Ñ€Ð°Ñ‚, Ð·Ð° Ð´Ð° ÑÐµ Ð¸Ð·Ð±ÐµÐ³Ð½Ðµ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÐµÐ½ Ð¾Ð¿Ð¸Ñ‚ Ð²ÐµÐ´Ð½Ð°Ð³Ð°. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¸Ð·Ñ‚Ð¸Ñ‡Ð°Ñ‚ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾ Ð¿Ñ€Ð¸ Ð½ÐµÑƒÑÐ¿ÐµÑˆÐ½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸ (Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸ Ð¾Ð¿Ð¸Ñ‚Ð¸), Ð½Ð¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ ÐµÑ„ÐµÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐµÑˆÐ°. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ ÑÐµ ÐºÐµÑˆÐ¸Ñ€Ð°Ñ‚ Ð¿Ð¾-Ð´ÑŠÐ»Ð³Ð¾ (Ð¿Ð¾-Ð¼Ð°Ð»ÐºÐ¾ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÐµÐ½Ð¸Ñ), Ð½Ð¾ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ð¾Ð¿Ð¸Ñ‚Ð¸Ñ‚Ðµ Ð·Ð° Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÐµÐ½Ð¸Ðµ. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1800s (30 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸).</t>
    <t id="9485">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÐµÐ½ Ð±Ñ€Ð¾Ð¹ ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð½Ð° Ð¶Ð¸Ð²Ð¾ (1-10). Ð ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ Ð·Ð°Ð¾Ð±Ð¸ÐºÐ°Ð»ÑÑ‚ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ°Ñ‚Ð° Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ñ ÑÐµÐºÑ‚Ð¾Ñ€, Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ð¹ÐºÐ¸ Ð½Ð° Ð½ÑÐºÐ¾Ð»ÐºÐ¾ ÐºÐ¾Ñ€Ð°Ð±Ð° Ð¾Ñ‚ ÐµÐ´Ð¸Ð½ Ð¸ ÑÑŠÑ‰Ð¸ Ð´Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€ Ð´Ð° Ñ‚ÑŠÑ€ÑÑÑ‚ ÐµÐ´Ð½Ð¾Ð²Ñ€ÐµÐ¼ÐµÐ½Ð½Ð¾. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð°Ñ‚ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°, Ð½Ð¾ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð·Ð°Ð±Ð°Ð²ÑÑ‚ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ‚Ðµ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð°Ñ‚ Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¿Ð°Ñ€Ð°Ð»ÐµÐ»Ð½Ð¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½Ð¸Ñ, Ð½Ð¾ ÑƒÐ²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð°Ñ‚ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 1.</t>
    <t id="9490">Ð—Ð°Ð±Ð°Ð²ÑÐ½Ðµ Ð½Ð° ÑÐ¸Ð³Ð½Ð°Ð»Ð° Ð·Ð° Ð¾Ñ‚ÐºÑ€Ð¸Ñ‚Ð° ÑÐ´ÐµÐ»ÐºÐ°:</t>
    <t id="9590">Ð—Ð°Ð±Ð°Ð²ÑÐ½Ðµ Ð¿Ñ€ÐµÐ´Ð¸ Ð¸Ð·Ð¿Ñ€Ð°Ñ‰Ð°Ð½Ðµ Ð½Ð° ÑÐ¸Ð³Ð½Ð°Ð» GT_Trade_Found Ð´Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð² Ð¼Ð¸Ð»Ð¸ÑÐµÐºÑƒÐ½Ð´Ð¸ (10-1000ms). ÐšÐ¾Ñ€Ð°Ð±Ð¸Ñ‚Ðµ Ð²Ð¸Ð½Ð°Ð³Ð¸ Ñ‡Ð°ÐºÐ°Ñ‚ (ÐºÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð¸Ñ€Ð°Ð½Ð¾ Ð·Ð°Ð±Ð°Ð²ÑÐ½Ðµ + 5ms Ð±ÑƒÑ„ÐµÑ€), Ð¿Ñ€ÐµÐ´Ð¸ Ð´Ð° Ð¸Ð·Ð¿Ñ€Ð°Ñ‚ÑÑ‚ Ð½Ð¾Ð²Ð¸ Ð·Ð°ÑÐ²ÐºÐ¸ Ð·Ð° ÑƒÐ»Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ð·Ð°Ð±Ð°Ð²ÐµÐ½Ð¸ ÑÐ¸Ð³Ð½Ð°Ð»Ð¸. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¸Ñ‚Ðµ ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸ Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ñ‚ ÑÐ¸Ð³Ð½Ð°Ð»Ð¸Ñ‚Ðµ Ð¼ÐµÐ¶Ð´Ñƒ ÐºÐ°Ð´Ñ€Ð¸Ñ‚Ðµ Ð·Ð° Ð¿Ð¾-Ð¿Ð»Ð°Ð²Ð½Ð° Ñ€Ð°Ð±Ð¾Ñ‚Ð°. ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: 10ms.</t>
    <t id="8000">Ð¤Ð»Ð¾Ñ‚ Ð½Ð° GalaxyTrader</t>
    <t id="8001">Ð£Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð° Ð½Ð° GalaxyTrader Ð¸ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ¸ Ð·Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸</t>
    <t id="8002">ÐŸÑ€ÐµÐ³Ð»ÐµÐ¶Ð´Ð°Ð¹Ñ‚Ðµ Ð¸ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÑÐ²Ð°Ð¹Ñ‚Ðµ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° GalaxyTrader</t>
    <t id="8100">ID Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="8101">ÐŸÐ¸Ð»Ð¾Ñ‚</t>
    <t id="8102">ÐšÐ¾Ñ€Ð°Ð±</t>
    <t id="8103">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ</t>
    <t id="8104">Ð Ð°Ð½Ð³</t>
    <t id="8105">ÐÐ¸Ð²Ð¾</t>
    <t id="8106">XP</t>
    <t id="8107">Ð”Ð¾Ð¶Ð¸Ð²Ð¾Ñ‚Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°</t>
    <t id="8108">ÐœÐµÑÑ‚Ð¾Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ</t>
    <t id="8109">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð° Ð±Ð°Ð·Ð°</t>
    <t id="8110">ÐŸÐ¾ÑÐ»ÐµÐ´Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ°</t>
    <t id="8111">ÐŸÐ¸Ð»Ð¾Ñ‚Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°</t>
    <t id="8112">ÐŸÐµÑ‡Ð°Ð»Ð±Ð° Ð¾Ñ‚ ÐºÐ¾Ñ€Ð°Ð±</t>
    <t id="8113">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¾ Ð±Ñ€Ð¾ÐµÐ½Ðµ</t>
    <t id="8200">ÐžÐ¿Ñ€ÐµÑÐ½ÑÐ²Ð°Ð½Ðµ</t>
    <t id="8201">Ð•ÐºÑÐ¿Ð¾Ñ€Ñ‚Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° CSV</t>
    <t id="8202">Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°</t>
    <t id="8203">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="8204">ÐŸÐ¾Ð¼Ð¾Ñ‰</t>
    <t id="8205">Ð·Ð°Ñ‚Ð²Ð¾Ñ€Ð¸</t>
    <t id="8300">Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸</t>
    <t id="8301">Ð¢ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ</t>
    <t id="8302">Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="8303">ÐŸÐ¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ°</t>
    <t id="8304">Ð¡Ð¿ÐµÑˆÐµÐ½ ÑÐ»ÑƒÑ‡Ð°Ð¹</t>
    <t id="8305">ÐÐ°Ñ‡Ð¸Ð½Ð°ÐµÑ‰Ð¸ (Lv 1-5)</t>
    <t id="8306">ÐÐ°Ð¿Ñ€ÐµÐ´Ð½Ð°Ð»Ð¸ (Lv 6-11)</t>
    <t id="8307">Ð•ÐºÑÐ¿ÐµÑ€Ñ‚Ð¸ (Ð½Ð¸Ð²Ð¾ 12+)</t>
    <t id="8308">Ð¢Ð¾Ð¿ 10 Ð½Ð° Ð¿ÐµÑ‡ÐµÐ»Ð¸Ð²ÑˆÐ¸Ñ‚Ðµ</t>
    <t id="8350">Ð¡Ð¾Ñ€Ñ‚Ð¸Ñ€Ð°Ð½Ðµ Ð¿Ð¾:</t>
    <t id="8351">ID Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="8352">Ð˜Ð¼Ðµ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="8353">Ð¢Ð¸Ð¿ ÐºÐ¾Ñ€Ð°Ð±</t>
    <t id="8354">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ</t>
    <t id="8355">Ð Ð°Ð½Ð³</t>
    <t id="8356">ÐÐ¸Ð²Ð¾</t>
    <t id="8357">XP</t>
    <t id="8358">Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°</t>
    <t id="8400">ÐÑÐ¼Ð° Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸</t>
    <t id="8401">ÐÐ¸Ñ‚Ð¾ ÐµÐ´Ð¸Ð½ Ð¿Ð¸Ð»Ð¾Ñ‚ Ð½Ðµ Ð¾Ñ‚Ð³Ð¾Ð²Ð°Ñ€Ñ Ð½Ð° Ñ„Ð¸Ð»Ñ‚ÑŠÑ€Ð°</t>
    <t id="8402">ÐžÐ±Ñ‰Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸:</t>
    <t id="8403">ÐžÐ±Ñ‰Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° Ð¾Ñ‚ Ñ„Ð»Ð¾Ñ‚Ð°:</t>
    <t id="8404">ÐŸÐ¾ÑÐ»ÐµÐ´Ð½Ð° Ð°ÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð°Ñ†Ð¸Ñ:</t>
    <t id="8405">Ð¢ÑŠÑ€ÑÐµÑ‚Ðµ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸...</t>
    <t id="8114">Ð¡ÐµÐºÑ‚Ð¾Ñ€</t>
    <t id="8320">ÐŸÑ€ÐµÐ¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="8321">ÐŸÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¾ Ð¸Ð¼Ðµ</t>
    <t id="8322">Ð—Ð°Ð´Ð°Ð¹Ñ‚Ðµ Ð¸Ð¼Ðµ</t>
    <t id="8323">Ð˜Ð·Ñ‡Ð¸ÑÑ‚ÐµÑ‚Ðµ Ð¸Ð¼Ðµ</t>
    <t id="8324">Ð˜Ð¼ÐµÑ‚Ð¾ Ðµ Ð·Ð°Ð´Ð°Ð´ÐµÐ½Ð¾ ÑƒÑÐ¿ÐµÑˆÐ½Ð¾</t>
    <t id="8325">Ð˜Ð¼ÐµÑ‚Ð¾ Ðµ Ð¸Ð·Ñ‡Ð¸ÑÑ‚ÐµÐ½Ð¾ ÑƒÑÐ¿ÐµÑˆÐ½Ð¾</t>
    <t id="8450">Ð˜Ð·Ð¿Ñ€Ð°Ñ‚Ð¸ Ð´Ð¾ ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="8451">Ð”ÐµÑ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÐµ</t>
    <t id="8452">ÐŸÑ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚ÐµÐ»Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="8453">Ð˜Ð·Ð¿Ñ€Ð°Ñ‚ÐµÑ‚Ðµ Ð½Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚</t>
    <t id="8454">Ð˜Ð·Ð¿Ñ€Ð°Ñ‚ÐµÑ‚Ðµ Ð´Ð¾ Supply</t>
    <t id="8455">Ð¡Ð¿Ñ€ÐµÑ‚Ðµ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ¸</t>
    <t id="8456">Ð”ÐµÐ¹ÑÑ‚Ð²Ð¸Ñ</t>
    <t id="8500">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ ID Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="8501">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ Ð¸Ð¼Ðµ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°</t>
    <t id="8502">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ Ñ‚Ð¸Ð¿ ÐºÐ¾Ñ€Ð°Ð±</t>
    <t id="8503">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ</t>
    <t id="8504">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ Ñ€Ð°Ð½Ð³</t>
    <t id="8505">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ Ð½Ð¸Ð²Ð¾</t>
    <t id="8506">ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ XP</t>
    <t id="8507">Ð©Ñ€Ð°ÐºÐ½ÐµÑ‚Ðµ, Ð·Ð° Ð´Ð° ÑÐ¾Ñ€Ñ‚Ð¸Ñ€Ð°Ñ‚Ðµ Ð¿Ð¾ Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° Ð¿Ñ€ÐµÐ· Ñ†ÐµÐ»Ð¸Ñ Ð¶Ð¸Ð²Ð¾Ñ‚</t>
    <t id="8508">ÐžÐ±Ð½Ð¾Ð²ÐµÑ‚Ðµ Ð¿Ð¸Ð»Ð¾Ñ‚Ð½Ð¸Ñ‚Ðµ Ð´Ð°Ð½Ð½Ð¸ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° Ð½Ð° Ð¼Ð¸ÑÐ¸ÑÑ‚Ð°</t>
    <t id="8509">Ð•ÐºÑÐ¿Ð¾Ñ€Ñ‚Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ñ Ð¸Ð·Ð³Ð»ÐµÐ´ Ð² CSV Ñ„Ð°Ð¹Ð»</t>
    <t id="8510">ÐŸÑ€ÐµÐ³Ð»ÐµÐ´ Ð½Ð° ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ° Ð¸ Ð´Ð¸Ð°Ð³Ñ€Ð°Ð¼Ð¸ Ð½Ð° Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÐ°</t>
    <t id="8511">ÐšÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸Ñ‚Ðµ Ð½Ð° Ð¼ÐµÐ½ÑŽÑ‚Ð¾</t>
    <t id="8512">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ð¾Ð¼Ð¾Ñ‰ Ð¸ ÐºÐ»Ð°Ð²Ð¸ÑˆÐ½Ð¸ ÐºÐ¾Ð¼Ð±Ð¸Ð½Ð°Ñ†Ð¸Ð¸</t>
    <t id="8600">ÐÑÐ¼Ð° Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð½Ð¸ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¸ Ð½Ð° GalaxyTrader</t>
    <t id="8601">Ð¡ÑŠÐ·Ð´Ð°Ð¹Ñ‚Ðµ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸, ÐºÐ°Ñ‚Ð¾ Ð·Ð°Ð´Ð°Ð´ÐµÑ‚Ðµ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð½Ð° GalaxyTrader, Ð¸Ð»Ð¸ Ð¸Ð·Ñ‡Ð°ÐºÐ°Ð¹Ñ‚Ðµ Ð´Ð°Ð½Ð½Ð¸Ñ‚Ðµ Ð´Ð° ÑÐµ Ð·Ð°Ñ€ÐµÐ´ÑÑ‚.</t>
    <t id="9001">GT ÐŸÑ€ÐµÐ¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ</t>
    <t id="9902">Ð˜Ð·Ð¿Ñ€Ð°Ñ‚Ð¸ Ð´Ð¾ ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="9903">Ð ÑŠÑ‡Ð½Ð¾ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ Ð² Ð¾Ð¿Ð°ÑˆÐºÐ° Ð·Ð° %1. ÐŸÐ¸Ð»Ð¾Ñ‚ÑŠÑ‚ Ñ‰Ðµ Ð·Ð°Ð¿Ð¾Ñ‡Ð½Ðµ Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ ÑÐ»ÐµÐ´ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ñ Ñ†Ð¸ÐºÑŠÐ».</t>
    <t id="9904">ÐžÐ±ÑƒÑ‡ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ° ÑÐ»ÐµÐ´ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ñ Ñ†Ð¸ÐºÑŠÐ»</t>
    <t id="9905">ÐŸÐ¸Ð»Ð¾Ñ‚ÑŠÑ‚ Ð¸Ð»Ð¸ ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð½Ðµ ÑÐ° Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸</t>
    <t id="9906">AutoTraining Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½ - Ð½Ðµ Ðµ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ñ€ÑŠÑ‡Ð½Ð¾ Ð¿Ð¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ°</t>
    <t id="9907">ÐŸÐ¸Ð»Ð¾Ñ‚ÑŠÑ‚ Ð½Ðµ Ðµ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ</t>
    <t id="9910">ÐÐºÐ°Ð´ÐµÐ¼Ð¸Ñ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ</t>
    <t id="9911">Ð§Ð¸Ñ€Ð°Ðº (Ð½Ð¸Ð²Ð¾ 4) - %1 / %2</t>
    <t id="9912">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† (Lvl 7) - %1 / %2</t>
    <t id="9913">ÐœÐ°Ð¹ÑÑ‚Ð¾Ñ€ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† (Ð½Ð¸Ð²Ð¾ 13) - %1 / %2</t>
    <t id="9920">ÐŸÐ¸Ð»Ð¾Ñ‚ %1 ÑÐµ Ð·Ð°Ð¿Ð¸ÑÐ° Ð² ÐºÑƒÑ€ÑÐ° Ð½Ð° ÐÐºÐ°Ð´ÐµÐ¼Ð¸ÑÑ‚Ð° Ð·Ð° Ð½Ð¸Ð²Ð¾ %2. ÐžÑ‚Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð·Ð° Ð½Ð°Ð¹-Ð±Ð»Ð¸Ð·ÐºÐ°Ñ‚Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ.</t>
    <t id="9921">ÐÑÐ¼Ð° Ð´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ ÑÑ€ÐµÐ´ÑÑ‚Ð²Ð° Ð·Ð° Ñ‚Ð¾Ð·Ð¸ ÐºÑƒÑ€Ñ (Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¸ ÑÐ° %1, Ð¸Ð¼Ð°Ð¹Ñ‚Ðµ %2).</t>
    <t id="9922">ÐšÑƒÑ€ÑÑŠÑ‚ Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡ÐµÐ½ - Ð¿Ð¸Ð»Ð¾Ñ‚ %1 Ð²ÐµÑ‡Ðµ Ðµ Ð½Ð° Ð¸Ð»Ð¸ Ð½Ð°Ð´ Ñ‚Ð¾Ð²Ð° Ð½Ð¸Ð²Ð¾.</t>
    <t id="9923">ÐŸÐ¸Ð»Ð¾Ñ‚ %1 ÑÐµ Ð·Ð°Ð¿Ð¸ÑÐ° Ð² ÐºÑƒÑ€ÑÐ° Trading Academy Ð½Ð¸Ð²Ð¾ %2 (Ñ†ÐµÐ½Ð°: %3 Cr, Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚: %4 Ð¼Ð¸Ð½.) Ð½Ð° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %5.</t>
    <t id="11011">Ð¡Ñ€ÐµÐ´ÐµÐ½ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ½ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT Apprentice</t>
    <t id="11012">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾ÑÑ‚Ð¾ Ð»ÐµÐºÐ¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð·Ð° Ð½ÐµÐ¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° ÑÑ€ÐµÐ´Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -5% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="11013">GT Apprentice Ð¡Ñ€ÐµÐ´ÐµÐ½ Ñ…Ð¾Ð´Ð¾Ð² Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€</t>
    <t id="11014">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾ÑÑ‚Ð¾ Ð»ÐµÐºÐ¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð·Ð° Ð½ÐµÐ¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° ÑÑ€ÐµÐ´Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -5% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="11021">Ð“Ð¾Ð»ÑÐ¼ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ½ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT Apprentice</t>
    <t id="11022">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾ÑÑ‚Ð¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð·Ð° Ð½ÐµÐ¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="11023">Ð“Ð¾Ð»ÑÐ¼ Ð¿ÑŠÑ‚ÐµÐ½ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT Apprentice</t>
    <t id="11024">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾ÑÑ‚Ð¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð·Ð° Ð½ÐµÐ¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="11031">GT Apprentice Capital ÐºÐ¾Ñ€Ð°Ð±ÐµÐ½ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€</t>
    <t id="11032">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾ÑÑ‚Ð¾ Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð·Ð° Ð½ÐµÐ¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="11033">GT Apprentice Capital Travel Reducer</t>
    <t id="11034">ÐœÐ¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ, ÐºÐ¾ÑÑ‚Ð¾ Ð·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð½Ð°Ð¼Ð°Ð»ÑÐ²Ð° Ð¿Ñ€Ð¾Ð¸Ð·Ð²Ð¾Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð·Ð° Ð½ÐµÐ¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="12001">GT ÐžÑÐ½Ð¾Ð²ÐµÐ½ ÑƒÑÐ¸Ð»Ð²Ð°Ñ‚ÐµÐ» Ð½Ð° Ð¼Ð°Ð»ÑŠÐº ÐºÐ¾Ñ€Ð°Ð±</t>
    <t id="12002">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð¼Ð°Ð»ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +3% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="12003">GT Basic Small Travel Enhancer</t>
    <t id="12004">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð¼Ð°Ð»ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +3% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="13001">GT Basic Ð“Ð¾Ð»ÑÐ¼ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ½ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€</t>
    <t id="13002">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -8% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="13003">GT Basic Large Travel Reducer</t>
    <t id="13004">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -8% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="14001">GT Basic Capital ÐºÐ¾Ñ€Ð°Ð±ÐµÐ½ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€</t>
    <t id="14002">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="14003">GT Basic Capital Travel Reducer</t>
    <t id="14004">Ð¡Ð¿ÐµÑ†Ð¸Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° ÐºÐ°Ð¿Ð¸Ñ‚Ð°Ð»Ð½Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. -15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="15001">GT Ð•ÐºÑÐ¿ÐµÑ€Ñ‚ Ð·Ð° Ð¿Ð¾Ð´Ð¾Ð±Ñ€ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð¼Ð°Ð»ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸</t>
    <t id="15002">Ð£ÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð¼Ð°Ð»ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="15003">GT Expert Small Travel Enhancer</t>
    <t id="15004">Ð£ÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð¼Ð°Ð»ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +25% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ.</t>
    <t id="16001">GT Expert Large Ship Enhancer</t>
    <t id="16002">Ð£ÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="16003">GT Expert Large Travel Enhancer</t>
    <t id="16004">Ð£ÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +15% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ.</t>
    <t id="17001">GT Ð•ÐºÑÐ¿ÐµÑ€Ñ‚ Capital Ship Enhancer</t>
    <t id="17002">Ð£ÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +6% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚, Ñ‚ÑÐ³Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½Ðµ.</t>
    <t id="17003">GT Expert Capital Travel Enhancer</t>
    <t id="17004">Ð£ÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ð¸ÐºÐ°Ñ†Ð¸Ñ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ Ð·Ð° Ð³Ð¾Ð»ÐµÐ¼Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¾Ð¿Ð¸Ñ‚Ð½Ð¸ Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader AI. +6% ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð²Ð¸Ð¶ÐµÐ½Ð¸Ðµ.</t>
    <t id="18001">Ð¡ÐµÑ€Ð¸Ð¾Ð·Ð½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (ÐºÐ¾Ñ€Ð°Ð±)</t>
    <t id="18002">Ð¡ÐµÑ€Ð¸Ð¾Ð·Ð½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (ÐºÐ¾Ñ€Ð°Ð±) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐ²Ð° ÑÐµÑ€Ð¸Ð¾Ð·Ð½Ð¸ Ð½Ð°ÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð»Ð¸Ð¿ÑÐ° Ð½Ð° Ð¾Ð¿Ð¸Ñ‚ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚ Ñ Ð³Ð¾Ð»ÐµÐ¼Ð¸ Ð¿Ð»Ð°Ð²Ð°Ñ‚ÐµÐ»Ð½Ð¸ ÑÑŠÐ´Ð¾Ð²Ðµ. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. Ð£Ð²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð° Ð¼Ð°ÑÐ°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. (Ð¡Ð°Ð¼Ð¾ GT ÑÐ¸ÑÑ‚ÐµÐ¼Ð° - Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ)</t>
    <t id="18003">Ð£Ð¼ÐµÑ€ÐµÐ½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (ÐºÐ¾Ñ€Ð°Ð±)</t>
    <t id="18004">Ð£Ð¼ÐµÑ€ÐµÐ½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (ÐºÐ¾Ñ€Ð°Ð±) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐ²Ð° ÑƒÐ¼ÐµÑ€ÐµÐ½Ð¸ Ð½Ð°ÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²ÑÐ½Ðµ, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚ÑŠÑ‚ ÑÐµ Ð°Ð´Ð°Ð¿Ñ‚Ð¸Ñ€Ð° ÐºÑŠÐ¼ ÑÐ»Ð¾Ð¶Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. Ð£Ð²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð° Ð¼Ð°ÑÐ°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. (Ð¡Ð°Ð¼Ð¾ GT ÑÐ¸ÑÑ‚ÐµÐ¼Ð° - Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ)</t>
    <t id="18005">ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° Ð»ÐµÐºÐ¾Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸Ðµ (ÐºÐ¾Ñ€Ð°Ð±)</t>
    <t id="18006">Ð›ÐµÐºÐ¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (ÐšÐ¾Ñ€Ð°Ð±) - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐ²Ð° Ð½ÐµÐ·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¸ Ð½Ð°ÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸ÐµÑ‚Ð¾ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. Ð£Ð²ÐµÐ»Ð¸Ñ‡Ð°Ð²Ð° Ð¼Ð°ÑÐ°Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. (Ð¡Ð°Ð¼Ð¾ GT ÑÐ¸ÑÑ‚ÐµÐ¼Ð° - Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ)</t>
    <t id="18007">Ð¡ÐµÑ€Ð¸Ð¾Ð·Ð½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»)</t>
    <t id="18008">Ð¡ÐµÑ€Ð¸Ð¾Ð·Ð½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ») - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐ²Ð° ÑÐµÑ€Ð¸Ð¾Ð·Ð½Ð¸ Ð½Ð°ÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð¿Ð¾Ñ€Ð°Ð´Ð¸ Ð»Ð¸Ð¿ÑÐ° Ð½Ð° Ð¾Ð¿Ð¸Ñ‚ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ñ Ð³Ð¾Ð»ÐµÐ¼Ð¸ Ð¿Ð»Ð°Ð²Ð°Ñ‚ÐµÐ»Ð½Ð¸ ÑÑŠÐ´Ð¾Ð²Ðµ. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. ÐÐ°Ð¼Ð°Ð»ÑÐ²Ð° Ñ‚ÑÐ³Ð°Ñ‚Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ. (Ð¡Ð°Ð¼Ð¾ GT ÑÐ¸ÑÑ‚ÐµÐ¼Ð° - Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ)</t>
    <t id="18009">Ð£Ð¼ÐµÑ€ÐµÐ½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»)</t>
    <t id="18010">Ð£Ð¼ÐµÑ€ÐµÐ½Ð¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ») - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐ²Ð° ÑƒÐ¼ÐµÑ€ÐµÐ½Ð¸ Ð½Ð°ÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²ÑÐ½Ðµ, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ð¿Ð¸Ð»Ð¾Ñ‚ÑŠÑ‚ ÑÐµ Ð°Ð´Ð°Ð¿Ñ‚Ð¸Ñ€Ð° ÐºÑŠÐ¼ ÑÐ»Ð¾Ð¶Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. ÐÐ°Ð¼Ð°Ð»ÑÐ²Ð° Ñ‚ÑÐ³Ð°Ñ‚Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ. (Ð¡Ð°Ð¼Ð¾ GT ÑÐ¸ÑÑ‚ÐµÐ¼Ð° - Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ)</t>
    <t id="18011">ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° Ð»ÐµÐºÐ¾Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸Ðµ (Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»)</t>
    <t id="18012">Ð›ÐµÐºÐ¾ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° (Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ») - ÐŸÑ€ÐµÐ´ÑÑ‚Ð°Ð²Ð»ÑÐ²Ð° Ð½ÐµÐ·Ð½Ð°Ñ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¸ Ð½Ð°ÐºÐ°Ð·Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€ÐµÐ´ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð¿Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð½Ð° Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸ÐµÑ‚Ð¾ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÐµ Ð¿Ñ€Ð¸Ð»Ð°Ð³Ð° Ð¾Ñ‚ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° GalaxyTrader, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑƒÐ¼ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð° Ðµ Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚ÑŠÑ‡Ð½Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¼ÐµÑ€Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. ÐÐ°Ð¼Ð°Ð»ÑÐ²Ð° Ñ‚ÑÐ³Ð°Ñ‚Ð° Ð¸ Ð²ÑŠÑ€Ñ‚ÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ð´Ð²Ð¸Ð³Ð°Ñ‚ÐµÐ»Ñ. (Ð¡Ð°Ð¼Ð¾ GT ÑÐ¸ÑÑ‚ÐµÐ¼Ð° - Ð½Ðµ Ðµ Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¾ Ð·Ð° Ñ€ÑŠÑ‡Ð½Ð¾ Ð¸Ð½ÑÑ‚Ð°Ð»Ð¸Ñ€Ð°Ð½Ðµ)</t>
    <t id="9250">ÐÐ°Ð¸Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°</t>
    <t id="9350">ÐŸÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸ÑÑ‚Ð° Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. Ð¡Ñ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ð¸Ñ‚Ðµ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ ÑÐµ Ð¿Ð¾ÐºÐ°Ð·Ð²Ð°Ñ‚ Ð² Ð¿Ð¾Ð»ÐµÑ‚Ð°Ñ‚Ð° Ð·Ð° Ð²ÑŠÐ²ÐµÐ¶Ð´Ð°Ð½Ðµ Ð¸ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð±ÑŠÐ´Ð°Ñ‚ Ð·Ð°Ð¼ÐµÐ½ÐµÐ½Ð¸. ÐœÐ°ÐºÑÐ¸Ð¼ÑƒÐ¼ 3 Ð·Ð½Ð°ÐºÐ°. Ð’ÑÐ¸Ñ‡ÐºÐ¸ Ð¸Ð¼ÐµÐ½Ð° Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ñ‰Ðµ ÑÐµ Ð°ÐºÑ‚ÑƒÐ°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ñ‚ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾Ð¼ÑÐ½Ð°.</t>
    <t id="9251">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½ÐµÑ‚Ð¾:</t>
    <t id="9252">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚:</t>
    <t id="9253">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¿Ð¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ°:</t>
    <t id="9254">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ð´ÑŠÑ€Ð¶Ð°Ð²Ð°Ñ‚Ð° Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ:</t>
    <t id="9255">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð¿Ñ€ÐµÐ½Ð°ÑÐ¾Ñ‡Ð²Ð°Ð½Ðµ:</t>
    <t id="9256">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ð´ÑŠÑ€Ð¶Ð°Ð²Ð°Ñ‚Ð° Ð½Ð° Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°Ð²Ð°Ð½Ðµ:</t>
    <t id="9257">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ:</t>
    <t id="9258">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ñ‚Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ:</t>
    <t id="9259">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ:</t>
    <t id="9260">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ°Ñ‚Ð° Ð´ÑŠÑ€Ð¶Ð°Ð²Ð°:</t>
    <t id="9261">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð² ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð½ÐµÐ°ÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚:</t>
    <t id="9262">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Escape State:</t>
    <t id="9268">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð¸Ð¶Ð¸Ð¼Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ:</t>
    <t id="9269">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸ÐµÑ‚Ð¾ Ð½Ð° Ð±Ð¾Ñ€ÑÐ°Ñ‚Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°:</t>
    <t id="9270">ÐŸÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½ Ð¼Ð°Ñ€ÐºÐµÑ€ Ð·Ð° Ð¿Ñ€ÐµÑ„Ð¸ÐºÑ Ð½Ð° Ñ‡ÐµÑ€Ð½Ð¸Ñ ÑÐ¿Ð¸ÑÑŠÐº:</t>
    <t id="9700">Ð§Ð¸Ð¹Ñ‚Ð¾Ð²Ðµ (ÑÑ‡ÑƒÐ¿ÐµÐ½Ð¾. Ð½ÑÐ¼Ð° Ð½Ð¸Ñ‰Ð¾ Ñ‚ÑƒÐº!! Ð½Ð°Ð¸ÑÑ‚Ð¸Ð½Ð°!!)</t>
    <t id="9701">GT ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð½ÐµÑƒÑÐ·Ð²Ð¸Ð¼Ð¸</t>
    <t id="9702">Ð’ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð° Ð½ÐµÑƒÑÐ·Ð²Ð¸Ð¼Ð¸</t>
    <t id="9800">ÐœÐ¸Ð½Ð°Ð²Ð°Ð¹Ñ‚Ðµ, Ð¿Ð¸Ð»Ð¾Ñ‚. Ð¡Ñ‡ÑƒÐ¿ÐµÐ½Ð¸ Ð¸Ð½ÑÑ‚Ñ€ÑƒÐ¼ÐµÐ½Ñ‚Ð¸ Ð·Ð° Ñ‚ÐµÑÑ‚Ð²Ð°Ð½Ðµ, Ð½Ðµ Ð·Ð°Ð±Ð°Ð²Ð½Ð¾ Ð¼ÐµÐ½ÑŽ. ÐÑÐ¼Ð° Ð½Ð¸Ñ‰Ð¾ Ñ‚ÑƒÐº. ÐÐ°Ð¸ÑÑ‚Ð¸Ð½Ð°. ÐŸÑ€ÐµÐ´ÑƒÐ¿Ñ€ÐµÐ´ÐµÐ½Ð¸ ÑÑ‚Ðµ. Ð’ÐµÑ€Ð¾ÑÑ‚Ð½Ð¾.</t>
    <t id="9801">ÐšÐ¾Ñ€Ð°Ð±Ð¸ Ñ Ð¿Ñ€Ð¸ÐºÐ°Ð· GalaxyTrader Ð½Ðµ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ð°Ð´Ð½Ð°Ñ‚ Ð¿Ð¾Ð´ 100% ÐºÐ¾Ñ€Ð¿ÑƒÑ Ð¸Ð»Ð¸ Ñ‰Ð¸Ñ‚Ð¾Ð²Ðµ. Ð©Ñ€Ð°ÐºÐ½ÐµÑ‚Ðµ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ Ð·Ð° Ð¸Ð·ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ.</t>
    <t id="9802">Ð’ÑÐ¸Ñ‡ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð¸ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð° Ð½Ðµ Ð¼Ð¾Ð³Ð°Ñ‚ Ð´Ð° Ð¿Ð°Ð´Ð½Ð°Ñ‚ Ð¿Ð¾Ð´ 100% ÐºÐ¾Ñ€Ð¿ÑƒÑ Ð¸Ð»Ð¸ Ñ‰Ð¸Ñ‚Ð¾Ð²Ðµ. Ð©Ñ€Ð°ÐºÐ½ÐµÑ‚Ðµ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ Ð·Ð° Ð¸Ð·ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ. Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ Ð½Ðµ ÑÐµ Ð·Ð°ÑÑÐ³Ð°Ñ‚.</t>
    <t id="9703">Ð Ð°Ð·ÐºÑ€Ð¸Ð²Ð°Ð½Ðµ Ð½Ð° Ð²ÑÐµÐ»ÐµÐ½Ð°Ñ‚Ð° Ð·Ð° GT Ñ‚ÐµÑÑ‚Ð¾Ð²Ðµ</t>
    <t id="9704">Ð Ð°Ð·ÐºÑ€Ð¸Ñ‚Ð¾</t>
    <t id="9705">Ð Ð°Ð·ÐºÑ€Ð¸Ð¹</t>
    <t id="9803">Ð Ð°Ð·ÐºÑ€Ð¸Ð²Ð° Ð¼ÑŠÐ³Ð°Ñ‚Ð° Ð½Ð° Ð²Ð¾Ð¹Ð½Ð°Ñ‚Ð° Ð²ÑŠÐ² Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸, Ð¼Ð°Ñ€ÐºÐ¸Ñ€Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ ÐºÐ°Ñ‚Ð¾ Ð¸Ð·Ð²ÐµÑÑ‚Ð½Ð¸, Ð´Ð°Ð²Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð°Ð±Ð¾Ð½Ð°Ð¼ÐµÐ½Ñ‚ Ð¸ Ð°Ð±Ð¾Ð½Ð¸Ñ€Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ñ„ÐµÑ€Ñ‚Ð¸ Ð² Ñ†ÑÐ»Ð°Ñ‚Ð° Ð³Ð°Ð»Ð°ÐºÑ‚Ð¸ÐºÐ°. ÐšÐ»Ð¸ÐºÐ½ÐµÑ‚Ðµ Ð¾Ñ‚Ð½Ð¾Ð²Ð¾ ÑÐ»ÐµÐ´ Ð½Ð¾Ð²Ð¸ DLC ÑÐµÐºÑ‚Ð¾Ñ€Ð¸. Ð¡Ð°Ð¼Ð¾ Ð·Ð° Ñ‚ÐµÑÑ‚Ð²Ð°Ð½Ðµ.</t>
    <t id="9706">ÐœÐ°ÐºÑÐ¸Ð¼Ð¸Ð·Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° XP Ð½Ð° Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ð¸ GT Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸</t>
    <t id="9707">ÐœÐ°ÐºÑÐ¸Ð¼Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¾</t>
    <t id="9708">XP Ð¼Ð°ÐºÑ</t>
    <t id="9804">Ð—Ð°Ð´Ð°Ð²Ð° Ð½Ð¸Ð²Ð¾ 15 Ð¸ Ð¼Ð°ÐºÑ. XP Ð·Ð° Ð²ÑÐµÐºÐ¸ Ð¿Ð¸Ð»Ð¾Ñ‚ Ð² GT Ñ€ÐµÐ³Ð¸ÑÑ‚ÑŠÑ€Ð°. ÐŸÑ€ÐµÐ¼Ð°Ñ…Ð²Ð° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²ÐºÐ¸ Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ. ÐŸÑ€Ð¾Ð¿ÑƒÑÐºÐ° ÑÐµ Ð¿Ñ€Ð¸ Ñ€ÐµÐ¶Ð¸Ð¼ ÑÐ°Ð¼Ð¾ Ð²Ð°Ð½Ð¸Ð»ÐµÐ½ XP. Ð¡Ð°Ð¼Ð¾ Ð·Ð° Ñ‚ÐµÑÑ‚Ð²Ð°Ð½Ðµ.</t>
    <t id="9351">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: RS)</t>
    <t id="9352">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: RP)</t>
    <t id="9353">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¿Ð¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ° (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: MT)</t>
    <t id="9354">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: TR)</t>
    <t id="9355">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¿Ñ€ÐµÐ½Ð°ÑÐ¾Ñ‡Ð²Ð°Ð½Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: RR)</t>
    <t id="9356">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¾ÑÐ²Ð¾Ð±Ð¾Ð¶Ð´Ð°Ð²Ð°Ð½Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: CL)</t>
    <t id="9357">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð°Ð½Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: BL)</t>
    <t id="9358">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: FB)</t>
    <t id="9359">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð°Ð½Ð¾ ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: IS)</t>
    <t id="9360">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: TD)</t>
    <t id="9361">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð½ÐµÐ°ÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: ID)</t>
    <t id="9362">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° Escape state (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: ES)</t>
    <t id="9367">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° Unreachable state (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: UR)</t>
    <t id="9368">Ð¡ÑŠÐºÑ€Ð°Ñ‰ÐµÐ½Ð¸Ðµ Ð·Ð° Pilot Exchange ÑÑŠÑÑ‚Ð¾ÑÐ½Ð¸Ðµ (Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: PE)</t>
    <t id="9369">ÐŸÐ¾ÐºÐ°Ð·Ð²Ð° ÑÐµ ÐºÐ°Ñ‚Ð¾ Ð¿Ñ€ÐµÑ„Ð¸ÐºÑ Ð·Ð° MK3 ÐºÐ¾Ñ€Ð°Ð±Ð¸, Ð·Ð°ÑÐµÐ³Ð½Ð°Ñ‚Ð¸ Ð¾Ñ‚ Ñ‡ÐµÑ€ÐµÐ½ ÑÐ¿Ð¸ÑÑŠÐº Ð½Ð° Ð¿ÐµÑ€ÑÐ¾Ð½Ð°Ð»Ð¸Ð·Ð¸Ñ€Ð°Ð½Ð¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸ (Ð²ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½Ð¸). ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ - Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ð° NPC Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸</t>
    <t id="30010">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="30011">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°</t>
    <t id="30012">ÐŸÑ€ÐµÐ½ÐµÐ±Ñ€ÐµÐ³Ð²Ð°Ð¹Ñ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð°</t>
    <t id="30013">Ware Filter</t>
    <t id="30014">Ð¦ÐµÐ»ÐµÐ²Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð½Ð¸Ñ Ñ‚Ð¾Ð²Ð°Ñ€</t>
    <t id="30015">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ ÐºÑŠÐ¼ Ð²Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð½Ð°Ð·Ð°Ð´</t>
    <t id="30016">Ð¦ÐµÐ»ÐµÐ²Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° ÐºÑƒÐ¿ÐµÑ‚Ðµ Ñ‚Ð¾Ð²Ð°Ñ€</t>
    <t id="30017">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð±Ð¾Ñ€Ð´Ð¾Ð²Ð¸Ñ Ð´Ð½ÐµÐ²Ð½Ð¸Ðº</t>
    <t id="30018">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ</t>
    <t id="30019">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="30020">ÐÐ¸Ð²Ð¾ Ð½Ð° Ð¾Ñ‚ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸</t>
    <t id="30021">Ð¡Ð½Ð°Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="30022">ÐœÐ¸Ð½. % ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="30023">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="30024">Ð¢Ð¾Ð²Ð°Ñ€/ÐŸÐµÑ‡Ð°Ð»Ð±Ð°</t>
    <t id="30025">ÐŸÐ¾Ð·Ð²Ð¾Ð»Ð¸ Ð¼ÑƒÐ»Ñ‚Ð¸-Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ</t>
    <t id="30110">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð°, Ð¾Ñ‚ ÐºÐ¾ÑÑ‚Ð¾ Ð´Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚Ðµ ÑÑ‚Ð¾ÐºÐ¸ (Ð¸Ð·Ð¸ÑÐºÐ²Ð° ÑÐµ Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ)</t>
    <t id="30111">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð´Ð¾ Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð·Ð° Ð½Ð°Ð¼Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸ Ð½Ð° NPC (Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð¾Ñ‚ ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð°)</t>
    <t id="30112">ÐŸÑ€ÐµÐ½ÐµÐ±Ñ€ÐµÐ³Ð²Ð°Ð¹Ñ‚Ðµ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸ÑÑ‚Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ - Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ð½Ð° Ð²ÑÑÐºÐ° Ð¿Ñ€Ð¸ÑÑ‚ÐµÐ»ÑÐºÐ° Ñ„Ñ€Ð°ÐºÑ†Ð¸Ñ, Ð½ÐµÐ·Ð°Ð²Ð¸ÑÐ¸Ð¼Ð¾ Ð¾Ñ‚ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð°Ñ‚Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="30113">Ð”Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»ÐµÐ½ Ñ„Ð¸Ð»Ñ‚ÑŠÑ€ Ð·Ð° ÑÑŠÐ´Ð¾Ð²Ðµ; Ð¾ÑÑ‚Ð°Ð²ÐµÑ‚Ðµ Ð¿Ñ€Ð°Ð·Ð½Ð¾, Ð·Ð° Ð´Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð´ÐµÑ‚Ðµ Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð° Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="30114">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð° Ð¿Ñ€ÐµÐ´Ð¸ Ð·Ð°Ð¼Ð¸Ð½Ð°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ð¸Ñ Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°</t>
    <t id="30115">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¸ Ð´Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð¸ ÑÐºÐ¾ÐºÐ¾Ð²Ðµ, Ð¿Ð¾Ð·Ð²Ð¾Ð»ÐµÐ½Ð¸ Ð¿Ñ€Ð¸ Ð´Ð¾Ð±Ð°Ð²ÑÐ½Ðµ Ð½Ð° Ð²Ñ‚Ð¾Ñ€Ð¸ Ð°Ñ€Ñ‚Ð¸ÐºÑƒÐ» ÐºÑŠÐ¼ Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ (0 = ÑÐ°Ð¼Ð¾ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸ Ð´Ð¸Ñ€ÐµÐºÑ‚Ð½Ð¾ Ð¿Ð¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð°)</t>
    <t id="30116">Ð¦ÐµÐ»ÐµÐ²Ð¾ Ð¿Ð¾Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð·Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ (Ð¼ÐµÐºÐ° Ñ†ÐµÐ», Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ†ÑŠÑ‚ Ð¼Ð¾Ð¶Ðµ Ð´Ð° Ñ‚Ñ€ÑŠÐ³Ð½Ðµ Ð¿Ð¾-Ñ€Ð°Ð½Ð¾)</t>
    <t id="30117">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð´Ð½ÐµÐ²Ð½Ð¸ÐºÐ° Ð·Ð° Ð²ÑÑÐºÐ° ÑÐ´ÐµÐ»ÐºÐ°</t>
    <t id="30118">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ: 0=Ð¢Ð¸Ñ…Ð¾, 1=ÐÐ¾Ñ€Ð¼Ð°Ð»Ð½Ð¾, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾</t>
    <t id="30119">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸ÑÑ‚Ð° Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð° Ð¸ ÑÐ¸ÑÑ‚ÐµÐ¼Ð°Ñ‚Ð° Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð°Ñ†Ð¸Ð¸</t>
    <t id="30120">ÐÐ¸Ð²Ð¾ Ð½Ð° Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸: 0=Ð˜Ð·ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾, 1=ÐÐ¾Ñ€Ð¼Ð°Ð»Ð½Ð¾, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾</t>
    <t id="30121">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, ÑÑŠÑ‰Ð¾ ÐºÑƒÐ¿ÑƒÐ²Ð°Ð¹Ñ‚Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ¸ Ð·Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð°. Ð”Ð¾ÑÑ‚Ð°Ð²ÐºÐ°Ñ‚Ð° Ð¸Ð¼Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð¿Ð°Ð´Ð½Ðµ Ð¿Ð¾Ð´ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¸Ñ Ð¿Ñ€Ð°Ð³</t>
    <t id="30122">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ð½ÑÐºÐ¾Ð¹ Ñ€ÐµÑÑƒÑ€Ñ Ð¿Ð°Ð´Ð½Ðµ Ð¿Ð¾Ð´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð¾Ñ‚ Ñ†ÐµÐ»Ñ‚Ð° ÑÐ¸, Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ°Ñ‚Ð° Ð¸Ð¼Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¿Ñ€ÐµÐ´ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°Ñ‚Ð°. Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð° ÑÐµ, Ð°ÐºÐ¾ ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð° Ð½Ðµ Ð¼Ð¾Ð¶Ðµ Ð´Ð° ÑÐ¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸ Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="30123">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð¸Ð»Ð¸ Ð·Ð°ÐºÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸/ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð±Ð°Ð½Ð´Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¸Ð¼Ð° Ñ‚Ð°ÐºÐ¸Ð²Ð°</t>
    <t id="30124">Ð˜Ð·Ð±Ð¾Ñ€ Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°: 1 = Ñ‚Ð¾Ð²Ð°Ñ€ (Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð°Ð¹-Ð²Ð¸ÑÐ¾ÐºÐ¾ Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° ÑÐºÐ»Ð°Ð´Ð° Ð·Ð° ÑÑ‚Ð¾ÐºÐ°Ñ‚Ð°; Ð¿Ñ€Ð¸ Ñ€Ð°Ð²ÐµÐ½ÑÑ‚Ð²Ð¾ - Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°), 2 = Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° (Ð½Ð°Ð¹-Ð´Ð¾Ð±ÑŠÑ€ Ñ€ÐµÐ·ÑƒÐ»Ñ‚Ð°Ñ‚ Ð·Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°)</t>
    <t id="30125">ÐŸÐ¾Ð·Ð²Ð¾Ð»ÑÐ²Ð° ÑÐ²ÑŠÑ€Ð·Ð²Ð°Ð½Ðµ Ð½Ð° Ð½ÑÐºÐ¾Ð»ÐºÐ¾ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð¸ Ð² ÐµÐ´Ð¸Ð½ Ñ†Ð¸ÐºÑŠÐ» (Ð´Ð¾ 3 ÑÑ‚Ð¾ÐºÐ¸ Ð¸Ð»Ð¸ Ñ†ÐµÐ»Ð¸). Ð˜Ð·ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ð·Ð° Ñ†Ð¸ÐºÐ»Ð¸ ÑÐ°Ð¼Ð¾ Ñ ÐµÐ´Ð½Ð° ÑÐ´ÐµÐ»ÐºÐ°</t>
    <t id="30200">ÐŸÑ€Ð¾Ð´Ð°Ð²Ð°Ð¼ %1 %2 Ð¾Ñ‚ %3 Ð´Ð¾ %4</t>
    <t id="30201">ÐÑÐ¼Ð° Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸ Ð·Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð² Ñ€Ð°Ð¼ÐºÐ¸Ñ‚Ðµ Ð½Ð° %1 ÑÐºÐ¾ÐºÐ°</t>
    <t id="30202">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ %1 Ðµ ÑƒÐ½Ð¸Ñ‰Ð¾Ð¶ÐµÐ½Ð° - Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ°Ñ‚Ð° Ð½Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ðµ Ð°Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ð°</t>
    <t id="30203">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð°Ñ‚Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ %1 Ð²ÐµÑ‡Ðµ Ð½Ðµ Ðµ ÑÐ¾Ð±ÑÑ‚Ð²ÐµÐ½Ð¾ÑÑ‚ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð° - Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ°Ñ‚Ð° Ðµ Ð°Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ð°</t>
    <t id="30204">Ð˜Ð·Ð¸ÑÐºÐ²Ð° ÑÐµ Ð¿Ñ€Ð¸ÑÐ²Ð¾ÑÐ²Ð°Ð½Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ - Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ°Ñ‚Ð° Ðµ Ð°Ð½ÑƒÐ»Ð¸Ñ€Ð°Ð½Ð°</t>
    <t id="30205">MK1 Station Trader Ð·Ð°Ð¿Ð¾Ñ‡Ð½Ð° Ð² %1</t>
    <t id="30206">Ð—Ð°Ð²ÑŠÑ€ÑˆÐµÐ½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°: %1 %2 Ð¿Ñ€Ð¾Ð´Ð°Ð´ÐµÐ½ Ð½Ð° %3 Ð·Ð° %4 Cr (Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°: %5 Cr)</t>
    <t id="30207">ÐŸÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ñ Ð¼Ð½Ð¾Ð¶ÐµÑÑ‚Ð²Ð¾ ÑÑ‚Ð¾ÐºÐ¸: Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð½Ð° %1 ÑÑ‚Ð¾ÐºÐ¸ Ð´Ð¾ %2 Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¸</t>
    <t id="30208">Ð”Ð¾ÑÑ‚Ð°Ð²ÑÐ½Ðµ Ð½Ð° %1 %2 Ð´Ð¾ %3 Ð¾Ñ‚ %4</t>
    <t id="30500">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð½Ð° GalaxyTrader MK1</t>
    <t id="30501">ÐÐ°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Station Trader</t>
    <t id="30502">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="30503">Ð¦ÐµÐ» Ð·Ð° Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="30504">ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð°</t>
    <t id="30505">ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ Ñ‚Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ð¾ÑÑ‚ ÐºÑŠÐ¼ Ð¾Ð±Ñ€Ð°Ñ‚ÐµÐ½ Ñ…Ð¾Ð´</t>
    <t id="30506">Ð’Ñ€ÐµÐ¼Ðµ Ð·Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½ÑÐ¼Ð° Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸ ÑÐ´ÐµÐ»ÐºÐ¸</t>
    <t id="30507">ÐŸÐ¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ Buy Cargo Fill Target</t>
    <t id="31002">Galaxy-Miner</t>
    <t id="31102">ÐÐ²Ñ‚Ð¾Ð½Ð¾Ð¼Ð½Ð¾ ÐºÐ¾Ð¿Ð°ÐµÐ½Ðµ ÑÑŠÑ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ ÑÑŠÑ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð¸ Ð½Ð°Ð¿Ñ€ÐµÐ´Ð²Ð°Ð½Ðµ Ð½Ð° XP</t>
    <t id="31010">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="31110">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ñ Ð·Ð° ÐºÐ¾Ð¿Ð°ÐµÐ½Ðµ Ð¸ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð´Ð¾ (Ð²Ð·Ð°Ð¸Ð¼Ð½Ð¾ Ð¸Ð·ÐºÐ»ÑŽÑ‡Ð²Ð°Ñ‰Ð¾ ÑÐµ Ñ Home Sector)</t>
    <t id="31011">Ð”Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€</t>
    <t id="31111">Ð¡ÐµÐºÑ‚Ð¾Ñ€, Ð² ÐºÐ¾Ð¹Ñ‚Ð¾ Ð´Ð° Ð¾Ð¿ÐµÑ€Ð¸Ñ€Ð°Ñ‚Ðµ; Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° ÑÐµ, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½Ðµ Ðµ Ð·Ð°Ð´Ð°Ð´ÐµÐ½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="31012">ÐšÐ¾ÑˆÐ½Ð¸Ñ†Ð° Ñ Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="31112">Ð˜Ð·Ð´ÐµÐ»Ð¸Ñ Ð·Ð° Ð¼Ð¸Ð½Ð°; Ð¿Ñ€Ð°Ð·Ð½Ð¾ ÑÐ»ÐµÐ´Ð²Ð° Ñ€ÐµÐ·Ð¾Ð»ÑŽÑ†Ð¸Ñ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð°</t>
    <t id="31013">Ð¦ÐµÐ»ÐµÐ²Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="31113">Ð”Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»ÐµÐ½ Ñ„Ð¸Ð»Ñ‚ÑŠÑ€ Ð·Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð·Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸; Ð¿Ñ€Ð°Ð·ÐµÐ½ Ð¿Ñ€Ð¾Ð¸Ð·Ð»Ð¸Ð·Ð° Ð¾Ñ‚ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð¸Ñ ÐºÐ¾Ð½Ñ‚ÐµÐºÑÑ‚</t>
    <t id="31014">ÐŸÑ€Ð°Ð³ Ð½Ð° Ð¿Ñ€ÐµÐ¿ÑŠÐ»Ð²Ð°Ð½Ðµ %</t>
    <t id="31114">Ð¡Ñ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ Ñ Ð¸Ð»Ð¸ Ð½Ð°Ð´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ ÑÐµ Ñ‚Ñ€ÐµÑ‚Ð¸Ñ€Ð°Ñ‚ ÐºÐ°Ñ‚Ð¾ Ð¿ÑŠÐ»Ð½Ð¸</t>
    <t id="31015">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð½Ð° Ð¿Ñ€ÐµÐ¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ð´Ñ€ÑƒÐ³Ð¸</t>
    <t id="31115">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾ Ð¸ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ñ‚Ðµ Ñ†ÐµÐ»Ð¸ ÑÐ° Ð¿ÑŠÐ»Ð½Ð¸, Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ð½Ð° Ð´Ñ€ÑƒÐ³Ð¸ Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¾Ð½Ð½Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="31016">ÐŸÑ€Ð¸ÑÐ²Ð¾ÑÐ²Ð°Ð½Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="31116">Ð—Ð°Ð´Ð°Ð¹Ñ‚Ðµ ÐºÐ¾Ñ€Ð°Ð± ÐºÐ°Ñ‚Ð¾ Ð¼Ð¸Ð½ÑŒÐ¾Ñ€ÑÐºÐ¸ Ð¿Ð¾Ð´Ñ‡Ð¸Ð½ÐµÐ½ Ð½Ð° Home Station, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð¿Ñ€Ð¸Ð»Ð¾Ð¶Ð¸Ð¼Ð¾</t>
    <t id="31017">ÐžÑÑ‚Ð°Ð½ÐµÑ‚Ðµ ÑÐ¸ Ñƒ Ð´Ð¾Ð¼Ð°</t>
    <t id="31117">ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡Ð°Ð²Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ð¿Ð°ÐµÐ½Ðµ/Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð´Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° Ð·Ð¾Ð½Ð°, Ñ Ð¸Ð·ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ðµ Ð½Ð° Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸ Ð¿ÑƒÑÐºÐ°Ð½Ð¸Ñ Ð¿Ñ€Ð¸ Ð¿Ñ€ÐµÐ¿ÑŠÐ»Ð²Ð°Ð½Ðµ</t>
    <t id="31018">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ€Ð°Ð·Ð³Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð½Ð° ÑÐ¾Ð½Ð´Ð¸ Ð·Ð° Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="31118">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ€Ð°Ð·Ð³Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ñ€ÐµÐ´ÐµÐ½Ð¸ ÑÐ¾Ð½Ð´Ð¸ Ð·Ð° Ñ€ÐµÑÑƒÑ€ÑÐ¸ Ð¸ Ð²ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ Ð½Ð° ÑÐ¾Ð½Ð´Ð¸ Ð² Ð²ÑŠÐ·ÑÑ‚Ð°Ð½Ð¾Ð²ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð·Ð°Ð¿Ð°ÑÐ¸Ñ‚Ðµ Ð·Ð° Ð¿Ð¾Ð´Ð´Ñ€ÑŠÐ¶ÐºÐ°</t>
    <t id="31019">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° ÑÑŠÐ±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="31119">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð·Ð° ÑÑŠÐ±Ð¸Ñ€Ð°Ð½Ðµ (0 Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚/ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€)</t>
    <t id="31020">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð°</t>
    <t id="31120">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð´Ð¾ Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð·Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° (0 Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ðµ Ð½Ð° ÑƒÐ¼ÐµÐ½Ð¸ÑÑ‚Ð° Ð½Ð° Ð¿Ð¸Ð»Ð¾Ñ‚/ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€)</t>
    <t id="31021">Ð‘Ð°Ð»Ð°Ð½ÑÐ¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ„Ð»Ð¾Ñ‚Ð°</t>
    <t id="31121">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ Ð´ÐµÑ‚ÐµÑ€Ð¼Ð¸Ð½Ð¸Ñ€Ð°Ð½Ð° ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ð¸Ñ Ð½Ð° Ð½Ð°Ð¼ÐµÑ€ÐµÐ½Ð¸ÑÑ‚Ð°, Ð·Ð° Ð´Ð° Ð½Ð°Ð¼Ð°Ð»Ð¸Ñ‚Ðµ Ð¿Ñ€ÐµÐ¿ÑŠÐ»Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð°</t>
    <t id="31022">Ð˜Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð·Ð° Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð° Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ° Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="31122">ÐšÐ¾Ð»ÐºÐ¾ Ñ‡ÐµÑÑ‚Ð¾ ÑÐµ Ð¸Ð·Ð¿ÑŠÐ»Ð½ÑÐ²Ð° Ð¾Ñ†ÐµÐ½ÐºÐ°Ñ‚Ð° Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ/Ð¿Ñ€ÐµÐ²ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ Ð½Ð° Ð¼Ð¸Ð½ÑŒÐ¾Ñ€</t>
    <t id="31023">Ð”ÐµÐ»Ñ‚Ð° Ð½Ð° ÐºÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð¾Ñ‚Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ</t>
    <t id="31123">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð° Ð´ÐµÐ»Ñ‚Ð° Ð·Ð° ÑÐ¿ÐµÑˆÐ½Ð¾ÑÑ‚, Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð° Ð·Ð° Ð¿Ñ€ÐµÐ²ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ Ð½Ð° Ð°ÐºÑ‚Ð¸Ð²ÐµÐ½ ÑÐ¾Ñ„Ñ‚ÑƒÐµÑ€ Ð·Ð° ÐºÐ¾Ð¿Ð°ÐµÐ½Ðµ</t>
    <t id="31024">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€ÐµÐ²ÐºÐ»ÑŽÑ‡Ð²Ð°Ñ‚ÐµÐ»Ñ</t>
    <t id="31124">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð²Ñ€ÐµÐ¼Ðµ Ð¼ÐµÐ¶Ð´Ñƒ Ð´Ð²Ðµ ÑÐ¼ÐµÐ½Ð¸ Ð½Ð° ÑÑ‚Ð¾ÐºÐ¸ Ð·Ð° Ñ‚Ð¾Ð·Ð¸ ÐºÐ¾Ñ€Ð°Ð±</t>
    <t id="31025">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ % Ð°Ð½Ð³Ð°Ð¶Ð¸Ð¼ÐµÐ½Ñ‚ Ð·Ð° Ñ‚Ð¾Ð²Ð°Ñ€</t>
    <t id="31125">ÐÐºÐ¾ Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð° Ðµ Ð½Ð°Ð´ Ñ‚Ð¾Ð²Ð°, ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ð¸Ñ‚Ð° Ð´Ð° Ð·Ð°Ð²ÑŠÑ€ÑˆÐ¸ Ñ‚ÐµÐºÑƒÑ‰Ð°Ñ‚Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð¿Ñ€ÐµÐ´Ð¸ ÑÐ¼ÑÐ½Ð°</t>
    <t id="31026">Ð¢Ð²ÑŠÑ€Ð´Ð° Ð°Ð²Ð°Ñ€Ð¸Ð¹Ð½Ð° Ð´ÐµÐ»Ñ‚Ð°</t>
    <t id="31126">Ð”ÐµÐ»Ñ‚Ð° Ð·Ð° ÑÐ¿ÐµÑˆÐ½Ð¾ÑÑ‚, ÐºÐ¾ÑÑ‚Ð¾ Ð¿Ð¾Ð·Ð²Ð¾Ð»ÑÐ²Ð° Ð½ÐµÐ·Ð°Ð±Ð°Ð²Ð½Ð¾ Ð¿Ñ€ÐµÐ²ÐºÐ»ÑŽÑ‡Ð²Ð°Ð½Ðµ Ð²ÑŠÐ¿Ñ€ÐµÐºÐ¸ Ð¿Ñ€Ð°Ð³Ð° Ð·Ð° Ð°Ð½Ð³Ð°Ð¶Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð°</t>
    <t id="31027">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ</t>
    <t id="31127">ÐÐ¸Ð²Ð¾ Ð½Ð° ÑƒÐ²ÐµÐ´Ð¾Ð¼ÑÐ²Ð°Ð½Ðµ: 0=Ð¢Ð¸Ñ…Ð¾, 1=ÐÐ¾Ñ€Ð¼Ð°Ð»Ð½Ð¾, 2=ÐŸÐ¾Ð´Ñ€Ð¾Ð±Ð½Ð¾</t>
    <t id="31028">Ð¡Ð°Ð¼Ð¾ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð·Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸</t>
    <t id="31128">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, ÑÐ°Ð¼Ð¾ Ð¿Ñ€Ð¸Ñ‚ÐµÐ¶Ð°Ð²Ð°Ð½Ð¸Ñ‚Ðµ Ð¾Ñ‚ Ð¸Ð³Ñ€Ð°Ñ‡Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ ÑÐµ ÑÑ‡Ð¸Ñ‚Ð°Ñ‚ Ð·Ð° Ñ†ÐµÐ»Ð¸ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾.</t>
    <t id="31031">ÐŸÑŠÑ€Ð²Ð¾ Ð¿Ñ€Ð¾Ð²ÐµÑ€Ð¸ Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="31131">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, Ð¼Ð¸Ð½ÑŒÐ¾Ñ€ÑŠÑ‚ Ð¿Ñ€Ð¾Ð²ÐµÑ€ÑÐ²Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ Ð¿Ñ€ÐµÐ´Ð¸ Ð´Ð¾Ð±Ð¸Ð² Ð¸ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚Ð¸Ð·Ð¸Ñ€Ð° ÑÑƒÑ€Ð¾Ð²Ð¸Ð½Ð¸Ñ‚Ðµ ÑÑŠÐ¾Ñ‚Ð²ÐµÑ‚Ð½Ð¾. ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, Ð´Ð¾Ð±Ð¸Ð²Ð° Ð¾Ñ‚ ÐºÐ¾ÑˆÐ½Ð¸Ñ†Ð°Ñ‚Ð° Ñ Ñ€ÐµÑÑƒÑ€ÑÐ¸ Ð±ÐµÐ· Ð¿Ñ€Ð¾Ð²ÐµÑ€ÐºÐ° Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð¸ ÑÐºÐ»Ð°Ð´Ð¸Ñ€Ð° Ð´Ð¾ Ð½Ð°Ð»Ð¸Ñ‡ÐµÐ½ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡ (Ð¿Ñ€ÐµÐ¿Ð¾Ñ€ÑŠÑ‡Ð¸Ñ‚ÐµÐ»Ð½Ð¾ Ð·Ð° Ñ„Ð»Ð¾Ñ‚Ð¸ Ñ ÐµÐ´Ð½Ð° ÑÑƒÑ€Ð¾Ð²Ð¸Ð½Ð°).</t>
    <t id="31032">ÐŸÑ€ÐµÐºÑŠÑÐ²Ð°Ð½Ðµ Ð¿Ñ€Ð¸ Ñ„Ð¸Ð·. ÑÐºÐ»Ð°Ð´ %</t>
    <t id="31132">Ð—Ð° Ð¿Ð¸Ð»Ð¾Ñ‚Ð¸ Ð½Ð¸Ð²Ð¾ 6+: ÑÐ¿Ð¸Ñ€Ð° Ð´Ð¾Ð±Ð¸Ð²Ð° Ð½Ð° Ñ‚ÐµÐºÑƒÑ‰Ð°Ñ‚Ð° ÑÑƒÑ€Ð¾Ð²Ð¸Ð½Ð°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ñ„Ð¸Ð·Ð¸Ñ‡ÐµÑÐºÐ¸ÑÑ‚ Ð·Ð°Ð¿Ð°Ñ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð° Ð¿Ð»ÑŽÑ Ñ‚Ð¾Ð²Ð°Ñ€ÑŠÑ‚ Ð½Ð° ÑÐ²ÑŠÑ€Ð·Ð°Ð½Ð¸Ñ‚Ðµ Ð¼Ð¸Ð½ÑŒÐ¾Ñ€Ð¸ Ð½Ð°Ð´Ð²Ð¸ÑˆÐ¸ Ñ‚ÐµÐºÑƒÑ‰Ð¸Ñ Ñ„Ð¸Ð·Ð¸Ñ‡ÐµÑÐºÐ¸ Ð·Ð°Ð¿Ð°Ñ Ñ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚. Ð˜Ð·Ð¿Ð¾Ð»Ð·Ð²Ð° Ñ€ÐµÐ°Ð»Ð½Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð½Ð¸ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑÑ‚Ð²Ð°, Ð½Ðµ Ð¿Ñ€Ð°Ð³Ð° Ð·Ð° Ð¿Ñ€ÐµÐ¿ÑŠÐ»Ð²Ð°Ð½Ðµ. 0 = Ð¸Ð·ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾.</t>
    <t id="32002">GalaxyTrader Ð”Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð½Ð° MK4</t>
    <t id="32102">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ Ð·Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸, Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ñ‰ GT ÐºÐµÑˆ/Ñ‚Ñ€ÑŠÐ±Ð¾Ð¿Ñ€Ð¾Ð²Ð¾Ð´ Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð¶Ð¸Ð²Ð¾</t>
    <t id="32010">Ð Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ð¸Ðµ</t>
    <t id="32110">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¾Ñ‚ Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð´Ð¾ Ð´Ð¾Ð¼Ð° Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ñ</t>
    <t id="32011">ÐšÑƒÐ¿ÐµÑ‚Ðµ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ</t>
    <t id="32111">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð½Ð° Ð²Ñ€Ð°Ñ‚Ð°Ñ‚Ð° Ð¾Ñ‚ Ð´Ð¾Ð¼Ð° Ð·Ð° Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ðº</t>
    <t id="32012">Ð¡ÐµÑ€Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÐ°Ð¼Ð¾ Ñƒ Ð´Ð¾Ð¼Ð°</t>
    <t id="32112">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, ÑÐµ Ð¾Ð±ÑÐ»ÑƒÐ¶Ð²Ð° ÑÐ°Ð¼Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½Ðµ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ</t>
    <t id="32013">Ð˜Ð·Ð³Ñ€Ð°Ð´ÐµÑ‚Ðµ ÑÐ°Ð¼Ð¾ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="32113">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, ÑÐµ Ð¾Ð±ÑÐ»ÑƒÐ¶Ð²Ð° ÑÐ°Ð¼Ð¾ Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾ Ð½Ð° Ñ…Ñ€Ð°Ð½Ð¸Ð»Ð¸Ñ‰Ðµ Ð·Ð° Ð¸Ð·Ð³Ñ€Ð°Ð¶Ð´Ð°Ð½Ðµ</t>
    <t id="32014">ÐšÑƒÐ¿ÐµÑ‚Ðµ Ð¾Ñ‚ Player</t>
    <t id="32114">Ð Ð°Ð·Ñ€ÐµÑˆÐµÑ‚Ðµ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÑÑ‚Ð¾ÐºÐ¸ Ð¾Ñ‚ Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ñ†Ð¸, Ð¿Ñ€Ð¸Ñ‚ÐµÐ¶Ð°Ð²Ð°Ð½Ð¸ Ð¾Ñ‚ Ð¸Ð³Ñ€Ð°Ñ‡Ð¸</t>
    <t id="32015">ÐšÑƒÐ¿ÐµÑ‚Ðµ Ð¾Ñ‚ Faction</t>
    <t id="32115">Ð Ð°Ð·Ñ€ÐµÑˆÐµÑ‚Ðµ ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° ÑÑ‚Ð¾ÐºÐ¸ Ð¾Ñ‚ Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ñ†Ð¸ Ð½Ð° Ñ„Ñ€Ð°ÐºÑ†Ð¸Ð¸, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð½Ðµ ÑÐ° Ð¸Ð³Ñ€Ð°Ñ‡Ð¸</t>
    <t id="32016">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="32116">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ½Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð² ÑÑŠÐ¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="32017">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¼ÐµÐ¶Ð´Ð¸Ð½Ð½Ð¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="32117">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ð¼ÐµÐ¶Ð´Ð¸Ð½Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð² Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="32018">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="32118">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¾Ð²Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð² ÑÑŠÐ¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="32019">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Tradewares</t>
    <t id="32119">Ð’ÐºÐ»ÑŽÑ‡ÐµÑ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ ÑÐ¾Ñ„Ñ‚ÑƒÐµÑ€Ð½Ð¸ ÑÑ‚Ð¾ÐºÐ¸ Ð² ÑÑŠÐ¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²Ð¸Ðµ Ð½Ð° Ñ‚ÑŠÑ€ÑÐµÐ½ÐµÑ‚Ð¾</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">Ð¡ÐºÐ»Ð°Ð´Ð¾Ð²Ð° Ð´Ð¸ÑÑ‚Ñ€Ð¸Ð±ÑƒÑ†Ð¸Ñ Ñ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ðµ Ð½Ð° Ð¿Ñ€Ð°Ð³Ð¾Ð²ÐµÑ‚Ðµ Ð·Ð° ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ</t>
    <t id="20010">Ð˜Ð·Ñ…Ð¾Ð´Ð½Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="20011">Ð¦ÐµÐ»ÐµÐ²Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸</t>
    <t id="20012">ÐœÐ¸Ð½. ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ %</t>
    <t id="20013">Ð¡Ñ‚Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ %</t>
    <t id="20014">ÐœÐ°ÐºÑ. ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ %</t>
    <t id="20015">Ware Filter</t>
    <t id="20016">Ð”Ð²ÑƒÐ¿Ð¾ÑÐ¾Ñ‡ÐµÐ½ Ñ€ÐµÐ¶Ð¸Ð¼</t>
    <t id="20017">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ (Ð¿Ð¾ Ð¸Ð·Ð±Ð¾Ñ€)</t>
    <t id="20018">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ</t>
    <t id="20032">Ð”Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€ (Ð¿Ð¾ Ð¸Ð·Ð±Ð¾Ñ€)</t>
    <t id="20019">Ð’Ñ€ÐµÐ¼Ðµ Ð·Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ñ†Ð¸ÐºÑŠÐ»</t>
    <t id="20030">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð½Ð¸ÑÑŠÐº Ð·Ð²ÑƒÐº</t>
    <t id="20031">ÐÐ¸ÑÑŠÐº Ð¾Ð±ÐµÐ¼ÐµÐ½ Ð¿Ð¾Ð´ %</t>
    <t id="20110">Ð¡Ð¿Ð¸ÑÑŠÐº Ð½Ð° Ð¸Ð·Ñ…Ð¾Ð´Ð½Ð¸Ñ‚Ðµ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸, Ð¾Ñ‚ ÐºÐ¾Ð¸Ñ‚Ð¾ Ð´Ð° ÑÐµ Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ñ‚ ÑÑ‚Ð¾ÐºÐ¸</t>
    <t id="20111">Ð¡Ð¿Ð¸ÑÑŠÐº Ð½Ð° Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸/ÑÐºÐ»Ð°Ð´Ð¾Ð²Ðµ Ð·Ð° Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð½Ð° ÑÑ‚Ð¾ÐºÐ¸Ñ‚Ðµ</t>
    <t id="20112">ÐŸÑ€Ð°Ð³ Ð½Ð° ÑÐ¿ÐµÑˆÐ½Ð¾ÑÑ‚ Ð½Ð° Ð¼ÐµÑÑ‚Ð¾Ð½Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸ÐµÑ‚Ð¾: ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ Ð¿Ð¾Ð´ Ñ‚Ð¾Ð·Ð¸ % Ð·Ð° ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð¿Ð¾Ð»ÑƒÑ‡Ð°Ð²Ð°Ñ‚ Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸</t>
    <t id="20113">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ Ð¿Ñ€Ð°Ð³ Ð½Ð° Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°: Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÑŠÑ‚ Ñ‚Ñ€ÑÐ±Ð²Ð° Ð´Ð° Ð¸Ð¼Ð° Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¾Ñ‚ Ñ‚Ð¾Ð·Ð¸ %, Ð·Ð° Ð´Ð° ÑÐµ Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð° Ð¸Ð·Ð¾Ð±Ñ‰Ð¾</t>
    <t id="20114">ÐŸÑ€Ð°Ð³ Ð½Ð° Ð¿Ñ€ÐµÐ¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°: Ð½Ð°Ð´ Ñ‚Ð¾Ð·Ð¸ % Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÑŠÑ‚ Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð° Ð´Ð¾Ñ€Ð¸ Ð´Ð¾ Ð½ÐµÑÐ¿ÐµÑˆÐ½Ð¸ Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¸</t>
    <t id="20115">Ð”Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»ÐµÐ½ Ñ„Ð¸Ð»Ñ‚ÑŠÑ€ Ð·Ð° ÑÑŠÐ´Ð¾Ð²Ðµ; Ð¾ÑÑ‚Ð°Ð²ÐµÑ‚Ðµ Ð¿Ñ€Ð°Ð·Ð½Ð¾, Ð·Ð° Ð´Ð° Ñ€Ð°Ð·Ð¿Ñ€ÐµÐ´ÐµÐ»Ð¸Ñ‚Ðµ Ð²ÑÐ¸Ñ‡ÐºÐ¸ ÑÑ‚Ð¾ÐºÐ¸ Ð¾Ñ‚ Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°</t>
    <t id="20116">ÐÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð¹Ñ‚Ðµ ÑÑŠÐ±Ð¸Ñ€Ð°Ð½ÐµÑ‚Ð¾ Ð½Ð° Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾ Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð¾Ñ‚ Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¸ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð¾ Ð´Ð¾ Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ°, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¸Ñ‚Ðµ Ð¸Ð¼Ð°Ñ‚ Ð¸Ð·Ð»Ð¸ÑˆÑŠÐº</t>
    <t id="20117">Ð”Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð·Ð° Ð¿Ñ€Ð¸ÑÐ²Ð¾ÑÐ²Ð°Ð½Ðµ. ÐÐºÐ¾ Ðµ Ð¿Ñ€Ð°Ð·ÐµÐ½, ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð¾ÑÑ‚Ð°Ð²Ð° Ð½ÐµÑ€Ð°Ð·Ð¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½ ÐºÑŠÐ¼ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸Ñ‚Ðµ.</t>
    <t id="20118">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»Ð½Ð¾ Ñ€Ð°Ð·ÑÑ‚Ð¾ÑÐ½Ð¸Ðµ Ð¼ÐµÐ¶Ð´Ñƒ Ð¸Ð·Ñ‚Ð¾Ñ‡Ð½Ð¸ÐºÐ° Ð¸ Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¸Ñ‚Ðµ (0 = Ð½ÐµÐ¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾)</t>
    <t id="20132">Ð”Ð¾Ð¿ÑŠÐ»Ð½Ð¸Ñ‚ÐµÐ»ÐµÐ½ Ð´Ð¾Ð¼Ð°ÑˆÐµÐ½ ÑÐµÐºÑ‚Ð¾Ñ€, Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð½ Ð·Ð° Ð¿Ð°Ñ€ÐºÐ¸Ñ€Ð°Ð½Ðµ Ð¿Ñ€Ð¸ Ð¿Ñ€ÐµÑÑ‚Ð¾Ð¹, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½ÑÐ¼Ð° Ð·Ð°Ð´Ð°Ð´ÐµÐ½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ.</t>
    <t id="20119">Ð’Ñ€ÐµÐ¼Ðµ Ð·Ð° Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð¼ÐµÐ¶Ð´Ñƒ Ñ†Ð¸ÐºÐ»Ð¸Ñ‚Ðµ Ð½Ð° Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ</t>
    <t id="20130">Ð Ð°Ð·Ñ€ÐµÑˆÐ°Ð²Ð°Ð½Ðµ Ð½Ð° Ð¿Ð¾-Ð¼Ð°Ð»ÐºÐ¸ Ñ‡Ð°ÑÑ‚Ð¸ Ð·Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ°, ÑÑŠÐ¾Ð±Ñ€Ð°Ð·ÐµÐ½Ð¸ ÑÑŠÑ ÑÐ¿ÐµÑˆÐ½Ð¾ÑÑ‚Ñ‚Ð°, Ð¿Ð¾Ð´ Ð½Ð¾Ñ€Ð¼Ð°Ð»Ð½Ð¸Ñ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ Ñ‚Ð¾Ð²Ð°Ñ€.</t>
    <t id="20131">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð½Ð° Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð°, Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ð½, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½ Ñ€ÐµÐ¶Ð¸Ð¼ÑŠÑ‚ Ð·Ð° Ð¼Ð°Ð»ÑŠÐº Ð¾Ð±ÐµÐ¼.</t>
    <t id="20200">Ð Ð°Ð·Ð¿Ñ€ÐµÐ´ÐµÐ»ÑÐ½Ðµ Ð½Ð° %1 %2 Ð¾Ñ‚ %3 Ð´Ð¾ %4</t>
    <t id="20201">ÐžÐ±Ñ€Ð°Ñ‚Ð½Ð¾ Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ: ÑÑŠÐ±Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° %1 %2 Ð¾Ñ‚ %3 Ð´Ð¾ %4</t>
    <t id="20202">ÐÐµ Ðµ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ Ñ€Ð°Ð·Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ - Ð²ÑÐ¸Ñ‡ÐºÐ¸ Ð´ÐµÑÑ‚Ð¸Ð½Ð°Ñ†Ð¸Ð¸ ÑÐ° Ð°Ð´ÐµÐºÐ²Ð°Ñ‚Ð½Ð¾ ÑÐ½Ð°Ð±Ð´ÐµÐ½Ð¸</t>
    <t id="20203">Vsichki izhodni stancii sa nevalidni - razprostranenieto chaka</t>
    <t id="20204">Vsichki celevi stancii sa nevalidni - razprostranenieto chaka</t>
    <t id="20205">Izhodna stanciya %1 e unishtozhena - premahnata ot porychkata za razprostranenie</t>
    <t id="20206">Celeva stanciya %1 e unishtozhena - premahnata ot porychkata za razprostranenie</t>
    <t id="20500">GalaxyTrader MK2 - Ð“Ð»Ð¾Ð±Ð°Ð»Ð½Ð¸ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸</t>
    <t id="20501">MK2 Ð´Ð¸ÑÑ‚Ñ€Ð¸Ð±ÑƒÑ†Ð¸Ñ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="20510">% Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ</t>
    <t id="20511">Ð¡Ñ‚Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑÑŠÑ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ðµ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ %</t>
    <t id="20512">ÐœÐ°ÐºÑ. Ñ…Ñ€Ð°Ð½Ð¸Ð»Ð¸Ñ‰Ðµ Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ %</t>
    <t id="20513">Ð˜Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ñ†Ð¸ÐºÑŠÐ» Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ (s)</t>
    <t id="20514">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð¾ Ð¿ÑŠÐ»Ð½ÐµÐ½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð° %</t>
    <t id="20520">ÐœÐ½Ð¾Ð³Ð¾ÑÐ»Ð¾Ð²Ð½Ð¾ÑÑ‚ Ð½Ð° Ð¸Ð·Ð²ÐµÑÑ‚Ð¸ÑÑ‚Ð°</t>
    <t id="20521">ÐÐ¸Ð²Ð¾ Ð½Ð° Ð¾Ñ‚ÑÑ‚Ñ€Ð°Ð½ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð³Ñ€ÐµÑˆÐºÐ¸</t>
    <t id="10006">Ð’ÑŠÑ€Ð½ÐµÑ‚Ðµ ÑÐµ Ñƒ Ð´Ð¾Ð¼Ð°</t>
    <t id="10007">GalaxyTrader Ð”Ð¾ÑÑ‚Ð°Ð²ÐºÐ° MK4-2</t>
    <t id="10106">Ð—Ð°ÐºÐ°Ñ‡ÐµÑ‚Ðµ ÑÐµ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð°Ñ‚Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð¸ Ð¾ÑÑ‚Ð°Ð½ÐµÑ‚Ðµ Ñ‚Ð°Ð¼, Ð´Ð¾ÐºÐ°Ñ‚Ð¾ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð° ÑÐµ Ð¿Ð¾Ð´Ð½Ð¾Ð²Ð¸</t>
    <t id="10107">ÐŸÐ¾Ñ€ÑŠÑ‡ÐºÐ° Ð·Ð° ÑÐ½Ð°Ð±Ð´ÑÐ²Ð°Ð½Ðµ Ð½Ð° Ð¸Ð³Ñ€Ð°Ñ‡Ð° Ñ Ð¿Ð»ÑŠÐ·Ð³Ð°Ñ‡Ð¸ Ð·Ð° Ð¿Ñ€Ð¸Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð° Ñ†ÐµÐ»Ð¸Ñ‚Ðµ Ð·Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ°</t>
    <t id="30026">Ð’Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ñƒ Ð´Ð¾Ð¼Ð° Ð¼ÐµÐ¶Ð´Ñƒ Ñ†Ð¸ÐºÐ»Ð¸Ñ‚Ðµ</t>
    <t id="30028">Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ¸ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹</t>
    <t id="30029">Ð”Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½ Ð½Ð° Ñ†ÐµÐ½Ð°Ñ‚Ð° Ð½Ð° ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð°</t>
    <t id="30027">ÐœÐ¸Ð½. ÑÐºÐ»Ð°Ð´ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚ %</t>
    <t id="30126">ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, Ð²Ñ€ÑŠÑ‰Ð°Ð½Ðµ ÐºÑŠÐ¼ Ð½Ð°Ñ‡Ð°Ð»Ð½Ð°Ñ‚Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð¸ Ð´Ð¾ÐºÐ¸Ð½Ð³ Ð¼ÐµÐ¶Ð´Ñƒ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸Ñ‚Ðµ Ñ†Ð¸ÐºÐ»Ð¸. ÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ðµ Ð´ÐµÐ°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾, Ð¿Ñ€Ð¾Ð´ÑŠÐ»Ð¶ÐµÑ‚Ðµ Ð´Ð° Ñ‚ÑŠÑ€ÑÐ¸Ñ‚Ðµ Ð¾Ñ‚ Ñ‚ÐµÐºÑƒÑ‰Ð¾Ñ‚Ð¾ Ð¼ÐµÑÑ‚Ð¾Ð¿Ð¾Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ (Ð½Ð°ÑÐ»ÐµÐ´ÐµÐ½Ð¾ Ð¿Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ðµ)</t>
    <t id="30128">Ð Ð°Ð·Ñ€ÐµÑˆÐ¸Ñ‚ÑŒ Ð²Ð½ÑƒÑ‚Ñ€ÐµÐ½Ð½Ð¸Ðµ Ð¿ÐµÑ€ÐµÐ²Ð¾Ð´Ñ‹ ÑÐ¾ ÑÐºÐ»Ð°Ð´Ð° Ð±ÐµÐ· Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ð¹ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸/Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð¸ ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸. Ð˜ÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÐµÑ‚ Ð¾Ð±Ð¼ÐµÐ½ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸ Ð´Ð»Ñ Ð·Ð°Ð±Ð¾Ñ€Ð° Ð¸ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ Ð¸Ð· Ð±ÑƒÑ„ÐµÑ€Ð°. Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ‹Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ð¸ ÑÐ¾Ñ…Ñ€Ð°Ð½ÑÑŽÑ‚ÑÑ, ÐµÑÐ»Ð¸ Â«Ð˜Ð³Ð½Ð¾Ñ€Ð¸Ñ€Ð¾Ð²Ð°Ñ‚ÑŒ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð»Ð¸Â» Ð¾Ñ‚ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¾.</t>
    <t id="30129">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»Ð½Ð° Ð¾Ñ‚Ð½Ð¾ÑÐ¸Ñ‚ÐµÐ»Ð½Ð° Ñ†ÐµÐ½Ð° Ð·Ð° NPC ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸ Ð¿Ñ€Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð°. ÐŸÐ»ÑŠÐ·Ð³Ð°Ñ‡ Ð½Ð° Ð¿Ð¾Ñ€ÑŠÑ‡ÐºÐ°Ñ‚Ð° 0-200 (100 = ÑÑ€ÐµÐ´Ð½Ð°, 0 = -100%, 200 = +100%), ÑÑŠÐ¾Ñ‚Ð²ÐµÑ‚ÑÑ‚Ð²Ð° Ð½Ð° -1,0..+1,0. ÐŸÐ¾-Ð²Ð¸ÑÐ¾ÐºÐ¾ = ÑÐ°Ð¼Ð¾ ÑÐºÑŠÐ¿Ð¸ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸. ÐŸÐ¾-Ð½Ð¸ÑÐºÐ¾ = Ð¿Ð¾Ð²ÐµÑ‡Ðµ Ð¾Ð¿Ñ†Ð¸Ð¸ Ð·Ð° ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‡Ð¸. Ð¡Ð½Ð°Ð±Ð´Ð¸Ñ‚ÐµÐ»Ð½Ð¸Ñ‚Ðµ Ð¼Ð¸ÑÐ¸Ð¸ Ð¸Ð·Ð¿Ð¾Ð»Ð·Ð²Ð°Ñ‚ Ð¾Ð±Ñ€Ð°Ñ‚Ð½Ð°Ñ‚Ð° ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ð·Ð° Ñ‚Ð°Ð²Ð°Ð½ Ð½Ð° Ñ†ÐµÐ½Ð¸Ñ‚Ðµ Ð½Ð° Ð´Ð¾ÑÑ‚Ð°Ð²Ñ‡Ð¸Ñ†Ð¸Ñ‚Ðµ.</t>
    <t id="30127">ÐœÐ¸Ð½Ð¸Ð¼Ð°Ð»ÐµÐ½ Ð¿Ñ€Ð¾Ñ†ÐµÐ½Ñ‚ Ð·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° ÑÐºÐ»Ð°Ð´Ð° Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸ÑÑ‚Ð° (ÑÐ¿Ñ€ÑÐ¼Ð¾ ÐºÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð¸Ñ€Ð°Ð½Ð¸Ñ Ð¼Ð°ÐºÑÐ¸Ð¼ÑƒÐ¼ Ð½Ð° ÑÑ‚Ð¾ÐºÐ°), Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼ Ð¿Ñ€ÐµÐ´Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ð±Ð° Ð½Ð° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚ Ð¸Ð»Ð¸ ÑÑ‚Ð¾ÐºÐ°. Ð¡Ñ‚Ð¾ÐºÐ¸ Ð¿Ð¾Ð´ Ñ‚Ð¾Ð·Ð¸ Ð¿Ñ€Ð°Ð³ ÑÐµ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°Ñ‚. 0 = Ð±ÐµÐ· Ð¼Ð¸Ð½Ð¸Ð¼ÑƒÐ¼.</t>
    <t id="3107">Ð˜Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ° Ð·Ð° Ð¼ÑƒÐ»Ñ‚Ð¸Ñ‚Ñ€ÐµÐ¹Ð´: %1. Ð¢Ñ€ÑÐ±Ð²Ð° Ð´Ð° ÑÐ¿ÐµÑ‡ÐµÐ»Ñ %2 Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°.</t>
    <t id="3108">ÐŸÑ€Ð¾Ð´Ð°Ð²Ð°Ð¼ %1 %2 Ð¾Ñ‚ %3 Ð½Ð° Ñ†ÐµÐ½Ð° %4. Ð¢Ñ€ÑÐ±Ð²Ð° Ð´Ð° ÑÐ¿ÐµÑ‡ÐµÐ»Ñ %5 Ð¿ÐµÑ‡Ð°Ð»Ð±Ð°.</t>
    <t id="3110">ÐŸÐ¾ÑÑ‚Ð°Ð²ÑÐ¼ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð·Ð° %1 %2. Ð—Ð°ÐºÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° %3 Ð¾Ñ‚ %4, Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð´Ð¾ %5. Ð“Ð¾Ñ€Ð½Ð° Ð³Ñ€Ð°Ð½Ð¸Ñ†Ð° Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ð½Ð° ÐºÐ»Ð¸ÐµÐ½Ñ‚Ð° %6 - %7/ÐµÐ´. Ð¿Ð¾Ð´ Ð³Ñ€Ð°Ð½Ð¸Ñ†Ð°Ñ‚Ð° (%8 Ð¾Ð±Ñ‰Ð¾).</t>
    <t id="3111">ÐŸÐ¾ÑÑ‚Ð°Ð²ÑÐ¼ Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð·Ð° %1 %2 Ð¾Ñ‚ %3 Ð´Ð¾ %4.</t>
    <t id="3112">Ð”Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð½Ð° Ð¾Ð¿Ð°ÑˆÐºÐ° (%1 ÐµÑ‚Ð°Ð¿Ð°): %2. ÐžÐ±Ñ‰Ð¾ %3 Ð¿Ð¾Ð´ Ð³Ð¾Ñ€Ð½Ð°Ñ‚Ð° Ð³Ñ€Ð°Ð½Ð¸Ñ†Ð° Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ° Ð½Ð° ÐºÐ»Ð¸ÐµÐ½Ñ‚Ð°.</t>
    <t id="3113">Ð¢ÑŠÑ€Ð³Ð¾Ð²ÐµÑ† Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ: Ð¸Ð·Ñ‡Ð°ÐºÐ²Ð°Ð½Ðµ Ð½Ð° ÐµÐºÑÐ¿Ð¾Ñ€Ñ‚ÐµÐ½ Ð¼ÑƒÐ»Ñ‚Ð¸Ñ‚Ñ€ÐµÐ¹Ð´: %1. ÐžÑ‡Ð°ÐºÐ²Ð°Ð½Ð° Ð¿ÐµÑ‡Ð°Ð»Ð±Ð° %2.</t>
    <t id="31029">Ð¦ÐµÐ» Ð½Ð° Ð·Ð°Ð¿Ð°ÑÐ° Ð½Ð° ÑÐ¾Ð½Ð´Ð°Ñ‚Ð°</t>
    <t id="31030">ÐœÐ¸Ð½ÑŒÐ¾Ñ€ÑÐºÐ¸ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ Ð·Ð° ÐºÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: Ð½ÑÐ¼Ð° Ð½Ð°Ð»Ð¸Ñ‡Ð½Ð¸ Ð´Ð¾Ð±Ð¸Ð²Ð°ÐµÐ¼Ð¸ ÑÑƒÑ€Ð¾Ð²Ð¸Ð½Ð¸. ÐšÐ¾Ñ€Ð°Ð± %1 [%2], Ð¤Ð»Ð¾Ñ‚: %3</t>
    <t id="31201">Galaxy-Miner: Ð·Ð°Ð´Ð°Ð¹Ñ‚Ðµ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° ÑÑ‚Ð°Ð½Ñ†Ð¸Ñ Ð¸Ð»Ð¸ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ð° Ð¿Ð¾Ð·Ð¸Ñ†Ð¸Ñ.</t>
    <t id="31130">ÐšÐ¾Ð»ÐºÐ¾ ÑÑŠÐ±Ð¸Ñ€Ð°Ñ‰Ð¸ (Ð¼Ð¸Ð½ÑŒÐ¾Ñ€ÑÐºÐ¸) Ð´Ñ€Ð¾Ð½Ð° ÐºÑƒÐ¿ÑƒÐ²Ð° Ð¼Ð¸Ð½ÑŒÐ¾Ñ€ÑŠÑ‚, ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð¼Ñƒ ÑÐ²ÑŠÑ€ÑˆÐ¸ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¸ÑÑ‚ Ñ‚Ð¸Ð¿ (Ñ‚Ð²ÑŠÑ€Ð´/Ñ€ÑƒÐ´Ð° Ð¸Ð»Ð¸ Ñ‚ÐµÑ‡ÐµÐ½/Ð³Ð°Ð·). ÐšÑƒÐ¿ÑƒÐ²Ð°Ð½ÐµÑ‚Ð¾ ÑÐµ Ð·Ð°Ð´ÐµÐ¹ÑÑ‚Ð²Ð° Ð¡ÐÐœÐž ÐºÐ¾Ð³Ð°Ñ‚Ð¾ ÐºÐ¾Ñ€Ð°Ð±ÑŠÑ‚ Ð½ÑÐ¼Ð° ÑÑŠÐ±Ð¸Ñ€Ð°Ñ‡Ð¸ Ð¾Ñ‚ Ñ‚Ð¾Ð·Ð¸ Ñ‚Ð¸Ð¿ - Ð¼Ð¸Ð½ÑŒÐ¾Ñ€, ÐºÐ¾Ð¹Ñ‚Ð¾ Ð²ÑÐµ Ð¾Ñ‰Ðµ Ð¸Ð¼Ð° Ð¿Ð¾Ð½Ðµ ÐµÐ´Ð¸Ð½, Ð½Ð¸ÐºÐ¾Ð³Ð° Ð½Ðµ ÑÐµ Ð¿Ð¾Ð¿ÑŠÐ»Ð²Ð° Ð¸Ð»Ð¸ ÐºÑƒÐ¿ÑƒÐ²Ð° Ð¾Ñ‚Ð½Ð¾Ð²Ð¾, Ð° ÑÑŠÑ‰ÐµÑÑ‚Ð²ÑƒÐ²Ð°Ñ‰Ð¸Ñ‚Ðµ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ ÑÐµ Ð·Ð°Ð¿Ð°Ð·Ð²Ð°Ñ‚. ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¾ Ð¾Ñ‚ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚Ð° Ð½Ð° Ð¾Ñ‚ÑÐµÐºÐ° Ð·Ð° ÐµÐ´Ð¸Ð½Ð¸Ñ†Ð¸ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð°. Ð—Ð°Ð´Ð°Ð¹Ñ‚Ðµ 0, Ð·Ð° Ð´Ð° Ð¸Ð·ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ñ‚Ð¾ ÐºÑƒÐ¿ÑƒÐ²Ð°Ð½Ðµ Ð½Ð° ÑÑŠÐ±Ð¸Ñ€Ð°Ñ‰Ð¸ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ Ð¸ Ð´Ð° ÑƒÐ¿Ñ€Ð°Ð²Ð»ÑÐ²Ð°Ñ‚Ðµ Ð´Ñ€Ð¾Ð½Ð¾Ð²ÐµÑ‚Ðµ Ñ€ÑŠÑ‡Ð½Ð¾. Ð¡Ñ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚Ñ‚Ð° Ð¿Ð¾ Ð¿Ð¾Ð´Ñ€Ð°Ð·Ð±Ð¸Ñ€Ð°Ð½Ðµ 5 Ðµ Ð¿ÑŠÐ»ÐµÐ½ ÐºÐ¾Ð¼Ð¿Ð»ÐµÐºÑ‚ Ð´Ñ€Ð¾Ð½Ð¾Ð²Ðµ Ð·Ð° Ð½Ð¾Ñ€Ð¼Ð°Ð»Ð½Ð° ÑÐºÐ¾Ñ€Ð¾ÑÑ‚ Ð½Ð° Ð´Ð¾Ð±Ð¸Ð².</t>
    <t id="31129">Ð‘Ñ€Ð¾Ð¹ ÑÐ¾Ð½Ð´Ð¸ Ð·Ð° Ñ€ÐµÑÑƒÑ€ÑÐ¸, ÐºÐ¾Ð¸Ñ‚Ð¾ Ð¼Ð¸Ð½ÑŒÐ¾Ñ€ÑŠÑ‚ ÐºÑƒÐ¿ÑƒÐ²Ð° Ð·Ð° Ð¿ÑŠÑ‚ÑƒÐ²Ð°Ð½Ðµ Ð·Ð° Ð¿Ñ€ÐµÐ·Ð°Ñ€ÐµÐ¶Ð´Ð°Ð½Ðµ. ÐšÑƒÐ¿ÑƒÐ²Ð°Ð½ÐµÑ‚Ð¾ ÑÐµ Ð·Ð°Ð´ÐµÐ¹ÑÑ‚Ð²Ð° Ð¡ÐÐœÐž ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° ÑÐ° ÑÐ²ÑŠÑ€ÑˆÐ¸Ð»Ð¸ ÑÐ¾Ð½Ð´Ð¸Ñ‚Ðµ (Ð±Ñ€Ð¾Ð¹ = 0), Ð° Ð½Ðµ Ð¿Ñ€Ð¸ Ð²ÑÑÐºÐ¾ Ñ€Ð°Ð·Ð³Ñ€ÑŠÑ‰Ð°Ð½Ðµ - Ð¿Ð¾ Ñ‚Ð¾Ð·Ð¸ Ð½Ð°Ñ‡Ð¸Ð½ Ð¼Ð¸Ð½ÑŒÐ¾Ñ€ÑŠÑ‚ Ð¿Ñ€ÐµÐ¼Ð¸Ð½Ð°Ð²Ð° Ð¿Ñ€ÐµÐ· Ð¿ÑŠÐ»Ð½Ð¾Ñ‚Ð¾ ÑÐ¸ Ð½Ð°Ñ‚Ð¾Ð²Ð°Ñ€Ð²Ð°Ð½Ðµ Ð½Ð° ÑÐ¾Ð½Ð´Ð°Ñ‚Ð° Ð¼ÐµÐ¶Ð´Ñƒ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸Ñ‚Ðµ, Ð²Ð¼ÐµÑÑ‚Ð¾ Ð´Ð° ÑÐµ Ð¾Ñ‚ÐºÐ»Ð¾Ð½ÑÐ²Ð° ÑÐ»ÐµÐ´ Ð²ÑÑÐºÐ¾ Ñ€Ð°Ð·Ð³Ñ€ÑŠÑ‰Ð°Ð½Ðµ. ÐžÐ³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½ Ð¾Ñ‚ Ð¾Ð±Ñ‰Ð¸Ñ ÐºÐ°Ð¿Ð°Ñ†Ð¸Ñ‚ÐµÑ‚ Ð·Ð° Ñ€Ð°Ð·Ð³Ñ€ÑŠÑ‰Ð°Ð½Ðµ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð° (ÑÐ¿Ð¾Ð´ÐµÐ»ÐµÐ½ ÑÑŠÑ ÑÐ°Ñ‚ÐµÐ»Ð¸Ñ‚Ð¸/Ð¼Ð¸Ð½Ð¸/Ð¸ Ñ‚.Ð½.); ÑÑ‚Ð¾Ð¹Ð½Ð¾ÑÑ‚ Ð½Ð° Ð¿Ð»ÑŠÐ·Ð³Ð°Ñ‡Ð°, Ð¿Ð¾-Ð³Ð¾Ð»ÑÐ¼Ð° Ð¾Ñ‚ ÑÐ²Ð¾Ð±Ð¾Ð´Ð½Ð¾Ñ‚Ð¾ Ð¿Ñ€Ð¾ÑÑ‚Ñ€Ð°Ð½ÑÑ‚Ð²Ð¾ Ð·Ð° Ñ€Ð°Ð·Ð¿Ð¾Ð»Ð°Ð³Ð°Ð½Ðµ, ÐµÐ»ÐµÐ³Ð°Ð½Ñ‚Ð½Ð¾ ÑÐµ Ð´ÐµÐ³Ñ€Ð°Ð´Ð¸Ñ€Ð° Ð´Ð¾ â€žÐ·Ð°Ð¿ÑŠÐ»Ð²Ð°Ð½Ðµ Ð½Ð° Ñ‚Ð¾Ð²Ð°, ÐºÐ¾ÐµÑ‚Ð¾ Ð¿Ð°ÑÐ²Ð°â€œ. Ð’Ð»Ð¸Ð·Ð° Ð² ÑÐ¸Ð»Ð° ÑÐ°Ð¼Ð¾ ÐºÐ¾Ð³Ð°Ñ‚Ð¾ Auto Deploy Resource Probes Ðµ Ð°ÐºÑ‚Ð¸Ð²Ð¸Ñ€Ð°Ð½Ð¾ - ÑÑŠÑ‰Ð°Ñ‚Ð° Ð½Ð°ÑÑ‚Ñ€Ð¾Ð¹ÐºÐ° ÑÑŠÑ‰Ð¾ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÑÐ²Ð° Ð¾Ð¿Ð¾Ñ€Ñ‚ÑŽÐ½Ð¸ÑÑ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ð½ÐµÐ´Ñ€ÑÐ²Ð°Ð½Ðµ Ð½Ð° ÑÐ¾Ð½Ð´Ð¸ Ð² Ð¼Ð¸Ð½Ð½Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð¸ ÑÑŠÐ±Ð¸Ñ€Ð°Ð½Ðµ Ð½Ð° Ð¾ÑÑ‚Ð°Ñ€ÐµÐ»Ð¸ ÑÐ¾Ð½Ð´Ð¸ (ÑÐ¾Ð½Ð´Ð¸ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð±ÐµÐ· Ñ€ÐµÑÑƒÑ€ÑÐ¸, ÑÐ²ÑŠÑ€Ð·Ð°Ð½Ð¸ Ñ ÐºÐ¾ÑˆÐ½Ð¸Ñ†Ð°Ñ‚Ð°).</t>
    <t id="3226">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐÐ· ÑÐºÐ°Ñ‡Ð¸Ñ… Ð½Ð° %2 Ð¸ Ñ€ÐµÐ³Ð¸ÑÑ‚Ñ€Ð°Ñ‚Ð¾Ñ€ÑŠÑ‚ Ð½Ð° Trading Academy Ð¿Ð¾Ñ‚Ð²ÑŠÑ€Ð´Ð¸ Ð·Ð°Ð¿Ð¸ÑÐ²Ð°Ð½ÐµÑ‚Ð¾ Ð¼Ð¸ Ð² Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð°Ñ‚Ð° â€ž%3â€œ. Ð¡Ð¼ÐµÑ‚ÐºÐ°Ñ‚Ð° Ð½Ð° Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÐ° Ðµ Ð´ÐµÐ±Ð¸Ñ‚Ð¸Ñ€Ð°Ð½Ð° %4 Cr Ð·Ð° Ð¾Ð±ÑƒÑ‡ÐµÐ½Ð¸ÐµÑ‚Ð¾ Ð² ÐºÑƒÑ€ÑÐ° Ð¸ Ð°Ð· Ð½Ðµ Ð¿Ñ€Ð¸ÐµÐ¼Ð°Ð¼ Ñ‚Ð°Ð·Ð¸ Ð¸Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ð¸Ñ Ñ Ð»ÐµÐºÐ° Ñ€ÑŠÐºÐ°.\n\nÐ¢Ð¾Ð²Ð° Ð½Ðµ Ðµ Ñ€ÑƒÑ‚Ð¸Ð½Ð½Ð¾ ÑÐµÑ€Ñ‚Ð¸Ñ„Ð¸Ñ†Ð¸Ñ€Ð°Ð½Ðµ. Ð˜Ð½ÑÑ‚Ñ€ÑƒÐºÑ‚Ð¾Ñ€Ð¸Ñ‚Ðµ Ð² Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸ÑÑ‚Ð° ÑÐ° Ð²ÐµÑ‚ÐµÑ€Ð°Ð½Ð¸ Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ñ†Ð¸ Ð¸ Ð¿Ñ€ÐµÐ³Ð¾Ð²Ð°Ñ€ÑÑ‰Ð¸ Ð² ÐºÐ¾Ð½ÑÐ¾Ñ€Ñ†Ð¸ÑƒÐ¼Ð¸, Ð° ÑƒÑ‡ÐµÐ±Ð½Ð°Ñ‚Ð° Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð° Ñ‚ÑƒÐº Ðµ Ð¼Ð½Ð¾Ð³Ð¾ Ð¿Ð¾-Ð²Ð·Ð¸ÑÐºÐ°Ñ‚ÐµÐ»Ð½Ð° Ð¾Ñ‚ ÑÑ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ð¸Ñ Ð¸Ð·Ð¿Ð¸Ñ‚ Ð·Ð° Ð½Ð°Ð¿Ñ€ÐµÐ´ÑŠÐº. ÐŸÑ€ÐµÐ· ÑÐ»ÐµÐ´Ð²Ð°Ñ‰Ð¸Ñ‚Ðµ %5 Ð¼Ð¸Ð½ÑƒÑ‚Ð¸ Ñ‰Ðµ ÑÐµ Ð¿Ð¾Ð´Ð»Ð¾Ð¶Ð° Ð½Ð° Ð¸Ð½Ñ‚ÐµÐ½Ð·Ð¸Ð²Ð½Ð¸ Ð¸Ð½ÑÑ‚Ñ€ÑƒÐºÑ†Ð¸Ð¸ Ð·Ð° ÑƒÑÑŠÐ²ÑŠÑ€ÑˆÐµÐ½ÑÑ‚Ð²Ð°Ð½Ð¸ Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ð¸ Ð·Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸Ñ, Ð°Ð½Ð°Ð»Ð¸Ð· Ð½Ð° Ð¿Ð°Ð·Ð°Ñ€Ð° Ð¿Ð¾Ð´ Ð½Ð°Ñ‚Ð¸ÑÐº Ð¸ Ñ‚Ð°ÐºÑ‚Ð¸ÐºÐ¸Ñ‚Ðµ Ð·Ð° Ð¿Ñ€ÐµÐ³Ð¾Ð²Ð¾Ñ€Ð¸, ÐºÐ¾Ð¸Ñ‚Ð¾ Ñ€Ð°Ð·Ð´ÐµÐ»ÑÑ‚ Ñ‡Ð¸Ñ€Ð°Ñ†Ð¸Ñ‚Ðµ Ð¾Ñ‚ Ð¼Ð°Ð¹ÑÑ‚Ð¾Ñ€Ð¸Ñ‚Ðµ.\n\nÐšÐ¾Ð³Ð°Ñ‚Ð¾ Ñ„Ð¸Ð½Ð°Ð»Ð½Ð¸ÑÑ‚ Ð¸Ð·Ð¿Ð¸Ñ‚ Ð¿Ñ€Ð¸ÐºÐ»ÑŽÑ‡Ð¸ Ð¸ ÑÐµ Ð¾Ñ‚ÐºÐ°Ñ‡Ð°, Ñ‰Ðµ Ð´ÑŠÑ€Ð¶Ð° Ñ‚Ð¸Ñ‚Ð»Ð°Ñ‚Ð° â€ž%3â€œ Ð¸ Ñ‰Ðµ Ð²ÑŠÑ€Ð½Ð° Ð²ÑÐ¸Ñ‡ÐºÐ¾, ÐºÐ¾ÐµÑ‚Ð¾ ÑÑŠÐ¼ Ð½Ð°ÑƒÑ‡Ð¸Ð», Ð² Ð½Ð°ÑˆÐ¸Ñ‚Ðµ Ñ‚ÑŠÑ€Ð³Ð¾Ð²ÑÐºÐ¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ð¸. ÐÑÐ¼Ð° Ð´Ð° Ð¿Ñ€Ð¾Ð¿Ð¸Ð»ÐµÑ Ð½Ð¸Ñ‚Ð¾ ÐµÐ´Ð¸Ð½ ÐºÑ€ÐµÐ´Ð¸Ñ‚ Ð¾Ñ‚ Ñ‚Ð°Ð·Ð¸ Ð²ÑŠÐ·Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚.\n\nÐ¡ Ð±Ð»Ð°Ð³Ð¾Ð´Ð°Ñ€Ð½Ð¾ÑÑ‚ Ð¸ Ñ€ÐµÑˆÐ¸Ñ‚ÐµÐ»Ð½Ð¾ÑÑ‚,\n%6\nÐÐ° Ð±Ð¾Ñ€Ð´Ð° Ð½Ð° %7</t>
    <t id="9924">ÐšÑƒÑ€ÑÑŠÑ‚ Ð½Ð° Trading Academy Ðµ Ð¿Ñ€ÐµÐºÑ€Ð°Ñ‚ÐµÐ½: Ð¿Ð¸Ð»Ð¾Ñ‚ÑŠÑ‚ %1 Ð½Ðµ Ð¼Ð¾Ð¶Ðµ Ð´Ð° ÑÐ¸ Ð¿Ð¾Ð·Ð²Ð¾Ð»Ð¸ Ñ‚Ð°ÐºÑÐ°Ñ‚Ð° Ð¾Ñ‚ %2 Cr Ð² Ð´Ð¾ÐºÐ° Ð½Ð° Ð°ÐºÐ°Ð´ÐµÐ¼Ð¸ÑÑ‚Ð° (Ð¸Ð¼Ð°Ð¹Ñ‚Ðµ %3 Cr). ÐšÑƒÑ€ÑÑŠÑ‚ Ðµ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½, Ð¿Ð¸Ð»Ð¾Ñ‚ÑŠÑ‚ Ð²ÑŠÐ·Ð¾Ð±Ð½Ð¾Ð²ÑÐ²Ð° Ñ‚ÑŠÑ€Ð³Ð¾Ð²Ð¸ÑÑ‚Ð°.</t>
  </page>
</language>
<?xml version='1.0' encoding='utf-8'?>
<language id="380">
  <page id="77000" title="GalaxyTrader MK3" descr="GalaxyTrader MK3 Localization" voice="no">
    <t id="10001">Ð”Ð¾Ðº Ñ– Ñ‡ÐµÐºÐ°Ð¹ (GalaxyTrader MK3)</t>
    <t id="10002">GalaxyTrader MK3</t>
    <t id="10003">Ð¤Ñ–Ð½Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ (GalaxyTrader MK3)</t>
    <t id="10004">Ð Ð°Ð½Ð´ÐµÐ²Ñƒ Ð¾Ð±Ð¼Ñ–Ð½Ñƒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸</t>
    <t id="10005">[Ð—ÐÐ¡Ð¢ÐÐ Ð†Ð›Ð•] GalaxyTrader MK4 ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ (Ð—Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¹)</t>
    <t id="10101">ÐŸÑ€Ð¸ÑÑ‚Ð¸ÐºÑƒÐ¹Ñ‚ÐµÑÑ Ð´Ð¾ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ñ‚Ð° Ð·Ð°Ñ‡ÐµÐºÐ°Ð¹Ñ‚Ðµ Ð²ÐºÐ°Ð·Ð°Ð½Ð¸Ð¹ Ñ‡Ð°Ñ</t>
    <t id="10102">ÐÐ²Ñ‚Ð¾Ð½Ð¾Ð¼Ð½Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð· Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÐµÐ½Ð½ÑÐ¼ ÐºÐ²Ð°Ð»Ñ–Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ—</t>
    <t id="10103">Ð¡ÐºÐ»Ð°Ð´Ñ–Ñ‚ÑŒ Ð²Ð¸Ð¿ÑƒÑÐºÐ½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ Ð´Ð»Ñ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð² Ð½Ð°Ð²Ñ‡Ð°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ð·Ð°ÐºÐ»Ð°Ð´Ñ–</t>
    <t id="10104">Ð”Ð¾Ðº Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð·ÑƒÑÑ‚Ñ€Ñ–Ñ‡Ñ– Ð´Ð»Ñ Ð¾Ð±Ð¼Ñ–Ð½Ñƒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸</t>
    <t id="10105">Ð¢Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ, Ð¾Ñ€Ñ–Ñ”Ð½Ñ‚Ð¾Ð²Ð°Ð½Ð° Ð½Ð° Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ, Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹ Ð³Ñ€Ð°Ð²Ñ†Ñ–Ð² Ð·Ð° Ð´Ð¾Ð¿Ð¾Ð¼Ð¾Ð³Ð¾ÑŽ ÐºÐµÑˆÑƒ Ñ‚Ð° Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– (Ð—Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¹)</t>
    <t id="10201">ÐšÑƒÐ¿ÑƒÐ¹Ñ‚Ðµ %s Ñƒ %s</t>
    <t id="10202">ÐŸÑ€Ð¾Ð´Ð°Ñ‚Ð¸ %s %s</t>
    <t id="10203">Ð¢Ð¾Ñ€Ð³ÑƒÐ²Ð°Ñ‚Ð¸ Ð· %s</t>
    <t id="1000">GalaxyTrader MK3</t>
    <t id="1001">Ð Ð¾Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð· Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑƒÐ²Ð°Ð½Ð½ÑÐ¼ XP Ñ– ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ”ÑŽ Ñ„Ð»Ð¾Ñ‚Ñƒ</t>
    <t id="1002">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ Ð±Ð°Ð·Ð°</t>
    <t id="1003">Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ð¿Ñ€ÐµÑÐµÑ‚Ð¸</t>
    <t id="1004">Ð¢Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð²ÑÑ–Ð¼Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1005">Ð¢Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð»ÐµÐ³Ð°Ð»ÑŒÐ½Ð¸Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1006">Ð¢Ð¾Ñ€Ð³ÑƒÐ²Ð°Ñ‚Ð¸ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ð¸Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1007">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑ XP</t>
    <t id="1008">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–ÑŽ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÑƒ</t>
    <t id="1009">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð½Ð°Ð»Ñ–Ð· Ñ€Ð¸Ð½ÐºÑƒ</t>
    <t id="1010">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ ÑƒÐ¿Ñ€Ð°Ð²Ð»Ñ–Ð½Ð½Ñ Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ñ–Ñ”ÑŽ</t>
    <t id="1011">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="1012">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ñ–</t>
    <t id="1013">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð¾ Ñ€Ð¸Ð·Ð¸ÐºÑƒ</t>
    <t id="1014">Ð Ð¾Ð·ÑÑ‚Ð°Ð²Ñ‚Ðµ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð¸ Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹ Ð³Ñ€Ð°Ð²Ñ†Ñ–Ð²</t>
    <t id="1015">ÐÐ²Ñ‚Ð¾Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="1016">Ð”Ð¸ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ ÑˆÑ‚Ñ€Ð°Ñ„Ñƒ %</t>
    <t id="1017">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ</t>
    <t id="1018">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ</t>
    <t id="1019">Ð¦Ñ–Ð»ÑŒÐ¾Ð²Ð¸Ð¹ % Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ</t>
    <t id="1050">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ñ€Ð¸Ð½ÐºÑƒ</t>
    <t id="1051">Ð–ÑƒÑ€Ð½Ð°Ð» Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ñ— Ð¾Ñ†Ñ–Ð½ÐºÐ¸</t>
    <t id="1052">Ð‘Ñ–Ð»Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð²</t>
    <t id="1054">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿ÐµÑ€ÐµÐ²Ñ–Ð·Ð½Ð¸ÐºÐ¸/Ð´Ð¾Ð¿Ð¾Ð¼Ñ–Ð¶Ð½Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–</t>
    <t id="1056">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Build Storage</t>
    <t id="1058">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ¹Ñ‚Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–</t>
    <t id="1060">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ¹Ñ‚Ðµ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—, Ñ‰Ð¾ Ð½Ð°Ð´Ð°ÑŽÑ‚ÑŒÑÑ MK1</t>
    <t id="1063">Ð’ Ñ€Ð¾Ð·Ñ€Ð¾Ð±Ñ†Ñ–</t>
    <t id="1064">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="1065">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð±Ð°Ð»Ñ–Ð² %</t>
    <t id="1066">Ð¢Ð¾Ð²Ð°Ñ€Ð¸, ÑÐºÐ¸Ð¼ ÑÐ»Ñ–Ð´ Ð²Ñ–Ð´Ð´Ð°Ð²Ð°Ñ‚Ð¸ Ð¿ÐµÑ€ÐµÐ²Ð°Ð³Ñƒ Ð² Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–. Ð‡Ñ…Ð½Ñ Ð¾Ñ†Ñ–Ð½ÐºÐ° Ð¼Ð½Ð¾Ð¶Ð¸Ñ‚ÑŒÑÑ Ð½Ð° % Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¾Ñ— Ð¾Ñ†Ñ–Ð½ÐºÐ¸.</t>
    <t id="1067">ÐœÐ½Ð¾Ð¶Ð½Ð¸Ðº Ð±Ð°Ð»Ñ–Ð² Ð´Ð»Ñ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð²: 100%=Ð½Ð¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹, 150%=+50%%, 200%=2x, 300%=3x. Ð—Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÐ²Ð°Ð²ÑÑ Ð¾ÑÑ‚Ð°Ð½Ð½Ñ–Ð¼.</t>
    <t id="1068">â”€â”€ Ð¤Ñ–Ð»ÑŒÑ‚Ñ€ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² â”€â”€</t>
    <t id="1069">Ð¢Ð¾Ð²Ð°Ñ€Ð¸ (Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="1070">Ð¤Ñ–Ð»ÑŒÑ‚Ñ€ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ–Ð²</t>
    <t id="1072">ÐžÐ±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸ Ñ‚Ñ–Ð»ÑŒÐºÐ¸ Ð²Ð´Ð¾Ð¼Ð°</t>
    <t id="1073">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÐ°-Ð³Ñ€Ð°Ð²Ñ†Ñ</t>
    <t id="1074">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÐ°-Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ—</t>
    <t id="1075">Ð’ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ð¸ Build Storage</t>
    <t id="1076">Ð”Ð¾Ð´Ð°Ð¹Ñ‚Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="1077">Ð’ÐºÐ»ÑŽÑ‡Ð°Ñ‚Ð¸ Ð¿Ñ€Ð¾Ð¼Ñ–Ð¶Ð½Ñ– Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="1078">Ð’ÐºÐ»ÑŽÑ‡Ð°Ñ‚Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="1080">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´ Ð·Ð° Ñ†Ð¸ÐºÐ»</t>
    <t id="1081">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð¾ Ð¿Ð¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ</t>
    <t id="1082">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð°Ð½Ð¸Ð¹ Ð²Ð°Ð½Ñ‚Ð°Ð¶ %</t>
    <t id="1083">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ‚Ð¾Ñ€ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð³Ñ€Ð°Ð²Ñ†Ñ %</t>
    <t id="1085">ÐŸÑ€Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ñ‚Ð¸ Ð±Ð°Ð·Ð¾Ð²Ñ–Ð¹ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="1086">Ð’Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ñ‚Ñ</t>
    <t id="1088">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ° Ð²Ñ–Ð´ Ð´Ð¾Ð¼Ñƒ Ð´Ð»Ñ Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ñ‚Ñ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ</t>
    <t id="1090">Ð’ÐºÐ»ÑŽÑ‡Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ ÐºÐ»Ð°ÑÑƒ Ñƒ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ/Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ—</t>
    <t id="1091">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ‚Ð¾Ñ€, Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²Ð°Ð½Ð¸Ð¹ Ð´Ð¾ Ñ†Ñ–Ð½Ð¾ÑƒÑ‚Ð²Ð¾Ñ€ÐµÐ½Ð½Ñ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÐ°, Ñ‰Ð¾ Ð½Ð°Ð»ÐµÐ¶Ð¸Ñ‚ÑŒ Ð³Ñ€Ð°Ð²Ñ†ÐµÐ²Ñ–, Ñƒ Ñ€Ð¾Ð·Ñ€Ð°Ñ…ÑƒÐ½ÐºÐ°Ñ… Ð»Ð¸ÑˆÐµ Ð·Ð° Ð¾Ñ‡Ð¾Ðº</t>
    <t id="1092">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Ñ†Ñ–Ð½Ð¸ Ð³Ñ€Ð°Ð²Ñ†Ñ–Ð²</t>
    <t id="1093">Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾: Ð·Ð°Ð²Ð¶Ð´Ð¸ ÐºÑƒÐ¿ÑƒÐ¹Ñ‚Ðµ Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–ÑÑ…, Ñ‰Ð¾ Ð½Ð°Ð»ÐµÐ¶Ð°Ñ‚ÑŒ Ð³Ñ€Ð°Ð²Ñ†ÑÐ¼, Ð½ÐµÐ·Ð°Ð»ÐµÐ¶Ð½Ð¾ Ð²Ñ–Ð´ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾Ñ— Ñ†Ñ–Ð½Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ, Ñ– Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ð»Ð¸ÑˆÐµ Ñ„Ñ€Ð°ÐºÑ†Ñ–ÑÐ¼ NPC. ÐšÐ¾Ñ€Ð¸ÑÐ½Ð¾ Ð´Ð»Ñ Ð»Ñ–ÐºÐ²Ñ–Ð´Ð°Ñ†Ñ–Ñ— Ð½Ð°Ð´Ð»Ð¸ÑˆÐºÐ¾Ð²Ð¸Ñ… Ð·Ð°Ð¿Ð°ÑÑ–Ð² Ñ–Ð· Ð²Ð°ÑˆÐ¸Ñ… Ð²Ð»Ð°ÑÐ½Ð¸Ñ… ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹.</t>
    <t id="1094">Ð—Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ñ– ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="1095">Ð’Ð¸Ð±Ñ€Ð°Ð½Ñ– Ñ‚ÑƒÑ‚ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð²Ð¸ÐºÐ»ÑŽÑ‡Ð°ÑŽÑ‚ÑŒÑÑ Ð· Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– MK3. Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†ÑŒ Ð½Ðµ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‚Ð¸Ð¼Ðµ Ð² Ð½Ð¸Ñ… Ñ– Ð½Ðµ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚Ð¸Ð¼Ðµ Ñ—Ð¼.</t>
    <t id="1096">ÐŸÐ°Ñ€ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿Ñ€Ð¾ÑÑ‚Ð¾ÑŽ</t>
    <t id="1097">Ð¯ÐºÑ‰Ð¾ ÑƒÐ²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–, ÑÐºÑ– Ð½ÐµÐ¾Ð´Ð½Ð¾Ñ€Ð°Ð·Ð¾Ð²Ð¾ Ð½Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð½Ð°Ð¹Ñ‚Ð¸ Ñ€Ð¾Ð±Ð¾Ñ‚Ñƒ, Ð¿Ð°Ñ€ÐºÑƒÑŽÑ‚ÑŒÑÑ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð°Ð±Ð¾ Ð² Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾Ð¼Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñ–. ÐŸÐ°Ñ€ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ– Ð½Ð°Ð´Ð°Ñ” Ð¿ÐµÑ€ÐµÐ²Ð°Ð³Ñƒ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑÐ¼ Ð³Ñ€Ð°Ð²Ñ†Ñ, Ð¿Ð¾Ñ‚Ñ–Ð¼ Ð´Ñ€ÑƒÐ¶Ð½Ñ–Ð¼ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑÐ¼. Ð§Ð°Ñ Ð·Ð²Ñ–Ð»ÑŒÐ½ÐµÐ½Ð½Ñ Ð´Ð¾ÐºÐ° Ð·Ð°Ð´Ð°Ñ”Ñ‚ÑŒÑÑ Ð² Ð³Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ð¸Ñ… Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½ÑÑ… (0 = Ð·Ð°Ð»Ð¸ÑˆÐ°Ñ”Ñ‚ÑŒÑÑ Ð±Ñ–Ð»Ñ Ð´Ð¾ÐºÐ°, Ð´Ð¾ÐºÐ¸ Ð½Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÑ‚ÑŒÑÑ Ñ€Ð¾Ð±Ð¾Ñ‚Ð°).</t>
    <t id="1098">ÐÐ²Ñ‚Ð¾Ð¼Ð°ÑÑˆÑ‚Ð°Ð±</t>
    <t id="1099">Ð¯ÐºÑ‰Ð¾ ÑƒÐ²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð¿Ð¾Ð²Ð·ÑƒÐ½ÐºÐ¸ Ð´Ð°Ð»ÑŒÐ½Ð¾ÑÑ‚Ñ– ÑÑ‚Ñ€Ð¸Ð±ÐºÐ° Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÑŽÑŽÑ‚ÑŒÑÑ Ð½Ð° Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾ Ð´Ð¾Ð·Ð²Ð¾Ð»ÐµÐ½Ñƒ Ð´Ð°Ð»ÑŒÐ½Ñ–ÑÑ‚ÑŒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð¿Ñ–ÑÐ»Ñ Ð¾Ð±Ð¾Ð²'ÑÐ·ÐºÐ¾Ð²Ð¾Ð³Ð¾ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð°Ð±Ð¾ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ñ— Ð°ÐºÐ°Ð´ÐµÐ¼Ñ–Ñ—. Ð—Ð½Ñ–Ð¼Ñ–Ñ‚ÑŒ Ð¿Ð¾Ð·Ð½Ð°Ñ‡ÐºÑƒ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð³Ð¾ Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ.</t>
    <t id="11001">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ ÑÑ…Ð¾Ð²Ð¸Ñ‰Ð° Ð±ÑƒÐ´Ñ–Ð²Ð½Ð¸Ñ†Ñ‚Ð²Ð°</t>
    <t id="11002">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹</t>
    <t id="11003">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð´Ð¾Ð¿Ð¾Ð¼Ñ–Ð¶Ð½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²</t>
    <t id="11004">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð°Ð²Ñ–Ð°Ð½Ð¾ÑÑ†Ñ–Ð²</t>
    <t id="11005">0 = Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾. 1-10 = Ð¼Ð½Ð¾Ð¶Ð½Ð¸Ðº Ð¾Ñ‡Ð¾Ðº (10 = Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ð°Ð³Ð°). ÐŸÑ–Ð´ÑÑƒÐ¼Ð¾Ðº = Ð¾Ñ‡ÐºÐ¸ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ Ã— Ð¼Ð½Ð¾Ð¶Ð½Ð¸Ðº.</t>
    <t id="11006">1 = Ð±ÐµÐ· Ð´Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ñ… Ð¾Ñ‡Ð¾Ðº (ÑÐ¿Ð¸ÑÐ¾Ðº Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² Ð±ÐµÐ· Ð·Ð¼Ñ–Ð½). 2-10 = Ð´Ð¾Ð´Ð°Ñ” (Ð¼Ð½Ð¾Ð¶Ð½Ð¸Ðºâˆ’1)Ã— Ð±Ð°Ð·Ð¾Ð²Ñ– Ð¾Ñ‡ÐºÐ¸ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ, ÑÐºÑ‰Ð¾ Ñ‚Ð¾Ð²Ð°Ñ€ Ñƒ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ. Ð—Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð¿Ð¾Ð²ÐµÑ€Ñ… Ð¾Ñ‡Ð¾Ðº Ñ‚Ð¸Ð¿Ñƒ.</t>
    <t id="11007">Ð‘Ð¾Ð½ÑƒÑ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð²</t>
    <t id="11008">%1: Ð£ÑÑ– Ð¿Ð¾Ð²Ð·ÑƒÐ½ÐºÐ¸ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ñƒ Ñ†Ñ–Ð»ÐµÐ¹ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾ Ð½Ð° 0 - Ñ†Ðµ Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð½Ðµ Ð¼Ð°Ñ” Ñ†Ñ–Ð»ÐµÐ¹ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸. Ð£Ð²Ñ–Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ Ð¿Ñ€Ð¸Ð½Ð°Ð¹Ð¼Ð½Ñ– Ð¾Ð´Ð¸Ð½ ÐºÐ»Ð°Ñ (Ð±ÑƒÐ´Ñ–Ð²ÐµÐ»ÑŒÐ½Ð¸Ð¹ ÑÐºÐ»Ð°Ð´, ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—, Ð´Ð¾Ð¿Ð¾Ð¼Ñ–Ð¶Ð½Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð°Ð±Ð¾ Ð½Ð¾ÑÑ–Ñ—), Ñ‰Ð¾Ð± Ð²Ñ–Ð´Ð½Ð¾Ð²Ð¸Ñ‚Ð¸ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ.</t>
    <t id="7001">[ÐŸÐžÐŸÐ•Ð Ð•Ð”ÐÐ¬Ðž]</t>
    <t id="7002">[ÐÐÐ’Ð§ÐÐÐÐ¯]</t>
    <t id="7008">[Ð Ð•Ð—Ð•Ð Ð’ÐÐ˜Ð™]</t>
    <t id="7009">[Ð†Ð—ÐžÐ›Ð¬ÐžÐ’ÐÐÐž]</t>
    <t id="7003">[Ð Ð•ÐœÐžÐÐ¢]</t>
    <t id="7004">[ÐŸÐžÐŸÐžÐ’ÐÐ•ÐÐÐ¯]</t>
    <t id="7005">[Ð¢Ð•Ð¥ÐÐ†Ð§ÐÐ• ÐžÐ‘Ð¡Ð›Ð£Ð“ÐžÐ’Ð£Ð’ÐÐÐÐ¯]</t>
    <t id="7006">[Ð—ÐœÐ†ÐÐ˜Ð¢Ð˜ ÐœÐÐ Ð¨Ð Ð£Ð¢]</t>
    <t id="7007">[Ð Ð¾Ð·Ñ‡Ð¸Ñ‰ÐµÐ½Ð½Ñ]</t>
    <t id="1020">Ð’Ð¸Ð±ÐµÑ€Ñ–Ñ‚ÑŒ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ð°Ð±Ð¾ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ, Ð´Ðµ Ð¿Ñ€Ð°Ñ†ÑŽÑ” Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€</t>
    <t id="1021">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ° Ð¿Ñ–Ð´ Ñ‡Ð°Ñ ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² (Ð¾Ð±Ð¼ÐµÐ¶ÑƒÑ”Ñ‚ÑŒÑÑ Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ°Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°)</t>
    <t id="1022">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ° Ñ‡ÐµÑ€ÐµÐ· Ð²Ð¾Ñ€Ð¾Ñ‚Ð° Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² (Ð¾Ð±Ð¼ÐµÐ¶ÑƒÑ”Ñ‚ÑŒÑÑ Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ°Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°)</t>
    <t id="1023">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¸Ð¹ Ð¿Ñ–Ð´Ð±Ñ–Ñ€ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ñ– ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ñ–Ñ—</t>
    <t id="1024">Ð ÑƒÑ‡Ð½Ð¸Ð¹ Ð¿Ñ–Ð´Ð±Ñ–Ñ€ ÐºÐ¾Ð½ÐºÑ€ÐµÑ‚Ð½Ð¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð²</t>
    <t id="1025">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð±Ð°Ð½Ð´Ð¾ÑŽ Ñ‚Ð° Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ð¸Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸</t>
    <t id="1026">Ð”Ð¾Ð¿ÑƒÑÐº Ð±ÐµÐ·Ð¿ÐµÐºÐ¸: 0,0=Ð›Ð¸ÑˆÐµ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ñ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸, 1,0=ÐŸÑ€Ð¸Ð¹Ð½ÑÑ‚Ð¸ Ð²ÑÑ– Ñ€Ð¸Ð·Ð¸ÐºÐ¸</t>
    <t id="1027">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÑŽÐ¹Ñ‚Ðµ Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð·Ð°Ð²Ð´ÑÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¼Ñƒ Ð´Ð¾ÑÐ²Ñ–Ð´Ñƒ</t>
    <t id="1028">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÑÐ¹Ñ‚Ðµ Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ, ÐºÐ¾Ð»Ð¸ Ñ†Ðµ Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¾</t>
    <t id="1029">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½ÑƒÐ¹Ñ‚Ðµ ÐºÑ–Ð»ÑŒÐºÐ° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð², Ñ‰Ð¾Ð± ÑƒÐ½Ð¸ÐºÐ½ÑƒÑ‚Ð¸ ÐºÐ¾Ð½Ñ„Ð»Ñ–ÐºÑ‚Ñ–Ð²</t>
    <t id="1030">Ð¤Ð¾ÐºÑƒÑ Ð½Ð° Ð¿Ð¾ÑÑƒÐ´Ñ–: 0=Ð—Ð±Ð°Ð»Ð°Ð½ÑÐ¾Ð²Ð°Ð½Ð¸Ð¹, 1=Ð Ð¾Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð¸Ð¹, 2=ÐžÑÐ½Ð¾Ð²Ð½Ñ– Ð¿Ð¾Ñ‚Ñ€ÐµÐ±Ð¸, 3=ÐÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ð¸Ð¹, 4=ÐÐ°ÑÐ¸Ð¿Ð½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="1031">Ð—Ð¾Ð½Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–: 0=Ð—Ð±Ð°Ð»Ð°Ð½ÑÐ¾Ð²Ð°Ð½Ð¸Ð¹, 1=ÐžÑÐ½Ð¾Ð²Ð½Ð¸Ð¹ Ñ„Ð¾ÐºÑƒÑ, 2=Ð’Ñ–Ð»ÑŒÐ½Ð¸Ð¹ Ñ€Ð¾ÑƒÐ¼</t>
    <t id="1032">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ: 0=Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹, 1=Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð¸Ð¹, 2=Ð´ÐµÑ‚Ð°Ð»ÑŒÐ½Ñ– Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ</t>
    <t id="1033">Ð¦Ñ–Ð»ÑŒÐ¾Ð²Ð¸Ð¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð°Ð½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ Ð¿ÐµÑ€ÐµÐ´ Ð²Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½ÑÐ¼ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ñ–Ð² Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñ–Ð²</t>
    <t id="1034">Ð¯Ðº Ñ‡Ð°ÑÑ‚Ð¾ Ð¾Ð½Ð¾Ð²Ð»ÑŽÑŽÑ‚ÑŒÑÑ Ñ€Ð¸Ð½ÐºÐ¾Ð²Ñ– Ð´Ð°Ð½Ñ– Ñ‚Ð° Ñ–Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ñ–Ñ Ð¿Ñ€Ð¾ Ñ†Ñ–Ð½Ð¸</t>
    <t id="1035">Ð Ñ–Ð²ÐµÐ½ÑŒ Ð²Ð¸Ð²Ð¾Ð´Ñƒ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ: 0=ÐÐµÐ¼Ð°Ñ”, 1=Ð‘Ð°Ð·Ð¾Ð²Ð¸Ð¹, 2=ÐŸÐ¾Ð²Ð½Ðµ Ð²ÐµÐ´ÐµÐ½Ð½Ñ Ð¶ÑƒÑ€Ð½Ð°Ð»Ñƒ</t>
    <t id="1036">ÐŸÐ¾Ð´Ñ–Ð»Ñ–Ñ‚ÑŒÑÑ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ð¸Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¼Ð¸ ÑˆÐ»ÑÑ…Ð°Ð¼Ð¸ Ð· Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼ (ÐºÐµÑˆÑƒÑ”Ñ‚ÑŒÑÑ Ð´Ð»Ñ ÑˆÐ²Ð¸Ð´ÐºÐ¾Ð³Ð¾ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ñƒ)</t>
    <t id="1037">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº, Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¸Ð¹ Ð´Ð»Ñ ÐºÐµÑˆÑƒÐ²Ð°Ð½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ñ‚Ð° Ð¾Ð±Ð¼Ñ–Ð½Ñƒ Ð· Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼</t>
    <t id="1038">Ð”Ð¾Ð·Ð²Ð¾Ð»ÐµÐ½Ðµ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ðµ Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ Ð´Ð¾ Ñ‚Ð¾Ð³Ð¾, ÑÐº ÐºÐµÑˆÐ¾Ð²Ð°Ð½Ñ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– ÑˆÐ»ÑÑ…Ð¸ ÑÑ‚Ð°Ð½ÑƒÑ‚ÑŒ Ð½ÐµÐ´Ñ–Ð¹ÑÐ½Ð¸Ð¼Ð¸</t>
    <t id="1039">Ð¯Ðº Ð´Ð¾Ð²Ð³Ð¾ ÐºÐµÑˆÐ¾Ð²Ð°Ð½Ñ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð·Ð°Ð»Ð¸ÑˆÐ°ÑŽÑ‚ÑŒÑÑ Ð´Ñ–Ð¹ÑÐ½Ð¸Ð¼Ð¸ Ð´Ð¾ Ð·Ð°ÐºÑ–Ð½Ñ‡ÐµÐ½Ð½Ñ Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ñƒ Ð´Ñ–Ñ—</t>
    <t id="1040">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð´ÐµÑ‚Ð°Ð»ÑŒÐ½Ðµ Ð²ÐµÐ´ÐµÐ½Ð½Ñ Ð¶ÑƒÑ€Ð½Ð°Ð»Ñƒ Ñ–Ð½Ð´Ð¸Ð²Ñ–Ð´ÑƒÐ°Ð»ÑŒÐ½Ð¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¾Ñ†Ñ–Ð½Ð¾Ðº Ñ– Ð²Ñ–Ð´Ñ…Ð¸Ð»ÐµÐ½ÑŒ (Ð¼Ð¾Ð¶Ðµ Ð±ÑƒÑ‚Ð¸ Ð´ÑƒÐ¶Ðµ Ð´Ð¾ÐºÐ»Ð°Ð´Ð½Ð¸Ð¼)</t>
    <t id="1041">Ð£Ð²Ñ–Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ñ– Ñ‚Ð¾Ñ€Ð³Ñ–Ð² Ñ– Ð·Ð°Ñ…Ð¾Ð¿Ð»ÑŽÑŽÑ‡Ñ– Ð½Ð°Ð²Ñ‡Ð°Ð»ÑŒÐ½Ñ– Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ (ÑÑ‚Ð¸Ð»ÑŒ TaterTrader)</t>
    <t id="1053">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð² Ñ†ÑŒÐ¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ Ð²Ð¸ÐºÐ»ÑŽÑ‡ÐµÐ½Ñ– Ð· Ñ‡Ð¾Ñ€Ð½Ð¸Ñ… ÑÐ¿Ð¸ÑÐºÑ–Ð² (Ð·Ð°Ð²Ð¶Ð´Ð¸ Ð´Ð¾Ð·Ð²Ð¾Ð»ÐµÐ½Ð¾)</t>
    <t id="1055">Ð’Ð¸ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ð¸ Ð°Ð²Ñ–Ð°Ð½Ð¾ÑÑ†Ñ– Ñ‚Ð° Ð´Ð¾Ð¿Ð¾Ð¼Ñ–Ð¶Ð½Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð· Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–</t>
    <t id="1057">Ð’Ð¸ÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ð¸ Ð±ÑƒÐ´Ñ–Ð²Ð½Ð¸Ñ†Ñ‚Ð²Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²-ÑÑ…Ð¾Ð²Ð¸Ñ‰ Ñ–Ð· Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="1059">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– ÑÑ‚Ð°Ð½Ñ†Ñ–ÑÐ¼Ð¸ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ (Ñ€Ð¾Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð¸Ð¹; Ð¼Ð¾Ð¶Ð½Ð° Ð²Ð¸Ð±Ñ€Ð°Ñ‚Ð¸ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ—, ÑÐºÑ– Ð·Ð°Ð·Ð²Ð¸Ñ‡Ð°Ð¹ Ð±Ð»Ð¾ÐºÑƒÑŽÑ‚ÑŒÑÑ)</t>
    <t id="1061">ÐŸÑ€Ð¾Ð¿ÑƒÑÐºÐ°Ð¹Ñ‚Ðµ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð³Ñ€Ð°Ð²Ñ†Ñ–Ð², ÑÐºÑ– Ð¼Ð°ÑŽÑ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ MK1 Ñ–Ð· Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ð¼ Ñ€ÐµÐ¶Ð¸Ð¼Ð¾Ð¼ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="1062">ÐŸÑ–Ð´Ð²Ð¸Ñ‰ÑƒÐ¹Ñ‚Ðµ Ñ€ÐµÐ·ÑƒÐ»ÑŒÑ‚Ð°Ñ‚Ð¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð´Ð»Ñ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ–Ð² Ñ–Ð· Ð·Ð°Ð»ÑƒÑ‡ÐµÐ½Ð½ÑÐ¼ Ð²Ð°ÑˆÐ¸Ñ… Ð²Ð»Ð°ÑÐ½Ð¸Ñ… ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹ (10% Ð±Ð¾Ð½ÑƒÑ Ð·Ð° Ð¾Ñ†Ñ–Ð½ÐºÑƒ)</t>
    <t id="1071">ÐšÐ¾Ð»Ð¸ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Â«Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸Â», Ñ‚Ð¾Ñ€Ð³ÑƒÐ¹Ñ‚Ðµ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸Ð¼Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸, Ð»Ð¸ÑˆÐµ ÑÐºÑ‰Ð¾ Ð²Ð¾Ð½Ð¸ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ–, Ñƒ Ð²ÑÑ–Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ð½Ð° ÑˆÐ»ÑÑ…Ñƒ Ð¿ÐµÑ€ÐµÑ…Ð¾Ð´Ñƒ (ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ, Ð¿Ñ€Ð¾Ð´Ð°Ð¶ Ñ– Ð¿Ñ€Ð¾Ð¼Ñ–Ð¶Ð½Ñ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸).</t>
    <t id="1087">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ° Ð²Ñ–Ð´ Ð´Ð¾Ð¼Ñƒ Ð´Ð»Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÐ°</t>
    <t id="1089">Ð¯ÐºÑ‰Ð¾ Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ Ð¼Ð¾Ð¶Ðµ Ð·Ð°Ð±ÐµÐ·Ð¿ÐµÑ‡ÑƒÐ²Ð°Ñ‚Ð¸ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð² Ð·Ð¾Ð½Ñ– Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ñ‚Ñ Ð·Ð° Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ð¸Ð¼ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð¾Ð¼ Ð·Ð°Ð¼Ñ–ÑÑ‚ÑŒ Ñ€ÐµÐ¶Ð¸Ð¼Ñƒ "Ð»Ð¸ÑˆÐµ Ð²Ð´Ð¾Ð¼Ð°"</t>
    <t id="2000">%s Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ð² %s XP!</t>
    <t id="2001">%s Ð¿Ñ–Ð´Ð½ÑÐ²ÑÑ Ð½Ð° Ð½Ð¾Ð²Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ! ÐÐ¾Ð²Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ: %s</t>
    <t id="2002">%s Ð¿Ð¾Ñ‚Ñ€ÐµÐ±ÑƒÑ” Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ! Ð‘ÑƒÐ´ÑŒ Ð»Ð°ÑÐºÐ°, Ð½Ð°Ð´Ñ–ÑˆÐ»Ñ–Ñ‚ÑŒ Ð½Ð° Ð½Ð°Ð¹Ð±Ð»Ð¸Ð¶Ñ‡Ñƒ Ð²ÐµÑ€Ñ„ Ð°Ð±Ð¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñƒ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ.</t>
    <t id="2003">%s Ð¿Ð¾Ñ‡Ð°Ð² Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð² %s</t>
    <t id="2004">%s Ð¿Ñ€Ð¾Ð¹ÑˆÐ¾Ð² Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ñ‚Ð° Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ð² ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ‚ Ñ€Ñ–Ð²Ð½Ñ %s!</t>
    <t id="2005">%s Ð´Ð¾ÑÑÐ³ Skill Level %s Ð¿Ñ–ÑÐ»Ñ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ! ÐŸÑ€Ð¾Ð³Ñ€ÐµÑ XP Ñ€Ð¾Ð·Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¾ Ð² %s.</t>
    <t id="2006">%s Ð´Ð¾ÑÑÐ³ Skill Level %s Ð·Ð°Ð²Ð´ÑÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– %s!</t>
    <t id="2007">%s Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð² Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Level %s! ÐŸÑ€Ð¾Ð³Ñ€ÐµÑ XP Ñ€Ð¾Ð·Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¾ Ð² %s.</t>
    <t id="3000">%s Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð² Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ! ÐŸÑ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº: %s ÐºÑ€</t>
    <t id="3001">%s Ð°Ð½Ð°Ð»Ñ–Ð·ÑƒÑ” Ñ€Ð¸Ð½ÐºÐ¾Ð²Ñ– ÑƒÐ¼Ð¾Ð²Ð¸...</t>
    <t id="3002">%s Ð·Ð½Ð°Ð¹ÑˆÐ¾Ð² Ð²Ð¸Ð³Ñ–Ð´Ð½Ð¸Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ ÑˆÐ»ÑÑ…!</t>
    <t id="3003">ÐÐµÐ¼Ð°Ñ” Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ð¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… ÑˆÐ»ÑÑ…Ñ–Ð² Ð´Ð»Ñ %s</t>
    <t id="3100">ÐŸÑ€Ð¾Ð´Ð°Ð¶ %1 %2 Ð· Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ Ð½Ð° %3 Ð·Ð° %4. Ð¯ Ð¼Ð°ÑŽ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ñ‚Ð¸ %5 Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="3101">ÐŸÐ¾ÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ° Ð² Ñ‡ÐµÑ€Ð³Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð´Ð»Ñ %1 %2. ÐšÑƒÐ¿Ñ–Ð²Ð»Ñ Ð·Ð° %3 Ð· %4, Ð¿Ñ€Ð¾Ð´Ð°Ð¶ Ð·Ð° %5 Ð½Ð° %6. Ð¯ Ð¼Ð°ÑŽ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ñ‚Ð¸ %7 Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="3102">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€: Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ñ” %1 %2 Ð· %3 Ð¿Ñ€Ð¸ %5%% Ð´Ð¾ %4 Ð¿Ñ€Ð¸ %6%%.</t>
    <t id="3103">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€: Ð¿Ñ€Ð¾Ð´Ð°Ð¶ %1 %2 Ð½Ð° %3 Ð·Ð° Ñ†Ñ–Ð½Ð¾ÑŽ %4. ÐžÑ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº %5.</t>
    <t id="3104">Ð¢Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ Ð·Ð° %1 %2 ÑƒÑÐ¿Ñ–ÑˆÐ½Ð¾ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¾. Ð—Ð°Ð³Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº: %3 ÐºÑ€ÐµÐ´Ð¸Ñ‚Ñ–Ð².</t>
    <t id="3105">ÐšÐµÑˆÐ¾Ð²Ð°Ð½Ð¸Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚: %1 %2 Ð· %3 Ð´Ð¾ %4 (Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº: %5 Cr)</t>
    <t id="3106">\nÐ—Ð°Ð³Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¾Ð³Ð½Ð¾Ð·Ð¾Ð²Ð°Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº Ð·Ð° Ð²ÐµÑÑŒ Ð¿ÐµÑ€Ñ–Ð¾Ð´ Ð´Ð¾ Ñ†Ñ–Ñ”Ñ— Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–: %1 Cr.</t>
    <t id="3120">Ð Ð¾Ð·Ð¿Ð¾Ñ‡Ð°Ñ‚Ð¾ Ð¿ÐµÑ€ÐµÐ´Ð°Ñ‡Ñƒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°</t>
    <t id="3121">ÐŸÑ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð» Ð¿ÐµÑ€ÐµÐ´Ð°Ñ‡Ñ– Ð¿Ñ–Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¶ÐµÐ½Ð¾. %1 (%2) Ñ– %3 (%4) Ð¿Ñ€ÑÐ¼ÑƒÑŽÑ‚ÑŒ Ð´Ð¾ %5 (%6), Ñ‰Ð¾Ð± Ð¿Ñ€Ð¸ÑÑ‚Ð¸ÐºÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ñ‚Ð° Ð¾Ð±Ð¼Ñ–Ð½ÑÑ‚Ð¸ÑÑ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð½Ð¸Ð¼Ð¸ Ð¼Ñ–ÑÑ†ÑÐ¼Ð¸.</t>
    <t id="3200">ÐŸÑ€Ð¸Ð²Ñ–Ñ‚ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ %1!\n\nÐ¯ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ð² Ð´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð¾ÑÐ²Ñ–Ð´Ñƒ, Ñ‰Ð¾Ð± ÑÐºÐ»Ð°ÑÑ‚Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ Ð½Ð° Ð·Ð²Ð°Ð½Ð½Ñ "%2". Ð†ÑÐ¿Ð¸Ñ‚ Ñ‚Ñ€Ð¸Ð²Ð°Ñ‚Ð¸Ð¼Ðµ Ð¿Ñ€Ð¸Ð±Ð»Ð¸Ð·Ð½Ð¾ %3 Ñ…Ð²Ð¸Ð»Ð¸Ð½ Ñƒ %4.\n\nÐ¦Ðµ Ð²Ð°Ð¶Ð»Ð¸Ð²Ð° Ð²Ñ–Ñ…Ð° Ð² Ð¼Ð¾Ñ—Ð¹ ÐºÐ°Ñ€â€™Ñ”Ñ€Ñ–. Ð†ÑÐ¿Ð¸Ñ‚ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€Ð¸Ñ‚ÑŒ Ð¼Ð¾Ñ— Ð·Ð½Ð°Ð½Ð½Ñ Ñ€Ð¾Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ñ–Ð², Ð°Ð½Ð°Ð»Ñ–Ð·Ñƒ Ñ€Ð¸Ð½ÐºÑƒ Ñ‚Ð° Ð¿Ñ€Ð¾Ñ†ÐµÐ´ÑƒÑ€ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ— Ñ„Ð»Ð¾Ñ‚Ñƒ.\n\nÐ¯ Ð²Ð¿ÐµÐ²Ð½ÐµÐ½Ð¸Ð¹ Ñƒ ÑÐ²Ð¾Ñ—Ñ… Ð·Ð´Ñ–Ð±Ð½Ð¾ÑÑ‚ÑÑ… Ñ– Ñ€Ð°Ð´Ð¸Ð¹ Ð´Ð¾Ð²ÐµÑÑ‚Ð¸, Ñ‰Ð¾ Ð³Ñ–Ð´Ð½Ð¸Ð¹ Ñ†ÑŒÐ¾Ð³Ð¾ Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÐµÐ½Ð½Ñ. ÐŸÐ¾Ð±Ð°Ð¶Ð°Ð¹Ñ‚Ðµ Ð¼ÐµÐ½Ñ– ÑƒÐ´Ð°Ñ‡Ñ–!\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\n%5\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3201">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ§ÑƒÐ´Ð¾Ð²Ñ– Ð½Ð¾Ð²Ð¸Ð½Ð¸! Ð¯ ÑƒÑÐ¿Ñ–ÑˆÐ½Ð¾ ÑÐºÐ»Ð°Ð² ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ Ñ– Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ð² Ð·Ð²Ð°Ð½Ð½Ñ "%2"!\n\nÐ†ÑÐ¿Ð¸Ñ‚ Ð¾Ñ…Ð¾Ð¿Ð»ÑŽÐ²Ð°Ð² Ð¿ÐµÑ€ÐµÐ´Ð¾Ð²Ñ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– ÑÑ‚Ñ€Ð°Ñ‚ÐµÐ³Ñ–Ñ—, Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ð¸ Ð¾Ñ†Ñ–Ð½ÐºÐ¸ Ñ€Ð¸Ð·Ð¸ÐºÑ–Ð² Ñ– Ð¿Ñ€Ð¾Ñ†ÐµÐ´ÑƒÑ€Ð¸ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ— Ñ„Ð»Ð¾Ñ‚Ñƒ. ÐœÐµÐ½Ñ– Ð¿Ñ€Ð¸Ñ”Ð¼Ð½Ð¾ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð¸Ñ‚Ð¸, Ñ‰Ð¾ Ñ ÑÐºÐ»Ð°Ð² Ð¹Ð¾Ð³Ð¾ Ð½Ð° Ð²Ñ–Ð´Ð¼Ñ–Ð½Ð½Ð¾.\n\nÐ¢ÐµÐ¿ÐµÑ€ Ñ ÐºÐ²Ð°Ð»Ñ–Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¹, Ñ‰Ð¾Ð± ÐºÐµÑ€ÑƒÐ²Ð°Ñ‚Ð¸ ÑÐºÐ»Ð°Ð´Ð½Ñ–ÑˆÐ¸Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ð¸Ð¼Ð¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–ÑÐ¼Ð¸, Ñ– ÑÐ¿Ð¾Ð´Ñ–Ð²Ð°ÑŽÑÑ Ð·Ñ€Ð¾Ð±Ð¸Ñ‚Ð¸ Ñ‰Ðµ Ð±Ñ–Ð»ÑŒÑˆÐ¸Ð¹ Ð²Ð½ÐµÑÐ¾Ðº Ð² ÑƒÑÐ¿Ñ–Ñ… Ð½Ð°ÑˆÐ¾Ð³Ð¾ Ñ„Ð»Ð¾Ñ‚Ñƒ. Ð”ÑÐºÑƒÑŽ, Ñ‰Ð¾ Ñ–Ð½Ð²ÐµÑÑ‚ÑƒÑ”Ñ‚Ðµ Ð² Ð¼Ñ–Ð¹ Ð¿Ñ€Ð¾Ñ„ÐµÑÑ–Ð¹Ð½Ð¸Ð¹ Ñ€Ð¾Ð·Ð²Ð¸Ñ‚Ð¾Ðº.\n\nÐ— Ð½Ð¾Ð²Ð¾ÑŽ Ð²Ñ–Ð´Ð´Ð°Ð½Ñ–ÑÑ‚ÑŽ,\n%3\nÐ¡ÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¹ %2\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %4</t>
    <t id="3202">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¯ Ð½Ð° Ð¶Ð°Ð»ÑŒ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑÑŽ Ð²Ð°Ð¼, Ñ‰Ð¾ Ð¼Ñ–Ð¹ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ Ð±ÑƒÐ»Ð¾ Ð¿ÐµÑ€ÐµÑ€Ð²Ð°Ð½Ð¾ Ñ‡ÐµÑ€ÐµÐ· Ð¾Ð¿ÐµÑ€Ð°Ñ‚Ð¸Ð²Ð½Ñ– Ð²Ð¸Ð¼Ð¾Ð³Ð¸. ÐœÐµÐ½Ñ– Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ð¾ Ð±ÑƒÐ´Ðµ Ð¿ÐµÑ€ÐµÐ½ÐµÑÑ‚Ð¸, ÐºÐ¾Ð»Ð¸ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑ‚ÑŒ Ð¾Ð±ÑÑ‚Ð°Ð²Ð¸Ð½Ð¸.\n\nÐ¯ Ð·Ð°Ð»Ð¸ÑˆÐ°ÑŽÑÑ Ð²Ñ–Ð´Ð´Ð°Ð½Ð¸Ð¼ Ð²Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð½ÑŽ ÑÐ²Ð¾Ñ—Ñ… Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ñ– Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð»Ð¸ Ð·Ð¼Ð¾Ð¶Ñƒ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¾Ñ†ÐµÑ Ñ–ÑÐ¿Ð¸Ñ‚Ñƒ.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\n%2\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %3</t>
    <t id="3203">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÑ Ð·Ð°Ñ€Ð°Ð· Ñƒ Ð´Ð¾Ñ€Ð¾Ð·Ñ– Ð´Ð¾ %2 Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ…Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ð¹Ð½Ð¾Ð³Ð¾ Ñ–ÑÐ¿Ð¸Ñ‚Ñƒ. ÐŸÐ¾Ð´Ð¾Ñ€Ð¾Ð¶ Ð´Ð°Ñ” Ð¼ÐµÐ½Ñ– Ñ‡Ð°Ñ Ð¿ÐµÑ€ÐµÐ³Ð»ÑÐ½ÑƒÑ‚Ð¸ ÑÐ²Ð¾Ñ” Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ñ‚Ð° Ð¼Ð¾Ñ€Ð°Ð»ÑŒÐ½Ð¾ Ð¿Ñ–Ð´Ð³Ð¾Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð´Ð¾ Ñ†ÑŒÐ¾Ð³Ð¾ Ð²Ð°Ð¶Ð»Ð¸Ð²Ð¾Ð³Ð¾ ÐºÑ€Ð¾ÐºÑƒ Ð² Ð¼Ð¾Ñ—Ð¹ ÐºÐ°Ñ€â€™Ñ”Ñ€Ñ–.\n\nÐžÑ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ðµ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ñ‚Ñ: %3 Ñ…Ð²Ð¸Ð»Ð¸Ð½\nÐ¢Ñ€Ð¸Ð²Ð°Ð»Ñ–ÑÑ‚ÑŒ Ñ–ÑÐ¿Ð¸Ñ‚Ñƒ: %4 Ñ…Ð²Ð¸Ð»Ð¸Ð½\n\nÐ¯ Ñ†Ñ–Ð½ÑƒÑŽ Ð²Ð°ÑˆÑƒ Ð²Ð¿ÐµÐ²Ð½ÐµÐ½Ñ–ÑÑ‚ÑŒ Ñƒ Ð¼Ð¾Ñ—Ñ… Ð·Ð´Ñ–Ð±Ð½Ð¾ÑÑ‚ÑÑ… Ñ– Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ñ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾ÑÑƒÐ²Ð°Ð½Ð½Ñ.\n\nÐ— Ñ€Ñ–ÑˆÑƒÑ‡Ñ–ÑÑ‚ÑŽ,\n%5\nÐÐ° Ð±Ð¾Ñ€Ñ‚ %6</t>
    <t id="3204">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸ Ñ Ð²Ð¸ÑÐ²Ð¸Ð² Ð²Ð°Ð½Ñ‚Ð°Ð¶ Ñƒ ÑÐ²Ð¾Ñ”Ð¼Ñƒ Ñ‚Ñ€ÑŽÐ¼Ñ–. ÐŸÐµÑ€Ñˆ Ð½Ñ–Ð¶ Ñ Ð·Ð¼Ð¾Ð¶Ñƒ Ñ€Ð¾Ð·Ð¿Ð¾Ñ‡Ð°Ñ‚Ð¸ Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ñƒ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ, Ð¼ÐµÐ½Ñ– Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ð¾ Ð¿Ñ€Ð¾Ð´Ð°Ñ‚Ð¸ Ñ†ÐµÐ¹ Ñ‚Ð¾Ð²Ð°Ñ€.\n\nÐ¯ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑŽ Ð½Ð°Ñˆ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº, Ñ‰Ð¾Ð± Ð·Ð½Ð°Ð¹Ñ‚Ð¸ Ð½Ð°Ð¹ÐºÑ€Ð°Ñ‰Ð¾Ð³Ð¾ Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ Ñ‚Ð° Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾ Ñ€Ð¾Ð·Ð²Ð°Ð½Ñ‚Ð°Ð¶Ð¸Ñ‚Ð¸ Ñ†ÐµÐ¹ Ð²Ð°Ð½Ñ‚Ð°Ð¶. Ð©Ð¾Ð¹Ð½Ð¾ Ð¼Ð¾Ñ” ÑƒÑ‚Ñ€Ð¸Ð¼Ð°Ð½Ð½Ñ Ð±ÑƒÐ´Ðµ Ð·Ð²Ñ–Ð»ÑŒÐ½ÐµÐ½Ð¾, Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶Ñƒ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ð·Ð¾Ð²Ð°Ð½Ñƒ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ.\n\nÐ¡Ñ‚Ð°Ñ‚ÑƒÑ: Ð¿Ð¾ÑˆÑƒÐº Ð¾Ð¿Ñ‚Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¼Ñ–ÑÑ†Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ\n\nÐ— Ñ€ÐµÑ‚ÐµÐ»ÑŒÐ½Ñ–ÑÑ‚ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %1</t>
    <t id="3205">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¦Ñ–Ð»Ñ–ÑÐ½Ñ–ÑÑ‚ÑŒ Ð¼Ð¾Ð³Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ Ð²Ð¿Ð°Ð»Ð° Ð´Ð¾ %1%% (Ð¿Ð¾Ñ€Ñ–Ð³: %2%%). Ð¯Ðº Ð¿Ñ–Ð»Ð¾Ñ‚ Ñ€Ñ–Ð²Ð½Ñ %3 Ñ Ð¼Ð°ÑŽ Ð¿Ñ€Ð°Ð²Ð¾ Ð²Ð¸Ð¼Ð°Ð³Ð°Ñ‚Ð¸ Ð¿Ð¾ÑÐ»ÑƒÐ³Ð¸ Ð· Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ.\n\nÐ¯ Ð¿ÐµÑ€ÐµÑ…Ð¾Ð´Ð¶Ñƒ Ð´Ð¾ %4 Ð´Ð»Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð¸Ñ… Ñ€Ð¾Ð±Ñ–Ñ‚. ÐžÑ€Ñ–Ñ”Ð½Ñ‚Ð¾Ð²Ð½Ð° Ð²Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ %5 Cr, Ñ‰Ð¾ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð°Ñ” Ð½Ð°ÑˆÐ¾Ð¼Ñƒ Ð±ÑŽÐ´Ð¶ÐµÑ‚Ñƒ.\n\nÐŸÑ–ÑÐ»Ñ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ Ñ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð»ÑŽ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ— Ð· Ð¿Ð¾Ð²Ð½Ð¾ÑŽ ÑÑ‚Ñ€ÑƒÐºÑ‚ÑƒÑ€Ð½Ð¾ÑŽ Ñ†Ñ–Ð»Ñ–ÑÐ½Ñ–ÑÑ‚ÑŽ.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3206">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¢Ð•Ð ÐœÐ†ÐÐžÐ’Ð• Ð¤Ð†ÐÐÐÐ¡ÐžÐ’Ð• ÐŸÐžÐŸÐ•Ð Ð•Ð”Ð–Ð•ÐÐÐ¯\n\nÐ¦Ñ–Ð»Ñ–ÑÐ½Ñ–ÑÑ‚ÑŒ Ð¼Ð¾Ð³Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ ÐºÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð° Ð½Ð° Ñ€Ñ–Ð²Ð½Ñ– %1%% (Ð¿Ð¾Ñ€Ñ–Ð³: %2%%), Ð°Ð»Ðµ Ð½Ð°ÑˆÐ¸Ñ… Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ñ… ÐºÐ¾ÑˆÑ‚Ñ–Ð² (%3 Cr) Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ð¿Ð¾Ð²Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ (Ð¾Ñ€Ñ–Ñ”Ð½Ñ‚Ð¾Ð²Ð½Ð° Ð²Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ: %4 Cr).\n\nÐ¯ Ð¿ÐµÑ€ÐµÑ…Ð¾Ð´Ð¶Ñƒ Ð´Ð¾ %5 Ð½Ð° Ð§ÐÐ¡Ð¢ÐšÐžÐ’Ð˜Ð™ Ð Ð•ÐœÐžÐÐ¢ Ð·Ð° Ð½Ð°ÑÐ²Ð½Ñ– ÐºÐ¾ÑˆÑ‚Ð¸. Ð¦Ðµ Ð½Ðµ Ñ–Ð´ÐµÐ°Ð»ÑŒÐ½Ðµ Ñ€Ñ–ÑˆÐµÐ½Ð½Ñ, Ð°Ð»Ðµ Ð²Ð¾Ð½Ð¾ Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ðµ Ð´Ð»Ñ Ð¿Ñ–Ð´Ñ‚Ñ€Ð¸Ð¼ÐºÐ¸ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ð¹Ð½Ð¾Ñ— ÑÐ¿Ñ€Ð¾Ð¼Ð¾Ð¶Ð½Ð¾ÑÑ‚Ñ–.\n\nÐ‘ÑƒÐ´ÑŒ Ð»Ð°ÑÐºÐ°, Ð¿Ð¾Ð´ÑƒÐ¼Ð°Ð¹Ñ‚Ðµ Ð¿Ñ€Ð¾ Ð²Ð¸Ð´Ñ–Ð»ÐµÐ½Ð½Ñ Ð´Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ñ… ÐºÐ¾ÑˆÑ‚Ñ–Ð² Ð½Ð° Ð¼Ð°Ð¹Ð±ÑƒÑ‚Ð½Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ— Ð· Ñ‚ÐµÑ…Ð½Ñ–Ñ‡Ð½Ð¾Ð³Ð¾ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ð½Ð½Ñ.\n\nÐ¡Ñ‚ÑƒÑ€Ð±Ð¾Ð²Ð°Ð½Ð¸Ð¹, Ð°Ð»Ðµ Ñ€Ñ–ÑˆÑƒÑ‡Ð¸Ð¹,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %6</t>
    <t id="3207">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¼Ñ–Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— %1 Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑ” Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð½Ð¾Ð³Ð¾ Ð¾Ð±Ð»Ð°Ð´Ð½Ð°Ð½Ð½Ñ. ÐŸÑ–ÑÐ»Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸ Ð¼Ð¾Ñ—Ñ… ÑÐ¸ÑÑ‚ÐµÐ¼ Ñ Ð²Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ð², Ñ‰Ð¾ Ð¼Ð¾Ñ— Ð·Ð°ÑÐ¾Ð±Ð¸ Ð¿Ñ€Ð¾Ñ‚Ð¸Ð´Ñ–Ñ— Ñ‚Ð° Ð·Ð°ÑÐ¾Ð±Ð¸ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ Ð½Ð¸Ð¶Ñ‡Ñ– Ð·Ð° Ñ€ÐµÐºÐ¾Ð¼ÐµÐ½Ð´Ð¾Ð²Ð°Ð½Ñ– Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ.\n\nÐ¯ Ð¿ÐµÑ€ÐµÑ…Ð¾Ð´Ð¶Ñƒ Ð´Ð¾ %2, Ñ‰Ð¾Ð± Ð¿Ð¾Ð¿Ð¾Ð²Ð½Ð¸Ñ‚Ð¸ Ð·Ð°Ð¿Ð°ÑÐ¸ ÑÐ²Ð¾Ð³Ð¾ Ð·Ð°Ñ…Ð¸ÑÐ½Ð¾Ð³Ð¾ Ð¾Ð±Ð»Ð°Ð´Ð½Ð°Ð½Ð½Ñ:\nâ€¢ Ð—Ð°Ñ…Ð¾Ð´Ð¸ Ð¿Ñ€Ð¾Ñ‚Ð¸Ð´Ñ–Ñ—: Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð´Ð¾ Ð¾Ð¿Ñ‚Ð¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ñ— Ð¿Ð¾Ñ‚ÑƒÐ¶Ð½Ð¾ÑÑ‚Ñ–\nâ€¢ Ð‘ÐµÐ·Ð¿Ñ–Ð»Ð¾Ñ‚Ð½Ð¸ÐºÐ¸ Ð·Ð°Ñ…Ð¸ÑÑ‚Ñƒ, Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñ– Ð±ÐµÐ·Ð¿Ñ–Ð»Ð¾Ñ‚Ð½Ð¸ÐºÐ¸, Ð»Ð°Ð·ÐµÑ€Ð½Ñ– Ð²ÐµÐ¶Ñ–: Ð·Ð°ÑÑ‚Ð¾ÑÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ñ€Ð¾Ñ„Ñ–Ð»ÑŽ Ð±Ð°Ð»Ð°Ð½ÑÑƒ\n\nÐ¦Ðµ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð³Ð°Ñ€Ð°Ð½Ñ‚ÑƒÑ”, Ñ‰Ð¾ Ñ Ð½Ð°Ð¹ÐºÑ€Ð°Ñ‰Ð¸Ð¹ Ð·Ð°Ñ…Ð¸Ñ‰ÐµÐ½Ð¸Ð¹ Ð²Ñ–Ð´ ÐºÐ¾ÑÐ¼Ñ–Ñ‡Ð½Ð¸Ñ… Ð·Ð°Ð³Ñ€Ð¾Ð·, Ð·Ð±ÐµÑ€Ñ–Ð³Ð°ÑŽÑ‡Ð¸ ÐµÑ„ÐµÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–.\n\nÐ— Ð¿Ð¸Ð»ÑŒÐ½Ñ–ÑÑ‚ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %3</t>
    <t id="3212">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¦Ñ–Ð»Ñ–ÑÐ½Ñ–ÑÑ‚ÑŒ Ð¼Ð¾Ð³Ð¾ ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ Ð²Ð¿Ð°Ð»Ð° Ð´Ð¾ %1%% (Ð¿Ð¾Ñ€Ñ–Ð³: %2%%), Ñ– Ð¼ÐµÐ½Ñ– Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ñ– Ð¿Ð¾ÑÐ»ÑƒÐ³Ð¸ Ð· Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ. ÐžÐ´Ð½Ð°Ðº Ð½Ð°Ð¹Ð±Ð»Ð¸Ð¶Ñ‡Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ Ð·Ð° Ð°Ð´Ñ€ÐµÑÐ¾ÑŽ %3 Ð½Ð°Ñ€Ð°Ð·Ñ– Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ñ‡ÐµÑ€ÐµÐ· Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿ÐµÑ€ÐµÑÑƒÐ²Ð°Ð½Ð½Ñ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ– (Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ).\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ²Ð°Ñ‚Ð¸Ð¼Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—, Ð½ÐµÐ·Ð²Ð°Ð¶Ð°ÑŽÑ‡Ð¸ Ð½Ð° Ñ†Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ. Ð©Ð¾Ð¹Ð½Ð¾ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ñ– Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð·Ð½Ð¾Ð²Ñƒ ÑÑ‚Ð°Ð½ÑƒÑ‚ÑŒ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ð¼Ð¸, Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð²ÐµÑ€Ð½ÑƒÑÑ Ð·Ð° Ð¿Ð¾ÑÐ»ÑƒÐ³Ð°Ð¼Ð¸ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ.\n\nÐ¯ ÑÑ‚ÐµÐ¶Ð¸Ñ‚Ð¸Ð¼Ñƒ Ð·Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ñ–Ñ”ÑŽ Ñ‚Ð° Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑÑ‚Ð¸Ð¼Ñƒ Ð²Ð°Ñ, ÐºÐ¾Ð»Ð¸ ÑÑ‚Ð°Ð½Ðµ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¸Ð¼ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %4</t>
    <t id="3213">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐœÐ¾Ñ” Ð·Ð°Ñ…Ð¸ÑÐ½Ðµ ÑÐ¿Ð¾Ñ€ÑÐ´Ð¶ÐµÐ½Ð½Ñ Ð¿Ð¾Ñ‚Ñ€ÐµÐ±ÑƒÑ” Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ, Ð°Ð»Ðµ Ð½Ð°Ð¹Ð±Ð»Ð¸Ð¶Ñ‡Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ ÑÐ¿Ð¾Ñ€ÑÐ´Ð¶ÐµÐ½Ð½Ñ Ð² %1 Ð½Ð°Ñ€Ð°Ð·Ñ– Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ñ‡ÐµÑ€ÐµÐ· Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿ÐµÑ€ÐµÑÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… (Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ).\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ²Ð°Ñ‚Ð¸Ð¼Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—, Ð½ÐµÐ·Ð²Ð°Ð¶Ð°ÑŽÑ‡Ð¸ Ð½Ð° Ñ†Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ. Ð©Ð¾Ð¹Ð½Ð¾ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ñ– Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð·Ð½Ð¾Ð²Ñƒ ÑÑ‚Ð°Ð½ÑƒÑ‚ÑŒ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ð¼Ð¸, Ñ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð²ÐµÑ€Ð½ÑƒÑÑ Ð·Ð° Ð¿Ð¾ÑÐ»ÑƒÐ³Ð°Ð¼Ð¸ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð·Ð°Ð¿Ð°ÑÑ–Ð².\n\nÐ¯ ÑÑ‚ÐµÐ¶Ð¸Ñ‚Ð¸Ð¼Ñƒ Ð·Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ñ–Ñ”ÑŽ Ñ‚Ð° Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ñ, ÐºÐ¾Ð»Ð¸ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ð½Ðµ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¸Ð¼.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %2</t>
    <t id="3208">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¯ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð² Ð²Ð¸Ñ‡ÐµÑ€Ð¿Ð½Ð¸Ð¹ Ð°Ð½Ð°Ð»Ñ–Ð· Ñ€Ð¸Ð½ÐºÑƒ %1 Ñ‚Ð° Ð½Ð°Ð²ÐºÐ¾Ð»Ð¸ÑˆÐ½Ñ–Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð² (Ñƒ Ð¼ÐµÐ¶Ð°Ñ… %2 ÑÑ‚Ñ€Ð¸Ð±ÐºÑ–Ð², Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ: %3 Cr), Ð°Ð»Ðµ, Ð½Ð° Ð¶Ð°Ð»ÑŒ, Ð½Ðµ Ð·Ð½Ð°Ð¹ÑˆÐ¾Ð² Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ð¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚ÐµÐ¹, ÑÐºÑ– Ð± Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð°Ð»Ð¸ Ð½Ð°ÑˆÐ¸Ð¼ Ð²Ð¸Ð¼Ð¾Ð³Ð°Ð¼.\n\nÐ—Ð’Ð†Ð¢ ÐŸÐ Ðž ÐÐÐÐ›Ð†Ð— Ð¢ÐžÐ Ð“Ð†Ð’Ð›Ð†:\nÐ—Ð°Ð³Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ñ†Ñ–Ð½ÐµÐ½Ð¸Ñ… Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚ÐµÐ¹: %4\n\nÐŸÐžÐ Ð£Ð¨Ð•ÐÐÐ¯ Ð’Ð†Ð”ÐœÐžÐ’Ð˜:\n- ÐžÐ±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð° ÑÑ‚Ð¸ÐºÑƒÐ²Ð°Ð½Ð½Ñ: %5 Ñ‚Ð¾Ñ€Ð³Ñ–Ð²\n (Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ Ð½Ðµ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑ” Ð¼Ñ–Ð¹ ÐºÐ»Ð°Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ)\n- ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½Ñ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ–ÑÑ‚ÑŒ: %6 Ñ‚Ð¾Ñ€Ð³Ñ–Ð²\n (ÐÐ¸Ð¶Ñ‡Ðµ Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ñƒ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ)\n- ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½Ñ–Ð¹ Ð¾Ð±ÑÑÐ³: %7 Ñ‚Ð¾Ñ€Ð³Ñ–Ð²\n (Ð½ÑƒÐ»ÑŒÐ¾Ð²Ð° Ð°Ð±Ð¾ Ð²Ñ–Ð´'Ñ”Ð¼Ð½Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ) ÑÑƒÐ¼Ð°)\n- ÐžÐ±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð±ÐµÐ·Ð¿ÐµÐºÐ¸: %8 ÑƒÐ³Ð¾Ð´\n (ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ Ð°Ð±Ð¾ Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ñ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸)\n\nÐ Ð•ÐšÐžÐœÐ•ÐÐ”ÐÐ¦Ð†Ð‡:\n- Ð Ð¾Ð·Ð³Ð»ÑÐ½ÑŒÑ‚Ðµ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ñ–ÑÑ‚ÑŒ ÐºÐ¾Ñ€Ð¸Ð³ÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ð¸Ñ… Ð·Ð½Ð°Ñ‡ÐµÐ½ÑŒ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ\n- Ð—Ð±Ñ–Ð»ÑŒÑˆÑ‚Ðµ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ñƒ Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–\n- ÐŸÐµÑ€ÐµÐ³Ð»ÑÐ½ÑŒÑ‚Ðµ Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð²\n- Ð—Ð°Ñ‡ÐµÐºÐ°Ð¹Ñ‚Ðµ, Ð´Ð¾ÐºÐ¸ Ñ€Ð¸Ð½ÐºÐ¾Ð²Ñ– ÑƒÐ¼Ð¾Ð²Ð¸ Ð¿Ð¾ÐºÑ€Ð°Ñ‰Ð°Ñ‚ÑŒÑÑ\n\nÐ¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶Ñƒ ÑÑ‚ÐµÐ¶Ð¸Ñ‚Ð¸ Ð·Ð° Ñ€Ð¸Ð½ÐºÐ¾Ð¼ Ñ– Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑÑ‚Ð¸Ð¼Ñƒ Ð²Ð°Ñ, ÐºÐ¾Ð»Ð¸ Ð·â€™ÑÐ²Ð»ÑÑ‚ÑŒÑÑ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ– Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚Ñ– Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ð¹.\n\nÐ§ÐµÐºÐ°ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ Ð²Ð°ÑˆÐ¾Ñ— ÑÐ»ÑƒÐ¶Ð±Ð¸</t>
    <t id="3209">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¢Ð•Ð ÐœÐ†ÐÐžÐ’Ð• ÐŸÐžÐŸÐ•Ð Ð•Ð”Ð–Ð•ÐÐÐ¯ ÐŸÐ Ðž ÐœÐÐ Ð¨Ð Ð£Ð¢\n\nÐœÐ¾Ñ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð¾Ð·Ð²Ñ–Ð´ÐºÐ¸ Ð¿Ñ€Ð¾ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ Ð²Ð¸ÑÐ²Ð¸Ð»Ð°, Ñ‰Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€ %1 (Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ %2) Ð·Ð°Ñ€Ð°Ð· Ð·Ð½Ð°Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒÑÑ Ð½Ð° Ð¼Ð¾Ñ”Ð¼Ñƒ Ð·Ð°Ð¿Ð»Ð°Ð½Ð¾Ð²Ð°Ð½Ð¾Ð¼Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð¼Ñƒ ÑˆÐ»ÑÑ…Ñƒ. Ð—Ð°Ñ€Ð°Ð´Ð¸ Ð±ÐµÐ·Ð¿ÐµÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ñ‚Ð° ÐµÐºÑ–Ð¿Ð°Ð¶Ñƒ Ñ Ð½ÐµÐ³Ð°Ð¹Ð½Ð¾ Ð¿Ñ€Ð¸Ð¿Ð¸Ð½ÑÑŽ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñƒ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–ÑŽ.\n\nÐ’Ð–Ð˜Ð¢Ð˜Ð¥ Ð—ÐÐ¥ÐžÐ”Ð†Ð’:\n- Ð£ÑÑ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ ÑÐºÐ°ÑÐ¾Ð²Ð°Ð½Ð¾\n- ÐŸÐ¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ Ð´Ð¾ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¶Ð¸Ð¼Ñƒ Ñ€Ð¾Ð±Ð¾Ñ‚Ð¸\n- Ð‘ÑƒÐ´Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾ Ð°Ð»ÑŒÑ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ð¸Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ ÑˆÐ»ÑÑ…, ÑÐºÐ¸Ð¹ ÑƒÐ½Ð¸ÐºÐ°Ñ” Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð²\n- ÐžÐ±Ñ€Ð¾Ð±ÐºÐ° Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ: ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð° (Ð±ÑƒÐ´Ðµ Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚Ð¸ Ð±ÑƒÐ´ÑŒ-ÑÐºÐ¸Ð¹ Ð²Ð°Ð½Ñ‚Ð°Ð¶ Ñƒ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾Ð¼Ñƒ Ð¼Ñ–ÑÑ†Ñ–, ÑÐºÑ‰Ð¾ Ñ†Ðµ Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¾)\n\nÐ¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ð´Ð¸Ð½Ð°Ð¼Ñ–Ñ‡Ð½Ð¾Ð³Ð¾ Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°Ñ‚Ð¸Ð¼Ðµ Ð¼Ð°Ð¹Ð±ÑƒÑ‚Ð½Ñ–Ð¼ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑÐ¼ Ñ‡ÐµÑ€ÐµÐ· Ñ†ÐµÐ¹ ÑÐµÐºÑ‚Ð¾Ñ€, Ð´Ð¾ÐºÐ¸ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð° Ð½Ðµ Ð·Ð½Ð¸ÐºÐ½Ðµ. Ð´Ð¾Ð·Ð²Ð¾Ð»ÐµÐ½Ð¾.\n\nÐ‘ÐµÐ·Ð¿ÐµÐºÐ° - Ð¼Ñ–Ð¹ Ð¿ÐµÑ€ÑˆÐ¾Ñ‡ÐµÑ€Ð³Ð¾Ð²Ð¸Ð¹ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚.\n\nÐ— Ð¿Ð¸Ð»ÑŒÐ½Ñ–ÑÑ‚ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %3</t>
    <t id="3210">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¨Ð›Ð¯Ð¥ Ð’Ð˜Ð¥ÐžÐ”Ð£ Ð†ÐÐ†Ð¦Ð†Ð®Ð’ÐÐÐž\n\nÐÐ°Ñ€Ð°Ð·Ñ– Ñ Ð¿ÐµÑ€ÐµÐ±ÑƒÐ²Ð°ÑŽ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñƒ %1 Ñ– Ð·Ð½Ð°Ð¹ÑˆÐ¾Ð² Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ ÑˆÐ»ÑÑ…, ÑÐºÐ¸Ð¹ Ð´Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚ÑŒ Ð¼ÐµÐ½Ñ– Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾ Ð²Ñ‚ÐµÐºÑ‚Ð¸.\n\nÐ¨Ð›Ð¯Ð¥ Ð¢ÐžÐ Ð“Ð†Ð’Ð›Ð†:\nÐšÑƒÐ¿Ð¸Ñ‚Ð¸: %2 (Ð¡ÐµÐºÑ‚Ð¾Ñ€: %3)\nÐŸÑ€Ð¾Ð´Ð°Ð²Ð°Ñ‚Ð¸: %4 (Ð¡ÐµÐºÑ‚Ð¾Ñ€: %5)\nÐ’Ð¸Ñ€Ñ–Ð±: %6 (x%7)\nÐžÑ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº: %8 Cr\n\nÐšÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ Ð²Ð¸Ð¹Ð´Ðµ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð° Ð¿Ñ–ÑÐ»Ñ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ñ†Ñ–Ñ”Ñ— Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐ”Ð¾ Ð²Ð°ÑˆÐ¸Ñ… Ð¿Ð¾ÑÐ»ÑƒÐ³</t>
    <t id="3211">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ†Ð—ÐžÐ›Ð¬ÐžÐ’ÐÐÐ˜Ð™ Ð Ð•Ð–Ð˜Ðœ Ð¢ÐžÐ Ð“Ð†Ð’Ð›Ð†\n\nÐ—Ð°Ñ€Ð°Ð· Ñ Ð¿ÐµÑ€ÐµÐ±ÑƒÐ²Ð°ÑŽ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ– %2, Ð°Ð»Ðµ Ð²ÑÑ– Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð´Ð¾ Ñ–Ð½ÑˆÐ¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð² Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ð¼Ð¸-Ñ…Ð°Ð±Ð°Ð¼Ð¸, ÑÐºÑ– Ð·Ð½Ð°Ñ…Ð¾Ð´ÑÑ‚ÑŒÑÑ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ. Ð¦Ðµ Ð¾Ð·Ð½Ð°Ñ‡Ð°Ñ”, Ñ‰Ð¾ Ñ Ð¼Ð¾Ð¶Ñƒ Ñ‚Ð¾Ñ€Ð³ÑƒÐ²Ð°Ñ‚Ð¸ Ð»Ð¸ÑˆÐµ Ð² Ð¼ÐµÐ¶Ð°Ñ… Ð¼Ð¾Ð³Ð¾ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¾Ð³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°, Ð´Ð¾ÐºÐ¸ Ð½Ðµ Ð·Ð¼Ñ–Ð½Ð¸Ñ‚ÑŒÑÑ ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ñ–Ñ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ.\n\nÐ¡Ð˜Ð¢Ð£ÐÐ¦Ð†Ð¯:\nÐŸÐ¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€: %2\nÐ¡Ñ‚Ð°Ñ‚ÑƒÑ: Ñ–Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¸Ð¹ (ÑÐµÐºÑ‚Ð¾Ñ€ Ð±ÐµÐ· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ Ñ–Ð· Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð°Ð¼Ð¸)\nÐ ÐµÐ¶Ð¸Ð¼ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–: Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð»Ð¸ÑˆÐµ Ð²ÑÐµÑ€ÐµÐ´Ð¸Ð½Ñ– ÑÐµÐºÑ‚Ð¾Ñ€Ð°\n\nÐœÐ¾Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ñ–Ð´ÐºÐ¾Ñ€Ð¸Ð³ÑƒÐ²Ð°Ð»Ð° Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ, Ñ‰Ð¾Ð± Ð²Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ñ‚Ð¸ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ñ… Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚ÐµÐ¹ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð²ÑÐµÑ€ÐµÐ´Ð¸Ð½Ñ– ÑÐµÐºÑ‚Ð¾Ñ€Ð°.\n\nÐ¯ Ð·Ñ€Ð¾Ð±Ð»ÑŽ Ñ†Ðµ. Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ¹Ñ‚Ðµ ÑÑ‚ÐµÐ¶Ð¸Ñ‚Ð¸ Ð·Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ñ–Ñ”ÑŽ Ñ‚Ð° Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑÐ¹Ñ‚Ðµ, ÑÐºÑ‰Ð¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð·Ð½Ð¾Ð²Ñƒ ÑÑ‚Ð°Ð½ÑƒÑ‚ÑŒ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ð¼Ð¸.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %1</t>
    <t id="3218">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ’Ð˜Ð¯Ð’Ð›Ð•ÐÐž Ð—ÐœÐ†ÐÐ£ Ð¨Ð›Ð¯Ð¥Ð£ ÐœÐÐ Ð¨Ð Ð£Ð¢Ð£\n\nÐŸÑ–ÑÐ»Ñ Ð²Ñ…Ð¾Ð´Ñƒ Ð² ÑÐµÐºÑ‚Ð¾Ñ€ %1 Ð¼Ð¾Ñ Ð½Ð°Ð²Ñ–Ð³Ð°Ñ†Ñ–Ð¹Ð½Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð²Ð¸ÑÐ²Ð¸Ð»Ð°, Ñ‰Ð¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ð´Ð¾ Ð¼Ð¾Ð³Ð¾ Ð¼Ñ–ÑÑ†Ñ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ %2 (%3) Ð·Ð¼Ñ–Ð½Ð¸Ð²ÑÑ.\n\nÐÐÐÐ›Ð†Ð— Ð¨Ð›Ð¯Ð¥Ð£:\n- ÐÐ¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ: %4 ÑÑ‚Ñ€Ð¸Ð±ÐºÑ–Ð²\n- Ð’Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ñ–Ð· Ð·Ð°Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½ÑÐ¼ Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ: %5\n- Ð¡Ñ‚Ð°Ñ‚ÑƒÑ: %6\n\nÐœÑ–Ð¹ Ð½Ð°Ð²Ñ–Ð³Ð°Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ ÐºÐ¾Ð¼Ð¿â€™ÑŽÑ‚ÐµÑ€ Ð²ÐºÐ°Ð·ÑƒÑ”, Ñ‰Ð¾ Ð±Ð°Ð¶Ð°Ð½Ð¸Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð½Ðµ Ð´Ñ–Ñ” Ñ‡ÐµÑ€ÐµÐ· Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ñ€ÑƒÑ…Ñƒ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ–. Ð—Ð°Ñ€Ð°Ð´Ð¸ Ð±ÐµÐ·Ð¿ÐµÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ñ‚Ð° ÐµÐºÑ–Ð¿Ð°Ð¶Ñƒ Ñ Ð½ÐµÐ³Ð°Ð¹Ð½Ð¾ Ð¿Ñ€Ð¸Ð¿Ð¸Ð½ÑÑŽ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñƒ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–ÑŽ.\n\nÐ’Ð–Ð˜Ð¢Ð˜Ð¥ Ð—ÐÐ¥ÐžÐ”Ð†Ð’:\n- Ð£ÑÑ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ ÑÐºÐ°ÑÐ¾Ð²Ð°Ð½Ð¾\n- ÐŸÐ¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ Ð´Ð¾ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¶Ð¸Ð¼Ñƒ Ñ€Ð¾Ð±Ð¾Ñ‚Ð¸\n- Ð‘ÑƒÐ´Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾ Ð°Ð»ÑŒÑ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ð¸Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚, ÑÐºÐ¸Ð¹ ÑƒÐ½Ð¸ÐºÐ°Ñ‚Ð¸Ð¼Ðµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð²\n- ÐžÐ±Ñ€Ð¾Ð±ÐºÐ° Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ: ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð° (Ð¿Ñ€Ð¾Ð´Ð°ÑÑ‚ÑŒ Ð±ÑƒÐ´ÑŒ-ÑÐºÐ¸Ð¹ Ð²Ð°Ð½Ñ‚Ð°Ð¶ Ñƒ Ð±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾Ð¼Ñƒ Ð¼Ñ–ÑÑ†Ñ–, ÑÐºÑ‰Ð¾ Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ð¾)\n\nÐœÐ¾Ñ Ð½Ð°Ð²Ñ–Ð³Ð°Ñ†Ñ–Ð¹Ð½Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ ÑƒÐ½Ð¸ÐºÐ°Ñ‚Ð¸Ð¼Ðµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð² Ñƒ Ð¼Ð°Ð¹Ð±ÑƒÑ‚Ð½ÑŒÐ¾Ð¼Ñƒ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ– Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð½Ð½Ñ.\n\nÐ‘ÐµÐ·Ð¿ÐµÐºÐ° - Ð¼Ñ–Ð¹ Ð¿ÐµÑ€ÑˆÐ¾Ñ‡ÐµÑ€Ð³Ð¾Ð²Ð¸Ð¹ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚.\n\nÐ— Ð¿Ð¸Ð»ÑŒÐ½Ñ–ÑÑ‚ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %7</t>
    <t id="3219">Ð¡ÐµÐºÑ‚Ð¾Ñ€ %1 Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½Ð¾ - ÑƒÑÑ– Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ ÑƒÑÑƒÐ½ÐµÐ½Ð¾</t>
    <t id="3220">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ’ÐžÐ ÐžÐ–Ð˜Ð™ ÐšÐžÐ ÐÐ‘Ð•Ð›Ð¬ Ð’Ð¢Ð†Ðš\n\nÐÐ°ÑˆÐ° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð¾Ð·Ð²Ñ–Ð´ÐºÐ¸ Ð¿Ñ€Ð¾ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ Ð²Ñ‚Ñ€Ð°Ñ‚Ð¸Ð»Ð° ÑÐ»Ñ–Ð´ Ð²Ð¾Ñ€Ð¾Ð¶Ð¾Ð³Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ %3, ÑÐºÐ¸Ð¹ Ð²Ñ‚Ñ–Ðº Ñ–Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñƒ %1.\n\nÐ”Ð•Ð¢ÐÐ›Ð†:\n- Ð’Ñ‚ÐµÑ‡Ðµ ÑÑƒÐ´Ð½Ð¾: %3\n- Ð¡ÐµÐºÑ‚Ð¾Ñ€ Ð»Ñ–Ð²Ð¾Ñ€ÑƒÑ‡: %1\n- ÐŸÑƒÐ½ÐºÑ‚ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¡ÐµÐºÑ‚Ð¾Ñ€: %2\n- Ð¡Ñ‚Ð°Ñ‚ÑƒÑ: Ð²Ñ–Ð´ÑÑ‚ÐµÐ¶ÐµÐ½Ð½Ñ Ð²Ñ‚Ñ€Ð°Ñ‡ÐµÐ½Ð¾ - ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ Ð¿Ð¾ÐºÐ¸Ð½ÑƒÐ² Ð½Ð°ÑˆÑƒ ÐºÐ¾Ð½Ñ‚Ñ€Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ñƒ Ð·Ð¾Ð½Ñƒ\n\nÐ¥Ð¾Ñ‡Ð° Ñ†Ðµ ÑÑƒÐ´Ð½Ð¾ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð½Ðµ ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚ÑŒ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ– %1, Ð¼Ð¸ Ð²Ñ‚Ñ€Ð°Ñ‚Ð¸Ð»Ð¸ Ð²Ñ–Ð·ÑƒÐ°Ð»ÑŒÐ½Ð¸Ð¹ ÐºÐ¾Ð½Ñ‚Ð°ÐºÑ‚ Ñ– Ð½Ðµ Ð¼Ð¾Ð¶ÐµÐ¼Ð¾ Ð¿Ñ–Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¸Ñ‚Ð¸ Ð¹Ð¾Ð³Ð¾ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ ÑÑ‚Ð°Ñ‚ÑƒÑ Ð°Ð±Ð¾ Ð½Ð°Ð¼Ñ–Ñ€Ð¸ Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ– %2.\n\nÐÐ°ÑˆÑ– ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸ Ð²Ñ–Ð´ÑÑ‚ÐµÐ¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ²Ð°Ñ‚Ð¸Ð¼ÑƒÑ‚ÑŒ Ð²Ñ–Ð´ÑÑ‚ÐµÐ¶ÑƒÐ²Ð°Ñ‚Ð¸ ÑÐµÐºÑ‚Ð¾Ñ€ %1 Ð½Ð° Ð½Ð°ÑÐ²Ð½Ñ–ÑÑ‚ÑŒ Ð·Ð°Ð³Ñ€Ð¾Ð·, Ñ‰Ð¾ Ð·Ð°Ð»Ð¸ÑˆÐ¸Ð»Ð¸ÑÑ. Ð¯ÐºÑ‰Ð¾ Ð²ÑÑ– Ð²Ñ–Ð´ÑÑ‚ÐµÐ¶ÑƒÐ²Ð°Ð½Ñ– Ð²Ð¾Ñ€Ð¾Ð³Ð¸ Ð¿Ñ–Ð´ÑƒÑ‚ÑŒ Ð°Ð±Ð¾ Ð±ÑƒÐ´ÑƒÑ‚ÑŒ Ð·Ð½Ð¸Ñ‰ÐµÐ½Ñ–, ÑÐµÐºÑ‚Ð¾Ñ€ Ð±ÑƒÐ´Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½Ð¾ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ.\n\nÐ— Ð¿Ð¸Ð»ÑŒÐ½Ñ–ÑÑ‚ÑŽ\nThreat Intelligence System</t>
    <t id="3221">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÐ¼ÐµÐ½Ñ– Ð½Ðµ Ð²Ð´Ð°Ð»Ð¾ÑÑ Ð·Ð½Ð°Ð¹Ñ‚Ð¸ Ð²Ð¸Ð³Ñ–Ð´Ð½Ñ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚Ñ– Ð½Ð° Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑÑ… (Ð´Ð¾ %3 ÑÑ‚Ñ€Ð¸Ð±ÐºÑ–Ð²), Ð¾ÑÐºÑ–Ð»ÑŒÐºÐ¸ Ñ†Ñ– Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸ Ð½Ð°Ñ€Ð°Ð·Ñ– Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ– Ñ‡ÐµÑ€ÐµÐ· Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿ÐµÑ€ÐµÑÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… (ÑˆÐ»ÑÑ…Ð¸ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ).\n\nÐ¡Ð˜Ð¢Ð£ÐÐ¦Ð†Ð¯:\nÐŸÐ¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€: %2\nÐŸÐ¾Ñ‡Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ð¹ Ð´Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½ Ð¿Ð¾ÑˆÑƒÐºÑƒ: %3 ÑÑ‚Ñ€Ð¸Ð±ÐºÑ–Ð²\nÐ”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ Ð¿Ð¾ÑˆÑƒÐºÑƒ: %4 Ñ‚Ñ€Ð°Ð¼Ð¿Ð»Ñ–Ð½Ñ–Ð²\n\nÐ¢ÐµÐ¿ÐµÑ€ Ñ Ð·Ð¾ÑÐµÑ€ÐµÐ´Ð¶ÑƒÑÑ Ð½Ð° Ð´Ð¾Ð²ÐºÐ¾Ð»Ð¸ÑˆÐ½Ñ–Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ñƒ Ð¼ÐµÐ¶Ð°Ñ… %4 Ñ‚Ñ€Ð°Ð¼Ð¿Ð»Ñ–Ð½Ñ–Ð², Ð´Ðµ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ð¸, ÑˆÐ²Ð¸Ð´ÑˆÐµ Ð·Ð° Ð²ÑÐµ, Ð±ÑƒÐ´ÑƒÑ‚ÑŒ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ–. Ð¦Ðµ Ð¼Ð°Ñ” Ð´Ð¾Ð¿Ð¾Ð¼Ð¾Ð³Ñ‚Ð¸ Ð¼ÐµÐ½Ñ– Ð·Ð½Ð°Ð¹Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ– ÑƒÐ³Ð¾Ð´Ð¸, ÑÐºÑ– Ñ€Ð°Ð½Ñ–ÑˆÐµ Ð±ÑƒÐ»Ð¸ Ð²Ñ–Ð´Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ð¾Ð²Ð°Ð½Ñ– Ñ‡ÐµÑ€ÐµÐ· Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð²Ñ–Ð´ÑÑ‚Ð°Ð½Ñ–, Ð° Ð½Ðµ Ñ„Ð°ÐºÑ‚Ð¸Ñ‡Ð½Ñƒ Ð·Ð±Ð¸Ñ‚ÐºÐ¾Ð²Ñ–ÑÑ‚ÑŒ.\n\nÐ¯ Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÑŽ Ð²Ð°Ð¼, ÐºÐ¾Ð»Ð¸ Ð·Ð½Ð°Ð¹Ð´Ñƒ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ñ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚Ñ– Ð¿Ð¾Ð±Ð»Ð¸Ð·Ñƒ.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %1</t>
    <t id="3222">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€,\n\nÐ¡Ð•ÐšÐ¢ÐžÐ  Ð£ Ð§ÐžÐ ÐÐžÐœÐ£ Ð¡ÐŸÐ˜Ð¡ÐšÐ£\n\nÐÐ°ÑˆÐ° ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ñ€Ð¾Ð·Ð²Ñ–Ð´ÐºÐ¸ Ð¿Ñ€Ð¾ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ Ð²Ð¸ÑÐ²Ð¸Ð»Ð° Ð²Ð¾Ñ€Ð¾Ð¶Ñƒ Ð°ÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñ– %1 Ñ‚Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ð½ÐµÑÐ»Ð° Ñ†ÐµÐ¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ñƒ Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº, Ñ‰Ð¾Ð± Ð·Ð°Ñ…Ð¸ÑÑ‚Ð¸Ñ‚Ð¸ Ð½Ð°ÑˆÑ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—.\n\nÐ’Ð˜Ð¯Ð’Ð›Ð•ÐÐž Ð’ÐžÐ ÐžÐ–ÐÐ† ÐšÐžÐ ÐÐ‘Ð›Ð†:\n%2\n\nÐ’Ð˜Ð¯Ð’Ð›Ð•ÐÐž: %3\n\nÐ”Ð»Ñ Ð±ÐµÐ·Ð¿ÐµÐºÐ¸ Ð½Ð°ÑˆÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ñ– ÐµÐºÑ–Ð¿Ð°Ð¶Ñƒ, ÑƒÑÑ– Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– ÑˆÐ»ÑÑ…Ð¸ Ñ‡ÐµÑ€ÐµÐ· Ñ†ÐµÐ¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ð±ÑƒÐ»Ð¸ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ñ–. ÐÐ°ÑˆÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¾Ð±Ñ…Ð¾Ð´ÑÑ‚ÑŒ Ñ†ÐµÐ¹ ÑÐµÐºÑ‚Ð¾Ñ€, Ð´Ð¾ÐºÐ¸ Ð·Ð°Ð³Ñ€Ð¾Ð·Ñƒ Ð½Ðµ Ð±ÑƒÐ´Ðµ ÑƒÑÑƒÐ½ÐµÐ½Ð¾.\n\nÐ¡ÐµÐºÑ‚Ð¾Ñ€ Ð±ÑƒÐ´Ðµ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ð¸Ð´Ð°Ð»ÐµÐ½Ð¾ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ, ÐºÐ¾Ð»Ð¸ Ð²ÑÑ– Ð²Ñ–Ð´ÑÑ‚ÐµÐ¶ÑƒÐ²Ð°Ð½Ñ– Ð²Ð¾Ñ€Ð¾Ð¶Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð±ÑƒÐ´ÑƒÑ‚ÑŒ ÑƒÑÑƒÐ½ÐµÐ½Ñ– Ð°Ð±Ð¾ Ð¿Ð¾ÐºÐ¸Ð½ÑƒÑ‚ÑŒ Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ñ–ÑŽ.\n\nÐ— Ð¿Ð¸Ð»ÑŒÐ½Ñ–ÑÑ‚ÑŽ,\nThreat Intelligence System</t>
    <t id="3223">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ,\n\nÑ Ð½Ðµ Ð¼Ð¾Ð¶Ñƒ Ð·Ð½Ð°Ð¹Ñ‚Ð¸ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñƒ Ñ‚Ñ€ÐµÐ½ÑƒÐ²Ð°Ð»ÑŒÐ½Ñƒ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ…Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ Ñ–ÑÐ¿Ð¸Ñ‚Ñƒ Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÐµÐ½Ð½Ñ Ñ€Ñ–Ð²Ð½Ñ %1. Ð¯ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶Ñƒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ— Ð·Ð³Ñ–Ð´Ð½Ð¾ Ð· Ñ–Ð½ÑÑ‚Ñ€ÑƒÐºÑ†Ñ–ÑÐ¼Ð¸, Ð°Ð»Ðµ Ñ Ñ€Ð¾Ð·ÑƒÐ¼Ñ–ÑŽ, Ñ‰Ð¾ Ñ Ð½Ðµ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°ÑŽ Ð±Ð°Ð»Ð¸ Ð´Ð¾ÑÐ²Ñ–Ð´Ñƒ, Ð´Ð¾ÐºÐ¸ Ð½Ðµ Ð¿Ñ€Ð¾Ð¹Ð´Ñƒ Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ðµ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ. ÐŸÑ–ÑÐ»Ñ Ñ†ÑŒÐ¾Ð³Ð¾ Ð¾Ð±Ð¼Ñ–Ð½Ñƒ Ñ Ð·Ð½Ð¾Ð²Ñƒ ÑˆÑƒÐºÐ°Ñ‚Ð¸Ð¼Ñƒ Ð±ÑƒÐ´ÑŒ-ÑÐºÑƒ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ñƒ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ñ–ÑÑ‚ÑŒ Ñ‚Ñ€ÐµÐ½ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ.\n\nÐ— Ð¿Ð¾Ð²Ð°Ð³Ð¾ÑŽ,\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %2</t>
    <t id="3224">Ð’Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ Ð»Ñ–Ñ†ÐµÐ½Ð·Ñ–Ñ— Ð½Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ: %1 Cr</t>
    <t id="3225">Ð‘Ð¾Ð½ÑƒÑ: Ñ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ð² %1 Ð´Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº%2 Ð·Ð°Ð²Ð´ÑÐºÐ¸ Ð½Ð°ÐºÐ¾Ð¿Ð¸Ñ‡ÐµÐ½Ð¾Ð¼Ñƒ Ð´Ð¾ÑÐ²Ñ–Ð´Ñƒ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ! ÐŸÐ¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ: %3</t>
    <t id="3214">Ð¦Ðµ Ñ‡ÐµÑÑ‚ÑŒ Ð¿Ñ€Ð°Ñ†ÑŽÐ²Ð°Ñ‚Ð¸ Ð´Ð»Ñ Ð²Ð°Ñ, %1! Ð¯ Ñ€Ð°Ð´Ð¸Ð¹ Ñ€Ð¾Ð·Ð¿Ð¾Ñ‡Ð°Ñ‚Ð¸ ÑÐ²Ð¾ÑŽ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€ÑÑŒÐºÑƒ ÐºÐ°Ñ€â€™Ñ”Ñ€Ñƒ Ð¿Ñ–Ð´ Ð²Ð°ÑˆÐ¸Ð¼ ÐºÐµÑ€Ñ–Ð²Ð½Ð¸Ñ†Ñ‚Ð²Ð¾Ð¼. Ð¯ Ð´Ð¾ÐºÐ»Ð°Ð´Ñƒ Ð²ÑÑ–Ñ… Ð·ÑƒÑÐ¸Ð»ÑŒ, Ñ‰Ð¾Ð± Ð´Ð¾Ð±Ñ€Ðµ ÑÐ»ÑƒÐ¶Ð¸Ñ‚Ð¸ Ð²Ð°Ð¼ Ñ– ÑÐ¿Ñ€Ð¸ÑÑ‚Ð¸ Ð²Ð°ÑˆÐ¾Ð¼Ñƒ ÑƒÑÐ¿Ñ–Ñ…Ñƒ.</t>
    <t id="3215">Ð”ÑÐºÑƒÑŽ, Ñ‰Ð¾ Ð´Ð°Ñ€ÑƒÑ”Ñ‚Ðµ Ð¼ÐµÐ½Ñ– Ñ†ÑŽ Ð·Ð°ÑÐ»ÑƒÐ¶ÐµÐ½Ñƒ Ð²Ñ–Ð´Ð¿ÑƒÑÑ‚ÐºÑƒ, %1! Ð¯ Ð½Ð°ÑÐ¾Ð»Ð¾Ð´Ð¶ÑƒÐ²Ð°Ð²ÑÑ Ñ‡Ð°ÑÐ¾Ð¼, Ð¿Ñ€Ð¾Ð²ÐµÐ´ÐµÐ½Ð¸Ð¼ Ð´Ð°Ð»ÐµÐºÐ¾ Ð²Ñ–Ð´ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–, Ñ– Ð¼Ð¾Ñ— Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ¸ Ð·Ð°Ð»Ð¸ÑˆÐ°ÑŽÑ‚ÑŒÑÑ Ð½ÐµÐ·Ð¼Ñ–Ð½Ð½Ð¸Ð¼Ð¸. Ð¯ Ð· Ð½ÐµÑ‚ÐµÑ€Ð¿Ñ–Ð½Ð½ÑÐ¼ Ñ‡ÐµÐºÐ°ÑŽ Ð¿Ð¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ Ð´Ð¾ Ñ€Ð¾Ð±Ð¾Ñ‚Ð¸, ÐºÐ¾Ð»Ð¸ Ñ Ð²Ð°Ð¼ Ð·Ð½Ð°Ð´Ð¾Ð±Ð»ÑŽÑÑŒ. Ð”Ð¾ Ñ‚Ð¾Ð³Ð¾ Ñ‡Ð°ÑÑƒ Ñ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ñ‚Ð¸Ð¼Ñƒ ÑÐ²Ð¾Ñ— Ð·Ð½Ð°Ð½Ð½Ñ Ð² Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–!</t>
    <t id="3216">Ð¯ Ð¿Ð¾Ð²ÐµÑ€Ð½ÑƒÐ²ÑÑ Ð· Ð²Ñ–Ð´Ð¿ÑƒÑÑ‚ÐºÐ¸ Ñ– Ð·Ð½Ð¾Ð²Ñƒ Ð³Ð¾Ñ‚Ð¾Ð²Ð¸Ð¹ Ð¿Ñ€Ð°Ñ†ÑŽÐ²Ð°Ñ‚Ð¸, %1! ÐœÐ¾Ñ— Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð·Ð°Ð»Ð¸ÑˆÐ°ÑŽÑ‚ÑŒÑÑ Ð²Ð¸ÑÐ¾ÐºÐ¸Ð¼Ð¸, Ñ– Ñ Ð³Ð¾Ñ‚Ð¾Ð²Ð¸Ð¹ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ²Ð°Ñ‚Ð¸ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸ Ð²Ð°Ñ Ð½Ð° %2. Ð”ÑÐºÑƒÑ”Ð¼Ð¾ Ð·Ð° Ð·Ð°ÑÐ»ÑƒÐ¶ÐµÐ½Ð¸Ð¹ Ð²Ñ–Ð´Ð¿Ð¾Ñ‡Ð¸Ð½Ð¾Ðº!</t>
    <t id="3217">Ð”ÑÐºÑƒÑŽ Ð·Ð° Ð¼Ñ–Ð¹ Ð¿ÐµÑ€ÐµÑ…Ñ–Ð´ Ð´Ð¾ %1, %2! Ð¦Ðµ Ð½Ð¾Ð²Ðµ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð»Ñ Ð¼ÐµÐ½Ðµ Ð²ÐµÐ»Ð¸ÐºÐ° Ñ‡ÐµÑÑ‚ÑŒ, Ñ– Ñ Ð±ÑƒÐ´Ñƒ Ñ‡ÑƒÐ´Ð¾Ð²Ð¾ Ð¿Ñ–ÐºÐ»ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð¿Ñ€Ð¾ ÑÐ²Ñ–Ð¹ Ð½Ð¾Ð²Ð¸Ð¹ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ. ÐœÑ–Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ Ð´Ð¾ÑÐ²Ñ–Ð´ Ñ– Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ¸ Ð·Ð°Ð»Ð¸ÑˆÐ°ÑŽÑ‚ÑŒÑÑ Ð½ÐµÐ·Ð¼Ñ–Ð½Ð½Ð¸Ð¼Ð¸, Ñ– Ñ Ð³Ð¾Ñ‚Ð¾Ð²Ð¸Ð¹ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ²Ð°Ñ‚Ð¸ Ð²Ð°Ð¼ ÑÐ»ÑƒÐ¶Ð¸Ñ‚Ð¸.</t>
    <t id="3227">ÐšÐ¾Ñ€Ð¿ÑƒÑ Ð²Ñ‚Ñ€Ð°Ñ‡ÐµÐ½Ð¾, Ð³Ñ–Ð´Ð½Ñ–ÑÑ‚ÑŒ Ñ‡ÐµÐºÐ°Ñ” Ð½Ð° Ð¿Ñ–Ð´Ð±Ñ–Ñ€</t>
    <t id="3228">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ %1,\n\n%2 Ð´Ð¾Ð¿Ð¾Ð²Ñ–Ð´Ð°Ñ” Ð· %3. ÐœÑ–Ð¹ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ Ð²Ð¸Ð±ÑƒÑ…Ð½ÑƒÐ². Ð¯ - Ð½Ñ–. Ð¢ÐµÐ¿ÐµÑ€ Ñ Ð½Ð°Ð¹Ð´Ð¾Ñ€Ð¾Ð¶Ñ‡Ð¸Ð¹ Ð¿Ð»Ð°Ð²ÑƒÑ‡Ð¸Ð¹ Ð²Ð°Ð½Ñ‚Ð°Ð¶ Ñ„Ð»Ð¾Ñ‚Ñƒ.\n\nÐœÑ–Ñ‚ÐºÑƒ Ð½Ð° ÐºÐ°Ñ€Ñ‚Ñ– Ð´Ð¾Ð´Ð°Ð½Ð¾. Ð‘ÑƒÐ´ÑŒ Ð»Ð°ÑÐºÐ°, Ð¿Ð¾ÑÐ¿Ñ–ÑˆÑ–Ñ‚ÑŒ - Ñ Ð±ÑƒÐ² Ð¿Ð¾ÑÐµÑ€ÐµÐ´ Ñ€Ð°Ñ…ÑƒÐ½ÐºÑƒ.\n\nÐŸÑ€Ð¾Ñ„ÐµÑÑ–Ð¹Ð½Ð¾ Ð¿Ð»Ð°Ð²ÑƒÑŽ,\n%2</t>
    <t id="3229">ÐŸÑ–Ð»Ð¾Ñ‚Ð° Ð²Ñ€ÑÑ‚Ð¾Ð²Ð°Ð½Ð¾ - Ð·Ð°Ð»ÐµÐ¶Ð½Ñ–ÑÑ‚ÑŒ Ð²Ñ–Ð´ ÐºÐ¸ÑÐ½ÑŽ Ð²Ð¸Ð»Ñ–ÐºÐ¾Ð²Ð°Ð½Ð°</t>
    <t id="3230">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ðµ %1,\n\nÐžÐ½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ: %2 Ð¿Ñ–Ð´Ñ–Ð±Ñ€Ð°Ð½Ð¾ %3 (%4) Ñ– Ð¿Ñ€Ð¸Ð¿Ð¸Ð½ÐµÐ½Ð¾ Ð²Ð¸ÑÑ‚Ð°Ð²Ð»ÑÑ‚Ð¸ Ñ€Ð°Ñ…ÑƒÐ½ÐºÐ¸ Ð·Ð° Ð¿Ð¾Ð´Ð¾Ð²Ð¶ÐµÐ½Ðµ EVA-Ñ‚Ñ€ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ.\n\nÐŸÑ€Ð¸Ð²'ÑÐ·ÐºÑƒ Ñ€ÐµÑ”ÑÑ‚Ñ€Ñƒ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾. Ð ÐµÐºÐ¾Ð¼ÐµÐ½Ð´Ð°Ñ†Ñ–Ñ: Ð½Ðµ Ð¿Ð¸Ñ‚Ð°Ñ‚Ð¸ Ð¿Ñ€Ð¾ ÑÑ‚Ð°Ñ€Ð¸Ð¹ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ.\n\nÐ¡Ð¾Ñ€Ð¾Ð¼'ÑÐ·Ð»Ð¸Ð²Ð¾ Ð²Ð°Ñˆ,\n%2</t>
<t id="4000">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ: %s Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¾ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s</t>
    <t id="4001">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ: Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð¿Ð¾Ð²Ð½Ñ–ÑÑ‚ÑŽ</t>
    <t id="4002">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ: %s Ð´Ð¾Ð·Ð²Ð¾Ð»Ð¸Ð² Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚ %s</t>
    <t id="5000">%s Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¾ Ð¾ÑÐ½Ð¾Ð²Ð½Ð¾ÑŽ Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ñ–Ñ”ÑŽ Ð´Ð»Ñ %s</t>
    <t id="5001">%s Ð´Ð¾ÑÑÐ³ Ñ€Ñ–Ð²Ð½Ñ Ð·Ð½Ð°Ð½ÑŒ %s Ñƒ %s!</t>
    <t id="5002">Ð¢ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ñ–Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð±Ð¾Ð½ÑƒÑ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²Ð°Ð½Ð¾: Ð·Ð±Ñ–Ð»ÑŒÑˆÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ Ð½Ð° %s%% Ñƒ %s</t>
    <t id="9500">ÐŸÐ¾Ð¼Ð¸Ð»ÐºÐ°: %s Ð·Ð°ÑÑ‚Ñ€ÑÐ³ Ñ– Ð¿Ð¾Ñ‚Ñ€ÐµÐ±ÑƒÑ” Ð´Ð¾Ð¿Ð¾Ð¼Ð¾Ð³Ð¸!</t>
    <t id="9501">ÐŸÐ¾Ð¼Ð¸Ð»ÐºÐ°: Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð½Ðµ Ð²Ð´Ð°Ð»Ð°ÑÑ Ð´Ð»Ñ %s</t>
    <t id="9502">ÐŸÐ¾Ð¼Ð¸Ð»ÐºÐ°: Ð½ÐµÐ¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ Ð·Ð°Ñ€ÐµÑ”ÑÑ‚Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ %s Ð² GalaxyTrader MK3</t>
    <t id="80001">ÐŸÐ¾ÑÑƒÐ´ %s Ð´Ð¾Ð´Ð°Ð½Ð¾ Ð´Ð¾ Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ</t>
    <t id="80002">Ð’Ð¸Ñ€Ñ–Ð± %s Ð²Ð¸Ð´Ð°Ð»ÐµÐ½Ð¾ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ</t>
    <t id="80003">ÐŸÐ¾ÑÑƒÐ´ %s Ð´Ð¾Ð´Ð°Ð½Ð¾ Ð´Ð¾ Ð±Ñ–Ð»Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ</t>
    <t id="80004">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ð½ÐµÑÐµÐ½Ð¾ Ð² Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº (Ð½Ð¸Ð·ÑŒÐºÐ° Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ): %s</t>
    <t id="80005">ÐŸÑ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¾Ð³Ð¾ Ð¿Ð¾ÑÑƒÐ´Ñƒ: %s</t>
    <t id="80006">Ð¤Ñ–Ð»ÑŒÑ‚Ñ€ Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð²: %s Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¸Ð¹, %s Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð°</t>
    <t id="80007">Ð£ÑÑ– Ð¿Ð¾ÑÑƒÐ´Ð¾Ð²Ñ– Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ð¸ Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½Ñ–</t>
    <t id="80008">Ð¤Ñ–Ð»ÑŒÑ‚Ñ€Ð¸ Ð¿Ð¾ÑÑƒÐ´Ñƒ ÑÐºÐ¸Ð½ÑƒÑ‚Ñ– Ð´Ð¾ ÑÑ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ð¸Ñ…</t>
    <t id="80009">ÐšÐµÑ€ÑƒÐ²Ð°Ð½Ð½Ñ Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ð°Ð¼Ð¸ Ð¿Ð¾ÑÑƒÐ´Ñƒ</t>
    <t id="80010">Ð—Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="80011">Ð”Ð¾Ð·Ð²Ð¾Ð»ÐµÐ½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="80012">ÐŸÐ¾Ð²Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ Ð· Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¸Ð¼ Ð¿Ð¾ÑÑƒÐ´Ð¾Ð¼</t>
    <t id="80013">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ Ñ‚Ð¾Ð²Ð°Ñ€Ñƒ</t>
    <t id="80014">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ Ð¿Ð¾ÑÑƒÐ´Ñƒ</t>
    <t id="80015">ÐžÐ±Ð¼ÐµÐ¶ÐµÐ½Ñ– Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ—</t>
    <t id="80016">ÐšÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ñ–Ñ— Ð¿Ð¾ÑÑƒÐ´Ñƒ Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾ Ð· Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ Ð³Ñ€Ð¸</t>
    <t id="80017">%s Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² Ð·Ð° ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ñ–ÑÐ¼Ð¸: %s Ð½Ð¸Ð·ÑŒÐºÐ¾Ñ— Ð²Ð°Ñ€Ñ‚Ð¾ÑÑ‚Ñ–, %s Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¸Ñ…, %s Ð²Ð¸ÑÐ¾ÐºÐ¾Ñ— Ð²Ð°Ñ€Ñ‚Ð¾ÑÑ‚Ñ–</t>
    <t id="80018">Ð£Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾ Ð´Ð¸Ð½Ð°Ð¼Ñ–Ñ‡Ð½Ñƒ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ñ–ÑŽ Ð¿Ð¾ÑÑƒÐ´Ñƒ</t>
    <t id="80019">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¸Ð¹ Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº Ð´Ð»Ñ ÐºÐ°Ñ‚ÐµÐ³Ð¾Ñ€Ñ–Ñ— %s Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾</t>
    <t id="80020">Ð’Ð¸ÑÐ²Ð»ÐµÐ½Ð¾ Ñ‚Ð° ÐºÐ»Ð°ÑÐ¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¾ Ð½Ð¾Ð²Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð· Ñ–Ð½ÑˆÐ¸Ñ… Ð¼Ð¾Ð´Ñ–Ð²</t>
    <t id="9000">GalaxyTrader - Ð³Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ– Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ</t>
    <t id="9010">XP Ñ– ÑÐ¸ÑÑ‚ÐµÐ¼Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="9012">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="9013">ÐœÐ½Ð¾Ð¶Ð½Ð¸Ðº XP</t>
    <t id="9015">Ð’Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð¿Ñ€ÐµÐ¼Ñ–Ñ— ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°</t>
    <t id="9020">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ</t>
    <t id="9021">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–ÑŽ Ñ„Ð»Ð¾Ñ‚Ñƒ</t>
    <t id="9023">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Trade Cache</t>
    <t id="9030">Ð¡Ð¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ</t>
    <t id="9031">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ</t>
    <t id="9040">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ</t>
    <t id="9041">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ</t>
    <t id="9042">ÐŸÐ¾Ñ€Ñ–Ð³ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ</t>
    <t id="9310">Ð“Ð°Ð»Ð°ÐºÑ‚Ð¸ÐºÐ°-Ð¨Ð°Ñ…Ñ‚Ð°Ñ€</t>
    <t id="9311">ÐžÑ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ ÑÐºÐ°Ð½ÑƒÐ²Ð°Ð½Ð½Ñ Ð·Ð¾Ð½Ð´Ñ–Ð² Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñ–</t>
    <t id="9312">Ð’Ð°Ð³Ð° Ð±Ð»Ð¸Ð·ÑŒÐºÐ¾ÑÑ‚Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="9043">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°</t>
    <t id="9004">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ñ†Ñ–Ð½Ð¾Ð²Ñ– Ð´Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½Ð¸</t>
    <t id="9005">Ð¦Ñ–Ð½Ð° Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ— Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ ÐœÐ°ÐºÑ</t>
    <t id="9006">ÐšÑƒÐ¿Ð¸Ñ‚Ð¸ ÐŸÑ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ Ð¦Ñ–Ð½Ð° ÐœÑ–Ð½</t>
    <t id="9007">Ð†Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¾: ÐœÐ°ÐºÑ. Ñ†Ñ–Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="9008">Ð†Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¾: ÐšÑƒÐ¿Ð¸Ñ‚Ð¸ Ð¦Ñ–Ð½Ð° ÐœÑ–Ð½</t>
    <t id="9009">Ð ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ð¹ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚: ÐœÐ°ÐºÑ. Ñ†Ñ–Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="9014">Ð—Ð°Ð¿Ð°ÑÐ½Ð¸Ð¹ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚: Ñ†Ñ–Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð¼Ñ–Ð½</t>
    <t id="9016">ÐŸÐ¾Ñ€Ð¾Ð³Ð¾Ð²Ð° Ð±Ð°Ð·Ð° Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ</t>
    <t id="9025">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ñ– Ð³Ñ€Ð¾ÑˆÑ– Ð³Ñ€Ð°Ð²Ñ†Ñ</t>
    <t id="9024">Ð”Ð¾Ð¿ÑƒÑÐº Ð´Ð¾ Ð²Ð¸Ð¿Ð°Ð´Ð°Ð½Ð½Ñ ÐºÐµÑˆÑƒ</t>
    <t id="9026">Ð§Ð°Ñ Ð¿Ñ€Ð¾ÑÑ‚Ð¾ÑŽ Ð¿ÐµÑ€ÐµÐ´ Ð·Ð²Ñ–Ð»ÑŒÐ½ÐµÐ½Ð½ÑÐ¼ Ð¿Ð¾Ñ€Ñ‚Ñƒ</t>
    <t id="9054">Ð‘Ð»Ð¾ÐºÑƒÐ¹Ñ‚Ðµ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð²Ð¾Ñ€Ð¾Ð¶Ð¾Ñ— Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ—</t>
    <t id="9055">Ð Ñ–Ð²ÐµÐ½ÑŒ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ</t>
    <t id="9056">Ð’Ñ–Ð´Ð½Ð¾Ð²Ð¸Ñ‚Ð¸ Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº</t>
    <t id="9057">Ð’Ñ–Ð´Ñ‚Ð²Ð¾Ñ€Ð¸Ñ‚Ð¸</t>
    <t id="9058">ÐŸÑ€Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ñ‚Ð¸ Ð½Ð° GT ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–</t>
    <t id="9059">ÐŸÑ€Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ñ‚Ð¸</t>
    <t id="9112">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÑÑ” Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ, ÐºÐ¾Ð»Ð¸ Ð²Ð¾Ð½Ð¸ Ð´Ð¾ÑÑÐ³Ð°ÑŽÑ‚ÑŒ Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¸Ñ… Ñ€Ñ–Ð²Ð½Ñ–Ð². Ð’Ð¸Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ Ð´Ð»Ñ Ñ€ÑƒÑ‡Ð½Ð¾Ð³Ð¾ ÐºÐµÑ€ÑƒÐ²Ð°Ð½Ð½Ñ Ñ‡Ð°ÑÐ¾Ð¼ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ.</t>
    <t id="9113">Ð ÐµÐ³ÑƒÐ»ÑŽÑ” ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð½Ð°Ð±ÑƒÑ‚Ñ‚Ñ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸ Ð´Ð¾ÑÐ²Ñ–Ð´Ñƒ. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð·Ð½Ð°Ñ‡Ð°ÑŽÑ‚ÑŒ ÑˆÐ²Ð¸Ð´ÑˆÐ¸Ð¹ Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑ.</t>
    <t id="9115">Ð’Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð´Ð¾ÑÐ²Ñ–Ð´Ñƒ Ð¿Ñ–Ð´Ð»ÐµÐ³Ð»Ð¸Ñ…, Ð½Ð°Ð´Ð°Ð½Ð¸Ð¹ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼-ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°Ð¼. Ð’ÑÑ‚Ð°Ð½Ð¾Ð²Ñ–Ñ‚ÑŒ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ 0%, Ñ‰Ð¾Ð± Ð²Ð¸Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð±Ð¾Ð½ÑƒÑ XP ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 10%.</t>
    <t id="9121">Ð”Ð¾Ð·Ð²Ð¾Ð»ÑÑ” Ñ–Ð½Ñ‚ÐµÐ»ÐµÐºÑ‚ÑƒÐ°Ð»ÑŒÐ½Ñ– Ñ„ÑƒÐ½ÐºÑ†Ñ–Ñ— ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ— Ð¿Ð°Ñ€ÐºÑƒ, Ð²ÐºÐ»ÑŽÑ‡Ð°ÑŽÑ‡Ð¸ Ð¾Ð¿Ñ‚Ð¸Ð¼Ñ–Ð·Ð°Ñ†Ñ–ÑŽ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñƒ Ñ‚Ð° Ð±Ð°Ð»Ð°Ð½ÑÑƒÐ²Ð°Ð½Ð½Ñ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ.</t>
    <t id="9123">Ð”Ð¾Ð·Ð²Ð¾Ð»ÑÑ” Ð¾Ð±Ð¼Ñ–Ð½ÑŽÐ²Ð°Ñ‚Ð¸ÑÑ Ð²Ð¸Ð³Ñ–Ð´Ð½Ð¸Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¼Ð¸ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚ÑÐ¼Ð¸ Ð¼Ñ–Ð¶ Ñ‡Ð»ÐµÐ½Ð°Ð¼Ð¸ Ñ„Ð»Ð¾Ñ‚Ñƒ Ð´Ð»Ñ ÐºÑ€Ð°Ñ‰Ð¾Ñ— ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ—.</t>
    <t id="9131">ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»ÑŽÑ” ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½ÑŒ, ÑÐºÑ– Ð²Ñ–Ð´Ð¾Ð±Ñ€Ð°Ð¶Ð°ÑŽÑ‚ÑŒÑÑ: 0=Ñ‚Ð¸Ñ…Ð¾, 1=Ð»Ð¸ÑˆÐµ Ð²Ð°Ð¶Ð»Ð¸Ð²Ñ–, 2=ÑƒÑÑ– ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ</t>
    <t id="9141">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÑÑ” ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð½Ð° Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ Ð¿Ñ–ÑÐ»Ñ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð², ÐºÐ¾Ð»Ð¸ ÐºÐ¾Ñ€Ð¿ÑƒÑ Ð¿Ð°Ð´Ð°Ñ” Ð½Ð¸Ð¶Ñ‡Ðµ Ð¿Ð¾Ñ€Ð¾Ð³Ñƒ. Ð¢Ñ–Ð»ÑŒÐºÐ¸ Ð´Ð»Ñ Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² (Ñ€Ñ–Ð²ÐµÐ½ÑŒ 12+). ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð¾Ð±Ð¸Ñ€Ð°ÑŽÑ‚ÑŒ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ð¸Ð¹ Ð¾Ð±â€™Ñ”ÐºÑ‚: S/M Equipment Dock, L/XL Shipyard.</t>
    <t id="9142">Ð’Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ, Ð½Ð¸Ð¶Ñ‡Ðµ ÑÐºÐ¾Ð³Ð¾ Ð·Ð°Ð¿ÑƒÑÐºÐ°Ñ”Ñ‚ÑŒÑÑ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¸Ð¹ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 95%. Ð£ Ñ€Ð°Ð·Ñ– Ð¿Ð¾ÑˆÐºÐ¾Ð´Ð¶ÐµÐ½Ð½Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð½Ð°Ð¿Ñ€Ð°Ð²Ð»ÑÑ‚Ð¸Ð¼ÑƒÑ‚ÑŒÑÑ Ð´Ð¾ Ð½Ð°Ð¹Ð±Ð»Ð¸Ð¶Ñ‡Ð¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ð½Ð¾Ð³Ð¾ Ð·Ð°ÐºÐ»Ð°Ð´Ñƒ.</t>
    <t id="9411">Ð¯ÐºÑ‰Ð¾ ÑƒÐ²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, ÑˆÐ°Ñ…Ñ‚Ð°Ñ€Ñ– Ñ‡ÐµÐºÐ°ÑŽÑ‚ÑŒ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¾Ñ†Ñ–Ð½ÐºÐ¸ Ñ€ÐµÑÑƒÑ€ÑÐ½Ð¸Ñ… Ð·Ð¾Ð½Ð´Ñ–Ð² Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ— Ð² ÑÐµÐºÑ‚Ð¾Ñ€Ñ– (+5 Ñ Ð·Ð° ÐºÐ¾Ð¶ÐµÐ½ Ð·Ð¾Ð½Ð´ Ð¿Ð¾Ð½Ð°Ð´ Ð¾Ð´Ð¸Ð½). Ð Ñ–Ð²ÐµÐ½ÑŒ GT Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð»Ñ–Ð½Ñ–Ð¹Ð½Ð¾ ÑÐºÐ¾Ñ€Ð¾Ñ‡ÑƒÑ” Ñ†Ðµ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð²Ñ–Ð´ Ð¿Ð¾Ð²Ð½Ð¾Ð³Ð¾ Ñ‡Ð°ÑÑƒ Ð½Ð° Ñ€Ñ–Ð²Ð½Ñ– 1 Ð´Ð¾ 5 ÑÐµÐºÑƒÐ½Ð´ Ð½Ð° Ñ€Ñ–Ð²Ð½Ñ– 15 (Ð»Ð¸ÑˆÐµ Ñ€ÐµÐ¶Ð¸Ð¼ GT XP, ÑÐºÑ‰Ð¾ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¿ÐµÑ€ÐµÐ²Ð¸Ñ‰ÑƒÑ” 5 Ñ). Ð’Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾ = Ð±ÐµÐ· Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ (Ð¿Ð¾Ð²ÐµÐ´Ñ–Ð½ÐºÐ° vanilla).</t>
    <t id="9412">Ð¡Ñ…Ð¸Ð»ÑÑ” ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– MK3/MK4 Ð´Ð¾ Ð±Ð»Ð¸Ð¶Ñ‡Ð¸Ñ… ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹ ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ– Ð¿Ñ–Ð´ Ñ‡Ð°Ñ ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ð½Ð½Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐµÐ½Ð¸Ñ… ÑƒÐ³Ð¾Ð´. ÐžÑ†Ñ–Ð½ÐºÐ° Ð²Ñ–Ð´Ð±Ð¾Ñ€Ñƒ = Ð¾Ñ†Ñ–Ð½ÐºÐ° ÑƒÐ³Ð¾Ð´Ð¸ / (1 + ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŒâ†’ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ Ã— Ð²Ð°Ð³Ð°). ÐŸÐ¾Ð²Ð·ÑƒÐ½Ð¾Ðº 0-100 (0 = Ð²Ð¸Ð¼Ðº.; 4 = Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ 0,04). ÐÐµ Ð²Ð¿Ð»Ð¸Ð²Ð°Ñ” Ð½Ð° Ñ€ÐµÐ¹Ñ‚Ð¸Ð½Ð³ ÐºÐµÑˆÑƒ Ñ‚Ð° Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ñ–Ð°Ð»ÑŒÐ½Ñ– Ð»Ñ–Ð¼Ñ–Ñ‚Ð¸ Ð´Ð°Ð»ÑŒÐ½Ð¾ÑÑ‚Ñ–.</t>
    <t id="9143">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ–Ð»Ð¾Ñ‚Ð½Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ, Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¸Ð¹ Ð´Ð»Ñ Ñ„ÑƒÐ½ÐºÑ†Ñ–Ñ— Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ð³Ð¾ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 12 (Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ñ– Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€Ð¸). ÐŸÑ–Ð»Ð¾Ñ‚Ð¸ Ð½Ð¸Ð¶Ñ‡Ð¾Ð³Ð¾ Ñ€Ñ–Ð²Ð½Ñ Ð¿Ð¾Ð²Ð¸Ð½Ð½Ñ– Ñ€ÐµÐ¼Ð¾Ð½Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ.</t>
    <t id="9104">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´Ð½Ð¾ÑÐ½Ð° Ñ†Ñ–Ð½Ð° Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶ (Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð½Ñ ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ– Ð—Ñ– ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹). Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: Ð²Ñ–Ð´ -1,0 Ð´Ð¾ +1,0. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 0,5 (Ð½Ð° 50% Ð²Ð¸Ñ‰Ðµ ÑÐµÑ€ÐµÐ´Ð½ÑŒÐ¾Ð³Ð¾). Ð’Ð¸Ñ‰Ðµ = Ð´Ð¾Ñ€Ð¾Ð¶Ñ‡Ðµ, Ð°Ð»Ðµ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ñ–Ð².</t>
    <t id="9105">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´Ð½Ð¾ÑÐ½Ð° Ñ†Ñ–Ð½Ð° Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ– (ÑÑƒÐ´Ð½Ð¾ Ð¿Ñ€Ð¾Ð´Ð°Ñ” TO ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—). Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: Ð²Ñ–Ð´ -1,0 Ð´Ð¾ +1,0. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: -0,5 (50% Ð½Ð¸Ð¶Ñ‡Ðµ ÑÐµÑ€ÐµÐ´Ð½ÑŒÐ¾Ð³Ð¾). ÐÐ¸Ð¶Ñ‡Ðµ = Ð´ÐµÑˆÐµÐ²ÑˆÑ– Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ–, Ð°Ð»Ðµ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ñ–Ð².</t>
    <t id="9106">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ñ†Ñ–Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð´Ð»Ñ Ñ–Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² (Ð·Ð°ÑÑ‚Ñ€ÑÐ³Ð»Ð¸ Ð² Ð¾Ð´Ð½Ð¾Ð¼Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñ–). Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: Ð²Ñ–Ð´ -1,0 Ð´Ð¾ +1,0. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 0,5.</t>
    <t id="9107">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ñ†Ñ–Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð´Ð»Ñ Ñ–Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² (Ð·Ð°ÑÑ‚Ñ€ÑÐ³Ð»Ð¸ Ð² Ð¾Ð´Ð½Ð¾Ð¼Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ñ–). Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: Ð²Ñ–Ð´ -1,0 Ð´Ð¾ +1,0. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: -0,5.</t>
    <t id="9108">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ñ†Ñ–Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð´Ð»Ñ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ Ð¿Ð¾ÑˆÑƒÐºÑƒ (Ð¾ÑÑ‚Ð°Ð½Ð½Ñ–Ð¹ Ð·Ð°ÑÑ–Ð±, ÐºÐ¾Ð»Ð¸ Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº Ð½Ðµ Ð²Ð´Ð°Ñ”Ñ‚ÑŒÑÑ). Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: Ð²Ñ–Ð´ -1,0 Ð´Ð¾ +1,0. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 0,5. Ð—Ð°Ð¿Ð°ÑÐ½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” MaxDistance=2 Ñ– Ð¿Ð¾ÑÐ»Ð°Ð±Ð»ÐµÐ½Ñ– Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="9109">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ñ†Ñ–Ð½Ð° Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸ Ð´Ð»Ñ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ Ð¿Ð¾ÑˆÑƒÐºÑƒ (Ð¾ÑÑ‚Ð°Ð½Ð½Ñ–Ð¹ Ð·Ð°ÑÑ–Ð±, ÐºÐ¾Ð»Ð¸ Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº Ð½Ðµ Ð²Ð´Ð°Ñ”Ñ‚ÑŒÑÑ). Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: Ð²Ñ–Ð´ -1,0 Ð´Ð¾ +1,0. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: -0,5. Ð—Ð°Ð¿Ð°ÑÐ½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” MaxDistance=2 Ñ– Ð¿Ð¾ÑÐ»Ð°Ð±Ð»ÐµÐ½Ñ– Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="9116">Ð‘Ð°Ð·Ð¾Ð²Ð¸Ð¹ Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº Ð½Ð° Ñ€Ñ–Ð²Ð½Ñ– 15 Ð´Ð»Ñ ÑÐµÑ€ÐµÐ´Ð½ÑŒÐ¾Ð³Ð¾ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€Ð° (ÐµÑ‚Ð°Ð»Ð¾Ð½Ð½Ð¸Ð¹ Ð²Ð°Ð½Ñ‚Ð°Ð¶ 8200). Ð¤Ð°ÐºÑ‚Ð¸Ñ‡Ð½Ð¸Ð¹ Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð°Ð±ÑÐ¾Ð»ÑŽÑ‚Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº Ð¾Ð±Ñ‡Ð¸ÑÐ»ÑŽÑ”Ñ‚ÑŒÑÑ Ð´Ð»Ñ ÐºÐ¾Ð¶Ð½Ð¾Ð³Ð¾ Ð¿Ñ–Ð»Ð¾Ñ‚Ð° + Ð¼Ð°ÑÑˆÑ‚Ð°Ð±Ð¾Ð²Ð°Ð½Ð¸Ð¹ Ð·Ð° Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ¼:\n\nÐ±Ð°Ð·Ð¾Ð²Ð¸Ð¹ (L) = Ð±Ð°Ð·Ð¾Ð²Ð¸Ð¹ * ((L-1)^2 / 14^2)\nÐ¼Ð°ÑÑˆÑ‚Ð°Ð±Ð¾Ð²Ð°Ð½Ð¸Ð¹ = Ð±Ð°Ð·Ð¾Ð²Ð¸Ð¹ (L) * (Ð²Ð°Ð½Ñ‚Ð°Ð¶ / 8200)\nÑ„Ñ–Ð½Ð°Ð»ÑŒÐ½Ð¸Ð¹ = Ð¼Ð°ÐºÑ. (Ð¼Ð°ÑÑˆÑ‚Ð°Ð±Ð¾Ð²Ð°Ð½Ð¸Ð¹, 25% Ð²Ñ–Ð´ Ð±Ð°Ð·Ð¾Ð²Ð¾Ð³Ð¾ (L))\n\nÐ£ÑÑ‚Ð°Ð½Ð¾Ð²Ñ–Ñ‚ÑŒ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ 0, Ñ‰Ð¾Ð± Ð¿Ñ€Ð¸Ð¹Ð½ÑÑ‚Ð¸ Ð±ÑƒÐ´ÑŒ-ÑÐºÐ¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº (Ð»Ð¸ÑˆÐµ ROI/Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ/Ñ–Ð½ÑˆÑ– Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ð¸ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸).</t>
    <t id="9125">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ñ– Ð³Ñ€Ð¾ÑˆÑ– Ð³Ñ€Ð°Ð²Ñ†Ñ (ÐºÑ€ÐµÐ´Ð¸Ñ‚Ð¸), Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ñ– Ð´Ð»Ñ Ñ‚Ð¾Ð³Ð¾, Ñ‰Ð¾Ð± ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– ÑˆÑƒÐºÐ°Ð»Ð¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð². ÐšÐ¾Ð»Ð¸ Ð³Ñ€Ð¾ÑˆÑ– Ð³Ñ€Ð°Ð²Ñ†Ñ–Ð² Ð¿Ð°Ð´Ð°ÑŽÑ‚ÑŒ Ð½Ð¸Ð¶Ñ‡Ðµ Ñ†ÑŒÐ¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ñƒ, ÑƒÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº Ñ– Ñ‡ÐµÐºÐ°ÑŽÑ‚ÑŒ, Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°ÑŽÑ‡Ð¸ Ð´Ð¾Ñ€Ð¾Ð³Ð¾Ð¼Ñƒ ÑÐºÐ°Ð½ÑƒÐ²Ð°Ð½Ð½ÑŽ ÐºÐµÑˆÑƒ, ÑÐºÐµ ÑÐ¿Ñ€Ð¸Ñ‡Ð¸Ð½ÑÑ” Ð·Ð°Ð²Ð¸ÑÐ°Ð½Ð½Ñ Ð³Ñ€Ð¸. Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½: 1000 - 100 000 Cr. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1000 Cr.</t>
    <t id="9124">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ñ€ÐµÐ½Ñ‚Ð°Ð±ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ñ– Ñ–Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ñ–Ð¹ Ñ–Ð· ÐºÐµÑˆÐ¾Ð²Ð°Ð½Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿ÐµÑ€ÐµÐ´ Ð²Ñ–Ð´Ñ…Ð¸Ð»ÐµÐ½Ð½ÑÐ¼ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–. ÐŸÑ€Ð¸ÐºÐ»Ð°Ð´: ÐºÐµÑˆÐ¾Ð²Ð°Ð½Ð° Ñ€ÐµÐ½Ñ‚Ð°Ð±ÐµÐ»ÑŒÐ½Ñ–ÑÑ‚ÑŒ Ñ–Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ñ–Ð¹ 20% Ñ–Ð· Ð´Ð¾Ð¿ÑƒÑÑ‚Ð¸Ð¼Ð¸Ð¼ Ð²Ñ–Ð´Ñ…Ð¸Ð»ÐµÐ½Ð½ÑÐ¼ 15% Ð´Ð¾Ð¿ÑƒÑÐºÐ°Ñ” Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ñ€ÐµÐ½Ñ‚Ð°Ð±ÐµÐ»ÑŒÐ½Ð¾ÑÑ‚Ñ– Ñ–Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ñ–Ð¹ Ð´Ð¾ 17% (ÑÐ¿Ð°Ð´ Ð½Ð° 14%).</t>
    <t id="9126">Ð¥Ð²Ð¸Ð»Ð¸Ð½ Ð±Ñ–Ð»Ñ Ð´Ð¾ÐºÐ° Ð¿ÐµÑ€ÐµÐ´ Ð²Ñ–Ð´ÑÑ‚Ð¸ÐºÑƒÐ²Ð°Ð½Ð½ÑÐ¼ Ð´Ð»Ñ Ð·Ð²Ñ–Ð»ÑŒÐ½ÐµÐ½Ð½Ñ Ð¿Ð¾Ñ€Ñ‚Ñƒ (0-60). 0 = Ð·Ð°Ð»Ð¸ÑˆÐ°Ñ”Ñ‚ÑŒÑÑ Ð±Ñ–Ð»Ñ Ð´Ð¾ÐºÐ°, Ð´Ð¾ÐºÐ¸ Ð½Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÑ‚ÑŒÑÑ Ð½Ð¾Ð²Ð° Ñ€Ð¾Ð±Ð¾Ñ‚Ð°. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1 Ñ…Ð²Ð¸Ð»Ð¸Ð½Ð°.</t>
    <t id="9154">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð´Ð¾Ð´Ð°Ð²Ð°Ñ‚Ð¸ Ð² Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº ÑƒÑÑ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸, Ñ‰Ð¾ Ð½Ð°Ð»ÐµÐ¶Ð°Ñ‚ÑŒ Ð²Ð¾Ñ€Ð¾Ð¶Ð¸Ð¼ Ñ„Ñ€Ð°ÐºÑ†Ñ–ÑÐ¼ (Ð¿Ñ€Ð°Ð¿Ð¾Ñ€ÐµÑ†ÑŒ Ð·Ð²â€™ÑÐ·ÐºÑƒ Ð² Ñ‡Ð¾Ñ€Ð½Ð¾Ð¼Ñƒ ÑÐ¿Ð¸ÑÐºÑƒ)</t>
    <t id="9155">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ (1-5), Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¸Ð¹ Ð´Ð»Ñ Ð²Ð½ÐµÑÐµÐ½Ð½Ñ ÑÐµÐºÑ‚Ð¾Ñ€Ñƒ Ð² Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº:\n2=Ð¡ÐµÑ€ÐµÐ´Ð½Ñ–Ð¹ (Ð¾Ð´Ð¸Ð½Ð¸Ñ‡Ð½Ð° Ð°Ñ‚Ð°ÐºÐ°)\n3=Ð¡ÐµÑ€ÐµÐ´Ð½Ñ–Ð¹-Ð²Ð¸ÑÐ¾ÐºÐ¸Ð¹ (Ð²Ð¾Ñ€Ð¾Ð¶Ñ– Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ—)\n4=Ð’Ð¸ÑÐ¾ÐºÐ¸Ð¹ (ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–/Ñ€Ð°ÐºÐµÑ‚Ð¸)\n5=Ð”ÑƒÐ¶Ðµ Ð²Ð¸ÑÐ¾ÐºÐ¸Ð¹ (ÐšÑÐµÐ½Ð¾Ð½/Ð¥Ð°Ð°Ðº)</t>
    <t id="9156">Ð’Ñ€ÑƒÑ‡Ð½Ñƒ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð¸Ñ‚Ð¸ Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°Ð½Ð½Ñ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð°Ð¼ (ÐºÐ¾Ñ€Ð¸ÑÐ½Ð¾, ÑÐºÑ‰Ð¾ Ð¹Ð¾Ð³Ð¾ Ð±ÑƒÐ»Ð¾ Ð²Ð¸Ð´Ð°Ð»ÐµÐ½Ð¾)</t>
    <t id="9157">Ð’Ñ€ÑƒÑ‡Ð½Ñƒ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ñ‚Ð¸ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ Ð´Ð¸Ð½Ð°Ð¼Ñ–Ñ‡Ð½Ð¸Ð¹ Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº ÑƒÑÑ–Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ ÐºÐ¾Ð¼Ð°Ð½Ð´ÑƒÐ²Ð°Ð½Ð½Ñ Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼ GT. ÐŸÑ–Ð´Ð»ÐµÐ³Ð»Ñ– ÑƒÑÐ¿Ð°Ð´ÐºÐ¾Ð²ÑƒÑŽÑ‚ÑŒ Ð²Ñ–Ð´ ÑÐ²Ð¾Ð³Ð¾ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°.</t>
    <t id="6001">Ð£Ñ‡ÐµÐ½ÑŒ</t>
    <t id="6002">ÐšÑƒÑ€'Ñ”Ñ€</t>
    <t id="6003">ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸Ðº</t>
    <t id="6004">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†ÑŒ</t>
    <t id="6005">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†ÑŒ</t>
    <t id="6006">ÐœÑ–Ð¶Ð¼Ñ–ÑÑŒÐºÐ¸Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†ÑŒ</t>
    <t id="6101">Ð—Ð±Ð°Ð»Ð°Ð½ÑÐ¾Ð²Ð°Ð½Ð¸Ð¹</t>
    <t id="6102">ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð½Ñ–</t>
    <t id="6103">ÐžÑ€Ñ–Ñ”Ð½Ñ‚Ð¾Ð²Ð°Ð½Ð¸Ð¹ Ð½Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ</t>
    <t id="6104">Ð’Ð°Ð¶ÐºÐ° Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð°</t>
    <t id="6105">ÐŸÑ–Ð´Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð²ÐµÐ¶Ñ–</t>
    <t id="9050">Ð¡Ð¸ÑÑ‚ÐµÐ¼Ð° Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°Ð½Ð½Ñ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð°Ð¼</t>
    <t id="9051">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ ÑƒÐ½Ð¸ÐºÐ½ÐµÐ½Ð½Ñ Ð·Ð°Ð³Ñ€Ð¾Ð·:</t>
    <t id="9052">ÐŸÐ¾Ñ€Ñ–Ð³ Ð²Ð¾Ñ€Ð¾Ð¶Ð¸Ñ… Ð²Ñ–Ð´Ð½Ð¾ÑÐ¸Ð½:</t>
    <t id="9053">Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ð´Ð¸Ð½Ð°Ð¼Ñ–Ñ‡Ð½Ð¸Ð¹ Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº:</t>
    <t id="9151">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ– Ñ€Ñ–Ð²Ð½Ñ 6+ Ð²Ð¸ÑÐ²Ð»ÑÑŽÑ‚ÑŒ Ð²Ð¾Ñ€Ð¾Ð¶Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ñ‚Ð° ÑƒÐ½Ð¸ÐºÐ°ÑŽÑ‚ÑŒ Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ð¸Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ–Ð². Ð’Ð¸Ð¼ÐºÐ½ÐµÐ½Ð½Ñ Ð·ÑƒÐ¿Ð¸Ð½ÑÑ” Ð²ÑÑ– ÑÐºÐ°Ð½ÑƒÐ²Ð°Ð½Ð½Ñ (Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ). Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð¾ Ñ€Ð¸Ð·Ð¸ÐºÑƒ Ð½Ð° ÑÑƒÐ´Ð½Ð¾ Ð² ÐºÐ¾Ð¼Ð°Ð½Ð´Ð½Ñ–Ð¹ Ð¿Ð¾Ð²ÐµÐ´Ñ–Ð½Ñ†Ñ– (ÑˆÐºÐ°Ð»Ð° 0-10).</t>
    <t id="9152">ÐŸÐ¾Ð·Ð½Ð°Ñ‡Ð°Ð¹Ñ‚Ðµ ÑÐº Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ Ð»Ð¸ÑˆÐµ Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ—, Ð²Ñ–Ð´Ð½Ð¾ÑˆÐµÐ½Ð½Ñ ÑÐºÐ¸Ñ… Ð´Ð¾Ñ€Ñ–Ð²Ð½ÑŽÑ” Ð°Ð±Ð¾ Ð½Ð¸Ð¶Ñ‡Ðµ Ñ†ÑŒÐ¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: -20%</t>
    <t id="9153">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð´Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ð½ÐµÐ±ÐµÐ·Ð¿ÐµÑ‡Ð½Ñ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð´Ð¾ Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ (Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸ 3+), Ñ‰Ð¾Ð± Ð·Ð¼ÑƒÑÐ¸Ñ‚Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð¾Ð±Ñ…Ð¾Ð´Ð¸Ñ‚Ð¸ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” Ð²Ð°Ð½Ñ–Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº Ð°Ð»ÑŒÑ‚ÐµÑ€Ð½Ð°Ñ‚Ð¸Ð²Ð½Ð¸Ñ… Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ–Ð².</t>
    <t id="9060">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð·Ð°Ñ…Ð¸ÑÐ½Ð¾Ð³Ð¾ ÑÐ¿Ð¾Ñ€ÑÐ´Ð¶ÐµÐ½Ð½Ñ (Ñ€Ñ–Ð²ÐµÐ½ÑŒ 15)</t>
    <t id="9061">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ:</t>
    <t id="9062">Ð—Ð°Ñ…Ð¾Ð´Ð¸ Ð¿Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð·Ð°Ð¿Ð°ÑÑ–Ð²:</t>
    <t id="9063">ÐŸÐ¾Ð¿Ð¾Ð²Ð½Ð¸Ñ‚Ð¸ Ð·Ð°Ð¿Ð°ÑÐ¸ Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð½Ð¸Ñ… Ð´Ñ€Ð¾Ð½Ñ–Ð²:</t>
    <t id="9064">ÐŸÐ¾Ð¿Ð¾Ð²Ð½Ñ–Ñ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð´Ñ€Ð¾Ð½Ð¸:</t>
    <t id="9065">ÐŸÐ¾Ð¿Ð¾Ð²Ð½Ð¸Ñ‚Ð¸ Ð·Ð°Ð¿Ð°ÑÐ¸ Ð»Ð°Ð·ÐµÑ€Ð½Ð¸Ñ… Ð²ÐµÐ¶:</t>
    <t id="9066">ÐŸÐ¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð·Ð°Ð¿Ð°ÑÑ–Ð² Ð´Ñ€Ð¾Ð½Ñ–Ð² Ð´Ð»Ñ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ:</t>
    <t id="9067">ÐŸÐ¾Ñ€Ñ–Ð³ Ð¿Ñ€Ð¾Ñ‚Ð¸Ð´Ñ–Ñ—:</t>
    <t id="9068">Ð£Ð½Ñ–Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ñ”Ð¼Ð½Ð¾ÑÑ‚Ñ–:</t>
    <t id="9069">ÐŸÑ€Ð¾Ñ„Ñ–Ð»ÑŒ Ð±Ð°Ð»Ð°Ð½ÑÑƒ Ð¾Ð±Ð»Ð°Ð´Ð½Ð°Ð½Ð½Ñ:</t>
    <t id="9161">ÐœÐ°Ð¹ÑÑ‚Ñ€Ð¸ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€Ð¸ (Ñ€Ñ–Ð²ÐµÐ½ÑŒ 15) Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÑŽÑŽÑ‚ÑŒ Ð·Ð°Ð¿Ð°ÑÐ¸ Ð·Ð°Ñ…Ð¸ÑÐ½Ð¾Ð³Ð¾ Ð¾Ð±Ð»Ð°Ð´Ð½Ð°Ð½Ð½Ñ Ð¿Ñ–ÑÐ»Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð². Ð—Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð´Ð¾ Ñ€Ñ–Ð²Ð½Ñ ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð° Ð´Ð»Ñ Ð¿Ñ–Ð´Ð»ÐµÐ³Ð»Ð¸Ñ….</t>
    <t id="9162">Ð£ÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– (S/M/L/XL). Ð Ð¾Ð·Ð´Ñ–Ð»ÑŒÐ½Ð° Ñ”Ð¼Ð½Ñ–ÑÑ‚ÑŒ. ÐšÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð¸Ð¹ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñ‚Ð¸Ñ€Ð°ÐºÐµÑ‚Ð½Ð¾Ñ— Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð¸.</t>
    <t id="9163">Ð”Ð¾ÑÑ‚Ð°Ð²Ð»ÑÑ”Ñ‚ÑŒÑÑ Ñ‚Ñ–Ð»ÑŒÐºÐ¸ L/XL. Ð”Ñ–Ð»Ð¸Ñ‚ÑŒÑÑ Ñ”Ð´Ð¸Ð½Ð¾ÑŽ Ñ”Ð¼Ð½Ñ–ÑÑ‚ÑŽ Ð· Ñ–Ð½ÑˆÐ¸Ð¼Ð¸ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ€Ð¸ÑÑ‚Ñ€Ð¾ÑÐ¼Ð¸.</t>
    <t id="9164">Ð”Ð¾ÑÑ‚Ð°Ð²Ð»ÑÑ”Ñ‚ÑŒÑÑ Ñ‚Ñ–Ð»ÑŒÐºÐ¸ L/XL. ÐÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¸Ð¹ Ð´Ð»Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ð¹. Ð Ð¾Ð·Ð´Ñ–Ð»ÑÑ” Ñ”Ð´Ð¸Ð½Ñƒ Ñ”Ð¼Ð½Ñ–ÑÑ‚ÑŒ.</t>
    <t id="9165">Ð’ÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–. ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ– L/XL Ð¼Ð°ÑŽÑ‚ÑŒ ÑÐ¿Ñ–Ð»ÑŒÐ½Ñƒ Ð¼Ñ–ÑÑ‚ÐºÑ–ÑÑ‚ÑŒ, S/M Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑŽÑ‚ÑŒ Ð²Ð°Ð½Ñ‚Ð°Ð¶.</t>
    <t id="9166">Ð”Ð¾ÑÑ‚Ð°Ð²Ð»ÑÑ”Ñ‚ÑŒÑÑ Ñ‚Ñ–Ð»ÑŒÐºÐ¸ L/XL. ÐŸÑ€Ð°Ñ†ÑŽÑ” Ð· ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð°Ð²Ñ‚Ð¾Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ. Ð Ð¾Ð·Ð´Ñ–Ð»ÑÑ” Ñ”Ð´Ð¸Ð½Ñƒ Ñ”Ð¼Ð½Ñ–ÑÑ‚ÑŒ.</t>
    <t id="9167">ÐŸÐ¾Ð¿Ð¾Ð²Ð½ÑŽÐ¹Ñ‚Ðµ Ð·Ð°Ð¿Ð°ÑÐ¸, ÐºÐ¾Ð»Ð¸ ÐºÐ¾Ð½Ñ‚Ñ€Ð·Ð°Ñ…Ð¾Ð´Ð¸ Ð½Ð¸Ð¶Ñ‡Ñ– Ð·Ð° Ñ†ÐµÐ¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº (ÑƒÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–, Ð¾ÐºÑ€ÐµÐ¼Ð° Ð¼Ñ–ÑÑ‚ÐºÑ–ÑÑ‚ÑŒ).</t>
    <t id="9168">ÐŸÐ¾Ð¿Ð¾Ð²Ð½ÑŽÐ¹Ñ‚Ðµ Ð·Ð°Ð¿Ð°ÑÐ¸, ÐºÐ¾Ð»Ð¸ Ð·Ð°Ð³Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ð½ÑƒÑ‚Ð¸Ñ… ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ–Ð² ÑÑ‚Ð°Ð½Ðµ Ð½Ð¸Ð¶Ñ‡Ð¾ÑŽ Ð·Ð° Ñ†ÐµÐ¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– L/XL: Ð´Ñ€Ð¾Ð½Ð¸ Ñ‚Ð° Ð²ÐµÐ¶Ñ– Ð¼Ð°ÑŽÑ‚ÑŒ Ð¾Ð´Ð½Ñƒ Ð¼Ñ–ÑÑ‚ÐºÑ–ÑÑ‚ÑŒ).</t>
    <t id="9169">Ð Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð» ÑƒÐ½Ñ–Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¾Ñ— Ð¿Ð¾Ñ‚ÑƒÐ¶Ð½Ð¾ÑÑ‚Ñ– (ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– L/XL): Ð¾Ñ€Ñ–Ñ”Ð½Ñ‚Ð¾Ð²Ð°Ð½Ð° Ð½Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ (20/50/20/10), Ð·Ð±Ð°Ð»Ð°Ð½ÑÐ¾Ð²Ð°Ð½Ð° (35/35/20/10), Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð½Ð° (50/20/20/10), Ð²Ð°Ð¶ÐºÐ° Ð¾Ð±Ð¾Ñ€Ð¾Ð½Ð° (40/30/20/10), Ð¿Ñ–Ð´Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð²ÐµÐ¶ (30/30/30/10). ÐšÐ¾ÐµÑ„Ñ–Ñ†Ñ–Ñ”Ð½Ñ‚Ð¸: ÐžÐ±Ð¾Ñ€Ð¾Ð½Ð°/Ð¢Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ/Ð’ÐµÐ¶Ñ–/Ð ÐµÐ¼Ð¾Ð½Ñ‚. ÐšÐ»Ð°Ñ†Ð½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð¿ÐµÑ€ÐµÐ³Ð»ÑÐ½ÑƒÑ‚Ð¸ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸.</t>
    <t id="9090">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="9091">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="9191">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÑŽÐ¹Ñ‚Ðµ Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ñ‚Ð° Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ñ– Ñ€Ñ–Ð²Ð½Ñ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°. Ð Ñ–Ð²ÐµÐ½ÑŒ 9+ = Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— Ñ€Ñ–Ð²Ð½Ñ 1, Ñ€Ñ–Ð²ÐµÐ½ÑŒ 12+ = Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— Ñ€Ñ–Ð²Ð½Ñ 2, Ñ€Ñ–Ð²ÐµÐ½ÑŒ 15+ = Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ— Ñ€Ñ–Ð²Ð½Ñ 3. ÐŸÑ–ÑÐ»Ñ ÑÐºÐ°ÑÑƒÐ²Ð°Ð½Ð½Ñ Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ð¸Ð´Ð°Ð»ÑÑŽÑ‚ÑŒÑÑ Ð»Ð¸ÑˆÐµ Ð¼Ð¾Ð´Ð¸, Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ñ– Ð² GT.</t>
    <t id="9070">ÐšÐ¾Ð½Ñ„Ñ–Ð³ÑƒÑ€Ð°Ñ†Ñ–Ñ Ð½Ð°Ð¹Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ ÑÑƒÐ´Ð½Ð°</t>
    <t id="9071">Ð”Ð¸ÑÐ¿Ð»ÐµÐ¹ XP:</t>
    <t id="9072">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚Ð¸ Ñ€ÐµÐ¹Ñ‚Ð¸Ð½Ð³:</t>
    <t id="9073">Ð Ñ–Ð²ÐµÐ½ÑŒ Ð²Ñ–Ð´Ð¾Ð±Ñ€Ð°Ð¶ÐµÐ½Ð½Ñ:</t>
    <t id="9074">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ Ð´Ð¸ÑÐ¿Ð»ÐµÑ:</t>
    <t id="9075">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð¿ÐµÑ€ÐµÐ¹Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ:</t>
    <t id="9076">ÐŸÑ€ÐµÑ„Ñ–ÐºÑ</t>
    <t id="9077">Ð¡ÑƒÑ„Ñ–ÐºÑ</t>
    <t id="9078">Ð”Ð¶ÐµÑ€ÐµÐ»Ð¾ Ñ–Ð¼ÐµÐ½Ñ– Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼:</t>
    <t id="9079">ÐÐ°Ð·Ð²Ð° Ð¼Ð¾Ð´ÐµÐ»Ñ–</t>
    <t id="9080">Ð¢Ð¸Ð¿ Ñ–Ð¼ÐµÐ½Ñ–</t>
    <t id="9081">Ð‘Ð°Ð·Ð° Ð¼Ð¾Ð´ÐµÐ»Ñ–</t>
    <t id="9083">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»ÑŒÐ½Ð° Ð½Ð°Ð·Ð²Ð°</t>
    <t id="9084">ÐŸÐ¾ÐºÐ°Ð·ÑƒÐ²Ð°Ñ‚Ð¸ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€:</t>
    <t id="9085">Ð ÐµÐ¶Ð¸Ð¼ Ñ–Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ:</t>
    <t id="9086">ÐšÐ»Ð°ÑÐ¸Ñ‡Ð½Ð¸Ð¹</t>
    <t id="9087">Ð¨Ð°Ð±Ð»Ð¾Ð½</t>
    <t id="9088">Ð¨Ð°Ð±Ð»Ð¾Ð½ Ñ–Ð¼ÐµÐ½Ñ–:</t>
    <t id="9089">ÐœÐ°Ñ€ÐºÐµÑ€Ð¸: {MODEL} {BASE} {HOME} {RANK} {LVL} {XP} {OPSTATE} {STATUS} {CLASS} {PILOT} {ORDER}. ÐÑ‚Ð¾Ð¼Ð°Ñ€Ð½Ñ–: {RS} {CB} {BL} Ñ‚Ð¾Ñ‰Ð¾. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” ÑÐºÐ¾Ñ€Ð¾Ñ‡ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ð½Ñ–Ð² Ð½Ð¸Ð¶Ñ‡Ðµ. ÐŸÐ¾Ñ€Ð¾Ð¶Ð½Ñ– Ð¼Ð°Ñ€ÐºÐµÑ€Ð¸ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ÑŒÑÑ; Ð¿Ñ€Ð¾Ð±Ñ–Ð»Ð¸ ÑÑ‚Ð¸ÑÐºÐ°ÑŽÑ‚ÑŒÑÑ. ÐœÐ°ÐºÑ. 128 ÑÐ¸Ð¼Ð²Ð¾Ð»Ñ–Ð².</t>
    <t id="9183">ÐŸÐ¾ÐºÐ°Ð·ÑƒÐ²Ð°Ñ‚Ð¸ Ð½Ð°Ð»Ð°ÑˆÑ‚Ð¾Ð²Ð°Ð½Ð¸Ð¹ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ Ñƒ Ð½Ð°Ð·Ð²Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ (Ð¿Ñ€ÐµÑ„Ñ–ÐºÑ Ð°Ð±Ð¾ ÑÑƒÑ„Ñ–ÐºÑ).</t>
    <t id="9184">ÐšÐ¾Ñ€Ð¸ÑÑ‚ÑƒÐ²Ð°Ñ†ÑŒÐºÐ¸Ð¹ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚ Ð½Ð°Ð·Ð²Ð¸ Ð· Ð¼Ð°Ñ€ÐºÐµÑ€Ð°Ð¼Ð¸ {TOKEN} Ð·Ð°Ð¼Ñ–ÑÑ‚ÑŒ ÐºÐ»Ð°ÑÐ¸Ñ‡Ð½Ð¸Ñ… Ð¿ÐµÑ€ÐµÐ¼Ð¸ÐºÐ°Ñ‡Ñ–Ð². ÐŸÐ¾Ñ‚Ñ€Ñ–Ð±ÐµÐ½ GalaxyTrader XP (Ð½Ðµ Ñ€ÐµÐ¶Ð¸Ð¼ vanilla XP).</t>
    <t id="9092">ÐœÐ°Ñ€ÐºÐµÑ€Ð¸ ÑˆÐ°Ð±Ð»Ð¾Ð½Ñƒ</t>
    <t id="9093">ÐšÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ: {MODEL} {MODELBASE} {TYPENAME} {BASE} {ID} {CLASS} {CLASSNAME}</t>
    <t id="9094">XP GT (mod): {XP} {LVL} {LVL_LABEL} {RANK} {RANKNUM} {STARS}</t>
    <t id="9095">Vanilla XP: {MGMT} {PILOTSKILL}</t>
    <t id="9096">Ð‘Ð°Ð·Ð°: {HOME} {HOMESTATION} {HOMESTATIONID}</t>
    <t id="9097">Ð•ÐºÑ–Ð¿Ð°Ð¶: {PILOT} {PILOTID} {FLEET} {COMMANDER} {COMMANDERID} {ORDER}</t>
    <t id="9098">Ð¡ÐµÐºÑ‚Ð¾Ñ€: {SECTOR} | Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°: {PROFIT} {TRADES} {SHIPPROFIT} {SHIPTRADES}</t>
    <t id="9099">ÐœÐ°Ñ€ÐºÐµÑ€Ð¸ ÑÑ‚Ð°Ñ‚ÑƒÑÑƒ:</t>
    <t id="9100">{OPSTATE}: ÑƒÑÑ– Ð°ÐºÑ‚Ð¸Ð²Ð½Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ð¹Ð½Ñ– Ð¿Ñ€Ð°Ð¿Ð¾Ñ€Ñ†Ñ– (Ð½Ð°Ð¿Ñ€. CB RS, MT)</t>
    <t id="9101">{STATUS}: Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ, Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ, Ñ€ÐµÐ·ÐµÑ€Ð² Ð°Ð±Ð¾ Ñ–Ð·Ð¾Ð»ÑÑ†Ñ–Ñ</t>
    <t id="9102">{CB}: Ð»Ð¸ÑˆÐµ Ð²Ð»Ð°ÑÐ½Ð¸Ð¹ blacklist, Ð²Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒ Ð´Ð¾ {OPSTATE}, Ð½Ðµ Ð¿Ð¾Ñ”Ð´Ð½ÑƒÐ²Ð°Ñ‚Ð¸</t>
    <t id="9082">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚Ð¸ ÐºÐ»Ð°Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ:</t>
    <t id="9171">ÐŸÐ¾ÐºÐ°Ð·ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ XP Ñƒ Ð½Ð°Ð·Ð²Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²</t>
    <t id="9175">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð±Ð¾ Ð²Ð¸Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ð¿ÐµÑ€ÐµÐ¹Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ Ð· Ñ–Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ñ–Ñ”ÑŽ Ð¿Ñ€Ð¾ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°</t>
    <t id="9172">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚Ð¸ Ñ€Ð°Ð½Ð³Ð¸ Ð² Ð½Ð°Ð·Ð²Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²</t>
    <t id="9173">ÐŸÐ¾ÐºÐ°Ð·ÑƒÐ²Ð°Ñ‚Ð¸ Ð½Ð¾Ð¼ÐµÑ€Ð¸ Ñ€Ñ–Ð²Ð½Ñ–Ð² Ñƒ Ð½Ð°Ð·Ð²Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²</t>
    <t id="9174">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚Ð¸ ÑÑ‚Ð°Ñ‚ÑƒÑ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð² Ð½Ð°Ð·Ð²Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²</t>
    <t id="9178">Ð’Ð¸Ð±ÐµÑ€Ñ–Ñ‚ÑŒ Ð´Ð¶ÐµÑ€ÐµÐ»Ð¾ Ð´Ð»Ñ Ð±Ð°Ð·Ð¾Ð²Ð¸Ñ… Ñ–Ð¼ÐµÐ½ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²: Ð½Ð°Ð·Ð²Ð° Ð¼Ð¾Ð´ÐµÐ»Ñ– (Ð· Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ð¾Ð¼), Ð½Ð°Ð·Ð²Ð° Ñ‚Ð¸Ð¿Ñƒ (Ð·Ð°Ð³Ð°Ð»ÑŒÐ½Ð°), Ð±Ð°Ð·Ð° Ð¼Ð¾Ð´ÐµÐ»Ñ– (Ð±ÐµÐ· Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ñƒ) Ð°Ð±Ð¾ ÑÐ¿ÐµÑ†Ñ–Ð°Ð»ÑŒÐ½Ð° Ð½Ð°Ð·Ð²Ð° (Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð° Ð½Ð°Ð·Ð²Ð°)</t>
    <t id="9182">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚Ð¸ ÐºÐ»Ð°Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ (S, M, L, XL) Ñƒ Ð½Ð°Ð·Ð²Ð°Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð²</t>
    <t id="9200">ÐŸÐ°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ</t>
    <t id="9201">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð¶ÑƒÑ€Ð½Ð°Ð» Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ:</t>
    <t id="9202">ÐžÑÐ½Ð¾Ð²Ð½Ð¸Ð¹ Ð¿ÐµÑ€ÐµÐ¼Ð¸ÐºÐ°Ñ‡ Ð´Ð»Ñ Ð²ÑÑŒÐ¾Ð³Ð¾ Ð²Ð¸Ð²Ð¾Ð´Ñƒ debug_text. Ð¯ÐºÑ‰Ð¾ Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, ÑƒÑÑ– Ð¶ÑƒÑ€Ð½Ð°Ð»Ð¸ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸Ð³Ð½Ñ–Ñ‡ÑƒÑŽÑ‚ÑŒÑÑ. Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð¿Ð¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ Ð·â€™ÑÐ²Ð»ÑÑŽÑ‚ÑŒÑÑ Ð² DebugLog Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ñ– Ñ–Ð½Ð´Ð¸Ð²Ñ–Ð´ÑƒÐ°Ð»ÑŒÐ½Ð¸Ñ… Ð·Ð½Ð°Ñ‡ÐµÐ½ÑŒ ÑˆÐ°Ð½ÑÑƒ debug_text.</t>
    <t id="9220">Ð¢ÐµÑ…Ð½Ñ–Ñ‡Ð½Ðµ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ð½Ð½Ñ Ñ‚Ð° Ð´Ñ–Ð°Ð³Ð½Ð¾ÑÑ‚Ð¸ÐºÐ°</t>
    <t id="9221">Ð¡ÐºÐ¸Ð½ÑƒÑ‚Ð¸ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÑƒ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ:</t>
    <t id="9222">Ð¡ÐšÐ˜Ð”ÐÐÐÐ¯</t>
    <t id="9223">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚Ð¸ Ð²ÑÑ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ:</t>
    <t id="9224">Ð¯Ð¡ÐÐž</t>
    <t id="9225">Ð¡ÐºÐ¸Ð½ÑƒÑ‚Ð¸ Ð²ÑÑ– Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ Ð´Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½ÑŒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼:</t>
    <t id="9226">Ð¡ÐšÐ˜Ð”ÐÐ£Ð¢Ð˜ Ð’Ð¡Ð•</t>
    <t id="9323">Ð’Ð¸Ð´Ð°Ð»ÑÑ” Ð²ÑÑ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ Ð°Ð½Ð°Ð»Ñ–Ð·Ñƒ Ð·Ð°Ð³Ñ€Ð¾Ð·. Ð¦Ðµ Ð½ÐµÐ³Ð°Ð¹Ð½Ð¾ Ð¾Ñ‡Ð¸ÑÑ‚Ð¸Ñ‚ÑŒ ÑƒÑÑ– ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð· Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ Ñ‚Ð° Ð´Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚ÑŒ Ð²Ð°ÑˆÐ¸Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶ÑƒÐ²Ð°Ñ‚Ð¸ Ð´Ð¾ Ñ€Ð°Ð½Ñ–ÑˆÐµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¸Ñ… Ð¾Ð±Ð»Ð°ÑÑ‚ÐµÐ¹. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ñ†Ðµ, ÑÐºÑ‰Ð¾ Ð²Ð¸ Ñ…Ð¾Ñ‡ÐµÑ‚Ðµ ÑÐºÐ¸Ð½ÑƒÑ‚Ð¸ ÑÐ¸ÑÑ‚ÐµÐ¼Ñƒ Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°Ð½Ð½Ñ Ð·Ð°Ð³Ñ€Ð¾Ð·Ð°Ð¼ Ð°Ð±Ð¾ ÑÐºÑ‰Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð±ÑƒÐ»Ð¸ Ð½ÐµÐ¿Ñ€Ð°Ð²Ð¸Ð»ÑŒÐ½Ð¾ Ð²Ð½ÐµÑÐµÐ½Ñ– Ð² Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº.</t>
    <t id="9321">Ð¡ÐºÐ¸Ð´Ð°Ñ” Ð²ÑÑŽ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÑƒ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ Ð´Ð¾ 0 Ð´Ð»Ñ Ð²ÑÑ–Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ñ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð². Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ñ†Ðµ Ð¿Ñ–ÑÐ»Ñ Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð´Ð¾ v0.6.0, Ñ‰Ð¾Ð± Ð¾Ñ‡Ð¸ÑÑ‚Ð¸Ñ‚Ð¸ Ð·Ð°Ð²Ð¸Ñ‰ÐµÐ½Ñƒ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÑƒ Ð½Ð° Ð¾ÑÐ½Ð¾Ð²Ñ– Ð´Ð¾Ñ…Ð¾Ð´Ñƒ. Ð’Ð¸Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð½Ñ Ñ‚ÐµÐ¿ÐµÑ€ Ð²Ñ–Ð´ÑÑ‚ÐµÐ¶ÑƒÑ” Ñ„Ð°ÐºÑ‚Ð¸Ñ‡Ð½Ð¸Ð¹ ÐŸÐ Ð˜Ð‘Ð£Ð¢ÐžÐš (Ð´Ð¾Ñ…Ñ–Ð´ - Ð²Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸). ÐŸÑ–Ð´Ñ€Ð°Ñ…ÑƒÐ½ÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ñ‚Ð° XP Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ñ–.</t>
    <t id="9325">Ð¡ÐºÐ¸Ð´Ð°Ñ” Ð²ÑÑ– Ð³Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ– Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ Ð´Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½ÑŒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼. Ð¦Ðµ Ð²ÐºÐ»ÑŽÑ‡Ð°Ñ” Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸ XP, ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–ÑŽ Ñ„Ð»Ð¾Ñ‚Ñƒ, ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ, Ð¼Ð¾Ð±Ñ–Ð»ÑŒÐ½Ð¸Ð¹ Intel, ÑƒÐ½Ð¸ÐºÐ½ÐµÐ½Ð½Ñ Ð·Ð°Ð³Ñ€Ð¾Ð·, Ð½Ð°Ð·Ð²Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð², Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¸Ð¹ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚, Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ—, Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ñ– Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚Ñƒ Ñ‡Ð¸ÑÐµÐ». ÐŸÐ°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Ð¶ÑƒÑ€Ð½Ð°Ð»ÑŽÐ²Ð°Ð½Ð½Ñ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ñ”Ñ‚ÑŒÑÑ, Ñ‰Ð¾Ð± Ð´Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð¶ÑƒÑ€Ð½Ð°Ð»ÑŽÐ²Ð°Ð½Ð½Ñ Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ— ÑÐºÐ¸Ð´Ð°Ð½Ð½Ñ.</t>
    <t id="9227">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚Ð¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ ÐºÐµÑˆ Ð´Ð»Ñ Ð²ÑÑ–Ñ… Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð²:</t>
    <t id="9228">ÐžÐ§Ð˜Ð¡Ð¢Ð˜Ð¢Ð˜ ÐšÐ•Ð¨</t>
    <t id="9327">ÐžÑ‡Ð¸Ñ‰Ð°Ñ” ÐºÐµÑˆ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð´Ð»Ñ Ð²ÑÑ–Ñ… Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð². Ð¦Ðµ Ð·Ð¼ÑƒÑÐ¸Ñ‚ÑŒ ÑƒÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð²Ð¸ÐºÐ¾Ð½ÑƒÐ²Ð°Ñ‚Ð¸ Ð½Ð¾Ð²Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð½Ð°ÑÑ‚ÑƒÐ¿Ð½Ð¾Ð³Ð¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ð¿Ð¾ÑˆÑƒÐºÑƒ. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ñ†Ðµ, ÑÐºÑ‰Ð¾ ÐºÐµÑˆ Ð²Ð¸Ð³Ð»ÑÐ´Ð°Ñ” Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¼ Ð°Ð±Ð¾ Ð¿Ð¾ÑˆÐºÐ¾Ð´Ð¶ÐµÐ½Ð¸Ð¼, Ð°Ð±Ð¾ ÑÐºÑ‰Ð¾ Ð²Ð¸ Ñ…Ð¾Ñ‡ÐµÑ‚Ðµ Ð¿Ñ€Ð¸Ð¼ÑƒÑÐ¾Ð²Ð¾ Ð¿Ð¾Ð²Ð½Ñ–ÑÑ‚ÑŽ Ð¾Ð½Ð¾Ð²Ð¸Ñ‚Ð¸ ÐºÐµÑˆ.</t>
    <t id="9229">Ð—Ð½Ñ–Ð¼Ñ–Ñ‚ÑŒ ÑƒÑÑ– Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ</t>
    <t id="9329">Ð—Ð²Ñ–Ð»ÑŒÐ½ÑÑ” Ð’Ð¡Ð† Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿Ð¾Ð»ÑŒÐ¾Ñ‚Ñƒ Ñ‚Ð° Ð¾Ñ‡Ð¸Ñ‰Ð°Ñ” Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ð¸Ð¹ Ð¿ÐµÑ€ÐµÑ…Ñ–Ð´Ð½Ð¸Ð¹ ÑÑ‚Ð°Ð½. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ñ†Ðµ, ÑÐºÑ‰Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð·Ð°ÑÑ‚Ñ€ÑÐ³Ð»Ð¸ Ð½Ð° Â«ÐŸÐ¾ÑˆÑƒÐºÑƒ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Â» Ñ‡ÐµÑ€ÐµÐ· Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ñ– Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð·Ñ– ÑÑ‚Ð°Ñ€Ð¸Ñ… Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ. Ð¦Ðµ Ð¼Ð¾Ð¶Ðµ Ð¿ÐµÑ€ÐµÑ€Ð²Ð°Ñ‚Ð¸ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸.</t>
    <t id="9290">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ Dump Trade Hub:</t>
    <t id="9291">Ð”Ð£ÐœÐŸ</t>
    <t id="9390">ÐŸÐ¾ÐºÐ°Ð·ÑƒÑ” Ð¾Ð´Ð½Ð¾Ñ€Ð°Ð·Ð¾Ð²Ð¸Ð¹ Ð·Ð½Ñ–Ð¼Ð¾Ðº Ñ†ÐµÐ½Ñ‚Ñ€Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð¾Ð³Ð¾ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ñ†ÐµÐ½Ñ‚Ñ€Ñƒ (Ñ‡ÐµÑ€Ð³Ð¸ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° + ÑÑ‚Ð°Ñ‚ÑƒÑ Ð¾ÑÑ‚Ð°Ð½Ð½ÑŒÐ¾Ð³Ð¾ Ð·Ð°Ð¿Ð¸Ñ‚Ñƒ Ð½Ð° Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð½Ñ) Ñƒ Ð¶ÑƒÑ€Ð½Ð°Ð»Ñ– Ñ‚Ð° ÑÐº ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ.</t>
    <t id="9292">Ð”Ð°Ð¼Ð¿ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ ÐºÐµÑˆÑƒ (ÐŸÐžÐ’ÐÐ˜Ð™):</t>
    <t id="9293">Ð”ÐÐœÐŸ ÐšÐ•Ð¨</t>
    <t id="9392">ÐŸÐžÐ’ÐÐ˜Ð™ Ð´Ð°Ð¼Ð¿ ÐºÐµÑˆÑƒ (Ð¼Ð¾Ð¶Ðµ Ð±ÑƒÑ‚Ð¸ Ð²ÐµÐ»Ð¸Ñ‡ÐµÐ·Ð½Ð¸Ð¼). Ð—Ð°Ð¿Ð¸ÑÑƒÑ” Ð²ÑÑ– Ð·Ð°Ð¿Ð¸ÑÐ¸ ÐºÐµÑˆÑƒ Ð´Ð¾ DebugLog Ñ‡Ð°ÑÑ‚Ð¸Ð½Ð°Ð¼Ð¸. ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ Ñ‰Ðµ Ñ€Ð°Ð·, Ñ‰Ð¾Ð± ÑÐºÐ°ÑÑƒÐ²Ð°Ñ‚Ð¸.</t>
    <t id="9294">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚Ð¸ Ð±Ñ€Ð¾Ð½ÑŽÐ²Ð°Ð½Ð½Ñ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÑƒ:</t>
    <t id="9295">Ð¯Ð¡ÐÐž</t>
    <t id="9394">ÐžÑ‡Ð¸Ñ‰Ð°Ñ” Ð²ÑÑ– Ð°ÐºÑ‚Ð¸Ð²Ð½Ñ– Ð±Ñ€Ð¾Ð½ÑŽÐ²Ð°Ð½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ñ†Ðµ, ÑÐºÑ‰Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð·Ð°ÑÑ‚Ñ€ÑÐ³Ð»Ð¸ Ð² Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ– Ð·Ð°ÐºÑ–Ð½Ñ‡ÐµÐ½Ð½Ñ Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ñƒ Ð´Ñ–Ñ— Ð·Ð°Ñ€ÐµÐ·ÐµÑ€Ð²Ð¾Ð²Ð°Ð½Ð¸Ñ… ÑƒÐ³Ð¾Ð´, Ð°Ð±Ð¾ ÑÐºÑ‰Ð¾ Ñ‚Ð°Ð±Ð»Ð¸Ñ†Ñ Ñ€ÐµÐ·ÐµÑ€Ð²ÑƒÐ²Ð°Ð½Ð½Ñ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð° Ð¿Ñ–ÑÐ»Ñ Ð·Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ñ€Ð¾Ð³Ð¾ Ð·Ð±ÐµÑ€ÐµÐ¶ÐµÐ½Ð½Ñ.</t>
    <t id="9230">ÐŸÑ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ</t>
    <t id="9231">Ð—Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ñ— Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸:</t>
    <t id="9232">Ð—Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð¿Ñ–Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¶ÐµÐ½Ð½Ñ:</t>
    <t id="9233">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð²:</t>
    <t id="9234">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´ Ð´Ð»Ñ Ð¿Ð¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ:</t>
    <t id="9235">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€:</t>
    <t id="9236">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€:</t>
    <t id="9237">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ Ð½Ð° Ð¿Ð¾ÑÑƒÐ´ Ð´Ð»Ñ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ð¾ÑÑ‚Ñ–:</t>
    <t id="9238">ÐŸÐ¾Ñ€Ñ–Ð³ Ñ€Ð°Ð½Ð½ÑŒÐ¾Ð³Ð¾ Ð²Ð¸Ñ…Ð¾Ð´Ñƒ:</t>
    <t id="9241">Ð†Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð·Ñ€Ñ–Ð·Ñƒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ— Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ–:</t>
    <t id="9266">TTL Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ:</t>
    <t id="9263">Ð Ð¾Ð·Ð¼Ñ–Ñ€ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð³Ð¾ Ð±Ð»Ð¾ÐºÑƒ:</t>
    <t id="9239">Ð¤Ð¾Ñ€Ð¼Ð°Ñ‚ Ñ‡Ð¸ÑÐ»Ð°</t>
    <t id="9240">Ð¡Ñ‚Ð¸Ð»ÑŒ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚Ñƒ:</t>
    <t id="9242">Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ ÑÑƒÑ„Ñ–ÐºÑ Ðœ</t>
    <t id="9243">ÐŸÐ¾Ñ€Ð¾Ð³Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑÑƒÑ„Ñ–ÐºÑÐ° M:</t>
    <t id="9244">Ð½Ñ–Ð¼ÐµÑ†ÑŒÐºÐ° (123.456,78)</t>
    <t id="9245">Ð°Ð½Ð³Ð»Ñ–Ð¹ÑÑŒÐºÐ° (123 456,78)</t>
    <t id="9510">Ð¡Ð¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÐµÐ½Ð½Ñ Ñ€Ñ–Ð²Ð½Ñ:</t>
    <t id="9511">ÐŸÐ¾Ð¿ÐµÑ€ÐµÐ´Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ñ–ÑÑ‚ÑŒ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ:</t>
    <t id="9512">Ð¡Ð¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ:</t>
    <t id="9513">Ð—Ð²Ñ–Ñ‚Ð¸ Ð¿Ñ€Ð¾ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº:</t>
    <t id="9514">Ð Ð¸Ð½ÐºÐ¾Ð²Ñ– ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ:</t>
    <t id="9515">ÐžÐ½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ:</t>
    <t id="9516">Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ Ð»Ð¸ÑˆÐµ Ð²Ð°Ð½Ñ–Ð»ÑŒ XP</t>
    <t id="9610">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð±Ð¾ Ð²Ð¸Ð¼ÐºÐ½ÑƒÑ‚Ð¸ ÑÐ¿Ð»Ð¸Ð²Ð°ÑŽÑ‡Ñ– ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÐµÐ½Ð½Ñ Ñ€Ñ–Ð²Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ Ð² Ñ–Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹ÑÑ– Ð³Ñ€Ð°Ð²Ñ†Ñ.</t>
    <t id="9611">ÐŸÐ¾Ð¿ÐµÑ€ÐµÐ´Ð¶ÐµÐ½Ð½Ñ, ÐºÐ¾Ð»Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼ Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ðµ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÑ…Ð¾Ð´Ñƒ Ð½Ð° Ð½Ð°ÑÑ‚ÑƒÐ¿Ð½Ð¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ.</t>
    <t id="9612">Ð¡Ð¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ, ÐºÐ¾Ð»Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð¸ Ð·Ð°Ð²ÐµÑ€ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ñ‚Ð° Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÑƒÑŽÑ‚ÑŒÑÑ Ð² Ð·Ð²Ð°Ð½Ð½Ñ–.</t>
    <t id="9613">ÐŸÐµÑ€Ñ–Ð¾Ð´Ð¸Ñ‡Ð½Ñ– Ð¿Ñ–Ð´ÑÑƒÐ¼ÐºÐ¸ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ (Ð¿Ñ€Ð¾ÑÑ‚Ñ– Ñ‚Ð° Ð²Ð¸Ñ‡ÐµÑ€Ð¿Ð½Ñ– Ð·Ð²Ñ–Ñ‚Ð¸).</t>
    <t id="9614">Ð’Ð¸ÐºÐ»ÑŽÑ‡Ð½Ñ– Ñ€Ð¸Ð½ÐºÐ¾Ð²Ñ– Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚Ñ– Ñ‚Ð° ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ Ð²Ð¸ÑÐ¾ÐºÐ¾Ñ†Ñ–Ð½Ð½Ñ– ÑƒÐ³Ð¾Ð´Ð¸.</t>
    <t id="9615">ÐŸÐ¾Ð²Ñ–Ð´Ð¾Ð¼Ð»ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–ÑŽ Ñ„Ð»Ð¾Ñ‚Ñƒ Ñ‚Ð° Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ñ‚ÑƒÑÑƒ.</t>
    <t id="9616">Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ pilot.skill.piloting Ñ– Ð²Ð¸Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ GT XP progression/caps.</t>
    <t id="9246">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° Ð¿Ñ€Ð¾ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð²Ñ–Ñ‚Ñƒ:</t>
    <t id="9247">Ð§Ð°ÑÑ‚Ð¾Ñ‚Ð° Ð²Ð¸Ñ‡ÐµÑ€Ð¿Ð½Ð¸Ñ… Ð·Ð²Ñ–Ñ‚Ñ–Ð²:</t>
    <t id="9248">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð² Ñƒ ÐºÐµÑˆÑ–:</t>
    <t id="9249">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð² Ñƒ Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ–:</t>
    <t id="9340">Ð’Ð¸Ð±ÐµÑ€Ñ–Ñ‚ÑŒ Ñ„Ð¾Ñ€Ð¼Ð°Ñ‚ Ñ‡Ð¸ÑÐ»Ð°: Ð½Ñ–Ð¼ÐµÑ†ÑŒÐºÐ° Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” '.' Ð´Ð»Ñ Ñ‚Ð¸ÑÑÑ‡ Ñ– ',' Ð´Ð»Ñ Ð´ÐµÑÑÑ‚ÐºÐ¾Ð²Ð¸Ñ… Ð·Ð½Ð°ÐºÑ–Ð² (123.456,78), Ð°Ð½Ð³Ð»Ñ–Ð¹ÑÑŒÐºÐ° Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” ',' Ð´Ð»Ñ Ñ‚Ð¸ÑÑÑ‡ Ñ– '.' Ð´Ð»Ñ Ð´ÐµÑÑÑ‚ÐºÐ¾Ð²Ð¸Ñ… Ð·Ð½Ð°ÐºÑ–Ð² (123 456,78)</t>
    <t id="9342">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ ÑÑƒÑ„Ñ–ÐºÑ M Ð´Ð»Ñ Ñ‡Ð¸ÑÐµÐ», Ñ‰Ð¾ Ð¿ÐµÑ€ÐµÐ²Ð¸Ñ‰ÑƒÑŽÑ‚ÑŒ Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ (Ð½Ð°Ð¿Ñ€Ð¸ÐºÐ»Ð°Ð´, 1,0 M Ð·Ð°Ð¼Ñ–ÑÑ‚ÑŒ 1 000 000)</t>
    <t id="9343">ÐŸÐ¾Ñ€Ñ–Ð³ Ð´Ð»Ñ ÑÑƒÑ„Ñ–ÐºÑÐ° Ðœ. Ð§Ð¸ÑÐ»Ð° Ð²Ð¸Ñ‰Ðµ Ñ†ÑŒÐ¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð²Ñ–Ð´Ð¾Ð±Ñ€Ð°Ð¶Ð°Ñ‚Ð¸Ð¼ÑƒÑ‚ÑŒÑÑ Ð· ÑÑƒÑ„Ñ–ÐºÑÐ¾Ð¼ M (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 999 999)</t>
    <t id="9346">ÐŸÐµÑ€Ñ–Ð¾Ð´Ð¸Ñ‡Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾ÑÑ‚Ð¾Ð³Ð¾ Ð·Ð²Ñ–Ñ‚Ñƒ (ÑÐ¿Ð»Ð¸Ð²Ð°ÑŽÑ‡Ðµ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ): 0-30 Ñ…Ð²Ð¸Ð»Ð¸Ð½ (0 = Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾ - Ð¿Ñ€Ð¾ÑÑ‚Ñ– Ð·Ð²Ñ–Ñ‚Ð¸ Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1 Ñ…Ð²Ð¸Ð»Ð¸Ð½Ð°)</t>
    <t id="9347">ÐŸÐµÑ€Ñ–Ð¾Ð´Ð¸Ñ‡Ð½Ñ–ÑÑ‚ÑŒ ÐºÐ¾Ð¼Ð¿Ð»ÐµÐºÑÐ½Ð¾Ð³Ð¾ Ð·Ð²Ñ–Ñ‚Ñƒ (Ð·Ð°Ð¿Ð¸Ñ Ñƒ Ð¶ÑƒÑ€Ð½Ð°Ð»Ñ–): 0-60 Ñ…Ð²Ð¸Ð»Ð¸Ð½ (0 = Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾ - ÐºÐ¾Ð¼Ð¿Ð»ÐµÐºÑÐ½Ñ– Ð·Ð²Ñ–Ñ‚Ð¸ Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 30 Ñ…Ð²Ð¸Ð»Ð¸Ð½)</t>
    <t id="9398">Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÐ¹Ñ‚Ðµ GT Credits Due Override</t>
    <t id="9399">Ð—Ð°Ð¼Ñ–Ð½Ñ–Ñ‚ÑŒ Ð°Ð±Ð¾ Ð´Ð¾Ð¿Ð¾Ð²Ð½Ñ–Ñ‚ÑŒ Ñ€ÑÐ´Ð¾Ðº Â«CR due from tradesÂ» Ð¿Ñ€Ð¾Ð³Ð½Ð¾Ð·Ð¾Ð²Ð°Ð½Ð¸Ð¼ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½ÑÐ¼ GT Ñƒ Ñ‚Ð¾Ð¼Ñƒ ÑÐ°Ð¼Ð¾Ð¼Ñƒ ÑÐ»Ð¾Ñ‚Ñ– Ñ–Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹ÑÑƒ ÐºÐ¾Ñ€Ð¸ÑÑ‚ÑƒÐ²Ð°Ñ‡Ð°.</t>
    <t id="9331">Ð—Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð¼Ñ–Ð¶ Ð¿Ð°Ñ€Ñ‚Ñ–ÑÐ¼Ð¸ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ Ð¿Ð¾ÑˆÑƒÐºÑƒ (1-500 Ð¼Ñ). Ð‘Ñ–Ð»ÑŒÑˆ Ð²Ð¸ÑÐ¾ÐºÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 120 Ð¼Ñ. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð² Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð¼Ñƒ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ñ– Ñ‚Ð° Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ð°Ñ†Ñ–Ñ— Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… ÑÐ¿Ð¸ÑÐºÑ–Ð².</t>
    <t id="9332">Ð—Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð¼Ñ–Ð¶ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ°Ð¼Ð¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð² ÑÐºÑ€Ð¸Ð¿Ñ‚Ñ– AI (1-500 Ð¼Ñ). Ð‘Ñ–Ð»ÑŒÑˆ Ð²Ð¸ÑÐ¾ÐºÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÑƒ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 50 Ð¼Ñ. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ Ð· ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸ MD.</t>
    <t id="9333">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð², ÑÐºÑ– Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð²Ð¸ÐºÐ¾Ð½ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¾ (1-10). ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð² Ñ‡ÐµÑ€Ð·Ñ–. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑˆÑƒÐºÐ°ÑŽÑ‚ÑŒ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ ÑÐ¿Ñ€Ð¸Ñ‡Ð¸Ð½Ð¸Ñ‚Ð¸ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ–. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9334">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´ Ð´Ð»Ñ Ð¿Ð¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ Ð· Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² ÐºÐµÑˆÑ– (1-100). Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð½Ð°Ð´Ð°ÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ñ–Ð² Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸ ÐºÐµÑˆÑƒ. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ Ð¶Ð¸Ñ‚Ñ‚Ñ”Ð·Ð´Ð°Ñ‚Ð½Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 20.</t>
    <t id="9335">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€ Ð´Ð»Ñ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ð¿Ð¾ÑˆÑƒÐºÑƒ (5-100). Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð²Ñ€Ð°Ñ…Ð¾Ð²ÑƒÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 20.</t>
    <t id="9336">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´ Ð½Ð° Ð²Ð¸Ñ€Ñ–Ð± Ð¿Ñ€Ð¸ Ð¿Ð°ÐºÐµÑ‚Ð½Ñ–Ð¹ Ð¾Ð±Ñ€Ð¾Ð±Ñ†Ñ– (5-100). Ð‘Ñ–Ð»ÑŒÑˆ Ð²Ð¸ÑÐ¾ÐºÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ÑŒ Ð·Ð±Ñ–Ð»ÑŒÑˆÐ¸Ñ‚Ð¸ ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´ Ð½Ð° Ð²Ð¸Ñ€Ñ–Ð±, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 20.</t>
    <t id="9337">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€ Ð´Ð»Ñ ÑƒÐ·Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ Ð² Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð¼Ñƒ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ñ– (5-100). Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð²Ñ€Ð°Ñ…Ð¾Ð²ÑƒÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 20.</t>
    <t id="9338">ÐŸÐ¾Ñ€Ñ–Ð³ Ñ€Ð°Ð½Ð½ÑŒÐ¾Ð³Ð¾ Ð²Ð¸Ñ…Ð¾Ð´Ñƒ Ð´Ð»Ñ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ñ— Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸ (100-10000). ÐšÐ¾Ð»Ð¸ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾ Ñ‚Ð°ÐºÑƒ ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑƒÐ³Ð¾Ð´, Ð¿Ð°ÐºÐµÑ‚Ð½Ð° Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ° Ð¿Ñ€Ð¸Ð¿Ð¸Ð½ÑÑ”Ñ‚ÑŒÑÑ Ñ€Ð°Ð½Ñ–ÑˆÐµ, Ñ‰Ð¾Ð± Ð·Ð°Ð¾Ñ‰Ð°Ð´Ð¸Ñ‚Ð¸ Ð¦ÐŸ. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ ÑƒÐ³Ð¾Ð´, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð²Ð¸Ñ…Ð¾Ð´ÑÑ‚ÑŒ Ñ€Ð°Ð½Ñ–ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð²Ñ– ÑƒÐ³Ð¾Ð´Ð¸. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 2000.</t>
    <t id="9341">Ð†Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð·Ñ€Ñ–Ð·Ñƒ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ Ñƒ Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– Ð² Ð¼Ñ–Ð»Ñ–ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (5-2000 Ð¼Ñ). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»ÑŽÑ”, ÑÐº Ñ‡Ð°ÑÑ‚Ð¾ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ð¾Ñ‡Ð¸Ð½Ð°Ñ‚Ð¸ÑÑ ÑÐµÐ³Ð¼ÐµÐ½Ñ‚Ð¸ Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¸Ñ… Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ÑŒ ÑˆÐ²Ð¸Ð´ÑˆÐµ Ð·Ð±Ð¸Ñ€Ð°Ñ‚Ð¸ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ—, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¦ÐŸ. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÑƒ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ–. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 500 Ð¼Ñ.</t>
    <t id="9363">Ð Ð¾Ð·Ð¼Ñ–Ñ€ Ð±Ð»Ð¾ÐºÑƒ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ñ— Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸ (5-20). ÐžÐ±Ñ€Ð¾Ð±Ð»ÑÑ” ÐºÐ¾Ð¼Ð±Ñ–Ð½Ð°Ñ†Ñ–Ñ— chunkSizeÃ—chunkSize Ð½Ð° ÑˆÐ¼Ð°Ñ‚Ð¾Ðº (Ð½Ð°Ð¿Ñ€Ð¸ÐºÐ»Ð°Ð´, 5Ã—5 = 25 ÐºÐ¾Ð¼Ð±Ñ–Ð½Ð°Ñ†Ñ–Ð¹). Ð‘Ñ–Ð»ÑŒÑˆÑ– Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚Ð¸ Ð¿Ð¾ÐºÑ€Ð°Ñ‰ÑƒÑŽÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ½Ñƒ Ð·Ð´Ð°Ñ‚Ð½Ñ–ÑÑ‚ÑŒ, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¦ÐŸ Ð½Ð° Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚. ÐœÐµÐ½ÑˆÑ– Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚Ð¸ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¦ÐŸ, Ð°Ð»Ðµ Ð²Ð¸Ð¼Ð°Ð³Ð°ÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÐµÐ½ÑŒ. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 5.</t>
    <t id="9348">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ð¾ÑˆÑƒÐºÑ–Ð² Ñƒ ÐºÐµÑˆÑ–, ÑÐºÑ– Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð²Ð¸ÐºÐ¾Ð½ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¾ (1-20). ÐŸÐ¾ÑˆÑƒÐº Ñƒ ÐºÐµÑˆÑ– ÑˆÐ²Ð¸Ð´ÐºÐ¸Ð¹ Ñ– Ð´ÐµÑˆÐµÐ²Ð¸Ð¹; Ð½Ð¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð¼ÐµÐ½ÑˆÐ¸Ñ‚Ð¸ Ð²Ð¸Ð±ÑƒÑ… Ð¿Ñ–Ð´ Ð²ÐµÐ»Ð¸Ñ‡ÐµÐ·Ð½Ð¸Ð¼Ð¸ Ñ„Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 2.</t>
    <t id="9349">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¶Ð¸Ð²Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð², ÑÐºÑ– Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð²Ð¸ÐºÐ¾Ð½ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¾ (1-10). Ð–Ð¸Ð²Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸ Ñ–Ð½Ñ‚ÐµÐ½ÑÐ¸Ð²Ð½Ð¾ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑŽÑ‚ÑŒ Ð¦ÐŸ, Ñ‚Ð¾Ð¼Ñƒ Ð½Ð¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¦ÐŸ, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð² Ñ‡ÐµÑ€Ð·Ñ–. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑˆÑƒÐºÐ°ÑŽÑ‚ÑŒ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ ÑÐ¿Ñ€Ð¸Ñ‡Ð¸Ð½Ð¸Ñ‚Ð¸ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ–. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9264">Ð Ð¾Ð·Ð¼Ñ–Ñ€ Ð±Ð»Ð¾ÐºÑƒ Ð·Ð°Ð¿Ð¸Ñ‚Ñƒ ÐºÐµÑˆÑƒ:</t>
    <t id="9265">Live Offer Append Chunk Size:</t>
    <t id="9364">Ð—Ð°Ð¿Ð¸ÑÐ¸ ÐºÐµÑˆÑƒ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÑÑŽÑ‚ÑŒÑÑ Ð½Ð° Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚ (10-200). ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ð¾ÑˆÐ¸Ñ€ÑŽÑŽÑ‚ÑŒ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÑƒ ÐºÐµÑˆÑƒ Ð½Ð° Ð±Ñ–Ð»ÑŒÑˆÐµ ÐºÐ°Ð´Ñ€Ñ–Ð² (Ð±Ñ–Ð»ÑŒÑˆ Ð¿Ð»Ð°Ð²Ð½Ð¾), Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð±Ñ–Ð»ÑŒÑˆÐ¸Ñ‚Ð¸ Ñ‡Ð°Ñ Ð´Ð»Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ ÐºÐµÑˆÐ¾Ð²Ð°Ð½Ð¾Ñ— ÑƒÐ³Ð¾Ð´Ð¸. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 10.</t>
    <t id="9365">ÐŸÑ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ— Ð´Ð¾Ð´Ð°ÑŽÑ‚ÑŒÑÑ Ð½Ð° Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚ Ð´Ð¾Ð´Ð°Ð²Ð°Ð½Ð½Ñ (50-2000). ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ñ€Ð¾Ð±Ð¾Ñ‚Ñƒ Ð· Ð´Ð¾Ð´Ð°Ð²Ð°Ð½Ð½ÑÐ¼ ÑÐ¿Ð¸ÑÐºÑƒ Ð´Ð»Ñ ÐºÐ¾Ð¶Ð½Ð¾Ð³Ð¾ ÐºÐ°Ð´Ñ€Ñƒ (Ð±Ñ–Ð»ÑŒÑˆ Ð¿Ð»Ð°Ð²Ð½Ð¾), Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ ÑƒÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½Ð¸Ñ‚Ð¸ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ–. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 200.</t>
    <t id="9366">Ð§Ð°Ñ Ð¶Ð¸Ñ‚Ñ‚Ñ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (60-7200). Ð¯ÐºÑ‰Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑŽ Ð·Ð°Ð±Ð¾Ñ€Ð¾Ð½ÐµÐ½Ð¾ Ñ‡ÐµÑ€ÐµÐ· Â«Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ð¸Ð¹ Ð¿Ð¾ÑˆÑƒÐº ÑƒÐ¶Ðµ Ñ‚Ñ€Ð¸Ð²Ð°Ñ”Â» Ð´Ð¾Ð²ÑˆÐµ Ñ†ÑŒÐ¾Ð³Ð¾ Ñ‡Ð°ÑÑƒ, GT ÑÐ°Ð¼Ð¾Ð²Ñ–Ð´Ð½Ð¾Ð²Ð¸Ñ‚ÑŒÑÑ ÑˆÐ»ÑÑ…Ð¾Ð¼ Ð¾Ñ‡Ð¸Ñ‰ÐµÐ½Ð½Ñ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ñ‚Ð° Ð·Ð½ÑÑ‚Ñ‚Ñ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 600 Ñ.</t>
    <t id="9370">Ðœ'ÑÐºÐ¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ð¿Ñ€Ð¾Ñ‚Ð¸Ñ‚Ð¸ÑÐºÑƒ Ð¿Ð°Ñ€Ñ‚Ñ–Ñ—:</t>
    <t id="9371">Ð–Ð¾Ñ€ÑÑ‚ÐºÐ¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ð¿Ñ€Ð¾Ñ‚Ð¸Ñ‚Ð¸ÑÐºÑƒ Ð¿Ð°Ñ€Ñ‚Ñ–Ñ—:</t>
    <t id="9372">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¸ Ð½Ð° Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚:</t>
    <t id="9373">Home Refresh Cooldown:</t>
    <t id="9374">Ð‘Ð°Ð·Ð° ÐºÐµÑˆÑƒÐ²Ð°Ð½Ð½Ñ Miss Cooldown:</t>
    <t id="9375">Ð†Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ°:</t>
    <t id="9376">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð·Ð°Ð¿Ð¸Ñ‚Ñ–Ð² Ð½Ð° ÐºÐµÑˆ-Ð¿Ð°Ð¼â€™ÑÑ‚ÑŒ Ð½Ð° Ð¾Ð´Ð¸Ð½ Ñ‚Ð¸Ðº:</t>
    <t id="9377">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÐµÐ½ÑŒ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð·Ð° Ñ‚Ð°ÐºÑ‚:</t>
    <t id="9378">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½ÑŒ Ð·Ð° Ñ‚Ð¸Ðº:</t>
    <t id="9379">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ–Ð² Ð½Ð° Ñ‚Ð¸Ðº:</t>
    <t id="9380">ÐœÐ°ÐºÑ. Ð¿Ñ€Ð¾Ð±ÑƒÐ´Ð¶ÐµÐ½Ð½Ñ Ð·Ð° Ñ‚Ð°ÐºÑ‚:</t>
    <t id="9381">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð·Ð°Ð¿Ð¸ÑÑ–Ð² Ð·Ð°Ð¿Ð¸Ñ‚Ñ–Ð² Ñƒ ÐºÐµÑˆÑ–:</t>
    <t id="9382">Ð—Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ñ– Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð²Ñ– ÑÐµÐºÑƒÐ½Ð´Ð¸:</t>
    <t id="9383">ÐŸÐ¾Ñ€Ð¾Ð³Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¾Ñ— Ñ‡ÐµÑ€Ð³Ð¸ Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ…:</t>
    <t id="9384">Ð¡ÐµÐºÑƒÐ½Ð´Ð¸ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ð½ÐµÐ²Ð´Ð°Ð»Ð¾Ñ— Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–:</t>
    <t id="9385">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¸Ñ… Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð²:</t>
    <t id="9386">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¸Ñ… Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð²:</t>
    <t id="9470">Ðœâ€™ÑÐºÐ¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ð´Ð»Ñ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð° (5-50). ÐšÐ¾Ð»Ð¸ Ð²Ñ–Ð´ÑÑ‚Ð°Ð²Ð°Ð½Ð½Ñ Ð´Ð¾ÑÑÐ³Ð°Ñ” Ñ†ÑŒÐ¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ, Ð¿Ð¾Ñ‡Ð¸Ð½Ð°Ñ” Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð·Ð²Ð¾Ñ€Ð¾Ñ‚Ð½Ð¸Ð¹ Ñ‚Ð¸ÑÐº, Ñ‰Ð¾Ð± ÑƒÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½Ð¸Ñ‚Ð¸ Ð½Ð¾Ð²Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¾Ð²Ñ– Ð·Ð°Ð¿Ð¸Ñ‚Ð¸. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑˆÐ²Ð¸Ð´ÑˆÐµ Ð²Ð¸ÐºÐ»Ð¸ÐºÐ°ÑŽÑ‚ÑŒ Ð·Ð²Ð¾Ñ€Ð¾Ñ‚Ð½Ð¸Ð¹ Ñ‚Ð¸ÑÐº (Ð±Ñ–Ð»ÑŒÑˆ ÐºÐ¾Ð½ÑÐµÑ€Ð²Ð°Ñ‚Ð¸Ð²Ð½Ð¸Ð¹). Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 10.</t>
    <t id="9471">Ð–Ð¾Ñ€ÑÑ‚ÐºÐ¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ð´Ð»Ñ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð³Ð¾ Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€Ð° (10-100). ÐšÐ¾Ð»Ð¸ Ð²Ñ–Ð´ÑÑ‚Ð°Ð²Ð°Ð½Ð½Ñ Ð´Ð¾ÑÑÐ³Ð°Ñ” Ñ†ÑŒÐ¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ, Ð½Ð¾Ð²Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¾Ð²Ñ– Ð·Ð°Ð¿Ð¸Ñ‚Ð¸ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– Ð±Ð»Ð¾ÐºÑƒÑŽÑ‚ÑŒÑÑ, Ð´Ð¾ÐºÐ¸ Ð²Ñ–Ð´ÑÑ‚Ð°Ð²Ð°Ð½Ð½Ñ Ð½Ðµ Ð·Ð¼ÐµÐ½ÑˆÐ¸Ñ‚ÑŒÑÑ. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑˆÐ²Ð¸Ð´ÑˆÐµ Ð±Ð»Ð¾ÐºÑƒÑŽÑ‚ÑŒ Ð¿Ð¾ÑˆÑƒÐº (Ð±Ñ–Ð»ÑŒÑˆ ÐºÐ¾Ð½ÑÐµÑ€Ð²Ð°Ñ‚Ð¸Ð²Ð½Ð¸Ð¹). Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 25.</t>
    <t id="9472">Ð¡ÐµÐºÑ‚Ð¾Ñ€Ð¸, Ð¾Ð±Ñ€Ð¾Ð±Ð»ÐµÐ½Ñ– Ð½Ð° Ñ„Ñ€Ð°Ð³Ð¼ÐµÐ½Ñ‚ Ñƒ ÐºÐ¾Ð»ÐµÐºÑ†Ñ–Ñ— Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¸Ñ… Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ (1-5). ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ñ€Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð»ÑÑŽÑ‚ÑŒ Ñ€Ð¾Ð±Ð¾Ñ‚Ñƒ Ð½Ð° Ð±Ñ–Ð»ÑŒÑˆÐµ ÐºÐ°Ð´Ñ€Ñ–Ð² (Ð±Ñ–Ð»ÑŒÑˆ Ð¿Ð»Ð°Ð²Ð½Ð¾), Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ ÑƒÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½Ð¸Ñ‚Ð¸ Ð·Ð±Ñ–Ñ€ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹. Ð’ÐµÐ»Ð¸ÐºÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ ÑÐ¿Ñ€Ð¸Ñ‡Ð¸Ð½Ð¸Ñ‚Ð¸ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ ÐºÐ°Ð´Ñ€Ñ–Ð². Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9473">Ð—Ð°Ñ€ÑÐ´ÐºÐ° Ð¿Ñ–ÑÐ»Ñ Ð·Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð½Ñ Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾Ð³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð° (10-120 ÑÐµÐºÑƒÐ½Ð´). Ð—Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°Ñ” Ð½Ð°Ð´Ð¼Ñ–Ñ€Ð½Ð¸Ð¼ Ð·Ð°Ð¿Ð¸Ñ‚Ð°Ð¼ Ð½Ð° Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ÑŒ Ñ‡Ð°ÑÑ‚Ñ–ÑˆÐµ Ð¾Ð½Ð¾Ð²Ð»ÑŽÐ²Ð°Ñ‚Ð¸, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¦ÐŸ. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°ÑÑ‚Ð¾Ñ‚Ñƒ Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð°Ñ‚Ñ€Ð¸Ð¼ÑƒÐ²Ð°Ñ‚Ð¸ Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ ÐºÐµÑˆÑƒ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 30 Ñ.</t>
    <t id="9474">Ð‘Ð°Ð·Ð¾Ð²Ð¸Ð¹ Ñ‡Ð°Ñ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð¿Ñ–ÑÐ»Ñ Ð¿Ñ€Ð¾Ð¼Ð°Ñ…Ñƒ ÐºÐµÑˆÑƒ Ð¿ÐµÑ€ÐµÐ´ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸Ð¼ Ð¿Ð¾ÑˆÑƒÐºÐ¾Ð¼ Ñƒ Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– (1-30 ÑÐµÐºÑƒÐ½Ð´). Ð—Ð°Ð¿Ð¾Ð±Ñ–Ð³Ð°Ñ” Ð½Ð°Ð´Ð¼Ñ–Ñ€Ð½Ð¸Ð¼ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸Ð¼ ÑÐ¿Ñ€Ð¾Ð±Ð°Ð¼. ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ñ–Ñ‚ÑŒ ÑÐ¿Ñ€Ð¾Ð±Ñƒ Ñ€Ð°Ð½Ñ–ÑˆÐµ, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÐ¸Ñ‚Ðµ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¦ÐŸ. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°ÑÑ‚Ð¾Ñ‚Ñƒ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸Ñ… ÑÐ¿Ñ€Ð¾Ð±, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð°Ñ‚Ñ€Ð¸Ð¼Ð°Ñ‚Ð¸ Ð¿Ð¾ÑˆÑƒÐº ÑƒÐ³Ð¾Ð´Ð¸. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 10 Ñ.</t>
    <t id="9475">Ð†Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¼Ñ–Ð¶ Ñ‚Ð°ÐºÑ‚Ð°Ð¼Ð¸ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° Ð² Ð¼Ñ–Ð»Ñ–ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (50-500 Ð¼Ñ). ÐšÐ¾Ð½Ñ‚Ñ€Ð¾Ð»ÑŽÑ”, ÑÐº Ñ‡Ð°ÑÑ‚Ð¾ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸Ðº Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑ” Ñ€Ð¾Ð±Ð¾Ñ‡Ñƒ Ñ‡ÐµÑ€Ð³Ñƒ. ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ Ñ‡Ð°ÑÑ‚Ñ–ÑˆÐµ, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð±Ñ–Ð»ÑŒÑˆÐ¸Ñ‚Ð¸ Ñ‡Ð°Ñ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð² Ñ‡ÐµÑ€Ð·Ñ–. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 100 Ð¼Ñ.</t>
    <t id="9476">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð·Ð°Ð¿Ð¸Ñ‚Ñ–Ð² Ð´Ð¾ ÐºÐµÑˆÑƒ, Ð·Ð°Ð¿ÑƒÑ‰ÐµÐ½Ð¸Ñ… Ð·Ð° Ñ‚Ð°ÐºÑ‚ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° (1-5). ÐžÐ±Ð¼ÐµÐ¶ÑƒÑ” ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð·Ð°Ð¿Ð¸Ñ‚Ñ–Ð² Ð´Ð¾ ÐºÐµÑˆÑƒ, Ñ‰Ð¾Ð± Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½ÑŽ ÐºÐ°Ð´Ñ€Ñ–Ð². ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¦ÐŸ, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¿Ð¾ÑˆÑƒÐº Ñƒ ÐºÐµÑˆÑ–. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¸Ð·Ð²ÐµÑÑ‚Ð¸ Ð´Ð¾ Ð·Ð°Ñ—ÐºÐ°Ð½ÑŒ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9477">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÐµÐ½ÑŒ Ð¿Ð¾ÑˆÑƒÐºÑƒ, Ð·Ð°Ð¿ÑƒÑ‰ÐµÐ½Ð¸Ñ… Ð·Ð° Ñ‚Ð°ÐºÑ‚ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° (1-5). ÐžÐ±Ð¼ÐµÐ¶ÑƒÑ” ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÐµÐ½Ð½Ñ, Ñ‰Ð¾Ð± Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½ÑŽ ÐºÐ°Ð´Ñ€Ñ–Ð². ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¦ÐŸ, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÑƒ Ð¿Ð¾ÑˆÑƒÐºÑƒ. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¸Ð·Ð²ÐµÑÑ‚Ð¸ Ð´Ð¾ Ð·Ð°Ñ—ÐºÐ°Ð½ÑŒ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9478">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½ÑŒ, Ð¾Ð±Ñ€Ð¾Ð±Ð»ÐµÐ½Ð¸Ñ… Ð·Ð° Ñ‚Ð°ÐºÑ‚ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° (1-5). ÐžÐ±Ð¼ÐµÐ¶ÑƒÑ” ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ, Ñ‰Ð¾Ð± Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½ÑŽ ÐºÐ°Ð´Ñ€Ñ–Ð². ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¦ÐŸ, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÑƒ Ñ‡ÐµÑ€Ð³Ð¸. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¸Ð·Ð²ÐµÑÑ‚Ð¸ Ð´Ð¾ Ð·Ð°Ñ—ÐºÐ°Ð½ÑŒ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9479">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ñ€Ð¾Ð±Ð¾Ñ‡Ð¸Ñ… ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ–Ð², Ð¾Ð±Ñ€Ð¾Ð±Ð»ÐµÐ½Ð¸Ñ… Ð·Ð° Ñ‚Ð°ÐºÑ‚ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° (1-5). ÐžÐ±Ð¼ÐµÐ¶ÑƒÑ” ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÐ¸ Ñ€Ð¾Ð±Ð¾Ñ‡Ð¾Ð³Ð¾ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð°, Ñ‰Ð¾Ð± Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ñ‚Ð¸ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½ÑŽ ÐºÐ°Ð´Ñ€Ñ–Ð². ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¦ÐŸ, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÑƒ Ñ‡ÐµÑ€Ð³Ð¸. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¸Ð·Ð²ÐµÑÑ‚Ð¸ Ð´Ð¾ Ð·Ð°Ñ—ÐºÐ°Ð½ÑŒ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9480">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ñ„Ñ–Ñ†Ñ–Ð°Ð½Ñ‚Ñ–Ð², Ñ€Ð¾Ð·Ð±ÑƒÐ´Ð¶ÐµÐ½Ð¸Ñ… Ð·Ð° Ð¾Ð´Ð¸Ð½ Ñ‚Ð°ÐºÑ‚ Ð¿Ð»Ð°Ð½ÑƒÐ²Ð°Ð»ÑŒÐ½Ð¸ÐºÐ° (1-10). ÐžÐ±Ð¼ÐµÐ¶ÑƒÑ” Ñ‡Ð°ÑÑ‚Ð¾Ñ‚Ñƒ Ð¿Ñ€Ð¾Ð±ÑƒÐ´Ð¶ÐµÐ½Ð½Ñ, Ñ‰Ð¾Ð± Ð·Ð°Ð¿Ð¾Ð±Ñ–Ð³Ñ‚Ð¸ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ°Ð¼ Ð¦ÐŸ, ÐºÐ¾Ð»Ð¸ Ð±Ð°Ð³Ð°Ñ‚Ð¾ Ð¾Ñ„Ñ–Ñ†Ñ–Ð°Ð½Ñ‚Ñ–Ð² ÑÑ‚Ð¾ÑÑ‚ÑŒ Ñƒ Ñ‡ÐµÑ€Ð·Ñ–. ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¦ÐŸ, Ð°Ð»Ðµ ÑÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½ÑŽÑŽÑ‚ÑŒ Ð¾Ð±Ñ€Ð¾Ð±ÐºÑƒ Ð¾Ñ„Ñ–Ñ†Ñ–Ð°Ð½Ñ‚Ð¾Ð¼. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ð±Ñ€Ð¾Ð±Ð»ÑÑŽÑ‚ÑŒÑÑ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¸Ð·Ð²ÐµÑÑ‚Ð¸ Ð´Ð¾ Ð·Ð°Ñ—ÐºÐ°Ð½ÑŒ. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 2.</t>
    <t id="9481">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð·Ð°Ð¿Ð¸ÑÑ–Ð² ÐºÐµÑˆÑƒ, Ð·Ð°Ð¿Ð¸Ñ‚ÑƒÐ²Ð°Ð½Ð¸Ñ… Ð½Ð° Ð¿Ð°ÐºÐµÑ‚ (1-200). ÐšÐµÑ€ÑƒÑ” Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ð¾Ð¼ Ð¿Ð°ÐºÐµÑ‚Ð° Ð·Ð°Ð¿Ð¸Ñ‚Ñ–Ð² ÐºÐµÑˆÑƒ. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¸ÑˆÐ²Ð¸Ð´ÑˆÑƒÑŽÑ‚ÑŒ Ð¿Ð¾ÑˆÑƒÐº Ñƒ ÐºÐµÑˆÑ–, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ ÐºÑ€Ð°Ñ‰Ñ– Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ñ—. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð²Ñ€Ð°Ñ…Ð¾Ð²ÑƒÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ ÐºÐµÑˆÐ¾Ð²Ð°Ð½Ð¸Ñ… ÑƒÐ³Ð¾Ð´, Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ñ‡Ð°Ñ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸. Ð¢Ð¸Ð¿Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: 50.</t>
    <t id="9482">ÐŸÐ¾Ñ€Ð¾Ð³Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (60-600). ÐšÐ¾Ð»Ð¸ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ ÑÑ‚Ð°Ð½ Ð¿Ð¾ÑˆÑƒÐºÑƒ ÑÑ‚Ð°Ñ€Ñ–ÑˆÐ¸Ð¹ Ð·Ð° Ñ†ÐµÐ¹, Ð²Ñ–Ð½ Ð²Ð²Ð°Ð¶Ð°Ñ”Ñ‚ÑŒÑÑ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¼ Ñ– Ð¾Ñ‡Ð¸Ñ‰Ð°Ñ”Ñ‚ÑŒÑÑ. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ñ‡Ð¸Ñ‰Ð°ÑŽÑ‚ÑŒ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¹ ÑÑ‚Ð°Ð½ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¿ÐµÑ€ÐµÑ€Ð¸Ð²Ð°Ñ‚Ð¸ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸. Ð‘Ñ–Ð»ÑŒÑˆ Ð²Ð¸ÑÐ¾ÐºÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ÑŒ Ñ‚Ñ€Ð¸Ð²Ð°Ð»Ñ–ÑˆÑ– Ð¿Ð¾ÑˆÑƒÐºÐ¸, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð°Ð»Ð¸ÑˆÐ¸Ñ‚Ð¸ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¹ ÑÑ‚Ð°Ð½. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 300 Ñ.</t>
    <t id="9483">ÐŸÐ¾Ñ€Ð¾Ð³Ð¾Ð²Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ñ… ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ñ–Ð² Ñ‡ÐµÑ€Ð³Ð¸ Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (30-300). Ð¯ÐºÑ‰Ð¾ ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸ Ñ‡ÐµÑ€Ð³Ð¸ ÑÑ‚Ð°Ñ€Ñ–ÑˆÑ–, Ð²Ð¾Ð½Ð¸ Ð²Ð²Ð°Ð¶Ð°ÑŽÑ‚ÑŒÑÑ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ð¼Ð¸ Ñ‚Ð° Ð²Ð¸Ð´Ð°Ð»ÑÑŽÑ‚ÑŒÑÑ. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¾Ñ‡Ð¸Ñ‰Ð°ÑŽÑ‚ÑŒ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ñ– ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸ ÑˆÐ²Ð¸Ð´ÑˆÐµ, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð²Ð¸Ð´Ð°Ð»ÑÑ‚Ð¸ Ð·Ð°ÐºÐ¾Ð½Ð½Ñ– ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸ Ð² Ñ‡ÐµÑ€Ð·Ñ–. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ÑŒ Ð´Ð¾Ð²ÑˆÐ¸Ð¹ Ñ‡Ð°Ñ Ñƒ Ñ‡ÐµÑ€Ð·Ñ–, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð°Ð»Ð¸ÑˆÐ¸Ñ‚Ð¸ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ñ– ÐµÐ»ÐµÐ¼ÐµÐ½Ñ‚Ð¸. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 60 Ñ.</t>
    <t id="9484">ÐÐµÐ²Ð´Ð°Ð»Ð¸Ð¹ Ñ‚ÐµÑ€Ð¼Ñ–Ð½ Ð´Ñ–Ñ— Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ð³Ð¾ ÐºÐµÑˆÑƒ Ð² ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (300-3600). ÐÐµÐ²Ð´Ð°Ð»Ñ– ÑƒÐ³Ð¾Ð´Ð¸ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°ÑŽÑ‚ÑŒÑÑ Ð² ÐºÐµÑˆÑ–, Ñ‰Ð¾Ð± ÑƒÐ½Ð¸ÐºÐ½ÑƒÑ‚Ð¸ Ð½ÐµÐ³Ð°Ð¹Ð½Ð¾Ñ— Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¾Ñ— ÑÐ¿Ñ€Ð¾Ð±Ð¸. ÐÐ¸Ð¶Ñ‡Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ñ‚ÐµÑ€Ð¼Ñ–Ð½ Ð´Ñ–Ñ— Ð½ÐµÐ²Ð´Ð°Ð»Ð¸Ñ… ÑƒÐ³Ð¾Ð´ Ð·Ð°ÐºÑ–Ð½Ñ‡ÑƒÑŽÑ‚ÑŒÑÑ Ñ€Ð°Ð½Ñ–ÑˆÐµ (Ð±Ñ–Ð»ÑŒÑˆÐµ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¸Ñ… ÑÐ¿Ñ€Ð¾Ð±), Ð°Ð»Ðµ Ð·Ð½Ð¸Ð¶ÑƒÑ”Ñ‚ÑŒÑÑ ÐµÑ„ÐµÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ ÐºÐµÑˆÑƒ. Ð‘Ñ–Ð»ÑŒÑˆ Ð²Ð¸ÑÐ¾ÐºÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°ÑŽÑ‚ÑŒÑÑ Ð² ÐºÐµÑˆÑ– Ð´Ð¾Ð²ÑˆÐµ (Ð¼ÐµÐ½ÑˆÐ° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ ÑÐ¿Ñ€Ð¾Ð±), Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð·Ð°Ñ‚Ñ€Ð¸Ð¼Ð°Ñ‚Ð¸ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ñ– ÑÐ¿Ñ€Ð¾Ð±Ð¸. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1800 Ñ (30 Ñ…Ð²Ð¸Ð»Ð¸Ð½).</t>
    <t id="9485">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¸Ñ… Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð² Ñƒ Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ– (1-10). Ð—Ð°Ð¿Ð°ÑÐ½Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸ Ð¾Ð±Ñ…Ð¾Ð´ÑÑ‚ÑŒ Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾Ð³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð°, Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‡Ð¸ ÐºÑ–Ð»ÑŒÐºÐ¾Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ Ð· Ð¾Ð´Ð½Ð¾Ð³Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾Ð³Ð¾ ÑÐµÐºÑ‚Ð¾Ñ€Ð° ÑˆÑƒÐºÐ°Ñ‚Ð¸ Ð¾Ð´Ð½Ð¾Ñ‡Ð°ÑÐ½Ð¾. ÐœÐµÐ½ÑˆÑ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð¼ÐµÐ½ÑˆÑƒÑŽÑ‚ÑŒ Ð½Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð½Ð° Ð¿Ñ€Ð¾Ñ†ÐµÑÐ¾Ñ€, Ð°Ð»Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ ÑƒÐ¿Ð¾Ð²Ñ–Ð»ÑŒÐ½Ð¸Ñ‚Ð¸ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ñ– Ð¿Ð¾ÑˆÑƒÐºÐ¸. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑŽÑ‚ÑŒ Ð±Ñ–Ð»ÑŒÑˆÐµ Ð¿Ð°Ñ€Ð°Ð»ÐµÐ»ÑŒÐ½Ð¸Ñ… Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ… Ð¿Ð¾ÑˆÑƒÐºÑ–Ð², Ð°Ð»Ðµ Ð·Ð±Ñ–Ð»ÑŒÑˆÑƒÑŽÑ‚ÑŒ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð°Ð½Ð½Ñ Ð¦ÐŸ. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 1.</t>
    <t id="9490">Ð—Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° ÑÐ¸Ð³Ð½Ð°Ð»Ñƒ Trade Found:</t>
    <t id="9590">Ð—Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° Ð¿ÐµÑ€ÐµÐ´ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð½ÑÐ¼ ÑÐ¸Ð³Ð½Ð°Ð»Ñƒ GT_Trade_Found ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÐ¼ Ñƒ Ð¼Ñ–Ð»Ñ–ÑÐµÐºÑƒÐ½Ð´Ð°Ñ… (10-1000 Ð¼Ñ). ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð·Ð°Ð²Ð¶Ð´Ð¸ Ñ‡ÐµÐºÐ°ÑŽÑ‚ÑŒ (Ð½Ð°Ð»Ð°ÑˆÑ‚Ð¾Ð²Ð°Ð½Ð° Ð·Ð°Ñ‚Ñ€Ð¸Ð¼ÐºÐ° + Ð±ÑƒÑ„ÐµÑ€ 5 Ð¼Ñ), Ð¿ÐµÑ€Ñˆ Ð½Ñ–Ð¶ Ð½Ð°Ð´ÑÐ¸Ð»Ð°Ñ‚Ð¸ Ð½Ð¾Ð²Ñ– Ð·Ð°Ð¿Ð¸Ñ‚Ð¸, Ñ‰Ð¾Ð± ÑƒÐ»Ð¾Ð²Ð¸Ñ‚Ð¸ Ð·Ð°Ñ‚Ñ€Ð¸Ð¼Ð°Ð½Ñ– ÑÐ¸Ð³Ð½Ð°Ð»Ð¸. Ð’Ð¸Ñ‰Ñ– Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ñ€Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð»ÑÑŽÑ‚ÑŒ ÑÐ¸Ð³Ð½Ð°Ð»Ð¸ Ð¼Ñ–Ð¶ ÐºÐ°Ð´Ñ€Ð°Ð¼Ð¸ Ð´Ð»Ñ Ð±Ñ–Ð»ÑŒÑˆ Ð¿Ð»Ð°Ð²Ð½Ð¾Ñ— Ñ€Ð¾Ð±Ð¾Ñ‚Ð¸. Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: 10 Ð¼Ñ.</t>
    <t id="8000">GalaxyTrader Ð¤Ð»Ð¾Ñ‚</t>
    <t id="8001">Ð£Ð¿Ñ€Ð°Ð²Ð»Ñ–Ð½Ð½Ñ Ñ„Ð»Ð¾Ñ‚Ð¾Ð¼ GalaxyTrader Ñ– ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ° Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð²</t>
    <t id="8002">ÐŸÐµÑ€ÐµÐ³Ð»ÑÐ´Ð°Ð¹Ñ‚Ðµ Ð²ÑÑ– Ð¿Ñ–Ð»Ð¾Ñ‚Ð½Ñ– Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¸ GalaxyTrader Ñ– ÐºÐµÑ€ÑƒÐ¹Ñ‚Ðµ Ð½Ð¸Ð¼Ð¸</t>
    <t id="8100">ID ÑÑƒÐ´Ð½Ð°</t>
    <t id="8101">ÐŸÑ–Ð»Ð¾Ñ‚</t>
    <t id="8102">ÐšÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ</t>
    <t id="8103">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ</t>
    <t id="8104">Ñ€Ð°Ð½Ð³</t>
    <t id="8105">Ð Ñ–Ð²ÐµÐ½ÑŒ</t>
    <t id="8106">XP</t>
    <t id="8107">Ð”Ð¾Ð²Ñ–Ñ‡Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº</t>
    <t id="8108">Ð Ð¾Ð·Ñ‚Ð°ÑˆÑƒÐ²Ð°Ð½Ð½Ñ</t>
    <t id="8109">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ Ð±Ð°Ð·Ð°</t>
    <t id="8110">ÐžÑÑ‚Ð°Ð½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ</t>
    <t id="8111">ÐŸÑ–Ð»Ð¾Ñ‚Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº</t>
    <t id="8112">ÐšÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº</t>
    <t id="8113">Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¹ Ð³Ñ€Ð°Ñ„</t>
    <t id="8200">ÐžÐ½Ð¾Ð²Ð¸Ñ‚Ð¸</t>
    <t id="8201">Ð•ÐºÑÐ¿Ð¾Ñ€Ñ‚ CSV</t>
    <t id="8202">Ð¡Ñ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÐ°</t>
    <t id="8203">ÐÐ°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ</t>
    <t id="8204">Ð”Ð¾Ð²Ñ–Ð´ÐºÐ°</t>
    <t id="8205">Ð—Ð°ÐºÑ€Ð¸Ñ‚Ð¸</t>
    <t id="8300">Ð’ÑÑ– Ð¿Ñ–Ð»Ð¾Ñ‚Ð¸</t>
    <t id="8301">Ð¢Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ</t>
    <t id="8302">ÐÐ°Ð²Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="8303">Ð¢ÐµÑ…Ð½Ñ–Ñ‡Ð½Ðµ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ð½Ð½Ñ</t>
    <t id="8304">ÐÐ°Ð´Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð° ÑÐ¸Ñ‚ÑƒÐ°Ñ†Ñ–Ñ</t>
    <t id="8305">ÐŸÐ¾Ñ‡Ð°Ñ‚ÐºÑ–Ð²Ñ†Ñ– (Lv 1-5)</t>
    <t id="8306">ÐŸÑ€Ð¾ÑÑƒÐ½ÑƒÑ‚Ð¸Ð¹ (Lv 6-11)</t>
    <t id="8307">Ð•ÐºÑÐ¿ÐµÑ€Ñ‚Ð¸ (Ñ€Ñ–Ð²ÐµÐ½ÑŒ 12+)</t>
    <t id="8308">10 Ð½Ð°Ð¹Ð±Ñ–Ð»ÑŒÑˆÐ¸Ñ… Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑ–Ð²</t>
    <t id="8350">Ð¡Ð¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð°:</t>
    <t id="8351">ID ÑÑƒÐ´Ð½Ð°</t>
    <t id="8352">Ð†Ð¼'Ñ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°</t>
    <t id="8353">Ð¢Ð¸Ð¿ ÑÑƒÐ´Ð½Ð°</t>
    <t id="8354">Ð¡Ñ‚Ð°Ñ‚ÑƒÑ</t>
    <t id="8355">Ñ€Ð°Ð½Ð³</t>
    <t id="8356">Ð Ñ–Ð²ÐµÐ½ÑŒ</t>
    <t id="8357">XP</t>
    <t id="8358">ÐŸÑ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº</t>
    <t id="8400">ÐÐµÐ¼Ð°Ñ” Ð·Ð°Ñ€ÐµÑ”ÑÑ‚Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð²</t>
    <t id="8401">Ð–Ð¾Ð´ÐµÐ½ Ð¿Ñ–Ð»Ð¾Ñ‚ Ð½Ðµ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð°Ñ” Ñ„Ñ–Ð»ÑŒÑ‚Ñ€Ñƒ</t>
    <t id="8402">Ð’ÑÑŒÐ¾Ð³Ð¾ Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð²:</t>
    <t id="8403">Ð—Ð°Ð³Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº Ñ„Ð»Ð¾Ñ‚Ñƒ:</t>
    <t id="8404">ÐžÑÑ‚Ð°Ð½Ð½Ñ” Ð¾Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ:</t>
    <t id="8405">ÐŸÐ¾ÑˆÑƒÐº Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð²...</t>
    <t id="8114">Ð¡ÐµÐºÑ‚Ð¾Ñ€</t>
    <t id="8320">ÐŸÐµÑ€ÐµÐ¹Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8321">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»ÑŒÐ½Ð° Ð½Ð°Ð·Ð²Ð°</t>
    <t id="8322">Ð’ÑÑ‚Ð°Ð½Ð¾Ð²Ð¸Ñ‚Ð¸ Ð½Ð°Ð·Ð²Ñƒ</t>
    <t id="8323">ÐžÑ‡Ð¸ÑÑ‚Ð¸Ñ‚Ð¸ Ð½Ð°Ð·Ð²Ñƒ</t>
    <t id="8324">Ð†Ð¼â€™Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾ ÑƒÑÐ¿Ñ–ÑˆÐ½Ð¾</t>
    <t id="8325">Ð†Ð¼'Ñ ÑƒÑÐ¿Ñ–ÑˆÐ½Ð¾ Ð²Ð¸Ð´Ð°Ð»ÐµÐ½Ð¾</t>
    <t id="8450">Ð’Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð¸Ñ‚Ð¸ Ð½Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="8451">Ð—Ð½ÑÑ‚Ð¸ Ñ€ÐµÑ”ÑÑ‚Ñ€Ð°Ñ†Ñ–ÑŽ</t>
    <t id="8452">ÐŸÑ€Ð¸Ð¼ÑƒÑÐ¾Ð²Ð¸Ð¹ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ</t>
    <t id="8453">Ð’Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð¸Ñ‚Ð¸ Ð² Ñ€ÐµÐ¼Ð¾Ð½Ñ‚</t>
    <t id="8454">ÐÐ°Ð´Ñ–ÑÐ»Ð°Ñ‚Ð¸ Ð´Ð¾ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="8455">Ð—ÑƒÐ¿Ð¸Ð½Ð¸Ñ‚Ð¸ Ð²ÑÑ– Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ</t>
    <t id="8456">Ð”Ñ–Ñ—</t>
    <t id="8500">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° Ñ–Ð´ÐµÐ½Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ‚Ð¾Ñ€Ð¾Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8501">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° Ð½Ð°Ð·Ð²Ð¾ÑŽ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°</t>
    <t id="8502">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° Ñ‚Ð¸Ð¿Ð¾Ð¼ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="8503">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° ÑÑ‚Ð°Ñ‚ÑƒÑÐ¾Ð¼</t>
    <t id="8504">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° Ñ€ÐµÐ¹Ñ‚Ð¸Ð½Ð³Ð¾Ð¼</t>
    <t id="8505">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° Ñ€Ñ–Ð²Ð½ÐµÐ¼</t>
    <t id="8506">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° XP</t>
    <t id="8507">ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ, Ñ‰Ð¾Ð± Ð²Ñ–Ð´ÑÐ¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð·Ð° Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÐ¾Ð¼ Ð·Ð° Ð²ÐµÑÑŒ Ð¿ÐµÑ€Ñ–Ð¾Ð´</t>
    <t id="8508">ÐžÐ½Ð¾Ð²Ð¸Ñ‚Ð¸ Ð´Ð°Ð½Ñ– Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð· ÑÐ¸ÑÑ‚ÐµÐ¼Ð¸ Ð¼Ñ–ÑÑ–Ñ—</t>
    <t id="8509">Ð•ÐºÑÐ¿Ð¾Ñ€Ñ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ Ð²Ð¸Ð³Ð»ÑÐ´ Ñƒ Ñ„Ð°Ð¹Ð» CSV</t>
    <t id="8510">ÐŸÐµÑ€ÐµÐ³Ð»ÑÐ´Ð°Ð¹Ñ‚Ðµ ÑÑ‚Ð°Ñ‚Ð¸ÑÑ‚Ð¸ÐºÑƒ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÑƒ Ñ‚Ð° Ð´Ñ–Ð°Ð³Ñ€Ð°Ð¼Ð¸</t>
    <t id="8511">ÐÐ°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸ Ð¼ÐµÐ½ÑŽ</t>
    <t id="8512">ÐŸÐ¾ÐºÐ°Ð·Ð°Ñ‚Ð¸ Ð´Ð¾Ð²Ñ–Ð´ÐºÑƒ Ñ‚Ð° ÐºÐ¾Ð¼Ð±Ñ–Ð½Ð°Ñ†Ñ–Ñ— ÐºÐ»Ð°Ð²Ñ–Ñˆ</t>
    <t id="8600">ÐŸÑ–Ð»Ð¾Ñ‚Ð½Ñ– Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¸ GalaxyTrader Ð½Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾</t>
    <t id="8601">Ð¡Ñ‚Ð²Ð¾Ñ€Ñ–Ñ‚ÑŒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð¸, Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ð²ÑˆÐ¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– GalaxyTrader, Ð°Ð±Ð¾ Ð·Ð°Ñ‡ÐµÐºÐ°Ð¹Ñ‚Ðµ, Ð´Ð¾ÐºÐ¸ Ð´Ð°Ð½Ñ– Ð·Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶Ð°Ñ‚ÑŒÑÑ.</t>
    <t id="9001">GT ÐŸÐµÑ€ÐµÐ¹Ð¼ÐµÐ½ÑƒÐ²Ð°Ñ‚Ð¸</t>
    <t id="9902">Ð’Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð¸Ñ‚Ð¸ Ð½Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="9903">Ð ÑƒÑ‡Ð½Ðµ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð² Ñ‡ÐµÑ€Ð·Ñ– Ð´Ð»Ñ %1. ÐŸÑ–Ð»Ð¾Ñ‚ Ñ€Ð¾Ð·Ð¿Ð¾Ñ‡Ð½Ðµ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð¿Ñ–ÑÐ»Ñ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¾Ð³Ð¾ Ñ†Ð¸ÐºÐ»Ñƒ.</t>
    <t id="9904">ÐÐ°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð² Ñ‡ÐµÑ€Ð·Ñ– Ð¿Ñ–ÑÐ»Ñ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¾Ð³Ð¾ Ñ†Ð¸ÐºÐ»Ñƒ</t>
    <t id="9905">ÐŸÑ–Ð»Ð¾Ñ‚ Ñ‡Ð¸ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ Ð½Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾</t>
    <t id="9906">AutoTraining ÑƒÐ²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾ - Ñ€ÑƒÑ‡Ð½Ð° Ñ‡ÐµÑ€Ð³Ð° Ð½Ðµ Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ð°</t>
    <t id="9907">ÐŸÑ–Ð»Ð¾Ñ‚ Ð½Ðµ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¾ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="9910">ÐÐºÐ°Ð´ÐµÐ¼Ñ–Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–</t>
    <t id="9911">Ð£Ñ‡ÐµÐ½ÑŒ (4 Ñ€Ñ–Ð²ÐµÐ½ÑŒ) - %1 / %2</t>
    <t id="9912">Ð¢Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†ÑŒ (7 Ñ€Ñ–Ð²ÐµÐ½ÑŒ) - %1 / %2</t>
    <t id="9913">ÐœÐ°Ð¹ÑÑ‚ÐµÑ€ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€ (Ñ€Ñ–Ð²ÐµÐ½ÑŒ 13) - %1 / %2</t>
    <t id="9920">ÐŸÑ–Ð»Ð¾Ñ‚ %1 Ð·Ð°Ñ€Ð°Ñ…Ð¾Ð²Ð°Ð½Ð¸Ð¹ Ð½Ð° ÐºÑƒÑ€Ñ ÐÐºÐ°Ð´ÐµÐ¼Ñ–Ñ— Ð´Ð»Ñ Ñ€Ñ–Ð²Ð½Ñ %2. Ð’Ð¸Ñ—Ð·Ð´ Ð´Ð¾ Ð½Ð°Ð¹Ð±Ð»Ð¸Ð¶Ñ‡Ð¾Ñ— Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ñ— ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—.</t>
    <t id="9921">ÐÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ ÐºÐ¾ÑˆÑ‚Ñ–Ð² Ð´Ð»Ñ Ñ†ÑŒÐ¾Ð³Ð¾ ÐºÑƒÑ€ÑÑƒ (Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ð¾ %1, Ð¼Ð°Ð¹Ñ‚Ðµ %2).</t>
    <t id="9922">ÐšÑƒÑ€Ñ Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ð¹ - Ð¿Ñ–Ð»Ð¾Ñ‚ %1 ÑƒÐ¶Ðµ Ð´Ð¾ÑÑÐ³ Ñ†ÑŒÐ¾Ð³Ð¾ Ñ€Ñ–Ð²Ð½Ñ Ð°Ð±Ð¾ Ð²Ð¸Ñ‰Ðµ.</t>
    <t id="9923">ÐŸÑ–Ð»Ð¾Ñ‚ %1 Ð·Ð°Ð¿Ð¸ÑÐ°Ð²ÑÑ Ð½Ð° ÐºÑƒÑ€Ñ Trading Academy Ñ€Ñ–Ð²Ð½Ñ %2 (Ð²Ð°Ñ€Ñ‚Ñ–ÑÑ‚ÑŒ: %3 Cr, Ñ‚Ñ€Ð¸Ð²Ð°Ð»Ñ–ÑÑ‚ÑŒ: %4 Ñ…Ð²) Ð½Ð° Ð±Ð¾Ñ€Ñ‚Ñƒ %5.</t>
    <t id="11011">Ð¡ÐµÑ€ÐµÐ´Ð½Ñ–Ð¹ ÑÑƒÐ´Ð½Ð¾Ð²Ð¸Ð¹ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT Apprentice</t>
    <t id="11012">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°, ÑÐºÐ° Ñ‚Ñ€Ð¾Ñ…Ð¸ Ð·Ð½Ð¸Ð¶ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð»Ñ Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° ÑÐµÑ€ÐµÐ´Ð½Ñ–Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -5% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="11013">Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ ÑÐµÑ€ÐµÐ´Ð½ÑŒÐ¾Ð³Ð¾ Ñ…Ð¾Ð´Ñƒ GT Apprentice</t>
    <t id="11014">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°, ÑÐºÐ° Ñ‚Ñ€Ð¾Ñ…Ð¸ Ð·Ð½Ð¸Ð¶ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ– Ð´Ð»Ñ Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° ÑÐµÑ€ÐµÐ´Ð½Ñ–Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -5% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ– Ñ€ÑƒÑ…Ñƒ.</t>
    <t id="11021">Ð’ÐµÐ»Ð¸ÐºÐ¸Ð¹ ÑÑƒÐ´Ð½Ð¾Ð²Ð¸Ð¹ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT Apprentice</t>
    <t id="11022">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°, Ñ‰Ð¾ Ð·Ð½Ð¸Ð¶ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð»Ñ Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -15% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="11023">Ð’ÐµÐ»Ð¸ÐºÐ¸Ð¹ Ñ…Ð¾Ð´Ð¾Ð²Ð¸Ð¹ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT Apprentice</t>
    <t id="11024">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°, ÑÐºÐ° Ð·Ð½Ð¸Ð¶ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ– Ð´Ð»Ñ Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -15% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ– Ñ€ÑƒÑ…Ñƒ.</t>
    <t id="11031">GT Ð ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ñ… ÑÑƒÐ´ÐµÐ½ ÑƒÑ‡Ð½ÐµÐ¼</t>
    <t id="11032">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°, ÑÐºÐ° Ð·Ð½Ð°Ñ‡Ð½Ð¾ Ð·Ð½Ð¸Ð¶ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð»Ñ Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -25% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="11033">GT Apprentice Capital Travel Reducer</t>
    <t id="11034">ÐœÐ¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°, ÑÐºÐ° Ð·Ð½Ð°Ñ‡Ð½Ð¾ Ð·Ð½Ð¸Ð¶ÑƒÑ” Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ– Ð´Ð»Ñ Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ð½Ð° Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»ÑÑ…. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -25% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ– Ñ€ÑƒÑ…Ñƒ.</t>
    <t id="12001">GT Basic Small Ship Enhancer</t>
    <t id="12002">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð½ÐµÐ²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÑÑƒÐ´ÐµÐ½ Ð· Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +3% ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="12003">GT Basic Small Travel Enhancer</t>
    <t id="12004">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð½ÐµÐ²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÑÑƒÐ´ÐµÐ½ Ð· Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +3% ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ–.</t>
    <t id="13001">GT Ð‘Ð°Ð·Ð¾Ð²Ð¸Ð¹ Ð²ÐµÐ»Ð¸ÐºÐ¸Ð¹ ÑÑƒÐ´Ð½Ð¾Ð²Ð¸Ð¹ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€</t>
    <t id="13002">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÑÑƒÐ´ÐµÐ½ Ð· Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -8% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="13003">GT Basic Large Travel Reducer</t>
    <t id="13004">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÑÑƒÐ´ÐµÐ½ Ð· Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -8% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ– Ñ€ÑƒÑ…Ñƒ.</t>
    <t id="14001">Ð‘Ð°Ð·Ð¾Ð²Ð¸Ð¹ ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ð¹ ÑÑƒÐ´Ð½Ð¾Ð²Ð¸Ð¹ Ñ€ÐµÐ´ÑƒÐºÑ‚Ð¾Ñ€ GT</t>
    <t id="14002">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -15% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="14003">GT Basic Capital Travel Reducer</t>
    <t id="14004">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»Ñ–Ð·Ð¾Ð²Ð°Ð½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð¾ÑÐ½Ð¾Ð²Ð½Ð¸Ð¼Ð¸ ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ¾Ð²Ð°Ð½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. -15% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ– Ñ€ÑƒÑ…Ñƒ.</t>
    <t id="15001">GT Expert Small Ship Enhancer</t>
    <t id="15002">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð½ÐµÐ²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +25% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="15003">GT Expert Small Travel Enhancer</t>
    <t id="15004">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð½ÐµÐ²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +25% ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ–.</t>
    <t id="16001">GT Expert Large Ship Enhancer</t>
    <t id="16002">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +15% ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ–, Ñ‚ÑÐ³Ð¸ Ñ‚Ð° Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="16003">GT Expert Large Travel Enhancer</t>
    <t id="16004">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ Ð²ÐµÐ»Ð¸ÐºÐ¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +15% ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ–.</t>
    <t id="17001">GT Ð•ÐºÑÐ¿ÐµÑ€Ñ‚ Capital Ship Enhancer</t>
    <t id="17002">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +6% ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ, Ñ‚ÑÐ³Ð° Ñ– Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ.</t>
    <t id="17003">GT Expert Capital Travel Enhancer</t>
    <t id="17004">Ð£Ð´Ð¾ÑÐºÐ¾Ð½Ð°Ð»ÐµÐ½Ð° Ð¼Ð¾Ð´Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð° Ð´Ð»Ñ ÐºÐ°Ð¿Ñ–Ñ‚Ð°Ð»ÑŒÐ½Ð¸Ñ… ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð· Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ð¸Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°Ð¼Ð¸. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ Ð¨Ð† GalaxyTrader. +6% ÑˆÐ²Ð¸Ð´ÐºÑ–ÑÑ‚ÑŒ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ–.</t>
    <t id="18001">Ð¡ÑƒÐ²Ð¾Ñ€Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ)</t>
    <t id="18002">Ð¡ÐµÑ€Ð¹Ð¾Ð·Ð½Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ) - Ð¾Ð·Ð½Ð°Ñ‡Ð°Ñ” ÑÐµÑ€Ð¹Ð¾Ð·Ð½Ñ– Ð¿Ð¾ÐºÐ°Ñ€Ð°Ð½Ð½Ñ Ñ‰Ð¾Ð´Ð¾ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ– Ñ‡ÐµÑ€ÐµÐ· Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ñ–ÑÑ‚ÑŒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð· Ð²ÐµÐ»Ð¸ÐºÐ¸Ð¼Ð¸ ÑÑƒÐ´Ð½Ð°Ð¼Ð¸. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ GalaxyTrader, ÐºÐ¾Ð»Ð¸ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð±Ñ–Ð»ÑŒÑˆÑƒÑ” Ð¼Ð°ÑÑƒ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. (Ð›Ð¸ÑˆÐµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="18003">ÐŸÐ¾Ð¼Ñ–Ñ€Ð½Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ)</t>
    <t id="18004">ÐŸÐ¾Ð¼Ñ–Ñ€Ð½Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ) - Ð¾Ð·Ð½Ð°Ñ‡Ð°Ñ” Ð¿Ð¾Ð¼Ñ–Ñ€Ð½Ðµ Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ ÐµÑ„ÐµÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ–, Ð¾ÑÐºÑ–Ð»ÑŒÐºÐ¸ Ð¿Ñ–Ð»Ð¾Ñ‚ Ð°Ð´Ð°Ð¿Ñ‚ÑƒÑ”Ñ‚ÑŒÑÑ Ð´Ð¾ ÑÐºÐ»Ð°Ð´Ð½Ð¾ÑÑ‚Ñ– ÑÑƒÐ´Ð½Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ GalaxyTrader, ÐºÐ¾Ð»Ð¸ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð±Ñ–Ð»ÑŒÑˆÑƒÑ” Ð¼Ð°ÑÑƒ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. (Ð›Ð¸ÑˆÐµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="18005">ÐžÐ±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð»ÐµÐ³ÐºÐ¸Ñ… Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ)</t>
    <t id="18006">Ð›ÐµÐ³ÐºÐµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ) - Ð½ÐµÐ·Ð½Ð°Ñ‡Ð½Ðµ Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ– Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ñ€Ð¾Ð·Ð²Ð¸Ñ‚ÐºÑƒ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ GalaxyTrader, ÐºÐ¾Ð»Ð¸ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð±Ñ–Ð»ÑŒÑˆÑƒÑ” Ð¼Ð°ÑÑƒ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. (Ð›Ð¸ÑˆÐµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="18007">Ð¡ÑƒÐ²Ð¾Ñ€Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (Ð´Ð²Ð¸Ð³ÑƒÐ½)</t>
    <t id="18008">Ð¡ÐµÑ€Ð¹Ð¾Ð·Ð½Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (Ð´Ð²Ð¸Ð³ÑƒÐ½) - Ð¾Ð·Ð½Ð°Ñ‡Ð°Ñ” ÑÐµÑ€Ð¹Ð¾Ð·Ð½Ðµ Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ– Ñ‡ÐµÑ€ÐµÐ· Ð½ÐµÐ´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ñ–ÑÑ‚ÑŒ Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð· Ð²ÐµÐ»Ð¸ÐºÐ¸Ð¼Ð¸ ÑÑƒÐ´Ð½Ð°Ð¼Ð¸. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ GalaxyTrader, ÐºÐ¾Ð»Ð¸ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð¼ÐµÐ½ÑˆÑƒÑ” Ñ‚ÑÐ³Ñƒ Ñ– Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°. (Ð›Ð¸ÑˆÐµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="18009">ÐŸÐ¾Ð¼Ñ–Ñ€Ð½Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (Ð´Ð²Ð¸Ð³ÑƒÐ½)</t>
    <t id="18010">ÐŸÐ¾Ð¼Ñ–Ñ€Ð½Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (Ð´Ð²Ð¸Ð³ÑƒÐ½) - Ð¾Ð·Ð½Ð°Ñ‡Ð°Ñ” Ð¿Ð¾Ð¼Ñ–Ñ€Ð½Ðµ Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ–, Ð¾ÑÐºÑ–Ð»ÑŒÐºÐ¸ Ð¿Ñ–Ð»Ð¾Ñ‚ Ð°Ð´Ð°Ð¿Ñ‚ÑƒÑ”Ñ‚ÑŒÑÑ Ð´Ð¾ ÑÐºÐ»Ð°Ð´Ð½Ð¾ÑÑ‚Ñ– ÑÑƒÐ´Ð½Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ GalaxyTrader, ÐºÐ¾Ð»Ð¸ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð¼ÐµÐ½ÑˆÑƒÑ” Ñ‚ÑÐ³Ñƒ Ñ– Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°. (Ð›Ð¸ÑˆÐµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="18011">ÐžÐ±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð»ÐµÐ³ÐºÐ¸Ñ… Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (Ð´Ð²Ð¸Ð³ÑƒÐ½)</t>
    <t id="18012">Ð›ÐµÐ³ÐºÐµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº (Ð´Ð²Ð¸Ð³ÑƒÐ½) - Ð½ÐµÐ·Ð½Ð°Ñ‡Ð½Ðµ Ð·Ð½Ð¸Ð¶ÐµÐ½Ð½Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸Ð²Ð½Ð¾ÑÑ‚Ñ– Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ñ€Ð¾Ð·Ð²Ð¸Ñ‚ÐºÑƒ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð°. ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð·Ð°ÑÑ‚Ð¾ÑÐ¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ ÑÐ¸ÑÑ‚ÐµÐ¼Ð¾ÑŽ GalaxyTrader, ÐºÐ¾Ð»Ð¸ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð½ÐµÐ´Ð¾ÑÑ‚Ð°Ñ‚Ð½ÑŒÐ¾ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¼Ñ–Ñ€Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð¼ÐµÐ½ÑˆÑƒÑ” Ñ‚ÑÐ³Ñƒ Ñ– Ð¾Ð±ÐµÑ€Ñ‚Ð°Ð½Ð½Ñ Ð´Ð²Ð¸Ð³ÑƒÐ½Ð°. (Ð›Ð¸ÑˆÐµ ÑÐ¸ÑÑ‚ÐµÐ¼Ð° GT - Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð° Ð´Ð»Ñ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ)</t>
    <t id="9250">ÐÐ°Ð¹Ð¼ÐµÐ½ÑƒÐ²Ð°Ð½Ð½Ñ ÑˆÑ‚Ð°Ñ‚Ñƒ ÑÑƒÐ´Ð½Ð°</t>
    <t id="9350">ÐÐ°Ð»Ð°ÑˆÑ‚ÑƒÐ¹Ñ‚Ðµ Ð°Ð±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð¸ ÑÑ‚Ð°Ð½Ñƒ ÑÑƒÐ´Ð½Ð°. Ð—Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ Ð²Ñ–Ð´Ð¾Ð±Ñ€Ð°Ð¶Ð°ÑŽÑ‚ÑŒÑÑ Ð² Ð¿Ð¾Ð»ÑÑ… Ð²Ð²ÐµÐ´ÐµÐ½Ð½Ñ Ñ‚Ð° Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð±ÑƒÑ‚Ð¸ Ð·Ð¼Ñ–Ð½ÐµÐ½Ñ–. ÐœÐ°ÐºÑÐ¸Ð¼ÑƒÐ¼ 3 ÑÐ¸Ð¼Ð²Ð¾Ð»Ð¸. Ð£ÑÑ– Ð½Ð°Ð·Ð²Ð¸ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ð¾Ð½Ð¾Ð²Ð»ÑŽÑŽÑ‚ÑŒÑÑ Ð¿Ñ–ÑÐ»Ñ Ð·Ð¼Ñ–Ð½Ð¸.</t>
    <t id="9251">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑˆÑ‚Ð°Ñ‚Ñƒ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð·Ð°Ð¿Ð°ÑÑ–Ð²:</t>
    <t id="9252">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ:</t>
    <t id="9253">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Ñ‚ÐµÑ…Ð½Ñ–Ñ‡Ð½Ð¾Ð³Ð¾ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ð½Ð½Ñ:</t>
    <t id="9254">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑˆÑ‚Ð°Ñ‚Ñƒ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ:</t>
    <t id="9255">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑˆÑ‚Ð°Ñ‚Ñƒ Ð·Ð¼Ñ–Ð½Ð¸ Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñƒ:</t>
    <t id="9256">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´ÐµÑ€Ð¶Ð°Ð²Ð¸ Ð¾Ñ„Ð¾Ñ€Ð¼Ð»ÐµÐ½Ð½Ñ:</t>
    <t id="9257">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ:</t>
    <t id="9258">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð·Ð°Ð¿Ð°ÑÐ½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ:</t>
    <t id="9259">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ñ–Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ:</t>
    <t id="9260">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ñ— Ð´ÐµÑ€Ð¶Ð°Ð²Ð¸:</t>
    <t id="9261">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ:</t>
    <t id="9262">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Escape State:</t>
    <t id="9268">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Ð½ÐµÐ´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¾ÑÑ‚Ñ–:</t>
    <t id="9269">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑˆÑ‚Ð°Ñ‚Ñƒ Pilot Exchange:</t>
    <t id="9270">Ð¡Ð¿ÐµÑ†Ñ–Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ñ‚ÐµÐ³ Ð¿Ñ€ÐµÑ„Ñ–ÐºÑÐ° Ñ‡Ð¾Ñ€Ð½Ð¾Ð³Ð¾ ÑÐ¿Ð¸ÑÐºÑƒ:</t>
    <t id="9700">Ð§Ñ–Ñ‚Ð¸ (Ð·Ð»Ð°Ð¼Ð°Ð½Ð¾. Ñ‚ÑƒÑ‚ Ð½Ñ–Ñ‡Ð¾Ð³Ð¾ Ð½ÐµÐ¼Ð°Ñ”!! ÑÐ¿Ñ€Ð°Ð²Ð´Ñ–!!)</t>
    <t id="9701">ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ– GT Ð½ÐµÐ²Ñ€Ð°Ð·Ð»Ð¸Ð²Ñ–</t>
    <t id="9702">Ð£ÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð³Ñ€Ð°Ð²Ñ†Ñ Ð½ÐµÐ²Ñ€Ð°Ð·Ð»Ð¸Ð²Ñ–</t>
    <t id="9800">Ð™Ð´Ñ–Ñ‚ÑŒ Ð´Ð°Ð»Ñ–, Ð¿Ñ–Ð»Ð¾Ñ‚Ðµ. Ð—Ð»Ð°Ð¼Ð°Ð½Ñ– Ñ–Ð½ÑÑ‚Ñ€ÑƒÐ¼ÐµÐ½Ñ‚Ð¸ Ñ€Ð¾Ð·Ñ€Ð¾Ð±Ð½Ð¸ÐºÐ°, Ð° Ð½Ðµ Ð²ÐµÑÐµÐ»Ðµ Ð¼ÐµÐ½ÑŽ. Ð¢ÑƒÑ‚ Ð½Ñ–Ñ‡Ð¾Ð³Ð¾ Ð½ÐµÐ¼Ð°Ñ”. Ð¡Ð¿Ñ€Ð°Ð²Ð´Ñ–. Ð’Ð°Ñ Ð¿Ð¾Ð¿ÐµÑ€ÐµÐ´Ð¸Ð»Ð¸. ÐœÐ°Ð±ÑƒÑ‚ÑŒ.</t>
    <t id="9801">ÐšÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð· Ð½Ð°ÐºÐ°Ð·Ð¾Ð¼ GalaxyTrader Ð½Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ÑÑ Ð½Ð¸Ð¶Ñ‡Ðµ 100% ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ Ð°Ð±Ð¾ Ñ‰Ð¸Ñ‚Ñ–Ð². ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ Ð·Ð½Ð¾Ð²Ñƒ, Ñ‰Ð¾Ð± Ð²Ð¸Ð¼ÐºÐ½ÑƒÑ‚Ð¸.</t>
    <t id="9802">Ð£ÑÑ– ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð³Ñ€Ð°Ð²Ñ†Ñ Ð½Ðµ Ð¼Ð¾Ð¶ÑƒÑ‚ÑŒ Ð¾Ð¿ÑƒÑÑ‚Ð¸Ñ‚Ð¸ÑÑ Ð½Ð¸Ð¶Ñ‡Ðµ 100% ÐºÐ¾Ñ€Ð¿ÑƒÑÑƒ Ð°Ð±Ð¾ Ñ‰Ð¸Ñ‚Ñ–Ð². ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ Ð·Ð½Ð¾Ð²Ñƒ, Ñ‰Ð¾Ð± Ð²Ð¸Ð¼ÐºÐ½ÑƒÑ‚Ð¸. Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ— Ð½Ðµ Ð·Ð°Ñ‡Ñ–Ð¿Ð°ÑŽÑ‚ÑŒÑÑ.</t>
    <t id="9703">Ð’Ñ–Ð´ÐºÑ€Ð¸Ñ‚Ð¸ Ð²ÑÐµÑÐ²Ñ–Ñ‚ Ð´Ð»Ñ Ñ‚ÐµÑÑ‚Ñ–Ð² GT</t>
    <t id="9704">Ð’Ñ–Ð´ÐºÑ€Ð¸Ñ‚Ð¾</t>
    <t id="9705">Ð’Ñ–Ð´ÐºÑ€Ð¸Ñ‚Ð¸</t>
    <t id="9803">Ð’Ñ–Ð´ÐºÑ€Ð¸Ð²Ð°Ñ” Ñ‚ÑƒÐ¼Ð°Ð½ Ð²Ñ–Ð¹Ð½Ð¸ Ñƒ Ð²ÑÑ–Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ…, Ð¿Ð¾Ð·Ð½Ð°Ñ‡Ð°Ñ” Ð²ÑÑ– ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— ÑÐº Ð²Ñ–Ð´Ð¾Ð¼Ñ–, Ð½Ð°Ð´Ð°Ñ” Ð²ÑÑ– Ð»Ñ–Ñ†ÐµÐ½Ð·Ñ–Ñ— Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¾Ñ— Ð¿Ñ–Ð´Ð¿Ð¸ÑÐºÐ¸ Ñ„Ñ€Ð°ÐºÑ†Ñ–Ð¹ Ñ– Ð¿Ñ–Ð´Ð¿Ð¸ÑÑƒÑ” Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ— Ð¿Ð¾ Ð²ÑÑ–Ð¹ Ð³Ð°Ð»Ð°ÐºÑ‚Ð¸Ñ†Ñ–. ÐÐ°Ñ‚Ð¸ÑÐ½Ñ–Ñ‚ÑŒ Ð·Ð½Ð¾Ð²Ñƒ Ð¿Ñ–ÑÐ»Ñ Ð½Ð¾Ð²Ð¸Ñ… ÑÐµÐºÑ‚Ð¾Ñ€Ñ–Ð² DLC. Ð›Ð¸ÑˆÐµ Ð´Ð»Ñ Ñ‚ÐµÑÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ.</t>
    <t id="9706">ÐœÐ°ÐºÑÐ¸Ð¼Ñ–Ð·ÑƒÐ²Ð°Ñ‚Ð¸ XP Ð·Ð°Ñ€ÐµÑ”ÑÑ‚Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ… Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² GT</t>
    <t id="9707">ÐœÐ°ÐºÑÐ¸Ð¼Ñ–Ð·Ð¾Ð²Ð°Ð½Ð¾</t>
    <t id="9708">XP Ð¼Ð°ÐºÑ</t>
    <t id="9804">Ð’ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÑŽÑ” 15 Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ñ– Ð¼Ð°ÐºÑ. XP Ð´Ð»Ñ ÐºÐ¾Ð¶Ð½Ð¾Ð³Ð¾ Ð¿Ñ–Ð»Ð¾Ñ‚Ð° Ð² Ñ€ÐµÑ”ÑÑ‚Ñ€Ñ– GT. Ð—Ð½Ñ–Ð¼Ð°Ñ” Ð±Ð»Ð¾ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ. ÐŸÑ€Ð¾Ð¿ÑƒÑÐºÐ°Ñ”Ñ‚ÑŒÑÑ Ð² Ñ€ÐµÐ¶Ð¸Ð¼Ñ– Ð»Ð¸ÑˆÐµ Ð²Ð°Ð½Ñ–Ð»ÑŒÐ½Ð¸Ð¹ XP. Ð›Ð¸ÑˆÐµ Ð´Ð»Ñ Ñ‚ÐµÑÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ.</t>
    <t id="9351">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñƒ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: RS)</t>
    <t id="9352">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñƒ Ñ€ÐµÐ¼Ð¾Ð½Ñ‚Ñƒ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: RP)</t>
    <t id="9353">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñƒ Ñ‚ÐµÑ…Ð½Ñ–Ñ‡Ð½Ð¾Ð³Ð¾ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ð½Ð½Ñ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: MT)</t>
    <t id="9354">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: TR)</t>
    <t id="9355">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ Reroute state (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: RR)</t>
    <t id="9356">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Ð¾Ñ„Ð¾Ñ€Ð¼Ð»ÐµÐ½Ð½Ñ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: CL)</t>
    <t id="9357">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ Ð·Ð°Ð±Ð»Ð¾ÐºÐ¾Ð²Ð°Ð½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: BL)</t>
    <t id="9358">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: FB)</t>
    <t id="9359">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ñ–Ð·Ð¾Ð»ÑŒÐ¾Ð²Ð°Ð½Ð¾Ð³Ð¾ ÑÑ‚Ð°Ð½Ñƒ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: IS)</t>
    <t id="9360">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ Trading state (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: TD)</t>
    <t id="9361">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñƒ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: ID)</t>
    <t id="9362">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° Ð´Ð»Ñ Escape state (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: ES)</t>
    <t id="9367">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Unreachable (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: UR)</t>
    <t id="9368">ÐÐ±Ñ€ÐµÐ²Ñ–Ð°Ñ‚ÑƒÑ€Ð° ÑÑ‚Ð°Ð½Ñƒ Pilot Exchange (Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: PE)</t>
    <t id="9369">Ð’Ñ–Ð´Ð¾Ð±Ñ€Ð°Ð¶Ð°Ñ”Ñ‚ÑŒÑÑ ÑÐº Ð¿Ñ€ÐµÑ„Ñ–ÐºÑ Ð´Ð»Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ–Ð² MK3, Ð½Ð° ÑÐºÑ– Ð²Ð¿Ð»Ð¸Ð²Ð°Ñ” Ñ‡Ð¾Ñ€Ð½Ð¸Ð¹ ÑÐ¿Ð¸ÑÐ¾Ðº ÑÐ¿ÐµÑ†Ñ–Ð°Ð»ÑŒÐ½Ð¾Ñ— Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ— (Ð²ÐºÐ»ÑŽÑ‡Ð½Ð¾ Ð· Ð¿Ñ–Ð´Ð»ÐµÐ³Ð»Ð¸Ð¼Ð¸). Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼: CB</t>
    <t id="30002">GalaxyTrader MK1</t>
    <t id="30102">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÑ†ÑŒ - Ð¿Ñ€Ð¾Ð´Ð°Ñ” ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹Ð½Ñ– Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸ Ñ„Ñ€Ð°ÐºÑ†Ñ–ÑÐ¼ NPC</t>
    <t id="30010">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ</t>
    <t id="30011">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="30012">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ¹Ñ‚Ðµ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–</t>
    <t id="30013">Ð¤Ñ–Ð»ÑŒÑ‚Ñ€ Ð¿Ð¾ÑÑƒÐ´Ñƒ</t>
    <t id="30014">Ð¦Ñ–Ð»ÑŒÐ¾Ð²Ð¸Ð¹ % Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="30015">Ð¢Ð¾Ð»ÐµÑ€Ð°Ð½Ñ‚Ð½Ñ–ÑÑ‚ÑŒ Ð´Ð¾ Ð¿Ð¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ</t>
    <t id="30016">ÐšÑƒÐ¿Ð¸Ñ‚Ð¸ Cargo Fill Target %</t>
    <t id="30017">Ð—Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ñ–</t>
    <t id="30018">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ</t>
    <t id="30019">ÐšÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–Ñ Ñ„Ð»Ð¾Ñ‚Ñƒ</t>
    <t id="30020">Ð Ñ–Ð²ÐµÐ½ÑŒ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ</t>
    <t id="30021">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="30022">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ % Ð¿Ð°Ð¼â€™ÑÑ‚Ñ– ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="30023">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð½ÐµÐ»ÐµÐ³Ð°Ð»ÑŒÐ½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="30024">Ð’Ð°Ð½Ñ‚Ð°Ð¶/ÐŸÑ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº</t>
    <t id="30025">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð±Ð°Ð³Ð°Ñ‚Ð¾ÑƒÐ³Ð¾Ð´ÐºÐ¾Ð²Ñƒ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ</t>
    <t id="30110">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ Ð³Ñ€Ð°Ð²Ñ†Ñ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² (Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ðµ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—)</t>
    <t id="30111">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð´Ð¾ Ð²Ð¾Ñ€Ñ–Ñ‚ Ð´Ð»Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ–Ð² NPC (Ð¾Ð±Ð¼ÐµÐ¶ÑƒÑ”Ñ‚ÑŒÑÑ Ð½Ð°Ð²Ð¸Ñ‡ÐºÐ°Ð¼Ð¸ Ð¿Ñ–Ð»Ð¾Ñ‚Ð°)</t>
    <t id="30112">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ¹Ñ‚Ðµ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— - Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ð¹Ñ‚Ðµ Ð±ÑƒÐ´ÑŒ-ÑÐºÑ–Ð¹ Ð´Ñ€ÑƒÐ¶Ð½Ñ–Ð¹ Ñ„Ñ€Ð°ÐºÑ†Ñ–Ñ— Ð½ÐµÐ·Ð°Ð»ÐµÐ¶Ð½Ð¾ Ð²Ñ–Ð´ Ð¿Ñ€Ð°Ð²Ð¸Ð» Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ– Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="30113">Ð”Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ð¹ Ð¿Ð¾ÑÑƒÐ´Ð¾Ð²Ð¸Ð¹ Ñ„Ñ–Ð»ÑŒÑ‚Ñ€; Ð·Ð°Ð»Ð¸ÑˆÑ‚Ðµ Ð¿Ð¾Ñ€Ð¾Ð¶Ð½Ñ–Ð¼, Ñ‰Ð¾Ð± Ð¿Ñ€Ð¾Ð´Ð°Ñ‚Ð¸ Ð²ÑÑ– Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ñ‚Ð° Ñ‚Ð¾Ð²Ð°Ñ€Ð¸</t>
    <t id="30114">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ Ð¿ÐµÑ€ÐµÐ´ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð½ÑÐ¼ Ð½Ð° Ð¿Ñ€Ð¾Ð´Ð°Ð¶</t>
    <t id="30115">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾ Ð´Ð¾Ð¿ÑƒÑÑ‚Ð¸Ð¼Ñ– Ð´Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ñ– ÑÑ‚Ñ€Ð¸Ð±ÐºÐ¸ Ð¿Ñ€Ð¸ Ð´Ð¾Ð´Ð°Ð²Ð°Ð½Ð½Ñ– Ð´Ñ€ÑƒÐ³Ð¾Ð³Ð¾ Ñ‚Ð¾Ð²Ð°Ñ€Ñƒ Ð´Ð¾ Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶Ñ– (0 = Ð»Ð¸ÑˆÐµ Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ– Ð±ÐµÐ·Ð¿Ð¾ÑÐµÑ€ÐµÐ´Ð½ÑŒÐ¾ Ð½Ð° Ð¼Ð°Ñ€ÑˆÑ€ÑƒÑ‚Ñ–)</t>
    <t id="30116">Ð¦Ñ–Ð»ÑŒÐ¾Ð²Ðµ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ Ð´Ð»Ñ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð¾Ðº (Ð¼â€™ÑÐºÐ° Ð¼ÐµÑ‚Ð°, Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€ Ð¼Ð¾Ð¶Ðµ Ð²Ñ–Ð´Ð¿Ñ€Ð°Ð²Ð¸Ñ‚Ð¸ÑÑ Ñ€Ð°Ð½Ñ–ÑˆÐµ)</t>
    <t id="30117">Ð£Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð·Ð°Ð¿Ð¸ÑÐ¸ Ð² Ð¶ÑƒÑ€Ð½Ð°Ð»Ñ– Ñ‚Ð¾Ñ€Ð³Ñ–Ð²</t>
    <t id="30118">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½ÑŒ: 0=Ð¢Ð¸Ñ…Ð¸Ð¹, 1=ÐÐ¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹, 2=Ð‘Ð°Ð³Ð°Ñ‚Ð¾</t>
    <t id="30119">Ð£Ð²Ñ–Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–ÑŽ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÑƒ Ñ‚Ð° ÑÐ¸ÑÑ‚ÐµÐ¼Ñƒ Ð±Ñ€Ð¾Ð½ÑŽÐ²Ð°Ð½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–</t>
    <t id="30120">Ð Ñ–Ð²ÐµÐ½ÑŒ Ð¶ÑƒÑ€Ð½Ð°Ð»ÑŽÐ²Ð°Ð½Ð½Ñ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ: 0=Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, 1=Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð¸Ð¹, 2=Ð´Ð¾ÐºÐ»Ð°Ð´Ð½Ð¸Ð¹</t>
    <t id="30121">Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, Ñ‚Ð°ÐºÐ¾Ð¶ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‚Ð¸ Ñ€ÐµÑÑƒÑ€ÑÐ¸ Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—. ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ Ð¼Ð°Ñ” Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚, ÐºÐ¾Ð»Ð¸ ÑÑ…Ð¾Ð²Ð¸Ñ‰Ðµ Ð¿Ð°Ð´Ð°Ñ” Ð½Ð¸Ð¶Ñ‡Ðµ Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ñƒ</t>
    <t id="30122">ÐšÐ¾Ð»Ð¸ Ð±ÑƒÐ´ÑŒ-ÑÐºÐ¸Ð¹ Ñ€ÐµÑÑƒÑ€Ñ Ð¿Ð°Ð´Ð°Ñ” Ð½Ð¸Ð¶Ñ‡Ðµ Ñ†ÑŒÐ¾Ð³Ð¾ Ð²Ñ–Ð´ÑÐ¾Ñ‚ÐºÐ° Ð²Ñ–Ð´ Ñ†Ñ–Ð»ÑŒÐ¾Ð²Ð¾Ð³Ð¾ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ, Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ñ Ð¼Ð°Ñ” Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð½Ð°Ð´ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ÐµÐ¼. Ð†Ð³Ð½Ð¾Ñ€ÑƒÑ”Ñ‚ÑŒÑÑ, ÑÐºÑ‰Ð¾ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ Ð½Ðµ Ð¼Ð¾Ð¶Ðµ Ð´Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ ÑÐ¾Ð±Ñ– Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="30123">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ Ð°Ð±Ð¾ ÐºÑƒÐ¿Ñ–Ð²Ð»ÑŽ Ð½ÐµÐ·Ð°ÐºÐ¾Ð½Ð½Ð¸Ñ…/ÐºÐ¾Ð½Ñ‚Ñ€Ð°Ð±Ð°Ð½Ð´Ð½Ð¸Ñ… Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð², ÑÐºÑ‰Ð¾ Ð²Ð¾Ð½Ð¸ Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ñ–</t>
    <t id="30124">Ð’Ð¸Ð±Ñ–Ñ€ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ: 1 = Ð²Ð°Ð½Ñ‚Ð°Ð¶ (Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚ Ð¼Ð°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ ÑÑ…Ð¾Ð²Ð¸Ñ‰Ð° Ð´Ð»Ñ Ñ‚Ð¾Ð²Ð°Ñ€Ñƒ; Ð¿Ñ€Ð¸ Ñ€Ñ–Ð²Ð½Ð¾ÑÑ‚Ñ– - Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº), 2 = Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº (Ð½Ð°Ð¹ÐºÑ€Ð°Ñ‰Ð¸Ð¹ Ð¿Ð¾ÐºÐ°Ð·Ð½Ð¸Ðº Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ)</t>
    <t id="30125">Ð”Ð¾Ð·Ð²Ð¾Ð»ÑÑ” Ð¾Ð±â€™Ñ”Ð´Ð½ÑƒÐ²Ð°Ñ‚Ð¸ ÐºÑ–Ð»ÑŒÐºÐ° Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñ–Ð² Ð² Ð¾Ð´Ð¸Ð½ Ñ†Ð¸ÐºÐ» (Ð´Ð¾ 3 Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² Ð°Ð±Ð¾ Ñ†Ñ–Ð»ÐµÐ¹). Ð’Ð¸Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ Ð´Ð»Ñ Ñ€ÐµÐ¶Ð¸Ð¼Ñƒ Ð»Ð¸ÑˆÐµ Ð¾Ð´Ð½Ñ–Ñ”Ñ— ÑƒÐ³Ð¾Ð´Ð¸ Ð·Ð° Ñ†Ð¸ÐºÐ»</t>
    <t id="30200">ÐŸÑ€Ð¾Ð´Ð°Ð¶ %1 %2 Ð· %3 Ð´Ð¾ %4</t>
    <t id="30201">ÐÐµ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾ Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ–Ð² Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñ–Ð² ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð¿Ñ€Ð¾Ñ‚ÑÐ³Ð¾Ð¼ %1 ÑÑ‚Ñ€Ð¸Ð±ÐºÑ–Ð²</t>
    <t id="30202">Ð“Ð¾Ð»Ð¾Ð²Ð½Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ %1 Ð·Ð½Ð¸Ñ‰ÐµÐ½Ð° â€“ Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ñ†Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ”ÑŽ ÑÐºÐ°ÑÐ¾Ð²Ð°Ð½Ð¾</t>
    <t id="30203">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ %1 Ð±Ñ–Ð»ÑŒÑˆÐµ Ð½Ðµ Ð½Ð°Ð»ÐµÐ¶Ð¸Ñ‚ÑŒ Ð³Ñ€Ð°Ð²Ñ†ÐµÐ²Ñ– â€“ Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ ÑÐºÐ°ÑÐ¾Ð²Ð°Ð½Ð¾</t>
    <t id="30204">ÐŸÐ¾Ñ‚Ñ€Ñ–Ð±Ð½Ðµ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— â€“ Ð·Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ ÑÐºÐ°ÑÐ¾Ð²Ð°Ð½Ð¾</t>
    <t id="30205">MK1 Station Trader Ð¿Ð¾Ñ‡Ð°Ð² Ñ€Ð¾Ð±Ð¾Ñ‚Ñƒ Ð¾ %1</t>
    <t id="30206">Ð—Ð°Ð²ÐµÑ€ÑˆÐµÐ½Ð¸Ð¹ Ð¿Ñ€Ð¾Ð´Ð°Ð¶: %1 %2 Ð¿Ñ€Ð¾Ð´Ð°Ð½Ð¾ %3 Ð·Ð° %4 Cr (Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº: %5 Cr)</t>
    <t id="30207">Ð‘Ð°Ð³Ð°Ñ‚Ð¾Ñ„ÑƒÐ½ÐºÑ†Ñ–Ð¾Ð½Ð°Ð»ÑŒÐ½Ð° Ð¿Ð¾Ð´Ð¾Ñ€Ð¾Ð¶: Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° %1 Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð² Ð´Ð¾ %2 Ð¼Ñ–ÑÑ†ÑŒ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ</t>
    <t id="30208">ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ %1 %2 Ð´Ð¾ %3 Ð²Ñ–Ð´ %4</t>
    <t id="30500">ÐÐ°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ GalaxyTrader MK1</t>
    <t id="30501">Ð¡Ñ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ñ– Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸ Station Trader</t>
    <t id="30502">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼</t>
    <t id="30503">Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ Ñ†Ñ–Ð»ÑŒ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ</t>
    <t id="30504">Ð—Ð° ÑƒÐ¼Ð¾Ð²Ñ‡Ð°Ð½Ð½ÑÐ¼ Ñ–Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–</t>
    <t id="30505">Ð”Ð¾Ð¿ÑƒÑÐº Ð·Ð²Ð¾Ñ€Ð¾Ñ‚Ð½Ð¾Ð³Ð¾ Ñ…Ð¾Ð´Ñƒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼</t>
    <t id="30506">Ð§Ð°Ñ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ, ÐºÐ¾Ð»Ð¸ ÑƒÐ³Ð¾Ð´ Ð½Ðµ Ð·Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾</t>
    <t id="30507">Ð—Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ Ñ†Ñ–Ð»ÑŒ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ</t>
    <t id="31002">Ð“Ð°Ð»Ð°ÐºÑ‚Ð¸ÐºÐ°-Ð¨Ð°Ñ…Ñ‚Ð°Ñ€</t>
    <t id="31102">ÐÐ²Ñ‚Ð¾Ð½Ð¾Ð¼Ð½Ð¸Ð¹ Ð¼Ð°Ð¹Ð½Ñ–Ð½Ð³ Ñ–Ð· Ð·Ð°Ð±ÐµÐ·Ð¿ÐµÑ‡ÐµÐ½Ð½ÑÐ¼ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ñ‚Ð° Ð¿Ñ€Ð¾Ð³Ñ€ÐµÑÑƒÐ²Ð°Ð½Ð½ÑÐ¼ XP</t>
    <t id="31010">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ</t>
    <t id="31110">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ Ð´Ð»Ñ Ð²Ð¸Ð´Ð¾Ð±ÑƒÑ‚ÐºÑƒ Ñ‚Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ (Ð²Ð·Ð°Ñ”Ð¼Ð¾Ð²Ð¸ÐºÐ»ÑŽÑ‡Ð½Ð° Ð· Home Sector)</t>
    <t id="31011">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€</t>
    <t id="31111">Ð¡ÐµÐºÑ‚Ð¾Ñ€ Ð´Ð»Ñ Ñ€Ð¾Ð±Ð¾Ñ‚Ð¸; Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ, ÐºÐ¾Ð»Ð¸ Ð½Ðµ Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ</t>
    <t id="31012">ÐšÐ¾ÑˆÐ¸Ðº Ñ€ÐµÑÑƒÑ€ÑÑ–Ð²</t>
    <t id="31112">Ð’Ð¸Ñ€Ð¾Ð±Ð¸ Ð´Ð»Ñ ÑˆÐ°Ñ…Ñ‚Ð¸; Ð¿Ð¾Ñ€Ð¾Ð¶Ð½Ñ–Ð¹ ÑÐ»Ñ–Ð´ÑƒÑ” Ð·Ð° Ð²Ð¸Ñ€Ñ–ÑˆÐµÐ½Ð½ÑÐ¼ Ð·Ð°Ð¿Ð¸Ñ‚Ñƒ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="31013">Ð¦Ñ–Ð»ÑŒÐ¾Ð²Ñ– ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="31113">Ð”Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ð¹ ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ„Ñ–Ð»ÑŒÑ‚Ñ€ Ð´Ð»Ñ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸; Ð¿Ð¾Ñ€Ð¾Ð¶Ð½Ñ–Ð¹ Ð¿Ð¾Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒ Ñ–Ð· Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾Ð³Ð¾ ÐºÐ¾Ð½Ñ‚ÐµÐºÑÑ‚Ñƒ</t>
    <t id="31014">ÐŸÐ¾Ñ€Ñ–Ð³ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ %</t>
    <t id="31114">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ—, Ñ‰Ð¾ Ð¼Ð°ÑŽÑ‚ÑŒ Ñ†ÐµÐ¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð¿Ð°Ð¼â€™ÑÑ‚Ñ– Ð°Ð±Ð¾ Ð²Ð¸Ñ‰Ðµ, Ð²Ð²Ð°Ð¶Ð°ÑŽÑ‚ÑŒÑÑ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð¸Ð¼Ð¸</t>
    <t id="31015">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ, Ð¿Ñ€Ð¾Ð´Ð°Ð²Ð°Ñ‚Ð¸ Ñ–Ð½ÑˆÐ¸Ð¼</t>
    <t id="31115">ÐšÐ¾Ð»Ð¸ Ð²Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¾ Ð¹ Ð¾ÑÐ½Ð¾Ð²Ð½Ñ– Ñ†Ñ–Ð»Ñ– Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ñ–, Ð¿Ñ€Ð¾Ð´Ð°Ð¹Ñ‚Ðµ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑÐ¼ Ñ–Ð½ÑˆÐ¸Ñ… Ñ„Ñ€Ð°ÐºÑ†Ñ–Ð¹</t>
    <t id="31016">ÐŸÑ€Ð¸Ð·Ð½Ð°Ñ‡Ð¸Ñ‚Ð¸ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="31116">ÐŸÑ€Ð¸Ð·Ð½Ð°Ñ‡Ñ‚Ðµ ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ ÑÐº Ð¿Ñ–Ð´Ð»ÐµÐ³Ð»Ð¸Ð¹ Ð³Ñ–Ñ€Ð½Ð¸Ñ‡Ð¾Ð´Ð¾Ð±ÑƒÐ²Ð½Ð¸Ð¹ Ñ†ÐµÐ½Ñ‚Ñ€ Ð“Ð¾Ð»Ð¾Ð²Ð½Ð¾Ñ— ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—, ÑÐºÑ‰Ð¾ Ñ†Ðµ Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾</t>
    <t id="31017">Ð—Ð°Ð»Ð¸ÑˆÐ°Ð¹ÑÑ Ð²Ð´Ð¾Ð¼Ð°</t>
    <t id="31117">ÐžÐ±Ð¼ÐµÐ¶Ð¸Ñ‚Ð¸ Ð¼Ð°Ð¹Ð½Ñ–Ð½Ð³/Ð¿Ñ€Ð¾Ð´Ð°Ð¶ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾ÑŽ Ñ‚ÐµÑ€Ð¸Ñ‚Ð¾Ñ€Ñ–Ñ”ÑŽ, Ð·Ð° Ð²Ð¸Ð½ÑÑ‚ÐºÐ¾Ð¼ Ñ€ÐµÐ·ÐµÑ€Ð²Ð½Ð¸Ñ… Ð·Ð°Ð¿ÑƒÑÐºÑ–Ð² Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ</t>
    <t id="31018">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ Ð·Ð¾Ð½Ð´Ñ–Ð² Ñ€ÐµÑÑƒÑ€ÑÑ–Ð²</t>
    <t id="31118">ÐÐ²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð¹Ñ‚Ðµ Ð·Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ñ– Ð·Ð¾Ð½Ð´Ð¸ Ñ€ÐµÑÑƒÑ€ÑÑ–Ð² Ñ– Ð²ÐºÐ»ÑŽÑ‡Ð°Ð¹Ñ‚Ðµ Ð·Ð¾Ð½Ð´Ð¸ Ð² Ñ€ÐµÐ·ÐµÑ€Ð² Ð´Ð»Ñ Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ð½Ð½Ñ</t>
    <t id="31019">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð·Ð±Ð¾Ñ€Ñƒ</t>
    <t id="31119">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð´Ð¾ Ð²Ð¾Ñ€Ñ–Ñ‚ Ð´Ð»Ñ Ð·Ð±Ð¸Ñ€Ð°Ð½Ð½Ñ (0 Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð°/ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°)</t>
    <t id="31020">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð´Ð¸ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ</t>
    <t id="31120">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð´Ð¾ Ð²Ð¾Ñ€Ñ–Ñ‚ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ (0 Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ð½Ð°Ð²Ð¸Ñ‡Ð¾Ðº Ð¿Ñ–Ð»Ð¾Ñ‚Ð°/ÐºÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€Ð°)</t>
    <t id="31021">Ð‘Ð°Ð»Ð°Ð½ÑÑƒÐ²Ð°Ð½Ð½Ñ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÑƒ</t>
    <t id="31121">Ð£Ð²Ñ–Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ Ð´ÐµÑ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ð°Ð½Ñƒ ÐºÐ¾Ð¾Ñ€Ð´Ð¸Ð½Ð°Ñ†Ñ–ÑŽ Ð½Ð°Ð¼Ñ–Ñ€Ñ–Ð², Ñ‰Ð¾Ð± Ð·Ð¼ÐµÐ½ÑˆÐ¸Ñ‚Ð¸ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="31022">Ð†Ð½Ñ‚ÐµÑ€Ð²Ð°Ð» Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð¾Ñ— Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸ Ð²Ð¸Ð¼Ð¾Ð³Ð¸</t>
    <t id="31122">Ð¯Ðº Ñ‡Ð°ÑÑ‚Ð¾ Ð²Ð¸ÐºÐ¾Ð½ÑƒÑ”Ñ‚ÑŒÑÑ Ð¾Ñ†Ñ–Ð½ÐºÐ° Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ/Ð¿ÐµÑ€ÐµÐ¼Ð¸ÐºÐ°Ð½Ð½Ñ Ð¼Ð°Ð¹Ð½ÐµÑ€Ñ–Ð²</t>
    <t id="31023">Ð”ÐµÐ»ÑŒÑ‚Ð° ÐºÑ€Ð¸Ñ‚Ð¸Ñ‡Ð½Ð¾Ð³Ð¾ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ</t>
    <t id="31123">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ð´ÐµÐ»ÑŒÑ‚Ð° Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ð¾ÑÑ‚Ñ–, Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð° Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐ¼Ð¸ÐºÐ°Ð½Ð½Ñ Ð°ÐºÑ‚Ð¸Ð²Ð½Ð¾Ð³Ð¾ Ð¾Ð±Ð»Ð°Ð´Ð½Ð°Ð½Ð½Ñ Ð´Ð»Ñ Ð¼Ð°Ð¹Ð½Ñ–Ð½Ð³Ñƒ</t>
    <t id="31024">ÐŸÐµÑ€ÐµÐ·Ð°Ñ€ÑÐ´ÐºÐ° Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð¿ÐµÑ€ÐµÐ¼Ð¸ÐºÐ°Ñ‡Ð°</t>
    <t id="31124">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ñ‡Ð°Ñ Ð¼Ñ–Ð¶ Ð´Ð²Ð¾Ð¼Ð° Ð·Ð¼Ñ–Ð½Ð°Ð¼Ð¸ Ð¿Ð¾ÑÑƒÐ´Ñƒ Ð´Ð»Ñ Ñ†ÑŒÐ¾Ð³Ð¾ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ</t>
    <t id="31025">ÐœÑ–Ð½. Ð·Ð¾Ð±Ð¾Ð²'ÑÐ·Ð°Ð½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ %</t>
    <t id="31125">Ð¯ÐºÑ‰Ð¾ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ Ð²Ð¸Ñ‰Ðµ Ñ†ÑŒÐ¾Ð³Ð¾, ÑÑƒÐ´Ð½Ð¾ Ð²Ð²Ð°Ð¶Ð°Ñ” Ð·Ð° ÐºÑ€Ð°Ñ‰Ðµ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ñ‚Ð¸ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ñƒ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÑƒ Ð¿ÐµÑ€ÐµÐ´ Ð¿ÐµÑ€ÐµÐ¼Ð¸ÐºÐ°Ð½Ð½ÑÐ¼</t>
    <t id="31026">Ð–Ð¾Ñ€ÑÑ‚ÐºÐ° Ð°Ð²Ð°Ñ€Ñ–Ð¹Ð½Ð° Ð´ÐµÐ»ÑŒÑ‚Ð°</t>
    <t id="31126">Ð”ÐµÐ»ÑŒÑ‚Ð° Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ð¾ÑÑ‚Ñ–, ÑÐºÐ° Ð´Ð¾Ð·Ð²Ð¾Ð»ÑÑ” Ð½ÐµÐ³Ð°Ð¹Ð½Ð¾ Ð¿ÐµÑ€ÐµÐºÐ»ÑŽÑ‡Ð¸Ñ‚Ð¸ÑÑ, Ð½ÐµÐ·Ð²Ð°Ð¶Ð°ÑŽÑ‡Ð¸ Ð½Ð° Ð¿Ð¾Ñ€Ñ–Ð³ Ñ„Ñ–ÐºÑÐ°Ñ†Ñ–Ñ— Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ</t>
    <t id="31027">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½Ð½Ñ</t>
    <t id="31127">Ð Ñ–Ð²ÐµÐ½ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½ÑŒ: 0=Ð¢Ð¸Ñ…Ð¸Ð¹, 1=ÐÐ¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹, 2=Ð‘Ð°Ð³Ð°Ñ‚Ð¾</t>
    <t id="31028">Ð›Ð¸ÑˆÐµ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð³Ñ€Ð°Ð²Ñ†Ñ–Ð²</t>
    <t id="31128">Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð»Ð¸ÑˆÐµ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—, ÑÐºÑ– Ð½Ð°Ð»ÐµÐ¶Ð°Ñ‚ÑŒ Ð³Ñ€Ð°Ð²Ñ†ÑÐ¼, Ð²Ð²Ð°Ð¶Ð°ÑŽÑ‚ÑŒÑÑ Ñ†Ñ–Ð»ÑŒÐ¾Ð²Ð¸Ð¼Ð¸ Ð¿Ð¾Ð¿Ð¸Ñ‚Ð¾Ð¼.</t>
    <t id="31031">Ð¡Ð¿Ð¾Ñ‡Ð°Ñ‚ÐºÑƒ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€Ð¸Ñ‚Ð¸ Ð¿Ð¾Ð¿Ð¸Ñ‚</t>
    <t id="31131">Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, ÑˆÐ°Ñ…Ñ‚Ð°Ñ€ Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÑÑ” Ð¿Ð¾Ð¿Ð¸Ñ‚ ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹ Ð¿ÐµÑ€ÐµÐ´ Ð²Ð¸Ð´Ð¾Ð±ÑƒÑ‚ÐºÐ¾Ð¼ Ñ– Ð²Ð¸Ð·Ð½Ð°Ñ‡Ð°Ñ” Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð¸ Ñ€ÐµÑÑƒÑ€ÑÑ–Ð². Ð¯ÐºÑ‰Ð¾ Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð²Ð¸Ð´Ð¾Ð±ÑƒÐ²Ð°Ñ” Ð· ÐºÐ¾ÑˆÐ¸ÐºÐ° Ñ€ÐµÑÑƒÑ€ÑÑ–Ð² Ð±ÐµÐ· Ð¿ÐµÑ€ÐµÐ²Ñ–Ñ€ÐºÐ¸ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ Ñ‚Ð° Ð½Ð°ÐºÐ¾Ð¿Ð¸Ñ‡ÑƒÑ” Ð´Ð¾ Ð¿Ð¾ÑÐ²Ð¸ Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ (Ñ€ÐµÐºÐ¾Ð¼ÐµÐ½Ð´Ð¾Ð²Ð°Ð½Ð¾ Ð´Ð»Ñ Ñ„Ð»Ð¾Ñ‚Ñ–Ð² Ð· Ð¾Ð´Ð½Ð¸Ð¼ Ñ€ÐµÑÑƒÑ€ÑÐ¾Ð¼).</t>
    <t id="31032">ÐŸÐµÑ€ÐµÑ€Ð¸Ð² Ñ„Ñ–Ð·Ð¸Ñ‡Ð½Ð¾Ð³Ð¾ ÑÐºÐ»Ð°Ð´Ñƒ %</t>
    <t id="31132">Ð”Ð»Ñ Ð¿Ñ–Ð»Ð¾Ñ‚Ñ–Ð² Ñ€Ñ–Ð²Ð½Ñ 6+: Ð·ÑƒÐ¿Ð¸Ð½ÑÑ” Ð²Ð¸Ð´Ð¾Ð±ÑƒÑ‚Ð¾Ðº Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¾Ñ— ÑÐ¸Ñ€Ð¾Ð²Ð¸Ð½Ð¸, ÐºÐ¾Ð»Ð¸ Ñ„Ñ–Ð·Ð¸Ñ‡Ð½Ð¸Ð¹ Ð·Ð°Ð¿Ð°Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð¿Ð»ÑŽÑ Ð²Ð°Ð½Ñ‚Ð°Ð¶ Ñ€ÐµÐ»ÐµÐ²Ð°Ð½Ñ‚Ð½Ð¸Ñ… ÑˆÐ°Ñ…Ñ‚Ð°Ñ€Ñ–Ð² Ð¿ÐµÑ€ÐµÐ²Ð¸Ñ‰Ð¸Ñ‚ÑŒ Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ Ñ„Ñ–Ð·Ð¸Ñ‡Ð½Ð¸Ð¹ Ð·Ð°Ð¿Ð°Ñ Ð½Ð° Ñ†ÐµÐ¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” Ñ€ÐµÐ°Ð»ÑŒÐ½Ñ– Ð²Ð°Ð½Ñ‚Ð°Ð¶Ð½Ñ– ÐºÑ–Ð»ÑŒÐºÐ¾ÑÑ‚Ñ–, Ð½Ðµ Ð¿Ð¾Ñ€Ñ–Ð³ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ. 0 = Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾.</t>
    <t id="32002">GalaxyTrader MK4 ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="32102">Ð¢Ñ€ÐµÐ¹Ð´ÐµÑ€ Ð¿Ð¾ÑÑ‚Ð°Ð²Ð¾Ðº ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð³Ñ€Ð°Ð²Ñ†Ñ Ð·Ð° Ð´Ð¾Ð¿Ð¾Ð¼Ð¾Ð³Ð¾ÑŽ GT ÐºÐµÑˆÑƒ/ÐºÐ°Ð½Ð°Ð»Ñƒ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð² Ñ€ÐµÐ°Ð»ÑŒÐ½Ð¾Ð¼Ñƒ Ñ‡Ð°ÑÑ–</t>
    <t id="32010">Ð’Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð¿Ð¾ÐºÑ€Ð¸Ñ‚Ñ‚Ñ</t>
    <t id="32110">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð´Ð¾ Ð²Ð¾Ñ€Ñ–Ñ‚ Ð²Ñ–Ð´ Ð´Ð¾Ð¼Ñƒ Ð´Ð»Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ Ð½Ð° Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ</t>
    <t id="32011">ÐšÑƒÐ¿Ð¸Ñ‚Ð¸ Ð’Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ</t>
    <t id="32111">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð²Ð¾Ñ€Ñ–Ñ‚ Ð²Ñ–Ð´ Ð´Ð¾Ð¼Ñƒ Ð´Ð»Ñ Ð¿Ð¾ÑˆÑƒÐºÑƒ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÐ°</t>
    <t id="32012">ÐžÐ±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸ Ñ‚Ñ–Ð»ÑŒÐºÐ¸ Ð²Ð´Ð¾Ð¼Ð°</t>
    <t id="32112">Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð»Ð¸ÑˆÐµ Ð·Ð°Ð¿Ð¸Ñ‚ Ð½Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ</t>
    <t id="32013">Ð›Ð¸ÑˆÐµ Ð±ÑƒÐ´ÑƒÐ²Ð°Ñ‚Ð¸ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="32113">Ð¯ÐºÑ‰Ð¾ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð¾Ð±ÑÐ»ÑƒÐ³Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð»Ð¸ÑˆÐµ Ð²Ð¸Ð¼Ð¾Ð³Ð° Ð´Ð¾ Ð¿Ð°Ð¼â€™ÑÑ‚Ñ– Ð·Ð±Ñ–Ñ€ÐºÐ¸</t>
    <t id="32014">ÐšÑƒÐ¿ÑƒÐ¹Ñ‚Ðµ Ñƒ Player</t>
    <t id="32114">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ ÐºÑƒÐ¿ÑƒÐ²Ð°Ñ‚Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð²Ñ–Ð´ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÑ–Ð², ÑÐºÑ– Ð½Ð°Ð»ÐµÐ¶Ð°Ñ‚ÑŒ Ð³Ñ€Ð°Ð²Ñ†ÑÐ¼</t>
    <t id="32015">ÐšÑƒÐ¿ÑƒÐ¹Ñ‚Ðµ Ñƒ Faction</t>
    <t id="32115">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð·Ð°ÐºÑƒÐ¿Ð¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð²Ñ–Ð´ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÑ–Ð² Ñ„Ñ€Ð°ÐºÑ†Ñ–Ð¹, ÑÐºÑ– Ð½Ðµ Ñ” Ð³Ñ€Ð°Ð²Ñ†ÑÐ¼Ð¸</t>
    <t id="32016">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ñ€ÐµÑÑƒÑ€ÑÐ¸</t>
    <t id="32116">Ð’ÐºÐ»ÑŽÑ‡Ð°Ð¹Ñ‚Ðµ Ñ€ÐµÑÑƒÑ€ÑÐ¸ Ñ€ÐµÑÑƒÑ€ÑÑ–Ð² Ñƒ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ</t>
    <t id="32017">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¾Ð¼Ñ–Ð¶Ð½Ñ– Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="32117">Ð’ÐºÐ»ÑŽÑ‡Ð°Ð¹Ñ‚Ðµ Ð¿Ñ€Ð¾Ð¼Ñ–Ð¶Ð½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð´Ð¾ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ð¾ÑÑ‚Ñ– Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ</t>
    <t id="32018">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ð¸</t>
    <t id="32118">Ð’ÐºÐ»ÑŽÑ‡Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ð²Ð°Ñ€Ð½Ñ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸, Ñ‰Ð¾ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð°ÑŽÑ‚ÑŒ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ</t>
    <t id="32019">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Tradewares</t>
    <t id="32119">Ð’ÐºÐ»ÑŽÑ‡Ð°Ð¹Ñ‚Ðµ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²ÐµÐ»ÑŒÐ½Ñ– Ð²Ð¸Ñ€Ð¾Ð±Ð¸ Ñƒ Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð½Ñ–ÑÑ‚ÑŒ Ð¿Ð¾Ð¿Ð¸Ñ‚Ñƒ</t>
    <t id="20002">GalaxyTrader MK2</t>
    <t id="20102">Ð¡ÐºÐ»Ð°Ð´ÑÑŒÐºÐ¸Ð¹ Ñ€Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð» Ñ–Ð· ÐºÐµÑ€ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ Ð¿Ð¾Ñ€Ð¾Ð³Ð¾Ð¼ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ð½Ð½Ñ</t>
    <t id="20010">Ð’Ð¸Ñ…Ñ–Ð´Ð½Ñ– ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—</t>
    <t id="20011">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ñ— Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ</t>
    <t id="20012">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ % Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ð½Ð½Ñ</t>
    <t id="20013">% ÑÑ‚Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ð³Ð¾ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ð½Ð½Ñ</t>
    <t id="20014">ÐœÐ°ÐºÑ. % Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ð½Ð½Ñ</t>
    <t id="20015">Ð¤Ñ–Ð»ÑŒÑ‚Ñ€ Ð¿Ð¾ÑÑƒÐ´Ñƒ</t>
    <t id="20016">Ð”Ð²Ð¾Ð½Ð°Ð¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ð¹ Ñ€ÐµÐ¶Ð¸Ð¼</t>
    <t id="20017">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ (Ð¾Ð¿Ñ†Ñ–Ð¾Ð½Ð°Ð»ÑŒÐ½Ð¾)</t>
    <t id="20018">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ</t>
    <t id="20032">Ð”Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€ (Ð¾Ð¿Ñ†Ñ–Ð¾Ð½Ð°Ð»ÑŒÐ½Ð¾)</t>
    <t id="20019">Ð§Ð°Ñ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ñ†Ð¸ÐºÐ»Ñƒ</t>
    <t id="20030">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð½Ð¸Ð·ÑŒÐºÑƒ Ð³ÑƒÑ‡Ð½Ñ–ÑÑ‚ÑŒ</t>
    <t id="20031">ÐÐ¸Ð·ÑŒÐºÐ¸Ð¹ Ñ€Ñ–Ð²ÐµÐ½ÑŒ Ð¾Ð±â€™Ñ”Ð¼Ñƒ %</t>
    <t id="20110">Ð¡Ð¿Ð¸ÑÐ¾Ðº Ð²Ð¸Ñ…Ñ–Ð´Ð½Ð¸Ñ… ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¿Ð¾Ð²ÑÑŽÐ´Ð¶ÐµÐ½Ð½Ñ Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð²</t>
    <t id="20111">Ð¡Ð¿Ð¸ÑÐ¾Ðº ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹/ÑÐºÐ»Ð°Ð´Ñ–Ð² Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð»Ñƒ Ñ‚Ð¾Ð²Ð°Ñ€Ñ–Ð²</t>
    <t id="20112">ÐŸÐ¾Ñ€Ñ–Ð³ Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ð¾ÑÑ‚Ñ– Ð¿ÑƒÐ½ÐºÑ‚Ñƒ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ: ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð½Ð¸Ð¶Ñ‡Ðµ Ñ†ÑŒÐ¾Ð³Ð¾ % Ð·Ð±ÐµÑ€Ñ–Ð³Ð°Ð½Ð½Ñ Ð¾Ñ‚Ñ€Ð¸Ð¼ÑƒÑŽÑ‚ÑŒ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ð½Ñ– Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸</t>
    <t id="20113">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ð¾Ñ€Ñ–Ð³ Ð´Ð¶ÐµÑ€ÐµÐ»Ð°: Ð´Ð»Ñ Ñ€Ð¾Ð·Ð¿Ð¾Ð²ÑÑŽÐ´Ð¶ÐµÐ½Ð½Ñ Ð´Ð¶ÐµÑ€ÐµÐ»Ð¾ Ð¼Ð°Ñ” Ð¿ÐµÑ€ÐµÐ²Ð¸Ñ‰ÑƒÐ²Ð°Ñ‚Ð¸ Ñ†ÐµÐ¹ %</t>
    <t id="20114">ÐŸÐ¾Ñ€Ñ–Ð³ Ð¿ÐµÑ€ÐµÐ¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð´Ð¶ÐµÑ€ÐµÐ»Ð°: Ð¿Ð¾Ð½Ð°Ð´ Ñ†ÐµÐ¹ % Ð´Ð¶ÐµÑ€ÐµÐ»Ð¾ Ñ€Ð¾Ð·Ð¿Ð¾Ð²ÑÑŽÐ´Ð¶ÑƒÑ” Ð½Ð°Ð²Ñ–Ñ‚ÑŒ Ð½ÐµÑ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ñ– Ð¿ÑƒÐ½ÐºÑ‚Ð¸ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ</t>
    <t id="20115">Ð”Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ð¹ Ð¿Ð¾ÑÑƒÐ´Ð¾Ð²Ð¸Ð¹ Ñ„Ñ–Ð»ÑŒÑ‚Ñ€; Ð·Ð°Ð»Ð¸ÑˆÑ‚Ðµ Ð¿Ð¾Ñ€Ð¾Ð¶Ð½Ñ–Ð¼, Ñ‰Ð¾Ð± Ñ€Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð»Ð¸Ñ‚Ð¸ Ð²ÑÑ– Ñ‚Ð¾Ð²Ð°Ñ€Ð¸ Ð· Ð´Ð¶ÐµÑ€ÐµÐ»Ð°</t>
    <t id="20116">Ð£Ð²Ñ–Ð¼ÐºÐ½Ñ–Ñ‚ÑŒ Ð·Ð²Ð¾Ñ€Ð¾Ñ‚Ð½Ð¸Ð¹ Ð·Ð±Ñ–Ñ€ Ð²Ñ–Ð´ Ð¿ÑƒÐ½ÐºÑ‚Ñ–Ð² Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð½Ð°Ð·Ð°Ð´ Ð´Ð¾ Ð´Ð¶ÐµÑ€ÐµÐ»Ð°, ÑÐºÑ‰Ð¾ Ð¿ÑƒÐ½ÐºÑ‚Ð¸ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¼Ð°ÑŽÑ‚ÑŒ Ð½Ð°Ð´Ð»Ð¸ÑˆÐ¾Ðº</t>
    <t id="20117">Ð”Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð° Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ Ð´Ð»Ñ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ. Ð¯ÐºÑ‰Ð¾ Ð¿Ð¾Ñ€Ð¾Ð¶Ð½Ñ–Ð¹, ÐºÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ Ð·Ð°Ð»Ð¸ÑˆÐ°Ñ”Ñ‚ÑŒÑÑ Ð½ÐµÐ¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ð¼ Ð´Ð»Ñ ÑÑ‚Ð°Ð½Ñ†Ñ–Ð¹.</t>
    <t id="20118">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´ÑÑ‚Ð°Ð½ÑŒ Ð¼Ñ–Ð¶ Ð´Ð¶ÐµÑ€ÐµÐ»Ð¾Ð¼ Ñ– Ð¿ÑƒÐ½ÐºÑ‚Ð°Ð¼Ð¸ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ (0 = Ð½ÐµÐ¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð¾)</t>
    <t id="20132">Ð”Ð¾Ð´Ð°Ñ‚ÐºÐ¾Ð²Ð¸Ð¹ Ð´Ð¾Ð¼Ð°ÑˆÐ½Ñ–Ð¹ ÑÐµÐºÑ‚Ð¾Ñ€, ÑÐºÐ¸Ð¹ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ Ð´Ð»Ñ Ð¿Ð°Ñ€ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿Ñ€Ð¾ÑÑ‚Ð¾ÑŽ, ÑÐºÑ‰Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ Ð½Ðµ Ð·Ð°Ð´Ð°Ð½Ð¾.</t>
    <t id="20119">Ð§Ð°Ñ Ð¾Ñ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ð¼Ñ–Ð¶ Ñ†Ð¸ÐºÐ»Ð°Ð¼Ð¸ Ñ€Ð¾Ð·Ð¿Ð¾Ð´Ñ–Ð»Ñƒ</t>
    <t id="20130">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð¼ÐµÐ½ÑˆÑ– Ð¿Ð¾Ñ€Ñ†Ñ–Ñ— Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ Ð· ÑƒÑ€Ð°Ñ…ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ Ñ‚ÐµÑ€Ð¼Ñ–Ð½Ð¾Ð²Ð¾ÑÑ‚Ñ– Ð½Ð¸Ð¶Ñ‡Ðµ Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð¾Ð³Ð¾ Ð¼Ñ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¾Ð³Ð¾ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ.</t>
    <t id="20131">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ % Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ, ÑÐºÐ¸Ð¹ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ”Ñ‚ÑŒÑÑ, ÐºÐ¾Ð»Ð¸ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾ Ñ€ÐµÐ¶Ð¸Ð¼ Ð¼Ð°Ð»Ð¾Ð³Ð¾ Ð¾Ð±â€™Ñ”Ð¼Ñƒ.</t>
    <t id="20200">Ð Ð¾Ð·Ð¿Ð¾Ð²ÑÑŽÐ´Ð¶ÐµÐ½Ð½Ñ %1 %2 Ð²Ñ–Ð´ %3 Ð´Ð¾ %4</t>
    <t id="20201">Ð—Ð²Ð¾Ñ€Ð¾Ñ‚Ð½Ð° Ð´Ð¾Ñ€Ð¾Ð³Ð°: Ð·Ð±Ñ–Ñ€ %1 %2 Ð· %3 Ð´Ð¾ %4</t>
    <t id="20202">Ð Ð¾Ð·Ð¿Ð¾Ð²ÑÑŽÐ´Ð¶ÐµÐ½Ð½Ñ Ð½Ðµ Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ðµ - Ð²ÑÑ– Ð¿ÑƒÐ½ÐºÑ‚Ð¸ Ð¿Ñ€Ð¸Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð½Ð°Ð»ÐµÐ¶Ð½Ð¸Ð¼ Ñ‡Ð¸Ð½Ð¾Ð¼ Ð·Ð°Ð±ÐµÐ·Ð¿ÐµÑ‡ÐµÐ½Ñ–</t>
    <t id="20203">Usi vikhidni stantsii nediyysni - rozpodil ochikuye</t>
    <t id="20204">Usi stantsii priznachennya nediyysni - rozpodil ochikuye</t>
    <t id="20205">Vikhidna stantsiya %1 znyshchena - vydalena z nakazu na rozpodil</t>
    <t id="20206">Stantsiya priznachennya %1 znyshchena - vydalena z nakazu na rozpodil</t>
    <t id="20500">GalaxyTrader MK2 - Ð“Ð»Ð¾Ð±Ð°Ð»ÑŒÐ½Ñ– Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ</t>
    <t id="20501">Ð¡Ñ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ñ– Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€Ð¸ Ð´Ð¸ÑÑ‚Ñ€Ð¸Ð±ÑƒÑ‚Ð¸Ð²Ð° MK2</t>
    <t id="20510">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ð¿Ð°Ð¼â€™ÑÑ‚ÑŒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ %</t>
    <t id="20511">% ÑÑ‚Ð°Ñ‚Ð¸Ñ‡Ð½Ð¾Ñ— Ð¿Ð°Ð¼â€™ÑÑ‚Ñ– Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼</t>
    <t id="20512">ÐœÐ°ÐºÑÐ¸Ð¼Ð°Ð»ÑŒÐ½Ð° Ð¿Ð°Ð¼â€™ÑÑ‚ÑŒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼, %</t>
    <t id="20513">ÐžÑ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð½Ñ Ñ†Ð¸ÐºÐ»Ñƒ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ (Ñ)</t>
    <t id="20514">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ðµ Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð²Ð°Ð½Ñ‚Ð°Ð¶Ñƒ %</t>
    <t id="20520">Ð‘Ð°Ð³Ð°Ñ‚Ð¾ÑÐ»Ñ–Ð²Ð½Ñ–ÑÑ‚ÑŒ ÑÐ¿Ð¾Ð²Ñ–Ñ‰ÐµÐ½ÑŒ</t>
    <t id="20521">Ð Ñ–Ð²ÐµÐ½ÑŒ Ð½Ð°Ð»Ð°Ð³Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ</t>
    <t id="10006">ÐŸÐ¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ Ð´Ð¾Ð´Ð¾Ð¼Ñƒ</t>
    <t id="10007">GalaxyTrader MK4-2 ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ</t>
    <t id="10106">ÐŸÑ€Ð¸ÑÑ‚Ð¸ÐºÑƒÐ¹Ñ‚ÐµÑÑ Ð´Ð¾ Ð±Ð°Ð·Ð¾Ð²Ð¾Ñ— ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ñ‚Ð° Ð·Ð°Ð»Ð¸ÑˆÐ°Ð¹Ñ‚ÐµÑÑ Ñ‚Ð°Ð¼, Ð´Ð¾ÐºÐ¸ Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ Ð½Ðµ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð¸Ñ‚ÑŒÑÑ</t>
    <t id="10107">Ð—Ð°Ð¼Ð¾Ð²Ð»ÐµÐ½Ð½Ñ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ Ð³Ñ€Ð°Ð²Ñ†Ñ Ð· Ð¿Ð¾Ð²Ð·ÑƒÐ½ÐºÐ°Ð¼Ð¸ Ð¿Ñ€Ñ–Ð¾Ñ€Ð¸Ñ‚ÐµÑ‚Ñƒ Ñ†Ñ–Ð»ÐµÐ¹ Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸</t>
    <t id="30026">ÐŸÐ¾Ð²ÐµÑ€Ð½ÐµÐ½Ð½Ñ Ð´Ð¾Ð´Ð¾Ð¼Ñƒ Ð¼Ñ–Ð¶ Ñ†Ð¸ÐºÐ»Ð°Ð¼Ð¸</t>
    <t id="30028">Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Ð½Ð°Ð»Ð°ÑˆÑ‚ÑƒÐ²Ð°Ð½Ð½Ñ Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹</t>
    <t id="30029">Ð”Ñ–Ð°Ð¿Ð°Ð·Ð¾Ð½ Ñ†Ñ–Ð½Ð¸ Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ</t>
    <t id="30027">ÐœÑ–Ð½. Ð·Ð°Ð¿Ð°Ñ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñƒ %</t>
    <t id="30126">ÐšÐ¾Ð»Ð¸ Ð²Ð²Ñ–Ð¼ÐºÐ½ÑƒÑ‚Ð¾, Ð¿Ð¾Ð²ÐµÑ€Ñ‚Ð°Ñ‚Ð¸ÑÑ Ð´Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŒÐ¾Ñ— ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ñ‚Ð° Ð¿Ñ€Ð¸ÑÑ‚Ð¸ÐºÐ¾Ð²ÑƒÐ²Ð°Ñ‚Ð¸ÑÑ Ð¼Ñ–Ð¶ Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ð¼Ð¸ Ñ†Ð¸ÐºÐ»Ð°Ð¼Ð¸. Ð¯ÐºÑ‰Ð¾ Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾, Ð¿Ñ€Ð¾Ð´Ð¾Ð²Ð¶ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿Ð¾ÑˆÑƒÐº Ñ–Ð· Ð¿Ð¾Ñ‚Ð¾Ñ‡Ð½Ð¾Ð³Ð¾ Ð¼Ñ–ÑÑ†ÐµÐ·Ð½Ð°Ñ…Ð¾Ð´Ð¶ÐµÐ½Ð½Ñ (Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð° Ð¿Ð¾Ð²ÐµÐ´Ñ–Ð½ÐºÐ°)</t>
    <t id="30128">Ð”Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ Ð²Ð½ÑƒÑ‚Ñ€Ñ–ÑˆÐ½Ñ– Ð¿ÐµÑ€ÐµÐ¼Ñ–Ñ‰ÐµÐ½Ð½Ñ ÑÐºÐ»Ð°Ð´Ñƒ Ð±ÐµÐ· Ð¿Ñ€Ð¾Ð¿Ð¾Ð·Ð¸Ñ†Ñ–Ð¹ ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ–/Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—. Ð’Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑ” Ð¾Ð±Ð¼Ñ–Ð½ Ñ‚Ð¾Ð²Ð°Ñ€Ð°Ð¼Ð¸ Ð´Ð»Ñ Ð·Ð°Ð±Ð¾Ñ€Ñƒ Ñ‚Ð° Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ¸ Ð· Ð±ÑƒÑ„ÐµÑ€Ð°. Ð¢Ð¾Ñ€Ð³Ð¾Ð²Ñ– Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— Ð´Ñ–ÑŽÑ‚ÑŒ, ÑÐºÑ‰Ð¾ Â«Ð†Ð³Ð½Ð¾Ñ€ÑƒÐ²Ð°Ñ‚Ð¸ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»Ñ–Â» Ð²Ð¸Ð¼ÐºÐ½ÐµÐ½Ð¾.</t>
    <t id="30129">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð° Ð²Ñ–Ð´Ð½Ð¾ÑÐ½Ð° Ñ†Ñ–Ð½Ð° Ð´Ð»Ñ NPC-Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ–Ð² Ð¿Ñ–Ð´ Ñ‡Ð°Ñ Ð¿Ñ€Ð¾Ð´Ð°Ð¶Ñƒ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñ–Ð² ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ—. ÐŸÐ¾Ð²Ð·ÑƒÐ½Ð¾Ðº Ð½Ð°ÐºÐ°Ð·Ñƒ 0-200 (100 = ÑÐµÑ€ÐµÐ´Ð½Ñ, 0 = -100%, 200 = +100%), Ð²Ñ–Ð´Ð¿Ð¾Ð²Ñ–Ð´Ð°Ñ” -1,0..+1,0. Ð’Ð¸Ñ‰Ðµ = Ð»Ð¸ÑˆÐµ Ð´Ð¾Ñ€Ð¾Ð³Ñ– Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ–. ÐÐ¸Ð¶Ñ‡Ðµ = Ð±Ñ–Ð»ÑŒÑˆÐµ Ð²Ð°Ñ€Ñ–Ð°Ð½Ñ‚Ñ–Ð² Ð¿Ð¾ÐºÑƒÐ¿Ñ†Ñ–Ð². ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ñ– Ñ€ÐµÐ¹ÑÐ¸ Ð²Ð¸ÐºÐ¾Ñ€Ð¸ÑÑ‚Ð¾Ð²ÑƒÑŽÑ‚ÑŒ Ñ–Ð½Ð²ÐµÑ€Ñ‚Ð¾Ð²Ð°Ð½Ðµ Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð´Ð»Ñ Ð¾Ð±Ð¼ÐµÐ¶ÐµÐ½Ð½Ñ Ñ†Ñ–Ð½ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð»ÑŒÐ½Ð¸ÐºÑ–Ð².</t>
    <t id="30127">ÐœÑ–Ð½Ñ–Ð¼Ð°Ð»ÑŒÐ½Ð¸Ð¹ Ð²Ñ–Ð´ÑÐ¾Ñ‚Ð¾Ðº Ð·Ð°Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ ÑÐºÐ»Ð°Ð´Ñƒ ÑÑ‚Ð°Ð½Ñ†Ñ–Ñ— (Ð²Ñ–Ð´ Ð½Ð°Ð»Ð°ÑˆÑ‚Ð¾Ð²Ð°Ð½Ð¾Ð³Ð¾ Ð¼Ð°ÐºÑÐ¸Ð¼ÑƒÐ¼Ñƒ Ð½Ð° Ñ‚Ð¾Ð²Ð°Ñ€), Ð½ÐµÐ¾Ð±Ñ…Ñ–Ð´Ð½Ð¸Ð¹ Ð¿ÐµÑ€ÐµÐ´ Ð¿Ñ€Ð¾Ð´Ð°Ð¶ÐµÐ¼ Ð¿Ñ€Ð¾Ð´ÑƒÐºÑ‚Ñƒ Ñ‡Ð¸ Ñ‚Ð¾Ð²Ð°Ñ€Ñƒ. Ð¢Ð¾Ð²Ð°Ñ€Ð¸ Ð½Ð¸Ð¶Ñ‡Ðµ Ñ†ÑŒÐ¾Ð³Ð¾ Ð¿Ð¾Ñ€Ð¾Ð³Ñƒ Ð¿Ñ€Ð¾Ð¿ÑƒÑÐºÐ°ÑŽÑ‚ÑŒÑÑ. 0 = Ð±ÐµÐ· Ð¼Ñ–Ð½Ñ–Ð¼ÑƒÐ¼Ñƒ.</t>
    <t id="3107">ÐŸÐ¾ÑÑ‚Ð°Ð½Ð¾Ð²ÐºÐ° Ð² Ñ‡ÐµÑ€Ð³Ñƒ Ð¼ÑƒÐ»ÑŒÑ‚Ð¸Ñ‚Ñ€ÐµÐ¹Ð´Ñƒ: %1. Ð¯ Ð¼Ð°ÑŽ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ñ‚Ð¸ %2 Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="3108">ÐŸÑ€Ð¾Ð´Ð°Ð¶ %1 %2 Ð· %3 Ð·Ð° %4. Ð¯ Ð¼Ð°ÑŽ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°Ñ‚Ð¸ %5 Ð¿Ñ€Ð¸Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="3110">Ð¡Ñ‚Ð°Ð²Ð»ÑŽ Ð² Ñ‡ÐµÑ€Ð³Ñƒ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ %1 %2. Ð—Ð°ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ Ð·Ð° %3 Ð· %4, Ð´Ð¾ÑÑ‚Ð°Ð²ÐºÐ° Ð½Ð° %5. Ð›Ñ–Ð¼Ñ–Ñ‚ Ð·Ð°ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ– ÐºÐ»Ñ–Ñ”Ð½Ñ‚Ð° %6 - %7/Ð¾Ð´. Ð½Ð¸Ð¶Ñ‡Ðµ Ð»Ñ–Ð¼Ñ–Ñ‚Ñƒ (%8 Ð·Ð°Ð³Ð°Ð»Ð¾Ð¼).</t>
    <t id="3111">Ð¡Ñ‚Ð°Ð²Ð»ÑŽ Ð² Ñ‡ÐµÑ€Ð³Ñƒ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ %1 %2 Ð· %3 Ð½Ð° %4.</t>
    <t id="3112">ÐŸÐ¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ Ð² Ñ‡ÐµÑ€Ð·Ñ– (%1 ÐµÑ‚Ð°Ð¿Ñ–Ð²): %2. Ð—Ð°Ð³Ð°Ð»Ð¾Ð¼ %3 Ð½Ð¸Ð¶Ñ‡Ðµ Ð»Ñ–Ð¼Ñ–Ñ‚Ñƒ Ð·Ð°ÐºÑƒÐ¿Ñ–Ð²Ð»Ñ– ÐºÐ»Ñ–Ñ”Ð½Ñ‚Ð°.</t>
    <t id="3113">Ð¡Ñ‚Ð°Ð½Ñ†Ñ–Ð¹Ð½Ð¸Ð¹ Ñ‚Ñ€ÐµÐ¹Ð´ÐµÑ€: ÐµÐºÑÐ¿Ð¾Ñ€Ñ‚Ð½Ð¸Ð¹ Ð¼ÑƒÐ»ÑŒÑ‚Ð¸Ñ‚Ñ€ÐµÐ¹Ð´ Ñƒ Ñ‡ÐµÑ€Ð·Ñ–: %1. ÐžÑ‡Ñ–ÐºÑƒÐ²Ð°Ð½Ð¸Ð¹ Ð¿Ñ€Ð¸Ð±ÑƒÑ‚Ð¾Ðº %2.</t>
    <t id="31029">Ð¦Ñ–Ð»ÑŒÐ¾Ð²Ð¸Ð¹ Ð·Ð°Ð¿Ð°Ñ Ð¿Ñ€Ð¾Ð±Ð½Ð¸ÐºÐ°</t>
    <t id="31030">Ð“Ñ–Ñ€Ð½Ð¸Ñ‡Ñ– Ð´Ñ€Ð¾Ð½Ð¸ Ð´Ð»Ñ Ð¿Ð¾ÐºÑƒÐ¿ÐºÐ¸</t>
    <!-- Runtime notifications -->
    <t id="31200">Galaxy-Miner: Ð½ÐµÐ¼Ð°Ñ” Ð´Ð¾ÑÑ‚ÑƒÐ¿Ð½Ð¸Ñ… Ð´Ð»Ñ Ð²Ð¸Ð´Ð¾Ð±ÑƒÑ‚ÐºÑƒ Ñ€ÐµÑÑƒÑ€ÑÑ–Ð². ÐšÐ¾Ñ€Ð°Ð±ÐµÐ»ÑŒ %1 [%2], Ð¤Ð»Ð¾Ñ‚: %3</t>
    <t id="31201">Galaxy-Miner: Ð²ÑÑ‚Ð°Ð½Ð¾Ð²Ñ–Ñ‚ÑŒ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽ ÑÑ‚Ð°Ð½Ñ†Ñ–ÑŽ Ð°Ð±Ð¾ Ð´Ð¾Ð¼Ð°ÑˆÐ½ÑŽ Ð¿Ð¾Ð·Ð¸Ñ†Ñ–ÑŽ.</t>
    <t id="31130">Ð¡ÐºÑ–Ð»ÑŒÐºÐ¸ Ð·Ð±Ð¸Ñ€Ð°Ð»ÑŒÐ½Ð¸Ñ… (Ð³Ñ–Ñ€Ð½Ð¸Ñ‡Ð¸Ñ…) Ð´Ñ€Ð¾Ð½Ñ–Ð² ÐºÑƒÐ¿ÑƒÑ” Ð¼Ð°Ð¹Ð½ÐµÑ€, ÐºÐ¾Ð»Ð¸ Ð² Ð½ÑŒÐ¾Ð³Ð¾ Ð·Ð°ÐºÑ–Ð½Ñ‡ÑƒÑ”Ñ‚ÑŒÑÑ Ð¿Ð¾Ñ‚Ñ€Ñ–Ð±Ð½Ð¸Ð¹ Ñ‚Ð¸Ð¿ (Ñ‚Ð²ÐµÑ€Ð´Ð¸Ð¹/Ñ€ÑƒÐ´Ð° Ð°Ð±Ð¾ Ñ€Ñ–Ð´ÐºÐ¸Ð¹/Ð³Ð°Ð·). ÐšÑƒÐ¿Ñ–Ð²Ð»Ñ Ð·Ð°Ð¿ÑƒÑÐºÐ°Ñ”Ñ‚ÑŒÑÑ Ð›Ð˜Ð¨Ð• ÐºÐ¾Ð»Ð¸ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð½ÐµÐ¼Ð°Ñ” Ð·Ð±Ð¸Ñ€Ð°Ñ‡Ñ–Ð² Ñ†ÑŒÐ¾Ð³Ð¾ Ñ‚Ð¸Ð¿Ñƒ - Ð¼Ð°Ð¹Ð½ÐµÑ€, Ñƒ ÑÐºÐ¾Ð³Ð¾ Ñ‰Ðµ Ñ” Ñ…Ð¾Ñ‡Ð° Ð± Ð¾Ð´Ð¸Ð½, Ð½Ñ–ÐºÐ¾Ð»Ð¸ Ð½Ðµ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÑŽÑ”Ñ‚ÑŒÑÑ Ð¹ Ð½Ðµ ÐºÑƒÐ¿ÑƒÑ”Ñ‚ÑŒÑÑ Ð·Ð½Ð¾Ð²Ñƒ, Ð½Ð°ÑÐ²Ð½Ñ– Ð´Ñ€Ð¾Ð½Ð¸ Ð·Ð±ÐµÑ€Ñ–Ð³Ð°ÑŽÑ‚ÑŒÑÑ. ÐžÐ±Ð¼ÐµÐ¶ÐµÐ½Ð¾ Ð¼Ñ–ÑÑ‚ÐºÑ–ÑÑ‚ÑŽ Ð²Ñ–Ð´ÑÑ–ÐºÑƒ ÑŽÐ½Ñ–Ñ‚Ñ–Ð² ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ. Ð’ÑÑ‚Ð°Ð½Ð¾Ð²Ñ–Ñ‚ÑŒ 0, Ñ‰Ð¾Ð± Ð²Ð¸Ð¼ÐºÐ½ÑƒÑ‚Ð¸ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ñƒ ÐºÑƒÐ¿Ñ–Ð²Ð»ÑŽ Ð·Ð±Ð¸Ñ€Ð°Ð»ÑŒÐ½Ð¸Ñ… Ð´Ñ€Ð¾Ð½Ñ–Ð² Ñ– ÐºÐµÑ€ÑƒÐ²Ð°Ñ‚Ð¸ Ð´Ñ€Ð¾Ð½Ð°Ð¼Ð¸ Ð²Ñ€ÑƒÑ‡Ð½Ñƒ. Ð—Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð·Ð° Ð·Ð°Ð¼Ð¾Ð²Ñ‡ÑƒÐ²Ð°Ð½Ð½ÑÐ¼ 5 - Ð¿Ð¾Ð²Ð½Ð¸Ð¹ Ð½Ð°Ð±Ñ–Ñ€ Ð´Ñ€Ð¾Ð½Ñ–Ð² Ð´Ð»Ñ Ð½Ð¾Ñ€Ð¼Ð°Ð»ÑŒÐ½Ð¾Ñ— ÑˆÐ²Ð¸Ð´ÐºÐ¾ÑÑ‚Ñ– Ð²Ð¸Ð´Ð¾Ð±ÑƒÑ‚ÐºÑƒ.</t>
    <t id="31129">ÐšÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ Ð·Ð¾Ð½Ð´Ñ–Ð² Ñ€ÐµÑÑƒÑ€ÑÑ–Ð², ÑÐºÑ– Ð¼Ð°Ð¹Ð½ÐµÑ€ ÐºÑƒÐ¿ÑƒÑ” Ð·Ð° Ð¿Ð¾Ñ—Ð·Ð´ÐºÑƒ Ð¿Ð¾Ð¿Ð¾Ð²Ð½ÐµÐ½Ð½Ñ Ð·Ð°Ð¿Ð°ÑÑ–Ð². ÐšÑƒÐ¿Ñ–Ð²Ð»Ñ Ð·Ð°Ð¿ÑƒÑÐºÐ°Ñ”Ñ‚ÑŒÑÑ Ð¢Ð†Ð›Ð¬ÐšÐ˜ Ñ‚Ð¾Ð´Ñ–, ÐºÐ¾Ð»Ð¸ Ð½Ð° ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ– Ð·Ð°ÐºÑ–Ð½Ñ‡ÑƒÑŽÑ‚ÑŒÑÑ Ð·Ð¾Ð½Ð´Ð¸ (ÐºÑ–Ð»ÑŒÐºÑ–ÑÑ‚ÑŒ = 0), Ð° Ð½Ðµ Ð¿Ñ–Ð´ Ñ‡Ð°Ñ ÐºÐ¾Ð¶Ð½Ð¾Ð³Ð¾ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ - Ñ‚Ð°ÐºÐ¸Ð¼ Ñ‡Ð¸Ð½Ð¾Ð¼ Ð¼Ð°Ð¹Ð½ÐµÑ€ Ð¿Ñ€Ð¾Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒ Ð¿Ð¾Ð²Ð½Ðµ Ð·Ð°Ð²Ð°Ð½Ñ‚Ð°Ð¶ÐµÐ½Ð½Ñ Ð·Ð¾Ð½Ð´Ñ–Ð² Ð¼Ñ–Ð¶ Ð·Ð°Ð¿ÑƒÑÐºÐ°Ð¼Ð¸ Ð¿Ð¾ÑÑ‚Ð°Ñ‡Ð°Ð½Ð½Ñ Ð·Ð°Ð¼Ñ–ÑÑ‚ÑŒ Ð¾Ð±â€™Ñ—Ð·Ð´Ñƒ Ð¿Ñ–ÑÐ»Ñ ÐºÐ¾Ð¶Ð½Ð¾Ð³Ð¾ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ. ÐžÐ±Ð¼ÐµÐ¶ÑƒÑ”Ñ‚ÑŒÑÑ Ð·Ð°Ð³Ð°Ð»ÑŒÐ½Ð¾ÑŽ Ð·Ð´Ð°Ñ‚Ð½Ñ–ÑÑ‚ÑŽ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ ÐºÐ¾Ñ€Ð°Ð±Ð»Ñ (ÑÐ¿Ñ–Ð»ÑŒÐ½Ð¾ Ñ–Ð· ÑÑƒÐ¿ÑƒÑ‚Ð½Ð¸ÐºÐ°Ð¼Ð¸/Ð¼Ñ–Ð½Ð°Ð¼Ð¸ Ñ‚Ð¾Ñ‰Ð¾); Ð·Ð½Ð°Ñ‡ÐµÐ½Ð½Ñ Ð¿Ð¾Ð²Ð·ÑƒÐ½ÐºÐ°, Ñ‰Ð¾ Ð¿ÐµÑ€ÐµÐ²Ð¸Ñ‰ÑƒÑ” Ð²Ñ–Ð»ÑŒÐ½Ð¸Ð¹ Ð¿Ñ€Ð¾ÑÑ‚Ñ–Ñ€ Ð´Ð»Ñ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ, Ð²Ð¸Ñ‚Ð¾Ð½Ñ‡ÐµÐ½Ð¾ Ð·Ð¼ÐµÐ½ÑˆÑƒÑ”Ñ‚ÑŒÑÑ Ð´Ð¾ Â«Ð·Ð°Ð¿Ð¾Ð²Ð½Ð¸Ñ‚Ð¸ Ñ‚Ðµ, Ñ‰Ð¾ Ð¿Ñ–Ð´Ñ…Ð¾Ð´Ð¸Ñ‚ÑŒÂ». ÐÐ°Ð±ÑƒÐ²Ð°Ñ” Ñ‡Ð¸Ð½Ð½Ð¾ÑÑ‚Ñ– Ð»Ð¸ÑˆÐµ Ñ‚Ð¾Ð´Ñ–, ÐºÐ¾Ð»Ð¸ Ð²Ð²Ñ–Ð¼ÐºÐ½ÐµÐ½Ð¾ Ð°Ð²Ñ‚Ð¾Ð¼Ð°Ñ‚Ð¸Ñ‡Ð½Ðµ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½Ñ Ð·Ð¾Ð½Ð´Ñ–Ð² Ñ€ÐµÑÑƒÑ€ÑÑ–Ð² - Ñ†ÐµÐ¹ ÑÐ°Ð¼Ð¸Ð¹ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ Ñ‚Ð°ÐºÐ¾Ð¶ ÐºÐµÑ€ÑƒÑ” Ð¾Ð¿Ð¿Ð¾Ñ€Ñ‚ÑƒÐ½Ñ–ÑÑ‚Ð¸Ñ‡Ð½Ð¸Ð¼ Ñ€Ð¾Ð·Ð³Ð¾Ñ€Ñ‚Ð°Ð½Ð½ÑÐ¼ Ð·Ð¾Ð½Ð´Ñ–Ð² Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ð²Ð¸Ð´Ð¾Ð±ÑƒÑ‚ÐºÑƒ Ñ‚Ð° Ð·Ð±Ð¾Ñ€Ñƒ Ð·Ð°ÑÑ‚Ð°Ñ€Ñ–Ð»Ð¸Ñ… Ð·Ð¾Ð½Ð´Ñ–Ð² (Ð·Ð¾Ð½Ð´Ñ–Ð² Ñƒ ÑÐµÐºÑ‚Ð¾Ñ€Ð°Ñ… Ð±ÐµÐ· Ñ€ÐµÑÑƒÑ€ÑÑ–Ð², Ñ€ÐµÐ»ÐµÐ²Ð°Ð½Ñ‚Ð½Ð¸Ñ… ÐºÐ¾ÑˆÐ¸ÐºÑƒ).</t>
    <t id="3226">ÐšÐ¾Ð¼Ð°Ð½Ð´Ð¸Ñ€ %1,\n\nÐ¯ Ð¿Ñ€Ð¸ÑÑ‚Ð¸ÐºÑƒÐ²Ð°Ð²ÑÑ Ð´Ð¾ %2, Ñ– Ñ€ÐµÑ”ÑÑ‚Ñ€Ð°Ñ‚Ð¾Ñ€ Trading Academy Ð¿Ñ–Ð´Ñ‚Ð²ÐµÑ€Ð´Ð¸Ð² Ð¼Ð¾ÑŽ Ñ€ÐµÑ”ÑÑ‚Ñ€Ð°Ñ†Ñ–ÑŽ Ð² Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ñ– "%3". Ð— Ñ€Ð°Ñ…ÑƒÐ½ÐºÑƒ Ð°Ð²Ñ‚Ð¾Ð¿Ð°Ñ€ÐºÑƒ ÑÐ¿Ð¸ÑÐ°Ð½Ð¾ %4 Cr Ð·Ð° Ð½Ð°Ð²Ñ‡Ð°Ð½Ð½Ñ Ð½Ð° ÐºÑƒÑ€ÑÑ–, Ñ– Ñ Ð½Ðµ Ð»ÐµÐ³ÐºÐ¾Ð²Ð°Ð¶Ñƒ Ð´Ð¾ Ñ†Ñ–Ñ”Ñ— Ñ–Ð½Ð²ÐµÑÑ‚Ð¸Ñ†Ñ–Ñ—.\n\nÐ¦Ðµ Ð½Ðµ Ð·Ð²Ð¸Ñ‡Ð°Ð¹Ð½Ð° ÑÐµÑ€Ñ‚Ð¸Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ. Ð’Ð¸ÐºÐ»Ð°Ð´Ð°Ñ‡Ð°Ð¼Ð¸ Ð°ÐºÐ°Ð´ÐµÐ¼Ñ–Ñ— Ñ” Ð´Ð¾ÑÐ²Ñ–Ð´Ñ‡ÐµÐ½Ñ– ÐºÐ¾Ð¼ÐµÑ€ÑÐ°Ð½Ñ‚Ð¸ Ñ‚Ð° ÑƒÑ‡Ð°ÑÐ½Ð¸ÐºÐ¸ Ð¿ÐµÑ€ÐµÐ³Ð¾Ð²Ð¾Ñ€Ñ–Ð² ÐºÐ¾Ð½ÑÐ¾Ñ€Ñ†Ñ–ÑƒÐ¼Ñƒ, Ð° Ð½Ð°Ð²Ñ‡Ð°Ð»ÑŒÐ½Ð° Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð° Ñ‚ÑƒÑ‚ Ð½Ð°Ð±Ð°Ð³Ð°Ñ‚Ð¾ ÑÐºÐ»Ð°Ð´Ð½Ñ–ÑˆÐ°, Ð½Ñ–Ð¶ ÑÑ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ Ð´Ð»Ñ Ð¿Ñ–Ð´Ð²Ð¸Ñ‰ÐµÐ½Ð½Ñ ÐºÐ²Ð°Ð»Ñ–Ñ„Ñ–ÐºÐ°Ñ†Ñ–Ñ—. ÐŸÑ€Ð¾Ñ‚ÑÐ³Ð¾Ð¼ Ð½Ð°ÑÑ‚ÑƒÐ¿Ð½Ð¸Ñ… %5 Ñ…Ð²Ð¸Ð»Ð¸Ð½ Ñ Ð¿Ñ€Ð¾Ð¹Ð´Ñƒ Ñ–Ð½Ñ‚ÐµÐ½ÑÐ¸Ð²Ð½Ð¸Ð¹ Ñ–Ð½ÑÑ‚Ñ€ÑƒÐºÑ‚Ð°Ð¶ Ñ–Ð· Ñ€Ð¾Ð·ÑˆÐ¸Ñ€ÐµÐ½Ð¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¿Ñ€Ð¾Ñ‚Ð¾ÐºÐ¾Ð»Ñ–Ð², Ð°Ð½Ð°Ð»Ñ–Ð·Ñƒ Ñ€Ð¸Ð½ÐºÑƒ Ð¿Ñ–Ð´ Ñ‚Ð¸ÑÐºÐ¾Ð¼ Ñ– Ñ‚Ð°ÐºÑ‚Ð¸ÐºÐ¸ Ð²ÐµÐ´ÐµÐ½Ð½Ñ Ð¿ÐµÑ€ÐµÐ³Ð¾Ð²Ð¾Ñ€Ñ–Ð², ÑÐºÑ– Ð²Ñ–Ð´Ð¾ÐºÑ€ÐµÐ¼Ð»ÑŽÑŽÑ‚ÑŒ ÑƒÑ‡Ð½Ñ–Ð² Ð²Ñ–Ð´ Ð¼Ð°Ð¹ÑÑ‚Ñ€Ñ–Ð².\n\nÐšÐ¾Ð»Ð¸ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ñ‚ÑŒÑÑ Ð¾ÑÑ‚Ð°Ñ‚Ð¾Ñ‡Ð½Ð¸Ð¹ Ñ–ÑÐ¿Ð¸Ñ‚ Ñ– Ñ Ð²Ñ–Ð´â€™Ñ”Ð´Ð½Ð°ÑŽÑÑ, Ñ Ð¾Ñ‚Ñ€Ð¸Ð¼Ð°ÑŽ Ñ‚Ð¸Ñ‚ÑƒÐ» Â«%3Â» Ñ– Ð¿Ð¾Ð²ÐµÑ€Ð½Ñƒ Ð²ÑÐµ, Ñ‰Ð¾ Ñ Ð½Ð°Ð²Ñ‡Ð¸Ð²ÑÑ, Ð´Ð¾ Ð½Ð°ÑˆÐ¸Ñ… Ñ‚Ð¾Ñ€Ð³Ð¾Ð²Ð¸Ñ… Ð¾Ð¿ÐµÑ€Ð°Ñ†Ñ–Ð¹. Ð¯ Ð½Ðµ Ð²Ñ‚Ñ€Ð°Ñ‡Ñƒ Ð¶Ð¾Ð´Ð½Ð¾Ð³Ð¾ ÐºÑ€ÐµÐ´Ð¸Ñ‚Ñƒ Ñ†Ñ–Ñ”Ñ— Ð¼Ð¾Ð¶Ð»Ð¸Ð²Ð¾ÑÑ‚Ñ–.\n\nÐ— Ð²Ð´ÑÑ‡Ð½Ñ–ÑÑ‚ÑŽ Ñ‚Ð° Ñ€Ñ–ÑˆÑƒÑ‡Ñ–ÑÑ‚ÑŽ,\n%6\nÐÐ° Ð±Ð¾Ñ€Ñ‚Ñƒ %7</t>
    <t id="9924">ÐšÑƒÑ€Ñ Trading Academy Ð¿ÐµÑ€ÐµÑ€Ð²Ð°Ð½Ð¾: Ð¿Ñ–Ð»Ð¾Ñ‚ %1 Ð½Ðµ Ð¼Ð¾Ð¶Ðµ Ð´Ð¾Ð·Ð²Ð¾Ð»Ð¸Ñ‚Ð¸ ÑÐ¾Ð±Ñ– Ð¿Ð»Ð°Ñ‚Ñƒ %2 Cr Ð² Ð´Ð¾Ñ†Ñ– Ð°ÐºÐ°Ð´ÐµÐ¼Ñ–Ñ— (Ð¼Ð°Ð¹Ñ‚Ðµ %3 Cr). ÐšÑƒÑ€Ñ ÑÐºÐ°ÑÐ¾Ð²Ð°Ð½Ð¾, Ð¿Ñ–Ð»Ð¾Ñ‚ Ð²Ñ–Ð´Ð½Ð¾Ð²Ð»ÑŽÑ” Ñ‚Ð¾Ñ€Ð³Ñ–Ð²Ð»ÑŽ.</t>
  </page>
</language>
<?xml version="1.0" encoding="UTF-8"?>
<addon name="gt_info_menu" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../stock_game/X4 Foundations/ui/core/addon.xsd">
  <environment type="menus">
    <!-- Shared UI library - MUST load first (provides _G.GT_UI) -->
    <file name="ui/gt_ui_library.lua" />
    <!-- Dynamic threat blacklist (packed-safe; do not load via Lua_Loader) -->
    <file name="ui/gt_blacklist_manager.lua" />
    <!-- Pilot data bridge is required by context redistribution level logic -->
    <file name="ui/gt_pilot_data_bridge.lua" />
    <!-- <file name="ui/gt_pilot_control_bridge.lua" /> -->
    <!-- <file name="ui/gt_info_menu.lua" /> -->
    <file name="ui/gt_context_rename.lua" />
    <file name="ui/gt_context_academy.lua" />
    <file name="ui/gt_context_diagnose.lua" />
    <file name="ui/gt_context_promote.lua" />
    <file name="ui/gt_context_redistribute.lua" />
    <file name="ui/gt_mk3_faction_blacklist.lua" />
    <file name="ui/gt_mod_removal.lua" />
    <file name="ui/gt_credits_due_override.lua" />
    <file name="ui/gt_crew_name_highlight.lua" />
    <file name="ui/gt_personnel_name_override.lua" />
    <!--<file name="ui/gt_order_monitor.lua" />-->
    <file name="ui/gt_subordinate_access.lua" />
    <file name="ui/gt_mk2_ware_exchange.lua" />
    <dependency name="ego_detailmonitorhelper" />
  </environment>
</addon>
--[[
==============================================================================
GalaxyTrader MK3 - Dynamic Blacklist Manager
==============================================================================
Bridges MD threat intelligence with X4's native blacklist system

Features:
- Creates empty fleet blacklist at game start/save load (avoids creation lag)
- Updates blacklist dynamically as threats are detected/cleared
- Automatically applies blacklist to all GT ships
- Uses vanilla pathfinding for automatic route recalculation

Dependencies:
- Loaded via ui.xml (works in packed cat/dat installs)
- X4 FFI blacklist functions

Author: GalaxyTrader Development Team
Version: 1.0
==============================================================================
]]--

local ffi = require("ffi")
local C = ffi.C

-- =============================================================================
-- FFI DEFINITIONS - X4 Blacklist API
-- =============================================================================

ffi.cdef[[
    typedef int32_t BlacklistID;
    
    typedef struct {
        const char* name;
        const char* type;           // "sectortravel" or "sectoractivity"
        uint32_t nummacros;         // Number of sector macros
        const char** macros;        // Array of sector macro names
        uint32_t numfactions;       // Number of factions
        const char** factions;      // Array of faction IDs
        const char* relation;       // Relation threshold
        bool hazardous;
        bool usemacrowhitelist;
        bool usefactionwhitelist;
        BlacklistID id;             // ID for updates
    } BlacklistInfo2;
    
    BlacklistID CreateBlacklist2(BlacklistInfo2 info);
    void UpdateBlacklist2(BlacklistInfo2 info);
    void RemoveBlacklist(BlacklistID id);
    void SetControllableBlacklist(uint64_t controllableid, BlacklistID id, const char* listtype, bool value);
    BlacklistID GetControllableBlacklistID(uint64_t controllableid, const char* listtype, const char* defaultgroup);
    bool IsComponentBlacklisted(uint64_t componentid, const char* listtype, const char* defaultgroup, uint64_t controllableid);
    bool GetBlacklistInfo2(BlacklistInfo2* info, BlacklistID id);
    
    // Component lookup
    uint64_t ConvertStringTo64Bit(const char* idcode);
    const char* ConvertIDToString(uint64_t componentid);
    const char* GetComponentData(uint64_t componentid, const char* propertyname);
]]

-- =============================================================================
-- MODULE STATE
-- =============================================================================

local GT_Blacklist = {
    -- Configuration
    CONFIG = {
        DEBUG_MODE = false,  -- true: init/update/FFI trace + per-macro verbose dumps
        BLACKLIST_NAME_PREFIX = "GT_ThreatAvoid_",
        THREAT_LEVEL_THRESHOLD = 3,  -- Default: Blacklist sectors with threat >= 3 (overridden by MD settings)
        UPDATE_INTERVAL = 5.0,        -- Check for updates every 5 seconds
    },
    
    -- State tracking
    dynamic_blacklists = {},  -- { ship_id -> blacklist_id }
    blacklisted_sectors = {}, -- { sector_name -> { threat_level, timestamp } }
    fleet_blacklist_id = nil, -- Shared fleet-wide blacklist ID
    relation_value = "",      -- Stored relation value: "enemy" or ""
    last_update = 0,
    initialized = false,
}

-- =============================================================================
-- STRING UTILITY FUNCTIONS (for ship name processing)
-- =============================================================================

-- Strip GT formatting from ship names
-- Removes: prefixes like "ADVANCE", "[TRAINING]", "AVANÃ‡AR" (any ALL-CAPS word or bracketed text)
-- Removes: suffixes like "(Comerciante Lv.10 XP:3150)"
local function stripGTFormatting(shipName)
    if not shipName or shipName == "" then
        return ""
    end
    
    local cleanName = shipName
    
    -- Step 1: Remove bracketed prefix like "[TRAINING]", "[AUSBILDUNG]", etc.
    cleanName = cleanName:gsub("^%[.-%]%s+", "")
    
    -- Step 2: Remove ALL-CAPS word prefix (like "ADVANCE ", "AVANÃ‡AR ", "FORTSCHRITT ", etc.)
    cleanName = cleanName:gsub("^[%u%d]+%s+", "")
    
    -- Step 3: Remove parenthetical suffix like "(Comerciante Lv.10 XP:3150)"
    local parenPos = cleanName:find("%s%(")
    if parenPos then
        cleanName = cleanName:sub(1, parenPos - 1)
    end
    
    -- Trim any trailing/leading whitespace
    cleanName = cleanName:match("^%s*(.-)%s*$")
    
    return cleanName
end

-- =============================================================================
-- UTILITY FUNCTIONS
-- =============================================================================

-- Load/init visibility; INFO only when DEBUG_MODE (errors/warnings always)
local function logLoad(message, level)
    level = level or "INFO"
    if level ~= "ERROR" and level ~= "WARNING" and not GT_Blacklist.CONFIG.DEBUG_MODE then
        return
    end
    local prefix = "[GT-Blacklist-Lua] "
    DebugError(prefix .. message)
end

-- Runtime trace; INFO only when DEBUG_MODE (errors/warnings always)
local function logTrace(message, level)
    level = level or "INFO"
    if level ~= "ERROR" and level ~= "WARNING" and not GT_Blacklist.CONFIG.DEBUG_MODE then
        return
    end
    local prefix = "[GT-Blacklist-Lua] "
    if level == "ERROR" or level == "WARNING" then
        DebugError(prefix .. level .. ": " .. message)
    else
        DebugError(prefix .. message)
    end
end

local function logVerbose(message, level)
    if GT_Blacklist.CONFIG.DEBUG_MODE then
        local prefix = level == "ERROR" and "ERROR" or level == "WARN" and "WARN" or "DBG"
        local logText = string.format("[GT-Blacklist-Lua] %s: %s", prefix, message)
        if level == "ERROR" or level == "WARN" then
            DebugError(logText)
        else
            print(logText)
        end
    end
end

-- Backward-compatible alias used throughout this file
local function debugLog(message, level)
    logVerbose(message, level)
end

local function summarizeMacroList(macros, max_show)
    max_show = max_show or 5
    if not macros or #macros == 0 then
        return "(none)"
    end
    if #macros <= max_show then
        return table.concat(macros, ", ")
    end
    local shown = {}
    for i = 1, max_show do
        shown[i] = macros[i]
    end
    return table.concat(shown, ", ") .. string.format(" ... +%d more", #macros - max_show)
end

local function logBlacklistVerify(blacklist_id, context)
    if not blacklist_id or blacklist_id == 0 then
        logTrace(string.format("%s: verify skipped (no blacklist id)", context), "WARNING")
        return
    end
    if type(C.GetBlacklistInfo2) ~= "cdata" then
        logTrace(string.format("%s: GetBlacklistInfo2 not available (id=%s)", context, tostring(blacklist_id)))
        return
    end
    local verify_buf = ffi.new("BlacklistInfo2")
    local ok, exists = pcall(function() return C.GetBlacklistInfo2(verify_buf, blacklist_id) end)
    if not ok then
        logTrace(string.format("%s: GetBlacklistInfo2 pcall failed for id=%s: %s", context, tostring(blacklist_id), tostring(exists)), "WARNING")
        return
    end
    if not exists then
        logTrace(string.format("%s: blacklist id=%s NOT FOUND in X4", context, tostring(blacklist_id)), "WARNING")
        return
    end
    local name = verify_buf.name and ffi.string(verify_buf.name) or "?"
    local relation = verify_buf.relation and ffi.string(verify_buf.relation) or ""
    logTrace(string.format(
        "%s: X4 confirms id=%s name='%s' nummacros=%d relation='%s'",
        context, tostring(blacklist_id), name, tonumber(verify_buf.nummacros) or 0, relation
    ))
end

--- Parse ship list from MD raise_lua_event param ("id1,id2,..." or single numeric component id)
local function parseShipListPayload(event_data)
    local ship_list = {}
    if not event_data then
        return ship_list
    end
    if type(event_data) == "number" then
        table.insert(ship_list, tostring(event_data))
    elseif type(event_data) == "string" and event_data ~= "" then
        for ship_id in string.gmatch(event_data, "([^,]+)") do
            table.insert(ship_list, ship_id)
        end
    end
    return ship_list
end

local function convertStringToID(idcode)
    if not idcode or idcode == "" then
        return 0
    end
    -- Match UPB pattern: tonumber -> tostring -> ConvertStringTo64Bit
    -- This handles numeric strings from MD like "123456789"
    local num = tonumber(idcode)
    if not num then
        debugLog(string.format("Failed to convert '%s' to number", idcode), "WARN")
        return 0
    end
    return C.ConvertStringTo64Bit(tostring(num))
end

-- NOTE: ConvertIDToString is restricted in FFI, so we can't use it
-- local function convertIDToString(componentid)
--     if not componentid or componentid == 0 then
--         return ""
--     end
--     return ffi.string(C.ConvertIDToString(componentid))
-- end

-- =============================================================================
-- BLACKLIST MANAGEMENT - CORE FUNCTIONS
-- =============================================================================

--- Create or update the fleet-wide dynamic blacklist
--- @param threatened_macro_list table List of sector macros with direct threats
--- @param relation_value string "enemy" to block enemy factions, "" to disable
local function updateFleetBlacklist(threatened_macro_list, relation_value)
    local relation_display = (relation_value == "enemy") and "enemy" or "disabled"
    logTrace(string.format(
        "updateFleetBlacklist: %d sector macro(s), faction blocking=%s, fleet_id=%s, initialized=%s",
        #(threatened_macro_list or {}),
        relation_display,
        tostring(GT_Blacklist.fleet_blacklist_id),
        tostring(GT_Blacklist.initialized)
    ))
    debugLog(string.format("Updating fleet blacklist with %d threatened sector macros, faction blocking: %s", 
             #threatened_macro_list, relation_display))
    
    -- MD already sent us the macros, so we can use them directly!
    local macro_strings = {}  -- Keep references to prevent garbage collection
    
    for _, macro_name in ipairs(threatened_macro_list) do
        if macro_name and macro_name ~= "" and macro_name ~= "nil" then
            -- Store FFI string to prevent GC
            table.insert(macro_strings, ffi.new("char[?]", #macro_name + 1, macro_name))
            debugLog(string.format("  Added threatened sector macro: %s", macro_name))
        else
            debugLog(string.format("WARNING: Skipping invalid macro: '%s'", tostring(macro_name)), "WARN")
        end
    end
    
    -- Allow empty blacklist (0 sectors) - this is intentional for "clear all threats"
    debugLog(string.format("Processed %d valid threatened sector macros", #macro_strings))
    
    -- Prepare FFI array of string pointers (handle empty case)
    local macros_array = nil
    if #macro_strings > 0 then
        macros_array = ffi.new("const char*[?]", #macro_strings)
        for i, macro_str in ipairs(macro_strings) do
            macros_array[i-1] = macro_str
        end
    end
    
    -- Set up relation value for automatic faction blocking
    -- X4 expects the literal string "enemy" to block enemy factions
    --   "enemy" = block all sectors owned by enemy factions
    --   ""      = disabled (no faction blocking)
    local relation_str = ffi.new("char[?]", #relation_value + 1, relation_value)
    
    if relation_value == "enemy" then
        debugLog("Faction-based blocking: ENABLED (blocks all enemy faction sectors)")
    else
        debugLog(" Faction-based blocking: DISABLED")
    end
    
    -- Create blacklist info structure
    local blacklist_name = GT_Blacklist.CONFIG.BLACKLIST_NAME_PREFIX .. "Fleet"
    local name_str = ffi.new("char[?]", #blacklist_name + 1, blacklist_name)
    local type_str = ffi.new("char[?]", 13, "sectortravel")  -- 12 chars + null
    
    local info = ffi.new("BlacklistInfo2")
    info.name = name_str
    info.type = type_str
    info.nummacros = #macro_strings
    info.macros = macros_array
    info.numfactions = 0
    info.factions = nil
    info.relation = relation_str  -- X4 will automatically block sectors owned by hostile factions!
    info.hazardous = false
    info.usemacrowhitelist = false
    info.usefactionwhitelist = false
    
    -- Log what we're creating/updating
    debugLog("========== BLACKLIST CONFIGURATION ==========")
    debugLog(string.format("  name: %s", blacklist_name))
    debugLog(string.format("  type: %s", ffi.string(type_str)))
    debugLog(string.format("  nummacros: %d", #macro_strings))
    debugLog(string.format("  numfactions: %d", info.numfactions))
    debugLog(string.format("  relation: '%s' (length: %d)", ffi.string(relation_str), #ffi.string(relation_str)))
    debugLog(string.format("  hazardous: %s", tostring(info.hazardous)))
    debugLog(string.format("  usemacrowhitelist: %s", tostring(info.usemacrowhitelist)))
    debugLog(string.format("  usefactionwhitelist: %s", tostring(info.usefactionwhitelist)))
    debugLog("=============================================")
    
    -- Create or update blacklist
    if not GT_Blacklist.fleet_blacklist_id then
        debugLog(string.format("Creating new fleet blacklist: %s", blacklist_name))
        local ok, new_id = pcall(function() return C.CreateBlacklist2(info) end)
        if not ok then
            logTrace("CreateBlacklist2 pcall failed: " .. tostring(new_id), "ERROR")
            return false
        end
        GT_Blacklist.fleet_blacklist_id = new_id
        if not new_id or new_id == 0 then
            logTrace("CreateBlacklist2 returned invalid id=0", "ERROR")
            return false
        end
        logTrace(string.format(
            "CreateBlacklist2 OK: id=%d macros=[%s] relation='%s'",
            new_id, summarizeMacroList(threatened_macro_list), relation_value
        ))
        debugLog(string.format("Fleet blacklist created with ID: %d", GT_Blacklist.fleet_blacklist_id))
        logBlacklistVerify(GT_Blacklist.fleet_blacklist_id, "after create")
    else
        -- Try to verify blacklist still exists before updating (player might have deleted it manually)
        local blacklist_still_exists = false
        
        -- Check if GetBlacklistInfo2 is available (might be restricted by X4 security)
        if type(C.GetBlacklistInfo2) == "cdata" then
            local verify_buf = ffi.new("BlacklistInfo2")
            local success, exists = pcall(function() return C.GetBlacklistInfo2(verify_buf, GT_Blacklist.fleet_blacklist_id) end)
            
            if success then
                blacklist_still_exists = exists
                if not exists then
                    debugLog(string.format(" Blacklist ID %d no longer exists (manually deleted?)", GT_Blacklist.fleet_blacklist_id))
                end
            else
                -- Function failed (likely restricted) - assume blacklist exists
                debugLog(" GetBlacklistInfo2 is restricted - cannot verify blacklist existence", "WARN")
                blacklist_still_exists = true -- Assume it exists
            end
        else
            -- Function not available - assume blacklist exists
            debugLog(" GetBlacklistInfo2 not available - cannot verify blacklist existence", "WARN")
            blacklist_still_exists = true -- Assume it exists
        end
        
        if not blacklist_still_exists then
            -- Blacklist was deleted - recreate it
            debugLog("Recreating deleted blacklist...")
            local ok, new_id = pcall(function() return C.CreateBlacklist2(info) end)
            if not ok then
                logTrace("Recreate CreateBlacklist2 pcall failed: " .. tostring(new_id), "ERROR")
                return false
            end
            GT_Blacklist.fleet_blacklist_id = new_id
            if not new_id or new_id == 0 then
                logTrace("Recreate CreateBlacklist2 returned invalid id=0", "ERROR")
                return false
            end
            logTrace(string.format(
                "Recreate OK: id=%d macros=[%s] relation='%s'",
                new_id, summarizeMacroList(threatened_macro_list), relation_value
            ))
            debugLog(string.format("Fleet blacklist recreated with new ID: %d", GT_Blacklist.fleet_blacklist_id))
            logBlacklistVerify(GT_Blacklist.fleet_blacklist_id, "after recreate")
            
            -- Notify MD to update the stored ID
            AddUITriggeredEvent("gt_blacklist_manager", "BlacklistCreated", GT_Blacklist.fleet_blacklist_id)
        else
            -- Blacklist exists (or we can't verify) - update it
            debugLog(string.format("Updating existing fleet blacklist ID: %d", GT_Blacklist.fleet_blacklist_id))
            info.id = GT_Blacklist.fleet_blacklist_id
            local ok, err = pcall(function() C.UpdateBlacklist2(info) end)
            if not ok then
                logTrace(string.format(
                    "UpdateBlacklist2 pcall failed for id=%s: %s",
                    tostring(GT_Blacklist.fleet_blacklist_id), tostring(err)
                ), "ERROR")
                return false
            end
            logTrace(string.format(
                "UpdateBlacklist2 OK: id=%d macros=[%s] relation='%s'",
                GT_Blacklist.fleet_blacklist_id, summarizeMacroList(threatened_macro_list), relation_value
            ))
            debugLog("Fleet blacklist updated")
            logBlacklistVerify(GT_Blacklist.fleet_blacklist_id, "after update")
        end
    end
    
    return true
end

--- Apply blacklist to a specific ship
local function applyBlacklistToShip(ship_id, blacklist_id)
    if not ship_id or ship_id == 0 then
        debugLog("Invalid ship ID provided", "ERROR")
        return false
    end
    
    if not blacklist_id or blacklist_id == 0 then
        debugLog("Invalid blacklist ID provided", "ERROR")
        return false
    end
    
    -- Apply blacklist to ship for sector travel (no per-ship logging for performance)
    C.SetControllableBlacklist(ship_id, blacklist_id, "sectortravel", true)
    
    -- Track assignment
    GT_Blacklist.dynamic_blacklists[ship_id] = blacklist_id
    
    return true
end

--- Remove blacklist from a specific ship
local function removeBlacklistFromShip(ship_id)
    if not ship_id or ship_id == 0 then
        debugLog("Invalid ship ID provided", "ERROR")
        return false
    end
    
    local blacklist_id = GT_Blacklist.dynamic_blacklists[ship_id]
    if not blacklist_id then
        return true -- Already has no blacklist
    end
    
    -- Remove blacklist assignment (-1 = use default)
    C.SetControllableBlacklist(ship_id, -1, "sectortravel", false)
    
    -- Clear tracking
    GT_Blacklist.dynamic_blacklists[ship_id] = nil
    
    return true
end

--- Apply fleet blacklist to non-subordinate GT ships (subordinates inherit from commanders)
local function applyFleetBlacklistToAllShips(ship_list)
    if not GT_Blacklist.fleet_blacklist_id then
        logTrace("applyFleetBlacklistToAllShips: no fleet blacklist id to apply", "WARNING")
        debugLog("No fleet blacklist to apply", "WARN")
        return false
    end
    
    debugLog(string.format("Applying fleet blacklist to %d non-subordinate ships", #ship_list))
    
    -- Debug: Show first 3 ship ID strings
    if #ship_list > 0 then
        debugLog(string.format("Sample ship IDs: %s, %s, %s", 
            ship_list[1] or "nil", 
            ship_list[2] or "nil", 
            ship_list[3] or "nil"))
    end
    
    local success_count = 0
    local fail_count = 0
    for i, ship_id_string in ipairs(ship_list) do
        local ship_id = convertStringToID(ship_id_string)
        
        -- Debug first 3 conversions
        if i <= 3 then
            debugLog(string.format("  Ship %d: '%s' ID: %s", i, ship_id_string, tostring(ship_id)))
        end
        
        if ship_id ~= 0 then
            if applyBlacklistToShip(ship_id, GT_Blacklist.fleet_blacklist_id) then
                success_count = success_count + 1
            else
                fail_count = fail_count + 1
            end
        else
            fail_count = fail_count + 1
            if i <= 3 then
                debugLog(string.format("  Failed to convert ship ID string: '%s'", ship_id_string), "WARN")
            end
        end
    end
    
    debugLog(string.format("Fleet blacklist applied to %d/%d non-subordinate ships (%d failed)", success_count, #ship_list, fail_count))
    return true
end

-- =============================================================================
-- THREAT DATA PROCESSING
-- =============================================================================

--- Parse threat data from MD script format
--- @param threat_data_string string Format: "sector_macro1:level1:timestamp1|sector_macro2:level2:timestamp2|..."
--- @return table threatened_macros List of sector macros to blacklist
local function parseThreatData(threat_data_string)
    local payload_len = threat_data_string and #threat_data_string or 0
    debugLog(string.format("Parsing threat data (%d chars): %s", payload_len, threat_data_string))
    
    -- Simple format: "sector_macro1:level1:timestamp1|sector_macro2:level2:timestamp2|..."
    local threatened_macros = {}
    local entry_count = 0
    local below_threshold = 0
    local invalid_entries = 0
    
    for sector_entry in string.gmatch(threat_data_string or "", "([^|]+)") do
        entry_count = entry_count + 1
        local parts = {}
        for part in string.gmatch(sector_entry, "([^:]+)") do
            table.insert(parts, part)
        end
        
        if #parts >= 3 then
            local sector_macro = parts[1]
            local threat_level = tonumber(parts[2]) or 0
            local timestamp = tonumber(parts[3]) or 0
            
            -- Only blacklist if threat level is above threshold and macro is valid
            if threat_level >= GT_Blacklist.CONFIG.THREAT_LEVEL_THRESHOLD and sector_macro and sector_macro ~= "" and sector_macro ~= "nil" then
                table.insert(threatened_macros, sector_macro)
                GT_Blacklist.blacklisted_sectors[sector_macro] = {
                    threat_level = threat_level,
                    timestamp = timestamp
                }
            elseif threat_level < GT_Blacklist.CONFIG.THREAT_LEVEL_THRESHOLD then
                below_threshold = below_threshold + 1
            else
                invalid_entries = invalid_entries + 1
            end
        else
            invalid_entries = invalid_entries + 1
        end
    end
    
    logTrace(string.format(
        "parseThreatData: entries=%d blacklisted=%d below_threshold=%d invalid=%d threshold=%d sample=[%s]",
        entry_count, #threatened_macros, below_threshold, invalid_entries,
        GT_Blacklist.CONFIG.THREAT_LEVEL_THRESHOLD,
        summarizeMacroList(threatened_macros)
    ))
    debugLog(string.format("Found %d sector macros above threat threshold", #threatened_macros))
    return threatened_macros
end

--- Clean up expired threats from tracking
local function cleanupExpiredThreats(current_time, expiry_time)
    local removed_count = 0
    
    for sector_name, threat_info in pairs(GT_Blacklist.blacklisted_sectors) do
        local age = current_time - threat_info.timestamp
        if age > expiry_time then
            GT_Blacklist.blacklisted_sectors[sector_name] = nil
            removed_count = removed_count + 1
        end
    end
    
    if removed_count > 0 then
        debugLog(string.format("Cleaned up %d expired threat entries", removed_count))
    end
    
    return removed_count
end

-- =============================================================================
-- EVENT HANDLERS - MD SCRIPT INTERFACE
-- =============================================================================

-- Track dropped updates when not initialized (always log first; then every 25th)
local dropped_update_count = 0

--- Initialize the blacklist system
local function onInitialize(_, event_data)
    local already_initialized = GT_Blacklist.initialized
    logTrace(string.format(
        "EVENT Initialize received (initialized=%s, payload_len=%d)",
        tostring(GT_Blacklist.initialized), event_data and #event_data or 0
    ))
    debugLog("Initializing GalaxyTrader Dynamic Blacklist System...")
    
    if already_initialized then
        logTrace("Initialize re-sync: refreshing settings and fleet blacklist shell")
        debugLog("System already initialized - re-syncing", "WARN")
    end
    
    -- Verify FFI functions are available
    if type(C.CreateBlacklist2) ~= "cdata" then
        logTrace("Initialize failed: CreateBlacklist2 FFI not available", "ERROR")
        debugLog("ERROR: CreateBlacklist2 FFI function not available!", "ERROR")
        return false
    end
    
    -- Parse init data: "relation|existing_id|threshold"
    -- relation is "enemy" (enabled) or "" (disabled)
    -- existing_id is the blacklist ID (0 = create new)
    -- threshold is the threat level threshold (1-5)
    debugLog(string.format("Received event_data from MD: '%s' (type: %s, length: %d)",
             tostring(event_data), type(event_data), event_data and #event_data or 0))
    
    local relation_value, existing_id, threshold = "", 0, 3
    if event_data and event_data ~= "" then
        local parts = {}
        for part in string.gmatch(event_data, "[^|]+") do
            table.insert(parts, part)
        end
        logTrace(string.format(
            "Initialize payload parsed: relation='%s' existing_id=%s threshold=%s",
            tostring(parts[1] or ""), tostring(parts[2] or "0"), tostring(parts[3] or "3")
        ))
        debugLog(string.format("Parsed parts: [1]='%s', [2]='%s', [3]='%s'",
                 tostring(parts[1] or "nil"), tostring(parts[2] or "nil"), tostring(parts[3] or "nil")))
        relation_value = parts[1] or ""
        existing_id = tonumber(parts[2]) or 0
        threshold = tonumber(parts[3]) or 3
    else
        logTrace("Initialize payload empty - using defaults (relation='', id=0, threshold=3)", "WARNING")
    end
    
    -- Apply threshold from MD settings
    GT_Blacklist.CONFIG.THREAT_LEVEL_THRESHOLD = threshold
    debugLog(string.format("Blacklist threshold set to: %d", threshold))
    
    GT_Blacklist.relation_value = relation_value
    
    -- Check if we're reusing an existing blacklist or creating new
    local faction_blocking_status = (relation_value == "enemy") and '"enemy"' or 'disabled'
    if existing_id > 0 then
        debugLog(string.format("â™»ï¸ Reusing existing blacklist ID: %d (faction blocking: %s)", existing_id, faction_blocking_status))
        GT_Blacklist.fleet_blacklist_id = existing_id
        -- No need to notify MD - it already knows the ID
    else
        debugLog(string.format("ðŸ†• Creating NEW fleet blacklist (faction blocking: %s)", faction_blocking_status))
    end
    
    -- Create/Update blacklist with relation value
    -- X4 will automatically block all sectors owned by enemy factions if relation="enemy"
    local empty_sectors = {}
    local success = updateFleetBlacklist(empty_sectors, GT_Blacklist.relation_value)
    
    if not success then
        logTrace("Initialize failed: updateFleetBlacklist returned false", "ERROR")
        debugLog(" Failed to create/update blacklist", "WARN")
        return false
    end
    
    -- If we created a NEW blacklist, notify MD to store the ID
    if not already_initialized and existing_id == 0 and GT_Blacklist.fleet_blacklist_id then
        logTrace(string.format("Notifying MD BlacklistCreated id=%d", GT_Blacklist.fleet_blacklist_id))
        debugLog(string.format("Notifying MD of new blacklist ID: %d", GT_Blacklist.fleet_blacklist_id))
        AddUITriggeredEvent("gt_blacklist_manager", "BlacklistCreated", GT_Blacklist.fleet_blacklist_id)
    end
    
    debugLog("Fleet blacklist initialized with faction-based blocking enabled")
    
    GT_Blacklist.initialized = true
    dropped_update_count = 0
    logTrace(string.format(
        "%s: id=%s threshold=%d relation='%s' (awaiting Update/ApplyToFleet)",
        already_initialized and "RE-SYNC OK" or "INIT OK",
        tostring(GT_Blacklist.fleet_blacklist_id), threshold, relation_value
    ))
    debugLog("Dynamic Blacklist System initialized successfully")
    
    return true
end

--- Update blacklists based on current threat data
local function onUpdateBlacklist(_, event_data)
    local payload_len = event_data and #event_data or 0
    if not GT_Blacklist.initialized then
        dropped_update_count = dropped_update_count + 1
        if dropped_update_count == 1 or (dropped_update_count % 25) == 0 then
            logTrace(string.format(
                "EVENT Update DROPPED (#%d): initialized=false payload_len=%d (MD sent update before Initialize?)",
                dropped_update_count, payload_len
            ), "WARNING")
        end
        debugLog("System not initialized - ignoring update request", "WARN")
        return false
    end
    
    logTrace(string.format("EVENT Update received payload_len=%d", payload_len))
    debugLog("Received blacklist update request")
    
    -- MD sends a full snapshot each time (not incremental). Replace local tracking so
    -- a clear/wipe cannot leave stale sectors that CleanupExpired would resurrect.
    GT_Blacklist.blacklisted_sectors = {}
    
    local threatened_sectors = {}
    if event_data and event_data ~= "" then
        threatened_sectors = parseThreatData(event_data)
    else
        debugLog("No threat data provided - updating blacklist to empty")
    end
    
    -- Update fleet blacklist with threatened sectors AND relation value (must pass it every time!)
    local ok = updateFleetBlacklist(threatened_sectors, GT_Blacklist.relation_value)
    if ok then
        logTrace(string.format(
            "EVENT Update applied: %d sector macro(s) id=%s",
            #threatened_sectors, tostring(GT_Blacklist.fleet_blacklist_id)
        ))
    else
        logTrace("EVENT Update failed: updateFleetBlacklist returned false", "ERROR")
    end
    return ok
end

--- Apply blacklist to GT fleet ships
local function onApplyToFleet(_, event_data)
    if not GT_Blacklist.initialized then
        logTrace("EVENT ApplyToFleet DROPPED: initialized=false", "WARNING")
        debugLog("System not initialized - ignoring apply request", "WARN")
        return false
    end
    
    local ship_list = parseShipListPayload(event_data)
    logTrace(string.format(
        "EVENT ApplyToFleet received ships=%d fleet_id=%s",
        #ship_list, tostring(GT_Blacklist.fleet_blacklist_id)
    ))
    debugLog("Received fleet application request")
    
    if #ship_list == 0 then
        logTrace("EVENT ApplyToFleet failed: empty ship list", "ERROR")
        debugLog("No ship list provided", "ERROR")
        return false
    end
    
    local ok = applyFleetBlacklistToAllShips(ship_list)
    logTrace(string.format(
        "EVENT ApplyToFleet finished: ships=%d ok=%s fleet_id=%s",
        #ship_list, tostring(ok), tostring(GT_Blacklist.fleet_blacklist_id)
    ))
    return ok
end

--- Clean up expired threats and update blacklist
local function onCleanupExpired(_, event_data)
    if not GT_Blacklist.initialized then
        logTrace("EVENT CleanupExpired DROPPED: initialized=false", "WARNING")
        return false
    end
    
    logTrace(string.format("EVENT CleanupExpired received payload_len=%d", event_data and #event_data or 0))
    
    -- Check for nil/empty event_data before parsing (prevents crash)
    if not event_data or event_data == "" then
        debugLog("Invalid cleanup parameters: event_data is nil or empty", "ERROR")
        return false
    end
    
    -- Format: "current_time:expiry_time"
    local parts = {}
    for part in string.gmatch(event_data, "([^:]+)") do
        table.insert(parts, part)
    end
    
    if #parts < 2 then
        debugLog("Invalid cleanup parameters", "ERROR")
        return false
    end
    
    local current_time = tonumber(parts[1]) or 0
    local expiry_time = tonumber(parts[2]) or 3600
    
    debugLog(string.format("Cleaning up threats older than %d seconds", expiry_time))
    
    -- Remove expired threats
    local removed = cleanupExpiredThreats(current_time, expiry_time)
    
    -- Rebuild blacklist with remaining threats
    local threatened_sectors = {}
    for sector_name, _ in pairs(GT_Blacklist.blacklisted_sectors) do
        table.insert(threatened_sectors, sector_name)
    end
    
    updateFleetBlacklist(threatened_sectors, GT_Blacklist.relation_value)
    
    return true
end

--- Remove blacklist from a specific ship
local function onRemoveFromShip(_, event_data)
    if not GT_Blacklist.initialized then
        return false
    end
    
    local ship_id = convertStringToID(event_data)
    return removeBlacklistFromShip(ship_id)
end

--- Force recreate the blacklist (bypasses initialized check)
local function onRecreateBlacklist(_, event_data)
    logTrace("EVENT Recreate received - resetting initialized flag")
    debugLog("FORCE RECREATE: Resetting blacklist system...")
    
    -- Reset initialized flag to allow recreation
    GT_Blacklist.initialized = false
    
    -- Call the normal initialize function
    return onInitialize(_, event_data)
end

-- =============================================================================
-- MODULE INITIALIZATION
-- =============================================================================

local function init()
    logLoad("================================================================================")
    logLoad("GalaxyTrader MK3 - Dynamic Blacklist Manager Loading...")
    logLoad("================================================================================")
    
    -- Verify FFI availability
    if not ffi then
        logLoad("ERROR: FFI not available!", "ERROR")
        return false
    end
    
    -- Register event handlers
    local events = {
        { name = "GT_Blacklist.Initialize",      handler = onInitialize },
        { name = "GT_Blacklist.Update",          handler = onUpdateBlacklist },
        { name = "GT_Blacklist.ApplyToFleet",    handler = onApplyToFleet },
        { name = "GT_Blacklist.CleanupExpired",  handler = onCleanupExpired },
        { name = "GT_Blacklist.RemoveFromShip",  handler = onRemoveFromShip },
        { name = "GT_Blacklist.Recreate",        handler = onRecreateBlacklist },
    }
    
    for _, event in ipairs(events) do
        local success = pcall(RegisterEvent, event.name, event.handler)
        if success then
            logLoad(string.format("Registered event: %s", event.name))
        else
            logLoad(string.format("Failed to register event: %s", event.name), "ERROR")
        end
    end
    
    logLoad("================================================================================")
    logLoad("Dynamic Blacklist Manager loaded successfully!")
    logLoad("Signalled MD: gt_blacklist_manager Ready")
    logLoad("Runtime state: initialized=false (waiting for GT_Blacklist.Initialize from MD)")
    logLoad("================================================================================")

    AddUITriggeredEvent("gt_blacklist_manager", "Ready", {})
    
    return true
end

-- Initialize module immediately
init()

-- Export module for debugging/testing
return GT_Blacklist

-- GalaxyTrader - Trading Academy submenu
-- Spec: DOCS/Spec/FEATURE_FLEET_ACADEMY.md
--
-- Renders a custom MapMenu context frame with one button per academy course.
-- Reads pilot/player/course state from the player NPC blackboard, computes
-- personalized cost (quadratic curve with floor) and duration (linear scale
-- with floor), and signals the chosen course back to MD via SignalObject.
--
-- Blackboard keys produced by md.GT_Context_Academy.GT_AcademyAction:
--   $GT_Academy_PilotLevel       (int, 1..15)
--   $GT_Academy_PlayerMoney      (raw credits, *100)
--   $GT_Academy_PilotName        (string)
--   $GT_Academy_ShipName         (string)
--   $GT_Academy_Courses          (list of tables)
--     each (MD side):  { $Index, $TargetLevel, $ListedCost, $ListedDuration, $TextId }
--     each (Lua side): {  Index,  TargetLevel,  ListedCost,  ListedDuration,  TextId }
--     (X4 strips the `$` prefix from MD table keys when exposing to Lua.)
--   $GT_Academy_MinCostPercent   (number, e.g. 0.05)
--   $GT_Academy_MinDuration      (seconds, e.g. 300)
--   $GT_Academy_CostExponent     (number, e.g. 1.5)
--
-- Blackboard keys consumed by md.GT_Context_Academy.HandleAcademyCourseChosen:
--   $GT_Academy_ChosenIndex
--   $GT_Academy_ChosenLevel
--   $GT_Academy_ChosenCost      (raw credits, *100)
--   $GT_Academy_ChosenDuration  (seconds)

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    typedef struct {
        int x;
        int y;
    } Coord2D;
    Coord2D GetCenteredMousePos(void);
]]

local menu = Helper.getMenu("MapMenu")
if not menu then
    DebugError("[GT Academy] MapMenu not found - academy submenu will not be available")
    return
end

-- ---------------------------------------------------------------------------
-- Constants
-- ---------------------------------------------------------------------------

local MENU_WIDTH                = 460
local LIST_PAGE_TEXT            = 77000
local TOP_LEVEL_TITLE_TEXT_ID   = 9910
local INSUFFICIENT_FUNDS_TEXT_ID = 9921
local UNAVAILABLE_TEXT_ID       = 9922

local originalCreateContextFrame  = menu.createContextFrame
local originalRefreshContextFrame = menu.refreshContextFrame

-- ---------------------------------------------------------------------------
-- Local helpers
-- ---------------------------------------------------------------------------

local function debugLog(msg)
    DebugError("[GT Academy] " .. tostring(msg))
end

local function getPlayerId64()
    return ConvertStringTo64Bit(tostring(C.GetPlayerID()))
end

-- Blackboard typed accessors with fallbacks. The list reader returns nil if
-- the key is missing or not a table, so callers can short-circuit cleanly.
local function readBlackboardList(playerId, key)
    local raw = GetNPCBlackboard(playerId, key)
    return (type(raw) == "table") and raw or nil
end

local function readBlackboardNumber(playerId, key, fallback)
    local raw = GetNPCBlackboard(playerId, key)
    return (type(raw) == "number") and raw or fallback
end

local function readBlackboardString(playerId, key, fallback)
    local raw = GetNPCBlackboard(playerId, key)
    return (type(raw) == "string") and raw or fallback
end

-- ---------------------------------------------------------------------------
-- Course math
--
-- Cost formula:
--   listedCost is the PRICE for a level-1 pilot (the "headline" price).
--   For a pilot already at $current, scale by ((target - current) / (target - 1))^exponent
--   and floor at minPercent of listedCost.
-- Duration formula:
--   listedDuration scales linearly with the same level-difference ratio,
--   floored at minDuration seconds.
-- ---------------------------------------------------------------------------

local function calculateCost(listedCost, currentLevel, targetLevel, minPercent, exponent)
    if targetLevel <= 1 then
        return listedCost
    end
    local span = targetLevel - 1
    local diff = targetLevel - math.max(1, currentLevel)
    if diff <= 0 then
        return 0
    end
    local ratio = diff / span
    local scale = math.pow(ratio, exponent or 1.5)
    local minScale = minPercent or 0.05
    if scale < minScale then
        scale = minScale
    end
    -- Round to whole credits. (Inputs are already in Cr -- GetNPCBlackboard
    -- auto-converts money-typed fields from centicredits when reading from
    -- player.entity. Earlier code snapped to multiples of 100 Cr on the
    -- centicredit assumption, which silently dropped two digits of precision.)
    return math.floor(listedCost * scale + 0.5)
end

local function calculateDuration(listedDuration, currentLevel, targetLevel, minDuration)
    if targetLevel <= 1 then
        return listedDuration
    end
    local span = targetLevel - 1
    local diff = targetLevel - math.max(1, currentLevel)
    if diff <= 0 then
        return minDuration or 300
    end
    local ratio = diff / span
    local scaled = math.floor(listedDuration * ratio + 0.5)
    local floor = minDuration or 300
    if scaled < floor then
        scaled = floor
    end
    return scaled
end

local function buildCourseLabel(course, currentLevel)
    local cost = calculateCost(
        course.listedCost,
        currentLevel,
        course.targetLevel,
        course.minPercent,
        course.costExponent
    )
    local duration = calculateDuration(
        course.listedDuration,
        currentLevel,
        course.targetLevel,
        course.minDuration
    )
    course.scaledCost = cost
    course.scaledDuration = duration

    local template = GT_UI.safeReadText(LIST_PAGE_TEXT, course.textId, nil)
    if template then
        local filled = template
        filled = string.gsub(filled, "%%1", GT_UI.formatCreditsExact(cost))
        filled = string.gsub(filled, "%%2", GT_UI.formatDurationMin(duration))
        return filled
    end
    return string.format("Level %d - %s / %s",
        course.targetLevel,
        GT_UI.formatCreditsExact(cost),
        GT_UI.formatDurationMin(duration))
end

-- ---------------------------------------------------------------------------
-- Blackboard snapshot
-- ---------------------------------------------------------------------------

local function snapshotContext()
    local playerId = getPlayerId64()
    local courses  = readBlackboardList(playerId, "$GT_Academy_Courses")
    if not courses then
        debugLog("snapshotContext: no $GT_Academy_Courses on blackboard")
        return nil
    end

    local pilotLevel   = readBlackboardNumber(playerId, "$GT_Academy_PilotLevel",     1)
    local playerMoney  = readBlackboardNumber(playerId, "$GT_Academy_PlayerMoney",    0)
    local pilotName    = readBlackboardString(playerId, "$GT_Academy_PilotName",      "Pilot")
    local shipName     = readBlackboardString(playerId, "$GT_Academy_ShipName",       "Ship")
    local minPercent   = readBlackboardNumber(playerId, "$GT_Academy_MinCostPercent", 0.05)
    local minDuration  = readBlackboardNumber(playerId, "$GT_Academy_MinDuration",    300)
    local costExponent = readBlackboardNumber(playerId, "$GT_Academy_CostExponent",   1.5)

    -- MD `$Field` is exposed to Lua as `Field` (case preserved, `$` stripped).
    -- The legacy `["$Field"]` and lowercase `field` lookups are kept as defensive
    -- fallbacks but should never fire in normal operation.
    local normalized = {}
    for i = 1, #courses do
        local c = courses[i]
        if type(c) == "table" then
            table.insert(normalized, {
                index          = c.Index          or c["$Index"]          or c.index          or i,
                targetLevel    = c.TargetLevel    or c["$TargetLevel"]    or c.targetLevel    or 0,
                listedCost     = c.ListedCost     or c["$ListedCost"]     or c.listedCost     or 0,
                listedDuration = c.ListedDuration or c["$ListedDuration"] or c.listedDuration or 0,
                textId         = c.TextId         or c["$TextId"]         or c.textId         or 0,
                minPercent     = minPercent,
                minDuration    = minDuration,
                costExponent   = costExponent,
            })
        end
    end

    return {
        playerId    = playerId,
        pilotLevel  = pilotLevel,
        playerMoney = playerMoney,
        pilotName   = pilotName,
        shipName    = shipName,
        courses     = normalized,
    }
end

-- ---------------------------------------------------------------------------
-- Course click â†’ write blackboard + signal MD
-- ---------------------------------------------------------------------------

local function chooseCourse(component, course, ctx)
    if not course then return end

    local playerId = ctx.playerId
    -- Round-trip unit fix: GetNPCBlackboard auto-converts money-typed MD
    -- fields from centi-credits to credits when handing them to Lua, but
    -- SetNPCBlackboard does NOT reverse that conversion - whatever number
    -- Lua writes lands raw on the player.entity blackboard. Every MD code
    -- path downstream (logbook message templates, reward_player, the
    -- insufficient-funds notification, debug texts) assumes the stored
    -- value is in centi-credits and divides by 100 to display credits.
    -- Pre-multiply by 100 here so the round-trip is consistent: the
    -- button shows "272,166 Cr", MD's `$lockedCost / 100` displays
    -- "272,166", and `($lockedCost * 1Cr) / 100` deducts exactly 272,166 Cr.
    -- Without this pre-multiply the player is charged 1/100th of the
    -- promised price (verified empirically: HAW-289's level-4 course
    -- showed 272,166 Cr on the button but only 2,721 Cr in the logbook).
    local centiCredits = math.floor(course.scaledCost * 100 + 0.5)
    SetNPCBlackboard(playerId, "$GT_Academy_ChosenIndex",    course.index)
    SetNPCBlackboard(playerId, "$GT_Academy_ChosenLevel",    course.targetLevel)
    SetNPCBlackboard(playerId, "$GT_Academy_ChosenCost",     centiCredits)
    SetNPCBlackboard(playerId, "$GT_Academy_ChosenDuration", course.scaledDuration)

    debugLog(string.format(
        "Player chose Level %d course (cost=%d Cr -> %d centi-cr raw, duration=%d s) for ship %s",
        course.targetLevel, course.scaledCost, centiCredits, course.scaledDuration, tostring(component)
    ))

    SignalObject(playerId, "gt_academy_course_chosen", ConvertStringToLuaID(tostring(component)))
end

-- ---------------------------------------------------------------------------
-- Frame rendering
-- ---------------------------------------------------------------------------

-- Substitute %1, %2, ... placeholders in a localized template with the
-- supplied positional values. Mirrors X4's `%N`-style substitution rules:
-- only matches a literal `%<digit>`, leaves everything else alone.
local function fillPlaceholders(template, ...)
    local args = { ... }
    return (string.gsub(template, "%%(%d)", function(n)
        local v = args[tonumber(n)]
        return v ~= nil and tostring(v) or ("%" .. n)
    end))
end

-- Renders one course entry: an enabled action button, or a disabled button
-- followed by an explanatory caption row. Splitting the caption onto its own
-- row avoids the visual overlap that "label\n(reason)" inside a single
-- fixed-height button caused in earlier versions.
local function renderCourseRow(tbl, course, ctx, component)
    local label = buildCourseLabel(course, ctx.pilotLevel)

    if course.targetLevel <= ctx.pilotLevel then
        local row = tbl:addRow(true, { fixed = true })
        GT_UI.createButton(row[1], label, { active = false })
        local template = GT_UI.safeReadText(
            LIST_PAGE_TEXT, UNAVAILABLE_TEXT_ID,
            "Course unavailable - pilot %1 is already at or above this level")
        GT_UI.addCaptionRow(tbl, "(" .. fillPlaceholders(template, ctx.pilotName) .. ")")
        return
    end

    if ctx.playerMoney < course.scaledCost then
        local row = tbl:addRow(true, { fixed = true })
        GT_UI.createButton(row[1], label, { active = false })
        local template = GT_UI.safeReadText(
            LIST_PAGE_TEXT, INSUFFICIENT_FUNDS_TEXT_ID,
            "Insufficient funds for this course (need %1, have %2)")
        local note = fillPlaceholders(template,
            GT_UI.formatCreditsExact(course.scaledCost),
            GT_UI.formatCreditsExact(ctx.playerMoney))
        GT_UI.addCaptionRow(tbl, "(" .. note .. ")")
        return
    end

    local row = tbl:addRow(true, { fixed = true })
    GT_UI.createButton(row[1], label, {
        onClick = function()
            chooseCourse(component, course, ctx)
            menu.noupdate = false
            if menu.refreshInfoFrame then
                menu.refreshInfoFrame()
            end
            menu.closeContextMenu("back")
        end,
    })
end

function menu.createGTAcademyContext(frame)
    local component = menu.contextMenuData and menu.contextMenuData.component
    local ctx       = menu.contextMenuData and menu.contextMenuData.ctx
    if not component or not ctx then
        debugLog("createGTAcademyContext: missing component or context, aborting")
        return
    end

    local tbl = frame:addTable(1, {
        tabOrder      = 2,
        x             = Helper.borderSize,
        y             = Helper.borderSize,
        width         = menu.contextMenuData.width,
        highlightMode = "off",
    })

    -- Title
    local titleRow = tbl:addRow(nil, { fixed = true })
    titleRow[1]:createText(
        GT_UI.safeReadText(LIST_PAGE_TEXT, TOP_LEVEL_TITLE_TEXT_ID, "Trading Academy"),
        Helper.headerRowCenteredProperties)

    -- Subtitle: pilot + ship + current level
    GT_UI.addCaptionRow(tbl,
        string.format("%s  -  %s  (Lvl %d)", ctx.pilotName, ctx.shipName, ctx.pilotLevel),
        { color = nil })  -- nil â†’ text_inactive default; explicit for clarity

    -- Course rows
    if #ctx.courses == 0 then
        GT_UI.addEmptyRow(tbl, "(no academy courses available)", 1)
    else
        for _, course in ipairs(ctx.courses) do
            renderCourseRow(tbl, course, ctx, component)
        end
    end

    -- Cancel button
    local cancelRow = tbl:addRow(true, { fixed = true })
    GT_UI.createButton(cancelRow[1], ReadText(1001, 64), {  -- "Cancel"
        onClick = function() menu.closeContextMenu("back") end,
    })

    -- Adjust frame position if needed (mirrors gt_context_rename pattern)
    local neededheight = tbl.properties.y + tbl:getVisibleHeight()
    if frame.properties.y + neededheight + Helper.frameBorder > Helper.viewHeight then
        menu.contextMenuData.yoffset = Helper.viewHeight - neededheight - Helper.frameBorder
        frame.properties.y = menu.contextMenuData.yoffset
    end
end

-- ---------------------------------------------------------------------------
-- Context-frame open / refresh hooks
-- ---------------------------------------------------------------------------

function menu.openGTAcademyContext(component)
    if not component then
        debugLog("openGTAcademyContext: no component supplied")
        return
    end

    local ctx = snapshotContext()
    if not ctx then
        debugLog("openGTAcademyContext: aborted - blackboard context missing")
        return
    end

    local mousepos = C.GetCenteredMousePos()
    menu.contextMenuMode = "gt_academy"
    menu.contextMenuData = {
        component = component,
        ctx       = ctx,
        xoffset   = mousepos.x + Helper.viewWidth / 2,
        yoffset   = mousepos.y + Helper.viewHeight / 2,
        width     = Helper.scaleX(MENU_WIDTH),
    }
    if menu.contextMenuData.xoffset + menu.contextMenuData.width > Helper.viewWidth then
        menu.contextMenuData.xoffset = Helper.viewWidth - menu.contextMenuData.width - Helper.frameBorder
    end

    menu.createContextFrame(menu.contextMenuData.width, nil,
        menu.contextMenuData.xoffset, menu.contextMenuData.yoffset)
    menu.refreshContextFrame()
end

menu.createContextFrame = function(width, height, xoffset, yoffset, noborder, startanimation, ...)
    if menu.contextMenuMode == "gt_academy" then
        local mousepos = C.GetCenteredMousePos()
        menu.contextMenuData = menu.contextMenuData or {}
        menu.contextMenuData.xoffset = xoffset or (mousepos.x + Helper.viewWidth / 2)
        menu.contextMenuData.yoffset = yoffset or (mousepos.y + Helper.viewHeight / 2)
        menu.contextMenuData.width   = width or Helper.scaleX(MENU_WIDTH)

        if menu.contextMenuData.xoffset + menu.contextMenuData.width > Helper.viewWidth then
            menu.contextMenuData.xoffset = Helper.viewWidth - menu.contextMenuData.width - Helper.frameBorder
        end

        local contextLayer = 2
        Helper.removeAllWidgetScripts(menu, contextLayer)

        menu.contextFrame = Helper.createFrameHandle(menu, {
            x        = menu.contextMenuData.xoffset - (noborder and 0 or 2 * Helper.borderSize),
            y        = menu.contextMenuData.yoffset,
            width    = menu.contextMenuData.width + (noborder and 0 or 2 * Helper.borderSize),
            layer    = contextLayer,
            standardButtons       = { close = true },
            closeOnUnhandledClick = true,
            startAnimation        = startanimation,
        })
        menu.contextFrame:setBackground("solid", { color = GT_UI.COLORS.frameBg })

        menu.createGTAcademyContext(menu.contextFrame)

        menu.contextFrame.properties.height = math.min(
            Helper.viewHeight - menu.contextFrame.properties.y,
            menu.contextFrame:getUsedHeight() + Helper.borderSize
        )

        return menu.contextFrame
    end

    if originalCreateContextFrame then
        return originalCreateContextFrame(width, height, xoffset, yoffset, noborder, startanimation, ...)
    end
end

menu.refreshContextFrame = function(setrow, setcol, noborder, ...)
    if menu.contextMenuMode == "gt_academy" then
        local contextLayer = 2
        Helper.removeAllWidgetScripts(menu, contextLayer)
        if menu.contextFrame then
            menu.contextFrame:display()
        end
        return
    end

    if originalRefreshContextFrame then
        originalRefreshContextFrame(setrow, setcol, noborder, ...)
    end
end

RegisterEvent("gt.openAcademyContext", function(_, component)
    if not component then
        debugLog("gt.openAcademyContext fired without component - ignoring")
        return
    end

    local component64 = ConvertIDTo64Bit(component)
    if not component64 or component64 == 0 then
        debugLog("gt.openAcademyContext: invalid component id")
        return
    end

    menu.openGTAcademyContext(component64)
end)

debugLog("Trading Academy context-menu integration loaded")
-- GalaxyTrader MK3 Diagnostic Report Display
-- Shows the exhaustive diagnostic report generated by gt_context_diagnose.xml
-- in a scrollable popup frame.
--
-- Uses GT_UI library (gt_ui_library.lua) for all table/row/button helpers.
--
-- Data transfer: MD serializes the report as a delimited string stored on
-- player.entity.$GT_DiagReport.  Format:
--   Sections separated by "@@"
--   Rows separated by ";;"
--   Fields separated by "||"
--   First element of each section chunk is the section name (no field separators)
--   Subsequent elements: STATUS||CHECK||DETAIL

-- FFI setup
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    UniverseID GetPlayerID(void);
    bool CopyToClipboard(const char*const text);
]]

local menu = Helper.getMenu("MapMenu")
if not menu then
    DebugError("[GT Diagnose] MapMenu not found - diagnostic display will not be available")
    return
end

-- Verify GT_UI library is loaded
if not GT_UI then
    DebugError("[GT Diagnose] ERROR: GT_UI library not loaded - check ui.xml load order")
    return
end

-- Diagnostic report state
local gtDiagnose = {
    sections    = {},   -- { { name=string, rows={ {status, check, detail}, ... } }, ... }
    shipId      = "",
    shipName    = "",
    timestamp   = 0,
    currentTab  = 1,    -- Currently selected section index (1-based)
    currentPage = 1,    -- Current page for paginated sections
    frameWidth  = 0,
    frameHeight = 0,
}

-- =============================================================================
-- REPORT PARSING
-- =============================================================================

function gtDiagnose.parseReport()
    local playerId = ConvertStringTo64Bit(tostring(C.GetPlayerID()))

    local reportStr   = GetNPCBlackboard(playerId, "$GT_DiagReport")
    gtDiagnose.shipId   = GetNPCBlackboard(playerId, "$GT_DiagShipId") or "???"
    gtDiagnose.shipName = GetNPCBlackboard(playerId, "$GT_DiagShipName") or "Unknown"
    gtDiagnose.timestamp = GetNPCBlackboard(playerId, "$GT_DiagTimestamp") or 0

    if not reportStr or reportStr == "" then
        DebugError("[GT Diagnose] No report data found on blackboard")
        return false
    end

    DebugError(string.format("[GT Diagnose] Report string length: %d, ship: %s",
        #reportStr, gtDiagnose.shipId))

    -- Parse sections (separated by "@@")
    local sectionChunks = GT_UI.split(reportStr, "@@")
    gtDiagnose.sections = {}

    for _, chunk in ipairs(sectionChunks) do
        local rowParts = GT_UI.split(chunk, ";;")
        if #rowParts > 0 then
            local section = {
                name    = rowParts[1],
                rows    = {},
                numCols = 3,  -- default: Status | Check | Detail
            }
            for i = 2, #rowParts do
                local fields = GT_UI.split(rowParts[i], "||")
                if #fields >= 6 then
                    -- 6-column structured row (Pair Details / Clearance)
                    table.insert(section.rows, {
                        status = fields[1] or "INFO",
                        check  = fields[2] or "",
                        detail = fields[3] or "",
                        col4   = fields[4] or "",
                        col5   = fields[5] or "",
                        col6   = fields[6] or "",
                    })
                    if section.numCols < 6 then
                        section.numCols = 6
                    end
                elseif #fields >= 3 then
                    table.insert(section.rows, {
                        status = fields[1] or "INFO",
                        check  = fields[2] or "",
                        detail = fields[3] or "",
                    })
                elseif #fields == 2 then
                    table.insert(section.rows, {
                        status = fields[1] or "INFO",
                        check  = fields[2] or "",
                        detail = "",
                    })
                end
            end
            table.insert(gtDiagnose.sections, section)
        end
    end

    DebugError(string.format("[GT Diagnose] Parsed %d sections", #gtDiagnose.sections))
    return #gtDiagnose.sections > 0
end

--- Flatten the full parsed report into plain text for clipboard / bug reports.
function gtDiagnose.buildPlainTextReport()
    local lines = {}
    table.insert(lines, string.format(
        "MK3 Diagnostic Report: %s (%s)",
        tostring(gtDiagnose.shipName), tostring(gtDiagnose.shipId)))
    table.insert(lines, string.format("Game time: %.0fs", gtDiagnose.timestamp or 0))
    table.insert(lines, "")

    for _, section in ipairs(gtDiagnose.sections) do
        table.insert(lines, "=== " .. tostring(section.name or "?") .. " ===")
        local numCols = section.numCols or 3
        if numCols >= 6 then
            table.insert(lines, "Status | Col1 | Col2 | Col3 | Col4 | Col5")
        else
            table.insert(lines, "Check | Status | Detail")
        end

        for _, row in ipairs(section.rows or {}) do
            if row.col4 then
                table.insert(lines, string.format(
                    "%s | %s | %s | %s | %s | %s",
                    tostring(row.status or ""),
                    tostring(row.check or ""),
                    tostring(row.detail or ""),
                    tostring(row.col4 or ""),
                    tostring(row.col5 or ""),
                    tostring(row.col6 or "")))
            else
                table.insert(lines, string.format(
                    "%s | %s | %s",
                    tostring(row.check or ""),
                    tostring(row.status or ""),
                    tostring(row.detail or "")))
            end
        end
        table.insert(lines, "")
    end

    return table.concat(lines, "\n")
end

function gtDiagnose.copyReportToClipboard()
    if #gtDiagnose.sections == 0 and not gtDiagnose.parseReport() then
        DebugError("[GT Diagnose] Copy failed: no report data")
        return false
    end

    local text = gtDiagnose.buildPlainTextReport()
    local success = C.CopyToClipboard(text)
    if success then
        DebugError(string.format("[GT Diagnose] Report copied to clipboard (%d chars)", #text))
    else
        DebugError("[GT Diagnose] CopyToClipboard failed")
    end
    return success
end

--- Copy button row for scrollable content tables (addRow(true) is invalid in fixed header tables).
function gtDiagnose.addCopyReportRow(tbl, columnCount)
    local row = tbl:addRow(true, { fixed = true, bgColor = GT_UI.COLORS.headerBg })
    row[1]:setColSpan(columnCount)
    GT_UI.createButton(row[1], "Copy Report", {
        fontSize = Helper.standardFontSize * 0.85,
        onClick  = function()
            gtDiagnose.copyReportToClipboard()
        end,
    })
end

-- =============================================================================
-- FRAME LIFECYCLE
-- =============================================================================

function gtDiagnose.openReport(component)
    DebugError("[GT Diagnose] openReport called")

    if not gtDiagnose.parseReport() then
        DebugError("[GT Diagnose] ERROR: Could not parse report data")
        return
    end

    -- Show Ship State tab first (contains VERDICT at top)
    gtDiagnose.currentTab  = 1
    gtDiagnose.currentPage = 1

    -- Frame dimensions
    local frameWidth  = math.min(Helper.viewWidth * 0.85, Helper.scaleX(1400))
    local frameHeight = math.min(Helper.viewHeight * 0.85, Helper.scaleY(900))
    gtDiagnose.frameWidth  = frameWidth
    gtDiagnose.frameHeight = frameHeight

    -- Center on screen
    local xpos = (Helper.viewWidth - frameWidth) / 2
    local ypos = (Helper.viewHeight - frameHeight) / 2

    menu.contextMenuMode = "gt_diagnose"
    menu.contextMenuData = {
        component = component,
        xoffset   = xpos,
        yoffset   = ypos,
        width     = frameWidth,
    }

    gtDiagnose.createAndDisplayFrame()
end

function gtDiagnose.createAndDisplayFrame()
    local contextLayer = 2
    Helper.removeAllWidgetScripts(menu, contextLayer)

    menu.contextFrame = Helper.createFrameHandle(menu, {
        x                     = menu.contextMenuData.xoffset,
        y                     = menu.contextMenuData.yoffset,
        width                 = gtDiagnose.frameWidth,
        height                = gtDiagnose.frameHeight,
        layer                 = contextLayer,
        standardButtons       = { close = true },
        closeOnUnhandledClick = false,
    })
    menu.contextFrame:setBackground("solid", { color = GT_UI.COLORS.frameBg })

    gtDiagnose.populateFrame(menu.contextFrame)
    menu.contextFrame:display()
end

-- =============================================================================
-- FRAME CONTENT
-- =============================================================================

function gtDiagnose.populateFrame(frame)
    local sections = gtDiagnose.sections
    if #sections == 0 then return end

    local width = gtDiagnose.frameWidth - 2 * Helper.borderSize

    -- ===== TITLE BAR =====
    local titleTable = frame:addTable(1, {
        tabOrder         = 0,
        x                = Helper.borderSize,
        y                = Helper.borderSize,
        width            = width,
        highlightMode    = "off",
        reserveScrollBar = false,
    })
    local titleRow = titleTable:addRow(nil, {
        fixed   = true,
        bgColor = GT_UI.COLORS.headerBg,
    })
    titleRow[1]:createText(
        string.format("MK3 Diagnostic Report: %s (%s)",
            tostring(gtDiagnose.shipName), tostring(gtDiagnose.shipId)),
        {
            halign   = "center",
            font     = Helper.headerRow1Font,
            fontsize = Helper.headerRow1FontSize,
        }
    )
    local titleHeight = Helper.headerRow1FontSize + 10

    -- ===== TAB BAR =====
    -- Sections in natural order (Ship State first, contains VERDICT at top)
    local numSections = #sections
    local tabDefs = {}
    for i = 1, numSections do
        tabDefs[i] = { name = sections[i].name, sectionIdx = i }
    end

    local _, tabHeight = GT_UI.createTabBar(frame, tabDefs, gtDiagnose.currentTab, {
        x       = Helper.borderSize,
        y       = titleHeight + Helper.borderSize + 4,
        width   = width,
        maxTabs = 14,
        onClick = function(sectionIdx)
            gtDiagnose.currentTab  = sectionIdx
            gtDiagnose.currentPage = 1
            gtDiagnose.createAndDisplayFrame()
        end,
    })

    local contentY = titleHeight + tabHeight + Helper.borderSize + 8

    -- ===== CONTENT TABLE =====
    local currentSection = sections[gtDiagnose.currentTab]
    if not currentSection then
        gtDiagnose.currentTab = 1
        currentSection = sections[1]
    end
    if not currentSection then return end

    local allRows   = currentSection.rows or {}
    local totalRows = #allRows
    local numCols   = currentSection.numCols or 3

    -- Pagination
    local pageInfo = GT_UI.paginate(totalRows, gtDiagnose.currentPage)
    gtDiagnose.currentPage = pageInfo.currentPage  -- clamp

    -- Large sections: smaller font, no wordwrap (prevents X4 min-height crash)
    local detailFontSize = GT_UI.DEFAULTS.fontSize * 0.9
    local useWordWrap    = true
    if pageInfo.isPaginated then
        detailFontSize = GT_UI.DEFAULTS.fontSize * 0.75
        useWordWrap    = false
    end

    -- Determine section name for layout selection
    local sectionName = currentSection.name or ""
    local isPairDetails    = (sectionName == "Pair Details")
    local isClearance      = (sectionName == "Clearance")
    local isSearchSummary  = (sectionName == "Search Summary")
    local isReservations   = (sectionName == "Reservations and Fleet")
    local isMinerScan      = (sectionName == "Miner Resource Scan")
    local isMultiCol       = (numCols >= 6) or isPairDetails or isClearance or isSearchSummary or isMinerScan

    if isMultiCol then
        -- ===== 6-COLUMN STRUCTURED LAYOUT =====
        -- Pair Details: Status | Ware | Buy From | Sell To | Profit/ROI | Reason
        -- Clearance:    Status | Ware | Station  | Price   | Revenue    | Reason
        local contentTable = GT_UI.createScrollTable(frame, 6, {
            tabOrder         = 2,
            x                = Helper.borderSize,
            y                = contentY,
            width            = width,
            maxVisibleHeight = gtDiagnose.frameHeight - contentY - Helper.borderSize - 10,
        })
        -- Column headers depend on section type
        if isSearchSummary then
            -- Search Summary: Status=6%, Check=25%, Sell=10%, Buy=10%, Total=10%, rest=flexible
            GT_UI.setColPercents(contentTable, { 6, 25, 10, 10, 10 })
            GT_UI.addHeaderRow(contentTable, {
                { text = "Status", halign = "center" },
                "Sector / Check",
                { text = "Sell", halign = "right" },
                { text = "Buy", halign = "right" },
                { text = "Total", halign = "right" },
                "",
            })
        elseif isReservations then
            -- Reservations: Status=7%, Entry=18%, Ship/Detail=30%, Ware=15%, Info=14%, Extra=flexible
            GT_UI.setColPercents(contentTable, { 7, 18, 30, 15, 14 })
            GT_UI.addHeaderRow(contentTable, {
                { text = "Status", halign = "center" },
                "Entry",
                "Ship / Detail",
                "Ware",
                "Info",
                "Extra",
            })
        elseif isPairDetails then
            -- Pair Details: Status=6%, Ware=10%, Route=28%, Profit=12%, Score/Sel=10%, Reason=flexible
            GT_UI.setColPercents(contentTable, { 6, 10, 28, 12, 10 })
            GT_UI.addHeaderRow(contentTable, {
                { text = "Status", halign = "center" },
                "Ware",
                "Route",
                { text = "Profit (incl. ROI)", halign = "right" },
                { text = "Score Â· Sel", halign = "right" },
                "Reason",
            })
        elseif isClearance then
            GT_UI.addHeaderRow(contentTable, {
                { text = "Status", halign = "center" },
                "Ware",
                "Station (Sector)",
                "Price/Demand",
                { text = "Revenue", halign = "right" },
                "Reason",
            })
        elseif isMinerScan then
            -- Miner Resource Scan (dedicated self-scan):
            -- Status=6%, Ware=20%, Best Yield=10%, Reachable=10%, Sectors=10%, Notes=flexible
            GT_UI.setColPercents(contentTable, { 6, 20, 10, 10, 10 })
            GT_UI.addHeaderRow(contentTable, {
                { text = "Status", halign = "center" },
                "Ware (* = active)",
                { text = "Best Yield", halign = "right" },
                { text = "Reachable", halign = "center" },
                { text = "Sectors", halign = "right" },
                "Notes",
            })
        else
            GT_UI.addHeaderRow(contentTable, {
                { text = "Status", halign = "center" },
                "Col 1", "Col 2", "Col 3", "Col 4", "Col 5",
            })
        end

        -- Pagination header
        GT_UI.addPaginationHeader(contentTable, pageInfo, 6)

        -- Data rows
        if totalRows == 0 then
            GT_UI.addEmptyRow(contentTable, "No data in this section.", 6)
        else
            for i = pageInfo.startIdx, pageInfo.endIdx do
                local row = allRows[i]
                if not row then break end

                local status    = row.status or "INFO"
                local check     = row.check or ""
                local detail    = row.detail or ""
                local col4      = row.col4 or ""
                local col5      = row.col5 or ""
                local col6      = row.col6 or ""

                local statusColor = GT_UI.getStatusColor(status)

                -- Separator rows (check starts with "---")
                local isSeparator = (string.sub(check, 1, 3) == "---")
                local rowBg = isSeparator and GT_UI.COLORS.headerBg or nil

                -- For 3-field rows within a 6-col section (e.g. summary rows),
                -- span the detail across remaining columns
                if not row.col4 then
                    GT_UI.addDataRow(contentTable, {
                        { text = status, halign = "center", fontsize = detailFontSize, color = statusColor },
                        { text = check, fontsize = detailFontSize },
                        { text = detail, fontsize = detailFontSize, colSpan = 4,
                          color = (status == "FAIL") and GT_UI.COLORS.textNegative or nil },
                    }, { bgColor = rowBg })
                else
                    -- Right-align numeric columns per section type
                    local detailAlign = "left"
                    local col4Align   = "left"
                    local col5Align   = "right"
                    if isSearchSummary then
                        detailAlign = "right"
                        col4Align   = "right"
                    elseif isPairDetails then
                        col4Align = "right"
                    elseif isMinerScan then
                        -- Miner Resource Scan: Best Yield right, Reachable centered, Sectors right
                        detailAlign = "right"
                        col4Align   = "center"
                        col5Align   = "right"
                    end

                    GT_UI.addDataRow(contentTable, {
                        { text = status, halign = "center", fontsize = detailFontSize, color = statusColor },
                        { text = check, fontsize = detailFontSize },
                        { text = detail, halign = detailAlign, fontsize = detailFontSize },
                        { text = col4, halign = col4Align, fontsize = detailFontSize },
                        { text = col5, halign = col5Align, fontsize = detailFontSize },
                        { text = col6, fontsize = detailFontSize,
                          color = (status == "FAIL") and GT_UI.COLORS.textNegative or nil },
                    }, { bgColor = rowBg })
                end
            end
        end

        -- Pagination nav (needs 3+ columns, we have 6)
        -- Put prev in col1, indicator in col3, next in col6 for spacing
        if pageInfo.isPaginated and pageInfo.totalPages > 1 then
            local navRow = contentTable:addRow(true, {
                fixed   = true,
                bgColor = GT_UI.COLORS.headerBg,
            })

            if pageInfo.currentPage > 1 then
                GT_UI.createButton(navRow[1], "<<", {
                    bgColor  = GT_UI.COLORS.tabInactiveBg,
                    fontSize = detailFontSize,
                    onClick  = function()
                        gtDiagnose.currentPage = gtDiagnose.currentPage - 1
                        gtDiagnose.createAndDisplayFrame()
                    end,
                })
            else
                navRow[1]:createText("", {})
            end

            navRow[2]:createText("", {})
            navRow[3]:createText(
                string.format("Page %d / %d", pageInfo.currentPage, pageInfo.totalPages),
                { halign = "center", fontsize = detailFontSize }
            )
            navRow[4]:createText(
                string.format("(%d rows total)", pageInfo.totalRows),
                { halign = "center", fontsize = detailFontSize }
            )
            navRow[5]:createText("", {})

            if pageInfo.currentPage < pageInfo.totalPages then
                GT_UI.createButton(navRow[6], ">>", {
                    bgColor  = GT_UI.COLORS.tabInactiveBg,
                    fontSize = detailFontSize,
                    onClick  = function()
                        gtDiagnose.currentPage = gtDiagnose.currentPage + 1
                        gtDiagnose.createAndDisplayFrame()
                    end,
                })
            else
                navRow[6]:createText("", {})
            end
        end

        gtDiagnose.addCopyReportRow(contentTable, 6)

        -- Footer
        GT_UI.addFooterRow(contentTable,
            string.format("Report at game time %.0fs  |  %d rows  |  %d sections total",
                gtDiagnose.timestamp or 0, totalRows, #sections),
            6)
    else
        -- ===== 3-COLUMN STANDARD LAYOUT =====
        local contentTable = GT_UI.createScrollTable(frame, 3, {
            tabOrder         = 2,
            x                = Helper.borderSize,
            y                = contentY,
            width            = width,
            maxVisibleHeight = gtDiagnose.frameHeight - contentY - Helper.borderSize - 10,
        })
        GT_UI.setColPercents(contentTable, { 22, 8 })  -- col 3 flexible

        -- Column headers
        GT_UI.addHeaderRow(contentTable, { "Check", "Status", "Detail" })

        -- Pagination header
        GT_UI.addPaginationHeader(contentTable, pageInfo, 3)

        -- Data rows (current page only)
        if totalRows == 0 then
            GT_UI.addEmptyRow(contentTable, "No data in this section.", 3)
        else
            for i = pageInfo.startIdx, pageInfo.endIdx do
                local row = allRows[i]
                if not row then break end

                local checkName = row.check or "?"
                local status    = row.status or "INFO"
                local detail    = row.detail or ""

                local statusColor = GT_UI.getStatusColor(status)

                -- Separator rows (check starts with "---")
                local isSeparator = (string.sub(checkName, 1, 3) == "---")
                local rowBg = isSeparator and GT_UI.COLORS.headerBg or nil

                GT_UI.addDataRow(contentTable, {
                    { text = checkName, fontsize = detailFontSize, wordwrap = false },
                    { text = status, halign = "center", fontsize = GT_UI.DEFAULTS.fontSize * 0.85, color = statusColor },
                    { text = detail, fontsize = detailFontSize, wordwrap = useWordWrap,
                      color = (status == "FAIL") and GT_UI.COLORS.textNegative or nil },
                }, { bgColor = rowBg })
            end
        end

        -- Pagination nav buttons
        GT_UI.addPaginationNav(contentTable, pageInfo, function(newPage)
            gtDiagnose.currentPage = newPage
            gtDiagnose.createAndDisplayFrame()
        end)

        gtDiagnose.addCopyReportRow(contentTable, 3)

        -- Footer
        GT_UI.addFooterRow(contentTable,
            string.format("Report at game time %.0fs  |  %d rows  |  %d sections total",
                gtDiagnose.timestamp or 0, totalRows, #sections),
            3)
    end
end

-- =============================================================================
-- MENU HOOKS
-- =============================================================================

local origCreateCtx = menu.createContextFrame
menu.createContextFrame = function(width, height, xoffset, yoffset, noborder, startanimation, ...)
    if menu.contextMenuMode == "gt_diagnose" then
        return menu.contextFrame
    end
    if origCreateCtx then
        return origCreateCtx(width, height, xoffset, yoffset, noborder, startanimation, ...)
    end
end

local origRefreshCtx = menu.refreshContextFrame
menu.refreshContextFrame = function(setrow, setcol, noborder, ...)
    if menu.contextMenuMode == "gt_diagnose" then
        if menu.contextFrame then
            menu.contextFrame:display()
        end
        return
    end
    if origRefreshCtx then
        origRefreshCtx(setrow, setcol, noborder, ...)
    end
end

-- =============================================================================
-- EVENT REGISTRATION
-- =============================================================================

RegisterEvent("gt.openDiagnoseReport", function(_, component)
    DebugError("[GT Diagnose] Lua: Event gt.openDiagnoseReport received")

    if component then
        local component64 = ConvertIDTo64Bit(component)
        DebugError(string.format("[GT Diagnose] Lua: Component converted: %s", tostring(component64)))
        if component64 and component64 ~= 0 then
            gtDiagnose.openReport(component64)
        end
    else
        DebugError("[GT Diagnose] Lua: No component - opening anyway")
        gtDiagnose.openReport(nil)
    end
end)

DebugError("[GT Diagnose] Diagnostic report display loaded (using GT_UI library)")
-- GalaxyTrader Context Menu Promote
-- Promotes clicked subordinate to fleet commander only (no pilot swap/crew transfer UI).

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    typedef struct {
        size_t queueidx;
        const char* state;
        const char* statename;
        const char* orderdef;
        size_t actualparams;
        bool enabled;
        bool isinfinite;
        bool issyncpointreached;
        bool istemporder;
    } Order;
    bool IsComponentClass(UniverseID componentid, const char* classname);
    bool IsOrderSelectableFor(const char* orderdefid, UniverseID controllableid);
    bool GetDefaultOrder(Order* result, UniverseID controllableid);
    const char* GetFleetName(UniverseID controllableid);
    float GetEntityCombinedSkill(UniverseID entityid, const char* roleid, const char* postid);
    uint32_t CreateOrder(UniverseID controllableid, const char* orderid, bool defaultorder);
    void EnableOrder(UniverseID controllableid, uint32_t idx);
    bool EnablePlannedDefaultOrder(UniverseID controllableid, bool checkonly);
    void ResetOrderLoop(UniverseID controllableid);
    bool AdjustOrder(UniverseID controllableid, uint32_t idx, uint32_t targetidx, bool begindragdrop, bool immediate, bool removecriticalorder);
    bool RemoveCommander2(UniverseID controllableid);
    void SetFleetName(UniverseID controllableid, const char* fleetname);
]]

local function asComponentId(entry)
    if not entry then
        return nil
    end
    if type(entry) == "table" and entry.component then
        return ConvertIDTo64Bit(entry.component)
    end
    return ConvertIDTo64Bit(entry)
end

local function normalizeAssignment(value)
    local s = value and tostring(value) or ""
    if s == "" or s == "null" then
        return "assist"
    end
    return s
end

local function normalizeGroup(value)
    local n = tonumber(value)
    if n == nil then
        return 0
    end
    return math.floor(n)
end

local function getDefaultOrderId(ship)
    if not ship or ship == 0 then
        return nil
    end
    local buf = ffi.new("Order")
    if C.GetDefaultOrder(buf, ship) and buf.orderdef then
        return ffi.string(buf.orderdef)
    end
    return nil
end

local pendingDefaultApplies = {}
local pendingOldCommanderReattach = {}
local pendingPromotedCommanderAttach = {}
local pendingPromotionReassign = {}
local orderAssignCommander -- forward declaration (used by deferred onUpdate path)
local collectFleetSubordinatesRecursive -- forward declaration (used by onUpdate queue finalization)

local function buildDefaultOrderSnapshotFromShip(sourceShip)
    local ship = asComponentId(sourceShip)
    if not ship or ship == 0 then
        return nil
    end
    local orderId = getDefaultOrderId(ship)
    if not orderId then
        return nil
    end

    local params = {}
    local srcParams = GetOrderParams(ship, "default") or {}
    if #srcParams == 0 then
        srcParams = GetOrderParams(ship, "planneddefault") or {}
    end
    for i, param in ipairs(srcParams) do
        if param and param.value ~= nil then
            params[#params + 1] = {
                idx = i,
                name = param.name,
                value = param.value,
            }
        end
    end

    return {
        sourceShip = ship,
        orderId = orderId,
        params = params,
    }
end

-- Reusable default-order capture utility:
-- walks commander chain and snapshots the first available default order with all params.
local function capturePromotionDefaultOrder(startCommander)
    local visited = {}
    local current = startCommander

    for _ = 1, 12 do
        if not current or current == 0 then
            break
        end
        local key = tostring(current)
        if visited[key] then
            break
        end
        visited[key] = true

        local snapshot = buildDefaultOrderSnapshotFromShip(current)
        if snapshot and snapshot.orderId then
            return snapshot
        end

        if not C.IsComponentClass(current, "controllable") then
            break
        end
        local parent = GetCommander(current)
        parent = parent and ConvertIDTo64Bit(parent) or nil
        if not parent or parent == 0 or parent == current then
            break
        end
        current = parent
    end

    return nil
end

local function getPilotLevel(ship)
    local pilot = GetComponentData(ship, "assignedpilot")
    if not pilot or pilot == 0 then
        return nil
    end
    local pilotId = asComponentId(pilot)
    if not pilotId or pilotId == 0 then
        return nil
    end
    local ok, combined = pcall(C.GetEntityCombinedSkill, pilotId, nil, "aipilot")
    if not ok then
        return nil
    end
    local lvl = math.floor((tonumber(combined) or 0) * 15 / 100)
    if lvl < 1 then lvl = 1 end
    if lvl > 15 then lvl = 15 end
    return lvl
end

local function shipClassLabel(ship)
    if not ship or ship == 0 then
        return "UNK"
    end
    if C.IsComponentClass(ship, "ship_xl") then return "XL" end
    if C.IsComponentClass(ship, "ship_l") then return "L" end
    if C.IsComponentClass(ship, "ship_m") then return "M" end
    if C.IsComponentClass(ship, "ship_s") then return "S" end
    if C.IsComponentClass(ship, "ship_xs") then return "XS" end
    return "UNK"
end

local function formatComponentRef(value)
    local cid = asComponentId(value)
    if cid and cid ~= 0 then
        local code = GetComponentData(cid, "idcode") or "NOID"
        return tostring(code) .. " (" .. tostring(cid) .. ")"
    end
    return tostring(value)
end

local function formatParamValue(value)
    local t = type(value)
    if t == "table" then
        if value.component then
            return formatComponentRef(value.component)
        end
        if value.id then
            return tostring(value.id)
        end
        return "<table>"
    end
    if t == "cdata" then
        return formatComponentRef(value)
    end
    return tostring(value)
end

local function captureFleetName(ship)
    local sid = asComponentId(ship)
    if not sid or sid == 0 then
        return nil
    end
    local ok, raw = pcall(C.GetFleetName, sid)
    if ok and raw then
        local s = ffi.string(raw)
        if s and s ~= "" then
            return s
        end
    end
    local fallback = GetComponentData(sid, "fleetname")
    if fallback and tostring(fallback) ~= "" then
        return tostring(fallback)
    end
    return nil
end

local function applyFleetName(ship, fleetName)
    local sid = asComponentId(ship)
    if not sid or sid == 0 or not fleetName or fleetName == "" then
        return false
    end
    local ok = pcall(C.SetFleetName, sid, fleetName)
    if ok then
        DebugError(string.format(
            "[GT Promote] Fleet name reapplied ship=%s fleet=%s",
            formatComponentRef(sid),
            tostring(fleetName)
        ))
        return true
    end
    DebugError(string.format(
        "[GT Promote] Fleet name reapply failed ship=%s fleet=%s",
        formatComponentRef(sid),
        tostring(fleetName)
    ))
    return false
end

local function logDefaultOrderSnapshotDetailed(tag, snapshot)
    if not snapshot then
        DebugError(string.format("[GT Promote] SNAPSHOT[%s] default-order snapshot: <nil>", tostring(tag)))
        return
    end
    DebugError(string.format(
        "[GT Promote] SNAPSHOT[%s] default-order source=%s order=%s params=%d",
        tostring(tag),
        formatComponentRef(snapshot.sourceShip),
        tostring(snapshot.orderId),
        #(snapshot.params or {})
    ))
    for _, entry in ipairs(snapshot.params or {}) do
        if entry then
            DebugError(string.format(
                "[GT Promote] SNAPSHOT[%s] default-order param idx=%s name=%s value=%s",
                tostring(tag),
                tostring(entry.idx),
                tostring(entry.name),
                formatParamValue(entry.value)
            ))
        end
    end
end

local function logFleetSnapshot(label, rootCommander)
    local root = asComponentId(rootCommander)
    if not root or root == 0 then
        DebugError(string.format("[GT Promote] SNAPSHOT[%s] root invalid: %s", tostring(label), tostring(rootCommander)))
        return
    end

    local visited = {}
    local queue = { root }
    local qhead = 1
    local count = 0
    DebugError(string.format("[GT Promote] SNAPSHOT[%s] begin root=%s", tostring(label), formatComponentRef(root)))

    while qhead <= #queue do
        local ship = asComponentId(queue[qhead])
        qhead = qhead + 1
        if ship and ship ~= 0 and not visited[tostring(ship)] then
            visited[tostring(ship)] = true
            count = count + 1

            local idcode, name, assignment, group, pilot = GetComponentData(ship, "idcode", "name", "assignment", "subordinategroup", "assignedpilot")
            local commander = GetCommander(ship)
            commander = commander and ConvertIDTo64Bit(commander) or nil
            local commanderCode = commander and GetComponentData(commander, "idcode") or "NONE"
            local orderId = getDefaultOrderId(ship) or "NONE"
            local subs = GetSubordinates(ship) or {}
            local level = getPilotLevel(ship)
            local pilotRef = pilot and asComponentId(pilot) or nil
            local pilotCode = pilotRef and GetComponentData(pilotRef, "idcode") or "NONE"

            DebugError(string.format(
                "[GT Promote] SNAPSHOT[%s] ship=%s (%s) class=%s commander=%s (%s) assignment=%s group=%s order=%s pilot=%s level=%s directSubs=%d",
                tostring(label),
                tostring(idcode or "NOID"),
                tostring(ship),
                tostring(shipClassLabel(ship)),
                tostring(commanderCode or "NONE"),
                tostring(commander or "NONE"),
                tostring(assignment or "nil"),
                tostring(group or "nil"),
                tostring(orderId),
                tostring(pilotCode),
                tostring(level or "nil"),
                #subs
            ))

            for _, sub in ipairs(subs) do
                local sid = asComponentId(sub)
                if sid and sid ~= 0 and not visited[tostring(sid)] then
                    queue[#queue + 1] = sid
                end
            end
        end
    end

    DebugError(string.format("[GT Promote] SNAPSHOT[%s] end ships=%d", tostring(label), count))
end

local function subordinateIdList(ship)
    local subs = GetSubordinates(ship) or {}
    local out = {}
    for _, sub in ipairs(subs) do
        local sid = asComponentId(sub)
        if sid and sid ~= 0 then
            local code = GetComponentData(sid, "idcode") or tostring(sid)
            out[#out + 1] = tostring(code)
        end
    end
    if #out == 0 then
        return "NONE"
    end
    return table.concat(out, ",")
end

local function isShipAssignedToCommander(ship, commander)
    local sid = asComponentId(ship)
    local cid = asComponentId(commander)
    if not sid or sid == 0 or not cid or cid == 0 then
        return false
    end
    local current = GetCommander(sid)
    current = current and ConvertIDTo64Bit(current) or nil
    return current == cid
end

local function enqueueOldCommanderReattach(oldCommander, newCommander, assignment, group, issuedShips)
    oldCommander = asComponentId(oldCommander)
    newCommander = asComponentId(newCommander)
    if not oldCommander or oldCommander == 0 or not newCommander or newCommander == 0 then
        return
    end
    pendingOldCommanderReattach[tostring(oldCommander)] = {
        oldCommander = oldCommander,
        newCommander = newCommander,
        assignment = normalizeAssignment(assignment),
        group = normalizeGroup(group),
        checks = 0,
        delayFrames = 2,
        maxChecks = 120, -- ~2 seconds at 60fps
        forceIssued = false,
        maxPostForceChecks = 20, -- short post-force settle window
        issuedShips = issuedShips or {},
    }
    DebugError(string.format(
        "[GT Promote] Deferred old commander attach queued old=%s new=%s assignment=%s group=%s",
        formatComponentRef(oldCommander),
        formatComponentRef(newCommander),
        tostring(normalizeAssignment(assignment)),
        tostring(normalizeGroup(group))
    ))
end

local function enqueuePromotedCommanderAttach(promotedCommander, parentCommander, assignment, group)
    promotedCommander = asComponentId(promotedCommander)
    parentCommander = asComponentId(parentCommander)
    if not promotedCommander or promotedCommander == 0 or not parentCommander or parentCommander == 0 then
        return
    end
    pendingPromotedCommanderAttach[tostring(promotedCommander)] = {
        ship = promotedCommander,
        parent = parentCommander,
        assignment = normalizeAssignment(assignment),
        group = normalizeGroup(group),
        checks = 0,
        delayFrames = 0,
        maxChecks = 80, -- ~1.3s at 60fps
        forceIssued = false,
    }
    DebugError(string.format(
        "[GT Promote] Deferred promoted commander attach queued ship=%s parent=%s assignment=%s group=%s",
        formatComponentRef(promotedCommander),
        formatComponentRef(parentCommander),
        tostring(normalizeAssignment(assignment)),
        tostring(normalizeGroup(group))
    ))
end

local function pilotMaxJumps(level)
    if not level then return 25 end
    if level <= 2 then return 1 end
    if level <= 5 then return 3 end
    if level <= 8 then return 5 end
    if level <= 11 then return 10 end
    if level <= 13 then return 15 end
    return 25
end

local function clampDistanceParamsByPilotCap(orderId, paramsByName, ship)
    if type(paramsByName) ~= "table" then
        return paramsByName
    end
    local level = getPilotLevel(ship)
    local cap = pilotMaxJumps(level)

    local function clamp(name, keepZero)
        if paramsByName[name] == nil then
            return
        end
        local n = tonumber(paramsByName[name])
        if n == nil then
            return
        end
        if keepZero and n == 0 then
            return
        end
        if n > cap then
            paramsByName[name] = cap
        end
    end

    if orderId == "GalaxyTraderMK3" then
        clamp("maxbuy", false)
        clamp("maxsell", false)
    elseif orderId == "GalaxyTraderMK1" then
        clamp("maxsell", false)
    elseif orderId == "GalaxyTraderMK2" then
        clamp("maxDistance", true)
    elseif orderId == "GalaxyMiner" then
        clamp("maxGatherDistance", true)
        clamp("maxSellDistance", true)
    end

    return paramsByName
end

local function applyCapturedDefaultOrder(toShip, snapshot, quiet)
    if not snapshot or not snapshot.orderId then
        if not quiet then
            DebugError(string.format("[GT Promote] Default order apply skipped: no snapshot for ship=%s", tostring(toShip)))
        end
        return false
    end
    if not C.IsOrderSelectableFor(snapshot.orderId, toShip) then
        if not quiet then
            DebugError(string.format("[GT Promote] Default order apply skipped: order not selectable order=%s ship=%s", tostring(snapshot.orderId), tostring(toShip)))
        end
        return false
    end

    -- Vanilla sequence for replacing default orders:
    -- reset loop/planned state first, then create new default order.
    pcall(C.ResetOrderLoop, toShip)

    local orderidx = 0
    local namedParams = {}
    for _, entry in ipairs(snapshot.params or {}) do
        if entry and entry.name and entry.value ~= nil then
            namedParams[entry.name] = entry.value
        end
    end
    namedParams = clampDistanceParamsByPilotCap(snapshot.orderId, namedParams, toShip)

    -- Use vanilla Lua CreateOrder wrapper first so required params are present at creation time.
    if type(CreateOrder) == "function" then
        local ok, created = pcall(CreateOrder, toShip, snapshot.orderId, namedParams, true, false, false)
        if ok and created then
            orderidx = created
        end
    end

    -- Fallback for environments where CreateOrder wrapper is unavailable.
    if not orderidx or orderidx <= 0 then
        orderidx = C.CreateOrder(toShip, snapshot.orderId, true)
    end
    if not orderidx or orderidx <= 0 then
        if not quiet then
            DebugError(string.format("[GT Promote] Default order apply failed: CreateOrder returned %s for order=%s ship=%s", tostring(orderidx), tostring(snapshot.orderId), tostring(toShip)))
        end
        return false
    end

    for _, entry in ipairs(snapshot.params or {}) do
        if entry and entry.idx and entry.value ~= nil then
            local v = entry.value
            if entry.name and namedParams[entry.name] ~= nil then
                v = namedParams[entry.name]
            end
            pcall(SetOrderParam, toShip, orderidx, entry.idx, nil, v)
        end
    end

    C.EnableOrder(toShip, orderidx)
    -- Match vanilla behavior: promote planned default to active default immediately.
    pcall(C.EnablePlannedDefaultOrder, toShip, false)
    DebugError(string.format("[GT Promote] Default order applied: order=%s ship=%s idx=%s params=%d source=%s", tostring(snapshot.orderId), tostring(toShip), tostring(orderidx), #(snapshot.params or {}), tostring(snapshot.sourceShip)))
    return true
end

local function enqueueDefaultOrderApply(ship, snapshot)
    if not ship or ship == 0 or not snapshot then
        return
    end
    pendingDefaultApplies[ship] = {
        ship = ship,
        snapshot = snapshot,
        delayFrames = 2,
    }
end

local function processPendingDefaultApplies()
    for key, entry in pairs(pendingDefaultApplies) do
        local ship = entry.ship
        local snapshot = entry.snapshot

        if (not ship) or ship == 0 or (not C.IsComponentClass(ship, "controllable")) then
            pendingDefaultApplies[key] = nil
        else
            if (entry.delayFrames or 0) > 0 then
                entry.delayFrames = entry.delayFrames - 1
            else
                local currentOrderId = getDefaultOrderId(ship)
                if (not currentOrderId) or (snapshot and snapshot.orderId and currentOrderId ~= snapshot.orderId) then
                    DebugError(string.format("[GT Promote] Pending default-apply trigger ship=%s currentOrder=%s", tostring(ship), tostring(currentOrderId)))
                    logFleetSnapshot("PENDING_APPLY_BEFORE", ship)
                    logDefaultOrderSnapshotDetailed("PENDING_APPLY", snapshot)
                    applyCapturedDefaultOrder(ship, snapshot, false)
                    logFleetSnapshot("PENDING_APPLY_AFTER", ship)
                end
                pendingDefaultApplies[key] = nil
            end
        end
    end
end

local function processPendingPromotionReassign()
    for key, job in pairs(pendingPromotionReassign) do
        local newCommander = job.newCommander
        local oldCommander = job.oldCommander
        if (not newCommander) or newCommander == 0 or (not C.IsComponentClass(newCommander, "controllable")) then
            pendingPromotionReassign[key] = nil
        else
            if (job.delayFrames or 0) > 0 then
                job.delayFrames = job.delayFrames - 1
            else
                local idx = job.index or 1
                local total = #(job.entries or {})
                if idx <= total then
                    local e = job.entries[idx]
                    local ship = e and e.ship or nil
                    if ship and ship ~= 0 and C.IsComponentClass(ship, "controllable") and ship ~= newCommander and ship ~= oldCommander then
                        local beforeCommander = GetCommander(ship)
                        beforeCommander = beforeCommander and ConvertIDTo64Bit(beforeCommander) or nil
                        DebugError(string.format(
                            "[GT Promote] Reassign step [%d/%d] ship=%s beforeCommander=%s targetCommander=%s assignment=%s group=%s",
                            idx,
                            total,
                            formatComponentRef(ship),
                            formatComponentRef(beforeCommander),
                            formatComponentRef(newCommander),
                            tostring(e.assignment),
                            tostring(e.group)
                        ))
                        if beforeCommander == newCommander then
                            DebugError(string.format(
                                "[GT Promote] Reassign skip ship=%s already assigned to target=%s",
                                formatComponentRef(ship),
                                formatComponentRef(newCommander)
                            ))
                        else
                            if orderAssignCommander(ship, newCommander, e.assignment, e.group, false) then
                                job.moved = (job.moved or 0) + 1
                                job.issuedShips = job.issuedShips or {}
                                job.issuedShips[tostring(ship)] = true
                            else
                                job.failed = (job.failed or 0) + 1
                                DebugError(string.format("[GT Promote] Reassign failed ship=%s target=%s", tostring(ship), tostring(newCommander)))
                            end
                        end
                    end
                    job.index = idx + 1
                    job.delayFrames = 2 -- tiny pacing delay to avoid order burst/race
                    pendingPromotionReassign[key] = job
                else
                    -- Subordinate reassignment queue finished: continue remaining promotion phases.
                    logFleetSnapshot("POST_SUBORDINATE_REASSIGN_QUEUE_OLD_TREE", oldCommander)
                    logFleetSnapshot("POST_SUBORDINATE_REASSIGN_QUEUE_NEW_TREE", newCommander)

                    enqueueOldCommanderReattach(oldCommander, newCommander, job.promotedAssign, job.promotedGroup, job.issuedShips)
                    logFleetSnapshot("POST_OLD_COMMANDER_REASSIGN_DEFERRED_NEW_TREE", newCommander)

                    applyCapturedDefaultOrder(newCommander, job.defaultOrderSnapshot)
                    enqueueDefaultOrderApply(newCommander, job.defaultOrderSnapshot)
                    applyFleetName(newCommander, job.originalFleetName)
                    logFleetSnapshot("POST_FINAL_DEFAULT_APPLY_NEW_TREE", newCommander)
                    local verifySubs = collectFleetSubordinatesRecursive(newCommander)
                    DebugError(string.format("[GT Promote] Post-promote verify commander=%s descendants=%d", tostring(newCommander), #verifySubs))
                    logFleetSnapshot("POST_VERIFY_NEW_TREE", newCommander)
                    local newName = GetComponentData(newCommander, "name") or "ship"
                    DebugError(string.format("[GT Promote] Promotion complete: %s is new commander (moved=%d, failed=%d)", tostring(newName), job.moved or 0, job.failed or 0))

                    pendingPromotionReassign[key] = nil
                end
            end
        end
    end
end

local function processPendingOldCommanderReattach()
    for key, entry in pairs(pendingOldCommanderReattach) do
        local oldCommander = entry.oldCommander
        local newCommander = entry.newCommander
        if (not oldCommander) or oldCommander == 0 or (not newCommander) or newCommander == 0
            or (not C.IsComponentClass(oldCommander, "controllable")) or (not C.IsComponentClass(newCommander, "controllable")) then
            pendingOldCommanderReattach[key] = nil
        else
            if (entry.delayFrames or 0) > 0 then
                entry.delayFrames = entry.delayFrames - 1
            else
                entry.checks = (entry.checks or 0) + 1
                local subs = GetSubordinates(oldCommander) or {}
                local subCount = #subs
                local shouldForce = entry.checks >= (entry.maxChecks or 120)
                local currentCommander = GetCommander(oldCommander)
                currentCommander = currentCommander and ConvertIDTo64Bit(currentCommander) or nil
                local oldAttached = (currentCommander == newCommander)
                if (entry.checks % 10) == 1 or subCount == 0 or shouldForce then
                    DebugError(string.format(
                        "[GT Promote] Deferred attach check old=%s subs=%d list=%s checks=%d/%d force=%s attached=%s",
                        formatComponentRef(oldCommander),
                        subCount,
                        subordinateIdList(oldCommander),
                        entry.checks,
                        entry.maxChecks or 120,
                        tostring(shouldForce),
                        tostring(oldAttached)
                    ))
                end

                if subCount == 0 and oldAttached then
                    DebugError(string.format(
                        "[GT Promote] Deferred attach converged old=%s new=%s",
                        formatComponentRef(oldCommander),
                        formatComponentRef(newCommander)
                    ))
                    pendingOldCommanderReattach[key] = nil
                elseif shouldForce then
                    if not entry.forceIssued then
                        logFleetSnapshot("DEFERRED_OLD_ATTACH_BEFORE_NEW_TREE", newCommander)
                        -- If subordinates are still stuck on old commander at force time, requeue them explicitly.
                        if subCount > 0 then
                            local subsNow = GetSubordinates(oldCommander) or {}
                            for _, sub in ipairs(subsNow) do
                                local sid = asComponentId(sub)
                                if sid and sid ~= 0 and sid ~= newCommander then
                                    local assignment, group = GetComponentData(sid, "assignment", "subordinategroup")
                                    local alreadyIssued = entry.issuedShips and entry.issuedShips[tostring(sid)] or false
                                    if alreadyIssued then
                                        DebugError(string.format(
                                            "[GT Promote] Deferred stuck-subordinate requeue skip ship=%s already had AssignCommander in this promote cycle",
                                            formatComponentRef(sid)
                                        ))
                                    elseif isShipAssignedToCommander(sid, newCommander) then
                                        DebugError(string.format(
                                            "[GT Promote] Deferred stuck-subordinate requeue skip ship=%s already assigned to new=%s",
                                            formatComponentRef(sid),
                                            formatComponentRef(newCommander)
                                        ))
                                    else
                                        local okSub = orderAssignCommander(sid, newCommander, normalizeAssignment(assignment), normalizeGroup(group), true)
                                        if okSub then
                                            entry.issuedShips = entry.issuedShips or {}
                                            entry.issuedShips[tostring(sid)] = true
                                        end
                                        DebugError(string.format(
                                            "[GT Promote] Deferred stuck-subordinate requeue ship=%s old=%s new=%s ok=%s assignment=%s group=%s cancelOrders=true",
                                            formatComponentRef(sid),
                                            formatComponentRef(oldCommander),
                                            formatComponentRef(newCommander),
                                            tostring(okSub),
                                            tostring(assignment),
                                            tostring(group)
                                        ))
                                    end
                                end
                            end
                        end
                        local ok = orderAssignCommander(oldCommander, newCommander, entry.assignment, entry.group, true)
                        DebugError(string.format(
                            "[GT Promote] Deferred old commander attach result old=%s new=%s ok=%s cancelOrders=true",
                            formatComponentRef(oldCommander),
                            formatComponentRef(newCommander),
                            tostring(ok)
                        ))
                        -- Give orders a short settle window before final verdict.
                        entry.forceIssued = true
                        entry.checks = 0
                        entry.delayFrames = 8
                        entry.maxChecks = entry.maxPostForceChecks or 20
                        pendingOldCommanderReattach[key] = entry
                    else
                        local postSubs = GetSubordinates(oldCommander) or {}
                        local postCount = #postSubs
                        local postCommander = GetCommander(oldCommander)
                        postCommander = postCommander and ConvertIDTo64Bit(postCommander) or nil
                        local postAttached = (postCommander == newCommander)
                        DebugError(string.format(
                            "[GT Promote] Deferred attach final status old=%s new=%s attached=%s remainingSubs=%d list=%s",
                            formatComponentRef(oldCommander),
                            formatComponentRef(newCommander),
                            tostring(postAttached),
                            postCount,
                            subordinateIdList(oldCommander)
                        ))
                        logFleetSnapshot("DEFERRED_OLD_ATTACH_AFTER_NEW_TREE", newCommander)
                        pendingOldCommanderReattach[key] = nil
                    end
                else
                    pendingOldCommanderReattach[key] = entry
                end
            end
        end
    end
end

local function processPendingPromotedCommanderAttach()
    for key, entry in pairs(pendingPromotedCommanderAttach) do
        local ship = entry.ship
        local parent = entry.parent
        if (not ship) or ship == 0 or (not parent) or parent == 0
            or (not C.IsComponentClass(ship, "controllable")) then
            pendingPromotedCommanderAttach[key] = nil
        else
            if isShipAssignedToCommander(ship, parent) then
                DebugError(string.format(
                    "[GT Promote] Deferred promoted commander attach converged ship=%s parent=%s",
                    formatComponentRef(ship),
                    formatComponentRef(parent)
                ))
                pendingPromotedCommanderAttach[key] = nil
            elseif (entry.delayFrames or 0) > 0 then
                entry.delayFrames = entry.delayFrames - 1
            else
                entry.checks = (entry.checks or 0) + 1
                local shouldForce = entry.checks >= (entry.maxChecks or 80)
                local cancelOrders = shouldForce and (not entry.forceIssued) or false
                local ok = orderAssignCommander(ship, parent, entry.assignment, entry.group, cancelOrders)
                DebugError(string.format(
                    "[GT Promote] Deferred promoted commander attach attempt ship=%s parent=%s ok=%s check=%d/%d force=%s cancelOrders=%s",
                    formatComponentRef(ship),
                    formatComponentRef(parent),
                    tostring(ok),
                    entry.checks,
                    entry.maxChecks or 80,
                    tostring(shouldForce),
                    tostring(cancelOrders)
                ))

                if shouldForce then
                    if entry.forceIssued then
                        pendingPromotedCommanderAttach[key] = nil
                    else
                        entry.forceIssued = true
                        entry.checks = 0
                        entry.delayFrames = 10
                        entry.maxChecks = 20
                        pendingPromotedCommanderAttach[key] = entry
                    end
                else
                    entry.delayFrames = 4
                    pendingPromotedCommanderAttach[key] = entry
                end
            end
        end
    end
end

collectFleetSubordinatesRecursive = function(rootCommander)
    local result = {}
    local visited = {}
    local queue = { rootCommander }
    local qhead = 1

    while qhead <= #queue do
        local current = queue[qhead]
        qhead = qhead + 1
        local cid = asComponentId(current)
        if cid and cid ~= 0 and not visited[tostring(cid)] then
            visited[tostring(cid)] = true
            local subs = GetSubordinates(cid) or {}
            for _, sub in ipairs(subs) do
                local sid = asComponentId(sub)
                if sid and sid ~= 0 and not visited[tostring(sid)] then
                    result[#result + 1] = sid
                    queue[#queue + 1] = sid
                end
            end
        end
    end
    DebugError(string.format("[GT Promote] Recursive collection root=%s count=%d", tostring(rootCommander), #result))
    for _, sid in ipairs(result) do
        local cmd = GetCommander(sid)
        cmd = cmd and ConvertIDTo64Bit(cmd) or nil
        DebugError(string.format("[GT Promote]  - candidate ship=%s currentCommander=%s", tostring(sid), tostring(cmd)))
    end
    return result
end

orderAssignCommander = function(ship, newCommander, assignment, group, cancelOrders)
    if not ship or ship == 0 or not newCommander or newCommander == 0 then
        DebugError(string.format("[GT Promote] AssignCommander skipped invalid args ship=%s newCommander=%s", tostring(ship), tostring(newCommander)))
        return false
    end
    if (not C.IsOrderSelectableFor("AssignCommander", ship)) or (not GetComponentData(ship, "assignedpilot")) then
        DebugError(string.format("[GT Promote] AssignCommander not selectable/no pilot ship=%s selectable=%s hasPilot=%s", tostring(ship), tostring(C.IsOrderSelectableFor("AssignCommander", ship)), tostring(GetComponentData(ship, "assignedpilot") ~= nil)))
        return false
    end

    local orderidx = C.CreateOrder(ship, "AssignCommander", false)
    if orderidx <= 0 then
        DebugError(string.format("[GT Promote] AssignCommander create failed ship=%s target=%s", tostring(ship), tostring(newCommander)))
        return false
    end

    local safeAssignment = normalizeAssignment(assignment)
    local safeGroup = normalizeGroup(group)
    local beforeCommander = GetCommander(ship)
    beforeCommander = beforeCommander and ConvertIDTo64Bit(beforeCommander) or nil

    SetOrderParam(ship, orderidx, 1, nil, ConvertStringToLuaID(tostring(newCommander))) -- commander
    SetOrderParam(ship, orderidx, 2, nil, safeAssignment) -- assignment
    SetOrderParam(ship, orderidx, 3, nil, safeGroup) -- subordinate group
    SetOrderParam(ship, orderidx, 4, nil, true) -- setgroupassignment
    if cancelOrders == nil then
        cancelOrders = false
    end
    SetOrderParam(ship, orderidx, 5, nil, cancelOrders) -- cancelorders
    SetOrderParam(ship, orderidx, 6, nil, true) -- response
    SetOrderParam(ship, orderidx, 8, nil, true) -- informfleetmanager

    C.EnableOrder(ship, orderidx)
    if orderidx ~= 1 then
        -- Try to promote assignment ahead of blocking critical queue entries first,
        -- while keeping cancelorders behavior independent.
        local targetIdx = 1
        if not C.AdjustOrder(ship, orderidx, targetIdx, true, true, true) then
            targetIdx = 2
        end
        C.AdjustOrder(ship, orderidx, targetIdx, true, true, false)
    end
    DebugError(string.format("[GT Promote] AssignCommander immediate ship=%s before=%s target=%s assignment=%s group=%s idx=%s cancelOrders=%s", tostring(ship), tostring(beforeCommander), tostring(newCommander), tostring(safeAssignment), tostring(safeGroup), tostring(orderidx), tostring(cancelOrders)))
    return true
end

local function promoteSubordinateToCommander(subordinateComponent)
    if not subordinateComponent or subordinateComponent == 0 then
        DebugError("[GT Promote] Invalid subordinate component")
        return
    end

    local newCommander = asComponentId(subordinateComponent)
    if not newCommander or newCommander == 0 then
        DebugError("[GT Promote] Failed to convert subordinate component")
        return
    end

    local oldCommander = nil
    if C.IsComponentClass(newCommander, "controllable") then
        oldCommander = GetCommander(newCommander)
        oldCommander = oldCommander and ConvertIDTo64Bit(oldCommander) or nil
    end
    if not oldCommander or oldCommander == 0 then
        DebugError("[GT Promote] Clicked ship is not a subordinate (no commander)")
        return
    end
    DebugError(string.format("[GT Promote] Start promote new=%s old=%s", tostring(newCommander), tostring(oldCommander)))
    logFleetSnapshot("PRE_OLD_COMMANDER_TREE", oldCommander)
    logFleetSnapshot("PRE_PROMOTED_SHIP_TREE", newCommander)

    -- Capture old commander's parent attachment (e.g. station trader) so new commander can inherit it.
    local oldCommanderParent = GetCommander(oldCommander)
    oldCommanderParent = oldCommanderParent and ConvertIDTo64Bit(oldCommanderParent) or nil
    local oldCommanderAssign, oldCommanderGroup = GetComponentData(oldCommander, "assignment", "subordinategroup")
    oldCommanderAssign = normalizeAssignment(oldCommanderAssign)
    oldCommanderGroup = normalizeGroup(oldCommanderGroup)

    -- Capture promoted ship's own subordinate role before detach (typically assist/group).
    local promotedAssign, promotedGroup = GetComponentData(newCommander, "assignment", "subordinategroup")
    promotedAssign = normalizeAssignment(promotedAssign)
    promotedGroup = normalizeGroup(promotedGroup)

    -- Get full subordinate tree so promotion can flatten hierarchy.
    -- Desired result after promotion:
    --   newCommander
    --    > oldCommander
    --    > all former subordinate ships (directly)
    local fleetShips = collectFleetSubordinatesRecursive(oldCommander)
    local moved = 0
    local failed = 0
    local originalFleetName = captureFleetName(oldCommander)
    local defaultOrderSnapshot = capturePromotionDefaultOrder(oldCommander)
    if defaultOrderSnapshot then
        DebugError(string.format("[GT Promote] Snapshot captured: source=%s order=%s params=%d", tostring(defaultOrderSnapshot.sourceShip), tostring(defaultOrderSnapshot.orderId), #(defaultOrderSnapshot.params or {})))
        logDefaultOrderSnapshotDetailed("CAPTURED", defaultOrderSnapshot)
    else
        DebugError(string.format("[GT Promote] Snapshot missing: no default order found in commander chain starting at %s", tostring(oldCommander)))
    end

    -- 1) Make clicked ship commander first.
    C.RemoveCommander2(newCommander)
    DebugError(string.format("[GT Promote] Detached promoted ship=%s from commander=%s", tostring(newCommander), tostring(oldCommander)))
    logFleetSnapshot("POST_DETACH_OLD_COMMANDER_TREE", oldCommander)
    logFleetSnapshot("POST_DETACH_NEW_COMMANDER_TREE", newCommander)

    -- Prime promoted commander with captured commander default order as early as possible.
    applyCapturedDefaultOrder(newCommander, defaultOrderSnapshot)
    applyFleetName(newCommander, originalFleetName)

    -- If old commander was attached to a parent (e.g. station), attach promoted commander immediately.
    -- This avoids a detached-fleet window where promoted fleets temporarily lose station attachment.
    if oldCommanderParent and oldCommanderParent ~= 0 and oldCommanderParent ~= newCommander then
        local attached = orderAssignCommander(newCommander, oldCommanderParent, oldCommanderAssign, oldCommanderGroup, false)
        DebugError(string.format(
            "[GT Promote] Promoted commander parent attach ship=%s parent=%s assignment=%s group=%s ok=%s cancelOrders=false",
            formatComponentRef(newCommander),
            formatComponentRef(oldCommanderParent),
            tostring(oldCommanderAssign),
            tostring(oldCommanderGroup),
            tostring(attached)
        ))
        if not attached then
            enqueuePromotedCommanderAttach(newCommander, oldCommanderParent, oldCommanderAssign, oldCommanderGroup)
        end
    end
    logFleetSnapshot("POST_INITIAL_DEFAULT_APPLY_NEW_COMMANDER_TREE", newCommander)

    -- 2) Reassign all former subordinate ships directly under new commander (flatten tree),
    --    paced one-by-one in onUpdate to avoid burst race conditions.
    local entries = {}
    for _, shipEntry in ipairs(fleetShips) do
        local ship = asComponentId(shipEntry)
        if ship and ship ~= 0 and ship ~= newCommander and ship ~= oldCommander and C.IsComponentClass(ship, "controllable") then
            local assignment, group = GetComponentData(ship, "assignment", "subordinategroup")
            entries[#entries + 1] = {
                ship = ship,
                assignment = normalizeAssignment(assignment),
                group = normalizeGroup(group),
            }
        end
    end

    pendingPromotionReassign[tostring(newCommander)] = {
        newCommander = newCommander,
        oldCommander = oldCommander,
        entries = entries,
        index = 1,
        moved = moved,
        failed = failed,
        delayFrames = 0,
        promotedAssign = promotedAssign,
        promotedGroup = promotedGroup,
        defaultOrderSnapshot = defaultOrderSnapshot,
        issuedShips = {},
        originalFleetName = originalFleetName,
    }
    DebugError(string.format(
        "[GT Promote] Sequential subordinate reassignment queued commander=%s old=%s ships=%d paceFrames=%d",
        formatComponentRef(newCommander),
        formatComponentRef(oldCommander),
        #entries,
        2
    ))
end

RegisterEvent("gt.openPromoteContext", function(_, subordinateComponent)
    promoteSubordinateToCommander(subordinateComponent)
end)

function onUpdate()
    processPendingPromotionReassign()
    processPendingDefaultApplies()
    processPendingPromotedCommanderAttach()
    processPendingOldCommanderReattach()
end
SetScript("onUpdate", onUpdate)

DebugError("[GT Promote] Commander-only promote integration loaded")
-- GalaxyTrader Context Menu - Pilot Redistribution
-- Redistributes pilots by level rank to ship class rank:
-- - sort pilots by level descending, ships by class descending
-- - assign highest level to largest ship, next to next largest, etc.
-- - only cross-class swaps (no S<->S, M<->M, L<->L, XL<->XL)
-- - never allow penalty outcomes (< 0 modifier)
-- - Fleet commander: only receives a same-class subordinate pilot when that pilot is on a higher
--   penalty tier than the commander (see skillTier / performanceModifier bands in gt_ship_management)

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    typedef uint64_t NPCSeed;
    typedef struct {
        size_t queueidx;
        const char* state;
        const char* statename;
        const char* orderdef;
        size_t actualparams;
        bool enabled;
        bool isinfinite;
        bool issyncpointreached;
        bool istemporder;
    } Order;
    typedef struct {
        const char* reason;
        NPCSeed person;
        NPCSeed partnerperson;
    } UICrewExchangeResult;
    bool IsComponentClass(UniverseID componentid, const char* classname);
    bool IsOrderSelectableFor(const char* orderdefid, UniverseID controllableid);
    UniverseID GetContextByClass(UniverseID componentid, const char* classname, bool includeself);
    float GetDistanceBetween(UniverseID component1id, UniverseID component2id);
    uint32_t CreateOrder(UniverseID controllableid, const char* orderid, bool defaultorder);
    void EnableOrder(UniverseID controllableid, uint32_t idx);
    UniverseID ConvertStringTo64Bit(const char* idcode);
    uint32_t GetNumAllFactionShips(const char* factionid);
    uint32_t GetAllFactionShips(UniverseID* result, uint32_t resultlen, const char* factionid);
    uint32_t GetNumOrders(UniverseID controllableid);
    uint32_t GetOrders(Order* result, uint32_t resultlen, UniverseID controllableid);
    bool GetDefaultOrder(Order* result, UniverseID controllableid);
    float GetEntityCombinedSkill(UniverseID entityid, const char* roleid, const char* postid);
    UICrewExchangeResult PerformCrewExchange2(UniverseID controllableid, UniverseID partnercontrollableid, NPCSeed* npcs, uint32_t numnpcs, NPCSeed* partnernpcs, uint32_t numpartnernpcs, NPCSeed captainfromcontainer, NPCSeed captainfrompartner, bool exchangecaptains, bool checkonly);
]]

local GT_ORDER_IDS = {
    GalaxyTraderMK1 = true,
    GalaxyTraderMK2 = true,
    GalaxyTraderMK3 = true,
    GalaxyTraderMK4Supply = true,
    GalaxyMiner = true,
}

local function debugLog(msg)
    DebugError("[GT Redistribute] " .. tostring(msg))
end

local function notify(msg)
    debugLog(msg)
end

local menu = Helper.getMenu("MapMenu")
local pendingRedistributeCommander = nil
local pilotDataRefreshRequestedAt = 0
local PILOT_DATA_REFRESH_TIMEOUT = 5.0
local pendingSwapShipsByPair = {}
local completedSwapByPair = {}
local pendingDockAssignmentsByPair = {}
local pendingReleaseRetries = {}
local pendingPostSwapRefreshRetries = {}
local pilotIndexCacheByShipId = nil

local function invalidatePilotIndexCache()
    pilotIndexCacheByShipId = nil
end

local function isShipInPendingRedistribution(ship, idcode)
    local shipKey = tostring(ship or "")
    local codeKey = tostring(idcode or "")
    for _, item in pairs(pendingDockAssignmentsByPair) do
        if item then
            if codeKey ~= "" and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
                return true
            end
            if shipKey ~= "" and (tostring(item.leftShip or "") == shipKey or tostring(item.rightShip or "") == shipKey) then
                return true
            end
        end
    end
    for key, _ in pairs(pendingSwapShipsByPair) do
        local a, b = string.match(tostring(key), "^([^|]+)|([^|]+)$")
        if codeKey ~= "" and ((a and a == codeKey) or (b and b == codeKey)) then
            return true
        end
    end
    for _, item in ipairs(pendingReleaseRetries) do
        if item and codeKey ~= "" and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
            return true
        end
    end
    for _, item in ipairs(pendingPostSwapRefreshRetries) do
        if item and codeKey ~= "" and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
            return true
        end
    end
    return false
end

local function clearPendingRedistributionForShip(idcode)
    if not idcode or idcode == "" then
        return
    end
    local codeKey = tostring(idcode)
    for key, item in pairs(pendingDockAssignmentsByPair) do
        if item and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
            pendingDockAssignmentsByPair[key] = nil
        end
    end
    -- Clear remembered swap pairs as well to avoid stale growth if an exchange is cancelled early.
    -- Swap execution now receives authoritative ship objects from MD, so we do not depend on this cache.
    for key, pair in pairs(pendingSwapShipsByPair) do
        if pair and (tostring(pair.left or "") == codeKey or tostring(pair.right or "") == codeKey) then
            pendingSwapShipsByPair[key] = nil
        end
    end
    for key, item in pairs(completedSwapByPair) do
        if item and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
            completedSwapByPair[key] = nil
        end
    end
    for i = #pendingReleaseRetries, 1, -1 do
        local item = pendingReleaseRetries[i]
        if item and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
            table.remove(pendingReleaseRetries, i)
        end
    end
    for i = #pendingPostSwapRefreshRetries, 1, -1 do
        local item = pendingPostSwapRefreshRetries[i]
        if item and (tostring(item.left or "") == codeKey or tostring(item.right or "") == codeKey) then
            table.remove(pendingPostSwapRefreshRetries, i)
        end
    end
end

local function sendDockingLogbookMessage(leftShip, rightShip, station)
    if type(AddUITriggeredEvent) ~= "function" then
        debugLog("Logbook emit skipped: AddUITriggeredEvent unavailable")
        return
    end
    local leftName = GetComponentData(leftShip, "name") or "Unknown Ship"
    local rightName = GetComponentData(rightShip, "name") or "Unknown Ship"
    local leftCode = GetComponentData(leftShip, "idcode") or "UNK"
    local rightCode = GetComponentData(rightShip, "idcode") or "UNK"
    local stationName = GetComponentData(station, "name") or "Unknown Station"
    local stationCode = GetComponentData(station, "idcode") or "UNK"

    local title = ReadText(77000, 3120)
    local template = ReadText(77000, 3121) or ""
    local values = {
        tostring(leftName), tostring(leftCode),
        tostring(rightName), tostring(rightCode),
        tostring(stationName), tostring(stationCode),
    }
    local message = tostring(template):gsub("%%(%d+)", function(idx)
        local n = tonumber(idx)
        if n and values[n] ~= nil then
            return values[n]
        end
        return "%" .. tostring(idx)
    end)

    AddUITriggeredEvent("GT_Redistribute", "Logbook", {
        title = title,
        message = message,
    })
    debugLog("Logbook emit queued for " .. tostring(leftCode) .. " <-> " .. tostring(rightCode) .. " at " .. tostring(stationCode))
end

local function publishPilotExchangeRenameState(leftCode, rightCode, active)
    if type(AddUITriggeredEvent) ~= "function" then
        return
    end
    AddUITriggeredEvent("GT_Redistribute", "PilotExchangeState", {
        left = tostring(leftCode or ""),
        right = tostring(rightCode or ""),
        active = active == true,
    })
end

local function publishPilotExchangeRelease(leftCode, rightCode, leftShip, rightShip)
    if type(AddUITriggeredEvent) ~= "function" then
        return
    end
    AddUITriggeredEvent("GT_Redistribute", "ReleaseDockHold", {
        left = tostring(leftCode or ""),
        right = tostring(rightCode or ""),
    })
end

local function publishPostSwapNameRefresh(leftCode, rightCode, leftShip, rightShip)
    if type(AddUITriggeredEvent) ~= "function" then
        return
    end
    AddUITriggeredEvent("GT_Redistribute", "PostSwapNameRefresh", {
        left = tostring(leftCode or ""),
        right = tostring(rightCode or ""),
    })
    debugLog("PostSwapNameRefresh emitted left=" .. tostring(leftCode or "")
        .. " right=" .. tostring(rightCode or "")
        .. " leftShip=" .. tostring(leftShip or 0)
        .. " rightShip=" .. tostring(rightShip or 0))
    if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData and type(Mods.GalaxyTrader.PilotData.requestRefresh) == "function" then
        invalidatePilotIndexCache()
        Mods.GalaxyTrader.PilotData.requestRefresh()
        debugLog("PostSwapNameRefresh requested GT pilot data refresh left=" .. tostring(leftCode or "")
            .. " right=" .. tostring(rightCode or ""))
    else
        debugLog("PostSwapNameRefresh could not request GT pilot data refresh")
    end
end

local function schedulePilotExchangeReleaseRetry(leftCode, rightCode, leftShip, rightShip)
    if not leftCode or not rightCode then
        return
    end
    table.insert(pendingReleaseRetries, {
        left = tostring(leftCode),
        right = tostring(rightCode),
        leftShip = leftShip or 0,
        rightShip = rightShip or 0,
        dueAt = getElapsedTime() + 2.0,
        attemptsLeft = 5,
    })
end

local function schedulePostSwapNameRefreshRetry(leftCode, rightCode, leftShip, rightShip)
    if not leftCode or not rightCode then
        return
    end
    table.insert(pendingPostSwapRefreshRetries, {
        left = tostring(leftCode),
        right = tostring(rightCode),
        leftShip = leftShip or 0,
        rightShip = rightShip or 0,
        dueAt = getElapsedTime() + 1.0,
        attemptsLeft = 4,
    })
end

local function isGTOrder(orderId)
    return orderId and GT_ORDER_IDS[orderId] == true
end

local function asComponentId(entry)
    if not entry then
        return nil
    end
    if type(entry) == "table" and entry.component then
        return asComponentId(entry.component)
    end
    if type(entry) == "cdata" then
        local luaId = ConvertStringToLuaID(tostring(entry))
        if luaId then
            return ConvertIDTo64Bit(luaId)
        end
        return nil
    end
    return ConvertIDTo64Bit(entry)
end

local function asLuaComponent(entry)
    if not entry then
        return nil
    end
    if type(entry) == "table" and entry.component then
        return asLuaComponent(entry.component)
    end
    if type(entry) == "cdata" then
        return ConvertStringToLuaID(tostring(entry))
    end
    return entry
end

local function getDefaultOrderId(ship)
    local shipId = asComponentId(ship)
    if not shipId or shipId == 0 then
        return nil
    end
    local buf = ffi.new("Order")
    if C.GetDefaultOrder(buf, shipId) and buf.orderdef then
        return ffi.string(buf.orderdef)
    end
    return nil
end

local function getOrderParamsSafe(shipId, orderIdx)
    if type(GetOrderParams) ~= "function" then
        return nil
    end
    local params = GetOrderParams(shipId, orderIdx)
    if params ~= nil then
        return params
    end
    local asLua = ConvertStringToLuaID(tostring(shipId))
    if asLua then
        return GetOrderParams(asLua, orderIdx)
    end
    return nil
end

local function getCallerOrderIdFromParams(params)
    if type(params) ~= "table" then
        return nil
    end
    local caller = params.callerid
    if type(caller) == "string" then
        return caller
    end
    if type(caller) == "table" then
        if type(caller.id) == "string" then
            return caller.id
        end
        if type(caller.orderid) == "string" then
            return caller.orderid
        end
    end
    return nil
end

local function shipHasActiveOrQueuedPilotExchangeOrder(ship)
    local shipId = asComponentId(ship)
    if not shipId or shipId == 0 then
        return false
    end

    local numOrders = tonumber(C.GetNumOrders(shipId) or 0) or 0
    if numOrders <= 0 then
        return false
    end

    local orders = ffi.new("Order[?]", numOrders)
    local count = tonumber(C.GetOrders(orders, numOrders, shipId) or 0) or 0
    if count <= 0 then
        return false
    end

    for i = 0, count - 1 do
        local orderdef = orders[i].orderdef and ffi.string(orders[i].orderdef) or ""
        if orderdef == "DockAndPilotExchange" then
            return true
        end
        if orderdef == "DockAndWait" then
            local orderIdx = tonumber(orders[i].queueidx) or (i + 1)
            local params = getOrderParamsSafe(shipId, orderIdx)
            local callerId = getCallerOrderIdFromParams(params)
            if callerId == "DockAndPilotExchange" then
                return true
            end
        end
    end

    return false
end

local function getCommanderId(ship)
    local shipId = asComponentId(ship)
    if not shipId or shipId == 0 then
        return nil
    end
    local cmd = GetCommander(shipId)
    local cmdId = asComponentId(cmd)
    if cmdId and cmdId ~= 0 then
        return cmdId
    end
    return nil
end

local function pairKey(leftCode, rightCode)
    local a = tostring(leftCode or "")
    local b = tostring(rightCode or "")
    if a < b then
        return a .. "|" .. b
    end
    return b .. "|" .. a
end

local function rememberSwapPair(leftCode, rightCode, leftShip, rightShip)
    if not leftCode or not rightCode or not leftShip or not rightShip then
        return
    end
    pendingSwapShipsByPair[pairKey(leftCode, rightCode)] = {
        left = leftShip,
        right = rightShip,
    }
end

local function popRememberedSwapPair(leftCode, rightCode)
    local key = pairKey(leftCode, rightCode)
    local pair = pendingSwapShipsByPair[key]
    pendingSwapShipsByPair[key] = nil
    return pair
end

local function resolveShipFromIdCode(idcode)
    if not idcode or idcode == "" then
        return nil
    end
    local code = tostring(idcode)
    -- Fast path for numeric/serialized values.
    local shipId = C.ConvertStringTo64Bit(code)
    if shipId and shipId ~= 0 then
        local resolvedCode = GetComponentData(shipId, "idcode")
        if resolvedCode and tostring(resolvedCode) == code then
            return shipId
        end
    end

    -- Authoritative idcode resolution for player ships across save/load:
    -- enumerate player-owned ships and match by idcode exactly.
    local numShips = C.GetNumAllFactionShips("player")
    if numShips and numShips > 0 then
        local shipIds = ffi.new("UniverseID[?]", numShips)
        local count = C.GetAllFactionShips(shipIds, numShips, "player")
        for i = 0, count - 1 do
            local candidate = shipIds[i]
            if candidate and candidate ~= 0 then
                local candidateCode = GetComponentData(candidate, "idcode")
                if candidateCode and tostring(candidateCode) == code then
                    return candidate
                end
            end
        end
    end
    return nil
end

local function classRank(ship)
    if C.IsComponentClass(ship, "ship_xl") then return 4, "XL" end
    if C.IsComponentClass(ship, "ship_l") then return 3, "L" end
    if C.IsComponentClass(ship, "ship_m") then return 2, "M" end
    if C.IsComponentClass(ship, "ship_s") then return 1, "S" end
    return 0, "UNK"
end

local function getGTPilotBridge()
    if not Mods or not Mods.GalaxyTrader or not Mods.GalaxyTrader.PilotData then
        return nil
    end
    local bridge = Mods.GalaxyTrader.PilotData
    if type(bridge.getPilots) ~= "function" then
        return nil
    end
    return bridge
end

local function getGTPilotIndexByShipId()
    if pilotIndexCacheByShipId then
        return pilotIndexCacheByShipId
    end
    local bridge = getGTPilotBridge()
    if not bridge then
        return nil
    end
    local pilots = bridge.getPilots() or {}
    local index = {}
    for _, p in ipairs(pilots) do
        if p and p.shipId and p.shipId ~= "" then
            index[tostring(p.shipId)] = p
        end
    end
    pilotIndexCacheByShipId = index
    return pilotIndexCacheByShipId
end

local function getGTPilotDataByShip(ship, pilotIndex)
    local shipIdCode = GetComponentData(ship, "idcode")
    if not shipIdCode or shipIdCode == "" then
        return nil
    end
    local index = pilotIndex or getGTPilotIndexByShipId()
    return index and index[tostring(shipIdCode)] or nil
end

local function getGTLevelByShip(ship, pilotIndex)
    local pilotData = getGTPilotDataByShip(ship, pilotIndex)
    if pilotData and pilotData.level ~= nil then
        local lvl = tonumber(pilotData.level)
        if lvl then
            return math.max(1, math.min(15, math.floor(lvl)))
        end
    end
    return nil
end

local function isShipPilotBlocked(pilotData)
    if not pilotData then
        return false, nil
    end
    local blockedLevel = tonumber(pilotData.blockedLevel) or 0
    if blockedLevel > 0 then
        return true, "blockedLevel_" .. tostring(blockedLevel)
    end
    if pilotData.trainingBlocked == true then
        return true, "trainingBlocked_true"
    end
    if type(pilotData.status) == "string" then
        local statusUpper = string.upper(pilotData.status)
        if string.find(statusUpper, "ADVANCE", 1, true) or string.find(statusUpper, "[BL]", 1, true) then
            return true, "status_" .. tostring(pilotData.status)
        end
    end
    return false, nil
end

-- Mirrors gt_ship_management.xml Calculate_Performance_Modifier
local function performanceModifier(level, rank)
    if level <= 2 then
        if rank == 1 then return 0 end
        if rank == 2 then return -5 end
        if rank == 3 then return -15 end
        if rank == 4 then return -25 end
    elseif level == 3 then
        if rank == 1 then return 3 end
        if rank == 2 then return 0 end
        if rank == 3 then return -8 end
        if rank == 4 then return -15 end
    elseif level >= 4 and level <= 6 then
        if rank == 1 then return 3 end
        if rank == 2 then return 0 end
        if rank == 3 then return -8 end
        if rank == 4 then return -15 end
    elseif level >= 7 and level <= 15 then
        local modifier = 0
        if level >= 12 then
            if rank == 1 then modifier = 12
            elseif rank == 2 then modifier = 9
            elseif rank == 3 then modifier = 6
            elseif rank == 4 then modifier = 3 end
        elseif level >= 9 then
            if rank == 1 then modifier = 9
            elseif rank == 2 then modifier = 6
            elseif rank == 3 then modifier = 3
            elseif rank == 4 then modifier = 0 end
        else -- 7-8
            if rank == 1 then modifier = 6
            elseif rank == 2 then modifier = 3
            elseif rank == 3 then modifier = 0
            elseif rank == 4 then modifier = -8 end
        end
        if level == 15 then
            modifier = modifier + 3
        end
        return modifier
    end
    return 0
end

-- Penalty-tier index aligned with performanceModifier / Calculate_Performance_Modifier level branches.
-- T1: 1-2 | T2: 3-6 | T3: 7-8 | T4: 9-11 | T5: 12-14 | T6: 15 (level 15 adds +3 in penalty math)
local function skillTier(level)
    local l = math.max(1, math.min(15, math.floor(tonumber(level) or 1)))
    if l <= 2 then return 1 end
    if l <= 6 then return 2 end
    if l <= 8 then return 3 end
    if l <= 11 then return 4 end
    if l <= 14 then return 5 end
    return 6
end

-- Priority within same target class: lower-level targets first.
local function compareTargetPriorityWithinClass(a, b)
    if a.level == b.level then
        return tostring(a.idcode) < tostring(b.idcode)
    end
    return a.level < b.level
end

local function collectFleetShips(commanderComponent)
    local commander = ConvertIDTo64Bit(commanderComponent)
    local ships = {}
    local seen = {}
    local pilotIndex = getGTPilotIndexByShipId()

    local function addShip(ship)
        ship = asComponentId(ship)
        if ship and ship ~= 0 and not seen[tostring(ship)] then
            local pilot = GetComponentData(ship, "assignedpilot")
            local order = getDefaultOrderId(ship)
            local commanderOrder = nil
            local isCommander = (ship == commander)
            if not isCommander then
                local shipCommander = getCommanderId(ship)
                if shipCommander then
                    commanderOrder = getDefaultOrderId(shipCommander)
                end
            end
            local isGTControlled = isCommander
                or (order and isGTOrder(order))
                or (order == "Assist" and commanderOrder and isGTOrder(commanderOrder))
            if pilot and isGTControlled then
                local rank, size = classRank(ship)
                if rank > 0 then
                    local pilot64 = ConvertIDTo64Bit(pilot)
                    local idcode = GetComponentData(ship, "idcode") or "UNK"
                    if shipHasActiveOrQueuedPilotExchangeOrder(ship) then
                        debugLog("Fleet ship ignored: " .. tostring(idcode) .. " reason=active_or_queued_pilot_exchange_order")
                        return
                    end
                    if isShipInPendingRedistribution(ship, idcode) then
                        debugLog("Fleet ship ignored: " .. tostring(idcode) .. " reason=pending_pilot_exchange")
                        return
                    end
                    local pilotData = getGTPilotDataByShip(ship, pilotIndex)
                    local isBlocked, blockedReason = isShipPilotBlocked(pilotData)
                    if isBlocked then
                        debugLog("Fleet ship ignored: " .. tostring(idcode) .. " reason=pilot_blocked detail=" .. tostring(blockedReason or "unknown"))
                        return
                    end
                    local gtLevel = getGTLevelByShip(ship, pilotIndex)
                    if gtLevel then
                        table.insert(ships, {
                            ship = ship,
                            idcode = idcode,
                            pilot = pilot64,
                            level = gtLevel,
                            rank = rank,
                            size = size,
                            orderId = order or "NONE",
                            commanderOrderId = commanderOrder or "NONE",
                            levelSource = "GT_PilotData",
                            isCommander = isCommander,
                        })
                        seen[tostring(ship)] = true
                    else
                        debugLog("Fleet ship ignored: " .. tostring(idcode)
                            .. " reason=missing_GT_level order=" .. tostring(order or "NONE")
                            .. " commanderOrder=" .. tostring(commanderOrder or "NONE"))
                    end
                end
            else
                local idcode = GetComponentData(ship, "idcode") or "UNK"
                debugLog("Fleet ship ignored: " .. tostring(idcode)
                    .. " pilot=" .. tostring(pilot ~= nil)
                    .. " gtControlled=" .. tostring(isGTControlled)
                    .. " order=" .. tostring(order or "NONE")
                    .. " commanderOrder=" .. tostring(commanderOrder or "NONE"))
            end
        end
    end

    addShip(commanderComponent)
    local subs = GetSubordinates(commander) or {}
    for _, sub in ipairs(subs) do
        addShip(sub)
    end
    return ships
end

local function requestDockOrdersFromMD(leftShip, rightShip, leftCode, rightCode)
    if type(AddUITriggeredEvent) ~= "function" then
        return false
    end
    if (not leftShip) or leftShip == 0 or (not rightShip) or rightShip == 0 then
        return false
    end
    if not leftCode or not rightCode then
        return false
    end
    AddUITriggeredEvent("GT_Redistribute", "AssignDockOrders", {
        left = tostring(leftCode),
        right = tostring(rightCode),
        leftObj = ConvertStringToLuaID(tostring(leftShip)),
        rightObj = ConvertStringToLuaID(tostring(rightShip)),
        immediate = true,
    })
    return true
end

local function trySwapCaptains(leftShip, rightShip)
    local emptyA = ffi.new("NPCSeed[1]")
    local emptyB = ffi.new("NPCSeed[1]")
    debugLog("PerformCrewExchange2 check leftShip=" .. tostring(leftShip) .. " rightShip=" .. tostring(rightShip))
    local check = C.PerformCrewExchange2(leftShip, rightShip, emptyA, 0, emptyB, 0, 0, 0, true, true)
    local checkReason = check.reason and ffi.string(check.reason) or ""
    debugLog("PerformCrewExchange2 check result leftShip=" .. tostring(leftShip) .. " rightShip=" .. tostring(rightShip) .. " reason=" .. tostring(checkReason))
    if checkReason ~= "" then
        return false, checkReason
    end

    debugLog("PerformCrewExchange2 execute leftShip=" .. tostring(leftShip) .. " rightShip=" .. tostring(rightShip))
    local exec = C.PerformCrewExchange2(leftShip, rightShip, emptyA, 0, emptyB, 0, 0, 0, true, false)
    local reason = exec.reason and ffi.string(exec.reason) or ""
    debugLog("PerformCrewExchange2 execute result leftShip=" .. tostring(leftShip) .. " rightShip=" .. tostring(rightShip) .. " reason=" .. tostring(reason))
    if reason ~= "" then
        return false, reason
    end
    return true, ""
end

local function redistribute(commanderComponent)
    local commander = ConvertIDTo64Bit(commanderComponent)
    if not commander or commander == 0 then
        return
    end

    local ships = collectFleetShips(commanderComponent)
    debugLog("Fleet setup for redistribution (eligible ships=" .. tostring(#ships) .. "):")
    for _, s in ipairs(ships) do
        debugLog(" - " .. tostring(s.idcode)
            .. " class=" .. tostring(s.size)
            .. " level=" .. tostring(s.level)
            .. " levelSource=" .. tostring(s.levelSource)
            .. " order=" .. tostring(s.orderId)
            .. " commanderOrder=" .. tostring(s.commanderOrderId))
    end
    if #ships < 2 then
        notify("Pilot redistribution: not enough eligible GT ships in fleet.")
        return
    end

    local swaps = {}
    local usedShips = {}  -- ships already committed to a swap (ensures each ship appears in at most one pair)
    local commanderShip = nil
    local subordinates = {}
    for _, s in ipairs(ships) do
        if s.isCommander then
            commanderShip = s
        else
            table.insert(subordinates, s)
        end
    end

    local function addSwap(srcShip, dstShip, reason)
        if not srcShip or not dstShip then
            return
        end
        local srcLevelBefore = srcShip.level
        local dstLevelBefore = dstShip.level
        table.insert(swaps, { left = srcShip.ship, right = dstShip.ship })
        usedShips[srcShip.idcode] = true
        usedShips[dstShip.idcode] = true
        srcShip.pilot, dstShip.pilot = dstShip.pilot, srcShip.pilot
        srcShip.level, dstShip.level = dstShip.level, srcShip.level
        debugLog("Rank swap (" .. tostring(reason or "rule") .. "): "
            .. tostring(srcShip.idcode) .. "(lvl " .. tostring(srcLevelBefore) .. ", " .. tostring(srcShip.size) .. "->" .. tostring(dstShip.size) .. ") <-> "
            .. tostring(dstShip.idcode) .. "(lvl " .. tostring(dstLevelBefore) .. ", " .. tostring(dstShip.size) .. "->" .. tostring(srcShip.size) .. ")")
    end

    -- Round 1: Fleet commander only if a same-class subordinate is on a higher penalty tier (not merely higher level within tier).
    if commanderShip then
        local cmdTier = skillTier(commanderShip.level)
        local bestForCommander = nil
        local bestTier = nil
        for _, src in ipairs(subordinates) do
            if (not usedShips[src.idcode]) and src.rank == commanderShip.rank then
                local st = skillTier(src.level)
                if st > cmdTier then
                    if (not bestForCommander)
                        or st > bestTier
                        or (st == bestTier and src.level > bestForCommander.level) then
                        bestForCommander = src
                        bestTier = st
                    end
                end
            end
        end
        if bestForCommander then
            addSwap(bestForCommander, commanderShip, "commander_round")
        else
            debugLog("Commander round: no same-class subordinate on a higher penalty tier for commander "
                .. tostring(commanderShip.idcode) .. " (cmdTier=" .. tostring(cmdTier) .. ")")
        end
    end

    -- Round 2: Subordinate-only priority assignment by destination class (XL -> L -> M).
    local classPriority = { 4, 3, 2 }
    for _, dstRank in ipairs(classPriority) do
        local destinations = {}
        for _, dst in ipairs(subordinates) do
            if (not usedShips[dst.idcode]) and dst.rank == dstRank then
                table.insert(destinations, dst)
            end
        end
        table.sort(destinations, compareTargetPriorityWithinClass)
        if #destinations > 0 then
            local order = {}
            for _, d in ipairs(destinations) do
                table.insert(order, tostring(d.idcode) .. ":lvl" .. tostring(d.level))
            end
            debugLog("Priority round rank " .. tostring(dstRank) .. " destination order (lowest first): " .. table.concat(order, ", "))
        end

        for _, dst in ipairs(destinations) do
            if not usedShips[dst.idcode] then
                local bestSource = nil
                for _, src in ipairs(subordinates) do
                    if (not usedShips[src.idcode]) and src.idcode ~= dst.idcode then
                        local classRuleOk = (src.rank < dst.rank) -- strictly lower class to higher class
                        local levelRuleOk = (src.level > dst.level) -- destination must strictly improve
                        if classRuleOk and levelRuleOk then
                            local modHigh = performanceModifier(src.level, dst.rank)
                            local modLow = performanceModifier(dst.level, src.rank)
                            local noPenalty = (modHigh >= 0 and modLow >= 0)
                            if noPenalty then
                                if (not bestSource)
                                    or (src.level > bestSource.level)
                                    or (src.level == bestSource.level and src.rank > bestSource.rank) then
                                    bestSource = src
                                end
                            end
                        end
                    end
                end

                if bestSource then
                    addSwap(bestSource, dst, "priority_round_rank_" .. tostring(dstRank))
                else
                    debugLog("Priority round rank " .. tostring(dstRank) .. ": no valid source for destination "
                        .. tostring(dst.idcode) .. " lvl=" .. tostring(dst.level))
                end
            end
        end
    end

    if #swaps == 0 then
        notify("Pilot redistribution: pilots already optimally distributed (level-to-class rank), or no penalty-free cross-class swaps possible.")
        debugLog("No swaps selected after commander + class-priority evaluation.")
        return
    end

    local requestCount = 0
    local failCount = 0
    for _, swap in ipairs(swaps) do
        local leftCode = GetComponentData(swap.left, "idcode") or "LEFT"
        local rightCode = GetComponentData(swap.right, "idcode") or "RIGHT"
        local assigned = requestDockOrdersFromMD(swap.left, swap.right, leftCode, rightCode)
        if assigned then
            local keyA, keyB = tostring(leftCode), tostring(rightCode)
            if keyA > keyB then
                keyA, keyB = keyB, keyA
            end
            pendingDockAssignmentsByPair[keyA .. "|" .. keyB] = {
                left = keyA,
                right = keyB,
                leftShip = swap.left,
                rightShip = swap.right,
            }
            requestCount = requestCount + 1
            debugLog("Dock assignment requested for " .. tostring(leftCode) .. " <-> " .. tostring(rightCode))
        else
            failCount = failCount + 1
            debugLog("Swap queue failed: could not request MD dock assignment")
        end
    end

    notify("Pilot redistribution dispatch started. Pairs: " .. tostring(requestCount) .. " requested, " .. tostring(failCount) .. " failed.")
    debugLog("Redistribution dispatch for commander " .. tostring(GetComponentData(commander, "idcode") or "UNKNOWN") .. " planned=" .. tostring(#swaps) .. " requested=" .. tostring(requestCount) .. " failed=" .. tostring(failCount))
end

local function executeSwapByIdCode(payload)
    if type(payload) ~= "table" then
        return
    end
    local leftCode = payload.left or payload.leftCode
    local rightCode = payload.right or payload.rightCode
    if not leftCode or not rightCode then
        return
    end
    debugLog("Swap execution event received left=" .. tostring(leftCode) .. " right=" .. tostring(rightCode))
    local keyA, keyB = tostring(leftCode), tostring(rightCode)
    if keyA > keyB then
        keyA, keyB = keyB, keyA
    end
    local pairKey = keyA .. "|" .. keyB
    local completed = completedSwapByPair[pairKey]
    if completed and completed.done then
        debugLog("Swap execution skipped (already completed) pair=" .. tostring(pairKey))
        return
    end

    local left = asComponentId(payload.leftUid or payload.leftObj)
    local right = asComponentId(payload.rightUid or payload.rightObj)
    local rememberedPair = popRememberedSwapPair(leftCode, rightCode)
    if (not left or left == 0) then
        left = rememberedPair and rememberedPair.left or nil
    end
    if (not right or right == 0) then
        right = rememberedPair and rememberedPair.right or nil
    end
    if not left or left == 0 or not right or right == 0 then
        left = resolveShipFromIdCode(leftCode)
        right = resolveShipFromIdCode(rightCode)
    end
    -- Enforce that resolved IDs match the expected pair idcodes before executing.
    local resolvedLeftCode = (left and left ~= 0) and tostring(GetComponentData(left, "idcode") or "") or ""
    local resolvedRightCode = (right and right ~= 0) and tostring(GetComponentData(right, "idcode") or "") or ""
    if resolvedLeftCode ~= tostring(leftCode) then
        left = resolveShipFromIdCode(leftCode)
        resolvedLeftCode = (left and left ~= 0) and tostring(GetComponentData(left, "idcode") or "") or ""
    end
    if resolvedRightCode ~= tostring(rightCode) then
        right = resolveShipFromIdCode(rightCode)
        resolvedRightCode = (right and right ~= 0) and tostring(GetComponentData(right, "idcode") or "") or ""
    end
    debugLog("Swap execution resolved leftCode=" .. tostring(leftCode) .. " leftShip=" .. tostring(left or 0)
        .. " rightCode=" .. tostring(rightCode) .. " rightShip=" .. tostring(right or 0)
        .. " resolvedLeftCode=" .. tostring(resolvedLeftCode) .. " resolvedRightCode=" .. tostring(resolvedRightCode))
    if not left or left == 0 or not right or right == 0 then
        publishPilotExchangeRelease(leftCode, rightCode, left, right)
        publishPilotExchangeRenameState(leftCode, rightCode, false)
        notify("Pilot swap failed: invalid ship IDs for queued exchange.")
        debugLog("Swap execution aborted: invalid IDs left=" .. tostring(leftCode) .. " right=" .. tostring(rightCode))
        return
    end
    if resolvedLeftCode ~= tostring(leftCode) or resolvedRightCode ~= tostring(rightCode) then
        publishPilotExchangeRelease(leftCode, rightCode, left, right)
        publishPilotExchangeRenameState(leftCode, rightCode, false)
        notify("Pilot swap failed: resolved ships do not match queued pair.")
        debugLog("Swap execution aborted: resolved mismatch expected=" .. tostring(leftCode) .. "/" .. tostring(rightCode)
            .. " got=" .. tostring(resolvedLeftCode) .. "/" .. tostring(resolvedRightCode))
        return
    end

    local ok, reason = trySwapCaptains(left, right)
    debugLog("Swap execution result left=" .. tostring(leftCode) .. " right=" .. tostring(rightCode) .. " ok=" .. tostring(ok) .. " reason=" .. tostring(reason))
    publishPilotExchangeRelease(leftCode, rightCode, left, right)
    schedulePilotExchangeReleaseRetry(leftCode, rightCode, left, right)
    publishPilotExchangeRenameState(leftCode, rightCode, false)
    if ok then
        completedSwapByPair[pairKey] = {
            left = tostring(leftCode),
            right = tostring(rightCode),
            done = true,
        }
        publishPostSwapNameRefresh(leftCode, rightCode, left, right)
        schedulePostSwapNameRefreshRetry(leftCode, rightCode, left, right)
        notify("Pilot swap executed: " .. tostring(leftCode) .. " <-> " .. tostring(rightCode))
    else
        notify("Pilot swap failed (" .. tostring(reason) .. "): " .. tostring(leftCode) .. " <-> " .. tostring(rightCode))
    end
end

local function handleDockAssignResult(payload)
    local status, leftCode, rightCode, stationCode, reason = nil, nil, nil, nil, nil
    if type(payload) == "table" then
        status = payload.status
        leftCode = payload.left or payload.leftCode
        rightCode = payload.right or payload.rightCode
        stationCode = payload.station or payload.stationCode
        reason = payload.reason
    elseif type(payload) == "string" then
        local a, b, c, d, e = string.match(payload, "^([^|]*)|([^|]*)|([^|]*)|([^|]*)|?(.*)$")
        status, leftCode, rightCode, stationCode, reason = a, b, c, d, e
    end

    if status == "fail" and (not reason or reason == "") then
        reason = stationCode
        stationCode = nil
    end

    if not status or not leftCode or not rightCode then
        debugLog("Dock assignment result ignored: invalid payload")
        return
    end

    local keyA, keyB = tostring(leftCode), tostring(rightCode)
    if keyA > keyB then
        keyA, keyB = keyB, keyA
    end
    local pairKey = keyA .. "|" .. keyB
    local pending = pendingDockAssignmentsByPair[pairKey]
    pendingDockAssignmentsByPair[pairKey] = nil

    if status == "ok" then
        local leftShip = pending and pending.leftShip or resolveShipFromIdCode(leftCode)
        local rightShip = pending and pending.rightShip or resolveShipFromIdCode(rightCode)
        local station = nil
        if stationCode and stationCode ~= "" then
            station = C.ConvertStringTo64Bit(tostring(stationCode))
        end

        rememberSwapPair(leftCode, rightCode, leftShip, rightShip)
        completedSwapByPair[pairKey] = nil
        publishPilotExchangeRenameState(leftCode, rightCode, true)
        if leftShip and leftShip ~= 0 and rightShip and rightShip ~= 0 and station and station ~= 0 then
            sendDockingLogbookMessage(leftShip, rightShip, station)
        end
        debugLog("Queued pilot swap docking orders for " .. tostring(leftCode) .. " <-> " .. tostring(rightCode) .. " station=" .. tostring(stationCode or ""))
        return
    end

    debugLog("Dock assignment failed for " .. tostring(leftCode) .. " <-> " .. tostring(rightCode) .. " reason=" .. tostring(reason or "unknown"))
end

local function requestFreshPilotDataAndRedistribute(commanderComponent)
    local commander = asComponentId(commanderComponent)
    if not commander or commander == 0 then
        return
    end
    if not Mods or not Mods.GalaxyTrader or not Mods.GalaxyTrader.PilotData or type(Mods.GalaxyTrader.PilotData.requestRefresh) ~= "function" then
        notify("Pilot redistribution unavailable: GT pilot data bridge missing.")
        debugLog("Cannot refresh GT pilot data: Mods.GalaxyTrader.PilotData.requestRefresh unavailable")
        return
    end

    pendingRedistributeCommander = commander
    pilotDataRefreshRequestedAt = getElapsedTime()
    invalidatePilotIndexCache()
    Mods.GalaxyTrader.PilotData.requestRefresh()
    debugLog("Requested fresh GT pilot data for redistribution commander " .. tostring(GetComponentData(commander, "idcode") or "UNKNOWN"))
end

local function processPendingRedistributeAfterRefresh()
    if not pendingRedistributeCommander then
        return
    end
    local now = getElapsedTime()
    if (pilotDataRefreshRequestedAt > 0) and (now - pilotDataRefreshRequestedAt > PILOT_DATA_REFRESH_TIMEOUT) then
        debugLog("GT pilot data refresh timeout for redistribution commander " .. tostring(GetComponentData(pendingRedistributeCommander, "idcode") or "UNKNOWN"))
        pendingRedistributeCommander = nil
        pilotDataRefreshRequestedAt = 0
    end
end

local function processPendingReleaseRetries()
    if #pendingReleaseRetries == 0 then
        return
    end
    local now = getElapsedTime()
    for i = #pendingReleaseRetries, 1, -1 do
        local item = pendingReleaseRetries[i]
        if item and now >= (item.dueAt or 0) then
            publishPilotExchangeRelease(item.left, item.right, item.leftShip, item.rightShip)
            item.attemptsLeft = (item.attemptsLeft or 0) - 1
            if item.attemptsLeft > 0 then
                item.dueAt = now + 2.0
                pendingReleaseRetries[i] = item
                debugLog("ReleaseDockHold retry scheduled left=" .. tostring(item.left) .. " right=" .. tostring(item.right) .. " remaining=" .. tostring(item.attemptsLeft))
            else
                table.remove(pendingReleaseRetries, i)
                debugLog("ReleaseDockHold retries completed left=" .. tostring(item.left) .. " right=" .. tostring(item.right))
            end
        end
    end
end

local function processPendingPostSwapRefreshRetries()
    if #pendingPostSwapRefreshRetries == 0 then
        return
    end
    local now = getElapsedTime()
    for i = #pendingPostSwapRefreshRetries, 1, -1 do
        local item = pendingPostSwapRefreshRetries[i]
        if item and now >= (item.dueAt or 0) then
            publishPostSwapNameRefresh(item.left, item.right, item.leftShip, item.rightShip)
            item.attemptsLeft = (item.attemptsLeft or 0) - 1
            if item.attemptsLeft > 0 then
                item.dueAt = now + 1.5
                pendingPostSwapRefreshRetries[i] = item
                debugLog("PostSwapNameRefresh retry scheduled left=" .. tostring(item.left) .. " right=" .. tostring(item.right) .. " remaining=" .. tostring(item.attemptsLeft))
            else
                table.remove(pendingPostSwapRefreshRetries, i)
                debugLog("PostSwapNameRefresh retries completed left=" .. tostring(item.left) .. " right=" .. tostring(item.right))
            end
        end
    end
end

if menu and menu.update then
    local originalUpdate = menu.update
    menu.update = function(...)
        originalUpdate(...)
        processPendingRedistributeAfterRefresh()
        processPendingReleaseRetries()
        processPendingPostSwapRefreshRetries()
    end
end

RegisterEvent("gt.redistributePilots", function(_, commanderComponent)
    requestFreshPilotDataAndRedistribute(commanderComponent)
end)

RegisterEvent("GT_PilotData.Update", function()
    invalidatePilotIndexCache()
    if pendingRedistributeCommander and pendingRedistributeCommander ~= 0 then
        local commander = pendingRedistributeCommander
        pendingRedistributeCommander = nil
        pilotDataRefreshRequestedAt = 0
        redistribute(commander)
    end
end)

RegisterEvent("gt.redistributeDockAssignResult", function(a, b, c, d)
    local payload = nil
    local args = { a, b, c, d }
    for _, v in ipairs(args) do
        if type(v) == "table" and (v.status or v.left or v.right or v.leftCode or v.rightCode) then
            payload = v
            break
        end
    end
    if not payload then
        for _, v in ipairs(args) do
            if type(v) == "string" and string.find(v, "|", 1, true) then
                payload = v
                break
            end
        end
    end
    if payload then
        handleDockAssignResult(payload)
    else
        debugLog("Dock assignment result event missing payload")
    end
end)

RegisterEvent("gt.redistributeOrderCancelled", function(_, idcode)
    clearPendingRedistributionForShip(idcode)
end)

RegisterEvent("gt.executePilotSwap", function(a, b, c, d)
    local payload = nil
    local args = { a, b, c, d }
    for _, v in ipairs(args) do
        if type(v) == "table" and (v.left or v.right or v.leftCode or v.rightCode) then
            payload = v
            break
        end
    end
    if not payload then
        for _, v in ipairs(args) do
            if type(v) == "string" and string.find(v, "|", 1, true) then
                local left, right, leftUid, rightUid = string.match(v, "^([^|]+)|([^|]+)|([^|]*)|([^|]*)$")
                if left and right and left ~= "" and right ~= "" then
                    payload = {
                        left = left,
                        right = right,
                        leftCode = left,
                        rightCode = right,
                        leftUid = leftUid,
                        rightUid = rightUid,
                    }
                    break
                end
                left, right = string.match(v, "^([^|]+)|([^|]+)$")
                if left and right and left ~= "" and right ~= "" then
                    payload = {
                        left = left,
                        right = right,
                        leftCode = left,
                        rightCode = right,
                    }
                    break
                end
            end
        end
    end
    if not payload then
        for _, v in ipairs(args) do
            if type(v) == "string" then
                local left = string.match(v, "left%s*=%s*([A-Z0-9%-]+)")
                local right = string.match(v, "right%s*=%s*([A-Z0-9%-]+)")
                if left and right and left ~= "" and right ~= "" then
                    payload = {
                        left = left,
                        right = right,
                        leftCode = left,
                        rightCode = right,
                    }
                    break
                end
            end
        end
    end
    if not payload then
        debugLog("Swap execution event payload missing/invalid argTypes="
            .. tostring(type(a)) .. "," .. tostring(type(b)) .. ","
            .. tostring(type(c)) .. "," .. tostring(type(d))
            .. " firstArg=" .. tostring(a))
        return
    end
    executeSwapByIdCode(payload)
end)

debugLog("Redistribution context integration loaded")
-- GalaxyTrader Context Menu Rename
-- Adds "GT Rename" context menu entry to ship overview in map menu

-- FFI setup
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    typedef struct {
        int x;
        int y;
    } Coord2D;
    const char* GetComponentName(UniverseID componentid);
    bool IsComponentClass(UniverseID componentid, const char* classname);
    Coord2D GetCenteredMousePos(void);
]]

local menu = Helper.getMenu("MapMenu")
if not menu then
    DebugError("[GT Context Rename] MapMenu not found - context menu rename will not be available")
    return
end

-- Store original functions
local originalCreateContextFrame = menu.createContextFrame
local originalRefreshContextFrame = menu.refreshContextFrame
local originalUpdate = menu.update
local originalButtonRenameConfirm = menu.buttonRenameConfirm

-- GT Rename Context Menu Handler
local gtRenameContext = {}

-- Create rename context menu with edit box (following vanilla pattern)
function menu.createGTRenameContext(frame)
    -- Use fallback string directly to avoid ReadText lookup errors
    local title = "GT Rename"
    local component = menu.contextMenuData.component
    
    -- Get original name to display (only use GT original name from blackboard, no fallback)
    local startname = ""
    if menu.contextMenuData.originalName and menu.contextMenuData.originalName ~= "" then
        -- Use GT original name if provided (from NPCBlackboard)
        startname = menu.contextMenuData.originalName
    end
    -- If no GT original name, startname remains empty (let user enter new name)
    
    local shiptable = frame:addTable(2, { 
        tabOrder = 2, 
        x = Helper.borderSize, 
        y = Helper.borderSize, 
        width = menu.contextMenuData.width, 
        highlightMode = "off" 
    })
    
    -- Title row
    local row = shiptable:addRow(nil, { fixed = true })
    row[1]:setColSpan(2):createText(title, Helper.headerRowCenteredProperties)
    
    -- Edit box row - CRITICAL: Store reference in contextMenuData
    -- Use Helper.standardTextHeight directly (vanilla uses config.mapRowHeight which equals Helper.standardTextHeight)
    local row = shiptable:addRow(true, { fixed = true })
    menu.contextMenuData.nameEditBox = row[1]:setColSpan(2):createEditBox({ 
        height = Helper.scaleY(Helper.standardTextHeight), 
        description = title 
    }):setText(startname)
    
    -- Set up text change handler
    row[1].handlers.onTextChanged = function (_, text, textchanged) 
        menu.contextMenuData.newtext = text 
    end
    
    -- Set up deactivation handler (called when edit box loses focus or is confirmed)
    row[1].handlers.onEditBoxDeactivated = function (_, text, textchanged, isconfirmed) 
        return menu.buttonGTRenameConfirm(isconfirmed) 
    end
    
    -- Confirmation buttons
    local row = shiptable:addRow(true, { fixed = true })
    row[1]:createButton({}):setText(ReadText(1001, 2821), { halign = "center" })  -- "OK"
    row[1].handlers.onClick = function () return menu.buttonGTRenameConfirm(true) end
    
    row[2]:createButton({}):setText(ReadText(1001, 64), { halign = "center" })  -- "Cancel"
    row[2].handlers.onClick = function () return menu.closeContextMenu("back") end
    
    -- Adjust frame position if needed
    local neededheight = shiptable.properties.y + shiptable:getVisibleHeight()
    if frame.properties.y + neededheight + Helper.frameBorder > Helper.viewHeight then
        menu.contextMenuData.yoffset = Helper.viewHeight - neededheight - Helper.frameBorder
        frame.properties.y = menu.contextMenuData.yoffset
    end
end

-- Handle rename confirmation
function menu.buttonGTRenameConfirm(isconfirmed)
    if isconfirmed then
        local component = menu.contextMenuData.component
        local newname = menu.contextMenuData.newtext
        
        if component and newname and newname ~= "" then
            -- Get current name to check if it changed
            local currentName = ""
            local namePtr = C.GetComponentName(component)
            if namePtr and namePtr ~= 0 then
                currentName = ffi.string(namePtr)
            end
            
            if newname ~= currentName then
                -- Store rename data in NPCBlackboard for MD to read
                -- Store newName separately to avoid table access issues
                local playerId = ConvertStringTo64Bit(tostring(C.GetPlayerID()))
                SetNPCBlackboard(playerId, "$GT_ContextRename_NewName", newname)

                -- Multi-rename support: apply same name to all selected ships.
                -- Non-GT ships are filtered on MD side (GT service guard).
                local targets = {}
                local seen = {}

                if menu.selectedcomponents then
                    for id, _ in pairs(menu.selectedcomponents) do
                        local selectedComponent = ConvertStringTo64Bit(tostring(id))
                        if selectedComponent and selectedComponent ~= 0 and C.IsComponentClass(selectedComponent, "ship") then
                            local key = tostring(selectedComponent)
                            if not seen[key] then
                                seen[key] = true
                                table.insert(targets, selectedComponent)
                            end
                        end
                    end
                end

                -- Fallback to single target if no multi-selection is present.
                if #targets == 0 and component and component ~= 0 then
                    table.insert(targets, component)
                end

                for _, targetComponent in ipairs(targets) do
                    SignalObject(playerId, "gt_context_rename_confirmed", ConvertStringToLuaID(tostring(targetComponent)))
                end
                DebugError(string.format("[GT Context Rename] Signaled MD for %d component(s), newName=%s", #targets, newname))
            end
        end
    end
    menu.noupdate = false
    if menu.refreshInfoFrame then
        menu.refreshInfoFrame()
    end
    menu.closeContextMenu("back")
    return true
end

-- Hook into createContextFrame to add support for "gt_rename" mode
-- Following vanilla pattern: createContextFrame creates frame, refreshContextFrame populates and displays
menu.createContextFrame = function(width, height, xoffset, yoffset, noborder, startanimation, ...)
    -- Check if we're creating our rename context
    if menu.contextMenuMode == "gt_rename" then
        -- Use same pattern as vanilla - create the frame handle immediately
        -- refreshContextFrame will populate it with content
        
        -- Set up data
        local mousepos = C.GetCenteredMousePos()
        menu.contextMenuData = menu.contextMenuData or {}
        menu.contextMenuData.xoffset = xoffset or (mousepos.x + Helper.viewWidth / 2)
        menu.contextMenuData.yoffset = yoffset or (mousepos.y + Helper.viewHeight / 2)
        menu.contextMenuData.width = width or Helper.scaleX(400)
        
        -- Adjust position if needed
        if menu.contextMenuData.xoffset + menu.contextMenuData.width > Helper.viewWidth then
            menu.contextMenuData.xoffset = Helper.viewWidth - menu.contextMenuData.width - Helper.frameBorder
        end
        
        -- CRITICAL: Create frame handle immediately (like vanilla does)
        -- Use standard contextFrameLayer (2) - context menus render on top regardless of layer
        local contextLayer = 2
        Helper.removeAllWidgetScripts(menu, contextLayer)
        
        menu.contextFrame = Helper.createFrameHandle(menu, {
            x = menu.contextMenuData.xoffset - (noborder and 0 or 2 * Helper.borderSize),
            y = menu.contextMenuData.yoffset,
            width = menu.contextMenuData.width + (noborder and 0 or 2 * Helper.borderSize),
            layer = contextLayer,
            standardButtons = { close = true },
            closeOnUnhandledClick = true,
            startAnimation = startanimation,
        })
        menu.contextFrame:setBackground("solid", { color = Color["frame_background_semitransparent"] })
        
        -- CRITICAL: Populate frame content immediately (like vanilla does)
        menu.createGTRenameContext(menu.contextFrame)
        
        -- Adjust frame height
        menu.contextFrame.properties.height = math.min(Helper.viewHeight - menu.contextFrame.properties.y, menu.contextFrame:getUsedHeight() + Helper.borderSize)
        
        return menu.contextFrame
    end
    
    -- Call original for other contexts
    if originalCreateContextFrame then
        return originalCreateContextFrame(width, height, xoffset, yoffset, noborder, startanimation, ...)
    end
end

-- Hook into refreshContextFrame to handle our rename mode AND add button to vanilla rename context
menu.refreshContextFrame = function(setrow, setcol, noborder, ...)
    -- Handle our rename mode BEFORE calling original (so we can override)
    if menu.contextMenuMode == "gt_rename" then
        -- CRITICAL: Remove widget scripts first (like vanilla does)
        local contextLayer = 2
        Helper.removeAllWidgetScripts(menu, contextLayer)
        
        -- Frame was already created and populated in createContextFrame
        -- refreshContextFrame just needs to display it (like vanilla does)
        if menu.contextFrame then
            menu.contextFrame:display()
        end
        return
    end
    
    -- Call original for other contexts
    if originalRefreshContextFrame then
        originalRefreshContextFrame(setrow, setcol, noborder, ...)
    end
    
    -- DO NOT add button to vanilla rename context - user wants to keep vanilla rename untouched
end

-- Hook into update to activate edit box after context menu is shown
menu.update = function(...)
    -- Call original update first
    if originalUpdate then
        originalUpdate(...)
    end
    
    -- Activate edit box if we have one pending (following vanilla pattern)
    if menu.contextMenuData and menu.contextMenuData.nameEditBox then
        ActivateEditBox(menu.contextMenuData.nameEditBox.id)
        menu.contextMenuData.nameEditBox = nil
    end
end

-- Function to open GT Rename context menu (can be called from anywhere)
function menu.openGTRenameContext(component, originalName)
    DebugError("[GT Context Rename] openGTRenameContext called")
    
    if not component then
        DebugError("[GT Context Rename] ERROR: No component provided")
        return
    end
    
    DebugError(string.format("[GT Context Rename] Component: %s", tostring(component)))
    
    local mousepos = C.GetCenteredMousePos()
    DebugError(string.format("[GT Context Rename] Mouse pos: x=%d, y=%d", mousepos.x, mousepos.y))
    
    menu.contextMenuMode = "gt_rename"
    menu.contextMenuData = { 
        component = component,
        originalName = originalName,  -- Store original name for display
        xoffset = mousepos.x + Helper.viewWidth / 2, 
        yoffset = mousepos.y + Helper.viewHeight / 2 
    }
    
    DebugError(string.format("[GT Context Rename] Context menu data: xoffset=%d, yoffset=%d", menu.contextMenuData.xoffset, menu.contextMenuData.yoffset))
    
    local width = Helper.scaleX(400)
    DebugError(string.format("[GT Context Rename] Width: %d", width))
    
    if menu.contextMenuData.xoffset + width > Helper.viewWidth then
        menu.contextMenuData.xoffset = Helper.viewWidth - width - Helper.frameBorder
        DebugError(string.format("[GT Context Rename] Adjusted xoffset: %d", menu.contextMenuData.xoffset))
    end
    
    DebugError("[GT Context Rename] Calling createContextFrame")
    menu.createContextFrame(width, nil, menu.contextMenuData.xoffset, menu.contextMenuData.yoffset)
    DebugError("[GT Context Rename] createContextFrame returned")
    
    DebugError("[GT Context Rename] Calling refreshContextFrame")
    menu.refreshContextFrame()
    DebugError("[GT Context Rename] refreshContextFrame returned")
end

-- DO NOT hook into createRenameContext - user wants to keep vanilla rename untouched

-- Register Lua event to handle MD script callback
RegisterEvent("gt.openRenameContext", function(_, component)
    DebugError("[GT Context Rename] Lua: Event gt.openRenameContext received")
    
    if component then
        local component64 = ConvertIDTo64Bit(component)
        DebugError(string.format("[GT Context Rename] Lua: Component converted: %s", tostring(component64)))
        
        if component64 and component64 ~= 0 then
            -- Get original name from NPCBlackboard (set by MD script)
            -- MD uses: player.entity.$GT_ContextRename_OriginalName
            -- Lua reads: GetNPCBlackboard(playerId, "$GT_ContextRename_OriginalName")
            local playerId = ConvertStringTo64Bit(tostring(C.GetPlayerID()))
            local originalName = GetNPCBlackboard(playerId, "$GT_ContextRename_OriginalName")
            
            DebugError(string.format("[GT Context Rename] Lua: Original name from blackboard: %s", tostring(originalName)))
            
            menu.openGTRenameContext(component64, originalName)
        end
    end
end)

-- Hook into onInteractMenuCallback to handle our "gt_renamecontext" event
-- This follows the vanilla pattern for "renamecontext" 
local originalOnInteractMenuCallback = menu.onInteractMenuCallback
if originalOnInteractMenuCallback then
    menu.onInteractMenuCallback = function(type, param, ...)
        -- Handle our "gt_renamecontext" event (similar to vanilla "renamecontext")
        if type == "gt_renamecontext" then
            local mousepos = C.GetCenteredMousePos()
            menu.contextMenuMode = "gt_rename"
            menu.contextMenuData = { 
                component = param[1], 
                xoffset = mousepos.x + Helper.viewWidth / 2, 
                yoffset = mousepos.y + Helper.viewHeight / 2 
            }
            
            local width = Helper.scaleX(400)
            if menu.contextMenuData.xoffset + width > Helper.viewWidth then
                menu.contextMenuData.xoffset = Helper.viewWidth - width - Helper.frameBorder
            end
            
            menu.createContextFrame(width, nil, menu.contextMenuData.xoffset, menu.contextMenuData.yoffset)
            return
        end
        
        -- Call original for other events
        if originalOnInteractMenuCallback then
            return originalOnInteractMenuCallback(type, param, ...)
        end
    end
end

-- Hook into createRenameContext to add our "GT Rename" button to the vanilla rename context
-- This adds a button that opens our floating window instead of the vanilla rename dialog

DebugError("[GT Context Rename] Context menu rename integration loaded")
DebugError("[GT Context Rename] To use: Call menu.openGTRenameContext(component) to open rename dialog")
-- GalaxyTrader MK3 - Credits Due Overlay
--
-- Displays GT projected due directly after player money on the left-side
-- player info line (line 3), while leaving vanilla due text untouched.
--
-- DESIGN NOTE:
-- All attempts to create an independent overlay frame via
-- Helper.createFrameHandle + display() on a dedicated layer crash the
-- MapMenu widget engine with "frameElement nil" (widget_fullscreen.lua:16258).
-- The widget_fullscreen presentation only supports the layers the MapMenu
-- registers (mainFrameLayer=6, infoFrameLayer=5, contextFrameLayer=2).
-- Creating a frame on any other layer causes persistent crashes on every
-- update tick.
--
-- This approach hooks Helper.playerInfoConfigTextLeft and appends compact GT
-- text to line 3 (player money), avoiding new lines and preserving vanilla
-- right-side due display.

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    UniverseID GetPlayerID(void);
]]

if not Helper or (not Helper.playerInfoConfigTextLeft and not Helper.playerInfoConfigInfoText) then
    DebugError("[GT CreditsDue] Required Helper player info text function(s) not found - override not installed")
    return
end

-- =============================================================================
-- STATE
-- =============================================================================

local state = {
    lastPoll = 0,
    enabled = false,
    projectedCredits = 0,
    lastLoggedCredits = nil,
    lastLoggedEnabled = nil,
    numberFormat = "german",
    useMSuffix = true,
    mSuffixThreshold = 999999,
}

-- =============================================================================
-- HELPERS
-- =============================================================================

local function isTruthy(value)
    if value == true then
        return true
    end
    if value == false or value == nil then
        return false
    end
    if type(value) == "number" then
        return value ~= 0
    end
    if type(value) == "string" then
        local lower = string.lower(value)
        return (lower == "true") or (lower == "1")
    end
    return false
end

local function addThousandsSeparators(value, sep)
    local s = tostring(math.floor(math.abs(value)))
    local out = s
    while true do
        local replaced, count = string.gsub(out, "^(-?%d+)(%d%d%d)", "%1" .. sep .. "%2")
        out = replaced
        if count == 0 then
            break
        end
    end
    return out
end

local function formatCredits(creditsAmount)
    local credits = tonumber(creditsAmount) or 0
    local absCredits = math.abs(credits)
    local thousandSep = (state.numberFormat == "german") and "." or ","
    local decimalSep = (state.numberFormat == "german") and "," or "."
    local prefix = (credits < 0) and "-" or ""

    if state.useMSuffix and absCredits >= (tonumber(state.mSuffixThreshold) or 999999) then
        local mValue = absCredits / 1000000
        local intPart = math.floor(mValue)
        local fracPart = math.floor((mValue - intPart) * 10 + 0.5)
        if fracPart >= 10 then
            intPart = intPart + 1
            fracPart = 0
        end
        local text = tostring(intPart) .. decimalSep .. tostring(fracPart) .. " M Cr"
        return prefix .. text
    end

    return prefix .. addThousandsSeparators(absCredits, thousandSep) .. " Cr"
end

local function formatCreditsCompact(creditsAmount)
    local credits = tonumber(creditsAmount) or 0
    local absCredits = math.abs(credits)
    local thousandSep = (state.numberFormat == "german") and "." or ","
    local decimalSep = (state.numberFormat == "german") and "," or "."
    local prefix = (credits < 0) and "-" or ""

    if state.useMSuffix and absCredits >= (tonumber(state.mSuffixThreshold) or 999999) then
        local mValue = absCredits / 1000000
        local intPart = math.floor(mValue)
        local fracPart = math.floor((mValue - intPart) * 10 + 0.5)
        if fracPart >= 10 then
            intPart = intPart + 1
            fracPart = 0
        end
        return prefix .. tostring(intPart) .. decimalSep .. tostring(fracPart) .. "M Cr"
    end

    return prefix .. addThousandsSeparators(absCredits, thousandSep) .. " Cr"
end

local function splitLines(text)
    local lines = {}
    for line in string.gmatch((text or "") .. "\n", "(.-)\n") do
        table.insert(lines, line)
    end
    while #lines < 3 do
        table.insert(lines, "")
    end
    return lines
end

-- =============================================================================
-- BRIDGE DATA (MD -> Lua via player.entity blackboard)
-- =============================================================================

local function pollBridgeData()
    local now = getElapsedTime()
    if (state.lastPoll + 1) > now then
        return
    end
    state.lastPoll = now

    local playerId = ConvertStringTo64Bit(tostring(C.GetPlayerID()))
    if not playerId or playerId == 0 then
        return
    end

    state.enabled = isTruthy(GetNPCBlackboard(playerId, "$GT_UI_UseCreditsDueOverride"))
    -- Read the RAW field directly. GetNPCBlackboard auto-converts centicredits
    -- to credits when reading from player.entity, so NO division needed here.
    -- MD stores 427720000 (centicredits) â†’ GetNPCBlackboard returns 4277200 (Cr).
    local projectedRaw = tonumber(GetNPCBlackboard(playerId, "$GT_UI_CreditsDueProjectedRaw")) or 0
    state.projectedCredits = projectedRaw
    state.numberFormat = GetNPCBlackboard(playerId, "$GT_UI_NumberFormat") or "german"
    state.useMSuffix = isTruthy(GetNPCBlackboard(playerId, "$GT_UI_UseMSuffix"))
    state.mSuffixThreshold = tonumber(GetNPCBlackboard(playerId, "$GT_UI_MSuffixThreshold")) or 999999

    if (state.numberFormat ~= "german") and (state.numberFormat ~= "english") then
        state.numberFormat = "german"
    end

    state.lastLoggedCredits = state.projectedCredits
    state.lastLoggedEnabled = state.enabled
end

-- =============================================================================
-- PLAYER INFO TEXT HOOKS
-- =============================================================================

local function getDefaultMoneyLineWidth()
    if not Helper or not Helper.playerInfoConfig then
        return nil
    end
    return Helper.playerInfoConfig.width - Helper.playerInfoConfig.height - 2 * Helper.borderSize
end

local function appendGtDueToMoneyLine(vanillaResult, width, ismultiverse)
    if ismultiverse then
        return vanillaResult
    end

    pollBridgeData()
    if not state.enabled then
        return vanillaResult
    end

    local gtCredits = tonumber(state.projectedCredits) or 0
    if gtCredits <= 0 then
        return vanillaResult
    end

    local lines = splitLines(vanillaResult)
    local moneyLineIndex = #lines
    if moneyLineIndex < 1 then
        return vanillaResult
    end

    local gtToken = ColorText["text_positive"] .. " | GT " .. formatCreditsCompact(gtCredits) .. "\27X"
    lines[moneyLineIndex] = (lines[moneyLineIndex] or "") .. gtToken

    local moneyLineWidth = width
    if not moneyLineWidth or moneyLineWidth <= 0 then
        moneyLineWidth = getDefaultMoneyLineWidth()
    end
    if moneyLineWidth and moneyLineWidth > 0 then
        lines[moneyLineIndex] = TruncateText(lines[moneyLineIndex], Helper.playerInfoConfig.fontname, Helper.playerInfoConfig.fontsize, moneyLineWidth)
    end

    return table.concat(lines, "\n")
end

-- Hook legacy 3-line panel path (used in some monitors).
if Helper.playerInfoConfigTextLeft then
    local originalPlayerInfoConfigTextLeft = Helper.playerInfoConfigTextLeft
    Helper.playerInfoConfigTextLeft = function(cell, width, ismultiverse)
        local vanillaResult = originalPlayerInfoConfigTextLeft(cell, width, ismultiverse)
        return appendGtDueToMoneyLine(vanillaResult, width, ismultiverse)
    end
end

-- Hook X4 9 map path (player panel now uses playerInfoConfigInfoText).
if Helper.playerInfoConfigInfoText then
    local originalPlayerInfoConfigInfoText = Helper.playerInfoConfigInfoText
    Helper.playerInfoConfigInfoText = function(cell, width, ismultiverse)
        local vanillaResult = originalPlayerInfoConfigInfoText(cell, width, ismultiverse)
        return appendGtDueToMoneyLine(vanillaResult, width, ismultiverse)
    end
end

DebugError("[GT CreditsDue] player info hook installed (TextLeft/InfoText inline money approach)")
-- GalaxyTrader - Crew Name Highlight Override
--
-- Colors crew list names in MapMenu when the person belongs to GT pilot registry.
-- Matching: PilotIdMap keys only â€” seed / StableIdentity / idcode, plus int64 aliases from gt_pilot_data_bridge (NPCSeed uint64).
-- This is UI-only and does not modify vanilla/MD name fields.

local DEBUG_RECOLOR = false
local REFRESH_THROTTLE_SECONDS = 2
local MISS_DIAG_THROTTLE_SECONDS = 6
local lastRefreshRequestTime = -1000
local lastMissDiagTime = -1000
local recolorPassCounter = 0
local missingMenuLogged = false

local function resolveMapMenu()
    if Helper and Helper.getMenu then
        local m = Helper.getMenu("MapMenu")
        if m then
            return m
        end
    end
    if Menus then
        return Menus["MapMenu"]
    end
    return nil
end

local function logRecolor(message)
    if DEBUG_RECOLOR then
        DebugError("[GT Crew Highlight] " .. tostring(message))
    end
end

local function getGTPilotIdMap()
    if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData and Mods.GalaxyTrader.PilotData.getGTPilotIdMap then
        return Mods.GalaxyTrader.PilotData.getGTPilotIdMap()
    end
    return {}
end

local function isCrewHighlightEnabledBySettings()
    local bridge = Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData
    if not bridge or not bridge.settings then
        return false
    end
    return bridge.settings.pilotRenamingEnabled == true
end

local function getPersonIdCode(person)
    -- personentry.person in MapMenu is an NPCSeed, not a component.
    -- Calling GetComponentData(person, "idcode") causes runtime errors.
    return nil
end

local function getPersonRefKey(person)
    if not person then
        return nil
    end
    local ref = tostring(person)
    if ref == "" or ref == "0" then
        return nil
    end
    return ref
end

local function normalizeUniquePilotKey(key)
    if not key then
        return nil
    end
    local s = tostring(key)
    s = s:gsub("^%s+", ""):gsub("%s+$", "")
    s = s:gsub("[Uu][Ll][Ll]$", "")
    s = s:gsub("[Ll][Ll]$", "")
    s = s:gsub("[Uu][Ll]$", "")
    s = s:gsub("[Uu]$", "")
    if s == "" or s == "0" then
        return nil
    end
    return s
end

local function requestGTRefreshIfNeeded(reason)
    if not (Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData and Mods.GalaxyTrader.PilotData.requestRefresh) then
        return
    end

    local now = getElapsedTime()
    if (now - lastRefreshRequestTime) >= REFRESH_THROTTLE_SECONDS then
        lastRefreshRequestTime = now
        Mods.GalaxyTrader.PilotData.requestRefresh()
        logRecolor("requested pilot refresh: reason=" .. tostring(reason))
    end
end

local function installCrewHighlightHook()
    local menu = resolveMapMenu()
    if not menu then
        if not missingMenuLogged then
            missingMenuLogged = true
            DebugError("[GT Crew Highlight] MapMenu not found - deferring crew highlight hook")
        end
        return
    end
    missingMenuLogged = false

    if menu.__gtCrewHighlightHookInstalled
        and menu.__gtCrewHighlightWrappedCombine
        and menu.infoSubmenuCombineCrewTables ~= menu.__gtCrewHighlightWrappedCombine then
        -- Another script / reload replaced the function after we hooked it.
        menu.__gtCrewHighlightHookInstalled = nil
        menu.__gtCrewHighlightWrappedCombine = nil
        DebugError("[GT Crew Highlight] Detected combine hook replacement - reinstalling")
    end

    if menu.__gtCrewHighlightHookInstalled then
        return
    end

    local orig_infoSubmenuCombineCrewTables = menu.infoSubmenuCombineCrewTables
    if type(orig_infoSubmenuCombineCrewTables) ~= "function" then
        DebugError("[GT Crew Highlight] infoSubmenuCombineCrewTables not found - deferring crew highlight hook")
        return
    end

    local wrappedCombine = function(instance)
        local result = orig_infoSubmenuCombineCrewTables(instance)
        if type(result) ~= "table" then
            return result
        end

        -- Keep GT pilot-id cache fresh while crew menu is open (newly swapped pilots).
        requestGTRefreshIfNeeded("periodic_refresh")

        -- Strict behavior: crew highlight is enabled only when pilot renaming is enabled in GT settings.
        if not isCrewHighlightEnabledBySettings() then
            return result
        end

        local gtPilotIdMap = getGTPilotIdMap()
        recolorPassCounter = recolorPassCounter + 1
        local passId = recolorPassCounter

        if not next(gtPilotIdMap) then
            DebugError("[GT Crew Highlight] pass=" .. tostring(passId) .. " skip: GT pilot-id map empty")
            requestGTRefreshIfNeeded("empty_pilot_id_map")
            return result
        end

        local checked = 0
        local matched = 0
        local missingPersonRef = 0
        local missingPilotId = 0
        local noMapEntry = 0
        local missingTaggedName = 0
        local missDiagDone = false

        local bridge = Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData
        local lookupTagged = bridge and bridge.lookupPilotIdMapTaggedName
        local diagnoseMiss = bridge and bridge.diagnosePilotIdMapMiss

        for _, personentry in ipairs(result) do
            checked = checked + 1

            local personRef = personentry and personentry.person
            if not personRef then
                missingPersonRef = missingPersonRef + 1
                logRecolor("pass=" .. tostring(passId) .. " row=" .. tostring(checked) .. " missing person reference; uiName='" .. tostring(personentry and personentry.name) .. "'")
            else
                local pilotId = getPersonIdCode(personRef)
                local personRefKey = getPersonRefKey(personRef)
                local personRefKeyNormalized = normalizeUniquePilotKey(personRefKey)
                local taggedName = nil
                local matchedKey = nil

                if pilotId and gtPilotIdMap[pilotId] and gtPilotIdMap[pilotId] ~= "" then
                    taggedName = gtPilotIdMap[pilotId]
                    matchedKey = pilotId
                elseif lookupTagged then
                    taggedName, matchedKey = lookupTagged(gtPilotIdMap, personRef)
                elseif personRefKey and gtPilotIdMap[personRefKey] and gtPilotIdMap[personRefKey] ~= "" then
                    -- Legacy fallback path if bridge helper is unavailable.
                    taggedName = gtPilotIdMap[personRefKey]
                    matchedKey = personRefKey
                elseif personRefKeyNormalized and gtPilotIdMap[personRefKeyNormalized] and gtPilotIdMap[personRefKeyNormalized] ~= "" then
                    taggedName = gtPilotIdMap[personRefKeyNormalized]
                    matchedKey = personRefKeyNormalized
                end

                if taggedName and taggedName ~= "" then
                    personentry.name = ColorText["text_positive"] .. taggedName .. "\27X"
                    matched = matched + 1
                    logRecolor(
                        "pass=" .. tostring(passId) ..
                        " row=" .. tostring(checked) ..
                        " match key=" .. tostring(matchedKey) ..
                        " idcode=" .. tostring(pilotId) ..
                        " personRef=" .. tostring(personRefKey) ..
                        " personRefNormalized=" .. tostring(personRefKeyNormalized) ..
                        " tagged='" .. tostring(taggedName) .. "'"
                    )
                elseif (not pilotId) and (not personRefKey) then
                    missingPilotId = missingPilotId + 1
                    logRecolor("pass=" .. tostring(passId) .. " row=" .. tostring(checked) .. " no idcode for person=" .. tostring(personRef) .. " uiName='" .. tostring(personentry and personentry.name) .. "'")
                else
                    if pilotId and gtPilotIdMap[pilotId] ~= nil and gtPilotIdMap[pilotId] == "" then
                        missingTaggedName = missingTaggedName + 1
                        DebugError("[GT Crew Highlight] pass=" .. tostring(passId) .. " row=" .. tostring(checked) .. " idcode key in map but tagged name empty: " .. tostring(pilotId))
                    elseif personRefKey and gtPilotIdMap[personRefKey] ~= nil and gtPilotIdMap[personRefKey] == "" then
                        missingTaggedName = missingTaggedName + 1
                        DebugError("[GT Crew Highlight] pass=" .. tostring(passId) .. " row=" .. tostring(checked) .. " personRef key in map but tagged name empty: " .. tostring(personRefKey))
                    elseif personRefKeyNormalized and gtPilotIdMap[personRefKeyNormalized] ~= nil and gtPilotIdMap[personRefKeyNormalized] == "" then
                        missingTaggedName = missingTaggedName + 1
                        DebugError("[GT Crew Highlight] pass=" .. tostring(passId) .. " row=" .. tostring(checked) .. " normalized personRef key in map but tagged name empty: " .. tostring(personRefKeyNormalized))
                    else
                        noMapEntry = noMapEntry + 1
                        logRecolor(
                            "pass=" .. tostring(passId) ..
                            " row=" .. tostring(checked) ..
                            " no map entry idcode=" .. tostring(pilotId) ..
                            " personRef=" .. tostring(personRefKey) ..
                            " personRefNormalized=" .. tostring(personRefKeyNormalized) ..
                            " uiName='" .. tostring(personentry and personentry.name) .. "'"
                        )
                        local now = getElapsedTime()
                        if (not missDiagDone) and diagnoseMiss and ((now - lastMissDiagTime) >= MISS_DIAG_THROTTLE_SECONDS) then
                            missDiagDone = true
                            lastMissDiagTime = now
                            diagnoseMiss(
                                gtPilotIdMap,
                                personRef,
                                "crew row=" .. tostring(checked) .. " uiName=" .. tostring(personentry and personentry.name)
                            )
                        end
                    end
                end
            end
        end

        DebugError(
            "[GT Crew Highlight] pass=" .. tostring(passId) ..
            " complete checked=" .. tostring(checked) ..
            " matched=" .. tostring(matched) ..
            " missingPersonRef=" .. tostring(missingPersonRef) ..
            " missingPilotId=" .. tostring(missingPilotId) ..
            " noMapEntry=" .. tostring(noMapEntry) ..
            " missingTaggedName=" .. tostring(missingTaggedName) ..
            " mapSizeKnown=" .. tostring(next(gtPilotIdMap) ~= nil)
        )

        if matched == 0 and checked > 0 then
            DebugError("[GT Crew Highlight] pass=" .. tostring(passId) .. " WARNING: zero matches in crew table; requesting refresh for diagnostics")
            requestGTRefreshIfNeeded("zero_matches")
        end

        return result
    end
    menu.infoSubmenuCombineCrewTables = wrappedCombine

    menu.__gtCrewHighlightHookInstalled = true
    menu.__gtCrewHighlightWrappedCombine = wrappedCombine
    DebugError("[GT Crew Highlight] MapMenu crew name highlight hook installed (strict pilot-id mode)")
end

local function installCrewHighlightUpdateGuard()
    local menu = resolveMapMenu()
    if not menu then
        return
    end
    if menu.__gtCrewHighlightUpdateGuardInstalled then
        return
    end
    if type(menu.update) ~= "function" then
        return
    end

    local originalUpdate = menu.update
    menu.update = function(...)
        installCrewHighlightHook()
        return originalUpdate(...)
    end
    menu.__gtCrewHighlightUpdateGuardInstalled = true
    DebugError("[GT Crew Highlight] MapMenu update guard installed")
end

installCrewHighlightHook()
installCrewHighlightUpdateGuard()

if RegisterEvent then
    RegisterEvent("showMapMenu", function()
        installCrewHighlightHook()
        installCrewHighlightUpdateGuard()
    end)
    RegisterEvent("GT_PilotIdMap.Update", function()
        installCrewHighlightHook()
        installCrewHighlightUpdateGuard()
    end)
end
-- GalaxyTrader MK3 Info Menu
-- Phase 1: Basic Display with Sorting

local menu = {}
local gtMenu = {
    isCreated = false,
    currentSort = { column = "pilotProfit", descending = true },  -- Default sort by pilot profit
    currentTab = "overview",  -- Current tab: "overview", "control", or "renaming"
    selectedShipId = nil,     -- Track selected ship across tabs (shipId string)
    renamingShipId = nil,     -- Track which ship is currently being renamed (to show editbox)
    lastRefreshTime = 0,      -- Track last refresh to prevent rapid updates
    refreshCooldown = 3,      -- Minimum seconds between auto-refreshes (prevents row jumping)
    lastDataRequestTime = 0,  -- Throttle MD refresh requests when bridge not initialized
    dataRequestCooldown = 2,  -- Seconds between initialization refresh requests
    isBuildingInfoFrame = false, -- Guard against re-entrant refresh during frame build
    rowHeight = Helper.standardTextHeight,
    fontSize = Helper.standardFontSize,
}

-- Fetch all pilot data from Lua bridge (populated by MD)
function gtMenu.getPilotData()
    local pilots = {}
    
    -- Check if pilot data bridge is loaded
    if not Mods or not Mods.GalaxyTrader or not Mods.GalaxyTrader.PilotData then
        DebugError("[GT Menu] Pilot data bridge not loaded yet")
        return pilots
    end
    
    local pilotBridge = Mods.GalaxyTrader.PilotData
    
    -- Request fresh data from MD if not initialized
    if not pilotBridge.isInitialized() then
        local now = getElapsedTime()
        if (now - gtMenu.lastDataRequestTime) >= gtMenu.dataRequestCooldown then
            DebugError("[GT Menu] Requesting initial pilot data from MD")
            pilotBridge.requestRefresh()
            gtMenu.lastDataRequestTime = now
        end
        return pilots
    end
    
    -- Get pilots from bridge
    pilots = pilotBridge.getPilots()
    
    -- local dataAge = getElapsedTime() - pilotBridge.getLastUpdate()
    -- DebugError(string.format("[GT Menu] Retrieved %d pilots from bridge (last update: %.1fs ago)", 
    --     #pilots, dataAge))
    
    return pilots
end

-- Called by pilot data bridge when new data arrives (event-driven refresh)
function gtMenu.onDataUpdate()
    -- Only refresh if the menu is currently open and showing our info
    if menu and menu.infoTableMode == "galaxytraderinfo" then
        -- X4 9 UI can throw rowgroup/cell overwrite errors when refreshInfoFrame
        -- is triggered asynchronously during an active frame build. Avoid
        -- event-driven refresh here; data is pulled on the next normal redraw.
        if gtMenu.isBuildingInfoFrame then
            return
        end
    end
end

-- Format money - delegate to GT_UI library (single source of truth)
function gtMenu.formatMoney(amount)
    if GT_UI and GT_UI.formatMoney then
        return GT_UI.formatMoney(amount)
    end
    -- Fallback if library not loaded (shouldn't happen)
    local credits = amount / 100
    if credits >= 1000000000 then
        return string.format("%.1fB Cr", credits / 1000000000)
    elseif credits >= 1000000 then
        return string.format("%.1fM Cr", credits / 1000000)
    else
        return ConvertMoneyString(amount, false, false, 0, true)
    end
end

-- Safe string comparison that handles special characters
local function safeStringCompare(a, b)
    -- Normalize strings to lowercase
    local aStr = string.lower(tostring(a or ""))
    local bStr = string.lower(tostring(b or ""))
    
    -- Simple string comparison
    if aStr == bStr then
        return false  -- Equal strings
    end
    return aStr < bStr
end

-- Sort pilot data by current sort configuration
function gtMenu.sortPilots(pilots)
    if not pilots or #pilots == 0 then
        return
    end
    
    local sortColumn = gtMenu.currentSort.column
    local descending = gtMenu.currentSort.descending
    
    -- Use pcall to protect against sort failures
    local success, err = pcall(function()
        table.sort(pilots, function(a, b)
            -- Safety check: ensure both objects are valid
            if not a then return false end
            if not b then return true end
            
            -- Get primary sort values with explicit type conversion
            local aVal, bVal
            local isNumeric = false
            
            if sortColumn == "shipId" then
                aVal = tostring(a.shipId or "")
                bVal = tostring(b.shipId or "")
            elseif sortColumn == "pilot" then
                aVal = tostring(a.pilotName or "")
                bVal = tostring(b.pilotName or "")
            elseif sortColumn == "ship" then
                aVal = tostring(a.shipType or "")
                bVal = tostring(b.shipType or "")
            elseif sortColumn == "status" then
                aVal = tostring(a.status or "")
                bVal = tostring(b.status or "")
            elseif sortColumn == "rank" then
                aVal = tonumber(a.rankIndex) or 1
                bVal = tonumber(b.rankIndex) or 1
                isNumeric = true
            elseif sortColumn == "level" then
                aVal = tonumber(a.level) or 1
                bVal = tonumber(b.level) or 1
                isNumeric = true
            elseif sortColumn == "xp" then
                aVal = tonumber(a.xp) or 0
                bVal = tonumber(b.xp) or 0
                isNumeric = true
            elseif sortColumn == "pilotProfit" then
                aVal = tonumber(a.pilotProfit) or 0
                bVal = tonumber(b.pilotProfit) or 0
                isNumeric = true
            elseif sortColumn == "shipProfit" then
                aVal = tonumber(a.shipProfit) or 0
                bVal = tonumber(b.shipProfit) or 0
                isNumeric = true
            elseif sortColumn == "sector" then
                aVal = tostring(a.location or "")
                bVal = tostring(b.location or "")
            else
                -- Default: sort by pilot name
                aVal = tostring(a.pilotName or "")
                bVal = tostring(b.pilotName or "")
            end
            
            -- Primary comparison
            if aVal ~= bVal then
                local result
                if isNumeric then
                    result = aVal < bVal
                else
                    result = safeStringCompare(aVal, bVal)
                end
                -- Fix: Proper strict weak ordering - when descending, invert result
                if descending then
                    return not result
                else
                    return result
                end
            end
            
            -- Secondary sort by pilot name (always ascending for stability)
            local aName = tostring(a.pilotName or "")
            local bName = tostring(b.pilotName or "")
            if aName ~= bName then
                return safeStringCompare(aName, bName)
            end
            
            -- Tertiary sort by ship ID if names are also equal
            local aShip = tostring(a.shipId or "")
            local bShip = tostring(b.shipId or "")
            return safeStringCompare(aShip, bShip)
        end)
    end)
    
    if not success then
        DebugError("[GT Menu] Sort failed: " .. tostring(err))
    end
end

-- Handle column header click for sorting
function gtMenu.onHeaderClick(sortColumn)
    -- DebugError(string.format("[GT Menu] onHeaderClick called: column='%s', currentColumn='%s', currentDesc=%s", 
    --     sortColumn, gtMenu.currentSort.column, tostring(gtMenu.currentSort.descending)))
    
    -- Toggle sort direction if clicking same column, otherwise default to descending
    if gtMenu.currentSort.column == sortColumn then
        gtMenu.currentSort.descending = not gtMenu.currentSort.descending
    else
        gtMenu.currentSort.column = sortColumn
        gtMenu.currentSort.descending = true
    end
    
    -- DebugError(string.format("[GT Menu] New sort state: column='%s', descending=%s", 
    --     gtMenu.currentSort.column, tostring(gtMenu.currentSort.descending)))
    
    -- User-initiated refresh bypasses cooldown and updates lastRefreshTime
    gtMenu.lastRefreshTime = getElapsedTime()
    
    -- Refresh the info frame to show new sort
    if menu and menu.refreshInfoFrame then
        menu.refreshInfoFrame()
        -- DebugError("[GT Menu] refreshInfoFrame called successfully")
    else
        DebugError("[GT Menu] ERROR: menu.refreshInfoFrame not available!")
    end
end

-- Display pilot table in info frame
function gtMenu.displayPilotTable(frame, instance, yOffset)
    -- DebugError(string.format("[GT Menu] displayPilotTable called - current sort: '%s' %s", 
    --     gtMenu.currentSort.column, gtMenu.currentSort.descending and "DESC" or "ASC"))
    
    -- Fetch pilot data
    local pilots = gtMenu.getPilotData()
    gtMenu.sortPilots(pilots)
    
    -- Create table with 10 columns - make it wider for better readability
    -- Position below tabs if yOffset is provided
    local pilotTable = frame:addTable(10, { 
        tabOrder = 2, 
        reserveScrollBar = false,  -- Disable for now - causes column width issues
        width = Helper.standardTextWidth * 4,
        y = yOffset or 0,
        maxVisibleHeight = Helper.viewHeight
    })
    pilotTable:setDefaultCellProperties("text", { minRowHeight = gtMenu.rowHeight, fontsize = gtMenu.fontSize })
    
    -- Set column widths (percentages add up to 100%)
    pilotTable:setColWidthPercent(1, 8)   -- Ship ID
    pilotTable:setColWidthPercent(2, 12)  -- Pilot
    pilotTable:setColWidthPercent(3, 10)  -- Ship
    pilotTable:setColWidthPercent(4, 13)  -- Status
    pilotTable:setColWidthPercent(5, 10)  -- Rank
    pilotTable:setColWidthPercent(6, 5)   -- Level
    pilotTable:setColWidthPercent(7, 11)  -- XP
    pilotTable:setColWidthPercent(8, 11)  -- Pilot Profit
    pilotTable:setColWidthPercent(9, 11)  -- Ship Profit
    pilotTable:setColWidthPercent(10, 9)  -- Sector
    
    -- Header row with click handlers for sorting
    local headerRow = pilotTable:addRow(false, { bgColor = Color["row_title_background"], fixed = true })
    
    -- Helper function to create sortable header (must use buttons, not text!)
    local function createSortableHeader(cell, textId, sortColumn)
        local text = ReadText(77000, textId)
        local displayText = text
        
        -- Add arrow indicator for currently sorted column
        if gtMenu.currentSort.column == sortColumn then
            displayText = text .. (gtMenu.currentSort.descending and " â–¼" or " â–²")
        end
        
        -- Create button (text cells are not clickable)
        cell:createButton({ height = gtMenu.rowHeight }):setText(displayText, { halign = "center" })
        
        -- Set click handler on the cell
        cell.handlers.onClick = function()
            DebugError("[GT Menu] Header clicked: " .. sortColumn)
            return gtMenu.onHeaderClick(sortColumn)
        end
    end
    
    createSortableHeader(headerRow[1], 8100, "shipId")      -- Ship ID
    createSortableHeader(headerRow[2], 8101, "pilot")       -- Pilot
    createSortableHeader(headerRow[3], 8102, "ship")        -- Ship
    createSortableHeader(headerRow[4], 8103, "status")      -- Status
    createSortableHeader(headerRow[5], 8104, "rank")        -- Rank
    createSortableHeader(headerRow[6], 8105, "level")       -- Level
    createSortableHeader(headerRow[7], 8106, "xp")          -- XP
    createSortableHeader(headerRow[8], 8111, "pilotProfit") -- Pilot Profit
    createSortableHeader(headerRow[9], 8112, "shipProfit")  -- Ship Profit
    createSortableHeader(headerRow[10], 8114, "sector")     -- Sector
    
    -- Check if we have any pilots
    if #pilots == 0 then
        local emptyRow = pilotTable:addRow(nil, {})
        emptyRow[1]:setColSpan(10):createText(ReadText(77000, 8600), { halign = "center" })
        local emptyRow2 = pilotTable:addRow(nil, {})
        emptyRow2[1]:setColSpan(10):createText(ReadText(77000, 8601), { halign = "center", fontsize = Helper.standardFontSize * 0.8 })
        return
    end
    
    -- FIX: Limit rows to prevent X4's 50 shield/hull bar limit from being exceeded
    -- X4 automatically creates shield/hull bars for selectable rows, and has a global limit of 50
    -- Limit display to 50 rows to stay under the limit (header + 50 rows = 51 total, but header doesn't count)
    local maxRows = 50
    local pilotsToDisplay = pilots
    if #pilots > maxRows then
        pilotsToDisplay = {}
        for i = 1, maxRows do
            pilotsToDisplay[i] = pilots[i]
        end
        DebugError(string.format("[GT Menu] Limiting display to %d rows (out of %d total) to prevent shield/hull bar limit", maxRows, #pilots))
    end
    
    -- Add pilot rows as regular rows (non-selectable) to avoid rowgroup conflicts in X4 9 UI.
    for i, pilot in ipairs(pilotsToDisplay) do
        -- Highlight selected row
        local isSelected = (pilot.shipId == gtMenu.selectedShipId)
        local cellBgColor = isSelected and Color["row_background_selected"] or nil
        
        local row = pilotTable:addRow(false, {})
        
        -- Column order MUST match headers: Ship ID, Pilot, Ship, Status, Rank, Level, XP, Pilot Profit, Ship Profit, Sector
        row[1]:createText(pilot.shipId or "???", { cellBGColor = cellBgColor })
        row[2]:createText(pilot.pilotName or "Unknown", { cellBGColor = cellBgColor })
        row[3]:createText(pilot.shipType or "Unknown Ship", { cellBGColor = cellBgColor })
        row[4]:createText(pilot.status or "[UNKNOWN]", { cellBGColor = cellBgColor })
        row[5]:createText(pilot.rank or "Apprentice", { cellBGColor = cellBgColor })
        row[6]:createText(tostring(pilot.level or 1), { halign = "center", cellBGColor = cellBgColor })
        row[7]:createText(pilot.xpFormatted or "0 / 1000", { halign = "right", cellBGColor = cellBgColor })
        row[8]:createText(pilot.pilotProfitFormatted or "0 Cr", { halign = "right", cellBGColor = cellBgColor })
        row[9]:createText(pilot.shipProfitFormatted or "0 Cr", { halign = "right", cellBGColor = cellBgColor })
        row[10]:createText(pilot.location or "Unknown", { cellBGColor = cellBgColor })
    end
    
    -- Footer row with totals
    local footerRow = pilotTable:addRow(nil, { bgColor = Color["row_title_background"] })
    if #pilots > maxRows then
        footerRow[1]:setColSpan(7):createText(string.format("%s %d (Showing: %d)", ReadText(77000, 8402), #pilots, maxRows), {})  -- "Total Pilots: N (Showing: 50)"
    else
        footerRow[1]:setColSpan(7):createText(string.format("%s %d", ReadText(77000, 8402), #pilots), {})  -- "Total Pilots: N"
    end
    
    -- Calculate total pilot profit and total ship profit
    local totalPilotProfit = 0
    local totalShipProfit = 0
    for _, pilot in ipairs(pilots) do
        totalPilotProfit = totalPilotProfit + (pilot.pilotProfit or 0)
        totalShipProfit = totalShipProfit + (pilot.shipProfit or 0)
    end
    footerRow[8]:createText(gtMenu.formatMoney(totalPilotProfit), { halign = "right" })
    footerRow[9]:createText(gtMenu.formatMoney(totalShipProfit), { halign = "right" })
end

-- Add sidebar button to Map Menu
function gtMenu.createSideBar(_config)
    -- Debug: Log what's being called (commented out to reduce log spam)
    -- DebugError("[GT Menu] createSideBar called - menu.name: " .. tostring(menu and menu.name or "nil"))
    
    -- CRITICAL: Only add button to Map Menu, not other menus
    -- Check the menu object itself, not just the config
    if not menu or menu.name ~= "MapMenu" then
        DebugError("[GT Menu] Skipping - not MapMenu (menu.name=" .. tostring(menu and menu.name or "nil") .. ")")
        return  -- Wrong menu object
    end
    
    -- Only add button once
    if gtMenu.isCreated then
        -- DebugError("[GT Menu] Skipping - button already created")
        return
    end
    
    if not _config or not _config.leftBar then
        DebugError("[GT Menu] Skipping - invalid config")
        return
    end
    
    -- Log existing buttons before we add ours (commented out to reduce log spam)
    -- DebugError("[GT Menu] leftBar has " .. tostring(#_config.leftBar) .. " items before adding GT button")
    -- for i, item in ipairs(_config.leftBar) do
    --     if item.name then
    --         DebugError("[GT Menu]   [" .. i .. "] name=" .. tostring(item.name) .. " mode=" .. tostring(item.mode))
    --     elseif item.spacing then
    --         DebugError("[GT Menu]   [" .. i .. "] (spacing)")
    --     end
    -- end
    
    -- Double-check by looking for Map Menu specific modes
    local hasMapMode = false
    for _, item in ipairs(_config.leftBar) do
        if item.mode and (item.mode == "info" or item.mode == "sectors") then
            hasMapMode = true
            break
        end
    end
    
    if not hasMapMode then
        -- DebugError("[GT Menu] Skipping - no Map Menu modes found")
        return  -- Not Map Menu
    end
    
    -- Add our button to Map Menu - insert right after "Information" button for consistent positioning
    local gtInfoButton = {
        name = ReadText(77000, 8000),  -- "GalaxyTrader Fleet"
        icon = "mapst_cheats",
        mode = "galaxytraderinfo",
        helpOverlayID = "help_sidebar_galaxytraderinfo",
        helpOverlayText = ReadText(77000, 8001)  -- "GalaxyTrader fleet management and pilot statistics"
    }
    
    -- Find the "Information" button position (vanilla button, always present)
    local insertPosition = #_config.leftBar + 1  -- Default: append at end
    for i, item in ipairs(_config.leftBar) do
        if item.mode and item.mode == "info" then
            -- Insert right after "Information" button (after its spacing if present)
            insertPosition = i + 1
            -- Skip spacing if next item is spacing
            if _config.leftBar[insertPosition] and _config.leftBar[insertPosition].spacing then
                insertPosition = insertPosition + 1
            end
            -- DebugError("[GT Menu] Found 'Information' button at position " .. i .. ", inserting at " .. insertPosition)
            break
        end
    end
    
    -- Insert button at fixed position relative to vanilla button
    table.insert(_config.leftBar, insertPosition, { spacing = true })
    table.insert(_config.leftBar, insertPosition + 1, gtInfoButton)
    
    gtMenu.isCreated = true
    -- DebugError("[GT Menu] GT button added successfully at position " .. (insertPosition + 1))
end

-- Render info frame when mode is active
-- Note: Callback passes menu.infoFrame as parameter, but we access it directly from menu
function gtMenu.createInfoFrame()
    if menu.infoTableMode == "galaxytraderinfo" then
        gtMenu.isBuildingInfoFrame = true
        local ok, err = pcall(function()
            -- Clear previously added widgets before rebuilding. In X4 9, repeated
            -- createInfoFrame callbacks can reuse menu.infoFrame; appending tables
            -- without clearing causes cell overwrite/disconnected rowgroup errors.
            if menu.infoFrame and menu.infoFrame.content then
                for _, widget in ipairs(menu.infoFrame.content) do
                    if widget.descriptor then
                        ReleaseDescriptor(widget.descriptor)
                    end
                end
                menu.infoFrame.content = {}
            end

            -- BETA PREVIEW BANNER
            local bannerTable = menu.infoFrame:addTable(1, {
                tabOrder = 0,
                width = Helper.standardTextWidth * 4,
                y = 0
            })
            local bannerRow = bannerTable:addRow(false, { bgColor = Color["text_warning"] })
            bannerRow[1]:createText("âš  BETA PREVIEW - This feature is under development. Some functionality may be incomplete or change in future versions. âš ", {
                halign = "center",
                fontsize = Helper.standardFontSize,
                color = Color["text_negative"],
                wordwrap = true
            })
            
            -- Calculate banner height for proper spacing
            local bannerHeight = Helper.standardTextHeight * 2
            
            -- Create tabs with proper width allocation (3 tabs)
            local tabTable = menu.infoFrame:addTable(3, { 
                tabOrder = 1, 
                width = Helper.standardTextWidth * 4,
                y = bannerHeight
            })
            tabTable:setColWidthPercent(1, 33)
            tabTable:setColWidthPercent(2, 34)
            tabTable:setColWidthPercent(3, 33)
            
            local tabRow = tabTable:addRow(false, { fixed = true })
            
            -- Overview Tab
            local overviewBgColor = (gtMenu.currentTab == "overview") and Color["row_background_selected"] or Color["row_background_blue"]
            local overviewBtn = tabRow[1]:createButton({ 
                height = gtMenu.rowHeight,
                bgColor = overviewBgColor 
            })
            overviewBtn:setText(ReadText(77000, 8300), { halign = "center" })
            tabRow[1].handlers.onClick = function()
                -- DebugError("[GT Menu] Overview tab clicked")
                gtMenu.currentTab = "overview"
                menu.refreshInfoFrame()
                return true
            end
            
            -- Control Tab
            local controlBgColor = (gtMenu.currentTab == "control") and Color["row_background_selected"] or Color["row_background_blue"]
            local controlBtn = tabRow[2]:createButton({ 
                height = gtMenu.rowHeight,
                bgColor = controlBgColor 
            })
            controlBtn:setText(ReadText(77000, 8301), { halign = "center" })
            tabRow[2].handlers.onClick = function()
                -- DebugError("[GT Menu] Control tab clicked")
                gtMenu.currentTab = "control"
                menu.refreshInfoFrame()
                return true
            end
            
            -- Renaming Tab
            local renamingBgColor = (gtMenu.currentTab == "renaming") and Color["row_background_selected"] or Color["row_background_blue"]
            local renamingBtn = tabRow[3]:createButton({ 
                height = gtMenu.rowHeight,
                bgColor = renamingBgColor 
            })
            renamingBtn:setText(ReadText(77000, 8302), { halign = "center" })
            tabRow[3].handlers.onClick = function()
                -- DebugError("[GT Menu] Renaming tab clicked")
                gtMenu.currentTab = "renaming"
                menu.refreshInfoFrame()
                return true
            end
            
            -- Calculate total offset: banner + tabs + spacing
            local tabHeight = gtMenu.rowHeight + 10  -- Tab button height + small margin
            local contentYOffset = bannerHeight + tabHeight  -- Banner height + tab height
            
            -- Display content based on current tab (positioned below banner and tabs)
            if gtMenu.currentTab == "overview" then
                gtMenu.displayPilotTable(menu.infoFrame, "left", contentYOffset)
            elseif gtMenu.currentTab == "control" then
                gtMenu.displayPilotControl(menu.infoFrame, "left", contentYOffset)
            elseif gtMenu.currentTab == "renaming" then
                gtMenu.displayRenaming(menu.infoFrame, "left", contentYOffset)
            end
        end)
        gtMenu.isBuildingInfoFrame = false
        if not ok then
            DebugError("[GT Menu] createInfoFrame failed: " .. tostring(err))
        end
    end
end

-- Display ship renaming panel
function gtMenu.displayRenaming(frame, instance, yOffset)
    DebugError(string.format("[GT Menu] displayRenaming called (yOffset=%s)", tostring(yOffset)))
    
    -- Validate parameters
    if not frame then
        DebugError("[GT Menu] ERROR: frame is nil!")
        return
    end
    
    -- Ensure yOffset is a valid number
    yOffset = tonumber(yOffset) or 0
    
    -- Fetch pilot data
    local pilots = gtMenu.getPilotData()
    gtMenu.sortPilots(pilots)
    
    -- Create table with 5 columns: Ship ID, Pilot, Current Name, EditBox/Rename, Set/Cancel
    local renamingTable = frame:addTable(5, { 
        tabOrder = 2, 
        reserveScrollBar = false,  -- Disable for now - causes column width issues
        width = Helper.standardTextWidth * 4,
        y = yOffset,
        maxVisibleHeight = Helper.viewHeight
    })
    renamingTable:setDefaultCellProperties("text", { minRowHeight = gtMenu.rowHeight, fontsize = gtMenu.fontSize })
    
    -- Set column widths (percentages add up to 100%)
    renamingTable:setColWidthPercent(1, 10)  -- Ship ID
    renamingTable:setColWidthPercent(2, 16)  -- Pilot
    renamingTable:setColWidthPercent(3, 30)  -- Current Custom Name (text display)
    renamingTable:setColWidthPercent(4, 30)  -- EditBox or Rename button
    renamingTable:setColWidthPercent(5, 14)  -- Set/Cancel buttons
    
    -- Header row
    local headerRow = renamingTable:addRow(false, { bgColor = Color["row_title_background"], fixed = true })
    headerRow[1]:createText(ReadText(77000, 8100), { halign = "center" })  -- Ship ID
    headerRow[2]:createText(ReadText(77000, 8101), { halign = "center" })  -- Pilot
    headerRow[3]:createText(ReadText(77000, 8321), { halign = "center" })  -- Custom Name
    headerRow[4]:createText("New Name", { halign = "center" })  -- EditBox/Rename
    headerRow[5]:createText(ReadText(77000, 8456), { halign = "center" })  -- Actions
    
    -- Check if we have any pilots
    if #pilots == 0 then
        local emptyRow = renamingTable:addRow(nil, {})
        emptyRow[1]:setColSpan(5):createText(ReadText(77000, 8600), { halign = "center" })
        local emptyRow2 = renamingTable:addRow(nil, {})
        emptyRow2[1]:setColSpan(5):createText(ReadText(77000, 8601), { halign = "center", fontsize = Helper.standardFontSize * 0.8 })
        return
    end
    
    -- FIX: Limit rows to prevent X4's 50 shield/hull bar limit from being exceeded
    local maxRows = 50
    local pilotsToDisplay = pilots
    if #pilots > maxRows then
        pilotsToDisplay = {}
        for i = 1, maxRows do
            pilotsToDisplay[i] = pilots[i]
        end
        DebugError(string.format("[GT Menu] Limiting renaming display to %d rows (out of %d total) to prevent shield/hull bar limit", maxRows, #pilots))
    end
    
    -- Add pilot rows - interactive to allow editbox and buttons
    local selectedRowIndex = nil
    for i, pilot in ipairs(pilotsToDisplay) do
        -- Track which row should be selected
        if pilot.shipId == gtMenu.selectedShipId then
            selectedRowIndex = i
        end
        
        -- Highlight selected row
        local isSelected = (pilot.shipId == gtMenu.selectedShipId)
        local cellBgColor = isSelected and Color["row_background_selected"] or nil
        
        local row = renamingTable:addRow(false, { interactive = true })
        
        -- Ship ID
        row[1]:createText(pilot.shipId or "???", { cellBGColor = cellBgColor })
        
        -- Pilot Name
        row[2]:createText(pilot.pilotName or "Unknown", { cellBGColor = cellBgColor })
        
        -- Current Custom Name (text display)
        local currentName = pilot.customName or "(not set)"
        local nameColor = pilot.customName and nil or Color["text_inactive"]
        row[3]:createText(currentName, { cellBGColor = cellBgColor, color = nameColor })
        
        -- Column 4 & 5 - show editbox+buttons if editing, otherwise show Rename button
        local isEditing = (gtMenu.renamingShipId == pilot.shipId)
        
        if isEditing then
            -- Show editbox for entering new name
            local editBox = row[4]:createEditBox({ 
                height = gtMenu.rowHeight
            })
            editBox:setText(pilot.customName or "")
            
            -- Set button to save the new name
            local setBtn = row[5]:createButton({ 
                height = gtMenu.rowHeight,
                bgColor = Color["button_background_default"]
            })
            setBtn:setText("Set", { halign = "center", fontsize = gtMenu.fontSize * 0.8 })
            row[5].handlers.onClick = function()
                local newName = GetEditBoxText(row[4].id)
                DebugError(string.format("[GT Renaming] Set name for %s: '%s'", pilot.shipId, tostring(newName)))
                
                -- TODO: Send to MD to store custom name
                if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotControl then
                    DebugError("[GT Renaming] Would set custom name: " .. tostring(newName))
                end
                
                -- Clear editing state and refresh
                gtMenu.renamingShipId = nil
                menu.refreshInfoFrame()
                return true
            end
        else
            -- Show Rename button in column 4, empty column 5
            local renameBtn = row[4]:createButton({ 
                height = gtMenu.rowHeight,
                bgColor = Color["button_background_default"]
            })
            renameBtn:setText("Rename", { halign = "center", fontsize = gtMenu.fontSize * 0.8 })
            row[4].handlers.onClick = function()
                -- DebugError("[GT Renaming] Rename button clicked for " .. pilot.shipId)
                gtMenu.renamingShipId = pilot.shipId
                menu.refreshInfoFrame()  -- Refresh to show editbox
                return true
            end
            
            -- Cancel button in column 5 (only shown when editing)
            row[5]:createText("", { cellBGColor = cellBgColor })
        end
    end
    
    -- Restore selection in X4 table system (preserves selection across refreshes/tab switches)
    if selectedRowIndex then
        renamingTable:setSelectedRow(selectedRowIndex)
        -- DebugError(string.format("[GT Menu] Renaming tab: Restored selection to row %d", selectedRowIndex))
    end
    
    -- Footer row
    local footerRow = renamingTable:addRow(nil, { bgColor = Color["row_title_background"] })
    if #pilots > maxRows then
        footerRow[1]:setColSpan(5):createText(string.format("%s %d (Showing: %d)", ReadText(77000, 8402), #pilots, maxRows), { halign = "center" })
    else
        footerRow[1]:setColSpan(5):createText(string.format("%s %d", ReadText(77000, 8402), #pilots), { halign = "center" })
    end
end

-- Display pilot control panel
function gtMenu.displayPilotControl(frame, instance, yOffset)
    DebugError(string.format("[GT Menu] displayPilotControl called (yOffset=%s)", tostring(yOffset)))
    
    -- Validate parameters
    if not frame then
        DebugError("[GT Menu] ERROR: frame is nil!")
        return
    end
    
    -- Ensure yOffset is a valid number
    yOffset = tonumber(yOffset) or 0
    
    -- Fetch pilot data and settings
    local pilots = gtMenu.getPilotData()
    gtMenu.sortPilots(pilots)
    
    -- Get settings from data bridge with safe access
    local settings = {
        autoTraining = true,
        autoRepair = true,
        autoResupply = true
    }
    
    local bridgeAvailable = Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData
    if bridgeAvailable and Mods.GalaxyTrader.PilotData.settings then
        DebugError("[GT Menu] Reading settings from bridge")
        settings.autoTraining = Mods.GalaxyTrader.PilotData.settings.autoTraining
        settings.autoRepair = Mods.GalaxyTrader.PilotData.settings.autoRepair
        settings.autoResupply = Mods.GalaxyTrader.PilotData.settings.autoResupply
    else
        DebugError("[GT Menu] WARNING: Bridge settings not available, using defaults")
    end
    
    DebugError(string.format("[GT Menu] Settings: AutoTraining=%s, AutoRepair=%s, AutoResupply=%s",
        tostring(settings.autoTraining), tostring(settings.autoRepair), tostring(settings.autoResupply)))
    
    -- Count how many action buttons to show (based on settings)
    local actionCount = 0
    if not settings.autoTraining then actionCount = actionCount + 1 end  -- Show training button if auto-training is OFF
    if not settings.autoRepair then actionCount = actionCount + 1 end    -- Show repair button if auto-repair is OFF
    actionCount = actionCount + 2  -- Always show: Force Sell Cargo + Deregister
    
    DebugError(string.format("[GT Menu] Action buttons to display: %d", actionCount))
    
    -- Calculate column count: 5 info columns + actionCount action columns
    local columnCount = 5 + actionCount
    
    -- Safety check
    if columnCount < 6 then
        DebugError("[GT Menu] ERROR: Column count too low: " .. columnCount)
        columnCount = 7  -- Minimum: 5 info + 2 actions
    end
    
    DebugError(string.format("[GT Menu] Creating table with %d columns", columnCount))
    
    -- Create table with dynamic column count
    -- Position below tabs if yOffset is provided
    local controlTable = frame:addTable(columnCount, { 
        tabOrder = 2, 
        reserveScrollBar = false,  -- Disable for now - causes column width issues
        width = Helper.standardTextWidth * 4,
        y = yOffset or 0,
        maxVisibleHeight = Helper.viewHeight
    })
    controlTable:setDefaultCellProperties("text", { minRowHeight = gtMenu.rowHeight, fontsize = gtMenu.fontSize })
    
    -- Set column widths (percentages add up to 100%)
    -- Info columns take 60%, action columns share remaining 40%
    local infoColumnTotal = 60
    local actionColumnTotal = 40
    local perActionColumn = actionColumnTotal / math.max(actionCount, 1)  -- Prevent division by zero
    
    DebugError(string.format("[GT Menu] Column width per action: %.2f%%", perActionColumn))
    
    controlTable:setColWidthPercent(1, 10)  -- Ship ID
    controlTable:setColWidthPercent(2, 15)  -- Pilot
    controlTable:setColWidthPercent(3, 15)  -- Ship
    controlTable:setColWidthPercent(4, 12)  -- Status
    controlTable:setColWidthPercent(5, 8)   -- Rank
    
    -- Set action column widths dynamically
    for i = 1, actionCount do
        local colIndex = 5 + i
        controlTable:setColWidthPercent(colIndex, perActionColumn)
        DebugError(string.format("[GT Menu] Set column %d width to %.2f%%", colIndex, perActionColumn))
    end
    
    -- Header row
    local headerRow = controlTable:addRow(false, { bgColor = Color["row_title_background"], fixed = true })
    headerRow[1]:createText(ReadText(77000, 8100), { halign = "center" })  -- Ship ID
    headerRow[2]:createText(ReadText(77000, 8101), { halign = "center" })  -- Pilot
    headerRow[3]:createText(ReadText(77000, 8102), { halign = "center" })  -- Ship
    headerRow[4]:createText(ReadText(77000, 8103), { halign = "center" })  -- Status
    headerRow[5]:createText(ReadText(77000, 8104), { halign = "center" })  -- Rank
    headerRow[6]:setColSpan(actionCount):createText(ReadText(77000, 8456), { halign = "center" })  -- Actions
    
    -- Check if we have any pilots
    if #pilots == 0 then
        local emptyRow = controlTable:addRow(nil, {})
        emptyRow[1]:setColSpan(columnCount):createText(ReadText(77000, 8600), { halign = "center" })
        local emptyRow2 = controlTable:addRow(nil, {})
        emptyRow2[1]:setColSpan(columnCount):createText(ReadText(77000, 8601), { halign = "center", fontsize = Helper.standardFontSize * 0.8 })
        return
    end
    
    -- FIX: Limit rows to prevent X4's 50 shield/hull bar limit from being exceeded
    local maxRows = 50
    local pilotsToDisplay = pilots
    if #pilots > maxRows then
        pilotsToDisplay = {}
        for i = 1, maxRows do
            pilotsToDisplay[i] = pilots[i]
        end
        DebugError(string.format("[GT Menu] Limiting control display to %d rows (out of %d total) to prevent shield/hull bar limit", maxRows, #pilots))
    end
    
    -- Add pilot rows - interactive rows allow buttons.
    for i, pilot in ipairs(pilotsToDisplay) do
        -- Highlight selected row
        local isSelected = (pilot.shipId == gtMenu.selectedShipId)
        local cellBgColor = isSelected and Color["row_background_selected"] or nil
        
        -- Use interactive = true to allow buttons in the row (non-selectable row to avoid rowgroup issues).
        local row = controlTable:addRow(false, { interactive = true })
        
        -- Info columns
        row[1]:createText(pilot.shipId or "???", { cellBGColor = cellBgColor })
        row[2]:createText(pilot.pilotName or "Unknown", { cellBGColor = cellBgColor })
        row[3]:createText(pilot.shipType or "Unknown Ship", { cellBGColor = cellBgColor })
        row[4]:createText(pilot.status or "[UNKNOWN]", { cellBGColor = cellBgColor })
        row[5]:createText(pilot.rank or "Apprentice", { cellBGColor = cellBgColor })
        
        -- Action buttons - added dynamically based on settings
        local currentCol = 6
        
        -- Training button (only if automatic training is disabled)
        if not settings.autoTraining then
            if pilot.trainingBlocked then
                local trainingBtn = row[currentCol]:createButton({ 
                    height = gtMenu.rowHeight, 
                    bgColor = Color["button_background_default"] 
                })
                trainingBtn:setText(ReadText(77000, 8450), { halign = "center", fontsize = gtMenu.fontSize * 0.8 })
                row[currentCol].handlers.onClick = function()
                    -- DebugError("[GT Control] Training button clicked for pilot: " .. pilot.pilotName .. " (Ship: " .. pilot.shipId .. ")")
                    if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotControl and Mods.GalaxyTrader.PilotControl.sendToTraining then
                        Mods.GalaxyTrader.PilotControl.sendToTraining(pilot.shipId)
                    else
                        DebugError("[GT Control] ERROR: PilotControl bridge not available!")
                    end
                    return true
                end
            else
                row[currentCol]:createText("-", { halign = "center", cellBGColor = cellBgColor, color = Color["text_inactive"] })
            end
            currentCol = currentCol + 1
        end
        
        -- Repair button (only if automatic repair is disabled)
        if not settings.autoRepair then
            local repairBtn = row[currentCol]:createButton({ 
                height = gtMenu.rowHeight, 
                bgColor = Color["button_background_default"] 
            })
            repairBtn:setText(ReadText(77000, 8453), { halign = "center", fontsize = gtMenu.fontSize * 0.8 })
            row[currentCol].handlers.onClick = function()
                -- DebugError("[GT Control] Repair button clicked for pilot: " .. pilot.pilotName .. " (Ship: " .. pilot.shipId .. ")")
                if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotControl and Mods.GalaxyTrader.PilotControl.sendToRepair then
                    Mods.GalaxyTrader.PilotControl.sendToRepair(pilot.shipId)
                else
                    DebugError("[GT Control] ERROR: PilotControl bridge not available!")
                end
                return true
            end
            currentCol = currentCol + 1
        end
        
        -- Force Sell Cargo button (always shown)
        local sellCargoBtn = row[currentCol]:createButton({ 
            height = gtMenu.rowHeight, 
            bgColor = Color["button_background_default"] 
        })
        sellCargoBtn:setText(ReadText(77000, 8452), { halign = "center", fontsize = gtMenu.fontSize * 0.8 })
        row[currentCol].handlers.onClick = function()
            -- DebugError("[GT Control] Force Sell Cargo button clicked for pilot: " .. pilot.pilotName .. " (Ship: " .. pilot.shipId .. ")")
            if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotControl and Mods.GalaxyTrader.PilotControl.forceSellCargo then
                Mods.GalaxyTrader.PilotControl.forceSellCargo(pilot.shipId)
            else
                DebugError("[GT Control] ERROR: PilotControl bridge not available!")
            end
            return true
        end
        currentCol = currentCol + 1
        
        -- Deregister button (always shown) - use red color to indicate danger
        local deregisterBtn = row[currentCol]:createButton({ 
            height = gtMenu.rowHeight, 
            bgColor = Color["button_background_default"]
        })
        deregisterBtn:setText(ReadText(77000, 8451), { halign = "center", fontsize = gtMenu.fontSize * 0.8, color = Color["text_warning"] })
        row[currentCol].handlers.onClick = function()
            -- DebugError("[GT Control] Deregister button clicked for pilot: " .. pilot.pilotName .. " (Ship: " .. pilot.shipId .. ")")
            if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotControl and Mods.GalaxyTrader.PilotControl.deregisterShip then
                Mods.GalaxyTrader.PilotControl.deregisterShip(pilot.shipId)
            else
                DebugError("[GT Control] ERROR: PilotControl bridge not available!")
            end
            return true
        end
    end
    
    -- Footer row with totals
    local footerRow = controlTable:addRow(nil, { bgColor = Color["row_title_background"] })
    if #pilots > maxRows then
        footerRow[1]:setColSpan(columnCount):createText(string.format("%s %d (Showing: %d)", ReadText(77000, 8402), #pilots, maxRows), { halign = "center" })
    else
        footerRow[1]:setColSpan(columnCount):createText(string.format("%s %d", ReadText(77000, 8402), #pilots), { halign = "center" })
    end
end

-- Initialize and register callbacks
local function init()
    DebugError("GalaxyTrader MK3 Info Menu - Phase 1: Basic Display with Sorting")
    
    menu = Helper.getMenu("MapMenu")
    if menu then
        menu.registerCallback("createSideBar_on_start", gtMenu.createSideBar)
        menu.registerCallback("createInfoFrame_on_menu_infoTableMode", gtMenu.createInfoFrame)
    end
    
    -- Export to global scope for pilot data bridge to trigger refreshes
    if not Mods then Mods = {} end
    if not Mods.GalaxyTrader then Mods.GalaxyTrader = {} end
    Mods.GalaxyTrader.InfoMenu = gtMenu
end

-- Start initialization
init()
-- GalaxyTrader MK2 - Ware exchange queue bridge
-- Resolves internal-transfer deals via GetWareExchangeTradeList and queues them
-- with AddTradeToShipQueue (buy legs first, then sell), matching normal MK2 flow.

local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    const char* ConvertIDToString(uint64_t componentid);
    bool IsComponentOperational(uint64_t componentid);
    uint32_t GetNumAllFactionShips(const char* factionid);
    uint32_t GetAllFactionShips(UniverseID* result, uint32_t resultlen, const char* factionid);
    uint32_t GetNumAllFactionStations(const char* factionid);
    uint32_t GetAllFactionStations(UniverseID* result, uint32_t resultlen, const char* factionid);
]]

local DEBUG = false

local function debugLog(msg)
    if DEBUG then
        DebugError("[GT-MK2-WX] " .. tostring(msg))
    end
end

local function legField(leg, key)
    if leg == nil then
        return nil
    end
    local v = leg[key]
    if v ~= nil then
        return v
    end
    return leg["$" .. key]
end

local function toId64(value)
    if value == nil then
        return 0
    end
    if type(value) == "number" then
        return value
    end
    return ConvertStringTo64Bit(tostring(value))
end

local function componentIdCode(componentId)
    if componentId == nil or componentId == 0 then
        return nil
    end
    local ok, code = pcall(function()
        return GetComponentData(componentId, "idcode")
    end)
    if ok and code and code ~= "" then
        return tostring(code)
    end
    return nil
end

local function resolveByIdCode(idcode, listFn, countFn)
    if idcode == nil or idcode == "" then
        return 0
    end
    local code = tostring(idcode)
    local count = countFn("player")
    if not count or count <= 0 then
        return 0
    end
    local ids = ffi.new("UniverseID[?]", count)
    local found = listFn(ids, count, "player")
    for i = 0, found - 1 do
        local candidate = ids[i]
        if candidate and candidate ~= 0 then
            local candidateCode = componentIdCode(candidate)
            if candidateCode == code then
                return candidate
            end
        end
    end
    return 0
end

local function resolveShipId(shipRef, shipIdCode)
    if shipRef ~= nil then
        local id = toId64(shipRef)
        if id ~= 0 and componentIdCode(id) then
            return id
        end
    end
    if shipIdCode then
        local id = resolveByIdCode(shipIdCode, C.GetAllFactionShips, C.GetNumAllFactionShips)
        if id ~= 0 then
            return id
        end
    end
    return 0
end

local function resolveStationId(leg)
    local stationRef = legField(leg, "Station")
    if stationRef ~= nil then
        local id = toId64(stationRef)
        if id ~= 0 and componentIdCode(id) then
            return id
        end
    end
    local stationCode = legField(leg, "StationId")
    if stationCode then
        local id = resolveByIdCode(stationCode, C.GetAllFactionStations, C.GetNumAllFactionStations)
        if id ~= 0 then
            return id
        end
    end
    return 0
end

local function normalizeWareToken(value)
    if value == nil then
        return nil
    end
    local text = string.lower(tostring(value))
    text = string.gsub(text, "^ware%.", "")
    text = string.gsub(text, "%s+", "")
    return text
end

local function wareKey(ware)
    if ware == nil then
        return nil
    end
    if type(ware) == "string" then
        return normalizeWareToken(ware)
    end
    local ok, id = pcall(function()
        return ConvertIDToString(ware)
    end)
    if ok and id and id ~= "" then
        return normalizeWareToken(id)
    end
    return normalizeWareToken(tostring(ware))
end

local function collectWareKeys(ware)
    local keys = {}
    local function add(value)
        local token = normalizeWareToken(value)
        if token and token ~= "" then
            keys[token] = true
        end
    end

    if ware == nil then
        return keys
    end

    add(wareKey(ware))
    if type(ware) == "string" then
        add(ware)
    else
        local ok, id = pcall(function()
            return ConvertIDToString(ware)
        end)
        if ok then
            add(id)
        end
    end

    pcall(function()
        add(GetWareData(ware, "name"))
    end)

    return keys
end

local function legsMatchWare(tradeData, reqWare)
    if tradeData == nil or tradeData.ware == nil or reqWare == nil then
        return false
    end
    if tradeData.ware == reqWare then
        return true
    end
    local reqKeys = collectWareKeys(reqWare)
    local offerKeys = collectWareKeys(tradeData.ware)
    for key, _ in pairs(reqKeys) do
        if offerKeys[key] then
            return true
        end
    end
    return false
end

local function collectLegs(legs)
    local items = {}
    if type(legs) ~= "table" then
        return items
    end
    for i = 1, #legs do
        if legs[i] then
            table.insert(items, legs[i])
        end
    end
    if #items == 0 then
        for _, leg in pairs(legs) do
            if type(leg) == "table" then
                table.insert(items, leg)
            end
        end
    end
    return items
end

local function prepareVirtualCargo(shipId, stationId)
    if shipId ~= 0 then
        local numTradeComputerTrades = 0
        pcall(function()
            numTradeComputerTrades = tonumber(C.GetNumTradeComputerOrders(shipId)) or 0
        end)
        SetVirtualCargoMode(shipId, true, numTradeComputerTrades > 0 and numTradeComputerTrades or -1)
    end
    if stationId ~= 0 then
        local operational = true
        pcall(function()
            operational = C.IsComponentOperational(stationId)
        end)
        if operational then
            SetVirtualCargoMode(stationId, true, -1)
        end
    end
end

local function offerMatchesDirection(tradeData, wantPickup)
    if wantPickup then
        return tradeData.isselloffer == true
    end
    return tradeData.isbuyoffer == true
end

local function canQueueOffer(tradeData, shipId, amount)
    if tradeData == nil or tradeData.id == nil then
        return false
    end
    local minAmount = tonumber(tradeData.minamount) or 1
    local queueAmount = tonumber(amount) or 0
    if queueAmount < minAmount then
        return false
    end
    local ok, canTrade = pcall(function()
        return CanTradeWith(tradeData.id, shipId, minAmount)
    end)
    if ok then
        return canTrade
    end
    return true
end

local function resolveWareExchangeLeg(shipId, leg)
    local stationId = resolveStationId(leg)
    local amount = tonumber(legField(leg, "Amount")) or 0
    local reqWare = legField(leg, "Ware") or legField(leg, "WareName")
    local direction = legField(leg, "Direction")
    if shipId == 0 or stationId == 0 or amount <= 0 then
        return nil, "invalid leg (ship=" .. tostring(shipId)
            .. " station=" .. tostring(stationId)
            .. " amount=" .. tostring(amount)
            .. " dir=" .. tostring(direction)
            .. " stationId=" .. tostring(legField(leg, "StationId")) .. ")"
    end

    prepareVirtualCargo(shipId, stationId)

    local offers = GetWareExchangeTradeList(shipId, stationId) or {}
    local wantPickup = (direction == "pickup")
    local offerCount = 0
    local wareHits = 0
    local bestId = nil

    for _, tradeData in pairs(offers) do
        offerCount = offerCount + 1
        if legsMatchWare(tradeData, reqWare) then
            wareHits = wareHits + 1
            if offerMatchesDirection(tradeData, wantPickup) and canQueueOffer(tradeData, shipId, amount) then
                return tradeData.id, nil
            end
            if bestId == nil and canQueueOffer(tradeData, shipId, amount) then
                bestId = tradeData.id
            end
        end
    end

    if bestId ~= nil then
        debugLog("direction fallback used for " .. tostring(wareKey(reqWare)) .. " at station " .. tostring(stationId))
        return bestId, nil
    end

    return nil, "no ware exchange match for " .. tostring(wareKey(reqWare))
        .. " (offers=" .. tostring(offerCount) .. ", wareHits=" .. tostring(wareHits) .. ")"
end

local function queueResolvedLeg(shipId, offerId, amount)
    AddTradeToShipQueue(ConvertStringToLuaID(tostring(offerId)), shipId, amount, false)
end

local function writeResult(playerId, result)
    SetNPCBlackboard(playerId, "$GT_MK2_WareExchangeResult", result)
end

RegisterEvent("gt.mk2QueueWareExchange", function(_, requestId)
    local playerId = ConvertStringTo64Bit(tostring(C.GetPlayerID()))
    local request = GetNPCBlackboard(playerId, "$GT_MK2_WareExchangeRequest")
    local result = {
        RequestId = requestId,
        Success = false,
        Queued = 0,
        Error = "missing request",
        QueueLegs = {},
    }

    if type(request) ~= "table" then
        writeResult(playerId, result)
        return
    end

    local reqId = request.RequestId or request["$RequestId"]
    if reqId ~= requestId then
        result.Error = "request id mismatch"
        writeResult(playerId, result)
        return
    end

    local shipId = resolveShipId(request.Ship or request["$Ship"], request.ShipIdCode or request["$ShipIdCode"])
    if shipId == 0 then
        result.Error = "invalid ship"
        writeResult(playerId, result)
        SignalObject(shipId, "gt_mk2_ware_exchange_done", requestId)
        return
    end

    local legs = collectLegs(request.Legs or request["$Legs"])
    if #legs == 0 then
        result.Error = "missing legs"
        writeResult(playerId, result)
        SignalObject(shipId, "gt_mk2_ware_exchange_done", requestId)
        return
    end

    local pickups = {}
    local delivers = {}
    for _, leg in ipairs(legs) do
        local direction = legField(leg, "Direction")
        if direction == "pickup" then
            table.insert(pickups, leg)
        elseif direction == "deliver" then
            table.insert(delivers, leg)
        end
    end

    local queueLegs = {}
    local function resolveAndQueueBatch(batch)
        for _, leg in ipairs(batch) do
            local offerId, err = resolveWareExchangeLeg(shipId, leg)
            if not offerId then
                return err or "resolve failed"
            end
            local amount = tonumber(legField(leg, "Amount")) or 0
            queueResolvedLeg(shipId, offerId, amount)
            table.insert(queueLegs, {
                Direction = legField(leg, "Direction"),
                Amount = amount,
                TradeOffer = offerId,
            })
        end
        return nil
    end

    local err = resolveAndQueueBatch(pickups)
    if err then
        result.Error = err
        writeResult(playerId, result)
        SignalObject(shipId, "gt_mk2_ware_exchange_done", requestId)
        debugLog(result.Error)
        return
    end

    err = resolveAndQueueBatch(delivers)
    if err then
        result.Error = err
        writeResult(playerId, result)
        SignalObject(shipId, "gt_mk2_ware_exchange_done", requestId)
        debugLog(result.Error)
        return
    end

    result.Success = true
    result.Queued = #queueLegs
    result.Error = ""
    result.QueueLegs = queueLegs
    writeResult(playerId, result)
    SignalObject(shipId, "gt_mk2_ware_exchange_done", requestId)
    debugLog("queued " .. tostring(#queueLegs) .. " ware-exchange legs for " .. tostring(requestId))
end)
-- MK3 per-ship faction blacklist (test UI)
-- Opens from interact menu action and lets player toggle dynamic faction entries.

local ffi = require("ffi")
local C = ffi.C

ffi.cdef[[
    typedef uint64_t UniverseID;
    UniverseID GetPlayerID(void);
]]

local menu = Helper.getMenu("MapMenu")
if not menu then
    DebugError("[GT MK3 FactionBlacklist] MapMenu not found - UI disabled")
    return
end

if not GT_UI then
    DebugError("[GT MK3 FactionBlacklist] GT_UI library not loaded - UI disabled")
    return
end

local state = {
    shipName = "Unknown",
    shipCode = "UNK",
    rows = {},
}

local function readBlackboard()
    local playerId = ConvertStringTo64Bit(tostring(C.GetPlayerID()))
    local data = GetNPCBlackboard(playerId, "$GT_MK3FBL_Data") or ""
    state.shipName = GetNPCBlackboard(playerId, "$GT_MK3FBL_ShipName") or "Unknown"
    state.shipCode = GetNPCBlackboard(playerId, "$GT_MK3FBL_ShipCode") or "UNK"
    state.rows = {}

    local entries = GT_UI.split(data, "@@")
    for _, entry in ipairs(entries) do
        if entry ~= "" then
            local fields = GT_UI.split(entry, "||")
            if #fields >= 3 then
                local idx = tonumber(fields[1]) or 0
                local name = tostring(fields[2] or "Unknown Faction")
                local selected = tostring(fields[3] or "0") == "1"
                if idx > 0 then
                    table.insert(state.rows, {
                        index = idx,
                        name = name,
                        selected = selected,
                    })
                end
            end
        end
    end
end

local function createFrame()
    local contextLayer = 2
    Helper.removeAllWidgetScripts(menu, contextLayer)

    local width = math.min(Helper.viewWidth * 0.62, Helper.scaleX(950))
    local height = math.min(Helper.viewHeight * 0.75, Helper.scaleY(860))
    local xpos = (Helper.viewWidth - width) / 2
    local ypos = (Helper.viewHeight - height) / 2

    menu.contextMenuMode = "gt_mk3_faction_blacklist"
    menu.contextMenuData = {
        xoffset = xpos,
        yoffset = ypos,
        width = width,
    }

    menu.contextFrame = Helper.createFrameHandle(menu, {
        x = xpos,
        y = ypos,
        width = width,
        height = height,
        layer = contextLayer,
        standardButtons = { close = true },
        closeOnUnhandledClick = false,
    })
    menu.contextFrame:setBackground("solid", { color = Color["frame_background_semitransparent"] })

    local innerWidth = width - 2 * Helper.borderSize
    local titleTable = menu.contextFrame:addTable(1, {
        x = Helper.borderSize,
        y = Helper.borderSize,
        width = innerWidth,
        reserveScrollBar = false,
        highlightMode = "off",
    })
    local trow = titleTable:addRow(nil, { fixed = true, bgColor = GT_UI.COLORS.headerBg })
    trow[1]:createText("MK3 Faction Blacklist - " .. tostring(state.shipName) .. " (" .. tostring(state.shipCode) .. ")", {
        halign = "center",
        font = Helper.headerRow1Font,
        fontsize = Helper.headerRow1FontSize,
    })

    local headerY = Helper.borderSize + Helper.headerRow1FontSize + 16
    local listTable = GT_UI.createScrollTable(menu.contextFrame, 3, {
        x = Helper.borderSize,
        y = headerY,
        width = innerWidth,
        maxVisibleHeight = height - headerY - Helper.scaleY(16),
        tabOrder = 1,
        highlightMode = "off",
    })
    -- Keep last column flexible to avoid reserveScrollBar/fixed-width issues.
    GT_UI.setColPercents(listTable, { 8, 62 })

    GT_UI.addHeaderRow(listTable, {
        { text = "#", halign = "center" },
        "Faction",
        { text = "State", halign = "center" },
    })

    if #state.rows == 0 then
        GT_UI.addEmptyRow(listTable, "No active factions available.", 3)
    end

    for _, row in ipairs(state.rows) do
        local r = listTable:addRow(true, { bgColor = GT_UI.COLORS.tabInactiveBg })
        r[1]:createText(tostring(row.index), { halign = "center" })
        r[2]:createText(row.name, { halign = "left" })
        local buttonText = row.selected and "Blocked" or "Allowed"
        local buttonColor = row.selected and GT_UI.COLORS.textNegative or GT_UI.COLORS.textPositive
        r[3]:createButton({ active = true }):setText(buttonText, { halign = "center", color = buttonColor })
        r[3].handlers.onClick = function()
            AddUITriggeredEvent("GT_MK3FactionBlacklist", "ToggleFaction", { index = row.index })
        end
    end

    menu.contextFrame:display()
end

local origCreateCtx = menu.createContextFrame
menu.createContextFrame = function(width, height, xoffset, yoffset, noborder, startanimation, ...)
    if menu.contextMenuMode == "gt_mk3_faction_blacklist" then
        return menu.contextFrame
    end
    if origCreateCtx then
        return origCreateCtx(width, height, xoffset, yoffset, noborder, startanimation, ...)
    end
end

local origRefreshCtx = menu.refreshContextFrame
menu.refreshContextFrame = function(setrow, setcol, noborder, ...)
    if menu.contextMenuMode == "gt_mk3_faction_blacklist" then
        if menu.contextFrame then
            menu.contextFrame:display()
        end
        return
    end
    if origRefreshCtx then
        origRefreshCtx(setrow, setcol, noborder, ...)
    end
end

RegisterEvent("gt.openMK3FactionBlacklist", function()
    readBlackboard()
    createFrame()
end)

RegisterEvent("gt.refreshMK3FactionBlacklist", function()
    if menu.contextMenuMode == "gt_mk3_faction_blacklist" then
        readBlackboard()
        createFrame()
    end
end)
--[[
GalaxyTrader MK3 - Equipment Mod Removal Lua Module
Handles removal of GT-installed modifications using C API
]]

local GT_ModRemoval = {}

-- Debug logging wrapper
-- Note: X4 Lua only has DebugError and DebugWarning, not DebugLog
local function logDebug(message, level)
    level = level or "INFO"
    local prefix = "[GT-Mods-Lua] "
    if level == "ERROR" then
        DebugError(prefix .. message)
    elseif level == "WARNING" then
        -- Some runtimes don't expose DebugWarning; use DebugError as safe fallback.
        DebugError(prefix .. message)
    else
        -- X4 Lua has no reliable normal debug logger for extension scripts.
        -- Route INFO through DebugError as well so module load and event flow stay visible.
        DebugError(prefix .. message)
    end
end

-- FFI setup for C API access
local ffi = require("ffi")
local C = ffi.C

-- FFI definitions for C API mod removal functions
ffi.cdef[[
    typedef uint64_t UniverseID;
    typedef struct {
        const char* Name;
        const char* RawName;
        const char* Ware;
        uint32_t Quality;
        const char* PropertyType;
        float ForwardThrustFactor;
        float StrafeAccFactor;
        float StrafeThrustFactor;
        float RotationThrustFactor;
        float BoostAccFactor;
        float BoostThrustFactor;
        float BoostDurationFactor;
        float BoostAttackTimeFactor;
        float BoostReleaseTimeFactor;
        float BoostChargeTimeFactor;
        float BoostRechargeTimeFactor;
        float TravelThrustFactor;
        float TravelStartThrustFactor;
        float TravelAttackTimeFactor;
        float TravelReleaseTimeFactor;
        float TravelChargeTimeFactor;
    } UIEngineMod2;
    typedef struct {
        const char* Name;
        const char* RawName;
        const char* Ware;
        uint32_t Quality;
        const char* PropertyType;
        float MassFactor;
        float DragFactor;
        float MaxHullFactor;
        float RadarRangeFactor;
        uint32_t AddedUnitCapacity;
        uint32_t AddedMissileCapacity;
        uint32_t AddedCountermeasureCapacity;
        uint32_t AddedDeployableCapacity;
        float RadarCloakFactor;
        float RegionDamageProtection;
        float HideCargoChance;
    } UIShipMod2;
    void DismantleShipMod(UniverseID shipid);
    void DismantleEngineMod(UniverseID objectid);
    void DismantleShieldMod(UniverseID defensibleid, UniverseID contextid, const char* group);
    void DismantleWeaponMod(UniverseID weaponid);
    void DismantleThrusterMod(UniverseID objectid);
    bool InstallEngineMod(UniverseID objectid, const char* wareid);
    bool InstallShipMod(UniverseID shipid, const char* wareid);
    bool InstallShieldMod(UniverseID defensibleid, UniverseID contextid, const char* group, const char* wareid);
    bool GetInstalledEngineMod2(UniverseID objectid, UIEngineMod2* enginemod);
    bool GetInstalledShipMod2(UniverseID shipid, UIShipMod2* shipmod);
]]

-- Convert a serialized UniverseID string to a 64-bit universe ID.
local function ConvertStringTo64Bit(str)
    if not str or str == "" then
        logDebug("ERROR: Empty string passed to ConvertStringTo64Bit", "ERROR")
        return 0
    end

    local num
    if type(str) == "string" and string.sub(str, 1, 2) == "0x" then
        num = tonumber(string.sub(str, 3), 16)
    else
        num = tonumber(str)
    end

    if not num then
        logDebug(string.format("ERROR: Failed to convert '%s' to number", tostring(str)), "ERROR")
        return 0
    end
    return ffi.cast("uint64_t", num)
end

-- Split pipe-separated parameters (format: "type|shipId|componentId|contextId|group")
local function SplitParams(params, sep)
    sep = sep or "|"
    local result = {}
    local pattern = string.format("([^%s]+)", sep)
    for match in string.gmatch(params, pattern) do
        table.insert(result, match)
    end
    return result
end

local function ToUniverseID(value)
    if value == nil or value == 0 or value == "0" then
        return ffi.cast("uint64_t", 0)
    end

    local valueType = type(value)
    if valueType == "string" or valueType == "number" then
        return ConvertStringTo64Bit(tostring(value))
    end

    local ok, converted = pcall(ConvertIDTo64Bit, value)
    if ok and converted and converted ~= 0 then
        return converted
    end

    logDebug(string.format("ERROR: Failed to convert component payload to UniverseID: %s", tostring(value)), "ERROR")
    return ffi.cast("uint64_t", 0)
end

local function ParseModPayload(params)
    if type(params) == "table" then
        return {
            type = params.type or params.modType or params.kind,
            component = params.component or params.ship or params.object,
            shipIdCode = params.shipIdCode or params.idcode or "UNKNOWN",
            wareId = params.wareId or params.ware or params.mod,
            reason = params.reason or "manual",
            group = params.group,
            componentId = params.componentId,
            contextId = params.contextId,
        }
    end

    local tPackets = SplitParams(params, "|")
    local isActionPayload = tPackets[1] == "ship" or tPackets[1] == "engine" or tPackets[1] == "shield" or tPackets[1] == "weapon" or tPackets[1] == "thruster"
    local hasExtendedFields = isActionPayload and (#tPackets >= 6)
    return {
        type = isActionPayload and tPackets[1] or nil,
        component = isActionPayload and tPackets[2] or tPackets[1],
        shipIdCode = isActionPayload and (hasExtendedFields and tPackets[3] or tPackets[2]) or tPackets[2],
        wareId = isActionPayload and (hasExtendedFields and tPackets[6] or tPackets[3]) or nil,
        reason = isActionPayload and nil or tPackets[3],
        componentId = isActionPayload and tPackets[4] or nil,
        contextId = isActionPayload and tPackets[5] or nil,
        group = isActionPayload and tPackets[6] or nil,
        packets = tPackets,
    }
end

local function SafeCString(value, defaultValue)
    defaultValue = defaultValue or "none"
    if value == nil then
        return defaultValue
    end
    local ok, text = pcall(ffi.string, value)
    if ok and text and text ~= "" then
        return text
    end
    return defaultValue
end

local function IsGTShipModWareId(wareId)
    return wareId == "mod_ship_gt_level1"
        or wareId == "mod_ship_gt_level2"
        or wareId == "mod_ship_gt_level3"
        or wareId == "mod_penalty_ship_light"
        or wareId == "mod_penalty_ship_moderate"
        or wareId == "mod_penalty_ship_severe"
        or wareId == "mod_penalty_light"
        or wareId == "mod_penalty_moderate"
        or wareId == "mod_penalty_severe"
end

local function IsGTEngineModWareId(wareId)
    return wareId == "mod_engine_gt_level1"
        or wareId == "mod_engine_gt_level2"
        or wareId == "mod_engine_gt_level3"
        or wareId == "mod_penalty_engine_light"
        or wareId == "mod_penalty_engine_moderate"
        or wareId == "mod_penalty_engine_severe"
        or wareId == "mod_penalty_light"
        or wareId == "mod_penalty_moderate"
        or wareId == "mod_penalty_severe"
end

local function GT_DismantleDetectedGTMods(_, params)
    if not params then
        logDebug("ERROR: GT_Mods.DismantleDetected called with nil params", "ERROR")
        return
    end

    local payload = ParseModPayload(params)
    if not payload.component then
        logDebug(string.format("ERROR: Invalid GT_Mods.DismantleDetected params format: %s", tostring(params)), "ERROR")
        return
    end

    local shipIdCode = payload.shipIdCode or "UNKNOWN"
    local reason = payload.reason or "manual"
    local shipId = ToUniverseID(payload.component)

    local shipBuf = ffi.new("UIShipMod2")
    local engineBuf = ffi.new("UIEngineMod2")
    local hasShip = C.GetInstalledShipMod2(shipId, shipBuf)
    local hasEngine = C.GetInstalledEngineMod2(shipId, engineBuf)
    local shipWare = hasShip and SafeCString(shipBuf.Ware) or "none"
    local engineWare = hasEngine and SafeCString(engineBuf.Ware) or "none"

    local removedShip = false
    local removedEngine = false

    if hasShip and IsGTShipModWareId(shipWare) then
        C.DismantleShipMod(shipId)
        removedShip = true
    end
    if hasEngine and IsGTEngineModWareId(engineWare) then
        C.DismantleEngineMod(shipId)
        removedEngine = true
    end

    logDebug(string.format("Detected GT mod cleanup ship=%s reason=%s removedShip=%s removedEngine=%s shipWare=%s engineWare=%s", shipIdCode, reason, tostring(removedShip), tostring(removedEngine), shipWare, engineWare), "WARNING")
end

-- Remove modification from ship
local function GT_DismantleMod(_, params)
    if not params then
        logDebug("ERROR: GT_Mods.Dismantle called with nil params", "ERROR")
        return
    end
    
    local payload = ParseModPayload(params)
    if not payload.type or not payload.component then
        logDebug(string.format("ERROR: Invalid params format: %s", tostring(params)), "ERROR")
        return
    end
    
    local type = payload.type
    local shipIdCode = payload.shipIdCode or "UNKNOWN"
    local shipId = ToUniverseID(payload.component)
    
    if type == "ship" then
        local shipBuf = ffi.new("UIShipMod2")
        local hasShip = C.GetInstalledShipMod2(shipId, shipBuf)
        local shipWare = hasShip and SafeCString(shipBuf.Ware) or "none"
        if hasShip and IsGTShipModWareId(shipWare) then
            C.DismantleShipMod(shipId)
            -- logDebug(string.format("Dismantled ship mod from %s ware=%s", shipIdCode, shipWare), "WARNING")
        end
    elseif type == "engine" then
        local engineBuf = ffi.new("UIEngineMod2")
        local hasEngine = C.GetInstalledEngineMod2(shipId, engineBuf)
        local engineWare = hasEngine and SafeCString(engineBuf.Ware) or "none"
        if hasEngine and IsGTEngineModWareId(engineWare) then
            C.DismantleEngineMod(shipId)
            -- logDebug(string.format("Dismantled engine mod from %s ware=%s", shipIdCode, engineWare), "WARNING")
        end
    elseif type == "shield" then
        local contextId = shipId
        local group = (payload.group and payload.group ~= "null") and payload.group or nil
        
        if group then
            C.DismantleShieldMod(shipId, contextId, group)
        else
            C.DismantleShieldMod(shipId, contextId, "")
        end
    elseif type == "weapon" then
        local componentId = nil
        if payload.componentId and tostring(payload.componentId) ~= "0" then
            componentId = ToUniverseID(payload.componentId)
        end
        
        if componentId then
            C.DismantleWeaponMod(componentId)
        else
            logDebug(string.format("WARNING: No component ID provided for weapon mod - ship: %s", shipIdCode), "WARNING")
        end
    elseif type == "thruster" then
        C.DismantleThrusterMod(shipId)
    else
        logDebug(string.format("ERROR: Unknown mod type: %s", type), "ERROR")
    end
end

-- Install modification on ship
local function GT_InstallMod(_, params)
    if not params then
        logDebug("ERROR: GT_Mods.Install called with nil params", "ERROR")
        return
    end

    local payload = ParseModPayload(params)
    if not payload.type or not payload.component or not payload.wareId then
        logDebug(string.format("ERROR: Invalid GT_Mods.Install params format: %s", tostring(params)), "ERROR")
        return
    end

    local type = payload.type
    local shipIdStr = payload.shipIdCode or "UNKNOWN"
    local shipId = ToUniverseID(payload.component)
    local wareId = payload.wareId

    -- logDebug(string.format("Install request type=%s shipId=%s ware=%s", tostring(type), tostring(shipIdStr), tostring(wareId)), "WARNING")

    if type == "ship" then
        local ok, success = pcall(C.InstallShipMod, shipId, wareId)
        if not ok then
            logDebug(string.format("InstallShipMod raised error for ship ID %s ware %s: %s", shipIdStr, wareId, tostring(success)), "ERROR")
            return
        end
        if not success then
            logDebug(string.format("Failed to install ship mod (%s) on ship ID: %s", wareId, shipIdStr), "ERROR")
        else
            local shipBuf = ffi.new("UIShipMod2")
            local hasShip = C.GetInstalledShipMod2(shipId, shipBuf)
            local installedWare = hasShip and SafeCString(shipBuf.Ware) or "none"
            -- logDebug(string.format("InstallShipMod observed ship ID %s requested=%s observed=%s hasShip=%s", shipIdStr, wareId, installedWare, tostring(hasShip)), "WARNING")
            if installedWare ~= wareId then
                logDebug(string.format("Ship mod install verification mismatch on ship ID %s: requested=%s, observed=%s", shipIdStr, wareId, installedWare), "WARNING")
            end
        end
    elseif type == "engine" or type == "thruster" then
        local ok, success = pcall(C.InstallEngineMod, shipId, wareId)
        if not ok then
            logDebug(string.format("InstallEngineMod raised error for ship ID %s ware %s: %s", shipIdStr, wareId, tostring(success)), "ERROR")
            return
        end
        if not success then
            logDebug(string.format("Failed to install engine mod (%s) on ship ID: %s", wareId, shipIdStr), "ERROR")
        else
            local engineBuf = ffi.new("UIEngineMod2")
            local hasEngine = C.GetInstalledEngineMod2(shipId, engineBuf)
            local installedWare = hasEngine and SafeCString(engineBuf.Ware) or "none"
            -- logDebug(string.format("InstallEngineMod observed ship ID %s requested=%s observed=%s hasEngine=%s", shipIdStr, wareId, installedWare, tostring(hasEngine)), "WARNING")
            if installedWare ~= wareId then
                logDebug(string.format("Engine mod install verification mismatch on ship ID %s: requested=%s, observed=%s", shipIdStr, wareId, installedWare), "WARNING")
            end
        end
    else
        logDebug(string.format("ERROR: Unknown mod type for installation: %s", type), "ERROR")
    end
end

-- Initialize module
local function init()
    logDebug("================================================================================")
    logDebug("GalaxyTrader MK3 - Mod Removal Lua Module Loading...")
    logDebug("================================================================================")
    
    if not ffi then
        logDebug("ERROR: FFI not available!", "ERROR")
        return false
    end
    
    local success1 = pcall(RegisterEvent, "GT_Mods.Dismantle", GT_DismantleMod)
    if success1 then
        logDebug("Registered event: GT_Mods.Dismantle")
    else
        logDebug("Failed to register event: GT_Mods.Dismantle", "ERROR")
        return false
    end
    
    local success2 = pcall(RegisterEvent, "GT_Mods.Install", GT_InstallMod)
    if success2 then
        logDebug("Registered event: GT_Mods.Install")
    else
        logDebug("Failed to register event: GT_Mods.Install", "ERROR")
        return false
    end

    local success3 = pcall(RegisterEvent, "GT_Mods.DismantleDetected", GT_DismantleDetectedGTMods)
    if success3 then
        logDebug("Registered event: GT_Mods.DismantleDetected")
    else
        logDebug("Failed to register event: GT_Mods.DismantleDetected", "ERROR")
        return false
    end
    
    logDebug("================================================================================")
    logDebug("Mod Removal Lua Module loaded successfully!")
    logDebug("================================================================================")
    
    return true
end

-- Initialize module immediately
init()

-- Export module
return GT_ModRemoval

-- GalaxyTrader MK3 Order Monitor
-- Batched order change detection (1 ship every 5 frames)

local L = {}

L.CHECK_INTERVAL = 5
L.frameCounter = 0
L.currentShipIndex = 0
L.shipList = {}
L.previousOrders = {}
L.previousPilots = {}
L.previousCommanders = {}
L.cleanupTriggered = {}
L.isMonitoring = false

-- FFI setup for order checking
local ffi = require("ffi")
local C = ffi.C
ffi.cdef[[
    typedef uint64_t UniverseID;
    bool IsComponentClass(UniverseID componentid, const char* classname);
    const char* GetObjectIDCode(UniverseID objectid);
    uint64_t ConvertStringTo64Bit(const char* idcode);
    typedef struct {
        size_t queueidx;
        const char* state;
        const char* statename;
        const char* orderdef;
        size_t actualparams;
        bool enabled;
        bool isinfinite;
        bool issyncpointreached;
        bool istemporder;
    } Order;
    bool GetDefaultOrder(Order* result, UniverseID controllableid);
    uint32_t GetNumSubordinatesOfGroup(UniverseID commanderid, int group);
]]

function Init()
    RegisterEvent("GT_OrderMonitor.UpdateShipList", L.UpdateShipList)
    RegisterEvent("GT_OrderMonitor.Start", L.StartMonitoring)
    RegisterEvent("GT_OrderMonitor.Stop", L.StopMonitoring)
    SetScript("onUpdate", L.OnUpdate)
    AddUITriggeredEvent("GT_OrderMonitor", "Ready", {})
end

function onUpdate()
    L.OnUpdate()
end

function L.UpdateShipList(eventName, shipListString)
    if not shipListString or shipListString == "" then
        L.shipList = {}
        return
    end
    
    L.shipList = {}
    if type(shipListString) == "string" then
        for shipPair in string.gmatch(shipListString, "([^,]+)") do
            shipPair = shipPair:match("^%s*(.-)%s*$")
            if shipPair and shipPair ~= "" then
                local colonPos = string.find(shipPair, ":")
                local shipIDStr = colonPos and string.sub(shipPair, 1, colonPos - 1) or shipPair
                -- Fix: tonumber("0x1234", 16) returns nil - strip "0x" before calling with base, or use auto-detect
                local num
                if string.sub(shipIDStr, 1, 2) == "0x" then
                    -- Strip "0x" prefix before calling tonumber with base 16
                    num = tonumber(string.sub(shipIDStr, 3), 16)
                else
                    num = tonumber(shipIDStr)
                end
                if num and num ~= 0 then
                    table.insert(L.shipList, num)
                end
            end
        end
    end
    
    L.currentShipIndex = 0
    L.previousOrders = {}
    L.previousPilots = {}
    L.previousCommanders = {}
    L.cleanupTriggered = {}
    
    if not L.isMonitoring then
        L.isMonitoring = true
    end
    
    for _, ship in ipairs(L.shipList) do
        local orderBuf = ffi.new("Order")
        if C.GetDefaultOrder(orderBuf, ship) and orderBuf.orderdef then
            -- Check for NULL pointer before calling ffi.string (prevents crash)
            local orderdef_ptr = orderBuf.orderdef
            L.previousOrders[ship] = (orderdef_ptr ~= nil) and ffi.string(orderdef_ptr) or "NONE"
        else
            L.previousOrders[ship] = "NONE"
        end
        
        local pilot = GetComponentData(ship, "assignedpilot")
        L.previousPilots[ship] = pilot and tostring(pilot) or "NONE"
        
        -- Some UniverseIDs can exist in the list but not be "controllable" (e.g. stale IDs / non-ship components).
        -- Calling GetCommander() on those throws engine errors, so guard it like vanilla UI code does elsewhere.
        local commander = nil
        if C.IsComponentClass(ship, "controllable") then
            commander = GetCommander(ship)
        end
        if commander then
            local commanderNum = ConvertIDTo64Bit(commander)
            L.previousCommanders[ship] = (commanderNum and commanderNum ~= 0) and tostring(commanderNum) or "NONE"
        else
            L.previousCommanders[ship] = "NONE"
        end
    end
end

function L.StartMonitoring()
    L.frameCounter = 0
    L.currentShipIndex = 0
    L.isMonitoring = true
end

function L.StopMonitoring()
    L.shipList = {}
    L.currentShipIndex = 0
    L.previousOrders = {}
    L.previousPilots = {}
    L.previousCommanders = {}
    L.cleanupTriggered = {}
    L.isMonitoring = false
end

function L.OnUpdate()
    if #L.shipList == 0 or not L.isMonitoring then
        return
    end
    
    L.frameCounter = L.frameCounter + 1
    if L.frameCounter < L.CHECK_INTERVAL then
        return
    end
    L.frameCounter = 0
    
    L.currentShipIndex = L.currentShipIndex + 1
    if L.currentShipIndex > #L.shipList then
        L.currentShipIndex = 1
    end
    
    local ship = L.shipList[L.currentShipIndex]
    if not ship or ship == 0 then
        return
    end
    
    -- Check for NULL pointer before calling ffi.string (prevents crash)
    local idcode_ptr = C.GetObjectIDCode(ship)
    local shipIDCode = (idcode_ptr ~= nil) and ffi.string(idcode_ptr) or "UNKNOWN"
    
    if not C.IsComponentClass(ship, "ship") then
        return
    end
    
    local orderBuf = ffi.new("Order")
    local currentOrderID = "NONE"
    if C.GetDefaultOrder(orderBuf, ship) and orderBuf.orderdef then
        -- Check for NULL pointer before calling ffi.string (prevents crash)
        local orderdef_ptr = orderBuf.orderdef
        currentOrderID = (orderdef_ptr ~= nil) and ffi.string(orderdef_ptr) or "NONE"
    end
    
    local currentPilot = GetComponentData(ship, "assignedpilot")
    local currentPilotID = currentPilot and tostring(currentPilot) or "NONE"
    
    -- Guard against non-controllable / stale IDs to avoid engine spam:
    -- "[=ERROR=] ... GetCommander(): Component 'X' is not of class controllable"
    local currentCommander = nil
    if C.IsComponentClass(ship, "controllable") then
        currentCommander = GetCommander(ship)
    end
    local currentCommanderID = "NONE"
    local currentCommanderNum = nil
    
    if currentCommander then
        -- Convert userdata ID to number using ConvertIDTo64Bit (like vanilla code)
        currentCommanderNum = ConvertIDTo64Bit(currentCommander)
        if currentCommanderNum and currentCommanderNum ~= 0 then
            currentCommanderID = tostring(currentCommanderNum)
        end
    end
    
    local previousOrderID = L.previousOrders[ship] or "NONE"
    local previousPilotID = L.previousPilots[ship] or "NONE"
    local previousCommanderID = L.previousCommanders[ship] or "NONE"
    
    -- Check if ship was promoted to commander (had commander before, no commander now)
    local wasPromotedToCommander = false
    if previousCommanderID ~= "NONE" and currentCommanderID == "NONE" then
        -- Ship previously had a commander, now has none - might have been promoted
        -- Check if ship has subordinates (confirms it's a commander)
        local numSubordinates = 0
        for group = 1, 10 do
            local count = C.GetNumSubordinatesOfGroup(ship, group)
            if count and count > 0 then
                numSubordinates = numSubordinates + count
            end
        end
        if numSubordinates > 0 then
            wasPromotedToCommander = true
        end
    end
    
    if currentOrderID ~= previousOrderID then
        local wasGTOrder = (previousOrderID == "GalaxyTraderMK3" or previousOrderID == "GalaxyTraderMK2" or previousOrderID == "GalaxyTraderMK1" or previousOrderID == "GalaxyMiner")
        local isGTOrderNow = (currentOrderID == "GalaxyTraderMK3" or currentOrderID == "GalaxyTraderMK2" or currentOrderID == "GalaxyTraderMK1" or currentOrderID == "GalaxyMiner")
        if wasGTOrder and not isGTOrderNow then
            -- Only trigger cleanup if ship wasn't promoted to commander
            -- Newly promoted commanders might temporarily lose order while X4 assigns it
            if not wasPromotedToCommander then
                L.cleanupTriggered[ship] = true
                AddUITriggeredEvent("GT_OrderMonitor", "GTOrderRemoved", {
                    ship = shipIDCode,
                    oldOrder = previousOrderID,
                    newOrder = currentOrderID
                })
            end
        end
        L.previousOrders[ship] = currentOrderID
    end
    
    local hasGTOrder = false
    local commanderHasGTOrder = nil  -- nil = unknown, true = yes, false = no
    
    if currentOrderID == "GalaxyTraderMK3" or currentOrderID == "GalaxyTraderMK2" or currentOrderID == "GalaxyTraderMK1" or currentOrderID == "GalaxyMiner" then
        hasGTOrder = true
    elseif currentOrderID == "Assist" then
        -- Ship has Assist order - check commander's order
        if currentCommanderNum and currentCommanderNum ~= 0 then
            local commanderOrderBuf = ffi.new("Order")
            local getOrderSuccess = C.GetDefaultOrder(commanderOrderBuf, currentCommanderNum)
            if getOrderSuccess and commanderOrderBuf.orderdef then
                -- Check for NULL pointer before calling ffi.string (prevents crash)
                local orderdef_ptr = commanderOrderBuf.orderdef
                local commanderOrderID = (orderdef_ptr ~= nil) and ffi.string(orderdef_ptr) or nil
                if commanderOrderID == "GalaxyTraderMK3" or commanderOrderID == "GalaxyTraderMK2" or commanderOrderID == "GalaxyTraderMK1" or commanderOrderID == "GalaxyMiner" then
                    hasGTOrder = true
                    commanderHasGTOrder = true
                else
                    commanderHasGTOrder = false
                end
            end
            -- If GetDefaultOrder failed, commanderHasGTOrder stays nil (unknown)
        end
        -- If ship has Assist but we can't verify commander status, don't clean it up
        -- Only clean up if we can VERIFY commander doesn't have GT order
    end
    
    local shouldKeepShip = false
    if currentOrderID == "GalaxyTraderMK3" or currentOrderID == "GalaxyTraderMK2" or currentOrderID == "GalaxyTraderMK1" or currentOrderID == "GalaxyMiner" then
        -- Direct GT order - keep if has pilot
        shouldKeepShip = (currentPilotID ~= "NONE")
    elseif currentOrderID == "Assist" then
        -- Assist order - keep if commander has GT order AND has pilot
        -- If commander status unknown (nil), err on side of keeping ship
        if commanderHasGTOrder == true then
            shouldKeepShip = (currentPilotID ~= "NONE")
        elseif commanderHasGTOrder == false then
            -- Commander confirmed to NOT have GT order - can clean up
            shouldKeepShip = false
        else
            -- Commander status unknown - keep ship to avoid false positives
            shouldKeepShip = true
        end
    elseif wasPromotedToCommander then
        -- Ship was promoted to commander (had commander before, now has subordinates)
        -- Keep it even if it doesn't have GT order yet - X4 needs time to assign order
        -- This handles vanilla's automatic commander promotion when old commander destroyed
        shouldKeepShip = (currentPilotID ~= "NONE")
    end
    
    if not L.cleanupTriggered[ship] and not shouldKeepShip then
        L.cleanupTriggered[ship] = true
        if hasGTOrder and currentPilotID == "NONE" then
            AddUITriggeredEvent("GT_OrderMonitor", "MissingPilot", {
                ship = shipIDCode,
                order = currentOrderID,
                previousPilot = previousPilotID
            })
        else
            AddUITriggeredEvent("GT_OrderMonitor", "GTOrderRemoved", {
                ship = shipIDCode,
                oldOrder = previousOrderID or "UNKNOWN",
                newOrder = currentOrderID
            })
        end
    end
    
    L.previousPilots[ship] = currentPilotID
    L.previousCommanders[ship] = currentCommanderID
end

Init()
return L

-- Personal Management display-name override for GT pilots.
-- Uses the same identity-only PilotIdMap lookup as crew highlighting.

local MENU_NAME = "PlayerInfoMenu"

local function resolveMenu()
    if Helper and Helper.getMenu then
        local menu = Helper.getMenu(MENU_NAME)
        if menu then
            return menu
        end
    end
    if Menus then
        return Menus[MENU_NAME]
    end
    return nil
end

local function getPilotData()
    return Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.PilotData
end

local function isPilotRenamingEnabled()
    local pilotData = getPilotData()
    if not pilotData or not pilotData.settings then
        return false
    end
    return pilotData.settings.pilotRenamingEnabled == true
end

local function lookupTaggedName(personRef)
    if not isPilotRenamingEnabled() then
        return nil
    end

    local pilotData = getPilotData()
    if not pilotData or not pilotData.getGTPilotIdMap or not pilotData.lookupPilotIdMapTaggedName then
        return nil
    end

    local idMap = pilotData.getGTPilotIdMap()
    if not idMap then
        return nil
    end

    local tagged = pilotData.lookupPilotIdMapTaggedName(idMap, personRef)
    if tagged and tagged ~= "" then
        return tagged
    end

    -- Some UI ids stringify as "ID: <number>" in this menu.
    local raw = tostring(personRef)
    local extracted = string.match(raw, "ID:%s*(%d+)")
    if extracted then
        tagged = pilotData.lookupPilotIdMapTaggedName(idMap, extracted)
        if tagged and tagged ~= "" then
            return tagged
        end
    end

    return nil
end

local function applyPersonnelTaggedNames(menu)
    if not menu or menu.mode ~= "personnel" or not menu.empireData or not menu.empireData.filteredemployees then
        return
    end

    if not isPilotRenamingEnabled() then
        return
    end

    local curPage = tonumber(menu.personnelData and menu.personnelData.curPage) or 1
    if curPage < 1 then
        curPage = 1
    end

    -- Vanilla Personnel Management page size is 100 entries.
    local pageSize = 100
    local employees = menu.empireData.filteredemployees
    local startIndex = ((curPage - 1) * pageSize) + 1
    local endIndex = math.min(#employees, startIndex + pageSize - 1)
    local taggedById = {}

    for i = startIndex, endIndex do
        local employee = employees[i]
        if employee and employee.type == "person" and employee.id then
            local key = tostring(employee.id)
            local tagged = taggedById[key]
            if tagged == nil then
                tagged = lookupTaggedName(employee.id) or false
                taggedById[key] = tagged
            end
            if tagged then
                employee.name = tagged
            end
        end
    end

    if menu.personnelData and menu.personnelData.curEntry and menu.personnelData.curEntry.type == "person" and menu.personnelData.curEntry.id then
        local curKey = tostring(menu.personnelData.curEntry.id)
        local tagged = taggedById[curKey]
        if tagged == nil then
            tagged = lookupTaggedName(menu.personnelData.curEntry.id)
        elseif tagged == false then
            tagged = nil
        end
        if tagged then
            menu.personnelData.curEntry.name = tagged
        end
    end
end

local function install()
    local menu = resolveMenu()
    if not menu or menu.__gtPersonnelNameOverrideInstalled then
        return
    end

    if type(menu.getEmployeeList) == "function" then
        local original = menu.getEmployeeList
        menu.getEmployeeList = function(...)
            local result = original(...)
            applyPersonnelTaggedNames(menu)
            return result
        end
    end

    menu.__gtPersonnelNameOverrideInstalled = true
    DebugError("[GT Personnel Name Override] PlayerInfoMenu hook installed")
end

install()

if RegisterEvent then
    RegisterEvent("show" .. MENU_NAME, function()
        install()
    end)
    RegisterEvent("GT_PilotIdMap.Update", function()
        local menu = resolveMenu()
        if not menu then
            return
        end
        install()
        applyPersonnelTaggedNames(menu)
    end)
end

-- ==============================================================================
-- GalaxyTrader MK3 - Pilot Control Bridge
-- ==============================================================================
-- Purpose: Handle MD-Lua communication for pilot control actions
-- This module sends control commands from the UI to the MD scripts
-- ==============================================================================

local Mods = Mods or {}
Mods.GalaxyTrader = Mods.GalaxyTrader or {}
Mods.GalaxyTrader.PilotControl = Mods.GalaxyTrader.PilotControl or {}

-- Debug logging
local function debugLog(message)
    DebugError("[GT Pilot Control] " .. tostring(message))
end

-- ==============================================================================
-- ACTION SENDERS (UI MD)
-- ==============================================================================

-- Send ship to training
function Mods.GalaxyTrader.PilotControl.sendToTraining(shipId)
    debugLog("Sending ship to training: " .. tostring(shipId))
    
    -- Send training request to MD (shipId in param3)
    AddUITriggeredEvent("GT_PilotControl", "Training", tostring(shipId))
    
    debugLog("Training signal sent for ship: " .. tostring(shipId))
end

-- Deregister ship from GalaxyTrader system
function Mods.GalaxyTrader.PilotControl.deregisterShip(shipId)
    debugLog("Deregistering ship: " .. tostring(shipId))
    
    -- Send signal to MD
    local param = "deregister|" .. tostring(shipId)
    AddUITriggeredEvent("GT_PilotControl", "Action", param)
    
    debugLog("Deregister signal sent for ship: " .. tostring(shipId))
end

-- Force sell cargo
function Mods.GalaxyTrader.PilotControl.forceSellCargo(shipId)
    debugLog("Forcing cargo sale for ship: " .. tostring(shipId))
    
    -- Send signal to MD
    local param = "sellcargo|" .. tostring(shipId)
    AddUITriggeredEvent("GT_PilotControl", "Action", param)
    
    debugLog("Force sell cargo signal sent for ship: " .. tostring(shipId))
end

-- Send ship to repair
function Mods.GalaxyTrader.PilotControl.sendToRepair(shipId)
    debugLog("Sending ship to repair: " .. tostring(shipId))
    
    -- Send signal to MD
    local param = "repair|" .. tostring(shipId)
    AddUITriggeredEvent("GT_PilotControl", "Action", param)
    
    debugLog("Repair signal sent for ship: " .. tostring(shipId))
end

-- Send ship to resupply
function Mods.GalaxyTrader.PilotControl.sendToResupply(shipId)
    debugLog("Sending ship to resupply: " .. tostring(shipId))
    
    -- Send signal to MD
    local param = "resupply|" .. tostring(shipId)
    AddUITriggeredEvent("GT_PilotControl", "Action", param)
    
    debugLog("Resupply signal sent for ship: " .. tostring(shipId))
end

-- Stop all orders for ship
function Mods.GalaxyTrader.PilotControl.stopAllOrders(shipId)
    debugLog("Stopping all orders for ship: " .. tostring(shipId))
    
    -- Send signal to MD
    local param = "stoporders|" .. tostring(shipId)
    AddUITriggeredEvent("GT_PilotControl", "Action", param)
    
    debugLog("Stop orders signal sent for ship: " .. tostring(shipId))
end

-- ==============================================================================
-- CONFIRMATION HANDLERS (MD Lua)
-- ==============================================================================

-- Handle action confirmation from MD
local function onActionConfirmation(_, param)
    debugLog("Action confirmation received: " .. tostring(param))
    
    -- Parse confirmation message
    -- Format: "action|shipId|status|message"
    local parts = {}
    for part in string.gmatch(param .. "|", "(.-)|") do
        if part ~= "" then
            table.insert(parts, part)
        end
    end
    
    if #parts >= 4 then
        local action = parts[1]
        local shipId = parts[2]
        local status = parts[3]
        local message = parts[4]
        
        debugLog(string.format("Action '%s' for ship '%s': %s - %s", action, shipId, status, message))
        
        -- TODO: Show in-game notification to user
        -- TODO: Refresh pilot overview UI if needed
        
        -- Trigger UI refresh if info menu is open
        if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.InfoMenu and Mods.GalaxyTrader.InfoMenu.onDataUpdate then
            debugLog("Triggering UI refresh after action confirmation")
            Mods.GalaxyTrader.InfoMenu.onDataUpdate()
        end
    else
        debugLog("WARNING: Invalid action confirmation format - expected 4 parts, got " .. #parts)
    end
end

-- ==============================================================================
-- INITIALIZATION
-- ==============================================================================

local function init()
    debugLog("Initializing GalaxyTrader Pilot Control Bridge")
    
    -- Register event listener for action confirmations from MD
    RegisterEvent("GT_PilotControl.Confirmation", onActionConfirmation)
    
    debugLog("Pilot Control Bridge initialized - listening for action confirmations")
end

init()

--[[
==============================================================================
GalaxyTrader MK3 - Pilot Data Bridge
==============================================================================
Bridges MD pilot/ship data with Lua UI for the Info Menu

Features:
- Receives pilot data from MD via events
- Stores data in Lua-accessible format
- Provides data to gt_info_menu.lua for display

Dependencies: 
- sn_mod_support_apis (Lua Loader API)

Author: GalaxyTrader Development Team
Version: 1.0
==============================================================================
]]--

local ffi = require("ffi")
local C = ffi.C

-- =============================================================================
-- FFI DEFINITIONS
-- =============================================================================

ffi.cdef[[
    const char* GetComponentName(uint64_t componentid);
    uint64_t ConvertStringTo64Bit(const char* idcode);
    const char* ConvertIDToString(uint64_t componentid);
]]

-- =============================================================================
-- MODULE STATE
-- =============================================================================

local GT_PilotData = {
    -- Configuration
    CONFIG = {
        DEBUG_MODE = false,  -- Set to true to enable debug logging
    },
    
    -- Global settings (received from MD)
    settings = {
        autoTraining = true,    -- Default: automatic training enabled
        autoRepair = true,      -- Default: automatic repair enabled
        autoResupply = true,    -- Default: automatic resupply enabled
        pilotRenamingEnabled = false, -- Default: pilot rename tags disabled until synced from MD
    },
    
    -- Pilot data storage (received from MD)
    pilots = {},  -- Array of pilot info tables
    gtNameIndex = {},  -- Set of normalized GT pilot names (includes paused pilots)
    gtNameMap = {},  -- normalized base name -> tagged display name
    gtPilotIdMap = {},  -- pilot idcode -> tagged display name
    lastUpdate = 0,
    initialized = false,
}

-- =============================================================================
-- DEBUG LOGGING
-- =============================================================================

local function debugLog(message)
    if GT_PilotData.CONFIG.DEBUG_MODE then
        DebugError("[GT Pilot Bridge] " .. tostring(message))
    end
end

-- =============================================================================
-- HELPER FUNCTIONS
-- =============================================================================

-- Format money - delegate to GT_UI library (single source of truth)
local function formatMoney(amount)
    if GT_UI and GT_UI.formatMoney then
        return GT_UI.formatMoney(amount)
    end
    -- Fallback if library not loaded (shouldn't happen)
    local credits = amount / 100
    if credits >= 1000000000 then
        return string.format("%.1fB Cr", credits / 1000000000)
    elseif credits >= 1000000 then
        return string.format("%.1fM Cr", credits / 1000000)
    else
        return ConvertMoneyString(amount, false, false, 0, true)
    end
end

local function normalizePilotName(name)
    if not name then
        return ""
    end

    local normalized = tostring(name)
    -- Strip GT training prefix for matching against vanilla UI names.
    normalized = normalized:gsub("^%(T:%d+%)%s*", "")
    -- Trim whitespace.
    normalized = normalized:gsub("^%s+", ""):gsub("%s+$", "")
    normalized = string.lower(normalized)
    return normalized
end

local function normalizeUniquePilotKey(key)
    if key == nil then
        return ""
    end
    local s = tostring(key)
    s = s:gsub("^%s+", ""):gsub("%s+$", "")
    -- NPC seed strings can appear as "123...ULL" in Lua; normalize to bare digits.
    s = s:gsub("[Uu][Ll][Ll]$", "")
    s = s:gsub("[Ll][Ll]$", "")
    s = s:gsub("[Uu][Ll]$", "")
    s = s:gsub("[Uu]$", "")
    return s
end

-- MD may stringify hi/lo as signed 32-bit negatives; fold to unsigned before uint64 combine.
local function uint32FromWire(s)
    local n = tonumber(s)
    if n == nil then
        return nil
    end
    n = math.floor(n)
    n = n % 4294967296
    if n < 0 then
        n = n + 4294967296
    end
    return n
end

-- Reconstruct exact NPC seed decimal string from MD u64p:hi32:lo32 wire (avoids FP rounding for seeds > 2^53).
local function u64DecimalStringFromHiLo(hiStr, loStr)
    local hiU = uint32FromWire(hiStr)
    local loU = uint32FromWire(loStr)
    if hiU == nil or loU == nil then
        return nil
    end
    local mult = ffi.new("uint64_t", 4294967296)
    local u = ffi.new("uint64_t", hiU) * mult + ffi.new("uint64_t", loU)
    return tostring(u)
end

-- Prefer engine uint64 (cdata); tostring(NPCSeed) alone can disagree with map keys for some builds.
local function npcSeedToCanonicalDecimalString(person)
    if person == nil then
        return nil
    end
    local ok, u = pcall(function()
        return ffi.cast("uint64_t", person)
    end)
    if ok and u ~= nil then
        return normalizeUniquePilotKey(tostring(u))
    end
    local s = normalizeUniquePilotKey(tostring(person))
    if not s or s == "" then
        return nil
    end
    if not s:match("^%-?%d+$") then
        return nil
    end
    local ok2, dec = pcall(function()
        if s:sub(1, 1) == "-" then
            return tostring(ffi.cast("uint64_t", ffi.new("int64_t", s)))
        end
        return tostring(ffi.new("uint64_t", s))
    end)
    if ok2 then
        return normalizeUniquePilotKey(dec)
    end
    return nil
end

-- All string keys we store for one logical id (matches MapMenu / MD wire).
local function collectPilotIdAliasKeys(keyRaw)
    local out = {}
    local seen = {}
    local function add(k)
        if k and k ~= "" and not seen[k] then
            seen[k] = true
            table.insert(out, k)
        end
    end
    if not keyRaw or keyRaw == "" then
        return out
    end
    add(keyRaw)
    local nk = normalizeUniquePilotKey(keyRaw)
    if nk ~= "" and nk ~= keyRaw then
        add(nk)
    end
    local body = nk:match("^s:(.+)$") or nk
    if not body:match("^%-?%d+$") then
        return out
    end

    local ok, u64, i64 = pcall(function()
        if body:sub(1, 1) == "-" then
            local i = ffi.new("int64_t", body)
            local u = ffi.cast("uint64_t", i)
            return u, i
        else
            local u = ffi.new("uint64_t", body)
            local i = ffi.cast("int64_t", u)
            return u, i
        end
    end)
    if not ok or not u64 or not i64 then
        return out
    end

    local u64s = tostring(u64)
    local i64s = tostring(i64)
    local u64n = normalizeUniquePilotKey(u64s)
    local i64n = normalizeUniquePilotKey(i64s)

    add(u64s)
    add(i64s)
    add(u64n)
    add(i64n)
    add("s:" .. u64s)
    add("s:" .. i64s)
    add("s:" .. u64n)
    add("s:" .. i64n)
    return out
end

-- MapMenu crew rows use tostring(NPCSeed) as unsigned decimal; MD may send the same 64-bit value
-- as signed (s:-â€¦) or with s: prefix. Register all equivalent string keys so strict lookup succeeds.
local function addPilotIdMapKeyWithInt64Aliases(idMap, taggedName, keyRaw)
    if not keyRaw or keyRaw == "" or not taggedName or taggedName == "" then
        return 0
    end
    local added = 0
    for _, k in ipairs(collectPilotIdAliasKeys(keyRaw)) do
        if idMap[k] == nil then
            added = added + 1
        end
        idMap[k] = taggedName
    end
    return added
end

-- =============================================================================
-- DATA RECEPTION FROM MD
-- =============================================================================

-- Receive pilot data from MD
-- Expected format: "CONFIG:autoTraining|autoRepair|autoResupply||shipId|pilotName|...|tradeCount||..."
-- Config flags separated by "|", pilots separated by "||"
local function onReceivePilotData(_, param)
    debugLog("Received pilot data from MD")
    
    if not param or param == "" then
        debugLog("No pilot data received (empty)")
        GT_PilotData.pilots = {}
        return
    end
    
    -- Parse the data string
    local pilots = {}
    local pilotStrings = {}
    
    -- Split by pilot separator "||" (double pipe)
    -- Use pattern that captures everything up to double-pipe or end of string
    for pilotStr in string.gmatch(param .. "||", "(.-)||") do
        if pilotStr ~= "" then
            table.insert(pilotStrings, pilotStr)
        end
    end
    
    debugLog(string.format("Parsing %d records (including config)", #pilotStrings))
    
    -- Check if first record is config data
    local startIndex = 1
    if #pilotStrings > 0 and string.sub(pilotStrings[1], 1, 7) == "CONFIG:" then
        local configStr = string.sub(pilotStrings[1], 8)  -- Remove "CONFIG:" prefix
        local configFields = {}
        for field in string.gmatch(configStr, "[^|]+") do
            table.insert(configFields, field)
        end
        
        if #configFields >= 3 then
            GT_PilotData.settings.autoTraining = (tonumber(configFields[1]) or 1) ~= 0
            GT_PilotData.settings.autoRepair = (tonumber(configFields[2]) or 1) ~= 0
            GT_PilotData.settings.autoResupply = (tonumber(configFields[3]) or 1) ~= 0
            GT_PilotData.settings.pilotRenamingEnabled = (tonumber(configFields[4]) or 0) ~= 0
            
            debugLog(string.format("Config flags: AutoTraining=%s, AutoRepair=%s, AutoResupply=%s, PilotRenamingEnabled=%s",
                tostring(GT_PilotData.settings.autoTraining),
                tostring(GT_PilotData.settings.autoRepair),
                tostring(GT_PilotData.settings.autoResupply),
                tostring(GT_PilotData.settings.pilotRenamingEnabled)))
        end
        
        startIndex = 2  -- Skip config record, start parsing pilots from index 2
    end
    
    debugLog(string.format("Parsing %d pilot records", #pilotStrings - startIndex + 1))
    
    for i = startIndex, #pilotStrings do
        local pilotStr = pilotStrings[i]
        
        -- Split pilot data by pipe (handling empty fields correctly)
        -- Pattern [^|]+ skips empty fields, causing field misalignment
        -- Use manual splitting to preserve empty fields
        local fields = {}
        local startPos = 1
        while startPos <= #pilotStr do
            local endPos = string.find(pilotStr, "|", startPos)
            if endPos == nil then
                -- Last field (no trailing pipe)
                table.insert(fields, string.sub(pilotStr, startPos))
                break
            else
                -- Field ends at pipe (includes empty fields)
                table.insert(fields, string.sub(pilotStr, startPos, endPos - 1))
                startPos = endPos + 1
            end
        end
        
        if #fields >= 13 then
            local pilotInfo = {
                shipId = fields[1] or "???",
                pilotName = fields[2] or "Unknown",
                shipType = fields[3] or "Unknown Ship",
                status = fields[4] or "[ADVANCE]",  -- Already formatted by MD
                rank = fields[5] or "Apprentice",
                rankIndex = tonumber(fields[6]) or 1,
                level = tonumber(fields[7]) or 1,
                xp = tonumber(fields[8]) or 0,
                xpNext = tonumber(fields[9]) or 1000,
                pilotProfit = tonumber(fields[10]) or 0,  -- Pilot's lifetime profit (follows pilot)
                shipProfit = tonumber(fields[11]) or 0,   -- Ship's profit (current ship)
                location = fields[12] or "Unknown",
                tradeCount = tonumber(fields[13]) or 0,
                blockedLevel = tonumber(fields[14]) or 0,
            }
            pilotInfo.trainingBlocked = pilotInfo.blockedLevel > 1
            
            -- Format XP for display
            pilotInfo.xpFormatted = string.format("%s / %s",
                ConvertIntegerString(pilotInfo.xp, true, 0, true),
                ConvertIntegerString(pilotInfo.xpNext, true, 0, true))
            
            -- Format both profit values for display
            pilotInfo.pilotProfitFormatted = formatMoney(pilotInfo.pilotProfit)
            pilotInfo.shipProfitFormatted = formatMoney(pilotInfo.shipProfit)
            
            table.insert(pilots, pilotInfo)
            
            debugLog(string.format("  Pilot %d: %s (%s) - Level %d, Pilot: %s Cr, Ship: %s Cr", 
                i, pilotInfo.pilotName, pilotInfo.shipType, pilotInfo.level, 
                pilotInfo.pilotProfitFormatted, pilotInfo.shipProfitFormatted))
        else
            debugLog(string.format("  WARNING: Pilot %d has incomplete data (%d fields)", i, #fields))
        end
    end
    
    GT_PilotData.pilots = pilots
    GT_PilotData.lastUpdate = getElapsedTime()
    GT_PilotData.initialized = true
    
    debugLog(string.format("Stored %d pilots in Lua", #pilots))
    
    -- Trigger UI refresh if menu is open
    if Mods and Mods.GalaxyTrader and Mods.GalaxyTrader.InfoMenu and Mods.GalaxyTrader.InfoMenu.onDataUpdate then
        Mods.GalaxyTrader.InfoMenu.onDataUpdate()
    end
end

-- Receive GT name index from MD
-- Expected format: "Name1||Name2||Name3"
local function onReceivePilotNameIndex(_, param)
    local index = {}
    local entryCount = 0

    if param and param ~= "" then
        for nameStr in string.gmatch(param .. "||", "(.-)||") do
            if nameStr ~= "" then
                local normalized = normalizePilotName(nameStr)
                if normalized ~= "" then
                    if not index[normalized] then
                        entryCount = entryCount + 1
                    end
                    index[normalized] = true
                end
            end
        end
    end

    GT_PilotData.gtNameIndex = index
    debugLog(string.format("Updated GT name index with %d entries", entryCount))
end

-- Receive GT name -> tagged-name map from MD
-- Expected format: "Base Name|Tagged Name||Base2|Tagged2"
local function onReceivePilotNameMap(_, param)
    local nameMap = {}
    local entryCount = 0

    if param and param ~= "" then
        for mapStr in string.gmatch(param .. "||", "(.-)||") do
            if mapStr ~= "" then
                local baseName, taggedName = string.match(mapStr, "^(.-)|(.*)$")
                if baseName and taggedName and baseName ~= "" and taggedName ~= "" then
                    local normalized = normalizePilotName(baseName)
                    if normalized ~= "" then
                        if not nameMap[normalized] then
                            entryCount = entryCount + 1
                        end
                        nameMap[normalized] = taggedName
                    end
                end
            end
        end
    end

    GT_PilotData.gtNameMap = nameMap
    debugLog(string.format("Updated GT name map with %d entries", entryCount))
end

-- Receive GT pilot-id -> tagged-name map from MD
-- Expected format: "PILOTID1|Tagged Name1||PILOTID2|Tagged Name2"
-- Merges into the existing Lua map: MD snapshots can be partial after vanilla crew
-- swaps / reassignment; a full replace dropped seeds still shown in MapMenu crew rows.
local function onReceivePilotIdMap(_, param)
    local prev = GT_PilotData.gtPilotIdMap or {}
    local prevKeyCount = 0
    for _ in pairs(prev) do
        prevKeyCount = prevKeyCount + 1
    end

    local idMap = {}
    for k, v in pairs(prev) do
        idMap[k] = v
    end

    local entryCount = 0
    local malformedCount = 0
    local u64WireCount = 0
    local u64DecodedCount = 0
    local u64DecodeFailed = 0
    local aliasKeyAdds = 0
    local sampleKeys = {}

    if param and param ~= "" then
        for mapStr in string.gmatch(param .. "||", "(.-)||") do
            if mapStr ~= "" then
                local pilotId, taggedName = string.match(mapStr, "^(.-)|(.*)$")
                if pilotId and taggedName and pilotId ~= "" and taggedName ~= "" then
                    entryCount = entryCount + 1
                    if #sampleKeys < 5 then
                        table.insert(sampleKeys, tostring(pilotId))
                    end
                    -- MD wire may send signed 32-bit halves (e.g. negative hi/lo); accept both signs.
                    local hi32, lo32 = string.match(pilotId, "^u64p:(%-?%d+):(%-?%d+)$")
                    local keyForAliases = pilotId
                    if hi32 and lo32 then
                        u64WireCount = u64WireCount + 1
                        local dec = u64DecimalStringFromHiLo(hi32, lo32)
                        if dec then
                            u64DecodedCount = u64DecodedCount + 1
                            keyForAliases = dec
                        else
                            u64DecodeFailed = u64DecodeFailed + 1
                        end
                    end
                    idMap[pilotId] = taggedName -- keep raw wire key for diagnostics
                    aliasKeyAdds = aliasKeyAdds + addPilotIdMapKeyWithInt64Aliases(idMap, taggedName, keyForAliases)
                else
                    malformedCount = malformedCount + 1
                end
            end
        end
    end

    local totalKeys = 0
    for _ in pairs(idMap) do
        totalKeys = totalKeys + 1
    end

    -- Never replace a good map with an empty snapshot: MD can raise this during
    -- SendPilotData "early" branch or transient registry races (crew UI refresh).
    if entryCount == 0 then
        if prevKeyCount > 0 then
            DebugError(string.format(
                "[GT Pilot Bridge] PilotIdMap skipped empty update (keeping %d keys; raw_len=%d)",
                prevKeyCount,
                string.len(tostring(param or ""))
            ))
        end
        return
    end

    GT_PilotData.gtPilotIdMap = idMap
    DebugError(string.format(
        "[GT Pilot Bridge] PilotIdMap merged: incomingLogical=%d totalKeys=%d prevKeys=%d malformed=%d wireU64=%d decodedU64=%d decodeFail=%d aliasAdds=%d raw_len=%d sampleKeys=[%s]",
        entryCount,
        totalKeys,
        prevKeyCount,
        malformedCount,
        u64WireCount,
        u64DecodedCount,
        u64DecodeFailed,
        aliasKeyAdds,
        string.len(tostring(param or "")),
        table.concat(sampleKeys, ", ")
    ))
    debugLog(string.format("Updated GT pilot id map: %d logical entries, %d lookup keys (malformed=%d, wire=%d, decoded=%d, decodeFail=%d, aliasAdds=%d)", entryCount, totalKeys, malformedCount, u64WireCount, u64DecodedCount, u64DecodeFailed, aliasKeyAdds))
    if malformedCount > 0 then
        DebugError(string.format("[GT Pilot Bridge] WARNING: Received malformed PilotIdMap entries: %d", malformedCount))
    end
    if u64DecodeFailed > 0 then
        DebugError(string.format("[GT Pilot Bridge] WARNING: u64p decode failed for %d entries (wire=%d decoded=%d)", u64DecodeFailed, u64WireCount, u64DecodedCount))
    end
end

-- =============================================================================
-- PUBLIC API (for gt_info_menu.lua)
-- =============================================================================

-- Crew highlight: resolve tagged name using same alias keys as PilotIdMap (NPCSeed cdata-safe).
function GT_PilotData.lookupPilotIdMapTaggedName(idMap, person)
    if not idMap then
        return nil, nil
    end

    local function tryKey(k)
        if not k or k == "" then
            return nil, nil
        end
        local v = idMap[k]
        if v and v ~= "" then
            return v, k
        end
        local nk = normalizeUniquePilotKey(tostring(k))
        if nk and nk ~= "" and nk ~= tostring(k) then
            v = idMap[nk]
            if v and v ~= "" then
                return v, nk
            end
        end
        return nil, nil
    end

    -- Fast path: exact decimal and s:<signed int64> (must match MD StableIdentity / MapMenu).
    local dec = npcSeedToCanonicalDecimalString(person)
    if dec then
        local v, kk = tryKey(dec)
        if v then
            return v, kk
        end
        local decNorm = normalizeUniquePilotKey(dec)
        if decNorm and decNorm ~= "" and decNorm ~= dec then
            v, kk = tryKey(decNorm)
            if v then
                return v, kk
            end
        end
        local ok, u = pcall(function()
            return ffi.new("uint64_t", decNorm or dec)
        end)
        if ok and u then
            local i64 = ffi.cast("int64_t", u)
            v, kk = tryKey("s:" .. normalizeUniquePilotKey(tostring(i64)))
            if v then
                return v, kk
            end
            v, kk = tryKey(normalizeUniquePilotKey(tostring(u)))
            if v then
                return v, kk
            end
        end
    end

    local seen = {}
    local function probe(keyRaw)
        for _, k in ipairs(collectPilotIdAliasKeys(keyRaw)) do
            if not seen[k] then
                seen[k] = true
                local v, kk = tryKey(k)
                if v then
                    return v, kk
                end
            end
        end
        return nil, nil
    end

    local v, k = probe(dec)
    if v then
        return v, k
    end
    v, k = probe(normalizeUniquePilotKey(tostring(person)))
    if v then
        return v, k
    end
    return probe(tostring(person))
end

-- One-shot diagnostic when a crew row does not match any GT pilot id (expected for non-GT NPCs).
function GT_PilotData.diagnosePilotIdMapMiss(idMap, person, label)
    local canon = npcSeedToCanonicalDecimalString(person)
    local samples = {}
    local n = 0
    for key, val in pairs(idMap or {}) do
        if n < 10 then
            n = n + 1
            local vs = tostring(val)
            if string.len(vs) > 48 then
                vs = string.sub(vs, 1, 45) .. "..."
            end
            table.insert(samples, tostring(key) .. "=>" .. vs)
        end
    end
    DebugError(string.format(
        "[GT Pilot Bridge] lookup miss %s type=%s tostring=%s canonicalFFI=%s sampleKeys=[%s]",
        tostring(label or ""),
        type(person),
        tostring(person),
        tostring(canon),
        table.concat(samples, " | ")
    ))
end

function GT_PilotData.getPilots()
    -- Return a COPY of the pilots array to prevent external sorting from modifying our stored data
    local pilots = GT_PilotData.pilots or {}
    local copy = {}
    for i = 1, #pilots do
        copy[i] = pilots[i]
    end
    return copy
end

function GT_PilotData.getLastUpdate()
    return GT_PilotData.lastUpdate
end

function GT_PilotData.isInitialized()
    return GT_PilotData.initialized
end

function GT_PilotData.requestRefresh()
    debugLog("Refresh requested - sending event to MD")
    AddUITriggeredEvent("gt_pilot_data_bridge", "RequestPilotData", 1)
end

function GT_PilotData.getGTNameIndex()
    return GT_PilotData.gtNameIndex or {}
end

function GT_PilotData.getGTNameMap()
    return GT_PilotData.gtNameMap or {}
end

function GT_PilotData.getGTPilotIdMap()
    return GT_PilotData.gtPilotIdMap or {}
end

-- =============================================================================
-- INITIALIZATION
-- =============================================================================

local function init()
    debugLog("Initializing GT Pilot Data Bridge")
    
    -- Register event listener for pilot data from MD
    RegisterEvent("GT_PilotData.Update", onReceivePilotData)
    RegisterEvent("GT_PilotNameIndex.Update", onReceivePilotNameIndex)
    RegisterEvent("GT_PilotNameMap.Update", onReceivePilotNameMap)
    RegisterEvent("GT_PilotIdMap.Update", onReceivePilotIdMap)
    
    debugLog("GT Pilot Data Bridge initialized - waiting for data from MD")
    -- Prime data once so MapMenu hooks have index data immediately.
    GT_PilotData.requestRefresh()
end

-- =============================================================================
-- MODULE EXPORT
-- =============================================================================

-- Export to global scope so gt_info_menu.lua can access it
if not Mods then Mods = {} end
if not Mods.GalaxyTrader then Mods.GalaxyTrader = {} end
Mods.GalaxyTrader.PilotData = GT_PilotData

-- Initialize on load
init()

return GT_PilotData

-- GalaxyTrader â€” Station Subordinate Order Access (UI Unlock)
--
-- Problem: When a ship is assigned as a station subordinate, vanilla menu_map.lua
-- makes all order parameters read-only by checking `infoTableData[instance].commander`.
-- This prevents the player from editing GT order settings on station-assigned ships.
--
-- Solution: Hook displayOrderParam and displayDefaultBehaviour in MapMenu.
-- For GT orders only, temporarily set commander = nil during rendering so vanilla
-- treats the params as editable, then immediately restore the original value.
--
-- Scope: Only unlocks editing for GT orders (GalaxyTraderMK1, MK2, MK3, GalaxyMiner).
-- All other orders (vanilla, other mods) remain read-only when station-assigned.

-- GT order IDs that should have order access when station-assigned
local GT_OrderIDs = {
    ["GalaxyTraderMK1"] = true,
    ["GalaxyTraderMK2"] = true,
    ["GalaxyTraderMK3"] = true,
    ["GalaxyTraderMK4Supply"] = true,
    ["GalaxyTraderMK4Supply2"] = true,
    ["GalaxyMiner"] = true,
}

-- Find MapMenu
local menu = Helper.getMenu("MapMenu")
if not menu then
    DebugError("[GT Subordinate Access] MapMenu not found â€” subordinate order access will not be available")
    return
end

-- Store original functions
local orig_displayOrderParam = menu.displayOrderParam
local orig_displayDefaultBehaviour = menu.displayDefaultBehaviour

-- Helper: check if an order ID is a GT order
local function isGTOrder(orderID)
    return orderID ~= nil and GT_OrderIDs[orderID] == true
end

-- Hook: displayOrderParam
-- Vanilla check (menu_map.lua ~line 9764):
--   paramactive = (menu.infoTableData[instance].commander == nil) and (not isplayeroccupiedship)
-- By temporarily nulling commander for GT orders, we make paramactive = true.
--
-- NOTE: The order table uses .orderdef (string ID), NOT .id.
-- Structure: { state, statename, orderdef="GalaxyTraderMK3", actualparams, enabled, orderdefref }
function menu.displayOrderParam(ftable, orderidx, order, paramidx, param, listidx, instance)
    local commander = nil
    local didOverride = false

    -- Only unlock for GT orders (order.orderdef holds the order ID string)
    if order and isGTOrder(order.orderdef) then
        commander = menu.infoTableData[instance].commander
        menu.infoTableData[instance].commander = nil
        didOverride = true
    end

    -- Call original (vanilla renders params as editable since commander is nil)
    orig_displayOrderParam(ftable, orderidx, order, paramidx, param, listidx, instance)

    -- Always restore commander
    if didOverride then
        menu.infoTableData[instance].commander = commander
    end
end

-- Hook: displayDefaultBehaviour
-- Vanilla check (menu_map.lua ~line 11786):
--   behaviouractive = (infoTableData.commander == nil) and isvalid and (not isplayeroccupiedship) and haspilot
-- Same approach: null commander for GT default orders.
--
-- NOTE: The defaultorder table uses .orderdef (string ID), NOT .id.
function menu.displayDefaultBehaviour(ftable, mode, titlerow, instance)
    local commander = nil
    local didOverride = false

    -- Check if the default order is a GT order
    local infoTableData = menu.infoTableData[instance]
    if infoTableData then
        local defaultorder = infoTableData.defaultorder
        if defaultorder and isGTOrder(defaultorder.orderdef) then
            commander = infoTableData.commander
            infoTableData.commander = nil
            didOverride = true
        end
    end

    -- Call original (vanilla renders default behaviour selector as active)
    orig_displayDefaultBehaviour(ftable, mode, titlerow, instance)

    -- Always restore commander
    if didOverride then
        menu.infoTableData[instance].commander = commander
    end
end

DebugError("[GT Subordinate Access] MapMenu hooks installed â€” GT orders editable when station-assigned")
--[[
==============================================================================
GalaxyTrader MK3 - UI Element Library
==============================================================================
Reusable UI components for consistent styling and behavior across all GT UI.
All patterns are validated against working GT UI code (info menu, context
menus, diagnose report).

IMPORTANT: This file MUST be loaded BEFORE any UI file that uses GT_UI.
           Ensure it appears first in ui.xml.

Usage (files loaded via ui.xml share _G):
    GT_UI.createScrollTable(frame, 3, { ... })
    GT_UI.addHeaderRow(tbl, {"Col1", "Col2", "Col3"})
    GT_UI.formatMoney(150000)


==============================================================================
]]--

local GT_UI = {}

-- =============================================================================
-- CONSTANTS
-- =============================================================================

GT_UI.DEFAULTS = {
    rowHeight       = Helper.standardTextHeight,
    fontSize        = Helper.standardFontSize,
    maxRowsPerPage  = 38,   -- max rows before pagination kicks in
                            -- X4 computes full table min-height even with maxVisibleHeight;
                            -- at ~26px/row + ~130px fixed rows, 38 rows â‰ˆ 1118px which fits
                            -- the ~1192px available in the diagnose frame at 1440p.
}

-- =============================================================================
-- COLORS  (validated against X4 7.x color table)
-- =============================================================================

GT_UI.COLORS = {
    headerBg        = Color["row_title_background"],
    selectedBg      = Color["row_background_selected"],
    buttonBg        = Color["button_background_default"],
    tabActiveBg     = Color["row_background_selected"],
    tabInactiveBg   = Color["row_background_blue"],
    textPositive    = Color["text_positive"],
    textNegative    = Color["text_negative"],
    textWarning     = Color["text_warning"],
    frameBg         = Color["frame_background_semitransparent"],
}

-- =============================================================================
-- STATUS HELPERS
-- =============================================================================

--- Returns the appropriate color for a status string.
--- @param status string  "PASS", "FAIL", "WARN", or anything else (nil = default)
function GT_UI.getStatusColor(status)
    if status == "PASS" then
        return GT_UI.COLORS.textPositive
    elseif status == "FAIL" then
        return GT_UI.COLORS.textNegative
    elseif status == "WARN" then
        return GT_UI.COLORS.textWarning
    end
    return nil  -- default text color
end

-- =============================================================================
-- FORMATTING
-- =============================================================================

--- Format money amount (in cents/centimes) with M/B suffixes.
--- Single source of truth -- do NOT duplicate this in other files.
--- @param amount number  Amount in cents (X4 internal format)
--- @return string  e.g. "1.5M Cr", "2.3B Cr", "42,000 Cr"
function GT_UI.formatMoney(amount)
    local credits = amount / 100
    if credits >= 1000000000 then
        return string.format("%.1fB Cr", credits / 1000000000)
    elseif credits >= 1000000 then
        return string.format("%.1fM Cr", credits / 1000000)
    else
        return ConvertMoneyString(amount, false, false, 0, true)
    end
end

--- Format an EXACT credit amount with thousand separators and "Cr" suffix.
--- No M/B compression -- use when the precise number matters (course costs,
--- transaction receipts, fee breakdowns, ...).
---
--- IMPORTANT - input units: this helper expects WHOLE CREDITS, NOT raw
--- centicredits. GetNPCBlackboard auto-converts money-typed fields from
--- centicredits to credits when reading back from player.entity (verified:
--- MD `player.money` of 427720000 returns 4277200 from the blackboard), so
--- values pulled directly off the blackboard can be passed to this helper
--- as-is. If you instead hold a raw centicredit value (e.g. from `player.money`
--- before any blackboard round-trip), divide by 100 first.
---
--- The thousand separator is implemented in pure Lua to avoid the unit
--- ambiguity in stock `ConvertMoneyString` (which silently divides by 100).
---
--- @param credits number  Whole-credit amount
--- @return string  e.g. "1,500,000 Cr"
function GT_UI.formatCreditsExact(credits)
    local n = math.floor((credits or 0) + 0.5)
    local s = tostring(n)
    local formatted, k = s, 0
    while true do
        formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", "%1,%2")
        if k == 0 then break end
    end
    return formatted .. " Cr"
end

--- Format a duration in seconds as "N min" (rounded, minimum 1).
--- @param seconds number
--- @return string  e.g. "10 min"
function GT_UI.formatDurationMin(seconds)
    local minutes = math.floor((seconds or 0) / 60 + 0.5)
    if minutes < 1 then minutes = 1 end
    return tostring(minutes) .. " min"
end

-- =============================================================================
-- LOCALIZATION
-- =============================================================================

--- Read a localized string with pcall protection. Returns the supplied fallback
--- (or a "{page,id}" placeholder) if ReadText errors or returns empty.
--- @param page number      Text page id
--- @param id   number      Text entry id
--- @param fallback string?  Optional fallback text
--- @return string
function GT_UI.safeReadText(page, id, fallback)
    if not page or not id then
        return fallback or "?"
    end
    local ok, txt = pcall(ReadText, page, id)
    if ok and txt and txt ~= "" then
        return txt
    end
    return fallback or string.format("{%d,%d}", page, id)
end

-- =============================================================================
-- STRING HELPERS
-- =============================================================================

--- Split a string by a delimiter (supports multi-char delimiters).
--- @param str string       Input string
--- @param delimiter string Delimiter (e.g. "||", ";;", ",")
--- @return table           Array of substrings
function GT_UI.split(str, delimiter)
    local result = {}
    if not str or str == "" then return result end

    if #delimiter > 1 then
        -- Multi-char delimiter: find-based
        local start = 1
        while true do
            local pos = string.find(str, delimiter, start, true)
            if pos then
                table.insert(result, string.sub(str, start, pos - 1))
                start = pos + #delimiter
            else
                table.insert(result, string.sub(str, start))
                break
            end
        end
    else
        -- Single-char delimiter
        local pattern = "([^" .. delimiter .. "]*)" .. delimiter .. "?"
        for match in string.gmatch(str .. delimiter, pattern) do
            table.insert(result, match)
        end
        -- Remove trailing empty entry
        if #result > 0 and result[#result] == "" then
            table.remove(result)
        end
    end
    return result
end

-- =============================================================================
-- TABLE CREATION
-- =============================================================================

--[[
    Creates a scrollable table with sane defaults.

    Uses reserveScrollBar = false and percentage-based column widths, which
    is the pattern used by ALL working GT UIs.  If you need reserveScrollBar
    = true, use fixed pixel widths via setColWidth() and leave at least one
    column un-set so it becomes the variable-width column.

    Parameters:
        frame       : Parent frame
        columnCount : Number of columns
        options     : {
            tabOrder          = number   (default 2)
            x                 = number   (default Helper.borderSize)
            y                 = number   (default 0)
            width             = number   (default frame usable width)
            maxVisibleHeight  = number   (default Helper.viewHeight)
            reserveScrollBar  = bool     (default false)
            highlightMode     = string   (default nil = normal)
            fontSize          = number   (default GT_UI.DEFAULTS.fontSize)
            rowHeight         = number   (default GT_UI.DEFAULTS.rowHeight)
        }

    Returns: table object
]]
function GT_UI.createScrollTable(frame, columnCount, options)
    options = options or {}

    local tbl = frame:addTable(columnCount, {
        tabOrder         = options.tabOrder or 2,
        x                = options.x or Helper.borderSize,
        y                = options.y or 0,
        width            = options.width,
        maxVisibleHeight = options.maxVisibleHeight or Helper.viewHeight,
        reserveScrollBar = (options.reserveScrollBar == true),  -- default false
        highlightMode    = options.highlightMode,
    })

    tbl:setDefaultCellProperties("text", {
        minRowHeight = options.rowHeight or GT_UI.DEFAULTS.rowHeight,
        fontsize     = options.fontSize or GT_UI.DEFAULTS.fontSize,
    })

    return tbl
end

--[[
    Add a lightweight floating text label to a frame.
    Designed for non-interactive overlays that must not participate in tab flow.

    Parameters:
        frame   : parent frame
        options : {
            x          = number (required)
            y          = number (required)
            width      = number (required)
            height     = number (required)
            text       = string OR function() -> string
            halign     = string (default "left")
            fontsize   = number (default GT_UI.DEFAULTS.fontSize)
            color      = color (optional)
            tabOrder   = number (default 0)
        }

    Returns: table object
]]
function GT_UI.addFloatingLabel(frame, options)
    options = options or {}

    local rowHeight = options.height or GT_UI.DEFAULTS.rowHeight

    local tbl = frame:addTable(1, {
        tabOrder         = options.tabOrder or 0,
        x                = options.x or 0,
        y                = options.y or 0,
        width            = options.width or 300,
        height           = rowHeight,
        scaling          = false,
        highlightMode    = "off",
        reserveScrollBar = false,
        skipTabChange    = true,
    })

    tbl:setDefaultCellProperties("text", {
        minRowHeight = rowHeight,
        fontsize     = options.fontsize or GT_UI.DEFAULTS.fontSize,
    })

    local labelText = options.text or ""
    if type(labelText) == "function" then
        labelText = labelText() or ""
    end

    local row = tbl:addRow(nil, { fixed = true })
    row[1]:createText(labelText, {
        halign   = options.halign or "left",
        fontsize = options.fontsize or GT_UI.DEFAULTS.fontSize,
        color    = options.color,
        wordwrap = false,
        x        = 0,
        y        = 0,
    })

    return tbl
end

--[[
    Set column widths using percentages.
    Leave one column UN-set to act as the flexible column (required when
    reserveScrollBar = true, harmless when false).

    Parameters:
        tbl     : table object
        widths  : array of {colIndex, percent} or just array of percents
                  e.g. {22, 8} sets columns 1=22%, 2=8%, rest flexible

    Example:
        GT_UI.setColPercents(tbl, {22, 8})
        -- Column 1 = 22%, Column 2 = 8%, Column 3+ = flexible
]]
function GT_UI.setColPercents(tbl, widths)
    if not widths then return end
    for i, pct in ipairs(widths) do
        if pct and pct > 0 then
            tbl:setColWidthPercent(i, pct)
        end
    end
end

-- =============================================================================
-- HEADER / ROW / FOOTER CREATION
-- =============================================================================

--[[
    Add a fixed header row with text labels.

    Parameters:
        tbl         : table object
        headers     : array of strings or tables:
                      string -> simple centered text
                      table  -> { text=, halign=, sortColumn=, currentSort=, onSort= }
        options     : { bgColor=, font= }

    Returns: row object
]]
function GT_UI.addHeaderRow(tbl, headers, options)
    options = options or {}

    local row = tbl:addRow(true, {
        fixed   = true,
        bgColor = options.bgColor or GT_UI.COLORS.headerBg,
    })

    for i, hdr in ipairs(headers) do
        local cell = row[i]
        if not cell then break end

        if type(hdr) == "string" then
            cell:createText(hdr, {
                halign = "center",
                font   = options.font or Helper.headerRow1Font,
            })
        else
            -- Table config: sortable header
            local text    = hdr.text or ""
            local halign  = hdr.halign or "center"

            if hdr.sortColumn and hdr.onSort then
                -- Sortable: use button
                local displayText = text
                if hdr.currentSort and hdr.currentSort.column == hdr.sortColumn then
                    displayText = displayText .. (hdr.currentSort.descending and " \xe2\x96\xbc" or " \xe2\x96\xb2")
                end
                local btn = cell:createButton({ height = GT_UI.DEFAULTS.rowHeight })
                btn:setText(displayText, { halign = halign })
                local sortCol = hdr.sortColumn
                local sortFn  = hdr.onSort
                cell.handlers.onClick = function()
                    sortFn(sortCol)
                    return true
                end
            else
                cell:createText(text, {
                    halign = halign,
                    font   = options.font or Helper.headerRow1Font,
                })
            end
        end
    end

    return row
end

--[[
    Add a data row.

    Parameters:
        tbl          : table object
        cells        : array of strings or tables:
                       string -> left-aligned text
                       table  -> { text=, halign=, color=, cellBGColor=, wordwrap=,
                                   fontsize=, colSpan=, onClick= }
        options      : { selectable=bool (default true), bgColor=, interactive= }

    Returns: row object
]]
function GT_UI.addDataRow(tbl, cells, options)
    options = options or {}
    local selectable = (options.selectable ~= false)  -- default true

    local rowOpts = {}
    if options.bgColor then rowOpts.bgColor = options.bgColor end
    if options.interactive then rowOpts.interactive = true end

    local row = tbl:addRow(selectable, rowOpts)

    for i, cellCfg in ipairs(cells) do
        local cell = row[i]
        if not cell then break end

        if type(cellCfg) == "string" then
            cell:createText(cellCfg, { halign = "left" })
        else
            if cellCfg.colSpan then
                cell:setColSpan(cellCfg.colSpan)
            end

            local textOpts = {
                halign      = cellCfg.halign or "left",
                fontsize    = cellCfg.fontsize,
                color       = cellCfg.color,
                cellBGColor = cellCfg.cellBGColor,
                wordwrap    = cellCfg.wordwrap,
            }
            cell:createText(cellCfg.text or "", textOpts)

            if cellCfg.onClick then
                local fn = cellCfg.onClick
                cell.handlers.onClick = function()
                    fn()
                    return true
                end
            end
        end
    end

    return row
end

--[[
    Add an empty-state row spanning all columns.

    Parameters:
        tbl         : table object
        message     : string
        columnCount : number of columns to span (REQUIRED - X4 has no getColumnCount)
        options     : { halign=, fontsize= }

    Returns: row object
]]
function GT_UI.addEmptyRow(tbl, message, columnCount, options)
    options = options or {}

    local row = tbl:addRow(nil, {})
    row[1]:setColSpan(columnCount):createText(message, {
        halign   = options.halign or "center",
        fontsize = options.fontsize or GT_UI.DEFAULTS.fontSize,
    })
    return row
end

--[[
    Add a small caption row (centered, muted color, word-wrapped). Useful as
    an explanatory note beneath a disabled button or section header.

    Cramming "label\n(reason)" into a single fixed-height row makes the second
    line overflow into the next row visually -- always render the caption on
    its own row instead.

    Parameters:
        tbl         : table object
        message     : string  (will be rendered verbatim; caller adds parens)
        options     : { halign=, fontsize=, color=, wordwrap=, colSpan= }

    Returns: row object
]]
function GT_UI.addCaptionRow(tbl, message, options)
    options = options or {}

    local row = tbl:addRow(nil, { fixed = true })
    if options.colSpan then
        row[1]:setColSpan(options.colSpan)
    end
    row[1]:createText(message, {
        halign   = options.halign or "center",
        wordwrap = (options.wordwrap ~= false),
        color    = options.color or Color["text_inactive"],
        fontsize = options.fontsize or GT_UI.DEFAULTS.fontSize,
    })
    return row
end

--[[
    Add a footer row spanning all columns.

    Parameters:
        tbl         : table object
        message     : string
        columnCount : number of columns to span (REQUIRED - X4 has no getColumnCount)
        options     : { halign=, fontsize=, bgColor= }

    Returns: row object
]]
function GT_UI.addFooterRow(tbl, message, columnCount, options)
    options = options or {}

    local row = tbl:addRow(nil, {
        fixed   = true,
        bgColor = options.bgColor or GT_UI.COLORS.headerBg,
    })
    row[1]:setColSpan(columnCount):createText(message, {
        halign   = options.halign or "center",
        fontsize = options.fontsize or GT_UI.DEFAULTS.fontSize * 0.85,
    })
    return row
end

-- =============================================================================
-- BUTTONS
-- =============================================================================

--[[
    Create a button in a table cell.

    Parameters:
        cell    : cell object (row[n])
        text    : button label
        options : {
            active   = bool    (default true; pass false for a disabled button)
            height   = number  (default GT_UI.DEFAULTS.rowHeight)
            bgColor  = color   (default GT_UI.COLORS.buttonBg)
            fontSize = number  (default GT_UI.DEFAULTS.fontSize * 0.85)
            halign   = string  (default "center")
            color    = color   (text color, optional)
            onClick  = function (ignored when active == false)
        }

    Returns: button object
]]
function GT_UI.createButton(cell, text, options)
    options = options or {}

    local btnConfig = {
        height  = options.height or GT_UI.DEFAULTS.rowHeight,
        bgColor = options.bgColor or GT_UI.COLORS.buttonBg,
    }
    if options.active == false then
        btnConfig.active = false
    end

    local btn = cell:createButton(btnConfig)

    local textOpts = {
        halign   = options.halign or "center",
        fontsize = options.fontSize or (GT_UI.DEFAULTS.fontSize * 0.85),
    }
    if options.color then textOpts.color = options.color end
    btn:setText(text, textOpts)

    if options.onClick and options.active ~= false then
        local fn = options.onClick
        cell.handlers.onClick = function()
            fn()
            return true
        end
    end

    return btn
end

-- =============================================================================
-- TAB BAR
-- =============================================================================

--[[
    Create a tab bar row.

    Parameters:
        frame       : parent frame
        tabs        : array of { name=string, sectionIdx=number }
        activeIdx   : currently active section index
        options     : {
            x        = number
            y        = number
            width    = number
            maxTabs  = number  (default 14)
            fontSize = number  (default GT_UI.DEFAULTS.fontSize * 0.75)
            truncLen = number  (default 12, tab names longer than this get truncated)
            onClick  = function(sectionIdx)  -- called when a tab is clicked
        }

    Returns: tabTable object, tabHeight (pixels)
]]
function GT_UI.createTabBar(frame, tabs, activeIdx, options)
    options = options or {}

    local maxTabs  = math.min(#tabs, options.maxTabs or 14)
    local truncLen = options.truncLen or 12
    local fontSize = options.fontSize or (GT_UI.DEFAULTS.fontSize * 0.75)

    local tabTable = frame:addTable(maxTabs, {
        tabOrder         = 1,
        x                = options.x or Helper.borderSize,
        y                = options.y or 0,
        width            = options.width,
        highlightMode    = "off",
        reserveScrollBar = false,
    })

    -- Equal column widths
    local colPct = math.floor(100 / maxTabs)
    for i = 1, maxTabs do
        tabTable:setColWidthPercent(i, colPct)
    end

    local tabRow = tabTable:addRow(true, { fixed = true })

    for i = 1, maxTabs do
        local tab = tabs[i]
        if not tab then break end

        local label = tab.name or ("Tab " .. i)
        if #label > truncLen then
            label = string.sub(label, 1, truncLen - 2) .. ".."
        end

        local isActive = (tab.sectionIdx == activeIdx)
        local bgColor  = isActive and GT_UI.COLORS.tabActiveBg or GT_UI.COLORS.tabInactiveBg

        local btn = tabRow[i]:createButton({
            height  = GT_UI.DEFAULTS.rowHeight,
            bgColor = bgColor,
        })
        btn:setText(label, { halign = "center", fontsize = fontSize })

        if options.onClick then
            local idx = tab.sectionIdx
            local fn  = options.onClick
            tabRow[i].handlers.onClick = function()
                fn(idx)
                return true
            end
        end
    end

    local tabHeight = GT_UI.DEFAULTS.rowHeight + 8
    return tabTable, tabHeight
end

-- =============================================================================
-- PAGINATION
-- =============================================================================

--[[
    Paginate a row set: determine page bounds and whether pagination is needed.

    Parameters:
        totalRows   : number of total rows
        currentPage : current page (1-based)
        maxPerPage  : max rows per page (default GT_UI.DEFAULTS.maxRowsPerPage)

    Returns: table {
        startIdx    = first row index (1-based)
        endIdx      = last row index (1-based)
        totalRows   = total number of rows
        totalPages  = total number of pages
        currentPage = clamped current page
        isPaginated = bool (totalRows > maxPerPage)
    }
]]
function GT_UI.paginate(totalRows, currentPage, maxPerPage)
    maxPerPage = maxPerPage or GT_UI.DEFAULTS.maxRowsPerPage

    local totalPages = math.max(1, math.ceil(totalRows / maxPerPage))
    currentPage = math.max(1, math.min(currentPage, totalPages))

    local startIdx = (currentPage - 1) * maxPerPage + 1
    local endIdx   = math.min(currentPage * maxPerPage, totalRows)

    return {
        startIdx    = startIdx,
        endIdx      = endIdx,
        totalRows   = totalRows,
        totalPages  = totalPages,
        currentPage = currentPage,
        isPaginated = (totalRows > maxPerPage),
    }
end

--[[
    Add a pagination info header row (e.g. "Page 2/7 (rows 81-160 of 500)").
    Only adds the row if pagination is active.

    Parameters:
        tbl         : table object
        pageInfo    : result from GT_UI.paginate()
        columnCount : number of columns to span

    Returns: row object or nil
]]
function GT_UI.addPaginationHeader(tbl, pageInfo, columnCount)
    if not pageInfo.isPaginated then return nil end

    local row = tbl:addRow(nil, {
        fixed   = true,
        bgColor = GT_UI.COLORS.headerBg,
    })
    row[1]:setColSpan(columnCount):createText(
        string.format("Page %d / %d  (rows %d - %d of %d total)",
            pageInfo.currentPage, pageInfo.totalPages,
            pageInfo.startIdx, pageInfo.endIdx,
            pageInfo.totalRows),
        { halign = "center", fontsize = GT_UI.DEFAULTS.fontSize * 0.8 }
    )
    return row
end

--[[
    Add pagination navigation buttons (Prev / page indicator / Next).
    Only adds the row if pagination is active and there are multiple pages.

    Parameters:
        tbl         : table object (must have at least 3 columns)
        pageInfo    : result from GT_UI.paginate()
        onPageChange: function(newPage) - called when prev/next is clicked

    Returns: row object or nil
]]
function GT_UI.addPaginationNav(tbl, pageInfo, onPageChange)
    if not pageInfo.isPaginated or pageInfo.totalPages <= 1 then
        return nil
    end

    local row = tbl:addRow(true, {
        fixed   = true,
        bgColor = GT_UI.COLORS.headerBg,
    })

    -- Prev button (column 1)
    if pageInfo.currentPage > 1 then
        GT_UI.createButton(row[1], "<< Prev", {
            bgColor  = GT_UI.COLORS.tabInactiveBg,
            fontSize = GT_UI.DEFAULTS.fontSize * 0.85,
            onClick  = function()
                onPageChange(pageInfo.currentPage - 1)
            end,
        })
    else
        row[1]:createText("", {})
    end

    -- Page indicator (column 2)
    row[2]:createText(
        string.format("%d / %d", pageInfo.currentPage, pageInfo.totalPages),
        { halign = "center", fontsize = GT_UI.DEFAULTS.fontSize * 0.8 }
    )

    -- Next button (column 3)
    if pageInfo.currentPage < pageInfo.totalPages then
        GT_UI.createButton(row[3], "Next >>", {
            bgColor  = GT_UI.COLORS.tabInactiveBg,
            fontSize = GT_UI.DEFAULTS.fontSize * 0.85,
            onClick  = function()
                onPageChange(pageInfo.currentPage + 1)
            end,
        })
    else
        row[3]:createText("", {})
    end

    return row
end

-- =============================================================================
-- MODULE EXPORT
-- =============================================================================

-- Export as global for X4 ui.xml loading (files loaded via ui.xml share _G)
_G.GT_UI = GT_UI

return GT_UI
<?xml version="1.0" encoding="utf-8"?>
<content id="" name="" description="" author="GoAhead" version="01504" date="2026-07-03" save="0" lastupdate="">
  <text language="44" name="GalaxyTrader MK3" description="Advanced Trading AI with XP Progression System" author="GoAhead"/>
  <text language="49" name="GalaxyTrader MK3" description="Advanced Trading AI with XP Progression System" author="GoAhead"/>
  <text language="55" name="GalaxyTrader MK3" description="IA de ComÃ©rcio AvanÃ§ada com Sistema de ProgressÃ£o de XP" author="GoAhead"/>
  <dependency version="900" optional="false" name="X4: Foundations 9.00"/>
  <dependency id="ws_2042901274" optional="false" name="SirNukes Mod Support APIs"/>
  <dependency id="kuerteeUIExtensionsAndHUD" optional="true" name="kuertee UI Extensions and HUD"/>
  <dependency id="ego_dlc_boron" optional="true" name="Kingdom End"/>
  <dependency id="ego_dlc_split" optional="true" name="Split Vendetta"/>
  <dependency id="ego_dlc_terran" optional="true" name="Cradle of Humanity"/>
  <libraries>
    <library path="libraries/wares.xml"/>
    <library path="libraries/equipmentmods.xml"/>
  </libraries>
</content>
